repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/joshuabeny1999/unisg-thesis-template-typst | https://raw.githubusercontent.com/joshuabeny1999/unisg-thesis-template-typst/main/layout/directory_writing_aids.typ | typst | Other | #let directory_writing_aids(language: "en", body) = {
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(leading: 1em)
// --- AI Usage ---
let title = (en: "Directory of writing aids", de: "Verzeichnis der Schreibhilfsmittel")
heading(title.at(language), numbering: none)
v(12pt)
body
} |
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas3/0_Nedela.typ | typst | #let M = (
"HV": (
("", "", "Tvojím krestóm Christé Spáse, smérti deržáva razrušísja, i dijávoľa prélesť uprazdnísja: ród že čelovíčeskij víroju spasájemyj, písň tebí vsehdá prinósit."),
("", "", "Tvojím krestóm Christé Spáse, smérti deržáva razrušísja, i dijávoľa prélesť uprazdnísja: ród že čelovíčeskij víroju spasájemyj, písň tebí vsehdá prinósit."),
("", "", "Prosvitíšasja vsjáčeskaja voskresénijem tvojím Hóspodi, i ráj páki otvérzesja: vsjá že tvár voschvaľájušči ťá, písň tebí vsehdá prinósit."),
("", "", "Slávľu Otcá i Sýna sílu, i svjatáho Dúcha pojú vlásť, nerazďíľnoje nesozdánnoje Božestvó, Tróicu jedinosúščnuju, cárstvujuščuju v vík víka."),
("Dogmat", "", "Prevélije čúdo: Ďíva róždšaja, i roždénnoje Bóh préžde vík, predjavlénnoje roždénije, i soveršénnoje páče jestestvá. O táinstva strášnaho! Jéže i mýslimoje neizrečénno prebyvájet, i zrímoje ne pojémletsja. Blažénna tý jesí prečístaja otrokovíce, Adáma zemnáho dščí, i Bóha výšňaho jávľšajasja Máti: tohó molí, spastísja dušám nášym."),
),
"S": (
("", "", "Strástiju tvojéju Christé, omračívyj sólnce, i svítom tvojehó voskresénija prosvitívyj vsjáčeskaja, prijimí nášu večérňuju písň čelovikoľúbče."),
("", "", "Kovčéh ťá úmnyj čístaja vímy, nosjáščij skrižáli Bohopísannyja, nám že zakonopoložíteľa i sozdáteľa: jemúže molísja spastísja dušám nášym."),
("", "", "Na zemlí ťa nébo čístaja pokazá, íže vo utróbi tvojéj vselívyjsja Bóh Slóvo, plóť prijím, íže jestestvóm nezrímyj: i doždíši vsím bezsmértnuju rósu neiskusobráčnaja."),
("", "", "Spasénije molítvami tvojími ímamy, íže ťími Ďívo ot bíd prísno i iskušénij búri izbihájem: i sehó rádi prósim neprestánno o nás jéže molíti, spastísja dušám nášym."),
("Dogmat", "", "Páki nazdánije i živót tobóju vtorýj vímy prečístaja Maríje čelovíčeskaho jestestvá, vo črévi tvojém smisívšahosja sozdáteľa tvári, i voskresívšaho nás ot áda i smérti, i žízň víčnuju podávšaho nám, jéže vopíti tebé prisnoĎívo: rádujsja, sovokupívšaja dólnaja nebésnym. rádujsja, nadéždo vsích koncéj zemlí, i predstáteľstvo i zastuplénije. Rádujsja, jáže voskresénijem Sýna tvojehó prosvitívši vsjáčeskaja, i podajúšči mírovi véliju mílosť."),
)
)
#let V = (
"HV": (
("", "", "Tvojím krestóm Christé Spáse, smérti deržáva razrušísja, i dijávoľa prélesť uprazdnísja: ród že čelovíčeskij víroju spasájemyj: písň tebí vsehdá prinósit."),
("", "", "Prosvitíšasja vsjáčeskaja voskresénijem tvojím Hóspodi, i ráj páki otvérzesja: vsjá že tvár voschvaľájušči ťá, písň tebí vsehdá prinósit."),
("", "", "Slávľu Otcá i Sýna sílu, i svjatáho Dúcha pojú vlásť, nerazďíľnoje, nesozdánnoje božestvó, Tróicu jedinosúščnuju, cárstvujuščuju v vík víka."),
("", "", "Krestú tvojemú čestnómu poklaňájemsja Christé, i voskresénije tvojé pojém i slávim: ránoju bo tvojéju mý vsí isciľíchom."),
("", "", "Pojém Spása ot Ďívy voplóščšahosja: nás bo rádi raspjátsja, i v trétij déň voskrése, dáruja nám véliju mílosť."),
("", "", "Súščym vo áďi sošéd Christós blahovistí: derzájte, hlahóľa, nýňi pobidích, áz jésm Voskresénije, áz vý vozvedú, razrušív smértnaja vratá."),
("", "", "Nedostójno stojášče v prečístom domú tvojém, večérňuju písň vozsylájem, iz hlubiný vzyvájušče Christé Bóže: prosvitívyj mír tridnévnym voskresénijem tvojím, izmí ľúdi tvojá ot rukí vrahóv tvojích čelovikoľúbče."),
("", "<NAME>", "Mílostiva, blahoprebýtna mňí Ďívo, i blahoposlúšna javísja prizyvájušču božéstvennuju tvojú bláhodáť vo vsích voístinnu slučájuščich mi sja: vsjú bo nadéždu duší mojejá vozložích k tebí, i vo vsích upováju na božéstvennyj prómysl tvój, tý i búduščija mjá slávy, i životá božéstvennaho spodóbi."),
("", "", "Úhlije vo mňí Bohoródice strastéj mojích vozhoríšasja, ot hňíva že i járosti, ot pijánstva i bludá, ot srebroľúbija i žéstosti sérdca, umerščvlénija ľútaho, ot unýnija i smuščénija, ot tščeslávija že i popránija sóviestnaho, ot níchže izbávi dúšu mojú, moľúsja, Vladýčice, i spasí mja."),
("", "", "Vsí čístoju sóvistiju Bohoródici pripadém, vopijúšče neprestánno ot sredý serdéčnyja: Vladýčice svjatája, spasí vsích ot hňíva i ozloblénija, bíd i padéžej: jáko tebé sťažáchom sťínu, i utverždénije, tobóju spasájemi pod króv tvój pritekájušče."),
("Dogmat", "", "Káko ne divímsja Bohomúžnomu roždéstvú tvojemú, prečéstnája? Iskušénija bo múžeskaho ne prijémši vseneporóčnaja, rodilá jesí bez otcá Sýna plótiju préžde vík ot Otcá roždénnaho bez mátere, nikákože preterpívšaho izminénija, ilí smišénija, ilí razďilénija, no obojú suščestvú svójstvo cílo sochránšaho. Ťímže Máti Ďívo Vladýčice, tohó molí spastísja dušám, pravoslávno Bohoródicu ispovídajuščich ťá."),
),
"S": (
("", "", "Strástiju tvojéju Christé, omračívyj sólnce i svítom tvojehó voskresénija, prosvitívyj vsjáčeskaja, prijimí nášu večérňuju písň čelovikoľúbče."),
("", "", "Živoprijémnoje tvojé vostánije Hóspodi vselénnuju vsjú prosvití, i tvojé sozdánije istľívšeje prizvá. Ťímže kľátvy Adámovy izmínšesja, vopijém: vsesíľne Hóspodi, sláva tebí."),
("", "", "Bóh sýj neizmínen, plótiju straždá izminílsja jesí, jehóže tvár ne terpjášči vísjašča zríti, stráchom preklaňášesja, i steňášči pojét tvojé dolhoterpínije: sošéd že vo ád, tridnéven voskrésl jesí, žízň dáruja mírovi, i véliju mílosť."),
("", "", "Da ród náš ot smérti Christé izbáviši, smérť preterpíl jesí: i tridnéven iz mértvych voskrés, s sobóju voskresíl jesí, íže ťá Bóha poznávšich: i mír prosvitíl jesí. Hóspodi sláva tebí."),
("Dogmat", "", "Bez símene ot božéstvennaho Dúcha, vóleju že Ótčeju začalá jesí Sýna Bóžija, ot Otcá bez Mátere préžde vík súšča: nás že rádi, iz tebé bez otcá bývša, plótiju rodilá jesí, i mládenca mlekóm pitála jesí. Ťímže ne prestáj, molíti, izbávitisja ot bíd dušám nášym."),
),
"T": (
("", "", "Da veseľátsja nebésnaja, da rádujutsja zemnája: jáko sotvorí deržávu mýšceju svojéju Hospóď, poprá smértiju smérť, pérvenec mértvych býsť, iz čréva ádova izbávi nás, i podadé mírovi véliju mílosť."),
("Bohoródičen", "", "Ťá chodátajstvovavšuju spasénije róda nášeho, vospivájem Bohoródice Ďívo: plótiju bo ot tebé vosprijátoju Sýn tvój, i Bóh náš, krestóm vospriím strásť, izbávi nás ot tlí jáko čelovikoľúbec."),
),
)
#let P = (
"1": (
("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."),
("", "", "Jáko <NAME>iju ťá Dúchom božéstvennym, Otcá že blahovolénijem jávľšujusja, vírniji písňmi čístymi vinčájim, prečístaja Bohonevísto: i cilújem ťá píňmi so archánhelom, vo spasénije náše."),
("", "", "Ot rébr úbo Adámovych sozidájetsja Jéva, drévnim Bohozdánijem: ot utróby že Bohoródicy javísja Christós, sýj Bóh náš, vočelovíčsja neprelóžno, vrémenen býsť prevíčnyj."),
("", "", "Íže Jévinu utróbu osúžď v pečálech, rodíti plodý v boľízni, vo črévo tvojé vselísja Ďívo čístaja, sýj Bóh náš, plótiju javísja páče slóva, i pramáternij razriší dólh."),
("", "", "V nečájanija hlubinú vpádše ťahotámi, priľížno zovém Bohorodítelnice k tebí: Vladýčice, pomozí potopľájemym ďíly lukávych prehrišénij, ťá bo jedínu ímamy nadéždu po Bózi."),
),
"3": (
("", "", "Íže ot ne súščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."),
("", "", "Ťá projavľáše žézl Aarónov, bez napojénija procvítšij, Bohoródice prečístaja, bez símene róždši voplóščšahosja Bóha nepreménno."),
("", "", "božéstvennyj óhň ťá nosjášču, jáko svitíľnik prečístaja, províďi prorók dúchom, blahouchánije nosjáščuju súščym v míri, i žízň víčnuju."),
("", "", "Ko archánhelu pristúpim Havriílu, rádujsja, viščájušče Ďívi písňmi: tobóju bo razrišítsja osuždénija práďidňaja kľátva."),
("", "", "Ťá presvjatája Bohoródice, jáko sťínu spasénija imúšče hríšniji spasájemsja: ne prézri Vladýčice, i ne posramí náša molénija."),
),
"4": (
("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."),
("", "", "Hóru mýslennuju, dobroďítelej síň, Dúchom drévle Avvakúm bohovídno ťá víďiv, propovídaše prečístaja: jáko ot júha prišédša ot tebé Slóvo plóť prijémša."),
("", "", "Hóru ťá véliju nesikómuju Daniíl Dúchom víďi, ne novosikómu javľája čístotú ďívstva tvojehó Vladýčice: ot nejáže kámeň usičésja, <NAME>óvo, lésti nizlahája ídoľskija."),
("", "", "Hóru ťá Davíd čúdnu i túčnu prorečé: jedinoródnyj bo ot Otcá Sýn v ťá blahovolí čístaja, vselítisja voploščájem. Ťím tí, rádujsja, dúchom zovém."),
("", "", "Vsjá blahája i téplaja zastúpnica súšči hríšnikom i smirénnym, Bohorodíteľnice prečístaja Vladýčice, ot bíd, i skorbéj, i hrichóv spasáj rabý tvojá."),
),
"5": (
("", "", "Jáko víďi Isáia obrázno na prestóľi prevozneséna Bóha, ot ánhel slávy dorinosíma, o okajánnyj, vopijáše, áz: províďich bo voploščájema Bóha, svíta nevečérňa, i mírom vladýčestvujušča."),
("", "", "Izrastí žézl Jesséev cvít neuvjadájemyj, Ďíva Maríja Bóha beznačáľnaho, bez símene, ot Dúcha božéstvennaho i Ótča, cárstva deržávnaja jazýčeskaja obladávšaho, na nehóže jazýcy upováša."),
("", "", "K<NAME> priíde na prestól Davídov, cárstvuja iz tebé Bohoródice Bóh voploščájem: o čúdo! i bráň razríš, potčé kňázi moavítskija, i tebé róždšuju carícu pokazá."),
("", "", "Neporóčnuju tvojú dobrótu, ot nejáže Christós v plóť oblečésja bez símene Ďívo, Isáia javľája, zovét vopijá: Hospóď slávy hrjadét na óblaci léhci, i prélesti ťmú othoňája, prosvitít nás."),
("", "", "Ot Dúcha svjáta začénši Slóvo jedinosúščnoje Otcú, Ďívo sijé rodilá jesí vo dvú jestestvú súšča, Bóha soveršénna i soveršénna čelovíka: jehóže víroju počitájem plotskóe javlénije."),
),
"6": (
("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."),
("", "", "Ódr ťá písňmi premúdryj prednapisúet vsepítaja, na némže počí Bóh voploščájem vo ipostási iz tebé, i proslávi ťá, nesmísno raždájem."),
("", "", "Býsť Slóvu jáko izbránnaja, Ďívo vsepítaja, izbránnaja odéžda: jáko porfíru božéstvennuju iz tebé plóť prijém vocarísja, Bohoľípno oďíjavsja."),
("", "", "Býsť sojedinénija božéstvennaho vmistílišče, Bohonevísto, zláta svitľíjši: tobóju bo býsť Bóh jáko čelovík, i besídova čelovíkom Bóh, jáko čelovík."),
("", "", "Umertví nečéstvujuščich v ťá, Ďívo vsepítaja, zlóby jéres: jáko závistiju tájut preslávnoje tvojehó óbraza víďašče podóbije."),
),
"S": (
("", "", "Ot teplotý víry vopijú ti Bohoródice, nedostójnymi ustý, i skvérnym sérdcem: spasí mja pohružénnaho hrichámi, uščédri umerščvlénnaho otčájanijem, da zovú ti spasájem: rádujsja Ďívo, christijánom pomóščnice."),
),
"7": (
("", "", "Préžde óbrazu zlatómu, persídskomu čtílišču, ótrocy ne pokloníšasja, trijé pojúšče posreďí péšči: otcév Bóže blahoslovén jesí."),
("", "", "Kupiná i plámeň soobrázňi sovokúpľšesja, i netľínna obojá jávľšesja, ťá Ďívo jásno projavľájut: íbo rodilá jesí Bóha, i ďívstvuješi."),
("", "", "Runó i rosá Hedeónu vo izminéniji obrazújema, roždestvó tvojé predpíšut: tý bo jedína božéstvennoje Slóvo nósiši vo črévi, jáko dóžď, Ďívo Máti."),
("", "", "Hrichá mojehó óhň páče hejénskaho, plámeň mňí soďivájet, síj uhasí čístaja, tvojéju mílostiju, pokajánijem mjá ko svítu nastavľájušči."),
("", "", "Tvojehó zráka javlénije Bohoródice prečístaja, čtúšče jáko pérvyj óbraz ťá, zastúpnicu prísno, i pokróv blahopremínen k Bóhu ímamy vsí."),
),
"8": (
("", "", "Vavilónskaja péšč ótroki ne opalí, nižé Božestvá óhň Ďívu rastlí. Ťím so ótroki vírniji vozopijím: blahoslovíte ďilá Hospódňa Hóspoda."),
("", "", "Ťá otéc izvóli nevístu neiskusobráčnuju, jáko krín presvítlyj posreďí térnija obrít, svítlostiju dobróty blistájuščuju Dúchom božéstvennym, Sýnu v žilíšče."),
("", "", "Svjaťíjšuju výšnich síl Ďívu preneporóčnuju, bez razsuždénija slávľu jávi: tvorcá bo sích vo črévi ponesé, nesmísnym sojedinénijem plóť prijémša ot tebé."),
("", "", "Ďívstvo nekrádomo Ďívo sochránši, Máti javílasja jesí Sýna Bóžija voístinnu, Otcá blahovolénijem nevísta bývši, i prijátelišče slávy Dúcha netľínno."),
("", "", "Íže jestestvóm neveščéstvennyj Bóh i nevídimyj, prósto i neizrečénno páče jestestvá raždájetsja čelovík ot svjatýja Ďívy, suhúb zrím vo jedínoj ipostási, v néjže vídim jésť pisáňmi."),
),
"9": (
("", "", "Nóvoje čúdo i Bohoľípnoje: ďivíčeskuju bo dvér zatvorénuju jávi prochódit Hospóď, náh vo vchóďi, i plotonósec javísja vo ischóďi Bóh, i prebyvájet dvér zatvoréna. Sijú neizrečénno jáko Bohomáter veličájem."),
("", "", "Svjatáho kórene svját plód: neplódnyja bo, osvjaščénnyja zakónom Bóžijim Ótčijim, neuvjadájemuju žízň soveršájuščuju Bohoródica otrokovíca procvité: i rádujetsja Ánna, prijémši otročá v stárosti, Bóžiju Máter, júže slávim."),
("", "", "Nóvo roždestvó i bohovídno svjatáho tvojehó i Bohonósnaho čréva čístaja: v ném bo napisásja óbraz v čelovíka Ótčijim pérstom, Sýn voplóščsja svját Dúchom svjatým. Jehóže nesmísno jáko Bóha i čelovíka veličájem."),
("", "", "Vopijét vsják súd na mjá: ďilá bo hrichóvnych ďijánij vópľ soďivájut mňí preťášče, i dušá vsjá vísť, ímiže preprína búdet, i trepéščet plámene hejénskaho: ot nehóže préžde koncá, molítvami tvojími izbávi mjá Vladýčice."),
("", "", "Po roždeství javísja netľínna čístaja: neizmínno bo ziždíteľa vsích plótiju, Bohoródice, rodilá jesí čelovíka páče jestestvá, Ótča suščestvá ne otstúpľša, i ábije prebýsť Ďíva Dúchom božéstvennym. Ťímže slávjašče ťá, písň soveršájem."),
),
)
#let N = (
"1": (
("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."),
("", "", "Nepostižímoje jedíno Hóspodonačálije, i jedíno Tróičeskoje Bohonačálije, trisijánnaho svíta tvojehó mja spodóbi: jáko da vospojú ťá, pivájemoje neprestánno trisvjátými písňmi, ánheľskimi ustý."),
("", "", "Svjáščénno neveščéstvenniji vsí čínove pojút, jáko tvoríteľnuju vinú, jedínstvennuju, trisvítluju, načáľňijšuju jávi: júže sohlásno pojém, i čelovíčeskaja mnóžestva, i vírno slávim brénnymi ustý."),
("", "", "Úm, i Slóvo i Dúch, Bohoslóvcy prilíčňi, i znameníteľňi tebé naríčut: bezstrástno roždestvó ot neroždénnaho otcá, Sýnu známenajušču, Bóže jedinonačáľne vsích, vkúpi i Dúcha božéstvennaho ischoždénije."),
("", "", "Jáko čelovikoľúbec jestestvóm, čelovíčeskoje suščestvó prijém Bóžij Slóve, Tróičnyj vozsijál jesí, jedinonačáľňijšij svít jedínaho Božestvá, preproslávlennuju vsím pokazávyj, róždšuju ťá Ďívu prečístuju."),
),
"3": (
("", "", "Íže ot ne súščich vsjá privedýj slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."),
("", "", "Utróiti drévle vódu poveľív Iliá na poľinach, obrázno projaví Tróičnuju ipostás, jedínstvennaho Bóžija Hóspodonačálija."),
("", "", "Tľínnoje jestestvó pojét ťá zemnoródnych, jedínaho i trisvítlaho sozdáteľa neizmínnaho, i vopijét tí Vladýko: vserazlíčnaho mjá preminénija izbávi, i spasí mja."),
("", "", "Rávno viščájušče slovesém proróčeskim, slávnych apóstol že i propovídnik víry, ravnoďíteľnuju ťá Tróicu slavoslóvim vírniji, Bóže vsích."),
("", "", "S prestóla vysókaho sníde Christós, čelovíka vozvyšája, jáko čelovikoľúbec, tobóju prečístaja, i trisólnečnyj svít vsím vozsijá."),
),
"S1": (
("", "<NAME>", "Presúščestvennyj i jedíne Hóspodi Christé, i roždénije prebeznačáľnaho Otcá, i Dúše božéstvenňijšij, pomíluj rabý tvojá: vsí bo sohrišíchom, no ot tebé ne otstupíchom. Ťímže mólim ťá triipostásne Hóspodi, jáko imíjaj vlásť, sozdánije tvojé spasí ot vsjákaho obstojánija."),
("Bohoródičen", "", "Presúščestvennyj Bóh i Hospóď iz tebé voplotísja za bláhosť, jéže po nám osuščestvovávyjsja, i prebýv jéže bí. Ťímže i Bohočelovíka sehó počitájušče vsečístaja, ťá neiskusobráčnuju Bohoródicu propovídujem, slávjašče prevélije čúdo tvojehó bezsímennaho roždénija."),
),
"4": (
("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho vo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."),
("", "", "Ótrasľ suhúb ot Otcá, jáko ot kórene prozjabé Sýn, i Dúch právyj, sojestéstvenna prozjabénija, i Bohosaždénna, i cvíti sobeznačáľniji: jáko trijém býti svítom Božestvá."),
("", "", "Ótrasľ suhúb ot Otcá, jáko ot kórene prozjabé Sýn, i Dúch právyj, sojestéstvenna prozjabénija, i Bohosaždénna, i cvíti sobeznačáľniji: jáko trijém býti svítom Božestvá."),
("", "", "Mnóžestva úmnych suščéstv, neprestánno pojút ťá, nedomýslimaho Bóha, s nímiže mý slávim, hlahóľušče: Tróice presúščnaja, tvojá rabý spasí, jáko čelovikoľúbec."),
("", "", "Raspalíl jesí nás v ľubóv tvojú, mnohomílostive Slóve Bóžij, íže nás rádi voplóščsja neprelóžňi, i trisvítloje jedíno Božestvó tájno naučív: ťímže ťá slávim."),
),
"5": (
("", "", "Jáko víďi Isáia obrázno na prestóľi prevoznesénna Bóha, ot ánhel slávy dorinosíma, o okajánnyj, vopijáše, áz: províďich bo voploščájema Bóha, svíta nevečérňa, i mírom vladýčestvujušča."),
("", "", "<NAME>óspodonačáľnika, obrázno jáko víďi Isáia Bóha, v trijéch lícich slavoslóvima prečístymi hlásy Serafím, póslan býsť propovídati ábije trisvítloje suščestvó, i jedínicu trisólnečnuju."),
("", "", "<NAME>óspodonačáľnika, obrázno jáko víďi Isáia Bóha, v trijéch lícich slavoslóvima prečístymi hlásy Serafím, póslan býsť propovídati ábije trisvítloje suščestvó, i jedínicu trisólnečnuju."),
("", "", "Jáže vsích nevídimych i vídimych jestestvó, ot ne súščich préžde sostávľšaja, jedínice trisólnečnaja, íže jedínaho ťá Bóha vírno vospivájuščich ot vsjákich iskušénij izbávľši, tvojejá slávy spodóbi."),
("", "", "Nevístnik svitonósen i číst Ďívo, bývšij Bóžij, vospivájem ťá ľubóviju, i blažím: iz tebé bo rodísja Christós, v suščestvách i choťínijich suhúbych, íže jedín ot Tróicy i slávy sýj Hospóď."),
),
"6": (
("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."),
("", "", "Preséľnik sýj Avraám, spodóbisja obrázno vosprijáti jedínstvennaho úbo Hóspoda v trijéch ipostásich, presúščestvenna múžeskimi že zráki."),
("", "", "Preséľnik sýj Avraám, spodóbisja obrázno vosprijáti jedínstvennaho úbo Hóspoda v trijéch ipostásich, presúščestvenna múžeskimi že zráki."),
("", "", "Naprávi serdcá tvojích rabóv k svítu nepristúpnomu, o trisólnečne Hóspodi, i tvojejá slávy sijánije podážď dušám nášym, vo jéže oblistájemym býti tvojéju dobrótoju neizrečénnoju."),
("", "", "Otvérzi mňí dvéri svíta róždšahosja ot utróby tvojejá prečístaja: da zrjú trisvítluju lučú Božestvá, i slávľu ťá vsesvítluju Vladýčicu."),
),
"S2": (
("", "Božéstvennyja víry", "Božéstvennaho jestestvá jedinosúščnaho trisólnečnuju pojém deržávu, i trisvjatými hlásy vozopijím: svját jesí Ótče prebeznačáľnyj, svját jesí Sýne sobeznačáľnyj, i Dúše svjatýj, jedíne nerazďíľnyj Bóže náš, i vsích tvórče čelovikoľúbče."),
("Bohoródičen", "Čúdo prevélije", "Káko soderžásja nevmistímyj vo črévi tvojém i voplotísja, i javísja, jáko čelovík, ne preterpívyj smišénija ilí razďilénija božéstvennaho i neprelóžnaho Božestvá, otrokovíce vsečístaja: ťímže Bohoródicu ťá vírno propovídujem prísno i slávim."),
),
"7": (
("", "", "Jákože drévle blahočestívyja trí ótroki orosíl jesí v plámeni chaldéjsťim, svítlym Božestvá ohném i nás ozarí, blahoslovén jesí vzyvájuščyja, Bóže otéc nášich."),
("", "", "Chrám mjá pokaží tvojehó Božestvá Vladýko, trisijánnaho, vés svítel: hrichóvnaho omračénija ľútaho i strastéj výšša, svitodáteľnymi tvojími sijániji, Bóže otéc nášich blahoslovén jesí."),
("", "", "Božestvá zrák jedín vozviščájem, v trijéch ipostásnych i razďíľnych svójstvach, Otcá, i Sýna, i Dúcha: blahoslovén jesí zovúšče, Bóže otéc nášich."),
("", "", "Javísja Avraámu Bóh trijipostásnyj u dúba drévle mamvríjskaho, o strannoľúbiji mzdú Isaáka vozdajá za mílosť: jehóže i nýňi slávim, jáko Bóha otéc nášich."),
("", "", "Javísja na zemlí, býv čelovík vseďíteľ, Bohoľípno ot ďívstvennaho i prečístaho tvojehó čréva, i nás oboží, blahoslovénnaja vsečístaja, Bohoródice prečístaja."),
),
"8": (
("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojášče júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."),
("", "", "Beznačáľna Otcá jáko ot kórene, Slóvo, i Dúch sobeznačáľňi súšča: jáko ótrasli presúščestvennaho Bohonačálija pokazáša Tróicy slávu jedínuju i sílu: júže pojém vsí vírniji vo víki."),
("", "", "Beznačáľna Otcá jáko ot kórene, Slóvo, i Dúch sobeznačáľňi súšča: jáko ótrasli presúščestvennaho Bohonačálija pokazáša Tróicy slávu jedínuju i sílu: júže pojém vsí vírniji vo víki."),
("", "", "Upravľáješi tvojími svitlosťmí číny nebésnyja, vospiváti nemólčno trisvjatými písňmi božéstvennymi, Ótče, Slóve soobrázne, i Dúše, trisvítluju deržávu i ravnomóščnuju. Ťímže ťá pojém vo vsjá víki."),
("", "", "Prorečénija proróčeskaja, tvojé roždestvó izdaléča víďivše Bohoródice, voschvaľáchu, jáko bez símene, i páče jestestvá róždšahosja Vladýčice: i sohlásno sehó pojém, jáko Hóspoda, i prevoznósim vo vsjá víki."),
),
"9": (
("", "", "Nóvoje čúdo i Bohoľípnoje, ďivíčeskuju bo dvér zatvorénnuju, jávi prochódit Hospóď, náh vo vchóďi, i plotonósec javísja vo ischóďi Bóh, i prebyvájet dvér zatvoréna: sijú neizrečénno jáko Bohomáter veličájem."),
("", "", "Víďiti slávu trisijánnuju, bohovídniji bezplótnych čínove jávi, voschodíti krilý želájut horí: no hovíjut ziló nepristúpnaho svíta, i písni neprestánno vopijút: s ními sohlásno jedínstvennaja Tróice ťá slávim."),
("", "", "Víďiti slávu trisijánnuju, bohovídniji bezplótnych čínove jávi, voschodíti krilý želájut horí: no hovíjut ziló nepristúpnaho svíta, i písni neprestánno vopijút: s ními sohlásno jedínstvennaja Tróice ťá slávim."),
("", "", "Nesýtnoju ľubóviju i íže na zemlí, úmnuju dúšu ot tebé prijémše, i slovésnuju, tebé pojím Vladýko, Bóže vsích, jedínstvennoje jestestvó voístinnu, i Tróičnoje lícy, ot vsehó sérdca. Ťímže ščédre jáko mnohomílostiv, nás uščédri."),
("", "", "Chrám mjá pokaží jedinonačáľnaho, i trisvítlaho tvojehó Bohonačálija, svitovíden, čísťi služíti tebí ziždíteľu vsích, i neizrečénnuju tvojú slávu úmno zríti: molítvami jedínyja Bohoródicy, júže dostójno jáko preslávnuju veličájem."),
),
)
#let U = (
"T": (
("", "", "Da veseľátsja nebésnaja, da rádujutsja zemnája: jáko sotvorí deržávu mýšceju svojéju Hospóď, poprá smértiju smérť, pérvenec mértvych býsť, iz čréva ádova izbávi nás, i podadé mírovi véliju mílosť."),
("Bohoródičen", "", "Ťá chodátajstvovavšuju spasénije róda nášeho, vospivájem Bohoródice Ďívo: plótiju bo ot tebé vosprijátoju Sýn tvój, i Bóh náš, krestóm vospriím strásť, izbávi nás ot tlí jáko čelovikoľúbec."),
),
"S1": (
("", "", "Christós ot mértvych vostá, načátok usópšich: pervoroždén tvári, i soďíteľ vsích bývšich, istľívšeje jestestvó róda nášeho v sebí samóm obnoví. Ne ktomú smérte obladáješi: íbo vsích Vladýka deržávu tvojú razruší."),
("", "", "Plótiju smérti vkusív Hóspodi, hóresť smérti presíkl jesí vostánijem tvojím, i čelovíka na ňú ukripíl jesí, pérvyja kľátvy odoľínije prizyvája: zaščítniče žízni nášeja Hóspodi, sláva tebí."),
("Bohoródičen", "", "Krasoťí ďívstva tvojehó, i presvítloj čistoťí tvojéj, Havriíl udivívsja, vopijáše tí Bohoródice: kúju tí pochvalú prinesú dostójnuju? Čtó že vozymenúju ťá? Nedoumiváju i užasájusja. Ťímže jáko poveľín bých, vopijú ti: rádujsja blahodátnaja."),
),
"S2": (
("", "Krasoťí ďívstva", "Neizmínnaho božestvá, i vóľnyja strásti tvojejá Hóspodi, užássja ád, v sebí rydáše: trepéšču plóti netľínnyja ipostási, víždu nevídimaho, tájno borjúšča mjá. Ťímže i íchže deržú, zovút: sláva Christé voskreséniju tvojemú."),
("", "", "Nepostižímoje raspjátija, i neskazánnoje vostánija Bohoslóvstvujem vírniji, tájinstvo neizrečénnoje: dnés bo smérť i ád pľinísja, ród že čelovíčeskij v netľínije oblečésja. Ťím blahodarjášče vopijém tí: sláva Christé vostániju tvojemú."),
("Bohoródičen", "", "Nepostižímaho i neopísannaho, jedinosúščnaho Otcú i Dúchovi, vo utróbu tvojú tájno vmistíla jesí Bohoródice, jedíno i nesmísno ot Tróicy Božestvó: poznáchom roždestvó tvojé v míri sláviti. Ťímže i blahodárstvenno vopijém tí: rádujsja blahodátnaja."),
),
"Y": (
("", "", "Udivľája viďínijem, orošája hlahólaniji, blistájajsja ánhel mironósicam hlahólaše: čtó živáho íščete vo hróbi? vostá istoščívyj hróby. Tlí preminíteľa razumíjte nepremínnaho. Rcýte Bóhovi: kóľ strášna ďilá tvojá, jáko ród spásl jesí čelovíčeskij!"),
),
"A1": (
("", "", "Pľín Sijóň tý izjál jesí ot Vavilóna: i mené ot strastéj k životú privlecý Slóve."),
("", "", "V júh síjuščiji slezámi božéstvennymi, žnút klásy rádostiju prisnoživótija."),
("", "", "Svjatómu Dúchu vsjákoje blahodárije, jákože Otcú i Sýnu sooblistájet, v némže vsjá živút i dvížutsja."),
("", "", "Svjatómu Dúchu vsjákoje blahodárije, jákože Otcú i Sýnu sooblistájet, v némže vsjá živút i dvížutsja."),
),
"A2": (
("", "", "Ášče ne Hospóď sozíždet dóm dobroďítelej, vsúje truždájemsja: dúšu že pokryvájušču, niktóže náš razorít hrád."),
("", "", "Plodá črévna Dúchom synotvorénoje tebí Christú jákože i Otcú, svjatíji vsehdá súť."),
("", "", "Svjatým Dúchom prozrítsja vsjákaja svjatýňa, premúdrosť: osuščestvújet bo vsjákuju tvár: tomú poslúžim, Bóh bo, jáko otcú že i slóvu."),
("", "", "Svjatým Dúchom prozrítsja vsjákaja svjatýňa, premúdrosť: osuščestvújet bo vsjákuju tvár: tomú poslúžim, Bóh bo, jáko otcú že i slóvu."),
),
"A3": (
("", "", "Bojáščijisja Hóspoda blažéni, v putí choďášče zápovidej: sňiďát bo živótnoje vseplódije."),
("", "", "Ókrest trapézy tvojejá vozveselísja, zrjá tvojá pastyrenačáľniče isčádija, nosjášča vítvi blahoďílanija."),
("", "", "Svjatým Dúchom vsjákoje bohátstvo slávy, ot nehóže blahodáť, i živót vsjákoj tvári: so Otcém bo vospivájem jésť, i s Slóvom."),
("", "", "Svjatým Dúchom vsjákoje bohátstvo slávy, ot nehóže blahodáť, i živót vsjákoj tvári: so Otcém bo vospivájem jésť, i s Slóvom."),
),
"P": (
("", "", "Rcýte vo jazýcich, jáko Hospóď vocarísja, íbo isprávi vselénnuju, jáže ne podvížitsja."),
("", "", "Chvalíte Bóha vo svjatých jehó: Jevánhelije voskrésno, i próčeje po rjádu."),
),
"K": (
"P1": (
"1": (
("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."),
("", "", "Íže zémľu osudív, prestúpľšemu pótom iznestí plodá térnije ot térnija vinéc iz rukí zakonoprestúpnyja, séj Bóh náš, plótski prijémyj, kľátvu razrušíl jésť: jáko proslávisja."),
("", "", "Pobidíteľ i odoľíteľ smérti, íže smérti ubojávsja, javísja: strástnuju bo plóť oduševlénnuju prijém, séj Bóh náš, i brávsja s mučítelem, vsjá sovoskresí: jáko proslávisja."),
("Bohoródičen", "", "Ístinnuju Bohoródicu vsí jazýcy slávjat ťá, bez símene róždšuju: sošéd bo vo utróbu osvjaščénnuju tvojú, séj Bóh náš, jéže po nám osuščestvovásja, Bóh že i čelovík iz tebé rodísja."),
),
"2": (
("", "", "Písň nóvuju pojím ľúdije, ot Ďívy róždšemusja vo spasénije náše, i jedíno sotvóršemu s nebésnymi zemnája: jáko proslávisja."),
("", "", "Ród čelovíč poraboščén mučítelem hrichoľúbnym, króviju božéstvennoju Christós iskupí, i obohotvorív obnovíl jésť: jáko proslávisja."),
("", "", "Jáko úbo smérten, smérti choťáj, íže životú sokróviščnik, Christós vkusí: a jáko bezsmérten sýj jestestvóm, mértvyja oživotvoríl jésť: jáko proslávisja."),
),
"3": (
("", "", "Písň nóvuju pojím ľúdije, ot Ďívy róždšemusja vo spasénije náše, i jedíno sotvóršemu s nebésnymi zemnája: jáko proslávisja."),
("", "", "Koľíno prikloňájet vsjáko jestestvó nebésnych Ďívo, voplóščšemusja iz tebé, so zemnými že dostoľípno preispódňaja: jáko proslávisja."),
("", "", "O primirénij jáže v tebí! Blahích bo nezavístno podáteľ, jáko Bóh Dúcha božéstvennaho podávyj nám, plóť ot tebé otrokovíce priját: jáko proslávisja."),
)
),
"P3": (
"1": (
("", "", "Íže ot ne súščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."),
("", "", "Krestóm tvojím postyďísja nečestívyj, soďíla bo jámu, júže iskopá, vpadé: smirénnych že voznesésja Christé róh, vo tvojém voskreséniji."),
("", "", "Blahočéstija propovídanije jazýkom, jáko vodá pokrý morjá čelovikoľúbče: voskrés bo ot hróba, Tróičeskij otkrýl jesí svít."),
("Bohoródičen", "", "Preslávnaja hlahólana býša o tebí, hráde oduševlénnyj prísno cárstvujuščaho: tobóju bo Vladýčice, súščym na zemlí Bóh spožíl jésť."),
),
"2": (
("", "", "Luk sokrušíl jesí vrážij, i ščitý stérl jesí, krípostiju Vladýko Christé, utverždénije náše, svját jesí Hóspodi."),
("", "", "Očiščénije prečístyj kreste, ídoľskich javílsja jesí tý nečistót: jáko Iisús prebožéstvennyj, na tebí rúci rasprostérl jésť."),
("", "", "Da vsí vírniji živoprijémnyj hróbe, tebí poklaňájemsja: pohrebésja bo v tebí i vostá Christós voístinnu Bóh náš."),
),
"3": (
("", "", "Luk sokrušíl jesí vrážij, i ščitý stérl jesí, krípostiju Vladýko Christé, utverždénije náše, svját jesí Hóspodi."),
("", "", "Žézl iz kórene Jesséova, proróčeski prozjábši Ďíva, cvít ťá Christé, vozsijá nám: svját jesí Hóspodi."),
("", "", "Da božéstvennomu pričástiju zemnoródnyja soďílaješi, ot Ďívy plóť nášu, tý obniščál jesí, prijém: svját jesí Hóspodi."),
)
),
"P4": (
"1": (
("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."),
("", "", "Jázvy Christé, i rány mílostivno podjál jesí, dosádu po lanítoma udarénij terpjá, i dolhoterpilívňi oplevánija nosjá, ímiže soďílal jesí mňí spasénije: sláva síľi tvojéj Hóspodi."),
("", "", "Ťílom smértnym životé, smérti pričastílsja jesí, strásti rádi níščich, i vozdychánija ubóhich tvojích: i rastlív tľíjuščaho preproslávlenne, vsích sovoskresíl jesí, jáko proslávisja."),
("Bohoródičen", "", "Pomjaní Christé, jéže sťažál jesí stádo strástiju tvojéju: preproslávlennyja tvojejá Mátere mílostivnyja moľbý prijém, i positív ozlóblennoje, izbávi síloju tvojéju Hóspodi."),
),
"2": (
("", "", "Stránna i neizréčenna roždestvá tvojehó tájna, uslýšach slúch tvój, i ubojáchsja, i veseľásja vopijú tí: síľi tvojéj sláva čelovikoľúbče."),
("", "", "Sozdávyj po óbrazu tvojemú čelovikoľúbče čelovíka, i umerščvléna hrichóm prestuplénija rádi, raspénsja na lóbňim, spásl jesí."),
("", "", "Mértvyja úbo, íchže požré smérť, otdadé: razorísja že i ádovo tletvórnoje cárstvo, voskrésšu tí iz hróba Hóspodi."),
("Bohoródičen", "", "Maríje čístaja, zlatája kadíľnice, neslijánno jáko jedín ot Tróicy v ťá sošéd, voplóščsja Bóh Slóvo, mír oblahouchál jésť."),
),
"3": (
("", "", "Stránna i neizréčenna roždestvá tvojehó tájna, uslýšach slúch tvój, i ubojáchsja, i veseľásja vopijú tí: síľi tvojéj sláva čelovikoľúbče."),
("", "", "Íže postávivyj hóry Vladýko, mírilom božéstvennaho rázuma, otsičén jesí ot Ďívy kámeň, kromí rúk: síľi tvojéj sláva čelovikoľúbče."),
("", "", "Nedúhujuščeje iscilíl jesí náše jestestvó Vladýko, skoríjšuju iz Ďívy sijú sojedinív ciľbú, tvojé prečístoje Slóve božestvó."),
("", "", "Čásť mojá jesí Hóspodi, i nasľídije želánnoje, sojedinívyj mjá iz Ďívy, Slóve, ipostási tvojéj, plótiju býv ipostás."),
)
),
"P5": (
"1": (
("", "", "K tebí útreňuju vsích tvorcú, preimúščemu vsják úm mírovi, zané svít poveľínija tvojá: v níchže nastávi mjá."),
("", "", "Sudijí neprávednomu, jevréjskoju závistiju prédan býv vsevídče, i vséj právedňi suďáj zemlí, Adáma drévňaho izbávil jesí osuždénija."),
("", "", "Tvój mír cérkvam tvojím Christé, nepobidímoju síloju krestá tvojehó, iz mértvych voskresýj podážď, i spasí dúšy náša."),
("Bohoródičen", "", "Skínija svjatája, i prostránňijši nebés, jáko íže vo vséj tvári nevmistímaho Slóva Bóžija prijémši, jedína javílasja jesí prisnoďívo."),
),
"2": (
("", "", "Na zemlí nevídimyj javílsja jesí, i čelovíkom vóleju sožíl jesí nepostižímyj, i k tebí útreňujušče, vospivájem ťá čelovikoľúbče."),
("", "", "Kopijém v rebró tvojé, o Christé mój, probodén býv, ot rebrá čelovíča sozdánnuju, hubíteľstva vsím čelovíkom bývšuju chodátaicu, kľátvy svobodíl jesí."),
("", "", "Ráven Otcú po suščestvú sýj, svjaščénnyj chrám prečístaho tvojehó i vsečestnáho ťilesé, iz mértvych voskresíl jesí Christé Spáse náš."),
),
"3": (
("", "", "Na zemlí nevídimyj javílsja jesí, i čelovíkom vóleju sožíl jesí nepostižímyj, i k tebí útreňujušče, vospivájem ťá čelovikoľúbče."),
("", "", "Slóvo Bóžije Sýn tvój Ďívo, soďíteľ Adáma pervozdánnaho, ne sozdánije, ášče i plóť oduševlénu sebí iz tebé sozdál jésť."),
("", "", "Ráven Otcú Sýn tvój Ďívo, Slóvo Bóžije, ipostás soveršénna vo dvojú jestestvú, Iisús Hospóď, Bóh soveršén i čelovík."),
)
),
"P6": (
"1": (
("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."),
("", "", "Bézdna mílosti i ščedrót obýde mjá, blahoutróbnym snítijem tvojím: voplóščsja bo Vladýko, i býv v rábiji zráci obožíl jesí, s sobóju soprosláviv."),
("", "", "Umerščvlénije podját umertvíteľ, umerščvlénaho oživlénno víďa: tvojehó voskresénija síji súť Christé óbrazy, i strásti tvojejá prečístyja pobidíteľnaja ."),
("Bohoródičen", "", "Prečístaja, jáže jedína sozdáteľu i čelovíkom, páče umá ischodátaivšaja, Sýna tvojehó mílostiva prehréššym rabóm tvojím, i pobórnika býti, pomolísja."),
),
"2": (
("", "", "<NAME>, jéže v preispódňim áďi, jestéstvennyj óbraz býv, vopijáše: vozvedí ot tlí živót mój, čelovikoľúbče."),
("", "", "Ránami tý iskusívsja, ot áda uránenych, strástiju krestá sovoskrésíl jesí. Ťímže tí zovú: vozvedí ot tlí živót mój, čelovikoľúbče."),
("", "", "Otverzájutsja tí Christé stráchom vratá ádova, sosúdy že vrážija voschiščájutsja: ťímže ťá žený sritóša, vmísto pečáli rádosť prijímša."),
),
"3": (
("", "", "<NAME>, jéže v preispódňim áďi, jestéstvennyj óbraz býv, vopijáše: vozvedí ot tlí živót mój, čelovikoľúbče."),
("", "", "Voobražájetsja jéže po nám, ot netľínnyja Ďívy, íže óbrazom nerazlúčnyj óbrazom býv i véščiju, ne prelóžsja Božestvóm čelovík."),
("", "", "Bézdny hrichóv, i búri strastéj prečístaja izbávi mjá: jesí bo pristánišče, i bézdna čudés, víroju pritekájuščym k tebí."),
)
),
"K": (
("", "Ďíva dnés", "Voskrésl jesí dnés iz hróba ščédre, i nás vozvél jesí ot vrát smértnych: dnés Adám likújet, i rádujetsja Jéva, vkúpi že i prorócy s patrijárchi vospivájut neprestánno božéstvennuju deržávu vlásti tvojejá."),
("", "", "Nébo i zemľá dnés da likovstvújut, i Christá Bóha jedinomúdrenno da vospivájut, jáko úzniki ot hrobóv voskresí. Srádujetsja vsjá tvár, prinosjášči dostójnyja písni sozdáteľu vsích, i izbáviteľu nášemu: jáko čelovíki iz áda dnés jáko žiznodáteľ sovozvéd, na nebesá sovozvyšájet, i nizlahájet vrážija voznošénija, i vratá ádova sokrušájet božéstvennoju deržávoju vlásti svojejá."),
),
"P7": (
"1": (
("", "", "Jákože drévle blahočestívyja trí ótroki orosíl jesí v plámeni chaldéjsťim, svítlym božestvá ohném i nás ozarí, blahoslovén jesí, vzyvájuščyja, Bóže otéc nášich."),
("", "", "Razdrásja cerkóvnaja svítlaja katapetásma v raspjátiji soďíteľa, sokrovénnuju v pisániji javľájušči vírnym ístinu, blahoslovén jesí, zovúščym, Bóže otéc nášich."),
("", "", "Probodénnym tvojím rébrom, kápľami Bohotóčnyja životvorjáščija króve Christé, smotríteľno kápľuščija na zémľu, súščich ot zemlí vozsozdál jesí, blahoslovén jesí, zovúščich, Bóže otéc nášich."),
("Tróičen", "", "Dúcha blaháho so Otcém proslávim, i s Sýnom jedinoródnym, jedíno v trijéch vírniji čtúšče načálo, i jedíno božestvó: blahoslovén jesí, zovúšče, Bóže otéc nášich."),
),
"2": (
("", "", "Hórdyj mučíteľ, no ďitéj býsť ihrálišče: jákože bo pérsť poprávše sedmeríčnyj plámeň, pojáchu: blahoslovén jesí Hóspodi, Bóže otéc nášich."),
("", "", "Ne prósta sólnce na kresťí vísjašča čelovíka, no Bóha voploščénna zrjá pomračájetsja. Jemúže i pojém: blahoslovén jesí Hóspodi, Bóže otéc nášich."),
("", "", "Krípkaho božestvóm prijém ád strašlívyj, netľínija podáteľa, dúšy právednych vopijúščyja izblevá: blahoslovén jesí Hóspodi, Bóže otéc nášich."),
("Bohoródičen", "", "Sokróvišče mnohocínnoje blahoslovénija javílasja jesí prečístaja, čístym sérdcem tebé ispovédajuščym Bohorodíteľnicu: Nébo iz tebé voplotísja Bóh otéc nášich."),
),
"3": (
("", "", "Hórdyj mučíteľ, no ďitéj býsť ihrálišče: jákože bo pérsť poprávše sedmeríčnyj plámeň, pojáchu: blahoslovén jesí Hóspodi, Bóže otéc nášich."),
("", "", "Íže slávy Hospóď, i deržáj hórnija síly, íže so Otcém siďáj, ďívstvennyma rukáma nosím: blahoslovén jesí Hóspodi, Bóže otéc nášich."),
("", "", "Jára smérť, no sijú tebí besídovavšuju pohubíl jesí, ot Ďívy Bohoipostásnaja plóť býv: blahoslovén jesí Hóspodi, Bóže otéc nášich."),
("", "", "Bohoródicu vsí ťa Bóha róždšuju uvíďichom, jedínaho bo ot Tróicy voplotívšahosja iz tebé rodilá jesí: blahoslovén prečístaja, plód tvojehó čréva."),
)
),
"P8": (
"1": (
("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojáše júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."),
("", "", "Razdrásja cerkóvnaja svítlosť, jehdá krest tvój vodruzísja na lóbňim, i tvár prekloňášesja stráchom, vospivájušči: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."),
("", "", "Voskrésl jesí Christé iz hróba, i pádšaho preľščénijem, drévom isprávil jesí božéstvennoju síloju, zovúšča i hlahóľušča: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."),
("Bohoródičen", "", "Chrám Bóžij javílasja jesí vmistílišče oduševlénnoje, i kovčéh: tvorcá bo čelovíkom, Bohorodíteľnice prečístaja, primiríla jesí, i dostójno vsjá ďilá pojém ťá, i prevoznósim vo vsjá víki."),
),
"2": (
("", "", "Veščéstvennaho ohňá plámeň neveščéstvennym uvjadíša, Bohozrímiji ótrocy, i pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda."),
("", "", "Slóvo nestrástnoje, bezstrástno úbo Božestvóm, stráždet že plótiju Bóh, jemúže i pojém: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."),
("", "", "Usnúvyj úbo jáko smérten, voskrésl jesí jáko bezsmérten Spáse, i spasáješi ot smérti pojúščich: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."),
("Tróičen", "", "Slúžim blahočéstno trijipostásnomu Božestvú, sojediňájemu neizrečénno, i pojém: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."),
),
"3": (
("", "", "Veščéstvennaho ohňá plámeň neveščéstvennym uvjadíša, Bohozrímiji ótrocy, i pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda."),
("", "", "Číny úmnyja jáko Máti prevozšlá jesí, i blíz Bóha bývši: blahoslovím blahoslovénnaja Ďívo, roždestvó tvojé, i prevoznósim vo vsjá víki."),
("", "", "Dobrótu jestéstvennuju, krasňíjšu pokazála jesí, oblistavájuščuju plóť Božestvá. Blahoslovím blahoslovénnaja Ďívo, roždestvó tvojé, i prevoznósim vo vsjá víki."),
)
),
"P9": (
"1": (
("", "", "Nóvoje čúdo i Bohoľípnoje, Ďívičeskuju bo dvér zatvorénuju jávi prochódit Hospóď, náh vo vchóďi, i plotonósec javísja vo ischóďi Bóh, i prebyvájet dvér zatvoréna: sijú neizrečénno, jáko Bohomáter veličájem."),
("", "", "Strášno jésť zríti tebé tvorcá na dreví vozdvížena Slóve Bóžij, plótski že stráždušča Bóha za rabý, i vo hróbi bezdychánna ležášča, mértvyja že iz áda razrišívša: ťímže ťá Christé, jáko vsesíľna veličájem."),
("", "", "Iz tlí smértnyja spásl jesí Christé práotcy, položén býv vo hróbi mértv, i živót procvíl jesí, mértvyja voskresív, rukovodív jestestvó čelovíčeskoje ko svítu, i v božéstvennoje oblék netľínije. ťímže istóčnika ťá svíta prísno živáho veličájem."),
("Bohoródičen", "", "Chrám i prestól javílasja jesí Bóžij, vóňže vselísja íže v výšnich sýj, roždéjsja neiskusomúžno vsečístaja, plóti tvojejá ne otvérz vsjáčeski vratá. Ťímže neprestánnymi čístaja molítvami tvojími, jazýki várvarskija skóro do koncá pokorí."),
),
"2": (
("", "", "Sládkoju prečístaho tvojehó roždestvá strilóju ujázvleni čístaja, tvojéj dostoželánňij dobróťi divjáščesja, písňmi ánheľskimi dostójno ťá, jáko Máter Bóžiju veličájem."),
("", "", "Čésť čelovíkom ot bezčéstnyja smérti vsím istočíl jesí: jejáže raspjátijem tvojím Spáse vkusív, suščestvóm smértnym netľínije mňí darovál jesí Christé, jáko čelovikoľúbec."),
("", "", "Spásl mjá jesí voskrés iz hróba Christé, voskrésl že jesí, i Otcú privél jesí tvojemú rodíteľu: odesnúju že jehó sposadíl jesí za blahoutróbije mílosti tvojejá Hóspodi."),
),
"3": (
("", "", "Sládkoju prečístaho tvojehó roždestvá strilóju ujázvleni čístaja, tvojéj dostoželánňij dobróťi divjáščesja, písňmi ánheľskimi dostójno ťá, jáko Máter Bóžiju veličájem."),
("", "", "Sýtosť tvojích pochvál Ďívo, blahočestívym vírnym otňúd ne byvájet: želánijem bo želánije prísno božéstvennoje, i duchóvnoje prijémľušče, jáko Máter Bóžiju veličájem."),
("", "", "Položíl jesí nám nepostýdnuju molítvennicu, tebé róždšuju Christé. Tojá moľbámi mílostiva podajéši nám Dúcha, podáteľa bláhosti, ot Otcá tobóju proischoďášča."),
)
),
),
"CH": (
("", "", "Prijidíte vsí jazýcy, urazumíjte strášnyja tájny sílu: Christós bo Spás náš, jéže v načáľi Slóvo, raspjátsja nás rádi, i vóleju pohrebésja, i voskrése iz mértvych, jéže spastí vsjáčeskaja: tomú poklonímsja."),
("", "", "Povídaša vsjá čudesá strážije tvojí Hóspodi: no sobór sujetý ispólni mzdóju desnícu ích, skrýti mňáše voskresénije tvojé, jéže mír slávit: pomíluj nás."),
("", "", "Rádosti vsjá ispólnišasja voskresénija iskús prijímša: Maríja bo Mahdalína ko hróbu priíde, obríte ánhela na kámeni siďášča, rízami blistájuščasja i hlahóľušča: čtó íščete živáho s mértvymi: ňísť zďí, no vostá, jákože rečé, predvarjája vý v Haliléji."),
("", "", "Vo svíťi tvojém Vladýko, úzrim svít čelovikoľúbče: voskrésl bo jesí iz mértvych, spasénije ródu čelovíčeskomu dáruja: da ťá vsjá tvár slavoslóvit jedínaho bezhríšnaho, pomíluj nás."),
("", "", "Písň útrenňuju mironósicy žený so slezámi prinošáchu tebí Hóspodi, blahouchánija bo aromáty imúščja, hróba tvojehó dostihóša, prečístoje ťílo tvojé pomázati tščáščjasja. Ánhel siďáj na kámeni ťím blahovistí: čtó íščete živáho s mértvymi? Smérť bo popráv voskrése jáko Bóh, podajá vsím véliju mílosť."),
("", "", "Blistájasja ánhel na hróbi tvojém životvórňim, mironósicam hlahólaše: istoščív hróby izbáviteľ pľiní áda, i voskrése tridnéven, jáko jedín Bóh i vsesílen."),
("", "", "Vo hróbi ťá iskáše, prišédši vo jedínu ot subbót <NAME>na, ne obrítši že rydáše s pláčem vopijúšči: uvý mňí Spáse mój! Ukráden býl jesí vsích carjú. Suprúh že živonósnych ánhel vnútr hróba vopijáše: čtó pláčeši o žéno? Pláču, hlahólet, jáko vzjáša Hóspoda mojehó ot hróba, i ne vím hďí položíša jehó. Sijá že obráščšisja vspjáť, jáko víďi ťá, ábije vozopí: Hospóď mój i Bóh mój, sláva tebí."),
("", "", "Jevréi zatvoríša vo hróbi živót, razbójnik že otvérze jazýkom naslaždénije, zovýj i hlahóľa: íže so mnóju mené rádi raspnýjsja: soobísi mi sja na drévi, i javísja mňí na prestóľi so Otcém siďá: tój bo jésť Christós Bóh náš, imíjaj véliju mílosť."),
)
)
#let L = (
"B": (
("", "", "Otvérhša Christé zápoviď tvojú, práotca Adáma iz rajá izhnál jesí: razbójnika že ščédre ispovídavša ťá na kresťí, vóň vselíl jesí, zovúšča: pomjaní mja Spáse, vo cárstviji tvojém."),
("", "", "Sohríššich nás smértnoju osudíl jesí kľátvoju, živodávče i Hóspodi, ťílom že tvojím bezhríšne Vladýko postradáv, smértnyja oživíl jesí zovúščyja: pomjaní i nás vo cárstviji tvojém."),
("", "", "Voskrés iz mértvych, sovoskrésíl jesí nás ot strastéj voskresénijem tvojím Hóspodi: smértnuju že vsjú sílu pohubíl jesí Spáse. Sehó rádi víroju tí zovém: pomjaní i nás vo cárstviji tvojém."),
("", "", "Tridnévnym tvojím pohrebénijem, íže vo áďi umerščvlénnyja jáko Bóh oživotvorívyj, sovozdvíhl jesí, i netľínije vsím jáko bláh istočíl jesí nám, víroju zovúščym vsehdá: pomjaní i nás vo cárstviji tvojém."),
("", "", "Mironósicam ženám pérvije javílsja jesí, voskrés iz mértvych, Spáse vozopív: jéže rádujtesja, i ťími druhóm tvojím vozviščáješi vostánije tvojé Christé, sehó rádi víroju tí zovém: pomjaní i nás vo cárstviji tvojém."),
("", "", "Na horí Moiséj rúci rasprostér, proobrazovánije krest, Amalíka pobidívyj: mý že víroju tohó na bísy orúžije krípkoje prijémše, vsí zovém: pomjaní i nás vo cárstviji tvojém."),
("", "", "Otcá i Sýna, i Dúcha svjatáho vospojím vírniji, jedínaho Bóha, jedínaho Hóspoda, jáko ot jedínaho bo sólnca trisijánnaho jésť Tróicai prosviščájet vsjá zovúščyja: pomjaní i nás vo cárstviji tvojém."),
("Bohoródičen", "", "Rádujsja dvére Bóžija, jéjuže prójde voplóščsja sozdáteľ, zapečátanu sochranív ťá. Rádujsja óblače léhkij, božéstvennyj dóžď nosjáj Christá, rádujsja ľístvice i prestóle nebésnyj. Rádujsja horó Bóžija čestnája, túčnaja, nesikómaja."),
),
"TKB": (
("", "", "Da veseľátsja nebésnaja, da rádujutsja zemnája: jáko sotvorí deržávu mýšceju svojéju Hospóď, poprá smértiju smérť, pérvenec mértvych býsť, iz čréva ádova izbávi nás, i podadé mírovi véliju mílosť."),
("", "Ďíva dnés", "Voskrésl jesí dnés iz hróba ščédre, i nás vozvél jesí ot vrát smértnych: dnés Adám likújet, i rádujetsja Jéva, vkúpi že i prorócy s patrijárchi vospivájut neprestánno božéstvennuju deržávu vlásti tvojejá."),
("Bohoródičen", "", "Ťá chodátajstvovavšuju spasénije róda nášeho, vospivájem Bohoródice Ďívo: plótiju bo ot tebé vosprijátoju Sýn tvój, i Bóh náš, krestóm vospriím strásť, izbávi nás ot tlí jáko čelovikoľúbec."),
),
"P": (
("", "", "Pójte Bóhu nášemu, pójte, pójte cárévi nášemu, pójte."),
("", "", "Vsí jazýcy vospleščíte rukámi, vosklíknite Bóhu hlásom rádovanija."),
("", "", "Na ťá Hóspodi upovách, da ne postyžúsja vo vík."),
("", "", "Búdi mí v Bóha zaščítiteľa, i v dóm pribížišča, jéže spastí mja."),
)
) |
|
https://github.com/metamuffin/typst | https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/compiler/import.typ | typst | Apache License 2.0 | // Test function and module imports.
// Ref: false
---
// Test basic syntax and semantics.
// Ref: true
// Test that this will be overwritten.
#let value = [foo]
// Import multiple things.
#import "module.typ": fn, value
#fn[Like and Subscribe!]
#value
// Should output `bye`.
// Stop at semicolon.
#import "module.typ": a, c;bye
---
// An item import.
#import "module.typ": item
#test(item(1, 2), 3)
// Code mode
{
import "module.typ": b
test(b, 1)
}
// A wildcard import.
#import "module.typ": *
// It exists now!
#test(d, 3)
---
// Test importing from function scopes.
// Ref: true
#import enum: item
#import assert.with(true): *
#enum(
item(1)[First],
item(5)[Fifth]
)
#eq(10, 10)
#ne(5, 6)
---
// A module import without items.
#import "module.typ"
#test(module.b, 1)
#test(module.item(1, 2), 3)
#test(module.push(2), 3)
---
// Edge case for module access that isn't fixed.
#import "module.typ"
// Works because the method name isn't categorized as mutating.
#test((module,).at(0).item(1, 2), 3)
// Doesn't work because of mutating name.
// Error: 2-11 cannot mutate a temporary value
#(module,).at(0).push()
---
// Who needs whitespace anyways?
#import"module.typ":*
// Allow the trailing comma.
#import "module.typ": a, c,
---
// Usual importing syntax also works for function scopes
#import enum
#let d = (e: enum)
#import d.e
#import d.e: item
#item(2)[a]
---
// Can't import from closures.
#let f(x) = x
// Error: 9-10 cannot import from user-defined functions
#import f: x
---
// Can't import from closures, despite modifiers.
#let f(x) = x
// Error: 9-18 cannot import from user-defined functions
#import f.with(5): x
---
// Error: 9-18 cannot import from user-defined functions
#import () => {5}: x
---
// Error: 9-10 expected path, module or function, found integer
#import 5: something
---
// Error: 9-11 failed to load file (is a directory)
#import "": name
---
// Error: 9-20 file not found (searched at typ/compiler/lib/0.2.1)
#import "lib/0.2.1"
---
// Some non-text stuff.
// Error: 9-21 file is not valid utf-8
#import "/rhino.png"
---
// Unresolved import.
// Error: 23-35 unresolved import
#import "module.typ": non_existing
---
// Cyclic import of this very file.
// Error: 9-23 cyclic import
#import "./import.typ"
---
// Cyclic import in other file.
#import "./modules/cycle1.typ": *
This is never reached.
---
// Error: 8 expected expression
#import
---
// Error: 26-29 unexpected string
#import "module.typ": a, "b", c
---
// Error: 23-24 unexpected equals sign
#import "module.typ": =
---
// An additional trailing comma.
// Error: 31-32 unexpected comma
#import "module.typ": a, b, c,,
---
// Error: 2:2 expected semicolon or line break
#import "module.typ
"stuff
---
// A star in the list.
// Error: 26-27 unexpected star
#import "module.typ": a, *, b
---
// An item after a star.
// Error: 24 expected semicolon or line break
#import "module.typ": *, a
---
// Error: 14-15 unexpected colon
// Error: 16-17 unexpected integer
#import "": a: 1
---
// Error: 14 expected comma
#import "": a b
|
https://github.com/sahasatvik/typst-theorems | https://raw.githubusercontent.com/sahasatvik/typst-theorems/main/README.md | markdown | MIT License | # typst-theorems
An implementation of numbered theorem environments in
[typst](https://github.com/typst/typst).
Available as [ctheorems](https://typst.app/universe/package/ctheorems) in the
official Typst Universe.
Import with
```typst
#import "@preview/ctheorems:1.1.3": *
#show: thmrules
```
Alternatively, copy and import the [theorems.typ](theorems.typ) file to use in
your own projects.
### Features
- Numbered theorem environments can be created and customized.
- Environments can share the same counter, via same `identifier`s.
- Environment counters can be _attached_ (just as subheadings are attached to headings) to other environments, headings, or keep a global count via `base`.
- The depth of a counter can be manually set, via `base_level`.
- Environments can be `<label>`'d and `@reference`'d.
## Manual and Examples
Get acquainted with `typst-theorems` by checking out the minimal example below!
You can read the [manual](manual.pdf) for a full walkthrough of functionality offered by this module; flick through [manual_examples](manual_examples.pdf) and its [typ file](manual_examples.typ) to just see the examples.
The [differential_calculus.typ](differential_calculus.typ) ([render](differential_calculus.pdf)) project provides a practical use case. _(Hastily translated from my notes written in LaTeX)_

### Preamble
```typst
#import "theorems.typ": *
#show: thmrules.with(qed-symbol: $square$)
#set page(width: 16cm, height: auto, margin: 1.5cm)
#set text(font: "Libertinus Serif", lang: "en")
#set heading(numbering: "1.1.")
#let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee"))
#let corollary = thmplain(
"corollary",
"Corollary",
base: "theorem",
titlefmt: strong
)
#let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em))
#let example = thmplain("example", "Example").with(numbering: none)
#let proof = thmproof("proof", "Proof")
```
### Document
```typst
= Prime numbers
#definition[
A natural number is called a #highlight[_prime number_] if it is greater
than 1 and cannot be written as the product of two smaller natural numbers.
]
#example[
The numbers $2$, $3$, and $17$ are prime.
@cor_largest_prime shows that this list is not exhaustive!
]
#theorem("Euclid")[
There are infinitely many primes.
]
#proof[
Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration
of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list,
it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since
$p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a
contradiction.
]
#corollary[
There is no largest prime number.
] <cor_largest_prime>
#corollary[
There are infinitely many composite numbers.
]
#theorem[
There are arbitrarily long stretches of composite numbers.
]
#proof[
For any $n > 2$, consider $
n! + 2, quad n! + 3, quad ..., quad n! + n #qedhere
$
]
```
## Acknowledgements
Thanks to
- [MJHutchinson](https://github.com/MJHutchinson) for suggesting and
implementing the `base_level` and `base: none` features,
- [rmolinari](https://github.com/rmolinari) for suggesting and
implementing the `separator: ...` feature,
- [DVDTSB](https://github.com/DVDTSB) for contributing
- the idea of passing named arguments from the theorem directly to the `fmt`
function.
- the `number: ...` override feature.
- the `title: ...` override feature in `thmbox`.
- [PgBiel](https://github.com/PgBiel) for fixing breaking changes in version
updates.
- The awesome devs of [typst.app](https://typst.app/) for their
support.
|
https://github.com/naps62/presentation-rust | https://raw.githubusercontent.com/naps62/presentation-rust/main/theme.typ | typst | #import "@preview/polylux:0.3.1": *
#import themes.simple: *
#let dark = rgb("#212121")
#let darkbg = rgb("#6b1d09")
#let light = white
#let focus-slide(body) = {
themes.simple.focus-slide(background: darkbg, foreground: light, body)
}
#let horizon-slide(body) = {
logic.polylux-slide(align(horizon, body))
}
#let oneliner-slide(size: 3em, body) = {
set text(size: size)
logic.polylux-slide(align(center + horizon, body))
}
|
|
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/pages/contents.typ | typst | The Unlicense | #import "/src/contents.typ": needle
#let contents() = {
pagebreak(weak: true, to: "odd")
v(1cm)
text(size: 22pt)[Contents]
parbreak()
context {
let results = query(needle).fold((:), (acc, it)=>{
acc.insert(it.value.scope, acc.at(it.value.scope, default: ()) + (it,))
return acc
})
grid(
columns: (1fr, auto),
align: (left + bottom, right + bottom),
column-gutter: 0.5em,
row-gutter: 1.75em,
..(for (part, entries) in results {
(
strong(part),
strong(
numbering(
entries.first().location().page-numbering(),
..counter(page).at(entries.first().location())
)
)
)
if entries.len() > 1 {
for entry in entries {
(
grid.cell(
inset: (left: 1em),
{
entry.value.body
h(0.75em)
box(repeat[.], width: 1fr)
}
),
numbering(
entry.location().page-numbering(),
..counter(page).at(entry.location())
),
)
}
}
})
)
}
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/supercharged-dhbw/1.0.0/acronyms-list.typ | typst | Apache License 2.0 | // https://github.com/typst/typst/issues/659
#import "template/acronyms.typ": acronyms
// The state which tracks the used acronyms
#let usedAcronyms = state("usedDic", (:))
#let acronyms-list() = {
v(2em)
heading(level: 1, numbering: none, "Acronyms")
locate(loc => usedAcronyms.final(loc)
.pairs()
.filter(x => x.last())
.map(pair => pair.first())
.sorted()
.map(key => grid(
columns: (1fr, 1fr),
gutter: 1em,
strong(key),acronyms.at(key)
)).join())
}
// The function which either shows the acronym or the full text for it
#let acro(body) = {
if(acronyms.keys().contains(body) == false) {
return rect(
fill: red,
inset: 8pt,
radius: 4pt,
[*Warning:\ #body*],
)
}
usedAcronyms.display(usedDic => {
if(usedDic.keys().contains(body)) {
return body
}
return acronyms.at(body) + " (" + body + ")"
});
usedAcronyms.update(usedDic => {
usedDic.insert(body, true)
return usedDic
})
} |
https://github.com/mitsuyukiLab/grad_thesis_typst | https://raw.githubusercontent.com/mitsuyukiLab/grad_thesis_typst/main/contents/proposed_method.typ | typst | = 提案手法 <proposed_method>
== 概要 <overview_of_proposed_method>
== 手法1 <method1>
== 手法2 <method2>
== 開発したシステム <developed_system>
|
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/linear/format.typ | typst | The Unlicense | #import "entry-types.typ": *
/// Formats the border lines
///
/// Example Usage:
///
/// ```typ
/// #set-border()
/// ```
#let set-border(type) = {
let top-axis = -8.4% // The title line height
let bottom-axis = 100% // The automatic bottom border
// Adjusts top and bottom borders for frontmatter and appendix entries
if (type == none) {
top-axis = -6.6%
bottom-axis = 106%
}
let left-axis = -8% // 8% less than the automatic left border (0%)
let right-axis = 108% // 8% more than the automatic right border (100%)
set line(stroke: 1.5pt)
// Top left border
place(line(start: (left-axis, top-axis), end: (0%, top-axis)))
// Top right border
place(line(start: (right-axis, top-axis), end: (100%, top-axis)))
// Left border
place(line(start: (left-axis, top-axis), end: (left-axis, bottom-axis)))
// Right border
place(line(start: (right-axis, top-axis), end: (right-axis, bottom-axis)))
// Bottom border
place(line(start: (left-axis, bottom-axis), end: (right-axis, bottom-axis)))
}
#let set-heading(it, type) = {
show: block
let color = entry-type-metadata.at(type)
if it.level == 1 {
set text(18pt)
}
if it.level == 2 {
set text(15pt)
}
if it.level == 3 {
set text(13pt)
} else {
set text(11pt)
}
set text(weight: "semibold")
box(inset: 0.5em, fill: color)[#it.body]
h(5pt)
box(baseline: -10pt, width: 1fr, line(length: 100%))
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-00.typ | typst | Other | _Shopping list_
#list[Apples][Potatoes][Juice]
|
https://github.com/matthiasGmayer/typst-math-template | https://raw.githubusercontent.com/matthiasGmayer/typst-math-template/main/manage.typ | typst | #let is_main_document = state("is_main_document",false) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/frac_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test large fraction.
$ x = (-b plus.minus sqrt(b^2 - 4a c))/(2a) $
|
https://github.com/SE-legacy/physics_lectures_3_term | https://raw.githubusercontent.com/SE-legacy/physics_lectures_3_term/main/lesson_3/main.typ | typst | #import "conf.typ": conf
#show: conf.with(
meta: (
title: "Физика. Занятие №3, 23.09.2024",
author: "<NAME>., <NAME>. Чернышевского",
group: 251,
city: "Саратов",
year: 2024,
)
)
= Проводники в электростатическом поле
$C = q(t)/phi_1 - phi_2 = q/U = (sigma S) / (E d) = (sigma S epsilon_0) / (sigma d) = (S epsilon_0) / d$
$phi = phi_1 - phi_2 = q / epsilon (1 / R_1 - 1 / R_2)$
$C = epsilon/(1 / R_1 - 1 / R_2) = epsilon (R_1 R_2) / (R_2 - R_1)$
$C = (epsilon l) / (2 ln(b / a))$
#image("images/1.jpg")
При параллельном соединении разности потенциалов между обкладками обоих конденсаторов одинаковы, заряды обкладок складываются: $q = q_1 + q_2$, емкость батареи: $C = C_1 + C_2$
$C = sum_(i=1)^n C_i$
При последовательном соединении средние пластины, соединенные между собой, электризуются через влияние, а потому их заряды равны и противоположны по знаку, емкость батареи:
$1/C = 1/C_1 + 1/C_2$ $C = (C_1 C_2) / (C_1 + C_2)$
$1/C = sum_(i=1)^n 1/C_i$
#image("images/2.jpg")
$d A = U d q$ $U = q_C$ => $d A = (q d q) / C$
*$W = q^2/(2 C) = (C U^2)/2 = (q U) / 2$*
Обобщим полученный результат на любые поля. Возьмем плоский конденсатор
$C = (epsilon epsilon_0 S) / d $ => $U = e d$
$d W = omega d V$, $W = integral_V omega d V$, $W = integral_V omega(x, y, z) d x d y d z$
$omega = (C (E d)^2) / (2 S d) = (epsilon epsilon_0 S (E d)^2) / (d 2 S d)$ => $omega = (epsilon epsilon_0 E^2) / 2 = (E D) / 2$
= Диэлектрики в электростатическом поле
#image("images/3.jpg")
*Полярные диэлектрики* (к ним относятся $H_2 O$, $C O$, $N H$, ) --- это диэоектрики, молекулы которых имеют асиметричное строение, т.е. центры тяжести положительных и отрицательных зарядов не совпадают. Таким образом, этим полекулы в отсутствие внешнего электрического поля представляют собой дипль.
Неполярные диэлектрики ($H_2$, $O_2$, $N_2$) --- это диэлектрики, молекулы которых имеют симметричное строение.
Ионные диэлектрики (вещества с кристаллической структурой, (Na Cl, K Cl, K Br) --- это диэлектрики, молекулы которых имеют ионное строение. Диэлектрик представляет собой ионную кристаллическую решетку с чередованием ионов разных знаков, т.е. диэлектрик можно рассматривать как две подрешетки противоположных зарядов вдвинутых одна в другую.
Смещение электрических зарядов вещества под действием электрического поля называется поляризацией.
Степень поляризации диэлектрика характеризуется величиной, называемой вектором поляризации (или поляризованностью). Вектор поляризации определяется как суммарный дипольный момент единицы объема диэлектрика и равен
$overline(P) = p_V / V = (sum_i overline(p_(l i))) / V$ [(Кл м)/м^3 = Кл / м^2]
$overline(p_l) = beta epsilon_0 E$
Для неполярного диэлектрика --- линейная зависимость (1). Для полярного диэлектрика --- логарифмическая зависимость (2).
#image("images/4.jpg")
При определенной величине $E$ достигается такое состояние, когда дипольные моменты всех молекул направлены по полю, т.е. наступает насыщение и модуль вектора поляризации достигает $P_("нас")$
*Связь между вектором P и $sigma$*
Объём цилиндра: $Delta V = Delta S_("перп") dot l = Delta S dot l cos(alpha)$
Цилиндр --- макродиполь. Электрический дипольный момент:
$p_1 = q l = sigma' dot Delta S dot l$
Поляризованность: $P = p_l / (Delta V)$
$p_1 = P dot Delta V = P dot Delta S dot l cos(alpha)$
$P cos(alpha) = sigma'$
$P_n$ --- проекция вектора поляризованности на внешнюю нормаль к поверхности диэлектрика.
$P_n$ --- численно равна электрическому заряду, смещаемому через единичную площадку в направлении положительной нормали к ней.
$P_n = sigma' = kappa epsilon_0 E$
#image("images/5.jpg")
По принципу суперпозиции $E = E_0 - E'$
Поле, образованное связанными зарядами E' = sigma' / epsilon_0
1) $E = E_0 - sigma'/epsilon_0$
2) $overline(P) = kappa epsilon_0 overline(E)$
3) $P = sigma'$
Из 1-3 следует:
$E = E_0 - (kappa epsilon_0 E) / epsilon_0$
1) $E_0 = (1 + kappa) E$
2) $epsilon = 1 + kappa$
Из 1,2 следует:
$epsilon = E_0 / E$
#underline[Физический смысл диэлектрической проницаемости] заключается в том, что она показывает во сколько раз ослабляется поле внутри диэлектрика
По теореме О.-Г: $#sym.integral.cont overline(E) d overline(S) = (q_("своб") + q_("пол")) / epsilon_0$
$#sym.integral.cont overline(D) d overline(S) = integral_V div overline(D) d V = integral_v rho d V$ => $div overline(D) = rho$
= Полупроводники в электростатическом поле
#image("images/6.jpg")
- Атомы кристаллических полупроводников связаны ковалентными связями, при которых валентные электроны становятся общими для соседних атомов
- При температурах близких к абсолютному нулю в п/п нет свободных электронов
- При возрастании температуры энергия (всех) электронов растет. Валентные электроны могут покинуть атом, в результате растет число свободных электронов и их энергия
- Априори можно утверждать, что главным свойством полупроводников является уменьшение ширины запрещенной зоны
Среднее значение энергии теплового движения электронов при комнатной температуре составляет примерно 0,04 эВ.
При T = 0 в зоне проводимости электронов нет, в валентной зоне все состояния заняты и наш кристалл будет демонстрировать чисто диэлектрические свойства.
При конечной температуре возникнет некоторое количество электронов и дырок, причем в силу общей электронейтральности и их концентрации совпадают $n_e = n_h$. Эти термоактивированные носители заряда называют также собственными носителями заряда, а о таком полупроводнике говорят как о полупроводнике с собственной проводимостью.
Электроны и дырки являются фермионами, для них применимо распределение Ферми-Дирака. Поэтому концентрации электронов и дырок равны
$n_(e, h) = 2 integral n (epsilon_(e, h)) (d^3 overline(q_(e, h))) / (2 pi)^3$
$n(epsilon_(e, h)) = 1 / (exp((epsilon_(e, h)) #sym.plus.minus mu) l T) + 1$
$n_e = 2 ((m_e T) / (2 pi h^2))^(3/2) e^(-(E_g - mu) / T)$
$n_h = 2 ((m_h T) / (2 pi h^2))^(3/2) e^(-mu / T)$
Собственная проводимость полупроводника пропорциональная числу носителей заряда, зависит от температуры по закону:
$sigma = sigma_c e^(-(W_g) / (2 k_B T))$
#image("images/7.jpg")
#image("images/8.jpg")
#image("images/9.jpg")
Уровень Ферми твердого тела --- это термодинамическая работа, необходимая для добавления одного электрона к телу.
= Основная задача электростатики
Нахождение решения дифференциальных уравнений Пуассона и Лапласа
$(dif^2 phi) / (dif x^2) + (dif^2 phi) / (dif y^2) + (dif^2 phi) / (dif z^2) = - rho/epsilon_0$
Уравнение Пуассона описывает распределение потенциалов в пространстве, если электрическое поле создано системой проводников и в пространстве между проводниками имеются свободные заряды.
$(dif^2 phi) / (dif x^2) + (dif^2 phi) / (dif y^2) + (dif^2 phi) / (dif z^2) = 0$
Уравнение Лапласа описывает распределение потенциалов в пространстве, если электрическое поле создано системой проводников и в пространстве между проводниками нет свободных зарядов.
= Постоянный электрический ток
*Электрический ток* --- упорядоченное движение электрических зарядов.
*Ток проводимости* (ток в проводниках) --- движение микрозарядов в макротеле.
*Конвекционный ток* --- движение макроскопических заряженных тел в пространстве
*Ток в вакууме* --- движение микрозарядов в вакууме.
*Наведенный ток* --- это механизм преобразования энергии источника в энергию токов или электромагнитных колебаний во внешней цепи.
#image("images/10.jpg")
Пусть заряд $q$ от некоторого источника влетает в пространство, ограниченное двумя металлическими поверхностями (сетками).
Известно, что заряд наводит на металлической поверхности заряды противопололожного знака. Поле двойного заряженного слоя $E_1 > E_2 -> phi_1 > phi_2$
Тогда во внешней цепи возникает разность потенциалов, следовательно, ток, называемый наведенным.
*Условия возникновения тока:*
+ Нужны носители тока, то есть заряды (свободные или почти свободные)
+ В проводниках первого рода --- свободные электроны
+ В полупроводниках --- электроны и "дырки" (валентные электроны)
+ В электролитах --- Ионные
+ В плазме --- свободные электроны и положительные ионы
+ Надо нарушить равновесие заряда в проводящей среде, т.е. необходимо наличие в среде электрического поля, энергия которого затрачивалась бы на перемещение электрических зарядов. |
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/tutorial/functions.md | markdown | MIT License | # Functions
## Functions
```typ
Okay, let's now move to more complex things.
First of all, there are *lots of magic* in Typst.
And it major part of it is called "scripting".
To go to scripting mode, type `#` and *some function name*
after that. We will start with _something dull_:
#lorem(50)
_That *function* just generated 50 "Lorem Ipsum" words!_
```
## More functions
```typ
#underline[functions can do everything!]
#text(orange)[L]ike #text(size: 0.8em)[Really] #sub[E]verything!
#figure(
caption: [
This is a screenshot from one of first theses written in Typst. \
_All these things are written with #text(blue)[custom functions] too._
],
image("../boxes.png", width: 80%)
)
In fact, you can #strong[forget] about markup
and #emph[just write] functions everywhere!
#list[
All that markup is just a #emph[syntax sugar] over functions!
]
```
## How to call functions
```typ
First, start with `#`. Then write the name.
Finally, write some parentheses and maybe something inside.
You can navigate lots of built-in functions
in #link("https://typst.app/docs/reference/")[Official Reference].
#quote(block: true, attribution: "Typst Examples Book")[
That's right, links, quotes and lots of
other document elements are created with functions.
]
```
## Function arguments
```typ
There are _two types_ of function arguments:
+ *Positional.* Like `50` in `lorem(50)`.
Just write them in parentheses and it will be okay.
If you have many, use commas.
+ *Named.* Like in `#quote(attribution: "Whoever")`.
Write the value after a name and a colon.
If argument is named, it has some _default value_.
To find out what it is, see
#link("https://typst.app/docs/reference/")[Official Typst Reference].
```
## Content
```typ
The most "universal" type in Typst language is *content*.
Everything you write in the document becomes content.
#[
But you can explicitly create it with
_scripting mode_ and *square brackets*.
There, in square brackets, you can use any markup
functions or whatever you want.
]
```
## Markup and code modes
```typ
When you use `#`, you are "switching" to code mode.
When you use `[]`, you turn back:
// +-- going from markup (the default mode) to scripting for that function
// | +-- scripting mode: calling `text`, the last argument is markup
// | first arg |
// v vvvvvvvvv vvvv
#rect(width: 5cm, text(red)[hello *world*])
// ^^^^ ^^^^^^^^^^^^^ just a markup argument for `text`
// |
// +-- calling `rect` in scripting mode, with two arguments: width and other content
```
## Passing content into functions
```typ
So what are these square brackets after functions?
If you *write content right after
function, it will be passed as positional argument there*.
#quote(block: true)[
So #text(red)[_that_] allows me to write
_literally anything in things
I pass to #underline[functions]!_
]
```
## Passing content, part II
`````typ
So, just to make it clear, when I write
```typ
- #text(red)[red text]
- #text([red text], red)
- #text("red text", red)
// ^ ^
// Quotes there mean a plain string, not a content!
// This is just text.
```
It all will result in a #text([red text], red).
`````
|
https://github.com/stephane-klein/asdf-typst | https://raw.githubusercontent.com/stephane-klein/asdf-typst/main/README.md | markdown | MIT License | <div align="center">
# asdf-typst [](https://github.com/stephane-klein/asdf-typst/actions/workflows/build.yml)
[typst](https://github.com/typst/typst) plugin for the [asdf version manager](https://asdf-vm.com).
</div>
# Contents
- [Dependencies](#dependencies)
- [Install](#install)
- [Contributing](#contributing)
- [License](#license)
# Dependencies
- `bash`, `curl`, `tar`, [`xz`](https://en.wikipedia.org/wiki/XZ_Utils), and [POSIX utilities](https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html).
# Install
Plugin:
```shell
asdf plugin add typst
# or
asdf plugin add typst https://github.com/stephane-klein/asdf-typst.git
```
typst:
```shell
# Show all installable versions
asdf list-all typst
# Install specific version
asdf install typst latest
# Set a version globally (on your ~/.tool-versions file)
asdf global typst latest
# Now typst commands are available
typst --help
```
Check [asdf](https://github.com/asdf-vm/asdf) readme for more instructions on how to
install & manage versions.
# Contributing
Contributions of any kind welcome! See the [contributing guide](contributing.md).
[Thanks goes to these contributors](https://github.com/stephane-klein/asdf-typst/graphs/contributors)!
# License
See [LICENSE](LICENSE) © [<NAME>](https://github.com/stephane-klein/)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/math-realize_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#let my = $pi$
#let f1 = box(baseline: 10pt, [f])
#let f2 = style(sty => f1)
#show math.vec: [nope]
$ pi a $
$ my a $
$ 1 + sqrt(x/2) + sqrt(#hide($x/2$)) $
$ a x #link("url", $+ b$) $
$ f f1 f2 $
$ vec(1,2) * 2 $
|
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-算法/二分查找/寻找旋转排序数组中的最小值.typ | typst | #import "../../../../lib.typ":*
=== #Title(
title: [寻找旋转排序数组中的最小值],
reflink: "https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array/description/",
level: 2,
)<寻找旋转排序数组中的最小值>
#note(
title: [
寻找旋转排序数组中的最小值
],
description: [
已知一个长度为 n 的数组,预先按照升序排列,经由 1 到 n 次旋转后,得到输入数组。例如,原数组` nums = [0,1,2,4,5,6,7] `在变化后可能得到:
- 若旋转 4 次,则可以得到` [4,5,6,7,0,1,2]`
- 若旋转 7 次,则可以得到` [0,1,2,4,5,6,7]`
注意,数组`[a[0], a[1], a[2], ..., a[n-1]]`旋转一次的结果为数组`[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`。
给你一个元素值互不相同的数组 `nums` ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的最小元素。
你必须设计一个时间复杂度为 O (log n) 的算法解决此问题。
],
examples: ([
> 输入:nums =` [3,4,5,1,2]`
> 输出:1
> 解释:原数组为 `[1,2,3,4,5]` ,旋转 3 次得到输入数组。
],[
> 输入:nums =` [4,5,6,7,0,1,2]`
> 输出:0
> 解释:原数组为` [0,1,2,4,5,6,7] `,旋转 3 次得到输入数组。
],[
> 输入:nums = `[11,13,15,17]`
> 输出:11
> 解释:原数组为` [11,13,15,17]` ,旋转 4 次得到输入数组。
]
),
tips: [
- N = nums.Length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- `Nums` 中的所有整数互不相同
- `Nums` 原来是一个升序排序的数组,并进行了 1 至 n 次旋转
],
solutions: (
( name:[二分查找],
text:[
一个不包含重复元素的升序数组在经过旋转之后,可以得到下面可视化的折线图:
#image("img/solution1.png")
其中横轴表示数组元素的下标,纵轴表示数组元素的值。图中标出了最小值的位置,是我们需要查找的目标。
我们考虑数组中的最后一个元素 x:在最小值右侧的元素(不包括最后一个元素本身),它们的值一定都严格小于 x;而在最小值左侧的元素,它们的值一定都严格大于 x。因此,我们可以根据这一条性质,通过二分查找的方法找出最小值。
在二分查找的每一步中,左边界为 low,右边界为 high,区间的中点为 pivot,最小值就在该区间内。我们将中轴元素 `nums[pivot]` 与右边界元素 `nums[high]` 进行比较,可能会有以下的三种情况:
第一种情况是 `nums[pivot]` < `nums[high]`。如下图所示,这说明 `nums[pivot]` 是最小值右侧的元素,因此我们可以忽略二分查找区间的右半部分。
#image("img/case1.png")
第二种情况是 `nums[pivot]` > `nums[high]`。如下图所示,这说明 `nums[pivot]` 是最小值左侧的元素,因此我们可以忽略二分查找区间的左半部分。
#image("img/case2.png")
由于数组不包含重复元素,并且只要当前的区间长度不为 1,pivot 就不会与 high 重合;而如果当前的区间长度为 1,这说明我们已经可以结束二分查找了。因此不会存在 `nums[pivot]` = `nums[high]` 的情况。
当二分查找结束时,我们就得到了最小值所在的位置。
],code:[
```cpp
class Solution {
public:
int findMin(vector<int>& nums) {
int low = 0;
int high = nums.size() - 1;
while (low < high) {
int pivot = low + (high - low) / 2;
if (nums[pivot] < nums[high]) {
high = pivot;
}
else {
low = pivot + 1;
}
}
return nums[low];
}
};
```
]),
),
gain:none,
) |
|
https://github.com/tani/gitpod-typst | https://raw.githubusercontent.com/tani/gitpod-typst/main/slide.typ | typst | #import "@preview/touying:0.5.2": *
#import themes.stargazer: *
#import "@preview/tiaoma:0.2.0": *
#import "@preview/numbly:0.1.0": numbly
#show: stargazer-theme.with(
aspect-ratio: "16-9",
config-info(
title: [Lorem Ipsum],
subtitle: [dolor sit amet, consectetur adipiscing elit],
author: [sed do eiusmod],
date: datetime.today(),
institution: [tempor incididunt ut labore]
),
)
// For Japanese
// #set text(font: "Noto Serif CJK JP", lang: "ja")
#show regex("[\p{scx:Han}\p{scx:Hira}\p{scx:Kana}]"): set text(font: "Noto Serif CJK JP", lang: "ja")
#set heading(numbering: numbly("{1}.", default: "1.1"))
#title-slide()
#outline-slide()
= Section A
== Subsection A.1
#slide[
#set align(center)
This slide is available at \
`https://github.com/tani/gitpod-typst`
#qrcode(
"https://github.com/tani/gitpod-typst",
options: (scale: 4.0)
)
]
#slide[
A slide with equation:
$ x_(n+1) = (x_n + a/x_n) / 2 $
]
== Subsection A.2
#slide[
A slide without a title but with *important* infos
]
= Section B
== Subsection B.1
#slide[
#lorem(80)
]
#focus-slide[
Wake up!
]
== Subsection B.2
#slide[
We can use `#pause` to #pause display something later.
#pause
Just like this.
#meanwhile
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
] |
|
https://github.com/Mc-Zen/tidy | https://raw.githubusercontent.com/Mc-Zen/tidy/main/examples/sincx.typ | typst | MIT License | /// This function computes the cardinal sine, $sinc(x)=sin(x)/x$.
///
/// #example(`#sinc(0)`, mode: "markup")
///
/// - x (int, float): The argument for the cardinal sine function.
/// -> float
#let sinc(x) = if x == 0 {1} else {calc.sin(x) / x} |
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/content/version_table.typ | typst | MIT No Attribution | #import "../helper/version.typ": *
#let versionTable(headingName, versions) = [
#if versions.len() > 0 [
#strong(headingName)
#let version = "0.0"
#table(
fill: (col, row) => if row == 0 { luma(240) },
columns: (0.56fr, 1.05fr, 0.7fr, 1.5fr),
inset: 10pt,
stroke: (paint: gray, thickness: 1pt),
align: left,
[*Version*],
[*Date*],
[*Author*],
[*Description*],
..for item in versions {
version = nextVersion(version, if "major" in item {
item.major
} else {
false
})
(
version,
item.date.display("[month repr:long] [day], [year]"),
item.name,
item.comment
)
}
)
]
] |
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/tutorial/templates.md | markdown | MIT License | # Templates
## Templates
If you want to reuse styling in other files, you can use the _template_ idiom.
Because `set` and `show` rules are only active in their current scope, they
will not affect content in a file you imported your file into. But functions
can circumvent this in a predictable way:
```typ-norender
// define a function that:
// - takes content
// - applies styling to it
// - returns the styled content
#let apply-template(body) = [
#show heading.where(level: 1): emph
#set heading(numbering: "1.1")
// ...
#body
]
```
This is equivalent to:
```typ-norender
// we can reduce the number of hashes needed here by using scripting mode
// same as above but we exchanged `[...]` for `{...}` to switch from markup
// into scripting mode
#let apply-template(body) = {
show heading.where(level: 1): emph
set heading(numbering: "1.1")
// ...
body
}
```
Then in your main file:
```typ-norender
#import "template.typ": apply-template
#show: apply-template
```
_This will apply a "template" function to the rest of your document!_
### Passing arguments
```typ-norender
// add optional named arguments
#let apply-template(body, name: "<NAME>") = {
show heading.where(level: 1): emph
set heading(numbering: "1.1")
align(center, text(name, size: 2em))
body
}
```
Then, in template file:
```typ-norender
#import "template.typ": apply-template
// `func.with(..)` applies the arguments to the function and returns the new
// function with those defaults applied
#show: apply-template.with(name: "Report")
// it is functionally the same as this
#let new-template(..args) = apply-template(name: "Report", ..args)
#show: new-template
```
Writing templates is fairly easy if you understand [scripting](../scripting/index.md).
See more information about writing templates in [Official Tutorial](https://typst.app/docs/tutorial/making-a-template/).
There is no official repository for templates yet, but there are a plenty community ones in [awesome-typst](https://github.com/qjcg/awesome-typst?ysclid=lj8pur1am7431908794#general). |
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/all_types_working/all_types_working_inserted_result.typ | typst | #underline[GNU];#underline[ ];#underline[nano];#underline[
];#underline[6.2];#underline[ ];#underline[test1.typ]
= #underline[Introduction]
#underline[In];#underline[ ];#underline[this];#underline[
];#underline[report,];#underline[ ];#underline[we];#underline[
];#underline[will];#underline[ ];#underline[explore];#underline[
];#underline[the];#underline[ ];#underline[various];#underline[
];#underline[factors];#underline[ ];#underline[that];#underline[
];#underline[influence];#underline[ ];#underline[#emph[fluid
dynamics];];#underline[ ];#underline[in];#underline[
];#underline[glaciers];#underline[ ];#underline[and];#underline[
];#underline[how];#underline[ ];#underline[they];#underline[
];#underline[contribute];#underline[ ];#underline[to];#underline[
];#underline[the];#underline[ ];#underline[formation];#underline[
];#underline[and];#underline[ ];#underline[behaviour];#underline[
];#underline[of];#underline[ ];#underline[these];#underline[
];#underline[natural];#underline[ ];#underline[structures.]
#underline[The];#underline[ ];#underline[equation];#underline[
];#underline[$Q = rho A v + C$];#underline[
];#underline[defines];#underline[ ];#underline[the];#underline[
];#underline[glacial];#underline[ ];#underline[flow];#underline[
];#underline[rate.]
#underline[The];#underline[ ];#underline[flow];#underline[
];#underline[rate];#underline[ ];#underline[of];#underline[
];#underline[a];#underline[ ];#underline[glacier];#underline[
];#underline[is];#underline[ ];#underline[defined];#underline[
];#underline[by];#underline[ ];#underline[the];#underline[
];#underline[following];#underline[ ];#underline[equation:]
#underline[$ Q = rho A v + C $]
#underline[The];#underline[ ];#underline[flow];#underline[
];#underline[rate];#underline[ ];#underline[of];#underline[
];#underline[a];#underline[ ];#underline[glacier];#underline[
];#underline[is];#underline[ ];#underline[given];#underline[
];#underline[by];#underline[ ];#underline[the];#underline[
];#underline[following];#underline[ ];#underline[equation:]
#underline[$ Q = rho A v + upright(" time offset ") $]
#underline[Total];#underline[ ];#underline[displaced];#underline[
];#underline[soil];#underline[ ];#underline[by];#underline[
];#underline[glacial];#underline[ ];#underline[flow:];#underline[
];#underline[$ 7.32 beta + sum_(i = 0)^nabla frac(Q_i (a_i - epsilon), 2) $]
#underline[$ v colon.eq vec(x_1, x_2, x_3) $]
#underline[$ a arrow.r.squiggly b $]
#underline[Lorem];#underline[ ];#underline[ipsum];#underline[
];#underline[dolor];#underline[ ];#underline[sit];#underline[
];#underline[amet,];#underline[ ];#underline[consectetur];#underline[
];#underline[adipiscing];#underline[ ];#underline[elit,];#underline[
];#underline[sed];#underline[ ];#underline[do]
#underline[Number:];#underline[ ];#underline[3]
#underline[$- x$];#underline[ ];#underline[is];#underline[
];#underline[the];#underline[ ];#underline[opposite];#underline[
];#underline[of];#underline[ ];#underline[$x$]
#underline[let];#underline[ ];#underline[name];#underline[
];#underline[\=];#underline[
];#underline[\[];#underline[#strong[Typst!];];#underline[\]]
#underline[#strong[strong];]
#underline[`print(1)`]
#link("https://typst.app/")[#underline[https:\/\/typst.app/];]
<intro>
= #underline[Heading]
#underline[$x^2$]
#underline[‘single”];#underline[ ];#underline[or];#underline[
];#underline[“double”]
#underline[~,];#underline[ ];#underline[—]
#underline[$x^2$]
#underline[$ x^2 $]
#underline[$x_1$]
#underline[$x^2$]
#underline[$1 + frac(a + b, 5)$]
#underline[$x\
y$]
#underline[$x & = 2\
& = 3$]
#underline[$pi$]
#underline[$arrow.r$];#underline[ \
];#underline[$x y$]
#underline[$arrow.r , eq.not$]
#underline[$a upright(" is natural")$]
#underline[$⌊x⌋$]
#underline[Lorem];#underline[ ];#underline[ipsum];#underline[
];#underline[dolor];#underline[ ];#underline[sit];#underline[
];#underline[amet,];#underline[ ];#underline[consectetur];#underline[
];#underline[adipiscing];#underline[ ];#underline[elit,];#underline[
];#underline[sed];#underline[ ];#underline[do];#underline[
];#underline[eiusmod];#underline[ ];#underline[tempor];#underline[
];#underline[incididunt];#underline[ ];#underline[ut];#underline[
];#underline[labore];#underline[ ];#underline[et];#underline[
];#underline[dolore];#underline[ ];#underline[magna];#underline[
];#underline[aliqua.];#underline[ ];#underline[Ut];#underline[
];#underline[enim];#underline[ ];#underline[ad];#underline[
];#underline[minim];#underline[ ];#underline[veniam,];#underline[
];#underline[quis];#underline[ ];#underline[nostrud];#underline[
];#underline[exercitation];#underline[ ];#underline[ullamco];#underline[
];#underline[laboris];#underline[ ];#underline[nisi]
#underline[#emph[Hello];];#underline[ \
];#underline[5]
#underline[hello];#underline[ ];#underline[from];#underline[
];#underline[the];#underline[ ];#underline[#strong[world];]
#underline[This];#underline[ ];#underline[is];#underline[
];#underline[Typst‘s];#underline[ ];#underline[documentation.];#underline[
];#underline[It];#underline[ ];#underline[explains];#underline[
];#underline[Typst.]
#underline[Sum];#underline[ ];#underline[is];#underline[ ];#underline[5.]
#underline[The];#underline[ ];#underline[coordinates];#underline[
];#underline[are];#underline[ ];#underline[1,];#underline[
];#underline[2.]
#underline[The];#underline[ ];#underline[first];#underline[
];#underline[element];#underline[ ];#underline[is];#underline[
];#underline[1.];#underline[ ];#underline[The];#underline[
];#underline[last];#underline[ ];#underline[element];#underline[
];#underline[is];#underline[ ];#underline[4.]
#underline[Austen];#underline[ ];#underline[wrote];#underline[
];#underline[Persuasion.]
#underline[Homer];#underline[ ];#underline[wrote];#underline[
];#underline[The];#underline[ ];#underline[Odyssey.]
#underline[The];#underline[ ];#underline[y];#underline[
];#underline[coordinate];#underline[ ];#underline[is];#underline[
];#underline[2.]
#underline[(5,];#underline[ ];#underline[6,];#underline[
];#underline[11)]
#underline[This];#underline[ ];#underline[is];#underline[
];#underline[shown]
#underline[abc]
#underline[Hello];#underline[ \
];#underline[Heading];#underline[ \
];#underline[3];#underline[ ];#underline[is];#underline[
];#underline[the];#underline[ ];#underline[same];#underline[
];#underline[as];#underline[ ];#underline[3]
#underline[4];#underline[ \
];#underline[3];#underline[ \
];#underline[a];#underline[ ];#underline[—];#underline[
];#underline[b];#underline[ ];#underline[—];#underline[ ];#underline[c]
#underline[Dobrze]
#underline[#strong[Date:];];#underline[
];#underline[26.12.2022];#underline[ \
];#underline[#strong[Topic:];];#underline[
];#underline[Infrastructure];#underline[ ];#underline[Test];#underline[
\
];#underline[#strong[Severity:];];#underline[
];#underline[High];#underline[ \
];#underline[abc];#underline[ \
];#underline[#strong[my text];];#underline[ \
];#underline[already];#underline[ ];#underline[low]
#underline[ABC];#underline[ \
];#underline[#strong[MY TEXT];];#underline[ \
];#underline[ALREADY];#underline[ ];#underline[HIGH]
#underline[“This];#underline[ ];#underline[is];#underline[
];#underline[in];#underline[ ];#underline[quotes.”]
#underline[“Das];#underline[ ];#underline[ist];#underline[
];#underline[in];#underline[ ];#underline[Anführungszeichen.”]
#underline[“C’est];#underline[ ];#underline[entre];#underline[
];#underline[guillemets.”]
#underline[1];#underline[#super[st];];#underline[ ];#underline[try!]
#underline[Italic];#underline[ ];#underline[Oblique]
#underline[This];#underline[ ];#underline[is];#underline[
];#underline[#underline[important];];#underline[.]
#underline[Take];#underline[ ];#underline[#underline[care];]
GNU nano 6.2 test1.typ
= Introduction
In this report, we will explore the various factors that influence
#emph[fluid dynamics] in glaciers and how they contribute to the
formation and behaviour of these natural structures.
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 + upright(" time offset ") $
Total displaced soil by glacial flow:
$ 7.32 beta + sum_(i = 0)^nabla frac(Q_i (a_i - epsilon), 2) $
$ v colon.eq vec(x_1, x_2, x_3) $
$ a arrow.r.squiggly b $
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
Number: 3
$- x$ is the opposite of $x$
let name = \[#strong[Typst!];\]
#strong[strong]
`print(1)`
#link("https://typst.app/")
<intro>
= Heading
$x^2$
‘single” or “double”
~, —
$x^2$
$ x^2 $
$x_1$
$x^2$
$1 + frac(a + b, 5)$
$x\
y$
$x & = 2\
& = 3$
$pi$
$arrow.r$ \
$x y$
$arrow.r , eq.not$
$a upright(" is natural")$
$⌊x⌋$
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi
#emph[Hello] \
5
hello from the #strong[world]
This is Typst‘s documentation. It explains Typst.
Sum is 5.
The coordinates are 1, 2.
The first element is 1. The last element is 4.
Austen wrote Persuasion.
Homer wrote The Odyssey.
The y coordinate is 2.
(5, 6, 11)
This is shown
abc
Hello \
Heading \
3 is the same as 3
4 \
3 \
a — b — c
Dobrze
#strong[Date:] 26.12.2022 \
#strong[Topic:] Infrastructure Test \
#strong[Severity:] High \
abc \
#strong[my text] \
already low
ABC \
#strong[MY TEXT] \
ALREADY HIGH
“This is in quotes.”
“Das ist in Anführungszeichen.”
“C’est entre guillemets.”
1#super[st] try!
Italic Oblique
This is #underline[important];.
Take #underline[care]
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/058%20-%20Duskmourn%3A%20House%20of%20Horror/008_Keep%20Them%20Alive.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Keep Them Alive",
set_name: "Duskmourn: House of Horror",
story_date: datetime(day: 27, month: 08, year: 2024),
author: "<NAME>",
doc
)
Grown now, child, strong and solid and ready to face the horrors of the halls. Let me have the look of you, the seeing before you go.
Cocoon was kind. It isn't always. Four good legs and two good arms, such sharp teeth and claws. Oh, you will be a good protector, a strong defense against wandering nightmare and unseen danger! You will serve so very well, will protect so very skillfully, and will be a clean-drawn line in the mural of our history!
You are ready, child-no-longer, to understand your purpose here. Come with me, and I will tell you what you are, what you will be, as I take you to your destined beginning.
Born we are of House, as all good things must be born of House—as all wicked things must be born as well, for House is all. There are legends of a time before House was any, when it was but a whisper carried on the wings of moths, telling us what might one day come to be, but those are only legends; they change nothing of our living now. In those old stories, however, we were like the keep-alives; we existed outside House. Then the walls closed in around us, and the cocoons came, and in the cocoons, we were first reborn, although we were not children as you were when the sweet silk closed around you. We were creatures grown and other than we are now, as you were other before your own cocooning. Such is the way of House. What exists here is changed, as much for its own safety as for the amusement of House itself.
Of course I speak of House as a living thing. Anyone who walks here can see it as a living thing, see the way it moves and answers and reacts. House moves with intention. House comprehends what happens with its body, at least to some degree. Its awareness is questionable. Its life is not.
As ours is not.
When the first of us emerged from our cocoons into the splendid horror of House, we wandered with no comprehension of our purpose. Why should such as we exist? We lacked the voracious hunger of the cellarspawn, or the wicked malice of the nightmares. We had claws and horns and fangs, but we could not rip and tear as did the razorkin, not claim and transform as did the wickerfolk. We alone in the body of the House walked without purpose. Our days were long and our nights restless, for we had too much intelligence to be idle, and too little reason to keep occupied.
In those days, we lived all as one pack, large and awkward, a target for the more dangerous occupants of House, and it seemed our purpose might be simple survival. But that was so small, and we had in us the potential to be so large; it seemed unfair that we should be so limited. And our leader, all the way back then in the very beginning, was a great and terrible beastie who called himself Spindlewight. Six legs had he, and three arms, and claws enough to carve through stone. Horns like spears, and teeth like knives, and a fine, thick pelt of blue and green, rosette-spotted like the eyes on a vast moth's wings.
"I will know our purpose," he declared, and he left us, left his pack and his kin, to walk the body of House.
Deep and deeper he went, away from the attics and the high halls where we made our homes, and many dangers he encountered, deep dangers, dreadful dangers, horrors such as we had never once imagined—Horrors even to the horrible, things from which the other children of House fled in fear. He fought many battles, he sharpened his claws on bones, and he knew himself for a terrible predator. To protect his eyes, he fashioned himself a mask of broken bone and stolen scrap. This will matter, child, remember it.
On he walked, greatest of our kind, masked and terrible. And then, in a library clearly ruined by some great battle, where he prowled with the easy confidence of a predator, he heard a new sound. A terrible sound, that created a pain in his head like splinters in the skin. It did not stop, and so he moved toward it, called and repulsed at the same time.
We know this sound very well now. It is called "crying," and it is a terrible, wonderful thing. Terrible, for it means pain. Wonderful, for it means life.
He moved a fallen shelf aside, and there he found three creatures, one large and two much smaller, clinging to each other in the wreckage. There was the smell of blood, and fresh, untainted meat, and had he been hungry in that moment, before the bargain had been sealed, our mural would be painted very differently indeed.
But he did not hunger, and curiosity brought him closer to the creatures. They were furless and clawless, with no horns and soft skins, their faces matched to their bodies and not set apart, as ours are. They had no tails, no fangs, but clothed themselves in scraps of fabric. By that, he knew they were intelligent, for they must have fashioned their false furs in the same way he had fashioned his mask, and he felt a mutual respect that they had both, unknowing, taken steps to look more like one another. They covered their baldness to suit his sensibilities, and he had covered his face to suit theirs, all before they had even seen one another. What a miracle that meeting was. What a moment. What a mercy.
The two smaller ones were crying, burrowing against their larger as cubs will burrow in the den before the cocooning time. Spindlewight moved closer in his curiosity, and the larger one pulled away, gathering the small ones close. He stopped, looking at them, and waited to learn what would happen next.
So long he waited that the echoes of the battle which had destroyed this place faded from the memory of House, and a cellarspawn pulled itself from the wall, hungry as House ever was. It came for the strange things, drawn by their crying as Spindlewight had been, and Spindlewight attacked it, driving it away from #emph[his] discovery, #emph[his] great mystery, which must be studied, which must be understood.
Back and back he drove it, and it fought, but he fought more fiercely, and in the end, it was felled by his power and his persistence, and he returned to the creatures.
The two smallest were crying harder than ever, while the largest was motionless, a spike of jagged wood protruding from its middle. It had been broken loose during the fight against the cellarspawn and had flown all unseen to pierce and pin. There was blood, more blood than ever, and while the creature yet breathed, it no longer had the strength to cry.
Spindlewight moved closer, sniffing at it, trying to decide what was to happen next, and the creature opened its eyes. It moved its mouth in a shape called a "smile"—you will see your first smile soon, and it will light you up inside as it did him, it will recolor your world in new brilliance, such as you have never even dreamt before! I envy you that first smile, I do, for mine was long ago, and the one who wore it is no more.
"You … saved us," it said.
Spindlewight huffed his acknowledgment.
"Or you … tried," said the creature, smile fading. "Ah. I don't think you quite … saved us all. But you saved what matters. I can't be too … unhappy."
The creature spoke the language of House, the language sometimes muttered by the razorkin and by the nightmares. Spindlewight understood enough to know that the large one was dying, and he was grieved, for he wanted to know more.
But then the large creature pushed the two smaller toward him, as they cried and quivered.
"Please …" it said. "One last … favor. Please … keep them alive."
It closed its eyes then, and it left house in the only way that any living thing ever can. Spindlewight wrapped his first two arms around the smaller creatures as they cried and clung to his furs, and he knew what they were, for they had been named by their elder as their care was passed to him:
They were keep-alives, and he would do exactly that. He would keep them alive, as long as he could.
#figure(image("008_Keep Them Alive/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Spindlewight returned to us with his new charges and told us that our purpose had been found. And thus, did we learn many things.
First, that a beastie is at their very best when they have a keep-alive to protect and care for. We cannot steal them from their own kind, but we can woo them, offer them gifts and friendship until they give us smiles in return. Once a keep-alive has smiled at you, you will be theirs forevermore, even once they have left House behind or been taken where you cannot follow. They give us gifts equal to the ones we offer them, and more, for they give us a kindness we ache for deep within our bones.
Second, that the keep-alives are terrified of our true faces. All the kindness we can offer, all the friendship that has passed before our masks come off, none of it matters, for if they see us truly, they will fear us, and they will flee. A fleeing keep-alive can never be befriended again; they are lost. We are divided, as a pack, on how to handle those losses. Some say they should be put to death at once, mercifully culled before House's other occupants can have them. Others say it is never right to kill a friend, and simply let them go, even knowing that they won't survive for long.
Those first two, they gave us the mural. They painted it on the attic walls with their own hands, with paint Spindlewight had gifted them from a playroom far below, stolen from under the watch of nightmares and cellarspawn. They painted a beautiful world we had never seen, and they filled it with us, with great shaggy creatures that watched over them benevolently and out of kindness. We add to it still, paint ourselves in the fields they drew for us, sketch our outlines in the spaces that remain. It is our history and our home and our greatest treasure, and we would fight House itself to protect it.
They gave us the mural, and they gave us the lessons. One grew tall and strong and clever in Spindlewight's keeping, staying with him for so long as their story goes. The other saw the maskless and fled into the halls, never to be seen again. The loss of that keep-alive broke Spindlewight's heart, and he led us no longer.
Without his heavy paw to guide and mold us, we broke into the packs we occupy today. The mural was declared neutral ground, shared between us, too precious to risk to the protection of a single pack, and we scattered through the House.
Spindlewight and his keep-alive remained together. They had many adventures, until at last they didn't; until his keep-alive came back to the mural with his mask in hand, broken down the center, and wept and wailed and smiled no more. It would not accept another keeper but followed the path of its sibling down into the House, to be seen no more.
Spindlewight's bones sleep somewhere in the House, unremarked and dearly remembered.
Your keep-alive is there as well, already waiting for you, although they do not know it. Fashion a mask from these things we have gathered, drape yourself in things both colorful and pleasant to the eye, and go forth to find your companion. We have one purpose in this House, one pleasure.
Keep them alive. I believe in you, no-longer-child, and Spindlewight would believe in you as well, were he still here. You have grown strong and clever, you have survived your own cocoon, and you are ready to be a glorious companion to one who needs you.
You will not succeed. None of us do, not forever, and when you fail, you will return here, to add your stories to our mural, to gather with your own kind for a time, to tend to the cocoons as I have done. And then you will go again, for we know why we are here, and we know what we must do, and we know one day, if we are clever, we will succeed.
Keep them alive.
Nothing more is needed.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/place-spacing_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#show figure: set block(spacing: 4em)
Paragraph before float.
#figure(rect(), placement: bottom)
Paragraph after float.
|
https://github.com/ofurtumi/formleg | https://raw.githubusercontent.com/ofurtumi/formleg/main/readme.md | markdown | # Formleg mál og reiknanleiki
Verkefni og svör úr Töl301G
> Verkefni skrifuð í typst, þurfa typst til að vera generated
> þurfa líka pakka fyrir template, hægt að finna í [typst-packages](https://github.com/ofurtumi/typst-packages)
> sjá upplýsingar um setup í því repo
|
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/src/lt.typ | typst | MIT License | #import "_imports.typ": *
#import "@preview/ccicons:1.0.0": ccicon, cc-is-valid
#let lerntheke(
..args,
body,
) = {
let (
doc,
page-init,
tpl,
) = base-template(
type: "LT",
type-long: "Lerntheke",
// defaults
paper: "a5",
flipped: true,
margin: 1cm,
fontsize: 11pt,
// disable title
title-block: (..) => [],
// Template options
// _tpl: (:),
..args,
body,
)
{
show: page-init.with(
header: (..) => [],
footer: (..) => [],
)
tpl
}
}
#let _counter-cards = counter("schule.cards")
#let _counter-cards-help = counter("schule.aid-cards")
#let card-header-height = 3em
#let card-footer-height = 6mm
#let _help-ref(kind: "card-help") = it => {
if it.element != none and it.element.kind == kind {
context link(
it.element.location(),
numbering(
it.element.numbering,
..it.element.counter.at(it.element.location()),
),
)
} else {
it
}
}
#let _card-header(
title,
counter: _counter-cards,
no: auto,
icon: none,
fill: theme.bg.muted,
label: none,
) = {
let fake-heading = text.with(font: theme.fonts.sans, size: 1.2em, weight: "bold")
let content-block = block.with(
width: 100%,
height: 100%,
radius: 6pt,
stroke: .6pt + rgb(33%, 33%, 33%, 33%),
)
place(
top + center,
{
if counter != none {
counter.step()
if label != none {
marks.place-reference(label, "card", "Karte")
}
}
block(
width: 100%,
height: card-header-height,
clip: true,
breakable: false,
grid(
columns: (1.5cm, 1fr, 1.5cm),
column-gutter: 2mm,
align: center + horizon,
content-block(
fill: theme.bg.muted,
{
if counter != none and no != none {
fake-heading(if no == auto {
counter.display()
} else if type(no) == function {
counter.display(no)
} else {
str(no)
})
} else if type(no) in (str, int) {
fake-heading(fill: theme.text.default, str(no))
}
},
),
content-block(
fill: fill,
fake-heading(fill: util.get-text-color(fill), title),
),
content-block(
fill: theme.bg.muted,
fake-heading(size: 1.8em, icon),
),
),
)
},
)
}
#let _card-header-back(
title,
fill: theme.bg.muted,
) = {
let fake-heading = text.with(font: theme.fonts.sans, size: 1.2em, weight: "bold")
place(
top + center,
{
block(
width: 100%,
height: card-header-height,
radius: 6pt,
stroke: .6pt + rgb(33%, 33%, 33%, 33%),
fill: fill,
clip: true,
breakable: false,
{
set align(center + horizon)
fake-heading(fill: util.get-text-color(fill), upper(title))
},
)
},
)
}
#let _card-body(body) = {
block(
width: 100%,
inset: (x: .64em, top: card-header-height + 1.28em, bottom: card-footer-height + .64em),
clip: true,
breakable: false,
body,
)
}
#let _card-footer(infotext: none) = place(
bottom + left,
block(
width: 100%,
height: card-footer-height,
clip: true,
breakable: false,
stroke: (top: .6pt + theme.muted),
{
set align(center + horizon)
set text(9pt, theme.muted)
grid(
columns: (auto, 1fr, auto),
column-gutter: 1em,
{
document.use-value(
"class",
class => [#{
class
}.],
)
document.use-value("number", v => [#v])
" "
document.use-value("title", v => [#v])
", "
document.use-value("version", ver => [v#ver])
},
align(
center,
document.use-value(
"license",
l => if cc-is-valid(l) {
ccicon(l)
},
),
),
align(right, infotext),
)
},
),
)
#let _help-token(label) = box(
fill: theme.cards.help,
stroke: .6pt + rgb(33%, 33%, 33%, 33%),
inset: (x: .33em, y: .5em),
radius: 30%,
text(util.get-text-color(theme.cards.help), weight: "bold", sym.arrow.t + label),
)
#let hilfe-marker(..labels) = {
place(
top + right,
dx: -1cm,
dy: -2em,
labels.pos().map(target => {
show link: set text(util.get-text-color(theme.cards.help), weight: "bold")
show ref: it => context link(
it.element.location(),
box(
fill: theme.cards.help,
stroke: .6pt + rgb(33%, 33%, 33%, 33%),
inset: (x: .33em, y: .5em),
radius: 30%,
sym.arrow.t + numbering(
it.element.numbering,
..it.element.counter.at(it.element.location()),
),
),
)
ref(target)
}).join(h(.2em)),
)
}
#let karte(
titel: auto,
infotext: none,
nr: auto,
icon: none,
fill: theme.bg.muted,
hilfen: none,
label: none,
body,
) = {
let (titel, body) = (titel, body)
if titel == auto {
(titel, body) = util.extract-title(body)
}
pagebreak(weak: true)
_card-header(titel, counter: _counter-cards, no: nr, fill: fill, icon: icon, label: label)
_card-body({
if hilfen != none {
hilfe-marker(..hilfen)
}
body
})
_card-footer(infotext: infotext)
}
#let karte1 = karte.with(fill: theme.cards.type1)
#let karte2 = karte.with(fill: theme.cards.type2)
#let karte3 = karte.with(fill: theme.cards.type3)
#let hilfekarte(
titel: auto,
infotext: none,
nr: auto,
icon: emoji.ringbuoy,
fill: theme.cards.help,
label: auto,
body,
) = {
let (titel, body) = (titel, body)
if titel == auto {
(titel, body) = util.extract-title(body)
}
if nr == auto {
nr = (
n,
..,
) => [H#n#if label != auto {marks.place-reference(label, "card-help", "Hilfekarte", numbering: "H1")}]
}
pagebreak(weak: true)
_card-header(titel, counter: _counter-cards-help, no: nr, fill: fill, icon: icon, label: none)
_card-body(body)
_card-footer(infotext: infotext)
}
#let rueckseite(
titel: auto,
infotext: none,
icon: none,
fill: theme.cards.back,
body,
) = {
let (titel, body) = (titel, body)
if titel == auto {
(titel, body) = util.extract-title(body)
}
pagebreak(weak: true)
_card-header-back(titel, fill: fill)
_card-body(body)
_card-footer(infotext: infotext)
}
#let leer() = {
pagebreak(weak: false)
}
// #let loesung = rueckseite.with(titel: "Lösung")
#let loesungskarte(..args) = {
rueckseite(titel: "Lösungen")[
#if args.pos() != () {
args.pos().first()
}
#context ex.solutions.display-solutions(ex.get-current-exercise(), title: none)
#if args.pos().len() > 1 {
args.pos().last()
}
]
}
#let infotext-loesung(sol) = rotate(180deg, sol)
|
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis | https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/tools/macros.typ | typst | #let remLE(x) = text(fill: blue, size: 0.75em)[[*LE:* #x]]
//--------------- eqref
// #let reffmt = it => box(stroke: rgb("#ff0000") + 0.5pt, outset: 2pt)[#smallcaps[#it]]
#let reffmt = it => text(fill: blue)[#it]
#show ref: reffmt
#let linkfmt = it => [#underline(text(blue)[#it])]
#import "eqref.typ": *
#let eqref = eqref.with(style: reffmt) // set defaults
#let customEqfmt = (nums) => [#box[Eq. (#numbering("1.1", ..nums))]]
#let customEqref = eqref.with(fmt: customEqfmt, style: emph) // alternate options
//--------------- eqref |
|
https://github.com/seapat/markup-resume-lib | https://raw.githubusercontent.com/seapat/markup-resume-lib/main/cv_core.typ | typst | Apache License 2.0 | #import "utils.typ" as utils
#import "@preview/fontawesome:0.1.0": *
// first define functions for each component then use them to generate the cv
#let link-blue = rgb("#0000EE")
#let make_title_line(entry, render_settings) = {
let date_format = "[month repr:numerical]/[year]"
let title = if "title" in entry.keys() [#entry.title]
title = if "url" in entry.keys() {
title + " - " + link(
entry.url,
text("link ", size: render_settings.font_size - 3pt) + fa-arrow-up-right-from-square(size: render_settings.font_size - 5pt, fill: link-blue),
)
} else { title }
let date = utils.format_date(entry, date_format, render_settings)
if title != none or date != none [*#title #h(1fr) #date* \ ]
}
#let make_sub_line(entry) = {
let sub = if "subtitle" in entry.keys() {
text(style: "italic", entry.subtitle)
}
let loc = if "location" in entry.keys() { entry.location }
if sub != none or loc != none [#sub #h(1fr) #loc \ ]
}
#let make_description(entry) = {
if "description" in entry.keys() and entry.description != none {
eval(entry.description, mode: "markup")
}
}
#let make_bullet_points(entry) = {
if "bullets" in entry.keys() and entry.bullets != none {
for bp in entry.bullets {
list(eval(bp, mode: "markup"))
}
}
}
#let make_space(entry) = {
if "spacer" in entry.keys() and entry.spacer != none {
if type(entry.spacer) == int {
for _ in range(entry.spacer) {
"\n"
}
} else if entry.spacer == "pagebreak" {
pagebreak(
// weak=true
)
}
}
}
#let make_tabular(entry) = {
if "tabular" in entry.keys() and entry.tabular != none {
let temp_arr = ()
for (key, value) in entry.tabular.pairs() {
if key == "columns" {continue};
let sep = ","
if "separator" in entry.tabular.keys() { let sep = entry.tabular.separator }
temp_arr.push(align(left, eval(key, mode: "markup")))
temp_arr.push(align(left, if type(value) == "array" {
eval(value.join(sep + " "), mode: "markup")
} else {
eval(str(value), mode: "markup")
}))
}
let pad_dist = (2 / 3) * 1em
pad(
bottom: if "description" in entry.keys() { -pad_dist } else { -pad_dist / 6 }, // `-pad_dist/6` was determined by trial and error
// We always want to have some spacing between the separating line and the first element, there's probably a better way to do this
top: if "subtitle" in entry.keys() { -pad_dist } else { -0.05em },
grid(
// multiply columns by two because key value are techically their own columns
columns: if "columns" in entry.tabular.keys() {2*entry.tabular.columns} else {(auto, auto)},
column-gutter: if "columns" in entry.tabular.keys() {5pt} else {15pt},
// 0.65 is the default linesapcing of paragraphs
row-gutter: 0.65em,
..temp_arr,
),
) // spreading-operator see docs.arguments
}
}
#let make_cv_core(info, render_settings) = {
// TODO: make user-configurable while using current as default
for (section, data) in info {
if type(data) == array { // true sections of CV body
let section_elements = ()
for entry in data {
// init content with empty fields
let content = (
"title": none,
"subtitle": none,
"bullets": none,
"list": none,
"description": none,
)
// Line 1: Institution and Location
content.insert("title", make_title_line(entry, render_settings))
// Line 2: Degree and Date Range
content.insert("subtitle", make_sub_line(entry))
// Part 1: Bullet points
content.insert("bullets", make_bullet_points(entry))
// Part 2: Pairs of title and listing, only collect values
content.insert("list", make_tabular(entry))
// Part 3: Add text paragraph directly
content.insert("description", make_description(entry))
//Part 4: data defined new lines for spacing
content.insert("spacer", make_space(entry))
// Push content of most recent section to our Datastructure/array
section_elements.push(content)
}
// render entry contents to page, order is important
[== #section
#for element in section_elements [
#element.title
#element.subtitle
#element.list
#element.description
#element.bullets
#element.spacer
#parbreak()
]
]
} else if type(content) == dictionary { none } // personal information and metadata
}
}
#let foot_note(render_settings) = if render_settings.show_footer {
place(
bottom + right,
block[
#set text(size: 5pt, font: "Consolas", fill: silver)
This document was last updated on #datetime.today().display("[year]-[month]-[day]").
],
)
}
|
https://github.com/jomaway/typst-teacher-templates | https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-utils/lib/layout.typ | typst | MIT License | /// display some content side-by-side
///
/// - columns (none, auto, integer): Set the amount of columns
/// - gutter (length): grid gutter
/// - ..cols (content): content to show
/// -> content
#let side-by-side(columns: none, gutter: 1em, ..cols) = {
let cols = cols.pos()
let columns = if columns == none { (1fr,) * cols.len() } else { columns }
assert(
columns.len() == cols.len(),
message: "number of columns must match number of cols"
)
grid(columns: columns, gutter: gutter, ..cols)
}
/// utility function to stick header and following block together
#let stick-together(a, b, threshold: 3em) = {
block(a + v(threshold), breakable: false)
v(-1 * threshold)
b
}
|
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/cartridges/huc1.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "../../common.typ": *
== HuC-1 mapper chip
HuC-1 supports ROM sizes up to 8 Mbit (64 banks of #hex("4000") bytes), and RAM
sizes up to 256 Kbit (4 banks of #hex("2000") bytes). It also includes a sensor
and a LED for infrared communication. The information in this section is based
on my HuC-1 research.
|
https://github.com/El-Naizin/cv | https://raw.githubusercontent.com/El-Naizin/cv/main/modules/certificates.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Certificates")
#cvHonor(
date: [2022],
title: [AWS Certified Security],
issuer: [Amazon Web Services (AWS)],
)
#cvHonor(
date: [2017],
title: [Applied Data Science with Python],
issuer: [Coursera]
)
#cvHonor(
date: [],
title: [SQL Fundamentals Track],
issuer: [Datacamp]
) |
https://github.com/jens-hj/ds-exam-notes | https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/main.typ | typst | #import "lib.typ": *
#show link: it => underline(emph(it))
#set page(numbering: "1 / 1")
#set math.equation(numbering: "(1)")
#set enum(full: true)
#set math.mat(delim: "[")
#set math.vec(delim: "[")
#set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled))
#show heading.where(level: 1): it => text(size: 22pt, it)
#show heading.where(level: 2): it => text(size: 18pt, it)
// #show heading.where(level: 3): it => {
// text(size: 14pt, mainh, pad(
// left: -0.4em,
// gridx(
// columns: (auto, 1fr),
// align: center + horizon,
// gap: 0em,
// it, rule(stroke: 1pt + mainh)
// )
// ))
// }
#show heading.where(level: 4): it => text(size: 12pt, secondh, it)
#show heading.where(level: 5): it => text(size: 12pt, thirdh, it)
#show heading.where(level: 6): it => text(thirdh, it)
#show emph: it => text(accent, it)
#show outline.entry.where(level: 2) : it => text(size: 1em, weight: "bold", it)
#show ref: it => {
//let sup = it.supplement
let el = it.element
if el == none {
it.citation
}
else {
let eq = math.equation
// let sup = el.supplement
if el != none and el.func() == eq {
// The reference is an equation
let sup = if it.fields().at("supplement", default: "none") == "none" {
[Equation]
} else { [] }
// [#it.has("supplement")]
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#sup #n]
}
else if it.citation.has("supplement") {
if el != none and el.func() == eq {
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#el.supplement #n]
}
else {
text(accent)[#it]
}
}
}
}
#text(size: 25pt, weight: 900, [Distributed Storage Exam Notes])
#v(-10pt)#hr
#outline(
indent: auto,
depth: 2,
fill: grid(
columns: 1,
block(
fill: black,
height: 0.5pt,
width: 100%,
),
block(
fill: none,
height: 0.25em,
width: 100%,
),
),
)
#let lecture-topics = (
"01: Socket Programming",
"02: Remote Procedure Calls & Network File System",
"03: Andrew File System & Reliable Storage: Single Server",
"04: RAID systems",
"05: Reliable Storage: Finite Fields & Linear Coding",
"06: Repair Problem & Regenerating Codes",
"07: Reliable Storage: Regenerating Codes & Local Repairability",
"08: Hadoop Distributed File System (HDFS)",
"09: Storage Virtualisation",
"10: Object Storage",
"11: Compression & Delta Encoding",
"12: Data Deduplication",
"13: Fog/Edge Storage",
"14: Security in Storage Systems"
)
#{
for i in range(0, lecture-topics.len()) {
pagebreak(weak: true)
[== #lecture-topics.at(i)]
include "lectures/" + str(i+1) + ".typ"
}
}
|
|
https://github.com/ofurtumi/hugbo-glosur | https://raw.githubusercontent.com/ofurtumi/hugbo-glosur/main/glosur.typ | typst | #let glob_color = luma(90)
#set text(font: "Virgil 3 YOFF", glob_color)
#set page(
margin: (x: 16pt, y: 16pt),
)
#show raw: it => {text(font: "Virgil 3 YOFF", size: 7pt)[#it]}
#let note(heading, body, delim: true) = {
show raw.where(block: true): r => {
box(stroke: 1pt + glob_color, inset: 8pt, radius: 8pt, r)
}
if type(body) != "array" {
align(center)[ == #heading ]
body
}
else if body.len() == 1 {
align(center)[ == #heading ]
body.first()
} else if calc.even((body.len())) {
body.first() = align(center + top)[ == #heading ] + body.first()
grid(columns: (2), gutter: 4pt, ..body.map(val => align(horizon)[#val])
)
} else {
body.first() = align(center + top)[ == #heading ] + body.first()
let last = body.pop()
grid(columns: 2, gutter: 4pt, ..body.map(val => align(horizon)[#val]))
align(center)[#last]
}
if delim {line(stroke: 1pt + glob_color, length: 100%)}
}
#note(
"Singleton",
(
[
Uses static attributes to bind vars to the class rather than the class instances. When accessed uses class name without prior instantiation. Uses \<\<static\>\> in uml, uses private constructor and private final instance with a getter to fetch the data
],
```java
class Singleton {
private static Singleton INSTANCE;
private Singleton() {}
public static Singleton getInstance() {
if ( instance == null ) instance = new Singleton();
return instance;
}
}
```
)
)
#note("Observer, publisher/subscriber",(
[
Uses a subject to notify observers of changes. Subject has a list of observers and notifies them when it changes. Observer has an update method that is called by the subject when it changes. Subject has methods to add and remove observers.
],
```java
interface IObservable { /* add, remove, notify */ }
class Observable implements IObservable {
private List<Observer> observers;
public void notifyObservers() { observers.forEach(o -> o.update()); }
}
interface IObserver { /* update */ }
class Observer implements IObserver {
private IObservable observable;
public Observer(IObservable o) { observable = o; }
public void update() { /* do something */ }
}
```,
))
#note("Proxy pattern",(
[
Uses a proxy to control access to an object. Proxy has the same interface as the object it is proxying. Proxy can be used to control access to the object, to cache the object, or to delay instantiation of the object.
],
```java
interface ISubject { /* doSomething */ }
class Subject implements ISubject { /* doSomething */ }
class Proxy implements ISubject {
private ISubject subject;
public Proxy(ISubject s) { subject = s; }
public void doSomething() { subject.doSomething(); }
}
```,
))
#note("Command pattern",(
[
Uses a command object to encapsulate a request. Command object has an execute method that is called by the invoker. Invoker has a setCommand method that sets the command to be executed.
],
```java
interface ICommand { /* execute */ }
class Command implements ICommand { /* execute */ }
class Invoker { /* ex. remote */
private ICommand command;
public void setCommand(ICommand c) { command = c; }
public void executeCommand() { command.execute(); }
}
```,
))
#note("Strategy pattern", (
[
Encapsulates behaviors into separate classes. Context has a strategy interface and a method to set the strategy. Context has a method to execute the strategy. This is done to allow for different behaviors to be used at runtime.
],
```java
interface IQuack { quack(); }
class QuackWithSound implements IQuack { /* execute */ }
class Context { /* ex. duck */
private IStrategy strategy;
public void setStrategy(IStrategy s) { strategy = s; }
public void executeStrategy() { strategy.execute(); }
}
```,
))
#grid(columns: (2fr, 1fr), gutter: 4pt,
image("design_patterns.png"),
note(
"Rational Unified Process",
[
*Inception:* Gather requirements, define project goals, identify risks and develop a project plan.
*Elaboration:* Develop a detailed project plan, identify use cases and develop a domain model.
*Construction:* Develop the system, run system tests and integrate the system.
*Transition:* Deploy the system, train users, and provide support.]
)
)
#note("Vision statement",
(
[
summary of purpose, reflection of stakeholder expectations, hopeful but realistic, and a guide for decision making.
],[
for [target customer(s)] who [need / opportunity], the [product name] is a [product category] that [key benefit, reason to buy]. Unlike [primary competitive alternative], our product [primary differentiation].w
]
)
)
#text(size: 7pt, grid(columns: 3, gutter: 6pt,
note("creator principle",
[
The responsibility of creating an object falls to the class that has the necessary information to do so.
ex. A Document class is responsible for creating new Page objects, as it has the necessary information about page layout and formatting.
],
delim: false
),
note("expert principle",
[
Responsibilities should be assigned to the class that holds the most relevant/complete information.
ex. A product class would be responsible for calculating its own price and discounts since it holds the most relevant info.
],
delim: false
),
note("fabrication principle", [
Creating complex objects should be delegated to a separate factory class or method.
ex. In a web application, a UserFactory class can be responsible for creating User objects with appropriate access levels and roles based on user credentials.
],
delim: false
),
note("high cohesion", [
A class should have a single responsibility and its methods should focus tightly on that responsibility.
ex. A Character class should only handle character-related functions like movement, attacks, and health management, rather than handling game logic or user input.
],
delim: false
),
note("low coupling", [
Minimizing dependencies between classes by designing loosely coupled relationships.
ex. Instead of directly accessing data within another class, use dependency injection or interfaces to avoid tight coupling.
],
delim: false
),
note("protected variations principle", [
When a class needs to be extended to accommodate variations, it should be done by creating subclasses rather than modifying the original class.
ex: A base Shape class can be extended to create specific shapes like Circle or Square allowing for variations without altering the base class.
],
delim: false
),
note("polymorphism", [
Objects should respond to the same method call in different ways based on their type.
ex. An Animal class can have a `makeSound()` method which returns 'woof' for a Dog object but 'meow' for a Cat object.
],
delim: false
),
note("indirection", [
introduces an intermediary layer between two classes to reduce direct coupling and provide flexibility in communication.
ex. A Controller class can act as an intermediary between a UI and DATA, handling user interactions and updating the view accordingly.
],
delim: false
),
note("controller principle", [
A separate controller class should be responsible for handling user interactions, managing application flow, and coordinating between other objects.
ex. In a web application, a UserController can handle user registration, login, and profile management, separating these tasks from the presentation layer (views) and data access layer (models).
],
delim: false
)
))
#text(size: 7pt, table(columns: 4,
[ Feature ],[ Unified Process (UP) ],[ Waterfall Model ],[ Agile Methodologies ],
[ Development approach ],[ Iterative and incremental ],[ Sequential ],[ Iterative and incremental],
[ Phases ],[ Inception, Elaboration, Construction, Transition ],[ Requirements, Design, Implementation, Testing, Deployment ],[ No defined phases, but with well-defined practices (e.g., Scrum, Kanban)],
[ Deliverables ],[ Working software at each phase ],[ Detailed documentation at each phase ],[ Working software increments],
[ Change management ],[ Extensible; changes can be accommodated at each phase ],[ Rigid; changes are difficult to implement after requirements are finalized ],[ Embraces change; changes are expected and welcomed],
[ Customer involvement ],[ High customer involvement ],[ Low customer involvement ],[ High customer involvement],
[ Documentation ],[ Detailed documentation ],[ Minimal documentation ],[ Minimal documentation],
[ Suitability ],[ Complex projects with changing requirements ],[ Well-defined projects with stable requirements ],[ Projects with uncertain requirements or where quick feedback is needed ]))
|
|
https://github.com/sabitov-kirill/os-distributed-systems-report | https://raw.githubusercontent.com/sabitov-kirill/os-distributed-systems-report/master/main.typ | typst | #import "template.typ": *
#import "@preview/codelst:2.0.0": sourcecode
#show: ams-article.with(
title: [Распределенные системы],
authors: (
(
name: "<NAME>",
department: [CT M3235],
organization: [Itmo University],
location: [Russia, St. Petersburg],
email: "<EMAIL>",
url: "t.me/ne1mnn"
),
),
abstract: [
В эру, когда технологический прогресс критически зависит от способности обрабатывать и анализировать огромные объемы данных, распределенные системы выступают в качестве краеугольного камня как
- в *пользовательской* среде - обучение моделей исскуственного интелекта в самых разных областях, серверные приложения с большим количеством сервисов, распределенные базы данных, blockchain
- так и в *научной* среде - обработке данных из экспериментов, таких как проводимые в Европейском центре ядерных исследований (CERN), где они используются для анализа результатов столкновений элементарных частиц, физически корректного моделирования в астрофизике, климатологии и других науках, где требуются сложные вычисления для моделирования и понимания явлений мира.
Таким образом, распределенные вычисления становятся не просто технологией, а основополагающим инструментом для дальнейшего развития и реализации технического прогресса, открывая новые горизонты в научных открытиях и пользовательском опыте. В связи с их значимостью и необходимостью для современного мира, *целью данной работы* является осветить основные моменты разработки данных технологий на примере уже известных подходов с точки зрения курса ОС.
],
)
#outline(title: [Содержание], depth: 2, indent: true)
= Концепции архитектуры распределенных систем
Перед более подробным рассмотрением подходов к реализации распределенных систем рассмотрим ключевые концепции их архитектур, а так же рассмотрим какие проблемы они решают:
== Совместное использование ресурсов
Концепция совместного использования ресурсов (Resource sharing) заключается в обеспечении совместного доступа к ресурсам, которые могут быть распределены по разным узлам системы. Разделение ресурсов позволяет улучшить эффективность использования ресурсов, обеспечивает масштабируемость и повышает доступность системы для пользователей.
Разделение ресурсов в распределенных системах предполагает, что ресурсы (как аппаратные --- хранилища данных, принтеры, сканеры, и т.д., так и программные) распределены по сети и доступны для использования разными узлами или клиентами. Это может включать в себя общий доступ к файлам, принтерам, информационным базам данных и другим ресурсам.
Преимущества такого подхода включают в себя:
- Экономию ресурсов: общий доступ к дорогостоящим ресурсам позволяет избежать необходимости дублирования этих ресурсов в каждом узле.
- Масштабируемость: распределенные системы легко масштабируются, так как добавление новых ресурсов или узлов не требует значительных изменений в архитектуре.
- Надежность и доступность: распределенные системы могут быть более устойчивыми к отказам. Если один узел выходит из строя, другие узлы могут продолжать работу.
- Упрощение совместной работы: позволяет географически разбросанным группам людей работать вместе, используя групповое программное обеспечение для совместного редактирования, телеконференций и т.д.
== Distribution transparency <distrib-transp>
Прозрачность распределения заключается в скрытии факта физического распределения процессов и ресурсов по множеству компьютеров, которые могут быть разделены большими расстояниями. Она делает распределение процессов и ресурсов невидимым для конечных пользователей и приложений. Достигается это с помощью так называемого промежуточного программного обеспечения (middleware) (более подробно об этом будет в #link(<middleware>)[следующей части]).
Различают разные аспекты прозрачности распределения, каждый из которых решает свои уникальные задачи:
- Прозрачность доступа (Access Transparency): Обеспечивает скрытие различий в доступе к локальным и удаленным ресурсам. Это позволяет пользователю обращаться к любым ресурсам, не заботясь о их физическом расположении.
- Прозрачность местоположения (Location Transparency): Скрывает физическое местоположение ресурсов и процессов в системе. Пользователи и приложения могут взаимодействовать с ресурсами, не зная их реального расположения.
- Прозрачность миграции (Migration Transparency): Позволяет перемещать ресурсы и компоненты внутри системы без влияния на работу пользователей. Это полезно для балансировки нагрузки и оптимизации производительности системы.
- Прозрачность репликации (Replication Transparency): Скрывает наличие копий (реплик) ресурсов или компонентов от пользователей и приложений. Это обеспечивает повышение доступности и отказоустойчивости системы.
- Прозрачность параллелизма (Concurrency Transparency): Позволяет нескольким процессам работать с ресурсами параллельно, скрывая от них детали синхронизации доступа.
- Прозрачность отказов (Failure Transparency): Способность системы скрывать отказы отдельных компонентов, обеспечивая непрерывную работу приложений.
Так же важно упомянуть, что Distribution transparency применимо не всегда, например может быть существеннен факт различия в часовых поясах узла системы и конечного пользователя, что не возможно определить, если считать все узлы единым целым.
== Промежуточный уровень (Middleware) <middleware>
Middleware в контексте распределенных систем - это программное обеспечение, которое обеспечивает связь и управление данными между различными частями распределенной системы. Его главная роль - облегчить сложность взаимодействия между компонентами системы, предоставляя абстракцию и управление ресурсами.
Исторически, развитие middleware связано с потребностью в эффективном управлении распределенными системами и решением проблем, связанных с гетерогенностью оборудования и программного обеспечения. Middleware позволяет разным приложениям и системам взаимодействовать друг с другом, скрывая техническую сложность и различия в сетевых протоколах, платформах и языках программирования.
Это решает проблемы, связанные с интеграцией различных систем, обеспечением безопасности, управлением транзакциями и предоставлением универсального доступа к ресурсам и службам. В современном контексте, middleware играет ключевую роль в облегчении создания и управления сложными распределенными системами, такими как облачные вычисления, большие данные и интернет вещей. Проще говоря middleware обеспечивает #link(<distrib-transp>)[Distribution transparency].
#align(center)[
#image("images/distrib-transp-scheme.png", width: 250pt)\
_Использования промежуточного уровня (middleware) для достижения прозрачности доступа_
]
Теперь рассмотрим организацию промежуточного уровня, для этого чаще всего используют 2 паттерна --- _wrapper_, _interceptor_, выполняющих различные задачи.
=== Wrappers
Обертки (wrappers) -- паттерн построения middleware распределенных систем, для интеграции существующих компонентов с разными интерфейсами. Они обеспечивают адаптацию интерфейсов, позволяя клиентским приложениям взаимодействовать с различными компонентами системы. Это решает проблему несовместимости интерфейсов, трансформируя функции клиентского приложения в те, которые доступны в компоненте.
В контексте распределенных систем обертки выходят за рамки простых трансформаторов интерфейсов. Например, адаптер объекта может позволить приложениям вызывать удаленные объекты, реализованные с помощью библиотечных функций, работающих с таблицами реляционной базы данных.
Для уменьшения количества оберток, используется middleware и такие компоненты, как брокеры. Брокер - это централизованный компонент, который обрабатывает доступ к различным приложениям. Например, брокер сообщений, описанный в разделе 4.3.3, принимает запросы от приложений и обеспечивает необходимое взаимодействие и трансформацию данных. Это позволяет сократить количество необходимых оберток с $O(N^2)$ до $O(N)$, упрощая масштабирование и интеграцию в распределенных системах.
#align(center)[
#image("images/broker.png", width: 250pt)
_(a). Обертка для доступа приложений к функционалу других узлов.\
(b). Использование брокера.
_
]
=== Interceptors <interceptors>
Перехватчики (interceptors) являются важным паттерном, позволяющим адаптировать middleware к конкретным потребностям приложений. Прерывания изменяют обычный поток управления и позволяют выполнять специфический для приложения код, что делает middleware позволяют выполнять спецефичные для приложения задачи, делая его более #link(<openness>)[открытым].
Что бы более детально разобраться в том, как перехватыватели выполняют поставленную задачу рассмотрим процесс обработки вызова методов удаленного узла:
#align(center)[
#image("images/interceptors.png")
_Схема применения перехватчиков, для реализации обработки вызова методов удаленного узла._
]
+ Клиентское приложение инициирует вызов метода (например, B.doit(val)), предназначенного для объекта B.
+ Request-level interceptor перехватывает этот вызов и может, например, дублировать его, если объект B реплицирован.
+ Затем вызов трансформируется в универсальный объектный вызов (например, invoke(B, &doit, val)), который может быть обработан middleware.
+ Message-level interceptor может вмешаться на этапе формирования сетевого сообщения, например, для фрагментации больших данных перед отправкой через сетевой интерфейс локальной ОС.
Request-level interceptor обеспечивает уровень абстракции, где можно управлять запросами на более высоком уровне, например, для балансировки нагрузки или репликации.
Message-level interceptor работает на более низком уровне, близком к передаче данных, и может оптимизировать или модифицировать пакеты данных перед их отправкой по сети.
== Открытость <openness>
Открытость (openness) в распределённых системах означает создание системы с компонентами, которые легко интегрируются в другие системы или могут быть использованы ими. Эти системы часто состоят из компонентов, взятых из других систем. Открытость подразумевает соответствие компонентов стандартным правилам, описывающим их синтаксис и семантику предоставляемых услуг, обычно с использованием языка описания интерфейса (IDL). Однако сложность заключается в точном определении семантики интерфейсов, которая часто формулируется неформально.
Для достижения открытости часто используется:
- Применение #link(<interceptors>)[перехватчиков], что позволяет различным реализациям систем или компонентов взаимодействовать, опираясь только на стандартизированные сервисы. Опыт показывает, что это позволяет приложениям быть исполнененым на другой системе с теми же интерфейсами (переносимость).
- Проектирование таким образом, что бы сисема могла легко настраиваться из разных компонентов и позволять добавлять новые или заменять существующие без воздействия на оставшиеся. Примером расширяемости могут служить плагины для веб-браузеров или систем управления содержимым вебсайтов.
Для этого важно разделять политику (policy) от механизма, что и позволяет менять части без воздействия на всю систему. Такой подход противоположен монолитным системам, которые обычно закрыты и менее гибки.
В идеале, открытая система должна предоставлять механизмы, позволяя пользователям или разработчикам определять политику их использования. Это может быть реализовано через определение набора параметров или возможность интеграции пользовательских политик. Пример параметров для определения политики:
+ Хранение: Определяет, где кешировать данные, например, в памяти или на диске.
+ Исключение: Какие данные удалять из кеша, когда он заполняется.
+ Общий доступ: Будет ли кеш общим между пользователями или приватным для каждого.
+ Обновление: Когда система должна проверять актуальность данных в кеше.
== Расширяемость
Расширяемость (scalability) в распределённых системах описывает способность системы эффективно масштабироваться в трёх измерениях: размер, географическое распределение и административные границы. Размерная расширяемость позволяет системе поддерживать увеличение числа пользователей и ресурсов без потери производительности. Географическая расширяемость позволяет пользователям и ресурсам эффективно взаимодействовать на большие расстояния. Административная расширяемость относится к способности системы оставаться управляемой, даже если она охватывает множество независимых административных организаций.
Техники масштабирования включают скрытие задержек коммуникации, распределение работы и репликацию. Скрытие задержек помогает в географической расширяемости, позволяя выполнять другие задачи, пока ожидается ответ от удалённого сервиса. Распределение работы может включать разделение компонентов или ресурсов на более мелкие части и их распределение по системе. Репликация увеличивает доступность и может помочь сбалансировать нагрузку, улучшая производительность и сокращая задержки коммуникации.
= Архитектурные стили для распределенных систем
Архитектурный стиль распределенной системы определяется компонентами, способами их соединения, обмена данными и конфигурации в целостную систему. Ключевым элементом архитектуры является компонент - модульный блок с определенными интерфейсами, который может быть заменен без остановки всей системы. Это особенно важно, поскольку во многих случаях невозможно полностью остановить систему для обслуживания или обновления.
Другим важным элементом архитектуры является коннектор - механизм, который обеспечивает связь и взаимодействие между компонентами, например, через удаленные вызовы процедур, передачу сообщений или потоковые данные.
Существует несколько архитектурных стилей для распределенных систем, среди которых наиболее значимыми являются:
- Слоистые архитектуры, где система делится на логические слои с определенными функциями.
- Сервис-ориентированные архитектуры, фокусирующиеся на предоставлении сервисов как основных строительных блоков.
- Архитектуры на основе публикации-подписки, где компоненты взаимодействуют через обмен сообщениями.
В реальных распределенных системах часто применяется комбинация нескольких архитектурных стилей, особенно распространена практика использования слоистого подхода в сочетании с другими стилями. Это обеспечивает гибкость и масштабируемость системы, позволяя ей адаптироваться к различным требованиям и условиям эксплуатации.
Далее мы более подробно рассмотрим каждый из этих стилей, их особенности и применение в создании эффективных распределенных систем.
== Слоистая архитектура
Слоистая архитектура является одним из ключевых стилей в проектировании распределенных систем. Этот стиль характеризуется организацией компонентов системы в виде иерархических слоев, где каждый слой предназначен для выполнения определенного набора функций и взаимодействует только со слоями, расположенными непосредственно выше или ниже.
=== Основные принципы слоистой архитектуры:
1. *Вертикальная организация компонентов*: Компоненты распределены по слоям, причем каждый слой обслуживает определенный уровень абстракции или функциональности. Компонент в слое $L_j$ может вызывать (делать downcall) компонент в более низком слое $L_i$ (где $i < j$), ожидая от него ответа.
2. *Ограниченное взаимодействие между слоями*: Как правило, компоненты общаются только с соседними слоями. То есть компонент в определенном слое может взаимодействовать с компонентами в непосредственно прилегающих слоях - ниже или выше.
3. *Исключения в коммуникации*: В некоторых случаях допускаются так называемые upcalls - вызовы компонентами нижнего слоя к компонентам более высокого слоя. Это бывает полезно, например, когда операционная система должна уведомить приложение о каком-либо событии.
Слоистая архитектура облегчает понимание, тестирование и поддержку системы за счет четкой структуризации и разделения ответственности между слоями. Она также обеспечивает гибкость в изменении или замене отдельных компонентов системы без влияния на другие части.
=== Пример приложения
Для лучшего понимания того, что из себя представляет приложение со слоистой архитектуре рассмотрим простейшее приложение на языке C под Linux. Каждый слой отвечает за определенный аспект работы приложения и взаимодействует только с соседними слоями. В качестве примера, давайте рассмотрим простое клиент-серверное приложение, где сервер обрабатывает запросы клиента.
==== Структура Директории
```
server/
├── network_layer.c
├── network_layer.h
├── business_logic.c
├── business_logic.h
└── main.c
client/
├── network_layer.c
├── network_layer.h
├── presentation_layer.c
├── presentation_layer.h
└── main.c
```
==== Реализация
===== *Слой Сетевого Взаимодействия (Сетевой Слой)*: Устанавливает и управляет сетевыми соединениями
- Отвечает за создание сокета (`socket()`).
- Привязывает сокет к адресу и порту (`bind()`).
- Слушает входящие соединения (`listen()` и `accept()`).
*network_layer.h*
#sourcecode[```c
#ifndef NETWORK_LAYER_H
#define NETWORK_LAYER_H
#include <netinet/in.h>
int initialize_server_socket(int port);
int accept_connection(int server_fd, struct sockaddr_in *address);
#endif
```]
*network_layer.c*
#sourcecode[```c
#include "network_layer.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
int initialize_server_socket(int port) {
int server_fd;
struct sockaddr_in address;
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
return server_fd;
}
int accept_connection(int server_fd, struct sockaddr_in *address) {
int addrlen = sizeof(*address);
int new_socket = accept(server_fd, (struct sockaddr *)address, (socklen_t*)&addrlen);
if (new_socket < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
return new_socket;
}
```]
===== *Слой Бизнес-Логики (Логический Слой)*: Обрабатывает данные, полученные от клиента, и формирует ответ
Функция processData() является частью этого слоя.
Обрабатывает данные, полученные от клиента.
Генерирует ответ на основе бизнес-правил или логики.
*business_logic.h*
#sourcecode[```c
#ifndef BUSINESS_LOGIC_H
#define BUSINESS_LOGIC_H
void process_data(const char *input, char *output);
#endif
```]
*business_logic.c*
#sourcecode[```c
#include "business_logic.h"
#include <ctype.h>
void process_data(const char *input, char *output) {
int i = 0;
while (input[i] != '\0') {
output[i] = toupper(input[i]); // Преобразование в верхний регистр
i++;
}
output[i] = '\0';
}
```]
===== *Слой Данных (Data Layer):* Хотя в данном примере он неявно представлен, он может быть использован для управления данными, такими как доступ к базе данных или файловой системе.
===== *main.c* (Точка входа)
#sourcecode[```c
#include "network_layer.h"
#include "business_logic.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
char buffer[BUFFER_SIZE] = {0};
char response[BUFFER_SIZE] = {0};
int server_fd = initialize_server_socket(PORT);
struct sockaddr_in address;
int new_socket = accept_connection(server_fd, &address);
read(new_socket, buffer, BUFFER_SIZE);
printf("Received: %s\n", buffer);
process_data(buffer, response);
send(new_socket, response, strlen(response), 0);
printf("Response sent: %s\n", response);
close(new_socket);
close(server_fd);
return 0;
}
```
]
Этот код демонстрирует разделение на слои в приложении. В реальном проекте слои могут быть более сложными и включать дополнительную функциональность, а так же скорее всего Слоистая архитектура будет использована в месте с другими архитектурными стилями.
#pagebreak()
== Сервис-ориентированная архитектура (SOA)
=== Основные Принципы
Сервис-ориентированная архитектура (SOA) представляет собой архитектурный стиль, в котором приложения состоят из отдельных, независимых сервисов, каждый из которых инкапсулирует определенную функциональность. Эти сервисы могут быть реализованы в виде объектов, микросервисов или других независимых единиц, выполняемых как отдельные процессы или потоки.
=== Ключевые Характеристики
+ *Инкапсуляция Сервисов:* Каждый сервис представляет собой самодостаточную сущность, которая может взаимодействовать с другими сервисами, но также может функционировать автономно.
+ *Объектно-ориентированный Подход:* В основе SOA лежит объектно-ориентированный дизайн, где каждый объект (или компонент) инкапсулирует состояние и методы, предоставляя четко определенный интерфейс для взаимодействия с другими объектами.
+ *Распределенные Объекты и Прокси:* В распределенных системах объект может быть физически расположен на одной машине, в то время как его интерфейс доступен на другой. При этом используются прокси и скелетоны (стабы) для маршалинга вызовов методов и обмена данными между клиентом и сервером.
+ *Микросервисы:* SOA может включать концепцию микросервисов, где каждый микросервис представляет собой отдельный процесс, выполняющий конкретную функцию. Микросервисы подчеркивают модульность и независимость.
=== Преимущества и Недостатки
Сервис-ориентированная архитектура имеет достаточно спецефичные аспекты, в следствии этого предлагается ознакомиться с ее преимуществами и недостатками.
==== Преимущества:
+ Модульность и Гибкость: Разделение функциональности на отдельные сервисы облегчает разработку, тестирование, развертывание и масштабирование.
+ Возможность Интеграции: SOA позволяет легко интегрировать и комбинировать сервисы разных производителей и технологий.
+ Улучшенное Управление Зависимостями: Снижается прямая зависимость между различными компонентами системы.
==== Недостатки:
+ Сложность Управления: Управление множеством сервисов и их взаимодействиями может быть сложным.
+ Производительность: Взаимодействие между сервисами через сеть может влиять на производительность.
+ Сложность Интеграции: Хотя SOA облегчает интеграцию, она также может привести к сложным сценариям интеграции и управления данными.
== Архитектура на основе публикации-подписки
Архитектура на основе публикации-подписки представляет собой подход к построению распределенных систем, где взаимодействие между процессами или компонентами системы минимизирует прямые зависимости. Это достигается за счет использования модели, в которой процессы автономно функционируют, публикуя события (сообщения) и подписываясь на интересующие их события.
=== Характеристики
1. *Разделение обработки и координации*: Процессы в системе работают автономно, а координация (коммуникация и сотрудничество) достигается через механизмы публикации и подписки.
2. *Временное и ссылочное разделение*: Процессы могут быть временно развязаны (не нуждаются в одновременной работе) и/или ссылочно развязаны (не знают друг о друге явно).
3. *Модели координации*:
- *Прямая координация*: Процессы временно и ссылочно связаны, например, прямое общение через телефон.
- *Координация через почтовый ящик*: Процессы временно развязаны, но ссылочно связаны. Общение происходит через обмен сообщениями, которые хранятся в почтовом ящике.
- *Событийно-ориентированная координация*: Процессы временно связаны, но ссылочно развязаны. Процессы публикуют уведомления о событиях, на которые подписываются другие процессы.
4. *Общие пространства данных (Shared Data Space)*: Процессы общаются через обмен данными, структурированными в виде кортежей (tuples). Процессы могут извлекать или добавлять кортежи, соответствующие определенным критериям поиска.
=== Примеры и Применение
- *Событийно-ориентированная система*: Процессы публикуют уведомления о событиях и подписываются на интересующие их типы уведомлений. Это может использоваться в системах обработки потоков данных, системах управления событиями и т.д.
- *Системы с общими пространствами данных*: Процессы обмениваются данными через общее пространство, где данные представлены в виде кортежей. Это может использоваться в системах, где необходимо эффективно обмениваться и обрабатывать большие объемы данных, например, в распределенных базах данных или системах управления потоками информации.
#align(center)[
#image("images/events.png")
_(a). Событийно-ориентированная система. \
(b). Системы с общими пространствами данных.
_
]
= Высокопроизводительные распределенные системы
Высокопроизводительные вычисления начались с введения мультипроцессорных систем, где несколько ЦПУ организованы таким образом, что все они имеют доступ к одной и той же физической памяти. Эта модель была удобной для улучшения производительности программ и относительно простой в программировании. Однако она обладает ограниченной масштабируемостью, особенно в контексте систем с множеством ядер.
Для преодоления ограничений систем с общей памятью высокопроизводительные вычисления перешли к использованию систем с распределенной памятью. Это требовало перехода от моделей с общей памятью к моделям передачи сообщений для коммуникации и синхронизации между потоками. К сожалению, модели передачи сообщений оказались более сложными и подвержены ошибкам по сравнению с моделями программирования с общей памятью.
Исследования в области распределенной общей памяти (DSM) были направлены на создание систем, позволяющих процессору обращаться к памяти на другом компьютере, как если бы она была локальной. Это достигалось за счет *техник, доступных операционной системе*, например, путем отображения всех страниц основной памяти различных процессоров в одно виртуальное адресное пространство. Однако попытки воссоздать системы с общей памятью с использованием мультикомпьютеров в конечном итоге были оставлены из-за несоответствия ожидаемой производительности, и программисты предпочли более сложные, но предсказуемо работающие модели передачи сообщений.
В современном мире высокопроизводительные распределенные системы могут быть разделены на две основные подгруппы:
+ Кластерные
+ Распределенные (Grid)
== Кластерные архитектуры
=== Развитие и Популярность
Кластерные вычислительные системы стали популярными с улучшением соотношения цены и производительности персональных компьютеров и рабочих станций. Построение суперкомпьютеров с использованием доступных в массовом производстве технологий путем объединения простых компьютеров в высокоскоростную сеть стало финансово и технически привлекательным. Кластерные вычисления обычно используются для параллельного программирования, при котором одна ресурсоемкая программа выполняется параллельно на нескольких машинах.
Таким образом кластерные вычислительные системы представляют собой ключевую часть высокопроизводительных вычислительных сред, обеспечивая мощные ресурсы для обработки сложных вычислительных задач. Благодаря использованию стандартных компонентов и оптимизированных сетевых технологий, они обеспечивают гибкость, масштабируемость и эффективность, необходимые для современных научных и инженерных исследований. Важно отметить, что кластерные системы продолжают развиваться, адаптируясь к новым технологическим трендам и потребностям пользователей.
=== Организация
В современных суперкомпьютерах, организованных в виде кластеров, используются конфигурации с более чем 100 000 ЦПУ, каждый из которых имеет 8 или 16 ядер. Существуют несколько сетей, наиболее важной из которых является сеть, образованная выделенными высокоскоростными взаимосвязями между различными узлами. Для управления и контроля организации и работы системы используется отдельная управляющая сеть, а также узлы.
=== Управление и Эксплуатация
Управляющий узел обычно отвечает за сбор заданий от пользователей и распределение связанных задач между различными вычислительными узлами. В практике при работе с очень крупными кластерами используются несколько управляющих узлов. Таким образом, управляющий узел выполняет программное обеспечение, необходимое для выполнения программ и управления кластером, в то время как вычислительные узлы оснащены стандартной операционной системой, расширенной типичными функциями для коммуникации, хранения, обеспечения отказоустойчивости и так далее.
=== Роль Операционной Системы
Существует четкая тенденция к минимизации операционной системы до легковесных ядер, чтобы обеспечить минимально возможные накладные расходы. Однако недостатком таких операционных систем является то, что они становятся высокоспециализированными и точно настроенными на базовое оборудование. Эта специализация влияет на совместимость или открытость системы. В качестве компенсации наблюдается постепенный переход к так называемым мультиядерным подходам, при которых полноценная операционная система работает рядом с легковесными ядрами (чаще всего в контейнерах), обеспечивая сочетание лучших качеств обеих систем. Эта комбинация становится необходимой, особенно в свете требований к одновременному выполнению множества независимых задач на высокопроизводительных вычислительных узлах. На сегодняшний день 95% всех высокопроизводительных компьютеров работают на системах, основанных на Linux; мультиядерные подходы разрабатываются для многоядерных ЦПУ, где большинство ядер процессора исполняют легковесные ядра Linux, и лишь малая часть - стандартную систему Linux. Это позволяет поддерживать новые разработки, такие как контейнеры. Влияние этих нововведений на вычислительную производительность невозможно преуменьшить.
#align(center)[
#image("images/cluster.png")
_Пример организации кластерной архитектуры._
]
== Grid - архитектуры
Grid-вычисления представляют собой уникальный подход к распределенным системам, позволяя объединять ресурсы из различных административных доменов для совместной работы и исследований. Благодаря своей гибкости и масштабируемости, они обеспечивают мощную инфраструктуру для сложных вычислительных задач, расширяя границы научного исследования и сотрудничества.
Они характеризуются высокой гетерогенностью, в отличие от традиционных кластерных систем, которые часто представляют собой однородную среду. В grid-системах нет предположений о сходстве оборудования, операционных систем, сетей, административных доменов, политик безопасности и т.д. Эти системы часто состоят из децентрализованных, федеративно объединенных компьютерных систем, каждая из которых может быть под управлением различных административных доменов и использовать различное оборудование и технологии.
=== Организация
Одной из ключевых задач в grid-вычислениях является объединение ресурсов от разных организаций для совместной работы группы людей из различных учреждений, формируя так называемую виртуальную организацию. Процессы, принадлежащие к одной виртуальной организации, имеют доступные права к предоставленным ресурсам, которые могут включать вычислительные серверы (включая суперкомпьютеры, возможно, реализованные как кластерные компьютеры), хранилища данных, базы данных, а также специальные сетевые устройства, такие как телескопы, сенсоры и т.д.
=== Слоистая Архитектура Grid-Вычислений
Архитектура grid-вычислений состоит из четырех уровней:
1. *Нижний Уровень (Fabric Layer)*: Обеспечивает интерфейсы к локальным ресурсам на конкретном сайте, предназначенные для совместного использования ресурсов в рамках виртуальной организации.
2. *Уровень Соединяемости (Connectivity Layer)*: Содержит коммуникационные протоколы для поддержки транзакций в grid, охватывающих использование множества ресурсов, включая протоколы передачи данных и доступа к ресурсам издалека, а также протоколы безопасности для аутентификации пользователей и ресурсов.
3. *Ресурсный Уровень (Resource Layer)*: Отвечает за управление отдельным ресурсом, использует функции, предоставляемые уровнем соединяемости, и напрямую обращается к интерфейсам, предоставляемым нижним уровнем. Этот уровень отвечает за контроль доступа к ресурсам, полагаясь на аутентификацию, выполняемую на уровне соединяемости.
4. *Коллективный Уровень (Collective Layer)*: Занимается управлением доступом к множественным ресурсам и обычно включает в себя услуги по обнаружению ресурсов, распределению и планированию задач на нескольких ресурсах, репликации данных и т.д. В отличие от уровней соединяемости и ресурсов, коллективный уровень может состоять из множества протоколов, отражающих широкий спектр услуг, которые он может предложить виртуальной организации.
=== Приложения и Программное Обеспечение
На самом верхнем уровне находится прикладной уровень, который состоит из приложений, работающих в рамках виртуальной организации и использующих среду grid-вычислений. Коллективный, соединительный и ресурсный уровни в совокупности образуют ядро того, что можно назвать промежуточным программным обеспечением grid (grid middleware). Эти уровни совместно обеспечивают доступ к ресурсам и управление ими, которые могут быть распределены по нескольким сайтам.
=== Перспектива Промежуточного ПО и SOA
Важное наблюдение с точки зрения промежуточного программного обеспечения заключается в том, что в grid-вычислениях понятие сайта (или административной единицы) является общепринятым. Это подчеркивается постепенным переходом к сервис-ориентированной архитектуре (SOA), в которой сайты предоставляют доступ к различным уровням через коллекцию веб-сервисов. Это привело к определению альтернативной архитектуры, известной как Open Grid Services Architecture (OGSA), основанной на первоначальных идеях Фостера и др. (2001), но прошедшей процесс стандартизации. Реализации OGSA обычно следуют стандартам веб-сервисов.
#pagebreak()
= Ссылки
+ <NAME>, <NAME> - "DISTRIBUTED SYSTEMS" (4th edition, 2023).
+ <NAME>, and others - "DISTRIBUTED SYSTEMS. Concepts and Design" (5th edition, 2012).
+ https://en.wikipedia.org/wiki/Distributed_computing
+ <NAME>; <NAME> - "A Practical Approach to High-Performance Computing" (2019). SpringerLink. DOI: 10.1007/978-3-030-27558-7.
+ https://habr.com/ru/companies/alconost/articles/522662/
+ #link("https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%89%D0%B8%D0%B9_%D1%80%D0%B5%D1%81%D1%83%D1%80%D1%81")[https://ru.wikipedia.org/wiki/Общий_ресурс] |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-rect-00.typ | typst | Other | // Default rectangle.
#rect()
|
https://github.com/flavio20002/cyrcuits | https://raw.githubusercontent.com/flavio20002/cyrcuits/main/tests/rc2/test.typ | typst | Other | #import "../../lib.typ": *
#set page(width: auto, height: auto, margin: 0.5cm)
#show: doc => cyrcuits(
scale: 1,
doc,
)
```circuitkz
\begin{circuitikz}
\draw (0,0)
to[battery1,l=$E$] ++ (0,2)
to[R,l=$R_1$] ++ (0,2)
to[short,-*] ++ (2,0) coordinate (aux1)
to[R,l_=$R_2$] ++(0,-4)
to[short,*-] ++ (-2,0);
\draw (aux1)
to[short,*-] ++ (2,0)
to[C,l_=$C$] ++(0,-4)
to[short] ++(-2,0);
\end{circuitikz}
```
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/src/edge.typ | typst | MIT License | #import "utils.typ": *
#import "marks.typ": *
#import "coords.typ": vector-polar-with-xy-or-uv-length, resolve, default-ctx
#let EDGE_FLAGS = (
"dashed": (dash: "dashed"),
"dotted": (dash: "dotted"),
"double": (extrude: (-2, +2)),
"triple": (extrude: (-4, 0, +4)),
"crossing": (crossing: true),
"wave": (decorations: "wave"),
"zigzag": (decorations: "zigzag"),
"coil": (decorations: "coil"),
)
#let LINE_ALIASES = (
"-": (:),
"=": EDGE_FLAGS.double,
"==": EDGE_FLAGS.triple,
"--": EDGE_FLAGS.dashed,
"..": EDGE_FLAGS.dotted,
"~": EDGE_FLAGS.wave,
)
#let MARK_SYMBOL_ALIASES = (
(sym.arrow.r): "->",
(sym.arrow.l): "<-",
(sym.arrow.r.l): "<->",
(sym.arrow.long.r): "->",
(sym.arrow.long.l): "<-",
(sym.arrow.long.r.l): "<->",
(sym.arrow.double.r): "=>",
(sym.arrow.double.l): "<=",
(sym.arrow.double.r.l): "<=>",
(sym.arrow.double.long.r): "=>",
(sym.arrow.double.long.l): "<=",
(sym.arrow.double.long.r.l): "<=>",
(sym.arrow.r.tail): ">->",
(sym.arrow.l.tail): "<-<",
(sym.arrow.twohead): "->>",
(sym.arrow.twohead.r): "->>",
(sym.arrow.twohead.l): "<<-",
(sym.arrow.bar): "|->",
(sym.arrow.bar.double): "|=>",
(sym.arrow.hook.r): "hook->",
(sym.arrow.hook.l): "<-hook'",
(sym.arrow.squiggly.r): "~>",
(sym.arrow.squiggly.l): "<~",
(sym.arrow.long.squiggly.r): "~>",
(sym.arrow.long.squiggly.l): "<~",
)
#let interpret-marks(marks) = {
marks = marks.enumerate().map(((i, mark)) => {
resolve-mark(mark, defaults: (
pos: i/calc.max(1, marks.len() - 1),
rev: i == 0,
))
}).filter(mark => mark != none) // drop empty marks
marks = marks.map(mark => {
mark.tip = (mark.pos == 0) == mark.rev
if (mark.pos not in (0, 1)) { mark.tip = none }
mark
})
marks
}
/// Parse and interpret the marks argument provided to `edge()`. Returns a
/// dictionary of processed `edge()` arguments.
///
/// - arg (string, array):
/// Can be a string, (e.g. `"->"`, `"<=>"`), etc, or an array of marks.
/// A mark can be a string (e.g., `">"` or `"head"`, `"x"` or `"cross"`) or a dictionary containing the keys:
/// - `kind` (required) the mark name, e.g. `"solid"` or `"bar"`
/// - `pos` the position along the edge to place the mark, from 0 to 1
/// - `rev` whether to reverse the direction
/// - parameters specific to the kind of mark, e.g., `size` or `sharpness`
/// -> dictiony
#let interpret-marks-arg(arg) = {
if type(arg) == array { return (marks: interpret-marks(arg)) }
if type(arg) == symbol {
if str(arg) in MARK_SYMBOL_ALIASES { arg = MARK_SYMBOL_ALIASES.at(arg) }
else { error("Unrecognised marks symbol #.", arg) }
}
assert(type(arg) == str)
let text = arg
let mark-names = MARKS.get().keys().sorted(key: i => -i.len())
let LINES = LINE_ALIASES.keys().sorted(key: i => -i.len())
let eat(arg, options) = {
for option in options {
if arg.starts-with(option) {
return (arg.slice(option.len()), option)
}
}
return (arg, none)
}
let marks = ()
let lines = ()
let mark
let line
let flip
// first mark, [<]-x->>
(text, mark) = eat(text, mark-names)
// flip modifier, hook[']
(text, flip) = eat(text, ("'",))
if flip != none { mark += flip }
marks.push(mark)
let parse-error(suggestion) = error("Invalid marks shorthand #0. Try #1.", arg, suggestion)
while true {
// line, <[-]x->>
(text, line) = eat(text, LINES)
if line == none {
let suggestion = arg.slice(0, -text.len()) + "-" + text
parse-error(suggestion)
}
lines.push(line)
// subsequent mark, <-[x]->>
(text, mark) = eat(text, mark-names)
// flip modifier, hook[']
(text, flip) = eat(text, ("'",))
if flip != none { mark += flip }
marks.push(mark)
if text == "" { break }
if mark == none {
// text remains that was not recognised as mark
let suggestion = marks.intersperse(lines.at(0)).join()
parse-error(suggestion)
}
}
if lines.dedup().len() > 1 {
// different line styles were mixed
let suggestion = marks.intersperse(lines.at(0)).join()
parse-error(suggestion)
}
let line = lines.at(0)
// make classic math arrows slightly larger on double/triple stroked lines
if line == "=" {
marks = marks.map(mark => {
if mark == none { return }
(
">": (inherit: "doublehead", rev: false),
"<": (inherit: "doublehead", rev: true),
).at(mark, default: mark)
})
} else if line == "==" {
marks = marks.map(mark => {
if mark == ">" { (inherit: "triplehead", rev: false) }
else if mark == "<" { (inherit: "triplehead", rev: true) }
else {mark}
})
}
return (
marks: interpret-marks(marks),
..LINE_ALIASES.at(lines.at(0))
)
}
/// Interpret the positional arguments given to an `edge()`
///
/// Tries to intelligently distinguish the `from`, `to`, `marks`, and `label`
/// arguments based on the argument types.
///
/// Generally, the following combinations are allowed:
///
/// ```
/// edge(..<coords>, ..<marklabel>, ..<options>)
/// <coords> = () or (to) or (from, to) or (from, ..vertices, to)
/// <marklabel> = (marks, label) or (label, marks) or (marks) or (label) or ()
/// <options> = any number of options specified as strings
/// ```
#let interpret-edge-args(args, options) = {
if args.named().len() > 0 {
error("Unexpected named argument(s) #..0.", args.named().keys())
}
let new-options = (:)
let pos = args.pos()
// predicates to detect the kind of a positional argument
let is-coord(arg) = type(arg) in (array, dictionary, label) or arg == auto
let is-rel-coord(arg) = is-coord(arg) or (
type(arg) == str and arg.match(regex("^[utdblrnsew,]+$")) != none
)
let is-arrow-symbol(arg) = type(arg) == symbol and str(arg) in MARK_SYMBOL_ALIASES
let is-edge-flag(arg) = type(arg) == str and arg in EDGE_FLAGS
let is-label-side(arg) = type(arg) == alignment
let maybe-marks(arg) = type(arg) == str and not is-edge-flag(arg) or is-arrow-symbol(arg)
let maybe-label(arg) = type(arg) != str and not is-arrow-symbol(arg) and not is-coord(arg)
let peek(x, ..predicates) = {
let preds = predicates.pos()
x.len() >= preds.len() and x.zip(preds).all(((arg, pred)) => pred(arg))
}
let assert-not-set(key, default, ..value) = {
if options.at(key) == default { return }
error(
"#0 specified twice with positional argument(s) #..pos and named argument #named.",
key, pos: value.pos().map(repr), named: repr(options.at(key)),
)
}
let coords = ()
let has-first-coord = false
let has-tail-coords = false
// First argument(s) are coordinates
// (<coord>, <rel-coord>*) => (<coord>, <rel-coord>*)
// (<rel-coord>*) => (auto, <rel-coord>*)
if peek(pos, is-coord) {
coords.push(pos.remove(0))
has-first-coord = true
}
while peek(pos, is-rel-coord) {
if type(pos.at(0)) == str {
coords += pos.remove(0).split(",")
} else {
coords.push(pos.remove(0))
}
has-tail-coords = true
}
// Allow marks argument to be in between two coordinates
// (<coord>, <marks>, <rel-coord>)
// (<marks>, <rel-coord>) => (auto, <marks>, <rel-coord>)
if not has-tail-coords and peek(pos, maybe-marks, is-rel-coord) {
new-options.marks = pos.remove(0)
assert-not-set("marks", (), new-options.marks)
coords.push(pos.remove(0))
has-tail-coords = true
if peek(pos, is-rel-coord) {
error("Marks argument #0 must appear after edge vertices (or between them if there are only two).", repr(new-options.marks))
}
}
if coords.len() > 0 or options.vertices.len() == 0 {
assert-not-set("vertices", (), ..coords)
if not has-tail-coords { coords = (auto, ..coords) }
if not has-first-coord { coords = (auto, ..coords) }
new-options.vertices = coords
}
// Allow label side argument anywhere after coordinates
let i = pos.position(is-label-side)
if i != none {
new-options.label-side = pos.remove(i)
assert-not-set("label-side", auto, new-options.label-side)
}
// Accept marks and labels after vertices
// (.., <marks>, <label>)
// (.., <label>, <marks>)
let marks
let label
if peek(pos, maybe-marks, maybe-label) {
marks = pos.remove(0)
label = pos.remove(0)
} else if peek(pos, maybe-label, maybe-marks) {
label = pos.remove(0)
marks = pos.remove(0)
} else if peek(pos, maybe-label) {
label = pos.remove(0)
} else if peek(pos, maybe-marks) {
marks = pos.remove(0)
}
if marks != none {
if "marks" in new-options {
error("Marks argument passed to `edge()` twice; found #0 and #1.", repr(new-options.marks), repr(marks))
}
assert-not-set("marks", (), marks)
new-options.marks = marks
}
if label != none {
assert-not-set("label", none, label)
new-options.label = label
}
// Accept any trailing positional strings as option shorthands
while peek(pos, is-edge-flag) {
new-options += EDGE_FLAGS.at(pos.remove(0))
}
if pos.len() > 0 {
error("Couldn't interpret `edge()` arguments #..0. Try using named arguments. Interpreted previous arguments as #1", pos, new-options)
}
new-options
}
/// Draw a connecting line or arc in an arrow diagram.
///
///
/// - ..args (any): An edge's positional arguments may specify:
/// - the edge's #param[edge][vertices], each specified with a CeTZ-style coordinate
/// - the #param[edge][label] content
/// - arrow #param[edge][marks], like `"=>"` or `"<<-|-o"`
/// - other style flags, like `"double"` or `"wave"`
///
/// Vertex coordinates must come first, and are optional:
///
/// ```typc
/// edge(from, to, ..) // explicit start and end nodes
/// edge(to, ..) == edge(auto, to, ..) // start snaps to previous node
/// edge(..) == edge(auto, auto, ..) // snaps to previous and next nodes
/// edge(from, v1, v2, ..vs, to, ..) // a multi-segmented edge
/// edge(from, "->", to) // for two vertices, the marks style can come in between
/// ```
///
/// All vertices except the start point can be shorthand relative coordinate
/// string containing the characters
/// ${#"lrudtbnesw".clusters().map(raw).join($, $)}$ or commas.
///
/// If given as positional arguments, an edge's #param[edge][marks] and
/// #param[edge][label] are disambiguated by guessing based on the types. For
/// example, the following are equivalent:
///
/// ```typc
/// edge((0,0), (1,0), $f$, "->")
/// edge((0,0), (1,0), "->", $f$)
/// edge((0,0), (1,0), $f$, marks: "->")
/// edge((0,0), (1,0), "->", label: $f$)
/// edge((0,0), (1,0), label: $f$, marks: "->")
/// ```
///
/// Additionally, some common options are given flags that may be given as
/// string positional arguments. These are
/// #fletcher.EDGE_FLAGS.keys().map(repr).map(raw).join([, ], last: [, and ]).
/// For example, the following are equivalent:
///
/// ```typc
/// edge((0,0), (1,0), $f$, "wave", "crossing")
/// edge((0,0), (1,0), $f$, decorations: "wave", crossing: true)
/// ```
///
/// - vertices (array): Array of (at least two) coordinates for the edge.
///
/// Vertices can also be specified as leading positional arguments, but if so,
/// the `vertices` option must be empty. If the number of vertices is greater
/// than two, #param[edge][kind] defaults to `"poly"`.
///
/// - kind (string): The kind of the edge, one of `"line"`, `"arc"`, or `"poly"`.
/// This is chosen automatically based on the presence of other options
/// (#param[edge][bend] implies `"arc"`, #param[edge][corner] or additional
/// vertices implies `"poly"`).
///
/// - corner (none, left, right): Whether to create a right-angled corner,
/// turning `left` or `right`.
/// (Bending right means the corner sticks out to the left, and vice versa.)
///
/// #diagram(
/// node((0,1), `from`),
/// node((1,0), `to`),
/// edge((0,1), (1,0), `right`, "->", corner: right),
/// edge((0,1), (1,0), `left`, "->", corner: left),
/// )
///
/// - bend (angle): Edge curvature. If `0deg`, the connector is a straight line;
/// positive angles bend clockwise.
///
/// #diagram(debug: 0, {
/// node((0,0), $A$)
/// node((1,1), $B$)
/// let N = 4
/// range(N + 1)
/// .map(x => (x/N - 0.5)*2*100deg)
/// .map(θ => edge((0,0), (1,1), θ, bend: θ, ">->", label-side: center))
/// .join()
/// })
///
/// - label (content): Content for the edge label. See the
/// #param[edge][label-pos] and #param[edge][label-side] options to control
/// the position (and #param[edge][label-sep] and #param[edge][label-anchor]
/// for finer control).
///
/// - label-side (left, right, center): Which side of the edge to place the
/// label on, viewed as you walk along it from base to tip.
///
/// If `center`, then the label is placed directly on the edge and
/// #param[edge][label-fill] defaults to `true`. When `auto`, a value of
/// `left` or `right` is automatically chosen so that the label is:
/// - roughly above the connector, in the case of straight lines; or
/// - on the outside of the curve, in the case of arcs.
///
/// - label-pos (number): Position of the label along the connector, from the
/// start to end (from `0` to `1`).
///
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// ..(0, 0.25, 0.5, 0.75, 1).map(p => fletcher.diagram(
/// cell-size: 1cm,
/// edge((0,0), (1,0), p, "->", label-pos: p))
/// ),
/// )
///
/// - label-sep (length): Separation between the connector and the label anchor.
///
/// With the default anchor (automatically set to `"south"` in this case):
///
/// #diagram(
/// debug: 2,
/// cell-size: 8mm,
/// {
/// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() {
/// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s)
/// }
/// })
///
/// With #param[edge][label-anchor] set to `"center"`:
///
/// #diagram(
/// debug: 2,
/// cell-size: 8mm,
/// {
/// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() {
/// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s, label-anchor: "center")
/// }
/// })
///
/// Set #param[diagram][debug] to `2` or higher to see label anchors and
/// outlines as seen here.
///
/// Default: #the-param[diagram][label-sep]
///
/// - label-angle (angle, left, right, top, bottom, auto): Angle to rotate the
/// label (counterclockwise).
///
/// If a direction is given, the label is rotated so that the edge travels in
/// that direction relative to the label. If `auto`, the best of `right` or
/// `left` is chosen.
///
/// #for angle in (0deg, 90deg, auto, right, top, left) {
/// diagram(edge((0,1), (2,0), "->", [#angle], label-angle: angle))
/// }
///
/// - label-anchor (anchor): The CeTZ-style anchor point of the label to use for
/// placement (e.g., `"north-east"` or `"center"`). If `auto`, the best anchor
/// is chosen based on #param[edge][label-side], #param[edge][label-angle],
/// and the edge's direction.
///
/// - label-fill (bool, paint): The background fill for the label. If `true`,
/// defaults to the value of #param[edge][crossing-fill]. If `false` or
/// `none`, no fill is used. If `auto`, then defaults to `true` if the label
/// is covering the edge (#param[edge][label-side]`: center`).
///
/// - label-size (auto, length): The default text size to apply to edge labels.
///
/// Default: #the-param[diagram][label-size]
///
/// - label-wrapper (auto, function): Callback function accepting a node
/// dictionary and returning the label content. This is used to add a label
/// background (see #param[edge][crossing-fill]), and can be used to adjust
/// the label's padding, outline, and so on.
///
/// #example(```
/// diagram(edge($f$, label-wrapper: e =>
/// circle(e.label, fill: e.label-fill)))
/// ```)
///
/// Default: #the-param[diagram][label-wrapper]
///
/// - stroke (stroke): Stroke style of the edge. Arrows/marks scale with the
/// stroke thickness (and with #param[edge][mark-scale]).
///
/// - dash (string): The stroke's dash style. This is also set by some mark
/// styles. For example, setting `marks: "<..>"` applies `dash: "dotted"`.
///
/// - decorations (none, string, function): Apply a CeTZ path decoration to the
/// stroke. Preset options are `"wave"`, `"zigzag"`, and `"coil"` (which may
/// also be passed as convenience positional arguments), but a decoration
/// function may also be specified.
///
/// #example(```
/// diagram(
/// $
/// A edge("wave") &
/// B edge("zigzag") &
/// C edge("coil") & D \
/// alpha &&& omega
/// $,
/// edge((0,1), (3,1), "<->", decorations:
/// cetz.decorations.wave
/// .with(amplitude: .4)
/// )
/// )
/// ```)
///
/// - marks (array): The marks (arrowheads) to draw along an edge's stroke. This
/// may be:
///
/// - A shorthand string such as `"->"` or `"hook'-/->>"`. Specifically,
/// shorthand strings are of the form $M_1 L M_2$ or $M_1 L M_2 L M_3$, etc,
/// where
///
/// $ M_i in #`fletcher.MARKS` = #context math.mat(..fletcher.MARKS.get().keys().map(i => $#raw(lang: none, i),$).chunks(6), delim: "{") $
/// is a mark name and
/// $ L in #`fletcher.LINE_ALIASES` = {#fletcher.LINE_ALIASES.keys().map(raw.with(lang: none)).join($,$)} $
/// is the line style.
///
/// - An array of marks, where each mark is specified by name of as a _mark
/// object_ (dictionary of parameters with a `draw` entry).
///
/// Shorthands are expanded into other arguments. For example,
/// `edge(p1, p2, "=>")` is short for `edge(p1, p2, marks: (none, "head"), "double")`, or more precisely, the result of `edge(p1, p2, ..fletcher.interpret-marks-arg("=>"))`.
///
/// #table(
/// columns: (1fr, 4fr),
/// align: (center + horizon, horizon),
/// [Result], [Value of `marks`],
/// ..(
/// "->",
/// ">>-->",
/// "<=>",
/// "==>",
/// "->>-",
/// "x-/-@",
/// "|..|",
/// "hook->>",
/// "hook'->>",
/// "||-*-harpoon'",
/// ("X", (inherit: "head", size: 15, sharpness: 40deg),), ((inherit:
/// "circle", pos: 0.5, fill: auto),),
/// ).map(arg => (
/// fletcher.diagram(edge((0,0), (1,0), marks: arg, stroke: 0.8pt)),
/// raw(repr(arg)),
/// )).join()
/// )
///
/// - mark-scale (percent): Scale factor for marks or arrowheads, relative to
/// the #param[edge][stroke] thickness. See also #the-param[diagram][mark-scale].
///
/// #diagram(
/// label-sep: 10pt,
/// edge-stroke: 1pt,
/// for i in range(3) {
/// let s = (1 + i/2)*100%
/// edge((2*i,0), (2*i + 1,0), label: s, "->", mark-scale: s)
/// }
/// )
///
/// Note that the default arrowheads scale automatically with double and
/// triple strokes:
///
/// #diagram(
/// label-sep: 10pt,
/// edge-stroke: 1pt,
/// for (i, s) in ("->", "=>", "==>").enumerate() {
/// edge((2*i,0), (2*i + 1,0), s, label: raw(s, lang: none))
/// }
/// )
///
/// - extrude (array): Draw a separate stroke for each extrusion offset to
/// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples
/// of the stroke's thickness) or lengths.
///
/// #diagram({
/// (
/// (0,),
/// (-1.5,+1.5),
/// (-2,0,+2),
/// (-.5em,),
/// (0, 5pt,),
/// ).enumerate().map(((i, e)) => {
/// edge(
/// (2*i, 0), (2*i + 1, 0), [#e], "|->",
/// extrude: e, stroke: 1pt, label-sep: 1em)
/// }).join()
/// })
///
/// Notice how the ends of the line need to shift a little depending on the
/// mark. This offset is computed with `cap-offset()`.
///
/// See also #the-param[node][extrude].
///
/// - crossing (bool): If `true`, draws a backdrop of color
/// #param[edge][crossing-fill] to give the illusion of lines crossing each
/// other.
///
/// #diagram({
/// edge((0,1), (1,0), stroke: 1pt)
/// edge((0,0), (1,1), stroke: 1pt)
/// edge((2,1), (3,0), stroke: 1pt)
/// edge((2,0), (3,1), stroke: 1pt, crossing: true)
/// })
///
/// You can also pass `"crossing"` as a positional argument as a shorthand for
/// `crossing: true`.
///
/// - crossing-thickness (number): Thickness of the "crossing" background stroke
/// (applicable if #param[edge][crossing] is `true`) in multiples of the
/// normal stroke's thickness.
///
/// #diagram({
/// (1, 2, 4, 8).enumerate().map(((i, x)) => {
/// edge((2*i, 1), (2*i + 1, 0), stroke: 1pt, label-sep: 1em)
/// edge((2*i, 0), (2*i + 1, 1), raw(str(x)), stroke: 1pt, label-sep:
/// 2pt, label-pos: 0.3, crossing: true, crossing-thickness: x)
/// }).join()
/// })
///
/// Default: #the-param[diagram][crossing-thickness]
///
/// - crossing-fill (paint): Color to use behind connectors or labels to give
/// the illusion of crossing over other objects.
///
/// #let cross(x, fill) = {
/// edge((2*x + 0,1), (2*x + 1,0), stroke: 1pt)
/// edge((2*x + 0,0), (2*x + 1,1), $f$, stroke: 1pt, crossing: true, crossing-fill: fill, label-fill: true)
/// }
/// #diagram(crossing-thickness: 5, {
/// cross(0, white)
/// cross(1, blue.lighten(50%))
/// })
///
/// Default: #the-param[diagram][crossing-fill]
///
/// - corner-radius (length, none): Radius of rounded corners for edges with
/// multiple segments. Note that `none` is distinct from `0pt`.
///
/// #for (i, r) in (none, 0pt, 5pt).enumerate() {
/// if i > 0 { h(1fr) }
/// fletcher.diagram(
/// edge-stroke: 1pt,
/// edge((3*i, 0), "r,t,rd,r", "=>", raw(repr(r)), label-pos: 0.6, corner-radius: r)
/// )
/// }
///
/// This length specifies the corner radius for right-angled bends. The actual
/// radius is smaller for acute angles and larger for obtuse angles to balance
/// things visually. (Trust me, it looks naff otherwise!)
///
/// Default: #the-param[diagram][edge-corner-radius]
///
/// - shift (length, number, pair): Amount to shift the edge sideways by,
/// perpendicular to its direction. A pair `(from, to)` controls the shifts at
/// each end of the edge independently, and a single shift `s` is short for
/// `(s, s)`. Shifts can absolute lengths (e.g., `5pt`) or coordinate
/// differences (e.g., `0.1`).
///
/// #diagram(
/// node((0,0), $A$), node((1,0), $B$),
/// edge((0,0), (1,0), "->", `3pt`, shift: 3pt),
/// edge((0,0), (1,0), "->", `-3pt`, shift: -3pt, label-side: right),
/// )
///
/// If an edge has many vertices, the shifts only affect the first and last
/// segments of the edge.
///
/// #example(```
/// diagram(
/// node-fill: luma(70%),
/// node((0,0), [Hello]),
/// edge("u,r,d", "->"),
/// edge("u,r,d", "-->", shift: 8pt),
/// node((1,0), [World]),
/// )
/// ```)
///
/// - snap-to (pair): The nodes the start and end of an edge should snap to.
/// Each node can be a position or node #param[node][name], or `none` to disable
/// snapping. See also #the-param[node][snap].
///
/// By default, an edge's first and last #param[edge][vertices] snap to nearby
/// nodes. This option can be used in case automatic snapping fails (if there
/// are many nodes close together, for example.)
///
/// - layer (number): Layer on which to draw the edge.
///
/// Objects on a higher `layer` are drawn on top of objects on a lower
/// `layer`. Objects on the same layer are drawn in the order they are passed
/// to `diagram()`.
///
/// - post (function): Callback function to intercept `cetz` objects before they
/// are drawn to the canvas.
///
/// This can be used to hide elements without affecting layout (for use with
/// #link("https://github.com/touying-typ/touying")[Touying], for example).
/// The `hide()` function also helps for this purpose.
///
#let edge(
..args,
vertices: (),
label: none,
label-side: auto,
label-pos: 0.5,
label-sep: auto,
label-angle: 0deg,
label-anchor: auto,
label-fill: auto,
label-size: auto,
label-wrapper: auto,
stroke: auto,
dash: none,
decorations: none,
extrude: (0,),
shift: 0pt,
kind: auto,
bend: 0deg,
corner: none,
corner-radius: auto,
marks: (),
mark-scale: 100%,
crossing: false,
crossing-thickness: auto,
crossing-fill: auto,
snap-to: (auto, auto),
layer: 0,
post: x => x,
) = {
let options = (
vertices: vertices,
label: label,
label-pos: label-pos,
label-sep: label-sep,
label-angle: label-angle,
label-anchor: label-anchor,
label-side: label-side,
label-fill: label-fill,
label-size: label-size,
label-wrapper: label-wrapper,
stroke: stroke,
dash: dash,
decorations: decorations,
kind: kind,
bend: bend,
corner: corner,
corner-radius: corner-radius,
extrude: extrude,
shift: shift,
marks: marks,
mark-scale: mark-scale,
crossing: crossing,
crossing-thickness: crossing-thickness,
crossing-fill: crossing-fill,
snap-to: as-pair(snap-to),
layer: layer,
post: post,
)
options += interpret-edge-args(args, options)
// relative coordinate shorthands
let interpret-coord-str(coord) = {
if type(coord) != str { return coord }
let rel = (0, 0)
let dirs = (
"t": ( 0,-1), "n": ( 0,-1), "u": ( 0,-1),
"b": ( 0,+1), "s": ( 0,+1), "d": ( 0,+1),
"l": (-1, 0), "w": (-1, 0),
"r": (+1, 0), "e": (+1, 0),
)
for char in coord.clusters() {
rel = vector.add(rel, dirs.at(char))
}
(rel: rel)
}
options.vertices = options.vertices.map(interpret-coord-str)
if options.label-side not in (left, center, right, auto) {
error("`label-side` must be one of `left`, `center`, `right`, or `auto`; got #0.", options.label-side)
}
if options.label-side == center {
options.label-anchor = "center"
options.label-sep = 0pt
}
if type(options.shift) != array { options.shift = (options.shift, options.shift) }
let obj = (
class: "edge",
..options,
is-crossing-background: false,
)
// for the crossing effect, add another edge underneath
if options.crossing {
metadata((
..obj,
is-crossing-background: true
))
}
metadata(obj)
}
#let resolve-edge-options(edge, options) = {
let to-pt(len) = to-abs-length(len, options.em-size)
edge += interpret-marks-arg(edge.marks)
if edge.stroke == none {
// hack: for no stroke, it's easier to do the following.
// then we have the guarantee that edge.stroke is actually
// a stroke, not possibly none
edge.extrude = ()
edge.marks = ()
edge.stroke = stroke((:))
}
edge.stroke = (
(
cap: "round",
dash: edge.dash,
thickness: 0.048em, // guarantees thickness is a length, not auto
) +
stroke-to-dict(options.edge-stroke) +
stroke-to-dict(map-auto(edge.stroke, (:)))
)
edge.stroke.thickness = to-pt(edge.stroke.thickness)
edge.extrude = as-array(edge.extrude).map(as-number-or-length.with(
message: "`extrude` must be a number, length, or an array of those"
)).map(d => {
if type(d) == length { to-pt(d) }
else { d*edge.stroke.thickness }
})
if type(edge.decorations) == str {
edge.decorations = (
"wave": cetz.decorations.wave.with(
amplitude: .12,
segment-length: .2,
),
"zigzag": cetz.decorations.zigzag.with(
amplitude: .12,
segment-length: .2,
),
"coil": cetz.decorations.coil.with(
amplitude: .15,
segment-length: .15,
factor: 140%,
),
).at(edge.decorations)
}
edge.crossing-fill = map-auto(edge.crossing-fill, options.crossing-fill)
edge.crossing-thickness = map-auto(edge.crossing-thickness, options.crossing-thickness)
edge.corner-radius = map-auto(edge.corner-radius, options.edge-corner-radius)
if edge.is-crossing-background {
edge.stroke = (
thickness: edge.crossing-thickness*edge.stroke.thickness,
paint: edge.crossing-fill,
cap: "round",
)
edge.marks = ()
edge.extrude = edge.extrude.map(e => e/edge.crossing-thickness)
}
edge.stroke = as-stroke(edge.stroke)
if edge.kind == auto {
if edge.vertices.len() > 2 { edge.kind = "poly" }
else if edge.corner != none { edge.kind = "corner" }
else if edge.bend != 0deg { edge.kind = "arc" }
else { edge.kind = "line" }
}
// Scale marks
edge.mark-scale *= options.mark-scale
edge.marks = edge.marks.map(mark => {
mark.scale *= edge.mark-scale
mark
})
edge.label-sep = to-pt(map-auto(edge.label-sep, options.label-sep))
edge.label-size = map-auto(edge.label-size, options.label-size)
edge.label-fill = map-auto(edge.label-fill, edge.label-side == center)
if edge.label-fill == true { edge.label-fill = edge.crossing-fill }
if edge.label-fill == false { edge.label-fill = none }
edge.label-wrapper = map-auto(edge.label-wrapper, options.label-wrapper)
edge
}
#let resolve-edge-vertices(edge, ctx: (:), nodes) = {
let adjacent-node-pos(forward, default) = {
if edge.node-index == none { return default }
let indices = if forward {
range(edge.node-index, nodes.len())
} else {
range(0, edge.node-index).rev()
}
for i in indices {
if nodes.at(i).snap != false {
return nodes.at(i).pos.at(ctx.target-system)
}
}
return default
}
let prev-pos = adjacent-node-pos(false, (0, 0))
let next-pos = adjacent-node-pos(true, (rel: (1, 0)))
let ctx = default-ctx + ctx + (
prev: (pt: prev-pos),
)
edge.vertices.at(0) = map-auto(edge.vertices.at(0), prev-pos)
edge.vertices.at(-1) = map-auto(edge.vertices.at(-1), next-pos)
let (ctx, ..verts) = resolve(ctx, ..edge.vertices)
verts.map(vector-2d)
}
#let convert-edge-corner-to-poly(edge) = {
if edge.kind != "corner" { return edge }
let (from, to) = edge.final-vertices
let θ = angle-between(from, to)
let bend-dir = (
if edge.corner == right { true }
else if edge.corner == left { false }
else { error("Edge `corner` option must be `left` or `right`.") }
)
let θ-floor = calc.floor(θ/90deg)*90deg
let θ-ceil = calc.ceil(θ/90deg)*90deg
let θs = if bend-dir {
(θ-ceil, θ-floor + 180deg)
} else {
(θ-floor, θ-ceil + 180deg)
}
let corner-point = if calc.even(calc.floor(θ/90deg) + int(bend-dir)) {
(to.at(0), from.at(1))
} else {
(from.at(0), to.at(1))
}
edge + (
kind: "poly",
final-vertices: (from, corner-point, to),
label-side: if bend-dir { left } else { right },
)
}
// For straight edges, `shift` translates the line laterally
#let apply-edge-shift-line(grid, edge) = {
let (from-xy, to-xy) = edge.final-vertices
let θ = angle-between(from-xy, to-xy) + 90deg
let (δ-from, δ-to) = edge.shift
let δ⃗-from = vector-polar-with-xy-or-uv-length(grid, from-xy, δ-from, θ)
let δ⃗-to = vector-polar-with-xy-or-uv-length(grid, to-xy, δ-to, θ)
edge.final-vertices.at( 0) = vector.add(from-xy, δ⃗-from)
edge.final-vertices.at(-1) = vector.add(to-xy, δ⃗-to)
edge
}
// For arc edges, `shift` grows/shrinks the arc concentrically
#let apply-edge-shift-arc(grid, edge) = {
let (from-xy, to-xy) = edge.final-vertices
let θ = angle-between(from-xy, to-xy) + 90deg
let (θ-from, θ-to) = (θ + edge.bend, θ - edge.bend)
let (δ-from, δ-to) = edge.shift
let δ⃗-from = vector-polar-with-xy-or-uv-length(grid, from-xy, δ-from, θ-from)
let δ⃗-to = vector-polar-with-xy-or-uv-length(grid, to-xy, δ-to, θ-to)
edge.final-vertices.at( 0) = vector.add(from-xy, δ⃗-from)
edge.final-vertices.at(-1) = vector.add(to-xy, δ⃗-to)
edge
}
// For poly edges, `shift` affects the first/last line segments
#let apply-edge-shift-poly(grid, edge) = {
let end-segments = (
edge.final-vertices.slice(0, 2), // first two vertices
edge.final-vertices.slice(-2), // last two vertices
)
let θs = (
angle-between(..end-segments.at(0)) + 180deg,
angle-between(..end-segments.at(1)) + 180deg,
)
let ends = (edge.final-vertices.at(0), edge.final-vertices.at(-1))
let δs = edge.shift.zip(ends, θs).map(((d, xy, θ)) => {
vector-polar-with-xy-or-uv-length(grid, xy, d, θ + 90deg)
})
// the `shift` option is nicer if it shifts the entire segment, not just the first vertex
// first segment
edge.final-vertices.at(0) = vector.add(edge.final-vertices.at(0), δs.at(0))
edge.final-vertices.at(1) = vector.add(edge.final-vertices.at(1), δs.at(0))
// last segment
edge.final-vertices.at(-2) = vector.add(edge.final-vertices.at(-2), δs.at(1))
edge.final-vertices.at(-1) = vector.add(edge.final-vertices.at(-1), δs.at(1))
edge
}
/// Apply #the-param[edge][shift] by translating edge vertices.
///
/// - grid (dictionary): Representation of the grid layout. This is needed to
/// support shifts specified as coordinate lengths.
/// - edge (dictionary): The edge with a `shift` entry.
#let apply-edge-shift(grid, edge) = {
if edge.kind == "line" { apply-edge-shift-line(grid, edge) }
else if edge.kind == "arc" { apply-edge-shift-arc(grid, edge) }
else if edge.kind == "poly" { apply-edge-shift-poly(grid, edge) }
else { edge }
}
|
https://github.com/Zuttergutao/Typstdocs-Zh-CN- | https://raw.githubusercontent.com/Zuttergutao/Typstdocs-Zh-CN-/main/Classified/Part%20I.typ | typst | #import "format.typ":*
#counter(page).update(1)
#[
#set heading(numbering: none)
#show heading: it => block[
#set align(center)
#set text(size:28pt,weight:700)
#it.body
]
= Part I Guide for LaTex Users
]
#[
#set heading(numbering: none)
= 前言
此部分将会简明的介绍LaTeX和Typst的差异之处,并使LaTeX玩家快速上手Typst。
就像LaTeX,Typst是一个基于标记的排版系统。你可以在文本文件中编写文档,并使用命令和语法进行标记。然后使用编译器将源文件排版为PDF格式。然而,Typst在以下几个方面不同于LaTeX:一方面,Typst 使用更专用的语法(就像您可能从 Markdown 中了解到的那样)用于常见任务。 Typst 的命令也更有原则性:它们的工作原理相同,因此与 LaTeX 不同,您只需要了解几个通用概念,而不是学习每个包的不同约定。此外,Typst 的编译速度比 LaTeX 快:编译通常需要几毫秒,而不是几秒钟,因此 Web 应用程序和编译器都可以提供即时预览。
我们将在下文介绍从 LaTeX 转换过来的用户在使用 Typst 编写文档时遇到的一些最常见的问题。如果您更喜欢 Typst 的分步介绍,请查看我们的教程。
= 创建文档
就像LaTeX创建`.tex`文件一样,Typst只需要创建`.typ`文件即可。无需提供模板文件。默认情况使用的是A4大小的页面,如果使用web版,只需要单击`+ Empty document`,就可以创建项目并进入编辑器。和LaTeX一样只需要使用空行就可以实现段落。
= 如何创建章标题,强调?
LaTeX使用命令`\section`、`\subsection`、`\subsubsection`创建章标题与子标题。根据写作内容的不同,还支持`\part`和`\chapter`。
在Typst中,标题的表现形式十分简约:`= Introduction`、`== In this paper`。标题的深度取决于你使用了多少个等号`=`。
内容强调通常以斜体文本的形式呈现,通过将文本括在下划线中表示\(`_underscores_`\),着重强调使用粗体表示\(`*stars*`\)。
如下表格为LaTeX命令与Typst命令的对比。也可以查看完整的cheatsheet。
#table(
columns:(auto,auto,auto,auto),
inset:10pt,
align:horizon,
[*Element*],[*LaTeX*],[*Typst*],[*See*],
[Strong emphasis],[\textbf{strong}],[*strong*],[@strong],
[Emphasis],[\emph{emphasis}],[_emphasis_],[@emph],
[Monospace code],[\texttt{print(1)}],[`print(1)`],[@raw],
[Link],[\url{https://typst.app}],[https://typst.app/],[@link],
[Label],[\label{intro}],[\<intro\>],[@label],
[Reference],[\ref{intro}],[\@intro],[@ref],
[Citation],[\cite{humphrey97}],[\@humphrey97],[@cite],
[Bullet list],[itemize environment],[- List],[@list],
[Numbered list],[enumerate environment],[\+ List],[@enum],
[Term list],[description environment],[\/ Term: List],[@terms],
[Figure],[figure environment],[figure function],[@image],
[Table],[table environment],[table function],[@table],
[Equation],[\$x\$, align / equation environments],[\$x\$, \$ x = y \$],[@equation],
)
Typst中Lists不依赖于环境。相反的,他们具有像标题一样的轻量化语法。如果需要创建无序列表,只需要在列表项前面加连字符。
```typ
To write this list in Typst...
```
```latex
\begin{itemize}
\item Fast
\item Flexible
\item Intuitive
\end{itemize}
```
```typ
...just type this:
- Fast
- Flexible
- Intuitive
```
#[
#show:blockk
To write this list in Typst...
```latex
\begin{itemize}
\item Fast
\item Flexible
\item Intuitive
\end{itemize}
```
...just type this:
- Fast
- Flexible
- Intuitive
]
通过将它们缩进到连字符之外,您还可以在单个列表项中包含多个段落或嵌套列表。如果列表项变得更长,最好在列表项之间放置空行。这会增加列表项之间的间距。
要改为获取编号列表(枚举),请使用 + 而不是连字符。对于术语列表(描述),写 `/ Term: Description` 代替。
= 命令
LaTeX 严重依赖命令(以反斜杠为前缀)。它使用这些宏来影响排版过程以及插入和操作内容。一些命令接受参数,最常见的是它们被括在花括号中:`\cite{rasmus}`。
Typst 区分标记模式和代码模式。标记模式是默认设置,您可以在其中编写文本并使用语法结构,例如`*`星号表示粗体文本。代码模式类似于 Python 等其他编程语言,允许您编写类似 `1 + 2 == 3` 的代码。
在 Typst 的标记中,您可以使用井号`#`为单个命令(或者更确切地说,表达式)切换到代码模式。这就是您调用函数和使用标记内导入等功能的方式。在这些命令和函数调用中,代码模式适用。要将内容作为值嵌入,您可以使用方括号返回标记模式:
```typ
First, a rectangle:
#rect()
Let me show how to do
#underline([_underlined_ text])
We can also do some maths:
#calc.max(3, 2 * 4)
And finally a little loop:
#for x in range(3) [
Hi #x.
]
```
#[
#show:blockk
First, a rectangle:
#rect()
Let me show how to do
#underline([_underlined_ text])
We can also do some maths:
#calc.max(3, 2 * 4)
And finally a little loop:
#for x in range(3) [
Hi #x.
]
]
函数调用总是涉及函数的名称(rect、underline、calc.max、range),然后是参数列表,即使它是空的。参数列表括在括号中。
一个函数可以有多个参数。一些参数是位置性的,即您只需提供值:函数 `#lower("SCREAM")` 以全小写形式返回其参数。许多函数使用命名参数而不是位置参数来提高易读性。例如,矩形的尺寸和笔划是使用命名参数定义的:
```typ
#rect(
width: 2cm,
height: 1cm,
stroke: red,
)
```
#[
#show:blockk
#rect(
width: 2cm,
height: 1cm,
stroke: red,
)
]
您可以通过首先输入名称(如上所示,width, height, and stroke)、冒号和值`(2cm, 1cm, red)`来指定命名参数。您可以在每个函数的参考页或键入时的自动完成面板中找到可用的命名参数。命名参数类似于一些 LaTeX 环境的配置方式,例如,您将键入 `\begin{enumerate}[label={\alph*)}]` 以使用标签 `a)`、`b)` 等开始列表。
通常,您希望为函数提供一些内容。例如,LaTeX 命令 `\underline{Alternative A}` 在 Typst 中将转换为`#underline([Alternative A])`。方括号表示一个值是内容。在这些括号内,您可以使用普通标记。然而,对于一个非常简单的构造来说,这是很多括号。这就是为什么您还可以在括号之后移动尾随内容参数(如果括号最终为空,则省略括号)。
```typ
Typst is an #underline[alternative]
to LaTeX.
#rect(fill: aqua)[Get started here!]
```
#[
#show:blockk
Typst is an #underline[alternative] to LaTeX.
#rect(fill: aqua)[Get started here!]
]
#h(2em)您可能已经注意到参数具有不同的数据类型。 Typst 支持多种数据类型。下面是一个表格,其中包含一些最重要的内容以及如何编写它们:
#align(
center,
table(
columns:(auto,auto),
inset:10pt,
align:horizon,
[*Data type*],[*Example*],
[Content],[\*fast\* typesetting],
[String],["<NAME>"],
[Integer],[23],
[Floating point number],[1.459],
[Absolute length],[12pt, 5in, 0.3cm, ...],
[Relative length],[65%],
)
)
#h(2em)内容和字符串之间的区别在于内容可以包含标记,包括函数调用,而字符串实际上只是一个字符序列。您可以像在传统编程语言中那样使用 `+` 运算符求和和 `==` 等运算符来计算这些类型的相等性,而不是使用 `\addtocounter` 或 `\ifnum`。您甚至可以定义变量并使用它们进行计算。
为了指定任何这些类型的值,您必须处于代码模式!
在 LaTeX 中,一些像 `\textbf{bold text}` 这样的命令在花括号中传递它们的参数并且只影响那个参数,而其他像 `\bfseries bold text` 这样的命令充当开关并改变文档或当前范围中所有后续内容的外观(由一组大括号表示)。
在 Typst 中,函数可以两种方式使用:效果应用到文档或块的末尾,或者只应用到它的参数。例如,`#text(weight: "bold")[bold text]` 只会加粗它的论点,而 `#set text(weight: "bold")` 会加粗任何文本,直到当前块结束。一个函数的效果是显而易见的,这取决于它是在调用中使用还是在设置规则中使用。
```typ
I am starting out with small text.
#set text(14pt)
This is a bit #text(18pt)[larger,]
don't you think?
```
#[
#show:blockk
I am starting out with small text.
#set text(14pt)
This is a bit #text(18pt)[larger,]
don't you think?
]
#h(2em)set规则可能出现在文档中的任何地方,并且可以被认为是预先设置其函数的参数:
```typ
#set enum(numbering: "I.")
Good results can only be obtained by
+ following best practices
+ being aware of current results
of other researchers
+ checking the data for biases
```
#[
#show:blockk
#set enum(numbering: "I.")
Good results can only be obtained by
+ following best practices
+ being aware of current results
of other researchers
+ checking the data for biases
]
#h(2em)`+` 是调用枚举函数的语法糖(将其视为缩写),我们在上面应用了一组规则。大多数语法都以这种方式链接到函数。如果你需要设置一个元素的样式超出其参数启用的范围,你可以使用显示规则(有点类似于 `\renewcommand`)完全重新定义它的外观。
= 模板
在 LaTeX 中,您可以使用 `\documentclass{article}` 命令启动您的主 `.tex` 文件,以定义您的文档的外观。在该命令中,您可能已将 article 替换为另一个值,例如 report 和 amsart 以选择不同的外观。
使用 Typst 时,您可以使用函数来设计文档的样式。通常,您使用的模板提供了一个功能,可以为整个文档设置样式。首先,您从模板文件导入函数。然后,将其应用于整个文档。这是通过将以下文档包装在给定函数中的显示规则来实现的。下面的例子说明了它是如何工作的:
```typ
#import "conf.typ": conf
#show: conf.with(
title: [
Towards Improved Modelling
],
authors: (
(
name: "<NAME>",
affiliation: "Artos Institute",
email: "<EMAIL>",
),
(
name: "<NAME>",
affiliation: "Honduras State",
email: "<EMAIL>",
),
),
abstract: lorem(80),
)
Let's get started writing this
article by putting insightful
paragraphs right here!
```
`import` 语句使来自另一个文件的函数(和其他定义)可用。在此示例中,它从 `conf.typ` 文件导入 `conf` 函数。此功能将内容格式化为会议文章。我们使用 `show` 规则将其应用于文档,并配置一些关于文章的元数据。最后,我们可以开始写下面的文章了!
函数是 Typst 的“命令”,可以将它们的参数转换为输出值,包括文档内容。函数是“纯”的,这意味着它们除了创建输出值/输出内容之外不能有任何效果。这与可以对您的文档产生任意影响的 LaTeX 宏形成鲜明对比。
为了让函数为整个文档设置样式,show 规则处理它之后的所有内容,并调用冒号后指定的函数,并将结果作为参数。 `.with` 部分是一种采用 conf 函数并在将其传递给 show 规则之前预先配置其参数的方法。
在 Web 应用程序中,您可以从预定义的模板中进行选择,甚至可以使用模板向导创建您自己的模板。您还可以查看 awesome-typst 存储库以查找社区制作的模板。我们计划构建一个包管理器,使模板在未来更容易共享!
您还可以创建自己的自定义模板。它们比相应的 `LaTeX .sty` 文件短几个数量级,可读性更强,所以试一试吧!
= 导入包
大多数你在 LaTeX 中加载包的东西都只包含在 Typst 中,不需要加载或安装任何东西。下面,我们整理了一张表格,列出了经常加载的包及其对应的 Typst 函数。
如果您需要从另一个文件加载函数和变量,例如使用模板,您可以使用 `import` 语句。如果你想包含另一个文件的文本内容,你可以使用 `include` 语句。它将产生包含文件的内容并将其放入您的文档中。
目前,Typst 没有包管理器,但我们计划构建一个,以便您可以轻松地使用来自社区的工具和模板的包,并发布您自己的包。
#align(
center,
table(
columns:(auto,auto),
inset:10pt,
align:horizon,
[graphicx, svg],[image function],
[tabularx],[table, grid functions],
[fontenc, inputenc, unicode-math],[Just start writing!],
[babel, polyglossia],[text function: #set text(lang: "zh")],
[amsmath],[Math mode],
[amsfonts, amssymb],[sym module and syntax],
[geometry, fancyhdr],[page function],
[xcolor],[text function: #set text(fill: rgb("#0178A4"))],
[hyperref],[link function],
[bibtex, biblatex, natbib],[cite, bibliography functions],
[lstlisting, minted],[raw function and syntax],
[parskip],[block and par functions],
[csquotes],[Type " or ' and set the text language],
[caption],[figure function],
[enumitem],[list, enum, terms functions],
)
)
= 数学公式
要在 Typst 中使用数学模式,只需将您的方程用美元符号括起来。您可以通过在开始和结束美元符号和等式之间放置空格或换行符来进入显示模式。
```typ
The sum of the numbers from
$1$ to $n$ is:
$ sum_(k=1)^n k = (n(n+1))/2 $
```
#[
#show:blockk
The sum of the numbers from
$1$ to $n$ is:
$ sum_(k=1)^n k = (n(n+1))/2 $
]
数学模式的工作方式与普通标记或代码模式不同。单个字符和任意数量的数字会被显示为数学变量和数值(取决于你的方程式),而多个连续的非数字字符将被解释为Typst变量。
正如你在上面的例子中看到的,Typst在数学模式下预先定义了很多有用的变量。所有的希腊字母和一些希伯来字母都由它们的名字来解决。请参考符号页或使用自动完成面板来检查哪些符号是可用的。符号的替代形式和相关形式通常可以通过在句点后附加一个修饰语来选择。例如,`arrow.l.squiggly`插入了一个左旋的箭头。如果你想在你的表达式中插入多字母文本,请用双引号将其括起来:
你可以用<=、>=和->等速记符号输入许多符号。同样,定界符也会为其表达式自动缩放,就像LaTeX中隐含插入的 \left 和 \right 命令一样。你可以使用lr函数自定义定界符的行为。
Typst会自动将斜线/周围的术语设置为分数,同时尊重运算符优先级。所有的圆括号都会出现在输出中,而不会因为分数而出现多余的括号。
下标和上标在 Typst 和 LaTeX 中的工作方式类似。输入 `$x^2$` 会产生一个上标,`$x_2$` 会产生一个下标。如果您想在下标或上标中包含多个值,请将它们的内容括在括号中:`$x_(a -> epsilon)$`。
就像您可以在不键入 `#` 或 `/` 的情况下插入变量一样,您也可以使用“裸”函数。
上面的例子使用 cases 函数来描述 f。在 cases 函数中,参数使用逗号分隔,并且参数也被解释为数学。如果您需要将参数解释为 Typst 值,请在它们前面加上`#`。
您可以在数学模式下使用所有 Typst 函数并插入任何内容。如果您希望它们正常工作,在参数列表中使用代码模式,您可以在它们的调用前加上`#`。没有人能阻止您再使用矩形或表情符号作为变量。
如果您想直接输入您的数学符号作为 Unicode,那也是可能的!
数学调用可以使用二维参数列表;作为分隔符。最常见的用途是创建矩阵的 mat 函数。
```typ
$ delta "if" x <= 5 $
$ f(x) = (x + 1) / x $
$ f(x, y) := cases(
1 "if" (x dot y)/2 <= 0,
2 "if" x "is even",
3 "if" x in NN,
4 "else",
) $
$ (a + b)^2
= a^2
+ text(fill: #maroon, 2 a b)
+ b^2 $
$ sum^10_(🥸=1)
#rect(width: 4mm, height: 2mm)/🥸
= 🧠 maltese $
$ mat(
1, 2, ..., 10;
2, 2, ..., 10;
dots.v, dots.v, dots.down, dots.v;
10, 10, ..., 10;
) $
```
#[
#show:blockk
$ delta "if" x <= 5 $
$ f(x) = (x + 1) / x $
$ f(x, y) := cases(
1 "if" (x dot y)/2 <= 0,
2 "if" x "is even",
3 "if" x in NN,
4 "else",
) $
$ (a + b)^2
= a^2
+ text(fill: #maroon, 2 a b)
+ b^2 $
$ sum^10_(🥸=1)
#rect(width: 4mm, height: 2mm)/🥸
= 🧠 maltese $
$ mat(
1, 2, ..., 10;
2, 2, ..., 10;
dots.v, dots.v, dots.down, dots.v;
10, 10, ..., 10;
) $
]
= “盗版”LaTeX
在 LaTeX 中设置的论文具有明确无误的外观。这主要是由于它们的字体、Computer Modern、对齐、窄行距和宽边距。
这应该是一个很好的起点!如果您想更进一步,为什么不创建一个可重复使用的模板呢?
- sets wide margins
- enables justification, tighter lines and first-line-indent
- sets the font to "New Computer Modern", an OpenType - derivate of Computer Modern for both text and code blocks
- disables paragraph spacing
- increases spacing around headings
```typ
#set page(margin: 1.75in)
#set par(leading: 0.55em, first-line-indent: 1.8em, justify: true)
#set text(font: "New Computer Modern")
#show raw: set text(font: "New Computer Modern Mono")
#show par: set block(spacing: 0.55em)
#show heading: set block(above: 1.4em, below: 1em)
```
= 局限性
尽管 Typst 可以成为当今许多人的 LaTeX 替代品,但 Typst 仍然(尚)不支持某些功能。以下是它们的列表,其中在适用的情况下包含可能的解决方法。
- 图表绘制Native charts and plots. LaTeX users often create charts along with their documents in PGF/TikZ. Typst does not yet include tools to draw diagrams, but the community is stepping up with solutions such as typst-canvas, typst-plot, and circuitypst. You can add those to your document to get started with drawing diagrams.
- 页边距Change page margins without a pagebreak. In LaTeX, margins can always be adjusted, even without a pagebreak. To change margins in Typst, you use the page function which will force a page break. If you just want a few paragraphs to stretch into the margins, then reverting to the old margins, you can use the pad function with negative padding.
- 浮动图片Floating figures. The figure command of LaTeX will smartly choose where to place a figure, be it on the top or bottom of the page, or a dedicated figure page. Typst's figure will always appear at the spot where they have been inserted in the markup. While this behavior can save some headache, it is often cumbersome to manually place figures. We will be adding this feature soon!
- 包含PDF Include PDFs as images. In LaTeX, it has become customary to insert vector graphics as PDF or EPS files. Typst supports neither format as an image format, but you can easily convert both into SVG files with online tools or Inkscape. We plan to add automatic conversion for these file formats to the Typst web app, too!
- 分页优化Page break optimization. LaTeX runs some smart algorithms to not only optimize line but also page breaks. While Typst tries to avoid widows and orphans, it uses less sophisticated algorithms to determine page breaks. You can insert custom page breaks in Typst using` #pagebreak(weak: true)` before submitting your document. The argument weak ensures that no double page break will be created if this spot would be a natural page break anyways. You can also use `#v(1fr)` to distribute space on your page. It works quite similar to LaTeX's \vfill.
- 参考数目格式Bibliographies are not customizable. In LaTeX, the packages bibtex, biblatex, and natbib provide a wide range of reference and bibliography formats. You can also use custom .bbx files to define your own styles there. Typst only supports a small set of citation styles at the moment, but we want to build upon this by supporting Citation Style Language (CSL), an XML-based format backed by Zotero that allows you to describe your own bibliography styles.
]
#pagebreak() |
|
https://github.com/ivaquero/book-control | https://raw.githubusercontent.com/ivaquero/book-control/main/06-比例微分控制.typ | typst | #import "@local/scibook:0.1.0": *
#show: doc => conf(
title: "比例微分控制",
author: ("ivaquero"),
header-cap: "现代控制理论",
footer-cap: "github@eqt:ivaquero",
outline-on: false,
doc,
)
= 根轨迹
<根轨迹>
== 图像绘制
<图像绘制>
对如下闭环系统
#figure(
image("./images/block/closed-1.drawio.png", width: 40%),
caption: [闭环控制],
supplement: "图",
)
$ frac(Y(s), R(s)) = frac(K G(s), 1 + K G(s)) $
分子为$0$时得到的极点,即为根。
#tip[
对根的分析,就是对分子中变量函数的分析。
]
对传递函数
$ G(s) = frac(N(s), D(s)) = frac(∑_(i=1)^m (s - z_i), ∑_(j=1)^n (s - p_j)) $
- $N(s) = 0$时,$s_1 = z_1, z_2 = z_2, …$,称零点(zeros),$N(s)$为$m$阶
- $D(s) = 0$时,$s_1 = p_1, s_2 = p_2, …$,称极点(poles),$D(s)$为$n$阶
此时有如下规则
- 当$m ≠ n$,根轨迹(root locus)共有$max(m, n)$条
- 当$m = n$,随着$K → ∞$,根轨迹从$G(s)$的零点向极点移动
- 复平面实轴上的根轨迹存在于由右至左的第$2n + 1$个零点或极点左边
- 当$m < n$,则有$n - m$条根轨迹从极点指向$∞$
- 当$m > n$,则有$m - n$条根轨迹从$∞$指向零点
- 若存在复数根,其必共轭,其更轨迹关于复平面实轴对称
- 根轨迹沿渐近线移动
- 渐近线与实轴的交点为$δ = frac(∑ p - ∑ z, n - m)$
- 渐近线与实轴的夹角为$θ = frac(2 q + 1, n - m) π, q = 0, 1, …, |m - n| - 1$
- 根轨迹上的点满足$∠K G(s) = -π$
#pagebreak()
== 汇合点 & 分离点
<汇合点-分离点>
对弹簧阻尼系统
#figure(
image("./images/model/vibration.drawio.png", width: 40%),
caption: [弹簧阻尼系统],
supplement: "图",
)
有
$ dot.double(x) + 2 ζ ω_n dot(x) + ω_n^2 x = u $
其中,$ζ$为阻尼比,$ω_n$为固有频率。
此时,传递函数为
$ G(s) = frac(1, s^2 + 2 ζ ω_n s + ω_n^2) $
令$ζ = K$,化为一般形式,得
$ frac(1, s^2 + ω_n^2) dot.double(x) + 2 K ω_n dot(x) + ω_n^2 x = 0 $
整理得
$ 1 + K frac(2 ω_n s, s^2 + ω_n^2) = 0 $
此时,新的传递函数为
$ G_("new")(s) = frac(2 ω_n s, s^2 + ω_n^2) $
- 该函数的极点:$p_1 = j ω_n$和$p_2 = -j ω_n$
- 该函数的零点:$z = 0$
由
$ K frac(2 ω_n s, s^2 + ω_n^2) = -1 $
得
$ K = -frac(s^2 + ω_n^2, 2 ω_n s) $
其中,$s = σ + j ω$,于是
$ K(σ) = -frac(σ^2 + ω_n^2, 2 ω_n σ) $
求导得$σ = ±ω_n$,由上$σ$只能在实轴的左边,故$σ = -ω_n$,此时
$ K(σ) = 1 = ζ $
== 几何性质
<几何性质>
对复数
- $z_1 = σ_1 + j ω_1 = r_1 e^(i θ_1)$
- $z_2 = σ_2 + j ω_2 = r_2 e^(i θ_2)$
有
- $z_1⋅z_2 = r_1 r_2 e^(i (θ_1 + θ_2))$
- $z_1 / z_2 = r_1 / r_2 e^(i (θ_1 - θ_2))$
对
$ G(s) = frac(N(s), D(s)) $
令$s = σ + j ω$,则
- $r = frac(∏|z_i - σ|, ∏|p_j - σ|)$
- $θ = ∑ θ_(z_i) - ∑ θ_(p_j)$
= 补偿器
<补偿器>
== 超前补偿器
<超前补偿器>
对如下系统
#figure(
image("./images/block/closed-2.drawio.png", width: 40%),
caption: [闭环系统],
supplement: "图",
)
- 极点:$p_1 = 0$和$p_2 = -2$
- 零点:无
- 渐近线:$σ_a = (-2 + 0 - 0)/(2 - 0) = -1$
- 夹角:$θ_a = π/2$
绘制出图像,对$K$分析
- 当$K$较小时,$p_1, p_2 < 0$,函数收敛,收敛速度由$p_1$和$p_2$中较小者决定
$ X(t) = C_1 e^(p_1 t) + C_2 e^(p_2 t) $
- 当$K$增加,根移动至复平面,实部落在渐近线,收敛速度由$e^(-σ_a t)$决定
$ C(t) = C e^(-σ_a t) sin ω_n t $
此时,改变$K$并不能加快收敛速度。加速需使渐近线左移。
== PD 控制
<pd-控制>
根轨迹的性质,根轨迹上的点满足$∠K G(s) = -π$。所以,若想使渐近线左移,可以在极点左边补充零点和极点,使夹角和满足上述条件。
在增益前,加入新的控制模块$H = s + 8$,其中
- $s$为微分(derivative)
- $8$为比例(proportion)
#figure(
image("./images/block/compens-lead.drawio.png", width: 40%),
caption: [PD 控制],
supplement: "图",
)
这就是比例微分控制(PD control),这种控制器有两个明显的缺点
- 需要外来能量源
- 对高频信号敏感
此时,需要引入超前补偿器(lead compensator)
$ H(s) = frac(s - z, s - p) $
其中,$|z| < |p|$。
#tip[
这里的“超前”指相位提前。
]
== 滞后补偿器
<滞后补偿器>
对闭环系统,其误差为
$ 𝔼[s] = R(s) - X(s) = R(s) - 𝔼[s] K G(s) $
整理得
$ 𝔼[s] = R(s) frac(1, 1 + K G(s)) = R(s) frac(N(s), 1 + K N(s)) / D(s) $
假设$R(s)$为单位阶跃函数$1/s$,此时的稳态误差为
$
e_(s s) &= lim_(t → ∞) e(t) = lim_(s → 0) s 𝔼[s]\
&= lim_(s → 0) s 1 / s frac(1, 1 + frac(N(s), D(s)))\
&= frac(1, 1 + K N(0)) / D(0)\
&= frac(D(0), D(0)) + K N(0)
$
#figure(
image("./images/block/compens-lag.drawio.png", width: 40%),
caption: [closed-lag],
supplement: "图",
)
加入滞后补偿器(lag compensator)后,$𝔼[s]$变为
$ 𝔼[s] = R(s) - X(s) = R(s) - 𝔼[s] K G(s) frac(s + z, s + p) $
整理得
$
𝔼[s] = R(s) frac(1, 1 + K G(s)) = R(s) frac(N(s), 1 + K N(s)) / D(s) * (s + z) / (s + p)
$
稳态误差为
$ e_(s s) = frac(D(0), D(0)) + K N(0) * z / p $
若$z > p$,则可减小$e_(s s)$,即通过调整$z/p$可以减少$e_(s s)$。
#tip[
当$p = 0$,$e_(s s) → 0$,$H(s) = 1 + z/s$,此为比例积分控制。
]
= PID 控制器
<PID-控制器>
== 控制途径
<控制途径>
当$r(t) - x(t) ≠ 0$,有如下 3 种手段减小误差
- 比例控制:基于当前误差,调节$k_p⋅e$,其中,$k_p$为比例增益
- 积分控制:基于过去误差,调节$k_I ∫e dd(t)$,其中,$k_I$为积分增益
- 微分控制:基于误差变化,调节$k_D dv(e, t)$,其中,$k_D$为微分增益
将三者整合,得
$ u = k_p e(t) + k_I ∫(t) dd(t) + k_D dv(e, t) $ <pid>
两端同时 Laplace 变换,得
$ U(s) = (k_p + k_I 1 / s + k_D s) 𝔼[s] $
由此得到的 PID 控制兼具了以下两种控制的优点
- PD 控制:提高稳定性,改善瞬态响应
- PI 控制:降低稳态误差
== Cauchy 幅角原理
<Cauchy-幅角原理>
对复数$q = a + b j$,将其通过映射$F(s)$,可得新的复数$F(q) = a′ + b′ j$。
假设两个复数分别位于的平面称为平面$A$和平面$B$,则映射$F(s)$将平面$A$中的零点/极点平移至平面$B$的原点,此时
#figure(
table(
columns: 5,
align: center + horizon,
inset: 4pt,
stroke: frame(rgb("000")),
[], [幅角], [新幅角], [模], [新模],
[零点], [$ϕ_1$], [$ϕ_1$], [$v_1$], [$v_1$],
[极点], [$ϕ_2$], [$-ϕ_2$], [$v_2$], [$1 \/ v_2$],
[零点 + 极点], [$ϕ_1, ϕ_2$], [$ϕ_1 - ϕ_2$], [$v_1, v_2$], [$v_1 \/ v_2$],
),
caption: [幅角],
supplement: "表",
kind: table,
)
#tip[
幅角:零点/极点与平面内的任一点连线与横轴的夹角
]
#theorem("幅角原理(Argument Principle)")[
在$S$平面内画一条闭环曲线$A$,曲线$B$由曲线$A$通过映射$F(s)$得到,则
- 曲线$A$每包含1个$F(s)$的零点,曲线$B$就绕原点顺时针一圈
- 曲线$A$每包含1个$F(s)$的极点,曲线$B$就绕原点逆时针一圈
]
== 标准型
令$k_I/k_p = 1/τ_I$,$k_D/k_p = τ_D$,则@eqt:pid 变为
$ u(t) = k_p e(t) + 1 / τ_I ∫e(t) dd(t) + τ_D dot(e)(t) $ <pidstd>
其中
- $τ_I$为积分时间,表征积分项追上比例相的所需时间;
- $τ_D$为微分时间,表征比例项追上微分相的所需时间;
#tip[
积分项是历史误差的积累,比例相是对当前误差的响应,微分相是对未来误差的判断。
]
对@eqt:pidstd 两端进行 Laplace 变换,得
$ u(s) = k_p (E(s) + E(s) / τ_I + τ_D E(s)) = underbrace(k_p (1 + 1 / τ_I + τ_D), "C(s)") E(s) $
由于传感器的微分相往往不稳定,会放大高频噪声。引入一阶滤波器除数$N$,得
$ C(s) = k_p (1 + 1 / (τ_I s) + (τ_D s) / ((τ_D s) / N + 1)) $
其包含了1个极点和1个零点,分别为
$
s_p = - N / τ_D \
s_z = - N / (N+1) / τ_D
$
即得到一个超前补偿器,其不会无限放大高频噪声。
|
|
https://github.com/Az-21/typst-components | https://raw.githubusercontent.com/Az-21/typst-components/main/style/1.0.0/override.typ | typst | Creative Commons Zero v1.0 Universal | #import "dependencies.typ": *
#let style(doc) = [
#set page(
paper: "a4",
margin: auto,
numbering: "1",
number-align: center,
)
// Font
#set text(12pt, lang: "en")
#show math.equation: set text(font: "New Computer Modern Math")
#show raw: text.with(font: "JetBrains Mono")
// Spacing
#set par(justify: true, leading: 1.5em)
#show raw.where(block: true): set par(leading: 0.8em)
#show heading.where(level: 1): set block(above: 2em)
#show heading.where(level: 2): set block(above: 3em)
#show heading.where(level: 3): set block(above: 2em)
#show heading.where(level: 4): set block(above: 2em)
#show heading.where(level: 5): set block(above: 1em)
// Better defaults
#set list(indent: 1em)
#set math.mat(delim: "[")
#set pagebreak(weak: true)
#set heading(numbering: "1.1.1.1")
#set outline(indent: true, depth: 4)
#set math.equation(numbering: "(1)")
#set enum(numbering: "1a.", indent: 1em)
#set table(align: center + horizon, inset: 8pt)
// ```Code block``` style
#show raw.where(block: true): set par(justify: false)
#show raw.where(block: true): block.with(
fill: tailwind.neutral-200,
inset: 10pt,
radius: 2pt,
width: 100%,
)
// `Inline code` style
#show raw.where(block: false): box.with(
fill: tailwind.blue-300,
inset: (x: 0.5em, y: 0em),
outset: (y: 0.5em),
radius: 2pt,
)
// Heading 1
#show heading.where(level: 1): it => block(width: 100%)[
#counter(heading).display()
#h(1em)
#text(smallcaps(it.body))
]
// Heading 2
#show heading.where(level: 2): it => block[
#set block(spacing: 0.4em)
#counter(heading).display()
#h(1em)
#text(it.body)
#line(length: 100%, stroke: 1pt + luma(180))
]
// Heading 3
#show heading.where(level: 3): it => block[
#counter(heading).display()
#h(1em)
#text(it.body)
]
// Heading 4
#show heading.where(level: 4): it => block[
#counter(heading).display()
#h(1em)
#text(it.body)
]
// Heading 5
#show heading.where(level: 5): it => block[
\u{25B6}
#h(1em)
#text(it.body, size: 11pt)
]
#doc
]
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/23-12-07/23-12-07.typ | typst | #import "/template.typ": *
#show: project.with(
date: "07/12/23",
subTitle: "Discussione a seguito del meeting con il Professor Cardin",
docType: "verbale",
authors: (
"<NAME>",
),
timeStart: "16:00",
timeEnd: "16:40",
);
= Ordine del giorno
A seguito di un dialogo che il gruppo ha avuto con il professor Cardin in data 07/12/23, sono stati discussi i seguenti argomenti:
- requisiti non funzionali;
- raggruppamento degli Use Case;
- quali sono i criteri che definiscono un'Analisi dei Requisiti ben fatta.
== Requisiti non funzionali
=== Specificare le versioni
È stata sottolineata l'importanza di specificare, nei requisiti non funzionali, i numeri di versione specifici dei componenti tecnologici con cui l'applicativo dovrà interfacciarsi, in particolare:
- le versioni dei sistemi operativi che supportano l'applicativo;
- le versioni dei software di gestione del database con il quale verrà interfacciato l'applicativo;
- le versioni dei browser che supportano l'applicativo.
=== Requisiti di qualità
Altri requisiti non funzionali da includere sono relativi alla qualità e a come l'applicativo debba rispettare determinate norme prestabilite.
=== Requisiti prestazionali
È necessario analizzare e definire con particolare attenzione i requisiti non funzionali relativi alle prestazioni, in quanto serve descrivere minuziosamente il contesto che permetta di replicare il requisito (velocità della rete, cardinalità delle operazioni, ecc.) per poter poi imporre dei vincoli prestazionali su tale contesto.
=== Requisito relativo all'utilizzo di alfabeti non latini
Diversamente da quanto ipotizzato inizialmente, il requisito riguardante la possibilità di utilizzare alfabeti non latini è un requisito funzionale in quanto rappresenta una vera e propria feature che determina il comportamento del programma.
== Raggruppamento degli Use Case
La suddivisione degli Use Case è da svolgere in funzione alla loro leggibilità e utilità, perciò si ritiene più ragionevole suddividere gli Use Case relativi alla modifica dell'ambiente di lavoro in:
- modifica scaffale;
- modifica ambiente;
- modifica bin.
E successivamente, per ciascuno di questi, si può, in base alle esigenze, estenderli con i relativi Use Case legati a:
- creazione;
- ridimensionamento;
- spostamento;
- eliminazione.
== Criteri che definiscono un'Analisi dei Requisiti ben fatta
Le caratteristiche di un'Analisi dei Requisiti ottimale sono:
- sintassi dei diagrammi UML corretta rispetto allo standard;
- requisiti atomici;
- requisiti deterministici;
- requisiti non ambigui;
- requisiti non troppo generici;
- chiaro tracciamento del rapporto tra Use Case e requisiti e viceversa.
= To do
In luce di quanto concordato durante il meeting, le prossime attività da svolgere sono:
- dividere gli Use Case troppo grandi, in particolare quello relativo alla modifica dell'ambiente di lavoro;
- modificare i requisiti non funzionali sviluppandoli ulteriormente;
- aggiornare i diagrammi UML in funzione delle nuove modifiche agli Use Case.
|
|
https://github.com/TimPaasche/Typst.Template.Thesis | https://raw.githubusercontent.com/TimPaasche/Typst.Template.Thesis/main/main.typ | typst | MIT License | #import "template/style.typ": titlePage
#show: doc => titlePage(
title: "Template",
subtitle: "for Typst",
authors: (
(
name: "<NAME>",
mnr: 12345
),
),
abstractUS: lorem(80),
abstractDE: lorem(80),
scientificSupervisor: "Prof. x",
technicalSupervisor: "<NAME>",
oath: false,
doc,
)
= Zusammenfassung
<zusammenfassung>
= Abstract
<abstract>
= introduction
<chap:introduction>
#lorem(300)
#pagebreak()
== problem definition
<sec:introduction.problem_definition>
#lorem(300)
=== scientifique question
<subsec:scienifique_question>
#lorem(100)
#pagebreak()
== motivation
<sec:introduction.motivation>
#lorem(300)
#pagebreak()
== scientific questions
<sec:introduction.scientific_questions>
#lorem(300)
#pagebreak()
= basics
<chap:basics>
#lorem(300)
#pagebreak()
= state of the technology
<chap:state_of_the_technology>
#lorem(100)
#linebreak()
#linebreak()
#lorem(100)
#figure([#box(width: 50%, image("images/logos/HKA_EIT_Logo.jpg"))], caption: [
This is a figure caption
])
<fig:my_figure>
#pagebreak()
= concept <chap:concept>
#lorem(100)
#pagebreak()
= implementation <chap:implementation>
#lorem(40)
#v(1cm)
#figure(
```python
# This is some Python code
print("Hello, world!")
```,
caption: "python Code"
)
#pagebreak()
= result
<chap:result>
#lorem(100)
#figure(
table(
columns: 3,
table.header(
[*A*],[*B*],[*C*]
),
//1. row
[1],[2],[3],
//2. row
[4],[5],[6],
),
caption: "This is a table caption"
)
#pagebreak()
= possible usecases
<chap:possible_extensions_usecases>
#lorem(100)
#pagebreak()
#bibliography("./src/src.bib", full: true, title: "Literaturverzeichnis")
#pagebreak()
#outline(
title: [Abbildungsverzeichnis],
target: figure.where(kind: image),
)
#pagebreak()
#outline(
title: [Tabellenverzeichnis],
target: figure.where(kind: table),
)
#pagebreak()
#outline(
title: [Sourcecodeverzeichnis],
target: figure.where(kind: raw),
) |
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/old-stuff/h-zksnark.typ | typst | #import "preamble.typ":*
This part covers two constructions of the zkSNARK,
the *PLONK* and *Groth16* constructions.
Despite being fairly modern constructions,
these are arguably simpler and more informative to learn about than
the PCP construction that preceded them (which is covered in @pcp).
The dependency chart of this chapter goes as follows:
- @ec describes the discrete logarithm problem on an elliptic curve,
which provides a basis for everything afterwards.
- @kzg and @ipa give two different *polynomial commitment schemes*,
which allow a prover Peggy to
- commit to some polynomial $P(X) in FF_q [X]$ ahead of time,
- and then *open the commitment* at any input $z in FF_q$ while not revealing $P$ itself.
The KZG scheme from @kzg is quite simple and elegant but requires a trusted setup.
In contrast, IPA from @ipa has fewer assumptions and is more versatile,
but it's slower and more complicated.
- Regardless of whether KZG/IPA scheme is used,
we then show two constructions of a zkSNARK.
In @plonk we construct PLONK;
in @groth16 we construct Groth16.
|
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Diagrams/idea1.typ | typst | ```pintora
erDiagram
Module {
INT id PK
INT credits
INT hoursPresence
INT nameId
INT subTitleId
INT descriptionId
INT examId
INT learningOutcomesId
}
Translation {
INT id PK
STRING German
STRING English
INT languageId FK
}
``` |
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/052%20-%20March%20of%20the%20Machine%3A%20The%20Aftermath/001_She%20Who%20Breaks%20the%20World.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"She Who Breaks the World",
set_name: "March of the Machine: The Aftermath",
story_date: datetime(day: 01, month: 05, year: 2023),
author: "<NAME>",
doc
)
<NAME> is digging her grave. Under the cover of night, she drives her shovel into Zhalfir's ground and wipes sweat from her brow. The task should come easily to her. It's just dirt, after all. Once, she could bend nature with a whim, but now her heart pounds, her limbs shiver. She concludes she must have overexerted her recovering body and decides she will take a well-deserved rest upon completing this task. But she cannot ignore the question that claws at her heart: is this what happens when a Planeswalker loses her spark?
She asked the others what happened, but they could only describe the battle and her revival. No one could answer what had happened within her soul. Chandra suggested it was a side effect of her revival. Karn theorized it was damaged when the Phyrexians altered Nissa's mind and body.
But Teferi only listened and nodded. "It's not just her," he said.
Teferi's spark had faded sometime after the invasion. Koth's as well. Chandra is the only one among them who seemed to have kept hers—well, Chandra and Ajani.
The sylex had gone off in the Blind Eternities. Holes had been punched in the space between planes. Maybe this is some sort of natural response from the Multiverse; a great pruning, a taking back of that mysterious energy that once filled them. It doesn't matter the cause, though. No amount of theorizing offers Nissa comfort.
So, to comfort herself, she touches the heavy clod she lifted from the red earth, but the dirt does not reassure her like the familiar soil of her homeworld, Zendikar. She squeezes it between her fingers. She asks the plane how it feels, but it does not answer. Perhaps the damage extends beyond her spark, right to her animist powers.
#figure(image("001_She Who Breaks the World/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
She hears something else, though. Not the deep, reverberating, voice of a plane that shakes her very soul, but something distant, lively, and human: music. The drums of Mirrodin and Zhalfir are celebrating their victory over the Phyrexian invaders. Since leaving the austere Joraga clan in her youth, music had become her favorite indulgence, but today it mocks her, does nothing but make her chest ache. She knows somewhere in the firelight, her friends are celebrating, too.
Just that morning, Karn and Koth had finished roofing the last house in a new village. Nissa saw relief—even happiness—in their eyes as they moved in alongside the Mirran refugees, for they were all united as survivors. They had invited her to join them.
"Are you sure I'm welcome?" she had asked.
"Of course." Teferi put his hand on her shoulder and said, "You will have a new home here if you just try."
So Nissa worked with the other survivors, ate with them, talked with them. But it wasn't the same. Teferi had his country again. Koth and Karn were forging a new one. Nissa's Zendikar was locked a Multiverse away.
But Zhalfir still never spoke to her. Neither did the five colored suns, more refugees from Mirrodin now at home in Zhalfir's sky. She felt cut off, lost in the Multiverse with no voice calling her home. Maybe no plane would hear her ever again. They'd all lost their sparks, but only Nissa still wanted to planeswalk.
Even if her friends seemed to be moving on without her, she still cared about their happiness. So not wanting to bring down the spirits of their celebration, she excused herself. There's at least one task she can do. She thrusts her shovel into the ground.
Again.
And again.
Finally, the hole is deep enough. Next to it, her Phyrexian carapace awaits burial. With the Phyrexian leader dead and her virulent vice grip on the glistening oil severed, the survivors were able to cleanse it with Halo, but the inert metal remained. Its copper skeleton is covered in mangled spikes, and those spikes are covered in the dried blood of her friends. She rubs one, and dark residue flakes off on her fingertips. She wonders whose blood it was. Maybe Koth? Maybe Wrenn? Maybe Chandra?
Chandra.
She had hurt Chandra, almost killed her.
Nissa and the other Planeswalkers had tried to fight the Phyrexian invaders, but they became the enemy's weapons. After the Phyrexian defeat, Nissa's friends said they forgave her. They cut her out of her metal prison and cleansed her mind of the Phyrexian influence. They cleansed the oil from her Stem Sword, but they could not cleanse the memories of what she had done.
The copper ribcage had been both trap and armor, a construct of crippling terror yet intoxicating power. It granted her the ability to unleash a call through the branches of the Invasion Tree and speak the glory of Phyrexia to every plane in the Multiverse.
And right now, Nissa is disgusted with herself because—despite her friends' sacrifices, despite Chandra's sacrifices—part of her misses hearing those planes.
She tries to kick the carapace into the grave she dug, but it is heavy, heavier than the shovel, heavier than the earth.
Someone behind her speaks, "You left the party early. Wanted to make sure you got something to eat."
Nissa would recognize that voice anywhere. She turns to face <NAME>, arm outstretched, offering her half a ripe mango. The smile on Chandra's face is warm, and Nissa knows she does not deserve it.
Nissa shakes her head, "I'm not hungry."
She watches Chandra's gaze drift to the shovel and then the emptied Phyrexian shell. "Need help?"
"I'm fine."
Chandra steps forward anyway. She hands the mango to Nissa and puts her palms against the copper hull. Heat radiates from her fingers, and the dirty metal starts to cave under her touch. Her hair ignites into a shock of flame.
Nissa can't help but think she's so beautiful like this.
The spikes bend down with the heat. The carapace softens into a formless hunk of slag. The smell of cooling metal fills the night air, and Nissa wants to tell Chandra to stop, to let her have just this one small success.
But instead, she still tells Chandra, "Thanks."
"No problem!" Chandra winks, and with one swift kick, punts the crumpled skeleton into the hole. Without hesitation, she gestures for Nissa's shovel. "The sooner we fill this hole, the sooner you can get back to having fun!"
Instead, Nissa hands Chandra the uneaten mango. "I'll celebrate when I'm done."
Chandra drops the mango to grab Nissa's wrist with both hands. Her palms are so warm. "Just do it later, then! C'mon!"
Nissa knows Chandra's just trying to make her feel better by focusing on their victory, but it's not working. She slides gently out from Chandra's grasp. "I'll be quick. Promise."
But Chandra does not leave. She paces around, using her foot to nudge dirt into the grave when she thinks Nissa isn't looking. There's something she's not saying.
So Nissa asks, "Is there a reason I have to go right now?"
Chandra gnaws her lip before lowering her head and softly admitting, "Because if you're too late, I might not be there."
As Chandra's words sink in, Nissa's memory drifts back to the day she awoke in Zhalfir. The first thing she felt was Chandra's warm hand gripping her own, and the first thing she saw was Chandra's broad smile. Her limbs were weighed down by dead copper metal, but her thoughts were hers. Chandra's smile was hers.
#emph[I'm right here. ] Chandra had said. #emph[I'm right here, and I'm not going anywhere.]
Nissa wants to stay something, to remind Chandra of her own words. But before she can protest, Chandra's voice spills out to fill the quiet she can't stand. "Tomorrow, I'm leaving to find Ajani."
Nissa opens her mouth to reply, but she doesn't know how to respond to a broken promise. Her reticence only troubles Chandra further.
"It's only for a bit! Only until I find him. I'm one of the few people who can still planeswalk, right? If I can't bring him back, who can? And I know you'll be right here, waiting for me—"
But Nissa does not want to wait here. She doesn't get to choose, because she's not a Planeswalker.
Nissa barely hears herself when she whispers, "But you kissed me."
You finally kissed me.
Chandra shifts from foot to foot. "I mean, yeah, but I still gotta go—"
The rest of Chandra's words mean nothing to Nissa. How could Chandra love so many people so freely? Yet leave her so easily? Does she lack more than just a spark? She has to know.
Nissa steels her voice. "Then be clear—exactly what kind of love do you have for me?"
Nissa watches anxiety build inside Chandra, made of words she doesn't know how to say, turning into frantic hand gestures that start, stop, and start again as if her fingers could shape her jumbled thoughts into sentences. What comes out is, "I~ I~" Chandra's hands drop to her sides. "Like, I knew I had to save you."
"You're a hero, Chandra, a Planeswalker. You'd save anyone." Nissa thrusts her shovel into the ground. "Am I no different than anyone else?"
"No, that's not it! It's~ it's~ it's hard to explain—it's just so big, like, I can't describe it. Isn't that enough? Can't you just believe me when I say you mean everything to me? Everything!"
Nissa frowns. Because what Chandra is saying doesn't match what Chandra is doing. Nissa thought Chandra would know better. That the kind of love Nissa needs is one that won't leave her. Or has she once again been drawn into Chandra's inextricable orbit only to be trapped in a one-sided love? Like her own personal, Immortal Sun.
"Please," Chandra begs. "Can't you at least tell me if something's wrong?"
Nissa looks down at the charred husk of her metal bones. To Nissa, her pain is so obvious, but she doesn't have the strength left to describe it, let alone heal it. She couldn't tell Teferi, Karn, or Koth about it, and she still can't even tell Chandra. Nissa shakes her head. "Go, then, find Ajani, and I'll just wait here."
Chandra cups her hand around Nissa's cheek and gently turns her head until their eyes meet. She bites her lips, and her voice is low with consolation. "I'll be back," she says, "Zhalfir's not a bad place, Nissa. I think you'd like it if you tried."
<NAME> is sick of trying. Turning to hide the tears welling in her eyes, she picks up her shovel. She does not watch Chandra planeswalk away, but Nissa can still smell the scent she leaves behind, like the last wisps of smoke from a fireplace.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Nissa wakes the next morning, and the first thing she feels is Chandra's absence. Instinctively, she reaches out to the soul of this unfamiliar plane for comfort, but Zhalfir is silent. Perhaps the land also hurts because it misses its home. The sting of a second abandonment pierces her heart, and she even wonders whether Ashaya, the elemental Worldsoul of her homeworld, would still recognize her call.
Nissa's nickname, Shaya, meant Worldwaker, not world breaker.
She lies on her bedroll, counting every inhale, every exhale. It's been a long time since she truly meditated. She used to practice every day before she joined the Gatewatch, before she met Chandra. She should try again.
But not here. Every voice, every sound, every vibration of life outside her tent reminds her how the distance has grown between her and her friends. Still, there's one who might understand.
Nissa takes her staff and climbs the forested hill that overlooks the village. Awkwardly, she lowers herself to the ground, sitting with her legs crossed beside the sprout that used to be Wrenn. She's growing fast, nurtured by the light of Zhalfir's five newly inherited suns.
Nissa had only spoken once to the dryad, and there's no point in speaking to the seedling. Nevertheless, she feels a unique kinship with the only other Planeswalker who bound herself to the Invasion Tree. Nissa saw so many ugly things from her time as a Phyrexian, but one beautiful moment stands clear in her mind. When Wrenn knit her fragile body into the sinew of the Invasion Tree, Nissa's bones were filled with haunting, beautiful music. It was more than a single treesong. It was a hymn sung by a chorus of planar voices, played on the strings of leylines.
Nissa tries to remember that song now. She closes her eyes and slows her breath. She listens to her heartbeat, willing it to calm with each inhale and exhale. She reaches into herself, to the roots of her soul. And she listens.
A song lies beyond the silence.
Its low tone rumbles deep in Nissa's chest, like her early days as an animist, before Ashaya. She turns her heart toward it, but she hears something else. A quiet, tinny, ringing coalesces behind her eyes.
Never mind that. She focuses on that song, the planar magic. But when she does, the ringing grows. She calls louder, and so does the noise. Her ears are itching, twitching, burning now.
Still, she tries again. Her heart pounds. Her soul screams out to the whispered song. But her cry is muffled by dozens of new, alien voices she recognizes and despises: the Eldrazi, Bolas, and finally, loudest, Phyrexia.
The ringing explodes into skull-shattering static. Vivid, lightning pain crackles in her muscles and up her spine. Colorful sparks explode in the dark of her vision.
She screams for real.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When Nissa opens her eyes, she's lying flat on her back in the shade of a nearby acacia, and the silent truth stares back at her: every being who touched her mind was now buried in her soul. She has spent so long connected to others that she has smothered her own connection to the Multiverse. Whether or not those bonds were made of her own volition, the planes have rejected her.
She rises unsteadily to her feet. As her vision sharpens, she sees a blue light hovering in the air, a glow pulsing to the beat of the leyline song. Its edges resemble ragged cloth, as if someone took a knife to the fabric of reality. Nissa reaches toward it and quickly pulls her hand back as a bolt of electricity jumps to her fingers.
With a thunderous boom, the light tears open.
The force throws Nissa to the ground. She scrambles to her knees just in time to dodge the massive creature that burst from the light. The beast is like nothing she has seen before, a predator larger than a bear with deadly claws that emit curling storm clouds. Golden fissures of lightning trace its muscular body, emitting sparks that threaten to ignite the dry grass. The ground cracks under its feet, and with a swing of its limbs, a nearby shrub goes flying. When it sees Nissa, it bellows with rage.
She can't let it near the village. Too many are still recovering from the wounds of war. They cannot handle a frenzied animal.
<NAME> may not be a Planeswalker, but she's the only person here right now.
She rolls across the ground. With one smooth motion, she grabs her staff and charges it with magic. Its tip lights green, and the desert grass bends to her will. It entwines with itself, becoming thick ropes to entangle the creature's legs. But on contact with its electric skin, the plant matter dries and crumbles to ash. Nissa summons roots, branches. The enraged beast tears through them all the same, leaving dust in its wake.
Still, she bought herself an opening to get back on her feet. With one deep breath, she tries to recall what it felt like to be a hero, to stop letting this creature play her like a game piece and become the hand that moves it.
She wraps her fingers around her staff, and its twisted wood comes to life. Green vines curl around her wrists as she draws the sword from its heart. She sends her magic down the blade, and its metal shines green. She steps nimbly forward, but the use of even a little magic has somehow winded her.
The beast lunges, but this time Nissa is ready. She vaults upward onto its back. When it rears, she has to dig her grip into its fur just to hold on. Burning heat pierces her glove, and she knows she won't have long.
She doesn't want to hurt the creature, but she needs to immobilize it. She drives her sword into one of the lightning cracks on its flank—not too far, just a prick for something so large. Green magic unwinds from the blade, solidifying into thick, spiked vines that pierce the creature's leg and wrap around its body. The beast bucks wildly before dropping to its damaged knee. The movement throws Nissa into the air, and she has barely enough time to tuck into a roll before hitting the ground.
#figure(image("001_She Who Breaks the World/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
She rights herself and looks at the animal. Her weapon is still wedged in its side. She watches the vines connected to it burn away again. The creature shakes and rises, unscathed and even angrier. Its eyes meet hers as her sword falls out, useless, onto the ground.
Nissa presses her hands to the earth, calling to the leylines for help as she used to. The ground glows under her touch as she asks, pleads, begs, for an elemental to appear. The pebbles around her tremble, and hope rises in her chest.
Then they fall right back down.
Zhalfir cannot hear her.
The creature charges directly into her, catching her on its broad claws. With a shake of its massive arms, it tosses her forward and she lands yards away with a sickening crunch. Pain explodes through her entire body.
Through bleary vision, she lifts her chin and sees the beast readying to charge, claws extended to gore her and lightning crackling down its spine. Perhaps this creature is no ordinary animal. She thinks back to how it appeared when she tried to reach the leylines. Maybe this #emph[is ] an elemental she summoned, one sent by Zhalfir to avenge the wrongs she had committed in the name of Phyrexia.
She does not want to die. But she cannot deny her crimes deserve it.
She lets her head drop fully to the ground. After all, why fight the world when you know who will win?
The creature lunges forward, fangs bared. Nissa braces for the blow.
When suddenly, the beast stops.
It hangs suspended in time, gnarled claw ready to strike. Nissa feels strong, warm, hands lifting her out of danger, and Koth's voice tells her, "We've got you."
"Don't hurt it~" Nissa tries to say, but she isn't sure anyone can hear her.
She sees Teferi, staff outstretched, his radiant, blue spell holding the beast in place. Karn moves toward the creature and wraps his massive metal arms around the creature's neck.
"I'm going to let go now," Teferi states.
Karn nods. "Ready."
Time resumes. The beast finishes its swing, but its claws strike only air where Nissa used to be. It wrestles against Karn, but its claws rake uselessly against steel. It gnashes its fangs, but Karn tightens his chokehold so it can't turn its neck.
Then the air grows hot with the smell of ozone, and white lightning bursts from the creature's skin. The explosion throws all four to the ground, and Nissa lifts her head just in time to see the creature barrel into the distance, storm clouds trailing behind it.
Koth is back on his feet, sliding his arm under Nissa to help her up. He returns her weapon, now back in its staff form. "Are you hurt?"
"I'm fine." Nissa struggles out of his grip. She takes the staff, using it to stand despite the pain throbbing down her entire body. "How did you find me?"
"Teferi was going to visit Wrenn when he saw a strange light at the top of the hill and gathered us to investigate. Luckily, she's all right, too," Koth says, gesturing toward the plant.
"It's one strange light, all right," she hears Teferi say. He stands in front of the place the beast emerged, where she had seen the hole in reality. Now, the gap is a massive portal, tall enough for any of them to walk through, even Karn.
"The creature," she explains. "I think it came out of there."
The portal calls to Nissa. Something on the other side hums with the energy of a leyline song. It's like a chorus of overlapping, chaotic, melodies from different planes, but through it all, she feels a familiar vibration. It's faint, but it sounds like Zendikar. Even if the plane cannot hear her, her heart instinctively fills with longing. But she needs more than instinct. She needs to understand. So she dares to ask, "Where do you think it leads?"
She wants it to lead her home.
"Hard to say," Teferi muses. "But that beast certainly wasn't from Zhalfir."
Desire grips Nissa's chest even harder. "Could it have traveled from another plane?"
Karn appeared to shrug, an awkward gesture with his massive shoulders. "It's possible. Realmbreaker burrowed holes through the fabric of reality. The sylex exploded in the Blind Eternities. Who knows what that might have changed."
Nissa's throat tightens as she speaks. "Do you think that one of us should go through?"
Silence passes over the group, and Nissa begins to worry. They could merely be thinking, or there could be something they aren't telling her.
Finally, Karn shakes his head. "The risks there are incalculable. If it indeed led to the Blind Eternities—without a spark, you could be instantly destroyed."
"But that creature wasn't destroyed!" Nissa shakes her head. Every frail strand of hope that she has built frays and snaps. Again, this is what it means to not be a Planeswalker.
Teferi places a reassuring hand on Nissa's shoulder. "Or it's possible that creature is a Planeswalker. But that's only one of an infinite number of possibilities. We don't know where this portal leads, so we can't say for sure what will happen. But to step through~ well, that would simply be a leap of faith."
A leap of faith.
Nissa is not the type of person who takes leaps of faith. Chandra, though. Chandra is a person who could do it. Without even thinking.
Koth speaks, interrupting their analysis. "I feel the need to remind everyone that the creature is still out there, and it's lost and angry. Our people have suffered greatly, and we have a duty to protect our new home from further risk." He nods at Nissa. "Let's corral this creature, and then we can talk about exploring."
The group agrees, and as much as Nissa loathes to abandon the portal, she knows Koth is right. As much as the war took from her, others have lost even more. They need to help first.
Teferi, Koth, and Karn have already begun to walk down the hill. Nissa follows as quickly as her tired legs and aching ribs can, but before joining them, she takes one last look at the glowing portal behind her.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Nissa still hurts. She lies on the bedroll in her tent, reaching for sleep that will not come. The Civic healer had looked exhausted, but she still took the time to look Nissa over. Nothing seemed broken. Nothing physical, anyway. Even so, she still made Nissa stay behind when Teferi, Karn, and Koth went to find the lightning beast. In some ways, Nissa is glad for the rest because it means she can be alone.
She hears muffled voices outside, going about their daily tasks, gossiping about people she has never met. She rolls over and attempts to sleep again. Times like these make her wish elven hearing wasn't so sensitive.
But then, the voices quicken, grow louder, and her calm is shattered by a scream. Followed by the sound of thunder.
Electricity heats the air, making her hair stand on end. Nissa has no doubt: the creature from the portal is here. Dread sinks into her stomach. What if it's looking for her? What if it followed her here to complete its mission?
Her actions have left the village unguarded and in danger. She staggers upright, grabbing her staff as she exits the tent.
Still not a Planeswalker, she thinks. Once again, just the only person around.
The creature is busy ransacking the mess tent. The ground is littered with torn canvas and spilled pots of stew. Even the largest wooden tables have been cracked in half, reduced to splinters. A brave team of Zhalfirin and Mirran warriors have surrounded it, but she can see their weapons are still in desperate need of repair from the fight with the Phyrexians. She needs to help them lead it away from the village.
With the help of her staff, she casts her magic forward. Thick roots emerge from the ground. They loop around the beast's neck and limbs, trying to tie it down or at least pull it in another direction. The effort causes Nissa's legs to shake, but she wills herself to stay standing.
She won't have much time until it burns the restraints away, but she takes advantage of its confusion. There! She runs toward a thick baobab tree just outside the village.
"Over here," she growls, unleashing another barrage of angry vines.
The creature takes the bait. It turns away from the villagers' swords and spears, mere nuisances compared to this prickly, new attacker. It swings at the plants, claws cutting them down like a scythe. A few feet away, Nissa raises another onslaught. The beast lunges forward again to chase its quarry. Slowly, vine by vine, swing by swing, Nissa leads the creature out of the village.
She breathes a sigh of relief to see the wounded inhabitants hurrying to safety. She's done one good thing at least. But the effort has exhausted her. The green light in her staff fizzles. She collapses to her knees.
And the creature has only one target now: Nissa.
It looms above her, claws ready to strike her down.
It's so damn big up close. Nissa raises her staff in defense and braces for impact.
Again, it doesn't come.
A lone, burning, figure stands in the way. Chandra.
Internally, Nissa curses the knack for Planeswalkers to show up exactly where there's trouble. Chandra has thrown up a barrier of fire between them and the creature. The beast staggers back and forth, trying to reach the prey it cornered just a second ago.
Now, she's hurling fireball after fireball at the animal, which is growing more and more agitated. It shakes, and static sparks off its fur. She instructs Nissa, "I'll take it from here! Head back to the village!"
But Nissa was the one who summoned the creature. It followed her here, not Chandra. This is Nissa's fight, and Chandra can't even let her have that. Her staff blazes with green light. Hundreds of thorny vines thrust from the ground. One almost hits Chandra in the face.
"Hey! Watch it!" the pyromancer shouts.
The vines whip at the beast. It roars against each stinging strike. One of them catches a fireball and ignites. The beast whines slightly, moving away from the flaming lash. Nissa watches Chandra crank up the heat. She grits her teeth as she watches every vine she conjured disintegrate in a blast of flame. It was as if she hadn't done anything at all. Sweat forms on her brow as she searches the landscape for her next move.
Her eyes pass over the baobab. The baobab! Their thick trunks resist fire, and the massive tree would be a staunch ally if she could animate it. She reaches her magic toward it, coaxes each branch to life. But she's not summoning an elemental that walks of its own accord, she must concentrate with all her effort, will it to move, puppet every action. Her breathing is labored. Her trembling palms sweat under her gloves.
Stem by stem, root by root, she forces it out of the ground. She gives it one final push, launching it at the beast. It hits the creature in the side, bowling it over into the grass. Tired as she is, Nissa still relishes the fleeting feeling of victory.
Because Chandra takes this as her cue. "Thanks!" she grins. She burns even hotter. Too hot. She encloses the beast and the tree in a ring of flames as tall as an elephant.
Nissa smells smoke, and she realizes the dry grass is starting to kindle. "Chandra, stop!"
The pyromancer doesn't seem to hear her, or doesn't seem to care. She tightens her circle, closer to the creature. It paces the edge, panicking as the flames close inward. It rears up, claws and teeth thrashing, and smashes the baobab to pieces. The water inside the tree evaporates immediately on contact with Chandra's superheated flame, turning into white steam.
Neither Nissa nor Chandra could have predicted the creature's next move. It inhales. With one deep breath, the storm beast sucks the hot steam from the sky. The added moisture makes it double in size. More than double. Now colossal, it bats away the shards of broken tree like playthings. The burning debris sets the grass ablaze wherever it lands.
It towers over the women.
They run, but every step the creature takes equals twenty of theirs. Soon, they find themselves directly under its massive form. It readies an attack.
"Watch out!" Chandra pushes Nissa out of the way of its snapping jaws, sending them both tumbling into the hole left by the uprooted baobab.
When the dizziness of the fall fades, Nissa looks up. The beast is scratching, gnashing at the opening, but the gap is too narrow for his huge form. They're safe, but for how long?
"Aaaaaaaaaaarrrrgh!" Chandra's lit hair flares with frustration. She points her hands up toward the creature, another blast charging in her open palm.
The beast has them trapped. The entire savannah is going to burn. "Stop!" Frustration and loneliness fill Nissa's lungs, emerging in a howl. "Just let me save myself for once!"
The light fizzles in Chandra's hands. "What?"
Nissa's heart is trembling, but this time, not from exhaustion. She uses all the energy she has left to turn her thoughts, her regrets, her worries, into words. "You made me a promise, Chandra, and you still left. Do you think," she says, voice cracking, "that because I no longer have a spark, that I'm happy to see you running around the Multiverse like nothing has changed? That I'm happy just waiting for you to come back?"
The flames in Chandra's hair extinguish themselves, returning to warm, natural red.
Nissa chokes as she speaks. "If that's how it's going to be, you don't need to return. I'll take care of myself."
Chandra pauses, thinking about what to say, and lowers her head. Her voice is soft when she answers, "No. I know you. Well, #emph[knew ] you. I guess things have changed. And they're still changing." She raises her warm eyes to meet Nissa's. "But I still want to know you."
Chandra takes Nissa's hands in hers, and Nissa's heart leaps to her throat.
"Nissa, I'm so, so, so, so sorry. Spark or not, you're an incredible fighter and even better person, and I'm so sorry to have ignored that."
But Nissa's soul still aches. She isn't ready to forgive just yet.
At that moment, fire and dirt begin to rain down on their heads. Unable to reach them, the lightning beast has decided to smother them instead. "Perhaps we can stop it if we work together," Nissa says.
Chandra nods. "All right, what's the plan?"
Warmth swells in Nissa's chest to finally be asked, but without her strongest magic, she can only respond, "I don't know."
"Is there anything we've done before?"
Nissa thinks back. Every time before, the elemental magic had come so effortlessly. She now knows she was taking it for granted. She bats away a hail of dirt from above.
"There's gotta be something," Chandra urges. "What about when we channeled my pyromancy through Zendikar's leylines? If it beat an Eldrazi, it'll work here, right?"
"But~" Nissa's admission comes as a whisper, "I~ I~ I can't reach any leylines anymore."
"What?"
Nissa shakes her head, coughing from the dust cloud forming around them. "They won't listen to me. I tried. Many times. But when I call out to them, it's like my voice isn't my own. Like it belongs to Phyrexia instead, like everything I've ever connected to is drowning me out."
For once, Chandra pauses. "You know," she concludes. "You have good connections, too."
"What do you mean?"
"It's true—you did bad things while they had you. But everyone you've connected with over the years with the Gatewatch, we're just happy you're still here. With us." Chandra sets fire to a chunk of moist dirt that was about to fall on Nissa, turning it into a soft rain of ash. "#emph[With me] ."
For the first time since she awoke in Zhalfir, Nissa smiles. Chandra, sweet Chandra, even if she doesn't realize it, has always understood and explained emotions better than Nissa ever could.
Chandra continues, "Your connections aren't drowning your voice, Nissa. They're changing it into something new, maybe something even more powerful. Infinite voices, infinite possibilities, right?"
Infinite possibilities. Nissa offers her hand to Chandra. "All right, let's try."
Gripping Chandra's fingers in hers, Nissa closes her eyes. She retreats inward and listens for her inner voice. It's hard, much harder than before, but Chandra is dutifully helping her concentrate, blasting the falling rock away before it can reach her.
Nissa is greeted by ringing deep in her ears, but she refuses to be deterred. With her connections in mind, she picks the static apart into unique melodies, the individual songs she picked up from all around the Multiverse. She arranges them, harmonizes them, and this time, when she calls to Zhalfir, her voice is amplified in chorus. She offers an apology.
The plane answers. It too was cut off from everything it knew, from the connections it had made. It, too, was scarred by Phyrexia and is growing into something new. It forgives her, and Nissa can finally forgive herself.
#figure(image("001_She Who Breaks the World/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Magic floods her flesh, her blood, her bone. She hears Chandra laugh, delighted by their success.
Nissa uses the elemental power to reach out to the creature. It's an elemental, but one made of unknown power which neither Nissa nor Zhalfir recognize. But Nissa can sense its disorientation and confusion, trapped in an earthly form by Zhalfir's unfamiliar magic and trying desperately to return to the pure energy that created it. Kind of like Nissa. The answer dawns on her.
"Steam," Nissa announces.
"Huh?"
"It's a storm elemental, a creature made of magic. But it's from another plane, so it's struggling to tap into Zhalfir's power. I think we can give it the energy it needs if we heat it up."
Chandra winks. "Heat? Now that I can do."
Nissa lets Zhalfir in and directs its power into Chandra. Her vision becomes a blinding, shimmering green. But even if she cannot see, she can feel Chandra's hand in hers. It grows warm, warmer, until it is unbearably hot, but she does not let go.
Fire magic, like a miniature sun, coalesces in Chandra's free hand, so bright that Nissa can see it through the green. With their connection made whole, Nissa sees what Chandra sees, feels what Chandra feels. Chandra aims upward, and a solid column of fire catches the lightning creature in the face. Together, they watch the beast inhale.
Chandra pours heat and energy into the creature. Its molecules and magic begin to vibrate faster and faster. Its fur melts into vapor. The lightning seams on its body crack and expand, and the beast breaks into pieces that convulse so furiously they liquify and then evaporate. Jets of steam escape its fading form and rise into the air, coalescing into a rumbling thunderhead overhead. Nissa wants to believe the cloud is grateful with laughter.
She laughs. And when the green light fades from Nissa's eyes, she sees Chandra, hair ablaze and laughing, too.
Rain falls in the desert.
One by one, fat droplets from the sky coalesce together into a torrent. A torrent becomes a flood. Water fills the crevasse they are trapped in, buoying them up. Soon, they are floating together, watching the cloud move away to reveal a clear, night sky. Chandra, hair still on fire, looks every bit like a lantern on the water.
She watches Nissa, refusing to take her warm eyes off the elf for one second. "Love comes in a lot of forms. I loved Gideon. I loved Jaya. You asked me what kind of love I had for you. I didn't know how to say it."
Nissa's heart beats faster. "Then what would you say now?"
Instinctively, Chandra tries to move her hand while she talks, creating awkward splashes around her. "It's still hard to describe. When I saw you there in New Phyrexia, I realized I wanted to save you more than I wanted to save the world. My love for you~ It's like when you left the Gatewatch, came back to the Gatewatch—it's not perfect all the time, but I want to do my best."
"I don't understand. How can love change?" To Nissa, it seemed like such a straightforward emotion, with the same primal, immutable quality as magic.
Chandra looks away to hide her face, but Nissa can tell her cheeks are as hot as her flame. "Sometimes, you convince yourself it's better to do what's easy, assumed, natural~ because it's easier than facing the unknown. Under stress you become who people expect. Throw that giant fireball instead of thinking first, you know? But you saw past that. Always. You made me better."
Emboldened by Chandra's vulnerability, Nissa musters her own honesty. "But you hurt me. I don't want to be left alone again."
"And I'm sorry. More sorry about that than anything I've ever done in my entire stupid life." Chandra turns to face her again, eyes bright with a new promise. "When I went to find Ajani, I realized he doesn't want to be found. He'll come back when he's ready. I'm still frustrated, of course, but I have to give him time and space. That's when I realized I can't just burn through any relationship I care about. Love leaves room for the other person to be who they are. I have to make room for you, too. I want to."
"Like fire needs oxygen~" Nissa asks her final question. "You have room for someone who can't planeswalk?"
"Yes. I'll make it. I will falter, I will be tempted, but I will make it. Fire's going to burn, no matter what you do, but you can shape it if you try. And I want to try. For you."
Nissa thinks for a moment. Finally, she nods. "I can handle that."
She leans over and places her hand on Chandra's neck, pulling the pyromancer toward her. Their eyes meet one last time before closing, and Nissa pulls Chandra into a kiss.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The sudden storm had caused a flash flood that stranded Teferi, Karn, and Koth in a cave a few miles outside the town. They were unable to return until the next morning after the waters receded. Nissa, Chandra, and the villagers welcome them back with blankets, warm stew, and smiles. Later that night, the friends celebrate the women's clever victory. This time, Nissa joins in. She and Chandra split the sweetest mango she'd ever tasted.
When the last bonfire dies down, Nissa takes Chandra's hand in hers and leads her up the hill overlooking the village. She waves at Wrenn before stopping in front of the portal.
"Here it is," she gestures, "the place where the creature came from."
Together, they gaze into the swirling blue light. Chandra asks, "Where's it go?"
"I don't know," Nissa admits. "Neither did Teferi, Koth, or Karn, for that matter. But when I listen, really listen, I think I can still hear Zendikar out there, strange and distorted, but possibly still out there. I could just be imagining it completely, but I think I would risk that unknown to see home again."
Chandra nods firmly. "And I'll be walking right alongside you."
Every Planeswalker can go anywhere they want, but Nissa recognizes Chandra's need to roam runs deeper than that. It's part of who she is, and part of what Nissa loves. So Nissa offers, "Maybe, after that, I wouldn't mind seeing more. As long as it's with you."
Chandra breaks into a wide smile. "Let me be your torch, then. First stop: find your way home! Hey, we can even check in on that little forest you started a while ago."
They move toward the portal and each place one foot on the threshold. Nissa wavers and turns to Chandra. Just in case, she asks, "Are you sure you want to commit to a leap of faith?"
"Together? You bet."
Hand in hand, Chandra and Nissa step through the portal into just one of infinite possibilities.
#figure(image("001_She Who Breaks the World/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
|
|
https://github.com/Bi0T1N/typst-iconic-salmon-svg | https://raw.githubusercontent.com/Bi0T1N/typst-iconic-salmon-svg/main/iconic-salmon-svg.typ | typst | MIT License | /// A function that creates a clickable link with the passed name as text.
/// In addition to this, the associated icon of the web page is inserted
///
/// - name (str): The visible name of the clickable link
/// - url (str): The URL to the website (it is assumed to start with the http(s) scheme)
/// - filename (str): The filename of the associated icon
/// - icon_height (float): The height of the icon
/// -> content
#let icon-link-generator(
name,
url,
filename,
icon_height: 0.9em,
..args
) = {
if name.len() == 0 {
panic("The name must contain at least one character")
}
if url.len() == 0 {
panic("The url must contain at least one character")
}
let styled_text = text(
name,
..args
)
let clickable_link
if url.ends-with(regex("\.(com|org|net)/@?$")) {
// links where the name is only appended, i.e. https://github.com/Bi0T1N
clickable_link = url + name
} else {
// links where the profile link is more complicated, i.e. https://stackoverflow.com/users/20742512/bi0t1n
clickable_link = url
}
// unify all links
if not clickable_link.ends-with("/") {
clickable_link = clickable_link + "/"
}
// content
box(image(
"svg/" + filename,
height: icon_height,
))
" "
link(clickable_link)[#styled_text]
}
#let facebook-info(
name,
url: "https://www.facebook.com/",
filename: "Facebook_Logo_Primary.svg",
..args
) = {
// icon-link-generator(name, url, filename, ..args)
icon-link-generator(name, url, filename, icon_height: 1.1em, ..args)
}
#let instagram-info(
name,
url: "https://www.instagram.com/",
filename: "Instagram_logo_2022.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let tiktok-info(
name,
url: "https://www.tiktok.com/@",
filename: "TikTok_Icon_Black.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let youtube-info(
name,
url: "https://www.youtube.com/@",
filename: "YouTube_full-color_icon_(2017).svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let vimeo-info(
name,
url: "https://vimeo.com/",
filename: "vimeo-tile.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let linkedin-info(
name,
url: "https://www.linkedin.com/",
filename: "LinkedIn_icon.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let xing-info(
name,
url: "https://www.xing.com/",
filename: "xing-icon.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let github-info(
name,
url: "https://github.com/",
filename: "github-mark.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let gitlab-info(
name,
url: "https://gitlab.com/",
filename: "GitLab_icon.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let bitbucket-info(
name,
url: "https://bitbucket.org/",
filename: "mark-gradient-blue-bitbucket.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let codeberg-info(
name,
url: "https://codeberg.org/",
filename: "codeberg-logo_icon_blue.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let sourceforge-info(
name,
url: "https://sourceforge.net/",
filename: "sourceforge-seeklogo.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let docker-info(
name,
url: "https://hub.docker.com/",
filename: "docker-mark-blue.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let stackoverflow-info(
name,
url: "https://stackoverflow.com/",
filename: "Stack_Overflow_icon.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let stackexchange-info(
name,
url: "https://stackexchange.com/",
filename: "Stack_Exchange_icon.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let skype-info(
name,
url: "https://www.skype.com/",
filename: "skype-icon.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let discord-info(
name,
url: "https://discord.com/",
filename: "Discord_icon_clyde_blurple_RGB.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let twitter-info(
name,
url: "https://twitter.com/",
filename: "Logo_of_Twitter.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let x-twitter-info(
name,
url: "https://x.com/",
filename: "X_logo_2023.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let orcid-info(
name,
url: "https://orcid.org/",
filename: "ORCID_iD.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
#let tryhackme-info(
name,
url: "https://tryhackme.com/p/",
filename: "tryhackme.com.svg",
..args
) = {
icon-link-generator(name, url, filename, ..args)
}
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Philosophie_Langage.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Philosophie Langage",
authors: (
"<NAME>",
),
date: "14 Juin, 2024",
)
#set heading(numbering: "1.1.")
= Définition
<définition>
- Langage : propriété universelle de l’homme d’utiliser des systèmes de
signes linguistiques afin de transmettre des informations.
- Langue : manifestation particulière de cette propriété de langage.
- Parole : usage singulier d’une langue.
= Problématique
<problématique>
- Problématique 1 : Le langage sert-il à communiquer à autrui des
informations présentes dans le for intérieur de notre conscience sous
forme d’idées ou le langage est-il ce qui permet la pensée et est donc
présent dans notre conscience~?
- Problématique 2 : Si la langue sert à penser, nous permet-elle de
penser le monde de manière objective ou de manière subjective~? La
langue décrit-elle la réalité telle qu’elle est ou ne donne-t-elle
qu’une interprétation de la réalité~?
= On ne peut penser que dans une langue. Le langage permet la pensée
<on-ne-peut-penser-que-dans-une-langue.-le-langage-permet-la-pensée>
== Signe linguistique
<signe-linguistique>
Désigne un concept. (Signifiant : matérielle, Signifié : le concept) Il
ne repose pas sur des images qui sont concrètes et singulières. La
langue nous amène donc à manier en permanence des concepts.
On dira que les animaux communiquent via des signaux, et qu’ils n’ont
pas en général et à proprement parler de langage si l’on réserve ce
terme pour les signes linguistiques. Ils ne font pas usage de concepts.
== On ne peut penser que dans une langue
<on-ne-peut-penser-que-dans-une-langue>
Hegel : En apprenant une langue, on apprend des concepts, qui nous
permettent de comprendre le monde. Seul le langage permet d’avoir des
concepts. C’est pourquoi apprendre une langue, c’est d’abord apprendre à
penser. Alors l’inneffable n’est pas de la pensée.
= Subjectivité
<subjectivité>
== Langues maternelles et étrangères
<langues-maternelles-et-étrangères>
Apprendre une langue signifie apprendre une nouvelle façon de voir le
monde et une partie de la culture.
== H.Bergson
<h.bergson>
Les langues naturelles découle de l’évolution et ont permis la survie
des hommes en leur permettant de communiquer mais elles ne décrivent pas
la réalité de manière objective mais en fonction de nos besoin.
Les langues ne permettent pas de saisir la singularité du réel.
== Le langage ne sert pas qu’à penser
<le-langage-ne-sert-pas-quà-penser>
= Solutions
<solutions>
== Clarifier la langue en créant une langue philosophique / logique
<clarifier-la-langue-en-créant-une-langue-philosophique-logique>
Problèmes : \
\- la langue est aussi expressive, émotive, vise aussi l’action. - faire
reposer la construction de la langue sur une ontologie , c’est la
caractéristique de toutes les langues, mais cette ontologie préconisée
dans cette langue artificielle est une thèse, et peut donc elle-même
être sujet à discussion.
== La philosophie
<la-philosophie>
La philosophie analyse les mots pour en étudier le sens, la pertinence,
la réalité et corriger les erreurs de la langue.
= Textes
<textes>
== Hegel, #emph[Encyclopédie des sciences philosophiques];. Philosophie de l’esprit
<hegel-encyclopédie-des-sciences-philosophiques.-philosophie-de-lesprit>
” C’est dans les mots que nous pensons. Nous n’avons conscience de nos
pensées déterminées et réelles que lorsque nous leur donnons la forme
objective, que nous les différencions de notre intériorité, et, par
suite, nous les marquons d’une forme externe, mais d’une forme qui
contient aussi le caractère de l’activité interne la plus haute. C’est
le son articulé, le mot, qui seul nous offre l’existence où l’externe et
l’interne sont si intimement unis. Par conséquent, vouloir penser sans
les mots, c’est une tentative insensée \[…\] Et il est également absurde
de considérer comme un désavantage et comme un défaut de la pensée cette
nécessité qui lie celle-ci au mot. On croit ordinairement, il est vrai,
que ce qu’il y a de plus haut, c’est l’ineffable. Mais c’est là une
opinion superficielle et sans fondement ; car, en réalité, l’ineffable,
c’est la pensée obscure, la pensée à l’état de fermentation, et qui ne
devient claire que lorsqu’elle trouve le mot. Ainsi le mot donne à la
pensée son existence la plus haute et la plus vraie. ”
== <NAME>, Le rire
<h-bergson-le-rire>
” Nous ne voyons pas les choses mêmes ; nous nous bornons, le plus
souvent, à lire des étiquettes collées sur elles. Cette tendance, issue
du besoin, s’est encore accentuée sous l’influence du langage. Car les
mots (à l’exception des noms propres) désignent des genres. Le mot, qui
ne note de la chose que sa fonction la plus commune et son aspect banal,
s’insinue entre elle et nous, et en masquerait la forme à nos yeux si
cette forme ne se dissimulait déjà derrière les besoins qui ont créé le
mot lui-même. Et ce ne sont pas seulement les objets extérieurs, ce sont
aussi nos propres états d’âme qui se dérobent à nous dans ce qu’ils ont
d’intime, de personnel, d’originalement vécu. Quand nous éprouvons de
l’amour ou de la haine, quand nous nous sentons joyeux ou tristes,
est-ce bien notre sentiment lui-même qui arrive à notre conscience avec
les mille nuances fugitives et les mille résonances profondes qui en
font quelque chose d’absolument nôtre~? Nous serions alors tous
romanciers, tous poètes, tous musiciens. Mais, le plus souvent, nous
n’apercevons de notre état d’âme que son déploiement extérieur. Nous ne
saisissons de nos sentiments que leur aspect impersonnel, celui que le
langage a pu noter une fois pour toutes parce qu’il est à peu près le
même dans les mêmes conditions, pour tous les hommes. Ainsi, jusque dans
notre propre individu, l’individualité nous échappe. Nous nous mouvons
parmi des généralités et des symboles, comme en un champ clos où notre
force se mesure utilement avec d’autres forces ; et, fascinés par
l’action, attirés par elle, pour notre plus grand bien, sur le terrain
qu’elle s’est choisi, nous vivons dans une zone mitoyenne entre les
choses et nous, extérieurement aux choses, extérieurement aussi à
nous-mêmes. ”
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-13.typ | typst | Other | // Test `in` operator.
#test("hi" in "worship", true)
#test("hi" in ("we", "hi", "bye"), true)
#test("Hey" in "abHeyCd", true)
#test("Hey" in "abheyCd", false)
#test(5 in range(10), true)
#test(12 in range(10), false)
#test("" in (), false)
#test("key" in (key: "value"), true)
#test("value" in (key: "value"), false)
#test("Hey" not in "abheyCd", true)
#test("a" not
/* fun comment? */ in "abc", false)
|
https://github.com/AugustinWinther/codedis | https://raw.githubusercontent.com/AugustinWinther/codedis/main/README.md | markdown | MIT License | # CODEDIS - Simple CODE DISplay for Typst
Used to display code files in Typst. Main feature is that it displays code blocks over multiple pages in a way that implies the code block continues onto the next page. Also a simple and intuitive syntax for displaying code blocks.
Usage:
```typ
// IMPORT PACKAGE
#import "@preview/codedis:0.1.0": code
// READ IN CODE
#let codeblock-1 = read("some_code.py")
#let codeblock-2 = read("some_code.cpp")
#set page(numbering: "1")
#v(80%)
// DEFAULT LANGUAGE IS Python ("py")
#code(codeblock-1)
#code(codeblock-2, lang: "cpp")
```
Renders to:

It is very basic and limited, but it does what I need it too, and hope that it may be of help to others. I'm most likely not going to develop it further than this.
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Modules/NetworkedCommunications.typ | typst | #import "../../../template.typ": *
= Networked Communications
== Spam
The rise of spam corresponded with the transformation of the Internet from a noncommercial academic and research enterprise into a commercial global network.
The volume of spam grew because spam is effective. The principal advantage of spam is its low cost compared to other forms of advertising.
#definition[
*Botnets:* huge networks of compromised computers controlled by "bot herders". Bot herders create botnets by launching programs that search the internet for computer w/bad security and install software bots that send emails.
]
== Political Impact of Social Media and Online Advertising
|
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/4-concept/requirement.typ | typst | Um die Anforderungen an die Anwendung zu definieren, wurden zunächst die zuvor definierten Ziele der Arbeit analysiert. Anschließend wurde auf Grundlage der Zielgruppenanalyse weitere Anforderungen abgeleitet.
=== Funktionale Anforderungen
Die funktionalen Anforderungen beschreiben die grundlegenden Funktionen und Interaktionsmöglichkeiten, die die Anwendung bereitstellen soll.
==== Importieren von 3D-Modellen und Daten
Die Anwendung soll die Fähigkeit besitzen, 3D-Modelle und die dazugehörigen Metadaten zu importieren. Der Importprozess soll robust gestaltet sein, um eine einfache Integration neuer Modelle zu ermöglichen.
==== Anzeigen von 3D-Modellen
Die Anwendung soll eine präzise und realitätsgetreue Darstellung von 3D-Modellen in einer virtuellen Szene ermöglichen. Die Darstellung soll sowohl die geometrischen Eigenschaften als auch die Texturen und Materialien der Modelle korrekt wiedergeben.
==== Hinzufügen von 3D-Modellen in der Szene
Die Anwendung soll es ermöglichen, importierte 3D-Modelle in einer bestehenden virtuellen Szene zu integrieren. Dies beinhaltet das Positionieren der Modelle an spezifischen Koordinaten innerhalb der Szene.
==== Anordnen von 3D-Modellen in der Szene
Die Anwendung soll Funktionen bereitstellen, die es ermöglichen, 3D-Modelle innerhalb der Szene zu arrangieren und in Beziehung zueinander zu setzen.
==== Selektion in der Szene
Die Anwendung soll eine Selektion von 3D-Modellen innerhalb der Szene ermöglichen. Dies beinhaltet die Fähigkeit, einzelne Modelle auszuwählen, um darauf basierende Aktionen durchzuführen.
==== Löschen aus der Szene
Die Anwendung soll eine Funktion bereitstellen, die es ermöglicht, 3D-Modelle aus der Szene zu entfernen. Der Löschvorgang soll irreversibel sein und sicherstellen, dass die Modelle vollständig aus der Szene entfernt werden.
==== Exportieren von Daten
Die Anwendung soll in der Lage sein, die Metadaten der hinzugefügten 3D-Modelle zu exportieren. Dies umfasst Informationen wie Modellname, Position, Orientierung, Skalierung und spezifische benutzerdefinierte Metadaten. Der Export soll in verschiedenen Formaten erfolgen können, um eine Weiterverarbeitung der Daten in anderen Anwendungen zu ermöglichen.
=== Nicht-funktionale Anforderungen
Die nachfolgende Aufzählung beschreibt die nicht-funktionalen Anforderungen, die die Anwendung erfüllen soll.
==== Integrierbarkeit
Die Anwendung soll sich in bestehende Systeme und Prozesse integrieren lassen. Dies beinhaltet die Unterstützung von Schnittstellen zu anderen Anwendungen und Datenquellen sowie die Möglichkeit, die Anwendung in vorhandene Workflows und Abläufe zu integrieren.
==== Performance
Die Anwendung soll eine hohe Performanz aufweisen, um eine flüssige und reaktionsschnelle Benutzererfahrung zu gewährleisten. Dies umfasst kurze Ladezeiten, schnelle Import- und Exportprozesse sowie eine effiziente Verarbeitung von Benutzerinteraktionen innerhalb der Szene. Die Anwendung soll auch bei einer großen Anzahl von 3D-Modellen und komplexen Szenen performant bleiben.
==== Benutzererfahrung
Die Anwendung soll eine intuitive und benutzerfreundliche Oberfläche bieten, die es sowohl Anfängern als auch erfahrenen Benutzern ermöglicht, effektiv mit der Anwendung zu interagieren. Dies beinhaltet eine klare und konsistente Navigation, verständliche Benutzeranweisungen und eine ergonomische Anordnung der Bedienelemente.
==== Skalierbarkeit
Die Anwendung soll skalierbar sein, um den Anforderungen unterschiedlicher Benutzergruppen und Anwendungsszenarien gerecht zu werden. Dies umfasst die Unterstützung von Projekten unterschiedlicher Größe und Komplexität sowie die Fähigkeit, bei Bedarf zusätzliche Funktionen und Erweiterungen zu integrieren.
==== Zuverlässigkeit
Die Anwendung soll eine hohe Zuverlässigkeit aufweisen, um einen stabilen und unterbrechungsfreien Betrieb zu gewährleisten. Dies beinhaltet robuste Fehlerhandhabung und Wiederherstellungsmechanismen, um Datenverlust und Ausfälle zu vermeiden. Die Anwendung soll regelmäßig getestet und aktualisiert werden, um Sicherheitslücken und Fehler zu beheben. |
|
https://github.com/piepert/typst-custombib | https://raw.githubusercontent.com/piepert/typst-custombib/main/example1/main.typ | typst | #import "../typst-custombib.typ": tcb-bibliography, tcb-cite, tcb-cites, tcb-style, tcb-show-bibliography, ifnotnone, ifhaskey
#tcb-bibliography("example1/bibliography.yaml")
#tcb-style((
options: (
is-numerical: false,
show-sections: true,
show-bibliography: true,
title: "Bibliography",
separator: ", "
),
// how each field is formatted (from entry (source-string) to citation (content))
fields: (
// performed on each author name
author: (entry, author) =>
smallcaps[#author.last, #author.first#ifhaskey(author, "middle", e => [ #e.middle])],
// performed on the list of authors
authors: (entry, authors) =>
(if authors.len() > 3 {
(authors.slice(0, 2), [et al]).flatten().join(", ", last: " ")
} else {
authors.join(", ", last: " und ")
}),
// performed on each prefix and postfix
postfix: (entry, postfix) => [#ifnotnone(postfix, e => [, #postfix])],
prefix: (entry, prefix) => [#ifnotnone(prefix, e => [#e ])],
// fallback
fallback: (entry, field) => field
),
// for entry-type "custom"
custom: (
sort-by: "marker",
inline: (entry) => [#ifhaskey(entry, "prefix", e => (e.prefix+" "))#eval("["+entry.show-inline+"]")#ifhaskey(entry, "postfix", e => (" "+e.postfix))],
bibliography: (entry) => [#eval("["+entry.show-bibliography+"]").]
),
inline: (
fields: (
// performed on each author name
author: (entry, author) =>
smallcaps[#author.first.at(0). #ifhaskey(author, "middle", e => [ #e.middle ]) #author.last]
),
// added after citation
citation-begin: (entry, citation) => citation,
// added before citation
citation-end: (entry, citation) => citation,
// format single citation inside
format: (entry, citation) => [#citation],
// on multiple citations, wrap all of them into this
wrap-multi: (citations) => [#citations],
// on all citations cited together tcb-cites / tcb-cite, wrap all of them into this
wrap-any: (citations) => [#citations],
types: (
fallback: (entry, citation) => [#citation.prefix#citation.authors (#citation.year)#citation.postfix]
)
),
bibliography: (
format: (entry, citation) => citation,
types: (
book: (entry, element) => [#element.authors:
#emph["#element.title"].
#ifhaskey(element,
"volume",
e => [vol. #e.volume.])
#element.location #element.year.
#ifhaskey(element,
"pages",
e => [ S. #if e.pages.ends-with(".") { e.pages } else { e.pages+"." }])],
fallback: (entry, element) => [#element.authors: #emph["#element.title"].]
)
),
sections: (
primary: "Primary Literature",
secondary: "Secondary Literature"
)
))
#let ncite(e, postfix: none, prefix: none) = footnote(tcb-cite(e, postfix: postfix, prefix: prefix))
= Title
#lorem(20)
#tcb-cites("Putnam1975", "Hanson2010")
#tcb-cite("Putnam1975", prefix: "vgl.", postfix: "S. 175")
#tcb-cite("Regier2017")
#tcb-cite("KrV", postfix: "A1 / B2")
#tcb-cite("Politeia", postfix: "418e")
#tcb-show-bibliography() |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/047.%20inequality.html.typ | typst | inequality.html
Inequality and Risk
August 2005(This essay is derived from a talk at Defcon 2005.)Suppose you wanted to get rid of economic inequality. There are
two ways to do it: give money to the poor, or take it away from the
rich. But they amount to the same thing, because if you want to
give money to the poor, you have to get it from somewhere. You
can't get it from the poor, or they just end up where they started.
You have to get it from the rich.There is of course a way to make the poor richer without simply
shifting money from the rich. You could help the poor become more
productive — for example, by improving access to education. Instead
of taking money from engineers and giving it to checkout clerks,
you could enable people who would have become checkout clerks to
become engineers.This is an excellent strategy for making the poor richer. But the
evidence of the last 200 years shows that it doesn't reduce economic
inequality, because it makes the rich richer too. If there
are more engineers, then there are more opportunities to hire them
and to sell them things. <NAME> couldn't have made a fortune
building cars in a society in which most people were still subsistence
farmers; he would have had neither workers nor customers.If you want to reduce economic inequality instead of just improving
the overall standard of living, it's not enough just to raise up
the poor. What if one of your newly minted engineers gets ambitious
and goes on to become another Bill Gates? Economic inequality will
be as bad as ever. If you actually want to compress the gap between
rich and poor, you have to push down on the top as well as pushing
up on the bottom.How do you push down on the top? You could try to decrease the
productivity of the people who make the most money: make the best
surgeons operate with their left hands, force popular actors to
overeat, and so on. But this approach is hard to implement. The
only practical solution is to let people do the best work they can,
and then (either by taxation or by limiting what they can charge)
to confiscate whatever you deem to be surplus.So let's be clear what reducing economic inequality means. It is
identical with taking money from the rich.When you transform a mathematical expression into another form, you
often notice new things. So it is in this case. Taking money from
the rich turns out to have consequences one might not foresee when
one phrases the same idea in terms of "reducing inequality."The problem is, risk and reward have to be proportionate. A bet
with only a 10% chance of winning has to pay more than one with a
50% chance of winning, or no one will take it. So if you lop off
the top of the possible rewards, you thereby decrease people's
willingness to take risks.Transposing into our original expression, we get: decreasing economic
inequality means decreasing the risk people are willing to take.There are whole classes of risks that are no longer worth taking
if the maximum return is decreased. One reason high tax rates are
disastrous is that this class of risks includes starting new
companies.InvestorsStartups are intrinsically risky. A startup
is like a small boat
in the open sea. One big wave and you're sunk. A competing product,
a downturn in the economy, a delay in getting funding or regulatory
approval, a patent suit, changing technical standards, the departure
of a key employee, the loss of a big account — any one of these can
destroy you overnight. It seems only about 1 in 10 startups succeeds.
[1]Our startup paid its first round of outside investors 36x. Which
meant, with current US tax rates, that it made sense to invest in
us if we had better than a 1 in 24 chance of succeeding. That
sounds about right. That's probably roughly how we looked when we
were a couple of nerds with no business experience operating out
of an apartment.If that kind of risk doesn't pay, venture investing, as we know it,
doesn't happen.That might be ok if there were other sources of capital for new
companies. Why not just have the government, or some large
almost-government organization like <NAME>, do the venture
investing instead of private funds?I'll tell you why that wouldn't work. Because then you're asking
government or almost-government employees to do the one thing they
are least able to do: take risks.As anyone who has worked for the government knows, the important
thing is not to make the right choices, but to make choices that
can be justified later if they fail. If there is a safe option,
that's the one a bureaucrat will choose. But that is exactly the
wrong way to do venture investing. The nature of the business means
that you want to make terribly risky choices, if the upside looks
good enough.VCs are currently
paid in a way that makes them
focus on the upside:
they get a percentage of the fund's gains. And that helps overcome
their understandable fear of investing in a company run by nerds
who look like (and perhaps are) college students.If VCs weren't allowed to get rich, they'd behave like bureaucrats.
Without hope of gain, they'd have only fear of loss. And so they'd
make the wrong choices. They'd turn down the nerds in favor of the
smooth-talking MBA in a suit, because that investment would be
easier to justify later if it failed.FoundersBut even if you could somehow redesign venture funding to work
without allowing VCs to become rich, there's another kind of investor
you simply cannot replace: the startups' founders and early employees.What they invest is their time and ideas. But these are equivalent
to money; the proof is that investors are willing (if forced) to
treat them as interchangeable, granting the same status to "sweat
equity" and the equity they've purchased with cash.The fact that you're investing time doesn't change the relationship
between risk and reward. If you're going to invest your time in
something with a small chance of succeeding, you'll only do it if
there is a proportionately large payoff.
[2]
If large payoffs aren't allowed, you may as well play it safe.Like many startup founders, I did it to get rich. But not because
I wanted to buy expensive things. What I wanted was security. I
wanted to make enough money that I didn't have to worry about money.
If I'd been forbidden to make enough from a startup to do this, I
would have sought security by some other means: for example, by
going to work for a big, stable organization from which it would
be hard to get fired. Instead of busting my ass in a startup, I
would have tried to get a nice, low-stress job at a big research
lab, or tenure at a university.That's what everyone does in societies where risk isn't rewarded.
If you can't ensure your own security, the next best thing is to
make a nest for yourself in some large organization where your
status depends mostly on seniority.
[3]Even if we could somehow replace investors, I don't see how we could
replace founders. Investors mainly contribute money, which in
principle is the same no matter what the source. But the founders
contribute ideas. You can't replace those.Let's rehearse the chain of argument so far. I'm heading for a
conclusion to which many readers will have to be dragged kicking
and screaming, so I've tried to make each link unbreakable. Decreasing
economic inequality means taking money from the rich. Since risk
and reward are equivalent, decreasing potential rewards automatically
decreases people's appetite for risk. Startups are intrinsically
risky. Without the prospect of rewards proportionate to the risk,
founders will not invest their time in a startup. Founders are
irreplaceable. So eliminating economic inequality means eliminating
startups.Economic inequality is not just a consequence of startups.
It's the engine that drives them, in the same way a fall of water
drives a water mill. People start startups in the hope of becoming
much richer than they were before. And if your society tries to
prevent anyone from being much richer than anyone else, it will
also prevent one person from being much richer at t2 than t1.GrowthThis argument applies proportionately. It's not just that if you
eliminate economic inequality, you get no startups. To the extent
you reduce economic inequality, you decrease the number of startups.
[4]
Increase taxes, and willingness to take risks decreases in
proportion.And that seems bad for everyone. New technology and new jobs both
come disproportionately from new companies. Indeed, if you don't
have startups, pretty soon you won't have established companies
either, just as, if you stop having kids, pretty soon you won't
have any adults.It sounds benevolent to say we ought to reduce economic inequality.
When you phrase it that way, who can argue with you? Inequality
has to be bad, right? It sounds a good deal less benevolent to say
we ought to reduce the rate at which new companies are founded.
And yet the one implies the other.Indeed, it may be that reducing investors' appetite for risk doesn't
merely kill off larval startups, but kills off the most promising
ones especially. Startups yield faster growth at greater risk than
established companies. Does this trend also hold among startups?
That is, are the riskiest startups the ones that generate most
growth if they succeed? I suspect the answer is yes. And that's
a chilling thought, because it means that if you cut investors'
appetite for risk, the most beneficial startups are the first to
go.Not all rich people got that way from startups, of course. What
if we let people get rich by starting startups, but taxed away all
other surplus wealth? Wouldn't that at least decrease inequality?Less than you might think. If you made it so that people could
only get rich by starting startups, people who wanted to get rich
would all start startups. And that might be a great thing. But I
don't think it would have much effect on the distribution of wealth.
People who want to get rich will do whatever they have to. If
startups are the only way to do it, you'll just get far more people
starting startups. (If you write the laws very carefully, that is.
More likely, you'll just get a lot of people doing things that can
be made to look on paper like startups.)If we're determined to eliminate economic inequality, there is still
one way out: we could say that we're willing to go ahead and do
without startups. What would happen if we did?At a minimum, we'd have to accept lower rates of technological
growth. If you believe that large, established companies could
somehow be made to develop new technology as fast as startups, the
ball is in your court to explain how. (If you can come up with a
remotely plausible story, you can make a fortune writing business
books and consulting for large companies.)
[5]Ok, so we get slower growth. Is that so bad? Well, one reason
it's bad in practice is that other countries might not agree to
slow down with us. If you're content to develop new technologies
at a slower rate than the rest of the world, what happens is that
you don't invent anything at all. Anything you might discover has
already been invented elsewhere. And the only thing you can offer
in return is raw materials and cheap labor. Once you sink that
low, other countries can do whatever they like with you: install
puppet governments, siphon off your best workers, use your women
as prostitutes, dump their toxic waste on your territory — all the
things we do to poor countries now. The only defense is to isolate
yourself, as communist countries did in the twentieth century. But
the problem then is, you have to become a police state to enforce
it.
Wealth and PowerI realize startups are not the main target of those who want to
eliminate economic inequality. What they really dislike is the
sort of wealth that becomes self-perpetuating through an alliance
with power. For example, construction firms that fund politicians'
campaigns in return for government contracts, or rich parents who
get their children into good colleges by sending them to expensive
schools designed for that purpose. But if you try to attack this type of wealth
through economic policy, it's hard to hit without destroying
startups as collateral damage.The problem here is not wealth, but corruption. So why not go after
corruption?We don't need to prevent people from being rich if we can prevent
wealth from translating into power. And there has been progress
on that front. Before he died of drink in 1925, Commodore Vanderbilt's
wastrel grandson Reggie ran down pedestrians on five separate
occasions, killing two of them. By 1969, when <NAME> drove
off the bridge at Chappaquiddick, the limit seemed to be down to
one. Today it may well be zero. But what's changed is not variation
in wealth. What's changed is the ability to translate wealth into
power.How do you break the connection between wealth and power? Demand
transparency. Watch closely how power is exercised, and demand an
account of how decisions are made. Why aren't all police interrogations
videotaped? Why did 36% of Princeton's class of 2007 come from
prep schools, when only 1.7% of American kids attend them? Why did
the US really invade Iraq? Why don't government officials disclose
more about their finances, and why only during their term of office?A friend of mine who knows a lot about computer security says the
single most important step is to log everything. Back when he was
a kid trying to break into computers, what worried him most was the
idea of leaving a trail. He was more inconvenienced by the need
to avoid that than by any obstacle deliberately put in his path.Like all illicit connections, the connection between wealth and
power flourishes in secret. Expose all transactions, and you will
greatly reduce it. Log everything. That's a strategy that already
seems to be working, and it doesn't have the side effect of making
your whole country poor.I don't think many people realize there is a connection between
economic inequality and risk. I didn't fully grasp it till recently.
I'd known for years of course that if one didn't score in a startup,
the other alternative was to get a cozy, tenured research job. But
I didn't understand the equation governing my behavior. Likewise,
it's obvious empirically that a country that doesn't let people get
rich is headed for disaster, whether it's Diocletian's Rome or
Harold Wilson's Britain. But I did not till recently understand
the role risk played.If you try to attack wealth, you end up nailing risk as well, and
with it growth. If we want a fairer world, I think we're better
off attacking one step downstream, where wealth turns into power.Notes
[1]
Success here is defined from the initial investors' point of
view: either an IPO, or an acquisition for more than the valuation
at the last round of funding. The conventional 1 in 10 success rate
is suspiciously neat, but conversations with VCs suggest it's roughly
correct for startups overall. Top VC firms expect to do better.[2]
I'm not claiming founders sit down and calculate the expected
after-tax return from a startup. They're motivated by examples of
other people who did it. And those examples do reflect after-tax returns.[3]
Conjecture: The variation in wealth in a (non-corrupt)
country or organization
will be inversely proportional to the prevalence of systems of
seniority. So if you suppress variation in wealth, seniority will
become correspondingly more important. So far, I know of no
counterexamples, though in very corrupt countries you may get
both simultaneously. (Thanks to <NAME> for pointing
this out.)[4]
In a country with a truly feudal economy, you might be able to
redistribute wealth successfully, because there are no startups to
kill.[5]
The speed at which startups develop new techology is the other
reason they pay so well. As I explained in "How to Make Wealth", what you do in a startup is compress a
lifetime's worth of work into a few years. It seems as
dumb to discourage that as to discourage risk-taking.
Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, and <NAME> for reading drafts of this
essay, and to <NAME>, <NAME>, and <NAME> for
information about venture investing.Romanian TranslationDutch TranslationTraditional Chinese TranslationJapanese TranslationHebrew Translation
If you liked this, you may also like
Hackers & Painters.
|
|
https://github.com/cu1ch3n/typst-lib | https://raw.githubusercontent.com/cu1ch3n/typst-lib/main/lib.typ | typst | #let rule_base(counter, lbl) = {
counter.step()
let num = box(align(left, counter.display()), width: 1em)
[ #figure(
math.attach(math.arrow.long, br: num),
kind: "rule",
supplement: [Rule])
#if lbl != none { label(lbl) } ]
}
// Custom Symbols
#let ex = math.hat
#let ph = "__"
#let mono = math.attach(math.forces, br: "m")
#let nonmono = math.attach(math.tack.r.not, br: "m")
#let monoa = math.attach(math.forces, br: "m")
#let nonmonoa = math.attach(math.forces.not, br: "m")
#let tto = math.class("relation", stack(
dir: ltr,
spacing: -0.5em,
math.arrow.double.r,
math.arrow.double.r
))
#let tweaks(body) = {
// Typst Quirks
show math.bot: math.class("normal", math.bot)
// Add space after .
show math.dot.basic: {math.dot.basic; math.space}
body
}
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/机器学习数学导引/作业/hw1.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../../template.typ": *
#show: note.with(
title: "作业1",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withOutlined : false,
withTitle : false,
)
#let ltC = math.lt.tilde
=
==
#let vsc = $V_S^c$
#let xvsc = $x in V_S^c$
$
E(P(xvsc | S)) &= E (sum_(j=1)^m P(xvsc | x in Q_j) P(x in Q_j)) \
&= 1/m E( sum_(j=1)^m P(xvsc | x in Q_j))\
&= 1/m sum_(j=1)^m E(P(xvsc | x in Q_j))\
&= 1/m sum_(j=1)^m E(P(xvsc | x in Q_j) | product_(i) x_i in.not Q_j) P(product_(i) x_i in.not Q_j) \
&+ E(P(xvsc | x in Q_j) | (product_(i) x_i in.not Q_j)^c) (1 - P(product_(i) x_i in.not Q_j))\
&= 1/m sum_(j=1)^m 1 dot P(product_(i) x_i in.not Q_j) + 0 dot (1 - P(product_(i) x_i in.not Q_j))\
&= 1/m sum_(j=1)^m product_(i) P(x_i in.not Q_j)\
&= (1 - h^d)^n \
$
本题中 $E_(S, x) P(xvsc)$ 的写法似乎有些奇怪,$P(xvsc)$ 从字面上来说是一定值,不需要求期望。如果假设含义是:
$
E_(S) (P(xvsc | S))
$
也就是对于某组取定的 $S$,$P(xvsc | S)$ 是一关于 $S$ 的函数,对其求期望,那么也应该与 $x$ 无关(第一层求概率已经消去了随机变量 $x$),不应该写作 $E_(S, x)$,况且不难验证:
$
E_(S) (P(xvsc | S)) = P(xvsc)
$
似乎并不需要表述地这么复杂。
==
令:
$
f(t) = n t (1 - t)^n, t in (0, 1)\
f'(t) = n (1 - t)^n - n^2 t (1 - t)^(n-1) = n (1-t)^(n-1) (1 - (n + 1) t)\
$
因此函数在 $t = 1/(n + 1)$ 处取最大值,因此有:
$
n t (1 - t)^n <= n / (n + 1) (1 - 1/(n + 1))^n = n / (n + 1) (n / (n + 1))^n = (n / (n + 1))^(n + 1) <= 1
$
因此:
$
h + (1 - h^d)^n <= h + 1/(n h^d)
$
另一方面,注意到:
$
h + 1/(n h^d) = sum_(i = 1)^d 1/d h + 1/(n h^d) >= root(d+1, (h/d)^d dot 1/(n h^d)) = 1/(root(d+1, d) root(d+1, n))
$
且在 $1/d h = 1/(n h^d)$ 处取得,因此:
$
min h + 1/(n h^d) = 1/(root(d+1, d) root(d+1, n))\
min h + (1 - h^d)^n <= 1/(root(d+1, d) root(d+1, n)) ltC 1/(root(d+1, n))
$
==
#let xv = $bold(x)$
#let yv = $bold(y)$
#let xs = $x_"sample"$
$
E norm(x - T(x))
&= E (norm(x - T(x))| xvsc) P(xvsc) \ &+ E (norm(x - T(x)) | x in V_S) P(x in V_S)\
&<= E (sqrt(d)| xvsc) P(xvsc) + E (h sqrt(d) | x in V_S) P(x in V_S)\
&= sqrt(d) P(xvsc) + h sqrt(d) P(x in V_S)\
&<= sqrt(d) P(xvsc) + h sqrt(d)\
&<= sqrt(d) integral_(xs in [0, 1]^d) P(xvsc | (x_1, ..., x_n) = xs) rho(xs) dif xs + h sqrt(d)\
&= sqrt(d) E_S (xvsc | S) (P(xvsc)) + h sqrt(d)\
&= sqrt(d) (1 - h^d)^n + h sqrt(d)\
&= sqrt(d) ((1 - h^d)^n + h)\
<C sqrt(d) (1/(n^(1/(d+1))))\
<C sqrt(d)/(n^(1\/(d+1)))\
$
==
#let f1 = $hat(f_S)$
#let fo = $f^*$
$
E norm(f1 - fo) &= E (integral_(x in [0, 1]^d) (f1(x) - fo(x))^2 dif x)\
&= E (integral_(x in [0, 1]^d) (fo(T(x)) - fo(x))^2 dif x)\
&<= E (integral_(x in [0, 1]^d) L norm(x - T(x)) dif x)\
&<= L integral_(x in [0, 1]^d) E (norm(x - T(x)) dif x)\
&<= L sqrt(d)/(n^(1\/(d+1)))\
$
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2300.typ | typst | Apache License 2.0 | #let data = (
("DIAMETER SIGN", "So", 0),
("ELECTRIC ARROW", "So", 0),
("HOUSE", "So", 0),
("UP ARROWHEAD", "So", 0),
("DOWN ARROWHEAD", "So", 0),
("PROJECTIVE", "So", 0),
("PERSPECTIVE", "So", 0),
("WAVY LINE", "So", 0),
("LEFT CEILING", "Ps", 0),
("RIGHT CEILING", "Pe", 0),
("LEFT FLOOR", "Ps", 0),
("RIGHT FLOOR", "Pe", 0),
("BOTTOM RIGHT CROP", "So", 0),
("BOTTOM LEFT CROP", "So", 0),
("TOP RIGHT CROP", "So", 0),
("TOP LEFT CROP", "So", 0),
("REVERSED NOT SIGN", "So", 0),
("SQUARE LOZENGE", "So", 0),
("ARC", "So", 0),
("SEGMENT", "So", 0),
("SECTOR", "So", 0),
("TELEPHONE RECORDER", "So", 0),
("POSITION INDICATOR", "So", 0),
("VIEWDATA SQUARE", "So", 0),
("PLACE OF INTEREST SIGN", "So", 0),
("TURNED NOT SIGN", "So", 0),
("WATCH", "So", 0),
("HOURGLASS", "So", 0),
("TOP LEFT CORNER", "So", 0),
("TOP RIGHT CORNER", "So", 0),
("BOTTOM LEFT CORNER", "So", 0),
("BOTTOM RIGHT CORNER", "So", 0),
("TOP HALF INTEGRAL", "Sm", 0),
("BOTTOM HALF INTEGRAL", "Sm", 0),
("FROWN", "So", 0),
("SMILE", "So", 0),
("UP ARROWHEAD BETWEEN TWO HORIZONTAL BARS", "So", 0),
("OPTION KEY", "So", 0),
("ERASE TO THE RIGHT", "So", 0),
("X IN A RECTANGLE BOX", "So", 0),
("KEYBOARD", "So", 0),
("LEFT-POINTING ANGLE BRACKET", "Ps", 0),
("RIGHT-POINTING ANGLE BRACKET", "Pe", 0),
("ERASE TO THE LEFT", "So", 0),
("<NAME>", "So", 0),
("CYLINDRICITY", "So", 0),
("ALL AROUND-PROFILE", "So", 0),
("SYMMETRY", "So", 0),
("TOTAL RUNOUT", "So", 0),
("DIMENSION ORIGIN", "So", 0),
("CONICAL TAPER", "So", 0),
("SLOPE", "So", 0),
("COUNTERBORE", "So", 0),
("COUNTERSINK", "So", 0),
("APL FUNCTIONAL SYMBOL I-BEAM", "So", 0),
("APL FUNCTIONAL SYMBOL SQUISH QUAD", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD EQUAL", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD DIVIDE", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD DIAMOND", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD JOT", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD CIRCLE", "So", 0),
("APL FUNCTIONAL SYMBOL CIRCLE STILE", "So", 0),
("APL FUNCTIONAL SYMBOL CIRCLE JOT", "So", 0),
("APL FUNCTIONAL SYMBOL SLASH BAR", "So", 0),
("APL FUNCTIONAL SYMBOL BACKSLASH BAR", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD SLASH", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD BACKSLASH", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD LESS-THAN", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD GREATER-THAN", "So", 0),
("APL FUNCTIONAL SYMBOL LEFTWARDS VANE", "So", 0),
("APL FUNCTIONAL SYMBOL RIGHTWARDS VANE", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD LEFTWARDS ARROW", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD RIGHTWARDS ARROW", "So", 0),
("APL FUNCTIONAL SYMBOL CIRCLE BACKSLASH", "So", 0),
("APL FUNCTIONAL SYMBOL DOWN TACK UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL DELTA STILE", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD DOWN CARET", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD DELTA", "So", 0),
("APL FUNCTIONAL SYMBOL DOWN TACK JOT", "So", 0),
("APL FUNCTIONAL SYMBOL UPWARDS VANE", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD UPWARDS ARROW", "So", 0),
("APL FUNCTIONAL SYMBOL UP TACK OVERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL DEL STILE", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD UP CARET", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD DEL", "So", 0),
("APL FUNCTIONAL SYMBOL UP TACK JOT", "So", 0),
("APL FUNCTIONAL SYMBOL DOWNWARDS VANE", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD DOWNWARDS ARROW", "So", 0),
("APL FUNCTIONAL SYMBOL QUOTE UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL DELTA UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL DIAMOND UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL JOT UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL CIRCLE UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL UP SHOE JOT", "So", 0),
("APL FUNCTIONAL SYMBOL QUOTE QUAD", "So", 0),
("APL FUNCTIONAL SYMBOL CIRCLE STAR", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD COLON", "So", 0),
("APL FUNCTIONAL SYMBOL UP TACK DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL DEL DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL STAR DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL JOT DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL CIRCLE DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL DOWN SHOE STILE", "So", 0),
("APL FUNCTIONAL SYMBOL LEFT SHOE STILE", "So", 0),
("APL FUNCTIONAL SYMBOL TILDE DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL GREATER-THAN DIAERESIS", "So", 0),
("APL FUNCTIONAL SYMBOL COMMA BAR", "So", 0),
("APL FUNCTIONAL SYMBOL DEL TILDE", "So", 0),
("APL FUNCTIONAL SYMBOL ZILDE", "So", 0),
("APL FUNCTIONAL SYMBOL STILE TILDE", "So", 0),
("APL FUNCTIONAL SYMBOL SEMICOLON UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD NOT EQUAL", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD QUESTION", "So", 0),
("APL FUNCTIONAL SYMBOL DOWN CARET TILDE", "So", 0),
("APL FUNCTIONAL SYMBOL UP CARET TILDE", "So", 0),
("APL FUNCTIONAL SYMBOL IOTA", "So", 0),
("APL FUNCTIONAL SYMBOL RHO", "So", 0),
("APL FUNCTIONAL SYMBOL OMEGA", "So", 0),
("APL FUNCTIONAL SYMBOL ALPHA UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL EPSILON UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL IOTA UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL OMEGA UNDERBAR", "So", 0),
("APL FUNCTIONAL SYMBOL ALPHA", "So", 0),
("NOT CHECK MARK", "So", 0),
("RIGHT ANGLE WITH DOWNWARDS ZIGZAG ARROW", "Sm", 0),
("SHOULDERED OPEN BOX", "So", 0),
("BELL SYMBOL", "So", 0),
("VERTICAL LINE WITH MIDDLE DOT", "So", 0),
("INSERTION SYMBOL", "So", 0),
("CONTINUOUS UNDERLINE SYMBOL", "So", 0),
("DISCONTINUOUS UNDERLINE SYMBOL", "So", 0),
("EMPHASIS SYMBOL", "So", 0),
("COMPOSITION SYMBOL", "So", 0),
("WHITE SQUARE WITH CENTRE VERTICAL LINE", "So", 0),
("ENTER SYMBOL", "So", 0),
("ALTERNATIVE KEY SYMBOL", "So", 0),
("HELM SYMBOL", "So", 0),
("CIRCLED HORIZONTAL BAR WITH NOTCH", "So", 0),
("CIRCLED TRIANGLE DOWN", "So", 0),
("BROKEN CIRCLE WITH NORTHWEST ARROW", "So", 0),
("UNDO SYMBOL", "So", 0),
("MONOSTABLE SYMBOL", "So", 0),
("HYSTERESIS SYMBOL", "So", 0),
("OPEN-CIRCUIT-OUTPUT H-TYPE SYMBOL", "So", 0),
("OPEN-CIRCUIT-OUTPUT L-TYPE SYMBOL", "So", 0),
("PASSIVE-PULL-DOWN-OUTPUT SYMBOL", "So", 0),
("PASSIVE-PULL-UP-OUTPUT SYMBOL", "So", 0),
("DIRECT CURRENT SYMBOL FORM TWO", "So", 0),
("SOFTWARE-FUNCTION SYMBOL", "So", 0),
("APL FUNCTIONAL SYMBOL QUAD", "So", 0),
("DECIMAL SEPARATOR KEY SYMBOL", "So", 0),
("PREVIOUS PAGE", "So", 0),
("NEXT PAGE", "So", 0),
("PRINT SCREEN SYMBOL", "So", 0),
("CLEAR SCREEN SYMBOL", "So", 0),
("LEFT PARENTHESIS UPPER HOOK", "Sm", 0),
("LEFT PARENTHESIS EXTENSION", "Sm", 0),
("LEFT PARENTHESIS LOWER HOOK", "Sm", 0),
("RIGHT PARENTHESIS UPPER HOOK", "Sm", 0),
("RIGHT PARENTHESIS EXTENSION", "Sm", 0),
("RIGHT PARENTHESIS LOWER HOOK", "Sm", 0),
("LEFT SQUARE BRACKET UPPER CORNER", "Sm", 0),
("LEFT SQUARE BRACKET EXTENSION", "Sm", 0),
("LEFT SQUARE BRACKET LOWER CORNER", "Sm", 0),
("RIGHT SQUARE BRACKET UPPER CORNER", "Sm", 0),
("RIGHT SQUARE BRACKET EXTENSION", "Sm", 0),
("RIGHT SQUARE BRACKET LOWER CORNER", "Sm", 0),
("LEFT CURLY BRACKET UPPER HOOK", "Sm", 0),
("LEFT CURLY BRACKET MIDDLE PIECE", "Sm", 0),
("LEFT CURLY BRACKET LOWER HOOK", "Sm", 0),
("CURLY BRACKET EXTENSION", "Sm", 0),
("RIGHT CURLY BRACKET UPPER HOOK", "Sm", 0),
("RIGHT CURLY BRACKET MIDDLE PIECE", "Sm", 0),
("RIGHT CURLY BRACKET LOWER HOOK", "Sm", 0),
("INTEGRAL EXTENSION", "Sm", 0),
("HORIZONTAL LINE EXTENSION", "Sm", 0),
("UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION", "Sm", 0),
("UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION", "Sm", 0),
("SUMMATION TOP", "Sm", 0),
("SUMMATION BOTTOM", "Sm", 0),
("TOP SQUARE BRACKET", "So", 0),
("BOTTOM SQUARE BRACKET", "So", 0),
("BOTTOM SQUARE BRACKET OVER TOP SQUARE BRACKET", "So", 0),
("RADICAL SYMBOL BOTTOM", "So", 0),
("LEFT VERTICAL BOX LINE", "So", 0),
("RIGHT VERTICAL BOX LINE", "So", 0),
("HORIZONTAL SCAN LINE-1", "So", 0),
("HORIZONTAL SCAN LINE-3", "So", 0),
("HORIZONTAL SCAN LINE-7", "So", 0),
("HORIZONTAL SCAN LINE-9", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL AND TOP RIGHT", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL AND BOTTOM RIGHT", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL WITH CIRCLE", "So", 0),
("DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH CIRCLE", "So", 0),
("DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH CIRCLE", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL WITH TRIANGLE", "So", 0),
("DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH TRIANGLE", "So", 0),
("DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH TRIANGLE", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL AND WAVE", "So", 0),
("DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH WAVE", "So", 0),
("DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH WAVE", "So", 0),
("DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL", "So", 0),
("DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL AND TOP LEFT", "So", 0),
("DENTISTRY SYMBOL LIGHT VERTICAL AND BOTTOM LEFT", "So", 0),
("SQUARE FOOT", "So", 0),
("RETURN SYMBOL", "So", 0),
("EJECT SYMBOL", "So", 0),
("VERTICAL LINE EXTENSION", "So", 0),
("METRICAL BREVE", "So", 0),
("METRICAL LONG OVER SHORT", "So", 0),
("METRICAL SHORT OVER LONG", "So", 0),
("METRICAL LONG OVER TWO SHORTS", "So", 0),
("METRICAL TWO SHORTS OVER LONG", "So", 0),
("METRICAL TWO SHORTS JOINED", "So", 0),
("METRICAL TRISEME", "So", 0),
("METRICAL TETRASEME", "So", 0),
("METRICAL PENTASEME", "So", 0),
("EARTH GROUND", "So", 0),
("FUSE", "So", 0),
("TOP PARENTHESIS", "Sm", 0),
("BOTTOM PARENTHESIS", "Sm", 0),
("TOP CURLY BRACKET", "Sm", 0),
("BOTTOM CURLY BRACKET", "Sm", 0),
("TOP TORTOISE SHELL BRACKET", "Sm", 0),
("BOTTOM TORTOISE SHELL BRACKET", "Sm", 0),
("WHITE TRAPEZIUM", "So", 0),
("BENZENE RING WITH CIRCLE", "So", 0),
("STRAIGHTNESS", "So", 0),
("FLATNESS", "So", 0),
("AC CURRENT", "So", 0),
("ELECTRICAL INTERSECTION", "So", 0),
("DECIMAL EXPONENT SYMBOL", "So", 0),
("BLACK RIGHT-POINTING DOUBLE TRIANGLE", "So", 0),
("BLACK LEFT-POINTING DOUBLE TRIANGLE", "So", 0),
("BLACK UP-POINTING DOUBLE TRIANGLE", "So", 0),
("BLACK DOWN-POINTING DOUBLE TRIANGLE", "So", 0),
("BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR", "So", 0),
("BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR", "So", 0),
("BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR", "So", 0),
("ALARM CLOCK", "So", 0),
("STOPWATCH", "So", 0),
("TIMER CLOCK", "So", 0),
("HOURGLASS WITH FLOWING SAND", "So", 0),
("BLACK MEDIUM LEFT-POINTING TRIANGLE", "So", 0),
("BLACK MEDIUM RIGHT-POINTING TRIANGLE", "So", 0),
("BLACK MEDIUM UP-POINTING TRIANGLE", "So", 0),
("BLACK MEDIUM DOWN-POINTING TRIANGLE", "So", 0),
("DOUBLE VERTICAL BAR", "So", 0),
("BLACK SQUARE FOR STOP", "So", 0),
("BLACK CIRCLE FOR RECORD", "So", 0),
("POWER SYMBOL", "So", 0),
("POWER ON-OFF SYMBOL", "So", 0),
("POWER ON SYMBOL", "So", 0),
("POWER SLEEP SYMBOL", "So", 0),
("OBSERVER EYE SYMBOL", "So", 0),
)
|
https://github.com/quarto-ext/typst-templates | https://raw.githubusercontent.com/quarto-ext/typst-templates/main/letter/README.md | markdown | Creative Commons Zero v1.0 Universal | # Typst Letter Format
Based on tbe letter template published by the Typst team at <https://github.com/typst/templates/tree/main/letter>.
**NOTE**: This format requires the pre-release version of Quarto v1.4, which you can download here: <https://quarto.org/docs/download/prerelease>.
## Installing
```bash
quarto use template quarto-ext/typst-templates/letter
```
This will install the extension and create an example qmd file that you can use as a starting place for your document.
## Using
Specify the sender, receipient, subject, etc. using YAML options, then write the body of the letter. For example, the following qmd source:
```yaml
---
subject: "Revision of our Procurement Contract"
name: "<NAME> \ Regional Director"
sender: "<NAME>, Universal Exports, 1 Heavy Plaza, Morristown, NJ 07964"
recipient: |
Mr. <NAME> \
Acme Corp. \
123 Glennwood Ave \
Quarto Creek, VA 22438 \
sent: "Morristown, June 9th, 2023"
format:
letter-typst: default
---
Dear Joe,
...
```
This document would be rendered as:

|
https://github.com/f14-bertolotti/bedlam | https://raw.githubusercontent.com/f14-bertolotti/bedlam/main/src/measure-theory/caratheodory-extension-theorem.typ | typst | #import "../theme.typ": definition, proof, lemma, theorem, proposition, comment
#import "introduction.typ": sigma-algebra, outer-measure, set-ring, pre-measure, measure, measure-space
#import "../notation/main.typ": extension, restriction
#import "../set-theory/main.typ" : cover
== Caratheodory Extension Theorem
#proposition(text[#sigma-algebra.tag generated by an #outer-measure.tag])[
Let $X$ be a set. Let $lambda$ be an #outer-measure.tag on $X$. Let $Sigma_lambda = {A in 2^X | forall E in 2^X : lambda(E) = lambda(E sect A) + lambda(E sect (X without A))}$ #comment[The set of subsets in which #outer-measure.tag cut $X$ in a "good way" ]. Then $Sigma_lambda$ is a #sigma-algebra.tag.
]<sigma-algebra-generated-by-an-outer-measure>
#proof(text[of @sigma-algebra-generated-by-an-outer-measure])[
We need to show that the axiom a #sigma-algebra.tag hold for $Sigma_lambda$:
1. #comment[($X in Sigma_lambda$)] Let $E in 2^x$, we have $lambda(E sect X) + lambda(E sect (X without X)) = lambda(E sect X) = lambda (X)$.
2. #comment[($A in Sigma_lambda ==> X without A in Sigma_lambda$)] Suppose $A in Sigma_lambda ==> forall E in 2^X lambda(E sect A) + lambda(E sect (X without A)) = lambda(E)$. Now consider $lambda(E sect (X without A)) + lambda(E sect (X without (X without A))) = lambda(E sect (X without A)) + lambda(E sect A) = lambda(E)$.
3. #comment[(${A_n}_(n in NN) in Sigma_lambda ==> union.big_(n in NN) A_n in Sigma_lambda$ (countable unions))]
1. #comment[($A,B in Sigma_lambda ==> A union B in Sigma_lambda$ (finite unions))] Suppose $A,B in Sigma_lambda$ then
- $forall E in 2^X: lambda(E) = lambda(E sect A) + lambda(E sect (X without A))$ and,
- $forall E in 2^X: lambda(E) = lambda(E sect B) + lambda(E sect (X without B))$.
Then, we have that:
$
&lambda(E sect (A union B)) + lambda(E sect (X without (A union B))) \
=&lambda(E sect (A union B)) + lambda(E sect (X without A) sect (X without B)) \
=&lambda(E sect (A union B) sect A) + lambda(E sect (A union B) sect (X without A)) + lambda(E sect (X without A) sect (X without B)) \
=&lambda(E sect A) + lambda(E sect B sect (X without A)) + lambda(E sect (X without A) sect (X without B)) \
=&lambda(E sect A) + lambda(E sect (X without A)) - lambda(E sect (X without A) sect (X without B)) + lambda(E sect (X without A) sect (X without B)) \
=&lambda(E sect A) + lambda(E sect (X without A)) \
=&lambda(E) \
$
2. Now we proceed to the third property. Let $N in NN$. Let ${A_n in Sigma_lambda}_(n in NN)$. Consider the pairwise disjoint ${A'_n}_(n in NN)$ built as in @unions-as-disjoint-unions. Recall that $union.big_(n in NN) A_n = union.big_(n in NN) A'_n = A$.
- We have that: $
& lambda(E sect (union.big_(n=1)^(N) A'_n)) + lambda(E sect (X without union.big_(n=1)^(N) A'_n)) && #comment[$Sigma_lambda$ is closed under finite unions.] \
<=& lambda(E sect (X without union.big_(n=1)^(N) A'_n)) + sum_(n=1)^N lambda(E sect A'_n) && #comment[definition of #outer-measure.tag] \
= & lambda(E sect (X without A'_1) sect dots sect (X without A'_N)) + lambda(E sect A'_1) + dots + lambda(E sect A'_N) && #comment[expansion] \
= & lambda(E sect (X without A'_2) sect dots sect (X without A'_N)) + lambda(E sect A'_2) + dots + lambda(E sect A'_N) && #comment[definition of $Sigma_lambda$] \
& dots \
= & lambda(E)
$
This relation holds for any $N$, even for $N=oo$.
Therefore:
$ lambda(E sect A) + lambda(E sect (X without A)) <= lambda(E) $
- On the other hand:
$ lambda(E) = lambda((E sect A) union (E sect (X without A))) <= lambda(E sect A) + lambda(E sect (X without A)) $
Therefore, we have:
$ lambda(E) <= lambda(E sect A) + lambda(E sect (X without A)) <= lambda(E) $
Or, equivalently:
$ lambda(E) = lambda(E sect A) + lambda(E sect (X without A)) $
Thus: $A in Sigma_lambda$
Therefore, $Sigma_lambda$ is a #sigma-algebra.tag.
]<sigma-algebra-generated-by-an-outer-measure-proof>
#proposition[
The restriction of the #outer-measure.tag $lambda$ to the #sigma-algebra.tag $Sigma_lambda$ as in @sigma-algebra-generated-by-an-outer-measure is a #measure.tag for $Sigma_lambda$.
]<outer-measure-restriction-is-a-measure>
#proof(text[of @outer-measure-restriction-is-a-measure])[
We need to show that the axioms of a measure hold:
1. #comment[(#(measure.ax1)($lambda$))]. \
This holds since $lambda$ is an #outer-measure.tag and $nothing in Sigma_lambda$.
2. #comment[(#(measure.ax2)($lambda$))]. \
This holds since $lambda$ is an #outer-measure.tag and $forall A in Sigma_lambda: nothing subset.eq A$
3. #comment[(#(measure.ax3)($lambda$))].
1. #comment[$lambda(union_(n in NN) E_n) <= sum_(n in NN) lambda(E_n)$]. \
This hold since $lambda$ is an #outer-measure.tag.
2. #comment[$lambda(union_(n in NN) E_n) >= sum_(n in NN) lambda(E_n)$]. \
From @sigma-algebra-generated-by-an-outer-measure-proof, we know that:
$ lambda(A sect (X without (union_(n in NN) E_n))) + sum_(n in NN) (A sect E_n) <= lambda(A) $
Since this inequality must hold for any $A$ in $Sigma_lambda$, it must hold also for $union_(n in NN) E_n$:
$
lambda((union_(n in NN) E_n) sect (X without (union_(n in NN) E_n))) + sum_(n in NN) lambda((union_(n in NN) E_n) sect E_n) & <= lambda(union_(n in NN) E_n) \
lambda(nothing) + sum_(n in NN) lambda(E_n) & <= lambda(union_(n in NN) E_n) \
sum_(n in NN) lambda(E_n) & <= lambda(union_(n in NN) E_n) \
$
Since $lambda(union_(n in NN) E_n) <= sum_(n in NN) lambda(E_n)$ and $lambda(union_(n in NN) E_n) >= sum_(n in NN) lambda(E_n)$, we have that $lambda(union_(n in NN) E_n) = sum_(n in NN) lambda(E_n)$
]
#proposition("measuring outside the measure domain")[
Let $(cal(R), X)$ be s #set-ring.tag.
Let $mu:cal(R) --> RR_(>=0) union {oo}$ be a #measure.tag $cal(R)$.
Let $E subset X$.
Let $inline( cal(A) = {{A_n}_(n in NN) | A_n in cal(R), E subset.eq union.big_(n in NN) A_n) })$ #comment[(Set of all #text[#cover.tag]s of $E$)].
Let $inline( lambda_mu = inf_({A_n}_(n in NN) in cal(A)) { sum_(n in NN) mu (A_n) })$. Then $lambda_mu$ is an #outer-measure.tag on $X$.
]<measuring-outside-the-measure>
#proof(text[of @measuring-outside-the-measure])[
We need to proove the three axiom for an #outer-measure.tag.
1. #comment[(#(outer-measure.ax1)($lambda_mu$))].
Since nothing in $cal(R)$, we have that ${nothing} in cal(A)$. Therefore $lambda_mu (nothing) = 0$.
2. #comment[(#(outer-measure.ax2)($lambda_mu$))].
A #cover.tag for $B$ is also a #cover.tag of $A$ since $A subset.eq B$. Therefore $lambda_mu (A) <= lambda_mu (B)$
3. #comment[(#(outer-measure.ax3)($lambda_mu$))].
Let ${A_(n,m)}_(m in NN)$ be the respective #cover.tag for $A_n$. Without loss of generality given by @unions-as-disjoint-unions, let each #cover.tag be pairwise disjoint. Since the union of #cover.tag of sets #text[#cover.tag]s the unions of sets #comment[($union.big A_n subset.eq union.big A_(m,n)$)], we have
$ lambda_mu (union.big_(n in NN) A_n) <=& lambda_mu (union.big_(m in NN) union.big_(n in NN) A_(n,m)) && #comment[previous axiom] \
<=& sum_(n in NN) mu (union.big_(m in NN) A_(n,m)) && #comment[None of the #text[#cover.tag]s $A_(n,m)$ achieves the infinum] \
=& sum_(n in NN) sum_(m in NN) mu (A_(n,m)) && #comment[$A_(n,m_0) sect A_(n,m_1) = nothing$] \
$
]
#proposition(text[restriction of $lambda_mu$])[
The restriction of $lambda_mu$ as in @measuring-outside-the-measure on $cal(R)$ is $mu$.
]<restriction-lambda-mu>
#proof(text[of @restriction-lambda-mu])[
1. #comment[$lambda_mu (A) <= mu(A)$]. \
For any $A in cal(R)$, $A$ itself is a #cover.tag for $A$, hence $lambda_mu (A) <= mu(A)$ #comment[($lambda_mu$ is the inf. of the measure of all #text[#cover.tag]s)].
2. #comment[$lambda_mu (A) >= mu(A)$].
Suppose there is a #cover.tag $cal(B) = {B_n in cal(R)}_(n in NN)$ of $A$.
Let $cal(B)'={B'_n}_(n in NN)$ be the respective pairwise disjoint cover according to @unions-as-disjoint-unions.
Let $cal(B)'' ={B'_n sect A}_(n in NN)$. We have that $cal(B)''$ is pairwise disjoint and $A = union_(B in cal(B)'') B subset.eq union_(B in cal(B)) B$
We have that $union_(B in cal(B)'') B = A$ since $cal(B)''$ is a #cover.tag for $A$ intersected with $A$.
Then, $mu(A) = mu(union_(B in cal(B)'') B) = sum_(B in cal(B)'') mu(B) <= sum_(B in cal(B)') mu(B) = sum_(B in cal(B)) mu(B)$ since $mu$ is a #measure.tag.
Therefore, for any #cover.tag $cal(B)$, we have shown that $mu(A) <= sum_(B in cal(B)) mu(B)$.
Then, $mu(A) <= lambda_mu (A)$, since $lambda_mu$ is the inf. of all #text[#cover.tag]s.
Putting all togheter:
$ mu(A) <= lambda_mu (A) <= mu(A) $
Therefore, $mu(A) = lambda_mu (A)$.
]
From @sigma-algebra-generated-by-an-outer-measure and @outer-measure-restriction-is-a-measure, we have the means to generate a #measure-space.tag (#sigma-algebra.tag and #measure.tag) just from an #outer-measure.tag. Further, from #set-ring.tag and a #measure.tag on the ring we can build an #outer-measure.tag, thanks to @measuring-outside-the-measure. Thus by piecing these construction together, we may be able to generate a #measure-space.tag from a #set-ring.tag with a #measure.tag. This is indeed the subject of @caratheodory-extension-theorem.
#lemma[
Let $(X,cal(R))$ be a #set-ring.tag.
Let $mu$ be a #measure.tag $(X,cal(R))$.
Let $lambda$ be the #outer-measure.tag associated with $mu$ (according to @measuring-outside-the-measure).
Let $Sigma$ be the #sigma-algebra.tag associated with $lambda$ (according to @sigma-algebra-generated-by-an-outer-measure).
Then $cal(R) subset.eq Sigma$
]<caratheodory-lemma>
#proof(text[of @caratheodory-lemma])[
Let $A in cal(R)$.
Let $E in 2^X$.
1. #comment[$lambda(E) <= lambda(E sect A) + lambda(E sect (X without A))$] \
Let Since $lambda$ is an #outer-measure.tag, we have $lambda(E) = lambda((E sect A) union (E sect (X without A))) <= lambda(E sect A) + lambda(E sect (X without A))$.
2. #comment[$lambda(E sect A) + lambda(E sect (X without A)) <= lambda(E)$] \
Now, Let ${A_n}_(n in NN)$ be a disjoint $cal(R)$-#cover.tag of $E$.
Then, ${A_n sect A}$ is a disjoint $cal(R)$-#cover.tag of $X sect A$.
And, ${A_n sect (X without A)}$ is a disjoint $cal(R)$-#cover.tag of $X sect (X without A)$.
Now recall that $lambda$ (according to @measuring-outside-the-measure) is the infimum from all possible covers for $mu$. Since, we simply picked two possible #text[#cover.tag]s the following hold:
$ lambda(E sect A) + lambda(E sect (X without A)) <= sum_(n in NN) mu(A_n sect A) + sum_(n in NN) mu(A_n sect (X without A)) $
Notice that $E sect A_n$ and $E sect (X without A_n)$ are disjoint, and therefore:
$ mu(E sect A_n) + mu(E sect (X without A_n)) = mu((E sect A_n) union (E sect (X without A_n))) = mu(A_n) $
Returning to the previous inequality, we have that:
$ sum_(n in NN) mu(A_n sect A) + sum_(n in NN) mu(A_n sect (X without A)) <= sum_(n in NN) mu(A_n) $
Since $lambda(E sect A) + lambda(E sect (X without A)) <= sum_(n in NN) mu(A_n)$ holds for all #text[#cover.tag]s, then it must hold for the tightest #cover.tag:
$ lambda(E sect A) + lambda(E sect (X without A)) <= lambda(E) $
3. #comment[$lambda(E) = lambda(E sect A) + lambda(E sect (X without A))$] \
Since $lambda(E) <= lambda(E sect A) + lambda(E sect (X without A)) <= lambda(E)$, we have that $lambda(E) = lambda(E sect A) + lambda(E sect (X without A))$.
4. #comment[$A in Sigma$] \
By definition of $Sigma$ (according to @sigma-algebra-generated-by-an-outer-measure) we have that $A in Sigma$.
]
TODO: check measure used in the ring, that is probably a pre-measure.
#theorem("Caratheodory's Extension Theorem")[
TODO
]<caratheodory-extension-theorem>
|
|
https://github.com/NOOBDY/formal-language | https://raw.githubusercontent.com/NOOBDY/formal-language/main/q2.typ | typst | The Unlicense | #import "@preview/finite:0.3.0": automaton, layout
#let q2 = [
2. Convert the `DFA`s to a `regex`:
#automaton(
(
q0: (q0:"a", q1:"b"),
q1: (q1:"b", q2:"a"),
q2: (q0:"b", q2:"a")
),
labels: (
q0: $ q_0 $,
q1: $ q_1 $,
q2: $ q_2 $
),
final: ("q0"),
style: (
state: (
stroke: 0.5pt,
),
transition: (
stroke: 0.5pt,
curve: 0,
label: (
angle: 0deg
)
),
q2-q2: (anchor: left)
),
layout: layout.custom.with(
positions: (..) => (
q0: (0, 3),
q1: (3, 3),
q2: (3, 0),
)
)
)
1.
$ &cases(
q_0 &= epsilon.alt union a union q_2 b \
q_1 &= b union q_0 b \
q_2 &= a union q_1 a
) \
=> &cases(
q_0 &= epsilon.alt union a union q_2 b \
q_1 &= q_0 b b^* = q_0 b^+ \
q_2 &= q_1 a a^* = q_1 a^+
) \
=> &q_0 = epsilon.alt union a union ((q_0 b^+)a^+)b \
=> &q_0 = epsilon.alt union a union q_0 b^+ a^+ b \
=> &q_0 = epsilon.alt union a (b^+ a^+ b)^* $
#automaton(
(
q0: (q1:"a,b"),
q1: (q1:"a", q2:"b"),
q2: (q0:"a", q1:"b")
),
labels: (
q0: $ q_0 $,
q1: $ q_1 $,
q2: $ q_2 $
),
final: ("q0", "q2"),
style: (
state: (
stroke: 0.5pt,
),
transition: (
stroke: 0.5pt,
curve: 0,
label: (
angle: 0deg
)
),
q1-q2: (curve: 0.5),
q2-q1: (curve: 0.5)
),
layout: layout.custom.with(
positions: (..) => (
q0: (0, 3),
q1: (3, 3),
q2: (3, 0),
)
)
)
2.
$ &cases(
q_0 &= epsilon.alt union q_2 a \
q_1 &= a union q_0 (a union b) union q_2 b \
q_2 &= q_1 b
) \
=> &cases(
q_0 &= epsilon.alt union q_2 a \
q_2 &= (a union q_0 (a union b) union q_2 b) b
) \
=> &cases(
q_0 &= epsilon.alt union q_2 a \
q_2 &= (a union q_0 (a union b)) b union q_2 b b
) \
=> &cases(
q_0 &= epsilon.alt union q_2 a \
q_2 &= (a union q_0 (a union b)) b(b b)^*
) \
$
= UNFINISHED
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list_07.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Edge cases.
-
Not in list
-Nope
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/figures/02-methodology/dsrp.typ | typst | #import "@preview/fletcher:0.4.2" as fletcher: node, edge
#set text(font: "Fira Sans", size: 9pt)
#let blob(pos, label, tint: yellow, ..args) = node(
pos,
align(center, label),
width: 40mm,
fill: tint.lighten(60%),
stroke: 1pt + tint.darken(20%),
corner-radius: 2pt,
..args,
)
#fletcher.diagram(
spacing: 20pt,
cell-size: (20mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 80%,
blob((0,1), [Problem identification #linebreak() and motivation]),
edge("-|>"),
blob((1,1), [Objectives of a solution]),
edge("-|>"),
blob((2,1), [Design and development]),
edge("-|>"),
blob((2,2), [Demonstration]),
edge("-|>"),
blob((1,2), [Evaluation]),
edge("-|>"),
blob((0,2), [Communication]),
)
|
|
https://github.com/EunTilofy/NumComputationalMethods | https://raw.githubusercontent.com/EunTilofy/NumComputationalMethods/main/Chapter5/Chapter5-2.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Computing Method",
title: "Computing Method - Chapter5",
date: "2024.4.14",
authors: "<NAME>, 3210106357",
has_cover: false
)
*Problems:8,10,15*
#HWProb(name: "8")[
试用两点三次 Hermite 插值函数作(5.1)式的求积公式。
$
integral_a^b f(x) dx
$
]
#solution[
设 $f(a) = y_a, f(b) = y_b, f'(a) = y'_a, f'(b) = y'_b$。
差商表如下:
#tablex(
columns: 5,
auto-hlines: false,
auto-vlines: false,
(), vlinex(), (), (), (),
$a$, $y_a$, [], [], [],
$a$, $y_a$, $y'_a$, [], [],
$b$, $y_b$, $(y_b-y_a)/(b-a)$, $(y'_a-(y_b-y_a)/(b-a))/(a-b)$, [],
$b$, $y_b$, $y'_b$, $(y'_b-(y_b-y_a)/(b-a))/(b-a)$, $(y'_b+y'_a-2(y_b-y_a)/(b-a))/(b-a)^2$,
)
所以插值函数为:
$
p(f;x)=(y'_b+y'_a-2(y_b-y_a)/(b-a))/(b-a)^2 (x-b)(x-a)^2 + (y'_a-(y_b-y_a)/(b-a))/(a-b) (x-a)^2 + y'_a (x-a) + y_a
$
$
integral_a^b p(f;x) dx &= y_a (b-a)+1/2 (b-a)^2 y'_a - 1/3 (y'_a-(y_b-y_a)/(b-a)) (b-a)^2 - 1/12 (y'_b+y'_a-2(y_b-y_a)/(b-a)) (b-a)^2\
&= (b-a)y_a + [(1/2 (y_b-y_a)/(b-a))-1/12 (y'_b - y'_a)](b-a)^2\
&=1/2(y_b+y_a) (b-a) - 1/12 (y'_b - y'_a) (b-a)^2
$
]
#HWProb(name: "10")[
用 $n=2,4$ 的 Gauss 公式计算下列积分:
#set enum(numbering: "(1)")
+ $integral_1^9 sqrt(x) dx$.
+ $2/sqrt(pi) integral_0^1 e^(-x^2) dx$.
+ $integral_0^1 arctan(x)/x^(3/2) dx$.
]
#solution[
使用 Gauss-Legendre 求积公式:\
#set enum(numbering: "(1)")
$n=2$: $x_k = pm 0.5773503, A_k = 1, k = 1, 2$
+ $
I = integral_(-1)^1 sqrt(4t+5) d(4t+5) = integral_(-1)^1 4sqrt(4t+5) dt =
4sqrt(4t+5)|_(x_1) + 4sqrt(4t+5)|_(x_2) = 17.375579645963338
$
+ $
I = 2 / sqrt(pi) integral_(-1)^1 1/2 e^(-1/4(t+1)^2) dt = 1 / sqrt(pi) sum_(i=1)^2 e^(-1/4 (x_i+1)^2) = 0.8424418886754169
$
+ $
I = integral_(-1)^1 1/2 arctan(1/2(t+1))/(1/2(t+1))^(3/2) dx = 1/2 sum_(i=1)^2 arctan(1/2(x_i+1))/(1/2(x_i+1))^(3/2) = 1.548617790677832
$
$n=4$: $x_(12) = pm 0.8611363, x_(34)=0.3399810, A_(12) = 0.3478548, A_(34)=0.6521452$
+ $
I = integral_(-1)^1 4sqrt(4t+5) dt = sum_(i=1)^4 4sqrt(4 x_i + 5) dot.c A_i = 17.3342011001631
$
+ $
I = 2 / sqrt(pi) integral_(-1)^1 1/2 e^(-1/4(t+1)^2) dt = 1 / sqrt(pi) sum_(i=1)^4 A_i e^(-1/4 (x_i+1)^2) = 0.8427011772004525
$
+ $
I = integral_(-1)^1 1/2 arctan(1/2(t+1))/(1/2(t+1))^(3/2) dx = 1/2 sum_(i=1)^4 arctan(1/2(x_i+1))/(1/2(x_i+1))^(3/2) = 1.7034547032433185
$
]
#HWProb(name: "15")[
令 $x_i = x_0 + i h, y_j = y_0 + j k$($h$ 和 $k$ 分别表示 $x$ 方向与 $y$ 方向的步长),又令 $f_(i j)$ 表示 $f(x, y)$ 在 $(x_i, y_j)$ 的值。应用抛物线公式推导关于在矩形 $x_0 leq x leq x_2, y_0 leq y leq y_2$ 上的二重积分
$
integral_(x_0)^(x_2) integral_(y_0)^(y_2) f(x, y) dx dy,
$
的求积公式
$
(h k)/9 (f_(0 0) + f_(0 2) + f_(2 0) + f_(2 2) + 4(f_(0 1) + f_(1 0) + f_(1 2) + f_(2 1)) + 16 f_(1 1))
$
且余项是
$
E = - (h k)/45 (h^4 (partial^4 f)/(partial x^4)(xi_1, eta_1) + k^4 (partial^4 f)/(partial y^4)(xi_2, eta_2))
$
其中,$xi_1,xi_2$ 是介于 $x_0,x_2$ 之间的值,$eta_1,eta_2$ 是介于 $y_0, y_2$ 之间的值。
把结果推广,计算积分
$
integral_(x_0)^(x_m) integral_(y_0)^(y_n) f(x, y) dx dy
$
其中,$m,n$ 是偶数。
]
#Proof[
令 $g(x) = integral_(y_0)^(y_2) f(x, y) dy$,应用抛物线公式得
$
g(x) approx k/3 (f(x, y_0) + 4 f(x, y_1) + f(x, y_2)),
$
所以
$
I &= integral_(x_0)^(x_2) g(x) dx approx h/3 (g(x_0) + 4 g(x_1) + g(x_2)) \ &approx h/3 [k/3(f_(00) + 4f_(01) + f_(02)) + 4k/3(f_(10) + 4f_(11) + f_(12)) + k/3(f_(20) + 4f_(21) + f_(22))] \
&= (h k)/9 (f_(0 0) + f_(0 2) + f_(2 0) + f_(2 2) + 4(f_(0 1) + f_(1 0) + f_(1 2) + f_(2 1)) + 16 f_(1 1))
$
计算二重积分的余项,
设 $m,M$ 是 $(partial^4 f)/(partial y^4)$ 在 $[x_0, x_2] times [y_0, y_2]$ 中的最小值和最大值,
所以有:
$
- k^5/90 M leq k/3 (f_(00) + 4 f_(01) + f_(02)) - g(x_0) leq - k^5/90 m\
- k^5/90 M leq k/3 (f_(10) + 4 f_(11) + f_(12)) - g(x_1) leq - k^5/90 m \
- k^5/90 M leq k/3 (f_(20) + 4 f_(21) + f_(22)) - g(x_2) leq - k^5/90 m
$
所以,
$
- (h k^5)/45 M leq (h k)/9 (f_(0 0) + f_(0 2) + f_(2 0) + f_(2 2) + 4(f_(0 1) + f_(1 0) + f_(1 2) + f_(2 1)) + 16 f_(1 1)) - h/3 (g(x_0) + 4 g(x_1) + g(x_2)) leq - (h k^5)/45 m
$
由介值定理得,存在 $x_0 leq xi_2 leq x_1, y_0 leq eta_2 leq y_2$,
$
(h k)/9 (f_(0 0) + f_(0 2) + f_(2 0) + f_(2 2) + 4(f_(0 1) + f_(1 0) + f_(1 2) + f_(2 1)) + 16 f_(1 1)) - h/3 (g(x_0) + 4 g(x_1) + g(x_2))
= - (h k^5)/45 (partial^4 f)/(partial y^4) (xi_2, eta_2)
$
根据一元抛物线公式的余项公式可以得到:
$
h/3 (g(x_0) + 4 g(x_1) + g(x_2)) - I = - h^5/90 g^((4)) (xi_1), quad (x_0 leq xi_1 leq x_1)
$
其中,$g^((4)) (xi_1) = integral_(y_0)^(y_2) (partial^4 f)/(partial y^4) (xi_1, y) dy$,根据积分中值定理,$g^((4)) (xi_1) = 2k (partial^4 f)/(partial y^4) (xi_1, eta_1), quad (y_0 leq eta_1 leq y_1)$。
所以
$
h/3 (g(x_0) + 4 g(x_1) + g(x_2)) - I = - (h^5 k)/45 (partial^4 f)/(partial x^4) (xi_1, eta_1)
$
相加得,
$
E &= (h k)/9 (f_(0 0) + f_(0 2) + f_(2 0) + f_(2 2) + 4(f_(0 1) + f_(1 0) + f_(1 2) + f_(2 1)) + 16 f_(1 1)) - I \
&= - (h k^5)/45 (partial^4 f)/(partial y^4) (xi_2, eta_2) - (h^5 k)/45 (partial^4 f)/(partial x^4) (xi_1, eta_1) = (h k)/45 (h^4 (partial^4 f)/(partial x^4)(xi_1, eta_1) + k^4 (partial^4 f)/(partial y^4)(xi_2, eta_2))
$
其中,$xi_1,xi_2$ 是介于 $x_0,x_2$ 之间的值,$eta_1,eta_2$ 是介于 $y_0, y_2$ 之间的值。
根据复化梯形公式,
$
& integral_(x_0)^(x_m) integral_(y_0)^(y_n) f(x, y) dx dy
approx h/3 (g(x_0) + g(x_m) + 4 sum_(k=1)^(m/2) g(x_(2k-1)) + 2 sum_(k=1)^(m/2 -1) g(x_(2k))) \
approx & (h k)/9 (f_(00) + f_(0 n) + f_(m 0) + f_(m n) +
4 (sum_(k=1)^(n/2) (f_(0,2k-1) + f_(m,2k-1)) + sum_(k=1)^(m/2) (f_(2k-1,0) + f_(2k-1,n)))\
& 2 (sum_(k=1)^(n/2 - 1) (f_(0,2k) + f_(m,2k)) + sum_(k=1)^(m/2 - 1) (f_(2k,0) + f_(2k,n))) + 16 sum_(k=1)^(m/2) sum_(j=1)^(n/2) f_(2k-1,2j-1) + 4 sum_(k=1)^(m/2-1) sum_(j=1)^(n/2-1) f_(2k,2j) \
& 8 (sum_(k=1)^(m/2) sum_(j=1)^(n/2 -1) f_(2k-1, 2j) + sum_(k=1)^(m/2-1) sum_(j=1)^(n/2) f_(2k, 2j-1))
)
$
] |
|
https://github.com/swaits/typst-collection | https://raw.githubusercontent.com/swaits/typst-collection/main/glossy/0.1.0/src/utils.typ | typst | MIT License | #let __default(val, default) = if val == none { default } else { val }
#let __pluralize(word) = {
// Define helper functions for checking endings
let ends_with = (suffix) => lower(word).ends-with(suffix)
let ends_with_any = (suffixes) => suffixes.any((suffix) => ends_with(suffix))
if ends_with_any(( "s", "x", "z", "sh", "ch" )) { // Handle special cases for "es" endings
word + "es"
} else if ends_with("y") and not ends_with_any(( "a", "e", "i", "o", "u" )) { // Handle "y" -> "ies"
word.slice(0, -1) + "ies"
} else if ends_with("f") { // Handle "f" or "fe" -> "ves"
word.slice(0, -1) + "ves"
} else if ends_with("fe") {
word.slice(0, -2) + "ves"
} else { // Default to adding "s"
word + "s"
}
}
|
https://github.com/QuadnucYard/crossregex-typ | https://raw.githubusercontent.com/QuadnucYard/crossregex-typ/main/examples/standard.typ | typst | MIT License | #import "../src/lib.typ": crossregex
#crossregex(
7,
constraints: (
`.*H.*H.*`,
`(DI|NS|TH|OM)*`,
`F.*[AO].*[AO].*`,
`(O|RHH|MM)*`,
`.*`,
`C*MC(CCC|MM)*`,
`[^C]*[^R]*III.*`,
`(...?)\1*`,
`([^X]|XCC)*`,
`(RR|HHH)*.?`,
`N.*X.X.X.*E`,
`R*D*M*`,
`.(C|HH)*`,
`.*G.*V.*H.*`,
`[CR]*`,
`.*XEXM*`,
`.*DD.*CCM.*`,
`.*XHCR.*X.*`,
`.*(.)(.)(.)(.)\4\3\2\1.*`,
`.*(IN|SE|HI)`,
`[^C]*MMM[^C]*`,
`.*(.)C\1X\1.*`,
`[CEIMU]*OH[AEMOR]*`,
`(RX|[^R])*`,
`[^M]*M[^M]*`,
`(S|MM|HHH)*`,
`.*SE.*UE.*`,
`.*LR.*RL.*`,
`.*OXR.*`,
`([^EMC]|EM)*`,
`(HHX|[^HX])*`,
`.*PRR.*DDC.*`,
`.*`,
`[AM]*CM(RC)*R?`,
`([^MC]|MM|CC)*`,
`(E|CR|MN)*`,
`P+(..)\1.*`,
`[CHMNOR]*I[CHMNOR]*`,
`(ND|ET|IN)[^X]*`,
),
show-views: false
)
|
https://github.com/duskmoon314/THU_AMA | https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch2/5-群的应用.typ | typst | Creative Commons Attribution 4.0 International | #import "/book.typ": *
#show: thmrules
#show: book-page.with(title: "群的应用")
= 群的应用
== 项链问题
#example("项链问题")[
设有$n$种颜色的珠子(每种颜色的珠子都足够多),要做成$m$课珠子都项链,问:在旋转与翻转意义下,可以做成多少种不同的项链?
]
数学表述:设珠子集$X = { 1 , 2 , dots.h.c , m }$,颜色集$A = { a_1 , dots.h.c , a_n }$,群$G = D_m$(二面体群),染色方案集${ f : X arrow.r A } eq.delta Omega$
$g : X arrow.r X , f = mat(delim: "(", 1, 2, dots.h.c, m;c_1, c_2, dots.h.c, c_m)$,其中$c_i in A$
令$g lr((f)) = mat(
delim: "(",
g lr((1)), g lr((2)), dots.h.c, g lr((m));c_1, c_2, dots.h.c, c_m,
) = mat(delim: "(", i_1, i_2, dots.h.c, i_m;c_1, c_2, dots.h.c, c_m) in Omega$
$g lr((f)) = f circle.stroked.tiny g^(- 1)$
验证群作用:$e lr((f)) = f circle.stroked.tiny e^(- 1) = f , g_1 g_2 lr((f)) = f circle.stroked.tiny lr((g_1 g_2))^(- 1) = f circle.stroked.tiny g_2^(- 1) circle.stroked.tiny g_1^(- 1) = g_1 lr((g_2 lr((f))))$
等价染色方案的判定:同轨道$g lr((f_1)) = f_2 arrow.l.r.double f_1 tilde.op f_2 arrow.r.double$不同类型的方案数,就是轨道数$N$。由Burnside引理,$N = frac(1, 2 m) sum_(g in D_m) chi lr((g))$
不动点的判定:$g lr((f)) = f arrow.l.r.double g$ 的标准分解中,同一轮换的元涂相同颜色 $chi lr((g)) = n^(lambda_1 + dots.h.c + lambda_m) arrow.r.double N = frac(1, 2 m) sum_(g in D_m) n^(lambda_1 + dots.h.c + lambda_m) = frac(1, 2 m) sum_(1^(lambda_1) dots.h.c m^(lambda_m)) c lr((lambda_1 dots.h.c lambda_m)) n^(lambda_1 + dots.h.c + lambda_m)$,其中$c lr((lambda_1 dots.h.c lambda_m))$为该类型置换数量
#example()[
用3种颜色做成6颗珠子的项链
]
#solution()[
$G = D_6 = {
rho^0 = lr((1)) , rho = lr((123456)) , rho^2 = lr((135)) lr((245))\
rho^3 = lr((14)) lr((25)) lr((36)) , rho^4 = lr((153)) lr((264)) , rho^5 = lr((165432))\
lr((16)) lr((25)) lr((34)) , lr((12)) lr((36)) lr((45)) , lr((14)) lr((23)) lr((56))\
lr((26)) lr((35)) , lr((13)) lr((46)) , lr((15)) lr((24))
}$
#figure(
align(center)[#table(
columns: 3,
align: (col, row) => (center, center, center).at(col),
inset: 6pt,
[置换类型], [个数], [$chi lr((g))$],
[$1^6$], [1], [$3^6$],
[$1^2 2^2$], [3], [$3^4$],
[$2^3$], [4], [$3^3$],
[$3^2$], [2], [$3^2$],
[$6^1$], [2], [$3^1$],
)],
)
$N = 1 / 12 lr([3^6 times 1 + 3^4 times 3 . . .]) = 92$
]
== 带约束条件的项链问题
群可能为$D_m$或其子群,集合可能为$Omega$或其子集
#example()[
3颗红珠和6颗白珠做项链
]
带珠子标号染色,共有$binom(9, 3) = 84$,$Omega_1 subset.eq Omega$且$Omega_1 = 84$,$D_9$作用在$Omega_1$,$g lr((f)) = f circle.stroked.tiny g^(- 1)$,轨道数$N$为不等价的方案数
#figure(
align(center)[#table(
columns: 3,
align: (col, row) => (center, center, center).at(col),
inset: 6pt,
[置换类型], [个数], [$chi lr((g))$],
[$1^9$], [1], [84],
[$1^1 2^4$], [9], [4],
[$3^3$], [2], [3],
[$9^1$], [$phi lr((9)) = 6$], [0],
)],
)
7种
#example()[
设苯环上可结合三种分子,若考虑单双键的区别,一共可形成多少种不同的物质?
]
$D_6$中保持单双键不变的置换有
$G = {
lr((1)) , rho^2 = lr((135)) lr((246)) , rho^4 = lr((153)) lr((264))\
lr((16)) lr((25)) lr((34)) , lr((12)) lr((36)) lr((45)) , lr((14)) lr((23)) lr((56))
} lt.eq D_6$
#figure(
align(center)[#table(
columns: 3,
align: (col, row) => (center, center, center).at(col),
inset: 6pt,
[置换类型], [个数], [$chi lr((g))$],
[$1^6$], [1], [$3^6$],
[$3^2$], [2], [$3^2$],
[$2^3$], [3], [$3^3$],
)],
)
138种
== 正多面体的染色问题
#example()[
用$n$种颜色,对正多面体的顶点、边、面进行染色,在多面体的旋转意义下,共有多少种本质上不同的染色方法?
]
群变为正多面体的旋转群
共有五类正多面体:
- 正四面体(自对偶)
- 正六面体,正八面体(对偶)
- 正十二面体,正二十面体(对偶)
顶点染色 $arrow.l.r.double$ 对偶体的面染色
== 布尔函数的对称计数问题
设$bb(F)_2 = bb(Z) \/ n bb(Z) = { 0 , 1 }$,形如$f lr((x_1 , dots.h.c , x_n)) : bb(F)_2 times bb(F)_2 times dots.h.c times bb(F)_2 arrow.r bb(F)_2$的函数,称为一个$n$元#strong[布尔函数]。若两个$n$元布尔函数,通过交换变量可相互转换,则称这两个布尔函数同类型。
自变量集$Y = { x_1 , dots.h.c , x_k }$,函数集$Omega = { f : bb(F)_2^k arrow.r bb(F)_2 }$,$G = S_n$
将$G$作用在$Omega$上,$sigma in S_k , f in Omega , sigma lr((f)) lr((x_1 , dots.h.c , x_k)) eq.delta f lr((x_(sigma lr((1))) , dots.h.c , x_(sigma lr((k))))) = f circle.stroked.tiny sigma^(- 1) lr((x_1 , dots.h.c , x_k))$
群作用验证:略
等价函数的判定 $arrow.l.r.double$ 同轨道
不动点判断:$sigma lr((f)) = f arrow.l.r.double f$在每一个$sigma$轨道上赋相同的值(取定$sigma$,作用在$f$的自变量集上产生的不变圈)
#example()[
3元布尔函数有多少种不同的类型?
]
取$sigma in G = S_3 = { lr((1)) , lr((12)) , lr((13)) , lr((23)) , lr((123)) , lr((132)) }$
== 图的计数问题
#example()[
图论中,若不计途中顶点的编号次序,$n$个顶点可构成多少种不同类型的简单无(有)向图?
]
从数学角度定义一个图:$lr((V , E))$,其中$V$为顶点集,$E$为边集。设$V = { v_1 , dots.h.c , v_n }$,则 $ cases(
delim: "{",
E = { { v_i , v_j } \| upright("对某些") i eq.not j } & upright("无向图"),
E = { lr((v_i , v_j)) \| upright("对某些") i eq.not j } & upright("有向图"),
) $ 实际上,一个图就对应了一个边集的赋值函数$f : Y arrow.r { 0 , 1 }$,其中$Y = { { v_i , v_j } \| forall i eq.not j }$或${ lr((v_i , v_j)) \| forall i eq.not j }$
故可将群$G = S_n$作用在图集$Omega = { f : Y arrow.r { 0 , 1 } }$,群作用同上。
图等价:$lr((v_i , v_j)) in E arrow.l.r.double lr((sigma lr((v_i)) , sigma lr((v_j)))) in E med lr((exists sigma in S_n))$ (同轨道)
不动点判则:$sigma lr((f)) = f arrow.l.r.double f$对同一个$sigma$轨道(含在集合$Y$中)赋相同值
#example()[
4个顶点可构成多少种不同类型的简单无向图?
]
#solution()[
$V = { 1 , 2 , 3 , 4 } , Y = { { i , j } \| 1 lt.eq i < j lt.eq 4 } , Omega = { f : Y arrow.r { 0 , 1 } } , G = S_4$。将$S_4$作用在$Omega$上,重点分析$sigma$作用在自变量集所产生的$sigma$轨道数:
$sigma = lr((12))$: 4个;$sigma = lr((123))$: 2个;$sigma = lr((12)) lr((34))$: 4个;$sigma = lr((1234))$: 2个
#figure(
align(center)[#table(
columns: 3,
align: (col, row) => (center, center, center).at(col),
inset: 6pt,
[置换类型], [个数], [$chi lr((g))$],
[$1^4$], [1], [$2^6$],
[$1^1 3^1$], [8], [$2^2$],
[$2^2$], [3], [$2^4$],
[$1^2 2^1$], [6], [$2^4$],
[$4^1$], [6], [$2^2$],
)],
)
故由 Burnside 引理,不同类型的图共有11个
]
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/examples/slides.typ | typst | #import "../lib.typ": *
// #let s = themes.simple.register(s, aspect-ratio: "16-9", footer: [Simple slides])
// #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: [Custom footer])
// #let s = themes.dewdrop.register(s, aspect-ratio: "16-9", footer: [Dewdrop])
#let s = (s.methods.info)(
self: s,
title: [Title],
subtitle: [Subtitle],
author: [Authors],
date: datetime.today(),
institution: [Institution],
)
#let s = (s.methods.enable-transparent-cover)(self: s)
#let (init, slides, touying-outline, alert) = utils.methods(s)
#show: init
#show strong: alert
#let (slide,) = utils.slides(s)
#show: slides
= Let's start a new section
== First Title
First content
#pause
with a pause.
== Second Title
Second content. |
|
https://github.com/jedinym/sqc-text | https://raw.githubusercontent.com/jedinym/sqc-text/main/state-of-the-art/main.typ | typst | #set page(margin: 1.75in, numbering: "1")
#set par(leading: 0.55em, justify: true)
#set text(font: "New Computer Modern")
#show raw: set text(font: "New Computer Modern Mono")
#show heading: set block(above: 1.4em, below: 1em, )
#align(center, text(17pt)[
*Structural biology validation landscape*
])
#align(center)[
<NAME> \
Masaryk University \
#link("mailto:<EMAIL>")
]
Structural biology, as a branch of molecular biology, is a life science that has
seen much impact in the scientific world. This is proven by the fact that as of
now (March 2024) there were 81 Nobel prizes awarded in relation to it
@biology-nobel. It has contributed with methods for examining and acquiring
biomacromolecular scientific data. These data constitute coordinate models
@coord-models of polymers that are biological in origin (i.e. nucleic acids,
polysacharrides, and proteins).
These assembled models in computer-readable form are frequently stored in
databases which aggregate results obtained by various experimental methods. The
largest and most notable curated database is the Protein Data Bank (PDB) @pdb.
Currently, this freely-accessible archive stores over 217,000 entries
@pdb-entry-stats. Most data in the PDB is created using methods such as Nuclear
Magnetic Resonance (NMR) spectroscopy, X-ray crystallography, or Electron
Microscopy (EM) @pdb-methods.
Because of the experimental nature of these methods, this data can contain
errors caused by the imperfections of measurements or simply, human error
@structure-errors[p. 1]. That is why significant effort has been made to develop
a consensus on how to validate this data. The PDB consortium has organised
so-called Validation Task Forces (VTFs), i.e. groups of experts on each
experimental method used in developing structure models @pdb-validation[p.
1917]. Based on the results of the task forces, the PDB started to offer
validation reports for most of the structures in the database @pdb-validation[p.
1917]. These reports are generated by the Validation Pipeline. The pipeline
modules run validations on the structure using existing bioinformatical software
@pdb-validation[p. 1921]. After running the validations, the results are
aggregated and the reports are composed into a human-readable form (PDF) and a
computer-readable form (XML) @pdb-validation[p. 1921]. When a new structure is
deposited into the PDB database, the pipeline is run and the reports are stored
alongside the deposited structure @pdb-validation[p. 1916].
To allow users to check their experimental data without beginning the deposition
process, the PDB consortium created the wwPDB standalone validation web server
@pdb-validation[p. 1917]. It is a scaled-down version of the validation
pipeline that is used during deposition proper @pdb-standalone-server.
Public access to the standalone server is provided using a web server, a CLI
application, and a Python library @pdb-validation[p. 1920]
@pdb-standalone-server-details. However, the service is constituted of only 2
compute servers (2 x 16 CPUs, 2 x 128 GB RAM), which serve the entire world. The
// TODO: low throughput? why?
low throughput makes it impractical to be used in research projects that need to
validate a lot of structures. Even though the software components of the
validation pipeline are public @pdb-validation[p. 1922], the implementation of
the pipeline itself is not. For this reason, it is not possible to deploy it
using on-premise infrastructure.
To allow for simple deployment and high-throughput validations, a new solution
is needed. Unfortunately, not all components of the pipeline are publicly
available. In this work, we reimplement the publicly available parts of the
validation pipeline using software that allows for easy scalability and
deployment.
Since the PDB validation pipeline uses multiple software components with various
dependencies, it is necessary to create an environment in which all of the
components can run. To achieve this goal, we use containers, which guarantee
that the software suite can run in any cloud or non-cloud environment
@containers[p. 2-3]. For packaging the components and their dependencies, we use
_Docker_, a set of tools that allows easy creation of containers @containers[p. 3].
To allow for scalability, _Kubernetes_ is utilized. An open-source system
originally developed at _Google_ allows for automatic deployment and scaling of
containerized applications @kubernetes.
To simplify deployment, we use _Ansible_, an open-source automation tool
@ansible which allows for deployment in any _Kubernetes_ cluster.
#bibliography("bibliography.yaml", style: "ieee") |
|
https://github.com/rickysixx/unimore-informatica | https://raw.githubusercontent.com/rickysixx/unimore-informatica/main/introduction-to-quantum-information-processing/riassunto_quantum.typ | typst | #import "@preview/physica:0.9.2": bra, ket, expval, braket, ketbra, vecrow, Tr, dmat, Order
#set par(leading: 0.55em, justify: true, linebreaks: "optimized")
#set text(font: "New Computer Modern", lang: "en")
#set heading(numbering: "1. ")
#show par: set block(spacing: 1em)
#show raw: set text(font: "Courier New", size: 11pt)
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt
)
#show heading.where(level: 1): it => {
pagebreak(weak: true)
it
}
#let ubs(x) = $upright(bold(sans(#x)))$
#outline(
indent: auto
)
#pagebreak(weak: true)
= Qubits
A classical computer operates on strings of 0s and 1s. Each bit can be in one (and only one) of the two states.
The two single-qubit states can be represented using two *orthogonal#footnote[their dot product is 0, i.e. $sum_(i = 0)^(n) x_i y_i = 0$] unit#footnote[a vector with all compoents equal to 0 except one which is equal to 1] vectors* in a 2-dimentional vector space:
$
ket(0) = vec(1, 0) quad ket(1) = vec(0, 1)
$
Two-qubit states can be written as a *tensor product* of single-qubit states:
$
ket(00) = ket(0) times.circle ket(0) = vec(1 dot vec(1, 0), 0 dot vec(1, 0)) = vec(1, 0, 0, 0) quad quad ket(01) = ket(0) times.circle ket(1) = vec(1 dot vec(0, 1), 0 dot vec(0, 1)) = vec(0, 1, 0, 0) \
ket(10) = ket(1) times.circle ket(0) = vec(0 dot vec(1, 0), 1 dot vec(1, 0)) = vec(0, 0, 1, 0) quad quad ket(11) = ket(1) times.circle ket(1) = vec(0 dot vec(0, 1), 1 dot vec(0, 1)) = vec(0, 0, 0, 1)
$
In general, an $n$-qubit state can be represented by a unit $2^n$-component vector:
#figure(
$
ket(5)_3 = ket(101) = vec(0 dot vec(1 dot vec(0, 1), 0 dot vec(0, 1)), 1 dot vec(1 dot vec(0, 1), 0 dot vec(0, 1))) = vec(0 dot vec(0, 1, 0, 0), 1 dot vec(0, 1, 0, 0)) = vec(0, 0, 0, 0, 0, 1, 0, 0)
$,
kind: "equation",
supplement: "Equation",
caption: [Vector representation of $ket(5)_3$]
)
== Quantum gates and reversible operations
In classical computing, ${and, not}$ is a *universal set* of operators: any binary operation can be written as a combination of these two operators.
The $and$ operator is not *reversible* in the general case: if $a and b = 0$, the state of $a$ and $b$ cannot be determined by just looking at the result. \
The $not$ operator instead it's reversible. In particular, is its own inverse:
$
not(not a) = a
$
#highlight(fill: yellow)[In quantum computing all gates are reversible], except for the special measurement gate.
All quantum gates can be represented by a *unitary* square matrix with complex coefficients.
In quantum physics, an *invertible* square matrix is said to be unitary if its inverse $U^(-1)$ is equal to its *Hermitian adjoint* $U^dagger$. $U^dagger$ is obtained from $U$ by first trasposing it and then applying the *complex conjugate*#footnote[for a complex number $a + i b$, its complex conjugate is $a - i b$] to each coefficient.
If $U$ is unitary, and therefore $U^(-1) = U^dagger$, it follows that $U U^dagger = U^dagger U = I$, where $I$ is the identity matrix.
=== Single-qubit gates
These gates acts on a *single* qubit at a time.
==== NOT gate
Flips the state of the qubit it acts on:
$
ubs(X)ket(0) = ket(1) quad quad ubs(X)ket(1) = ket(0) quad quad ubs(X) = mat(0, 1; 1, 0)
$
==== Identity gate
It's the equivalent of the *identity matrix*:
$
ubs(1)ket(0) = ket(0) quad quad ubs(1)ket(1) = ket(1) quad quad ubs(1) = mat(1, 0; 0, 1)
$
=== 2-qubit gates
These gates acts on 2 qubits at a time. The first is the *control* qubit, which determines what action occur on the second qubit (the *target* qubit).
==== SWAP gate
Swaps the control with the target qubit:
$
ubs(S)_10 ket(x y) = ubs(S)_01 ket(x y) = ket(y x) quad quad ubs(S)_10 = ubs(S)_01 = mat(1, 0, 0, 0; 0, 0, 1, 0; 0, 1, 0, 0; 0, 0, 0, 1)
$
==== CNOT gate
Flips the state of the target qubit only if the control qubit is in state $ket(1)$:
$
ubs(C)_10 ket(x y) = ket(x)ket(y plus.circle x) quad quad ubs(C)_01 ket(x y) = ket(x plus.circle y)ket(y) quad quad ubs(C)_10 = mat(1, 0, 0, 0; 0, 1, 0, 0; 0, 0, 0, 1; 0, 0, 1, 0)
$
=== Number operator
This operator (which is not a gate) is the *projector operator* onto the state $ket(1)$#footnote[i.e. it counts the number of 1s in the quantum state]:
$
ubs(n)ket(x) = x ket(x) quad quad x in {0, 1} quad quad ubs(n) = mat(0, 0; 0, 1)
$
The complementary operator $tilde(ubs(n))$ instead is the projector operator onto the state $ket(0)$#footnote[i.e. it counts the number of 0s in the quantum state]:
$
tilde(ubs(n)) = ubs(1) - ubs(n) quad quad tilde(ubs(n)) = mat(1, 0; 0, 0)
$
=== $ubs(Z)$ operator
This operator has no counterpart in classical computation. It can be defined out of $ubs(n)$ and $tilde(ubs(n))$ operators:
$
ubs(Z) = tilde(ubs(n)) - ubs(n) = mat(1, 0; 0, -1)
$
This operator adds a phase to the state $ket(1)$.
$ubs(Z)$ anticommutes with $ubs(X)$, i.e. $ubs(Z X) = -ubs(X Z)$.
=== Pauli gates
The set of operators ${ubs(X), ubs(Y), ubs(Z)}$ are called *Pauli gates*, with $ubs(Y)$ defined as
$
ubs(Y) = mat(0, -i; i, 0)
$
When squared, all these operators are equal to the identity:
$
ubs(X)^2 = ubs(Y)^2 = ubs(Z)^2 = ubs(1)
$
Also, they anticommute in pairs:
$
ubs(X Y) = -ubs(Y X) = i ubs(Z) quad quad ubs(Y Z) = - ubs(Z Y) = i ubs(X) quad quad ubs(Z X) = -ubs(X Z) = i ubs(Y)
$
=== Hadamard gate
This is another quantum gate which does not have a counterpart in classical computation:
$
ubs(H) = 1/sqrt(2)(ubs(X) + ubs(Z)) = 1/sqrt(2)mat(1, 1; 1, -1)
$
$ubs(H)$ is able to set the qubit in a *linear superposition* of $ket(0)$ and $ket(1)$:
$
ubs(H)ket(0) = 1/sqrt(2)(ket(0) + ket(1)) = ket(+) quad quad ubs(H)ket(1) = 1/sqrt(2)(ket(0) - ket(1)) = ket(-)
$
$ubs(H)$ exibits some properties from its definition:
$
ubs(H)^2 = 1 quad quad ubs(H X H) = ubs(Z) quad quad ubs(H Z H) = ubs(X)
$
#highlight(fill: yellow)[These properties are used a lot when building quantum circuits].
$ubs(H)$ is also able to exchange the role of control and target qubit of a `CNOT` gate:
$
ubs(C)_(j i) = (ubs(H)_i ubs(H)_j)ubs(C)_(i j)(ubs(H)_i ubs(H)_j)
$
== Qubits and their states
The state $ket(psi)$ associated with a qubit can be any unit vector in the 2-dimensional vector space spanned by $ket(0)$ and $ket(1)$ over the complex numbers.
The general form of a qubit is:
$
ket(psi) = alpha_0 ket(0) + alpha_1 ket(1) = vec(alpha_0, alpha_1) quad quad alpha_0, alpha_1 in CC
$
Since $ket(psi)$ must be a *unit vector* in the complex vector space, coefficients $alpha_0$ and $alpha_1$ must satisfy the *normalization condition*:
$
|alpha_0|^2 + |alpha_1|^2 = 1
$
If this is not true, the state $ket(psi)$ does not represent the state of a qubit.
#pagebreak(weak: true)
The normalization condition can also be expressed using the bra-ket notation:
$
& braket(psi) = 1 \
=> & (alpha_0^*bra(0) + alpha_1^*bra(1))(alpha_0ket(0) + alpha_1ket(1)) = 1 \
=> & underbrace(alpha_0^*alpha_0, |alpha_0|^2)underbrace(braket(0), 1) + alpha_0^*alpha_1 underbrace(braket(0, 1), 0) + alpha_1^*alpha_0 underbrace(braket(1, 0), 0) + underbrace(alpha_1^*alpha_1, |alpha_1|^2)underbrace(braket(1), 1) = 1 \
=> & |alpha_0|^2 + |alpha_1|^2 = 1
$
where $alpha_i^*$ is the *complex conjugate* of $alpha_i$ and $braket(0, 1) = braket(1, 0) = 0$ because $ket(0)$ and $ket(1)$ are orthogonal.
Since $alpha_0, alpha_1 in bb(C)$, we can say that in a single qubit there are 4 _degrees of freedom_, one for each real number#footnote[for a complex number $z = a + i b$ there are 2 real numbers, $a$ and $b$]. This condition fixes one of them, so we are left with 3 degrees of freedom.
=== Normalization and phase of a complex number
The same complex number $z$ can be represented in two equivalent forms:
#figure(
table(
columns: (auto, auto, auto),
align: (left + horizon, center + horizon, left + horizon),
[*cartesian representation*], [$ z = a + i b $], [$a$ is the *real part* and $b$ is the *imaginary part*],
[*polar representation*], [$ z = r e^(i phi) $], [$r$ is the *magnitue* and $phi$ is the *phase*]
),
caption: [Cartesian and polar representation of a complex number $z$]
)
One can switch easily between these two representation thanks to the *Euler's formula*:
#figure(
table(
columns: (auto, auto),
align: (center + horizon, center + horizon),
[cartesian $-->$ polar], [polar $-->$ cartesian],
[$ r = sqrt(a^2 + b^2) \ phi = arccos(a / r) = arcsin(b / r) $], [$ a = r cos phi \ b = r sin phi $]
),
caption: [Switch between complex number representations]
)
Therefore $ket(psi)$ can be written also using polar coordinates:
$
alpha_0ket(0) + alpha_1ket(1) <=> r_0 e^(i phi_0)ket(0) + r_1 e^(i phi_1)ket(1)
$
When computing the modulus of a complex number the phase is irrelevant:
$
|alpha|^2 = alpha^* alpha = r e^(-i phi)r e^(i phi) = r^2(cancel(e^(-i phi + i phi))) = r^2
$
so the normalization condition, expressed using polar coordinates, becomes:
$
r_0^2 + r_1^2 = 1
$
This means that if two quantum states $ket(psi_1), ket(psi_2)$ differ only by their phase component then they are representing the *same qubit*. In other words, #highlight(fill: yellow)[the *global* phase of a quantum state is irrelevant] and can be collected:
$
r_0 e^(i phi_0)ket(0) + r_1 e^(i phi_1)ket(1) = e^(i phi_1)(r_0 e^(i(phi_0 - phi_1))ket(0) + r_1 ket(1))
$
#highlight(fill: yellow)[However, the *local* phase of a quantum state (i.e. the phase of the *single* component) cannot be ignored].
#pagebreak(weak: true)
== Measurement and Born rule
A qubit can be in any linear superposition of $ket(0)$ and $ket(1)$, but when *measured* the outcome is either 0 or 1. There is no way to get the amplitudes $alpha_0, alpha_1$ from a measurement and therefore #highlight(fill: yellow)[there is no way to know the *state* of a qubit].
The string of 0s and 1s obtained by measurement is not determined by the quantum state $ket(psi)$. Instead, the state determines only the *probabilities* of the possible outcomes.
#table(
columns: (1fr),
[
*Born rule*: for an $n$-qubit state $ket(Psi)_n = sum_(i <= n < 2^n)a_x ket(x)_n$, the *probability* that the outcome of a measurement is the binary expansion of $x$ is given by:
$
p(x) = |alpha_x|^2
$
]
)
Example: for the single-qubit state $ket(psi) = alpha_0 ket(0) + alpha_1 ket(1)$, the probability of getting `1` from the measurement is $|alpha_1|^2$.
Born rule explains why the quantum state must be normalized in order to represent a qubit: the sum of the probabilities of all possible outcomes must be exactly 1.
Born rule has also another part: #highlight(fill: yellow)[measurement *changes* the state of the quantum system]. After the measurement, the only state that remains is the one obtained from the measurement. In order words, #highlight(fill: yellow)[the system *collapses* on the state obtained from the measurement].
#figure(
image("assets/5b35c9f58eda95fc205928592948f6a2.png", width: 50%),
caption: [After measurement, state $ket(psi)$ collapses to state $ket(x)$ with a probability of $|alpha_x|^2$]
)
However, if measurement of quantum state $ket(psi)$ returns $x$, it does not mean that the state of the quantum system was $ket(x)$. In general, #highlight(fill: yellow)[we can't say in which state the quantum system was before the measurement].
#highlight(fill: yellow)[The probabilistic nature of quantum physics comes from the *ignorance of the observer*], because we don't know the state of the system. However, #highlight(fill: yellow)[for the system itself its state is deterministic].
=== Measurement and relative phases
Relative phases are really relevant, but they cannot be inferred by a simple measurement, i.e. they are not *observable*.
These two states represent the *same qubit*:
$
ket(psi_0) = ubs(H)ket(0) = 1/sqrt(2)(ket(0) + ket(1)) quad quad ket(psi_1) = ubs(H)ket(1) = 1/sqrt(2)(ket(0) - ket(1))
$
Indeed, the probability of getting 0 or 1 from a measurement is the same for both $ket(psi_0)$ and $ket(psi_1)$:
$
p_0(0) = (1/sqrt(2))^2 = 1/2 quad quad p_0(1) = (1/sqrt(2))^2 = 1/2 \
p_1(0) = (1/sqrt(2))^2 = 1/2 quad quad p_1(1) = (-1/sqrt(2))^2 = 1/2
$
However, even though $ket(psi_0)$ and $ket(psi_1)$ represent the same qubit, they are not equal to each other.
#pagebreak(weak: true)
== Quantum entanglement
#table(
columns: (1fr),
[
*Quantum entanglement*: the quantum state $ket(psi_(A B))$ of two qubits $A$ and $B$ is *entangled* if $ket(psi_(A B))$ cannot be factorized in the product of two single-qubit states $ket(psi_A)$ and $ket(psi_B)$ such that $ket(psi_(A B)) = ket(psi_A) times.circle ket(psi_B)$.
]
)
#figure(
table(
columns: (auto, auto, auto),
align: (center + horizon, center + horizon, center + horizon),
[*state*], [*is entangled?*], [*factorization*],
[$ ket(Psi_1) = frac(1, sqrt(2))(ket(00) + ket(01)) $], [no], [$ ket(Psi_1) = frac(1, sqrt(2))[ket(0) times.circle (ket(0) + ket(1))] $],
[$ ket(Psi_2) = frac(1, sqrt(2))(ket(00) + ket(11)) $], [yes], [N/A]
),
caption: [Examples of an entangled and non-entangled state]
)
Entanglement is a property of a quantum state, not of a quantum system.
Entanglement is fundamental for quantum information processing.
In an entangled 2-qubit state, the state of one qubit depends on the state of the other.
Entanglement cannot be revealed by measurement.
=== Check if a 2-qubit state is entangled
We can check explicitly if a 2-qubit state is entangled by solving a system of equations.
Example:
$
ket(Psi_1) = 1/sqrt(2)(ket(00) + ket(01)) quad quad ket(Psi_2) = 1/sqrt(2)(ket(00) + ket(11))
$
If these states are not entangled, a tuple of coefficients $vecrow(a_i, b_i, c_i, d_i)$ must exists so that $ket(Psi)_i$ can be rewritten as
$
ket(Psi_i) = (a_i ket(0) + b_i ket(1))(c_i ket(0) + d_i ket(1))
$
For $ket(Psi_1)$ such tuple does exist, because this system has a solution:
$
cases(
a_1 c_1 = 1,
a_1 d_1 = 1,
b_1 c_1 = 0,
b_1 d_1 = 0
)
$
What is the solution of this system is not relevant. What is relevant is that a solution does exist, therefore $ket(Psi_1)$ is not entangled.
However, for $ket(Psi_2)$ the system does not have any solution:
$
cases(
a_2 c_2 = 1,
a_2 d_2 = 0,
b_2 c_2 = 0,
b_2 d_2 = 1
)
$
therefore $ket(Psi_2)$ is entangled.
Quantum entanglement is one of the most unintuitive concept of quantum physics. From a classical point of view, the state of a car for example can be represented by its position and its velocity. If this (classical) system is splitted in two parts, the state of each subsystem is very well defined. This is not true instead for a quantum system if it's entangled.
Entanglement is bidirectional: if system $A$ is entangled with system $B$, then $B$ is entangled with $A$ too.
=== Entanglement and generalized Born rule
The generalized Born rule says that for an $n$-qubit system, we get the *same result* if we either:
- measure *all* of the $n$-qubits of our state;
- measure *a subset* of the $n$-qubits of our state
#highlight(fill: yellow)[The order in which we perform our measurements does not change the result].
In the generalized version, instead of measuring the state as a whole we measure only a *subset* of the system.
A general state of $n$-qubit can be written as $ket(Psi)_n = sum_x c_x ket(x)_n$. An $n + m$-qubit state can be written in the same way:
$
ket(Psi)_(m + n) = sum_(x, y)a_(x y)ket(x)_m ket(y)_n
$
If one measures only the $m$ qubits forming the $ket(x)_m$ part of the state, the result will be a specific $ket(overline(x))$ with a probability of:
$
p(tilde(x)) = sum_y |a_(tilde(x) y)|^2
$
and the system will collapse in the state $ket(tilde(x))ket(Phi)_n$, with $ket(Phi)_n$ defined as
$
ket(Phi)_n = frac(1, sqrt(p(x)))sum_y a_(tilde(x) y)ket(y)_n
$
= The general computational process
Let's suppose we have an arbitrary function $f$ which takes $n$-qubit in input and gives $m$-qubit as a result. This $f$ is arbitrary and it may not be reversible. How can we compute $f$ on an arbitrary quantum bit state?
Solution: we define a quantum gate $ubs(U)_f$:
$
ubs(U)_f (ket(x)_n ket(y)_n) = ket(x)_n ket(y plus.circle f(x))_m
$
where $ket(x)$ is the *input register* and $ket(y)$ is the *output register*. The input register is not changed by $ubs(U)_f$.
#figure(
image("assets/450d22040f112b614a3935447740493d.png", width: 30%),
caption: [Logical representation of $ubs(U)_f$]
)
$ubs(U)_f$ is reversible, and in particular is its own inverse:
$
ubs(U)_f ubs(U)_f (ket(x) ket(y)) = ubs(U)_f (ket(x) ket(y plus.circle f(x))) = ket(x) ket(y plus.circle f(x) plus.circle f(x)) = ket(x)ket(y)
$
== Quantum parallelism
If we have an $n$-qubit register and we apply an Hadamard gate on each of these qubits, what we obtain is an *equally weighted linear superposition* of all possible $n$-qubit states:
$
ubs(H)^(times.circle n)ket(0)_n = 1/sqrt(2^n)sum_(0 <= x < 2^n)ket(x)_n
$
By linearity of quantum physics, if we then apply $ubs(U)_f$ to this superposition we get
$
ubs(U)_f (ubs(H)^(times.circle n) times.circle ubs(1))(ket(0)_n ket(0)_m) = 1/sqrt(2^n)sum_(0 <= x < 2^n)ket(x)_n ket(f(x))_m
$
This final state contains the result of $2^n$ evaluations of $f$, by just a *single* execution of $ubs(U)_f$. This magic is called *quantum parallelism*.
However, we cannot exploit quantum parallelism in a trivial way, because when we measure the final state, even though it represents the result of all $2*n$ evaluations of $f$, we get a single (and random) result.
Not all algorithms benefits from quantum processing because of its *probabilistic nature*. If we are interested in *all* of $2^n$ outputs of $f(x)$, then we must use the classical approach (i.e. executing $f$ $2^n$ times). However, if we are interested in other aspects of the problem, quantum processing may provide an enourmus speedup compared to classical processing.
= No cloning theorem
#table(
columns: (1fr),
[
*No cloning theorem*: there is no unitary transformation $ubs(U)_f$ that can take the state $ket(psi)_n ket(0)_n$ into the state $ket(psi)_n ket(psi)_n$ for an arbitrary $ket(psi)_n$.
]
)
In other words, this theorem says that we cannot *copy* the input register into the output register, i.e. *cloning* $ket(psi)_n$.
== Proof
Let's suppose by absurd that such $ubs(U)$ exists. Therefore for tho states $ket(psi), ket(phi.alt)$ we have:
$
ubs(U)(ket(psi)ket(0)) = ket(psi)ket(psi) quad quad ubs(U)(ket(phi.alt)ket(0)) = ket(phi.alt)ket(phi.alt)
$
Since $ubs(U)$ can clone any input, it can also clone any linear superposition of $ket(psi)$ and $ket(phi.alt)$:
$
ubs(U)[(a ket(psi) + b ket(phi.alt))ket(0)] & = (a ket(psi) + b ket(phi.alt))(a ket(psi) + b ket(phi.alt)) \
& = a^2 ket(psi)ket(psi) + a b ket(psi)ket(phi.alt) + a b ket(phi.alt)ket(psi) + b^2 ket(phi.alt)ket(phi.alt)
$
but this result is in constract with the *linearity of quantum physics*:
$
ubs(U)[(a ket(psi) + b ket(phi.alt))ket(0)] & = a ubs(U)ket(psi)ket(0) + b ubs(U)ket(phi.alt)ket(0) \
& = a ket(psi)ket(psi) + b ket(phi.alt)ket(phi.alt)
$
This result is different from the one above unless either $a = 1$ and $b = 0$ or viceversa, therefore such $ubs(U)$ cannot exist.
== No cloning theorem for approximations
#table(
columns: (1fr),
[
*No cloning theorem* (for approximation): there is no unitary transformation $ubs(U)$ that can take the state $ket(psi)_n ket(0)_n$ into a state $ket(psi)_n ket(psi)_n$ such that $ubs(U)(ket(psi)_n ket(0)_n) approx ket(psi)_n ket(psi)_n$.
]
)
=== Proof
Let's suppose by absurd that such $ubs(U)$ exists, so:
$
ubs(U)(ket(psi)ket(0)) approx ket(psi)ket(psi) quad quad ubs(U)(ket(phi.alt)ket(0)) approx ket(phi.alt)ket(phi.alt)
$
$ubs(U)$ is *unitary* by hypothesis, so it preserves the *scalar product* $braket(phi.alt, psi)$. In other words, this condition must be verified for $ubs(U)$ to exist:
$
& braket(phi.alt, braket(0, psi), 0) approx braket(phi.alt, braket(phi.alt, psi), psi) \
=> & braket(phi.alt, psi)braket(0) approx braket(phi.alt, psi)braket(phi.alt, psi)
$
The state must be normalized, so $braket(0) = 1$, which laves:
$
braket(phi.alt, psi) = (braket(phi.alt, psi))^2
$
which is not true in the general case, but only in two cases:
+ $braket(phi.alt, psi) = 0$, which means that $ket(psi)$ and $ket(phi.alt)$ are nearly *orthogonal* (which is true only for $ket(0)$ and $ket(1)$);
+ $braket(phi.alt, psi) = 1$, which means that $phi.alt = psi$, i.e. that we had to have 2 states which were already the same *before* cloning them
Therefore, since a *general* state $ket(psi)$ cannot be cloned even with an approximation error, such $ubs(U)$ does not exist.
= Spooky action at a distance
Let's consider the *Hardy state*:
$
ket(Phi) & = frac(1, sqrt(12))(3ket(00) + ket(01) + ket(10) - ket(11)) \
& = 1/sqrt(3)(2ket(00) - ubs(H)_a ubs(H)_b ket(11))
$
If Alice and Bob measure their qubit now, the probability of both getting a `1` is $(-1/sqrt(12))^2$. In particular, this probability is $!= 0$.
But if both Alice and Bob apply an Hadamard *before* measuring their qubit, the probability of both getting `1` is $= 0$:
$
ubs(H)_a ubs(H)_b ket(Phi) & = 1/sqrt(3)(2ubs(H)_a ubs(H)_b ket(00) + cancel(ubs(H)_a^2)cancel(ubs(H)_b^2)ket(11)) \
& = frac(1, sqrt(3))(ket(00) + ket(01) + ket(10) + cancel(ket(11)) - cancel(ket(11)))
$
This can be easily spotted from the expression above: the state $ket(11)$ does not exist anymore.
If only Alice applies an Hadamard before the measurement, this will remove the outcome `01` from the possible results:
$
ubs(H)_a ket(Phi) = 1/sqrt(3)(2ubs(H)_a ket(00) - ubs(H)_b ket(11))
$
Since $ubs(H)_a ket(00)$ is a linear combination of $ket(00)$ and $ket(11)$ and $ubs(H)_b ket(11)$ is a linear combination of $ket(10)$ and $ket(11)$, the state $ket(01)$ does not appear in the expansion of $ubs(H)_a ket(Phi)$.
#highlight(fill: yellow)[The spooky part about this is that by applying an Hadamard on her qubit, Alice has also affected the possible outcomes for Bob], even though she hasn't touched its qubit. This is because of Alice and Bob qubits are entangled.
The same spooky action happens if only Bob applies an Hadamard to his qubit. This will remove the outcome `10`:
$
ubs(H)_b ket(Phi) = 1/sqrt(3)(2ubs(H)_b ket(00) - ubs(H)_a ket(11))
$
#figure(
image("assets/c46bef02628528cb1d56757307d19584.png", height: 15%),
caption: [Summary of possible outcomes]
)
This set of possible outcomes is inconsistent with classical physics. It's only valid for quantum physics.
#highlight(fill: yellow)[This is also an alternative experiment that evaluates the truth of *Bell's inequality*].
= Deutsch's problem
Let's consider a function $f : {0, 1} |-> {0, 1}$. There can be only 4 of these functions:
#figure(
table(
columns: (auto, auto, auto),
[], [$ x = 0 $], [$ x = 1 $],
[$ f_0 $], [$ f(x) = 0 $], [$ f(x) = 0 $],
[$ f_1 $], [$ f(x) = 0 $], [$ f(x) = 1 $],
[$ f_2 $], [$ f(x) = 1 $], [$ f(x) = 0 $],
[$ f_3 $], [$ f(x) = 1 $], [$ f(x) = 1 $]
),
caption: [All possible $f_i$]
)
We can represent the quantum transformation that applies $f$ in the usual way:
$
ubs(U)_f (ket(x)ket(y)) = ket(x)ket(y plus.circle f(x))
$
Assuming that the input register is initialized to $ket(0)$, there are 4 distinct $ubs(U)_f_i$ (one for each $f_i$):
+ $ubs(U)_f_1 = ubs(1)$ because the output register is left to $ket(0)$ for both inputs $ket(0)$ and $ket(1)$;
+ $ubs(U)_f_1 = ubs(C)_(10)$ because it changes the output register to $ket(1)$ only if the input register (used as the control qubit) is $ket(1)$;
+ $ubs(U)_f_2 = ubs(C)_(10)ubs(X)_0$ because it's simply the previous case with a NOT gate applied;
+ $ubs(U)_f_3 = ubs(X)_1$ because the output register is set to $ket(1)$ regardless of the input register
We assume that we have a *black box* that implements one of those $f_i$, but we don't know which one of them. Our goal is to determine if the $f_i$ inside the black box is *constant* or not.
With a classical approach we would need 2 evaluations of $f$ to determine this. Instead, with a quantum approach we can determine this with just a *single* evaluation of $f$.
However, it must be said that with a classical approach we would also know exactly *which* of those 4 $f$ is inside the black box. The quantum approach cannot tell us this, but it can tell us if the function is one of ${f_0, f_3}$ (constant) or of ${f_1, f_2}$ (not constant).
== Proof
Let's start with the state $(ubs(X) times.circle ubs(X))(ket(0)ket(0)) = ket(1)ket(1)$. We then apply an Hadamard gate on each qubit:
$
(ubs(H) times.circle ubs(H))(ket(1)ket(1)) & = 1/2(ket(0) - ket(1))(ket(0) - ket(1)) \
& = 1/2(ket(00) - ket(01) - ket(10) + ket(11))
$
This state is *not entangled*. This fact can be spotted by two things:
+ the state is clearly separable (look at the first expression);
+ we started from a non-entangled state and we have used only single-qubit gates. There was no interaction between the two qubits, therefore there cannot be any entanglement
If now we apply $ubs(U)_f$ to this state, by *linearity* we get:
$
1/2[ubs(U)_f (ket(0)ket(0)) - ubs(U)_f (ket(0)ket(1)) - ubs(U)_f (ket(1)ket(0)) + ubs(U)_f (ket(1)ket(1))]
$
Now we apply $ubs(U)_f$ and rewrite the expression explicitly:
$
1/2(ket(0)ket(0 plus.circle f(0)) - ket(0)ket(1 plus.circle f(0)) - ket(1)ket(0 plus.circle f(1)) + ket(1)ket(1 plus.circle f(1)))
$
and then we rename $tilde(f)(x) = ket(1 plus.circle f(x))$:
$
1/2(ket(0)ket(f(0)) - ket(0)ket(tilde(f)(0)) - ket(1)ket(f(1)) + ket(1)ket(tilde(f)(1)))
$
Now, if $f$ is constant, then $f(0) = f(1)$, so we can collect either $f(0)$ or $f(1)$:
$
1/2(ket(0) - ket(1))(ket(f(0)) - ket(tilde(f)(0))) quad quad f(0) = f(1) <=> tilde(f)(0) = tilde(f)(1)
$
If instead $f$ is not constant and then $f(0) != f(1)$, we can still collect something because in this case $f(0) = tilde(f)(1)$:
$
1/2(ket(0) + ket(1))(ket(f(0)) - ket(tilde(f)(0))) quad quad f(0) != f(1) <=> f(0) = tilde(f)(1)
$
These two states are very similar. Indeed, the only difference is the sign. This difference however cannot be detected by a measurement, so we apply again an Hadamard on the input register in order to make these states clearly different:
$
frac(1, 2)[ubs(H)(ket(0) - ket(1))](ket(f(0)) - ket(tilde(f)(0))) --> ket(1)frac(1, sqrt(2))(ket(f(0)) - ket(tilde(f)(0))) quad quad f(0) = f(1) \
frac(1, 2)[ubs(H)(ket(0) + ket(1))](ket(f(0)) - ket(tilde(f)(0))) --> ket(0)frac(1, sqrt(2))(ket(f(0)) - ket(tilde(f)(0))) quad quad f(0) = tilde(f)(1)
$
If we now measure the *input* register and we get a $ket(0)$, then $f(0) = tilde(f)(1)$ (i.e. $f$ is not constant), instead if we get $ket(1)$ then $f(0) = f(1)$ (i.e. $f$ is constant).
Note that $ubs(U)_f$ has created entanglement. This is why we can get either $ket(0)$ or $ket(1)$ from the measurement even though we started from a non-entangled state $ket(1)$ on the input register.
To sumarize, this is the full chain of operations we have performed, starting from state $ket(0)ket(0)$:
$
(ubs(H) times.circle ubs(1))ubs(U)_f (ubs(H) times.circle ubs(H))(ubs(X) times.circle ubs(X))(ket(0)ket(0)) = cases(
ket(1)frac(1, sqrt(2))(ket(f(0)) - ket(tilde(f)(0))) "if" f(0) = f(1),
ket(0)frac(1, sqrt(2))(ket(f(0)) - ket(tilde(f)(0))) "if" f(0) = tilde(f)(1)
)
$
== Circuit representation
#figure(
image("assets/c91fa2e59aad4b1f670c837d0fa36f2f.png", height: 22%),
caption: [Circuit for the 4 $ubs(U)_f_i$]
)
#pagebreak(weak: true)
To solve the Deutch's problem we simply need to add a pair of Hadamard both before and after the processing:
#figure(
image("assets/4ab06afeae03bea562a90e98d315f955.png", height: 22%),
caption: [Circuit which solves the Deutsch's problem]
)
We have used these identities:
#figure(
image("assets/2a74dbe72a1dd0099fe9ac54e03333c1.png", width: 50%),
caption: [Identities used to build the circuit which solves the Deutsch's problem. The circuit on the left is *equivalent* to the circuit on the right.]
)
#pagebreak(weak: true)
= How to build the Hardy state
$
ket(Phi) = frac(1, sqrt(12))(3ket(00) + ket(01) + ket(10) - ket(11)) = frac(1, sqrt(12))[ket(0)(3ket(0) + ket(1)) + ket(1)(ket(0) - ket(1))]
$
We want to build this state starting from $ket(00)$.
We will start with qubit 1 (i.e. the left-most qubit), which have this probability distribution:
$
p_1(0) = frac(|3|^2 + |1|^2, 12) = 10/12 quad quad p_1(1) = frac(|1|^2 + |-1|^2, 12) = 2/12
$
To get these probabilities from $ket(0)$ we need a unitary transformation $ubs(U)$ such that
$
ubs(U)ket(0) = frac(1, sqrt(12))(sqrt(10)ket(0) + sqrt(2)ket(1))
$
To find this $ubs(U)$, we first consider its general form:
$
ubs(U)(theta, phi.alt, lambda) = mat(
cos(frac(theta, 2)), -e^(i lambda)sin(frac(theta, 2));
e^(i phi.alt)sin(frac(theta, 2)), e^(i(phi.alt + 1))cos(frac(theta, 2))
)
$
We can find our $ubs(U)$ by finding the values of $theta, phi.alt$ and $lambda$.
Since our target state $ubs(U)ket(0)$ does not have any phase (all coefficients are real), we can put $phi.alt = lambda = 0$ and focus only on $theta$. We need to solve this equation in order to find its value:
$
mat(cos(frac(theta, 2)), -sin(frac(theta, 2)); sin(frac(theta, 2)), cos(frac(theta, 2)))vec(1, 0) = frac(1, sqrt(12))(sqrt(10)vec(1, 0) + sqrt(2)vec(0, 1))
$
This equation is solved for $theta = 0.8410$, so the $ubs(U)$ we want is:
$
ubs(U)(0.8410, 0, 0) = mat(cos(0.8410 / 2), -sin(0.8410 / 2); sin(0.8410 / 2), cos(0.8410 / 2)) = frac(1, sqrt(12)) mat(sqrt(10), -sqrt(2); sqrt(2), sqrt(10))
$
This $ubs(U)$ is the quantum gate we want for our *first* qubit. But we also need to handle the *second* qubit (the Hardy state is a 2-qubit state), so we need to find another unitary transformation $ubs(V)$.
Steps here are more complex, since the two qubits are *entangled*. The quantum gate we want should produce this result when applied to the first qubit:
$
ubs(V)ket(0) = frac(1, sqrt(10))(3ket(0) + ket(1))
$
We can use the same procedure as before, i.e. we need to find for which $theta$ this equation is verified:
$
ubs(V)(theta, 0, 0)vec(1, 0) = sqrt(10)(3vec(1, 0) + vec(0, 1))
$
We set $phi.alt = lambda = 0$ also in this case because also in this case our target state $ubs(V)ket(0)$ does not have any phase.
This equation is solved for $theta = 0.6435$, which gives this matrix:
$
ubs(V)(0.6435, 0, 0) = frac(1, sqrt(10))mat(3, -1; 1, 3)
$
Now we combine $ubs(U)$ and $ubs(V)$ and see what these gates do on $ket(00)$:
$
ubs(U)_1 ubs(V)_0 ket(00) = frac(1, sqrt(12))[ket(0)(3 ket(0) + ket(1)) + ket(1)(3 ket(0) + ket(1))]
$
but we notice that this is not the Hardy state.
So wee need a third quantum gate $ubs(K)$ that should be a *controlled* gate, because it should act on qubit 0 only if qubit 1 is $ket(1)$.
The procedure is still the same. Our goal for the second qubit is the linear superposition $ket(0) - ket(1)$ (as is in the Hardy state), so we need to find the value of $theta$ that verifies this equation:
$
ubs(K)(theta, 0, 0)frac(1, sqrt(10))vec(3, 1) = frac(1, sqrt(2))vec(1, -1)
$
which is $theta = -2.2142$.
So we put all these gates together:
$
ubs(K)_10 ubs(U)_1 ubs(V)_0 ket(00) = frac(1, sqrt(12))[ket(0)(3ket(0) + ket(1)) + ket(1)(ket(0) - ket(1))]
$
and we get the Hardy state.
#pagebreak(weak: true)
= Bernstein-Vazirani problem
Let $a$ be a non negative $n$-bit number, which is our _secret key_. We also have a function $f : {0, 1}^n |-> {0, 1}$ that computes the *scalar product modulo 2* between $a$ and the input $x$:
$
f(x) = a dot x = a_0 x_0 plus.circle a_1 x_1 plus.circle ... plus.circle a_n x_n
$
Our goal is to find $a$, i.e. all the $n$ bits of which it is composed.
On a classical computer, we would need $n$ evaluations of $f$, one for each bit. For example, if $n = 3$:
$
f_a (001) = a_0 quad quad f_a (010) = a_1 quad quad f_a (100) = a_3 quad quad ==> a = (a_2, a_1, a_0)
$
With a quantum approach, we need just a *single* evaluation of $f$ to find $a$, regardless of how big $n$ is, so we switch from a computational cost linear to $n$ (classic approach) to a constant computational cost (quantum approach).
We prepare the output register in state $ubs(H)ket(1) = ubs(H)ubs(X)ket(0) = frac(1, sqrt(2))(ket(0) - ket(1))$.
Since $ubs(H)ket(0) = frac(1, sqrt(2))(ket(0) + ket(1))$ and $ubs(H)ket(1) = frac(1, sqrt(2))(ket(0) - ket(1))$, we can write the general single-qubit state obtained by applying an Hadamard in this way:
$
ubs(H)ket(x)_1 = frac(1, sqrt(2))(ket(0) + (-1)^x ket(1)) = frac(1, sqrt(2))sum_(y = 0)^(1)(-1)^(x y) ket(y)_1
$
Therefore the generalization of $ubs(H)$ for $n$-qubits can be written as
$
ubs(H)^(times.circle n)ket(x)_n = frac(1, sqrt(2^n))sum_(y = 0)^(2^n - 1)(-1)^(x y)ket(y)_n
$
Now, since $ubs(U)_f ket(x)ket(y) = ket(x)ket(y plus.circle x)$, i.e. $ubs(U)_f$ flips the output register only if the input register has value 1, we have:
$
ubs(U)_f ubs(H)_0 ubs(X)_0 ket(x)_n ket(0) = (-1)^(f(x))ket(x)_n frac(1, sqrt(2))(ket(0) - ket(1))
$
Now we apply again an Hadamard on each qubit of the input resiger:
$
(ubs(H)^(times.circle n) times.circle ubs(1))ubs(U)_f (ubs(H)^(times.circle n) times.circle ubs(H))ket(0)_n ket(1)_1 & = (ubs(H)^(times.circle n) times.circle ubs(1))ubs(U)_f (frac(1, sqrt(2^n)) sum_(x = 0)^(2^n - 1)ket(x))frac(1, sqrt(2))(ket(0) - ket(1)) \
& = frac(1, sqrt(2^n))(ubs(H)^(times.circle n)sum_(x = 0)^(2^n - 1)(-1)^(f(x))ket(x))frac(1, sqrt(2))(ket(0) - ket(1)) \
& = frac(1, 2^n)sum_(x = 0)^(2^n - 1)sum_(y = 0)^(2^n - 1)(-1)^(f(x) + x dot y)ket(y)frac(1, sqrt(2))(ket(0) - ket(1))
$
Now we use an identity to rewrite the sum over $x$:
$
sum_(x = 0)^(2^n - 1)(-1)^(a dot x)(-1)^(y dot x) = product_(j = 1)^(n)sum_(x_j = 0)^(1)(-1)^((a_j + y_j)x_j)
$
and then we notice that at least one term of the product vanishes unless each bit $y_j$ of $y$ is equal to each bit $a_j$ of $a$, i.e. unless $y = a$.
We can now get the value of $a$ by measuring the input register.
== Circuit representation
The Bernstein-Vazirani problem can be demonstrated also by using a circuit diagram.
#figure(
image("assets/24328cbc2160363c10e5a3ad9e77579c.png", width: 50%),
caption: [Circuit that implements $ubs(U)_f$ for $f(x) = a dot x$]
)
Each of the cNOT gates adds $1 mod 2$ to the output register if and only if $a_j x_j = 1$, therefore there are as many cNOT gates as bits equal to 1 in $a$.
We now add the Hadamards:
#figure(
image("assets/dbca55a67890d4be6e966b933d652e46.png", width: 50%),
caption: [Circuit for the Bernstein-Vazirani problem]
)
We can simplify this circuit by considering a property of the Hadamard gate that, when applied to both the control and the target qubit, it flips the role of control and target qubit of a CNOT:
$
(ubs(H)_i ubs(H)_j)ubs(C)_(i j)(ubs(H)_i ubs(H)_j) = ubs(C)_(j i)
$
#figure(
image("assets/e4551e8f2d35757089c5c3205e436796.png", width: 60%),
caption: [Circuit for the Bernstein-Vazirani problem (simplified)]
)
#pagebreak(weak: true)
= Building multi-qubit gates from 1- and 2-qubit gates: the Toffoli gate
The CNOT gate and a generica single-qubit gate form a *universal set* of quantum gates. Any quantum algorithm can be built entirely out of these gates.
Realizing hardware for quantum computers is really challenge. Currently, we are able to build single- and 2-qubit gates, but building 3- (or more) qubit gates is practically impossible.
The *Toffoli gate* is one example on how to build a 3-qubit gate out of 1- and 2-qubit gates:
$
ubs(T)ket(x)ket(y)ket(z) = ket(x)ket(y)ket(z plus.circle x y)
$
$ubs(T)$ is its own inverse, therefore it's a unitary quantum gate.
If $z = 0$, the Toffoli gate can be used to compute the logical AND of two qubits. Since AND and NOT gates are a universal set of classical gates, #highlight(fill: yellow)[the Toffoli gate represents a universal set of quantum gates].
We need 3 things to build the Toffoli gate out of 1- and 2-qubit gates:
+ a *controlled* $ubs(U)$ gate;
+ a 3-qubit doubly-controlled $ubs(U)^2$ gate;
+ the *square root of NOT gate*, $sqrt(ubs(X))$
We can build a controlled $ubs(U)$ from 2 arbitrary single-qubit gates $ubs(V), ubs(W)$ and the CNOT:
#figure(
image("assets/648202a1d5286108d053e141ef43dcf8.png", height: 8%),
caption: [Building of a controlled $ubs(U)$ from 2 single-qubit arbitrary gates $ubs(V), ubs(W)$. The last $ubs(E)$ gate is a *phase shift* gate.]
)
From this controlled $ubs(U)$ gate, a doubly-controlled $ubs(U)^2$ gate can be constructed by putting together:
- two controlled $ubs(U)$ gates;
- one controlled $ubs(U)^dagger$ gate;
- two CNOT gates
#figure(
image("assets/71c94f0b94048e48d6903856c751f389.png", height: 8%),
caption: [Doubly-controlled $ubs(U)^2$ gate]
)
If we now consider the $ubs(U)$ to be the square root of not $sqrt(ubs(X))$ gate, we obtain the Toffoli gate:
#figure(
image("assets/95a9e7a40a84c9dd917571bae5a1e243.png", height: 13%),
caption: [The Toffoli gate]
)
which actually is a controlled-controlled-NOT gate.
The $ubs(T)$ gate in the circuit above is a single-qubit gate that *rotates* the state by a factor $pi/4$.
The last circuit comes from the fact that $sqrt(ubs(X)) = ubs(H)sqrt(ubs(Z))ubs(H)$, because $ubs(X) = ubs(H Z H)$ and $ubs(H)^2 = ubs(1)$.
== Examples of multi-qubit gates
#figure(
image("assets/ed36f42cf0113b7faefe8213afdccec1.png", height: 13%),
caption: [A quantum half adder using 4 qubits]
)
#figure(
image("assets/8f6eaab83e4098c8c64d3d71946c27c0.png", height: 13%),
caption: [A quantum full adder using 5 qubits]
)
We can build a quantum full adder also with only 4 qubits, but we lose the difference between the input and the output register:
#figure(
image("assets/421dfc36bae98601c1eed7ee99f6a94c.png", height: 13%),
caption: [Quantum full adder using 4 qubits]
)
but the circuit is still reversible, so it is a quantum circuit.
#pagebreak(weak: true)
= V<NAME>umann entanglement entropy
#highlight(fill: yellow)[The state of a classical system is always defined]. The observer may not be aware of it, but still it's defined.
A classical system can be described using a single variable and an *array* of states. #highlight(fill: yellow)[A quantum system instead must be represented by a 1D array (not a single variable) and a *matrix* with the *probability distribution* of the states].
A quantum system is in a *pure* state if its state is represented by a well-defined state vector $ket(psi)$. In a classical system made of two subsystems, each subsystem is always in a specific state. For quantum systems, this holds only if the state is *separable* in two subsystems, i.e. if the quantum state is *not entangled*.
#table(
columns: (1fr),
[*Density matrix*: the density matrix $rho$ of a system in a pure state is defined as $rho = ket(psi)bra(psi)$.]
)
#figure(
table(
columns: (auto, auto),
align: (center + horizon, center + horizon),
[*state* $ket(psi)$], [*density matrix* $rho$],
[$ ket(psi_1) = ket(01) $], [$ rho = ket(01)bra(01) = vec(0, 1, 0, 0)mat(0, 1, 0, 0) = mat(0, 0, 0, 0; 0, 1, 0, 0; 0, 0, 0, 0; 0, 0, 0, 0) $],
[$ ket(psi_2) = frac(1, sqrt(2))(ket(00) + ket(11)) $], [$ rho = frac(1, 2)(ket(00) + ket(11))(bra(00) + bra(11)) = frac(1, 2)vec(1, 0, 0, 1)mat(1, 0, 0, 1) = frac(1, 2)mat(1, 0, 0, 1; 0, 0, 0, 0; 0, 0, 0, 0; 1, 0, 0, 1) $]
),
caption: [Examples of density matrices. $ket(psi_2)$ is entangled.]
)
#highlight(fill: yellow)[The *reduced* density matrix of a quantum system is the density matrix of only a part of the system]. For example, the reduced density matrix on subsystem $B$ is the $2 times 2$ matrix obtained from $rho$ by *tracing out* the degrees of freedom of subsystem $B$. This is done by applying a *partial trace operation* on the density matrix $rho$.
For a $4 times 4$ matrix, the partial trace operation is defined as:
$
Tr mat(
#text(fill: red)[a], b, #text(fill: blue)[c], d;
e, #text(fill: red)[f], g, #text(fill: blue)[h] ;
#text(fill: green)[i], j, #text(fill: purple)[k], l;
m, #text(fill: green)[n], o, #text(fill: purple)[p]
) = mat(
#text(fill: red)[a + f], #text(fill: blue)[c + h] ;
#text(fill: green)[i + n], #text(fill: purple)[k + p]
)
$
The *Von Neumann entropy* $S(gamma)$ of a density matrix $gamma$ is defined as:
$
S(gamma) = -Tr(gamma ln gamma)
$
This formula contains the *logarithm of a matrix*. In our case, since we deal only with *diagonal* matrices, the logarithm of a matrix is the same matrix with a logarithm applied to each of its coefficients:
$
ln dmat(a, b) = dmat(ln a, ln b)
$
The *degree of entanglement* $Epsilon_(A, B)(rho)$ between qubit $A$ and qubit $B$ can be computed as the Von Neumann entropy of the reduced density matrix:
$
Epsilon_(A, B)(rho) = S(rho_A) = -Tr(rho_A log_2 rho_A)
$
The basis of the $log$ is just a matter of normalization. In our case it's convenient to pick the basis 2 because in this way #highlight(fill: yellow)[the result can either be 0 (no entanglement at all), 1 (maximum entanglement possible) or something in between].\
In our case is also convenient to consider $log_2 0 = -infinity = 0$.
#highlight(fill: yellow)[The amount of entanglement is the amount of information one can get from a subsystem by measuring the other subsystem].
The amount of entanglement depends on the definition of the two subsystems. If the system is composed only of 2 qubits, there is a single way to split it in two subsystems (each subsystem is composed of just 1 qubit). If instead the system is composed of $>= 3$ qubits, there are $>= 2$ ways to split the system in two subsystems. #highlight(fill: yellow)[The amount of entanglement will likely be different for each different subdivision].
Example: let's reconsider state $ket(psi_2) = frac(1, sqrt(2))(ket(00) + ket(11))$:
#figure(
table(
columns: (auto, auto),
align: (center + horizon, center + horizon),
[*density matrix*], [*reduced density matrix*],
[$ rho = frac(1, 2)mat(1, 0, 0, 1; 0, 0, 0, 0; 0, 0, 0, 0; 1, 0, 0, 1) $], [$ rho_A & = frac(1, 2)mat(1 + 0, 0 + 0; 0 + 0, 0 + 1) = 1/2 mat(1, 0; 0, 1) $]
),
caption: [Density matrix and reduced density matrix for subsystem $A$ of state $ket(psi_2)$]
)
The Von Neumann entropy of $rho_A$ is:
$
Epsilon_(A, B)(rho) & = -Tr[1/2 mat(1, 0; 0, 1) log_2 frac(1, 2)mat(1, 0; 0, 1)] \
& = -Tr[mat(1/2, 0; 0, 1/2)mat(-1, 0; 0, -1)] = 1
$
So subsystems $A$ and $B$ have the maximum entanglement possible.
Let's now consider another entangled state $ket(psi_3) = frac(1, sqrt(5))(ket(00) + 2ket(11))$:
#figure(
table(
columns: (auto, auto),
align: (center + horizon, center + horizon),
[*density matrix*], [*reduced density matrix*],
[$ rho = frac(1, 5)mat(1, 0, 0, 2; 0, 0, 0, 0; 0, 0, 0, 0; 2, 0, 0, 4) $],
[$ rho_A = frac(1, 5)mat(1 + 0, 0 + 0; 0 + 0, 0 + 4) = 1/5 mat(1, 0; 0, 4) $]
),
caption: [Density matrix and reduced density matrix of $ket(psi_3)$]
)
The Von Neumann entropy of $rho_A$ is:
$
Epsilon_(A, B)(rho_A) & = -Tr[1/5 mat(1, 0; 0, 4)log_2 1/5 mat(1, 0; 0, 4)] = 0.722
$
therefore $A$ and $B$ are not partially entangled.
#pagebreak(weak: true)
= Simon's problem
Let's consider a function $f : {0, 1}^n |-> {0, 1}^n$ with an unknown *periodicity* $a$:
$
f(x) = f(y) <=> y = x plus.circle a
$
Our goal is to discover the period $a$.
== Classical approach
A classical approach requires multiple evaluations of $f$, each with a different input $x_i$ and storing each output $f(x_i)$. When one finds an input $x_j$ for which $f(x_j)$ has already been seen for some input $x_i$, then $a = x_i plus.circle x_j$.
The number of times $f$ needs to be evaluated grows *exponentially* with $n$, i.e. the computational cost is $Order(sqrt(2^n))$.
The cost of this algorithm is so high because after $m$ evaluations of $f$, if $a$ has not been found yet, we have ruled out only $1/2 m(m - 1)$ possibilites for $a$, which is a very small number if compared to the total number of possibilites for $a$ (which is $2^n - 1$).
== Quantum approach
A quantum computer can determine $a$ by running $f$ only about $n$ times (actually a little more, but still the cost is *linear*).
However, the algorithm changes its nature because it becomes a *probabilistic algorithm*: $a$ may not be found with a probability of 100%, but the chance of failing for this algorithm is $< 10^(-6)$.
As usual, the input register is prepared in a uniformly weighted superposition and the output register in the state $ket(0)$:
$
(ubs(H)^(times.circle n) times.circle ubs(1))ket(0)_n ket(0)_n = frac(1, sqrt(2^n))sum_(x = 0)^(2^n - 1)ket(x)ket(0)_n
$
Since the output register is initialized to $ket(0)_n$, when $ubs(U)_f$ is applied to this state the result is
$
ubs(U)_f ubs(H)^(times.circle n) ket(0)_n ket(0)_n = frac(1, sqrt(2^n))sum_(x = 0)^(2^n - 1)ket(x)ket(f(x))
$
$ubs(U)_f$ has entangled the input and the output register. If we now measure the output register, the input register collapses into this state:
$
frac(1, sqrt(2))(ket(x_0)_n + ket(x_0 plus.circle a)_n)
$
for some $x_0$. This is because the outcome of the measurement $f(x_0)$ is associated to two input values, which are indeed $x_0$ and $x_0 plus.circle a$, since $f$ is periodic.
#highlight(fill: yellow)[We can't measure the input register yet], because the possible outcomes $x_0$ and $x_0 plus.circle a$ would be indistinguishable for us, and therefore we would not be able to determine $a$.
So we apply another $ubs(H)^(times.circle n)$ to this state:
$
ubs(H)^(times.circle n)(ket(x_0) + ket(x_0 + a)) & = frac(1, sqrt(2^(n + 1)))sum_(y = 0)^(2^n - 1)[(-1)^(x_0 dot y) + (-1)^((x_0 plus.circle a) dot y)]ket(y) \
& = frac(1, sqrt(2^(n + 1)))sum_(y = 0)^(2^n - 1)[(-1)^(x_0 dot y) + (-1)^(x_0 dot y)(-1)^(a dot y)]ket(y)
$
From this we notice that the coefficient for $ket(y)$ is 0 if $a dot y = 1$, because in the sum we would have $(-1)^(x_0 dot y) - (-1)^(x_0 dot y)$. If instead $a dot y = 0$, the coefficient for $ket(y)$ is $2(-1)^(x_0 dot y)$.
So we can rewrite the expression above ignoring the cases of $a dot y = 1$:
$
ubs(H)^(times.circle n)(ket(x_0) + ket(x_0 + a)) & = frac(1, sqrt(2^(cancel(n + 1))))cancel(2)sum_(a dot y = 0)(-1)^(x_0 dot y)ket(y) \
& = frac(1, sqrt(2^(n - 1)))sum_(a dot y = 0)(-1)^(x_0 dot y)ket(y)
$
If we now measure the input register $ket(y)$ we get a random $y$ such that $a dot y = 0 <=> sum_(i = 0)^(n - 1)a_i y_i = 0$ (the equivalence applies because $a$ and $y$ are $n$-bit numbers). In particular, a single evaluation of $ubs(U)_f$ can rule out *half* of the possibilites for $a$, so we are left with $2^(n - 1) -1$ possibilites.
If we run the procedure again, we get another random $y'$ which further rules out half of the possibilites for $a$, leaving only $2^(n - 2) - 1$ possibilites and so on.
We should also consider the case when the algorithm returns $y = 0_n$, which does not give any clue about $a$. However, this is not a big deal because the probability of getting $y = 0$ is very small ($frac(1, 2^n - 1)$). Even if we got $y = 0$, by simply try again the algorithm there is a high probability that we get another $y$.
== Example
#figure(
table(
stroke: none,
columns: (auto, auto),
align: (top + center, top + center),
[
#table(
columns: (auto, auto, auto),
align: (center + horizon, center + horizon, center + horizon),
[$ x $], [$ x plus.circle a $], [$ y = f(x) $],
[000], [101], [001],
[001], [100], [010],
[010], [111], [100],
[011], [110], [110],
[100], [001], [010],
[101], [000], [001],
[110], [011], [110],
[111], [010], [100]
)
], [
#table(
columns: (auto, auto, auto),
align: (center + horizon, center + horizon, left + horizon),
[$ y $], [$ y dot a $], [*can be returned by the algorithm*],
[001], [1], [no],
[010], [0], [yes],
[100], [1], [no],
[110], [1], [no]
)
]
),
caption: [Example of an $f$ with $n = 3$ and $a = (101)_2$. Note that values in the $f(x)$ columns are random, but they respect the property that $f(x plus.circle a) = f(x)$.]
)
The procedure ends immediately in this case, because with a single evaluation of $ubs(U)_f$ we have ruled out all the possibilites for $a$.
Since we got $f(x) = 010_2$ for both $x_1 = 001_2$ and $x_2 = 100$, $a = 001_2 plus.circle 100_2 = 101_2$.
= Bell states
These are 4 foundamental entangled states:
$
ket(psi_(00)) = frac(1, sqrt(2))(ket(00) + ket(11)) equiv ket(phi.alt^+) quad quad ket(psi_(10)) = frac(1, sqrt(2))(ket(00) - ket(11)) equiv ket(phi.alt^-) \
ket(psi_(01)) = frac(1, sqrt(2))(ket(01) + ket(10)) equiv ket(Psi^+) quad quad ket(psi_(11)) = frac(1, sqrt(2))(ket(01) - ket(10)) equiv ket(Psi^-)
$
The *amount of entanglement* (e.g. the Von Neumann entropy) is the same in all of these states.
These states are accomunated by the fact that they are a linear superposition between a 2-qubit state and its flipper variant (e.g. $ket(00) arrow.r ket(11)$ and $ket(01) arrow.r ket(10)$).
The Bell states define a complete basis for the two qubit states. In other words, a 2-qubit state can be rewritten as a linear combination of Bell states:
$
ket(00) = frac(1, sqrt(2))(ket(psi_00) + ket(psi_10)) quad quad ket(10) = frac(1, sqrt(2))(ket(psi_01) - ket(psi_11)) \
ket(01) = frac(1, sqrt(2))(ket(psi_01) + ket(psi_11)) quad quad ket(11) = frac(1, sqrt(2))(ket(psi_00) - ket(psi_10))
$
== Single qubit properties of the Bell states
#highlight(fill: yellow)[The Bell states are indistinguishable at a single qubit level]. This is a very important property, because it means that if noise affects *locally* a qubit encoded using a Bell state, then the information held by that qubit is not destroyed.
Indeed, if one of the Pauli gates ${ubs(X), ubs(Y), ubs(Z)}$ is applied either to qubit $A$ or qubit $B$ of a Bell state, the result is always the same for all the gates:
$
bra(psi_00)ubs(X)_A times.circle ubs(I)_B ket(psi_00) = frac(1, 2)(bra(00) + bra(11))(ket(10) + ket(01)) = 0 \
bra(psi_00)ubs(Y)_A times.circle ubs(I)_B ket(psi_00) = frac(i, 2)(bra(00) + bra(11))(ket(10) - ket(01)) = 0 \
bra(psi_00)ubs(Z)_A times.circle ubs(I)_B ket(psi_00) = frac(1, 2)(bra(00) + bra(11))(ket(00) - ket(11)) = 0
$
#figure(
table(
columns: (auto, auto, auto, auto),
align: (center + horizon, center + horizon, center + horizon, center + horizon),
[], [$expval(X_(A\/B))$], [$expval(Y_(A\/B))$], [$expval(Z_(A\/B))$],
[$ket(psi_00)$], [0], [0], [0],
[$ket(psi_01)$], [0], [0], [0],
[$ket(psi_10)$], [0], [0], [0],
[$ket(psi_11)$], [0], [0], [0]
),
caption: [Expected value of a single-qubit measurement of a Bell state after applying a Pauli gate on it. #highlight(fill: yellow)[All expected values are the same for each Bell state, so they are not distinguishable at single-qubit level.]]
)
#pagebreak(weak: true)
They are however distinguishable at 2-qubit level, because each Bell state has its own set of expected values:
#figure(
table(
columns: (auto, auto, auto, auto),
align: (center + horizon, center + horizon, center + horizon, center + horizon),
[], [$expval(ubs(X)_A times.circle ubs(X)_B)$], [$expval(ubs(Y)_A times.circle ubs(Y)_B)$], [$expval(ubs(Z)_A times.circle ubs(Z)_B)$],
[$ket(psi_00)$], [$+1$], [$-1$], [$+1$],
[$ket(psi_01)$], [$+1$], [$-1$], [$-1$],
[$ket(psi_10)$], [$-1$], [$+1$], [$+1$],
[$ket(psi_11)$], [$-1$], [$+1$], [$-1$]
),
caption: [Expected value of a 2-qubit measurement of a Bell state after applying a Pauli gate on each of its 2 qubits]
)
=== Side note: uncorrelated and correlated measurements
In the first case, we performed an *uncorrelated measurement*: we measured each qubit of the Bell state *independently*, so we got 2 distinct results.
In the second case, we performed a *correlated measurement*: we measured the two qubits of the Bell state *jointly*, thus we get a *single* result which only specifies their relative state.
== Generating Bell states
The Bell states can be obtained by taking an initial basis state and then applying a CNOT preceded by an Hadamard applied to the control qubit:
$
ket(psi_(x_1 x_0)) = ubs(C)_10 ubs(H)_1 ket(x_1 x_0) = frac(1, sqrt(2))(ket(0\, x_0) + (-1)^(x_1) ket(1\, x_0 plus.circle 1))
$
#highlight(fill: yellow)[This process is reversible]: we can get back $ket(x_1 x_0)$ by applying the operators in reverse order to $ket(psi_(x_1 x_0))$:
$
ubs(H)_1 ubs(C)_10 ket(psi_00) = frac(1, 2)(ket(00) + ket(10) + ket(00) - ket(10)) = ket(00)
$
This should be not suprising, since $ubs(H)^2 = ubs(I)$ and $ubs(C)_10^2 = ubs(I)$:
$
ubs(H)_1 ubs(C)_10 ket(psi_00) = ubs(H)_1 cancel((ubs(C)_10 ubs(C)_10))ubs(H)_1 ket(00) = cancel(ubs(H)_1 ubs(H_1))ket(00) = ket(00)
$
== Rotation of Bell states
#highlight(fill: yellow)[A Bell state can be *rotated* into another Bell state by applying two single-qubit gates]:
$
ket(psi_(x_1 x_0)) = ubs(Z)_1^(x_1)ubs(X)_0^(x_0)ket(psi_00) = ubs(X)_0^(x_0)ubs(Z)_0^(x_1)ket(psi_00)
$
== Dense coding
#highlight(fill: yellow)[A qubit state holds an *infinite* amount of information], because its coefficient can be any number in $CC$, but when we measure a qubit we can only extract a *single* bit of information.
However, if we use *entanglement* as a resource, there is a way we can obtain *two* bits of information. This is known as *dense coding*.
This protocol consists in 4 steps:
1. Alice and Bob share two qubits in a Bell state, for example $ket(psi_00)$;
2. Alice applies to her qubit one of 4 transformations ($ubs(1), ubs(X), ubs(Z), ubs(Z X)$), depending on which set of bit she wants to communicate:
#figure(
table(
columns: (auto, auto),
align: (center + horizon, center + horizon),
[`00`], [$ ubs(1)_A ket(psi_00) = ket(psi_00) $],
[`01`], [$ ubs(X)_A ket(psi_00) = frac(1, sqrt(2))(ket(10) + ket(01)) $],
[`10`], [$ ubs(Z)_A ket(psi_00) = frac(1, sqrt(2))(ket(00) - ket(11)) $],
[`11`], [$ ubs(Z)_A ubs(X)_A ket(psi_00) = frac(1, sqrt(2))(ket(01) - ket(10)) $]
),
caption: [Transformation Alice must apply to her qubit based on the set of bits she wants to communicate]
)
3. Alice sends her qubit to Bob;
4. Bob, which has a Bell state (shared with Alice), reverses it to a basis state, e.g. it first applies a CNOT on the Bell state (using Alice's qubit $A$ as target) and then an Hadamadrd on qubit $A$;
5. the basis state Bob gets after step 4 is the set of bits Alice communicated
== Circuit representation
If Alice has two qubits $ket(x)$ and $ket(y)$ and she wants to send them to Bob, the circuit can be modeled using 2 CNOT gates:
#figure(
image("assets/b2eba2f29d9d2053667f7a548bfeb18e.png", height: 13%),
caption: [Step a: minimal circuit to send a basis state to Bob]
)
Although this circuit is very simple, it does not show at all the dense coding protocol. But we can rewrite this circuit to make the protocol evident.
#figure(
image("assets/467681dd262186a70650808cf296925a.png", height: 13%),
caption: [Step b: using the relation $ubs(X) = ubs(H Z H)$ to replace $ubs(C)_31$ with $ubs(H)ubs(Z)_31 ubs(H)$]
)
#figure(
image("assets/defecc62ea7a940e426889ed6cabe7bf.png", height: 13%),
caption: [Step c: inserting $(ubs(C)_10)^2 = ubs(1)_10$ and exploiting the commutation between $ubs(C)_10$ and $ubs(C)_31$]
)
#pagebreak(weak: true)
#figure(
image("assets/3e090243c16b91e8936ec69a8e607a10.png", height: 13%),
caption: [Step d: moving $ubs(H)_1$ and $ubs(C)_10$ to the extreme left by exploiting the commucation between $ubs(C)_20$ and $ubs(H)_1 ubs(C)_10$]
)
Next we can expand the 2 $ubs(C)$ gates on the left with 3 $ubs(C)$ gates:
#figure(
image("assets/603a387c727d7ddfa6a4ff0d6e200bed.png", height: 13%),
caption: [Step e: replacing $ubs(C)_20 ubs(C)_10$ with $ubs(C)_21 ubs(C)_10 ubs(C)_21$]
)
The effect is the same:
$
& ubs(C)_20 ubs(C)_10 ket(x_2\, x_1\, x_0) = ubs(C)_21 ubs(C)_10 ubs(C)_21 ket(x_2\, x_1\, x_0) \
--> & ubs(C)_20 ket(x_2\, x_1\, x_0 plus.circle x_1) = ubs(C)_21 ubs(C)_10 ket(x_2\, x_1 plus.circle x_2\, x_0) \
--> & ket(x_2\, x_1\, x_0 plus.circle x_1 plus.circle x_2) = ubs(C)_21 ket(x_2\, x_1 plus.circle x_2\, x_0 plus.circle x_1 plus.circle x_2) \
--> & ket(x_2\, x_1\, x_0 plus.circle x_2 plus.circle x_2) = ket(x_2\, x_1 cancel(plus.circle x_2) cancel(plus.circle x_2)\, x_0 plus.circle x_1 plus.circle x_2)
$
Finally, we can remove the leftmost $ubs(C)_21$ because $ubs(X H)ket(0) = frac(1, sqrt(2))ubs(X)(ket(0) + ket(1)) = frac(1, sqrt(2))(ket(0) + ket(1))$:
#figure(
image("assets/b4930f06b5f1c138a10193d1dda0562b.png", height: 13%),
caption: [Step f: removing $ubs(C)_21$ because it acts as an identity]
)
Indeed:
$
underbrace(mat(0, 1; 1, 0), ubs(X))underbrace(frac(1, sqrt(2))mat(1, 1; 1, -1), ubs(H))underbrace(vec(1, 0), ket(0)) = frac(1, sqrt(2))mat(0, 1; 1, 0)vec(1, 1)
= frac(1, sqrt(2))vec(1, 1) = ubs(H)ket(0)
$
#pagebreak(weak: true)
= Bloch sphere
#figure(
image("assets/223635fd0ad1b7e3ecd71d83d119a498.png", height: 17%),
caption: [Bloch sphere]
)
#highlight(fill: yellow)[Each *pure* state of the qubit corresponds to a point on the surface of the Bloch sphere].
Coefficients $alpha, beta in CC$ of state $ket(psi) = alpha ket(0) + beta ket(1)$ can be rewritten as $alpha = cos theta/2$ and $beta = e^(i phi) sin theta/2$, so $ket(psi)$ can be rewritten as:
$
ket(psi) = cos(frac(theta, 2))ket(0) + e^(i phi)sin(frac(theta, 2))ket(1) quad quad theta in [0, pi] quad phi in [0, 2pi]
$
The coordinates of a quantum state in the Bloch sphere are given by this relation:
$
ubs(r) = (sin theta cos phi, sin theta sin phi, cos theta) <=> (braket(psi, ubs(X), psi), braket(psi, ubs(Y), psi), braket(psi, ubs(Z), psi))
$
Points *inside* the sphere have a meaning too: they represent a *mixture of states*.
The distance from the center of the sphere of the quantum state is related to the Von Neumann entropy: the higher the distance, the lower the entropy.
Quantum gates represent a *rotation* of this sphere, e.g. the $ubs(X)$ gate represents a rotation of $pi$.
Bloch sphere is useful to show single qubit properties, but it's useless to discriminate between different entangled states.
If we have an unknown qubit state:
$
ket(psi) = alpha ket(0) + beta ket(1) = frac(1, sqrt(2))[(alpha + beta)ket(+) + (alpha - beta)ket(-)]
$
and we measure it as is, we get information only for one of its 3 components (the $z$ component). To get information on other components, we must *rotate* the state first (e.g. by applying an Hadamard), measure it, and rotate it back again.
= Quantum teleportation
*Problem*: Alice has a single copy of an unknown quantum state $ket(psi) = alpha ket(0) + beta ket(1)$ and she wants to send it to Bob.
Alice cannot physically send the qubit to Bob. She also cannot measure it to determine its state (Born rule) nor copy it (no cloning theorem).
#highlight(fill: yellow)[The protocol for quantum teleportation is somewhat the inverse of the dense coding protocol]:
- with the dense coding protocol, Alice communicates 2 bits of information by sending a single-qubit state to Bob;
- with the quantum teleportation protocol, Alice communicates an unknown single-qubit state by sending 2 bits of information to Bob
The protocol consists in 4 steps:
1. Alice and Bob share an entangled state, e.g. the Bell state $ket(psi_00)$. Considering Alice's 2 qubits and Bob's 1 qubit (total amount of 3 qubit), the quantum system is in the state $ket(Phi_1)$:
$
ket(Phi_1) = ket(psi)_A ket(psi_00)_(A B) & = (alpha ket(0)_A + beta ket(1)_A)frac(1, sqrt(2))(ket(00)_(A B) + ket(11)_(A B)) \
& = frac(1, sqrt(2))[alpha ket(0)_A (ket(00)_(A B) + ket(11)_(A B)) + beta ket(1)_A (ket(00)_(A B) + ket(11)_(A B))]
$
2. Alice applies a CNOT to her two qubits. The qubit whose state has to be communicated acts as the control qubit:
$
ket(Phi_2) = ubs(C)_21 ket(Phi_1) = frac(1, sqrt(2))[alpha ket(0)_A (ket(#text(fill: green)[0]0)_(A B) + ket(#text(fill: green)[1]1)_(A B)) + beta ket(1)_A (ket(#text(fill: red)[1]0)_(A B) + ket(#text(fill: red)[0]1)_(A B))]
$
$ubs(C)_21$ has flipped the qubits highlighted in #text(fill: red)[*red*], but it left untouched the qubits highlighted in #text(fill: green)[*green*] because the control qubit has value 0.
3. Alice applies an Hadamard gate to the qubit whose state has to be communicated:
$
ket(Phi_3) = ubs(H)_3 ket(Phi_2) = frac(1, 2)[alpha (ket(0)_A + ket(1)_A)(ket(00)_(A B) + ket(11)_(A B)) + beta(ket(0)_A - ket(1)_B)(ket(10)_(A B) + ket(01)_(A B))]
$
4. Alice measures her two qubits and communicates the outcome to Bob. Let's rewrite state $ket(Phi_3)$ to make the possible outcomes for Alice and Bob clearer:
$
ket(Phi_3) & = frac(1, 2)[ket(00)_(A A)(alpha ket(0)_B + beta ket(1)_B) + ket(10)_(A A)(alpha ket(0)_B - beta ket(1)_B) \
& + ket(01)_(A A)(alpha ket(1)_B + beta ket(0)_B) + ket(11)_(A A)(alpha ket(1)_B - beta ket(0)_B)]
$
5. Bob applies some gates to his qubit. The gates he has to apply are determined by Alice's measurement outcome:
#figure(
table(
columns: (auto, auto, auto),
[*outcome for Alice*], [*Bob qubit state*], [*what Bob has to do to get $ket(psi)$*],
[`00`], [$alpha ket(0) + beta ket(1)$], [nothing, Bob already has its qubits in state $ket(psi)$],
[`01`], [$alpha ket(1) + beta ket(0)$], [Bob has to apply $ubs(X)$],
[`10`], [$alpha ket(0) - beta ket(1)$], [Bob has to apply $ubs(Z)$],
[`11`], [$alpha ket(1) - beta ket(0)$], [Bob has to apply $ubs(Z X)$]
),
caption: [What Bob has to do to get $ket(psi)$ based on the outcome of Alice's measurement]
)
#highlight(fill: yellow)[Quantum teleportation does not violate the no cloning theorem]: at the end of the process, Alice is left with the state $ket(x_1 x_0) times.circle ket(psi_00)$ (where $x_1, x_0$ are the outcome of her measurement). She loses all information about the original, unknown state $ket(psi)$.
== A qubit can be looked from different perspectives
#highlight(fill: yellow)[This is what allows quantum teleportation].
State $ket(Phi_1)$ can be rewritten using the Bell states as basis states:
$
ket(Phi_1) = ket(psi)_A ket(psi_00)_(A B) = frac(1, sqrt(2))(alpha ket(000)_(A A B) + beta ket(100)_(A A B) + alpha ket(011)_(A A B) + beta ket(111)_(A A B)) \
= frac(1, 2)[ket(psi_00)_(A A)(alpha ket(0)_B + beta ket(1)_B) + ket(psi_01)_(A A)(alpha ket(1)_B + beta ket(0)_B) \+ ket(psi_10)_(A A)(alpha ket(0)_B - beta ket(1)_B) + ket(psi_11)(alpha ket(1)_B - beta ket(0)_B)]
$
By looking at $ket(Phi_1)$ rewritten in this way, it's clear that the next operations Alice does (a CNOT followed by an Hadamard) produce a *rotation* of this state; the information contained in these qubits is not altered in any way.
== Circuit representation
The goal is to transfer an unknown state from the first qubit to the second one.
#figure(
image("assets/c59eef996428afc2b2e3c897ccb49968.png", height: 8%),
caption: [Step a: quantum circuit that transfers a generic single-qubit state $ket(psi)$ to $ket(0)$]
)
This circuit, despite being very simple, does not implement the quantum teleportation protocol, also because quantum teleportation communicate a *linear superposition* of states, but this circuit communicates only a single basis state.
We therefore introduce an ancillar qubit $ket(phi.alt)$ initialized to $ubs(H)ket(0)$:
#figure(
image("assets/79bc63b583bad2f0693a1f6827f514ca.png", height: 8%),
caption: [Step b: introduction of $ket(phi.alt) = ubs(H)ket(0)$]
)
Similar to what done in the circuit derivation for the dense coding protocol, we substitue $ubs(C)_20$ with a controlled $ubs(Z)$ gate. We also add $ubs(C)_21$ because it acts like an identity for $ket(phi.alt) = ubs(H)ket(0)$, because $ubs(X H)ket(0) = ubs(H)ket(0)$:
#figure(
image("assets/30b4a2651c695c1ae02017ba92262451.png", height: 8%),
caption: [Step c: using $ubs(C)_02 = ubs(H)_2 ubs(Z)_02 ubs(H)_2$ and $ubs(X H)ket(0) = ubs(H)ket(0)$ identities to rewrite the circuit]
)
#figure(
image("assets/7bfcd50e7f65d814d21870a98e11a4d5.png", height: 8%),
caption: [Step d: flipping target and control qubits of $ubs(Z)_02$ and exploiting the equivalence $ubs(C)_20 ubs(C)_21 = ubs(C)_10 ubs(C)_21 ubs(C)_10$]
)
#figure(
image("assets/94254b6044694a7d21cf7bc0c819cc31.png", height: 8%),
caption: [Step e: adding $ubs(H)_1$ and replacing $ubs(C)_10 ubs(H)_2$ with $ubs(H)_2 ubs(C)_10$ because they commute with each other]
)
#figure(
image("assets/948e5f7065d1c6f3b7a47a572ad33c82.png", height: 8%),
caption: [Step f: adding $ubs(M)_2$ and $ubs(M)_1$]
)
#figure(
image("assets/ee748397b4b7e1b999e0a18c18430694.png", height: 8%),
caption: [Step g: swapping $ubs(M)_2$ and $ubs(M)_1$ with $ubs(C)_10 ubs(Z)_20$ because they commute with each other]
)
This last circuit represents the quantum teleportation protocol.
= Quantum cryptography
Quantum cryptography works quite differently from non-quantum modern cryptography:
- non-quantum *asymmetric* cryptography is based on *hard problems*, i.e. problems that require a high amount of computing power to be solved. If someday there will be enough computing power, this type of cryptography will be broken;
- quantum cryptography instead is based on properties of quantum systems, i.e. on *laws of nature*. Computing power is irrelevant here.
Quantum cryptography is possible by exploiting some properties of quantum systems which may be annoying in other contexts:
- no cloning theorem: Eve cannot store a copy of the eavesdropped quantum state and then try to decrypt it, because a quantum state cannot be cloned;
- measurement destroys the original state: if Eve tries to scramble with the qubit state, Alice and Bob will notice it;
- measurement outcome is *random*. Quantum systems are *truly random*, not just pseudo-random like classical systems, therefore they can never be *predicted*
== BB84 protocol (Bennet-Brassard)
This protocol actually is a *key-exchange protocol*. Alice has a sequence $S$ of random bits and wants to send it to Bob, so they can use $S$ as the key for a *symmetric encryption* scheme.
The protocol starts with Alice preparing a sequence of qubits that will form the *shared secret key* when the outcomes of the measurements of each qubit will be put together. #highlight(fill: yellow)[For each qubit, Alice chooses *randomly* in which state preparing it between 4 alternatives]: ${ket(0), ket(1), ket(+), ket(-)}$. In other words, she decides randomly the *basis* in which the qubit will be prepared:
- type-1 qubit (basis ${ket(0), ket(1)}$);
- type-H qubit (basis ${ket(+), ket(-)} = {ubs(H)ket(0), ubs(H)ket(1)}$)
Alice then sends each qubit to Bob, which will perform a similar choice for each qubit: he will choose *randomly* whether
- measuring the qubit immediately (type-1 measurement);
- measuring the qubit only after applying an Hadamard on it (type-H measurement)
Alice and Bob then communicate over an *insecure* channel the type of their qubits and they discard the qubits which are not of the same type. They do not communicate the exact state of the qubit (and they must not to if they want the protocol to be secure!), but only the type.
The sequence of bits that survives is the shared secret key, but before using it Alice and Bob must check for *eavesdroppers*. Alice and Bob choose an arbitrary number of qubits to check (the higher, the more secure, but also the slower): if in these qubits Bob finds a state which does not match with the type of qubit sent by Alice, it means that the shared key has been eavesdropped and therefore it's not secure.\
Example: if Alice sents a qubit in the basis ${ket(+), ket(-)}$ and Eve measures it using a type-1 measurement before forwarding the qubit to Bob, the qubit will change the basis to ${ket(0), ket(1)}$. When Bob applies an Hadamard to it, the state will remain in that basis and therefore it will not match with the basis Alice prepared the qubit in.
= Grover algorithm
== Preliminary notions
=== Vector space and dual space
#figure(
image("assets/0fb5efd267965972fb56ccf1ca4b34e6.png", width: 50%),
caption: [Vector space and dual space representation. Our qubits can be represented in one of these two spaces.]
)
The *inner product* $braket(alpha, beta)$ is a complex number which is the #highlight(fill: yellow)[measurement of the *overlap* between the two vectors].
The *outer product* $ketbra(beta, alpha)$ is an *operator* that when applied to a state $ket(psi)$ gives $braket(alpha, psi)ket(beta)$ and when applied to $bra(psi)$ gives $braket(psi, beta)ket(alpha)$.
=== Projector
A projector $ubs(P)$ is an Hermitian and *idempotent* operator (i.e. $ubs(P)^2 = ubs(P)$) that can be written as $ubs(P) = ketbra(lambda, lambda)$.
The *eigenvalues* of a projector operator $ubs(P)$ corresponds to 0 or 1, because the operator is idempotent:
$
ubs(P)ket(lambda) = lambda ket(lambda) = ubs(P)^2 ket(lambda) = lambda^2 ket(lambda) <=> lambda in {0, 1}
$
One might note that the *density matrix* is also defined as $rho = ketbra(psi, psi)$. Projectors and density matrices are different things conceptually, but if $ket(psi)$ is a *pure state* (and not a *mixture* of states), then the projector and the density matrix are equivalent.\
#highlight(fill: yellow)[In general, if we have a pure quantum state, we can say that the projector is actually a *density operator*].
== Grover algorithm
The problem is to search for an item $a$ in an *unsorted database* of size $N$. We have a function $f : {0, 1}^n |-> {0, 1}$ that acts like an *oracle*, i.e. it says if $x = a$:
$
f(x) = cases(
0 "if" x != a,
1 "if" x = a
)
$
The computational cost of this algorithm is the number of times $f$ has to be evaluated before finding a value $x_k = a$.
In a classical approach, the average cost is $Order(N / 2) = Order(2^(n - 1))$ for $n$ bits (i.e. *exponential cost* in the number of bits).
The average cost for the quantum approach instead is $Order(sqrt(N)) = Order(2^(n / 2))$. This cost is still exponential, but it's significantly lower than the classical approach.
The first step is to define $ubs(U)_f$ in the usual way, i.e. $ubs(U)_f (ket(x)_n ket(y)_n) = ket(x)_n ket(y plus.circle f(x))_n$.
#pagebreak(weak: true)
Our problem can be represented using this circuit:
#figure(
image("assets/76e4360feeff87e9d3f210e99d1c32d8.png", height: 20%),
caption: [Circuit representation of the Grover algorithm, a *multi-controlled* $ubs(X)$ gate.]
)
We initialize the output register in the state $ubs(H)ket(1) = frac(1, sqrt(2))(ket(0) - ket(1)) = ket(-)$, so the operator $ubs(U)_f$ can be rewritten in this way:
$
ubs(U)_f (ket(x)_n times.circle ket(-)) = ket(x)_n times.circle [(-1)^(f(x))ket(-)] = [(-1)^(f(x))ket(x)_n] times.circle ket(-)
$
In the second step we moved $(-1)^(f(x))$ to the left, which is always possible due to *linearity* of quantum mechanics. Written in this form, we notice that $f(x)$ is acting on the *input* register only; the output register is left untouched in the state $ket(-)$.
So we can ignore the output register and rephrase the problem in terms of a unitary transformation $ubs(V)$ acting con the input space alone:
$
ubs(V)ket(x) = (-1)^(f(x))ket(x) = cases(ket(x) "if" x != a, -ket(a) "if" x = a) = ubs(1) - 2ketbra(a)
$
In other words, $ubs(V)$ is the *projector operator* on state $ket(a)$.
The next step is to initialize the input qubits in a linear superposition of all the basis states, with equal weights:
$
ket(phi.alt) = ubs(H)^(times.circle n)ket(0)_n = frac(1, sqrt(2^n))sum_(x = 0)^(2^n - 1)ket(x)_n
$
and then introducing another operator $ubs(W)$ that is the *projector operator* on state $ket(phi.alt)$ (and in particular it does not depend on the value of $a$):
$
ubs(W) = 2ketbra(phi.alt) - ubs(1)
$
Operators $ubs(V)$ and $ubs(W)$ are *closed* in the vector space ${ket(a), ket(phi.alt)}$, because when they are applied to any vector, the result is a linear combination of $ket(phi.alt)$ and $ket(a)$:
#align(center)[
#table(
columns: (auto, auto),
align: (center + horizon, center + horizon),
stroke: none,
[$ ubs(V)ket(a) = -ket(a) $], [$ ubs(W)ket(a) = frac(2, sqrt(2^n))ket(phi.alt) - ket(a) $],
[$ ubs(V)ket(phi.alt) = ket(phi.alt) $], [$ ubs(W)ket(phi.alt) = ket(phi.alt) - frac(2, sqrt(2^n))ket(a) $]
)
]
These relations are verified because $ket(phi.alt)$ is a linear superposition of all the possible input registers including $ket(a)$ itself, so the overlap between $ket(a)$ and $ket(phi.alt)$ is $2^(-frac(n, 2)) = frac(1, sqrt(N))$.
#pagebreak(weak: true)
This overlap between $ket(phi.alt)$ and $ket(a)$ is also the *cosine* of the angle $theta$ between these two vectors:
$
cos theta = braket(a, phi.alt) = frac(1, sqrt(N)) -->_(n -> infinity) 0
$
This tells us that for a very big $N$, $ket(phi.alt)$ and $ket(a)$ are *nearly* orthogonal. However, we want a linear superposition which is *exactly* orthogonal to $ket(a)$, so we define the state $ket(a_perp)$ in this way:
$
ket(a_perp) = frac(1, sqrt(2^n - 1))sum_(x != a)ket(x)
$
$ket(a_perp)$ is the linear superposition of all possible inputs *excluding* $a$ (and this is the reason why there is a $-1$ in the denominator in front of the sum).
Operator $ubs(V)$ represented in the basis ${ket(a), ket(a_perp)}$ is given by:
$
ubs(V) = mat(
braket(a, ubs(V), a), braket(a, ubs(V), a);
braket(a_perp, ubs(V), a), braket(a_perp, ubs(V), a_perp)
) = mat(-1, 0; 0, 1)
$
In the last step we used the relation $ubs(V)ket(a) = (ubs(1) - 2ketbra(a))ket(a) = -ket(a)$, which implies that $braket(a, ubs(V), a) = -1$ and that $braket(a_perp, ubs(V), a) = 0$.
To get $ubs(W)$ we need to consider the operator $ketbra(phi.alt)$. First, let's rewrite $ket(phi.alt)$ in the basis ${ket(a), ket(a_perp)}$:
$
ket(phi.alt) = frac(1, sqrt(N))(ket(a) + sqrt(N - 1)ket(a_perp))
$
From this we can obtain $ketbra(phi.alt)$ much like we obtained $ubs(V)$:
$
ketbra(phi.alt) = mat(
braket(a, ketbra(phi.alt), a), braket(a, ketbra(phi.alt), a_perp);
braket(a_perp, ketbra(phi.alt), a), braket(a_perp, ketbra(phi.alt), a_perp)
) = frac(1, N)mat(
1, sqrt(N - 1);
sqrt(N - 1), N - 1
)
$
and then we can get $ubs(W) = 2ketbra(phi.alt) - ubs(1)$:
$
ubs(W) = frac(1, N)mat(
2 - N, 2sqrt(N - 1);
2sqrt(N - 1), N - 2
)
$
Now we can define the *Grover operator* $ubs(W V)$:
$
ubs(W V) = underbrace(frac(1, N)mat(2 - N, 2sqrt(N - 1); -2sqrt(N - 1), N - 2), ubs(W))underbrace(mat(-1, 0; 0, 1), ubs(V)) = frac(1, N)mat(
N - 2, 2sqrt(N - 1);
-2sqrt(N - 1), N - 2
)
$
#pagebreak(weak: true)
== Geometric interpretation
#highlight(fill: yellow)[Two quantum states are *orthogonal* if the angle $theta$ between them is $pi$. In this context _perpendicular_ and _orthogonal_ are not synonyms: to be orthogonal, the vectors must point in *opposite* directions].
#figure(
image("assets/3c207846ae998e3c237c14cde7624e42.png", height: 20%),
caption: [A plane with the geometric interpretation of the Grover algorithm]
)
The input register $ket(phi.alt)$ is very close to $ket(a_perp)$, because these two vectors are very similar:
- $ket(phi.alt)$ is the linear superposition of all possible $n$-qubit states *including* $ket(a)$;
- $ket(a_perp)$ is the linear superposition of all possible $n$-qubit states *excluding* $ket(a)$
The Grover operator $ubs(W V)$ actually *rotates* the vector $ket(phi.alt)$:
- $ubs(V)$ implements a reflection of $ket(psi) = ubs(W V)^k ket(phi.alt)$ along the $ket(a_perp)$ axis, corresponding to a clockwise rotation by an angle $2(alpha + beta)$ (where $alpha = arccos braket(a_perp, phi.alt)$ and $beta = arccos braket(phi.alt, psi)$);
- $ubs(W)$ implements a reflection of $ubs(V)ket(psi)$ along the $ket(phi.alt)$ axis, corresponding to a counterclockwise rotation by an angle of $2(2alpha + beta)$
The net effect is a rotation by an angle of $2(alpha + beta) - 2(2alpha + beta) = -2alpha$, i.e. a counterclockwise rotation of $gamma = 2alpha$. The value of $gamma$ can be retrieved by comparing the Grover operator with the generic *rotation operator* $ubs(R)_y (gamma)$:
$
ubs(R)_y (gamma) = mat(cos(frac(gamma, 2)), sin(frac(gamma, 2)); -sin(frac(gamma, 2)), cos(frac(gamma, 2)))
$
Therefore the angle $gamma$ is given by:
$
gamma = 2 arcsin(frac(2sqrt(N - 1), N)) tilde.eq 2arcsin(frac(2, sqrt(N))) tilde.eq frac(4, sqrt(N))
$
Since $ket(phi.alt)$ starts very close to $ket(a_perp)$ and the goal is to reach $ket(a)$, and every application of the Grover operator rotates counterclockwise $ket(psi)$ by an angle of $frac(4, sqrt(N))$, the number of required rotations is given by:
$
R = frac(pi, frac(4, sqrt(N))) = frac(pi, 4)sqrt(N)
$
Since $R = Order(sqrt(N))$, this demonstrates why the Grover algorithm has an average cost of $Order(sqrt(N))$.
However, after all these rotations, we will not arrive *exactly* to $ket(a)$, but to another value $ket(overline(a))$ which is very close to $ket(a)$. The probability of arriving exactly to $ket(a)$ is given by:
$
P >= cos^2(frac(alpha, 2)) = 1 - frac(1, N) -->_(n -> infinity) 1
$
If after $R$ rotation we land on a value $overline(a) != a$, the whole procedure must be tried again. If after a large (arbitrary) number of trials we still have not found $a$, then this means $a$ does not exist.
== Grover algorithm with two qubits
$ket(phi.alt)$ is the linear superposition of all possible input states:
$
ket(phi.alt) = frac(1, 2)(ket(00) + ket(01) + ket(10) + ket(11)) = frac(1, 2)vec(1, 1, 1, 1)
$
Let's consider the case of $ket(a) = ket(01)$. We have:
$
ubs(W) = 2ketbra(phi.alt) - ubs(1) = frac(1, 2)mat(-1, 1, 1, 1; 1, -1, 1, 1; 1, 1, -1, 1; 1, 1, 1, -1) quad quad ubs(V) = 1 - 2ketbra(a) = mat(1, 0, 0, 0; 0, -1, 0, 0; 0, 0, 1, 0; 0, 0, 0, 1) \
ubs(W V) = frac(1, 2)mat(-1, -1, 1, 1; 1, 1, 1, 1; 1, -1, -1, 1; 1, -1, 1, -1)
$
In this case a single application of $ubs(W V)$ is enough to find the solution:
$
ubs(W V)ket(phi.alt) = frac(1, 4)mat(-1, -1, 1, 1; 1, 1, 1, 1; 1, -1, -1, 1; 1, -1, 1, -1)vec(1, 1, 1, 1) = vec(0, 1, 0, 0) = ket(01)
$
Let's now switch to the basis ${ket(a), ket(a_perp)}$:
$
ket(a_perp) = frac(1, sqrt(3))(ket(00) + ket(10) + ket(11)) = frac(1, sqrt(3))vec(1, 0, 1, 1) \
ubs(W V)ket(a) = frac(1, 2)mat(-1, -1, 1, 1; 1, 1, 1, 1; 1, -1, -1, 1; 1, -1, 1, -1)vec(0, 1, 0, 0) = frac(1, 2)vec(-1, 1, -1, -1) quad quad ubs(W V)ket(a_perp) = frac(1, 2sqrt(3))mat(-1, -1, 1, 1; 1, 1, 1, 1; 1, -1, -1, 1; 1, -1, 1, -1)vec(1, 0, 1, 1) = frac(1, 2sqrt(3))vec(1, 3, 1, 1) \
braket(a, ubs(W V), a) = frac(1, 2)mat(0, 1, 0, 0)vec(-1, 1, -1, -1) = frac(1, 2) quad quad braket(a_perp, ubs(W V), a) = frac(1, 2sqrt(3))mat(1, 0, 1, 1)vec(-1, 1, -1, -1) = -frac(sqrt(3), 2) \
braket(a, ubs(W V), a_perp) = frac(1, 2sqrt(3))mat(0, 1, 0, 0)vec(1, 3, 1, 1) = frac(sqrt(3), 2) quad quad braket(a_perp, ubs(W V), a_perp) = frac(1, 6)mat(1, 0, 1, 1)vec(1, 3, 1, 1) = frac(1, 2) \
ubs(W V) = frac(1, 2)mat(1, sqrt(3); -sqrt(3), 1) = ubs(R)_y (frac(2pi, 3))
$
$
alpha = 2arccos braket(a_perp, phi.alt) = 2arccos(frac(sqrt(3), 2)) = frac(pi, 3) -> gamma = 2alpha = frac(2pi, 3)
$
== How to construct $ubs(W)$
In this section we will consider the gate $-ubs(W)$ instead of $ubs(W)$, because it's easier to implement and it still leads to a final state that differs only by a (harmless) minus sign.
Since $ubs(W) = 2ketbra(phi.alt) - ubs(1)$, it follows that $-ubs(W) = ubs(1) - 2ketbra(phi.alt)$. If we write $ket(phi.alt)$ explicitly we have:
$
-ubs(W) & = ubs(H)^(times.circle n)(ubs(1) - 2ketbra(00 ... 00, 00 ... 00))ubs(H)^(times.circle n) \
& = ubs(H)^(times.circle n)[ubs(X)^(times.circle n)(ubs(1) - 2ketbra(1...1))ubs(X)^(times.circle n)]ubs(H)^(times.circle n) \
& = ubs(H)^(times.circle n)[ubs(X)^(times.circle n)(c^(n - 1)ubs(Z))ubs(X)^(times.circle n)]ubs(H)^(times.circle n)
$
The multi-qubit gate $c^(n - 1)ubs(Z)$, which is actually a multi-controlled $ubs(Z)$ gate, can be decomposed into a double-controlled $ubs(Z)$ gate ($c^2 ubs(Z)$) sandwitched between $2(n - 3)c^2 ubs(X)$ gates:
#figure(
image("assets/c8b6a4949b1799b0f80328f7fe9f2239.png", height: 18%),
caption: [Decomposition of $c^(n - 1)ubs(Z)$ in multiple 3-qubit gates]
)
This decomposition uses $n - 3$ ancillary qubits, all initialized in the state $ket(0)$.
== Generalization to the case of $m > 1$ special items
We assume there are *multiple* special items $a_1, ..., a_m$ in the database and we want to retrieve one of them (which one does not matter).
The problem does not change
Our oracle changes in this way:
$
f(x) = cases(
0 "if" x in.not {a_1, ..., a_m},
1 "if" x in {a_1, ..., a_m}
)
$
but the problem does not changes conceptually with respect to the case of $m = 1$.
$ket(psi)$ changes with respect to the case $m = 1$ because there are *multiple* states to "remove" from the linear superposition, not just a single one:
$
ket(psi) = frac(1, sqrt(m))sum_(k = 1)^(m)ket(a_k) quad quad ket(psi_perp) = frac(1, sqrt(N - m))sum_(x in.not {a_1, ..., a_m})ket(x)
$
Operator $ubs(V)$ is generalized as follows:
$
ubs(V) = ubs(1) - frac(2, m)sum_(j = 1 \ k = 1)^(m) ketbra(a_j, a_k) = ubs(1) - 2ketbra(psi)
$
The angle $gamma$ now becomes $tilde.eq 4sqrt(frac(m, N))$. We reach this approximation because $N << m$, therefore $N - m tilde.eq N$. This angle $gamma$ is much bigger than the one for the case of $m = 1$, so the cost of the Grover operator is reduced.
However, the speedup from $m = 1$ to $m > 1$ is smaller in the quantum case than in the classical case:
- with a classical approach, the speedup is linear in $m$ (if there are multiple special items, it's easier to find one of them);
- with a quantum approach, the speedup is just of $sqrt(N)$
Anyway, the quantum version for $m > 1$ is more efficient than the quantum version for $m = 1$, because the presence of $m$ special items reduces the number of calls by a factor $sqrt(m)$.
= Quantum Fourier transform
We have a *periodic function* $f$ such that $f(x) = f(y) <=> x - y = k r$ for some integer $k$. Our goal is to find the period $r$.
The best known classical algorithm for finding $r$ scales as $root(3, n)$. The quantum version instead has a significant speedup of $n^3$.
The *discrete Fourier transform* is a function $cal(F): CC^N -> CC^N$:
$
tilde(gamma)_x = frac(1, sqrt(N))sum_(y = 0)^(N - 1)gamma_y e^(-frac(2pi i x y, N))
$
To implement this function on a quantum computer, we can rephrase the problem in a transformation from the Hilbert space to itself. The *quantum Fourier transform* is the unitary transformation $ubs(U)_("FT")$ whose action on the computational basis is given by
$
ubs(U)_("FT") ket(x)_n = frac(1, sqrt(2^n))sum_(y = 0)^(2^n - 1)e^(frac(2pi i x y, 2^n))ket(y)_n
$
$ubs(U)_("FT")$ is *unitary* because it preserves the inner product:
$
braket(x, ubs(U)_("FT")^dagger ubs(U)_("FT"), x') = braket(x, x')
$
Another proof of the "unitaryness" of $ubs(U)_("FT")$ is that we will construct it out of 1- and 2-qubit unitary gates.
$ubs(U)_("FT")$ implements the discrete Fourier transform on the $N$ complex numbers that correspond to the coefficients of the state $ket(psi)$.
The classical fast Fourier transform requres $Order(n 2^n)$ steps, while the quantum version requires just $Order(n^2)$ steps (#highlight(fill: yellow)[exponential vs polynomial]).
The major drawback of the quantum version is that we cannot retrieve all the Fourier coefficients $tilde(gamma)$, but if $gamma$ is a periodic function (with a period $<= sqrt(2^n)$), then the quantum version can give powerful clues about the value of the period $r$.
To construct a circuit to execute the quantum Fourier transform $ubs(U)_("FT")$, it's convenient to introduce an $n$-qubit operator $cal(bold(Z))$:
$
cal(bold(Z))ket(y)n = e^(frac(2pi i y, 2^n))ket(y)
$
This $cal(bold(Z)))$ is the generalization to $n$-qubit of the 1-qubit $ubs(Z)$ operator. It is used to add a *phase* to every state of the linear superposition generated by the $ubs(H)^(times.circle n)$ operator.
This $cal(bold(Z))$ operator can be written as an *exponential function* of the single-qubit number operators:
$
& y = y_(k - 1)2^(k - 1) + ... + y_0 2^0 \
--> & hat(y) = ubs(n)_(k - 1)2^(k - 1) + ... + ubs(n)_0 2^0 \
--> & cal(bold(Z)) = exp[frac(2i pi, 2^k)(ubs(n)_(k - 1)2^(k - 1) + ... + ubs(n)_0 2^0)]
$
By using this $cal(bold(Z))$ operator, we can rephrase the definition of $ubs(U)_("FT")$:
$
ubs(U)_("FT")ket(x) = cal(bold(Z))^x ubs(H)^(times.circle n)ket(0)_n
$
This gives $ubs(U)_("FT")ket(x)_n$ as an $x$-dependent operator acting on the state $ket(0)$. This operator is quite odd, because it depends on its input $x$. Therefore the goal now is to rewrite this expression to obtain an $x$-independent operator acting on the state $ket(x)_n$.
== Four qubit example
When $k = n = 4$, the QFT expression can be rewritten as
$
ubs(U)_("FT")ket(x_3)ket(x_2)ket(x_1)ket(x_0) = cal(bold(Z))^x ubs(H)_3 ubs(H)_2 ubs(H)_1 ubs(H)_0 ket(0)ket(0)ket(0)ket(0)
$
Expression for $cal(bold(Z))$ for $n = 4$ can be retrieved by its general form:
$
& cal(bold(Z)) = exp[frac(i pi, 8)(8ubs(n)_3 + 4ubs(n)_2 + 2ubs(n)_1 + ubs(n)_0)] \
--> & cal(bold(Z))^x = exp[frac(i pi, 8)(8ubs(n)_3 + 4ubs(n)_2 + 2ubs(n)_1 + ubs(n)_0)(8x_3 + 4x_2 + 2x_1 + x_0)]
$
This expression for $cal(bold(Z))^x$ is quite long (16 terms), but it can be simplified.
The first simplification comes from the fact that $e^(2pi i ubs(n)) = ubs(1)$:
$
e^(2pi i ubs(n)) = cases(
e^((2i pi) dot 0) = (-1)^0 = 1 "for" ubs(n)ket(0) = 0,
e^((2i pi) dot 1) = (-1)^2 = 1 "for" ubs(n)ket(1) = 1
)
$
therefore all products $x_i ubs(n)_j$ whose coefficient is $> 2^(n - 1)$ can be dropped, leaving
$
cal(bold(Z))^x = exp{[x_0 ubs(n)_3 + (x_1 + frac(x_0, 2))ubs(n)_2 + (x_2 + frac(x_1, 2) + frac(x_0, 4))ubs(n)_1 + (x_3 + frac(x_2, 2) + frac(x_1, 4) + frac(x_0, 8))ubs(n_0)]}
$
The second simplification comes from the fact that $e^(i pi x ubs(n))ubs(H)ket(0) = ubs(H)ket(x)$, indeed:
$
x = 0 --> cancel(e^(i pi ubs(n) dot 0))ubs(H)ket(0) = ubs(H)ket(0) \
x = 1 --> e^(i pi ubs(n) dot 1)ubs(H)ket(1) = (-1)^(ubs(n))frac(1, sqrt(2))(ket(0) + ket(1)) = frac(1, sqrt(2))(ket(0) - ket(1)) = ubs(H)ket(1)
$
Therefore this relation can be applied to all *integer* coefficients in the $cal(bold(Z))^x$ expression:
$
exp[(i pi(x_0 ubs(n)_3 + x_1 ubs(n)_2) + x_2 ubs(n)_1 + x_3 ubs(n)_0)]ubs(H)_3 ubs(H)_2 ubs(H)_1 ubs(H)_0 ket(0)ket(0)ket(0)ket(0) \
= [exp(i pi x_0 ubs(n)_3)ubs(H)_3][exp(i pi x_1 ubs(n)_2)ubs(H)_2][exp(i pi x_2 ubs(n)_1)ubs(H)_1][exp(i pi x_3 ubs(n)_0)ubs(H)_0]ket(0)ket(0)ket(0)ket(0) \
= ubs(H)_3 ubs(H)_2 ubs(H)_1 ubs(H)_0 ket(x_0)ket(x_1)ket(x_2)ket(x_3)
$
but the are also *fractional* coefficients in the expression for $ubs(U)_("FT")$, so the complete expression is:
$
ubs(U)_("FT")ket(x_3)ket(x_2)ket(x_1)ket(x_0) = \
exp{i pi[frac(1, 2)x_0 ubs(n)_2 + (frac(1, 2)x_1 + frac(1, 4)x_0)ubs(n)_1 + (frac(1, 2)x_2 + frac(1, 4)x_1 + frac(1, 8)x_0)ubs(n)_0]}ubs(H)_3 ubs(H)_2 ubs(H)_1 ubs(H)_0 ket(x_0)ket(x_1)ket(x_2)ket(x_3)
$
All $ubs(n)$ operators in this expression are *commutative*, because they act on different qubits. We can therefore use a property of the exponential function:
$
e^(A + B) = e^A e^B
$
This property is valid if and only if $A B = B A$, like in our case. So we can group the expression above by rewriting it as a *product of exponentials*:
$
ubs(U)_("FT")ket(x_3)ket(x_2)ket(x_1)ket(x_0) = ubs(H)_3 exp(i pi frac(1, 2)x_0 ubs(n)_2)ubs(H)_2 exp[i pi(frac(x_1, 2) + frac(x_0, 4))ubs(n)_1] ubs(H)_1 exp[i pi(frac(x_2, 2) + frac(x_1, 4) + frac(x_0, 8))ubs(n)_0]ubs(H)_0 ket(x_0)ket(x_1)ket(x_2)ket(x_3)
$
Note that while $exp$ and $ubs(H)$ operators can be rearranged freely when they act on *different* qubit, when they act on the same qubit this is not true. In this example, the $exp$ on qubit 0 and $ubs(H)_0$ cannot be rearranged.
To better write this expression, we introduce two 2-qubit operators:
$
ubs(V)_(i j) = exp(frac(i pi ubs(n)_i ubs(n)_j, 2^(|i - j|))) \
ubs(P)ket(x_3)ket(x_2)ket(x_1)ket(x_0) = ket(x_0)ket(x_1)ket(x_2)ket(x_3)
$
where $ubs(P)$ is just a *permutation* operator.
Now we can rewrite $ubs(U)_("FT")$ in this way:
$
ubs(U)_("FT")ket(x_3)ket(x_2)ket(x_1)ket(x_0) = ubs(H)_3 (ubs(V)_32 ubs(H)_2)(ubs(V)_31 ubs(V)_21 ubs(H)_1)(ubs(V)_30 ubs(V)_20 ubs(V)_10 ubs(H)_0)ubs(P)ket(x_0)ket(x_1)ket(x_2)ket(x_3)
$
and this ends the demonstration on how to build $ubs(U)_("FT")$ out of 1- and 2-qubit unitary gates, which also proves that $ubs(U)_("FT")$ is unitary.
#figure(
image("assets/47c991593a441c28a98ae9401f8a22a3.png", width: 72%),
caption: [Circuit that implements QFT for $n = 4$ qubits]
)
== Quantum period finding
Let's resume our problem about finding the period of a function:
$
ubs(U)_f ket(x)_n ket(0)_(n_0) = ket(x)_n ket(f(x))_(n_0)
$
where $n_0$ is the smallest integer such that $2^(n_0) >= M$ with $0 <= f(x) < M$ and $n = 2n_0$.
The quantum Fourier transform is very efficient, but its result cannot be used directly because when we measure the output register we don't get any coefficient.
To find the period of $f$, first the input register is prepared in a linear superposition of all possible input states, while the output register is initialized to $ket(0)$:
$
ubs(U)_f (ubs(H)^(times.circle n)ket(0)_n ket(0)_(n_0)) = frac(1, sqrt(2^n))sum_(x = 0)^(2^n - 1)ket(x)_n ket(f(x))_(n_0)
$
Next we measure the *output* register, which causes a collapse of the *input* register to all states related to the outcome:
$
ket(psi)_n = frac(1, sqrt(m))sum_(k = 0)^(m - 1)ket(x_0 + k r)_n ket(f(x_0))_(n_0)
$
where:
- $r$ is the period of $f$;
- $m$ is the number of input values for which $f$ has value $f(x_0)$;
- $x_0$ is the smallest of such input values such that $0 <= x_0 < r$
In other words, when we measure the output register the input register collapses in a state composed of $m$ values. Each of these $m$ values has a distance $k r$ (i.e. a *multiple* of the period) from $x_0$.
Now we apply the QFT to the input register:
$
ket(Psi') & = ubs(U)_("FT") frac(1, sqrt(m))sum_(k = 0)^(m - 1)ket(x_0 + k r)_n \
& = sum_(y = 0)^(2^n - 1)exp(frac(2pi i x_0 y, 2^n))frac(1, sqrt(2^n m))(sum_(k = 0)^(m - 1)exp[frac(2pi i k r y, 2^n)])ket(y)
$
and then we measure the input qubits.
For $N = 2^n = m r$, the probability of getting $y = j m$ (i.e. a *multiple* of $m$) as an outcome is $frac(1, r)$. Instead, the probability of getting a non-multiple of $m$ is 0.
Let's consider the case of $N = m r$ for simplicity. In this case:
$
frac(y, N) = frac(j_0 dot cancel(m), cancel(m) dot r_0) = j_0/r_0
$
therefore:
- if $gcd(j_0, r_0) = 1$, then $r = r_0$ is the period of $f$;
- if $gcd(j_0, r_0) != 1$, then $r_0$ is not the period of $f$, but it's one of its *factors*, so:
+ we store this value $r_0$;
+ we repeat the procedure again, getting another value $r_1$;
+ if $f(x_0 + r_0 r_1) = f(x_0)$ then $r = r_0 r_1$ is the period of $f$, otherwise we will repeat again the procedure
#highlight(fill: yellow)[Quantum period finding using the QFT is a generalization of the Simon's problem. Here we deal with the standard sum operation], i.e. we have a function $f$ for which $f(x + y) = f(x) <=> x - y = k r$. #highlight(fill: yellow)[In the Simon's problem instead we dealt with the *modulo 2 sum* operation], i.e. the function was $f(x plus.circle y) = f(x) <=> x plus.circle y = a$.
=== Why we need the QFT
One may think that we should have stopped at this point:
$
ket(psi)_n = frac(1, sqrt(m))sum_(k = 0)^(m - 1)ket(x_0 + k r)ket(f(x_0))_(n_0)
$
We could have repeat the process multiple times to get multiple values $x_0_i + k_i r$, then we could have found $r$ pretty easily.
But this is not true, because not only the $k$ is different between these values, but also the $x_0$, so a simple subtraction would not reveal nothing about $r$, e.g.:
- measurement 1 gives $x_0 + k r$;
- measurement 2 gives $x_0^' + k^' r$
$
x_0 + k r - (x_0^' + k^' r) = x_0 - x_0^' + (k - k^')r
$
which is useless to get information about $r$.
= Quantum error correction
Quantum computers provide a significant speedup for specific problems, but they are also extremely *fragile*. This fragility highly impacts the practical usage of quantum computers.
Avoiding errors in quantum computers would require an unrealistic degree of isolation from the environment, therefore *error correction* is unavoidable.
Error detection (and correction) may seem impossible in quantum systems at first glance:
- if we measure the state to try to detect an error, we destroy it in an irreversible way;
- quantum information cannot be *cloned*;
- errors in quantum systems can be much more subtle than the ones that may occur in a classical system. In this last case, all can happen is a *bit flipping error*. In a quantum system instead we have to deal also with *phase errors*, which are much more subtle
But despite all of these, quantum error correction is nonetheless possible.
== Three-qubit encoding
In this scheme, each logical qubit is encoded using multiple (3, in this case) physical qubits:
$
ket(psi) = alpha ket(0) + beta ket(1) = alpha ket(000) + beta ket(111) equiv alpha ket(overline(0)) + beta ket(overline(1)) in cal(S)
$
We can represent a *single bit flip* in one of these physical qubit as an $ubs(X)$ gate:
$
ket(psi_0) = ubs(X)_0 ket(psi) = alpha ket(001) + beta ket(110) in cal(S)_0 \
ket(psi_1) = ubs(X)_1 ket(psi) = alpha ket(010) + beta ket(101) in cal(S)_1 \
ket(psi_2) = ubs(X)_2 ket(psi) = alpha ket(100) + beta ket(011) in cal(S)_2
$
$cal(S), cal(S)_0, cal(S)_1$ and $cal(S)_2$ are different subspaces and they are mutually disjoint. So an $ubs(X)_i$ gate applied on state $ket(psi)$ transfers the state into a different subspace.
#figure(
image("assets/5bce12a35f007b94c0d5abc08b3f93ba.png", width: 40%),
caption: [Representation of subspaces]
)
Since all these subspaces are mutually disjoint, a *suitable measurement* can detect in *which* state the qubit is without altering it. The measurement scheme we are looking for has to discriminate between the subsystems, but not within each subsystem. In other words we want to know if we are in state $cal(S)$ (no error occurred) or in one of $cal(S)_0, cal(S)_1, cal(S)_2$, but we don't want to know in which state $cal(S)_i$ we are, because a measurement that returns this information would destroy the qubit.
To perform this discrimination, a single-qubit measurement is not enough. A two-qubit measurement must be used to unambiguously identify the error.
#figure(
table(
columns: (auto, auto, auto, auto, auto, auto, auto, auto, auto),
[], [$ket(000)$], [$ket(111)$], [$ket(001)$], [$ket(110)$], [$ket(010)$], [$ket(101)$], [$ket(100)$], [$ket(011)$],
[$ubs(Z)_2 ubs(Z)_1$], [$+1$], [$+1$], [$+1$], [$+1$], [$-1$], [$-1$], [$-1$], [$-1$],
[$ubs(Z)_1 ubs(Z)_0$], [$+1$], [$+1$], [$-1$], [$-1$], [$-1$], [$-1$], [$+1$], [$+1$]
),
caption: [Possible outcomes for $ubs(Z)_2 ubs(Z)_1$ and $ubs(Z)_1 ubs(Z)_0$ measurements]
)
By looking at the table above, it's evident that each subsystem $cal(S)_i$ (i.e. each pair of columns) has a different outcome, therefore we can discriminate between the subsystems.
The values of $alpha$ and $beta$ are not accessed, therefore the linear superposition is preserved. This measurement does not destroy the quantum state.
The two measurements commute:
$
(ubs(Z)_2 cancel(ubs(Z)_1))(cancel(ubs(Z)_1) ubs(Z)_0) = ubs(Z)_2 ubs(Z)_0 = ubs(Z)_0 ubs(Z)_2 = (ubs(Z)_1 ubs(Z_0))(ubs(Z)_2 ubs(Z)_1)
$
The application of $ubs(X)_k$ restores the original state:
$
ubs(X)_k ket(psi_k) = ket(psi)
$
== Single- and two-qubit observables
A generic two-qubit initial state is given:
$
ket(psi) = alpha_00 ket(00) + alpha_01 ket(01) + alpha_10 ket(10) + alpha_11 ket(11)
$
#figure(
table(
columns: (auto, auto, auto),
[*outcome*], [*probability*], [*state after measurement*],
[$+1$], [$p = |alpha_00|^2 + |alpha_10|^2$], [$ket(psi') = frac(1, sqrt(p))(alpha_00 ket(00) + alpha_10 ket(10))$],
[$-1$], [$p = |alpha_01|^2 + |alpha_11|^2$], [$ket(psi') = frac(1, sqrt(p))(alpha_01 ket(01) + alpha_11 ket(11))$]
),
caption: [Result of measurement of $ubs(Z)_0$]
)
#figure(
table(
columns: (auto, auto, auto),
[*outcome*], [*probability*], [*state after measurement*],
[$+1$], [$p = |alpha_00|^2 + |alpha_01|^2$], [$ket(psi') = frac(1, sqrt(p))(alpha_00 ket(00) + alpha_01 ket(01))$],
[$-1$], [$p = |alpha_10|^2 + |alpha_11|^2$], [$ket(psi') = frac(1, sqrt(p))(alpha_10 ket(10) + alpha_11 ket(11))$]
),
caption: [Result of measurement of $ubs(Z)_1$]
)
#figure(
table(
columns: (auto, auto, auto),
[*outcome*], [*probability*], [*state after measurement*],
[$+1$], [$p = |alpha_00|^2 + |alpha_11|^2$], [$ket(psi') = frac(1, sqrt(p))(alpha_00 ket(00) + alpha_11 ket(11))$],
[$-1$], [$p = |alpha_10|^2 + |alpha_11|^2$], [$ket(psi') = frac(1, sqrt(p))(alpha_01 ket(01) + alpha_10 ket(10))$]
),
caption: [Result of measurement of $ubs(Z)_0 ubs(Z)_1$]
)
The point here is that the coherence of $ket(psi)$ is destroyed, but the linear superposition between *pair* of states is preserved after the measurement.
== Two-qubit observables and three-qubit states
Generic three-qubit state:
$
ket(psi) = sum_(x_2, x_1, x_0 = 0, 1)alpha_(x_2, x_1, x_0)ket(x_2\, x_1\, x_0)
$
#figure(
table(
columns: (auto, auto),
[*outcome*], [*state after measurement*],
[$+1$], [$ket(psi') = frac(1, sqrt(p))sum_(x_2 = 0, 1)(alpha_(0, 0, x_2)ket(x_2\, 0\, 0) + alpha_(1, 1, x_2)ket(x_2\, 1\, 1))$],
[$-1$], [$ket(psi') = frac(1, sqrt(p))sum_(x_2 = 0, 1)(alpha_(0, 1, x_2)ket(x_2\, 0\, 1) + alpha_(1, 0, x_2)ket(x_2\, 1\, 0))$]
),
caption: [Result of measurement of $ubs(Z)_0 ubs(Z)_1$]
)
#figure(
table(
columns: (auto, auto),
[*outcome*], [*state after measurement*],
[$+1$], [$ket(psi') = frac(1, sqrt(p))sum_(x_0 = 0, 1)(alpha_(x_0, 0, 0)ket(0\, 0\, x_0) + alpha_(x_0, 1, 1)ket(1\, 1\, x_0))$],
[$-1$], [$ket(psi') = frac(1, sqrt(p))sum_(x_0 = 0, 1)(alpha_(x_0, 0, 1)ket(1\, 0\, x_0) + alpha_(x_0, 1, 0)ket(1\, 0\, x_0))$]
),
caption: [Result of measurement of $ubs(Z)_1 ubs(Z)_2$]
)
When combined, $ubs(Z)_0 ubs(Z)_1$ and $ubs(Z)_1 ubs(Z)_2$ cut the Hilber space in four 2-dimensional subspaces.
== Implementation on a quantum circuit
This implementation requires some *ancillar qubits* prepared in state $ket(0)$. Then a sequence of 2 CNOTs is applied (one for each measurement) and the state of the ancillars is measured.
#figure(
image("assets/849faead64c6f3f160ec32f584328f29.png", height: 39%),
caption: [Implementation of 2-qubit measurements]
)
In this circuit:
- the two ancillars + qubit 0 and 1 + CNOT 1 and 2 + M1 implements the measurement $ubs(Z)_2 ubs(Z)_1$;
- the two ancillars + qubit 1 and 2 + CNOT 3 and 4 + M2 implement the measurement $ubs(Z)_1 ubs(Z)_0$
Combined together, these measurements give two possible outcomes. Each outcome corresponds to a pair of qubits in the linear superposition.
== Encoded quantum gates
Quantum gates too can be encoded using the 3-qubit encoding:
$
overline(ubs(X)) = ubs(X)_0 ubs(X)_1 ubs(X)_2 quad quad overline(ubs(Y)) = i overline(ubs(X) ubs(Z)) quad quad overline(ubs(Z)) = ubs(Z)_0 ubs(Z)_2 ubs(Z)_2 quad quad overline(ubs(H)) = frac(1, sqrt(2))(overline(ubs(X)) + overline(ubs(Z))) \
$
In fact:
$
overline(ubs(X))ket(overline(0)) = ubs(X)_0 ubs(X)_1 ubs(X)_2 ket(000) = ket(111) = ket(overline(1))
$
and so on.
== General principles in quantum error correction
We start from a space $cal(S)$, we apply our gates for the computation and, if no error occurred, we are still in $cal(S)$. Each possible error instead maps $cal(S)$ to a different 2-dimensional subspace $cal(S)_i$.
In order to discriminate between these subspaces, the size of the Hilber space $2^n$ should be bigger than $2(1 + n)$, which is the size of $cal(S)$ plus the size of all $cal(S)_i$. This is the reason why we need $n >= 3$ qubits to perform error correction.
The measurement identifies the subspace $cal(S)_i$, but it does not provide clues about coefficients $alpha$ and $beta$.
== 5-qubit error-correcting code
We have an *observable* which can be written as a sum of eigenvalues and eigenstates:
$
A = sum_i a_i ketbra(a_i)
$
If the outcome of the measurement is $a_i$, the state of this observable will collapse to $ket(a_i)$.
Now, let's consider a general case in which all errors can happen, not just a bit flip. These errors can be sumarized by a single application of an $ubs(X), ubs(Y)$ or $ubs(Z)$ gate.
We need therefore to find the value of $n$ for which $2^n >= 2(1 + 3n)$ (the $n$ is now multiplied by 3 because there are 3 types of error that can happen). This $n$ is the number of *physical* qubits we need to encode a single logical qubit.
The solution is $n >= 5$.
We need also a *set of measurements* which allows us to discriminate between the subspaces $cal(S)_i$. We need 4 different measurements, because $k >= 4$ is the one that satisfies the condition $2^k >= 3n + 1$.
Each measurement has to satisfy these properties:
- it must be equal to the identity operator $ubs(1)$ when squared;
- they should *commute* with each other
An example of such set of measurements is this one:
$
ubs(M)_0 = ubs(Z)_1 ubs(X)_2 ubs(X)_3 ubs(Z)_4 quad quad ubs(M)_1 = ubs(Z)_2 ubs(X)_3 ubs(X)_4 ubs(Z)_0 \
ubs(M)_2 = ubs(Z)_3 ubs(X)_4 ubs(X)_0 ubs(Z)_1 quad quad ubs(M)_3 = ubs(Z)_4 ubs(X)_0 ubs(X)_1 ubs(Z)_2
$
Now that we have a set of measurements, we can encode our logical bits:
$
ket(overline(0)) = 1/4(1 + ubs(M)_0)(1 + ubs(M)_1)(1 + ubs(M)_2)(1 + ubs(M)_3)ket(00000) \
ket(overline(1)) = 1/4(1 + ubs(M)_0)(1 + ubs(M)_1)(1 + ubs(M)_2)(1 + ubs(M)_3)ket(11111)
$
$ket(overline(0))$ and $ket(overline(1))$ are orhogonal because each $ubs(M)$ flips two qubits, so they have an even and odd number of qubits in state 1 respectively.
These states are normalized. We can check it with the bra-ket product:
$
braket(overline(0)) & = 1/16braket(00000, [(1 + ubs(M)_0)(1 + ubs(M)_1)(1 + ubs(M)_2)(1 + ubs(M)_3)]^2, 00000) \
& = braket(00000, (1 + ubs(M)_0)(1 + ubs(M)_1)(1 + ubs(M)_2)(1 + ubs(M)_3), 00000)
$
where each $(1 + ubs(M)_i)^2 = 1 + ubs(M)_i + ubs(M)_i + ubs(M)_i^2 = 2(1 + ubs(M)_i)$ (because $ubs(M)_i^2 = ubs(1)$).
Our 4 operator $ubs(M)_i$ allow us to discriminate between 16 different subspaces: 15 with a corruption and 1 without:
#figure(
image("assets/155d0b07f3dca5fbf2058f2b4b0f10ab.png", height: 14%),
caption: [Outcome for each $ubs(M)_i$ and each possible corruption]
)
Each of these cases has a unique set of values for the $ubs(M)_i$ operators.
The table above shows the sign of the eigenvalues. If no error occurred, all eigenvalues are positive.
Differently corrupted states are orthogonal. To demonstrate this, one can use a measurement operator $ubs(M)_i$ that commutes with one of the error operators and anticommutes with the other one:
$
braket(overline(0), ubs(X)_0 ubs(Y)_0, overline(0)) & = braket(overline(0), ubs(X)_0 ubs(M)_2^2 ubs(Y)_0, overline(0)) \
& = braket(overline(0), (ubs(M)_2 ubs(X)_0)(-ubs(Y)_0 ubs(M)_2), overline(0)) \
& = -braket(overline(0), ubs(X)_0 ubs(Y)_0, overline(0))
$
#figure(
image("assets/1cff48fafacd5458c13c45c0531f42c8.png", height: 19%),
caption: [Circuit that implements a measurement $ubs(M)_i$]
)
In the circuit above, $A$ is the observable and $ubs(P)_0 = 1/2(1 + A)$ and $ubs(P)_1 = 1/2(1 - A)$ are the projectors on the eigenspaces corresponding to $a_1 = +1$ and $a_2 = -1$ respectively. |
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/049%20-%20The%20Brothers'%20War/010_Episode%205%3A%20As%20Cruel%2C%20As%20Necessary.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 5: As Cruel, As Necessary",
set_name: "The Brothers' War",
story_date: datetime(day: 26, month: 10, year: 2023),
author: "<NAME> & <NAME>",
doc
)
#strong[4562 AR]
Teferi lay shirtless in a cold metal coffin, counting his breath. How much time did he have before transmission? A minute at most, though it felt like an eternity.
A quick double knock on the lid of the coffin. Kaya, asking if he was ready.
It had been a month and some days of testing, of venturing back an hour, a day, a week at a time, ensuring that nothing changed, that the secret phrases Kaya and Saheeli wrote down and planted days prior were accurately reported back to the present; a month of this and Kaya still asked if he was ready. If he was okay. Teferi smiled inside the coffin, a soft and sad smile. These new walkers were different from the ones he had come up with. More human—even if they weren't human.
Teferi knocked twice on the inside of the lid. He was ready.
A faint purple glow spread before him, brightening his vision with ultraviolet and deeper shades. A lightness tingled his fingertips, his toes.
A comforting thought, should he not return: Kaya would lead them all. She and Elspeth, and Jace besides. Good hands. Teferi exhaled and tried to get comfortable. He thought of Wrenn and her songs.
The metal never seemed to warm, no matter how long he lay on it. How long did #emph[The Antiquities] #emph[War] say Tawnos was in his coffin? Five years?
"You can ask him," Kaya said. Her voice was faint, sibilant in his mind. He couldn't hear her—she spoke through him, for him. In this middle stage between corporeal and insubstantial, there was less and less of a distinction between the two of them.
Teferi laughed, Kaya laughed. They couldn't stop themselves—the nerves, the fatigue. Kaya was his medium; she was already in his head. More accurately, #emph[he] was in #emph[hers] .
"Remember," Kaya whispered. "Concentrate on the sky. Find the deepest dark."
Teferi did. The Temporal Anchor's humming climbed another step.
"Time is a tapestry, and you are a needle."
Piercing. Howling.
The coffin started to grow hot. Teferi's breath came faster. He couldn't hear anything but the layered tones of the anchor rising. He heard Kaya and Saheeli shouting across the cacophony to each other, Kaya's voice echoing in his own mind.
He never got used to this part. He hated this moment, this tearing of his spark and soul from his body—
"Go."
#figure(image("010_Episode 5: As Cruel, As Necessary/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
He felt his body slip away,
and with it the cold metal
of the facsimile coffin.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The mission was not the problem. They had their target identified, and they knew where to look for answers. They had power, they had weapons, they had knowledge, and they had allies. Crucially, they had a new sylex.
The problem was they didn't know how to #emph[use] the damn thing.
Saheeli had built an essentially perfect replica from Karn's plans and notes, but for all her brilliance she remained only an engineer. The mystery of the sylex's activation was not mechanical—it was magical, a spell buried in history, and history was unreliable.
To wit:
The Golgothian sylex had first been created or discovered by Feldon, a scholar of languages and ancient glaciers, some decades before the Brothers' War. As well, it had been created by Ashnod, carved from the skullcap of the qadir her master, Mishra, replaced. Also, it had been pulled from Old Phyrexia's deepest ichor well by Gix, a demon who slouched to Dominaria out from dreams of steel and oil. Also, the sylex had been chiseled from a giant's tooth and kept by the kobolds of the Khers; as well it was one of Tal's hardened tears, the spell-frozen corona of a falling star, the melted heart of a mountain hammered into shape by Sardian dwarves, and so on, and so on.
The myths of that old world-ender's beginning filled reams, and there was no way to tell which one was true. Likewise, for the sylex's end.
Karn believed his to be the real one, but histories Teferi had dug up spoke of the sylex being destroyed by Urza, or shattered by J<NAME>, or consumed by a great and long dead dragon, or tossed into a lake as tribute to some icebound god.
By Teferi's reckoning there were four or five sylexes worth following up on, and contradictory histories for all of them: thus, the anchor, the needle, and the tapestry.
"So how do we find it?" Saheeli asked. She had a direct, solutions-focused mode that Teferi appreciated in a crisis.
Teferi looked out over the papers, scrolls, manuscripts, etchings, and ancient tomes spread before him. They covered the old drafting table, a layer of history encompassing thousands of years of Dominarian legend. All of them were useless, he thought, save for one.
Teferi reached out and shoved the histories aside, knocking some to the floor as he searched. He had read and discarded it early on—not for a lack of craft, but for a lack of specifics.
Saheeli said nothing. She arched an eyebrow and watched the time mage throw valuable texts into musty corners until he stood, triumphant, holding a mold-scarred manuscript.
"#emph[The Antiquities War] ," Teferi said. He slapped the papers on the table and opened them. "Here," he said, stabbing a finger on the moldering epic. "Urza's wife, <NAME>-Kroog, wrote this epic chronicling the history of the war she herself bore witness to. There are many versions and translations, but they all end the same way: Urza activated the sylex on Argoth and ended the war." Teferi looked up at Saheeli. "We go here—the last battle of the Brothers' War."
"Good enough." Saheeli nodded. "I'll get to work."
#figure(image("010_Episode 5: As Cruel, As Necessary/02.jpg", width: 100%), caption: [Art by: Kekai Kotaki], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
He felt her there with him
He was her needle through time,
a spirit who echoed, echoed,
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Echoed.
Urza, this coffin, the sylex, the Phyrexians—threads enough for Teferi to be sure that there was some greater cosmic architecture, some logic animating this moment that even he could not hope to understand. Fate's unknowable tempo moving not just Teferi, but all of them in a grand orchestration through history. All Teferi could do was look backwards through his furrowed path and hope that something in his wake would hint at what was to come.
Teferi kept this worry private. It would not be reassuring to his friends and allies to see the consummate chronomage so reduced. To know he was a captain standing blindfolded at the rudder, only a sailor who had not once been to sea.
At night he stood alone in his room near the top of old Urza's tower, staring at the worn floor, unable to sleep.
Teferi was just as lost as the rest of them.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The darkness was absolute,
He floated, a
Alone?
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Teferi's head ached. With all this temporal sojourning, he hadn't slept well in weeks. Or maybe he did—maybe he had been asleep this whole time. He didn't remember.
In the coffin Teferi wore a blindfold over his eyes and a simple set of underclothes. A bandage wrapped around his midsection. Though it had been some time and Elspeth had laid on hands and treated his wound with Halo, the Phyrexian creature had wounded him deep. He felt its ache when he breathed, though this, too, he kept to himself. Whether phyresis gnawed away at his marrow or the Phyrexians threatened the barricaded doors of this chamber, the approach of death was steady and unstoppable. Unless—
Echoes. Time. History repeating itself, with variations. Teferi did not know whether the creature that carved him open had left glistening oil in him. He did not know if Elspeth, Wrenn, Jodah, and the others would fail to hold them back now. All he could do was play his part.
Teferi managed his breathing. He didn't know when now was.
Had he died? Or was there someone else in the darkness with him?
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Count the beats
One, two, three, four,
What was taking him so long—
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
All Teferi had learned from time travel was the easy and true joke: it was only possible to go forward, once, and only at the pace of life.
Urza cracked this axiom. Teferi had been there and knew that it cost nearly everything. Since his own brush with time, he had stayed away from violating that law. Manipulating time was casting sparks in a drought-dried ocean of grass: conflagration was all but assured. The only thing left to chance was the might of the fire that would follow.
But when the field was already burning? When the fire had already swallowed up everything?
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
for both
the needle and its thread, flashing—
Once set in motion, you can't stop it
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Silver.
Silver could evade time's ironclad law. Urza discovered that silver could travel physically back in time, made Karn and, Teferi supposed, started this whole affair.
Physical travel was not what Teferi and the others needed or desired. Physical travel would be the same as standing in the conflagration and dousing oneself with lamp oil. No, they didn't need to go back themselves—they only needed to #emph[see] what occurred.
Saheeli had cracked the problem. Forgo the silver; if you're heading into a conflagration, go as a spark. By extracting one's spirit and casting that back, one would be unable to interact with the past while remaining able to observe—the flipside must also be true, or at least not false.
On paper, this made sense.
So had Urza's plan, Teferi reminded himself—and how did that end? Tolaria in flames, rifts torn in time, that endless lingering. Had there not been a threat so great to warrant this endeavor, Teferi would never have agreed to undertake this expedition.
Had there not been a threat so great, Urza never—
Yes, yes, Teferi thought. Of course.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
And in the end? What
would they both say of their timelessness?
It was like falling, like dancing.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[85 AR]
Teferi arrived in a dark room in a flooded city that he would later learn to be Kroog.
There, he watched a brutal man go mad and scream about ghosts and assassins. This was worrying: no one should be able to see him. None of the tests they ran indicated that anyone could see him as a spirit.
Teferi departed; anyway, this was not the moment he was looking for.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[28 AR]
Teferi stood in a dark alley under a burning sky. He was back in Kroog. He recognized it immediately from the towers: during his first visit they were crumbled ruins. Now, they stood proud above a city under siege. The bells thundered above rising screams.
The dead were everywhere.
This was not the Last Battle, but Teferi lingered for a moment. A soldier, a boy in what Teferi would later learn to be a Fallaji uniform, reached out to him. He said something over and over, a plaintive word that, while Teferi told himself he did not understand, he knew he understood.
"Father," the boy gasped. The boy died.
Teferi stood, jaw clenched. His body back in the coffin twitched, as one does when they are dreaming.
"Not yet," he whispered.
Kaya, who saw everything Teferi saw, never spoke about this moment to anyone.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[44 AR]
Teferi walked through a charnel valley somewhere southeast of Tomakul. This was the same war as the one he saw days prior, now decades later. Metastasized to its mechanized apex.
Long, deep trenches striated the land. If Teferi could fly above it, he would look down on a world rippling with muddy scars. Machine and human corpses were thick as crops in a farmer's field, draped over trench and wire, twisted and broken. Between them marched columns of soldiers laden with packs under rain-slicked coats. These were armies of men more dead than alive, as spectral in soul as Teferi was in body.
#figure(image("010_Episode 5: As Cruel, As Necessary/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Once the armies passed, ghouls stalked the fields of the dead, harvesting the bodies they found useful. Teferi watched as black-clad and shuddering figures loaded crude, wheeled carts with human and machine corpses, hauling them away toward Tomakul, until one of them saw him.
Teferi departed, steeling himself. If this unremembered field had seemed to him a circle of hell, then what terrors did the Last Battle hold?
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[4562 AR]
Teferi, Kaya, and Saheeli sat around the open coffin, Teferi eating while Kaya and Saheeli drank coffee. It was some horrible time between night and morning. None of them slept anymore.
Outside it was quiet. Kaya told Teferi that Elspeth had been in an hour or two before he emerged. She had asked about his progress and told them that the Phyrexians were close.
"What does 'close' mean?" Saheeli had asked her.
"Bar the door when I leave," Elspeth had responded. She had been on the line with the other Planeswalkers, and her voice was hoarse from shouting over the sounds of combat.
Time was running out. Success or failure, they were stuck inside until the end.
"I found it," Teferi said, breaking the silence.
"When?" Kaya asked.
"When I was coming back," Teferi said. "I saw it, like a scar. Part of the tapestry blotted out, like ink spilled on a page. Blotted time. I haven't been to that one yet."
Kaya nodded. She didn't need an explanation.
"The anchor might not be able to take another sojourn," Saheeli said. Her voice was softest of the three of them, but it carried best in this cold and vaulted room.
"What happens if the anchor fails while he's inside?" Kaya asked.
"I don't know," Saheeli admitted. "I would guess that he dies. His body dies, at least. His spark," she waved her hand, fingers dancing toward the ceiling. "Nothing good."
"And her?" Teferi said, nodding toward Kaya. "She is my medium—she's back there with me. What would happen to her?"
"Teferi, I only built the anchor," Saheeli said. "I'm an engineer. I know how it #emph[could] fail. The anchor's powerstone could erupt, or the temporal bridge would collapse. The coffin would overheat and implode." Saheeli sipped her coffee. "I know how machines break," she said, "not what happens to a soul when it is severed from its body."
They let Saheeli's words be the last on the topic. They finished their coffee and small foods. Wordlessly, Teferi slid back into the coffin and draped the cloth back over his eyes.
"Ready?" Kaya asked Saheeli.
"Ready," Saheeli agreed.
"Teferi?"
"Let's go," Teferi said. "I'll see you all in a little while."
Kaya closed the coffin lid. In the darkness, Teferi slipped away.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[63 AR]
#emph[Urza sat cross-legged with the bowl in his lap. The runes within the bowl spiraled toward the center. Blood from the gushing wound on his forehead dribbled into the bowl and filled the carved runes with crimson.]
In the present day, Kaya whispered her dialogue with Teferi, relaying everything that he saw. Her voice had a deeper resonance, a layering that placed Teferi's voice under her own. Saheeli, though she was occupied with running the anchor, could not help but listen.
"The blood from the cut on Urza's forehead is dropping into the bowl, filling the runes. He's sitting cross-legged with the bowl in his lap," Kaya muttered. She swayed, sweating, hands placed on the coffin.
#emph[The Mishra machine had recovered from the avalanche and was now charging up the hill, its dragon head screaming. Urza looked up and saw his brother's face, half-torn from the metallic skull beneath, and wept for him.]
#figure(image("010_Episode 5: As Cruel, As Necessary/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"His brother is close to him. It could be triggered by a kind of sympathetic resonance between the two. Maybe it takes more than one person focused, some heightened emotional state—or could it be the proximity of Phyrexian technology," Kaya said.
"What else?" Kaya asked.
"Tears. Lots of tears. Urza never cried. He's so~ human, here," she replied.
#emph[The Mishra machine had attained the hilltop now, and its serpent head loomed high above them. Mishra was grinning, the smile half-flesh and half-steel. It was the grin of a man triumphant.]
#emph[Mishra was screaming something.]
#emph[A flash at the base of the bowl—]
#emph[A flash at the base of the bowl—]
#emph[A flash at the base—]
#emph[A flash—]
"STOP!"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[4562 AR]
Teferi slipped back to the present.
He barely made it out of the coffin before he retched, coughing out a thin mix of water and salt crackers onto the cold stone floor of the chamber. He trembled, the wound at his side aching. Behind the blindfold he wore against the brightness of the real world, a kaleidoscope of color pinwheeled.
"I almost have it," he lied as Kaya helped him out of the coffin. "I think it has to do with the blood, or maybe the depth of the grooves. Saheeli," Teferi shouted. "Does your sylex spiral? The runes?"
"Of course it does," Saheeli shouted back from the base of the anchor, where she was busy making small adjustments and repairs.
Kaya pressed a cold towel to Teferi's forehead. "Listen," she said, steadying him as he swayed. "What we're seeing back there—what your spirit is exposed to—it's brutal."
"Do we have time to rest?" Teferi asked.
"Eat," Kaya said, ignoring the question.
Teferi ate a small amount, as much as his stomach could handle. He took a sip of water, then climbed back inside the coffin. The sound of fighting outside the chamber went unremarked.
"Hurry," Kaya said. "Please. This is difficult for me as well." Her usual demeanor, her devil-may-care attitude was gone.
Kaya was right and Teferi knew it. As his medium, she may as well have been right there with him every time he cast back.
"Give me as much time as you can," Teferi said.
Kaya looked at the barricade they had piled against the chamber door, then back to Teferi. "Last one," she said. She closed the coffin lid and slammed its latches locked.
In the quiet of the stasis coffin, Teferi felt he could be anywhere. It was warm now, comfortable, and stank of his sweat. He exhaled and waited for Kaya to do her work.
Two soft taps on the lid of the coffin—her hands. A purple whorl, spreading like silent fire across the inner lid, bright through his blindfold.
His body dropped away. He was anywhere.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
A division between real-time—that is, what Teferi thought of as the present day, which he could not see beyond—and #emph[back then] . With the aid of Saheeli's Temporal Anchor and Kaya's extraction and mediumship, it was an easy enough task for Teferi to step between real-time and back then; the difficulty was fatigue and navigation. He could go back to any point he could remember but had to discover the moment first. The travel left him exhausted and weak.
Teferi, as best he could, set his fears aside. He tried to let the task at hand replace them. A month of meticulous searching, and he had finally found the moment he needed when it was most desperate. The Phyrexians were, quite literally, at the door.
Alone Teferi stood under a firmament his mind told him was a night sky and searched it for the dark nebula he knew to be the Brothers' War. He found it and stepped inside, his spirit crossing millennia with a thought. Inside that space was a manifold darkness, a nothingness patterned with textures Teferi had only just begun to comprehend.
He found the curious one, the stygian blot he hoped was the Last Battle, and—as a needle plunging through cloth—dove inside.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
A black sky. A rain-lashed beach. Ticking and twitching metal ruins, still dragging themselves toward their enemies. Two titanic constructs collapsed across each other over the wild-burning old growth. Behind him, oil-slick waves crashed and roared, dragging dead bodies up and down the stained sand.
Argoth. The Last Battle. Moments before the end of the world, again.
#figure(image("010_Episode 5: As Cruel, As Necessary/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[63 AR]
#emph[The Mishra machine had attained the hilltop now, and its serpent head loomed high above them. Mishra was grinning, the smile half-flesh and half-steel. It was the grin of a man triumphant.]
#emph[Mishra was screaming something.]
#emph[A flash at the base of the bowl—]
Everything stopped.
That was not entirely accurate. Everything slowed. With a gesture, Teferi divided time's progression by halves down to an infinite number. Time, as much as Teferi could observe, froze.
Command over time was an awesome power. Godly. Teferi knew it to be ruinous, so he was a careful practitioner. He had thought the answer lay in observation, in taking special care with this moment to note every detail of Urza's movements, emotions, and words. There was so much he did not know, so he tried to observe and report on every single thing—even the rain, just in case that was a component of the spell.
All his care rewarded him with nothing. None of what he saw even so much as warmed the bowl of Saheeli's facsimile sylex. He had to find some way to step beyond.
Teferi thought of a way. It was a risk. Was this not a risk? Everything could go wrong, yes, but back in his time everything was already going wrong: Karn was gone, the Phyrexians were on Dominaria again, Jaya was dead, their last redoubt was about to fall. What was the worst that could happen? Teferi thought. The end of the Multiverse?
Circumstances pushed him to be reckless. That infinite halving that protected him also distanced him; he needed to align his time with Urza's.
It was a terrible risk. Teferi weighed what he knew: Urza did not die when the sylex detonated. No one knew how he came back or when, but Teferi knew him when he was young. He had studied under him at the Tolarian Academy. However, just because Urza lived it did not mean Teferi—even as a spirit—could withstand the sylex's blast. That artifact was more than just a bomb: the Shard of Twelve Worlds, the Ice Age, every important event over the last four millennia—everything came after this moment. His family came after this moment. If Teferi could have taken a deep breath, he would have. A thought, as he acted: existence is not guaranteed.
Teferi stopped holding back time.
The Multiverse tore open.
Everything came after.
#figure(image("010_Episode 5: As Cruel, As Necessary/06.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[??????]
What remained of Urza sat cross-legged on a scrape of Argothian earth. The sylex was balanced on his lap, its bowl filled with white, scouring light frozen in bloom.
Teferi stood a short distance away, a spirit in soft hues. He could see little of Urza behind the light emitting from the sylex, but enough to make out the Planeswalker's silhouette inside the detonation.
Together, the two of them were alone in an empyrean void. The ground underneath them was a small patch of Argoth, and then blank nothingness in all directions. To Teferi, it looked as if they were standing within the belly of a cloud.
Urza. How long had it been since Teferi had last seen him? How many lifetimes, how many lives? Teferi walked over to Urza and sat opposite the sylex. He cleared his throat.
"I need to tell you some things about the future," Teferi said to Urza. "Your future, my present. It concerns everything."
Urza looked up, his face a raw, grinning skull. "What?" he said, his voice unburnt.
"They won't be good things," Teferi emphasized.
"Curious," Urza said. He looked at the sylex, at the light creeping out from an illuminated point in the bowl's nadir, then out at the space that surrounded them. "One does not expect happy news in a formless void," he muttered. "Is this the afterlife?"
"No," Teferi said. "I hope not."
"Fine, then," Urza said. "Who are you?"
"In a moment—I need to ask for your help."
"You said you are from my future," Urza said, ignoring Teferi's insistence. "That you need my help. How do you know whether you talking to me will change anything?" Urza waved at the vastness of eternity. "Or worse—maybe it will change everything."
Teferi hesitated. "I'm not sure," he said. "We had to take this chance."
"We," Urza said. A question, posed as a comment. "Either what you're going to tell me matters a great deal, or it doesn't matter at all."
"That seems so," Teferi muttered. The two men fell silent. They looked once more at the sylex, that ruinous thing.
"You should know first that you are a great man now," Teferi said. "But you're nothing like what you will become." He tapped the edge of the sylex. The solid core of the light, tense as brimming water at the bowl's lip now, wobbled. That light was doom, Teferi thought. He was staring at the end of one age and the dawn of another.
"And what is that?" Urza asked. He cradled the bowl in his lap. Most of him was burned away by the sylex's detonation, but he did not appear to be in pain. Blackened flesh peeled back to expose scoured bone, and where there was nothing there was a brighter light—a spark, coalescing.
His spark. In this moment, Urza was becoming what he would become.
"Some would probably call you a god." Teferi thought back to his school days. "Others would call you a curse. I called you my teacher; most know you as 'Planeswalker.'"
Urza could not smile anymore—his skull had blackened and crumbled, his shoulders and ribs burned to ash. And yet his voice was strong as when he was whole.
"There's nothing I can do to change that, is there?" Urza asked. He sounded exhausted, not plaintive. Fatigued as a man gone decades without sleep.
"If I'm here now," Teferi whispered, "I don't think there's anything you or I can do to change what will happen. Time does not pass like the hand of a clock: it's already happening."
"Then what is this," Urza said, gesturing at the formless void that surrounded them. He stood, staggering up to his feet, the whole of his torso tumbling in gray clumps of ash.
"Allow me to lecture for a moment?" Teferi asked.
"Take all the time you need," Urza said, a sarcastic snarl creeping into his voice.
Teferi, still seated, leaned back, resting as one does in a soft field of grass, as if soaking in the sun. "There are many metaphors for time," Teferi began. "All of them are true, to some degree. Together they form a mosaic of understanding." Teferi watched as Urza stepped to the edge of the ground. If he had features left, Teferi guessed he would be staring out into the void.
"There's something out there," Urza whispered. "Hurry."
"People say time flows like a river," Teferi said. "But that only imagines time moving #emph[forward] ."
Despite his evident frustration, Urza was curious. He listened as Teferi spoke.
"That is neither totally wrong nor totally right. It's just limited by our perspective. Humans, I mean. We have one angle into the prism of existence: we only ever see time going one way, so to imagine time as a river isn't wrong. And since we're all a part of this," Teferi waved a hand at the void around them, "our metaphor contains some of the truth. Rivers are agents of time's passage. They exist on a scale larger than us. They also hold mysteries: If we were to walk alongside any river—the Mardun, maybe—we'd come across places where it tumbles into whorls and eddies, shoots off on little branches that go nowhere, or join other rivers, or are snipped off into their own lakes. Those lakes are places where the river stops; if time is a river, then those lakes are moments where time stops." Teferi said "I think we're in one of those right now."
After a moment's pause, Urza finally spoke. "Why?"
Teferi smiled and shook his head. "No idea. I took a risk based off what I knew to be true—I'm just as surprised to be here as you are."
"You say in the future I become a teacher?"
"Many thousands of years from now," Teferi said.
Urza scoffed. "My pedagogy needs work," he said. Gruff, but not unkind. Teferi knew the Urza of his own youth in Tolaria well enough to know the old goat approved of his decision. "So, what's next?" Urza said. "What do I need to know so I can tell you what you need to know?"
"You're going to encounter more of them," Teferi said. He did not need to explain; Urza understood who "them" meant. His brother, and the demon from Koilos.
"You're going to spend your life trying to fight the Phyrexians. First for what they did to your brother, and then for what they will do to you."
"Is that what that thing is called?" Urza muttered. "A whole race of them~" He was too insubstantial to emote, but Teferi saw light creeping in at the raw edges where Urza's body once was, latticing through the burned void. In the empty sockets where his eyes once were, new light began to glow: one red, and one green.
Urza was being remade. Stitched together into something else.
Planeswalker.
"You lose," Teferi said. "The Phyrexians win. You fight them for millennia, but they always win. You discover there are more worlds than one, more than even you can count. Each occupies a plane of existence, and together they are bound up in a space called the Multiverse. You travel these planes for centuries and discover there are others who can travel them as well. Eventually, you establish a school—that's where we first meet, at this school—and you try to crack open the mysteries of time. You succeed but find you cannot go back."
"Then how did you manage it?"
"With great difficulty," Teferi said with a weary smile.
Skin filled in over Urza's light-woven scaffolding, raw and young, bleeding across to fill his features like a peach crushed on a white sheet. His lips re-formed in time for him to frown.
"Get to the point," Urza said. "Despite everything, I do not stop the Phyrexians. You are here having travelled through time in a way I could not. Why?"
Teferi could hear the pain in his old instructor's voice. Here he was, trapped at the moment of his death with a desperate man from the future who told him that his war did not end here. That his final act did not grant him any peace, but only unlocked a door holding back an even greater war, one whose trail of ruin was unavoidable, one that would stretch across thousands of years and claim countless lives. Had he been a kinder man, Teferi would have stopped talking. He would not have told Urza the truth.
Am I as cruel as he? Teferi wondered. As necessary? Time will tell.
"The Phyrexians are back," Teferi said. "In my time they threaten the whole of the Multiverse. As we speak, my body lies in your tower, surrounded by other Planeswalkers like us. The Phyrexians are attacking; they're trying to stop us from learning how to stop them before their invasion can begin."
Urza was nearly whole. "Why not go back to when I—when we—first beat the Phyrexians?" He asked. "What happened then that is so much worse than now?"
"No," Teferi said. He thought of Zhalfir. Of Shiv. Of the Mirage War. Of time torn apart and Urza's fury. "Not then. Never."
"Then why now?"
"The sylex," Teferi said. "In our time we have a facsimile of this one. Saheeli—a brilliant woman from a plane you would think is paradise—she recreated this very device: all we need to know how to do is activate it."
"You're going to use it against the Phyrexians?"
"Yes."
"And that will end this?"
"Yes."
Urza nodded. "Give me some room," he said, waving Teferi back. Urza approached the sylex and stood over it. The obliterating light would soon grow to eclipse the setting sun. He sat. He gripped the edge of the bowl and lifted it back into his lap. Once more his body began to smolder away, flaking into ash—this time revealing the lattice of light underneath.
Teferi recalled what power had been like before the Mending. The body was only a vessel: the spark was greater.
"I held it like so," Urza said. He was contemplative. His voice hitched for a moment as his upper body burned away again—and yet, though the light streaming from the sylex was overpowering, Teferi could still see Urza's silhouette within it, a brighter light somehow. A being refusing death.
"I let the blood from the cut my brother dealt me fall into it," Urza said. "I felt the weight of Terisiare on my heart," he thought for a moment. "I could hear the whole world crying out—I didn't need to read the runes here to understand what they meant." He traced a solar finger across the belly of the bowl. "There was a woman during the war—Hurkyl, of the College of Lat-Nam." Urza spoke aloud, but not to Teferi.
Teferi listened—anything Urza said could be the key.
"They said she could use magic," Urza shook his head. "I didn't believe the stories, but I was wrong. Hurkyl's meditation was real: a method by which one could make themselves a conduit for the~ soul of the land: love, pain, joy, fear, emotion, and memory. All of it, channeled through a single point. Through a single person, who could draw this power through them and project it into the world. This is what I called upon when I used the sylex. I had nothing left, and when I held this in my hands, I poured #emph[everything] into it. Then it all ended." Urza looked up at Teferi. "As soon as I held it, I knew what to do. That's all I can tell you."
Teferi understood. With horror, he understood. There was no unknown spell to discover, no secret mechanism by which Urza activated his sylex. Hurkyl's meditations were well documented. The runic carvings on the sylex had been cast and re-cast, etched in perfect replica on Saheeli's copy. It was all known and understood. They had everything they needed but the person. The trigger to detonate the sylex was not a spell or an artifact—it was a person.
"I think our time is up," Urza said, pointing into the void above Teferi's head.
They looked up toward the empyrean distance. Cracks spidered across the infinitude, silent and seeping. Against the blank unfathomable space, numberless, dark fingers began to probe. Shadows, pressing against this enclave. They were overstaying their welcome. Something was coming for them.
"Will I remember this?" Urza asked.
"No, I don't think you will," Teferi replied. "Our lake—it just becomes part of the river again."
"I thought as much." Urza stood. "Thousands of years of this," he whispered. "Gods, I'm not ready."
"You are," Teferi said. "You have to be."
Urza looked at Teferi, his eyes flashing ruby and emerald facets. "You never told me," he said. "What is your n—"
The void broke.
The dark rushed in.
#figure(image("010_Episode 5: As Cruel, As Necessary/07.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[64 AR]
And there was silence in Terisiare.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[69 AR]
What had once been a verdant coastline was now awash with debris. The flotsam of great trees and the jetsam of huge boulders had been driven miles into shore, creating a blasted region along the shore, devoid of life.
Among the wreckage was a large metal box, seven feet in length, three feet in width and height. It had weathered the destruction and came to rest among the other far-flung remains of what had been Argoth.
Urza stood alongside the box and pressed his hand against the lid.
#figure(image("010_Episode 5: As Cruel, As Necessary/08.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
The box's top slid along its casters, revealing the slumbering form of his former apprentice. Tawnos took a breath, then sat bolt upright, gasping for air. His face was pale, and he was covered with dead skin that had flaked off but had nowhere to go within his confinement.
Urza waited for Tawnos to regain his composure, standing as patient as a statue. Tawnos took a deep breath, held it, then took a second one. Then he looked around at the devastation that surrounded them.
"It is over," said Urza, sitting on the edge of the box.
Tawnos gulped and looked around. "This was the safest hiding place I could think of," he said. Urza did not reply. Tawnos said, "Your brother?"
"Dead," said Urza. "I~" He shook his head. "The demon, the Phyrexian, killed my brother long ago. I never realized it."
"Where are we?" asked Tawnos.
Urza looked around and sighed, deeply. "The southern coast of Yotia."
Tawnos blinked. "It has changed."
"The world has changed," said Urza, "because of what we did. Because of what I did."
Tawnos climbed out of the box, and Urza helped him. Tawnos felt weak from his incarceration and rubbed his arms and legs, both to shake off the dead skin and to restore circulation. It was cold on this shore, colder than Tawnos remembered it as a youth.
"I need one last task from you, my former student," said Urza.
"Name it," said Tawnos.
"I want you to go west. Find the remains of the Union, the scholars of the ivory towers. Tell them what happened here. Tell them what we did, and what we failed to do. See to it that they do not do the same. I trust you to do this."
Tawnos looked at the older man, but it seemed to him that Urza was no longer old. His hair was blond again and his shoulders straight. But his eyes were old beyond years and pained beyond mortal hurt.
"You can always trust me," said Tawnos. "Where are you going?"
Urza turned from his former pupil. "Away," he said after a short while. "I am going~ away."
"It looks as if we could use your help here," said Tawnos. Urza made a noise that Tawnos thought was a nervous laugh. "I don't think the land could survive any more of my help. I need to~ I need to go away. And think by myself. Where I will not harm others."
Tawnos nodded, and said, "I don't know if there is any place that far away."
Urza shook his head and said, "There are places far beyond the land of Terisiare, far beyond the world of Dominaria. When I poured my memories into the sylex, I saw them. I see many things that I had never seen before."
He turned back to Tawnos, and the Master Scholar saw Urza's eyes. They were no longer human eyes, but rather two gemstones, radiating with a cascade of multicolored hues: green, white, red, black, and blue.
Mightstone and Weakstone, reunited at last, within the surviving brother.
#figure(image("010_Episode 5: As Cruel, As Necessary/09.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
The image was only for an instant; then Urza's eyes were normal again. Urza smiled. "I must go away," he repeated.
Tawnos nodded slowly, and the man with human crystalline eyes stood. "You have long been a student," said Urza. "Now go be a teacher."
As he spoke, Urza began to fade from view. Slowly the color drained from him, leaving only outlines; then they too faded. "Teach them of our triumphs and our mistakes," said a distant voice. "And tell Kayla to remember me not~"
"As you were, but as you tried to be," finished Tawnos, but he was speaking to empty space. Urza had passed from the world into greater worlds that only his crystalline eyes could see.
Tawnos looked around, but there was no sign of life. He struck out inland, hoping to get past the worst of the devastation before he had to travel west. He recognized no familiar landmarks, and he had the feeling that he would not for a long time. Tawnos wondered how bad the devastation truly was.
And as Tawnos walked inland, he was greeted by the first flakes of snow drifting down a chill wind.
|
|
https://github.com/LucaCiucci/custom-typst | https://raw.githubusercontent.com/LucaCiucci/custom-typst/main/boxes.typ | typst |
//#import "styles.typ": *
//#show: common-styles
#outline()
#let typ_label = label
= Callout
`callout` creates a box with a header and a body. It is used inside the other macros.
#let callout(
color: gray,
header: [],
body
) = {
let stroke = 2pt + color;
let radius = 1pt;
let inset = 1pt;
let clip = true;
if header == [] {
block(
block(body, inset: 0.5em, width: 100%),
stroke: 2pt + color,
radius: 1pt,
inset: 1pt,
clip: true,
)
} else {
block(
stack(
box(header, fill: color.lighten(50%), inset: 0.5em, width: 100%),
block(body, inset: 0.5em, width: 100%)
),
stroke: 2pt + color,
radius: 1pt,
inset: 1pt,
clip: true,
)
}
}
#let custom-figure(
body-func,
kind: "@gh:LucaCiucci99::custom-figure",
supplement: [Custom Figure],
label: [],
) = {
if type(body-func) != "function" {
panic()
}
show figure.where(kind: kind): f => f.counter.display()
body-func([#figure([], kind: kind, supplement: supplement) #label])
}
#let callout-box(
body,
header: none,
color: gray,
) = {
let stroke = 2pt + color;
let radius = 1pt;
let inset = 1pt;
let clip = true;
let common-settings = (
inset: 0pt,
clip: true,
);
if header == none {
block(
block(body, inset: 0.5em, width: 100%),
stroke: (left: 3pt + color),
..common-settings,
)
} else {
block(
stack(
box(header, fill: color.lighten(50%), inset: 0.5em, width: 100%),
block(body, inset: 0.5em, width: 100%)
),
stroke: (
left: 2pt + color,
top: 1pt + color,
right: 1pt + color,
bottom: 1pt + color,
),
radius: 3pt,
..common-settings,
)
}
}
#table(
columns: (auto, auto),
[
```typ
#callout[lorem(10)]
```
],
[
#callout(lorem(10))
],
[
```typ
#callout(
color: gray,
header: lorem(5)
)[
#lorem(10)
]
```
],
[
#callout(
color: gray,
header: lorem(5)
)[
#lorem(10)
]
],
)
= Predefined Callouts
#let custom-callout(
title: none,
label: none,
body,
color: gray,
header: [#sym.circle.filled #underline[*Callout*]],
header-short: none,
supplement: [Call],
kind: "custom-theorem",
) = custom-figure(
if title == none {
n => callout-box(
color: color,
[#(if header-short == none { header } else { header-short }) #n: #body],
)
} else {
n => callout-box(
header: if title == [] or title == "" {
[#header #n]
} else {
[#header #n: #title]
},
color: color,
body,
)
},
label: label,
supplement: supplement,
kind: kind,
)
#let note = custom-callout.with(
//color: rgb("#2ecc40"),
color: yellow.darken(10%),
header: [#emoji.pencil *Note*],
supplement: [Note],
kind: "note",
)
#let idea = custom-callout.with(
//color: rgb("#2ecc40"),
color: green,
header: [#emoji.lightbulb *Idea*],
supplement: [idea],
kind: "note",
)
#let example = custom-callout.with(
color: gray,
header: [🕮 *example*],
supplement: [ex.],
kind: "example",
)
#let question = custom-callout.with(
color: rgb("#0074d9"),
header: [🕮 *question*],
supplement: [question],
kind: "question",
)
#let exercise = custom-callout.with(
color: rgb("#0074d9"),
header: [#emoji.pencil *exercise*],
supplement: [exercise],
kind: "exercise",
)
#let info = custom-callout.with(
//color: rgb("#2ecc40"),
//color: yellow.darken(10%),
color: rgb("#2ecc40"),
header: [🛈 *Info*],
supplement: [info],
kind: "info",
)
#let todo = custom-callout.with(
color: rgb("#ba55d3"),
header: [#emoji.square *TODO*],
supplement: [todo],
kind: "todo",
)
// TODO maybe unify with todo using a "done" parameter
// this can be done by redirecting the other args (..args)
#let todo-done = custom-callout.with(
color: rgb("#ba55d3").darken(15%).desaturate(50%),
header: strike[#emoji.ballot.check *TODO*],
supplement: [todo],
kind: "todo",
)
#let proposition = custom-callout.with(
color: rgb("#ff851b"),
header: [#sym.square *proposition*],
supplement: [prop.],
kind: "theorem",
)
#let observation = custom-callout.with(
color: rgb("#ff851b"),
header: [#sym.square *observation*],
supplement: [obs.],
kind: "theorem",
)
#let theorem = custom-callout.with(
color: red.lighten(20%),
header: [#sym.square *theorem*],
supplement: [thm.],
kind: "theorem",
)
#let lemma = custom-callout.with(
color: red.lighten(20%),
header: [#sym.square *lemma*],
supplement: [Lem.],
kind: "theorem",
)
#let corollary = custom-callout.with(
color: red.lighten(20%),
header: [#sym.square *corollary*],
supplement: [Cor.],
kind: "theorem",
)
#let proof = custom-callout.with(
color: green,
header: [#sym.square *proof*],
supplement: [Proof],
kind: "theorem",
)
#let definition = custom-callout.with(
color: rgb("#ff851b"),
header: [#sym.square *definition*],
supplement: [def.],
kind: "definition",
)
#let postulate = custom-callout.with(
color: rgb("#ff851b"),
header: [#sym.square *postulate*],
supplement: [post.],
kind: "definition",
)
#let warning = custom-callout.with(
color: orange,
header: [#emoji.warning *Warning*],
supplement: [Warning],
kind: "warning",
)
#let remark = custom-callout.with(
color: rgb("#e74c3c"),
header: [#emoji.excl.double *remark*],
supplement: [rem.],
kind: "warning",
)
#let important = custom-callout.with(
color: rgb("#e74c3c"),
header: [#emoji.excl.double *important*],
supplement: [rem.],
kind: "warning",
)
#let danger = custom-callout.with(
color: rgb("#e74c3c"),
header: [#emoji.excl.double *danger*],
supplement: [rem.],
kind: "warning",
)
#let quote = custom-callout.with(
color: rgb("#2c3e50"),
header: [❞ *quote*],
//header: [🕮 *quote*],
supplement: [quote],
kind: "quote",
)
#let algorithm = custom-callout.with(
color: rgb("#2c3e50"),
header: [#emoji.gear *algorithm*],
supplement: [algo.],
kind: "algorithm",
)
#let listing = custom-callout.with(
color: rgb("#2c3e50"),
header: [/*#text("</>", font: "FreeMono")*/#box(text("</>", fill: gradient.linear(green.darken(50%), blue), font: "DejaVu Sans Mono", weight: "black", size: 0.75em), radius: 0.125em, inset: 0.25em) *Listing*],
supplement: [listing.],
kind: "algorithm",
)
#let trick = custom-callout.with(
color: yellow.darken(30%),
header: [#emoji.wand *trick*],
supplement: [trick],
kind: "trick",
)
A number of predefined callouts are defined, the usage is the following:
#table(columns: (auto, auto, auto))[
Inline callout
][
```typ
#note[Short text]
```
][
#note[Short text]
][
Block, callout
][
```typ
#note(title: [])[
#lorem(10)
]
```
][
#note(title: [])[
#lorem(10)
]
][
Block callout with title
][
```typ
#note(title: [Title])[
#lorem(10)
]
```
][
#note(title: [Title])[
#lorem(10)
]
][
Reference a callout
][
```typ
#note(
title: [Title],
label: <some-note>,
)[
#lorem(10)
]
Ref: @some-note
```
][
#note(title: [Title])[
#lorem(10)
]
Ref: @some-note
]
#let cells = {
let cells = ();
let functions = (
("note", note),
("idea", idea),
("example", example),
("question", question),
("exercise", exercise),
("info", info),
("todo", todo),
("todo-done", todo-done),
("proposition", proposition),
("observation", observation),
("theorem", theorem),
("lemma", lemma),
("corollary", corollary),
("proof", proof),
("definition", definition),
("postulate", postulate),
("warning", warning),
("remark", remark),
("important", important),
("danger", danger),
("quote", quote),
("algorithm", algorithm),
("listing", listing),
("trick", trick),
)
for (name, f) in functions {
cells.push(raw("#"+name+"[Short text]", lang: "typ"));
cells.push(f([Short text]));
let label_name = "some-" + name;
cells.push(raw("#"+name+"(\n title: [Title],\n label: <" + label_name + ">,\n)[\n #lorem(10)\n]\nRef: @" + label_name, lang: "typ"));
cells.push([
#f(title: [Title], label: label(label_name))[#lorem(10)]
Ref: #ref(label(label_name))
]);
}
cells
}
#table(
columns: (auto, auto),
..cells
)
#listing(title: [Some algorithm])[
```rs
type float = f32;
fn ciao() -> real {
42.0
}
```
] |
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/stretch.typ | typst | // Test math stretch.
--- math-stretch-basic ---
// Test basic stretch.
$ P -> Q stretch(->, size: #200%) R \
R stretch(->) S stretch(->, size: #50%)^"epimorphism" T $
--- math-stretch-complex ---
// Test complex stretch.
$ H stretch(=)^"define" U + p V \
x stretch(harpoons.ltrb, size: #3em) y
stretch(\[, size: #150%) z \
f : X stretch(arrow.hook, size: #150%)_"injective" Y \
V stretch(->, size: #(100% + 1.5em))^("surjection") ZZ $
--- math-stretch-horizontal-attach ---
// Test horizontal stretch interactions with attachments.
#set page(width: auto)
$stretch(stretch(=, size: #4em))_A$
$stretch(arrow.hook, size: #5em)^"injective map"$
$stretch(arrow.hook, size: #200%)^"injective map"$
$ P = Q
stretch(=)^(k = 0)_(forall i) R
stretch(=, size: #150%)^(k = 0)_(forall i) S
stretch(=, size: #2mm)^(k = 0)_(forall i) T \
U stretch(equiv)^(forall i)_"Chern-Weil" V
stretch(equiv, size: #(120% + 2mm))^(forall i)_"Chern-Weil" W $
--- math-stretch-vertical-attach ---
// Test vertical stretch interactions with attachments.
$arrow.t$
$stretch(arrow.t)^"map"$
$stretch(arrow.t, size: #2em)^"map"$
$stretch(arrow.t, size: #200%)^"map"$
--- math-stretch-horizontal ---
// Test stretching along horizontal axis.
#let ext(sym) = math.stretch(sym, size: 2em)
$ ext(arrow.r) quad ext(arrow.l.double.bar) \
ext(harpoon.rb) quad ext(harpoons.ltrb) \
ext(paren.t) quad ext(shell.b) \
ext(eq) quad ext(equiv) $
--- math-stretch-vertical ---
// Test stretching along vertical axis.
#let ext(sym) = math.stretch(sym, size: 2em)
$ ext(bar.v) quad ext(bar.v.double) quad
ext(angle.l) quad ext(angle.r) quad
ext(paren.l) quad ext(paren.r) \
ext(bracket.l.double) quad ext(bracket.r.double) quad
ext(brace.l) quad ext(brace.r) quad
ext(bracket.l) quad ext(bracket.r) $
--- math-stretch-shorthand ---
// Test stretch when base is given with shorthand.
$stretch(||, size: #2em)$
$stretch(\(, size: #2em)$
$stretch("⟧", size: #2em)$
$stretch("|", size: #2em)$
$stretch(->, size: #2em)$
$stretch(↣, size: #2em)$
--- math-stretch-nested ---
// Test nested stretch calls.
$ stretch(=, size: #2em) \
stretch(stretch(=, size: #4em), size: #50%) $
#let base = math.stretch($=$, size: 4em)
$ stretch(base, size: #50%) $
#let base = $stretch(=, size: #4em) $
$ stretch(base, size: #50%) $
--- math-stretch-attach-nested-equation ---
// Test stretching with attachments when nested in an equation.
#let body = $stretch(=)$
$ body^"text" $
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/021%20-%20Battle%20for%20Zendikar/001_Slaughter%20at%20the%20Refuge.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Slaughter at the Refuge",
set_name: "Battle for Zendikar",
story_date: datetime(day: 19, month: 08, year: 2015),
author: "<NAME>",
doc
)
#emph[Sea Gate has fallen, joining Sejiri and Bala Ged in annihilation in the wake of the Eldrazi. As the city teetered on the brink of destruction, the Planeswalker Gideon Jura went to find help: a thinker who could help the fleeing scholars of Sea Gate solve the "puzzle of leylines" that could tilt the odds back in the Zendikari's favor. He went to Ravnica and convinced <NAME> to return to Zendikar with him.]
#emph[For Jace, though, extricating himself from the responsibilities of the Guildpact took some time—time that the refugees of Sea Gate did not have.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
They stepped into carnage.
Gideon's gut wrenched as the enormity of the slaughter pressed itself on his mind. Vorik's purple banner flapped in the wind that wheezed down the ravine and stirred chalky dust and black ash into whirling eddies across the blasted ground. Smoke still rose from glowing embers here and there, where campfires had spread in the chaos to engulf whatever other shelters the defenders had built. The Eldrazi corruption covered the ground, an intricate meshwork of thin white filaments.
And bodies—bodies were everywhere.
Some looked like the casualties of any other war, blood soaking their chests and streaking their faces, limbs torn free, gore spilling from gaping gut wounds. But more—so many more—had partially crumbled away, leaving heaps of dust where heads or legs or arms had been. The smell of blood and entrails mixed with the carrion odor of the Eldrazi and turned Gideon's stomach.
During the final assault on Sea Gate, <NAME> had established a camp here, a refuge for the people fleeing the advancing Eldrazi. Last Gideon knew, it had been safe—or as safe as anyplace on Zendikar. It was sheltered in a narrow ravine that's mouth was almost blocked by a huge fallen hedron. If nothing else, the hedron served to choke off the approach to the camp, but Vorik had seemed to put some stock in the hedron's magical ability to ward off the Eldrazi as well.
But Vorik's camp was clearly no longer a safe refuge. Gideon's mission had taken longer than he intended: Jace had had work to attend to on Ravnica, and Gideon had needed the attention of a healer. Then they had gone to Regatha in a fruitless effort to recruit <NAME>. And while they had delayed, the Eldrazi had apparently overwhelmed Vorik and his defenders.
#figure(image("001_Slaughter at the Refuge/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Gideon!"
He spun on reflex and saw Jace crouching defensively as a pack of Eldrazi spawn spilled around the wreckage of a nearby wall, squelching and skittering as they moved.
Gideon leaped between the Eldrazi and Jace. His sural swept around him, hurling the Eldrazi away, crashing them into each other and shattering the featureless, bony plates that passed for their heads. Then the camp lay silent again.
Gideon snatched up a short, round-bladed sword that was half-buried in a pile of white dust. "Take this," he said, offering the hilt to Jace.
For a moment Jace looked as if Gideon were handing him a snake, but then he took the blade and gave it a few swings through the air.
"Not exactly my specialty," he said.
"Do what you can," Gideon told him.
"So where is this scholar you want me to talk to?"
Gideon looked down at the much smaller man. "Is that all you can think of? Here? Now?"
Jace shrugged, but something in his eyes told Gideon that the mind mage was just covering his own dismay.
Gideon turned away. "We need to move," he said. He looked around to get the lay of the land. "Up the ravine. If anyone survived this, that's where they'll be." Even as he said them, he felt the weight of his words. What if no one had survived?
If he had been here, the camp would not have fallen.
"Are you sure about this?"
"Trust me," Gideon said.
To his credit, Jace nodded and drew closer, ready to follow where Gideon led.
The ravine narrowed and rose sharply behind the camp. Scattered clumps of small Eldrazi ranged around the gully, leaving a spreading pattern of chalky meshwork behind them. Gideon suspected they were feeding, though he couldn't imagine what sustenance they could derive from the bare rock. His first inclination was to destroy all the Eldrazi he could see—but he had Jace to think about, and there was no time to lose in looking for any survivors from Vorik's camp. So he picked a path along the rocky ground that kept them away from the Eldrazi.
Only the occasional Eldrazi veered from the bulk of its fellows to come at them. Gideon quickly dispatched those stragglers, and before long he crested a rocky ridge and his heart lifted.
A wall blocked the ravine ahead, a rickety wooden barrier that looked like it had been torn from a shed and wedged into a choke point. Spears bristling over the top testified that some Zendikari, at least, had survived the slaughter at the refuge.
But between Gideon and those survivors, hundreds of Eldrazi crowded in front of the wall, reaching long tentacles and sharp claws up and over the top. The spears jabbed frantically at any Eldrazi that came within reach, but it was clear that the survivors were vastly outnumbered and outmatched.
Gideon bellowed, "Zendikar!" and charged. His sural whirled around in front of him, clearing a path through the massed Eldrazi as he rushed toward the ramshackle wall.
A lone voice from behind the barricade echoed his cry, followed by a ragged chorus as spears jabbed out with renewed vigor.
"Gideon!" someone shouted. His first thought was to shoot a glance over his shoulder—he had all but forgotten Jace in his eagerness to reach the survivors. But Jace was right behind him. The shout had come from behind the wall, and again it was picked up by a group, even louder than the first.
He reached the wall and whipped his sural back and forth as the Eldrazi continued to press the assault.
#figure(image("001_Slaughter at the Refuge/02.jpg", width: 100%), caption: [Art by <NAME>cott], supplement: none, numbering: none)
"Now what?" Jace said.
Gideon's sural swept in a wide arc to clear them some space. Then he laced his fingers together and nodded to Jace. "Up you go."
"Really."
Jace had missed his chance. The Eldrazi crowded close again. A surge of them from his left drew his attention for a second too long—when he whirled to his right, he saw a wriggling spawn lunging at Jace. Gideon was too slow. Jace threw his arms up to cover his face—and some unseen force pushed the creature back an instant before it could skewer him with a sharp appendage. It wasn't a powerful blow, but it was enough that Gideon had time to get his sural around the Eldrazi's neck.
Then Jace staggered and yelped as a sickly blue tentacle coiled around his leg. Gideon lifted the first Eldrazi into the air and smashed it down on the tentacled one.
"Are you all right?" he asked Jace.
Jace nodded and his eyes flickered with blue light as another spawn scuttled away from him, knocked back by what must have been a telekinetic blow.
Again Gideon swept his sural back and forth to clear a path. Eldrazi bodies were piling up, slowing the advance of the rest of the swarm. He laced his fingers again, and this time Jace promptly put a foot in place. Gideon heaved him up and a hand from the other side of the wall helped him over.
His back to the wall, Gideon faced the remaining mob—squirming spawn and faceless drones, bestial extensions of their titan sire's alien will, of Ulamog's unending hunger. These creatures didn't know who stood before them. They didn't care that he was <NAME>, the savior of <NAME>, the great hunter of Ondu, the champion of Kabira. To them, he was just another piece of flesh, a thing with life to be drained away.
But the people behind the barrier knew. He was hope to them, their one chance to survive this dire threat, their salvation and deliverance. That was what he had been to countless soldiers across Zendikar, and now he had to do it again.
"I just hope I'm not too late," he said to himself.
#figure(image("001_Slaughter at the Refuge/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
He stood his ground and fought, sweeping his sural back and forth, his mind preoccupied with talking to the survivors and getting Jace safely to Jori En.
"Gideon!" came another chorus from behind the wall.
It was time. A larger spawn with heavy bone plates on its head came rushing toward him. He crouched, awaiting the perfect moment, then jumped. One foot came down hard on the Eldrazi's head, then he leaped up, flipped backward, and vaulted over the wall.
His feet kicked up clouds of dust as he landed and laid eyes on the survivors of Vorik's camp.
Eight haggard soldiers sat with their backs against the wall, evidently enjoying the moment of respite that Gideon had brought them. A skittering and clawing at the wall told them that respite was over, and they pulled themselves to their feet again, leaning on their spears for support.
Gideon's sural knocked an Eldrazi off the top of the wall.
"Tell me you're not the only survivors," he said.
One of the soldiers, a kor, jerked her head toward the higher end of the ravine. "Commander Vorik is leading the rest," she said. "But most of them are worse off than we are."
Considering the array of bandages and splints that adorned these eight soldiers, that said a great deal. Gideon frowned.
"How many?" he asked.
The woman shook her head. "A few dozen."
"I should have been here," Gideon said under his breath.
She made a half-hearted jab with her spear at an Eldrazi coming over the wall, her face telling Gideon that she was only pretending not to have heard him.
"Does Vorik have a plan? Where is he taking them?"
"I think getting out of this death trap of a ravine is his first objective. I'm not sure he's thought beyond that."
Jace snorted. "What kind of leader—" he began.
"No, he's right," Gideon said. "We all need to get out of this ravine. I'll hold this wall as long as I can." His sural punctuated his words as more Eldrazi fell dead at his feet. "Go rejoin the others, and take Jace with you."
The kor nodded, not bothering to hide her relief. And, Gideon noted, not bothering to question whether he could hold the wall for long. His reputation had spread widely.
"Jace," he said, "when you get to the others, look for a merfolk named <NAME>. Tell her I brought you to help with the puzzle, and she'll give you everything she knows."
"Assuming she's still alive," Jace said.
Dread knotted Gideon's stomach. He hadn't wanted to put that doubt into words. He hadn't seen <NAME> among the dead in the camp down below, but that didn't mean anything. She could be dust blowing in the wind, or perhaps she never escaped Sea Gate at all. Maybe he had brought Jace all the way here for nothing.
Which made Gideon's prolonged absence all the more inexcusable. He tasted bile. "Go!" he shouted, and the soldiers limped away from the wall as fast as they could manage.
#figure(image("001_Slaughter at the Refuge/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Without having to worry about Jace, Gideon could give the Eldrazi his full attention. Now that the soldiers had left, the Eldrazi scuttled over and around the wall faster than Gideon could strike them down. He fell into an easy rhythm of slaughter, a dance that had become second nature to his muscles. His sural cracked and whistled, golden light gleaming along the length of the four whip-like blades as he channeled his magic through it. His buckler alternately deflected blows and became a weapon itself, smashing into bony plates and breaking limbs. And ripples of energy washed across his skin where the Eldrazi threatened to touch him, warding him from harm.
Maintaining his defenses was actually the harder task. Against human foes, it was easy to anticipate every stab and thrust, and thus make sure that any strike that got past his whirling sural and his buckler would bounce off skin fortified with his magic. Against human foes, he was virtually invulnerable.
Against the Eldrazi, though, he was more susceptible to injury. Especially when he was tired, as he had been for days. Their movements were harder to anticipate. Their limbs were bifurcated, or they were writhing masses of tentacles. He often ended up shielding more of his body than he needed to, which was a drain on his energy, or he misjudged and took a hit. That had happened too many times in the last week.
As much as he hated to admit it, if Jace had not dragged him to see that healer in Ravnica the night before, he might not have been much help in the camp's defense anyway. He might have been dead.
He glanced over his shoulder as the Eldrazi corpses piled up around him. Jace and the Zendikari were out of sight. And in front of him, it seemed like the Eldrazi advance was beginning to slow.
Which might just mean they had found an easier route to the tasty morsels of Zendikari flesh behind him. He started backing his way up the ravine, his sural gripping and slicing at the Eldrazi that followed him. Occasionally, too, he struck high on the side of the ravine, sending a shower of gravel or a few larger chunks of rock down onto the Eldrazi.
Then a huge Eldrazi surged up behind him—not Ulamog, but something very like the enormous titan. It had no legs, just a writhing mass of tentacles, and it pulled itself along the broken ground with its arms, making the ground quiver each time a huge, clawed hand struck the ground. Bony plates ran up the backs of its arms and covered its shoulders, so its head was just one more plate among many. A tangle of tentacles reached skyward from just behind its head.
#figure(image("001_Slaughter at the Refuge/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
One great claw hit the ground, squashing a slithering spawn in an eruption of purplish slime. Neither it nor the surrounding spawn paid any heed.
Gideon planted his feet and took a deep breath, steeling himself. How do you win a war, he wondered, when the enemy has no fear of death and nothing to lose? They never tired, they apparently fed on #emph[everything] —so what would ever stop their advance? How many had he killed here in this ravine, just today? And still they kept coming.
Now the Eldrazi lifted its upper body so it loomed over Gideon, more than twice his height. What looked almost like a second head and torso protruded forward from the thing's chest, squirming independently of the larger body as if trying to pull itself free.
Did it mean to scare him, showing off its much greater size? Or was this more of an animalistic threat display, like a wolf's bristling fur making it look larger? Was there some calculated intent behind that bony plated head?
It didn't matter. One of those great claws came swinging toward Gideon. With the barest movement of his arm, he wrapped his sural around the creature's hand, then he pulled, yanking the Eldrazi off balance.
No. That move would have pulled a human off balance, or even a giant. But the Eldrazi's tentacles barely shifted on the ground, keeping it perfectly grounded. Without hesitation, it grabbed at him with its other claw. He batted the claw aside with his buckler and lashed his sural upward, where it slashed and coiled at the creature's neck.
Neck? Head? He wasn't sure the words even made sense when applied to an Eldrazi. Did it draw air from some opening in its head, down its neck to lungs in its chest? Was its brain located behind that bony plate at the top of its body? Did it even have a brain, or lungs, or a heart, or any vital and vulnerable organs? For all the Eldrazi he had killed, he had never cut one open and studied its anatomy, and he'd seen many continue to fight despite what he would have assumed to be mortal wounds.
And this one seemed unconcerned as Gideon's sural tightened around its neck. The mass of tentacles supporting the creature surged forward and engulfed him, coiling around him and squeezing. Golden light shimmered and rippled over his entire body, protecting him from injury, but maintaining that shield would drain his energy as quickly as the Eldrazi would squeeze the breath from his body if he let it down.
Kicking and thrashing, he managed to loosen the creature's hold enough that he could pull on his sural, dragging the Eldrazi's head down. Then, on a hunch, he brought his shield hand up to punch the smaller second head that grew from its chest.
It was a good hunch. The tentacles loosed their grip. Gideon pulled his sural free from the Eldrazi's neck, and the creature staggered backward, depositing him on the ground. Two more quick slashes with the glowing blades severed first the smaller head and then the larger, and the Eldrazi fell dead to the ground.
#figure(image("001_Slaughter at the Refuge/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Gideon had no time to celebrate his victory. While he had fought the larger Eldrazi, at least a dozen spawn had skittered past him, following Jace and the Zendikari soldiers up toward the other survivors, and more were advancing with every passing second, swarming over the Eldrazi corpse. Sweeping his sural through every crawling and squirming spawn he could reach, he strode up the ravine.
The rocky ravine walls grew closer and closer together as the ground rose. At last, his body spattered with ooze and gore from dozens of Eldrazi spawn, he reached a narrow choke point where bare stone walls opened just wide enough for him to pass through. He jumped up a few natural stone steps and paused for a moment in the narrow gap, surveying the crowd of spawn that still surged up the ravine behind him.
He ran a few more strides past the gap. As the ravine opened up again, he stopped, turned, and lashed out with his sural—once, twice—striking the rock walls and breaking rubble from both sides of the gap to shower down on the Eldrazi below. More strikes, the whip-like blades cracking like a miner's pick on the stone, and larger stones were sheared from the walls, squashing more spawn and blocking the advance of the ones behind. A few more hits, carefully placed, and he had created a defensive wall.
It would not hold, of course—not any better than the one the Zendikari had erected in their retreat. He could hear the Eldrazi scuttling and scraping at the boulders, shifting the rubble as they started to climb. But with any luck, the wall would buy him enough time.
He took off at a run, leaping from stone to stone as he neared the top of the ravine. Then, at last, he heard a woman's voice shouting orders, and a moment later the Zendikari survivors came into view.
"So few," he said to himself. A few dozen, the soldier had said—very few, if he was seeing the whole group. From the top of the ravine, they were making their way along a high ridge. He saw many crutches, many makeshift stretchers held by limping soldiers, and bandages on almost every living body.
Jace's blue cloak stood out among the grays and browns, the plain fabrics and dirt-caked clothes of the Zendikari. The mind mage was standing beside an armored human woman. Gideon hurried to join them.
"You made it," Jace said. Was that a touch of admiration in his voice?
The woman turned to face him, and her eyebrows rose in recognition. "You must be Gideon," she said.
"Did you find her?" he asked Jace. "<NAME>?"
Jace shook his head. "I asked everyone."
"Did she . . . Was she—"
"She never got to the camp. One of the merfolk said she never got out of Sea Gate."
Gideon's chest clenched. "She died there?" He had left her in the middle of the battle, abandoned her to make her own way to the camp while he went to find Jace. If she was dead, it was his fault.
"Probably," Jace said. "But perhaps not. The man I talked to said that a small group got trapped, cut off from the evacuation. He thinks <NAME> was among them, and they might have found shelter."
"So they could still be alive. They could still be in Sea Gate." His shoulders sagged at the thought of what he had to do next.
The woman cleared her throat. "I'm Tazri," she said.
She was a brown-skinned woman in elaborate plate armor, adorned with small wings at her shoulders and a glowing metal ring like an angel's halo, but around her neck. A heavy, flanged mace hung at her belt.
"Sorry," Gideon said. He extended his hand, the blades of his sural trailing on the ground.
She took his hand gingerly, eyeing his weapon. "I'm glad you're here."
"Where is Commander Vorik?" Gideon asked.
"Right here," came a hoarse voice from behind Tazri.
Tazri turned, and Gideon saw Vorik. He was a strongly built man with deep brown skin and curly gray hair cropped short. His shirtless chest was wrapped in bandages, and some blood had seeped through them at his left side. He leaned on a staff as he shuffled toward them.
"Hello, Gideon," he said, his voice a harsh whisper.
"Sir," Gideon said, keeping his concern out of his tone. Vorik was a proud man, and Gideon knew better than to patronize him. "We don't have much time. I slowed the Eldrazi advance, but I couldn't stop it."
"<NAME>, the savior of <NAME>," Vorik said, a touch of wonder in his voice. "Perhaps now we'll call you the defender of Vorik's gully."
Gideon looked at the ground. "I should have been here earlier."
"Yes," Vorik said flatly. "We could have used you."
"What's your plan, sir?"
Vorik heaved a deep sigh. "What can we do but keep running? About three miles down this ridge, there's another fallen hedron in front of a large overhang. That'll make as good a camp as any."
Gideon frowned. "A protected entrance is good. But no way out?"
"If we can't hold them back from in there, we're doomed anyway. There's no way we can outrun them, even if the great defender of Vorik's gully stays around this time."
Gideon looked around the ridge, rubbing his chin. They stood at the crest of the Bulwark, the great ring of mountains that encircled Tazeem, though the ring was lower here, close to Sea Gate, than it was on the other side of the island. To his right, the land sloped gradually down to the Halimar, the great inner sea, fed by Tazeem's many rivers and held in place by the enormous dam that was the city of Sea Gate. To the left, a much sharper slope led down to the ocean. The curve of the land and the tangled trees of the Vastwood shielded Sea Gate from view.
A few hedrons hung motionless in the air nearby, fallen only halfway from the floating hedron field high above Tazeem to the sea below. Gideon let his gaze drift up to the hedron field. Ropes dangled from several of the lower hedrons and connected some of the ones that hovered in the sky.
"I have another idea," he said.
Vorik frowned at him. "You know a better place?"
"I think I do. Look." He pointed at the nearest hedron. "There's practically a staircase waiting for us."
#figure(image("001_Slaughter at the Refuge/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Have you gone mad?" Tazri said. "You have two dozen people here who can barely walk, and you expect them to climb ropes and perch on hedrons?"
"Yes. For many of them, it will be easier than walking. And with enough hooks and ropes, we can help the others up." He turned back to Vorik. "Sir, with the sheer number of Eldrazi on the ground here, I believe there's no other place that can offer a similar level of protection."
"Fine," Vorik said. "Lead the way."
Tazri gaped at her commander. "Sir?"
"Gideon is right, Tazri," Vorik said. "Help him get the people ready."
Together, Gideon and Tazri worked quickly, despite her reservations. First they talked to the kor among the survivors, drawing on their skill with ropes. While some kor worked to build harnesses and slings that could carry the wounded up the heights, others scouted the path and fixed ropes in place to ease the ascent. Then they distributed what meager supplies the survivors had managed to take with them from Sea Gate and the destroyed refuge, giving heavier burdens to those who were strong enough to carry them. In just a few hours, they were ready to begin the climb.
The kor scouts led the way, with Gideon right behind them. He used his sural much as they used their ropes, though its whip-like blades weren't as long. He lacked their slender grace, but made up for it with strength and speed. Jace, though, was not a skilled climber nor an athlete of any sort. He trailed behind Gideon, offering meager assistance to the kor who were carrying those too injured to move themselves.
Most of the hedrons, tilted askew in the air, offered a relatively smooth and level surface to move along. It was easiest to crawl—which was the reason Gideon had said it might be easier than walking for some of the wounded. Crossing on ropes between hedrons was more challenging, as an act of both balance and courage. But these were hardy folk, accustomed to life on Zendikar with all its dangers. They made the ascent with no complaints, no missteps, and no further injuries.
A huge hedron near the bottom edge of Emeria proper offered a large, flat surface to establish a new camp, at least for the short term. It also offered a spectacular view of Tazeem, with all its rushing rivers, tangled woods, and clear lakes. The Halimar glittered in the evening sunlight and Sea Gate—
#figure(image("001_Slaughter at the Refuge/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Gideon stared long and hard at Sea Gate. Even at this distance, he could see the Eldrazi corruption spreading across the city. Buildings had crumbled to dust or turned into elaborate chalky meshwork. The great dam, which held in the waters of the Halimar, showed no signs of that corruption yet. But how long would it continue to hold? How long would its lighthouse stand?
"So now what?" Jace asked, startling him out of his musings.
"<NAME> could still be there," he said, nodding toward the city. "I have to go find her." If he couldn't find her, then it was all for nothing. He had abandoned Sea Gate to go find Jace so Jace could help Jori solve a magical puzzle. Spending that time with Jace had meant that he wasn't at Vorik's camp when the Eldrazi came, and all those people had died. If he couldn't find her, they had died for nothing.
"Unlikely," Jace said gently. "Given what we know, she is probably dead. We should find another approach."
"You should," Gideon said. "We don't have Jori's notes, but maybe you can figure out what she was talking about. She said leylines and hedrons. Plenty of hedrons around—see what you can learn. And I'll find Jori En and bring her back here."
"It's a fool's errand," Jace said, as Gideon had known he would.
"It doesn't matter. I have to find her. If I don't, then what was all this for? Why did I bring you here at all, when I could have been here defending the camp from the beginning? If you and Jori En don't solve this puzzle of hers, then it was all for nothing."
"It's all for nothing if you die trying to find her in a city teeming with Eldrazi."
"Jace." Gideon put a hand on the mind mage's shoulder. "Look at what we've done today. Greater deeds lie ahead for both of us. Trust me."
Jace squirmed out from under his hand, stepped back out of reach, and met his gaze. He opened his mouth to speak, then paused.
"Trust me," Gideon said again.
"I do," Jace said, with a touch of wonder in his voice. "I still think it's foolish, but I do."
"Thank you. I'll be back as soon as I can."
"I believe you will," Jace said. "Good luck."
"You too." He turned away and walked along the edge of the hedron face, making a wide circle around the camp until he reached the rope leading downward. Luck, skill, the power of his magic, the lessons of his training—Gideon would need them all, surely.
"I have to do this," he told himself, gripping the rope. "They can't have died for nothing."
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Expertes_Ex_28_05_2024.typ | typst | #import "@preview/bubble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2": canvas, draw, tree
#import "@preview/cheq:0.1.0": checklist
#import "@preview/typpuccino:0.1.0": macchiato
#import "@preview/wordometer:0.1.1": *
#import "@preview/tablem:0.1.0": tablem
#show: bubble.with(
title: "Maths Expertes",
subtitle: "28/05/2024",
author: "<NAME>",
affiliation: "<NAME>",
year: "2023/2024",
class: "Terminale B",
logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"),
)
#set page(footer: context [
#set text(8pt)
#set align(center)
#text("page "+ counter(page).display())
]
)
#set heading(numbering: "1.1")
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
= Exercice 21 p 220
==
L'ordre du graphe est $5$
==
Le nombre d'arête est $12/2= 6$
==
Non car A et D ne sont pas adjacent
==
Oui le graphe est simple
==
A: $2$
B: $3$
C: $3$
D: $2$
E: $2$
==
Le graphe admet une chaîne eulérienne car il y a $2$ sommets de degré impair
==
Le graphe n'admet pas de cycle eulérien car il a $2$ sommets de degré impair
= Exercice 1 p 242
==
$ U_1 = A U_0 = mat(-1 times 2 -1 times 2; 1 times 2 -1 times 0.5;) = mat(-4; 3/2) $
$ U_2 = A U_1 = mat(-1 times -4 + 2 times 3/2; 1 times -4 + 0.5 times 3/2) = mat(7; -13/4;) $
==
$U_n = A^n U_0$
$U_10 = A^10 U_0 = mat(252217/256;-432253/1024)$
= Exercice 2 p 242
==
$A = mat(10, 5; -3, 4)$
$U_0 = mat(5; -2)$
==
$A = mat(-0.2,0.5;1.3,-0.7)$
$U_0 = mat(0;1)$
==
$U_0 = mat(2;1)$
$U_n = mat(a_n; a_(n+1))$
$A = mat(0,1 ;-13, 6)$
= Exercice 3 p 242
==
Faux $U_3 = A^3 U_0 = mat(0.094;0.031)$
==
$lim_(n arrow +infinity) -n = -infinity$ #linebreak()
$lim_(n arrow -infinity) e^n = 0$ #linebreak()
Par composition $lim_(n arrow +infinity) e^(-n) = 0$
Pour $-1<k<1$ $lim_(n arrow +infinity) k^n = 0$
Ainsi $lim_(n arrow +infinity) 0.7^n -1 = -1$
$lim_(n arrow +infinity) U_n = mat(0; -1)$
==
$A U = mat(2, 1, 1; 1,3,1;4,5,2;) times mat(1; 0; -1) = mat(1; 0 ;2 ) != U$
Donc U n'est pas un état stable
==
$ U_n = A^n U_0$
$ U_n = mat(3^n, 0; 0, 2^n) times mat(1;1) = mat(3^n; 2^n)$
$lim 3^n = +infinity$
$lim 2^n = +infinity$
Donc $lim U_n = mat(+infinity; +infinity)$
Ainsi $(U_n)$ diverge
==
La matrice $mat(0;0)$ est un état stable car $A times O = mat(0; 0)$
|
|
https://github.com/lvignoli/typst-action | https://raw.githubusercontent.com/lvignoli/typst-action/main/README.md | markdown | MIT License | # Typst GitHub action
Build Typst documents using GitHub workflows.
## Minimal example
The following `.github/workflows/build.yaml` action compiles `main.typ` to `main.pdf` on every push.
```yaml
name: Build Typst document
on: push
jobs:
build_typst_documents:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Typst
uses: lvignoli/typst-action@main
with:
source_file: main.typ
```
## Longer example
Here we compile multiple files on each push, and publish all the PDFs in a tagged and timestamped release when the commit is tagged.
```yaml
name: Build Typst document
on: [push, workflow_dispatch]
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Typst
uses: lvignoli/typst-action@main
with:
source_file: |
first_file.typ
second_file.typ
third_and_final_file.typ
- name: Upload PDF file
uses: actions/upload-artifact@v3
with:
name: PDF
path: *.pdf
- name: Get current date
id: date
run: echo "DATE=$(date +%Y-%m-%d-%H:%M)" >> $GITHUB_ENV
- name: Release
uses: softprops/action-gh-release@v1
if: github.ref_type == 'tag'
with:
name: "${{ github.ref_name }} — ${{ env.DATE }}"
files: main.pdf
```
Repository [lvignoli/typst-action-example](https://github.com/lvignoli/typst-action-example) provides an example setup on a whole repo.
## Notes
- This action runs on the docker image shipped with the latest Typst.
As long as Typst is in v0, changes of the CLI API are to be expected, breaking the workflow.
I'll update regularly.
- I was hasty to tag for a v1. I have now deleted it.
As long as Typst is not in a stable state, the action will stay in v0.
You should use `lvignoli/typst-action@main` in the meantime.
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/046%20-%20Streets%20of%20New%20Capenna/011_A%20Garden%20of%20Flesh.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"A Garden of Flesh",
set_name: "Streets of New Capenna",
story_date: datetime(day: 03, month: 05, year: 2022),
author: "<NAME>",
doc
)
"Here, in the Machine Orthodoxy, there is perfection. Here, there is blessing."
As she said it, her synthesized voice echoing over the Fair Basilica's courtyard, Elesh Norn, Phyrexian regent and Mother of Machines, felt the light of that truth deep within her sacred, mechanized body. The Machine Orthodoxy was the only path to ultimate unification, a path as pure and infallible and undeniable as her own glistening oil.
When she looked out over the gathering of Phyrexians from her dais, her armor gleaming in the milky light, Norn had never been surer of it. Here were the emblems of the might she had facilitated: the Fair Basilica, its towers, its metal spires like porcelain, grand cathedrals arching skyward, winding, delicate, and airy. Crimson banners waved from bridges and turrets, stark against the gleaming structures and flagstones of the courtyard.
The Phyrexian faithful, their mechanically altered faces upturned toward her, their consciousness woven through her own, were eager for her to speak. They were her people, grown in birthing pods. They were her adopted children, captured from opposing armies, those once poor, pitiable creatures who had lived so long covered in vile, unaltered skin, now idealized with mechanical parts. The air smelled of their new bodies. Metallic. Sharp. Clean. The distant chanting of Phyrexian prayers, hundreds of voices synchronized, flowed around it all.
#figure(image("011_A Garden of Flesh/01.jpg", width: 100%), caption: [Due Respect | Art by: <NAME>], supplement: none, numbering: none)
How could anybody deny the beauty of this? The rightness? The absolute truth?
And yet, the Mirran she held before her still struggled. It was a foolish effort. The top of the woman's dark, tangled hair barely came to Norn's shoulder. The flesh beneath her long, clawed fingers was pitiably weak, and she merely tightened her grip to subdue her. She cried out, her arms and legs, lashed together, stiffening as blood blossomed from the wound Norn had made.
Humans were such flawed and fragile things.
Norn had considered letting the vat priests and splicers begin this Mirran's alterations while she addressed the assembly. She had no doubt they would do an admirable job. But the Machine Orthodoxy was growing and expanding rapidly.
How best to teach her children, if not by example?
"Now is the time for unity." Norn raised her voice, cool and smooth as the breeze blowing through the Basilica's grounds. "Behold this imperfect creature. Even she, an organic abomination, is worthy of the mercy of the Orthodoxy. Even she may be blessed."
Norn thrust the Mirran toward the edge of the dais. She tottered in her grip, gasping and pleading, a flailing, shameful display. Something about her, the dark hair, the angle of her eyes, the squareness of her jaw, tickled at the edges of Norn's memory. Had she encountered this human before? Doubtful. She would surely have transformed the pitiful creature if she had.
It was almost unheard of for anyone to escape the Machine Orthodoxy.
Norn tightened her hand. "Soon, this wretched human will be released from the burden of fear. We will flay her. Strip away the flesh that binds her to this weak body. Then, she too, will join us in total unification with our divine purpose and will."
There was a shift of sound, a deep rumbling Norn had never heard before, from all around her. What could that be but the power of Phyrexian faith, their synthetic voices deepening in prayer? The sound resonated as she lifted her free hand, curled her long, clawed finger, and punctured her wrist.
For a moment, the pale sky seemed to darken, as if clouded by smoke, but Norn's attention was fixed on the glistening oil flowing from her wrist, her very body, the purest possible source. The crowd swayed forward as one, their eyes glinting as they watched the oil flow from the wound and onto the Mirran's head and quaking shoulders. It slicked her hair, coating the back of her neck. She thrashed when it penetrated the wound there, and screamed, the sound shrill and organic. Irritating. Soon those vocal cords would be replaced and immaculately calibrated and her voice would join the others' in reverence.
She sputtered and choked as the glistening oil smothered her, filled her, her body twitching as the oil began to flow from her gaping mouth and the corners of her open eyes.
All around Norn, the rumble grew louder.
She held the Mirran up by the scruff for all to see. "Behold perfection."
But in her grip, the Mirran shuddered, an organic movement that bubbled up from the center of her body in sudden, uneven waves. There was nothing mechanical about it, no measured rhythm of sacred alteration. Instead, the meat beneath Norn's hand bulged. It rolled and squirmed as if the bony vertebrae knuckling against her palm were trying to shove her away.
The Mirran's body heaved, a convulsion so violent Norn nearly dropped her, and a pulpy cord of organic material, a fibrous wooden root, sinuous and alien, burst from the human's belly. Blood, unnaturally thick and foul, oozed onto the dais. It pooled beneath Norn's feet, a twisted abomination of her own glistening oil, even as more roots bulged from the human's open mouth, wrenching teeth, and tongue aside, breaking through her eye sockets and squirming into the air.
Ele<NAME> was so perplexed, it took a moment for her to react. With a crackle and flare of white light, she transformed a piece of her porcelain armor into a narrow blade and sliced the Mirran's throat with a single stroke. Her lifeless body crumpled at Norn's feet, a pile of unnatural roots, blood, and offal.
There was no sign of change or machinery. There was only unnatural corruption.
This should never have happened.
Beneath her, the Phyrexians' chants faltered, though that deep rumble remained, rolling low through their confusion.
Norn gathered herself, standing tall as she reabsorbed her porcelain blade. "Witness this example and pity her," she said, her voice calm, though her mind was reeling, ticking through every probability, every possible explanation for what had just happened. "She was a vessel so corrupt, not even our glistening oil could save her. Here is proof that we must spread our doctrine swiftly, so that all can be saved."
But even as she said it, Norn had to fight to compose herself.
None of what had just happened, made sense.
The glistening oil should never have failed.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The pale light of the Fair Basilica was gleaming over its domes and spires, turning them a cold silver-white, its banners an inky black, when <NAME> returned to the courtyard.
She had not lingered after the incident with the Mirran woman. She had only remained long enough to order the bloated body with its fleshy roots removed, to be dissected and disposed of. Norn had walked gracefully from that dais to demonstrate that she was, indeed, still in control. She had moved with easy purpose back into the Basilica as though she had anticipated the failure of her demonstration, the eruption of those roots from that human's twitching body. But she had never seen such a thing.
Even when administered by a Phyrexian without her considerable power, the effects of glistening oil were predictable. It erased useless things—memory, attachments, desires—and reordered chaotic, organic minds into perfect patterns. While the oil often leaked from the eyes and nose and other orifices before the splicers and vat priests did their work replacing organic matter with machinery, the oil itself never induced seizures. It certainly never thickened the blood or caused the body to rupture.
The oil was the holiest of elements. Its grace was self-evident.
So, what, exactly, had gone wrong?
No human would ever have been powerful enough to resist the glistening oil themselves, despite what Norn had told the gathering.
<NAME> walked across the courtyard, the distant hum of Phyrexian prayers the only sound to accompany her measured footsteps. She ran one long finger over the lip of the dais. She thought to ascend the steps, to revisit the place the Mirran had collapsed and attempt to determine what might have caused the disruption, when she noticed a small blemish on the flagstones.
Elesh Norn paused.
There, where the Mirran's blood had run over the dais and onto the courtyard, was a small, inky weed, sprouting through a crack in the flagstones. Its stalk was twisted, a mottled jumble of greens and browns. It was fully organic. Hideous. Offensive.
Elesh Norn reached down to pluck it out, to rid the otherwise perfect stone of the weed, but it was slick, giving beneath her touch like the soft flesh of the Mirran's neck. Norn scowled. Whatever was happening, whatever this abnormality was that had crept into the Machine Orthodoxy, it would not be tolerated. She had worked too hard to cultivate this place, to assure the furthering of the Phyrexian cause to have it soiled, even a little bit.
Norn twisted her wrist, intent on uprooting and crushing the weed in one swift movement, but it resisted as if clutching the underside of the stones.
"Heresy," Norn breathed and yanked the weed viciously upward. It broke loose, far larger than anticipated, the flagstone rupturing at the force of its dislodging. But no roots were hanging from the small intruder. Instead, a human forearm dangled, disproportionately large, half-rotten, bone swinging like the clapper of a cracked bell in the dislocated slop. Its limp fingers were splayed wide as if still reaching toward the very soil she had plucked it from.
"Abomination." Norn lifted the offensive thing to study it, her head cocked.
Was this a result of the Mirran's contaminated blood flowing onto the flagstones?
It made no sense.
#figure(image("011_A Garden of Flesh/02.jpg", width: 100%), caption: [<NAME>, Grand Cenobite | Art by: <NAME>], supplement: none, numbering: none)
Norn flung the weed away in disgust. She needed to uncover the meaning of this heresy, to stamp out the true cause before it could take root again. She was about to order the priests to dispose of it when she saw another strange plant by her foot. And another further along the path. And there, another.
An unfamiliar tightness coiled deep in Elesh Norn's belly.
Norn strode across the courtyard, ripping another weed from the marble. It was the remnants of a human lung, a rootless, sagging lump, the upper lobe wrapped around what should have been the plant's stalk. She crushed it in her hand. It could not have come directly from the Mirran's body. The vat priests had dissected her corpse and found nothing abnormal, save those roots, and no reason for them to have sprouted from her human body in the first place.
The tightness in her stomach grew.
One after another, Norn ripped the abominations from the ground. She unearthed a thick, dismembered thigh, sinew shredding between her long fingers as she ripped it in two. A heart, arteries drooping away from it. A bulging strand of spongey intestine. A single kidney. An ear. A dozen teeth impossibly strung together like jagged pearls. Again and again, she pulled them up, faster and faster, determined to purge the Basilica of impurities. And with every discovery, she felt something inside her tighten and sour.
A jitteriness spread through her limbs.
Could it be a malfunction? Impossible. She was the Mother of Machines. Regent. Infallible.
And yet, the last thing that had touched that Mirran had been her own glistening oil.
<NAME> grew still, her porcelain armor gleaming, her soiled hands clenched, her red robes flowing in the soft, steady breeze.
"We are the Mother of Machines," she breathed and somewhere in the distance, that never-ending stream of Phyrexian prayers seemed to quaver and that low rumbling returned, deep and almost imperceptible. What had once felt like an affirmation of power and faith now seemed to resonate with doubt. A thousand Phyrexian minds trembled.
She could not allow the Orthodoxy to fall prey to this alien sensation plaguing her. There had to be an explanation for all of this. An order to all of this.
<NAME> raised her head, but even the bright sky seemed impossibly dimmer now, as if the air itself had darkened, as if a cloud had descended upon the Basilica. The smoky dimness congealed and softened in turns, seeming for a small second to resolve itself into a figure floating above the Basilica's skyline, lean and dark, before dissipating. She shook her head, willing herself to believe it wasn't her eyesight failing. It must have been a trick of the changing light, Norn tried to tell herself.
Or another, unexplainable corruption.
The very idea that anything would dare dim the beauty of her glorious creation was preposterous. And yet, the atmosphere did seem darker, the world around her vaguely out of sync with itself in a way that nothing in the Machine Orthodoxy had ever been. There was an unreal quality to it, a heaviness that belied the airy nature she had tried so hard to cultivate.
This was her Basilica, after all.
This place was nothing if not an extension of herself.
And yet~
Norn looked down at the plaza and recoiled. Every cavity she had cleared of those organic atrocities, every place that Mirran's blood had stained the exquisite earth, was full of new weeds sprouting. They pulsed and grew, overrunning the Fair Basilica like a garden of flesh.
Norn strode into the once-open space between the Basilica and the northern tower, where unnatural growths now coiled over the broken flagstones. She ripped them out of the earth as she passed.
She paused beside a tower where a leg had erupted from the flagstones like the crown of a burgeoning tooth. Was this really the result of that Mirran's blood? Was this what happened when organic imperfection was allowed to infect the Orthodoxy? Norn lifted the dismembered limb, holding its meat between her hands. It was soft. Weak. Rotting in ways a machine wouldn't. It felt as though her Basilica was doing just that. Putrefying from the ground up. It was intolerable.
No.
It was impossible.
As she tossed the heavy chunk of flesh aside, Norn told herself that again.
Impossible.
There had to be a logical explanation.
If the human and her unnatural blood hadn't unleashed these abominations, what, then, would have been powerful enough to have altered the world Elesh Norn herself had created?
Norn looked down at her hand, the wrist from which the glistening oil had flowed.
Could she herself indeed have done this?
Who else would have been powerful enough to disrupt the order of the Orthodoxy so completely? What if she was the reason the oil had that effect on the Mirran's body?
Norn had always been everything a praetor should be, but what if she had somehow failed in this? What if she had been wrong? What if all this time, lurking inside of her, there had been some unseen flaw, germinating and waiting to burst forth and ruin the Machine Orthodoxy? Was she somehow intrinsically corrupt? Had the Grand Cenobite Ele<NAME> inadvertently spawned something so impure and organic? Was she unfit to lead the Machine Orthodoxy?
The Orthodoxy was righteous, therefore the glistening oil itself could not be to blame. There was no logical reason a lowly, pitiable human's blood would have spawned the horror spread before her.
<NAME> pressed one uncharacteristically unsteady hand against the dais as if to brace herself against her own world, twisted and inexplicable in its imperfection.
All of it, #emph[all of it] , still felt so oddly unreal.
She remembered, once, witnessing Mirrans, captured after the insurrection, sleeping in their holding cells. They had laid curled around themselves, dreaming, whimpering, caught in the nightmarish designs of their own, singular, weak minds. She remembered how they howled and screamed through a reality that only existed in themselves, trapped and begging to wake up.
The Orthodoxy had purged them of those dreams when it gifted them with their alterations, but Norn hadn't forgotten the alien sight of them dreaming. If nothing else, it confirmed her belief that flesh was inferior. It was all the more reason to strip them of it and gift them with the mechanical certainty of the Orthodoxy.
Phyrexians did not dream.
Phyrexian minds were anchored in reality, in the predictable rhythm of machinery and righteousness. There was no reason for her mind to have wandered into a fanciful, subconscious space full of plants, fleshy horrors, and illogical assumptions. But as she stood there, her body taut, her mind trying to make sense of an improbable reality, Norn felt as though she was trapped like those sleeping humans had been. As if all would be right with the world if only she could wake up and think clearly again.
<NAME> grew still. She did not breathe. Her porcelain armor was as motionless as the stone pillars around her.
This world was not hers.
Slowly, <NAME> looked upward toward the sky where the darkness had seemed to form a figure earlier. Scowling, she whispered, "Ashiok."
The rumbling sound that had been rolling beneath everything deepened and then, across the Basilica's courtyard, a slender, androgynous form appeared. They floated up and over the delicate bridges and carefully sculpted towers as if gravity had no hold on them, gossamer robes trailing beneath their bare feet, the narrow angle of their face spiraling upward into a pair of horns where their eyes should have been. Black smoke curled, wraith-like and sinuous from the sharp tips of their horns, that same darkening of the air that Norn had seen when she first cut the Mirran.
#figure(image("011_A Garden of Flesh/03.jpg", width: 100%), caption: [Ashiok, Nightmare Weaver | Art by: <NAME>], supplement: none, numbering: none)
Norn's fingers curled around the lip of the dais, cracking the white stone.
Ashiok. Planeswalker. Nightmare mage. She had heard of them, of course. Norn was not unfamiliar with the chaos Ashiok had inflicted on the Mirrans, how the nightmare mage often infected lesser minds with dreams for their own amusement, to induce fear. But she had never considered Ashiok would be so foolish as to attempt to impose their nightmarish "art" upon her.
Though <NAME> was a Phyrexian and a regent, above emotional outbursts, she felt enraged at the realization that none of this—not the organic slop that had infested her Basilica, not the human body parts sprouting like weeds beneath her feet, not even her improbable distress—had been real. It was simply an illusion.
An amusement.
A waste.
<NAME> drew herself up to her full height, her porcelain armor shining, her crimson robes trailing behind her.
"Ashiok." This time, when she said their name, her voice was icy, the synthetic overtone of each vowel and consonant dangerously sharp. It was a voice that commanded armies, a voice that spoke truth and purity, a voice that, until today, had never doubted itself. Norn drew her shoulders back, pouring every ounce of authority and divine menace into her posture.
Ashiok approached at a leisurely pace, drifting across the courtyard, gazing down on their nightmare creation with a small, satisfied grin. They hovered just out of reach of Norn, bare feet not quite touching the spoiled flagstones, their robes billowing behind them.
Ashiok spread their broad hands outward as if to caress it all. "Beautiful, isn't it? I worked so very long on this particular masterpiece." Ashiok leaned forward slightly, their head cocked. "Your mind is a very~ unique canvas, <NAME>. Very unique indeed."
"So this abomination, this filth, is indeed your doing?" Norn asked coolly.
"But of course." Ashiok smiled. "To be completely honest, I was not certain Phyrexians would be suitable for my art. One simply cannot create a masterpiece without a proper canvas."
"So you were testing us?" Norn said this with control, carefully calculated, even though her indignant fury had begun to boil. She refused to entertain the thought that the kernel of her lingering uncertainty might be perpetuating her doubt.
"Who else would have been a better test subject? You are the Mother of Machines, after all, are you not? Your mind~" Ashiok's voice trailed away, contemplative and vaguely perplexed. "It does not process fear the way human minds do."
"We are a Regent of Phyrexia," Norn said. "We are perfection personified. We do not fear." Until today, she would have never questioned that statement; it would not have been a lie to say she never doubted herself. But Norn refused to let that uncertainty surface completely. She forced authority into her voice, every ounce of deception and manipulation she had honed to defeat her rivals. She was not made entirely of organic material.
She was not weak.
She was not flesh.
She was not human.
Ashiok's smile only broadened. They glided in a broad circle around Norn, toes skimming the earth but not quite touching. "Oh, if that were true, I wouldn't still be here, would I?"
Ashiok rose into the air slowly, and the smoke curling from the tips of their horns began to flow downward, coiling around the human limbs and organs sprouting from the courtyard's flagstones. Norn's gaze followed the path of their ephemeral touch. There in the jumble of broken stone was a human head, growing through a broad crack like a fungus. It was a female with dark hair and light skin. White armor grew up around her chin and jaw like fronds. Her features were covered in the mire but, beneath the filth, something about her countenance seemed strangely familiar to Norn.
"I first encountered her when I was creating my art in Theros," Ashiok said, each word somehow menacing in its softness as their smoke caressed the human head's cheeks and brow. "Her name is <NAME>." Ashiok rolled the name through their mouth as if tasting it for the first time. "She caught my attention, and I sought her out in the Underworld. Her fear of Phyrexians was glorious. Simply breathtaking. How could my curiosity not have been piqued? What kind of artist would I be if I did not seek out such an opportunity to hone my craft, to test it on a being such as yourself? I simply had to find out. What would a Phyrexian nightmare be like?"
<NAME> remembered <NAME> now from her failed assault on her sacred Basilica, and that nagging familiarity she'd felt with the Mirran suddenly made more sense.
"Elspeth escaped, didn't she?" Ashiok said and smiled softly. "This small, inconsequential human escaped the Machine Orthodoxy."
"Irrelevant." Norn felt her indignation rise. "The truths we see are beyond your understanding, Ashiok. We will not be cowed. We will not be a tool for your 'art.'" In a place deeper than any nightmare could ever penetrate, she felt the connection to her people, the collective of Phyrexia, joined together, the strength of that unity, an unstoppable force of thousands upon thousands of splendidly altered beings waiting for her command to strike.
Ashiok's smile faltered.
"We will not abide this blasphemy any longer," Norn continued. She took a deep breath and turned her focus inward. There was a stirring in the shadows, movement from the deep corners of the courtyard. A creak of doors being opened. Measured footfalls on stone steps. One by one, dozens of Phyrexians, as real in her dream as they might have been in the waking world, materialized from the shadows, their metal bodies gleaming, their eyes glowing red and eager.
For a moment, Ashiok looked almost confused. "They are not part of this piece," they said. "I did not design them to be here. Not now."
"We are one," Norn said. "Did you think you could so easily control us with this #emph[nightmare] ?"
There was a beat of silence, all machinery still. The grinding of gears and the wet sounds of Ashiok's nightmare garden ceased. There was only wind, carrying the smell of decay and oil, snapping the crimson banners high overhead.
"You have underestimated us." Norn said quietly, a synthesized whisper.
And then, pure as a prayer, the Phyrexians behind her repeated, "You have underestimated us."
Ashiok tipped their head, drummed their fingertips together, and floated backward carefully, putting distance between Norn and the rest of the Phyrexians as the white light flared, a swarm of porcelain blades forming in the metal encasing her body.
"Interesting," Ashiok said.
The rumble became a roar, a deep, throaty, organic sound that rushed across the nightmare landscape like a wave. The smoke swirling between Ashiok's horns darkened, thickened, and descended. The limbs sprouting from the earth shambled together in a mockery of Phyrexian beauty, the garden below merging into creatures and hurtling toward Norn, a tangle of legs and arms, half-formed heads dangling from dissected shoulders.
The Phyrexians surged forward, slicing through the dream manifestations, the illusion made corporeal in an extension of Norn's will. What the Phyrexians did not overtake, she eviscerated quickly and efficiently herself in a barrage of needle-thin porcelain blades flying from her body in blinding flashes of white light, crackling viciously through the air. She sliced Ashiok's creatures to ribbons before they even had a chance to approach the dais she was standing beside.
"You have blasphemed against us!" Norn's voice reverberated through the courtyard. She drew back her arm, preparing to obliterate Ashiok's wraith-like body, when the thing that would be <NAME> rose.
It heaved itself upright at Norn's feet, sloshing up and out of the earth with a thick, wet sound, rising from the nightmarish mire until it hovered facing her, spinal cord dangling like a rodent's tail. Ashiok's smoke wound around it rapidly, swelling and curving, shaping the very air into a tall, solid form corded with sinuous muscle and covered with pearly porcelain metal and a curving helmet. It was a mirror of Elesh Norn's sacred form.
Norn took a step back. Elspeth did the same. It was a twisted reflection of her own body, her posture that seemed suddenly, horribly, undeniably human. And there it was again, that tightness in Norn's throat, prickling the back of her neck, dropping deep into the center of her like a stone. She felt the urge to back away. To run. This was an abomination, not only of the Orthodoxy but of her. Mother of Machines, Regent. This was a twisted version of the Orthodoxy's future.
<NAME> did not want to call it fear, but as she watched Elspeth's hand rise to her mouth, as she watched those fingers so much like her own tremble, she knew that, yes, logically, that was how she too must have looked in that moment.
Impure.
Imperfect.
Impossible.
How could this planeswalker make her feel this way with their trickery, nightmares, and illusions? With a simple vision of a human woman sculpted to look like her, to mock her? She, <NAME>, who so masterfully bent her enemies to her will? She, who was the apex of Phyrexia?
With a deafening crackle and a blast of bright light, the needle-thin daggers prickling from Norn's body merged and formed a massive, deadly blade in her hand. With more power than would ever be necessary, she flung it into the nightmare version of <NAME>, slicing through her chest with such force that she flew across the courtyard, landing in a heap on the far side. A form clothed in her own white metal and crimson robes, still covered in human flesh, dead.
No, not dead.
Because it never was alive to begin with. It was all an illusion, a trick.
Norn turned to Ashiok, her internal workings pounding with this new and unfamiliar emotion, rage seasoning the fear she'd felt into something almost uncontainable. She prepared to unleash it all upon the planeswalker, but they were already high above the Basilica, darting backward with uncustomary speed until they were out of range, looking every bit as unsettled as Norn.
"You are quite the canvas, indeed, Mother of Machines." Ashiok spread their arms wide and bowed their head. "Another masterpiece."
Norn watched as Ashiok disappeared, gliding through the night sky. The veil of Ashiok's nightmare world lifted with their departure. The Phyrexians she had willed into existence dissipated. The broken flagstones resolved themselves once more into immaculate smoothness. The thick blood and unnatural plants quivered, hardened, and then crumbled to dust, easily scattered by the fresh breeze.
The body of Elspeth, still clad in Norn's armor, was the last to fade, clinging to corporeality until the regent took a step toward her. Elspeth's armor quaked and then crumbled away, fine as white sand, leaving her severed human head. The skin cracked. Lines thin as wisps of smoke formed around her mouth, spreading outward, dissolving her nightmare flesh from the inside out.
But just before the vision of Elspeth disintegrated, she opened her eyes and met Norn's gaze. She looked at Norn with such human pity, with such horrid#emph[ sympathy] , that Norn couldn't breathe.
When the nightmare had well and truly faded from the world, <NAME> walked carefully over the courtyard of the Basilica and touched the stones, clean now, pure and holy, where the thing that had been <NAME> had been birthed. She could not erase Elspeth from her mind. She could not unsee the pity there. She could not bear the thought of something so human unsettling her so completely.
And <NAME> knew then, with the same amount of conviction with which she worshiped the Machine Orthodoxy, that in order to purge this new emotion she was feeling, this fear and uncertainty, she would need to find the human, <NAME>, and rid the Multiverse of her.
|
|
https://github.com/lucifer1004/leetcode.typ | https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0017.typ | typst | #import "../helpers.typ": *
#let letter-combinations-of-a-phone-number-ref(digits) = {
let digits = digits.clusters()
let d = ("2": ("a", "b", "c"), "3": ("d", "e", "f"), "4": ("g", "h", "i"), "5": ("j", "k", "l"), "6": ("m", "n", "o"), "7": ("p", "q", "r", "s"), "8": ("t", "u", "v"), "9": ("w", "x", "y", "z"))
let ans = ("",)
for c in digits {
let nxt = ()
for nc in d.at(c) {
for s in ans {
nxt.push(s + nc)
}
}
ans = nxt
}
if ans == ("",) { () } else { ans }
}
|
|
https://github.com/duskmoon314/THU_AMA | https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch4/1-域和域扩张.typ | typst | Creative Commons Attribution 4.0 International | #import "/book.typ": *
#show: thmrules
#show: book-page.with(title: "域和域扩张")
= 域和域扩张
域 = 两个交换群 + 分配律 = 可交换的除环 = 乘法可逆的整环
#property()[
$U lr((F)) = F \\ {0} = F^(\*)$
$F$中理想只有平凡理想$arrow.r.double F$为单环
域之间的同态$sigma : F_1 arrow.r F_2$
$ker sigma$为$F_1$中的理想$arrow.r.double ker sigma = lr((0))$或$F_2 arrow.r.double sigma$单同态或$sigma equiv 0$
]
#definition()[
设$lr((K , + , dot.op))$为域,$nothing eq.not F subset.eq K$,若$F$对于$+ , dot.op$也构成一个域,则称$F$为$K$的#strong[子域(subfield)],反之称$K$为$F$的#strong[扩域(extension field)]。记作$F lt.eq K$或$K \/ F$
]
== 域的特征与素域
#definition()[
对域$F$而言,$nothing eq.not S subset.eq F$,则$F$中包含$S$对最小子域称为#strong[由$S$生成的子域],记作$angle.l S angle.r$
$1$生成的子域$angle.l 1 angle.r$称为$F$的#strong[素域],记作$F_0$
]
#theorem()[
设$F$为域,则若1在$lr((F , +))$中的阶$o^(+) lr((1)) < oo$,则必有$o^(+) lr((1)) = p$,其中$p$为素数
]
#proof()[
若$o^(+) lr((1)) < oo$,不妨设$o^(+) lr((1)) = n in bb(Z)^(+)$,假设$n$不是素数,则$exists n_1 , n_2 > 1$满足$n = n_1 n_2 arrow.r.double 0 = n 1 = lr((n_1 n_2)) 1 = lr((n_1 1)) lr((n_2 1)) in F$,由于$F$中无零因子,只有$n_1 1 = 0$或$n_2 1 = 0$,与$o^(+) lr((1))$的最小性矛盾,故$n$为素数
]
#definition()[
设$lr((F , + , dot.op))$,如下定义其#strong[特征(character)]: $ c h lr((F)) = cases(
delim: "{",
p & upright("若") o^(+) lr((1)) = p < oo,
0 & upright("若") o^(+) lr((1)) = oo,
) $
]
#property()[
若$o^(+) lr((1)) = p$为素,$forall a in F^(\*)$均有$o^(+) lr((a)) = p$
]
#proof()[
若$m a = 0 arrow.r.double lr((m a)) b = 0 = a lr((m b)) arrow.r.double m b = 0$
]
#theorem()[
设$F$为域,$F_0$是$F$的素域,则 $ F_0 tilde.equiv cases(
delim: "{",
bb(Q) & o^(+) lr((1)) = oo,
bb(Z) \/ p bb(Z) & o^(+) lr((1)) = p < oo,
) $
]
#proof()[
若$c h lr((F)) = 0 , o^(+) lr((1)) = oo , lr((n 1)) lr((m 1))^(- 1) in F_0$,令$sigma : bb(Q) arrow.r F_0$,从而有$n / m arrow.r.bar lr((n 1)) lr((m 1))^(- 1)$,可验证$sigma$为单同态,即$sigma lr((bb(Q))) subset.eq F_0$。由$F_0$的最小性知$sigma lr((bb(Q))) = F_0$,则$sigma$满,故为同构。
若$c h lr((F)) = p$,令$sigma : bb(Z) \/ p bb(Z) arrow.r F_0 , a^(‾) arrow.r.bar a_0 1 lr((a_0 = 0 , 1 , dots.h.c , p - 1 upright("s.t.") a_0 in a^(‾)))$可验证$sigma$为单同态,进一步由$F_0$的最小性知$sigma lr((bb(Z) \/ p bb(Z))) = F_0$,则$sigma$满,故为同构。
]
== 域的扩张方式
设$K \/ F$为域扩张,设$u , v in K , a , b in F arrow.r.double a u + b v in K$,可视为$u$与$v$的$F$-线性组合
#definition()[
设$K \/ F$为域扩张,$K$作为$F$-线性空间的维数$dim_F K$就称为$K$对$F$的#strong[扩张次数(extension degree)],记作$lr((K : F))$
]
#theorem("链式法则,望远镜公式")[
若$F , K , E$为域,且$F subset.eq K subset.eq E$,则$E \/ F$为#strong[有限扩张]$arrow.l.r.double K \/ F$,$E \/ K$均为有限扩张,且此时还有如下数量关系: $ lr((E : F)) = lr((E : K)) lr((K : F)) $
]
#proof()[
设${ v_i }_(i = 1)^(n_1)$为$K$的一组$F$-基,${ u_j }_(j = 1)^(n_2)$为$E$的一组$K$-基
构造$E$的$F$-基${ u_i v_j }_(1 lt.eq i lt.eq n_1 , 1 lt.eq j lt.eq n_2)$,验证线性无关与表出性
]
#example()[
$bb(C) = { a + b i \| a , b in bb(R) }$,故${ 1 , i }$为$bb(C)$的一组$bb(R)$-基,从而$lr((bb(C) : bb(R))) = 2$
$K = { a + b sqrt(2) \| a , b in bb(Q) }$,故${ 1 , sqrt(2) }$为$K$的一组$bb(Q)$-基,从而$lr((K : bb(Q))) = 2$
$E = { c + d sqrt(3) \| c , d in K }$,故${ 1 , sqrt(3) }$为$E$的一组$K$-基,从而$lr((E : K)) = 2$
$lr((E : bb(Q))) = lr((E : K)) lr((K : bb(Q))) = 4$,且$E$的一组$bb(Q)$-基为${ 1 , sqrt(2) , sqrt(3) , sqrt(6) }$,即$E = { a + b sqrt(2) + c sqrt(3) + d sqrt(6) \| a , b , c , d in bb(Q) }$
如此添加$sqrt(p)$作扩张,可知$bb(R) \/ bb(Q)$为无限扩张,即$lr((bb(R) : bb(Q))) = oo$
]
== 添元扩张法
#definition()[
设$K \/ F$为域扩张,$nothing eq.not S subset.eq K$,称包含$S union F$的$K$的最小子域为#strong[$F$添加$S$所得的域],记作$F lr((S))$
当$S = { u }$时,即$F$添加一个元素$u$所得的域$F lr((u))$,称为$F$上的#strong[单扩张(simple extension)]
]
#definition()[
设$K \/ F$为域扩张,$u in K$,若$u$是$F$上某个非零多项式$f lr((x)) in F lr([X])$的根,则称$u$为$F$上的#strong[代数元(algebraic element)],否则称为#strong[超越元(transcendental element)]
当$F = bb(Q)$时,$bb(Q)$上的代数元称为#strong[代数数(algebraic number)],超越元称为#strong[超越数(transcendental number)]
]
#definition()[
若$u$为$F$上的代数元,称以$u$为根的首一的次数最小的多项式$f lr((x)) in F lr([x])$为$u$在$F$上的#strong[最小多项式],记作$m_u lr((x))$。当$deg m_u lr((x)) = n$时,称$u$为一个$n$次代数元
]
#property()[
+ 最小多项式不可约
+ 最小多项式是唯一的
+ 最小多项式是全体以$u$为根的多项式的公因子
]
#theorem("单扩张定理")[
若$E \/ F$为域扩张,$u in E$,则 $ F lr((u)) tilde.equiv cases(
delim: "{",
{ a_0 + a_1 u + dots.h.c a_(n - 1) u^(n - 1) \| a_i in F } tilde.equiv F lr([x]) \/ lr((m lr((x)))) & u upright("为") F upright("上") n upright("次代数元"),
{ frac(f lr((x)), g lr((x))) \| f lr((x)) , g lr((x)) in F lr([x]) , g lr((x)) eq.not 0 } tilde.equiv F lr((x)) & u upright("为") F upright("上超越元"),
) $ 且有$lr((F lr((u)) : F)) = cases(delim: "{", deg m lr((x)) & upright("代数"), oo & upright("超越"))$
]
#proof()[
+ 当$u$为$F$上的$n$次代数元时,由$F lr([x])$是PID,$m lr((x))$是$F lr([x])$中的不可约多项式$arrow.r.double lr((m lr((x))))$是极大理想$arrow.r.double F lr([x]) \/ lr((m lr((x))))$是域,其中的元素为$a^(‾) lr((x)) = a lr((x)) + lr((m lr((x))))$且$deg a lr((x)) lt.eq n - 1$,不妨设$a lr((x)) = a_0 + a_1 + dots.h.c + a_(n - 1) x^(n - 1)$
作映射$sigma : S eq.delta { a_0 + a_1 u + dots.h.c a_(n - 1) u^(n - 1) \| a_i in F } arrow.r F lr([x]) \/ lr((m lr((x)))) , g lr((u)) arrow.r.bar g lr((x))$。验证$sigma$为环同态、双射,故$sigma$为同构映射。则$S$为包含$F union { u }$的在同构意义下的一个域,即$F lr((u)) subset.eq S$。另一方面,$S subset.eq F lr([u]) subset.eq F lr((u))$,故$S = F lr((u))$,且${ 1 , u , dots.h.c , u^(n - 1) }$为其$F$-基,$lr((F lr((u)) : F)) = deg m lr((x)) = n$
+ 当$u$为$F$上超越元时,作映射$sigma : F lr((u)) arrow.r F lr((x)) = { frac(f lr((x)), g lr((x))) \| f , g in F lr([x]) , g eq.not 0 }$,验证$sigma$为同构……
]
$F lr((u))$中乘法就是关于多项式乘法,特别当$u$代数时为关于$u$的多项式乘法($mod m_u lr((x))$)
== 代数扩张域有限扩法
#definition()[
设$K \/ F$为域扩张,若每一个$u in K$,均为$F$上的代数元,则称$K$是$F$的#strong[代数扩张(algebraic extension)]。否则(只须存在一个超越元)称为#strong[超越扩张(transcendental extension)]
]
#theorem()[
$K \/ F$为有限扩张$arrow.r.double K \/ F$为代数扩张,反之不成立
]
#proof()[
设$lr((K : F)) = n , forall u in K$,考虑$1 , u , u^2 , dots.h.c , u^n in K$共$n + 1$个元,$K$是$n$维的$F$-线性空间$arrow.r.double { 1 , u , dots.h.c , u^n }$线性相关,即$exists$不全为零的$a_i in F$使得$a_0 + a_1 u + dots.h.c + a_n u^n = 0 arrow.r.double f lr((x)) eq.not 0$且$f lr((u)) = 0$,从而$u$维代数元。进而$K \/ F$为代数扩张。
]
#property()[
设$K \/ F$为域扩张,$a , b in K$,分别为$m , n$次代数元,则$lr((F lr((a , b)) : F)) lt.eq m n$
]
#proof()[
设$a , b$在$F$上的最小多项式分别为$f lr((x)) , g lr((x)) in F lr([x]) , deg f = m , deg g = n$。$F lr((a , b)) = lr((F lr((a)))) lr((b))$相当于将$b$添加到$F lr((a))$中,设$b$在$F lr((a))$上的最小多项式为$g prime lr((x)) in F lr((a)) lr([x])$,将$g lr((x))$视为$F lr((a)) lr([x])$中到多项式($F subset.eq F lr((a))$),则有$g lr((b)) = g prime lr((b)) = 0 arrow.r.double g prime lr((x)) \| g lr((x)) in F lr((a)) lr([x]) arrow.r.double deg g prime lt.eq deg g = n$。故$lr((F lr((a , b)) : F lr((a)))) = deg g prime lt.eq n arrow.r.double lr((F lr((a , b)) : F)) = lr((F lr((a , b)) : F lr((a)))) lr((F lr((a)) : F)) lt.eq m n$
]
#property()[
设$K \/ F$为域扩张,$a , b in K$为$F$上的代数元,则$a$与$b$到四则运算(加减乘除)均为$F$上的代数元
]
#proof()[
由性质1,$F lr((a , b)) \/ F$有限扩,进而是代数扩。
]
#property("代数扩张的传递性")[
若$K \/ F , E \/ K$为代数扩张,则$E \/ F$为代数扩张
]
#definition()[
$F$添加全体$F$上的代数元所得的域称为$F$的#strong[代数闭包(algebraic closure)],记作$F^(A C)$或$F^(‾)$
]
== 有限域
$bb(Z) \/ p bb(Z)$为有限域,特别当$p = 2$时,$bb(Z) \/ p bb(Z) = bb(F)_2 = G F lr((2))$为最简单的有限域
=== 有限域的构造与唯一性
首先,若$\# F = n < oo$,则$c h lr((F)) = p arrow.r.double F_0 tilde.equiv bb(Z) \/ p bb(Z) eq.delta bb(F)_p arrow.r.double F \/ bb(F)_p$域扩张
其次,扩张次数$lr((F : bb(F)_p)) = s < oo arrow.r.double \# F = p^s$
如何表示:
+ 线性空间 $F tilde.equiv bb(F)_p u_1 + dots.h.c + bb(F)_p u_s$
+ 单代数扩张 $F tilde.equiv bb(F)_p lr((alpha)) tilde.equiv bb(F)_p lr([x]) \/ lr((m_alpha lr((x)))) , deg m_alpha lr((x)) = s$
#example()[
构造8阶域
]
#solution()[
$8 = 2^3 arrow.r.double c h lr((F)) = 2$且$F \/ bb(F)_2$的3次扩域。取$bb(F)_2 lr([x])$上的3次不可约多项式$x^3 + x + 1 , x^3 + x^2 + 1$
$f lr((x)) = x^3 + x^2 + 1 in bb(F)_2 lr([x])$,设$alpha$为$f lr((x))$在$bb(F)_2^(A C)$中的一根
令\$F \= \\mathbb{F}\_2\(\\alpha) \= \\mathbb{F}\_2\[x\]/\(f\(x)) \= \\{ \\overline{a\_0 + a\_1 x + a\_2 x^2} | a\_i \\in \\mathbb{F}\_2 \\} \\\\
\= \\{ \\bar{0}, \\bar{1}, \\bar{x}, \\overline{1+x}, \\bar{x^2}, \\overline{1+x^2}, \\overline{x + x^2}, \\overline{1 + x + x^2} \\} \\\\
\= \\{ 0, 1, \\alpha, 1 + \\alpha, \\alpha^2, 1 + \\alpha^2, \\alpha + \\alpha^2, 1 + \\alpha + \\alpha^2 \\}\$
$F$中的加法:多项式的加法,也是线性空间的加法,${ 1 , alpha , alpha^2 }$为一组$bb(F)_2$-基
$F$中的乘法:多项式的乘法$med ( mod med f lr((x)) \)$(利用$alpha^3 = alpha^2 + 1$化简)
+ 根的选取有自由性
+ 选取另一多项式构造的域是同构的
]
#theorem()[
任何两个元素个数为$p^n$的有限域是同构的,且都同构于$S = { alpha in bb(F)_n^(A C) \| alpha upright("为") x^(p^n) - x upright("的根") }$
]
+ $f lr((x)) = x^(p^n) - x = x lr((x^(p^n - 1) - 1))$,称"一篮子多项式"
+ $forall F_1 tilde.equiv S tilde.equiv forall F_2$(唯一性)
+ $forall p , forall n in bb(Z)^(+) , x^(p^n) - x$存在$arrow.r.double S$存在$arrow.r.double$阶数为$p^n$的有限域存在
#proof()[
+ 先讨论$S$的结构,即说明$S$构成域
设$f lr((x)) = x^(p^n) - x$,则$f prime lr((x)) = p^n x^(p^n - 1) - 1 = - 1 arrow.r.double lr((f , f prime)) tilde.op 1 arrow.l.r.double f lr((x))$无重根$arrow.r.double \# S = p^n$。设$S = { alpha_0 = 0 , alpha_1 = 1 , alpha_2 , dots.h.c , alpha_(p^n - 1) }$,其中$alpha_1 , dots.h.c , alpha_(p^n - 1)$为$x^(p^n - 1) - 1$的根$arrow.r.double o_times lr((alpha_i)) \| p^n - 1 lr((forall i eq.not 0))$
若$S$中有$p^n - 1$阶元,设为$alpha$,则$angle.l alpha angle.r = { alpha^j \| 0 lt.eq j lt.eq p^n - 2 }$就是$x^(p^n) - 1 = 0$的全部根,即$S = { 0 } union angle.l alpha angle.r$。
进一步验证$S$对于加法乘法运算封闭,且构成群。 \
$forall a , b in S arrow.r.double lr((a + b))^(p^n) - lr((a + b)) = a^(p^n) + b^(p^n) - a - b = lr((a^(p^n) - a)) + lr((b^(p^n) - b)) = 0 arrow.r.double lr((a + b)) in S$ \
$lr((a b))^(p^n) - lr((a b)) = a b - a b = 0 arrow.r.double a b in S$ \
$S$构成域
+ 证明$S$中必有$p^n - 1$阶元(参考教材)
+ 再看$F$与$S$的关系:$forall F s . t . \# F = p^n$
$bb(F)_p$中元满足$a^p = a$(费马小定理$a^(p - 1) equiv 1 med ( mod med p \)$若$lr((a , p)) = 1$)$arrow.r.double bb(F)_p subset.eq S arrow.r.double 0 , 1 in S$
$forall u in F^(\*)$有$o_times lr((u)) \| \# F^(\*) = p^n - 1 arrow.r.double u^(p^n - 1) = 1 arrow.r.double u in S arrow.r.double F subset.eq S$
又$lr(|F|) = lr(|S|) = p^n arrow.r.double F tilde.equiv S$
]
#remark()[
+ 取定$p , n$,则$p^n$阶的有限域存在且在同构意义下唯一,记作$bb(F)_(p^n)$或$G F lr((p^n))$
+ 加法方面$lr((bb(F)_(p^n) , +)) tilde.equiv lr((bb(F)_p^n , +))$
+ 乘法方面$lr((bb(F)_(p^n)^(\*) , dot.op)) = angle.l alpha angle.r tilde.equiv C_(p^n - 1)$,生成元$alpha$称为$bb(F)_(p^n)$的本原元
+ $bb(F)_(p^n) tilde.equiv cases(
delim: "{",
bb(F)_p lr((beta)) = bb(F)_p lr([x]) \/ lr((p lr((x)))) & p lr((x)) upright("为") bb(F)_p upright("上n次不可约多项式,") beta upright("为其一根"),
{ a_0 + a_1 beta + dots.h.c + a_(n - 1) beta^(n - 1) \| a_i in bb(F)_p },
{ x^(p^n) - x upright("在") bb(F)_p^(A C) upright("的全部根") },
{ 0 } union angle.l alpha angle.r,
)$
]
#definition()[
+ $F_(p^n)^(\*)$中$p^n - 1$阶元称为$bb(F)_(p^n)$的#strong[本原元\(primitive element)],本原元$alpha$在$bb(F)_p$上的最小多项式称为$bb(F)_p lr([x])$中的#strong[本原多项式(primitive polynomial)]
+ 若$alpha$是方程$x^r - 1 = 0$在$bb(F)_p^(A C)$中的根,但不是任何$x^h - 1 = 0 lr((h < r))$的根,则称$alpha$是#strong[r次本原单位根(primitive root of unit)]
]
#example()[
给出一个$bb(F)_2 lr([x])$中的4次本原多项式
]
#solution()[
首先找一个4次不可约多项式: \
试根法得可选项$x^4 + x^3 + x^2 + x + 1 , x^4 + x^3 + 1 , x^4 + x^2 + 1 upright("讨论可知可约") , x^4 + x + 1$ \
其次,在上述3个不可约多项式中,寻找本原多项式,即其根的阶$2^4 - 1 = 15$
因$x^5 - 1$含有$x^4 + x^3 + x^2 + x + 1$,故$x^4 + x^3 + x^2 + x + 1$的根$alpha$的阶为5,故不是本原的
考虑$x^4 + x^3 + 1$,设其根$alpha , o_times lr((alpha)) \| 15 , alpha^4 = alpha^3 + 1 arrow.r.double alpha^5 = alpha^4 + alpha = alpha^3 + alpha + 1 eq.not 1 arrow.r.double alpha$ 必为15阶元$arrow.r.double x^4 + x^3 + 1$ 为本原多项式
同理,$x^4 + x + 1$也是本原的
]
=== 有限域的子域
#theorem()[
$bb(F)_(p^n)$的全部子域为$bb(F)_(p^m)$,其中$m \| n$
]
#proof()[
一方面,设$K$为$bb(F)_(p^n)$的子域,则$bb(F)_p subset.eq K subset.eq bb(F)_(p^n) arrow.r.double lr(|K|) = p^m lr((m lt.eq n))$。又因$bb(F)_(p^n)$可视为$K$-线性空间,$lr((bb(F)_(p^n) : K)) = r arrow.r.double lr(|bb(F)_(p^n)|) = lr(|K|)^r arrow.r.double p^n = lr((p^m))^r arrow.r.double m \| n$
另一方面,$forall d \| n$,有$lr((p^d - 1)) lr(|lr((p^n - 1)) arrow.r.double lr((x^(p^d - 1) - 1))|) lr((x^(p^n - 1) - 1)) arrow.r.double lr((x^(p^d) - x)) \| lr((x^(p^n) - x)) arrow.r.double bb(F)_(p^d) subset.eq bb(F)_(p^n)$
]
=== 有限域上的多项式
#theorem()[
设$q$为素数$p$的方幂,$f lr((x)) in bb(F)_q lr([x])$是n次不可约的,$u$为$f lr((x))$在$bb(F)_q^(A C)$的一个根,则$f lr((x))$在$bb(F)_q^(A C)$的全部根为$u , u^q , dots.h.c u^(q^(n - 1))$。注:$u^(q^n) = u$
]
#proof()[
设$f lr((x)) = sum_(i = 0)^n a_i x^i lr((a_i in bb(F)_q , a_n eq.not 0))$,则$f lr((u)) = 0$
又$a_i in bb(F)_q arrow.r.double a_i^q = a_i lr((forall i)) arrow.r.double a_i^(q^j) = a_i$,$f lr((u^(q^j))) = a_0 + a_1 u^(q^j) + dots.h.c + a_n u^(n q^j) = lr((a_0 + a_1 u + dots.h.c + a_n u^n))^(q^j) = f lr((u))^(q^j) = 0^(q^j) = 0 arrow.r.double u^(q^j)$为$f lr((x))$的根($j = 0 , 1 , 2 , dots.h.c n - 1$)
$bb(F)_q lr((u)) = bb(F)_q lr([x]) \/ lr((f lr((x)))) tilde.equiv bb(F)_(q^n) = {x^(q^n) - x upright("的全部根")}$
下证n个根互不相同,反证:设$exists i eq.not j s . t . u^(q^i) = u^(q^j) lr((i > j)) arrow.r.double 0 = u^(q^i) - u^(q^j) = lr((u^(q^(i - j)) - u))^(q^j) arrow.r.double u^(q^(i - j)) = u arrow.r.double u in bb(F)_(q^(i - j))$且$i - j < n arrow.r.double bb(F)_q lr((u)) subset.eq bb(F)_(q^(i - j))$但$bb(F)_q lr((u)) tilde.equiv bb(F)_(q^n) arrow.r.double bb(F)_(q^n) subset.eq bb(F)_(q^(i - j))$与$i - j < n$矛盾。故这n个根就是$f lr((x))$的全部根(由代数基本定理得)
]
#example()[
在$bb(F)_2 lr([x])$中分解多项式$x^7 - 1$
]
#solution()[
$x^7 - 1$在$bb(F)_2^(A C)$中的根必为${ 1 , alpha , alpha^2 dots.h.c alpha^6 } , alpha^7 = 1$。
设$p lr((x))$为$x^7 - 1$的不可约因式,若$alpha$为$p lr((x))$的根$arrow.r.double alpha , alpha^2 , alpha^4$为$p lr((x))$的全部根$arrow.r.double deg p lr((x)) = 3$
设$q lr((x))$为$x^7 - 1$的另一不可约多项式,且$alpha^3$为$q lr((x))$的根$arrow.r.double alpha^3 , alpha^6 , alpha^5$为$q lr((x))$的全部根$arrow.r.double deg q lr((x)) = 3$
$x^7 - 1 = lr((x - 1)) p lr((x)) q lr((x))$
]
#theorem("一篮子多项式分解定理")[
$x^(p^n) - x$是$bb(F)_p lr([x])$中次数除尽n的首一不可约多项式的乘积
$x^(p^n) - x = product_(d \| n) g lr((x)) , g lr((x)) = upright("d次首一不可约多项式")$
]
#theorem()[
+ $bb(F)_q lr([x])$中n次不可约多项式的个数为 $ I_q lr((n)) = 1 / n sum_(d \| n) mu lr((d)) q^(n \/ d) $
+ $bb(F)_q lr([x])$中n次本原多项式的个数为 $ J_q lr((n)) = frac(phi lr((q^n - 1)), n) $
] |
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/布局/colbreak/colbreak.typ | typst | = colbreak
强制换行。
当在单列布局或页面上的最后一列中使用时,该函数的行为类似于分页符。否则,分栏符之后的内容将放置在下一列中。
#image("屏幕截图 2024-04-14 170805.png")
#image("屏幕截图 2024-04-14 171136.png")
weak
如果true,如果当前列已为空,则跳过分栏符。
默认:false |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/zalmy/Z33_vecieren.typ | typst | #import "/style.typ": *
#set par(first-line-indent: 1em)
#subheader[Psalm 33]
#note[Žalm berieme v prípade, že je predpísaná lítia.]
Blahoslovľú Hóspoda na vsjákoje vremjá, výnu chvála jehó vo usťích mojích.
O Hóspoďi da pochválitsja dušá mojá, da uslýšat krótciji i vozveseľátsja.
Vozvelíčite Hóspoda so mnoju, i voznesém ímja jehó vkúpi.
Vzyskách Hóspoda i uslýša mja, i ot vsich skorbéj mojích izbávi mja.
Pristupíte k nemú i prosvititésja, i licá váša ne postyďátsja.
Sej níščij vozzvá i Hóspoď uslýša í, i ot vsich skorbéj jehó spasé í.
Opolčítsja <NAME>óspodeň ókrest bojáščichsja jehó, i izbávit ich.
Vkusíte i vídite, jáko blah Hóspoď, blažén múž iže upovájet naň.
Bójtesja Hóspoda vsi svjatíji jehó, jáko ňísť lišénija bojáščymsja jehó.
Bohátiji obniščáša i vzalkáša, vzyskájuščiji že Hóspoda ne lišátsja vsjákaho blahá. |
|
https://github.com/Vortezz/fiches-mp2i-physique | https://raw.githubusercontent.com/Vortezz/fiches-mp2i-physique/main/chapitre_4.typ | typst | #import "@preview/cetz:0.0.1"
#import "@local/typst-plot:0.0.1": plot, sample
#set page(header: box(width: 100%, grid(
columns: (100%),
rows: (20pt, 8pt),
align(right, text("CHAPITRE 4. RÉGIME PERMANANT DANS UN CIRCUIT D'ORDRE 1")),
line(length: 100%),
)), footer: box(width: 100%, grid(
columns: (50%, 50%),
rows: (8pt, 20pt),
line(length: 100%),
line(length: 100%),
align(left, text("<NAME> - MP2I")),
align(right, text("<NAME> - 2023/2024")),
)))
#set heading(numbering: "I.1.a")
#let titleBox(title) = align(center, block(below: 20pt, box(height: auto, fill: rgb("#eeeeee"), width: auto, inset: 40pt, text(title, size: 20pt, weight: "bold"))))
#let proof(content) = text("Preuve", weight: "semibold", fill: rgb("#666666")) + h(1em) + text(content, size: 10pt, fill: rgb("#888888"))
#titleBox("Régime permanent dans un circuit d'ordre 1")
= Le condensateur
== Présentation
Le *condensateur* est un dipôle _linéaire_ composé de deux armatures séparées par un milieu isolant (*diélectrique*). C'est l'un des composant de base en électronique. Il est schématisé comme ci dessous :
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line
import "@local/circuitypst:0.0.1": node, to
to("capacitor", (-2,0), (2,0), label: "C", v: $U$, i: $i$)
}),
caption: [Schématisation du condensateur]
)
On a $+Q$ la charge algébrique portée par l'armature de gauche. Puisque le _condensateur est globalement neutre_, $-Q$ est la charge portée par l'armature de droite.
On a le rapport $Q = C U$ avec $C$ la *capacité du condensateur* en fahrad (F).
== Caractéristique U/I
En convention récepteur on a $i = c (d U)/(d t)$.
#proof("On a " + $(d Q)/(d t) = (delta Q)/(d t) = i$ + " et " + $Q = C U$ + " donc " + $i = (d Q)/(d t) = (d C U)/(d t) = c (d U)/(d t)$)
== Approche énergétique
On a $E$ l'énergie stockée dans un condensateur tel que $E = 1/2 C U^2$.
#proof($P_("reçue") = U i = U C (d U)/(d t) = (d)/(d t)(1/2 C U^2)$ + " et " + $P_("reçue") = (d E)/(d t)$ + " d'où " + $E = 1/2 C U^2 + A$ + " avec " + $A = 0$)
Aux bornes d'une condensateur $U$ est une fonction continue par le temps.
#proof("On suppose " + $U$ + " discontinue donc " + $E$ + " aussi. " + $P = (d E)/(d t)$ + ", ainsi on a une puissance infinie ce qui n'est possible.")
== Association série et parallèle de condensateurs
=== Association parallèle
Dans le schéma suivant, on a $C = C_1 + C_2$ :
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line, content
import "@local/circuitypst:0.0.1": node, to
to("capacitor", (-2,1), (0,1), label: $C_1$, i: $i_1$)
to("capacitor", (-2,-1), (0,-1), label: $C_2$, i: $i_2$, name: "R2")
line((-2,1), (-2,-1))
line((0,1), (0,-1))
line((0,0), (0.5,0), name: "equiv")
line((-2,0), (-2.5,0))
node("currarrow", (-2.2, 0))
content((rel: (0, 0.3)), $i$)
line((-2, -1.7), (0, -1.7), mark: (start: ">"), name: "tension")
content((rel: (-1, -0.3)), $U$)
content("equiv", h(4em)+[équivalent à], anchor: "left")
to("capacitor", (5,0), (9,0), label: $C$, i: $i$, v: $U$)
}),
caption: [Association parallèle de condensateurs]
)
#proof("Loi des noeuds, " + $i = i_1 + i_2$ + ", d'après la caractéristique " + $U I$ + " du condensateur, " + $i_1 = C_1 (d U)/(d t)$ + " et " + $i_2 = C_2 (d U)/(d t)$ + " soit " + $i = C_1 (d U)/(d t) + C_2 (d U)/(d t) = (C_1 + C_2) (d U)/(d t)$)
=== Association série
Dans le schéma suivant, on a $1/C_(\eq) = 1/C_1 + 1/C_2$ :
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line, content
import "@local/circuitypst:0.0.1": node, to
to("capacitor", (-2,0), (0,0), label: $C_1$, i: $i$, v: $U_1$)
to("capacitor", (0,0), (2,0), label: $C_2$, i: $i$, v: $U_2$, name: "R2")
line((-1.5, -1.1), (1.5, -1.1), mark: (start: ">"), name: "tension")
content((rel: (-1.5, -0.3)), $U$)
content("R2", h(4em)+[équivalent à], anchor: "left")
to("capacitor", (5,0), (9,0), label: $C$, i: $i$, v: $U_C$)
}),
caption: [Association série de condensateurs]
)
= Étude de la charge d'un condensateur
== Mise en équation
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line, content
import "@local/circuitypst:0.0.1": node, to
to("idealTension", (-2, -1), (-2, 1), name: "idealTension", i: $i$)
to("capacitor", (-2,1), (2,1), label: $C$, i: $i$, v: $U_C$)
to("R", (2,1), (2,-1), label: $R$, i: $i$, v: $U_R$, name: "R2")
line((2,-1), (-2,-1), name: "tension")
}),
caption: [Circuit RC (Résistance/Condensateur)]
)
On a la loi des mailles $E = U_R + U_C$, la loi d'Ohm $U_R = R i$ et la caractéristique $U I$ du condensateur $i = c (d U_c)/(d t)$.
Ainsi on a $E = R i + U_C = R C (d U_c)/(d t) + U_C$ avec $tau = R C$ le temps caractéristique.
On en déduit une équation différentielle pour la charge $E C = R C (d q)/(d t) + q$.
Pour résoudre une équation différentielle linéaire d'ordre 1 :
- Si il y a un second membre, on cherche une _solution particulière_ $s_p$ de l'équation avec second membre (ici $s_p = E$).
- Chercher la forme générale des _solutions générales sans second membre_ $s_(g)(t)$. Il y a apparition de constantes (ici $s_(g)(t) = A e^(-t/tau)$)
- La solution est $s_p + s_g$. Il faut ensuite déterminer les constantes (ici $U_(C)(t) = E(1-e^(-t/tau))$)
== Durée du transitoire, temps de réponse
*Temps du réponse à X%* : Temps au bout duquel $(|U - U_0|)/(|U_(infinity)-U_0|)$ a varié de X%.
- $63% : tau$
- $95% : 3 tau$
- $99% : 5 tau$
== Bilan d'énergie
$ P_("fournie") &= P_("joule") + P_C "(loi d'Ohm et loi des mailles dans le circuit RC)" \ integral_0^t E i d t' &= integral_0^t R i^2 d t' + integral_0^t (d)/(d t')(1/2 C U^2) d t' $
== Analyse graphique d'une réponse indicielle
#grid(
columns: (50%, 50%),
{
"Méthode de la tangeante (dépréciée) :"
plot(
sample(x => (1 - calc.exp(-x/1)), min: 0.1, max: 6, samples: 50),
sample(x => x, min: 0.1, max: 1.5, samples: 50),
sample(x => 1, min: 0.1, max: 6, samples: 50),
width: 6cm,
mirror: false,
height: 4cm
)
},
{
"Méthode des 63% :"
plot(
sample(x => (1 - calc.exp(-x/1)), min: 0.1, max: 6, samples: 50),
sample(x => x, min: 1.499, max: 1.5, samples: 50),
sample(x => 1, min: 0.1, max: 6, samples: 50),
sample(x => 0.63, min: 0.1, max: 6, samples: 50),
width: 6cm,
mirror: false,
height: 4cm
)
}
)
== Dipôle équivalent à un condensateur en régime permanent
En régime permanent, un condensateur est équivalent à un *interrupteur ouvert* ($I = 0A$).
= La bobine
== Présentation
La *bobine* est un dipôle composé d'un enroulement d'un fil sur lui-même.
Une bobine est schématisée de la manière suivante :
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line
import "@local/circuitypst:0.0.1": node, to
to("bobine", (-2,0), (2,0), label: "L", v: $U$, i: $i$)
}),
caption: [Schématisation d'une bobine]
)
== Caractéristique U/I
En convention récepteur, $U_L = L (d i)/(d t)$ avec $L$ l'inductance (_self_) en Henry (H).
Les bobines sont des dipôles _linéaires_ (relation U/I), et ont une inductance de quelques dizaines de _mA_ en TP. $L$ dépend des propriétés de la bobine tels que le _nombre de fils_ et la _quantité de spires_ (tours).
== Approche énergétique
On a l'énergie stockée dans une bobine $E = 1/2 L i^2$ en convention générateur.
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line
import "@local/circuitypst:0.0.1": node, to
to("bobine", (-2,0), (2,0), label: "L", v: $U$, i: $i$, convention: 1)
}),
caption: [Schématisation d'une bobine]
)
#proof($P_("reçue") = - U I "et " U_L = - L (d i)/(d t) "(convention générateur)"$ + ". Donc " + $P_("reçue") = - (- L (d i)/(d t)) i = L (d i)/(d t) i = (d)/(d t)(1/2 L i^2)$ + " d'où " + $E = 1/2 L i^2$)
L'intensité est _continue_ dans un bobine.
== Associations séries et parallèles de bobines
=== Association série
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line, content
import "@local/circuitypst:0.0.1": node, to
to("bobine", (-2,0), (0,0), label: $L_1$, i: $i$, v: $U_1$)
to("bobine", (0,0), (2,0), label: $L_2$, i: $i$, v: $U_2$, name: "R2")
line((-1.5, -1.1), (1.5, -1.1), mark: (start: ">"), name: "tension")
content((rel: (-1.5, -0.3)), $U$)
content("R2", h(4em)+[équivalent à], anchor: "left")
to("bobine", (5,0), (9,0), label: $L$, i: $i$, v: $U_C$)
}),
caption: [Association série de bobines]
)
#proof("On a " + $U = U_1 + U_2 = L_1 (d i)/(d t) + L_2 (d i)/(d t) = (L_1 + L_2) (d i)/(d t)$)
=== Association parallèle
Dans le schéma suivant, on a $1/L_(\eq) = 1/L_1 + 1/L_2$ :
#figure(
cetz.canvas(length: 1cm, debug: false, {
import cetz.draw: line, content
import "@local/circuitypst:0.0.1": node, to
to("bobine", (-2,1), (0,1), label: $L_1$, i: $i_1$)
to("bobine", (-2,-1), (0,-1), label: $L_2$, i: $i_2$, name: "R2")
line((-2,1), (-2,-1))
line((0,1), (0,-1))
line((0,0), (0.5,0), name: "equiv")
line((-2,0), (-2.5,0))
node("currarrow", (-2.2, 0))
content((rel: (0, 0.3)), $i$)
line((-2, -1.7), (0, -1.7), mark: (start: ">"), name: "tension")
content((rel: (-1, -0.3)), $U$)
content("equiv", h(4em)+[équivalent à], anchor: "left")
to("bobine", (5,0), (9,0), label: $L$, i: $i$, v: $U$)
}),
caption: [Association parallèle de bobines]
)
== Dipôle équivalent à une bobine en régime permanent
En régime continu, la bobine se comporte comme un _fil_ ($U = 0V$). |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/142.%20property.html.typ | typst | property.html
Defining Property
March 2012As a child I read a book of stories about a famous judge in eighteenth
century Japan called <NAME>. One of the cases he decided
was brought by the owner of a food shop. A poor student who could
afford only rice was eating his rice while enjoying the delicious
cooking smells coming from the food shop. The owner wanted the
student to pay for the smells he was enjoying.The student was
stealing his smells!This story often comes to mind when I hear the RIAA and MPAA accusing
people of stealing music and movies.It sounds ridiculous to us to treat smells as property. But I can
imagine scenarios in which one could charge for smells. Imagine
we were living on a moon base where we had to buy air by the
liter. I could imagine air suppliers adding scents at an extra
charge.The reason it seems ridiculous to us to treat smells as property
is that it wouldn't work to. It would work on a moon base, though.What counts as property depends on what works to treat as property.
And that not only can change, but has changed. Humans may always
(for some definition of human and always) have treated small items
carried on one's person as property. But hunter gatherers didn't
treat land, for example, as property in the way we do.
[1]The reason so many people think of property as having a single
unchanging definition is that its definition changes very slowly.
[2]
But we are in the midst of such a change now. The record
labels and movie studios used to distribute what they made like air
shipped through tubes on a moon base. But with the arrival of
networks, it's as if we've moved to a planet with a breathable
atmosphere. Data moves like smells now. And through a combination
of wishful thinking and short-term greed, the labels and studios
have put themselves in the position of the food shop owner, accusing
us all of stealing their smells.(The reason I say short-term greed is that the underlying problem
with the labels and studios is that the people who run them are
driven by bonuses rather than equity. If they were driven by equity
they'd be looking for ways to take advantage of technological change
instead of fighting it. But building new things takes too long.
Their bonuses depend on this year's revenues, and the best way to
increase those is to extract more money from stuff they do already.)So what does this mean? Should people not be able to charge for
content? There's not a single yes or no answer to that question.
People should be able to charge for content when it works to charge
for content.But by "works" I mean something more subtle than "when they can get
away with it." I mean when people can charge for content without
warping society in order to do it. After all, the companies selling
smells on the moon base could continue to sell them on the Earth,
if they lobbied successfully for laws requiring us all to continue
to breathe through tubes down here too, even though we no longer
needed to.The crazy legal measures that the labels and studios have been
taking have a lot of that flavor. Newspapers and magazines are
just as screwed, but they are at least declining gracefully. The
RIAA and MPAA would make us breathe through tubes if they could.Ultimately it comes down to common sense. When you're abusing the
legal system by trying to use mass lawsuits against randomly chosen
people as a form of exemplary punishment, or lobbying for laws
that would break the Internet if they passed, that's ipso facto
evidence you're using a definition of property that doesn't work.This is where it's helpful to have working democracies and multiple
sovereign countries. If the world had a single, autocratic government,
the labels and studios could buy laws making the definition of
property be whatever they wanted. But fortunately there are still
some countries that are not copyright colonies of the US, and even
in the US, politicians
still seem to be afraid of actual voters, in sufficient numbers.
[3]The people running the US may not like it when voters or other
countries refuse to bend to their will, but ultimately it's in all
our interest that there's not a single point of attack for people
trying to warp the law to serve their own purposes. Private property
is an extremely useful idea — arguably one of our greatest inventions.
So far, each new definition of it has brought us increasing material
wealth.
[4]
It seems reasonable to suppose the newest one will
too. It would be a disaster if we all had to keep running an
obsolete version just because a few powerful people were too lazy
to upgrade.Notes[1]
If you want to learn more about hunter gatherers I strongly
recommend <NAME> The
Harmless People and The
Old Way.[2]
Change in the definition of property is driven mostly by
technological progress, however, and since technological progress
is accelerating, so presumably will the rate of change in the
definition of property. Which means it's all the more important
for societies to be able to respond gracefully to such changes,
because they will come at an ever increasing rate.[3]
As far as I know, the term "copyright colony" was first used
by <NAME>.[4]
The state of technology isn't simply a function of
the definition of property. They each constrain the other. But
that being so, you can't mess with the definition of property without
affecting (and probably harming) the state of technology. The
history of the USSR offers a vivid illustration of that.Thanks to <NAME> and <NAME> for reading drafts
of this.Japanese Translation
|
|
https://github.com/Arsenii324/matap-p2 | https://raw.githubusercontent.com/Arsenii324/matap-p2/main/t-repo/lecture6.typ | typst | #import "macros.typ" : *
= Лекция
== Операции со степенными рядами
=== Теорема о почленном дифференцировании/интегрировании
*Пусть:*
a) $f(x) = limits(sum)_(n = 0)^infinity$ - степенной ряд
b) $R > 0$ - радиус его сходимости
*Тогда:*
1) $f'(x) = limits(sum)_(n = 1)^infinity n c_n x^(n-1), R_1$
2) $limits(integral)_0^x f(t) d t = limits(sum)_(n = 0)^infinity c_n/(n+1) x^(n+1), R_2$
3) R_1 = R_2 = R
*Proof:*
3)
$R_1 = 1/ (limits(overline(lim))_(n -> infinity) root(n-1, abs(n c_n))) = 1/ (limits(overline(lim))_(n -> infinity) root(n, abs(c_n))) = R$
$R_2 = 1/ (limits(overline(lim))_(n -> infinity) root(n+1, abs(c_n/(n+1)))) = 1/ (limits(overline(lim))_(n -> infinity) root(n, abs(c_n))) = R$
1) $R_1 = R > 0$
Выберем на интервале $(-R, R)$ произвольную точку х и отрезок $[a, b]$ её содержащий. По т. о радиусе сходимости на этом отрезке ряд сходится равномерно.
Исходный ряд сходится в 0. $u_k in D([a, b])$
Тогда по теореме о почленном дифференцировании $f'(x) = limits(sum)_(n = 1)^infinity n c_n x^(n-1)$ выполняется, а в силу произвольности x выполняется везде.
2) $R_2 = R > 0$
Возьмем отрезок $[0, x]$. На нём есть равномерная сходимость. $u_k in R([0, x])$. Тогда по теореме о почленном интегрировании выполняется $limits(integral)_0^x f(t) d t = limits(sum)_(n = 0)^infinity c_n/(n+1) x^(n+1)$.
_#underline[Замечание]_
Радиусы сходимости могут быть равны, а множества сходимости отличаться.
$(limits(sum)^infinity_(n = 1) 1/n x^n)' underbrace(=, (-1, 1)) (limits(sum)^infinity_(n = 1) x^(n-1)))$
$R = 1$
В точке 1 первый ряд расходится. В точке -1 первый ряд сходится.
В точке 1 второй ряд расходится. В точке -1 второй ряд расходится.
Радиусы равны, а множества сходимости нет.
=== Теорема о нулях степенного ряда
*Пусть:*
a) $f(x) = limits(sum)_(n = 0)^infinity$ - степенной ряд
b) $R > 0$ - радиус его сходимости
c) Пусть существует ${x_n}_(n=1)^infinity subset (-R, R) \\ {0}$
$limits(lim)_(n -> infinity) x_n = 0$ и $f(x_n) = 0, forall n in NN$
*Тогда:*
$c_n = 0, forall n in NN_0$
*Proof:*
Индукция по индексу $n$.
$underline("База")$:
$n = 0, f in C(-R, R)$
Тогда $0 = limits(lim)_(n -> infinity) f(x_n) = underbrace(f(limits(lim)_(n -> infinity) x_n), "по непрерывности" ) = f(0) = c_0$
$underline("Предположение"):$
$c_0 = ... = c_n = 0$
$f(x) = limits(sum)_(k = 0)^infinity c_k x^k = limits(sum)_(k = n+1)^infinity c_k x^k = x^(n+1) underbracket(limits(sum)_(k = n+1)^infinity c_(k+n+1) x^k, g(x))$
$R_(g(x)) = R_(f(x))$ как предел сдвинутой на $n$ последовательности.
$g(x_n) = 0, forall n$
$0 = f(x_n) = underbracket( x_n^(n+1), != 0) g(x_n) ==> c_(0+n+1) = 0$ (следует из базы индукции для g). Доказано.
== Аналитические функции
=== Опр. ряд Тейлора
Пусть есть $f in C^infinity ({a}), a in E, f: E -> R$
Значит $ exists f^((k)) (a), forall k in NN_0$
Тогда $T_(f, a) (x) = limits(sum)_(k = 0)^infinity (f^((k)) (a)) / k! (x-a)^k underbracket(=, M) f(x)$
$a in M$ точно можно гарантировать.
_#underline[Пример 1]_
$a = 0$
$f(x) = cases(e^(-1/x^2) "при" x != 0, 0 "при" x = 0) ==> f^((k)) (x) = cases(Q(x) e^(-1/x^2) "при" x != 0, 0 "при" x = 0) ==> f^((k)) (0) = 0, forall k in NN_0 ==> T_(f, 0) (x) equiv 0$
_#underline[Пример 2]_
$g(x) = limits(integral)_0^infinity e^(-t) cos(t^2 x ) d t)$
$g^((2k)) (0) = (4k)! dot (-1)^k $
$g^((2k + 1)) (0) = 0$
$T_(g, 0) = limits(sum)_(k=0)^infinity ((4k)! (-1)^k)/(2k)! x^(2k) arrow.not 0, x!=0 ==> R = 0$
=== Опр. аналитичской функции
$f: E -> R$, $f$ аналитична в точке $a$, если $exists delta > 0 : T_(f, a) (x) = f(x), forall x in (a - delta, a + delta) sect E$
=== Теорема Тейлора
*Пусть:*
${c_k} - $произвольная последовательность
*Тогда:*
$exists f in C^infinity ({0}) : T_(f, 0) (x) = limits(sum)_(k = 0)^infinity c_k/k! x^k$
(Для любой последовательности вещественных чисел существует функция $f in C^infinity ({0})$, такая что $f^((n)) (0) = c_n, forall n in NN_0$)
=== Достаточные условия аналитичности
*Пусть:*
a) $f in C^infinity (-r, r), $ для некоторого $r > 0$
b) $exists L > 0, exists lambda in [0, 1) : forall n in NN_0 ,forall x in (-r, r) --> abs(f^((n)) (x)) <= L^n n ^(n lambda)$
*Тогда:*
$f(x) = T_(f, 0) (x), forall x in (-r , r)$
*Proof:*
В силу формулы Тейлора с остаточным членом в форме Лагранжа имеем:
$f(x) = underbrace(limits(sum)_(k = 0)^(N-1) (f^((k)) (a)) / k! x^k, ->T_(f, 0) (x)) + underbrace((f^((N)) (tau_N x)) / (N)! x^(N), -> 0), tau_N in (0, 1)$
В силу условия (b) имеем оценку:
$0 <= abs((f^((N)) (tau_N x)) / (N)! x^(N)) <= underbrace((L^N N ^(N lambda)) / N! r^N, "нужно чтобы это" -> 0)$
Обозначим правую часть за $b_n$. Тогда $b_(n+1)/b_n = (L r)/(n+1) ((N+1)/N)^(N lambda) (N + 1)^lambda -> L dot r dot e^lambda dot 0 -> 0$
Тогда по Даламберу $limits(sum) b_N$ сходится $=> b_N -> 0$.
|
|
https://github.com/timetraveler314/Note | https://raw.githubusercontent.com/timetraveler314/Note/main/24Spring/AI/AI.typ | typst | #import "@local/MetaNote:0.0.1" : *
#import "@preview/physica:0.9.0": *
#set text(font:("linux libertine", "FandolSong"), lang: "cn")
#show: doc => MetaNote(
title: [
Introduction to Artificial Intelligence
],
authors: (
(
name: "timetraveler314",
affiliation: "University of Genshin",
email: "<EMAIL>",
),
),
doc,
)
#let vb = math.bold($b$)
#let vu = math.bold($u$)
#let vv = math.bold($v$)
#let vw = math.bold($w$)
#let vx = math.bold($x$)
#let vy = math.bold($y$)
#let mX = math.bold($X$)
#let mY = math.bold($Y$)
#let argmin = math.limits(math.op("argmin"))
#let argmax = math.limits(math.op("argmax"))
#let sign = math.op("sign")
#outline()
= Lec 9 机器学习和线性回归 (2024/3/21)
== 参数化模型
最简单的参数化模型:线性模型 (Linear Model).
$ f(vx) = vw^T vx + b. $
其中 $vx in RR^d$ 是输入, $vw in RR^d$ 是权重向量, $b in RR$ 是偏置项.
== 线性回归训练
- 训练目标:最小化损失函数.
- 对于线性回归,损失函数通常是均方误差 (Mean Squared Error, MSE), 又名平方损失 (Squared Loss).
$ L(f(vx_i),y_i) = (f(x_i)-y_i)^2. $
惩罚预测值偏离真实值 (ground truth) 太大的情况.
- 通过在训练集上最小化平均损失函数来优化参数.
$ argmin_(w,b) 1/n sum_i L(f(vx_i),y_i) $
训练问题转化为求解以上优化问题.
== 梯度下降
分析上述问题,我们将待优化的*目标* (objective) 定义为 $vw, b$ 的函数:
$ J(vw, b) = 1/n sum_i L(f(x_i)-y_i). $
- 随机选定$vw, b$的初始值,逐步调整$vw, b$的值以降低$J(vw, b)$.
- 思路:每次沿使$J(vw, b)$减小最快的方向走一小步.
$ w <- w - alpha dot pdv(J,vw), b <- b - alpha dot pdv(J,b). $
其中事先指定的超参数 $alpha$ 是*学习率* (learning rate).
- 不断迭代,直至 $J$ 收敛(例如相邻两次迭代$J$的变化小于某个阈值).
这就是*梯度下降* (Gradient Descent) 算法.
=== 梯度的细节
$ grad J = mat(pdv(J,vw);pdv(J,b)) in RR^(d+1) $
上式定义了$J$关于$vw, b$的梯度. 考察梯度的几何意义:
考虑增量 $Delta x, Delta y$.
$ Delta f = pdv(f,x) Delta x + pdv(f,y) Delta y &= grad f dot (Delta x, Delta y) \
&= norm(grad f) norm(mat(Delta x; Delta y)) cos(theta). $
$Delta f$ 最大时,$theta=0$,此时 $Delta x, Delta y$ 与 $grad f$ 同向.
这说明梯度的几何意义:梯度方向是函数增长最快的方向.
== 线性回归的梯度
- 计算 $J(vw, b)$ 关于 $vw, b$ 的梯度, 首先将 $J$ 写成矩阵形式:
$ J = 1/n underbrace((vw^T mX + vb - vy), "行向量") (vw^T mX + vb - vy)^T. $
其中 $mX = mat(vx_1, vx_2, dots, vx_n)$ 是输入数据矩阵, $vy = mat(y_1, y_2, dots, y_n)$ 是标签向量.
#theorem[
$ pdv(J,vw) &= 2/n sum_i (vw^T vx_i + b - y_i) vx_i = 2/n mX (vw^T mX + vb - vy)^T, \
pdv(J,b) &= 2/n sum_i (vw^T vx_i + b - y_i). $
]
#note[
根据“维度相容原则”可简记如下:
$ pdv(J,vw) = 2/n pdv(vw^T mX + vb - vy, vw) (vw^T mX + vb - vy)^T = 2/n mX (vw^T mX + vb - vy)^T, $
下面证明是通过严格计算微分得到的.
]
#proof[
计算 $J$ 的微分:
$ dif J = 1/n [ dif(vw^T mX + vb - vy) (vw^T mX + vb - vy)^T + (vw^T mX + vb - vy) dif(vw^T mX + vb - vy)^T ]. $
这里注意应用内积原则:
#note("矩阵求导常用的内积原则")[
对列向量 $vu,vv$,
$ vu^T vv = vv^T vu. $
对行向量 $vu,vv$,
$ vu vv^T = vv vu^T. $
因为以上的式子都表示内积.
]
$ (vw^T mX + vb - vy) dif(vw^T mX + vb - vy)^T &= (vw^T mX + vb - vy) [dif(vw^T mX + vb - vy)]^T \
&= dif(vw^T mX + vb - vy) (vw^T mX + vb - vy)^T ("与第一项相同") $
$ dif J &= 2/n dif (vw^T mX + vb - vy) dot (vw^T mX + vb - vy)^T. $
计算 $dif(vw^T mX + vb - vy)$:
$ dif(vw^T mX + vb - vy) = dif(vw^T mX) = (dif vw)^T mX. $
用标量矩阵函数求导的核心:
$ dif f = tr(pdv(f,mX)^T dif mX). $
对比 $ dif J = 2/n (dif vw)^T X (vw^T mX + vb - vy)^T = 2/n (vw^T mX + vb - vy) mX^T dif vw, $
得到 $ pdv(J,vw) &= 2/n mX(vw^T mX + vb - vy)^T \
&= 2/n sum_i (vw^T vx_i + b - y_i) vx_i. $
对 $b$ 求导是显然的.
]
== 凹凸性与优化
- 凹函数 (Convex Function) 的定义:对于任意 $x, y$ 和 $0 <= lambda <= 1$,
$ f(lambda x + (1-lambda) y) <= lambda f(x) + (1-lambda) f(y). $
- 凹函数的性质:
#theorem("凹函数的性质")[
凹函数的局部最小值是全局最小值.
]
#proof[
反证.
- 假设 $x^*$ 是局部最小点,$x'$ 是全局最小点,且 $f(x') < f(x^*)$.
- 则取 $x = lambda x^* + (1-lambda) x'$,有 $f(x) <= lambda f(x^*) + (1-lambda) f(x') < f(x^*)$.
- 取 $lambda->1$附近,知 $x^*$ 不是局部最小点,矛盾.
]
因此我们可以考虑线性回归问题:
#theorem[
线性回归的损失函数 $J(vw, b)$ 是凸函数.
]
#proof[
考虑 Hessian 矩阵 $H$:
$ H &= mat(pdv(J,vw,2), pdv(J,vw,b); pdv(J,b,vw), pdv(J,b,2))
= mat(2/n mX mX^T, 2/n mX bold(1)^T; 2/n mX^T bold(1), 2/n n) \
&= 2/n vec(mX,bold(1)) vec(mX,bold(1))^T. $
因此 $H$ 是半正定矩阵,$J$ 是凸函数.
]
=== 学习率的调整
- 学习率过大可能导致算法不收敛,过小可能导致收敛速度慢.
- 要选择适中的学习率,可以考虑自适应学习率算法,逐步减小.
= Lec 10. 逻辑回归、多分类和正则化 (2024/3/25)
== 回顾:经验风险最小化框架 (ERM)
大部分监督学习都遵循基本框架:经验风险最小化 (Empirical Risk Minimization, ERM),区别仅在于选择的具体损失函数.
- ERM 框架:在训练集上最小化损失函数.
== 逻辑回归
逻辑回归处理二分类问题. 仍然使用线性模型,但采用交叉熵损失函数 (Cross Entropy Loss).
=== 二分类问题
- 标签只有两种. e.g. $y in {-1,1}$.
- 一般不直接让 $f(x)$ 拟合 $y$,而是使用 $sign(f)$ 将实数输出转化为二分类的类别输出. 因而转化为了一个回归问题.
- 损失函数的选择:
朴素想法:0-1 损失函数:
$ L(f(x),y) = cases(0\, space f(x) y >= 0, 1\, space "otherwise")
<=> L(f(x),y) = cases(0\, space "if " sign(f(x)) = y, 1\, space "otherwise"). $
这是最直接的目标,但是不连续,不易优化.
=== 最大似然框架 (Maximum Likelihood)
- 最大似然估计的原则:
(1) 对观测数据进行(条件)概率建模:
每个观测数据即为一个训练样本.
对于判别式模型,只建模 $p(y|x;theta)$, $theta$ 是模型参数.
(2) 通过最大化观测数据在给定模型下的*似然*(例如,把训练样本预测正确的概率),来调整模型参数.
*独立同分布假设*下,MLE: $theta^* = argmax_theta product_i p(y=y_i|x=x_i;theta). $ 简写为
$ theta^* = argmax_theta product_i p(y_i|x_i;theta). $
但是大量乘法会带来数值精度问题,因此通常转化为对数似然最大化:
$ theta^* = argmax_theta sum_i log p(y_i|x_i;theta). $
=== 逻辑回归的最大似然估计
- 建模:
已有线性模型 $f(x) = vw^T vx + b$. 只需将其转化为正类的概率.
采用 Sigmoid 函数:
#note("Sigmoid 函数")[
$ sigma(z) = 1/(1+exp(-z)). $
$ 1- sigma(z) = sigma(-z). $
将 $RR$ 映射到 $[0,1]$ 区间,可以看作是概率值.
]
则
$ p(y=1|x;vw,b) = sigma(f(x)) = sigma(y dot f(x)), $
$ p(y=-1|x;vw,b) = 1- sigma(f(x)) = sigma(y dot f(x)). $
二者形式恰统一.
- 优化对数似然:
这里最优化问题为
$ &argmax_(vw,b) sum_i log sigma(y dot f(x)) \
= & -argmax_(vw,b) sum_i log (1+exp(-y_i (vw^T vx_i + b))) . $
写成最小化形式,这就是逻辑回归的*ERM*形式.
$ argmin_(vw,b) sum_i log (1+exp(-y_i (vw^T vx_i + b))). $
其中提取出损失函数:Logistic Loss / Log Loss.
=== 另一视角:替代损失函数
以上从最大似然估计的角度推导了逻辑回归的损失函数,但也可以从另一角度看待:
- 交叉熵损失函数是$0-1$损失的上界,且是凸函数.
- 合页损失 (Hinge Loss):$L = max(0,1-y_i f(x_i))$ 同样是$0-1$损失的上界.
== 多分类问题: Softmax 回归
#let softmax = math.op("softmax")
=== $K$ 分类问题
- 标签有 $K$ 个类别,$y in {1,2,dots,K}$.
- 共同训练 $K$ 个模型 $f_1(x), f_2(x), dots, f_K(x)$,每个模型输出属于该类别的概率.
- 概率归一化:Softmax函数
#definition("Softmax 函数")[
$ softmax(z) = [exp(z_1), exp(z_2), dots, exp(z_K)] / (sum_i exp(z_i)). $
]
= Lec 12. 神经网络与反向传播
== |
|
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/main.typ | typst | MIT License | #import "lib/multi-bib.typ": *
#import "lib/layout.typ": *
// set show rules
#show: layout
#include {"./chapters/00_title/titlepage.typ"}
#include {"./chapters/01_chapter/mod.typ"}
#include {"./chapters/02_chapter/mod.typ"}
#include {"./chapters/03_chapter/mod.typ"}
|
https://github.com/Ligandlly/typst-templates | https://raw.githubusercontent.com/Ligandlly/typst-templates/main/panda.typ | typst | MIT License | // Some definitions presupposed by pandoc's typst output.
#let blockquote(body) = [
#set text( size: 0.92em )
#block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body]
]
#let horizontalrule = [
#line(start: (25%,0%), end: (75%,0%))
]
#let endnote(num, contents) = [
#stack(dir: ltr, spacing: 3pt, super[#num], contents)
]
#show terms: it => {
it.children
.map(child => [
#strong[#child.term]
#block(inset: (left: 1.5em, top: -0.4em))[#child.description]
])
.join()
}
#let conf(
title: none,
authors: none,
date: none,
abstract: none,
cols: 1,
margin: (x: 1.25in, y: 1.25in),
paper: "us-letter",
lang: "en",
region: "US",
font: (),
fontsize: 11pt,
sectionnumbering: none,
doc,
) = {
set page(
paper: paper,
margin: margin,
numbering: "1",
)
set par(justify: true)
set text(lang: lang,
region: region,
font: font,
size: fontsize)
set heading(numbering: sectionnumbering)
if title != none {
align(center)[#block(inset: 2em)[
#text(weight: "bold", size: 1.5em)[#title]
]]
}
if authors != none {
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 1.5em,
..authors.map(author =>
align(center)[
#author.name \
#author.affiliation \
#author.email
]
)
)
}
if date != none {
align(center)[#block(inset: 1em)[
#date
]]
}
if abstract != none {
block(inset: 2em)[
#text(weight: "semibold")[Abstract] #h(1em) #abstract
]
}
if cols == 1 {
doc
} else {
columns(cols, doc)
}
}
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/states/counters.md | markdown | MIT License | # Counters
<div class="warning">This section is outdated. It may be still useful, but it is strongly recommended to study new context system (using the reference).</div>
Counters are special states that _count_ elements of some type.
As with states, you can create your own with identifier strings.
_Important:_ to initiate counters of elements, you need to _set numbering for them_.
## States methods
Counters are states, so they can do all things states can do.
```typ
#set heading(numbering: "1.")
= Background
#counter(heading).update(3)
#counter(heading).update(n => n * 2)
== Analysis
Current heading number: #counter(heading).display().
```
```typ
#let mine = counter("mycounter")
#mine.display()
#mine.step()
#mine.display()
#mine.update(c => c * 3)
#mine.display()
```
## Displaying counters
```typ
#set heading(numbering: "1.")
= Introduction
Some text here.
= Background
The current value is:
#counter(heading).display()
Or in roman numerals:
#counter(heading).display("I")
```
Counters also support displaying _both current and final values_ out-of-box:
```typ
#set heading(numbering: "1.")
= Introduction
Some text here.
#counter(heading).display(both: true) \
#counter(heading).display("1 of 1", both: true) \
#counter(heading).display(
(num, max) => [#num of #max],
both: true
)
= Background
The current value is: #counter(heading).display()
```
## Step
That's quite easy, for counters you can increment value using `step`. It works the same way as `update`.
```typ
#set heading(numbering: "1.")
= Introduction
#counter(heading).step()
= Analysis
Let's skip 3.1.
#counter(heading).step(level: 2)
== Analysis
At #counter(heading).display().
```
## You can use counters in your functions:
```typ
#let c = counter("theorem")
#let theorem(it) = block[
#c.step()
*Theorem #c.display():*
#it
]
#theorem[$1 = 1$]
#theorem[$2 < 3$]
```
|
https://github.com/Shuenhoy/citext | https://raw.githubusercontent.com/Shuenhoy/citext/master/README.md | markdown | MIT License | # Citext
- - -
This package provides:
* Bilingual bibliography hack before official Typst support for CSL-M (https://github.com/typst/citationberg/issues/5)
* `parencite` `citep` like support
It calls `citation.js` from QuickJS and WebAssembly using https://github.com/Enter-tainer/jogs.
It is designed for `gb-t-7714-2015-numeric-bilingual.csl` but may work for other CSL styles with `numeric` category.
```typst
#import "package/lib.typ": *
#let bib = init_citation(read("test.bib"))
#show: show-extcite.with(bib: bib)
@texbook
@zjugradthesisrules
@latex2e
@zjugradthesisrules<citeauthor>
@zjugradthesisrules<citep>
@lesk:1977<citet>
@latex:companion<citef>
// #show bibliography: none
#bibliography("test.bib", style: "gb-7714-2015-numeric")
= 参考文献
#extbib(bib)
```
|
https://github.com/weeebdev/cv | https://raw.githubusercontent.com/weeebdev/cv/main/modules/publications.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Publications")
#cvPublication(
bibPath: "../src/publications.bib",
keyList: (
"serekAnalysisSupervisorsStudents2021a",
"serekApplicationKmeansPerception2021a",
"serekPartofspeechTaggingKazakh2021a"),
refStyle: "apa"
)
|
https://github.com/cafeclimber/typst-psu | https://raw.githubusercontent.com/cafeclimber/typst-psu/main/main.typ | typst | #import "psu_thesis.typ": *
#show: psu_thesis.with(
title: "Dissertation Title",
author: "<NAME>",
department: "Your Department",
degree_type: "doctorate", // one of "doctorate" or "masters"
committee_members: (
(
name: "Committee Member 1",
title: "Committee Member Title",
)
),
date: ( // Date of degree CONFERRAL
year: "2023",
month: "December",
day: "15",
)
)
// Here you can include chapters (or anything) written in seperate files. One is given as an example
#include "ch1.typ"
#bibliography("citations.bib", style: "ieee")
#pagebreak()
#show: appendices
#heading("Appendix Title", supplement: "Appendix") <app_a>
|
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/bigbook.typ | typst | #import "src/preamble.typ":*
#let chapter(filename) = {
include filename
}
#show: evan.with(
title: "Notes on Programmable Cryptography",
author: "0xPARC",
date: datetime.today(),
)
#quote[
I can prove to you that I have a message $M$ such that
$op("sha")(M) = "0xa91af3ac..."$, without revealing $M$.
But not just for the hash function SHA.
I can do this for any function you want.
]
#toc
#pagebreak()
#set heading(offset: 1)
#part[Introduction]
#chapter("src/bigbook-frontmatter.typ")
#chapter("src/intro.typ") // needs some rewriting though
#part[Two-party Computation]
#chapter("src/mpc.typ")
#chapter("src/ot.typ")
#chapter("src/2pc-takeaways.typ")
#part[SNARKs Prelude: Elliptic Curves and Polynomial Commitments]
#chapter("src/ec.typ")
#chapter("src/pair.typ")
#chapter("src/kzg.typ")
#chapter("src/kzg-takeaways.typ")
#part[Your first SNARK: The PLONK Protocol]
#chapter("src/zkintro.typ")
#chapter("src/plonk.typ")
#chapter("src/copy-constraints.typ")
#chapter("src/fs.typ")
#chapter("src/snark-takeaways.typ")
#part[Another STARK: GROTH-16]
#chapter("src/ipa.typ")
#chapter("src/groth16.typ")
#part[Binius]
#chapter("src/sumcheck.typ")
#part[Fully Homomorphic Encryption with LWE]
#chapter("src/fhe0.typ")
#chapter("src/lwe.typ")
#chapter("src/fhe2.typ")
#chapter("src/fhe3.typ")
#chapter("src/fhe-takeaways.typ")
#part[Oblivious RAM]
#part[Obfuscation]
#part[Others]
#chapter("src/cq.typ")
|
|
https://github.com/avonmoll/ifacconf-typst | https://raw.githubusercontent.com/avonmoll/ifacconf-typst/main/README.md | markdown | MIT No Attribution | # abiding-ifacconf
(unofficial) IFAC Conference Template for Typst
IFAC stands for [International Federation of Automatic Control](https://ifac-control.org/).
This repository is meant to be a port of the existing author tools for conference papers (e.g., for LaTeX, see [ifacconf_latex.zip](https://www.ifac-control.org/conferences/author-guide/copy_of_ifacconf_latex.zip/view)) for Typst.
## Usage
Running the following command will create a new directory with all the files that are needed:
```
typst init @preview/abiding-ifacconf
```
## Configuration
This template exports the `ifacconf` function with the following named arguments:
- `authors`: (default: ()) array of authors. For each author you can specify a name, email (optional), and affiliation. The affiliation must be an integer corresponding to an entry in the 1-indexed affiliations list (or 0 for no affiliation).
- `affiliations`: (default: ()) array of affiliations. For each affiliation you can specify a department, organization, and address. Everything is optional (i.e., an affiliation can be an empty array).
- `abstract`: (default: none) the paper's abstract. Can be omitted if you don't have one.
- `keywords`: (default: ()) array of keywords to display after the abstract
- `sponsor`: (default: none) acknowledgment of sponsor or financial support (appears as a footnote on the first page)
## Minimal Working Example
```typst
#import "@preview:abiding-ifacconf:0.1.0": *
#show: ifacconf-rules
#show: ifacconf.with(
title: "Minimal Working Example",
authors: (
(
name: "<NAME>",
email: "<EMAIL>",
affiliation: 1,
),
),
affiliations: (
(
department: "Engineering",
organization: "National Institute of Standards and Technology",
address: "Boulder, CO 80305 USA",
),
),
abstract: [
Abstract should be 50-100 words.
],
keywords: ("keyword1", "keyword2"),
sponsor: [
Sponsor information.
],
)
= Introduction
A minimum working example (with bibliography) @Abl56.
#lorem(80)
#lorem(80)
#bibliography("refs.bib")
```
## Full(er) Example
See [`main.typ`](https://github.com/avonmoll/ifacconf-typst/blob/main/template/main.typ).
## Dependencies
- typst 0.11.0
- ctheorems 1.1.0 (a Typst package for handling theorem-like environments)
## Notes, features, etc.
- the call to `#show: ifacconf-rules` is necessary for some show rules defined in `template.typ` to get activated
- `ifac-conference.csl` is a lightly modified version of `apa.csl` and is included in order to change the citation format from, e.g., `(Able 1956)` to `Able (1956)` in order to match `ifacconf_latex`
- Tables have formatting rules that get activated inside calls to `figure` with `kind: "table"`; a convenience function `tablefig` is provided which sets this automatically
- all theorem-like environments that were available in `ifacconf_latex` are defined in `template.typ`; simply call, for example, `#theorem[Content...] ... #proof[Proof...]`
- the LaTeX version does not include a QED symbol at the end of proofs, however one is included here (this is easy to change)
- Typst did not seem to like BibTeX citation keys containing colons (which was how they came from `ifacconf_latex`)
- alignment for linebreaks in long equations is somewhat manual (e.g., for equation (2) in `ifacconf.typ`) but probably there is a better way to handle this now or in the future
- the files `refs.bib` (essentially) and `bifurcation.jpg` come from `ifacconf_latex`
- the file `template/main.typ` is modeled directly after `ifacconf.tex` by <NAME>
- the `citep` function renders citations like `(Keohane, 1958)` instead of the default style of `Keohane (1958)`
## License
This template is licensed according to the MIT No Attribution license (see `LICENSE.MD`).
The files in the `CSL` folder are licensed according to `CSL/LICENSE.md` (CC BY/SA 4.0) because it is a lightly modified version of `apa.csl` by <NAME> which is also licensed by a CC BY/SA license.
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/place-01.typ | typst | Other | // Test how the placed element interacts with paragraph spacing around it.
#set page("a8", height: 60pt)
First
#place(bottom + right)[Placed]
Second
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/dimension/dim-5.typ | typst | Other | #import "/lib/draw.typ": *
#import "/lib/glossary.typ": tr
#let start = (0, 0)
#let end = (300, 170)
#let base = (128, 45)
#let up = 123
#let down = 45
#let width = 85
#let line-color = gray.darken(30%)
#let lt = (base.at(0), base.at(1) + up)
#let rb = (base.at(0) + width, base.at(1) - down)
#let bbox-calc = (lt, rb, arg) => {
let (l, t, r, b) = arg
return ((lt.at(0) + l, lt.at(1) - t),
(rb.at(0) - r, rb.at(1) + b))
}
#let (bbox-lt, bbox-rb) = bbox-calc(lt, rb, (9, 37, 8, 61))
#let bbox-ct = (
(bbox-lt.at(0) + bbox-rb.at(0)) / 2,
bbox-lt.at(1),
)
#let graph = with-unit((ux, uy) => {
// mesh(start, end, (50, 50), stroke: 1 * ux + gray)
rect(
lt, end: rb,
stroke: 1.4 * ux + line-color,
)
rect(
bbox-lt, end: bbox-rb,
stroke: 1 * ux + line-color,
)
txt(text(fill: line-color)[#tr[bounding box]], bbox-lt, anchor: "lb", size: 12 * ux, dy: 4)
let line-stroke = 1 * ux + line-color
segment(
(0, base.at(1)), (end.at(0), base.at(1)),
stroke: line-stroke,
)
txt([#tr[baseline]], (0, base.at(1)), size: 12 * ux, anchor: "lb", dy: 2)
txt([x+], base, size: 145 * ux, anchor: "lb", dx: -75)
})
#canvas(end, start: start, width: 50%, graph)
|
https://github.com/0x6e66/hbrs-typst | https://raw.githubusercontent.com/0x6e66/hbrs-typst/main/main.typ | typst | #import "template/template.typ": *
#show: thesis
// #auto_import("00_introduction")
// #auto_import("01_fundamentals")
#include "modules_de/00_introduction.typ"
#pagebreak()
#include "modules_de/01_fundamentals.typ" |
|
https://github.com/florianhartung/studienarbeit | https://raw.githubusercontent.com/florianhartung/studienarbeit/main/work/dhbw_template/lib.typ | typst | #import "titlepage.typ": titlepage
#import "declaration_of_authenticity.typ": declaration_of_authenticity
#import "@preview/hydra:0.3.0": hydra
#let dhbw_template(
title: [Placeholder (title)],
author: [Placeholder (author)],
course: [Placeholder (course)],
submissiondate: datetime(year: 2000, month: 1, day: 1),
workperiod_from: datetime(year: 2000, month: 1, day: 1),
workperiod_until: datetime(year: 2000, month: 1, day: 1),
matr_num: 9999999,
supervisor: [Placeholder (supervisor)],
abstract: [Placeholder (abstract)],
show_jump_to_table_of_contents: true,
contents,
) = [
// General formatting
#set text(size: 12pt, font: "Arial", lang: "de")
#set page(paper: "a4", margin: 25mm)
#let in-outline = state("in-outline", false)
#show outline: it => {
in-outline.update(true)
it
in-outline.update(false)
}
#if show_jump_to_table_of_contents {
place(top + left, link(<outline_>)[#box(inset: 10mm, fill: red)[*Goto table of contents*]])
}
// Titlepage
#titlepage(
title,
author,
course,
submissiondate,
workperiod_from,
workperiod_until,
matr_num,
supervisor,
)
#pagebreak()
// Start page numbering
#set page(numbering: "I")
#counter(page).update(1)
// Declaration of authenticity
#declaration_of_authenticity(title)
#pagebreak()
// Abstract
#align(center)[
#box(width: 80%)[
#text(size: 1.2em)[#align(center)[*Abstract*]]
#par(justify: true, first-line-indent: 0.2em)[
#abstract
]
]
]
#pagebreak()
// Outline
<outline_>
#set par(leading: 1.20em)
// Mark top-level headings as strong
#show outline.entry.where(level: 1): it => {
if it.element.func() == heading {
v(10mm, weak: true)
strong(it)
} else {
it
}
}
#outline(indent: auto, depth: 3)
#pagebreak()
// List of figures
#outline(title: [List of figures #v(7mm)], target: figure.where(kind: image))
#pagebreak()
// List of tables
#outline(title: [List of tables #v(7mm)], target: figure.where(kind: table))
#pagebreak()
#outline(title: [List of code listings#v(7mm)], target: figure.where(kind: raw))
#pagebreak()
#let is_on_new_section_page = state("is_on_new_section_page", false)
// General formatting for contents
#set par(justify: true, first-line-indent: 5mm)
#set heading(numbering: "1.1 ")
#set page(
numbering: "1",
margin: ("top": 35mm, "left": 25mm, "right": 40mm, "bottom": 30mm),
header: [
#locate(loc => {
if is_on_new_section_page.get() {
return []
}
let elems = query(selector(heading).before(loc), loc).filter(elem => elem.outlined)
if elems == () {
[]
} else {
elems.last()
}
})
#line(length: 100%)
],
)
// Line height and resulting vertical spacings
#let line_height = 1.0em
#set par(leading: line_height)
#show par: set block(spacing: line_height)
#show heading: it => {
block(above: 2.0 * line_height, below: 1.2 * line_height)[ #it ]
}
// Reset page counter
#counter(page).update(1)
#show heading.where(level: 1): it => {
is_on_new_section_page.update(true)
colbreak(weak: true)
it
is_on_new_section_page.update(false)
}
#contents
]; |
|
https://github.com/lcharleux/LCharleux_Teaching_Typst | https://raw.githubusercontent.com/lcharleux/LCharleux_Teaching_Typst/main/src/courses/MECA512_Cinematique/MECA512_Cinematique.typ | typst | MIT License | // TEMPLATE IMPORT
#import "../../templates/conf.typ": conf, todo, comment, idea, note, important
#import "../../templates/drawing.typ": dvec, dpoint, dangle3p, dimension_line, arotz90, arrnumprod, arrsub, anorm, normalize, rotmat2D, dispvcol, arradd, mvec, arrcrossprod, arrdotprod, torseur1, torseur2, torseur6, part_label
#import "@preview/unify:0.6.0": num, qty, numrange, qtyrange
#import "@preview/cetz:0.2.2"
#import "@preview/showybox:2.0.1": showybox
#import "@preview/chic-hdr:0.4.0": *
#import cetz.draw: *
#import "@preview/physica:0.9.3": *
#set math.equation(numbering: "(1)")
// DOCUMENT SETUP
#let course = "MECA512: Cinématique"
#let block = "Cinématique des solides indéformables"
#let section = "MECA3-FISA"
#let teacher = "<NAME>"
#let email = "<EMAIL>"
#show: doc => conf(
course: course,
block: block,
section: section,
teacher: teacher,
email: email,
doc,
)
= Cours
#todo[MAJ du cours]
#bibliography("../../biblio.bib", style: "institute-of-electrical-and-electronics-engineers", title: "Références") |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p2_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test for no collisions between descenders/ascenders and attachments
$ sup_(x in P_i) quad inf_(x in P_i) $
$ op("fff",limits: #true)^(y) quad op("yyy", limits:#true)_(f) $
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/017%20-%20Dragons%20of%20Tarkir/002_The%20Great%20Teacher's%20Student.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Great Teacher's Student",
set_name: "Dragons of Tarkir",
story_date: datetime(day: 04, month: 03, year: 2015),
author: "<NAME>",
doc
)
#emph[In another time there were no dragons. In another time Narset was the khan of a clan known as the Jeskai. In another time she felt a great potential within her—one that she would never release, for in that time she fell at the hands of Zurgo Helmsmasher, the khan of the Mardu. But that time is gone, lost forever to endless eternities. This time is all that remains. In this time, dragons fill the skies of Tarkir, there are no khans, there is no clan known as the Jeskai, and Zurgo is a bell-striker. But one thing remains the same: Narset has a secret power burning inside of her—a restless potential that pulls on her, begging to be released.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"You have to learn to let things go." Her mother's words swam in Narset's mind as she teetered on the precipice of the Eternities.
Oh, how she wished she could! How she longed to forget what was and leap into the unknown. Her skin crawled with impatient anticipation and her legs twitched and burned with a familiar restlessness, one she had known her whole life. Only now it was amplified; it was as if her body was telling her that this was the place she had always been meant to go, this was where she had been heading all these years.
She wanted to take the next step more than she had ever wanted anything.
There was so much out there. So many new things. So much to learn. So much to see.
#figure(image("002_The Great Teacher's Student/01.png", height: 30%), caption: [], supplement: none, numbering: none)
Then why didn't she go? What was holding her back?
Ojutai.
The thought of him nearly dragged her all the way back to herself.
He was the reason she was clinging to the edge; he was the reason she had been holding on for so many years, fighting her restlessness.
Ojutai. Her teacher. Her dragon.
She hadn't thought about him that way in a long time.
She wished she could pick up the pieces and put them back together the way they were before; before, when she didn't know the things she knew now; before, when he was everything, when he knew everything, and when he held the promise to share it all with her.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Fresh fruit! Honey-sweet apples!"
"Carrots plucked straight from the field! You can still see the dirt on 'em. Look here!"
"Hot breads! Nothing better than piping hot bread!"
The cries of the merchants, the bold colors of the wares, and the too-sweet aromas of the produce were like walls that made the marketplace feel too tight, too close, too much. The muscles of Narset's legs twitched and her lungs felt cramped. She tugged at her robe; it was strangling her. Her mother must have cinched it too tightly.
"Stand still," her mother scolded from above. "You'll knock something over." She was poring over the apples at the top of a tall mound too high for Narset to see.
Narset tried to stand still, but she couldn't. The restlessness inside her wanted her to move. Sometimes when she felt that way she distracted herself. She would count things, or search for patterns, or study people's expressions. But she knew the marketplace too well; she knew its numbers and she knew its patrons. She had already taken inventory. The man with the cane was limping less that day, putting more weight on his bad leg; Narset supposed the balm he had purchased from the herbalist the week before had worked to ease the pain. There were, as usual, three dozen meat slabs hanging at the butcher's stand with an average of eighteen striations per slab; the average number of striations hardly ever changed, although sometimes there was greater variance. The merchant at the squash stand had uneven stains on his sleeves and three stray threads hanging from his robe; he must have gotten it caught in his cart and had to pull himself free. And there were sixty-eight apples in the mound in front of Narset; that was accounting for the volume inside the mound, which she couldn't see but could predict well enough. There would be sixty-seven apples if her mother would ever just choose one.
Her mother hemmed and hawed, her fingers alighting first on one apple and then another, fluttering over the choices, but never settling.
#emph[She's never going to pick one] , Narset thought. #emph[We're never going to leave] . Panic set in. Her vision blurred, her ears rang, and her forehead began to sweat. She frantically searched for something else to distract her, but there was nothing else she could see. At eight, Narset wasn't tall enough to see over any of the stands or any of the bodies. It was like she was in a never-ending maze of tall sweaty, smelly people-trees.
She was trapped.
#figure(image("002_The Great Teacher's Student/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She struggled to draw the thick, cloying air into her lungs, but she couldn't get enough. Her body tingled and itched. It felt like her skin was warning her that it wasn't going to stay put much longer; if she didn't move, it would move without her and she wouldn't have skin anymore. She had to go. She had to get out of there.
"Take this one." Narset pointed to the nearest apple.
Her mother bent to inspect it. "No, no. It's bruised." She waved her hand dismissively. "And stop fidgeting, Narset."
Narset ignored the reprimand. "Then this one."
"Bad spot." Her mother barely looked. She was dancing her fingers over the fruit at the top of the mountain.
If it was an apple from up there that her mother wanted then that was what she would get. Narset jumped. "Then that one!" She pointed to one of the topmost fruits—and her sleeve snagged the long stem of it.
What happened next happened in slow motion. The apple wavered first forward and then back. Narset reached to steady it, but she was already on her way down from her leap, and when her fingers touched it they dragged the fruit to the precipice. It teetered there for a heartbeat and then began to tumble down.
"No!" She heard the apple merchant's desperate shout from somewhere above.
She reached for his precious piece of produce as it sailed off the stack and plummeted toward the floor.
She could predict the trajectory; she had studied falling objects before, and her hand connected just before it hit the ground.
"Ha! Got it!" She lifted her arm, holding the apple on display—as hundreds more rained down around her, thumping and bumping, hopping over each other and rolling across the floor.
"Oh no." That shouldn't have happened, Narset thought, not if the pile was stacked as tightly as she had assumed. However, if there were only sixty-five apples then there would have been structural instability and this behavior would make sense.
"My fruit! All of my beautiful fruit! It's ruined!" the merchant cried.
"I'm sorry, I'm so sorry." Her mother scampered across the floor, picking up the apples within her reach. "They're fine. See?" She held one up. "They'll be fine."
The merchant marched around the stand. "They're bruised."
"How many are there?" Narset asked. "Because if there were only sixty-five then you should have—"
"You!" The merchant rounded on Narset. "Get away from my stand!"
Narset jumped back, bumping the corner of the stand. A dozen more apples tumbled to the ground.
"Get out! Out!" the merchant shouted.
Narset looked to her mother. "I'm only trying to explain. He stacked them wrong."
"How dare you turn the blame on me!" the merchant bellowed. "I've been stacking apples for decades. Decades! And you come in and take out an entire day's harvest in one fell swoop."
"But sir—"
Her mother's hand on Narset's wrist cut her off. "Please," her mother said. "You have to learn to let things go."
"But—"
"Wait outside," her mother nodded to the exit. "I'll try to make this right."
Narset didn't bother to say that that's what she had been trying to do: make it right. She didn't want to argue any further because her mother had uttered the words she had been waiting desperately to hear. She was finally allowed to escape the too-tight marketplace; she was permitted to go outside.
#figure(image("002_The Great Teacher's Student/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She made a break for it, pushing past the hard stares of the other merchants and shoppers who had seen the debacle. She ducked under the melon booth, jumped over three baskets of bread, and flew through the parted curtain before anyone could stop her.
She was free.
The first breath of fresh air filled her lungs and her soul lifted.
The sun on her skin, the scent of fish in the nearby river, and the vast, endless space before her were perfection. That was the way things were supposed to be. Narset began to run. It's what she did, or rather what she couldn't help but do whenever there was unexplored space in front of her. She had never been on the far side of the market before; the land was all new to her. The thrill of it propelled her down the river, her restlessness turning to delight. The wind worked its way through her thick hair, cooling her scalp, and her feet learned the rocks with each step. She studied the flow of the river as it ran and memorized the patterns of the currents and eddies. She took account of the number and types of plants that were blooming and which were still barren. Her mind churned with the details of the world unfurling before her, devouring every minutia.
This was what she was made to do: to go, to find, to learn, to search, to run, to seek—
"Seek enlightenment."
The voice startled her. It had sounded like someone had spoken in her ear. A tingle ran down her spine and she slowed.
"Hello?" She glanced over her shoulder. There was no one there. She told herself it was just the wind playing, nothing more. She fell back into step with the coursing water.
"Pursue wisdom." The voice sounded in her ear again.
Narset gasped and spun around so fast that she nearly fell into the river.
"Who's there?" Was someone following her?
She could see nothing but the low bushes that lined the water, the grassy field on the other side, and beyond that—"Wait." It couldn't be…
Narset staggered back, floundering to find her balance. It was. She knew exactly what she was looking at although she had never seen it before. There in the distance was the grandest of all the sanctuaries: Dragon's Eye. And perched atop it at the highest point was Dragonlord Ojutai, the Great Teacher. She knew him the moment she saw him, although he was a distant figure. She could make out his sleek, strong body silhouetted against the sun.
#figure(image("002_The Great Teacher's Student/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Gather knowledge."
It was his voice! Narset reeled. It was Ojutai's voice that she was hearing in her ear. But how could it be? He was so far away. And didn't he speak in Draconic?
"Find truth."
Once she understood what she was hearing, she heard his voice for what it was. It was far more complex than anything she had ever encountered—a fusion of grunts, clicks, clacks, scratches, snaps ticks, groans, squawks, growls, and perhaps a roar. But somehow it made sense to her; her hungry mind could parse its meaning.
As she listened to the sound that carried across the distance, she realized he must have been giving his lesson. Narset had heard of the lessons the dragon gave daily from his perch, but she never thought she would hear one.
"Ha-ha!" She threw up her arms, her insides bursting with excitement. "This is amazing!"
The dragon turned his head in Narset's direction and she instinctively shrunk down. Was he looking at her?
"This is where it begins," he said.
Was he speaking to her?
"I can show you the way."
"Me?"
"You are on a quest for knowledge; a journey for wisdom," Ojutai said.
"Yes," Narset said. He understood her. The Great Teacher understood what she had been trying to explain to her mother for so long.
"You have come to the right place. I know all there is to know." The dragon puffed out his chest proudly. "And I will teach those who are willing to learn."
She knew it was strange to feel that way, but she couldn't help but think his words were meant for her and her alone. "I am willing." Narset's voice was no more than a whisper. "I want to learn everything." She focused her gaze on his silhouette, and although he was no more than a speck on the horizon, she felt closer to Ojutai in that moment than she had ever felt to anyone before. "I want to be your student," she said. "Please, let me be your student."
The dragon nodded.
She had seen it. It was not a trick of the light. Ojutai, the greatest dragon in the land had nodded his assent. She would be his student and he her teacher. And she would learn all there was to know.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
And she had learned. She had learned so very much.
From that day on, Narset greeted her trips to the marketplace with anticipation rather than apprehension. Her mother had found it agreeable that Narset wait outside where she couldn't knock anything over and land the family with more apples than they could ever hope to eat as long as Narset was there to carry the filled bags back home at the end of the day. She was allowed to wander as far down the riverbank as the bend, and as it turned out the bend was the perfect vantage point. From there, she could see Ojutai's silhouette unobscured and she could hear his voice crisp and clear from across the water.
Over the next three years, Narset studied, trained, and practiced under the Great Teacher from afar. She learned of the ancient wisdom of dragons and the endless wells of knowledge they possessed. She learned that of all the dragons in all the land, Ojutai was the oldest, the wisest, the most powerful. And he was her teacher.
With her dragon as her guide she studied the draconic aspect of cunning and sharpened her mind, working through puzzles and solving riddles. She exercised her body, too, learning what to do by watching Ojutai's silhouette and mimicking his movements. She practiced in every spare moment she could find, and quickly increased her strength, stamina, balance, and dexterity. The bags she carried back from the marketplace soon felt as light as bags of cotton. And if she had wanted them to be lighter, she could have cast a spell to make it so. Her curious mind adored the complexities of spellcasting. There were so many moving parts, so much to keep track of, so many concepts and layers to become intimately familiar with. And she threw herself into the task of it. She learned how to wield the magic of the plane like the dragons of Tarkir had done for ages.
#figure(image("002_The Great Teacher's Student/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Much of the restlessness she felt subsided, but not all of it. Narset's insides still fidgeted and stirred when she thought of how far away Dragon's Eye Sanctuary was. Although she knew that in many ways she was close to Ojutai, the physical distance that separated them was great. She longed to one day train alongside the Great Teacher on his perch, and she sent quiet pleas out to him every day.
"Ojutai, my dragon," from her inverted position in a one-armed handstand on the riverbank, her gaze set on Ojutai's form, "my greatest wish is to learn all that you teach." She worked up her courage to say the next part. "I have come so far, but I know I could learn so much more if I could study at your side. Help me find a path to you and I will forever be your most devoted student."
"Hello, student." The voice startled her. It was not Ojutai's voice; it was not the voice of a dragon at all. It had come from somewhere up by her feet.
Had she not been well practiced in concentration and balance she would have tumbled to the ground. As it was, she managed to hold on to her center and lower herself into a standing position with only the slightest hint of a wobble in her left ankle. She glared down at her ankle, silently cursing it; it was a weak point for her, often refusing to cooperate in her exercises.
"Impressive."
Narset spun around to see a tall, regal aven standing at arm's length.
"I wouldn't be too hard on that ankle if I were you," the aven said, nodding down to Narset's left foot. "Often the things we perceive as our most undesirable imperfections turn out to be our strongest assets."
Narset gaped. The aven wore a robe, which she recognized—a dragonspeaker's robe!
"I can see that I have disturbed you and I beg your pardon," the aven said. "I would not normally interrupt a student's practice, but this message comes urgently from—"
"Ojutai." Narset said the dragon's name without thinking, but as she said it certainty set in. The dragonspeaker's robe was not just any dragonspeaker's robe—the lines of the fabric, the decoration, it was unmistakable. Blood rushing away from her head, Narset lowered herself into a bow. "Dragonspeaker Ishai."
#figure(image("002_The Great Teacher's Student/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Ah, so you know who I am." Narset glanced up to see the aven cock her head. "Impressive, again."
Narset stood up, only barely stopping herself from wheeling straight into the elegant aven. "You're—you're his—and you're, well you're here, and you're talking to me. Ojutai's dragonspeaker is talking to me!" She squealed and then threw her hand up to cover her mouth. She couldn't believe that sound had escaped her lips in front of Ojutai's dragonspeaker.
The aven clucked a short, kind laugh. "Yes, student, I am here to speak to you. Ojutai"—she said his name with the correct Draconic accent, flicking her wings to add the appropriate emphasis—"has heard of your dedicated practice. We all have. You are quite the talk up in Dragon's Eye Sanctuary."
"Dragon's Eye Sanctuary." Narset's scalp tingled and her face felt hot and then cold and then both at the same time. She faltered, lightheaded.
"Breathe, young one." Ishai—Ojutai's dragonspeaker!—lifted her wing to steady Narset.
Narset did as the aven said, sucking in a long, deep breath. Slowly the world ceased its spinning.
Ishai patted Narset's shoulder gently, reassuringly. "It pleases me greatly to see your enthusiasm. And it will please Ojutai all the more. That is, if you agree to come."
"To—to Dragon's Eye Sanctuary?" Narset whispered.
"Yes," Ishai said. "To study under the Great Teacher."
"You're serious?" Narset looked into Ishai's eyes.
The Aven held her gaze. "Of course."
This was real. This was really happening. The moment had finally come; she would finally journey to the top of the mountain. She would finally meet her teacher face to face. She would finally learn all there was to know.
All Narset could do was nod.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Their first meeting had been everything she had hoped, everything she had dreamed—everything. When Ojutai greeted her, Narset returned the greeting in Draconic, and the Great Teacher smiled. She would see him smile many more times over the course of the next few years. As she trained with the other students at Dragon's Eye Sanctuary, the eyes of the dragon were often on her. His gaze empowered her; she performed at her best when he watched. And he smiled when she did well.
Often, she felt his words too were meant for her alone to hear. It was as though the two of them were engaged in a private conversation and others were merely eavesdropping. No one else could hope to understand the true depth of meaning in what passed between them, for no one else had a mind like hers and Ojutai's—not even the skywise. Narset did not mean to be arrogant, those were just the facts. Her mind was more like a dragon's mind than a human's. She learned more and faster than any other student at the Sanctuary, and the more she learned the closer she felt to her teacher.
#figure(image("002_The Great Teacher's Student/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
As she looked back now, she recognized her time at the sanctuary as the best years of her life. She was happier than she had ever been; she was challenged, recognized, fulfilled. Her restlessness had ceased haunting her; she had felt a sense of peace. And while she wasn't physically moving, she knew she was on a path, going where she was meant to go, becoming who she was meant to be. Ojutai was leading her. And not a day went by that she didn't thank her dragon for the gift.
Narset advanced more quickly than any other student, climbing the ranks of Dragon's Eye Sanctuary, moving upward from the lowest balconies to the highest terraces, until one day Ojutai called for her to come stand on his own private perch. He interrupted lessons to do so, requesting her presence after she had won a practice match against her peer, Taigam. As she ascended the final flight of stairs, Narset felt Taigam's glare burning into her back. He had been at the Sanctuary much longer than she. She knew he longed to be where she was, but she also knew he would not stand there until he learned to purify his quest, until he learned to seek wisdom instead of power.
She pushed her awareness of Taigam aside and cleared her mind before taking that step up onto Ojutai's perch. It was the most significant step she had ever taken.
"My student, Narset, it is time. Your hunger for knowledge is your greatest strength. You have become strong, and powerful, and wise because you have never stopped seeking enlightenment." The dragon beamed down at her. She knew what was about to come, and for one glorious moment everything felt perfect. "I now bestow upon you the title of Master, which you have assuredly earned, and with it all the honor and responsibility it brings." Ojutai bowed his head and rested his giant paw on her shoulder.
Narset bowed her head in return and clasped her small hand over the dragon's paw, making no attempt to wipe the hot tear that streaked down her cheek. At fifteen, she was the youngest master Ojutai had ever named. She had reached the top.
She turned to look down from the summit of Dragon's Eye Sanctuary, down at the world below. It was the first time, she realized, that she was not looking up at Ojutai's perch.
It felt strange.
The students below her cheered—or at least most of them. The skywise soared around her in a display of celebration. And Ojutai's bright bursts of magic danced and cavorted in the sky.
#figure(image("002_The Great Teacher's Student/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
This was it then. She had done it. She had reached the end…
Suddenly, a ringing started somewhere deep in Narset's ears.
There was nowhere else to go.
There was nothing more to learn.
Her face flushed and the moment started to fade. And just like that she was trapped. Her vision blurred and her forehead sweated. In her mind she was back in the marketplace.
Ojutai looked down at her, pride in his eyes. She could tell he expected her to speak, to thank him, to celebrate. But she could do nothing more than fight the urge to run. And though the thought shocked her, she could not help but feel that this was the dragon's fault. She could not help but feel that this moment was supposed to be different, that there was supposed to be more. He had promised that he knew everything, but everything couldn't just end. She wanted to cry out. Her journey couldn't be over.
She wondered now: had he known what she would do? The wise Ojutai, the Great Teacher who knew all, had he known then that she would run? She hadn't meant to. She would never have left him on purpose. She wanted to tell him that. She would tell him that now if she believed he would listen.
"I'm sorry," she whispered out across the water.
There was no answer.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Although Narset fought the restlessness for nearly a year after the day it set in, it only worsened. Her insides bucked like a wild storm, tearing her apart. She had to move, she had to go. Since she could not climb any higher, Narset decided to descend the mountain.
The descent went more quickly than she anticipated. Once she started running, she did not slow. And when she reached the bottom she kept going because her legs would not cease carrying her.
She did not stop until she discovered a hidden doorway tucked away in a corner of the mountain and sealed shut. Even then she did not stop for long. She cast a spell to open the door. Behind it she found a passage and stairs that went down. She descended them. And when they ended on a platform that offered another staircase, she descended that one as well.
She kept going down, down, down, winding through passages and crawling through partially collapsed tunnels. She would have burrowed deeper and deeper into the land forever, studying the rocks, learning the sand and silt, but all too soon the tunnel came to an end.
At first, her restlessness reared, but before it could sink its claws into her, Narset saw that there was somewhere else to go. The walls of the room were lined with scrolls! She could read them; they would take her somewhere; they would teach her more.
As she raced to the nearest scroll, desperate, she was vaguely aware of where she must be. It had to be an ancient archive, a place that she had only heard of in legend, a place that Ojutai had all but forbidden. She did not care, could not care—all she could feel was the need to search, to seek, to know.
#figure(image("002_The Great Teacher's Student/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
With as much care as she could muster in her mind's ravenous state she unfurled the longest of the scrolls. It was brittle, but intact. And it was filled with words—glorious words that conveyed history, knowledge, and wisdom. She knelt on the dusty, brick ground spreading the words out before her, and she began to read. She felt like she was moving again.
The ancient scrolls contained an account of Tarkir's past, but one she had not learned before. While some of it overlapped with what the Great Teacher had taught her, there were also stray pieces that stuck out and contradicted. The details were twisted: clans that served khans, not dragonlords, and spellcasting and magic she did not recognize. And from what the scrolls said, it seemed that there had been dragons before Ojutai.
Was the Great Teacher not the oldest dragon on Tarkir? Was he not the wisest? Was he not the one who knew everything?
The idea took root in Narset's mind. She had to know the truth. She had to know if there was more she could learn.
When she ran out of scrolls to read in the archives under Dragon's Eye, she decided to search for more somewhere else. She ran back up the stairs and out into the light—and then straight into Taigam's hard, muscled chest.
"I knew you were down there," Taigam spat.
"Let me through." Narset had no patience for his petulance. Not now.
"You know as well as I that there are things down there unfit for Ojutai's followers, especially those who are called master." He lingered on the word.
"Taigam, please, out of my way. I must go." The restlessness was buzzing inside Narset, the burning need to know the truth was a force of its own pushing her from within. She would not be able to resist it much longer.
#figure(image("002_The Great Teacher's Student/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"I have no choice but to report you for blasphemy. You have betrayed Ojutai. You have chosen to follow a dark path, and for that the Great Teacher will punish you."
"Then let him!" Narset erupted with power, blasting past Taigam and ignoring his screams.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Narset remembered exactly how she had felt in that moment. It was the same feeling that had propelled her in her youth under the melon booth, over the baskets of bread, and out into freedom. It was the same feeling that had carried her up the mountain of Dragon's Eye Sanctuary, through her training, to Ojutai's perch. And it was the same feeling that swelled in her chest, pushing her to let go, to take the leap, to walk away.
She hated the feeling. In her life all it had caused her was pain. But never so much pain as when it had pushed her to learn the truth about Ojutai.
After the archive at Dragon's Eye, Narset had succumbed to her restlessness and she let it guide her actions. It was hungry for more, always hungry for more. There was more knowledge out there, she could feel it, and she was desperate to know it.
She found other archives under Cori Mountain and Riverwheel, and in them she found more scrolls. From the words written on the scrolls she pieced together a deeper account of that alternative history of Tarkir. She learned of a Spirit Dragon, Ugin, who was the source of all magic on the plane, as well as the dragon tempests. She learned of a time when clans warred, and when dragons kept their distance.
It fascinated her, all of it.
It should have been enough, but it wasn't. She searched for more.
And then she found the archive under Dirgur.
Unlike the other archives, the one under Dirgur was not well preserved. It seemed to have been looted and broken long ago. Part of her hoped it was utterly empty; something inside told her that if she continued to look she wasn't going to like what she found.
On the fourth week of searching, she came upon what seemed to be the singular scroll remaining at the archive. It was locked away deep underground and sealed behind a thick door. For a long moment Narset did nothing more than stare at it. She could hardly believe she had found anything at all. Then, fingers trembling and heart beating wildly, she reached for it.
She unrolled the scroll on the ground, summoned a cold fire on her fingertips for light, and began to read.
The writing was rushed and smudged, as though whoever had written it knew there was very little time. And as she read she understood why.
The scroll was an account of a meeting between the khans of long ago.
#figure(image("002_The Great Teacher's Student/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She learned of the khans' hope to end the dragons in order to save their clans. She learned of their disagreements and their plans. And she learned of a name: Sarkhan—a man, a dragon, a khan—one who had saved the Spirit Dragon and thereby saved the dragons of Tarkir. And then she learned one last thing, one final truth. The meeting had been brought to an abrupt end as two dragons and their broods swooped in to attack the gathered khans. One of those dragons had been Ojutai.
As she read her teacher's name, Narset's back straightened and her hands clenched. The brittle paper cracked in her fists. At the same moment, something inside her cracked, too. She felt it breaking in her chest like an egg. Whatever was inside the thing that broke was hot and thick and it ran down her ribcage, spreading outward through her body. And then she was pulled backward with such a force as she had never felt before and ripped away from Tarkir.
Another world extended before her. A new world. An unexplored world. It held promise—promise of knowledge, of possibilities, of places to go.
It was wonderful.
And Narset almost went.
But at the last moment she pulled herself back.
Gasping and quivering, Narset crumpled into a heap on top of the very last scroll on Tarkir.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
She still couldn't explain exactly why she had not gone.
Since that time, she had felt the force tug on her insides nearly every hour of every day. It would have been so easy to give in to it. It would have been so right. But she had held back. She had instead scoured Tarkir—every crevasse, every mountaintop—convinced there had to be more to learn, that there had to be more to find.
Now she had come full circle, she had seen all the land and witnessed all of its secrets. And she sat again at the river's bend.
"We must always find time to reflect on what we have learned." The gravelly voice suddenly drew Narset's gaze upward.
Ojutai.
Her dragon, her teacher, silhouetted against the first rays of the rising sun. He had come out on his perch to teach the morning's lesson.
#figure(image("002_The Great Teacher's Student/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"So, what have you learned?" He turned his head toward her.
He was looking at her.
"What have you found?"
He was speaking to her.
Narset's insides trembled. She had thought for so long that he had disowned her as Taigam had promised he would. She was a heretic. She had disobeyed.
"What do you know?"
Perhaps Taigam had been wrong. Perhaps Ojutai was still her teacher. His question rang in Narset's ears. What did she know? She knew Tarkir. She knew it for all it was, for its beauty, its wonders, and for its imperfections. And often it was those imperfections that were its greatest assets. She smiled up at her dragon. He was part of Tarkir, and because of his presence, the land, the people, and the history were better. The world was stronger; it was more perfect. She could see that now.
"I have learned the truth," she whispered.
Ojutai nodded. And Narset knew that while she could not see it he was smiling too. A warmth filled her. A peace. "Once we reflect we must then move forward," Ojutai said. "All one needs do is—"
"Seek enlightenment," Narset added her voice to his.
"For there is always more to learn." With that, Ojutai spread his wings and took to the sky.
"Thank you," Narset said. Her words were carried away on the winds of Tarkir as she let go.
#figure(image("002_The Great Teacher's Student/13.jpg", width: 100%), caption: [Narset Transcendent | Art by Magali Villeneuve], supplement: none, numbering: none)
|
|
https://github.com/david-davies/typst-prooftree | https://raw.githubusercontent.com/david-davies/typst-prooftree/main/src/internal.typ | typst | MIT License | /// = Prooftree
/// Some acronyms will be used:
/// * lbl-tree:
/// A 'line-by-line' tree, where a tree is represented by a sequence of 'lines', each stating
/// how many premises it should have.
/// * s-tree:
/// A 'structured' tree, the IR of proof trees. These have a nested structure mirroring that
/// of the tree they represent
/// * ss-tree:
/// A 'semi-structured' tree, providing an alternate way for users to define proof trees.
/// These are not yet implemented.
#import "utils.typ": *
/// Enabling debugging mode will give all the prooftree blocks thin red outlines,
/// and some various other markers to help with development.
#let __debug_mode = false
/// Do/show `b` if we are in debugging mode.
#let __debug_trace(b) = {
if __debug_mode {b}
else {}
}
/// How to outline prooftree blocks when debugging.
#let block_stroke = __debug_trace((paint: red, thickness: .15pt))
/// The block config used by most of the prooftrees.
#let qblock = block.with(breakable: false, stroke: block_stroke, inset: 0pt)
// The default assert prepends with 'assertion error',
// we want the user to immediately know it is in a prooftree error
// welp just realised this prepends with 'panic' anyways.
#let __mk_err_str(message) = "prooftree Error: " + message
#let assert_ = assert
#let assert(cond, msg) = {
if not cond [
#panic(__mk_err_str(msg))
]
}
/*************************************************************************************************/
// Printing to content
/*****************************************************************************/
// Printing Inferences
/// Types:
/// Dimensions = dict(width, height)
/// The return structure of the main show functions
/// - conc_dim (Dimensions):
/// - block_dim (Dimensions):
/// - block (content):
/// - conc_start_x (length):
/// -> TreeShowReturn
#let _mk_show_return(conc_dim, block_dim, block, conc_start_x) = {
( conc_dim: conc_dim
, block_dim: block_dim
, block: block
, conc_start_x: conc_start_x
)
}
/// Build a block containing the conclusion
/// - styles (styles):
/// - conclusion (content):
/// - alignment (alignment):
/// - conc_start_x (length):
/// -> TreeShowReturn
#let __show_conclusion(
styles : __kw_arg,
tree_config : __kw_arg,
conclusion : __kw_arg,
alignment : __kw_arg,
conc_start_x : __kw_arg
) = {
let conc = align(alignment + left, qblock(conclusion.content))
_mk_show_return(measure(conc, styles), measure(conc,styles), conc, conc_start_x)
}
/// Create a `Label`, storing the content of the label and its spacing from the inference line.
/// - content (content)
/// - spacing (length)
/// -> Label
#let __mk_label(content, spacing) = if is_not_none(content) {
( content: from_none(content, none)
, spacing: from_none(spacing, 0pt)
)
}
/// Format a s-tree with no premises
/// -> TreeShowReturn
#let _show_axi_tree(
styles : __kw_arg,
tree_config : __kw_arg,
conclusion : __kw_arg
) = __show_conclusion(
styles : styles,
tree_config : tree_config,
conclusion : conclusion,
alignment : bottom,
conc_start_x : 0pt
)
/// Format the block of premises preceding a conclusion.
/// All premises are assumed to have already been formatted.
///
/// - first_premise (TreeShowReturn): The leftmost premise, assumed to have already been formatted.
/// - mid_premises (array[TreeShowReturn]): The middle premises, in order of left-to-right.
/// - last_premise (TreeShowReturn): The rightmost premise.
/// - is_unary (bool): true when the inference is unary;
/// i.e. there is only one premise, the `first_premise`.
/// -> (content, length):
/// The `content` is the formatted block.
/// The `length` is the distance from the left boundary of the block to the end of the
/// conclusion of the rightmost premise.
#let __show_premise_block(
tree_config : __kw_arg,
first_premise : __kw_arg,
mid_premises : __kw_arg,
last_premise : __kw_arg,
is_unary : __kw_arg
) = {
// __check_kw_args(first_premise, mid_premises, last_premise, is_unary)
let ret_content
let last_p_end_x
if is_unary {
last_p_end_x = first_premise.conc_start_x + first_premise.conc_dim.width
ret_content = qblock(first_premise.block)
} else {
let p_spacing = tree_config.premises_spacing
let all_but_last_premise_x = (
(first_premise.block_dim.width)
+ p_spacing
+ mid_premises.map(p => p.block_dim.width + p_spacing).sum(default: 0pt)
)
last_p_end_x = all_but_last_premise_x + last_premise.conc_start_x + last_premise.conc_dim.width
ret_content = align(bottom,qblock(stack(
dir: ltr,
pad(first_premise.block, right: p_spacing),
..(mid_premises.map(p => pad(p.block, right: p_spacing))),
last_premise.block,
)))
}
return (ret_content, last_p_end_x)
}
/// Get the dimensions of a label.
/// - styles (styles):
/// - label (TreeLabel):
/// -> ((width (length), height (length)), length):
/// `width` and `height` are those of the label as given by `measure`.
/// The rightmost `length` is the total length of the label
/// including its spacing.
#let __tree_label_dim(styles, label) = {
if is_not_none(label) and is_not_none(label.content) {
let dim = measure(label.content, styles)
(dim, label.spacing + dim.width)
} else {
((width: 0pt, height: 0pt), 0pt)
}
}
/// Format the inference line and its labels, if any.
///
/// - styles (styles):
/// - tree_config (TreeConfig):
/// - left_label (TreeLabel?):
/// - right_label (TreeLabel?):
/// - line_start_x (length):
/// The distance to the right of the block's leftmost boundary at which the line should start.
/// - line_length (length):
/// -> content
#let __show_inference_line_block(
styles : __kw_arg,
tree_config : __kw_arg,
left_label : __kw_arg,
right_label : __kw_arg,
line_start_x : __kw_arg,
line_length : __kw_arg
) = {
let (L_label_dim, L_label_total_h_space) = __tree_label_dim(styles, left_label)
let (R_label_dim, R_label_total_h_space) = __tree_label_dim(styles, right_label)
align(left + horizon,{
stack(dir: ltr, spacing: 0pt,
// Place the left label
if is_not_none(left_label) {
place(
dx: line_start_x - L_label_total_h_space,
dy: - L_label_dim.height / 2,
left_label.content
)
},
// The inference line
line(start: (line_start_x, 0pt), length: line_length, stroke: tree_config.line_config.stroke),
// Place the right label
if is_not_none(right_label) {
place(
dy: - R_label_dim.height / 2,
dx: right_label.spacing,
right_label.content
)
}
)
// Show the midpoint of the line
__debug_trace(place(
line(
start: (line_start_x + line_length / 2, 2pt),
stroke: 1pt + blue, angle: -90deg, length: 4pt
)
))
})
}
/// Format a s-tree with one or more premises.
/// `first_premise`, `last_premise`, and each premise in `mid_premises` are assumed to have already
/// been formatted.
///
/// - conclusion (content: content, spacing: length):
/// - first_premise (TreeShowReturn):
/// - mid_premises (list[TreeShowReturn]):
/// - last_premise (TreeShowReturn):
/// - left_label (TreeLabel?) :
/// - right_label (TreeLabel?):
/// - is_unary (bool):
/// -> TreeShowReturn
#let _show_nary_tree(
styles : __kw_arg,
tree_config : __kw_arg,
conclusion : __kw_arg,
first_premise : __kw_arg,
mid_premises : __kw_arg,
last_premise : __kw_arg,
left_label : __kw_arg,
right_label : __kw_arg,
is_unary : __kw_arg,
) = {
// The leftmost point of the first premise's conclusion
let first_p_start_x = first_premise.conc_start_x
// The rightmost point of the last premise's conclusion
let last_p_end_x
// Premises: all stuff above the line
let (premise_block, last_p_end_x) = __show_premise_block(
tree_config: tree_config,
first_premise: first_premise,
mid_premises: mid_premises,
last_premise: last_premise,
is_unary: is_unary
)
let conc_dim = measure(conclusion.content, styles)
let p_line_length = last_p_end_x - first_p_start_x
let p_total_len = measure(premise_block, styles).width
let line_length = calc.max(conc_dim.width, last_p_end_x - first_p_start_x)
let line_start_x
let conc_start_x
if (conc_dim.width < p_line_length) {
line_start_x = first_p_start_x
conc_start_x = line_start_x + (line_length - conc_dim.width) / 2
} else if (conc_dim.width < p_total_len) {
line_start_x = p_total_len / 2 - conc_dim.width / 2
conc_start_x = line_start_x
} else {
line_start_x = 0pt
conc_start_x = 0pt
}
let get_overhang(h) = if is_not_none(h) {
h
} else if is_not_none(tree_config.line_config.overhang) {
tree_config.line_config.overhang
} else {
0pt
}
let overhang_l = get_overhang(tree_config.line_config.overhang_l)
let overhang_r = get_overhang(tree_config.line_config.overhang_r)
line_start_x -= overhang_l
line_length += overhang_l + overhang_r
// The line and possibly labels.
let line_block = __show_inference_line_block(
styles : styles,
tree_config : tree_config,
left_label : left_label,
right_label : right_label,
line_start_x : line_start_x,
line_length : line_length
)
// The conclusion
let conc_block = __show_conclusion(
styles : styles,
conclusion : conclusion,
alignment : horizon,
conc_start_x : conc_start_x
)
// final proof block
let prf_block = qblock(pad(
align(center + bottom,
stack(
spacing: tree_config.vertical_spacing,
qblock(premise_block),
line_block,
align(left,pad(left: conc_start_x, conc_block.block))
)
)
))
_mk_show_return(
conc_dim,
measure(prf_block, styles),
prf_block,
conc_start_x
)
}
/*****************************************************************************/
// Printing trees
/// The structure of a formatted tree
#let _mk_showed_tree(m_content, m_spacing) = {
( content: default_if_none(m_content, [])
, spacing: default_if_none(m_spacing, 0pt)
)
}
#let _mk_line_config(
overhang: none,
overhang_l: none,
overhang_r: none,
stroke: none
) = {
let overhang_l = default_if_none(overhang_l, overhang)
let overhang_r = default_if_none(overhang_r, overhang)
return ( stroke: stroke
, overhang: overhang
, overhang_l: overhang_l
, overhang_r: overhang_r
)
}
#let default_line_config = _mk_line_config(
overhang: 2pt,
stroke: 1pt + black
)
#let _mk_tree_config(
premises_spacing: __kw_arg
, spacing_between_next_premise: __kw_arg
, vertical_spacing: __kw_arg
, line_config: __kw_arg
) = {
( premises_spacing: premises_spacing
, spacing_between_next_premise: spacing_between_next_premise
, vertical_spacing: vertical_spacing
, line_config: line_config
)
}
/// Convert structured tree to content
#let _show_str_sub_tree(styles, tree_config, tree) = {
let num_premises = tree.premises.len()
let conc = _mk_showed_tree(tree.conclusion, tree.spacing)
// Recurse on a premise
let prepare_premise(premise) = _show_str_sub_tree(styles, tree_config, premise)
let line_config = tree_config.line_config
if is_not_none(tree.line_config) {
line_config += tree.line_config
}
let tree_config = tree_config
tree_config.line_config = line_config
if num_premises == 0 {
_show_axi_tree(
styles : styles,
tree_config : tree_config,
conclusion : conc
)
} else if num_premises == 1 {
let premise = prepare_premise(tree.premises.first())
_show_nary_tree(
styles : styles,
tree_config : tree_config,
conclusion : conc,
first_premise : premise,
mid_premises : (),
last_premise : none,
left_label : tree.left_label,
right_label : tree.right_label,
is_unary : true
)
} else {
let first_premise = prepare_premise(tree.premises.first())
let last_premise = prepare_premise(tree.premises.last())
let mid_premises = tree.premises.slice(1, num_premises - 1).map(prepare_premise)
_show_nary_tree(
styles : styles,
tree_config : tree_config,
conclusion : conc,
first_premise : first_premise,
mid_premises : mid_premises,
last_premise : last_premise,
left_label : tree.left_label,
right_label : tree.right_label,
is_unary : false
)
}
}
/// Convert structured tree to content
#let __show_str_tree(tree_config, tree) = {
style(styles => {
let prt_tree = _show_str_sub_tree(styles, tree_config, tree)
align(center,qblock(width: prt_tree.block_dim.width, prt_tree.block))
})
}
/*************************************************************************************************/
/// == Building Trees
/*****************************************************************************/
/// === Flat Trees
/// The raw input form.
#let _mk_tree_line(
num_premises: __kw_arg
, body: __kw_arg
, right_spacing: none
, left_label: none
, left_label_spacing: none
, right_label: none
, right_label_spacing: none
, line_config: none
) = {
// __check_kw_args(num_premises, body)
assert(
num_premises >= 0,
"Inference line with a negative number of premises: $k"
.replace("$k", str(num_premises))
)
/// raw_tree
( num_premises: num_premises // : Nat
, conclusion: body // : content
, spacing: right_spacing // : length
, left_label: __mk_label(left_label, left_label_spacing)
, right_label: __mk_label(right_label, right_label_spacing)
, line_config: line_config
)
}
/*****************************************************************************/
/// === 'Structured' Trees
/// These are an intermediate form.
/// - premises (list[str_tree])
/// - conclusion (content)
/// -> str_tree
#let _mk_str_tree(
premises
, conclusion
, left_label
, right_label
, spacing
, line_config
) = {
( premises: premises // : List Tree
, conclusion: conclusion // : content
, left_label: left_label // : Maybe TreeLabel
, right_label: right_label // : Maybe TreeLabel
, spacing: spacing // : length
, line_config: line_config // : Maybe LineConfig
)
}
#let _test_mk_str_tree_(ps, c) = _mk_str_tree(ps, c, none, none, 0pt, none)
/// These extra constructors are useful for building tests.
#let snary(..args, conclusion) = {
let tree_config_override = args.named()
let premises = args.pos()
_mk_str_tree(premises, conclusion)
}
#let _str_axi(c) = _test_mk_str_tree_((), c)
#let _str_uni(p, c) = _test_mk_str_tree_((p,), c)
#let _str_bin(p1, p2, c) = _test_mk_str_tree_((p1,p2), c)
/*****************************************************************************/
/// === Parsing line-by-line trees to structured
/// Parse a line-by-line tree.
/// The root of the tree is at the end of the list.
///
/// - stats (list[raw_tree])
/// -> (str_tree, list[raw_tree])
/// The recursive tree and list of statements left to consume.
#let __parse_tree(stats) = {
assert(stats.len() > 0, "malformed tree: not enough premises")
let stat = stats.pop()
let curr_stats = stats
let premises = ()
if stat.num_premises > 0 {
let i = stat.num_premises
while i > 0 {
let (p, ss) = __parse_tree(curr_stats)
curr_stats = ss
premises.push(p)
i -= 1
assert(curr_stats.len() >= i,
"malformed tree: not enough premises for conclusion: $c"
.replace("$c", repr(stat.conclusion))
)
}
premises = premises.rev()
}
(
_mk_str_tree(
premises,
stat.conclusion,
stat.left_label,
stat.right_label,
stat.spacing,
stat.line_config
),
curr_stats
)
}
/// Parse a flat tree to structured
/// - stats (list[raw_tree])
/// -> str_tree
#let _parse_tree(stats) = {
let (tree, stats_left) = __parse_tree(stats)
assert(stats_left.len() == 0,
"malformed prooftree: not all premises consumed, $n many were left: $stats"
.replace("$stats", repr(stats))
.replace("$n", str(stats_left.len()))
)
tree
}
/*****************************************************************************/
/// Semi-structured trees: the structure is given by the user.
/// The idea is for these to be mixes of nested arrays and dictionaries
// TODO change these to functions that parse nested arrays/dicts
#let saxi(conclusion) = _test_mk_str_tree_((), conclusion)
#let suni(t, c) = _test_mk_str_tree_((t,), c)
#let sbin(t1, t2, c) = _test_mk_str_tree_((t1,t2), c)
/*****************************************************************************/
/// Parse-show pipeline functions
/// Parse a line-by-line tree and display it
#let __parse_then_show(tree_config, stats) = {
let tree = _parse_tree(stats)
__show_str_tree(tree_config, tree)
}
/// Parse a line-by-line tree and display it
/// - tree_config (TreeConfig):
/// - stats: Any kw_args are assumed to be overriding the tree_config.
/// The user could possibly use this to also store stuff, if at some point we add the ability for the proof cell to access the config.
/// -> content: The tree as formatted content, ready for display.
#let _parse_then_show(
tree_config: __kw_arg,
args
) = {
let tree_config_override = args.named()
let tree_config = tree_config + tree_config_override
let tree_lines = args.pos()
__parse_then_show(tree_config, tree_lines)
}
/// Display the structured tree.
#let stree(tree_config, ..args, stree) = {
assert(
args.pos().len() == 0,
"`stree` too many positional arguments: $n were given, only 1 is expected."
.replace("$n", args.pos().len())
)
let tree_config_override = args.named()
let tree_config = tree_config + tree_config_override
__show_str_tree(tree_config, stree)
}
|
https://github.com/jamesrswift/musicaux | https://raw.githubusercontent.com/jamesrswift/musicaux/main/tests/tie.typ | typst | #import "/src/lib.typ": *
#set text(font: "New Computer Modern", size: 20pt)
#show: score.with(
title: [Dance in D Major],
subtitle: [Op 8 No. 3 Mov. 1--3],
author: [<NAME>]
)
#notation(
{
cmd.bars.double-bold-open()
cmd.common.trebble()
cmd.common.key-signature(pitch: -4)
cmd.time.signature("4", "4")
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.tie(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.