repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/args-sink.typ
typst
Apache License 2.0
// Test bugs with argument sinks. --- #let foo(..body) = repr(body.pos()) #foo(a: "1", b: "2", 1, 2, 3, 4, 5, 6)
https://github.com/Nasus20202/probale
https://raw.githubusercontent.com/Nasus20202/probale/main/skrypt.typ
typst
#let premium = false #set text( font: "New Computer Modern", size: 11pt ) #set page( paper: "a4", margin: (x: 0.5cm, y: 1cm), numbering: "1 / 1", footer: context [ #set text(8pt) #h(1fr) #counter(page).display( "1 / 1", both: true ) ], header: context [ #set text(8pt) #counter(page).display( "1 / 1", both: true ) ], background: context [ #if not premium { image("./img/watermark_5.png", height: 50%) } ] ) #set heading(numbering: "1.1.1") #show heading.where(level: 1): set text(weight: "regular", size: 16pt) #show heading.where(level: 2): set text(weight: "regular", size: 14pt) #show heading.where(level: 3): set text(weight: "bold") #show heading: it => [ #if it.level < 3 { align(right)[#it] } else { [#it] } ] #let toc() = { context [ #set text(size: 11pt) #let to-string(content) = { if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } #text(size: 16pt, weight: "bold")[#align(center)[Spis treści]] #v(2pt) #set block(above: 6pt, below: 0pt) #counter(heading).update(0) #columns( 2, gutter: 5pt, for e in query(selector(heading)).filter(x => x.level != 3) [ #link(e.location())[ #grid( columns: (auto, auto, auto, auto), h(e.depth * 10pt), e, h(5pt), "(" + str(e.location().page()) + ")" ) ] ] ) ] } #let index() = { context [ #set text(size: 11pt) #let to-string(content) = { if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } #text(size: 16pt, weight: "bold")[#align(center)[Indeks pojęć]] #v(2pt) #set block(above: 6pt, below: 0pt) #counter(heading).update(0) #columns( 2, gutter: 5pt, for e in query(selector(heading)).sorted(key: x => upper(to-string(x))).filter(x => x.level == 2) [ #link(e.location())[ #grid( columns: (auto, auto, auto), text(weight: "extrabold", to-string(e.body).at(0)) + to-string(e.body).slice(1), h(5pt), "(" + str(e.location().page()) + ")" ) ] ] ) ] } #align(center)[ #text(size: 18pt, weight: "bold")[<NAME> na Metody Probabilistyczne] ] #toc() #index() = Pytania o wszystkim i o niczym == Probabilistyka - cele, umiejscowienie === Wyjaśnij rolę probabilistyki jako "interfejsu". Probabilistyka jest interfejsem między procesami poznawczymi i decyzyjnymi w obecności mechanizmów losowych a matematyką. Pozwala dokonywać ocen ilościowych i jakościowych oraz ułatwia podejmowanie racjonalnych decyzji. Jako probabilistycy, jesteśmy klientami matematyki, a np. informatyka jest naszym klientem. == Mechanizmy losowe i pseudolosowe === Wyjaśnij obiektywny i subiektywny walor pojęcia prawdopodobieństwa. Obiektywny - opisuje część danego zdarzenia przy wielokrotnym uruchamianiu mechanizmu losowego w doświadczeniu losowym. Subiektywny - opisuje stan wiedzy o danym mechanizmie losowym. === Jakie są elementy opisu modelu probabilistycznego doświadczenia losowego, czyli przestrzeni probabilistycznej? Zbiór zdarzeń elementarnych oraz zdarzeń zdefiniowanych na podstawie zdarzeń elementarnych i ich prawdopodobieństwa. === Wymień podstawowe cechy dobrego generatora liczb pseudolosowych. Każdą liczbę zwraca niemal tak samo często i bez uchwytnego związku z uprzednimi w bardzo długim cyklu. === Podaj znane Ci definicje prawdopodobieństwa. - Klasyczna $P(A) = abs(A)/abs(omega)$ - Geometryczna $P(A) = abs(abs(A))/abs(abs(omega))$ - Aksjomatyczna - Częstościowa == Mity a fakty === Czy i ewentualnie kiedy na wykładzie obaliliśmy mit, że jeśli w każdym pokoleniu średnio przypada jeden potomek na osobnika, to populacja ma szansę przetrwać? Populacja ma szansę przetrwać w badanym skończonym przedziale czasowym, lecz nie w nieskończoności. Obaliliśmy ten mit przy okazji problemu opróżnienia stosu. === Jaki rozkład prawdopodobieństwa mają pierwsze cyfry znaczące zgodnie z prawem Benforda? Rozkład logarytmiczny. === Jak z probabilistycznego punktu widzenia zaklasyfikujemy ciąg kolejnych przewag orłów nad reszkami w serii rzutów monetą? Ciąg przewag orłów nad reszkami w serii rzutów monetą można analizować jako losową wędrówkę, gdzie każdy rzut to krok w górę dla orła (+1) lub w dół dla reszki (-1). Prawdopodobieństwo, że przewaga orłów utrzyma się przez $n$ rzutów, wynosi około $1/2^n$. Średnia długość najdłuższego ciągu przewag orłów rośnie proporcjonalnie do pierwiastka kwadratowego liczby rzutów, czyli $log_2(n)$. === Na podstawie rysunku zamieszczonego na slajdzie podaj probabilistyczną przyczynę, dla której "statystyczny pasażer" poczeka na przystanku dłużej niż 5 minut. Jeśli przychodzą trzy autobusy po sobie, pierwszy, potem drugi z czasem X po pierwszym (mniejszym od średniej) a potem trzeci z czasem Y po drugim (większym od średniej) to częściej statystyczny pasażer będzie trafiał w przedział Y, czyli będzie czekał dłużej od wartości średniej. === W kontekście "prześladowania przez pecha" co dokładnie rozumiemy przez "symetryczną sytuację losową"? Prześladowanie przez pecha to złudzenie. Spośród symetrycznych doświadczeń losowych, mocniej zapamiętujemy te, które są na naszą niekorzyść. Przykładowo, jeżeli codziennie na przystanek przyjeżdża autobus, to zapamiętamy tylko te sytuacje, kiedy nie przyjedzie na czas. Czyli symetryczna sytuacja losowa to powtórzone doświadczenie pod tymi samymi warunkami. === W teście wyboru z 5 wariantami odpowiedzi za poprawną odpowiedź przyznawany jest 1 punkt, za niepoprawną $-1/4$ punktu. Wyjaśnij, w jakim sensie neutralizuje to efekt przypadkowego wyboru odpowiedzi. Ponieważ przewidywany zwrot jest równy zero. Inaczej - średnio strzelając uzyskamy 0 punktów. = Rozkłady prawdopodobieństwa == iTrust === Gdy liczby agentów objętych dystrybucją zapytań ($z$) i metadanych ($m$) są równe $4sqrt(n)$ prawdopodobieństwo braku trafień oszacujemy jako... $ P(T=0) < e^(-(m z)/n) = e^((-4sqrt(n)*4sqrt(n))/n) = e^(-16) $ == Symulator w hiperkuli === Wydajność generatora dopuszczalnych układów odchyłek dla symulatora systemu zależy w następujący sposób od dopuszczalnego promienia hiperkuli. Nie zależy (na wzorze można pokazać). Zależy jedynie od ilości wymiarów, w których jest określona. === W jaki sposób zastosowana została geometryczna definicja prawdopodobieństwa? Prawdopodobieństwo jest równe stosunkowi miary obszaru hiperkuli do miary obszaru hiperkostki. === Jaki jest wpływ dopuszczalnej odchyłki sumarycznej $delta$ na efektywność symulatora opartego na generacji punktów hiperkostki? Żaden $P(A)$ nie zależy od $delta$. == Kod korekcyjny w przestrzeni Hamminga === Dlaczego w użytym przykładzie tabeli dekodowania żaden korygowany ciąg błędów nie może zawierać trzech jedynek? Bo dla trzech jedynek mamy do czynienia z fatalnym błędem decyzyjnym. Moc korekcyjna naszego kodu sięga niektórych dwóch błędów === Ciągiem nadanym jest 10000, ciągiem błędów jest 01001. Jaką decyzję podejmie dekoder? Odbierzemy 11001, czyli koder podejmie decyzję 01001, czyli będzie to błąd fatalny. $ 10000 -> "ciąg nadany S", 01001 -> "ciąg błędów Z"\ 11001 -> "ciąg odebrany" Y = S plus.circle Z, "wybieramy" S_d ", gdzie najmniej jedynek w" S_d plus.circle Y $ #align(center)[ #table( columns: 5, [$S_d$], [10111], [10000], [01110], [01001], [$S_d plus.circle Y$], [01110 (3)], [01101 (2)], [10111 (4)], [10000 (1)] ) ] === Wyjaśnij rolę zasady maksimum wiarygodności w konstrukcji kodu. Na podstawie zasady maksimum wiarygodności wyprowadzamy metrykę Hamminga i wybieramy najbardziej wiarygodny ciąg bitów. === Jaka jest zasada konstrukcji tabeli dla dekodowania ciągów odebranych i na czym się ona opiera? Pierwszy wiersz zawiera możliwe ciągi kodowe s. Pierwsza kolumna zawiera korygowalne ciągi błędów z. Pozostałe komórki zawierają odebrane sygnały y. Opiera się ona na zasadzie maksimum wiarygodności (sygnał y jest interpretowany jako najbardziej prawdopodobny ciąg s). Prawdopodobieństwo określane na podstawie liczby przekłamań (metryka Hamminga - im mniejsza tym bardziej prawdopodobny). == Sieć sensorów === Co oznacza prawdopodobieństwo $P(Z_50_+ >= 2)$? Prawdopodobieństwo, że po czasie 2 w sieci będzie żyło ponad 50 sensorów. === Ile według przyjętego modelu wynosi wartość średnia czasu życia jednego sensora? Całka z rozkładu życia sensora, czyli mianownik w wykładniku potęgi, czyli u nas: 1 Rozkład życia $P(X_i >=x) = e^(-x)$z tego komplementarna $F(X) = 1 - e^(-x)$ z tego $p(x)$ i całka $x p(x)$ przez części ale tego nie trzeba pewnie liczyć w ogóle. $ integral_0^infinity x e^(-x) d x = 1 $ === Jaki według przyjętego modelu jest rozkład czasu życia sensora, który przetrwał najdłużej spośród 100 sensorów? $ P(Z_0 >= x) = 1 - (1-e^(-x))^100 $ == Wielodostęp rywalizacyjny === Jakie byłoby prawdopodobieństwo $P(X = k)$ gdyby $A$ były niezależne? Takie samo, bo moglibyśmy je policzyć również z twierdzenia o kombinacji zdarzeń. === Jak wyglądałby rozkład $P(X=k), k = 0,1,...,n$ gdyby zdarzenia $A_i$ były rozłączne? Gdy są nierozłączne może być kilka szczelin prostych naraz. Tylko jedno puste może zajść $k = 0$ lub $k = 1$. === Co jest większe: $abs(X = k)$ czy $binom(n, k) (n - k)^m$? $binom(n, k) (n - k)^m$, bo doliczamy jeszcze, gdy $k + 1$, $k + 2$, ..., $n$ szczelin pustych. Jest to uogólnienie wzoru Bernoulliego. === Uzasadnij, że zdarzenia $A_1$, ..., $A_n$, gdzie $A_i$ - szczelina $i$ jest pusta, nie są rozłączne i nie są niezależne. Nie są rozłączne, ponieważ może być kilka pustych szczelin naraz. Nie są niezależne, bo pustość jednej szczeliny zmniejsza prawdopodobieństwo pustości innej. === Wzór $P(B_(n, p) = k) = binom(n, k)p^k (1-p)^(n-k)$ dla schematu Bernoulliego jest szczególnym przypadkiem twierdzenia o kombinacji zdarzeń. Na czym polega jego szczególność? W schemacie Bernoulliego zdarzenia są 1) niezależne oraz 2) równoprawdopodobne. == <NAME> === Dokładne wyliczenie prawdopodobieństwa fałszywego alarmy jest trudne z uwagi na... Fakt, że "zapalanie" kolejnych bitów nie jest niezależne statystycznie. Można liczyć z twierdzenia o kombinacji zdarzeń, ale jest to uciążliwe ze względu na naprzemienną sumę. == Fuzja danych === Wyjaśnij naiwność klasyfikatora #image("img/2_7_1.png") Niezależność zdarzeń nie implikuje niezależności tych zdarzeń pod wystąpieniem jakiegoś warunku jak ilustruje rysunek. === Podaj przykład relacji między zdarzeniami B i C zapewniającej warunkową niezależność statystyczną zdarzeń A i B na przykładowym wykresie Venna. Powyższy rysunek: Wystąpienie/niewystąpienie $Z$ może wprowadzać statystyczną zależność pomiędzy sygnałami detektorów. Niemniej warunkowa niezależność sygnałów często jest zakładana. === Dlaczego bezpośrednie zastosowanie zasady maksimum wiarygodności nazwaliśmy naiwnym? Niezależne zdarzenia $A$ i $B$ nie muszą pozostać takimi przy warunku $C$ - niezależność statystyczna na ogół nie implikuje warunkowej niezależności. == Producenty i konsumenty === Niech $psi_(j,k)$ reprezentuje prawdopodobieństwo ostatecznego opróżnienia RK. Ułóż odpowiednią zależność rekurencyjną. $ cases( psi_(j, k) = p * psi_(j + 1, k) + q * psi_(j, k - 1), psi_(j, 0) = 1, psi_(100, k) = 0 ) #h(2cm) cases( Pi_(j, k) = p * Pi_(j + 1, k) + q * Pi_(j, k - 1), Pi_(100, k) = 1, Pi_(j, 0) = 0 ) \ psi " - prawdopodobieństwo opróżnienia RK" #h(2cm) Pi " - prawdopodobieństwo przepełnienia RP" $ === Co jest większe: $product_(j, k)$ czy $product_(j + 1, k - 1)$? Większe jest $product_(j + 1, k - 1)$, ponieważ jest większe prawdopodobieństwo kroku w stronę zwiększenia $j$ a bufor konsumenta jest bliżej od opróżnienia. \ Większe $j$ - bliżej przepełnienia buforu producenta, mniejsze $k$ - bliżej opróżnienia buforu konsumenta. Prawdopodobieństwo rośnie. $#h(2cm) product_(j, k) < product_(j + 1, k - 1) #h(2cm) product_(j, k) > product_(j - 1, k + 1)$ === Czym od przedstawionego różniłoby się rozumowanie prowadzące do prawdopodobieństwa opróżnienia RK? Metoda ta różniłaby się warunkami granicznymi (zamiast $psi_(j, 0) = 1$ i $psi_(100, k) = 0$ mamy $Pi_(100, k) = 1$ i $Pi_(j, 0) = 0$). === W omawianym dwuwymiarowym błądzeniu przypadkowym występują dwa ekrany. Jakiego rodzaju? Pierwszy ekran - przepełnienie RP $101k+100$, drugi ekran opróżnienie RK $101*100+j$. == Rozproszony wybór lidera === Jaki sens ma wartość $l$ (małe L) w wyrażeniu na $P(T <= k)$? Jest to liczba wylosowana przez lidera, czyli ciąg orłów i reszek zamieniony na liczbę. Może ona być z przedziału $[0, 2^k - 1]$ i służy nam w twierdzeniu o prawdopodobieństwie całkowitym. === Podaj oszacowanie mediany rozkładu wielkości losowej $T$ otrzymanego w pokazanym przykładzie dla $n = 10$. $M e T = min { k | P(T <= k) >= 0.5 } = 4$ (uznawane były też odpowiedzi $<5$ i $>3$) == Sieć społecznościowa === Obliczając dynamikę $W(t)$ trzy razy korzystaliśmy z twierdzenia o prawdopodobieństwie całkowitym. Z jakich układów hipotez korzystaliśmy? 1. Zajście lub niezajście błędu implementacji lub interpretacji. 2. Spotkanie lub brak spotkania w ciągu $d t$. 3. Reputacje uczestnika i partnera, korzystając z $W(t)$ do obliczenia prawdopodobieństw hipotez. === Obliczając $h_(x y)$ stosujemy twierdzenie o prawdopodobieństwie całkowitym. Co jest tutaj układem zupełnym zdarzeń? Wystąpienie/nie wystąpienie błędu implementacji/interpretacji === Opisz układy zupełne zdarzeń wykorzystywane w rozumowaniu prowadzącym do określenia dynamiki procesu $W(t)$. Na odcinku czasu wystąpi lub nie wystąpi interakcja. Jeśli wystąpi interakcja, to układ zupełny z 4 hipotezami $->$ losowy uczestnik i losowy partner mogą mieć niską lub wysoką reputację == Szybkie sortowanie === Wyjaśnij sens równania $e k|k = n - 1 + e k + e n - 1 - k$. Równanie rekurencyjne liczby potrzebnych porównań dla przypadku w którym wylosowana liczba jest większa od k liczb w sortowanym zbiorze. W tym wywołaniu wykonujemy $n-1$ porównań (pivoting), oraz ilość porównań potrzebną do posortowania zbiorów o rozmiarze k oraz o rozmiarze $n-1-k$. == Odtwarzanie tras pakietów IP === Dlaczego słupki rozkładu odciętego są wyższe niż nieodciętego? Ze względu na to, że masa prawdopodobieństwa przeniesiona została z ogona do tego przedziału, do którego obcięliśmy model. Jest to reprezentowane przez warunek normalizacyjny. === Jaki sens mają wielkości losowe $X_1$, ..., $X_d$ w problemie zbieracza kuponów? Są to czasy czekania natrafienie na kolejny kupon (kolor), którego jeszcze nie mamy. === Niech ciąg $(Z_1, Z_2, ...)$ reprezentuje zbiory posiadanych kolorów w kolejnych etapach zbierania kuponów. Uzasadnij, że jest to łańcuch Markowa I rzędu. $P(Z_t = z_t | Z_(t-1) = z_(t-1),Z_(t-2) = z_(t-2), ... , Z_1 = z_1)$ jest prawdopodobieństwem że kolejny wylosowany kolor $k in z_(t-1)$ (gdy $z_t = z_(t-1)$), bądź że $k in z_t / z_(t-1)$ (gdy $z_t != z_(t-1)$); zatem do jego wyznaczenia nie jest potrzebna znajomość $z_(t-2), ... , z_1$. == Optymalizacja polityki terminacji === Dlaczego dla rozważanej klasy polityk terminacji wystarczająca jest skończona tablica STOP/KONT? Od pewnego momentu w wierszach i kolumnach tablicy są same wartości STOP. === Dlaczego nie jest poprawna polityka terminacji "znajdź pozycję w ciągu prób, dla której $a$ jest maksymalne i podejmij wówczas decyzję STOP"? Bo tę decyzję musimy podjąć na bieżąco, a nie po poznaniu całego ciągu. Jeżeli moglibyśmy podjąć ją po poznaniu całego ciągu, to zawsze bylibyśmy w stanie podjąć decyzję optymalną. === Wyjaśnij probabilistyczny sens równania $e(o, r) = 1/2 e(o + 1, r) = 1/2 e(o, r + 1)$. Równanie to można interpretować probabilistycznie jako przewidywanie prawdopodobieństwa wystąpienia zdarzenia e w punkcie $(o,r)$ na podstawie prawdopodobieństw wystąpienia tego samego zdarzenia w sąsiednich punktach: $(o+1, r)$ i $(o, r+1)$. == Testowanie oprogramowania === Co reprezentują wielkości losowe $B$ i $G$? $B$ to liczba niepoprawnych modułów jeśliby zakończyć testowanie na etapie $i$. $G$ to liczba przetestowanych modułów do następnego etapu, czyli do natrafienia na niepoprawny. Jest to koszt przejścia z danego etapu do następnego jeśli wybrano kontynuację. === Wyjaśnij słownie w terminach wartości oczekiwanych optymalną regułę decyzji KONT/STOP w kolejnych etapach. Wybieramy tą decyzję, która ma mniejszy koszt. Kontynuacja to koszt wykonania testów. Stop to ryzyko awarii krytycznej spowodowanej błędnym modułem === W którym momencie zastosowaliśmy uogólnione pojęcie wartości średniej? Liczenie kosztu kontynuacji: $E h (B_(n- y, p) / h)$ == Bizantyjscy generałowie === Jakiej informacji nie wykorzystuje zasada maksimum wiarygodności w porównaniu do twierdzenia Bayesa? Nie korzysta ona z informacji o prawdopodobieństwie zostania bizantyjskim generałem przez agenta. Nie zakłada, że dzieje się to w sposób niezależny. === Jakie różnice między wynikami dla twierdzenia Bayesa i zasady maksimum wiarygodności zaobserwowaliśmy przyjmując, że liczba agentów typu BG może być dowolna od 0 do 100 z jednakowym prawdopodobieństwem? Wówczas wyniki byłyby do siebie proporcjonalne, nie obserwowalibyśmy różnic w kształtach tzn. $P(H_i/R = k) ~ P(R = k|H_i)$ (przeskalowane o współczynnik normalizacji). === Jak mierzyć niepewność uzyskanych wyników? Dlaczego w przypadku zasady maksimum wiarygodności jest ona większa w porównaniu z twierdzeniem Bayesa? Niepewność uzyskanych wyników możemy mierzyć przez rozproszenie słupków histogramu od maksimum. Dla zasady maksimum wiarygodności nie wykorzystujemy znajomości o prawdopodobieństwie zostania przez agenta bizantyjskim generałem, dlatego nie jest faworyzowana mniejsza ich ilość dla mniejszej liczby niepoprawnych odpowiedzi, co mogłoby stanowić czynnik przyczyniający się do zredukowania niepewności. === Zastosowanie zasady maksimum wiarygodności zamiast twierdzenia Bayesa może być motywowane tym, że... Dla zasady maksimum wiarygodności nie wykorzystujemy znajomości o prawdopodobieństwie zostania przez agenta bizantyjskim generałem, dlatego nie jest faworyzowana mniejsza ich ilość dla mniejszej liczby niepoprawnych odpowiedzi, co mogłoby stanowić czynnik przyczyniający się do zredukowania niepewności. == System reputacyjny Beta === Jak na jakość eliminacji nieuczciwych klientów wpłynęłoby zastąpienie parametrów kwantyl $0.95$ i kwantyl $0.05$ przez kwantyl $0.9$ i kwantyl $0.1$? Więcej klientów zostałoby uznanych za oszczerców i wspólników. === Czy zastosowanie kwantyli rzędu $0.01$ i $0.99$ zamiast $0.05$ i $0.95$ w skróciłoby, czy wydłużyło opisaną procedurę eliminacji nieuczciwych klientów? Wydłużyłoby, ponieważ w każdej iteracji system byłby bardziej uważny przy odrzucaniu nieuczciwej liczby klientów i odrzucał by ich mniej. === Do wypracowania oceny $z^*$ wykorzystuje się rozkład a posteriori $p(z|w, n)$. Z punktu widzenia twierdzenia Bayesa, co reprezentuje $z$, a co $w$ i $n$? $z$ należy do zbioru ciągłego układu zupełnego hipotez. Jego wartość należy do $[0, 1]$ i jest hipotezą, że poziom zaufania agenta = z. \ $w$ - liczba raportów o wysokiej satysfakcji \ $n$ - liczba raportów o niskiej satysfakcji \ $w, n$ - to co już zaszło i o tym wiemy \ === Dla ograniczenia efektów nieuczciwych raportów ocenę $z^*$ porównuje się z jaką charakterystyką rozkładu $p(z|w, n)$? Ocenę większościową $z^*(M)$ porównujemy z kwantylami rozkładu otrzymanego dla $w$ i $m$ tylko danego klienta. Jeśli ocena jest mniejsza lub większa od progowego kwantyla to klienta uznajemy za nieuczciwego. === Rozkład beta jest pewnym warunkowym rozkładem gęstości prawdopodobieństwa - jakiej wielkości losowej i przy jakim warunku? Rozkład beta jest określony dla dwóch parametrów, $alpha$ i $beta$, które są parametrami kształtu. Wartości tych parametrów wpływają na kształt rozkładu gęstości prawdopodobieństwa. Zmienna losowa $X$ z rozkładem beta ma gęstość prawdopodobieństwa określoną wzorem: $ f(x|alpha, beta) = (x^(alpha - 1) (1-x)^(beta - 1))/B(alpha, beta) \ x "jest wartością zmiennej losowej," \ alpha > 0 "jest parametrem kształtu," \ beta > 0 "jest drugim parametrem kształtu," \ B(alpha, beta) "jest funkcją beta, która normalizuje rozkład (całka gęstości prawdopodobieństwa od 0 do 1 równa 1)." $ === W 10 próbach Bernoulliego zaobserwowano 7 sukcesów i 3 porażki. Jaki jest rozkład à posteriori prawdopodobieństwa sukcesu $p$, jeżeli rozkład à priori jest równomierny dla $p in [0,1]$? $"Beta"_(7,3) (p)$ == Generacja liczb pseudolosowych #context counter(heading).update((counter(heading).get().at(0), counter(heading).get().at(1) - 1)) == Metoda odwracania dystrybuanty === Jakie przekształcenie generuje liczby losowe o rozkładzie $f(x)$? Liczby losowe o rozkładzie $f(x)$ generuje funkcja odwrotna. Czasami trzeba zrobić całke $f(x)$ jak p(x) podane. $ p(x) = 1/a e^(-x/a) => X = - a ln(1 - U) $ $ F(x) = 0.5 + arctan(x)/pi => X = tan(pi(U - 1/2)) $ $ F(x) = 1 - e^(-x^b/a) => X = root(b, - a ln(U)) $ $ p(x) = 2x => X = sqrt(U) $ == Naturalne zbiory danych === Jaki jest fizyczny sens stałej $k$ w wyrażeniu $P(X < x) = P(k X < x)$? Naturalna zmienna losowa nie może zależeć od skali (jednostki), czyli prawdopodobieństwo $X$ musi być takie samo jak $k X$, gdzie $k > 0$ jest dowolną stałą. = Sumy niezależnych wielkości losowych == Funkcje charakterystyczne i tworzące #context counter(heading).update((counter(heading).get().at(0), counter(heading).get().at(1) - 1)) == Rozkłady sum === Jakiej operacji na niezależnych wielkościach losowych odpowiada mnożenie ich funkcji charakterystycznych? Dodawaniu tych wielkości. === Dodawanie niezależnych wielkości losowych odpowiada następującym operacjom na ich rozkładach prawdopodobieństwa i funkcjach charakterystycznych: na rozkładach: splot, na funkcjach charakterystycznych: mnożenie === Jak z funkcji charakterystycznej otrzymać rozkład prawdopodobieństwa dyskretnej wielkości losowej? Korzystając z twierdzenia o jednoznaczności === Jak z funkcji tworzącej otrzymać rozkład prawdopodobieństwa dyskretnej wielkości losowej? Korzystając z rozwinięcia w szereg potęgowy === Czy słuszne jest stwierdzenie, że funkcja tworząca jest szczególnym przypadkiem funkcji charakterystycznej, gdzie $e j u = z$? Uzasadnij. $ g(X) = cases( e^(j v X) X "ciągła o zbiorze realizacji" x in [a, b], z^X X "dyskretna o zbiorze realizacji" x in {0, 1, 2, ...} ) $ Jest, charakterystyczna to całkowanie, tworząca to dodawanie. Różnica jest w dziedzinie. === Niezależne wielkości losowe $X$ i $Y$ mają dane funkcje charakterystyczne $phi_X (v)$ i $phi_Y (v)$. Zapisz $phi_Z(v)$, gdzie $Z = a X + b Y + c$, zaś a, b, c - stałe. $ phi_Z(v) = E e^(j v (a X + b Y + c)) = E e^(j v a X) E e^(j v b Y) E e^(j v c) = phi_X (a v) phi_Y (b v) e^(j v c) $ == Równoważenie obciążenia: round robin === Jaki rozkład ma interwał między dwoma kolejnymi wywołaniami do danego serwera w obecności 5 równoległych serwerów? Rozkład Erlanga-5. === Jaka własność funkcji charakterystycznej jest wykorzystywana przy dodawaniu niezależnych wielkości losowych? Funkcja charakterystyczna sumy niezależnych wielkości losowych jest równa iloczynowi funkcji charakterystycznych tych zmiennych. === W jaki sposób liczba równoległych serwerów wpływa na rozkład interwału widzianego przez ustalony serwer? Czym więcej serwerów, tym jest to rozkład Erlanga-n o większym $n$. Wówczas, masa prawdopodobieństwa przesuwa się w kierunku wyższych wartości. === Rozkład Erlanga powstaje w wyniku dodawania niezależnych wielkości losowych o rozkładach... wykładniczych == Zaległości w obsłudze === W wyniku czego powstaje rozkład Erlanga rzędu $k$? W wyniku $k$-krotnego splotu rozkładu wykładniczego. === Skąd bierze się jakościowa różnica w wykresach prawdopodobieństwa naruszenia reżimu czasu rzeczywistego? Z różnicy w czasach wykonania pojedynczego przerwania. Jeśli przychodzące przerwania zajmują nam dużo czasu to prawdopodobieństwo zaległości jest wysokie. === W wyniku dodawania niezależnych wielkości losowych o rozkładach równomiernych powstaje rozkład... Irwina-Halla == Utracone wywołaniami === Jaki jest związek między rozkładem Poissona a rozkładem geometrycznym? Jeżeli dla ilości wywołań opisywanych rozkładem Poissona przyjmiemy losowy przedział czasu o rozkładzie wykładniczych (czyli $T$ zamiast $t$) to ilosc wywołan w tym losowym przedziale bedzie miała rozkład geometryczny (mozna to wyprowadzic z twierdzenia o prawdopodobienstwie całkowitym). === Jeżeli liczba wywołań w danym przedziale czasowym ma rozkład Poissona, to jaki jest rozkład liczby wywołań utraconych w czasie awarii o losowym czasie trwania o rozkładzie wykładniczym? Jest to rozkład geometryczny. === Jeżeli liczba wywołań w danym przedziale czasu ma rozkład Poissona, to jaki jest rozkład interwału między dwoma kolejnymi wywołaniami? Jest to rozkład wykładniczy. === Jaki rozkład prawdopodobieństwa odpowiada funkcji charakterystycznej będącej pojedynczą eksponentą? Atom w jednym punkcie, a reszta jest rozłożona jak krzywa wykładnicza. === Jaki rozkład ma liczba zdarzeń na odcinku czasu ustalonej długości $t$, jeżeli interwały między nimi są iid i mają rozkład wykładniczy o średniej $a$? Rozkład Poissona ze średnią $t/a$. == Opróżnianie stosu === W przykładzie dla $P(N = 0) = 0.3$, $P(N = 1) = 0.2$, $P(N = 2) = 0.2$, $P(N = 3) = 0.1$ prawdopodobieństwo, że populacja w drugim pokoleniu wymrze wynosi... $ P(Y^(2) = 0) = 0.4407 $ === Jakie jest prawdopodobieństwo ostatecznego wymarcia populacji przy $P(N = 0) = 0.3, P(N = 1) = 0.4, P(N = 2) = 0.2, P(N = 3) = 0.05$. Korzystamy z metody Newtona (iteracyjnym przybliżaniu pierwiastka równania) \ $q = 0.3 + 0.4q +0.2q^2 + 0.05q^3$ (przyrównujemy to do 0, czyli przenosimy q na drugą) \ $f(q) = 0.05q^3 + 0.2q^2 - 0.6q + 0.3$ (obliczamy z tego pochodną) \ $f'(q) = 0.15q^2 + 0.4q - 0.6$ \ $q_(n+1) = q_n - f(q_n)/(f'(q_n))$ \ Jako $q_0$ wybieramy 0 i podstawiając do $f(q)$ i $f'(q)$ obliczamy wartości. Podstawiamy je do wzoru na kolejne $q$ i mamy $q_1$. Następnie obliczamy $q_2$ za pomocą $q_1$ itd. \ $q_0 = 0 -> q_1 = 0.5 -> q_2 = 0.65517 -> q_3 = 0.67964$ \ $product = 0.68078$ === Prawdopodobieństwa liczby bezpośrednich potomków są następujące: 0 - 30%, 1 - 40%, 2 - 20% i 3 - 10%. Jaka jest szansa, że populacja nie wymrze? Szansa że wymrze, to 0.791, czyli że przeżyje to 1-0.791 = 0.209 === Jeżeli równanie $product = G_N (product)$ ma dwa rozwiazania, to co można powiedzieć o prawdopodobienstwie, że stos ponownie się opróżni? Jest ono równe mniejszemu z tych dwóch prawdopodobieństw, czyli $product = min{product_1, product_2}$. Nie ma pewności czy się opróżni, czy nie. === Jaka jest probabilistyczna interpretacja nachylenia krzywej $G_n (z)$ w punkcie 1? Jest to wartość średnia liczby bezpośrednich potomków $G'_n (1) = E N$. Jeśli $E N <= 1$ to populacja na pewno wymrze. W przeciwnym wypadku, istnieje niezerowe prawdopodobieństwo, że stos się już nigdy nie opróżni. \ Dla tych parametrów wymrze: 0.791, przetrwa: 0.209 === Opisz wszystkie elementy równania $product = G_N (product)$ i uzasadnij, że $product = 1$ zawsze jest jednym z jego pierwiastków. $product$ - prawdopodobieństwo ostatecznego wymarcia populacji, $N$ - liczba potomków osobnika, $G_N$ - funkcja tworząca wielkości losowej $N$; $G_N(1) = sum_(k=0)^infinity P(N = k) = 1$ (warunek normalizacyjny) == Słabe prawo wielkich liczb: eksperyment === Gdyby rozkład $X$ był wykładniczy, to do którego z pokazanych przebiegów podobny byłby analogicznie otrzymany przebieg w funkcji $n$? Byłby analogiczny do rozkładu równomiernego, bo ma skończoną wartość średnią. === Co możemy powiedzieć o wartości średniej rozkładu Cauchy'ego? Nie istnieje, ponieważ nie działa prawo wielkich liczb. Wielokrotnie powtórzone doświadczenie daje statystycznie tak samo dobry wynik jak pojedyncza iteracja. === Dlaczego przebieg $S_n/n$ w funkcji $n$ nie ustala się dla wielkości losowej X o rozkładzie Cauchy'ego? Rozkład Cauchy'ego oscyluje wokół 0.5 i się nie zbiega. W przypadku tego rozkładu wartość średnia nie istnieje więc nie działa prawo wielkich liczb, dowolna ilość obserwacji gwarantuje statystycznie tak samo dobry wynik jak jedna obserwacja. === Co jest powodem narastania trendu przebiegu $(S_n)/n$ w funkcji $n$ dla wielkości losowej $X$ o rozkładzie Pareto? Jest to spowodowane faktem, że rozkład Pareto z takim współczynnikiem kształtu ma wartość średnią nieskończoną, zatem dąży do nieskończoności. === Który parametr rozkładu Pareto należałoby zmienić, aby uzyskać przebieg $(S_n)/n$ w funkcji $n$ podobny jak dla wielkości losowej $X$ o rozkładzie równomiernym? Należałoby zmienić współczynnik kształtu tak, żeby otrzymać wartość średnią skończoną. Należy go ustalić $k > 1$. === Czy w wariancie Chinczyna słabe prawo wielkich liczb działa dla każdego typu rozkładu prawdopodobieństwa obserwacji? Nie, nie będzie on działał dla rozkładu, który nie ma średniej, czyli np. dla Cauchy'ego. === Wyjaśnij przyczynę braku zbieżności w otrzymanych wykresach $S_n/n$ dla rozkładów Pareto i Cauchy'ego. Dla rozkładu Pareto z parametrem kształtu $<= 1$ mamy $E X = infinity$; dla rozkładu Cauchy'ego prawo wielkich liczb nie działa (nie istnieje $E X$). == Centralne twierdzenie graniczne === W odróżnieniu od słabego prawa wielkich liczb, w wariancie Chinczyna centralne twierdzenie graniczne wymaga, aby... wielkość losowa miała skończoną wariancję. === Czy statystycznie niezależne wielkości losowe o jednakowych rozkładach spełniają słabe prawo wielkich liczb i twierdzenie graniczne i pod jakimi warunkami? Słabe prawo wielkich liczb tak, pod warunkiem, że istnieje wartość średnia. Centralne twierdzenie graniczne (Ctg) tak, pod warunkiem, że istnieje skończona wariancja. === Co zaobserwujemy dodając do siebie wiele rozkładów wykładniczych? Zaobserwujemy kolejne rozkłady Erlanga-n, które będą coraz bardziej przypominać krzywą dzwonową. Rozkład wykładniczy ma skończoną wariancję. == Serwer webowy === Aby obliczyć $P(99000 <= S_40000 <= 101000)$ potrzebna nam jest wartość funkcji Laplace'a dla... $ Phi((101000 - 40000 * 2.5)/(sqrt(40000) * 1.369)) - Phi((99000 - 40000 * 2.5)/(sqrt(40000)*1.369)) = 2 Phi(3.652) \ 2 Phi((101000 - 99000)/(2 * sqrt(40000) * 1.369)) = 2 Phi((101000 - 99000)/(547.6)) "- szybkie liczenie gdy" (a+b)/2 = 100000 \ sigma = sqrt(10*0.25*(1-0.25)) \ P(a <= S_n < b) = Phi((b - n * m)/(sqrt(n) * sigma)) - Phi((a - n * m)/(sqrt(n)*sigma)) $ Wynik na slajdzie: $x = 3.652$ == Eksperyment Wolfa === Jakie odchylenie standardowe miałby rozkład wielkości losowej $(S_n)/n$ przy założeniu, że eksperyment obejmował nie 20000, lecz 200 rzutów kostką? $ s = 0.373/sqrt(200) $ === Co gdyby rozkład obejmował 200 rzutów? Hipoteza, że kostka jest uczciwa byłaby bardziej wiarygodna, bo mielibyśmy większe odchylenie standardowe. === Dlaczego do zakwestionowania uczciwości kostki <NAME> potrzebne było centralne twierdzenie graniczne, a nie wystarczyło słabe prawo wielkich liczb? Potrzebne były oceny masy prawdopodobieństwa wielkości losowej $S_n/n$ wokół $E S_n/n$ dla dużych $n < infinity$. == Czas trwania sesji === Gęstość prawdopodobieństwa przekształconej wielkości losowej otrzymujemy zakładając, że przekształcenie $g$ spełnia warunki... gładkość, odwracalność === Dystrybuantę przekształconej wielkości losowej otrzymujemy zakładając, że przekształcenie $g$ spełnia warunki... odwracalność === Dla jakiej funkcji $g$ rozkład wielkości losowej $Y = g(X)$ ma ten sam kształt co rozkład X? Dla funkcji liniowej. Pochodna musi być stała. === Jaka jest zasada konstrukcji wykresu Q-Q i co taki wykres nam daje? Jest to wykres kwantyl funkcji dopasowywanej do kwantyla empirycznego. Dzięki temu możemy mierzyć jakość dopasowania - idealnie prosta. Zasada tworzenia - w celu dopasowania jak najlepszego rozkładu. === Jaki byłby kształt rozkładu $Z$, gdyby przyjąć $g(x) = a x + b "(a, b - stałe)"$? Taki sam jak kształt S, bo pochodna stała. === Przyjmując $g(s) = s^2$ otrzymaliśmy następujący rozkład $Z$: $ p_Z(z) = F'_Z(z) = F'_S(s)/abs(g'(s)) bar.v_(s=g^(-1)(z)) \ "Dla" g(s) = s^2 "oraz" p_S(s) = 1/(sqrt(2 pi) dot sigma) e^(-(s-m)^2 \/ 2 sigma^2) \ g^(-1)(s) = sqrt(s) \ p_Z(z) = 1/(sqrt(2 pi) dot sigma dot 2 sqrt(z)) e^(-(sqrt(z)-m)^2 \/ 2 sigma^2) $ === Jeżeli $S$ ma rozkład $N(m, sigma)$, to jaki rozkład ma wielkość losowa $Z = 2S$? $N(2m, 2sigma)$ (przekształcenie $Z = g(S)$ jest liniowe, zatem kształt rozkładu zostaje zachowany, zaś wartość oczekiwana i odchylenie standardowe zostają odpowiednio przeskalowane) == Atak na Wi-Fi === Jakie zagadnienie rozstrzyga nierówność Popoviciu? Pozwala nam określić maksymalną wariancję dla wszystkich rozkładów ${X_1}, ..., {X_n}$. === Czym należy zastąpić warunek $n >= 663.6 sigma^2$, jeżeli wymagany procent pewności zmniejszymy do 98%? Odczytujemy argument funkcji Laplace'a dla $0.49$ i oznaczamy go przez $k$. Wtedy $n >= k^2 sigma^2 / 0.01$. === Gdyby dopuszczalne ryzyko że $|S_n/n - m| > 0.1$ zwiększyć do 2%, to minimalna bezpieczna liczba obserwacji $n$ wzrośnie czy zmaleje? Uzasadnij. Skoro wymagana wartość $Phi(0.1 sqrt(n)/sigma)$ zmniejszyła się, to $n$ także ($Phi$ jest funkcją rosnącą) = Ogony rozkładów prawdopodobieństwa == Częstość anomalii w sygnale === Podaj szkic obliczenia wartości $0.25%$ dla szumu w kanale. $ P("szum" > 50) = P("szum" > 20 sigma_"szum") <= 1/(20^2) = 0.0025 $ === Gdyby odchylenie sygnału wejściowego było o 50% większe $P(abs("out" - E) > 50)$ byłoby ograniczone nie przez $2.4%$, tylko przez $ P(abs(X - E X) >= c sigma) <= 1/c^2 \ "Wartość dla" P(abs("sygnał" - E) > 50) <= 2.4% \ 50 = c * 7.76 => c = 6.44 \ P(abs("sygnał" - E) > 50) <= 1/6.44^2 = 2.4% \ "W zadaniu" sigma "ma się równać" 1.5 * 7.76 "czyli" 11.64 \ 50 = sigma * c ", a więc" c = 50/11.64 = 4,296 \ P(abs("sygnał" - E) > 50) <= 1/4.296^2 = 5.4% $ = <NAME> == Jednorodny łańcuch Markowa I rzędu Macierz przejść jednorodnego łańcucha Markowa I rzędu ma następujące własności: - Jest to macierz kwadratowa, stochastyczna, czyli $sum_(j=0)^s m_(i j) = 1$ - Komórki reprezentują niezmienne w czasie prawdopodobieństwa przejść między stanami: $P(X_t = j | X_(t-1) = i) = m_(i j)$ - Niech $p(0)$ oznacza rozkład stanów w chwili początkowej, wówczas korzystając z macierzy $M$ możemy policzyć $p(t) = p(0) M^t$ - Natomiast $M^t$ jest również macierzą stochastyczną. Wartości własne tej macierzy spełniają równanie $1 = lambda_0 >= ... >= lambda_S$ == Sztuczne źródła tekstowe === Jak wielką przestrzeń stanów musielibyśmy rozważać, gdyby generacji tekstu na podstawie częstości $n$-gramów dokonywać przy pomocy łańcuchów Markowa 1 rzędu? $ abs(S)^(n-1)", S to liczba możliwych znaków" $ === Jaki byłby rozmiar macierzy przejść w sztucznym generatorze tekstu opartym na łańcuchach Markowa I rzędu operującym częstościami $n$-gramów? $ abs(S)^(n-1) times abs(S)^(n-1) $ === Wyjaśnij, dlaczego do analizy w zasadzie wystarczają nam łańcuchy Markowa I rzędu. Bo każdy łańcuch wyższego rzędu można zredukować do łańcucha 1. rzędu kosztem wykładniczego wzrostu ilości stanów. === Liczba stanów łańcuchów Markowa I rzędu do analizy quadrogramów na tekstach angielskich wynosi $26^3$ lub $27^3$ (uwzględniając spacje, na slajdach uwzględniona) \ $abs(S)^2$ dla trigramów w I rzędzie (pamiętamy 2 ostatnie) == Ergodyczność łańcucha Markowa === Co przesądza o szybkości zbieżności do rozkładu granicznego? Druga wartość własna $lambda_1$ macierzy $M$. Im mniejsza, tym szybsza zbieżność. === Jaki jest rozkład graniczny jednorodnego dwustanowego łańcucha Markowa o macierzy przejść $M = mat(1/2, 1/2; 1/4, 3/4)$ $(pi_1, pi_2) mat(1/2, 1/2; 1/4, 3/4) = (pi_1, pi_2) #h(2cm) cases( 1/2 pi_1 + 1/4 pi_2 = pi_1, 1/2 pi_1 + 1/4 pi_2 = pi_2 ) #h(2cm) pi_1 = 3/4, pi_2 = 1/4 => pi = (3/4, 1/4) $ === Który parametr macierzy prawdopodobieństw przejść decyduje o szybkości zbieżności rozkładu prawdopodobieństwa stanów jednorodnego łańcucha Markowa I rzędu do rozkładu granicznego $p(infinity)$? Szybkość zbieżności łańcucha Markowa odpowiada drugiej wartości własnej M czyli $lambda_1$. Czym $lambda_1$ mniejsze, tym szybciej się zbiega. === Jaki jest rozkład graniczny jednorodnego dwustanowego łańcucha Markowa I rzędu o macierzy przejść $M = mat(1/3, 2/3; 1/2, 1/2)$? Z układu równań Chapmana-Kołmogorowa $p*M = p$ z warunkiem $abs(p) = 1$ dostajemy $p_1 = 3/7, p_2 = 4/7$. == PageRank === Jak z punktu widzenia markowskiego modelu probabilistycznego należy interpretować współczynnik tłumienia w podstawowej formule PageRank? Jest to prawdopodobieństwo, że internauta nieskończenie błądzący po internecie nie zrestartuje przeglądania. Prawdopodobieństwo to stanowi współczynnik proporcjonalności między PageRank, a częstością odwiedzin strony w błądzeniu losowym. === Współczynniki PageRank odpowiadają następującej charakterystyce łańcucha Markowa I rzędu... $ p_j/d = (1-d)/s + sum_i p_i/a_i $ == Rozpoznawanie mowy === Gdyby jako sygnaturę ciągu $X$ ustalić rozkład długości $3$-paczek to w porównaniu z otrzymanymi na wykładzie byłby on... o wolniejszym spadku wraz ze wzrostem $k$, ponieważ prawdopodobieństwo $3$-paczki długości $k$ jest większe niż ciągu jedynek długości $k$. $3$-paczki obejmują też wszystkie $1$-paczki, a ciąg jedynek to właśnie $1$-paczka. === Opisz zasadę tworzenia ciągu binarnego zgodnie z mechanizmem ukrytego łańcucha Markowa. Mamy dwa stany, jeżeli znajdujemy się w danym kroku w stanie $1$ to $P$ wypisania jedynki jest równe $b_1$, a zera $1-b_1$, natomiast w stanie $2$ wypisanie jedynki jest równe $b_2$, a zera $1-b_2$ (czyli generujemy z pewnym prawdopodobieństwem zależnym od stanu). = Wektory losowe i korelacja == Wektory losowe === W jakiej sytuacji rozkład łączny wektora losowego jest jednoznacznie wyznaczony przez jego rozkłady brzegowe? Gdy składowe są statystycznie niezależne, wówczas w każdym punkcie swojej dziedziny wartość rozkładu łącznego jest iloczynem wartości rozkładów brzegowych. == Korelacja: wariancja X+Y === Dane są wielkości losowe X i Y o znanych odchyleniach standardowych $sigma_X$ i $sigma_Y$. Jaka jest największa możliwa wartość $V(X+Y)$? $ V(X+Y) = V X + V Y + 2 gamma_(X Y) <= sigma_X^2 + sigma_Y^2 + 2 sigma_X sigma_Y = (sigma_X + sigma_Y)^2 $ == Korelacja, a zależność statystyczna === Określ korelację i zależność statystyczną pomiędzy wielkościami losowymi $X$ i $Y$, gdzie $X = cos(U), Y = sin(U), p_U = 1/2 pi, u in [-pi, pi]$ Są nieskorelowane, ale zależne (jedynka trygonometryczna). $X^2 + Y^2 = 1$ - zależne. Po scałkowaniu i obliczeniu $E(X Y) - E(X) E(Y)$ wychodzi 0 - nieskorelowane. === Jak mają się do siebie własności korelacji i zależności statystycznej składowych wektora losowego? Jeżeli składowe wektora są niezależne, to są nieskorelowane (cov = 0). Jeżeli są nieskorelowane, to z tego nie wynika niezależność - patrz zad. wyżej. == Regresja liniowa === Jaki wpływ ma unormowany współczynnik kowariancji na prostą regresji i błąd średniokwadratowy regresji? Od tego współczynnika zależy współczynnik kierunkowy prostej. Przykładowo, ujemnie skorelowane skutkują w prostej malejącej. Ponadto, im bardziej skorelowane zmienne, tym mniejszy błąd średniokwadratowy. Błąd ten wynosi 0 dla korelacji liniowej. Natomiast jest maksymalny, gdy współczynnik korelacji wynosi 1. Czym bardziej skorelowane tym lepiej (nie ważne czy dodatnio czy ujemnie). === Jak wygląda prosta regresji w przypadku, gdy $X i Y$ są nieskorelowane? W przypadku, gdy zmienne $X$ i $Y$ są nieskorelowane, współczynnik kierunkowy $beta_1$ w prostym modelu regresji liniowej będzie bliski lub równy zeru, co oznacza, Że nie ma liniowego związku między $X$ i $Y$. W takiej sytuacji, najlepszym estymatorem dla $Y$ byłaby po prostu średnia $Y$, ponieważ $X$ nie dostarcza żadnej dodatkowej informacji, która mogłaby pomóc w przewidywaniu $Y$. \ Zatem równanie prostej regresji przy braku korelacji między $X$ i $Y$ sprowadza się do: $ Y = beta_0 + epsilon$, gdzie $beta_0$ będzie równy średniej $Y$. === W jakich granicach może zmieniać się współczynnik kowariancji $gamma_(X Y)$ dowolnych wielkości losowych $X$ i $Y$ o znanych skończonych wariancjach $V X$ i $V Y$? Z nierówności Schwarza mamy $|gamma_(X Y)| <= sqrt(V X)sqrt(V Y)$, zatem $-sqrt(V X) sqrt(V Y) <= gamma_(X Y) <= sqrt(V X) sqrt(V Y)$. == Stratna kompresja obrazu === Optymalna stratna kompresja obrazu wymaga, by kolumny macierzy do obrotu wektora pikseli spełniały następujące warunki: żeby były m największymi wartościami własnymi macierzy kowariancji $Gamma$. Wtedy jako kolumny macierzy wstawiamy wektory własne macierzy kowariancji o tych wartościach. === Opisz operację macierzową prowadzącą do dekorelacji ciągu pikseli. Operacja ta polega na obrocie układu współrzędnych za pomocą macierzy $Q$, której kolumny są największymi wektorami własnymi macierzy kowariancji $Gamma$. Obrót ten prowadzi do zapisania $n$ wartości pikseli za pomocą $m$ wartości, gdzie $m <= n$. === Które charakterystyki macierzy kowariancji ciągu pikseli są istotne z punktu widzenia optymalizacji stratnej kompresji obrazu? Istotne są odpowiednie wektory własne macierzy. === Jak należy dobrać kolumny macierzy przekształcenia $Q$, aby zdekorelować piksele i zminimalizować stratność kompresji? Błąd ten zminimalizujemy, gdy kolumnami macierzy $Q$ uczynimy wektory własne macierzy. === Jaka własność macierzy obrotu $Q$ powoduje dekorelację pikseli obrazu ? Kolumny $Q$ są wektorami własnymi macierzy kowariancji wektora pikseli. = Estymatory == Próbka losowa populacji === Podaj warunki probabilistyczne, jakie powinna spełniać prawidłowo pobrana próba losowa z populacji. Prosta - $X_i$ są niezależne. Reprezentatywna - $X_i ~ X$ (rozkład cech osobnika i taki jak rozkład cech całej populacji). == Estymatory maksimum wiarygodności === Jaki jest wpływ błędów statystycznych poszczególnych obserwacji na ocenę wartości średniej w populacji o modelu $N(a, sigma)$? Czym większy błąd statystyczny danej próbki, z tym mniejszą wagą uwzględniamy ją przy estymacji wartości średniej. Ma to sens, gdyż obserwacje są dla nas mniej wiarygodne, skoro obarczone są większym błędem. == Monte Carlo: redukcja wariancji === Która z dwóch wielkości: $V X + V Y$ oraz $V(X + Y)$ jest większa? To zależy od ich korelacji. \ Jeżeli jest ujemna to $V(X + Y) < V X + V Y$ \ Jeżeli dodatnia to $V(X + Y) > V X + V Y$ \ Jeżeli zerowa to $V(X + Y) = V X + V Y$ czyli wtedy, kiedy $X$ i $Y$ są niezależne. === Jaki efekt przyniosłaby metoda zmiennych parami przeciwstawnych, gdyby dla $k=1,3,5...$ przyjąć $U_((k+1)) = U_((k))?$ Zmniejszenia odchylenia standardowego. == Prognoza ataków dnia zerowego === Jak wzrost liczby typów zaobserwowanych ataków przekładałby się na jakość prognozy ataków dnia zerowego? Otrzymalibyśmy wówczas mniej efektywny estymator. === Co reprezentuje otrzymana wartość $14376 - 4343 + 2292 - ... = 11430$: estymator? obciążenie estymatora? ocenę? bład statystyczny oceny? coś innego? Estymatę, czyli konkretną ocenę dokonaną przez estymator. A konkretnie liczbę nowych typów. Natomiast 178 to błąd statystyczny oceny. == Przedziały ufności - wyznaczanie === Dla ustalonych $n$ i $z$ szerokość przedziału ufności rośnie wraz z... Ze wzrostem $delta$, ponieważ wówczas pozwalamy na to, że $a$ może przyjmować szersze spektrum wartości. == Robak sieciowy === Gdyby przy $n = 1000$ i $z = 0.2$ jako poziom ufności przyjąć $99%$, to czy mogłaby być poprawna wartość $P(0.1697 < a < 0.2324) = 0.99$? Nie, ponieważ nie wyznaczamy prawdopodobieństwa tego, że $a$ należy do jakiegoś przydziału, bo $a$ nie jest zmienną losową. Zamiast tego wyznaczamy prawdopodobieństwo tego, że kolejne wyznaczone przedziały ufności będą zawierały $a$. === Gdyby przy $n = 1000$ i $z = 20%$ jako poziom ufności przyjąć $delta = 90%$, to czy spodziewany rezultatem jest $J delta (z) = [0.16, 0.24]$? Uzasadnij. Nie, prawdziwy wynosi $[0,1801,0,2216]$. Ponieważ wraz ze spadkiem poziomu ufności, "ufamy" mniejszej ilości rozwiązań, więc przedział się zwęża a nie rozszerza. #align(center)[ #table( columns: 4, table.header( [*n*], [*z*], [*$delta$*], [*$J_delta (z)$*] ), [1000], [0.2], [0.95], [[0.1764, 0.2260]], [1000], [0.2], [0.90], [[0.1801, 0.2216]], [10000], [0.2], [0.95], [[0.1923, 0.2080]], [1000], [0.25], [0.95], [[0.2242, 0.2778]] ) ] === Gdyby przy $n = 1000$ i $z = 20%$ jako poziom ufności przyjąć $delta = 99%$, to czy mogłaby być prawdziwa równość $P(a in [0.1619, 0.232]) = 0.99$? Nie, jeżeli np. $a = 0.17$ to $P = 1$, jeżeli $a = "np." 0.1$ to $P = 0$, a nie $50/50$. Patrz wyżej. = Testowanie hipotez == Policer SLA === Czy hipotezę $H_0$ częściej będziemy odrzucać na poziomie istotności $5%$ niż na poziomie istotności $1%$? Częściej będziemy odrzucać dla $5%$, ponieważ ma większy obszar odrzucenia. === Kiedy definiujemy prawostronny, a w jakiej sytuacji lewostronny obszar odrzucenia $O_alpha$? Prawostronny, jeśli duże wartości $accent(A, hat)$ przemawiają przeciwko $H_0$. Lewostronny, jeśli małe. === Dlaczego w teście serii przyjęliśmy dwustronny obszar odrzucenia? Bo i male i duże ilości serii przemawiają przeciwko temu, że próba jest prosta. === Opisz idealny i najdalszy od idealnego przebieg krzywej ROC. Uzasadnij Idealna krzywa ROC zaczyna się w punkcie (0,0), przechodzi pionowo do punktu (0,1), a następnie poziomo do punktu (1,1), co oznacza doskonałą klasyfikację z AUC równym 1. Najgorsza krzywa ROC to linia prosta od (0,0) do (1,1), wskazująca na losowe przypisywanie klas z AUC równym 0.5, czyli brak zdolności do nauki i rozróżniania klas. === Jakiemu wzajemnemu położeniu rozkładów $p_(accent(A, hat)|H_0)(z)$ i $p_(accent(A, hat)|H_1)(z)$ odpowiada najgorszy możliwy test istotności, w którym moc testu = $alpha$? Oba rozkłady pokrywają się (moc testu jest masą rozkładu z warunkiem $H_1$ powyżej kwantyla $K_(1-alpha)$ rozkładu z warunkiem $H_0$; zatem gdy rozkłady pokrywają się, jest równa $alpha$). == Test istotności === Gdy wyznaczona wartość $p$-value jest wyższa niż przyjęty poziom istotności, to czy powinniśmy odrzucić hipotezę zerową? Gdy jest wyższa to bezpieczniej czujemy się nie odrzucając. === Gdy wyznaczona wartość $p$-value jest niższa niż przyjęty poziom istotności, powinniśmy odrzucić hipotezę zerową? Tak, powinniśmy odrzucić hipotezę zerową, ponieważ dla mniejszych poziomów istotności byśmy to odrzucili. Odrzucając to czujemy się tym bezpieczniej, im mniejsza jest $p$-value. === Gdy wyznaczona wartość $p$-value jest wyraźnie niższa niż przyjęty poziom istotności, czujemy się bardziej, czy mniej komfortowo odrzucając hipotezę zerową? Gdy jest niższa to odrzucając czujemy się bezpieczniej. === W teście na poziomie istotności $alpha = 5%$ pobranie próby prostej dało $p$-value = 95% i czuję się z tym komfortowo. Czy odrzuciłem $H_0$ - uzasadnij? $p$-value > $alpha$ powoduje nieodrzucenie $H_0$; im większe jest $p$-value, tym bardziej czuję się z tym komfortowo.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/super-suboptimal/0.1.0/src/super-suboptimal.typ
typst
Apache License 2.0
// Element function for sequences #let sequence = $a b$.body.func() #let space = $a b$.body.children.at(1).func() #let text-func = $a b$.body.children.at(0).func() // Convert content to an array of its children #let to-children(content) = { if type(content) == str { content.clusters().map(char => [#char]) } else if content.has("children") { content.children } else if content.has("text") { to-children(content.text) } else if content.func() == math.equation { to-children(content.body) } } #let super-dict = ("⁰":"0", "¹":"1", "²":"2", "³":"3", "⁴":"4", "⁵":"5", "⁶":"6", "⁷":"7", "⁸":"8", "⁹":"9", "⁺":"+", "⁻":"−", "⁼":"=", "⁽":"(", "⁾":")", "ᴬ":"A", "ᴮ":"B", "ᴰ":"D", "ᴱ":"E", "ᴳ":"G", "ᴴ":"H", "ᴵ":"I", "ᴶ":"J", "ᴷ":"K", "ᴸ":"L", "ᴹ":"M", "ᴺ":"N", "ᴼ":"O", "ᴾ":"P", "ᴿ":"R", "ᵀ":"T", "ᵁ":"U", "ⱽ":"V", "ᵂ":"W", "ᵃ":"a", "ᵇ":"b", "ᶜ":"c", "ᵈ":"d", "ᵉ":"e", "ᶠ":"f", "ᵍ":"g", "ʰ":"h", "ⁱ":"i", "ʲ":"j", "ᵏ":"k", "ˡ":"l", "ᵐ":"m", "ⁿ":"n", "ᵒ":"o", "ᵖ":"p", "ʳ":"r", "ˢ":"s", "ᵗ":"t", "ᵘ":"u", "ᵛ":"v", "ʷ":"w", "ˣ":"x", "ʸ":"y", "ᶻ":"z", "ᵝ":"β", "ᵞ":"γ", "ᵟ":"δ", "ᵠ":"ψ", "ᵡ":"χ", "ᶿ":"θ", "꙳":"∗") #let sub-dict = ("₀":"0", "₁":"1", "₂":"2", "₃":"3", "₄":"4", "₅":"5", "₆":"6", "₇":"7", "₈":"8", "₉":"9", "₊":"+", "₋":"−", "₌":"=", "₍":"(", "₎":")", "ₐ":"a", "ₑ":"e", "ₕ":"h", "ᵢ":"i", "ⱼ":"j", "ₖ":"k", "ₗ":"l", "ₘ":"m", "ₙ":"n", "ₒ":"o", "ₚ":"p", "ᵣ":"r", "ₛ":"s", "ₜ":"t", "ᵤ":"u", "ᵥ":"v", "ₓ":"x", "ᵦ":"β", "ᵧ":"γ", "ᵨ":"ρ", "ᵩ":"ψ", "ᵪ":"χ", ) #let super-dict-keys = super-dict.keys() #let sub-dict-keys = sub-dict.keys() #let super-sub-keys = super-dict-keys + sub-dict-keys // To save on performance, we pre-compile all // the regexes. #let super-regex = regex(super-dict-keys.join("|")) #let sub-regex = regex(sub-dict-keys.join("|")) #let exactly-one-super-or-sub-regex = regex("[" + super-sub-keys.join("") + "]") #let at-least-one-super-or-sub-regex = regex("[" + super-sub-keys.join("") + "]+") #let to-baseline(str) = { // Converts superscript- or subscript-char // to a sequence: // (str, dict, str, dict, str, …) // where `dict` is // - (t: [super-baseline-string], // b: [sub-baseline-string] ) // super-baseline-string and sub-baseline-string are // the superscript- and subscript-baseline-strings // for consecutive sequence of characters // that are superscript or subscript. // So to-baseline(1²₃⁴56⁷8) = // (1, (t: 24, b: 3), 56, (t: 7), 8) // // Note that the first and last string of the array may be empty. // // Returns `none` if str contains no // superscript- or subscript-char. // .matches uses byte-indices. let matches = str.matches(at-least-one-super-or-sub-regex) if matches==none { return none } let result = () let prev-match-end = 0 for match in matches { // .slice uses byte-indices. result.push(str.slice(prev-match-end, match.start)) let text = match.text let subs = text.replace(super-regex, "").clusters().map(x => sub-dict.at(x)).join("") let supers = text.replace(sub-regex, "").clusters().map(x => super-dict.at(x)).join("") result.push(( t: [#supers], b: [#subs] )) prev-match-end = match.end } result.push(str.slice(prev-match-end)) return result } #let clean-baseline(baseline) = { if (baseline.at("t", default:none)!=none and baseline.t==[]) { baseline.remove("t") } if (baseline.at("b", default:none)!=none and baseline.b==[]) { baseline.remove("b") } return baseline } #let attachy(base-str, unclean-baseline-dict) = { // unclean-baseline-dict has format // (b: [content], t: [content]), // where both contents may possibly be // empty. Also, neither key needs be // present. let clean-baseline-dict = clean-baseline(unclean-baseline-dict) return math.attach([#base-str], ..clean-baseline-dict) } #let process-prev-child-and-text-child(prev-child, child) = { // Returns `none` if `child` contains no // super-/subscript chars. // Otherwise, returns a new sequence, to // be intervowen with the children-array. // If prev-child==none, we either don't // care, or return the attachment to // the empty string. let text = child.text let baseline-arr = to-baseline(text) if baseline-arr==none { // Didn't find any super-/subscript chars. return none } else { // If the head-string of baseline // is empty, we have to move // the first set of super-/subscripts // over to the previous-child: let head-str = baseline-arr.at(0) if head-str.len()==0 { // If there is no previous child, // there's nothing much we can do, // so uhh the next section will // attach the super- and subscripts // to the empty string, I suppose. if prev-child==none { prev-child = [] } else { // Otherwise, remove the head: baseline-arr.remove(0) let head-baseline = baseline-arr.remove(0) // Depending on what the prev-child // is, we either want to add // the new super and subscripts // to it (if it's `attach`), or // take it as a base to attach // our super and subscripts to. if prev-child.func()==math.attach { let prev-fields = prev-child.fields() let prev-base = prev-fields.remove("base") let prev-t = prev-fields.remove("t", default: []) let prev-b = prev-fields.remove("b", default: []) let new-t = prev-t + head-baseline.t let new-b = prev-b + head-baseline.b if (new-t!=[]) {prev-fields.insert("t", new-t)} if (new-b!=[]) {prev-fields.insert("b", new-b)} prev-child = math.attach(prev-base, ..prev-fields) } else { // The previous content is not math.attach, // so create a new attachment with the // previous content as a base. head-baseline = clean-baseline(head-baseline) prev-child = math.attach(prev-child, ..head-baseline) } } } // What's left over now is an array // we want to join over: // Baseline could still have length 1, even // if it had matches, because the first match // might have been absorbed into the // previous content. if (baseline-arr.len()<=1) { // prev-child is now guaranteed to // not be `none` let final-str = baseline-arr.at(0) if (final-str.len()>0) { return (prev-child, [#final-str]) } else { return (prev-child,) } } // Initial setup, because arrays can't // be empty (?), so we have to // distinguish the cases between // prev-child being `none` or not. let result-arr let new-attach0 = attachy( baseline-arr.at(0), baseline-arr.at(1) ) if (prev-child!=none) { result-arr = (prev-child,new-attach0) } else { result-arr = (new-attach0,) } let baseline-ix = 2 let iter-max = baseline-arr.len()-1 while baseline-ix < iter-max { let new-attach = attachy( baseline-arr.at(baseline-ix), baseline-arr.at(baseline-ix+1) ) result-arr.push(new-attach) baseline-ix += 2 } // At last, take care of the // final string: let final-str = baseline-arr.at(baseline-ix) if final-str.len()>0 { result-arr.push([#final-str]) } return result-arr } } // The function to convert a given sequence. #let convert-sequence(seq) = { let is-sequence = type(seq) == content and seq.func() == sequence if not is-sequence { return seq } let children = seq.children if children.len() == 0 { return seq } let children-ix = 0 while children-ix < children.len() { let child = children.at(children-ix) if (child.func()!=text) { children-ix += 1 } else { // Look backwards for the first // content that's not a space // and assign that to prev-child. // Assign `none` if there is none. let prev-child-ix = children-ix - 1 while (prev-child-ix>=0 and children.at(prev-child-ix).func() == space) { prev-child-ix -= 1 } let prev-child if (prev-child-ix>=0) { prev-child = children.at(prev-child-ix) } else { prev-child = none } if prev-child!=none {let ugh = prev-child.func()} let new-sequence = process-prev-child-and-text-child(prev-child, child) if (new-sequence==none) { children-ix += 1 } else { let init = children.slice(0, calc.max(0,prev-child-ix)) let tail = children.slice(children-ix+1) children = init + new-sequence + tail children-ix = init.len() + new-sequence.len() } } } return children.join() } // Define the `eq`-function, which works // just like math.equation, except // it inserts a space before every // super- or subscript-character, to // avoid "unknown variable" errors. #let whitespace-regex = regex("\\s+") #let eq-string(string, ..args) = { let replaced-string = string.replace( exactly-one-super-or-sub-regex, match=> " " + match.text ).trim(whitespace-regex) let mathy = eval(replaced-string, mode: "math") // yuck return math.equation(mathy.body, ..args) } #let eq(raw, ..args) = { assert(type(raw)!=content or raw.func()!=raw, message: "eq needs to be passed `raw` content") if raw.block { return eq-string(raw.text, block: true, ..args) } else { return eq-string(raw.text, block: false, ..args) } } #let super-subscripts(body) = { show raw.where(lang: "eq"): raw => { set text(size: 1.25em) eq(raw) } show math.equation: eq => { show sequence: seq => { let new = convert-sequence(seq) if seq!=new { new } else { seq } } if (type(eq.body)!=content or eq.body.func()!=text) { eq } else { // This is a crude patch to allow at // least $35²²$ to render like $35^22$. let fields = eq.fields() let body = fields.remove("body") let new-body = process-prev-child-and-text-child(none, body) math.equation(sequence(new-body), ..fields) } } body }
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/docs/manual.typ
typst
MIT License
#import "../src/book.typ": * #import "@preview/subpar:0.1.1" #import "./manual-template.typ": * #show: manual-template.with( abstract : [Ce package Typst est une proposition de modèle pour la rédaction de mémoire thèse ou de HDR pour les personnels du Laboratoire de Mécanique des Structures et des Systèmes Couplés du Conservatoire National des Arts et Métiers.], version: "Template 0.3.0", typst-version: "Typst 0.11.1" ) = Qu'est-ce que Typst ? #typst est un nouveau langage de balise open source é crit en Rust et développé à partir de 2019 par deux étudiants allemands, <NAME> et <NAME>, dans le cadre de leur projet de master @Mad22 @Hau22. La version 0.1.0 a été publiée sur GitHub le 04 avril 2023#footnote[Adresse du dépôt GitHub : #link("https://github.com/typst/typst", text("https://github.com/typst/typst", fill: typst-color))]. #typst se présente comme un successeur de #LaTeX plus moderne, rapide et simple d'utilisation. Parmi ses avantages, on peut citer : - la compilation incrémentale ; - des messages d'erreur clair et compréhensible ; - un langage de programmation Turing-complet ; - une système de style cohérent permettant de configurer aisément tous les aspects de son document (police, pagination, marges, #sym.dots) ; - une communauté active et sympathique (serveur Discord pour le support, annonce de nouveaux paquets) ; - un système de paquets simple d'utilisation (pour rechercher ou voir la liste des paquets, n'hésitez pas à visiter #link("https://typst.app/universe", text("Typst: Universe", fill: typst-color))) ; - des extensions pour VS Code existent, comme `Typst LSP` ou `Tinymist`, pour avoir des fonctionnalités similaires à `LaTeX Workshop`. #v(0.5em) Pour finir, la documentation de #typst est suffisamment bien écrite et détaillée pour permettre de créer rapidement ses propres documents. Il faut compter moins d'une heure pour prendre en main la syntaxe (sans mentir #emoji.face.beam). Pour accéder à la documentation, suivez ce #link("https://typst.app/docs", text("lien", fill: typst-color)). Pour faciliter la transition de #LaTeX vers #typst, un guide est disponible #link("https://typst.app/docs/guides/guide-for-latex-users/", text("ici", fill: typst-color)). = Illustrations Avant de décrire plus en détail les principaux éléments du modèle, voici quelques images illustrant le rendu du modèle. #subpar.grid( gap: 1em, figure(image("manual-images/page_garde.png", width: 60%), caption: [Page de garde]), figure(image("manual-images/back-cover.png", width: 60%), caption: [Quatrième de ouverture]), figure(image("manual-images/page-chapitre.png", width: 60%), caption: [Introduction d'un chapitre]), figure(image("manual-images/page-chapitre-section.png", width: 60%), caption: [Section d'un chapitre]), columns: (1fr, 1fr), caption: [Illustrations du rendu du modèle] ) // #figure( // grid(columns: 2, column-gutter: 0em, row-gutter: 1em, // subfigure(image("manual-images/page_garde.png", width: 60%), caption: [Page de garde]), // subfigure(image("manual-images/back-cover.png", width: 60%), caption: [Quatrième de ouverture]), // subfigure(image("manual-images/page-chapitre.png", width: 60%), caption: [Introduction d'un chapitre]), // subfigure(image("manual-images/page-chapitre-section.png", width: 60%), caption: [Section d'un chapitre]) // ), // caption: [Illustrations du rendu du modèle], // ) #pagebreak() = Utilisation Pour utiliser le modèle, il faut l'importer dans votre fichier principal `typ` en utilisant la commande suivante. #codesnippet[ ```typ #import "./src/book.typ": * ``` ] #ibox[ #set text(size: 11pt) Si vous décomposez votre document en différents fichiers, il faut insérer la commande précédente en préambule de chaque fichier. ] == Initilisation du modèle Après avoir importé le modèle, celui doit être initialisé en appliquant une règle d'affichage (`show` rule) avec la commande #cmd("book") en passant les options nécessaires avec l'instruction `with` dans votre fichier principal `typ` : #codesnippet( ```typ #show book.with( ... ) ``` ) Le modèle #cmd("book") possède un certain nombre de paramètres permettant de personnaliser le document. Voici la liste des paramètres disponibles : #command("book", ..args( title: "Titre de la thèse", author: "<NAME>", type: "these", school: "Conservatoire National des Arts et Métiers", doctoral-school: "Sciences des Métiers de l'Ingénieur", supervisor: ("Nom du directeur de thèse",), cosupervisor: none, laboratory: "Nom du laboratoire", defense-date: "01 janvier 1970", discipline: "Mécanique, Génie Mécanique, Génie Civil", speciality: "Mécanique", commity: (), lang: "fr", logo: "assets/logo_cnam.png", body-font: "Lato", math-font: "Lete Sans Math", [body]))[ #argument("title", default: "Titre de la thèse", types: "string")[Titre du mémoire de thèse ou de HDR.] #colbreak() #argument("author", default: "Nom du candidat", types: "string")[Nom de l'auteur du mémoire.] #argument("type", default: "these", types: "string")[Type de document (these, hdr). Le type du document figurant sur la page de garde sera adapté à la valeur prise par ce paramètre. #h(1em) Si #arg("type"): \"these\", le document sera intitulé _Thèse de doctorat_. #h(1em) Si #arg("type"): \"hdr\", le document sera intitulé _Habilitation à Diriger des Recherches_. ] #argument("school", default: "Conservatoire National des Arts et Métiers", types: "string")[Nom de l'établissement de préparation du mémoire.] #argument("doctoral-school", default: "Sciences des Métiers de l'Ingénieur", types: "string")[Nom de l'école doctorale de rattachement du candidat.] #argument("supervisor", default: ("Nom du directeur de thèse",), types: "array")[Nom du/des directeurs de thèse ou du garant de la HDR. Chaque élément de la liste est de type #dtype("string").] #argument("cosupervisor", default: none, types: "array")[Nom du ou des co-encadrants de thèse. Chaque élément de la liste est de type #dtype("string")] #argument("laboratory", default: "Nom du laboratoire", types: "string")[Nom du laboratoire de recherche de rattachement du candidat.] #argument("defense-date", default: "01 janvier 1970", types: "string")[Date de soutenance du mémoire.] #argument("discipline", default: "Mécanique, Génie Mécanique, Génie Civil", types: "string")[Discipline dans laquelle s'inscrit le mémoire.] #argument("speciality", default: "Mécanique", types: "string")[Spécialité dans laquelle s'inscrit mémoire.] #argument("commity", default: (), types: "array")[Liste des membres du jury de soutenance. Chaque membre du jury est défini par un dictionnaire, de type #dtype((:)), contenant les champs suivant : - `name` : Nom du membre du jury - `position` : Poste occupé (MCF, PU, #sym.dots) - `affiliation` : Établissement de rattachement - `role` : Rôle dans le jury (Rapporteur, Examinateur, #sym.dots) #example-box[ ```typc commity: ( ( name: "<NAME>", position: "Professeur des Universités", affiliation: "Streeling university", role: "Rapporteur", ), ( name: "<NAME>", position: "Maître de conférences", affiliation: "Beltegeuse University", role: "Examinateur" ), ) ``` ] ] #argument("lang", default: "fr", types: "string")[Langue du document. En fonction de la valeur prise par ce paramètre, la localisation du document sera adaptée. Outre le français, la seule langue prise en compte est l'anglais (`lang: "en"`).] #argument("logo", default: "image(" + "resources/images/logo_cnam.png" + ")", types: "content")[Chemin vers le logo de l'établissement de préparation du mémoire. #wbox[ #set text(size: 11pt) Il faut que le template soit à la racine du répertoire pour que le chemin soit correctement interprété. Dans le cas contraire, une erreur de compilation sera générée. ] ] #argument("body-font", default: "Lato", types: "string")[Nom de la police de caractère du corps du texte.] #colbreak() #argument("math-font", default: "Lete Sans Math", types: "string")[Nom de la police de caractère des équations mathématiques.] #ibox[ #set text(size: 11pt) Les polices de caractère doivent être préalablement installées sur votre système pour être utilisées dans le document. Pour vérifier la disponibilité de la police choisie, vous pouvez entrer la commande `typst font` dans un terminal. ] ] #v(1.5em) == Contenu du mémoire Le contenu du mémoire est à rédiger dans le fichier principal `typ` ou dans des fichiers annexes. Le modèle fournit une structure de base pour la rédaction du mémoire. D'une manière générale, la partie du fichier principal correspondant au contenu du mémoire est structurée de la manière suivante : #codesnippet[ ```typ #show: front-matter #include "front-content.typ" #show: main-matter #tableofcontents() #listoffigures() #listoftables() #include "chapitre.typ" #bibliography("bibliography.bib") #show: appendix #include "appendix.typ" #back-cover(...) ``` ] Le contenu du mémoire est divisé en trois parties principales : `front-matter`, `main-matter` et `appendix`. Ces éléments s'accompagnent de fonctions complémentaires permettant de faciliter la rédaction du mémoire. === Environnements Le modèle propose trois environnements pour structurer le contenu du mémoire : 1. *front-matter* : environnement pour le contenu préliminaire du mémoire (page de garde, résumé, remerciements, #sym.dots). En terme de pagination, les pages sont numérotées en chiffres romains et les chapitres ne sont pas numérotés. Pour activer cet environnement, il faut insérer dans le fichier principal `typ` à l'endroit souhaité la commande suivante : #codesnippet[ ```typ #show: front-matter ``` ] 2. *main-matter* : environnement pour le contenu principal du mémoire (introduction, tables des matières chapitres, conclusion, bibliographie, #sym.dots). Les pages sont numérotées et les chapitres sont numérotés en chiffres arabes. Pour activer cet environnement, il faut insérer dans le fichier principal `typ` à l'endroit souhaité la commande suivante : #codesnippet[ ```typ #show: main-matter ``` ] 3. *appendix* : environnement pour le contenu des annexes du mémoire. Les pages sont numérotées en chiffres romains et les chapitres sont numérotés en lettres. Pour activer cet environnement, il faut insérer dans le fichier principal `typ` à l'endroit souhaité la commande suivante : #codesnippet[ ```typ #show: appendix ``` ] === Chapitre Les chapitres du mémoire sont définis par la fonction #cmd("chapter") qui dispose d'une certain nombre de paramètres permettant d'adapter le rendu du chapitre en fonction du contexte. Voici la liste des paramètres disponibles : #command("chapitre", arg[title], ..args( abstract: none, toc: true, numbered: true, [body], ) )[ #argument("title", types: "string")[Titre du chapitre.] #argument("abstract", default: none, types: "content")[Résumé affiché sous le titre du chapitre.] #argument("toc", default: true, types: "boolean")[Indique si un mini table des matières doit être affichée au début du chapitre.] #argument("numbered", default: true, types: "boolean")[Indique si le chapitre doit être numéroté.] ] #example-box[ ```typ #chapitre( "Introduction", abstract: [Résumé du chapitre], toc: true, numbered: true )[...] ``` ] === Bibliographie Pour insérer une bibliographie, il faut insérer dans le fichier principal `typ` la commande suivante : #codesnippet[ ```typ #bibliography("your-biblio-file.yml/bib") ``` ] #ibox[ #set text(size: 11pt) Le modèle propose deux formats de bibliographie : YAML et BibTeX. Pour le fichier YAML, celui-ci est interprété par le module `hayagriva`, dont la documentation est disponible #link("https://github.com/typst/hayagriva/blob/main/docs/file-format.md", text("ici", fill: typst-color.darken(10%))). ] Pour citer une référence bibliographique dans le texte, il suffit d'utiliser la commande #cmd("cite", arg[key]) ou plus simplement #text(`@key`, fill: typst-color) (où `key` est la clé associée à la référence). Pour plus d'informations sur la gestion des références bibliographiques, il faut se référer à la documentation de la fonction #cmd("bibliography") de #typst (accessible #link("https://typst.app/docs/reference/model/bibliography/", text("ici", fill: typst-color))). === Fonctions complémentaires Cette section présente les fonctions complémentaires implémentées dans le modèle pour faciliter la rédaction du mémoire. *Tables des matières* - #cmd-["tableofcontents"] : création la table des matières. - #cmd-["listoffigures"] : création la table des figures. - #cmd-["listoftables"] : création la table des tableaux. *Figures* D'une manière générale, les figures sont insérées dans le document à l'aide de la fonction #cmd("figure") de #typst. Cependant, #typst ne dispose pas actuellement de mécanismes permettant de gérer les sous-figures (numérotation et référencement). Pour pallier ce manque, le modèle intègre une fonction #cmd("subfigure") permettant de gérer les sous-figures de manière adaptée. Cette fonction encapsule la fonction #cmd("subpar.grid") du package `subpar`. #pagebreak() #example-box[ ```typ #subfigure( figure(image("image1.png"), caption: []), figure(image("image2.png"), caption: []), <b>, columns: (1fr, 1fr), caption: [Titre de la figure], label: <fig:subfig>, ) ``` L'exemple précédent illustre le cas d'une figure composée de deux sous-figures. La première sous-figure est accompagnée d'une légende, tandis que la seconde possède un #dtype("label") mais pas de titre. La seconde sous-figure peut ainsi être référencée dans le texte à l'aide de la commande #text(`@b`, fill: typst-color.darken(15%)). ] *Équations* Pour encadrer une équation importante, la fonction #cmd("boxeq") doit être utilisée. #example-box[ #set math.equation(numbering: "(1)") #show math.equation: set text(font: "Lete Sans Math", fallback: false) ```typ $ #boxeq[$p(A|B) prop p(B|A) space p(A)$] $ ``` #align(center)[#line(stroke: 1pt + typst-color, length: 95%)] $ #boxeq[$p(A|B) prop p(B|A) space p(A)$] $ ] Pour créer une équation sans numérotation, il faut utiliser la fonction #cmd("nonumeq"). #example-box[ #show math.equation: set text(font: "Lete Sans Math") ```typ #nonumeq[$integral_0^1 f(x) dif x = F(1) - F(0)$] ``` #align(center)[#line(stroke: 1pt + typst-color, length: 95%)] #nonumeq[$ integral_0^1 f(x) dif x = F(1) - F(0) $] ] *Quatrième de couverture* La quatrième de couverture de la thèse est générée automatiquement à partir de la fonction #cmd("back-cover"), qui affiche les informations relatives à la thèse (titre et auteur), ainsi qu'un résumé en français et en anglais. #command("back-cover", ..args( resume: none, abstract: none ))[ #argument("resume", types: "content")[Résumé de la thèse en français.] #argument("abstract", types: "content")[Résumé de la thèse en anglais.] ] #v(1.5em) = Paquets recommandés Cette section présente une liste de paquets qui peuvent être pertinents lors de la rédaction d'un mémoire en #typst. *Dessin* -- `CeTZ` - *Description* : Ce paquet se veut être un équivalent #typst de TiKZ pour #LaTeX. - *Liens* - #link("https://typst.app/universe/package/cetz", text("Typst: Universe", fill: typst-color)), #link("https://github.com/cetz-package/cetz", text("dépôt GitHub", fill: typst-color)) et #link("https://github.com/cetz-package/cetz/blob/stable/manual.pdf?raw=true", text("documentation", fill: typst-color)). #v(0.5em) *Boîtes* -- `showybox` - *Description* : Ce paquet permet de créer des boîtes de contenus (textes, #sym.dots) personnalisables. - *Liens* - #link("https://typst.app/universe/package/showybox", text("Typst: Universe", fill: typst-color)), #link("https://github.com/Pablo-Gonzalez-Calderon/showybox-package", text("dépôt GitHub", fill: typst-color)) et #link("https://github.com/Pablo-Gonzalez-Calderon/showybox-package/blob/main/Showybox's%20Manual.pdf", text("documentation", fill: typst-color)). #v(0.5em) *Code* -- `codelst` - *Description* : Ce paquet permet de formatter des blocs de code source en incluant notamment la numérotation des lignes. - *Liens* #link("https://typst.app/universe/package/codelst", text("Typst: Universe", fill: typst-color)), #link("https://github.com/jneug/typst-codelst", text("dépôt GitHub", fill: typst-color)) et #link("https://github.com/jneug/typst-codelst/blob/main/manual.pdf", text("documentation", fill: typst-color)). #v(0.5em) *Algorithme* -- `lovelace` - *Description* : Ce paquet permet d'écrire du pseudo-code, dont le formattage est personnalisable. - *Liens* - #link("https://typst.app/universe/package/lovelace", text("Typst: Universe", fill: typst-color)), #link("https://github.com/andreasKroepelin/lovelace", text("dépôt GitHub", fill: typst-color)) et documentation (voir ReadMe sur GitHub). #v(0.5em) *Mathématiques* - `physica` - *Description* : Ce paquet propose des raccourcis pour l'écriture de symboles mathématiques. - *Liens* - #link("https://typst.app/universe/package/physica", text("Typst: Universe", fill: typst-color)), #link("https://github.com/Leedehai/typst-physics", text("dépôt GitHub", fill: typst-color)) et #link("https://github.com/Leedehai/typst-physics/blob/v0.9.3/physica-manual.pdf", text("documentation", fill: typst-color)). #v(0.5em) *Glossaire* - `glossarium` - *Description* : Ce paquet permet de créer un glossaire. - *Liens* - #link("https://typst.app/universe/package/glossarium", text("Typst: Universe", fill: typst-color)), #link("https://github.com/ENIB-Community/glossarium", text("dépôt GitHub", fill: typst-color)) et #link("https://github.com/ENIB-Community/glossarium/blob/master/docs/main.pdf", text("documentation", fill: typst-color)). #v(0.5em) *Index* - `in-dexter` - *Description* : Ce paquet permet de créer aisément un index. - *Liens* : #link("https://typst.app/universe/package/in-dexter", text("Typst: Universe", fill: typst-color)), #link("https://github.com/RolfBremer/in-dexter", text("dépôt GitHub", fill: typst-color)) et #link("https://github.com/RolfBremer/in-dexter/blob/main/sample-usage.pdf", text("documentation", fill: typst-color)). = Feuille de route Le modèle est en cours de développement. Voici la liste des fonctionnalités qui sont implémentées ou le seront dans une prochaine version. *Couvertures* - [x] Page de garde - [x] Quatrième de couverture #pagebreak() *Environnements* - [x] Création de l'environnement `front-matter` - [x] Création de l'environnement `main-matter` - [x] Création de l'environnement `appendix` *Tables des matières* - [x] Création de la table des matières -- #cmd-["tableofcontents"] - [x] Création de la table des figures -- #cmd-["listoffigures"] - [x] Création de la table des tableaux -- #cmd-["listoftables"] - [x] Création d'une mini table des matières en début de chapitre grâce au paquet `minitoc` (voir #link("https://typst.app/universe/package/minitoc", text("lien", fill: typst-color))) - [x] Personnalisation des entrées (apparence, lien hypertexte) en modifiant l'élément `outline.entry` - [x] Localisation des différentes tables *Figures et tableaux* - [x] Personnalisation de l'apparence des légendes des figures et des tableaux en fonction du contexte (chapitre ou annexe) - [x] Titres courts pour les tables des figures et des tableaux - [x] Création de la fonction #cmd-["subfigure"] pour les sous-figures - [x] Référencement automatique des sous-figures via la modification de la fonction Typst #cmd-["ref"] - [x] Recréation des liens hypertextes pour les sous-figures pour la navigation dans le document via la fonction Typst #cmd-["link"] *Équations* - [x] Adaptation de la numérotation des équations en fonction du contexte (chapitre ou annexe) - [x] Création d'une fonction pour encadrer les équations importante -- #cmd-["boxeq"] - [x] Création d'une fonction définir des équations sans numérotation -- #cmd-["nonumeq"] - [ ] Numérotation des équations d'un système de type (1.1a) -- _Discussions en cours sur le dépôt Github de Typst_ // *Liens* // - [ ] Personnalisation plus poussée des liens hypertextes (couleur, style, #sym.dots) ? *Bibliographie* - [x] Vérification de la liste des références via `bibtex` - [x] Idem pour `hayagriva` (voir #link("https://github.com/typst/hayagriva/blob/main/docs/file-format.md", text("documentation", fill: typst-color))) #bibliography("manual-biblio.yml", style: "american-institute-of-aeronautics-and-astronautics")
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/themes/metropolis.md
markdown
--- sidebar_position: 2 --- # Metropolis Theme ![image](https://github.com/touying-typ/touying/assets/34951714/a1b34b11-6797-42fd-b50f-477a0d672ba2) This theme is inspired by the [Metropolis beamer](https://github.com/matze/mtheme) theme created by <NAME> and transformed by [Enivex](https://github.com/Enivex). The Metropolis theme is elegant and suitable for daily use. For the best results, it is recommended to install the Fira Sans and Fira Math fonts on your computer. ## Initialization You can initialize the Metropolis theme using the following code: ```typst #import "@preview/touying:0.2.1": * #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: self => self.info.institution) #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, slides, title-slide, new-section-slide, focus-slide, touying-outline, alert) = utils.methods(s) #show: init #show strong: alert ``` The `register` function takes parameters such as: - `aspect-ratio`: The aspect ratio of the slides, either "16-9" or "4-3," with the default being "16-9." - `header`: Content to be displayed in the header, with the default being `states.current-section-title`. You can also pass a function like `self => self.info.title`. - `footer`: Content to be displayed in the footer, with the default being `[]`. You can also pass a function like `self => self.info.author`. - `footer-right`: Content to be displayed on the right side of the footer, with the default being `states.slide-counter.display() + " / " + states.last-slide-number`. - `footer-progress`: Whether to show the progress bar at the bottom of the slide, with the default being `true`. The Metropolis theme also provides an `#alert[..]` function that you can use with the `#show strong: alert` syntax. ## Color Themes Metropolis uses the following default color theme: ```typst #let s = (s.methods.colors)( self: s, neutral-lightest: rgb("#fafafa"), primary-dark: rgb("#23373b"), secondary-light: rgb("#eb811b"), secondary-lighter: rgb("#d6c6b7"), ) ``` You can modify the color theme using `#let s = (s.methods.colors)(self: s, ..)`. ## Slide Function Family Metropolis theme provides a series of custom slide functions: ```typst #title-slide(extra: none, ..args) ``` The `title-slide` reads information from `self.info` for display. You can also pass an `extra` parameter to display additional information. --- ```typst #slide( repeat: auto, setting: body => body, composer: utils.side-by-side, section: none, subsection: none, // metropolis theme title: auto, footer: auto, align: horizon, margin: (top: 3em, bottom: 1em, left: 0em, right: 0em), padding: 2em, )[ ... ] ``` This is the default ordinary slide function with a title and footer according to your settings. The `title` is set to the current section title by default, and the footer is as per your settings. --- ```typst #focus-slide[ ... ] ``` Used to draw attention. The background color is `self.colors.primary-dark`. --- ```typst #new-section-slide(short-title: auto, title) ``` Opens a new section with the given title. ## `slides` Function The `slides` function has parameters: - `title-slide`: Default is `true`. - `outline-slide`: Default is `true`. - `outline-title`: Default is `[Table of contents]`. You can set these using `#show: slides.with(..)`. ```typst #import "@preview/touying:0.2.1": * #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: self => self.info.institution) #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, slides, title-slide, new-section-slide, focus-slide, touying-outline, alert) = utils.methods(s) #show: init #show strong: alert #show: slides = Title == First Slide Hello, Touying! #pause Hello, Typst! ``` ![image](https://github.com/touying-typ/touying/assets/34951714/4ab45ee6-09f7-498b-b349-e889d6e42e3e) ## Example ```typst #import "@preview/touying:0.2.1": * #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: self => self.info.institution) #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, title-slide, new-section-slide, focus-slide, touying-outline, alert) = utils.methods(s) #show: init #show strong: alert #title-slide(extra: [Extra]) #slide(title: [Table of contents])[ #touying-outline() ] #slide(title: [A long long long long long long long long long long long long long long long long long long long long long long long long Title])[ A slide with some maths: $ x_(n+1) = (x_n + a/x_n) / 2 $ #lorem(200) ] #new-section-slide[First section] #slide[ A slide without a title but with *important* infos ] #new-section-slide[Second section] #focus-slide[ Wake up! ] // simple animations #slide[ a simple #pause dynamic slide with #alert[alert] #pause text. ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide, new-section-slide) = utils.methods(s) #new-section-slide[Appendix] #slide[ appendix ] ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/renderer/vue3.typ
typst
Apache License 2.0
#import "/docs/cookery/book.typ": book-page #show: book-page.with(title: "Compiler Service") = Compiler Service Use `@myriaddreamin/typst.vue3` Coming soon.
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/布局/page/page.typ
typst
#image("屏幕截图 2024-04-16 162446.png") #image("屏幕截图 2024-04-16 162559.png") #image("屏幕截图 2024-04-16 162633.png") #image("屏幕截图 2024-04-16 162705.png") #image("屏幕截图 2024-04-16 164242.png") #image("屏幕截图 2024-04-16 164333.png") #image("屏幕截图 2024-04-16 164420.png") #image("屏幕截图 2024-04-16 164451.png") #image("屏幕截图 2024-04-16 164528.png") #image("屏幕截图 2024-04-16 164556.png") #image("屏幕截图 2024-04-16 164625.png")
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/spue/anforderungen/erfolgreicher_unterricht.typ
typst
Other
#import "/src/template.typ": * == #ix("Erfolgreicher Unterricht", "Unterricht, erfolgreich") Unterricht in der Philosophie ist _problem_-#ix([], "Problemorientierung") und _kompetenzorientiert_#ix([], "Kompetenz"). Allgemeine Ziele des Unterrichts sind die Ausbildung von Kompetenzen, ein grundlegender Strukturgeber dabei ist die #box[#ix("Problemorientierung"),] die den Lernweg anhand von Problemen entfaltet. #ix("Erfolgreicher Unterricht", "Unterricht, erfolgreich") ist derjenige, der seine Ziele erreicht. Stellen Sie sich daher folgende Fragen: #orange-list-with-body[*Welche Ziele sollen erreicht werden?*][ Orientieren Sie sich an den Anforderungen zur #ix("Zielorientierung"). Ziele (in Kombination mit der #ix("Kompetenzorientierung")) benennen Komptenzen und werden #ix("operationalisiert", "Operator"). Der Unterricht sollte auf allen drei #ix("Anforderungsbereichen", "Anforderungsbereich") stattfinden, wobei man eigentlich erst beim Betreten des AFB III vom eigentlichen Philosophieren sprechen kann. Das Ziel des Philosophieunterrichts ist das Philosophieren, ohne einen AFB III ist fraglich, wie philosophische Reflexionsfähigkeiten ausgebildet werden sollen. Gleichzeitig kann der Unterricht nicht nur im AFB III stattfinden, da dies nicht mit der #ix("Heterogenität der SuS") zusammenpasst. *Bsp.:* Die SuS erlangen Sachkompetenz, indem Sie die drei Schritte von Descartes methodischem Zweifel je einem Beispiel zuordnen. ][*Wie weisen Sie nach, dass Sie die Ziele im Unterricht erreicht haben?*][ Machen Sie im Unterricht die Aufgaben, die Sie in den Zielen #ix("operationalisiert", "Operator") haben. Das erfolgreiche Bearbeiten der Aufgaben entspricht einem Nachweis über die erreichten Ziele. *Bsp.:* Im Unterricht wurde eine Aufgabe mit der Formulierung "Ordnen Sie die drei Schritte Descartes dem jeweiligen Beispiel zu!" bearbeitet. ][*Wie ist die erlangte Kompetenz nachweisbar?*][ #ix("Kompetenzen", "Kompetenz") sind nicht messbar, sondern nur die Leistung, die die SuS in einer konkreten Situation erbringen, die sogenannte _#ix("Performanz")_. Trotzdem können Sie Situationen angeben, in denen die erlangte Kompetenz hilfreich zur Lösung des Problems ist. *Bsp.:* Die erlangte Sachkompetenz hilft, wenn die SuS die drei Schritte von Descartes methodischem Zweifel je einem neuen Beispiel zuordnen müssen. ]
https://github.com/jimvdl/typven
https://raw.githubusercontent.com/jimvdl/typven/master/README.md
markdown
Apache License 2.0
`typven` is a command-line interface for vendoring local Typst packages. Its core job is to take local packages that are not shared through [Typst's package management] and place them in the designated local Typst package directory to make them available system-wide. For more information see the Typst [packages] repository. ## Installation Typven's CLI is only available from the [releases page] where you can get sources and pre-built binaries for the latest release of typven. ## Usage Installs packages in the [local system directory](#package-directory). It will either install a top-level package or recursively search the next two subdirectories for packages and install each valid one. ```sh # Install package(s) from the current working directory typven install # Install package(s) from a given directory typven install A:/GitHub/my-packages # Install package(s) from a repository typven install --git https://github.com/jimvdl/typven.git ``` Viewing the installed packages can be done by running `ls`, this will output every package with all of their versions. ```sh # List installed packages in table format typven ls ``` If you want to clean packages from your system the `clean` subcommand can either clean the whole directory entirely or target a specific package by either name or a combination of a name and version. ```sh # Clean all packages typven clean # Clean a specific package typven clean mypkg # Clean a spefic version for a given package typven clean mypkg 0.2.5 ``` ## Package directory Packages are stored in `{data-dir}/typst/packages/{namespace}/{name}/{version}` to make them available locally on your system. Here, `{data-dir}` is: - `$XDG_DATA_HOME` or `~/.local/share` on Linux. - `~/Library/Application Support` on macOS. - `%APPDATA%` on Windows. Packages in the data directory have precedence over ones in the cache directory. While you can create arbitrary namespaces with folders, the namespace typven uses is `local`: - Stores a package in `~/.local/share/typst/packages/local/mypkg/1.0.0` - Import from it with `#import "@local/mypkg:1.0.0": *` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [packages]: https://github.com/typst/packages [Typst's package management]: https://typst.app/docs/packages/ [releases page]: https://github.com/jimvdl/typven/releases
https://github.com/fenjalien/cirCeTZ
https://raw.githubusercontent.com/fenjalien/cirCeTZ/main/parts.typ
typst
Apache License 2.0
#import "../typst-canvas/draw.typ": * #import "utils.typ": anchors #let and-gate-body = { merge-path(close: true, { arc((0,0), -90deg, 90deg, radius: 0.5, name: "curve", anchor: "origin") line( (0, 0.5), (-0.5, 0.5), (-0.5, -0.5) ) }) anchors(( "bin 1": (-0.5, 0.25), "in 1": (rel: (-0.5, 0)), "bin 2": (-0.5, -0.25), "in 2": (rel: (-0.5, 0)), "bout": (0.5, 0), "out": (rel: (0.5, 0)), "north": (0, 0.5), "south": (rel: (0, -1)), "east": "out", "west": ("in 1", "|-", "center"), "left": ("bin 1", "|-", "center"), "right": "bout" )) } #let or-gate-body = { merge-path(close: true, { arc((0.5, 0), -90deg, -30deg, anchor: "end", name: "bcurve") arc((0.5,0), 30deg, 90deg, anchor: "start", name: "tcurve") line("tcurve.end", (-0.5, 0.5)) arc((), -30deg, 30deg, anchor: "end") }) // x coordinate of where the input legs touch the body of the gate let x = calc.cos(calc.asin(0.25)) - calc.cos(calc.asin(0.5)) - 0.5 anchors(( "bin 1": (x, 0.25), "in 1": (-1, 0.25), "bin 2": (x, -0.25), "in 2": (-1, -0.25), "bout": (0.5, 0), "out": (rel: (0.5, 0)), "north": (0, 0.5), "south": (rel: (0, -1)), "east": "out", "west": ("in 1", "|-", "center"), "left": ("bin 1", "|-", "center"), "right": "bout" )) } #let not-circle = { circle((rel: (0.1, 0), to: "bout"), radius: 0.1) anchors(( "N-not": (), "body right": "bout", "bout": (rel: (0.2, 0)), "right": "bout" )) } #let xor-bar = { arc((-0.6, -0.5), -30deg, 30deg) anchors(( "ibin 1": "bin 1", "ibin 2": "bin 2", "bin 1": (rel: (-0.1, 0), to: "bin 1"), "bin 2": (rel: (-0.1, 0), to: "bin 2"), "body left": "left", "left": (rel: (-0.1, 0), to: "left") )) } #let logic-gate-legs = for a in ("in 1", "in 2", "out") { line("b" + a, a) }
https://github.com/spidersouris/touying-unistra-pristine
https://raw.githubusercontent.com/spidersouris/touying-unistra-pristine/main/CHANGELOG.md
markdown
MIT License
# v1.1.0 (2024-10-16) ## General - Updated to Touying 0.5.3. ### Slides - **Hero Slides**: - Added the following parameters: `fill`, `inset`, `footnote`. - `fill` (color): allows to fill the entire slide with a color. It can be used to achieve a better result if an image with a fixed background color different from the default one does not properly cover the entire slide, leaving some parts of the default background color visible. - `inset` (length): allows to specify the negative inset value for the image to take the most space possible on the slide. - `footnote` (bool): allows to specify whether there is a footnote. If true, gives some width to accommodate the footnote. Experimental feature. Default: false. - Removed the following parameters: `img-height`, `img-width`, `text-fill`, `text-alignment`, `enhanced-text`. - The `txt` parameter, used to show text next to the image, is now a dictionary accepting the following optional keys: `text`, `enhanced`, `fill`, `align`. - `text` (str): the text to display. Default: none. - `enhanced` (bool | function): whether to enhance the text. Can pass a custom function that will act as a callback to enhance the text. Default: true. - `fill` (color): the fill color of the text. Default: none. - `align` (alignment): the alignment of the text. Default: horizon + center. ### Colors - Added all the colors from the [official color palette of the University of Strasbourg](https://langagevisuel.unistra.fr/index.php?id=396) to `colors.typ`. - Every color is defined as a dictionary with its different shades as keys (A: dark (_foncée_), B: vivid (_vive_), C: pale (_layette_), D: light (_claire_), E: Web colors (_Web_)). - The following colors and their shades are included: `grey`, `maroon`, `brown`, `orange`, `red`, `pink`, `purple`, `violet`, `nblue`, `cyan`, `ngreen`, `green`, `camo`, `yellow`. - Example use: `grey.A` for the dark shade of grey, `maroon.B` for the vivid shade of maroon, etc. - Standard colors `black`, `white`, and `link-color` remain available without dictionary use. - Added the following colorthemes: `forest`, `berry`, `ocean`, `lavender`, `moss`, `clay`, `mint`, `lemon`, `wine`. ## Fixes - The image on hero slides now takes double the space of the text box width on the main axis (LTR, RTL) when text is provided. - Increased font size from 22pt to 25pt. - Fixed template title slide missing logo. - Fixed outdated `title-slide` function docstring. - Fixed logo in footer not positioning correctly. - Fixed other footer positioning issues. # v1.0.0 (2024-09-18) Initial release for publication as a Typst template package. # v0.2.0 (2024-08-30) ## General ### Slides - **Focus Slides**: - Added counter support. - Added the following parameters: `text_alignment`, `show_counter`. - Added the following parameters to `grandientize(): `lighten-pct`, `angle`. - **Title Slides**: - Added the following parameters: `title`, `subtitle`. - **Hero Slides**: - Added support for the following directions: left-to-right (default), right-to-left, up-to-down, down-to-up. - Added caption support. - - Captions can be bolded using `bold_caption: true`. - Added enhanced text option. - Enhanced text appears bigger than normal text, in bold, and close to the image for better visibility. - Enhanced text can have a background using the `text_fill` parameter and specifying a fill color. - Added option to hide footer on individual slides. - Added the following parameters: `bold_caption`, `caption`, `direction`, `enhanced_text`, `gap`, `heading_level`, `hide_footer`, `img_height`, `img_width`, `numbering`, `rows`, `text_alignment`, `text_fill`, `txt`. - **Gallery Slides**: - Added caption support for individual images. - Captions can be bolded using `bold_caption: true`. - Added the following parameters: `captions`, `height`, `gutter`, `subtitle`, `bold_caption`, `heading_level`, `width`, `gap`. ### Admonitions - Added "Brainstorming" admonition type. - Added "Question" admonition type. - Added option to enable or disable admonition numbering (default: false). - Added localization support. ### Settings - Added the following settings: - ADMONITION_NUMBERING (default: false), - DEBUG (default: false), - FOOTER_LOWER_SEP (footer lower separator) (default: " | "), - FOOTER_SHOW_SUBTITLE - FOOTER_UPPER_SEP (footer upper separator) (default: " | "), - LANGUAGE (used for [Typst's `text()` lang parameter](https://typst.app/docs/reference/text/text/#parameters-lang)) (default: "fr"), - QUOTES (used to specify left and right quotation mark characters for the "Quote" element) (default: "« ,  »). - Added [wiki page listing settings](https://github.com/spidersouris/typst-unistra-slides/wiki/Settings). ### Other - Updated example with newest changes. - Added a customized version of [`quote`](https://typst.app/docs/reference/model/quote/). - Added the following exportable methods: `smaller`, `smallest`. - `smaller` sets text to 25pt. - `smallest` sets text to 20pt. - Added `link-color` to `colors.typ`. ## Fixes - Fixed aligment issue with `cell()`. - Fixed alignment issue with `focus-slide()`. - Improved `focus-slide()` theme-related error messages. ## Miscellaneous - Added licence. # v0.1.0 (2024-08-05) Initial pre-release.
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/layouts/doc.typ
typst
MIT License
// 文稿设置,可以进行一些像页面边距这类的全局设置 #let doc( // documentclass 传入参数 info: (:), // 其他参数 fallback: false, // 字体缺失时使用 fallback,不显示豆腐块 lang: "zh", margin: (x: 89pt), it, ) = { // 1. 默认参数 info = ( title: ("基于 Typst 的大学学位论文"), author: "张三", ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if type(info.title) == str { info.title = info.title.split("\n") } // 3. 基本的样式设置 set text(fallback: fallback, lang: lang) set page(margin:(top:3cm,bottom:2.5cm,left:2.8cm,right:2.5cm)) //双面需求可改 inside:2.8cm,outside:2.5cm // 4. PDF 元信息 set document( title: (("",)+ info.title).sum(), author: info.author, ) it }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/ref_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set heading(numbering: "1.") = Introduction <intro> See @setup. == Setup <setup> As seen in @intro, we proceed.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/par-bidi_07.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test whether L1 whitespace resetting destroys stuff. الغالب #h(70pt) ن#" "ة
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/lang_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 19-23 expected string or auto, found none // #set text(script: none)
https://github.com/wenjia03/JSU-Typst-Template
https://raw.githubusercontent.com/wenjia03/JSU-Typst-Template/main/Templates/实验报告(无框)/config/thesisInfo.typ
typst
MIT License
// #let title = "测试" #let name = "测试" #let stuId = "2021402296" #let majorGrade = "2021计算机科学与技术2班" #let guideTeacher = "张三" #let finishTime = "2021年6月" #let experimentName = "实验名称" #let experimentId = 2
https://github.com/gdg-cnu/thumbnail-renderer
https://raw.githubusercontent.com/gdg-cnu/thumbnail-renderer/main/using-typst-app/README.md
markdown
MIT License
# Typst 앱을 이용해 렌더링 ![](./.github/assets/a.png) [Typst 온라인 편집기](https://typst.app/app/)에 접속하고 새 프로젝트를 생성합니다. (회원가입 필요) ![](./.github/assets/b.png) 1. 이 폴더(`/using-typst-app`)에 [gdg-cnu/slide-typst](https://github.com/gdg-cnu/slide-typst)의 `lib` 폴더를 합칩니다. 2. 이 폴더의 내용물을 모두 새 프로젝트에 업로드합니다. \* `main.typ` 파일이 이미 존재하기 때문에 덮어쓸지 묻는 다이얼로그가 나타납니다. Overwrite합니다. ![](./.github/assets/c.png) `#let authors=(` 아래를 수정합니다. - `title`: (`Content`) 대괄호(`[]`) 안은 [typst의 Content 타입](https://typst.app/docs/reference/foundations/content/) 데이터입니다. - 글자의 폰트, 크기, 색상을 수정할 수 있을 뿐 아니라 사진, 표 등 다양한 값을 넣을 수 있지만, 여기서는 개행에 사용됩니다. ```typst [\ // <- \를 끝에 두고 개행하면 실제로 개행됩니다. // <- 두 칸 개행하면 실제로 개행됩니다. ] ``` - `author`: (`String`) 발표자; String 데이터를 받습니다. 큰따옴표(`"`)로 감쌉니다. - `author-meta`: (`String`) 소속을 작성하도록 의도되었습니다. - `author`: (`String`) 이미지 경로를 작성합니다. 만약 경로가 잘못되었다면, 오류와 함께 렌더링되지 않습니다. - `theme`: 열거형처럼 사용됩니다. `ai-data`, `dev`, `devrel`, `game`, 혹은 `theme.slide.theme-color.blue`, `theme.slide.theme-color.red`, `theme.slide.theme-color.green`, `theme.slide.theme-color.yellow` 여야 합니다. ![](./.github/assets/d.png) Typst 앱의 우측 상단 다운로드 버튼의 옵션을 선택하면 PDF가 아닌 PNG로 내보내기할 수 있습니다. 기본 PPI는 72로 설정되므로, 출력하기 전 해상도 설정에 유의해야합니다.
https://github.com/zenor0/FZU-report-typst-template
https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/lib.typ
typst
MIT License
#import "templates/report.typ": report-conf, thanks, appendix
https://github.com/vaucher-leo/template-tb-typst
https://raw.githubusercontent.com/vaucher-leo/template-tb-typst/main/README.md
markdown
MIT License
# template-tb-typst Template de TB en Typst # Usage To use this template, first edit the config.typ file with your informations and change the language in the main.typ if you want it in English. # Compiling ## VS Code To use it in VS Code, just install theses extensions: - Typst LSP (id: nvarner.typst-lsp ) - Typst Preview (id: mgt19937.typst-preview ) With theses extensions, I recommend you to change the settings of Typst LSP to export PDF only on pinned main save and to set the main file to main.typ. To set that, just open the main.typ file, go to the command palette and choose "Pin the main file to the currently oppening document". To get a fast preview and the ability to go from pdf to code, use the Typst preview located on the top right corner. ## Typst website Import all the files in a project on their editor on the website and it works! (Thanks to Florian for testing) # Languages This template is available in 2 languages: French and English. To use one or another version, just change the import in the main.typ file to the correct template with either "FR" or "EN" in it's name.
https://github.com/Mc-Zen/tidy
https://raw.githubusercontent.com/Mc-Zen/tidy/main/src/parse-module.typ
typst
MIT License
#import "tidy-parse.typ" #import "styles.typ" #let resolve-parents(function-docs) = { for i in range(function-docs.len()) { let docs = function-docs.at(i) if not "parent" in docs { continue } let parent = docs.parent if parent == none { continue } let parent-docs = function-docs.find(x => x.name == parent.name) if parent-docs == none { continue } // Inherit args and return types from parent docs.args = parent-docs.args docs.return-types = parent-docs.return-types for (arg, value) in parent.named { assert(arg in docs.args) docs.args.at(arg).default = value } // Maybe strip some positional arguments if parent.pos.len() > 0 { let named-args = docs.args.pairs().filter(((_, info)) => "default" in info) let positional-args = docs.args.pairs().filter(((_, info)) => not "default" in info) assert(parent.pos.len() <= positional-args.len(), message: "Too many positional arguments") positional-args = positional-args.slice(parent.pos.len()) docs.args = (:) for (name, info) in positional-args + named-args { docs.args.insert(name, info) } } function-docs.at(i) = docs } return function-docs } /// Parse the docstrings of a typst module. This function returns a dictionary /// with the keys /// - `name`: The module name as a string. /// - `functions`: A list of function documentations as dictionaries. /// - `label-prefix`: The prefix for internal labels and references. /// The label prefix will automatically be the name of the module if not given /// explicity. /// /// The function documentation dictionaries contain the keys /// - `name`: The function name. /// - `description`: The function's docstring description. /// - `args`: A dictionary of info objects for each function argument. /// /// These again are dictionaries with the keys /// - `description` (optional): The description for the argument. /// - `types` (optional): A list of accepted argument types. /// - `default` (optional): Default value for this argument. /// /// See @@show-module() for outputting the results of this function. /// /// - content (str): Content of `.typ` file to analyze for docstrings. /// - name (str): The name for the module. /// - label-prefix (auto, str): The label-prefix for internal function /// references. If `auto`, the label-prefix name will be the module name. /// - require-all-parameters (boolean): Require that all parameters of a /// functions are documented and fail if some are not. /// - scope (dictionary): A dictionary of definitions that are then available /// in all function and parameter descriptions. /// - preamble (str): Code to prepend to all code snippets shown with `#example()`. /// This can for instance be used to import something from the scope. #let parse-module( content, name: "", label-prefix: auto, require-all-parameters: false, scope: (:), preamble: "", enable-curried-functions: true ) = { if label-prefix == auto { label-prefix = name } let parse-info = ( label-prefix: label-prefix, require-all-parameters: require-all-parameters, ) let module-docstring = tidy-parse.parse-module-docstring(content, parse-info) let matches = content.matches(tidy-parse.docstring-matcher) let function-docs = () let variable-docs = () for match in matches { if content.len() <= match.end or content.at(match.end) != "(" { let doc = tidy-parse.parse-variable-docstring(content, match, parse-info) if enable-curried-functions { let parent-info = tidy-parse.parse-curried-function(content, match.end) if parent-info == none { variable-docs.push(doc) } else { doc.parent = parent-info doc.remove("type") function-docs.push(doc) } } else { variable-docs.push(doc) } } else { let function-doc = tidy-parse.parse-function-docstring(content, match, parse-info) function-docs.push(function-doc) } } if enable-curried-functions { function-docs = resolve-parents(function-docs) } return ( name: name, description: module-docstring, functions: function-docs, variables: variable-docs, label-prefix: label-prefix, scope: scope, preamble: preamble ) }
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/colors.typ
typst
MIT License
#import "catppuccin.typ": * #let theirs = catppuccin.latte.peach #let ours = catppuccin.latte.lavender #let variable = catppuccin.latte.green #let factor = catppuccin.latte.lavender
https://github.com/jamesrswift/chemicoms-paper
https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/tests/example/credit.typ
typst
#let credits = ( concept: [Conceptualization], // Ideas; formulation or evolution of overarching research goals and aims methodology: [Methodology], // Development or design of methodology; creation of models software: [Software], // Programming, software development; designing computer programs; implementation of the computer code and supporting algorithms; testing of existing code components validation: [Validation], // Verification, whether as a part of the activity or separate, of the overall replication/ reproducibility of results/experiments and other research outputs analysis: [Formal analysis], // Application of statistical, mathematical, computational, or other formal techniques to analyze or synthesize study data investigation: [Investigation], // Conducting a research and investigation process, specifically performing the experiments, or data/evidence collection resources: [Resources], // Provision of study materials, reagents, materials, patients, laboratory samples, animals, instrumentation, computing resources, or other analysis tools dataCuration: [Data curation], // Management activities to annotate (produce metadata), scrub data and maintain research data (including software code, where it is necessary for interpreting the data itself) for initial use and later reuse writingDraft: [Writing -- Original Draft], // Preparation, creation and/or presentation of the published work, specifically writing the initial draft (including substantive translation) writingReview: [Writing -- Review #sym.amp Editing], // Preparation, creation and/or presentation of the published work by those from the original research group, specifically critical review, commentary or revision – including pre-or postpublication stages visualization: [Visualization], // Preparation, creation and/or presentation of the published work, specifically visualization/ data presentation supervision: [Supervision], // Oversight and leadership responsibility for the research activity planning and execution, including mentorship external to the core team administration: [Project administration], // Management and coordination responsibility for the research activity planning and execution funding: [Funding acquisition] // Acquisition of the financial support for the project leading to this publication ) #let CRediT( author, ..credits ) = { return [*#author*: #credits.pos().join(", "). ] }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/deco_09.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test strike background #set strike(background: true, stroke: 5pt + red) #strike[This is in the background]
https://github.com/s-ccs/consentform_gh_action
https://raw.githubusercontent.com/s-ccs/consentform_gh_action/main/_extensions/custom/typst-template.typ
typst
// This is an example typst template (based on the default template that ships // with Quarto). It defines a typst function named 'article' which provides // various customization options. This function is called from the // 'typst-show.typ' file (which maps Pandoc metadata function arguments) // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-show.typ' entirely. You can find // documentation on creating typst templates and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #let article( title: none, cols: 2, margin: (left: 20mm, right: 20mm, top: 3cm, bottom: 20mm), paper: "a4", font: ("libertine"), fontsize: 12pt, sectionnumbering: none, toc_title: false, toc_depth:0, doc ) = { set page( paper: paper, margin: margin, numbering: "1", header: align(right)[ #image("unistuttgartlogo.png", width: 40%) ] ) set par(justify: true) set text(font: font, size: fontsize) set heading(numbering: sectionnumbering) show heading.where(level: 1): set align(center) doc }
https://github.com/OrangeX4/typst-tablem
https://raw.githubusercontent.com/OrangeX4/typst-tablem/main/examples/example.typ
typst
MIT License
#import "@preview/tablex:0.0.6": tablex, hlinex #import "../tablem.typ": tablem #set page(width: 30em, height: auto) #tablem[ | *Name* | *Location* | *Height* | *Score* | | ------ | ---------- | -------- | ------- | | John | Second St. | 180 cm | 5 | | Wally | Third Av. | 160 cm | 10 | ] #let three-line-table = tablem.with( render: (columns: auto, ..args) => { tablex( columns: columns, auto-lines: false, align: center + horizon, hlinex(y: 0), hlinex(y: 1), ..args, hlinex(), ) } ) #three-line-table[ | *Name* | *Location* | *Height* | *Score* | | ------ | ---------- | -------- | ------- | | John | Second St. | 180 cm | 5 | | Wally | Third Av. | 160 cm | 10 | ]
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Templates/assignment.typ
typst
#let NumberingAfter(doc) = { let level = 1 set heading( numbering: (..numbers) => if numbers.pos().len() <= level { return numbering("1", ..numbers) }, supplement: "Question", ) show heading: it => { if (it.numbering == none or it.level > 1) { return it } let numbers = counter(heading).at(it.location()) let display-number = numbering(it.numbering, ..numbers) let body = it.body pagebreak(weak: true) block([*#body #display-number*]) } doc }; #let MultiColumnBox(body, height: 26pt, column_number: 3) = { box(height: height)[ #columns(column_number)[ #set par(justify: true) #body ] ] }
https://github.com/sthenic/technogram
https://raw.githubusercontent.com/sthenic/technogram/main/src/document.typ
typst
MIT License
#import "palette.typ": DEFAULT-PALETTE, update-palette, generate-admonition-palette, table-fill, table-stroke #import "metadata.typ": get-metadata, update-metadata #import "raw-links.typ" as _raw-links #import "requirements.typ" as _requirements /* A state that holds the page number where the `backmatter` starts at. We use this to exclude backmatter pages from the total page count. */ #let _page-before-backmatter = state("page-before-backmatter", none) #let _margins = ( right: 2.5cm, left: 2.5cm, top: 110pt, bottom: 79pt, ) /* Header constructor */ #let _header(metadata, logotype) = grid( columns: (auto, 1fr, auto), align: top, logotype, v(42pt), if metadata != none { set text(size: 7pt) grid( columns: 2, gutter: 7pt, align: left, strong("Classification"), strong("Revision"), metadata.classification, metadata.revision, strong("Document ID"), strong("Date"), metadata.document-id, metadata.date, ) }, ) /* Footer constructor (contextual) */ #let _footer(metadata) = context { set text(size: 9pt) let final-page = if _page-before-backmatter.final() != none { _page-before-backmatter.final() } else { counter(page).final().at(0) } grid( columns: (1fr, 1fr, 1fr), align: (left, center, right), grid.cell(colspan: 3)[ #line(length: 100%, stroke: 0.5pt + black) #v(5pt) ], metadata.document-name, link(metadata.url.url)[#metadata.url.label], [Page #counter(page).display("1") of #final-page] ) } #let _title-page(metadata, logotype, palette) = { /* Suppress the footer and remove the header metadata. */ set page( header: _header(none, logotype), footer: none, margin: (.._margins, bottom: _margins.left) ) /* Title and subtitle */ set align(center + top) v(26%) text(size: 26pt, weight: "bold", fill: palette.primary)[#metadata.title] v(5pt) text(size: 16pt, weight: "bold", fill: palette.primary)[#metadata.subtitle] /* Helper to format the author line. */ let format-author = { if type(metadata.author) == array { let label = if metadata.author.len() > 0 { "Authors:" } else { "Author:" } let author = metadata.author.join(", ", last: " and ") (strong(label), author) } else if type(metadata.author) == str { (strong("Author:"), metadata.author) } } /* Metadata typeset in the bottom left corner. */ set align(left + bottom) grid( columns: 2, row-gutter: 7pt, column-gutter: 15pt, align: left, ..format-author, strong("Document ID:"), metadata.document-id, strong("Classification:"), metadata.classification, strong("Revision:"), metadata.revision, strong("Date:"), metadata.date, ) } #let _title-line(metadata, palette) = { grid( columns: (1fr, 1fr), align: (left, right), /* Title on a line of its own. */ grid.cell(colspan: 2)[ #text(size: 22pt, weight: "bold", fill: palette.primary)[#metadata.title] ], /* A horizontal rule to separate. */ grid.cell(colspan: 2, inset: (top: 12pt, bottom: 6pt))[ #line(stroke: 0.4pt, length: 100%) ], /* The subtitle followed by the authors. */ text(size: 14pt, weight: "bold", fill: palette.primary)[#metadata.subtitle], text(size: 12pt)[ #if type(metadata.author) == array { metadata.author.join(", ", last: " and ") } else { metadata.author } ], ) v(2em, weak: true) } /* Outline with custom styling applied in a scope so as not to affect other outlines. */ #let _outline() = { // TODO: The spacing between the heading number and the label is rather small but fine // with a space at the end in heading.numbering, acceptable workaround? set outline(indent: auto) show outline: set par(leading: 0.8em, first-line-indent: 0pt) // From https://stackoverflow.com/questions/77031078/how-to-remove-numbers-from-outline show outline.entry: it => { if it.at("label", default: none) == <technogram-outline-entry> { it } else { let fill = if it.level > 1 { repeat[#h(3pt).#h(3pt)] } else [] let body = if it.level == 1 { v(20pt, weak: true) strong(it.body) } else { it.body } let page = if it.level == 1 { strong(it.page) } else { it.page } [#outline.entry( it.level, it.element, body, fill, page )<technogram-outline-entry>] } } outline() } #let document( title: none, subtitle: none, document-name: none, author: none, classification: "Public", revision: sys.inputs.at("revision", default: none), document-id: none, date: sys.inputs.at("date", default: datetime.today().display()), url: none, logotype: none, backmatter: none, show-title-page: true, show-outline: true, font: "Liberation Sans", monofont: "Latin Modern Mono", fontsize: 10pt, palette-overrides: none, body, ) = { /* Merge the default palette with any user overrides. */ palette-overrides = DEFAULT-PALETTE + palette-overrides /* Construct the document name. */ if document-name == none and title != none { document-name = title if subtitle != none { document-name += [ --- #subtitle] } } /* Pack a metadata dictionary for to pass to typesetting functions. */ let metadata = ( title: title, subtitle: subtitle, document-name: document-name, author: author, classification: classification, revision: revision, document-id: document-id, date: date, url: url, ) /* Page */ set page( paper: "a4", margin: _margins, header: _header(metadata, logotype), footer: _footer(metadata), header-ascent: 24pt, footer-descent: 12pt, ) /* Paragraphs */ set par(leading: 0.8em, spacing: 0.8em, first-line-indent: 15pt, justify: true) /* Fonts */ set text(font: font, size: fontsize) show raw: set text(font: monofont, size: fontsize) set super(typographic: false, baseline: -0.6em) /* Footnote entries (we add some spacing after the counter and a grid to align multiline footnotes). */ show footnote.entry: it => { grid( columns: (it.indent, auto, 0.3em, 1fr), none, { /* For some reason we need content (made invisible) for `super` to anchor correctly. */ box(width: 0pt)[#hide[M]] super[#counter(footnote).at(it.note.location()).first()] }, none, it.note.body ) } set footnote.entry(indent: 1em, gap: 0.8em) /* Sections */ set heading(numbering: "1.1 ") show heading: set block(above: 2.4em, below: 1.4em) /* Equations */ set math.equation(numbering: "(1)") /* Links (we don't color references) */ show link: set text(fill: palette-overrides.primary) /* Tables and figures */ show table.cell.where(y: 0): strong set table(fill: table-fill, stroke: table-stroke, align: left, inset: (top: 0.65em, bottom: 0.65em)) show figure.where(kind: table): set figure.caption(position: top) show figure.where(kind: table): set block(inset: (left: 5%, right: 5%)) show figure: set block(above: 3em , below: 3em, breakable: false) set figure(gap: 1.5em) /* Custom caption formatting to get the alignment right. */ show figure.caption: it => { let label = [ #it.supplement #context numbering(it.numbering, it.counter.get().first())#it.separator ] grid( columns: (auto, auto), align: left, column-gutter: 0.4em, label, it.body, ) } /* Lists */ set list(indent: 1.5em, body-indent: 1em) set enum( indent: 1.5em, body-indent: 1em, number-align: start + top, full: true, numbering: (..n) => { let remainder = calc.rem(n.pos().len(), 4) let format = if remainder == 1 { "1." } else if remainder == 2 { "(a)" } else if remainder == 3 { "i." } else if remainder == 0 { "A." } numbering(format, n.pos().last()) } ) /* We only want the first level of a list to be indented so we have a global show rule to make it so the objects are created with a nonzero indentation. Then, once the show rules below are invoked, we change the indentation to zero. This works (I think) because nested lists specified with the markdown syntax do not create list objects until they are encountered when walking through the top level items. */ show list: it => { set list(indent: 0pt) it } show enum: it => { set enum(indent: 0pt) it } /* Hook to pass raw content through the function library. */ show raw: it => { _raw-links.format-raw(it) } show raw.line: it => { _raw-links.format-raw-line(it) } /* Hook to pass references through the requirements library. */ show ref: it => { _requirements.format-reference(it) } /* Conditionally insert the title page. */ if show-title-page { _title-page(metadata, logotype, palette-overrides) counter(page).update(1) } else { _title-line(metadata, palette-overrides) } /* Conditionally insert the outline and a pagebreak. */ if show-outline { _outline() pagebreak() } /* Update the global palette and generate a matching one for admonition boxes. */ set raw(theme: "raw.tmTheme") update-palette(..palette-overrides) generate-admonition-palette(palette-overrides.primary, palette-overrides.secondary) /* Update the global document metadata for arbitrary access to the values provided to the template. We spread the dictionary be because each named argument gets inserted into the metadata (we don't interact with the state variable directly). */ update-metadata(..metadata) /* FIXME: Probably need referenceable enumeration items with https://gist.github.com/PgBiel/23a116de4a235ad4cf6c7a05d6648ca9 */ /* Typeset the document body. */ body /* Check for duplicate requirements. */ _requirements.check-for-duplicates() /* Typeset any backmatter. */ backmatter } /* Insert unnumbered pages w/o header and footer at the end of the document. */ #let backmatter(logotype: none, footer: none, body) = { context _page-before-backmatter.update(counter(page).get().at(0)) set page(footer: footer, header: _header(none, logotype), numbering: none) body } /* FIXME: Call it "document history" instead? */ #let changelog(..any) = context { pagebreak(weak: true) heading(level: 1, numbering: none, outlined: false, bookmarked: false)[Changelog] table( columns: (0.2fr, 0.8fr), fill: none, table.header[Location][Description], ..any.pos().flatten(), ) pagebreak() } #let changelog-section(hide: false, label, date, ..any) = ( /* Add a section header row. */ table.cell(colspan: 2, stroke: (top: 0.7pt, bottom: 0.7pt))[ #if label == auto { strong("Revision " + context get-metadata().revision) } else { strong("Revision " + label) } #h(1fr) #if date == auto { context get-metadata().date } else { date } ], /* Interpret the positional arguments as table cells which we apply an alternating fill color to in pairs of two (since we have two columns). If `hide` is set to true, we skip these cells. */ ..if not hide { any.pos().enumerate().map(((i, x)) => { table.cell(fill: if calc.odd(int(i / 2)) { luma(240) } )[#x] }) } ) #let appendix(body) = { set heading(numbering: "A.1 ", supplement: [Appendix]) counter(heading).update(0) body }
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-1/calculus-homework2.typ
typst
#import "../template.typ": * #show: project.with( title: "Calculus Homework #2", authors: (( name: "<NAME> (#47)", email: "<EMAIL>", phone: "3230104585" ),), date: "September 28, 2023", ) = 习题1-2 2(3) #prob[按定义证明数列极限:$ lim_(n->oo)(sqrt(n+1)-sqrt(n))=0 $] $forall eps>0$,要使 $ |sqrt(n+1)-sqrt(n)-0|<eps <=> sqrt(n+1)<sqrt(n)+eps \ <=> n+1<n+2sqrt(n) dot eps+eps^2 <=> 2sqrt(n) dot eps > 1-eps^2 $ 只要 $ n>(display((1-eps^2)/(2eps)))^2 = display((1-eps^2)^2/(4 eps^2)) $ 取 $N=max{1,display((1-eps^2)^2/(4 eps^2))}$,当 $n>N$ 时,都有 $|sqrt(n+1)-sqrt(n)-0|<eps$. 所以 $display(lim_(n->oo)(sqrt(n+1)-sqrt(n))=0)$. = 习题1-2 2(4) #prob[按定义证明数列极限:$ lim_(n->oo)n/a^n=0 quad (a>1 "为常数") $] 设 $t=a-1 in R_+$,则 $ a^n =(t+1)^n > t^n+n t^(n-1) $ $forall eps>0$,要使 $ |display(n/a^n)-0|<eps <=> display(n/a^n)<eps <=> display(n/(t+1)^n)<eps $ 由于 $display(n/((t+1)^n) < n/(t^n+n t^(n-1)))$,只需使 $ n/(t^n+n t^(n-1)) < eps <=> 1/(t^(n-1) (1+t/n)) < eps $ 由于 $display(1/(1+t/n))<1$,只需使 $ 1/(t^(n-1)) < eps <=> t^(n-1) eps > 1 <=> (n-1) ln(t) + ln(eps) > 0 <=> n > 1 + ln(eps) / ln(t) $ 取 $N = max{1, display(1 + ln(eps) / ln(t))}$,当 $n>N$ 时,都有 $|display(n/a^n)-0|<eps$. 所以 $display(lim_(n->oo)n/a^n=0)$. = 习题1-2 4 #prob[证明:若 $display(lim_(n->oo)a_n=a)$ 则 $display(lim_(n->oo)|a_n|=|a|)$,但反之不正确,试举例说明.但当 $a=0$ 时,反之也成立,试证明之.] 1. 证明:$=>$ 成立 因为 $display(lim_(n->oo)a_n=a)$,所以 $forall eps>0$, 存在 $N_1 in ZZ_+$ 使得 $forall n>N_1$,$|a_n-a|<eps$,即 $-eps<a_n-a<eps$ 成立. - 当 $a>0$ 时,根据极限的保号性 $exists N_2 in ZZ_+$,使得 $forall n>N_2$,$a_n>0$.那么取 $N$ $=$ $max{N_1,N_2}$,当 $n>N$ 时,有 $||a_n|-|a||=|a_n-a|<eps$. - 当 $a<0$ 时,根据极限的保号性 $exists N_2 in ZZ_+$,使得 $forall n>N_2$,$a_n<0$.那么取 $N$ $=$ $max{N_1,N_2}$,当 $n>N$ 时,有 $||a_n|-|a||=|-a_n+a|=|a_n-a|<eps$. - 当 $a=0$ 时,已经有 $forall n>N_1,space |a_n|<eps$. 综上,得证. 2. 证明:$arrow.l.double$ 不成立 对于通项为 $a_n=(-1)^n$ 的数列 ${a_n}$,满足 $display(lim_(n->oo)|a_n|=1)$.但显然,对于 $n=2k-1$ 和 $n=2k$ 的两个子列,分别有 $display(lim_(k->oo)(-1)^(2k-1)) =-1$ 和 $display(lim_(k->oo)(-1)^(2k)=1)$.因此数列 ${a_n}$ 发散,不存在极限.此时反方向不成立. 3. 证明:当 $a=0$ 时,$arrow.l.double$ 也成立. 当 $a=0$ 时,$forall eps>0$ 存在 $N in ZZ_+$,使得 $forall n>N$,$||a_n|-o|<eps$,即 $|a_n|<eps$,也即 $|a_n-0|<eps$.故 $display(lim_(n->oo) a_n = 0)$,反方向也成立. = 习题1-2 7(1) #prob[利用性质计算极限:$ lim_(n->oo)((-2)^n+3^n)/((-2)^(n+1)+3^(n+1)) $] $ lim_(n->oo)((-2)^n+3^n)/((-2)^(n+1)+3^(n+1)) =lim_(n->oo)(1/3((-2/3)^n+1)) / ((-2/3)^(n+1)+1) =1/3 lim_(n->oo)((-2/3)^n+1)/((-2/3)^(n+1)+1) $ 由于 $display(lim_(n->oo))(-2/3)^n=0$,故原数列的极限为 $1/3$. = 习题1-2 7(3) #prob[利用性质计算极限:$ lim_(n->oo)(1+a+a^2+dots.c+a^n)/(1+b+b^2+dots.c+b^n) quad (|a|<1, |b|<1) $] $ lim_(n->oo)(1+t+t^2+dots.c+t^n) = lim_(n->oo)(1-t^(n+1))/(1-t) $ $forall t in (-1,1)$,$display(lim_(t->oo)t^(n))=0$,因此 $display(lim_(t->oo)(1-t^(n+1))/(1-t) = 1/(1-t))$. 由于 $a,b in (-1,1)$,故 $ lim_(n->oo)(1+a+a^2+dots.c+a^n)/(1+b+b^2+dots.c+b^n) = (1/(1-a))/(1/(1-b)) = (1-b)/(1-a) $ = 习题1-2 7(5) #prob[利用性质计算极限:$ lim_(n->oo)[1^2/n^3+2^2/n^3+dots.c+(n-1)^2/n^3] $] $ &lim_(n->oo)[1^2/n^3+2^2/n^3+dots.c+(n-1)^2/n^3]\ =& lim_(n->oo)1/(n^3)(1^2 + 2^2 + dots.c + (n-1)^2)\ =& lim_(n->oo) (n (n-1) (2n-1)) / (6 n^3)\ =& lim_(n->oo) ((1 - 1/n) (2 - 1/n)) / (6) = 1/3 $ = 习题1-2 8(1) #prob[利用夹逼定理计算极限:$ lim_(n->oo)(sqrt(1 dot 2)/(n^2+1)+sqrt(2 dot 3)/(n^2+2)+dots.c+sqrt(n(n+1))/(n^2+n)) $] 由于 $ k/(n(n+1))<k/(n^2+k)<sqrt(k(k+1))/(n^2+k)<(k+1)/(n^2+k)<(k+1)/(n^2) $ 且 $ sum_(k=1)^n k/(n(n+1)) = (1/2n(n+1))/(n(n+1)) = 1/2 $ $ sum_(k=1)^n (k+1)/n^2 = (1/2(n+1)(n+2))/n^2 = (n^2+3n+2)/(2n^2) $ $ lim_(n->oo) (n^2+3n+2)/(2n^2) = lim_(n->oo) (1+3/n+2/n^2)/2 = 1/2 $ 故由夹逼定理得 $display(lim_(n->oo)[1^2/n^3+2^2/n^3+dots.c+(n-1)^2/n^3] = 1/2)$. = 习题1-2 8(3) #prob[利用夹逼定理计算极限:$ lim_(n->oo)root(n,n^p+n^q) quad(p,q in ZZ_+) $] - 先证明 $display(lim_(n->oo)) root(n,n) = 1$ 设 $root(n,n) = 1+h_n$,显然 $h_n$,且有 $ n = (1+h_n)^n > (n(n+1))/2 h_n^2 => h_n < sqrt(2/(n+1)) $ 由于 $display(lim_(n->oo) sqrt(2/(n+1))) =0$,由夹逼定理得 $display(lim_(n->oo) h_n) = 0$,即 $display(lim_(n->oo) root(n,n) = 1)$. - 再证明原命题,不妨令 $p<=q$,有 $ root(n,2 n^p)<=root(n,n^p+n^q)<=root(n,2 n^q) $ 其中 $display(lim_(n->oo) root(n,2) =1)$,且 $p,q$ 是定常数,则 $display(lim_(n->oo) root(n,2 n^p) = 1^(p+1) = 1)$,同理 $display(lim_(n->oo) root(n,2 n^q) = 1)$.由夹逼定理得 $display(lim_(n->oo)root(n,n^p+n^q)) = 1$. = 习题1-2 8(5) #prob[利用夹逼定理计算极限:$ lim_(n->oo)1/sqrt(n!) $] 由于 $n <= n! <= n^n$,所以 $ 1/sqrt(n^n) <= 1/sqrt(n!) <= 1/sqrt(n) $ 且 $display(lim_(n->oo)1/sqrt(n)=0)$,$display(lim_(n->oo)1/sqrt(n^n)=0)$,由夹逼定理知 $display(lim_(n->oo)1/sqrt(n!)=0)$.
https://github.com/jneug/typst-typopts
https://raw.githubusercontent.com/jneug/typst-typopts/main/README.md
markdown
MIT License
# typst-typopts A *Typst* package to conveniently handle options and arguments.
https://github.com/gianzamboni/cancionero
https://raw.githubusercontent.com/gianzamboni/cancionero/main/wip/16-tons.typ
typst
#import "../theme/project.typ": *; #cancion("16 Tons","<NAME>")[ Some people say a man is made outta mud A poor man's made outta muscle and blood Muscle and blood and skin and bones A mind that's a-weak and a back that's strong You load 16 tons, what do you get? Another day older and deeper in debt St. Peter, don't you call me 'cause I can't go I owe my soul to the company store I was born one mornin' when the sun didn't shine I picked up my shovel and I walked to the mine I loaded 16 tons of number nine coal And the straw boss said, "Well, a-bless my soul" You load 16 tons, what do you get? Another day older and deeper in debt St. Peter, don't you call me 'cause I can't go I owe my soul to the company store I was born one mornin', it was drizzlin' rain Fightin' and trouble are my middle name I was raised in the canebrake by an ol' mama lion Can't no high toned woman make me walk the line You load 16 tons, what do you get? Another day older and deeper in debt St. Peter, don't you call me 'cause I can't go I owe my soul to the company store If you see me comin', better step aside A lotta men didn't, a lotta men died One fist of iron, the other of steel If the right one don't get you Then the left one will You load 16 tons, what do you get? Another day older and deeper in debt St. Peter, don't you call me 'cause I can't go I owe my soul to the company store ]
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/import_path_inner.typ
typst
Apache License 2.0
// path: base.typ ----- #import /* position after */ "base.typ"
https://github.com/LDemetrios/ProgLectures
https://raw.githubusercontent.com/LDemetrios/ProgLectures/main/03-kotlin-inheritance.typ
typst
#import "kotlinheader.typ" : * #import "@preview/cetz:0.1.2" #show : kt-paper-rule = Контракты и наследование == Интерфейсы #kt-par[ Так, допустим, у нас есть некая реализация динамического массива целых чисел. Мы можем безболезненно вставлять элемент по любому неотрицательному индексу и массив автоматически расширится. ] #kt-eval( ``` import java.util.* class ArrayIntList { private var arr = IntArray(16) private var capacity = 16 private var size: Int = 0 fun getSize() : Int = size operator fun contains(element: Int): Boolean { for (i in 0 until size) if (arr[i] == element) return true return false } fun containsAll(elements: Collection<Int>): Boolean { for (el in elements) { if (!contains(el)) return false } return true } operator fun get(index: Int): Int { if (index < 0) throw ArrayIndexOutOfBoundsException("$index") if (index >= size) return 0 return arr[index] } fun isEmpty(): Boolean = size == 0 fun add(element: Int) { if (size == capacity) { arr = Arrays.copyOf(arr, capacity + capacity / 2 + 1) capacity = arr.size } arr[size] = element size++ } fun addAll(elements: Collection<Int>) { if (capacity < size + elements.size) { arr = Arrays.copyOf(arr, maxOf(capacity + capacity / 2 + 1, size + elements.size)) capacity = arr.size } for (el in elements) set(size++, el) } fun clear() { size = 0 } operator fun set(index: Int, element: Int) { if (capacity <= index) { arr = Arrays.copyOf(arr, maxOf(capacity + capacity / 2 + 1, index + 1)) capacity = arr.size } arr[index] = element if (index >= size) size = index + 1 } override fun toString(): String { val sb = StringBuilder("[") var empties = 0 for (i in 0 until getSize()) { if (this[i] == 0) empties++ else { if(i != 0) sb.append(", ") if(empties != 0) sb.append("<$empties empty slots>, ") empties = 0 sb.append(this[i]) } } if(empties != 0) sb.append("<$empties empty slots>") sb.append("]") return sb.toString() } } ```, ) #v(1fr) #kt-par[ \ Что у нас есть: - getSize --- возвращает текущий размер массива - contains --- проверяет, содержится ли такой элемент - containsAll --- проверяет, содержатся ли все элементы из коллекции - get --- берёт по индексу, по умолчанию возвращает ноль - isEmpty --- проверяет, не пуст ли массив - add --- добавляет элемент в конец - addAll --- добавляет все элементы в конец - clear --- очищает массив (в данном случае чистить `arr` необходимости нет, всё лежащее за `size` теперь будет игнорироваться) - set --- кладёт по индексу - toString --- щадаёт строковое представление. Это на лекции не обсуждалось, я дописал для наглядности. Устроен несложно, можете разобраться. ] #v(1fr) #kt-par[ Ничего интеллектуального. Что здесь изменилось с прошлой лекции? Теперь у нас у объектов класса есть состояние, которое хранится в var'ах, вместо просто постоянных данных, которые хранились в val'ах ] #v(1fr) #kt-par[ Давайте напишем функцию, заполняющую заданный отрезок массива заданным числом. ] #v(1fr) #kt-eval-append(``` fun fill(list: ArrayIntList, fromIndex: Int, toIndex: Int, value: Int) { for (i in fromIndex until toIndex) { list[i] = value } } ```) #v(1fr) #nobreak[ #kt-par[Проверим, что всё означенное дело работает.] #kt-eval-append(``` val arr = ArrayIntList() arr.addAll(listOf(1, 2, 3, 4, 5)) arr[9] = 566 arr ```) #kt-res(`[1, 2, 3, 4, 5, <4 empty slots>, 566]`, `ArrayIntList`) #kt-par[Поведение ожидаемое.] ] #nobreak[ #kt-par[ Теперь `fill`:] #kt-eval-append(``` fill(arr, 20, 30, -1) arr ```) #kt-res( `[1, 2, 3, 4, 5, <4 empty slots>, 566, <10 empty slots>, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]`, `ArrayIntList`, ) ] #nobreak[ #kt-par[Теперь такой момент. Это хорошо, когда массив небольшого размера. А если захочется сделать так?] #kt-eval-append(``` fill(arr, 5, 30, 0) arr[1000000] = 1 arr ```) #kt-res(`[1, 2, 3, 4, 5, <999995 empty slots>, 1]`, `ArrayIntList`) ] #nobreak[ #kt-par[ Окей, работает. Попробуем ] #kt-eval-append(``` arr[2147000000 /*Don't remember*/] = 1 arr ```) #kt-par[ Хотелось бы увидеть здесь ответ ] #kt-res( `[1, 2, 3, 4, 5, <999995 empty slots>, 1, <2145999999 empty slots>, 1]`, `ArrayIntList`, ) ] #nobreak[ #kt-par[ Но на деле мы получим ] #kt-runt-err(``` Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:3284) at pack.ArrayIntList.set(Test.kts:53) at pack.TestKts.main(Test.kts:91) at pack.TestKts.main(Test.kts) ```) #kt-par[ Нам намекают, что мы хотим слишком много памяти. $2^31 dot.op 4$ байт, то есть 8Гб, если быть точным. ] ] #let n = 4 #let arr-repr-h(x, y, name-pref) = { import cetz.draw: * for i in range(0, n) { rect((x + i, y - 0.5), (x + i + 1, y + 0.5), name: name-pref + str(i)) /* content( name-pref + str(i) + ".top-left", text(size: 8pt)[#name-pref#i], anchor: "top-left", )*/ content(name-pref + str(i) + ".top", [#pad(y: 0.2em)[#i]], anchor: "bottom") } } #let arr-repr-v(x, y, name-pref) = { import cetz.draw: * for i in range(0, n) { rect((x - 0.5, y - i), (x + 0.5, y - i - 1), name: name-pref + str(i)) content(name-pref + str(i) + ".left", [#pad(x: 0.3em)[#i]], anchor: "right") /* content( name-pref + str(i) + ".top-left", text(size: 8pt)[#name-pref#i], anchor: "top-left", )*/ } } #let block-repr(x, y, name-pref) = { import cetz.draw: * arr-repr-v(x - n * 0.7, y + 2.5, name-pref + "h") for i in range(0, n) { arr-repr-h(x, y - i * 1.7, name-pref + str(i)) // circle(name-pref + "h" + str(i) + ".center", radius: 0.07, fill:black) line( name-pref + "h" + str(i) + ".center", name-pref + str(i) + "0.left", mark: (end: ">", size: .4), ) circle(name-pref + "h" + str(i) + ".center", radius: .1, fill: black) } } #let lib-repr(x, y, name-pref) = { import cetz.draw: * arr-repr-h(x - n / 2, y + 2.5, name-pref + "h") for i in range(0, n) { block-repr(x + i * n * 2.5 - n * n * 0.9, y - n * 1.2, name-pref + str(i)) line( name-pref + "h" + str(i) + ".center", name-pref + str(i) + "h0.top", mark: (end: ">", size: .4), ) circle(name-pref + "h" + str(i) + ".center", radius: .1, fill: black) } } #nobreak[ #kt-par[ Давайте вдохновимся JS и напишем другой вариант этого списка. ] #align(center)[ #cetz.canvas({ import cetz.draw: * scale(0.5) lib-repr(4, 4, "r") }) ] ] #v(1fr) #kt-par[ Будем хранить в памяти вот такую иерархическую структуру. Допустим, мы хотим положить элемент 566 по индексу 30. Для этого переводим 30 в четверичную систему: $30_10 = 132_4$. В верхнем массиве выберем элемент по индексу 1, там лежит ссылка на блок. Там выберем элемент по индексу 3, получим ссылку на массив. По индексу 2 положим туда 566. ] #v(1fr) #align(center)[ #cetz.canvas({ import cetz.draw: * scale(0.5) lib-repr(4, 4, "r") stroke((paint: red, thickness: 3pt)) rect("rh1.top-left", "rh1.bottom-right") rect("r1h3.top-left", "r1h3.bottom-right") rect("r132.top-left", "r132.bottom-right") stroke((paint: red, thickness: 1.2pt)) line("rh1.center", "r1h0.top", mark: (end: ">", size: .4)) circle("rh1.center", radius: .1, fill: red) line("r1h3.center", "r130.left", mark: (end: ">", size: .4)) circle("r1h3.center", radius: .1, fill: red) content("r132.center", [#text(size: .9em)[566]]) }) ] #v(1fr) #kt-par[ Так, а чем это лучше? Мы же совершаем кучу лишних индирекций по оперативной памяти? ] #let chunked-arr(arr, x, y, name-pref, defaults) = { import cetz.draw: * if (arr == none) { return } arr-repr-h(x - n / 2, y + 2.5, name-pref + "h") for i in range(0, n) { if (arr.at(i) == none) { content( name-pref + "h" + str(i) + ".center", text(fill: defaults, size: 8pt)[null], anchor: "center", ) continue } let block-x = x + i * n * 2.5 - n * n * 0.9 let block-y = y - n * 1.2 arr-repr-v(block-x - n * 0.7, block-y + 2.5, name-pref + str(i) + "h") for j in range(0, n) { if (arr.at(i).at(j) == none) { content( name-pref + str(i) + "h" + str(j) + ".center", text(fill: defaults, size: 8pt)[null], anchor: "center", ) continue } arr-repr-h(block-x, block-y - j * 1.7, name-pref + str(i) + str(j)) line( name-pref + str(i) + "h" + str(j) + ".center", name-pref + str(i) + str(j) + "0.left", mark: (end: ">", size: .4), ) circle(name-pref + str(i) + "h" + str(j) + ".center", radius: .1, fill: black) for k in range(0, n) { if (arr.at(i).at(j).at(k) != none) { content( name-pref + str(i) + str(j) + str(k) + ".center", [#arr.at(i).at(j).at(k)], anchor: "center", ) } else { content( name-pref + str(i) + str(j) + str(k) + ".center", text(fill: defaults)[0], anchor: "center", ) } } } line( name-pref + "h" + str(i) + ".center", name-pref + str(i) + "h0.top", mark: (end: ">", size: .4), ) circle(name-pref + "h" + str(i) + ".center", radius: .1, fill: black) } } #let chunked-arr-from-list(list, x, y, name-pref, defaults: white) = { let a(from-index, arr) = { let res = ( arr.at(str(from-index), default: none), arr.at(str(from-index + 1), default: none), arr.at(str(from-index + 2), default: none), arr.at(str(from-index + 3), default: none), ) if (res == (none, none, none, none)) { none } else { res } } let b(from-index, arr) ={ let res = ( a(from-index, arr), a(from-index + 4, arr), a(from-index + 8, arr), a(from-index + 12, arr), ) if (res == (none, none, none, none)) { none } else { res } } let c(arr) ={ let res = (b(0, arr), b(16, arr), b(32, arr), b(48, arr),) if (res == (none, none, none, none)) { none } else { res } } chunked-arr(c(list), x, y, name-pref, defaults) } #nobreak[ #kt-par[ Хотя бы тем, что мы можем не хранить лишние элементы структуры, заменив их на null. ] #align(center)[ #cetz.canvas({ import cetz.draw: * scale(0.5) chunked-arr-from-list( ("0": 1, "14": 18, "30": 566, "60": "63", "63": 65), 4, 4, "r", defaults: rgb(110, 110, 110), ) }) ] ] #kt-par[ Преимущества на лицо! Существенно меньше памяти, если данные сильно распределены. Можно, конечно, было бы воспользоваться какой-нибудь хэш-таблицей, но это ещё сложнее. Давайте по-быстрому это реализуем. Только вместо массивов длины 3 будем использовать длиной 256, а всю структуру сделаем глубиной 4. $256^4 = 2^32$, тогда как массивы позволяют индексы до $2^31-1$. Ну, останется место при желании занумеровать элементы отрицательными индексами. ] #kt-eval-append( ``` class ChunkedIntList { private var arr: Array<Array<Array<IntArray?>?>?>? = null private var size: Int = 0 fun getSize(): Int = size operator fun contains(element: Int): Boolean { if (arr == null) return false for (i in 0 until 256) { if (arr!![i] == null) continue for (j in 0 until 256) { if (arr!![i]!![j] == null) continue for (k in 0 until 256) { if (arr!![i]!![j]!![k] == null) continue for (l in 0 until 256) { if (arr!![i]!![j]!![k]!![l] == element) return true } } } } return false } fun containsAll(elements: Collection<Int>): Boolean { for (el in elements) { if (!contains(el)) return false } return true } operator fun get(index: Int): Int { if (index < 0) throw ArrayIndexOutOfBoundsException("$index") if (index >= size) return 0 return arr?.get(index shr 24)?.get(index shr 16 and 255)?.get(index shr 8 and 255)?.get(index and 255) ?: 0 } fun isEmpty(): Boolean = size == 0 fun add(element: Int) { val i = size shr 24 val j = size shr 16 and 255 val k = size shr 8 and 255 val l = size and 255 if (arr == null) arr = Array(256) { null } if (arr!![i] == null) arr!![i] = Array(256) { null } if (arr!![i]!![j] == null) arr!![i]!![j] = Array(256) { null } if (arr!![i]!![j]!![k] == null) arr!![i]!![j]!![k] = IntArray(256) arr!![i]!![j]!![k]!![l] = element size++ } fun addAll(elements: Collection<Int>) { for (el in elements) add(el) } fun clear() { size = 0 arr = null } operator fun set(index: Int, element: Int) { val i = index shr 24 val j = index shr 16 and 255 val k = index shr 8 and 255 val l = index and 255 if (arr == null) arr = Array(256) { null } if (arr!![i] == null) arr!![i] = Array(256) { null } if (arr!![i]!![j] == null) arr!![i]!![j] = Array(256) { null } if (arr!![i]!![j]!![k] == null) arr!![i]!![j]!![k] = IntArray(256) arr!![i]!![j]!![k]!![l] = element if (index >= size) size = index + 1 } } ```, ) #kt-par[ `toString` будет выглядеть так же, не будем занимать лишнее место в конспекте. Что здесь есть нового? `IntArray` --- это почти `Array<`Int`>`, только эффективнее (это связано с внутренним устройством JVM). `shr`, `and` --- битовые операции над числами (shift right --- битовый сдвиг вправо, and --- битовое "и"). При очищении обнуляем `size` и удаляем ссылку на `arr`. Остальное за нас сборщик мусора подберёт. ] #nobreak[ #kt-par[Давайте проверять!] #kt-eval-append(``` val arr2 = ChunkedIntList() arr2.addAll(listOf(1, 2, 3, 4, 5)) arr2[1000000] = 1 arr2[2147000000] = 1 arr2 ```) #kt-res( `[1, 2, 3, 4, 5, <999995 empty slots>, 1, <2145999999 empty slots>, 1]`, `ChunkedIntList`, ) #kt-par[Отличнейшим образом работает.] #kt-eval-append(``` fill(arr2, 10, 20, -1) ```) #kt-comp-err( `Kotlin: Type mismatch: inferred type is ChunkedIntList but ArrayIntList was expected`, ) #kt-par[ Э-э-э... А? Ну, впрочем, ничего удивительного. Мы ведь объявляли функцию как работающую с `ArrayIntList`, откуда бы компилятору знать, что `ChunkedIntList` умеет всё то же самое и не хуже? Надо ему рассказать. Для этого существуют интерфейсы. ] ] #kt-eval(``` interface IntList { fun getSize(): Int operator fun contains(element: Int): Boolean fun containsAll(elements: Collection<Int>): Boolean operator fun get(index: Int): Int fun isEmpty(): Boolean fun add(element: Int) fun addAll(elements: Collection<Int>) fun clear() operator fun set(index: Int, element: Int) override fun toString(): String } ```) #kt-par[ Здесь мы описываем сигнатуры, модификаторы и возвращаемые типы. Всё. Теперь у нас есть отдельный тип под названием `IntList`, с которым можно делать всё перечисленное. Но реализации методов у нас нигде не прописаны. Как нигде и не указано, что `ArrayIntList` и `ChunkedIntList` реализуют их не просто так, а чтобы подходить под требование `IntList`. Для этого надо написать это в заголовке класса, а ко всем соответствующим методам дописать модификатор override. ] #nobreak[ #kt-eval-append(``` class ArrayIntList : IntList { private var arr = IntArray(16) private var capacity = 16 private var size: Int = 0 override fun getSize(): Int = size override operator fun contains(element: Int): Boolean { for (i in 0 until size) if (arr[i] == element) return true return false } // et cetera } ```) ] #nobreak[ #kt-eval-append(``` class ChunkedIntList : IntList { private var arr: Array<Array<Array<IntArray?>?>?>? = null private var size: Int = 0 override fun getSize(): Int = size override operator fun contains(element: Int): Boolean { if (arr == null) return false for (i in 0 until 256) { if (arr!![i] == null) continue for (j in 0 until 256) { if (arr!![i]!![j] == null) continue for (k in 0 until 256) { if (arr!![i]!![j]!![k] == null) continue for (l in 0 until 256) { if (arr!![i]!![j]!![k]!![l] == element) return true } } } } return false } // et cetera } ```) ] #nobreak[ #kt-par[ Теперь вполне можем написать ] #kt-eval-append( ``` private fun fill(list: IntList, fromIndex: Int, toIndex: Int, value: Int) { for (i in fromIndex until toIndex) { list[i] = value } } val arr = ChunkedIntList() fill(arr, 5, 10, -1) arr[2147000000] = -2 arr ```, ) #kt-res( `[, <5 empty slots>, -1, -1, -1, -1, -1, <2146999990 empty slots>, -2]`, `ChunkedIntList`, ) #kt-par[ It's alive! ] ] #kt-par[ Обратим внимание теперь, что у нас очень много похожего кода. `addAll`, `containsAll`, `toString`, `isEmpty` --- вообще одинаково, в `get` отличается одна строчка. Учитывая, что `set` автоматически создаст необходимое место, оба `add` можно было бы заменить на вызов `set`. Давайте что-нибудь с этим сделаем, а то ведь если мы захотим новую какую-нибудь реализацию (хоть бы и на хэш-таблице), что, снова всё перепечатывать? ] #comment[ #kt-par[ Справедливости ради, можно было бы сделать следующим образом: убрать их из `IntList` и объявить как внешние (external): ] #kt(``` fun IntList.containsAll(elements: Collection<Int>): Boolean { for (el in elements) { if (!contains(el)) return false } return true }```) #kt-par[ ...как мы могли сделать и с `fill`, в общем-то... Но вот, например, с `toString` такой фокус не пройдёт --- почему, поймёте чуть позже. Если мы объявим её как внешнюю, мы продолжим получать абракадабру вроде `ChunkedIntList@610455d6`. Поэтому делать будем по-другому. ] ] == Абстрактные классы Это сущность, очень похожая на интерфейс, но с двумя существенными отличиями --- она может описывать не только сигнатуру методов, но и их реализацию; а также может иметь собственное состояние, хранимое в переменных. Чаще всего они используются для того как раз, чтобы задать "частичную" реализацию интерфейса. #kt-eval(``` import java.util.* interface IntList { fun getSize(): Int operator fun contains(element: Int): Boolean fun containsAll(elements: Collection<Int>): Boolean operator fun get(index: Int): Int fun isEmpty(): Boolean fun add(element: Int) fun addAll(elements: Collection<Int>) fun clear() operator fun set(index: Int, element: Int) } ```) #kt-eval-append(``` abstract class AbstractIntList : IntList { override fun containsAll(elements: Collection<Int>): Boolean { for (el in elements) { if (!contains(el)) return false } return true } override fun isEmpty(): Boolean = getSize() == 0 override fun addAll(elements: Collection<Int>) { for (el in elements) add(el) } override fun add(element: Int) { set(getSize(), element) } override fun toString(): String { val sb = StringBuilder("[") var empties = 0 for (i in 0 until getSize()) { if (this[i] == 0) empties++ else { if (i != 0) sb.append(", ") if (empties != 0) sb.append("<$empties empty slots>, ") empties = 0 sb.append(this[i]) } } if (empties != 0) sb.append("<$empties empty slots>") sb.append("]") return sb.toString() } } ```) #kt-eval-append(``` class ArrayIntList : AbstractIntList() { private var arr = IntArray(16) private var capacity = 16 private var size: Int = 0 override fun getSize(): Int = size override operator fun contains(element: Int): Boolean { for (i in 0 until size) if (arr[i] == element) return true return false } override operator fun get(index: Int): Int { if (index < 0) throw ArrayIndexOutOfBoundsException("$index") if (index >= size) return 0 return arr[index] } override fun clear() { size = 0 } override operator fun set(index: Int, element: Int) { if (capacity <= index) { arr = Arrays.copyOf(arr, maxOf(capacity + capacity / 2 + 1, index + 1)) capacity = arr.size } arr[index] = element if (index >= size) size = index + 1 } } ```) #nobreak[ #kt-eval-append( ``` class ChunkedIntList : AbstractIntList() { private var arr: Array<Array<Array<IntArray?>?>?>? = null private var size: Int = 0 override fun getSize(): Int = size override operator fun contains(element: Int): Boolean { if (arr == null) return false for (i in 0 until 256) { if (arr!![i] == null) continue for (j in 0 until 256) { if (arr!![i]!![j] == null) continue for (k in 0 until 256) { if (arr!![i]!![j]!![k] == null) continue for (l in 0 until 256) { if (arr!![i]!![j]!![k]!![l] == element) return true } } } } return false } override operator fun get(index: Int): Int { if (index < 0) throw ArrayIndexOutOfBoundsException("$index") if (index >= size) return 0 return arr?.get(index shr 24)?.get(index shr 16 and 255)?.get(index shr 8 and 255)?.get(index and 255) ?: 0 } override fun clear() { size = 0 arr = null } override operator fun set(index: Int, element: Int) { val i = index shr 24 val j = index shr 16 and 255 val k = index shr 8 and 255 val l = index and 255 if (arr == null) arr = Array(256) { null } if (arr!![i] == null) arr!![i] = Array(256) { null } if (arr!![i]!![j] == null) arr!![i]!![j] = Array(256) { null } if (arr!![i]!![j]!![k] == null) arr!![i]!![j]!![k] = IntArray(256) arr!![i]!![j]!![k]!![l] = element if (index >= size) size = index + 1 } } ```, ) ] #kt-eval-append(``` fun fill(list: IntList, fromIndex: Int, toIndex: Int, value: Int) { for (i in fromIndex until toIndex) { list[i] = value } } ```) #kt-par[ Теперь мы пишем, что классы `ArrayIntList` и `ChunkedIntList` _наследуют_ `AbstractIntList`. То есть, все реализации методов, описанные в `AbstractIntList`, отработают ровно так же и на наследниках. Впрочем, класс-наследник их может переопределить (override), то есть написать свою реализацию, которая имеет приоритет над "родительской" реализацией. ] #kt-par[ Обратите внимание, что класс-предок ничего не знает о своих наследниках: он, в некотором смысле, описывает "общий случай". Поэтому в нём обращение к приватной переменной `size` заменено на `getSize` --- откуда ему знать, что, по факту, все его наследники хранят `size` в просто переменной? Точно так же класс не должен знать о своих "братьях" --- далеко не всегда можно гарантировать, что ты знаешь обо всех наследниках твоего предка. ] #kt-par[ Также здесь внезапно появился вызов родительского _конструктора_ --- круглые скобки #box[после `: AbstractIntList`]. Мы не объявили там никакого конструктора, поэтому по умолчанию создался пустой, без аргументов, просто создающий объект без всяких внешних данных. ] #kt-par[ Можно реализовывать _сколько угодно_ интерфейсов, но наследовать _не более чем у одного_ класса. Это связано с тем, что если вы наследуете несколько реализаций методов с одинаковой сигнатурой, не вполне понятно, в каком случае какую из них вызывать (Языки с множественным наследованием существуют, но там бывают довольно... запутанные правила). ] #kt-par[ Также в абстрактных классах можно требовать от наследников реализации определённых методов, написав их сигнатуру с модификатором abstract. ] #kt-par[ Например, можно сделать так: ] #kt(``` abstract class AbstractIntList : IntList { // blah-blah override operator fun get(index: Int): Int { if (index < 0) throw ArrayIndexOutOfBoundsException("$index") if (index >= size) return 0 return take(index) } protected abstract fun take(index: Int) : Int } class ArrayIntList : AbstractIntList() { // blah-blah override take(index: Int) : Int = arr[index] } class ChunkedIntList : AbstractIntList() { // blah-blah override fun take(index: Int) = arr ?.get(index shr 24) ?.get(index shr 16 and 255) ?.get(index shr 8 and 255) ?.get(index and 255) ?: 0 } ```) #kt-par[ В целом, абстрактный класс может не оставлять нереализованных методов, но тогда не очень понятно, зачем ему вообще быть абстрактным. Единственное его отличие в таком случае --- нельзя создать объект этого типа (это логично --- абстрактность позволяет иметь нереализованные методы, а что мы будем делать, если попытаемся его вызвать...). В таком случае можно объявить класс open. _Открытые_ классы можно наследовать и при этом можно создавать объекты (инстанцировать --- от английского instance). При этом вы можете разрешить переопределять методы open класса, объявив их также open ] #kt-par[ Хороший пример такого класса --- Any. Это открытый класс, который содержит три открытых метода --- `equals`, `hashCode`, `toString`. Первый отвечает за сравнение на равенство (`==`), второй --- за вычисление хэш-кода, третий --- за строковое представление. Как раз их мы переопределяем, если хотим, чтобы `==` и вывод на объектах этих классов работал адекватно. Переопределённые функции автоматически отмечаются open ] #nobreak[ == Виртуальное наследование Допустим, у нас есть следующая схема. #kt-eval(``` abstract class Parent { abstract fun foo() } ```) ] #nobreak[ #kt-eval-append(``` class ChildA : Parent() { override fun foo() { println("ChildA: foo") } } ```) ] #nobreak[ #kt-eval-append(``` open class ChildB : Parent() { override fun foo() { println("ChildB: foo") } } ```) ] #nobreak[ #kt-eval-append(``` class Grandchild : ChildB() { override fun foo() { println("Grandchild: foo") } } ```) ] #nobreak[ #kt-eval-append(``` val obj : Parent = Grandchild() obj.foo() ```) #kt-print(`Grandchild: foo`) #kt-par[ Почему так? ] ] #kt-par[ Вернее, хорошо, что оно так работает, но как? Откуда на самом деле компилятор знает, какой вариант функции вызвать, если тип переменной --- `Parent`? А он и не знает. Уже во время исполнения происходит переход по ссылке, лежащей в переменной --- туда, где лежит сам объект, читается его заголовок (где, в частности, прописан его настоящий класс), после чего, в зависимости от результата, переход в нужную версию функции. Такой вариант наследования называется виртуальным --- таблица, где выполняется поиск нужной реализации, соответственно, таблицей виртуальных функций. В JVM всё наследование виртуальное. ] #comment[ #kt-par[ Собственно, это отвечает на вопрос, почему определённая в качестве external функция `toString` никоим образом не помогает. Объявленные внутри класса методы транслируются в... методы java-классов, а внешние функции --- в функции, принимающие `receiver type` первым аргументом. Поэтому когда println вызовет `toString` на вашем объекте, будет вызван собственный метод, а не внешняя функция. ] ] == Бонус 1: Интерфейсы-маркеры #kt-par[ Никто, в общем-то, не запрещает делать интерфейс, который не содержит методов вовсе. Они служат двум целям: либо объединить в себе несколько других (интерфейс наследует другой интерфейс --- означает, что он требует реализовать то, что описано в нём самом, и то, что описано в его предках), либо просто пометить класс как принадлежащий какой-то группе. Как раз маркером является, например, интерфейс Serializable --- его требования не формализуемы в виде просто набора методов, но если вы помечаете класс как Serializable --- это означает, что в нём есть всё необходимое, чтобы объект этого класса можно было записать в файл и восстановить после прочтения. ] == Бонус 2: Абстрактные постоянные #kt-par[ На самом деле, когда вы объявляете в классе переменную или постоянную, вы делаете две вещи: собственно заводите переменную или постоянную, и заводите метод `getИмя` и `setИмя` (set --- понятное дело, только для переменной). И всегда, когда вы обращаетесь по синтаксису через точку --- вы на самом деле вызываете соответствующий метод (так это сделано в Котлине, в большинстве языков по-другому). В обычном случае они ничего не делают умного --- просто записывают или возвращают значение. Но можно также их изменить. Для этого есть ключевые слова #kt-keyword("get") и #kt-keyword("set"). ] #kt(``` var variable : Int = 0 get() { return field } set(value) { field = value } ```) #kt-par[ Собственно, здесь описано в явном виде то, что они делают по умолчанию. Но можно добавить туда, например, вывод сообщения при каждом обращении, или какие-то проверки, и так далее. ] #nobreak[ #kt-par[ А ещё можно модифицировать область видимости этих методов отдельно: ] #kt(``` var variable : Int = 0 private set ```) #kt-par[ Это, например, переменная, которую можно читать из любого места (по умолчанию модификатор public), а записывать только изнутри класса (private). Ещё может быть protected --- доступно только наследникам, и internal --- внутри одного пакета. ] #kt-par[ Всё это даёт нам возможность провернуть любопытный фокус: можно в интерфейсе объявить постоянную (то есть как бы потребовать реализовать только геттер), а в реализации сделать её переменной с приватным сеттером: ] #indent[ #kt(``` interface IntList { val size : Int // et cetera } class ArrayIntList : IntList { override var size : Int private set // et cetera } ```) ] ]
https://github.com/sergiodrd/analisis_real
https://raw.githubusercontent.com/sergiodrd/analisis_real/main/tarea3/main.typ
typst
#import "template.typ": * #let title = "Tarea 3" #let author = "<NAME>" #let course_id = "MATE 5201" #let instructor = "<NAME>" #let semester = "C41" #let due_time = "7 de octubre" #set enum(numbering: "a)") #set math.equation(numbering: "(1)", supplement: "la ecuación") #show: assignment_class.with(title, author, course_id, instructor, semester, due_time) #let contradiction = text($refmark$, size: 1.75em) // problema 1 #prob[ _(5 puntos) -- Demuestre que los únicos subconjuntos de $RR$ que son abiertos y cerrados son $nothing$ y $RR$._ == Prueba: Sea $E subset.eq RR$ abierto y cerrado. Sea $E^compose := { x in E | exists r gt 0 "tal que" B(x; r) subset.eq E }$ y \ $E' := { x in RR | (U_(r)(x) without {x}) sect E eq.not nothing }$. Note que $E^compose subset.eq E'$. Como $E$ es abierto, $E eq E^compose$, y como $E$ es cerrado, $E' subset.eq E eq E^compose$. Por lo tanto, $E^compose eq E'$, lo que implica que $E' without E^compose eq nothing$. Suponga, por contradicción, que $E eq.not nothing and E eq.not RR$. Ahora fije un elemento arbitrario $x in E$ y considere $F := { d(x, y) | y in E^complement } subset.eq RR$. Note que $E eq.not RR ==> E^complement eq.not nothing ==> F eq.not nothing$. Además, por la definición de la métrica, $0$ es una cota inferior para $F$. Por lo tanto, por la propiedad de la cota inferior mínima, $inf(F)$ existe en $RR$. Entonces existe un $alpha in RR$ tal que $d(x, alpha) = inf(F)$ con $(U_(rho)(alpha) without {alpha}) sect E eq.not nothing " " forall rho gt 0$ (porque $inf(F) - rho in.not F " " forall rho gt 0 ==> "si" d(x, y) = inf(F) - rho, "entonces" y in.not E^complement ==> y in E$). Además, $U_(rho)(alpha) subset.eq.not E$ (porque $exists epsilon in F$ tal que $inf(F) lt epsilon lt inf(F) + rho " " forall rho gt 0 ==> exists y in E^complement "tal que" d(x, y) = epsilon$). Por lo tanto, $x in E^compose without E' ==> E^compose without E' eq.not nothing$. $contradiction$ Por lo tanto, $E eq nothing or E eq RR$. Ahora, note que $x in nothing ==> exists r gt 0 "tal que" B(x; r) subset.eq E$ es cierto porque la hipótesis es falsa, por lo tanto $nothing$ es abierto y $nothing^complement = RR$ es cerrado. Similarmente, $x in nothing ==> (U_(r)(x) without {x}) sect E eq.not nothing " " forall r gt 0$. Por lo tanto, $nothing$ es cerrado y $nothing^complement = RR$ es abierto. *MEP* ] // problema 2 #prob[ _(12 puntos) -- Para $x, y in RR$, definamos: $ &d_1(x, y) := (x - y)^2 \ &d_2(x, y) := sqrt(abs(x - y)) \ &d_3(x, y) := abs(x - 2 y) \ &d_4(x, y) := abs(x^2 - y^2) $_ _Determine cuáles de estos definen métricas en $RR$. Justifique completamente cada respuesta._ == Determinación: $d_1$ no define una métrica en $RR$ porque falla la desigualdad triangular. Tome $x eq 1, y eq 0, z eq -1$ y note que $d_1(1, -1) eq 4 lt.eq.not 2 eq 1 + 1 eq d_1(1, 0) + d_1(0, -1)$. $d_2$ define una métrica en $RR$. Note que $d_2(x, y) eq sqrt(d(x, y))$ con $d$ siendo la métrica usual de $RR$. Ahora: $ d_2(x, x) eq sqrt(d(x, x)) eq sqrt(0) eq 0 $ $ d_2(x, y) eq sqrt(d(x, y)) eq sqrt(d(y, x)) eq d_2(y, x) $ $ d_2(x, z) eq sqrt(d(x, z)) lt.eq sqrt(d(x, y)) + sqrt(d(y, z)) eq d_2(x, y) + d_2(y, z) $ $d_3$ no define una métrica en $RR$ porque falla la propiedad de que $d(x, y) eq 0 <==> x eq y$. Tome \ $x eq 2, y eq 1$ y note que $d_3(2, 1) eq abs(2 - 2) = 0$ $d_4$ no define una métrica en $RR$ porque falla la propiedad de que $d(x, y) eq 0 <==> x eq y$. Tome \ $x eq 1, y eq -1$ y note que $d_4(1, -1) eq abs(1^2 - (-1)^2) eq abs(1 - 1) eq 0$. ] // problema 3 #prob[ _(5 puntos) -- Sea $(X, d)$ un espacio métrico, y definamos: $ d^*(x, y) := d(x, y) / (1 + d(x, y)), " " forall x, y in X $_ _Pruebe que $(X, d^*)$ es un espacio métrico, y que $d^*: X times X -> [0, 1)$._ == Prueba: Note que como $d$ es una métrica: $ d^*(x, x) eq d(x, x) / (1 + d(x, x)) eq 0, " " forall x in X $ $ d^*(x, y) eq d(x, y) / (1 + d(x, y)) eq d(y, x) / (1 + d(y, x)) eq d^*(y, x), " " forall x, y in X $ $ d^*(x, z) &eq d(x, z) / (1 + d(x, z)) lt.eq (d(x, y) + d(y, z)) / (1 + d(x, y) + d(y, z)) \ &lt.eq (d(x, y) + 2 d(x, y) d(y, z) + d(y, z)) / (1 + d(x, y) + d(x, y) d(y, z) + d(y, z))\ &eq d(x, y) / (1 + d(x, y)) + d(y, z) / (1 + d(y, z)) eq d^*(x, y) + d^*(y, z) $ Es claro que el dominio de $d^*$ es $X times X$. Como $d^*$ es una métrica, su rango empieza limitado a $[0, infinity)$, pero ahora, note que $lim_(d(x, y) -> infinity) d^*(x, y) eq 1$. $therefore d^*: X times X -> [0, 1)$. *MEP* ] // problema 4 #prob[ _(4 puntos c.u.) -- Dado $(X, d)$ espacio métrico, y $E subset.eq X$, definamos: $ E^compose := { x in E | x "punto interior" }, " " E' := { x in X | x "punto límite" } $_ _(a) Demuestre que $E^compose$ es abierto (no puede usar parte (d))._ == Prueba: Tome $x in E^compose$. Como $x$ es un punto interior de $E$, sabemos que $exists r gt 0$ tal que $B(x; r) subset.eq E$. Suponga, por contradicción, que $B(x; r) sect (E^compose)^complement eq.not nothing$. Entonces, $exists y in B(x; r)$ tal que $y$ no es un punto interior de $E$. Esto implica que $B(y, rho) subset.eq.not E " " forall rho gt 0$, pero como $B(x; r) subset.eq E$, también tenemos que $B(y, rho) subset.eq.not B(x; r) " " forall rho gt 0$. Esto quiere decir que encontramos un punto $y in B(x; r)$ tal que ninguna bola centrada en $y$ está contenida en $B(x; r)$. Por lo tanto, $B(x; r)$ no es abierto. $contradiction$ Entonces: $ &B(x; r) sect (E^compose)^complement eq nothing \ ==> &B(x; r) subset.eq E^compose $ $therefore$ $E^compose$ es abierto. *MEP* === _(b) Pruebe que $E$ es abierto si y sólo si $E^compose eq E$._ == Prueba: $(==>)$ Suponga que $E$ es abierto. Es claro que $E^compose subset.eq E$. Ahora, tome $x in E$ y note que, como $E$ es abierto, $exists r gt 0$ tal que $B(x; r) in E$. Pero esto implica, por definición, que $x in E^compose$. Entonces \ $E subset.eq E^compose$. $therefore E^compose eq E$ $(<==)$ Suponga que $E^compose eq E$. Por (a), sabemos que $E^compose$ es abierto, pero como $E^compose eq E$, tenemos que $E$ es abierto. *MEP* === _(c) Si $G$ es abierto y $G subset.eq E$, demuestre que $G subset.eq E^compose$._ == Prueba: Tome $x in G$, y note que como $G$ es abierto, $exists r gt 0$ tal que $B(x; r) subset.eq G subset.eq E$. Por transitividad, esto quiere decir que $x$ es un punto interior de $E$. Entonces $x in E^compose$. $therefore G subset.eq E^compose$ *MEP* === _(d) Pruebe que $(E^compose)^complement eq overline(E^complement)$._ == Prueba: Note que $(E^compose)^complement eq { x in X | x "no es punto interior de" E }$ y $overline(E^complement) eq E^complement union (E^complement)'$. Suponga que $x in (E^compose)^complement$. === Caso 1 --- $x in.not E$: $x in.not E ==> x in E^complement ==> x in overline(E^complement)$. === Caso 2 --- $x in E$: Como $x$ no es un punto interior de $E$, sabemos que $B(x; r) subset.eq.not E " " forall r gt 0$. Esto implica que $B(x; r) sect E^complement eq.not nothing " " forall r gt 0$. Pero $x in.not E^complement$, así que lo podemos quitar de la bola sin quitar la intersección: $B(x; r) without {x} sect E^complement eq.not nothing " " forall r gt 0$. Por lo tanto, $x in (E^complement)' ==> x in overline(E^complement)$. *MEP* === _(e) Determine si $E^compose eq (overline(E))^compose$. Pruebe ó provea un contraejemplo._ == Prueba: Tome $x in E^compose$, entonces $exists r gt 0$ tal que $B(x; r) subset.eq E ==> B(x; r) subset.eq E union E' eq overline(E) ==> x in (overline(E))^compose$ \ $therefore E^compose subset.eq (overline(E))^compose$. Tome $x in (overline(E))^compose ==> exists r gt 0$ tal que $B(x; r) subset.eq overline(E) eq E union E' eq E union.sq E' without E$. Note que, como esta unión es disjunta, si probamos que $y in B(x; r) and y in.not E'$, entonces $B(x; r) subset.eq E$. Ahora, sea \ $F := {d(x, z) | z in B(x; r) sect E}$. Note que $F subset.eq RR, F eq.not nothing$, y $r$ es cota superior para $F$. Entonces, por la propiedad de la cota superior mínima $exists alpha in RR$ tal que $alpha eq sup(F)$. Suponga, por contradicción, que $B(x; r) sect E^complement eq.not nothing$, entonces $exists y_0 in B(x; r) sect E^complement$. Note que $alpha lt.eq d(x, y_0) lt r$, entonces, por la densidad de los reales, y la abiertitud de las bolas, $exists y in B(x; r) sect E^complement$ tal que \ $alpha lt.eq d(x, y_0) lt d(x, y) lt r ==> alpha lt d(x, y) lt r$. Nuevamente, usando la densidad y la abiertitud, $exists epsilon gt 0$ tal que $alpha lt d(x, y) - epsilon lt d(x, y) lt d(x, y) + epsilon lt r$. Entonces $B(y; epsilon) subset.eq B(x; r)$ y $B(y; epsilon) without {y} sect E eq nothing$. Esto contradice que $B(x; r) subset.eq E union.sq E' without E$. $contradiction$ Entonces $B(x; r) sect E^complement eq nothing$, lo que implica que $B(x; r) sect E' without E eq nothing ==> B(x; r) subset.eq E ==> x in E^compose$. \ $therefore (overline(E))^compose subset.eq E^compose$ $therefore (overline(E))^compose eq E^compose$ *MEP* === _(f) Determine si $overline(E) eq overline(E^compose)$. Pruebe ó provea un contraejemplo._ == Prueba: Tome $E eq (0, 1) union {7}$, entonces $E' eq [0, 1] ==> overline(E) eq [0, 1] union {7}$. Note que $E^compose eq (0, 1) ==> overline(E^compose) eq [0, 1]$. Por lo tanto, $overline(E) subset.eq.not overline(E^compose) ==> overline(E) eq.not overline(E^compose)$. *MEP* === _(g) Si $E subset.eq RR^n$ es convexo, demuestre que $E^compose$ y $overline( E)$ son convexos._ == Prueba: \ \ Se deja como un ejercicio para el profesor ;) \ \ \ === _(h) Pruebe que $E'$ es cerrado._ == Prueba: Tome $x in (E')^complement$ y note que $exists r gt 0$ tal que $B(x; r) without {x} sect E eq nothing$. Entonces $y in B(x; r) ==> exists rho in RR$ con $0 lt rho lt r$ tal que $B(y; rho) subset.eq B(x; r) ==> B(y, rho) without {y} sect E subset.eq B(x; r) without {x} sect E eq nothing$. Entonces $B(y; rho) without {y} sect E eq nothing ==> y in (E')^complement$. Por lo tanto, $B(x; r) subset.eq (E')^complement ==> (E')^complement$ abierto. $therefore E'$ cerrado. *MEP* === _(i) Demuestre que $overline(E)' eq E'$._ == Prueba: Tome $x in overline(E)'$ y note que: $ &U_(r)(x) without {x} sect (E union E') eq.not nothing \ ==> &(U_(r)(x) without {x} sect E) union (U_(r)(x) without {x} sect E') eq.not nothing \ ==> &U_(r)(x) without {x} sect E eq.not nothing \ ==> &x in E' $ $therefore overline(E)' subset.eq E'$ Tome $x in E'$ y note que: $ &U_(r)(x) without {x} sect E eq.not nothing \ ==> &U_(r)(x) without {x} sect (E union E') eq.not nothing \ ==> &U_(r)(x) without {x} sect overline(E) eq.not nothing \ ==> &x in overline(E)' $. $therefore E' subset.eq overline(E)'$ $therefore overline(E)' eq E'$ *MEP* === _(j) Determine si $(E')' eq E'$. Pruebe ó provea un contraejemplo._ == Prueba: Tome $x in (E')'$ y note que: $ &U_(r)(x) without {x} sect E' eq.not nothing " " forall r gt 0 \ ==> &exists y in U_(r)(x) without {x} "tal que" U_(epsilon)(y) without {y} sect E eq.not nothing " " forall epsilon gt 0 \ ==> &exists epsilon gt 0 "tal que" U_(epsilon)(y) subset.eq U_(r)(x) \ ==> &U_(r)(x) without {x} sect E eq.not nothing ==> x in E' $ $therefore (E')' subset.eq E'$ Tome $x in E'$ y note que: $ &U_(r)(x) without {x} sect E eq.not nothing " " forall r gt 0 \ ==> &exists y in U_(r)(x) without {x} and exists epsilon gt 0 "tal que" U_(epsilon)(y) subset.eq U_(r)(x) without {x} "(porque" U_(r)(x) "es abierto)" \ ==> &U_(epsilon)(y) without {y} sect E eq.not nothing ==> y in E' \ ==> &U_(r)(x) without {x} sect E' eq.not nothing ==> x in (E')' $ $therefore E' subset.eq (E')'$ $therefore (E')' eq E'$ *MEP* ] // problema 5 #prob[ _(4 puntos) -- Demuestre que el intervalo $(0, 1)$ no es compacto de forma directa, esto es, encuentre una cubierta abierta de $(0, 1)$ que no posee una subcubierta finita._ == Prueba: Considere la familia $A_n := (1 / n, 1 - 1 / n), n in NN without {1}$. Note que $A_i$ es abierto $forall i in NN without {1}$. Tome $x in (0, 1)$ y note que $0 lt x lt 1$. Entonces $exists k in NN without {1}$ tal que $0 lt 1 / k lt x lt 1 - 1 / k lt 1$, por lo tanto, $x in A_k ==> x in union.big_(n eq 2)^infinity A_n$. Entonces: $ (0, 1) subset.eq union.big_(n eq 2)^infinity A_n ==> union.big_(n eq 2)^infinity "es una cubierta abierta para" (0, 1). $ Sea ${A_1, A_2, ..., A_k}$ una subcolección finita arbitraria de $F := union.big_(n eq 2)^infinity A_n$. Ahora escoja \ $1 / m_0 eq min { 1 / m | (1 / m, 1 - 1 / m) in F }$, y note que $0 lt 1 / m_0$. Entonces, $exists alpha in (0, 1)$ tal que $0 lt alpha lt 1 / m_0$. Entonces $alpha in.not F$. $therefore (0, 1) subset.eq.not F ==> (0, 1)$ no es compacto. *MEP* ] // problema 6 #prob[ _(5 puntos) -- Sean $K_1, K_2, ..., K_n$ subconjuntos compactos del espacio métrico $(X, d)$. Pruebe que: $ K := union.big_(j eq 1)^n K_j $ es compacto._ == Prueba: Sea $U$ una cubierta abierta para $K$. Entonces $U$ cubre a $union.big_(j=1)^n K_j$, lo que implica que $U$ cubre a $K_i " " forall i in {1, 2, ..., n}$. Pero, como $K_i$ es compacto $forall i in {1, 2, ..., n}$, existen subcubiertas abiertas finitas $F_i subset.eq U$ tal que $F_i$ cubre a $K_i " " forall i in {1, 2, ..., n}$. Ahora considere: $ F := union.big_(j eq 1)^n F_j $ Note que, por construcción, $F$ es una cubierta abierta finita que cubre a $K$. Además, $F_i subset.eq U$ \ $forall i in {1, 2, ..., n}$, lo que implica que $F subset.eq U$. Como $U$ era arbitrario, siempre podemos construir una subcubierta abierta finita de $U$ que cubre a $K$. $therefore K$ es compacto. *MEP* ] // problema 7 #prob[ _(4 puntos) -- Dado que $a, b in RR without QQ$ con $a lt b$, definamos el conjunto: $S := { x in QQ | a lt x lt b}$. Demuestre que $S subset.eq QQ$ es cerrado y acotado (en $QQ$), pero no compacto (en $QQ$)._ == Prueba: Por contradicción, suponga que $S' subset.eq.not S$, entonces $S' eq.not nothing ==> exists x in S' without S$. Sin pérdida de generalidad, suponga que $x gt.eq b$. Note que $x in QQ$ y $b in.not QQ$ $==> x eq.not b ==> x gt b$. Pero $x in S' ==> U_(r)(x) without {x} sect S eq.not nothing " " forall r in (0, infinity)$. Ahora, tome $rho eq (x - b) / 2 in (0, infinity)$ y construya $U_(rho)(x)$. Note que: $ y in U_(rho)(x) ==> y gt x - rho eq x - abs(x - b) / 2 eq (2 x - x + b) / 2 eq (x + b) / 2 $ Como $x gt b, exists alpha in (0, infinity)$ tal que $x eq b + alpha$. Entonces: $ &y gt ((b + alpha) + b) / 2 eq (2 b + alpha) / 2 eq (2 b) / 2 + alpha / 2 eq b + alpha / 2 gt b \ ==> &y in.not S ==> U_(rho)(x) without {x} sect S eq nothing. contradiction $ $therefore S' subset.eq S ==> S$ cerrado en $QQ$. Tome $p, q in QQ$ tal que $p lt a$ y $q gt b$. \ $therefore S$ está acotado por $p$ y $q$ en $QQ$. Sea $S_n := B((b - a) / 2; (b - a) / n) subset.eq QQ, n in NN without {1, 2}$. Tome $x in S$ y note que: $a lt x lt b$ \ $==> exists k in NN without {1, 2}$ tal que $a lt (b - a) / 2 - (b - a) / k lt x lt (b - a) / 2 + (b - a) / k lt b ==> x in S_k ==> x in union.big_(n eq 3)^infinity S_n$ es una cubierta abierta para $S$. Tome una subcolección finita arbitraria $F := union {A_1, A_2, ..., A_k} subset.eq union_(n eq 3)^infinity S_n$. Sea $alpha eq (b - a) / j in F$ tal que $abs(alpha - a) eq min {abs(x - a) | x in F}$. Entonces $a lt (b - a) / j ==> exists s in S$ tal que $a lt s lt (b - a) / j$. Pero \ $s in.not F$. Por lo tanto $S subset.eq.not F$. $therefore S$ no es compacto en $QQ$. *MEP* ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/scholarly-tauthesis/0.4.0/template/content/preface.typ
typst
Apache License 2.0
/*** preface.typ * * Write the preface (alkusanat) of your work here. * **/ This #link("https://typst.app/docs/")[typst] document template is intended to support writing theses in the technical fields in Tampere University. The template is based on the earlier one from the Tampere University of Technology, but it has been updated for use in Tampere University from 2019 onwards. Version #version(0,11,0) of the typst compiler does not yet automatically create PDF/A-compliant documents. *Once your thesis is ready, remember to feed it to the PDF/A converter at https://muuntaja.tuni.fi before submitting it*. Acknowledgements to those who contributed to the thesis are generally presented in the preface. It is not appropriate to criticize anyone in the preface, even though the preface will not affect your grade. The preface must fit on one page. Add the date, after which you have not made any revisions to the text, at the end of the preface.
https://github.com/matteobongio/TCR-typ
https://raw.githubusercontent.com/matteobongio/TCR-typ/master/main.typ
typst
#import "@preview/showybox:2.0.1": showybox #import "@preview/codly:0.2.0": * #show: codly-init.with() #import "@preview/lovelace:0.2.0": * #show: setup-lovelace #let comment(body) = { let centered-asterisk = "*" // "\u{2217}" let s = "/" + centered-asterisk + " " + body + " " + centered-asterisk + "/" let t = text(fill: gray.darken(30%), font: "Source Code Pro", s) t } #set page( paper: "a4", numbering: "1", // flipped: true, // columns: 2, // margin: 3%, header: [TCR The minute his head is in view, hit it with the rock!] ) #counter(page).update(1) #codly( languages: ( cpp: ( name: "C++", icon: "", //text(font: "FiraCode Nerd Font", "\u{e61d}"), color: rgb("#2995df") ), ) ) #set heading(numbering: "1.") #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } #outline(indent: auto) Compilation Command `g++ -std=c++11 -O2 -Wall test.cpp -o test` = Template ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using vi = vector<ll>; typedef pair<ll, ll> pii; #define FOR(a, c) for (int(a) = 0; (a) < (c); (a)++) #define all(x) begin(x), end(x) #define allRev(x) rbegin(x), rend(x) #define FAST_IO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); int main() { // freopen("input.txt", "r", stdin); // redirect file to STDIN } ``` 128bit ```cpp using lll = __int128; ostream& operator<<( ostream& o, __int128 n ) { auto t = n<0 ? -n : n; char b[128], *d = end(b); do *--d = '0'+t%10, t /= 10; while (t); if(n<0) *--d = '-'; o.rdbuf()->sputn(d,end(b)-d); return o; } ``` == split str ```cpp vector<string> split_str(string s, const char delim) { vector<string> out; istringstream ss(s); string e; while (getline(ss, e, delim)){ out.push_back(e); } return out; } ``` == Vectors ```cpp // insert v.insert(v.begin() + index, value); // head or index | O(n) v.push_back(value); // tail | O(1) access auto v_head = v.front(); // head | O(1) auto v_index = v.at(index); // index (or v[i]) | O(1) auto v_tail = v.back(); // tail | O(1) // remove v.erase(v.begin() + index); // head or index | O(n) v.pop_back(); // tail | O(1) // clear - common to all data structures v.clear(); // O(n) ``` == Lists ```cpp list<int> l; int value = 1; int index = 1; // insert l.push_front(value); // head | O(1) l.insert(l.begin(), index, value); // index | O(n) l.push_back(value); // tail | O(1) // access auto v_head = l.front(); // head | O(1) auto v_value = *next(l.begin(), 1); // index | O(n) auto v_tail = l.back(); // tail | O(1) // remove auto pos = next(l.begin(),index); l.pop_front(); // head | O(1) l.erase(pos); // index | O(1) + O(n) l.pop_back(); // tail | O(1) list<int> l = {1,2,3}; list<int> l2; l2.splice(l2.begin(), l); // transfer elements between list l.remove(1); // remove an element by value l.unique(); // remove duplicates l.merge(l2); // merge two sorted lists ``` == Pairs and tuples ```cpp pair<int,int> p = {1,2}; cout << p.first << ' ' << p.second << '\n'; pair<int,int> p2 = {3,4}; p.swap(p2); tuple<int,int,int> t = {1,2,3}; cout << get<0>(t) << get<1>(t) << get<2>(t) << '\n'; ``` == Map Map: $O log n$ Unordered Map: $O 1$ ```cpp using pss = pair<string,string>; int main() { map<string,string> m; // unordered_map<string,string> m; m.insert(pss("key", "value")); // insert string value = m.at("key"); // access (or m["key"]) m.erase("key"); // remove bool exists = (m.find("key") != m.end()); // find // iterate for(auto &it: m) { cout << it.first << ' ' << it.second; } } ``` == Set Set: $O log n$ Unordered Set: $O 1$ ```cpp int main() { set<int> s; // unordered_set<int> s; int value = 1; s.insert(value); // insert s.erase(value); // remove bool exists = (s.find(value) != s.end()); // find // iterate for(auto &i: s) { cout << i; } cout << '\n'; } ``` = Math $ x = frac(- b plus.minus sqrt(b^2 - 4 a c) , 2 a)\ sin(v + w) = sin(v) cos(w) + cos(v)sin(w)\ cos(v + w) = cos(v)cos(w) + sin(v)sin(w) $ == Law of sines $ sin(A) / a = sin(B)/b = sin(C)/c $ == Law of cosines $ a^2 = b^2 + c^2 - 2 b c cos(alpha) $ == Complex numbers $ r = sqrt(a^2 + b^2)\ theta = arctan(b/a)\ a = r cos theta\ b = r sin theta\ z^n = r^n (cos(n theta) + i sin(n theta) = r e^(i n theta))\ root(n, r) e^(i (frac(theta + 2 pi k, n))) $ == Permutations $ n "elements of length" r\ "with repititions" n^r\ "without repititions" frac(n!, (n - r)!)\ "The number of distinguishable permutations that can be formed from a collection of"\ n "objects," " where object" o_i "appears" k_i "times is:"\ frac(n!,k_1! k_2! k_3! ...) $ e.g. MISSISSIPPI: 1M 4I 4S 2P $ n = 1 + 4 + 4 + 2 = 11\ 11!/( 1!4!4!2! ) = 34 650 $ == Combinations (order doesn t matter) $ ""_n C _r = frac(n!, r!(n - r)!) = vec(n, r) $ with repetitions: $ ""_(n + r - 1)C_r $ == Sequences $ A_n = n/2(2a_1 + (n-1)d) $ $ G_n = a_1(1-r^n)/(1-r) $ = Number Theory == GCD ```cpp template <typename T> T gcd(T a, T b) { if (b == 0) { return a; } return gcd(b, a % b); } ``` Iter ```cpp template <typename T> T gcd(T a, T b) { T result = min(a, b); while (result > 0) { if (a % result == 0 && b % result == 0) { break; } result--; } return result; } ``` == LCM $ a * b = gcd(a, b) * "lcm"(a, b) $ ```cpp T lcm(T a, Tb) { return (a*b) / gcd(a, b); } ``` == Primes ```cpp bool isPrime(int n) { if (n < 2) { return false; } for (int x = 2; x * x <= n; ++x) { if (n % x == 0) { return false; } } return true; } vector<int> primeFactorisation(int n) { vector<int> facts; for (int x = 2; x * x <= n; ++x) { while (n % x == 0) { facts.push_back(x); n /= x; } } if (n > 1) { facts.push_back(n); } return facts; } ``` == Complex Numbers ```cpp constexpr double pi = 3.1415926535897932384626433; // or std::acos(-1) struct Complex { using T = Complex; double u,v; Complex(double u=0, double v=0) : u{u}, v{v} {} T operator+(T r) const { return {u+r.u, v+r.v}; } T operator-(T r) const { return {u-r.u, v-r.v}; } T operator*(T r) const { return {u*r.u - v*r.v, u*r.v + v*r.u}; } T operator/(T r) const { auto norm = r.u*r.u+r.v*r.v; return {(u*r.u + v*r.v)/norm, (v*r.u - u*r.v)/norm}; } T operator*(double r) const { return T{u*r, v*r}; } T operator/(double r) const { return T{u/r, v/r}; } T inv() const { return T{1,0}/ *this; } T conj() const { return T{u, -v}; } static T root(ll k){ return {cos(2*pi/k), sin(2*pi/k)}; } bool zero() const { return max(abs(u), abs(v)) < 1e-6; } }; ``` == Matrix ```cpp #define REP(i, n) for(auto i = decltype(n)(0); i < (n); i++) using T = double; constexpr T EPS = 1e-8; template<int R, int C> using M = array<array<T,C>,R>; // matrix template<int R, int C> T ReducedRowEchelonForm(M<R,C> &m, int rows) { // return the determinant int r = 0; T det = 1; // MODIFIES the input for(int c = 0; c < rows && r < rows; c++) { int p = r; for(int i=r+1; i<rows; i++) if(abs(m[i][c]) > abs(m[p][c])) p=i; if(abs(m[p][c]) < EPS){ det = 0; continue; } swap(m[p], m[r]); det = -det; T s = 1.0 / m[r][c], t; det *= m[r][c]; REP(j,C) m[r][j] *= s; // make leading term in row 1 REP(i,rows) if (i!=r){ t = m[i][c]; REP(j,C) m[i][j] -= t*m[r][j]; } ++r; } return det; } bool error, inconst; // error => multiple or inconsistent template<int R,int C> // Mx = a; M:R*R, v:R*C => x:R*C M<R,C> solve(const M<R,R> &m, const M<R,C> &a, int rows){ M<R,R+C> q; REP(r,rows){ REP(c,rows) q[r][c] = m[r][c]; REP(c,C) q[r][R+c] = a[r][c]; } ReducedRowEchelonForm<R,R+C>(q,rows); M<R,C> sol; error = false, inconst = false; REP(c,C) for(auto j = rows-1; j >= 0; --j){ T t=0; bool allzero=true; for(auto k = j+1; k < rows; ++k) t += q[j][k]*sol[k][c], allzero &= abs(q[j][k]) < EPS; if(abs(q[j][j]) < EPS) error = true, inconst |= allzero && abs(q[j][R+c]) > EPS; else sol[j][c] = (q[j][R+c] - t) / q[j][j]; // usually q[j][j]=1 } return sol; } ``` = Sorting and Searching ```cpp // Binary predicate int compare(const void* ap, const void* bp) { // Typecasting const int* a = (int*)ap; const int* b = (int*)bp; if (*a < *b) return -1; else if (*a > *b) return 1; else return 0; } int main() { vector<int> vec; auto first = vec.begin(); auto last = vec.end(); sort(first, last); // reverse: sort(vec.rbegin(), vec.rend()) // sorting arrays: a[]; sort(a, a+n) int key = 1; bool isPresent = binary_search(first, last, key); int* p1 = (int*)bsearch(&key, vec.data(), vec.size(), sizeof(int), compare) } ``` = Graph == Dijkstra ```cpp // Time Complexity: O(E log V) // Space Complexity: O(V + E) #define ll long long #define fi first #define se second typedef pair<ll, ll> ii; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll v, e; cin >> v >> e; vector<ii> adj[v]; ll dist[v]; for (ll i = 0; i < v; i++) dist[i] = INT64_MAX; for (ll i = 0; i < e; i++) { ll u, v, wi; cin >> u >> v >> wi; u--, v--; adj[u].push_back(ii(v, wi)); adj[v].push_back(ii(u, wi)); } priority_queue<ii> q; // (dist, node) q.push(ii(-0, 0)); while(!q.empty()) { ii cur = q.top(); q.pop(); ll curDist = -cur.fi, curNode = cur.se; if (curDist > dist[curNode]) continue; for (ll i = 0; i < adj[curNode].size(); i++) { ii nx = adj[curNode][i]; ll nxDist = curDist + nx.se; if (nxDist < dist[nx.fi]) { dist[nx.fi] = nxDist; q.push(ii(-nxDist, nx.fi)); } } } cout << dist[v-1] << '\n'; } ``` == <NAME> ```cpp int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll t; cin >> t; while (t--) { string s; cin >> s; ll n = s.size(); ll adj[n][n]; adj[0][0] = 0; for (ll j=1; j<n; j++) adj[0][j] = (s[j]=='Y'?1:1e9); for (ll i=1; i<n; i++) { cin >> s; for (ll j=0; j<n; j++) { if (i == j) adj[i][j] = 0; else adj[i][j] = (s[j]=='Y'?1:1e9); } } for (ll k=0; k<n; k++) { for (ll i=0; i<n; i++) { for (ll j=0; j<n; j++) { adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]); } } } ll mxVal = 0, mxInd = 0; for (ll i=0; i<n; i++) { ll ans = 0; for (ll j=0; j<n; j++) { if (adj[i][j] == 2) ans++; } if (ans > mxVal) { mxVal = ans; mxInd = i; } } cout << mxInd << ' ' << mxVal << '\n'; } } ``` == Breadth First Search ```cpp void bfs(vector<vector<int>>& adj, int s, vector<bool>& visited) { queue<int> q; visited[s] = true; q.push(s); while (!q.empty()) { int curr = q.front(); q.pop(); for (int x : adj[curr]) { if (!visited[x]) { visited[x] = true; q.push(x); } } } } void addEdge(vector<vector<int>>& adj, int u, int v) { adj[u].push_back(v); adj[v].push_back(u); // Undirected Graph } int main() { // Number of vertices in the graph int V = 5; // Adjacency list representation of the graph vector<vector<int>> adj(V); addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 4); // Mark all the vertices as not visited vector<bool> visited(V, false); // Perform BFS traversal starting from vertex 0 bfs(adj, 0, visited); return 0; } ``` == Depth First Search ```cpp // Function to add an edge to the adjacency list void addEdge(vector<vector<int>> &adj, int s, int t){ // Add edge from vertex s to t adj[s].push_back(t); // Due to undirected Graph adj[t].push_back(s); } // Recursive function for DFS traversal void DFSRec(vector<vector<int>> &adj, vector<bool> &visited, int s){ // Mark the current vertex as visited visited[s] = true; // Print the current vertex cout << s << " "; // Recursively visit all adjacent vertices that are not visited yet for (int i : adj[s]) if (visited[i] == false) DFSRec(adj, visited, i); } // Main DFS function that initializes the visited array and call DFSRec void DFS(vector<vector<int>> &adj, int s){ vector<bool> visited(adj.size(), false); // Call the recursive DFS function DFSRec(adj, visited, s); } int main(){ int V = 5; // Number of vertices in the graph // Create an adjacency list for the graph vector<vector<int>> adj(V); // Define the edges of the graph vector<vector<int>> edges={{1, 2},{1, 0},{2, 0},{2, 3},{2, 4}}; // Populate the adjacency list with edges for (auto &e : edges) addEdge(adj, e[0], e[1]); int source = 1; // Starting vertex for DFS cout << "DFS from source: " << source << endl; DFS(adj, source); // Perform DFS starting from the source vertex return 0; } ``` = Data Srtuctures == Trie ```cpp const int ALPHABET_SIZE = 26; inline int mp(char c) { return c - 'a'; } struct Node { Node* ch[ALPHABET_SIZE]; bool isleaf = false; Node() { for(int i = 0; i < ALPHABET_SIZE; ++i) ch[i] = nullptr; } void insert(string &s, int i = 0) { if (i == s.length()) isleaf = true; else { int v = mp(s[i]); if (ch[v] == nullptr) ch[v] = new Node(); ch[v]->insert(s, i + 1); } } bool contains(string &s, int i = 0) { if (i == s.length()) return isleaf; else { int v = mp(s[i]); if (ch[v] == nullptr) return false; else return ch[v]->contains(s, i + 1); } } void cleanup() { for (int i = 0; i < ALPHABET_SIZE; ++i) if (ch[i] != nullptr) { ch[i]->cleanup(); delete ch[i]; } } }; ``` == Fenwick ```cpp template <class T> struct FenwickTree { // use 1 based indices!!! int n; vector<T> tree; FenwickTree(int n) : n(n) { tree.assign(n + 1, 0); } T query(int l, int r) { return query(r) - query(l - 1); } T query(int r) { T s = 0; for(; r > 0; r -= (r & (-r))) s += tree[r]; return s; } void update(int i, T v) { for(; i <= n; i += (i & (-i))) tree[i] += v; } }; ``` == Heap ```cpp vector<int> v1 = { 20, 30, 40, 25, 15 }; // Converting vector into a heap make_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap using front() cout << v1.front() << endl; // add element v1.push_back(1); push_heap(v1.begin(), v1.end()); // remove element // using pop_heap() function to move the largest element to the end pop_heap(v1.begin(), v1.end()); // actually removing the element from the heap using pop_back() v1.pop_back(); ``` == Linked List ```cpp list<int> l = {1, 2, 3}; l.push_front(0); l.push_back(4); l.unique(); ``` == Search Tree ```cpp template <typename T> struct Node { T data; Node *left; Node *right; }; template <typename T> Node<T> *newNode(T data) { Node<T> *n = new Node<T>; n->data = data; n->left = n->right = nullptr; return n; } template <typename T> Node<T> *insertNode(Node<T> *root, int data) { if (root == nullptr) { return newNode(data); } if (data < root->data) { root->left = insertNode(root->left, data); } else if (data > root->data) { root->right = insertNode(root->right, data); } return root; } template <typename T> Node<T> *searchNode(Node<T> *root, int key) { if (root == nullptr || root->data == key) { return root; } if (root->data < key) { return searchNode(root->right, key); } return searchNode(root->left, key); } template <typename T> Node<T> *minValueNode(Node<T> *node) { Node<T> *current = node; while (current && current->left != nullptr) { current = current->left; } return current; } template <typename T> Node<T> *deleteNode(Node<T> *root, int data) { if (root == nullptr) return root; if (data < root->data) { root->left = deleteNode(root->left, data); } else if (data > root->data) { root->right = deleteNode(root->right, data); } else { if (root->left == nullptr) { Node<T> *temp = root->right; delete root; return temp; } else if (root->right == nullptr) { Node<T> *temp = root->left; delete root; return temp; } Node<T> *temp = minValueNode(root->right); root->data = temp->data; root->right = deleteNode(root->right, temp->data); } return root; } ``` = Libraries == BigInt ```cpp class BigInt{ string digits; public: //Constructors: BigInt(unsigned long long n = 0); BigInt(string &); BigInt(const char *); BigInt(BigInt &); //Helper Functions: friend void divide_by_2(BigInt &a); friend bool Null(const BigInt &); friend int Length(const BigInt &); int operator[](const int)const; /* * * * Operator Overloading * * * */ //Direct assignment BigInt &operator=(const BigInt &); //Post/Pre - Incrementation BigInt &operator++(); BigInt operator++(int temp); BigInt &operator--(); BigInt operator--(int temp); //Addition and Subtraction friend BigInt &operator+=(BigInt &, const BigInt &); friend BigInt operator+(const BigInt &, const BigInt &); friend BigInt operator-(const BigInt &, const BigInt &); friend BigInt &operator-=(BigInt &, const BigInt &); //Comparison operators friend bool operator==(const BigInt &, const BigInt &); friend bool operator!=(const BigInt &, const BigInt &); friend bool operator>(const BigInt &, const BigInt &); friend bool operator>=(const BigInt &, const BigInt &); friend bool operator<(const BigInt &, const BigInt &); friend bool operator<=(const BigInt &, const BigInt &); //Multiplication and Division friend BigInt &operator*=(BigInt &, const BigInt &); friend BigInt operator*(const BigInt &, const BigInt &); friend BigInt &operator/=(BigInt &, const BigInt &); friend BigInt operator/(const BigInt &, const BigInt &); //Modulo friend BigInt operator%(const BigInt &, const BigInt &); friend BigInt &operator%=(BigInt &, const BigInt &); //Power Function friend BigInt &operator^=(BigInt &,const BigInt &); friend BigInt operator^(BigInt &, const BigInt &); //Square Root Function friend BigInt sqrt(BigInt &a); //Read and Write friend ostream &operator<<(ostream &,const BigInt &); friend istream &operator>>(istream &, BigInt &); }; BigInt::BigInt(string & s){ digits = ""; int n = s.size(); for (int i = n - 1; i >= 0;i--){ if(!isdigit(s[i])) throw("ERROR"); digits.push_back(s[i] - '0'); } } BigInt::BigInt(unsigned long long nr){ do{ digits.push_back(nr % 10); nr /= 10; } while (nr); } BigInt::BigInt(const char *s){ digits = ""; for (int i = strlen(s) - 1; i >= 0;i--) { if(!isdigit(s[i])) throw("ERROR"); digits.push_back(s[i] - '0'); } } BigInt::BigInt(BigInt & a){ digits = a.digits; } bool Null(const BigInt& a){ if(a.digits.size() == 1 && a.digits[0] == 0) return true; return false; } int Length(const BigInt & a){ return a.digits.size(); } int BigInt::operator[](const int index)const{ if(digits.size() <= index || index < 0) throw("ERROR"); return digits[index]; } bool operator==(const BigInt &a, const BigInt &b){ return a.digits == b.digits; } bool operator!=(const BigInt & a,const BigInt &b){ return !(a == b); } bool operator<(const BigInt&a,const BigInt&b){ int n = Length(a), m = Length(b); if(n != m) return n < m; while(n--) if(a.digits[n] != b.digits[n]) return a.digits[n] < b.digits[n]; return false; } bool operator>(const BigInt&a,const BigInt&b){ return b < a; } bool operator>=(const BigInt&a,const BigInt&b){ return !(a < b); } bool operator<=(const BigInt&a,const BigInt&b){ return !(a > b); } BigInt &BigInt::operator=(const BigInt &a){ digits = a.digits; return *this; } BigInt &BigInt::operator++(){ int i, n = digits.size(); for (i = 0; i < n && digits[i] == 9;i++) digits[i] = 0; if(i == n) digits.push_back(1); else digits[i]++; return *this; } BigInt BigInt::operator++(int temp){ BigInt aux; aux = *this; ++(*this); return aux; } BigInt &BigInt::operator--(){ if(digits[0] == 0 && digits.size() == 1) throw("UNDERFLOW"); int i, n = digits.size(); for (i = 0; digits[i] == 0 && i < n;i++) digits[i] = 9; digits[i]--; if(n > 1 && digits[n - 1] == 0) digits.pop_back(); return *this; } BigInt BigInt::operator--(int temp){ BigInt aux; aux = *this; --(*this); return aux; } BigInt &operator+=(BigInt &a,const BigInt& b){ int t = 0, s, i; int n = Length(a), m = Length(b); if(m > n) a.digits.append(m - n, 0); n = Length(a); for (i = 0; i < n;i++){ if(i < m) s = (a.digits[i] + b.digits[i]) + t; else s = a.digits[i] + t; t = s / 10; a.digits[i] = (s % 10); } if(t) a.digits.push_back(t); return a; } BigInt operator+(const BigInt &a, const BigInt &b){ BigInt temp; temp = a; temp += b; return temp; } BigInt &operator-=(BigInt&a,const BigInt &b){ if(a < b) throw("UNDERFLOW"); int n = Length(a), m = Length(b); int i, t = 0, s; for (i = 0; i < n;i++){ if(i < m) s = a.digits[i] - b.digits[i]+ t; else s = a.digits[i]+ t; if(s < 0) s += 10, t = -1; else t = 0; a.digits[i] = s; } while(n > 1 && a.digits[n - 1] == 0) a.digits.pop_back(), n--; return a; } BigInt operator-(const BigInt& a,const BigInt&b){ BigInt temp; temp = a; temp -= b; return temp; } BigInt &operator*=(BigInt &a, const BigInt &b) { if(Null(a) || Null(b)){ a = BigInt(); return a; } int n = a.digits.size(), m = b.digits.size(); vector<int> v(n + m, 0); for (int i = 0; i < n;i++) for (int j = 0; j < m;j++){ v[i + j] += (a.digits[i] ) * (b.digits[j]); } n += m; a.digits.resize(v.size()); for (int s, i = 0, t = 0; i < n; i++) { s = t + v[i]; v[i] = s % 10; t = s / 10; a.digits[i] = v[i] ; } for (int i = n - 1; i >= 1 && !v[i];i--) a.digits.pop_back(); return a; } BigInt operator*(const BigInt&a,const BigInt&b){ BigInt temp; temp = a; temp *= b; return temp; } BigInt &operator/=(BigInt& a,const BigInt &b){ if(Null(b)) throw("Arithmetic Error: Division By 0"); if(a < b){ a = BigInt(); return a; } if(a == b){ a = BigInt(1); return a; } int i, lgcat = 0, cc; int n = Length(a), m = Length(b); vector<int> cat(n, 0); BigInt t; for (i = n - 1; t * 10 + a.digits[i] < b;i--){ t *= 10; t += a.digits[i] ; } for (; i >= 0; i--){ t = t * 10 + a.digits[i]; for (cc = 9; cc * b > t;cc--); t -= cc * b; cat[lgcat++] = cc; } a.digits.resize(cat.size()); for (i = 0; i < lgcat;i++) a.digits[i] = cat[lgcat - i - 1]; a.digits.resize(lgcat); return a; } BigInt operator/(const BigInt &a,const BigInt &b){ BigInt temp; temp = a; temp /= b; return temp; } BigInt &operator%=(BigInt& a,const BigInt &b){ if(Null(b)) throw("Arithmetic Error: Division By 0"); if(a < b){ return a; } if(a == b){ a = BigInt(); return a; } int i, lgcat = 0, cc; int n = Length(a), m = Length(b); vector<int> cat(n, 0); BigInt t; for (i = n - 1; t * 10 + a.digits[i] < b;i--){ t *= 10; t += a.digits[i]; } for (; i >= 0; i--){ t = t * 10 + a.digits[i]; for (cc = 9; cc * b > t;cc--); t -= cc * b; cat[lgcat++] = cc; } a = t; return a; } BigInt operator%(const BigInt &a,const BigInt &b){ BigInt temp; temp = a; temp %= b; return temp; } BigInt &operator^=(BigInt & a,const BigInt & b){ BigInt Exponent, Base(a); Exponent = b; a = 1; while(!Null(Exponent)){ if(Exponent[0] & 1) a *= Base; Base *= Base; divide_by_2(Exponent); } return a; } BigInt operator^(BigInt & a,BigInt & b){ BigInt temp(a); temp ^= b; return temp; } void divide_by_2(BigInt & a){ int add = 0; for (int i = a.digits.size() - 1; i >= 0;i--){ int digit = (a.digits[i] >> 1) + add; add = ((a.digits[i] & 1) * 5); a.digits[i] = digit; } while(a.digits.size() > 1 && !a.digits.back()) a.digits.pop_back(); } BigInt sqrt(BigInt & a){ BigInt left(1), right(a), v(1), mid, prod; divide_by_2(right); while(left <= right){ mid += left; mid += right; divide_by_2(mid); prod = (mid * mid); if(prod <= a){ v = mid; ++mid; left = mid; } else{ --mid; right = mid; } mid = BigInt(); } return v; } istream &operator>>(istream &in,BigInt&a){ string s; in >> s; int n = s.size(); for (int i = n - 1; i >= 0;i--){ if(!isdigit(s[i])) throw("INVALID NUMBER"); a.digits[n - i - 1] = s[i]; } return in; } ostream &operator<<(ostream &out,const BigInt &a){ for (int i = a.digits.size() - 1; i >= 0;i--) cout << (short)a.digits[i]; return cout; } ``` = Pseudo Code #pseudocode-list( indentation-guide-stroke: .5pt + gray.darken(20%), )[ + *Dijkstra (G, v)* - *input* connected weighted graph $G$ with node $v$ - *output* function $d$ yielding for every node the length of a shortest path to $v$ - $S <- "nodes"(G)$ #comment[ initialize ToDo list ] + *For All* {$u in "nodes"(G)$} + $d[u] <-$ *if* $u = v$ *then* 0 *else* $infinity$ + #comment[initialize $d$] + *While* $S$ is not empty + $u <-$ node in $S$ such that $d[u]$ is minimal + remove $u$ from $S$ + *For All* $z \in S$ with $(u, z) in "edges"(G)$ + $d[u] <- min(d[z], d[u] + "weight"[u][z])$ + *Return* d ]
https://github.com/MrToWy/Bachelorarbeit
https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/glossary.typ
typst
#import "@preview/gloss-awe:0.0.5": * // Defining the Glossary Pool with definitions. #let glossary-pool = ( StudyBase: ( description: [ Das gemeinsame Backend von verschiedenen Anwendungen der Abteilung Informatik. ] ), StudyGraph: ( description: [ Eine Anwendung, die den Zusammenhang zwischen Studieninhalten, Modulen und Studiengängen in einer Graphenstruktur visualisiert. ] ), StudyPlan: ( description: [ Eine Anwendung, mit der Studierende ihr Studium individuell planen können. ] ), Controller: ( description: [ Controller sind für die Bearbeitung eingehender Anfragen und die Rückgabe von Antworten an den Client zuständig. @nestDocumentation ] ), NestJS: ( description: [ Ein auf JavaScript basierendes Framework für serverseitige Anwendungen. @nestDocumentation ] ), Prisma:( description: [ "Automatisch generierter und typsicherer Datenbankabfrage-Generator für Node.js & TypeScript" @prisma ] ) )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/modules/base.typ
typst
Apache License 2.0
// path: may_import.typ ----- #import "may_import.typ"
https://github.com/505000677/2024SpringNote
https://raw.githubusercontent.com/505000677/2024SpringNote/main/2056/note-1.typ
typst
#import "../tizart.typ": * #show: project.with( title: "笔记", authors: (yuanxiang,), date: datetime.today() ) #show link: underline #outline() /*#lorem(5)*/ #set heading(numbering: "1.1.") = Day1 #definition(name: "Big Data Denfinition - The Three VS")[ #block(inset: (left: 2em))[ - *Volume* - size does matter! - *Velocity* - data at speed - *Variety* -heterogeneity is the rule 多样性 ] ] #definition(name:"Moore’s Law")[ Moore's law is the observation that, over the history of computing hardware, the number of transistors in a dense integrated circuit doubles approximately every two years. The law is named after <NAME>, co-founder of Intel Corporation, who described the trend in his 1965 paper. ] #definition(name:"Bezos' law ")[ Bezos' law is the observation that, over the history of cloud, a unit of computing power price is reduced by 50% approximately every 3 years ] == Phases in the Big Data Pipeline #figure( image("day1.png", width: 80%) ) - Big Data Processing goes well beyond data storage - Must consider end-to-end and human aspect [1] == References - [1] The Beckman Report on Database Research By Abadi et al, October 2013 #link("http://beckman.cs.wisc.edu") - [2] Big Data and Its Technical Challenges By Jagadish, Gehrke, Labrinidis, Papakonstantinou, Patel, Ramakrishnan, and Shahabi, Communications of the ACM, July 2014 #link("http://bit.ly/bigdatachallenges") #definition(name:"What is Data?")[ - Collection of data objects and their attributes - An attribute is a property or characteristic of an object - Examples: eye color of a person, temperature, etc. - Attribute is also known as variable, field, characteristic, dimension, or feature - A collection of attributes describe an object - Object is also known as record, point, case, sample, entity, or instance ] #figure( image("whatsData.png", width: 41%) ) #clarification(name: "A More Complete View of Data")[ - Data may have parts - Attributes (objects) may have relationships with other attributes (objects) - More generally, data may have structure - Data can be incomplete ] #definition(name:"Attribute Values")[ - Attribute values are numbers or symbols assigned to an attribute for a particular object - Distinction between attributes and attribute values - Same attribute can be mapped to different attribute values #example[ height can be measured in feet or meters] - Different attributes can be mapped to the same set of values #example[: Attribute values for ID and age are integers] - But properties of attribute values can be different ] = Day2 #definition(name:"")[ ] == Many types of charts #figure( image("day2.png", width: 80%), caption: [ A step in the molecular testing pipeline of our lab. ], ) === Scatter plots: - 可以把俩组数据,比较我们去观察预测值和观测值 - 可以去玩graph #link("https://developers.google.com/chart/interactive/docs/gallery") #example("Dataset #1") - Coffee sales values over time , for two stores: - we can used Bar charts Or Scatter plots or Line charts /* #figure( image("", width: auto), caption: [ ], ) */ == Dateset #2 - we can do Bar charts == Dataset #3 == Data Quality - Poor data quality negatively affects many data processing efforts == Noise - Noise refers to modification of original values - Examples: distortion of a person's voice when talking on a poor phone and “snow” on television screen == Outliers - *Outliers* are data objects with characteristics that are considerably different than most of the other data objects in the data set - Case 1: Outliers are noise that interferes with data analysis - Case 2: Outliers are the goal of our analysis - Credit card fraud - Intrusion detection == Missing values - Reasons for missing values - Information is not collected (e.g., people decline to give their age and weight) - Attributes may not be applicable to all cases (e.g., annual income is not applicable to children) - Handling missing values - Eliminate data objects or variables - Estimate missing values (imputation) - Example: time series of temperature - Example: census results - Ignore the missing value during analysis == Duplicate Data - Data set may include data objects that are duplicates, or almost duplicates of one another - Major issue when merging data from heterogeneous sources - Examples: - Same person with multiple email addresses - Data cleaning - Process of dealing with duplicate data issues = Day3 Similarity and Distance #definition(name: "Eucliean Distance")[ - Euclidean distance is the "ordinary" straight-line distance between two points in Euclidean space. - $d(x,y)=sqrt({sum_{k=1}^{n}(x_k-y_k)^2}) $ - where n is the number of dimensions (attributes) in the data set and $x_k$ and $y_k$ are, respectively, the kth attributes (components) of data objects x and y. ] #definition(name:" Minkowski Distance")[ - The Minkowski distance is a generalization of the Euclidean distance - $d(x,y)=({sum_{k=1}^{n}|x_k-y_k|^p})^{1/p}$ - where p is a parameter that determines the order of the Minkowski metric - When p=1, the distance is Manhattan distance - When p=2, the distance is Euclidean distance - As p approaches infinity, the Minkowski distance approaches the Chebyshev distance ] #clarification(name:"Common Properties of a Distance")[ - Distance, such as the Euclidean distance, have some well known properties: - Nonnegativity: $d(x,y)>=0$ for all x and y and d(x,y) = 0 only if x=y. (Positive definiteness) - Symmetry: $d(x,y)=d(y,x)$ for all x and y. (Symmetry) - Triangle inequality: $d(x,z) <= d(x,y)+ d(y,z)$ for all x, y, and z. (Triangle inequality) - where d(x,y) is the distance between objects x and y - A distance that satisfies these properties is known as a metric ] #clarification(name:" Common Properties of a Similarity")[] #clarification(name:" Similarity Between Binary Vectors")[] #example(name:" SMC versus Jacard : Example")[ - x= 1 0 0 0 0 0 0 0 0 0 - y= 0 0 0 0 0 0 1 0 0 1 - $f_(01)$ = 2 - $f_(00)$ = 7 - $f_(10)$ = 1 - $f_(11)$ = 0 - SMC = $(f_(11)+f_(00))/(f_(11)+f_(00)+f_(10)+f_(01)) = 7/10=0.7$ - J = $(f_(11))/(f_(11)+f_(10)+f_(01)) = 0/3=0$ ] #clarification(name:" Cosine Similarity")[ - If $d_1$ and $d_2$ are two documents, then the cosine similarity between them is defined as: - $cos(d_1,d_2)= (<d_1,d_2>)/(||d_1||*||d_2||)$ - where $(<d_1,d_2>)$ indicates inner product or vector dot product of vector, and $||d||$ is the length (norm) of vector $d$ ] = Day4 #definition(name:"Comparison of Proximity Measures")[ - Domain of application - Similarity measures tend to be specific to the type of attribute and data - Record data, images, graphs, sequences, 3D-protein structure, etc. tend to have different measures - However, one can talk about various properties that you would like a proximity measure to have - Symmetry is a common one - Tolerance to noise and outliers is another - Ability to find more types of patterns? - Many others possible - The measure must be applicable to the data and produce results that agree with domain knowledge ] #definition(name:"Density")[ - Measures the degree to which data objects are close to each other in a specified area - The notion of density is closely related to that of proximity - Concept of density is typically used for clustering and anomaly detection - Examples: - Euclidean density - Euclidean density = number of points per unit volume - Probability density - Estimate what the distribution of the data looks like - Graph-based density - Connectivity ] #example(name:" Eulidean Density: Grid-based Approach")[ - Euclidean density = number of points per unit volume - Simplest approach is to divide region into a number of rectangular cells of equal volume and define density as $"#"$ of points the cell contains #figure( image("den.png", width: 80%) ) ] == Data preprocessing #definition(name:"Aggregation")[ - Combining two or more attributes (or objects) into a single attribute (or object) - Purpose - Data reduction - Reduce the number of attributes or objects - Change of scale - Cities aggregated into regions, states, countries, etc. - Days aggregated into weeks, months, or years - More “stable” data - Aggregated data tends to have less variability ] #example(name:"Example: Precipitation in Australia")[ - This example is based on precipitation in Australia from the period 1982 to 1993. The next slide shows - A histogram for the standard deviation of average monthly precipitation for 3,030 0.5◦ by 0.5◦ grid cells in Australia, and - A histogram for the standard deviation of the average yearly precipitation for the same locations. - The average yearly precipitation has less variability than the average monthly precipitation. - All precipitation measurements (and their standard deviations) are in centimeters. #figure( image("pre.png", width: 80%) ) ] #definition(name:"Sampling")[ - Sampling is the process of selecting a subset of data objects - Purpose - Data reduction - Speed up the data mining process - May improve the performance of the model - May improve the quality of the model - Sampling is the main technique employed for data reduction. - It is often used for both the preliminary investigation of the data and the final data analysis. - Statisticians often sample because obtaining the entire set of data of interest is too expensive or time consuming. - Sampling is typically used in data mining because processing the entire set of data of interest is too expensive or time consuming. - The key principle for effective sampling is the following: - Fundamental for proper sampling: - Must avoid having a sample that is not representative of the entire “population” - i.e., must avoid sample bias - Example: Literary Digest poll in the 1936 presidential election - Surveyed over two million people, chosen from the magazine's subscriber list, phone books, and car registrations. - Sample was not representative of entire population of voters (not everyone could afford a phone or a car during the Depression!) - Using a sample will work almost as well as using the entire data set, if the sample is representative - A sample is representative if it has approximately the same properties (of interest) as the original set of data - Example: Original dataset - [10,20,40,30] locations with temperature in $[<-10], [-10,0],[0,20],[>20]$. After sampling, we have [2,4,8,6] samples in these intervals. #figure( image("ssize.png", width: 80%) ) ] #clarification(name:"Types of Sampling")[ - Simple random sample without replacement (SRSWOR): - Draw s of the N tuples (s << N) - Probability of drawing any one tuple is 1/N -> 1/(N-1) -> ... - Once an object is drawn, it is removed from the population - Simple random sample with replacement (SRSWR): - Draw s of the N tuples (s << N) - Each time a tuple is drawn, it is replaced (i.e., placed back into original set, so that it may be drawn again) - Stratified sampling - Split the data into several partitions; then draw random samples from each partition ] #definition(name:"Feature Subset Selection")[ - Reduce the dimensionality of data - Redundant features - Duplicate much or all of the information contained in one or more other attributes - Example: purchase price of a product and the amount of sales tax paid - Irrelevant features - Contain no information that is useful for the data mining task at hand - Example: students' ID is often irrelevant to the task of predicting students' GPA - Many techniques developed, especially for classification ] = Day5 SQL #definition(name:"mean(or average)")[ - Arithmetic mean (or average) is the most common and effective measure of the “center” of a set of data - $overline(x)= (sum_(i=1)^N x_i )/N$ - - If values xi are associated with weights wi, we have the weighted arithmetic mean (or weighted average): - $overline(x)= (sum_(i=1)^N w_i x_i )/(sum_(i=1)^N w_i)$ ] = Day6 Introduction to The relational model And SQL #definition(name:"The Relational Model")[ - "Relations just a table" - It is the most popular data model - Simplest, most uniform data structures - Most formal (algebra to describe operations) - Introduced in 1970 (by <NAME> – Turing Award/1981) - Before: records, pointers, sets, etc - Hierarchical Data Model (IBM IMS, 1966-68) - Network Data Model (CODASYL DBTG, 1969) - Everything from real world is represented by relations - i.e., tables - Each table has multiple rows and columns - Row in a table “binds” values together (row = tuple) - Data stored in tables - Everything is stored in tables under the relational model! ] #example(name:" Let's store more data: List of products")[ - Product Number = 557 - Name = Fleece Pullover (in English) - Colors = navy, black - Department = Women's - Product Number = 563 - Name = Floppy Sun Hat (in English) - Department = Accessories - Product Number = 443 - Name = Deluxe Travel Bag (in English) - Department = Accessories - Product Number = 784 - Name = Cotton Dress Shirt (in English) - Colors = white, gray - Department = Men's - Description: Our <i>favorite</i> shirt! - #figure( image("relation1.png", width: 80%) ) - #figure( image("relation2.png", width: 80%) ) - ] #figure( image("relation3.png", width: 80%) ) Sample relations: Price #figure( image("relation6.png", width: 80%) ) #example(name:"Sample relation:")[ - Catlog #figure( image("relation4.png", width: 80%) ) - Orders and OrerItems #figure( image("relation5.png", width: 80%) ) ] == SQL == DAy 7 Join and KEys #theorem(name: "Yuanxiang Remarkable Thenreom")[ All Gaysv are Gays. ] $ integral^a_b f(x)d x $ == Day 8 = Aliasing = Aggregation Queries #definition(name: "Aggregation functions")[ - SQL provides several aggregation functions - COUNT, SUM, AVG, MIN, MAX ] #definition(name:" Aggreagtion with grouping")[ - select year, avg(grade) from students group by year ] #definition(name:" Modification Queries")[ - SQL provides several modification queries - INSERT, DELETE, UPDATE - Two forms: Implicit and explicit - Implicit: specify only the values to be inserted - Explicit: specify the columns to be inserted ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/linebreak_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // A relation followed by a relation doesn't linebreak #let hrule(x) = box(line(length: x)) #hrule(70pt)$a < = b$\ #hrule(74pt)$a < = b$
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/theme/disclaimer.typ
typst
Other
#import "common/metadata.typ": * #let disclaimer( title: "", degree: "", author: "", submissionDate: none, signature: none, ) = { pagebreak(weak: true) v(80%) text("I confirm that this " + degree + "'s thesis is my own work and I have documented all sources and material used.") v(15mm) grid( columns: 2, gutter: 1fr, "Mons, " + submissionDate, { set align(right) author + signature }, ) }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/044%20-%20Innistrad%3A%20Crimson%20Vow/001_Episode%201%3A%20Tithes%20and%20Invitations.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1: Tithes and Invitations", set_name: "Innistrad: Crimson Vow", story_date: datetime(day: 28, month: 10, year: 2021), author: "<NAME>", doc ) Stensia sleeps soundly. The sleep of the undisturbed, the sleep of the carefree, the sleep of those utterly without worry—so sleep the vampires within their spires. They have no real need of sleep, but the peasants have need of it, and that makes it an almost novel thing. #emph[Wouldn't it be delightful if—now, at the height of our power—we slept?] It does not last long. An hour or two, perhaps. A nap. A joke, a gesture, a passing fascination. But it is the best hour the humans of Stensia have had in weeks. With the moon high in the sky, though their bodies may long for a moment's respite, there isn't any to be found. For when the vampires wake from their little jest, they will doubtless hunger, and when they hunger, they hunt, and when they hunt, people die. #figure(image("001_Episode 1: Tithes and Invitations/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Grigori presses the knife to his mother's wrist. She does not move, she does not stir, for she too is asleep—and has been for some time. Two nights (it is difficult now to keep track) after the Harvesttide Massacre, his mother simply~fell asleep. Refused to wake. He had seen her before, so full of hope, carving her own effigies to burn in the streets. He had seen her after, when the moon refused to set, skin full of wounds, something in her now broken. "Innistrad will endure," she had said to him. Another prayer the angels did not deign to hear. And he sees her now, weeks later, still asleep. Sallow skinned and thin framed. Chest rising and falling. His mother. Her blood drips into a small glass bowl. It is likely worth more than anything he has ever touched in his life—perhaps worth more than everything he's ever touched together—but it is not his. The decree hanging outside his door was very clear on that part. #emph[Blessings and good tidings upon the reader, for the day of most splendid joy approaches.] #emph[We eagerly await your tithes: one bowl of blood from each resident, once a night until the festivities. We have even been so generous as to provide you the bowls. Mind that they are enchanted; we shall know if you, ungrateful beast that you are, shatter them. Our representatives will be by to collect. Do not make the mistake of offending them. You know, I should think, the consequences of such foolish actions.] #emph[We hope that this found you well. If it did not, know that your blood will serve no matter your condition. You are not exempt.] #emph[Your eternal liege,] #emph[<NAME>, Unquestioned Lord of Innistrad] He watches his mother's blood drip into the bowl and wonders, idly, what she would have made of such a proclamation. If she would have burned it, like he considered burning it. If they would have fled together for any other place than this. Stensia. Once, he loved this place: its spires, its secular air, its traditions. Everywhere on Innistrad, there were traditions, of course, but only in Stensia did it feel like they had proper application. In Kessig, they only suspected they were surrounded by werewolves. Here, the presence of vampires was as natural as the presence of the plague. But how could you manage a plague that had so changed? Some of the villagers had taken up jobs in the castles nearby. If you worked for them, they said, you were safe. But sometimes you die out there in the castles, while you're on the job, and what's your family to do then? And now, the tithes. The people here used to think they were safe—but even those who risked work in the palaces of the damned had to provide their blood. Nothing felt right anymore. Grigori picks up the bowl of his mother's blood. He kisses her forehead. With a fingertip, he wipes the rim so that none spills on the ground as he carries it outside. Everywhere his eyes fall, there is death and there is emptiness. Weeks ago, his friends lit candles and sang songs outside their homes. Weeks ago, effigies burned in every window. Weeks ago, he could not take a step outside without seeing half a dozen of his friends grinning, arm in drunken arm, as they danced on the roads too frightening to walk. But the streets were empty now. Too busy working, most of them—and those who didn't often died. It hadn't happened all at once, like the massacre, but it had happened all the same. These days, the only people he saw on the roads were not people at all. Those who could leave had left, though where he could not say. Things had gotten worse in Stensia, certainly, but they'd gotten worse everywhere else, too. From the scarce news he'd gathered, nowhere was safe anymore. In this everlasting night, they never have to rest. Where could you go to hide from the moon? The lifegiving silver light of the moon is now only another kind of pallor upon the Plane. Grigori sets the bowl down next to its twin, the one he filled an hour ago. Weary—from loss of blood and loss of hope—he sits on his haunches and stares up at the moon. Black bats streak across the silver, a swarm thick as crows on a corpse. And, like crows, they've found something to carry: ornate black envelopes, slashed with white and red. He sees them as they soar past. Some break off from the others. Two head straight for him, each stopping before the bowls. They pick them up in their little mouths, his blood and his mother's, and for an instant, Grigori considers killing them. It would surely be an easy thing to snap their necks. But within the day (could he even call them days?), they would come for him, and for his mother, and nothing at all would change except that the two of them would be dead. Innistrad would continue on, dying and undying. The bats take off. Grigori watches them go. He heads back in to take care of his mother. He can only hope she, too, is sleeping soundly. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("001_Episode 1: Tithes and Invitations/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Adeline has known darkness in her life. She has known evil. Every breath she's taken since the tender age of twelve, when the Church first took her in, has been to strike down those who prey upon humanity. It hasn't always been easy. But it's been easier than this. As she drives her sword through the vampire's heart, she feels only the smallest kind of triumph: #emph[at least he will not kill again. ] Shame soon follows the thought. The work she's doing here is vital—more vital than it's ever been—but it is hungry work, too. And it has eaten away at something within her. Yet that isn't the face she can present to the others. They are expecting the indomitable hero, the knight on a white horse, the beacon of justice on a Plane that's long forgotten the meaning of the word. They're looking for a light. But so is Adeline. Light finds her no sooner than the vampire hits the ground and Chandra's fires swallow the body whole. In the orange glow, Adeline's eyes find her companion's. Adeline can put on the brave face for everyone else—but only Chandra can see her now. She lets her shoulders slump. She lets exhaustion reach her eyes. In the dark of the night, Chandra's flames are brighter than the moon. The pyromancer doesn't ask if Adeline's okay. They both know that would be a pointless question. Instead, she squeezes Adeline's shoulder. "You know, I found some wine in one of these old houses," she says. "Think we've earned a little treat." Despite all that's happened, there's still a twinkle to Chandra's voice. Dimmer, these days, but it's there. Adeline lets it guide her for just a little while. "It'll have to wait until after the meeting," she says, "but you're on." The remains of the vampire smolder in front of them, the stench of cooking flesh crawling up their nostrils. Adeline sheathes her sword and heads upwind. All around them, their rag-tag group fights back. Some, like her, use weapons, battling the last of this old bloodsucker's ghouls and thralls. Some do it with compassion: the witch Deidama is among the many tending to the sick, the wounded, those who have seen too much and borne too much weight already. Magic cannot soothe all their ills. But the right thing to do is to try. This is the fifth counterattack they've launched this week. A little boy heard that there were those who fought against the endless night. When the vampires descended upon the village of Karo, he ran to them, his feet cracking open on the rocks in his path. Arlinn was the first person he found—and it's Arlinn who watches over him now, telling him a story as one of the witches tends to his wounds. The blood streaked and drying across her leathers makes a strange complement to the stew she's pouring into a bowl for the boy. As Adeline and Chandra approach, Arlinn casts a glance their way. She gives the boy a nod and a heartening smile before breaking off to meet with them. Alongside her: Teferi, Kaya, Deidama, some of the other witches, deputized fiendslayers. Their group is not large, perhaps only two or three dozen to protect humanity, yet they are fierce siblings-in-arms. The rest—two hundred—remained in the woods. People needed a place to go when their homes were destroyed. "How'd it go?" Arlinn asks. "Fiends vanquished," Chandra answers. Adeline nods, grateful she found such a bright way to put it. "The village will take time to rebuild, but they'll have safety. At least for tonight." "Good work," says Arlinn. "We'll do what we can for them. Good thing about Kessigers—we can raise a house in a day. Give it a week or two and there'll be plenty of room for everyone." There's much unsaid—that first the villagers will need to survive that long, that it's harder to build in the absolute darkness, that more will fall before anything can rise at all. But it's tiring, too tiring, to think of that now. Arlinn's right: they'll do what they can. Other villages need them, too. "You wanted to call a meeting?" she says. Arlinn points to a makeshift campsite—the village's firepit, surrounded by flattened tree stumps and handwrought benches. One by one the valiant take their seats. Somehow, the smallest bench—suitable for two—remains empty for her and Chandra. Kaya's work, probably; she's the one smirking. Well. Adeline won't argue. She sits, resting her sword against her knees. "So~" All eyes align on Arlinn. The endless night's worn on her, too—that, and whatever drove her fight with Tovolar. Adeline sees more of the wolf than the woman, especially outside of meetings like this one. The sigh that leaves her this time is all too human. "There's no song and dance about it," she says. "We can't keep this up." "But what about Teferi's time magic?" Adeline asks. "Surely he could~" Teferi presses his lips together. He looks up at the treacherous moon and back down. "Unfortunately, there isn't much I can do. Innistrad's solar system is a complicated one. The magic that's keeping the moon in place is ancient and tailored specifically for this Plane." His shoulders slump. "Even assuming I did figure out how to do it without ruining the Plane's ecosystems, it'd take more power than I currently have." "This is bigger than any one person can solve," Kaya says. "Much as I'd prefer the alternative, we're going to need to stick together on this one." "I don't understand," says Adeline. "We've grouped up already, haven't we?" "We have. But our group, for the most part, is human," Arlinn explains. And she is right—apart from two or three of the remaining Wolfir, everyone #emph[is ] human. But why wouldn't they be? Adeline searches Arlinn's eyes for an explanation. It's quick to come. "The endless night doesn't just affect humans. If things continue the way they are, the vampires are going to run out of food eventually. Ten years, maybe, the whole Plane's picked clean. Once upon a time, there was someone among them who realized that. We need to pay him a visit." Chandra's laugh is a nervous one. "Please say you're kidding." "Chandra is right," says Adeline. "If you're talking about <NAME>, he showed us no kindness before. Why should that change now?" Arlinn must have known this was coming—she doesn't let the question hang in the air very long. "Because everything's changed. Besides, it was <NAME> who stole the Moonsilver Key. If anyone will know something about her plans, it's him." "And if the rumors I've heard are true, he hates her guts right about now," Kaya adds. Then, after a beat: "It's all anyone in Stensia can talk about. She's asking everyone there to donate a bowl full of blood." "Which means she's up to something," Adeline agrees. "But why do we have to ask him?" "We don't have any other way in," says Teferi. "Sorin's in a mood, but he's always been pragmatic. As our leading expert on egomaniacal planar guardians—" "Give me a few years," Kaya cuts in. "As someone who's known him for centuries, I think we can get through to him. This isn't the first time he's been in a mood, after all. In fact, come to think of it, I'm not sure if I've ever seen him any other way. But if nothing else, I'm sure he'll tell us what Olivia is planning." "None of this ends unless we can get our hands on the key again. He's the only one who might give us a clue where it is," says Kaya. It makes sense. Yet there's something Adeline can't forgive about him. "Arlinn, the last time we saw him, he was fighting Sigarda." The muscles of Arlinn's jaw work. "I know. It~this isn't easy for me, either. But when part of your flock's gone astray, you don't leave them to the wolves." "But he isn't a sheep," Adeline says, "and you #emph[are ] a wolf." A wry, knowing smile from the woman. "Means I know a thing or two about hunting, and a thing or two about packs. Adeline, I'd like if you came with us—but if you want to stay, I'll understand." Adeline knows what's right; she knows how often the just thing is the heaviest thing. Cathars sometimes trained with weighted swords to drive the message home: the violent path should never be the first one taken; it should never feel #emph[easy ] to snuff out life. If they #emph[can ] get through to him, maybe it's worth trying. She feels Chandra's eyes on her, waiting for the answer. "I'll go. If there's a trace of Avacyn left in him, he'll listen." Later, as they're gathering to leave, the boy from Karo finds her. He is waiting outside of her makeshift tent, his feet bandaged, in too-big armor he's scavenged. The Avacynian symbol on the front is nearly as long as he is. The pig he brought with him—a gigantic thing easily the size of a horse—sniffs at the ground nearby. "How can I help?" he asks her. <NAME>. "You've already helped plenty," she says. From the folds of her armor, she produces a symbol woven from sticks and unlit candles, which she drapes over his head. "The best thing you can do is get back home safe." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("001_Episode 1: Tithes and Invitations/03.jpg", width: 100%), caption: [Sorin the Mirthless | Art by: <NAME>], supplement: none, numbering: none) Innistrad will endure, so the saying goes. But one look out the window is all it takes to render that meaningless. There is no way Innistrad can endure this. <NAME> is sure of it. He's been sure of it for nameless centuries. Inclined as he was to philosophy, he sorted out the truth of the matter not long after his grandfather turned him. If no vampire ever died, and each vampire fed once a month, often killing their "donor," speaking conservatively, and humans took nine months to reproduce~ Well, it just didn't make sense. Even discounting humans who died of diseases, humans who became vampires, humans crunched between the jaws of wolves, and so forth—it didn't work. For Innistrad to endure (the saying existed even then), they would need to either severely limit the number of vampires created or ensure that humans lived. Sorin, young then, approached his grandfather with his discovery. Edgar had long fostered the boy's interest in alchemy; surely, once he saw it all laid out in black and white, he'd realize the grave error he'd made. Edgar listened intently to young Sorin's words. More than that, he asked insightful questions at every junction. In that two hours, Sorin learned more of the world than he had in preparing the presentation. His grandfather cast all his sources in a new light. "Sorin. Do you truly believe I've never had the same thought?" "But Grandfather," Sorin objected, "if you have, then why proceed in this way? The future is not intangible; as immortals, we will have to face it. Innistrad must endure—" "Innistrad will endure. But only peasants feel the need to say so," his grandfather countered. "We have eternity to plan for it—or very near to it. The solution will present itself." "Grandfather, this can't wait—" "On the contrary. You're staring at only a small part of history's tapestry," said Edgar. Then, he picked up one of his quills and dipped it in ink. The scratch of it against parchment was a dismissal. #emph[A small part.] He took his grandfather's advice. The solution would present itself. He had to think bigger, had to see beyond the immediate. The thought lingered in the back of his mind no matter where he went, growing more complex with every passing year. It took six millennia for the larger picture to come together, but once it did, it felt obvious and right. He felt foolish for not seeing it sooner. Humans needed a protector. He gave them one. Of course, by then, his fellow vampires had nearly drunk the Plane dry. It was a very close thing, saving Innistrad as he had. Yet defeat found him, and defeat found her, and now even to breathe the air of this place fills him with bitterness. Part of him wonders if his grandfather had planned for Avacyn and planned for her eventual fall. Edgar thought of everything, after all, and he knew his grandson better than anyone ever had and likely ever would. Had he planned for this eternal night? Had he known what it would do to the vampire population? To the #emph[human ] population? All his years of life had not prepared Sorin for it. At first, he'd taken the role of observer. Licked his wounds, holed up in the manor, and watched it all unfurl. The others knew as well as he did what would happen if they gorged themselves. But if impatience is the last thing to die among vampires, then inhibition is the first. By Sorin's count, they have only months before all the humans on this Plane were vampires, werewolves, geists, or just plain dead. His grandfather had been slumbering for long enough. If there was a plan for this eventuality, then it was time the two of them spoke. Sorin descends the steps of Markov Manor. His short war with Nahiri, his failed protege, left much of the place in ruins, but the family archives remained largely intact, buried deep underground as they were. Twisted, floating knife blades gave way to graceful white arches and smooth stairs. Here, the geistflame burned bright; here, there was no dust on the steps nor motes in the air. Sorin himself enchanted this place. If all of Innistrad were to collapse in on itself today, his family archives would remain in testament to their own foolishness. There were the books, of course, the first thing to greet him—carefully curated collections of all the Plane's wisdom. His grandfather's journals were given special treatment here, bound in golden covers and displayed beneath the purest glass. Three bookcases comprised Sorin's own journals—those he was not actively rereading or writing. The musings of generals, alchemists, even cathars and Avacynian priests winked back at him from their places on the shelves. #emph[Save us] , they seem to say. How often people said those words to him. He grew weary of other people's problems, of saving other Planes, of the vast and complicated web he'd woven in his unending life. Innistrad—at least he knew Innistrad. He thought he could recover here. Once his house was in order, so to speak, he might emerge and deal with the other Planes once more. #emph[Save us] , they say to him. #emph[I'm trying] , he wants to say. Past the books were portraits, statues, and the armory. He walks the narrow halls of white stone and does not stop to peruse the works of his brethren. Innistrad would endure. There would be time, later, if he wanted to lose himself in the memories of a House that never embraced him. Only a little farther to the coffins. When elders tired of the Plane around them, they often rested until it grew so alien that they could discover it anew. If he were a normal vampire—a simple immortal without the ability to leave Innistrad—he might have ended up here himself. But there must always be someone to watch over them, and, without fail, this person was always Sorin. He resents them. He does not hide it, not here in the cold silence of the tomb. He glares at each name above each coffin, and he asks them in his mind why #emph[they ] could not be bothered to emerge. It was their decadence that led to all this, and yet here they were resting—perhaps even dreaming—while he cleaned up their mess. Exhausting. He has a coffin, too. A foolish thing. A promise he made to himself that he would rest. The only thing keeping him from smashing it is the thought that his grandfather might see and might name it the childish fit of pique it is. Onward. His grandfather rests in a mausoleum at the very end of the corridor, protected by a massive stone door. Often, Edgar woke for small spells. Sorin left him books for those cases—things he thought exemplified the current state of Innistrad. Sometimes, when he needed his grandfather's counsel, he would even wake him. The two would speak in the drawing room of the dead, and when it was done, Edgar would rest once more. It always left Sorin feeling like a child—but the advice had not once failed him. #figure(image("001_Episode 1: Tithes and Invitations/04.jpg", width: 100%), caption: [Fateful Absence | Art by: <NAME>], supplement: none, numbering: none) Resigned, he walks into the mausoleum expecting to see his grandfather resting in the mighty coffin Sorin commissioned for him or reading at his stately desk—and instead finds an empty room. There are no statues here to greet him. Gone are the table, the chairs, even the empty teapot he kept here. Dust silhouettes the bookshelves where his grandfather's collection of knowledge used to dwell. But none of this compares to the largest lack in the room: the coffin itself is missing. Fury burns in his heart. It so often does, and yet now there is so little left to burn that all he can do is laugh. Of course. Yesterday, he'd allowed himself to leave the grounds. He'd wanted to see what was going on with his own two eyes. Of course, someone had struck while he was away. He pinches his nose, considers his options. It is then that he hears the flapping of wings and feels the air shifting within the palace. Someone else is here. Perhaps more than one intruder. He turns, snatching at the sound. A bat, by the feel of it. He crushes it without a second thought. Within its clutches—stained now by its blood—there is a single envelope. #emph[To my Dearest, Most Precious Sorin Markov, Whom We Could Never Forget on This Day.] He knows that handwriting. It takes centuries of patience not to crush the envelope, too. Instead, he opens it. The words within do nothing for his mood. Oh, no. If his previous gloom was the darkness of a new moon, then this is the darkness of a moon snatched from the sky, never to return. He throws the bat's limp body into a corner of the mausoleum and storms back up the stairs. There are other intruders; he can feel them. Still, if they have any part of this mockery~ "Careful, that book's bound in human flesh." The voice echoes down to him. A woman. Familiar, but only vaguely. They're in the library. When he comes upon them, they're standing in a half circle around his reading desk. Some of them he knows, but there are plenty of new additions. Seems they've picked up some strays along their travels: a thief of some kind, her eyes quicker and her smirk sharp; the pyromancer, hands in the air like she's seen something horrible. Then his eyes land on Teferi. Jovial as always, he's hiding a laugh. Teferi puzzled Sorin. He so rarely met others who could see the whole of history or anyone who smiled so easily. The wolf, <NAME>, with her hands on her hips, lecturing. And the cathar that last came with them. All in #emph[his ] library, in #emph[his ] family archives, behaving like children when confronted with one of the foremost texts on stitching in Innistrad. Of #emph[course ] it was bound in human vellum, what else did they expect? He didn't keep work by #emph[novices] . He has half a mind to puppet them all out of here, to grab them by their veins and set them walking. The other half—older, more patient, cognizant of his awful position—realizes that they must have come here for a reason. "You have one minute to tell me why you're trespassing here," he growls. Perhaps they did not hear him coming, for most snap to attention. Arlinn and Teferi are the lone exceptions. It is frustrating to him how easy Teferi remains, how none of this seems to trouble him. Worse yet, the wolf's eyes are on the letter. "I think you know why we're here, Sorin," she says. "But the real question is: what's that?" He could refuse to answer. But the truth—loath as he is to admit it—is that she's right. He knows why she's here. The eternal night bodes ill for the humans she cares so much about. Of course she would come to him again for help. And, if honesty is the name of the hour~ He throws the letter upon the table. The thief snatches it up first, the pyromancer leaning over her shoulder to read. Like a child, the latter cannot conceal her shock. #figure(image("001_Episode 1: Tithes and Invitations/05.jpg", width: 100%), caption: [Wedding Invitation | Art by: <NAME>], supplement: none, numbering: none) "It's an invitation," he says. "An invitation?" Arlinn echoes. She, too, leans over to get a better look at the letter, but by now, the others are blocking her view with their rubbernecking. "To a wedding. #emph[<NAME>'s ] wedding." The name is poison on his tongue. "She's stolen my grandfather. If they marry, they'll form the largest of the vampire families. They'll—#emph[she'll] rule all of Innistrad." Arlinn snatches the letter away from the pyromancer. He watches as she reads it—watches her jaw work, watches as she realizes he isn't lying. Then she fixes him with a look of surprising determination. "Looks like we've got a wedding to crash."
https://github.com/Maeeen/thesis_template_typst
https://raw.githubusercontent.com/Maeeen/thesis_template_typst/master/thesis.typ
typst
#import "./template/template.typ": * #show: setup-page-counting #title_page( title: "A wonderful thesis about the merits of scientific writing", logos: ( image("./logos/EPFLlogo.svg"), image("./logos/LABlogo.svg") ), body: [ Approved by the Examining Committee: Prof. Dr. sc. ETH <NAME> \ Thesis Advisor The External Reviewer \ External Expert The Doctoral Student \ Thesis Supervisor ] ) #dedication[ #align(right)[ #quote("Follow the white rabbit...", attribution: "The Matrix", block: true) ] #align(center)[ Dedicated to my pet bunny. ] The dedication is usually a short inspirational quote. Define your dedication here. ] #pagebreak(weak: true) #enable-counting #lorem(5000) #hide-counting = Disabling page counting #lorem(1000) #enable-counting = Enabling page counting #lorem(1000)
https://github.com/ahplev/notes
https://raw.githubusercontent.com/ahplev/notes/main/qm/3d.typ
typst
#set text( font: "Noto Sans SignWriting Regular", ) #set math.equation(numbering: "1", supplement: [Eq.]) == Equation in 3 dimensions Schrodinger’s equation: $ i planck.reduce (diff Psi)/(diff t) = hat(H) Psi $ <seq> Hamiltonian: $ -(planck.reduce^2)/(2m) nabla^2 + V $ with time-independent potential $V$, $ -(planck.reduce^2)/(2m)nabla^2 psi + V psi = E psi $ In spherical Coordinates $ nabla^2 = 1/r^2(diff)/(diff r)(r^2(diff)/(diff r)) + 1/(r^2 sin theta)diff/(diff theta)(sin theta diff/(diff theta)) + 1/(r^2 sin^2 theta)(diff^2/(diff phi.alt^2)) $ along with separation of variables $ psi(r, theta, phi.alt) = R(r)Y(theta, phi.alt) $ the @seq becomes $ -planck.reduce^2/(2m)[Y/r^2 d/(d r)(r^2(d R)/(d r))+ R/(r^2 sin theta)diff/(diff theta)(sin theta (diff Y)/(diff theta))+R/(r^2 sin^2 theta)(diff^2 Y)/(diff phi.alt^2)] + V R Y = E R Y $ $ {1/R d/(d r)(r^2 (d R)/(d r)) - (2m r^2)/planck.reduce^2 [V(r) - E]} + 1/Y {1/(sin theta)diff/(diff theta)(sin theta (diff Y)/(diff theta)) + 1/(sin^2 theta)(diff^2 Y)/(diff phi.alt^2)} = 0 $ write the constant as $l(l+1)$: $ 1/R d/(d r)(r^2 (d R)/(d r)) - (2m r^2)/planck.reduce^2 [V(r) - E] = l(l+1) $ <req> and $ sin theta diff/(diff theta)(sin theta (diff Y)/(diff theta)) + (diff^2 Y)/(diff phi.alt^2) = -l(l+1)Y sin^2 theta $ let $Y(theta, phi.alt) = Theta(theta)Phi(phi.alt)$, we have $ {1/Theta [sin theta d/(d theta)(sin theta (d Theta)/(d theta))] + l(l+1)sin^2 theta} + 1/Phi (d^2 Phi)/(d phi.alt^2) = 0 $ Again but the separation constant is now $m^2$ $ 1/Theta [sin theta d/(d theta)(sin theta (d Theta)/(d theta))] + l(l+1)sin^2 theta = m^2 $ <aeq1> $ 1/Phi (d^2 Phi)/(d phi.alt^2) = -m^2 $ <aeq0> solving @aeq0 and @aeq1 $ Phi(phi.alt) = e^(i m phi.alt) $ alas, in spherical coordinate, we have $Phi(phi.alt + 2 pi) = Phi(phi.alt)$, $m$ must be an $italic("integer")$, i.e. $ m = 0, plus.minus 1, plus.minus 2, dots.h $ solution to @aeq1 is $ Theta(theta) = A P^m_l (cos theta) $ $ P^m_l(x) eq.triple (-1)^m (1-x^2)^(m slash 2)(d/(d x))^m P_l(x) $ <alf> $ P_l(x) eq.triple 1/(2^l l!)(d/(d x))^l(x^2 - 1)^l $ according to @alf, $m$ should be no larger than $l$, there are $(2l + 1)$ possible values for $m$: $ m = 0, plus.minus 1, dots.h, plus.minus l $ and of course $l$ should be a natural number. The normalization condition: $ integral abs(psi)^2 r^2 sin theta d r d theta d phi.alt = integral abs(R)^2 r^2 d r integral abs(Y)^2 d Omega = 1 $ IDK how to normalize this one, but we can do it separately $ integral_0^oo abs(R)^2 r^2 d r = 1 and integral_0^pi integral_0^(2pi) abs(Y)^2 sin theta d theta d phi.alt = 1 $ The normalized angular wave functions are *spherical harmonics* $ Y_l^m (theta, phi.alt) = sqrt((2l+1)/(4pi) ((l-m)!)/((l+m)!)) e^(i m phi.alt)P_l^m (cos theta) $ As for the radial equation @req, let $u(r) eq.triple r R(r)$, $ R &= u/r\ (d R) / (d r) &= [r (d u)/(d r) - u]/r^2\ (d/(d r))[r^2 (d R)/(d r)] &= r (d 2 u)/(d r^2) $ the radia equation is then $ -planck.reduce^2/(2m) (d^2 u)/(d r^2) + [V + planck.reduce^2/(2m)(l(l+1))/r^2]u = E u $ and the effective potential $ V_"eff" = V + planck.reduce^2/(2m)(l(l+1))/r^2 $ == Hydrogen Atom Potential $ V(r) = -e^2/(4pi epsilon.alt_0) 1/r $ radial equation $ -planck.reduce^2/(2m_e)(d^2 u)/(d r^2) + [-e^2/(4 pi epsilon.alt_0) 1/r + planck.reduce^2/(2 m_e)(l(l+1))/r^2]u = E u $ we only consider the bounding state, i.e. $E < 0$ Let $k eq.triple sqrt(-2m_e E)/planck.reduce$, which is real, we have $ 1/kappa^2 (d^2 u)/(d r^2) = [1 - (m_e e^2)/(2pi epsilon.alt planck.reduce^2 kappa) 1/(kappa r) + (l(l+1))/((kappa r)^2)]u $ and again we change the variable and constant $ rho eq.triple kappa r "and" rho_0 eq.triple (m_e e^2)/(2pi epsilon.alt planck.reduce^2 kappa) $ <28> so that $ (d^2 u)/(d rho^2) = [1 - rho_0/rho + (l(l+1))/rho^2]u $ as $rho -> oo$, $(d^2 u)/(d rho^2) = u$, $u(rho) = A e^(-rho) + B e^(rho)$, but _u_ have to converge, so $B = 0$, and the same holds for $rho -> 0$, where $u(rho) = C rho^(l+1)$, so we assume that $ u(rho) = rho^(l+1)e^(-rho)v(rho) $ so $ (d^2 u)/(d rho^2) = rho^l e^(-rho){[-2l-2+rho+(l(l+1))/rho]v + 2(l + 1 - rho)(d v)/ (d rho) + rho (d^2 v)/(d rho^2)} $ then the radial equation reads $ rho (d^2 v)/(d rho^2) + 2(l + 1 - rho)(d v)/(d rho) + [rho_0 - 2(l + 1)]v = 0 $ using power series solution, we have $ v(rho) = sum_(j = 0)^oo c_j rho^j $ $ c_(j+1) = [(2(j + l + 1) - rho_0)/((j+1)(j+2l+2))]c_j $ <recur> for $v(rho)$ to converge, @recur must terminates, i.e. $exists N "such that" c_N = 0$, then we have $ 2(N+l) - rho_0 = 0 $ according @28, we have $ E = -(planck.reduce^2 kappa^2)/(2m) = -(m_e e^4)/(8 pi^2 epsilon.alt_0^2 planck.reduce^2 rho_0^2) $ Defining $ n eq.triple N + l $ <principle> we have $rho_0 = 2n$, and the famous result, *Bohr formula* $ E_n = -[m_e/(2planck.reduce^2)(e^2/(4pi epsilon.alt_0))^2]1/n^2 = E_1/n^2, n = 1,2,3,dots.h $ since $E$ is function of $kappa$, it's obvious that $ kappa = (m_e e^2)/(4 pi epsilon.alt_0 planck.reduce^2)1/n = 1/(a n) $ $a$ is so-called *Bohr radius* The spatial wave function is labeled by three quantum nubers($n, l, m$) $ psi_(n l m)(r, theta, phi.alt) = R_(n l)(r)Y_l^m(theta, phi.alt) $ notice that $l < n$, since if $N = 0$, $v(r)$ will vanish, i.e. $ l = 0, 1, 2,dots.h, n - 1 $ and for each $l$ there are $2l+1$ possible vlaues of m, so the total degeneracy of the energy level $E_n$ is $ d(n) = sum_(l = 0)^(n - 1)2l+1 = n^2 $ again, to formalize our solution $ v(rho) = L_(n - l - 1)^(2l+1)(2rho) $ where $ L_q^p(x) eq.triple (-1)^p (d/(d x))^p L_(p+q)(x) $ is an *associated Laguerre polynomial*, and the *Laguerre polynomial* is $ L_q(x) eq.triple e^x/(q!)(d/(d x))^q (e^(-x) x^q) $ finally we give the normalized hydrogen wave function here $ psi_(n l m) = sqrt((2/(n a))^3 ((n-l-1)!)/(2n(n+l)!))e^(-r slash n a) ((2r)/(n a))^l [L_(n-l-1)^(2l+1)(2r slash n a)]Y_l^m (theta, phi.alt) $ and the orthogonality $ integral psi_(n l m)^* psi_(n' l' m') r^2 d r d Omega = delta_(n n') delta_(l l') delta_(m m') $ == Angular Momentum $ bold(L) = bold(r) times bold(p) = vec(delim: "[", y p_z - z p_y, z p_x - x p_z, x p_y - y p_x) $ $ [L_i, L_j] = i planck.reduce epsilon.alt_(i j k) L_k $ $ sigma_(L_i)^2 sigma_(L_j)^2 gt.eq (1/(2i) angle.l i planck.reduce epsilon.alt_(i j k) L_k angle.r)^2 $ $ sigma_(L_i) sigma_(L_j) gt.eq planck.reduce/2 abs(angle.l epsilon.alt_(i j k) L_k angle.r) $ $ [L^2, bold(L)] = 0 $ we define a *ladder operator* $ L_(plus.minus) eq.triple L_x plus.minus i L_y $ its commutator with $L_z$ $ [L_z, L_plus.minus] = [L_z, L_x] plus.minus i[L_z, L_y] = i planck.reduce L_y plus.minus i(-i planck.reduce L_x) = plus.minus planck.reduce L_plus.minus $ since $L^2$ and $L_plus.minus$ are commutative, we have $ L^2 (L_plus.minus f) = L_plus.minus (L^2 f) = L_plus.minus (lambda f) = lambda(L_plus.minus f) $ $L_plus.minus f$ is still an eigenfunction of $L^2$, with the same eigenvalue, but for $L_z$ $ L_z (L_plus.minus f) = (L_z L_plus.minus - L_plus.minus L_z) f + L_plus.minus L_z f = plus.minus planck.reduce L_plus.minus f + L_plus.minus (mu f) = (mu plus.minus planck.reduce)(L_plus.minus f) $ thus the operator changes the eigenvalue with an amount of $planck.reduce$ for $L_z$ Since the _z_ component cannot exceed the total angular momentum, there must exists a top rung (maximal state) such that $ L_+ f_t = 0 $ introduce some constants $ L_z f_t = planck.reduce l f_t, space L^2 f_t = lambda f_t $ Then, $ L_plus.minus L_minus.plus = (L_x plus.minus i L_y)(L_x minus.plus i L_y) = L_x^2 + L_y^2 minus.plus i[L_x, L_y] = L^2 - L_z^2 minus.plus i(i planck.reduce L_z) $ $ L^2 = L_plus.minus L_minus.plus + L_z^2 minus.plus planck.reduce L_z $ <60> so we can say that $ L^2 f_t = (L_- L_+ + L_z^2 + planck.reduce L_z)f_t = (0 + planck.reduce^2 l^2 + planck.reduce^2 l)f_t = planck.reduce^2 l(l+1)f_t $ and hence $ lambda = planck.reduce^2 l(l+1) $ <62> this indicates the eigenvalue of $L^2$ in terms of the _maximum_ eigenvalue of $L_z$ Of course there is the bottom rung where $L_- f_b = 0$, let's say $ L_z f_b = planck.reduce macron(l)f_b, space L^2 f_b = lambda f_b $ using @60 again, we have $L^2 f_b = planck.reduce^2 macron(l)(macron(l) - 1)f_b$, and therefore $ lambda = planck.reduce^2 macron(l)(macron(l)-1) $ <64> combine @62 and @64 we can see that $l(l+1)=macron(l)(macron(l)-1)$, since $l$ should be larger than $macron(l)$ to make any sense $ macron(l) = -l $ The eigenvalues of $L_z$ are $m planck.reduce$ where $m$ goes from $-l$ to $+l$ in _N_ integer steps. Specifically, since$l - macron(l) = N$ and hence $l = N/2$, thus $l$ must be an integer or half-integer. The eigenfunctions characterized by the numbers $l$ and $m$ $ L^2 f_l^m = planck.reduce^2 l(l+1)f_l^m , space L_z f_l^m = planck.reduce m f_l^m $ with $ l = 0, 1/2, 1, 3/2, dots.h; space m = -l, -l+1,dots.h,l-1,l $ and for a $l$ there are $2l+1$ different values of $m$ the remaining problem is that I don't know why angular momentum is discrete in the first place - $L_minus.plus$ and $L_plus.minus$ are hermitian conjugate $ [x, p_y] = 0 \ L_x^dagger = p_z y - z p_y = L_x \ L_plus.minus^dagger = L_x^dagger minus.plus i L_y^dagger = L_x minus.plus i L_y = L_minus.plus $
https://github.com/mrknorman/cv
https://raw.githubusercontent.com/mrknorman/cv/main/template.typ
typst
#let left_column_size = 25% #let grid_column_gutter = 8pt #let main_color = rgb("#8B1B65") #let heading_color = main_color #let job_color = rgb(115, 115, 115) #let project( title: "", author: [], phone: "", email: "", github: "", linkedin : "", left_column_size: left_column_size, grid_column_gutter: grid_column_gutter, main_color: main_color, heading_color: heading_color, job_color: job_color, body ) = { set document(author: author, title: title) set page(numbering: none) //set text(font: ("Latin Modern Sans", "Inria Sans"), lang: "en", fallback: true) set text(font: "Avenir", lang: "en", fallback: false, size: 10pt) show math.equation: set text(weight: 400) /* * How headings are used: * - h1: section (colored, prominent, with colored rectangle, spans two columns) * - h2: role (bold) * - h3: place (italic) * - h4: generic heading (normal, colored) */ show heading.where(level: 1): element => [ #v(0em) #box( inset: (right: grid_column_gutter, bottom: 0.1em), rect(fill: main_color, width: left_column_size, height: 0.25em) ) #text(element.body, fill: heading_color, weight: 400) ] show heading.where(level: 2): element => [ #text(element.body + ",", size: 0.8em) ] show heading.where(level: 3): element => [ #text(element.body, size: 1em, weight: 400, style: "italic") ] show heading.where(level: 4): element => block[#text(element.body, size: 1em, weight: 400, fill: heading_color)] set list(marker: box(circle(radius: 0.2em, stroke: heading_color), inset: (top: 0.15em))) set enum(numbering: (n) => text(fill: heading_color, [#n.])) grid( columns: (1fr, 1fr), box[ // Author information. #text([#author], weight: 400, 2.0em) #v(-1.2em) // Title row. #block(text(weight: 400, 1.5em, title, style: "italic", fill: job_color)) ], align(right + top)[ // Contact information #set block(below: 0.5em) #if github != "" { align(top)[ #box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#image("icons/github.svg")]] #link("https://github.com/" + github)[#github] ] } #if linkedin != "" { align(top)[ #box(height: 1em, baseline: 0%)[#pad(right: 0.0em)[#image("icons/linkedin.svg")]] #link("https://www.linkedin.com/in/" + linkedin)[#linkedin] ] } #if email != "" { align(top)[ #box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#image("icons/envelope-regular.svg")]] #link("mailto:" + email) ] } #if phone != "" { align(top)[ #box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#image("icons/phone-solid.svg")]] #link("tel:" + phone)[#phone] ] } ] ) // Main body. set par(justify: true, leading: 0.5em) body } #let datebox(month: "", year: []) = box( align(center, stack( dir: ttb, spacing: 0.4em, text(size: 1em, [#year]), text(size: 0.75em, month), ) ) ) #let daterange(start: (month: "", year: []), end: (month: "", year: [])) = box( stack(dir: ltr, spacing: 0.75em, datebox(month: start.month, year: start.year), [--], datebox(month: end.month, year: end.year) ) ) #let cvgrid(..cells) = pad(bottom: 0.8em)[#grid( columns: (left_column_size, auto), row-gutter: 0em, column-gutter: grid_column_gutter, ..cells )] #let cvcol(content) = cvgrid([], content) #let xdot(s) = { if s.ends-with(".") { s } else { s + "." } } #let cventry( description, start: (month: "", year: ""), end: (month: "", year: ""), place: "", role: [] ) = cvgrid( align(center, daterange(start: start, end: end)), [ == #role === #xdot(place) ], [], description ) #let cvlanguage( language: [], description: [], certificate: [], ) = cvgrid( align(right, language), [#description #h(3em) #text(style: "italic", certificate)], )
https://github.com/figarofuga/Typst-template
https://raw.githubusercontent.com/figarofuga/Typst-template/main/Sepsis_iv/sepsis_iv.typ
typst
// Get Polylux from the official package repository #import "@preview/polylux:0.3.1": * // Make the paper dimensions fit for a presentation and the text larger #set page(paper: "presentation-16-9") #set text(font: "Noto Serif CJK JP", size: 20pt) #set footnote.entry(clearance: 0.1em, gap: 0.2em) #show heading:set align(start + top) #set align(horizon) // Use #polylux-slide to create a slide and style it using your favourite Typst functions #polylux-slide[ #align(horizon + center)[ = 敗血症における輸液療法今昔 新美 望 2024/5/24 ] ] #polylux-slide[ == 9月になりましたね 9月と言えば・・・・・・ #align(horizon)[ #side-by-side[ #set align(horizon + center) = 秋だ! ][ #set align(horizon + center) = 月見だ! ][ #set align(horizon + center) = 敗血症だ!!#footnote[9月13日は世界敗血症デー] #h(0.5em) ] ] ] #polylux-slide[ == という事で #align(horizon + center)[ #text(size: 24pt, weight: "bold")[- 今日は敗血症における輸液療法について考えてみたい ] ] ] #polylux-slide[ == EGDTについて - EGDTは複数の介入(バンドル)で構成されているが、そのメインのものに*大量輸液による早期の組織への灌流の改善*が挙げられる - この組織灌流は平均血圧で規定されていた #align(horizon + center)[ このEGDTにより、死亡率が #text(size: 28pt)[*16%*] (46.5% vs. 30.5%)も改善した ] ] #polylux-slide[ == EGDT時代の終焉 #figure( image("figures/egdt_metaanalysis.jpeg", height: 50%) ) - その後、通常の治療と比較した3つのRCTがあり通常治療とEGDTで死亡率に差を認めなかった#footnote[N Engl J Med 2017;376:2223-2234] #h(0.5em) - さらに、#text(fill: red, weight: "bold")[輸液過剰の害]が指摘されるようになった ] #polylux-slide[ == 輸液過剰の害 - 大量輸液(初日に5L/day以上)により + 人工呼吸器装着期間 + ICU入室期間に加えて + 死亡率 #align(center)[ まで上昇することが判明した。#footnote[Intensive Care Medicine 43 (5): 625–32. ] #h(0.1em) ] ] #polylux-slide[ == Post EGDT時代のギモン - 輸液はどのくらい入れればよいのか? = どれくらいまで絞ってもいいのか? - 輸液の量を絞る代わりの治療法はなにか? - 組織灌流をはかる他の方法は何? ] #polylux-slide[ == 輸液はどれくらいいれる?(どれくらい絞っても大丈夫?) - 現在、初期輸液以降のあとはどこまで入れるのかわかっていない - 輸液反応性を見て、必要に応じて入れるという曖昧な感じ - 初期輸液以降の輸液量をちゃんと評価したRCTは2つある + CLASSIC trial + CLOVERS trial ] #polylux-slide[ == CLASSIC trial #align(top)[#figure( image("figures/classic_km.png", height: 50%) ) ] #text(size: 16pt)[ - P: 24時間以内に1L以上の補液下でSeptic shockが持続する患者(n = 1,554) - I: 輸液制限群 (ICUでのIn balance 1,645mL)#footnote[Protocl違反は 20%であった事は注目に値する] #h(0.1em) - C: 通常治療群 (ICUでのIn balane 2,368mL) - O: 90日目死亡は差なし(輸液制限群 42.3% vs. 通常治療群 42.1%) #align(right)[ #text(size: 12pt)[N Engl J Med. 2022;386(26):2459-2470.] ] ] ] #polylux-slide[ == CLOVERS trial #align(top)[ #figure( image("figures/clovers_km.png", height: 50%) ) ] #text(size: 16pt)[ - P: 1-3Lの輸液でも改善しないSepsisによる低灌流患者 (n = 1,563) - I: 輸液制限療法 (24時間で平均1267mL, 95%CI: 555-2279mL) - C: 輸液自由療法 (24時間で平均3400mL, 95%CI: 2500-4495mL) - O: 90日目死亡は差なし(輸液制限群 14% vs. 輸液自由群 14.9%) #align(right)[ #text(size: 12pt)[N Engl J Med. 2023;388(6):499-510.] ] ] ] #polylux-slide[ == まとめると・・・・・・ - 理論上は輸液制限によりSeptic shock患者の予後を改善出来そうだった - しかし実際には差はなく輸液制限によるメリットはなかった - 逆に言うとデメリットもない #align(center)[ #text(style: "italic", weight: "bold", size: 1.5em)[敗血症への輸液をどのように考えればいい?] ] ] #polylux-slide[ == 適切な輸液? - とはいえ、輸液は絞りたい時が多い(呼吸が悪い、心不全、腎不全など) - 輸液はMAP >65 mmHgとして、末梢循環を改善させる為のもの - 輸液を絞ると当然MAPの目標の達成は難しくなる。その時はどうする? + 早期の昇圧剤使用 + 目標のMAPの値を下げる - シンプルにMAPの目標値を下げる - MAP以外の指標を用いる ] #polylux-slide[ == CENSOR trial #align(top)[#figure( image("figures/censor_km.png", height: 50%) ) ] #text(size: 16pt)[ - P: Sepsisで低血圧の患者(n = 310) - I: 早期のNAD併用群(n = 155) - C: 通常治療群(n = 155) - O: 6時間後のショックのコントロールは有意に早期NAD群で良い(76.1% vs. 48.4%) #align(right)[ #text(size: 12pt)[Am J Respir Crit Care Med. 2019;199(9):1097-1105.] ] ] ] #polylux-slide[ == シンプルに目標のMAPの値を下げる - 目標MAP >= 65 mmHgは少数のICU患者のLactateの値などで決められておりEvidenceに乏しい - SEPSISPAM trialで少なくともこれ以上高くなくても良いとされた (65-70 mmHg vs. 75-80 mmHg) - 高齢者(65歳以上)では、目標MAPを下げて NADを減らした方が良いかも - 高齢者に関しては面白い研究がある(65 trial) ] #polylux-slide[ == 65 trial #align(top)[ #figure( image("figures/sixty_five_trial.png", height: 50%) )] #text(size:16pt)[ - P: ICUに入った65歳以上の患者で点滴および昇圧剤使用初期 (n = 2,600) - I: 低血圧許容群 (MAP 60-65 mmHg, n = 1291) - C: 通常治療群 (MAP >65 mmHg, n = 1,307) - O: 90日目死亡は差なし(低血圧許容群 41.0% vs. 通常治療群 43.8%) #align(right)[ #text(size: 12pt)[JAMA. 2020;323(10):938-949.] ] ] // 結果として、差はあるものの殆どの低血圧許容群はMAP >65 mmHgに達していた // median MAP 66.7 vs. 72.6, MedianのMAP< 65の時間は12 hr vs. 6hr ] #polylux-slide[ == MAP以外の指標を用いる - MAPは臓器灌流を改善させるのが目的 - 臓器灌流を直接評価した方が良いかも知れない - ショックの時の循環評価の代表的な指標: + 腎臓 → 尿量: 0.5 mL/kg/hr + 脳 → 意識 + 皮膚 → #text(fill: red, weight: "bold")[Capillary Refilling Time] + 全身臓器 → #text(fill: red, weight: "bold")[乳酸値]#footnote[SSCG 2021でもLactate guidedを弱く推奨している] #h(0.1em) #align(right)[ #text(size: 12pt)[N Engl J Med 2013;369:1726-1734]] - MAPを65 mmHgで決めつけず、上記を指標に参考に調整しても良いかもしれない ] #polylux-slide[ == Capillary refilling time #align(top)[ #figure( image("figures/crt.png", height: 50%) ) ] - 中指の末節骨を5秒圧迫して離して、血管が再充血するまでの時間 - 成人男性: 2秒以内、成人女性: 3秒、高齢者: 4秒が正常範囲 - この指標は脱水の指標としてLR 6.9と有用性が高い #align(right)[ #text(size: 12pt)[JAMA. 1999;281(11):1022-1029.]] ] #polylux-slide[ == ANDROMEDA-SHOCK trial #side-by-side[ #align(top)[ #figure( image("figures/andromeda_protocol.png", height: 50%) )] ][ #align(top)[ #figure( image("figures/andromeda_km.png", height: 50%) )] ] #text(size: 16pt)[ - P: 20mL/kg以上の初期輸液で反応しないSeptic shock患者 (n = 424) - I: CRT guided therapy (30分毎にCRT check) - C: Lactaet guided therapy (2時間毎にLactate check) - O: 28日目死亡は差なし(CRT群 34.9% vs. Lactate群 43.4%)] #align(right)[ #text(size: 12pt)[Ann Intensive Care. 2018;8(1):52.\ JAMA. 2019;321(7):654-664.] ] // 軽症例でよりCRT群が予後良好と関連している // 通常のCRTとは異なり10秒間圧迫している。異常値は3秒以上 // MAP 65も目標にしている事に注意 ] #polylux-slide[ == 小括 - 輸液をガツガツ入れる事についてはHarm~Neutral - 輸液をやや絞るために + MAPの目標値を下げる: 高齢者で60-65 mmHg + 早期のNAD併用 + MAPに加えて他のPerfusionについての指標を用いる(?) のが良いかもしれない ] #polylux-slide[ == 注意点!! - 上記RCTは基本的には1-3L(30 mL/kg程度)の外液を入れたあとの介入 - Optimization and stablization phaseと称される #align(right)[ #text(size: 12pt)[JAMA. 2023;329(22):1967-1980.]] - 基本はまずは30 mL/kgの初期輸液は勇気をもって行う - 心不全背景でもショックのときには大量初期輸液が良いという観察研究が多い #align(right)[ #text(size: 12pt)[J Intensive Care Med. 2021;36(9):989-1012.]] - 初期輸液はガツンと入れる事はためらわない ] #polylux-slide[ == Take home message - Sepsisの輸液はまずはガツンと、その後は絞る - 早期のNAD併用を考慮 - 患者背景や他の指標を考えて、MAPの目標値を変更しても良いかも! ]
https://github.com/MDLC01/board-n-pieces
https://raw.githubusercontent.com/MDLC01/board-n-pieces/main/README.md
markdown
MIT License
# Board & Pieces This is a [Typst](https://github.com/typst/typst) package to display chessboards. It is available on [Typst Universe](https://typst.app/universe/package/board-n-pieces). ## Project structure This project consists of a Typst library and a plugin written in Rust. Sources for the library are under [`src/`](src/), and sources for the plugin are in [`plugin/`](plugin/). This project can be built into a proper Typst package and tested by [`build.py`](build.py). This build script was made for Python 3.12, and does not require anything outside of the standard library. The [`tests/`](tests/) directory contains a small test suite. ## Usage For more information on how to use this package, take a look at the rendered README on [Typst Universe](https://typst.app/universe/package/board-n-pieces). ## License Unless otherwise stated, the contents of this repository are licensed under the [MIT License](LICENSE), with the exception of the chess pieces under [`src/assets/`](src/assets/). Those are licensed under the [GNU General Public License, version 2](src/assets/LICENSE). They were initially published on Wikimedia by [Cburnett](https://en.wikipedia.org/wiki/User:Cburnett), and later modified by other contributors.
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/8-maly-princ.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": dilo, hrule #dilo("Malý princ", "princ", "<NAME>", "<NAME>", "Světová meziválečná lit.", "Francie", "1943", "epika", "filozofická pohádka") #columns(2, gutter: 1em)[ *Téma*\ Poukázání na rozdíly mezi světem dospělých a dětí. Důraz na důležitost přátelství, lásky a věrnosti. *Motivy*\ tajemno, priority v životě, kresba *Časoprostor*\ v průběhu 8 dní, na Sahaře a ve vesmíru *Postavy* \ _Malý princ_ -- chlapec z asteroidu B-612, mírný a citlivý, symbol dítěte \ _Pilot_ -- autor, symbol dospělého \ _Liška_ -- symbol přítelkyně \ _Had_ -- symbol smrti\ _Růže_ -- láska Malého prince \ _postavy z planet_ -- viz *Obsah* *Kompozice* \ 27 krátkých kapitol, začátek a konec chronologicky, nevštěvování planetek retrospektivně *Vypravěč* -- ich-forma, v pasážích o životě Malého prince vševědoucí er-f. *Jazykové prostředky*\ zdrobněliny, archaismy, přímá řeč, alegorie, vnitřní monolog (_M. prince_), symboly, metafory *Obsah*\ Autor stroskotá na Sahaře, kde potká malého prince; ten odletěl ze své Planety B612 (o kterou se dobře stará) kvůli starostem se svojí růží. Nechává si nakreslit beránka v krabici. Na své cestě navštíví několik planet se specifickými postavami: 1. _Král_ chce někomu rozkazovat, ale na planetě nikdo jiný není. Chtěl z _MP_ udělat svého poddaného. 2. _Domýšlivec_ si přál, aby ho _MP_ obdivoval, opět osamocený. 3. _Pijan_ pil aby zapomněl, že se stydí, za to, že pije. 4. _Byznysmen_ je "vážný člověk" co nemá čas na hlouposti a stále přepočítává své hvězdy, se kterými nic nedělá. 5. _Lampář_ se jako jediný nezabývá jen sám sebou, jeho planeta se točí čím dál tím rychleji a nestíhá. 6. _Zeměpisec_ zakresluje "nepomíjivé" věci, doporučí _MP_ navštívit Zemi. Na poušti potkává lišku, kterou si ochočí. Uvědomuje si, že je zodpovědný za svou růži. Procházejí spolu s _Pilotem_ pouští, než se nakonec _MP_ nechá zabít hadem, vrací se starat o svojí růži/planetu. *Literárně historický kontext*\ Autor skutečně jednou na Sahaře ztroskotal. Dílo bylo přeloženo do více jak 400 jazyků a dialektů.#footnote[Mimo jiné i do hantecu, brněnské variety češtiny.] V knize lze vidět hodně symbolů z autorova života -- letec, liška (jeho new-yorská přítelkyně). Inspirací mu bylo Pražské Jezulátko.#footnote[Inspirací bylo i P. Coelhovi (Alchymista), který se k němu modlil, aby se stal spisovatelem; po 200 milionech prodaných výtisků svých knih mu daroval obleček a nedá na něj dopustit.] // *Autor*\ // Francouzský spisovatel a letec šlechtického původu.#footnote[Jeho jméno je ve skutečnosti ještě delší, než nahoře v rámečku, ale to už mi přislo zbytečný.] Sám se přihlásil do WWII (ODKAZ), kde byl sestřelen nad středozemním mořem. // *Další díla*\ // Citadela -- \ // Kurýr na jih -- // *Současníci*\ ] #pagebreak() *Ukázka* „Ale podívej se … to není beránek, to je beran. Má rohy…“ Tak jsem kresbu znovu předělal. On ji však zase odmítl jako ty předcházející: „Ten je moc starý. Já chci takového, aby dlouho žil.“ A tu, protože jsem ztratil trpělivost a protože jsem spěchal, abych se co nejdřív pustil do rozebírání motoru, načmáral jsem tuhle kresbu a prohlásil jsem: „To je bedýnka. Beránek, kterého chceš, je uvnitř.“ Ale byl jsem velice překvapen, když se obličej malého soudce rozzářil. „Právě tak jsem to chtěl. Myslíš, že ten beránek bude potřebovat hodně trávy?“ #hrule() „Je to hrozné zaměstnání. Kdysi to vyhovovalo. Zhášel jsem ráno a rozžínal večer. Zbývající část dne jsem si mohl odpočinout a zbytek noci spát…“ „A od té doby se příkaz změnil?“ „Příkaz se nezměnil,“ řekl lampář. „To je právě to strašné! Planeta se rok od roku točila rychleji, a příkaz se nezměnil!“ „No a?“ divil se malý princ. „No a teď se otočí jednou za minutu a já nemám ani vteřinku klidu. Rozsvěcuji a zháším jednou za minutu.“ „To je divné! Dny u tebe trvají minutu!“ „To není vůbec divné,“ řekl lampář. „Už je tomu měsíc, co spolu hovoříme.“ „Měsíc?“ „Ano. Třicet minut. Třicet dní. Dobrý večer.“ A zase rozsvítil svou svítilnu. #hrule() „Ovšem,“ řekla liška. „Ty jsi pro mne jen malým chlapcem podobným statisícům malých chlapců. Nepotřebuji tě a ty mě také nepotřebuješ. Jsem pro tebe jen liškou podobnou statisícům lišek. Ale když si mě ochočíš, budeme potřebovat jeden druhého. Budeš pro mne jediným na světě a já zase pro tebe jedinou na světě…“ „Začínám chápat,“ řekl malý princ. „Znám jednu květinu … myslím, že si mě ochočila…“ „To je možné,“ dodala liška. „Na Zemi je vidět všelicos…“ „Ó, to není na Zemi,“ řekl malý princ. #pagebreak()
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-23.typ
typst
Other
// Error: 20-22 unexpected argument #(1, 2, 3).fold(0, () => none)
https://github.com/jangala-dev/product-docs
https://raw.githubusercontent.com/jangala-dev/product-docs/main/pdf/template/template.typ
typst
// This function sets our whole manual as its `body` and formats // it as a simple fiction book. #let manual( // The manual title. title: [Manual title], // The author. author: none, // The paper size to use. paper: none, // Details about the book's publisher that are // display on the second page. publishing-info: none, // The content. body, ) = { // Set the document's metadata. set document(title: title, author: author) set page( paper: paper, margin: (x: 2cm, y: 2cm), ) set heading(numbering: "1.1.1") // Heading format show heading: it => { // Always start a H1 section on a new page if it.level == 1 { pagebreak() } v(0.5em) it v(0.3em) } set par(justify: true) set text(font: "Source Sans 3", size: 12pt) // Link formatting. To do: highlight external links differently, provide // section numbers for internal links, etc. show link: it => { set text(rgb("514089")) highlight(fill: rgb("51408922"), it) } // The first page. page(align(center + horizon)[ #text(2em)[*#title*] #v(2em, weak: true) #text(1.6em, author) ]) // Display our info at the bottom of the second page. if publishing-info != none { align(center + bottom, text(0.8em, publishing-info)) } // Start with a chapter outline. outline( title: [Table of Contents], depth: 3, indent: true, ) // Configure page properties. set page( numbering: "1/1", header: locate(loc => { // Query all level 1 headings and determine the current page number. let curr-page = counter(page).at(loc).first() let sections = query(heading.where(level: 1), loc) // Find if there's a level 1 heading starting on this page. let is-section-start = sections.any(h => h.location().page() == curr-page); // If a chapter starts on this page, only show the document title. if (is-section-start) { return smallcaps(title) } // Otherwise, find the last level 1 heading before this location, if any. let last-section = query(selector(heading.where(level: 1)).before(loc), loc).last() // Show title and that heading. smallcaps(title) + h(1fr) + smallcaps(last-section.body) }), ) body } // Everything below is just to test #show: manual.with( title: [Get Box V1 - User Guide], author: "Jangala", paper: "a5", publishing-info: [ Jangala. \ 4-6a Hookers Road \ London, E17 6DP #link("https://janga.la/") ], ) = Introducing Get Box <introduction.md__introducing-get-box> Jangala’s Get Box is designed to provide effective internet access for households and small groups. It’s designed to be easy to set up, provide robust performance, and make the most of available data #footnote[Here is the footnote.];. #box(width: 100%, image("images/jangala-mission.svg")) = Package Contents <package-contents.md__package-contents> #figure( align(center)[#table( columns: 2, align: (col, row) => (auto,auto,).at(col), inset: 6pt, [#box(width: 100%, image("images/item1.svg")) Item 1 Caption], [#box(width: 100%, image("images/item2.svg")) Item 2 Caption], [#box(width: 100%, image("images/item3.svg")) Item 3 Caption], [#box(width: 100%, image("images/item4.svg")) Item 4 Caption], [#box(width: 100%, image("images/item5.svg")) Item 5 Caption], [#box(width: 100%, image("images/item6.svg")) Item 6 Caption], )] ) = Key Features <features.md__key-features> - #strong[Easy to Use];: Get Box is designed with simplicity in mind, ensuring that users can get online quickly without technical expertise. - #strong[Flexible Connectivity];: Works with mobile nertworks or fixed sources of internet. - #strong[Robust Performance];: Delivers reliable Wi-Fi coverage. #box(width: 100%, image("images/get-box-features.svg")) = Setting up Get Box <quick-setup.md__setting-up-get-box> + Insert a SIM card into Get Box and/or connect the Get Box to another source of internet using the provided Ethernet cable. + Connect the Get Box to a power source. + Wait for the LED indicators to signal that it is fully operational. #box(width: 100%, image("images/installation-process.svg")) If you have issues setting up your Get Box please see the #link(<troubleshooting.md__troubleshooting>)[troubleshooting] section = Advanced Setup <advanced-setup.md__advanced-setup> == Accessing Get Box’s Control Centre <advanced-setup.md__accessing-get-boxs-control-centre> Get Box is a plug and play device. You can find information on the connection, signal strength and more by connecting to Get Box’s Wi-Fi network and typing the following address into your phone or laptop browser: ``` http://172.28.1.1 ``` This should take you to a screen like the one below #box(width: 100%, image("images/control-centre.svg")) #quote(block: true)[ \[!CAUTION\] Negative potential consequences of an action. ] == Custom Wi-Fi Name and Password <advanced-setup.md__custom-wi-fi-name-and-password> \[TBD\] = Troubleshooting <troubleshooting.md__troubleshooting> == Common Issues <troubleshooting.md__common-issues> - #strong[Power Issues];: Ensure the Get Box is connected to a working power outlet. - #strong[Connectivity Issues];: If the lights on Get Box flash on and off all together, then there is no connection, either through the modem or through a wired connection. #box(width: 100%, image("images/troubleshooting-tips.svg")) = Technical Specifications <technical-specifications.md__technical-specifications> - #strong[Model];: Get Box v1 - #strong[Network Compatibility];: LTE cat 4, up to 40 Mbps - #strong[Wi-Fi Capacity];: Supports up to 20 users - #strong[Power Requirements];: AC 110-240V, 50/60Hz #box(width: 100%, image("images/technical-specifications.svg")) = Appendix <appendix.md__appendix> == A: Firmware Updates <appendix.md__a-firmware-updates> Keeping your Get Box updated ensures you have the latest features and security enhancements. Your firmware will update automatically. == B: Legal and Safety Information <appendix.md__b-legal-and-safety-information> The Get Box complies with all relevant safety and regulatory standards. #box(width: 100%, image("images/appendix-information.svg"))
https://github.com/Sematre/typst-letter-pro
https://raw.githubusercontent.com/Sematre/typst-letter-pro/main/README.md
markdown
MIT License
# typst-letter-pro A template for creating business letters following the DIN 5008 standard. ## Overview typst-letter-pro provides a convenient and professional way to generate business letters with a standardized layout. The template follows the guidelines specified in the DIN 5008 standard, ensuring that your letters adhere to the commonly accepted business communication practices. The goal of typst-letter-pro is to simplify the process of creating business letters while maintaining a clean and professional appearance. It offers predefined sections for the sender and recipient information, subject, date, header, footer and more. ## [Documentation](https://raw.githubusercontent.com/wiki/Sematre/typst-letter-pro/documentation-v2.1.0.pdf) ## Example Text source: [Musterbrief Widerspruch gegen Einkommensteuerbescheid](https://web.archive.org/web/20230927152049/https://www.deutschepost.de/de/b/briefvorlagen/beschwerden.html#Einspruch) ### Preview ([PDF version](https://raw.githubusercontent.com/wiki/Sematre/typst-letter-pro/simple_letter.pdf)) ![Image of a simple letter created with typst-letter-pro](template/thumbnail.png) ### Code ```typst #import "@preview/letter-pro:2.1.0": letter-simple #set text(lang: "de") #show: letter-simple.with( sender: ( name: "<NAME>", address: "Deutschherrenufer 28, 60528 Frankfurt", extra: [ Telefon: #link("tel:+4915228817386")[+49 152 28817386]\ E-Mail: #link("mailto:<EMAIL>")[<EMAIL>]\ ], ), annotations: [Einschreiben - Rückschein], recipient: [ Finanzamt Frankfurt\ Einkommenssteuerstelle\ Gutleutstraße 5\ 60329 Frankfurt ], reference-signs: ( ([Steuernummer], [333/24692/5775]), ), date: "12. November 2014", subject: "Einspruch gegen den ESt-Bescheid", ) Sehr geehrte Damen und Herren, die von mir bei den Werbekosten geltend gemachte Abschreibung für den im vergangenen Jahr angeschafften Fotokopierer wurde von Ihnen nicht berücksichtigt. Der Fotokopierer steht in meinem Büro und wird von mir ausschließlich zu beruflichen Zwecken verwendet. Ich lege deshalb Einspruch gegen den oben genannten Einkommensteuerbescheid ein und bitte Sie, die Abschreibung anzuerkennen. Anbei erhalten Sie eine Kopie der Rechnung des Gerätes. Mit freundlichen Grüßen #v(1cm) <NAME> #v(1fr) *Anlagen:* - Rechnung ``` ## Usage ### Preview repository Import the package in your document: ```typst #import "@preview/letter-pro:2.1.0": letter-simple ``` ### Local namespace Download the repository to the local package namespace using Git: ```sh $ git clone -c advice.detachedHead=false https://github.com/Sematre/typst-letter-pro.git --depth 1 --branch v2.1.0 ~/.local/share/typst/packages/local/letter-pro/2.1.0 ``` Then import the package in your document: ```typst #import "@local/letter-pro:2.1.0": letter-simple ``` ### Manual Download the ``letter-pro-v2.1.0.typ`` file from the [releases page](https://github.com/Sematre/typst-letter-pro/releases) and place it next to your document file, e.g., using *wget*: ```sh $ wget https://github.com/Sematre/typst-letter-pro/releases/download/v2.1.0/letter-pro-v2.1.0.typ ``` Then import the package in your document: ```typst #import "letter-pro-v2.1.0.typ": letter-simple ``` ## Contributing Contributions to typst-letter-pro are welcome! If you encounter any issues or have suggestions for improvements, please open an issue on GitHub or submit a pull request. Before making any significant changes, please discuss your ideas with the project maintainers to ensure they align with the project's goals and direction. ## Acknowledgments This project is inspired by the following projects and resources: * [Wikipedia / DIN 5008](https://de.wikipedia.org/wiki/DIN_5008) * [Deutsche Post / DIN 5008 Vorlage](https://web.archive.org/web/20240223035339/https://www.deutschepost.de/de/b/briefvorlagen/normbrief-din-5008-vorlage.html) * [Deutsche Post / Automationsfähige Briefsendungen](https://www.deutschepost.de/dam/dpag/images/P_p/printmailing/downloads/dp-automationsfaehige-briefsendungen-2024.pdf) * [EDV Lehrgang / DIN-5008](https://www.edv-lehrgang.de/din-5008/) * [<NAME> / typst-din-5008-letter](https://github.com/ludwig-austermann/typst-din-5008-letter) * [<NAME> / typst-letter-template](https://github.com/pascal-huber/typst-letter-template) ## License Distributed under the **MIT License**. See ``LICENSE`` for more information.
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/063.%20island.html.typ
typst
island.html The Island Test July 2006I've discovered a handy test for figuring out what you're addicted to. Imagine you were going to spend the weekend at a friend's house on a little island off the coast of Maine. There are no shops on the island and you won't be able to leave while you're there. Also, you've never been to this house before, so you can't assume it will have more than any house might.What, besides clothes and toiletries, do you make a point of packing? That's what you're addicted to. For example, if you find yourself packing a bottle of vodka (just in case), you may want to stop and think about that.For me the list is four things: books, earplugs, a notebook, and a pen.There are other things I might bring if I thought of it, like music, or tea, but I can live without them. I'm not so addicted to caffeine that I wouldn't risk the house not having any tea, just for a weekend.Quiet is another matter. I realize it seems a bit eccentric to take earplugs on a trip to an island off the coast of Maine. If anywhere should be quiet, that should. But what if the person in the next room snored? What if there was a kid playing basketball? (Thump, thump, thump... thump.) Why risk it? Earplugs are small.Sometimes I can think with noise. If I already have momentum on some project, I can work in noisy places. I can edit an essay or debug code in an airport. But airports are not so bad: most of the noise is whitish. I couldn't work with the sound of a sitcom coming through the wall, or a car in the street playing thump-thump music.And of course there's another kind of thinking, when you're starting something new, that requires complete quiet. You never know when this will strike. It's just as well to carry plugs.The notebook and pen are professional equipment, as it were. Though actually there is something druglike about them, in the sense that their main purpose is to make me feel better. I hardly ever go back and read stuff I write down in notebooks. It's just that if I can't write things down, worrying about remembering one idea gets in the way of having the next. Pen and paper wick ideas.The best notebooks I've found are made by a company called Miquelrius. I use their smallest size, which is about 2.5 x 4 in. The secret to writing on such narrow pages is to break words only when you run out of space, like a Latin inscription. I use the cheapest plastic Bic ballpoints, partly because their gluey ink doesn't seep through pages, and partly so I don't worry about losing them.I only started carrying a notebook about three years ago. Before that I used whatever scraps of paper I could find. But the problem with scraps of paper is that they're not ordered. In a notebook you can guess what a scribble means by looking at the pages around it. In the scrap era I was constantly finding notes I'd written years before that might say something I needed to remember, if I could only figure out what.As for books, I know the house would probably have something to read. On the average trip I bring four books and only read one of them, because I find new books to read en route. Really bringing books is insurance.I realize this dependence on books is not entirely good—that what I need them for is distraction. The books I bring on trips are often quite virtuous, the sort of stuff that might be assigned reading in a college class. But I know my motives aren't virtuous. I bring books because if the world gets boring I need to be able to slip into another distilled by some writer. It's like eating jam when you know you should be eating fruit.There is a point where I'll do without books. I was walking in some steep mountains once, and decided I'd rather just think, if I was bored, rather than carry a single unnecessary ounce. It wasn't so bad. I found I could entertain myself by having ideas instead of reading other people's. If you stop eating jam, fruit starts to taste better.So maybe I'll try not bringing books on some future trip. They're going to have to pry the plugs out of my cold, dead ears, however.Spanish TranslationJapanese Translation
https://github.com/songguokunsgg/HUNNU-Typst-Master-Thesis
https://raw.githubusercontent.com/songguokunsgg/HUNNU-Typst-Master-Thesis/master/thesis.typ
typst
MIT License
#import "hnu-thesis/template.typ": documentclass, tablex, fig, tlt, indent, 字体, 字号 #import "hnu-thesis/template.typ": tablex, gridx, hlinex, vlinex, colspanx, rowspanx, tophlinex, midhlinex, bottomhlinex, midvlinex, topvlinex, bottomvlinex // 双面模式,会加入空白页,便于打印 #let twoside = false #let ( doc, preface, mainmatter, mainmatter-end, appendix, fonts-display-page, cover, decl-page, abstract, abstract-en, outline-page, notation, acknowledgement, ) = documentclass( type: "master", degree: "academic", anonymous: false, // 盲审模式 twoside: twoside, // 双面模式,会加入空白页,便于打印 // 可自定义字体,先英文字体后中文字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」 // fonts: (楷体: ("Times New Roman", "FZKai-Z03S")), info: ( title: ("基于 Typst 的", "湖南师范大学硕士学位论文"), title-en: "My Title in English", grade: "2021", student-id: "202120293792", author: "张三", author-en: "<NAME>", department: "信息科学与工程学院", department-en: "School of Chemistry and Chemical Engineering", major: "计算机科学与技术", major-en: "some major", supervisor: ("李四", "教授"), supervisor-en: "Professor My Supervisor", // supervisor-ii: ("王五", "副教授"), // supervisor-ii-en: "Professor My Supervisor", submit-date: datetime.today(), ), ) // 文稿设置 #show: doc.with(margin: (x: 28mm, y:25mm)) // 封面页 #cover() // 声明页 #decl-page() // 前言 #show: preface // 中文摘要 #abstract( keywords: ("Typst", "模板", "HNU", "master") )[ 本研究旨在开发一个基于Typst的硕士论文模板,为湖南师范大学(HNU)的硕士研究生撰写论文提供便捷。Typst是一款新型的排版软件,具有简单易用、功能强大的特点。本研究首先分析了硕士论文的结构和排版要求,然后利用Typst的编程功能,设计并实现了一套完整的硕士论文模板。该模板涵盖了论文封面、摘要、目录、正文、参考文献等部分,可满足大部分硕士论文的排版需求。硕士研究生可以更加专注于论文内容的撰写,提高论文写作效率。本研究成果有望为湖南师范大学乃至其他高校的硕士研究生提供一种便捷、高效的论文排版解决方案。但要注意的是,该模板没有经过官方认证,建议在使用时基于Word、TeX Live或者MacTeX等软件做好方案B,以免造成不必要的麻烦。 ] // 英文摘要 #abstract-en( keywords: ("typst", "template", "HNU", "master") )[ This study aims to develop a master's thesis template based on Typst for master's students at Hunan Normal University (HNU), providing a convenient tool for writing theses. Typst is a new typesetting software known for its simplicity and powerful features. This research first analyzed the structure and typesetting requirements of master's theses and then utilized Typst's programming capabilities to design and implement a complete set of master's thesis templates. The template covers sections such as the cover page, abstract, table of contents, main text, references, and more, meeting the typesetting needs of most master's theses. Master's students can focus more on the content of their theses, improving their writing efficiency. The findings of this study are expected to provide an efficient and convenient typesetting solution for master's students at Hunan Normal University and potentially other institutions. However, it is important to note that this template is not officially certified; please have a backup plan using software such as Word, TeX Live, or MacTeX before use. ] // 目录 #outline-page() // 正文 #show: mainmatter #import "@preview/ctheorems:1.1.1": * #show: thmrules // 添加定理环境 #set heading(numbering: (..args) => { if args.pos().len() == 1 { return numbering("第1章", ..args.pos()) } else { return numbering("1. 1", ..args.pos()) } }) #import "hnu-thesis/utils/theorem.typ": definition, theorem, corollary, example, proof, proposition #import "@preview/lovelace:0.2.0": * #show: setup-lovelace #let algorithm = algorithm.with(supplement: "算法") // 符号表 #notation[ / DFT: 密度泛函理论 (Density functional theory) / DMRG: 密度矩阵重正化群密度矩阵重正化群密度矩阵重正化群 (Density-Matrix Reformation-Group) ] = 快速入门 文件中只讲解常用的使用方式,不涉及复杂的语法和文档编排。如果需要技术指导,请查看README文档或者直接查看原南京大学模板项目README文档。 == 基本概念 - \[\] 包裹的是文本块 - \{\} 包裹的是代码块 - 代码块和文本块可以互相嵌套,如果没写括号,默认为文本。 - 如果某行中文没有缩进,使用\#indent加在前面 - 公式模式下,单个字符才是字符,多个字符是变量 $a = tan b$, 如果你写成a = tanb,会报错。而如果你想打a = tanb,你需要写成$a = t a n b$. \$前后空格很重要,如果你写为$ a=tan b $,这将是行间公式。 - 作用域。也就是set命令,set之后会影响整个文档。举例来说,`#text(weight: "bold")[bold text]`仅仅会加粗传入的参数,而`#set text(weight: "bold")`会影响「到作用域结束」,(或者,如果不在作用域中,影响文档的剩余部分)。根据使用方式的不同(函数调用/使用set命令),很容易区分它的作用域。 - 包导入。使用\#import命令。 好了,你已经入门了,可以继续学习了。建议在使用过程中学习,效率更高。 == 章节标题,黑体、斜体 LaTeX 使用 \\section 命令创建章节标题。多级标题分别用 \\subsection、\\subsection 等表示。根据文档种类的不同,还有 \\part 和 \\chapter。 在 Typst 中,标题设置更简洁:在标题所在的行前面加上一个等号和一个空格,便得到了一级标题:= Introduction。 如果你需要一个二级标题,则可以使用两个等号:== In this paper。 通过在前面加上更多的等号,你可以嵌套任意层级的标题。这一点上更接近 Markdown 中 `#` 的作用,在接下来的阅读中你会不断看到这种「Markdown + LaTeX」杂糅的产物,结合这两者分别的痛点,可以更加深入了解 Typst 设计这些语法的原因。 英文斜体使用 _itali_, 粗体使用 *black*。中文有所不同,目前还没有原生支持中文粗体,你可以通过 set 设置字体的方式来曲线救国,从而实现黑体和斜体。。 == 列表 使用方法如下: - 无序列表 - 无序列表2 - 无序列表3 + 有序列表 + 有序列表2 + 有序列表3 == 代码 (与markdown完全一致) === 行内代码 \`npm install react-dom\` 效果如下: `npm install react-dom` === 行间代码 python示例: \`\`\`python import numpy as np print(np.zeros((10,10))) \`\`\` 效果如下: ```python import numpy as np print(np.zeros((10,10))) ``` c++示例: ```cpp int main() { return 0; } ``` 代码会自动提供高亮。 == 脚注 我们可以添加一个脚注。#footnote[脚注内容] == 链接 这是一个链接 https://typst.app == 引用标签 对应latex中的\\label{XX} 在定义后使用\<citekey\>即可,关于这点,在下面的图表和公式有详细说明。 == 图表 引用@tbl:timing,引用@tbl:timing-tlt,以及@fig:nju-logo。引用图表时,表格、图片和代码分别需要加上 `tbl:`、`fig:` 和 `lst:` 前缀才能正常显示编号。以及这里使用 `fig` 函数替代原生 `figure` 函数以支持将 `tablex` 作为表格来识别。 #align(center, (stack(dir: ltr)[ #fig( tablex( align: center + horizon, columns: 4, [t], [1], [2], [3], [y], [0.3s], [0.4s], [0.8s], ), caption: [常规表], ) <timing> ][ #h(50pt) ][ #fig( gridx( columns: 4, tophlinex(), [t], [1], [2], [3], midhlinex(), [y], [0.3s], [0.4s], [0.8s], bottomhlinex(), ), caption: [三线表], ) <timing-tlt> ])) 表格看似复杂,但使用gpt或者chatglm都可以轻松学会转化规则,直接让AI帮助转化即可。 如果你希望直接导入一个csv文件,或者,那么你有可能无法手动绘制三线。这时候你可以使用 tlt 函数。 #let tbs = csv("tables/test.csv") #align(center, (stack(dir: ltr)[ #fig( tlt( columns: 4, ..tbs.flatten() ), caption: [测试csv], ) <csv> ])) #fig( image("hnu-thesis/assets/vi/hunnu_log_red.png", width: 50%), caption: [图片测试], ) <nju-logo> 注意,Typst目前不支持插入pdf和eps图片,需要转换为svg或者png等图片格式,可以使用inkscape、Adobe AI 软件或者相关网站转换。并且我在使用svg格式的图片时,出现了一些问题,因为本文档内,我暂时使用的是png格式。 == 公式 可以像 Markdown 一样写行内公式 $x + y$,以及带编号的行间公式: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> 引用数学公式需要加上 `eqt:` 前缀,则由@eqt:ratio,我们有: $ F_n = floor(1 / sqrt(5) phi.alt^n) $ #indent 图表和公式后的段落要用 `#indent` 手动缩进。同时,我们也可以通过 `<->` 标签来标识该行间公式不需要编号 $ y = integral_1^2 x^2 dif x $ <-> 而后续数学公式仍然能正常编号。 $ F_n = floor(1 / sqrt(5) phi.alt^n) $ == 定理环境 使用 https://github.com/sahasatvik/typst-theorems 作为定理环境。常用的主要有definition、example、theorem、proof和corolary。 #definition[ 这是一条中文的定义,如果这条句子很长,定义是可以自动进行换行的。 ] #example[ 这是示例的使用情况,他们都可以使用英文书写。 ] #theorem("括注可以这样子写")[ 这是一条定理环境。 ] #proof[ 在这里写你的证明。你可以引用 @cor_largest_prime ] #corollary[ corolary 1. ] <cor_largest_prime> #corollary[ corolary 2. ] == 算法 - 表示无行号,+ 表示有行号 #algorithm( caption: [The Euclidean algorithm], pseudocode-list( line-number-transform: num => numbering("1:", num), indentation-guide-stroke: .5pt, )[ - *input:* integers $a$ and $b$ - *output:* greatest common divisor of $a$ and $b$ + *while* $a != b$ *do* + *if* $a > b$ *then* + $a <- a - b$ + *else* + $b <- b - a$ + *end* + *end* + *return* $a$ ] ) <alg:test> 这是@alg:test == 参考文献 建议使用betterbibtex导出bib文件,调整好citekey后直接\@citekey即可 机器学习是一门人工智能(AI)的分支@wehenkelUnconstrainedMonotonicNeural2019,主要研究如何让计算机从数据或经验中学习,并据此进行预测或决策@wangHuanJieSuiJiYiZhiXingDeJiNiZhiShuYuJueCeShuFangFa2023。简单来说,机器学习就是用算法来解析数据、从中学习、然后做出决策或预测。 机器学习可以分为几种主要类型: 1. *监督学习(Supervised Learning)*: 在这种模式下,算法从标记过的训练数据中学习,然后用学到的知识来预测新的、未标记的数据@granittoNeuralNetworkEnsembles2005。例如,通过分析过去的房价数据来预测未来的房价。 2. *无监督学习(Unsupervised Learning)*: 算法在没有标记的数据集上进行训练,试图自己找出数据内在的结构或规律。聚类和关联规则学习就是两个常见的例子@danielsMonotonePartiallyMonotone2010。 3. *半监督学习(Semi-supervised Learning)*: 这是一种介于监督学习和无监督学习之间的方法,其中一部分数据是标记的,但大部分数据是未标记的。 4. *强化学习(Reinforcement Learning)*: 在这种类型中,算法(通常被称为“智能体”)通过与环境进行交互来学习如何完成特定任务。智能体会获得奖励或惩罚@huangMobileNetworkTraffic2022,以便调整其行为。 机器学习在各个领域都有广泛的应用,包括但不限于自然语言处理、图像识别、推荐系统、金融预测@wangTimeSeriesForecastingFuzzyProbabilistic2022 等。 机器学习也在中国得到了广泛的研究和应用,与国家的战略发展和人民群众的生活密切相关。例如,在医疗健康、工业制造、城市管理等领域都有出色的应用案例@wanNBDTNeuralBackedDecision2021。 另外,我放置了一份 CSL 文件于 bibs 文件夹下,但目前该文件无法正常使用,只能暂时保留,等后续更新。 = 写作模式 Typst 区分两种模式:「标记模式」和「脚本模式」。默认是「标记模式」。此模式下,你可以直接编排文本、使用不同的语法结构,如*使用星号标记粗体文本* 。 == 标记模式中使用命令 ```typst #let patterns = ("有", "无") #for pattern in patterns [ #for j in range(3) [ #if (pattern == "有") [ + it's the ordered list of #(j+1) \ ] else [ - it's the non-ordered list of #(j+1) \ ] ] ] ``` #let patterns = ("有", "无") #for pattern in patterns [ #for j in range(3) [ #if (pattern == "有") [ + it's the ordered list of #(j+1) \ ] else [ - it's the non-ordered list of #(j+1) \ ] ] ] 可以极大地减少重复文本以及多处引用相同文本情况的错误率。 此功能上限很高,发挥你的想象力。 = 脚本/代码模式 「代码模式」下,则更类似像 Python 一样的编程语言,提供了输入、执行代码的选项。 == 数组 array === 基本用法 前面已经有了演示,再说明一下,在标记模式中,可以通过\#加命令来执行脚本,但这种做法美观性不佳,因此可考虑如下方式的代码块。 ```typst #{ let vec = (1,2,3,4) for i in vec [ #i \ // # is used to get value ] } ``` 输出如下:\ #{ let vec = (1,2,3,4) for i in vec [ #i \ // 这里的 # 表示取值 ] } === 解构赋值 ```typst let (x, y) = (1, 2) [The coordinates are #x, #y.] let (a, .., b) = (1, 2, 3, 4) [The first element is #a.] [The last element is #b.] let (_, y, _) = (1, 2, 3) [The y coordinate is #y.] ``` #{ let (x, y) = (1, 2) [The coordinates are #x, #y.] let (a, .., b) = (1, 2, 3, 4) [The first element is #a.] [The last element is #b.] let (_, y, _) = (1, 2, 3) [The y coordinate is #y.] } 自己感受一下,跟一般的编程语言差不多 文档内容块和代码块可以相互内嵌,下面示例中,[hello] 与 a + [ the ] + b 合并,生成 [hello from the *world*]。 ```typst #{ let a = [from] let b = [*world*] [hello ] a + [ the ] + b } ``` 注意,\[\]中的空格不会被忽略。 除此之外,数组还可以添加元素删除元素等,但这方面功能过于脚本化,对普通用户作用不大,故不赘述。 == 字典 字典结构就是键值对结构,能够存储一些固定信息。 ```typst #{ let expResult = ( Accuracy: 98.8%, MAE: 1.2%, recall: 0.34, ) // Destructuring let (Accuracy, MAE, recall:RC) = expResult [The experiment of accuracy is #Accuracy, MAE is #MAE, and Recall is #RC] [The accuracy is #expResult.Accuracy, MAE is #expResult.MAE, and Recall is #expResult.recall] } ``` 也可以只获取某些内容 ```typst #{ let expResult = ( Accuracy: 98.8%, MAE: 1.2%, recall: 0.34, ) let (Accuracy, ) = expResult let (Accuracy, ..other) = expResult } ``` 这种变量极大方便了前后跨度大且提到同一个数据的时候,可以大幅度避免改漏某个数据的情况。 = 流程控制语句 == for 循环 & while 循环 ```typst #{ // Array is wroten above for ch in "Apple" [ #ch is a letter in _Apple_. ] let expResult = ( Accuracy: 98.8%, MAE: 1.2%, recall: 0.34, ) for (key, value) in expResult { [The #key of experiment is #value,] } } ``` 以下是while 循环,while循环似乎不能在脚本模式使用 ```typst #let n = 2 #while n < 10 { n = (n * 2) - 1 (n,) } ``` == if 语句 每个分支从句可以写为语句块或者文档内容块。 - if condition {..} - if condition [..] - if condition [..] else {..} - if condition [..] else if condition {..} else [..] ```typst #{ let criteria = 0.95 let expResult = ( Accuracy: 98.8%, MAE: 1.2%, recall: 0.34, ) // ratio can't be compared with float, converting it is neccesary. if (float(expResult.Accuracy) > criteria) [ Accuracy #expResult.Accuracy is better. ] else { [The accuracy is worse.] } } ``` = 冷门操作符 #fig( tlt( columns: 4, [操作符], [作用说明], [参数数量], [优先级], [in], [属于], [二元], [4], [not in], [不属于], [二元], [4], [not], [逻辑非], [一元], [3], [and], [短路式逻辑并], [二元], [3], [or], [短路式逻辑或], [二元], [2], [+=], [相加赋值], [二元], [1], [-=], [相减赋值], [二元], [1], [\*=], [相乘赋值], [二元], [1], [/=], [相除赋值], [二元], [1], ), caption: [操作符表格], ) <operator-table> 不要背这些优先级,需要优先的不要吝啬你的括号。 // 手动分页 #if (twoside) { pagebreak() + " " } // 参考文献 #bibliography(("bibs/中文参考文献.bib", "bibs/英文参考文献.bib"), style: "gb-7714-2015-numeric" // style: "bibs/hunnu.csl" ) // 致谢 #acknowledgement[ 衷心感谢南京大学无私地分享的开源项目,为我们提供了一个优秀的硕士论文模板。在此,我向他表示由衷的感谢。 ] // 手动分页 #if (twoside) { pagebreak() + " " } // 正文结束标志,不可缺少 #mainmatter-end() // 附录 #show: appendix = 附录 == 附录子标题 === 附录子子标题 附录内容,这里也可以加入图片,例如@fig:appendix-img。 #fig( image("hnu-thesis/assets/vi/hunnu_log_red.png", width: 20%), caption: [图片测试], ) <appendix-img>
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/keyle/0.1.0/doc/keyle.typ
typst
Apache License 2.0
#import "@preview/mantys:0.1.4": * // Vendored because of https://github.com/jneug/typst-mantys/pull/20 #let cmdref(name) = { link(cmd-label(name), cmd-(name)) } // End Vendored #import "../src/keyle.typ" #let lib-name = package[keyle] #show: mantys.with(..toml("../typst.toml"), date: datetime.today(), examples-scope: (keyle: keyle)) #show link: underline // end of preamble = About #lib-name is a library that allows you to create HTML `<kbd>` like keyboard shorts simple and easy. The name, `keyle`, is a combination of `key` and `style`. This project is inspired by #link("http://github.com/auth0/kbd")[auth0/kbd] and #link("https://github.com/dogezen/badgery")[dogezen/badgery]. Send them respect! #v(2em) #keyle.kbd-example #keyle.kbd-mac-example #keyle.kbd-com-example #v(2em) #keyle.kbd-set-style(keyle.kbd-styles.deep-blue) #keyle.kbd-example #v(2em) #keyle.kbd-set-style(keyle.kbd-styles.type-writer) #keyle.kbd-example = Usage #lib-name is imported using #codesnippet[```typ #import "@preview/keyle:0.1.0" ```] Basic usage is as follows, see #cmdref("kbd") for more details: #keyle.kbd-set-style(keyle.kbd-styles.standard) #example(```typst #keyle.kbd("Ctrl", "C") ```) Also you can change the style of the keyboard. See #cmdref("kbd-set-style") for more details. #example(```typst #keyle.kbd-set-style("deep-blue") #keyle.kbd("Alt") #keyle.kbd-set-style("type-writer") #keyle.kbd("Enter") #keyle.kbd-set-style("standard") ```) You can also use the constants `mac-key` and `com-key` to get the key names for Mac and Windows/Linux respectively. #example(```typst #keyle.kbd(keyle.mac-key.control, keyle.mac-key.shift, "A") ```) == Available constants === `kbd-styles` Use `kbd-styles` to get available styles. #example(```typ #keyle.kbd-styles ```) === `mac-key` and `com-key` Use `mac-key` and `com-key` to get the key names for Mac and Windows/Linux respectively. #example(```typ #keyle.mac-key ```) #example(```typ #keyle.com-key ```) = Available commands #tidy-module(read("../src/keyle.typ"), name: "keyle", include-example-scope: true)
https://github.com/cui-ke/semantic-tech
https://raw.githubusercontent.com/cui-ke/semantic-tech/main/courses/Semantic%20Web/Chapters/05-Description_Logics/dl-exercises.typ
typst
#let title = [Exercises on Description Logics] #align(left, text(17pt)[ *#title* ]) <NAME> #let II = $cal(I)$ #let subclass = $subset.eq.sq$ #let ors = $union.sq$ #let ands = $sect.sq$ = 1. Interpretations and models 1. Prove that the DL expressions / E1 = : $forall r . (C union.sq D)$ / E2 =: $(forall r.C) union.sq (forall r . D)$ are not equivalent by finding an interpretation $cal(I) = (C^II, D^II, r^II)$ such that $"E1"^II != "E2"^II$. 2. Find an interpretation $II$ that satisfies the following axioms: 1. $A equiv forall s.L$, 2. $L subclass (exists r.A) ands (forall r.(exists s.top)),$ 3. $L(u)$ 3. Find an interpretation $II$ that satisfies the following axioms: 1. $A subclass forall s.L$, 2. $L subclass (exists r.A) ands (forall r.(exists s.top)),$ 3. $L(u)$ 4. Find an acyclic interpretation that satisfies the above axioms. == Solutions 1. With the interpretation $Delta^II= {a,c,d }, C^( II}= {c }, D^II= {d }, r^II= {(a,c),(a,d) }$ we have $A^II=( forall r.(C union.sq D))^II= {a }$ and $B^II=(( forall r.C) ors ( forall r.D))^II=(( forall r.C))^II union ( forall r.D))^II = emptyset union emptyset = emptyset$ 2. An interpretation that satisfies the axioms: $Delta^II= {u, a}, L^II= {u}, A^II= {u, a}, r^II= {(u,a) }, s^II= {(a, u) }$. Note that $u$ must be in $A^II$ because it trivially satisfies $forall s.L$. #import "@preview/diagraph:0.2.0": * #let renderc(code) = render(code.text) #renderc( ``` digraph { rankdir=LR node [shape=diamond] u a node [shape=ellipse] u -> a [label = " r"] u -> A [label = "instance of"] u -> L [label = "instance of"] a -> u [label = " s "] a -> A [label = "instance of"] } ``` ) 3. A minimal interpretation that satisfies the axioms: $Delta^II= {u}, L^II= {u}, A^II= {u}, r^II= {(u,u) }, s^II= {(u,u) }$ #raw-render( ``` digraph { rankdir=LR node [shape=diamond] u node [shape=ellipse] u -> u [label = " r"] u -> A [label = "instance of"] u -> L [label = "instance of"] u -> u [label = s] } ```) ) 4. An acyclic interpretation: $Delta^II = {u_1,u_2,...,a_1,a_2,... }$, $L^II= {u_1,u_2,... }$, $A^II= {a_1,a_2,... }$, $r^II= {(u_1,a_1),(u_2,a_2),... }$, $s^II= {(a_1,u_2),(a_2.u_{3}),... }$. This interpretation is infinite. #renderc( ``` digraph { rankdir=LR; node [shape=diamond] u1 u2 u3 [label="...", shape=none] a1 a2 node [shape=ellipse] u1 -> a1 [label = " r"] a1 -> u2 [label = " s"] u2 -> a2 [label = " r"] a2 -> u3 [label = " s"] } ``` ) == 2. DL Logical consequences *Source:* <NAME>. (2011). Foundations of Description Logics. Longman Publishing. http://www.aifb.kit.edu/images/1/19/DL-Intro.pdf Consider the knowledge base $cal("KB")$ with #let HCO = $sans("HappyCatOwner")$ #let Cat = $sans("Cat")$ #let Dead = $sans("Dead")$ #let Alive = $sans("Alive")$ #let Healthy = $sans("Healthy")$ #let owns = $sans("owns")$ #let caresFor = $sans("caresFor")$ RBox - $sans("owns") subset.eq.sq sans("caresFor")$ TBox - $Healthy subclass not Dead)$ - $Cat subclass Dead ors Alive$ - $HCO subclass exists owns . Cat) ands forall caresFor . Healthy$ ABox - $sans("HappyCatOwner")(sans("schrödinger")) $ - $sans("Cat")(sans("hbar")),$ - $sans("owns")(sans("schrödinger"),sans("psi")), sans("owns")(sans("schrödinger"),sans("hbar"))$ Decide whether the following propositions about the knowledge base are true and give evidence: 1. $cal("KB")$ is satisfiable, 2. $cal("KB") models sans("Alive")(sans("schrödinger"))$, 3. $cal("KB") models sans("Dead") sect.sq sans("Alive") subset.eq.sq bot$ , 4. $cal("KB") models sans("Alive")(sans("psi"))$, 5. $cal("KB") models sans("Alive")(sans("hbar"))$. == Solutions 1. $cal("KB")$ is satisfiable , with the model $cal(M)$ defined as - $Delta^cal(M)={s,h,p}$ - $sans("schrödinger")^cal(M)=s$, $sans("psi")^cal(M)=p$, $sans("hbar")^cal(M)=h$, - $sans("Cat")^cal(M)={h,p}$, - $sans("HappyCatOwner")^cal(M)={s}$ - $sans("Healthy")^cal(M)={h, p}$, - $sans("Alive")^cal(M)={h}$, - $sans("Dead")^cal(M)={}$, - $sans("owns")^cal(M)={(s,p), (s,h)}$, - $sans("caresFor")^cal(M)={(s,p), (s,h)}$, 2. $cal("KB") models sans("Alive")(sans("schrödinger"))$ is false. For instance in the model $cal(M)$ $s in.not sans("Alive")(sans("schrödinger"))^cal(M)$ 3. $cal("KB") models sans("Dead") sect.sq sans("Alive") subset.sq bot$ is false. If we add $s$ to $sans("Alive")^cal(M)$ and $sans("Dead")^cal(M)$ we obtain a model of $cal("KB")$ in which the interpretation of $sans("Dead") sect.sq sans("Alive")$ is not empty. 4. $cal("KB") models sans("Alive")(sans("psi"))$ is false, in the model $cal(M)$ $p$ is not in $sans("Alive")^cal(M)$ 5. $cal("KB") models sans("Alive")(sans("hbar"))$ is true. In every model $cal(J)$ of KB $h$ must be in $sans("Cat")^cal(J)$ and in $sans("Healthy")^cal(J)$ because of $sans("HappyCatOwner") subset.eq.sq exists sans("owns").sans("Cat") sect.sq forall sans("caresFor").sans("Healthy")$ so it must be in $not sans("Dead")^cal(J)$ bacause of $sans("Healthy") subset.eq.sq not sans("Dead")$ and hence in $sans("Alive")^cal(J)$ because $sans("Cat") subset.eq.sq sans("Dead") union.sq sans("Alive") $ = 3. Inference Use the tableau DL algorithm to show that $( forall r.(B sect.sq C))sect.sq( exists r.(not C))$ is not satisfiable == Solution Let's start with the ABox $ {( forall r.(B sect.sq C))sect.sq( exists r.(not C))(a)} $ Applying the $sect.sq$ rule adds $ ( forall r.(B sect.sq C))(a), \ ( exists r.(not C))(a) $ The $exists$ rule adds $ r(a,b), (not C)b $ The $forall$ rule adds $ (B sect.sq C))(b) $ The $sect.sq$ rule adds $ B(b), \ C(b) $ There is a clash between $not C(a)$ and $C(a)$ $=>$ the starting concept was inconsistent. = 4. OWL-RL inference Use the OWL-RL inference rules to find the ABox logical consequences of the following knowledge bases $cal("KB1")$: 1. $exists sans("owns") . sans("Cat") subclass sans("CatOwner")$ 2. $exists sans("owns") . sans("Mouse") subclass sans("MouseOwner")$ 3. $sans("CatOwner") subclass forall sans("owns"). sans("Cat")$ 4. $sans("owns(felix, max)")$, 5. $sans("owns(felix, illi)")$, 6. $sans("owns(marta, chesee)")$, 7. $sans("owns(marta, bob)")$, 8. $sans("Cat(max)")$, 9. $sans("Cat(bob)")$ 10. $sans("Mouse(cheese)")$ == Solution #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, stroke: 0.5pt, table.header( [*Rule*], [*Applied on (IF)*], [*Infers (THEN)*], ), [*some*], [1, 4, 8], [11. $sans("CatOwner(felix)")$], [*some*], [1, 7, 9], [12. $sans("CatOwner(marta)")$], [*some*], [2, 6, 10], [13. $sans("MouseOwner(marta)")$], [*only*], [3, 11, 5], [14, $sans("Cat(illi)")$], [*only*], [3, 12, 10], [14, $sans("Cat(cheese)")$], ) So, $sans("cheese")$ is both a Cat and a Mouse 🤔 = Exercise 6. Closing the world Consider the knowledge base $cal("KB")$ #let BlueRun = $sans("BlueRun")$ #let RedRun = $sans("RedRun")$ #let SkiRun = $sans("SkiRun")$ #let RedOnlyPlace = $sans("RedOnlyPlace")$ #let Place = $sans("Place")$ #let isEndOf = $sans("isEndOf")$ #let p1 = $sans("p1")$ #let sr1 = $sans("sr1")$ #let isEndOf = $sans("isEndOf")$ #let IsEndOfOnlyOneRun = $sans("IsEndOfOnlyOneRun")$ TBox 1. $BlueRun subclass SkiRun$ 2. $BlueRun subclass SkiRun}$, 3. $RedOnlyPlace equiv Place sect.sq exists isEndOf . SkiRun) sect.sq (forall isEndOf . RedRun)$ ABox 4. $isEndOf(p1,sr1)$, 5. $RedRun(sr1)$, 6. $Place(p1)$ What must be added to the ABox and/or TBox to ensure that $cal("KB") models RedOnlyPlace(p1)$? Test your answer with a DL reasoner (in Protégé). == Solution For example: 7. $IsEndOfOnlyOneRun equiv " " <=""_1 isEndOf . top$ 8. $IsEndOfOnlyOneRun(p1)$
https://github.com/Pegacraft/typst-plotting
https://raw.githubusercontent.com/Pegacraft/typst-plotting/master/readme.md
markdown
MIT License
# A plotting library for Typst A Typst library for drawing graphs and plots. Made by Gewi413 and Pegacraffft ## Currently supported graphs - Scatter plots - Graph charts - Histograms - Bar charts - Pie charts - Overlaying plots/charts (more to come) ## How to use To use the package you can import it through this command `import "@preview/plotst:0.2.0": *` (as soon as the pull request ist accepted). The documentation is found in the `Docs.pdf` in the `docs` folder. It contains all functions necessary to use this library. It also includes a tutorial to create every available plot under their respective render methods. If you need some example code, check out `main.typ` in the `examples` folder. It also includes a compiled version of the current `main.typ` ## Examples: All these images were created using the `main.typ` ### Scatter plots ```js // Plot 1: // The data to be displayed let gender_data = ( ("w", 1), ("w", 3), ("w", 5), ("w", 4), ("m", 2), ("m", 2), ("m", 4), ("m", 6), ("d", 1), ("d", 9), ("d", 5), ("d", 8), ("d", 3), ("d", 1), (0, 11) ) // Create the axes used for the chart let y_axis = axis(min: 0, max: 11, step: 1, location: "left", helper_lines: true, invert_markings: false, title: "foo") let x_axis = axis(values: ("", "m", "w", "d"), location: "bottom", helper_lines: true, invert_markings: false, title: "Gender") // Combine the axes and the data and feed it to the plot render function. let pl = plot(data: gender_data, axes: (x_axis, y_axis)) scatter_plot(pl, (100%,50%)) // Plot 2: // Same as above let data = ( (0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1) ) let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom") let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false) let pl = plot(data: data, axes: (x_axis, y_axis)) scatter_plot(pl, (100%, 25%)) ``` ![scatter](./images/scatter.png) ### Graph charts ```js // The data to be displayed let data = ( (0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1) ) // Create the axes used for the chart let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom") let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false) // Combine the axes and the data and feed it to the plot render function. let pl = plot(data: data, axes: (x_axis, y_axis)) graph_plot(pl, (100%, 25%)) graph_plot(pl, (100%, 25%), rounding: 30%, caption: "Graph Plot with caption and rounding") ``` ![graph](./images/graph.png) ### Histograms ```js // Plot 1: // The data to be displayed let data = ( 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 35000, 46000, 75000, 95000 ) // Classify the data let classes = class_generator(10000, 50000, 4) classes.push(class(50000, 100000)) classes = classify(data, classes) // Create the axes used for the chart let x_axis = axis(min: 0, max: 100000, step: 10000, location: "bottom") let y_axis = axis(min: 0, max: 31, step: 5, location: "left", helper_lines: true) // Combine the axes and the data and feed it to the plot render function. let pl = plot(data: classes, axes: (x_axis, y_axis)) histogram(pl, (100%, 40%), stroke: black, fill: (purple, blue, red, green, yellow)) // Plot 2: // Create the different classes let classes = () classes.push(class(11, 13)) classes.push(class(13, 15)) classes.push(class(1, 6)) classes.push(class(6, 11)) classes.push(class(15, 30)) // Define the data to map let data = ((20, 2), (30, 7), (16, 12), (40, 13), (5, 17)) // Create the axes let x_axis = axis(min: 0, max: 31, step: 1, location: "bottom", show_markings: false) let y_axis = axis(min: 0, max: 41, step: 5, location: "left", helper_lines: true) // Classify the data classes = classify(data, classes) // Combine the axes and the data and feed it to the plot render function. let pl = plot(axes: (x_axis, y_axis), data: classes) histogram(pl, (100%, 40%)) ``` ![histogram](./images/histogram.png) ### Bar charts ```js // Plot 1: // The data to be displayed let data = ((10, "Monday"), (5, "Tuesday"), (15, "Wednesday"), (9, "Thursday"), (11, "Friday")) // Create the necessary axes let y_axis = axis(values: ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"), location: "left", show_markings: true) let x_axis = axis(min: 0, max: 20, step: 2, location: "bottom", helper_lines: true) // Combine the axes and the data and feed it to the plot render function. let pl = plot(axes: (x_axis, y_axis), data: data) bar_chart(pl, (100%, 33%), fill: (purple, blue, red, green, yellow), bar_width: 70%, rotated: true) // Plot 2: // Same as above, but with numbers as data let data_2 = ((20, 2), (30, 7), (16, 12), (40, 13), (5, 17)) let y_axis_2 = axis(min: 0, max: 41, step: 5, location: "left", show_markings: true, helper_lines: true) let x_axis_2 = axis(min: 0, max: 21, step: 1, location: "bottom") let pl_2 = plot(axes: (x_axis_2, y_axis_2), data: data_2) bar_chart(pl_2, (100%, 60%), bar_width: 100%) ``` ![bar](./images/bar.png) ### Pie charts ```js show: r => columns(2, r) // create the sample data let data = ((10, "Male"), (20, "Female"), (15, "Divers"), (2, "Other") // Skip the axis step, as no axes are needed // Put the data into a plot let p = plot(data: data) // Display the pie_charts in all different display ways pie_chart(p, (100%, 20%), display_style: "legend-inside-chart") pie_chart(p, (100%, 20%), display_style: "hor-chart-legend") pie_chart(p, (100%, 20%), display_style: "hor-legend-chart") pie_chart(p, (100%, 20%), display_style: "vert-chart-legend") pie_chart(p, (100%, 20%), display_style: "vert-legend-chart") ``` ![pie](./images/pie.png) **Overlayed Graphs** ```js // Create the data for the two plots to overlay let data_scatter = ( (0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1) ) let data_graph = ( (0, 3), (1, 5), (2, 1), (3, 7), (4, 3), (5, 5), (6, 7),(7, 4),(11, 6) ) // Create the axes for the overlay plot let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom") let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false) // create a plot for each individual plot type and save the render call let pl_scatter = plot(data: data_scatter, axes: (x_axis, y_axis)) let scatter_display = scatter_plot(pl_scatter, (100%, 25%), stroke: red) let pl_graph = plot(data: data_graph, axes: (x_axis, y_axis)) let graph_display = graph_plot(pl_graph, (100%, 25%), stroke: blue) // overlay the plots using the overlay function overlay((scatter_display, graph_display), (100%, 25%)) ``` ![overlay](./images/overlay.png)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/footnote-list_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 100pt) #block(height: 50pt, width: 100%, fill: aqua) - #footnote[1] - #footnote[2]
https://github.com/simon-epfl/notes-ba3-simon
https://raw.githubusercontent.com/simon-epfl/notes-ba3-simon/main/shs/template.typ
typst
// TODO: 1. Make sure no page breaks between the blocks and their titles /* Blocks */ // Pls add or remove elements in this array first, // if you want to add or remove the class of blocks #let classes = ("Definition", "Lemma", "Theorem", "Corollary") #let h1_marker = counter("h1") #let h2_marker = counter("h2") #let stick-together(a, threshold: 3em) = { block(a + v(threshold), breakable: false) v(-1 * threshold) } #let note_block(body, class: "Block", fill: rgb("#FFFFFF"), stroke: rgb("#000000")) = { let block_counter = counter(class) locate(loc => { // Returns the serial number of the current block // The format is just like "Definition 1.3.1" let serial_num = ( h1_marker.at(loc).last(), h2_marker.at(loc).last(), block_counter.at(loc).last() + 1) .map(str) .join(".") let serial_label = label(class + " " + serial_num) v(2pt) stick-together( text(12pt, weight: "bold")[#class #serial_label #block_counter.step()] + v(-8pt) + block(fill:fill, width: 100%, inset:8pt, radius: 4pt, stroke:stroke, body) ) }) } // You can change the class name or color here #let definition(body) = note_block( body, class: "Definition", fill: rgb("#EDF1D6"), stroke: rgb("#609966") ) #let theorem(body) = note_block( body, class: "Theorem", fill: rgb("#FEF2F4"), stroke: rgb("#EE6983") ) #let lemma(body) = note_block( body, class: "Lemma", fill: rgb("#FFF4E0"), stroke: rgb("#F4B183") ) #let example(body) = note_block( body, class: "Exemple", fill: rgb("#FFF4E0"), stroke: rgb("#F4B183") ) #let corollary(body) = note_block( body, class: "Corollary", fill: rgb("#F7FBFC"), stroke: rgb("#769FCD") ) /* Figures */ // The numbering policy is as before, and the default display is centered #let notefig(path, width: 100%) = { let figure_counter = counter("Figure") locate(loc => { let serial_num = ( h1_marker.at(loc).last(), h2_marker.at(loc).last(), figure_counter.at(loc).last() + 1) .map(str) .join(".") let serial_label = label("Figure" + " " + serial_num) block(width: 100%, inset:8pt, align(center)[#image(path, width: width)]) set align(center) text(12pt, weight: "bold")[Figure #serial_num #serial_label #figure_counter.step()] }) } /* Proofs */ #let proof(body) = { [*#smallcaps("Proof"): *] [#body] align(right)[*End of Proof*] } /* References of blocks */ // Automatically jump to the corresponding blocks // The form of the input should look something like "Definition 1.3.1" #let refto(class_with_serial_num, alias: none) = { if alias == none { link(label(class_with_serial_num), [*#class_with_serial_num*]) } else { link(label(class_with_serial_num), [*#alias*]) } } /* Headings of various levels */ // Templates support up to three levels of headings, // and notes with more than three headings are usually mess :) #let set_headings(body) = { set heading( numbering: "1.1.1" ) // 1st level heading show heading.where(level: 1): it => [ // Under each new h1, reset the sequence number of the blocks #for class in classes { counter(class).update(0) } #counter("h2").update(0) #counter("Figure").update(0) // Start a new page unless this is the first chapter #locate(loc => { let h1_before = query( heading.where(level: 1).before(loc), loc) if h1_before.len() != 1 { pagebreak() } }) // Font size and white space #set text(20pt, weight: "bold") #block[Cours #counter(heading).display(): #it.body] #v(25pt) #h1_marker.step() ] // 2st level heading show heading.where(level: 2): it => [ #set text(17pt, weight: "bold") #block[#it] #h2_marker.step() ] // 3st level heading show heading.where(level: 3): it => [ #set text(14pt, weight: "bold") #block[#it] ] body } /* Cover page */ // Create a note cover with the course name, author, and time // Modify parameters here if you want to add or modify information item #let cover_page(title, author, professor, creater, time, abstract) = { set page( paper:"us-letter", header: align(right)[ #smallcaps[#title] #v(-6pt) #line(length: 40%) ], footer: locate(loc => { align(center)[#loc.page()] }) ) block(height:25%,fill:none) align(center, text(18pt)[*Notes de cours: #title*]) align(center, text(12pt)[*#author*]) align(center, text(11pt)[_Donné par Prof. #professor _]) v(7.5%) abstract block(height:35%,fill:none) align(center,[*#creater, #time*]) } /* Outline page */ // Defualt depth is 2 #let outline_page(title) = { set page( paper:"us-letter", // Headers are set to right- and left-justified // on odd and even pages, respectively header: locate(loc => { if calc.odd(loc.page()) { align(right)[ #smallcaps[#title] #v(-6pt) #line(length: 40%) ] } else { align(left)[ #smallcaps[#title] #v(-6pt) #line(length: 40%) ] } }), footer: locate(loc => { align(center)[#loc.page()] }) ) show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong("§ " + it) } align(center, text(18pt, weight: "bold")[#title]) v(15pt) outline(title: none, depth: 2, indent: auto) } /* Body text page */ // Format the headers and headings of the body #let body_page(title, body) = { set page( paper:"us-letter", header: locate(loc => { let h1_before = query( heading.where(level: 1).before(loc), loc) let h1_after = query( heading.where(level: 1).after(loc), loc) // Right- and left-justified on odd and even pages, respectively // Automatically matches the nearest level 1 title if calc.odd(loc.page()) { if h1_before == (){ align(right)[_ #h1_after.first().body _ #v(-6pt) #line(length: 40%)] } else { align(right)[_ #h1_before.last().body _ #v(-6pt) #line(length: 40%)] } } else { if h1_before == (){ align(left)[_ #h1_after.first().body _ #v(-6pt) #line(length: 40%)] } else { align(left)[_ #h1_before.last().body _ #v(-6pt) #line(length: 40%)] } } }), footer: locate(loc => { align(center)[#loc.page()] }), ) set_headings(body) } /* All pages */ // Organize all types of pages // If you want to add or modify other global Settings, please do so here #let note_page(title, author, professor, creater, time, abstract, body) = { set document(title: title, author: author) set par(justify: true) show math.equation.where(block: true) :it=>block( width: 100%, align(center, it) ) cover_page(title, author, professor, creater, time, abstract) outline_page("Sommaire") body_page(title, body) }
https://github.com/MrToWy/Bachelorarbeit
https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/compose.typ
typst
#import("../Template/customFunctions.typ"): * #codly( skips: ((5, 6), (19, 7)), highlights:( (line: 12, fill: red, label: <volume>), ) ) ```yml name: studymodules_project services: frontend: image: localhost/studymodules-frontend backend: image: localhost/studybase-backend ports: - "3000:3000" environment: - NODE_ENV=production volumes: - C:\Users\tobi\studybase\docker-volume:/app/docker-volume documentation: image: localhost/studymodules-documentation ports: - "8080:80" - "443:443" latex-api: image: localhost/latex-api:latest ports: - "2345:8080" build: . command: make start environment: # SENTRY_DSN: CACHE_HOST: cache depends_on: - backend latex-poll-script: image: localhost/studymodules-latex:latest volumes: caddy_data: caddy_config: ```
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/ea2724-ai_hw/hw4.typ
typst
== HW4 Due 2024.04.09 #let ans(it) = [ #pad(1em)[ #text(fill: blue)[ #it ] ] ] === Question 5.9 5.9 本题以井字棋(圈与十字游戏)为例练习博弈中的基本概念. 定义 $X_n$ 为恰好有 $n$ 个 $X$ 而没有 $O$ 的行、列或者对角线的数目. 同样 $O_n$ 为正好有 $n$ 个 $O$ 的行、列或者对角线的数目. 效用函数给 $X_3=1$ 的棋局 $+1$, 给 $O_3 = 1$ 的棋局 $-1$. 所有其他终止状态效用值为 $0$. 对于非终止状态, 使用线性的评估函数定义为 $"Eval"(s) = 3X_2(s) + X_1(s) - (3 O_2(s) + O_1(s))$ . + 估算可能的井字棋局数. + 考虑对称性, 给出从空棋盘开始的深度为2的完整博弈树(即, 在棋盘上一个 $X$ 一个 $O$ 的棋局). + 标出深度为$2$的棋局的评估函数值. + 使用极小极大算法标出深度为$1$和$0$的棋局的倒推值,并根据这些值选出最佳的起始行棋. + 假设结点按对 $alpha-beta$ 剪枝的最优顺序生成, 圈出使用 $alpha-beta$ 剪枝将被剪掉的深度为2的结点. #ans[ + + 考虑到最小深度 $5$, 最大深度 $9$, 每个位置有 $3$ 种可能, 因此可能的井字棋局数为 $ sum_(i=5)^9 i! approx 4.1 times 10^5 $ 上述估算给出了实际局数的一个上界, 显然部分棋局在中途就会因为一方胜利而结束. 在此数量级上, 我们可以通过简单的程序给出实际上的井字棋局数: 完整的代码链接放在了 #link("https://github.com/tiankaima/USTC_AI_24/blob/main/utils/Q5_9.cpp")[这里], 运行后得到: ```text Total possible games: 255168 Total win for player 1: 131184 Total win for player 2: 77904 Total draw: 46080 ``` #rect(width: 100%, height: 0.2pt, fill: blue) + + + 如图: #align(center)[ #image("./imgs/Solution_5.9.jpg", width: 60%, fit: "contain") ] 其中 d 的最佳行棋为 顶点 / 中心处; 剪枝、评估函数值等已标注在图中. ] === Question 5.8 5.8 考虑图 5.17 中描述的两人游戏. + 根据如下约定画出完整博弈树: - 每个状态用 $(s_A, s_B)$表示, 其中 $s_A$ 和 $s_B$ 表示棋子的位置. - 每个终止状态用方框画出, 用圆圈写出它的博弈值. - 把循环状态(在到根结点的路径上已经出现过的状态)画上双层方框. 由于不清楚他们的值, 在圆圈里标记一个“? ”. + 给出每个结点倒推的极小极大值 (也标记在圆圈里). 解释怎样处理“?”值和为什么这么处理. + 解释标准的极小极大算法为什么在这棵博弈树中会失败, 简要说明你将如何修正它, 在 (b) 的图上画出你的答案. 你修正后的算法对于所有包含循环的游戏都能给出最优决策吗? + 这个4-方格游戏可以推广到$n$个方格, 其中. 证明如果 $n$ 是偶数 $A$ 一定能赢, 而 $n$ 是奇数则 $A$ 一定会输. #ans[ + + #align(center)[ #image("./imgs/Solution_5.8_1.jpg", width: 50%, fit: "contain") ] + 对上述循环状态, 可以先赋 $0$, 计算出重复节点真实值, 再回溯更新 ($alpha-beta$ 向前剪枝). 考虑一组循环的更新路径 $(P_1, dots.c, P_(2k), P_1)$, 考虑其中的一次更新 $P_i$, 即 $P_i^' = "MAX"("MIN"(dots.c "MIN"(P_i, dots.c )))$, 其中 $P_i = "MAX"("MIN"(dots.c "MIN"(0, dots.c )))$, 这样的更新是至多平凡的, 意味着从 $(P_i, P_(i-1), P_(i-2))$ 的更新至多为 $P_i$ 本身, 并且从一个节点开始停止. 对于 $"MIN"$ 节点的操作类似, 在一般性包含循环的游戏中都能给出最优决策. + 在上述博弈图中, 我们容易发现 - $n=3$ 时, B 总有必胜策略 (考虑从 $=>^A (1,3)$ 开始的子图, 并去掉 $=>^B (3,4)$ 的分枝) - $n=4$ 时, A 总有必胜策略 - $n=5$ 时, B的必胜策略: $(1,5) =>^A (2,5) =>^B (2,4) =>^A {(1,4), (3,4)}$, 前者可以视为颠倒的 $n=4$ 的情况(左右颠倒、选手颠倒), 后者的必胜策略: $ (3,4) =>^B (3,2) =>^A (x, 2) =>^B (x, 1) $ 即可获胜. #rect(stroke: blue.opacify(50%), inset: 1em)[ 考虑到对 $n<=2$ 时游戏无意义, 奇数的部分与偶数的部分讨论类似, 我们下面仅讨论 $n=2i, 2<=i<=k$ 时 A 有必胜策略, $n=2k+2$ 时 A 的必胜策略: $ (1, 2k+2) =>^A (2, 2k+2) =>^B (2, 2k+1) =>^A (3, 2k+1) &=>^B (3, 2k+2) =>^A dots.c quad & (2k-2) \ & =>^B (3, 2k) =>^A dots.c quad & (2k - 4) $ 只需要将 $n = 2k - 2$ 的策略应用到 $(3, 2k+2)$, $n = 2k - 4$ 的策略应用到 $(3, 2k)$ 即可(始终不向左走, 并且在 $B$ 第一次到达 $3$ 之前到达$2k+2$, 在此之前 B 不可能到达 $1$) ] ] === Question 5.13 请给出 $alpha - beta$ 剪枝正确性的形式化证明. 要做到这一点需要考虑图 5.18, 问题为是否要剪掉节点 $n_j$, 它是一个 MAX 节点, 是 $n_1$ 的一个后代. 基本思路是当且仅当 $n_1$ 的极小极大值可以被证明独立于 $n_j$ 的值时, 会发生剪枝. + $n_1$ 的值是所有后代节点的最小值 $n_1 = min(n_2, n_(2,1), dots.c , n_(2 b_2))$, 请为 $n_2$ 找到类似的表达式, 以便得到用$n_j$ 表示的 $n_1$ 的表达式. #ans[ $ &n_2 = max(n_(2,1), n_(2,2), dots.c , n_(2 b_2)) \ &n_1 = min(max(min( ... quad max(n_j, dots.c), dots.c), dots.c)) $ ] + #strike[深度为 $i$ 的结点 $n_i$ 的极小极大值已知, $l_i$ 是在结点 $n_i$ 左侧结点的极小值 (或者极大值). 同样, $r_i$ 是 $n_i$ 在右侧的未探索过的结点的极小值(或者极大值). 用 $l_i$ 和 $r_i$ 的值重写 $n_1$ 的表达式. ] *这个翻译完全不准确, 正确的翻译是:* $l_i$ 是在结点 $n_i$ 左侧结点的极小值 (或者极大值), 其大小已知. 同样, $r_i$ 是 $n_i$ 在右侧的未探索过的结点的极小值(或者极大值). 用 $l_i$ 和 $r_i$ 的值重写 $n_1$ 的表达式. #ans[ $ &n_1 = min(l_2, n_2, r_2) \ &n_2 = max(l_3, n_3, r_3) \ &dots \ &n_1 = min(l_2, max(l_3, dots.c , n_j, dots.c), r_1) $ ] + 现在重新形式化表达式, 来说明为了向 $n_1$ 施加影响, 不能超出由 $l_i$ 值得到的某特定界限. #ans[ // 根据 $alpha-beta$ 剪枝的递归性质, $forall i<j quad n_i$ 均能对 $n_1$ 施加影响, 这样的影响是逐层的, 意味着 $n_(i-1)$ 能对 $n_i$ 施加影响. 显然, 逐层的性质是*充要*的. // 考虑 $n_(j-2) = max(l_(j-1), n_(j-1), r_(j-1)) = max(l_(j-1), min(l_j, n_j, r_j), r_(j-1))$ // - 如果 $n_j > l_j$, 那么 $n_(j-1) tilde (l_j, r_j)$. 不存在从 $n_j$ 到 $n_(j-1)$ 的影响. // - 如果 $n_j < l_(j-1)$, 那么 $min(l_j, n_j, r_j) < n_j < l_(j-1) => n_(j-2) tilde (l_(j-1), r_(j-1))$, 不存在从 $n_(j-1)$ 到 $n_(j-2)$ 的影响. // 对以上讨论进行归纳, 容易得到 $n_j > l_(2k + 1), forall k$ // 考虑所有 MAX 节点 $2k-1$ 的 子节点, $l_(2k)$ 是已经探索过的最大值. 如果 $n_j < l_(2k)$, 在如下的操作时, $n_j$ 的值会被忽略: // $ // n_(2k-1) = max(l_(2k), n_(2k), r_(2k)) > l_(2k) > n_j // $ 考虑对定义做如下改进, 我们自下而上定义 $n_(2k+1)^' = max(l_(2k+2), n_(2k+2))$ 以及 $n_(2k)^' = min(l_(2k), n_(2k+1))$: $ &n_1^' = min(l_2, n_2) \ &n_2^' = max(l_3, n_3) \ &dots \ &n_(j-1)^' = min(l_j, n_j) \ $ 这样 $n_j$ 对 $n_1$ 施加影响 $<=>$ $n_1^' = n_2^' = dots.c = n_j$ 因此只需要满足: $forall i = 2k$, $n_i^' <=l_i$, $forall i = 2k+1$, $n_i^' >= l_i$, $ n_j = n_i^' <= l_i, &forall i = 2k + 1 &quad => quad n_j &<= min(l_3, l_5, dots.c, l_(j-1)) &= beta\ n_j = n_i^' >= l_i, &forall i = 2k &quad => quad n_j &>= max(l_2, l_4, dots.c, l_j) &= alpha $ 对应到 $n_j$ 作为 MAX 节点: - $max(n_(j+1, 1), n_(j+1, 2), dots.c n_(j+1, b_(j+1))) <= beta$, 因此 只需要在遍历子节点时, 保证 $n_(j, b_i) <= beta$ - $max(n_(j+1, 1), n_(j+1, 2), dots.c n_(j+1, b_(j+1))) >= alpha$, 可在遍历后由父节点 (MIN) 判断 不满足上述要求的节点可以被剪掉. ] + 假设 $n_j$ 是 MIN 节点的情况, 请重复上面的过程. #ans[ 对应到 $n_j$ 作为 MIN 节点: - $min(n_(j+1, 1), n_(j+1, 2), dots.c n_(j+1, b_(j+1))) <= beta$, 可在遍历后由父节点 (MAX) 判断 - $min(n_(j+1, 1), n_(j+1, 2), dots.c n_(j+1, b_(j+1))) >= alpha$, 因此 只需要在遍历子节点时, 保证 $n_(j, b_i) >= alpha$ 上述过程实际上给出了 $alpha-beta$ 剪枝的一个构造, 保证了形式化证明的正确性. ]
https://github.com/jakoblistabarth/ica-conference-series-abstract-template
https://raw.githubusercontent.com/jakoblistabarth/ica-conference-series-abstract-template/main/README.md
markdown
# typst template for the ICA abstracts of the ICA conferences series This repo implements the official [ICA abstracts of the ICA conference series](https://www.abstracts-of-the-ica.net/) as [typst](https://typst.app/docs/) template. It is based in particular on the official [`LaTeX` Template](https://www.ica-conference-publications.net/ica_latex_template.html). > [!CAUTION] > The bibliography style (the way your citations in the text body and your references show up) differs (slightly) from the official `LaTeX` template. ## What is typst? > Typst is a new markup-based typesetting system that is designed to be as powerful as LaTeX while being much easier to learn and use. > > – From the [typst github repo](https://github.com/typst/typst) ## How to use ### 🔧 1. Install `typst` See [here](https://github.com/typst/typst?tab=readme-ov-file#installation) for more information on how to install `typst` on your system. ### 📜 2. Make sure required fonts are available Make sure the required font _Times New Roman_ is installed (and activated) on your system. ### 🚀 3. Compile the document Compile the document to a `.pdf` file by running: ```bash typst c main.typ ``` To watch the file for changes and recompile the output on save (super fast, thanks to `typst`!) run: ```bash typst w main.typ ``` You can define a custom output path for the above two commands: ```bash typst c main.typ my-abstract.pdf ``` ### 🧪 4. Adjust the metadata You can set the document's `title`, the `keywords`, a `bib` file and the authors and their affiliations at the beginning top of the `main.typ`, via the arguments in the function call of `ica-abstract`. #### `title` The `title` can either be a string (`"My awesome title"`) or a `content` (`[My awesome title]`) #### `authors` The `authors` argument needs to be an array of which each item corresponds to one author. Every author has a name and one ore multiple affiliations. Additionally, the attribute `corresponding` can be set to `true` for the corresponding author. Every author's affiliation need to have at least an `id` which corresponds to the position in the affiliations array. Optionally, an e-mail address for the respective author at the respective affiliation, can be set via the `email` attribute. > [!TIP] > The `authors` array in `main.typ` can serve as a starting point. #### `affiliations` The `affiliations` argument is an `array` of `string`s, containing the names of the each affiliation. #### `keywords` The `keywords` argument is optional, though storngly recommended. It needs to be an `array` of `string`s. #### `bibliography-file` The `bibliography-file` arguments is optional. If you want to use citations you can define the name or (or the path) to a `.bib` file. ## Limitations / To-Dos - [ ] The bibliography style used at the moment seems to be close to the one in the in `LaTeX` template but is not yet 100% correct (e.g., Volumes are not indicated)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/pintorita/0.1.0/pintorita.typ
typst
Apache License 2.0
#import "@preview/jogs:0.2.2": compile-js, call-js-function #let pintora-src = read("./pintora.js") #let pintora-bytecode = compile-js(pintora-src) #let render(src, ..args) = { let svg-output = call-js-function(pintora-bytecode, "PintoraRender", src) let named-args = args.named() let factor = named-args.at("factor",default:none) if (factor != none){ let svg-width = svg-output.find(regex("width=\"(\d+)")).find(regex("\d+")) let new-width = int(svg-width) * factor * 1pt named-args.insert("width", new-width) let junk = named-args.remove("factor") } image.decode(svg-output, ..args.pos(), ..named-args) }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/with_element.typ
typst
Apache License 2.0
#let g = text.with(/* position */);
https://github.com/jneug/typst-mantys
https://raw.githubusercontent.com/jneug/typst-mantys/main/src/theme.typ
typst
MIT License
#let page = ( paper: "a4", margin: auto ) #let fonts = ( serif: ("Linux Libertine", "Liberation Serif"), sans: ("Liberation Sans", "Helvetica Neue", "Helvetica"), mono: ("Liberation Mono"), text: ("Linux Libertine", "Liberation Serif"), headings: ("Liberation Sans", "Helvetica Neue", "Helvetica"), code: ("Liberation Mono") ) #let font-sizes = ( text: 12pt, headings: 12pt, // Used as a base size, scaled by heading level code: 9pt ) #let colors = ( primary: eastern, // rgb(31, 158, 173), secondary: teal, // rgb(18, 120, 133), argument: navy, // rgb(0, 29, 87), option: rgb(214, 182, 93), value: rgb(181, 2, 86), command: blue, // rgb(75, 105, 197), comment: gray, // rgb(128, 128, 128), module: rgb("#8c3fb2"), text: rgb(35, 31, 32), muted: luma(210), info: rgb(23, 162, 184), warning: rgb(255, 193, 7), error: rgb(220, 53, 69), success: rgb(40, 167, 69), // Datatypes taken from typst.app dtypes: { let red = rgb(255, 203, 195) let gray = rgb(239, 240, 243) let purple = rgb(230, 218, 255) let gradient-colors = ( (rgb("#7cd5ff"), 0%), (rgb("#a6fbca"), 33%), (rgb("#fff37c"), 66%), (rgb("#ffa49d"), 100%), ) ( // special any: gray, "auto": red, "none": red, // foundations arguments: gray, array: gray, bool: rgb(255, 236, 193), bytes: gray, content: rgb(166, 235, 229), datetime: gray, dictionary: gray, float: purple, function: gray, int: purple, location: gray, plugin: gray, regex: gray, selector: gray, str: rgb(209, 255, 226), type: gray, label: rgb(167, 234, 255), // layout alignment: gray, angle: purple, direction: gray, fraction: purple, length: purple, ratio: purple, relative: purple, // visualize color: gradient.linear(..gradient-colors), gradient: gradient.linear(..gradient-colors), stroke: gray, ) } )
https://github.com/Mc-Zen/tidy
https://raw.githubusercontent.com/Mc-Zen/tidy/main/tests/test_parse_argument_list.typ
typst
MIT License
#import "/src/tidy-parse.typ": * //// General test #{ let str = "#let func(p1, p2: 3pt, p3: (), p4: (entries: ()), p5, \"as:d\")" let (args, processed-chars) = parse-argument-list(str, 9) assert.eq(processed-chars, str.len() - 9) assert.eq(args.len(), 6) assert.eq(args.at(0), ("p1",)) assert.eq(args.at(1), ("p2", "3pt")) assert.eq(args.at(2), ("p3", "()")) assert.eq(args.at(3), ("p4", "(entries: ())")) assert.eq(args.at(4), ("p5",)) assert.eq(args.at(5), ("\"as:d\"",)) } // Comma after last argument #{ let str = "#let func(p1,)" let (args, processed-chars) = parse-argument-list(str, 9) assert.eq(processed-chars, str.len() - 9) assert.eq(args.len(), 1) } // line breaks in argument list #{ let str = "#let func(p1\n,p2\n,\n\n)\n" let (args, processed-chars) = parse-argument-list(str, 9) assert.eq(processed-chars, str.len() - 10) assert.eq(args.len(), 2) } // #parse-argument-list("#let func(p1, p2: 3pt, p3: (), p4: (entries: ()), p5)", 9)
https://github.com/jakoblistabarth/ica-conference-series-abstract-template
https://raw.githubusercontent.com/jakoblistabarth/ica-conference-series-abstract-template/main/main.typ
typst
#import "ica-abstract.typ": * #show: ica-abstract.with( title: "Guidelines for authors preparing manuscripts for publication in the Abstracts of the ICA conference series (Title of paper)", authors: ( ( name: "<NAME>", affiliations: ( id: 1, email: "<EMAIL>", ), corresponding: true, ), ( name: "<NAME>", affiliations: ( (id: 1, email: "<EMAIL>"), (id: 2), ), ), ( name: "<NAME>", affiliations: ( (id: 1, email: "<EMAIL>"), ) ), ( name: "<NAME>", affiliations: ( (id: 2, email: "<EMAIL>"), ), ), ), affiliations: (("Affiliation"), ("Affiliation"),), keywords: ("guidelines", "formatting", "style", "Abstracts of the ICA"), bibliography-file: "ICAguidelines_bib.bib" ) These are ICA guidelines for submitting abstracts to supplement ICA guidelines for preparation of papers. All abstracts for abstract-only submission to ICA-events must follow these guidelines and be written using this template. The ICA-event organizers may omit any paper that does not conform to the specified requirements. An abstract for abstract-only submission must be *within maximum 2 pages*, single-spaced, A4 size (297 #sym.times 210mm / 11.69 #sym.times 8.27 inches). The font type Times New Roman with a size of ten (10) points is to be used. Use of paragraphing is encouraged. Section headings should not be used. Although full references are not expected, it is permitted to cite others' works with author and date information, e.g. #cite(<AAS92>, form: "prose"), #cite(<AHNFRE84>, form: "prose"), #cite(<WERDER2010>, form: "prose"). References should be listed in alphabetical order in the reference section. #figure( image("ica-logo.svg", width: 40%), caption: [Example figure, placement, caption and numbering: the famous ICA logo] ) Tables and figures may be used. When using tables or figures, captions should be used, centered directly beneath the tables or figures. All captions are to be numbered consecutively, e.g. Figure 1, Table 2, Figure 2. #figure( table( columns: 3, stroke: (x: 0.5pt, y: none), inset: (y: 3pt), align: (left, center, center), table.header( table.hline(y: 0, stroke: 0.5pt), table.hline(y: 1, stroke: 0.5pt), table.hline(y: 6, stroke: 0.5pt), [Setting], table.cell(colspan: 2)[A4 size paper], ), [], [mm], [inches], [Top], [25], [1.0], [Bottom], [28], [1.1], [Left], [20], [0.8], [Right], [20], [0.8], ), caption: [Margin settings for A4 size paper] ) The Abstracts of the International Cartographic Association (Abstracts of the ICA) are the conference series that publishes abstracts accepted for conferences and workshops organized by the ICA. The abstracts undergo an abstract-based review by the programme committee. The Abstracts of the ICA are open-access publications; they are published under the Creative Commons Attribution 4.0 License and the authors retain the copyright. Abstracts are intended to present very early or practical work. They provide a platform for artwork, demonstrations, or work of practitioners - work that would otherwise not be very well suited for a description in an extended scientific paper. Still, the publication of the abstract is very valuable both for the authors and for the participants of the meeting. Abstracts are reviewed based on quality and innovativeness, as well as on the practical relevance. // optional = Acknowledgements Acknowledgements of support for the project / paper / author are welcome.
https://github.com/jhnko/umu-templates
https://raw.githubusercontent.com/jhnko/umu-templates/main/report/main.typ
typst
The Unlicense
#import "@preview/codelst:2.0.1": sourcecode, code-frame #import "template.typ": * // Makes the code listings look a bit nicer. #let code-frame = code-frame.with( fill: none, stroke: 0.6pt + luma(150), ) #let sourcecode = sourcecode.with(frame: code-frame) #show heading: it => { set text(weight: "regular") let above = if it.level > 1 { 2em } else { 1em } block( above: above, it, ) } #show figure.where(kind: table): set figure.caption(position: top) // A list of authors #let authors = (( name: "<NAME>", // username: "c00abc", email: "<EMAIL>", ), // The comma is needed to make this a list with a single element rather than a dictionary. ) #let course = ( name: "Kursnamn", code: "5DV999", ) // Specify the language of the document here. #let lang = "sv" // Assignments usually follow the pattern "Obligatorisk uppgift 1", "Obligatorisk uppgift 2", etc. // Feel free to just use `subtitle` and `top_left_title` directly. #let assignment = ( name: "Uppgiftsnamn", number: 1, type: if lang == "sv" { "Obligatorisk uppgift" } else { "Assignment" }, ) // Assignment titles usually follow the pattern "Obligatorisk uppgift 1", "Obligatorisk uppgift 2", etc. // Feel free to just use `subtitle` and `top_left_title` directly. #let assignment_title = [#assignment.type #assignment.number] // See template.typ for more parameters. #show: doc => conf( title: [#course.code #course.name], // Feel free to use `title` directly subtitle: [#assignment_title #sym.dash.em #assignment.name], margin: (x: 1.25in, y: 1.5in), lang: lang, authors: authors, // Disable the outline page by usings the line below: // outline: none, cols: 1, // Why not make the template your own and add your own parameters to the template? doc, ) // The choice of headings is completely up to you. #if lang == "sv" [ = Introduktion ] else [ = Introduction ] Skriv en introduktion här. = En till rubrik Planeten _Caladan_ är <NAME> hemvärld @dune. Nu ska jag visa lite matte och kod. == Matematik <math> Jag vet att om $a > b$ och $b > c$ så är $a > c$. Igår insåg jag även att två halvor blir en hel: $ 0.5 + 0.5 = 1 $ == Programmering Rust är ett vackert programmeringsspråk, kolla här: ```rust fn main() { let apples_per_bag = vec![5, 4, 3, 5, 7, 2]; let total_apples = grades.iter().sum(); let bag_count = apples_per_bag.len(); println!("We have {total_apples} apples in the {bag_count} bags."); } ``` Som ni såg så använde jag mina additionskunskaper, som jag demonstrerade i avsnitt @math. #figure( caption: [Mängden frukt på kontoret.], table( columns: 2, table.header([Frukt], [Antal]), [Äpple, 5], [Apelsin, 3], [Banan], [2], [Päron], [4], [Kiwi], [1], ), ) #let thin_black = 0.6pt + black #figure( caption: [Mängden bilar på parkeringen.], table( columns: 2, stroke: none, table.header([Bilfärg], table.vline(stroke: thin_black), [Antal]), table.hline(stroke: thin_black), [Svart], [5], [Blå], [3], [Röd], [2], [Grå], [4], [Gul], [1], ), ) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam aliquet tempus mattis. Vivamus molestie non ligula at tristique. Fusce tincidunt a turpis eget pretium. Vivamus odio orci, congue sit amet risus a, consequat feugiat eros. Suspendisse potenti. Pellentesque feugiat malesuada egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque aliquet porttitor tempus. In et lectus nulla. Aliquam vel arcu aliquam, porta felis scelerisque, placerat massa. Donec dapibus pulvinar interdum. In at lobortis sem. Nam lacinia ex non tempor pulvinar. Nullam luctus blandit sem a facilisis. Duis et magna pretium, tempor mauris at, congue eros. #bibliography( "reference.yml", style: "./karlstad-universitet-harvard.csl", title: if lang == "sv" { "Referenser" } else { "References" }, )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-30A0.typ
typst
Apache License 2.0
#let data = ( ("KATAKANA-HIRAGANA DOUBLE HYPHEN", "Pd", 0), ("KATAKANA LETTER SMALL A", "Lo", 0), ("KATAKANA LETTER A", "Lo", 0), ("KATAKANA LETTER SMALL I", "Lo", 0), ("KATAKANA LETTER I", "Lo", 0), ("KATAKANA LETTER SMALL U", "Lo", 0), ("KATAKANA LETTER U", "Lo", 0), ("KATAKANA LETTER SMALL E", "Lo", 0), ("KATAKANA LETTER E", "Lo", 0), ("KATAKANA LETTER SMALL O", "Lo", 0), ("KATAKANA LETTER O", "Lo", 0), ("KATAKANA LETTER KA", "Lo", 0), ("KATAKANA LETTER GA", "Lo", 0), ("KATAKANA LETTER KI", "Lo", 0), ("KATAKANA LETTER GI", "Lo", 0), ("KATAKANA LETTER KU", "Lo", 0), ("KATAKANA LETTER GU", "Lo", 0), ("KATAKANA LETTER KE", "Lo", 0), ("KATAKANA LETTER GE", "Lo", 0), ("KATAKANA LETTER KO", "Lo", 0), ("KATAKANA LETTER GO", "Lo", 0), ("KATAKANA LETTER SA", "Lo", 0), ("KATAKANA LETTER ZA", "Lo", 0), ("KATAKANA LETTER SI", "Lo", 0), ("KATAKANA LETTER ZI", "Lo", 0), ("KATAKANA LETTER SU", "Lo", 0), ("KATAKANA LETTER ZU", "Lo", 0), ("KATAKANA LETTER SE", "Lo", 0), ("KATAKANA LETTER ZE", "Lo", 0), ("KATAKANA LETTER SO", "Lo", 0), ("KATAKANA LETTER ZO", "Lo", 0), ("KATAKANA LETTER TA", "Lo", 0), ("KATAKANA LETTER DA", "Lo", 0), ("KATAKANA LETTER TI", "Lo", 0), ("KATAKANA LETTER DI", "Lo", 0), ("KATAKANA LETTER SMALL TU", "Lo", 0), ("KATAKANA LETTER TU", "Lo", 0), ("KATAKANA LETTER DU", "Lo", 0), ("KATAKANA LETTER TE", "Lo", 0), ("KATAKANA LETTER DE", "Lo", 0), ("KATAKANA LETTER TO", "Lo", 0), ("KATAKANA LETTER DO", "Lo", 0), ("KATAKANA LETTER NA", "Lo", 0), ("KATAKANA LETTER NI", "Lo", 0), ("KATAKANA LETTER NU", "Lo", 0), ("KATAKANA LETTER NE", "Lo", 0), ("KATAKANA LETTER NO", "Lo", 0), ("KATAKANA LETTER HA", "Lo", 0), ("KATAKANA LETTER BA", "Lo", 0), ("KATAKANA LETTER PA", "Lo", 0), ("KATAKANA LETTER HI", "Lo", 0), ("KATAKANA LETTER BI", "Lo", 0), ("KATAKANA LETTER PI", "Lo", 0), ("KATAKANA LETTER HU", "Lo", 0), ("KATAKANA LETTER BU", "Lo", 0), ("KATAKANA LETTER PU", "Lo", 0), ("KATAKANA LETTER HE", "Lo", 0), ("KATAKANA LETTER BE", "Lo", 0), ("KATAKANA LETTER PE", "Lo", 0), ("KATAKANA LETTER HO", "Lo", 0), ("KATAKANA LETTER BO", "Lo", 0), ("KATAKANA LETTER PO", "Lo", 0), ("KATAKANA LETTER MA", "Lo", 0), ("KATAKANA LETTER MI", "Lo", 0), ("KATAKANA LETTER MU", "Lo", 0), ("KATAKANA LETTER ME", "Lo", 0), ("KATAKANA LETTER MO", "Lo", 0), ("KATAKANA LETTER SMALL YA", "Lo", 0), ("KATAKANA LETTER YA", "Lo", 0), ("KATAKANA LETTER SMALL YU", "Lo", 0), ("KATAKANA LETTER YU", "Lo", 0), ("KATAKANA LETTER SMALL YO", "Lo", 0), ("KATAKANA LETTER YO", "Lo", 0), ("KATAKANA LETTER RA", "Lo", 0), ("KATAKANA LETTER RI", "Lo", 0), ("KATAKANA LETTER RU", "Lo", 0), ("KATAKANA LETTER RE", "Lo", 0), ("KATAKANA LETTER RO", "Lo", 0), ("KATAKANA LETTER SMALL WA", "Lo", 0), ("KATAKANA LETTER WA", "Lo", 0), ("KATAKANA LETTER WI", "Lo", 0), ("KATAKANA LETTER WE", "Lo", 0), ("KATAKANA LETTER WO", "Lo", 0), ("KATAKANA LETTER N", "Lo", 0), ("KATAKANA LETTER VU", "Lo", 0), ("KATAKANA LETTER SMALL KA", "Lo", 0), ("KATAKANA LETTER SMALL KE", "Lo", 0), ("KATAKANA LETTER VA", "Lo", 0), ("KATAKANA LETTER VI", "Lo", 0), ("KATAKANA LETTER VE", "Lo", 0), ("KATAKANA LETTER VO", "Lo", 0), ("KATAKANA MIDDLE DOT", "Po", 0), ("KATAKANA-HIRAGANA PROLONGED SOUND MARK", "Lm", 0), ("KATAKANA ITERATION MARK", "Lm", 0), ("KATAKANA VOICED ITERATION MARK", "Lm", 0), ("KATAKANA DIGRAPH KOTO", "Lo", 0), )
https://github.com/SillyFreak/typst-packages-old
https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/scrutinize/gallery/test.typ
typst
MIT License
#import "@preview/scrutinize:0.2.0": grading, question, questions // #import "../src/lib.typ" as scrutinize: grading, question, questions // you usually want to alias this, as you'll need it often #import question: q // make the PDF reproducible to ease version control #set document(date: none) #set table(stroke: 0.5pt) // let's show the available points to the right of each // question's title and give the grader a space to put points #show heading: it => { // here, we need to access the current question's metadata [#it.body #h(1fr) / #question.current().points] } // for grading, we need to consider all questions #context { let qs = question.all() let total = grading.total-points(qs) // the total-points function can also accept a filter function let hard = grading.total-points(qs, filter: q => q.points >= 5) // create a grading key let grades = grading.grades([bad], total * 2/4, [okay], total * 3/4, [good]) // adjust the key to you individual needs. Here // - for the lowest grade, the upper limit is exclusive, we render as "< limit" // - for the second lowest grade, both limits are inclusive, we render as "limit - limit" // - for the other grades, lower limit is exclusive, upper inclusive, we render as "limit - limit" // for exclusivity, we add half a point to the limit and for the highest grade we use total points let grades = grades.enumerate().map(((i, (body, lower-limit, upper-limit))) => { if lower-limit == none { (body: body, range: [< #upper-limit P.]) } else if i == 1 { (body: body, range: [#(lower-limit) - #upper-limit P.]) } else if upper-limit != none { (body: body, range: [#(lower-limit + 0.5) - #upper-limit P.]) } else { (body: body, range: [#(lower-limit + 0.5) - #total P.]) } }) // render a table with the points table( columns: (auto, ..(1fr,) * grades.len()), align: (col, row) => if col == 0 { left + horizon } else { center + horizon }, [Points], ..grades.map(g => g.range), [Grade], ..grades.map(g => g.body), ) [Points from hard questions: #hard] } // the q function adds metadata to a question #q(points: 6)[ = Hard Question #lorem(20) ] #v(1fr) #context [ #let points = question.current().points This question is worth #points points. I may award up to #(points + 1) points for great answers! ] #q(points: 2)[ = Question #lorem(20) ] #v(1fr)
https://github.com/htlwienwest/da-vorlage-typst
https://raw.githubusercontent.com/htlwienwest/da-vorlage-typst/main/lib/template.typ
typst
MIT License
#import "elements.typ" as elems #import "settings.typ" as settings #import "fontchecker.typ" as fc #import "assertions.typ": * #let diplomarbeit( titel: none, abteilung: none, unterschrifts-datum: none, schuljahr: none, autoren: none, kurzfassung: none, abstract: none, vorwort: none, danksagung: none, anhang: none, literaturverzeichnis: none, body ) = { assertNotNone(titel, message: "Der Titel muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(abteilung, message: "Die Abteilung muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(schuljahr, message: "Das Schuljahr muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(unterschrifts-datum, message: "Das Datum der Unterschrift für die Eidesstaatliche-Erklärung muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(autoren, message: "Die Autoren müssen in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(kurzfassung, message: "Die Kurzfassung muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(abstract, message: "Der Abstract muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(vorwort, message: "Das Vorwort muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(danksagung, message: "Die Danksagung muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") assertNotNone(literaturverzeichnis, message: "Der Pfad zum Literaturverzeichnis muss in den Diplomarbeits-Konfigurationen (`diplomarbeit.with(...)`) gesetzt sein") if anhang != none { assertType(anhang, "content", message: "Wenn der Parameter `anhang` gesetzt ist, muss er `content` sein. Alternativ kann er auf `none` gesetzt oder aus den Übergabeparametern entfernt werden") } // check autoren assertType(autoren, "array", message: "Der Parameter `autoren` hat einen falschen Typen") for t in autoren { assertType(t, "dictionary", message: "Autor hat falschen Typen") assertDictKeys(t, ("vorname", "nachname", "klasse", "betreuer"), message: "Autor ist ungültig") assertDictKeys(t.betreuer, ("name", "geschlecht"), message: "Betreuer eines Autors ist ungültig") assertEnum(t.betreuer.geschlecht, ("male","female"), message: "`betreuer_geschlecht` muss korrekten Wert enthalten") } let title = titel // ========== global definitions ============ set page("a4") set page(margin: ( inside: settings.PAGE_MARGIN_INSIDE, outside: settings.PAGE_MARGIN_OUTSIDE, bottom: 2cm, )) // ------ text, paragraph and block ------ set text( 11pt, font: settings.FONT_PRIMARY, hyphenate: false, lang: "de" ) set par(leading: 0.7em, justify: true) set block(below: 1.7em) // ----------- headings ---------- // heading settings show heading: set text(weight: "regular") show heading.where(level: 1): set text(size: 16pt) show heading.where(level: 2): set text(size: 14pt) show heading.where(level: 3): set text(size: 12pt) // numbering show heading: it => { let elems = () if (it.numbering != none and it.body != [Inhaltsverzeichnis]) { elems.push(counter(heading).display()) } elems.push(it.body) grid( columns: 2, column-gutter: 4mm, ..elems ) } // support `Ausgearbeitet von ...` substrings show heading: it => { if it.level > 2 { return it } let author = elems.elaborated_by it text(9pt, author, style: "italic") } show heading: set block(below: 0pt) // spacing show heading: it => { if it.level == 1 { it v(8mm, weak: true) // pad(bottom: 8mm, it) } else if it.level == 2 { v(3mm) it v(6mm, weak: true) } else { pad(top: 0mm, bottom: 4mm, it) } } // -------- figures -------- show figure: set text(9pt, style: "italic", fill: rgb("#44546c")) set figure(gap: 3.5mm) show figure: set block(below: 8mm) // --------- outline and bibliography ------- // add outlines to Inhaltsverzeichnis, except for Inhaltsverzeichnis itself // and make first level entries bold show outline.where(title: [Inhaltsverzeichnis]): it => { set heading(outlined: false) it } show outline: set heading(outlined: true) show outline: set heading(numbering: "1") show bibliography: set heading(numbering: "1") // modify spacing of entires // modify outline entries // add spacing between numbering and text show outline.entry: it => { let t = counter(heading).display() let e = it.element if ( e.has("supplement") and e.supplement == [Abschnitt] and e.numbering != none ) { let c = counter(heading).at(it.element.location()) numbering(it.element.numbering, ..c) h(2mm) it.element.body box(width: 1fr, it.fill) it.page } else { it } } // show outline.entry: it => { // // v(1.5em, weak: true) // it // } // ------- Common Elements ------------- show link: underline show raw.where(block: true): set block(stroke: 0.2pt, inset: 2mm) show raw.where(block: false): box.with( fill: luma(235), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) set list( indent: 6mm, marker: ([$circle.filled.small$], [$circle.stroked.small$], [$square.filled.tiny$]), body-indent: 3mm, ) set enum( indent: 6mm, numbering: "1.a.i.", body-indent: 3mm, ) // =============== Content ============== // -------- Check if Fonts are available fc.checkfont(settings.FONT_PRIMARY) fc.checkfont(settings.FONT_ACCENT) // -------- Vordefinierte Seiten ------- //Deckblatt import "pages/deckblatt.typ": deckblatt deckblatt(title, abteilung, schuljahr, autoren) // keep one blank page pagebreak(to: "odd") set page(numbering: "i") // set correct header margin set page( margin: ( outside: settings.PAGE_MARGIN_OUTSIDE, inside: settings.PAGE_MARGIN_INSIDE, top: settings.HEADER_HEIGHT, ) ) // set common header and footer set page( header: elems.common_header(title), footer: elems.common_footer(autoren), footer-descent: 0%, ) counter(page).update(1) { //Eidesstattliche Erklärung import "pages/eidesstattliche.typ": eidesstattliche let persons = autoren.map(e => [#e.vorname #e.nachname]) eidesstattliche(datum: unterschrifts-datum, persons: persons) pagebreak() //Eidesstattliche Erklärung import "pages/dokumentation.typ": dokumentation dokumentation() pagebreak() //Kurzfassung [= Kurzfassung <Kurzfassung>] kurzfassung pagebreak() //Abstract [= Abstract <Abstract>] abstract pagebreak() //Vorwort [= Vorwort <Vorwort>] vorwort pagebreak() //Inhaltsverzeichnis outline( title: "Inhaltsverzeichnis", indent: 2em ) } // ------------------------------- // Numerierung der Seiten festlegen set page(numbering: "1") counter(page).update(1) // Danksagung [= Danksagung <Danksagung>] danksagung pagebreak(weak: true) // Nummerierung der Kapitel festlegen set heading(numbering: "1.1") counter(heading).update(0) // start of actual DA writing [#metadata((type: "start-of-body")) <startOfBody>] { // add pagebreak before each level 1 heading (except for first heading after outline) show heading.where(level: 1): it => { if counter(heading).at(it.location()).first() != 1 { pagebreak() } it } body } pagebreak() [#metadata((type: "end-of-body")) <endOfBody>] // -------- Vordefinierte Seiten -------- //Abbildungsverzeichnis outline( title: "Abbildungsverzeichnis", target: figure.where(kind: image), ) pagebreak() //Tabellenverzeichnis outline( title: "Tabellenverzeichnis", target: figure.where(kind: table), ) pagebreak() // Literaturverzeichnis literaturverzeichnis( title: [Literaturverzeichnis] ) pagebreak() counter(heading).update(0) set heading(numbering: "A") // Arbeitsaufteilung import "pages/arbeitsaufteilung.typ": arbeitsaufteilung let aufteilungen = autoren .map(a => ([#a.vorname #a.nachname], a.aufgaben)) arbeitsaufteilung(aufteilungen: aufteilungen) // Anhang if (anhang != none) { pagebreak() [= Anhang <Anhang>] anhang } } // This is used by the #let autor(author) = { metadata((type: "author", value: author)) }
https://github.com/matchy233/typst-chi-cv-template
https://raw.githubusercontent.com/matchy233/typst-chi-cv-template/main/template/resume.typ
typst
MIT License
#import "/src/chicv.typ": * #show: chicv.with( margin: (x: 1cm, top: 1.5cm, bottom: 2cm), par-padding: (left: 0pt, right: 0pt), ) = <NAME> #personal-info( email: "<EMAIL>", github: "https://github.com/skyzh", website: "https://skyzh.dev", linkedin: "https://www.linkedin.com/in/alex-chi-skyzh/", // x-twitter: "https://twitter.com/iskyzh", // (link: "https://typst.app/", text: "Typst", icon: "t", solid: true), ) == Education #cventry( tl: "Carnegie Mellon University", tr: dates(from: "2022/08", to: "2023/12"), bl: "Master of Science in Computer Science, GPA 4.10/4.33", br: "Pittsburgh, PA, USA" )[ - Teaching Assistant for 15-445/645 Database Systems (Fall 2022, Spring 2023, Fall 2023) - Courses: Distributed Systems, Compiler Design, Advanced Database Systems, Deep Learning Systems, etc. ] // by default, #cventry will bold top-left text #cventry( tl: "Shanghai Jiao Tong University", tr: dates(from: "2018/09", to: "2022/06"), bl: "Bachelor of Engineering in Computer Science and Technology", br: "Shangehai, China" )[ - GPA 93.80/100, Rank 1/149, National Scholarship 2019 (Top 0.2% national-wide) - A+ Courses: Operating Systems, Computer Architecture, Computer Networks, and 28 others ] == Work Experience // but you can override the default bold style by passing content blocks #cventry( tl: [#link("https://neon.tech")[*Neon*]], tr: dates(from: "2024/02"), bl: [Systems Software Engineer], br: [Remote / Pittsburgh, PA, USA], // you can also override the default padding of content blocks padding: (bottom: -5pt) )[] #cventry( tl: [_... and also_], tr: dates(from: "2023/05", to: "2023/08"), bl: [Software Engineer Intern], br: [Remote / Pittsburgh, PA, USA], )[ - Neon is a fully-managed PostgreSQL service built on a key-value storage engine with point-to-time recovery support. - *Compaction Strategy Enhancement*. Conducted an in-depth analysis and evaluation of the storage engine to assess performance metrics and storage space efficiency. Implemented the RocksDB-style tiered compaction and improved page reconstruction strategy, which reduced space amplification by 2x and enhanced read-update performance by 20%. - *Improved User Adoption on the Edge*. Enhanced the overall reliability of the Neon serverless driver and the control plane proxy. Collaborated closely with the #link("https://github.com/prisma/prisma", [Prisma]) ORM team to integrate the serverless driver into Prisma and ensured compatibility with Vercel Edge Runtime by transitioning the Rust Prisma engine codebase to be WebAssembly-ready. ] #cventry( tl: [#link("https://risingwave.com/", [*RisingWave Labs*])], tr: dates(from: "2021/08", to: "2022/07"), bl: [Database System R&D Intern], br: [Shanghai, China] )[ - *Top contributor of #githublink("https://github.com/risingwavelabs/risingwave", text: "RisingWave")*. RisingWave is a database system with PostgreSQL-compatible interface that incrementally maintains materialized views. Worked on features including streaming index joins, query optimization of stream plans, distributed streaming execution, cloud-native LSM state store, vectorized expression framework. - *Streaming Index Joins*: Designed shared state and streaming index in RisingWave; implemented index lookup join executor; implemented delta join DAG optimizer transformations; implemented distributed delta join scheduler. - *Performance Improvement*: Conducted intensive benchmarks and analyzed performance issues. Fixed bugs, proposed strategies, and led cross-team collaboration which improved the system throughput by 10x in a 3-month period. - *Developer Experience*. Initiated the RiseDev development tool and the developer dashboard, which is deeply integrated into the development workflow across debugging, unit testing, integration testing, and benchmarking. - *Mentoring*. Mentored database kernel interns and helped their successful integration into the team. Maintained overview documents of the database kernel to facilitate knowledge transfer and help new hires learn about the system. ] #cventry( tl: "ByteDance", tr: dates(from: "2021/06", to: "2021/08"), bl: "Storage System R&D Intern, TerarkDB Team", br: "Beijing, China" )[ - *Co-Optimized #githublink(text: "TerarkDB", "https://github.com/bytedance/terarkdb")* and *#githublink(text: "ZenFS", "https://github.com/westerndigitalcorporation/zenfs")*. TerarkDB is a fork of RocksDB and ZenFS is a filesystem on Zoned Namespaces (ZNS) SSDs. Implemented Zone-aware Garbage Collection in TerarkDB for ZNS and WAL-Aware Zone Allocator in ZenFS, which reduced 3-4x of space amplification and greatly improved tail latencies caused by zone allocation. ] #cventry( tl: "PingCAP", tr: dates(from: "2020/08", to: "2021/01"), bl: "Storage System R&D Intern, TiKV Storage Team", br: "Shanghai, China" )[ - Built LSM-based storage engine *#githublink("https://github.com/tikv/agatedb", text: "AgateDB")* from ground-up. Inspired by WiscKey and BadgerDB, AgateDB separates large values from the LSM tree into a separate value log, so as to reduce write amplification and improve throughput. ] == Open-Source Contributions #cventry( tl: [ *BusTub* #githublink("https://github.com/cmu-db/bustub", text: "cmu-db/bustub") _as Teaching Assistant for Database Systems_ ], tr: dates(from: "2022/08", to: "2023/12") )[ - Lead the development of the BusTub educational database system and course projects in CMU Database Systems course. - Added query processing layer to the system with PostgreSQL syntax support. Restructured the query execution project. - Added multi-version concurrency control to the system based on HyPer/Umbra undo log version chain implementation. - Redesigned course projects to help students better understand the concepts and align with industrial database systems. - Developed leaderboard tests to challenge advanced students and enable further study in optimizing database systems. ] #cventry( tl: [ *RisingLight Maintainer* #githublink("https://github.com/risinglightdb", text: "risinglightdb") ], tr: dates(from: "2022/01") )[ - Lead the development of RisingLight, an OLAP database system in Rust for educational purpose. RisingLight supports simple TPC-H queries, and has a merge-tree based columnar storage. ] #cventry( tl: [ *TiKV Community* #githublink("https://github.com/tikv", text: "tikv") ], tr: dates(from: "2020/05") )[ - Maintains TiKV Coprocessor, the push-down execution framework of TiDB. Mentored community members to contribute features (e.g. new data types, plugin system) in the *LFX Mentorship*. #iconlink("https://github.com/tikv/tikv/issues/9066") #iconlink("https://github.com/tikv/tikv/issues/9747") ] #cventry( tl: [ *Personal Projects* #githublink(text: "skyzh", "https://github.com/skyzh") ], tr: [6.6k followers on GitHub] )[ - *#githublink(text: "mini-lsm", "https://github.com/skyzh/mini-lsm")* (#fa-icon("star", solid: true) 2k) Build a simple LSM-Tree storage system in Rust in a week - *#githublink(text: "type-exercise-in-rust", "https://github.com/skyzh/mini-lsm")* (#fa-icon("star", solid: true) 1k) Learn Rust generics by implementing a vectorized expression evaluation framework ] == Research Experience #cventry( tl: [*Adaptive Query Optimization Framework* #githublink("https://github.com/cmu-db/optd", text: "cmu-db/optd")], tr: dates(from: "2023/09", to: "2023/12"), bl: [CMU Database Group, advised by Professor Andy Pavlo], br: [Pittsburgh, PA, USA] )[ - *Developed optd*, an optimizer framework based on the Columbia Cascades paper targeting real-time OLAP queries. - *Adaptive Optimization*. optd collects statistics during execution and uses runtime data to guide later plan searches. - *Partial Exploration*. optd explores plans by reusing and incrementally expanding the plan space from the last search. ] #cventry( tl: [*PostgreSQL Extension Manager* #githublink("https://github.com/cmu-db/pgextmgrext", text: "cmu-db/pgextmgrext")], tr: dates(from: [2023/02], to: [2023/05]), bl: [CMU Database Group, advised by Professor Andy Pavlo], br:[Pittsburgh, PA, USA] )[ - *Implemented pgextmgrext*, a PostgreSQL extension that manages other PostgreSQL extensions and provides new APIs to PostgreSQL extension developers that enables them to write new extensions with fewer lines of code. - *Integration with PostgreSQL Ecosystem*. Integrated pg_hint_plan with the extension manager. Implemented output rewriter in the extension manager, and based on that, a demo extension pg_poop that rewrites all text to poop emojis. ] == Skills - *Programming Languages*: Rust (6 years), C++, Python, Node.js and Golang - *Tech Skills*: Stream-Processing Systems, Database Systems (Optimizer and Query Execution), Key-Value Storage Systems, SSD-optimized File System #align(right, text(fill: gray)[Last Updated on #today()])
https://github.com/TheRealKaup/Journal
https://raw.githubusercontent.com/TheRealKaup/Journal/main/README.md
markdown
# Kaup's Public Journal I upload here my essays (some in Hebrew, some in English), provided as source Typst and compiled PDF. License is specified per file. `"draft/"` contains essays expected to undergo significant changes (e.g. in approache and argumentation) until considered complete enough to be moved to `"release/"`, which may still see there minor changes (e.g. in wording and typography). If you encounter errors, regardless of their magnitude, I'd greatly appreciate it if you could submit a GitHub issue. # Uploades ## 6-7-2024 : Cosmological Argument Book Review - [Dark PDF](https://github.com/TheRealKaup/Journal/blob/main/draft/cosmological_argument_book_review_dark.pdf) - [Light PDF](https://github.com/TheRealKaup/Journal/blob/main/draft/cosmological_argument_book_review_light.pdf) - [Typst](https://github.com/TheRealKaup/Journal/blob/main/draft/cosmological_argument_book_review.typ)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2500.typ
typst
Apache License 2.0
#let data = ( ("BOX DRAWINGS LIGHT HORIZONTAL", "So", 0), ("BOX DRAWINGS HEAVY HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT VERTICAL", "So", 0), ("BOX DRAWINGS HEAVY VERTICAL", "So", 0), ("BOX DRAWINGS LIGHT TRIPLE DASH HORIZONTAL", "So", 0), ("BOX DRAWINGS HEAVY TRIPLE DASH HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT TRIPLE DASH VERTICAL", "So", 0), ("BOX DRAWINGS HEAVY TRIPLE DASH VERTICAL", "So", 0), ("BOX DRAWINGS LIGHT QUADRUPLE DASH HORIZONTAL", "So", 0), ("BOX DRAWINGS HEAVY QUADRUPLE DASH HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT QUADRUPLE DASH VERTICAL", "So", 0), ("BOX DRAWINGS HEAVY QUADRUPLE DASH VERTICAL", "So", 0), ("BOX DRAWINGS LIGHT DOWN AND RIGHT", "So", 0), ("BOX DRAWINGS DOWN LIGHT AND RIGHT HEAVY", "So", 0), ("BOX DRAWINGS DOWN HEAVY AND RIGHT LIGHT", "So", 0), ("BOX DRAWINGS HEAVY DOWN AND RIGHT", "So", 0), ("BOX DRAWINGS LIGHT DOWN AND LEFT", "So", 0), ("BOX DRAWINGS DOWN LIGHT AND LEFT HEAVY", "So", 0), ("BOX DRAWINGS DOWN HEAVY AND LEFT LIGHT", "So", 0), ("BOX DRAWINGS HEAVY DOWN AND LEFT", "So", 0), ("BOX DRAWINGS LIGHT UP AND RIGHT", "So", 0), ("BOX DRAWINGS UP LIGHT AND RIGHT HEAVY", "So", 0), ("BOX DRAWINGS UP HEAVY AND RIGHT LIGHT", "So", 0), ("BOX DRAWINGS HEAVY UP AND RIGHT", "So", 0), ("BOX DRAWINGS LIGHT UP AND LEFT", "So", 0), ("BOX DRAWINGS UP LIGHT AND LEFT HEAVY", "So", 0), ("BOX DRAWINGS UP HEAVY AND LEFT LIGHT", "So", 0), ("BOX DRAWINGS HEAVY UP AND LEFT", "So", 0), ("BOX DRAWINGS LIGHT VERTICAL AND RIGHT", "So", 0), ("BOX DRAWINGS VERTICAL LIGHT AND RIGHT HEAVY", "So", 0), ("BOX DRAWINGS UP HEAVY AND RIGHT DOWN LIGHT", "So", 0), ("BOX DRAWINGS DOWN HEAVY AND RIGHT UP LIGHT", "So", 0), ("BOX DRAWINGS VERTICAL HEAVY AND RIGHT LIGHT", "So", 0), ("BOX DRAWINGS DOWN LIGHT AND RIGHT UP HEAVY", "So", 0), ("BOX DRAWINGS UP LIGHT AND RIGHT DOWN HEAVY", "So", 0), ("BOX DRAWINGS HEAVY VERTICAL AND RIGHT", "So", 0), ("BOX DRAWINGS LIGHT VERTICAL AND LEFT", "So", 0), ("BOX DRAWINGS VERTICAL LIGHT AND LEFT HEAVY", "So", 0), ("BOX DRAWINGS UP HEAVY AND LEFT DOWN LIGHT", "So", 0), ("BOX DRAWINGS DOWN HEAVY AND LEFT UP LIGHT", "So", 0), ("BOX DRAWINGS VERTICAL HEAVY AND LEFT LIGHT", "So", 0), ("BOX DRAWINGS DOWN LIGHT AND LEFT UP HEAVY", "So", 0), ("BOX DRAWINGS UP LIGHT AND LEFT DOWN HEAVY", "So", 0), ("BOX DRAWINGS HEAVY VERTICAL AND LEFT", "So", 0), ("BOX DRAWINGS LIGHT DOWN AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LEFT HEAVY AND RIGHT DOWN LIGHT", "So", 0), ("BOX DRAWINGS RIGHT HEAVY AND LEFT DOWN LIGHT", "So", 0), ("BOX DRAWINGS DOWN LIGHT AND HORIZONTAL HEAVY", "So", 0), ("BOX DRAWINGS DOWN HEAVY AND HORIZONTAL LIGHT", "So", 0), ("BOX DRAWINGS RIGHT LIGHT AND LEFT DOWN HEAVY", "So", 0), ("BOX DRAWINGS LEFT LIGHT AND RIGHT DOWN HEAVY", "So", 0), ("BOX DRAWINGS HEAVY DOWN AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT UP AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LEFT HEAVY AND RIGHT UP LIGHT", "So", 0), ("BOX DRAWINGS RIGHT HEAVY AND LEFT UP LIGHT", "So", 0), ("BOX DRAWINGS UP LIGHT AND HORIZONTAL HEAVY", "So", 0), ("BOX DRAWINGS UP HEAVY AND HORIZONTAL LIGHT", "So", 0), ("BOX DRAWINGS RIGHT LIGHT AND LEFT UP HEAVY", "So", 0), ("BOX DRAWINGS LEFT LIGHT AND RIGHT UP HEAVY", "So", 0), ("BOX DRAWINGS HEAVY UP AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LEFT HEAVY AND RIGHT VERTICAL LIGHT", "So", 0), ("BOX DRAWINGS RIGHT HEAVY AND LEFT VERTICAL LIGHT", "So", 0), ("BOX DRAWINGS VERTICAL LIGHT AND HORIZONTAL HEAVY", "So", 0), ("BOX DRAWINGS UP HEAVY AND DOWN HORIZONTAL LIGHT", "So", 0), ("BOX DRAWINGS DOWN HEAVY AND UP HORIZONTAL LIGHT", "So", 0), ("BOX DRAWINGS VERTICAL HEAVY AND HORIZONTAL LIGHT", "So", 0), ("BOX DRAWINGS LEFT UP HEAVY AND RIGHT DOWN LIGHT", "So", 0), ("BOX DRAWINGS RIGHT UP HEAVY AND LEFT DOWN LIGHT", "So", 0), ("BOX DRAWINGS LEFT DOWN HEAVY AND RIGHT UP LIGHT", "So", 0), ("BOX DRAWINGS RIGHT DOWN HEAVY AND LEFT UP LIGHT", "So", 0), ("BOX DRAWINGS DOWN LIGHT AND UP HORIZONTAL HEAVY", "So", 0), ("BOX DRAWINGS UP LIGHT AND DOWN HORIZONTAL HEAVY", "So", 0), ("BOX DRAWINGS RIGHT LIGHT AND LEFT VERTICAL HEAVY", "So", 0), ("BOX DRAWINGS LEFT LIGHT AND RIGHT VERTICAL HEAVY", "So", 0), ("BOX DRAWINGS HEAVY VERTICAL AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL", "So", 0), ("BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL", "So", 0), ("BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL", "So", 0), ("BOX DRAWINGS DOUBLE HORIZONTAL", "So", 0), ("BOX DRAWINGS DOUBLE VERTICAL", "So", 0), ("BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE", "So", 0), ("BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE DOWN AND RIGHT", "So", 0), ("BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE", "So", 0), ("BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE DOWN AND LEFT", "So", 0), ("BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE", "So", 0), ("BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE UP AND RIGHT", "So", 0), ("BOX DRAWINGS UP SINGLE AND LEFT DOUBLE", "So", 0), ("BOX DRAWINGS UP DOUBLE AND LEFT SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE UP AND LEFT", "So", 0), ("BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE", "So", 0), ("BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE VERTICAL AND RIGHT", "So", 0), ("BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE", "So", 0), ("BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE VERTICAL AND LEFT", "So", 0), ("BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE", "So", 0), ("BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL", "So", 0), ("BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE", "So", 0), ("BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE UP AND HORIZONTAL", "So", 0), ("BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE", "So", 0), ("BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE", "So", 0), ("BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL", "So", 0), ("BOX DRAWINGS LIGHT ARC DOWN AND RIGHT", "So", 0), ("BOX DRAWINGS LIGHT ARC DOWN AND LEFT", "So", 0), ("BOX DRAWINGS LIGHT ARC UP AND LEFT", "So", 0), ("BOX DRAWINGS LIGHT ARC UP AND RIGHT", "So", 0), ("BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT", "So", 0), ("BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT", "So", 0), ("BOX DRAWINGS LIGHT DIAGONAL CROSS", "So", 0), ("BOX DRAWINGS LIGHT LEFT", "So", 0), ("BOX DRAWINGS LIGHT UP", "So", 0), ("BOX DRAWINGS LIGHT RIGHT", "So", 0), ("BOX DRAWINGS LIGHT DOWN", "So", 0), ("BOX DRAWINGS HEAVY LEFT", "So", 0), ("BOX DRAWINGS HEAVY UP", "So", 0), ("BOX DRAWINGS HEAVY RIGHT", "So", 0), ("BOX DRAWINGS HEAVY DOWN", "So", 0), ("BOX DRAWINGS LIGHT LEFT AND HEAVY RIGHT", "So", 0), ("BOX DRAWINGS LIGHT UP AND HEAVY DOWN", "So", 0), ("BOX DRAWINGS HEAVY LEFT AND LIGHT RIGHT", "So", 0), ("BOX DRAWINGS HEAVY UP AND LIGHT DOWN", "So", 0), )
https://github.com/JakMobius/courses
https://raw.githubusercontent.com/JakMobius/courses/main/mipt-os-basic-2024/theme/asm.typ
typst
#let asmcolors-light = ( instruction: rgb("871094"), register: rgb("00627A"), number: rgb("1750EB"), dwordptr: rgb("871094"), comment: rgb(139, 139, 139), label: rgb("0033B3"), constant: rgb("0033B3") ) #let highlight(input, theme, no-mnemonic: false) = { let rules = ( (regex("\#.*"), theme.comment), (regex("[a-zA-Z_][0-9a-zA-Z_]*:"), theme.label), ) if not no-mnemonic { rules.push((regex("^\s*[a-z]+(\.[a-z]+)?"), theme.instruction)) } rules += ( // hexademicals (regex("0x[0-9a-zA-Z]+"), theme.number), // x86 r1-r15 (regex("%?r[0-9]?[0-9]"), theme.register), // arm registers (regex("(x|w)[0-9]?[0-9]"), theme.register), // numbers (regex("[0-9]+"), theme.number), // ax, bc, cx, dx, si, di, bp, sp, ip and extensions (regex("%?([re]?(([abcd]x)|si|bp|sp|ip|di))"), theme.register), (regex("%?[abcd][lh]"), theme.register), (regex("(pc)|(x|wzr)"), theme.register), (regex("(([DQ]?WORD)|(BYTE)) PTR"), theme.dwordptr), (regex("[a-zA-Z_][0-9a-zA-Z_]*"), theme.constant) ) let replace(string, rule, color) = { let result = () for part in string { if type(part) == str { let matches = part.matches(rule).map(match => { // match text(fill: color, {raw(match.text)}) }) let parts = part.split(rule) matches.push(none) let append = parts.zip(matches).flatten().filter(a => a != none and a != "") result = (result, append).flatten() } else { result.push(part) } } return result } let finalize(string) = { return string.map(part => { if(type(part) == str) { return raw(part) } return part }).join() } let string = (input,) for rule in rules { string = replace(string, rule.at(0), rule.at(1)) } finalize(string) } #let asm(code) = { codebox(lang: "asm", code) } #let lightasm(code, no-mnemonic: false) = { box(inset: 2pt, baseline: 2pt)[ #set text(weight: "semibold") #highlight(code, asmcolors-light, no-mnemonic: no-mnemonic) ] } #let inlineasm(asm) = { set text(size: 1.2em) lightasm(asm) } #let register(name) = { set text(size: 1.2em, fill: asmcolors-light.register, weight: "bold") raw(name) } #let mnemonic(name) = { set text(size: 1.2em, fill: asmcolors-light.instruction, weight: "bold") raw(name) } #let lightasmtable(code, numbers: false, inset: auto) = { let lines = code.text.split("\n") let table-inset = (:) if inset != auto { table-inset.y = inset } table( columns: 2, align: (horizon + right, left), stroke: none, inset: table-inset, ..lines.enumerate().map(((i, line)) => { let number = if numbers { text(font: "Monaco", size: .6em, fill: luma(100))[ #str(i + 1) ] h(0.5em) } else [] if line.len() > 0 { line = lightasm(line) } else { line = hide(lightasm("x")) } (number, line) }).flatten() ) }
https://github.com/Dherse/typst-brrr
https://raw.githubusercontent.com/Dherse/typst-brrr/master/README.md
markdown
# 🚀 Typst goes brrrrrrrrr Benchmarking runner used to benchmark the performance of the [Typst](https://typst.app/) compiler.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/projects/hexo-renderer-typst/README.md
markdown
Apache License 2.0
# hexo-renderer-typst Typst renderer plugin for Hexo. ### Installation Install Hexo dependencies: ```shell npm install @myriaddreamin/typst.ts @myriaddreamin/typst-ts-renderer @myriaddreamin/typst-ts-node-compiler npm install hexo-renderer-typst ``` Caution: You must algin the version of all of the above packages. ### Font assets Currently it is not configurable. Please put your font assets in one of following directory. - `fonts` - `assets/fonts` - `asset/fonts` ### Target-aware compilation The plugin will set the `sys.inputs.x-target` to `web`. You can configure your template with the variable: ````typ /// The default target is _pdf_. /// The compiler will set it to _web_ when rendering a dynamic layout. /// /// Example: /// ```typc /// #let is-web-target() = target.starts-with("web") /// #let is-pdf-target() = target.starts-with("pdf") /// ``` #let target = sys.inputs.at("x-target", default: "pdf") #show: it => { if target.starts-with("web") { // configure stuff for web } else { // configure stuff for pdf } it } ````
https://github.com/jrihon/cv
https://raw.githubusercontent.com/jrihon/cv/main/metadata.typ
typst
/* Personal Information */ // https://github.com/mintyfrankie/brilliant-CV <- Original repo #let firstName = "Jérôme" #let lastName = "Rihon" #let personalInfo = ( github: "jrihon", phone: "+32 123 45 78 90", email: "<EMAIL>", linkedin: "jérôme-rihon", orcid: "0000-0002-9207-1556", address: "Thatstreet 1, 1111 SomeCity, Belgium" ) #let headerQuoteInternational = ( "": [PhD candidate in Molecular Modeling, Free and Open-Source Software enthusiast, toolmaker], ) /* Layout Setting */ // Optional: skyblue, red, nephritis, concrete, darknight, babyblue, coral, nightblue, dark rose, greenish, kahki, brown, blood, anthracite #let awesomeColor = "anthracite" // Leave blank if profil photo is not needed //#let profilePhoto = "../src/cv_photo.svg" #let profilePhoto = "" // Change this variable to control output language & cited module // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh" #let varLanguage = "" // Decide if you want to put your company in bold or your position in bold #let varEntrySocietyFirst = false // Decide if you want to display organisation logo or not #let varDisplayLogo = true // for cvFooter and letterFooter arrays, add your own languages while the keys must match the varLanguage variable #let cvFooterInternational = ( "": "Curriculum vitae", ) #let letterFooterInternational = ( "": "Cover Letter", )
https://github.com/AnsgarLichter/cv-typst
https://raw.githubusercontent.com/AnsgarLichter/cv-typst/main/modules/header.typ
typst
#import "../settings/styles.typ": * #import "utils.typ": * #let renderSocials( socials: () ) = { let columns = () for item in socials { columns.push( [ #item.icon #link(item.link, item.text) ] ) } return columns } #let createHeaderInfo( fullName: [], jobTitle: [], socials: () ) = { text( font: headerStyle.fonts, size: headerStyle.fullName.size, weight: headerStyle.fullName.weight, fullName ) linebreak() hLine() linebreak() text( font: headerStyle.fonts, size: headerStyle.jobTitle.size, weight: headerStyle.jobTitle.weight, jobTitle ) v(headerStyle.margins.BetweenInfoAndSocials) let countOfSocials = socials.len() if(countOfSocials > 1) { table( columns: countOfSocials, inset: 0pt, column-gutter: headerStyle.socials.columnGutter, align: center, stroke: none, ..renderSocials( socials: socials ) ) } } #let createHeaderImage( profilePhoto: "" ) = { if profilePhoto.len() > 0 { block( width: headerStyle.profilePhoto.width, height: headerStyle.profilePhoto.height, stroke: headerStyle.profilePhoto.stroke, radius: headerStyle.profilePhoto.radius, clip: true, image( height: headerStyle.profilePhoto.imageHeight, fit: "contain", profilePhoto ) ) } }
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/PreventivoSprint/SecondaRevisione.typ
typst
MIT License
#import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost #import "PrimaRevisione.typ": rimanente_ore, rimanente_soldi #import "../../functions.typ": glossary #let ruoli_ore = ( Re: 17, Am: 20, An: 12, Pt: 60, Pr: 92, Ve: 78, ) #let costo_ruoli_ore=( Costo_Re: Re_cost * ruoli_ore.at("Re"), Costo_Am: Am_cost * ruoli_ore.at("Am"), Costo_An: An_cost * ruoli_ore.at("An"), Costo_Pt: Pt_cost * ruoli_ore.at("Pt"), Costo_Pr: Pr_cost * ruoli_ore.at("Pr"), Costo_Ve: Ve_cost * ruoli_ore.at("Ve"), ) #let rimanente_ore = rimanente_ore - ruoli_ore.values().sum(); #let rimanente_soldi = rimanente_soldi - costo_ruoli_ore.values().sum(); == Seconda revisione (Product Baseline #glossary[PB]) === Prospetto economico In questa #glossary[milestone], il costo per ogni ruolo sarà come da tabella: #table( columns: (120pt,60pt,100pt), align: center, [*Ruolo*],[*Ore*],[*Costo*], [Responsabile],[#ruoli_ore.at("Re")],[#costo_ruoli_ore.at("Costo_Re")€], [Amministratore],[#ruoli_ore.at("Am")],[#costo_ruoli_ore.at("Costo_Am")€], [Analista],[#ruoli_ore.at("An")],[#costo_ruoli_ore.at("Costo_An")€], [Progettista],[#ruoli_ore.at("Pt")],[#costo_ruoli_ore.at("Costo_Pt") €], [Programmatore],[#ruoli_ore.at("Pr")],[#costo_ruoli_ore.at("Costo_Pr") €], [Verificatore],[#ruoli_ore.at("Ve")],[#costo_ruoli_ore.at("Costo_Ve")€], [*Totale*],[#ruoli_ore.values().sum()],[#costo_ruoli_ore.values().sum()€], [*Rimanente*],[#rimanente_ore],[#rimanente_soldi€] )
https://github.com/olligobber/friggeri-cv
https://raw.githubusercontent.com/olligobber/friggeri-cv/master/example.typ
typst
#import "friggeri.typ": cv, entries #import "link.typ": email #show: doc => cv( [<NAME>], subtitle: [Excellent Candidate for Position], [ = Contact 42 Wallaby Way \ Sydney, NSW \ Australia #v(2mm) #email("<EMAIL>", display:[ example \ \@<EMAIL>.com ]) #v(2mm) #link("https://github.com/olligobber", "github.com/olligobber") #v(2mm) 0123 456 789 #v(2mm) = Skills #lorem(2) \ #lorem(1) \ #lorem(3) \ #lorem(2) = Languages English \ #lorem(3) ], doc, ) = Introduction #lorem(40) = Work Experience #entries( ( [2022], lorem(2), lorem(4), lorem(20), ), ( [2020-2021], lorem(4), lorem(4), lorem(23), ), ( [2013-2019], lorem(3), lorem(6), lorem(18), ), ( [2000-2012], lorem(5), lorem(4), lorem(25), ) ) = History #lorem(50) #lorem(30) = Education #entries( ( [2017-2018], lorem(5), lorem(6), lorem(21), ), ( [2008-2010], lorem(6), [], lorem(24), ), ( [1999], lorem(4), lorem(8), lorem(19), ), ( [1995-1998], lorem(8), lorem(1), lorem(19), ) )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/space_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test spacing with comments. A/**/B/**/C \ A /**/ B/**/C \ A /**/B/**/ C
https://github.com/pornmanut/resume
https://raw.githubusercontent.com/pornmanut/resume/main/template.typ
typst
// This file uses a template from the typst-mixed-resume project. // Credit: https://github.com/titaneric/typst-mixed-resume #let contact(text: "", link: none, type: "") = { (text: text, link: link, type: type) } #let subSection(title: "", titleEnd: none, subTitle: none, subTitleEnd: none, link: none, content: []) = { ( title: title, titleEnd: titleEnd, subTitle: subTitle, subTitleEnd: subTitleEnd, link: link, content: content ) } #let section(title: "", content: subSection()) = { (title: title, content: content) } #let project( theme: rgb("#4273B0"), first_name: "", last_name: "", title: none, profile_img: "", contact: ((text: [], link: "")), skills: ( languages: () ), main: ( (title: "", content: []) ), sidebar: (), bottom: (), body) = { let backgroundTitle(content) = heading( level: 1, numbering: none, text( fill: theme, size: 1.25em, weight: "bold", [ #{content} #v(-0.75em) #line(length: 100%, stroke: 1pt + theme) ] ) ) let secondaryTitle(content) = { text(weight: "bold", size: 1.125em, content) } let italicColorTitle(content) = { text(style: "italic", size: 1.125em, theme, content) } let formattedName = stack( dir: ltr, spacing: 1em, text(strong[#first_name], weight: 100, 3.0em), text(strong[#last_name], weight: 100, 3.0em, fill: theme), ) let formattedTitle = text(strong[#title], weight: 100, 1.5em) let titleColumn = align(center)[ #stack( dir: ttb, spacing: 1.5em, formattedName, formattedTitle, ) ] let icon(name, shift: 1.5pt) = { box( baseline: shift, height: 10pt, image("assets/icons/" + name + ".svg") ) } let contactColumn = align(left)[#stack( dir: ltr, spacing: 0.5em, ..contact.map(c => { if c.link == none [ #icon(c.type) #c.text ] else [ #icon(c.type) #underline(link(c.link, text(c.text))) ] }) )] let titleAndContactColumn = align(center)[#stack( dir: ttb, spacing: 1.5em, titleColumn, contactColumn )] let profileImageSection = align(center)[ #box( image(profile_img, height: 135pt, alt: "Profile") , clip: true) ] let parseSubSections(subSections) = { stack( dir: ttb, spacing: 1em, ..subSections.map(s => { [ #box([ #secondaryTitle(s.title)#h(1fr) #if s.link == none [ #italicColorTitle(s.titleEnd) ] else [ #italicColorTitle(link(s.link, text(s.titleEnd))) ] ]) #if (s.subTitle != "" and s.subTitle != none) or (s.subTitleEnd != "" and s.subTitleEnd != none) { box[ #text(9pt)[ #if (s.subTitle != "" and s.subTitle != none) { [#icon("calendar") #s.subTitle] } #h(1fr)#icon("location") #s.subTitleEnd] ] } #s.content ] }) ) } let parseSection(section) = { stack( dir: ttb, spacing: 1em, ..section.map(m => { if m.title == "" { [ #m.content ] } else { [ #backgroundTitle(m.title) #parseSubSections(m.content) ] } })) } let mainSection = [#stack( dir: ttb, spacing: 1.5em, titleAndContactColumn, parseSection(main) )] let sidebarSection = [#stack( dir: ttb, spacing: 1.5em, profileImageSection, parseSection(sidebar) )] // line(length: 100%, stroke: 1pt + theme) set par(justify: true) grid( columns: (2fr, 1fr), column-gutter: 1em, mainSection, sidebarSection, ) parseSection(bottom) }
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/nutzung.typ
typst
Other
#import "/src/template.typ": en #set heading(outlined: false) = Nutzungshinweise == Inhalt Auch wenn die Gestaltung und der Name des KÜKs als Parodie an den MÜK angelehnt sind, soll hier versucht werden die Inhalte der Philosophiedidaktik-Seminare an der Universität Rostock ernsthaft aufzuarbeiten und zusammenzufassen, zu belegen und weitere Hinweise und Tipps darzulegen. #align(center)[ #set par(justify: false) #set text(fill: red, size: 1.5em, hyphenate: false) #show: strong Der KÜK ist keine wissenschaftliche Arbeit und sollte in keiner Prüfung, Seminararbeit, Unterrichtsentwurf oder ähnlichem zitiert werden! ] Nutzen Sie stattdessen einfach die Quellen, die hier in den Anmerkungen angegeben werden, um die Informationen, die Sie brauchen, in wissenschaftlicher Lektüre zu finden. == Zusatzelemente Die Zusatzelemente des KÜKs bieten weitere Informationen und Belege. Außerdem sollen Sie die Navigation innerhalb des KÜKs erleichtern, sowohl in der Digital- als auch in einer Print-Version. #table(columns: (33.33%, 33.33%, 33.33%), stroke: none, strong[Aufgaben und Lösungen], strong[Anmerkungen], strong[Index], [ Einige Abschnitte enthalten Aufgaben inklusive Lösungsvorschläge. Diese setzen sich zusammen aus den Aufgaben innerhalb des Seminars, aus den fakultativen Hausaufgaben, den bereitgestellten Beispielklausuraufgaben und einigen eigenen Ideen. Die Aufgaben sind als Anwendungsmöglichkeit der Seminarinhalte gedacht. Aufgaben werden mit Großbuchstaben nummeriert und sind in hellblauen Boxen eingerahmt. ], [ Anmerkungen werden durch hochgestellte, arabisch nummerierte Endnotenverweise dargestellt, wie z.B. hier.#en[Hier eine Beispiel-Anmerkung!] Auf die hochgestellten Zahlen können sie in der digitalen Version klicken, um zu der Anmerkung zu gelangen. Die Anmerkungen werden am Ende des Dokuments mit der Seitenzahl, auf der sie auftreten, aufgelistet. Klicken Sie erneut auf die Zahl in dieser Anmerkungsliste, gelangen Sie zurück zu dem Ort, an dem die Anmerkung verwendet wird. ], [ Der Index ist am Ende des KÜKs eine alphabetisch sortierte Liste von Fachbegriffen und Namen, die hier im KÜK verwendet werden. Hinter jedem Begriff sind die Seitenzahlen aufgelistet, wo er verwendet wird. Dies ist besonders nützlich, sollte der KÜK ausgedruckt werden. ] ) == To Do Der KÜK ist nicht abgeschlossen. Auch für die bisher erarbeiteten Inhalte gibt es noch zu ergänzende Themengebiete. Hauptsächlich handelt es sich dabei um fehlende Lösungsvorschläge zu Aufgabenbeispielen. Um Stellen zu markieren, die ergänzt werden müssen, werden fettgedruckte, rote, hochgestellte, eingeklammerte römische Zahlen verwendet. Sie funktionieren sonst wie Anmerkungen, mit einem eigenen Verzeichnis am Ende des KÜKs. == Versionierung Da der KÜK kein abgeschlossenes Werk ist und auch weiterhin daran gearbeitet werden soll, muss sichergestellt werden, dass die unterschiedlichen Versionen des KÜK gut erkannt und die neuste Version leicht auffindbar ist. Die Version ist auf dem Deckblat notiert und setzt sich aus dem Veröffentlichungsjahr und -monat zusammen. Dieses Dokument ist die *Version #(str(datetime.today().year())+"-"+if datetime.today().month() < 9 { "0" } else { "" } +str(datetime.today().month()))*. Die aktuellste Version dieses Dokuments finden Sie immer hier: #strong(link("https://piepert.github.io/philodidaktik-hro-phf-ifp/KÜK.pdf")). Eine archivierte Version dieser Datei finden Sie unter #strong(link("https://piepert.github.io/philodidaktik-hro-phf-ifp/KÜK-"+str(datetime.today().year())+"-"+if datetime.today().month() < 9 { "0" } else { "" } +str(datetime.today().month())+".pdf")).
https://github.com/KanarekLife/CV
https://raw.githubusercontent.com/KanarekLife/CV/main/README.md
markdown
# <NAME>'s CV Repository with my CV and Typst source files. ## How to run? To build your own version of this CV, you need to download and configure Typst on your system. ### Development mode ```bash ./bin/typst watch --font-path fonts cv.typ ``` ### Build ```bash ./bin/typst compile --font-path fonts cv.typ ``` ## Used Resources ### Icons Icons are downloaded from [feathericons.com](https://feathericons.com/). ### Fonts Fonts are downloaded from [fonts.google.com](https://fonts.google.com/). Used fonts: - [Inter](https://fonts.google.com/specimen/Inter)
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/PreventivoSprint/PrimoSprint.typ
typst
MIT License
#import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost #import "../../functions.typ": prospettoOrario, prospettoEconomico, glossary == Primo #glossary[sprint] *Inizio*: Venerdì 10/11/2023 *Fine*: Giovedì 23/11/2023 #prospettoOrario(sprintNumber: "1") #prospettoEconomico(sprintNumber: "1")
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/notes.typ
typst
automatically align math equals using "&" anchor show goes with ":" set is a function call datetime ... is pretty useful should be a way to locate the definitions on the present page datetime.today is useful you can automatically generate terms #datetime.today().display( "[month repr:short] [year] Week [week_number padding:none] y:[year sign:mandatory repr:last_two][week_number padding:none]" ) // flex(shifted(left), right, justify-content: "space-between")
https://github.com/andreasKroepelin/typst-notebook
https://raw.githubusercontent.com/andreasKroepelin/typst-notebook/main/template-notebook.typ
typst
MIT License
#let notebook( tags: (:), title: [Notebook], author: none, page-width: 50em, body ) = { set page(width: page-width, height: auto, margin: 3em) for tag in tags.keys() { let curr-value = tags.at(tag) if type(curr-value) == "color" { tags.insert(tag, (color: curr-value, text-color: white)) } } let named-tags = tags.pairs().map( ((name, colors)) => (name: name, ..colors) ) let tag-occurrences = state("tag-occurences", (:)) let heading-positions = state("heading-positions", ()) let todos = state("todos", ()) let tag-box(tag) = box( width: auto, height: auto, fill: tag.color, stroke: none, inset: 1mm, baseline: 1mm, radius: 1mm, text(fill: tag.text-color, tag.name) ) let sections-with-count(locs, display-count: (_ => [])) = { let locs-and-titles = locs.map( l => { let title = query(heading.where(level: 1).before(l), l).last() (l, title) }) let deduped = () for (l, title) in locs-and-titles { if deduped.len() == 0 { deduped.push((loc: l, title: title, count: 1)) continue } let last = deduped.pop() if last.title != title { deduped.push(last) deduped.push((loc: l, title: title, count: 1)) } else { last.count += 1 deduped.push(last) } } deduped.map( it => { link(it.loc, sym.arrow.tr + it.title.body + display-count(it.count)) }).join(h(1em)) } show ref: it => { let refed-tag = named-tags.find(tag => it.target == label(tag.name)) if refed-tag == none { underline({ sym.arrow.tr; it }) } else { let display = refed-tag display.name = it tag-box(display) locate( loc => { tag-occurrences.update( to => { if refed-tag.name in to { to.at(refed-tag.name).push(loc) } else { to.insert(refed-tag.name, (loc,)) } to }) }) } } block(width: 100%, height: 5em, align(center + horizon)[ #text(size: 1.5em, strong(title)) #linebreak() #author ]) [= Open TODOs] locate( loc => { sections-with-count( todos.final(loc), display-count: c => text(fill: red, [ (#c)]) ) }) [= Entries] locate( loc => { let all-headings = heading-positions.final(loc) grid( columns: (1fr, 1fr, 1fr), gutter: 1em, ..all-headings.map( h => link(h.last(), sym.arrow.tr + h.first()) ) ) }) [= Tags] { let grid-children = () for tag-name in tags.keys().sorted() { let tag = tags.at(tag-name) let named-tag = (name: tag-name, ..tag) let def = box(baseline: 1mm)[ #figure(kind: "tag", supplement: tag-name, numbering: (..n) => [], tag-box(named-tag)) #label(tag-name) ] let details = locate( loc => { let all-tag-occurrences = tag-occurrences.final(loc) if tag-name in all-tag-occurrences { sections-with-count(all-tag-occurrences.at(tag-name)) } }) grid-children.push(def) grid-children.push(details) } grid( columns: (auto, 1fr), gutter: 1em, ..grid-children ) } show heading: it => { let content-text(c) = if type(c) == "string" { c } else if c.has("text") { content-text(c.text) } else if c.has("children") { c.children.map(content-text).join(" ") } else { "" } let label-name = content-text(it.body).codepoints().filter( cp => { cp.match(regex("[[:alnum:]]| ")) != none }).map( cp => { lower(if cp == " " { "-" } else { cp }) }).fold( (), (cps, cp) => { if cp == "-" and cps.len() > 0 and cps.last() == "-" { cps } else { cps + (cp,) } }).join().trim("-") locate( loc => { heading-positions.update( hp => hp + ( (it.body, loc), ) ) }) block[ #it.body #text(size: .5em, raw(block: false, lang: "typ", "@" + label-name)) #box[ #figure(kind: "entry", supplement: it.body, numbering: (..n) => [], []) #label(label-name) ] ] } show link: it => { if type(it.dest) == "string" { text(fill: blue, sym.triangle.stroked.tr + [ ] + it) } else { it } } show "TODO": it => { locate( loc => { todos.update(ts => ts + (loc,)) }) text(fill: red, size: 1em, weight: "bold", smallcaps(it)) } show "DONE": it => text(fill: green, size: 1em, weight: "bold", smallcaps(it)) line(length: 100%, stroke: .2em + gray) body }
https://github.com/emfeltham/emf-cv
https://raw.githubusercontent.com/emfeltham/emf-cv/main/simplecv.typ
typst
// Based on https://www.overleaf.com/latex/templates/autocv/scfvqfpxncwb and https://www.overleaf.com/latex/templates/faangpath-simple-template/npsfpdqnxmbc #set list(indent: 1em) // Reduce space between paragraphs. #let par_space = 0.5em // Reduce space between headings and descriptions. #let sep_space = par_space + 0.2em // Format start and end dates. #let format_date(start_date: none, end_date: none) = { let date = { if end_date == none { start_date } else if start_date == none { end_date } else { start_date + " - " + end_date } } [*#date*] } // Format locations. #let format_location(location) = { [_#block(above: sep_space, location)_] } // General entry that is split into a left and right half (for experience and education). #let cv_entry(left_content: none, right_content: none) = { grid( columns: (30fr, 9fr), // column 1 originally 11fr column-gutter: 1cm, { set align(left) left_content }, { set align(right) right_content } ) } // Entry for education. #let education_entry(degree, university, degree_title: none, description: none, start_date: none, end_date: none, location: none) = { cv_entry( left_content: { if degree_title != none { [*#degree_title*] + " " } + [*#degree*] + [, #university] + block(above: sep_space, par[#description]) }, right_content: { format_date(start_date: start_date, end_date: end_date) if location != none { "\n" + format_location(location) } } ) } // Entry for work. #let work_entry(role, company, tasks: none, start_date: none, end_date: none, location: none) = { cv_entry( left_content: { [*#role*] + "\n" + block(above: sep_space, text[#company]) if tasks != none { let tasks_list = [] for task in tasks { tasks_list += [- #task] } tasks_list } }, right_content: { format_date(start_date: start_date, end_date: end_date) if location != none { "\n" + format_location(location) } } ) } // Entry for skills #let skill_entry(category, skills) = { [== #category] let cell = rect.with(radius: 5pt, inset: (top: 4pt, bottom: 4pt, left: 5pt, right: 5pt)) let boxes = for skill in skills {(box(cell(skill)),)} {boxes.join(" ")} } // Set name and contact data and format headings #let template(name, contact_data, color, doc) = { set page(margin: (x: 0.75in, y: 0.75in)) set text(11pt) set par(justify: true, leading: par_space) align(center)[ #smallcaps(text(size: 2.2em, fill: black)[#name]) \ #{ if contact_data != none and contact_data.len() > 0 { let elements = for el in contact_data { (link(el.link)[#{box(image(height: 0.7em, el.service + ".svg")) + " " + el.display}],) } elements.join(" | ") } } ] show heading.where(level: 1): i => { set align(left) let title = smallcaps(i.body) set block(above: 1em) set text(weight: "light", size: 1.1em, fill: color) stack( dir: ttb, spacing: 2mm, title, line(length: 100%, stroke: color + 2pt) ) } show heading.where(level: 2): i => { set align(left) let title = smallcaps(i.body) set block(above: 0.8em) set text(weight: "light", size: 1.0em, fill: color) title } doc }
https://github.com/ohmycloud/computer-science-notes
https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/two_columns_demo.typ
typst
#import "two_columns.typ": make_pages #show: make_pages.with( title: "析锂检测" ) #let person_info = ( name: "小猪妖", address: "浪浪山", home_page: "https://rakulang.github.io", phone_number: "123456" ) = 周一 #lorem(10) = 周二 #lorem(10) - 颠三倒四多大点事 - 实得分数但是算法 - 等梦醒来啊醒来呀 = 今天周三 - 测试 - 测试 - 测试 #colbreak() = test1 #lorem(10) = test2 #lorem(10) = test3 #lorem(3)
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/SYE/docs/4-Processus%26ContextChange/processus-changement-context.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Processus et changements de contextes ], lesson: "SYE", chapter: "4 - Processus & changement de context", definition: "Definition", col: 1, doc, ) = Structure PCB (Process Control Block) - PCB (Process Control Block) - Fiche signalétique d'un processus - Structure de données gérée et visible que par le noyau - Contient toutes les informations système liées au processus - Utilisé lors de changements de contexte - Chaque processus dispose d'un PCB propre et unique. = Création de processus, appels systèmes fork(), exec(), waitpid(), exit() = Changement de contexte
https://github.com/francescoo22/masters-thesis
https://raw.githubusercontent.com/francescoo22/masters-thesis/main/preface/acknowledgements.typ
typst
#pagebreak(to:"odd") #import "../config/variables.typ" : profTitle, myProf, myLocation, myTime, myName #import "../config/constants.typ" : acknowledgements #set par(first-line-indent: 0pt) #set page(numbering: "i") #align(right, [ #box(align( start, text( style: "italic", [“E il treno io l'ho preso e ho fatto bene \ Spago sulla mia valigia non ce n'era \ Solo un po' d'amore la teneva insieme \ Solo un po' di rancore la teneva insieme”] ) )) #v(6pt) #sym.dash#sym.dash#sym.dash <NAME> ]) #v(10em) #text(24pt, weight: "semibold", acknowledgements) #v(3em) #text(style: "italic", "First of all, I would like to thank everyone who supported me during these months, making this work possible. My sincere thanks go to all the people at JetBrains, especially <NAME> and <NAME>, for giving me the opportunity to work on this project and for their guidance throughout. I would also like to express my gratitude to my supervisor, Prof. <NAME>, for his guidance and suggestions both before and during the development of this thesis.") #linebreak() #text(style: "italic", "Voglio poi ringraziare i miei genitori per avermi sempre aiutato nei momenti di difficoltà e per tutti i sacrifici che hanno fatto per me, solo ora riesco a capire davvero quanto certe scelte siano state complicate. Un grazie speciale anche a Chiara per essermi stata sempre vicina, sia nei momenti belli che in quelli più difficili. Grazie anche ai nonni per avermi sempre supportato.") #linebreak() #text(style: "italic", "Un grazie anche a tutti gli amici che ho incontrato a Padova per aver reso questi anni di università indimenticabili.") #linebreak() #text(style: "italic", "I would also like to thank all the friends I met in Munich over the past year. You are truly making my time there extraordinary.") #linebreak() #text(style: "italic", "Infine voglio ringraziare Niko e Ghenzo per tutti i bei momenti e per essere stati sempre presenti quando ho avuto bisogno di un confronto.") #v(2em) #text(style: "italic", myLocation + ", " + myTime + h(1fr) + myName) #v(1fr)
https://github.com/jonsch318/rules_typst
https://raw.githubusercontent.com/jonsch318/rules_typst/main/CONTRIBUTING.md
markdown
Apache License 2.0
# How to Contribute ## Using devcontainers If you are using [devcontainers](https://code.visualstudio.com/docs/devcontainers/containers) and/or [codespaces](https://github.com/features/codespaces) then you can start contributing immediately and skip the next step. ## Formatting Starlark files should be formatted by buildifier. We suggest using a pre-commit hook to automate this. First [install pre-commit](https://pre-commit.com/#installation), then run ```shell pre-commit install ``` Otherwise later tooling on CI will yell at you about formatting/linting violations. ## Updating BUILD files Some targets are generated from sources. Currently this is just the `bzl_library` targets. Run `bazel run //:gazelle` to keep them up-to-date. ## Using this as a development dependency of other rules You'll commonly find that you develop in another WORKSPACE, such as some other ruleset that depends on rules_typst, or in a nested WORKSPACE in the integration_tests folder. To always tell Bazel to use this directory rather than some release artifact or a version fetched from the internet, run this from this directory: ```sh OVERRIDE="--override_repository=rules_typst=$(pwd)/rules_typst" echo "common $OVERRIDE" >> ~/.bazelrc ``` This means that any usage of `@rules_typst` on your system will point to this folder. ## Releasing 1. Determine the next release version, following semver (could automate in the future from changelog) 1. Tag the repo and push it (or create a tag in GH UI) 1. Watch the automation run on GitHub actions
https://github.com/FelipeCybis/quarto-physmed-template
https://raw.githubusercontent.com/FelipeCybis/quarto-physmed-template/main/physmed-poster-portrait/README.md
markdown
MIT License
## Physmed Quarto/Typst poster portrait template Check the [example PDF here](https://felipecybis.github.io/quarto-physmed-template/physmed-poster-portrait/template.pdf).
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/node-shapes/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge, shapes #diagram( node-stroke: 1pt, node-outset: 5pt, axes: (ltr, ttb), node((0,0), $A$, radius: 5mm), edge("->"), node((1,1), [crowded], shape: shapes.house, fill: blue.lighten(90%)), edge("..>", bend: 30deg), node((0,2), $B$, shape: shapes.diamond), edge((0,0), "d,ru,d", "=>"), edge((1,1), "rd", bend: -40deg), node((2,2), `cool`, shape: shapes.pill), edge("->"), node((1,3), [_amazing_], shape: shapes.parallelogram), node((2,0), [robots], shape: shapes.hexagon), node((2,3), [squashed], shape: shapes.ellipse), edge("u", "->", bend: -30deg), ) #pagebreak() Diagram `node-shape` option #diagram( node-shape: circle, node-fill: yellow, node((0,0), [A]), node((1,0), [A B C]), ) #diagram( node-shape: rect, node-fill: orange, node((0,0), [A]), node((1,0), [A B C]), ) #pagebreak() #set align(center) #for (name, shape) in dictionary(shapes) { if type(shape) == module { continue } diagram(debug: 0, node((0, 0), name, shape: shape, stroke: 1pt, extrude: (0, 2))) linebreak() } #pagebreak() #diagram( node-stroke: 1pt, spacing: 10pt, node((0,0), [STOP], shape: shapes.octagon.with(truncate: 0)), node((1,0), [STOP], shape: shapes.octagon.with(truncate: 0.5)), node((2,0), [STOP], shape: shapes.octagon.with(truncate: 1)), node((0,1), [STOP], shape: shapes.octagon.with(truncate: 2pt)), node((1,1), [STOP], shape: shapes.octagon.with(truncate: 5pt)), node((2,1), [STOP], shape: shapes.octagon.with(truncate: 8pt)), ) #pagebreak() Direction #diagram( for (i, shape) in ( shapes.trapezium, shapes.triangle, shapes.house, shapes.chevron, ).enumerate() { for (j, dir) in (top, bottom, left, right).enumerate() { node( (j, i), [#dir], fill: orange.transparentize(40%), shape: shape.with(dir: dir), ) } } ) #pagebreak() Flip #diagram( for (i, flip) in (false, true).enumerate() { node( (i, 0), [#flip], fill: teal.transparentize(40%), shape: shapes.parallelogram.with(flip: flip), ) } ) #pagebreak() Fit factor #diagram( node-inset: 0pt, for (i, shape) in ( shapes.parallelogram, shapes.trapezium, shapes.diamond, shapes.triangle, shapes.chevron, shapes.hexagon, ).enumerate() { for (j, fit) in (0, 0.5, 1).enumerate() { node( (j, i), box(fill: blue.transparentize(60%), inset: 10pt, raw("fit: " + repr(fit))), fill: green.transparentize(20%), shape: shape.with(fit: fit), ) } } )
https://github.com/janlauber/bachelor-thesis
https://raw.githubusercontent.com/janlauber/bachelor-thesis/main/chapters/literature_review.typ
typst
Creative Commons Zero v1.0 Universal
= Analysis of the Current Landscape and Challenges This chapter analyzes the current landscape of OSS deployment, highlighting key technologies in use, prevalent challenges, and gaps that the One-Click Deployment system seeks to address. The analysis and insights are derived from *Project 2*, also conducted at the Bern University of Applied Sciences (BUAS) by <NAME> @lauberProjectOneClickDeployment2024. == Overview of Open-Source Software & Deployment OSS refers to software that is distributed with its source code, allowing users to view, modify, and distribute it freely. OSS has gained significant popularity due to its collaborative development model, transparency, and cost-effectiveness. Many OSS projects have emerged as critical components of modern software systems, powering applications, infrastructure, and services across various industries. The deployment of OSS projects is a crucial step in realizing their benefits and enabling users to leverage their capabilities effectively. @2023StateOpen Deploying open-source software involves delivering and installing software solutions in an operational environment where they can be executed and utilized. This process includes activities such as configuration, provisioning, orchestration, scaling, and management. Unlike proprietary software, OSS deployment benefits from a collaborative community that contributes to its development, testing, and optimization. However, this advantage also presents unique challenges due to the diverse nature of OSS projects, their dependencies, and the need for specialized knowledge to deploy them efficiently. Open-source software has been transformative, providing an array of tools and resources for building reliable systems. OSS projects are driven by community collaboration, which accelerates development and innovation. However, the diversity and complexity of these projects can pose significant challenges for deployment, as observed in Project 2 @lauberProjectOneClickDeployment2024. #pagebreak() == Current Technologies and Tools Several technologies and tools facilitate OSS deployment, each addressing different aspects of the deployment lifecycle. Some of the key technologies and tools include: - *Containerization Platforms (e.g., Docker #footnote[https://docker.com]):* These platforms package software, libraries, and dependencies in containers, ensuring consistent environments across development, testing, and production. - *Orchestration Tools (e.g., Kubernetes #footnote[https://kubernetes.io/docs/home/]):* Orchestration tools manage the deployment, scaling, and networking of containers, supporting complex, scalable applications. - *Continuous Integration/Continuous Deployment (CI/CD) Tools (e.g. GitLab CI #footnote[https://docs.gitlab.com/ee/ci/]):* CI/CD tools automate the testing and deployment of software, enabling rapid iteration and deployment. - *Infrastructure as Code (IaC) Tools (e.g. Terraform #footnote[https://www.terraform.io/], Ansible #footnote[https://www.ansible.com/]):* IaC tools automate the provisioning and management of infrastructure through code, improving deployment speed and consistency. - *Platform as a Service (PaaS) Providers (e.g. Vercel #footnote[https://vercel.com/], Heroku #footnote[https://www.heroku.com/], OpenShift #footnote[https://www.redhat.com/de/technologies/cloud-computing/openshift]):* PaaS providers offer cloud-based platforms that simplify the deployment, management, and scaling of applications. These platforms abstract infrastructure complexities, allowing developers to focus on building applications. The trade-off is being locked into the provider's ecosystem and potentially higher costs in the long run. @mikeramirezAttentionVercelUsers2023 @silberlingSocialAppCreatives2024 - *SaaS Hosting Providers (e.g. Bonsai Hosting #footnote[https://bonsai.io/], Kaa Node-Red Hosting #footnote[https://www.kaaiot.com/products/nodered-hosting-plan], Plural.sh #footnote[https://plural.sh], Streamlit Cloud #footnote[https://docs.streamlit.io/streamlit-community-cloud/deploy-your-app]):* SaaS hosting providers offer managed hosting services for specific OSS projects, simplifying deployment and management. These providers often offer additional features such as monitoring, scaling, and security. But they can be expensive and may limit customization options. @lauberProjectOneClickDeployment2024 These technologies collectively streamline the deployment process but also introduce their own complexities. While OSS tools offer flexibility and customization, they often require significant technical expertise to manage effectively. @nairPopularOSSTools2020 #pagebreak() == Challenges in OSS Deployment Despite advancements in deployment technologies, several challenges persist in OSS deployment: - *Complexity:* OSS projects often involve complex dependencies and configurations, requiring specialized knowledge and significant effort to deploy and manage effectively. The learning curve for tools like Kubernetes can be steep, limiting accessibility. @mccartyKubernetesDumpTruck @cooneyBrutalLearningCurve2022 @PlatinaSystemsChallenges - *Scalability:* Ensuring that OSS deployments can scale in response to demand without manual intervention is a significant challenge, particularly for organizations with limited resources. Managing horizontal and vertical scaling can be complex and time-consuming without automation. @cooneyBrutalLearningCurve2022 - *Security:* The open nature of OSS necessitates vigilant security practices to manage vulnerabilities and updates, protecting against breaches and compliance issues. - *Integration:* Integrating OSS into existing systems or with other OSS projects can be complicated by compatibility issues, requiring extensive customization and testing. This can lead to deployment delays and operational challenges. @PlatinaSystemsChallenges - *Community Support Variability:* While OSS benefits from community support, the level and quality of support can vary greatly between projects, affecting the reliability of deployment and maintenance efforts. Projects with limited community engagement may lack essential documentation, updates, or support channels. These challenges highlight the need for solutions that can simplify and streamline OSS deployment, making it accessible to a broader range of users. #pagebreak() == Gaps in Existing Solutions A review of current technologies and challenges reveals several gaps in the OSS deployment ecosystem that the One-Click Deployment system aims to address. === Simplification and Accessibility There is a need for solutions that can simplify the deployment process, making it accessible to users without deep technical expertise in containerization, orchestration, or infrastructure management. Current tools often require a steep learning curve and significant manual intervention. - *Example*: Tools like Docker and Kubernetes are powerful but complex. Docker Compose can simplify multi-container applications but lacks advanced orchestration capabilities. Kubernetes provides extensive features but requires managing numerous YAML configuration files, which can be overwhelming for new users. @mccartyKubernetesDumpTruck @cooneyBrutalLearningCurve2022 === Unified Deployment Solution Current tools often address specific aspects of the deployment lifecycle, leading to the need for a unified solution that can manage the end-to-end deployment process cohesively. - *Example*: Each tool in the deployment pipeline (e.g., CI/CD, containerization, orchestration) requires separate configurations and management, leading to fragmentation and complexity. === Customization vs. Standardization Striking a balance between supporting customization and maintaining standard deployment practices is a persistent gap. Solutions must be flexible enough to accommodate the unique needs of different OSS projects while providing a standardized approach to simplify deployment. - *Example*: Customizing deployments for specific requirements can lead to inconsistencies and maintenance challenges. Standardizing deployment practices can simplify management but may limit flexibility. === Security and Compliance Enhanced tools for automating security checks, updates, and compliance validations within the deployment process are needed to address the evolving threat landscape and regulatory requirements. - *Example*: Ensuring that OSS deployments are secure and compliant with industry standards and regulations is a critical concern. Automated security scans, vulnerability assessments, and compliance checks can help mitigate risks. \ \ *Proposed Solution: One-Click Deployment System* \ The One-Click Deployment system is proposed as a solution to these gaps, aiming to simplify the deployment process, enhance accessibility, and provide a unified, secure, and compliant deployment platform for OSS projects. By addressing these identified gaps, the system seeks to support broader adoption and more efficient utilization of OSS.
https://github.com/Myriad-Dreamin/shiroa
https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/sys.typ
typst
Apache License 2.0
//! Variables for typst.ts's dyn-svg controlling the layout //! Here is a good example of dynamic layout template: <https://github.com/Myriad-Dreamin/shiroa/blob/308e0aacc2578e9a0c424d20332c6711d1df8d1c/contrib/typst/gh-pages.typ> /// The default target is _pdf_. /// `typst.ts` will set it to _web_ when rendering a dynamic layout. /// /// Example: /// ```typc /// #let is-web-target() = target.starts-with("web") /// #let is-pdf-target() = target.starts-with("pdf") /// ``` #let target = sys.inputs.at("x-target", default: "pdf") /// It is in default A4 paper size (21cm) /// example: /// ```typc /// set page( /// width: page-width, /// height: auto, // Also, for a website, we don't need pagination. /// ) if is-web-target; /// ``` #let page-width = sys.inputs.at("x-page-width", default: 21cm)
https://github.com/ShapeLayer/ucpc-solutions__typst__archived
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst__archived/main/theme.typ
typst
Other
/* MIT License Copyright (c) 2024 Park, Jonghyeon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #let conf(doc) = { set page("presentation-16-9") doc } #let cover_conf(doc) = { set page(margin: 0%) doc } #let content_conf(content, doc) = { set page( margin: ( top: 2em, bottom: 3em, left: 2.5em, right: 2.5em ), footer: text(size: 10pt)[ #columns(2)[ #align(left)[#content] #colbreak() #align(right)[#counter(page).display("1")] ] ]) doc } #let difficulties = ( easy: text(fill: rgb("#bd7733"), weight: "bold")[Easy], normal: text(fill: rgb("#687f94"), weight: "bold")[Normal], hard: text(fill: rgb("#efae33"), weight: "bold")[Hard], challenging: text(fill: rgb("#00d497"), weight: "bold")[Challenging], bronze: text(fill: rgb("#bd7733"), weight: "bold")[Bronze], silver: text(fill: rgb("#687f94"), weight: "bold")[Silver], gold: text(fill: rgb("#efae33"), weight: "bold")[Gold], platinum: text(fill: rgb("#52e7b6"), weight: "bold")[Platinum], diamond: text(fill: rgb("#33c3fc"), weight: "bold")[Diamond], ruby: text(fill: rgb("#f7337b"), weight: "bold")[Ruby] ) #let problem(id, title, tags, difficulty, statistics, config, body) = { /* config: dict = ( theme_color: color ) statistics: dict = ( submit_count: int, ac_count: int, first_solver: str, first_solve_time: int, author: str ) */ [ #set page(margin: (top: 3em)) #set text(size: 20pt) = #text(fill: config.theme_color, size: 1.35em)[#id. #title] \ #text(size: .8em)[#tags.map(each => "#" + each).join(", ") \ ] 출제진 의도 --- #difficulty #align(horizon)[ - 제출 #statistics.submit_count\회, 정답 #statistics.ac_count\건 - 최초 해결: #statistics.first_solver\, #statistics.first_solve_time\분 - 출제자: #statistics.author ] #pagebreak() #set page(header: text(size: .8em)[ #text(fill: config.theme_color)[ #text(weight: "bold")[#id\.] #title ] ]) #set align(horizon) #set list(marker: [»]) #body ] }
https://github.com/alex-touza/fractal-explorer
https://raw.githubusercontent.com/alex-touza/fractal-explorer/main/paper/src/shortcuts.typ
typst
#import "../meta.typ": PRINT #let colon = $#h(0%):$ #let hausdorffdelta = $cal(H)_delta^s (A)$ #let hausdorff = $cal(H)^s (A)$
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/utils/state.typ
typst
#let outline = state("__ctf:state:outline", false) #let appendix = state("__ctf:state:appendix", false)
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/impl.typ
typst
The Unlicense
#import "package/ctheorems.typ": thmrules #import "package/gentle-clues.typ": gentle-clues #import "package/drafting.typ" as drafting #import "package/codly.typ" as codly #import "models/debug.typ" as debug-models #let template( title: [Contribution Title], authors: (), abstract: none, debug: false, printer-test: false, frame: none ) = (body) => { // -------------------------------------------------------------------------- // Debug option show: (it)=>{ if (debug){ show v: (it)=>{ place(box(width: 1pt, it, stroke: olive)) place(dx: 0.5em, text(size: 7pt, fill: olive, repr(it))) it } show link: set text(stroke: eastern) show cite: set text(stroke: eastern) show ref: set text(stroke: eastern) show footnote: box.with(stroke: eastern) show math.equation.where(block: true): block.with(stroke: olive) // show box: set box(stroke: 1pt + olive) // show block: set block(stroke: 1pt + olive) it } else { it } } // -------------------------------------------------------------------------- // Text set text(size: 9pt, weight: 450) set block(spacing: 1em) set par(justify: true, first-line-indent: 1.5em) show par: set block(spacing: 0.65em) show par: set align(left) // -------------------------------------------------------------------------- // Page set page(margin: (x:5cm, top:5cm, bottom: 6.25cm)) set page(header-ascent: 1.5em) set page( header: context{ set text(size: 7pt) if debug {debug-models.frame()} if here().page() > 1 { if (calc.even(here().page())){ text[#here().page()] h(1fr) authors.map(it=>it.name).join(", ", last: " and ") } else { text(title) h(1fr) text[#here().page()] } } }, footer: if debug {debug-models.frame()}, background: { if frame != none {debug-models.frame(stroke: frame)} if debug {debug-models.horizontal-frames} }, foreground: if printer-test {debug-models.printer-test} ) // -------------------------------------------------------------------------- // Headings set heading(numbering: "1.1", offset: 0) show heading: set block(above: 3em, spacing: 1.5em) show heading.where(level: 4): set block(above: 1.5em, below: 1em) show heading.where(level:4): set text(weight: 450) show heading.where(level: 4): set heading(numbering: none, outlined: false) show heading.where(level: 5): set block(above: 1.5em, below: 1em) show heading.where(level: 5): set text(weight: 450, style: "italic") show heading.where(level: 5): set heading(numbering: none, outlined: false) set heading(supplement: [Sect.]) // -------------------------------------------------------------------------- // Mathematics set math.equation(numbering: "(1)") show math.equation: set block(spacing: 1.5em) // -------------------------------------------------------------------------- // Footnotes set footnote.entry( indent: 0em, separator: line(length: 25%, stroke: 0.75pt), // gap: 0.65em ) show footnote.entry: set text(7.25pt) // -------------------------------------------------------------------------- // Figures set figure(supplement: [Fig.]) set figure(placement: auto, gap: 1em) show figure.caption: set text(size: 8pt) show figure.where(placement: auto): set place(clearance: 1.5em) show figure.where(kind: table): set figure(supplement: [Table]) set figure.caption(position: bottom) show figure.where(kind: table): set figure.caption(position: top) show figure.caption: set align(left) show figure.caption: set par(first-line-indent: 0em) // show figure.caption: (it) => [ // *#it.supplement #it.counter.display()*#it.separator;#it.body // ] show table: set text(size: 8pt) // -------------------------------------------------------------------------- // Lists show enum: set block(spacing: 1.5em) show list: set block(spacing: 1.5em) // -------------------------------------------------------------------------- // Bibliography set bibliography(style: "springer-mathphys") show bibliography: set par(first-line-indent: 0em) show bibliography: set block(spacing: 1em) show bibliography: it=> { show heading: set block(above: 3em, below: 1.5em) it } // -------------------------------------------------------------------------- // Packages show: thmrules show: gentle-clues place(drafting.set-page-properties()) show: codly.codly-init.with() // -------------------------------------------------------------------------- // Title v(2cm) { set text(weight: "black", size: 16pt) block(title) } v(0.5cm) { block(text(authors.map(it=>it.name).join(", ", last: " and "))) } v(3.5cm) // -------------------------------------------------------------------------- // Main body place( float: true, bottom, { set text(size: 7.5pt) set par(first-line-indent: 0em) line(length: 25%, stroke: 0.75pt) show par: set block(below: 1.5em) authors.map( (it)=>{ it.name linebreak() [#it.institute, #it.address, email: #link("mailto:" + it.email)] } ).join(parbreak()) } ) if (abstract != none){ strong({ [Abstract] h(0.25em) sym.dash.em }) h(weak: true, 0.25em) abstract } body // -------------------------------------------------------------------------- }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/renderer/hexo.typ
typst
Apache License 2.0
#import "/docs/cookery/book.typ": book-page #show: book-page.with(title: "Hexo Library") = Hexo Library == Installation Install Hexo dependencies: Note: please align the version of the dependencies to same vesrion, otherwise you may get runtime rendering error. ```bash // ensure dependencies is installed npm install @myriaddreamin/typst.ts @myriaddreamin/typst-ts-renderer @myriaddreamin/typst-ts-node-compiler // ensure plugin is installed npm install hexo-renderer-typst ``` == Usage Add your *main* files to `source/_posts` directory. And run: ``` # serve files hexo serve # generate files hexo generate ``` Currently, it could only render typst documents inside of `source/_posts` (Hexo Posts) and fix typst workspace (root directory) to the root of your blog project. === Font assets Currently it is not configurable. Please put your font assets in one of following directory. - `fonts` - `assets/fonts` - `asset/fonts` === Target-aware compilation The plugin will set the `sys.inputs.x-target` to `web`. You can configure your template with the variable: ````typ /// The default target is _pdf_. /// The compiler will set it to _web_ when rendering a dynamic layout. /// /// Example: /// ```typc /// #let is-web-target() = target.starts-with("web") /// #let is-pdf-target() = target.starts-with("pdf") /// ``` #let target = sys.inputs.at("x-target", default: "pdf") #show: it => { if target.starts-with("web") { // configure stuff for web } else { // configure stuff for pdf } it } ````