repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/chubetho/Bachelor_Thesis
https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/templates/bibliography.typ
typst
#bibliography("/assets/works.bib", style: "ieee") #pagebreak(weak: true)
https://github.com/donghoony/typst_editorial
https://raw.githubusercontent.com/donghoony/typst_editorial/main/description.typ
typst
MIT License
#let descriptions(description) = { pad(top: 40pt, list( marker: [#image("images/checkmark.png", height: 5%)], ..description.map(d => { pad(top: 5pt, bottom: 20pt, align(horizon)[#text(size: 18pt,weight: "light")[#d]]) }) ) ) pagebreak(weak: true) }
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/par-knuth.typ
typst
Apache License 2.0
#set page(width: auto, height: auto) #set par(leading: 4pt, justify: true) #set text(font: "New Computer Modern") #let story = [ In olden times when wishing still helped one, there lived a king whose daughters were all beautiful; and the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king’s castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king’s child went out into the forest and sat down by the side of the cool fountain; and when she was bored she took a golden ball, and threw it up on high and caught it; and this ball was her favorite plaything. ] #let column(title, linebreaks, hyphenate) = { rect(inset: 0pt, width: 132pt, fill: rgb("eee"))[ #set par(linebreaks: linebreaks) #set text(hyphenate: hyphenate) #strong(title) \ #story ] } #grid( columns: 3, gutter: 10pt, column([Simple without hyphens], "simple", false), column([Simple with hyphens], "simple", true), column([Optimized with hyphens], "optimized", true), )
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/footnote.typ
typst
Apache License 2.0
// Test footnotes. --- #footnote[Hi] --- // Test space collapsing before footnote. A#footnote[A] \ A #footnote[A] --- // Test nested footnotes. First \ Second #footnote[A, #footnote[B, #footnote[C]]] \ Third #footnote[D, #footnote[E]] \ Fourth --- // Currently, numbers a bit out of order if a nested footnote ends up in the // same frame as another one. :( #footnote[A, #footnote[B]], #footnote[C] --- // Test customization. #show footnote: set text(red) #show footnote.entry: set text(8pt, style: "italic") #set footnote.entry( indent: 0pt, gap: 0.6em, clearance: 0.3em, separator: repeat[.], ) Beautiful footnotes. #footnote[Wonderful, aren't they?]
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/05-complex-functions/02-uniqueness.typ
typst
#import "../../utils/core.typ": * == Теорема о единственности #lemma(label: "opened-closed-trivial")[ $Omega$ --- область в метрическом пространстве, $E subset Omega$. Если $E != nothing$, $E$ открыто в $Omega$ и замкнуто в $Omega$, то $E = Omega$. ] #proof[ Рассмотрим $ f(x) = cases(1 "при" x in E, 0 "при" x in Omega without E). $ Эта функция непрерывна в $Omega$, так как прообраз открытого множества открыт в $Omega$. Значит $ nothing, E, Omega without E, Omega $ открытые в $Omega$. Тогда если у $f$ есть значение $0$, то по теореме Больцано-Коши, $f$ принимает все промежуточные значения, то есть, например $1/2$. Такого быть не может, значит $E = Omega$ (вариант $E = nothing$ запрещен по условию.) ] #th(name: "о единственности", label: "uniqueness")[ $f in H(Omega)$, $z_0 in Omega$. Следующие условия равносильны: 1. Все производные $f^((n)) (z_0) = 0$. 2. $f equiv 0$ в окрестности $z_0$. 3. $f equiv 0$ в $Omega$. ] #proof[ - "$1 ==> 2$": разложим по Тейлору. В круге сходимости --- это тождественный нуль. - "$2 ==> 1$": очевидно. - "$3 ==> 2$": очевидно. - "$2 ==> 3$": Рассмотрим в качестве $E$ множество точек, в окрестностях которых, функция равна $0$: $ E := {z in Omega: exists U_z space f(U_z) equiv 0}. $ Так как $z_0 in E$, $E != nothing$. По построению, $E$ открыто. Докажем, что $E$ замкнуто: рассмотрим последовательность $z_n in E$ такую, что $z_n --> z_*$. Тогда $0 = f^((k)) (z_n) -->_(n -> oo) f^((k)) (z_*)$, так как $f^((k))$ непрерывны. Пользуемся выводом $1 ==> 2$ для $z_*$. ] #follow(label: "uniqueness'")[ Если $f, g in H(Omega)$ и $f = g$, в окрестности $z_0 in Omega$, то $f = g$ в $Omega$. ] #proof[ Рассмотрим разность. Она нуль в окрестности, значит по теореме нуль везде. ] #th(name: "о среднем", label: "value-through-average")[ $f in H(Omega)$, $a in Omega$, такие, что круг $abs(z - a) <= r$ содержится в $Omega$. Тогда $ f(a) = 1 / (2pi) integral_0^(2pi) f(a + r e^(i t)) dif t. $ Иными словами, значение функции в точке --- среднее значение функции на окружности с центром в этой точке. ] #proof[ Запишем интегральную формулу Коши#rf("cauchy-integral"): $ f(a) = 1/(2 pi i) integral_(abs(z - a) = r) f(z) / (z - a) dif z. $ Положим $z = a + r e^(i t)$ --- параметризация окрестности $abs(z - a) = r$, $dif z = r e^(i t) dot i dif t$. Тогда $ f(a) = 1/(2 pi i) integral_(abs(z - a) = r) f(z) / (z - a) dif z = 1/(2 pi cancel(i)) integral_0^(2 pi) f(a + r e^(i t)) (cancel(r e^(i t)) cancel(i))/(cancel(r e^(i t))) dif t = 1 / (2pi) integral_0^(2pi) f(a + r e^(i t)) dif t. $ ] #follow(label: "value-through-average'")[ При условии теоремы, также верно $ f(a) = 1 / (pi r^2) integral_(abs(z - a) <= r) f(z) dif x dif y. $ То есть значение функции в точке --- среднее значение функции в круге с центром в этой точке. ] #proof[ Считаем интеграл: $ integral_(abs(z - a) <= r) f(z) dif x dif y = integral_0^r integral_0^(2 pi) f(a + rho e^(i t)) rho dif t dif rho = integral_0^r f(a) dot 2pi rho dif rho = f(a) dot cancel(2) pi dot r^2/cancel(2) = pi r^2 f(a). $ ] #th(name: "Принцип максимума", label: "max-principle")[ Пусть $f in H(Omega)$. $a in Omega$ --- локальный максимум модуля, то есть $abs(f(z)) <= abs(f(a))$ для $forall z in U_a$. Тогда функция --- константа. ] #proof[ Пусть $M = abs(f(a))$ --- максимум по модулю. Если $M = 0$, то функция равна нулю в окрестности, и по теореме о единсвенности#rf("uniqueness"), везде. Если $M > 0$, то домножим функцию на константу вида $e^(-i alpha)$ так, чтобы $f(a) = M$. Значение в точке станет положительным. Запишем интегральную формулу Коши#rf("cauchy-integral"): $ M = f(a) = 1/(2pi) integral_0^(2pi) f(a + r e^(i t)) dif t. $ Так как справа интеграл положительный, можно навесить на него модуль. Более того, значения можно сравнивать как вещественные: $ M = f(a) = 1/(2pi) abs(integral_0^(2pi) f(a + r e^(i t)) dif t) <= 1/(2pi) integral_0^(2pi) underbrace(abs(f(a + r e^(i t))), <= M) dif t <= 1/(2pi) integral_0^(2pi) M dif t = M. $ Получилась цепочка неравенств значений между $M$ и $M$. Значит все неравенства в ней равенства. $abs(f(a + r e^(i t)))$ в какой-то окрестности не $M$, то интеграл будет поменьше. Значит $abs(f(a + r e^(i t))) = M$ везде из непрерывности. Более того, $ M = f(a) = 1/(2pi) Re integral_0^(2pi) f(a + r e^(i t)) dif t = 1/(2pi) integral_0^(2pi) underbrace(Re f(a + r e^(i t)), <= M) dif t <= 1/(2pi) integral_0^(2pi) M dif t = M. $ Снова везде равентсва. Аналогично получается, что $Re f(a + r e^(i t)) = M$. Получается, и модуль, и вещественная часть везде равна $M$. Тогда для каждой точки круга, $f(a + r e^(i t)) = M space forall r <= R space forall t$, а значит $f(z) = M$ для всех $z$ в круге, и по теореме о единственности#rf("uniqueness"), $f = const$. ] #follow(label: "max-hfn-is-on-bound")[ Пусть $Omega$ --- ограниченная область, $f in H(Omega)$ и $f in C(Cl Omega)$. Тогда $max_(z in Cl Omega) abs(f(z))$ достигается на границе. ] #proof[ $Cl Omega$ --- компакт. Значит максимум где-то достигается. Пусть не на границе. Тогда по принципу максимума, функция константа. Но тогда максимум на границе тоже достигается. ] Тривиа: из таких теорем можно делать какие-то выводы из гидродинамики. Например, для несжимаемых жидкостей, если рассмотреть их в одной плоскости, то скорость жидкости в точке описывается голоморфной функцией. Тогда можно понять, что максимальная скорость достигается на границе. Лет 70 назад, почти все расчеты в гидродинамике в приближении несжимаемой жидкости делались с помощью голоморфных функций. Аналогичным образом можно симулировать течение воздуха вокруг крыла самолета в простых случаях (воздух все-таки сжимаем), или поведение толпы. #def[ Пусть $f in H(Omega)$, $a in Omega$. $a$ --- _нуль голоморфной функции_ $f$, если $f(a) = 0$. ] #th(label: "hfn-zero-multiplicity")[ Пусть $f in H(Omega)$, $f(z_0) = 0$, $f equiv.not 0$. Тогда существует $m in NN$ и $g in H(Omega)$ такая, что $g(z_0) != 0$ и $f(z) = (z - z_0)^m g(z)$. В частности, $f(z) != 0$ в некоторой проколотой окрестности $z_0$. Такое $m$ называется _кратностью нуля_. ] #proof[ Рассмотрим разложение $f(z) = sum_(n = 0)^oo a_n (z - z_0)^n$, в нем не все $a_n$ нули. Возьмем в качетстве $m := min {k: a_k != 0} >= 1$ --- минимальный индекс, в котором значение не $0$ (напомню, что $a_0$ равно нулю, так как $z_0$ --- корень, и $m >= 1$). Тогда $ f(z) = (z - z_0)^m sum_(n = 0)^oo a_(n + m) (z - z_0)^n. $ Определим $ g(z) := cases( f(z)/(z - z_0)^m "при" z != z_0, a_m "при" z = z_0 ) $ Надо проверить голоморфность. При $z != z_0$ очевидно: это степенной ряд. При $z = z_0$, это предел функции $f(z)/(z - z_0)^m$ при $z -> z_0$, значит функция непрерывна. У нас была теорема, что если непрерывная функция голоморфна без точки, то она все равно голоморфна везде#rf("hfn-without-line-hfn"). Значит $g$ голоморфна везде. Наконец, $g(z) != 0$ в окрестности $z_0$ по непрерывности, значит $f(z) != 0$ в проколотой окрестности $z_0$. ] #follow(label: "hfn-prod-zero-hfn-zero")[ Пусть $f, g in H(Omega)$, и $f dot g equiv 0$. Тогда либо $f equiv 0$, либо $g equiv 0$. ] #proof[ Пусть $g equiv.not 0$. Берем $z_0 in Omega$ такое, что $g(z_0) != 0$. Тогда $f(z_0) = 0$, и $f(z) != 0$ в $circle(U)_(z_0)$ по предыдущей теореме#rf("hfn-zero-multiplicity"). Тогда $g equiv 0$ в $circle(U)_(z_0)$, так как $f dot g equiv 0$. Значит это нуль везде по теореме о единсвенности#rf("uniqueness"). ] #follow(label: "hfn-zeros-isolated")[ Множество нулей голоморфной функции $f equiv.not 0$ состоит из изолированных точек. ] #proof[ Очевидно по теореме#rf("hfn-zero-multiplicity"): около каждого нуля есть проколотая окрестность, в которой функция не равна нулю. ] #th(name: "о единственности, вторая версия", label: "uniqueness2")[ Пусть $f, g in H(Omega)$ и $E := {z in Omega : f(z) = g(z)}$. Если $E$ имеет предельную точку в $Omega$, то $f equiv g$ в $Omega$. ] #proof[ Пусть $z_n in E$ и $lim z_n = z_0 in Omega$. Пусть $h := f - g$. Тогда $h(z_n) = 0$, и по непрерывности $h(z_0) = 0$. Но тогда $z_0$ не изолированный нуль $h$, значит $h equiv 0$ в $Omega$#rf("hfn-zeros-isolated"). ] #notice[ Здесь важно, что $z_0$ попал в $Omega$. Рассмотрим, например, $Omega := CC without {0}$, $f(z) = sin 1/z$, $g(z) equiv 0$. Тогда если рассмотреть $z_n = 1/(pi n)$, то $lim z_n = 0 in.not Omega$, но $f(z_n) = 0 = g(z_n)$, хотя $f equiv.not g$. ] #follow[ Докажем какое-нибудь следствие. Напрмер, $sin^2 z + cos^2 z = 1$. Мы знаем, что оно выполняется для вещественных аргументов, из кружка 8-го класса школы. Тогда по принципу единственности, оно выполняется везде. Любые формулы над голоморфными функциями верные на $RR$, верны везде. ]
https://github.com/justinvulz/document
https://raw.githubusercontent.com/justinvulz/document/main/test.typ
typst
#import "@preview/pinit:0.1.4": * #set text(size: 24pt) A simple #pin(1)highlighted text#pin(2). #pinit-highlight(1, 2) #pinit-point-from(2)[It is simple.]
https://github.com/feng-spinning/Optics-Notes
https://raw.githubusercontent.com/feng-spinning/Optics-Notes/master/resolution_lim.typ
typst
#set text(12pt, font: ("Times New Roman", "SimSun")) #set rect(width: 100%, height: auto, inset: 4pt, fill: rgb("#eeffee")) #let indent = h(1em) #set math.mat(delim: "[") #show figure.where( kind: table ): set figure.caption(position: top) #let indent = h(1em) #let ali = h(1.2em) #let pp = v(0.5em) #let today = datetime.today() #align(center, text(17pt)[*Discussion of the Diffraction Limit*]) #align(center, text(15pt)[#today.display() <NAME>]) #import "@preview/sourcerer:0.2.1": code #import "@preview/physica:0.9.1": * #import "@preview/i-figured:0.2.3" #import "@preview/ctheorems:1.1.0": * #show: thmrules #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) // make sure you have some heading numbering set #set heading(numbering: "1.1.") // // apply the show rules (these can be customized) // #show heading: i-figured.reset-counters // #show math.equation: i-figured.show-equation.with( // level: 1, // zero-fill: true, // leading-zero: true, // numbering: "(1.1)", // prefix: "eqt:", // only-labeled: false, // numbering all block equations implicitly // unnumbered-label: "-", // ) #set math.equation(numbering: "(1.1)") = Introduction to my question #pp When we discuss the simplist case of imaging system: A lens with a circular pupil of diameter $w$, the angular and line diffraction limit is always given by: $ delta theta = 1.22 (lambda ) / (w) \ delta x = 1.22 (lambda z_i) / (w) $<11> *I wonder: if a lens with an infinitly large pupil is used, i.e. $w -> infinity$, will $delta x -> 0$?* = Derivation of the above formula #pp The above formula @11 can be easily accessed by a conclusion from Fourier Optics @Goodman146 #theorem[For a diffraction-limited system, the impulse response of the imaging system is the Fourier Transform of the pupil function] So for a circular pupil, its FT is the $J_1$, an Airy disk, with first zero point at $1.22 lambda / w$. *But the derivation of this conclusion uses the Fresnel diffraction formula rather than the accurate angular spectrum.* The transmmission function used in the derivation is $ H(f_x,f_y) = exp(j k z)exp[-j pi lambda z (f_x ^2 + f_y ^2)] $ which is a first-order approximation of the angular spectrum method, whose formula should be $ H(f_x,f_y) = exp(j k z sqrt(1- (lambda f_x)^2 - (lambda f_y)^2)) $<asm> This approximation usually holds *ONLY for* $bold(abs(lambda f_x)), bold(abs(lambda f_y) << 1)$, which is small angle approximation. The exact applicable could be derived from the Taylor expansion of the sqrt function. Suppose $theta$ is the $arrow(k)$'s angle with the $z$ axis. The Fresnel formula holds when: $ (theta ^4 z) / (4 lambda) << 1 $ If we want $w -> infinity$, of course the $theta$ will be larger than the above criterion, so the @11 is no longer valid. We *CANNOT* make $w -> infinity$ and claim the diffraction limit is broken. = Diffraction Limit in the general case #pp Next question is: If the above @11 only holds for paraxial approximation, what formula should we use to describe the diffraction limit in the general case? The diffraction limit can be rewritten as $ delta x = 1.22 lambda / (2"NA") = lambda / (2 n sin alpha) >= lambda / (2n) $<22> But @22 seems contradict with @11, as @11 indicates a $tan$ relationship, rather than $sin$. This can be explained by the *Abbe sine condition*. #theorem[the sine of the object-space angle $alpha_o$ should be proportional to the sine of the image space angle $alpha_i$. ] #figure( image("abbysin.png", width: 80%), caption: [Abbe sine condition from Wikipedia] ) A collary of the Abbe sine condition @Mertz2019 establishes a linear correspondence between transverse wavevector components in the object (or image) plane, and spatial coordinates in the pupil plane. #figure( image("sincol.png", width: 70%), caption: [linear correspondence] ) = Numerical Aperture #pp As <NAME> explains, "It is a common *error *to suppose that the ratio [D/2f] is actually equal to tan θ, and not sin θ ... The tangent would, of course, be correct if the principal planes were really plane. However, the complete theory of the Abbe sine condition shows that if a lens is corrected for coma and spherical aberration, as all good photographic objectives must be, the second principal plane becomes a portion of a sphere of radius f centered about the focal point" WHYYYY? Why not tan? Why sin? = Physics underlying the diffraction limit == From Fourier Optics's point of view #pp According to the idea of angular spectrum method of @asm, only the low frequency components ($f_x^2+f_y^2 < 1"/"lambda^2$) can propagate in space, so high frequency components are lost. From this point of view, imaging cannot be perfect, as long as there is propagation in free space. *Calculation*: The maximum frequency that can propagate is on order of $f_x = 1 / lambda$, so the diffraction limit is with the same order of $1"/"f_x = lambda$. == From Heisenberg Uncertainty Principle's point of view #pp With the Heisenberg Uncertainty Principle: $ Delta x Delta p_x > h $<unc> (right hand side of @unc should be $hbar / 2$. $h$ is adopted here for magnitude estimation) The photon has a momentum $ p = (h nu) / c $ Which is equivalent to $ p = h / lambda = hbar k $ $ Delta x Delta k_x > pi $ $ Delta k_x = 2k sin alpha <= 2k = (2 pi) / lambda $ The equal sign is reached when the lens pupil reaches infinity. #figure( image("resolu1.png") ) ($alpha -> 90$, $sin alpha -> 1$) $ Delta x > pi / (Delta k_x) = lambda / 2 $ = Super-Resolution #pp The Heisenberg Uncertainty Principle offers a great physical insight into the diffraction limit. With the same point of view, we can explore ways of breaking the diffraction limit. *The key seems counter intuitive: should $sin alpha <= 1$ hold for all scenarios?* NO! By having a complex $k_z = j |k_z|$, have $ k_x ^2 = k^2-k_z^2= k^2 + |k_z|^2> k^2 $ As the uncertainty principle requires:$Delta x > pi / (Delta k_x)$, if we use *evanescent waves*: $k_x -> infinity <--> Delta x ->0$ = 高速探测 #pp 用来探测光场的探测器,响应速度比光场的频率大很多 外差干涉技术-》相位分辨 #bibliography("works.bib")
https://github.com/swablab/documents
https://raw.githubusercontent.com/swablab/documents/main/rechnung.typ
typst
Creative Commons Zero v1.0 Universal
#import "templates/tmpl_letter.typ": tmpl_letter #import "templates/common.typ": colors, money #import "@preview/cades:0.3.0": qr-code #let config = yaml("rechnung.yml") #show: doc => tmpl_letter( title: ( invoice: "Rechnung", offer: "Angebot", estimate: "Kostenvoranschlag", internal: "Eigenbeleg" ).at(config.type), address: config.address, info: [ Datum: #config.date \ #if config.type != "internal" [ Kunden-Nr.: #config.customer_no \ ] #if config.type == "invoice" [ Rechnungs-Nr.: #config.invoice_no \ ] else if config.type == "offer" [ Angebots-Nr.: #config.invoice_no \ ] ], footer: [ #if config.type == "invoice" [ Vielen Dank für deine Bestellung! \ ] else if config.type == "estimate" or config.type == "offer" [ Wir freuen uns auf deine Bestellung! \ ] else if config.type == "internal" [ *Grund für Eigenbeleg:* \ #config.internal_reason ] #text(size: 0.7em, fill: colors.subtext)[ #if config.type == "invoice" [ Gesamtbetrag fällig in 10 Tagen ab Rechnungserhalt. \ Für überfällige Zahlungen wird eine Bearbeitungsgebühr von min. 5 % pro Monat berechnet. ] else if config.type == "offer" [ Dieses Angebot ist für einen Monat gültig. ] else if config.type == "estimate" [ Dieser Kostenvoranschlag ist unverbindlich. ] ] ], doc, ) #if config.type == "invoice" [ Bitte nutze deine Rechnungs-Nr. als Verwendungszweck für die Überweisung! ] #table( columns: (auto, 1fr, auto, auto, auto ,auto), fill: (_, row) => if row == 0 { colors.highlight } else { white }, stroke: 0.1pt + colors.subtext, [*Pos.*], [*Beschreibung*], [*Stück*], [*Einzelpreis*], [*Rabatt*], [*Betrag*], ..config.entries.enumerate().map(e => ( e.at(0)+1, e.at(1).description, e.at(1).pieces, money(e.at(1).price), money(e.at(1).sale), money(e.at(1).pieces * e.at(1).price - e.at(1).sale), )).flatten().map(e => [#e]), ) #align(right)[ #pad(x:1em)[ *Gesamtbetrag: #money(config.entries.map(e => e.pieces * e.price - e.sale).sum())* ] ] #if config.type == "invoice" [ #v(1em) #align(right)[ #block( stroke: 1pt, inset: 1em, radius: 1em )[ #qr-code("BCD\n002\n1\nSCT\n\nswablab e.V.\nDE12642624080125634005\nEUR" + str(config.entries.map(e => e.pieces * e.price - e.sale).sum()) + "\nGDDS\n\nRechnung " + str(config.invoice_no) + "\nswablab Rechnung", width: 2cm) #place(center+bottom, dy: 1.1em)[ #block(width: 100%+0.75em, fill: white)[ #text(size: 8pt)[ Zahlen mit Code ] ] ] ] ] ]
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/mergesort/merge_algorithm_2.typ
typst
#import "/components/num_row.typ": num_row, arrowed #let nums = (12, 23, 34, 45, 7, 17, 18, 38, 43, []) #let n = nums.len()-1 #let m = calc.div-euclid(n, 2) #table( columns: (auto, ) + (1fr,) * nums.len(), align: center, stroke: (x, _) => if x == n+1 {none} else {1pt}, ..num_row( nums, hl_tertiary: 3, hl_gray: range(3) + range(4, n), arrow_down: ( (3, n - 1), ), labels: ( (3, 4, arrowed[`a1f`]), (n, n+1, arrowed[`a2f`]) ), below: 0pt ), ..num_row( (7, 12, 17, 18, 23, 34, 38, 43, 45) + ([],), hl_success: range(n) ) )
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/067.%20startupmistakes.html.typ
typst
startupmistakes.html The 18 Mistakes That Kill Startups Want to start a startup? Get funded by Y Combinator. October 2006In the Q & A period after a recent talk, someone asked what made startups fail. After standing there gaping for a few seconds I realized this was kind of a trick question. It's equivalent to asking how to make a startup succeed — if you avoid every cause of failure, you succeed — and that's too big a question to answer on the fly.Afterwards I realized it could be helpful to look at the problem from this direction. If you have a list of all the things you shouldn't do, you can turn that into a recipe for succeeding just by negating. And this form of list may be more useful in practice. It's easier to catch yourself doing something you shouldn't than always to remember to do something you should. [1]In a sense there's just one mistake that kills startups: not making something users want. If you make something users want, you'll probably be fine, whatever else you do or don't do. And if you don't make something users want, then you're dead, whatever else you do or don't do. So really this is a list of 18 things that cause startups not to make something users want. Nearly all failure funnels through that.1. Single FounderHave you ever noticed how few successful startups were founded by just one person? Even companies you think of as having one founder, like Oracle, usually turn out to have more. It seems unlikely this is a coincidence.What's wrong with having one founder? To start with, it's a vote of no confidence. It probably means the founder couldn't talk any of his friends into starting the company with him. That's pretty alarming, because his friends are the ones who know him best.But even if the founder's friends were all wrong and the company is a good bet, he's still at a disadvantage. Starting a startup is too hard for one person. Even if you could do all the work yourself, you need colleagues to brainstorm with, to talk you out of stupid decisions, and to cheer you up when things go wrong.The last one might be the most important. The low points in a startup are so low that few could bear them alone. When you have multiple founders, esprit de corps binds them together in a way that seems to violate conservation laws. Each thinks "I can't let my friends down." This is one of the most powerful forces in human nature, and it's missing when there's just one founder.2. Bad LocationStartups prosper in some places and not others. Silicon Valley dominates, then Boston, then Seattle, Austin, Denver, and New York. After that there's not much. Even in New York the number of startups per capita is probably a 20th of what it is in Silicon Valley. In towns like Houston and Chicago and Detroit it's too small to measure.Why is the falloff so sharp? Probably for the same reason it is in other industries. What's the sixth largest fashion center in the US? The sixth largest center for oil, or finance, or publishing? Whatever they are they're probably so far from the top that it would be misleading even to call them centers.It's an interesting question why cities become startup hubs, but the reason startups prosper in them is probably the same as it is for any industry: that's where the experts are. Standards are higher; people are more sympathetic to what you're doing; the kind of people you want to hire want to live there; supporting industries are there; the people you run into in chance meetings are in the same business. Who knows exactly how these factors combine to boost startups in Silicon Valley and squish them in Detroit, but it's clear they do from the number of startups per capita in each.3. Marginal NicheMost of the groups that apply to Y Combinator suffer from a common problem: choosing a small, obscure niche in the hope of avoiding competition.If you watch little kids playing sports, you notice that below a certain age they're afraid of the ball. When the ball comes near them their instinct is to avoid it. I didn't make a lot of catches as an eight year old outfielder, because whenever a fly ball came my way, I used to close my eyes and hold my glove up more for protection than in the hope of catching it.Choosing a marginal project is the startup equivalent of my eight year old strategy for dealing with fly balls. If you make anything good, you're going to have competitors, so you may as well face that. You can only avoid competition by avoiding good ideas.I think this shrinking from big problems is mostly unconscious. It's not that people think of grand ideas but decide to pursue smaller ones because they seem safer. Your unconscious won't even let you think of grand ideas. So the solution may be to think about ideas without involving yourself. What would be a great idea for someone else to do as a startup?4. Derivative IdeaMany of the applications we get are imitations of some existing company. That's one source of ideas, but not the best. If you look at the origins of successful startups, few were started in imitation of some other startup. Where did they get their ideas? Usually from some specific, unsolved problem the founders identified.Our startup made software for making online stores. When we started it, there wasn't any; the few sites you could order from were hand-made at great expense by web consultants. We knew that if online shopping ever took off, these sites would have to be generated by software, so we wrote some. Pretty straightforward.It seems like the best problems to solve are ones that affect you personally. Apple happened because <NAME> wanted a computer, Google because Larry and Sergey couldn't find stuff online, Hotmail because <NAME> and <NAME> couldn't exchange email at work.So instead of copying the Facebook, with some variation that the Facebook rightly ignored, look for ideas from the other direction. Instead of starting from companies and working back to the problems they solved, look for problems and imagine the company that might solve them. [2] What do people complain about? What do you wish there was?5. ObstinacyIn some fields the way to succeed is to have a vision of what you want to achieve, and to hold true to it no matter what setbacks you encounter. Starting startups is not one of them. The stick-to-your-vision approach works for something like winning an Olympic gold medal, where the problem is well-defined. Startups are more like science, where you need to follow the trail wherever it leads.So don't get too attached to your original plan, because it's probably wrong. Most successful startups end up doing something different than they originally intended — often so different that it doesn't even seem like the same company. You have to be prepared to see the better idea when it arrives. And the hardest part of that is often discarding your old idea.But openness to new ideas has to be tuned just right. Switching to a new idea every week will be equally fatal. Is there some kind of external test you can use? One is to ask whether the ideas represent some kind of progression. If in each new idea you're able to re-use most of what you built for the previous ones, then you're probably in a process that converges. Whereas if you keep restarting from scratch, that's a bad sign.Fortunately there's someone you can ask for advice: your users. If you're thinking about turning in some new direction and your users seem excited about it, it's probably a good bet.6. Hiring Bad ProgrammersI forgot to include this in the early versions of the list, because nearly all the founders I know are programmers. This is not a serious problem for them. They might accidentally hire someone bad, but it's not going to kill the company. In a pinch they can do whatever's required themselves.But when I think about what killed most of the startups in the e-commerce business back in the 90s, it was bad programmers. A lot of those companies were started by business guys who thought the way startups worked was that you had some clever idea and then hired programmers to implement it. That's actually much harder than it sounds — almost impossibly hard in fact — because business guys can't tell which are the good programmers. They don't even get a shot at the best ones, because no one really good wants a job implementing the vision of a business guy.In practice what happens is that the business guys choose people they think are good programmers (it says here on his resume that he's a Microsoft Certified Developer) but who aren't. Then they're mystified to find that their startup lumbers along like a World War II bomber while their competitors scream past like jet fighters. This kind of startup is in the same position as a big company, but without the advantages.So how do you pick good programmers if you're not a programmer? I don't think there's an answer. I was about to say you'd have to find a good programmer to help you hire people. But if you can't recognize good programmers, how would you even do that?7. Choosing the Wrong PlatformA related problem (since it tends to be done by bad programmers) is choosing the wrong platform. For example, I think a lot of startups during the Bubble killed themselves by deciding to build server-based applications on Windows. Hotmail was still running on FreeBSD for years after Microsoft bought it, presumably because Windows couldn't handle the load. If Hotmail's founders had chosen to use Windows, they would have been swamped.PayPal only just dodged this bullet. After they merged with X.com, the new CEO wanted to switch to Windows — even after PayPal cofounder <NAME> showed that their software scaled only 1% as well on Windows as Unix. Fortunately for PayPal they switched CEOs instead.Platform is a vague word. It could mean an operating system, or a programming language, or a "framework" built on top of a programming language. It implies something that both supports and limits, like the foundation of a house.The scary thing about platforms is that there are always some that seem to outsiders to be fine, responsible choices and yet, like Windows in the 90s, will destroy you if you choose them. Java applets were probably the most spectacular example. This was supposed to be the new way of delivering applications. Presumably it killed just about 100% of the startups who believed that.How do you pick the right platforms? The usual way is to hire good programmers and let them choose. But there is a trick you could use if you're not a programmer: visit a top computer science department and see what they use in research projects.8. Slowness in LaunchingCompanies of all sizes have a hard time getting software done. It's intrinsic to the medium; software is always 85% done. It takes an effort of will to push through this and get something released to users. [3]Startups make all kinds of excuses for delaying their launch. Most are equivalent to the ones people use for procrastinating in everyday life. There's something that needs to happen first. Maybe. But if the software were 100% finished and ready to launch at the push of a button, would they still be waiting?One reason to launch quickly is that it forces you to actually finish some quantum of work. Nothing is truly finished till it's released; you can see that from the rush of work that's always involved in releasing anything, no matter how finished you thought it was. The other reason you need to launch is that it's only by bouncing your idea off users that you fully understand it.Several distinct problems manifest themselves as delays in launching: working too slowly; not truly understanding the problem; fear of having to deal with users; fear of being judged; working on too many different things; excessive perfectionism. Fortunately you can combat all of them by the simple expedient of forcing yourself to launch something fairly quickly.9. Launching Too EarlyLaunching too slowly has probably killed a hundred times more startups than launching too fast, but it is possible to launch too fast. The danger here is that you ruin your reputation. You launch something, the early adopters try it out, and if it's no good they may never come back.So what's the minimum you need to launch? We suggest startups think about what they plan to do, identify a core that's both (a) useful on its own and (b) something that can be incrementally expanded into the whole project, and then get that done as soon as possible.This is the same approach I (and many other programmers) use for writing software. Think about the overall goal, then start by writing the smallest subset of it that does anything useful. If it's a subset, you'll have to write it anyway, so in the worst case you won't be wasting your time. But more likely you'll find that implementing a working subset is both good for morale and helps you see more clearly what the rest should do.The early adopters you need to impress are fairly tolerant. They don't expect a newly launched product to do everything; it just has to do something.10. Having No Specific User in MindYou can't build things users like without understanding them. I mentioned earlier that the most successful startups seem to have begun by trying to solve a problem their founders had. Perhaps there's a rule here: perhaps you create wealth in proportion to how well you understand the problem you're solving, and the problems you understand best are your own. [4]That's just a theory. What's not a theory is the converse: if you're trying to solve problems you don't understand, you're hosed.And yet a surprising number of founders seem willing to assume that someone, they're not sure exactly who, will want what they're building. Do the founders want it? No, they're not the target market. Who is? Teenagers. People interested in local events (that one is a perennial tarpit). Or "business" users. What business users? Gas stations? Movie studios? Defense contractors?You can of course build something for users other than yourself. We did. But you should realize you're stepping into dangerous territory. You're flying on instruments, in effect, so you should (a) consciously shift gears, instead of assuming you can rely on your intuitions as you ordinarily would, and (b) look at the instruments.In this case the instruments are the users. When designing for other people you have to be empirical. You can no longer guess what will work; you have to find users and measure their responses. So if you're going to make something for teenagers or "business" users or some other group that doesn't include you, you have to be able to talk some specific ones into using what you're making. If you can't, you're on the wrong track.11. Raising Too Little MoneyMost successful startups take funding at some point. Like having more than one founder, it seems a good bet statistically. How much should you take, though?Startup funding is measured in time. Every startup that isn't profitable (meaning nearly all of them, initially) has a certain amount of time left before the money runs out and they have to stop. This is sometimes referred to as runway, as in "How much runway do you have left?" It's a good metaphor because it reminds you that when the money runs out you're going to be airborne or dead.Too little money means not enough to get airborne. What airborne means depends on the situation. Usually you have to advance to a visibly higher level: if all you have is an idea, a working prototype; if you have a prototype, launching; if you're launched, significant growth. It depends on investors, because until you're profitable that's who you have to convince.So if you take money from investors, you have to take enough to get to the next step, whatever that is. [5] Fortunately you have some control over both how much you spend and what the next step is. We advise startups to set both low, initially: spend practically nothing, and make your initial goal simply to build a solid prototype. This gives you maximum flexibility.12. Spending Too MuchIt's hard to distinguish spending too much from raising too little. If you run out of money, you could say either was the cause. The only way to decide which to call it is by comparison with other startups. If you raised five million and ran out of money, you probably spent too much.Burning through too much money is not as common as it used to be. Founders seem to have learned that lesson. Plus it keeps getting cheaper to start a startup. So as of this writing few startups spend too much. None of the ones we've funded have. (And not just because we make small investments; many have gone on to raise further rounds.)The classic way to burn through cash is by hiring a lot of people. This bites you twice: in addition to increasing your costs, it slows you down—so money that's getting consumed faster has to last longer. Most hackers understand why that happens; <NAME> explained it in The Mythical Man-Month.We have three general suggestions about hiring: (a) don't do it if you can avoid it, (b) pay people with equity rather than salary, not just to save money, but because you want the kind of people who are committed enough to prefer that, and (c) only hire people who are either going to write code or go out and get users, because those are the only things you need at first.13. Raising Too Much MoneyIt's obvious how too little money could kill you, but is there such a thing as having too much?Yes and no. The problem is not so much the money itself as what comes with it. As one VC who spoke at Y Combinator said, "Once you take several million dollars of my money, the clock is ticking." If VCs fund you, they're not going to let you just put the money in the bank and keep operating as two guys living on ramen. They want that money to go to work. [6] At the very least you'll move into proper office space and hire more people. That will change the atmosphere, and not entirely for the better. Now most of your people will be employees rather than founders. They won't be as committed; they'll need to be told what to do; they'll start to engage in office politics.When you raise a lot of money, your company moves to the suburbs and has kids.Perhaps more dangerously, once you take a lot of money it gets harder to change direction. Suppose your initial plan was to sell something to companies. After taking VC money you hire a sales force to do that. What happens now if you realize you should be making this for consumers instead of businesses? That's a completely different kind of selling. What happens, in practice, is that you don't realize that. The more people you have, the more you stay pointed in the same direction.Another drawback of large investments is the time they take. The time required to raise money grows with the amount. [7] When the amount rises into the millions, investors get very cautious. VCs never quite say yes or no; they just engage you in an apparently endless conversation. Raising VC scale investments is thus a huge time sink — more work, probably, than the startup itself. And you don't want to be spending all your time talking to investors while your competitors are spending theirs building things.We advise founders who go on to seek VC money to take the first reasonable deal they get. If you get an offer from a reputable firm at a reasonable valuation with no unusually onerous terms, just take it and get on with building the company. [8] Who cares if you could get a 30% better deal elsewhere? Economically, startups are an all-or-nothing game. Bargain-hunting among investors is a waste of time.14. Poor Investor ManagementAs a founder, you have to manage your investors. You shouldn't ignore them, because they may have useful insights. But neither should you let them run the company. That's supposed to be your job. If investors had sufficient vision to run the companies they fund, why didn't they start them?Pissing off investors by ignoring them is probably less dangerous than caving in to them. In our startup, we erred on the ignoring side. A lot of our energy got drained away in disputes with investors instead of going into the product. But this was less costly than giving in, which would probably have destroyed the company. If the founders know what they're doing, it's better to have half their attention focused on the product than the full attention of investors who don't.How hard you have to work on managing investors usually depends on how much money you've taken. When you raise VC-scale money, the investors get a great deal of control. If they have a board majority, they're literally your bosses. In the more common case, where founders and investors are equally represented and the deciding vote is cast by neutral outside directors, all the investors have to do is convince the outside directors and they control the company.If things go well, this shouldn't matter. So long as you seem to be advancing rapidly, most investors will leave you alone. But things don't always go smoothly in startups. Investors have made trouble even for the most successful companies. One of the most famous examples is Apple, whose board made a nearly fatal blunder in firing <NAME>. Apparently even Google got a lot of grief from their investors early on.15. Sacrificing Users to (Supposed) ProfitWhen I said at the beginning that if you make something users want, you'll be fine, you may have noticed I didn't mention anything about having the right business model. That's not because making money is unimportant. I'm not suggesting that founders start companies with no chance of making money in the hope of unloading them before they tank. The reason we tell founders not to worry about the business model initially is that making something people want is so much harder.I don't know why it's so hard to make something people want. It seems like it should be straightforward. But you can tell it must be hard by how few startups do it.Because making something people want is so much harder than making money from it, you should leave business models for later, just as you'd leave some trivial but messy feature for version 2. In version 1, solve the core problem. And the core problem in a startup is how to create wealth (= how much people want something x the number who want it), not how to convert that wealth into money.The companies that win are the ones that put users first. Google, for example. They made search work, then worried about how to make money from it. And yet some startup founders still think it's irresponsible not to focus on the business model from the beginning. They're often encouraged in this by investors whose experience comes from less malleable industries.It is irresponsible not to think about business models. It's just ten times more irresponsible not to think about the product.16. Not Wanting to Get Your Hands DirtyNearly all programmers would rather spend their time writing code and have someone else handle the messy business of extracting money from it. And not just the lazy ones. <NAME> Sergey apparently felt this way too at first. After developing their new search algorithm, the first thing they tried was to get some other company to buy it.Start a company? Yech. Most hackers would rather just have ideas. But as Larry and Sergey found, there's not much of a market for ideas. No one trusts an idea till you embody it in a product and use that to grow a user base. Then they'll pay big time.Maybe this will change, but I doubt it will change much. There's nothing like users for convincing acquirers. It's not just that the risk is decreased. The acquirers are human, and they have a hard time paying a bunch of young guys millions of dollars just for being clever. When the idea is embodied in a company with a lot of users, they can tell themselves they're buying the users rather than the cleverness, and this is easier for them to swallow. [9]If you're going to attract users, you'll probably have to get up from your computer and go find some. It's unpleasant work, but if you can make yourself do it you have a much greater chance of succeeding. In the first batch of startups we funded, in the summer of 2005, most of the founders spent all their time building their applications. But there was one who was away half the time talking to executives at cell phone companies, trying to arrange deals. Can you imagine anything more painful for a hacker? [10] But it paid off, because this startup seems the most successful of that group by an order of magnitude.If you want to start a startup, you have to face the fact that you can't just hack. At least one hacker will have to spend some of the time doing business stuff.17. Fights Between FoundersFights between founders are surprisingly common. About 20% of the startups we've funded have had a founder leave. It happens so often that we've reversed our attitude to vesting. We still don't require it, but now we advise founders to vest so there will be an orderly way for people to quit.A founder leaving doesn't necessarily kill a startup, though. Plenty of successful startups have had that happen. [11] Fortunately it's usually the least committed founder who leaves. If there are three founders and one who was lukewarm leaves, big deal. If you have two and one leaves, or a guy with critical technical skills leaves, that's more of a problem. But even that is survivable. Blogger got down to one person, and they bounced back.Most of the disputes I've seen between founders could have been avoided if they'd been more careful about who they started a company with. Most disputes are not due to the situation but the people. Which means they're inevitable. And most founders who've been burned by such disputes probably had misgivings, which they suppressed, when they started the company. Don't suppress misgivings. It's much easier to fix problems before the company is started than after. So don't include your housemate in your startup because he'd feel left out otherwise. Don't start a company with someone you dislike because they have some skill you need and you worry you won't find anyone else. The people are the most important ingredient in a startup, so don't compromise there.18. A Half-Hearted EffortThe failed startups you hear most about are the spectacular flameouts. Those are actually the elite of failures. The most common type is not the one that makes spectacular mistakes, but the one that doesn't do much of anything — the one we never even hear about, because it was some project a couple guys started on the side while working on their day jobs, but which never got anywhere and was gradually abandoned.Statistically, if you want to avoid failure, it would seem like the most important thing is to quit your day job. Most founders of failed startups don't quit their day jobs, and most founders of successful ones do. If startup failure were a disease, the CDC would be issuing bulletins warning people to avoid day jobs.Does that mean you should quit your day job? Not necessarily. I'm guessing here, but I'd guess that many of these would-be founders may not have the kind of determination it takes to start a company, and that in the back of their minds, they know it. The reason they don't invest more time in their startup is that they know it's a bad investment. [12]I'd also guess there's some band of people who could have succeeded if they'd taken the leap and done it full-time, but didn't. I have no idea how wide this band is, but if the winner/borderline/hopeless progression has the sort of distribution you'd expect, the number of people who could have made it, if they'd quit their day job, is probably an order of magnitude larger than the number who do make it. [13]If that's true, most startups that could succeed fail because the founders don't devote their whole efforts to them. That certainly accords with what I see out in the world. Most startups fail because they don't make something people want, and the reason most don't is that they don't try hard enough.In other words, starting startups is just like everything else. The biggest mistake you can make is not to try hard enough. To the extent there's a secret to success, it's not to be in denial about that. Notes[1] This is not a complete list of the causes of failure, just those you can control. There are also several you can't, notably ineptitude and bad luck.[2] Ironically, one variant of the Facebook that might work is a facebook exclusively for college students.[3] <NAME> tried to motivate people by saying "Real artists ship." This is a fine sentence, but unfortunately not true. Many famous works of art are unfinished. It's true in fields that have hard deadlines, like architecture and filmmaking, but even there people tend to be tweaking stuff till it's yanked out of their hands.[4] There's probably also a second factor: startup founders tend to be at the leading edge of technology, so problems they face are probably especially valuable.[5] You should take more than you think you'll need, maybe 50% to 100% more, because software takes longer to write and deals longer to close than you expect.[6] Since people sometimes call us VCs, I should add that we're not. VCs invest large amounts of other people's money. We invest small amounts of our own, like angel investors.[7] Not linearly of course, or it would take forever to raise five million dollars. In practice it just feels like it takes forever.Though if you include the cases where VCs don't invest, it would literally take forever in the median case. And maybe we should, because the danger of chasing large investments is not just that they take a long time. That's the best case. The real danger is that you'll expend a lot of time and get nothing.[8] Some VCs will offer you an artificially low valuation to see if you have the balls to ask for more. It's lame that VCs play such games, but some do. If you're dealing with one of those you should push back on the valuation a bit.[9] Suppose YouTube's founders had gone to Google in 2005 and told them "Google Video is badly designed. Give us $10 million and we'll tell you all the mistakes you made." They would have gotten the royal raspberry. Eighteen months later Google paid $1.6 billion for the same lesson, partly because they could then tell themselves that they were buying a phenomenon, or a community, or some vague thing like that.I don't mean to be hard on Google. They did better than their competitors, who may have now missed the video boat entirely.[10] Yes, actually: dealing with the government. But phone companies are up there.[11] Many more than most people realize, because companies don't advertise this. Did you know Apple originally had three founders?[12] I'm not dissing these people. I don't have the determination myself. I've twice come close to starting startups since Viaweb, and both times I bailed because I realized that without the spur of poverty I just wasn't willing to endure the stress of a startup.[13] So how do you know whether you're in the category of people who should quit their day job, or the presumably larger one who shouldn't? I got to the point of saying that this was hard to judge for yourself and that you should seek outside advice, before realizing that that's what we do. We think of ourselves as investors, but viewed from the other direction Y Combinator is a service for advising people whether or not to quit their day job. We could be mistaken, and no doubt often are, but we do at least bet money on our conclusions.Thanks to <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this. Japanese TranslationSpanish TranslationRomanian TranslationChinese TranslationArabic Translation
https://github.com/krestenlaust/AAU-Typst-Template
https://raw.githubusercontent.com/krestenlaust/AAU-Typst-Template/main/report-template/chapters/understanding_typst.typ
typst
MIT License
= Command- and Markup-Mode Typst has two modes of text. This text right here is written directly in markup mode. The default mode of a document is always markup mode. To enter command mode for a single command, the `#` is used. rect() #rect() To enter markup mode in a command context/mode, use `[...]`, previously shown, this can be thought of as similar to a string `"..."` in a general-purpose programming language#footnote("Typst infers between the concept of strings, and content mode seamlessly. String literals are primarily used in function calls, like this one right here.")#footnote([This could've also been written using the content mode `[...]`. This way it is easier to *markup* things than in a string.]). The operators can be combined to cancel each other out like so: #[This is exactly the same as] writing the text like this. To enter command-mode for multiple commands, you can use curly braces like so: `{...}`#footnote([This is generally only used in the template file, it's pretty rare to need to use multiple commands in a row, in documents like this one.]) == Further reading & Assistance The Typst documentation has, for the most part, matured enough to answer any question. The documentation is located at https://typst.app/docs. Furthermore, the documentation site often appears in Google search results. Typst has a very welcoming community, the easiest and fastest place to get help with an issue is their Discord server at https://typst.app/docs/community/. If you are a fellow student on AAU (Or any other university/high-school for that sake), and are experiencing issues with this Template (Or Typst in general) feel free to reach out at `kscker23[at]student.aau.dk`, and I'll do my best.
https://github.com/iseri27/tagbar-typst
https://raw.githubusercontent.com/iseri27/tagbar-typst/master/README.md
markdown
MIT License
# tagbar-typst ## Intro [中文介绍](https://github.com/Corona09/tagbar-typst/blob/master/README_zh.md) tagbar-typst is a tagbar extension for typst. It is a fork of [lvht/tagbar-markdown](https://github.com/lvht/tagbar-markdown.git). ## Screenshot ![](./screenshot/screenshot.png) ## Install - [vim-plug] ```viml Plug 'majutsushi/tagbar' Plug 'Corona09/tagbar-typst' ``` Please make sure **php** is in your `$PATH` and the `bin/typst_ctags` has execute permission. Enjoy :) [vim-plug]: https://github.com/junegunn/vim-plug [dein.vim]: https://github.com/Shougo/dein.vim Highlight plugin for typst: [Corona/nvim-typst](https://github.com/Corona09/nvim-typst.git)
https://github.com/Its-Alex/resume
https://raw.githubusercontent.com/Its-Alex/resume/master/lib/skills.typ
typst
MIT License
#import "components/title.typ": customTitle #let skills(title, skills) = [ #customTitle(title) #grid( columns: (100%), gutter: 0pt, row-gutter: 1.5em, ..skills.map((skill) => [ #text(weight: 600)[#skill.name] \ #text()[#skill.description] ]) ) ]
https://github.com/Area-53-Robotics/53A-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53A-Notebook-Over-Under-2023-2024/master/Vex%20Robotics%2053A%20Notebook%202023%20-%202024/Entries/Tournament%20Entry/Dulaney-Royal-Rumble.typ
typst
#set page(header: [ VR #h(1fr) November 4, 2023 ]) = DULANEY ROYAL RUMBLE TOURNAMENT REFLECTIONS \ Today we competed in our first tournament of the Over-under season: the Dulaney Royal Rumble. We did well during qualifications, ranking 9th, ending by becoming the second seed of the elimination rounds. We won our first round of 16 and quarterfinals. We were defeated during semi-finals. == Strategy - Our robot can shoot match loads and score triballs - One partner will shoot match loads to goal side of field and one will score them - We can complete either part depending on alliance partner’s capabilities == Match Analysis - Green: Matches we won - Red: Matches we lost //~table~ //green for win //red for lose #table( columns: (2fr, 1.5fr, 1.5fr, 8fr), fill: (_, row) => if row > 0 and row <= 3 or row == 5 or row == 9 or row == 10 {rgb("#CCFFCC")} else if row == 7 or row == 8 or row == 11 { rgb("#FFCCCC") } //else if row == 0 { rgb("#ebccff") } else { white }, align: (left), inset: 5pt, [*Q\#*], [*Auton W/L*], [*Score*], [*Notes*], [6], [Tie], [85 - 53], [#set list(marker: ([•], [>])) *#underline[Auton]* - Started on side opposite to goal - Didn’t run a program *#underline[Driver Control]* - Wanted to match load triballs across field for alliance partner to score - Tried to run catapult - Launched once - Lowered for second shot, but wouldn’t shoot - Couldn't use original strategy - Decided to push triballs onto our side using wings - Pushed triballs - Opponents match loaded near their goal over the middle barrier - Double zoned, and scored triballs we pushed over ourselves - Noticed that catapult randomly lowered and slowly released even when not being used ], [11], [Tie], [72 - 55], [#set list(marker: ([•], [>])) * #underline[Auton]* - Started on side opposite to goal - Didn’t run a program *#underline[Driver Control]* - Strategized to score triballs that our alliance partner launched onto our side of the field - 1 min into match, alliance partner became stuck on load zone - Alliance partner quickly gained control, but failed to shoot more triballs for us to score - Alliance partner and us defended on opposing alliance - Prevented match loads from reaching their side - Prevented triballs from being scored - Towards end of match, pushed triballs on opponent’s side of field into load zones so they wouldn’t count towards their score - Alliance partner tried to climb, but failed to ], [19], [Win], [139 - 12], [#set list(marker: ([•], [>])) *#underline[Auton]* - Started on our side of field - Didn’t run autonomous *#underline[Driver Control]* - Scored Triballs that alliance partner launched to our side - Alliance partner shot many triballs very quickly - Strategy worked seamlessly - Found that intake was very efficient at scoring single triballs, when there weren’t crowds of triballs to ram using wings - Succeeded in climbing ], [Skills Run #1], [], [25], [#set list(marker: ([•], [>])) *#underline[Driver Control]* - Strategy - Use catapult to match load triballs to goal - Drive to other side, use wings to ram triballs into goal - Launched one triball - Catapult lowered, but became stuck - Used wings to push triballs over the middle barrier - Drove to other side of field to score triballs using wings ], [30], [Win], [63 - 26], [#set list(marker: ([•], [>])) *#underline[Auton]* - Started on same side as goal - Won autonomous through alliance parter’s autonomous program *#underline[Driver Control]* - Alliance partner could not shoot match loads - Alliance partner defended on opponents while we scored triballs into our goal - Pushed triballs from opponents defensive zone into ours, and scored them - Alliance partner succeeds in climbing ], [Skills Run #2], [], [20], [#set list(marker: ([•], [>])) *#underline[Driver Control]* - Strategy: Use intake and wings to score triballs - Tried to score first triball using intake - Intake could not outtake the triball into the goal - Used wings and side of robot to score triballs for the rest of the run ], [42], [Loss], [59 - 78], [#set list(marker: ([•], [>])) *#underline[Auton]* - Started near our goal - Ran program to drive forward, turn, and score one triball - Robot went forward, hit the side of the goal, veered of course, and did not score *#underline[Driver Control]* - Strategy: Score triballs our alliance partner match loads onto our defensive zone - Could not execute strategy because intake was not working - Similarly to previous skills run - Defended on opposing robot match loading onto their side - Failed because their catapult shot over our robot ], [49], [Loss], [58 - 62], [#set list(marker: ([•], [>])) *#underline[Auton]* - Started on side opposite to our goal - Alliance partner crossed middle of field - Autonomous win went to opponents *#underline[Driver Control]* - Tried to push triballs over middle barrier for alliance partner to score - Could only use wings - Catapult and intake did not work - Alliance partner decided to defend on opponents - We drove triballs from the load zone to our goal ], [Round of 16], [Loss], [123 - 77], [#set list(marker: ([•], [>])) *#underline[Auton]* - Started on our goal’s side - Didn’t run autonomous program for risk of crossing middle field and losing all autonomous points - Alliance partner scored one alliance triball *#underline[Driver Control]* - Alliance partner shot match loads onto our side of field, we scored them - Succeeded in climbing ], [#set text(hyphenate: true) Quarterfinals], [Win], [92 - 36], [#set list(marker: ([•], [>])) *#underline[Before match]* - coded last minute auton that pushed alliance triball into goal from loading station - Robot drives forward to push triballs infront of it into side of goal *#underline[Auton]* - Started on our goal’s side - Program was successful *#underline[Driver Control]* - Used same strategy as first elimination match - Side of drivetrain started lagging - Didn’t climb during endgame *#underline[After match]* - After match, found that one of the motors became unscrewed from chassis - Axle came out of motor and wasn’t driven, so drivetrain lost power ], [#set text(hyphenate: true) Semifinals], [Loss], [52 - 93], [#set list(marker: ([•], [>])) *#underline[Before match]* - called timeout to screw in lose motor - Fixed drivetrain lagging * #underline[Auton]* - Ran same program as last match - Not successful - Angle of robot to goal was not accurate - Triball didn’t get into goal * #underline[Driver Control]* - During match, got rammed by opponent - Battery became unplugged - Robot was disabled for the rest of the match ], )
https://github.com/vitto4/ttuile
https://raw.githubusercontent.com/vitto4/ttuile/main/template/main.typ
typst
MIT License
// ttuile template, find out more on github https://github.com/vitto4/ttuile // Documentation available in the readme file. // * : ttuile, equation-anonyme, annexe, afficher-annexes, figure-emboitee #import "@preview/ttuile:0.1.1": * #show: ttuile.with( titre: [« #lorem(8) »], auteurs: ( "<NAME>", "<NAME>", "<NAME>", ), groupe: "TD0", numero-tp: 0, numero-poste: "0", date: datetime.today(), // sommaire: false, // logo: image("path_to/logo.png"), // point-legende: true, ) // Supprimez tout ce qu'il y a en dessous de cette ligne pour commencer. // Delete everything below this line to get stared. // // If you're feeling lazy, give `Ctrl + Shift + End` a try :p // // <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> // // ---------------------------------------------------------------------------- // // Corps du rapport // // ---------------------------------------------------------------------------- // // ------------------------------- Introduction ------------------------------- // = #lorem(1) #lorem(30) - #lorem(30) - #lorem(25) // Les équations sont numérotées par défaut $ E = m c^2 + italic("AI") $ // Note de bas de page #lorem(28) #footnote([#lorem(27)]) #{2*linebreak()} // Création d'une figure #let liste-couleurs = (black, gray, silver, white, navy, blue, aqua, teal, eastern, purple, fuchsia, maroon, red, orange, yellow, olive, green, lime) #let couleurs = grid( columns: 9*(1fr,), rows: 2, row-gutter: 1em, ..liste-couleurs.map(c => { square( size: 45pt, fill: c, stroke: if (black, navy, maroon).contains(c) {1.2pt + silver} else {1.2pt}, ) }) ) #figure( couleurs, caption: [#lorem(10)] ) // Saut de page après l'introduction #pagebreak() // ------------------------------- Deuxième page ------------------------------ // = #lorem(10) // L'espacement entre les titres est géré automatiquement == #lorem(7) #lorem(26) // Il est possible de référencer une annexe définie à la fin du rapport @annexe-1 #lorem(10) == #lorem(2) #lorem(18) === #lorem(6) #lorem(45) #linebreak() #lorem(35) // Les titres de niveau 4 ne sont pas affichés dans la table des matière // C'est le plus bas niveau actuellement supporté par le template, un titre de niveau 5 ne sera pas stylisé adéquatement ==== #lorem(1) #lorem(30) // Cette équation n'est pas numérotée (contrairement à celle en introduction) #equation-anonyme( $ tilde(cal(T)) = mat( delim: "|", 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; gap: #0.3em ) $ ) #lorem(45) ==== #lorem(5) #lorem(50) #linebreak() #lorem(23) // ---------------------------------- Annexes --------------------------------- // // Définition d'une annexe, elle reste pour l'instant simplement stockée dans une variable et n'est pas immédiatement affichée #let annexe-1 = annexe( titre: [#lorem(5)], reference: <annexe-1>, )[ // Le corps de l'annexe, c'est ce qui est affiché sur la page en dessous du titre #lorem(50) #align( center )[ *95% of people cannot solve this!* #let rr = $thin \u{1f98f} thin$ #let bb = $thin \u{1f37b} thin$ #let ll = $thin \u{1f3ee} thin$ #equation-anonyme( $ ll / (bb + rr) + bb / (ll + rr) + rr / (ll + bb) = 4 $ ) *Can you find positive whole values for $ll$, $bb$ and $rr$?* ] #lorem(45) ] #afficher-annexes( annexes: (annexe-1,), // Ajouter les autres annexes dans la liste table: true, // `true` par défaut, on demande l'affichage de la table des annexes )
https://github.com/jxpeng98/Typst-CV-Resume
https://raw.githubusercontent.com/jxpeng98/Typst-CV-Resume/main/modernpro-cv.typ
typst
MIT License
/////////////////////////////// // modernpro-cv.typ // A CV template with modern Sans font and professional look // Copyright (c) 2024 // Author: <NAME> // License: MIT // Version: 1.0.2 // Date: 2024-10-21 // Email: <EMAIL> /////////////////////////////// // Define the colour scheme #let date-colour = rgb("#666666") #let primary-colour = rgb("#000000") #let headings-colour = rgb("#2b2b2b") #let subheadings-colour = rgb("#333333") #let sectionsep = { [#v(0.5pt)] } #let subsectionsep = { [#v(0.5pt)] } // Section Headings (Education, Experience, etc) #let section(title) = { text(12pt, fill: headings-colour, weight: "bold")[ #upper[#title] #v(-8pt) #line(length: 100%) #v(-5pt) ] } // Subsection Headings (institution, Company, etc) #let subsection(content) = { text(11pt, fill: subheadings-colour, weight: "bold")[#content] } // Education part #let education(institution: "", major: "", date: "", location: "", description: "") = { text(11pt, fill: subheadings-colour, weight: "bold")[#institution, #location] h(1fr) text(11pt, style: "italic", fill: headings-colour, weight: "regular")[#date \ ] text(11pt, style: "italic", fill: subheadings-colour, weight: "medium")[#major \ ] if description != [] or description != "" { text(11pt, fill: primary-colour, weight: "regular")[#description] } } // Projects #let project(title, date, info) = { text(11pt, fill: subheadings-colour, weight: "semibold")[#title ] if date != [] or date != "" { h(1fr) text(11pt, fill: headings-colour, weight: "medium")[#date \ ] } else { [\ ] } if info != [] or info != "" { text(11pt, fill: primary-colour, weight: "light")[#info ] } } // Description of a job, degree, etc #let descript(content) = { text(11pt, fill: subheadings-colour, weight: "regular")[#content ] } // Job title #let job(position: "", institution: "", location: "", date: "", description: "") = { text(11pt, fill: subheadings-colour, weight: "semibold")[#position] h(1fr) text(11pt, style: "italic", fill: headings-colour, weight: "regular")[#location \ ] text(11pt, style: "italic", fill: subheadings-colour, weight: "medium")[#institution] h(1fr) text(11pt, style: "italic", fill: headings-colour, weight: "regular")[#date] if description != [] or description != "" { text(11pt, fill: primary-colour, weight: "regular")[#description] } } // Details #let info(content) = { text(11pt, fill: primary-colour, weight: "light")[#content\ ] } #let oneline-title-item(title: "", content: "") = { text(11pt, fill: subheadings-colour, weight: "bold")[#title: ] text(11pt, fill: primary-colour, weight: "light")[#content \ ] } #let oneline-two(entry1: "", entry2: "") = { text(11pt, fill: subheadings-colour, weight: "regular")[#entry1] h(1fr) text(11pt, fill: primary-colour, weight: "regular")[#entry2 \ ] } #let twoline-item(entry1: none, entry2: none, entry3: none, entry4: none, description: none) = { text(11pt, fill: subheadings-colour, weight: "semibold")[#entry1] if entry2 != none { h(1fr) text(11pt, style: "italic", fill: headings-colour, weight: "regular")[#entry2 \ ] } if entry3 != [] or entry3 != "" != none { text(11pt, style: "italic", fill: subheadings-colour, weight: "medium")[#entry3] } if entry4 != none { h(1fr) text(11pt, style: "italic", fill: headings-colour, weight: "regular")[#entry4 \ ] } if description != [] or description != "" { text(11pt, fill: primary-colour, weight: "regular")[#description] } } #let award(award: "", institution: "", date: "") = { [#text(11pt, fill: primary-colour, weight: "medium")[#award,] #text( 11pt, fill: primary-colour, weight: "regular", )[#emph(institution)] #h(1fr) #text(11pt, fill: primary-colour, weight: "regular")[#emph(date)\ ]] } #let references(references: ()) = { grid(columns: (1fr, 1fr), row-gutter: 10pt, ..references.map(reference => { align( left, { if ("position" in reference) { text(11pt, fill: primary-colour, weight: "semibold")[#reference.name | #reference.position\ ] } else { text(11pt, fill: primary-colour, weight: "semibold")[#reference.name\ ] } if ("department" in reference) { text(10pt, fill: primary-colour, weight: "regular")[#reference.department\ ] } if ("institution" in reference) { text(10pt, fill: primary-colour, weight: "regular")[#reference.institution\ ] } if ("address" in reference) { text(10pt, fill: primary-colour, weight: "regular")[#reference.address\ ] } if ("email" in reference) { text(10pt, fill: primary-colour, weight: "regular")[ #reference.email \ ] } v(2pt) }, ) })) } // Publications #let publication(path, styletype) = { set text(11pt, fill: primary-colour, weight: "light") bibliography(path, title: none, full: true, style: styletype) } // show contact details #let contact-display(contacts) = { v(-5pt) set text(10pt, fill: headings-colour, weight: "regular") contacts .map(contact => { if ("link" in contact) { link(contact.link)[#contact.text] } else { [#contact.text] } }) .join(" | ") } #let cv-single( font-type: "Times New Roman", continue-header: "false", name: "", address: "", lastupdated: "true", pagecount: "true", date: none, contacts: (), mainbody, ) = { set text(font: font-type, weight: "regular") set cite(form: "full") if date == none { let date = [#datetime.today().display()] } // last update let lastupdate(lastupdated, date) = { if lastupdated == "true" { set text(8pt, style: "italic", fill: primary-colour, weight: "light") [Last updated: #date] } } set page(footer: [ #lastupdate(lastupdated, date) #h(1fr) #text(9pt, style: "italic", fill: primary-colour, weight: "light")[#name] #h(1fr) #if pagecount == "true" { text( 9pt, style: "italic", fill: primary-colour, weight: "light", )[Page #counter(page).display("1 / 1", both: true)] } ]) if continue-header == "true" { set page( margin: (left: 1.25cm, right: 1.25cm, top: 2.5cm, bottom: 1.5cm), header: { text( 20pt, fill: primary-colour, weight: "bold", top-edge: "baseline", bottom-edge: "baseline", baseline: 11pt, )[#align(center, [#name])] // address if address != none { v(3pt) text( 11pt, fill: primary-colour, weight: "regular", top-edge: "baseline", bottom-edge: "baseline", baseline: 2pt, )[#align(center, [#address])] } v(2pt) align(center)[#contact-display(contacts)] }, header-ascent: 1em, ) mainbody } else { set page(margin: (left: 1.25cm, right: 1.25cm, top: 1cm, bottom: 1cm)) text( 20pt, fill: primary-colour, weight: "bold", top-edge: "baseline", bottom-edge: "baseline", baseline: 11pt, )[#align(center, [#name])] // address if address != none { v(3pt) text( 11pt, fill: primary-colour, weight: "regular", top-edge: "baseline", bottom-edge: "baseline", baseline: 2pt, )[#align(center, [#address])] } v(2pt) align(center)[#contact-display(contacts)] // line(length: 100%, stroke: 0.5pt + primary-colour) mainbody } //Main Body } #let cv-double( font-type: "Times New Roman", continue-header: "false", name: "", address: "", lastupdated: "true", pagecount: "true", date: none, contacts: (), left: "", right: "", ) = { set text(font: font-type, weight: "regular") set cite(form: "full") if date == none { let date = [#datetime.today().display()] } // last update let lastupdate(lastupdated, date) = { if lastupdated == "true" { set text(8pt, style: "italic", fill: primary-colour, weight: "light") [Last updated: #date] } } set page(footer: [ #lastupdate(lastupdated, date) #h(1fr) #text(9pt, style: "italic", fill: primary-colour, weight: "light")[#name] #h(1fr) #if pagecount == "true" { text( 9pt, style: "italic", fill: primary-colour, weight: "light", )[Page #counter(page).display("1 / 1", both: true)] } ]) if continue-header == "true" { set page( margin: (left: 1.25cm, right: 1.25cm, top: 2.5cm, bottom: 1.5cm), header: { text( 20pt, fill: primary-colour, weight: "bold", top-edge: "baseline", bottom-edge: "baseline", baseline: 11pt, )[#align(center, [#name])] // address if address != none { v(3pt) text( 11pt, fill: primary-colour, weight: "regular", top-edge: "baseline", bottom-edge: "baseline", baseline: 2pt, )[#align(center, [#address])] } v(2pt) align(center)[#contact-display(contacts)] v(2pt) }, header-ascent: 1em, ) //Main Body grid( columns: (1fr, 2fr), column-gutter: 2em, left, right, ) } else { set page(margin: (left: 1.25cm, right: 1.25cm, top: 1cm, bottom: 1.5cm)) text( 20pt, fill: primary-colour, weight: "bold", top-edge: "baseline", bottom-edge: "baseline", baseline: 11pt, )[#align(center, [#name])] // address if address != none { v(3pt) text( 11pt, fill: primary-colour, weight: "regular", top-edge: "baseline", bottom-edge: "baseline", baseline: 2pt, )[#align(center, [#address])] } v(2pt) align(center)[#contact-display(contacts)] v(2pt) //Main Body grid( columns: (1fr, 2fr), column-gutter: 2em, left, right, ) } }
https://github.com/SillyFreak/typst-prequery
https://raw.githubusercontent.com/SillyFreak/typst-prequery/main/gallery/test.typ
typst
MIT License
// make the PDF reproducible to ease version control #set document(date: none) // #import "/src/lib.typ" as prequery #import "@preview/prequery:0.1.0" // toggle this comment or pass `--input prequery-fallback=true` to enable fallback // #prequery.fallback.update(true) #prequery.image( "https://upload.wikimedia.org/wikipedia/commons/a/af/Cc-public_domain_mark.svg", "assets/public_domain.svg")
https://github.com/hweissi/tugraz-typst-theme
https://raw.githubusercontent.com/hweissi/tugraz-typst-theme/main/main.typ
typst
#import "./tugraz-polylux.typ": * #import "@preview/pinit:0.1.4": * #show: tugraz-theme.with( footer: [Footer], progress-bar: true ) #set text(font: "Fira Sans", weight: "regular", size: 20pt) #show math.equation: set text(font: "Fira Math") #set strong(delta: 100) #set par(justify: true) #title-slide( author: [Author], title: [Slide Title], subtitle: [Subtitle], date: [Date], ) #slide(title: "Outline")[ #metropolis-outline ] #new-section-slide("First Chapter") #slide(title: "First Slide")[ - Some really important points - like, #alert("really") important ] #slide(title: "Cool box thing")[ #quotebox(footer: text(size: 0.9em, "Some Guy"), [ #lorem(60) ]) ] #slide(title: "Cool box thing")[ #defbox(title: [Definition: ], [ $P != N P$ ]) ] #new-section-slide([Second Chapter]) #focus-slide[ Wake up! ]
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Reading/跟李沐学AI(论文)/ViT.typ
typst
// --- // order: 8 // --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "d2l_paper", lang: "zh", ) = An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale) - 时间:2020.10 - ViT: Vision Transformer - ViT 是过去一年 CV 最有影响力的工作 + 推翻了 2012 Alexnet 以来 CNN 在 CV 的统治地位 + 有足够多的预训练数据,NLP 的 Transformer 直接搬运到 CV,效果也很好(模型迁移) + 打破 CV 和 NLP 的壁垒,给 CV、多模态 挖坑 == 标题 & 摘要 - 原本的 CV:Attention + CNN, or Attention 替换 CNN components 但依然保持 CNN 整体结构,但现在是完全的 Transformer - 标题的意思:每一个方格都是 $16 * 16$ 大小(patch),用 Transformer 去做大规模的图像识别 - 摘要中说“计算资源消耗少”是相对的概念,实际上还是很大(凡尔赛) == 引言 & 相关工作 - Transformers 是目前 NLP 必选模型,主流方式是 BERT 提出的在大规模数据集预训练,在特定领域小数据集做微调。即使在 $5300$ 亿参数的模型中也还没看到饱和现象 - Transformer 应用在 CV 的难点:计算复杂度是 $O(n^2)$,$224$ 分辨率的图片,有 $50176$ 个像素点(2d 图片 flatten),序列长度是 BERT 的近 $100$ 倍 - 于是自然的想法是,先用卷积抽特征,把变小的特征图再送进 Transformer,如 CVPR Wang et al. 2018, Local Network - 另外一种思路是把卷积层整个替换(换句话说,ViT 并不是首个用 Attention 完全替换 CNN 的): + stand-alone attention 孤立自注意力:用 local window 控制 transformer 的计算复杂度(类似卷积也有 locality) + axial attention 轴注意力:复杂度来自于 $n = H * W$,于是可以用 $2$ 个 1d 自注意力,先把 2d 矩阵拆分为两个 1d 向量,再分别对 $H$ 和 $W$ 做自注意力 - 但是这种特殊 Attention 不够通用,因此还没能规模做大 - 而 ViT 这篇论文就是把图像分成 $16 * 16$ 的 patch,然后直接送进 Transformer,这样就能规模化了。这个思路很简单,之前也有人做过,但区别在于 ViT 团队更有钱,之前那篇工作只在 CIFAR-10 上做了 $2 * 2$ 的 patch - 结果:在同等规模下,ViT 比 ResNet 还是弱不少,因为少了归纳偏置(inductive bias)即人为结构性先验知识(比如卷积的 locality 和 translation equlity);但是在大规模下能比 ResNet 相当或更强 - *相关工作*章节里还涉及到其它的一些,这里就不展开了 == 方法 - 模型总览图 - 把图片切成 patch,过一个全连接层,然后加上(相加而非连接)可学习的 position encoding - (借鉴 BERT)加了个 extra token - 然后送进 Transformer Encoder,用这个 extra token 输出的特征过一个 MLP 来做分类 #fig("/public/assets/Reading/limu_paper/ViT/2024-09-23-23-21-08.png") - Positional Encoding: 1d, 2d, relative - 1d, 2d, relative 均可,按理说 2d 更符合图像设定,但消融实验结果差不多 - 1d 位置编码:图上画的是 1234 这种数字,但实际上类似于一个表,每个对应一个 $D$ 维向量 - 2d 位置编码:横纵坐标各用 $D/2$ 的向量表示,然后 concat 起来 - 相对位置编码:顾名思义用相对位置查表 - 如何分类 - 以前的 CNN 都是得到多个通道的特征图之后,做个 global average pooling 得到一个向量,然后预测特征,这里其实也可以这么做 - 这里采用 BERT 那种额外 `<cls>` 的方法,其实效果都差不多,不过作者为了更接近原始 Transformer 用了这种方式(不想让人觉得效果好是针对 CV 的某些 trick 带来的) - 关于 fune-tune - transformer 是可以微调变长数据的,但是 ViT 由于用了学习的位置编码,这导致如果 patch size 不变的话,序列长度变化会使得位置编码不够用了,这时做个简单的上采样/差值可以一定程度解决问题 == 实验 - 几个模型与命名 #tlt( columns: 6, [Model], [Layers], [Hidden size $D$], [MLP size], [Heads], [Params], [ViT-Base], [12], [768], [3072], [12], [86M], [ViT-Large], [24], [1024], [4096], [16], [307M], [ViT-Huge], [32], [1280], [5120], [16], [632M], ) - 最重要的图:在小的数据集上 ViT 不如 ResNet,在大数据集上相近 #fig("/public/assets/Reading/limu_paper/ViT/2024-09-24-16-39-43.png") - 和 CNN 大模型比,分数都很高,而 Transformer 训练成本相对低一些 #fig("/public/assets/Reading/limu_paper/ViT/2024-09-24-16-55-39.png") - 自监督实验 - 遮住某个 patch 去预测 - 效果还可以,但比有监督预训练还是差了不少。后来 MAE 使用自监督来训练 ViT 效果非常好 == 结论 - 和其它 self-attention in CV 的工作不同:除了将图片转成 $16 * 16$ patches + 位置编码之外,没有额外引入图像特有的 inductive bias。好处是不需要对 vision 领域的了解,不需要 domain knowledge - NLP 中大的 Transformer 模型使用*自监督*预训练,ViT 做了简单的 initial experiments 证明自监督预训练也不错,但和有监督训练 still large gap - 挖坑 - 新模型 ViT,Transformer 成为 CV 领域的一个通用的骨干网络(backbone) - 新问题 —— Transformer for CV 除了 image classfication 其他的任务,分割、检测 - 新方向 —— 自监督的预训练方式;以及多模态,用一个 Transformer 处理 CV 和 NLP #info()[ - DETR (Carion et al. 2020) 目标检测的力作,改变了目标检测出框的方式。证明 ViT 做其它 CV 任务效果也很好 - 2020年 12 月(ViT 1.5月之后) + ViT-FRCNN 检测 detection + SETR 分割 segmentation(CVPR 论文,11.15 完成写作投稿) + (3个月后)Swin Transformer 融合 Transformer 和多尺度设计 - 作者团队自己:ViT-G,把 ViT 变得很大,把 ImageNet 刷到 $90%+$ ]
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/06_Ergebnisse/02_known_bugs.typ
typst
== Known Bugs <known-bugs> In diesem Kapitel werden die wichtigsten noch offenen Bugs beschrieben.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-marker-03.typ
typst
Other
// Test that bare hyphen doesn't lead to cycles and crashes. #set list(marker: [-]) - Bare hyphen is - a bad marker
https://github.com/SkiFire13/master-thesis
https://raw.githubusercontent.com/SkiFire13/master-thesis/master/config/printed.typ
typst
#let printed = { let input = sys.inputs.at("printed", default: "true") if input in ("true": true, "false": false) { input == "true" } else { panic("Invalid input `printed`: value must be true or false") } } #let pagebreak-to(to, weak, printed) = { pagebreak(weak: weak, to: if printed { to } else { none }) } #let pagebreak-to-right(weak: false, printed: printed) = pagebreak-to("odd", weak, printed) #let pagebreak-to-left(weak: false, printed: printed) = pagebreak-to("even", weak, printed) #let left-right-margins(page, printed: printed) = { if not printed { return (left: 3cm, right: 3cm) } if calc.rem(page, 2) == 0 { return (left: 3cm, right: 4cm) } else { return (left: 4cm, right: 3cm) } }
https://github.com/pauladam94/curryst
https://raw.githubusercontent.com/pauladam94/curryst/main/tests/README.md
markdown
MIT License
# Curryst test suite To run the tests, use ``` $ typst compile tests.typ 'test-{n}.png' --root .. ``` This will override the images. If no image changes, this means the tests passed.
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/155.%20before.html.typ
typst
before.html Before the Startup Want to start a startup? Get funded by Y Combinator. October 2014(This essay is derived from a guest lecture in <NAME>'s startup class at Stanford. It's intended for college students, but much of it is applicable to potential founders at other ages.)One of the advantages of having kids is that when you have to give advice, you can ask yourself "what would I tell my own kids?" My kids are little, but I can imagine what I'd tell them about startups if they were in college, and that's what I'm going to tell you.Startups are very counterintuitive. I'm not sure why. Maybe it's just because knowledge about them hasn't permeated our culture yet. But whatever the reason, starting a startup is a task where you can't always trust your instincts.It's like skiing in that way. When you first try skiing and you want to slow down, your instinct is to lean back. But if you lean back on skis you fly down the hill out of control. So part of learning to ski is learning to suppress that impulse. Eventually you get new habits, but at first it takes a conscious effort. At first there's a list of things you're trying to remember as you start down the hill.Startups are as unnatural as skiing, so there's a similar list for startups. Here I'm going to give you the first part of it — the things to remember if you want to prepare yourself to start a startup. CounterintuitiveThe first item on it is the fact I already mentioned: that startups are so weird that if you trust your instincts, you'll make a lot of mistakes. If you know nothing more than this, you may at least pause before making them.When I was running Y Combinator I used to joke that our function was to tell founders things they would ignore. It's really true. Batch after batch, the YC partners warn founders about mistakes they're about to make, and the founders ignore them, and then come back a year later and say "I wish we'd listened."Why do the founders ignore the partners' advice? Well, that's the thing about counterintuitive ideas: they contradict your intuitions. They seem wrong. So of course your first impulse is to disregard them. And in fact my joking description is not merely the curse of Y Combinator but part of its raison d'etre. If founders' instincts already gave them the right answers, they wouldn't need us. You only need other people to give you advice that surprises you. That's why there are a lot of ski instructors and not many running instructors. [1]You can, however, trust your instincts about people. And in fact one of the most common mistakes young founders make is not to do that enough. They get involved with people who seem impressive, but about whom they feel some misgivings personally. Later when things blow up they say "I knew there was something off about him, but I ignored it because he seemed so impressive."If you're thinking about getting involved with someone — as a cofounder, an employee, an investor, or an acquirer — and you have misgivings about them, trust your gut. If someone seems slippery, or bogus, or a jerk, don't ignore it.This is one case where it pays to be self-indulgent. Work with people you genuinely like, and you've known long enough to be sure. ExpertiseThe second counterintuitive point is that it's not that important to know a lot about startups. The way to succeed in a startup is not to be an expert on startups, but to be an expert on your users and the problem you're solving for them. <NAME> didn't succeed because he was an expert on startups. He succeeded despite being a complete noob at startups, because he understood his users really well.If you don't know anything about, say, how to raise an angel round, don't feel bad on that account. That sort of thing you can learn when you need to, and forget after you've done it.In fact, I worry it's not merely unnecessary to learn in great detail about the mechanics of startups, but possibly somewhat dangerous. If I met an undergrad who knew all about convertible notes and employee agreements and (God forbid) class FF stock, I wouldn't think "here is someone who is way ahead of their peers." It would set off alarms. Because another of the characteristic mistakes of young founders is to go through the motions of starting a startup. They make up some plausible-sounding idea, raise money at a good valuation, rent a cool office, hire a bunch of people. From the outside that seems like what startups do. But the next step after rent a cool office and hire a bunch of people is: gradually realize how completely fucked they are, because while imitating all the outward forms of a startup they have neglected the one thing that's actually essential: making something people want. GameWe saw this happen so often that we made up a name for it: playing house. Eventually I realized why it was happening. The reason young founders go through the motions of starting a startup is because that's what they've been trained to do for their whole lives up to that point. Think about what you have to do to get into college, for example. Extracurricular activities, check. Even in college classes most of the work is as artificial as running laps.I'm not attacking the educational system for being this way. There will always be a certain amount of fakeness in the work you do when you're being taught something, and if you measure their performance it's inevitable that people will exploit the difference to the point where much of what you're measuring is artifacts of the fakeness.I confess I did it myself in college. I found that in a lot of classes there might only be 20 or 30 ideas that were the right shape to make good exam questions. The way I studied for exams in these classes was not (except incidentally) to master the material taught in the class, but to make a list of potential exam questions and work out the answers in advance. When I walked into the final, the main thing I'd be feeling was curiosity about which of my questions would turn up on the exam. It was like a game.It's not surprising that after being trained for their whole lives to play such games, young founders' first impulse on starting a startup is to try to figure out the tricks for winning at this new game. Since fundraising appears to be the measure of success for startups (another classic noob mistake), they always want to know what the tricks are for convincing investors. We tell them the best way to convince investors is to make a startup that's actually doing well, meaning growing fast, and then simply tell investors so. Then they want to know what the tricks are for growing fast. And we have to tell them the best way to do that is simply to make something people want.So many of the conversations YC partners have with young founders begin with the founder asking "How do we..." and the partner replying "Just..."Why do the founders always make things so complicated? The reason, I realized, is that they're looking for the trick.So this is the third counterintuitive thing to remember about startups: starting a startup is where gaming the system stops working. Gaming the system may continue to work if you go to work for a big company. Depending on how broken the company is, you can succeed by sucking up to the right people, giving the impression of productivity, and so on. [2] But that doesn't work with startups. There is no boss to trick, only users, and all users care about is whether your product does what they want. Startups are as impersonal as physics. You have to make something people want, and you prosper only to the extent you do.The dangerous thing is, faking does work to some degree on investors. If you're super good at sounding like you know what you're talking about, you can fool investors for at least one and perhaps even two rounds of funding. But it's not in your interest to. The company is ultimately doomed. All you're doing is wasting your own time riding it down.So stop looking for the trick. There are tricks in startups, as there are in any domain, but they are an order of magnitude less important than solving the real problem. A founder who knows nothing about fundraising but has made something users love will have an easier time raising money than one who knows every trick in the book but has a flat usage graph. And more importantly, the founder who has made something users love is the one who will go on to succeed after raising the money.Though in a sense it's bad news in that you're deprived of one of your most powerful weapons, I think it's exciting that gaming the system stops working when you start a startup. It's exciting that there even exist parts of the world where you win by doing good work. Imagine how depressing the world would be if it were all like school and big companies, where you either have to spend a lot of time on bullshit things or lose to people who do. [3] I would have been delighted if I'd realized in college that there were parts of the real world where gaming the system mattered less than others, and a few where it hardly mattered at all. But there are, and this variation is one of the most important things to consider when you're thinking about your future. How do you win in each type of work, and what would you like to win by doing? [4] All-ConsumingThat brings us to our fourth counterintuitive point: startups are all-consuming. If you start a startup, it will take over your life to a degree you cannot imagine. And if your startup succeeds, it will take over your life for a long time: for several years at the very least, maybe for a decade, maybe for the rest of your working life. So there is a real opportunity cost here.Larry Page may seem to have an enviable life, but there are aspects of it that are unenviable. Basically at 25 he started running as fast as he could and it must seem to him that he hasn't stopped to catch his breath since. Every day new shit happens in the Google empire that only the CEO can deal with, and he, as CEO, has to deal with it. If he goes on vacation for even a week, a whole week's backlog of shit accumulates. And he has to bear this uncomplainingly, partly because as the company's daddy he can never show fear or weakness, and partly because billionaires get less than zero sympathy if they talk about having difficult lives. Which has the strange side effect that the difficulty of being a successful startup founder is concealed from almost everyone except those who've done it.Y Combinator has now funded several companies that can be called big successes, and in every single case the founders say the same thing. It never gets any easier. The nature of the problems change. You're worrying about construction delays at your London office instead of the broken air conditioner in your studio apartment. But the total volume of worry never decreases; if anything it increases.Starting a successful startup is similar to having kids in that it's like a button you push that changes your life irrevocably. And while it's truly wonderful having kids, there are a lot of things that are easier to do before you have them than after. Many of which will make you a better parent when you do have kids. And since you can delay pushing the button for a while, most people in rich countries do.Yet when it comes to startups, a lot of people seem to think they're supposed to start them while they're still in college. Are you crazy? And what are the universities thinking? They go out of their way to ensure their students are well supplied with contraceptives, and yet they're setting up entrepreneurship programs and startup incubators left and right.To be fair, the universities have their hand forced here. A lot of incoming students are interested in startups. Universities are, at least de facto, expected to prepare them for their careers. So students who want to start startups hope universities can teach them about startups. And whether universities can do this or not, there's some pressure to claim they can, lest they lose applicants to other universities that do.Can universities teach students about startups? Yes and no. They can teach students about startups, but as I explained before, this is not what you need to know. What you need to learn about are the needs of your own users, and you can't do that until you actually start the company. [5] So starting a startup is intrinsically something you can only really learn by doing it. And it's impossible to do that in college, for the reason I just explained: startups take over your life. You can't start a startup for real as a student, because if you start a startup for real you're not a student anymore. You may be nominally a student for a bit, but you won't even be that for long. [6]Given this dichotomy, which of the two paths should you take? Be a real student and not start a startup, or start a real startup and not be a student? I can answer that one for you. Do not start a startup in college. How to start a startup is just a subset of a bigger problem you're trying to solve: how to have a good life. And though starting a startup can be part of a good life for a lot of ambitious people, age 20 is not the optimal time to do it. Starting a startup is like a brutally fast depth-first search. Most people should still be searching breadth-first at 20.You can do things in your early 20s that you can't do as well before or after, like plunge deeply into projects on a whim and travel super cheaply with no sense of a deadline. For unambitious people, this sort of thing is the dreaded "failure to launch," but for the ambitious ones it can be an incomparably valuable sort of exploration. If you start a startup at 20 and you're sufficiently successful, you'll never get to do it. [7]<NAME>berg will never get to bum around a foreign country. He can do other things most people can't, like charter jets to fly him to foreign countries. But success has taken a lot of the serendipity out of his life. Facebook is running him as much as he's running Facebook. And while it can be very cool to be in the grip of a project you consider your life's work, there are advantages to serendipity too, especially early in life. Among other things it gives you more options to choose your life's work from.There's not even a tradeoff here. You're not sacrificing anything if you forgo starting a startup at 20, because you're more likely to succeed if you wait. In the unlikely case that you're 20 and one of your side projects takes off like Facebook did, you'll face a choice of running with it or not, and it may be reasonable to run with it. But the usual way startups take off is for the founders to make them take off, and it's gratuitously stupid to do that at 20. TryShould you do it at any age? I realize I've made startups sound pretty hard. If I haven't, let me try again: starting a startup is really hard. What if it's too hard? How can you tell if you're up to this challenge?The answer is the fifth counterintuitive point: you can't tell. Your life so far may have given you some idea what your prospects might be if you tried to become a mathematician, or a professional football player. But unless you've had a very strange life you haven't done much that was like being a startup founder. Starting a startup will change you a lot. So what you're trying to estimate is not just what you are, but what you could grow into, and who can do that?For the past 9 years it was my job to predict whether people would have what it took to start successful startups. It was easy to tell how smart they were, and most people reading this will be over that threshold. The hard part was predicting how tough and ambitious they would become. There may be no one who has more experience at trying to predict that, so I can tell you how much an expert can know about it, and the answer is: not much. I learned to keep a completely open mind about which of the startups in each batch would turn out to be the stars.The founders sometimes think they know. Some arrive feeling sure they will ace Y Combinator just as they've aced every one of the (few, artificial, easy) tests they've faced in life so far. Others arrive wondering how they got in, and hoping YC doesn't discover whatever mistake caused it to accept them. But there is little correlation between founders' initial attitudes and how well their companies do.I've read that the same is true in the military — that the swaggering recruits are no more likely to turn out to be really tough than the quiet ones. And probably for the same reason: that the tests involved are so different from the ones in their previous lives.If you're absolutely terrified of starting a startup, you probably shouldn't do it. But if you're merely unsure whether you're up to it, the only way to find out is to try. Just not now. IdeasSo if you want to start a startup one day, what should you do in college? There are only two things you need initially: an idea and cofounders. And the m.o. for getting both is the same. Which leads to our sixth and last counterintuitive point: that the way to get startup ideas is not to try to think of startup ideas.I've written a whole essay on this, so I won't repeat it all here. But the short version is that if you make a conscious effort to think of startup ideas, the ideas you come up with will not merely be bad, but bad and plausible-sounding, meaning you'll waste a lot of time on them before realizing they're bad.The way to come up with good startup ideas is to take a step back. Instead of making a conscious effort to think of startup ideas, turn your mind into the type that startup ideas form in without any conscious effort. In fact, so unconsciously that you don't even realize at first that they're startup ideas.This is not only possible, it's how Apple, Yahoo, Google, and Facebook all got started. None of these companies were even meant to be companies at first. They were all just side projects. The best startups almost have to start as side projects, because great ideas tend to be such outliers that your conscious mind would reject them as ideas for companies.Ok, so how do you turn your mind into the type that startup ideas form in unconsciously? (1) Learn a lot about things that matter, then (2) work on problems that interest you (3) with people you like and respect. The third part, incidentally, is how you get cofounders at the same time as the idea.The first time I wrote that paragraph, instead of "learn a lot about things that matter," I wrote "become good at some technology." But that prescription, though sufficient, is too narrow. What was special about <NAME> and <NAME> was not that they were experts in technology. They were good at design, and perhaps even more importantly, they were good at organizing groups and making projects happen. So you don't have to work on technology per se, so long as you work on problems demanding enough to stretch you.What kind of problems are those? That is very hard to answer in the general case. History is full of examples of young people who were working on important problems that no one else at the time thought were important, and in particular that their parents didn't think were important. On the other hand, history is even fuller of examples of parents who thought their kids were wasting their time and who were right. So how do you know when you're working on real stuff? [8]I know how I know. Real problems are interesting, and I am self-indulgent in the sense that I always want to work on interesting things, even if no one else cares about them (in fact, especially if no one else cares about them), and find it very hard to make myself work on boring things, even if they're supposed to be important.My life is full of case after case where I worked on something just because it seemed interesting, and it turned out later to be useful in some worldly way. Y Combinator itself was something I only did because it seemed interesting. So I seem to have some sort of internal compass that helps me out. But I don't know what other people have in their heads. Maybe if I think more about this I can come up with heuristics for recognizing genuinely interesting problems, but for the moment the best I can offer is the hopelessly question-begging advice that if you have a taste for genuinely interesting problems, indulging it energetically is the best way to prepare yourself for a startup. And indeed, probably also the best way to live. [9]But although I can't explain in the general case what counts as an interesting problem, I can tell you about a large subset of them. If you think of technology as something that's spreading like a sort of fractal stain, every moving point on the edge represents an interesting problem. So one guaranteed way to turn your mind into the type that has good startup ideas is to get yourself to the leading edge of some technology — to cause yourself, as Paul Buchheit put it, to "live in the future." When you reach that point, ideas that will seem to other people uncannily prescient will seem obvious to you. You may not realize they're startup ideas, but you'll know they're something that ought to exist.For example, back at Harvard in the mid 90s a fellow grad student of my friends Robert and Trevor wrote his own voice over IP software. He didn't mean it to be a startup, and he never tried to turn it into one. He just wanted to talk to his girlfriend in Taiwan without paying for long distance calls, and since he was an expert on networks it seemed obvious to him that the way to do it was turn the sound into packets and ship it over the Internet. He never did any more with his software than talk to his girlfriend, but this is exactly the way the best startups get started.So strangely enough the optimal thing to do in college if you want to be a successful startup founder is not some sort of new, vocational version of college focused on "entrepreneurship." It's the classic version of college as education for its own sake. If you want to start a startup after college, what you should do in college is learn powerful things. And if you have genuine intellectual curiosity, that's what you'll naturally tend to do if you just follow your own inclinations. [10]The component of entrepreneurship that really matters is domain expertise. The way to become Larry Page was to become an expert on search. And the way to become an expert on search was to be driven by genuine curiosity, not some ulterior motive.At its best, starting a startup is merely an ulterior motive for curiosity. And you'll do it best if you introduce the ulterior motive toward the end of the process.So here is the ultimate advice for young would-be startup founders, boiled down to two words: just learn. Notes[1] Some founders listen more than others, and this tends to be a predictor of success. One of the things I remember about the Airbnbs during YC is how intently they listened.[2] In fact, this is one of the reasons startups are possible. If big companies weren't plagued by internal inefficiencies, they'd be proportionately more effective, leaving less room for startups.[3] In a startup you have to spend a lot of time on schleps, but this sort of work is merely unglamorous, not bogus.[4] What should you do if your true calling is gaming the system? Management consulting.[5] The company may not be incorporated, but if you start to get significant numbers of users, you've started it, whether you realize it yet or not.[6] It shouldn't be that surprising that colleges can't teach students how to be good startup founders, because they can't teach them how to be good employees either.The way universities "teach" students how to be employees is to hand off the task to companies via internship programs. But you couldn't do the equivalent thing for startups, because by definition if the students did well they would never come back.[7] <NAME> was 22 when he received an invitation to travel aboard the HMS Beagle as a naturalist. It was only because he was otherwise unoccupied, to a degree that alarmed his family, that he could accept it. And yet if he hadn't we probably would not know his name.[8] Parents can sometimes be especially conservative in this department. There are some whose definition of important problems includes only those on the critical path to med school.[9] I did manage to think of a heuristic for detecting whether you have a taste for interesting ideas: whether you find known boring ideas intolerable. Could you endure studying literary theory, or working in middle management at a large company?[10] In fact, if your goal is to start a startup, you can stick even more closely to the ideal of a liberal education than past generations have. Back when students focused mainly on getting a job after college, they thought at least a little about how the courses they took might look to an employer. And perhaps even worse, they might shy away from taking a difficult class lest they get a low grade, which would harm their all-important GPA. Good news: users don't care what your GPA was. And I've never heard of investors caring either. Y Combinator certainly never asks what classes you took in college or what grades you got in them. Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Arabic Translation
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-AC00.typ
typst
Apache License 2.0
#let data = ( "0": ("<Hangul Syllable, First>", "Lo", 0), "2ba3": ("<Hangul Syllable, Last>", "Lo", 0), )
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/resources/typst/reproducibility-rule.typ
typst
Other
#{ set text(font: "Virgil 3 YOFF") image("../../resources/images/rules.svg", fit: "stretch") v(-1.5em) grid( columns: (1fr, 1fr, 1fr), { set align(left) "Not reproducible" }, { set align(center) "Partially reproducible" }, { set align(right) "Reproducible" }, ) v(2em) }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-27.typ
typst
Other
// Error: 3-4 unknown variable: z #(z = 1)
https://github.com/marcothms/clean-polylux-typst
https://raw.githubusercontent.com/marcothms/clean-polylux-typst/main/presentation.typ
typst
#import "theme.typ": * #show: presentation.with( author: [Sample Author \<<EMAIL>\>], title: [Sample Title], occasion: [Sample Occasion], date: [01.01.1970], logos: ("figures/typst.svg", "figures/polylux.png", "figures/ferris.png"), logo_height: 40%, footer: [This is a really cool footer], ) #section("My Section") #slide(title: "My Title")[ #grid( columns: (50%, 50%), [ - #lorem(10) - #lorem(10) - #lorem(10) - #lorem(10) ], image("figures/ferris.png") ) ] #focus-slide()[ We need to focus now... ] #slide(title: "Some code!")[ #figure( sourcecode(```rust enum Foo { Bar1(Box<Foo>), Bar2(String), } ```), caption: [Some awesome Rust!] ) ]
https://github.com/BreakingLead/note
https://raw.githubusercontent.com/BreakingLead/note/main/Misc/教程/教程.typ
typst
#set text(font: ("New Computer Modern", "Source Han Serif")) #set page( paper: "a4", header: align(left)[ #rect(stroke: (bottom: 0.05em))[ Orchiectomy by Yourself ] ], numbering: "1/1", ) #set par( justify: false, leading: 0.45em, ) #set heading(numbering: "A 1") #set quote(block: true) #show quote : it => { set text(font: "Z<NAME> (technical preview)") rect(fill: luma(90%), stroke: (left: 0.25em))[ #it ] } #align(center, text(20pt)[ *自切教程* ]) #align(center)[ twitter@ Breaking_Lead_G \ #link("<EMAIL>") \ #link("https://github.com/BreakingLead") ] #align(center)[ #block(width: 70%)[ *摘要* \ 本文介绍了自行切除睾丸的后果,准备工作,手术过程与手术后的处理。并附带了个人的心得体会和实践经验。 Changelog: v1.0\@2024/6/21 #text(fill: red.darken(50%), size: 1.5em)[*看之前先问自己一个问题:这一切值得吗?*] ] ] #columns[ = 准备工作 免责声明:本教程仅供学习交流使用,请勿进行文中的操作,由擅自操作引起的一切后果本人概不负责。 == 一些忠告 + 「只要我怎么样,一切都会好的」是最愚蠢的错觉。 + 由上,如果你不是实在没有钱HRT(标准是现存款不到300元且无能力自行赚钱),切勿自切。 + 不要以自切作为对抗亲人的资本。这是十分愚蠢的。自己默默切了就好了。 + 也不要拿这个博关注。 + 再重复一遍「只要我怎么样,一切都会好的」是最最最愚蠢的错觉。你切了达不到效果还是会GD。 + 显然这事没那么好受。。若你完成的十分成功也就罢了,像我一样进医院的话,花的两千多够HRT几年了。 + 真打算干的话做好觉悟。别到时候往睾丸里打几针都不敢。 == 术前采购单 + 头孢拉定/左氧氟沙星等抗生素至少买1个月的量防止术后感染。 + 止血钳弯头2把。 + 手术剪直头1把。 + 持针器1把,医用镊1把。 + 2-0或3-0可吸收缝合线线束(要多!),如果你有钱,最好用4-0的薇乔线。 + 1/2圆的手术缝合针若干,不建议太少,原因见下。 + 盐酸利多卡因至少20个0.1g/5ml的安瓿。这么多的原因是血的教训。(我没缝好里面,但发现麻药不够了只能去医院。) 别问我怎么搞到的,我用的是兽药,据说和人用的产线是一致的。但使用后果自负。 + 无菌手套若干(这个的前提是你觉得你能保持全过程无菌,但我认为99%的人都做不到(我自己没做到,见下),所以你可以不买。我为了完整性写上了) + 砂轮一个用来开安瓿。 + 1瓶75%医用酒精,6瓶以上0.9%生理盐水洗液。1瓶碘伏,1瓶双氧水。 + 4号手术刀,若干手术刀片。 + 金属托盘或其等价物。 + 锅,用来煮沸消毒。 + 5ml一次性注射器若干。配 25G x 5/8 (0.5 × 16 mm)(橘色)针头。 + 50ml或更大号注射器若干用来冲洗, + 10cmx10cm纱布块若干(至少20块),不建议太少。 + 医用胶带若干。用来固定阴茎和术后固定纱布。 + 棉球若干。 + 无菌手术单,面积记得大一些。 + 用来练习缝合的假皮。 + 葡萄糖口服液,或含糖饮料几瓶。 + 用来备皮的剃刀。 + 若你足够有钱,可以买一把能止血的高频电刀,但是你都有那个钱了,正常HRT不好吗... 除经济实在困难或备注,不建议省略任何一项。 == 后果 双侧睾丸切除术会大大降低睾酮水平 @wiki。这可以导致: + 性兴趣丧失 + 勃起功能障碍 + 潮热 + 乳房增大 + 体重增加 + 肌肉质量下降 + 骨质疏松症。 + 减少跨性别女性外源性药物的使用 = 练习 首先去大量地学习并练习外科学基础知识,主要有如下几点,B站上资料很多。 + 外科结(食指,中指)结的打法。 + 血管结扎方法。 + 单纯间断缝合,单纯连续缝合。 + 皮下注射的方法。 + 无菌相关操作。 + 外生殖器与泌尿系统的构造。 + 其他常识。 记住其中最重要的莫过于缝合与血管结扎方法,这两项极大影响你的成功概率,请务必多加练习。 #figure( caption: [外生殖器], )[ #image("构造.png") ] == 注意事项 首先,在手术的时候,不可避免地会见很多血的。可以说是血流成河,所以你的手肯定会止不住的抖,这是人体的本能控制的,基本上不可能避免(除非你够自信能用意志战胜本能)。在手术进行途中的时候,你肯定会有一种十分绝望的感觉,因为你可能会发现事情并不像你想的那么顺利。这时,请停下手中的工作,多次深呼吸以保持冷静。若你实在无法冷静,请立刻寻求医疗帮助!本人就是因为没有第一时间去医院,想着「先忍忍」,导致了伤口情况变糟,最终多花了不少钱。 因此,在手抖的情况下缝合是极难的,特别是缝合精索,因为精索是个圆柱体,并且很难固定。所以我建议如果无法持用持针器的情况下不要硬撑请直接用手进行操作。(这也是为什么你很难做到无菌) == 方法参考 这是不同的结形成的样子,一般我们结扎精索用外科结(先食指后中指节)就可以了。注意:外科结比方结多绕了一圈所以比较紧。打第一个结绕两次,使缝合线间的摩擦力增大,打第二个结时就不易滑脱和松动,比较可靠。 在打结过程中,常产生的错误有假结和滑结两种。两手用力不均,易形成滑结;打结方向错误,易形成假结。这两种一挑就开了,所以多练。 #figure( caption: [不同的节 @suture], )[ #image("节的类型.png") ] 这是食指节的打法: #figure( caption: [食指节], )[ #image("食指.png") ] 这是中指结的: #figure( caption: [中指节 @knot], )[ #image("中指.png") ] 剪线在不引起结扎线松脱的原则下,线头愈短愈好,以减少组织的异物反应。三字诀:*滑靠斜*。 #figure( caption: [剪线方法], )[ #image("滑靠斜.png") ] 单纯间断缝合的节的话,记住这句话即可:*钳压线绕两圈,线压钳绕一圈*。 #figure( caption: [持钳打结], )[ #image("持钳打结.png") ] *注意* + 结扎之前,需将束线在生理盐水中浸湿,然后再进行结扎,以增加线的重量,便于操作,并增加摩擦力,使线结牢固。 + 在收紧线结时,两手用力均匀,如果一手松一手紧,易形成滑结。 + 无论用哪种打结方法,相邻两个节的方向必须相反,否则易打成假节而松动。 + 打结时,每个方结的第一个单结与第二个单结方向不能相同,否则就成假结,容易滑脱。两手用力应均匀,否则亦可成为滑结,应避免。深部打结时用一个手指按压线结附近,逐渐拉紧,要求两手用力点与结扎点成一直线。即三点一线,不可成角或向上提起,否则易组织撕脱或线结松脱。 == 麻醉 利用利多卡因进行局部浸润麻醉。 将局麻药沿手术切口分层注射于手术区的组织内,阻滞组织中的神经末梢,称为局部浸润麻醉。 操作时,在拟定手术切口一端进针,针头斜面紧贴皮肤,进入皮内以后推注局麻药液,形成橘皮样皮丘,自此皮丘继续向前推进同时浸润注射至切口全长,再向皮下组织逐层注入局麻药。 #table( columns: 4, table.header( [],[浓度(%)],[最大剂量(mg)],[持续时间(min)] ), [普鲁卡因],[0.5-1.0],[800],[15-30], [氯普鲁卡因],[1.0-2.0],[800],[15-30], [利多卡因],[0.5-1.0],[300],[30-60], [甲哌卡因],[0.5-1.0],[300],[45-90], [丙胺卡因],[0.5-1.0],[500],[30-90], ) = 进行手术 这部分内容将会用过程+点评的形式呈现。点评就是我个人当初踩到的坑,请务必认真对待。 == 术前 洗个澡,建议用温水避免着凉。进行排便和排遗工作。服用一些抗雄药物以防勃起。 然后给你最信任的人备好联系方式以防万一(其实不是万一,有很大的几率你会失败。) 将会阴部位用刮刀刮毛,用碘伏消毒之后用盐水擦去,不要伤到皮肤。 接下来平复一下心情,首先,如果你没有别人陪同做手术的话,一定要事先有一位紧急联系人帮你在紧急情况(可以找我),不要像我一样因为没有手机导致了一些无趣的后果。 开水煮沸止血钳,手术剪,持针器等用品,将上述用品分类摆到铁盘中备用,将床上铺好手术单。记住不要在软床上操作,不然容易将东西搞得到处都是。设置30分钟响一次的倒计时闹钟提醒自己时间流逝。 用砂轮开安瓿,抽15瓶以上的利多卡因放在一端备用。用大号注射器抽几管生理盐水用作冲洗,拔掉针头便于操作。 拿一个小盒子,*提前把针穿好线!* 至少穿10个带线的针。将束线在生理盐水中浸湿。 #quote[ 为什么要用大号注射器?因为当时我用一个型号的,结果搞混了麻药和盐水的注射器,导致白白浪费了两管麻药,这也为之后手术的失败埋下伏笔。 为什么要这么多利多卡因?因为你很容易浪费很多药。 千万要再三确认所有的东西都备齐了再开始手术,否则你会像我一样,中途下床一手托着悬在外面挂着的血淋淋的睾丸一边找生理盐水。孩子,这并不好笑。 还有好好分类整理好手术用品,千万不要像我一样把盐水当麻药,把止血钳当持针器。注意,把止血钳当持针器是十分危险的!针容易崩到别处,万一扎到自己就不好了。 PS: 利多卡因是很苦的,所以如果你真的把它与什么弄混了的话可以用我的这个笨办法... Switch 卡带的那个苦味剂似乎就是利多卡因的衍生物。 ] 找一支碳素笔,在你的阴囊缝左右2mm处标记一道2cm长的线,不要直接划到阴囊缝,最好避开大血管。 #quote[ 注意,宜短不宜长。不要觉得2cm太短,依我经验够用了。而且你现在划的越大,一会缝合越麻烦。 ] 现在,用医用胶带好好固定好你的阴茎,最好不要让它中途脱落,你没时间重新固定的。 #quote[ 万一它中途脱落了你会很像我一样很慌,这种慌乱感是比高考考前还可怕的感觉,高考你考一会就像往常的模考一样进入状态了。但是这里你可没有模考,你*必须*在毫无经验的情况下一次成功,可想而知这会让人有多大压力。再说一遍,*千万不要高估自己的心理承受能力,一定要做好最坏的打算*。但是*手头的事情不能停*,一样照做。多多深呼吸平复心情。 我建议你有钱的话,直接去祼考个雅思口语,不许备考(前提是你口语水平和我一样,我说中文都结巴,英语可想而知)。你就明白那种感觉了。 ] == 术中 *麻药注射* 在划线区域的皮下注射麻药。注意注射的方式:少量多次多点位,注射器在肉里面多转几圈,不要怕痛。下手要快准狠,不要磨叽一直不敢注射,你既然看到这说明你都做好了觉悟了。所以,直接斜20度快速进针多次给此处皮肤注射。每个占位注射到皮肤将将鼓起(类似于做皮试的那个包一样)的程度为宜。 此时测试开口处还有没有痛感,若有的话继续 #figure( caption: [注射点位示意], )[ #image("注射.svg") ] #figure( caption: [皮肤@orchi], )[ #image("皮肤.png") ] 接下来先别急着开刀,还要在两侧精索和睾丸里注射各1ml麻药。精索自己捏一捏感受一下位置。由于阴囊内有一层膜质地较硬的膜,所以下手要更快,更准,更狠,再说一遍,*切忌磨磨叽叽*,直接捏住睾丸快速一打就完事了。注射完毕后可能有少量渗血,这是无关紧要的。但是大量出血请立刻包扎并寻求医疗救助。 @sf #figure( caption: [精索注射], )[ #image("精索注射.png") ] #quote[ 什么?你说向睾丸里注射痛不痛?废话,当然痛。我当初因为扎偏都痛得差点想要放弃了。但是那种痛苦比起 GD 的痛苦孰优孰劣,你需要自行斟酌。 不过,正确操作的痛苦还是在忍受范围内的,但是在睾丸里注射确实会有一种蛋被什么东西打了的那种特殊的痛感。要形容的话和打破伤风的痛感差不多或更胜一筹。 ] *切开阴囊* 然后,用手术刀(注意手术刀不能用热水消毒不然会变钝)切开你画的那条缝。这时你应该感觉不到什么痛感,否则你可能需要补一些麻药。之后你也可以随时在痛的地方补一些麻药。 #figure( caption: [阴囊切开], )[ #image("阴囊切开.png") ] 切开的力道需要适中,此时最容易犯的错误就是切得太浅或太深。切开表皮后,有适量出血是正常现象(只要不切到什么动脉,撑一会还是没事的)。注射麻药不用我多说,你哪里痛打哪里就好。 *分离睾丸* 这时请用手将一侧睾丸挤到那条缝处,然后用力切开睾丸表面的那层膜(*一定要切透*),把睾丸连同精索拉出来。(我先切的是右侧)。 #quote[ 记得一定要切完那层膜! 那层膜挺厚的,我切完第一个蛋的时候是正常切除的,但是切到第二个的时候犯蠢,竟然没把那层膜完全切透! 所以一直拉不出精索,还不知为何打了麻药精索也十分地疼痛。后来反咉过来切了就不痛了。 这里还有个小插曲,因为出血有点多,所以我想拿盐水冲一冲,结果发现在几米外的桌子上够不到,所以我只好一手拿着我的挂在外面的睾丸一手站起来去拿盐水... ] 拉出来后痛的话给精索补麻药,然后*把精索外面的膜切开*,切记不要直接弄断了精索。 #quote[ 我这里因为紧张,忘记了切开膜,直接用止血钳把整个精索全夹住了。结果把精索压扁成了一个2cm宽的扁圆形,我当时缝合的时候心说不对呀怎么精索这么大!然后就没缝好,结果呢?精索在我缝完外边之后里面还在出血。之后阴囊肿得和拳头一般大。就是这个失误让我住了四天医院。 ] *剪断精索* 然后用四个止血钳(其实两个就行,但是为了保险多一些)夹住你将要剪下的精索的两侧,此时精索应该能被完全夹住,如果不能(或你感觉夹住时很痛),请检查到底划开精索外面那层膜没有。 这个时候你的手基本上必然会非常地抖。所以多多深呼吸。 #figure( caption: [精索的两半], )[ #image("两半.png") ] 然后直接用手术剪沿着止血钳外侧5mm(也可以更大,给自己留足够的空间)处将睾丸剪下。并把精索用*2-0的丝线*结扎好。你很有可能发现自己手过于抖没法使用持针器,这时果断用手将精索断端结扎,打1-3个外科结再重复结扎一次以防出血! #figure( caption: [精索结扎], )[ #image("精索结扎.png") ] #quote([ 这一步说得轻巧,实际上是最难的一步!比最后缝合阴囊重要的多也难得多!这步直接关系到你手术之后会不会有内出血之类的情况,所以还是老生常谈地:多练,多练,多练。 ]) 缓缓松开止血钳,剪掉线头。拿着精索断端检查有无大量出血。如果还是有出血,那么再好好地把精索结扎好。 然后在对侧进行同样的操作。用手将对侧睾丸挤到开口处,划开睾丸外的膜。划开精索外的膜。用生理盐水冲洗。若有痛感补麻药。 此时你若出血有点多,头晕是正常现像,请喝一些含糖饮料(这个时候你就别怕不健康了...),多次深呼吸,平复一下紧张的心情。也可以用盐水清洗一下周围的血迹。整理一下工作台面。在5分钟内无大量出血就可以准备缝合阴囊切口了。 #quote[ 你可能因为手忙脚乱浪费掉大量的麻药,这就是为什么我让你多备一点的原因。 还有个原因就是如果你把切口缝合了又发现精索没缝好。(个人亲身经历),那么你就需要重新打开阴囊缝合。 但是你现在又没麻药了,相当于骑虎难下,开也不是,不开也不是。这真令人遗憾。你只能去医院了。 ] *缝合阴囊切口* 将精索塞到腹股沟处,不要让腹股沟的什么东西掉下来搞成疝气。 若掐一把创口处发现创口还痛,给创口补一些麻药(仍然是少量多次多点位)。 然后捏住切口使其不要内翻,用持针器夹起早已准备好的缝合针,穿过皮肤创口进行单纯间断缝合,用*4-0的可吸收线*(不可吸收的也行,但是需要两周后拆线),每缝一针单独打结。缝完后“滑靠斜”剪线。你应该此时非常熟悉如何缝合了。否则还是打120吧。 #figure( caption: [阴囊切口], )[ #image("外部缝合.png") ] 缝合完毕后,什么都不要做,密切观察伤口处有无出血情形,或异常现象。若没有的话,用盐水和双氧水彻底将皮肤冲刷干净,并用纱布将创口处包好,取下固定阴茎的胶带。 之后就平躺下休息吧。注意不要盖被子也不要让什么脏东西碰到伤口,请垫着手术单不要取下。 == 术后 至此,手术算是做完了,不知你做到这里有什么感想。反正当时的我是因为疼痛和头晕没什么感想。 你若担心睾丸还活着,可以将其泡在酒精里破坏。 *术后当天* 躺在床上什么也不要做,不要去收拾工具和血迹,记录下当前时间以便之后有什么意外,以便医生要询问创伤时间。刷手机就可以了,没有手机的看看书也行。 待利多卡因效果过了之后,阴囊特别是精索会有一些可以忍受的胀痛感,如果疼痛没有到无法忍受的地步,不要服用*中枢性止痛药*,例如普瑞巴林,阿片类药物等。可以服用一些*非甾体类止痛药*,如阿司匹林,布洛芬等,对乙酰氨基酚等。 之后服用一些抗生素,如头孢拉定,左氧氟沙星等。注意之后的两周每天都要按说明书的量服用抗生素。 当伤口出现感染征候,如发红、肿胀、疼痛、分泌物、发烧等,应立即去医院检查。保持伤口敷料清洁干燥,伤口不可碰到水。 *术后3天内* 不要吃太硬的食物,不要吃辛辣的食物,最好吃流食。也最好不要吃太多,尽可能减少排遗次数。排遗后记得换药防止感染。 每天用碘伏擦一遍创口。然后更换新的敷料。不要进行运动,不要使阴茎意外勃起。有意外情况请就医。 *两周后* 若没什么感染的迹像,就可以不用吃抗生素了。若你缝合表皮时用的是不可吸收线,那可以去当地诊所拆个线。也可以服用雌激素了。 *之后的一切* 这一切都已经结束了,开启你的新生活吧 。 ] #pagebreak() #align(center)[ #set text(size: 20pt) *后记 The Dark Side of The Moon* #grid( columns: (1fr,1fr), row-gutter: 5pt, [ #image("D.png", width: 95%) ], [ #image("C.png", width: 95%) ], [ #image("story.png", width: 95%) ], [ #image("A.png", width: 95%) ], ) ] 纵观我的生活(亦或生命),如同一坨打结了的耳机线,是一团纷乱如麻的矛盾、痛苦与希望的结合体。何以如此痛苦与矛盾?这正是“想得太多,做得太少”。但令我最悲伤的是,我或许明白这些道理,却无法跳出一层一层的递归性思考的陷阱。 矛盾便是我的懦弱、自视甚高与眼高手低。我时常想先验地怀有“明天会比今天好”的执念。却又思考着“若我已经知道这只是为了麻痹我的痛苦,而为我自己设置的谎言,那我设立这种执念还有什么意义?”。想要骗过自己,何尝容易?有人说你的痛苦其实都是“在家里待太久,吃饱了没事干”,我其实同意这种说法。可是我或许认为“在家里待太久”就是比在外面打工舒服呀!我宁愿在家一辈子,我也宁愿自杀呢。还有一种观点是,“痛苦都是人脑主观意愿产生的,你的(趋利避害的)目的先于你痛苦的本质”(来自《被讨厌的勇气》@courage,不知道我理解的对不对)我也同意呀,问题是你这种话,说了和没说一样。这话的本质就是说“你说你赢了,你就赢了”,和精神胜利法没差。问题是大多数别人可不认为你赢了呀!这是最大的矛盾。我有时想,我要是不想这么多,只专注于做事,是不是就没有这么多痛苦了。但是这也就是想想。你做不到。 #quote(attribution: [銀河鉄道の夜 @ginga])[ 康帕瑞拉却抢先说道:“可惜,大家虽然拼命追,但还是没赶上这趟列车。查内力跑在最前头,仍然追不上。” ] 我常常想,“只要我有了XXX,一切都会好起来的”。但是现实的惨痛教训无时无刻不在提醒我,这是一个巨大的谎言。我考上了全国前中的以前想都不敢想的高中,情况变得更好了吗?没有,我的精神情况还变得更差了。我找到了一个或许爱我的人,情况变得更好了吗?没有,我却更加痛苦了。我熬了那么久出了ICU,终于能开启新生活了吗?不能,我只是沉沦在噩梦里。我自己都切除了我的生殖器官,我会不焦虑了吗?没有。难道是我对自己的要求太高了吗?并不高呀,因为,我明明是擅长欺骗自己,安慰自己很厉害的呀。不过已经知道自己在“欺骗自己”,那么,还算在欺骗自己吗? 我不相信梦是假的。 所有我的矛盾,都转移成我对自己和他人的谩骂与嘲弄。辟如 #quote[ 最好不要让我看到你想死了,你想死就去死好了,没有人在乎你死不死。你发出来看是作秀给谁看呢? 你自己都不想改变,凭什么要求别人帮你? 人家给我钱我不要,为什么?因为我还想从中获得一种廉价的满足感,欺骗自己「我真是个大善人!」哈哈。 ] 我是真心希望我这种人愈来愈痛苦的。他们懦弱,又喜欢欺骗自己,而且不是平庸的恶,他们是有意想让这个世界变得更差,拉着别人陪葬的。 在写这些话的时候,我又不禁在想我为什么写它们呢?是为了博取同情吗?也不是吧,我的心已经彻底凉了。是为了安慰自己?我又有什么好安慰的。啊,我明白了,原来是我既要想当婊子又想立牌坊。既想博取同情,又不想产生罪恶感呀。这段话也是这个meta游戏的一环,好显得我的感情是真实的没有在愚弄你们。但实际上这一切都是我精心布好的局。这句话也是我增加真实性的手段吗?我不知道。这是个你我之间的猜疑链。话虽如此,其实你完全不用去想也不会有任何后果,你我之间只是陌路人。我也不会给你一分钱去看我的这些梦呓。 我以前想过,我若是放下这一切,专门去卖惨骗钱,那样我还能更快乐一点,至少会有人在评论区用他们廉价的文字假装安慰一下我,抱抱我,我的心里怎么能不感到一丝温暖,即便他们唯一做的事就是打几个毫无成本的字。但他们永远没给过我一分钱。相比之下,只有父母才会给我生命的资本,没有他们,我也无法生存。 可是那些没有什么成本的“爱”,那种廉价的同情却比那种严厉的爱更能让我看到生活的希望。可是我已经选择吃下了红色药丸,再也回不去那抓住一点爱就不撒手的阶段了。这不是变成熟了吗?可是为什么我的成熟,会带来这么多痛苦。我羡慕能欺骗自己的人,他们是幸福的。 那书认为,如果你是曾经去过井外的井底之蛙,只要不去想井外的广阔世界,仍然能活得很好。这也太不人道了,现实中选择蓝色药丸,你的记忆也不会消除呀。 我其实最想要的,就是有一个能爱我的人,但是我永远不敢跟任何人说“我爱你”,因为我被伤害得不敢说了。别人若对我说“我爱你”,我也会一口回绝,好让我看起来是个冷血的人。那么,我到底是想要有人爱我呢,还是不想要有人爱我呢?原来,我只是想当婊子又想立牌坊罢了。我只想不劳而获。想让别人死缠烂打地追求我,以产生一种愚弄他人的快感... 但是,我说了这么多,我或许自己也不怎么相信以下惊人的事实:我没有选择去死,也没有去「杀死我自己」。 我只是感到悲哀。我是个乐观的人,但是感到悲哀。 多一点爱好了。只要世界上多一点爱,便有一个人多了一分希望。 #align(center)[ #par(justify: false)[ #text(fill: red.darken(50%), size: 1.5em, font:"Zhuque Fangsong (technical preview)")[ *回答* 卑鄙是卑鄙者的通行证, 高尚是高尚者的墓志铭,\ 看吧,在那镀金的天空中, 飘满了死者弯曲的倒影。 冰川纪过去了, 为什么到处都是冰凌?\ 好望角发现了, 为什么死海里千帆相竞? 我来到这个世界上, 只带着纸、绳索和身影,\ 为了在审判之前, 宣读那些被判决了的声音。 告诉你吧,世界,\ 我——不——相——信! 纵使你脚下有一千名挑战者, 那就把我算做第一千零一名。 我不相信天是蓝的, 我不相信雷的回声,\ 我不相信梦是假的, 我不相信死无报应。 如果海洋注定要决堤, 就让所有的苦水都注入我心中,\ 如果陆地注定要上升, 就让人类重新选择生存的峰顶。 新的转机和闪闪的星斗, 正在缀满没有遮拦的天空。\ 那是五千年的象形文字, 那是未来人们凝视的眼睛。@answer ]]] 我以此诗结束这篇将近万字的教程,在写这篇教程的时候,我很开心,因为我想或许我能帮到一些和我一样没钱的人去做真正的自己。但是我仍然想提醒你,做。我不建议18岁以下的人擅自决定(尽管我才16岁...)。还是跟父母说说比较好。说不定你是家长党呢? 请忘掉上面的那些偏激的文字吧。我想说的是,假若你真正相信什么东西,那么就为了它而奋斗。 如果你的父母对你真的很不好,也不要去怪他们。仇恨是痛苦的一个源头。不要去伤害自己以报负任何人。努力提升自己的人格便是最好的“报负”。若你一直持着这种想法,你会最终和你的执念与不甘和解的。如果你五六十岁了,你觉得那时的你还会去怪他们吗? 希望大家以后不要烦恼,顺顺利利,平平安安。找到自己喜欢做的事,即使流浪街头,吃不起饭,也要有一颗坚强的心。这些苦难将会成为你日后宝贵的回忆。还有,请多去帮助那些深陷泥沼的人吧。这样不管怎么样,请你相信,都能达到真正的幸福的。 #quote(attribution: [銀河鉄道の夜 @ginga])[ “何为幸福,我也搞不清。其实,无论多么痛苦的事,只要能正道直行,即使赴汤蹈火,也能一步步接近幸福。” ] = 附录 我在住院期间读的一些书: - _银河铁道之夜_ @ginga - _The Dark Forest_ @body - _铸剑_ - _Flowers for Algernon_ @algernon - _妙法莲华经_ - _心经_ - 炎拳 尽管不想承认,但是我很缺钱,我的父母好像现在也不知道双低不好,还是不给我买药(尽管我有大证...)。若这篇文章对你有帮助的话,请给我的B站充电,或者联系我资助我一些HRT药物。我没有手机,只能这样了。 #link("https://space.bilibili.com/34258013") #bibliography( "refs.yml", full: true, )
https://github.com/jinhao-huang/SimplePaper
https://raw.githubusercontent.com/jinhao-huang/SimplePaper/main/README.md
markdown
MIT License
## 模版简介 SimplePaper 是 [Typst](https://github.com/typst/typst) 的模版,用于编写简单的论文/报告/作业。 ## 使用说明 ### 如何使用 下载 [simplepaper.typ](https://github.com/1bitbool/SimplePaper/blob/main/simplepaper.typ) 到本地,可以参考仓库中的示例 [论文示例](https://github.com/1bitbool/SimplePaper/blob/main/examples/example.typ) [作业示例](https://github.com/1bitbool/SimplePaper/blob/main/examples/homework.typ) 进行编写即可。 ### 字体 使用前请先确认已经安装了模板所需字体! 当前模板的中文字体使用了 5 款方正字体:[方正黑体](https://www.foundertype.com/index.php/FontInfo/index/id/131)、[方正书宋](https://www.foundertype.com/index.php/FontInfo/index/id/151)、[方正楷体](https://www.foundertype.com/index.php/FontInfo/index/id/137)、[方正仿宋](https://www.foundertype.com/index.php/FontInfo/index/id/128)、[方正小标宋](https://www.foundertype.com/index.php/FontInfo/index/id/164),你需要到[方正官网](https://www.foundertype.com/)安装这些字体。 模板英文字体使用了 "Georgia", "Times New Roman", "Courier New", "Menlo", 通常系统已经内置了这些字体,如发现异常可及时安装对应字体。 如果你想更换其他字体,你需要在模版中直接修改字体。 ### 使用环境 由于网页版 Typst 没有内置这些中文字体,你需要手动上传字体以编译,这会导致每次打开模板的时候都会全量下载一遍字体。因此**不推荐在网页版上使用该模板**。 ## 模版效果 ### 论文效果 ![example-1](examples/output/example-1.png) ![example-2](examples/output/example-2.png) ![example-3](examples/output/example-3.png) ### 作业效果 ![homework-1](examples/output/homework-1.png) ![homework-2](examples/output/homework-2.png) ![homework-3](examples/output/homework-3.png)
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/par.typ
typst
// Test configuring paragraph properties. --- par-basic --- #set page(width: 250pt, height: 120pt) But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun. Arise, fair sun, and kill the envious moon, Who is already sick and pale with grief, That thou her maid art far more fair than she: Be not her maid, since she is envious; Her vestal livery is but sick and green And none but fools do wear it; cast it off. It is my lady, O, it is my love! O, that she knew she were! She speaks yet she says nothing: what of that? Her eye discourses; I will answer it. I am too bold, 'tis not to me she speaks: Two of the fairest stars in all the heaven, Having some business, do entreat her eyes To twinkle in their spheres till they return. What if her eyes were there, they in her head? The brightness of her cheek would shame those stars, As daylight doth a lamp; her eyes in heaven Would through the airy region stream so bright That birds would sing and think it were not night. See, how she leans her cheek upon her hand! O, that I were a glove upon that hand, That I might touch that cheek! --- par-leading-and-spacing --- // Test changing leading and spacing. #set par(spacing: 1em, leading: 2pt) But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun. --- par-spacing-context --- #set par(spacing: 10pt) #context test(par.spacing, 10pt) --- par-first-line-indent --- #set par(first-line-indent: 12pt, spacing: 5pt, leading: 5pt) #show heading: set text(size: 10pt) The first paragraph has no indent. But the second one does. #box(image("/assets/images/tiger.jpg", height: 6pt)) starts a paragraph, also with indent. #align(center, image("/assets/images/rhino.png", width: 1cm)) = Headings - And lists. - Have no indent. Except if you have another paragraph in them. #set text(8pt, lang: "ar", font: ("Noto Sans Arabic", "Libertinus Serif")) #set par(leading: 8pt) = Arabic دع النص يمطر عليك ثم يصبح النص رطبًا وقابل للطرق ويبدو المستند رائعًا. --- par-spacing-and-first-line-indent --- // This is madness. #set par(first-line-indent: 12pt) Why would anybody ever ... ... want spacing and indent? --- par-hanging-indent --- // Test hanging indent. #set par(hanging-indent: 15pt, justify: true) #lorem(10) --- par-hanging-indent-manual-linebreak --- #set par(hanging-indent: 1em) Welcome \ here. Does this work well? --- par-hanging-indent-rtl --- #set par(hanging-indent: 2em) #set text(dir: rtl) لآن وقد أظلم الليل وبدأت النجوم تنضخ وجه الطبيعة التي أعْيَتْ من طول ما انبعثت في النهار --- par-trailing-whitespace --- // Ensure that trailing whitespace layouts as intended. #box(fill: aqua, " ") --- par-empty-metadata --- // Check that metadata still works in a zero length paragraph. #block(height: 0pt)[#""#metadata(false)<hi>] #context test(query(<hi>).first().value, false) --- par-metadata-after-trimmed-space --- // Ensure that metadata doesn't prevent trailing spaces from being trimmed. #set par(justify: true, linebreaks: "simple") #set text(hyphenate: false) Lorem ipsum dolor #metadata(none) nonumy eirmod tempor. --- issue-4278-par-trim-before-equation --- #set par(justify: true) #lorem(6) aa $a = c + b$ --- issue-4938-par-bad-ratio --- #set par(justify: true) #box($k in NN_0$) --- issue-4770-par-tag-at-start --- #h(0pt) #box[] <a> #context test(query(<a>).len(), 1) --- show-par-set-block-hint --- // Warning: 2-36 `show par: set block(spacing: ..)` has no effect anymore // Hint: 2-36 this is specific to paragraphs as they are not considered blocks anymore // Hint: 2-36 write `set par(spacing: ..)` instead #show par: set block(spacing: 12pt)
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/03-polynomials/07-multiroots-and-derivatives.typ
typst
Other
#import "../../utils/core.typ": * == Кратные корни и производные #def[ Пусть $f in R[x]$ и $f eq.not 0$. Пусть $a in R$ --- корень. $(X - a) divides f$ по теореме Безу. Наибольший $n$, такой что $(X - a)^n divides f$, называется _кратностью корня_ $a$. Можно заметить, что $n <= deg f$, поэтому он всегда существует. Корни кратности $1$ называются _простыми корнями_ $f$, корни кратности $<= 2$ называются _кратными корнями_ $f$, корни кратности $2$ --- _двойными_, $3$ --- _тройными_ ] #th[ Пусть $K$ поле, $f in K[X]$, $d = deg f > 0$ $a_1, ..., a_s$ --- его корни, $n_1, ..., n_s$ --- их кратности. Тогда $n_1 + ... + n_s <= d$. ] #proof[ Разложим $f$ на неприводимые множители. $f = (X - a_1)^(m_1) ... (X - a_s)^(m_s) dot g$, где $g in K[x]$ и $(X - a_j)$ --- неприводимые множители. Заметим, что $(X - a_1) eq.not g, space ..., space (X - a_s) eq.not g$. Считаем, что $m_1 <= n_1, space ..., space m_s <= n_s$. Предположим, при некотором $j$: $n_j > m_j ==>$ $(X - a_j)^(m_j + 1) divides f ==> (X - a_j)^(m_j + 1) dot h = (X - a_1)^(m_1) ... (X - a_s)^(m_s) dot g ==>$ $(X - a_j) dot h = (X - a_1)^(m_1) ... hat((X - a_j)^(m_j)) ... (X - a_s)^(m_s) dot g ==>$ $(X - a_j) divides (X - a_1)^(m_1) ... hat((X - a_j)^(m_j)) ... (X - a_s)^(m_s) dot g ==>$ Либо $(X - a_j) divides (X - a_i), space i eq.not j$ или $(X - a_j) divides g$, но такого не может быть, значит $m_j = n_j, space j = 1, ..., s$. Тогда $d = deg f = m_1 + ... + m_s + underbrace(deg g, >= 0) >= n_1 + ... + n_s$ ] #def[ Пусть $f in K[X]$, $f = a_n X_n + a_(n-1) X_(n-1) + ... + a_1 X_1 + a_0$ Его _производной_ будет называться многочлен $f' in K[X]$, $f' = n a_n X_(n - 1) + (n - 1) a_(n - 1) X_(n - 2) + ... + a_1$ ] #pr[ + $(f + g)' = f' + g'$ + $(f g)' = f' g + f g'$ + $(f^n)' = n f^(n - 1) f'$ ] #proof[ + лёгкая непосредственная проверка (сначала очевидно, потом тривиально, как всегда короче) + #[ Пусть $f, g$ --- мономы, то есть $f = a X^n, space g = b X^m$ $(f g)' = (a b X^(n + m))' = (n + m)a b X^(n + m - 1) = n dot a b X^(n + m - 1) + m dot a b X^(n + m - 1) = $ $ underbrace(n a X^(n - 1), f') dot underbrace(b X^m, g) + underbrace(a X^n, f) dot underbrace(m b X^(m - 1), g') $ $f = sum f_i, space g = sum g_i, quad f_i, g_i$ --- мономы $(f g)' = ( limits(sum)_(i, j) f_i g_j ) = limits(sum)_(i, j) (f_i g_j)' = limits(sum)_(i, j) (f_i' g_j + f_i g_j') =\ limits(sum)_(i, j) f_i' g_j + limits(sum)_(i, j) f_i g_j' = limits(sum)_(i) f_i' limits(sum)_(j) g_j + limits(sum)_(i) f_i limits(sum)_(j) g_j' = f' g + f g'$ ] + #[ Индукция по $n$ "База": $n = 1$ $f' = f'$ "Переход": $n > 1$ $(f^n)' = (f^(n - 1) dot f)' = (f^(n - 1))' dot f + f^(n - 1) dot f' limits(=)^("переход")$ $((n - 1) dot f' dot f^(n - 2)) dot f + f^(n - 1) dot f' = (n - 1) f' dot f^(n-1) + f' dot f^(n - 1) = n f^(n - 1) f'$ ] ] #pr[ $K$ --- поле. $f in K[X], space f eq.not 0, space a in K$ Тогда $a$ кратный корень $f <==> f(a) = f'(a) = 0$ ] #proof[ "$arrow.r.double$": $a$ кратный корень $f ==> (X - a)^2 divides f ==> f = (X - a)^2 dot g,quad g in K[X]$ $f' = ( (X - a)^2 )' dot g + (X - a)^2 dot g' = 2(X - a) dot g + (X - a)^2 dot g' ==> f'(a) = 0$ "$arrow.l.double$": Пусть $f(a) = f'(a) = 0$. $f(a) = 0 limits(==>)^("т.Безу") f = (X - a) dot g,quad g in K[X] ==> f' = g + (X - a) g'$ $f'(a) = 0 ==> g(a) = 0 ==> (X - a) divides g ==> (X - a)^2 divides f ==> a$ кратный корень $f$ ] #follow[ $K$ --- поле. $f in K[X], space f eq.not 0, space a in K$ Пусть $D = (f, f')$ Тогда $a$ кратный корень $f <==> D(a) = 0$ ] #proof[ $a$ кратный корень $<==>$ $f(a) = f'(a) = 0 limits(<==>)^("т.Безу") (X - a) divides f$ и $(X - a) divides f' <==> (X - a) divides D limits(<==>)^("т.Безу") D(a) = 0$ ] #def[ Для кольца с $1$ _характеристикой_ $char R$ называется минимальное $n in NN$ такое, что $underbrace(1 + ... + 1, n) = 0$, а если такого $n$ нет, то $char R = 0$ ] #pr[ $K$ --- поле c характеристикой $0$, то есть $underbrace(1 + ... + 1, n) eq.not 0,quad forall n in NN$ $f in K[X], space a in K$ --- корень $f$ кратности $s >= 2$. Тогда $a$ --- корень $f'$ кратности $s - 1$ ] #proof[ $f = (X - a)^s g$ $(X - a) divides.not g limits(==>)^("т.Безу") g(a) eq.not 0$ $f' = ((X - a)^s)' dot g + (X - a)^s dot g' = $ $s(X - a)^(s - 1) dot g + (X - a)^s dot g' = $ $(X - a)^(s-1) dot h$, где $h = s dot g + (X - a) g'$ $h(a) limits(=)^(char K = 0) s dot g(a) eq.not 0 ==> (X - a) divides.not h$ ]
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/themes/5.typ
typst
#import "../conf.typ": * = Формула Тейлора с остаточным членом в форме Пеано или Лагранжа == Остаточный член в форме Лагранжа #lemma[ Если $f$ $n$ раз дифференцируема в точке $x_0$, то $exists !$ многочлен $P_n (f, x)$ степени $<= n$ такой, что #eq[ $f(x_0) = P_n (f, x_0) ; f'(x_0) = P'_n (f, x_0) ; ... ; f^((n)) (x_0) = P_n^((n))(f, x_0)$ ] Этот многочлен имеет вид #eq[ $P_n (f, x) = f(x_0) + (f'(x_0)) / 1! (x - x_0) + (f''(x_0)) / 2! (x - x_0)^2 + ... + (f^((n))(x_0)) / n! (x - x_0)^n$ ] и называется *многочленом Тейлора* степени $n$ относительно точки $x_0$. ] #proof[ Проверяется банальной подстановкой. ] #lemma( "Об отношении", )[ Если $phi, psi$ $(n + 1)$ раз дифференцируемы в $U_delta (x_0)$, причём #eq[ $forall k = overline("0, n") : space phi^((k))(x_0) = psi^((k))(x_0) = 0$ ] но #eq[ $forall k = overline("0, n") : forall x in dot(U)_delta (x_0) : space psi^((k))(x) != 0$ ] то #eq[ $forall x in dot(U)_delta (x_0) : exists xi in (x_0, x) : space (phi(x)) / (psi(x)) = (phi^((n + 1))(xi)) / (psi^((n + 1))(xi))$ ] ] #proof[ Заметим, что $phi, psi$ удовлетворяют условиям теоремы Коши о среднем. Тогда #eq[ $exists xi_... in (x_0, x) : space (phi(x) - underbrace(phi(x_0), 0)) / (psi(x) - underbrace(psi(x_0), 0)) = (phi'(xi_1)) / (psi'(xi_1)) = (phi'(xi_1) - underbrace(phi'(x_0), 0)) / (psi'(xi_1) - underbrace(psi'(x_0), 0)) = (phi''(xi_2)) / (psi''(xi_2)) = ... = (phi^((n + 1))(xi_(n + 1))) / (psi^((n + 1))(xi_(n + 1))) $ ] ] #theorem( "Формула Тейлора с остаточным членом в форме Лагранжа", )[ Если $f$ $(n + 1)$ раз дифференцируема в $U_delta (x_0), delta > 0$, то #eq[ $forall x in dot(U)_delta (x_0) : exists xi in (x_0, x) : space f(x) - P_n (f, x) = (f^((n + 1))(xi)) / (n + 1)! (x - x_0)^(n + 1)$ ] ] #proof[ Сведём к предыдущей лемме об отношении: #eq[ $phi(x) := f(x) - P_n (f, x); quad psi(x) := (x - x_0)^(n + 1)$ ] Все требуемые свойства проверяются очевидно. ] == Остаточный член в форме Пеано #definition[ Пусть функции $f(x), g(x)$ определены на множестве $X$. Тогда $f(x)$ есть *о-малое* от $g(x)$ при $x -> x_0$, если существует окрестность $dot(U)(x_0)$ такая, что #eq[ $forall x in dot(U)(x_0) : f(x) = g(x) alpha(x)$, ] где $lim_(x -> x_0) alpha(x) = 0$. ] #theorem( "Формула Тейлора с остаточным членом в форме Пеано", )[ Если $f$ $n$ раз дифференцируема в точке $x_0$, то #eq[ $f(x) - P_n (f, x) = o((x - x_0)^n), x -> x_0$ ] где $P_n (f, x)$ -- многочлен Тейлора степени $n$ функции $f$ относительно $x_0$. ] #proof[ По определению, если $f$ $n$ раз дифференцируема в точке, то она $n - 1$ раз дифференцируема в окрестности. Снова используем лемму об отношении, но для случая $n - 1$: #eq[ $phi(x) := f(x) - P_n (f, x) ; quad psi(x) = (x - x_0)^n$ ] Получим, что #eq[ $exists xi in (x_0, x) : space (f(x) - P_n (f, x)) / (x - x_0)^n = (f^((n - 1))(xi) - P_n^((n - 1))(f, xi)) / (n! (xi - x_0))$ ] Заметим, что при $x -> x_0 => xi -> x_0$: #eq[ $lim_(x -> x_0) (f(x) - P_n (f, x)) / (x - x_0)^n = lim_(xi -> x_0) (f^((n - 1))(xi) - P_n^((n - 1))(f, xi)) / (n! (xi - x_0)) = 1 / n! (f(x_0) - P_n (f, x_0))^((n)) = 0$ ] ]
https://github.com/heychhavi/resume-template
https://raw.githubusercontent.com/heychhavi/resume-template/main/docs/README.md
markdown
# Another Typst Resume Template! Plenty of issues, but it works well for me. 1. Install Typst (`brew install typst`). 2. Install Justfile (`brew install justfile`). 3. Create a file called `resume.typ` that looks like `sample-resume.typ` 4. Run `just dev` to start hot-reloading Alternatively, check out the `typst` extension for VS Code. Pull requests are welcome. ![screenshot](screenshot.png)
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/uebungen/1/main.typ
typst
#import "/config.typ" #show: config.config = Algorithmen == ggT / kgV == Eratosthenes == Matrix Eine $(m times n)$ Matrix hat $m$ Zeilen und $n$ Spalten. $ A = (a_(i j))_(1<=i<=m\ 1<=i<=n) $ === Addition Zwei Matrizen $A$ und $B$ müssen die gleiche Anzahl an Zeilen und Spalten haben, um addiert werden zu können. Das Ergebnis $C$ hat auch die gleiche Anzahl an Zeilen und Spalten. Es wird durch komponentenweise Addition berechnet: $ c_(i j) = a_(i j) + b_(i j) $ In Python lässt sich das folgendermaßen implementieren: ```py for i in range(m): for j in range(n): c[i][j] = a[i][j] + b[i][j] ``` === Multiplikation Die Spalten der ersten Matrix muss gleich der Zeilen der Zweiten sein. $ A.n = B.m $ Das Ergebnis hat die Zeilen der ersten Matrix und die Spalten der Zweiten. $ (C_(i j))_(1 <= i <= A.m \ 1 <= j <= B.n) $ Jeder Ergebniseintrag $c_(i j)$ errechnet sich aus der $i$-ten Zeile in $A$ und der $j$-ten Spalte in B. #include "matrix_mult.typ" Konkret wird für jede Spalte in $A$ und jede Zeile in $B$ das Produkt von $a_(i k)$ und $b_(k j)$ berechnet. Alle Produkte werden anschließend aufsummiert. $ c_(i j) = sum_(k=1)^n a_(i k) dot b_(k j) $ In Python: ```py for i in range(m): for j in range(p): for k in range(n): c[i][j] += a[i][k] * b[k][j] ``` == Matrix Laufzeit Die Addition zwei quadratischer Matrizen hat eine Laufzeit von $ T_+ = m dot n = n^2 $ weil es so viele Einträge gibt. Die Multiplikation hat eine Laufzeit von $ T_times = m dot p dot n = n^3 $ weil für jeden Eintrag zusätzlich $n$ Multiplikationen und Additionen ausgeführt werden. === Zeitkomplexität Mit $n = 1000$ benötigt mein Laptop für die Matrixmultiplikation $t = 175$s. Daraus ergibt sich die Frequenz $ f &= T(n) / t \ &= 1000^3 / 175 \ &approx 5.7 "MHz" $ Mit meiner Prozessorleistung kann ich in einer gegebenen Dauer $t$ zwei Matrizen der Größe $ n(t) &= T^(-1)(t dot f) \ &= root(3, t dot 5.7 "MHz") $ //multiplizieren #footnote[ //Wenn $T(n)$ die Anzahl benötigter Schritte bei einer Eingabelänge $n$ liefert, dann liefert die Umkehrfunktion $T^(-1)(n)$ die Eingabelänge bei einer gegebenen Anzahl an berechneten Schritten. //]. Daraus ergibt sich die Wertetabelle (Addition wird analog zur Multiplikation gehandhabt): #table(columns: 3, $t$, [$n$ ($times$)], [$n$ ($+$)], "1 min", "699", $1.7 dot 10^4$, "2 min", "881", $2.5 dot 10^4$, "5 min", "1195", $3.9 dot 10^4$, "10 min", "1506", $5.6 dot 10^4$ ) === Platzkomplexität Mit $n = 2000$ nimmt eine Matrix 92 MB ein. Die Anzahl speicherbarer Elemente $x$ pro Byte ist also $ x &= P(n)/s \ &= 2000^2/(92 dot 10^6) \ &approx 0.04 $ Hochgerechnet benötigt eine $10^4 times 10^4$ Matrix $ s &= P(n)/x \ &= 10^8/0.04 \ &= 2.5 "GB" $ Bei der Addition ist also die Platzkomplexität der beschränkende Faktor.
https://github.com/Nianyi-GSND-Projects/GSND-5130-GP2
https://raw.githubusercontent.com/Nianyi-GSND-Projects/GSND-5130-GP2/master/Team%20Agreement/Team%20Agreement.typ
typst
#set page(paper: "us-letter") #let team_name = [Group 4 of GSND 5130 GP2] #{ set align(center); set text(17pt, weight: "bold"); text[ Team Agreement of #set text(style: "italic") #team_name ]; } #{ set align(center); v(-0.5em); datetime.today().display("[month]/[day]/[year]"); v(0.5em); } This is group 4 for the second group project of GSND 5130. Unlike the first group project, this time we get to choose our teammates. Since there are only two members in the group, many rules that are meant for regulating many people could be saved this time. = Members #let member(name: "", localname: "", mail: "") = { show link: set text(font: "Consolas"); set align(center); text(size: 1.2em)[#name (#localname)]; linebreak(); link("mailto:" + mail)[<#mail>]; } #table( columns: (1fr, 1fr), stroke: none, member( name: "<NAME>", localname: "<NAME>", mail: "<EMAIL>" ), member( name: "<NAME>", localname: "王念一", mail: "<EMAIL>" ) ) = Goals By this stage, everyone has already gained experience of conducting qualitative researches. In this group project, we aim to furtherly generalize our ability to _usability researches_ by designing a research proposal and then realizing it. = Behavioral Expectations - Respect each other. Treat each other as equal co-workers and talk things in an adequate way. - Get work done on time. Try not to do everything in the last minutes. Always keep the project's affairs in mind. - Hold each other accountable. A member's responsibility not only includes speed, but also quality. If you ever find another member's work is not capable, point it out. = In-team Communication For regular communication, use _Telegram_. For big/complex topics, go for an in-person meeting. Because we share the same class schedule, it is convenient for us to meet before/after class. Other urgent business should be appointed at least one day prior than the meeting. = Decision Making When a disagreement is encountered, lay out our reasons. Carefully analyze the pros and cons of each of them and see which could be compromised. A possible solution should then pop out. If still not resolved, reach for the professor for advice.
https://github.com/akshaybabloo/CV
https://raw.githubusercontent.com/akshaybabloo/CV/master/README.md
markdown
MIT License
# CV ## Requirements - [Poetry](https://python-poetry.org/docs/#installation) - [typst](https://github.com/typst/typst/releases/latest) - [Python 3](https://www.python.org/downloads/) ## Install Add `typst` to your path. Than: ```bash poetry install ``` ## Build Edit `data.yaml` with your data. Leave the `phone_number` empty. Than: ```bash PHONE_NUMBER="YOUR_PHONE_NUMBER" poetry run python helper.py add-phone-number typst compile --font-path ./fonts resume.typ typst compile --font-path ./fonts cv.typ ``` This will generate `resume.pdf` and `cv.pdf` files. ## Automate > Make sure you have the `PHONE_NUMBER`, `SENDGRID_API_KEY` and `EMAIL_TO` secrets set in your repository settings. You can automate the build process with GitHub Actions, see the [workflow](.github/workflows/build-and-send.yml) file. The workflow does the following: - Install `typst` binary - Install `poetry` and the dependencies used here - Fetches the secrets from the repository settings - `PHONE_NUMBER` and `SENDGRID_API_KEY` - Updates the `data.yaml` file with the `PHONE_NUMBER` secret and builds the PDFs - Sends the PDFs to the email address specified in the `EMAIL_TO` secret
https://github.com/daniel-ttel/banana-omen
https://raw.githubusercontent.com/daniel-ttel/banana-omen/main/template/show.typ
typst
MIT License
#import "/Template/page.typ": * #let shows(doc) = [ #show figure.caption: it => [ #box(width: 80%,[ #it.supplement #context it.counter.display(it.numbering)#it.separator#it.body] ) ] #show figure.caption: set text(9pt) #show: super-T-as-transpose #show: thmrules #metro-setup(per-mode: "symbol") #metro-setup(output-decimal-marker: ",") #metro-setup(exponent-mode: "threshold", exponent-thresholds: (-4, 4)) #declare-unit("parsec", "pc") #declare-unit("atm", "atm") #doc ] #let fin(doc) = [ #pagebreak() #set heading(numbering: none) #show heading.where(level: 3): set heading(outlined: false) #doc ]
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/text/lang.typ
typst
// Test setting the document language. --- text-lang --- // without any region #set text(font: "Noto Serif CJK TC", lang: "zh") #outline() --- text-lang-unknown-region --- // with unknown region configured #set text(font: "Noto Serif CJK TC", lang: "zh", region: "XX") #outline() --- text-lang-region --- // with region configured #set text(font: "Noto Serif CJK TC", lang: "zh", region: "TW") #outline() --- text-lang-hyphenate --- // Ensure that setting the language does have effects. #set text(hyphenate: true) #grid( columns: 2 * (20pt,), gutter: 1fr, text(lang: "en")["Eingabeaufforderung"], text(lang: "de")["Eingabeaufforderung"], ) --- text-lang-shaping --- // Test that the language passed to the shaper has an effect. #set text(font: "Ubuntu") // Some lowercase letters are different in Serbian Cyrillic compared to other // Cyrillic languages. Since there is only one set of Unicode codepoints for // Cyrillic, these can only be seen when setting the language to Serbian and // selecting one of the few fonts that support these letterforms. Бб #text(lang: "uk")[Бб] #text(lang: "sr")[Бб] --- text-lang-script-shaping --- // Verify that writing script/language combination has an effect #{ set text(size:20pt) set text(script: "latn", lang: "en") [Ş ] set text(script: "latn", lang: "ro") [Ş ] set text(script: "grek", lang: "ro") [Ş ] } --- text-script-bad-type --- // Error: 19-23 expected string or auto, found none #set text(script: none) --- text-script-bad-value --- // Error: 19-23 expected three or four letter script code (ISO 15924 or 'math') #set text(script: "ab") --- text-lang-bad-type --- // Error: 17-21 expected string, found none #set text(lang: none) --- text-lang-bad-value --- // Error: 17-20 expected two or three letter language code (ISO 639-1/2/3) #set text(lang: "ӛ") --- text-lang-bad-value-emoji --- // Error: 17-20 expected two or three letter language code (ISO 639-1/2/3) #set text(lang: "😃") --- text-region-bad-value --- // Error: 19-24 expected two letter region code (ISO 3166-1 alpha-2) #set text(region: "hey") --- text-language-fallback-english --- #set text(lang: "qaa") #outline() #set text(lang: "qaa", region: "aa") #outline() --- text-lang-hint-region-parameter --- // Error: 17-24 expected two or three letter language code (ISO 639-1/2/3) // Hint: 17-24 you should leave only "en" in the `lang` parameter and specify "gb" in the `region` parameter #set text(lang: "en-gb")
https://github.com/astro-group-bristol/what-is-rss
https://raw.githubusercontent.com/astro-group-bristol/what-is-rss/main/slides/main.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import "tamburlaine.typ": * #let HANDOUT_MODE = false #enable-handout-mode(HANDOUT_MODE) #show: tamburlaine-theme.with(aspect-ratio: "4-3") #show link: item => underline(text(blue)[#item]) #let COLOR_CD = color.rgb("#56B4E9") #let COLOR_REFL = color.rgb("#D55E00") #let COLOR_CONT = color.rgb("#0072B2") #set text(size: 30pt) #let rss_logo = read("./figs/Feed-icon.svg") #title-slide( title_size: 114pt, title: [ #set par(leading: 40pt) #set par(spacing: 40pt) #grid(columns: (40%, 1fr), [#align(center, image.decode(rss_logo, width: 70%))], [_Really_ Simple], ) Syndication ], authors: ([<NAME>],), where: "Astro Dev Group", )[ ] #slide()[ #align(center)[ #text(size: 80pt, "🤔") #text(size: 30pt)[How to you keep track of the things \ you're *interested* in?] ] #v(1em) - Make an account, like 👍 and subscribe 🤠 - "Feeds" - Algorithmically curated "feed" #text(size: 35pt)[ *What about academic interests?* ] - Do you check the arXiv every day? - Mailing lists? ] #slide()[ #align(right)[ Too many places, too much to keep track of, *infinite* items in a feed. ] - Can get noisy and overly messy with "recommended" items #v(-0.5em) #align(center)[ #image("./figs/rss1.png", width: 50%) ] #v(-0.4em) #text(size: 18pt, [Image from: #link("https://ncase.me/rss/")]) #v(-0.4em) #text(size: 40pt)[ *RSS* is seeing the things you *want* to see. ] ] #slide(title: "Nicky's shtuff")[ #text(size: 20pt, [Go read it in your own time: #link("https://ncase.me/rss/")]) #align(center)[ #image("./figs/rss2.png", width: 50%) ] #v(-0.4em) #quote[Unlike newsletters where you give each publisher your email (and they may abuse that trust), RSS works on a "*don't call me, I'll call you*" policy.] ] #slide(title: "The advantages")[ You get more time to do other things. - Feeds have an end again. - Everything in one place. #v(1em) Publishing RSS is easy! - Your favourite blogs (probably) have RSS feeds. - Journals and ArXiV publish RSS. - YouTube channels can be treated as RSS feeds. ] #slide(title: "What's in an RSS?")[ It's just XML: #h(1fr) #text(size: 12pt, [Example from: https://en.wikipedia.org/wiki/RSS]) #v(-0.5em) #set text(size: 17pt) ```xml <?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0"> <channel> <title>RSS Title</title> <description>This is an example of an RSS feed</description> <link>http://www.example.com/main.html</link> <copyright>2020 Example.com All rights reserved</copyright> <lastBuildDate>Mon, 6 Sep 2010 00:01:00 +0000</lastBuildDate> <pubDate>Sun, 6 Sep 2009 16:20:00 +0000</pubDate> <ttl>1800</ttl> <item> <title>Example entry</title> <description>Here is some text containing an interesting description.</description> <link>http://www.example.com/blog/post/1</link> <guid isPermaLink="false">7bd204c6-1655-4c27-aeee-53f933c5395f</guid> <pubDate>Sun, 6 Sep 2009 16:20:00 +0000</pubDate> </item> </channel> </rss> ``` ] #slide(title: "How to get started?")[ #set text(size: 22pt) You'll need a *feed reader* and an RSS feed you want to fetch from. Some recommendations: - #link("https://www.inoreader.com/")[Inoreader] - #link("https://github.com/yang991178/fluent-reader")[Fluent Reader (GitHub)] - #link("https://newsboat.org/")[Newsboat] - #link("https://github.com/martinrotter/rssguard")[RSS Guard (GitHub)] There are plugins for other apps as well, such as web browsers or Obsidian. A good list of people's #link("https://www.reddit.com/r/rss/comments/16yo2p5/your_favorite_rss_reader/")[favourite readers (Reddit)], but caution, not all of them are FOSS. A _huge_ list of RSS feeds to look through: \ #link("https://github.com/plenaryapp/awesome-rss-feeds") ] #slide(title: "How can I make my own?")[ Write a generator yourself (it's quite straight forward)! Use a package that will generate it for you: - e.g., for Python there is the #link("https://github.com/svpino/rfeed")[rfeed] package. Share it with your friends! Build your own syndication network! ] #slide(title: "Tips")[ #set text(size: 30pt) - Don't subscribe to too many feeds. Only keep the ones that continue to post things you find interesting. - Avoid feeds that only contain a link to a webpage. - Don't refresh your feed too often. Have fun! 🎉 ]
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/main.typ
typst
#import "../template.typ": note // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: note.with( title: "代数学二", author: "YHTQ", date: none, logo: none, withChapterNewPage: true ) #include "章节/上半学期.typ" #include "章节/下半学期.typ"
https://github.com/Godalin/Typst-Notations
https://raw.githubusercontent.com/Godalin/Typst-Notations/main/Proof.typ
typst
// proof #let blue_ = text.with(fill: blue) #let Assume = text("Assume", fill: blue) #let imp = blue_[$==>$] #let iff = text($<==>$, fill: blue) #let wts = text("Want To Show", fill: blue) #let If = text("If", fill: blue) #let Then = text("Then", fill: blue) #let exist = text(sym.exists, fill: blue) #let st = text("s.t.", fill: blue) #let ie = blue_("i.e.") #let ok = text(fill: green.darken(30%), $checkmark$, weight: "bold")
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2700.typ
typst
Apache License 2.0
#let data = ( ("BLACK SAFETY SCISSORS", "So", 0), ("UPPER BLADE SCISSORS", "So", 0), ("BLACK SCISSORS", "So", 0), ("LOWER BLADE SCISSORS", "So", 0), ("WHITE SCISSORS", "So", 0), ("WHITE HEAVY CHECK MARK", "So", 0), ("TELEPHONE LOCATION SIGN", "So", 0), ("TAPE DRIVE", "So", 0), ("AIRPLANE", "So", 0), ("ENVELOPE", "So", 0), ("RAISED FIST", "So", 0), ("RAISED HAND", "So", 0), ("VICTORY HAND", "So", 0), ("WRITING HAND", "So", 0), ("LOWER RIGHT PENCIL", "So", 0), ("PENCIL", "So", 0), ("UPPER RIGHT PENCIL", "So", 0), ("WHITE NIB", "So", 0), ("BLACK NIB", "So", 0), ("CHECK MARK", "So", 0), ("HEAVY CHECK MARK", "So", 0), ("MULTIPLICATION X", "So", 0), ("HEAVY MULTIPLICATION X", "So", 0), ("BALLOT X", "So", 0), ("HEAVY BALLOT X", "So", 0), ("OUTLINED GREEK CROSS", "So", 0), ("HEAVY GREEK CROSS", "So", 0), ("OPEN CENTRE CROSS", "So", 0), ("HEAVY OPEN CENTRE CROSS", "So", 0), ("LATIN CROSS", "So", 0), ("SHADOWED WHITE LATIN CROSS", "So", 0), ("OUTLINED LATIN CROSS", "So", 0), ("MALTESE CROSS", "So", 0), ("STAR OF DAVID", "So", 0), ("FOUR TEARDROP-SPOKED ASTERISK", "So", 0), ("FOUR BALLOON-SPOKED ASTERISK", "So", 0), ("HEAVY FOUR BALLOON-SPOKED ASTERISK", "So", 0), ("FOUR CLUB-SPOKED ASTERISK", "So", 0), ("BLACK FOUR POINTED STAR", "So", 0), ("WHITE FOUR POINTED STAR", "So", 0), ("SPARKLES", "So", 0), ("STRESS OUTLINED WHITE STAR", "So", 0), ("CIRCLED WHITE STAR", "So", 0), ("OPEN CENTRE BLACK STAR", "So", 0), ("BLACK CENTRE WHITE STAR", "So", 0), ("OUTLINED BLACK STAR", "So", 0), ("HEAVY OUTLINED BLACK STAR", "So", 0), ("PINWHEEL STAR", "So", 0), ("SHADOWED WHITE STAR", "So", 0), ("HEAVY ASTERISK", "So", 0), ("OPEN CENTRE ASTERISK", "So", 0), ("EIGHT SPOKED ASTERISK", "So", 0), ("EIGHT POINTED BLACK STAR", "So", 0), ("EIGHT POINTED PINWHEEL STAR", "So", 0), ("SIX POINTED BLACK STAR", "So", 0), ("EIGHT POINTED RECTILINEAR BLACK STAR", "So", 0), ("HEAVY EIGHT POINTED RECTILINEAR BLACK STAR", "So", 0), ("TWELVE POINTED BLACK STAR", "So", 0), ("SIXTEEN POINTED ASTERISK", "So", 0), ("TEARDROP-SPOKED ASTERISK", "So", 0), ("OPEN CENTRE TEARDROP-SPOKED ASTERISK", "So", 0), ("HEAVY TEARDROP-SPOKED ASTERISK", "So", 0), ("SIX PETALLED BLACK AND WHITE FLORETTE", "So", 0), ("BLACK FLORETTE", "So", 0), ("WHITE FLORETTE", "So", 0), ("EIGHT PETALLED OUTLINED BLACK FLORETTE", "So", 0), ("CIRCLED OPEN CENTRE EIGHT POINTED STAR", "So", 0), ("HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK", "So", 0), ("SNOWFLAKE", "So", 0), ("TIGHT TRIFOLIATE SNOWFLAKE", "So", 0), ("HEAVY CHEVRON SNOWFLAKE", "So", 0), ("SPARKLE", "So", 0), ("HEAVY SPARKLE", "So", 0), ("BALLOON-SPOKED ASTERISK", "So", 0), ("EIGHT TEARDROP-SPOKED PROPELLER ASTERISK", "So", 0), ("HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK", "So", 0), ("CROSS MARK", "So", 0), ("SHADOWED WHITE CIRCLE", "So", 0), ("NEGATIVE SQUARED CROSS MARK", "So", 0), ("LOWER RIGHT DROP-SHADOWED WHITE SQUARE", "So", 0), ("UPPER RIGHT DROP-SHADOWED WHITE SQUARE", "So", 0), ("LOWER RIGHT SHADOWED WHITE SQUARE", "So", 0), ("UPPER RIGHT SHADOWED WHITE SQUARE", "So", 0), ("BLACK QUESTION MARK ORNAMENT", "So", 0), ("WHITE QUESTION MARK ORNAMENT", "So", 0), ("WHITE EXCLAMATION MARK ORNAMENT", "So", 0), ("BLACK DIAMOND MINUS WHITE X", "So", 0), ("HEAVY EXCLAMATION MARK SYMBOL", "So", 0), ("LIGHT VERTICAL BAR", "So", 0), ("MEDIUM VERTICAL BAR", "So", 0), ("HEAVY VERTICAL BAR", "So", 0), ("HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT", "So", 0), ("HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT", "So", 0), ("HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT", "So", 0), ("HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT", "So", 0), ("HEAVY LOW SINGLE COMMA QUOTATION MARK ORNAMENT", "So", 0), ("HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT", "So", 0), ("CURVED STEM PARAGRAPH SIGN ORNAMENT", "So", 0), ("HEAVY EXCLAMATION MARK ORNAMENT", "So", 0), ("HEAVY HEART EXCLAMATION MARK ORNAMENT", "So", 0), ("HEAVY BLACK HEART", "So", 0), ("ROTATED HEAVY BLACK HEART BULLET", "So", 0), ("FLORAL HEART", "So", 0), ("ROTATED FLORAL HEART BULLET", "So", 0), ("MEDIUM LEFT PARENTHESIS ORNAMENT", "Ps", 0), ("MEDIUM RIGHT PARENTHESIS ORNAMENT", "Pe", 0), ("MEDIUM FLATTENED LEFT PARENTHESIS ORNAMENT", "Ps", 0), ("MEDIUM FLATTENED RIGHT PARENTHESIS ORNAMENT", "Pe", 0), ("MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT", "Ps", 0), ("MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT", "Pe", 0), ("HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT", "Ps", 0), ("HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT", "Pe", 0), ("HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT", "Ps", 0), ("HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT", "Pe", 0), ("LIGHT LEFT TORTOISE SHELL BRACKET ORNAMENT", "Ps", 0), ("LIGHT RIGHT TORTOISE SHELL BRACKET ORNAMENT", "Pe", 0), ("MEDIUM LEFT CURLY BRACKET ORNAMENT", "Ps", 0), ("MEDIUM RIGHT CURLY BRACKET ORNAMENT", "Pe", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT ONE", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT TWO", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT THREE", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT FOUR", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT FIVE", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT SIX", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT SEVEN", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT EIGHT", "No", 0), ("DINGBAT NEGATIVE CIRCLED DIGIT NINE", "No", 0), ("DINGBAT NEGATIVE CIRCLED NUMBER TEN", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT ONE", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT TWO", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT THREE", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT FOUR", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT FIVE", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT SIX", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT SEVEN", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT EIGHT", "No", 0), ("DINGBAT CIRCLED SANS-SERIF DIGIT NINE", "No", 0), ("DINGBAT CIRCLED SANS-SERIF NUMBER TEN", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT TWO", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT THREE", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FOUR", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FIVE", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SIX", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SEVEN", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT EIGHT", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT NINE", "No", 0), ("DINGBAT NEGATIVE CIRCLED SANS-SERIF NUMBER TEN", "No", 0), ("HEAVY WIDE-HEADED RIGHTWARDS ARROW", "So", 0), ("HEAVY PLUS SIGN", "So", 0), ("HEAVY MINUS SIGN", "So", 0), ("HEAVY DIVISION SIGN", "So", 0), ("HEAVY SOUTH EAST ARROW", "So", 0), ("HEAVY RIGHTWARDS ARROW", "So", 0), ("HEAVY NORTH EAST ARROW", "So", 0), ("DRAFTING POINT RIGHTWARDS ARROW", "So", 0), ("HEAVY ROUND-TIPPED RIGHTWARDS ARROW", "So", 0), ("TRIANGLE-HEADED RIGHTWARDS ARROW", "So", 0), ("HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW", "So", 0), ("DASHED TRIANGLE-HEADED RIGHTWARDS ARROW", "So", 0), ("HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW", "So", 0), ("BLACK RIGHTWARDS ARROW", "So", 0), ("THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD", "So", 0), ("THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD", "So", 0), ("BLACK RIGHTWARDS ARROWHEAD", "So", 0), ("HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW", "So", 0), ("HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW", "So", 0), ("SQUAT BLACK RIGHTWARDS ARROW", "So", 0), ("HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW", "So", 0), ("RIGHT-SHADED WHITE RIGHTWARDS ARROW", "So", 0), ("LEFT-SHADED WHITE RIGHTWARDS ARROW", "So", 0), ("BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW", "So", 0), ("FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW", "So", 0), ("HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW", "So", 0), ("HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW", "So", 0), ("NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW", "So", 0), ("CURLY LOOP", "So", 0), ("NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW", "So", 0), ("CIRCLED HEAVY WHITE RIGHTWARDS ARROW", "So", 0), ("WHITE-FEATHERED RIGHTWARDS ARROW", "So", 0), ("BLACK-FEATHERED SOUTH EAST ARROW", "So", 0), ("BLACK-FEATHERED RIGHTWARDS ARROW", "So", 0), ("BLACK-FEATHERED NORTH EAST ARROW", "So", 0), ("HEAVY BLACK-FEATHERED SOUTH EAST ARROW", "So", 0), ("HEAVY BLACK-FEATHERED RIGHTWARDS ARROW", "So", 0), ("HEAVY BLACK-FEATHERED NORTH EAST ARROW", "So", 0), ("TEARDROP-BARBED RIGHTWARDS ARROW", "So", 0), ("HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW", "So", 0), ("WEDGE-TAILED RIGHTWARDS ARROW", "So", 0), ("HEAVY WEDGE-TAILED RIGHTWARDS ARROW", "So", 0), ("OPEN-OUTLINED RIGHTWARDS ARROW", "So", 0), ("DOUBLE CURLY LOOP", "So", 0), )
https://github.com/ntjess/typst-tada
https://raw.githubusercontent.com/ntjess/typst-tada/main/src/display.typ
typst
The Unlicense
#import "helpers.typ" as H #let default-hundreds-separator = state("separator-state", ",") #let default-decimal = state("decimal-state", ".") /// Converts a float to a string where the comma, decimal, and precision can be customized. /// /// ```example /// #format-float(123456, precision: 2, pad: true)\ /// #format-float(123456.1121, precision: 1, hundreds-separator: "_") /// ``` /// /// - hundreds-separator (auto,str): The character to use to separate hundreds /// - decimal (auto,str): The character to use to separate the integer and fractional portions /// - precision (none,int): The number of digits to show after the decimal point. If `none`, /// then no rounding will be done. /// - pad (bool): If true, then the fractional portion will be padded with zeros to match the /// precision if needed. /// -> str #let format-float(number, hundreds-separator: auto, decimal: auto, precision: none, pad: false, ) = { // Adds commas after each 3 digits to make // pricing more readable if hundreds-separator == auto { hundreds-separator = default-hundreds-separator.display() } if precision != none { number = calc.round(number, digits: precision) } if decimal == auto { decimal = default-decimal.display() } // negative != hyphen, so grab from unicode let negative-sign = str.from-unicode(0x2212) let sign = if number < 0 { negative-sign } else { "" } let number-pieces = str(number).split(".") let integer-portion = number-pieces.at(0).trim(negative-sign) let num-with-commas = "" for ii in range(integer-portion.len()) { if calc.rem(ii, 3) == 0 and ii > 0 { num-with-commas = hundreds-separator + num-with-commas } num-with-commas = integer-portion.at(-ii - 1) + num-with-commas } let frac-portion = if number-pieces.len() > 1 { number-pieces.at(1) } else { "" } if precision != none and pad { for _ in range(precision - frac-portion.len()) { frac-portion = frac-portion + "0" } } if frac-portion != "" { num-with-commas = num-with-commas + decimal + frac-portion } sign + num-with-commas } /// Converts a float to a United States dollar amount. /// /// ```example /// #format-usd(12.323)\ /// #format-usd(-12500.29) /// ``` /// /// - number (float,int): The number to convert /// - ..args (any): Passed to @@format-float() /// -> str #let format-usd(number, ..args) = { // "negative" sign if needed if args.pos().len() > 0 { panic("format-usd() does not accept positional arguments") } let sign = if number < 0 {str.from-unicode(0x2212)} else {""} let currency = "$" [#sign#currency] let named = (precision: 2, pad: true, ..args.named()) format-float(calc.abs(number), ..named) } #let format-percent(number, ..args) = { format-float(number * 100, ..args) + "%" } #let format-content(value) = { if type(value) == str { value = eval(value, mode: "markup") } value } #let DEFAULT-TYPE-FORMATS = ( string: (default-value: "", align: left), content: (display: format-content, align: left), float: (align: right), integer: (align: right), percent: (display: format-percent, align: right), // TODO: Better country-robust currency // currency: (display: format-currency, align: right), index: (align: right), ) #let _value-to-display(value, value-info) = { if value == none { // TODO: Allow customizing `none` representation return value } if "display" in value-info { let scope = value-info.at("scope", default: (:)) + (value: value) H.eval-str-or-function(value-info.display, scope: scope, positional: value) } else { value } } #let title-case(field) = field.replace("-", " ").split(" ").map( word => upper(word.at(0)) + word.slice(1) ).join(" ") #let _field-info-to-tablex-kwargs(field-info) = { let get-eval(dict, key, default) = { let value = dict.at(key, default: default) if type(value) == "string" { eval(value) } else { value } } let (names, aligns, widths) = ((), (), ()) for (key, info) in field-info.pairs() { if "title" in info { let original-field = key let info-scope = info.at("scope", default: (:)) let scope = (..info-scope, field: original-field, title-case-field: title-case(original-field)) key = H.eval-str-or-function(info.at("title"), scope: scope, positional: original-field) if type(key) not in (str, content) { key = repr(key) } } names.push(key) let default-align = if info.at("type", default: none) == "string" { left } else { right } aligns.push(get-eval(info, "align", default-align)) widths.push(get-eval(info, "width", auto)) } // Keys correspond to tablex specs other than "names" which is positional (names: names, align: aligns, columns: widths) } /// Converts a @@TableData into a `tablex` table. This is the main (and only intended) /// way of rendering `tada` data. Most keywords can be overridden for customizing the /// output. /// /// ```example /// #let td = TableData( /// data: (a: (1, 2), b: (3, 4)), /// // Tables can carry their own kwargs, too /// tablex-kwargs: (inset: (x: 3em, y: 0.5em)) /// ) /// #to-tablex(td, fill: red) /// ``` /// /// - td (TableData): The data to render /// - ..tablex-kwargs (any): Passed to `tablex` #let to-tablex(td, tablex-version: "0.0.6", ..tablex-kwargs) = { import "@preview/tablex:" + tablex-version: tablex, cellx, rowspanx let (field-info, type-info) = (td.field-info, td.type-info) // Order by field specification let to-show = field-info.keys().filter( key => not field-info.at(key).at("hide", default: false) ) let subset = H.keep-keys(td.data, keys: to-show) // Make sure field info matches data order field-info = H.keep-keys(field-info, keys: subset.keys(), reorder: true) let display-columns = subset.pairs().map(key-column => { let (key, column) = key-column column.map(value => _value-to-display(value, field-info.at(key))) }) let rows = H.transpose-values(display-columns) let col-spec = _field-info-to-tablex-kwargs(field-info) let names = col-spec.remove("names") // We don't want a completely flattened array, since some cells may contain many values. // So use sum() to join rows together instead tablex(..td.tablex-kwargs, ..col-spec, ..tablex-kwargs, ..names, ..rows.sum()) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-math_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test on cancel #show math.equation: set text(fill: gradient.linear(..color.map.rainbow)) #show math.equation: box $ a dot cancel(5) = cancel(25) 5 x + cancel(5) 1 $
https://github.com/ayoubelmhamdi/typst-phd-AI-Medical
https://raw.githubusercontent.com/ayoubelmhamdi/typst-phd-AI-Medical/master/chapters/ch02-dep.typ
typst
MIT License
// pour que tu manque les autres, est ce que mon invite besoin de changement #import "../functions.typ": heading_center, images, italic #import "../tablex.typ": tablex, cellx, rowspanx, colspanx, hlinex #let finchapiter = text(fill:rgb("#1E045B"),[■]) = APERÇU SUR DEEP LEARNING. == Introduction. L'apprentissage profond est une branche de l'apprentissage automatique#footnote[https://fr.wikipedia.org/wiki/Apprentissage_profond] <wikiDeeplearning>, qui est lui-même un domaine de l'intelligence artificielle. L'apprentissage profond permet de prédire ou d'analyser des données de haute dimension ou complexes, comme les images, les textes ou les sons, d'une manière similaire au cerveau humain. L'apprentissage profond utilise des réseaux de neurones artificiels multicouches#footnote[https://www.ibm.com/topics/deep-learning] <ibmDeeplearning> qui peuvent extraire les sens et les motifs cachés dans les données sans avoir besoin d'intervention humaine. Ainsi, l'apprentissage profond acquiert une grande capacité d'adaptation et d'évolution avec le changement de données#cite("Goodfellowetal2016"). #images( filename:"images/ais.png", caption:[ Comment l'apprentissage en profondeur est un sous-ensemble de l'apprentissage automatique et comment l'apprentissage automatique est un sous-ensemble de l'intelligence artificielle (IA). ], width: 30% // ref: ) Par conséquent, l'apprentissage profond se distingue de l'apprentissage traditionnel par le fait qu'il ne repose pas sur des règles ou des algorithmes prédéfinis, mais qu'il peut générer ses propres règles et algorithmes par essai et erreur. De plus, l'apprentissage profond peut surmonter certains des problèmes rencontrés par l'apprentissage traditionnel, tels que le bruit, le manque ou le changement des données. Ainsi, nous voyons que l'apprentissage profond est un domaine récent et prometteur en informatique qui mérite l'attention et la recherche, et qui peut contribuer à résoudre de nombreux problèmes dans différents domaines tels que la traduction, la reconnaissance d'images et de sons, etc. == Fonctionnement de Deep Learning. Pour comprendre le principe de l'apprentissage profond, on peut utiliser des exemples de notre vie quotidienne. Lorsque nous voulons améliorer certains résultats, on change certains facteurs influençant ces résultats de manière cyclique, en se basant sur l'expérience et l'erreur. Par exemple, un vendeur de fruits essaie d'augmenter son revenu en changeant la quantité et les types de fruits offerts aux clients, en se référant aux ventes passées et actuelles. Il n'y a pas de règle fixe qui détermine la quantité de chaque fruit que le vendeur doit fournir, il doit donc expérimenter jusqu'à ce qu'il atteigne le point d'équilibre entre l'offre et la demande. En apprentissage profond, on utilise une fonction mathématique appelée *fonction coût* pour mesurer la différence entre les résultats d'un modèle d'apprentissage et les résultats souhaités ou corrects. Puis on utilise une autre fonction appelée *fonction optimisation* pour ajuster la valeur de chaque cellule neuronale dans le réseau d'apprentissage afin de réduire la valeur de la *fonction coût*. Ces étapes sont répétées sur un grand ensemble de données jusqu'à ce que le modèle d'apprentissage soit capable d'accomplir les tâches demandées avec précision ou acceptabilité. Cet exemple peut nous donner une idée qui nous aide à comprendre l'apprentissage en profondeur, mais il résume des concepts fondamentaux de l'apprentissage en profondeur tels que la fonction de coût ou la fonction de régression graduelle et l'optimisation<wikideeplearning>, ce qui est clair pour nous dans des applications telles que la traduction automatique ou la vision par ordinateur. == Applications. Dans la traduction automatique, un système d'apprentissage en profondeur utilise un réseau neuronal pour convertir une phrase d'une langue à une autre. Ce système utilise une fonction de coût pour mesurer la différence entre la traduction générée et la traduction cible. Ensuite, il utilise un algorithme d'optimisation tel que la descente de gradient pour ajuster le poids de chaque cellule neuronale dans le réseau afin de minimiser la valeur de la fonction de coût. Ce processus est répété sur un grand ensemble de phrases à traduire jusqu'à ce que le système soit capable de générer des traductions précises et naturelles. En vision par ordinateur, un système d'apprentissage en profondeur utilise des réseaux neuronaux artificiels pour extraire des informations et des perspectives à partir d'images et de vidéos. Certaines applications dans ce domaine sont#footnote[https://machinelearningmastery.com/applications-of-deep-learning-for-computer-vision/] <brownlee2019>: - La *classification d'images* consiste à attribuer une étiquette à une image ou une photographie entière. Ce problème est également appelé "classification d'objets" et peut-être plus généralement "reconnaissance d'images", bien que cette dernière tâche puisse s'appliquer à un ensemble beaucoup plus large de tâches liées à la classification du contenu des images. #images( filename:"images/MNIST-Dataset.png", caption:[Un exemple de chiffres de en jeu de données MNIST.], width: 50% // ref: ) Un exemple populaire de classification d'images utilisé est le jeu de données(dataset) MNIST. - *Surveillance du contenu*: pour supprimer automatiquement le contenu non sécurisé ou inapproprié des archives d'images et de vidéos. - *Reconnaissance faciale*: pour identifier l'identité des personnes ou extraire des caractéristiques de leur visage, telles que l'ouverture ou la fermeture des yeux, le port de lunettes ou de moustaches. - *Violation du droit d'auteur*: pour supprimer le contenu volé ou détourné d'images ou de vidéos protégées par des droits d'auteur. Ces applications sont rendues possibles grâce à l'utilisation de réseaux neuronaux profonds qui peuvent apprendre à partir d'un grand nombre d'exemples et extraire des caractéristiques complexes à partir des données. == Les réseaux de neurones artificiels. Les réseaux de neurones artificiels sont des modèles d'intelligence artificielle qui utilisent des cellules nerveuses artificielles pour convertir les entrées en sorties. Chaque cellule nerveuse reçoit des signaux d'autres cellules et envoie des signaux à d'autres cellules. Chaque signal est ajouté à une valeur de poids qui détermine sa force et son importance. Chaque cellule nerveuse calcule la somme des signaux reçus et applique une fonction d'activation pour produire un signal de sortie. #images( filename:"images/reseuxActicvation.png", caption:[Architecture de modèle multicouche.], width: 50% // ref: ) === Exemple de Deep learning dans la pratique. Pour savoir la relation entre les réseaux de neurones artificiels et la fonction linéaire, on utilise l'exemple de calcule de temperature precedent. La fonction linéaire est un type de fonctions mathématiques qui décrit une relation simple entre deux variables, où un changement dans l'une entraîne un changement proportionnel dans l'autre. Par exemple, si nous avons une fonction qui convertit la température de Celsius en Fahrenheit, cette fonction sera linéaire, car chaque augmentation d'un degré Celsius entraîne une augmentation constante de la température en Fahrenheit. La formule utilisée pour convertir la température de Celsius en Fahrenheit est#cite("conversionDeLatemperature") : $ F = 9/5 C + 32 $ On peut le représenter par le schéma de réseau suivant: #images( filename:"images/1-nerons.svg", caption:[Structure mono-neurone..], width: 60% // ref: ) Dans cette formule, nous pouvons définir deux facteurs principaux : le poids des entrées et l'ordonnée à l'origine. Le poids des entrées est un nombre qui multiplie la valeur de la variable indépendante (°C) pour déterminer son effet sur la valeur de la variable dépendante (°F). Dans ce cas, le poids des entrées est 1.8. L'ordonnée à l'origine est un nombre qui est ajouté au produit du poids des entrées par la valeur de la variable indépendante pour déterminer la valeur de la variable dépendante lorsque la variable indépendante est égale à zéro. Dans ce cas, l'ordonnée à l'origine est 32. #images( filename:"images/celsius-fahrenheit.png", caption: [Relation enter deux échelles de température Celsius et Fahrenheit.], width: 50% // ref: ) Ces exemples montrent comment utiliser une fonction linéaire pour convertir la température de Celsius en Fahrenheit. Mais comment utiliser une fonction linéaire pour comprendre le concept de coût et d'optimisation dans l'apprentissage profond ? Dans l'apprentissage profond, nous utilisons des fonctions linéaires pour produire des résultats basés sur un ensemble d'entrées. Chaque entrée a un poids qui ajuste la mesure de son impact sur le résultat produit. Ensuite, nous utilisons une fonction de coût pour mesurer la différence entre les résultats produits et les résultats cibles. Ensuite, nous utilisons un algorithme d'optimisation#cite("Goodfellowetal2016","kingma2014adam") pour ajuster les poids des entrées afin de réduire la valeur de la fonction de coût. Comme première étape dans l'apprentissage profond, nous devons collecter un ensemble de données qui forment des paires d'entrées et de résultats cibles. Dans l'exemple de conversion de la température de Celsius en Fahrenheit, nous utilisons un tableau avec des mesures différentes de température dans les deux systèmes comme des paires d'entrées et de résultats cibles : #figure( tablex( columns: 2, align: center + horizon, auto-vlines: false, repeat-header: false, [*température en Celsius °C*], [*température en Fahrenheit °F *], [-40 ],[ -40 ], hlinex(stroke: 0.25pt), [-20 ],[ -4 ], hlinex(stroke: 0.25pt), [ 0 ],[ 32 ], hlinex(stroke: 0.25pt), [ 20 ],[ 68 ], hlinex(stroke: 0.25pt), [ 40 ],[ 104 ], hlinex(stroke: 0.25pt), [ 60 ],[ 140 ], hlinex(stroke: 0.25pt), [ 80 ],[ 176 ], hlinex(stroke: 0.25pt), [ 100],[ 212 ], ), caption: [Conversion de températures entre Celsius et Fahrenheit], kind: "tabl", supplement: [#text(weight: "bold","Table")], ) Ce tableau nous permet de comparer la valeur de la température en Celsius avec sa valeur correspondante en Fahrenheit. Mais que se passe-t-il si nous voulons convertir une valeur qui n'est pas dans le tableau ? Pouvons-nous trouver le poids des entrées et la coupe de l'axe qui convient pour représenter ces données ? La réponse est oui, mais pas facilement. Si nous essayons de deviner le poids des entrées et la coupe de l'axe au hasard, nous obtiendrons des résultats différents des résultats cibles. Par exemple, si nous supposons que le poids des entrées est de $2$ et que la coupe de l'axe est de $0$, notre fonction sera: $ F = (C × 1) + 0 $ Cette fonction donne des résultats imprécis. Par exemple, si nous voulons convertir $20°C$ en Fahrenheit, elle donne#cite("Activation"): $ F = (20 × 1) + 0 = 20 $ Et c'est une erreur car la valeur correcte est $68°F$. #images( filename:"images/temperaturesPrevuesReelles.svg", caption:[L'écart entre les températures prévues et réelles.], width: 50% // ref: ) Alors, comment trouvons-nous le poids des entrées et la coupe de l'axe corrects ? C'est là que l'apprentissage en profondeur intervient. L'apprentissage en profondeur utilise un algorithme appelé régression pour trouver les meilleures valeurs pour ces deux facteurs afin de réduire l'écart entre les résultats générés et les résultats cibles. Cet écart est appelé fonction de coût ou fonction d'erreur. === Erreur quadratique moyenne $E$. La fonction de coût est une fonction mathématique mesurée entre zéro et la valeur maximale possible. Plus la valeur de la fonction de coût est proche de zéro, plus les résultats générés sont proches des résultats cibles. Par exemple, nous utilisons la fonction de coût appelée erreur quadratique moyenne $E$, qui calcule la moyenne de toutes les mesures d'erreur quadratique entre chaque résultat généré et chaque résultat cible. $ E = 1/n sum (y - y_0)^2 $ Où $n$ est le nombre de paires d'entrées et de résultats cibles, $y$ (ou $°F$) est la mesure du résultat généré et $y_0$ (ou $°F_0$) est la mesure du résultat cible. Ainsi, si nous utilisons la $E$ pour mesurer l'écart entre une fonction linéaire et un tableau de conversion des températures Celsius en Fahrenheit, la valeur de la $E$ sera : $ E &= 1/n sum (y - y_0)^2\ &= 1/n sum ((w x+b) - y_0)^2\ &= 4480 $ Il s'agit d'une explication de l'algorithme de descente de gradient#cite("Goodfellowetal2016") qui est utilisé pour trouver les meilleurs poids d'entrée et les biais afin que la valeur de la fonction de coût soit réduite à zéro. Cela se fait en commençant par des poids et des biais aléatoires, puis en les mettant à jour fréquemment en se déplaçant dans la direction opposée du gradient de la fonction de coût. === Algorithme de descente de gradient. Le gradient est un vecteur qui indique la direction dans laquelle la fonction de coût augmente. En se déplaçant dans la direction opposée, nous pouvons trouver le point le plus bas de la fonction de coût, qui correspond aux meilleures valeurs pour les poids et les biais. La règle de mise à jour pour les poids et les biais est donnée par#cite("rumelhart1986learning"): $ w_(n+1) = w_n - epsilon (∂E)/(∂w) $ $ b_(n+1) = b_n - epsilon (∂E)/(∂b) $ Où $epsilon$ est appelé taux d'apprentissage et est un petit nombre positif qui contrôle la taille du pas que nous prenons à chaque itération pour réduire la différence entre les résultats attendus et initiaux. $(∂E)/(∂w)$ et $(∂E)/(∂b)$ sont les dérivées partielles de la fonction de coût par rapport aux poids et aux biais respectivement. Ces dérivées partielles nous disent dans quelle mesure la fonction de coût change lorsque le poids ou le biais change légèrement. Pour calculer ces dérivées partielles, nous pouvons utiliser une technique appelée règle de chaîne#cite("spivak1967calculus"), qui nous permet de décomposer une fonction complexe en fonctions plus simples et de multiplier leurs dérivées. Par exemple, si nous avons une fonction $f (x) = g (h (x))$, où g et h sont des fonctions plus simples, nous pouvons écrire: $ (∂f)/(∂x) = (∂g)/(∂h) * (∂h)/(∂x) $ En utilisant cette technique, nous pouvons trouver les dérivées partielles de $E$ par rapport à $w$ et $b$ comme suit: $ (∂E)/(∂w) &= 1/n sum -2x (y - y_0) \ (∂E)/(∂b) &= 1/n sum -2 (y - y_0) $ Soit $epsilon = 2epsilon/n$ car $epsilon$ est un nombre arbitraire. Cela signifie que vous pouvez simplifier les formules en éliminant le facteur $2/n$, ce qui ne change pas le sens de l'algorithme dans cette cas. $ w_(n+1) &= w_n + α sum x (y - y_0) \ b_(n+1) &= b_n + α sum (y - y_0) $ Où $x$ est la valeur d'entrée $°C$, $y_0$ est la valeur cible de sortie $°F$ et $y$ est la valeur de sortie obtenue en utilisant notre fonction linéaire. En utilisant ces formules, on peut mettre à jour notre poids et notre biais à chaque itération jusqu'à ce qu'on atteigne un point où la fonction de coût est réduite au minimum#cite("rumelhart1986learning","lecun2015deep"). Et on peut programmer un code simple en langage $CC$ qui effectue cette tâche (voir Annexe). Dans l'entraîner de ce modèle, on a utilisé un ensemble de données d'entraînement (td) qui contient des paires de températures en Celsius et en Fahrenheit, et qui cherche à apprendre la formule de conversion entre ces deux unités. La formule exacte est $y =9/5 x + 32$, où $y$ est la température en Fahrenheit et $x$ est la température en Celsius. On a initialisé les paramètres du modèle à des valeurs aléatoires proches de zéro, et on a lancé la descente de gradient pour $100 000$ itérations. A chaque $10 000$ itérations, on a affiché l'évolution de la fonction de coût et des paramètres du modèle. Après $100 000$ itérations, on a obtenu les résultats suivants : - Fonction de coût : $0.009562$ - Poids : $1.801169$ - Biais : $31.883127$ On peut voir que les paramètres du modèle sont très proches des valeurs exactes de la formule de conversion. Pour tester la performance du modèle, on a utilisé une nouvelle température $50C$ qui n'est l'entrainner pas et on obient une temperature de $121.94F$, On a calculé l'erreur moyenne absolue (E) entre les prédictions du modèle et les valeurs réelles. On a obtenu un E de $0.029°C$, ce qui montre que le modèle est très précis et qu'il a bien appris la formule de conversion. On peut visualiser les résultats du modèle sur un graphique qui montre la relation entre les températures en Celsius et en Fahrenheit. On peut voir que les points sont alignés sur une droite qui correspond à la formule $y = 1.8x + 32$. On peut également comparer le modèle avec un modèle aléatoire qui prédit des valeurs aléatoires entre $-40°C$ et $100°C$. On peut voir que le modèle aléatoire a un E beaucoup plus élevé que le modèle entraîné. On peut conclure que le modèle de régression linéaire#footnote[https://en.wikipedia.org/wiki/Linear_regression]<wikipediaLinearRegression>, #footnote[https://fr.wikipedia.org/wiki/R%C3%A9gression_lin%C3%A9aire]<wikipediaLinearRegressionfr>, #footnote[https://fr.wikipedia.org/wiki/Algorithme_du_gradient]<wikipediaAlgorithmeDuGradient> est capable de générer des prédictions très proches des valeurs réelles, et qu'il a réussi à apprendre la formule de conversion entre les températures en Celsius et en Fahrenheit. Ce modèle pourrait être utilisé pour convertir des températures dans d'autres unités, comme les kelvins ou les degrés Rankine. /* * = CONCLUSION. * Dans ce chapitre, on a vu ce qu'est le deep learning, comment il fonctionne. On * a appris que le deep learning est une branche de machine learning qui utilise * des réseaux de neurones artificiels multicouches pour apprendre à partir de * données complexes ou de haute dimension. On a vu que le deep learning se * distingue de l'apprentissage traditionnel par le fait qu'il ne repose pas sur * des règles ou des algorithmes prédéfinis, mais qu'il peut générer ses propres * règles et algorithmes par essai et erreur#cite("Goodfellowetal2016"). On a aussi vu * que le deep learning peut surmonter certains des problèmes rencontrés par * l'apprentissage traditionnel, tels que le bruit, le manque ou le changement des * données. * * On a également compris le principe de l'apprentissage profond en utilisant des * exemples de notre vie quotidienne. On a vu comment on peut utiliser une * fonction mathématique appelée *fonction coût* pour mesurer la différence entre * les résultats d'un modèle d'apprentissage et les résultats souhaités ou * corrects. Puis on a vu comment on peut utiliser une autre fonction appelée * *fonction optimisation* pour ajuster la valeur de chaque cellule neuronale dans * le réseau d'apprentissage afin de réduire la valeur de la *fonction coût*. Ces * étapes sont répétées sur un grand ensemble de données jusqu'à ce que le modèle * d'apprentissage soit capable d'accomplir les tâches demandées avec précision ou * acceptabilité. * * On a aussi exploré les réseaux de neurones artificiels, qui sont des modèles * d'intelligence artificielle qui utilisent des cellules nerveuses artificielles * pour convertir les entrées en sorties<wikiDeeplearning>. On a vu comment chaque * cellule nerveuse reçoit des signaux d'autres cellules et envoie des signaux à * d'autres cellules. Chaque signal est ajouté à une valeur de poids qui détermine * sa force et son importance. Chaque cellule nerveuse calcule la somme des * signaux reçus et applique une fonction d'activation pour produire un signal de * sortie. * * Enfin, on a donné un exemple de deep learning dans la pratique en utilisant un * code simple en langage C qui effectue une régression linéaire pour convertir la * température de Celsius en Fahrenheit. On a vu comment on peut collecter un * ensemble de données qui forment des paires d'entrées et de résultats cibles, * comment on peut initialiser les paramètres du modèle à des valeurs aléatoires * proches de zéro, comment on peut lancer la descente de gradient pour mettre à * jour les paramètres du modèle à chaque itération, et comment on peut tester la * performance du modèle sur une nouvelle température qui n'est pas dans * l'ensemble d'entraînement. * * On peut conclure que le deep learning est un domaine récent et prometteur en * informatique qui mérite l'attention et la recherche, et qui peut contribuer à * résoudre de nombreux problèmes dans différents domaines tels que la traduction, * la reconnaissance d'images et de sons, etc. Le deep learning permet aux * systèmes de regrouper les données et de faire des prédictions avec une * précision incroyable. Le deep learning s'inspire de la structure du cerveau * humain et tente de tirer des conclusions similaires à celles que les humains * feraient en analysant continuellement les données avec une structure logique * donnée. Le deep learning utilise des structures multicouches d'algorithmes * appelées réseaux neuronaux, qui peuvent extraire les sens et les motifs cachés * dans les données sans avoir besoin d'intervention humaine<wikiDeeplearning>. * #finchapiter * * = RÉFÉRENCES BIBLIOGRAPHIQUES. * // #counter(heading).step() */ == Images et Deep Learning. Les images tridimensionnelles qui portent des informations vitales sur la santé humaine sont connues sous le nom d'images scanner (CT scan) et sont utilisées dans le diagnostic et le traitement de nombreuses maladies telles que le cancer, les accidents vasculaires cérébraux et les fractures#cite("aggarwal2018neural"). Ces images nécessitent un traitement spécial pour éliminer les distorsions, améliorer la qualité et extraire les caractéristiques importantes #cite("zhang2023dive"). C'est pourquoi on utilise des réseaux de neurones artificiels avancés capables de traiter efficacement ces images. Les réseaux de neurones artificiels sont un système inspiré du fonctionnement des cellules du cerveau dans le traitement de l'information et se composent d'un ensemble de cellules nerveuses qui reçoivent et envoient des signaux en utilisant des fonctions d'activation, des poids et des biais. Le réseau de neurones se compose de plusieurs couches, y compris la couche d'entrée(input layer), la couche de sortie (output layer) et les couches cachées (hidden layers). Chaque couche étant composée d'un ensemble de cellules nerveuses. La première couche joue le rôle de récepteur des données et la dernière joue le rôle de sortie des données du réseau, et entre elles il y a plusieurs couches qui jouent le rôle de récepteur des signaux des couches précédentes et de les envoyer aux couches suivantes. Cette étude vise à passer en revue les principaux types de réseaux de neurones utilisés dans le domaine de l'imagerie médicale, en particulier les images scanner. Elle vise également à expliquer l'importance des matrices dans le stockage et la mise à jour des paramètres dans un réseau de neurones, en mettant en lumière un exemple d'un réseau de neurones écrit avec des matrices et des vecteurs. === Fonctions d'activation. Dans cette exemple, nous avons vu comment l'apprentissage profond prédit la température Fahrenheit en utilisant une seule cellule nerveuse basée sur les données initiales uniquement. La solution requise était une équation pour une ligne droite qui pouvait être représentée par une ligne droite. Mais dans certains cas, la distribution des données est courbe comme une fonction sinus ou autre, et ne peut pas être représentée par une ligne droite. Nous avons donc besoin d'ajouter des fonctions non linéaires appelées fonctions d'activation, qui aident à plier la courbe linéaire générée par les cellules nerveuses en utilisant la puissance de leur poids et de leur biais#cite("Goodfellowetal2016"). #images( filename:"images/activation.png", caption: [Graphique de la fonction Unité Linéaire Rectifiée *ReLU*], width: 70% // ref: ) L'une des fonctions d'activation les plus simples est l'unité linéaire rectifiée, ou fonction *ReLU*, qui est une fonction linéaire par morceaux qui renvoie zéro si son entrée est négative et renvoie directement l'entrée sinon: $ f(x) = max(0,x) $ La fonction *ReLU* est souvent utilisée dans les réseaux d'apprentissage en profondeur pour ajouter de la non-linéarité au modèle. Cette non-linéarité permet au réseau neuronal d'apprendre des relations complexes entre les entrées et les sorties et d'éviter le surajustement des données d'entraînement. #images( filename:"images/relu.png", caption: [Graphique de la fonction Unité Linéaire Rectifiée *ReLU*], width: 70% // ref: ) Il existe plusieurs d'autres fonctions d'activation populaires en deep learning. Les plus courantes sont: - *Sigmoid* : $f(x)=1/(1+e^(-x))$ - *Tanh* : $f(x)=tanh(x)=(e^x-e^(-x))/(e^x+e^(-x))$ === L'importance des matrices dans l'apprentissage profond. Les matrices sont un moyen efficace de stocker et mettre à jour les paramètres dans un réseau de neurones. Plus le nombre de cellules et de liens dans un réseau de neurones est élevé, plus le nombre de paramètres à modifier pour améliorer les performances du réseau est élevé. Nous utilisons donc des matrices pour éviter d'écrire des lignes de code répétitives pour corriger chaque paramètre individuellement. Au lieu de cela, nous utilisons des boucles itératives et des opérations algébriques sur les matrices pour mettre à jour les paramètres plus rapidement et plus simplement#cite("bishop2006pattern"). #images( filename:"images/4-nerons.svg", caption:[Un réseau de neurones simple.], width: 40% // ref: ) Soit un réseau de neurones avec deux entrées, une sortie et une couche cachée. Ce réseau contient 4 neurones et 12 paramètres. Si on ajoute des couches cachées supplémentaires, on augmente le nombre de variables. Cela complexifie les équations et les matrices. On utilise pas des fonctions d'activation pour simplifier le calcul. Le but est de faciliter la traduction du réseau en matrices, avant de le coder dans un langage de programmation. // edit L'euquation de prédication $y$ c'est comme suit: $ y = a_1^((1))+a_2^((1))+a_3^((1))+a_4^((1)) $ Avec $ a_1^((1)) &= w_11^((1)) x_1 + w_21^((1)) x_2 + b_1^((1)) \ a_2^((1)) &= w_12^((1)) x_1 + w_22^((1)) x_2 + b_2^((1)) \ a_3^((1)) &= w_13^((1)) x_1 + w_23^((1)) x_2 + b_3^((1)) \ a_4^((1)) &= w_14^((1)) x_1 + w_24^((1)) x_2 + b_4^((1)) $ et finalemet: $ y = ( mat(x_1, x_2) mat( w_11^((1)), w_12^((1)) , w_13^((1)), w_14^((1)); w_21^((1)), w_22^((1)) , w_23^((1)), w_24^((1)); ) + mat( b_1^((1)) , b_2^((1)) , b_3^((1)) , b_4^((1)); ) ) vec(1, 1, 1, 1) $ L'ajout de couches cachées dans les réseaux de neurones peut compliquer la fonction de prédiction $y$ en augmentant le nombre de matrices de dimensions différentes. Les couches cachées sont considérées comme des activations qui reçoivent des signaux des couches précédentes et les modifient. Cela peut donner lieu à des fonctions imbriquées /* * , que l'on peut symboliser par l'équation suivante : * $ y = a_1(a_2(a_3(...(x)))) $. * */ == Types de réseaux de neurones. // melonge ces lignes: Les réseaux de neurones peuvent être classés en plusieurs types selon la structure et les applications utilisées. Les réseaux de neurones peuvent être multicouches (MLP), récurrents (RNN), convolutionnels (CNN), et d'autres types. Le type de réseau de neurones est choisi en fonction du problème posé et des données disponibles#cite("lecun2015deep"). == Conversion d'images en vecteurs pour l'analyse par réseaux neuronaux. La détection des nodules pulmonaires à l'aide du deep learning repose sur le traitement d'images, spécifiquement des scans de poumons. Ces images, représentées en matrices de pixels, constituent la matière première de notre apprentissage automatique. Chaque pixel de l'image correspond à une valeur qui détermine son intensité ou sa couleur. En exploitant les caractéristiques matricielles de l'image, nous effectuons des opérations comme la rotation ou le filtrage. Par exemple, une rotation de 90 degrés s'obtient en transposant la matrice. Pour filtrer, il suffit de multiplier la matrice de l'image par un masque, aussi appelé noyau, contenant des coefficients définissant l'effet recherché, tels qu'une amélioration de la netteté ou une détection de contours. Nos réseaux neuronaux nécessitent des vecteurs en entrée et en sortie - des matrices en une dimension. Cette configuration simplifie les calculs et garantit la compatibilité entre les couches du réseau. Pour transformer notre image en un tel vecteur, nous la redimensionnons en fonction de la taille attendue par le réseau, ensuite nous l’aplatissons en une ligne ou une colonne, et enfin, nous la normalisons, pour que ses valeurs soient allant de 0 à 1. Ces étapes permettent de réduire le nombre de paramètres à prendre en compte et d'améliorer ainsi l'efficacité de notre réseau. Représenter les images en tant que matrice, opérer sur elles grâce à ces caractéristiques matricielles et les transformer en vecteurs pour les intégrer à notre réseau neuronal, sont des étapes cruciales dans l'exploitation du Deep Learning pour la détection de nodules pulmonaires avec l'ensemble de données Luna16. == Conclusion. Après avoir exploré les principes fondamentaux du deep learning, la façon dont les réseaux neuronaux artificiels fonctionnent et le rôle des matrices dans cet apprentissage profond, nous avons pu comprendre l'importance de transformer les données d'images en vecteurs pour leur analyse par les réseaux de neurones. Ce processus s'avère d'une grande importance pour la détection des nodules pulmonaires sur l'ensemble de données Luna16. Nous avons discuté en profondeur du fonctionnement des réseaux de neuronaux artificiels, moteurs du Deep Learning, capables d'extraire et d'interpréter des motifs complexes dans les données. Les matrices jouent un rôle central, stockant et mettant à jour les paramètres dans les réseaux neuronaux. Le processus de transformation des images en vecteurs, pour leur analyse par les réseaux neuronaux, a également été souligné. Cette transformation facilite l'intégration des images dans le réseau et optimise son efficacité. En plus de cela, nous avons également utilisé un autre modèle pour classer les nodules comme probablement normaux ou anormaux. Ce modèle a également été confronté à des défis similaires en termes de diversité des nodules et de distribution inégale dans l'ensemble de données. En résumé, le Deep Learning, grâce à sa capacité à traiter et analyser des images et sa grande adaptabilité, s'impose comme un outil essentiel dans la détection des nodules pulmonaires. L'utilisation de l'ensemble de données _LIDC-IDRI_ présente un potentiel énorme pour améliorer la précision et la rapidité des diagnostics, contribuant de manière significative à la lutte contre le cancer du poumon. #finchapiter
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/type_check/annotation_fn.typ
typst
Apache License 2.0
/// - fn (function): The `fn`. /// - max-repetitions (int): The `max-repetitions`. /// - repetitions (int): The `repetitions`. /// - args (any): The `args`. #let touying-fn-wrapper(fn, max-repetitions: none, repetitions: none, ..args) = none
https://github.com/Dherse/typst-brrr
https://raw.githubusercontent.com/Dherse/typst-brrr/master/samples/typst-ansi_render/demo.typ
typst
#import "ansi_render.typ": * #ansi_render( "\u{1b}[38;2;255;0;0mThis text is red.\u{1b}[0m \u{1b}[48;2;0;255;0mThis background is green.\u{1b}[0m \u{1b}[38;2;255;255;255m\u{1b}[48;2;0;0;255mThis text is white on a blue background.\u{1b}[0m \u{1b}[1mThis text is bold.\u{1b}[0m \u{1b}[4mThis text is underlined.\u{1b}[0m \u{1b}[38;2;255;165;0m\u{1b}[48;2;255;255;0mThis text is orange on a yellow background.\u{1b}[0m " ) #ansi_render( "\u{1b}[38;5;196mRed text\u{1b}[0m \u{1b}[48;5;27mBlue background\u{1b}[0m \u{1b}[38;5;226;48;5;18mYellow text on blue background\u{1b}[0m \u{1b}[7mInverted text\u{1b}[0m \u{1b}[38;5;208;48;5;237mOrange text on gray background\u{1b}[0m \u{1b}[38;5;39;48;5;208mBlue text on orange background\u{1b}[0m \u{1b}[38;5;255;48;5;0mWhite text on black background\u{1b}[0m" ) #ansi_render( "\u{1b}[31;1mHello \u{1b}[7mWorld\u{1b}[0m \u{1b}[53;4;36mOver and \u{1b}[35m Under! \u{1b}[7;90mreverse\u{1b}[101m and \u{1b}[94;27mreverse" ) // uses the font supports ligatures #ansi_render(read("test.txt"), font: "CaskaydiaCove Nerd Font Mono", theme: terminal_themes.putty) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.Campbell) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("Campbell Powershell")) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.Vintage) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("One Half Dark")) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("One Half Light")) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("Solarized Dark")) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("Solarized Light")) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("Tango Dark")) #ansi_render(read("color.txt"), size: 10pt, theme: terminal_themes.at("Tango Light"))
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/show.typ
typst
Apache License 2.0
#show: it => it #show text: it => it #show: rect #show: list.item.with() #show: rect.with(width: 1pt) #show <_>: rect #show "A": rect #show regex("A"): (it) => it #show raw.where(block: true): { rect() } #show { text }: (it) => it
https://github.com/touying-typ/touying
https://raw.githubusercontent.com/touying-typ/touying/main/examples/stargazer.typ
typst
MIT License
#import "../lib.typ": * #import themes.stargazer: * #import "@preview/numbly:0.1.0": numbly #show: stargazer-theme.with( aspect-ratio: "16-9", config-info( title: [Stargazer in Touying: Customize Your Slide Title Here], subtitle: [Customize Your Slide Subtitle Here], author: [Authors], date: datetime.today(), institution: [Institution], logo: emoji.school, ), ) #set heading(numbering: numbly("{1}.", default: "1.1")) #title-slide() #outline-slide() = Section A == Subsection A.1 #tblock(title: [Theorem])[ A simple theorem. $ x_(n+1) = (x_n + a / x_n) / 2 $ ] == Subsection A.2 A slide without a title but with *important* information. = Section B == Subsection B.1 #lorem(80) #focus-slide[ Wake up! ] == Subsection B.2 We can use `#pause` to #pause display something later. #pause Just like this. #meanwhile Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously. #show: appendix = Appendix == Appendix Please pay attention to the current slide number.
https://github.com/rytst/experiment02
https://raw.githubusercontent.com/rytst/experiment02/main/week01/report/main.typ
typst
#import "template.typ": * #show: project.with( title: "KUE-CHIPを用いた公開伴暗号通信の実装(1)", author: "<NAME>", year: "2024", ) #outline(indent: auto, fill: box(width: 1fr, repeat[.])) // start page number #set page(numbering: "1", number-align: center) #counter(page).update(1) = 実験内課題 == 予習問題(前期の復習) 下の手順を参考に2つの整数 x, n に対し Modular(剰余)Mod[x, n] を 求めるアセンブリ語プログラムを作成し,命令毎の動作を説明せよ. このプログラムでは以下のような入出力を想定する. *入力* ``` 180: (X)**H (自然数: 1バイト) 182: (N)**H (自然数: 1バイト) ``` *出力* ``` ACC: Mod[X, N] ``` 与えられた問題を解くプログラムは以下のようになった. ``` 00: 65 LD ACC, (80) 01: 80 02: 6D LD IX, (82) 03: 82 04: A1 SUB ACC, IX 05: 32 BZP 02 06: 02 07: B1 ADD ACC, IX 08: 0F ``` *プログラムの説明* プログラムの手順としては、Xからnを引いていき、それが負数になったら、nを足すことによって剰余を求めるというものである. Xからnを引く際に、繰り返す回数は自然数であるから、Xは $(n times (text("自然数")) + text("整数"))$ という形で表せる. 最後にnを足す理由は、剰余は$n$より小さく、かつ非負である必要があるからである. == 課題01 $op("Mod") [a x]$ を求めるプログラムを作成し、KUECHIPで実行せよ. このプログラムでは以下のような入出力を想定する. *入力* ``` 180: (X)**H (乗数) 182: (N)**H 1B0: (A)**H *(被乗数) ``` *出力* ``` ACC: Mod[AX,N] ``` 与えられた問題を解くプログラムは以下のようになった. ``` 00: C0 EOR ACC, ACC 01: C9 EOR IX, IX 02: B5 ADD ACC, (80) 03: 80 04: A5 SUB ACC, (82) 05: 82 06: 32 BZP 04 07: 04 08: B5 ADD ACC, (82) 09: 82 0A: BA ADD IX, 1 0B: 01 0C: FD CMP IX, (B0) 0D: B0 0E: 3A BN 02 0F: 02 10: 0F HLT ``` *プログラムの説明* このプログラムでは、Mod演算が足し算に対して不変であることを利用する. @experiment すなわち、 $ s_0 = 0, s_(i+1) = op("Mod") [s_i + x,n] $ としたとき $ op("Mod") [a x, n] &= s_a $ を利用する. よって、期待する出力であるMod[AX,N]を得るためには、$s_i$の$i$が$A$となるまで $ s_(i+1) = op("Mod") [s_i + x,n] $ を計算していけば良い. このプログラムではIXで$s_i$の$i$をカウントし、ACCに$s_i$を格納して計算を行っている. ここで、予習問題にて作成したMod[x,n]を求めるプログラムを利用し、$op("Mod") [s_i + x,n]$を求めている. == 課題02 3つの整数$x, k, n$に対し、$op("Mod") [x^k, n]$を計算するプログラムを実装せよ. このプログラムでは以下のような入出力と作業領域を想定する. *入力* ``` 180: (X) 181: (K) 182: (N) ``` *作業領域* ``` 1B0: (W1)**H (作業領域1: 途中経過 A=Mod[X^p,N], 被乗数) 1C0: (W2)**H (作業領域2: Xの乗算を実行した回数p) ``` *出力* ``` ACC: Mod[X^K, N] ``` 与えられた問題を解くプログラムは以下のようになった. ``` 00: 65 LD ACC, (80) 01: 80 02: 6A LD IX, 1 03: 01 04: 7D ST IX, (C0) 05: C0 06: 75 ST ACC, (B0) 07: B0 08: C0 EOR ACC, ACC 09: C9 EOR IX, IX 0A: B5 ADD ACC, (80) 0B: 80 0C: A5 SUB ACC, (82) 0D: 82 0E: 32 BZP 0C 0F: 0C 10: B5 ADD ACC, (82) 11: 82 12: BA ADD IX, 1 13: 01 14: FD CMP IX, (B0) 15: B0 16: 3A BN 0A 17: 0A 18: 6D LD IX, (C0) 19: C0 1A: BA ADD IX, 1 1B: 01 1C: FD CMP IX, (81) 1D: 81 1E: 3A BN 04 1F: 04 20: 0F HLT ``` *プログラムの説明* このプログラムでは、Mod演算が乗算に対して不変であることを利用する.すなわち、 $ r_0 = 0, r_(i+1) = op("Mod") [r_i x,n] $ としたとき $ op("Mod") [x^k, n] &= r_k $ を利用する. よって、期待する出力であるMod[X^K,N]を得るためには、$r_i$の$i$が$K$となるまで $ r_(i+1) = op("Mod") [r_i x,n] $ を計算していけば良い. このプログラムにおいて、課題01において作成したMod[ax,n]を利用し、$r_(i+1) = op("Mod") [r_i x,n]$ を求めている. また、このプログラムではIX, ACCをMod[AX,N]の計算を行う上で必要となるため、$r_i$の$i$は作業領域1C0に格納しておき、$r_i$は作業領域1B0に格納しておく. この作業領域1C0に格納している$i$の値が$K$になるまで処理を繰り返すことで$r_k$を求めることができる. == 課題03 課題02をプログラム領域のアドレス080H以下に実装し、分岐命令BAを使い、ルーチンとして2つの数値を連続して暗号化し、メモリに保存するプログラムを作成せよ. このプログラムでは以下のような入出力と作業領域を想定する. *入力* ``` 170: (D) 02H 0FH (データ) 181: (K) 05H (公開鍵) 182: (N) 5BH (共通鍵) ``` *作業領域* ``` 150: (LN)**H (作業領域: 残り繰り返し回数) 180: (X)**H (作業領域: 暗号化するデータの一時保存) ``` *出力* ``` 190: (EN) 20H 47H (暗号化データ) ``` 与えられた問題を解くプログラムは以下のようになった. ``` 00: 6A LD IX, 1 01: 01 02: 7D ST IX, (50) 03: 50 04: 67 LD ACC, (IX+70) 05: 70 06: 75 ST ACC, (80) 07: 80 08: 30 BA 80 09: 80 0A: 6D LD IX, (50) 0B: 50 0C: 77 ST ACC, (IX+90) 0D: 90 0E: AA SUB IX, 1 0F: 01 10: 32 BZP 02 11: 02 12: 0F HLT # Subroutine 80: 65 LD ACC, (80) 81: 80 82: 6A LD IX, 1 83: 01 84: 7D ST IX, (C0) 85: C0 86: 75 ST ACC, (B0) 87: B0 88: C0 EOR ACC, ACC 89: C9 EOR IX, IX 8A: B5 ADD ACC, (80) 8B: 80 8C: A5 SUB ACC, (82) 8D: 82 8E: 32 BZP 8C 8F: 8C 90: B5 ADD ACC, (82) 91: 82 92: BA ADD IX, 1 93: 01 94: FD CMP IX, (B0) 95: B0 96: 3A BN 8A 97: 8A 98: 6D LD IX, (C0) 99: C0 9A: BA ADD IX, 1 9B: 01 9C: FD CMP IX, (81) 9D: 81 9E: 3A BN 84 9F: 84 A0: 30 BA 0A A1: 0A ``` *プログラムの説明* 課題02で作成した000Hからのプログラム領域に格納したプログラムを080H以下に格納し、サブルーチンとして実装しておく. これにより、適切なデータ領域(180H)に引数が与えられれば、その引数(180Hに格納されたデータ)を暗号化するような関数として動作する. この関数を2回呼び出すことによって、データ領域の連続した値(170H, 171H)を暗号化して、連続したデータ領域(190H, 191H)に出力することができる. このプログラムにおいてまず、IXに1を格納し、171H(170H+IX)のデータから読みこみ、180H領域に引数としてセットし、関数を呼び出し、1つ目のデータを暗号化し191H(190H+IX)に格納する.その後、IXの値をデクリメントし、170H(170H+IX)のデータに対しても同様の処理を行うことで、暗号化したデータを190H(190H+IX)に格納する. = 考察 == 考察課題01 予習問題, 課題01,課題02 で実装したプログラムの計算量を評価せよ.命令回数を a, x, k, n 等を用いて定量的に評価すること(例えば, $op("O") (a x^2 k n)$ 等のように表す). === 考察 ==== 予習問題 まず最初に予習問題のプログラムの計算量について考える. このプログラムでは、$x$ から $n$ を負になるまで繰り返し引いていくので、繰り返しの回数は $ floor(x / n) + 1 $ となる.ここで、$x$ が $n$ で割り切れる場合もこの回数分繰り返しが行われることに注意する. よって、このプログラムの計算量は $op("O") (x / n)$ となる. ==== 課題01 次に課題01のプログラムの計算量について考える. このプログラムでは、 $ s_(i+1) = op("Mod") [s_i + x,n] $ を$s_a$を得るまで繰り返す.よって、$op("Mod") [s_i + x,n]$を$a$回繰り返す. ここで、$op("Mod") [s_i + x,n]$の計算について、$0 <= s_i < n$であるから、 $0 <= s_i / n < 1$ となる. よって、 $ op("O") ((s_i + x) / n) = op("O") (s_i / n + x / n) = op("O") (x / n) $ よって、課題01のプログラムの計算量は $op("O") ((a x) / n)$ となる. ==== 課題02 最後に課題02のプログラムの計算量について考える. このプログラムでは、 $ r_(i+1) = op("Mod") [r_i x,n] $ を$r_k$を得るまで繰り返す.よって、$op("Mod") [r_i x,n]$ を $k$ 回繰り返す. ここで、$0 <= r_i < n$ であるから $ 0<= r_i / n < 1$ である.よって、$op("Mod") [r_i x,n]$ の計算量は $ op("O") ((r_i x) / n) = op("O") (r_i / n dot x) = op("O") (x) $ よって、課題02の計算量は $op("O") (k x)$ となる. == 考察課題02 課題01において,$op("Mod") [a x, N]$の値を,まず$a x$の計算を行った後,Nによる剰余を求めることにより計算した場合,課題1の方法で計算したときとどのような違いがあるか考察せよ. === 考察 $op("Mod") [a x, N]$の値を求める際に、先に $a x$ の乗算を行った後に $a x$ の$N$による剰余を求める場合、$a x$ の計算結果がオーバーフローしてしまい、その後の $N$ による剰余の計算において正常な出力ができなくなってしまう可能性がある. そこで、課題01のように $ s_(i+1) = op("Mod") [s_i + x,n] $ を繰り返し求めることで、$s_a$ を求める方法では、各$s_i$を計算したとき、$s_i$は常に$0$ 以上 $n -1$以下となるので、次に計算すべき$s_(i+1)$の計算において、$s_i + x$ がオーバーフローする可能性を小さくすることができる. #[ #set text(lang: "en") #bibliography(title: "参考文献", style:"ieee", "bib.yaml") ]
https://github.com/lkndl/typst-bioinfo-thesis
https://raw.githubusercontent.com/lkndl/typst-bioinfo-thesis/main/modules/figures.typ
typst
#let default-2D-align = top + right #let as-ratio(number) = { eval(str(number * 100) + "%") } #let unravel(funcs, poss, nameds, body) = { assert(funcs.len() == poss.len() and poss.len() == nameds.len(), message: "whoops") if funcs.len() == 0 { return body } let (f, p, n) = (funcs.pop(), poss.pop(), nameds.pop()) unravel(funcs, poss, nameds, f(..p, ..n)[#body]) } #let nest(stuff, body) = { if stuff in (none, ()) or type(stuff) != array { return body } let thing = stuff.pop() if type(thing) != arguments { return body } let func = thing.pos().at(0) let args = arguments(..thing.pos().slice(1), ..thing.named()) nest(stuff, func(..args)[#body]) } #let floaty(thing, args) = { if args != none { place( ..args, thing ) } else { thing } } // This is the function / show rule that styles figure captions. #let caption-styles( supplement-position: "left", // container: ((box,), ((),), ((:),)), container: (arguments(box,)), body) = { assert(supplement-position in ("left", "inline", "above")) // left-aligned, not wider than the outer scope. show figure.caption: it => { let style(body) = { set text(size: 10pt) set par(leading: .6em) set align(left + top) body } if supplement-position == "inline" { nest(container)[#show: style; *#it.supplement #it.counter.display(it.numbering):* #it.body] } else { nest(container)[ #show: style #let named = { if supplement-position == "left" { (columns: (auto, 1fr), gutter: 4pt) } else { assert(supplement-position == "above") (rows: (auto, auto), gutter: 1em) } } #grid( ..named, [*#it.supplement #it.counter.display(it.numbering):*], it.body) ] } } body } #let expand-to-2D-alignment(ali, default) = { assert(type(ali) == alignment) let ali = { if ali.y == none { default.y } else { ali.y } } + { if ali.x == none { default.x } else { ali.x } } return ali } #let wrap-fig( fig: none, width: none, caption: [], label: none, position: default-2D-align, gutter: 1em, supplement-position: "left", ..named, body ) = { // we're actually building a two-column grid for the figure and the text beside it let ali = expand-to-2D-alignment(position, default-2D-align) assert(ali.x != center, message: "That's a bit weird! Can't center a wrapfig") let col-widths = (auto, width) let columns = ([#body], [ // if the caption style is supposed to be changed, it must be re-applied in the current scope #show: caption-styles.with(supplement-position: supplement-position) #figure( fig, caption: caption, ..named, ) #label ]) // if the figure goes to the left, flip the columns if ali.x == left { col-widths = col-widths.rev() columns = columns.rev() } block[ #set align(ali.y) // this sets the vertical alignment between figure and text. #grid( columns: col-widths, gutter: gutter, ..columns ) ] } #let side-cap-fig( fig: none, fig-width: none, caption-width: none, caption-pos: default-2D-align, caption: [], label: none, gutter: 1em, supplement-position: "left", placement: none, ..args, ) = { // move and scale the caption by *styling* it! let cap-width = { let t = type(caption-width) if t == ratio { // re-scale the caption-width when it is a ratio (i.e. in %) so that it applies to the width of the figure parent - not the image! as-ratio(caption-width / fig-width) } else if t == fraction { if type(fig-width) == fraction { // both widths in fr as-ratio(caption-width / fig-width) } else { // only one width in fr => make it full-width as-ratio((100% - fig-width) / fig-width) - gutter } } else if t == relative { // a relative length like "40% + 2em". // keep the 2em and re caption-width.length + eval(str(caption-width.ratio / fig-width * 100) + "%") } else { caption-width } } let ali = expand-to-2D-alignment(caption-pos, default-2D-align) // calculate the horizontal movement let dx = (cap-width + gutter) * { if ali.x == right { 1 } else { -1 } } // apply the move+width+style show: caption-styles.with( supplement-position: supplement-position, container: ( // (place, box), // ((ali,), ()), // ((dx: dx), (width: cap-width))) arguments(place, ali, dx:dx), arguments(box, width: cap-width)) ) // actually this is going to be a grid again let columns = ( [#figure( fig, caption: caption, ..args.named(), ) #label ], [] // the second column is not really necessary ) // the original, user-defined caption width defines the column width! let col-widths = (fig-width, caption-width) // flip if the caption goes on the left if ali.x == left { col-widths = col-widths.rev() columns = columns.rev() } floaty(grid( columns: col-widths, gutter: gutter, ..columns ), placement) }
https://github.com/gdg-cnu/thumbnail-renderer
https://raw.githubusercontent.com/gdg-cnu/thumbnail-renderer/main/using-local-runtime-with-jupyter/main.typ
typst
MIT License
#import "/lib/theme.typ" #show: theme.theme.with() #let ai-data = theme.slide.theme-color.green #let dev = theme.slide.theme-color.blue #let devrel = theme.slide.theme-color.red #let game = theme.slide.theme-color.yellow __PLACEHOLDER_TITLE_DATA__
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/algo/seminars/2024-09-21.typ
typst
= Задача Дано два массива `a` и `b` хотим массив `num` такой, что ``` num[i] = # способов выбрать j, k, что a[j] + a[k] = i ``` == Решение Составим два многочлена: $ A(x) = x^(a_0) + x^(a_1) + ... + x^(a_n) \ B(x) = x^(b_0) + x^(b_1) + ... + x^(b_n) $ Перемножим их
https://github.com/pedrofp4444/BD
https://raw.githubusercontent.com/pedrofp4444/BD/main/report/content/[5] Implementação Física/caracterizaçãoVistas.typ
typst
#let caracterizaçãoVistas = { [ == Definição e caracterização de vistas de utilização em SQL Nesta secção, apresenta-se a definição de um conjunto de vistas essenciais para uma utilização eficiente da base de dados implementada. As vistas foram criadas para fornecer informações relevantes sobre os funcionários e suas características, bem como sobre casos e terrenos, facilitando o trabalho dos detetives e representantes. Para a caracterização destas vistas foram usadas um conjunto de seleções e junções. A primeira vista cria uma tabela virtual que contém informações vitais para a identificação de um funcionário, incluindo o nome e o número de telemóvel, além de dados cruciais para uma compreensão completa dos casos associados a cada funcionário. #align(center)[ #figure( kind: image, caption: [Vista que demonstra todos os funcionários e os seus casos associados.], block( fill: rgb("#f2f2eb"), inset: 8pt, ```sql -- View das informações dos funcionários e dos casos associados CREATE VIEW FuncionariosEmCasos AS SELECT Funcionário.Nome, Número_de_telemóvel.Número_de_telemóvel_ID, Caso.Caso_ID, Caso.Data_de_abertura, Caso.Estado, Caso.Estimativa_de_roubo, Caso.Data_de_encerramento, Caso.Terreno_ID FROM Funcionário INNER JOIN Suspeito ON Funcionário.Funcionário_ID = Suspeito.Funcionário_ID INNER JOIN Caso ON Suspeito.Caso_ID = Caso.Caso_ID LEFT JOIN Número_de_telemóvel ON Funcionário.Funcionário_ID = Número_de_telemóvel.Funcionário_ID; ``` ) ) ] A segunda vista foca-se na utilização pelos representantes, permitindo-lhes acessar de forma exclusiva as informações de identificação de um funcionário, entre elas, o nome, o número de telemóvel, função desempenhada e através de uma função, a idade, assim como os dados relativos aos terrenos aos quais cada funcionário está associado. #align(center)[ #figure( kind: image, caption: [Vista que demonstra todos os funcionários e os seus casos associados.], block( fill: rgb("#f2f2eb"), inset: 8pt, ```sql -- View das informações dos funcionários e dos terrenos associados CREATE VIEW FuncionariosEmTerrenos AS SELECT Funcionário.Nome, Função.Designação, Número_de_telemóvel.Número_de_telemóvel_ID, CalcularIdade(Funcionário.Data_de_nascimento) AS Idade, Funcionário.Salário, Terreno.Terreno_ID, Terreno.Minério_previsto, Terreno.Minério_coletado FROM Funcionário INNER JOIN Trabalha ON Funcionário.Funcionário_ID = Trabalha.Funcionário_ID INNER JOIN Terreno ON Trabalha.Terreno_ID = Terreno.Terreno_ID INNER JOIN Função ON Funcionário.Função_ID = Função.Função_ID LEFT JOIN Número_de_telemóvel ON Funcionário.Funcionário_ID = Número_de_telemóvel.Funcionário_ID; ``` ) ) ] Segue abaixo, um exemplo de formato de utilização de uma das vistas criadas: #align(center)[ #figure( kind: image, caption: [Exemplo de utilização da vista "FuncionariosEmTerrenos".], block( fill: rgb("#f2f2eb"), inset: 8pt, ```sql -- Exemplo de utilização da vista FuncionariosEmTerrenos SELECT * FROM FuncionariosEmTerrenos; ``` ) ) ] ] }
https://github.com/ljgago/typst-chords
https://raw.githubusercontent.com/ljgago/typst-chords/main/examples/chart-chords.typ
typst
MIT License
#import "../lib.typ": * #set document(date: none) #set page(width: auto, height: auto, margin: 0pt) #let chart-chord-sharp = chart-chord.with(size: 18pt) #let chart-chord-round = chart-chord.with(design: "round", size: 1.5em) #rect( stroke: none, radius: 3pt, inset: (x: 10pt, y: 10pt), fill: white, [ #chart-chord-sharp(tabs: "x32o1o", fingers: "n32n1n")[C] #h(2em) #chart-chord-sharp(tabs: "ooo3", fingers: "ooo3")[C] #h(4em) #chart-chord-round(tabs: "xn332n", fingers: "o13421", fret: 3, capos: "115", position: "bottom")[Cm] #h(2em) #chart-chord-round(tabs: "onnn", fingers: "n111", capos: "313", position: "bottom")[Cm] #h(4em) #chart-chord-round(tabs: "xn332n", fingers: "o13421", fret: 3, capos: "115", background: silver)[Cm] #h(2em) #chart-chord-round(tabs: "onnn", fingers: "n111", capos: "313", background: silver)[Cm] ] )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-07.typ
typst
Other
// Edge cases. - Not in list -Nope
https://github.com/pascalguttmann/typst-template-report-lab
https://raw.githubusercontent.com/pascalguttmann/typst-template-report-lab/main/template/chapter/results.typ
typst
MIT License
= Description of the Experiments and Results
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/anti-matter/0.0.1/src/lib.typ
typst
Apache License 2.0
// avoid exporting util #let ( anti-front-end, anti-back-start, anti-outer-counter, anti-inner-counter, anti-active-counter-at, anti-page-at, anti-page, anti-header, anti-thesis, anti-matter, ) = { // TODO: I think the spec could be removed in favor of loc.page-numbering() // validate spec let assert-spec-valid(spec) = { if type(spec) != dictionary { panic("spec must be a dictionary, was " + type(spec)) } if spec.len() != 3 { panic("spec must be exactly 3 elements long, was " + str(spec.len())) } if "front" not in spec { panic("missing front key") } if "inner" not in spec { panic("missing inner key") } if "back" not in spec { panic("missing back key") } } let label-front-end = <anti-matter:front:end> let label-back-start = <anti-matter:back:start> // get matter and correction at given loc let where-am-i(spec, loc) = { let front-matter = query(label-front-end, loc) let back-matter = query(label-back-start, loc) assert.eq(front-matter.len(), 1, message: "Must have exactly one front matter start marker") assert.eq(back-matter.len(), 1, message: "Must have exactly one back matter start marker") let front-matter = front-matter.first().location() let back-matter = back-matter.first().location() let front-matter-end = counter(page).at(front-matter).at(0) let back-matter-start = counter(page).at(back-matter).at(0) if loc.page() <= front-matter.page() { ("front", spec.front, 0) } else if front-matter.page() < loc.page() and loc.page() <= back-matter.page() { ("inner", spec.inner, front-matter-end) } else { ("back", spec.back, back-matter-start - front-matter-end) } } let mark(label) = [#metadata("anti-matter-marker")#label] /// Mark the end of the front matter of your document. let anti-front-end = mark(label-front-end) /// Mark the start of the back matter of your document. let anti-back-start = mark(label-back-start) /// The counter for the front and back matter of your document. let anti-outer-counter = counter("anti-matter:outer") /// The counter for the main content of your document. let anti-inner-counter = counter("anti-matter:inner") /// Returns the active counter at the given loction. /// /// - spec (dictionary): the spec of the document, see @@anti-matter /// - loc (location): the location to get the active counter for /// -> counter let anti-active-counter-at(spec, loc) = { let (matter, _, _) = where-am-i(spec, loc) if matter == "inner" { anti-inner-counter } else { anti-outer-counter } } /// Use the default spec with shared outer numbering and counter. /// /// The dictionary that is returned is simply the numbering for the `front`, `inner` and `back` /// keys. /// /// - outer (string, function): the numbering used for front and back matter /// - inner (string, function): the numbering used for the document's main content /// -> dictionary let anti-thesis(outer: "I", inner: "1") = ( front: outer, inner: inner, back: outer, ) /// Returns the page numbering at the given location with the required adjustments and numbering /// given by the spec. /// /// - spec (dictionary): the spec of the document, see @@anti-matter /// - loc (location): the location at which to evaluate the numbering /// -> content let anti-page-at(spec, loc) = { let (_, num, correction) = where-am-i(spec, loc) let vals = counter(page).at(loc) vals.at(0) = vals.at(0) - correction numbering(num, ..vals) } /// Returns the formatted page number at the given location with the required adjustments and /// numbering given by the spec. /// /// - spec (dictionary): the spec describing the document numbering, see @@anti-matter /// -> content let anti-page(spec) = locate(loc => anti-page-at(spec, loc)) /// Render a page header while maintaining anti-matter counter stepping. /// /// - spec (dictionary): the spec describing the document numbering, see @@anti-matter /// - header (content): the header to render /// -> content let anti-header(spec, header) = { locate(loc => anti-active-counter-at(spec, loc).step()) header } /// A template function that applies the page numbering and a show rule for outline.entry to fix /// it's page numbering. If you need more granular control over outline entries and page headers /// see the library documentation. This can be used for a show rule. The parameters are validated. /// /// - spec (dictionary): the spec describing the document numbering, see @@anti-matter /// - body (content): the content to render with anti-matter numbering /// -> content let anti-matter( spec: anti-thesis(), body, ) = { assert-spec-valid(spec) set page( header: anti-header(spec, none), numbering: (..args) => anti-page(spec), ) show outline.entry: it => { link(it.element.location(), it.body) if it.fill != none { [ ] box(width: 1fr, it.fill) [ ] } else { h(1fr) } link(it.element.location(), anti-page-at(spec, it.element.location())) } body } ( anti-front-end, anti-back-start, anti-outer-counter, anti-inner-counter, anti-active-counter-at, anti-page-at, anti-page, anti-header, anti-thesis, anti-matter, ) }
https://github.com/qujihan/toydb-book
https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter2/mvcc.typ
typst
#import "../../typst-book-template/book.typ": * #let path-prefix = figure-root-path + "src/pics/" == MVCC介绍 MVCC#footnote("Multi-Version Concurrency Control: https://zh.wikipedia.org/wiki/多版本并发控制")是广泛使用的并发控制机制,他为ACID事务提供快照隔离#footnote("https://jepsen.io/consistency/models/snapshot-isolation"),能实现读写并发。快照隔离级别是最高的隔离级别么? 并不是,最高的隔离级别是可串行化隔离级别,但是可串行化隔离级别会导致性能问题,所以快照隔离级别是一个折中的选择。 快照隔离级别会导致写倾斜(Write Skew)问题#footnote("https://justinjaffray.com/what-does-write-skew-look-like/"),但是这个问题在实际中并不常见。详细的讨论可以参考@write-skew。 === MVCC的实现 ToyDB在存储层实现了MVCC,可以使用任何实现了`storage::Engine`存储引擎作为底层存储。在ToyDB中,提供了常见的事务操作: - `begin`: 开始一个新的事务。(可以是只读事务(read only),也可以是读写事务) - `get`: 读取一个key的值 - `set`: 设置一个key的值 - `delete`: 删除一个key的值 - `scan`: 遍历指定范围的key/value对 - `scan_prefix`: 遍历指定前缀的key/value对 - `commit`: 提交一个事务。(保留更改,对其他事务可见) - `rollback`: 回滚一个事务。(丢弃更改) MVCC,顾名思义,是通过多个版本来管理事务的。版本的先后通过`Version`来界定,可以说,`Version`就是一个逻辑时间戳。通过`Version`用来标记每一个写入的`Key`,就可以在一个确定的时刻(`Version`一定的时刻),知道一个`Key`的值是什么。 ```rust // x 表示 tombstone 值 时间(Version) 5 4 a4 3 b3 x 2 1 a1 c1 d1 a b c d Key ``` 上面就是一个例子,在`Version = 2`的时候,可以看到`a`的值是`a1`,`c`的值是`c1`,`d`的值是`d1`。在`Version = 4`的时候,`a`的值是`a4`,`b`的值是`b3`,`c`的值是`c1`。(没提到就是空值) 这里有必要说一下,上面一段话中多次提到`Key`,但是表示有不同的意思。`Key`分为存储引擎中的`Key`和事务管理(MVCC)中的`Key`枚举类。在本书后续部分,大家需要根据上下文来理解。 事务管理的`Key`枚举类的值会通过序列化成存储引擎中的`Key`来存储。这一点对于理解下面MVCC的实现非常重要。关于序列化的实现,会在 @encoding 详细说明#footnote("关于序列化也可以阅读一下: " + "https://research.cs.wisc.edu/mist/SoftwareSecurityCourse/Chapters/3_5-Serialization.pdf"),这里只需要知道实现了`serde`的`Deserialize`和`Serialize`两个`trait`就可以通过`encode()`将一个对象序列化成`vec<u8>`,通过`decode()`把`vec<u8>`反序列化成一个对象就可以了。 另外,通过`serde`的`with = "serde_bytes"`和`borrow`可以将`Cow`类型的数据序列化成`vec<u8>`,这个在`Key`枚举类中会用到。 下面来看一下`Key`枚举类的定义。 #code("toydb/src/storage/mvcc.rs", "Key 枚举类")[ ```rust /// MVCC keys, using the KeyCode encoding which preserves the ordering and /// grouping of keys. Cow byte slices allow encoding borrowed values and /// decoding into owned values. /// MVCC keys, 使用 KeyCode 编码, 保留了 key 的顺序和分组. /// Cow 允许对 borrowed 的值进行编码, 并且解码成 owned 的值. #[derive(Debug, Deserialize, Serialize)] pub enum Key<'a> { /// The next available version. /// 下一个可以使用的 version. NextVersion, /// Active (uncommitted) transactions by version. /// 在给定 version 下, 活动的(未提交的)事务. TxnActive(Version), /// A snapshot of the active set at each version. Only written for /// versions where the active set is non-empty (excluding itself). /// 每个 version 下的活动集的快照. 只有在活动集非空的时候才会写入. TxnActiveSnapshot(Version), /// Keeps track of all keys written to by an active transaction (identified /// by its version), in case it needs to roll back. /// 用于跟踪所有被活动事务(通过 version 标识)写入的 key, 以防需要回滚. TxnWrite( Version, #[serde(with = "serde_bytes")] #[serde(borrow)] Cow<'a, [u8]>, ), /// A versioned key/value pair. /// 一个带有 version 的 key/value 对. Version( #[serde(with = "serde_bytes")] #[serde(borrow)] Cow<'a, [u8]>, Version, ), /// Unversioned non-transactional key/value pairs. These exist separately /// from versioned keys, i.e. the unversioned key "foo" is entirely /// independent of the versioned key "foo@7". These are mostly used /// for metadata. /// 非事务的 key/value 对. 这些和带有 version 的 key 是独立的. /// 例如, unversioned key "foo" 和 versioned key "foo@7" 是完全独立的. /// 这些主要用于元数据. Unversioned( #[serde(with = "serde_bytes")] #[serde(borrow)] Cow<'a, [u8]>, ), } ``` ] 看到这里应该看的一头雾水,不过没有关系,再粗略看一下`KeyPrefix`,然后再统一解释。 #code("toydb/src/storage/mvcc.rs", "KeyPrefix 枚举类")[ ```rust /// MVCC key prefixes, for prefix scans. These must match the keys above, /// including the enum variant index. /// MVCC key 的前缀, 用于前缀扫描. 这些必须和上面的 key 匹配, 包括枚举变量的索引. #[derive(Debug, Deserialize, Serialize)] enum KeyPrefix<'a> { NextVersion, TxnActive, TxnActiveSnapshot, TxnWrite(Version), Version( #[serde(with = "serde_bytes")] #[serde(borrow)] Cow<'a, [u8]>, ), Unversioned, } ``` ] 现在来理解一下`Key`和`KeyPrefix`。它们都实现了`Deserialize/Serialize`这两个trait,所以里面的枚举值就可以序列化和反序列化。换句话说,就是可以将`Key`和`KeyPrefix`中的枚举值序列化成`vec<u8>`,然后存储到存储引擎中。 `NextVersion`:顾名思义,表示的是下一个Version。当事务开始的时候,会从`NextVersion`获取下一个可用的version并且递增它。 `TxnActive`:表示的是活动中事务 `TxnActiveSnapshot`:表示的是活动事务的快照 `TxnWrite`: `Version`: `Unversioned`: 其实在测试用例中说明了问题。 #code("toydb/src/storage/mvcc.rs", "Key 与 KeyPrefix 的测试用例")[ ```rust #[test_case(KeyPrefix::NextVersion, Key::NextVersion; "NextVersion")] #[test_case(KeyPrefix::TxnActive, Key::TxnActive(1); "TxnActive")] #[test_case(KeyPrefix::TxnActiveSnapshot, Key::TxnActiveSnapshot(1); "TxnActiveSnapshot")] #[test_case(KeyPrefix::TxnWrite(1), Key::TxnWrite(1, b"foo".as_slice().into()); "TxnWrite")] #[test_case(KeyPrefix::Version(b"foo".as_slice().into()), Key::Version(b"foo".as_slice().into(), 1); "Version")] #[test_case(KeyPrefix::Unversioned, Key::Unversioned(b"foo".as_slice().into()); "Unversioned")] fn key_prefix(prefix: KeyPrefix, key: Key) { let prefix = prefix.encode(); let key = key.encode(); assert_eq!(prefix, key[..prefix.len()]) } ``` ] #reference-block("Rust中的写时复制")[ 在上面`Key`以及`KeyPrefix`枚举类中多次出现了COW类型,这里简单介绍一下COW。 COW(copy on wirte,写时复制)这是一个非常常见的概念。在Rust中,`Cow`是一个枚举类,有两个值,`Borrowed`和`Owned`,`Borrowed`表示借用,`Owned`表示拥有。 当一个`Cow`是`Borrowed`的时候,它是一个引用,当一个`Cow`是`Owned`的时候,它是一个拥有者。 通过`Cow`可以实现写时复制,也就是说,当一个`Cow`是`Borrowed`的时候,如果需要修改,就会复制一份,然后修改这份拷贝,这样就不会影响原来的数据。 看一下这段代码能简单的理解一下COW。 ```rust use std::borrow::Cow; fn process_data(input: &str, modify: bool) -> Cow<str> { if modify { let mut owned_string = input.to_string(); owned_string.push_str("(modified)"); Cow::Owned(owned_string) } else { Cow::Borrowed(input) } } /* 结果为: Result 1: this is a test string, Address: 0x56a76d9d3213 Result 2: this is a test string, Address: 0x56a76d9d3213 Result 3: this is a test string(modified), Address: 0x56a76f1efb80 */ fn main() { let test_string = "this is a test string"; let result1 = process_data(test_string, false); let result2 = process_data(test_string, false); let result3 = process_data(test_string, true); println!("Result 1: {}, Address: {:?}", result1, result1.as_ptr()); println!("Result 2: {}, Address: {:?}", result2, result2.as_ptr()); println!("Result 3: {}, Address: {:?}", result3, result3.as_ptr()); } ``` ] 看完了 `Key` 和 `KeyPrefix`,就来具体看一下MVCC的实现了。不过还有一个前置点是需要理解ToyDB中`MVCC`与`Transaction`的关系。 先看一下MVCC的代码。 #code("toydb/src/storage/mvcc.rs", "MVCC")[ ```rust /// An MVCC-based transactional key-value engine. It wraps an underlying storage /// engine that's used for raw key/value storage. /// /// While it supports any number of concurrent transactions, individual read or /// write operations are executed sequentially, serialized via a mutex. There /// are two reasons for this: the storage engine itself is not thread-safe, /// requiring serialized access, and the Raft state machine that manages the /// MVCC engine applies commands one at a time from the Raft log, which will /// serialize them anyway. /// 基于 MVCC 的事务键值引擎. 它包装了一个底层的存储引擎, 用于原始的 key/value 存储. /// 虽然它支持任意数量的并发事务, 但是单个读写操作是顺序执行的, 通过互斥锁串行化. /// 有两个原因: 存储引擎本身不是线程安全的, 需要串行访问, 以及管理 MVCC 引擎的 Raft 状态机 /// 会从 Raft 日志中一次应用一个命令, 这样也会将它们串行化. pub struct MVCC<E: Engine> { pub engine: Arc<Mutex<E>>, } impl<E: Engine> MVCC<E> { /// Creates a new MVCC engine with the given storage engine. /// 使用给定的存储引擎创建一个新的 MVCC 引擎. pub fn new(engine: E) -> Self { Self { engine: Arc::new(Mutex::new(engine)) } } /// Begins a new read-write transaction. /// 开始一个新的读写事务. pub fn begin(&self) -> Result<Transaction<E>> { Transaction::begin(self.engine.clone()) } /// Begins a new read-only transaction at the latest version. /// 开始一个新的只读事务, 在最新的 version 下. pub fn begin_read_only(&self) -> Result<Transaction<E>> { Transaction::begin_read_only(self.engine.clone(), None) } /// Begins a new read-only transaction as of the given version. /// 开始一个新的只读事务, 在给定的 version 下. pub fn begin_as_of(&self, version: Version) -> Result<Transaction<E>> { Transaction::begin_read_only(self.engine.clone(), Some(version)) } /// Resumes a transaction from the given transaction state. /// 从给定的事务状态恢复事务. pub fn resume(&self, state: TransactionState) -> Result<Transaction<E>> { Transaction::resume(self.engine.clone(), state) } /// Fetches the value of an unversioned key. /// 获取一个非版本化 key 的值. pub fn get_unversioned(&self, key: &[u8]) -> Result<Option<Vec<u8>>> { self.engine.lock()?.get(&Key::Unversioned(key.into()).encode()) } /// Sets the value of an unversioned key. /// 设置一个非版本化 key 的值. pub fn set_unversioned(&self, key: &[u8], value: Vec<u8>) -> Result<()> { self.engine.lock()?.set(&Key::Unversioned(key.into()).encode(), value) } /// Returns the status of the MVCC and storage engines. /// 返回 MVCC 和存储引擎的状态. pub fn status(&self) -> Result<Status> { let mut engine = self.engine.lock()?; let versions = match engine.get(&Key::NextVersion.encode())? { Some(ref v) => Version::decode(v)? - 1, None => 0, }; let active_txns = engine.scan_prefix(&KeyPrefix::TxnActive.encode()).count() as u64; Ok(Status { versions, active_txns, storage: engine.status()? }) } } /// MVCC engine status. /// MVCC 引擎状态. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Status { /// The total number of MVCC versions (i.e. read-write transactions). /// MVCC 版本的总数(即读写事务). pub versions: u64, /// Number of currently active transactions. /// 当前活动事务的数量. pub active_txns: u64, /// The storage engine. /// 存储引擎. pub storage: super::engine::Status, } ``` ] #reference-block("Rust中transpose")[ `transpose`就是帮助我们将*嵌套的结构*转换成更合适处理的一种结构。比如将`Option<Result<T,E>>`转换成`Result<Option<T>, E>`。这样就可以更方便的同时处理可能的错误(`Result`)以及可能的空值(`Option`)。 看一下下面的例子,可以更好的理解`transpose`的作用。 ```rust fn fetch_data(input: Option<&str>) -> Option<Result<i32, std::num::ParseIntError>> { input.map(|s| s.parse::<i32>()) } fn main() { let data = Some("123"); // 有一个字符串,可能会转换为数字 // 不使用 transpose // 手动处理 Option<Result<i32, E>> let result: Result<Option<i32>, std::num::ParseIntError> = match fetch_data(data) { Some(Ok(value)) => Ok(Some(value)), // 成功解析数字 Some(Err(e)) => Err(e), // 解析时出错 None => Ok(None), // 没有数据 }; // 等价于上面的代码 let result = fetch_data(data).transpose(); // 处理result结果 match result { Ok(Some(value)) => println!("成功解析数字: {}", value), Ok(None) => println!("没有数据"), Err(e) => println!("解析错误: {}", e), } } ``` 在ToyDB中有许多地方使用了`transpose`,这样可以更方便的处理`Option<Result<T, E>>`这种结构。 比如下面这段代码,我感觉非常的优雅: ```rust // scan.next() 返回的是 Option<Result<(key, value), E>> // 为了方便处理, 使用了 transpose(), 将其转换为 Result<Option<(key, value)>, E> // 如果 scan.next() 返回 None, 意味着迭代结束, transpose() 会返回 Ok(None) // 就会跳出循环 // 如果 scan.next() 返回 Some(Err(e)), transpose() 会返回 Err(e) // 并立即中断循环, 错误通过 ? 操作符进行传播 // 如果 scan.next() 返回 Some(Ok((key, value))), transpose() 会返回 Ok(Some((key, value))) // 就会向下处理 while let Some((key, value)) = scan.next().transpose()? { match Key::decode(&key)? { Key::Version(_, version) => { // ... } key => return errdata!("expected Key::Version got {key:?}"), }; } ``` ] 在代码中可以看到,MVCC中更多的对Transaction以及存储引擎的一层封装。在一个事务想要开启的时候,先通过`MVCC`来开启一个(读写/只读)事务,之后关于事务的处理就不再属于`MVCC`来管理,转而到了稍后会讲到的`Trancation`中。 当事务开始的时候,从`Key::NextVersion`获取下一个可用的version并且递增它,然后通过`Key::TxnActive(version)`将自身记录为活动中的事务。它还会将当前活动的事务做一个快照,其中包含了事务开始的时候其他所有活动事务的version,并且将起另存为`Key::TxnActiveSnapshot(id)`。 key/value保存为`Key::Version(key, version)`的形式,其中`key`是用户提供的key,`version`是事务的版本。事务的key/value的可见性如下: - 对于给定的key,从当前事务的版本开始对`Key::Version(key, version)`进行反向的扫描。 - 如果一个版本位于活动集(active set)中的时候,跳过这个版本。 - 返回第一个匹配记录(如果有的话),这个记录可能是`Some(value)`或者`None`。 写入key/value的时候,事务首先要扫描其不可见的`Key::Version(key, version)`来检查是否存在任何冲突。如果有找到一个,那么需要返回序列化错误,调用者必须重试这个事务。如果没有找到,事务就会写入新记录,并且以`Key::TxnWrite(version, key)`的形式来跟踪更改,以防必须回滚的情况。 当事务提交的时候,就只需要删除其`Txn::Active(id)`记录,使其更改对其他后续的事务可见就可以了。如果事务回滚,就遍历所有的`Key::TxnWrite(id, key)`记录,并删除写入的key/value值,最后删除`Txn::Active(id)`记录就可以了。 这个方案可以保证ACID事务的快照隔离: 提交是原子的,每一个事务在开始的时候,看到的都是key/value存储的一致性快照,并且任何写入冲突都会导致序列化冲突,必须重试。 为了实现时间穿梭查询,只读事务只需加载过去事务的`Key::TxnActiveShapshot`记录就可以了,可见性规则和普通事务是一样的。 === MVCC在ToyDB中的取舍 + 旧的MVCC版本永远不会被删除,会导致存储空间的浪费。但是这简化了实现,也允许完整的数据历史记录。 + 事务id会在64位后溢出,没有做处理。
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/2650-cjk-latin-spacing-meta_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // https://github.com/typst/typst/issues/2650 #let with-locate(body) = locate(loc => body) 测a试 测#with-locate[a]试
https://github.com/benjamineeckh/kul-typst-template
https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/src/lib.typ
typst
MIT License
// #import "external-functions.typ":* #import "text-blobs.typ":declaration-of-originality, copyright, submission-text #import "packages.typ" #import "page-utils.typ" #import "core/component.typ": * #import "@preview/hydra:0.5.1": hydra // This is a template adapted from: // https://typst.app/universe/package/modern-unito-thesis // Made by <NAME> // // Adaptation made by <NAME> // FIXME: workaround for the lack of `std` scope // #let std-bibliography = bibliography #let template( // Your thesis title title: [Thesis Title], // The academic year you're graduating in academic-year: (2023), // Your thesis subtitle, should be something along the lines of // "Bachelor's Thesis", "bachelorproef" etc. subtitle: [Master's Thesis], // The paper size, refer to https://typst.app/docs/reference/layout/page/#parameters-paper for all the available options paper-size: "a4", // authors's informations. You should specify a `name` key authors: (), // Array with the thesis' promotor(s) promotors: (), // An array of the thesis' evaluators. // Set to `none` if not needed evaluators: (), // An array of the thesis' supervisors // set to `none` if not needed supervisors: (), // An affiliation dictionary, you should specify a `university` // keyword, `school` keyword and a `degree` keyword affiliation: ( color: (1,0,0,0), faculty: "politics", degree: "bidenomics", elective: "Trumpism" ), // Set to "it" for the italian template lang: "en", // The thesis' bibliography, should be passed as a call to the // `bibliography` function or `none` if you don't need // to include a bibliography bibliography: none, // The university's logo, should be passed as a call to the `image` // function or `none` if you don't need to include a logo logo: none, // whether it is an electronic version or not // does not include front page if electronic electronic-version: false, // Abstract of the thesis, set to none if not needed abstract: none, // preface, set to none if not needed preface: none, // Will maybe be removed declaration-of-originality:none, // The thesis' keywords, can be left empty if not needed keywords: none, // The thesis' content body ) = { let non-odd-page-headers = ("Declaration of Originality", "Declaratie van originaliteit", "Preface", "Voorwoord", "Abstract", "Samenvatting", "Nomenclature", "Lijst Van Symbolen", "Contents","List of Abbreviations and Symbols", "List of Figures and Tables", "Bibliography", "Bibliografie") set page(paper: paper-size, margin: (top: 10em), header: context page-utils.custom-header()) // Set document matadata. set document(title: title, author: authors.map(v=>v.name)) // Set the body font, "New Computer Modern" gives a LaTeX-like look set text(font: "New Computer Modern", lang: lang, size: 11pt) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure figure's captions show figure.caption: set text(size: 0.8em) // Configure lists and enumerations. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt, marker: ([•], [--])) /////////////////////////// Heading config // Configure headings set heading(numbering: "1.1.1") show heading.where(level: 1): it => [ #[] <chapter-end-marker> // marker positioned before the pagebreak #if not non-odd-page-headers.contains(it.body.text) and not counter(heading).get().first() == 1{ pagebreak(to: "odd", weak: true) } #block[ #v(15.55%) // kinda ass offset, but this is now the same as the latex one Should really check the latex source code #if not non-odd-page-headers.contains(it.body.text){ // This works because the level is 1 [Chapter #counter(heading).get().first()] } #v(6%) // Needed because we need to know where the actual body of the text begins #let lab = if counter(heading).get().first() == 1{ <start-of-body> } #block(width: 100%, height: 7%)[ #set text(1.45em, weight: "bold") #it.body ]#lab ]<chapter-start-marker> ] show heading.where(level: 2): it => block(width: 100%)[ #set text(1.1em, weight: "bold") #let heading-number = counter(heading).get().map(str).join(".") #heading-number #h(measure([1.1.1.]).width - measure(heading-number).width) #it.body ] show heading.where(level: 3): it => block(width: 100%)[ #set text(1em, weight: "bold") #let heading-number = counter(heading).get().map(str).join(".") #heading-number #h(measure([1.1.1.]).width - measure(heading-number).width) #it.body ] /////////////////////////// page chapter metadata context { let chapter-end-markers = query(<chapter-end-marker>) let chapter-start-markers = query(<chapter-start-marker>) let pairs = chapter-end-markers.enumerate().map(((index, chapter-end-marker)) => { let chapter-start-marker = chapter-start-markers.at(index) let end-page = chapter-end-marker.location().page() let start-page = chapter-start-marker.location().page() (end-page, start-page) }) state("chapter-markers").update(pairs) } /////////////////////////// actual content // Print cover page if not electronic-version{ insert-cover-page(title,authors, promotors, evaluators, supervisors, academic-year, submission-text, affiliation, logo:logo,cover:true, lang:lang) } // Actual cover page insert-cover-page(title,authors, promotors, evaluators, supervisors, academic-year, submission-text, affiliation, logo:logo,cover:false, lang:lang) // Copyright insert-copyright(copyright) set page(footer: context page-utils.custom-footer()) // Declaration of originality, prints in English or Dutch insert-dec-of-orig(declaration-of-originality) // custom numbering because KUL set page(numbering: (num, ..) => { let body = locate(<start-of-body>).page() let preamble = locate(<start-of-preamble>).page() // let body = 7 let pat = if num < body{ "i" } else { "1" } if num < body{ numbering(pat, num - preamble + 1) }else{ numbering(pat, num - body + 1) } }) // Preface insert-preface(preface, authors, lang:lang) // Outline insert-outline(non-odd-page-headers) // Abstract insert-abstract(abstract, lang:lang) // Keywords insert-keywords(keywords, lang:lang) // context if calc.odd(page-utils.get-page-number()){ // page(footer: none, header: none, numbering: none)[] // } // set align(top + left) body pagebreak(weak: true) insert-bibliography(bibliography, lang:lang) }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-02.typ
typst
Other
// Error: 6-10 expected boolean, integer, float, or string, found length #int(10pt)
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/text/raw-code.typ
typst
Apache License 2.0
// Test code highlighting. --- #set page(width: 180pt) #set text(6pt) #show raw: it => rect( width: 100%, inset: (x: 4pt, y: 5pt), radius: 4pt, fill: rgb(239, 241, 243), place(right, text(luma(110), it.lang)) + it, ) ```typ = Chapter 1 #lorem(100) #let hi = "Hello World" #show heading: emph ``` ```rust /// A carefully designed state machine. #[derive(Debug)] enum State<'a> { A(u8), B(&'a str) } fn advance(state: State<'_>) -> State<'_> { unimplemented!("state machine") } ``` ```py import this def hi(): print("Hi!") ``` ```cpp #include <iostream> int main() { std::cout << "Hello, world!"; } ``` ```julia # Add two numbers function add(x, y) return x * y end ``` // Try with some indent. ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <h1>Topic</h1> <p>The Hypertext Markup Language.</p> <script> function foo(a, b) { return a + b + "string"; } </script> </body> </html> ```
https://github.com/jamesrswift/pixel-pipeline
https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/primitives/lib.typ
typst
The Unlicense
#import "position.typ": position #import "../pipeline/primitives.typ" as pipeline: assembled, positioned, stroked, rendered
https://github.com/grnin/Zusammenfassungen
https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/Bsys2/04_Programme_Bibliotheken.typ
typst
// Compiled with Typst 0.11.1 #import "../template_zusammenf.typ": * #import "@preview/wrap-it:0.1.0": wrap-content /*#show: project.with( authors: ("<NAME>", "<NAME>"), fach: "BSys2", fach-long: "Betriebssysteme 2", semester: "FS24", tableofcontents: (enabled: true), language: "de" )*/ = Programme und Bibliotheken == C Toolchain `C-Quelle -> Präprozessor -> Bereinigte C-Quelle -> Compiler -> Assembler-Datei -> Assembler -> Objekt-Datei -> Linker -> Executable` - _Präprozessor:_ Die Ausgabe des Präprozessors ist eine reine C-Datei (Translation-Unit) ohne Makros, Kommentare oder Präprozessor-Direktiven. - _Linker:_ Der Linker verknüpft Objekt-Dateien (und statische Bibliotheken) zu Executables oder dynamischen Bibliotheken. Löst Referenzen der Objekt-Dateien untereinander soweit wie möglich auf. Executable und dynamische Bibliotheken müssen vollständig aufgelöst sein. == Loader und das ELF Der _Loader_ lädt Executables und eventuelle _dynamische_ Bibliotheken dieser in den Hauptspeicher. Executable und dynamische Bibliotheken müssen also _alle Informationen_ enthalten, die der Loader benötigt. Lädt _keine statische Bibliotheken_, diese werden bereits vorher im Kompilationsprozess vom Linker mit Executable oder dynamischer Bibliothek verknüpft. === Linux Loader Eine Funktion der `exec*`-Familile erhält `syscall`. Diese wird auf `sys_execve` übersetzt. _Sucht_ Datei, _prüft_ Rechte (x-Bits) und _öffnet_ die spezifizierte Datei. _Zählt und kopiert_ die Argumente und Umgebungsvariablen #hinweis[(weil execv#emph[e])]. _Übergibt den Request_ an jeden registrierten "Binary Handler" #hinweis[(für verschiedene Dateiformate: ELF, a.out etc.)]. Diese versuchen nacheinander jeweils die _Datei zu laden_ und zu interpretieren #sym.arrow _Ausführung des neuen Programms_. #wrap-content( image("img/bsys_16.png"), align: bottom + right, columns: (80%, 20%), )[ === ELF (Executable and Linking Format) _Binär-Format_, das Kompilate spezifiziert. Eigentlich zwei Formate / Views, werden aber oft beide benötigt: _Linking View_ #hinweis[(wichtig für Linker)] und _Execution View_ #hinweis[(wichtig für Loader)]. Verwendung: - _Object-Files:_ Linking View - _Programme:_ Execution View - _Shared Objects (Dynamische Bibliotheken):_ Linking View und Execution View === Struktur des ELF - #link(<elf-header>)[_Header_] - #link(<elf-pht>)[_Programm Header Table_] #hinweis[(nur in Execution View erforderlich)] - #link(<elf-pht>)[_Segmente_] #hinweis[(nur in Execution View erforderlich)] - #link(<elf-sht>)[_Section Header Table_] #hinweis[(nur in Linking View erforderlich)] - #link(<elf-sht>)[_Sektionen_] #hinweis[(nur in Linking View erforderlich)] ] #pagebreak() #wrap-content( image("img/bsys_17.png"), align: bottom + right, columns: (85%, 15%), )[ ==== Segmente und Sektionen Segmente und Sektionen sind jeweils eine _andere Einteilung für die gleichen Speicherbereiche_. Die _View des Loaders_ sind die _Segmente_: Diese definieren die Portionen, die in den Hauptspeicher geladen werden. Die _View des Compilers_ sind die _Sektionen_: Diese definieren "gleichartige" Daten #hinweis[(z.B. `.data`, `.text`)]. Der _Linker_ vermittelt zwischen beiden Views: kombiniert gleichnamige Sektionen aus unterschiedlichen Objekt-Dateien und definiert Segmente. ] ==== Header <elf-header> Der Header #hinweis[(52 Byte)] beschreibt _den Aufbau_ der Datei: - _Typ:_ Relozierbar #hinweis[(beliebig verschiebbar im Speicher)], Ausführbar, Shared Object - _32-bit oder 64-bit_ - _Encoding:_ little-endian oder big-endian - _Maschinenarchitektur:_ z.B. i386, Motorola 68k - _Entrypoint:_ Adresse, an der das Programm starten soll #hinweis[(Default: `_start`)] - _Infos zu den Einträgen in der Program Header Table:_ Relative Adresse, Anzahl und Grösse - _Infos zu den Einträgen in der Section Header Table:_ Relative Adresse, Anzahl und Grösse ==== Segment/Program Header Table und Segmente <elf-pht> Die Segment Header Table #hinweis[(SHT/PHT)] ist eine Tabelle mit $n$ Einträgen. Jeder Eintrag (je 32 Byte) _beschreibt ein Segment:_ - Segment-Typ und Flags - Offset und Grösse in der Datei - Virtuelle Adresse und Grösse im Speicher #hinweis[(möglich zusätzlich auch physische Adresse)] Die SHT ist die _Verbindung zwischen den Segmenten im RAM und im File_. Die PHT definiert, wo ein Segment in der Datei liegt und wohin der Loader das Segment in den RAM laden soll. _Achtung:_ Grösse der Datei und Grösse im Speicher können unterschiedlich sein. Es kann auch Speicher reserviert werden. Deswegen kann Dateigrösse 0 sein, aber Speicher z.B. 5MB.\ Segmente werden vom Loader _zur Laufzeit_ verwendet: Der _Loader_ lädt bestimmte Segmente in den Speicher und kann weitere Segmente für andere Informationen verwenden #hinweis[(dynamisches Linken oder Meta-Informationen)]. ==== Section Header Table und Sektionen <elf-sht> Die Section Header Table (auch SHT) ist eine Tabelle mit $m$ Einträgen ($m$ meist $!= n$). Jeder Eintrag (je 40 Byte) _beschreibt eine Sektion_: - _Name:_ Referenz auf String Table - _Section-Typ_ und Flags - _Offset_ und _Grösse_ in der Datei - _Spezifische Informationen_ je nach Sektions-Typ Sektionen werden vom _Linker_ verwendet: Sammelt alle Sektionen aus allen Object-Files zusammen. _Verschmilzt_ Sektionen _gleichen Namens_ aus verschiedenen Object-Files und _erzeugt ausführbares Executable_. #columns(2)[ ===== Sektionstypen #hinweis[(Auswahl)] - _`SHT_PROGBITS`:_ Daten definiert vom Programm, Linker interpretiert Inhalt nicht - _`SHT_SYMTAB`:_ #link(<symbol-tabelle>)[Symbol-Tabelle] - _`SHT_STRTAB`:_ #link(<string-tabelle>)[String-Tabelle] - _`SHT_REL/RELA`:_ Relokations-Informationen - _`SHT_HASH`:_ Hashtabelle für Symbole - _`SHT_DYNAMIC`:_ Informationen für dynamisches Linken - _`SHT_NOBITS`:_ Sektionen ohne Daten in der Datei #colbreak() ===== Sektionsattribute - _`SHF_WRITE`:_ Daten dieser Sektion sollen bei Ausführung _schreibbar_ sein #hinweis[(SH#emph[F] für Flag)] - _`SHF_ALLOC`:_ Daten dieser Sektion sollen bei Ausführung _im Speicher liegen_ - _`SHF_EXECINSTR`:_ Daten dieser Sektion stellen _Maschinencode_ dar ] #pagebreak() ===== Spezielle Sektionen #hinweis[(Auswahl)] - _`.bss`:_ Uninitialisierte Daten #hinweis[(`SHT_NOBITS, SHF_ALLOC, SHF_WRITE`)] - _`.data` / `data1`:_ Initialisierte Daten #hinweis[(`SHT_PROGBITS, SHF_ALLOC, SHF_WRITE`) - `data1` ist historisch] - _`.debug`:_ Debug-Informationen #hinweis[(`SHT_PROGBITS`)] - _`.rodata` / `.rodata1`:_ Read-Only Daten #hinweis[(`SHT_PROGBITS, SHF_ALLOC`)] - _`.text`:_ Ausführbare Instruktionen #hinweis[(`SHF_PROGBITS, SHF_ALLOC, SHF_EXECINSTR`)] - _`.symtab`:_ #link(<symbol-tabelle>)[Symbol-Tabelle] #hinweis[(`SHT_SYMTAB`)] - _`.strtab`:_ #link(<string-tabelle>)[String-Tabelle] #hinweis[(`SHT_STRTAB`)] ==== String-Tabelle <string-tabelle> Bereich in der Datei, der nacheinander _null-terminierte Strings enthält_. Strings werden _relativ zum Beginn der Tabelle_ referenziert #hinweis[(z.B. Tabelle beginnt bei Dateioffset 1234, String bei 1238 #sym.arrow String-Referenz = 4)].\ Enthält typischerweise _Namen von Symbolen_ und _keine String-Literale_ #hinweis[(z.B. "Hello World" - diese sind typischerweise in `.rodata`)] ==== Symbole & Symboltabelle <symbol-tabelle> Die Symboltabelle enthält jeweils _einen Eintrag je Symbol_. Ein Symbol hat _16 Byte_. - 4 Byte _Name_: Referenz in String-Tabelle - 4 Byte _Wert_: Je nach Symboltyp, kann z.B. Adresse sein - 4 Byte _Grösse_: Grösse des Symbold #hinweis[(z.B. Länge einer Funktion)] - 4 Byte _Info_: Typ #hinweis[(Objekt, Funktion, Sektion...)], Binding-Attribute, Referenz auf Sektions-Header == Bibliotheken #wrap-content( image("img/bsys_18.png"), align: top + right, columns: (70%, 30%), )[ === Statische Bibliotheken Statische Bibliotheken sind _Archive von Objekt-Dateien_. Archive sind Dateien, die andere Dateien enthalten #hinweis[(wie ein ZIP ohne Kompression)], werden mit dem Tool `ar` erzeugt. Per Konvention folgen Bibliotheksnamen dem Muster `lib<name>.a`.\ Referenziert wird dann nur `<name>: clang -lmylib ...`. Der Linker behandelt statische Bibliotheken wie _mehrere Objekt-Dateien_. Alle gelinkten statischen Bibliotheken werden vom Linker im Programm-Image _verteilt_, alle Variablen und Funktionen werden auf absolute Adressen _fixiert_. Ursprünglich gab es _nur statische Bibliotheken_. Das war _einfach_ zu implementieren, jedoch müssen Programme bei Änderungen in Bibliotheken _neu erstellt_ werden und die _Funktionalität ist fix_ #hinweis[(Keine Plugins möglich)]. ] #wrap-content( image("img/bsys_19.png"), align: top + right, columns: (70%, 30%), )[ === Dynamische Bibliotheken Dynamische Bibliotheken linken erst zur _Ladezeit_ bzw. Laufzeit des Programms. _Höherer Aufwand_ für Programmierer, Compiler, Linker und OS. Das Executable enthält nur noch Referenz auf Bibliothek. Vorteile davon sind: *Entkoppelter Lebenszyklus:* Das Programm kann _Updates erhalten_, ohne das Binary zu ändern. Funktionalität kann unabhängig voneinander _geupdatet_ werden. Bugfixes können _direkt_ zur Anwenderin gebracht werden. ] *Verzögertes Laden:* Das Programm muss _nur die Bibliotheken laden_, die es minimal braucht. Führt zu schnelleren Ladezeiten. *Flexibler Funktionsumfang:* Programme können um Funktionalitäten _ergänzt_ werden, die beim Schreiben nicht vorgesehen war. _Ablauf:_ Programm definiert API für Plugin-Bibliotheken und enthält Mechanismus, anhand des Modulnamens Bibliotheken zu finden. #pagebreak() === POSIX: Shared Objects API ```c void * dlopen (char * filename, int mode)``` _öffnet eine dynamische Bibliothek_ und gibt ein _Handle_ darauf zurück. `mode` gibt Art an, wie mit der Bibliothek umgegangen wird: - _`RTLD_NOW`:_ Alle Symbole werden beim Laden der Bibliothek gebunden - _`RTLD_LAZY`:_ Symbole werden bei Bedarf gebunden - _`RTLD_GLOBAL`:_ Symbole können beim Binden anderer Objekt-Dateien verwendet werden #hinweis[(damit andere Libs diese benutzen können)] - _`RTLD_LOCAL`:_ Symbole werden nicht für andere Objekt-Dateien verwendet ```c void * dlsym (void * handle, char * name)``` gibt die _Adresse des Symbols_ `name` aus der mit `handle` bezeichneten _Bibliothek_ zurück. Keine Typinformationen, nur Adresse. Es ist also weder klar, ob es sich um Funktionen oder Variablen handelt, noch welche Signatur bzw. welchen Typ diese haben. ```c // type "func_t" is a address of a function with a int param and int return type typedef int (*func_t)(int); handle = dlopen("libmylib.so", RTLD_NOW); // open library func_t f = dlsym(handle, "my_function"); // write address of "my_function" into a func_t int *i = dlsym(handle, "my_int"); // get address of "my_int" (*f)(*i); // call "my_function" with "my_int" as parameter ``` Dabei ist `f` die Adresse der Funktion namens `my_function` in `libmylib.so.1` und `i` die Adresse der globalen Variable namens `my_int`. Beides sind Symbole, die von der Library exportiert werden. ```c int dlclose (void * handle)``` schliesst das durch `handle` bezeichnete, zuvor von `dlopen` geöffnete Objekt. Gibt 0 zurück, wenn erfolgreich. Aufgepasst vor offenen Pointer auf Library-Symbole! ```c char * dlerror()``` gibt die Fehlermeldung als null-terminierten String zurück, wenn ein Fehler aufgetreten war. === Shared-Object Konventionen ==== Automatisches Laden von Shared Objects Shared Objects können _automatisch_ bei Bedarf geladen werden. Im Executable (ELF) muss eine Referenz auf das Shared Object (ELF) hinterlegt sein (Dependency). Das OS sucht automatisch beim Programmstart die richtigen Bibliotheken. ==== Shared Objects Benennungsschema - _Linker-Name:_ `lib + Bibliotheksname + .so` #hinweis[(z.B. libmylib.so)] - _SO-Name:_ `Linker-Name + . + Versionsnummer` #hinweis[(z.B. libmylib.so.2)] - _Real-Name:_ `SO-name + . + Unterversionsnummer` #hinweis[(z.B. libmylib.so.2.1)] Sind in POSIX meist gelinkt im Dateisystem: Linker #sym.arrow SO #sym.arrow Real #hinweis[(libmylib.so #sym.arrow libmylib.so.2 #sym.arrow libmylib.so.2.1)]\ _Real-Name_ wird beim _Erstellen des Shared Objects_ verwendet. Die _Versionsnummer_ wird erhöht, wenn sich die Schnittstelle _ändert_. Die _Unterversionsnummer_ wird erhöht, wenn die Schnittstelle gleichbleibt #hinweis[(Bugfixes)]. Der Linker verwendet den Linker-Namen, der Loader verwendet den SO-Namen. ==== Shared Objects Koexistenz verschiedener Versionen Alle Versionen und Unterversionen können gleichzeitig existieren und verwendet werden. Programme können bei Bedarf die Unterversion ganz präzise angeben #hinweis[(`libmylib.so.2` zeigt auf die neuste 2-er Version)]. === Erstellen von Bibliotheken ==== Erstellen von statischen Bibliotheken mit dem `clang` Zuerst kompilieren mit ```sh clang -c f1.c -o f1.o;``` ```sh clang -c f2.c -o f2.o```, dann zusammenfügen zu einem Archiv: ```sh ar r libmylib.a f1.o f2.o``` #hinweis[(`r` fügt Dateien hinzu oder überschreibt existierende)] ==== Dynamische Bibliotheken mit `clang` kompilieren Falls zusätzlich zu den Befehlen oben `-fPIC` für Position-Independent Code verwendet wird, kann ein spezielles Image erzeugt werden mit ```sh clang -shared -Wl, -soname, libmylib.so.2 -o libmylib.so.2.1 f1.o f2.o -lc```, wobei _`-shared`_ = Erzeugen eines Shared Objects, _`-Wl,`_ = Weitergeben der folgenden Option an den Linker, _`-soname`_ = spezifizieren des SO-Namens `libmylib.so.2`, _`-lc`_ = Einbinden der Standard C-Bibliothek (`libc.so`). === Verwenden von Bibliotheken - _Statische Bibliothek #hinweis[(Link-time Library)]:_ ```sh clang main.c -o main -L. -lmylib```\ #hinweis[`-L.` fügt "." zum Suchpfad hinzu, `-lmylib` bezieht sich auf die Bibliothek `mylib`, nach Konvention also auf Datei `libmylib.a`] - _Dynamische Bibliothek, die mit Programm geladen werden soll #hinweis[(Load-time Library)]:_\ ```sh clang main.c -o main -lmylib```\ #hinweis[`-lmylib` bezieht sich auf `libmylib.so`, ohne `-L.` muss `libmylib.so` im OS installiert sein] - _Dynamische Bibliothek, die mit `dlopen` geladen werden soll #hinweis[(Run-time Library)]:_\ ```sh clang main.c -o main -ldl```\ #hinweis[`-ldl` linkt auf (dynamische) Bibliothek `libdl.so`, die `dlopen` etc zur Verfügung stellt] *Shared Objects:* Referenzierte Shared Objects sind im _Executable_ abgelegt. _`readelf -d`_ zeigt den _Inhalt der dynamischen Sektion_. Typ der entsprechenden Einträge ist _`NEEDED`_. Das Tool _`ldd`_ zeigt _alle, auch indirekt_ benötigten Shared Objects an. Dazu führt es die Executable aus, sollte deshalb nur auf _vertrauenswürdigen Executables_ ausgeführt werden. Nahezu alle Executeables benötigen _zwei Shared Objects_: - _`libc.so`:_ Standard C library - _`ld-linux.so`:_ ELF Shared Object loader. Wird indirekt vom OS aufgerufen, wenn ein Shared Object geladen werden soll. Findet und lädt nacheinander alle benötigten Shared Objects, danach rekursiv die Dependencies der geladenen Shared Objects. === Implementierung von dynamischen Bibliotheken Dynamische Bibliotheken müssen _verschiebbar_ sein und mehrere Bibliotheken müssen in den _gleichen Prozess_ geladen werden können. Die Aufgabe des Linkers wird in den Loader bzw. Dynamic Linker verschoben #hinweis[(Load Time Relocation)]. #wrap-content( image("img/bsys_21.png"), align: top + right, columns: (60%, 40%), )[ Dynamische Bibliotheken sollen _Code zwischen Programmen teilen_. Code soll _nicht mehrfach_ im Speicher abgelegt werden, auch wenn mehrere Programme die Bibliothek verwenden. Das kann durch _Shared Memory_ gelöst werden. Jedes Programm kann eine _eigene virtuelle Page_ für den Code definieren. Diese werden auf denselben Frame im RAM gemappt, so belegt der Code den Hauptspeicher nur einmal. ] _Code-Sharing_ erlaubt jedoch keinen _Position-Dependent Code_. Wenn zwei Prozesse unterschiedliche virtuelle Seiten verwenden, an welchen Prozess werden die Adressen angepasst? Deshalb muss mit dynamischen Bibliotheken mit _Position-Independent Code_ gearbeitet werden. Dieser verwendet _keine absoluten Adressen_, sondern nur Adressen _relativ zum Instruction Pointer_. === Position-Independent Code (PIC) Für Position-Independent Code (PIC) muss der _Prozessor relative Instruktionen anbieten._ `x86_64` #hinweis[(64-bit Prozessoren)] hat relative Funktionsaufrufe und Move-Instruktionen, `x86_32` #hinweis[(32-bit Prozessoren)] nur relative Calls. Relative Moves können aber über relative Calls emuliert werden. ==== Relative Moves via Relative Calls CPU legt bei einem Call die _Rücksprungadresse auf den Stack_. Funktion `f` will relativen Move ausführen und ruft Hilfsfunktion `h` auf. `h` kopiert _Rücksprungadresse_ vom Stack in ein _Register_ und springt zurück. `f` hat nun die _Rücksprungadresse = Instruction Pointer_ im Register und kann relativ dazu arbeiten, weil `f` nun weiss, wo sie im Speicher liegt. ==== Global Offset Table (GOT) Existiert einmal pro dynamischer Bibliothek und Executable. Enthält _pro Symbol_, welches von anderen Libs benötigt wird, _einen Eintrag_. Im Code werden relative Adressen in die GOT verwendet. Der Loader füllt zur Laufzeit die Adressen in die GOT ein. ==== Procedure Linkage Table (PLT) Implementiert _Lazy Binding_ #hinweis[(erst binden, wenn benötigt)]. Enthält _pro Funktion einen Eintrag_. PLT-Eintrag enthält einen _Sprungbefehl_ an Adresse in GOT-Eintrag. Der GOT-Eintrag zeigt zunächst auf eine _Proxy-Funktion_, welche dann den Link zur richtigen Funktion sucht und den eigenen GOT-Eintrag überschreibt. _Vorteil:_ Erspart bedingten Sprung #hinweis[(teuer)].
https://github.com/ayoubelmhamdi/typst-phd-AI-Medical
https://raw.githubusercontent.com/ayoubelmhamdi/typst-phd-AI-Medical/master/TYP_PPT/main.typ
typst
MIT License
= PPT == Intorduction. Le cancer du poumon figure parmi les principales causes de mortalité liées au cancer dans le monde entier. La reconnaissance et le diagnostic précoces des nodules pulmonaires, petites masses de tissu dans les poumons, peuvent considérablement augmenter les taux de survie et le succès du traitement pour les individus atteints de cancer du poumon. Cependant, la détection et la classification de ces nodules pulmonaires représentent un défi de taille en raison de leur taille, forme, emplacement et caractéristiques physiques variables. De plus, la majorité des nodules pulmonaires sont bénins ou non cancéreux, avec seulement un faible pourcentage classé comme malin ou cancéreux. Ces conditions créent des complications pour la détection et la classification automatisées des nodules pulmonaires par le biais de modèles d'apprentissage automatique. Dans cette étude, nous mettons en œuvre une expérience d'apprentissage automatique utilisant un modèle CNN pour déterminer si les nodules pulmonaires sont bénins ou malins à partir d'images de scans. Nous avons utilisé l'ensemble de données LUNA16 accessible au public comprenant 888 scans CT de nodules annotés. Un total de 6692 nodules ont été isolés à partir de ces scans, dont seulement 2526 étaient malveillants et 4166 étaient bénins. Nous avons l'entraînement du modèle CNN en utilisant l'ensemble d'entraînement et avons évalué ses performances sur l'ensemble de validation. == Méthode. Notre étude comprenait trois étapes principales : le prétraitement des données, le développement de l'algorithme de détection des nodules et l'évaluation des performances. === Ressources. Les ressources de notre étude étaient des scans CT et des annotations provenant de l'ensemble de données LUNA16. LUNA16, un ensemble de scans CT accessible au public du Lung Database Consortium (LIDC) et de l'Image Database Resource Initiative (IDRI), comprend 888 scans CT avec une épaisseur de tranche inférieure à 3 mm et un espacement de pixel inférieur à 0,7 mm. Cet ensemble propose également deux fichiers CSV distincts contenant les détails des candidats et des annotations. Dans le fichier candidates_V2.csv, quatre colonnes sont illustrées : seriesuid, coordX, coordY, coordZ, et classe. Le fichier annotations.csv est composé de cinq colonnes : seriesuid, coordX, coordY, coordZ, et diamètre_mm, commandant l'identifiant unique du scanner, les coordonnées d'annotation spatiales en millimètres, et le diamètre de chaque annotation en millimètres, respectivement. === Scans CT avec Nodules Pulmonaires. Pour lire, traiter et représenter visuellement les scans CT montrant des nodules pulmonaires, nous avons mis en œuvre deux bibliothèques Python : SimpleITK et matplotlib. Avec SimpleITK, nous avons lu les fichiers de scan CT de l'ensemble de données LUNA16, convertissant ces images de leur format DICOM ou NIfTI en tableaux numériques multidimensionnels manipulables, appelés tableaux numpy. De plus, SimpleITK a été utilisé pour obtenir l'origine et l'espacement des images, définis comme les coordonnées de l'image et la taille du voxel, respectivement. Par la suite, nous avons rééchantillonné les images en utilisant SimpleITK, obtenant une taille de voxel uniforme de 1 mm x 1 mm x 1 mm, normalisé les valeurs de pixel à une plage de -1000 à 320 unités Hounsfield (HU), et appliqué un algorithme de segmentation pulmonaire pour isoler les régions pulmonaires des images. Nous avons utilisé matplotlib pour tracer et afficher les tranches de scan CT contenant des nodules, complétant ces images par des lignes blanches marquant les limites autour de chaque nodule pour souligner leur emplacement et leurs dimensions. ==== Prétraitement des données. Dans la phase de prétraitement des données, les scans CT ont été transformés du format DICOM en tableaux (tenseurs). Cela a été suivi par le rééchantillonnage des images pour obtenir des dimensions de voxel uniformes de 1 mm x 1 mm x 1 mm, la normalisation des valeurs de pixel pour répondre à une plage de -1000 à 320 unités Hounsfield (HU), et enfin l'utilisation d'un algorithme de segmentation pulmonaire pour extraire les régions pulmonaires des images. Après avoir préparé les images de scans CT et les masques pulmonaires, l'ensemble de données a été divisé en ensembles d'entraînement et de test. L'ensemble d'entraînement comprenait 67% des données(4483 nodules), tandis que l'ensemble de test comprenait les 33% restants(2209 nodules). ==== Développement de l'algorithme de détection des nodules. La construction de l'algorithme de détection des nodules a été divisée en plusieurs étapes impératives. À sa base, l'algorithme reposait sur un modèle de réseau neuronal convolutif (CNN), chargé d'identifier les nodules à partir d'images de scans CT. == Resulat Nous avons évalué le succès du modèle à travers sa précision sur les ensembles de données d'entraînement et de validation. Le terme précision fait référence à la capacité du modèle à prévoir avec précision les résultats sur les données d'entraînement, tandis que la précision de validation signifie la capacité du modèle à étendre ses prédictions à de nouvelles données inédites, c'est-à-dire les données de validation. En examinant les valeurs de précision et de précision de validation tout au long des étapes d'apprentissage, il est indiqué que le modèle acquiert des connaissances, comme on peut le voir à travers l'amélioration progressive des précisions d'entraînement et de validation. La performance du modèle a également été évaluée à l'aide de métriques telles que la précision, le Rappel (sensibilité) et le score F1 en plus de la précision. == Disscusion Les résultats illustrent que le modèle a performé de manière compétente dans l'identification des deux classes, avec une légère préférence pour l'identification de la classe 0 (pas de nodule) par rapport à la classe 1 (présence de nodule). En général, le modèle a performé de manière impressionnante en termes de précision, de rappel et de score F1. L'ensemble de données présente une disparité excessive entre les classes bénignes et malignes, la classe bénigne étant plus de 400 fois plus prévalente que la classe maligne. Cette disproportion entrave le processus d'apprentissage du modèle pour distinguer entre les classes, et il pourrait par défaut prédire la classe la plus fréquente. Un certain nombre de facteurs peuvent expliquer pourquoi le modèle montre une préférence pour identifier la classe 0 (pas de nodule) par rapport à la classe 1 (présence de nodule). Des caractéristiques différentes entre les classes peuvent également conduire à des taux de détection différents. Pour résoudre ce problème, il faut une stratégie raffinée pour entraîner notre modèle et un indicateur de performance amélioré mieux que la précision. Les solutions potentielles comprennent l'implémentation de techniques d'augmentation des données et l'utilisation de techniques de suréchantillonnage ou de sous-échantillonnage. Dans notre travail ultérieur, nous visons à incorporer certaines de ces solutions et nous nous attendons à améliorer les performances de notre modèle par rapport à la classification des nodules pulmonaires. == Conclusion Nous avons utilisé le Deep-Learning pour détecter et classifier les nodules pulmonaires dans l'ensemble de données LUNA16. Le modèle a affronté des défis liés à la diversité des nodules en termes de taille, de forme et d'emplacement, ainsi qu'à une distribution inégale dans l'ensemble de données. Malgré ces difficultés, il a performé de manière satisfaisante, produisant des scores précis, un bon rappel et un F1 score convaincant pour les nodules, qu'ils soient bénins ou malins. Le modèle a montré un léger avantage dans l'identification des non-nodules, probablement à cause du déséquilibre de classes dans l'ensemble de données. Nous envisageons des techniques d'augmentation des données et de rééquilibrage des classes pour remédier à ce problème. Les résultats de notre étude soulignent que le Deep-Learning est efficace pour la détection et la classification des nodules pulmonaires. Il a le potentiel pour faciliter le diagnostic précoce du cancer du poumon, ce qui peut améliorer les chances de survie et l'efficacité du traitement. Nous cherchons à améliorer notre modèle pour perfectionner sa performance, en particulier dans la détection des sous-types de nodules pulmonaires. Pour cela, des recherches supplémentaires sont nécessaires.
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/树/验证二叉搜索树.typ
typst
#import "../../../../lib.typ":* === #Title( title: [验证二叉搜索树], reflink: "https://leetcode.cn/problems/validate-binary-search-tree/description/", level: 2, )<验证二叉搜索树> #note( title: [ 验证二叉搜索树 ], description: [ 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。 有效 二叉搜索树定义如下: - 节点的左子树只包含 小于 当前节点的数。 - 节点的右子树只包含 大于 当前节点的数。 - 所有左子树和右子树自身必须也是二叉搜索树。 ], examples: ([ #figure( image("./img/tree1.jpg", width: 20%) ) 输入:root = [2,1,3] 输出:true ],[ #figure( image("./img/tree2.jpg", width: 20%) ) 输入:root = [5,1,4,null,null,3,6] 输出:false 解释:根节点的值是 5 ,但是右子节点的值是 4 。 ] ), tips: [ - 树中节点数目范围在$[1, 10^4]$ 内 - $-2^31 <= "Node.val" <= 2^31 - 1$ ], solutions: ( ( name:[递归], text:[ 要解决这道题首先我们要了解二叉搜索树有什么性质可以给我们利用,由题目给出的信息我们可以知道:如果该二叉树的左子树不为空,则左子树上所有节点的值均小于它的根节点的值; 若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值;它的左右子树也为二叉搜索树。 这启示我们设计一个递归函数 `helper(root, lower, upper)` 来递归判断,函数表示考虑以 `root` 为根的子树,判断子树中所有节点的值是否都在 $(l,r)$ 的范围内(注意是开区间)。如果 `root` 节点的值 `val` 不在 $(l,r)$ 的范围内说明不满足条件直接返回,否则我们要继续递归调用检查它的左右子树是否满足,如果都满足才说明这是一棵二叉搜索树。 那么根据二叉搜索树的性质,在递归调用左子树时,我们需要把上界 `upper` 改为 `root.val`,即调用 `helper(root.left, lower, root.val)`,因为左子树里所有节点的值均小于它的根节点的值。同理递归调用右子树时,我们需要把下界 `lower` 改为 `root.val`,即调用 `helper(root.right, root.val, upper)`。 函数递归调用的入口为 `helper(root, -inf, +inf)`, `inf` 表示一个无穷大的值。 ],code:[ ```cpp class Solution { public: bool helper(TreeNode* root, long long lower, long long upper) { if (root == nullptr) { return true; } if (root -> val <= lower || root -> val >= upper) { return false; } return helper(root -> left, lower, root -> val) && helper(root -> right, root -> val, upper); } bool isValidBST(TreeNode* root) { return helper(root, LONG_MIN, LONG_MAX); } }; ``` ]),( name:[中序遍历], text:[ 基于方法一中提及的性质,我们可以进一步知道二叉搜索树「中序遍历」得到的值构成的序列一定是升序的,这启示我们在中序遍历的时候实时检查当前节点的值是否大于前一个中序遍历到的节点的值即可。如果均大于说明这个序列是升序的,整棵树是二叉搜索树,否则不是,下面的代码我们使用栈来模拟中序遍历的过程。 ], code:[ ```cpp class Solution { public: bool isValidBST(TreeNode* root) { stack<TreeNode*> stack; long long inorder = (long long)INT_MIN - 1; while (!stack.empty() || root != nullptr) { while (root != nullptr) { stack.push(root); root = root -> left; } root = stack.top(); stack.pop(); // 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树 if (root -> val <= inorder) { return false; } inorder = root -> val; root = root -> right; } return true; } }; ``` ] ) ), gain:[ 以下代码是*错误*的,因为其只考虑了搜索二叉树的局部特征,没有考虑搜索二叉树的整体特性,例如某节点在其父节点的左子树中,其父节点在根节点的右子树下,而某节点值比根节点要小,从整体情况上看其不会出现在根节点的右子树下。 ```cpp class Solution { public: bool isValidBST(TreeNode* root) { if(root == nullptr) { return true; } return isValidBST(root->left) && isValidBST(root->right) && (root->left==nullptr||root->left->val < root->val) && (root->right==nullptr||root->right->val > root->val); } }; ``` ], )
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/themes/9.typ
typst
#import "../conf.typ": * = Теорема о неявной функции, заданной одним уравнением #definition[ *Кубом* радиуса $delta$ вокруг точки $x_0 in RR^n$ назовём #eq[ $K_(delta, bold(x_0)) = times.big_(k = 1)^n (x_0^k - delta, x_0^k + delta)$ ] где под $times$ подразумевается декартово произведение. ] #theorem[ Пусть $F(bold(x), y) = F(x_1, ..., x_n, y)$ дифференцируема в окрестности точки $(bold(x_0), y_0) = (x_0^1, ..., x_0^n, y_0)$. Её производная $(partial F) / (partial y)$ непрерывна в этой окрестности, причём $F(x_0, y_0) = 0, (partial F) / (partial y) (x_0, y_0) != 0$. Тогда для любого достаточно малого $epsilon > 0$ найдётся $delta > 0$: #eq[ $forall x in K_(delta, x_0) : exists ! y = phi(x) : forall (x, y) in K_(delta, x_0) times (y_0 - epsilon, y_0 + epsilon) : \ F(x, y) = 0 <=> y = phi(x), "причём" exists phi'(x_0)$ ] ] #proof[ БОО будем считать, что $(partial F) / (partial y)(x_0, y_0) > 0$. По непрерывности частной производной, $exists$ окрестность точки $(x_0, y_0)$, в которой $(partial F) / (partial y)(x, y) > 0$. Тогда из непрерывности $F$ по $y$ и знакоопределённости производной следует #eq[ $exists epsilon_0 : forall epsilon in (0, epsilon_0) : space F(x_0, y_0 + epsilon) > 0 and F(x_0, y_0 - epsilon) < 0$ ] Расширяем территорию дальше, из непрерывности $F$ по $x$ следут #eq[ $exists delta > 0 : forall x in K_(delta, x_0) : F(x, y_0 + epsilon) > 0 and F(x, y_0 - epsilon) < 0$ ] Из теоремы о промежуточных значениях непрерывной функции берём существование, а из знакоопределённости производной единственность: #eq[ $exists! phi(x) in (y_0 - epsilon, y_0 + epsilon) : F(x, phi(x)) = 0$ ] Заметим, что $phi$ непрерывна по построению в $(x_0, y_0)$: мы брали $x$ из $2delta$ окрестности точки $x_0$, а значение лежало в $2epsilon$ окрестности точки $y_0$. Теперь докажем дифференцируемость $phi$, для этого распишем дифференцируемость $F$: #eq[ $F(x, y) - underbrace(F(x_0, y_0), 0) = \ sum_(k = 1)^n (partial F) / (partial x_k) (x_0, y_0)dot (x_k - x_0^k) + (partial F) / (partial y) (x_0, y_0) dot (y - y_0) + alpha(x, y)$ ] где $alpha = o(norm((x, y) - (x_0, y_0))), (x, y) -> (x_0, y_0)$. Воспользуемся умножением на "умную единицу": #eq[ $alpha(x, y) = sum_(i = 1)^n (alpha(x, y) dot (x_i - x_0^i)^2) / norm((x, y) - (x_0, y_0))_2^2 + (alpha(x, y) dot (y - y_0)^2) / norm((x, y) - (x_0, y_0))_2^2$ ] Введём новые обозначения: #eq[ $alpha_i (x, y) := (alpha(x, y) dot (x_i - x_0^i)) / norm((x, y) - (x_0, y_0))_2^2 ; quad beta(x, y) := (alpha(x, y) dot (y - y_0)) / norm((x, y) - (x_0, y_0))_2^2$ ] Тогда #eq[ $F(x, y) = sum_(k = 1)^n &((partial F) / (partial x_k)(x_0, y_0) + alpha_k (x, y))(x_k - x_0^k) + \ &((partial F) / (partial y)(x_0, y_0) + beta(x, y))(y - y_0)$ ] Подставляя $y = phi(x)$ в выражение выше, будем использовать новые обозначения: #eq[ $tilde(alpha)_k (x) := alpha_k (x, phi(x)) ; quad tilde(beta) (x) := beta(x, phi(x))$ ] Таким образом, #eq[ $underbrace(F(x, phi(x)), 0) = sum_(k = 1)^n &((partial F) / (partial x_k)(x_0, phi(x_0)) + tilde(alpha)_k (x))(x_k - x_0^k) + \ &((partial F) / (partial y)(x_0, phi(x_0)) + tilde(beta)(x))(phi(x) - phi(x_0))$ ] Выразим приращение $phi$: #eq[ $phi(x) - phi(x_0) = -sum_(k = 1)^n (((partial F) / (partial x_k)(x_0, phi(x_0)) ) / ((partial F) / (partial y)(x_0, phi(x_0))) + gamma_k (x)) (x_k - x_0^k) $ ] где #eq[ $gamma_k (x) := -((partial F) / (partial x_k)(x_0, phi(x_0)) ) / ((partial F) / (partial y)(x_0, phi(x_0))) + ((partial F) / (partial x_k)(x_0, phi(x_0)) + tilde(alpha)_k (x) ) / ((partial F) / (partial y)(x_0, phi(x_0)) + tilde(beta)(x))$ ] Остаётся заметить, что $tilde(alpha)_k (x) ->_(x -> x_0) 0; tilde(beta) (x) ->_(x -> x_0) 0$, а это значит, что #eq[ $phi(x) - phi(x_0) = sum_(k = 1)^n A_k (x_k - x_0^k) + gamma(x); quad gamma(x) = o(norm(x - x_0)), x -> x_0$ ] Что и является требуемой дифференцируемостью $phi$ в $x_0$. ]
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit2/OOP.typ
typst
La programación orientada a objetos es un paradigma de programación que utiliza "objetos" para diseñar aplicaciones y programas de computadora. A diferencia de la programación procedimental, que se centra en funciones y la lógica para manipular datos, OOP se organiza en torno a los datos, es decir, los objetos, y los métodos que operan sobre estos datos. 1. *¿Qué es un Objeto?* - Un objeto es una entidad dentro de un programa que tiene un estado y comportamiento asociados. 2. *Características de un Objeto*: - *Estado*: Representado por atributos o campos. Define las características del objeto. - *Comportamiento*: Representado por métodos. Define lo que el objeto puede hacer. - *Encapsulamiento*: Los detalles internos del objeto, como su estado, están ocultos del exterior. Esto se logra mediante el uso de modificadores de acceso que restringen el acceso directo a los componentes del objeto.
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/3-methodology/study-1/variable-structure.typ
typst
MIT License
#import "../../../lib/mod.typ": * // #pagebreak() #let variable-timesteps(lookahead_horizon, lookahead_multiple) = { let n = 1 + (0.5 * (-1.0 + calc.sqrt(1.0 + 8.0 * lookahead_horizon / lookahead_multiple))) let n = calc.floor(n) let timesteps = () for i in range(lookahead_multiple * (n + 1)) { let section = int(i / lookahead_multiple) let f = (i - section * lookahead_multiple + lookahead_multiple / 2 * section) * (section + 1); if f >= lookahead_horizon { timesteps.push(lookahead_horizon) break } timesteps.push(f) } timesteps } === Variable Structure <s.variable-structure> // #jonas[Check this] Each variable is a separate structure holding internal state such as its belief expressed in the Gaussian moments form, aswell as a hashmap that buffers messages from connected factors. When the factorgraph is constructed, the variables are initialized such that the mean of their initial belief have them placed along the line segment from the robot's spawn point to its first waypoint. Variables are not spaced evenly in time, but are instead spaced apart in a monotonically increasing order. The algorithm for this is parameterized over $l_h in RR_+$ and $l_m in ZZ_+$ called _lookahead horizon_ and _lookahead multiple_ respectively. - #[$l_h$ is the time horizon in seconds that the last variable also referred to as the _horizon_ variable should be placed at. It is a dependant quantity that is computed from $r_R$, $|v_("target")|$ and $t_(K-1)$ as shown in @[email protected]. $ t_(0,1) = r_R / 2 |v_("target")|^(-1) $ <equ.time-between-current-and-next-state> $t_(0,1)$ is the time between the current state $v_0$ and the next state $v_(1)$. It is defined as such to constrain the robot from moving more than half its radius $r_R "/" 2$ in a timestep $Delta t$. $ l_h = t_(K-1) / t_(0,1) $ <equ.lookahead-horizon> $l_h$ is the ratio between $t_(K-1)$ and $t_(0,1)$ and represent the granularity or discretization of the timespan at which variables can be placed in. ] - $l_m$ groups variables together into chunks with even relative distance in time. After each $l_m$ group of variables the size between each increases by $1$. @f.variable-timesteps illustrates how the algorithm place the variables, and how the parameters influence the output. One thing of note is that $l_m - 1 = l_h$ achieves an even spacing of all variables. \ A thorough argument for this method of placing variables is not provided in #gbpplanner paper@gbpplanner nor the source code@gbpplanner-code. However, a plausible argument for this approach can be made based on the theory presented earlier in @s.b.factor-graphs. Firstly, variables close to the current state are placed with little distance between each other to ensure high maneuverability and fidelity. This arrangement ensures that the immediate future, has a higher influence on the trajectory optimized for. Secondly, variables spaced further into the future are less dense to prevent them from overwhelming the influence of near-term variables. This spacing accounts for the increasing uncertainty and broader maneuvers required as the robot plans further ahead. As the figure shows; $l_m$ can be modified to control how closely variables are grouped. A lookahead multiple of $1$ gives a strictly monotonically increasing sequence. As $l_m$ increases the number of variables increases. The bottom sequence with $l_m = 3$ strikes a balance between certain immediate control and broader future planning. // The middle sequence with lm=19lm​=19 demonstrates this, with larger gaps indicating less frequent updates for distant future states. This approach captures uncertainty without excessive computational load. // // The bottom sequence, with lm=3lm​=3, strikes a balance between detailed immediate control and broader future planning. This method ensures that the robot can coordinate path deviations and interactions with other robots using interrobot factors effectively, without the burden of overly dense variable placement. // // This method ensures a practical trade-off between precision in the immediate future and computational efficiency for long-term planning, making it a robust choice for dynamic and uncertain environments. Despite the lack of a thorough explanation, the chosen approach appears to balance immediate responsiveness with long-term strategy effectively. // // // // // which critically influences the trajectory, is modeled with greater precision. As illustrated in the top sequence with lm=1lm​=1, closely packed variables allow for detailed control and quick adjustments, accommodating sudden changes or obstacles effectively. // // // // // A comment near the function generating the sequence explains that it was chosen on the simple basis that it seemed good enough. #todo[ref] \ // // HERE // // An argument for why that is could go as follows. First Variables are placed like this to ensure that has more maneouvebility and fidelity close in time to the current state such that it is primarily the immediate future that affects the trajectory derived at. Secondly variables further into the future should not overwhelm the variables closest to the current state, but should represent information uncertainty about broader maneuvers needed in the future such as coordinating path deviations through interrobots factors with other robots. // #k[ // The authors of the method do not thoroughly explain their choice of variable placement. However, a plausible argument for this approach can be made. // // Firstly, variables are placed densely near the current state to ensure high maneuverability and fidelity. This arrangement ensures that the immediate future, which critically influences the trajectory, is modeled with greater precision. As illustrated in the top sequence with lm=1lm​=1, closely packed variables allow for detailed control and quick adjustments, accommodating sudden changes or obstacles effectively. // // Secondly, variables spaced further into the future are less dense to prevent them from overwhelming the influence of near-term variables. This spacing accounts for the increasing uncertainty and broader maneuvers required as the robot plans further ahead. The middle sequence with lm=19lm​=19 demonstrates this, with larger gaps indicating less frequent updates for distant future states. This approach captures uncertainty without excessive computational load. // // The bottom sequence, with lm=3lm​=3, strikes a balance between detailed immediate control and broader future planning. This method ensures that the robot can coordinate path deviations and interactions with other robots using interrobot factors effectively, without the burden of overly dense variable placement. // // This method ensures a practical trade-off between precision in the immediate future and computational efficiency for long-term planning, making it a robust choice for dynamic and uncertain environments. Despite the lack of a thorough explanation, the chosen approach appears to balance immediate responsiveness with long-term strategy effectively. // // ] // Likewise this formulation does not make it possible to change the number of variables $|V|$ independent of the parameters $r_R, |v_("target")|, t_(K-1)$ and $l_m$. // #k[argue why this way of placing the variables are a good way of doing it.] // // #line(length: 100%, stroke: 1em + red) // // maximum possible number of variables is $l_h$ // // Meaning that the number of variables are formulated/defined to be a dependent variable on the $r_R$, $|v_max|$ and $t_(K-1)$ // // $ |V| = 2 $ <equ.number-of-variables> // spacing should sort of increase exponentially // T0 = ROBOT_RADIUS / 2.f / // MAX_SPEED; // Time between current state and next state of planned path // eg. variables are in groups of size lookahead_multiple. // the spacing within a group increases by one each time (1 for the first // group, 2 for the second ...) Seems convoluted, but the reasoning was: // the first variable should always be at 1 timestep from the current // state (0). the first few variables should be close together in time // the variables should all be at integer timesteps, but the spacing // should sort of increase exponentially. // T0 = ROBOT_RADIUS / 2.f / // MAX_SPEED; // Time between current state and next state of planned path // Variable Timesteps // The choice was selected as being "good enough" // Cap max speed, since it should be <= ROBOT_RADIUS/2.f / TIMESTEP: // In one timestep a robot should not move more than half of its radius #figure( std-block(image("../../../figures/out/variable-timesteps.svg")), caption: [ Three different results of the variable placement algorithm from $0$ to $t_(K-1) = 12$ in seconds, with $t_(0,1) = 1s$. The top sequence is generated with $l_m=1$. The middle with $l_m = 11$ and the bottom one with $l_m = 3$. ] ) <f.variable-timesteps> // #k[does $l_m = 1$ give even spacing?] // #k[describe as an algorithm] #par(first-line-indent: 0pt)[The Settings Panel @s.m.simulation-tool provide slider widgets to manipulate both $t_(K-1)$ and $l_m$. With this a user of the simulation can quickly experiment with the parameters and find a combination that suit the complexity of the simulated scenario.]
https://github.com/GYPpro/Java-coures-report
https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/Report/2.typ
typst
#set text(font:("Times New Roman","Source Han Serif SC")) #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Display block code in a larger block // with more padding. #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) #show raw: set text( font: ("consolas", "Source Han Serif SC") ) #set math.equation(numbering: "(1)") #set text( font:("Times New Roman","Source Han Serif SC"), style:"normal", weight: "regular", size: 13pt, ) #set page( paper:"a4", number-align: right, margin: (x:2.54cm,y:4cm), header: [ #set text( size: 25pt, font: "KaiTi", ) #align( bottom + center, [ #strong[暨南大学本科实验报告专用纸(附页)] ] ) #line(start: (0pt,-5pt),end:(453pt,-5pt)) ] ) = 基础IO操作 \ #text("*") 实验项目类型:设计性\ #text("*")此表由学生按顺序填写\ #text( font:"KaiTi", size: 15pt )[ 课程名称#underline[#text(" 面向对象程序设计/JAVA语言 ")]成绩评定#underline[#text(" ")]\ 实验项目名称#underline[#text(" 基础IO操作 ")]指导老师#underline[#text(" 干晓聪 ")]\ 实验项目编号#underline[#text(" 1 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\ 学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\ 学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\ 实验时间#underline[#text(" 2023年10月20日上午 ")]#text("~")#underline[#text(" 2023年10月20日中午 ")]\ ] #set heading( numbering: "一、" ) #set par( first-line-indent: 1.8em) = 实验目的 \ #h(1.8em)熟悉输入输出与基础面向过程语法 = 实验环境 \ #h(1.8em)计算机:PC X64 操作系统:Windows 编程语言:Java IDE:Visual Studio Code = 程序原理 \ #h(1.8em)使用了Scanner实现了输入一个给定长度的差分数组,求出其原数组,即对数组进行逐项求和。 #pagebreak() = 程序代码 \ 文件:`sis1\basicIO.java` ```java package sis1; import java.util.ArrayList; import java.util.Scanner; public class basicIO { public static void main(String[] args) { String initOutputMessage = "Input a div_arr(差分数组),this program will cacu the row arr.\nfirstly, you should input the length of your arr\n"; System.out.print(initOutputMessage); int n; Scanner sc = new Scanner(System.in); n = sc.nextInt(); ArrayList<Integer> arr = new ArrayList<Integer>(n); for(int i = 0;i < n;i ++) { int tmp = sc.nextInt(); arr.add(tmp); } System.out.print(arr.get(0) + " "); for(int i = 1;i < n;i ++) { arr.set(i,arr.get(i-1)+arr.get(i)); System.out.print(arr.get(i) + " "); } System.out.print("\n"); sc.close(); } } ``` = 出现的问题、原因与解决方法 \ #h(1.8em)未出现问题 #pagebreak() = 测试数据与运行结果 #figure( table( align: left + horizon, columns: 3, [*输入*],[*输出*],[*解释*], [],[`Input a div_arr(差分数组),this program will cacu the row arr. firstly, you should input the length of your arr`],[], [`3 1 2 3`],[`1 3 6 `],[输入三个数:\ 1 2 3 \ 答案为1 3 6] ) )
https://github.com/ckunte/m-one
https://raw.githubusercontent.com/ckunte/m-one/master/inc/wind.typ
typst
= Wind The following offers a way to visualize wind profile for a given $U_o$ and $t$ for a range of heights up to a maximum of $h$. == Based on ISO 19901-1:2005@iso19901-1_2005 #figure( image("/img/isowind.svg", width: 100%), caption: [Wind as per ISO 19901] ) <iw> #pagebreak(weak: true) Plot code to generate @iw is as follows. #let isowind = read("/src/isowind.py") #{linebreak();raw(isowind, lang: "python")} == Probability density function #figure( image("/img/pdf.svg", width: 100%), caption: [Probability density function] ) <p1> Plot code to generate @p1 is as follows. #let wind_pdf = read("/src/wind_pdf.py") #{linebreak();raw(wind_pdf, lang: "python")} == Based on EN 1991-1-4:2005@en1991-1-4_2005 The generic nature of EN's applicability makes for a complicated recipe. The number of things one needs to determine before one even gets to wind velocity is staggering. Here's a flavour of things that come with the territory. #figure( image("/img/enwind.png", width: 100%), caption: [PVP, RF, TI, TLS] ) <enw> Here is the code for these plots. #let enwind = read("/src/enwind.py") #{linebreak();raw(enwind, lang: "python")} $ - * - $
https://github.com/TeddyHuang-00/typpuccino
https://raw.githubusercontent.com/TeddyHuang-00/typpuccino/main/src/macchiato.typ
typst
MIT License
#let rosewater = rgb(244, 219, 214) #let flamingo = rgb(240, 198, 198) #let pink = rgb(245, 189, 230) #let mauve = rgb(198, 160, 246) #let red = rgb(237, 135, 150) #let maroon = rgb(238, 153, 160) #let peach = rgb(245, 169, 127) #let yellow = rgb(238, 212, 159) #let green = rgb(166, 218, 149) #let teal = rgb(139, 213, 202) #let sky = rgb(145, 215, 227) #let sapphire = rgb(125, 196, 228) #let blue = rgb(138, 173, 244) #let lavender = rgb(183, 189, 248) #let text = rgb(202, 211, 245) #let subtext1 = rgb(184, 192, 224) #let subtext0 = rgb(165, 173, 203) #let overlay2 = rgb(147, 154, 183) #let overlay1 = rgb(128, 135, 162) #let overlay0 = rgb(110, 115, 141) #let surface2 = rgb(91, 96, 120) #let surface1 = rgb(73, 77, 100) #let surface0 = rgb(54, 58, 79) #let base = rgb(36, 39, 58) #let mantle = rgb(30, 32, 48) #let crust = rgb(24, 25, 38) #let color-entries = ( "rosewater": rosewater, "flamingo": flamingo, "pink": pink, "mauve": mauve, "red": red, "maroon": maroon, "peach": peach, "yellow": yellow, "green": green, "teal": teal, "sky": sky, "sapphire": sapphire, "blue": blue, "lavender": lavender, "text": text, "subtext1": subtext1, "subtext0": subtext0, "overlay2": overlay2, "overlay1": overlay1, "overlay0": overlay0, "surface2": surface2, "surface1": surface1, "surface0": surface0, "base": base, "mantle": mantle, "crust": crust, )
https://github.com/choglost/LessElegantNote
https://raw.githubusercontent.com/choglost/LessElegantNote/main/example/less-elegant-note.typ
typst
MIT License
#import "../lib.typ": * #let ( // 布局函数 twoside, doc, mainmatter, appendix, preface, // 页面函数 fonts-display-page, cover, outline-page, ) = documentclass( twoside: false, // 双面模式,会加入空白页,便于打印 info: ( title: ("LessElegantNote:一个Typst笔记模版"), author: "IxionWheel", submit-date: datetime.today(), cover-image: "../example/images/cover.jpg", // 封面图片路径,注意是相对于pages/elgeant-cover.typ的路径 numbering-style:"maths" // "maths":数学或论文风格的标题编号 | "literature":文学风格的标题编号 ), ) // 文稿设置 #show: doc // 封面页 #cover() // 前言部分 #show: preface // 目录 #outline-page() // 字体显示测试页 // #fonts-display-page() // 正文部分 #show: mainmatter = 模版简介 本项目是一个Typst笔记模板。 == 模版下载 + 打开项目Github页面(https://github.com/IxionWheel/LessElegantNote)。 + 点击绿色Code按钮,下载ZIP压缩包。 + 解压到你喜欢的位置。 + 在vscode中_打开整个文件夹_,并安装_Tinymist Typst_插件。 + 打开example/less-elegant-note.typ,检查能否预览。 == 模版使用 + 参照less-elegant-note.typ,编写你自己的笔记。 + 例如可在LessElegantNote下新建一个mynotes文件夹,在其中新建一个 数学.typ 文件,并输入如下基础内容。 ```typst #import "../lib.typ": * #let ( // 布局函数 twoside, doc, mainmatter, appendix, preface, // 页面函数 fonts-display-page, cover, outline-page, ) = documentclass( twoside: false, // 双面模式,会加入空白页,便于打印 info: ( title: ("数学笔记"), author: "张三", submit-date: datetime.today(), cover-image: "", // 封面图片路径,注意是相对于pages/elgeant-cover.typ的路径 numbering-style:"maths" // "maths":数学或论文风格的标题编号 | "literature":文学风格的标题编号 ), ) // 文稿设置 #show: doc #cover()// 封面页 // 前言部分 #show: preface #outline-page()// 目录 // 正文部分 #show: mainmatter = 章节标题 == 子标题 正文内容 ``` = 模版设置说明 == 封面设置 == 文章格式设置 === 正文格式 === 标题格式 === 列表格式 = 写作示例 == 列表 === 无序列表 ```typst - 无序列表项一 - 无序列表项二 - 无序子列表项一 - 无序子列表项二 ``` - 无序列表项一 - 无序列表项二 - 无序子列表项一 - 无序子列表项二 === 有序列表 ```typst + 有序列表项一 + 有序列表项二 + 有序子列表项一 + 有序子列表项二 ``` + 有序列表项一 + 有序列表项二 + 有序子列表项一 + 有序子列表项二 === 术语列表 ```typst / 术语一: 术语解释 / 术语二: 术语解释 ``` / 术语一: 术语解释 / 术语二: 术语解释 == 图表 引用@tbl:timing,引用@tbl:timing-tlt,以及@fig:cover。引用图表时,表格和图片分别需要加上 `tbl:`和`fig:` 前缀才能正常显示编号。 #align(center, (stack(dir: ltr)[ #figure( table( align: center + horizon, columns: 4, [t], [1], [2], [3], [y], [0.3s], [0.4s], [0.8s], ), caption: [常规表], ) <timing> ][ #h(50pt) ][ #figure( table( columns: 4, stroke: none, table.hline(), [t], [1], [2], [3], table.hline(stroke: .5pt), [y], [0.3s], [0.4s], [0.8s], table.hline(), ), caption: [三线表], ) <timing-tlt> ])) #figure( image("images/cover.jpg", width: 20%), caption: [图片测试], ) <cover> == 数学公式 可以像 Markdown 一样写行内公式 $x + y$,以及带编号的行间公式: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> 引用数学公式需要加上 `eqt:` 前缀,则由@eqt:ratio,我们有: $ F_n = floor(1 / sqrt(5) phi.alt^n) $ 我们也可以通过 `<->` 标签来标识该行间公式不需要编号 $ y = integral_1^2 x^2 dif x $ <-> 而后续数学公式仍然能正常编号。 $ F_n = floor(1 / sqrt(5) phi.alt^n) $ == 定理环境 #show: thmrules.with(qed-symbol: $square$) #theorem("Euclid")[ There are infinitely many primes. ] #definition[ A natural number is called a #highlight[_prime number_] if it is greater than 1 and cannot be written as the product of two smaller natural numbers. ] #example[ The numbers $2$, $3$, and $17$ are prime. @cor_largest_prime shows that this list is not exhaustive! ] #proof[ Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list, it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since $p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a contradiction. ] #corollary[ There is no largest prime number. ] <cor_largest_prime> #corollary[ There are infinitely many composite numbers. ] #theorem[ There are arbitrarily long stretches of composite numbers. ] #proof[ For any $n > 2$, consider $ n! + 2, quad n! + 3, quad ..., quad n! + n $ ] == 代码块 // 代码块支持语法高亮。引用时需要加上 `lst:` @lst:code ````typst ```py def add(x, y): return x + y ``` ```` // #figure( // ```py // def add(x, y): // return x + y // ```, // caption:[代码块], // ) <code> // 手动分页 // #if twoside { // pagebreak() + " " // } // 附录 #show: appendix = 附录 == 子标题 附录内容
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/07_programmi_NN.typ
typst
#import "../alias.typ": * #import "@preview/algo:0.3.3": code #import "@preview/lemmify:0.1.5": * #let (theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules) = default-theorems( "thm-group", lang: "it", ) #show: thm-rules #show thm-selector("thm-group", subgroup: "theorem"): it => block( it, stroke: red + 1pt, inset: 1em, breakable: true, ) #show thm-selector("thm-group", subgroup: "proof"): it => block( it, stroke: green + 1pt, inset: 1em, breakable: true, ) = $programmi tilde NN$ La relazione interviene nella parte che afferma che $ F(cal(C)) tilde programmi tilde NN. $ In poche parole, la potenza computazionale, cioè l'insieme dei programmi che un sistema di calcolo $cal(C)$ riesce a calcolare, è isomorfa all'insieme di tutti i programmi, a loro volta isomorfi a $NN$. Per dimostrare l'ultima parte di questa catena di relazione dobbiamo esibire una legge che mi permetta di ricavare un numero dato un programma e viceversa. Per fare questo vediamo l'insieme $programmi$ come l'insieme dei programmi scritti in un certo linguaggio di programmazione. Analizzeremo due sistemi diversi: - sistema di calcolo RAM; - sistema di calcolo WHILE. In generale, ogni sistema di calcolo ha la propria macchina e il proprio linguaggio. == Sistema di calcolo RAM Il sistema di calcolo RAM è un sistema molto semplice che ci permette di definire rigorosamente: - $programmi tilde NN$; - la *semantica dei programmi eseguibili*, ovvero calcolo $cal(C)(P,\_)$ con $cal(C) = ram$, ottenendo $ram(P, \_)$; - la *potenza computazionale*, ovvero calcolo $F(cal(C))$ con $cal(C) = ram$, ottenendo $F(ram)$. Il linguaggio utilizzato è un assembly molto semplificato, immediato e semplice. Dopo aver definito $F(ram)$ potremmo chiederci se questa definizione sia troppo stringente e riduttiva per definire tutti i sistemi di calcolo. Introdurremo quindi delle macchine più sofisticate, dette *macchine while*, che, a differenza delle macchine RAM, sono _strutturate_. Infine, confronteremo $F(ram)$ e $F(mwhile)$. I due risultati possibili sono: - le potenze computazionali sono _diverse_: ciò che è computazionale dipende dallo strumento, cioè dal linguaggio utilizzato; - le potenze computazionali sono _uguali_: la computabilità è intrinseca dei problemi, non dello strumento. Il secondo è il caso più promettente e, in quel caso, cercheremo di trovare una caratterizzazione teorica, ovvero di _"recintare"_ tutti i problemi calcolabili. === Struttura Una macchina RAM è una macchina formata da un processore e da una memoria _potenzialmente infinita_ divisa in *celle/registri*, contenenti dei numeri naturali (i nostri dati aritmetizzati). Indichiamo i registri con $R_k$, con $k gt.eq 0$. Tra questi ci sono due registri particolari: - $R_0$ contiene l'_output_; - $R_1$ contiene l'_input_. Un altro registro molto importante, che non rientra nei registri $R_k$, è il registro $L$, detto anche *program counter* (_PC_). Questo registro è essenziale in questa architettura, in quanto indica l'indirizzo della prossima istruzione da eseguire. Dato un programma $P$, indichiamo con $|P|$ il numero di istruzioni che il programma contiene. Le istruzioni nel linguaggio RAM sono: - *incremento*: $inc(R_k)$; - *decremento*: $subsus(R_k)$; - *salto condizionato*: $ifgoto(R_k, m)$, con $m in {1, dots, |P|}$. L'istruzione di decremento é tale che $ x overset(-,.) y = cases(x - y quad & "se" x gt.eq y, 0 & "altrimenti") quad . $ === Esecuzione di un programma RAM L'esecuzione di un programma su una macchina RAM segue i seguenti passi: + *Inizializzazione*: + viene caricato il programma $P equiv istr(1), dots, istr(n)$ in memoria; + il PC viene posto a $1$ per indicare di eseguire la prima istruzione del programma; + nel registro $R_1$ viene caricato l'input; + ogni altro registro è azzerato. + *Esecuzione*: si eseguono tutte le istruzioni _una dopo l'altra_, ovvero ad ogni iterazione passo da $L$ a $L+1$, a meno di istruzioni di salto. Essendo il linguaggio RAM _non strutturato_ il PC è necessario per indicare ogni volta l'istruzione da eseguire al passo successivo. Un linguaggio strutturato, invece, sa sempre quale istruzione eseguire dopo quella corrente, infatti non è dotato di PC; + *Terminazione*: per convenzione si mette $L = 0$ per indicare che l'esecuzione del programma è finita oppure è andata in loop. Questo segnale, nel caso il programma termini, è detto *segnale di halt* e arresta la macchina; + *Output*: il contenuto di $R_0$, se vado in halt, contiene il risultato dell'esecuzione del programma $P$. Indichiamo con $phi_P (n)$ il contenuto del registro $R_0$ (in caso di halt) oppure $bot$ (in caso di loop), allora: $ phi_P (n) = cases(op("contenuto")(R_0) quad & "se halt", bot & "se loop") quad . $ Con $phi_P: NN arrow.long NN_bot$ indichiamo la *semantica* del programma $P$. Come indicavamo con $cal(C)(P, \_)$ la semantica del programma $P$ nel sistema di calcolo $cal(C)$, indichiamo con $ram(P, \_) = phi_P$ la semantica del programma $P$ nel sistema di calcolo $ram$. === Esecuzione definita formalmente Vogliamo dare una definizione formale della semantica di un programma RAM. Quello che faremo sarà dare una *semantica operazionale* alle istruzioni RAM, ovvero specificare il significato di ogni istruzione esplicitando l'*effetto* che quell'istruzione ha sui registri della macchina. Per descrivere l'effetto di un'istruzione ci serviamo di una _foto_. L'idea che ci sta dietro è: + faccio una foto della macchina _prima_ dell'esecuzione dell'istruzione; + eseguo l'istruzione; + faccio una foto della macchina _dopo_ l'esecuzione dell'istruzione. La foto della macchina si chiama *stato* e deve descrivere completamente la situazione della macchina in un certo istante. La coppia $("StatoPrima", "StatoDopo")$ rappresenta la semantica operazionale di una data istruzione del linguaggio RAM. L'unica informazione da salvare dentro una foto è la situazione globale dei registri $R_k$ e il registro $L$. Il programma non serve, visto che rimane sempre uguale. La *computazione* del programma $P$ è una sequenza di stati $S_i$, ognuno generato dall'esecuzione di un'istruzione del programma. Diciamo che $P$ induce una sequenza di stati $S_i$. Se quest'ultima è formata da un numero infinito di stati, allora il programma è andato in loop. In caso contrario, nel registro $R_0$ si trova il risultato $y$ della computazione di $P$. In poche parole: $ phi_P: NN arrow.long NN_bot "tale che" phi_P (n) = cases(y & "se" exists S_("finale"), bot quad & "altrimenti") quad . $ Definiamo ora come passiamo da uno stato all'altro. Per far ciò, definiamo: - *stato*: istantanea di tutte le componenti della macchina, è una funzione $ S: {L,R_i} arrow.long NN $ tale che $S(R_k)$ restituisce il contenuto del registro $R_k$ quando la macchina si trova nello stato $S$. \ Gli stati possibili di una macchina appartengono all'insieme $ stati = {f : {L,R_i} arrow.long NN} = NN^({L,R_i}). $ Questa rappresentazione è molto comoda perché ho potenzialmente un numero di registri infinito. Se così non fosse avrei delle tuple per indicare tutti i possibili registri al posto dell'insieme ${L, R_i}$; - *stato finale*: uno stato finale è un qualsiasi stato $S$ tale che $S(L) = 0$; - *dati*: abbiamo già dimostrato come $dati tilde NN$; - *inizializzazione*: serve una funzione che, preso l'input, ci dia lo stato iniziale della macchina. La funzione è $ inizializzazione : NN arrow.long stati "tale che" inizializzazione(n) = iniziale. $ Lo stato $iniziale$ è tale che $ iniziale(R) = cases(1 quad & "se" R = L, n & "se" R = R_1, 0 & "altrimenti") quad ; $ - *programmi*: definisco $programmi$ come l'insieme dei programmi RAM. Ci manca da definire la _parte dinamica_ del programma, ovvero l'*esecuzione*. Definiamo la *funzione di stato prossimo* $ delta: stati times programmi arrow.long stati_bot $ tale che $ delta(S, P) = S', $ dove $S$ rappresenta lo stato attuale e $S'$ rappresenta lo stato prossimo dopo l'esecuzione di un'istruzione di $P$. La funzione $delta(S,P) = S'$ è tale che: - se $S(L) = 0$ ho halt, ovvero deve terminare la computazione. Poniamo lo stato come indefinito, quindi $S' = bot$; - se $S(L) > |P|$ vuol dire che $P$ non contiene istruzioni che bloccano esplicitamente l'esecuzione del programma. Lo stato $S'$ è tale che: $ S'(R) = cases(0 & "se" R = L, S(R_i) quad & "se" R = R_i space forall i) quad ; $ - se $1 lt.eq S(L) lt.eq |P|$ considero l'istruzione $S(L)$-esima: - se ho incremento/decremento sul registro $R_k$ definisco $S'$ tale che $ cases(S'(L) = S(L) + 1, S'(R_k) = S(R_k) plus.minus 1, S'(R_i) = S(R_i) "per" i eq.not k) quad ; $ - se ho il GOTO sul registro $R_k$ che salta all'indirizzo $m$ definisco $S'$ tale che $ S'(L) = cases(m & "se" S(R_k) = 0, S(L) + 1 quad & "altrimenti") quad , \ \ S'(R_i) = S(R_i) quad forall i. $ L'esecuzione di un programma $P in programmi$ su input $n in NN$ genera una sequenza di stati $ S_0, S_1, dots, S_i, S_(i+1), dots $ tali che $ S_0 = inizializzazione(n) \ forall i quad S_(i+1) = delta(S_i, P). $ La sequenza è infinita quando $P$ va in loop, mentre se termina raggiunge uno stato $S_m$ tale che $S_m (L) = 0$, ovvero ha ricevuto il segnale di halt. La semantica di $P$ è $ phi_P (n) = cases(y quad & "se" P "termina in" S_m", con" S_m (L) = 0 " e " S_m (R_0) = y, bot & "se" P "va in loop") quad . $ La potenza computazionale del sistema RAM è: $ F(ram) = {f in NN_bot^NN bar.v exists P in programmi bar.v phi_P = f} = {phi_P bar.v P in programmi} subset.neq NN_bot^NN. $ L'insieme è formato da tutte le funzioni $f: NN arrow.long NN_bot$ che hanno un programma che le calcola in un sistema RAM. == Aritmetizzazione di un programma Per verificare che vale $programmi tilde NN$ dobbiamo trovare un modo per codificare i programmi in numeri in modo biunivoco. Notiamo che, data la lista di istruzioni semplici $P equiv istr(1), dots, istr(m)$, se questa fosse codificata come una lista di interi potremmo sfruttare la funzione coppia di Cantor per ottenere un numero associato al programma $P$. Quello che dobbiamo fare è trovare una funzione che trasforma le istruzioni in numeri, così da avere poi accesso alla funzione coppia per fare la codifica effettiva. In generale, il processo che associa biunivocamente un numero ad una struttura viene chiamato *aritmetizzazione* o *godelizzazione*. Troviamo una funzione $ar$ che associ ad ogni istruzione $I_k$ la sua codifica numerica $c_k$. Se la funzione trovata è anche biunivoca siamo sicuri di trovare la sua inversa, ovvero quella funzione che ci permette di ricavare l'istruzione $I_k$ data la sua codifica $c_k$. Riassumendo quanto detto finora, abbiamo deciso di trasformare ogni lista di istruzioni in una lista di numeri e, successivamente, applicare la funzione coppia di Cantor, ovvero $ [istr(1), dots, istr(n)] arrow.long.squiggly^(ar) [c_1, dots, c_n] arrow.long.squiggly^(cantor()) n. $ Vorremmo anche ottenere la lista di istruzioni originale data la sua codifica, ovvero $ n arrow.long.squiggly^(cantor()^(-1)) [c_1, dots, c_n] arrow.long.squiggly^(ar^(-1)) [istr(1), dots, istr(n)]. $ La nostra funzione _"complessiva"_ è biunivoca se dimostriamo la biunivocità della funzione $ar$, avendo già dimostrato questa proprietà per $cantor()$. Dobbiamo quindi trovare una funzione biunivoca $ar : istruzioni arrow.long NN$ con la sua funzione inversa $ar^(-1) : NN arrow.long istruzioni$ tali che $ ar(I) = n arrow.long.double.l.r ar^(-1)(n) = I. $ === Applicazione ai programmi RAM Dovendo codificare tre istruzioni nel linguaggio RAM, definiamo la funzione $ar$ tale che: $ ar(I) = cases(3k & "se" I equiv inc(R_k), 3k + 1 & "se" I equiv subsus(R_k), 3 cantor(k,m) - 1 quad & "se" I equiv ifgoto(R_k, m)) quad . $ Come è fatta l'inversa $ar^(-1)$? In base al modulo tra $n$ e $3$ ottengo una certa istruzione: $ ar^(-1)(n) = cases(inc(R_(n/3)) & "se" n mod 3 = 0, subsus(R_(frac(n-1,3))) & "se" n mod 3 = 1, "IF" R_(cantorsin(frac(n+1,3))) = 0 "THEN GOTO" cantordes(frac(n+1,3)) quad & "se" n mod 3 = 2) quad . $ La codifica del programma $P$ è quindi $ cod(P) = cantor(ar(istr(1)), dots, ar(istr(n))). $ Per tornare indietro devo prima invertire la funzione coppia di Cantor e poi invertire la funzione $ar$. La lunghezza del programma $P$, indicata con $|P|$, si calcola come $listlength(cod(P))$. Abbiamo quindi dimostrato che $programmi tilde NN$. === Osservazioni Vediamo una serie di osservazioni importanti: - avendo $n = cod(P)$ si può scrivere $ phi_P (t) = phi_n (t), $ ovvero la semantica di $P$ è uguale alla semantica della sua codifica; - i numeri diventano un _linguaggio di programmazione_; - posso scrivere l'insieme $ F(ram) = {phi_P : P in programmi} $ come $ F(ram) = {phi_i}_(i in NN). $ L'insieme, grazie alla dimostrazione di $programmi tilde NN$, è numerabile; - ho dimostrato rigorosamente che $ F(ram) tilde NN tilde.not NN_bot^NN, $ quindi anche nel sistema di calcolo RAM esistono funzioni non calcolabili; - la RAM è troppo elementare affinche $F(ram)$ rappresenti formalmente la "classe dei problemi risolubili automaticamente", quindi considerando un sistema di calcolo $cal(C)$ più sofisticato, ma comunque trattabile rigorosamente come il sistema RAM, potremmo dare un'idea formale di "ciò che è calcolabile automaticamente"; - se riesco a dimostrare che $F(ram) = F(cal(C))$ allora cambiare la tecnologia non cambia ciò che è calcolabile, ovvero la calcolabilità è intrinseca ai problemi, quindi possiamo _"catturarla"_ matematicamente. == Sistema di calcolo WHILE Introduciamo quindi il sistema di calcolo WHILE per vedere se riusciamo a "catturare" più o meno funzioni calcolabili della macchina RAM. === Struttura La *macchina WHILE*, come quella RAM, è molto semplice, essendo formata da una serie di *registri*, detti *variabili*, ma al contrario delle macchine RAM questi ultimi non sono _potenzialmente infiniti_, ma sono esattamente $21$. Il registro $R_0$ è il *registro di output*, mentre $R_1$ è il *registro di input*. Inoltre, non esiste il registro del program counter in quanto il linguaggio è _strutturato_ e ogni istruzione di questo linguaggio va eseguita in ordine. Il linguaggio WHILE prevede una *definizione induttiva*: vengono definiti alcuni comandi base e i comandi più complessi sono una concatenazione dei comandi base. Il comando di base è l'*assegnamento*. In questo linguaggio ne esistono di tre tipi: $ x_k &:= 0, \ x_k &:= x_j + 1, \ x_k &:= x_j overset(-,.) 1. $ Vediamo come queste istruzioni siamo molto più complete rispetto alle istruzioni RAM $ inc(R_k) \ subsus(R_k) $ in quanto con una sola istruzione possiamo azzerare il valore di una variabile o assegnare ad una variabile il valore di un'altra aumentata/diminuita di $1$. I comandi "induttivi" sono invece il comando while e il comando composto. Il *comando while* è un comando nella forma $ comandowhile, $ dove $C$ è detto *corpo* e può essere un assegnamento, un comando while o un comando composto. Il *comando composto* è un comando nella forma $ composto, $ dove i vari $C_i$ sono, come prima, assegnamenti, comandi while o comandi composti. Un *programma WHILE* è un comando composto, e l'insieme di tutti i programmi WHILE è l'insieme $ wprogrammi = {programmi "scritti in linguaggio" mwhile}. $ Chiamiamo $ Psi_W : NN arrow NN_bot $ la *semantica* del programma $W in wprogrammi$. Per dimostrare una proprietà $P$ di un programma $W in wprogrammi$ procederemo induttivamente: 1. dimostro $P$ vera sugli assegnamenti; 2. suppongo $P$ vera sul comando $C$ e la dimostro vera per $comandowhile$; 3. suppongo $P$ vera sui comandi $C_1, dots, C_n$ e la dimostro vera per $composto$. === Esecuzione di un programma WHILE L'esecuzione di un programma while $W$ è composta dalle seguenti fasi: + *inizializzazione*: ogni registro $x_i$ viene posto a $0$ tranne $x_1$, che contiene l'input $n$; + *esecuzione*: essendo $mwhile$ un linguaggio con strutture di controllo, non serve un program counter, perché le istruzioni di $W$ vengono eseguite una dopo l'altra; + *terminazione*: l'esecuzione di $W$ può: - _arrestarsi_, se sono arrivato al termine delle istruzioni; - _non arrestarsi_, se si è entrati in un loop; + *output*: se il programma va in halt, l'output è contenuto nel registro $x_0$. Possiamo scrivere $ Psi_W (n) = cases(op("contenuto")(x_0) quad & "se halt", bot & "se loop") quad . $ La funzione $Psi_W : NN arrow.long NN_bot$ indica la *semantica* del programma $W$. === Esecuzione definita formalmente Diamo ora la definizione formale della semantica di un programma $mwhile$. Come per i programmi RAM, abbiamo bisogno di una serie di elementi: + *stato*: usiamo una tupla grande quanto il numero di variabili, quindi $wstato(x) = (c_0, dots, c_20)$ rappresenta il nostro stato, con $c_i$ contenuto della variabile $i$; + $bold(wstati)$: insieme di tutti gli stati possibili, che è in $NN^21$, vista la definizione degli stati; + *dati*: sappiamo già che $dati tilde NN$; + *inizializzazione*: lo stato iniziale è descritto dalla seguente funzione $ winizializzazione(n) = (0,n,0,dots,0); $ + *semantica operazionale*: vogliamo trovare una funzione che, presi il comando da eseguire e lo stato corrente, restituisce lo stato prossimo. Soffermiamoci sull'ultimo punto. Vogliamo trovare la funzione $ [||](): wcomandi times wstati arrow.long wstati_bot $ che, dati un comando $C$ del linguaggio $mwhile$ e lo stato corrente $wstato(x)$, calcoli $ [|C|](wstato(x)) = wstato(y), $ con $wstato(y)$ stato prossimo. Quest'ultimo dipende dal comando $C$, ma essendo $C$ induttivo, possiamo provare a dare una definizione induttiva della funzione. Partiamo dal passo base, quindi dagli *assegnamenti*: $ [|x_k := 0|](wstato(x)) &= wstato(y) = cases(x_i quad & "se" i eq.not k, 0 & "se" i = k) quad , \ [|x_k := x_j plus.minus 1|](wstato(x)) &= wstato(y) = cases(x_i & "se" i eq.not k, x_j plus.minus 1 quad & "se" i = k) quad . $ Proseguiamo con il passo induttivo, quindi: - *comando composto*: vogliamo calcolare $ [|composto|](wstato(x)) $ conoscendo ogni $[|C_i|]$ per ipotesi induttiva. Calcoliamo allora la funzione: $ [|C_n|](dots([|C_2|]([|C_1|](wstato(x))))dots) = ([|C_n|] composizione dots composizione [|C_1|]) (wstato(x)), $ ovvero applichiamo in ordine i comandi $C_i$ presenti nel comando composto $C$. - *comando while*: vogliamo calcolare $ [|comandowhile|](wstato(x)) $ conoscendo ogni $[|C_i|]$ per ipotesi induttiva. Calcoliamo allora la funzione: $ [|C|](dots([|C|](wstato(x)))dots). $ Dobbiamo capire quante volte eseguiamo il loop: dato $[|C|]^e$ (comando $C$ eseguito $e$ volte) vorremmo trovare il valore di $e$. Questo è uguale al minimo numero di iterazioni che portano in uno stato in cui $x_k = 0$, ovvero il mio comando while diventa: $ comandowhile = cases([|C|]^e (wstato(x)) quad & "se" e = mu_t, bot & "altrimenti") quad . $ Il valore $e = mu_t$ è quel numero tale che $[|C|]^e (wstato(x))$ ha la $k$-esima componente dello stato uguale a $0$. Definita la semantica operazionale, manca solo da definire cos'è la *semantica del programma* $W$ su input $n$. Quest'ultima è la funzione $ Psi_W : NN arrow.long NN_bot bar.v Psi_W (n) = op("Proj")(0, [|W|](winizializzazione(n))). $ Questo è valido in quanto $W$, programma $mwhile$, è un programma composto, e abbiamo definito come deve comportarsi la funzione $[||]()$ sui comandi composti. La *potenza computazionale* del sistema di calcolo $mwhile$ è l'insieme $ F(mwhile) = {f in NN_bot^NN bar.v exists W in wprogrammi bar.v f = Psi_W} = {Psi_W : W in wprogrammi}, $ ovvero l'insieme formato da tutte le funzioni che possono essere calcolate con un programma in $wprogrammi$. == Confronto tra macchina RAM e macchina WHILE Viene naturale andare a confrontare i due sistemi di calcolo descritti, cercando di capire quale è "più potente" dell'altro, sempre che ce ne sia uno. Ci sono quattro possibili situazioni: - $F(ram) subset.neq F(mwhile)$, che sarebbe anche comprensibile vista l'estrema semplicità del sistema $ram$; - $F(ram) sect F(mwhile) = emptyset.rev$ (_insiemi disgiunti_) o abbia elementi (_insiemi sghembi_). Questo scenario sarebbe preoccupante, perché il concetto di calcolabile dipenderebbe dalla macchina che si sta utilizzando; - $F(mwhile) subset.eq F(ram)$, che sarebbe sorprendente dato che il sistema $mwhile$ sembra più sofisticato del sistema $ram$, ma la relazione decreterebbe che il sistema $mwhile$ non è più potente del sistema $ram$; - $F(mwhile) = F(ram)$, sarebbe il risultato migliore, perché il concetto di _calcolabile_ non dipenderebbe dalla tecnologia utilizzata, ma sarebbe intrinseco nei problemi. Poniamo di avere $C_1$ e $C_2$ sistemi di calcolo con programmi in $c1programmi$ e $c2programmi$ e potenze computazionali $ F(C_1) = {f: NN arrow.long NN_bot bar.v exists P_1 in c1programmi bar.v f = Psi_P_1} = {Psi_P_1 : P_1 in c1programmi}, \ F(C_2) = {f: NN arrow.long NN_bot bar.v exists P_2 in c2programmi bar.v f = Psi_P_2} = {Psi_P_2 : P_2 in c2programmi}. $ Come mostro che $F(C_1) subset.eq F(C_2)$, ovvero che il primo sistema di calcolo non è più potente del secondo? Devo dimostrare che ogni elemento nel primo insieme deve stare anche nel secondo, ovvero: $ forall f in F(C_1) arrow.long.double f in F(C_2). $ Se _espandiamo_ la definizione di $f in F(C)$ allora la relazione diventa: $ forall P_1 in c1programmi bar.v f = Psi_P_1 arrow.long.double exists P_2 in c2programmi bar.v f = Psi_P_2 . $ In poche parole, per ogni programma calcolabile nel primo sistema di calcolo ne esiste uno con la stessa semantica nel secondo sistema. Quello che vogliamo trovare è un *compilatore*, ovvero una funzione che trasformi un programma del primo sistema in un programma del secondo sistema. Useremo il termine *traduttore* al posto di _compilatore_. === Traduzioni Dati $C_1$ e $C_2$ due sistemi di calcolo, definiamo *traduzione* da $C_1$ a $C_2$ una funzione $ T : c1programmi arrow.long c2programmi $ con le seguenti proprietà: - *programmabile*: esiste un modo per programmarla; - *completa*: sappia tradurre *ogni* programma in $c1programmi$ in un programma in $c2programmi$; - *corretta*: mantiene la semantica del programma di partenza, ovvero $ forall P in c1programmi quad Psi_P = phi_T(P), $ dove $Psi$ rappresenta la semantica dei programmi in $c1programmi$ e $phi$ rappresenta la semantica dei programmi in $c2programmi$. #theorem(numbering: none)[ Se esiste $T : c1programmi arrow.long c2programmi$ allora $F(C_1) subset.eq F(C_2)$. ] #proof[ \ Se $f in F(C_1)$ allora esiste un programma $P_1 in c1programmi$ tale che $Psi_P_1 = f$. A questo programma $P_1$ applico $T$, ottenendo $T(P_1) = P_2 in c2programmi$ (per _completezza_) tale che $phi_P_2 = Psi_P_1 = f$ (per _correttezza_). Ho trovato un programma $P_2 in c2programmi$ la cui semantica è $f$, allora $F(C_1) subset.eq F(C_2)$. ] Mostreremo che $F(mwhile) subset.eq F(ram)$, ovvero il sistema $mwhile$ non è più potente del sistema $ram$. Quello che faremo sarà costruire un compilatore $ op("Comp") : wprogrammi arrow.long programmi $ che rispetti le caratteristiche di programmabilità, completezza e correttezza. === Compilatore da WHILE a RAM Per comodità andiamo ad usare un linguaggio RAM *etichettato*: esso aggiunge la possibilità di etichettare un'istruzione che indica un punto di salto o di arrivo. In altre parole, le etichette rimpiazzano gli indirizzi di salto, che erano indicati con un numero di istruzione. Questa aggiunta non aumenta la potenza espressiva del linguaggio, essendo pura sintassi: il $ram$ etichettato si traduce facilmente nel $ram$ _puro_. Essendo $wprogrammi$ un insieme definito induttivamente, possiamo definire anche il compilatore induttivamente: - *passo base*: mostro come compilare gli assegnamenti; - *passo induttivo*: + per ipotesi induttiva, assumo di sapere $compilatore(C_1), dots, compilatore(C_m)$ e mostro come compilare il comando composto $composto$; + per ipotesi induttiva, assumo di sapere $compilatore(C)$ e mostro come compilare il comando while $comandowhile$. Nelle traduzioni andremo a mappare la variabile WHILE $x_k$ nel registro $ram R_k$. Questo non mi crea problemi o conflitti, perché sto mappando un numero finito di registri ($21$) in un insieme infinito. Il primo assegnamento che mappiamo è $x_k := 0$. $ compilatore(x_k := 0) = "LOOP" : & ifgoto(R_k, "EXIT") \ & subsus(R_k) \ & ifgoto(R_21, "LOOP") \ "EXIT" : & subsus(R_K) quad . $ Questo programma $ram$ azzera il valore di $R_k$ usando il registro $R_21$ per saltare al check della condizione iniziale. Viene utilizzato il registro $R_21$ perché, non essendo mappato su nessuna variabile $mwhile$, sarà sempre nullo dopo la fase di inizializzazione. Gli altri due assegnamenti da mappare sono $x_k := x_j + 1$ e $x_k := x_j overset(-,.) 1$. Se $k = j$,la traduzione è immediata e banale e l'istruzione $ram$ è $ compilatore(x_k := x_k plus.minus 1) = R_k arrow.long.l R_k plus.minus 1. $ Se invece $k eq.not j$ la prima idea che viene in mente è quella di "migrare" $x_j$ in $x_k$ e poi fare $plus.minus 1$, ma non funziona per due ragioni: + se $R_k eq.not 0$, la migrazione (quindi sommare $R_j$ a $R_k$) non mi genera $R_j$ dentro $R_k$. Possiamo risolvere azzerando il registro $R_k$ prima della migrazione; + $R_j$ dopo il trasferimento è ridotto a 0, ma questo non è il senso di quella istruzione: infatti, io vorrei solo _"fotocopiarlo"_ dentro $R_k$. Questo può essere risolto salvando $R_j$ in un altro registro, azzerare $R_k$, spostare $R_j$ e ripristinare il valore originale di $R_j$. Ricapitolando: + #text(red)[salviamo $x_j$ in $R_22$, registro _sicuro_ perché mai coinvolto in altre istruzioni;] + #text(orange)[azzeriamo $R_k$;] + #text(green)[rigeneriamo $R_j$ e settiamo $R_k$ da $R_22$;] + #text(blue)[$plus.minus 1$ in $R_k$.] $ compilatore(x_k := x_j plus.minus 1) = colorcode(#red, "LOOP" : & ifgoto(R_j, "EXIT1") \ & subsus(R_j) \ & inc(R_22) \ & ifgoto(R_21, "LOOP")) \ colorcode(#orange, "EXIT1" : & ifgoto(R_k, "EXIT2") \ & subsus(R_k) \ & ifgoto(R_21, "EXIT1")) \ colorcode(#green, "EXIT2" : & ifgoto(R_22, "EXIT3") \ & inc(R_k) \ & inc(R_j) \ & subsus(R_22) \ & ifgoto(R_21, "EXIT2")) \ colorcode(#blue, "EXIT3" : & R_k arrow.long.l R_k plus.minus 1) quad . $ Per ipotesi induttiva, sappiamo come compilare $C_1, dots, C_m$. Possiamo calcolare la compilazione del comando composto come $ compilatore(composto) = & compilatore(C_1) \ & dots \ & compilatore(C_m) quad . $ Per ipotesi induttiva, sappiamo come compilare $C$. Possiamo calcolare la compilazione del comando while come $ compilatore(comandowhile) = "LOOP" : & ifgoto(R_k, "EXIT") \ & compilatore(C) \ & ifgoto(R_21, "LOOP") \ "EXIT" : & subsus(R_k) quad . $ La funzione $ compilatore : wprogrammi arrow.long programmi $ che abbiamo costruito soddisfa le tre proprietà che desideravamo, quindi $ F(mwhile) subset.eq F(ram). $ _Questa inclusione appena dimostrata è propria?_ === Interprete in WHILE per RAM Introduciamo il concetto di *interprete*. Chiamiamo $I_W$ l'interprete scritto in linguaggio WHILE per programmi scritti in linguaggio $ram$. $I_W$ prende in input un programma $P in programmi$ e un dato $x in NN$ e restituisce _"l'esecuzione"_ di $P$ sull'input $x$. Più formalmente, restituisce la semantica di $P$ su $x$, quindi $phi_P (x)$. Notiamo come l'interprete non crei dei prodotti intermedi, ma si limita ad eseguire $P$ sull'input $x$. Abbiamo due problemi principali: + il primo riguarda il tipo di input della macchina $mwhile$: questa non sa leggere il programma $P$ (listato di istruzioni $ram$), sa leggere solo numeri. Dobbiamo modificare $I_W$ in modo che non passi più $P$, piuttosto la sua codifica $cod(P) = n in NN$. Questo mi restituisce la semantica del programma codificato con $n$, che è $P$, quindi $phi_n (x) = phi_P (x)$. + il secondo problema riguarda la quantità di dati di input della macchina $mwhile$: quest'ultima legge l'input da un singolo registro, mentre qui ne stiamo passando due. Dobbiamo modificare $I_W$ condensando l'input con la funzione coppia di Cantor, che diventa $cantor(x,n)$. La semantica di $I_W$ diventa $ forall x,n in NN quad Psi_I_W (cantor(x,n)) = phi_n (x) = phi_P (x). $ Come prima, per comodità di scrittura useremo un altro linguaggio, il *macro-WHILE*. Questo include alcune macro che saranno molto comode nella scrittura di $I_W$. Visto che viene modificata solo la sintassi, la potenza del linguaggio non $mwhile$ non aumenta. Le macro utilizzate sono: - $x_k := x_j + x_s$; - $x_k := cantor(x_j, x_s)$; - $x_k := cantor(x_1, dots, x_n)$; - proiezione $x_k := proiezione(x_j, x_s)$: estrae l'elemento $x_j$-esimo dalla lista codificata in $x_s$; - incremento $x_k := macroincr(x_j, x_s)$: codifica la lista $x_s$ con l'elemento in posizione $x_j$-esima aumentato di uno; - decremento $x_k := macrodecr(x_j, x_s)$: codifica la lista $x_s$ con l'elemento in posizione $x_j$-esima diminuito di uno; - $x_k := cantorsin(x_j)$; - $x_k := cantordes(x_j)$; - costrutto $"if" dots "then" dots "else"$. Risolto il problema dell'input di un interprete scritto in linguaggio WHILE per i programmi RAM, ora vogliamo scrivere questo interprete, ricordando che per comodità non useremo il WHILE puro ma il macro-WHILE. Cosa fa l'interprete? In poche parole, esegue una dopo l'altra le istruzioni RAM del programma $P$ e restituisce il risultato $phi_P (x)$. Notiamo come restituiamo un risultato, non un eseguibile. Infatti, quello che fa l'interprete è ricostruire virtualmente tutto ciò che gli serve per gestire il programma. Nel nostro caso, $I_w$ deve ricostruire l'ambiente di una macchina RAM. Quello che faremo sarà ricreare il programma $P$, il program counter $L$ e i registri $R_0, R_1, R_2, dots$ dentro le variabili messe a disposizione dalla macchina WHILE. Qua sorge un problema: i programmi RAM possono utilizzare infiniti registri, mentre i programmi WHILE ne hanno solo $21$. _Ma veramente il programma P usa un numero infinito di registri?_ La risposta è no. Infatti, se $cod(P) = n$ allora $P$ non utilizza mai dei registri $R_j$, con $j > n$. Se uso un registro di indice $n+1$ non posso avere codifica $n$ perché l'istruzione che usa $n+1$ ha come codifica i numeri $3(n+1)$ se incremento, $3(n+1)+1$ se decremento oppure il numero generato da Cantor se GOTO. Inoltre, le singole istruzioni codificate vanno codificate tramite lista di Cantor, e abbiamo mostrato come questa funzione cresca molto rapidamente. Di conseguenza, possiamo restringerci a modellare i registri $R_0, dots, R_(n+2)$. Usiamo i registri fino a a $n+2$ solo per avere un paio di registri in più che potrebbero tornare utili. Ciò ci permette di codificare la memoria utilizzata dal programma $P$ tramite la funzione di Cantor. Vediamo, nel dettaglio, l'interno di $I_w (cantor(x,n)) = phi_n (x)$: - $x_0 arrow.long.l cantor(R_0, dots, R_(n+2))$: stato della memoria della macchina RAM; - $x_1 arrow.long.l L$: program counter; - $x_2 arrow.long.l x$: dato su cui lavora $P$; - $x_3 arrow.long.l n$: "listato" del programma P; - $x_4$: codice dell'istruzione da eseguire, prelevata da $x_3$ grazie a $x_1$. Ricordiamo che all'avvio l'interprete $I_w$ trova il suo input nella variabile di input $x_1$. #code( fill: luma(240), indent-guides: 0.2pt + red, inset: 10pt, line-numbers: false, radius: 4pt, row-gutter: 6pt, stroke: 1pt + black )[ ```py # Inizializzazione input(<x,n>); # In x1 x2 := sin(x1); # Dato x x3 := des(x1); # Programma n x0 := <0,x2,0,...,0>; # Memoria iniziale x1 := 1; # Program counter # Esecuzione while (x1 != 0) do: # Se x1 = 0 HALT if (x1 > length(x2)) then # Sono fuori dal programma? x1 := 0; # Vado in HALT else x4 := Pro(x1, x3); # Fetch istruzione if (x4 mod 3 == 0) then # Incremento? x5 := x4 / 3; # Trovo k x0 := incr(x5, x0); # Incremento x1 := x1 + 1; # Istruzione successiva if (x4 mod 3 == 1) then # Decremento? x5 := (x4 - 1) / 3; # Trovo k x0 := decr(x5, x0); # Decremento x1 := x1 + 1; # Istruzione successiva if (x4 mod 3 == 2) then # GOTO? x5 := sin((x4 + 1) / 3); # Trovo k x6 := des((x4 + 1) / 3); # Trovo m if (Proj(x5, x0) == 0) then # Devo saltare? x1 := x4; # Salto a m else x1 := x1 + 1; # Istruzione successiva # Finalizzazione x0 := sin(x0); # Oppure Pro(0,x0) ``` ] Avendo in mano l'interprete $I_W$ possiamo costruire un compilatore $ compilatore : programmi arrow.long wprogrammi $ tale che $ compilatore(P in programmi) equiv & x_2 := cod(P) \ & x_1 := cantor(x_1, x_2) \ & I_W quad . $ Questo significa che il compilatore non fa altro che cablare all'input $x$ il programma RAM da interpretare e procede con l'esecuzione dell'interprete. Vediamo se le tre proprietà di un compilatore sono soddisfatte: - *programmabile*: sì, lo abbiamo appena fatto; - *completo*: l'interprete riesce a riconoscere ogni istruzione RAM e la riesce a codificare; - *corretto*: vale la relazione $P in programmi arrow.double.long compilatore(P) in wprogrammi$, quindi: $ Psi_(compilatore(P)) (x) = Psi_I_W (cantor(x,n)) = phi_n (x) = phi_P (x) $ rappresenta la sua semantica. Abbiamo dimostrato quindi che $ F(ram) subset.eq F(mwhile), $ che è l'inclusione opposta del precedente risultato. === Conseguenze Il risultato appena ottenuto ci permette di definire un teorema molto importante. #theorem( name: "Teorema di Böhm-Jacopini (1970)", numbering: none, )[ Per ogni programma con GOTO (RAM) ne esiste uno equivalente in un linguaggio strutturato (WHILE). ] Questo teorema è fondamentale perché lega la programmazione a basso livello con quella ad alto livello. In poche parole, il GOTO può essere eliminato e la programmazione a basso livello può essere sostituita da quella ad alto livello. Grazie alle due inclusioni dimostrate in precedenza abbiamo dimostrato anche che $ F(mwhile) subset.eq F(ram) \ F(ram) subset.eq F(mwhile) \ arrow.double.b \ F(ram) = F(mwhile) \ arrow.double.b \ F(ram) = F(mwhile) tilde programmi tilde NN tilde.not NN^NN_bot. $ Quindi, seppur profondamente diversi, i sistemi RAM e WHILE calcolano le stesse cose. Viene naturale chiedersi quindi quale sia la vera natura della calcolabilità. Un altro risultato che abbiamo dimostrato _formalmente_ è che nei sistemi di programmazione RAM e WHILE esistono funzioni *non calcolabili*, che sono nella _parte destra_ della catena scritta sopra. === Interprete universale Facciamo una mossa esotica: usiamo il compilatore da WHILE a RAM $ compilatore : wprogrammi arrow programmi $ sul programma $I_w$. _Lo possiamo fare?_ Certo, posso compilare $I_W$ perché è un programma WHILE. Chiamiamo questo risultato $ cal(U) = compilatore(I_W) in programmi. $ La sua semantica è $ phi_(cal(U)) (cantor(x,n)) = Psi_(I_W) (cantor(x,n)) = phi_n (x) $ dove $n$ è la codifica del programma RAM e $x$ il dato di input. Cosa abbiamo fatto vedere? Abbiamo appena mostrato che esiste un programma RAM in grado di *simulare* tutti gli altri programmi RAM. Questo programma viene detto *interprete universale*. Considereremo _"buono"_ un linguaggio se esiste un interprete universale per esso. === Concetto di calcolabilità generale Ricordiamo che il nostro obiettivo è andare a definire la regione delle funzioni calcolabili e, di conseguenza, anche quella delle funzioni non calcolabili. Abbiamo visto che RAM e WHILE permettono di calcolare le stesse cose. _Possiamo definire ciò che è calcolabile a prescindere dalle macchine che usiamo per calcolare?_ Come disse *Kleene*, vogliamo definire ciò che è calcolabile in termini più astratti, matematici, lontani dall'informatica. Se riusciamo a definire il concetto di calcolabile senza che siano nominate macchine calcolatrici, linguaggi e tecnologie ma utilizzando la matematica potremmo usare tutta la potenza di quest'ultima.
https://github.com/kristoferssolo/Mafia-the-Game-Description
https://raw.githubusercontent.com/kristoferssolo/Mafia-the-Game-Description/main/main.typ
typst
#import "layout.typ": project, indent-par #import "@preview/i-figured:0.1.0" #import "@preview/tablex:0.0.6": tablex, rowspanx, colspanx, cellx #import "utils.typ": * #show: project.with( university: "Latvijas Universitāte", faculty: "Datorikas fakultāte", title: [Tiešsaistes spēles sistēma "Mafija"\ Praktiskais darbs programminžinierijā], authors: ( "<NAME>, ac22065", "<NAME>, kc22015", "<NAME>, eg22086", "<NAME>, mk22092", "<NAME>, js21283", ), advisor: "prof. Dr. sc. comp. <NAME>", date: "Rīga 2024", ) #set heading(numbering: none) #pagebreak(weak: true) = Apzīmējumu saraksts #par( first-line-indent: 0cm, [ / API: lietojumprogrammu saskarne (angl. Application Program Interface); / Abonements: uz noteiktu laiku par maksu piešķirtās papildus lietotāja iespējas; / BCNF: Boisa-Kodda normālforma (angl. Boyce–Codd normal form) izmanto datu bāzu normalizācijā; / CSRF: Starpvietņu pieprasījuma viltošana (angl. Cross-Site Request Forgery) -- uzbrukuma veids, kurā ļaunprātīgi pieprasījumi tiek izsūtīti no lietotāja pārlūka, izmantojot lietotāja autentifikācijas datus; / DPD: datu plūsmas diagramma; / Dialogs: lietotāja saskarnes elements, kas parāda ziņojumu un piedāvā lietotājam vienu vai vairākas iespējas, kuras izvēlēties; / Docker/Konteineris: ir platforma, kas izmanto operētājsistēmas līmeņa virtualizāciju, lai piegādātu programmatūru; / ER modelis: entitāšu saišu modelis (angl. Entity-Relationship model); / GDPR: vispārīgā datu aizsardzības regula (angl. General Data Protection Regulation) -- Eiropas Savienības regula, kas nosaka kā jāapstrādā un jāaizsargā personu dati; / HTTP: hiperteksta pārsūtīšanas protokols (angl. Hypertext Transfer Protocol) -- protokols datu pārsūtīšanai tīmeklī, galvenokārt izmantojot tīmekļa lapas; / IP adrese: Interneta protokola adrese (angl. Internet Protocol address) -- unikāls numurs, kas tiek piešķirts katrai ierīcei, kas ir savienota ar datoru tīklu, kas izmanto IP komunikāciju; / Istaba (spēles istaba): lietotāju kopa, kas ir saistīti vienas spēles ietvaros, i.e., spēles instance; / Izvairīšanās simboli: izvairīšanās simboli (angl. escape symbols vai escape characters) ir īpaši simboli, kas ļauj iekļaut teksta virknēs simbolus, kuri parasti ir rezervēti citām funkcijām; / Karodziņš: Būla mainīgais, i.e., mainīgais, kas var būt patiess vai nepatiess; / Klienta identifikators: maksājumu apstrādātāja uzglabāts identifikators, kas ir saistīts ar sistēmas lietotāju; / Komandu injekcija: drošības uzbrukuma veids, kurā uzbrucējs var izpildīt ļaunprātīgas komandas sistēmā, izmantojot drošības nepilnības; / Loma (spēles loma): spēlēs loma, kam piemīt noteiktas darbības un mērķis; / Maksas siena: maksājums par lietotāju pieeju daļai no sistēmas piedāvātās funkcionalitātes; / PNG: portatīvā tīkla grafika (angl. Portable Network Graphics) ir rastra grafikas failu formāts, kas atbalsta datu saspiešanu bez zudumiem; / PPA: programmatūras projektējuma apraksts; / PPS: programmatūras prasību specifikācija; / PostgreSQL: ir atvērtā koda objektu-relationālās datu bāzes pārvaldības sistēma, kas atbalsta plašu strukturētas vaicājumu valodas funkcionalitāti; / SQL injekcija: drošības apdraudējums, kas rodas, kad uzbrucējs var ievietot vai "injicēt" SQL komandas datu bāzes vaicājumā, tādējādi mainot tā darbību vai izgūstot konfidenciālu informāciju; / SQL: strukturēta vaicājumu valoda (angl. val. Structured Query Language) ir standartizēta programmēšanas valoda, kas ir plaši izmantojama datu bāzu pārvaldībai; / Sanitizēšana: Datu vai ievades apstrāde, lai noņemtu vai neitralizētu potenciāli kaitīgus vai nevēlamus elementus; / Sistēmas loma: sistēmas lietotāju grupa ar noteiktām privilēģijām; / Skripts: Automatizēta instrukciju virkne, kas izpilda noteiktas darbības programmēšanas vai sistēmas vidē; / Spēlētājs: lietotāja ieraksts vienas virtuālās istabas kontekstā; / Sāls pievienošana: Drošības metode, kurā pirms paroles jaucējfunkcijas izmantošanas tai tiek pievienots nejaušs simbolu virknes fragments, lai padarītu paroles atšifrēšanu sarežģītāku; / UTC: saskaņotais pasaules laiks (angl. Coordinated Universal Time) -- starptautisks, ļoti precīzs un stabils laika noteikšanas standarts; / UTF8: Vienota teksta formāta kodējums 8-bitu garumā (angl. Unicode Transformation Format -- 8 bit) -- populārs teksta kodējums, kas atbalsta visu pasaules valodu rakstzīmes; / XSS: Starpvietņu skriptēšana (angl. Cross-Site Scripting) -- drošības uzbrukuma veids, kurā uzbrucēji ievieto ļaunprātīgus skriptus tīmekļa lapā, kas tiek izpildīti citu lietotāju pārlūkos. ], ) #pagebreak(weak: true) = Ievads == Nolūks #indent-par([ Šī dokumenta mērķis ir raksturot tiešsaistes sistēmas "Mafija" programmatūras prasības. Sistēma ir paredzēta individuāliem lietotājiem, kuru interesēs ir iesaistīties savstarpējā sociālā aktivitātē lomu spēles formātā. ]) == Darbības sfēra #indent-par([ Sistēma "Mafija" ir atvasināta no plaši pazīstamas sociālas lomu spēles, kas balstīta uz dedukciju. Spēlē piedalās indivīdi -- spēlētāji. Tiem piešķirtas lomas, kas pieder kādai lomu grupai. Lomu grupa "Ciems" cenšas izdibināt kuri ir lomu grupas "Mafija" locekļi. Mafijas mērķis ir radīt haosu ciema iedzīvotāju vidū un pakāpeniski izslēgt ciema iedzīvotājus no spēles, izmantojot stratēģisku manipulāciju un iedalītās lomas darbības. Spēlētāji, kuri nav ietverti ne "Ciems", ne "Mafija" lomu grupā cenšas sasniegt tiem iedalītās lomas mērķi. Tikai "Mafijas" locekļiem ir informācija par to, kuri no spēlētāju loka pieder "Mafija" lomu grupai. Katram spēlētājam jāizmanto individuāla ierīce, kas var pieslēgties tīmeklim, lai pieteiktos sistēmā, pievienotos konkrētai spēlei un tajā piedalītos. ]) Katra spēlētāja ierīcē spēles sesijas laikā tiek parādīta informācija par iedalīto lomu un ar to saistītajām, pieejamajām darbībām. Informāciju nav paredzēts vai atļauts rādīt citiem spēlētājiem. Sistēmas vizuālā saskarne ietver informāciju par spēles aktuālo stāvokli, precīzāk, fāzi (diena, nakts vai balsošana), spēles ilgumu, palikušo spēlētāju skaitu un citiem spēli raksturojošiem faktoriem. Spēlētāja darbību klāsts ir atkarīgs no iedalītās lomas un aktuālā spēles stāvokļa. Spēles organizatoram (maksas lietotājam) ir iespēja izveidot virtuālu istabu un pielāgot tās uzstādījumus, lai mainītu to uzstādījumu, kas ietver noteiktās lomas, kā arī mainīt un veidot jaunas lomas. Maksas lietotājs spēj izveidot jaunas lomas ar kādu darbību kombināciju, ko, savukārt, var izmantot spēles uzstādījumos, kas ir kombinācijas no lomām -- gan pamata izveidotām, gan citu lietotāju (publiski) izveidotām. Katram spēlētājam tiek nodrošināta sinhronizēta informācija par spēles stāvokli un pieejamajām darbībām, tai skaitā, paziņojumi par spēles stāvokļa izmaiņām. Ārpus spēles sesijas, lietotājiem ir pieejams spēļu istabu saraksts, kas var ietvert gan atvērtas, gan privātas virtuālās spēļu telpas, un lietotāja profils, kurā var rediģēt lietotāju raksturojošo informāciju. // Explain customization of the roles / setups == Saistība ar citiem dokumentiem #indent-par([ PPS ir izstrādāta, ievērojot LVS 68:1996 "Programmatūras prasību specifikācijas ceļvedis" un LVS 72:1996 "Ieteicamā prakse programmatūras projektējuma aprakstīšanai" standarta prasības. ]) == Pārskats #indent-par([ Dokumenta ievads satur tā nolūku, izstrādājamās programmatūras skaidrojumu, vispārīgu programmatūras mērķi un funkciju klāstu, saistību ar citiem dokumentiem, kuru prasības tika izmantotas dokumenta izstrādāšanas gaitā, kā arī pārskatu par dokumenta daļu saturu ar dokumenta struktūras skaidrojumu. ]) Pirmajā nodaļa tiek aprakstīti faktori, kas var ietekmēt produktu un tā prasības. Nodaļā tiek pamatota programmatūras izstrādes motivācija un nolūks, aprakstītas produkta vieta citu sistēmu perspektīvā, galvenās augsta līmeņa darījumprasības, sistēmas lietotāju grupu lomas un mērķi, kā arī tiek uzskaitīti faktori, kas var ierobežot vai ietekmēt programmatūras prasību specifikāciju. Otrajā nodaļā tiek norādītas konkrētas prasības, kas satur visu nepieciešamo programmatūras projektējuma veidošanai. Tā ietver: datu bāzes konceptuālo modeli, funkcionālās prasības, kas apraksta sistēmas funkciju sadalījumu pa moduļiem, arējās saskarnes prasības un sistēmas vispārējās prasības. Trešajā nodaļā tiek aprakstīta daļa no projektējuma. Nodaļa satur datu bāzes projektējumu - datubāzes loģisko modeli, fizisko modeli un tā lauku aprakstu -, dažu funkciju projektējumu diagrammas un dažu lietotāju saskarņu ekrānskatus. #set heading(numbering: "1.1.") = Vispārējais apraksts == Esošā stāvokļa apraksts #indent-par([ Tirgū pastāv vairākas sistēmas un citi programmatūras formāti, piemēram, lietotnes, kas piedāvā dažādas lomu spēļu variācijas, to skaitā, "Warewolf online", "Town of Salem", "Mafia.gg", "BeyondMafia", "Mafia: The Game" un daudzi citi. Esošiem risinājumiem ir vairākas problēmas: maksas piekļuve, pārmērīgs iespēju skaits, kas ir pieejamas tikai par maksu, spēle ir pieejama tikai uz mobilā viedtālruņa. "Mafija" īstenos svarīgākās no esošo spēļu iespējām un pievienos jaunas iespējas, kas papildinās un uzlabos lietotāju pieredzi, kā arī samazinās maksas funkciju īpatsvaru. ]) == Pasūtītājs #indent-par([ Sistēma nav izstrādāta pēc konkrēta pasūtītāja pieprasījuma, tā ir raksturota un projektēta ar iespēju realizēt pēc studentu grupas iniciatīvas programminženierijas kursa ietvaros. ]) == Produkta perspektīva #indent-par([ Sistēmā tiek integrēti vai izmantoti citu uzņēmumu un izstrādātāju piedāvāti pakalpojumi. Produkta realizācijā ir paredzēts izmantot maksājumu apstrātāja un e-pasta pakalpojumu sniedzēja pakalpojumus, kamēr tie atbilst sistēmas pieprasītajai funkcionalitātei un piedāvā optimālākos, kā arī drošākos un efektīvākos risinājumus tirgū. ]) Maksājumu apstrādātājs realizēs lietotāju maksas pakalpojumu iegādi konkrētu papildus funkciju iegūšanai uz noteiktu laiku. Informācija par abonementiem tiek glabāta galvenokārt ārpus sistēmas. Tiks izmantota pakalpojumu sniedzēja nodrošināta maksājumu apstrāde ārpus "Mafija" sistēmas, sistēmā glabājot minimālu informāciju par maksājumu, tas ir, klienta identifikatoru, ko sagatavo maksājumu pakalpojuma sniedzējs. E-pasta apstiprināšanas un paroles atjaunošanas e-pastu izsūtīšanai tiks izmantots e-pasta pakalpojumu sniedzējs. == Darījumprasības #indent-par([ Sistēmā tiks realizētas sekojošās darījumprasības: + Lietotāju reģistrācija, autentifikācija; + Lietotāju un to kontu pārvalde; + Lietotāju kontu apstiprināšana, izmantojot e-pastu; + Lietotāju profilu personalizācija un kontu rediģēšana; + Lietotāju stāvokļa virtuālajās telpās uzturēšana un izmaiņa; + Spēles automātiska vadība; + Lietotāju informēšana, izmantojot paziņojumu sistēmu; + Sinhronizēta spēles stāvokļa atjaunināšana; + Spēles uzstādījumu un lomu veidošana, rediģēšana un dzēšana; + Atvērtās un privātās virtuālās spēles istabas; + Kopēja un ierobežota (spēles lomu grupu atkarīga) tērzēšana; + Privilēģiju izmaiņa, izmantojot bezpersonisku maksājumu sistēmu; // Isn't it similar wo the 2nd? + Lietotāju administrēšana administratoru lietotāju grupai. ]) == Sistēmas lietotāji #indent-par([ Neautentificēts lietotājs (viesis), i.e., viesis ir jebkurš lietotājs, kas nav pieteicies vai reģistrējies sistēmā. Šiem lietotājiem ir pieejamas funkcijas, lai reģistrētos vai pieteiktos sistēmā; ]) Kad lietotājs ir pieteicies un ir autentificēts, tam ir pieejamas reģistrēta lietotāja grupas tiesības, precīzāk, darbības, kas saistītas ar spēli, profilu un konta pārvaldi. Tā būs vislielākā grupa pēc lietotāju skaita. Maksas lietotājiem, precīzāk, reģistrētiem lietotājiem, kuriem piesaistīts aktīvs abonements, tiek piešķirtas papildus tiesības -- izveidot jaunas virtuālās istabas, izveidot jaunu lomu, izvēlēties spēles uzstādījumus sevis veidotās istabās un citas. Maksas lietotāja grupa ir atvasināta no reģistrēta lietotāja grupas. Administratoru uzdevumi ietver lietotāju, spēles lomu un uzstādījumu rediģēšanu un lietotāju moderēšanu, izmantojot darbības, kā konta bloķēšana, konta rediģēšana, konta dzēšana, abonementa atcelšana, spēles atcelšana, spēlētāja izslēgšana, sarakstes dzēšana. Lietotājs "Sistēma" ir izmantots notikumu apstrādes izsaukšanai, kas ir nepieciešama automātiskai spēles gaitas vadībai. Ar lietotājiem saistītās datu plūsmas ir attēlotas sistēmas nultā līmeņa DPD (skat. @fig:dpd-0 att.) #figure( caption: "0. līmeņa DPD", image("img/dpd0/0tāLīmeņaDPD.svg"), ) <dpd-0> == Vispārējie ierobežojumi + Drošības un aizsardzības apsvērumi: + Lietotāju paroles tiek šifrētas pirms glabāšanas, izmantojot sāls pievienošanu AES-256 algoritmu; + Regulējošās politikas apsvērumi: + Tiek pieprasīta lietotāju atļauja realizēt analītisku datu ievākšanu, izmantojot sīkdatnes. + Tiek pieparsīta lietotāju atļauja personas datu ievākšanai un apstrādei, kas atbilst vispārējai datu aizsardzības regulai (GDPR) + Izstrādes vides, tehnoloģijas un tīmekļa ierobežojumi: + Programmēšanas valodas, to tehniskie ierobežojumi; + Responsivitāte; + Sistēmas saskarne ir tīmekļa vietne; + Sistēmas ietvaros mitināta vietne ir kopīga neatkarīgi no ierīces (netiek izmantots apakšdomēns mobilo tālruņu lietotājiem). == Pieņēmumi un atkarības - Ierīce atbilst un spēj pilnvērtīgi izpildīt sistēmas prasības; - Ierīce uztur stabilu interneta savienojumu ar joslas platumu vismaz 2 megabiti sekundē un latentumu līdz 1000ms; - Lietotāja izvēlētā pārlūkprogramma atbilst un spēj pilnvērtīgi izpildīt sistēmas prasības; // Added a note: Payment processor should offer similar functionality as required by the specification - Maksājumus apstrādās pasūtītāja izvēlēts pakalpojumu sniedzējs, nodrošinot tīmekļa vietnes saskarni maksājuma veikšanai un tā apstrādi ārpus "Mafija" sistēmas. Pasūtītāja izvēlētam maksājumu apstrādātājam ir jārealizē no tā sagaidāmā funkcionalitāte. #pagebreak(weak: true) = Programmatūras prasību specifikācija == Konceptuālais datu bāzes apraksts #indent-par([ Konceptuālajā modelī redzamās entitātes no konceptuālā ER modeļa (@fig:conceptual-model attēls): ]) - Lietotājs -- reģistrēts lietotājs, kas pieder noteiktai grupai; - Attēls -- datnes metadati un tās adrese, kas ir saistīta ar lietotāju vai spēles lomu; - Spēles uzstādījums -- vairāku spēles lomu kopa (konfigurācija), kas ir izveidojamas arī publiski (maksas lietotājiem); - Spēles loma -- spēlē izmantojamās lomas apraksts, katrai lomai obligāti piemīt darbības. Tā var tikt izveidota publiski (līdzīgi spēles uzstādījumiem); - Lomas darbība -- vienai vai vairākām spēles lomām piemītošās spēles darbības apraksts un spēlei specifiskie atribūti; - Spēlētājs -- vienai spēles istabai piederošais spēlētājs. Tam piemīt viena spēles loma un var būt vairākas spēles gaitā veiktās lomai atbilstošās darbības; - Sarakste -- virtuālās istabas tērzēšanā izveidotā sarakste, kas tiek saistīta ar vienu spēlētāju un var atbildēt uz citu saraksti izveides laikā; - Spēles notikums -- spēlē iespējamie notikumi, tai skaitā spēles fāzes maiņa, spēlētāju izslēgšana, piemēram, izbalsošana vai slepkavība un citi. - Istaba -- vienas gaidāmas, tekošās vai pagātnē notikušas spēles, kam piemīt spēlētāji, spēles uzstādījums, notikumi, izveidotājs (lietotājs maskas lietotāja grupā). Katrai spēlei ir sava istaba. #figure( caption: "Datu bāzes konceptuālais ER modelis", placement: auto, image("img/erd/KonceptualaisERModelis.svg"), ) <conceptual-model> == Funkcionālās prasības === Funkciju sadalījums moduļos #indent-par([ Funkciju sadalījums moduļos ir aprakstīts tabulā (@tbl:function-modules tab.). Katrs maksas lietotājs un administrators ir uzskatāms par reģistrētu lietotāju. Administratora privilēģijas ir atvasinātas no maksas lietotāja privilēģijas. Sistēmas lietotājs nav ierobežots. ]) Citas lietotāju grupas, izņemot reģistrētu lietotāju, tiek norādītas pie lietotāja grupas tikai tad, ja, funkcijas rezultāts atšķiras no rezultāta, kuru atgrieztu reģistrētam lietotājam. Tiek pieņemts, ka lietotāja autentifikācija ir izpildīta, izmantojot funkcijas, kur apstrāde ir neatkarīga no lietotāju grupas. \2. līmeņa DPD parāda izvērstāku 1. līmeņa (jeb konteksta) DPD ar sistēmas sadalījumu pa moduļiem. Pārskatāmības dēļ DPD tika sadalīta divās daļās (skat @fig:dpd-1.1 att. un @fig:dpd-1.2 att.). Datu plūsmas diagrammās tiek izlaisti lietotāja identifikācijas dati, ja tie ir nepieciešami lietotāja darbības autorizācijai. #figure( caption: "1. līmeņa DPD (1)", image("img/dpd1/1LīmeņaDPDN1.svg"), ) <dpd-1.1> #figure( caption: "1. līmeņa DPD (2)", image("img/dpd1/1LīmeņaDPDN2.svg"), ) <dpd-1.2> #pagebreak(weak: true) #figure( caption: "Funkciju sadalījums pa moduļiem", kind: table, tablex( columns: 4, /* --- header --- */ [*Modulis*], [*Funkcija*], [*Identifikators*], [*Lietotāja grupa*], /* -------------- */ rowspanx(7)[Reģistrācijas un pieteikšanās modulis], [Lietotāja reģistrācija], [#link(<AMF01>)[AMF01]], [Nereģistrēts lietotājs], [Apstiprinājuma ziņas atkārtotās izsūtīšanas pieteikums], [#link(<AMF02>)[AMF02]], [Reģistrēts lietotājs], [Paroles atjaunošanas pieteikums], [#link(<AMF03>)[AMF03]], [Reģistrēts lietotājs], [Paroles atjaunošana], [#link(<AMF04>)[AMF04]], [Reģistrēts lietotājs], [Lietotāja atteikšanās], [#link(<AMF05>)[AMF05]], [Reģistrēts lietotājs], [Lietotāja pieteikšanās], [#link(<AMF06>)[AMF06]], [Reģistrēts lietotājs], [Lietotāja konta apstiprināšana], [#link(<AMF07>)[AMF07]], [Reģistrēts lietotājs], rowspanx(5)[Lietotāju kontu modulis], [Lietotāju profilu pārskats], [#link(<LKMF01>)[LKMF01]], [Reģistrēts lietotājs], [Lietotāja konta detaļas], [#link(<LKMF02>)[LKMF02]], [Reģistrēts lietotājs, Administrators], [Lietotāja konta bloķēšana], [#link(<LKMF03>)[LKMF03]], [Administrators], [Lietotāja konta rediģēšana], [#link(<LKMF04>)[LKMF04]], [Reģistrēts lietotājs, Administrators], [Lietotāja konta dzēšana], [#link(<LKMF05>)[LKMF05]], [Reģistrēts lietotājs, Administrators], rowspanx(4)[Maksas abonementu modulis], [Abonementa pieteikums], [#link(<MAMF01>)[MAMF01]], [Reģistrēts lietotājs], [Abonementu pārskats], [#link(<MAMF02>)[MAMF02]], [Reģistrēts lietotājs, Administrators], [Abonementa atcelšana], [#link(<MAMF03>)[MAMF03]], [Maksas lietotājs], [Abonementa plānu pārskats], [#link(<MAMF04>)[MAMF04]], [Nereģistrēts lietotājs, Reģistrēts lietotājs], /*rowspanx(4)[Cenu modulis], [Cenas pievienošana], [#link(<CMF01>)[CMF01]], [Administrators], [Cenas rediģēšana], [#link(<CMF02>)[CMF02]], [Administrators], [Cenu pārskats], [#link(<CMF03>)[CMF03]], [Administrators], [Cenas dzēšana], [#link(<CMF04>)[CMF04]], [Administrators],*/ rowspanx(9)[Spēles istabu modulis], [Spēles istabu pārskats], [#link(<SIMF01>)[SIMF01]], [Reģistrēts lietotājs], [Pieslēgšanās spēles istabai], [#link(<SIMF02>)[SIMF02]], [Reģistrēts lietotājs], [Atslēgšanās no spēles istabas pieteikums], [#link(<SIMF03>)[SIMF03]], [Reģistrēts lietotājs], [Jaunas spēles istabas izveide], [#link(<SIMF04>)[SIMF04]], [Maksas lietotājs], [Spēles sākuma pieteikums], [#link(<SIMF05>)[SIMF05]], [Maksas lietotājs], [Spēlētāja izslēgšana], [#link(<SIMF06>)[SIMF06]], [Administrators], [Spēlētāju pārskats], [#link(<SIMF07>)[SIMF07]], [Reģistrēts lietotājs], [Spēļu vēstures pārskats], [#link(<SIMF08>)[SIMF08]], [Reģistrēts lietotājs], [Spēles atcelšana], [#link(<SIMF09>)[SIMF09]], [Maksas lietotājs, Administrators], rowspanx(4)[Tērzēšanas modulis], [Jaunas sarakstes izveidošana], [#link(<TMF01>)[TMF01]], [Reģistrēts lietotājs], [Sarakstes dzēšana], [#link(<TMF02>)[TMF02]], [Reģistrēts lietotājs, Administrators], [Sarakstu pārskats], [#link(<TMF03>)[TMF03]], [Reģistrēts lietotājs, Administrators], [Sarakstes rediģēšana], [#link(<TMF04>)[TMF04]], [Reģistrēts lietotājs], rowspanx(4)[Spēles gaitas modulis], [Spēles darbības veikšana], [#link(<SGMF01>)[SGMF01]], [Reģistrēts lietotājs], [Spēles notikumu izveidošana], [#link(<SGMF02>)[SGMF02]], [Sistēma], [Spēles notikumu pārskats], [#link(<SGMF03>)[SGMF03]], [Sistēma, Administrators, Reģistrēts lietotājs], [Spēles stāvokļa detaļas], [#link(<SGMF04>)[SGMF04]], [Sistēma, Administrators, Reģistrēts lietotājs], rowspanx(6)[Spēles lomu uzstādījumu modulis], [Lomas detaļas], [#link(<SLMF01>)[SLMF01]], [Reģistrēts lietotājs], [Lomu pārskats], [#link(<SLMF02>)[SLMF02]], [Reģistrēts lietotājs], [Lomas darbību pārskats], [#link(<SLMF03>)[SLMF03]], [Reģistrēts lietotājs], [Jaunas lomas izveidošana], [#link(<SLMF04>)[SLMF04]], [Maksas lietotājs, Administrators], [Lomas rediģēšana], [#link(<SLMF05>)[SLMF05]], [Maksas lietotājs, Administrators], [Lomas dzēšana], [#link(<SLMF06>)[SLMF06]], [Maksas lietotājs, Administrators], rowspanx(5)[Spēles uzstādījumu modulis], [Spēles uzstādījumu pārskats], [#link(<SUMF01>)[SUMF01]], [Reģistrēts lietotājs], [Spēles uzstādījuma lomu pārskats], [#link(<SUMF02>)[SUMF02]], [Reģistrēts lietotājs], [Jauna spēles uzstādījuma izveidošana], [#link(<SUMF03>)[SUMF03]], [Maksas lietotājs, Administrators], [Spēles uzstādījuma rediģēšana], [#link(<SUMF04>)[SUMF04]], [Maksas lietotājs, Administrators], [Spēles uzstādījuma dzēšana], [#link(<SUMF05>)[SUMF05]], [Maksas lietotājs, Administrators], ), ) <function-modules> === Kopīgās funkcijas ievades / izvades datu prasības #indent-par([ Apakšnodaļa ietver informāciju par funkciju parametriem, tai skaitā, nosaukumu, identifikatoru, aprakstu, parametra prasībām. Parametri ir aprakstīti atsevišķās tabulās (skat. #link(<IIDP01>)[IIDP01], #link(<IIDP02>)[IIDP02], #link(<IIDP03>)[IIDP03], #link(<IIDP04>)[IIDP04], #link(<IIDP05>)[IIDP05], #link(<IIDP06>)[IIDP06], #link(<IIDP07>)[IIDP07], #link(<IIDP08>)[IIDP08], #link(<IIDP09>)[IIDP09], #link(<IIDP10>)[IIDP10], #link(<IIDP11>)[IIDP11], #link(<IIDP12>)[IIDP12], #link(<IIDP13>)[IIDP13], #link(<IIDP14>)[IIDP14], #link(<IIDP15>)[IIDP15], #link(<IIDP16>)[IIDP16], #link(<IIDP17>)[IIDP17], #link(<IIDP18>)[IIDP18], #link(<IIDP19>)[IIDP19], #link(<IIDP20>)[IIDP20], #link(<IIDP21>)[IIDP21], #link(<IIDP22>)[IIDP22]). ]) #parameter-table( "Datuma simbolu virkne", "IIDP01", "Datums, kas ir reprezentēts ar simbolu virkni noteiktā formātā un laika zonā (sistēmas ietvaros tiek izmantota viena laika zona).", [ + Jāatbilst standarta ISO 8601 datumu formātam; + Gadam jābūt 4 cipariem; + Mēnesim un gadam jāsatur 2 ciparus, ar sākuma nullēm, ja attiecināms; + Gadu, mēnesi un dienu jāatdala ar svītru (-); + Datumu jānosaka pēc koordinētās universālās laika zonas (UTC); + Struktūru raksturo shēma: YYYY-MM-DD, kur Y simboli ir aizvietojami ar gadu, M ar mēnesi un D ar dienu. ], ) <IIDP01> #parameter-table( "Laika simbolu virkne", "IIDP02", "Datums un laiks, kas ir reprezentēts ar simbolu virkni noteiktā formātā un laika zonā (sistēmas ietvaros tiek izmantota viena laika zona).", [ + Jāatbilst standarta ISO 8601 datumu un laika formātam; + Gadam jābūt 4 cipariem; + Mēnesim un gadam jāsatur 2 ciparus, ar sākuma nullēm, ja nepieciešams; + Gadu, mēnesi un dienu jāatdala ar svītru (-); + Stundai un minūtei un sekundei jābūt 2 cipariem, ar sākuma nullēm, ja attiecināms; + Laiks un datums jānosaka pēc koordinētās universālās laika zonas (UTC); + Struktūru raksturo shēma: YYYY-MM-DDThh:mm:ss, kur Y simboli ir aizvietojami ar gadu, M ar mēnesi un D ar dienu, kā arī h simboli ir aizvietojami ar stundām, m ar minūtēm un s ar sekundēm. ], ) <IIDP02> #parameter-table( "Skaitlisks stāvokļa kods", "IIDP03", "Skaitlis, kas reprezentē noteiktu stāvokli funkcijas darbībai vai datubāzes tabulai.", [ + Vesels pozitīvs skaitlis. ], ) <IIDP03> #parameter-table( "Vārds un uzvārds", "IIDP04", "Reģistrēta lietotāja vārds un uzvārds.", [ + Simbolu virkne garumā līdz 255 simboliem; + Atļautie simbola: unikoda lielie burti (_Lu_), mazie burti (_Ll_), virsraksta burti (_Lt_) modifikatoru burti (_Lm_), citi burti (_Lo_), atstarpe, domuzīme. ], ) <IIDP04> #pagebreak(weak: true) #parameter-table( "E-pasts", "IIDP05", "Reģistrēta lietotāja e-pasts.", [ + Simbolu virkne garumā līdz 255 simboliem; + Jāatbilst standarta RFC 2822 interneta ziņu formātam. ], ) <IIDP05> #parameter-table( "Parole", "IIDP06", "Reģistrēta lietotāja parole.", [ + Simbolu virkne garumā no 8 līdz 127 simboliem; + Var saturēt burtciparu simbolus, skaitļus, atstarpi, speciālos simbolus: izsaukuma zīmi ($!$), dubultpēdiņas ($\"$), skaitļa zīmi ($\#$),dolāra zīmi ($\$$), procenta zīmi ($%$), ampersandu ($\&$), pēdiņas ($'$), iekavas ($($)), figūriekavas ({}), zvaigznīti ($*$), plusu ($+$), komatu ($,$), mīnusu ($-$), punktu ($.$), slīpsvītru ($\/$), kolu ($:$), semikolu ($;$), salīdzinājuma zīmes ($<$ $>$), vienādības zīmi ($=$), jautājuma zīmi ($?$), "et" zīmi ($@$), pasvītru ($\_$), vertikālo joslu ($|$), tildi ($~$); + Minimālās drošības prasības: satur vismaz vienu lielo un mazo burtu, vienu ciparu. ], ) <IIDP06> #parameter-table( "Segvārds", "IIDP07", "Reģistrēta lietotāja vārds, kas tiek izmantots saskarnes personalizācijai.", [ + Simbolu virkne garumā no 6 līdz 255 simboliem; + Atļautie simboli: lielie burti (_Lu_), mazie burti (_Ll_, virsraksta burti (_Lt_,) modifikatoru burti (_Lm_), citi burti (_Lo_), atstarpe, domuzīme, apakšsvītra. ], ) <IIDP07> #parameter-table( "Attēls", "IIDP08", "Sistēmā lietotu attēlu datne.", [ + Attēla datne; + Paplašinājums ir viens no: JPEG, JPG, GIF, PNG, WEBP; + Izmērs nepārsniedz 1MB. ], ) <IIDP08> #parameter-table( "Apraksts", "IIDP09", "Informācija par spēles priekšmetu, lietotāju u. tml.", [ + Simbolu virkne garumā līdz 512 simboliem; + Atļautie simboli: Unikoda lielie burti (_Lu_), mazie burti (_Ll_), virsraksta burti (_Lt_), modifikatoru burti (_Lm_), citi burti (_Lo_), speciālie simboli. ], ) <IIDP09> #parameter-table( "Tabulas identifikators", "IIDP10", "Datubāzē izmantots skaitlisks tabulas identifikators.", [ + Vesels pozitīvs skaitlis ], ) <IIDP10> #parameter-table( "Kārtošanas kods", "IIDP11", [Skaitlisks kods, kas atbilst kādam atribūtam, kurš ir kārtojams: 0 -- nekārtot, 1 -- kārtot augoši, 2 -- kārtot dilstoši.], [ + Vesels pozitīvs skaitlis ], ) <IIDP11> #parameter-table( "Datubāzes atribūta nosaukums", "IIDP12", "Datubāzes atribūta nosaukums", [ + Simbolu virkne garumā līdz 127 simboliem; + Atļautie simboli: unikoda mazie burti (_Ll_), pasvītra. ], ) <IIDP12> #parameter-table( "Datubāzes pieprasījums", "IIDP13", "Datubāzes pieprasījums.", [ + Pieprasījums PostgreSQL formātā iekodēts simbolu virknes struktūrā; + Pieprasījumā jābūt iespējai rediģēt pastāvošos un pievienot papildus nosacījumus. ], ) <IIDP13> #parameter-table( "Meklēšanas uzvedne", "IIDP14", "Uzvedne datubāzes ierakstu meklēšanai", [ + Simbolu virkne garumā līdz 255 simboliem; + Atļautie simboli: Unikoda lielie burti (_Lu_), mazie burti (_Ll_), virsraksta burti (_Lt_), modifikatoru burti (_Lm_), citi burti (_Lo_), atstarpe, domuzīme, cipari. ], ) <IIDP14> #parameter-table( "Cena", "IIDP15", "Maksas abonementa cena", [ + Decimāls skaitlis līdz 16 cipariem un 2 cipariem aiz komata. ], ) <IIDP15> #parameter-table( "Sarakstes teksts", "IIDP16", "Lietotāja sūtītās sarakstes teksts istabas tērzētavā.", [ + Simbolu virkne līdz 2047 simboliem; + Atļautie simboli: Unikoda lielie burti (_Lu_), mazie burti (_Ll_), virsraksta burti (_Lt_) modifikatoru burti (_Lm_), citi burti (_Lo_), speciālie simboli. ], ) <IIDP16> #parameter-table( "Marķieris", "IIDP17", "Sistēmas izmantots marķieris lietotāju identifikācijai.", [ + Atbilst RFC 7519 standartam. ], ) <IIDP17> #parameter-table( "Filtra kods", "IIDP18", [Skaitlisks kods, kam atbilst filtra veids: 0 -- Būla mainīgā filtrs, 1 -- tabulas identifikatora filtrs.], [ + Vesels pozitīvs skaitlis. ], ) <IIDP18> #parameter-table( "Filtru vārdnīcu saraksts", "IIDP19", "Saraksts ar vārdnīcām, kas satur informāciju par pārskatā pielietojamiem filtriem.", [ + Saraksts, kas sastāv no vārdnīcām; + Vārdnīcu atslēgas -- datu bāzes atribūta nosaukums (atbilst #link(<IIDP12>)[IIDP12]); + Vārdnīcu vērtības -- filtra vērtība -- vesels skaitlis -- un filtra veids -- atbilst #link(<IIDP18>)[IIDP18]). ], ) <IIDP19> #parameter-table( "Kārtošanas vārdnīcu saraksts", "IIDP20", "Saraksts ar vārdnīcām, kas satur informāciju par pārskatā pielietojamo kārtošanu.", [ + Saraksts, kas sastāv no vārdnīcām; + Vārdnīcu atslēgas -- datu bāzes atribūta nosaukums (atbilst #link(<IIDP12>)[IIDP12]); + Vārdnīcu vērtības -- kārtošanas kods (atbilst #link(<IIDP11>)[IIDP11]); ], ) <IIDP20> #parameter-table( "Spēles entitātes nosaukums", "IIDP21", "Spēles istabas, uzstādījuma vai lomas nosaukums.", [ + Simbolu virkne ar garumu no 0 līdz 50 simboliem. + Atļautie simboli: Unikoda lielie burti (_Lu_), mazie burti (_Ll_), virsraksta burti (_Lt_), modifikatoru burti (_Lm_), citi burti (_Lo_), atstarpe, domuzīme, cipari. ], ) <IIDP21> #parameter-table( "Maksājumu apstrādātāja identifikators", "IIDP22", "Maksājumu apstrādātāja izveidotais un izmantotais unikālais identifikators.", [ + Simbolu virkne ar garumu 50. + Atļautie simboli: Unikoda lielie burti (_Lu_), mazie burti (_Ll_), atstarpe, cipari, pasvītra. ], ) <IIDP22> === Kopīgās procedūras #indent-par([ Apakšnodaļa ietver funkcijās izmantojamās procedūras, kas tiek izmantotas vairākās funkcijās, kas ietver nosaukumu, aprakstu, ievadi, apstrādi un izvadi. Procedūras ir aprakstītas atsevišķās tabulās (skat. #link(<KPR01>)[KPR01], #link(<KPR02>)[KPR02], #link(<KPR03>)[KPR03], #link(<KPR04>)[KPR04], #link(<KPR05>)[KPR05], #link(<KPR06>)[KPR06], #link(<KPR07>)[KPR07], #link(<KPR08>)[KPR08], #link(<KPR09>)[KPR09], #link(<KPR10>)[KPR10], #link(<KPR11>)[KPR11], #link(<KPR12>)[KPR12]). ]) #procedure-table( "Pārskata lappuses iegūšana", "KPR01", "Aprēķina pārskata lappuses ierakstu nobīdi pēc kura atgriež lappuses ierakstus.", [ Obligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1; + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]\; + Rezultātu skaits -- vesels nenegatīvs skaitlis. Neobligātie parametri: + Ierakstu skaits lappusē -- vesels pozitīvs skaitlis. ], [ + Aprēķina lappušu skaitu ar formulu: $L = ceil(Q / Q_l)$, $Q$ -- rezultātu skaits, $Q_l$ -- ierakstu skaits vienā lappusē; + Ja lappuses numurs pārsniedz kopējo lappušu skaitu, tad turpmāk lappuses numurs ir 1; + Aprēķina ierakstu nobīdi ar formulu: $O = (N - 1) dot Q_l$, kur $O$ -- nobīde; $N$ -- lappuses numurs, $Q_l$ -- ierakstu skaits vienā lappusē; + Pievieno aprēķinātu nobīdi datubāzes pieprasījumam. ], [ + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]\; + Lappuses numurs -- vesels pozitīvs skaitlis; + Kopējs lappušu skaits -- vesels pozitīvs skaitlis. ], ) <KPR01> #procedure-table( "Konkrētā istabas, spēlētāja, lietotāja atbilstības pārbaude", "KPR02", "Pārbauda vai datubāzē eksistē un savstarpēji saistīti lietotāja, spēlētāja un istabas ieraksti, i.e, pārbauda vai spēlētājs atrodas istabā un lietotājs ir šis spēlētājs.", [ Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Meklē istabas ierakstu pēc spēles istabas identifikatora; + Ja neatrod atgriež "nepatiess". + Meklē spēlētāju ierakstu pēc spēlētāja un spēles istabas identifikatora; + Ja neatrod, atgriež "nepatiess". + Meklē lietotāju ierakstu pēc spēlētāja un spēles istabas identifikatora; + Ja neatrod, atgriež "nepatiess". + Pārbauda, vai lietotāja un spēlētāja ieraksta attiecīgie identifikatori sakrīt; + Ja nesakrīt, atgriež "nepatiess". + Atgriež "patiess". ], [ + Atbilstības karodziņš -- vai dotie identifikatori ir savā starpā saistīti. ], ) <KPR02> #procedure-table( [ Piederības pārbaude "Mafija" lomu grupai ], "KPR03", [ Pārbauda, vai konkrētais spēlētājs pieder "Mafija" lomu grupai. ], [ Obligātie parametri: + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Meklē spēlētāja lomu pēc spēlētāja identifikatora; + Ja lomas "Mafija" karodziņš parāda to, ka spēlētāja loma nepieder "Mafija" lomu grupai, tad atgriež "nepatiess" (vērtība 0), pretēji -- atgriež "patiess". ], [ + Mafijas piederības karodziņš -- vai spēlētājs pieder mafijai. ], ) <KPR03> #procedure-table( "Pieprasījuma filtru pievienošana", "KPR04", "Apstrādā datubāzes pieprasījumu, pievienojot atbilstošus filtra nosacījumus.", [ Obligātie parametri: + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]\; + Filtra atribūta nosaukums -- datubāzes identifikators. Neobligātie parametri: + Identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Pārbauda, vai katrs atribūts no filtra atribūtu saraksta ar tādu nosaukumu eksistē; + Ja kāds no tiem neeksistē, beidz apstrādi. + Katram filtra atribūtam pievieno filtru datubāzes pieprasījumu; + Ja identifikators ir iesniegts, pievieno filtrēšanu pēc šī identifikatora; + Ja nav, filtrē pēc karodziņa "patiess". ], [ + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]. ], ) <KPR04> #procedure-table( "Meklēšanas nosacījuma pievienošana", "KPR05", "Apstrādā datubāzes pieprasījumu, pievienojot atbilstošus meklēšanas nosacījumus.", [ Obligātie parametri: + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]\; + Meklēšanas atribūtu nosaukumu saraksts, kas sastāv no simbolu virknēm, kas atbilst #link(<IIDP12>)[IIDP12]\; + Meklēšanas uzvedne -- simbolu virkne, atbilst #link(<IIDP14>)[IIDP14], noklusētā vērtība -- "". ], [ + Pārbauda, vai katrs atribūts no meklēšanas atribūtu saraksta ar tādu nosaukumu eksistē; + Ja neeksistē, beidz apstrādi. + Pievieno meklēšanas nosacījumu pieprasījumu ar meklēšanas saraksta atribūtiem. ], [ + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]. ], ) <KPR05> #procedure-table( "Kārtošanas nosacījuma pievienošana", "KPR06", "Apstrādā datubāzes pieprasījumu, pievienojot atbilstošus meklēšanas nosacījumus.", [ Obligātie parametri: + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]\; + Kārtošanas atribūta nosaukums, kas atbilst #link(<IIDP12>)[IIDP12]\; + Kārtošanas kods, kas atbilst #link(<IIDP11>)[IIDP11]. ], [ + Pārbauda, vai atribūts ar tādu nosaukumu eksistē; + Ja neeksistē, beidz apstrādi. + Pievieno kārtošanu attiecīgajam atribūtam attiecīgi kārtošanas kodam. ], [ + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]. ], ) <KPR06> #procedure-table( "Pārskata pieprasījuma sagatavošana", "KPR07", "Sagatavo pārskatu datubāzes pieprasījumu pievienojot neobligātu lappuses nobīdi, filtrēšanu un kārtošanu", [ Obligātie parametri: + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]. Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1; + Meklēšanas uzvedne -- simbolu virkne, atbilst #link(<IIDP14>)[IIDP14], noklusētā vērtība -- "". + Kārtošanas vārdnīcu saraksts - atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. ], [ + Ja filtru vārdnīcu saraksts nav tukšs, katram saraksta elementam pievieno kārtošanu pieprasījumam ar attiecīgiem atribūtu nosaukumiem, filtra veidiem un vērtībām, izmantojot #link(<KPR04>)[KPR04]\; + Ja meklēšanas uzvedne ir iesniegta un nav tukša simbolu virkne, tad pieprasījumam pievieno meklēšanas nosacījumu meklēšanai pēc pilna vārda, segvārda un biogrāfijas, izmantojot #link(<KPR05>)[KPR05]\; + Ja kārtošanas vārdnīcu saraksts nav tukšs, katram saraksta elementam pievieno kārtošanu pieprasījumam ar attiecīgiem atribūtu nosaukumiem, kārtošanas kodiem, izmantojot #link(<KPR06>)[KPR06]\; + Ja lappuses numurs netika iesniegts, uzskata, ka lappuses numurs ir 1; + Pieprasa ierakstu saskaitīšanu, izmantojot sagatavoto pieprasījumu. + Ja rezultātu skaits ir lielāks par 0, iegūst lappuses ierakstu nobīdi, lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR01>)[KPR01] ar attiecīgo rezultātu skaitu, lappuses numuru, noklusēto ierakstu skaitu lappusē; + Ja rezultātu skaits ir 0, kopējo lappušu skaitu un lappuses numuru uzskata par 0. ], [ + Datubāzes pieprasījums, kas atbilst #link(<IIDP13>)[IIDP13]\; + Lappuses numurs -- vesels pozitīvs skaitlis; + Kopējs lappušu skaits -- vesels pozitīvs skaitlis. ], ) <KPR07> #procedure-table( "Lietotāja maksas abonementa aktīvuma pārbaude", "KPR08", "Pārbauda, vai lietotājam ir aktīvs maksas abonements.", [ Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\. ], [ + Iegūst lietotāja klienta identifikatoru no datubāzes. + Ja identifikators atbilst nulles vērtībai, izvada "nepatiess". + Pieprasa abonementu sarakstu no maksājumu apstrādātāja. + Ja pieprasījums neizdevās, izvada "nepatiess". + meklē pēdējo abonementu pēc izveidošanas laika. + Ja atbildē nav abonementu, izvada "nepatiess". + Ja pēdējais abonements ir aktīvs, izvada "patiess". ], [ + Aktīva abonementa karodziņš -- vai dotam lietotājam ir aktīvs abonements. ], ) <KPR08> #procedure-table( "Teksta sanitizācija", "KPR09", "Sanizizē ievadīto tekstu, i.e., noņem no teksta simbolus, kas varētu būt nozīmīgi simboli iezīmēšanas vai skriptu valodā.", [ Obligātie parametri: + Teksts -- simbolu virkne. ], [ + Ievades tekstā aizvieto sekojošos simbolus ar attiecīgiem izvairīšanās simboliem: + ampersandu (&); + mazāks par (<); + lielāks par (>); + dubultpēdiņu (""); + pēdiņu (''); + slīpsvītra (/). ], [ + Sanitizēts teksts -- simbolu virkne. ], ) <KPR09> #procedure-table( "E-pasta apstiprinājuma pieteikšana", "KPR10", "Uzstāda lietotāja apstiprinājuma datus lietotāja ierakstam.", [ Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\. ], [ + Meklē lietotāju, izmantojot lietotāja identifikatoru. + Ja neadrot, izvada kodu, kas atbilst neveiksmei. + Ģenerē e-pasta apstiprinājuma marķieri, kas atbilst #link(<IIDP17>)[IIDP17]. + Meklē lietotājus ar šo e-pasta apstiprinājuma marķieri; + Ja lietotājs tika atrasts, atkārto e-pasta apstiprinājuma ģenerēšanu un lietotāju meklēšanu līdz marķieris ir unikāls. + Aprēķina derīguma termiņu, pieskaitot tagadējam laikam noteiktu laiku. + Lietotāja ierakstam pievieno apstiprinājuma stāvokļa informāciju, marķieri un derīguma termiņu. + Ieraksta lietotāja e-pasta apstiprināšanas informāciju. + Ja tā netiek apstiprināta, izvada kodu, kas atbilst neveiksmei. + Izveido saiti apstiprinājumam, iekļaujot e-pasta apstiprinājuma marķieri; + Sagatavo e-pasta ziņas saturu no šablona, ievietojot tajā apstiprinājuma saiti; + Pieprasa e-pasta aizsūtīšanu. + Ja tā netiek apstiprināta, izvada kodu, kas atbilst neveiksmei. ], [ + E-pasta apstiprinājuma pieteikuma stāvoklis -- skaitlisks kods. ], ) <KPR10> #procedure-table( "Lietotāja maksas apstrādātāja identifikatora izveide", "KPR11", "Izveidot lietotājam maksas apstrādātāja unikālo identifikatoru.", [ Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ // https://stripe.com/docs/api/customers/create + Meklē lietotāju, izmantojot lietotāja identifikatoru. + Ja neatrod, izvada kodu, kas atbilst neveiksmei. + Sagatavo datus pieprasījumam, kas iekļauj lietotāja vārdu, uzvārdu un e-pastu. Pārveido to maksājuma apstrādātāja pieprasītā formātā, izmantojot maksājuma apstrādātāja API. + Ģenerē lietotāja maksājumu apstrādātāja identifikatoru, sazinoties ar maksājumu apstrādātāju. ], [ + Lietotāja maksājuma apstrādātāja identifikators -- atbilst #link(<IIDP22>)[IIDP22]. ], ) <KPR11> #procedure-table( "Attēla validācija", "KPR12", "Parbauda, vai attēls (attēla datne) atbilst noteiktām prasībām.", [ Obligātie parametri: + Attēls -- atbilst #link(<IIDP08>)[IIDP08]. ], [ // Image + Pārbauda, vai datne atbilst pieļaujamajiem datnes paplašinājumiem; + Ja neatbilst, atgriež kļūdu ar par nepieļaujamo datnes paplašinājumu: "Attēlam ir nepieļaujams paplašinājums: \[pieļaujamie paplašinājumi\]". + Pārbauda, vai datne nepārsniedz noteikto datnes lielumu; + Ja pārsniedz, atgriež kļūdu par pārsniegto datnes lielumu: "Attēls nedrīkst pārsniegt: \[noteiktais faila izmēra maksimums\]". + Ja iesniegtā attēla paplašinājums ir pieļaujams, bet nav PNG, tad datne tiek konvertēta šajā paplašinājumā. // Invokation //+ Ja tika iesniegts attēls, validē attēlu ar #link(<KPR12>)[KPR12]. // + Ja validācija ir neveiksmīga, parāda X. vai Z. paziņojumu, atkarībā no validācijas rezultāta. ], [ Validācijas rezultāts veiksmes vai kļūdas kods, balstoties uz kuru lietotājam tiks parādīta attiecīga kļūda. + Validācijas rezultāts -- kļūdas paziņojums -- noteiktās kļūdas skaitlisks kods vai 1, ja validācija ir veiksmīga. ], ) <KPR12> === Reģistrācijas un pieteikšanās modulis #indent-par([ /* TEMPLATE Apakšnodaļa ietver [MODULE_NAME] moduļa funkcijas. Moduļa funkcionalitāte ir izmantota [KAM?]. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. [FIGURE_REFERENCE]). */ Apakšnodaļa ietver reģistrācijas un pieteikšanās moduļa funkcijas. Moduļa funkcionalitāte ir izmantota lietotāju reģistrācijai, pieteikšanās un citām darbībām, kas saistās ar lietotāja autentifikāciju un to kontu. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-auth). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<AMF01>)[AMF01], #link(<AMF02>)[AMF02], #link(<AMF03>)[AMF03], #link(<AMF04>)[AMF04], #link(<AMF05>)[AMF05], #link(<AMF06>)[AMF06], #link(<AMF07>)[AMF07]). ]) #figure( caption: "Reģistrācijas un pieteikšanās moduļa 2. līmeņa DPD", image("img/dpd2/ReģistrācijasPieteikšanāsModulis.svg"), ) <dpd-2-auth> #pagebreak(weak: true) #function-table( "Lietotāja reģistrācija", "AMF01", [ Funkcijas mērķis ir reģistrēt lietotāja kontu sistēmā, autentifikācijas procesam un lietotāja darbību autorizācijai, un lietotāja informācijas uzglabāšanai. Apstrādes procesā ievades dati tiek pārbaudīti attiecīgi noteiktajām prasībām. Paroles šifrēšanas procesā tiek izmantota jaucējfunkcija ar papildus drošības metodiku -- "sāls pievienošanu" -- nejaušu simbolu virknes pievienošanu pirms šifrēšanas procesa uzsākšanas. ], [ // Why remove 'veidlapa' Ievades dati tiek saņemti no nereģistrētiem lietotājiem. Obligātie parametri: + Vārds, uzvārds -- atbilst #link(<IIDP04>)[IIDP04]\; + Segvārds -- atbilst #link(<IIDP07>)[IIDP07]\; + E-pasta adrese -- atbilst #link(<IIDP05>)[IIDP05]\; + Parole -- atbilst #link(<IIDP06>)[IIDP06]\; + Paroles apstiprinājums -- simbolu virkne, kas atbilst #link(<IIDP06>)[IIDP06]\; + Dzimšanas datums -- atbilst #link(<IIDP01>)[IIDP01]. Neobligātie parametri: + Profila attēls -- atbilst #link(<IIDP08>)[IIDP08], noklusētā vērtība -- noklusētā attēla adrese; + Biogrāfiskā informācija -- atbilst #link(<IIDP09>)[IIDP09], noklusētā vērtība -- "". ], [ // Validation + Pārbauda, vai visi obligātie lauki ir iesniegti; + Ja tie nav, iegūst sarakstu ar neaizpildītajiem laukiem, parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai parole un paroles apstiprinājums sakrīt; + Ja nesakrīt, tad parāda 2. paziņojumu. Beidz apstrādi. + Pārbauda, vai vārds un uzvārds, segvārds, e-pasta adrese, parole satur tikai pieļaujamos simbolus; + Ja nesatur, tad iegūst izmantotos neatļautos simbolus, tad parāda 3. paziņojumu ar attiecīgi laukiem un simboliem. Beidz apstrādi. + Pārbauda, vai vārds un uzvārds, segvārds, e-pasta adrese, biogrāfiskā informācija, parole nepārsniedz noteikto garumu; + Ja pārsniedz, tad iegūst pārsniegto garumu parametru sarakstu un parāda 4. paziņojumu ar attiecīgajiem laukiem un garumiem. Beidz apstrādi. + Pārbauda, vai parole atbilst noteiktiem drošības prasībām; + Ja tā tiem neatbilst, tad parāda 5. paziņojumu ar attiecīgām neizpildītajām prasībām. Beidz apstrādi. + Pārbauda, vai dzimšanas datums atbilst minimālam vecumam reģistrācijai; + Ja neatbilst, parāda 6. paziņojumu. Beidz apstrādi. // Trasnformation + Sanitizē biogrāfisko informāciju, izmantojot #link(<KPR09>)[KPR09]\. // Image + Ja tika iesniegts attēls, validē attēlu ar #link(<KPR12>)[KPR12] un uzstāda pievienošanas laiku uz tagadējo laiku. + Ja validācija ir neveiksmīga, parāda 8. paziņojumu ar attiecīgu validācijas kļūdu. + Meklē datubāzē lietotājus ar ievadīto e-pastu vai segvārdu; + Ja tāds(/-i) pastāv, tad parāda 9. paziņojumu ar attiecīgo aizņemto lauku. Beidz apstrādi. // Password + Ģenerē "sāls" simbolu virkni ar noteiktu algoritmu, to pievieno parolei. + Šifrē paroli ar jaucējfunkciju. + Uzstāda konta stāvokli uz vērtību, kas atbilst stāvoklim "aktīvs". // Construct user (+ fill the DB statuses etc.) + Uzstāda e-pasta apstiprinājuma karodziņa vērtību uz nepatiesu. + Uzstāda izveidošanas laiku uz tagadējo laiku. + Jauna lietotāja sagatavotie dati tiek ierakstīti datubāzē; + Ja ierakstīšana nenotiek, parādīt 10. paziņojumu. Beidz apstrādi. // USER is created // Add e-mail information to the DB and send an email + Piesaka konta apstiprinājumu, izmantojot #link(<KPR10>)[KRP10] procedūru. + Ja procedūra nav veiksmīga, parāda 12. paziņojumu. ], [ Izvades datu mērķis ir noteikt, vai lietotājs tiks pāradresēts un uz kuru lapu lietotājs tiks pāradresēts. Lietotāja tiek parādīts 11. paziņojums. + Reģistrācijas apstiprinājuma stāvoklis -- skaitlisks kods. ], [ + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)!; + Parole un paroles apstiprinājums nesakrīt!; + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]!; + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]!; + Parolei ir jāsatur: [neizpildīto paroles prasību saraksts]!; + Minimālais vecums reģistrācijai: [noteikts minimālais vecums reģistrācijai]\; + Reģistrācija ir veiksmīga! Pagaidām nav iespējams aizsūtīt apstiprinājumu, mēģiniet vēlreiz!; + Šo attēlu nedrīkst izmantot: \[validācijas kļūda\]!; + Lietotājs ar tādu [aizņemtā lauka nosaukums] jau eksistē!; + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz!; + Reģistrācija ir veiksmīga! Apstipriniet lietotāja kontu ar saiti, kas tiks izsūtīta tuvākā laikā, e-pastā. ], ) <AMF01> #function-table( "Apstiprinājuma ziņas atkārtotās izsūtīšanas pieteikums", "AMF02", "Funkcijas mērķis ir izsūtīt e-pasta apstiprinājumu atkārtoti lietotājam, kas jau veica reģistrāciju vai reģistrācijas laikā, vai pēc e-pasta izmaiņas lietotāja kontā.", [ Ievaddati tiek iegūti no darbības -- klikšķis uz attiecīgo apstiprinājuma pieteikuma pogu reģistrācijas laikā vai lietotāja konta rediģēšanas lapā. Ievades dati tiek iegūti no konteksta. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Meklē lietotāju datubāzē pēc ievades datu identifikatora parametra; + Ja tāds lietotājs neeksistē, parāda 1. paziņojumu. Beidz apstrādi. + Ja lietotāja e-pasts ir apstiprināts, parāda 4. paziņojumu. // Add e-mail information to the DB and send an email + Piesaka konta apstiprinājumu, izmantojot #link(<KPR10>)[KRP10] procedūru. + Ja procedūra nav veiksmīga, parāda 1. paziņojumu. ], [ Izvades datu mērķis ir lietotāja informēšana par apstiprinājuma ziņojuma izsūtīšanas stāvokli. Lietotāja saskarnē parādās 3. paziņojums ar instrukciju par e-pasta apstiprināšanu. + E-pasta apstiprinājuma ziņas izsūtīšanas stāvoklis -- skaitlisks kods. ], [ + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Apstiprinājuma ziņa ir izsūtīta! Apstipriniet lietotāja kontu ar saiti, kas tiks izsūtīta tuvākā laikā, e-pastā. + Apstiprinājuma ziņa tiks izsūtīta 1-10 minūšu laikā; + E-pasts jau ir apstiprināts. ], ) <AMF02> #function-table( "Paroles atjaunošanas pieteikums", "AMF03", "Funkcijas mērķis ir ļaut lietotājam atjaunot aizmirstu vai nedrošu paroli, nodrošinot drošu paroles maiņas procesu, kas ietver unikāla marķiera izveidi, tā nosūtīšanu lietotāja e-pastā un tā verifikāciju.", [ Ievaddati tiek iegūti no veidlapas. Obligātie parametri: + E-pasta adrese -- atbilst #link(<IIDP05>)[IIDP05]. ], [ + Pārbauda, vai e-pasta adrese eksistē datubāzē, meklējot lietotāju ar sakrītošu e-pasta adresi. + Ja tāds lietotājs jau eksistē, parāda 1. paziņojumu. Beidz apstrādi. + Ģenerē unikālu marķieri paroles atjaunošanai, pārbaudot unikalitāti, meklējot lietotāju ar sakrītošu un derīgu marķieri, kas atbilst #link(<IIDP17>)[IIDP17]. + Ja tāds lietotājs eksistē, atkārto ģenerāciju līdz iegūtais marķieris ir unikāls. + Ieraksta jaunu marķieri lietotāja, kas atjauno paroli, ierakstam, pievienojot tam noteikto derīguma laiku. + Izveido saiti paroles atjaunošanai, iekļaujot marķieri. + Pieprasa paroles atjaunošanas saites izsūtīšanu ar atbilstošo e-pasta saturu. + Ja izsūtīšana nav veiksmīga, parāda 5. paziņojumu. ], [ Izvades datu mērķis ir lietotāja informēšana par paroles atjaunošanas pieteikuma ziņas izsūtīšanas stāvokli. Lietotāja saskarnē parādās 4. paziņojums. + Paroles atjaunošanas pieteikuma stāvoklis -- skaitlisks kods. ], [ + E-pasta adrese jau ir reģistrēta!; + Saitei ir beidzies derīguma termiņš!; + Parolei ir jāsatur: [neizpildīto paroles prasību saraksts]!; + Apstiprinājuma ziņa ir izsūtīta! Apstipriniet lietotāja kontu ar saiti, kas tiks izsūtīta tuvākā laikā e-pastā. + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <AMF03> #function-table( "Paroles atjaunošana", "AMF04", "Funkcijas mērķis ir ļaut lietotājam atjaunot aizmirstu vai nedrošu paroli, nodrošinot drošu paroles maiņas procesu, kas ietver unikāla marķiera izveidi, tā nosūtīšanu lietotāja e-pastā un tā pārbaudi.", [ Ievaddati tiek iegūti no apstiprinājuma vietrādes parametriem ar kuru lietotājs piekļūst sistēmas funkcijai. Obligātie parametri: + Lietotāja paroles atjaunošanas marķieris -- atbilst #link(<IIDP17>)[IIDP17]\; + Lietotāja jaunā parole -- atbilst #link(<IIDP06>)[IIDP06]\; + Lietotāja jaunās parole apstiprinājums -- skaitlisks kods. ], [ + Ja lietotāja paroles identifikatora atjaunošanas marķieris nav iesniegts, parāda 1. paziņojumu. Beidz apstrādi; + Meklē lietotāja ierakstu datubāzē, meklējot to pēc atjaunošanas marķiera; + Ja lietotāja ieraksts netika atrasts, parāda 2. paziņojumu. Beidz apstrādi; + Pārbauda, vai saitē iekļautais marķieris ir derīgs un nav novecojis. Ja tas ir nederīgs vai novecojis, parāda 2. paziņojumu. Beidz apstrādi. + Pārbauda, vai parole un paroles apstiprinājums ir iesniegts; + Ja kāds no laukiem nav iesniegts parāda 4. paziņojumu ar attiecīgo lauku nosaukumiem. + Pārbauda, vai jaunā parole atbilst drošības prasībām; + Ja nē, parāda 5. paziņojumu ar neizpildīto prasību sarastu. Beidz apstrādi. + Ģenerē "sāls" simbolu virkni ar noteiktu algoritmu, to pievieno parolei. + Šifrē paroli ar jaucējfunkciju. + Ieraksta marķiera derīguma termiņu pamaina uz tagadējo laiku; + Atjaunoto lietotāja ierakstu ieraksta datubāzē. + Ja ierakstīšana neizdevās, parāda 3. paziņojumu. ], [ Izvades datu mērķis ir lietotāja informēšana par paroles atjaunošanas stāvokli. Lietotāja saskarnē parādās 6. paziņojums. + Paroles atjaunošanas stāvoklis -- skaitlisks kods. ], [ + Paroles atjaunošanas marķieris nav norādīts! + Paroles atjaunošanas marķieris nav derīgs! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + Parolei ir jāsatur: [neizpildīto paroles prasību saraksts]! + Paroles atjaunošana ir veiksmīga! ], ) <AMF04> #function-table( "Lietotāja atteikšanās", "AMF05", "Funkcijas mērķis ir pārtraukt lietotāja pārlūkprogrammas sasaisti ar noteiktu lietotāju kontu.", [ Ievades dati tiek saņemti no lietotāja -- klikšķis uz atteikšanās pogu. Obligātie parametri: + Lietotāja sesijas marķieris -- atbilst #link(<IIDP17>)[IIDP17]\. ], [ + No lietotāja pārlūkprogrammas tiek iegūts sesijas marķieris; + Izdzēš lietotāja sesijas ierakstu datubāzē. + Ja lietotāja sesijas ieraksta izdzēšana neizdevās. Parāda 1. paziņojumu. Beidz apstrādi. + Ja sesijas marķieris eksistē, tas tiek izdzēsts. Lietotājs tiek pāradresēts uz mājaslapas sākuma lapu. + Ja marķiera izdzēšana nav veiksmīga. Parāda 1. paziņojumu. Beidz apstrādi. ], "Izvades datu funkcijai nav. Lietotājs tiek pāradresēts mājaslapas sākuma lapā.", [ + Atteikšanās neizdevās! Mēģiniet pārlādēt lapu vai mēģiniet vēlāk! ], ) <AMF05> #function-table( "Lietotāja pieteikšanās", "AMF06", "Autentificēt lietotāju, lai sistēma to uztver kā lietotāju ar konkrēto sistēmas lomu un atļauj turpmākās sistēmas lomas darbības sistēmā.", [ Ievades dati tiek saņemti no pieteikšanās veidlapas. Obligātie parametri: + E-pasta adrese vai segvārds -- atbilst #link(<IIDP05>)[IIDP05]\; + Ja tā neatbilst, tad tai jāatbilst sekojošām prasībām: atbilst #link(<IIDP10>)[IIDP10]. + Parole -- simbolu virkne, atbilst #link(<IIDP06>)[IIDP06]. ], [ + Pārbauda vai visi obligātie lauki ir aizpildīti. + Ja kāds no laukiem nav aizpildīts, tad parāda 1. paziņojumu ar attiecīgiem laukiem. + Pārbauda, vai e-pasta adrese vai segvārds un parole satur tikai pieļaujamos simbolus; + Ja satur, tad iegūst izmantotos neatļautos simbolus, tad parāda 2. paziņojumu ar laukiem un simboliem. Beidz apstrādi. + Pārbauda, vai e-pasta adrese vai un parole nepārsniedz noteikto garumu; + Ja satur, tad iegūst pārsniegto garumu parametru sarakstu un parāda 3. paziņojumu ar laukiem un garumiem. Beidz apstrādi. + Iegūst lietotāja autentifikācijas datus no datubāzes, meklējot lietotājus pēc segvārdu vai e-pasta adreses; + Ja tāds lietotājs netika atrasts, parāda 4. paziņojumu. Beidz apstrādi. + Pievieno ievades datu parolei sāls simbolu virkni; + Pārbauda, vai lietotāja sniegtā paroles jaucējfunkcijas rezultāts sakrīt ar datubāzē glabātu vērtību; + Ja paroles jaucējfunkcijas rezultāts nesakrīt ar datubāzē glabāto vērtību nesakrīt, parāda 5. paziņojumu. Beidz apstrādi. + Ja sakrīt, ģenerē lietotāja sesijas marķieri, kas atbilst #link(<IIDP17>)[IIDP17] prasībām. Saglabā marķieri kā sīkdatni lietotāja pārlūkprogrammas datu krātuvē un saglabā lietotāja sesiju datubāzē ar noteiktu derīgumu termiņu. + Ja saglabāšana neizdodas, parāda 6. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir noteikt, vai lietotājs tiks pāradresēts un kurā lapā lietotājs tiks pāradresēts. Lietotāja saskarnē lietotājs tiek pāradresēts uz autentificēto lietotāju sākuma lapu. + Paroles atjaunošanas stāvoklis -- skaitlisks kods. ], [ + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)!; + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]!; + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]!; + Lietotājs ar šādu segvārdu vai e-pastu netika atrasts vai parole nav pareiza! + Lietotājvārds, e-pasts vai parole nav korekti! + Atteikšanās neizdevās! Mēģiniet pārlādēt lapu vai mēģiniet vēlāk! ], ) <AMF06> #function-table( "Lietotāja konta apstiprināšana", "AMF07", "Funkcijas mērķis ir apstiprināt lietotāja konta e-pasta adresi, i.e., apstiprināt to, ka lietotājam pieder norādītā e-pasta adrese.", [ Ievaddati tiek iegūti no apstiprinājuma vietrādes parametriem, ar kuras lietotājs piekļūst funkcijai. Obligātie parametri: + E-pasta apstiprinājuma marķieris -- atbilst #link(<IIDP17>)[IIDP17]. ], [ + Pārbauda, vai ievades datos ir e-pasta apstiprinājuma marķieris; + Ja tā nav, tad parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai e-pasta adreses apstiprinājuma marķieris atbilst sagaidāmam garumam; + Ja neatbilst, parāda 2. paziņojumu. Beidz apstrādi. + Meklē datubāzē lietotājus ar iesniegto marķieri; + Ja tāds lietotājs netiek atrasts, parāda 2. paziņojumu. Beidz apstrādi; + Ja datubāzē atrastā lietotāja e-pasta apstiprināšanas karodziņš apzīmē apstiprinātu e-pastu, parāda 3. paziņojumu. Beidz apstrādi. + Ierakstam pamaina e-pasta apstiprinājuma karodziņa stāvokli uz "patiess". + Atjaunoto lietotāja ierakstu ieraksta datubāzē. + Ja ierakstīšana neizdevās, parāda 5. paziņojumu. ], [ Izvades datu mērķis ir lietotāja informēšana par konta apstiprināšanas stāvokli. Lietotājam tiek parādīts 4. paziņojums. + E-pasta adreses apstiprinājuma stāvoklis -- skaitlisks kods. ], [ + Apstiprināšanas saite nav korekta: marķieris nav norādīts! Mēģiniet vēlreiz vai pieprasiet atkārtotu apstiprinājuma ziņas izsūtīšanu!; + Marķieris nav aktuāls vai nav korekts! Mēģiniet vēlreiz vai pieprasiet atkārtotu apstiprinājuma ziņas izsūtīšanu!; + E-pasts jau ir apstiprināts!; + E-pasts ir veiksmīgi apstiprināts! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <AMF07> === Lietotāju kontu modulis #indent-par([ Apakšnodaļa ietver lietotāju konta moduļa funkcijas. Moduļa funkcionalitāte ir izmantota lietotāju kontu pārskatam un darbībām ar lietotāju kontiem. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-user). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<LKMF01>)[LKMF01], #link(<LKMF02>)[LKMF02], #link(<LKMF03>)[LKMF03], #link(<LKMF04>)[LKMF04], #link(<LKMF05>)[LKMF05]). ]) #figure( caption: "Lietotāju kontu moduļa 2. līmeņa DPD", image("img/dpd2/LietotājuKontuModulis.svg"), ) <dpd-2-user> #pagebreak(weak: true) #function-table( "Lietotāju profilu pārskats", "LKMF01", "Funkcijas mērķis ir lietotājiem sniegt citu lietotāju profilu publisku informāciju. Funkcijas ietvaros var tikt veikta neobligāta meklēšana pēc noteiktiem lietotāja profilu atribūtiem.", [ Ievades datus iegūst no lietotāja neobligāti uzstādītiem filtriem, kārtošanas izvēles un lappuses numura un meklēšanas uzvednes. Parametri atbilst attiecīgām saitēm un ievades laukam lietotāja saskarnē un izvēlnēm pārskata lapās. Parametru vērtības tiek iegūtas no vietrādes parametriem. Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1; + Meklēšanas uzvedne -- simbolu virkne, atbilst #link(<IIDP14>)[IIDP14], noklusētā vērtība -- "". + Kārtošanas vārdnīcu saraksts - atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. ], [ + Sāk gatavot datubāzes pieprasījumu no lietotāju tabulas; + Sagatavo pārskata pieprasījumu un iegūst lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru, meklēšanas uzvedni, kārtošanas vārdnīcu sarakstu, filtru vārdnīcu sarakstu, šos parametrus iesniedzot, ja tie ir iesniegti funkcijā; + Ja lappušu skaits ir 0, tad parāda 1. paziņojumu. Beidz apstrādi. + Veic sagatavoto pieprasījumu, iegūstot lietotāja segvārdu, lietotāja konta izveidošanas laiku (lietotāja pievienošanās laiku), lietotāja attēla datnes adresi; + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Katram ierakstam no rezultāta, iegūst atrastais attēla datnes adresi no attēlu tabulas pēc attēla identifikatora. + Ja attēla datnes adrese neeksistē ierakstam, tad iegūst noklusētā attēla datnes adresi un samaina ieraksta datnes adresi izvades datos uz noklusētā datnes attēla adresi. ], [ Izvades datu mērķis ir parādīt rezultāta pārskatu lietotāja saskarnē. Lietotāja saskarnē tiek prezentēti dati no sagatavotā saraksta. + Pārskata ierakstu saraksts, kas sastāv no vārdnīcām: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Segvārds -- atbilst #link(<IIDP07>)[IIDP07]; + Lietotāja konta izveidošanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Lietotāja attēls -- atbilst #link(<IIDP08>)[IIDP08]\. + Kārtošanas vārdnīcu saraksts -- atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. + Kopējais lapu skaits -- vesels pozitīvs skaitlis; + Tekošā lappuse -- vesels pozitīvs skaitlis, kas ir mazāks vai vienāds par lapu skaitu; ], [ + Netika atrasts neviens lietotājs! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <LKMF01> #function-table( "Lietotāja konta detaļas", "LKMF02", "Funkcijas mērķis ir reģistrētiem lietotājiem saņemt informāciju par kontu -- gan publisko, gan privāto (atkarībā no lietotāja lomas un konta piederības). Administratoriem visa informācija ir iegūstama par jebkuru lietotāju.", [ Ievades datus iegūst no vietrāža parametriem, caur kuru tiek piekļūts funkcijai. Alternatīvi, dati (lietotāja identifikators) tiek iegūti no konteksta. Neobligātie parametri: + Apskatāmo konta datu lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10], noklusētā vērtība -- no konteksta lietotāja (kas piekļūst funkciju) iegūtais identifikators. ], [ + Sāk gatavot datubāzes pieprasījumu no lietotāju tabulas. + Sagatavo pieprasīto lauku sarakstu: + Vārds un uzvārds; + Segvārds; + Biogrāfijas informācija; + Dzimšanas datums; + Konta izveidošanas laiks; + Attēls (datnes adrese). + Autorizē administratora darbību. Ja darbība ir autorizēta, tad pie saraksta pievieno lietotāja konta stāvokli, vai lietotājs ir administrators. + Ja lietotājam pieder pieprasījuma konts vai administratora darbība tika autorizēta, sarakstam pievieno sekojošos atribūtus: + E-pasta adresi; + E-pasta apstiprinājuma stāvokli. + Veic sagatavoto pieprasījumu, pieprasot iepriekš sagatavoto lauku sarakstu, attēla datnes adreses; + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Ja lietotājs netika atrasts, parāda 3. paziņojumu. Beidz apstrādi. + Ja attēla datnes adrese neeksistē, tad iegūst noklusētā attēla datnes adresi. ], [ Izvades datu mērķis ir lietotāja konta datu parādīšana. Lietotāja saskarnē tiek prezentēti konta dati, kas atbilst lietotājam paredzamai datu kopai. Pamata vārdnīcas saturs: + Vārds un uzvārds -- atbilst #link(<IIDP04>)[IIDP04]\; + Segvārds -- atbilst #link(<IIDP07>)[IIDP07]\; + Biogrāfiskā informācija -- atbilst #link(<IIDP09>)[IIDP09]\; + Dzimšanas datums -- atbilst #link(<IIDP01>)[IIDP01]\; + Konta izveidošanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Lietotāja profila attēls -- atbilst #link(<IIDP08>)[IIDP08]. Papildus vārdnīcas dati, ja pieprasītājs lietotājs ir administrators vai konts pieder lietotājam: + E-pasta adrese -- atbilst #link(<IIDP05>)[IIDP05]\; + E-pasta apstiprinājuma stāvoklis -- karodziņš. Papildus vārdnīcas dati, ja pieprasītājs lietotājs ir administrators: + Konta stāvoklis -- atbilst #link(<IIDP10>)[IIDP10]\; + Vai lietotājs ir administrators -- karodziņš. ], [ + Darbība nav autorizēta! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Tāds lietotājs nav atrasts! Mēģiniet vēlreiz! ], ) <LKMF02> #function-table( "Lietotāja konta bloķēšana", "LKMF03", "Funkcijas mērķis ir bloķēt lietotāja kontu, ja notikuši drošības pārkāpumi vai cita veida noteikumu pārkāpumi.", [ Ievades datus iegūst no veicamās darbības -- klikšķis uz lietotāja bloķēšanas pogu. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Meklē lietotāja ierakstu datubāzē, meklējot to pēc identifikatora. + Ja lietotāja ieraksts netika atrasts, parāda 2. paziņojumu. Beidz apstrādi. + Autorizē administratora darbību. + Ja darbība netika autorizēta, parāda 2 paziņojumu. Beidz apstrādi. + Maina lietotāja konta stāvokli uz stāvokli, kas atbilst bloķētam lietotājam. + Ja ierakstīšana nav veiksmīga, parāda 4. paziņojumu. ], [ Izvades mērķis ir atjaunot lietotāja stāvokli lietotāja saskarnē. Ja ierakstīšana ir veiksmīga, parāda 3. paziņojumu. + Konta bloķēšanas stāvoklis -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Lietotājs ar norādītu identifikatoru neeksistē! + Darbība nav autorizēta! + Konts veiksmīgi bloķēts! + Sistēmas iekšējā kļūda, konts nav bloķēts! ], ) <LKMF03> #pagebreak(weak: true) #function-table( "Lietotāja konta rediģēšana", "LKMF04", "Funkcijas mērķis ir rediģēt lietotāju konta datus, kas ir rediģējami. Administratoriem rediģēt dažus laukus, kuru rediģēšana nav pieejama lietotājiem, kas nav administratori.", [ Ievades dati tiek saņemti no reģistrēto un autentificēto lietotāju pieejamās veidlapas. Obligātie parametri: + Pilns vārds -- atbilst #link(<IIDP04>)[IIDP04]\; + Segvārds -- atbilst #link(<IIDP07>)[IIDP07]\; + E-pasta adrese -- atbilst #link(<IIDP05>)[IIDP05]\; + Biogrāfiskā informācija -- atbilst #link(<IIDP09>)[IIDP09]\; + Dzimšanas datums -- atbilst #link(<IIDP01>)[IIDP01]\;. Administratoram specifiskie obligātie parametri: + Konta izveidošanas laiks -- datums, atbilst #link(<IIDP02>)[IIDP02]\. + E-pasta apstiprinājums -- karodziņš; + Konta stāvokļa kods -- atbilst #link(<IIDP10>)[IIDP10]\. // + Vai ir administrators -- karodziņš. Neobligātie parametri: + Konta datu lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10], noklusētā vērtība -- no konteksta lietotāja (kas piekļūst funkciju) iegūtais identifikators. + Vecā parole -- atbilst #link(<IIDP06>)[IIDP06], noklusētā vērtība -- "". + Jaunā parole -- atbilst #link(<IIDP06>)[IIDP06], noklusētā vērtība -- "". + Jaunās paroles apstiprinājums -- atbilst #link(<IIDP06>)[IIDP06], noklusētā vērtība -- "". ], [ // Autorizācija + Ja lietotājs nav administrators un lietotāja identifikators nesakrīt ar pieprasītāja lietotāja identifikatoru, parādīt 1. paziņojumu. Beidz apstrādi. + Veido izmainīto datu sarakstu pēc turpmāk izmainītiem laukiem. // Datu validācija + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja tie nav, iegūst sarakstu ar neaizpildītajiem laukiem, parāda 2. paziņojumu. Beidz apstrādi. + Pārbauda, vai pilns vārds, segvārds, e-pasta adrese, biogrāfiskā informācija satur tikai pieļaujamos simbolus. + Ja satur, tad iegūst izmantotos neatļautos simbolus, tad parāda 4. paziņojumu ar attiecīgi laukiem un simboliem. Beidz apstrādi. + Pārbauda, vai dzimšanas datumam ir korekts formāts. + Ja nav korekts, parāda 17. paziņojumu. Beidz apstrādi. + Pārbauda, vai dzimšanas datums atbilst noteiktam minimālam lietotāja vecumam. + Ja neatbilst, parāda 7. paziņojumu. + Pārbauda, vai pilns vārds, segvārds, e-pasta adrese, biogrāfiskā informācija, parole nepārsniedz noteikto garumu. + Ja satur, tad iegūst pārsniegto garumu parametru sarakstu un parāda 5. paziņojumu ar attiecīgi laukiem un garumiem. Beidz apstrādi. + Pārbauda, vai parole un paroles apstiprinājums sakrīt. + Ja nesakrīt, tad parāda 3. paziņojumu. Beidz apstrādi. + Pievieno atjaunoto atribūtu vērtības sarakstam. // Sanitizācija / Transformācija // Biogrāfiskā informācija + Sanitizē biogrāfisko informāciju, izmantojot #link(<KPR09>)[KPR09]\. // Paroles apstrāde + Ja jaunā parole tika iesniegta, pārbauda, vai parole atbilst noteiktām drošības prasībām. + Ja tā tiem neatbilst, tad parāda 6. paziņojumu ar attiecīgām neizpildītajām prasībām. Beidz apstrādi. + Ģenerē "sāls" simbolu virkni ar noteiktu algoritmu, to pievieno parolei. + Šifrē paroli ar jaucējfunkciju. // Image + Ja tika iesniegts attēls, validē attēlu ar #link(<KPR12>)[KPR12] un uzstāda pievienošanas laiku uz tagadējo laiku. + Ja validācija ir neveiksmīga, parāda 8. paziņojumu ar attiecīgu validācijas kļūdu. + Citādi saglabā vecā attēla datni, ja tāda ir. // Uniqueness check + Ja tika iesniegts atšķirīgs segvārds, mēģina meklēt datubāzē lietotājus ar ievadīto segvārdu. + Ja tāds (/-i) pastāv, tad parāda 10. paziņojumu ar attiecīgo aizņemto lauku. Beidz apstrādi. Beidz apstrādi. + Ja tika iesniegts atšķirīgs e-pasts, mēģina meklēt datubāzē lietotājus ar ievadīto e-pastu. + Ja tāds (/-i) pastāv, tad parāda 10. paziņojumu ar attiecīgo aizņemto lauku. Beidz apstrādi. Beidz apstrādi. // Admin specific + Autorizē administratora darbību. Ja darbība ir autorizēta, veic sekojošās darbības. + Pārbauda, vai izveidošanas laikam ir korekts formāts. + Ja nav, parāda 12. paziņojumu. Beidz apstrādi. + Pārbauda vai konta stāvokļa kods atbilst definētiem stāvokļa kodiem. + Ja neatbilst, parāda 12. paziņojumu. Beidz apstrādi. + Pārbauda, vai datums ir pagātnē vai tagad. + Ja datums ir nākotnē, parāda 17. paziņojumu. Beidz apstrādi. + Pārbauda vai e-pasta apstiprinājuma karodziņš ir korekts. + Ja neatbilst, parāda 8. paziņojumu. Beidz apstrādi. + Pievieno atjaunoto atribūtu vērtības sarakstam. /*+ Ja administratora karodziņš ir "patiess". + No datubāzes noskaidro, vai lietotājs ir administrators. + Ja lietotājs nav administrators, piešķir lietotājam administratora tiesības. + Ja administratora karodziņš ir "nepatiess". + No datubāzes noskaidro, vai lietotājs ir administrators. + Ja lietotājs ir administrators, noņem lietotājam administratora tiesības.*/ // Save + Lietotāja konta sagatavotie dati -- lauki, kas ir rediģēto lauku sarakstā, tiek ierakstīti datubāzē. + Ja ierakstīšana nenotiek, parādīt 11. paziņojumu. Beidz apstrādi. + Izdzēš veco attēlu ar saglabāto vecā attēla datni. ], [ Izvades datu mērķis ir noteikt rediģēšanas konta stāvokli. + Konta rediģēšanas apstiprinājuma stāvoklis -- skaitlisks kods. ], [ + Darbība nav autorizēta! + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + Parole un paroles apstiprinājums nesakrīt! + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]! + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]! + Parolei ir jāsatur: [neizpildīto paroles prasību saraksts]! + Minimālais vecums reģistrācijai: [noteikts minimālais vecums reģistrācijai]. + E-pasta apstiprinājuma karodziņš nav korekts! + Šo attēlu nedrīkst izmantot: [validācijas kļūda\]! + Lietotājs ar tādu [aizņemtā lauka nosaukums] jau eksistē! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Nekorekts laiks! Laika formāts: [nepieciešamais laika formāts]. + Izveidošanas laiks nedrīkst būt nākotnē! + Lietotāja stāvokļa kods nav korekts! + Konta rediģēšana ir veiksmīga! + Tāds konta stāvoklis neeksistē! + Nekorekts datums! Datuma formāts: [nepieciešamais datuma formāts]. ], ) <LKMF04> #function-table( "Lietotāja konta dzēšana", "LKMF05", "Funkcijas mērķis ir dzēst lietotāju kontus, lai to konta informācija būtu neatgriezeniski izdzēsta.", [ Ievades dati tiek saņemti no reģistrēto lietotāju pieejamās darbības. Alternatīvi, dati tiek iegūti no konteksta (autentificēta lietotāja identifikators). Neobligātie parametri: + Konta datu lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. Noklusētā vērtība -- no konkrēta lietotāja (kas piekļūst funkciju) iegūtais identifikators. ], [ + Autorizē administratora darbību. + Ja darbība ir autorizēta, parādīt 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai lietotājs ar tādu identifikatoru eksistē. + Ja neeksistē, parāda 2. paziņojumu. Beidz apstrādi. + Saglabā veco lietotāja attēla datnes adresi, ja tāda ir. + Lietotāja ierakstu izdzēš. + Ja izdzēšana nav veiksmīga, parāda 3. paziņojumu. Beidz apstrādi. + Ja izdzēšana ir veiksmīga, parāda 4. paziņojumu. Beidz apstrādi. + Izdzēš lietotāja konta attēla datni. ], [ Izvades datu mērķis ir noteikt, vai lietotājs tiks pāradresēts. + Lietotāja konta dzēšanas stāvoklis -- skaitlisks kods. ], [ + Darbība nav autorizēta! + Tāds lietotājs nav atrasts! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Lietotāja deaktivizēšana ir veiksmīga! ], ) <LKMF05> === Maksas abonementu modulis #indent-par([ Apakšnodaļa ietver maksas abonementa moduļa funkcijas. Moduļa funkcionalitāte ir izmantota darbībām ar lietotāju maksas abonementiem. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-premium-user). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<MAMF01>)[MAMF01], #link(<MAMF02>)[MAMF02], #link(<MAMF03>)[MAMF03], #link(<MAMF04>)[MAMF04]). ]) #figure( caption: "Maksas abonementu moduļa 2. līmeņa DPD", image("img/dpd2/MaksasAbonementaModulis.svg"), ) <dpd-2-premium-user> #function-table( "Abonementa pieteikums", "MAMF01", "Funkcijas mērķis ir izveidot maksājuma pieteikumu maksas abonementam, izveidojot maksas abonementa ierakstu datubāzē maksājuma apstiprināšanas gadījumā.", [ Ievades dati tiek iegūti no lietotāja maksājuma pieteikuma veidlapas, apmaksājot abonementu. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Maksājuma plāna identifikators -- atbilst #link(<IIDP22>)[IIDP22]. // + Kartes īpašnieka vārds. Simbolu virkne, kas var saturēt lielo un mazos burtus (a-z, A-Z) no ASCII simbolu kopas, atstarpes, defīzes, apostrofus. Maksimālais simbolu skaits ir 100 simboli. // + Kartes numurs. Simbolu virkne, kas sastāv no cipariem un ir 16 simbolus gara. // + Kartes derīguma termiņš -- datuma simbola virkne, kas sastāv no gada un mēneša. Pieļaujamas tikai termiņi, kas nav pirms tekošā mēneša. // + Kartes drošības kods -- simbolu virkne no 3 cipariem. ], [ /*+ Pārbauda, vai datubāzē neeksistē aktīvs abonements, kas ir saistīts ar lietotāja identifikatora, kas veido maksājuma pieteikumu. + Ja eksistē, parāda 9. paziņojumu.*/ /*+ Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja tie nav, iegūst sarakstu ar neaizpildītajiem laukiem, parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai visi obligātie lauki satur tikai pieļaujamos simbolus. + Ja satur, tad iegūst izmantotos neatļautos simbolus, tad parāda 2. paziņojumu ar attiecīgajiem laukiem un izmantotiem aizliegtiem simboliem. Beidz apstrādi. + Pārbauda, vai veidlapas visi obligātie lauki nepārsniedz noteikto garumu. + Ja satur, tad iegūst pārsniegto garumu parametru sarakstu un parāda 3. paziņojumu ar attiecīgi laukiem un garumiem. Beidz apstrādi. + Pārbauda, vai kartes numura pirmie 4 cipari atbilst vienai no bankām, ko apstrādā maksājumu apstrādātājs. + Ja neatbilst, parāda 4. paziņojumu. Beidz apstrādi. + Pārbauda, vai kartes derīguma termiņš ir pēc tekošā mēneša. + Ja tas ir pirms, parāda 5. paziņojumu. Beidz apstrādi. + Datubāzē meklē aktuālo šodienas cenu par abonementu, izmantojot tagadējo laiku. + Ja cena netika atrasta, iegūst noklusējuma cenu.*/ // https://stripe.com/docs/api/subscriptions/create + Pārbauda, vai pieprasītais abonementa plāns eksistē, pieprasot abonementa plāna informāciju no maksas apstrādātāja. + Ja neeksistē, parāda 5. paziņojumu. Beidz apstrādi. + Pārbauda, vai datubāzē lietotājam eksistē ārējā maksas pakalpojuma izveidots identifikators. + Ja eksistē, pārbauda vai identifikators ir saistīts ar aktīvu lietotāju maksas apstrādātāja sistēmā, pieprasot klienta informāciju. + Pārbauda vai klientam nav abonēts šis plāns. Ja ir abonēts, parāda 4. paziņojumu. Beidz apstrādi. + Ja neeksistē vai eksistē un nav saistīts ar aktīvu lietotāju maksas apstrādātāja sistēmā, tad identifikatoru izveido, izmantojot #link(<KPR11>)[KPR11]. Saglabā izveidoto identifikatoru datubāzē. + Ja izveidošana neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Sagatavo datus pieprasījumam, kas iekļauj lietotāja ārējā maksas pakalpojuma identifikatoru un maksājuma plāna identifikatoru. Pārveido tos maksājuma apstrādātāja pieprasītā formātā, izmantojot maksājumu apstrādātāja API. + Pieprasa abonementa izveidošanu, sazinoties ar maksājumu apstrādātāju. + Ja atbildē izveidošana netiek apstiprināta, parāda 2. paziņojumu. Beidz apstrādi. /*+ Ja abonementa izveidošana ir apstiprināta, izveido ierakstu ar abonementa datiem datubāzē: + Sākuma laiks -- tagadējais laiks, atbilst #link(<IIDP02>)[IIDP02]\; + Maksājumu periods -- noteikts maksājuma periods; + Maksas abonementa stāvoklis -- stāvoklis, kas atbilst stāvoklim "atbilst". + Maksājuma apstrādātāja atbildē saņemto klienta identifikators.*/ ], [ Izvades datu mērķis ir informēt, vai lietotājs tiks pāradresēts. Lietotāja saskarnē parāda 3. paziņojumu. + Abonementa izveidošanas apstiprinājuma stāvoklis -- skaitlisks kods. ], [ /*+ Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]! + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]! + Kartes numurs nav korekts! + Kartes derīguma termiņš ir beidzies!*/ + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Abonementa apmaksa nav veiksmīga! Mēģiniet vēlreiz vai sazinieties ar tehniskās palīdzības speciālistu! + Abonēšana ir veiksmīga! + Jums jau ir aktīvs abonements ar Jūsu izvēlēto plānu! + Jūsu pieteiktais abonementa plāns neeksistē! ], ) <MAMF01> #function-table( "Abonementu pārskats", "MAMF02", "Funkcijas mērķis ir lietotājiem rādīt informāciju par maskas esošiem un bijušiem maksas abonementiem. Šī pārskata dati tiek kārtoti un filtrēti neobligātā kārtā.", [ Ievades dati tiek saņemti no vietrāža parametriem. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. Neobligātie parametri: + Lappuses numurs -- pozitīvs skaitlis. + Kārtošanas vārdnīcu saraksts -- atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. ], [ // https://stripe.com/docs/api/subscriptions/list // + Sāk gatavot datubāzes pieprasījumu no maksas abonementu tabulas. + Autorizē administratora darbību. + Ja darbība nav autorizēta un pieprasītais lietotāja identifikators nesakrīt ar lietotāja identifikatoru, parāda 4. paziņojumu. Beidz apstrādi. + Iegūst maksas apstrādātāja klienta identifikatoru no datubāzes. + Ja tā vērtība atbilst nulles vērtībai, parāda 4. paziņojumu. Beidz apstrādi. + Sagatavo pārskata pieprasījumu, lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru, kārtošanas vārdnīcu sarakstu, filtru vārdnīcu sarakstu, šos parametrus iesniedzot, ja tie ir iesniegti funkcijā. Pārveido tos maksājuma apstrādātāja pieprasītā formātā, izmantojot maksājumu apstrādātāja API. + Ja identifikators neeksistē, tad izveido to, #link(<KPR11>)[KPR11], un mēģina vēlreiz. + Ja lappušu skaits ir 0, tad parāda 1. paziņojumu. Beidz apstrādi. + Pieprasa lietotāja abonementu sarakstu, sazinoties ar maksājumu apstrādātāju. Sarakstu pārveido vārdnīcu sarakstu ar sekojošām atslēgām: + Maksājuma plāna identifikators\; + Abonementa stāvoklis\; + Sākuma laiks\; + Beigu laiks\; + Atteikuma laiks\; + Pēdējais norēķina laiks\; + Nākamā norēķina laiks\; + Cena\; + Valūta\; + Apraksts\. + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir parādīt pārskatu, ņemot vērā filtrus un kārtošanu, ja tas tika pieprasīts. Kā arī izvadīt datus abonementa atcelšanai. Lietotāja saskarnē tiek prezentēti dati no sagatavotā saraksta. + Vārdnīcu saraksts: + Maksājuma plāna identifikators -- atbilst #link(<IIDP22>)[IIDP22]\; + Abonementa stāvoklis -- atbilst #link(<IIDP10>)[IIDP10]\; + Sākuma laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Beigu laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Atteikuma laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Pēdējais norēķina laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Nākamā norēķina laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Cena -- atbilst #link(<IIDP15>)[IIDP15]\; + Valūta -- uzskatījums, atbilst ISO 4217 valūtas kodam; + Apraksts -- simbolu virkne. /* + Papildus vārdnīcu dati administratoriem: + Maksājumu apstrādātāja klienta identifikators -- vesels pozitīvs skaitlis;*/ + Lappušu skaits -- pozitīvs skaitlis. + Tekošā lappuse -- pozitīvs skaitlis, kas ir mazāks vai vienāds par lapu skaitu. ], [ + Netika atrasts neviens abonements! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Darbība nav autorizēta! + Jums nav aktīva abonementa! ], ) <MAMF02> #function-table( "Abonementa atcelšana", "MAMF03", "Funkcijas mērķis ir atcelt lietotājam, kam ir aktīvs maksas abonementi. Maksājuma apstrādātāja abonements tiks atcelts, kā rezultātā no lietotāja vairs nebūs iekasēti maksājumi. Abonementa stāvoklis sistēmā būs apzīmēts kā atcelts.", [ Ievades dati tiek iegūti no darbības abonementu pārskatā. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. //+ Maksājuma apstrādātāja klienta identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Maksājuma plāna identifikators -- atbilst #link(<IIDP22>)[IIDP22]. Neobligātie parametri: + Atcelšanas iemesls -- simbolu virkne. ], [ /*+ Datubāzē meklē maksas abonementa ierakstu, pēc maksas apstrādātāja klienta identifikatora. + Ja tāds neeksistē, parāda 1. paziņojumu. Beidz apstrādi. + Ja lietotāja idendifikators neatbilst ieraksta identifikatoram, parāda 2. paziņojumu. Beidz apstrādi. */ + Iegūst maksas apstrādātāja klienta identifikatoru no datubāzes. + Ja tā vērtība atbilst nulles vērtībai, parāda 3. paziņojumu. Beidz apstrādi. + Sagatavo datus pieprasījumam, kas iekļauj lietotāja ārējā maksas pakalpojuma identifikatoru, maksājuma plāna identifikatoru un atcelšanas iemeslu. Pārveido tos maksājuma apstrādātāja pieprasītā formātā, izmantojot maksājumu apstrādātāja API. + Pieprasa abonementa atcelšanu, sazinoties ar maksājumu apstrādātāju. + Ja atbildē atcelšana netiek apstiprināta, parāda 1. paziņojumu. Beidz apstrādi. + Datubāzē meklē lietotāja ierakstu. + Izdzēš klienta identifikatoru no lietotāja ieraksta. /*+ Izmantojot maksājumu apstrādātāja klienta identifikatoru, pieprasa abonementa atcelšanu, izmantojot maksājuma apstrādātāja API. + Ja maksājuma apstrādāja atbilde norāda, ka atcelšana neizdevusies. Parāda 1. paziņojumu. Beidz apstrādi. + Ja maksājuma apstrādātāja atbilde norāda, ka abonementa atcelšana ir veiksmīga, attiecīgā datubāzes ieraksta stāvokli nomaina uz stāvokli, kas apzīmē atceltu abonementu. */ ], [ Izvades datu mērķis ir noteikt, vai abonementa atcelšana bija veiksmīga. Lietotāja saskarnē parāda 2. paziņojumu. + Abonementa atcelšanas stāvoklis -- skaitlisks kods. ], [ + Neizdevās atcelt abonementu! Mēģiniet vēlreiz vai sazinieties ar tehniskās palīdzības speciālistu! + Abonements ir veiksmīgi atcelts! + Jums nav aktīva abonementa! ], ) <MAMF03> #function-table( "Abonementu plānu pārskats", "MAMF04", "Funkcijas mērķis ir lietotājiem sniegt pārskatu par pieejamajiem abonementu plāniem.", [ Neobligātie parametri: + Vai ir aktīva -- Bula mainīgais, noklusētā vērtība -- "patiess"; + Izveides datums -- atbilst #link(<IIDP02>)[IIDP02], noklusētā vērtība -- 0; + Ierobežojums -- vesels pozitīvs skaitlis, no 1 līdz 100, noklusētā vērtība -- 10; ], [ // https://stripe.com/docs/api/plans/list + Sagatavo datus pieprasījumam. Pārveido tos maksājuma apstrādātāja pieprasītā formātā, izmantojot maksājumu apstrādātāja API. + Pieprasa abonementa plānu sarakstu, sazinoties ar maksājumu apstrādātāju. + Ja pieprasījums neizdodas, parāda 1. paziņojumu. Beidz apstrādi. + Iegūto plānu sarakstu pārveido vārdnīcu sarakstā ar sekojošām atslēgām: + Maksājuma plāna identifikators\; + Izveidošanas laiks\; + Abonementa stāvoklis\; + Cena\; + Valūta\; + Maksāšanas periods\; + Diena; + Nedēļa; + Mēnesis; + Gads. + Plāna segvārds\; + Apraksts\. ], [ Izvades datu mērķis ir parādīt abonementu plānu pārskatu. Lietotāja saskarnē tiek prezentēti dati no sagatavotā saraksta. + Vārdnīcu saraksts: + Maksājuma plāna identifikators -- atbilst #link(<IIDP22>)[IIDP22]\; + Izveidošanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Abonementa stāvoklis -- atbilst #link(<IIDP10>)[IIDP10]\; + Cena -- atbilst #link(<IIDP15>)[IIDP15]\; + Valūta -- uzskatījums, atbilst ISO 4217 valūtas kodam; + Maksāšanas periods -- uzskaitījums ar vienu no vērtībām: + Diena; + Nedēļa; + Mēnesis; + Gads. + Plāna segvārds -- simbolu virkne; // Īss plāna apraksts, kas ir paslēpts no lietotājiem; + Apraksts -- simbolu virkne. ], [ + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <MAMF04> === Tērzēšanas modulis #indent-par([ Apakšnodaļa ietver tērzēšanas moduļa funkcijas. Moduļa funkcionalitāte ir izmantota iekšspēles tērzēšanas nodrošināšanai. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-chat). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]). ]) #figure( caption: "Tēržēšanas moduļa 2. līmeņa DPD", image("img/dpd2/TerzēšanasModulis.svg"), ) <dpd-2-chat> #function-table( "Jaunas sarakstes izveidošana", "TMF01", "Funkcijas mērķis ir dot iespēju rakstiskā veidā sazināties spēlētājam ar citiem klātesošajiem spēlētājiem vienas spēles istabas ietvaros.", [ Ievade tiek saņemta no teksta ievades lauciņa spēlētāju tērzētavā. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Sarakstes teksts -- atbilst #link(<IIDP16>)[IIDP16]\; + Vai sarakste ir mafijas tērzētavā -- karodziņš. Neobligātie parametri: + Atbildes saņēmēja sarakstes identifikators - atbilst atbilst #link(<IIDP10>)[IIDP10]\; ], [ + Pārbauda, vai sarakstes teksts nav tukša simbolu virkne. + Ja ir tukša, parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai sarakstes teksts nepārsniedz maksimālo simbolu skaitu. + Ja pārsniedz, parāda 2. paziņojumu ar attiecīgo maksimālo pieļauto garumu. Beidz apstrādi. + Izmantojot #link(<KPR02>)[KPR02] procedūru pārbauda, vai spēlētājs, lietotājs un spēles istaba eksistē un ir savstarpēji saistīti. + Ja nav, parāda 3. paziņojumu. Beidz apstrādi. + Ja spēlētais ir neaktīvs, izslēgts, vai kāds no atribūtiem, kas apzīmē spēles beigas spēlētājiem ir "patiess", parāda 6. paziņojumu. Beidz apstrādi. + Izmantojot #link(<KPR03>)[KPR03] procedūru pārbauda, vai spēlētājs pieder mafijai un ja "vai sarakste ir mafijas tērzētavā" karodziņš ir "patiess", uzstāda attiecīgo ieraksta karodziņa vērtību. + Ja spēlētājs nepieder mafijai, parāda 4. paziņojumi. Beidz apstrādi. + Ja atbildes sarakstes identifikators ir iesniegts, meklē atbildes sarakstes ar atbildes sarakstu identifikatoru. + Ja sarakste ierakstu neatrod, parāda 5. paziņojumu. Beidz apstrādi. + Sagatavoto sarakstes ierakstu. + Ieraksta saraksti datubāzē. + Ja ierakstīšana neizdevās, parāda 3. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir norādīt izveidotās ziņas stāvokli. + Ziņas sūtīšanas stāvoklis -- skaitlisks kods. ], [ + Sarakste ir tukša! + Ziņas garums pārsniedz maksimāli atļauto garumu: [maksimāli atļautais garums]! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Jūsu loma neatļauj piedalīties mafijas tērzēšanā! + Atbildes sarakste netika atrasta! + Jūs nevarat izveidot jaunu saraksti! ], ) <TMF01> #function-table( "Sarakstes izdzēšana", "TMF02", "Funkcija atbild par netīšām uzrakstītām ziņām, kuras spēlētāji vēlas izdzēst, pēc ziņu nosūtīšanas vai atbild par nekorektu vai neobjektīvi pareizu ziņu izdzēšanu.", [ Ievade tiek iegūta no ziņas izdzēšanas darbības tērzētavā. + Sarakstes identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Meklē datubāzē sarakstes ierakstu, izmantojot sarakstes identifikatoru. + Ja tas netika atrasts, parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai lietotāja identifikators sakrīt ar sarakstes ieraksta lietotāja identifikatoru. + Ja tas nesakrīt, autentificē administratora darbību. + Ja darbības netika autentificēta, parāda 2. paziņojumu. Beidz apstrādi. + No datubāzes izdzēš sarakstes ierakstu. + Ja dzēšana ir veiksmīga, parāda 3. paziņojumu. Beidz apstrādi. + Ja nav veiksmīga, parāda 4. paziņojumu. Beidz apstrādi. ], "Izdzēstā ziņa no sarakstes uzskaites ir pazudusi. Parādās par izdzēsto saraksti.", [ + Dzēšamā sarakste netika atrasta! + Ir iespējams dzēst tikai savas sarakstes! + Ziņa ir veiksmīgi izdzēsta! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <TMF02> #function-table( "Sarakstu pārskats", "TMF03", "Funkcija nepieciešama, lai uzskaitītu un parādītu visas uzrakstītās sarakstes visās tērzētavās (mafijas un parastās). Tā kā pieprasīto sarakstu skaits var atšķirties saskarnēs -- tas tiek noteikts ar papildus parametru.", [ Ievade tiek saņemta no spēles istabas konteksta. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Pieprasīto ierakstu skaits -- vesels pozitīvs skaitlis; + Lappuses numurs -- vesels pozitīvs skaitlis; + Vai ir mafijas tērzētava -- karodziņš. Neobligātie parametri: + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10], noklusētā vērtība -- 0\; ], [ + Izmantojot #link(<KPR02>)[KPR02] procedūru pārbauda, vai spēlētājs, lietotājs un spēles istaba eksistē un ir savstarpēji saistīti. + Ja nav saistīti, veic administratora darbības autorizāciju. + Ja darbība nav autorizēta, parāda 2. paziņojumu. Beidz apstrādi. + Ja darbība ir autorizēta, izlaiž apstrādes 2. soli. + Meklē spēlētāja ierakstu un ar to saistītu spēles lomas un spēles istabas ierakstu pēc attiecīgajiem identifikatoriem. + Ja kāds no ierakstiem netika atrasts, parāda 2. paziņojumu. + Ja spēlētāja stāvoklis neatbilst aktīvam, no spēles neizslēgtam spēlētājam, parāda 3. paziņojumu. Beidz apstrādi. + Ja mafijas tērzēšanas karodziņš ir "patiess" un spēlētāja loma nepieder mafijai, parāda 2. paziņojumu. + Sāk gatavot datubāzes pieprasījumu no sarakstu tabulas. + Pievieno pieprasījumam atlasīšanu attiecīgi mafijas tērzēšanas parametra-karodziņa vērtībai. + Pieprasa rezultātu saskaitīšanu. + Ja pieprasījums neizdodas, parāda 1. paziņojumu. + Pievieno pieprasījumam nepieciešamo nobīdi lappusei, izmantojot #link(<KPR01>)[KPR01] procedūru ar pieprasīto ierakstu skaitu. + Veic sagatavoto pieprasījumu, iegūstot īsziņas tekstus, sarakstes adresāta identifikatorus. + Ja pieprasījums neizdodas, parāda 1. paziņojumu. Beidz apstrādi. + Meklē saraksti attēlošanas nepieciešamo spēlētāju segvārdus, meklējot attiecīgos lietotāju un spēlētāju ierakstus datubāzē, izmantojot attiecīgos spēlētāju un lietotāju identifikatorus. + Ja, kāds no nepieciešamiem ierakstiem netika atrasts, aizvieto neatrasto informāciju ar noklusētām vērtībām. + Katrai sarakstei ar atbildi meklē attiecīgo sarakstu un ar to saistītā lietotāja ierakstu, uz ko tā atbild datubāzē pēc attiecīgās sarakstes identifikatora, iegūstot sarakstes tekstus, atbildes lietotāju segvārdus un izmainīšanas karodziņus. + Ja kāda sarakste netika atrasta, sarakstes tekstu un identifikatoru aizvieto ar noklusētām vērtībām. ], [ Izvades datu mērķis ir parādīt sarakstes noteiktā intervālā. Lietotāja saskarnē tiek prezentēti dati no sagatavotā saraksta. Sarakstes parādās noteiktās grupas (mafijas un parastā) tērzētavā. + Saraksts ar vārdnīcām: + Sūtītāja segvārds -- atbilst #link(<IIDP10>)[IIDP10]\; + Sūtītāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Sarakstes teksts -- atbilst #link(<IIDP16>)[IIDP16]\; + Sarakstes sūtīšanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Atbildes sarakstes teksts -- atbilst #link(<IIDP16>)[IIDP16] vai ""\; + Atbildes sarakstes autora segvārds -- atbilst #link(<IIDP07>)[IIDP07] vai ""\; + Atbildes sarakstes autora identifikators -- atbilst #link(<IIDP10>)[IIDP10] vai 0\; + Izmainīšanas karodziņš. ], [ + Neizdevās piekļūt tērzētavai! + Jums nav iespējams rakstīt šajā tērzētavā vai tērzētavas sadaļā! + Jūs nevarat piekļūt tērzētavai! ], ) <TMF03> #function-table( "Savu sarakstu rediģēšana", "TMF04", [ Funkcija nodrošina iespēju spēlētājam rediģēt jau izsūtītu ziņu tērzētavā. Spēlētājs nospiež pogu "Rediģēt" blakus vēlamajai ziņai. Parādās rakstīšanai pieejams ievades lauks ar esošās ziņas saturu. Spēlētājs rediģē tekstu un nosūta izmaiņas. ], [ Ievades dati tiek iegūti no lietotāja darbības -- klikšķis uz pogas "Rediģēt" un ievadītās rediģējamās sarakstes ievades laukā ievadītā satura. Obligātie parametri: + Rediģējamās ziņas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Sarakstes rediģētais teksts -- atbilst #link(<IIDP16>)[IIDP16]\; + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Izmantojot #link(<KPR02>)[KPR02] procedūru pārbauda, vai spēlētājs, lietotājs un spēles istaba eksistē un ir savstarpēji saistīti. + Ja nav, parāda 2. paziņojumu. Beidz apstrādi. + Pārbauda, vai sarakste pieder lietotājam, meklējot sarakstu datubāzē pēc lietotāja identifikatora. + Ja sarakste nav atrasta, parāda 1. paziņojumu. Beidz apstrādi. + Ja nepieder, parāda 3. paziņojumu. Beidz apstrādi. + Pārbauda, vai spēlētājs piedalās spēlē. + Ja nepiedalās, parāda 6. paziņojumu. Beidz apstrādi. + Pārbauda, vai sarakste rediģētais teksts nav tukša simbolu virkne. + Ja ir tukša, parāda 4. paziņojumu. Beidz apstrādi. + Pārbauda, vai sarakstes teksts nepārsniedz maksimālo simbolu skaitu. + Ja pārsniedz, parāda 5. paziņojumu ar attiecīgo maksimālo pieļauto garumu. Beidz apstrādi. + Ieraksta atjaunoto sarakstes ierakstu datubāzē, samainot "izmainīts" karodziņa vērtību uz "patiess". + Ja ierakstīšana neizdevās, parāda 2. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir atjaunot rediģētās ziņas saturu lietotāja saskarnē. + Rediģētā ziņas saturs -- sarakstes teksts -- atbilst #link(<IIDP16>)[IIDP16]. ], [ + Sarakste nav atrasta! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Drīkst rediģēt tikai savas sarakstes! + Ziņa ir tukša! + Ziņas garums pārsniedz maksimāli atļauto garumu: [maksimāli atļautais garums]! + Jūs nevarat rediģēt sarakstes nepiedaloties spēlē! ], ) <TMF04> === Spēles istabu modulis #indent-par([ Apakšnodaļa ietver spēles istabas moduļa funkcijas. Moduļa funkcionalitāte ir izmantota darbībām saistībā ar spēles virtuālo istabu. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-game-room). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<SIMF01>)[SIMF01], #link(<SIMF02>)[SIMF02], #link(<SIMF03>)[SIMF03], #link(<SIMF04>)[SIMF04], #link(<SIMF05>)[SIMF05], #link(<SIMF06>)[SIMF06], #link(<SIMF07>)[SIMF07], #link(<SIMF08>)[SIMF08], #link(<SIMF09>)[SIMF09]). ]) #figure( caption: "Spēles istabu moduļa 2. līmeņa DPD", image("img/dpd2/SpēlesIstabasModulis.svg"), ) <dpd-2-game-room> #function-table( "Spēles istabu pārskats", "SIMF01", "Funkcijas mērķis ir ļaut reģistrētiem lietotājiem apskatīt pieejamās spēles istabas.", [ Ievades datus iegūst no lietotāja neobligāti uzstādītiem filtriem lietotāja saskarnē, kārtošanas izvēles un lappuses numura un meklēšanas uzvednes. Parametri atbilst attiecīgām saitēm un ievades laukam lietotāja saskarnē un izvēlnēm pārskata lapās. Parametru vērtības tiek iegūtas no vietrādes parametriem. Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1. + Meklēšanas uzvedne -- simbolu virkne, atbilst #link(<IIDP14>)[IIDP14], noklusētā vērtība -- "". + Kārtošanas vārdnīcu saraksts -- atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. ], [ + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 3. paziņojumu. Beidz apstrādi. + Sāk gatavot datubāzes pieprasījumu no spēles istabu tabulas. + Sagatavo pārskata pieprasījumu un iegūst lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru, meklēšanas uzvedni, kārtošanas vārdnīcu sarakstu, filtru vārdnīcu sarakstu, šos parametrus iesniedzot, ja tie ir iesniegti funkcijā. Izmantojot procedūru, pievieno filtru, lai pieprasījumā nebūtu spēles, kas ir atceltas vai jau beidzās. + Ja lappušu skaits ir 0, parāda 1. paziņojumu. Beidz apstrādi. + Veic sagatavoto pieprasījumu, iegūstot istabas nosaukumu, atbilstošo lietotāju skaits, stāvokli, izveidošanas laiku, piekļuves kodu. + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Katram ierakstam no rezultāta, sekojošas manipulācijas: + Saskaita spēlētājus, kas gaida spēles sākšanu -- spēlētāji, kuru stāvoklis atbilst "aktīvs" vai "atslēdzies". + Meklē spēles uzstādījumu pēc identifikatora. + Ja tas netika atrasts, izņem spēles istabas vārdnīcu no saraksta. + Citādi pievieno spēles uzstādījuma nosaukumu vārdnīcai. + Ja spēles sākšanas laiks nav tukšs vai stāvoklis neatbilst neuzsāktās spēles stāvokļa kodam, izņem ārā vārdnīcu no rezultāta saraksta; + Aprēķina maksimālo spēlētāju skaitu, meklējot datubāzē ar spēles uzstādījumu saistītās spēles lomas un saskaitot kopā to skaitus. + Ja kāda no lomām netiek atrasta, izņem istabas vārdnīcu no saraksta. + Pievieno "privāts" karodziņu; + Ja piekļuves kods nav tukšs, "privāts" vērtība ir "patiess", citādi "nepatiess". + Izņem piekļuves kodu un spēles sākšanas laiku no vārdnīcas. ], [ Izvades mērķis ir saskarnē tiek izvietots pārskatāms saraksts ar visām lietotājam pieejamajām spēles istabām un to raksturojošajiem parametriem, pielietojot filtrus un kārtošanu, ja tas tika pieprasīts. Lietotāja saskarnē tiek prezentēti dati no sagatavotā saraksta. + Saraksts ar vārdnīcām: + Nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Spēles uzstādījuma nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Izveidošanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Atbilstošo lietotāju skaits -- vesels skaitlis; + Maksimālais lietotāju skaits -- vesels skaitlis; + Privātuma karodziņš. ], [ + Nav pieejamu istabu! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <SIMF01> #function-table( "Pieslēgšanās spēles istabai", "SIMF02", "Funkcijas mērķis ir ļaut reģistrētiem lietotājiem pievienoties izvēlētajai spēles istabai.", [ Ievades datus iegūst no veidlapas lietotāja saskarnē. Istabas piekļuves kods tiek iegūts no attiecīgā ieraksta sarakstā un no paroles dialoga lodziņa. Obligātie parametri: + Istabas identifikators -- atbilst #link(<IIDP06>)[IIDP07]\; + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\. Neobligātie parametri: + Istabas piekļuves kods -- atbilst #link(<IIDP06>)[IIDP06], noklusētā vērtība -- ""\. // ASK: Should we encrypt this password (code*). Decision: This field will not be encrypted ], [ + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 6. paziņojumu. Beidz apstrādi. + Tiek meklēta spēles istaba spēles istabu tabulā spēles istabas identifikatora. + Ja istaba netika atrasta, parāda 4. paziņojumu. Beidz apstrādi. + Meklē spēlētāju, kas ir saistīts ar lietotāja identifikatoru. + Ja to atrod, pamaina spēlētāja stāvokli nomaina uz stāvokli, kas atbilst aktīvam spēlētājam. Ieraksta izmaiņas datubāzē. Beidz apstrādi. + Ja ierakstīšana neizdevās, parāda 3. paziņojumu. Beidz apstrādi. + Ja istabas lietotāju skaits ir sasniedzis maksimālo lietotāju skaitu, tad tiek parādīts 1. paziņojums. Beidz apstrādi. + Ja istaba ir atrasta un ja tās piekļuves kritēriji ietver paroli, i.e., istaba ietver paroli un istabas stāvoklis atbilst spēlei, kas vēl nav sākusies, tad tiek parādīts dialogs piekļuves kods iesniegšanai. + Ja istabas piekļuves kodu nesaņēma (kods netika iesniegts), parāda 5. paziņojumu. Beidz apstrādi. + Ja piekļuves kods nesakrīt ar istabas kodu, tad parāda 2. paziņojumu. Beidz apstrādi. + Ja istabas stāvoklis neatbilst, tad parāda 8. paziņojumu. Beidz apstrādi. + Izveido spēlētāja ierakstu, kas ir saistīts ar spēles istabu un lietotāja identifikatoru ar stāvokli, kas atbilst aktīvam spēlētājam. // ACTIVE PLAYER attribute? -> YES. Perhaps we can remove the active player, since it will be hard to keep track of it and just handle it with programmatic checks on whether the player exists or not (same user ID) ], [ Izvades mērķis ir noteikt, vai lietotājs tiks pāradresēts istabas lapā - spēles vestibilā. Lietotājam parāda 7.paziņojumu. + Pieslēgšanās stāvoklis -- skaitlisks kods. ], [ + Istabā nav brīvu vietu! + Nepareizs piekļuves kods! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Istaba netika atrasta! + Istaba ir aizsargāta ar paroli! Lūdzu, ievadiet paroli! + Nepieciešamie pieslēgšanās dati netika iesniegti. + Pievienošanās istabai ir veiksmīga! + Spēles istaba nav aktīva. Nav iespējas tai pievienoties! ], ) <SIMF02> #function-table( "Atslēgšanās no spēles istabas", "SIMF03", "Funkcijas mērķis ir ļaut reģistrētiem lietotājiem atslēgties no pašreizējās spēles istabas.", [ Dati tiek iegūti no konteksta (autentificēta lietotāja identifikators) un vietrādes parametriem (spēles istabas identifikators) Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Spēles istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 6. paziņojumu. Beidz apstrādi. + Izmantojot #link(<KPR02>)[KPR02] procedūru pārbauda, vai spēlētājs, lietotājs un spēles istaba eksistē un ir savstarpēji saistīti. + Ja nav, parāda 5. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles istabas ierakstu, izmantojot spēles istabas identifikatoru. + Ja nav, parāda 3. paziņojumu. Beidz apstrādi. + Meklē spēlētāja ierakstu, izmantojot spēlētāja identifikatoru. + Ja to neatrod, parāda 2. paziņojumu. Beidz apstrādi. + Spēlētāja stāvoklis tiek nomainīts uz "atslēdzies". Izmaiņas ieraksta datubāzē. + Ja ierakstīšana neizdodas, parāda 3. paziņojumu. Beidz apstrādi. + Ja atslēgšanās ir veiksmīga, parāda 4. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir noteikt vai lietotājs tiks pāradresēts. Atslēdzoties, lietotājs tiek pāradresēts pieejamo istabu saraksta lapā. + Atslēgšanās stāvoklis -- skaitlisks kods. ], [ + Spēles istaba nav atrasta! Mēģiniet vēlreiz. + Spēlētājs nav atrasts! Mēģiniet vēlreiz. + Sistēmas iekšēja kļūda. Mēģiniet vēlreiz! + Atslēgšanās no istabas ir veiksmīga! + Jūs neesat šajā istabā! + Nepieciešamie pieslēgšanās dati netika iesniegti. ], ) <SIMF03> #pagebreak(weak: true) #function-table( "Jaunas spēles istabas izveide", "SIMF04", "Maksas lietotājiem ļauj izveidot jaunu spēles istabu ar noteiktiem iestatījumiem", [ Dati tiek iegūti no veidlapas lietotāja saskarnē. Lietotāja identifikators tiek iegūts no konteksta. Obligātie parametri: + Spēles istabas nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Spēles uzstādījuma identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; Neobligātie parametri: + Istabas piekļuves kods -- atbilst #link(<IIDP06>)[IIDP06], noklusētā vērtība -- ""\. ], [ + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 4. paziņojumu. Beidz apstrādi. + Izmantojot #link(<KPR08>)[KPR08] procedūru, pārbauda, vai lietotājam ir aktīvs abonements. + Ja nav, tad parāda 2. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles uzstādījumu. + Ja tas netika atrasts, parāda 3. paziņojumu. Beidz apstrādi. + Sāk gatavot spēles istabas ierakstu. + Ja piekļuves kods tika iesniegts, pārbauda, vai tas atbilst prasībām. + Ja neatbilst, parāda 5. paziņojumu. Beidz apstrādi. + Citādi pievieno piekļuves kodu spēles istabas ierakstam. + Ja istabas nosaukums neatbilst prasībām. Parāda 6. paziņojumu. Beidz apstrādi. + Stāvokli uzstāda uz stāvokli, kas atbilst nesāktai spēlei. + Uzstāda izveidošanas laiku uz tagadējo laiku. + Pārējos laukus uzstāda uz noklusētām vērtībām. + Ieraksta istabas ierakstu datubāzē. + Ja ierakstīšana neizdevās, parāda 3. paziņojumu. + Izveido spēlētāja ierakstu, kas ir saistīta ar spēles istabu un lietotāju ar stāvokli, kas atbilst aktīva spēlētāja stāvoklim. Pārējos laukus uzstāda uz noklusētām vērtībām. + Ieraksta spēlētāja ierakstu datubāzē. + Ja ierakstīšana neizdevās, parāda 3. paziņojumu. ], [ Izvades mērķis ir noteikt vai lietotājs tiks pāradresēts. Lietotājs tiek automātiski pievienots, tas ir pāradresēts, jaunizveidotajai istabai. Parāda 1. paziņojumu. + Atslēgšanās stāvoklis -- skaitlisks kods. ], [ + Istaba ir veiksmīgi izveidota! + Darbība nav izdevusies! Jums nav aktīva abonementa. + Sistēmas iekšēja kļūda. Mēģiniet vēlreiz! + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + Piekļuves kods neatbilst prasībām: [prasības]. + Nosaukums neatbilst prasībām: [prasības]. ], ) <SIMF04> #function-table( "Spēles sākuma pieteikums", "SIMF05", "Funkcijas mērķis ir istabas izveidotājam iesākt spēles procesu istabā, kuru ir izveidojis.", [ Dati tiek iegūti no konteksta (autentificēta lietotāja identifikators) un darbības (istabas identifikators). Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; ], [ + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 3. paziņojumu. Beidz apstrādi. + Datubāzē meklē istabas ierakstu. + Ja neatrod, parāda 3. paziņojumu. Beidz apstrādi. + Pārbauda, vai lietotājs ir istabas izveidotājs, meklējot spēlētāja ierakstu datubāzē. + Ja spēlētāju neatrod, parāda 3. paziņojumu. Beidz apstrādi. + Ja lietotājs nav istabas izveidotājs, tad parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai spēles stāvoklis atbilst nesāktās spēles stāvoklim. + Ja neatbilst, parāda 4. paziņojumu. Beidz apstrādi. + Pārbauda, vai istabā ir nepieciešamais spēlētāju skaits. + Ja nav, tad parāda 2. paziņojumu. Beidz apstrādi. + Pamaina istabas stāvokli uz stāvokli, kas atbilst spēlei procesā un uzstāda spēles sākšanas laiku uz tagadējo laiku. + Izveido spēles istabas sākuma notikumu. + Piešķir katram spēlētājam nejaušas lomas pieejamas spēles uzstādījumā. + Saglabā izmaiņas datubāzē. + Ja ierakstīšana neizdodas. Parāda 4. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir noteikt spēles sākšanas stāvokli. Veiksmīgas spēles sākšanas gadījumā, lietotājs tiek pāradresēts attiecīgās istabas spēles gaitas lapā. Spēles saskarnē parādās sākuma informācija par spēli. + Spēles sākšanas stāvoklis -- skaitlisks kods. ], [ + Darbība nav izdevusies! Jūs neesat šīs istabas izveidotājs. + Uzsākt spēli nav iespējams, nepietiek dalībnieku. + Sistēmas iekšēja kļūda. Mēģiniet vēlreiz! + Spēle jau ir sākusies vai beidzās! ], ) <SIMF05> #function-table( "Spēlētāja izslēgšana", "SIMF06", "Administrators var izslēgt spēlētāju no spēles istabas.", [ Dati tiek iegūti no konteksta (autentificēta lietotāja identifikators) un darbības (istabas identifikators un spēlētāja identifikators). Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Izslēdzamā spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; ], [ + Autorizē administratora darbību. + Ja tā nav autorizēta, parāda 4. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēlētāja ierakstu. + Ja netiek atrasts, parāda 3. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles istabas ierakstu. + Ja netiek atrasta, parāda 2. paziņojumu. Beidz apstrādi. + Pamaina spēlētāja stāvokli uz stāvokli, kas atbilst izslēgta spēlētāja stāvoklim. // + Spēlētāja ierakstu izdzēš. // + Ja izdzēšana neizdodas, parāda 2. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir noteikt izslēgšanas stāvokli, kas attiecīgi izraisa spēles saraksta atjaunošanu lietotāja saskarnē. Parāda 1. paziņojumu. + Spēlētāja izslēgšanas stāvoklis -- skaitlisks kods. ], [ + Spēlētājs ir veiksmīgi izslēgts. + Spēlētāja izslēgšana ir neveiksmīga, mēģiniet vēlreiz. + Spēlētājs netika atrasts. + Darbība nav autorizēta. ], ) <SIMF06> #function-table( "Spēlētāju pārskats", "SIMF07", "Funkcija ļauj lietotājiem iegūt pārskatu par visiem spēlētājiem noteiktā istabā.", [ Obligātie parametri: + Spēles istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Datubāzē meklē spēles istabu. + Ja nav atrasta, parādā 1. paziņojumu. Beidz apstrādi. + Iegūst spēlētāju sarakstu no datubāzes, kas ir saistīti ar spēles istabu. + Ja neviens spēlētājs netika atrasts, parāda 3. paziņojumu. Beidz apstrādi. + Katram spēlētājam iegūst attiecīgā lietotāja ierakstu. + Ja kādam spēlētājam nevar atrakst lietotāju, parāda 2. paziņojumu. Beidz apstrādi. + Izveido spēlētāju vārdnīcu sarakstu: + lietotāja segvārds; + stāvoklis; + lietotāja profila attēls. ], [ Izvades mērķis ir parādīt informāciju lietotāju par konkrētās istabas spēlētājiem. Lietotāja saskarnē tiek parādīts saraksts ar istabas spēlētājiem. + Vārdnīcu saraksts: + Lietotāja segvārds -- atbilst #link(<IIDP07>)[IIDP07]\; + Spēlētāja stāvoklis -- simbolu virkne. + Lietotāja profila attēls -- atbilst #link(<IIDP08>)[IIDP08]; ], [ + Spēles istaba nav atrasta! + Neizdevās iegūt spēlētāju sarakstu. Mēģiniet vēlreiz! + Istabā nav spēlētāju! ], ) <SIMF07> #function-table( "Spēļu vēstures pārskats", "SIMF08", "Funkcija ļauj lietotājiem iegūt pārskatu par savām iepriekšējām spēlēm.", [ Ievades dati tiek iegūti no konteksta (lietotāja identifikators) un neobligāto vietrādes meklēšanas parametra. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1; ], [ + Sāk gatavot datubāzes pieprasījumu no spēlētāja tabulas. + Sagatavo pārskata pieprasījumu un iegūst lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru. + Ja lappušu skaits ir 0, tad parāda 1. paziņojumu. Beidz apstrādi. + Veic sagatavoto pieprasījumu, iegūstot spēlētāja identifikatoru, pievienojot nosacījumu, ka spēles istabu stāvoklim jāatbilst pabeigtās spēles stāvoklim. + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Katram ierakstam no rezultāta iegūst lomas nosaukumu no spēles lomas tabulas pēc spēles lomas identifikatora. + Ja spēles loma neeksistē, parāda 3. paziņojumu. Beidz apstrādi. + Ja spēles loma eksistē, tad katram ierakstam, iegūst attēla datnes adresi no attēlu tabulas pēc attēla identifikatora. + Ja attēla datnes adrese neeksistē ierakstam, tad iegūst noklusētā attēla datnes adresi un pamaina ieraksta datnes adresi izvades datos uz noklusētā datnes attēla adresi. + Katram ierakstam no rezultāta iegūst istabas nosaukumu, spēles sākšanas un beigšanas laiku, stāvokli no istabas tabulas un saistīto spēles uzstādījuma nosaukumu pēc istabas identifikatora. + Ja istaba neeksistē, parāda 4. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir lietotāja spēļu saraksta datu izvadīšana. Lietotāja saskarnē parādās saraksts ar spēlēm. + Vārdnīcu saraksts: + Istabas nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Spēles sākšanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Spēles beigšanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Istabas stāvoklis -- skaitlisks kods; + Spēles uzstādījuma nosaukums -- atbilst #link(<IIDP21>)[IIDP21]. ], [ + Neviena spēle netika atrasta! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Nezināma spēles loma! + Nezināma spēles istaba! ], ) <SIMF08> #function-table( "Spēles atcelšana", "SIMF09", "Funkcijas mērķis ir atcelt spēli. Atcelt spēli var maksas lietotājs, ja viņš ir spēles izveidotājs, vai administrators, neatkarīgi no spēles statusa.", [ Dati tiek iegūti no konteksta (autentificēta lietotāja identifikators) un darbības (spēles identifikators). Obligātie parametri: + Lietotāja identifikators –- atbilst #link(<IIDP10>)[IIDP10]\; + Spēles identifikators –- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 4. paziņojumu. Beidz apstrādi. + Pārbauda lietotāja lomu un tiesības atcelt spēli. + Ja lietotājs nav administrators un nav spēles izveidotājs, tad parāda 3. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles ierakstu. + Ja spēli neatrod, parāda 2. paziņojumu. Beidz apstrādi. + Maina spēles stāvokli uz atceltu. + Maina visu ar spēli saistīto spēlētāju "aktīvs" lauku uz "nepatiess". + Saglabā izmaiņas datubāzē. + Ja neizdodas saglabāt izmaiņas, parāda 1. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir informēt lietotāju par veiksmīgu spēles atcelšanu vai kļūdu procesā. + Spēles atcelšanas stāvoklis –- karodziņš. ], [ + Spēles statusa maiņa neizdevās, mēģiniet vēlreiz. + Spēle ar šādu identifikatoru netika atrasta. + Jums nav tiesību atcelt šo spēli. + Nepieciešamie dati nav pilnībā iesniegti. ], ) <SIMF09> === Spēles gaitas modulis #indent-par([ Apakšnodaļa ietver spēles gaitas moduļa funkcijas. Moduļa funkcionalitāte ir izmantota spēles procesa realizēšanai. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-game-progress). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<SGMF01>)[SGMF01], #link(<SGMF02>)[SGMF02], #link(<SGMF03>)[SGMF03], #link(<SGMF04>)[SGMF04]). ]) #figure( caption: "Spēles gaitas moduļa 2. līmeņa DPD", image("img/dpd2/SpēlesGaitasModulis.svg"), ) <dpd-2-game-progress> #function-table( "Spēles darbības veikšana", "SGMF01", "Funkcijas mērķis ir veikt spēles darbību lietotājiem, kas atrodas spēles istabā, saglabājot darbību kā notikuma ierakstu.", [ Ievade tiek iegūta no darbības spēles laikā. Lietotājs uzspiež uz darbības pogu, kas ir saistīta ar konkrētu darbības ierakstu datubāzē. Obligātie parametri: + Veicēja lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Darbības identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Spēles istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. Neobligātie parametri: + Mērķa spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ // Pārbauda istabas un darbības eksistenci un atbilstību aktīvam stāvoklim + Datubāzē meklē spēles istabu, izmantojot darbības identifikatoru. + Ja spēles istaba netiek atrasta parāda 2. paziņojumu. Beidz apstrādi. + Ja spēles istabas stāvoklis neatbilst stāvoklim spēlei procesā, tad parāda 1. paziņojumu. Beidz apstrādi. // Pārbauda lietotāja, spēlētāja un spēles istabas atbilstību + Izmantojot #link(<KPR02>)[KPR02] procedūru pārbauda, vai spēlētājs, lietotājs un spēles istaba eksistē un ir savstarpēji saistīti. + Ja nav, parāda 2. paziņojumu. Beidz apstrādi. // Pārbauda darbības un lomas eksistenci, darbības saistību ar spēlētāja lomu + Iegūst lomas identifikatoru no atrastā ieraksta. Meklē lomu, izmantojot identifikatoru. + Ja loma netiek atrasta, parāda 2. paziņojumu. Beidz apstrādi. + Meklē lomas darbību attiecīgā tabulā, izmantojot darbības identifikatoru. + Ja darbība netiek atrasta parāda 2. paziņojumu. Beidz apstrādi. + Ja mērķa spēlētāju saraksts nav tukšs, meklē spēlētāju attiecīgajā tabulā, izmantot spēlētāja identifikatorus. + Pārbauda, vai darbība ir ar spēlētāja lomu saistīta darbība, meklējot saistību ar darbību pēc lomas identifikatora. + Ja tā nav, parāda 3. paziņojumu. Beidz apstrādi. // Pārbauda vai darbība ir aizliegta vai atļauta (atļaujošie/aizliedzošie notikumi) + Iegūstot spēles notikumus datubāzē, noskaidro, vai darbība ir atļauta vai aizliegta. + Pēdējais notikums, kas atļauj vai aizliedz šo darbību, šo notikumu aizliedz vai atļauj. + Ja tādu notikumu nav, tad darbība ir aizliegta. Ja pēdējais nav atļaujošais notikums, darbība ir aizliegta. + Ja darbība ir aizliegta, parāda 4. paziņojumu. Beidz apstrādi. // Izveido notikuma saistību datubāzē + Izveido jaunu darbības ierakstu ar attiecīgu spēlētāja identifikatoru, darbības identifikatoru un lomas darbību. Ja darbībai ir kāds mērķa spēlētājs, tad izveido atsevišķu ierakstu, kur vai pilda ir stāvoklī "patiess". + Ja ieraksta veikšana neizdevās. Parāda 2. paziņojumu. Beidz apstrādi. ], [ Izvades mērķis ir parādīt ar izpildīto darbību saistīto informāciju. Stāvoklis izraisa izmaiņas spēles gaitas saskarnē. + Darbības stāvokļa kods -- skaitlisks kods. ], [ + Spēle ir beigusies, nevar veikt darbību! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Darbība nav atļauta jūsu lomai! + Darbība nav atļauta šajā spēles fāzē! ], ) <SGMF01> #function-table( "Spēles notikumu izveidošana", "SGMF02", [ Funkcijas mērķis ir izveidot visiem konkrētās istabas spēlētājiem aktuālu spēles notikumu. Notikumiem ir sekojoši cēloņi: fāzes maiņa, spēlētāja darbība, darbības aizliegums vai atļauja, taimera sākums, spēles sākums, spēles beigas. Notikums var sevī ietvert noteiktu ietekmi uz spēles stāvokli, kas tiek izmainīts funkcijas ietvaros. Katram notikumam ir noteikts nosaukums, kas tiek darināts no veidnes. Piemēram "Fāze mainās uz \[fāzes nosaukums\]". ], [ Ievades dati tiek iegūti no esošās spēles gaitas konteksta. Obligātie parametri: + Spēlēs istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ // Pārbauda istabas eksistenci un atbilstību aktīvam stāvoklim. + Meklē spēles istabu attiecīgā tabulā, izmantojot darbības identifikatoru. + Ja spēles istaba netiek atrasta parāda 1. paziņojumu. Beidz apstrādi. + Ja spēles istabas stāvoklis neatbilst aktīvam stāvoklim, parāda 2. paziņojumu. // Vai pastāv aktīvs taimeris + Iegūst no datubāzes notikumus ar taimera veidu. + Ja tāds notikums ir un taimeris ir aktīvs (nav pagājis laika periods), tad parāda. Beidz apstrādi. // // Nav validācijas, jo tā ir sistēma // // Sāk fāzes fāzes pāreju: + Katram turpmāk izveidotam notikumam, izveido nosaukumu, darinot to no attiecīgās veidnes. Izveidošanas laiku norāda kā tagadējo laiku. Pārējos atribūtus norāda atkarībā no notikuma specifikas. // Iegūst spēles fāzi un spēlētāju stāvokļus un notikumus. //+ No datubāzes iegūst vēlāko nakts maiņas notikumu datubāzē. // + Ja netika atrasts neviens nakts maiņas notikums, tad pieņem, ka ir 0-tā nakts (neviena nakts vel nav notikusi). + No datubāzes iegūst spēlētāju stāvokļus. // Nosaka pēdējo fāzes maiņu + No datubāzes iegūst pēdējo spēles fāzes maiņas notikumu. + Ja pēdējā fāzes maiņa ir no dienas vai balsošanas uz nakts, veic sekojošas darbības: + Izslēdz no spēles neaktīvus spēlētājus, kam bija jāizvēlas darbība. + Aizliedz darbības. + Apstrādā darbības, veicot izmaiņas spēles un spēlētāju stāvoklī un izveidojot dažādu veidu notikumus, iekļaujot tajā attiecīgās saistības ar darbībām, lietotājiem, ja attiecināms. + Pārbauda spēles beigu nosacījumus un ja tie ir apmierināti, izveido spēles beigu notikumu, izmaina istabas stāvokli un beidz apstrādi. + Izveido notikumu fāzes maiņai uz nakti, ja ir pirmā diena vai uz balsošanu, ja nav pirmā diena. + Citādi, ja pēdējā fāzes maiņa ir no dienas uz balsošanu vai pāreja no pirmās dienas uz nakti, veic sekojošas darbības: + Iegūst balsošanas darbības no dzīviem spēlētājiem. + Izslēdz izbalsoto spēlētāju, pamainot spēlētāja stāvokli (atbilstošs atribūts). + Pārbauda spēles beigu nosacījumus un ja tie ir apmierināti, izveido spēles beigu notikumu, izmaina istabas stāvokli un beidz apstrādi. + Izveido nakts darbību atļaujošus notikumus. + Izveido notikumu fāzes maiņai uz nakti. + Citādi, veic sekojošas darbības: + Izveido balsošanas atļaujošu notikumu. + Izveido notikumu fāzes maiņai uz balsošanu. + Izveido taimera notikumu nākamai fāzei uz noteiktu laiku periodu. + Izmaina spēles istabas stāvokli uz stāvokli, kas atbilst pabeigtai spēlei un norāda beigšanas laiku uz tagadējo laiku. + Ieraksta datubāze sagatavotos notikumus un izmaiņas spēlētāju stāvokļos un spēles istabas izmaiņas. + Ja ierakstīšana neizdodas parāda 3. paziņojumu. // ASK: Some of the actions / functions are crucial for functioning. Should robustness be specified within the functions, e.g., reschedule the action if it fails in event creation. ], ], [ Izvades mērķis ir noteikt notikumu izveidošanas rezultāta stāvokli. + Notikumu izveidošanas stāvoklis -- skaitlisks kods. ], [ + Spēles istaba ar identifikatoru [istabas identifikators] netika atrasta! + Spēle nav procesā! + Notikumu izveidošana neizdevās! ], ) <SGMF02> #function-table( "Spēles notikumu pārskats", "SGMF03", "Funkcijas mērķis ir iegūt informāciju par spēles notikumiem.", [ Ievades dati tiek iegūti no attiecīgās lietotāja darbības vai vietrāža un konteksta. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]; + Spēles istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Paslēptā informācija -- karodziņš. Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1. ], [ + Veic sistēmas vai administratora darbības autorizāciju. + Ja darbība nav autorizēta ir pieprasīta paslēptā informācija un spēles istabas stāvoklis neapzīmē pabeigtu spēli, parāda 2. paziņojumu. Beidz apstrādi. + Meklē spēles istabu attiecīgā tabulā, izmantojot darbības identifikatoru. + Ja spēles istaba netiek atrasta parāda 1. paziņojumu. Beidz apstrādi. + Sāk gatavot datubāzes pieprasījumu no spēles notikumu tabulas. + Ja ir iesniegts lappuses numurs, sagatavo pārskata pieprasījumu un iegūst lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru. + Ja lappušu skaits ir 0, tad parāda 3. paziņojumu. Beidz apstrādi. + Sāk veidot sarakstu ar notikumu vārdnīcām. + Veic sagatavoto pieprasījumu, iegūstot nosaukumu, izveidošanas laiku, nakts numuru, veidu, vai ir nakts. + Ja pieprasījums neizdodas, parāda 4. paziņojumu. Beidz apstrādi. + Ja paslēptās informācijas karodziņš ir "patiess", tad vārdnīcai pievieno atbilstošā spēlētāja, tā lomas identifikatoru un tā darbības identifikatoru, ja tas ir attiecināms, meklējot to datubāzē. + Ja pieprasījums datubāzei neizdodas, parāda 4. paziņojumu. + Ja notikuma redzamības spēles procesā karodziņš ir "patiess" un ja paslēptās informācijas karodziņš ir "patiess", notikumu pievieno sarakstam, citādi notikumu sarakstam nepievieno. + Ja notikuma veids atbilst taimera notikumam, sarakstam pievieno taimera laiku. + Citādi taimera laiks ir 0. ], [ Izvades mērķis ir par notikumiem nepieciešamās informācijas apkopošana vārdnīcu sarakstā atkarībā no paslēptās informācijas ievades karodziņa. Ja netiek parādīta paslēptā informācija, saraksts sastāvēs no vārdnīcām: + Notikuma nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Izveidošanas laiks -- atbilst #link(<IIDP02>)[IIDP21]\; + Nakts numurs -- vesels skaitlis; + Veids -- atbilst #link(<IIDP03>)[IIDP03]; + Vai ir nakts -- atbilst #link(<IIDP21>)[IIDP21]\; + Taimera laiks -- skaitlis vai 0\. Ja netiek parādīta paslēptā informācija, tad vārdnīcām papildus ir: + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Darbības identifikators -- atbilst #link(<IIDP10>)[IIDP10]\. ], [ + Spēles istaba ar identifikatoru [istabas identifikators] netika atrasta! + Notikumu detalizēts pārskats nav pieejams spēles laikā! + Nav neviena spēles notikuma! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <SGMF03> #pagebreak(weak: true) #function-table( "Spēles stāvokļa detaļas", "SGMF04", "Funkcijas mērķis par spēles tagadējo stāvokli, kas ietver spēlētāju stāvokli, nakts numuru un atļautās darbības.", [ Ievades dati tiek iegūti no attiecīgās lietotāja darbības vai vietrāža un konteksta. Paslēptā informācija nosaka, vai izvade saturēs lomu datus par spēlētājiem. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēles istabas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. + Paslēptā informācija -- karodziņš. ], [ + Veic sistēmas vai administratora darbības autorizāciju. + Ja darbība nav autorizēta ir pieprasīta paslēptā informācija un spēles istabas stāvoklis neapzīmē pabeigtu spēli, parāda 3. paziņojumu. Beidz apstrādi. + Ja darbība nav autorizēta, izmantojot #link(<KPR02>)[KPR02] procedūru pārbauda, vai spēlētājs, lietotājs un spēles istaba eksistē un ir savstarpēji saistīti. + Ja nav, parāda 3. paziņojumu. Beidz apstrādi. + Meklē spēles istabu attiecīgā tabulā, izmantojot darbības identifikatoru. + Ja spēles istaba netiek atrasta parāda 1. paziņojumu. Beidz apstrādi. + Iesāk stāvokļa vārdnīcas gatavošanu ar noteiktu informāciju. Vārdnīcai pievieno sekojošus datus: + Spēles istabas stāvoklis; + Spēles sākšanas laiks; + Mafijas sakaru redzamība -- ja spēlētājam ir mafijai piederoša loma; + Vispārīgo sakaru redzamība -- ja spēlētāja stāvoklis atbilst aktīvam, neizslēgtam no spēles spēlētājam; + Nakts numurs. + Iegūst spēlētāju identifikatoru sarakstu no datubāzes, kas ir saistītas ar spēles istabu. + Katram identifikatoram no iegūtā saraksta veic sekojošas darbības: + Meklē spēlētāju datubāzē, izmantojot spēlētāja identifikatoru. + Ja spēlētāja ieraksts netika atrasts, parāda 4. paziņojumu. Beidz apstrādi. + Sagatavo spēlētāja lietotāja profila attēlu: + Ja profila attēls nav tukšs, to uzskata par noteikto noklusēto attēlu. + Pievieno vārdnīcu sarakstam vārdnīcu ar sekojošiem datiem: + Spēlētāja identifikators; + Lietotāja lietotājvārds; + Dzīvības stāvoklis; + Lietotāja profila attēls. + Ja paslēptās informācijas karodziņš ir "patiess" vai spēles stāvoklis atbilst izbeigtās spēles stāvoklim, vārdnīcai pievieno sekojošus datus: + Lomas identifikators. ], [ Izvades mērķis nepieciešamās spēles stāvokļa informācijas parādīšana lietotāja saskarnē. + Spēles istabas stāvoklis -- atbilst #link(<IIDP03>)[IIDP03]\; + Spēles sākšanas laiks -- atbilst #link(<IIDP02>)[IIDP02]\; + Mafijas sakaru redzamība -- karodziņš; + Vispārīgo sakaru redzamība -- karodziņš; + Nakts numurs -- vesels pozitīvs skaitlis. + Spēlētāju vārdnīcu saraksts. Katra spēlētāja vārdnīca, kuras atslēgas ir: + Spēlētāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Lietotāja lietotājvārds -- atbilst #link(<IIDP10>)[IIDP10]\; + Dzīvības stāvoklis -- karodziņš; + Lietotāja profila attēls -- atbilst #link(<IIDP08>)[IIDP08]\; Ja paslēptā informācija tiek izvadīta, tad spēlētāju vārdnīca saturēs arī: + Lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; ], [ + Spēles istaba ar identifikatoru [istabas identifikators] netika atrasta! + Spēlētāju ar identifikatoru: [spēlētāju identifikatori] netika atrasti! + Darbība nav autorizēta! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <SGMF04> === Spēles lomu uzstādījumu modulis #indent-par([ Apakšnodaļa ietver spēles lomu uzstādījumu moduļa funkcijas. Moduļa funkcionalitāte ir izmantota darbībām saistībā ar lomām. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-game-role). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<SLMF01>)[SLMF01], #link(<SLMF02>)[SLMF02], #link(<SLMF03>)[SLMF03], #link(<SLMF04>)[SLMF04], #link(<SLMF05>)[SLMF05], #link(<SLMF06>)[SLMF06]). ]) #figure( caption: "Spēles lomu uzstādījumu moduļa 2. līmeņa DPD", image("img/dpd2/SpēlesLomuModulis.svg"), ) <dpd-2-game-role> #function-table( "Lomas detaļas", "SLMF01", "Funkcijas mērķis ir izvadīt pieprasītās lomas detaļas, kas neietver lomas darbības (tam ir domāta atsevišķa funkcija).", [ Ievades dati tiek iegūti no vietrāža vai lietotāja darbības. Obligātie parametri: + Spēles lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Sagatavo datubāzes pieprasījumu no spēles lomu tabulas. + Pieprasījumam pievieno atlasīšanu pēc spēles lomas identifikatora. + Sagatavo pieprasījuma lauku sarakstu. Saraksta pamatā ir identifikators, nosaukums, apraksts, vai ir pamata, vai pieder mafijas grupai. + Veic sagatavoto pieprasījumu, pieprasot iepriekš sagatavoto lauku sarakstu. + Ja pieprasījums neizdotas, parāda 1. paziņojumu. Beidz apstrādi. + Ja spēles loma netika atrasta, parāda 2. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir spēles lomas datu izvadīšana. Lietotāja saskarnē tiek prezentētas pieprasītās lomas detaļas. + Vārdnīca + Lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Nosaukums -- atbilst #link(<IIDP10>)[IIDP10]\; + Apraksts -- simbolu virkne; // + Maksimāli pieļaujamais skaits spēlē -- nenegatīvs skaitlis; // + Vai var tikt mafijas noslepkavots -- karodziņš; + Vai ir pamata -- karodziņš. + Vai pieder mafijas grupai -- karodziņš. ], [ + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Tāda spēles lomas nav atrasta! Mēģiniet vēlreiz! ], ) <SLMF01> #function-table( "Lomu pārskats", "SLMF02", "Funkcijas mērķis ir izvadīt sarakstu ar visām pieejamajām lomām, to nosaukumiem.", [ Ievades datus iegūst no veicamās darbības un neobligāto vietrādes meklēšanas parametra. Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1. + Meklēšanas uzvedne -- simbolu virkne, atbilst #link(<IIDP14>)[IIDP14], noklusētā vērtība -- "". + Kārtošanas vārdnīcu saraksts -- atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. ], [ + Sāk gatavot datubāzes pieprasījumu no spēles lomu tabulas. + Sagatavo pārskata pieprasījumu un iegūst lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru, meklēšanas uzvedni, kārtošanas vārdnīcu sarakstu, filtru vārdnīcu sarakstu, šos parametrus iesniedzot, ja tie ir iesniegti funkcijā. + Ja lappušu skaits ir 0, tad parāda 1. paziņojumu. Beidz apstrādi. + Veic sagatavoto pieprasījumu, iegūstot lomas nosaukumu, vai ir pamata, aprakstu, piederību mafijai. + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Katram ierakstam no rezultāta iegūst attēla datnes adresi no attēlu tabulas pēc attēla identifikatora. + Ja attēla datnes adrese neeksistē ierakstam, tad iegūst noklusētā attēla datnes adresi un pamaina ieraksta datnes adresi izvades datos uz noklusētā datnes attēla adresi. ], [ Izvades datu mērķis ir spēles lomu saraksta datu izvadīšana. Lietotāja saskarnē parādās saraksts ar lomām. + Vārdnīcu saraksts: + Lomas nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; // + Maksimāls spēlējošo skaits -- vesels pozitīvs skaitlis; + Lomas apraksts -- atbilst #link(<IIDP09>)[IIDP09]\; + Vai ir pamata -- karodziņš; // + Vai var tikt mafijas noslepkavots -- karodziņš; + Lomas attēla adrese -- atbilst #link(<IIDP08>)[IIDP08]\; + Piederība mafijas grupai -- karodziņš. ], [ + Neviena spēles loma netika atrasta! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Tāda spēles lomas nav atrasta! Mēģiniet vēlreiz! ], ) <SLMF02> #function-table( "Lomas darbību pārskats", "SLMF03", "Funkcijas mērķis ir izvadīt visas darbības, kuras var izpildīt attiecīgā loma.", [ Ievades dati tiek iegūti no vietrāža vai lietotāja darbības. Obligātie parametri: + Spēles lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Sagatavo datubāzes pieprasījumu lomas darbību meklēšanai pēc lomas identifikatora. + Veic sagatavoto pieprasījumu, iegūstot aprakstu, lomas nosaukumu, lomas darbības nosaukumu. + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Ja spēles loma netika atrasta, parāda 3. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir spēles lomas darbības datu izvadīšana. Lietotāja saskarnē parādās informācija par konkrētās lomas darbībām. + Vārdnīca: + Darbības apraksts -- atbilst #link(<IIDP09>)[IIDP09]\; + Lomas nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Lomas darbības nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; // + Vai lomas darbība ir tūlītēja -- karodziņš. ], [ + Sistēmas iekšēja kļūda! Mēģiniet vēlreiz! + Tāda spēles lomas nav atrasta! Mēģiniet vēlreiz! ], ) <SLMF03> #function-table( "Jaunas lomas izveidošana", "SLMF04", "Funkcijas mērķis ir izveidot spēles lomu.", [ Ievades dati tiek saņemti no maksas lietotājiem un administratoriem pieejamās veidlapas. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Apraksts -- atbilst #link(<IIDP09>)[IIDP09]\; + Lomas darbību identifikatoru saraksts -- saraksts no identifikatoriem, kas atbilst #link(<IIDP10>)[IIDP10]\; + Vai pieder mafijas grupai -- karodziņš; Neobligātie parametri: + Vai ir pamata -- karodziņš, noklusētā vērtība -- nepatiess. + Attēls -- atbilst #link(<IIDP08>)[IIDP08], noklusētā vērtība -- noklusētā attēla datnes adrese. ], [ + Veic maksas lietotāja darbības autorizāciju, izmantojot #link(<KPR08>)[KPR08] procedūru, vai administratora darbības autorizāciju. + Ja darbība nav autorizēta, parāda 10. paziņojumu. Beidz apstrādi. + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai apraksts un lomas nosaukums ir ievadīts. + Ja ievadīts, pārbauda, vai nepārsniedz noteikto garumu. + Ja pārsniedz, tad iegūst pārsniegto garumu parametru sarakstu un parāda 2. paziņojumu ar attiecīgajiem laukiem un garumiem. Beidz apstrādi. + Ja ievadīts, pārbauda, vai satur tikai pieļaujamos simbolus. + Ja nesatur, tad iegūst izmantotos neatļautos simbolus, tad parāda 7. paziņojumu ar attiecīgiem laukiem un simboliem. Beidz apstrādi. + Ja "vai ir pamata" karodziņš ir stāvoklī "patiess", autorizē administratora darbību. + Ja tā netiek autorizēta, parāda 8. paziņojumu. Beidz apstrādi. + Mēģina atrast datubāzē spēles lomu ar ievadīto nosaukumu. + Ja tāds pastāv, tad parāda 3. paziņojumu. Beidz apstrādi. + Ja ir ievadīts lomas darbību identifikatoru saraksts, tad katram saraksta identifikatoram izveidot saistības ierakstu starp spēles lomas un spēles darbības ierakstu, pirms tam pārbaudot darbību eksistenci datubāzē. + Ja kāda no darbībām neeksistē, parāda 9. paziņojumu. Beidz apstrādi. // Image + Ja tika iesniegts attēls, validē attēlu ar #link(<KPR12>)[KPR12] un uzstāda pievienošanas laiku uz tagadējo laiku. + Ja validācija ir neveiksmīga, parāda 11. paziņojumu ar attiecīgu validācijas kļūdu. + Citādi saglabā vecā attēla datni, ja tāda ir. + Jaunas spēles lomas dati -- nosaukums, apraksts un karodziņi -- tiek ierakstīti datubāzē. + Ja kāda ierakstīšana nenotiek, parāda 5. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir noteikt, vai spēles loma ir veiksmīgi saglabāta. Lietotāja saskarnē parāda 4. paziņojumu. Lietotājs tiek pāradresēts lomu pārskata lapā. + Lomas izveidošanas stāvoklis -- skaitlisks kods. ], [ + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]! + Loma ar tādu nosaukumu jau eksistē! Samainiet nosaukumu un mēģiniet vēlreiz! + Loma veiksmīgi izveidota! + Sistēmas iekšēja kļūda! Mēģiniet vēlreiz! + Skaitlim jābūt nenegatīvam! Mēģiniet vēlreiz! + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]! + Darbība nav autorizēta: Jūs nevarat veidot pamata lomas! + Viena vai vairākas darbības, ko Jūs izvēlējāties, neeksistē! + Darbība nav autorizēta: Jūs nevarat veidot lomas! + Šo attēlu nedrīkst izmantot: [validācijas kļūda\]! ], ) <SLMF04> #function-table( "<NAME>ģēšana", "SLMF05", "Funkcijas mērķis ir rediģēt spēles lomas.", [ Ievades dati tiek saņemti no maksas lietotājiem un administratoriem pieejamās veidlapas. Obligātie parametri: + Spēles lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]; + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Apraksts -- atbilst #link(<IIDP09>)[IIDP09]\; + Lomas darbību identifikatoru saraksts -- saraksts no identifikatoriem, kas atbilst #link(<IIDP10>)[IIDP10]\; + Vai pieder mafijas grupai -- karodziņš. Neobligātie parametri: + Vai ir pamata -- karodziņš; + Attēls -- atbilst #link(<IIDP08>)[IIDP08], noklusētā vērtība -- noklusētā attēla datnes adrese. ], [ + Veic maksas lietotāja darbības autorizāciju, izmantojot #link(<KPR08>)[KPR08] procedūru, vai administratora darbības autorizāciju. + Ja darbība nav autorizēta, parāda 10. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles lomas ierakstu. + Ja tā netiek atrasta, parāda 9. paziņojumu. Beidz apstrādi. + Ja ar spēles lomu saistīts lietotāja identifikators nesakrīt ar lietotāja identifikatoru, kurš izveidoja doto spēles lomu, veic administratora darbības autorizāciju. + Ja tā netiek autorizēta parādīt 6. paziņojumu. Beidz apstrādi. + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai nosaukums un apraksts nepārsniedz noteikto garumu. + Ja pārsniedz, parāda 2. paziņojumu ar attiecīgajiem laukiem un garumiem. Beidz apstrādi. + Pārbauda, vai nosaukums un darbības nosaukums, ja ievadīts, satur tikai pieļaujamos simbolus. + Ja nesatur, tad iegūst izmantotos neatļautos simbolus, tad parāda 8. paziņojumu ar attiecīgajiem laukiem un simboliem. Beidz apstrādi. + Veido izmainīto datu sarakstu pēc turpmāk izmainītajiem laukiem. + Ja tika iesniegts atšķirīgs nosaukums, mēģina datubāzē atrast lomu ar ievadīto nosaukumu. Ja tāda pastāv, tad parāda 3. paziņojumu. Beidz apstrādi. + Katram identifikatoram spēles lomas darbību identifikatoru sarakstā meklē darbību datubāzē. + Ja kāda no darbībām netika atrasta, parāda 11. paziņojumu. Beidz apstrādi. // Image + Ja tika iesniegts attēls, validē attēlu ar #link(<KPR12>)[KPR12] un uzstāda pievienošanas laiku uz tagadējo laiku. + Ja validācija ir neveiksmīga, parāda 12. paziņojumu ar attiecīgu validācijas kļūdu. + Citādi saglabā vecā attēla datni, ja tāda ir. + Iepriekš izmainītos laukus pievieno izmainīto lauku sarakstam un atjauno darbību saistības ar lomu. Spēles uzstādījumu sagatavotie dati -- lauki, kas ir rediģēto lauku sarakstā, tiek ierakstīti datubāzē. + Ja ierakstīšana nenotiek, parādīt 5. paziņojumu. Beidz apstrādi. + Izdzēš vecā attēla datni. ], [ Izvades datu mērķis ir noteikt, vai spēles loma ir veiksmīgi rediģēta. Lietotāja saskarnē parāda 4. paziņojumu. Lietotājs tiek pāradresēts lomu pārskata lapā. + Lomas rediģēšanas stāvoklis -- skaitlisks kods. ], [ + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]! + Loma ar tādu nosaukumu jau eksistē! Samainiet nosaukumu un mēģiniet vēlreiz! + Loma veiksmīgi rediģēta! + Lomas rediģēšana nav veiksmīga! + Darbība nav autorizēta: jums nepieder šī loma! + Skaitlim jābūt nenegatīvam! Mēģiniet vēlreiz! + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]! + Loma netika atrasta! + Darbība nav autorizēta: Jūs nevarat rediģēt lomas! + Viena vai vairākas darbības, ko Jūs izvēlējāties, neeksistē! + Šo attēlu nedrīkst izmantot: [validācijas kļūda\]! ], ) <SLMF05> #function-table( "Lomas dzēšana", "SLMF06", "Funkcijas mērķis ir neatgriezeniski dzēst spēles lomu.", [ Ievades dati tiek saņemti no maksas lietotājiem un administratoriem pieejamās darbības lomu sarakstā vai lomu rediģēšanas lapā. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēles lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Veic maksas lietotāja darbības autorizāciju, izmantojot #link(<KPR08>)[KPR08] procedūru, vai administratora darbības autorizāciju. + Ja darbība nav autorizēta, parāda 1. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles lomas ierakstu. + Ja tā netiek atrasta, parāda 2. paziņojumu. Beidz apstrādi. + Ja ar spēles lomu saistīts lietotāja identifikators nesakrīt ar lietotāja identifikatoru, kurš izveidoja doto spēles lomu, veic administratora darbības autorizāciju. + Ja tā netiek autorizēta parādīt 5. paziņojumu. Beidz apstrādi. + Visas spēles lomas un lomas darbības daudz pret daudz starptabulas izdzēš. + Ja izdzēšana nav veiksmīga, parāda 4. paziņojumu. Beidz apstrādi. + Saglabā veco lomas datnes adresi, ja tāda ir. + Spēles lomas ierakstu izdzēš. + Ja izdzēšana nav veiksmīga, parāda 4. paziņojumu. Beidz apstrādi. + Izdzēš veco lomas attēlu. ], [ Izvades datu mērķis ir noteikt spēles lomas dzēšanas stāvokli. Lietotāja saskarnē parāda 3. paziņojumu. Lietotājs ir pāradresēts uz lomu pārskata lapu, ja nepieciešams. + Spēles lomas dzēšanas stāvoklis -- skaitlisks kods. ], [ + Darbība nav autorizēta: Jūs nevarat dzēst lomas! + Tāda loma nav atrasta! + Loma ir veiksmīgi izdzēsta! + Sistēmas iekšēja kļūda! Mēģiniet vēlreiz! + Darbība nav autorizēta: dzēšamā loma nav Jūsu loma! ], ) <SLMF06> === Spēles uzstādījumu modulis #indent-par([ Apakšnodaļa ietver spēles uzstādījumu moduļa funkcijas. Moduļa funkcionalitāte ir izmantota darbībām saistībā ar spēles uzstādījumiem. Moduļa funkciju datu plūsmas ir parādītas 2. līmeņa datu plūsmas diagrammā (skat. @fig:dpd-2-game-setup). Funkcijas ir aprakstītas atsevišķās tabulās (skat. #link(<SUMF01>)[SUMF01], #link(<SUMF02>)[SUMF02], #link(<SUMF03>)[SUMF03], #link(<SUMF04>)[SUMF04], #link(<SUMF05>)[SUMF05]). ]) #figure( caption: "Spēles uzstādījumu moduļa 2. līmeņa DPD", image("img/dpd2/SpēlesUzstādījumuModulis.svg"), ) <dpd-2-game-setup> #function-table( "Spēles uzstādījumu pārskats", "SUMF01", "Funkcijas mērķis ir sniegt pārskatu par spēles uzstādījumiem.", [ Ievades dati tiek iegūti no vietrāža. Neobligātie parametri: + Lappuses numurs -- vesels pozitīvs skaitlis, noklusētā vērtība -- 1. + Meklēšanas uzvedne -- simbolu virkne, atbilst #link(<IIDP14>)[IIDP14], noklusētā vērtība -- "". + Kārtošanas vārdnīcu saraksts - atbilst #link(<IIDP20>)[IIDP20], noklusētā vērtība -- tukšs saraksts. + Filtru vārdnīcu saraksts -- atbilst #link(<IIDP19>)[IIDP19], noklusētā vērtība -- tukšs saraksts. ], [ + Sāk gatavot datubāzes pieprasījumu no spēles uzstādījumu tabulas. + Sagatavo pārskata pieprasījumu un iegūst lappuses numuru un kopējo lappušu skaitu, izmantojot #link(<KPR07>)[KPR07] ar lappuses numuru, meklēšanas uzvedni, kārtošanas vārdnīcu sarakstu, filtru vārdnīcu sarakstu, šos parametrus iesniedzot, ja tie ir iesniegti funkcijā. + Ja lappušu skaits ir 0, tad parāda 1. paziņojumu. Beidz apstrādi. + Veic sagatavoto pieprasījumu, iegūstot spēles uzstādījuma nosaukumu, aprakstu, vai tas ir pamata un izveidošanas laiku. + Ja pieprasījums neizdodas, parāda 2. paziņojumu. Beidz apstrādi. + Pie rezultāta vārdnīcai aktīvuma karodziņu -- meklē spēles istabas tekošās spēles stāvoklī un ja atrod vismaz vienu tādu istabu, tad spēles uzstādījums ir aktīvs. + Aprēķina maksimālo spēlētāju skaitu, meklējot datubāzē ar spēles uzstādījumu saistītās spēles lomas un saskaitot kopā to skaitus katram uzstādījumam. + Ja kāda no lomām netiek atrasta, izņem spēles uzstādījumu no saraksta. ], [ Izvades datu mērķis ir spēles virtuālās istabas uzstādījumu datu izvadīšana. Lietotāja saskarnē parādās saraksts ar informāciju par spēles uzstādījumiem. + Vārdnīcu saraksts: + Nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\. + Apraksts -- atbilst #link(<IIDP09>)[IIDP09]\; + Vai ir pamata -- karodziņš; + Vai ir aktīvs -- karodziņš; + Nepieciešamo spēlētāju skaits -- vesels pozitīvs skaitlis\; + Izveidošanas laiks -- atbilst #link(<IIDP02>)[IIDP02]. ], [ + Neviens spēles uzstādījums nav atrasts! + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! ], ) <SUMF01> #function-table( "Spēles uzstādījuma lomu pārskats", "SUMF02", "Funkcijas mērķis ir sniegt pārskatu ar daļēju informāciju par spēles uzstādījumu lomām.", [ Ievades dati tiek iegūti no vietrāža. Obligātie parametri: + Spēles uzstādījumu identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Sagatavo datubāzes pieprasījumu no spēles uzstādījumu tabulas. + Pieprasījumam pievieno atlasīšanu pēc spēles uzstādījuma identifikatora. + Sagatavo pieprasījumu lauku sarakstu: lomu identifikatori, nosaukumi, attēli, piederība mafijai. + Veic sagatavoto pieprasījumu, pieprasot iepriekš sagatavoto lauku sarakstu. + Ja pieprasījums neizdodas, parāda 1. paziņojumu. Beidz apstrādi. + Ja spēles uzstādījums netika atrasts, parāda 2. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir spēles virtuālās istabas uzstādījumu datu izvadīšana. Lietotāja saskarnē parādās saraksts ar konkrēta spēles uzstādījuma lomu informācija. + Vārdnīca: + Lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Lomas nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Vai pieder mafijai -- karodziņš; + Lomas attēls -- atbilst #link(<IIDP08>)[IIDP08]. ], [ + Sistēmas iekšējā kļūda! Mēģiniet vēlreiz! + Tāds spēles uzstādījums nav atrasts! Mēģiniet vēlreiz ], ) <SUMF02> #function-table( "Jauna spēles uzstādījuma izveidošana", "SUMF03", "Funkcijas mērķis ir izveidot spēles uzstādījumu, turpmākai izmantošanai spēlē.", [ Ievades dati tiek saņemti no maksas lietotājiem un administratoriem pieejamās veidlapas. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Apraksts -- atbilst #link(<IIDP09>)[IIDP09]. + Lomu datu vārdnīcu saraksts -- saraksts ar vārdnīcām; + Lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Skaits - vesels pozitīvs skaitlis. Neobligātie parametri: + Vai ir pamata -- karodziņš. ], [ + Veic maksas lietotāja darbības autorizāciju, izmantojot #link(<KPR08>)[KPR08] procedūru, vai administratora darbības autorizāciju. + Ja darbība nav autorizēta, parāda 9. paziņojumu. Beidz apstrādi. + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, parāda 1. paziņojumu ar attiecīgajiem laukiem. Beidz apstrādi. + Pārbauda, vai nosaukums un darbības nosaukums, ja ievadīts, satur tikai pieļaujamos simbolus. + Ja nesatur, parāda 6. paziņojumu ar attiecīgi laukiem un simboliem. Beidz apstrādi. + Pārbauda, vai nosaukums un apraksts nepārsniedz noteikto garumu. + Ja pārsniedz, parāda 2. paziņojumu ar attiecīgajiem laukiem un garumiem. Beidz apstrādi. + Mēģina atrast datubāzē uzstādījumus ar ievadīto nosaukumu. + Ja tāds pastāv, tad parāda 3. paziņojumu. Beidz apstrādi. + Katrai vārdnīcai no lomu datu vārdnīcu saraksta veic sekojošas manipulācijas. + Meklē lomu datubāzē. + Ja tā neeksistē, parāda 10. paziņojumu. Beidz apstrādi. + Ja skaits nav pozitīvs, parāda 7. paziņojumu. Beidz apstrādi. + Lomas skaitu pieskaita pie skaita summas. + Ieraksta izveidošanas laiku uzstāda uz tagadējo laiku. + Pārbauda, vai lomu kopējais skaits (skaitu summa) atbilst noteiktai skaita robežai. + Ja neatbilst, parāda 8. paziņojumu. Beidz apstrādi. + Jaunas spēles uzstādījuma dati -- apraksts, nosaukums, karodziņš -- un attiecīgas lomu saistības tiek ierakstītas datubāzē. + Ja ierakstīšana nenotiek parāda 5. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir noteikt, vai spēles uzstādījumi ir veiksmīgi saglabāti. Lietotāja saskarnē parāda 7. paziņojumu. Lietotāju pāradresē lomu pārskata lapā. + Uzstādījumu izveidošanas stāvoklis -- skaitlisks kods. ], [ + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]! + Spēles uzstādījums ar tādu nosaukumu jau eksistē! Samainiet nosaukumu un mēģiniet vēlreiz! + Spēles uzstādījums ir veiksmīgi izveidots! + Sistēmas iekšēja kļūda! Mēģiniet vēlreiz! + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]! + Lomas skaitam jābūt pozitīvam skaitlim! + Lomu skaitam jābūt [lomas skaita robežas]! + Darbība nav autorizēta: Jūs nevarat izveidot jaunu spēles uzstādījumu! + Viena vai vairākas no Jūsu izvēlētām lomām neeksistē! ], ) <SUMF03> #function-table( "Spēles uzstādījuma rediģēšana", "SUMF04", "Funkcijas mērķis ir rediģēt spēles uzstādījumu.", [ Ievades dati tiek saņemti no maksas lietotājiem un administratoriem pieejamās veidlapas. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēles uzstādījuma identifikators -- atbilst #link(<IIDP10>)[IIDP10]. Noklusētā vērtība -- no konteksta spēles uzstādījumu, kas tiek rediģēts, iegūtais identifikators. + Apraksts -- atbilst #link(<IIDP09>)[IIDP09]\; + Nosaukums -- atbilst #link(<IIDP21>)[IIDP21]\; + Lomu datu vārdnīcu saraksts -- saraksts ar vārdnīcām; + Lomas identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Skaits - vesels pozitīvs skaitlis. Administratoram specifiskie ievaddati: + Vai ir pamata -- karodziņš, noklusētā vērtība -- nepatiess. + Izveidošanas laiks -- datums formatēts kā simbolu virkne, noklusētā vērtība -- tagadējais laiks. ], [ + Veic maksas lietotāja darbības autorizāciju, izmantojot #link(<KPR08>)[KPR08] procedūru, vai administratora darbības autorizāciju. + Ja darbība netiek autorizēta, parādīt 11. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles uzstādījumu. + Ja tas netiek atrasts. Parāda 11. paziņojumu. Beidz apstrādi. + Ja ar spēles uzstādījumu saistīts lietotāja identifikators nesakrīt ar lietotāja identifikatoru, veic administratora darbības autorizāciju. + Ja darbība nav autorizēta. Parāda 6. paziņojumu. + Veido izmainīto datu sarakstu pēc turpmāk izmainītajiem laukiem. + Pārbauda, vai visi obligātie lauki ir iesniegti. + Ja nav, iegūst sarakstu ar neaizpildītajiem laukiem un parāda 1. paziņojumu. Beidz apstrādi. + Pārbauda, vai nosaukums un darbības nosaukums, ja ievadīts, satur tikai pieļaujamos simbolus. + Ja nesatur, tad iegūst izmantotos neatļautos simbolus, tad parāda 9. paziņojumu ar attiecīgi laukiem un simboliem. Beidz apstrādi. + Pārbauda, vai nosaukums un apraksts nepārsniedz noteikto garumu. + Ja pārsniedz, tad iegūst pārsniegto garumu parametru sarakstu un parāda 2. paziņojumu ar attiecīgajiem laukiem un garumiem. Beidz apstrādi. + Ja tika iesniegts atšķirīgs nosaukums, mēģina datubāzē atrast uzstādījumus ar ievadīto nosaukumu. + Ja tāds pastāv, tad parāda 3. paziņojumu. Beidz apstrādi. + Iepriekš izmainītos laukus pievieno izmainīto lauku sarakstam. + Autorizē administratora darbību. Ja darbība ir autorizēta, veic sekojošās darbības. + Pārbauda, vai datumam ir korekts formāts. + Ja nav, parāda 7. paziņojumu. Beidz apstrādi. + Pārbauda, vai datums ir pagātnē vai tagad. Beidz apstrādi. + Ja datums ir nākotnē, parāda 8. paziņojumu. Beidz apstrādi. + Sagatavotiem datiem pievieno administratoriem specifiskās. Beidz apstrādi. + Katrai vārdnīcai no lomu datu vārdnīcu saraksta veic sekojošas manipulācijas. + Meklē lomu datubāzē. + Ja tā neeksistē, parāda 13. paziņojumu. Beidz apstrādi. + Ja skaits nav pozitīvs, parāda 4. paziņojumu. Beidz apstrādi. + Lomas skaitu pieskaita pie skaita summas. + Pārbauda, vai lomu kopējais skaits (skaitu summa) atbilst noteiktam skaita robežai. + Ja neatbilst, parāda 8. paziņojumu. Beidz apstrādi. + Spēles uzstādījumu sagatavotie dati -- lauki, kas ir rediģēto lauku sarakstā -- tiek ierakstīti un lomu jaunās saistības datubāzē. + Ja ierakstīšana nenotiek, parādīt 5. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir noteikt spēles uzstādījumu rediģēšanas stāvokli. Lietotāja saskarnē parāda 10. paziņojumu. Lietotājs tiek pāradresēts uz spēles uzstādījumu pārskata lapu. + Spēles uzstādījumu rediģēšanas apstiprinājuma stāvoklis -- skaitlisks kods. ], [ + Lauks: [neaizpildīto lauku saraksts] netika aizpildīts (/-i)! + [Parametra nosaukums] nedrīkst pārsniegt [noteikto parametra maksimālo simbolu skaits]! + Spēles uzstādījums ar tādu nosaukumu jau eksistē! Samainiet nosaukumu un mēģiniet vēlreiz! + Lomas skaitam jābūt pozitīvam skaitlim! + Spēles uzstādījuma rediģēšana nav veiksmīga! + Darbība nav autorizēta: Jums nepieder šis spēles uzstādījums! + Nekorekts datums! Datuma formāts: [nepieciešamais datuma formāts]. + Izveidošanas datums nedrīkst būt nākotnē! + [Parametra nosaukums] nedrīkst saturēt: [izmantoto parametra neatļauto simbolu saraksts]! + Spēles uzstādījums ir veiksmīgi rediģēts! + Tāds spēles uzstādījums netika atrasts! + Darbība nav autorizēta: Jūs nevarat rediģēt spēles uzstādījumus! + Viena vai vairākas no Jūsu izvēlētām lomām neeksistē! ], ) <SUMF04> #function-table( "Spēles uzstādījuma dzēšana", "SUMF05", "Funkcijas mērķis ir neatgriezeniski dzēst spēles virtuālās istabas uzstādījumus.", [ Ievades dati tiek saņemti no maksas lietotājiem un administratoriem pieejamās darbības spēles uzstādījumu sarakstā vai spēles uzstādījumu lapā. Obligātie parametri: + Lietotāja identifikators -- atbilst #link(<IIDP10>)[IIDP10]\; + Spēles uzstādījuma identifikators -- atbilst #link(<IIDP10>)[IIDP10]. ], [ + Veic maksas lietotāja darbības autorizāciju, izmantojot #link(<KPR08>)[KPR08] procedūru, vai administratora darbības autorizāciju. + Ja darbība netiek autorizēta, parādīt 1. paziņojumu. Beidz apstrādi. + Datubāzē meklē spēles uzstādījumu. + Ja tas netiek atrasts. Parāda 6. paziņojumu. Beidz apstrādi. + Ja ar spēles uzstādījumu saistīts lietotāja identifikators nesakrīt ar lietotāja identifikatoru, veic administratora darbības autorizāciju. + Ja darbība nav autorizēta. Parāda 7. paziņojumu. + Pārbauda, vai uzstādījums pašlaik ir aktīvs, meklējot datubāzē aktīvas spēles istabas, kas izmanto spēles uzstādījumu. + Ja tādas ir, parāda 3. paziņojumu. Beidz apstrādi. + Uzstādījumu ierakstu izdzēš. + Ja izdzēšana nav veiksmīga, parāda 5. paziņojumu. Beidz apstrādi. ], [ Izvades datu mērķis ir noteikt spēles uzstādījumu dzēšanas stāvokli. Lietotāja saskarnē parāda 4. paziņojumu. Lietotājs tiek pāradresēts spēles uzstādījumu pārskata lapā, ja nepieciešams. + Spēles uzstādījumu dzēšanas stāvoklis -- skaitlisks kods. ], [ + Darbība nav autorizēta: Jūs nevarat dzēst spēles uzstādījumus! + Tāds spēles uzstādījums nav atrasts! Mēģiniet vēlreiz! + Spēles uzstādījumi pašlaik tiek izmantoti. Mēģiniet vēlreiz vēlāk. + Spēles uzstādījums ir veiksmīgi izdzēsts! + Sistēmas iekšēja kļūda! Mēģiniet vēlreiz! + Spēles uzstādījums netika atrasts! + Darbība nav autorizēta: Jūs nevarat dzēst šo spēles uzstādījumu! ], ) <SUMF05> == Nefunkcionālās prasības === Veiktspējas prasības ==== Statiskā veiktspēja #indent-par([ Uz statisko veiktspēju ir sekojošas prasības: ]) - Normāla sistēmas darbība vismaz 500 lietotājiem paralēli. - Normāla sistēmas darbība ar vismaz 40 paralēlām spēles instancēm. ==== Dinamiskā veiktspēja #indent-par([ Uz dinamisko veiktspēju ir sekojošas prasības: ]) // CHANGE ! - Sistēmai ir jānodrošina, ka 95% no dienā veiktajiem pieprasījumiem tiek izpildīti uz servera ne ilgāk kā 3 sekundēs un 95% no dienā veiktam darbībām spēles procesā jāizpildās ne ilgāk kā 4 sekundēs. - Darbspējas laiks ir vismaz 99% no visa laika. === Atribūti ==== Izmantojamība #indent-par([ Uz sistēmas izmantojamību ir sekojošas prasības: ]) - 90% jaunu lietotāju jāspēj lietot visas tiem pieejamās funkcijas bez palīdzības. - Sistēmai jāatbalsta reaģējošs noformējums -- jāpielāgojas dažādiem ekrānu izmēriem. - Saskarnēm jābūt adaptētām gan priekš ainavas, gan portreta orientācijas. - Teksta fonta izmēram datoru ekrāniem jābūt vismaz 14 pikseļiem, labas salasāmības nodrošināšanai. - Visām funkcijām palīdzības ziņojumi pieejami angļu un latviešu valodā. - Sistēmai ir jānodrošina, ka lietotājam pirms datu dzēšanas tiek pieprasīts darbību apstiprināt. - Izveidota piekļuves programmsaskarnes (API) integrācija ar ārējiem pakalpojumiem: maksājumu apstrādātāja un mākoņa balstīts e-pasta pakalpojumu sniedzējs. - Lapas kodējumā jāizmanto funkcijas un tehnoloģijas, kas tiek atbalstītas visās izplatītajās tīmekļa pārlūkprogrammās, nodrošinot piekļuvi sistēmai no dažādām operētājsistēmām. ==== Mērogojamība #indent-par([ Sistēmai jābūt paredzētai gan vertikālai, gan horizontālai mērogošanai. Inkrementālai slodzes izmaiņai ir pielietojama vertikāla mērogošana. Savukārt, kardinālai slodzes izmaiņai ir pielietojama horizontālā mērogošana. Horizontālās mērogošanas vienkāršošanai funkcionalitāte tiks sadalījuma pakalpojumu komponentēs. ]) ==== Drošība #indent-par([ Sistēmas drošības atribūti ir kategorizēti sarakstā: ]) - Autentifikācija: - Paroles tiek glabātas šifrētā formātā, pirms šifrēšanas, tām pievieno sāli. - Sāls tiek saglabāts teksta formātā pie lietotāja ieraksta. - Paroles atiestatīšanai tiek izmantots marķieris ar derīguma termiņu, ģenerēts ar jaucējfunkciju. - Autorizācija: - Sistēmā ir jārealizē uz lomu bāzēta piekļuve, kas nosaka noteiktās darbības noteiktām sistēmas lietotāju grupām. - Autorizācijas pārbaude gan priekšgala saskarnē, gan aizmugursistēmā. - Datu aizsardzība: - Paroles, maksājuma informācijas un citu ierobežotas piekļuves datu šifrēšana, tos glabājot un sūtot. - Sistēmai nav jāglabā dati, kas nav nepieciešami sistēmas darbībai. - Sesiju pārvalde: - Izmanto tikai HTTP sīkdatnes. - Sesijas noildzes izmantošana. - Sesijas atpazīšana tiek realizēta, izmantojot sīkdatnes. - Ievades pārbaude un dezinficēšana: - Aizsardzība pret SQL injekcijām, komandu injekcijām un citiem injekciju veidiem. - Visu ārējo pieprasījumu dati ir validēti un sanitizēti, ja nepieciešams. - Ieviesiet pareizu validāciju visiem lietotāja ievadītajiem datiem un visiem datiem, kas saņemti no ārējām sistēmām. - Aizsardzība pret tīmekļa apdraudējumiem: - Aizsardzība pret CSRF) uzbrukumiem ar CSRF marķiera izmantošanu. - Aizsardzība pret starpvietņu-skriptošanas (XSS) uzbrukumiem. - Kļūdu apstrāde: - Kļūdu paziņojumi neatklāj ierobežotas piekļuves informāciju. - Kļūdu paziņojumi ir pielāgoti lietotāju grupai - sistēmas lietotāji, kas nepieder administratoru grupai, neredz ar sistēmas iekšējiem komponentiem saistīto informāciju, piemēram, datubāzes kļūmes. - API: - API marķieru izmantošana, izņemot publiski pieejamos API galapunktos. - API pieprasījumu ierobežojums laikā (vienam lietotājam un vienai IP adresei). - Visu API pieprasījumu ievades validācija un sanitizēšana, ja nepieciešams. - Datņu augšuplādēšana: - Datnes, kas tiek augšuplādētas, tiek analizētas pret ļaunatūru pirms uzglabāšanas. - Datņu lielums un datu tips tiek validēts. - Rezerves kopēšana: - Rezerves kopijas izveidošanai jānotiek noteiktā laika periodā automātiski lokālā glabātuvē. - Automatizēta procedūra sistēmas datu atjaunošanai, datu zaudēšanas vai bojājumu gadījumā. - Darbību žurnāls: - Darbību žurnāla uzturēšana. - Darbību žurnāls nesatur ierobežotas piekļuves informāciju. - Darbību žurnāla rezerves kopēšana atsevišķi no pamata rezerves kopijām. ==== Uzturamība #indent-par([ Pret sistēmas izstrādājamo programmatūras uzturamību tiek izvirzītas sekojošās prasības: ]) // - Ciklomātiskā sarežģītība nepārsniedz 10. - API dokumentācijas pārklājumam jābūt vismaz 80%. - Koda testēšanas pārklājumam jābūt vismaz 70%. // - Moduļu fan-out metriks (ārējo moduļu izsaukuma izskaušanas skaits šī moduļa ietvaros) nepārniedz 7. // - Moduļu fan-out metriks (ārējo moduļu izsaukuma skaits ārpus šī moduļa ietvariem) jābūt nepārniedz 11. - Programmatūrā ir realizēta automātiska vairs nevajadzīgo datu izdzēšana diska vietas atbrīvošanai, piemēram, darbības spēlēs, kas notikušas pirms 840 stundām (5 nedēļām). ==== Pārnesamība #indent-par([ Sistēmas programmatūrā ir jārealizē migrācijas skripti, kas nodrošina strukturētu datu glabāšanu pārnešanas laikā, datu dublēšanu un ģenerē kontrolsummas datu integritātei. Pēc sistēmas migrācijas ir jābūt realizētiem datu pārbaudes skriptiem, datu integritātes pārbaudei. ]) === Projekta ierobežojumi ==== Intelektuālā īpašuma tiesības #indent-par([ Projektā jāievēro autortiesību un preču zīmju likumi. Lai izvairītos no juridiskām problēmām, ir jāsaņem atbilstošas atļaujas un licences par spēļu aktīviem (assets). ]) /* ==== Atbilstība standartiem #indent-par([ Šajā sadaļā ir izklāstīti galvenie standarti, kā prasībām sistēmai ir jāatbilst, lai nodrošinātu robustumu, uzticamību un lietotāju tiesību un cerību ievērošanu. ]) ===== Datu privātuma atbilstība #indent-par([ Sistēmai ir jāatbilst datu aizsardzības noteikumiem, tostarp vispārīgajai datu aizsardzības regulai (GDPR - General Data Protection Regulation). Ir būtiski noteikt visaptverošu datu apstrādes praksi, lai nodrošinātu lietotāju datu konfidencialitāti un drošību. ]) ===== Pieejamības standarti #indent-par([ Lai nodrošinātu vienlīdzīgu piekļuvi visiem lietotājiem, sistēmai jāatbilst tīmekļa satura pieejamības vadlīnijām (WCAG - Web Content Accessibility Guidelines) attiecībā uz tīmekļa pieejamību. Jāapsver lokalizācijas un iekļaušanas iespējas, lai pielāgotos dažādām auditorijām. ]) ===== Drošības standarti #indent-par([ Jāievieš stingri drošības pasākumi, ievērojot nozares paraugpraksi, piemēram, atvērto lietojumprogrammu drošības projektu visā pasaulē (OWASP - Open Worldwide Application Security Project), lai pasargātu no bieži sastopamām tīmekļa ievainojamībām. Datu aizsardzībai jāizmanto šifrēšanas protokoli. ]) */ ==== Aparatūras ierobežojumi ===== Atbalstītās ierīces #indent-par([ Sistēmai jābūt saderīgai ar dažādām ierīcēm, tostarp galddatoriem, klēpjdatoriem, viedtālruņiem un planšetdatoriem. Lai nodrošinātu netraucētu spēlēšanu, jānosaka minimālās aparatūras prasības. ]) ===== Serveris un mitināšana #indent-par([ Uz servera, kurā tiek mitināta sistēma, jābūt pieejamam Docker programmatūras atbalstam, lai standartizētu programmatūras izvietošanu ražošanas vidē un ražošanas vides simulēšanai un atvieglotai tehnoloģiju versiju sinhronizācijai ar izstrādes vidi. ]) === Ārējās saskarnes prasības ==== Lietotāja saskarne #indent-par([ Sistēmas "Mafija" vietne piedāvā atbalstu plašam spektram ekrāna formātu un izmēriem, nodrošinot elastīgu un reaktīvu dizainu, kas pielāgojas lietotāja ierīces un ekrāna izmēram. Tas ietver, bet nav ierobežots ar sekojošiem prasītajiem ekrāna formātiem un attiecībām: ]) - Atbalstāmās ekrāna attiecības (platums:augstums): 16:9; 4:3; 1:1; 3:2; 21:9; - Atbalstāmie ekrānu izmēri (Mobilās ierīces): - Mazie mobilie ekrāni (maksimāli 360 pikseļu plati): Piemēram, iPhone 5 un līdzīgi. - Parastie mobilie ekrāni (maksimāli 414 pikseļu plati): Piemēram, iPhone 6/7/8 un daudzi Android telefoni. - Plašie mobilie ekrāni (maksimāli 768 pikseļu plati): Piemēram, daži planšetdatori un lieli mobilo ierīču ekrāni. - Atbalstāmie ekrānu izmēri (Planšetdatori): - Mazie planšetdatoru ekrāni (maksimāli 768 pikseļu plats): Piemēram, 7 collu planšetdatori. - Parastie planšetdatoru ekrāni (maksimāli 1024 pikseļu plats): Piemēram, 10 collu planšetdatori. - Atbalstāmie ekrānu izmēri (Datori): - Mazie datoru ekrāni (maksimāli 1280 pikseļu plats): Piemēram, daži nelieli datoru ekrāni. - Parastie datoru ekrāni (maksimāli 1440 pikseļu plats): Parastie datoru ekrāni ar vidēju izšķirtspēju. - Lielie datoru ekrāni (maksimāli 1920 pikseļu plats): Plaši lietoti augstas izšķirtspējas datoru ekrāni. - Ļoti lielie datoru ekrāni (lielāki par 1920 pikseļiem): Piemēram, 4K ekrāni un daudzi datoru monitori. #indent-par([ Grafiskā izkārtojuma pielāgošanai paredzēts izmantot sekojošos ekrāna izmēra precizējumu punktus: ]) - 360px -- maziem mobilajiem ekrāniem. - 768px -- plašiem mobilajiem ekrāniem un maziem planšetdatoru ekrāniem. - 1024px -- parastiem planšetdatoriem un maziem datoru ekrāniem. - 1440px -- lieliem datoru ekrāniem. - 1920px -- ļoti lieliem un augstas izšķirtspējas datoru ekrāniem. #indent-par([ Lietotāja saskarne piedāvā pielāgotu izkārtojumu un saturu, kas pilnībā atbilst konkrētam ekrāna formātam un izmēram. Teksta izvietojums ir optimizēts atbilstoši ekrāna izmēram, izmantojot precīzi pielāgojamu fonta izmēru un stilu, lai nodrošinātu ērtu lasīšanu. Lietotne var iekļaut teksta formatējuma klāstā, bet nav ierobežota ar aprakstītiem teksta elementu noformējumiem (skat. @tbl:font-size tab.). ]) #pagebreak(weak: true) #figure( caption: "Teksta elementu noformējuma specifikācija", kind: table, tablex( columns: 5, [*Teksta elementa klase*], [*Izmērs*], [*Svars*], [*Stils*], [*Cits*], [H1:\ Galvenais virsraksts], "vismaz 64pt", "Regulārs (parasts)", "Regulārs", "Var izmantot atšķirīgu krāsu, lai izceltu no citiem virsrakstiem.", [H2:\ Apakšvirsraksti], "vismaz 24pt", "Regulārs (parasts)", "Regulārs", "Var izmantot atšķirīgu krāsu, lai izceltu no pamata teksta.", [H3:\ Sekundārie virsraksti], "36pt", "Regulārs (parasts)", "Regulārs", "Var izmantot atšķirīgu krāsu.", [H4:\ Apakšvirsraksti], "18pt", "Medium (vidējs treknraksts)", "Regulārs", "Izcelt ar atšķirīgu krāsu.", "H5", "16pt", "Regulārs (parasts)", "Regulārs", "", "H6", "14pt", "Regulārs (parasts)", "Regulārs", "", "Pamatteksts", "12pt", "Regulārs (parasts)", "Regulārs", "", "Saturteksts", "14pt", "Regulārs (parasts)", "Regulārs", "Var izmantot slīprakstu, lai akcentētu citātus vai īpaši teksta fragmentus.", "Citāti un īpaši akcentēti teksti", "16pt", "Regulārs (parasts)", "Italics (slīpraksts)", "Lai iezīmētu citātus vai īpaši akcentētu tekstus var izmantot slīprakstu.", "Sarunas un komentāri", "18pt", "Regulārs (parasts)", "Regulārs", "Var izmantot atšķirīgu krāsu, lai nošķirtu saturiskās daļas", "Standarta saites", "12pt", "Regulārs (parasts)", "Regulārs", "Izmantot krāsas un pasvītrojumu, lai izceltu saites.", "Apmeklētās un neapmeklētās saites", "12pt", "Regulārs (parasts)", "Regulārs", "Izmantot krāsas un pasvītrojumu, lai atšķirtu apmeklētās un neapmeklētās saites.", "Numurētās un nenumurētās saraksta vienības", "16pt", "Regulārs (parasts)", "Regulārs", "Izmantot atzīmes (bullets) vai numurēšanas stilu.", "Atzīmes (bullets)", "12pt", "Regulārs (parasts)", "Regulārs", "", "Tabulu teksts un tabulu virsraksti", "14pt", "Regulārs (parasts)", "Regulārs", "", "Ievades lauki", "16pt", "Regulārs (parasts)", "Regulārs", "", "Izvēles rūtiņas un radio pogas", "12pt", "Regulārs (parasts)", "Regulārs", "Var izmantot atšķirīgu krāsu.", "Ievades lauku kļūdu ziņojumi", "10pt", "Regulārs (parasts)", "Regulārs", "", "Galvenās navigācijas saites", "18pt", "Bold (treknraksts)", "Regulārs", "", "Sānu paneļa navigācijas saites", "10pt", "Regulārs (parasts)", "Regulārs", "", ), ) <font-size> // ==== Apratūras saskarne // ==== Programmatūras saskarne ==== Sakaru saskarne #indent-par([ Visas iekšējās komponentes (pakalpojumi) komunicē, izmantojot HTTPS (drošu HTTP). Komunikācija ar ārējo pakalpojumu sniedzēju API notiek, izmantojot HTTPS. ]) #pagebreak(weak: true) = Programmatūras projektējuma apraksts == Datu bāzes projektējums /* Loģiskais un fiziskais DB modelis + apraksta pāreju no konceptuālā uz loģisko un pēc tam uz fizisko (ja sistēma vienkārša, loģisko var izlaist) */ === Datu bāzes loģiskais ER modelis #indent-par([ Loģiskajā modelī datubāze tika normalizēta uz BCNF, tāpēc bija nepieciešams izveidot atsevišķas tabulas katram daudzvērtību atribūtam, kā parādīts @fig:logical-erd attēlā. ]) #figure( caption: "Datu bāzes loģiskais ER modelis", image("img/erd/LogiskaisERDModelis.svg"), ) <logical-erd> === Datu bāzes fiziskais ER modelis #indent-par([ Fiziskajā modelī, salīdzinot ar loģisko modeli, nav redzamas pamanāmas izmaiņas, kā parādīts @fig:logical-erd un @fig:physical-erd attēlā. ]) #figure( caption: "Datu bāzes fiziskais ER modelis", image("img/erd/FiziskaisERDModelis.png"), ) <physical-erd> === Datu bāzes tabulu apraksts #indent-par([ Datubāzes tabulu lauku, datu tipi, lauka atribūti -- obligātums, noklusētās vērtības, primārā atslēga, unikalitāte -- ir aprakstītas atsevišķās tabulās (skat. @tbl:entity-role-action tab., @tbl:entity-image tab., @tbl:entity-session tab., @tbl:entity-password-recovery tab., @tbl:entity-email-confirmation tab., @tbl:entity-game-role tab., @tbl:entity-account-status tab., @tbl:entity-room-status tab., @tbl:entity-player-status tab., @tbl:entity-user tab., @tbl:entity-game-setup tab., @tbl:entity-room tab., @tbl:entity-game-event tab., @tbl:entity-player tab., @tbl:entity-message tab. @tbl:entity-player-action tab. @tbl:entity-player-causes-event tab. @tbl:entity-player-influences-event tab. @tbl:entity-game-setup-roles tab. @tbl:entity-event-actions tab. @tbl:entity-game-role-events tab. @tbl:entity-answer tab.) Visām tabulām `VARCHAR` un `TEXT` laukiem tiek lietot UTF8 kodējums. ]) Saliktā atslēga tiek izmantota kā primārā atslēga daudziem pret daudziem entitātem (skat. @tbl:entity-player-action tab. @tbl:entity-player-causes-event tab. @tbl:entity-player-influences-event tab. @tbl:entity-game-setup-roles tab. @tbl:entity-event-actions tab. @tbl:entity-game-role-events tab.) #entity-table( caption: "LomasDarbiba", "nosaukums", "varchar(255)", "unique, not null", "<NAME>ības nosaukums", "apraksts", "text", "default '', not null", "Lomas darbības apraksts", ) <entity-role-action> #entity-table( caption: "Attels", "datnes_adrese", "varchar(255)", "unique, not null", "Saglabātā attēla adrese operētājsistēmā", "pievienosanas_laiks", "timestamp", "default current_timestamp, not null", "Laiks, kad tika izveidots/saglabāts dotais attēls datubāzē", ) <entity-image> #entity-table( caption: "Sesija", "markieris", "varchar(255)", "unique, not null", "Ģenerēts marķieris lietotāja sesijas", "deriguma_termins", "timestamp", "not null", "Laiks, līdz kuram sesija ir aktīva", ) <entity-session> #entity-table( caption: "ParolesAtjaunosana", "markieris", "varchar(255)", "unique, not null", "Ģenerēts marķieris paroles atjaunošanai", "deriguma_termins", "timestamp", "not null", "Laiks, līdz kuram paroles atjaunošana ir iespējama", ) <entity-password-recovery> #entity-table( caption: "EpastaApstiprinajums", "markieris", "varchar(255)", "unique, not null", "Ģenerēts marķieris e-pasta lietotāja apstiprināšanai", "deriguma_termins", "timestamp", "not null", "Laiks, līdz kuram e-pasta apstiprināšana ir iespējama", ) <entity-email-confirmation> #entity-table( caption: "SpelesLoma", "nosaukums", "varchar(255)", "unique, not null", "<NAME>", "apraksts", "text", "default '', not null", "<NAME>aksts", "ir_pamata", "bool", "default false, not null", "Vai loma ir spēles pamatā vai lietotāju izveidots?", "ir_mafija", "bool", "default false, not null", "Vai loma ir mafija?", "attels", "int8", "", [Lomas attēls, `FOREING KEY`, uz #link(<entity-image>)[Attels] tabulas id kolonnu], "autors", "int8", "", [Lomas izveides autors, `FOREING KEY`, uz #link(<entity-user>)[Lietotajs] tabulas id kolonnu], ) <entity-game-role> #entity-table( caption: "KontaStavoklis", "birka", "varchar(255)", "unique, not null", "Konta stāvokļa apraksts", ) <entity-account-status> #entity-table( caption: "IstabasStavoklis", "birka", "varchar(255)", "unique, not null", "Istabas stāvokļa apraksts", ) <entity-room-status> #entity-table( caption: "SpeletajaStavoklis", "birka", "varchar(255)", "unique, not null", "Speletaja stāvokļa apraksts", ) <entity-player-status> #entity-table( caption: "Lietotajs", "segvards", "varchar(255)", "unique, not null", "Lietotājvārds", "epasts", "varchar(255)", "unique, not null", "Lietotāja e-pasts", "parole", "varchar(255)", "not null", "Šifrēšanas algoritms, sāls un šifrēta lietotāja parole", "vards", "varchar(255)", "default '', not null", "Lietotāja vārds", "uzvards", "varchar(255)", "default '', not null", "Lietotāja uzvārds", "dzimsanas_datums", "date", "", "Lietotāja dzimšanas datums", "bio_info", "text", "default ''", "Lietotāja apraksts par sevi", "izveidosanas_laiks", "timestamp", "default current_timestamp, not null", "Laiks, kad tika izveidots/saglabāts dotais lietotājs datubāzē", "ir_apstiprinats_ epasts", "bool", "default false, not null", "Vai lietoājs ir apsiprinājis savu e-pastu?", "stripe_id", "varchar(50)", "unique", [Unikālais lietotāja identifikators, kas tiek iegūts no maksājuma apstrādātāja klienta -- #link("https://stripe.com")[Stripe]], "ir_administrators", "bool", "default false, not null", [Vai lietotājam ir administratora privilēģijas?], "attels", "int8", "", [Lietotāja profila attēls, `FOREING KEY` uz #link(<entity-image>)[Attels] tabulas id kolonnu], "konta_stavoklis", "int8", "not null", [Lietotāja konta stāvoklis, `FOREING KEY` uz #link(<entity-account-status>)[KontaStavoklis] tabulas id kolonnu], "sesija", "int8", "unique", [Lietotāja sesija, `FOREING KEY` uz #link(<entity-session>)[Sesija] tabulas id kolonnu], "epasta_ apstiprinajums", "int8", "unique", [Lietotāja e-pasta apstiprinājums, `FOREING KEY` uz #link(<entity-email-confirmation>)[EpastaApstiprinajums] tabulas id kolonnu], "paroles_ atjaunosana", "int8", "unique", [Lietotāja paroles atjaunošana, `FOREING KEY` uz #link(<entity-password-recovery>)[ParolesAtjaunojana] tabulas id kolonnu], ) <entity-user> #entity-table( caption: "SpelesUzstadijums", "nosaukums", "varchar(255)", "unique, not null", "Uzstādījuma nosaukums", "apraksts", "text", "default '', not null", "Uzstādījuma apraksts", "ir_pamata", "bool", "default false, not null", "Vai spēles uzstādījums ir spēles pamatā vai lietotāju izveidots", "izveidosanas_laiks", "timestamp", "default current_timestamp, not null", "Laiks, kad dotais uzstādījums tika izveidots/saglabāts datubāzē", "autors", "int8", "not null", [Uzstādījuma autors, `FOREING KEY` uz #link(<entity-user>)[Lietotajs] tabulas id kolonnu], ) <entity-game-setup> #entity-table( caption: "Istaba", "nosaukums", "varchar(255)", "unique, not null", "Istabas Nosaukums", "speles_saksanas_ laiks", "timestamp", "", "Laiks, kad spēle sākas", "speles_beigsanas_ laiks", "timestamp", "", "Laiks, kad spēle beidzas", "stavoklis", "int8", "not null", [Pašreizējais spēles stāvoklis, `FOREING KEY` uz #link(<entity-room-status>)[IstabasStavoklis] tabulas id kolonnu], "piekluves_kods", "char(6)", "unique, not null", "Unikāls istabas piekļuves kods, 6 lielie burtcipari", "izveidosanas_laiks", "timestamp", "default current_timestamp, not null", "Laiks, kad dotā spēles istaba tika izveidota/saglabāta datubāzē", "speles_uzstadijums", "int8", "not null", [Spēles uzstādījumi, kurus izmanto dotā istaba, `FOREING KEY` uz #link(<entity-game-setup>)[SpelesUzstādījums] tabulas id kolonnu], ) <entity-room> #entity-table( caption: "SpelesNotikums", "nosaukums", "varchar(255)", "unique, not null", "Notikuma nosaukums", "nakts_pk", "int2", "default 0, not null, check (nakts_pk >= 0)", "Spēles nakts pēc kārtas", "ir_redzams", "bool", "default false, not null", "Vai notikums ir redzams spēlētājiem procesa laikā?", "izveidosanas_laiks", "timestamp", "default current_timestamp, not null", "Laiks, kad dotais spēles notikums tika izveidots/saglabāts datubāzē", "taimeris", "interval", "", "Laika intervāls taimera notikumiem spēles gaitā", "lomas_darbiba", "int8", "not null", [Lomas darbība, `FOREING KEY` uz #link(<entity-game-role>)[LomasDarbiba] tabulas id kolonnu], ) <entity-game-event> #entity-table( caption: "Speletajs", "nosaukums", "varchar(255)", "unique, not null", "Notikuma nosaukums", "ir_noslepkavots", "bool", "default false, not null", "Vai dotais spēlētājs ir noslepkavots?", "ir_izbalsots", "bool", "default false, not null", "Vai dotais spēlētājs ir izbalsots?", "stavoklis", "int8", "not null", [Spēlētāja stāvoklis, `FOREING KEY` uz #link(<entity-player-status>)[SpeletajaStavoklis] tabulas id kolonnu], "istaba", "int8", "", [Istaba, kurā spēlē dotais spēlētājs, `FOREING KEY` uz #link(<entity-room>)[Istaba] tabulas id kolonnu], "speles_loma", "int8", "not null", [Loma, kuru spēlē dotais spēlētājs, `FOREING KEY` uz #link(<entity-game-role>)[SpelesLoma] tabulas id kolonnu], ) <entity-player> #entity-table( caption: "Sarakste", "teksts", "text", "not null", "Sarakstes teksts", "if_mafijas_sarakste", "bool", "default false, not null", "Vai sarakstes sūtītājs ir mafija?", "ir_izmainita", "bool", "default false, not null", "Vai sarakstes saturs ir izmainīts?", "autors", "int8", "not null", [Sarakstes sūtītājs, `FOREING KEY` uz #link(<entity-player>)[Speletajs] tabulas id kolonnu], ) <entity-message> #entity-table( caption: "SpeletajaDarbibas", id: ( "speletajs", "int8", "primary key, not null", [Spēlētājs, `FOREING KEY` uz #link(<entity-player>)[Speletajs] tabulas id kolonnu], ), "lomas_darbiba", "int8", "primary key, not null", [Lomas darbība, `FOREING KEY` uz #link(<entity-game-role>)[LomasDarbiba] tabulas id kolonnu], "vai_pilda", "bool", "default true, not null", [Vai spēlētājs ir darbības izraisītājs?], ) <entity-player-action> #entity-table( caption: "SpeletajsIzraisaNotikumu", id: ( "speletajs", "int8", "primary key, not null", [Spēlētājs, `FOREING KEY` uz #link(<entity-player>)[Speletajs] tabulas id kolonnu], ), "speles_notikums", "int8", "primary key, not null", [Spēles notikums, `FOREING KEY` uz #link(<entity-game-event>)[SpelesNotikums] tabulas id kolonnu], ) <entity-player-causes-event> #pagebreak(weak: true) #entity-table( caption: "SpeletajsIetekmeNotikumu", id: ( "speletajs", "int8", "primary key, not null", [Spēlētājs, `FOREING KEY` uz #link(<entity-player>)[Speletajs] tabulas id kolonnu], ), "speles_notikums", "int8", "primary key, not null", [Spēles notikums, `FOREING KEY` uz #link(<entity-game-event>)[SpelesNotikums] tabulas id kolonnu], ) <entity-player-influences-event> #entity-table( caption: "SpelesUzstatijumuLomas", id: ( "speles_uzstadijums", "int8", "primary key, not null", [Spēles uzstādījums, `FOREING KEY` uz #link(<entity-game-setup>)[SpelesUzstadijums] tabulas id kolonnu], ), "speles_loma", "int8", "primary key, not null", [Spēles loma, `FOREING KEY` uz #link(<entity-game-role>)[SpelesLoma] tabulas id kolonnu], "skaits", "int2", "default 1, not null, check (skaits >= 1)", "Spēlē izmantojamo lomu skaits", ) <entity-game-setup-roles> #entity-table( caption: "NotikumsAizliedzAtlaujDarbibu", id: ( "lomas_darbiba", "int8", "primary key, not null", [Lomas darbība, `FOREING KEY` uz #link(<entity-role-action>)[LomasDarbiba] tabulas id kolonnu], ), "speles_notikums", "int8", "primary key, not null", [Spēles notikums, `FOREING KEY` uz #link(<entity-game-event>)[SpelesNotikums] tabulas id kolonnu], "ir_atlauts", "bool", "default true, not null", [Apzīmē, vai notikums atļauj vai aizliedz darbību], ) <entity-event-actions> #pagebreak(weak: true) #entity-table( caption: "SpelesLomasDarbiba", id: ( "speles_loma", "int8", "primary key, not null", [Spēles loma, `FOREING KEY` uz #link(<entity-game-role>)[SpelesLoma] tabulas id kolonnu], ), "lomas_darbiba", "int8", "primary key, not null", [Lomas darbība, `FOREING KEY` uz #link(<entity-role-action>)[LomasDarbiba] tabulas id kolonnu], ) <entity-game-role-events> #entity-table( caption: "Atbilde", "raksta", "int8", "not null", [Lietotājs, kas atbild uz saraksti, `FORERING KEY` uz #link(<entity-message>)[Sarakste] tabulas id kolonnu], "atbild", "int8", "not null", [Lietotājs, uz kura saraksti atbild, `FORERING KEY` uz #link(<entity-message>)[Sarakste] tabulas id kolonnu], ) <entity-answer> == Daļējs funkciju projektējums #indent-par([ Spēles notikumu izveidošanas algoritma aktivitātes diagramma (@fig:PD02-1 att.) apraksta spēles notikumu izveidošanu, ko veic sistēma. Ja fāzes taimeris nav aktīvs, tiek izveidoti nepieciešamie spēles notikumi nākamai fāzei, tiek mainīti spēlētāju stāvokļi. Dažu fāžu ietvaros tiek pārbaudīti spēles beigu nosacījumi, kuriem izpildoties, spēles istabas stāvoklis ir mainīts uz pabeigtu spēli. ]) Diagrammā ir iekļauta apakšaktivitāte spēlētāju stāvokļa izmaiņai atkarībā no darbībām, kas ir aprakstīta atsevišķi (skat. @fig:PD02-2 att.) Tajā tiek apstrādātas darbības un aprēķināta darbību ietekme uz spēles stāvokli, izveidojot jaunus notikumus. #figure( caption: "Spēles notikumu izveidošanas algoritms", image("img/uml/EventCreationActivityDiagram-01.svg", height: 80%), ) <PD02-1> #figure( caption: "Izmaiņas spēlētāju stāvoklī (apakšaktivitāte)", image("img/uml/EventCreationActivityDiagram-02.svg"), ) <PD02-2> #pagebreak(weak: true) #indent-par([ Lietotāja spēles darbības veikšanas funkcijas projektējuma peldceliņu diagramma (@fig:PD01 att.) apraksta spēlētāja darbības izveidošanas procesu. Funkcija ietver darbības korektuma pārbaudi, spēles istabas un spēlētāja saistību, darbības autorizēšanu spēles ietvaros un darbības ieraksta izveidošanu. ]) #figure( caption: "Spēles darbības peldceliņu diagramma", image("img/uml/GameActionSwimlaneChart.svg", height: 80%), ) <PD01> #indent-par([ Iespējamie spēles istabas stāvokļi un to pārejas ir aprakstīti stāvokļu pārejas diagrammā (skat. @fig:PD03 att.). ]) #figure( caption: "Spēles istabas stāvokļu diagramma", image("img/uml/GameRoomStateDiagram.svg"), ) <PD03> #pagebreak(weak: true) #indent-par([ Abonementa pieteikuma process ir aprakstīts secību diagrammā (skat. @fig:PD04 att.). Process iekļauj aktīva abonementa pārbaudi, klienta konta izveidošanu, ja tāds neeksistē, apmaksas sesijas izveidi un apstiprinājumu. ]) #figure( caption: "Abonementa pieteikuma secību diagramma", image("img/uml/SubscriptionFunctionSequenceDiagram.svg"), ) <PD04> #pagebreak(weak: true) #indent-par([ Sistēmas izvietojuma diagramma (skat. @fig:PD05 att.) apraksta sistēmas izvietojuma -- programmatūras izvietojumu ierīcēs, uz kuras tiks darbināta sistēmas programmatūra. ]) #figure( caption: "Sistēmas izvietojuma diagramma", image("img/uml/ManifiestationDiagram.svg"), ) <PD05> /* Apraksta svarīgākās, sarežģītākās funkcijas vai sistēmas darbības aspektus; obligāti jālieto vismaz 4 dažādi diagrammu veidi, izņemot DPD un lietošanas piemēru (use case) diagrammas */ == Daļējs lietotāju saskarņu projektējums /* 5-7 lietotāja saskarnes un to apraksts */ === Navigācija #indent-par([ Navigācijas shēma visām lietotāju grupām ir attēlota ekrānskatu plūsmas diagrammā (skat. @fig:view-flow-diagram att.) Diagrammā ir apvienoti visi skati, kas ieskaita gan parasta lietotāja pusi, gan administratora pusi. Diagrammā redzami visi pieejamie skati katram lietotāja veidam. Katru sadalīto skatu zonu manto lietotājs ar lielākām tiesībām par otru. Administratoram ir pieejami visi skati, maksas lietotājiem ir pieejama apakškopa no ekrānskatiem, reģistrētam lietotājam un nereģistrētam lietotājiem analoģiski ir pieejamas apakškopas. Šī hierarhija ir redzama diagrammas kreisā apakšējā stūrī. Pastāv ekrānskati, kas pieejami tikai neautentificētam lietotājam un nav pieejami nevienam citam. Tāpēc ir izdalīta atsevišķa grupa, kas netiek iekļauta citās grupās. ]) #figure( caption: "Ekrānskatu plūsmas diagramma", image("img/EkrānskatuPlūsmasDiagramma.svg"), ) <view-flow-diagram> #indent-par([ Saskarnes projektējuma ekrānskatos izmantotās funkcijas ir apkopotas @tbl:interface-views tabulā. ]) // For self check (sorta) and traceability #figure( caption: "Funkciju atbilstība ekrānskatiem", kind: table, tablex( columns: 3, /* --- header --- */ [*Ekrānskata nosaukums*], [*Ekrānskata identifikators*], [*Atbilstošās funkcijas*], /* -------------- */ [Galvenā lapa], [#link(<SS01>)[SS01]], [Statiska lapa#footnote[Statiskas lapas saturs mainās reti, tās saturs tiek atjaunots manuāli.]], [Pieteikšanās], [SS02], [#link(<AMF06>)[AMF06]], [Atkārtotā apstiprinājuma pieteikšana], [SS03], [#link(<AMF02>)[AMF02]], [Paroles atjaunošanas pieteikums], [SS04], [#link(<AMF03>)[AMF03]], [Paroles atjaunošana], [SS05], [#link(<AMF04>)[AMF04]], [E-pasta apstiprināšana], [SS06], [#link(<AMF07>)[AMF07]], [Reģistrācija], [#link(<SS07>)[SS07]], [#link(<AMF01>)[AMF01]], [Spēles notikumu pārskats], [SS08], [#link(<SGMF03>)[SGMF03]], [Spēļu vēstures pārskats], [SS09], [#link(<SIMF08>)[SIMF08]], [Spēles istabu pārskats], [SS10], [#link(<SIMF01>)[SIMF01], #link(<SIMF03>)[SIMF03], #link(<AMF06>)[AMF06], #link(<AMF04>)[AMF04]], [Atteikšanās], [SS11], [#link(<AMF05>)[AMF05]], [Lietotāju pārskats], [SS12], [#link(<LKMF01>)[LKMF01]], [Konta detaļas], [SS13], [#link(<LKMF02>)[LKMF02]], [Konta rediģēšana], [SS14], [#link(<LKMF04>)[LKMF04]], [Konta dzēšana], [SS15], [#link(<LKMF05>)[LKMF05]], [Abonementa pieteikšana], [SS16], [#link(<MAMF01>)[MAMF01]], [Abonementu pārskats], [SS17], [#link(<MAMF02>)[MAMF02]], [Abonementa atcelšana], [SS18], [#link(<MAMF03>)[MAMF03]], [Abonementu plānu pārskats], [SS19], [#link(<MAMF04>)[MAMF04]], [Lomas detaļas], [SS20], [#link(<SLMF01>)[SLMF01]], [Lomu pārskats], [SS21], [#link(<SLMF02>)[SLMF02]], [Lomas darbību pārskats], [SS22], [#link(<SLMF03>)[SLMF03]], [Lomas izveidošana], [SS23], [#link(<SLMF04>)[SLMF04]], [Lomas rediģēšana], [SS24], [#link(<SLMF05>)[SLMF05]], [Lomas dzēšana], [SS25], [#link(<SLMF06>)[SLMF06]], [Spēles uzstādījumu pārskats], [#link(<SS26>)[SS26]], [#link(<SUMF01>)[SUMF01]], [Spēles uzstādījuma lomu pārskats], [SS27], [#link(<SUMF02>)[SUMF02]], [Spēles uzstādījuma izveidošana], [SS28], [#link(<SUMF03>)[SUMF03]], [Spēles uzstādījuma rediģēšana], [SS29], [#link(<SUMF04>)[SUMF04]], [Spēles uzstādījuma dzēšana], [SS30], [#link(<SUMF05>)[SUMF05]], [Spēles istabas izveidošana], [SS31], [#link(<SIMF04>)[SIMF04]], [Pievienošanās spēlei], [SS32], [#link(<SIMF02>)[SIMF02]], [Pirmsspēles vestibils], [#link(<SS33>)[SS33]], [#link(<SIMF07>)[SIMF07], #link(<SIMF05>)[SIMF05], #link(<SUMF02>)[SUMF02], #link(<SIMF09>)[SIMF09], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], [Spēles sākums], [SS34], [#link(<SGMF04>)[SGMF04], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], [Spēles skats], [#link(<SS35>)[SS35]], [#link(<SGMF04>)[SGMF04], #link(<SLMF03>)[SMLF03], #link(<SLMF01>)[SLMF01], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], [Spēles darbība], [#link(<SS36>)[SS36]], [#link(<SGMF01>)[SGMF01], #link(<SLMF03>)[SLMF03], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], [Spēles fāzes maiņa], [#link(<SS37>)[SS37]], [#link(<SGMF04>)[SGMF04], #link(<SGMF03>)[SGMF03], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], // [Atslēgšanās no spēles istabas], [SS38], [#link(<SIMF03>)[SIMF03]], [Spēles beigas], [SS38], [#link(<SGMF04>)[SGMF04], #link(<SGMF03>)[SGMF03], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], // [Spēles uzstādījuma detaļas], [SS40], [#link(<SUMF01>)[SUMF02]], [Spēles notikumu pārskats], [#link(<SS39>)[SS39]], [#link(<SGMF04>)[SGMF04], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], [Spēles novērošana], [SS40], [#link(<SGMF04>)[SGMF04], #link(<SIMF07>)[SIMF07], #link(<TMF01>)[TMF01], #link(<TMF02>)[TMF02], #link(<TMF03>)[TMF03], #link(<TMF04>)[TMF04]], [Spēles iestatījumi], [SS41], [Lietotāju saskarnes iestatījumi], [Lietotāja konta bloķēšana], [SS42], [#link(<LKMF03>)[LKMF03]], [Spēlētāja izslēgšana], [SS43], [#link(<SIMF07>)[SIMF07], #link(<SIMF06>)[SIMF06]], ), ) <interface-views> #pagebreak(weak: true) === Ekrānskati // UPDATED: 2024-01-18 17:37 #indent-par([ Galvenās lapas ekrānskats (SS01; @fig:SS01 att.) parāda informāciju nereģistrētiem lietotājiem, kas ietver statistiku par mājaslapu un saiti uz reģistrāciju vai pieteikšanos un citu aktuālu informāciju. Informācija, kas tiek parādīta, ir statiska. ]) #figure( caption: "Galvenās lapas ekrānskats", image("img/ui/desktop/landingpage.png"), ) <SS01> #pagebreak(weak: true) #indent-par([ Reģistrācijas ekrānskats (SS07; @fig:SS07 att.) satur reģistrācijas veidlapu. Jāievada reģistrācijai nepieciešamie dati. Paziņojumi par ievades datu validācijas neveiksmēm parādās pie attiecīgajiem ievades laukiem. Nospiežot reģistrācijas pogu lietotājs apstiprina mājaslapas noteikumiem un saistītām politikām. ]) #figure( caption: "Reģistrācijas ekrānskats", image("img/ui/desktop/register.png"), ) <SS07> #pagebreak(weak: true) #indent-par([ Spēles istabu pārskata ekrānskats (SS26; @fig:SS26 att.) ir pirmais ekrānskats, kurā lietotājs iekļūst, veiksmīgi piesakoties sistēmā. Tas satur pieejamās spēles istabas ar informāciju par konkrētām istabām ar meklēšanas, filtru un kārtošanas iespēju. Pieejamām spēles istabām ir pieslēgšanās poga. Skatā ir iespēja arī nokļūt uz sava reģistrētā konta pārskatu. Ekrānskats satur papildus aktuālu informāciju. Papildus informācija ir statiska, informācija par abonementa iegādi un blogs. Maksas lietotājam ir redzama istabu izveidošanas poga. ]) #figure( caption: "Spēles istabu pārskata ekrānskats", image("img/ui/desktop/available-game-room-list.png"), ) <SS26> #pagebreak(weak: true) #indent-par([ Pirmsspēles vestibila ekrānskats (SS33; @fig:SS33 att.) parāda informāciju par spēles istabu, kas ir aktuāla pirms spēle sākas. Tas iekļauj spēlētājus istabā un informāciju par spēles uzstādījumu un tajā iekļautām spēles lomām. ]) #figure( caption: "Spēles vestibila ekrānskats", image("img/ui/mobile/lobby.png", height: 80%), ) <SS33> #pagebreak(weak: true) #indent-par([ Ekrānskats "Spēles skats" (SS35; @fig:SS35 att.) parāda būtiskāko informāciju spēles procesā. Ir iespēja apskatīt visus spēlētājus, kas ir pieslēgušies spēlei. Pie katra spēlētāja ar noteiktu krāsu tiek parādīts vai spēlētājs ir dzīvs vai nē. Oranža krāsa nozīmē, ka ir dzīvs, melns -- nē. Kā arī savu lomu un lomas aprakstu, kas tika piešķirta spēlētājam, spēles sākumā, šajā skatā mediķis. Skatā ir iespēja izmantot tērzētavu, sarunājoties ar citiem spēles dalībniekiem. Pieejams arī spēles pārskats, kurā ir redzama spēles fāze, dzīvo spēlētāju skaitu un diena. No šī skata ir iespējams nokļūt uz notikumu pārskata skatu. ]) #figure( caption: "Spēles skata ekrānskats", image("img/ui/desktop/game-screen.png"), ) <SS35> #pagebreak(weak: true) #indent-par([ Spēles notikumu pārskata ekrānskats (SS39; @fig:SS39 att.) attēlo spēles notikumu pārskatu. Tas ir līdzīgs spēles skatam (SS35; @fig:SS35 att.) ar savām dažām atšķirībām. Informācija sniedz pārskatu par svarīgiem spēles notikumiem atsevišķās spēles fāzēs – naktī un dienā. Spēles laikā ir notikuši konkrēti notikumi, piemēram, kāds spēlētājs ir nogalināts vai izglābts. Notikumi ir izmantoti, lai saprastu nesenos notikumus spēlē un plānotu nākamās darbības, balstoties uz spēles gaitu un citu spēlētāju lēmumiem. ]) #figure( caption: "Spēles notikumu pārskata ekrānskats", image("img/ui/desktop/game-event-overview.png"), ) <SS39> #pagebreak(weak: true) #indent-par([ Ekrānskats "Spēles darbība" (SS36; @fig:SS36 att.) parāda darbības izvēli, noteiktajai spēlētāja lomai, šajā gadījumā mediķim, kas ietekmē nākamos spēles soļus. Šis skats parādās katrā darbību momentā naktī. Katrai noteiktajai spēlētāja lomai šis skats ir nedaudz atšķirīgs. Mafijas gadījumā parādās saraksts ar vēl dzīvajiem spēlētājiem, kur jāizvēlas viens. Iedzīvotāja gadījumā nav nevienas darbības, kas jādara, tie vienkārši sagaida nākamo dienu. ]) #figure( caption: "Spēles darbības ekrānskats", image("img/ui/desktop/game-action.png"), ) <SS36> #pagebreak(weak: true) #indent-par([ Ekrānskats "Fāzes maiņa" (SS37; @fig:SS37 att.) demonstrē fāzes maiņas momentu, atspoguļojot pāreju no dienas uz nakti vai otrādi. Ekrānā dominē grafiskais uzraksts "Trešā diena", kas simbolizē spēles iekšējo ciklu maiņu un pavada spēlētājus uz nākamo darbību sēriju. Fāzes maiņa informē spēlētājus par svarīgu spēles posmu notikumiem, šajā gadījumā par Jaunzemnieka slepkavību. ]) #figure( caption: "Fāzes maiņas ekrānskats", image("img/ui/tablet/game-phase-change.png", height: 60%), ) <SS37> #pagebreak(weak: true) #heading(numbering: none, "Izmantotā literatūra un avoti") + #hyperlink-source( "Eiropas Parlaments.", "Vispārēja datu aizsardzības regula (angl. GDPR). 2016, aprīlis.", "https://eur-lex.europa.eu/legal-content/LV/TXT/PDF/?uri=CELEX:32016R0679", datetime( year: 2023, month: 11, day: 20, ), ) + #hyperlink-source( "International standard organisation (Starptautiska standartu organizācija).", [ISO/DIS 8601-1. Data elements and interchange formats -- Information interchange -- Representation of dates and times -- Part 1: Basic rules.], "https://web.archive.org/web/20171019211402/https://www.loc.gov/standards/datetime/ISO_DIS%208601-1.pdf", datetime( year: 2023, month: 11, day: 20, ), ) + #hyperlink-source( "International standard organisation.", "ISO 4217. Currency codes. 2015.", "https://www.iso.org/iso-4217-currency-codes.html", datetime( year: 2023, month: 12, day: 16, ), ) + #hyperlink-source( "Internet Engineering Task Force (IETF).", "RFC 7519. JSON Web Token (JWT). 2015, maijs.", "https://web.archive.org/web/20171019211402/https://www.loc.gov/standards/datetime/ISO_DIS%208601-1.pdf", datetime( year: 2023, month: 11, day: 20, ), ) + #hyperlink-source( [Institūcija "Latvijas standarts".], [LVS 68:1996 "Programmatūras prasību specifikācijas ceļvedis". 1996, marts.], "", datetime( year: 2023, month: 11, day: 20, ), ) + #hyperlink-source( [Institūcija "Latvijas standarts".], [LVS 72:1996 PPS "Ieteicamā prakse programmatūras projektējuma aprakstīšanai". 1996, marts.], "", datetime( year: 2023, month: 11, day: 20, ), ) + #hyperlink-source( "QUALCOMM Incorporated.", "RFC2822. Internet Message Format (Interneta ziņojumu formāts). 2001, aprīlis.", "https://datatracker.ietf.org/doc/html/rfc2822", datetime( year: 2023, month: 11, day: 20, ), ) + #hyperlink-source( "Maksas apstrādātāja lietošanas dokumentācija.", "Stripe API Reference.", "https://stripe.com/docs/api", datetime( year: 2023, month: 12, day: 17, ), ) /*+ #hyperlink-source( "W3C.", "Web Content Accessibility Guidelines (WCAG, Tīmekļa satura pieejamības vadlīnijas) 2.1. 2023, septembris.", "https://www.w3.org/TR/WCAG21/", datetime( year: 2023, month: 11, day: 20, ), )*/ // Hyperlink example /* #hyperlink-source( "Kļaviņš, <NAME>as vāciešu un latviešu kopīgā pagātne.", "Diena, 2003, 19. marts, 15. lpp.", "http://www.historia.lv/publikacijas/piblicist/kljavins01.htm", datetime( year: 2023, month: 1, day: 2, ), ) */ #pagebreak(weak: true) #let vspace = 1fr #heading(numbering: none, outlined: false, "Dokumentārā lapa") #v(vspace) #indent-par([Praktiskais darbs programminžinierijā "Tiešsaistes spēles sistēma "Mafija"" izstrādāts LU Datorikas fakultātē.]) #v(vspace) Šī darba autori apliecina, ka darbs ir veikts patstāvīgi, un ir izmantoti tikai tajā norādītie informācijas avoti. #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Darba autori:", [ + <NAME>, ac22065, + <NAME>, kc22015, + <NAME>, eg22086, + <NAME>, mk22092, + Jorens Štekeļs, js21283, ], ), ) #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Darba vadītāja:", "prof. Dr. sc. comp. <NAME>", ), ) #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Darba galīgā versija izgatavota:", "18.01.2024.", ), ) #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Darba iesniegšanas datums:", "18.01.2024.", ), ) #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Darba aizstāvēšanas datums:", "22.01.2024.", ), ) #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Komisijas vērtējums:", line(length: 100%, start: (0pt, 10pt)), ), ) #v(vspace) #figure( tablex( stroke: none, columns: (1fr, 1fr), "Komisijas sastāvs:", [ #line(length: 100%, start: (0pt, 10pt)) #line(length: 100%, start: (0pt, 30pt)) #line(length: 100%, start: (0pt, 50pt)) ], ), ) /*Dokumentārā lapa Dokumentārajā lapā (sk. 5. pielikumu) ietver: •darba nosaukumu, fakultātes nosaukumu; •autora apliecinājumu, ka darbs veikts patstāvīgi, ka darbā izmantoti tikai tajā norādītie informācijas avoti un ka darba elektroniskā kopija atbilst izdrukai; •vadītāja atzinumu, vai darbs ir rekomendējams aizstāvēšanai; •atbildīgās personas atzīmi par darba saņemšanu; •recenzenta-/u datus (vārds, uzvārds, amats, zinātniskais grāds); •noslēguma pārbaudījuma komisijas sēdes datumu un protokola numuru.*/
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/game-theoryst/0.1.0/src/lib.typ
typst
Apache License 2.0
#import "nfg.typ": * #import "ul.typ": *
https://github.com/paugarcia32/CV
https://raw.githubusercontent.com/paugarcia32/CV/main/modules_es/technicalSkills.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Conocimientos Técnicos") #cvTechSkill( title: [Programación], description: list( [Conocimiento en Typescript, Java, Flutter, C and `C#` junto con librerias y frameworks relacionados para el desarrollo de Backends, RestAPs y aplicaciones Full Stack], [Conocimiento en algoritmos de Big Data y desarrollo de circuitos cuanticos usanod librerias de Python], ) ) #cvTechSkill( title: [Microcontroladores], description: list( [Proyectos de RFID y NFC usando Arduino], [Proyectos de IOT con protocolos como MQTTy LoRa usando el microcontrolador ESP32], [Conocimiento en protocolos de comunicación serial: I2C i SPI] ) ) #cvTechSkill( title: [Redes], description: list( [Análisis de redes usando Wireshark así como los protocolos involucrados en el escenario], [Simulación de escenarios reales mediante software como Omnet++, Mininet, GNS3 y Contiki], [Configuración de redes MPLS con routers Mikrotik], ) ) #cvTechSkill( title: [Software], description: list( [Familiarizado con entornos Linux], [Usuario de la suite de Microsoft Office], ) )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/027%20-%20Conspiracy%3A%20Take%20the%20Crown/001_Laid%20to%20Rest.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Laid to Rest", set_name: "Conspiracy: Take the Crown", story_date: datetime(day: 03, month: 08, year: 2016), author: "<NAME> & <NAME>", doc ) Kaya sat with her back to a corner, legs up on a chair, eyes on the door. Of course, she didn't want to #emph[look] like she had her eyes on the door, in a place like this. So she kept her eyes on her tea and checked the door one sip at a time. It was good tea, dark and cold and thick with honey. #emph[Not] the sort of thing you could buy in a place like this. The place was called the Wasp's Nest, and it was a certain sort of place, perfect for meeting up with unsavory characters. The man she was there to meet was respectable, a nobleman, which she supposed meant she was the unsavory one in the arrangement. Though you never could tell. #figure(image("001_Laid to Rest/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Her fellow rogues came and went to the strains of an inexpertly played mandolin, and nobody let their eyes linger too long on anybody else's business. Tavern, saloon, watering hole, great hall—on a dozen worlds, these places were all the same. Kaya had tossed the barkeep a coin to cover the drinks she wasn't buying and another to leave her alone. Her prospective employer was only a few minutes late, but Kaya had been sitting and sipping for over an hour, getting a feel for the place. She was contemplating spending one more coin to buy the mandolin player's silence when her contact walked in. The man was wearing an iris in his brooch, the sign Kaya had been told to watch for, but she knew even before she saw that—beneath the shabby clothes, the man's bearing was crisp and military. Kaya inwardly rolled her eyes. Kaya herself had told them to look for her jacket, a distinctive style in the city. The place was warm, and Kaya had the jacket unbuttoned all the way to reveal a loose blouse beneath, but the man with the brooch caught her eye and walked straight toward her. So discreet! #figure(image("001_Laid to Rest/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) The soldier loomed over Kaya's table. Kaya didn't move except to wave one hand, inviting him to sit. Instead, the man leaned down over the table and said, "You're the hunter?" "As charged," said Kaya. "I'm going to guess you're not my client." "His grace will see you now," said the man, gesturing to the stairway. "Upstairs." Of course. #emph[His grace] would never be seen in a place like this. Probably came in the back way. Kaya rose in one fluid motion, smiling. "Lead the way." The man frowned and walked ahead of her to the stairs. Kaya buttoned her jacket as they walked up the stairs and down a short hallway. At the end of the hallway, the man knocked twice on a door much like the others, then opened it and gestured for Kaya to go in. The room was cramped, with a small desk set up in place of the bed. Behind the desk sat the man she had come here to see: <NAME>, third son of a noble house of middling influence. Behind him, standing at attention, were two well-dressed servants whose job had probably been hauling that stupid desk up here. Revari had greased hair and fine clothes. He sat like a young man, cocky and headstrong, but the lines on his face and the slackness of the skin around his jaw put him closer to 40 than 30. He smiled the bland, indulgent smile of nobility, only his dark, darting eyes betraying his nervousness. "Please, sit," he said, gesturing to a chair on the near side of the desk with a hand bristling with rings. One was a signet ring bearing his personal seal, and the rest looked jeweled and expensive. The man with the brooch closed the door and took up a bodyguard position beside the desk. Kaya sat, back to the door. Not her favorite thing. She leaned back in her chair. "<NAME>," she said with a properly deferential nod. "Indeed. And how shall I address you, Miss—?" "Kaya's fine." In fact, Kaya came from a noble line herself, though she and her kin had never stood on ceremony. Since leaving her home plane, she saw no reason to mention her lineage at all. She knew. That was what mattered. "So," she said, before he could speak again. "What makes you think I can help you?" Some prospective employers misunderstood her work—tried to hire her for theft, or espionage, or mundane assassination. She had no qualms about walking out on them, nor about cutting right to the part of the conversation where she could decide whether to do so. Revari shifted uncomfortably. "Some time ago," he said, "upon the death of my dear mother, I inherited her holdings here in town. My brother, the duke, had granted her a manor here to live out her dotage in peace and quiet. That manor now belongs to me. I waited for a seemly interval of mourning, sent workers to renovate the house, and prepared to take up residence." The Revari estate was back in Paliano. As the duke's younger brother, Emilio was free to stay there. But this manor out in the hinterlands, a house big enough to quarter dozens of soldiers or a couple good-sized families, would be far more comfortable for one coddled nobleman and his retinue. "I've heard your remodeling is taking longer than planned," said Kaya. She kept her ear to the ground wherever she went, and the rumors swirling around town had plenty of theories about the reason for the delays to the renovations. <NAME> had run out of money. He kept changing his mind about the decor. His mistress kept changing #emph[her] mind about the decor. The house was haunted. The house was cursed. A scam-artist fortune teller had #emph[told] him the house was cursed, but really...and on and on. Given that he was looking to hire her, Kaya had a pretty good guess which one of those rumors was true. "Considerably," said Revari. "It was little things, at first. Tools gone missing, repairs being undone. I chalked it up to laziness and peasant superstitions. But it got worse and worse, and there is no doubt in my mind: the place is haunted. Now the workers won't go in there even in the daytime for fear of the ghost, and people are starting to talk." A specter from beyond the veil of death had a grudge against him, and he was concerned for his #emph[reputation] . "And this is...just some ghost," said Kaya. Revari squirmed. "...who happened to move in right after your mother's death?" Revari drew himself up. "The spirit's identity," he sniffed, "is no business of yours. The point is, there's a ghost in #emph[my] house, and I want it #emph[gone] . I was told that's what you do." Spoiled little lordling. Kaya's mother had certainly never let her speak to people that way, lineage or no. "It is what I do," she said. "But I'm not just some exterminator, <NAME>, and ghosts are not vermin. I need to know the facts of the case so I can guess what this ghost of yours might do." He nodded, red-faced. "I have reason to suspect," he said, "that my mother...has refused to depart the premises." #figure(image("001_Laid to Rest/03.jpg", width: 100%), caption: [Homicidal Seclusion | Art by Cliff Childs], supplement: none, numbering: none) "Huh," said Kaya. "Any idea why?" "She's been clinging to this house for decades," spat Revari. "Could've passed it to me at any time, and I'd have seen that she was cared for. But no. The house was hers, and she wouldn't relinquish it. So I waited, #emph[patiently] . Now she's dead, and I have mourned, and it is #emph[my] turn. I want my house." Kaya nodded, slowly.#linebreak #linebreak "I'm sympathetic to your cause, <NAME>," she said. "I'll take the job." "Oh, good," he said bitingly. Kaya ignored that. Perhaps his grace was not accustomed to having the worth of his requests evaluated. In fact, she'd taken an immediate dislike to the man. But Kaya would happily take an unpleasant nobleman's money for ridding the world of one more soul who couldn't be bothered to finish their business when they had the chance. "Did you bring the building plans?" One of the servants stepped forward with a cylindrical wooden case, but Revari held up a hand. "I did," he said. "The originals and the renovations. But I keep asking myself...#emph[why] you need them. They seem more suited to thievery than ghost hunting." Kaya laughed. "You calling me a thief?" "Well—I mean, really, what else are they good for?" She leaned forward. "If you don't trust me, don't let me into your house," she said. "I can always find another client. And you can either find someone else with my very unusual skill set or live with your dear mother's ghost forever." "There's no need for that," said Revari stiffly. "I meant nothing by it." "Oh, good," said Kaya. She took the wooden cylinder from the servant's hand and tucked it under one arm. "Has the spirit been favoring any particular part of the house? Your mother's chambers, perhaps, or the room where she died?" "She's been seen all over the house," said Revari. He paused a moment, seeming to consider, then said: "From what I've heard, however...east wing. Second floor. Not her chambers. Could be where she died, I suppose." "And have you seen this ghost yourself?" "No," said Revari. "Since receiving reliable reports of the haunting, I've not set foot in the house, for obvious reasons." "Obvious?" "I'm the interloper, aren't I?" said Revari. "If the old harridan is clinging to her property, I'm sure she'd have it out for me in particular." "Could be," said Kaya. "Anything else I ought to know?" "Not that I can think of," said Revari. "You'll do this tonight?" "Tomorrow night," said Kaya. She patted the case of building plans. "Proper preparation takes time." "Very well," said Revari. "Inform me as soon as the deed is done, regardless of the hour. I'll sleep far more soundly knowing that my mother is well and truly laid to rest." "As you like," said Kaya. "Then all that's left is the matter of payment. Half down, as I said in my letter." "Ah yes," said Revari, with obvious distaste. He withdrew a bag from beneath the table. Kaya took it without looking inside. It wasn't as if the man was in any position to cheat her. "I was wrong," he said. "At this price, you're not a thief. You're an extortionist." "Exorcist, your grace," said Kaya, smiling broadly. "It's pronounced #emph[exorcist] ." She took her money and the building plans, rose, bowed to the nobleman with an exaggerated flourish, and walked out. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kaya woke the next evening as the light from the setting sun peeked through the gap she'd left in the curtains. She'd spent the night in her little room at an inn, drinking cold tea and studying the house plans, then slept through the day. There was just no sense hunting ghosts in the daytime. Some of them wouldn't or couldn't come out, and others would but weren't substantial enough during the daylight hours to actually fight with. Kaya lit a candle, yawned, and splashed her face with water from a basin. She rolled out the building plans and studied them one last time, humming an old ballad and unwinding the knots she'd put her hair in to sleep. The plans had yielded no real surprises. It was a textbook High Troscan manor, with a few Anvar-era flourishes thrown in after the fact. All pretty standard for a house of this age in one of Paliano's less fashionable minor fiefdoms. The renovations were going to be the real challenge—Revari had provided both the original design and the plan the builders were working toward, but there was no indication how much work had actually been done before the workers had fled. She donned her jacket, checked that her two rondel daggers were well oiled, and securely sheathed them on her forearms. The candle had burned down by then. She blew it out, poured wax into a tray, shaped it into two little globs, and tucked them in a jacket pocket. She examined herself in the looking glass and saw a well-rested, fully prepared ghost hunter. Perhaps a bit cocky. Perhaps. #figure(image("001_Laid to Rest/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Out the little door and down the stairs, then, to the common room of the inn where she was staying—a rather nicer one than the Wasp's Nest. The barkeep, a stout woman with a missing eye, gestured to her. "Mail for you," she said, handing over an unmarked envelope. "Hand delivered." Kaya raised an eyebrow. The list of people who even knew how to contact her here was not a long one. She opened the envelope and unfolded the single sheet within. It wasn't a letter, exactly; in fact, it bore no writing at all, just a symbol. The Black Rose. Her heartbeat quickened. So it was time—time for the #emph[big] job, the one she'd been preparing for since last year. She knew where her next big payday was coming from, then...assuming she could actually pull it off. She thanked the barkeep with a copper coin and walked out the door with a spring in her step. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) She arrived at the manor as twilight gave way to full dark. One of Revari's pages unlocked the gate and the house doors for her, then fled the grounds as quickly as he could. The mahogany double doors swung open with a loud creak. She shut them behind her with heavy finality, then withdrew the wax plugs from her pockets and worked them into her ears. Call it a hunch. #figure(image("001_Laid to Rest/05.jpg", width: 100%), caption: [Moorland Haunt | Art by <NAME>], supplement: none, numbering: none) Kaya flicked her hand, and a trio of will-o'-the-wisps sprang from her fingers. They weren't true wisps, just lights, but they wandered around her as though they had minds of their own, sending cold light and deep shadows dancing silently around the entryway. Kaya walked through the entryway and into the receiving room. Her muffled footsteps echoed in the stillness. From the high ceiling hung a chandelier, which she opted not to walk directly beneath. One of the curving staircases was modern in style, brand new; the other had been torn out and not yet replaced. The whole place smelled of dust and age. She stepped over a hodgepodge of artisan's tools, shattered plates, and shredded paintings. So Dear Mother was one of#emph[ those] ghosts. "Hey!" she yelled. "Ghost!" Her voice echoed through empty hallways and was lapped up by lush carpets, fading back to silence. Fine. Cautiously, with her wisps bobbing behind her, she walked up the curving staircase step by creaking step. She paused on the balcony at the top of the stairs. To her right lay the western side of the house, given over to bedrooms, maids' quarters, and all the other amenities of noble life. To her left lay the east wing, which mirrored the west but was broken into a warren of guest bedrooms, sitting rooms, and libraries. She headed left with a purposeful stride, counting her steps. Whatever the phantom was protecting in the east wing, her best chance of finding the thing was to threaten that area directly. Beyond the balcony was a long hallway, with sitting rooms down one side and a large double door at the end. Behind the other wall, according to the plans, ran a long, cramped servants' passage. There'd been no construction here, and the carpeted floor was clear except for a shattered tea service dropped by some terrified butler. Kaya stepped around it. "I know you're here!" This time, a chill wind blew through the hallway, accompanied by a keening wail that seemed to come from everywhere at once. "Very spooky!" said Kaya. "Want to rattle some windows? Maybe throw some plates around?" Most spirits hated the living, and almost all of them hated being mocked. A spectral form appeared most of the way down the hallway, as though a curtain had blown open. She looked like an old woman, glowing and translucent, her features distorted by death and rage. Her frail arms ended in slashing claws, and her shawl trailed off into something like a tail. Her sweet-old-lady face was split by a maw full of needle-sharp teeth. She hovered not by the double doors at the end of the hallway, but outside one of the doors along its length. Kaya took note of which one. #figure(image("001_Laid to Rest/06.jpg", width: 100%), caption: [Patrician's Scorn | Art by <NAME>], supplement: none, numbering: none) "There you are!" said Kaya. The ghost screamed at her, a piercing shriek that slammed into her like a physical thing. Doors rattled, and somewhere a glass shattered. Kaya winced from it—but that was all, thanks to the wax in her ears. She drew her rondel daggers and pushed their blades beyond the physical, into the realm of the dead. They glowed purple-white and grew cold in her hands. "Yeah, no," she said. "Fun's over. Get out, and don't come back." The ghost screamed again and charged her. Oh well. That almost never worked, but Kaya felt like she had to give them the chance. The hallway wasn't wide enough to dodge the ghost's raking claws. Kaya imagined the blueprints, walking her fingers across them, counting steps. Left: library. No good. Too many loose objects a poltergeist-inclined spirit could send flying at her. To the right, then. Servants' passage. Tight squeeze. #figure(image("001_Laid to Rest/07.jpg", width: 100%), caption: [<NAME> | Art by <NAME>], supplement: none, numbering: none) She waited until Dear Mother was almost within striking distance, then sprang to the right. This...was not the fun part. She started with her hand, already holding the dagger. The ghostly light and deathly chill spread up her arm, almost to the shoulder, as her hand, dagger and all, passed into the realm of the dead and #emph[through] the wall. By the time her shoulder went through, her hand was in the servants' passage. She brought the hand back to physicality, let it anchor her to the realm of the living. The ghostly light consumed her head and body, bright and cold. She pulled her trailing arm and leg through and brought herself back to the world of the living, slamming into the far side of the cramped little passage with her now-corporeal shoulder. The whole motion took, perhaps, a heartbeat. Not that her heart actually #emph[beat] , when she stepped out like that. She didn't dare stay long. She spun and dove back through the wall, back into the main hall, as the confused phantom flew past where she'd been a moment ago, trailing that shawl. She lit up one of her daggers and pinned the shawl to the wall. The ghost lurched to a stop, screaming, and turned to stare at her with dead white eyes. "Hi," said Kaya. The ghost struck, but Kaya blocked with the other dagger, stabbing it through the ghost's gnarled palm. Dead eyes grew wide. #emph[That] was the fun part—watching an undying, insubstantial phantom realize it had messed with someone who could fight back. Dear Mother twisted away from her, howling and snarling, tearing the shawl free of Kaya's dagger. Shawl and hand both leaked trails of glimmering smoke—ghost blood, more or less. Then the ghost was gone, spiraling up through the hallway ceiling. Kaya could do a lot of things a ghost could do, but she couldn't do that. She turned and ran toward the door where the ghost had first appeared. Dear Mother boiled up out of the floor ahead of her, and Kaya threw herself left, through the wall, into what had looked like some kind of bedroom in the plans. It had been scheduled for a remodel, but nothing drastic— The bedroom had no floor. It was just an open pit lined with jutting timbers. Kaya glimpsed a half-finished spiral staircase before she went over the edge. That had #emph[not] been in the plans. Secrets! Why did nobles always insist on keeping secrets? Kaya dropped one of her daggers—no time to sheath it—and spun, catching one of the timbers with her free right hand. The dagger landed down on the first floor with a clatter. She surveyed her situation as her wisp-lights caught up with her. Her feet were dangling maybe six feet above an uneven floor, her hand aching from taking all her weight at once. In front of her was some kind of crawlspace, maybe a foot and a half high, between the floors. She sheathed the dagger in her off hand. She could probably land without turning an ankle, but only probably—and even then, she'd be back down on the first floor. Above her, the phantom flew screaming through the wall, then floated in a moment of confusion. The shawl-tail dangled tantalizingly close. Kaya swung herself back and forth once, twice. Always have a plan... ...never rely on it. She let go of the timber, reached out into the chilly realm of the dead, and closed spectral hands around the spectral shawl. She'd caught the ghost by surprise, and it lurched downward a foot or two, snarling and spinning. Then it was up toward the third floor in dizzying flight, through what should have been a bedroom, screaming at the indignity. Kaya didn't want to hitch a ride for long—the ghost could drag her all sorts of nasty places. Straight up, for instance. She judged the ghost's spin, timed her jump, and let go of the phantom's tail. She passed through a side wall of the bedroom-turned-deadfall, tucked, and rolled on the floor of the room beyond it. People tended to underestimate the amount of acrobatics involved in ghost hunting. She sprang to her feet and drew her remaining dagger. She'd lost count of her steps, but if she'd seen correctly, this was the room the ghost had appeared outside. The place had been some kind of tea room, but it was completely wrecked. Splintered furniture lay everywhere, and the ground crunched with broken glass and shards of porcelain. And in one corner, a little pile of debris... Dear Mother flew shrieking through the wall just as Kaya put it all together. East wing. #emph[Not ] the mother's chambers. Crawl space. And now a strange little pile of detritus in one corner of an otherwise ordinary room the ghost seemed to care very much about. Kaya took a fighting stance with her dagger out in front of her, glowing with ghostlight. The spirit veered away this time, howling, now keenly aware that Kaya could hurt it. "Wait!" said Kaya, edging toward the corner. Most spirits were too twisted by rage or grief to be reasoned with, but maybe... Dear Mother screamed again, and shards of glass and porcelain jittered on the floor. Kaya dove behind a heavy toppled hutch as every piece of loose shrapnel in the room flew toward her. The shards slammed into the hutch, and she felt a few of them snag in her hair. Dear Mother would be right behind... Kaya leapt toward the corner, glimpsing a ruined portrait, some jewelry, and floorboards with long, deep scratches in them. "I said #emph[wait] !" yelled Kaya, holding out a hand. "I understand!" This time, the ghost paused. Keeping her eyes on the ghost, Kaya pushed aside the detritus, jammed her dagger between two of the ragged floorboards, and pried. She pulled up one board, then another. There, in the crawlspace, was the withered corpse of an old woman. The ghost wailed, and this time it sounded more like grief than anger. Kaya looked at the corpse, then back up at the ghost. The resemblance was striking. #figure(image("001_Laid to Rest/08.jpg", width: 100%), caption: [Ghoulcaller's Accomplice | Art by <NAME>], supplement: none, numbering: none) Kaya glanced at the things she had brushed aside. #emph[Men's] jewelry, rings and cufflinks. A shirt, tailored for a man, torn to ribbons. A portrait, also shredded, of a nobleman posing. And among the jewelry... A signet ring. A #emph[familiar] signet ring. "Son of a—" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kaya waited in the fully lit entryway of <NAME>'s modest but unhaunted townhouse, standing and resisting the urge to tap her foot. She ran her hands through her hair, picking out what she hoped was the last of the porcelain shards and tucking them in her pockets. Better her hair than her scalp, at any rate. It was nearly midnight, but she'd been ushered in. And despite the lateness of the hour, Revari himself appeared in the entryway, fully dressed and wearing a coat. "It's done?" he asked. Avarice gleamed in his eyes. "After tonight, <NAME>, your mother will rest in peace." "Take me there," he said. "I want to see the house." "Weren't we talking about trust?" said Kaya, with open indignation. "You've performed a valuable service," said Revari. "I can't be faulted for wishing to inspect your work before remitting payment." "Fine," said Kaya. "Bring the money, though. I'm not coming all the way back here." "As you wish," said Revari icily. It wasn't a long walk, but Revari opted to use a carriage, with a driver and a bodyguard riding in front and Kaya and himself inside. Revari asked a string of questions about her work, apparently out of no more than simple curiosity and the conviction shared by so many nobles that everything was their business if they wanted it to be. "Does it leave...remains? When you kill them?" "Every ghost is different," said Kaya, not for the first time. "In this case, yes, there's a physical residue." "Ah," said Revari. "I'll want to see that. Should it be...buried?" "That's between you and your religion," said Kaya. "I'm not that kind of exorcist." What Kaya did was seen as blasphemous by some, a disruption of the natural order of life beyond death. But in other belief systems it was the ghosts themselves who were disrupting the natural order, and Kaya who was setting things right. She'd been showered with blessings some places and run out of town in others, all for doing the same thing. Whatever the ultimate destiny of the dead on any given world, it was Kaya's personal conviction that they weren't fulfilling it by hanging around being a nuisance to the living. #figure(image("001_Laid to Rest/09.jpg", width: 100%), caption: [Harrowing Journey | Art by <NAME>], supplement: none, numbering: none) Revari nodded with satisfaction. His own deeply held religious beliefs, she suspected, called for not paying for another funeral unless he had to. They arrived at the manor. The bodyguard, the driver, and Kaya's payment remained with the carriage, and Revari followed Kaya to the door. He'd brought a lantern, so Kaya didn't bother with wisps. The scene in the entryway was the same as before. Revari murmured in distress as he surveyed the debris. "It'll take a month just to clean up this mess so remodeling can resume," he said. "And that's assuming I can get the workers back in the door." He turned to Kaya. "Would you be willing to, ah, attest to your handiwork? Tell them it's safe to return?" "I could be persuaded," said Kaya, which only set Revari to murmuring again. They ascended the staircase, Revari swinging the lantern around like a nervous young hunter on his first night in the woods. He paused at the top of the stairs. "You'll want to examine the east wing, I'm sure," said Kaya. "Your tip-off was very helpful. That's where I found her." "Yes," said Revari. "Yes, of course. And you're...certain it's safe?" "Safe as your own house, your grace." He nodded and crept into the east wing, lantern bobbing. He jumped at every gust of wind and creak of the floorboards. Kaya walked beside him. "Here we are," said Kaya, gesturing to the closed door of the room where she'd found the old woman's body. "Here?" said Revari. "This is where it happened," said Kaya. Revari's breathing quickened. "You go in first," he said. Kaya smiled reassuringly, opened the door, and stepped through. Revari peered through the door, then stepped through slowly. He held the lantern high, the shadows of the room's ruined furniture looming crazily. Very quietly, Kaya closed the door behind him. "Now then," he said, dry-throated, looking around. "Where is this—" He stared into the corner where Kaya had pried up the floorboards, then spun to face her. "What is this?" he spat. "#emph[What is this?] " "I know what you did," said Kaya. Her voice was quiet, measured, calm. Revari's face was red, his veins bulging. "Whatever it is you're trying to extort from me—" "I don't want anything from you, kinslayer," said Kaya. She nodded, over his shoulder. "#emph[She's] the one you ought to be worried about." Dear Mother had appeared, sorrowful and timeless, behind her wayward son. Revari turned. Kaya covered her ears. #figure(image("001_Laid to Rest/10.jpg", width: 100%), caption: [Hollowhenge Spirit | Art by Lars Grant-West], supplement: none, numbering: none) "No," he said. "No. Please, Mother—" The ghost screamed, and Revari fell to his knees, clutching his head. The lantern clattered to the ground. Kaya picked it up and blew it out, so the room was lit only by the cold light of the dead. Revari turned to her, still on his knees, eyes wide. "Help me," he said. "I'll pay you—I'll pay double!" "Your own #emph[mother] ," said Kaya. "You can rot in hell." His mother's ghost advanced on him slowly, with a flair for the theatric that Kaya could appreciate. Revari edged away on his elbows until he bumped into the closed door. "You #emph[liar] ," he said. "I paid you to, to, to fix this! Stop her! #emph[Do your job!] " "I'm defaulting, with cause," said Kaya. She hadn't lied to him, not quite, but she hadn't actually done the job either. "I'll tell your underlings they can keep the other half." He snarled and lunged at her, but her legs went ghostly, and he went straight through them and sprawled out behind her with a strangled cry. "Please—" Then his mother's wailing ghost was upon him with those needle teeth and those dagger claws. Kaya walked through the closed door in a flash of purple-white light, leaving mother and son to their sad, sorry business. Kaya smoothed her jacket, turned, and walked away. Behind her, <NAME> began to scream, and kept screaming as she walked down the stairs, across the ruined entryway, through the thick, wooden doors of the manor, and into the night beyond.
https://github.com/prettyroseslover/CV_July_24
https://raw.githubusercontent.com/prettyroseslover/CV_July_24/main/data.typ
typst
#let data(lang) = ( name: ("ru": [<NAME>на], "it": []).at(lang), links: ( ( title: [`Санкт-Петербург`], url: "", icon: "\u{f276}", available: ("ru", "it"), ), ( title: [`<EMAIL>`], url: "mailto:<EMAIL>", icon: "\u{f0e0}", available: ("ru", "it"), ), ( title: [`+7(953)545-16-95`], url: "tel:+79535451695", icon: "\u{f095}", available: ("ru", "it"), ), ( title: [`@prettyroseslover`], url: "https://t.me/prettyroseslover", icon: "\u{f2c6}", available: ("ru", "it"), ), ( title: [`GitHub: prettyroseslover`], url: "https://github.com/prettyroseslover", icon: "\u{f09b}", available: ("ru", "it"), ), ( title: [`GitLab: prettyroseslover`], url: "https://gitlab.com/prettyroseslover", icon: "\u{f296}", available: ("ru", "it"), ),).filter(l => l.available.contains(lang)), education: ( title: ("ru": [Образование], "it": []).at(lang), contruts: ( (title: ( "ru": [#link("https://diploma.itmo.ru/docs/85E532EDAC44D6DE9C6E7591E4EFFA7F")[ *Университет ИТМО* ]], "it": [], ).at(lang), subtitle: ( "ru": [БАКАЛАВР 2020-2024 GPA 5.0 Информационная безопасность], "it": [], ).at(lang)), ), ), experience: ( title: ("ru": [Опыт], "it": []).at(lang), contruts: ( ( title: ( "ru": [#link("https://drive.google.com/file/d/1z6kau1Z1Czd_CiWwbbV04V2q9G24_3MD/view?usp=sharing")[*Стажёр*], ИнфоТеКС], "it": [], ).at(lang), subtitle: ("ru": [март 2023 - июль 2023], "it": []).at(lang), ), (title: ( "ru": [*Аналитик ИБ*, ИнфоТеКС], "it": [], ).at(lang), subtitle: ( "ru": [июль 2023 - настоящее время], "it": [], ).at(lang)), ), ), skills: ( title: ("ru": [Навыки], "it": []).at(lang), contruts: ( ( title: [Rust, Python, C/C++, bash], ), ( title: [Docker, Git, Postman], ), ( title: [Linux, Windows], ), ( title: [Confluence, Azure DevOps, Figma], ), ), ), projects: ( title: ("ru": [Проекты], "it": []).at(lang), contruts: ( (title: ("ru": [ #link("https://github.com/prettyroseslover/cgjail")[ cgjail] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Двумодульное приложение ограничения аномальных процессов в Linux с помощью динамической настройки cgroup, 2024], "it": []).at(lang),), (title: ("ru": [ #link("https://gitlab.com/prettyroseslover/mysql_pytest")[ INT 1], #link("https://github.com/prettyroseslover/INT-3")[ INT 3] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Интенсивы PT START 2024.1], "it": []).at(lang),), (title: ("ru": [ #link("https://drive.google.com/file/d/1DzpWzYnqXtrlgAi1I2p3Z5RQ6ZkU9jAf/view?usp=sharing")[ Selectel Hackathon] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) UI Дизайн в #link("https://www.figma.com/design/uIEtW9hMCnWxx1x9baizRT/Hackaton?node-id=0-1&t=y1kjW6bWPk002UIv-1")[Figma], 2024], "it": []).at(lang),), (title: ("ru": [ #link("https://github.com/prettyroseslover/VVery-Bad-flask-app")[ VVery-Bad-flask-app] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Уязвимое приложение на Flask для обучения и демонстрации, 2023], "it": []).at(lang),), (title: ("ru": [ #link("https://github.com/prettyroseslover/ti_crc_lab5/tree/master")[ CRC и ElGamal] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Лабораторная работа по Теории Информации с реализацией алгоритмов, 2023], "it": []).at(lang),), (title: ("ru": [ #link("https://github.com/prettyroseslover/task_cpp")[ Task Cpp] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Клиент-серверное приложение на C++, 2023], "it": []).at(lang),), (title: ("ru": [ #link("https://github.com/prettyroseslover/ti_crc_lab5/tree/master")[ WinProtect] ]).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Лабораторная работа по защитe от несанкционного редактирования файлов в Windows, 2022], "it": []).at(lang),), (title: ("ru": [Респондент CustDev для курса _Информационная безопасность.Basic_ ] ).at(lang), // subtitle: ("ru": [ #set text(size: 10pt) // OTUS, 2024], "it": []).at(lang), ), ), ), courses: ( title: ("ru": [Курсы], "it": []).at(lang), contruts: ( ( title: ( "ru": [#link("https://drive.google.com/file/d/1JJDb1-vYmrpq9HDn0qINmzZdcPniZLN8/view")[ *Хранение и обработка данных*], #link("https://drive.google.com/file/d/15CWHy9ShZwr0QeB_Kp_SWXJHvgvUEFIJ/view")[ *Прикладная статистика* ]], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Университет ИТМО\ февраль 2021 - декабрь 2021], "it": []).at(lang), ), ( title: ( "ru": [#link("https://drive.google.com/file/d/1zZntKjg2Zzx-3yw0fgohqU9aR5iYBdm7/view?usp=sharing")[ *КРИПТА: от теории к практике* ]], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Университет ИТМО\ август 2022], "it": []).at(lang), ), ( title: ( "ru": [#link("https://drive.google.com/file/d/1qUF5OvEQI8c4jbvzihEWaOS1M6vO8kuO/view")[ *Advent of Cyber 2022* ]], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Try Hack Me\ декабрь 2022], "it": []).at(lang), ), ( title: ( "ru": [#link("https://drive.google.com/file/d/1k-DWrp51Ls2fbShwqE-SBm4UmXTIM6m7/view")[ *SQL*], #link("https://drive.google.com/file/d/1CiDQvN8d3ZzFNaxViwtfZcwtW8I6dqsg/view")[ *Python для ИИ* ]], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Mathshub], "it": []).at(lang), ), ( title: ( "ru": [ *Методы анализа данных bonus_track* ], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Университет ИТМО & Иннополис\ октябрь 2023 - июнь 2024], "it": []).at(lang), ), ( title: ( "ru": [ *PT START 2024.1* ], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Positive Technologies\ март 2024 - настоящее время], "it": []).at(lang), ), ( title: ( "ru": [ *Прикладные методы анализа пространственных данных в урбанистике* ], "it": [], ).at(lang), subtitle: ("ru": [ #set text(size: 10pt) Университет ИТМО\ июнь 2024], "it": []).at(lang), ), ), ), languages: ( title: ("ru": [Языки], "it": []).at(lang), contruts: ( ( title: ("ru": [*Английский* C1-C2], "it": []).at(lang), subtitle: ("ru": [#link("https://drive.google.com/file/d/1zln7xf1oxGDDJDZYZh8UNOrSM7p8V-3g/view?usp=sharing")[ FCE ]], "it": []).at(lang), ), ( title: ("ru": [*Итальянский* B1], "it": []).at(lang), ), ( title: ("ru": [*Немецкий* A2], "it": []).at(lang), ), ), ), )
https://github.com/julius2718/typst-jpdoc-template
https://raw.githubusercontent.com/julius2718/typst-jpdoc-template/main/0.0.1/main.typ
typst
MIT License
#let sans(it, font: ("Helvetica", "Hiragino Sans", "BIZ UDPGothic")) = { text(font: font)[ #it ] } #let gtheading(it, font: ("Helvetica", "Hiragino Sans", "BIZ UPDGothic")) = { text(sans(font: font)[#h(-1em) *#it* #h(1em)]) } #let signature(title: "", date: "", author: "") = { align(center, text(1.4em)[ *#title* #v(0.6em) ]) align(center, text(1.1em)[ #date #v(0.6em) #author ]) v(0.6em) } #let jpdoc(doc) = { set text(font: ("STIX Two Text", "Hiragino Mincho ProN", "BIZ UDPMincho"), size: 11pt,) show math.equation: set text(font: "STIX Two Math") show raw: set text(font: "Osaka", size: 1.4em) set heading(numbering: "1.") set page(margin: (top: 30mm, rest: 25mm)) set par(first-line-indent: 1em, justify: true, leading: 1em) set block(spacing: 1em) show heading: it => { v(0.6em) it par(text(size: 0.6em, "")) } [#doc] }
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/24-01-02/24-01-02.typ
typst
#import "/template.typ": * #show: project.with( date: "02/01/24", subTitle: "Analisi paragrafi Norme di Progetto e context switch", docType: "verbale", authors: ( "<NAME>", ), timeStart: "15:00", timeEnd: "16:30", ); = Ordine del giorno - Analisi paragrafi Norme di Progetto da redigere rispetto allo standard ISO/IEC 12207:2017; - Context switch dei programmatori in merito al PoC. == Analisi paragrafi Norme di Progetto da redigere rispetto allo standard ISO/IEC 12207:2017 Nell'espansione e aggiornamento del documento Norme di Progetto, il gruppo fa riferimento allo standard ISO/IEC 12207:2017. Dato l'avvinarsi della prima revisione esterna (RTB), il gruppo ha ritenuto opportuno identificare i paragrafi facenti riferimento ad aspetti del progetto che non trovano riscontro e applicazione nel periodo attuale. Si è pertanto stabilito che i seguenti paragrafi saranno redatti in seguito alla revisione esterna, perché più pertinenti al periodo di PB: - _Architecture Definition Process_; - _Design Definition Process_; - _System Analysis Process_; - _Implementation Process_; - _Integration Process_; - _Verification Process_; - _Transition Process_; - _Validation Process_; - _Operation Process_; - _Maintenance Process_; Questa decisione non impone vincoli sulla redazione della totalità dei paragrafi sopra elencati, ma pospone al secondo periodo di progetto la loro analisi approfondita e il loro adeguamento al contesto del progetto didattico. == Context switch dei programmatori in merito al PoC Al fine di rendere più efficace ed efficiente l'approccio al codice sorgente del PoC prodotto, si è ritenuto necessario effettuare un meeting dedicato tra i programmatori dello sprint precedente e quelli dello sprint corrente. Durante lo svolgimento del meeting si è analizzata la struttura principale del prodotto software, evidenziando le sezioni richiedenti maggiore attenzione e cercando di pareggiare le competenze tra i programmatori. Si nota che il PoC presenta al momento un bug di performance la cui probabile causa è dovuta all'uso non ottimale dei `Renderer` in Three.js. Sarà compito dei programmatori dello sprint corrente risolvere il problema. Non si ritiene necessaria l'aggiunta di nuove feature al PoC prodotto.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pagebreak_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Pagebreak, empty with styles and then pagebreak // Should result in one auto-sized page and two conifer-colored 2cm wide pages. #pagebreak() #set page(width: 2cm, fill: conifer) #pagebreak()
https://github.com/donRumata03/aim-report
https://raw.githubusercontent.com/donRumata03/aim-report/master/lib/preview-template.typ
typst
#set page(paper: "presentation-16-9") #import "@preview/cetz:0.1.2": * // #let someText = lorem(30) #let previewTemplate(body, index: none, PTHSColor: fuchsia) = { layout(pageSize => [ #grid(columns: (30%, 70%))[ #set align(center + horizon) #box(stroke: none, fill: none,// rgb("#4f3a3a"), width: pageSize.width / 2 * 1, height: pageSize.height, canvas({ // WHY IS THAN NOT THE WHOLE PAGE H@LF?!?! import draw: * // content((0, 0), image(height: 451pt, "res/PTHS.svg"), anchor: "center", name: "i") let tripleInt(pos, rules: it => it) = content(pos, [ #show math.equation: set text(194pt) #show: rules // $ integral.triple $ $ integral $ ], name: "i") tripleInt((0, 0)) content(/*"i.center"*/(0.8, 0), image(height: 220pt, "../res/ferris-point.png"), anchor: "center", name: "i") let low-opacity = it => [#show math.equation: set text(fill: rgb(0%, 0%, 0%, 50%)); #it] // tripleInt(rules: low-opacity, (1.5, 0)) // tripleInt(rules: low-opacity, (-1., 0)) // content((-5, 0), [#text(size: 158pt, fill: PTHSColor, "Ф")], anchor: "center", name: "i") // content((5, 0), [#text(size: 158pt, fill: PTHSColor, "Ш")], anchor: "center", name: "i") })) ][ #set align(center + horizon) #show heading: it => [ #set align(center) #set text(75pt / it.level, weight: "bold", /* line-spacing: 2pt */) // Former 140pt #block(smallcaps(it.body)) ] #set text(size: 3em) = Rust #v(-1em) == Лекция #str(index) #v(-0.5em) #body ]]) } // #let thing = style(styles => [ // #let img = image("res/PTHS.svg") // #locate(loc => [ // // #measure(img, styles) // // #loc.position() // #place( // top+start, // // float: true, // dx: loc.position().x + measure(img, styles).width / 2, // dy: loc.position().y + measure(img, styles).height / 2 // )[1] // ]) // #img // ]) // #thing // #box(stroke: 2pt + red, canvas({ // import draw: * // content((0,0), image("res/PTHS.svg"), anchor: "top-left", name: "integral") // set-style(radius: 0.1) // for k in ("top-left", "top", "top-right", "left", "center", "right", // "bottom-left", "bottom", "bottom-right") { // fill(blue); circle("integral." + k) // } // fill(red); // circle(("integral.top-left", 0.75, "integral.top-right")) // }))
https://github.com/ChristophVanDeest/FH-Kiel-Typst-Template
https://raw.githubusercontent.com/ChristophVanDeest/FH-Kiel-Typst-Template/main/lib/translations.typ
typst
MIT License
#let value(en: "", de: "") = { context { if text.lang == "en" { return en } if text.lang == "de" { return de } return "Unknown language" } } #let translations = ( bachelor-thesis: value( en: "Bachelor thesis", de: "Bachelorarbeit", ), master-thesis: value( en: "Master thesis", de: "Masterarbeit", ), faculty-of: value( en: "Faculty of", de: "Fachbereich", ), department-of: value( en: "Department of", de: "Studiengang", ), bachelor-thesis-submitted-for-examination-in-bachelors-degree: value( en: "Bachelor thesis submitted for examination in Bachelor's degree", de: "Bachelorarbeit eingereicht im Rahmen der Bachelorprüfung", ), master-thesis-submitted-for-examination-in-masters-degree: value( en: "Master thesis submitted for examination in Master's degree", de: "Masterarbeit eingereicht im Rahmen der Masterprüfung", ), in-the-study-course: value( en: "in the study course", de: "im Studiengang" ), at-the-department: value( en: "at the Department", de: "am Department" ), at-the-faculty-of: value( en: "at the Faculty of", de: "der Fakultät" ), at-university-fh-kiel: value( en: "at Fachhochschule Kiel", de: "der Fachhochschule Kiel" ), supervising-examiner: value( en: "Supervising examiner", de: "Betreuender Prüfer", ), second-examiner: value( en: "Second examiner", de: "Zweitgutachter", ), submitted: value( en: "Submitted", de: "Eingereicht am", ), list-of-figures: value( en: "List of Figures", de: "Abbildungsverzeichnis" ), list-of-tables: value( en: "List of Tables", de: "Tabellenverzeichnis" ), listings: value( en: "Listings", de: "Listings" ), declaration-of-independent-processing: value( en: "Declaration of Independent Processing", de: "Erklärung zur selbstständigen Bearbeitung", ), declaration-of-independent-processing-content: value( en: "I hereby certify that I wrote this work independently without any outside help and only used the resources specified. Passages taken literally or figuratively from other works are identified by citing the sources.", de: "Hiermit versichere ich, dass ich die vorliegende Arbeit ohne fremde Hilfe selbständig verfasst und nur die angegebenen Hilfsmittel benutzt habe. Wörtlich oder dem Sinn nach aus anderen Werken entnommene Stellen sind unter Angabe der Quellen kenntlich gemacht.", ), place: value( en: "Place", de: "Ort", ), date: value( en: "Date", de: "Datum", ), signature: value( en: "Original Signature", de: "Unterschrift im Original" ), )
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/7.typ
typst
#import "../cfg.typ": * #show: cfg $ "Prove that" "rng"(x |-> a^x) = RR_+ $ $"rng"(x |-> a^x) subset.eq RR_+$ I'm proving that $ex(x): a^x = r$ $ex(x): (sup c: a^c < r) <= x <= (inf c: r < a^c)$
https://github.com/ntjess/showman
https://raw.githubusercontent.com/ntjess/showman/main/src/runner.typ
typst
MIT License
/* Inspiration: https://github.com/typst/packages/blob/main/packages/preview/cetz/0.1.0/manual.typ */ #let example-blocks = state("example-blocks", ()) #let label-counters = state("external-code-label-counters", (:)) #let config = ( runnable-langs: ("example", ), showable-labels: (<example-output>, ), output-label: <example-output>, input-label: <example-input>, ) #let bidirectional-grid(direction: auto, ..args) = { // More complex logic can determine auto layout in the future if direction == auto { direction = ltr } let n-args = args.pos().len() let grid-kwargs = (:) if direction in (ltr, rtl) { grid-kwargs = (columns: (auto,) * n-args, column-gutter: 1em) } else { grid-kwargs = (rows: n-args, row-gutter: 1em) } let pos = args.pos() if direction in (rtl, btt) { pos = pos.rev() } grid(..grid-kwargs, ..pos, ..args.named()) } #let _natural-sized-image(content, format: "svg") = { style(styles => { let (width, height) = measure( image.decode(content, format: format), styles ) image.decode(content, format: format, width: width, height: height) }) } #let _result-decoder-map = ( svg: _natural-sized-image.with(format: "svg"), png: _natural-sized-image.with(format: "png"), jpeg: _natural-sized-image.with(format: "jpeg"), gif: _natural-sized-image.with(format: "gif"), jpg: _natural-sized-image.with(format: "jpeg"), text: it => it, ) #let _format-result(result) = { let typ = type(result) if typ == array { return result.map(_format-result).join("\n") } else if typ == dictionary { let content = result.at("content") let content-type = result.at("type", default: "text") if content-type not in _result-decoder-map { panic("Unknown content type: " + content-type) } return _result-decoder-map.at(content-type)(content) } else if typ == type(none) { return [\<Not yet evaluated\>] } else { return result } } #let _fetch-result-from-cache(result-cache, index: -1) = { let out = result-cache.at(index, default: none) _format-result(out) } #let external-code( raw-content, result-cache: (:), direction: auto, scope: (:), container: bidirectional-grid, ) = { let input-source = raw-content.text let lang = raw-content.at("lang", default: "default") [#metadata(input-source)#label(lang)] label-counters.update(old => { old.insert(lang, old.at(lang, default: -1) + 1) old }) context { let idx = label-counters.get().at(lang) let fetched = _fetch-result-from-cache(result-cache.at(lang, default: ()), index: idx) let output = [#fetched#config.output-label] let input = [#raw-content#config.input-label] container(direction: direction, input, output) } } #let wildcard-import-string-from-modules(scope) = { let preamble = () for key in scope.keys() { if type(scope.at(key)) == module { preamble.push("#import " + key + ": *") } } preamble.join("\n") } #let standalone-example( raw-content, direction: auto, eval-prefix: "", eval-suffix: "", unpack-modules: false, scope: (:), container: bidirectional-grid, ) = { let input-source = raw-content.text let lang = raw-content.at("lang", default: "default") [#metadata(input-source)#label(lang)] let pieces = (eval-prefix, raw-content.text, eval-suffix) if unpack-modules { pieces.insert(0, wildcard-import-string-from-modules(scope)) } let output = eval(pieces.join("\n"), mode: "markup", scope: scope) let grid-args = (box(width: 1fr)[#raw-content#config.input-label], ) grid-args.push[ #output#config.output-label ] container(direction: direction, ..grid-args) } #let global-example(raw-content, eval-prefix: "", eval-suffix: "", ..args) = { context { let all-blocks = () all-blocks.push("#let output = (body) => {}") for block in example-blocks.get() { all-blocks.push(eval-prefix) all-blocks.push(block) all-blocks.push(eval-suffix) } all-blocks.push("#let output = (content) => { content }") all-blocks.push(eval-prefix) let lang = raw-content.at("lang", default: "default") [#metadata(raw-content.text)#label(lang)] standalone-example( raw-content, eval-prefix: all-blocks.join("\n"), eval-suffix: eval-suffix, ..args ) } example-blocks.update(old => { old.push(raw-content.text) old }) } #let raw-with-eval( it, global: auto, langs: config.runnable-langs, block: true, eval-kwargs: (:) ) = { if type(langs) != array { langs = (langs,) } for (ii, lang) in langs.enumerate() { if type(lang) == content and lang.has("text") { langs.at(ii) = regex(lang.text) } } let cur-lang = it.at("lang", default: none) let needs-run = block == it.at("block", default: false) and ( langs == auto or langs.any(el => cur-lang.match(el) != none) ) if not needs-run { it return } [#metadata(cur-lang)<runnable-lang>] if global == auto { global = "global" in cur-lang } if cur-lang != "typ" { // Raw style will be double applied which shrinks text, so preemptively undo the // shrinking set text(size: 1.25em) it = raw(it.text, lang: "typ", block: it.block) } if global { global-example(it, ..eval-kwargs) } else { standalone-example(it, ..eval-kwargs) } }
https://github.com/herbhuang/utdallas-thesis-template-typst
https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/content/acknowledgement.typ
typst
MIT License
First, I'd like to thank coffee for fueling my brain cells and making this thesis possible. A big shoutout to my advisor for your patience and for not laughing (too hard) at my wild ideas. To my family, your snack supplies and constant reminders to "just finish it already" were invaluable. Finally, to my pet, your keyboard sit-ins ensured I took breaks, whether I wanted to or not.
https://github.com/Shedward/dnd-charbook
https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/core/resources.typ
typst
#let icon(name, ..args) = context { let resolvedArgs = if (args.named().len() == 0) { let fontSize = text.size let baseline = 1pt (height: fontSize - baseline, baseline: baseline) } else { args } box(image("../../resources/icons/" + name + ".svg"), ..resolvedArgs) } }
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/descartes/methodischer_zweifel.typ
typst
Other
#import "/src/template.typ": * #let med(page) = en[Vgl. <NAME>: AT VII. S. #page.] == #ix("Der methodische Zweifel", "Zweifel, methodisch") Der #ix("methodische Zweifel", "Zweifel, methodisch") wird in der ersten #ix("Meditation", "Meditationes de prima philosophia") beschrieben. Grundlage ist #ix([Descartes'], "<NAME>") Versuch, sein bisher als sicher geltendes Wissen auf den Prüfstand zu stellen und eine für die Wissenschaft geeignete Grundlage zu finden.#med[17] Die Methode zur Untersuchung ist der radikale, methodische Zweifel: Alles, was zweifelbar ist, soll entfallen.#med[18] Der methodische Zweifel schreitet in drei Stufen voran: 1. *#ix("Argument der Sinnestäuschung"):*#med[18] Die Außenwelt ist real, aber der Zugang über die Sinne ist zweifelhaft. Optische Täuschungen offenbaren nicht immer das, wie die Welt wirklich ist. Da die Welt existiert und die Sinne uns nicht imer täuschen, können wir trotzdem Zugang zur Außenwelt erhalten. Also scheint die Welt und die empirischen Wissenschaften unzweifelbar. 2. *#ix("Traumargument"):*#med[18 f] Die Außenwelt und alle empirischen Wissenschaften sind zweifelhaft, die Welt könnte z.B. nur ein Traum sein. Trotzdem gelten auch in einem Traum die Gesetze der Mathematik und Geometrie. Also scheint die Geometrie und Mathematik unzweifelbar. 3. *#ix("Genius malignus-Argument", "Genius malignus", "Genius malignus-Argument"):*#med[21] Die Regeln der Mathematik und Geometrie sind zweifelhaft. Sie könnten von einem bösen Täuschergott (#ix("<NAME>")) nur vorgespielt sein, er zwingt einen jedes mal, sich zu verrechnen und dies für wahr zu halten. Also ist alles zweifelbar. #set par(justify: false) #grid(columns: (10%, 45%, 45%).map(e => e - 1.5em), row-gutter: 1em, column-gutter: 1.5em, strong[Stufe], strong[Thema im Rahmenplan], strong[Thema bei Descartes], [5], [ - *Verlässlichkeit der Sinne*: Können wir sicher sein, dass uns die Sinne nicht täuschen?#en[Vgl. @MBWKMV1996_RP56[S. 15]] ], [ - Argument der Sinnestäuschung ], [], [ - *Verbindlichkeit der eigenen Wahrnehmung*: Ergibt die Addition Wahrnehmungserfahrungen ein sicheres Bild der Wirklichkeit?#en[Vgl. @MBWKMV1996_RP56[S. 15]] ], [ - methodischer Zweifel als Projekt sicherer Erkenntnis, Ablehnung des Empirismus im Argument der Sinnestäuschung ], [6], align(center + horizon)[/], align(center + horizon)[/], [7], [ - *Träumen und Denken:* Der nächtliche Traum#en[Vgl. @MBWKMV2002_RP710[S. 18]] ], [ - das Traumargument; Wie erkenne ich den Unterschied zwischen Traum und Realität? Wann Träume ich? ], [8/9], [ - *Woher beziehe ich meine Quellen des Wissens? Wie zuverlässig sind diese?*#en[Vgl. @MBWKMV2002_RP710[S. 28]] ], [ - Sind die Sinne verlässliche Wissensquelen? -- Argument der Sinnestäuschung ], [10], [ - *Wege philosophischen Denkens:* Wie gelange ich zu begründeter Einsicht?#en[Vgl. @MBWKMV2002_RP710[S. 34]] ], [ - #ix("methodischer Zweifel", "Zweifel, methodisch") als weg sicherer Erkenntnis, als Methode des Philosophierens ], [], [ - *Regeln logischen Denkens:* Wie urteile und schließe ich korrekt?#en[Vgl. @MBWKMV2002_RP710[S. 34]] ], [ - Wie gut ist die Argumentation im #ix("methodischen Zweifel", "Zweifel, methodisch") ], [], [ - *Strategien empirischer Forschung:* Welches Erkenntnisinteresse leitet die Naturwissenschaften?#en[Vgl. @MBWKMV2002_RP710[S. 34]] ], [ - Wie sehr unterscheidet und/oder gleicht sich die Vorgehensweise der Naturwissenschaften mit Descartes #ix("methodischem Zweifel", "Zweifel, methodisch")? ], [11/12], [ - *Wissen:* Frage nach der Sicherheit von Wissen/Skepsis#en[Vgl. @MBWKMV2019_RP1112[S. 12]] ], [ - methodischer Zweifel als Form des radikalen Zweifels; Ziel zur Grundlegung sicheren Wissens ], [], [ - *Erkenntnis:* dialektische Auseinandersetzung mit Thesen zur menschlichen Erkenntnis, Rationalismus#en[Vgl. @MBWKMV2019_RP1112[S. 12]] ], [ - Denken und Vernunft als reine Methode der Erkenntnis ])
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/tracking-spacing_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test tracking in arabic text (makes no sense whatsoever) #set text(tracking: 0.3em) النص
https://github.com/piepert/typst-seminar
https://raw.githubusercontent.com/piepert/typst-seminar/main/Beispiele/ImSeminarNichtBesprochen/main.typ
typst
// === PAGE SETUP START ====================================== #set page(paper: "a4", footer: align(center, counter(page).display() + " / " + locate(l => counter(page).final(l).first()))) #set text(lang: "de", size: 12pt) #set par(justify: true, first-line-indent: 1.5em, leading: 0.65em) #show par: set block(spacing: 0.65em) #show heading: set block(spacing: 1em) #show raw.where(block: true): it => { set par(justify: false) pad(1em, it) } #let code-example(code, content) = grid(columns: (auto, auto), gutter: 2em, code, pad(1em, content)) #let ssc(body) = strong(smallcaps(body)) #align(center, text(size: 2em, ssc("Was im Seminar nicht besprochen wurde"))) #v(1em) #outline() #v(1em) // === PAGE SETUP END ======================================= = Kompliziertere Funktionen #ssc[Funktionen als Werte.] In Typst ist es möglich, Funktionen als Wert einer Variable zu betrachten. Hier ein Beispiel: #code-example( ```typc let caller(fn) = { [Jetzt wird sie ausgeführt:] fn() } let f() = { lorem(20) } caller(f) ```, { let caller(fn) = { [Jetzt wird sie ausgeführt: ] fn() } let f() = { lorem(20) } caller(f) }) `f` ist also eine Funktion, die einen Blindtext aus 20 Wörtern generiert. `caller` ist eine Funktion, die ein Argument `fn` übernimmt, `[Jetzt wird die Funktion ausgeführt: ]` zurückgibt und dann noch das Ergebnis `fn()`. Also führt es den Code aus, der in `fn` liegt. #ssc[Lambda-Ausdrücke.] Mithilfe sogenannter "Lambda"-Ausdrücke können wir den Code kürzen. Damit kann eine Funktion wie folgt definiert werden: `(k) => k+1`. Diese Funktion nimmt ein Argument `k` und gibt den Wert von `k+1` zurück. (Im Lambda-Ausdruck können, wenn die Funktion nur ein Argument übernimmt, die Klammern auch weggelassen werden. Mehr dazu folgt.) Dieser Lambda-Ausdruck hat keinen Namen und ist daher ein einfacher Wert, keine Variable, und kann damit z.B. in eine Variable gespeichert werden oder als Argument übergeben werden. Hier ein Beispiel: #code-example( ```typc let caller(fn) = { [Jetzt wird sie ausgeführt:] fn() } caller(() => lorem(20)) ```, { let caller(fn) = { [Jetzt wird sie ausgeführt:] fn() } caller(() => lorem(20)) }) Anstatt also `f` zu definieren, können wir einfach den Lambda-Ausdruck `() => lorem(20)` als Funktion übergeben. Die leeren Klammern vor dem `=>` Pfeil heißen einfach, dass der Lambda-Ausdruck keine Argumente übernimmt. #ssc[Warum Lambda-Ausdrücke?] Weil Lambda-Ausdrücke mehr Flexibilität bieten und etwa in den folgenden Abschnitten zu States und Countern wichtig sind. Typst verbietet das Verändern von globalen Variablen, Funktionen können sich keine Werte merken, sondern produzieren mit den gleichen Parametern *immer* die gleiche Ausgabe. Das kann man hiermit teilweise umgehen. #ssc[Erlaubte Notationen.] Typst ist beim Syntax ganz schön variabel. Hier ein paar Beispiele, was alles erlaubt ist (unter anderem mehrzeilige Ausdrücke): ```typc c => c + 1 (e) => { e + 1 } (e,) => { e + 1 } (e, f, g) => { e + f + g } a => { lorem(a) // Das funktioniert natürlich nur, wenn a eine Zahl ist, lorem(a*2) // sonst gibt's einen Fehler. } let f = c => c * 7 // f(3) = 21 ``` = Erweiterte Show-Regeln Es ist möglich in `show`-Regeln Inhalte mehr anzupassen, als im Seminar gezeigt. Dazu werden Ausdrücke verwendet, die ein Argument entgegennehmen. Hier ein Beispiel, in dem alle Überschriften mit "Überschrift:" beginnen sollen: ```typ #show heading: it => [Überschrift: ] + it.body === Wichtiger Text ``` Wird zu: #block(inset: (left: 1em))[ #set heading(outlined: false) // soll ja nicht im Inhaltsverzeichnis auftreten #show heading: it => [Überschrift: ] + it.body === Wichtiger Text ] Ein wichtiger Hinweis muss angebracht werden: es ist möglich rekursive Regeln zu erzeugen, die den Compiler zum Absturz bringen. Hier ein Beispiel: ```typ #show heading: it => heading([Überschrift: ] + it.body) ``` Erzeugt man in der `show`-Regel das Element, das durch diese Regel beeinflusst wird, dann stürzt der Compiler ab, weil er diese Regel versucht rekursiv ohne Abbruchbedingung anzuwenden. = Counter #ssc[Pure Functions.] Ein imperativer (und in Typst nicht-funktionsfähiger) Ansatz zu zählen wäre Folgender: ```typ #let counter = 0 #let step() = { counter += 1; } Hallo #counter! #step() Das zweite Hallo: #counter! ``` Schreibt man diesen Code in Typst, erhält man den folgenden Fehler: `error: variables from outside the function are read-only and cannot be modified`. Das klappt also nicht. Es verstößt auch gegen den Grundsatz von "Pure Functions" in Typst. Eine Funktion kann sich keine Dinge merken und keine Variablen von außen verändern. Mit den gleichen Argumenten gibt eine Funktion immer den gleichen Rückgabewert zurück. _(Fun-Fact: Typst ist wegen genau dieses Prinzips auch so unglaublich schnell. Es kann sich nämlich den Wert der Funktionen merken und muss ihn nicht immer neu berechnen.)_ `step()` übernimmt gar keine Argumente, also muss sie immer den gleichen Rückgabewert haben. Für eine imperative Denkweise ist das problematisch. Wie lösen wir das Problem? #ssc[Lasst uns zählen!] Es geht also trotzdem. Aber wie? Die Antwort: States. Eine spezifische Art dieser States sind Counter. Ohne viel zu reden, hier ein Beispiel: #code-example( ```typ #let my_counter = counter("my_counter") #my_counter.display() \ #my_counter.step() #my_counter.display() \ #my_counter.update(c => c * 3) #my_counter.display() \ ```, [ #let my_counter = counter("my_counter") #my_counter.display() \ #my_counter.step() #my_counter.display() \ #my_counter.update(c => c * 3) #my_counter.display() \ ]) Und zack! Da sind unsere Counter und unsere Lambda-Ausdrücke sind plötzlich nützlich geworden. Doch was passiert hier eigentlich? In der ersten Zeile wird der Counter erstellt, dort hat er bereits den Wert `0`: ```typ #let my_counter = counter("my_counter") ``` Anstatt aber einfach mit `#my_counter` auf den Wert des Counters zugreifen zu können, benötigen wir die Methode `.display()`. Damit kann Typst es in der richtigen Reihenfolge für sich selbst auswerten. Und damit können wir nicht direkt auf den Wert zugreifen und ihn verändern, damit das "Pure Function"-Konzept erhalten bleibt. ```typ #my_counter.display() ``` Mit der Methode `.step()` wird der Counter erhöht. Alternativ kann man den Wert auch mit `.update(1)` auf einen spezigischen Wert (hier `1`) setzen. ```typ #my_counter.step() #my_counter.display() #my_counter.update(1) // Beispiel für Update #my_counter.display() ``` Die `.update()`-Funktion ist sehr mächtig. Man kann ihr statt einem Wert auch eine Lambda-Funktion übergeben. Diese Lambda-Funktion übernimmt den aktuellen Wert, führt den Ausdruck aus und setzt den Wert des Counters auf den Rückgabewert der Funktion. Hier wird der aktuelle Counter-Wert einfach nur verdreifacht, zurückgegeben und in den Counter gespeichert: ```typ #my_counter.update(c => c * 3) #my_counter.display() ``` #ssc[Typische Counter.] Es gibt einige Counter, die standardmäßig definiert sind, wie etwa: #code-example( ```typ #set heading(numbering: "1.") #let page_counter = counter(page) #let heading_counter = counter(heading) = Überschrift == Noch eine Ich bin auf Seite #page_counter.display() und das ist die Überschrift Nummer #heading_counter.display() ```, [ #set heading(outlined: false) // Ich will nicht, dass die Überschriften hier aus // dem Beispiel im Inhaltsverzeichnis auftauchen #set heading(numbering: "1.") #let page_counter = counter(page) #let heading_counter = counter(heading) = Überschrift == Noch eine Ich bin auf Seite #page_counter.display() und das ist die Überschrift Nummer #heading_counter.display() ]) = States Wenn man Counter verstanden hat, werden States genauso verständlich. Anstatt Zahlen wie in Countern, kann man in States _alles_ speichern. Hier ein Beispiel, indem jeder Aufruf einer Funktion einen State verändert. Ein Dictionary mit `list` und einem Zähler `ctr` wird angelegt. Immer, wenn `example` aufgerufen wird, soll `example` die Liste um das Element `ctr+1` erweitern, und dann `ctr` um 1 erhöhen und das Dictionary anzeigen. #code-example( ```typ #let dict_state = state("dict") #state("dict").update((ctr: 0, list: ())) #let example() = { state("dict").update(dict => { dict.at("list").push(dict.ctr+1) dict.at("ctr") += 1 dict }) state("dict").display() } #example() \ #example() \ #example() \ FINALLY: #state("dict").display() ```, [ #let dict_state = state("dict") #state("dict").update((ctr: 0, list: ())) #let example() = { state("dict").update(dict => { dict.at("list").push(dict.ctr+1) dict.at("ctr") += 1 dict }) state("dict").display() } #example() \ #example() \ #example() \ FINALLY: #state("dict").display() ]) = Locate Du willst also unbedingt auf den Wert eines Counters oder States zugreifen? Das geht. Aber nur in einem abgesicherten Bereich. Und ändern darfst du den Wert dadrin nicht! Dieser abgesicherte Bereich ist die `locate`-Funktion: #code-example( ```typ #let my_state = state("my_state") #my_state.update(17) #locate(loc => { my_state.at(loc) + 1 }) ```, [ #let my_state = state("my_state") #my_state.update(17) #locate(loc => { my_state.at(loc) + 1 }) ]) Und wieder ein Lambda-Ausdruck! `locate` nimmt einen Lambda-Ausdruck mit einem Argument. Damit erhält die Funktion die Information, wo sich der Typst-Compiler gerade befindet und kann den richtigen Wert des States raussuchen. Immer, wenn ein `.update()` gemacht wird, wird der Wert gespeichert. Am Ende kennt Typst alle Zustände, die der State hatte. Mit `.at()` kann man auf einen dieser Werte zugreifen. Damit erhält man dann auch tatsächlich den Wert an sich. Aus dem `locate()` bekommt man ihn aber nicht heraus, denn `locate()` gibt Content zurück, hier die `18` als Text formatiert. Soetwas wie ... ```typ #let my_state = state("my_state") #my_state.update(17) // wir wollen 18, die +1 ist heir außerhalb des locates(...) #let added = locate(loc => { my_state.at(loc) }) + 1 // FEHLER! #added // 18 soll ausgegeben werden }) ``` ... ist also nicht möglich. Es gibt den Fehler: `cannot add content and integer`, weil `locate(...) + 1` keine gültige Addition ist, da `locate(...)` Content zurückgibt, was nicht mit Zahlen addiert werden kann. #ssc[Zeitreisen.] Mit States und Countern ist es auch möglich durch die Zeit zu reisen. Mit `.final()` bekommt man den letzten Wert des States am Ende des Dokuments: #code-example( ```typ #let s = state("timetraveler") #let increase_s() = s.update(k => { k.push(k.len()) return k }) Am Ende ist `#s` = #locate(loc => s.final(loc)) Vorher: #s.update((0,1)) #s.display() #increase_s() #s.display() #increase_s() #s.display() ```, [ #set par(first-line-indent: 0em) #let s = state("timetraveler") #let increase_s() = s.update(k => { k.push(k.len()) return k }) Am Ende ist `#s` = #locate(loc => s.final(loc)) Vorher: #s.update((0,1)) #s.display() #increase_s() #s.display() #increase_s() #s.display() ]) = Zu kompliziert? Das Konzept von "Pure Functions", "Lambda Ausdrücken" und "States" in Typst ist nicht einfach. Es beinhaltet viele Ansätze von nicht-imperativen Programmiersprachen. Wie geht man damit am besten um? Die Dokumentation ist natürlich ein guter Anfang, der Discord hilft immer und in allen anderen Fällen: Probieren geht über studieren. Man kann auch mit einem System warm werden, indem man einfach seine Limitationen ausreizt und probiert, was geht und was nicht. Vor den Fehlermeldungen muss man im Gegensatz zu denen bei LaTeX ja keine Angst haben.
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/ea2724-ai_hw/hw5.typ
typst
== HW5 Due 2024.04.18 #let ans(it) = [ #pad(1em)[ #text(fill: blue)[ #it ] ] ] === Question 7.13 7.13 本题考查子句盒蕴含语句之间的关系. a. 证明子句 $(not P_1 or dots.c or not P_m or Q)$ 逻辑等价于蕴含语句 $(P_1 and dots.c and P_m) => Q$. #ans[ $ &(not P_1 or dots.c or not P_m or Q) \ eq.triple & ((not P_1 or dots.c or not P_m) or Q) \ eq.triple & (not (P_1 and dots.c and P_m) or Q) space.quad & "<NAME>" \ eq.triple & ((P_1 and dots.c and P_m) => Q) space.quad & "implication elimination" $ ] b. 证明每个子句 (不管正文字的数量) 都可以写成 $(P_1 and dots.c and P_m) => (Q_q or dot.c or Q_n)$ 的形式, 其中 $p_i$ 和 $Q_i$ 都是命题词. 由这类语句构成的知识库表示为 *蕴含范式* 或称 *Kowalski范式*. #ans[ 将语句表达成 $(not P_1 or dots.c or not P_m or Q_1 or dots.c Q_n)$ 的形式, 则有: $ & (not P_1 or dots.c or not P_m or Q_1 or dots.c Q_n) \ eq.triple & (not P_1 or dots.c or not P_m or Q) \ eq.triple & (P_1 and dots.c and P_m) => (Q_1 or dots.c or Q_n) $ ] c. 写出蕴含范式语句的完整归结规则. #ans[ $ p_q and dots.c p_j and dots.c p_(n_1) => r_1 or dots.c or r_(n_2) \ s_1 and dots.c s_(n_3) => q_1 or dots.c or q_k or dots.c or q_(n_4) \ overline("SUBST"(theta, (p_1 or dots.c p_(j-1) or p_(j+1) or p_1 or p_(n_1) or s_1 or dots.c or s_(n_3) => r_1 or dots.c or r_(n_2) or q_1 or dots.c or q_k or dots.c or q_(n_4)))) $ ] === Question $VV$ 证明. 证明前向链接算法的完备性. #ans[ 证明前向链接算法的完备性, 即证明 FC 可以推出每个被 KB 蕴含的原子语句: - 考查 inferred 表的最终状态(FC 到达不动点之后, 不在出现新的推理), 将这个表推理出的所有符号设为 true, 其他符号设为 false, 将这个表视为一个逻辑模型 m. - 注意到原始 KB 的每个限定子句在这个模型下都为真 - 考虑反证, 如果 $a_1 and dots.c a_k => b$ 在此模型下为假, 那么 $a_1 and dots.c a_k$ 为真, $b$ 为假, 与推理过程矛盾. - 因此 m 是 KB 的一个模型 - $forall q, "KB" |= q$, q 在 KB 的所有模型必须为真. - $q$ 在 m 中为真 $=>$ 在 inferred 表中为真 $=>$ 被 FC 算法推理出来 $qed$ ]
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/math/math-let.typ
typst
Apache License 2.0
#let xmat(..arg) = [..#arg] $ #let g = (i) => $g^#i$ xmat(2, 2, #g) $
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11180.typ
typst
Apache License 2.0
#let data = ( ("SHARADA SIGN CANDRABINDU", "Mn", 0), ("SHARADA SIGN ANUSVARA", "Mn", 0), ("SHARADA SIGN VISARGA", "Mc", 0), ("SHARADA LETTER A", "Lo", 0), ("SHARADA LETTER AA", "Lo", 0), ("SHARADA LETTER I", "Lo", 0), ("SHARADA LETTER II", "Lo", 0), ("SHARADA LETTER U", "Lo", 0), ("SHARADA LETTER UU", "Lo", 0), ("SHARADA LETTER VOCALIC R", "Lo", 0), ("SHARADA LETTER VOCALIC RR", "Lo", 0), ("SHARADA LETTER VOCALIC L", "Lo", 0), ("SHARADA LETTER VOCALIC LL", "Lo", 0), ("SHARADA LETTER E", "Lo", 0), ("SHARADA LETTER AI", "Lo", 0), ("SHARADA LETTER O", "Lo", 0), ("SHARADA LETTER AU", "Lo", 0), ("SHARADA LETTER KA", "Lo", 0), ("SHARADA LETTER KHA", "Lo", 0), ("SHARADA LETTER GA", "Lo", 0), ("SHARADA LETTER GHA", "Lo", 0), ("SHARADA LETTER NGA", "Lo", 0), ("SHARADA LETTER CA", "Lo", 0), ("SHARADA LETTER CHA", "Lo", 0), ("SHARADA LETTER JA", "Lo", 0), ("SHARADA LETTER JHA", "Lo", 0), ("SHARADA LETTER NYA", "Lo", 0), ("SHARADA LETTER TTA", "Lo", 0), ("SHARADA LETTER TTHA", "Lo", 0), ("SHARADA LETTER DDA", "Lo", 0), ("SHARADA LETTER DDHA", "Lo", 0), ("SHARADA LETTER NNA", "Lo", 0), ("SHARADA LETTER TA", "Lo", 0), ("SHARADA LETTER THA", "Lo", 0), ("SHARADA LETTER DA", "Lo", 0), ("SHARADA LETTER DHA", "Lo", 0), ("SHARADA LETTER NA", "Lo", 0), ("SHARADA LETTER PA", "Lo", 0), ("SHARADA LETTER PHA", "Lo", 0), ("SHARADA LETTER BA", "Lo", 0), ("SHARADA LETTER BHA", "Lo", 0), ("SHARADA LETTER MA", "Lo", 0), ("SHARADA LETTER YA", "Lo", 0), ("SHARADA LETTER RA", "Lo", 0), ("SHARADA LETTER LA", "Lo", 0), ("SHARADA LETTER LLA", "Lo", 0), ("SHARADA LETTER VA", "Lo", 0), ("SHARADA LETTER SHA", "Lo", 0), ("SHARADA LETTER SSA", "Lo", 0), ("SHARADA LETTER SA", "Lo", 0), ("SHARADA LETTER HA", "Lo", 0), ("SHARADA VOWEL SIGN AA", "Mc", 0), ("SHARADA VOWEL SIGN I", "Mc", 0), ("SHARADA VOWEL SIGN II", "Mc", 0), ("SHARADA VOWEL SIGN U", "Mn", 0), ("SHARADA VOWEL SIGN UU", "Mn", 0), ("SHARADA VOWEL SIGN VOCALIC R", "Mn", 0), ("SHARADA VOWEL SIGN VOCALIC RR", "Mn", 0), ("SHARADA VOWEL SIGN VOCALIC L", "Mn", 0), ("SHARADA VOWEL SIGN VOCALIC LL", "Mn", 0), ("SHARADA VOWEL SIGN E", "Mn", 0), ("SHARADA VOWEL SIGN AI", "Mn", 0), ("SHARADA VOWEL SIGN O", "Mn", 0), ("SHARADA VOWEL SIGN AU", "Mc", 0), ("SHARADA SIGN VIRAMA", "Mc", 9), ("SHARADA SIGN AVAGRAHA", "Lo", 0), ("SHARADA SIGN JIHVAMULIYA", "Lo", 0), ("SHARADA SIGN UPADHMANIYA", "Lo", 0), ("SHARADA OM", "Lo", 0), ("SH<NAME>", "Po", 0), ("SHARADA DOUBLE DANDA", "Po", 0), ("SHARADA ABBREVIATION SIGN", "Po", 0), ("SHARADA SEPARATOR", "Po", 0), ("SHARADA SANDHI MARK", "Mn", 0), ("SHARADA SIGN NUKTA", "Mn", 7), ("SHARADA VOWEL MODIFIER MARK", "Mn", 0), ("SHARADA EXTRA SHORT VOWEL MARK", "Mn", 0), ("SHARADA SUTRA MARK", "Po", 0), ("SHARADA VOWEL SIGN PRISHTHAMATRA E", "Mc", 0), ("SHARADA SIGN INVERTED CANDRABINDU", "Mn", 0), ("SHARADA DIGIT ZERO", "Nd", 0), ("SHARADA DIGIT ONE", "Nd", 0), ("SHARADA DIGIT TWO", "Nd", 0), ("SHARADA DIGIT THREE", "Nd", 0), ("SHARADA DIGIT FOUR", "Nd", 0), ("SHARADA DIGIT FIVE", "Nd", 0), ("SHARADA DIGIT SIX", "Nd", 0), ("SHARADA DIGIT SEVEN", "Nd", 0), ("SHARADA DIGIT EIGHT", "Nd", 0), ("SHARADA DIGIT NINE", "Nd", 0), ("SHARADA EKAM", "Lo", 0), ("SHARADA SIGN SIDDHAM", "Po", 0), ("SHARADA HEADSTROKE", "Lo", 0), ("SHARADA CONTINUATION SIGN", "Po", 0), ("SHARADA SECTION MARK-1", "Po", 0), ("SHARADA SECTION MARK-2", "Po", 0), )
https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst
https://raw.githubusercontent.com/TJ-CSCCG/tongji-undergrad-thesis-typst/main/.github/ISSUE_TEMPLATE/bug_report.md
markdown
MIT License
--- name: Bug 反馈 about: 通过该 Issue 模板反馈使用 tongji-undergrad-thesis-typst 时的 bug labels: 'type/bug' --- ### 使用平台详情 <!--在你所使用的平台上打勾,或填写你使用的平台--> * [ ] 线上:Typst App * [ ] 本地:Typst * [ ] 不,我使用的是 _________ <!--此外,建议你在下方详细描述你所使用的工具,如编辑器与编译器类型等等--> ### 编译日志 <!--在下方贴出编译时输出的错误日志--> <details><summary><b>报错内容</b> <i>[点击打开]</i></summary> <div> ```log # Paste your log here: ``` </div> </details> ### 文件结构 <!--如果你修改了项目文件结构(例如:将 bib 文件从 bib 目录移出),还请在下方给出当前目录树。如果没有修改的话,还请删除本小节--> ```log ``` ### 问题描述 <!--在下方填写你认为可能存在的问题。如果可以的话,还希望你能够给出你的建议和修改意见--> ### 其他信息 <!--这里用于写有关于上述 bug 的其他信息-->
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/2902-gradient-oklch-panic_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(width: 15cm, height: auto, margin: 1em) #set block(width: 100%, height: 1cm, above: 2pt) // Oklab #block(fill: gradient.linear(red, purple, space: oklab)) #block(fill: gradient.linear(..color.map.rainbow, space: oklab)) #block(fill: gradient.linear(..color.map.plasma, space: oklab))
https://github.com/Isaac-Fate/booxtyp
https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/preface.typ
typst
Apache License 2.0
#let preface(body, title: [Preface]) = { // Do not number or outline the preface heading(numbering: none, outlined: false)[#title] // Preface content body }
https://github.com/PgBiel/typst-oxifmt
https://raw.githubusercontent.com/PgBiel/typst-oxifmt/main/oxifmt.typ
typst
Apache License 2.0
// oxifmt v0.2.1 // For compatibility with pre-0.8.0 Typst types, which were strings #let _int-type = type(0) #let _float-type = type(5.5) #let _str-type = type("") #let _label-type = type(<hello>) #let using-080 = type(type(5)) != _str-type #let using-090 = using-080 and str(-1).codepoints().first() == "\u{2212}" #let using-0110 = using-090 and sys.version >= version(0, 11, 0) #let _arr-chunks = if using-0110 { array.chunks } else { (arr, chunks) => { let i = 0 let res = () for element in arr { if i == 0 { res.push(()) i = chunks } res.last().push(element) i -= 1 } res } } #let _float-is-nan = if using-0110 { float.is-nan } else { x => type(x) == _float-type and "NaN" in repr(x) } #let _float-is-infinite = if using-0110 { float.is-infinite } else { x => type(x) == _float-type and "inf" in repr(x) } #let _strfmt_formatparser(s) = { if type(s) != _str-type { panic("String format parsing internal error: String format parser given non-string.") } let result = () let codepoints = s.codepoints() // -- parsing state -- let current-fmt-span = none let current-fmt-name = none // if the last character was an unescaped { let last-was-lbracket = false // if the last character was an unescaped } let last-was-rbracket = false // -- procedures -- let write-format-span(last-i, result, current-fmt-span, current-fmt-name) = { current-fmt-span.at(1) = last-i + 1 // end index result.push((format: (name: current-fmt-name, span: current-fmt-span))) current-fmt-span = none current-fmt-name = none (result, current-fmt-span, current-fmt-name) } // -- errors -- let excessive-lbracket() = { panic("String format parsing error: Inserted a second, non-escaped { inside a {format specifier}. Did you forget to insert a } somewhere, or to escape the { with {{?") } let excessive-rbracket() = { panic("String format parsing error: Inserted a stray } (doesn't match any { from before). Did you forget to insert a { somewhere, or to escape the } with }}?") } let missing-rbracket() = { panic("String format parsing error: Reached end of string with an open format specifier {, but without a closing }. Did you forget to insert a right bracket, or to escape the { with {{?") } // -- parse loop -- let last-i = none let i = 0 for character in codepoints { if character == "{" { // double l-bracket = escape if last-was-lbracket { last-was-lbracket = false // escape {{ last-was-rbracket = false if current-fmt-span.at(0) == last-i { current-fmt-span = none // cancel this span current-fmt-name = none } if current-fmt-name != none { // if in the middle of a larger span ({ ... {{ <-): // add the escaped character to the format name current-fmt-name += character } else { // outside a span ({...} {{ <-) => emit an 'escaped' token result.push((escape: (escaped: "{", span: (last-i, i + 1)))) } last-i = i i += 1 // '{' is ASCII, so 1 byte continue } if last-was-rbracket { // { ... }{ <--- ok, close the previous span (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name) last-was-rbracket = false } if current-fmt-span == none { // begin span current-fmt-span = (i, none) current-fmt-name = "" } last-was-lbracket = true } else if character == "}" { last-was-lbracket = false if last-was-rbracket { last-was-rbracket = false // escape }} if current-fmt-name != none { current-fmt-name += character } else { result.push((escape: (escaped: "}", span: (last-i, i + 1)))) } last-i = i i += 1 // '}' is ASCII, so 1 byte continue } // delay closing the span to the next iteration // in case this is an escaped } last-was-rbracket = true } else { // { ... {A <--- non-escaped { inside larger {} if last-was-lbracket and (current-fmt-span != none and current-fmt-span.at(0) != last-i) { excessive-lbracket() } if last-was-rbracket { if current-fmt-span == none { // {...} }A <--- non-escaped } with no matching { excessive-rbracket() } else { // { ... }A <--- ok, close the previous span (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name) } } // {abc <--- add character to the format name if current-fmt-name != none { current-fmt-name += character } last-was-lbracket = false last-was-rbracket = false } last-i = i i += character.len() // index must be in bytes, and a UTF-8 codepoint can have more than one byte } // { ... if current-fmt-span != none { if last-was-rbracket { // ... } <--- ok, close span (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name) } else { // {abcd| <--- string ended with unclosed span missing-rbracket() } } result } #let _strfmt_parse-fmt-name(name) = { // {a:b} => separate 'a' from 'b' // (also accepts {a}, {}, {0}, {:...}) let (name, ..extras) = name.split(":") let name = if type(name) != _str-type { name } else if name == "" { none } else if name.codepoints().all(x => x == "0" or x == "1" or x == "2" or x == "3" or x == "4" or x == "5" or x == "6" or x == "7" or x == "8" or x == "9") { int(name) } else { name } (name, extras.join()) } #let _strfmt_is-numeric-type(obj) = { type(obj) in (_int-type, _float-type) } #let _strfmt_stringify(obj) = { if type(obj) == _float-type { if _float-is-infinite(obj) { // Fix 0.12.0 inf string inconsistency if obj < 0 { "-" } else { "" } + "inf" } else { // Fix negative sign not being a hyphen // for consistency with our rich formatting output str(obj).replace("\u{2212}", "-") } } else if type(obj) == _int-type { str(obj).replace("\u{2212}", "-") } else if type(obj) in (_label-type, _str-type) { str(obj) } else { repr(obj) } } #let _strfmt_display-radix(num, radix, signed: true, lowercase: false) = { let num = int(num) if type(radix) != _int-type or num == 0 or radix <= 1 { return "0" } let sign = if num < 0 and signed { "-" } else { "" } let num = calc.abs(num) let radix = calc.min(radix, 16) let digits = if lowercase { ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f") } else { ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F") } let result = "" while (num > 0) { let quot = calc.quo(num, radix) let rem = calc.floor(calc.rem(num, radix)) let digit = digits.at(rem) result = digit + result num = quot } sign + result } #let _strfmt_with-precision(num, precision) = { if precision == none { return _strfmt_stringify(num) } let result = _strfmt_stringify(calc.round(float(num), digits: calc.min(50, precision))) let digits-match = result.match(regex("^\\d+\\.(\\d+)$")) let digits-len-diff = 0 if digits-match != none and digits-match.captures.len() > 0 { // get the digits capture group; its length will be digit amount let digits = digits-match.captures.first() digits-len-diff = precision - digits.len() } else if "." not in result { // 5.0 or something // 0 digits! Difference will be exactly 'precision' digits-len-diff = precision } // add missing zeroes for precision if digits-len-diff > 0 { if "." not in result { result += "." // decimal separator missing } result += "0" * digits-len-diff } result } #let _strfmt_exp-format(num, exponent-sign: "e", base: 10, precision: none) = { assert(_strfmt_is-numeric-type(num), message: "String formatter internal error: Cannot convert '" + repr(num) + "' to a number to obtain its scientific notation representation.") let f = float(num) let exponent = if f == 0 { 1 } else { calc.floor(calc.log(calc.abs(f), base: base)) } let mantissa = f / calc.pow(10, exponent) let mantissa = _strfmt_with-precision(mantissa, precision) (mantissa, exponent-sign + _strfmt_stringify(exponent)) } // Parses {format:specslikethis}. // Rust's format spec grammar: /* format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type fill := character align := '<' | '^' | '>' sign := '+' | '-' width := count precision := count | '*' type := '' | '?' | 'x?' | 'X?' | identifier count := parameter | integer parameter := argument '$' */ #let _generate-replacement( fullname, extras, replacement, pos-replacements: (), named-replacements: (:), fmt-decimal-separator: auto, fmt-thousands-count: 3, fmt-thousands-separator: "" ) = { if extras == none { let is-numeric = _strfmt_is-numeric-type(replacement) if is-numeric { let is-nan = type(replacement) == _float-type and _float-is-nan(replacement) let is-inf = type(replacement) == _float-type and _float-is-infinite(replacement) let string-replacement = _strfmt_stringify(calc.abs(replacement)) let sign = if not is-nan and replacement < 0 { "-" } else { "" } let (integral, ..fractional) = string-replacement.split(".") if fmt-thousands-separator != "" and not is-nan and not is-inf { integral = _arr-chunks(integral.codepoints().rev(), fmt-thousands-count) .join(fmt-thousands-separator.codepoints().rev()) .rev() .join() } if fractional.len() > 0 { let decimal-separator = if fmt-decimal-separator not in (auto, none) { _strfmt_stringify(fmt-decimal-separator) } else { "." } return sign + integral + decimal-separator + fractional.first() } else { return sign + integral } } else { return _strfmt_stringify(replacement) } } let extras = _strfmt_stringify(extras) // note: usage of [\s\S] in regex to include all characters, incl. newline // (dot format ignores newline) let extra-parts = extras.match( // fill align sign # 0 width(from param) width precision(from param) precision spectype regex("^(?:([\\s\\S])?([<^>]))?([+-])?(#)?(0)?(?:(?:(\\d+)|([^.$]+))\$|(\\d+))?(?:\\.(?:(?:(\\d+)|([^$]+))\$|(\\d+|\*)))?([^\\s]*)\\s*$") ) if extra-parts == none { panic("String formatter error: Invalid format spec '" + extras + "', from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'. Try escaping the braces { } with {{ }} if you wanted to insert literal braces.") } let (fill, align, sign, hashtag, zero, width-posarg, width-namedarg, width-lit, precision-posarg, precision-namedarg, precision-lit, spectype) = extra-parts.captures // 'count' type parameters in the spec (width, precision) can be either a literal number (123), // a number referring to a positional argument (123$), or some text referring to a named argument (abc$). // The final $ is mandatory for the last two cases. let parse-count(lit, pos, named, spec-part-name: "unknown") = { if lit != none { int(lit) } else if pos != none { let i = int(pos) assert( pos-replacements.len() > 0, message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but no positional arguments were given (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')." ) assert( i >= 0 and i < pos-replacements.len(), message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but there is no argument at that position (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Please note that positional arguments start at position 0, and are specified in order after the format string in the 'strfmt' call." ) let arg = pos-replacements.at(i) assert( type(arg) == _int-type, message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but it was a(n) '" + type(arg) + "', not an integer (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')." ) int(arg) } else if named != none { assert( named-replacements.len() > 0, message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but no named arguments were given (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')." ) assert( named in named-replacements, message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but there is no argument associated to that name (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Ensure you pass that argument in the 'strfmt' call, e.g. strfmt(\"string {:.myarg$}\", 5.823, myarg: 10)." ) let arg = named-replacements.at(named) assert( type(arg) == _int-type, message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but it was a(n) '" + type(arg) + "', not an integer (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')." ) int(arg) } else { none } } if precision-lit == "*" { panic("String formater error: Precision specification of type `.*` is not supported yet (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Try specifying your desired precision directly on the format spec, e.g. `.5`, or through some argument, e.g. `.name$` to take it from the 'name' named argument.") } let align = if align == "" { none } else if align == "<" { left } else if align == ">" { right } else if align == "^" { center } else if align != none { panic("String formatter error: Invalid alignment in the format spec: '" + align + "' (must be either '<', '^' or '>').") } let width = parse-count(width-lit, width-posarg, width-namedarg, spec-part-name: "width") let width = if width == none { 0 } else { int(width) } let precision = parse-count(precision-lit, precision-posarg, precision-namedarg, spec-part-name: "precision") let hashtag = hashtag == "#" let zero = zero == "0" let hashtag-prefix = "" let valid-specs = ("", "?", "b", "x", "X", "o", "x?", "X?", "e", "E") let spec-error() = { panic( "String formatter error: Unknown spec type '" + spectype + "', from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'. Valid options include: '" + valid-specs.join("', '") + "'. Maybe you specified some invalid formatting spec syntax (after the ':'), which can also prompt this error. Check the oxifmt docs for more information.") } if spectype not in valid-specs { spec-error() } let is-numeric = _strfmt_is-numeric-type(replacement) if is-numeric { let is-nan = type(replacement) == _float-type and _float-is-nan(replacement) let is-inf = type(replacement) == _float-type and _float-is-infinite(replacement) if zero { // disable fill, we will be prefixing with zeroes if necessary fill = none } else if fill == none { fill = " " zero = false } // default number alignment to right if align == none { align = right } // if + is specified, + will appear before all numbers >= 0. if sign == "+" and not is-nan and replacement >= 0 { sign = "+" } else if not is-nan and replacement < 0 { sign = "-" } else { sign = "" } // we'll add the sign back later! replacement = calc.abs(replacement) // Separate integral from fractional parts // We'll recompose them later let integral = "" let fractional = () let exponent-suffix = "" if spectype in ("e", "E") and not is-nan and not is-inf { let exponent-sign = if spectype == "E" { "E" } else { "e" } let (mantissa, exponent) = _strfmt_exp-format(calc.abs(replacement), exponent-sign: exponent-sign, precision: precision) (integral, ..fractional) = mantissa.split(".") exponent-suffix = exponent } else if type(replacement) != _int-type and precision != none and not is-nan and not is-inf { let new-replacement = _strfmt_with-precision(replacement, precision) (integral, ..fractional) = new-replacement.split(".") } else if type(replacement) == _int-type and spectype in ("x", "X", "b", "o", "x?", "X?") { let radix-map = (x: 16, X: 16, "x?": 16, "X?": 16, b: 2, o: 8) let radix = radix-map.at(spectype) let lowercase = spectype.starts-with("x") integral = _strfmt_stringify(_strfmt_display-radix(replacement, radix, lowercase: lowercase, signed: false)) if hashtag { let hashtag-prefix-map = ("16": "0x", "2": "0b", "8": "0o") hashtag-prefix = hashtag-prefix-map.at(str(radix)) } } else { precision = none let new-replacement = if spectype.ends-with("?") { let repr-res = repr(replacement) if using-090 and not using-0110 and type(replacement) == _float-type and "." not in repr-res { // Workaround for repr inconsistency in Typst 0.9.0 and 0.10.0 repr-res + ".0" } else { repr-res } } else { _strfmt_stringify(replacement) } (integral, ..fractional) = new-replacement.split(".") } let decimal-separator = if fmt-decimal-separator not in (auto, none) { _strfmt_stringify(fmt-decimal-separator) } else { "." } let replaced-fractional = if fractional.len() > 0 { decimal-separator + fractional.join(decimal-separator) } else { "" } let exponent-suffix = exponent-suffix.replace(".", decimal-separator) if zero { let width-diff = width - (integral.len() + replaced-fractional.codepoints().len() + sign.len() + hashtag-prefix.len() + exponent-suffix.codepoints().len()) if width-diff > 0 { // prefix with the appropriate amount of zeroes integral = ("0" * width-diff) + integral } } // Format with thousands AFTER zeroes, but BEFORE applying textual prefixes if fmt-thousands-separator != "" and not is-nan and not is-inf { integral = _arr-chunks(integral.codepoints().rev(), fmt-thousands-count) .join(fmt-thousands-separator.codepoints().rev()) .rev() .join() } replacement = integral + replaced-fractional + exponent-suffix } else { sign = "" hashtag-prefix = "" hashtag = false zero = false replacement = if spectype.ends-with("?") { repr(replacement) } else { _strfmt_stringify(replacement) } if fill == none { fill = " " } if align == none { align = left } if precision != none and replacement.len() > precision { replacement = replacement.slice(0, precision) } } // use number prefixes parsed above replacement = sign + hashtag-prefix + replacement if fill != none { // perform fill/width adjustments: "x" ---> " x" if width is 4 let width-diff = width - replacement.codepoints().len() // number prefixes are also considered for width if width-diff > 0 { if align == left { replacement = replacement + (fill * width-diff) } else if align == right { replacement = (fill * width-diff) + replacement } else if align == center { let width-fill = fill * (calc.ceil(float(width-diff) / 2)) replacement = width-fill + replacement + width-fill } } } replacement } #let strfmt(format, ..replacements) = { if format == "" { return "" } let formats = _strfmt_formatparser(format) let num-replacements = replacements.pos() let named-replacements = replacements.named() let unnamed-format-index = 0 let fmt-decimal-separator = if "fmt-decimal-separator" in named-replacements { named-replacements.at("fmt-decimal-separator") } else { auto } let fmt-thousands-count = if "fmt-thousands-count" in named-replacements { named-replacements.at("fmt-thousands-count") } else { 3 } let fmt-thousands-separator = if "fmt-thousands-separator" in named-replacements { named-replacements.at("fmt-thousands-separator") } else { "" } assert( type(fmt-thousands-count) == _int-type, message: "String formatter error: 'fmt-thousands-count' must be an integer, got '" + type(fmt-thousands-count) + "' instead." ) assert( fmt-thousands-count > 0, message: "String formatter error: 'fmt-thousands-count' must be a positive integer, got " + str(fmt-thousands-count) + " instead." ) assert( type(fmt-thousands-separator) == _str-type, message: "String formatter error: 'fmt-thousands-separator' must be a string (or empty string, \"\", to disable), got '" + type(fmt-thousands-separator) + "' instead." ) let parts = () let last-span-end = 0 for f in formats { let replace-by = none let replace-span = none if "escape" in f { replace-by = f.escape.escaped replace-span = f.escape.span } else if "format" in f { let f = f.format let (name, extras) = _strfmt_parse-fmt-name(f.name) if name == none { let fmt-index = unnamed-format-index let amount-pos-replacements = num-replacements.len() if amount-pos-replacements == 0 { panic("String formatter error: Specified a {} (or similar) format to extract positional replacements, but none were given. Try specifying them sequentially after the format string, e.g. strfmt(\"{}, {}\", 5, 1+1) would become \"5, 2\".") } if amount-pos-replacements <= fmt-index { let were-was = if amount-pos-replacements == 1 { "was" } else { "were" } panic("String formatter error: Specified more {} (or similar) formats than positional replacements (only " + str(amount-pos-replacements) + " of them " + were-was + " given!). Please specify the missing positional arguments sequentially after the format string in the 'strfmt' call.") } replace-by = num-replacements.at(fmt-index) unnamed-format-index += 1 } else if type(name) == _int-type { let fmt-index = name let amount-pos-replacements = num-replacements.len() if amount-pos-replacements == 0 { panic("String formatter error: format key '" + str(name) + "' would attempt to get a positional replacement, but none were given after the string. Try specifying positional replacements after the format string in the 'strfmt' call, e.g. strfmt(\"{1}, {0}\", 2, 3) would become \"3, 2\".") } if amount-pos-replacements <= fmt-index { let were-was = if amount-pos-replacements == 1 { "was" } else { "were" } panic("String formatter error: format key '" + str(name) + "', from '{" + f.name.replace("{", "{{").replace("}", "}}") + "}', is not a valid positional replacement position (only " + str(amount-pos-replacements) + " of them " + were-was + " given). Note that the first position is 0. For example, strfmt(\"{1}, {0}\", 2, 3) would become \"3, 2\".") } replace-by = num-replacements.at(fmt-index) } else { // named replacement if name not in named-replacements { panic("String formatter error: format key '" + name + "', from '{" + f.name.replace("{", "{{").replace("}", "}}") + "}', does not match any given named replacement. Try specifying it after the format string, e.g. like so: strfmt(\"Test: {myarg}\", myarg: 1 + 1) would become \"Test: 2\".") } replace-by = named-replacements.at(name) } replace-by = _generate-replacement(f.name, extras, replace-by, pos-replacements: num-replacements, named-replacements: named-replacements, fmt-decimal-separator: fmt-decimal-separator, fmt-thousands-count: fmt-thousands-count, fmt-thousands-separator: fmt-thousands-separator) replace-span = f.span } else { panic("String formatter error: Internal error (unexpected format received).") } // {...}ABCABCABC{...} <--- push ABCABCABC to parts parts.push(format.slice(last-span-end, replace-span.at(0))) // push the replacement string instead of the {...} at the end parts.push(replace-by) last-span-end = replace-span.at(1) } if last-span-end < format.len() { parts.push(format.slice(last-span-end, format.len())) } // join all the string parts (constant parts + formatted parts + escaped parts) parts.join() }