repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/KrisjanisP/lu-icpc-notebook
https://raw.githubusercontent.com/KrisjanisP/lu-icpc-notebook/main/3-geometry.typ
typst
= Geometry == Dot product #grid( columns: 2, gutter: 3em, [ #align(center)[#image("assets/dot.png", width: 10em)] ], [ $ a dot b = |a| |b| cos(theta) $ $ a dot b = a_x b_x + a_y b_y $ $ theta = arccos(frac(a_x b_x + a_y b_y , |a| |b|)) $ ], ) Projection of a onto b: $frac(a dot b, |b|) $ == Cross product $ a times b = |a| |b| sin(theta) = a_x b_y - a_y b_x $ $theta$ is positive if a is clockwise from b == Line-point distance Line given by $a x+b y+c=0$ and point $(x_0, y_0)$. $ "distance" = frac(|a x_0 + b y_0 +c|, sqrt(a^2+b^2)) $ The coordinates of this point are: $ x = frac(b(b x_0 - a y_0)- a c,a^2 + b^2) #h(1em) y = frac(a(-b x_0 + a y_0)- b c,a^2 + b^2) $ == Shoelace formula $ 2A = sum_(i=1)^n space mat(delim:"|", x_i, y_i; x_(i+1), y_(i+1)) , "where" mat(delim: "|", a, b; c, d) = a d - b c $ #block(breakable: false,[ == Circumradius Let $a$, $b$, $c$ be the sides of a triangle and $A$ the area of the triangle. Then the circumradius $R = a b c slash(4A)$. Alternatively, using the Law of Sines: $ R = a/(2 sin(alpha)) = b/(2 sin(beta)) = c/(2 sin(gamma)) $ where $alpha$, $beta$, and $gamma$ are the angles opposite sides $a$, $b$, and $c$ respectively. ]) #block(breakable: false,[ == Law of Sines In any triangle with sides $a$, $b$, $c$ and opposite angles $alpha$, $beta$, $gamma$ respectively: $ frac(a,sin(alpha)) = frac(b,sin(beta)) = frac(c,sin(gamma)) = 2R $ where $R$ is the circumradius of the triangle. This can be rearranged to find any side or angle: $a = 2R sin(alpha)$ and $sin(alpha) = frac(a,2R)$ ]) #block(breakable: false,[ == Law of Cosines In any triangle with sides $a$, $b$, $c$ and opposite angles $alpha$, $beta$, $gamma$ respectively: $ c^2 = a^2 + b^2 - 2 a b cos(gamma) $ ]) #block(breakable: false,[ == Median Length Formulas In any triangle with sides $a$, $b$, $c$, the lengths of the medians $m_a$, $m_b$, $m_c$ from the respective vertices are given by: $ m_a = frac(1, 2) sqrt(2b^2 + 2c^2 - a^2) $ These formulas can be derived using the Apollonius's theorem. ]) #block(breakable: false,[ == Segment to line linear equation Converting segment $((P_x,P_y),(Q_x,Q_y))$ to $A x + B y + C = 0$: $ ( P_y-Q_y)x + (Q_x-P_x)y + (P_x Q_y - P_y Q_x) = 0 $ ]) == Three point orientation ```cpp int orientation(Point p1, Point p2, Point p3){ int val = (p2.y-p1.y)*(p3.x-p2.x)-(p2.x-p1.x)*(p3.y-p2.y); if (val == 0) return 0; // collinear return (val > 0) ? 1 : 2; // clock or counterclock }``` == Line-line intersection From system of linear equations derived Cramer's rule: $ cases(a_1 x + b_1 y = c_1, a_2 x + b_2 y = c_2) => cases(x = (c_1 b_2 - c_2 b_1) slash (a_1 b_2 - a_2 b_1), y = (a_1 c_2 - a_2 c_1) slash (a_1 b_2 - a_2 b_1)) $ If the denominator equals zero, the lines are parallel or coincident. #block(breakable: false,[ == Check if two segments intersect ```cpp bool on_seg(Point p, Point q, Point r) { return (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) } bool do_intersect(Point p1, Point q1, Point p2, Point q2){ int o1 = orient(p1, q1, p2), o2 = orient(p1, q1, q2); int o3 = orient(p2, q2, p1), o4 = orient(p2, q2, q1); if (o1 != o2 && o3 != o4) return true; return (o1==0&&on_seg(p1,p2,q1))||(o2==0&&on_seg(p1,q2,q1))|| (o3==0&&on_seg(p2,p1,q2))||(o4==0&&on_seg(p2,q1,q2)); } ``` ]) #block(breakable: false,[ == Heron's formula Let $a$, $b$, $c$ - sides of a triangle. Then the area $A$ is: $ A = 1/4sqrt((a+b+c)(-a+b+c)(a-b+c)(a+b-c)) $ Numerically stable version: $ a >= b >= c, A = 1/4sqrt((a+(b+c))(c-(a-b))(c+(a-b))(a+(b-c))) $ ]) #block(breakable: false,[ == Graham's scan Constructs convex hull of a set of points. ```cpp void convex_hull(vector<pt>&a, bool coll=false){ pt p = *min_element(all(a), [](const pt&x, const pt&y){ return make_pair(x.y, x.x) < make_pair(y.y, y.x); }); sort(all(a), [](const pt&x, const pt&y){ int ori = orientation(p, x, y); if(ori == 0) return (p.x-x.x)*(p.x-x.x) + (p.y-x.y)*(p.y-x.y) < (p.x-y.x)*(p.x-y.x) + (p.y-y.y)*(p.y-y.y); return ori < 0; }); if(coll){ int i = a.size()-1; while(i>=0 && collinear(a[i], a.back(), p)) i--; reverse(a.b()+i+1, a.e()); } vector<pt> s; for(auto &p : a){ while(s.size() > 1 && !cw(s[s.size()-2], s.back(), p, coll)) s.pop_back(); s.push_back(p); } a = s; } ``` ]) #block(breakable: false,[ == Closest pair of points Finds pair of points with minimum euclidean distance. ```cpp struct pt { ld x, y; int id; }; ld md; pair<int,int> bp; vector<pt> a, t; void ua(const pt&a1, const pt&b1){ // update answer ld d=sqrtl((a1.x-b1.x)*(a1.x-b1.x)+(a1.y-b1.y)*(a1.y-b1.y)); if(d<md){md=d; bp={a1.id,b1.id};} } void rec(int l, int r){ // recursive function if(r - l <= 3){ rep(i, l, r) rep(j, i+1, r) ua(a[i], a[j]); sort(a.b()+l, a.b()+r, [](const pt&x, const pt&y){return x.y<y.y;}); return;} int m = (l + r) >> 1, midx = a[m].x; rec(l, m); rec(m, r); merge(a.b()+l, a.b()+m, a.b()+m, a.b()+r, t.b(), [](const pt&x, const pt&y){return x.y<y.y;}); copy(t.b(), t.b()+r-l, a.b()+l); int ts = 0; rep(i, l, r) if(abs(a[i].x - midx) < md){ for(int j=ts-1;j>=0&&a[i].y-t[j].y<md;j--)ua(a[i],t[j]); t[ts++] = a[i]; } } ``` ])
https://github.com/protohaven/printed_materials
https://raw.githubusercontent.com/protohaven/printed_materials/main/class-handouts/class-wood_103-millwork.typ
typst
#import "/meta-environments/env-templates.typ": * #import "./glossary/glossary_terms.typ": * #show: doc => class_handout( title: "Millwork Clearance", category: "Wood", number: "103", clearances: ("Dust Collection", "Jointer", "<NAME>", "Planer", "<NAME>", "Router Table"), instructors: ("<NAME>",), authors: ("<NAME>", "<NAME>"), draft: true, doc ) // TODO // // [ ] Test the images to make sure they resolve well with a B&W printer = Welcome Welcome to the Millwork and Joinery class at Protohaven! #set heading(offset:1) #include "/common-policy/shop_rules.typ" #include "/common-policy/tool_status_tags.typ" #include "/common-policy/filing_a_tool_report.typ" #set heading(offset:0) #pagebreak() = Millwork and Joinery Safety - Always use eye protection.\ _The machines covered in this class can cause pieces of wood to move unpredictably, and at high speed._ - Always use hearing protection.\ _Power tools can be loud enough to permanently damage your hearing._ - Do not wear loose clothing, long sleeves, jewelry, or gloves.\ _They will get caught in moving parts and cause severe harm._ - Wear closed-toe footwear. - Clean as you go, and keep the floor clean of accumulated debris and sawdust. - Use the appropriate dust collection. - Maintain a balanced stance at all times.\ _Do not lean into the cut, or overreach._ - Disconnect the power before servicing a machine. \ _Unplug any power tool before changing blades, bits, or abrasives._ - Cuts should always be made *with the grain*. \ _Cutting against the grain leads to tearout and chatter. Extreme cases may lead to kickback, or the tool may bind._ - If any adjustment crank or knob feels stiff, #warning([*STOP*]). Check the lock knobs and look for accumulated sawduct that is interfering with the movement. If you feel unsure of something, feel free to ask! #pagebreak() = Introduction == Learning Objectives This class focuses on power tools used to preparing and shaping lumber. After taking this class, you should be comfortable with: - Preparing a square face and edge on the jointer. - Cutting down stock to width on the resaw bandsaw. - Thinning stock to parallel faces on the thickness planer. - Smoothing stock with the drum sander. - Shaping stock with the router table. == Millwork and Joinery Terminology #bow_term #cup_term #twist_term #wind_term #crook_term #check_term #fence_term #gullet_term #kerf_term #set_term #swarf_term #table_term #square_term #flat_term #push_block_term #push_pad_term // = Project Plan // // Prepare a piece of stock, and then shape it on the router table: // // + Joint a face and side of a piece of rough lumber. // + Resaw the workpiece into thinner boards. // + Surface plane the workpiece for thickness and a parallel face. // + Drum sand the workpiece for thickness and finish. // + Profile the edges of the workpiece with the router table. = Tools #set heading(offset:1) #include "/common-tools/woodshop_dust_collection.typ" #include "/common-tools/jointer.typ" #include "/common-tools/resaw_band_saw.typ" #include "/common-tools/planer.typ" #include "/common-tools/drum_sander.typ" #include "/common-tools/router_table.typ" #set heading(offset:0) = Resources #emph([Additional resources go here: - Websites? - Books/Magazines? - YouTube Channels? ]) = Acknowledgments Some definitions used in this document were sourced from the Wikipedia article _Wood Warping_: https://en.wikipedia.org/wiki/Wood_warping The images of wood defects were sourced from Design and Technology Online: https://wiki.dtonline.org/index.php/File:DefectsLabelled.png
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p3_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test default of limit attachments on large operators at display size only $ tack.t.big_0^1 quad \u{02A0A}_0^1 quad join_0^1 $ $tack.t.big_0^1 quad \u{02A0A}_0^1 quad join_0^1$
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/ref-04.typ
typst
Other
#set heading(numbering: (..nums) => { nums.pos().map(str).join(".") }, supplement: [Chapt]) #show ref: it => { if it.element != none and it.element.func() == heading { let element = it.element "[" emph(element.supplement) "-" numbering(element.numbering, ..counter(heading).at(element.location())) "]" } else { it } } = Introduction <intro> = Summary <sum> == Subsection <sub> @intro @sum @sub
https://github.com/AliothCancer/AppuntiUniversity
https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_applicazioni/ossigenatore.typ
typst
= Ossigenatore a Membrana == Saturazione di ossigeno $ "SpO2" = ((P o_2)^n) / ((P_(50))^n + (P o_2)^n) $ - $n:$ fattore che viene dato, *varia in base alla temperatura*.
https://github.com/catppuccin/typst
https://raw.githubusercontent.com/catppuccin/typst/main/template/README.md
markdown
MIT License
# Compiling the template The compiled template `main.typ` is made by running `just build` in the root. Or, by running the private recipe `just build_template`. When run, the file `catppuccin_src.typ` is appended to the header: ```typ #import "@preview/catppuccin:{{version}}": catppuccin, themes, get-palette ``` Where the substring `{{version}}` is replaced with the packages' current version.
https://github.com/MichaelFraiman/TAU_template
https://raw.githubusercontent.com/MichaelFraiman/TAU_template/main/mfraiman-min.typ
typst
// **** imports **** // boxes #import "mfraiman-boxes.typ" as box // problem setup #import "mfraiman-problem.typ" as problem // theorems setup #import "mfraiman-theorem.typ" as th // lists #import "mfraiman-lists.typ" as li // Global parameters for the handout #let g_les_num = state("LessonNumber", 0) #let g_les_date = state("LessonDate", "00.00.2000") #let g_les_name = state("LessonName", "Hello World!") #let g_les_name_header = state("LessonNameHeader", "Hello Header!") #let g_les_num_symb = state("LessonNumberSymbol", "") #let g_sol_disp = state("SolutionsDisplay", false) #let g_answ_disp = state("AnswersDisplay", false) //counters #let ProblemNumber = counter("ProblemNumber") #let InlineCounter = counter("InlineCounter") #let TheoremCounter = counter("TheoremCounter") //lengths #let glob_font_size = 11pt #let glob_baselineskip = glob_font_size * 1.35 //13.6pt #let glob_b = glob_font_size * 2 //22pt #let glob_leading = glob_b - glob_baselineskip #let glob_rel_leading = 0.65em #let glob_parskip = glob_leading + glob_baselineskip / 2 //global fonts #let glob_font_rm = state("FontText", "Meta Serif Pro") #let glob_font_sf = state("FontHead", "Helvetica Neue Pro") // lists #let enum_l = li.enum_l #let enum_big = li.enum_big.with(spacing: glob_b) #let rr = li.rr.with(InlineCounter) //Problem setup #let prob = problem.problem.with( ProblemNumber, //counter used to display problem number (ProblemNumber) InlineCounter, //InlineCounter prob_word: "Problem", prob_punct: ".", display_answer: locate(loc => {g_answ_disp.at(loc)}), display_solution: locate(loc => {g_sol_disp.at(loc)}), les_num: locate(loc => {str(g_les_num.at(loc))}), les_num_symb: locate(loc => {str(g_les_num_symb.at(loc))}) ) #let ex = problem.problem.with( ProblemNumber, //counter used to display problem number (ProblemNumber) InlineCounter, //InlineCounter prob_word: "Example", prob_punct: ".", display_answer: locate(loc => {g_answ_disp.at(loc)}), display_solution: locate(loc => {g_sol_disp.at(loc)}), les_num: locate(loc => {str(g_les_num.at(loc))}), les_num_symb: locate(loc => {str(g_les_num_symb.at(loc))}) ) #let theorem = th.theorem.with( TheoremCounter, name: "Theorem", les_num: locate(loc => {str(g_les_num.at(loc))}), les_num_symb: locate(loc => {str(g_les_num_symb.at(loc))}), body_style: "italic", numbered: true ) #let definition = th.theorem.with( TheoremCounter, name: "Definition", les_num: locate(loc => {str(g_les_num.at(loc))}), les_num_symb: locate(loc => {str(g_les_num_symb.at(loc))}), body_style: "normal", numbered: true ) #let remark = th.theorem.with( TheoremCounter, name: "Remark", les_num: locate(loc => {str(g_les_num.at(loc))}), les_num_symb: locate(loc => {str(g_les_num_symb.at(loc))}), body_style: "normal", numbered: false, name_func: text ) // default setup #set math.equation(numbering: "(1)") //doc style setup #let conf( paper: "a4", head_numbering: "1.1.1", font_rm: ("Meta Serif Pro", "Noto Serif Hebrew", "Noto Naskh Arabic"), font_sf: ("Helvetica Neue LT W1G", "Noto Sans Hebrew", "Noto Sans Arabic"), font_tt: ("Noto Sans Mono", "Helvetica Monospaced W1G", "PT Mono"), font_math: ("STIX Two Math", "STIX Math"), font_header: ("Helvetica Neue LT W1G", "Noto Sans Hebrew", "Noto Sans Arabic"), font_footer: ("Helvetica Neue LT W1G", "Noto Sans Hebrew", "Noto Sans Arabic"), lang: "en", num: 0, date: "00.00.0000", disp: true, name: "<NAME>!", name_header: "<NAME>!", num_symb: "", part: "Tel Aviv University", chapter: "Subject", // info_file: "info", class_id: "00", activity: "Plan", // doc ) = { let w_foot_b = "regular" let w_foot_l = "extralight" let w_foot_th = "thin" let w_foot_eb = "bold" let w_head_b = "medium" let w_head_l = "light" let n_top_above = 1 //number of lines above the header let n_top_below = 1 // same, but below the header let header_font_size = 0.9em let n_bottom_above = 1 let n_bottom_below = 1 let footer_font_size = 0.75em let n_header_height = 0 let n_footer_height = 0 //how many lines fit in the paper (REQUIRES A FIX) let baselines_num = calc.floor(297mm / glob_baselineskip) let paper_excess = 297mm - baselines_num * glob_baselineskip set page( paper: paper, columns: 1, margin: ( left: 2*glob_baselineskip, right: 2*glob_baselineskip, top: ( n_top_above + n_header_height + n_top_below ) * glob_baselineskip, bottom: (n_bottom_above + n_footer_height + n_bottom_below) * glob_baselineskip + paper_excess - 1mm // -1 mm is a fix, because otherwise the last line in the text doesn't fit ), header-ascent: 0%, ) set text( font: font_rm, lang: lang, size: glob_font_size, number-type: "lining", number-width: "tabular", top-edge: "cap-height", bottom-edge: "baseline", //features: ("calt", "case", "salt"), //discretionary-ligatures: true, historical-ligatures: true, fractions: false, ) set par( justify: true, linebreaks: "optimized", leading: glob_rel_leading ) show par: set block( spacing: glob_parskip ) set outline( indent: true, depth: 4 ) set heading( numbering: "§ 1." ) show heading.where( level: 1 ): it => locate( loc => { block( width: 100%, above: glob_b, below: glob_b, )[#{ set align(left) set text( 1em, weight: 900, font: font_sf, stretch: 100% ) if it.numbering != none { counter(heading).display() [ ] } smallcaps(it.body) }] }) /* show heading.where( level: 2 ): it => locate( loc => { block( width: 100%, below: glob_b, above: glob_b )[#{ set align(left) set text( 16pt, weight: 700, font: font_sf ) [§ ] locate(loc1 => { counter(heading).at(loc1).last() }) [. ] smallcaps(it.body) }] }) */ show math.equation: set text( font: font_math, size: 1.05em ) set enum( numbering: { (..nums) => { if nums.pos().len() == 1 { set text(weight: "extrabold") "(" nums.pos().map(str).first() ")" } else { "(" set text(weight: "bold") nums.pos().map(str).first() "." set text(weight: "medium") nums.pos().slice(1).map(str).join(".") ")" } } }, full: true, indent: 0.5em, number-align: start + top, spacing: glob_b * 0.5, tight: false ) show figure.caption: set text(size: 0.7em) g_sol_disp.update(disp) g_les_num.update(num) g_les_num_symb.update(num_symb) glob_font_rm.update(font_rm) glob_font_sf.update(font_sf) doc } #let br_log() = { block( width: 100%, height: glob_baselineskip, //spacing: - 0.5 * glob_baselineskip )[ #align( center + horizon, text(size: 1em)[\u{E065} \u{E065} \u{E065}]) ] }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-29.typ
typst
Other
// Error: 13 expected equals sign #let func(x) // Error: 15 expected expression #let func(x) =
https://github.com/JosephBoom02/Appunti
https://raw.githubusercontent.com/JosephBoom02/Appunti/main/Anno_3_Semestre_2/Diritto_dell_Informatica/Diritto_dell_Informatica.typ
typst
#let title = "Diritto dell'Informatica" #let author = "<NAME>" #set document(title: title, author: author) #show link: set text(rgb("#cc0052")) #show ref: set text(green) #set page(margin: (y: 0.5cm)) #set page(margin: (x: 1cm)) #set text(14pt) #set heading(numbering: "1.1.1.1.1.1") //#set math.equation(numbering: "(1)") #set math.mat(gap: 1em) //Code to have bigger fraction in inline math #let dfrac(x,y) = math.display(math.frac(x,y)) //Equation without numbering (obsolete) #let nonum(eq) = math.equation(block: true, numbering: none, eq) //Usage: #nonum($a^2 + b^2 = c^2$) #let space = h(5em) //Color #let myblue = rgb(155, 165, 255) #let myred = rgb(248, 136, 136) //Shortcut for centered figure with image #let cfigure(img, wth) = figure(image(img, width: wth)) //Usage: #cfigure("Images/Es_Rettilineo.png", 70%) #let nfigure(img, wth) = figure(image("Images/"+img, width: wth)) #set highlight(extent: 2pt) //Code to have sublevel equation numbering /*#set math.equation(numbering: (..nums) => { locate(loc => { "(" + str(counter(heading).at(loc).at(0)) + "." + str(nums.pos().first()) + ")" }) },) #show heading: it => { if it.level == 1 { counter(math.equation).update(0) } }*/ // //Shortcut to write equation with tag aligned to right #let tageq(eq,tag) = grid(columns: (1fr, 1fr, 1fr), column-gutter: 1fr, [], math.equation(block: true ,numbering: none)[$eq$], align(horizon)[$tag$]) // Usage: #tageq($x=y$, $j=1,...,n$) // Show title and author #v(3pt, weak: true) #align(center, text(18pt, title)) #v(8.35mm, weak: true) #align(center, text(15pt, author)) #v(8.35mm, weak: true) // colors #let mygray = rgb(242, 242, 242) #outline() = Concetti giuridici di base #rect(fill: mygray, stroke: 1pt)[Che cos'è una norma giuridica? E una sentenza?] La norma giuridica è un comando o precetto generale ed astratto, alla base dell'ordinamento giuridico, che impone o proibisce un certo comportamento. La sentenza costituisce la giurisprudenza, il frutto dell'attività del giudice. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[I precedenti giurisprudenziali sono vincolanti in Italia? E nei paesi di common law?] No, ma possono essere presi come punto di riferimento. Invece sì. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Fonti del diritto] Regolamenti europei, costituzione, leggi ordinare (d.l. d.lgs.), leggi regionali, regolamenti, usi e consuetudini. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Regolamenti comunitari e direttive comunitarie] I primi vengono subito attuati, sono già leggi dello Stato. Le direttive devono essere recepite tramite d.lgs. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Differenza tra legge, decreto legge e decreto legislativo] La prima deve essere approvata dal Parlamento ed emanata dal PdR. Il d.l. viene emanato dal governo in atti di urgenza e necessità. Il d.lgs. è emanato dal governo con legge delega. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se è stata pubblicata una direttiva ed è scaduto il termine per il recepimento nei singoli ordinamenti giuridici, posso applicare direttamente la direttiva anche in assenza di una legge nazionale?] Sì se è sufficientemente chiara. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa succedese un articolo di un contratto o un regolamento di un'amministrazione locale viola una legge nazionale? Sono validi?] No. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Efficacia della legge nel tempo: in quale momento una legge inizia ad avere efficacia? E quando cessa di avere efficacia?] Se non è stabilito dalla legge stessa, entra in vigore dopo 15 giorni dalla pubblicazione sulla gazzetta ufficiale. Cessa quando viene abrogata (esplicita se viene dichiarata incostituzionale o abrogata, oppure implicita quando i contenuti di una nuova legge superanola vecchia legge). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Efficacia della legge nello spazio] Una legge nazionale è valida in Italia, il regolamento in UE, la legge regionale in una regione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i principali criteri di interpretazione della legge?] L'interpretazione autentica viene data da chi ha emanato la legge, oppure abbiamo l'interpretazione giurisprudenziale, da un giudice. Oppure dagli esperti del diritto, la dottrina. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Persona fisica e persona giuridica] Le società costituite per atto pubblico hanno personalità giuridica, sono titolari di diritti e di doveri (come le società o le associazioni). La persona fisica è la persona umana titolare di diritti e di doveri. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Differenza tra capacità giuridica e capacità di agire] La capacità giuridica è l'insieme dei diritti che si acquisisconosin dalla nascita (vita, nome, salute, integrità fisica, famiglia). La capacità di agire si acquisisce con la maggiore età ed è la capacitàdi compiere atti giuridici, cioè atti rilevanti per l'ordinamento giuridico (comprare una casa, comprare una macchina). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Diritti reali] Diritti che si hanno su un bene, come la proprietà, l'usufrutto, il diritto di abitazione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Obbligazioni e fonti delle obbligazioni] Le obbligazioni nascono da un contratto, da un fatto illecito o da ogni altro atto o fatto idoneo a produrlo. Le fonti sono il contratto o il fatto illecito. L'obbligazione è un diritto a una prestazione personale (soggetto attivo creditore, soggetto passivo debitore). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Requisiti del contratto] Accordo delle parti (il contratto è concluso quando al proponente arriva l'accettazione), causa (deve essere lecita), oggetto (possibile, lecito, determinato, determinabile), forma (quando è prescritta dalla legge sotto pena di nullità). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Nullità e annullabilità del contratto] Il contratto è nullo quando è contrario a norme imperative, cioè quando è contrario all'ordinamento giuridico. Oppure la mancanza dei requisiti all'articolo 1325 (accordo, causa, oggetto, forma) e l'illiceità dei motivi (oggetto o causa illeciti). Invece l'annullabilità si ha quando una delle parti era legalmente incapace di contrattare, quando manca la capacità di agire. Il contratto non è annullabile se il minore ha raggirato la sua minore età, ma potrebbe non essere sufficiente. È annullabile per i vizi del consenso, cioè errore, violenza e dolo (inganno). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Contratti tipici e atipici] I primi sono quelli previsti dall'ordinamento giuridico. Quelli atipici da un altro ordinamento. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il contratto, in generale, deve essere stipulato per iscritto e firmato? E' valido un contratto verbale? Qualiproblemi potrebbero sorgere da un contratto non scritto?] Un contratto verbalepuò essere valido, a meno che la legge non preveda la forma scritta con pena di nullità. = Diritto d'autore #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa tutela la legge sul diritto d'autore?] Le opere dell'ingegno di carattere creativo (qualunque modo o forma di espressione), programmi per l'elaboratore come opere letterarie, banche dati (creazione intellettuale). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Chi è titolare del diritto d'autore?] Il creatore dell'opera. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quando sorge il diritto d'autore?] Al momento della creazione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quanto dura il diritto d'autore?] Per i diritti patrimoniali fino a 70 anni dalla morte dell'autore. Per le opere collettive è 70 anni dalla prima pubblicazione. Per le amministrazioni è 20 anni dalla prima pubblicazione. I diritti morali sono esercitabili dai discendenti e ascendenti o coniuge. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i diritti morali d'autore?] Diritto di rivendicare la paternità dell'opera, integrità dell'opera (opporsi a modificazione dell'opera che crea pregiudizi all'onore e alla reputazione dell'autore), diritto di inedito (decidere se e quando pubblicare l'opera, se l'autore aveva deciso di non pubblicare l'opera, i suoi eredi non potranno farlo) e diritto di pentimento (ritirare l'opera o derivate dal commercio per gravi ragioni morali, con l'obbligo di rimborso verso chi ha acquistato i diritti di utilizzazione economica, è personale e intrasmissibile). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i diritti patrimoniali d'autore?] Dirittidi utilizzazione economica (pubblicazione, riproduzione, distribuzione, elaborazione, noleggio, prestito). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[I diritti patrimoniali devono essere trasferiti tutti insieme o possono essere ceduti separatamente?] Sono indipendenti, quindi possono essere ceduti separatamente. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Diritto di riproduzione, di modificazione, di distribuzione] Il primo è la moltiplicazionein copie in qualunque forma, eccezion fatta per riproduzioni senza rilievo economico e utilizzo legittimo. Il secondo è la trasformazione dell'opera che costituisceun rifacimento sostanziale dell'opera. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Principio di esaurimento comunitario del software] Il diritto di distribuzione dell'originale si esaurisce in CE se la prima vendita o il primo atto di trasferimento è effettuato dal titolare o con il suo consenso. Non si applica alla messa a disposizione on demand. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa sono le libere utilizzazioni?] Ad esempio una citazione di un'opera protetta da diritto d'autore ma con un fine didattico. L'uso lecito. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa sono i diritti connessi?] Sono diritti patrimoniali che spettano a chi permette la fruizione dell'opera. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Come è tutelato il software nell'ordinamento giuridico italiano?] Il software è protetto da diritto d'autore, in qualsiasi forma (sorgente o eseguibile), ma deve essere originale. Non sono protette le idee e i principi. È tutelatala forma espressiva (struttura e sviluppo delle istruzioni che compongono il programma). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Chi è titolare dei diritti patrimoniali sul software? E dei diritti morali?] Autore, altri soggetti, il dipendente. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Differenza tra opera collettiva e opera in comunione] La prima è la riunione di opere di autori distinti che vengono messe insieme da un altro soggetto che coordina il lavoro nel suo complesso e diviene a sua volta autore, con diritti diversi da quelli dagli altri sulle opere. La seconda è un'opera in cui il contributo degli autori è indistinguibile, il diritto d'autore appartiene a tutti gli autori, in tutte le parti che sono uguali, salvo accordo scritto. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Cosa succede se il dipendente di un'azienda sviluppa un software? Di chi sono i diritti morali e patrimoniali?] Il datore di lavoro è titolare del diritto esclusivo di utilizzazione economica sul software se esso è sviluppato nello svolgimento delle sue mansioni o su istruzioni del datore di lavoro, salvo patto contrario. Il diritto morale è sicuramente del lavoratore. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[In che cosa consistono i diritti esclusivi sul software?] Riproduzione, modificazione, distribuzione, il principio di esaurimento. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono le eccezioni per consentire l'interoperabilità?] Se la riproduzione e traduzione del codice sono indispensabili per ottenere le informazioni necessarie per l'interoperabilità. Lecito se le attività sono compiute dal licenziatario o soggetto autorizzato, se le informazioni non sono facilmente accessibili, se le attività sono limitate alle parti del software necessarie. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se sviluppate un software, è necessario registrarlo? E' utile? Perché?] È facoltativa. Può essere utile per fornire una prova dell'esistenza del software e della titolarità dei diritti. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Brevettabilità del software] La concessione dei brevetti software è esclusa, è tutelato dal diritto d'autore, salvo il caso in cui siano parte integrante dell'invenzione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Misure tecnologiche a protezione del software] Tecnologie, dispositivi, componenti aventi lo scopo di impedire o limitare atti non autorizzatidai titolari dei diritti (es. accesso, copia). Le possono apporre i titolari dei diritti d'autore, diritti connessi, costitutori di banche dati. Sono controlli di accesso, protezione o limitazione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Le principali sanzioni (civili, penali, amministrative) a tutela delle opere dell'ingegno] - *Sanzioni civili*: lesione del diritto di utilizzazione economica, con risarcimento e distruzione o rimozione dello stato di fatto. - *Sanzioni penali*: multe per la riproduzione, diffusione di un'opera altrui, messa a disposizione del pubblico, riproduzione di un numero maggiore di esemplari di quelle di cui aveva diritto, duplicazione per profitto. - *Sanzioni amministrative*: il doppio del prezzo di mercato dell'opera per ogni violazione e per ogni esemplare abusivamente duplicato o riprodotto. = Banche di dati e opere multimediali #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali banche di dati possono essere protette in base alla normativa sul diritto d'autore? Tutte o no? Quali caratteristiche devono avere per essere protette?] Sono protette dal diritto d'autore le banche di dati che per la scelta o la disposizione del materiale costituiscono una creazione intellettuale dell'autore. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Definizione di banca di dati] Raccolta di opere, dati o altri elementi ndipendenti sistematicamente o metodicamente disposti ed individualmente accessibili mediante mezzi elettronici o in altro modo. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa è tutelato della banca di dati?] La forma espressiva (struttura, disposizione, scelta dei contenuti). Non si estende al contenuto della base dei dati. Non si estende al software per la costituzione e il funzionamento della banca di dati. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il concetto di creatività/originalità] Per originalità si intende originalità intrinseca nel contenuto. Se non sono originali i dati, la base di dati può essere considerata originale se la disposizione è originale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[L'elenco telefonico è una banca di dati tutelabile? Perché?] No secondo una sentenza, mancano di originalità e creatività. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Banca di dati selettiva e non selettiva] La prima ha un contenuto scelto discrezionalmente dall'autore, che ne costituisce l'originalità. La seconda include tutti i dati possibili sull'argomento senza selezione e l'originalità va cercata nella struttura. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quando sorge il diritto d'autore su una banca di dati?] Quando vi è la creazione dell'opera. Spesso è un'opera collettiva o in comunione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i diritti esclusivi dell'autore di una banca di dati?] Riproduzione, traduzione, distribuzione al pubblico dell'originale o di copie, presentazione, dimostrazione, comunicazione in pubblico. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono le deroghe al diritto d'autore su di una banca di dati?] Accesso o consultazione per scopi didattici, di ricerca scientifica, non svolta nell'ambito di un'impresa. Bisogna indicare la fonte. La riproduzione non è permanente. Oppure impiego per scopi di sicurezza pubblica o per effetto di una procedura amministrativa o giurisdizionale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Uso da parte dell'utente legittimo. Che cosa può fare?] Riproduzione, presentazione, distribuzione, modificazione se necessario per il suo normale impiego. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[In che cosa consiste il diritto del costitutore?] Si dice anche diritto sui generis, è un diritto indipendente e parallelo al diritto d'autore, ha la natura di diritto connesso. Si possono vietare operazioni di estrazione e rimpiego dell'intera base dati, anche di parti non sostanziali. Sono vietate se contrarie alla normale gestione o arrecano pregiudizio al costitutore. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quanto dura il diritto del costitutore?] Dura 15 anni dal momento del completamento della base di dati. Per quelle messe al pubblico 15 anni dal 1° gennaio dell'anno successivo della messa al pubblico. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Perché il legislatore ha riconosciuto il diritto del costitutore?] #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il costitutore deve dare un apporto creativo?] No. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Vi sono eccezioni e limitazioni anche al diritto del costitutore?] Sì, le eccezioni che si applicano al diritto d'autore, le libere utilizzazioni. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Principio di esaurimento comunitario delle banche di dati] La prima vendita di una base di dati o di una copia esaurisce il diritto di controllare la vendita successiva, come il dirittod'autore. Se la base di dati è trasmessa online però è una prestazione di servizi. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa succede se vengono effettuati nuovi investimenti su una banca di dati?] Decorre un nuovo termine di tutela del diritto del costitutore, 15 anni dal completamento della base di dati modificata o dalla sua messa a disposizione del pubblico. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se intende creare un sito web, quali problemi si pone sotto il profilo della proprietà intellettuale? Vi sono altri aspetti legali da considerare? (V. obblighi informativi commercio elettronico, privacy, ecc.)] Non è semplice capire se un sito web possa essere tutelato dal diritto d'autore, può contenere opere dell'ingegno creative protette dal diritto d'autore. La dottrina dice che se il sito web è creativo e originale può essere considerato opera dell'ingegno. = Contratti a oggetto informatico #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il concetto di contratto a oggetto informatico] Il contratto a oggetto informatico è la licenza software, cioè il licenziante cede al licenziatario il diritto di godimento del software e la documentazione accessoria per il tempo stabilito. È un contratto atipico. Non si cede la titolarità del programma o lo sfruttamento economico. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cos'è un contratto?] È l'accordo di due o più parti di costituire, regolare o estinguer un rapporto giuridico patrimoniale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il principio di autonomia contrattuale] Si può determinare liberamente il contenuto di un contratto a patto che sia a norma di legge. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i requisiti del contratto?] L'accordo, la causa, l'oggetto, la forma (può essere prescritta dalla legge a pena di nullità). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quando è concluso un contratto?] Quando la proposta ha conoscenza dell'accettazione dell'altra parte. Si può accettare l'accettazione tardiva se se ne dà avviso all'altra parte. Può essere imposta una forma di accettazione. Se il contratto si esegue senza una preventiva risposta, è concluso all'inizio dell'esecuzione, l'accettante deve avvisare prima dell'esecuzione (pena risarcimento del danno). Oppure la proposta può essere revocata, ma se l'accettante ha intrapreso in buona fese l'esecuzione, il proponente deve risarcire il danno. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[I contratti devono essere stipulati per iscritto/firmati per la loro validità?] Dipende, se la legge detta una forma vincolata, sono validi sono in quella forma. È concessa la forma verbale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono le potenziali criticità di un contratto concluso solo verbalmente?] Laddove dovesse presentarsi una contestazione, in un contratto scritto si ha la certezza dell'accordo, verbalmente no. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Cosa sono le condizioni generali di contratto?] Sono predisposte dai contraenti. Sono efficaci nei confronti dell'altro. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Alcune clausole delle condizioni generali di contratto devono essere specificamente approvate per iscritto? Perché? Può farmi qualche esempio di clausola c.d. vessatoria? Per quale motivo è necessaria una doppia sottoscrizione?] Non hanno effetto se non approvate per iscritto le limitazioni di responsabilità, la facoltà di recedere, di sospendere l'esecuzione o sanciscono per l'altro le decadenze, le limitazioni alle eccezioni, restrizioni coi terzi, tacita proroga o rinnovazione, clausole compromissorie e deroghe. Le clausole vessatorie determinano uno squilibrio di diritti e obblighi tra le parti. Ad esempio limitare le azioni o i diritti del consumatore in caso di inadempimento da parte del professionista o imporre il pagamento di una somma di denaro eccessiva nel caso di ritardo di un adempimento. Si applica la doppia sottoscrizione perché con la prima l'aderente accetta il contenuto delle condizioni generali di contratto non onerose, con la seconda da apporsi in modo specifico il contenuto di quelle vessatorie. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Come si può gestire la doppia sottoscrizione nei contratti online?] Tramite la firma digitale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Contratti conclusi mediante moduli o formulari.] Le clausole aggiunte a mano prevalgono sulle clausole del modulo a favore della parte opposta. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Clausole vessatorie nei contratti con i consumatori.] C'è uno squilibrio di diritti ed obblighi a sfavore del consumatore. L'accettazione deve essere fatta autonomamente e separatamente, altrimenti non hanno effetto. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Contratto di licenza d'uso di software] Licenziante cede al licenziatario il diritto di godimento del sw e la documentazione accessoria per il tempo stabilito. Può essere previsto un corrispettivo. Se la licenza è gratuita si parla di freeware. NON si cede la titolarità del programma, non si cede il diritto di sfruttamento economico. Si tratta di un contratto atipico. Possono essere applicate le norme del codice civile sulla locazione per quantocompatibili e salvo accordo contrario. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se per sviluppare un software Le occorre utilizzare un altro software/libreria scaricato da Internet mediante licenza, a quali clausole della licenza deve prestare attenzione?] Esclusività, trasferibilità, proprietà intellettuale, riservatezza, utilizzo per scopi personali, numero massimo di installazioni. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Garanzie e responsabilità per vizi. Rimedi per l'utilizzatore] Di solito ci sono clausole che escludono la responsabilità. Se il software non permette di ottenere risultati utili, si può restituire o riparare, o sostituire o ottenere un indennizzo. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Licenza "a strappo"] Il software è confezionato in un involucro trasparente che indica le condizioni del contratto: se aperto si accetta il contratto. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Contratto di sviluppo software] Una parte si obbliga a studiare, sviluppare e realizzare un software in base alle richieste dell'altra parte. Se è un imprenditore è un contratto d'appalto di servizi. Se è un professionista è un contratto di prestazione d'opera intellettuale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se dovessero proporLe un contratto di sviluppo software, a quali clausole presterebbe particolare attenzione e perché?] Conformità del software alle specifiche, il tempo e il luogo, l'utilizzo di macchine, parti da sviluppare separatamente, collaudo, costo, diritti di proprietà intellettuale, responsabilità dei danni. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Appalto e contratto d'opera intellettuale] Nel primo caso, una parte assume con organizzazione dei mezzi e gestione a proprio rischio il compimento di un'opera per conto di un'altra parte, c'è l'obbligo di risultato, divieto di subappalto senza autorizzazione del committente. Nel secondo caso, l'obbligo viene assunto da un professionista e non ha un obbligo di risultato, ma un obbligo di mezzi. = Proprietà industriale #rect(fill: mygray, stroke: 1pt)[Che cosa tutela la proprietà industriale?] Marchi, indicazioni geografiche, disegni, modelli, invenzioni, topografie dei prodotti a semiconduttori, segreti commerciali, nuove varietà vegetali. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quando sorgono e come si acquisiscono i diritti di proprietà industriale?] Mediante brevettazione per le invenzioni e registrazione per i marchi. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[I marchi oggetto di registrazione] Tutti i segni, le parole i nomi di persone, i disegni, le lettere, le cifre, i suoni, la forma del prodotto o della confezione purché servanoa distinguere i prodotti o servizi e ad essere rappresentati nel registro in modo tale da consentire alle autorità di determinare chiaramente l'oggetto della protezione. Un marchio si può registrare per una o più classi. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali segni non possono essere registrati come marchi?] I segni simili per prodotti o servizi identici o affini, o distintivi, conta anche la notorietà. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il requisito di novità] Non si possono registrare marchi che in base alla notorietà di un marchio già esistente può portare a confusione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali segni non possono essere oggetto di tutela per mancanza di capacità distintiva?] I segni divenuti di uso comune nel linguaggio corrente o usi costanti nel commercio. Denominazione generiche, salvo i segni che a seguito dell'uso e prima della domanda di registrazione abbiano acquistato carattere distintivo. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Chi può registrare un marchio?] Chiunque, ma hanno diritto chi utilizza per il commercio o prestazione di servizi, non chi presenta domanda in mala fede, le amministrazioni dello Stato. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i diritti del titolare di un marchio registrato?] Uso esclusivo, diritto di vietare ai terzi l'uso di un segno identico o simile per prodotti identici o affini, anche non affini se il marchio ha rinomanza. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono le limitazioni al diritto di marchio?] Non si può vietare l'uso nell'attività economica, purché valgano i principi della correttezza professionale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il trasferimento del marchio] Il marchio può essere trasferito o concesso in licenza per la totalità o una parte dei prodotti o servizi per i quali è stato registrato, salvo la violazione delle condizioni di licenza da parte del licenziatario. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quando/come sorgono i diritti esclusivi su di un'invenzione industriale?] Con il brevetto. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il brevetto per invenzione industriale] Sono brevettabili le invenzioni di ogni settore della tecnica nuove che implicano un'attività inventiva e sono destinate all'applicazione industriale. È escluso per le scoperte, teorie, piani, principi, programmi in quanto tali (sono brevettabili solo se danno un risultato tecnico). #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il requisito di novità delle invenzioni] Nuovo vuol dire non compreso allo stato della tecnica. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il concetto di priorità] Quando si fa una domanda di deposito di brevetto ha 12 mesi di tempo per decidere in quali paesi far valere ilbrevetto. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il concetto di attività inventiva] Un'invenzione implica un'attività inventiva se per una persona esperta essa non risulti evidentemente allo stato della tecnica. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il concetto di industrialità] Si tratta di applicazione industriale se un'invenzione può essere fabbricata o utilizzata in qualsiasi industria, compresa quella agricola. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Come si fa domanda di brevetto?] Online sul sito di UIBM, presso qualunque Camera di Commercio, tramite posta all'UIBM. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Cosa sono le rivendicazioni?] Si intende ciò che debba formare oggetto del brevetto. La descrizione e i disegni servono ad interpretare le rivendicazioni, per avere un'equa protezione al titolare e una sicurezza giuridica ai terzi. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono gli effetti della brevettazione?] Decorrono dalla pubblicazione della domanda, 18 mesi dopo il deposito o 90 giorni se il richiedente ha dichiarato di volerla pubblicare immediatamente. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Qual è la durata di un brevetto?] Stessi diritti del brevetto italiano a decorrenza dalla data di pubblicazione sul Bollettino europeo. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[In che cosa consistono i diritti morali? E quelli patrimoniali?] I primi sono di essere riconosciuti autori e alla morte da discendenti o ascendenti. I secondi sono alienabili e trasmissibili. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Le invenzioni dei dipendenti] Nel primo caso idiritti spettano al datore di lavoro se l'attività inventiva è posta come oggetto del contratto e retribuita. Se non è retribuita e l'invenzione è fatta in adempimento di un contratto, i diritti sono del datore di lavoro, ma spetta al lavoratore un equo premio. Altrimenti se l'invenzione rientra nel campo di attività del datore di lavoro, esso ha il diritto di opzione per l'uso, l'acquisto del brevetto, la facoltà di chiedere brevetti all'estero, e dovrà pagare un canone al lavoratore; ha diritto di opzione per 3 mesi dalla comunicazione del deposito della domanda di brevetto. L'invenzione del dipendente è tale se fatta durante l'esecuzione del contratto o entro un anno da quando l'inventore ha lasciato l'azienda o amministrazione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[La nullità del brevetto] Il brevetto è nullo se l'invenzione non è brevettabile, se non è descritta in modo sufficientemente chiaro, se l'oggetto si estende oltre il contenuto della domanda iniziale, se il titolare non aveva diritto di ottenerlo. La nullità può essere parziale. Ilbrevetto nullo può produrre gli effetti di un diverso brevetto. Il titolare del brevetto convertito può entro 6 mesi presentare una domanda di correzione del brevetto. Se il brevetto prevede un prolungarsi dei tempi chi ha investito per sfruttare la brevettabilità dopo il vecchio termine ha diritto a ottenere una licenza obbligatoria e gratuita per il periodo di maggior durata. Ha effetto retroattivo ma non pregiudica atti eseguiti o contratti eseguiti e pagamenti a titolo di equo premio, canone o prezzo. = Protezione dei dati personali #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Chi ha diritto alla protezione dei dati personali?] Le persone fisiche, non quelle giuridiche. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[A quali trattamenti di dati si applica il Regolamento sulla protezione dei dati persona?] Si applica al trattamento di dati personali automatizzati o non automatizzati in archivio. Non si applica alle persone fisiche in attività personali o domestiche e ad autorità competenti a fini di prevenzione di reati. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Ambito di applicazione territoriale - Ambito di applicazione materiale] Il primo dice che il regolamento si applica a titolari o responsabili stabiliti nell'UE o non stabiliti nell'UE se riguarda dati di interessati che si trovano nell'UE per l'offerta di beni o prestazione di servizi o per monitorare il loro comportamento all'interno dell'UE. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se tratto dati personali per scopi esclusivamente personali sono soggetto al Regolamento?] No. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cos'è un dato personale?] Qualsiasi informazione di una persona fisica identificata o identificabile direttamente o indirettamento, come il nome, ID, ubicazione, codice fiscale. Si distinguono in comuni e sensibili. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa si intende per trattamento? Esempi di attività che costituiscono un trattamento di dati personali] Qualsiasi operazione o insieme di operazioni compiute con o senza ausilio di processi automatizzati per la raccolta, registrazione, conservazione, uso, consultazione, modifica dei dati personali. Degli esempi sono la profilazione e la pseudonimizzazione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se memorizzate il cellulare di un vostro compagno di corso che incontrate in giro dovete fornirgli l'informativa privacy? Si/no? Perché?] No, perché un uso personale. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[L'indirizzo IP/un nickname sono dati personali? Perché?] Sì, perché identificano indirettamente una persona fisica. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il Regolamento si applica ai dati anonimi? Quand'è che un dato è anonimo?] Il dato anonimo non si sa a chi può essere riferita, ma può diventare dato personale se collegato a informazioni di diversa natura e risulti idoneo a identificare un soggetto. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Cosa significa anonimizzare e pseudonimizzare un dato?] Anonimizzare un dato vuol dire rendere il dato non riconducibile alla persona. Pseudonimizzare il dato vuol dire rendere un dato personale riconducibile alla persona esclusivamente solo se associati ad altri dati. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Chi sono i soggetti coinvolti nel trattamento? (= Titolare, Responsabile, Interessato, Soggetto designato, DPO)] Il titolare determina le finalità e i mezzi del trattamento. Il responsabile tratta i dati personali per conto del titolare. L'interessato è la persona fisica a cui si riferiscono i dati personali. Il DPO svolge numerosi compiti di supporto all'applicazione del regolamento. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Come si fa a nominare un responsabile del trattamento? Posso farlo a voce?] Sempre tramite atto scritto con le generalità, i compiti, le funzioni. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Secondo quali principi fondamentali deve essere effettuato un trattamento?] Liceità, correttezza e trasparenza, limitazione della finalità, minimizzazione dei dati, esattezza, limitazione della conservazione, integrità e riservatezza, responsabilizzazione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Liceità del trattamento (6 condizioni)] Almeno una delle condizioni deve essere soddisfatta. + L'interessato ha espresso il consenso. + Il trattamento è necessario all'esecuzione di un contratto o le misure precontrattuali. + Il trattamento è necessario per adempiere un obbligo legale. + Il trattamento è necessario per la salvaguardia degli interessi vitali dell'interessato o di un'altra persona fisica. + Il trattamento è necessario per l'esecuzione di un compito di interesse pubblico o connesso. + Il trattamento è necessario per legittimo interesse del titolare. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Trattamento di categorie particolari di dati personali] Non si devono trattare dati personali su razza o etnia, politica, religione, filosofia, appartenenza sindacale, genetica, biometrica, salute, vita sessuale. Sono i dati sensibili. Non vale se l'interessato ha prestato il consenso esplicito per finalità specifiche o se è necessario per assolvere obblighi sul diritto al lavoro, protezione sociale, se è necessario in sede giudiziaria, se è di interesse pubblico rilevante. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se qualcuno intende trattare i Suoi dati personali, a quali adempimenti è tenuto per rispettare la normativa?] Deve attuare misure tecniche adeguate, come la pseudonimizzazione quando deve determinare i mezzi di trattamento e all'atto del trattamento stesso. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Per quanto tempo posso conservare dei dati personali?] Per un tempo non superiore al conseguimento delle finalità per cui sono trattati. Altrimenti di più a fini di archiviazione nel pubblico interesse. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cos'è l'informativa? Chi la deve fornire? Quale contenuto ha (esempi)? Ha un contenuto obbligatorio minimo? Quando deve essere fornita? Può non essere fornita?] L'informativa deve contenere l'identità del titolare, i dati di contato del DPO, le finalità e la base giuridica, i destinatari dei dati, l'intenzione di trasferirli a un paese terzo, il periodo di conservazione, i diritti dell'interessato, il diritto di revoca, il diritto di reclamo, se è un requisito necessario, la notifica diun processo decisionale automatizzato come la profilazione. La fornisce il titolare del trattamento. È un obbligo del GDPR. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Quali sono i diritti dell'interessato?] Accesso, rettifica, integrazione, cancellazione (oblio), limitazione del trattamento, portabilità dei dati, opposizione. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Il consenso. Deve sempre essere richiesto per poter trattare dati personali a norma di legge? Quali caratteristiche deve avere? Se l'interessato tace, vale come consenso?] Non sempre, è necessario per quanto riguarda il trattamento di dati sensibili, ma non serve per investigazioni o in ambito della regolare attività d'impresa. No se non si riesce a dimostrare che l'interessato abbia dato il consenso. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Vi sono casi in cui non occorre il consenso? Quali (esempi)?] Sì, per esempio per tutelare la salute o il diritto alla vita dell'interessato. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Obblighi e responsabilità del Titolare: misure tecniche e organizzative] Lo deve fare per proteggere i dati con la minimizzazione, garantire il soddisfacimento dei requisiti del regolamento e tutelare i diritti degli interessati. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Articolo 25 del GDPR : Protezione dei dati fin dalla progettazione e protezione dei dati per impostazione predefinita] 1. Tenendo conto dello stato dell'arte e dei costi di attuazione, nonché della natura, dell'ambito di applicazione, del contesto e delle finalità del trattamento, come anche dei rischi aventi probabilità e gravità diverse per i diritti e le libertà delle persone fisiche costituiti dal trattamento, sia al momento di determinare i mezzi del trattamento sia all'atto del trattamento stesso il titolare del trattamento mette in atto misure tecniche e organizzative adeguate, quali la pseudonimizzazione, volte ad attuare in modo efficace i principi di protezione dei dati, quali la minimizzazione, e a integrare nel trattamento le necessarie garanzie al fine di soddisfare i requisiti del presente regolamento e tutelare i diritti degli interessati. 2. Il titolare del trattamento mette in atto misure tecniche e organizzative adeguate per garantire che siano trattati, per impostazione predefinita, solo i dati personali necessari per ogni specifica finalità del trattamento. Tale obbligo vale per la quantità dei dati personali raccolti, la portata del trattamento, il periodo di conservazione e l'accessibilità. In particolare, dette misure garantiscono che, per impostazione predefinita, non siano resi accessibili dati personali a un numero indefinito di persone fisiche senza l'intervento della persona fisica. 3. Un meccanismo di certificazione approvato ai sensi dell'articolo 42 può essere utilizzato come elemento per dimostrare la conformità ai requisiti di cui ai paragrafi 1 e 2 del presente articolo. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Responsabile del trattamento: spiegare il ruolo e le responsabilità] Tratta i dati per conto del titolare, fornisce garanzie sufficienti per mettere in atto misure tecniche e organizzative adeguate. Può nominare un subresponsabile con autorizzazione del titolare. Questo è il DP, non il DPO. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Registri delle attività di trattamento del Titolare e del Responsabile: cosa sono, chi è tenuto a predisporli, in quale forma? Cosa devono contenere? Perché sono importanti?] Li devono tenere tutte le imprese con più di 250 dipendenti; le imprese con meno di 250 dipendenti devono tenerlo se il trattamento rappresenta un rischio per i diritti e le libertà dell'individuo, o non sia un trattamento occasionale o includa il trattamento di particolari categorie di dati. Va tenuto in forma scritta, anche elettronica. Il registro del titolare deve contenere nome e dati di contatto del titolare e del DPO, le finalità del trattamento, la descrizione delle categorie di interessati e delle categorie dei dati personali, le categorie di destinatari, trasferimenti verso paesi terzi, termini ultimi per la cancellazione di dati, descrizione generale delle misure di sicurezza tecniche. Il registro del responsabile deve contenere nome e dati di contatto del responsabile, di ogni titolare per cui agisce e del DPO, le categorie dei trattamenti, i trasferimenti verso paese terzo, l'identificazione del paese terzo, descrizione delle misure di sicurezza tecniche. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Sicurezza del trattamento - misure di sicurezza tecniche e organizzative] Il titolare deve garantire e dimostrare che il trattamento è effettuato in modo conforme al regolamento. Le misure sono riesaminate e aggiornate. Si attuano politiche adeguate all'attività di trattamento, come il codice di condotta o un meccanismo di certificazione. Si tiene conto di perdita o accesso illegale ai dati trattati. Degli esempi sono pseudonimizzazione, cifratura, capacità di assicurare riservatezza, integrità, di ripristinare l'accesso, di testare l'efficacia delle misure. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Articolo 24 del GDPR: Responsabilità del titolare del trattamento] 1. Tenuto conto della natura, dell'ambito di applicazione, del contesto e delle finalità del trattamento, nonché dei rischi aventi probabilità e gravità diverse per i diritti e le libertà delle persone fisiche, il titolare del trattamento mette in atto misure tecniche e organizzative adeguate per garantire, ed essere in grado di dimostrare, che il trattamento è effettuato conformemente al presente regolamento. Dette misure sono riesaminate e aggiornate qualora necessario. 2. Se ciò è proporzionato rispetto alle attività di trattamento, le misure di cui al paragrafo 1 includono l'attuazione di politiche adeguate in materia di protezione dei dati da parte del titolare del trattamento. 3. L'adesione ai codici di condotta di cui all'articolo 40 o a un meccanismo di certificazione di cui all'articolo 42 può essere utilizzata come elemento per dimostrare il rispetto degli obblighi del titolare del trattamento. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Notifica violazioni dei dati (data breach): in che cosa consiste? Cosa si deve fare?] Il titolare deve notificare la violazione al Garante privacy entro 72 ore a meno che la violazione non presenti un rischio per i diritti e le libertàdelle persone fisiche. Il responsabile deve informare il titolare. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Comunicazione violazioni dei dati (data breach): in che cosa consiste? Cosa si deve fare?] Se la violazione dei dati presenta un rischio elevato per i diritti e le libertà delle persone fisiche il titolare deve comunicare la violazione all'interessato. A meno che il titolare abbia attuato misure di protezione tecniche e organizzative, le abbia adottate successivamente per scongiurare un rischio elevato o se la comunicazione richiederebbe sforzi sproporzionati, si procede con una comunicazione pubblica in quest'ultimo caso. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Valutazione d'impatto sulla protezione dei dati] Se un tipo di trattamento ha un rischio elevato per i diritti e le libertà delle persone fisiche, prevedendo l'uso di nuove tecnologie, il titolare deve effettuare prima di procedere al trattamento una valutazione dell'impatto dei trattamenti previsti sulla protezione dei dati personali, una singola valutazione può esaminare trattamenti simili con rischi analoghi. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Responsabile della Protezione dei Dati (DPO): quando deve essere nominato, ruolo, compiti] Deve essere nominato da tutte le aziende del settore pubblico. Nel settore privato va nominato quando il titolare effettua trattamenti su larga scala di categorie particolaridi dati personali. Deve informare e fornire consulenza al titolare e ai dipendenti del trattamento, sorvegliare l'osservanza del regolamento, fornire pareri sulla valutazione d'impatto, cooperare con l'autorità di controllo. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Trasferimenti di dati extra UE: a quali condizioni sono consentiti?] Decisioni di adeguatezza, garanzie adeguate, per esempio norme vincolanti d'impresa, clausole contrattuali simili al regolamento. In mancanza delle precedenti, con il consenso dell'interessato, se necessario per conclusione o esecuzione di un contratto, giurisprudenza, interesse pubblico, interessi vitali dell'interessato o di altre persone o se il trasferimento avviene da un registro pubblico. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[A quali condizioni possono essere inviati SMS, e-mail pubblicitarie?] È possibile se si può dimostrare di aver ottenuto il consenso esplicito e sistematico dell'interessato. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Qual è l'attuale disciplina per le telefonate pubblicitarie? Cosa può fare per tutelarsi? Il Registro pubblico delle opposizioni?] Diventano reato le telefonate pubblicitarie se si registra il numero al Registro pubblico delle opposizioni. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Se un'impresa ha un sito web (es. di e-commerce), quali sono i principali problemi di privacy che deve affrontare?] Se tratta dati deve mostrare in chiaro l'informativa della privacy policy con i tipi di dati che vengono trattati, i destinatari, come vengono trattati. = Firme elettroniche e documenti digitali #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cosa si intende per documento?] Possiamo inquadrarlo come scritture private, riproduzioni meccaniche, atti pubblici, non c'è una definizione precisa nell'ordinamento. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Scrittura privata] Fa piena prova fino a querela di falso, la firma non deve essere disconosciuta. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Atto pubblico] È un documento redatto da un notaio o altro pubblico ufficiale autorizzato, dà certezza ufficiale e può essere contestato. Degli esempi sono l'atto di compravendita immobiliare o l'atto di costituzione di società di capitali. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Riproduzioni meccaniche] Ogni rappresentazione meccanica di fatti e cose (fotografie, fonogrammi, informatica, cinematografica) costituiscono piena prova se colui contro il quale sono prodotte non né disconosce la conformità. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Concetto di firma elettronica, firma elettronica avanzata, qualificata e digitale. Definizione ed effetti giuridici] La firma elettronica sono dati in forma elettronica acclusi o connessi ad altri dati elettronici usati per firmare. La firma avanzata è una firma elettronica connessa unicamente al firmatario, idonea a identificare il firmatario, la può usare il firmatario sotto il proprio esclusivo controllo, è collegata ai dati sottoscritti. La firma qualificata è avanzata e creata da un dispositivo per la creazione di una firma qualificata e basata su un certificato qualificato. A una firma elettronica non sono negati gli effetti giuridici, la firma qualificata ha effetti di firma autografa, se rilasciata in UE è qualificata in UE. La firma digitale è una firma qualificata basata su crittografia asimmetrica. Le firme qualificate o digitali sono valide se è associabile un riferimento temporale opponibile. #line(length: 100%) #rect(fill: mygray, stroke: 1pt)[Che cos'è un certificato qualificato? Quali sono le principali informazioni che contiene?] È un attestato elettronico che convalida la firma elettronica, è rilasciato da un fornitore di servizi. Contiene il nome o pseudonimo del firmatario, il periodo di validità, la firma elettronica avanzata o sigillo del prestatore di servizi fiduciari qualificato che rilascia il certificato.
https://github.com/kicre/note
https://raw.githubusercontent.com/kicre/note/main/study/毕设/4-19中期答辩.typ
typst
#import "../../tem/beamer.typ": beamer #show: beamer.with( title: "基于 SAM 大模型的肝脏肿瘤分割软件开发", subtitle: "4-19 中期答辩", author: "答辩人:王恺 指导老师:刘琨", date: "质量技术监督学院 2020级测控普通班 2024-04-19", ) = 项目介绍 == 背景 === 准确分割肝脏肿瘤在医学图像领域的重要性 肝脏肿瘤作为常见的恶性肿瘤之一,其早期发现和治疗对提高患者生存率至关重要。优秀的肝脏肿瘤分割软件能够帮助医生提供更精确的分割结果,减少工作量,提高患者的存活率。 === 工程背景 深度学习技术在图像分割领域取得了显著进展,特别是U-Net、V-Net等模型目前在肝脏肿瘤分割上的应用较为广泛。然而,这些模型通常需要大量标注数据进行训练,且迁移能力有限。 #align( center + horizon, figure( image(width: 20%, "U-net.png"), caption:[U-net] ) ) = 研究方案 == 使用 SAM 模型进行肝脏肿瘤图像分割 SAM 是一种基于Vision Transformer架构的图像分割模型。它通过大规模预训练学会了理解和处理各种图像特征。SAM模型的一个关键特点是它的零样本(zero-shot)学习能力,即模型能够在没有直接在特定任务上训练的情况下,通过理解用户的提示(如文本描述、点击或框选)来执行分割任务。 == SAM 的优势 - 强大的特征学习:SAM在大量自然图像上进行预训练,学习到了丰富的视觉特征,这些特征对于理解医学图像中的肿瘤区域非常有用。 - 泛化能力:SAM能够泛化到新的数据集和任务上,这意味着它可以适应不同的医学图像和肿瘤类型。 - 端到端分割:SAM可以直接从原始图像输出分割掩码,无需复杂的预处理或后处理步骤。 - 易于集成:SAM 的 API 和工具设计使得它容易集成到现有的医疗影像分析流程中,为研究调试和软件开发提供了便利。 = 项目进展 == 数据预处理 ```py lower_bound = -500 upper_bound = 1000 image_data_pre = np.clip(image_data, lower_bound, upper_bound) image_data_pre = (image_data_pre - np.min(image_data_pre))/(np.max(image_data_pre)-np.min(image_data_pre))*255.0 image_data_pre[image_data==0] = 0 image_data_pre = np.uint8(image_data_pre) ``` === 将医学图像常用 `.nii` 格式转化为 NPY 图像格式 ```py import os import SimpleITK as sitk import numpy as np # 输入和输出文件夹路径 input_folder = 'input_folder' output_folder = 'output_folder' # 获取输入文件夹中所有的.nii.gz文件 input_files = [f for f in os.listdir(input_folder) if f.endswith('.nii.gz')] # 遍历每个.nii.gz文件并转换为.npz格式 for file_name in input_files: # 读取.nii.gz文件 image = sitk.ReadImage(os.path.join(input_folder, file_name)) image_array = sitk.GetArrayFromImage(image) # 保存为.npz格式 np.savez_compressed(os.path.join(output_folder, file_name.replace('.nii.gz', '.npz')), image=image_array) print("Conversion completed.") ``` === 将数据集分割为训练集与测试集 ```py import numpy as np # 假设data是你的数据集,包括特征和标签 data = np.random.randn(100, 10) labels = np.random.randint(0, 2, size=100) # 定义训练集和测试集的比例 train_ratio = 0.8 test_ratio = 1 - train_ratio # 随机打乱数据集的索引 indices = np.random.permutation(data.shape[0]) # 计算训练集和测试集的样本数量 train_samples = int(data.shape[0] * train_ratio) test_samples = data.shape[0] - train_samples # 根据索引分割数据集 train_data = data[indices[:train_samples]] train_labels = labels[indices[:train_samples]] test_data = data[indices[train_samples:]] test_labels = labels[indices[train_samples:]] print("训练集样本数量:", train_data.shape[0]) print("测试集样本数量:", test_data.shape[0]) ``` == 无微调运行 SAM 对图像分割处理结果 #align( center + horizon, figure( image(width: 35%, "mask3.jpg"), caption:[Mask 3 score:0.878] ) ) == 模型训练 === 设置优化损失函数 使用 Adam 优化器优化掩码器部分,设置 Dice+Cross Entropy Loss 作为损失函数。 ```py optimizer = torch.optim.Adam(sam_model.mask_decoder.parameters(), lr=args.lr, weight_decay=args.weight_decay) seg_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction='mean') ``` === 训练模型 循环训练,通过 SAM 模型 的 掩码解码器获取预测结果,计算损失,使用优化器更新参数,最小化损失函数。 ```py for epoch in range(num_epochs): for step, (image_embedding, gt2D, boxes) in enumerate(tqdm(train_dataloader)): # 获取模型输出 low_res_masks, iou_predictions = sam_model.mask_decoder( image_embeddings=image_embedding.to(device), image_pe=sam_model.prompt_encoder.get_dense_pe(), sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=False, ) # 计算损失并优化模型 loss = seg_loss(low_res_masks, gt2D.to(device)) optimizer.zero_grad() loss.backward() optimizer.step() ``` = 后续工作 === 🌟对模型训练结果评估 - 肿瘤分割的精确度、召回率和 Dice 系数等性能指标。 - SAM 模型结果与其他分割模型的视觉比较。 - 展示 SAM 大型模型的准确性和有效性的案例研究或实例。 === 🌟前端接口 - 为软件开发的前端界面。 - 界面功能,包括结果显示、交互工具和其他功能。 - 实现便捷的图像输入,结果显示操作。 - 用户友好的设计和医疗专业人员的易用性。 === 🌟论文撰写
https://github.com/flechonn/interface-typst
https://raw.githubusercontent.com/flechonn/interface-typst/main/BD/TYPST/format.typ
typst
#show terms: meta => { let title = label("Mon Title") let duration = label("1h30") let difficulty = label("easy") let solution = label("0") let figures = label("") let points = label("5") let bonus = label("0") let author = label("Moi") let references = label("") let language = label("français") let material = label("") let name=label("format.typ") } = Exercise // Exercise body = Solution
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/038%20-%20War%20of%20the%20Spark/001_Old%20Friends%20and%20New.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Old Friends and New", set_name: "War of the Spark", story_date: datetime(day: 08, month: 05, year: 2019), author: "<NAME>", doc ) #align(center)[#strong[I.]] Hekara was waiting for me on the Transguild Promenade. I paused for a second or two to soak her in. I know that sounds ridiculous, but she was my best mate, my hero, my role model. She had bells in her hair, and I wore bells hanging from my shoulders—from my shoulders instead of my hair because I #emph[didn't] want it to be #emph[too ] obvious that I was totally copying her, copying her look, her style, her~#emph[Hekaraness] . But I was being silly, so I called out and she turned, smiling that big grin of hers as she called out my name: "Rat! C'mere, baby-cakes, and gimme some sugar." #emph[She talks like that all the time.] I gave her a hug. She's a lot taller than I am, and she spun me around like we were acrobats in one of her guild's blood-pageants. Except we were on the ground not up on a high wire, and there were no blades or actual blood involved. #emph[This time.] "Tell me what's what, the whole crazy lowdown," she said. "Sure, sure," I said, babbling rapidly, as I often do around her (or, you know, whenever I open my big mouth). "I followed Master Zarek to Nivix, just like you wanted. Not sure why he keeps ditching you all the time—" "I know, right? Why would #emph[anyone] want to ditch me?" "It is kinda inconceivable. But if it gives me the chance to help you out by keeping tabs on him, you know I'm happy to be useful." "You're my Rat." "I'm your Rat." "Keen. So who'd he talk to?" My girl Hekara was emissary to the demon Rakdos and had been tasked by her master to keep an eye on Master Zarek of the Izzet League. But said eyeful kept sending her away, which was where I came in, you know? Hekara had tasked #emph[me ] to follow Master Zarek when she couldn't. Trailing someone without being noticed is one of my particular skills, my best skill. And, like I said, I loved being useful to my best mate. "He shut himself away with his boss." "Niv-Mizzet?" "Uh huh." "Shut?" "In a lab. A big lab. But it was just the two of them in there alone. I had snuck my way into the Nivix, but I couldn't sneak into the lab before the door shut. And I thought if I tried to open it, they might notice." "Really?" "It was a very big door and not well-oiled." "Ah." "So I made my way into and through the air ducts~" "You're my Rat." "I'm your Rat. Anyway, I missed most of the action. There was some kinda~explosion? So by the time I crawled up to a vent overlooking the lab, almost all I could see was smoke. The vent's fan had turned on—automatically, I think—and it was sucking the smoke right in. I was coughing so much, I was actually afraid they might hear me." She wagged her finger at me. "No, you weren't." "No, I wasn't. Problem was I couldn't hear them either. There were a lot of fans blowing, lots of noise. Master Niv-Mizzet did not look happy though. They were both staring at a #emph[big] machine, which is apparently what blew up. I have no idea what it was supposed to do, but it clearly hadn't worked. It was charred, smoking. Even on fire in a couple places, though neither Master Niv-Mizzet nor Master Zarek did anything about the flames. I caught maybe one sentence. Something about a beacon being their only chance now." "That fits. If anything does." "If you say so." "What else, mate?" "Not much. Master Niv-Mizzet flew off. Master Zarek opened the door to the lab, and a bunch of goblins rushed in to put out the fires. They were very efficient." "Izzet goblins have lots of practice at fire suppression. Almost as much as they have at fire causation." "Master Zarek pulled a goblin aside and told him to send messengers to Mistress Kaya, Mistress Vraska, <NAME>, <NAME>, and you. I figured I'd better get out of there and give you the heads-up so you knew what was what before you answered his call." As if on cue, a goblin came running up. Ignoring me, he bowed before Hekara and handed her a slip of parchment. She patted the goblin on the head and dropped a razor blade in his open palm as a tip. He stared at the thing, glanced up at Hekara's dangerous smile, and then backed away slowly. Once he was about five feet away, he turned and took off at a run. Hekara unfolded the parchment and nodded. The bells in her hair tinkled softly. "You were right," she said. "It's now-or-never time. My mate Ral needs yours truly-truly to activate the Beacony-Beacon to summon the uber-troopers to fight the evil dragon." "Master Niv-Mizzet is evil?" "Nah. Different dragon." "What can I do?" She looked down at me and stroked my hair. I think if I had an older sister, she'd have been like Hekara. But I didn't need an older sister because I #emph[had] Hekara. She said, "Well, I'll be with ol' Rally-Boy, myself, so you can take the night off. Let's meet back here, oh~just before dawn. If I don't show, it's 'cuz I'm still with him, and you can take the whole day off." "You sure?" "Sure, I'm sure. Don't need you to follow the guy if I'm with him." "Okay~" I think she must have sensed I was reluctant to leave her. She lifted my chin and said, "Hey, you're my Rat. Not my moth. I know I'm the brightest light in the Multiverse, but no need to hover. I'm a big girl. Can take care of myself." "I know that," I said, maybe a little resentfully. A little. She took some pity on me then. Hugged me and swung me around again. I'm a little old for that game, but, honestly, I still love it. She put me down and kissed my forehead. "Gotta go, baby-cakes." "By<NAME>." "Bye, Araithia." It struck me as odd that she used my full name. She almost never calls me Araithia. But I shrugged it off. I watched her cross the promenade. Then I turned to go. I hadn't eaten in a while, and I was hungry. I made my way to a Selesnyan market, which was just closing—or maybe just preparing to open. I stole a ripe plum. I might have also picked the pocket of an Orzhov ministrant, who was collecting a debt from the fruitier. I didn't really need the coins, but they were polished and shiny, and I like shiny things. #emph[What can I say? I'm the Rat.] I nearly went to see the Rakdos perform their Flaming Jubilee, but it felt a bit like I'd be cheating on Hekara, which is nuts. Maybe I just wasn't in the mood. So I wandered, killing time. I thought about going home to the Gruul lands, maybe spend some time with my folks. But I didn't. I felt restless. They'd be hugging me and hugging me, and the thought of it made me, um, what's the word~#emph[claustrophobic] , yeah. I wanted to stay in the open air. Brilliant notion, as it soon started to rain. Not that I mind the rain all that much. I holed up in a doorway, watching Ravnica's sparse night traffic pass me by. They all had places to go, or so it seemed. Finally, hours later, I could taste dawn in the air, so I scurried back to the Transguild Promenade to meet Hekara. She wasn't there. I waited, but she didn't come. She was still with <NAME>, of course, and wouldn't need me. I knew I could leave, but I lingered for no good reason, as the sun began to rise~ And as a sand-covered boy materialized right in front of me. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[II.]] The boy—who looked to be about eighteen or so—was on his hands and knees, coughing up sand. He wiped a sandy arm across his eyes in a futile attempt to clear his vision, then looked up at the sky with a confused and perhaps pleading sort of expression. I watched him 'cuz he looked kinda pathetic. I wondered a little where he'd teleported from that had that much sand. Then, still spitting up sand, he lowered his head and looked in my general direction. I kept watching him, while absently picking a small blood-red berry off my belt and popping it in my mouth. #emph[Told you I was hungry, right?] He was bleeding a little from a wound on his forehead, and as I bit down and tasted the berry's blood-red juice, his blood-red blood trickled into his own mouth to mix with all that sand. He spit again, fought off a fit of coughing, and—still on his hands and knees—called out for help. Surprised, I pointed to myself, and said, "Me?" He nodded desperately, and coughed out, "Please~" Immediately, I hopped off the railing and raced to his side, saying, "Hardly anyone notices me. I'm so insignificant." I helped him to his feet and began brushing sand off his tunic. He murmured a thank you and asked, "Where am I?" "Transguild Promenade," I said with a shrug. "What?" "You're on the Transguild Promenade. And there'll be thrull-carts coming through here any second in both directions. So unless you want to be crushed beneath 'em, we better move." He let me pull him forward. Rubbing his hand furiously back and forth over his scalp, he tried—and failed—to get the sand out of his hair as we walked across the bridge. I was pretty excited to be meeting someone new and, as usual, began babbling at my standard mile-a-minute pace: "We haven't been properly introduced. I'm Rat. I mean Rat's not my real name, of course. It's more of a nickname. Folks call me that. Well, not a lot of folks. But you get the idea. My real name—or, you know, my #emph[given] name—is Araithia. Araithia Shokta. So Rat is shorter, easier to say. You can call me Rat. I'm not offended by the name at all. Truth is, it's kinda perfect for me. Perfecter than Araithia, I guess. Although I think Araithia is prettier, you know? My mother still calls me Araithia. So does my father. But they're pretty much the only ones. Well, there's this centaur I know, but he's kinda my godfather, so it's the same idea. Parents get stuck on the names #emph[they] pick. But I'm fine with Rat. So you go ahead and call me Rat, okay?" "I—" "I'm currently Gateless, in case you were wondering, but I was born into Gruul Clans, so my parents want me to officially join their clan, except I just don't think I'm #emph[angry] enough, you know? Plus, I have good friends in Rakdos and Selesnya—yeah, yeah, they couldn't be more different, but some days I feel like I fit well in the one, and then the next day, the other. Anyway, those are my big three: Gruul, Rakdos, Selesnya. I'll definitely join one of those. Probably. Are you in a guild? I don't recognize the outfit." "I—" "Oh, and what's your name? That should come first, I guess. I don't talk to a lot of new people, so I may not get the order of things right. I always have so many questions, but I usually have to figure out the answers on my own, you know?" "I—" "That was rhetorical. We just met. I don't actually expect you to know how I get through life instantaneously. Besides, we're having a conversation here. There's no rush. We'll get to all the important stuff eventually, right? How's your head? That's a pretty nasty cut. I don't think you'll need stitches, but we should really get it cleaned up, get the sand off it, and stick a bandage on it or maybe find you a healer who can cast a little mending spell. I can take you somewhere they can do that for you, but even a #emph[little] healing magic can get a little pricey. Still, it's #emph[such ] a little cut, they might do it gratis, if you ask nice. Or if you're too shy to ask a stranger for help—you seem shy to me, but I don't want to presume too much since we only just met—I can patch you up myself. I mean, I guess I'm a stranger, too. But I feel like we're bonding a little. In any case, I'm a fairly decent medic. I've had to learn to do that for myself over the years. It's not like my mother wouldn't do it for me, but she's a Gruul warrior. She's not always available. Besides, I've never really been hurt all #emph[that ] badly, you know? Cuts and scrapes. I'm relatively short, and bigger folks are always bumping into me if I'm not too careful. Ravnica's a busy place, you see." "I—" "I don't have any healing magic, mind you, and I don't think I have anything I can use as a bandage, but I can steal something easy enough. Or maybe you wouldn't want a stolen bandage. I forget that not everyone's okay with me being a thief. The Azorius Arresters wouldn't approve, that's for sure. Um, you're not Azorius, are you?" "I—" "Nah, look at you. You can't be Azorius. I'm guessing you're—" Suddenly, he stepped into my path and grabbed my arms, shouting, "Listen!" I think he kinda scared himself, because he immediately looked sorry for yelling, frightened even—like I might take #emph[vengeance] or something for getting yelled at. #emph[Boy, he does not know me, right?] I smiled up at him to let him know I wasn't so fragile and said, "I talk too much, don't I? I spend a lot of time alone, and I talk to myself too much. I'm always telling myself that. Then I get with other people, and you'd think I'd learn to listen more. I want to learn to listen more. So, yeah, I'll listen to you, uh~you know, you still haven't told me your name. Start with that, and I promise I'll listen." "Teyo," he replied, his voice rising at the end, as if #emph[he] was asking #emph[me] whether he had his name right. Trying to be helpful, I repeated it back to him: "Teyo. That's a nice name. Are you in a guild, Teyo? You're injured and off your game. Is there somewhere I should take you? Someone I should take you to?" "I'm not in any guild. I'm an acolyte of the Shieldmage Order." "Huh. Never heard of it." "You've never heard of the Order? How is that possible? What do you do during a diamondstorm?" #figure(image("001_Old Friends and New/01.jpg", width: 100%), caption: [Teyo, the Shieldmage | Art by: <NAME>], supplement: none, numbering: none) "Never heard of a diamondstorm either, but it sounds pretty. Sparkly. I like sparkly things. It's kind of immature, but there you have it. If I see something sparkly, I take it. I mentioned I'm a thief, right?" He let go of my arms and stumbled over to the bridge's stone railing to look down at the river passing beneath. His eyes went wide and his hands gripped the railing tightly, turning his knuckles white. He muttered, "She's never faced a diamondstorm? Never heard of the Order? That makes no sense. The Monastic Order of the Shieldmage is famous the length and breadth of Gobakhan. The people depend upon it." Joining him at the railing, I smiled and shrugged, making an effort to speak at a more moderate pace: "I've never heard of '#emph[Gobakhan] ,' either." He slammed his hand down on the railing and stomped his foot on the ground. "This is Gobakhan! Our world is Gobakhan! You're standing on Gobakhan!" I put my arm through his and propelled him forward. "Teyo, #emph[this] ~" Without slowing my pace, I gave a little hop on the paving stones, causing my shoulder bells to #emph[jingle] softly. <NAME>. This world is Ravnica. Teyo, I've a feeling you're not on Gobakhan anymore. I'm guessing you're a 'walker." "We're walking. #emph[I'm] walking. Of course, I'm a walker." "Not #emph[that ] kind of walker. I don't know too much about it. Just stuff I overheard Master Zarek and Mistress Vraska discussing when they didn't know I was hanging around. I mean, Hekara asked me to follow Master Zarek, so it was almost a mission, an assignment, right? She wanted to know where they went when they went wheres without her. That's almost a quote, by the way. She talks like that, Hekara. Anyway, I was supposed to follow them, but I also eavesdropped a bit. I probably shouldn't admit this, but I'm a chronic eavesdropper. I really can't help myself." "I swear by the Storm, I don't know #emph[what] you're talking about." "Okay. Yeah. I get that. I mean I saw you materialize all covered in sand back there, so I probably should have guessed. But your mind always goes with the simplest explanation first, you know? I figured you knew how to teleport from place to place. Do you know how to teleport from place to place?" "No!" "Exactly. So what you #emph[can ] do, if I've got this right, is teleport from world to world, plane to plane." "I promise you I don't know how to do that either!" "I think maybe the first time, it's like an accident or, no, um, I mean not on purpose. Like an involuntary flight thing. Like to save your life maybe? Was your life in danger, maybe?" He stared at me wide-eyed. Wider-eyed than he stared at the river, anyhow. "How— how'd you know that?" "Oh, yeah, no. I didn't. But I think those might be the rules. Plus I'm very intuitive, and you were #emph[really ] covered in sand. Buried alive, maybe?" He nodded and then said, "So I'm not on Gobakhan?" "Ravnica." "Ravnica." His accent, which I hadn't really noticed before, seemed subtly more foreign when speaking the word. Already knowing the answer, I asked, "And you don't—you couldn't—know anyone here, right?" "Just you, I suppose." I gave his arm a squeeze. "Then I'm officially adopting you. Until you're ready to leave, you and I are family. Don't worry; I'll take good care of you. I'm great at that. I've had to learn to take care of myself, you know?" "Uh huh." He responded, although not necessarily to what I was saying. "So let's think about what you need to know to live on Ravnica." I glanced up at him as we walked. He looked about the city, at all the buildings and roads and the passers-by (who took zero notice of him or me), and his wide-eyed stare kept getting wider and wider. I started to worry his eyes would just bust out of his head, so I decided that he needed to eat this meal in smaller bits. "Okay, here's what you need to know: Ravnica is one big city. And a lot of folks live here. A whole lot. Mostly humans, I guess, like you and me. But plenty of elves and minotaurs and cyclops and centaurs and goblins and angels and vedalken and viashino and giants and dragons and demons and, well, pretty much anything you can think of. Mistress Vraska's a gorgon. I've only ever seen three of those, but I think they're really, really beautiful, you know?" "I—I don't think I've ever seen a gorgon." "They're striking. You can trust me on that. Anyway, I don't know who runs things on Gobakhan~" "<NAME>? Or, no. He just runs the monastery." "So you're like a monk? I thought all monks had to shave their heads." "I'm not a monk yet. I'm an acolyte. And shaving your head's not a rule. At least I don't think it is." He threw up his hands. "Right now, I'm not sure of anything!" "Calm down. That's why I'm telling you stuff. So the abbot runs Gobakhan. But here on Ravnica, it's the guilds. There are ten guilds, and between them, they run everything." "They had guilds in Oasis. That's a big town on Gobakhan." He stopped and looked around. "I suppose Oasis isn't #emph[that] big." "But it's big enough to have guilds?" "Yes. There's the Carpenters' Guild. And the Stablemen's Guild. But I don't think they run anything. I think they just get together to drink ale and complain. At least, that was my impression. I was only in Oasis for a few days." "Well, our guilds are kind of a bigger deal. Although I'm sure they drink ale and complain as much as they do anything. I know my father drinks ale and complains a lot, and he's an important warrior in the Gruul Clans." "So you're in this Gruul guild?" "I told you already. I'm Gateless. That means I haven't committed to any guild yet. Gruul, Rakdos, Selesnya. They're all kinda wooing me. I'm in high demand." I laughed. He didn't get the joke. "I'm kidding. I'm #emph[not ] in high demand." "All right. If you say so." "You're sweet." "I am?" "I think so. I like you already. I'm glad I adopted you." "I—" He laughed. Or I think it was a laugh. It was kinda hard to tell. "I think I'm glad of that, too." He was looking at me in a way that made me feel~well, I don't know how it made me feel. #emph[Is this what embarrassment feels like?] I looked away and said #emph[Stop it] to myself. #emph[Or did I say it out loud? Please, tell me I didn't say it out loud!] He took a deep breath and asked, "What else do I need to know?" "Oh, um~let's see. The guilds are always fighting with each other. It seems idiotic to me. It feels like they should all be able to get along, since they're all so different. What they care about barely overlaps. But they think being different means they need to pick at each other and stuff. So if things start to get out of control, the conflict's supposed to be resolved by this guy named <NAME>. He's called the Living Guildpact, which means whatever he says goes. You know, magically. Problem is, he's been missing for months and months. I think he's like you. Traveling from world to world. Only on purpose, maybe. Anyway, with #emph[him] gone—things have gotten iffy, you know? The guilds all tried to get together to stop some kind of evil dragon, who's supposed to be on his way. But Mistress Vraska—she's the Golgari guildmaster—assassinated Mistress Isperia, the Azorius guildmaster." "Wait, she killed her?" "Uh huh. And now the guilds all hate each other. Or, you know, don't trust each other anymore." "And the evil dragon?" "I dunno. I guess he's #emph[still] on his way." We turned a corner, and I stopped in my tracks. We had meandered our way to Tenth District Plaza, and I found myself staring up at a tall obelisk in the center of the plaza topped by the statue of a dragon. An evil dragon, if I had to guess. "Huh," I said. "That's new." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[III.]] I'd barely had time to register the brand-new obelisk in the center of the plaza when my eyes focused on the #emph[massive ] pyramid at the far end. Sometime—sometime #emph[very ] recently—it had risen out of the ground, displacing buildings and gardens and whatever else used to be there. The whole thing hit me as so overwhelming, I could hardly remember what things had been in that spot only the day before. #emph[Had those things been so insignificant?] The irony of someone like #emph[myself] forgetting wasn't lost on me, you know? "Is that the evil dragon?" Teyo asked nervously. At first I thought he was talking about the statue atop the obelisk. But his eyes were also focused on the pyramid. Sure enough, atop it sat another dragon statue—except this statue suddenly turned its head to look in our general direction. I was pretty confident it wasn't looking at me, which led me to believe Teyo might be right when he said, "It feels like he's looking right at me." But I said, "That doesn't seem likely." Or at any rate, I started to say it. But the last half of my sentence was obliterated by a loud sonic boom and a rush of dry desert air from behind us that literally knocked Teyo and I off our feet. I scampered up first. He remained on his hands and knees, shaking and muttering, "Wake up, wake up, wake up~" I turned to look as the sound of crashing masonry echoed across the plaza. A #emph[gigantic] portal—easily fifty yards tall—had opened up behind us, instantly decimating the Embassy of the Guildpact, sheering it right in half. Soft violet light poured forth from the portal. It almost looked soothing—you know, except for the destruction the tear in space had caused and was still causing. An ogre stumbled forward before collapsing; a full quarter of her body had been evaporated by the portal's arrival. The embassy's crumbling façade fell, crushing two more bystanders beneath it. It was a horror show. And not the fun Rakdos type. I looked back over my shoulder toward the dragon. We were too far away for me to see the expression on his face, but I'm a little bit psychic, and his mental gloating radiated off him in waves. His gloating and his name. #emph[Bolas. <NAME>.] It sent shivers down my spine. And then it all got worse~ #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[IV.]] A raven-haired woman in an elegant black dress stepped gingerly up onto some wreckage. She reached the top of a fallen balustrade, stood up straight and paused. Teyo murmured, #emph["Something's emerging from that geometry] ~#emph["] It took me a moment to realize he meant the circular tear in space. I looked toward it. An army. An army was marching through the portal. They shone a metallic blue in the morning sun. I thought they looked pretty. But I'm not a complete idiot. An army marching on Ravnica is not a good thing—no matter how shiny it is. The raven-haired woman raised some other shiny thing to her face. When her hands came away, I could see it was a metallic veil of burnished gold chain links that also glinted in the sunlight. Her exposed skin began to glow with purple lines, etchings, like tattoos. I thought maybe I heard her scream. But I wasn't sure if she was screaming out loud or just in her mind. #emph[Or just my fears, you know, projected?] As her bare arms glowed brighter, the metallic army began to glow, as well. Even from this distance, I could see their eyes turning purple to match the color of Miss Raven-Hair's tattoos. At any rate, the army stopped as one and turned to look her way, before, with a clear wave of her arm, she ordered her shining forces to turn and march toward everyone, toward all the folks still recovering from the portal's destruction, and all still standing there, stupidly staring at the approaching horde. #figure(image("001_Old Friends and New/02.jpg", width: 100%), caption: [Liliana, Dreadhorde General | Art by: <NAME>], supplement: none, numbering: none) Teyo whispered, "What do we do?" It frankly hadn't occurred to me to do #emph[anything] —except maybe run and hide. Instead, I stood there, silently frozen, as the first of the metal warriors reached a young human woman, who was trying to free her husband or boyfriend or brother from under fallen stone. She looked up at the approaching warrior. She didn't move a muscle as it stepped up and quickly snapped her neck. We were some ways away, but we heard the crack, felt it in our own bodies. "What do we do?" Teyo repeated. I didn't know. The carnage continued as the advancing army continued its march, killing everyone in its path. As they approached, I could see they were undead creatures: humans, minotaurs, aven, and other species, covered top to toe in some kinda metallic blue mineral. Soon, they'd get to us. I couldn't think. Couldn't move. Couldn't even talk, which is #emph[really ] weird for me. Suddenly, I heard the crack of thunder. We both turned. It was <NAME>, firing lightning bolts from hands white-hot with electricity at the blue metallic attackers, often taking out two or three at a time. He strode forward, a look of fury on his face, his hair standing on end, and the blue warriors exploded before him. Mistress Kaya was there, too; she had drawn her long knives to protect a red-haired mother huddled over a red-haired son and had launched herself at the undead killer that was raising a sword over the young woman's head. Mistress Kaya's daggers, glowing purple with her magic, sank deep into the creature's back. It collapsed in a heap in front of the shrieking mother, who pulled her son closer to her bosom and stared up at Kaya, more frightened than grateful. Mistress Kaya said, "Run." The woman snapped out of it and ran with her child in her arms. For some reason, this served to snap me and Teyo out of it, as well. "Can we help?" he asked. "I think we can try," I said, though I still wasn't quite sure how. Two more of the shiny monsters rushed Mistress Kaya. The closest and largest swung an axe, but Kaya turned incorporeal, which I knew was one of her mystic talents, and the axe swished harmlessly through her. This seemed to confuse her attacker, and Kaya made use of the time to re-corporealize and slash the throat of the incoming second creature. The pale-purple light from her daggers seemed to briefly war with the dark-purple light radiating from the warrior's eyes and cartouche. But like a poison, Mistress Kaya's powers seeped through the corpse, infecting it. It fell. She turned back to the axe wielder, who swung at her again. Again she went intangible and again the axe passed through her, leaving her opponent open to take both daggers in the abdomen. He didn't go down right away, and—solid once more—she dragged the blades up and gutted him. It was the kinda thing my mom would do. Or Hekara. I wondered where she was. But I was maybe kinda glad she wasn't here. She'd be having too much fun—and might get herself killed or something. <NAME>, meanwhile, was making a stand from atop a park bench, defending three more children, one of whom cradled a rubber ball with much the same protectiveness that the mother had used for her son. <NAME>k was smiting the metallic warriors, one after another, but as Mistress Kaya moved to join him, it was clear they—all of us—would soon be overrun. Soon another of the creatures was on her. Again, her body lost substance, and the warrior stumbled right through her. It turned. She turned. She solidified and drove her daggers into its eyes, deep into whatever was left of its brain. It dropped like a marionette whose strings had been cut. But she watched it for a second too long. A mineralized minotaur slammed into her and sent her sprawling across the cobbles. She groaned and struggled to her feet. That's where we came in. Finally. I didn't think I could take the minotaur in a frontal attack, so I ran around behind the beast. It ignored me, continuing toward Mistress Kaya faster than I had anticipated. Faster than I could make my play. And then out of nowhere, Teyo was there. He stood over Mistress Kaya, erecting a triangular shield of light to protect her and himself from the creature. (I guess that's what it means to be an acolyte of the Shieldmage Order.) The creature's mace smashed into the triangle, which flashed brightly but held its form. Teyo grimaced but held his ground, chanting low. I was both surprised and impressed and—though I had no real reason, as my godfather Boruvo would say, #emph[to harvest this honor] —proud of #emph[my ] adoptee. The minotaur reared to swing its mace again, but by that time I was ready. I had drawn my own two (much smaller) daggers. I leapt onto its back and drove them down into the beast's neck. It roared and bucked and threw me off. I went flying, though I did manage to hold on to my knives. I landed hard on my butt. #emph[Cuts and scrapes, like I said.] Suddenly, a bolt of blue-white electricity ignited the creature, which exploded into flaming piles of melting blue. As Master Zarek approached, Teyo dropped his shield. A small circle of light at his ear also vanished, and his shoulders slumped. He helped Mistress Kaya to her feet. Master Zarek addressed Teyo: "You're a Planeswalker." "I'm a what?" "How do you know he's a Planeswalker?" Mistress Kaya asked Master Zarek. I was zipping around between the metallic blue creatures. Stabbing them here and there to distract them from their targeted prey. I cut the hamstrings of one, and when it dropped to its knees, I stabbed it in the eyes. #emph[Well, it had worked for Mistress Kaya.] Fortunately, it worked for me, too. I scurried back over to Teyo, dodging another monster en route. At which point, Mistress Kaya looked directly at me and said, "Those things don't seem too interested in you. What's your secret?" I think I stared at her for a beat. Master Zarek, thinking she was talking to him, said, "They're interested enough." Ignoring him, she addressed me again, now with some concern: "You okay?" Once again, I had to snap out of my stupor. I muttered something like, "Oh, yes. I just never expected the mighty Orzhov Guildmaster to take any notice of me." Then under my breath, I muttered, "Wow, two in one day. That's almost weirder than the big hole in the world." Master Zarek, still under the mistaken impression that Mistress Kaya was addressing him, said, "I'm fine. Sorry. It's the goggles. They're the Firemind's design. I can use them to identify Planeswalkers. It's~mildly disconcerting." "Any others around?" Mistress Kaya asked. "Planeswalkers, that is. Not goggles. We could use the help." Master Zarek lowered his goggles down over his eyes and scanned the skies, slowly tracking something downward. I could tell from his expression—and a slight buzzing noise in my brain—that he was having a psychic conversation with someone. I wasn't powerful enough to intercept it, but I recognized the signs. I followed his line of vision and saw four humans approaching. Two were men I didn't recognize and the third was <NAME>, the former assistant to the Living Guildpact. You know, Mister <NAME>, who was also with them. They fought their way toward us. The largest of the men was using an ordinary broadsword to make hash of any creature that came within his reach. Master Zarek unleashed a lightning bolt that took out a couple of the monsters in the foursome's path. Then the big man shouted, "Chandra!" We all turned. Four more warriors were fighting their way toward us. Two human female pyromancer's were in the lead. One, with flaming—#emph[literally flaming] —red hair fired off tremendous blasts of fire that reduced the enemy to puddles of molten goo. The other, this one with long steel-gray hair, was using more precision blasts that were just as effective. Behind them were a male leonin and massive silver automaton. Both groups of four converged beside the four of us, and the one-eyed leonin seemed to glory in the fellowship, raising his arms toward the heavens and roaring in—what seemed to me to be somewhat premature—triumph. Quick introductions were made. The big man was <NAME>. The other man was <NAME>. The red-haired pyromancer was <NAME>. The grey-haired pyromancer was <NAME>. The leonin was <NAME>, and the automaton, who seemed to actually be alive and sentient, was <NAME>. Like Teferi, he had no last name. Seems like a whole bunch of these 'walkers didn't get one, almost like it was the cost of doing business in the Multiverse. I was about to ask Teyo if #emph[he] had a last name, but he was busy attempting to introduce the two of us to the others. But he was nervous and muttery. So when <NAME> put his large hand on Teyo's shoulder and, #emph[addressing only him] , said, "Good to have you in the fight, Teyonraht," it made me chuckle just a bit. Teyo tried to correct the impression that "Teyonraht" was his name, but by this time, <NAME> was shouting, "Form up! The Eternals are still coming! We need to save as many people as possible!" So that's what the metallic warriors were called: #emph[Eternals] . It was a name that didn't exactly bode well for our survival, you know? #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[V.]] The elegant Miss Raven-Hair in her elegant black dress was crossing the plaza from the portal to the pyramid, surrounded by a phalanx of Eternal bodyguards. She watched us as <NAME> led us forward against what he called "the Dreadhorde." She watched us lift urchins smaller than me into our arms to ferry them out of harm's way. #emph[At one point, <NAME> was holding three.] She watched us run interference for bystanders too frightened to mount any defenses of their own. She watched us destroy Eternal after Eternal. And the last thing I saw of her, before losing sight of her entirely, was her shaking her head in pity, if not disgust. I turned to Teyo—whose last name turned out to be Verada, by the way—and he just looked exhausted. He was raising shield after shield to protect all sorts of folks—all perfect strangers to him—from these undead Eternals. I was too busy trying to stay alive to read his literal thoughts, but I got the gist: he didn't trust himself, didn't think he could handle the cards he'd been dealt. I leaned over and said, "Aw, you're doing all right." He swallowed hard and nodded to me and put up another shield, a circle that expanded over his outstretched hands, giving two elven kids the cover they needed to run away from the mineral-covered—or #emph[lazotep-covered] , as <NAME> called it—Eternal that had been chasing them. His shield held, blocking the Eternal from chasing the elves and giving me the opportunity to use my little daggers on its less-than-Eternal eyes. I'd already done that move six or seven times by now. It was #emph[really] effective. I could just scurry right up to them and stab. The first time, I thought Teyo might vomit, but he swallowed it back and was now growing used to my trick. I'd never had anyone study my tricks quite this much, except maybe my mother, but I tried not to let that mess with my head. Teyo summoned a new shield to block the incoming flail attack of another Eternal. Mister Jura shouted, "Teyonraht, push that one this way!" "It's just Teyo," he squeaked while attempting to obey. I noticed that whenever he needed leverage, Teyo summoned up a small circle of light beneath his right ear. It hung there like a bright, shiny earring that held my attention dangerously. I had to resist the urge to grab at it, resist the urge to stare at it too long. Teyo expanded his left-hand shield, transforming it from a circle to a diamond. He smiled just a little, perhaps slightly proud of the maneuver, and then used both hands to add dimension to the diamond shield and walk it forward. The Eternal's flail bounced off the odd angle, throwing the monster off balance. Teyo leaned in and #emph[shoved] . The Eternal stumbled back, and <NAME> cut off its head, real smooth. "Good," he barked before turning away to attack another of the creatures. Teyo smiled again, and I smiled for him. Then he shook off the smile and turned his shield to protect Mistress Kaya's back. <NAME> shouted, "We need to summon the guilds! Bring them into the fight!" <NAME> blasted another Eternal and shouted back, "I'm not sure that's possible! I can command the Izzet into the field and maybe Kaya could do the same with the Orzhov~" Miss Lavinia finished his thought: "The rest of the guilds have retreated to shore up their own territories, more suspicious of one another than of Bolas." Mistress Kaya said, "And that's not even counting the guilds that already serve Bolas. Golgari and Azorius. Maybe Gruul, too." I couldn't believe Gruul would serve the dragon. I knew my father and mother never would. Miss Lavinia also scowled. She clearly didn't like the idea of the Azorius serving Bolas, either. Teyo and Mistress Kaya were back to back, parrying blows between two Eternals. Thinking I could help, I slipped in between them. I leaned over and whispered to Mistress Kaya, "Call Hekara. She'll bring the whole Cult." Mistress Kaya stabbed her Eternal, then paused to shake her head sorrowfully. "Hekara's dead," she said. And that was it. My world just~reeled. #emph[It couldn't be] ~ I had seen her only last night. She was fine. She was cheerful. She was Hekara. She was my best mate in the whole world. The whole Multiverse. Behind his shield, Teyo stared at me with concern. "<NAME> my friend," I said hopelessly. "She knew me. She saw me." Teyo looked the way I felt: helpless. He wanted to comfort me; pushing his shield off his right hand and onto his left, he reached over and gave my arm a little reassuring squeeze. I won't pretend I was reassured in the slightest. I still couldn't get my head around what Mistress Kaya had said. I couldn't imagine a world without Hekara in it, without her laughter, her ricocheting thoughts, her loyalty and friendship, even without her bloodlust. But Teyo was trying, and so I tried to acknowledge the effort with a grateful smile. I had no idea what expression actually appeared on my face. #emph[Hekara couldn't be dead. She just couldn't be.] "#emph[Hekara's dead] ," Mistress Kaya had said, and I knew she liked Hekara enough to never lie about that kind of thing. I #emph[wanted] to believe she would. But I knew better. My best mate wasn't waiting for me on the Transguild Promenade. She'd never wait there again. She'd never hug me or tease me or tickle me or swing me around or #emph[talk] to me again. "#emph[C'mere, baby-cakes, and gimme some sugar] ." I'd never hear that again. Or anything #emph[like] that again. Not the tinkle of the bells in her hair. Not the little giggle she made when she manifested a razor blade. Not the snorting guffaws that escaped her mouth when she found something particularly hilarious. It was all gone. The curtain had come down. Her show had gone dark. More Eternals advanced, and I wondered why we even bothered fighting them. Ravnica was dying all around me, and suddenly it didn't seem worth saving. #emph[Hekara was dead] ~
https://github.com/MichaelNotDeveloper/custom-CVs
https://raw.githubusercontent.com/MichaelNotDeveloper/custom-CVs/main/main.typ
typst
#import "@preview/showybox:2.0.1" : showybox #let algorithm = showybox.with( title-style: ( boxed-style: ( anchor: ( x: center, y: horizon ), ) ), frame: ( title-color: rgb(247, 210, 65), body-color:rgb(247, 210, 65), border-color: rgb(247, 210, 65), radius: 100pt, body-inset : 0.4em ) ) #set text(font: "Yandex Sans Display", size : 40pt, weight : "bold", ) //#set text(fill : rgb(228, 228, 228)) //#set text(font : "Yandex Sans Display", size: 20pt) #set page(paper : "a3") #set page(fill: rgb("070716")) #set text(fill: rgb("#e4e4e4")) #grid( columns: (1fr, 1fr), [ #image("mesus.png", fit: "cover", width: 70%) ], [ #v(10pt) = Замешаев\ Михаил\ #text($plus$, fill :rgb(247, 210, 65), size: 70pt) #text(underline("backend"), fill :rgb(247, 210, 65)) #set text(fill: rgb("#e4e4e4")) ] ) #set text(size: 20pt) #line(length: 100%, stroke : rgb("#e4e4e4") + 2pt) #grid(columns: (1fr, 2.7fr), [ #set text(size: 40pt) #v(15pt) #algorithm()[ #text("Образование", size : 20pt)\ ] ], [ #set text(size: 15pt) #let diff = 100pt #h(diff) #underline(text("2019-2020", fill: rgb(142, 130, 255))) - #text("Geekbrains C++", weight : "thin")\ #h(diff) #underline(text("2019", fill: rgb(142, 130, 255))) - #text("Delta Project 2x2(летняя школа от физтеха)", weight : "thin")\ #h(diff) #underline(text("2019-2022", fill: rgb(142, 130, 255))) - #text("Skillbox DataScience", weight : "thin")\ #h(diff) #underline(text("2022", fill: rgb(142, 130, 255))) - #text("Летняя Компьютерная Школа", weight : "thin")\ #h(diff) #underline(text("2022", fill: rgb(142, 130, 255))) - #text("Сириус Алгоритмы и Анализ данных", weight : "thin")\ #h(diff) #underline(text("2021-2023", fill: rgb(142, 130, 255))) - #text("Физматшкола при СФУ", weight : "thin")\ #h(diff) #underline(text("2023-2027", fill: rgb(142, 130, 255))) - #text("НИУ ВШЭ ПМИ пилотный поток", weight : "thin")\ ]) #grid(columns: (1fr, 2.7fr), [ #set text(size: 40pt) #v(15pt) #algorithm()[ #text(" Достижения", size : 20pt)\ ] ], [ #set text(size: 14pt) #let diff = 100pt #h(diff) #underline(text("2023", fill: rgb(142, 130, 255))) - #text("Призер открытой олимпиады", weight : "thin")\ #h(diff) #text("школьников по программированию", weight : "thin")\ #h(diff) #underline(text("2023", fill: rgb(142, 130, 255))) - #text("<NAME>", weight : "thin")\ #h(diff) #underline(text("2023", fill: rgb(142, 130, 255))) - #text("Всероссник по информатике", weight : "thin")\ #h(diff) #underline(text("2021-2023", fill: rgb(142, 130, 255))) - #text("Абсолют региона по информатике", weight : "thin")\ #h(diff) #underline(text("2021", fill: rgb(142, 130, 255))) - #text("Победитель всероссийского этапа Юниор", weight : "thin")\ #h(diff) #text("профи <NAME>", weight : "thin")\ #h(diff) #underline(text("2019-2023", fill: rgb(142, 130, 255))) - #text("Куча других олимпиад", weight : "thin")\ ]) #grid(columns: (1fr, 4.2fr), [ #set text(size: 40pt) #v(0pt) #algorithm()[ #text("Проекты", size : 20pt)\ ] #set text(size: 10pt) #h(12pt) #text("Не включая чатботов, ", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ #h(12pt) #text("сайтов и школьных", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ #h(12pt) #text("проектиков", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ ], [ #set text(size: 14pt) #let diff = 40pt #h(diff) #underline(text("2019", fill: rgb(142, 130, 255))) - #text("Симуляция жидкости на C++", weight : "thin")\ #h(diff) #text("Узнал, что такое плюсы и командная разработка", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ #h(diff) #underline(text("2019-2024", fill: rgb(142, 130, 255))) - #text("Библиотека с продвинутыми алгоритмами на C++", weight : "thin")\ #h(diff) #text("Храню энциклопедию, чтобы вставлять в олимпиады, применяю новые знания о плюсах", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ #h(diff) #underline(text("2024", fill: rgb(142, 130, 255))) - #text("Приложение с геолокацией в Сириусе на Swift", weight : "thin")\ #h(diff) #text("Занимался бэком, получил опыт дейликов и работы с ребятами из яндекса. Познал git", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ #h(diff) #underline(text("2022", fill: rgb(142, 130, 255))) - #text("FewShot Чатбот cо сменой стилистики речи", weight : "thin")\ #h(diff) #text("Справлялся с конфликтами в команде и с темпратурой. Очень много питона", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ #h(diff) #underline(text("2023", fill: rgb(142, 130, 255))) - #text("Сложные фильтры картинок на с++", weight : "thin")\ #h(diff) #text("Научился писать в нужном кодстайле, познал cmake и юниттесты", weight : "thin", size : 10pt, fill: rgb(116, 116, 116))\ ]) #set text(size: 14pt) #grid(columns: (1fr, 1fr, 1.4fr), [ Навыки #line(length: 80%, stroke : rgb("#e4e4e4") + 2pt) -- C++ / Go / Swift\ -- Eng B2, smooth speech \ -- Python + ML Libs + SQL\ -- Linux / Git\ -- LaTex / Typst #text("(резюме сам техал)", size : 9pt)\ -- Алгосы #text("(во внешней памяти тоже много знаю)", size : 9pt)\ ], [ Теория без Практики #line(length: 80%, stroke : rgb("#e4e4e4") + 2pt) -- Http Протоколы\ -- Докер\ -- Многопоточка\ -- 100 Анекдотов ] ,[ Контакты #line(length: 100%, stroke : rgb("#e4e4e4") + 2pt) -- #link("<EMAIL>")[<EMAIL>]\ -- #text(link("https://codeforces.com/profile/Grandmaster_gang")[Codeforces], fill: rgb(142, 130, 255))\ -- #text(link("https://github.com/MichaelNotDeveloper")[GitHub], fill: rgb(142, 130, 255))\ -- #text(link("https://t.me/meshaza")[\@meshaza], fill: rgb(142, 130, 255)) - tg\ ] )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/document_symbols/base.typ
typst
Apache License 2.0
= Heading 1 #let a = 1; == Heading 2 #let b = 1; = Heading 3 #let c = 1; #let d = { let e = 1; 0 }
https://github.com/TeddyHuang-00/typpuccino
https://raw.githubusercontent.com/TeddyHuang-00/typpuccino/main/src/latte.typ
typst
MIT License
#let rosewater = rgb(220, 138, 120) #let flamingo = rgb(221, 120, 120) #let pink = rgb(234, 118, 203) #let mauve = rgb(136, 57, 239) #let red = rgb(210, 15, 57) #let maroon = rgb(230, 69, 83) #let peach = rgb(254, 100, 11) #let yellow = rgb(223, 142, 29) #let green = rgb(64, 160, 43) #let teal = rgb(23, 146, 153) #let sky = rgb(4, 165, 229) #let sapphire = rgb(32, 159, 181) #let blue = rgb(30, 102, 245) #let lavender = rgb(114, 135, 253) #let text = rgb(76, 79, 105) #let subtext1 = rgb(92, 95, 119) #let subtext0 = rgb(108, 111, 133) #let overlay2 = rgb(124, 127, 147) #let overlay1 = rgb(140, 143, 161) #let overlay0 = rgb(156, 160, 176) #let surface2 = rgb(172, 176, 190) #let surface1 = rgb(188, 192, 204) #let surface0 = rgb(204, 208, 218) #let base = rgb(239, 241, 245) #let mantle = rgb(230, 233, 239) #let crust = rgb(220, 224, 232) #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/ern1/typiskt
https://raw.githubusercontent.com/ern1/typiskt/main/templates/colors.typ
typst
#import "colors-md14.typ" as md // Todo: Add default values here and more palettes later #let default = ( grey100: rgb(123, 123, 123), ) #let oggole = ( blue: rgb(66, 133, 244), red: rgb(219, 68, 55), yellow: rgb(244, 160, 0), green: rgb(15, 157, 88), )
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2018/MS-06.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [1], [马龙], [CHN], [3682], [2], [樊振东], [CHN], [3520], [3], [许昕], [CHN], [3344], [4], [蒂姆 波尔], [GER], [3273], [5], [林高远], [CHN], [3197], [6], [迪米特里 奥恰洛夫], [GER], [3140], [7], [水谷隼], [JPN], [3113], [8], [周雨], [CHN], [3110], [9], [张继科], [CHN], [3099], [10], [闫安], [CHN], [3094], [11], [张禹珍], [KOR], [3083], [12], [雨果 卡尔德拉诺], [BRA], [3083], [13], [马蒂亚斯 法尔克], [SWE], [3071], [14], [方博], [CHN], [3065], [15], [郑荣植], [KOR], [2994], [16], [利亚姆 皮切福德], [ENG], [2990], [17], [梁靖崑], [CHN], [2988], [18], [李尚洙], [KOR], [2982], [19], [张本智和], [JPN], [2982], [20], [吉村和弘], [JPN], [2961], [21], [吉村真晴], [JPN], [2944], [22], [赵胜敏], [KOR], [2927], [23], [上田仁], [JPN], [2925], [24], [沙拉特 卡马尔 阿昌塔], [IND], [2920], [25], [汪洋], [SVK], [2915], [26], [吉田雅己], [JPN], [2915], [27], [黄镇廷], [HKG], [2914], [28], [#text(gray, "吉田海伟")], [JPN], [2913], [29], [于子洋], [CHN], [2905], [30], [西蒙 高兹], [FRA], [2902], [31], [夸德里 阿鲁纳], [NGR], [2902], [32], [安德烈 加奇尼], [CRO], [2894], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [33], [林钟勋], [KOR], [2892], [34], [王楚钦], [CHN], [2887], [35], [丹羽孝希], [JPN], [2887], [36], [帕特里克 弗朗西斯卡], [GER], [2885], [37], [KOU Lei], [UKR], [2884], [38], [弗拉基米尔 萨姆索诺夫], [BLR], [2880], [39], [松平健太], [JPN], [2877], [40], [卢文 菲鲁斯], [GER], [2872], [41], [徐晨皓], [CHN], [2871], [42], [乔纳森 格罗斯], [DEN], [2870], [43], [<NAME>], [AUT], [2869], [44], [特里斯坦 弗洛雷], [FRA], [2868], [45], [朱霖峰], [CHN], [2867], [46], [PERSSON Jon], [SWE], [2864], [47], [周启豪], [CHN], [2862], [48], [达科 约奇克], [SLO], [2856], [49], [森园政崇], [JPN], [2851], [50], [#text(gray, "<NAME>")], [QAT], [2840], [51], [刘丁硕], [CHN], [2839], [52], [马克斯 弗雷塔斯], [POR], [2834], [53], [<NAME>], [HUN], [2829], [54], [#text(gray, "陈卫星")], [AUT], [2826], [55], [SHIBAEV Alexander], [RUS], [2826], [56], [诺沙迪 阿拉米扬], [IRI], [2826], [57], [WALTHER Ricardo], [GER], [2823], [58], [SKACHKOV Kirill], [RUS], [2818], [59], [贝内迪克特 杜达], [GER], [2817], [60], [林昀儒], [TPE], [2814], [61], [丁祥恩], [KOR], [2804], [62], [克里斯坦 卡尔松], [SWE], [2803], [63], [廖振珽], [TPE], [2798], [64], [薛飞], [CHN], [2796], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [65], [及川瑞基], [JPN], [2795], [66], [奥维迪乌 伊奥内斯库], [ROU], [2789], [67], [KIM Donghyun], [KOR], [2785], [68], [周恺], [CHN], [2782], [69], [巴斯蒂安 斯蒂格], [GER], [2775], [70], [基里尔 格拉西缅科], [KAZ], [2768], [71], [蒂亚戈 阿波罗尼亚], [POR], [2766], [72], [博扬 托基奇], [SLO], [2765], [73], [村松雄斗], [JPN], [2761], [74], [TSUBOI Gustavo], [BRA], [2758], [75], [斯特凡 菲格尔], [AUT], [2758], [76], [王臻], [CAN], [2758], [77], [GERELL Par], [SWE], [2752], [78], [PISTEJ Lubomir], [SVK], [2750], [79], [KIM Minhyeok], [KOR], [2745], [80], [WANG Zengyi], [POL], [2743], [81], [帕纳吉奥迪斯 吉奥尼斯], [GRE], [2739], [82], [雅罗斯列夫 扎姆登科], [UKR], [2739], [83], [特鲁斯 莫雷加德], [SWE], [2738], [84], [庄智渊], [TPE], [2737], [85], [大岛祐哉], [JPN], [2737], [86], [#text(gray, "MATTENET Adrien")], [FRA], [2735], [87], [TAKAKIWA Taku], [JPN], [2732], [88], [哈米特 德赛], [IND], [2731], [89], [奥马尔 阿萨尔], [EGY], [2727], [90], [ZHAI Yujia], [DEN], [2714], [91], [詹斯 伦德奎斯特], [SWE], [2710], [92], [江天一], [HKG], [2704], [93], [STOYANOV Niagol], [ITA], [2702], [94], [朴申赫], [PRK], [2701], [95], [安宰贤], [KOR], [2700], [96], [木造勇人], [JPN], [2698], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [97], [HO Kwan Kit], [HKG], [2698], [98], [<NAME>uka], [JPN], [2696], [99], [PARK Ganghyeon], [KOR], [2696], [100], [<NAME>], [ECU], [2695], [101], [宇田幸矢], [JPN], [2694], [102], [金珉锡], [KOR], [2691], [103], [安东 卡尔伯格], [SWE], [2688], [104], [MONTEIRO Joao], [POR], [2688], [105], [卡纳克 贾哈], [USA], [2686], [106], [<NAME>], [KOR], [2683], [107], [#text(gray, "<NAME>")], [FRA], [2683], [108], [赵大成], [KOR], [2683], [109], [#text(gray, "FANG Yinchi")], [CHN], [2681], [110], [LIVENTSOV Alexey], [RUS], [2681], [111], [罗伯特 加尔多斯], [AUT], [2675], [112], [OUAICHE Stephane], [ALG], [2675], [113], [TAZOE Kenta], [JPN], [2671], [114], [ANGLES Enzo], [FRA], [2670], [115], [SIRUCEK Pavel], [CZE], [2665], [116], [ECSEKI Nandor], [HUN], [2662], [117], [TAKAMI Masaki], [JPN], [2660], [118], [<NAME>], [TUR], [2659], [119], [<NAME>], [ESP], [2659], [120], [<NAME>], [JPN], [2659], [121], [<NAME>], [CZE], [2659], [122], [<NAME>], [PAR], [2657], [123], [<NAME>], [JPN], [2655], [124], [<NAME>], [HKG], [2654], [125], [邱党], [GER], [2653], [126], [WALKER Samuel], [ENG], [2649], [127], [高宁], [SGP], [2648], [128], [SEYFRIED Joe], [FRA], [2646], ) )
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/eval.typ
typst
#import "base-utils.typ": * #let mathup(s, ..sink) = { let default-scope = ( blue: xblue, red: xred, green: xgreen, xdot: xdot, xequal: xequal, xarrow: xarrow, ) let scope = if sink.pos().len() > 0 { sink.pos().first() } else { default-scope } let kwargs = sink.named() let ref = ( "*": " #xdot() ", "=": " #xequal() ", ) let expr = dreplace(s, ref) assert(test(expr, "^\$") != true, message: "no dollars allowed: " + expr + "\n\noriginal:\n\n" + "[" + s + "]") let value = eval(expr, mode: "math", scope: scope) let size = kwargs.at("size", default: none) if size != none { value = text(size: size, value) } let label = kwargs.at("label", default: none) if label != none { let labelContent = bold(label) return stack(dir: ltr, spacing: 10pt, labelContent, value) } return value } #let resolve-math-content(x) = { if is-string(x) { x = removeStartingDollars(x) return mathup(x) } return x } #let mathdown(s, ..sink) = { let scope = sink.named() return eval(s, mode: "math", scope: scope) } #let markup(..sink) = { let s = sink.pos().first() let scope = sink.named().at("scope", default: (:)) let b = eval(s, mode: "markup", scope: scope) return b }
https://github.com/elpekenin/access_kb
https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/content/parts/introduction.typ
typst
== Motivación <motivación> Hoy en día, es mucha la gente que se pasa buena parte del día frente a un ordenador, tanto por trabajo como en su tiempo libre. Esto, por supuesto, puede suponer problemas para la salud si no se toman las precauciones necesarias. Por ejemplo, problemas de vista por pasar excesivas horas mirando un monitor, aunque en este frente ya hay una buena cantidad de divulgación e investigación. Sin embargo, el periférico que más usamos es el teclado y, sin embargo, su diseño no ha cambiado en siglos, es prácitcamente idéntico a su predecesora: la máquina de escribir. Uno de los principales problemas que presenta es que puede favorecer la aparción de diversas dolencias en las muñecas. == Objetivo <objetivo> El principal fin de este trabajo va a ser cuestionarnos algunas cosas que damos por hechas y poder hacer un teclado un poco mejor. Una de las cosas que vamos a hacer es aprovechar la creciente potencia de cáculo en los microcontroladores para añadir al teclado la opción de comunicarse con el ordenador, de formar que se comunique con domótica#cite(<home-assistant>) de casa (u otros servicios). Esto es especialmente interesante a medio plazo, debido al auge del IoT.
https://github.com/leiserfg/fervojo
https://raw.githubusercontent.com/leiserfg/fervojo/master/README.md
markdown
MIT License
Fervojo ======= Use [railroads](https://github.com/lukaslueg/railroad_dsl) in your documents. You use the function by calling `render(diagram-text, css)` which renders the diagram. There, `diagram-text` contains is the diagram itself and css is the one used for the style, `css` is `default-css()` if you don't pass it. Both fields can be strings, bytes or a raw [raw](https://typst.app/docs/reference/text/raw/) block.
https://github.com/christmascoding/DHBW_LAB_GET
https://raw.githubusercontent.com/christmascoding/DHBW_LAB_GET/main/acronyms.typ
typst
// Define your acronyms here #let acronyms = ( API: "Application Programming Interface", AWS: "Amazon Web Services" )
https://github.com/Zuttergutao/Typstdocs-Zh-CN-
https://raw.githubusercontent.com/Zuttergutao/Typstdocs-Zh-CN-/main/README.md
markdown
# Typst 的中文教程 # ***Typst.pdf为官网doc的不详尽翻译版本,由typst生成!*** # ***此版本已严重过时,请移步@OrangeX4维护的中文网站https://typst-doc-cn.github.io/docs/*** 欢迎加入Typst 非官方中文交流QQ群:793548390 <img src="https://github.com/Zuttergutao/Typstdocs-Zh-CN-/assets/40693240/368178f0-6d8e-4f4d-bc39-f9d1e8bc9217" width="25%"/> 2023/05/29 更新至version 0.4 手册新增脚注以及LaTex用户指南 > 开发者称脚注必须在文章开头设置并且全文一致 2023/04/06 symbol文件夹将typst的内置的symbol输出为pdf文件 2023/04/05 英文文档已全部翻译完成,有省略有错误有误解,欢迎提出批评并指正。 Typst的使用便捷性特别合我胃口,就像知乎有位大佬说的,虽然Typst还远远达不到$\LaTeX$的排版效果,但是也比markdown好,日常做做笔记啥的,也十分方便。 所以我就将学习官方doc的过程以文字的形式记录下来,一方面可以让自己随时查阅,另一方面也可以为他人提供一些便利。 > 该pdf使用typst生成 > 与其说是文档,不如说是一个简单教程 > ***因个人学习的关系,文章组织并没有官网好,但也凑合看*** > 目前只学习/翻译了`Tutorial`,`Language`。`CONTENT`还没有翻译,但是日常记录也够用了 > Typst最吸引我的地方是函数排版,粗略看了一下应该在`Meta`部分,争取早日学到!
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/gallery/dual-reflection.typ
typst
MIT License
#set par(justify: true) #set page(width: auto, height: auto, margin:1em) #set text( size: 7pt) #import "../src/lib.typ": * #let linalool-raw = csv("../assets/linalool.csv") #let linalool = linalool-raw.slice(1) #let isobut-epoxide-raw = csv("../assets/isobutelene_epoxide.csv") #let isobut-epoxide = isobut-epoxide-raw.slice(1) #let args = ( range: (0,150), plot-extras: (this)=>{ (this.title)([Isobutelene Epoxide]) (this.callout-above)(72) }, plot-extras-bottom: (this)=>{ (this.title)([Linalool, NIST Library 2017]) (this.callout-above)(121) (this.callout-above)(93) (this.callout-above)(80) (this.callipers)(41, 55, content: [-CH#sub[2]]) } ) #let ms = mass-spectrum(isobut-epoxide, data2:linalool, args: args) #(ms.display)(mode: "dual-reflection") // #(ms.display)(mode: "dual-shift")
https://github.com/zenor0/simple-neat-typst-cv
https://raw.githubusercontent.com/zenor0/simple-neat-typst-cv/master/cv/utils/fonts.typ
typst
MIT License
#let size_lib = ( 初号: 42pt, 小初: 36pt, 一号: 26pt, 小一: 24pt, 二号: 22pt, 小二: 18pt, 三号: 16pt, 小三: 15pt, 四号: 14pt, 中四: 13pt, 小四: 12pt, 五号: 10.5pt, 小五: 9pt, 六号: 7.5pt, 小六: 6.5pt, 七号: 5.5pt, 小七: 5pt, ) #let font_lib = ( main: ("Alibaba PuHuiTi 3.0"), code: ("New Computer Modern Mono", "Times New Roman", "Fandolsong"), )
https://github.com/MLAkainu/Network-Comuter-Report
https://raw.githubusercontent.com/MLAkainu/Network-Comuter-Report/main/contents/05_demo/index.typ
typst
Apache License 2.0
= Design UI == Register and Login #figure(caption: [UI Register and Login], image("../../components/assets/UIlogin.png")) Đây là trang đăng ký, đăng nhập vào hệ thống bao gồm: địa chỉ IP Server, username, password, địa chỉ IP Peer, địa chỉ Peer Port.\ Phía dưới có 2 nút: Register và Login.\ Khi nhấn nút Register, hệ thống sẽ gửi thông tin đăng ký lên Server.\ Khi nhấn nút Login, hệ thống sẽ gửi thông tin đăng nhập lên Server.\ #pagebreak() == Publish Page #figure(caption: [UI Publish File], image("../../components/assets/UIpublish.png")) Đây là trang Publish File, bao gồm: đường dẫn file, tên file fname sau khi publish, mô tả file, nút Publish.\ Khi nhấn nút Publish, hệ thống sẽ gửi thông tin Publish lên Server.\ Phía dưới là lưới hiển thị danh sách các file đã Publish.\ #pagebreak() == Fetch Page #figure(caption: [UI Fetch File], image("../../components/assets/UIfetch.png")) Đây là trang Fetch File, bao gồm: tên file fname cần Fetch, nút Search.\ Sau khi Search, giao diện sẽ hiển thị danh sách các file có tên fname.\ Người dùng có thể chọn 1 file trong danh sách và nhấn nút Fetch để Fetch file về.\ #pagebreak() Ngoài ra còn hiển thị thông tin người dùng: username, địa chỉ IP Peer, địa chỉ Peer Port.\ #figure(caption: [UI Profile], image("../../components/assets/UIprofile.png")) #pagebreak() = Tutorial - Guides == Server Người dùng có thể start server bằng cách chạy file server.py\ #figure(caption: [Start Server], image("../../components/assets/GuServer.png")) #figure(caption: [Start Server], image("../../components/assets/start.png")) === ping Server có thể ping tới các Peer khác bằng cách nhập ping <<Host>> \ Nếu ping thành công, sẽ hiển thị thông báo client đang hoạt động\ #figure(caption: [Ping], image("../../components/assets/pingHV.jpg")) #pagebreak() Nếu ping thất bại, sẽ hiển thị thông báo client không hoạt động\ #figure(caption: [Ping No Online], image("../../components/assets/pingABC.jpg")) === Dícover Server có thể discover các Peer khác bằng cách nhập discover\ #figure(caption: [Discover], image("../../components/assets/discover.jpg")) #pagebreak() == Client Người dùng có thể start client bằng cách chạy file main.py\ #figure(caption: [Start Client], image("../../components/assets/client_start.png")) === Register Người dùng sẽ nhập IP Server, username, password, địa chỉ IP Peer, địa chỉ Peer Port để đăng ký tài khoản trên hệ thống.\ #figure(caption: [Client Register], image("../../components/assets/clientRe.jpg")) Giao diện sẽ hiển thị thông báo đăng ký thành công\ #figure(caption: [Client Register Success], image("../../components/assets/Success.jpg")) Phía Server sẽ hiển thị thông báo đăng ký thành công\ #figure(caption: [Server Register Success], image("../../components/assets/server_register.png")) === Login Người dùng sẽ nhập IP Server, username, password, địa chỉ IP Peer, địa chỉ Peer Port để đăng nhập vào hệ thống.\ #figure(caption: [Client Login], image("../../components/assets/Login.jpg")) Phía Server sẽ hiển thị thông báo đăng nhập thành công\ #figure(caption: [Login Success], image("../../components/assets/LoginSuccess.jpg")) === Publish Người dùng sẽ nhập đường dẫn file, mô tả file và nhấn nút Publish để Publish file lên hệ thống.\ #figure(caption: [Publish], image("../../components/assets/Client_publish.jpg")) Giao diện sẽ hiển thị file đã Publish vào danh sách\ #figure(caption: [Publish Success], image("../../components/assets/publish_su.jpg")) === Fetch Người dùng sẽ nhập tên file cần Fetch và nhấn nút Search để tìm kiếm file.\ #figure(caption: [Fetch], image("../../components/assets/search.jpg")) Sau khi chọn file cần Fetch và nhấn nút Fetch, file sẽ được Fetch về.\ #figure(caption: [Fetch Success], image("../../components/assets/fetch_su.jpg")) Lưới danh sách file sẽ hiển thị file đã Fetch về.\ #figure(caption: [Fetch Success], image("../../components/assets/file.jpg")) #pagebreak()
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/template.typ
typst
#let project( title: [Thesis Title], type: "", course: "", author: "", number: "", supervisor: "", date: none, logo: none, body, ) = { // Set the document's basic properties. set document(author: author, title: title) set text(font: "Linux Libertine", lang: "de") set text(12pt) set page(margin: (top: 3cm, left: 3cm, right: 2.5cm, bottom: 3.5cm)) set figure(gap: 10pt) set align(center) if logo != none { logo } text(2em, weight: 700, title) v(4em, weak: true) text(1.5em, type) linebreak() "Studiengang " text(course) linebreak() " der Hochschule Ruhr West" v(5em, weak: true) text(author) v(1.2em, weak: true) "Matrikelnummer: " text(number) v(8em, weak: true) "Erstbetreuer" linebreak() "Prof. Dr. <NAME>" v(1.2em, weak: true) "Zweitbetreuer" linebreak() "M. Sc. <NAME>" if date != none { v(1fr, weak: true) "Abgabedatum: " text(date) } pagebreak() // Main body. set align(start) show heading.where(level: 1): set block(above: 1.95em, below: 1em) show heading.where(level: 2): set block(above: 1.85em, below: 1em) show heading.where(level: 3): set block(above: 1.75em, below: 1em) show heading.where(level: 4): set block(above: 1.55em, below: 1em) show heading.where( level: 4 ): it => [ #set heading(numbering: none) #block(it.body) ] set par(justify: true) body }
https://github.com/mintyfrankie/brilliant-CV
https://raw.githubusercontent.com/mintyfrankie/brilliant-CV/main/template/modules_fr/professional.typ
typst
Apache License 2.0
// Imports #import "@preview/brilliant-cv:2.0.3": cvSection, cvEntry #let metadata = toml("../metadata.toml") #let cvSection = cvSection.with(metadata: metadata) #let cvEntry = cvEntry.with(metadata: metadata) #cvSection("Expérience Professionnelle") #cvEntry( title: [Directeur de la Science des Données], society: [XYZ Corporation], date: [2020 - Présent], logo: image("../src/logos/xyz_corp.png"), location: [San Francisco, CA], description: list( [Diriger une équipe de scientifiques et d'analystes de données pour développer et mettre en œuvre des stratégies axées sur les données, développer des modèles prédictifs et des algorithmes pour soutenir la prise de décisions dans toute l'organisation], [Collaborer avec la direction pour identifier les opportunités d'affaires et stimuler la croissance, mettre en œuvre les meilleures pratiques en matière de gouvernance, de qualité et de sécurité des données], ), tags: ("Exemple de tags ici", "Dataiku", "Snowflake", "SparkSQL"), ) #cvEntry( title: [Analyste de Données], society: [ABC Company], date: [2017 - 2020], location: [New York, NY], logo: image("../src/logos/abc_company.png"), description: list( [Analyser de grands ensembles de données avec SQL et Python, collaborer avec les équipes pour découvrir des insights commerciaux], [Créer des visualisations de données et des tableaux de bord dans Tableau, développer et maintenir des pipelines de données avec AWS], ), ) #cvEntry( title: [Stagiaire en Analyse de Données], society: [PQR Corporation], date: [été 2017], location: [Chicago, IL], logo: image("../src/logos/pqr_corp.png"), description: list([Aider à la préparation, au traitement et à l'analyse de données à l'aide de Python et Excel, participer aux réunions d'équipe et contribuer à la planification et à l'exécution de projets]), )
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/religion/rw1.typ
typst
#import "template.typ": * #show: template.with( title: "24.05 First Revision", subtitle: "<NAME> (924310245)", pset: true, ) = Introduction The basic Divine Command Theory (DCT) states that "it is right because God commands it". One notable challenge to the DCT is presented in the Euthyphro Dilemma, which raises two conflicting horns: + God commands because it is right. + It is right because God commands it. In response to this dilemma, a new Modified DCT (MDCT) is presented, which <NAME> puts forward with the critical observation that an act is wrong if and only if it is contrary to to the will of a *loving God*. I will present an argument which leads to the exposure of a weakness in the DCT. This argument is motivated by an excerpt from Adams' paper about the MDCT: #quote(block: true)[ What is essential to such a theory is to maintain that when a believer says something is (ethically) wrong, at least part of what he means is that the action in question is contrary to God’s will or commands ] == Argument / P1: The DCT should be rejected. / P2: If the DCT should be rejected, then what is right is not simply because God commands it. / P3: If what is right is not simply because God commands it, then God is not the author of ethics. / P4: If God is not the author of ethics, then God does not add anything to ethics. / P5: If God does not add anything to ethics, then no part of what it means to be ethically wrong can be attributed to God. / P6: If no part of what it means to be ethically wrong can be attributed to God, then the MDCT should be rejected. / C: The MDCT should be rejected. = Premise 1 I maintain that it is a necessity for any discussion regarding the correctness of a modified DCT to assume that the DCT should be rejected. If it is not, then there is no reason to suggest a modified version, nor is there any point in arguing about the correctness of any such modified DCT. = Premise 2 The DCT states "it is right because God commands it", and thus to reject the DCT is to accept the fact that it is not always the case that something is right because God commands it. I do not claim that it is *not right* if God commands it. I instead assert that there may be unrelated factors which matter to the righteousness of an action equally (or more) than the command of God. Thus, stemming from the rejection of the DCT, what is right is *not simply* because God commands it. = Premise 3 == Author Definition I define an author of a particular matter to be the entity responsible for creating the definition others use when referring to it. I also posit that being an author is an absolute power, that is, that which you decree is the truth. I do not deny the possibility that a particular matter can have multiple authors, but in that case, regarding any specific topic, they must either: + Come to an agreement on a particular definition. + Only have one author responsible for the definition. There is also an important distinction to make about authors. While it is the case that they are responsible for creating definitions, the interpretation of those definitions, as well as any particular enforcement, is fair grounds to be influenced by both authors and non-authors alike. This definition of an author will be critical in the motivation of the next premises. == Returning to P3 *P2* says that which is right is not *simply* right because God commands it. Thus God cannot be the author of ethics (the moral principles governing what is right and not), as otherwise it must be the case that anything God commands regarding ethics must be the definition and the truth. = Premise 4 The verb "add" does not refer to the influence non-authors can have regarding the interpretation or enforcement as described above. Rather, "add" refers to the direct power to change, modify, or alter the definition of ethics. When I say that God is not the author of ethics, I also say that God does not add anything to ethics. This premise serves as a concrete representation of the lack of power non-authors have. = Premise 5 The most crucial part of *P5* is answering the question that my definition of an author raises - is it not the case that someone who helps interpret or enforce ethics should be attributed to what it means to be ethically wrong? Should one really deny the attribution on the basis that they are not the author? A defender of the claim that, at least some part of what it means to be ethically wrong should be attributed to God, might say that while God cannot be considered the author of ethics, it is only by his command that certain actions become right or wrong on the basis of ethics. I propose the following scenario in response. == Mr. Steal Mr. Steal is an oblivious man who does not like paying for things. One day, Mr. Steal walks into a grocery store and takes some food because he is hungry. He decides to shoplift the food to avoid paying. Shortly after, he gets arrested. Clearly Mr. Steal committed a crime. In an alternate universe, Mr. Steal walks into a grocery store again, and takes food because he is hungry, but this time does not know that stealing food is a crime. There are no police around the grocery store, and as a result Mr. Steal goes home and enjoys his meal. In the second case, although there was both no knowledge that a crime was being committed, nor an enforcement of the underlying law, it is still evident that Mr. Steal has committed a crime. It is not the fact that Mr. Steal is conscious of the action or that the police arrest him that makes the action a crime, rather it is the idea that stealing from a grocery store without paying is illegal. == Returning to P5 Following the story of Mr. Steal, even if God is the entity that enforces ethics, or otherwise brings it to the attention of man, it does not add any significance to the underlying, authored definition of ethics. What it means to be ethically wrong is independent of these factors, and is controlled by the authors of ethics, which God is not. = Premise 6 *P6* starts with the conditional that "no part of what it means to be ethically wrong can be attributed to God". Why is it necessarily the case that this leads to the rejection of the MDCT? Adams' MDCT concedes that not every part of what it means to be right can be attributed to God. However, what the MDCT does require is that "when a believer says something is (ethically) wrong, at least part of what he means is that the action in question is contrary to God’s will or commands". In the context of cruelty, even if no God commands that we should not be cruel for the sake of it, it is reasonable to assume most people would take this stance anyways, thus it becomes necessary to accept that certain beliefs may be independent of God. The importance of at least some attribution to God for the MDCT is "the belief in a law that is superior to all human laws". Certainly, this would be the case if parts of ethics can be linked directly to the will of God. However, no part of what it means to be ethically wrong can be attributed to God, and thus God does not dictate a law that is superior to human law. This fundamentally disrupts one of the core pillars of the MDCT, which is the connection between human ethics and a higher law imposed by God. = Contention As a result of the above premises, I conclude that one ought to reject the MDCT. This is not a rejection of every MDCT, and also does not mean that it is not possible to construct a potential MDCT that circumvents these criticisms. However, any prospective modified theory must take into account the implications of what it means to reject the standard DCT.
https://github.com/LEXUGE/dirac
https://raw.githubusercontent.com/LEXUGE/dirac/main/lib.typ
typst
MIT License
#import "@preview/t4t:0.3.2": is #import "std.typ" // "Definitions" state which collects all the user definitions #let user_defns = state("dirac_user_defns", ()) // Check if content is defined, either as atomic or as math.attach #let __check_defined(content, loc) = { let user_defns_values = user_defns.final(loc).map(x => x.content) return (content in user_defns_values) or (content in std.builtins_defns) } #let __check_is_atomic(content) = { for a in std.atomic_contents { if is.elem(a, content) { return true } } false } // Insert an definition. `expr` should be an equation #let defn(expr, custom_label: none, visible: true) = locate( loc => { // Unwrap our expr (mainly needed to deal with e.g. dirac) if is.elem(math.equation, expr) { defn(expr.body, custom_label: custom_label, visible: visible) } else { // User should only be allowed to define atomics or attach if not (__check_is_atomic(expr) or is.elem(math.attach, expr)) { panic("User definition is not atomic: " + repr(expr)) } user_defns.update( x => { x.push((content: expr, custom_label: custom_label, location: loc)); x }, ) if visible { [#expr] } } }, ) // Generate link #let genlink(content, custom_label: none) = locate( loc => { // Step into body if content is an equation. // We accept equation because otherwise writing e.g. `bold(upright(E))` is impossible outside math environment if is.elem(math.equation, content) { genlink(content.body, custom_label: custom_label) } else { if __check_is_atomic(content) or is.elem(math.attach, content) { // Match both custom_label and content, therefore there must only be one match at most let defn_filtered = user_defns.final(loc).filter(x => (x.content == content) and (x.custom_label == custom_label)) if defn_filtered.len() == 1 { return [#link(defn_filtered.first().location)[#content]] } else { panic( "Multiple or no match. Link cannot be generated for label: " + repr(custom_label) + " and content: " + repr(content), ) } } else { panic("Link can only be generated for atomic or attach") } } }, ) // Recursive equation check #let check(content, loc) = { // Check if the content is atomic (i.e. must be defined by user explicitly) if __check_is_atomic(content) { // If the content is atomic, we need to check if it's already defined - either by user or in std. if not __check_defined(content, loc) { // But before panicking check if it is a scalar (i.e. number), we don't want to define numbers // Use `match` as it returns `none` on no-match // Scalar are always given as text if not ( (content.func() == math.text) and (not (content.text.match(regex("^\d+$")) == none)) ) { panic("undefined atomic content: " + repr(content)) } } } else { // Before all, if content is an attach, check we could match the entire attach. if is.elem(math.attach, content) and __check_defined(content, loc) { return } // Check if the content has subfields that is accessible to us: so we could proceed into next level // First determine the content type and its accessible fields let acc_fields = () let unknown_content = true for a in std.accessible_fields { let (typ, flds) = a if is.elem(typ, content) { acc_fields = flds; unknown_content = false; break } } // If the content is unknown, panic if unknown_content { panic("encountered unknown content " + repr(content.func())) } for (_, next) in content.fields().pairs().filter(x => { let (key, _) = x; key in acc_fields }) { if type(next) == array { // This indicates we are dealing with a sequence's children for item in next { check(item, loc) } } else { check(next, loc) } } } } // Register the checker #let register() = locate(loc => { // check eqns for eqn in query(math.equation, loc) { check(eqn, loc) } })
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/features-06.typ
typst
Other
// Test extra number stuff. #set text(font: "IBM Plex Serif") 0 vs. #text(slashed-zero: true)[0] \ 1/2 vs. #text(fractions: true)[1/2]
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Allemand_Hermann_Hesse.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "<NAME>", authors: ( "<NAME>", ), date: "12 Novembre, 2023", ) #set heading(numbering: "1.1.") <NAME> ist einer der wichtigsten Schriftsteller des 20. Jahrhunderts. Er wurde am 2. Juli 1877 in Calw, bei Stuttgart, geboren und starb am 9. August 1962 in Montagnola, in der Schweiz. Seine Familie war sehr religiös. Sein <NAME> war Missionar und wollte, dass Hermann Theologie studierte. Hesse wurde jedoch Schriftsteller. Er schrieb zuerst im Jugendstil und später im Expressionismus. In seinen Romanen wie Demian oder der Steppenwolf untersucht er das Thema der Sinn des Lebens und der Einsamkeit. Hesses Stil ist lyrisch und symbolisch. Im Jahr 1904 heiratete Hesse <NAME> und im Jahr 1922 heiratete er <NAME>. Ab 1931 lebte Hesse mit seiner Frau in Montagnola, wo die Natur und die Landschaft seine Texte stark beeinflussten. Im Jahr 1946 erhielt er den Nobelpreis für Literatur für sein Werk das Glasperlenspiel.
https://github.com/donghoony/KUPC-2023
https://raw.githubusercontent.com/donghoony/KUPC-2023/master/problem_info.typ
typst
#import "colors.typ" : * #import "abstractions.typ" : pick_color #let mono(s, color: black) = {text(font: "Inconsolata", fill: color)[#s]} #let isDiv1(problem) = { return problem.d1.trim().len() != 0 } #let isDiv2(problem) = { return problem.d2.trim().len() != 0 } #let constructTitle(problem, size: 2.5em, bookmark: true) = { let title = ""; if (isDiv2(problem)) {title += "2" + problem.d2} if (isDiv2(problem) and isDiv1(problem)) {title += "/"} if (isDiv1(problem)) {title += "1" + problem.d1} if (bookmark == true) { heading()[#text(title, weight: 600, fill:KUPC_GREEN, size:size)#text(". " + problem.title, weight: 400, fill:KUPC_GREEN, size:size)] } else { set text(size: size) text(title, weight: 600, fill:KUPC_GREEN) text(". " + problem.title, weight: 400, fill:KUPC_GREEN) } text("") } #let printDetails(problem, size: 1.5em) = { set text(size: 1.5em) v(-1em) text(font: "Inconsolata")[#problem.algorithms] linebreak() v(0em) text[출제진 의도 - #text(weight: 600, problem.difftext, fill: pick_color(tier: problem.diff))] } #let printStat(problem) = { set text(size: 2em) let d1_submit_count = problem.d1_stat.at(1) let d1_ac_count = problem.d1_stat.at(0) let d1_rate_count = d1_submit_count if (d1_submit_count == 0) {d1_rate_count = 1} let d1_ac_rate = calc.round(d1_ac_count / d1_rate_count * 100, digits: 2); let d2_submit_count = problem.d2_stat.at(1) let d2_ac_count = problem.d2_stat.at(0) let d2_rate_count = d2_submit_count if (d2_submit_count == 0) {d2_rate_count = 1} let d2_ac_rate = calc.round(d2_ac_count / d2_rate_count * 100, digits: 2); let d1_first_ac = problem.d1_first_ac.at(0) let d1_ac_at = problem.d1_first_ac.at(1) let d2_first_ac = problem.d2_first_ac.at(0) let d2_ac_at = problem.d2_first_ac.at(1) if (isDiv1(problem) == false) {d1_submit_count = "─ "; d1_ac_count = "─ "; d1_ac_rate = "─ "} if (isDiv2(problem) == false) {d2_submit_count = "─ "; d2_ac_count = "─ "; d2_ac_rate = "─ "} list(marker: [#text("🦆", size:1.2em)], text[제출 #d2_submit_count\회, 정답 #d2_ac_count\명 (정답률 #d2_ac_rate\%)#v(0.5em)], ) list(marker: [#text("🥇", size:1.2em)], [#if (isDiv2(problem) == true and d2_ac_count != 0) { [#d2_first_ac, #d2_ac_at\분] } else {"─"}] ) v(2em) list(marker: [#text("🪿", size:1.2em)], text[제출 #d1_submit_count\회, 정답 #d1_ac_count\명 (정답률 #d1_ac_rate\%)#v(0.5em)] ) list(marker: [#text("🥇", size:1.2em)], [#if (isDiv1(problem) == true and d1_ac_count != 0) {[#d1_first_ac, #d1_ac_at\분]} else {"─"}] ) } #let printSetter(problem) = { set text(size: 2em) let setter_names = problem.setter.map(setter => { text(setter.at(0) + " ") text(setter.at(1), size: 0.8em, font: "Inconsolata", fill: gray) }).join(", ") v(2em) list(marker: [#text("📣", size:1.2em)], [#setter_names] ) v(1em) } #let info(problem) = { pad(left: -1em)[ #v(1em) #pad(left: 0em)[ #constructTitle(problem) #linebreak() #v(1em) #printDetails(problem) #v(5em) ] #pad(left: -2em)[ #printStat(problem) #printSetter(problem) ] ] pagebreak() }
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week8.typ
typst
#import "../../utils.typ": * #section("Meta Patterns 2") #subsection([Anything (Fancy Property List)]) #set text(size: 14pt) Problem | We need to represent *any* data that can include sequences of data and should be stored recursively and should be easily extendable.\ Solution | Create a datastructure that can be casted to or casted from(usually implemented as trait -> toAny, fromAny), see dbus-rs with dyn RefArg. Simple types usually have a direct representation like integers booleans etc. While structs and maps have to be broken down and then rebuilt -> cast.\ #set text(size: 11pt) // images #align( center, [#image("../../Screenshots/2023_11_10_09_33_45.png", width: 100%)], ) Example with JSON: #align( center, [#image("../../Screenshots/2023_11_10_09_38_47.png", width: 70%)], ) existing implemenation: - any type in typescript #columns( 2, [ #text(green)[Benefits] - readable streaming format and appropriate for configuration data - universally applicable, flexible interchange across class/object boundaries #colbreak() #text(red)[Liabilities] - less type safety than regular structs - intent of parameter elements not always obvious - overhead for value lookup and access / or cast - no real object, everything is just data without interpretation ], ) #section("Frameworkers Dilemma") #subsection("Framework Lock-in") How do you as a developer guarantee the following points despite usinga framework that will pre-define certain things: - portability: framework dependent... -> how to create an application that can use multiple frameworks? - frameworks usually use inheritance -> strongest coupling out there -> very hard to create portable application - testability: framework dependent... -> how to test only your code and not the framework code? - longevity: framework dependent... -> what happens when framework is abandoned Quite frankly, you don't, because of coupling with the framework, you are bound with these properties, e.g. you can't port your application to platform x when your framework doesn't support that platform, hence you would need a new framework, but you are already *locked-in* as you have spent x amount of time using it and getting to know it.\ In other words, MAUI -> wanna make a linux app, well too bad... Or GTK -> wanna make a windows app, well ... it "works" but not that well\ #text( red, )[Check out your functional and non-functional requirements and evaluate your Framework (and its vendor) with care, before you get locked-in.] #subsection("Framework Evaluation Delta") This defines a value that makes the difference(advantage/disadvantage) between frameworks clear via benchmarks -> aka how does framework a differ from framework b: - Key idea behind the technology evaluation framework is: - Presumes «well-defined goals before starting the evaluation» - Defines a three-phase model + understanding how the evaluated technology differs from other technologies + understanding how these differences address the needs of specific usage contexts. #align( center, [#image("../../Screenshots/2023_11_10_09_53_28.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_11_10_09_53_46.png", width: 100%)], ) #subsection("Developing Frameworks") Frameworks essentially should always recieve updates as developers might otherwise look for alternatives -> see the meme, if the library doesn't get an update every 14 minutes the library is considered abandoned. Change the 14 minutes to hald a year, and suddenly people see this as true, and hence they will try something else. Other reasons to change frameworks: - performance - new architecture - simplicity - development progress - stability #subsection("Frameworkers Dilemma") #text( teal, )[There is a problem with creating a framework and trying to update it constantly:\ Once you have an application that uses the framework, this application is interested in having a stable framework that doesn't make drastic changes to it's base. E.g. The application would like you to not create breaking changes, while developers that might want to use your framework later would like to see major (often breaking) features before using it.] #subsubsection("Avoiding the dilemma") + Think very hard up-front - invest now, reap rewards later - requires experience - hard to decide without concrete applications and needs -> see xorg problem - can lead to expensive or over-engineered frameworks - might take too long to hit the market -> create react clone in 2023 ... wowie you just played yourself + don't care too much about framework users - Lay the burden of porting applications to the application's developer - Provide many good and useful new features to make porting a "must" - Might require porting tools, training/guidelines and conventions - fight hard to keep backwards compatibility -> keeps existing users + let users participate - Social process can help, e.g. by giving users time to migrate -> deprecation - Tendency for infinite backward compatibility - open source + use helping technology - Configurability - less direct code-dependencies - Simple and flexible interfaces - tendency to be more stable - Patterns - Encapsulate Context, Extension Interface - already known: Reflection, Property List, Anything #subsubsubsection("Configuration") - Use configuration to reduce code-dependencies - Let the framework do as much as possible without writing code - Apply Reflection to identify interfaces, classes (extension points) and methods (hooks) - Rely on annotations (attributes) which configures application wiring - and can be extended later-on without breaking user’s code - e.g. Angular Dependency Injection (\@Injectable / InjectionToken) - or just use traits like a normal person? - Reflection allows using Conventions over Configuration paradigm - Completely eliminates the need of directly coupling the framework API - but introduces black magic #subsubsubsection("Flexibility") - composition over inheritance - frameworks using composition allow users to create whatever they want and to more easily break coupling where they don't need it. - trait usage - traits can be implemented on user defined structs and can be used more generically -> exactly what we want - Encapsulate the parameters/properties into another object
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/code/2.typ
typst
查阅艾里斑的相关资料,讨论光学仪器的分辨本领(假设入射光波长 500 nm,透镜焦距 0.2 m, 圆孔半径 0.5 mm) 艾里斑是由于衍射限制而在焦点处形成的光斑,其中央为明亮的圆斑,周围有一组较弱的明暗相间的同心环状条纹。在光学仪器中,艾里斑的大小影响了仪器的分辨能力,即能够区分两个接近物体的最小距离。 根据瑞利判据,两个点光源的艾里斑中心与第一暗环重合时,这两个点光源刚好能够被分辨。艾里斑的半径可以用以下公式计算: $ r = 1.22 times (f times lambda)/D $ 其中: - $r$ 是艾里斑的半径 - $f$ 是透镜的焦距 - $lambda$ 是入射光的波长 - $D$ 是圆孔的直径 给定的条件是入射光波长 $lambda$ = 500 nm,透镜焦距 f = 0.2 m,圆孔半径 a = 0.5 mm,所以圆孔直径 D = 1 mm。将这些值代入上述公式,我们可以计算出艾里斑的半径: $ r = 1.22 times (0.2 times 500 times 10^(-9))/(1 times 10^(-3)) = 1.22 times 10^(-4) m = 122 "µm" $ 因此,这个光学仪器的分辨本领,或者说能够分辨的最小距离是 122 µm。这意味着如果两个点光源的距离小于 122 µm,它们在该光学仪器下就无法被清晰地分辨开来。这个计算对于理解光学仪器的性能和设计非常重要。如果需要进一步提高分辨率,可以尝试减小波长、增加焦距或使用更小的圆孔。
https://github.com/ruziniuuuuu/modern-cv-zh
https://raw.githubusercontent.com/ruziniuuuuu/modern-cv-zh/main/resume.typ
typst
#import "template.typ": * #show: resume.with( author: ( firstname: "二狗", lastname: "王", email: "<EMAIL>", phone: "(+86) 138-8888-8888", github: "doggy2", linkedin: "wang-er-gou-888888888", address: "火星省火星市, 666666", positions: ( "养猪专家", "专业觅食", "咸鱼翻身", "睡眠研究" ), ), date: datetime.today().display(), language: "zh", colored-headers: true, ) = 教育背景 #resume-entry( title: "野鸡国际大学", location: "野鸡国", date: "201x.x - 202x.x", description: "硕士 养猪工程, GPA: 5.0/5.0", ) #resume-item[ 主修课程:养猪学 | 猪语言学 | 猪舍管理 | 猪食学 ] #resume-entry( title: "土豆科技大学", location: "土豆镇,中国", date: "201x.x - 201x.x", description: "本科 咸鱼翻身, GPA: 59.9/100 (Top 99%)", ) // #resume-item[ // 主修课程:咸鱼学 | 翻身学 | 睡眠学 // ] = 研究经历 #resume-entry( title: "PIG-GPT: 猪到猪技能学习框架", location: "野鸡国", date: "202x.x - 202x.x", description: "野鸡国际大学", ) #resume-item[ - 开发了创新的*猪到猪技能学习框架*,将*大语言模型(LLM)*整合到猪的技能学习过程中 - 负责*喂猪、放猪、猪叫、猪睡觉*等核心研究工作 - 开发了*猪语言翻译器*,实现了猪与人类的无障碍沟通 ] #resume-entry( title: "Potato-Pi:关于吃土豆放屁的研究", location: "土豆镇,中国", date: "202x.x - 202x.x", description: "高级土豆研究所", ) #resume-item[ - 研究土豆摄入量与放屁频率的关系,建立了*土豆-放屁数学模型* - 开发了*便携式放屁检测器*,可实时监测和分析放屁成分 - 设计了*土豆膳食优化算法*,平衡营养摄入和放屁控制 - 撰写了《土豆与肠道健康》论文,发表在*《国际放屁研究期刊》*上 ] = 项目经历 #resume-entry( title: "自主觅食的超级喵星人", location: [#github-link("wangergou666666/miaomiao.git")], date: "202x.x - 202x.x", description: "撸猫中心", ) #resume-item[ - 设计并实现了基于*深度强化学习*的自主觅食机器人,实现了自动寻找食物的功能 - 优化了*猫粮分发算法*,减少了30%的浪费 - 研究猫咪行为模式,提出了*猫咪心理健康调理方案* ] = 实习经历 #resume-entry( title: "花胃科技有限公司", location: "宝宝花园", date: "202x.x - 202x.x", description: "种花算法", ) #resume-item[ - 开发了*智能浇水系统*,运用机器学习算法预测植物需水量,提高水资源利用率20% - 设计了*花朵识别AI*,可识别10000+种花卉,准确率达99.9% - 参与*虚拟花园*项目,使用AR技术让用户在任何地方都能欣赏到美丽的花园 ] = 自我评价 #resume-item[ - 本狗是一只*活力四射*的汪星人,对*新鲜肉骨头*和*高科技逗猫棒*充满好奇心 - 拥有*超强嗅觉*,能在方圆十里之内闻出美食的位置 - *撒娇卖萌*技能满级,擅长用*狗狗眼*获取额外的零食和关注 - 具有*出色的挖坑能力*,曾在后院挖出一个半月形游泳池 - *睡觉大师*,可以在任何地方、任何姿势秒睡,并保持高质量睡眠 ] = 其他 #show link: underline #resume-item[ - #resume-addition-item( "基于树莓派的智能冰箱追食机器人控制", "wangergou666666/fridge.git" ) - #resume-addition-item( "基于树莓派的自动猫抓机器人控制", "wangergou666666/miao_raspberry.git" ) ]
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Anglais_Compte_Rendu.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Anglais Compte Rendu", authors: ( "<NAME>", ), date: "3 Juin, 2024", ) #set heading(numbering: "1.1.") The text, written by <NAME> and published in Times Higher Education in 2017, provides an insightful look into the daily life of a Harvard University student. It explores the rigorous schedule and high expectations that define the Harvard experience, shedding light on why Harvard maintains its reputation as one of the top universities globally. Raphaëlle begins by addressing the common perception of Harvard’s elitism and prestige. She clarifies that the university’s reputation is not solely due to its history or exclusivity but rather the relentless hard work of its students. Every Harvard student dedicates significant time to studying and extracurricular activities, often working late into the night. Raphaëlle emphasizes that time is the most valued currency among Harvard students, who prioritize their academic and extracurricular commitments over everything else. The text describes a typical Wednesday for Raphaëlle, starting with her first class at the Kennedy School of Government at 8:45 a.m. After an hour of studying in the library, she attends an economics class, followed by lunch and a research assistant job at the Weatherhead Centre for International Affairs. Her responsibilities include working with a postdoctoral fellow on voting habits and the suffrage movement in Denmark. After dinner, Raphaëlle takes an economics review test and attends the weekly Institute of Politics meeting. She listens to engaging debates, then returns to the library for more studying. Her day is characterized by a constant cycle of reading, writing, and calculating, with little time for rest. Despite the heavy workload, Raphaëlle notes that students still manage to find time for social activities, underscoring their resilience and determination. This text offers a fascinating and vivid glimpse into the life of a Harvard student, showcasing the intense dedication and hard work required to thrive in such a prestigious environment. Personally, I find Raphaëlle’s account both inspiring and daunting. It is impressive to see the level of commitment and resilience exhibited by Harvard students, balancing a grueling academic schedule with extracurricular activities and social life. However, it also raises questions about the sustainability of such a lifestyle and the potential pressures it places on students. While the experience may foster incredible growth and opportunities, it is essential to consider the importance of mental well-being and the need for a balanced life. This account serves as a reminder of the sacrifices behind the success and the relentless pursuit of excellence that defines Harvard’s esteemed reputation.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2C00.typ
typst
Apache License 2.0
#let data = ( ("GLAGOLITIC CAPITAL LETTER AZU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER BUKY", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER VEDE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER GLAGOLI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER DOBRO", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER YESTU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER ZHIVETE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER DZELO", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER ZEMLJA", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER IZHE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER INITIAL IZHE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER I", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER DJERVI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER KAKO", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER LJUDIJE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER MYSLITE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER NASHI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER ONU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER POKOJI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER RITSI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SLOVO", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER TVRIDO", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER UKU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER FRITU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER HERU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER OTU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER PE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SHTA", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER TSI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER CHRIVI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SHA", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER YERU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER YERI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER YATI", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SPIDERY HA", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER YU", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SMALL YUS", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER YO", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER BIG YUS", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER FITA", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER IZHITSA", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER SHTAPIC", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER TROKUTASTI A", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE", "Lu", 0), ("GLAGOLITIC CAPITAL LETTER CAUDATE CHRIVI", "Lu", 0), ("GLAGOLITIC SMALL LETTER AZU", "Ll", 0), ("GLAGOLITIC SMALL LETTER BUKY", "Ll", 0), ("GLAGOLITIC SMALL LETTER VEDE", "Ll", 0), ("GLAGOLITIC SMALL LETTER GLAGOLI", "Ll", 0), ("GLAGOLITIC SMALL LETTER DOBRO", "Ll", 0), ("GLAGOLITIC SMALL LETTER YESTU", "Ll", 0), ("GLAGOLITIC SMALL LETTER ZHIVETE", "Ll", 0), ("GLAGOLITIC SMALL LETTER DZELO", "Ll", 0), ("GLAGOLITIC SMALL LETTER ZEMLJA", "Ll", 0), ("GLAGOLITIC SMALL LETTER IZHE", "Ll", 0), ("GLAGOLITIC SMALL LETTER INITIAL IZHE", "Ll", 0), ("GLAGOLITIC SMALL LETTER I", "Ll", 0), ("GLAGOLITIC SMALL LETTER DJERVI", "Ll", 0), ("GLAGOLITIC SMALL LETTER KAKO", "Ll", 0), ("GLAGOLITIC SMALL LETTER LJUDIJE", "Ll", 0), ("GLAGOLITIC SMALL LETTER MYSLITE", "Ll", 0), ("GLAGOLITIC SMALL LETTER NASHI", "Ll", 0), ("GLAGOLITIC SMALL LETTER ONU", "Ll", 0), ("GLAGOLITIC SMALL LETTER POKOJI", "Ll", 0), ("GLAGOLITIC SMALL LETTER RITSI", "Ll", 0), ("GLAGOLITIC SMALL LETTER SLOVO", "Ll", 0), ("GLAGOLITIC SMALL LETTER TVRIDO", "Ll", 0), ("GLAGOLITIC SMALL LETTER UKU", "Ll", 0), ("GLAGOLITIC SMALL LETTER FRITU", "Ll", 0), ("GLAGOLITIC SMALL LETTER HERU", "Ll", 0), ("GLAGOLITIC SMALL LETTER OTU", "Ll", 0), ("GLAGOLITIC SMALL LETTER PE", "Ll", 0), ("GLAGOLITIC SMALL LETTER SHTA", "Ll", 0), ("GLAGOLITIC SMALL LETTER TSI", "Ll", 0), ("GLAGOLITIC SMALL LETTER CHRIVI", "Ll", 0), ("GLAGOLITIC SMALL LETTER SHA", "Ll", 0), ("GLAGOLITIC SMALL LETTER YERU", "Ll", 0), ("GLAGOLITIC SMALL LETTER YERI", "Ll", 0), ("GLAGOLITIC SMALL LETTER YATI", "Ll", 0), ("GLAGOLITIC SMALL LETTER SPIDERY HA", "Ll", 0), ("GLAGOLITIC SMALL LETTER YU", "Ll", 0), ("GLAGOLITIC SMALL LETTER SMALL YUS", "Ll", 0), ("GLAGOLITIC SMALL LETTER SMALL YUS WITH TAIL", "Ll", 0), ("GLAGOLITIC SMALL LETTER YO", "Ll", 0), ("GLAGOLITIC SMALL LETTER IOTATED SMALL YUS", "Ll", 0), ("GLAGOLITIC SMALL LETTER BIG YUS", "Ll", 0), ("GLAGOLITIC SMALL LETTER IOTATED BIG YUS", "Ll", 0), ("GLAGOLITIC SMALL LETTER FITA", "Ll", 0), ("GLAGOLITIC SMALL LETTER IZHITSA", "Ll", 0), ("GLAGOLITIC SMALL LETTER SHTAPIC", "Ll", 0), ("GLAGOLITIC SMALL LETTER TROKUTASTI A", "Ll", 0), ("GLAGOLITIC SMALL LETTER LATINATE MYSLITE", "Ll", 0), ("GLAGOLITIC SMALL LETTER CAUDATE CHRIVI", "Ll", 0), )
https://github.com/timetraveler314/Note
https://raw.githubusercontent.com/timetraveler314/Note/main/Discrete/logic.typ
typst
#import "@local/MetaNote:0.0.1" : * = Logic #let Prop = math.bold("PROP") #let ts = math.tack.r #let tss = math.tack.r.double == Propositional Logic To describe a proposition, we introduce the following syntax defining the set of propositions $prop$: #definition($"Syntax of" Prop$)[ Atoms: $A := {p, q, r, ...}$; Connectives: $C := {not, and, or, ->, <->, bot}$; Propositions: $Prop := A | C(Prop)$. ] The set of propositions $Prop$ is the smallest set satisfying the above syntax, where "smallest" can be understood as the least fixed point of the grammar, or the intersection of all sets satisfying the syntax. === Semantics of Prop The approach of semantics is to give a meaning to each proposition in $Prop$, which we wish to be true or false. This is called a _truth assignment_, or a _model_. === Syntax of Prop In a pure semantics approach, we forget about the concrete meaning of propositions, only focusing on how the syntax, or strings, are manipulated. We first introduce the big-step natural deduction system for propositional logic. #definition("Natural Deduction")[ We define the notation $ts$ as ] The other is the small-step system _System K_, which is a sequent calculus. #definition("System K")[ System K features $=>$ as the meta ]
https://github.com/typst-community/glossarium
https://raw.githubusercontent.com/typst-community/glossarium/master/examples/plural-example/main.typ
typst
MIT License
#import "../../glossarium.typ": make-glossary, register-glossary, print-glossary, gls, glspl // Replace the local import with a import to the preview namespace. // If you don't know what that mean, please go read typst documentation on how to import packages at https://typst.app/docs/packages/. #show: make-glossary #let entry-list = ( ( key: "potato", long: "potato", // "plural" will be used when "short" should be pluralized longplural: "potatoes", description: [#lorem(10)], ), ( key: "dm", short: "DM", long: "diagonal matrix", // "longplural" will be used when "long" should be pluralized longplural: "diagonal matrices", description: "Probably some math stuff idk", ), ( key: "cpu", short: "CPU", long: "Central Processing Unit", description: [#lorem(10)], ), ( key: "buffer", long: "buffer", description: "A place to store stuff", ), ) #register-glossary(entry-list) #set page(paper: "a5") #show link: set text(fill: blue.darken(60%)) I like to eat #glspl("potato"). Yes I still like to eat #glspl("potato"). But I don't like to eat #glspl("dm"). ... I thought about it and now I like to eat #glspl("dm"). I love #glspl("cpu"). I ate a #gls("cpu") once. Would you eat a #gls("buffer") ? I heard #glspl("buffer") are tasty. = Glossary #print-glossary( entry-list, // show all term even if they are not referenced, default to false show-all: true, // disable the back ref at the end of the descriptions disable-back-references: true, )
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/package/codly.typ
typst
The Unlicense
#import "@preview/codly:0.2.0": * #let codly = codly.with( // display-icon: false, display-name: false, zebra-color: luma(95%), radius: 2pt, stroke-width: 0.25pt, stroke-color: black, language-block: (x) => (name, icon, default-color, loc) => { let radius = __codly-radius.at(loc) let padding = __codly-padding.at(loc) let stroke-width = __codly-stroke-width.at(loc) let color = if default-color == none { __codly-default-color.at(loc) } else { default-color } box( radius: radius, fill: color.lighten(60%), inset: padding, stroke: none, outset: 0pt, icon + name, ) } )
https://github.com/Thumuss/truthfy
https://raw.githubusercontent.com/Thumuss/truthfy/main/README.md
markdown
MIT License
# Truthfy Make an empty or filled truth table in Typst # Export ```sh truth-table-empty(info: array[math_block], data: array[str]): table # Create an empty (or filled with "data") truth table. truth-table(..info: array[math_block]): table # Create a filled truth table. karnaugh-empty(info: array[math_block], data: array[str]): table # Create an empty karnaugh table. NAND: Equivalent to sym.arrow.t NOR: Equivalent to sym.arrow.b ``` # OPTIONS ## `sc` Theses functions have a new named argument, called `sc` for symbol-convention. You can add you own function to customise the render of the 0 and the 1. See examples. Syntax: ```typst #let sc(symb) = { if (symb) { "an one" } else { "a zero" } } ``` ## `reverse` Reverse your table, see issue #3 # Examples ## Simple ```typst #import "@preview/truthfy:0.4.0": truth-table, truth-table-empty #truth-table($A and B$, $B or A$, $A => B$, $(A => B) <=> A$, $ A xor B$) #truth-table($p => q$, $not p => (q => p)$, $p or q$, $not p or q$) ``` ![image](https://github.com/Thumuss/truthfy/assets/42680097/7edb921d-659e-4348-a12a-07bcc3822012) ```typst #import "@preview/truthfy:0.4.0": truth-table, truth-table-empty #truth-table(sc: (a) => {if (a) {"a"} else {"b"}}, $a and b$) #truth-table-empty(sc: (a) => {if (a) {"x"} else {"$"}}, ($a and b$,), (false, [], true)) ``` ![image](https://github.com/Thumuss/truthfy/assets/42680097/1ccf6077-5cfb-4643-b621-1dc9529b8176) # Contributing If you have any idea to add in this package, add a new issue [here](https://github.com/Thumuss/truthfy/issues)! # Changelog `0.1.0`: Create the package. <br/> `0.2.0`: - You can now use `t`, `r`, `u`, `e`, `f`, `a`, `l`, `s` without any problems! - You can now add subscript to a letter - Only `generate-table` and `generate-empty` are now exported - Better example with more cases - Implemented the `a ? b : c` operator <br/> `0.3.0`: - Changing the name of `generate-table` and `generate-empty` to `truth-table` and `truth-table-empty` - Adding support of `NAND` and `NOR` operators. - Adding support of custom `sc` function. - Better example and README.md `0.4.0`: - Add `karnaugh-empty` - Images re-added (see #2) - Add `reverse` option (see #3)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-06.typ
typst
Other
// Error: 3-19 cannot apply '<=' to relative length and ratio #(30% + 1pt <= 40%)
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/lernerfolgskontrollen/uebung01/main.typ
typst
Other
#import "/src/lernerfolgskontrollen/template.typ": * #set page(flipped: true) #set text(size: 0.675em) #show: columns.with(2) #show: project.with( topic: "Descartes methodischer Zweifel" ) #citation[ #{ set text(size: 0.75em) place(dx: -1.5em, dy: 0.1em, [1]) place(dx: -1.5em, dy: 7.85em, [5]) // place(dx: -1.5em, dy: 16.6em, [10]) } \3. Alles nämlich, was ich bisher am ehesten für wahr gehalten habe, verdanke ich den Sinnen oder der Vermittlung der Sinne. Nun aber bin ich dahintergekommen, daß diese uns bisweilen täuschen, und es ist ein Gebot der Klugheit, denen niemals ganz zu trauen, die uns auch nur einmal getäuscht haben. \4. Indessen -- mögen uns auch die Sinne mit Bezug auf zu kleine und entfernte Gegenstände bisweilen täuschen, so gibt es doch am Ende sehr vieles andere, woran man gar nicht zweifeln kann, wenngleich es aus denselben Quellen geschöpft ist; so z.B. daß ich jetzt hier bin, daß ich, mit meinem Winterrock angetan, am Kamin sitze, daß ich dieses Papier mit den Händen betaste und ähnliches; vollends daß diese Hände selbst, daß überhaupt mein ganzer Körper da ist, wie könnte man mir das abstreiten? [...] ][ Rene Descartes: _Meditationes de prima philosophia._ AT VII. S. 18 f. ] #v(1em) #task(5, [ Fassen Sie das philosophische Problem des oben angegebenen Textes zusammen! ]) #task(6, [ Erläutern Sie an je einem eigenen Beispielen, welche Gründe Descartes für eine Ablehnung der Erkenntnis aus der Sinneswahrnehmung hervorbringt und welche dagegen sprechen können! ]) #task(5, [ Nehmen Sie begründet Stellung, ob man den Sinnen trauen kann! ]) #colbreak() #show: project.with( topic: "Descartes methodischer Zweifel", eh: true ) #table(columns: (1fr, auto), strong[Aufgabe], strong[P.], table.cell(fill: black.lighten(80%), strong[A1 -- Zusammenfassen]), table.cell(fill: black.lighten(80%), strong[5 P.]), [ Wesentliche Aspekte sind enthalten. - _Ausgangslage_: Es gibt Erkenntnis aus den Sinnen - _Problem_: Sinne können täuschen, also sind die Sinne nicht vertrauenswürdig - _Erwiderung_: es scheint Dinge zu geben, die aus den Sinnen stammen und nicht zweifelbar sind ], [\_\_ / 3], [ Die Formulierung ist in eigenen Worten gefasst. ], [\_\_ / 1], [ Die Formulierung ist kurz und präzise. ], [\_\_ / 1], table.cell(fill: black.lighten(80%), strong[A2 -- Erläutern]), table.cell(fill: black.lighten(80%), strong[6 P.]), [ Grund dafür wird genannt: - Sinne können täuschen, Gebot der Klugheit ], [\_\_ / 1], [ Grund degegen wird genannt: - Sinneswahrnehmungen finden aber statt und können nicht einfach ignoriert werden, Zweifel sollte berechtigt sein - evtl. eigene, da nicht genau in Aufgabenstellung beschrieben ], [\_\_ / 1], [ Die Formulierung ist nachvollziehbar und verständlich. ], [\_\_ / 2], [ Die Beispiele unterstützen je einmal die Position der Ablehnung empirischer Erkenntnis und einmal die Anerkennung empirischer Erkenntnis. ], [\_\_ / 2], table.cell(fill: black.lighten(80%), strong[A3 -- Stellungnehmen]), table.cell(fill: black.lighten(80%), strong[5 P.]), [ Die persönliche Meinung ist erkennbar. Z.B.: - Ich finde, dass man den Sinnen durchaus trauen kann. ], [\_\_ / 1], [ Argumente für und gegen die eigene Meinung werden vorgebracht. Z.B.: - Dafür: Sinne funktionieren meistens ziemlich verlässlich, sie grundlegend abzulehnen ist radikal und für den Alltag nicht sinnvoll - Dagegen: Es bietet einen philosophischen Mehrwert sich über die Verlässlichkeit unserer Erkenntniswege Gedanken zu machen. Die Sinne scheinen nicht immer gut zu funktionieren und können daher nicht als grundlegend sicherer Erkenntnisweg beschrieben werden. ], [\_\_ / 2], [ Die hervorgebrachten Argumente werden abgewogen, die Abwägung stützt die eigene Meinung. Z.B.: - das Gegenargument ist verständlich, jedoch sind wir nicht immer Philosophen. Daher müssen wir nicht ständig an unseren Erkenntnisquellen zweifeln. ], [\_\_ / 2], table.cell(colspan: 2, fill: black.lighten(80%), [#v(-0.5em)]), [], [ \_\_ / 16 ] )
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/src/defaults.typ
typst
MIT License
#let mass-spectrum-default-style = ( axes: ( tick: (length:-0.1, stroke: 0.4pt), frame: true, label: (offset: 0.3), stroke: 0.4pt ), title: (:), callipers: ( line: (stroke: gray + 0.45pt), content: (:) ), callouts: ( line: (stroke: gray + 0.45pt), ), peaks: ( stroke: (paint: black, thickness: 0.55pt, cap: "butt") ), data1: (peaks: (stroke: (paint: blue, thickness: 0.55pt, cap: "butt"))), data2: (peaks: (stroke: (paint: red, thickness: 0.55pt, cap: "butt"))), shift-amount: 0.13 )
https://github.com/caro3dc/typststuff
https://raw.githubusercontent.com/caro3dc/typststuff/main/reminder.typ
typst
#import "jx-style.typ": * #show: docu.with( size: "longbond-l" ) #align(horizon+center)[#text(size: 1in, weight: 900)[UT TASVE TI, WORK ON #ac("midblue")[EMPTECH] FIRST, THEN #ac("pink")[PE], THEN #ac("yellow")[III]]]
https://github.com/Woodman3/modern-ysu-thesis
https://raw.githubusercontent.com/Woodman3/modern-ysu-thesis/main/pages/bachelor-detail.typ
typst
MIT License
#import "../utils/datetime-display.typ": datetime-display #import "../utils/style.typ": 字号, 字体 #import "../utils/custom-cuti.typ" : fakebold #let bachelor-detail( anonymous: false, twoside: false, fonts: (:), info: (:), // 其他参数 stoke-width: 0.5pt, min-title-lines: 2, info-inset: (x: 0pt, bottom: 1pt), info-key-width: 100pt, info-key-font: "黑体", info-value-font: "宋体", column-gutter: 0pt, row-gutter: 11.5pt, anonymous-info-keys: ("grade", "student-id", "author", "supervisor", "supervisor-ii"), bold-info-keys: ("title",), bold-level: "bold", datetime-display: datetime-display, ) = { if type(info.submit-date) == datetime { info.submit-date = datetime-display(info.submit-date) } let info-key(body) = { set align(center) rect( width: 100%, inset: info-inset, stroke: none, text( font: fonts.at(info-key-font, default: "黑体"), size: 字号.四号, body ), ) } let info-value(key, body) = { set align(left) rect( width: 100%, inset: info-inset, stroke: none, text( font: fonts.at(info-value-font, default: "宋体"), size: 字号.四号, weight: if (key in bold-info-keys) { bold-level } else { "regular" }, bottom-edge: "descender", body, ), ) } let info-long-value(key, body) = { grid.cell(colspan: 1, info-value( key, if anonymous and (key in anonymous-info-keys) { "██████████" } else { body } ) ) } let info-short-value(key, body) = { info-value( key, if anonymous and (key in anonymous-info-keys) { "█████" } else { body } ) } pagebreak(weak: true,to:"odd") v(字号.小四*4) set align(center) fakebold(text(font:fonts.宋体,size:字号.小二,weight:"bold")[燕山大学本科生毕业设计(论文)]) v(字号.小二*2) text(font:fonts.黑体,size:字号.二号,info.title) v(字号.小二*12) block(width: auto,grid( columns: (3.03cm+0.75cm ,5.75cm), column-gutter: column-gutter, row-gutter: row-gutter, // stroke: stoke-width, info-key("学   院:"), info-long-value("department", info.department), info-key("专   业:"), info-long-value("major", info.major), info-key("姓   名:"), info-long-value("author", info.author), info-key("学   号:"), info-long-value("student-id", info.student-id), info-key("指 导 教 师:"), info-long-value("supervisor", info.supervisor.at(0)), info-key("答 辩 日 期:"), info-long-value("submit-date", info.submit-date), )) pagebreak(weak:false,to:"even") }
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/attach-p2.typ
typst
Apache License 2.0
// Test t and b attachments, part 2. --- // Test high subscript and superscript. $ sqrt(a_(1/2)^zeta), sqrt(a_alpha^(1/2)), sqrt(a_(1/2)^(3/4)) \ sqrt(attach(a, tl: 1/2, bl: 3/4)), sqrt(attach(a, tl: 1/2, bl: 3/4, tr: 1/2, br: 3/4)) $ --- // Test for no collisions between descenders/ascenders and attachments $ sup_(x in P_i) quad inf_(x in P_i) $ $ op("fff",limits: #true)^(y) quad op("yyy", limits:#true)_(f) $ --- // Test frame base. $ (-1)^n + (1/2 + 3)^(-1/2) $ --- #set text(size: 8pt) // Test that the attachments are aligned horizontally. $ x_1 p_1 frak(p)_1 2_1 dot_1 lg_1 !_1 \\_1 ]_1 "ip"_1 op("iq")_1 \ x^1 b^1 frak(b)^1 2^1 dot^1 lg^1 !^1 \\^1 ]^1 "ib"^1 op("id")^1 \ x_1 y_1 "_"_1 x^1 l^1 "`"^1 attach(I,tl:1,bl:1,tr:1,br:1) scripts(sum)_1^1 integral_1^1 abs(1/2)_1^1 \ x^1_1, "("b y")"^1_1 != (b y)^1_1, "[∫]"_1 [integral]_1 $
https://github.com/Shambuwu/stage-docs
https://raw.githubusercontent.com/Shambuwu/stage-docs/main/documenten/onderzoeksrapport.typ
typst
#align( center, text( size: 1.2em, [ *Competentie: Onderzoeken* \ Onderzoeksrapport en resultaten \ ], ) ) #align( center, figure( image("../bijlagen/onderzoeksrapport/OIG.jpg", width: 400pt ) ) ) #let date = datetime( year: 2023, month: 6, day: 30 ) #place( bottom + left, text[ *Student:* <NAME> \ *Studentnummer:* 405538 \ *Datum:* #date.display() \ *Onderwerp:* Competentie: Analyseren \ *Opleiding:* HBO-ICT \ *Studiejaar:* 3 \ ] ) #place( bottom + right, image("../bijlagen/logo.png", width: 175pt) ) #pagebreak() #set heading(numbering: "1.1") #show heading: it => { set block(below: 10pt) set text(weight: "bold") align(left, it) } #outline( title: [ *Inhoudsopgave* ], ) #set page( numbering: "1 / 1", number-align: right, ) #pagebreak() = Abstract Dit onderzoeksrapport presenteert een vergelijkende analyse van de prestaties tussen het gebruik van een Object Graph Mapper (OGM) en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. Het doel van dit onderzoek was om inzicht te krijgen in de impact van de OGM-functionaliteit op de verwerkingstijden en variabiliteit van de metingen. De dataset bestond uit 2349 nodes, 7678 relaties, 19998 eigenschappen en 2321 labels. De metingen betroffen de tijdsduur in milliseconden om alle nodes op te halen uit de database. De resultaten toonden aan dat het gebruik van OGM resulteerde in een gemiddelde tijdsduur van 52.1171 ms, terwijl de standaard Neo4j-driver een gemiddelde tijdsduur van 39.065 ms vertoonde. Bovendien vertoonden de metingen met OGM een hogere mate van variabiliteit in vergelijking met de standaard Neo4j-driver, zoals blijkt uit de analyse van de standaarddeviatie en variantie. Deze bevindingen hebben praktische implicaties voor het ontwerp en de implementatie van systemen die gebruikmaken van een Neo4j-database. Afhankelijk van de vereisten van het systeem, kan het gebruik van de standaard Neo4j-driver de voorkeur hebben vanwege kortere verwerkingstijden en een meer voorspelbaar gedrag. Het is echter belangrijk om rekening te houden met de specifieke context en vereisten van het systeem bij het maken van deze keuze. Hoewel dit onderzoek enkele beperkingen kent, zoals de beperkte dataset en de focus op het ophalen van alle nodes, draagt het bij aan het begrip van de prestatie-implicaties van het gebruik van OGM in een Neo4j-database. Toekomstig onderzoek kan zich richten op het verkennen van andere aspecten en scenario's, evenals het identificeren van optimalisaties voor OGM om de prestaties verder te verbeteren. Dit onderzoek biedt waardevolle inzichten voor ontwikkelaars en beheerders die gebruikmaken van Neo4j-databases, en kan dienen als basis voor weloverwogen beslissingen bij het kiezen tussen OGM en de standaard Neo4j-driver. #pagebreak() = Introductie == Inleiding Het onderzoeksrapport presenteert een analyse van metingen met betrekking tot de tijdsduur voor het ophalen van alle nodes uit een Neo4j-database. Het onderzoek is gebaseerd op een dataset bestaande uit 2349 nodes, 7678 relaties, 19998 eigenschappen en 2321 labels. De efficiënte opslag en verwerking van grote hoeveelheden gegevens zijn essentieel geworden in het moderne tijdperk van gegevensbeheer. Met zijn grafenstructuur biedt Neo4j een krachtig platform voor het beheren en verkennen van complexe relaties tussen entiteiten. Symfony wordt gebruikt als een robuuste en flexibile API-laag om toegang te bieden tot de database. Een belangrijk onderdeel van de Symfony API is de Object Graph Mapper (OGM) functionaliteit, die de vertaling tussen objectgeoriënteerde modellen en de grafenstructuur van Neo4j mogelijk maakt. Dit onderzoek is gemotiveerd door de behoefte om de prestaties van de Neo4j-database te verbeteren en de impact van OGM op de prestaties te onderzoeken. De focus van het onderzoek ligt op het ophalen van alle nodes uit de Neo4j-database. De resultaten van het onderzoek kunnen gebruikt worden om een keuze te maken tussen het gebruik van OGM of het gebruik van de standaard Neo4j-driver. == Onderzoeksvraag De onderzoeksvraag die in dit rapport wordt behandeld, luidt: "Wat is het verschil in prestaties tussen het gebruik van de Object Graph Mapper (OGM) en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database?" Deze onderzoeksvraag is geformuleerd om een vergelijking mogelijk te maken tussen de prestaties van een OGM en de standaard Neo4j-driver bij het uitvoeren van een specifieke taak, namelijk het ophalen van alle nodes uit de Neo4j-database. Hierbij wordt gekeken naar de tijdsduur die nodig is om deze taak uit te voeren. == Doelstellingen De volgende doelstellingen zijn geformuleerd om de onderzoeksvraag te beantwoorden: + Het vergelijken van de prestaties van een OGM en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. + Het bepalen van de invloed van de grootte van de dataset op de prestaties van een OGM en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. + Het identificeren van eventuele prestatieverschillen tussen een OGM en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. + Het bieden van inzicht in de geschiktheid van een OGM voor het ophalen van alle nodes uit een Neo4j-database. == Verwachte resultaten Op basis van de hiervoor genoemde doelstellingen worden de volgende resultaten verwacht: + Het verschil in tijdsduur tussen het gebruik van een OGM en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. + Mogelijke prestatievoordelen of -nadelen van een OGM ten opzichte van de standaard Neo4j-driver. + Aanbevelingen voor het gebruik van een OGM of de standaard Neo4j-driver. == Scope van het onderzoek Het onderzoek richt zich specifiek op het vergelijken van de prestaties van OGM en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. Andere aspecten van de Neo4j-database of andere taken worden buiten beschouwing gelaten in dit onderzoek. == Structuur van het rapport #box(height: 125pt, columns(2)[ #set par(justify: true) + *Introductie:* In dit hoofdstuk wordt een introductie gegeven op het onderwerp van het onderzoek. + *Methodiek:* In dit hoofdstuk wordt de methodiek van het onderzoek beschreven. + *Resultaten:* In dit hoofdstuk worden de resultaten van het onderzoek gepresenteerd. + *Alternatieven* In dit hoofdstuk worden alternatieven voor het gebruik van een OGM of de standaard Neo4j-driver besproken. + *Conclusie:* In dit hoofdstuk wordt een conclusie gegeven op basis van de resultaten van het onderzoek. ] ) #pagebreak() = Methodiek == Onderzoeksopzet Om de onderzoeksvraag te beantwoorden en de impact van OGM op de prestaties te onderzoeken, is een onderzoeksopset gehanteerd. Het opzet wordt beschreven in dit hoofdstuk. == Dataset Voor dit onderzoek is gebruikgemaakt van een dataset bestaande uit 2349 nodes, 7678 relaties, 19998 eigenschappen en 2321 labels. Dit is de dataset die beschikbaar is gesteld door de opdrachtgever van het project waar dit onderzoek onderdeel van uitmaakt. #figure( image("../bijlagen/onderzoeksrapport/graph.png", width: 300pt ), caption: "Grafiek van de dataset", supplement: "Figuur", kind: "figure" ) De dataset bestaat uit een verzameling van nodes die een bepaalde entiteit representeren. Deze nodes zijn onderling verbonden door relaties. De relaties representeren de relaties tussen de entiteiten. De nodes en relaties kunnen eigenschappen bevatten die de entiteiten en relaties beschrijven. #figure( [ ```json { "identity": 0, "labels": [ "Node" ], "properties": { "externalid": "100", "type": "HGNC" }, "elementId": "0" } ``` ], caption: "Voorbeeld van een node uit de dataset", supplement: "Figuur", kind: "figure" ) Zoals te zien is in het bovenstaande voorbeeld, bestaat een node uit een identiteit, een verzameling labels en een verzameling eigenschappen. De identiteit is een unieke identificatie van de node binnen de dataset. De labels zijn een verzameling van labels die de node categoriseren. De eigenschappen zijn een verzameling van eigenschappen die de node beschrijven. == Meetmethode Om de prestaties van een OGM en de standaard Neo4j-driver te vergelijken, is de tijdsduur gemeten die nodig is om alle nodes uit de dataset op te halen. De tijdsduur is gemeten met behulp van de PHP-functie `microtime()`. Deze functie geeft de huidige tijd in seconden en microseconden terug. Door het verschil te nemen tussen de tijd voor en na het uitvoeren van de taak, kan de tijdsduur worden bepaald. #figure( [ ```java public function saveQueryMeasurements(Neo4jClient $client): void { $measurements = []; for ($i = 0; $i < 100; $i++) { $startTime = microtime(true); // Haal alle nodes uit de Neo4j-database, // via de standaard Neo4j-driver $response = $client->getAllEntities(); $endTime = microtime(true); $executionTime = $endTime - $startTime; // Voeg de executionTime toe aan de lijst met metingen. // Vermenigvuldig de executionTime met 1000 om de tijd // in milliseconden te krijgen. $measurements[] = $executionTime * 1000; } // Sla de metingen op in een JSON-bestand $jsonMeasurements = json_encode($measurements); file_put_contents('measurements.json', $jsonMeasurements); } ``` ], caption: "Voorbeeld van het meten van de tijdsduur, geschreven in PHP.", supplement: "Figuur", kind: "figure" ) In het bovenstaande voorbeeld is te zien hoe de tijdsduur is gemeten. De metingen zijn uitgevoerd op een lokale ontwikkelomgeving. De metingen zijn uitgevoerd in een docker container met de volgende specificaties: #figure( [ ```sh root@3d18886dc705 ----------------- OS: Debian GNU/Linux 12 (bookworm) x86_64 Host: B450M DS3H Kernel: 6.4.2-zen1-1-zen Uptime: 3 hours, 42 mins Packages: 308 (dpkg) Shell: bash 5.2.15 Resolution: 2560x1440 CPU: AMD Ryzen 5 3600 (12) @ 3.600GHz GPU: AMD ATI Radeon RX 6600/6600 XT/6600M Memory: 10688MiB / 15912MiB ``` ], caption: "Specificaties van de docker container waarin de metingen zijn uitgevoerd.", supplement: "Figuur", kind: "figure" ) De resultaten van de metingen zijn opgeslagen in een JSON-bestand. Met deze resultaten kunnen de prestaties van een OGM en de standaard Neo4j-driver worden vergeleken. == Analysemethode De verzamelde metingen worden geanalyseerd om inzicht te krijgen in de prestatieverschillen tussen het gebruik van een OGM en de standaard Neo4j-driver. Hierbij worden statistsche technieken toegepast om de resultaten te vergelijken en te interpreteren. Voor de analyse van de resultaten is een script#footnote("Script is te vinden in ./bijlagen/onderszoeksrapport/main.py") ontwikkeld. Dit script is geschreven in Python en maakt gebruik van matplotlib, een Python-bibliotheek voor het maken van grafieken. Het script leest de metingen uit het JSON-bestand en maakt een grafiek van de metingen. De grafiek wordt opgeslagen als een PNG-bestand. Ook maakt het script gebruik van de Python-bibliotheek statistics om de standaarddeviatie en variantie van de metingen te berekenen. Een tweede script#footnote("Script is te vinden in ./bijlagen/onderzoeksrapport/tables.py") is ontwikkeld voor het creeëren van tabellen met de beschrijvende statistieken van de metingen. Dit script is geschreven in Python en maakt gebruik van tabulate, een Python-bibliotheek voor het maken van tabellen. Het script leest de metingen uit het JSON-bestand en berekent de beschrijvende statistieken van de metingen. De statistieken worden weergegeven in een tabel. De tabel wordt opgeslagen als een PNG-bestand. Het script voert de volgende stappen uit om de metingen te verwerken en de resultaten te genereren: + Inlezen van de gegevens: De metingen worden ingelezen uit het JSON-bestand. + Berekenen van de aspecten van de metingen: De gemiddelde, minimale en maximale tijdsduur worden berekend. Ook worden de standaarddeviatie en variantie berekend. + Berekenen van het verschil in tijdsduur: Het verschil in tijdsduur tussen het gebruik van een OGM en de standaard Neo4j-driver wordt berekend. + Genereren van een visuele plot: De metingen worden geplot in een grafiek. De grafiek wordt opgeslagen als een PNG-bestand. Door het gebruik van dit script kunnen de verzamelde gegevens op een gestructureerde en efficiënte manier worden geanalyseerd. Het script biedt de mogelijkheid om inzicht te krijgen in verschillende aspecten van de metingen, zoals de gemiddelde tijdsduur, standaarddeviatie en het verschil in tijdsduur. Dit inzicht kan worden gebruikt om de resultaten te interpreteren en conclusies te trekken. == Validatie Om de validiteit van de resultaten te waarborgen, is gebruikgemaakt van een aantal validatietechnieken. Deze technieken zijn toegepast om de betrouwbaarheid van de resultaten te verhogen. De validatietechnieken die zijn toegepast, worden in dit hoofdstuk beschreven. - *Betrouwbaarheid van de metingen:* Om de betrouwbaarheid van de metingen te verhogen, zijn de metingen 100 keer uitgevoerd. De metingen zijn uitgevoerd op een lokale ontwikkelomgeving, in een docker container. De metingen zijn uitgevoerd op een rustig moment, om de invloed van andere processen te minimaliseren. - *Steekproefgrootte en representativiteit:* De steekproefgrootte is een dataset van 2349 nodes. Dit is de dataset die beschikbaar is gesteld door de opdrachtgever van het project waar dit onderzoek onderdeel van uitmaakt. De grootte van de dataset is representatief voor de dataset die gebruikt wordt in het project. - *Interne validiteit:* De standaard Neo4j-driver dient als controlegroep voor de metingen. De metingen met de standaard Neo4j-driver worden gebruikt als referentiepunt voor de metingen met een OGM. De metingen met de standaard Neo4j-driver worden uitgevoerd op dezelfde dataset als de metingen met een OGM. Hierdoor is de interne validiteit van de resultaten gewaarborgd. - *Kritische reflectie:* Een beperking van dit onderzoek is dat grootte van de dataset relatief klein is. De dataset bestaat uit 2349 nodes. Dit is een relatief kleine dataset. De resultaten van dit onderzoek zijn mogelijk niet representatief voor grotere datasets. Een aanbeveling voor vervolgonderzoek is om de resultaten te valideren met een grotere dataset. Ook is er geen variatie in de grootte van de dataset. De grootte van de dataset is constant. Een aanbeveling voor vervolgonderzoek is om de resultaten te valideren met datasets van verschillende groottes. #pagebreak() = Resultaten Dit hoofdstuk presenteert de resultaten van het onderzoek naar de impact van de OGM op de prestaties van het ophalen van alle nodes uit de database. De resultaten worden gepresenteerd aan de hand van de analyses van de verzamelde metingen. == Beschrijvende statistieken De beschrijvende statistieken van de metingen zijn berekend met behulp van het script dat is beschreven in het hoofdstuk Methodiek. Er wordt gekeken naar de gemiddelde, minimale en maximale tijdsduur van de metingen. Ook wordt er gekeken naar de standaarddeviatie en variantie van de metingen. De gemiddelde, minimale en maximale tijdsduur bieden inzicht in de prestaties van zowel de OGM als de standaard Neo4j-driver. Met deze statistieken kunnen er vergelijkingen worden gesteld tussen de prestaties van beide benaderingen. Daarnaast geven de gemiddelde, minimale en maximale tijdsduur ook inzicht in de variabiliteit van de metingen, terwijl de standaarddeviatie en variantie informatie verschaffen over de mate van spreiding van de metingen. == Vergelijking van de prestaties #figure( table( columns: 6, [Dataset], [Gemiddelde], [Standaarddeviatie], [Variantie], [Minimum],[Maximum], [Met OGM], [52.1171], [13.789], [190.138], [47.3928], [187.796], [Zonder OGM], [39.065], [2.2187], [4.92264], [35.6419], [53.942], ), caption: "Vergelijking van de prestaties van een OGM en de standaard Neo4j-driver.", supplement: "Tabel", kind: "figuur" ) Dit tabel toont de beschrijvende statistieken van de metingen. Alle statistieken zijn in milliseconden. Dit tabel#footnote("Oorspronkelijke generatie van dit tabel is te vinden in ./bijlagen/onderzoeksrapport/tabel.txt") is gebaseerd op het tabel dat is gegenereerd door het script dat is beschreven in het hoofdstuk Methodiek. Er kunnen enkele observaties worden gemaakt op basis van dit tabel: + *Gemiddelde tijdsduur:* De gemiddelde tijdsduur voor het ophalen van alle nodes uit de database met behulp van de OGM is 52.1171 milliseconden, terwijl de gemiddelde tijdsduur zonder het gebruik van de OGM 39.065 milliseconden bedraagt. Hieruit valt mogelijk te concluderen dat het gebruik van de OGM een negatieve invloed heeft op de prestaties van het ophalen van alle nodes uit de database. + *Variabiliteit van metingen:* De standaarddeviatie van de metingen met de OGM is 13.789 milliseconden, terwijl deze slechts 2.2187 milliseconden is zonder de OGM. Dit wijst op een grotere spreiding in de metingen met de OGM, wat betekent dat de prestaites van de OGM mogelijk meer variëren dan de prestaties zonder de OGM. + *Spreiding van metingen:* De minimale en maximale tijdsduur geven inzicht in het bereik van de metingen. Met de OGM varieert de tijdsduur tussen de 47.3928 milliseconden en 187.769 milliseconden, terwijl de tijdsduur zonder de OGM varieert tussen de 35.6419 milliseconden en 53.942 milliseconden. Ook dit geeft mogelijk aan dat de tijdsduur van het ophalen van alle nodes meer varieert met de OGM. Deze observaties suggereren dat het gebruik van een OGM de prestaties van het ophalen van alle nodes uit de database kan beïnvloeden. De prestaties van de OGM lijken meer te variëren dan de prestaties zonder de OGM. == Visuele weergave De resultaten van de metingen worden gepresenteerd in een grafiek die de tijdsduur van de metingen weergeeft. De grafiek toont twee kleuren: één voor de metingen met OGM en één voor de metingen zonder OGM. De grafiek illustreert de verschillen in tijdsduur tussen de twee benaderingen en biedt een visuele weergave van de prestaties. Daarnaast kunnen individuele datapunten worden weergegeven om de variabiliteit en spreiding van de metingen te tonen. Tenslotte zijn er subplots toegevoegd. Deze subplots dienen als extra visuele weergave van de prestaties. #grid( columns: (auto, auto), rows: (auto, auto), column-gutter: 100pt, [ #figure( image("../bijlagen/onderzoeksrapport/plot_1.png", width: 300pt ), caption: "Grafiek van de metingen 1", supplement: "Figuur", kind: "figure" ) ], [ #figure( image("../bijlagen/onderzoeksrapport/plot_2.png", width: 300pt ), caption: "Grafiek van de metingen 2", supplement: "Figuur", kind: "figure" ) ] ) Zoals voorheen al is geobserveerd, lijkt het gebruik van de OGM een negatieve invloed te hebben op de prestaties van het ophalen van alle nodes uit de database. De grafiek toont aan dat de tijdsduur van de metingen met de OGM hoger is dan de tijdsduur van de metingen zonder de OGM. Ook is te zien dat de tijdsduur van de metingen met de OGM meer varieert dan de tijdsduur van de metingen zonder de OGM. == Discussie In deze sectie worden de resultaten van het onderzoek besproken en geïnterpreteerd. Het doel is om inzicht te bieden in de bevindingen en de implicaties ervan te analyseren. De resultaten worden geanalyseerd aan de hand van de onderzoeksvraag en de doelstellingen van het onderzoek. === Prestatieverschillen tussen de OGM en de standaard Neo4j-driver Uit de resultaten blijkt dat de gemiddelde tijdsduur voor het ophalen van alle nodes met OGM (52.1171 ms) hoger is dan zonder OGM (39.065 ms). Dit suggereert dat het gebruik van OGM de prestaties kan beïnvloeden en leiden tot langere verwerkingstijden. Bovendien vertoont de OGM-gebaseerde benadering een grotere standaarddeviatie (13.789 ms) in vergelijking met de standaard Neo4j-driver (2.2187 ms), wat wijst op een hogere mate van variabiliteit in de metingen met de OGM. === Mogelijke verklaringen Er zijn verschillende factoren die kunnen bijdragen aan de waargenomen prestatieverschillen. Ten eerste voegt de OGM een extra laag toe aan de interactie tussen het objectgeoriënteerde model en de grafenstructuur van neo4j. Deze extra complexiteit kan leiden tot vertragingen en hogere verwerkingstijden. Ten tweede kan de implementatie van de OGM en de configuratie ervan invloed hebben op deze prestaties. Het is mogelijk dat bepaalde instellingen of optimalisaties de efficiëntie van de OGM beïnvloeden. === Praktische implicaties Op basis van de bevindingen kunnen praktische implicaties worden afgeleid. Indien de snelheid van het ophalen van alle nodes een cruciale factor is in het systeem, kan overwogen worden om de standaard Neo4j-driver te gebruiken in plaats van de OGM implementatie. Dit kan de prestaties van het systeem verbeteren en de efficiëntie van het ophalen van alle nodes verhogen. Het is echter belangrijk om op te merken dat de keuze afhankelijk is van de context van het systeem. Andere aspecten, zoals complexiteit van het model en de behoefte aan grafenmanipulaties, kunnen ook een rol spelen bij de keuze tussen de OGM en de standaard Neo4j-driver. Tenslotte is het ook belangrijk om de voordelen van de OGM te benadrukken. De OGM biedt een objectgeoriënteerde benadering van de grafenstructuur van Neo4j. Dit kan de ontwikkeling van het systeem vereenvoudigen en de complexiteit van de interactie met de Neo4j-database verminderen. === Beperkingen en aanbevelingen Bij het interpreteren van de resultaten is het belangrijk om rekening te houden met enkele beperkingen van dit onderzoek. Ten eerste is de dataset beperkt tot een specifieke grootte. Het is mogelijk dat de prestatieverschillen tussen OGM en de standaard Neo4j-driver variëren bij gebruik van grotere datasets. Daarnaast is de focus van dit onderzoek beperkt tot het ophalen van alle nodes. Het is mogelijk dat de prestatieverschillen in andere contexten of bij het uitvoeren van verschillende soorten operaties op de database anders zijn. Voor verder onderzoek wordt aanbevolen om de prestatieverschillen tussen OGM en de standaard Neo4j-driver verder te onderzoeken in verschillende scenario's en met diverse datasets. Daarnaast kan het interessant zijn om te kijken naar optimalisaties en configuratie-instellingen die de prestaties van OGM kunnen verbeteren. #pagebreak() = Conclusie Dit onderzoek richtte zich op het vergelijken van de prestaties tussen het gebruik van een Object Graph Mapper (OGM) en de standaard Neo4j-driver bij het ophalen van alle nodes uit een Neo4j-database. De resultaten van het onderzoek bieden inzicht in de impact van de OGM-functionaliteit op de verwerkingstijden en variabiliteit van de metingen. Uit de bevindingen blijkt dat het gebruik van OGM resulteert in een gemiddelde tijdsduur van 52.1171 ms, terwijl de standaard Neo4j-driver een gemiddelde tijdsduur van 39.065 ms vertoont. Dit duidt op een prestatieverschil tussen beide benaderingen, waarbij de OGM-gebaseerde benadering over het algemeen langere verwerkingstijden laat zien. Bovendien blijkt uit de analyse van de standaarddeviatie en variantie dat de metingen met OGM een hogere mate van variabiliteit vertonen in vergelijking met de standaard Neo4j-driver. Deze bevindingen hebben praktische implicaties voor het ontwerp en de implementatie van systemen die gebruikmaken van een Neo4j-database. Indien de snelheid van het ophalen van alle nodes een cruciale factor is in het systeem, kan overwogen worden om de standaard Neo4j-driver te verkiezen boven de OGM-functionaliteit. Door de standaard driver te gebruiken, kunnen kortere verwerkingstijden worden gerealiseerd en kan een meer voorspelbaar gedrag worden verkregen. Het is echter belangrijk om op te merken dat de keuze tussen OGM en de standaard Neo4j-driver afhankelijk is van de specifieke vereisten en context van het systeem. Andere aspecten, zoals de complexiteit van het objectgeoriënteerde model en de behoefte aan geavanceerde grafenmanipulaties, kunnen doorslaggevend zijn bij de keuze voor OGM. Hoewel dit onderzoek inzicht heeft geboden in de prestatieverschillen tussen OGM en de standaard Neo4j-driver, zijn er enkele beperkingen die moeten worden overwogen. De dataset is beperkt tot een specifieke omvang en kenmerken, en de focus ligt op het ophalen van alle nodes. Het is mogelijk dat de prestatieverschillen variëren bij gebruik van grotere datasets of andere soorten operaties op de database. Voor toekomstig onderzoek wordt aanbevolen om de prestatieverschillen tussen OGM en de standaard Neo4j-driver verder te onderzoeken in verschillende scenario's en met diverse datasets. Daarnaast kunnen optimalisaties en configuratie-instellingen voor OGM worden onderzocht om de prestaties te verbeteren en de variabiliteit te verminderen. Dit onderzoek draagt bij aan het begrip van de prestatie-implicaties van het gebruik van OGM bij het ophalen van alle nodes uit een Neo4j-database. De bevindingen kunnen worden toegepast bij het maken van weloverwogen keuzes tussen OGM en de standaard Neo4j-driver, afhankelijk van de specifieke vereisten van het systeem en de gewenste prestaties. #pagebreak() = Literatuurlijst #bibliography( title: "", "../bibliografie/hayagriva.yml" ) #pagebreak() = Bronnen #align(left, table( columns: (auto, auto, auto), rows: (auto, auto, auto), align: left, inset: 10pt, stroke: none, [*Bijlagen*], [], [], [Hanzehogeschool Groningen logo], [Hanzehogeschool Groningen], [https://freebiesupply.com/logos/hanzehogeschool-groningen-logo/], [Titelpagina figuur], [DALL-E-2, OpenAI], [bijlagen -> onderzoeksrapport -> OIG.jpg], [Figuur 1], [<NAME>], [bijlagen -> onderzoeksrapport -> graph.png], [Figuur 2], [<NAME>], [Neo4j Browser], [Figuur 3], [<NAME>], [broncode -> backend -> src -> Controller -> QueryController.php.png], [Figuur 4], [<NAME>], [Neo4j Container], [Tabel 1], [<NAME>], [bijlagen -> onderzoeksrapport -> tabel.txt], [Figuur 5], [<NAME>], [bijlagen -> onderzoeksrapport -> plot_1.png], [Figuur 6], [<NAME>], [bijlagen -> onderzoeksrapport -> plot_2.png], ) )
https://github.com/rabotaem-incorporated/probability-theory-notes
https://raw.githubusercontent.com/rabotaem-incorporated/probability-theory-notes/master/main.typ
typst
#import "utils/core.typ": * #show: notes.with( name: "Конспект лекций по теории вероятностей", short-name: "Теория вероятностей", lector: "<NAME>", info: "СПБГУ МКН, Современное программирование, 2023-2024", ) #show: show-references #include "sections/01-elementary/!sec.typ" #include "sections/02-general/!sec.typ" #include "sections/03-characteristic-functions/!sec.typ" #include "sections/04-discrete-random-processes/!sec.typ" #include "appendix.typ"
https://github.com/orkhasnat/resume
https://raw.githubusercontent.com/orkhasnat/resume/master/modern-big/resume-lib.typ
typst
#import "fa-lib.typ": * // font sizes #let bf = 9.5pt #let h1f = bf+4pt #let h2f = bf+2pt #let h2secf = bf+1pt #let h3f = bf - 1pt #let markerf = 7pt #let sepf = markerf - 2pt #let padf = 2pt #let spf= 1em // const color #let color-darknight = rgb("141E1E") #let color-darkgray = rgb("213131") #let default-accent-color = rgb("2C7865") #let color-lightgray = rgb("415161") // const icons #let linkedin-icon = box(fa-icon("linkedin", fa-set: "Brands", fill: color-darknight)) #let github-icon = box(fa-icon("github", fa-set: "Brands", fill: color-darknight)) #let phone-icon = box(fa-phone(fill: color-darknight)) #let email-icon = box(fa-icon("at", fill: color-darknight)) /// Helpers #let __justify_align(left_body, right_body) = { set text(fill:color-lightgray ) block[ #left_body #box(width: 1fr)[ #align(right)[ #right_body ] ] ] } #let __justify_align_3(left_body, mid_body, right_body) = { block[ #box(width: 1fr)[ #align(left)[ #left_body ] ] #box(width: 1fr)[ #align(center)[ #mid_body ] ] #box(width: 1fr)[ #align(right)[ #right_body ] ] ] } #let github-link(github_path) = { set box(height: 11pt) align(right + horizon)[ #fa-icon("github", fa-set: "Brands", fill: color-darkgray) #link("https://github.com/" + github_path, github_path) ] } #let secondary-right-header(body, accent_color: default-accent-color) = { set text(accent_color, size: h2secf, style: "italic", weight: "medium") body } #let tertiary-right-header(body) = { set text(weight: "medium", style: "italic", size: h3f) body } #let justified-header(primary, secondary) = { set block(above: spf*0, below: spf) pad[ #__justify_align[ == #primary ][ #secondary-right-header[#secondary] ] ] } #let secondary-justified-header(primary, secondary) = { __justify_align[ === #primary ][ #tertiary-right-header[#secondary] ] } /// --- End of Helpers #let resume( author: (:), accent_color: default-accent-color, body) = { set document( author: author.firstname + " " + author.lastname, title: "resume", ) set text( font: ("Atkinson Hyperlegible"), lang: "en", size: bf, fill: color-darkgray, hyphenate: false, fallback: true ) set page( paper: "a4", margin: (left: 15mm, right: 15mm, top: 10mm, bottom: 10mm), footer-descent: 0pt, ) // set paragraph spacing show par: set block(above: spf, below: spf) set par(justify: true,linebreaks: "optimized") set heading( numbering: none, outlined: false, ) show heading.where(level:1): it => [ #set block(above: spf*0, below: spf) #set text( size: h1f, weight: "regular" ) #align(left)[ // Simple Design #text(fill:default-accent-color)[#strong[#it.body]] // Fancy Deesign // #text[#strong[#text(accent_color)[#it.body.text.slice(0, 3)]]]#strong[#text[#it.body.text.slice(3)]] #box(width: 1fr, line(length: 100%)) ] ] show heading.where(level: 2): it => { set text(color-darkgray, size: h2f, style: "normal", weight: "bold") it.body } show heading.where(level: 3): it => { set text(size: h3f, weight: "bold") smallcaps[#it.body] } let name = { align(center)[ #block[ #set text(size: 32pt, style: "normal", font: ("Free Serif")) #text(accent_color, weight: "regular")[#author.firstname] #text(weight: "bold")[#author.lastname] ] ] } let contacts = { set box(height: markerf) let separator = box(width: sepf) align(center)[ #set text(size: h2f, weight: "regular", style: "normal",fill:default-accent-color) #block[ #align(horizon)[ #phone-icon // #box[#text(author.phone)] #box[#link("tel:" + author.phone)[#author.phone]] #separator #email-icon #box[#link("mailto:" + author.email)[#author.email]] #separator #github-icon #box[#link("https://github.com/" + author.github)[#author.github]] #separator #linkedin-icon #box[ #link("https://www.linkedin.com/in/" + author.linkedin)[#author.firstname #author.lastname] ] ] ] ] } name // positions contacts body } #let resume-item(body) = { set text(size: bf, style: "normal", weight: "light") set par(leading: spf*0.75) body } #let resume-entry( title: none, location: "", date: "", description: "" ) = { pad[ #justified-header(title, location) #secondary-justified-header(description, date) ] } #let resume-skill-item(category, items) = { set block(below: spf*0.65) set pad(top: padf) pad[ #grid( columns: (25fr, 70fr), gutter: 15pt, align(right)[ #set text(hyphenate: false) == #category ], align(left)[ #set text(size: h2secf, style: "normal", weight: "light",fill:default-accent-color,) #items.join(", ") ], ) ] } /// ---- End of Resume Template ---- // My custom functions #let resume-achievement(body) = { // let t = text.with(weight:"black") set list( tight:true, marker: ([#box(height:markerf,fa-trophy(fill:color-lightgray))],[]) ) body } #let resume-achievement2(title,rank) = { __justify_align[ === #fa-trophy(fill:color-lightgray) #text(fill:color-darkgray,weight:"black")[#title] ][ #tertiary-right-header[ #text(fill:default-accent-color)[#rank] ] ] // secondary-justified-header(fa-trophy()+title,rank) } #let resume-cocurr(body) = { set list( tight:true, marker: [#box(height:markerf,fa-award(fill:color-lightgray))] ) body } #let resume-project( title: none, location: "", stack:"" ) = { pad[ #justified-header(title, location) #set text(fill:color-lightgray,weight:"bold") #set list( tight: true, marker:[#box(height:markerf,fa-code(fill:default-accent-color))], indent: padf, body-indent: spf* 0.5 ) #v(padf) - #stack ] } #let resume-ref-iut(name,position,mail)={ resume-entry( title: name, location: [ #link("mailto:"+mail)[#box(height:markerf,fa-envelope(fill:color-lightgray)) #mail] ], date: "", description:[ // #v(padf) #position \ Computer Science and Engineering Department\ Islamic University of Technology ] ) } #let resume-ref( name, position, PoE, // PoE - Place of Employment phone, mail ) = { v(-2*padf) table( columns: 2, // inset: (0pt,5pt), // same as below inset:( x:0pt, y:5pt, ), stroke: none, column-gutter: 1fr, align:(left,right), [== #name], [ #tertiary-right-header([ #set text(fill:default-accent-color) #box[#fa-phone(fill:color-lightgray) #link("tel:" + phone)[#phone]] ]) ], [ #text(color-lightgray,size: h3f, weight: "bold")[#position]\ #text(color-lightgray,size: h3f, weight: "bold")[#PoE] ], [#if mail!="" { tertiary-right-header([ #set text(fill:default-accent-color) #box[#fa-envelope(fill:color-lightgray) #link("mailto:" + mail)[#mail]] ]) }] ) }
https://github.com/WinstonMDP/knowledge
https://raw.githubusercontent.com/WinstonMDP/knowledge/master/orders.typ
typst
#import "cfg.typ": cfg #show: cfg = Порядки $<=$ - предпорядок $:= med <=$ рефлексивное и транзитивное. $<=$ - порядок $:= med <=$ антисимметричный предпорядок. $<$ - строгий порядок $:= med <$ иррефлексивное и транзитивное.
https://github.com/juruoHBr/typst_xdutemplate
https://raw.githubusercontent.com/juruoHBr/typst_xdutemplate/main/test.typ
typst
#import "@preview/cuti:0.2.1": show-cn-fakebold #show strong: show-cn-fakebold *keywords*
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/linebreak_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test consecutive breaks. Two consecutive \ \ breaks and three \ \ more.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/container-fill.typ
typst
Apache License 2.0
#set page(height: 100pt) #let words = lorem(18).split() #block(inset: 8pt, width: 100%, fill: aqua, stroke: aqua.darken(30%))[ #words.slice(0, 13).join(" ") #box(fill: teal, outset: 2pt)[tempor] #words.slice(13).join(" ") ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2600.typ
typst
Apache License 2.0
#let data = ( ("BLACK SUN WITH RAYS", "So", 0), ("CLOUD", "So", 0), ("UMBRELLA", "So", 0), ("SNOWMAN", "So", 0), ("COMET", "So", 0), ("BLACK STAR", "So", 0), ("WHITE STAR", "So", 0), ("LIGHTNING", "So", 0), ("THUNDERSTORM", "So", 0), ("SUN", "So", 0), ("ASCENDING NODE", "So", 0), ("DESCENDING NODE", "So", 0), ("CONJUNCTION", "So", 0), ("OPPOSITION", "So", 0), ("BLACK TELEPHONE", "So", 0), ("WHITE TELEPHONE", "So", 0), ("BALLOT BOX", "So", 0), ("BALLOT BOX WITH CHECK", "So", 0), ("BALLOT BOX WITH X", "So", 0), ("SALTIRE", "So", 0), ("UMBRELLA WITH RAIN DROPS", "So", 0), ("HOT BEVERAGE", "So", 0), ("WHITE SHOGI PIECE", "So", 0), ("BLACK SHOGI PIECE", "So", 0), ("SHAMROCK", "So", 0), ("REVERSED ROTATED FLORAL HEART BULLET", "So", 0), ("BLACK LEFT POINTING INDEX", "So", 0), ("BLACK RIGHT POINTING INDEX", "So", 0), ("WHITE LEFT POINTING INDEX", "So", 0), ("WHITE UP POINTING INDEX", "So", 0), ("WHITE RIGHT POINTING INDEX", "So", 0), ("WHITE DOWN POINTING INDEX", "So", 0), ("SKULL AND CROSSBONES", "So", 0), ("CAUTION SIGN", "So", 0), ("RADIOACTIVE SIGN", "So", 0), ("BIOHAZARD SIGN", "So", 0), ("CADUCEUS", "So", 0), ("ANKH", "So", 0), ("ORTHODOX CROSS", "So", 0), ("CHI RHO", "So", 0), ("CROSS OF LORRAINE", "So", 0), ("CROSS OF JERUSALEM", "So", 0), ("STAR AND CRESCENT", "So", 0), ("FARSI SYMBOL", "So", 0), ("ADI SHAKTI", "So", 0), ("HAMMER AND SICKLE", "So", 0), ("PEACE SYMBOL", "So", 0), ("YIN YANG", "So", 0), ("TRIGRAM FOR HEAVEN", "So", 0), ("TRIGRAM FOR LAKE", "So", 0), ("TRIGRAM FOR FIRE", "So", 0), ("TRIGRAM FOR THUNDER", "So", 0), ("TRIGRAM FOR WIND", "So", 0), ("TRIGRAM FOR WATER", "So", 0), ("TRIGRAM FOR MOUNTAIN", "So", 0), ("TRIGRAM FOR EARTH", "So", 0), ("WHEEL OF DHARMA", "So", 0), ("WHITE FROWNING FACE", "So", 0), ("WHITE SMILING FACE", "So", 0), ("BLACK SMILING FACE", "So", 0), ("WHITE SUN WITH RAYS", "So", 0), ("FIRST QUARTER MOON", "So", 0), ("LAST QUARTER MOON", "So", 0), ("MERCURY", "So", 0), ("FEMALE SIGN", "So", 0), ("EARTH", "So", 0), ("MALE SIGN", "So", 0), ("JUPITER", "So", 0), ("SATURN", "So", 0), ("URANUS", "So", 0), ("NEPTUNE", "So", 0), ("PLUTO", "So", 0), ("ARIES", "So", 0), ("TAURUS", "So", 0), ("GEMINI", "So", 0), ("CANCER", "So", 0), ("LEO", "So", 0), ("VIRGO", "So", 0), ("LIBRA", "So", 0), ("SCORPIUS", "So", 0), ("SAGITTARIUS", "So", 0), ("CAPRICORN", "So", 0), ("AQUARIUS", "So", 0), ("PISCES", "So", 0), ("WHITE CHESS KING", "So", 0), ("WHITE CHESS QUEEN", "So", 0), ("WHITE CHESS ROOK", "So", 0), ("WHITE CHESS BISHOP", "So", 0), ("WHITE CHESS KNIGHT", "So", 0), ("WHITE CHESS PAWN", "So", 0), ("BLACK CHESS KING", "So", 0), ("BLACK CHESS QUEEN", "So", 0), ("BLACK CHESS ROOK", "So", 0), ("BLACK CHESS BISHOP", "So", 0), ("BLACK CHESS KNIGHT", "So", 0), ("BLACK CHESS PAWN", "So", 0), ("BLACK SPADE SUIT", "So", 0), ("WHITE HEART SUIT", "So", 0), ("WHITE DIAMOND SUIT", "So", 0), ("BLACK CLUB SUIT", "So", 0), ("WHITE SPADE SUIT", "So", 0), ("BLACK HEART SUIT", "So", 0), ("BLACK DIAMOND SUIT", "So", 0), ("WHITE CLUB SUIT", "So", 0), ("HOT SPRINGS", "So", 0), ("QUARTER NOTE", "So", 0), ("EIGHTH NOTE", "So", 0), ("BEAMED EIGHTH NOTES", "So", 0), ("BEAMED SIXTEENTH NOTES", "So", 0), ("MUSIC FLAT SIGN", "So", 0), ("MUSIC NATURAL SIGN", "So", 0), ("MUSIC SHARP SIGN", "Sm", 0), ("WEST SYRIAC CROSS", "So", 0), ("EAST SYRIAC CROSS", "So", 0), ("UNIVERSAL RECYCLING SYMBOL", "So", 0), ("RECYCLING SYMBOL FOR TYPE-1 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR TYPE-2 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR TYPE-3 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR TYPE-4 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR TYPE-5 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR TYPE-6 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR TYPE-7 PLASTICS", "So", 0), ("RECYCLING SYMBOL FOR GENERIC MATERIALS", "So", 0), ("BLACK UNIVERSAL RECYCLING SYMBOL", "So", 0), ("RECYCLED PAPER SYMBOL", "So", 0), ("PARTIALLY-RECYCLED PAPER SYMBOL", "So", 0), ("PERMANENT PAPER SIGN", "So", 0), ("WHEELCHAIR SYMBOL", "So", 0), ("DIE FACE-1", "So", 0), ("DIE FACE-2", "So", 0), ("DIE FACE-3", "So", 0), ("DIE FACE-4", "So", 0), ("DIE FACE-5", "So", 0), ("DIE FACE-6", "So", 0), ("WHITE CIRCLE WITH DOT RIGHT", "So", 0), ("WHITE CIRCLE WITH TWO DOTS", "So", 0), ("BLACK CIRCLE WITH WHITE DOT RIGHT", "So", 0), ("BLACK CIRCLE WITH TWO WHITE DOTS", "So", 0), ("MONOGRAM FOR YANG", "So", 0), ("MONOGRAM FOR YIN", "So", 0), ("DIGRAM FOR GREATER YANG", "So", 0), ("DIGRAM FOR LESSER YIN", "So", 0), ("DIGRAM FOR LESSER YANG", "So", 0), ("DIGRAM FOR GREATER YIN", "So", 0), ("WHITE FLAG", "So", 0), ("BLACK FLAG", "So", 0), ("HAMMER AND PICK", "So", 0), ("ANCHOR", "So", 0), ("CROSSED SWORDS", "So", 0), ("STAFF OF AESCULAPIUS", "So", 0), ("SCALES", "So", 0), ("ALEMBIC", "So", 0), ("FLOWER", "So", 0), ("GEAR", "So", 0), ("STAFF OF HERMES", "So", 0), ("ATOM SYMBOL", "So", 0), ("FLEUR-DE-LIS", "So", 0), ("OUTLINED WHITE STAR", "So", 0), ("THREE LINES CONVERGING RIGHT", "So", 0), ("THREE LINES CONVERGING LEFT", "So", 0), ("WARNING SIGN", "So", 0), ("HIGH VOLTAGE SIGN", "So", 0), ("DOUBLED FEMALE SIGN", "So", 0), ("DOUBLED MALE SIGN", "So", 0), ("INTERLOCKED FEMALE AND MALE SIGN", "So", 0), ("MALE AND FEMALE SIGN", "So", 0), ("MALE WITH STROKE SIGN", "So", 0), ("MALE WITH STROKE AND MALE AND FEMALE SIGN", "So", 0), ("VERTICAL MALE WITH STROKE SIGN", "So", 0), ("HORIZONTAL MALE WITH STROKE SIGN", "So", 0), ("MEDIUM WHITE CIRCLE", "So", 0), ("MEDIUM BLACK CIRCLE", "So", 0), ("MEDIUM SMALL WHITE CIRCLE", "So", 0), ("MARRIAGE SYMBOL", "So", 0), ("DIVORCE SYMBOL", "So", 0), ("UNMARRIED PARTNERSHIP SYMBOL", "So", 0), ("COFFIN", "So", 0), ("FUNERAL URN", "So", 0), ("NEUTER", "So", 0), ("CERES", "So", 0), ("PALLAS", "So", 0), ("JUNO", "So", 0), ("VESTA", "So", 0), ("CHIRON", "So", 0), ("BLACK MOON LILITH", "So", 0), ("SEXTILE", "So", 0), ("SEMISEXTILE", "So", 0), ("QUINCUNX", "So", 0), ("SESQUIQUADRATE", "So", 0), ("SOCCER BALL", "So", 0), ("BASEBALL", "So", 0), ("SQUARED KEY", "So", 0), ("WHITE DRAUGHTS MAN", "So", 0), ("WHITE DRAUGHTS KING", "So", 0), ("BLACK DRAUGHTS MAN", "So", 0), ("BLACK DRAUGHTS KING", "So", 0), ("SNOWMAN WITHOUT SNOW", "So", 0), ("SUN BEHIND CLOUD", "So", 0), ("RAIN", "So", 0), ("BLACK SNOWMAN", "So", 0), ("THUNDER CLOUD AND RAIN", "So", 0), ("TURNED WHITE SHOGI PIECE", "So", 0), ("TURNED BLACK SHOGI PIECE", "So", 0), ("WHITE DIAMOND IN SQUARE", "So", 0), ("CROSSING LANES", "So", 0), ("DISABLED CAR", "So", 0), ("OPHIUCHUS", "So", 0), ("PICK", "So", 0), ("CAR SLIDING", "So", 0), ("HELMET WITH WHITE CROSS", "So", 0), ("CIRCLED CROSSING LANES", "So", 0), ("CHAINS", "So", 0), ("NO ENTRY", "So", 0), ("ALTERNATE ONE-WAY LEFT WAY TRAFFIC", "So", 0), ("BLACK TWO-WAY LEFT WAY TRAFFIC", "So", 0), ("WHITE TWO-WAY LEFT WAY TRAFFIC", "So", 0), ("BLACK LEFT LANE MERGE", "So", 0), ("WHITE LEFT LANE MERGE", "So", 0), ("DRIVE SLOW SIGN", "So", 0), ("HEAVY WHITE DOWN-POINTING TRIANGLE", "So", 0), ("LEFT CLOSED ENTRY", "So", 0), ("SQUARED SALTIRE", "So", 0), ("FALLING DIAGONAL IN WHITE CIRCLE IN BLACK SQUARE", "So", 0), ("BLACK TRUCK", "So", 0), ("RESTRICTED LEFT ENTRY-1", "So", 0), ("RESTRICTED LEFT ENTRY-2", "So", 0), ("ASTRONOMICAL SYMBOL FOR URANUS", "So", 0), ("HEAVY CIRCLE WITH STROKE AND TWO DOTS ABOVE", "So", 0), ("PENTAGRAM", "So", 0), ("RIGHT-HANDED INTERLACED PENTAGRAM", "So", 0), ("LEFT-HANDED INTERLACED PENTAGRAM", "So", 0), ("INVERTED PENTAGRAM", "So", 0), ("BLACK CROSS ON SHIELD", "So", 0), ("SHINTO SHRINE", "So", 0), ("CHURCH", "So", 0), ("CASTLE", "So", 0), ("HISTORIC SITE", "So", 0), ("GEAR WITHOUT HUB", "So", 0), ("GEAR WITH HANDLES", "So", 0), ("MAP SYMBOL FOR LIGHTHOUSE", "So", 0), ("MOUNTAIN", "So", 0), ("UMBRELLA ON GROUND", "So", 0), ("FOUNTAIN", "So", 0), ("FLAG IN HOLE", "So", 0), ("FERRY", "So", 0), ("SAILBOAT", "So", 0), ("SQUARE FOUR CORNERS", "So", 0), ("SKIER", "So", 0), ("ICE SKATE", "So", 0), ("PERSON WITH BALL", "So", 0), ("TENT", "So", 0), ("JAPANESE BANK SYMBOL", "So", 0), ("HEADSTONE GRAVEYARD SYMBOL", "So", 0), ("FUEL PUMP", "So", 0), ("CUP ON BLACK SQUARE", "So", 0), ("WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE", "So", 0), )
https://github.com/0x1B05/english
https://raw.githubusercontent.com/0x1B05/english/main/cnn10/content/20240513.typ
typst
#import "../template.typ": * #pagebreak() = 20240513 == You Do You Friday So today is Monday, first day of the school week, first day of the work week for most #strike[of us]#underline[folks], but does#strike[n't] #underline[it] have to be that way? #underline[Whether you're *tightening screws*] on #strike[the]#underline[an] assembly line#strike[, the ...] #underline[or *crunching*] numbers on the computer, people have been working for five days #strike[of] a week for a long time. <NAME> standardized the practice about a hundred years ago when he required the employees at his Ford Motor Company factories to work 40-hour weeks or 8 hours a day for 5 days. A century later though, some companies are reconsidering whether that schedule still make#underline[s] sense. CNN's Clare DUFFY has more: We went from desktop#underline[s] to laptop#underline[s], to mobiles#underline[.] #strike[to]#underline[We're] working working and working. And there was no discussion around, #strike[where]#underline[wait,] this #strike[is]#underline[has gotten] out of control. Preventing employee#strike[s for now] #underline[*burnout*] has become such an important priority that nearly one third of large U.S. companies are exploring shorter work weeks. One of them is Exos, a performance #strike[willness]#underline[*wellness*] company. CEO <NAME>, saw the #underline[burnout] and wanted to fix it. Her answer was something called "You do you Fridays." So tell us about "You do you Fridays", what does that mean? So it means "You do you". So you #strike[play]#underline[may] choose to say, this Friday I'm exhausted, I need to go #strike[spin]#underline[spend] time #strike[on]#underline[out] hiking. Other people may say Friday is my #strike[date,]#underline[day to] just #underline[do quiet] work and not be disturbed. But what we *put #strike[to the]#underline[in] place* was you can not email#underline[,] text, #strike[right ...]#underline[write to any of your colleagues. You can't set] meetings. It is "You do you Friday" and what goes *hand #strike[on]#underline[in] hand* with "You do you Friday" is how we#strike[ek] constructed the other days of the week. We *structured* this because we know actually from training high performance athletes that you put a lot of load on them and then you follow #strike[was] #underline[it with] really intentional recovery to get more out of how the athletes performing. So think about us in the *workplace*, like if we are working, 80-hour weeks, 70-hour weeks#underline[,] which some people are#underline[,] it's #underline[like how *on earth* is] your body #underline[ever] recovery#strike[ of caution]#underline[. Of course you're] gonna #strike[be]#underline[get] burned out. #underline[So] the more #strike[weekend helped ...]#underline[we can help to introduce] this concept that recovery isn't #strike[a week]#underline[weak], it's actually a part of preparing you for high#underline[er] performance. I think it's better for all of us. <NAME> *partner#underline[ed]* with the University of #strike[is working in school]#underline[Pennsylvania's Wharton School] to study how a four-day work week #underline[*impacted*] employee performance. During the six months of study, Exos also reported that employee burn#strike[ ]out #strike[job]#underline[dropped] from 70% to 30%. It#strike['s something]#underline[ sounds] like #strike[these]#underline[this] works #underline[*in part*] because Exos#underline['s culture] #strike[this culture] is already structured in this way#strike[. We're] #underline[where you] #strike[having]#underline[have] employees #underline[who are probably already having] a lot of freedom over their hours. Do think this is something that #strike[gonna]#underline[can] work anywhere? Yeah, that's funny. We get #strike[us ...]#underline[asked that question] a lot. And I actually do like.. I think it requires leadership really being #underline[*innovative* in] how they think about what work really is. Every industry can really think about is there a way to *stagger shifts*. #strike[Other]#underline[Are there] ways#underline[,] even #underline[if] you #underline[can't do the] four-day work week to really think about what we call a recovery first culture. === words, phrases and sentences ==== words - _crunch_ - _burnout_ - _wellness_ - _structure_ - _partner_ - _assembly line_ ==== phrases - _tighten screw_ - _crunch numbers_ - _put in place_ - _hand in hand_ - _on earth_ - _in part_ - _be innovative in_ - _stagger shifts_ ==== sentences - _We *get asked* that question a lot._ === 回译 ==== 原文 So today is Monday, first day of the school week, first day of the work week for most folks, but does it have to be that way? Whether you're tightening screws on an assembly line or crunching numbers on the computer, people have been working for five days a week for a long time. <NAME> standardized the practice about a hundred years ago when he required the employees at his Ford Motor Company factories to work 40-hour weeks or 8 hours a day for 5 days. A century later though, some companies are reconsidering whether that schedule still makes sense. CNN's Clare DUFFY has more: We went from desktops to laptops, to mobiles. We're working working and working. And there was no discussion around, wait, this has gotten out of control. Preventing employee burnout has become such an important priority that nearly one third of large U.S. companies are exploring shorter work weeks. One of them is Exos, a performance wellness company. CEO Sarah <NAME>, saw the burnout and wanted to fix it. Her answer was something called "You do you Fridays." So tell us about "You do you Fridays", what does that mean? So it means "You do you". So you may choose to say, this Friday I'm exhausted, I need to go spend time out hiking. Other people may say Friday is my day to just do quiet work and not be disturbed. But what we put in place was you can not email, text, write to any of your colleagues. You can't set meetings. It is "You do you Friday" and what goes hand in hand with "You do you Friday" is how we constructed the other days of the week. We structured this because we know actually from training high performance athletes that you put a lot of load on them and then you follow it with really intentional recovery to get more out of how the athletes performing. So think about us in the workplace, like if we are working, 80-hour weeks, 70-hour weeks, which some people are, it's like how on earth is your body ever recovery. Of course you're gonna get burned out. So the more we can help to introduce this concept that recovery isn't weak, it's actually a part of preparing you for higher performance. I think it's better for all of us. <NAME> partnered with the University of Pennsylvania's Wharton School to study how a four-day work week impacted employee performance. During the six months of study, Exos also reported that employee burnout dropped from 70% to 30%. It sounds like this works in part because Exos's culture is already structured in this way where you have employees who are probably already having a lot of freedom over their hours. Do think this is something that can work anywhere? Yeah, that's funny. We get asked that question a lot. And I actually do like.. I think it requires leadership really being innovative in how they think about what work really is. Every industry can really think about is there a way to stagger shifts. Are there ways, even if you can't do the four-day work week to really think about what we call a recovery first culture. ==== 参考翻译 今天是星期一,大多数人认为这是学校周的第一天,也是工作周的第一天,但真的非得这样吗?无论你是在流水线上拧螺丝还是在电脑上处理数字,人们已经一周工作五天很长时间了。<NAME>大约一百年前在他的福特汽车公司工厂标准化了这种做法,他要求员工每周工作40小时,即每天8小时,每周5天。然而,一个世纪后,一些公司正在重新考虑这种安排是否仍然合理。CNN的<NAME>有更多报道: 我们从台式电脑到笔记本电脑,再到移动设备,一直在工作工作再工作。没有人讨论,这已经失控了。 防止员工倦怠已成为如此重要的优先事项,以至于近三分之一的大型美国公司正在探索缩短工作周。其中之一是Exos,一家健康表现公司。首席执行官<NAME>看到了倦怠现象,想要解决它。 她的答案是所谓的“You Do You Friday”。 那么,告诉我们“You Do You Friday”是怎么回事? 意思是“You Do You”。所以你可以选择说,这个星期五我太累了,我需要出去徒步旅行。其他人可能会说星期五是我安静工作的日子,不想被打扰。但我们实施的规定是你不能给任何同事发邮件、短信、写信,不能安排会议。这就是“You Do You Friday”。与“You Do You Friday”相伴随的是我们如何安排一周的其他几天。我们这样安排是因为我们实际上从训练高水平运动员中了解到,你对他们施加大量负荷,然后进行非常有意图的恢复,以便更好地发挥运动员的表现。所以想象一下我们在工作场所,如果我们每周工作80小时,70小时,有些人确实是这样,那你的身体如何恢复?你当然会倦怠。所以我们越多地帮助引入这种概念,即恢复不是软弱,而是为更高表现做准备的一部分。我认为这对我们所有人都更好。 <NAME>与宾夕法尼亚大学沃顿商学院合作研究了四天工作周对员工表现的影响。在为期六个月的研究期间,Exos还报告说员工倦怠率从70%下降到30%。 听起来这部分有效是因为Exos的文化已经这样安排,员工可能已经有很多时间自由。你认为这种方法在任何地方都可以推广吗? 是的,这很有趣。我们经常被问到这个问题。我实际上认为这需要领导层在思考工作本质时真正具有创新精神。每个行业都可以真正考虑是否有办法错开班次。即使你不能做到四天工作周,也要真正考虑我们所谓的“恢复优先”文化。 ==== 1st Today's Monday #strike[which is considered as]#underline[,] the first day of the school #strike[days]#underline[week], as well as the first day of the work #strike[days]#underline[week]#strike[by most of us]. But does it have to be #strike[like this]#underline[that way]? #strike[Whatever you]#underline[Whether you're tightening] screw#underline[s] #strike[things] #strike[in]#underline[on] an assembly line or #strike[do a data processing]#underline[*crunching numbers*] #strike[in]#underline[on] a computer, people have been working for 5 days a week for a long time. <NAME> standardized the practice about 100 years ago #strike[at his Ford Car Company, who]#underline[when he] asked #strike[workers]#underline[employees at his Ford Motor Company factories] to work 40 hours a week, meaning 8 hours every day#strike[, and 5 days a week]#underline[for five days]. However, a #strike[decade]#underline[century] passed, some companies are reconsidering whether such a schedule #strike[is still reasonable]#underline[still *makes sense*]. CNN's Clare Duffy has more: #underline[We went] from #strike[computers]#underline[desktops] to laptops, to mobiles, we are working, working and working. There's no discussion. It has been out of control. #strike[Avoiding workers]#underline[Preventing employee] burnout has been #strike[so prioritized]#underline[such an important priority] that nearly one third of the large U.S. companies are exploring #strike[how to shorten their work days]#underline[shorter work weeks]. One of the companies is Exos, a performance wellness company. CEO <NAME> saw the burnout and wanted to #strike[solve]#underline[fix] it. Her answer #strike[is]#underline[was something called] "You Do You Friday". So tell us what is "You Do You Friday"? It means "You Do You". So you can choose to say, I am exhausted this Friday, a foot trip is required. Others may say, Friday is the day #strike[I can work quietly without being disturbed]#underline[to just do quiet work and not be disturbed]. But what #strike[our rules are]#underline[we put in place was that] you are not allowed to email, text or write to any of your colleagues, you can't set meetings. This is "You Do You Friday"#strike[. Along with]#underline[and what *goes hand in hand with*] "You Do You Friday" is how we #strike[schedule]#underline[construct] the other day#underline[s] of the week. #strike[The reason why we schedule like this]#underline[We *structured this*] is because we have learnt from training high performance athletes that you #underline[*put a lot of load*] on them and then #strike[give them an intentional recovery to make their performance better]#underline[you follow it with really intentional recovery to get more out of how the athletes performing]. So image when at workplaces, if we do 80-hour week work, 70-hour week work, #underline[which] some people #strike[work like this indeed]#underline[are indeed], how #underline[*on earth*] does your body #underline[ever] recover? You of course #strike[will burn out]#underline[are gonna get burned out]. #strike[So we help introduce the conception more]#underline[So the more we can help to introduce this concept] that recovery isn't weak but a part of #strike[preparation]#underline[preparing you] for higher performance. I think it's better for all of us. <NAME> partnered with the University of Pennsylvania's Wharton School and studied #strike[the influence of 4-day week work on employees]#underline[how a four-day work week impacted employee performance]. During the six months #underline[of] study, Exos reported that the rate of #underline[employee] burnout dropped from 70% to 30%. It sounds like #strike[effective]#underline[this works *in part*] because the culture in Exos has #strike[scheduled,]#underline[structured in this way where you have] employees #underline[who are] probably already have lots of free time over their hours. Do you think #strike[it's a method that can be introduced anywhere] #underline[this is something that can work anywhere]? Yes, it's interesting. We get asked the question a lot. I actually think it requires #strike[the] leadership to be innovative in #strike[thinking]#underline[how they think about] what #strike[the] work really #strike[are]#underline[is]. #strike[Each job]#underline[Every industry] can think about if there's a way to #strike[make a]#underline[*stagger*] shifts. Even though you can't do 4-day work week, you should consider what we call #strike[the culture of "Recovery Priority"] #underline[a recovery first culture]. == Lady Elliot Island Next we're taking a trip to one of those islands, Lady Elliot Island, located at #underline[the *southernmost tip*] of Great Barrier Reef. The island is #underline[*lush*] with #underline[*greenery* again], *regrowing* after decades of *topsoil* mining. But now there's a new threat to this #underline[*delicate*] ecosystem -- mass coral #underline[*bleaching*]. CNN's Ivan Watso has more: An hour #strike[after]#underline[*off*] the #strike[cost]#underline[coast] of Brisbane, Australia, lies a tiny paradise island, only accessible by aircraft. But it didn't always look like this. It has been through incredible transformation led by one man. Landing here is tricky. My pilot is <NAME>. He basically owns the island, #underline[*leasing* it] from the Australian government and running a eco#underline[-resort] #strike[result] here with his family. Meanwhile, above this surface, the island #underline[*teems*] with sea birds. In the 19th century, settlers #strike[minded]#underline[*mined*] the island for the bird #underline[*guano*] leaving the place mostly #underline[*barren*] hard coral. Peter's message #strike[with]#underline[of] hope is inspiring, but it's tempered by something we see under water. #underline[*Amid* the reef sharks] and sea turtles, there's coral #underline[*bleached*] white, enough to worry this island's #underline[greatest *enthusiast*]. The damaged coral here, part of #underline[the mass bleaching event caused by the marine heat wave along the Great Barrier Reef], a #underline[*phenomenon*] that could threaten the entire ecosystem. === words, phrases and sentences ==== words - _the southernmost tip of ..._ - _greenery_ - _topsoil_ - _delicate_ - _bleaching_ - _lease_ - _teem_ - _mine_ - _guano_ - _barren_ - _enthusiast_ - _amid_ - _phenomenon_ ==== phrases - _be lush with_ - _teem with_ ==== sentences - _It has been through incredible transformation led by one man._ === 回译 ==== 原文 Next we're taking a trip to one of those islands, Lady Elliot Island, located at the southernmost tip of Great Barrier Reef. The island is lush with greenery again, regrowing after decades of topsoil mining. But now there's a new threat to this delicate ecosystem -- mass coral bleaching. CNN's Ivan Watso has more: An hour off the coast of Brisbane, Australia, lies a tiny paradise island, only accessible by aircraft. But it didn't always look like this. It has been through incredible transformation led by one man. Landing here is tricky. My pilot is <NAME>. He basically owns the island, leasing it from the Australian government and running a eco-resort here with his family. Meanwhile, above this surface, the island teems with sea birds. In the 19th century, settlers mined the island for the bird guano leaving the place mostly barren hard coral. Peter's message of hope is inspiring, but it's tempered by something we see under water. Amid the reef sharks and sea turtles, there's coral bleached white, enough to worry this island's greatest enthusiast. The damaged coral here, part of the mass bleaching event caused by the marine heat wave along the Great Barrier Reef, a phenomenon that could threaten the entire ecosystem. ==== 参考翻译 接下来我们将前往其中一个岛屿,位于大堡礁最南端的Lady Elliot Island。经过数十年的表土开采后,这个岛屿再次充满了绿色植物,正在重新生长。但现在,这个脆弱的生态系统面临着一个新的威胁——大规模珊瑚白化。CNN的Ivan Watso带来了更多报道: 离澳大利亚布里斯班海岸一小时路程,有一个只能通过飞机到达的小天堂岛。但它并不总是像现在这样。它经历了一场由一人领导的惊人转变。降落在这里并不容易。我的飞行员是<NAME>。他基本上拥有这个岛,从澳大利亚政府租赁并和家人在这里经营一个生态度假村。 与此同时,岛上的天空中充满了海鸟。 19世纪时,定居者在岛上开采鸟粪,导致这里几乎变成了光秃秃的硬珊瑚。 Peter的希望信息令人鼓舞,但我们在水下看到的情况让人心情复杂。在礁鲨和海龟之间,有白化的珊瑚,足以让这个岛屿最热心的爱好者担忧。 这里受损的珊瑚是大堡礁沿海海洋热浪引发的大规模白化事件的一部分,这种现象可能威胁整个生态系统。 ==== 1st Next we are #strike[going to]#underline[taking a trip to] one of the islands, Lady Elliot Island, located #strike[in] the southernmost #strike[coast]#underline[*tip*] of the Great Barrier Reef. After decades of topsoil mining, the island is lush with greenery again and now regrowing. But now, the delicate ecosystem are confronting a new threat, #strike[vast bleaching coral]#underline[mass coral bleaching]. CNN's Ivan Watso has more: An hour off the coast of Brisbane in Australia, there is a #strike[small]#underline[tiny] paradise island#strike[ that could only be through]#underline[, only accessible] by aircraft. But it isn't always like this. It #strike[experienced an upheaval]#underline[has been *through incredible transformation*] led by one man. #strike[It's not easy to land on the island]#underline[Landing here is *tricky*]. Our pilot is <NAME> who almost possesses the island, leasing from the Australian government and runing a eco-resort with his family. Meanwhile, #strike[the sky]#underline[above this surface, the island] teems with sea birds. In the 19th century, settlers mined #underline[for] birds guano, #strike[leading the place to be barren had coral..]#underline[leaving the place mostly *barren* hard coral.] Peter's message of hope is inspiring, but #strike[what we have seen under the water made us more sentimental]#underline[it's *tempered* by something we see under water]. Amid the #strike[coral]#underline[reef] shark and sea turtles #strike[is bleaching coral]#underline[, there's coral bleached white], which is enough to worry #underline[this island's greatest] enthusiasts. The damaged coral #strike[is]#underline[,] a part of #strike[what the Great Barrier Reef heat wave has caused]#underline[the mass bleaching event caused by the marine heat wave along the Great Barrier Reef], #strike[which could threaten the whole ecosystem]#underline[a phenomenon that could threaten the entire ecosystem].
https://github.com/bugsbugsbux/learning-typst
https://raw.githubusercontent.com/bugsbugsbux/learning-typst/master/understanding.typ
typst
// requires "Fira Math" font // jump: TODO, DEBUG, CHECK, TAG #let mytitle = "Understanding Typst" #set document(title: mytitle) #set text(lang: "en", hyphenate: false) #set par(justify: true) #set heading(numbering: "1.") #set table(stroke: silver) // TAG:table_silver #set page( paper: "a4", numbering: "1", ) #stack( align(center, text(size: 22pt, weight: "bold")[#mytitle] ), 4em, [ _Typst-Versions: 0.11.1_ _This does not aim to cover the entire documentation of typst, but to explain core concepts, the builtin shorthand syntax and tables._ ], 1fr, outline( title: none, //target: selector(heading).before(<appendix>, inclusive: true), ), 1fr, ) = Overview A typst document is a plain text file with the extension `.typ`. The instructions in a typst document are executed by the typst compiler in order, meaning they do not effect the previous text. Code between dollar-signs is interpreted in *`$formula$`* mode, which allows to typeset formulas beautifully. If there is no whitespace between the dollar-signs and the formula, like ```typ $a^2 + b^2 = c^2$```, an inline element, like $a^2 + b^2 = c^2$, is created, otherwise the formula is its own paragraph: ```typ $ x_(1,2) = (-b plus.minus sqrt(b^2 - 4 a c))/(2 a) $ ``` $ x_(1,2) = (-b plus.minus sqrt(b^2 - 4 a c))/(2 a) $ A hash-sign enables *`#code`* mode until the end of the expression, which is usually the end of the word or the corresponding closing parenthesis. For single-line keyword expressions, it is the end of the line or a semicolon. This mode is for interacting with the typst scripting language, which is used to define the look of the resulting document. ```typ #let foo = "foo" Redefining #foo inline #let foo() = 4; and using it: #text(fill: red, lorem(foo()) ) Cool! ``` #let foo = "foo" Redefining #foo inline #let foo() = 4; and using it: #text(fill: red, lorem(foo()) ) Cool! The default mode is *`[markup]`* mode, which is used to write the document's content and can also be used in `#code` mode by surrounding the relevant text with brackets. It enables markdown-like syntax as shorthand for common functions. ```typ - Syntax examples: #text(fill: red, [*bold* _italic_ *_bold+italic_*]) ``` - Syntax examples: #text(fill: red, [*bold* _italic_ *_bold+italic_*]) Last, but not least, there are *comments*, which are not officially a "mode" because they do not do anything: they are simply ignored by the compiler, is if they did not exist. ```typ - in all modes this /* anything between */ is ignored - and in `[markup]` and `#code` mode the following ignores the rest of the line // rest of line ``` - in all modes this /* anything between */ is ignored - and in `[markup]` and `#code` mode the following ignores the rest of the line // rest of line To *escape* the special meaning of of a symbol, prefix it with `\`. For example, `\\` inserts a regular backslash (\\). Sometimes, mostly in strings in `#code` mode, backslash instead activates some special meaning; an example (which not only works in strings but also works in [markup] mode) is `\u{hex}`, which inserts the given unicode codepoint: \u{03bc}. Backslash escapes do not work in `raw` text (backtick surrounded)! #pagebreak(weak: true) = `[Markup]` mode All `[markup]` blocks return `content`, which is a type of object and different from the type `string`. In many cases functions which take content arguments, also accept strings; sometimes strings are required and content objects are not allowed. The following syntax available in `[markup]` mode, is only shorthand for calling the respective functions: #table(columns: 3, table.header([*syntax*], [*function equivalent*], [*note*]), table.hline(stroke: black), `\`, ```typ #linebreak()```, [ new line (same paragraph); if followed by symbol: escapes it's special meaning ], [ empty line ], ```typ #parbreak()```, [ new paragraph ], `== Text`, ```typ #heading(depth: 2, [Text])```, [ heading of _depth_ 2 ], `*\*bold*text\**`, ```typ #strong("*bold*text*")```, [ *\*bold*text\** ], `_\_italic_text\__`, ```typ #emph("_italic_text_")```, [ _\_italic_text\__ ], [ ``` `` ``` \ ``` `string` ``` \ ```` ``` string``` ```` \ ```` ```lang string``` ```` ```` ```lang string ``` ```` ``` `foo indent: 4 ` ``` ```` ```lang indent: 1 indent: 0 indent: 4 ``` ```` ], par(justify:false,)[ ```typ #raw("")``` \ ```typ #raw("string")``` \ ```typ #raw("string")``` \ ```typ #raw("string", lang: "lang")``` ```typ #raw("string", lang: "lang", block: true) ``` #v(1em) ```typ #raw( "foo\n indent: 4\n ", block: false, lang: none) ``` ```typ #raw(" indent: 1 indent: 0 indent: 4", block: true, lang: "lang") ``` ], [ `raw/literal` text, must start and end with same number (must not be 2 which is for empty content) of backticks. If 3+ are used, a single leading space is trimmed or the _word_ following _without whitespace_ specifies the `lang` argument; unlike markdown _all following_ characters of the opening line go into the output! Moreover, the common indent of the lines following the opening line, including the line with the end-marker is stripped! Single backtick blocks don't trim anything and don't have a `lang` argument. Backslash-escapes don't work in any `raw` block. ], `- text`, ```typ #let e=([text],) #list(..e) ```, [ - bullet-list element, also passable as: `list.item([text])` ], `+ text`, ```typ #let e=([text],) #enum(..e) ```, [ + numbered-list element, also passable as: `enum.item([text])` ], `/ text1: text2`, ```typ #let e=([text1], [text2]) #terms(..e) ```, [ / Term-list element: also passable as: `terms.item([text1], [text2])` ], [ `http://example.com` \ `https://example.com` ], [ ```typ #link("http://example.com")``` \ ```typ #link("https://example.com")``` ], [ link to https://example.com The function also allows other link-types and changing the text. ], `<string>`, ```typ #label("string")```, [ tags the previous element (in the same scope) to be able to reference it; only one label per element allowed ], `@string`, ```typ #ref("string")```, [ reference to `<string>` which may be defined later ], `"text" "`, ```typ #smartquote(double: true)```, [ language-, start-, end-aware "quotes": " ], `'text' '`, ```typ #smartquote(double: false)```, [ language-, start-, end-aware 'quotes': ' ], `a~z`, ```typ a#(sym.space.nobreak)z```, [ unbreakable space ], `a-?z`, ```typ a#(sym.hyphen.soft)z```, [ #set text(hyphenate: true) // CHECK: first az should be on two lines to show the hyphen this hyphen only appears if needed: #h(5pt) a-?z a-?z ], `-3`, ```typ #(sym.minus)3```, [ the dash in -3, but not a- b-c or -d nor - ], `--`, ```typ #sym.dash.en```, [ This is a -- so called -- _en_-dash. ], `---`, ```typ #sym.dash.em```, [ This is a dash --- an _em_-dash. ], `...`, ```typ #sym.dots.h```, [ An ellipsis... ], ) Some constructs, like lists, consider the indentation of a line to determine to which element it belongs. As long as a line is indented more than the item's marker and at maximum as deep as the marker of a previous deeper nested item, it is attributed to this (outer) item. Note that in indented `[markup]` blocks, the relevant distance is the one from the start of the line and not the one from the opening bracket! // I want to keep this together such that the indents are obvious #box[```typ #table[ - outer outer List items may have paragraphs if indented correctly! - nested nested outer Not part of the list. ] ``` ] #box(table[ - outer outer List items may have paragraphs if indented correctly! - nested nested outer Not part of the list. ]) #pagebreak(weak: true) = `$Formula$` mode (aka math mode) // reset this at end of chapter TAG:table_formulas #set table( align: start + horizon, inset: 0.5em, ) `$formula$` mode is a special `[markup]` mode for typesetting mathematical formulas and thus also creates `content` objects; however, it has completely different shorthand syntax... The element function (see below) of `$formulas$` is `math.equation`, which can be used for example to change the math-font: #let eq = $ n! := product_(k=1)^n k = 1 dot 2 dot 3 dot ... dot n $ #box(grid( columns: (3fr, 4fr), inset: 0.3em, [], [```typ #show math.equation: set text(font: "Fira Math") ```], eq, { show math.equation: set text(font: "Fira Math") eq } )) As mentioned above, when there is whitespace between the dollar-signs and the formula, a block element is created, which is its own paragraph, while omitting the whitespace padding produces an inline element. This also influences the text size and positioning of bottom- and top-attachments. == Symbols Since `$formula$` mode imports the `sym` module, all those symbols are available without having to enter `#code` mode and prefixing them with the module name. Symbol objects may have subfields accessible with dot-notation and many use this to make variants available with logical names; for example: #table(columns: 2, [```typ $#sym.plus$```], $#sym.plus$, [```typ $plus$```], $plus$, [```typ $#sym.plus.minus$```], $#sym.plus.minus$, [```typ $plus.minus$```], $plus.minus$, ) Some character combinations are interpreted as shorthand for certain symbols: #{ set grid( align: center + horizon, inset: 0.5em, stroke: silver, ) set stack( dir: ltr, spacing: 0.5em, ) stack( grid(columns: 5, [`+`], [`-`], [`*`], [`'` ], [`...`], $+$, $-$, $*$, $'$, $...$, ), grid(columns: 3, [`[|`], [`||`], [`|]`], $[|$, $||$, $|]$, ), ) stack( grid(columns: 3, [`<<<`], [`<<`], [`<=`], $<<<$, $<<$, $<=$, ), grid(columns: 1, [`!=`], $!=$, ), grid(columns: 3, [`>=`], [`>>`], [`>>>`], $>=$, $>>$, $>>>$, ), ) stack( grid(columns: 3, [`->`], [`=>`], [`~>`], $->$, $=>$, $~>$, ), grid(columns: 2, [`<-`], [`<~`], $<-$, $<~$, ), grid(columns: 3, [`-->`],[`==>`], [`~~>`], $-->$, $==>$, $~~>$, ), grid(columns: 3, [`<--`],[`<==`], [`<~~`], $<--$, $<==$, $<~~$, ), ) stack( grid(columns: 2, [`<->`], [`<=>`], $<->$, $<=>$, ), grid(columns: 2, [`<-->`], [`<==>`], $<-->$, $<==>$, ), grid(columns: 2, [`->>`], [`<<-`], $->>$, $<<-$, ), grid(columns: 2, [`>->`], [`<-<`], $>->$, $<-<$, ), grid(columns: 2, [`|->`], [`|=>`], $|->$, $|=>$, ), ) } == Mathematical functions Since `$formula$` mode imports the `math` module, all those functions are available without having to enter `#code` mode and prefixing them with the module name. Arguments of functions called in this way (without entering `#code` mode) are interpreted in `$formula$` mode! #table(columns: 2, ```typ $#math.sqrt($1/2$)$```, $#math.sqrt($1/2$)$, ```typ $sqrt(1/2)$```, $sqrt(1/2)$, ) == Variables As explained, unquoted words in `$formula$` mode are looked up --- with the notable exception of single letters, which are the most common names of mathematical variables. Multi-letter mathematical variables need to be quoted (with `"` not `'`). Quoted strings can also be used to insert text into a formula. To access single-letter typst variables, use `#code` mode. #table(columns: (auto, 1fr), align: (start, center), [```typ #let x = 3; $"foo" = 2 dot x = 2 dot #x = #(2 * x)$```], [#let x = 3; $"foo" = 2 dot x = 2 dot #x = #(2 * x)$], ) The mathematical convention of implying multiplication is denoted by separating the factors with whitespace: ```typ $a b$``` produces $a b$ == Shorthand Operators The shorthand symbols combining two elements only operate on those immediately next to them. To apply them to more elements, these have to be wrapped in parentheses, which are not shown in the output but another pair can be added, which is then shown. #table(columns: 4, align: horizon, inset: 0.7em, table.cell(rowspan: 4)[fraction], ```typ $a/b$```, $a/b$, ```typ $frac(a,b)$```, /**/ ```typ $a b / c d$```, $a b / c d$, ```typ $a frac(b,c) d$```, /**/ ```typ $(a b)/ c d$```, $(a b)/ c d$, ```typ $frac(a b, c) d$```, /**/ ```typ $((a b))/ c d$```, $((a b))/ c d$, ```typ $frac((a b), c) d$```, [superscript], ```typ $a^b$```, $a^b$, ```typ $attach(a, t: b)$```, [subscript], ```typ $a_b$```, $a_b$, ```typ $attach(a, b: b)$```, ) == Attachment Style Wrapping a base in the `limits` function, allows it to place its attachments _directly_ above or below it. This is (one of) the reasons why there is a separate `sum` symbol when there is also `Sigma`. Placing attachments directly above or below the base can be avoided in inline formulas by passing `inline: #false` when applying `limits`. To force the other style, wrap the base in the `scripts` function or pass the attachment as argument `tr` or `br` of `attach`. #table(columns: 2, inset: 0.7em, ```typ $ macron(x) = 1/n sum ^n_(i=1) x_i $```, $ macron(x) = 1/n sum^n_(i=1) x_i $, ```typ $macron(x) = 1/n sum ^n_(i=1) x_i$```, $macron(x) = 1/n sum^n_(i=1) x_i$, ```typ $ macron(x) = 1/n scripts(sum)^n_(i=1) x_i $```, $ macron(x) = 1/n scripts(sum)^n_(i=1) x_i $, ```typ $macron(x) = 1/n limits(sum)^n_(i=1) x_i$```, $macron(x) = 1/n limits(sum)^n_(i=1) x_i$, ) #pagebreak() // CHECK: avoid table alone on next page == Layout, Alignment `$formula$` mode behaves like a table with invisible borders and the argument `align: (right, left)`; this allows to easily align the formula along the equal sign for example. Rows must be separated with `\ ` (or `#linebreak()`; `\` also escapes characters as in `[markup]` mode) and columns with `&`. Skip a column to change alignment. #table(columns: (auto, 1fr), inset: (top: 0.5em, bottom: 0.5em), table.cell(breakable: false, ```typ $ "right" & "left" & "right" && "right" \ "aligned" & "aligned" & "aligned" && "aligned" $ ```), $ "right" & "left" & "right" && "right" \ "aligned" & "aligned" & "aligned" && "aligned" $, ```typ $ a\^2 + b\^2 &= c\^2 \ c &= sqrt(a^2 + b^2) $```, $ a\^2 + b\^2 &= c\^2 \ c &= sqrt(a² + b²) $, ) // resetting TAG:table_formulas #set table( align: auto, inset: 5pt, ) #pagebreak(weak: true) = `#Code` mode: The typst scripting language Expressions in the typst scripting language can be inserted into `[markup]` or `$formulas$` by starting them with a hash-sign. These expressions are parsed in `#code` mode, which ends with the end of the expression, which for keyword expressions is the end of the line, or a semicolon. Some expressions, such as binary operators like ```typ #(1+2)```, need to be parenthesized to be recognized. `[Markup]` can be inserted in `#code` mode, by wrapping it in brackets; `[markup]` and `#code` mode can be recursively nested. The same applies to `$formulas$`. Functions are invoked by putting the parenthesized arguments without whitespace after their name. Named arguments separate the name with a colon from the value; they can be placed anywhere in the argument list, as positional arguments only care about their order among themselves. (A sequence of) `[markup]` blocks (not separated by anything, not even whitespace!) can be appended to the closing parenthesis (without whitespace!) and will be appended to the list of positional arguments. An empty argument list, as in ```typ #strike()[not]```, which produces #strike[not], can be omitted if followed by `[markup]` blocks: ```typ #strike[not]```. Appending `[markup]` blocks is optional but can improve readability if the closing parenthesis would otherwise come many lines later, or it allows to omit the noise of empty parentheses. #table(columns: (2fr, 1fr), table.header([*Markup*], [*Result*]), ```typ `#Code` mode only applies to #linebreak() the expression.```, [`#Code` mode only applies to #linebreak() the expression.], ```typ #table(columns: 2)[a][b][c][d] [not a cell] ```, [#table(columns: 2)[a][b][c][d] [not a cell]], ```typ // previous example is equivalent to this: #table( [a],[b], columns: 2, [c],[d], ) [not a cell] ```, [#table( [a],[b], columns: 2, [c],[d], ) [not a cell]], ) == Output Values returned by code expressions are inserted into the output, thus ```typ #(1+2)``` inserts the result #(1+2). Expressions which should not influence the output (like assignments), return `none`. It is possible to stay longer in `#code` mode than for a single expression by using a `{codeblock}` which is a code wrapped in braces. The return-values from all expressions in a `{codeblock}` are joined and inserted into the output; for this to work, the values need to be joinable; often it is enough to cast values to strings with `str`. This is not necessary for expressions with a single return value, as they are implicitly cast to something joinable with the surrounding content. Here is an example: ```typ #(-1) #{ str(-1 + 1) [ insert some *markup* ] str(0 + 1) } ``` Produces: #(-1) #{ str(-1 + 1) [ insert some *markup* ] str(0 + 1) } == Namespaces/Scopes Every variable is associated with a namespace/scope. Every `[markup]` block, `{codeblock}` and function crates their own namespace, meaning after exiting from the block or function variables defined there are not available anymore. Generally, scopes have read- and write-access to names defined in their parent scopes, meaning writing to a name from a parent scope preserves the change even after leaving the child scope; however, the *scope of a function* only has read-access to the inherited namespaces! When a name is declared (meaning newly created in the current scope) while there is the same name, inherited from a parent scope, available, the name from the parent scope stays untouched and becomes unavailable for the rest of the scope. Variables are declared with the `let` keyword; this initializes its value to `none` unless the declaration is combined with an assignment (`=` operator). Declaring a variable multiple times in the same scope is fine, it just overrides the old value. ```typ #let var = "global " // declaration + assignment in one #{ { var // "global " var = "changed " // var must exist! changes it in origin scope let var // declare in current scope, init to none [#str(type(var)) ] // [none ] } var // "changed " let var = "foo " var // "foo " } #var // "changed " ``` Produces: #let var = "global " #{ { var var = "changed " let var [#str(type(var)) ] } var let var = "foo " var } #var // TODO: state variables (changeable from functions) == Types (incl. Functions) The following value types might be familiar from other programming languages: #table(columns: 3 * (auto,), align: start+top, table.header([*Name*], [*Examples*], [*Notes*]), [none], ```typc table(stroke: none)```, [ Represents nothing. Can be joined with anyting without changing it, thus assignments and other expressions which should not be shown in the output return `none`. ], [bool], [ ```typc true``` \ ```typc false```], [ The only values which have truthiness thus other values like `none` _cannot_ be used in their place! ], [integer], [ ```typc 3``` \ ```typc int("3")``` \ ```typc int(3.14) // floored``` \ ```typc int(true)==1``` \ ```typc int(false)==0``` ], [ 64-bit number from $ZZ$ \ Hexadecimal-, octal- and binary-numbers are prefixed with `0x`, `0o`, `0b` respectively. Division by zero is not allowed. ```typ #(0 == -0)``` and \ ```typ #((0).signum() == (-0).signum())``` ], [float], [ ```typc .12 == 0.12``` \ ```typc 12e-2 == 0.12``` \ ```typc float.is-infinite(-calc.inf)``` \ ```typc float.is-nan(calc.nan)``` ], [ 64-bit floating-point number. The constructor `float` can be used to cast the types supported by `int` as well as ratios to floats. `calc.inf` and `calc.nan` are floats! Division by zero is not allowed, division by infinity is zero. ```typ #(0.0==-0.0)``` _but_ ```typ #((0.0).signum() != (-0.0).signum())``` ], [string], ```typc set page(numbering: "- 1 -")```, [ Strings are sequences of unicode-codepoints and must be double-quoted (`"`). They do not interpret `[markup]` shorthand syntax, but support the following escape sequences: `\\` (backslash), `\"` (double quote), `\n` (newline), `\r` (carriage return), `\t` (horizontal tab), `\u{HEX}` (unicode character HEX). Using literal newlines in strings is equivalent to inserting `\n` without breaking the line. ], [array], [ ```typc ()``` \ ```typc (0,)``` \ ```typc (0, "one", 2.0)``` \ ```typc (0,1,2).at(0)``` ], [ A list of values of arbitrary type. Note the required trailing comma of single element lists. The first element has index `0`, negative indices count from the back (thus `-1` is the last element). ], [dictionary], [ ```typc (:)``` \ ```typc ("key": "value", k2: 2)``` \ ```typc (one: 1).at("one")``` \ ```typc ("one": 1).one``` ], [ Dictionaries are collections mapping _string_ keys (quotes may be omitted if unambiguous) to values of arbitrary type; iterating over them yields the items in the order they were inserted. Use method `insert` for both adding and updating items. ], [function], [ ```typc let f(x, y: 1) = {x + y}``` \ ```typc let f= (x, y: 1) => [#(x+y)]``` \ ```typc let f(x,y) = x + y``` \ ```typc let f = x => x + 1``` \ \ ```typc let add1(x) = { return x + 1 x + 2 // not executed } ``` ```typc let add1(x) = { x + 1 return x + 2 // not executed } ``` \ ```typc // closure: let adder(n) = x => x+n let add1 = adder(1) add1(1) ``` ], [ A function is defined with an assignment of a function body to a name, which is followed without whitespace by an argspec, and has its own namespace/scope. An argspec combines the syntax of arrays and dictionaries to name positional and keyword arguments, which have to be passed by name and if omitted keep the default value assigned in the argspec; however, names may not be quoted and no trailing comma is required. An anonymous function is only an argspec followed by `=>` and a function body; if it takes only a single positional argument, the parentheses may be omitted. A function body can be a single expression, like a `[markup]` block, or a `{codeblock}`, which returns its last evaluated value and may be terminated early with *keyword `return`*, which may prefix the expression after which to exit. See also: `..`~operator and the sections on namespaces/scopes and function invocation! ], ) The following types are more unusual, but some might be known from CSS: #table(columns: 3 * (auto,), align: start+top, table.header([*Name*], [*Examples*], [*Notes*]), [arguments], ```typc let f(x,y:1,..args)=repr(args)```, [ The argument prefixed with `..` (see: `..` operator) in a function's definition captures all supplied arguments which were not named in the definition. Method `pos` returns an array with the positional arguments, method `named` a dictionary with the named arguments. ], [auto], ```typc table(columns: 3 * (auto,))```, [ Represents a "smart default" value. ], [length], [ ```typc text(size: 12pt)``` \ ```typc line(length: 4cm, stroke: 1mm)``` \ ```typc table(inset: 1em)``` ], [ Unit indicators are appended to a number: `pt` (point), `mm` (millimeters), `cm` (centimeters), `in` (inches), `em` (relative to font height) ], [angle], [ ```typc rotate(3.14rad)[foo]``` \ ```typc rotate(-45deg)[foo]``` ], [ Represents a clockwise rotation around a starting point. Supported suffixes are `deg` for degrees and `rad` for radians. There is no constructor for these types. ], [fraction], ```typc table(columns: (1fr, 2fr))```, [ Represents a part of the remaining available space after subtracting all other units. ], [ratio], ```typc scale(x: 300%, reflow: true)```, [ Percentage of something. Prefer fractions over rations when describing relative lengths, because percentages are computed from the available space _before_ subtracting other units! ], [label], ```typc show <mylabel>: set text(red)```, [ Refers to the label with name `"mylabel"`. Labels can only be attached to elements in `[markup]` mode. ], [content], [ ```typc [pi]``` \ ```typc $pi$``` \ ```typc `pi` ``` \ ```typc lorem(10)``` \ ````typ ```lang pi ``` ```` ], [ Represents an element of the document produced by a certain function, which can be obtained with the content's `func` method. Depending on which element they represent, content objects have different fields, which can be obtained with the `fields` method. \ All these examples produce type `content`. ], ) There are many more types, like `color`, `stroke` or `counter`, which won't be covered here. Moreover, most types have more methods than were mentioned! Most of these methods can be called in one of two ways: + The type's constructor is indexable; retrieve the method this way and pass the value to it: ```typ #str.rev("abc")``` produces: #str.rev("abc") This is not allowed for methods like `array.insert` which modify the value in-place. + A value of a given type has this type's methods as fields; the value is prepended to the list of given positional arguments. ```typc "abc".rev()``` produces: #"abc".rev() == Operators _Infixes except where mentioned otherwise:_ #table(columns: (auto, 1fr), align: (center+horizon, start), `+`, [ *As prefix* of numbers: returns number unchanged \ *As infix:* adds numbers, adds content, appends strings, appends lists, joins dictionaries, combines alignments ```typc (align: center+horizon)```, combines colors and lengths to strokes ```typc (stroke: 1pt+red)``` ], `-`, [ *As prefix:* negates numbers \ *As infix:* subtracts numbers ], `*`, [ multiplies numbers, multiplies lengths with numbers (```typc 12pt*2```), repeats content, repeats strings, repeats lists ], `/`, [ divides numbers, divides lengths with numbers (```typc 12pt/3```), divides lengths resulting in a float ], `=>`, [ Separates the argspec of an anonymous function from the function's body. ], `=`, [ Assigns the value on the right to the name on the left. This can be combined with one of the basic mathematical operations according to the pattern ```typc x += y``` is equivalent to #box(```typc x = x+y```). The resulting operators are: #align(center, table(columns: 4, inset: 0.7em, [`+=`], [`-=`], [`*=`], [`/=`] )) Assignments also allow to destructure values, meaning parts of the collection on the right side are extracted into multiple variables named on the left. For lists, this is easy: use a list with the wanted names on the left side: ```typc let (x, y) = (1,2)```. For dictionaries, one assigns to a list of the keys to extract, or to a dictionary with the keys to extract and the names to use as their values: \ #box(```typc let location = (lat: 0, long: 0, name: "Null Island") let (name,) = location let (lat: y, long: x) = location [#name is located at (#x, #y)] ```) \ See also the `..` operator! ], [*`..`*], [ *As prefix:* In a function argument definition or when destructuring a dictionary (see `=` operator) it denotes the variable which shall capture everything which was not explicitly mentioned in the argument definition or destructuring: \ #box(```typc let f(x, y:1, ..rest) = [ You provided #rest.pos().len() unexpected positional-, and #rest.named().len() unexpected named-arguments! ] let (user: name, ..info) = (user: "Alice", age: 18, score: 100) [#name got a score of #info.score] ```) \ In other cases it is used to replace the value it prefixes with its items: \ #box(```typc let foo = (1,2,3) (0,1,2,3,4) == (0, ..foo, 4) let foo = (one: 1) (one: 1, two: 2) == (two: 2, ..foo) ```) \ *As independent token* when destructuring a list it can be used _once_ to skip values: #box(```typc let (x, .., y) = (1,2,3,4)```) ], [*`.`*], [ Interprets the right side as a string with which to index the left side: #box(`calc . pi`)\; usually the spaces are omitted, like so `calc.pi`, because this is recognized by `#code` mode without parentheses: \ #box(```typ The digit #(one: 1).one reads "one".```) \ Retrieved functions can be called immediately by appending the argument-list without whitespace to the index: ```typc calc.pow(2,3)``` ], //CHECK: ensure this is not last row on page table.cell(colspan: 2, fill: silver)[Comparison Operators:], table.cell(colspan: 2, align: start)[ They cannot be chained, meaning an expression like `(0 == 0.0 == -0)` is not allowed and has to be rewritten using the `and`, `or` and `not` keyword-operators: `(0 == 0.0 and 0 == -0)` The (in)equality operators can basically compare anything: #align(center, table(columns: 2, align: center + horizon, inset: 0.7em, column-gutter: 0.5em, [`==`], [`!=`], $=$, $!=$, )) The other comparison operators are less widely applicable: they work on numbers, strings (seems to be a lexicographical comparison: `("A" < "a")`) and lengths with the same unit. #align(center, table(columns: 4, align: center + horizon, inset: 0.7em, column-gutter: 0.5em, [`<`], [`<=`], [`>=`], [`>`], $<$, $<=$, $>=$, $>$, )) ], //CHECK: ensure this is not last row on page table.cell(colspan: 2, fill: silver)[Keyword Operators:], `and`, [ `true` if left side _and_ right side are `true`. A sequence of `and` and `or` expressions only executes as many parts as necessary ("short-circuits").], `or`, [ `true` if at least one side is `true`. A sequence of `and` and `or` expressions only executes as many parts as necessary ("short-circuits").], `not`, [ negates a boolean ], align(end+horizon)[`in` \ `not in`], [ `true` if left side is (not) an element of the collection on the right side. On arrays, this checks if left is (not) an element; for strings this checks whether left is (not) a substring of right; for dictionaries this checks if left is (not) a key of right. (```typc "ac" not in "abc"```), (```typc (1,2) not in (0,1,2,3)```), (```typc "foo" not in (bar: "foo")```) ] ) == Control structures Control structures are recognized as a single expression and can be written inline without parenthesizing them. #table(columns: (1fr, 2fr), ``` if COND BLOCK else if COND BLOCK else BLOCK ```, [ A conditional only executes at most one branch; there may be none or multiple `else if` branches and at most one `else` branch, which executes if all other conditions failed. Omitting the `else` branch implicitly returns `none` when necessary. Branch-bodies must not be bare expressions, but either be a `{codeblock}` or a `[markup]` block. Conditionals can be used as values. Checking for `none` or a "truthy" value _implicitly_ is not possible. See also: comparison-, keyword-operators ], //CHECK: ensure this is not last row on page table.cell(colspan: 2, fill: silver, align: center)[Loops:], ``` while COND BLOCK ```, [ A loop which checks the condition before every iteration. Loops join each iteration's result before inserting this into the output; this is of no big relevance since loop bodies have to be either a `[markup]` block or a `{codeblock}` and thus are joinable anyways. ], ``` for NAME in COL BLOCK ```, [ Executes BLOCK once for each item in collection COL making this item available as NAME. NAME is scoped to the loop and may be a destructuring pattern; see: `=` and `..` operators. If collection COL is a dictionary, it yields `(key, value)` pairs. Loops join each iteration's result before inserting this into the output; this is of no big relevance since loop bodies have to be either a `[markup]` block or a `{codeblock}` and thus are joinable anyways. ], //CHECK: ensure this is not last row on page table.cell(colspan: 2, fill: silver, align: center)[Loop Keywords:], `break`, [ Immediately exits the loop entirely; neither does the current iteration finish, nor does the loop continue with the next iteration. ], `continue`, [ Immediately ends the current iteration and the loop continues with the next iteration (if there is one). ], ) == Element functions The functions which create specific document elements are called element functions; for example `table` creates table elements. These functions can be used in `set` and `show` rules (see keyword expressions), as well as as selectors. They also expose many of their arguments with dot notation to `context` expressions (see: `context`). Specific elements will be discussed later... == Keyword expressions Keyword expressions, except `context`, consume the rest of the line unless it was explicitly ended early with a semicolon. #table(columns: (auto, 1fr), `include`, [ Can only access current directory and its descendants! #box(`include "NAME.typ"`) evaluates the specified file and inserts its _content_. ], `import`, [ Can only access current directory and its descendants! #box(`import "./NAME.typ" as NAME`) or equivalently #box(`import "./NAME.typ"`) evaluates the specified file and _makes its namespace available_ as variable `NAME`. It is possible to only load specified names directly into the current namespace by putting them comma-separated after a colon; `as` can be used to rename them: #box(`import "file.typ" : bar as baz, foo`) ], `let`, [`let NAME` declares (meaning creates) a name in the current scope, hiding inherited values of the same name and destroying earlier values of this name in the current scope. If not combined with an assignment (see: `=` operator), it initializes the value to `none`. There are only few restrictions for variable names, such as don't start with a number or a symbol other than underscore. By convention, irrelevant names, for example unskipable positions in destructuring patterns, are named with a sole underscore. ], `set`, [ Having to pass all arguments to an element function every time, is tedious, thus it is not necessary for most arguments: If arguments are omitted, their default values are used instead. These defaults can be changed for all _following_ code in the current _scope_ and its descendants using the `set` keyword: After the keyword invoke the function with the new defaults. #grid(columns: (2fr, 1fr), //stroke: silver, ```typ #{ set table(columns: 2, stroke: 2pt + red) table([foo], [bar]) // uses the new defaults { // child scope is affected: table( // compound types keep defaults // of unspecified parts: 2pt stroke: green, [foo], [bar] ) } } // outside scope isn't affected: #table([foo], [bar]) ```, [ #v(2em) #{ set table(columns: 2, stroke: 2pt + red) table([foo], [bar]) { table( stroke: green, [foo], [bar] ) } } #v(5em) #table([foo], [bar], stroke: black) ], ) ], `show`, [ The `show` keyword is for selecting and transforming this selection in some way; the selector argument is separated from the transformer argument with a colon.Instead of passing a function (with one positional argument: the selected element) as transformer, it is also possible to pass content or a string, or a `set` expression which is applied to the selection. A missing selector argument means everything from here one; if it is not missing it can be: - a `selector` type: for example one returned by the `where` method of an element function; all other valid selector arguments can be converted to this type by passing them to the constructor `selector`; this type also has useful methods, like `before` and `after`, to combine such objects - a `location` type: for example the one returned by the `locate` function; selects the element at the given location - a label: selects the tagged element - a string: selects every further occurrence of this text - a regular expression: selects every further occurrence of this pattern. Regular expressions are constructed with the `regex` function, which takes a string; they are unicode-aware and the specific syntax can be looked up at: #box()[https://docs.rs/regex/latest/regex/#syntax] ], `context`, [ To access the context in which an expression runs, it needs to be prepended with the `context` keyword; some expressions, like `show` rules, implicitly pass context. This is possible because the compiler does not process a document once, but multiple times, until it resolves completely or the maximum number of compiler iterations (5) is reached. \ For example to access style information like the current font use `#context text.font;` which gives: #context text.font; Context also knows about the current position in the document --- the `counter` type uses this information to provide the current value of whatever it counts with its `get` method: Currently we are in #context [ #let info = counter(heading).get() subchapter #info.at(1) of chapter #info.at(0)], which we know from the following expression: \ #box(```typ #context [ #let info = counter(heading).get() subchapter #info.at(1) of chapter #info.at(0)] ```) \ See the official docs for more info about counters, how to create custom ones and other methods returning locations. \ Expressions using context, always use the context from when the `context` keyword was used; thus when context changes in a context block, the `context` keyword has to be used again to reflect this: \ #box(```typ #context [ #set text(lang: "de") Text lang in this block is "#context text.lang", but outside it is "#text.lang"! ] ```) \ Produces: #context [ #set text(lang: "de") Text language in this block is "#context text.lang", but outside it is "#text.lang"! ] ], ) /* #set heading(numbering: "A.1") #counter(heading).update(0) = Appendix <appendix> #outline( title: none, target: selector(heading).after(inclusive: false, <appendix>), ) */ #pagebreak(weak: true) = Tables and Grids #set table(stroke: black) // resetting TAG:table_silver A `grid` is just a `table` with different default values, such as no borders, and usually used for layout purposes. == Constructor and Gutters Individual cells are passed to the element function as positional arguments, which are either content or `table.cell` (`grid.cell`) elements, which allow to customize the specific cell, for example to make is span multiple rows or columns. The cells are layed out in order in text direction, skipping occupied (due to the `colspan` or `rowspan` value of previous cells) places and starting new rows as needed according to the `columns` keyword-argument. Trailing empty cells may be omitted. `gutter` specifies the space between cells. #grid(columns: (auto, 1fr), align: (start, end+horizon), ```typ #table(columns: 4, gutter: 3pt, table.cell(rowspan: 2)[1\ 5], table.cell(colspan: 2)[2 3], /**/ [4], /**/ [/*empty*/], [7], /*[omitted empty trailing cell]*/ ) ```, table(columns: 4, gutter: 3pt, table.cell(rowspan: 2)[1\ 5], table.cell(colspan: 2)[2 3], /**/ [4], /**/ [/*empty*/], [7], /*[empty trailing cell]*/ ), ) == Width and Height Instead of passing the number of columns, it is also possible to pass a list of column widths, which may be absolute lengths, or relative values, where percentages act like absolute values computed from the available space _before_ laying out the table (which can lead to problems if there is not enough space or when using gutters) and fractions are computed from the remaining space _after_ determining the widths of the columns with absolute lengths. `auto` tries to take as little space as needed. ```typ #stack( table(columns: 2*(50%,) + (auto,), [50% of available space], [50%], [auto], ), table(columns: 2*(25%,) + (auto,), [25%], [25%], [auto]), block(width: 50%, table(columns: 2*(1fr,) + (auto,), [1fr], [1fr], [auto]) ), ) ``` #box(stack( table(columns: 2*(50%,) + (auto,), [50% of available space], [50%], [auto], ), table(columns: 2*(25%,) + (auto,), [25%], [25%], [auto]), block(width: 50%, table(columns: 2*(1fr,) + (auto,), [1fr], [1fr], [auto]) ), )) #grid(columns: 3, inset: (0pt, (left: 1em), (left: 1em)), [ The _minimum_ number of rows and their heights can be specified in the same way using the `rows` argument. When there are more cells supplied than fit into the specified rows, more rows are added, using the last specified height. ```typ #table(rows: (1em, 2em, 3em,), [1], [2]) #table(rows: (auto, 3em), [?], [3], [3]) ``` ], box(table(rows: (1em, 2em, 3em,), [1], [2])), box(table(rows: (auto, 3em), [?], [3], [3])), ) #v(-1em) // CHECK: keeps next table example on this page == Padding To pad content _within_ its cell, use argument `inset`, which allows supplying a dictionary (valid keys: `top`, `bottom`, `left`, `right`, `x` (left and right), `y` (top and bottom), `rest` (those not explicitly mentioned)) instead of a single value for all sides, a list which specifies values per column and is repeated as needed, or a function, which will be called with the x- and y-index of each cell for which it has to return an appropriate value. #grid(columns: (1fr, 1fr), align: (start, (center+horizon)), ```typ #table(columns: 5, inset: (0.5em, (x: 0pt, rest: 0.5em)), [1], [2], [3], [4], [5], ) ```, table(columns: 5, inset: (0.5em, (x: 0pt, rest: 0.5em)), [1], [2], [3], [4], [5] ) ) == Alignment Argument `align` specifies how to align content within its cell. There are the following alignment values, of which horizontal ones can be combined (using the `+` operator) with vertical ones: `start` and `end` (of text direction), `center` (horizontally), `horizon` (vertically), `left`, `right`, `top`, `bottom`. Value `auto` reuses the alignment from context; a list specifies alignments per column and is repeated as needed; a function will be called with the x- and y-index of each cell for which it has to return an appropriate value. #v(-0.5em) #grid(columns: (1.25fr, 1fr), align: horizon, inset: (top: 0.5em), ```typ #table(columns: 2*(1fr,), gutter: 1em, table(columns: 3em, [1]), align(end, table(columns: 3em, [1])), )```, table(columns: 2*(1fr,), gutter: 1em, table(columns: 3em, [1]), align(end, table(columns: 3em, [1])), ), ```typ #table(columns: 5*(1fr,), align: (right, left), .. for i in range(1, 11) { ([#i],) }, )```, table(columns: 5*(1fr,), align: (right, left), .. for i in range(1, 11) { ([#i],) }, ) ) == Borders Borders are specified with the `stroke` argument, which not only allows `stroke` objects, but also `color`s, `length`s and their combination (using `+`). It is also possible to specify border lines explicitly by passing `table.hline` and `table.vline` (`grid.hline`, `grid.vline`) elements as positional arguments after the cells before this border; arguments `start` and `end` take a (zero-based) row/column index to restrict their length. However, `hline`s and `vline`s extend into the gutter, while borders drawn due to a `stroke` argument only draw the border of cells. #grid(columns: (3fr,1fr), align: (start, end+horizon), ```typ #table(columns: 3, stroke: black, [1], [2], table.vline(end: 2, stroke: red + 2pt), [3], [4], [5], [6], table.hline(start: 1, end: 2, stroke: 3pt), table.cell(stroke: (right: 0pt, rest: none))[7], [8], [9], )```, grid.cell(breakable: false, table(columns: 3, stroke: black, [1], [2], table.vline(end: 2, stroke: red + 2pt), [3], [4], [5], [6], table.hline(start: 1, end: 2, stroke: 3pt), table.cell(stroke: (right: 0pt, rest: none))[7], [8], [9], )), ) As the example showed, - every cell has four borders which can be addressed separately by supplying a dictionary (valid keys: `top`, `bottom`, `left`, `right`, `x` (left and right), `y` (top and bottom), `rest` (those not explicitly mentioned)) and - touching borders do not draw over each other, but merge their values; when (parts of) values conflict, a later drawn cell's value prevails, unless some border value is more specific: the `stroke` value of a `vline`/`hline` trumps a `table.cell`'s (`grid.cell`'s) which trumps the table's (grid's) which trumps inherited (`set`) values. `none` values never prevail over other values of the _same specificity_ and specify not to draw a border. A list as value specifies `stroke` per column and is repeated as needed; a function will be called with the x- and y-index of each cell for which it has to return an appropriate value. There is no way to explicitly address the last cell in a row or column without knowing the table's dimensions. However, using the touching-border-behaviour it is possible to achieve the intended effect in some cases: Set the `stroke` value intended for an outer edge border on all cells and remove it from the unwanted cells by setting (again on all cells) the opposite border to a different value. Due to the edge borders not having a neighbour, their value is kept; however, this also means the approach does not work with gutters and leads to unexpected results if a table is split. ```typ #let tbl = table(columns: 3, align: center+horizon, .. for i in range(3) { for j in range(3) { ([#i #j],) } } ) ``` #let tbl = table(columns: 3, align: center+horizon, .. for i in range(3) { for j in range(3) { ([#i #j],) } } ) #v(-1em) #grid(columns: (4fr, 1fr), align: (start, end+horizon), inset: (top: 1em), ```typ #let with_outer_border(x, y) = ( bottom: black, // all cells get bottom border top: if y == 0 {black} // top row cells get top border else { 0pt }, // in other rows override top border // same approach for left and right borders: right: black, left: if x == 0 { black } else { 0pt }, ) #{set table(stroke: with_outer_border); tbl} ```, grid.cell(breakable: false, { let with_outer_border(x, y) = ( bottom: black, // all cells get bottom border top: if y == 0 {black} // top row cells get top border else { 0pt }, // in other rows override top border // same approach for left and right borders: right: black, left: if x == 0 { black } else { 0pt }, ) {set table(stroke: with_outer_border); tbl} }), ```typ #let no_outer_border(x,y) = ( bottom: none, // all cells have no bottom border top: if y == 0 { none } // top row cells don't have top border else { black }, // cells in other rows get top border // same approach for left and right borders: right: none, left: if x == 0 { none } else { black } ) #{set table(stroke: no_outer_border); tbl} ```, grid.cell(breakable: false, { let no_outer_border(x,y) = ( bottom: none, // all cells have no bottom border top: if y == 0 { none } // top row cells don't have top border else { black }, // cells in other rows get top border // same approach for left and right borders: right: none, left: if x == 0 { none } else { black } ) {set table(stroke: no_outer_border); tbl} }), ) == Colors Cell colors are specified with the `fill` argument. Passing a list specifies colors per column; it is repeated as needed. A function as value of `fill` will be called with the x- and y-index of each cell for which it has to return an appropriate value. ```typ #let tbl = table(columns: 5, stroke: none, align: center+horizon, .. for i in (range(1, 26)) { ([#i],) } ) ``` #let tbl = table(columns: 5, stroke: none, align: center+horizon, .. for i in (range(1, 26)) {([#i],)} ) #v(-1em) #grid( columns: (2fr, 1fr), align: (start+horizon, end+horizon), ```typ #{ set table( fill: (none, silver, gray) ) tbl }```, grid.cell(breakable: false, { set table( fill: (none, silver, gray)); tbl }), ```typ #{ set table( fill: (x,y) => if 0 == calc.rem(y,3) {none} else if 1 == calc.rem(y,3) {silver} else if 2 == calc.rem(y,3) {gray}, ) tbl }```, grid.cell(breakable: false, { set table( fill: (x,y) => if 0 == calc.rem(y,3) {none} else if 1 == calc.rem(y,3) {silver} else if 2 == calc.rem(y,3) {gray}, ) tbl }), ) == Misc. - *Headers and footers* may be wrapped in `table.header` and `table.footer` (`grid.header` and `grid.footer`), which repeats them when the table is split (unless `repeat=false`) and will allow to apply style rules to them in later typst versions. There is no element for a heading which is not in the first row. - *Horizontal cells* can be created by applying ```typc rotate(-90deg, reflow: true)``` to them.
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/syntax/shorthand.typ
typst
// Test shorthands for unicode codepoints. --- shorthand-nbsp-and-shy-hyphen --- The non-breaking space~does work, soft-?hyphen also does. --- shorthand-nbsp-width --- // Make sure non-breaking and normal space always // have the same width. Even if the font decided // differently. #set text(font: "New Computer Modern") a b \ a~b --- shorthand-dashes --- - En dash: -- - Em dash: --- --- shorthand-ellipsis --- #set text(font: "Roboto") A... vs #"A..." --- shorthand-minus --- // Make sure shorthand is applied only before a digit. -a -1 --- shorthands-math --- // Check all math shorthands. $...$\ $-$\ $'$\ $*$\ $~$\ $!=$\ $:=$\ $::=$\ $=:$\ $<<$\ $<<<$\ $>>$\ $>>>$\ $<=$\ $>=$\ $->$\ $-->$\ $|->$\ $>->$\ $->>$\ $<-$\ $<--$\ $<-<$\ $<<-$\ $<->$\ $<-->$\ $~>$\ $~~>$\ $<~$\ $<~~$\ $=>$\ $|=>$\ $==>$\ $<==$\ $<=>$\ $<==>$\ $[|$\ $|]$\ $||$
https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis
https://raw.githubusercontent.com/fuchs-fabian/typst-template-aio-studi-and-thesis/main/template/main.typ
typst
MIT License
#import "lib.typ": * #import "abstract.typ": abstract #import "abbreviations.typ": abbreviations #import "literature_and_bibliography.typ": literature-and-bibliography #import "attachements.typ": attachements // Kapitel #import "chapters/introduction.typ": introduction #import "chapters/summary.typ": summary // Füge hier weitere Kapitel hinzu #show: project.with( lang: "de", authors: ( ( name: "<NAME>", id: "12 34 567", email: "<EMAIL>" ), ), title: "Keine Panik!", subtitle: "Mit Typst durchs Studium", //date: "29.07.2024", version: none, // Hier kann die Versionsnummer des Dokumentes eingetragen werden thesis-compliant: true, // Setze es auf false, wenn es nur für Dokumentationen genutzt wird // Format side-margins: ( left: 3.5cm, right: 3.5cm, top: 3.5cm, bottom: 3.5cm ), h1-spacing: 0.5em, line-spacing: 0.65em, font: "Roboto", font-size: 11pt, hyphenate: false, // Color settings primary-color: dark-blue, secondary-color: blue, text-color: dark-grey, background-color: light-blue, // Cover sheet custom-cover-sheet: none, cover-sheet: ( university: ( name: "University of Applied Typst Sciences", street: "Musterstraße 1", city: "D-12345 Musterstadt", logo: none ), employer: ( name: "<NAME>", street: "Musterstraße 2", city: "D-12345 Musterstadt", logo: none ), cover-image: none, description: [ Bachelorarbeit zur Erlangung des akademischen Grades Bachelor of Science ], faculty: "Ingenieurwissenschaften", programme: "Typst Sciences", semester: "SoSe2024", course: "Templates with Typst", examiner: "Prof. Dr.-Ing Mustermann", submission-date: "30.07.2024", ), // Declaration custom-declaration: none, declaration-on-the-final-thesis: ( legal-reference: none, thesis-name: none, consent-to-publication-in-the-library: none, genitive-of-university: none ), // Abstract abstract: abstract(), // Setze es auf none, wenn es nicht angezeigt werden soll // Outlines depth-toc: 4, outlines-indent: 1em, show-list-of-figures: false, // Wird immer angezeigt, wenn `thesis-compliant` true ist show-list-of-abbreviations: true, // Nur sichtbar, wenn tatsächlich mit `gls` oder `glspl` Abkürzungen im Text aufgerufen werden list-of-abbreviations: abbreviations(), show-list-of-formulas: true, // Setze es auf false, wenn es nicht angezeigt werden soll custom-outlines: ( // none ( title: none, // required custom: none // required ), ), show-list-of-tables: true, // Setze es auf false, wenn es nicht angezeigt werden soll show-list-of-todos: true, // Setze es auf false, wenn es nicht angezeigt werden soll literature-and-bibliography: literature-and-bibliography(), list-of-attachements: attachements() ) = Einleitung<einleitung> #introduction() = Hauptteil // Hier sollten die einzelnen Kapitel aufgerufen werden, welche zuvor unter `chapters` angelegt wurden == Beispiele // Aufruf einer Abkürzung #gls("repo-vorlage") // Referenz zu einer anderen Überschrift @einleitung // TODO anlegen #todo[Das ist ein Beispiel] = Schluss/Zusammenfassung/Fazit<zusammenfassung> #summary()
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/homework/linear-algebra-bonus1.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra\nBonus Problems #1 (Cp. 1~2)", authors: ( (name: "<NAME>", email: "<EMAIL>", phone: "3230104585"), ), date: "October 29, 2023", ) = 第二周附加题 T1 #ac #prob[ #set math.mat(delim: "(") $ bold(A)&=(a_(i j))_(n times n)\ bold(B)&=mat( a_11,a_12b^(-1),a_13b^(-2),dots.c,a_(1n)b^(1-n); a_21b,a_22,a_23b^(-1),dots.c,a_(2n)b^(2-n); dots.v,dots.v,dots.v,,dots.v; a_(n 1)b^(n-1),a_(n 2)b^(n-2),a_(n 3)b^(n-3),dots.c,a_(n n); ) quad (b!=0)\ $ 已知 $|bold(A)|=t$,求 $|bold(B)|$. ] #set math.mat(delim: "|") $ |bold(B)| =& (product_(k=1)^n b^(-k)) mat( a_11 b^n, a_12 b^(n-1), a_13 b^(n-2), dots.c, a_(1 n) b; a_21 b^n, a_22 b^(n-1), a_23 b^(n-2), dots.c, a_(2 n) b; dots.v,dots.v,dots.v,,dots.v; a_(n 1) b^n, a_(n 2) b^(n-1), a_(n 3) b^(n-2), dots.c, a_(n n) b; )\ =& (product_(k=1)^n b^(k)) (product_(k=1)^n b^(-k)) mat( a_11, a_12, a_13, dots.c, a_(1 n); a_21, a_22, a_23, dots.c, a_(2 n); dots.v,dots.v,dots.v,,dots.v; a_(n 1), a_(n 2), a_(n 3), dots.c, a_(n n); )\ =& |bold(A)| = t $ = 第二周附加题 T2 #ac #set math.mat(delim: "|") #prob[ 计算:$ D_n = mat( space 1,1,1,dots.c,1,1,1 space; space 0,0,0,dots.c,0,2,1 space; space 0,0,0,dots.c,3,0,1 space; space dots.v,dots.v,dots.v,,dots.v,dots.v,dots.v space; space 0,n-1,0,dots.c,0,0,1 space; space n,0,0,dots.c,0,0,1 space; ) $ ] $ D_n = mat( 1/n,1/(n-1),1/(n-2),dots.c,1/3,1/2,1; 0,0,0,dots.c,0,1,1; 0,0,0,dots.c,1,0,1; dots.v,dots.v,dots.v,,dots.v,dots.v,dots.v; 0,1,0,dots.c,0,0,1; 1,0,0,dots.c,0,0,1; ) = mat( 1/n,1/(n-1),1/(n-2),dots.c,1/3,1/2,1-sum_(i=2)^n 1/i; 0,0,0,dots.c,0,1,1; 0,0,0,dots.c,1,0,1; dots.v,dots.v,dots.v,,dots.v,dots.v,dots.v; 0,1,0,dots.c,0,0,1; 1,0,0,dots.c,0,0,1; ) = (-1)^(n(n-1)/2) (1-sum_(i=2)^n 1/i) $ = 第二周附加题 T3 #prob[ 计算:$ D_n = mat( a_1+b_1,a_2,dots.c,a_n; a_1,a_2+b_2,dots.c,a_n; dots.v,dots.v,,dots.v; a_1,a_2,dots.c,a_n+b_n; ) $ ] = 第二周附加题 T4 #prob[ 计算:$ D_n = mat( 1,2,3,dots.c,n-1,n; 2,3,4,dots.c,n,1; 3,4,5,dots.c,1,2; dots.v,dots.v,dots.v,,dots.v,dots.v; n-1,n,1,dots.c,n-3,n-2; n,1,2,dots.c,n-2,n-1; ) $ ] $ D_n =& mat( 1,2,3,dots.c,n-1,n; 2,3,4,dots.c,n,1; 3,4,5,dots.c,1,2; dots.v,dots.v,dots.v,,dots.v,dots.v; n-1,n,1,dots.c,n-3,n-2; n,1,2,dots.c,n-2,n-1; ) = mat( space 1,2,3,dots.c,n-1,n; space 1,1,1,dots.c,1,-(n-1); space 1,1,1,dots.c,-(n-2),1; space dots.v,dots.v,dots.v,,dots.v,dots.v; space 1,1,-2,dots.c,1,1; space 1,-1,1,dots.c,1,1; )\ =& mat( space 1,1,2,dots.c,n-2,n-1; space 1,0,0,dots.c,0,-n; space 1,0,0,dots.c,-(n-1),0; space dots.v,dots.v,dots.v,,dots.v,dots.v; space 1,0,-3,dots.c,0,0; space 1,-2,0,dots.c,0,0; ) = (-1)^(n-1) mat( space 1,0,0,dots.c,0,-n; space 1,0,0,dots.c,-(n-1),0; space dots.v,dots.v,dots.v,,dots.v,dots.v; space 1,0,-3,dots.c,0,0; space 1,-2,0,dots.c,0,0; space 1,1,2,dots.c,n-2,n-1; )\ =& (-1)^(n-1) mat( space 1,0,0,dots.c,0,1; space 1,0,0,dots.c,1,0; space dots.v,dots.v,dots.v,,dots.v,dots.v; space 1,0,1,dots.c,0,0; space 1,1,0,dots.c,0,0; space 1,-1/2,-2/3,dots.c,-(n-2)/(n-1),-(n-1)/n; ) = (-1)^(n-1) mat( space 0,0,0,dots.c,0,1; space 0,0,0,dots.c,1,0; space dots.v,dots.v,dots.v,,dots.v,dots.v; space 0,0,1,dots.c,0,0; space 0,1,0,dots.c,0,0; space 1+sum_(i=1)^(n-1) i/(i+1),-1/2,-2/3,dots.c,-(n-2)/(n-1),-(n-1)/n; )\ =& (-1)^(n(n+1)/2+1) (1+sum_(i=1)^(n-1) i/(i+1)) $ = 第二周附加题 T5 #prob[ 将 $n$ 阶矩阵 $bold(D)$ 的每个元素减去其同行其余元素之和,得到 $bold(D_1)$,若 $|bold(D)|=t$,求 $|bold(D_1)|$. ] = 第三周附加题 T1 #prob[ #set math.mat(delim: "|") 求:$ D_n = mat( d,b,b,dots.c,b; c,x,a,dots.c,a; c,a,x,dots.c,a; dots.v,dots.v,dots.v,,dots.v; c,a,a,dots.c,x; ) quad (x!=a and b != 0 and c != 0) $ ] = 第三周附加题 T2 #ac #prob[ 求:$ D_n = mat( x_1, a_1 b_2, dots.c, a_1 b_n; a_2 b_1, x_2, dots.c, a_2 b_n; dots.v,dots.v,,dots.v; a_n b_1, a_n b_2, dots.c, x_n; ) $ ] $ D_n = mat( x_1, a_1 b_2, dots.c, a_1 b_n; a_2 b_1, x_2, dots.c, a_2 b_n; dots.v,dots.v,,dots.v; a_n b_1, a_n b_2, dots.c, x_n; ) = (product_(i=1)^n a_i b_i) mat( display(x_1/(a_1 b_1)), 1, dots.c, 1; 1, display(x_2/(a_2 b_2)), dots.c, 1; dots.v, dots.v, , dots.v; 1, 1, dots.c, display(x_n/(a_n b_n)); ) $ 令 $t_i = display(frac(x_i, a_i b_i))$,新矩阵的行列式为 $D'_n$ 那么 $ D'_n &= mat( t_1, 1, dots.c, 1; 1, t_2, dots.c, 1; dots.v, dots.v, , dots.v; 1, 1, dots.c, t_n; ) = mat( t_1,1,1,dots.c,1; 1-t_1,t_2-1,0,dots.c,0; 1-t_1,0,t_3-1,dots.c,0; dots.v,dots.v,dots.v,,dots.v; 1-t_1,0,0,dots.c,t_n-1; )\ &= -(product_(i=1)^n (t_i-1)) mat( display(t_1/(1-t_1)), display(1/(t_2-1)), display(1/(t_3-1)), dots.c, display(1/(t_n-1)); 1, 1, 0, dots.c, 0; 1, 0, 1, dots.c, 0; dots.v, dots.v, dots.v, , dots.v; 1, 0, 0, dots.c, 1; )\ &= -(product_(i=1)^n (t_i-1))(t_1/(1-t_1) - sum_(i=2)^n 1/(t_i )- 1)\ &= (product_(i=1)^n (t_i-1))(1 + sum_(i=1)^n 1/(t_i-1))\ => D_n &= (product_(i=1)^n a_i b_i) (product_(i=1)^n (x_i-a_i b_i)/(a_i b_i)) (1 + sum_(i=1)^n (a_i b_i) / (x_i - a_i b_i))\ &= product_(i=1)^n (x_i-a_i b_i) (1 + sum_(i=1)^n (a_i b_i) / (x_i - a_i b_i))\ $ = 第三周附加题 T3 #ac #prob[ 求:$ D_n = mat( a_1, a_2, dots.c, a_n; x_1, x_2, dots.c, x_n; x_1^2, x_2^2, dots.c, x_n^2; dots.v,dots.v,,dots.v; x_1^(n-1), x_2^(n-1), dots.c, x_n^(n-1); ) $ ] $ D_n &= sum_(i=1)^n a_i product_(j=1\ i!=j)^n x_j product_(1<=p<q<=n\ i!=p and i!=q) (x_q - x_p) \ &= (product_(i=1)^n x_i) (product_(1<=j<k<=n) (x_k-x_j)) (sum_(i=1)^n a_i/x_i) / (product_(j=1)^(i-1) (x_i-x_j) product_(k=i+1)^n (x_k-x_i))\ &= (product_(i=1)^n x_i) (product_(1<=j<k<=n) (x_k-x_j)) sum_(i=1)^n (a_i (-1)^(n-i))/(x_i product_(j!=i) (x_i-x_j))\ $ = 第三周附加题 T4 #prob[ 求:$ D_n = mat( 0,a_1+a_2,a_1+a_3,dots.c,a_1+a_n; a_2+a_1,0,a_2+a_3,dots.c,a_2+a_n; a_3+a_1,a_3+a_2,0,dots.c,a_3+a_n; dots.v,dots.v,dots.v,,dots.v; a_n+a_1,a_n+a_2,a_n+a_3,dots.c,0 ) $ ] = 第三周附加题 T5 在往年小测中出现过,故略去.
https://github.com/sicheng1806/typst-book-for-sicheng
https://raw.githubusercontent.com/sicheng1806/typst-book-for-sicheng/main/scr/typst速览/main.typ
typst
#import "../basic_pkg/note_CN.typ" #import "../basic_pkg/par.typ" : abstact #import "../basic_pkg/table.typ" : webtable #import "../basic_pkg/board.typ" : code-board,result-board,background-board #show : doc => note_CN.conf( title: "typst速览笔记", author: text(blue)[sicheng1806], _numbering: true, doc ) // 设置一些小函数 #let ind2 = h(2em) // 给术语每一项加标签用于索引 // ---------------------正文------------------------------------ #abstact()[ typst具有代码模式和文本模式 ] = 术语表 #note_CN.term-list() = 文本模式符号速览 == 常用结构化标记 #ind2 下面用表格列出,注意标签需要是可引用的,如标题,公式,图表等。 #align(center,block(width: 90%, webtable( columns: (1fr,2fr,2fr), row-gutter: 1em, fill: luma(95%), linestroke: luma(0%), align: left, "名称", "用法" ,"示例", "划分章节", "=若干" , `== 二级标题`, "段落中断", "空行 或 parbreak", `parbreak()`, "行中断" , "linebreak 或 \ " , `你好\ 世界` , "无序列表" , "-" , `- item` , "有序列表" , "+" , `+ item` , "术语列表" , "/ ITEM: 解释" , `/ ITEM: 解释`, "注释" , `// line 或 /* block */` , `// 注释`, "源码段" , "`", "`print(1)`", "链接" , "link 或 直接输入链接" , `link(https://www.bilibili.com)`, "数学公式", `$` , `$e = mc^2$`, "标签" , "<>" , `<a>`, "引用" , "@" , "@a", "加重" , "strong() 或 *" , `*hello*`, "斜体" , "_hello_ 或 emph()", `_hello_` , "下划线" , "underline()" , `underline(hello)` ) )) == 文本修饰命令 #for ( func, mean ) in ( "strong" : "加粗文本", "emph" : "斜体文本", "hightlight" : "高亮文本", "raw" : "具有可选语法突出显示的原始文本", "strike" : "在文本中画一条线", "sub" : "以下标的形式呈现文本", "super" : "以上标的形式呈现文本", "underline" : "给文本加下划线", "linebreak" : "断行不产生新的段落", "overline" : "在文本头顶画线" ) { set terms( separator: "——", ) show terms : it => { stack(dir:ltr,box(width:2em),emoji.face.lick,it) } [/ #func : #mean] } === raw 命令的解释 #ind2 使用符号 #"`" 时具有两种模式,一种时没有语法高亮的 #"``" 一般用于不分行的显示原文,一种是通过参数确定语法高亮或者不高亮的模式 #"```" , 例如: ```` ```python print("hello world")``` ```` 参数为空时为不高亮,参数可选 `python` , `rust` 等。当需要显示上文的示例时,需要使用 #"````",才不会导致识别错误。 raw函数可进一步设置文本显示情况,也可以通过 `show-set规则` 管理样式。 === 断行与段落中断的用法 #ind2 断行可以通过 `\` 或者 `linebreak()` 来设置,段落中断可以通过连续两个换行符来设置,断行和新行的区别是显著的,需要注意区别。 == 常用符号命令 #ind2 一些特殊的符号除了转义表达还有其自己的命令函数,也可以自定义相关符号。 #for (_func , mean) in ( "linebreak":"断行", "parbreak" : "段落中断", "colbreak" : "列中断", "pagebreak" : "分页符" ) { set terms( separator: " "+emoji.bubble.speech+"——", ) [/ #_func: #mean] } == sym符号族和emoji符号族 #ind2 sym符号族存储了大量的一般符号(非emoji),而emoji则储存了大量表情符号。 == 用symbol函数创建新的符号族 #ind2 使用 `symbol函数` 可以快速构建和 `sym符号族` 和 `emoji符号族` 一样调用方法的符号族。用法见示例: #code-board()[ ```typst #let car = symbol( "\u{1F697}", ("front","\u{1F698}"), ("pickup","\u{1F6FB}"), ) // 使用符号 #car #car.front #car.pickup ``` ] // 使用符号 #result-board()[ #let car = symbol( "\u{1F697}", ("front","\u{1F698}"), ("pickup","\u{1F6FB}"), ) #car #car.front #car.pickup ] = 文本模式布局速览 #ind2 如果要细分typst用于布局的工具的话,可以分为以下几类: - 布局符号 --- 使用添加类似符号的内容用于布局,例如内联式容器中的 `h`、 `v` 或者 非内联式的 `line`、 `rect` 等。 - 内容容器 --- 使用各种性质的容器来组织内容,如 `list` 、 `grild` 等。 - 变换工具 --- 此类工具有平移、旋转、放缩等。 - 绘图工具 --- 此类工具提供绘画的基础功能,使用 `ctez` 库,可以轻松绘制更加复杂的图形。如 `circle` 、 `line` 等。 - 布局参数调节工具和容器 --- 此类工具用于设置内容的布局参数,也可以作为内容容器,是内容容器的一种类型。如 `align` 、 `text` 等。 == 使用布局符号布局 #for ele in ( ("h","在段落中插入水平空白",result-board[First #h(1fr) Second #h(1fr) Third]), ("v", "在一系列块中插入垂直空白", result-board[A #v(2em) B #v(1em) C] ), ("box", "指定大小的内联式容器", result-board[Refer to the docs #box(height: 9pt,width: 9pt) for more information.]), ("place" , "在当前页面的指定位置放置内容,不会影响其他内容布局,示例请在当前页面各方位查找", place(top + right,dy:1em,square(width: 20pt,stroke: 2pt + blue,),)) ) { set par(first-line-indent: 0pt) set terms( separator: "——", ) show terms : it => { stack(dir:ltr,emoji.face.diagonal,it) } par[ / #ele.at(0): #ele.at(1) \ *示例* : \ #ele.at(2) ] } === place 说明 #ind2 由于place具有浮动布局的效果,因而可以视为一个单独的布局元素,这与其他元素都不同,包括字符形式的布局工具。 == 使用内容容器布局 这一类既包括列表、表格之类的有特定表示形式的容器,也包括网格、块这类通用的布局容器,同时也包括在文字排版中就使用的可以设置布局参数的内容容器。 === 特殊形式类 #for ele in ( ("list","无序列表",result-board[略]), ("enum","有序列表",result-board[略]), ( "table","表格",result-board[#table( columns: (1fr, auto, auto), inset: 10pt, align: horizon, [],[*Area*],[*Parameter*], "圆柱",[$ pi h (D^2 - d^2) / 4 $],[ $h$: height \ $D$: outer radius \ $d$: inner radius ])] ), ("figure","带有可选描述的图表",result-board[略]), ("terms","术语列表",result-board[略]), ("image","图形的加载接口",result-board[略]), ("bibliography","一份参考文献",result-board[略]), ("outline","目录、图表或其他元素的大纲",result-board[略]) ) { set par(first-line-indent: 0pt) set terms( separator: "——", ) show terms : it => { stack(dir:ltr,emoji.face.explode,it) } par[ / #ele.at(0): #ele.at(1) \ *示例* : \ #ele.at(2) ] } === 基础布局类 #for ele in ( ("block","自适应给定宽度或高度圆角方形外联容器",result-board(width:100%)[#block(width: 2em,height: 2em,fill: blue)]), ("rect","更适合几何控制的外联容器",result-board[#rect(height: 2em,fill: blue)[#rect(height: 2em,width: 1em,fill:red)#rect(height: 2em,width: 1em,fill:red)]]), ("box","一个内联级容器,可调整内容的大小",result-board[略]), ("grid","将内容排列成网格",result-board[略]), ("pad","在内容周围添加间距",result-board[#pad(bottom: 2em,rect(fill:blue)[bottom:2em])_Typing speeds can be measured in words per minute._]), ("stack","实现内容按指定方向的快速堆叠",result-board[#stack(box(fill: blue,width: 1em,height: 1em),"你好" ,box(fill: blue,width: 1em,height: 1em))]) ) { set par(first-line-indent: 0pt) set terms( separator: "——", ) show terms : it => { stack(dir:ltr,emoji.face.explode,it) } par[ / #ele.at(0): #ele.at(1) \ *示例* : \ #ele.at(2) ] } ==== rect 和 block的区别 #ind2 block是个自适应极强的容器,如果在block进行多重嵌套,且只有block,会发现其width或者height参数失效,而rect不会发生这样的情况。 所以如果希望目标容器可以根据内容自适应排版选择block,如果希望其的大小可以严格控制,选择rect。 === 可调全局布局的容器 #ind2 这一类容器按照一定的逻辑结构将文本和其他内容排列成整个文档。 #for ele in ( ( "document", "这个文档的根元素同时包含着其元数据,一般用于设置元数据", code-board[ ```typst #set document(title: [Hello]) This has no visible output, but embeds metadata into the PDF! ```] ), ("page","将其中的内容布局进一个或多个页面,可以用来设置页面的样式",code-board[ ```typst #set page("us-letter") There you go, US friends! ```]), ("par","管理一个段落中的文档、间距和行内元素,可以用来设置段落样式",code-board[ ```typst #show par : set block(spacing: 2em) // 段落垂直间距 #set par( first-line-indent: 1em, // 首行缩进 justify: true, // 对齐 ) ```]), ("text","以各种方式自定义文本的外观和布局。一般用来设置",result-board[#text(fill: red)[红色字体]]), ("columns","将区域分割为多个大小相等的列。",result-board[ #columns(2,gutter: 11pt)[ #set par(justify: true) This research was funded by the National Academy of Sciences. NAoS provided support for field tests and interviews with a grant of up to USD 40.000 for a period of 6 months. ]]), ("align","将内容垂直和水平对齐",result-board[ #set align(center) Centered text, a sight to see \ In perfect balance, visually \ Not left nor right, it stands alone \ A work of art, a visual throne ]) ) { set par(first-line-indent: 0pt) set terms( separator: "——", ) show terms : it => { stack(dir:ltr,emoji.face.explode,it) } par[ / #ele.at(0): #ele.at(1) \ *示例* : \ #ele.at(2) ] } === 变换工具 #for (_func , mean) in ( "rotate" : "旋转内容而不影响布局", "move" : "移动内容而不影响布局", "hide" : "隐藏内容而不影响布局", "scale" : "缩放内容而不影响布局" ) { set terms( separator: " "+emoji.bubble.speech+"——", ) [/ #_func: #mean] } === 获取内容的布局元素大小 #[ #set par(first-line-indent: 0em) / measure: 和 style函数结合使用来获取指定内容的大小 / layout: 提供对当前外部容器大小的访问 ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/010_Return%20to%20Dominaria%3A%20Episode%2010.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Return to Dominaria: Episode 10", set_name: "Dominaria", story_date: datetime(day: 16, month: 05, year: 2018), author: "<NAME>", doc ) For a long time Slimefoot knew nothing except the #emph[Weatherlight] 's warm hull and the hot sun of Bogardan. As it grew out of its sporehood into its stalk phase, it was conscious of sound, the voices of other living things. These voices were sometimes loud and sometimes soft, and gradually it learned to differentiate them into individual life forms. One day two of those individual life forms used ropes to climb down the hull with a tool, a long wooden handle with a blade on the end. "I think we left this one too long," one said. "It's going to be hard to pry off." "Just give it a good whack first," the other said. "That should loosen it." Slimefoot didn't think a whack would be good at all. Then the roar of fire came from the sky and voices shouted in alarm. The two life forms dropped their tool and scrambled down their ropes toward the ground. The sound and scent of fire was alarming enough to boost Slimefoot right into the next stage of its development. It popped its partially grown stalks out of their casing and then hesitated. It wasn't developed enough to see for more than a short distance around and it couldn't tell where the fire and shouting was coming from. But this warm hull had been Slimefoot's whole life and it was afraid to leave. Instead, it started the laborious climb upward. #figure(image("010_Return to Dominaria: Episode 10/01.jpg", width: 100%), caption: [Saproling | Art by <NAME>], supplement: none, numbering: none) Its stalks were weak and undeveloped, and it trembled with the effort of the climb. The waves of heat in the air dried its skin and made it harder and harder to hold on. Nearly limp with exhaustion, it reached the edge of the deck and wiggled under the lowest bar of the railing. The heat had stopped but the voices continued. Slimefoot knew it wasn't safe yet and dragged itself forward across the deck, looking for shelter. Abruptly the deck disappeared under it. It plunged down through dark empty air and landed with a splat. It lay there for a time, dazed by the darkness and the fall, until it realized it could sense a presence. A warm white star, shining from the nest of tubes and metal filling the dark space. It gave Slimefoot the strength to crawl farther, to find a passage to climb through into an empty space, where it could finally rest. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Slimefoot grew in darkness, the shining white star supplying all the nourishment of the sun. After a time, it knew its home had lifted up and moved through the air, but it wasn't sure what that meant. As it grew larger and its senses became more keen, it started to hear voices, carried on the tubes that connected the white star at the ship's heart to the rest of its Thran body. "I hope they're all right down there," one voice said. "This Cabal agent has been able to fool an entire academy of mages—that doesn't sound good." The white star surrounded this voice with a warm glow, and Slimefoot was sure it had heard it before, before its stalk phase. This was the voice that had guided the ship's rebirth. Tiana. It was called Tiana. Another voice said, "All the agent had to do was lie low and pretend not to be a bloodthirsty murderer." That was Arvad, who the white star had called from across the world to be Tiana's friend and helper. "Cabal cultists are good at that." "Wait, is that Jhoira's owl? She said she'd send it up when they were done." "That's the owl. I'll go start dinner." Slimefoot knew it was nearing the beginning of its emergent phase when its stalks grew stronger. At some point it would have to venture out, but the outside world had been so frightening. It seemed much more sensible to stay here and go into an early reproduction cycle. At least after that it would have company. Slimefoot went dormant during reproduction to concentrate its energy, but when it became aware again, it was to a sense of heat on the ship's hull. The air was dry as dust. It was definitely more sensible to stay here in the safe dark, watched over by the white star. But it heard voices again. One said, "I like your daughter." That was Jhoira, a voice the ship knew in its Thran bones. The ship recognized Teferi's laugh. "Of course you do. I wish you could have met Subira." "So you don't regret it, then. Giving up your spark?" "I regret a lot of things. But not that." Slimefoot mostly communed with its new sprouts, enjoying the sense of companionship, but it listened to the voices, learning about the other inhabitants of the ship. The scent of Yavimaya drifted down through the openings in the wooden walls. It almost made Slimefoot consider going out for a look. But the sprouts couldn't move yet, and the fresh green scent of Yavimaya was combined with the frightening taint of smoke. Slimefoot huddled down with its sprouts and didn't move. Then a voice said, "The #emph[Weatherlight] is so much the same, and so different." #emph[Karn] , the white star whispered. Slimefoot felt the Thran structure hum in response. #figure(image("010_Return to Dominaria: Episode 10/02.jpg", width: 100%), caption: [Karn, Scion of Urza | Art by Chase Stone], supplement: none, numbering: none) "Is it strange to be on board again?" That was Shanna, who had patterns in her blood that were the same as those woven through the ship's bones. "After all that happened to you?" A trace of amusement in his resonant voice, Karn answered, "After all that happened to me, everything is strange." Raff was another whose blood was familiar. Slimefoot was wary of the two new ones, Chandra and Jaya, who smelled of fire, though the white star didn't seem to mind them. Jhoira said, "Jodah told me about you. Does he know you're back?" Jaya said, "Huh. I didn't know he was back." "He's in Tolaria West, at the Academy. Once all this is over, we can take you back there. If you want." "Thanks for the offer. But I'm not sure just how back I am yet, if you know what I mean." The other two aboard weren't known to the ship, but the white star did not object to their presence. Not even the one who had death written into her skin. Liliana said, "You didn't tell Chandra about Josu." Gideon told her, "No, and I won't. It's not my story to tell, is it." "If you told her, you might have used it to make her feel . . . make her feel she should help us kill Belzenlok." Gideon sounded exasperated. But Gideon sounded exasperated a lot, so Slimefoot wasn't sure it meant anything. "Liliana . . . If that's what you want, why didn't you tell her?" "I don't need to, do I? She already wants to help us kill Belzenlok." "Because she agrees with us that it has to be done before we face <NAME> again. I don't even know what you're asking me. Are you trying to find out why my first impulse isn't to use information given to me in strict confidence by one friend to manipulate another friend?" "No, of course not!" Liliana strode away. Slimefoot heard Gideon murmur, "Her capacity to lie to herself is #emph[almost] infinite." Slimefoot began to seriously consider whether it should leave its safe haven. The sprouts had reached their incipient stalk phase and Slimefoot had sent the chemical signal telling them it was time to complete their transition. They uprooted their stalks and practiced walking around the chamber and climbing its walls. Slimefoot needed to use its own stalks before it slid back into a dormant phase. It was considering the problem when the door opened. #figure(image("010_Return to Dominaria: Episode 10/03.jpg", width: 100%), caption: [Slimefoot, the Stowaway | Art by <NAME>], supplement: none, numbering: none) A figure stood there. It had been a long time since Slimefoot had seen another living being and it was more curious than startled. After a long moment, the figure said, "Tiana, I think I found where that smell is coming from." It was Arvad! Slimefoot freed an armstalk from the bulk of its body and waved. "The storage space next to the main engine compartment," Arvad added. Slimefoot and Arvad stared at each other until Tiana appeared. "Oh, holy Serra," Tiana said. Slimefoot waved at her. "Did it just wave at me?" Tiana said. "I think so." Arvad hesitated. "If you can understand me, wave at both of us." Slimefoot freed a second armstalk and waved at both of them. "Huh." Tiana seemed nonplussed. "Right, then." "I think it's a thallid," Arvad said. "Probably." Tiana was quiet for a moment. "Hey, are you a thallid?" Slimefoot didn't have the vocal apparatus to reply, but used its armstalks to gesture. It wasn't entirely sure what it was yet, though it felt that knowledge would come with a later phase of development. It was hard to convey that with gestures. "It's obviously trying to answer you," Arvad said. "I wouldn't say #emph[obviously] ," Tiana said. "Because it doesn't have a face?" Arvad asked. Tiana seemed to be trying to turn her head sideways to look at Slimefoot from another angle. "Well, yes, but it is talking to us, so it's definitely . . . Hold on, Raff might be able to talk to it." Tiana left. Slimefoot and Arvad stared at each other some more. Arvad said, "Hello. I'm Arvad. Sometimes called the Cursed." Slimefoot gestured assent and pointed at the slime curtain around its stalks, trying to convey its own name. "Uh huh," Arvad said. Then Tiana appeared with Raff. Raff said, "Oh, right, this is a thallid. Hi there, thallid." Slimefoot freed a third armstalk to wave a greeting. "That's helpful, Raff," Tiana said. Her tone suggested that it was not at all helpful. "What is it doing here?" "Well, thallids are from Yavimaya, and are sort of related to mushrooms," Raff explained. "They were originally created as a . . . Uh, I'll tell you later. It's a little awkward to get into all that with it standing there. This one probably came aboard as a spore, stuck to that tree elemental seed Jhoira used to regrow the hull. Oh, hey, and it's had like ten babies already." "WHAT?" Tiana said. Slimefoot looked around at its sprouts, all in the stalk phase now. It prompted them, and they all waved at their new friends. "Yeah, those are little thallids. Hi, little thallids," Raff said. He turned to Tiana. "What are you going to do about it?" Tiana didn't answer, but sighed deeply. Slimefoot wasn't sure how to interpret that. Arvad said, "It—they haven't shown any sign of trying to attack us or hurt the ship . . . Do we need to do anything about it?" "We could take it to Yavimaya," Raff suggested. "We were just at Yavimaya." Tiana put both hands in the auburn growth on her head, like she might pull it out. "Right, let's just leave it where it is right now. I'm going to talk to Jhoira." Arvad closed the door, and Slimefoot heard them walking away. Voice fading with distance, Raff said, "Tell Jhoira that Serra said it was okay that it's here—Ow! I was kidding!" Slimefoot considered its situation, then looked around at its sprouts. Instinctively, it knew that it was time to move around and look at the world. Well, it had better get started. Slimefoot sent the chemical signals to its sprouts to tell them it was time to leave their home. Once they were all thumping around on the floor, Slimefoot went to the door. Pushing it open, Slimefoot stepped out, calling the sprouts to come along. It followed the path Tiana and Arvad had taken. They had gone down a large curving corridor, and Slimefoot realized it must run along the inside of the ship's hull. It went through the first opening and found Tiana and Arvad standing in a chamber in the center part of the ship, which had openings to other corridors. Arvad said, "It's followed us. With the babies." "I see that." Tiana stared at Slimefoot and Slimefoot stared back. #figure(image("010_Return to Dominaria: Episode 10/04.jpg", width: 100%), caption: [Slimefoot, the Stowaway | Art by <NAME>], supplement: none, numbering: none) Liliana strode in, stopped, and demanded, "What's this?" "They're thallids, from Yavimaya, probably," Tiana said. Arvad spoke to Slimefoot: "Thallids, this is Liliana." Slimefoot waved a greeting at her, and prompted all the sprouts to do the same. Tiana added, "Apparently they've been aboard since the ship was constructed in—" Liliana frowned at Slimefoot. "Yes, whatever. What do they do?" Tiana eyed Slimefoot. "So far, they stare at people." "Well, that's useless." Liliana turned to Arvad and said, "How did you decide not to eat people?" Arvad could eat people? That was alarming. Slimefoot and all its sprouts turned to stare at Arvad. Arvad seemed taken aback as well. "It wasn't a decision. I didn't want to be a vampire. I was turned against my will." Liliana waved a hand. "Yes, I understand that, but once you were turned, wouldn't drinking blood be the natural thing to do?" "No." Arvad appeared confused. "Are you trying to convince me that drinking blood is a good idea?" "No, of course not." Liliana appeared to reconsider. "Unless it's expedient, then—" Tiana had folded her arms, watching with a speculative expression. Now she said, "You're asking him how he resisted the urge to be selfish." Liliana turned to glare at her. "No, I'm not asking that." She glanced at Arvad again. "But since she's brought it up, how did you?" Arvad's expression turned thoughtful. "It wasn't easy. I had to hold on to an image of myself as I was before I was changed. As I wanted to be." He added, "With the Powerstone's effect on me, it's much easier. But I know I could leave its influence if I had to, and retain control." Liliana didn't look as if that was what she wanted to hear. "So there's no trick to it." Tiana scratched her head and asked, "Is there something you'd like to talk about? I am an angel. We're supposed to be good at this sort of thing." "No, of course not." Liliana recoiled in horror. "Never mind. And if you tell anyone we had this conversation, you'll both regret it." She strode away down another corridor. That had been interesting. Slimefoot felt better about its decision to explore. After growing so long in the dark, the outside world was certainly proving to be an interesting place. There was obviously a lot more to see. It chose a different corridor and started away. Behind it, Arvad said, "Uh, we better warn the others that it's here." Tiana said, "I'll go forward, you go aft." Slimefoot explored for a while. The winding paths of the corridors and rounded shapes of the chambers were pleasantly familiar. The people had said the ship had grown from the seed of an elemental, which was probably why it felt so familiar, and why it had sheltered Slimefoot and accelerated its growth and life cycle, why Slimefoot seemed to know and understand so many things about its other inhabitants. It found an opening to a chamber and looked inside. Teferi sat on one side of the room reading a book, and on the other Gideon was sharpening a weapon. Gideon looked up at Slimefoot. Slimefoot waved a greeting. Gideon said, "Teferi." #figure(image("010_Return to Dominaria: Episode 10/05.jpg", width: 100%), caption: [Slimefoot, the Stowaway | Art by <NAME>], supplement: none, numbering: none) Teferi looked up briefly. "Ah, thallids. Yes, Tiana said they found some living in the engine compartment." Gideon was silent a moment, then said, "That sounds like someone else's problem," and went back to sharpening the blade. Slimefoot watched them for a while, but they didn't do anything else, so it moved on. Next it found a large compartment where Jhoira sat at a table. Jhoira was the ship's favorite. Jhoira had a lens over her right eye to examine the crystal and metal artificer's components spread out on the table. She fumbled for a tool just out of reach and Slimefoot used an extra armstalk to pick it up and hand it to her. She said, "Thank you, Shanna." "That's not me." Shanna came into the room and took a seat across from Jhoira. "And I'll try not to take it personally." "What?" Jhoira looked up, blinking. She focused on Slimefoot. "Oh, sorry. Yes, Tiana said we had stowaways." Raff had followed Shanna in. "Hello, thallids." He sat down and said to Shanna, "I'm just saying, most famous warriors have a tragic past." "I don't," Shanna said, with an air of finality. "I know, I just think it's odd," Raff persisted. "You're odd," Shanna retorted. Slimefoot thought almost being killed by a shovel and having to use its still-soft stalks to flee for its life up to shelter in the ship's engine compartment might qualify as a tragic past, but everything had gone pretty well after that point. Its sprouts cautiously explored the room, studying the books and tools in all the shelves they could reach. "Please ask them not to touch anything," Jhoira said to Slimefoot. Slimefoot told the sprouts not to get too close to anything, though right now they didn't have armstalks. Raff apparently still wanted to talk about tragic pasts. "No, I mean, are you sure it's not just a little tragic?" Shanna sighed. "There was the time my younger sister burnt the honey bread on Solstice morning because she was flirting with the neighbors, and my older sister told her she'd ruined the holiday. There were tears." Jhoira adjusted her eyepiece. "You know, Raff, you don't have a tragic past either." "That's because he barely has a past," Shanna said. Raff drew himself up. "You don't know my past isn't tragic." Jhoira lifted her brows. He tried, "It's not easy studying at the Tolarian Academy, you know." "She does know," Shanna pointed out. Jhoira propped her chin on her hand, glaring at him through her eyepiece. "And how many time rifts did you get trapped in?" Raff deflated. "I forgot about that." Arvad stopped in the doorway and said, "Oh, they're in here." Jhoira looked up at Slimefoot, who had leaned over to examine the objects on the table. "Yes, they are." Arvad stepped in. "They seem harmless. What do you plan to do with them?" Slimefoot twisted its upper part to regard Jhoira closely. She watched it steadily for a long moment, then smiled. "I must have brought them here with Molimo's seed, so we'll have to take them back to Yavimaya when we have a chance." Slimefoot wasn't sure how to express its appreciation, so it handed her another tool. A muffled roaring sounded from above, then was abruptly cut off. Slimefoot recognized the sound of fire, and ordered its sprouts to cluster close. Raff sat up, startled. "What was that?" "That's Chandra and Jaya, up on the deck." Shanna pointed upward. "Pyromancers throwing fireballs on a wooden skyship?" Raff didn't look happy. "Is that really a good idea?" Slimefoot thought it was a terrible idea. Arvad seemed resigned. "No, not really, but they both say Chandra needs to find her true self, and that seems to involve a lot of fire." #figure(image("010_Return to Dominaria: Episode 10/06.jpg", width: 100%), caption: [Fight with Fire | Art by Yongjae Choi], supplement: none, numbering: none) "Karn is keeping an eye on them." Jhoira adjusted her eyepiece and picked up another tool. This was curious. Slimefoot ordered its sprouts to stay with Raff, and set off to get more information. As it headed for the door, Raff called out, "Hey, where are you going? You left your babies!" The sprouts had obeyed and were clustered tightly around Raff's chair. "I think you're the babysitter, Raff," Shanna commented. Slimefoot found the stairs up to the deck and climbed into the glare of sunlight. The first thing it saw was that the ship flew over water. Endless water that seemed to stretch in all directions. Slimefoot had been distantly aware that the ship had flown over water before, but seeing it was different. It walked across the deck to the rail, remembering how long that journey had seemed when it was a barely mobile sprout, fleeing for its life. The sun warmed Slimefoot's cap and pores, the heat soaking in. The sky was blue and clouds drifted across it, and in the distance Slimefoot's senses detected land. Someone beside it said, "Hello, thallid. I am Karn." Slimefoot turned and waved a greeting. Karn gestured toward the stern. "Don't approach the pyromancers; they're working and require a great deal of concentration. Also, though they haven't done it since we boarded the ship, they have been known to shout at each other very loudly." Karn leaned closer and lowered his voice. "It is annoying." Slimefoot settled down on the deck, demonstrating that it had no intention of going anywhere near the pyromancers. Karn sat down beside it, and said, "We are on our way to Urborg, to destroy the demon Belzenlok in the Stronghold of the Cabal." Slimefoot watched Karn soberly. It wasn't sure what all of that meant, but it was frightening. Karn continued, "Our success is not guaranteed, but we are a formidable group." He hesitated, then said, "I'm sorry I had to disturb the earth of Yavimaya to retrieve the Sylex. I know it was disruptive to every being living in the forest nearby. But I thought it was necessary. I need to take it to New Phyrexia and destroy their plane once and for all. I mean to end them forever." He looked closely at Slimefoot, waiting for a response. Something about the word #emph[Phyrexia] made the white star at the ship's heart pulse with—anger? Fear? Anticipation? Slimefoot wasn't sure, and its skin twitched with reaction. Karn still waited, and Slimefoot gestured with its armstalks, signaling understanding. Karn nodded, and looked out over the water. "The others think the Phyrexians are no longer a threat, and perhaps they're right." Karn's heavy brow lowered, and Slimefoot thought he seemed both sad and worried. Karn added, "But I feel the sooner I act, the better." Slimefoot stared at Karn, but he said nothing more, so Slimefoot just sat beside him and watched the endless water. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Chandra sat on the deck, thirty-seven individual fireballs floating above her head. Keeping them all contained and in motion wasn't easy, but Chandra was managing it. "How am I doing?" she asked. Pacing on the deck behind her, Jaya said, "If you need to ask, you must not be doing very well." Chandra didn't let any of the balls slip. Whatever Jaya thought about her temper, she had too much sense to lose control on a wooden skyship. And there were things she needed to know. "Why did you change your mind about helping me? Is it because of what I did for Multani?" "Partly." Jaya moved around to face her. "It was the first indication I'd ever seen that you were capable of concentrating on something for any length of time." Chandra kept her attention on the fireballs, and not one wobbled. She grinned. "I know what you're doing. You're being mean to test me." Jaya snorted. "I'm being honest to test you, kid." Chandra had the feeling that wasn't a joke. "Was I really that bad?" Jaya sighed and paced away again. "Not so much. I've seen worse. Stubborn, impatient, like talking to stone walls, no idea what they want—" Chandra didn't remember it that way, though she was willing to admit she had been terrible at listening to <NAME>. She thought about how she would have felt in Jaya's place. #emph[I would probably have gotten into a fight with me and taught myself a painful lesson.] It was a little daunting, how much self-control it seemed a powerful pyromancer needed. "Hey, I wasn't that bad. I kind of know what I want. Sort of, sometimes." "You know what you #emph[think] you want," Jaya corrected. "Just like I did." She paced away. "I thought I wanted my freedom. It took me a long time to realize what I really wanted was to help a bunch of monks guide young pyromancers. Even stubborn ones like you." Chandra grinned. "Is that why you didn't give up on me?" Jaya sighed. "Let's say I don't like unfinished business." She shrugged a little. "You don't know yourself yet, so you don't think things through. The way you helped Multani showed me that you just might have some idea of how to get in touch with your true self." She looked down at Chandra again, her face serious. "If you know what you really want, you don't make mistakes." #figure(image("010_Return to Dominaria: Episode 10/07.jpg", width: 100%), caption: [Deadlock Trap | Art by <NAME>], supplement: none, numbering: none) Chandra let the words sink in, thinking about what she thought she wanted, the mistakes she had made. How she really felt. One of the fireballs on the far end flared a little and Chandra steadied it. "My friend Nissa left us when we first got here. She didn't trust Liliana, and didn't think we should kill Belzenlok, and . . . I know she needed to get back to her own plane, after everything that happened there. But it just felt really . . . " Jaya watched her. "Like she abandoned you." "Yeah, and I guess that's partly why I got so upset," Chandra admitted. "And yelled at you when I thought you were <NAME>, and really yelled at you when I found out who you were." Chandra knew it sounded like she was making an excuse. She was done with excuses. "I know that doesn't make how I acted any better. But I'm over it now, and I'm ready to burn Belzenlok and the Cabal right off this plane. That's what I want." "Hmm," Jaya said. Chandra risked a look up at her and saw that Jaya's gaze was on the horizon. A dark smudge marked the blue sky there, like a cloud. Like the ash cloud over a volcano. Chandra's eyes narrowed. They were coming up on Urborg. Jaya glanced down at her and said, "You're going to get your chance to prove that, kid." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Slimefoot could smell smoke on the sea wind, and the distant scent of rot and burning. Its skin shivered, and it went back to the stairs and climbed down to find its sprouts. It was time to go back to the safety of the engine compartment and the white star's light. For now.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/footnote-list.typ
typst
Apache License 2.0
// Test that footnotes in lists do not produce extraneous page breaks. The list // layout itself does not currently react to the footnotes layout, weakening the // "footnote and its entry are on the same page" invariant somewhat, but at // least there shouldn't be extra page breaks. --- #set page(height: 100pt) #block(height: 50pt, width: 100%, fill: aqua) - #footnote[1] - #footnote[2]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.3.0/ucd/block-11FB0.typ
typst
Apache License 2.0
#let data = ( ("LISU LETTER YHA", "Lo", 0, none), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/example/0.1.0/util/math.typ
typst
Apache License 2.0
#let add(x, y) = x + y #let sub(x, y) = x - y #let mul(x, y) = x * y #let div(x, y) = x / y
https://github.com/Its-Alex/resume
https://raw.githubusercontent.com/Its-Alex/resume/master/lib/components/title.typ
typst
MIT License
#let customTitle( name ) = [ #block( above: 2em, )[ #grid( inset: (x: 0pt, y: 0pt), columns: (100%), gutter: 6pt, { text(fill: rgb("BCBABF"), weight: 600)[#name] }, { line(stroke: (1pt + rgb("BCBABF")), length: 70%) } ) ] ]
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit2/properties.typ
typst
== Propiedades en Kotlin - Las propiedades en Kotlin son esencialmente variables que son miembros de una clase. - Son equivalentes a los campos combinados con sus métodos getter y setter en otros lenguajes de programación como Java. - Kotlin genera automáticamente getters para las propiedades inmutables y getters y setters para las propiedades mutables. === Ejemplo de Propiedad con Getter y Setter Personalizados ```kotlin class GettersAndSetters { var name: String = "John" get() { // Getter personalizado return field } set(value) { // Setter personalizado field = value } } ``` - `field` se refiere al valor almacenado de la propiedad. === Propiedad con Getter como Expresión ```kotlin class GettersAndSetters { var name: String = "John" get() = field // Getter como expresión set(value) { field = value } } ``` === Propiedad con Getters y Setters por Defecto ```kotlin class GettersAndSetters { var name: String = "John" } ``` - Este código es equivalente a tener getters y setters por defecto. === Propiedad que Calcula su Valor ```kotlin class GettersAndSetters { val now: String get() = Clock.System .now() .toString() } ``` - Esta propiedad no almacena un valor, sino que calcula un valor cada vez que se accede a ella. === Propiedad con Setter Privado ```kotlin class GettersAndSetters(age: Int) { var age: Int = age private set // Setter privado } ``` - Podemos restringir la visibilidad del método set. === Propiedad con Backing Field ```kotlin class GettersAndSetters(private var _age: Int) { val age: Int get() = _age } ``` - Utilizando un backing field, podemos lograr lo mismo que con un setter privado. Aquí tienes una versión mejorada y más explicativa del código sobre interfaces con getters y setters en Kotlin: === Interfaces con Getters y Setters Personalizados En Kotlin, las interfaces pueden incluir propiedades con getters y setters personalizados, lo que permite añadir lógica adicional al acceder o modificar dichas propiedades. A continuación se presenta un ejemplo de una interfaz con getters y setters personalizados. ```kotlin interface InterfaceWithGettersAndSetters { val name: String get() { println("Getting name") return "InterfaceWithGettersAndSetters" } var age: Int get() { println("Getting age") return 0 } set(value) { println("Setting age") } } ``` En este ejemplo, la interfaz `InterfaceWithGettersAndSetters` define dos propiedades: `name` y `age`. El getter de `name` imprime un mensaje y devuelve una cadena, mientras que el getter y el setter de `age` imprimen mensajes al acceder o modificar el valor de la propiedad. Este enfoque es útil para agregar lógica adicional, como validaciones o registros, al trabajar con propiedades. La clase `ClassWithGettersAndSetters` implementa esta interfaz y proporciona su propia lógica para los getters y setters. Además, utiliza la palabra clave `super` para invocar los getters y setters de la interfaz. ```kotlin class ClassWithGettersAndSetters : InterfaceWithGettersAndSetters { override val name: String get() { super.name return "ClassWithGettersAndSetters" } override var age: Int = 0 get() { super.age return field } set(value) { super.age = value field = value } } ``` En la clase `ClassWithGettersAndSetters`, el getter de `name` llama al getter de la interfaz y luego devuelve un valor diferente. El getter y el setter de `age` llaman a los métodos correspondientes de la interfaz antes de acceder o modificar el valor del campo respaldado (`field`). Este enfoque permite realizar validaciones o cualquier otra lógica adicional antes de completar la operación.
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/tests/codly/test.typ
typst
The Unlicense
#import "/tests/preamble.typ": * #import springer-spaniel.codly #show: springer-spaniel.template( title: [Towards Swifter Interstellar Mail Delivery], authors: ( ( name: [<NAME>], institute: "Primary Logistics Departmen", address: "Delivery Institute, Berlin, Germany", email: "<EMAIL>" ), ( name: "<NAME>", institute: "Communications Group", address: "Space Institute, Florence, Italy", email: "<EMAIL>" ), ( name: "<NAME>", institute: "Missing Letters Task Force", address: "Mail Institute, Budapest, Hungary", email: "<EMAIL>" ) ), abstract: none, ) #codly.codly( languages: ( rust: (name: "Rust", icon: [], color: rgb("#CE412B")), python: (name: "Python", icon: [], color: rgb("#3572A5")), typ: (name: "Typst", icon: [], color: rgb("#3572A5")), typc: (name: "Typst", icon: [], color: rgb("#3572A5")), ) ) #lorem(10) ```rust pub fn main() { println!("Hello, world!"); } ``` #lorem(20) ```python def fibonaci(n): if n <= 1: return n else: return(fibonaci(n-1) + fibonaci(n-2)) ``` #pagebreak() ```typ #codly.codly(languages: ( rust: (name: "Rust", icon: [], color: rgb("#CE412B")), python: (name: "Python", icon: [], color: rgb("#3572A5")), typst: (name: "Typst", icon: [], color: rgb("#3572A5")), )) ``` ```typc codly.codly(languages: ( rust: (name: "Rust", icon: [], color: rgb("#CE412B")), python: (name: "Python", icon: [], color: rgb("#3572A5")), typst: (name: "Typst", icon: [], color: rgb("#3572A5")), )) ```
https://github.com/Lulliter/cv_typst
https://raw.githubusercontent.com/Lulliter/cv_typst/master/README.md
markdown
# CV My CV (in ENG and ITA) made with quarto & `typstcv` pckg. ## What is `typst`? [`typst`](https://github.com/typst/typst) is a new markup-based typesetting system that is designed to be as powerful as `LaTeX` while being much easier to learn and use. ![Source: [<NAME>'s blog post](https://nrennie.rbind.io/blog/pdf-quarto/making-pdf-with-quarto-typst-latex/)](images/typst.png){width="339"} It can be installed on macOS with ``` bash # shell brew install typst ``` ### How do `typst` and `Quarto` interact? Check it out [here](https://quarto.org/docs/output-formats/typst.html) With the latest 1.4 release of Quarto, you can now use `typst` as an output format! ``` bash # shell quarto --version # 1.4.550 ``` ### How to use `typst` as a format? ``` yaml # YAML --- title: "Hello Typst!" format: typst --- ``` ### How to use `typstcv` (specifically) as a format? [`typstcv`](https://kazuyanagimoto.com/typstcv/) provides helper functions for rendering a CV like [this](kazuyanagimoto/quarto-awesomecv-typst). This can be installed with: ``` r # R install.packages("typstcv", repos = "https://kazuyanagimoto.r-universe.dev") ``` Basically it is a `*.qmd` file that has format... ``` yaml # YAML --- format: awesomecv-typst: font-paths: ["PATH_TO_FONT"] --- ``` ...and is rendered into a `*.pdf` file. - it allows fontawesome icons - it allows SVG icons - it basically helps with a `resume_entry()` function that makes it easier to write a CV. - in my case, all the CV info are `*.csv` files stored in a `data/` folder, and then called with `readr::read_csv()`. - the final, rendered, `cv*.pdf` files are saved in the `docs/` folder - hopefully, with `renv.lock` in the mix, this won't break too soon 🤞🏻 Under the hood, the extension `awesomecv-typst` has 2 key files: + `_extensions/kazuyanagimoto/awesomecv/typst-template.typ` \~ the core template file. It defines the styling of the document. + `_extensions/kazuyanagimoto/awesomecv/typst-show.typ` \~ a file that calls the template. It maps Pandoc metadata to template function arguments. . # Acknowledgments I adapted the example kindly provided by [<NAME>](https://kazuyanagimoto.com/) 👏🏻, who is the creator of the `typstcv` [package](https://kazuyanagimoto.com/typstcv/).
https://github.com/topdeoo/Course-Slides
https://raw.githubusercontent.com/topdeoo/Course-Slides/master/Seminar/2024-09-08/main.typ
typst
#import "../../theme/iTalk.typ": * #import "@preview/algo:0.3.3": algo, i, d, comment, code // TODO fill all "TODO" with your information #show: nenu-theme.with( short-title: "MWCP", short-date: "240911", short-author: "Virgil" ) #let argmax = math.op("arg max", limits: true) #let argmin = math.op("arg min", limits: true) #title-slide( title: text("A Semi-Exact Algorithm for Quickly Computing a Maximum Weight Clique in Large Sparse Graphs", size: 0.8em), authors: ( name: "凌典", email: "<EMAIL>" ), logo: image("../template/fig/nenu-logo-title.png", width: 30%), institution: "Northeast Normal University", date: "2024-09-11" ) #slide( title: "Defination", session: "Problem" )[ 给定一个点加权图 $G=<V, E, W>$ 期望找到一个团 $C$,使得 $sum_(v in C) w(v)$ 最大,其中,团 $C$ 是 $G$ 的一个完全子图。 ] #slide( title: "Framework", session: "Algorithm" )[ #only(1)[ 算法通过两个子算法交叉运行,如@algo1[算法] 所示 #set text(size: 20pt) #figure( algo( title: "FastWClq", parameters: ($G$, $"cutoff"$), strong-keywords: true, row-gutter: 15pt )[ while $"elapsed time" < "cutoff"$#i\ while $w(C) lt w(C^*)$ do#i\ $C arrow.l "FindClique"(G)$#d\ $C^* arrow.l C$\ $G arrow.l "ReduceGraph"(G, w(C^*))$\ if $G eq emptyset.rev$ then#i\ return $C^*$ #comment[最优解] #d\ return $C^*$ ] )<algo1> ] #only(2)[ #set text(size: 20pt) #grid( columns: 1, row-gutter: .5em, rows: (1.8fr, .6fr), algo( title: "FastWClq", parameters: ($G$, $"cutoff"$), strong-keywords: true, row-gutter: 10pt )[ while $"elapsed time" < "cutoff"$#i\ while $w(C) lt w(C^*)$ do#i\ $C arrow.l "FindClique"(G)$#d\ $C^* arrow.l C$\ $G arrow.l "ReduceGraph"(G, w(C^*))$\ if $G eq emptyset.rev$ then#i\ return $C^*$ #comment[最优解] #d\ return $C^*$ ], text(size: 22pt)[ 其中,规约图的算法本质上是去除了一些 #pin(5) 不可能在最优解中 #pin(6) 的顶点,因此,当图被规约完(也就是不存在能被规约的顶点了),我们就找到了最优解 这就是为什么算法被称为半精确 ] ) #pinit-highlight(5, 6) ] ] #slide( title: "FindClique", session: "Algorithm" )[ #only(1)[ 我们首先规定几个记号: - $"StartSet"$:初始的顶点集合,表示从哪个点开始构造团,最开始时为 $V$ - $"CandSet" = sect.big_(v in C)N(v)$:候选集,由当前团中所有顶点的的公共邻居组成 我们还需要规定 $v$ 的有效邻居 $u$ 为 ${u | u in N(v) sect "CandSet"}$ ] #only(2)[ 整体的算法如@algo2[算法] 所示 #set text(size: 17pt) #figure( algo( title: "FindClique", parameters: ($G$, $"StartSet"$), strong-keywords: true, row-gutter: 10pt )[ if $"StartSet" eq emptyset.rev$ then#i\ $"StartSet" arrow.l V$\ $t arrow.l t gt "MAX_BMS" ? "MIN_BMS" : 2 times t$#d\ $u^* arrow.l "random"("StartSet")$\ while $"CandSet" eq.not emptyset.rev$ do#i\ $v arrow.l "ChooseSolutionVertex"("CandSet", t)$\ if $w(C) + w(v) + w(N(v) sect "CandSet") lt w(C^*)$ then#i\ break #comment[剪枝] #d\ $C arrow.l C union {v}$\ $"CandSet" arrow.l "CandSet" \\ {v} sect N(v)$#d\ if $w(C) gt.eq w(C^*)$ then#i\ $C arrow.l "ImproveClique"(C)$#d\ ] )<algo2> ] #only(3)[ 我们通过动态 `BMS`(`Best from Multiple Selection`) 策略来进行选点,`BMS` 是一种概率启发式策略,通过多次采样,最后选择采样中表现最好的。 因此,在介绍策略之前,我们首先需要定义打分函数,用于评判顶点的好坏 ] #only((4, 5, 6))[ #only(4)[ 我们定义贡献值为 $"benfit"(v) = w(C_f) - w(C)$,其中,$C_f$ 是最终由 $C union {v}$ 得到的团。然而,我们无法直接计算 $"benfit"(v)$,因为 $C_f$ 是未知的。 ] 因此,我们在这里使用上下界的方法来逼近 $"benfit"(v)$ #only((5, 6))[ 1. 当 $v$ 被加入到 $C$ 中后,权重增长的一个显然的下界为 $w(v)$ 2. 当 $v$ 被加入后,最好的可能是 $v$ 的所有有效邻居都被加入到 $C$ 中,也就是说 $C arrow.l C union {v} union (N(v) sect "CandSet")$,这个时候,我们得到了上界为 $w(v) + w(N(v) sect "CandSet")$ #only(6)[ 于是,我们通过上下界的平均#footnote[这里的 $2$ 可以被替换成其他数值,可以认为是一个可调参数]来作为顶点的分数: $ hat(b) = w(v) + w(N(v) sect "CandSet") / 2 $ ] ] ] #only((7, 8))[ #only(7)[ 有了打分函数后,`BMS` 选择顶点的算法如@algo3[算法] 所示: #set text(size: 18pt) #figure( algo( title: "ChooseSolutionVertex", parameters: ($"CandSet"$, $t$), strong-keywords: true, row-gutter: 15pt )[ if $|"CandSet"| lt t$ then#i\ return $argmax_(hat(b)(v)) "CandSet"$#d\ $v^* arrow.l "random(CandSet)"$\ for $i arrow.l 1$ to $t - 1$ do #i\ $v arrow.l "random(CandSet)"$\ if $hat(b)(v) gt hat(b)(v^*)$ then#i\ $v^* arrow.l v$#d#d\ return $v^*$ ] )<algo3> ] #only(8)[ #set text(size: 18pt) #algo( title: "ChooseSolutionVertex", parameters: ($"CandSet"$, $t$), strong-keywords: true, row-gutter: 15pt )[ if $|"CandSet"| lt t$ then#i\ return $argmax_(hat(b)(v)) "CandSet"$#d\ $v^* arrow.l "random(CandSet)"$\ for $i arrow.l 1$ to $t - 1$ do #i\ $v arrow.l "random(CandSet)"$\ if $hat(b)(v) gt hat(b)(v^*)$ then#i\ $v^* arrow.l v$#d#d\ return $v^*$ ] 我们可以通过控制 $t$ 的大小来控制贪心的程度 而称为动态的原因就是因为在运行的过程中,每当 $"StartSet"$ 变空后,$t$ 的大小会动态改变 ] ] ] #slide( title: "Improving the Clique", session: "Algorithm" )[ #only(1)[ #set text(size: 18pt) #algo( title: "FindClique", parameters: ($G$, $"StartSet"$), strong-keywords: true, row-gutter: 10pt )[ if $"StartSet" eq emptyset.rev$ then#i\ $"StartSet" arrow.l V$\ $t arrow.l t gt "MAX_BMS" ? "MIN_BMS" : 2 times t$#d\ $u^* arrow.l "random"("StartSet")$\ while $"CandSet" eq.not emptyset.rev$ do#i\ $v arrow.l "ChooseSolutionVertex"("CandSet", t)$\ if $w(C) + w(v) + w(N(v) sect "CandSet") lt w(C^*)$ then#i\ break #comment[剪枝] #d\ $C arrow.l C union {v}$\ $"CandSet" arrow.l "CandSet" \\ {v} sect N(v)$#d\ if $w(C) gt.eq w(C^*)$ then#i\ #pin(1)$C arrow.l "ImproveClique"(C)$#pin(2)#d\ #pinit-highlight(1, 2) ] ] #only(2)[ 我们的做法是:$forall v in C$,我们尝试移除 $v$,于是,$"CandSet"$ 变为 $N(v) sect sect.big_(u in C\\{v})N(u)$ 我们尝试检查,是否存在一个 $v^prime in "CandSet"$,使得 $C \\ {v} union {v^prime}$ 优于 $C$,是的话更新解,否则保持 $C$ ] ] #slide( title: "Reduction", session: "Algorithm" )[ 如果我们能通过精确的方法(分支限界)来规避掉一些绝不可能出现在最优解的顶点,那么就能够加快求解的速度,这里我们通过一个简单的上界方法进行限界。 ] #slide( title: "Upper Bound", session: "Algorithm" )[ #only((1, 2, 3))[ 给定一个点加权图 $G=<V, E, W>$,对于一个顶点 $v in V$,假设 $"UB"(v)$ 表示 #pin(1) 任意一个包含顶点 $v$ 的团 $C$ 的上界 #pin(2) 显然,上界一定会满足以下性质 $"UB"(v) gt.eq max{w(C) | "C is a clique of " G, v in C}$ #pinit-highlight(1, 2) ] #only((2, 3))[ 于是,我们可以通过这个规则,来去除一些不满足这个性质的顶点,也就是不在 #pin(3)最优解中的顶点#pin(4) #pinit-highlight(3, 4) ] #only(3)[ 给定一个团 $C$,我们通过下面三种方法来计算其上界 ] #only((4, 5))[ 对于任意一个包含了顶点 $v$ 的团 $C$,我们都有 $"UB"_0(v) = w(N[v])$#footnote[$N[v]$ 表示顶点$v$ 的领域闭集,也就是 ${u | <u, v> in E} union {v}$] ] #only(5)[ 由于 $C$ 是一个完全图,因此如果 $v in C$,那么 $forall u in N(v), u in C$,所以我们可以通过计算 $N[v]$ 的权重来得到 $C$ 的上界#footnote[因为 $|C| lt.eq |N[v]|$]。 ] #only(6)[ 给定一个顶点 $v$,我们假设 $u^* = argmax_(u in N(v))w(u)$,那么对包含这个顶点的任意一个团 $C$,存在两种情况,要么包含 $u^*$,要么不包含。 那么这个团的权值可以被计算如下: $ w(C) = cases( w(N[v]) - w(u^*) " if" u^* in.not C, w(v) + w(u^*) + w(N(v) sect N(u^*)) " otherwise" ) $ 于是,$"UB"_1$ 就是 $w(C)$ 的最坏情况,也就是这两个中的较大值 ] #only(7)[ 更一般的,最大加权团问题的上界,我们可以通过图着色得出: 由于一个合法的图着色是对图 $G$ 的顶点集 $V(G)$ 一个划分 ${A_1, A_2, dots, A_k}$,每个划分都是一个独立集#footnote("独立集中的顶点两两不相邻"),于是,任意一个团最多只有一种颜色的一个顶点 ] #only((8, 9))[ 由于一个合法的图着色是对图 $G$ 的顶点集 $V(G)$ 一个划分 ${A_1, A_2, dots, A_k}$,每个划分都是一个独立集,于是,任意一个团最多只有一种颜色的一个顶点 那么,我们可以得出另一个上界: $ "UB"_c (G) = sum^k_(i=1)max_(u in A_i){w(u)} $ 也就是每个划分中最大的权值之和 我们将其与 $"UB"_2$ 联合,可以知道,任意一个包含 $v$ 的团 $C$,其权值的可能如下: ] #only(10)[ $ w(C) = cases( "UB"_c (G[N[v]\\{u^*}]) " if " u^* in.not C, w(v) + w(u^*) + "UB"_c (G[N(v) sect N(u^*)]) " otherwise" ) $ 于是,对于顶点 $v in V$,我们有: $ "UB"_2 = w(v) + max{"UB"_c (G[N(v)\\{u^*}]), w(u^*) + "UB"_c (G[N(v) sect N(u^*)])} $ 其中 $G[N(v)]$ 表示顶点集为 $N(v)$ 的 $G$ 的子图] ] #slide( title: "Reduction", session: "Algorithm" )[ 通过上述的上界,由于其计算代价不同,于是,我们的规约算法如下: #algo( title: "ReduceGraph", parameters: ($G$, $C$, $"level"$), row-gutter: 11pt )[ for $v in V$ do#i\ if $"UB"_"level" lt.eq w(C)$ then#i\ $"rmQueue" arrow.l "rmQueue" union {v}$#d#d\ while $"rmQueue" eq.not emptyset.rev$ do#i\ $u arrow.l "rmQueue.head()"$\ $"rmFrom"(G, u)$\ for $v in N(u) sect V$ do#i\ if $"UB"_"level" lt.eq w(C)$ then#i\ $"rmQueue" arrow.l "rmQueue" union {v}$#d#d\ return $G$ ] ] #slide( title: "Experiment", session: "Experiment" )[ #set align(center) #only(1)[ #image("fig/instance.png") ] #only(2)[ #image("fig/instance2.png") ] #only(3)[ #image("fig/instance2-time.png") ] #only(4)[ #image("fig/result.png") ] ]
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliEsterni/VerbaleEsterno_230223/meta.typ
typst
MIT License
#let data_incontro = "23-02-2024" #let inizio_incontro = "17:00" #let fine_incontro = "17:30" #let luogo_incontro = "Google Meet" #let company = "Sync Lab"
https://github.com/xsro/xsro.github.io
https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/Control-for-Integrator-Systems/lib/ode-dict.typ
typst
// solve ode equation with states expressed with dictionary #let ode45(func,tfinal,x0,step,record_step:0.1,force_update:())={ let t=0. //initial time let x=x0 //initial state let xout=((t,x),) let dxout=((t,func(t,x)),) let dict_biop(x,y,func)={ let x2=(:) for (key, value) in x0 { x2.insert(key,func(x.at(key),y.at(key))) } x2 } let recorded_time=0; while t < tfinal{ let k1=func(t,x) let k2=func(t+step/2,dict_biop(x,k1,(x,d)=>x+step/2*d)) let k3=func(t+step/2,dict_biop(x,k2,(x,d)=>x+step/2*d)) let k4=func(t+step,dict_biop(x,k3,(x,d)=>x+step*d)) t=t+step for (key, value) in x0 { if key in force_update{ x.at(key)=k1.at(key) } else{ x.at(key)=x.at(key)+step/6*(k1.at(key)+2*k2.at(key)+2*k3.at(key)+k4.at(key)) } } if t>recorded_time+record_step{ xout.push((t,x)) dxout.push((t,func(t,x))) recorded_time=t; } } (xout,dxout) } #let get_signal(data,key)={ let out=((data.at(0).at(0),data.at(0).at(1).at(key)),) for kv in data{ out.push((kv.at(0),kv.at(1).at(key))) } out } #let x0 = ( x1:0, x2: 2, ) #let (xout,dxout)=ode45((t,x)=>(x1:0,x2:-x.x2,s:1),10,x0,0.1) #xout.at(-1) #dxout.at(-1)
https://github.com/julyfun/jfmfoi
https://raw.githubusercontent.com/julyfun/jfmfoi/main/总结/第二年集训经验.typ
typst
== 招生 - 队伍成立前招的学生越多越好,70 人以上都可以(像第一年开头),第一节课为试听课,必须给所有学生讲清楚集训的压力,告诉他们最终会有什么收获和益处,展示整年度大致集训安排和作业量,这样过两三节课很多意志不坚定的人就会退出,机房位置绝对够。 == 课程 - 课程量太少,确实需要多排一些课。如果学校觉得支出较大,其实我觉得时薪是次要的,如果课程量没法和其他竞赛达到同一量级,就更难出成绩。 - 可以给学生准备的培训书籍:董永建的 C++ 奥赛一本通(入门版和提高版),算法竞赛入门经典,洛谷的入门书冗余信息太多了 - 由于部分同学一进队就有信奥基础,如果从最简单题目讲起,会劝退他们。第二年尝试的分提高组和入门组教学,有效果,但我在讲其中一个组题目的时候会干扰另一组同学做题。方案一:分两个机房教学。方案二:简单题和复杂题都讲,开始复杂题可以多讲讲数学题。 == 讲题 - 我需要压缩讲题时间,给同学更多时间来实现代码。 - 可能需要校内老师协同监督作业完成情况。第二年很少有同学愿意自主完成作业,导致代码熟练度上升缓慢。
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/cancel_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Specifying cancel line angle with an absolute angle $cancel(x, angle: #0deg) + cancel(x, angle: #45deg) + cancel(x, angle: #90deg) + cancel(x, angle: #135deg)$
https://github.com/e10e3/devops
https://raw.githubusercontent.com/e10e3/devops/main/report/report.typ
typst
#let project(title: "", authors: (), date: none, body) = { // Set the document's basic properties. set document(author: authors, title: title) set page( margin: (left: 27mm, right: 35mm, top: 30mm, bottom: 30mm), numbering: "1", number-align: center, ) set text(font: "Linux Libertine", lang: "en") set heading(numbering: "1.1") // Title row. align(center)[ #block(text(weight: 700, 1.75em, title)) #v(1em, weak: true) #date ] // Author information. pad( top: 0.5em, bottom: 0.5em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center, strong(author))), ), ) // Main body. set par(justify: true) body } // The counter for questions #let q_count = counter(<question>) // Create the question layout with a grey box. It is inside a #locate // because it needs to access the current top-level heading number. #let question(wording, answer) = { locate(loc => { let heading_level = counter(heading).at(loc).at(0) let format_q_number(..nums) = {str(heading_level)+"-"+str(nums.pos().at(0))} block(fill: luma(235), inset: 10pt, radius: 6pt, width: 100%, [*Question<question> #q_count.display(format_q_number)*: _ #wording _\ #answer] ) }) } #let title1_is_displayed() = { locate(loc => { let heading_level = counter(heading).at(loc).at(0) if heading_level == 0 { }else [ #heading_level ] + " " }) } // Reset the question counter for each top-level heading #show heading.where(level: 1): it => { q_count.update(0) title1_is_displayed() it.body [\ ] } #set raw(tab-size: 4) #show link:it => {underline(stroke: 1pt + navy, offset: 1.5pt, it)} #show figure.where(kind: raw): set block(breakable: true, width: 100%) #show: project.with( title: "DevOps practical work", authors: ( "<NAME>", ), date: "November 2023", ) #outline(depth: 1) = Setting up Docker Remark: adding the regular user to the `docker` group defeats all security isolation (it makes the user a quasi-root), so all Docker commands are run with `sudo`. == Creating the database image We create a "database" directory to house the configuration for our database image. There, we create a `Dockerfile` file instructing to create an image starting from the Alpine Linux version of the Postgres base image. Environment variables are provided for the configuration. ```dockerfile FROM postgres:14.1-alpine ENV POSTGRES_DB=db \ POSTGRES_USER=usr \ POSTGRES_PASSWORD=pwd ``` The image is then build, and tagged "me/tp-database": ```sh sudo docker build -t me/tp1-database database/ ``` Once the image is build, a container can be started, binding it to the port 5000 on the host machine (Postgres' default port is 5432): ```sh sudo docker run -p 5000:5432 --name database-layer me/tp-database ``` It runs without error. Let’s remove it since we’ll want to reuse its name afterwards for a new instance: ```sh sudo docker stop database-layer sudo docker remove database-layer ``` We now create a network to isolate containers together: ```sh sudo docker network create app-network ``` ```sh sudo docker run -p 5000:5432 --name database-layer --network app-network me/tp-database ``` We use _Adminer_ as a client to connect to the database and view its contents. It too is available as a Docker image: ```sh sudo docker run -d \ -p "8090:8080" \ --net=app-network \ --name=adminer \ adminer ``` The database is currently empty --- after all, it was just created. To initialise the database, we create the files `01-CreateScheme.sql` and `02-InsertData.sql`. They are copied in the `/docker-entrypoint-initdb.d` directory of the container when it is started. The first file creates the tables "departments" and "students"; the second file inserts some data in them. #figure( ```sql CREATE TABLE public.departments ( id SERIAL PRIMARY KEY, name VARCHAR(20) NOT NULL ); CREATE TABLE public.students ( id SERIAL PRIMARY KEY, department_id INT NOT NULL REFERENCES departments (id), first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL ); ```, caption: [The `01-CreateScheme.sql` file.], ) The necessary instructions are added to the Dockerfile: ```dockerfile FROM postgres:14.1-alpine COPY 01-CreateScheme.sql /docker-entrypoint-initdb.d/ COPY 02-InsertData.sql /docker-entrypoint-initdb.d/ ENV POSTGRES_DB=db \ POSTGRES_USER=usr \ POSTGRES_PASSWORD=pwd ``` And the image is rebuilt like before. The data is indeed inserted in the database, as seen in @filled-database. #figure( image("assets/adminer-database-filled.png", width: 80%), caption: [The database with the two tables added, in Adminer.], placement: auto )<filled-database> Lastly, we add a _bind volume_ to the container for persistence: ```sh sudo docker run -p 5000:5432 -v ./database/persistence:/var/lib/postgresql/data --name database-layer --network app-network me/tp-database ``` This means the files from the container located in the directory `/var/lib/postgresql/data` are copied to the host, in the directory `database/persistence`. With the data being kept on the host’s disk, it stays between executions, even if the container is destroyed. The data created by Postgres looks like: ``` $ sudo ls database/persistence/ base pg_ident.conf pg_serial pg_tblspc postgresql.auto.conf global pg_logical pg_snapshots pg_twophase postgresql.conf pg_commit_ts pg_multixact pg_stat PG_VERSION postmaster.opts pg_dynshmem pg_notify pg_stat_tmp pg_wal pg_hba.conf pg_replslot pg_subtrans pg_xact ``` The database’s password should not be written in a Dockerfile: this file is distributed to anyone, and should not contain any sensitive information. Instead, environment variables are better provided with command line options. The cleaned-up Dockerfile is then: ```dockerfile FROM postgres:14.1-alpine COPY 01-CreateScheme.sql /docker-entrypoint-initdb.d/ COPY 02-InsertData.sql /docker-entrypoint-initdb.d/ ``` And the command to instantiate a container, including environment variables: ```sh sudo docker run --rm -d \ -p 5000:5432 \ -v ./database/persistence:/var/lib/postgresql/data \ -e POSTGRES_DB=db \ -e POSTGRES_USER=usr \ -e POSTGRES_PASSWORD=pwd \ --network app-network \ --name database-layer \ me/tp-database ``` #question[Document your database container essentials: commands and Dockerfile.][ To create an image: - Create a file named `Dockerfile`, - Use the keyword `FROM` to start from a base image: `FROM alpine:3.18`, - You can copy files from the host to the container using the `COPY` keyword. - Build an image from a Dockerfile with `sudo docker build -t <image-name> <path>`. To create containers: - The base command is `sudo docker run <image-name>`, - Specify a port mapping to expose the container to with the `-p` option, - A container can be named with the option `--name`, - The `-e` option can be used to provide environment variables. ] == Create the back-end We'll now create a Java app in the `backend/` directory. === Step 1, a dead simple program Here is a classic "hello world" Java program. #figure( ```java public class Main { public static void main(String[] args) { System.out.println("Hello World!"); } } ```, caption: [Java's _Hello World_] ) Here is a Dockerfile that can run it (notice the `java Main` command to run the class): ```dockerfile FROM amazoncorretto:17 COPY Main.class / CMD ["java", "Main"] ``` This image is built and run in a container: ```sh sudo docker build -t me/tp1-backend backend/ ``` ```sh sudo docker run -d \ --name backend-layer \ me/tp1-backend ``` It works, printing "Hello World!". === Simple API Let's create a more complex app. #link("https://start.spring.io/")[Spring initializr] is used to create a Spring demo. This scaffold is extracted in `backend/`. The directory now has (we kept the previous `Main.java` file): ``` $ ls backend/ Dockerfile HELP.md Main.class Main.java mvnw mvnw.cmd pom.xml src ``` We now use this multi-stage Dockerfile to compile and run the program: ```dockerfile # Build FROM maven:3.8.6-amazoncorretto-17 AS myapp-build ENV MYAPP_HOME /opt/myapp WORKDIR $MYAPP_HOME COPY pom.xml . RUN mvn dependency:go-offline COPY src ./src RUN mvn package -DskipTests # Run FROM amazoncorretto:17 ENV MYAPP_HOME /opt/myapp WORKDIR $MYAPP_HOME COPY --from=myapp-build $MYAPP_HOME/target/*.jar $MYAPP_HOME/myapp.jar ENTRYPOINT java -jar myapp.jar ``` With ` RUN mvn dependency:go-offline` after the `pom.xml` file is copied to save the dependencies between builds. Building the image with the new Dockerfile and instantiating a container is as was done before: ```sh sudo docker build -t me/tp1-backend backend/ ``` ```sh sudo docker run -d \ -p 8000:8080 \ --network app-network \ --name backend-layer \ me/tp1-backend ``` When visiting #link("http://[::]:8080?name=Émile")#footnote[IPv6 is the present, but you can replace `[::]` with `localhost` if it doesn't work.], the following response is obtained, as expected: ```json { "id":2, "content":"Hello, Émile!" } ``` #question[Why do we need a multistage build? And explain each step of this Dockerfile.][ A multistage build is a way to optimise Dockerfiles. They allow both a file to be more readable and to reduce the resulting image size. To do this, the image is first primed with a first base image, a building step is run, then a new image is started (it can have a different base). The necessary files can be copied from one step to the other. Once all steps are finished, all the images are discarded but the final one. This means the setup needed to compile and build an app is not kept in the final image, and only the executable is copied, allowing the remaining image to have a reduced size. Because each step is conscripted to its own stage, its own image, the relationship between them can be more clearly laid down. The steps: + Select `maven` as the base image (in order to build with Maven). + Create an environment variable `$MYAPP_HOME`, set to `/opt/myapp`. + Go to `/opt/myapp`. + Copy the `pom.xml` file there. + Download the dependencies offline (for Docker layer cache). + Copy full source tree to `./src`. + Compile the app. + Create a new image based `amazoncorretto` (Maven is not needed anymore once it is built). + Re-create the environment variable `$MYAPP_HOME`, set to `/opt/myapp` (its a new image), go to it. + Copy the Jar produced during the build. + Set the image's entrypoint to run the obtained Jar. ] === Full API We'll run use a more complete Java backend that provides a more complex API. Since we a right now focused on the operations more than the development, we'll use a ready-made Java application. We download it from https://github.com/takima-training/simple-api-student. The Dockerfile used previously for the Spring demo was not specific, and will function for most Maven-based Java project, including this one. This means we can reuse it.. Once built with the same name, it is run as before: ```sh sudo docker run -d \ -p 8000:8080 \ --network app-network \ --name backend-layer \ me/tp1-backend ``` But it fails, on the ground of database access. Because it is more complex, this program needs to use the database we created earlier. Reusing the same environment variables as previously for a clean setup, information in how to contact the database is added to `application.yml`: ```yaml spring: jpa: properties: hibernate: jdbc: lob: non_contextual_creation: true generate-ddl: false open-in-view: true datasource: url: jdbc:postgresql://database-layer:5432/${POSTGRES_DB} username: ${POSTGRES_USER} password: ${<PASSWORD>} driver-class-name: org.postgresql.Driver management: server: add-application-context-header: false endpoints: web: exposure: include: health,info,env,metrics,beans,configprops ``` In `jdbc:postgresql://database-layer:5432/${POSTGRES_DB}`, `database-layer` is the name of the container running the database. In a network, Docker automatically fills in the hostnames. Running a container with the application and supplying the appropriate variables looks now like: ```sh sudo docker run --rm -d \ -p 8000:8080 \ --network app-network \ -e POSTGRES_DB=db \ -e POSTGRES_USER=usr \ -e POSTGRES_PASSWORD=pwd \ --name backend-layer \ me/tp1-backend ``` == HTTP server No modern web app is complete without at least one reverse proxy. So let's add one. First, let's create a new directory for this part, `http/`. === A basic server to begin with At its core, a reverse proxy is a classic HTTP server. So let's setup one that displays an HTML docuemnt to show it works. We'll use Apache's _httpd_ for this. A Dockerfile with a basic configuration for this task looks like : ```dockerfile FROM httpd:2.4 COPY ./index.html /usr/local/apache2/htdocs/ ``` Let's build the image and run a container from it: ```sh sudo docker build -t me/tp1-http http/ ``` ```sh sudo docker run -d \ -p 8888:80 \ --name http-layer \ me/tp1-http ``` #figure( ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="color-scheme" content="light dark"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>A good HTML "Hello world"</title> <style> body{ margin: auto; max-width: 80ch; font: sans-serif; } </style> </head> <body> <h1>Hello world!</h1> </body> </html> ```, caption: [The `index.html` file used for the demo] ) Visiting http://[::]:8888 displays our HTML file. ==== A few Docker commmands `docker stats` shows for each running container some information about its resources use, like CPU fraction used or memory comsumed. `docker inspect <container>` gives detailed information about th etarget container, by default in a JSON format. `docker logs <container>` shows the standard output of the target running container. In the HTTP server’s case, this include the connexion logs. === Reverse proxy A reverse proxy is commonly used to hide or abstract a service’s architecture, in case there are many servers. To set one up, we need to configure our HTTP server to behave like one. Let’s retrieve the server’s default configuration to base ours on it. We use `docker cp`, which can copy files between containers and the host. ```sh sudo docker cp http-layer:/usr/local/apache2/conf/httpd.conf http/httpd.conf ``` The file is quite long, so not shown here. Here are the changes that were made to the configuration to turn it into a reverse proxy: ```diff --- http/httpd.conf +++ http/httpd.conf @@ -225,4 +225,14 @@ # +<VirtualHost *:80> + ProxyPreserveHost On + ProxyPass / http://backend-layer:8080/ + ProxyPassReverse / http://backend-layer:8080/ +</VirtualHost> +LoadModule proxy_module modules/mod_proxy.so +LoadModule proxy_http_module modules/mod_proxy_http.so + # # ServerAdmin: Your address, where problems with the server should be @@ -230,4 +240,5 @@ # #ServerName www.example.com:80 +ServerName localhost:80 # ``` The new configuration file must now be copied in the image to replace the default one. Since the server will redirect all requests, we don't need the HTML file anymore. ```dockerfile FROM httpd:2.4 # COPY ./index.html /usr/local/apache2/htdocs/ COPY ./httpd.conf /usr/local/apache2/conf/httpd.conf ``` After building, running a container (in the network) is done with: ```sh sudo docker run --rm -d \ -p 80:80 \ --network app-network \ --name http-layer \ me/tp1-http ``` The proxy runs on the port 80, the default port for HTTP, so we don't have to specify a port when doing requests. And now, it behaves transparently, like if we were talking directly to the back-end. == Wrapping it all with Compose Executing the Docker commands works well, but it is a bit tedious. Fortunately, Compose is here for us. With Compose, we list all the properties we want our containers to have, and they are automagically provisioned. Once we don't need them, we ask Compose to stop them, and they are removed. To have the same functionnality as we had spinning the containers up manually, we write the following `compose.yaml` file: #figure( ```yaml version: '3.7' services: backend: build: ./backend container_name: backend-layer networks: - my-network depends_on: - database env_file: .env database: build: ./database container_name: database-layer networks: - my-network volumes: - db-persitence:/var/lib/postgresql/data env_file: .env httpd: build: ./http container_name: frontend-layer ports: - "80:80" networks: - my-network depends_on: - backend networks: my-network: {} volumes: db-persitence: {} ```, caption: [Our `compose.yaml` recipe file.] ) #question[Document docker-compose most important commands.][ In symetry: `sudo docker compose up` to create the containers and `sudo docker compose down` to remove them. Then, `sudo docker compose logs` is really useful to see what happens in the containers if they are in detached mode. ] #question[Document your docker-compose file.][ The containers need to live in the same network, so to communicate with each other but be isolated from potential other containers. This is done with the `networks` key. The actual name of the container does not really matter since we only have one and it is name only used in the file. Similarly, it is better to declare a volume for the database storage, allowing to restore the state at startup and not have to recreate all entries. We create a named volume in the `volumes` key and bind it in the databse service definition. Because we hard-coded the names of the containers in the URLs of the various configurations, we need to keep the same ones here. Hence the `container_name` keys. Set the container names The database and back-end containers need some environment variables to work well. Since some are the same, an `.env` file is created to host the variables, and is provided to the containers with the `env_file` key. Because the startup order of the containers can have an impact (the proxy must be able to reach the back-end, which must access the database), we declare a dependency tree with the `depends_on` key. ] == Publishing the images I published the images as `e10e3/ops-database`, `e10e3/ops-backend`, and `e10e3/ops-frontend`#footnote[This last name will cause problems later and is changed in a following section.]. Let's use the database as an example of how it's done. First, building the image, with tag and version: ```sh sudo docker build -t e10e3/ops-database:1.0 database/ ``` Then, publishing it: ```sh sudo docker push e10e3/ops-database:1.0 ``` The result is: https://hub.docker.com/repository/docker/e10e3/ops-database/ #question[Document your publication commands and published images in DockerHub.][ To push an image to Docker Hub, you must namespace it with you Docker Hub username first. In my case, this is _e10e3_. The tag of an image is set at build time (with the `--tag` option) or with the `docker image rename` command. In order to push an image to your account, it is necessary to first log in. This is done with the command `docker login`. Once an image is created and the account information entered, the image can be sent online with the `docker push` command. ] = Using Github Actions The whole project --- with the database, back-end and proxy --- was uploaded in a Git repository at https://github.com/e10e3/devops. Let's focus on the back-end, arguably the most brittle part of our system for now: the database and the HTTP server are more complex, but we only configured them and suppose they are both more mature and more tested. The Java app --- while we didn't write it ourselves --- is quite new and it was created from the ground up (albeit using frameworks that help a bit). Thankfully, the back-end has some tests written to ensure its functionality. To run them all, we need to build the app. This is easily done in one command with Maven: ```sh sudo mvn clean verify ``` This launches two Maven targets: _clean_ will remove the temporary directories, like `target` (the build directory). _verify_ will the the application's tests#footnote[Maven has goal dependencies. This means that in order to excute the goal _verify_ (the unit tests), it will first run the unit tests (_validate_) and build the program (_compile_), between others.]. Some of the tests are more encompassing (they are called _integration tests_) and run in specialised Docker containers in order to have total control on their environment. #question[What are testcontainers?][ _Testcontainers_ is a testing library (https://testcontainers.org) that run tests on the codebase in lightweight Docker containers. In the context of Java apps, they execute JUnit tests. ] == Yamllint is your friend From now on, we'll use a tonne of YAML files. But the tools they configure will fail if the file are improperly formatted. _Yamllint_ is here to help! Running it on a file will give you a list of all malformed items, like wrong indentation. ```yaml # perhaps.yaml key: on enum: - name: Test kind: None - name: Other ``` ``` $ yamllint perhaps.yaml perhaps.yaml 1:1 warning missing document start "---" (document-start) 1:6 warning truthy value should be one of [false, true] (truthy) 4:10 error syntax error: mapping values are not allowed here (syntax) ``` YAML awaits you! == Creating a workflow Part of the DevOps philosophy is CI --- continuous integration. Because our Git repository is hosted on GitHub, let's use GitHub's own CI runner, GitHub Actions, to create a testing pipeline. We created the file `.github/workflows/main.yml` to declare a workflow that runs the integration tests: ```yaml name: CI devops 2023 on: #to begin you want to launch this job in main and develop push: branches: - main - develop pull_request: jobs: test-backend: runs-on: ubuntu-22.04 steps: #checkout your github code using actions/[email protected] (upgraded to v4) - uses: actions/checkout@v4 #do the same with another action (actions/setup-java@v3) that enable to setup jdk 17 - name: Set up JDK 17 uses: actions/setup-java@v3 with: distribution: 'temurin' java-version: '17' cache: 'maven' #finally build your app with the latest command (not forgetting the tests) - name: Build and test with Maven run: mvn -B clean verify --file backend/pom.xml ``` Note: _checkout_ was updated to v4 because the previous version were deprecated. The JDK version installed is version 17 (the tried-and-true LTS version of the last few years), from the Eclipse _temurin_ distribution. The program is build with the command `mvn -B clean verify --file backend/pom.xml`. The option `-B` is for "batch" (no colours are needed for automation), and `--file` to indicate Maven it needs to use the `pom.xml` file at the root of the backend as the job runs at the root of the repository. After a push to the remote repository, it runs with success. #question[Document your Github Actions configurations.][ The workflow reacts to two kinds of events: commit pushes on the _main_ and _develop_ branches, and all pull requests. When the workflow starts, it creates an environment on a machine running Ubuntu 22.04, and checkouts the code that awoke it. Then, it installs the Java JDK 17 and Maven. Once this is done, it runs the back-end's unit tests. ] == Automatically publish the images In the previous part we created Docker images for the project's components. The other great keyword of DevOps is CD --- continuous deployment. Using GitHub Actions, we can create a workflow that published the images to Docker Hub when code is pushed, no human action required. === Action secrets<gh-secrets> Publishing to Docker Hub implies to log in, but we don't want to have our credentials visible to anyone and their dog in clear on GitHub. Fortunately, the forge has a solution, _secrets_. We created the secrets `DOCKER_HUB_TOCKEN` and `DOCKER_HUB_USERNAME` (the names are case-insensitive). `DOCKER_HUB_TOCKEN` contains a dedicated access tocken from Docker Hub that only has read and write permission, in order to push images. === Pushing to Docker Hub To push the newly built image to Docker Hub, a new job is created in the same workflow file, called `build-and-push-docker-images`. Because we only want to publish code that works at least a bit, it only runs it the previous one (`test-backend`) finishes successfully. After checking out the code like before, the job logs in to Docker Hub using the secret credentials from #ref(<gh-secrets>) and the action `docker/login-action`. Then, it uses `docker/build-and-push` to build each image (database, backend and frontend). If the current branch is `main`, it additionally pushes the result to the Hub. == Setup SonarCloud's Quality Gate #link("https://sonarcloud.io/")[SonarCloud] is a static analyser. Its role is to scan our app and tell what part of the code can be improved, if the tests are sufficient, or if there are potential security holes. It is an online service that can be called by Maven when the app is built. Once we register our project, we are provided with a token. Because we want to call SonarCloud from our CI pipeline, we add the token to our action secrets. The `backend-tests` job can now be amended to use the following command for the tests: ```sh mvn -B clean verify sonar:sonar \ --file backend/pom.xml \ -Dsonar.token=${{ secrets.SONAR_TOKEN }} ``` Additionally, we need to add some metadata to our `pom.xml` for SonarCloud to find its kitten: ```xml <sonar.organization>e10e3</sonar.organization> <sonar.host.url>https://sonarcloud.io</sonar.host.url> <sonar.projectKey>e10e3_devops</sonar.projectKey> ``` And _voilà_! SonarCloud will now scan the code when the tests run, and can alert you when it goes south. It will even post comments to you pull requests! Important note: because GitHub Actions are defined using YAML files, it is really important to use multi-line strings if you want to split your commands on multiple lines. To do this, add a pipe (`|`) or a "greater than" (`>`) symbol after the key and start a new line. For instance: ```yaml --- key: | multi-line string! ``` == Fixing SonarCloud's alerts SonarCloud raises two types of security warnings on the default back-end code: - The first ones are for potential unauthorised cross-origin access, because the annotation `@CrossOrigin` was added to the controllers. - The second one warns about using database-linked data types as the input from endpoints. This could be exploited to overload the database. In addition, but not blocking at first, the code coverage was reported to be around 50%, where SonarCloud requires it to be above 80% for new code. Fixing the first set of warnings was easy: removing the incriminated lines was enough. Since this is a simple case with only one route (coming from the proxy), nothing important goes missing with this deletion. The second one is more involved. It is necessary to create a _data transfer object_ (DTO) that will be the API's input, and will then be transformed into the regular object. For this kind of object that hold no logic, Java 14's records are perfect. The DTO for the Student class is: ```java public record StudentDto( String firstname, String lastname, Long departmentId) { } ``` Because a new object is introduced, the function signatures change, conversion needs to be handled, new service routines are added, the tests must be adapted, etc. A little bit everywhere is needed to secure the API. And then, once the security is taken care of, SonarCloud complains about the tests. "Clean code" fails. Indeed: it detects only 20% of new code coverage. But the locally-run tests indicate 90%! This is because the test coverage is not updated, so SonarCloud cannot see it. The tool used for this is called #link("https://www.jacoco.org/jacoco/")[JaCoCo]. The `jacoco:report` goal needs to be added when the tests are run, and the option `-Pcoverage` should be given to Sonar when called through Maven. After this all, the coverage is updated and the pipeline passes. Because I was looking at the tests, I used the opportunity to add some missing tests for the original code, bringing the coverage to 97%#footnote[The coverage with these tools cannot be 100%, because some of the code cannot or has no point in begin tested individually.]. == Split pipelines Our workflow work fine, but we want to refactor it in two separate workflows. We remove the `build-and-push-docker-image` job from the previous workflow and add put it instead in its own workflow: "Push images". The other one is renamed to "Run tests" for the occasion, and doesn't change further. On the "Push images" side, we set it to be triggered by the successful termination of the tests workflow "Run tests", with the added condition that it only runs is the active branch is `main`. In the end, the behaviour is as so: If located on main, develop or a pull request → run the tests\ If located on main and previous steps is successful → push the images #figure( image("assets/split-workflows.png"), caption: [The split workflows' behaviour] ) == Automatic image version Pushing the latest version of an image is cool, but isn't it _cooler_ for our images to have numbered versions? What is needed is a system that makes so that the images that are build get automatically assigned a version number when a tag is pushed. Otherwise, they have the _main_ and _latest_ tag. This is created by splitting the workflows in three: - One workflow is a reusable one, it runs the tests on the back-end; - One executes the preceding workflow (the reusable one) when a commit is pushed on _main_ or _develop_, - The last one build and pushes the Docker images when a commit is made on _main_ or a tag is pushed. Before building, it runs the tests through the reusable workflow. The calling jobs use the line `secrets: inherit` to transmit their action secrets to the reusable workflow. Additionally, in order to factor the image push (it is three times the same thing), a matrix strategy is used for the various images we want: ```yaml strategy: matrix: include: - image: e10e3/ops-database dockerfile: ./database - image: e10e3/ops-backend dockerfile: ./backend - image: e10e3/ops-frontend dockerfile: ./http ``` The image and Dockerfile are respectively accessed with `${{ matrix.image }}` and `${{ matrix.dockerfile }}`. The images' tag are set to the correct version using the `docker/metadata-action` action. And indeed, with the workflows complete, pushing a #link("https://semver.org/")[semantic versioning] tag like `v1.1.0` pushes #link("https://hub.docker.com/repository/docker/e10e3/ops-database/tags")[an image with the same tag] on Docker Hub. #figure( image("assets/auto-version.png"), caption: [The two main workflows, and a reusable one (in yellow)] ) = Ansible Let's now deploy our app to a real server. I was assigned one, reachable with the domain name #link("emile.royer.takima.cloud"). Its only account is called _centos_ (after the distribution installed on it, CentOS#footnote[Buried by RedHat, RIP CentOS]). Since this is a distant server, the preferred method to access it is with SSH. A key pair was generated, with the public one installed already on the server. The private one, `id_rsa`, is stored on our side, in the parent directory to our project. Let's connect to our server: ```sh ssh -i ../id_rsa <EMAIL>.cloud ``` Great, it works. ``` [centos@ip-10-0-1-232 ~]$ id uid=1000(centos) gid=1000(centos) groups=1000(centos),4(adm),190(systemd-journal) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 ``` To deploy our apps on the server, we could use Docker Compose, as they are already packaged. But this means logging in the server with SSH, transferring files between hosts and running the commands manually. We'll use _Ansible_ to automate the deployment and discover how it could be done if we were operating at a larger scale. We only have one server, so it's a bit overkill, but will this stop us? Ansible is configured using a tree of files, making it play nicely with POSIX systems. It happens to only run on them anyway. == Configuring the server with Ansible In order to use Ansible with our server, we need to register it. Ansible uses its own file `/etc/ansible/hosts`. To add our server, we write its domain name in this file: ```sh sudo echo "emile.royer.takima.cloud" > /etc/ansible/hosts ``` It can then be pinged with Ansible: ```sh $ ansible all -m ping --private-key=../id_rsa -u centos emile.royer.takima.cloud | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } ``` Let's install an apache httpd server to how it works well: ```sh ansible all -m yum -a "name=httpd state=present" --private-key=../id_rsa -u centos --become ``` Now create and HTML file to display and start the service: ```sh ansible all -m shell -a 'echo "<html><h1>Hello World</h1></html>" >> /var/www/html/index.html' --private-key=../id_rsa -u centos --become ansible all -m service -a "name=httpd state=started" --private-key=../id_rsa -u centos --become ``` Visiting http://emile.royer.takima.cloud diplays "Hello World" as expected. An inventory is created in order not to have to give the path to the private key at each command: #figure( ```yaml all: vars: ansible_user: centos ansible_ssh_private_key_file: ~/schol/devops/id_rsa children: prod: hosts: emile.royer.takima.cloud ```, caption: [The inventory file at `ansible/inventories/setup.yaml`] ) Using the inventory works just as well: ```sh $ ansible all -i ansible/inventories/setup.yaml -m ping emile.royer.takima.cloud | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } ``` It is also possible to display information about the target systems: ```sh $ ansible all -i ansible/inventories/setup.yaml -m setup -a "filter=ansible_distribution*" emile.royer.takima.cloud | SUCCESS => { "ansible_facts": { "ansible_distribution": "CentOS", "ansible_distribution_file_parsed": true, "ansible_distribution_file_path": "/etc/redhat-release", "ansible_distribution_file_variety": "RedHat", "ansible_distribution_major_version": "7", "ansible_distribution_release": "Core", "ansible_distribution_version": "7.9", "discovered_interpreter_python": "/usr/bin/python" }, "changed": false } ``` #question[Document your inventory and base commands][ An Ansible inventory is grouped in categories. Here, only one group of hosts is created: the default _all_. For each group, variables can be created. Here, it is the user and the private key file path. Groups can have children (subgroups): _prod_ is implicitly created as a subgroup of _all_. It has one host: our server. For now, we only used the base `ansible(1)` command. Its one required argument is \<pattern>, indicating which groups to target. Some useful options are: / `-m`: The Ansible module to run. / `-a`: The arguments to give to the module. / `-i`: The inventory to use. / `--private-key`: Which private key should be used. ] == Creating a playbook Just like with Docker, it is tedious to run so many commands, especially when there are many packages to set up on the hosts. But just like with Docker, there is a solution: playbooks. Let's create a basic one: `ansible/playbook.yaml` ```yaml - hosts: all gather_facts: false become: true tasks: - name: Test connection ping: ``` Execute the playbook on our server: ``` ansible-playbook-i ansible/inventories/setup.yaml ansible/playbook.yaml ``` The ping is successful. Because our apps are containerised, it'll be needed to install Docker on the server. A playbook to do this looks like: `docker-playbook.yaml` ```yaml --- - hosts: all gather_facts: false become: true # Install Docker tasks: - name: Install device-mapper-persistent-data yum: name: device-mapper-persistent-data state: latest - name: Install lvm2 yum: name: lvm2 state: latest - name: add repo docker command: cmd: sudo yum-config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo - name: Install Docker yum: name: docker-ce state: present - name: Make sure Docker is running service: name=docker state=started tags: docker ``` Ansible has the notion of _roles_, where reusable tasks can be defined. A role can be added to any number of playbooks, and its tasks are then added to them, without having to all the tasks by hand. `ansible-galaxy` helps creating roles: ```sh ansible-galaxy init roles/docker ``` The _docker_ role is outfitted with the tasks that were in the playbook to install Docker. `roles/docker/tasks/main.yml` ```yaml - name: Install device-mapper-persistent-data yum: name: device-mapper-persistent-data state: latest - name: Install lvm2 yum: name: lvm2 state: latest - name: add repo docker command: cmd: sudo yum-config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo - name: Install Docker yum: name: docker-ce state: present - name: Make sure Docker is running service: name=docker state=started tags: docker ``` And the _docker_ role is added to the cleaned-up playbook: ```yaml --- - hosts: all gather_facts: false become: true tasks: - name: Test connection ping: roles: - docker ``` #question[Document your playbook][ The playbook is now really simple --- only a bit more complex that the basic one at the start. It declares to apply to all the hosts, and to execute the commands as root (it says "become root"). The tasks from its roles are added to the list, meaning all the tasks there were before to install Docker. Finally, as the cherry on the cake, a _ping_ is added, just to be sure. ] == Deploying our app Let's now create a number of roles, one for each step need to have our API running online. The roles we created are `create_network`, `create_volume`, `install_docker`, `launch_app`, `launch_database`, `launch_proxy`, and `setup-env-file`. / Install Docker: This is the one called _docker_ previously. It ensures Docker is installed in the environment. / Create network: This role creates a named network for all our container to be in, so they are isolated and can communicate with each other. / Create volume: This role creates a named volume in order to persist our database's entries, even between restarts. / Launch database: This one starts the database, with its environment variables, the volume and the network. / Launch app: This role starts the back-end with the environment variables necessary to connect to the database and is attached to the network. / Launch proxy: This role starts the HTTP proxy server, includes it in the network and maps its port so that the hosts' port 80 redirects to it. / Setup env file: This transient role is a dependency of the database and app roles. It is not called directly in our playbook. Its role is to copy our `.env` file to the server (in `/root/ansible-env`), in order for the other riles to access its content. The task each contains is an equivalent of what the `compose.yaml` file what doing for Docker Compose. Here is the `task/main.yml` file for _launch\_database_: ```yaml --- - name: Create the database container community.docker.docker_container: name: database-layer image: e10e3/ops-database pull: true volumes: - db_storage:/var/lib/postgresql/data networks: - name: app_network env-files: - /root/ansible-env ``` All of the roles are called in the playbook. `playbook.yaml` ```yaml --- - hosts: all gather_facts: false become: true tasks: - name: Test connection ping: roles: - install_docker - create_network - create_volume - launch_database - launch_app - launch_proxy ``` In order to efficiently use Docker container and have a syntax that resembles Compose, a few Ansible modules are used. `community.docker.docker_container` allows to start containers from images and parameter them, `community.docker.docker_network` can create networks and `community.docker.docker_volume` will create storage volumes. #question[Document your `docker_container` tasks configuration.][ A handful of options of `docker_container` are used to configure the containers: / name: Gives a name to the container. Useful to make a reference to it in an program's configuration. / image: The image to use for the container. It is pulled from Docker Hub by default. / pull: Whether to systematically fetch the image, even if it appears not to have changed. Because the images used are all with the _latest_ tag, this option is useful to force Ansible to use the latest version of the _latest_ tag. / networks: A list of networks to connect the container to. / env: A mapping of environment variables to create in the container. Useful for configuration. / volumes: A list for volumes to map the container's directories to. Only the database has a use for this option in this case. / ports: Port binding for the container. In this case, the proxy's port 80 is mapped to the server's port 80. ] == Ansible Vault Environment variables to are listed in the roles' tasks, but some variable's value should stay a secret, whereas roles should be published. A secure way to handle secrets is needed. Ansible itself supports variables, that are distinct from environment variables. These variables can be declared in the playbook, tasks files, and also in external files. They allow to parameterise the configuration: a value is no longer hard-written, but references a variable declared in YAML. The project's Ansible configuration is put in `ansible/env.yaml`. ```yaml --- database: container_name: "database-layer" postgres_name: "db" postgres_username: "usr" postgres_password: "pwd" backend: container_name: "backend-layer" ``` Ansible has another mechanism to protect secret: the vault. The Ansible Vault encrypts file and variables in place, and decrypts them when e.g. a playbook is used. The files can only be decrypted if the correct pass is given (the same one that was used to encrypt it). Under the hood, it uses AES-256 to secure the data. In this situation, the `en.yaml` file was encrypted with `ansible-vault encrypt env.yaml`, and a vault pass. Encrypted files can still be referenced in playbooks: ```yaml --- - hosts: all gather_facts: false become: true vars_files: - env.yaml tasks: - name: Test connection ping: roles: - install_docker - create_network - create_volume - launch_database - launch_app - launch_proxy ``` ... and the decrypted value can be transferred to role (here with the database): ```yaml --- - name: Create the database container community.docker.docker_container: name: "{{ database.container_name }}" image: e10e3/ops-database volumes: - db_storage:/var/lib/postgresql/data networks: - name: app_network env: POSTGRES_DB: "{{ database.postgres_name }}" POSTGRES_USER: "{{ database.postgres_username }}" POSTGRES_PASSWORD: "{{ database.postgres_password }}" ``` A playbook that uses an encrypted file can be launched with: ``` ansible-playbook -i inventories/setup.yaml playbook.yaml --ask-vault-pass ``` to ask for the secret pass. = A new front-end As a further step, a front-end is introduced in the project. In our case, since the reverse proxy was called "front-end", this means we need to rename it everywhere. Here goes v2. The front-end is found here: https://github.com/takima-training/devops-front. It is a Vue app, meaning a Node.js image is the base for the Dockerfile. But once Vue compiled the code, JavaScript is no longer needed on the server side, and the packaged `*.js` files can be distributed by a regular web server. The reverse proxy now has a use: it will distribute the traffic between the back- and the front-end depending on the requested URL. The proxy server needs to be reconfigured to handle the different redirections. #figure( ```tcl <VirtualHost *:80> ProxyPreserveHost On ProxyPass "/api/" "http://${BACKEND_CONTAINER_NAME}:8080/" ProxyPassReverse "/api/" "http://${BACKEND_CONTAINER_NAME}:8080/" ProxyPass "/" "http://${FRONTEND_CONTAINER_NAME}:80/" ProxyPassReverse "/" "http://${FRONTEND_CONTAINER_NAME}:80/" </VirtualHost> ```, caption: [How the reverse proxy is configured in the HTTP server] ) The redirection is made as so: - the traffic looking for `/api/*` will go to the back-end, - the traffic looking for all other paths will go to the front-end. The following architecture diagram shows the relation between the servers: #figure( image("assets/architecture.png"), caption: [The app's architecture] ) Since the front-end makes itself use of the API, it needs to make calls to `/api/`, routing though the reverse proxy. In order to deploy the front-end with the rest of the app, a service was added to the Compose file, and a corresponding new role was created in Ansible. They both use the same principles as were seen before. == More parametrisation Because the proxy needs to access the back-end ans front-end servers' container name, the occasion was used to further the parametrisation of the configuration. Now, in addition of the database name, user and password, the machine's hostname and the containers' name can be indicated directly in the configuration#footnote[The hostname is not decided by our app, so it cannot be changed on our side (the value is still used), but all other variables are commands on what to set.]. == Changing environment variables at build time Vue is configured at build time. It can be parametered with variables, but it only uses variables from a defined set of files, depending on what part of the lifecycle is wanted. Thankfully these variables can be overridden with environment variables from the host. But remember: it needs to happen at build time. In particular, it is needed to indicate what the base URL to access the API is. Without it, the front-end cannot function. We know it is `/api/`, but for _which_ host name? (Local use and server use require different host names.) To set this up, an environment variable is declared directly in the Dockerfile; but its value is not static: ```dockerfile ARG API_URL ENV VUE_APP_API_URL ${API_URL} ``` This allows to change the value of `VUE_APP_API_URL` with the `-build-arg` option. Compose supports this option, so the local use-case is covered. For the general use-case, it is needed to go through GitHub Actions: this is where the images are built. A workflow variable was created, and the build argument uses this variable to change the API URL. ```yaml build-args: | API_URL=${{ vars.TARGET_HOSTNAME }}/api ``` = Conclusion A lot of things would have been faster if I had hard-written the configuration, and not had to use environment variables to set it. But at the end, I have the satisfaction of a well-tended project. All in all we did created Docker containers, created a CI/CD workflow for them, fixed linting errors, and deployed the project on a server with Ansible. Success!
https://github.com/0x1B05/english
https://raw.githubusercontent.com/0x1B05/english/main/grammar/content/虚拟语气.typ
typst
#import "../template.typ": * = 虚拟语气 == 介绍 === 如何彻底掌握虚拟语气 - 理解虚拟语气的本质:为什么虚拟?能不能不虚拟?虚拟 or 不虚拟,意思有何区别? - 对虚拟语气的语法规则必须烂熟于心(口语比书面语更为常见) - 真实条件句 VS 非真实条件句,要认真对比 - 记住:虚拟语气都有言外之意 - If I can help you, I will definitely do so. - If I could help you, I would definitely do so.(帮不上) - 把本课程的讲义烂熟于心,你就啥都明白了 === 语法规则 #tablem[ |虚拟的对象|主句的谓语形式|IF从句的谓语形式| | - | - | - | |将来|【would/could/might/should + do】|【were to do】/ 【should/could do】/ 【did】| |现在|【would/could/might/should + do】|【did】 / 【were】| |过去|【would/could/might/should + have done】|【had done】 / 【had been】| ] #tip("Tip")[ 时态倒退一格。 ] #tablem[ |虚拟的对象|主句的谓语形式|IF从句的谓语形式| | - | - | - | |were 型虚拟条件句|If Michael had known about this, he wouldn’t have married Susan.|表示说话人的一种*主观假设*,句子本身包含一种 【隐含的否定】。| |be 型虚拟句|It is important that we marry the one we love.|不包含假设,也不包含【隐含的否定】,但句子传 达某种*主观意愿*(愿望、建议、命令、请求等)。| |wish虚拟句||| |时态交叉虚拟句||| |其他乱七八糟的虚拟句||| ] #tip("Tip")[ 分为两大类,假设和主观意愿。 ] == 狗血的故事 - 男一:Michael,酒吧舞大学大四学生,身高 185 cm,人长得贼帅,但家境贫寒。 - 女一:Sally,酒吧舞大学大四学生,家境同样贫寒,跟 Michael 是同班同学,俩人是恋人关系。 - 女二:Susan,酒吧舞大学大四学生,白富美,是 Michael 和 Sally 的同班同学,已经喜欢 Michael 四年了。 - 男二:Jimmy,酒吧舞大学大四学生,高帅富,和上述三位是同班同学,已经当 Sally 的舔狗四年了。 == 针对过去、现在、将来的虚拟【表示假设】 明天就是酒吧舞大学的招聘会了,很多大企业都会来招聘。傍晚的时候,Michael 和 Sally 在校园漫步… - Sally: “ Jobs are so hard to come by these days. _If I can't find one and don't have any income, will you still love me?_” #tip("Tip")[ If I *couldn't* find one and *didn't* have any income, *would* you still love me? 这样改成虚拟就说明很容易找到工作。 ] - Michael: “ Of course! Don't worry, babe. I've always had good grades. I'm sure some big company will *snatch me up* tomorrow! ” - Sally: “ _And how will that help? We still can't afford a house._ The prices are ridiculous. ” - Michael: “Housing prices have crashed in many cities, and Evergrande is down. *_If we could wait, we’d be able to buy a house for peanuts soon._* ”(等不起) - Sally: “ Tomorrow is the job fair. Any companies you've got your eye on?” - Michael: “ *_If Apple wanted me, I would consider it._* ”(苹果公司不太可能要他) - Sally: “ You‘re just boasting. ” - Michael: “ Just kidding! _But if Tancent offers me a job, I might just take it._ ”(Tancent很可能要,但是Michael不太想去) #tip("Tip")[ 过去式的情态动词本质上就是虚拟语气,例如Could you help me? could可能性更小,所以表达起来更加委婉。 ] #example("Example")[ Sally: - “ If I *can‘t* find one and don’t have any income, will you still love me? ” - “ If I *couldn’t* find one and didn’t have any income, would you still love me? ” - “ If I *shouldn’t* find one and didn’t have any income, could you still love me? ” - “ If I *were not to* find one and didn’t have any income, might you still love me? ” - “ If I *didn’t* find one and didn’t have any income, should you still love me? ” 区别:情态动词本身含义的区别就是句子含义的区别。 ] #example("Example")[ Michael: - “ If we could wait, we’d be able to buy a house for peanuts soon. ” - “ If we can wait, we’ll be able to buy a house for peanuts soon.” - “ If we should wait, we might be able to buy a house for peanuts soon.” - “ If we were to wait, we should be able to buy a house for peanuts soon.” - “ If we waited, we’d be able to buy a house for peanuts soon.” ] #example("Example")[ Michael: - “ If Apple wanted me, I would consider it.” - “ But if Tancent offers me a job, I might just take it. ” 辨析: - “ But if Tancent offers me a job, I might just take it. ”( Tancent 大概率会给我offer,但我不太想去。) - “ But if Tancent offers me a job, I may just take it. ”( Tancent 大概率会给我offer,我也有点想去。) - “ But if Tancent offered me a job, I might just take it. ”( Tancent 大概率压根就不会给我offer…) #tip("Tip")[ 可以混搭 ] ] 第二天,Michael 和 Sally 都参加了学校的招聘会,傍晚的时候,两人又在校园里散步… - Sally: “ Which companies did you apply to? ” - Michael: “ Quite a few. I also dropped my resume at Apple, but I'm not *holding my breath*. ” 这时,Michael 的手机响了,他接起电话,片刻后,他的表情变得十分惊讶。 - Michael: “ The HR department at Apple called. They've hired me! I start tomorrow, and they've offered me a senior manager position, with a million-dollar salary! ” - Sally: “ What?! A million bucks? _We can buy a house right away!_ ” - Michael: “ Yeah, it's unbelievable. But a million only covers the down payment. *_If we had five million, we could buy a house outright. Then, you wouldn't have to work. I'd take care of you._* ” - Sally: “ I'm capable of working, thank you very much. I don't even dare to dream of a company like Apple. *_If Tancent would hire me, I'd be over the moon._* ” #example("Example")[ Sally: - “We can buy a house right away! ” - “We can buy a house right away (if you have a job with a million-dollar salary).” - “We will buy a house right away (if you have a job with a million-dollar salary).” - “We would/could buy a house right away (if you had a job with a million-dollar salary).” ] - Michael: “ Yeah, it's unbelievable. But a million only covers the down payment. *_If we had five million, we could buy a house outright. Then, you wouldn't have to work. I'd take care of you._* ” - Sally: “ I'm capable of working, thank you very much. I don't even dare to dream of a company like Apple. *_If Tancent would hire me, I'd be over the moon._* ” #tablem[ |虚拟的对象| 从句| 主句| |-|-|-| |未来|If we had five million,|we could buy a house outright.| |未来|If we should have five million,|we would buy a house outright.| |未来|If we could have five million,|we might buy a house outright.| |未来|If we were to have five million,|we should buy a house outright.| |现在|If we had five million,|we could buy a house outright.| |现在|If we had five million,|we would buy a house outright.| |现在|If we had five million,|e might buy a house outright.| |现在|If we had five million,|e should buy a house outright.| ] 第二天,Michael 来 Apple 公司报道,意外地发现他居然有一间独立的办公室,他居然刚入职就成了一个百人项目的负责人,最离谱的是,公司居然给 他配了一个女秘书,这个女秘书还不是别人,正是他的同班同学 Susan!看着一身OL制服的 Susan 帮自己冲咖啡,直接给 Michael 整不会了… - Susan: “ Why are you looking so *glum*? Am I not doing well as your secretary? ” - Michael: “ Turns out Apple is your family's business. I knew you were well-off, but I never imagined your dad was the richest guy in the country. ” - Susan: “ What's the point of being the wealthiest if you still don't like me? ” - Michael: “ *Forced love never works out.* ” - Susan: “ *_It might work out if you gave it a try._* ”(有点委屈,不管Susan怎么做,Michael还是不喜欢她) - Michael: “ Don't do this, Susan. I never imagined it would be like this. *_If I had known Apple was your family's company, if I had known you were behind all this, I wouldn't have taken this job in the first place._* I'm going to HR to resign. ”(过去的虚拟) - Susan: “ So just because my family has money, you don't like me? *_If my dad was a regular farmer like Sally's, would you fancy me?_* ” - Michael: “ *_Even if Apple wasn't in the mix, I still wouldn't be into you, Susan._* We're just not meant to be. ” #tip("Tip")[ 口语里面都使用was,书面语必须用were。 ] 听到 Michael 绝情的话语,Susan 泫然欲泣,这个时候,Michael 的电话响了,Michael 一看是自己老爸打来的,于是接起了电话… - Michael‘s dad: “ Son, your mom got into a car accident and she's in the ICU. It's costing us a hundred grand a day. I've already sold the house, but we can only keep going for a week. Son, _if we don’t come up with the damn money, your mom won’t make it!_ ” - Michael: “ Dad, don't worry. I'll figure it out. ” Susan 走过来,抓住 Michael 的手,另外一只手掏出一张银行卡放在 Michael 的手里。 - Susan: “ There's a billion in the account, it's what my dad set aside for my wedding. Take it for now, the password is your birthday. ” - Michael: “ Susan, I... ” (Michael 第一次发现 Susan 竟然如此美丽…) - Susan: “ Just take it! I know you don't love me, you love Sally. I know _even with this billion, you still won't love me_, but Auntie's illness is urgent! ”(语气更委屈) Michael 张了张嘴,却什么都说不出口,他想把手里的银行卡还给 Susan,但这张密码设置成了自己生日的银行卡此刻重若千钧... Michael 心系母亲的安危,只好开着 Susan 的布加迪赶往医院,Michael 在医院交了五百万住院费之后,母亲的病情马上就稳定 下来了。在医院忙活了两天之后,Michael 开着布加迪回了学校,校园里此时下起了雨… - Sally: “ Where did you get this car? ” - Michael: “ It's from work. ” - Sally: “ Does the company really provide employees with such outrageous sports cars? ” - Michael: “ Yeah, our company's got great *perks*. ” - Sally: “ You're lying! This is Susan's car! *_If you loved me, you wouldn’t have lied to me._* Are you planning to dump me and marry Susan, huh? ”(从句现在,主句过去) - Michael: “ Enough! *_Even if I had told you the truth, would you believe me? If I had known you were this kind of woman, I..._* ”(从句过去,主句将来) - Sally: “ You! *_Had I known you were like this, I would have taken Tancent's offer today._* I only turned it down because Tancent is Jimmy's family business.” - Michael: “ Oh, so you've found someone else during all this? I must be blind! ” - Sally: (Tears in eyes) “ Michael, you jerk! You'll regret this! ” 看着 Sally 在雨中跑远,Michael 心痛万分,他想追上去留住 Sally,但身边的布加迪却像磁石一样让他动弹不得,Michael 仰天长啸,然后 duang 地一声把拳头砸在了布加迪的引擎盖上。 傍晚八点,Susan 和 Jimmy 在一家顶级餐厅共进晚餐。 - Susan: “ Things went well, but we didn't leave any loose ends, right? ” - Jimmy: “ Don't worry, I gave that hit-and-run driver five million as hush money. *_If he dared to rat me out, I'll make him disappear!_* ”(他不太可能把Jimmy供出来,但是如果供出来了,Jimmy会让他消失) - Susan: “ Good. I'll transfer the five million to you later. ” - Jimmy: “ No need. This isn't all for you anyway. *_Hadn’t we orchestrated this little drama, there wouldn’t be any chance for Sally to fall into my lap._* ” - Susan: “ I still don't get what you see in her. Sure, she's pretty, but there are plenty of pretty girls out there. What's so special about her? ” - Jimmy: “ Because Sally always makes me ponder one thing: *_If my family wasn't so loaded, could I still have a chance with her?_* ” - Susan: “ Oh, spare me! So mawkish! ” - Jimmy: “ You have the nerve to say that to me? I gave you advice long ago. *_I should've sealed the deal with Michael from the get-go if I were you. If you two had gotten together earlier, I would've had Sally wrapped around my finger ages ago, believe me._* ” - Susan: “ Spare me! If Michael was so easy to hook, I wouldn't have liked him either. You're no different. *_If Sally was the type to fall for you at the snap of your fingers, would you still be hung up on her?_* ” - Jimmy: “ Fair point. ” FIVE YEARS LATER… 五年后,Michael 已经成了 Apple 公司的 CEO,他和 Susan 的婚姻还算美满,只不过,这么多年了,俩人却没生下个一男半女。Michael 十分渴望拥有自己 的孩子,于是经常去幼儿园周围“云”别人家的孩子,这一天,Michael 恰巧遇到了 Sally 来接自己的儿子 Max,见到 Max 的那一刻,Michael 立马就傻了… - Michael: (pointing to Max) “ Sal, he… ” - Sally: “ He what? Max, my son! ” - Michael: “ His dad is Jimmy? ” - Sally: “ Of course! *_If it wasn’t Jimmy, could it be you?_* ” - Michael: “ I don't believe it! This must be my son! He looks so much like me! ” - Sally: “ Lots of people look alike! *If he was your son*, how come he's five years old and hasn't seen you as a dad? ” - Michael: “ Now today he’s seeing me! Son, come here to Dad! ” - Max: “ Mom, I'm scared. This weirdo is so scary. ” - Sally: “ Don't be scared, son. This uncle became like this by accident. *Hadn’t it been for a seductive woman and a Bugatti, he wouldn't be like this today.* ” - Max: “ Mom, what's a Bugatti? ” - Sally: “ It's a very, very expensive car.” - Max: “ Can I drive a Bugatti when I grow up? ” - Sally: “ _If you earn the money yourself, you can buy any expensive car you want._ *But if it was given by some seductive woman, you absolutely should not accept it. Got it?* ” - Max: “ Got it! ” 翌日,某顶级私人医院亲子鉴定中心。Michael、Sally、Susan,还有 Jimmy,四个人一言不发地盯着桌子上的鉴定报告,这时,Susan 突然起身,抓起报告单撕成两半,狠狠摔在Michael的脸上,然后夺门而出,Jimmy 深深看了一眼 Sally,冷笑一声,随后拂袖而去。 - Susan: “ *_If I had known it would turn out like this..._* ” - Jimmy: “ Damn it! *_If I had known earlier, I wouldn’t have been raising his son for five years!_* ” - Susan: “ It's *karma*! People from our class aren't meant to have dealings with those poor bastards! ” - Jimmy: “ Makes sense! Hey, Susan, what do you think about us? ” - Susan: “ You mean me and you? Are you serious? ” - Jimmy: “ Yeah, why not? *_If we were to tie the knot, we would both have our freedom,_* if you know what I mean. *_Getting married should benefit both our families’ businesses. Plus, no more fees for WeeChat Tip on Apple's channels! We’d be one big happy family!_* ” - Susan: “ You love me? ” - Jimmy: “ Not really, but you look gorgeous. I’m tired of this love game now. You look good, and that’s enough.” - Susan: “ Have our freedom? ” - Jimmy: “ Have our freedom! ” - Susan: “ Alright! Let’s get married! ” 几天后,Michael、Sally、Susan,还有 Jimmy,这四个曾经的大学同学一起去民政局办理了离婚手续,Michael 净身出户,Susan 也没能带走 Tancent 的任何资产,之后,四个人又一起办理了结婚手续,之后,Michael 和 Sally 在城中村租了一间小屋,开启了新的生活。 - Michael: “ I'm sorry, darling, it's all my fault. *_If I hadn’t made such unforgivable mistake back then, you wouldn't have suffered so much, Max wouldn't have spent all these years not knowing who his real dad is, and you two wouldn’t be reduced to this today._* ” - Sally: “ Don't say that, honey, at least we still have our son, right? ” - Michael: “ Yeah, at least we still have our son, though we live in the slums now. *_You know what, even if somebody gave me a billion dollars, I wouldn't give up our life here. Even if Apple and Tancent were handed over to me, I wouldn't abandon you and Max for them._* ” - Sally: “Darling, if I had to choose again, I would still divorce Jimmy and choose you. I only love you! Max, come call Daddy!” - Max: “ I don't want to live here! I want a Bugatti! ” == 倒装结构虚拟句【表示假设】 从句倒装的规则(书面语):省略 if,然后条件句中的 were、had、could、should 放在主语之前。 - If we could wait, we’d be able to buy a house for peanuts soon. - Could we wait, we’d be able to buy a house for peanuts soon. - If Apple wanted me, I would consider it. [无法倒装] - If we had five million, we could buy a house outright. [无法倒装] #tip("Tip")[ 针对did的形式无法倒装,要有助动词才可以。 ] - If Tancent would hire me, I'd be over the moon. - Would Tancent hire me, I'd be over the moon. - If I had known Apple was your family's company, if I had known you were behind all this, I wouldn't have taken this job in the first place. - Had I known Apple was your family's company, had I known you were behind all this, I wouldn't have taken this job in the first place. - If my dad were a regular farmer like Sally's, would you fancy me?(书面正式) - Were my dad a regular farmer like Sally's, would you fancy me? - If my dad was a regular farmer like Sally's, would you fancy me?(口语非正式) - Even if Apple wasn't in the mix, I still wouldn't be into you, Susan. - Even if Apple weren’t in the mix, I still wouldn‘t be into you, Susan. - Even were Apple not in the mix, I still wouldn‘t be into you, Susan. [罕用,不推荐] - Even weren’t Apple in the mix, I still wouldn‘t be into you, Susan. [罕用,不推荐] #tip("Tip")[ even if/本身包含否定的,不推荐倒装。 ] - If you loved me, you wouldn’t have lied to me. [无法倒装] - Even if I had told you the truth, would you believe me? If I had known you were this kind of woman, I... - Even had I told you the truth, would you believe me? Had I known you were this kind of woman, I... [罕用,不推荐] - Had I known you were like this, I would have taken Tancent's offer today. - If he dared to rat me out, I'll make him disappear! [无法倒装] - Hadn’t we orchestrated this little drama, there wouldn’t be any chance for Sally to fall into my lap. - If my family wasn't so loaded, could I still have a chance with her? - If my family weren’t so loaded, could I still have a chance with her? - Were my family not so loaded, could I still have a chance with her? [罕用,不推荐] - Weren’t my family so loaded, could I still have a chance with her? [罕用,不推荐] - I should've sealed the deal with Michael from the get-go *if I were you. If you two had gotten together earlier*, I would've had Sally wrapped around my finger ages ago, believe me. - *Were I you*, I should've sealed the deal with Michael from the get-go. *Had you two gotten together earlier*, I would've had Sally wrapped around my finger ages ago, believe me. - If Michael was so easy to hook, I wouldn't have liked him either. If Sally was the type to fall for you at the snap of your fingers, would you still be hung up on her? - If Michael were so easy to hook, I wouldn't have liked him either. If Sally were the type to fall for you at the snap of your fingers, would you still be hung up on her? - Were Michael so easy to hook, I wouldn't have liked him either. Were Sally the type to fall for you at the snap of your fingers, would you still be hung up on her? - If it wasn’t Jimmy, could it be you? - If it weren’t Jimmy, could it be you? - Were it not Jimmy, could it be you? [罕用,不推荐] - Weren’t it Jimmy, could it be you? [罕用,不推荐] - If he was your son, how come he's five years old and hasn't seen you as a dad? - If he were your son, how come he's five years old and hasn't seen you as a dad? - Were he your son, how come he's five years old and hasn't seen you as a dad? - Hadn’t it been for a seductive woman and a Bugatti, he wouldn't be like this today. - But if it was given by some seductive woman, you absolutely should not accept it. - But if it were given by some seductive woman, you absolutely should not accept it. - But were it given by some seductive woman, you absolutely should not accept it. - If I had known it would turn out like this...If I had known earlier, I wouldn’t have been raising his son for five years! - Had I known it would turn out like this...Had I known earlier, I wouldn’t have been raising his son for five years! - If we were to tie the knot, we would both have our freedom, if you know what I mean. Getting married should benefit both our families’ businesses. Plus, no more fees for WeChat Tip on Apple's channels! We’d be one big happy family! - Were we to tie the knot, we would both have our freedom, if you know what I mean. Getting married should benefit both our families’ businesses. Plus, no more fees for WeChat Tip on Apple's channels! We’d be one big happy family! - If I hadn’t made such unforgivable mistake back then, you wouldn't have suffered so much, Max wouldn't have spent all these years not knowing who his real dad is, and you two wouldn’t be reduced to this today. - Had I not made such unforgivable mistake back then, you wouldn't have suffered so much, Max wouldn't have spent all these years not knowing who his real dad is, and you two wouldn’t be reduced to this today. [罕用,不推荐] - Hadn’t I made such unforgivable mistake back then, you wouldn't have suffered so much, Max wouldn't have spent all these years not knowing who his real dad is, and you two wouldn’t be reduced to this today. [罕用,不推荐] - You know what, even if somebody gave me a billion dollars, I wouldn't give up our life here. Even if Apple and Tancent were handed over to me, I wouldn't abandon you and Max for them. [无法倒装] - Darling, if I had to choose again, I would still divorce Jimmy and choose you. [无法倒装] == 交叉时态虚拟句 === 交叉时态虚拟句①:从句过去虚拟 + 主句现在虚拟 Max长大后,因为家境贫寒,自己又不努力,最终成为了一名loser,他一无学历,二无能力,父母又都是普通人,万般无奈之下,儿时梦想着长大后驾驶布加迪的Max,最终加入了某团,成为了一名光荣的外卖骑手… 这一天,Max正在跟街边等着抢单的同事吹牛... - Max: “ You've heard of Jimmy, the boss of Tancent, right? *_If my mom hadn't divorced him back then, I'd be cruising in a Bugatti by now._* ” - Delivery Guy: “ You're just talking big man. *_If your mom had been the ex-wife of the Tancent boss, my mom would be the grandmother of the Microsoft CEO!_* ” - Max: “ Don't believe me, huh? Let me tell you, my mom's side is nothing special. It's my dad who's impressive. *_If my dad hadn't divorced the Apple boss back then, I could be the heir to the richest company in the world!_* ” - Delivery Guy: “ I'm real impressed! Why don't you just buy the whole world while you're at it? ” - Max: “ That's just how the world is, nobody believes the truth. ” === 交叉时态虚拟句②:从句现在虚拟 + 主句过去虚拟 Max坐在小电驴上捧着手机打游戏,玩了一上午,一个外卖单子都没接,刚送完几单回来的同事见状有些看不下去了… - Delivery Guy: “ *_If I were you, I would've taken those orders just now._* So what if the floor is a bit high? What's the big deal about climbing some stairs? You can't be lazy! ” - Max: “ *_If you were me, you would've committed suicide a long time ago._* Nobody in this world understands me. ” - Delivery Guy: “ Come on, buddy, be realistic! You're just a delivery guy. Do you really think your mom was the ex-wife of the Tancent boss? ” - Max: “ That's right! And my dad was the ex-husband of the Apple boss! ” - Delivery Guy: “ Man, I really can't believe you. *_If I were your parent, I would've regretted having a son like you._* ” - Max: “ *_If you were my parent, you definitely wouldn't have divorced a billionaire and chosen to live in slums!_* ” === 交叉时态虚拟句③:从句现在虚拟 + 主句将来虚拟 或许是同事的话点醒了Max,Max在某团的APP上抢了一单后就送货去了。一个小时候后,Max哭着回来了… - Delivery Guy: “ What's up, bro? Why the tears? ” - Max: “ It's over! Everything's over! ” - Delivery Guy: “ Stop crying and get back to work. I just delivered a few orders myself and just got back. You better get moving too. _If you keep slacking off, you won't even have food for tomorrow._ ” - Max: “ *_Even if I took a hundred more orders, I still wouldn't have food for tomorrow._* Just now, on my way back from delivering, I scratched a BMW, just a bit of paint came off, and I ended up paying two hundred bucks!” - Delivery Guy: “ Well, you're lucky. You met someone kind. *_If I were the owner of that BMW, I'd have demanded a grand from you, and you'd be broke for next month's food!_* ” === 交叉时态虚拟句④:从句过去虚拟 + 主句将来虚拟 送了一天的外卖,不但没赚到钱,还倒赔了两百,精神崩溃的 Max 再也无心工作,于是回到了城中村父母租住的小屋。到家后, Max 和父母发生了激烈的争吵… - Max: “ It's all your fault! *_If you hadn't divorced the boss of Tancent back then, I wouldn't be in this mess today!_* And you! *_If you hadn't broken up with the boss of Apple, I wouldn't wake up to be a delivery guy tomorrow!_* ” - Michael: “ All you care about is money! Do you think money is everything? *_If I hadn't broken up with the boss of Apple back then, could I have the love I have now? And my life would be totally meaningless!_* You just don't understand the feelings of parents at all. I'll beat you! ” - Sally: “ Stop it! Darling! Max is still young, he doesn't know any better, and we're also at fault. We were too kind back then. *_If we had shared the wealth of Tancent or Apple, we wouldn't have to worry about our future._* ” - Michael: “ Yeah, but none of that matters anymore. At least we're happy now, aren't we? *_If we had chosen money back then, we wouldn't have the happy life we have now, nor could we expect a better future!_* ” - Sally: “ Darling, you're so kind! ” #tip("Tip")[ 非常灵活,爱咋咋。 ] == 无条件虚拟句 无条件虚拟句:不再使用if从句的形式,而改用非谓语动词、介词短语、或其他形式来表达类似的虚拟意义。 - If I had another chance, I would still divorce Susan to marry Sally. - Given another chance, I would still divorce Susan to marry Sally. - Any wise man would still divorce Susan to marry Sally. - A man would be blind not to have divorced Susan to marry Sally. - Not to divorce Susan to marry Sally would be the silliest thing to do. - To have divorced Susan earlier, I would have married Sally sooner for a better life. - I would have spent the rest of my life with Susan, only (that) I fell in love with Sally again. - It might have been better for Michael to have married Sally in the first place. - Any man who has married Susan would have divorced her to marry Sally. - But for Sally, Michael would have spent another twenty years of meaningless life with Susan. - I would have spent my rest of life with Susan, but/except I fell in love with Sally again. - Without Sally’s love, I would have lived a meaningless life. - Myself, I also would have divorced Susan to marry Sally. - Michael would have done anything to divorce Susan to marry Sally. == 含蓄条件句 含蓄条件(结果)句:完全省略if从句,也不存在任何非条件成分,虚拟的意味完全依靠上下文或者依靠读者自行脑补。 含蓄条件句: - Michael: “#strike[Yeah, it's unbelievable. But a million only covers the down payment. If we had five million, we could buy a house outright.] Then, you wouldn't have to work. I'd take care of you. ” 含蓄结果句: - Michael: “ Yeah, it‘s unbelievable. But a million only covers the down payment. If only we had five million! #strike[we could buy a house outright. Then, you wouldn't have to work. I'd take care of you.] ” - Susan: “ If I had known it would turn out like this... ” - Max: “ If only my dad hadn’t divorced the boss of Apple! ” == 名词性从句中的虚拟语气【表示意愿】 如果名词性从句中含有特定的、表示强烈主观意志的标志性单词,则从句的谓语动词必须使用原形形式(英式英语使用 should + 动词原形), 此类表示强烈主观意志的标志性单词大多表示 愿望、建议、命令、请求等 ,这类标志词包括但不限于: ask, advise, command, beg, request, suggest, demand, decide, deserve, desire, insist, order, prefer, propose, urge。(意愿就是,说话人希望某事儿发生,但是这件事还没有发生,他认为应该发生,发生了就是好事儿) - Michael *insisted* that this marriage *be ended* as soon as possible. - Jimmy *demanded* that Sally *not be allowed* to take any property because she was at fault for getting pregnant with Michael’s child. - Sally *suggested* that they *start* a new life in the slums given their dire financial situation. - Max *asked* that his father *divorce* Sally to remarry Susan because he was fed up with delivery work. 一定要区别相关词汇是否表达了真实的、强烈的主观意志 - Sally *suggested* that they start a new life in the slums given their dire financial situation.(虚拟语气) - Sally‘s unusual behavior *suggested* that she had been pregnant with Michael’s child for quite some time.(这里suggest不是虚拟语气,而是"表明"的意思,可以换成show,indicate) - Michael *insisted* that this marriage be ended as soon as possible.(虚拟语气) - Susan *insisted* that it was Michael who was at fault.(这里是陈述事实) #tip("Tip")[ 不要拘泥于形式,主要看是不是在表达主观意愿。 ] === 识别标志词变体 标志词:ask, advise, command, beg, request, suggest, demand, decide, deserve, desire, insist, order, prefer, propose, urge… 要点:① 熟悉上述标志词;② 判断上述标志词是否具备虚拟意义;③ 标志词的各种变体,要具备分辨能力。 #example("Example")[ - The attorney *advised* that Sally take no property because she was at fault for getting pregnant with Michael's child. - It is *advisable* that Sally take no property because she was at fault for getting pregnant with Michael's child. - The attorney *thought* it advisable that Sally take no property because she was at fault for getting pregnant with Michael's child. - What is *advisable* is that Sally take no property because she was at fault for getting pregnant with Michael's child. - Sally was *advised* that she take no property because she was at fault for getting pregnant with Michael's child. - The *advice* that Sally take no property because she was at fault for getting pregnant with his child makes a lot of sense. ] ==== It is + adj + that 结构的虚拟语气 标志词:important, necessary, advisable, appropriate, desirable,essential, imperative, normal, surprising, strange, vital 等。 - It is important that Jimmy make sure Sally doesn’t take away any property. - It is strange that Michael should divorce Susan, the boss of Apple. [表示“竟然”的should需要保留] - It is … that … - It is natural that people divorce someone they don’t love.(主观意愿) - It is natural that Michael has divorced Susan.(陈述事实) - It is surprising that Jimmy should marry Susan. [表示“竟然”的should需要保留] - It is surprising that Jimmy has married Susan. === It is (about/high) time + that 从句的用法: - It’s time (that) you divorced Susan. (你应该跟 Susan 离婚。) - It’s about time (that) you divorced Susan. (你也该跟 Susan 离婚了吧。) - It’s high time (that) you divorced Susan. (你可是早就该跟 Susan 离婚了。) #tip("Tip")[ - It is about time -> 语气弱 - It is high time -> 语气强 ] - It’s time (that) we were going.(咱该走了。) - It’s about time (that) we were going.(咱差不多该走了吧。) - It’s high time (that) we were going.(咱早该走了。) 这几个句式不要混淆: - It is time (that) we left. (我们该走了。) - It is the first time (that) we’ve been here.(这是我们第一次来这里。) - It was the first time (that) we’d been here. (当时是我们第一次来这里) - It will be the first time (that) we’ve been here. (这将是我们第一次来这里。) == 非主流形式虚拟句 === 非主流形式虚拟句【表示意愿】 #tip("Tip")[ 直接背,没啥规则。 ] ==== 超大型主观意念降临虚拟句: - Long live The People’s Republic of China! - Heaven help us! - Manners be hanged! (该死的规矩!) - Damn you! - God bless you! - The devil take it! - Be ours a happy meeting! - Thief be hanged! - Would that I were young again! - Would that my grandfather were alive to see me married! === 非主流形式虚拟句【表示假设】 ==== as if, as though,以及 if only / would that 引导的虚拟句: - It seems as if you were going to divorce Susan.(概率低) - It seems as if you are going to divorce Susan.(概率大) - Michael is really upset. It seems as though he’s going to divorce Susan. - It seems as though Michael were going to divorce Susan, but he's just putting on an act. - If only my dad had never divorced Apple’s boss ! - If only I were still the son of a wealthy family ! - Would that my dad had never divorced Apple’s boss ! - Would that I were still the son of a wealthy family ! ==== for feat that, in order that, so that, lest, in case 等引导的虚拟语气: - Sally dares not tell Michael that he is actually Max's biological parent *for fear that* he would disrupt their current stable life. - Sally dares not tell Michael that he is actually Max's biological parent *lest* he might disrupt their current stable life. - *In order that* Michael would not disrupt their current stable life, Sally dares not tell him about Max’s parentage. - Sally dares not tell Michael that he is actually Max's biological parent *so that* he wouldn’t disrupt their current stable life. - Sally dares not tell Michael that he is actually Max's biological parent *in case* he would disrupt their current stable life. 注意鉴别 - I’ll bring an ambarella in case it rains. - I’ll bring an umbrella in case it rained.(概率更小) - I’ll bring an umbrella in case it might/should/would rain.(更更小) #tip("Tip")[ 虚拟语气非常自由。觉得可能性小那就可以虚拟,觉得可能性大就可以不虚拟。 ] ==== I wish + 宾语从句: 针对过去的虚拟 - I wish (that) my dad had never divorced Apple’s boss. - I wish (that) my mom had never broken up with Tancent’s boss. 针对现在的虚拟 - I wish (that) my mom were still the wife of the boss of Tancent. - I wish (that) my dad were still the CEO of Apple. 针对将来的虚拟 - I wish (that) I could have a Bugatti someday. - I wish (that) my dad would get back together with Apple’s boss. wish 和 hope 用法的不同: 相同点①:都可以接不定式 - I wish/hope to marry you soon. 相同点②:都可以for sth - I wish/hope for the best. 不同点①:wish sb to do sth 成立,但 hope sb to do sth 不成立 - I wish my dad to get back together with Apple’s boss. 不同点②:wish 可以接双宾语,但 hope 不可以 - I wish you a better life. 不同点②:wish 后接that从句使用虚拟语气,而 hope 后接that从句使用陈述语气 - I wish (that) I could marry you. - I hope (that) I can marry you. == 其他类型的虚拟语气: - I *would rather* (that) it were winter. - My dad is a billionaire. I*’d rather* (that) he weren’t. - I *would prefer* (that) you had been available. - *Granted* that he had been drunk, there is no excuse for him to have done that. - You*’d better* finish your work as soon as possible. - You*’d better* finish your work as soon as possible. - *Suppose* that there were no gravitational force, things would not fall to the ground when dropped. - I couldn’t finish this work *unless* I were allowed another ten days. - _Be it so late_, I have to finish this work.(形式记住就行了) - _Be that as it may_, Michael is determined to divorce Susan. - Whether it be sunny or raining, he takes a walk outside everyday.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/lint/markup_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Warning: 1-3 no text within underscores // Hint: 1-3 using multiple consecutive underscores (e.g. __) has no additional effect // Warning: 13-15 no text within underscores // Hint: 13-15 using multiple consecutive underscores (e.g. __) has no additional effect __not italic__
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/022%20-%20Commander%20(2015%20Edition)/002_Family%20Values.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Family Values", set_name: "Commander (2015 Edition)", story_date: datetime(day: 11, month: 11, year: 2015), author: "<NAME>", doc ) #emph[<NAME> is a formidable force in the courts of the city-plane of Ravnica, but she wants more. With her extraordinary command of Ravnica's law-magic and the help of a Boros soldier, she is finally ready to make a bid for power. But she still has to contend with her treacherous, domineering ancestor Karlov, who hasn't let being dead slow him down . . .] #figure(image("002_Family Values/01.png", width: 100%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) <NAME> had spent another full day being yelled at by the dead. This time, the Orzhov Ghost Council had failed to see why condemning a debtor to five hundred years of servitude was problematic in the eyes of the law. Teysa had argued till her throat stung. The Grand Envoy of the Orzhov collapsed into her favorite chair, cane leaning at hand. One of the Grugg brothers had tidied her desk (bless him) and had left a pile of papers to go through. <NAME> carefully sorted and scanned her old mail before she tossed it into the crackling fireplace of her study. An update on tunneling progress from Tajic. A demand of compliance from the Obzedat. A weeks-old confirmation of appointment with the Living Guildpact. Teysa grinned. What a fun meeting that was. #emph["Would you agree that the content of the Safety Provisions and Regulations, specifically Article 14, exists and is a valid law?] #emph["Yes? <NAME>, I'm extremely busy and need to go," Jace asserted, shoving a grappling hook and traveler's coat into a bag, frantic sweat on his brow.] #emph["Would you also agree that stealing is illegal?"] #emph["Yes, please leave."] After asking him to confirm no less than twenty minor laws and legal requirements, it was worth getting kicked to the curb by the Living Guildpact himself. That meeting was weeks ago, yet still Teysa reveled in his adorable irritation. She tossed the stack of letters into the fire and stoked it with the tip of her cane. She ran through a mental checklist as she began reading in the comfort of her study. The fire flickered at her feet, warming the skin of her long-numb legs. #figure(image("002_Family Values/02.jpg", width: 100%), caption: [Teysa, Envoy of Ghosts | Art by <NAME>], supplement: none, numbering: none) She had written #emph[The Official Accord and Guidance of the Guilds of Ravnica ] long before the Maze. Long before the Guildpact had a body and could sleep, eat, void, and die like the rest of the world. That law book sat in her lap now. Teysa didn't need to physically read it to know its contents, but tomorrow was the day she would act. Teysa needed the comfort of her proudest creation. Finally she had the tools to restructure her guild. The allies to help her. The loophole to generate a path to freedom from the abusive dead. Really, the best part of the whole Maze affair was losing. As she warmed her blood by the fire, Teysa remembered the thrill of secret realization when she watched Niv-Mizzet test the Living Guildpact after his victory over the Guild champions. Now that the Guildpact had a body, the law had a voice. And what that voice spoke was law. She could manipulate this technicality to challenge the monopoly of the Obzedat. It was a lovely loophole. Teysa was, first and foremost, an advokist. She #emph[adored] loopholes. "I see you're a narcissist even in your spare time, Granddaughter." Teysa jumped in her chair. The fat, opulent folds of her deceased grandfather, Karlov, ghosted through the closed window of her study. She scowled. "I do not care if you cannot physically knock, I will not be interrupted during my leisure time," she snapped. With a nimbleness he certainly did not have in life, Karlov lowered himself gently onto a chair across from Teysa, eyeballing the self-authored book sitting in his granddaughter's lap. "Why read through a text you wrote yourself, sweet child?" Had he the mass of his living self Karlov would sink down past the chair's tolerance, but death has many advantages. "Unless you would rather read your own words than listen to the advice of your own family." Teysa mentally filed through the endless list of disagreements she had had with the Obzedat recently. Instead of deciphering which subject her grandfather may have been referring to, Teysa decided she honestly did not care. Instead, she evenly sat up in her chair. "What sort of advice would you have for me, <NAME>?" "Stop busying yourself with acts of vanity," the ghost cooed, placing a massive hand on her copy of #emph[The Official Accord and Guidance of the Guilds of Ravnica] . He lifted his other hand up to his granddaughter's cheek, grazing a large strange claw across her cheekbone. "And start thinking of your blood. Your physical life will go by much quicker if you stop reminiscing on past mistakes." Teysa ate her disgust. Though she could not feel the physical touch on her cheek, she still felt a wave of repulsion roil in her gut. Teysa arranged her face. "I read this to remind myself of past mistakes. The Council requested exception from my laws; I foolishly ignored their advice. My position as Grand Envoy remains secondary to the Obzedat," she reassured through silver tongue. "However, my duties as advokist require me to read many texts, none of which are done in vanity." The spirit soured. "You still claim the title of advokist over Grand Envoy?" "I claim the titles both gifted to me and earned. I worked hard to be an advokist of the Law." "There are more important laws than the ones in your books." Teysa's tolerance tilted. "It isn't right—" "It is our way! I felt it in life, I feel it more strongly in death." "You feel nothing in death," she hissed. Karlov stilled. "What you feel is an unending loop of what you felt when you were alive. You were a coin-gobbling sack of a man in life and have become only more foul in death," Teysa seethed with a venom usually reserved for court theatrics—she couldn't help it as the truths escaped her lips. Karlov raised his eyebrows. His lips turned up slightly as he sat back passively. "I fail to see a problem with any of that, child." #figure(image("002_Family Values/03.jpg", width: 100%), caption: [Karlov of the Ghost Council | Art by Volkan Baga], supplement: none, numbering: none) Karlov stood and held out a translucent hand. Teysa wanted to spit on it. Instead, the Grand Envoy of the Orzhov leaned forward, bound by centuries of the living's obedience, and subserviently kissed the outline of the Councilman's gossamer ring. In that moment, she fantasized about biting his fat finger to the bone. Throttling him with her strong arms and slapping his fleshy face until he sobbed for mercy. She knew without a physical body she could not hurt him. Teysa lifted her lips with internal resolve. "Silly girl," Karlov laughed. "Find my thrull tomorrow," he offered passively as he exited. "Ask for a spare coin or two. Buy yourself something nice." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Teysa used that coin to buy a knife. At present, it was cloaked and strapped to her side as she was guided, in shackles, by her ally, Tajic of the Boros guild. He led her, shrouded and disguised, through a busy street past the Orzhova basilica. Crowds of desperate patrons passed, all moving nervously and quickly through the causeway. A cluster of spirits wafted sadly past Teysa and Tajic as they shuffled around a frenzied trio of devotees. There were no markets in Orzhova, no vendors peddling goods. There was nothing for the public to buy, only gifts from the church to be given. Orzhova was an anxious place if one did not belong to the guild, and the tension in the streets did well to hide Teysa from prying eyes. "Keep up, crone!" Tajic ordered as Teysa allowed herself to trip over her own lame leg. Her disguise was essential to the plan. Although the records she needed were in the basilica itself, she would be too recognizable to access it herself. She needed her friend Tajic for the purpose of sneaking her in, and hoped this show of good faith could lead to a guild alliance in the future. There was a Boros outpost prison near the edge of the main church building. Tajic led her in through the front door and past several guards who nodded at the knight of the Boros. Tajic returned their nod and briskly led Teysa down a long hall of cells. The vacant eyes of several criminals awaiting transport to the main prison stared at Teysa through her veil. She rolled her eyes. Tajic led her down a crooked spiral staircase into a damp underground cell block. There were no prisoners down here, and no light to show them the way. Tajic let go, and Teysa lifted her veil. He lit a torch and ushered her into a basement cell, shutting the door behind him. "My apologies for calling you a crone earlier," the knight said, moving with coarse but gentle palms to remove Teysa's shackles. "Oh, it's fair. I'm old. Technically." Tajic smiled awkwardly, unlocking the shackles on Teysa's wrists. She stretched her freed arms and examined the barren cell around her. She shallowly sighed. "Anything I can use as a cane?" Tajic unsheathed his sword and handed it to her. The knight grinned, "Not only can it assist in walking; it's also a great tool for opening jars and occasionally killing people." Teysa grabbed the hilt, using the blade as a makeshift walking stick. She moved to the wall and tapped a brick at the end of the cell. "I like to think I hid it well down here. None of the other guards ever found the entrance," Tajic said proudly, motioning to a part of the wall that must have hidden the door. Plenty of sleepless nights had gone into magically carving out the three hundred hands' length that connected the Boros cell to the Obzedat's record room. #figure(image("002_Family Values/04.jpg", width: 100%), caption: [Tajic, Blade of the Legion | Art by <NAME>man], supplement: none, numbering: none) Tajic picked at a stone jutting out from the wall of the dimly lit cell. "I can open it myself, but you do you want to see if your method works first?" "Any law verbally affirmed by the Living Guildpact is unbreakable to the person he speaks the affirmation to," she said while taking off the veil and disguise she had worn on the street. "All I need to do is directly reference a law affirmed by him and it must be made manifest. I had him affirm roughly twenty minor laws. He was ever so annoyed," Teysa smiled. "It was precious." Tajic returned her grin and tapped the wall, leading Teysa through an opening he had constructed. The height was short—understandable, given that he had carved it quickly and in secret—and the light of their torch could barely illuminate the wall at the other end of the passage. Teysa ducked and held one hand to the wall as she moved down the dark path. Her new cane clicked across the rocks, sending echoes into the darkness ahead. Tajic stayed to close the wall behind them, quickly rejoining Teysa's side in the cramped passage. #figure(image("002_Family Values/05.jpg", width: 100%), caption: [Rogue's Passage | Art by <NAME>oi], supplement: none, numbering: none) "You didn't have to do any of this, Tajic," Teysa said. "The Ghost Council hasn't done anything to you specifically." "You are a strong leader and ally. Your talents are wasted while you are under the thumb of the Obzedat." "Why thank you, Tajic." "Also, I really hate ghosts," he divulged. "No offense." "None taken." Teysa ran her hand along the side of the passageway. "These dead men are worthy of your hatred." They reached the end of the passage. Teysa stilled herself and recited from memory: "Policies and procedures section 12, item 4." Her heart leaped as a thrill of borrowed law magic surged through her voice. "Official guild representatives may be granted passage from one guild-controlled place of residence or business to another through use of official warrant." Tajic handed her a piece of paper he had drafted earlier. It seemed small in his hand. Teysa held the warrant to the stone and felt the wall vibrate slightly. She stood back as the wall rotated in on itself, bricks folding inward and behind to reveal a pitch-black space. Dust and grit fell to the floor, revealing a dark room lined with files and records before them. Teysa squirmed. "Ugh," she winced. "Law magic feels weird." "What is it like?" The knight asked. Teysa scrunched up her face. "Starchy. Lukewarm. Like a family dinner you couldn't get out of," she shook off a shiver. Tajic made an impartial noise. "An accurate description of every interaction with the Azorius I've ever had." Teysa snorted a quick laugh, handing Tajic his sword back. "Be ready. There may be spells to set off an alarm," the Envoy warned. She palmed the walls of bookcases as she entered; the portal sealed closed on its own behind her and the knight. The records library was pitch-black save for the warm glow of their torch on countless stacks of books. Teysa stood still and recited, "Safety Provisions and Regulations, Article 14: All recorded security measures are to be approved by the Azorius Senate Office of Library and Information Affairs before inspection and operation, all those in violation will be marked for future investigation." Small threads appeared in the air, reflecting a web of silvery shimmers in the light of the torch. "There. Don't touch any of those and follow me," she instructed. Tajic handed back the sword as she moved down the line of books, carefully ducking and weaving through the tangled loom of twinkling magic. With the mass of threads behind them, the light of their torch fell upon a grimy crystal door inlaid with thousands of jewels. Whatever artisan had constructed the door put more intent on the volume of gems than the aesthetic. What was intended to be a grand display of wealth came off as a desperate attempt to impress an empty room. #figure(image("002_Family Values/06.jpg", width: 100%), caption: [Godless Shrine | Art by Cliff Childs], supplement: none, numbering: none) "This is the gaudiest thing I have ever seen in my life," the soldier stated flatly. "We're entering the Obzedat's sanctum. Trust me, it's worse on the inside," Teysa said, lifting her new knife to her arm with a smile. "This next bit is one #emph[I ] wrote." She unflinchingly and shallowly nicked the top of her forearm while reciting, "Article 12 of the #emph[Orzhovniha] , a governing person of Orzhov recognition may be granted entrance to the Obzedat's Chamber with proof of identity." Teysa knelt and discreetly smeared her blood on a far bottom corner of the door. "Why down there?" Tajic asked. Teysa shrugged. "It's an expensive door." The blood was quickly absorbed as a lock deep within the structure released. Teysa started to open the gem-encrusted door. "As if those dead magpies would really throw out anything they owned," Teysa said while grunting and prying the door loose. Tajic moved as if to help, but Teysa continued, lost in thought, "And to think Uncle told me the bodies were #emph[burnt. ] Ha!" The door swung open, and the knight let out a gasp. Dozens of glittering, leathery, gold-and-velvet-draped bodies propped on thrones lined the walls of the room. The mummified former vessels of every Obzedat patriarch and matriarch sat silent and preserved, each covered from head to toe in what must have been nearly every piece of jewelry they owned in life. Huge sagging clothes covered tight-skinned skeletons, with diamonds and jet placed in the hollows of their eyes and Orzhovan deformities more obvious in some than others. The black velvet of their robes shone dimly against the tight ancient skin of the corpses they covered, dozens of rings stacked on bony, fleshless fingers. The thrones the bodies were propped on shone dark ebony and obsidian atop a polished floor inlaid with glittering diamonds. Tajic stopped and stared upwards at the dozens of other bodies resting on inlaid shelves lining the walls of the Obzedat's chamber. The age of the bodies and their belongings increased dramatically as they approached the ceiling, which was covered in an elaborate mosaic of diamonds. The light of Tajic's torch was infinitely refracted around them as Teysa walked confidently towards the center of the empty hall. Her eyes skimmed the floor. The little space left between the gems had been filled with glistening gold and platinum. There were no chairs save for the grisly thrones, and the air stung with vinegar and preserving liquids. #figure(image("002_Family Values/07.jpg", width: 100%), caption: [Orzhov Basilica | Art by <NAME>], supplement: none, numbering: none) A more recent body on the far side of the room reeked of chemicals, body fluids, and dark magic. Teysa stopped near it briefly. "Hello, Uncle," she muttered. Tajic moaned. "Angels above. It's a family reunion." "I warned you it was worse on the inside," Teysa quipped, setting down the sword in the center of the room and lifting a handle inlaid in the floor. She pulled a bejeweled chest out from beneath her feet. Tajic's face was sturgeoned in displeasure. "Please tell me they don't move around." "Don't be barbaric." "You called your family 'magpies' because they #emph[magically preserve their bodies.] " "Well, I do appreciate the principle, but the execution #emph[is] a bit flashy." Teysa used her hand to sweep dust away from the clasp on the front of the jeweled chest she had pulled from the floor. "The records are in there?" Tajic asked. Teysa nodded, opening it and laying a crumbling record book on the opulent floor. She delicately turned the pages until she smiled in delighted recognition. Teysa stood back. "Here goes nothing," she whispered. Teysa lifted her chin and recited from memory, her attention focused on the dimly lit chest in front of her. "By order of the united guilds of Ravnica, it is decided that the betterment and progression of any one guild over another may be seen and understood as an act of war. Should proof of such subversion be discovered by another representative of any other guild, it may be confiscated and turned over to the Living Guildpact for investigation. Tajic of the Boros Guild, what do you see before you?" "You mean other than the skeletons with their skin still on them?" Teysa stared at him with irritation. "I mean the contents of the book on the floor." "My apologies. The skeletons are distracting." Tajic knelt and quickly scanned the page on the floor, being careful not to move his torch too close. The page seemed to be a logbook of Orzhov income. He gently flipped through several pages of crossed-out numbers, listings of interactions, recognizable names, and vault locations. "It is a very old logbook that has clearly been edited multiple times. My gut says this is probably the proof you're looking for. " Teysa smiled in earnest. "In consonance with the #emph[New Accord of the Guild of Ravnica] , you are granted the right of exposure and are obligated by duty to present your evidence of financial corruption to the Living Guildpact," Teysa said through happy tears. She felt a twinge of magic weave through the law in her words and her heart leapt with joy. Tajic tried to lift the record book from the floor He tried again. Teysa's smile vanished. Crumbling dusty pages now stood indestructible and resolute, as if part of the diamond floor. Tajic laid down his torch and clung to the spine of the volume with all his might, using all of his strength and unearthly will to shift the book from where it stood. Teysa's heart stood still. She felt him summon iron-hard Boros magic as he struggled to lift the records. No matter how hard he tried, he could not pick it up. Teysa shook her head. "I don't understand. It should work. I wrote the law, it was confirmed by the Guildpact, it should work." Tajic looked at the Envoy in desperate uncertainty. Teysa felt anxiety tighten in her chest. She closed her eyes and held a hand to her head, running through her knowledge of law with every ounce of concentration. She opened her eyes as sudden revelation spread horror across her face. She moved back her robe to reveal her knife at her hip. "Try to steal this," she said. Tajic stared in confusion as Teysa pointed to her knife. Her brow furrowed in determination. "Petty theft is a violation of personal property with a charge dependent on judicial ruling!" Teysa yelled, weaving as much power as she could into her statement of law. Tajic stood and crossed to her, his boots clicking on the diamond floor. He easily grabbed the hilt of the knife and Teysa gasped. He lifted it away from her belt. The Grand Envoy of the Orzhov froze in horror. "The law can be broken in this room," she choked. Her gray eyes widened to the whites as she looked in terror around the empty, ostentatious chamber. "What do you mean the law can be broken in this room?!" Tajic objected. Teysa choked in response, "The Guildpact does not apply in this room! Something about this place directly manipulates Ravnican law." "How did the Obzedat manage that?! They are dead! They cannot perform magic!" "It's old! It's older than me, it's probably older than any member of the council, it's old and I don't know!" "Well, then you are a silly girl." Teysa gasped. Tajic reflexively held out the stolen knife in defense. The voice came from nowhere. The quickened breath of the Boros and Orzhov echoed eerily in the chamber. The silence was broken suddenly as Teysa growled to the emptiness, "Grandfather." The ghost's form shined strangely in the light of the torch. He silently floated toward his granddaughter, a reproachful and parental scowl on his face. "The law is worthless to our kind, granddaughter. I have told you this for centuries." "Everything about the Obzedat, everything about how our guild has functioned is wrong in the eyes of the law." She trembled in frustration. Every muscle in her body ached to fight, stab, flay, kill, but knew it would be for nothing. Karlov faked a condescending sigh. The ghost had obviously not had to breathe in quite some time—it was a sad mockery of a sigh. "I'm afraid I will have to punish you for your temper tantrum, Teysa. I am very disappointed in you." "I am not a child!" "You have disobeyed my will." "Nothing can be obeyed in this room!" Teysa asserted, flinging a gesture to the entire chamber. "We can be obeyed in this room," Karlov overruled with iron conviction. "I initiate an immediate summoning of the Obzedat." Tajic yelled with surprise as dozens of ghosts swiftly rose from beneath the floor. Corpulent, deformed bodies of long-dead Orzhov rose from beneath Tajic's feet and icily grazed his skin. He jolted in shock where he stood and the torch fell to the floor. Teysa stood still through the summoning, well-accustomed to the manners of the dead. The temperature in the chamber dropped dramatically as Teysa's tears of prior joy chilled on her cheek. Karlov lifted himself to float slightly above the other ghosts of the Obzedat. "The Grand Envoy of the Orzhov seeks to upend the council. What say we to her insolence?" The ghosts cried out in anger, an alien, unearthly sound that shook Teysa and Tajic to their cores. #figure(image("002_Family Values/08.jpg", width: 100%), caption: [Obzedat, Ghost Council | Art by Svetlin Velinov], supplement: none, numbering: none) "Summon a thrull to escort the Boros to our dungeon," Karlov ordered. A thrull shambled quickly through the previously open door and grabbed Tajic by the wrists. The soldier looked back at Teysa, uncertain whether to fight. Teysa subtly shook her head in response. The Boros left with his captor and the massive door closed behind him. Teysa was dimly lit in the glow of the torch on the floor. Dozens of ghosts stared down at her from every corner of the chamber. Karlov approached her, his frown deepening on the folds of his face. "By order of the Obzedat, your title of advokist is hereby #emph[revoked] ." Teysa's heart clenched. "You can't!" "I can in here. The council forbids you from the practice of law for the rest of your existence," Karlov avowed. Teysa's head was spinning. "I barely practice anymore! Only the Azorius Senate can remove my title as advokist—" "We do as we please. Just as we always have." Her life. Her work. It was over. Teysa's hip slid to the floor as she held herself up by her arms. "You've been planning this . . ." "On revoking your title as advokist? Why of course, you vain little idiot. And unless you want it back, you will step in line and remember your blood." Karlov flexed his fat, translucent hands. "We will discuss the details of your remaining title as Grand Envoy immediately. I will meet you in the Orzhova tower, yes?" Karlov smiled and motioned towards the record room door on the far side of the room. Her chest heaved as her hands balled into fists on the diamond floor. "You can't take away something I achieved on my own." Karlov smiled. "I can when you don't put the Obzedat first. We gave you a title. You owe us your unquestioning service." He held out his hand and presented his ghostly ring. Teysa looked directly through it at the jeweled floor. Karlov tsked. "Insolent little girl." "I am one hundred and twelve years old," the Grand Envoy seethed. Karlov slowly knelt until his face was near her ear. He faked an intake of old and shuddering breath and seethed through his teeth. "You are small." And she was. "The tower, as you know, is roughly seven floors above this one. Don't keep me waiting," the ghost chided while floating up and into the ceiling. Teysa was alone. The dying embers of the torch illuminated Tajic's sword. She sighed. The title of Grand Envoy was never a gift. It was a way to keep her bound. She, <NAME> of the Orzhov Guild, was in debt. She grabbed the sword. She stood firmly, supporting herself with the blade as her cane. And she began to walk toward the stairs.
https://github.com/Error0229/-
https://raw.githubusercontent.com/Error0229/-/main/__/__%20...%20_...typ
typst
The Unlicense
#set text(font: ("Microsoft Sans Serif", "New Computer Modern")) #align(center, text(24pt)[ *現代科技概論 期中心得報告*\ *淺談虛擬貨幣與其風險* ]) #align(right, [資工三 110590004 林奕廷]) = 導言 虛擬貨幣,特別是比特幣及其衍生的其他加密貨幣,自2009年首次出現以來,迅速引起了全球範圍內的廣泛關注。這些數字貨幣的出現被視為金融技術領域的一次重大創新,它們提供了一種全新的支付方式,並且為資產交易和投資活動開辟了新途徑。虛擬貨幣的非中心化特性和潛在的匿名交易能力,使它們在全球範圍內受到了投資者和科技愛好者的青睞。然而,隨著其交易量和市值的激增,虛擬貨幣也帶來了不少風險,這些風險不僅對個人投資者構成了威脅,對全球的經濟安全和金融穩定也產生了深遠的影響。本報告將深入探討虛擬貨幣面臨的主要風險類型,並提供相應的分析和省思。 = 虛擬貨幣的市場風險 == 價格波動性 虛擬貨幣市場的波動性極高,這是因為它受多種因素的影響,包括市場情緒、政治事件、技術變革以及全球經濟狀況。比如,比特幣在其短暫的歷史中已多次經歷了劇烈的價格波動。2017年,比特幣的價格從不到1,000美元迅速上漲到近20,000美元,隨後在不到一年的時間內又跌回到約3,000美元,更不用提之後2021年的65000美元,以及在今年的新高近71000美元。這種快速的價格變動雖然吸引了大量的投機者,但同時也帶來了極高的投資風險。對於那些尋求快速盈利的投資者來說,虛擬貨幣市場的不確定性和波動性可以提供機會,但對於尋求長期投資的人來說,這種波動則是一個重大的風險因素。 = 市場操縱 相對於成熟的金融市場,虛擬貨幣市場的監管仍然不夠完善,這使得市場操縱行為更加容易發生。在虛擬貨幣市場中,大額交易者—通常被稱為“鯨魚”—能夠通過大規模的買賣行為影響市場價格,這種影響有時會導致市場價格的不正常波動。例如,某個“鯨魚”可能會突然賣出大量虛擬貨幣,導致價格暴跌,然後在低價位再次大量購入,以此來獲得利潤。這種行為不僅損害了市場的公平性,也增加了普通投資者面臨的風險。 = 技術安全風險 == 安全漏洞 虛擬貨幣交易和存儲依賴於複雜的技術,尤其是區塊鏈技術。雖然區塊鏈技術本身具有較高的安全性,但它不是完全無懈可擊。交易平台和錢包的安全漏洞仍然是黑客攻擊的目標。例如,2019年一家知名的加密貨幣交易平台遭受駭客攻擊,導致超過4億美元的虛擬貨幣被盜。這類事件不僅對受影響的用戶造成直接經濟損失,也嚴重損害了公眾對虛擬貨幣系統安全性的信任。 = 技術失誤 除了外部攻擊,技術失誤也是虛擬貨幣用戶需要面對的風險。在虛擬貨幣的交易或存儲過程中,一次簡單的操作錯誤—如輸入錯誤的地址或失去私鑰—可能導致資金的永久性丟失。由於大部分虛擬貨幣交易是不可逆的,一旦資金被錯誤地轉移或是私鑰丟失,這些資金幾乎無法被追回。 = 法律與監管的風險 == 不確定的法律地位 全球範圍內對於虛擬貨幣的法律地位和監管政策存在極大的不一致性。在一些國家,如美國和日本,虛擬貨幣得到了相對明確的法律認可和較為嚴格的監管框架。然而在其他國家,如中國,政府則禁止了虛擬貨幣的交易和流通。這種法律和政策的不確定性為跨國交易和投資帶來了額外的風險,投資者必須時刻關注相關法律和政策的變化,以避免意外的法律風險。 == 監管變動的風險 除了各國法律的不一致外,虛擬貨幣的監管政策也可能會快速變化。這些變化可能源於政治因素、經濟變動或是技術發展。政策的突然變更,如某國突然決定對虛擬貨幣實施更嚴格的監管,或者完全禁止其交易,都可能對虛擬貨幣的市場價值造成顯著的衝擊。這種風險使得虛擬貨幣的投資更加複雑和不確定。 = 社會和心理風險 == 社會影響 虛擬貨幣的匿名性和去中心化特性提供了一定程度的自由和隱私,但這些特性也容易被用於非法活動。洗錢、資助恐怖活動、網絡詐騙和其他犯罪行為經常利用虛擬貨幣來逃避法律追踪。這些行為不僅對社會安全造成威脅,也損害了虛擬貨幣作為合法金融工具的形象和信譽。 == 投資心理 投資虛擬貨幣不僅需要技術和市場知識,還需要強大的心理承受能力。市場的極端波動性和不確定性常常導致投資者經歷劇烈的情緒波動,從貪婪到恐慌的心理變化可能在短時間內迅速交替。這種情緒驅動的投資行為容易導致非理性決策,從而加劇個人和市場的風險。 = 結論與個人見解 虛擬貨幣作為一種新興的金融工具,其提供的獨特機會和相對應的風險是前所未有的。投資虛擬貨幣需要不僅對其潛在的經濟利益有充分的認識,同時也要對相關的風險有深刻的理解。隨著技術的進步和監管環境的完善,預計虛擬貨幣的市場將逐漸成熟,但這需要政策制定者、技術開發者和市場參與者之間的積極合作與智慧應對。在這個快速變化的市場中,持續的教育和適應是每個投資者的必經之路。\ 但除此之外,我認為投資虛擬貨幣不僅僅是一種經濟行為,更是一種價值觀的選擇。在投資虛擬貨幣的同時,我們也應該關注其對社會、環境和個人的影響,並努力尋求一種更加公平、透明和可持續的金融體系。唯有帶著這樣的價值觀謹慎且嚴肅地砥礪前行,才能帶來真正的財富。
https://github.com/mhspradlin/wilson-2024
https://raw.githubusercontent.com/mhspradlin/wilson-2024/main/programming/day-2.typ
typst
MIT License
#set page("presentation-16-9") #set text(size: 30pt) = Day 2 #pagebreak() == Functions A function lets you execute another piece of code. Functions are *invoked* by using the name of the function, parentheses, and passing *arguments*. #pagebreak() == Anatomy of a Function Invocation ```python max(10, 15, 6) ``` #pagebreak() == Function Invocation Arguments can be variables. ```python alice_score = 10 bob_score = 22 carol_score = 2 max(alice_score, bob_score, carol_score) ``` #pagebreak() == Function Invocation Function invocations can be arguments to other functions. ```python max(564, max(100, 689), 12) ``` #pagebreak() == Modules Many useful functions come from modules. You get access to these functions by *import* ing them. This is used a lot to interact with the Sense HAT. #pagebreak() == Module Import ```python from random import randint random(0, 10) ``` #pagebreak() == Multiple Imports Good modules come with *documentation* that explains what they do. Here is the documentation for the built-in `string` module: #link("https://docs.python.org/3/library/string.html") ```python import string print(string.digits) print(string.punctuation) ``` #pagebreak() == `for..in` Loop It's common to want to run a piece of code a certain number of times. For that, you can use `for..in`. #pagebreak() == `for..in` with `range` `range(a, b)` returns numbers starting with `a` and going to `b - 1`. ```python for i in range(0, 5): print(i) ``` #pagebreak() == `if` Condition Often you only want to execute a piece of code *conditionally*. For this you can use `if..else`. #pagebreak() == `if` Condition Like with `while`, it takes in a condition to evaluate. ```python if True: print("True!") # This is executed else: print("False!") # This is not ``` #pagebreak() == `if` Condition Usually variable will be involved in the condition. ```python is_even = False if is_even: print("Even") else: print("Odd") ``` #pagebreak() == Loops and Conditionals Together Loops and conditionals together can express a wide range of *algorithms*. An *algorithm* is a sequence of steps for solving some problem. #pagebreak() == First Algorithm Design an algorithm to find the smallest integer $n$ such that $n$ squared is greater than two million. #pagebreak() == Find smallest $n$ such that $n^2 > 2000000$ An algorithm to solve this is as follows: + Start at zero (`current_number`) + Square `current_number` + If the square is greater than 2000000, print the number and stop. + If the square is less than 2000000, add one to `current_number` and go back to step 2. #pagebreak() == First Attempt What is the problem below? ```python current_number = 0 while True: square = current_number * current_number if square > 2000000: print(current_number) else: current_number = current_number + 1 ``` #pagebreak() == Find smallest $n$ such that $n^2 > 2000000$ #text(size: 26pt)[ ```python still_searching = True current_number = 0 while still_searching: square = current_number * current_number if square > 2000000: print(current_number) print(square) still_searching = False else: current_number = current_number + 1 ``` ] #pagebreak() == Break #pagebreak() == Lab 2: Countdown Timer #link("https://tinyurl.com/wilson-pi-lab-2")
https://github.com/Gowee/typst-clatter
https://raw.githubusercontent.com/Gowee/typst-clatter/main/README.md
markdown
MIT License
# clatter - PDF417 Barcode Generator clatter is a simple Typst package for generating PDF417 barcodes, utilizing the [rxing](https://github.com/rxing-core/rxing) library. ## Features - **Easy to Use**: The package provides a single, intuitive function to generate barcodes. - **Flexible Sizing**: Control the size of the barcode with optional width and height parameters. - **Customizable Orientation**: Barcodes can be rendered horizontally or vertically, with automatic adjustment based on size. ## Usage The primary function provided by this package is `pdf417`. ### Parameters - `text` (required): The text to encode in the barcode. - `width` (optional): The desired width of the barcode. - `height` (optional): The desired height of the barcode. - `direction` (optional): Sets the orientation of the barcode, either `"horizontal"` or `"vertical"`. If not specified, the orientation is automatically determined based on the provided dimensions. ### Sizing Behavior - By default, the barcode is rendered horizontally at a reasonable size. - If both `width` and `height` are provided, the barcode will fit within the specified dimensions (i.e. `fit: "contain"`). - If the `height` is greater than the `width`, the barcode will automatically switch to vertical orientation unless `direction` is manually set. ### Example Usage ```typst #import "@preview/clatter:0.0.0": pdf417 // Generate a sized horizontal PDF417 barcode // Note: The specified size may not be exact, as the barcode will fit within the box, maintaining its aspect ratio. #pdf417("sized-barcode", width: 50mm, height: 20mm) // Generate a vertical barcode #pdf417("vertical-barcode", direction: "vertical") // Generate a barcode and position it on the page #place(top + right, pdf417("absolutely-positioned-barcode", width: 50mm), dx: -5mm, dy: 5mm) ``` --- <small>Of course, such a lengthy README can't be written without the help of ChatGPT.</small>
https://github.com/flaribbit/indenta
https://raw.githubusercontent.com/flaribbit/indenta/master/README.md
markdown
MIT License
# Indenta An attempt to fix the indentation of the first paragraph in typst. It works. ## Usage ```typst #set par(first-line-indent: 2em) #import "@preview/indenta:0.0.3": fix-indent #show: fix-indent() ``` ## Demo ![image](https://github.com/flaribbit/indenta/assets/24885181/874df696-3277-4103-9166-a24639b0c7c6) ## Note When you use `fix-indent()` with other show rules, make sure to call `fix-indent()` **after other show rules**. For example: ```typst #show heading.where(level: 1): set text(size: 20pt) #show: fix-indent() ``` If you want to process the content inside your custom block, you can call `fix-indent` inside your block. For example: ```typst #block[#set text(fill: red) #show: fix-indent() Hello #table()[table] World ] ``` This package is in a very early stage and may not work as expected in some cases. Currently, there is no easy way to check if an element is inlined or not. If you got an unexpected result, you can try `fix-indent(unsafe: true)` to disable the check. Minor fixes can be made at any time, but the package in typst universe may not be updated immediately. You can check the latest version on [GitHub](https://github.com/flaribbit/indenta) then copy and paste the code into your typst file. If it still doesn't work as expected, you can try another solution (aka fake-par solution): ```typst #let fakepar=context{box();v(-measure(block()+block()).height)} #show heading: it=>it+fakepar #show figure: it=>it+fakepar #show math.equation.where(block: true): it=>it+fakepar // ... other elements ```
https://github.com/munzirtaha/typst-cv
https://raw.githubusercontent.com/munzirtaha/typst-cv/main/lib.typ
typst
MIT License
#let primary-color = rgb("#0395DE") #let secondary-color = gray #let header(name: none, title: none, mobile: none, email: none, github: none, linkedin: none, photo: none) = { grid( columns: (1fr, 13%), [ #text(font: "<NAME>", 3em, name)\ #set text(primary-color) #smallcaps(title) 📱 #link("tel:" + mobile) | 📧 #link("mailto:" + email) |  #link(github)[#github.split("/").last()] |  #link(linkedin)[#linkedin.split("/").last()] ], if "photo" != none { box(clip: true, radius: 50%, image(photo)) } ) } #let section(title) = { set par(spacing: 0.65em) set text(1.4em, weight: "bold") text(primary-color)[#title.slice(0, 3)] + title.slice(3) box(width: 1fr, line(start: (0.1em, 0em), length: 100%)) } #let entry(logo: none, entity: none, title: none, location: none, date: none, details: [], tags: ()) = { grid( columns: (2em, 1fr, auto), align: horizon, gutter: 0.5em, text(2em, fill: primary-color, logo), { strong(smallcaps(entity)) linebreak() text(primary-color, title) }, { align(right)[ #text(primary-color, style: "italic", location)\ #text(secondary-color, style: "italic", date) ] }, ) details let tagList(tags) = { for tag in tags { box(inset: 0.25em, fill: luma(240), radius: 0.3em, text(0.8em, tag)) h(0.5em) } } tagList(tags) } #let honor(date: none, logo: none, title: none, issuer: none) = { grid( columns: (16%, 1.5em, 1fr), align: horizon, gutter: 0.2em, align(right, text(secondary-color, date)), align(center, box(height: 1em, logo)), [#strong(title), #issuer], ) } #let skill(type: "", info: "") = { grid( columns: (16%, 1fr), gutter: 0.9em, align(right, text(weight: "bold", type)), info, ) }
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/admonitions.typ
typst
The Unlicense
#import "../colors.typ": * #import "../icons/icons.typ" #import "/utils.typ" #import "../metadata.typ": * #import "/packages.typ": showybox #import showybox: * #let admonition = utils.make-admonition((type, body) => { let info = admonition-type-metadata.at(type) let colored-icon = utils.change-icon-color( raw-icon: info.icon, fill: info.color, ) showybox( frame: ( border-color: info.color, body-color: info.color.lighten(80%), thickness: ( left: 4pt, ), radius: 1.5pt, ), [ #text( size: 15pt, fill: info.color, [ #box(baseline: 30%, image.decode(colored-icon, width: 1.5em)) *#info.title* ], ) \ #body ], ) })
https://github.com/senaalem/ISMIN_reports_template
https://raw.githubusercontent.com/senaalem/ISMIN_reports_template/main/template.typ
typst
#let rectangle( title: "", subtitle: "", authors: (), date: "", logo: none, main-color: rgb(87,42,134), header-title: "", header-subtitle: "", body ) = { set document(title: title) set text(lang: "fr") // le séparateur dans la légende des figures set figure.caption(separator: [ : ]) let count = authors.len() let ncols = calc.min(count, 3) // on enregistre les polices du document dans des variables let title-font = "Klima" let body-font = "New Computer Modern" // on enregistre les couleurs du document dans des variables let primary-color = rgb(main-color) let secondary-color = rgb("#5c6670") // on règle l'affichage du code show raw: it => { text(font: "Cascadia Code", it) // police pour les blocs de texte brut } // on règle l'affichage des blocs de code show raw.where(block: true): block.with( fill: luma(240), radius: 3pt, inset: 10pt, stroke: 0.1pt ) // on règle l'affichage du code en ligne show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 3pt, ) // on règle l'affichage des équations en ligne show math.equation: set text(font: "New Computer Modern Math") // on règle l'affichage des blocs d'équation show math.equation: it => { show regex("\d+\.\d+"): it => { show ".": {"," + h(0pt)} it } it } // permet d'utiliser les virgules comme séparateur décimal // on règle l'affichage des liens show link: it => {underline(text(it, fill: primary-color))} // permet de casser l'affichage des figures show figure: set block(breakable: true) show heading: set text(fill: primary-color) show quote.where(block: true): rect.with( stroke: (left: 2.5pt + secondary-color), inset: (left: 1em) ) // police de texte set text(font: body-font) // page de garde set page(margin: 0%) place(top + center, rect(width: 100%, fill: primary-color)[ #v(2%) #align(center)[#image("assets/logo_emse_white.svg", width: 50%)] #v(2%) ] ) place(bottom + center, rect(width: 200%, fill: primary-color, [#v(3%)])) place(bottom + center, dy: -150pt, text(size: 18pt)[#date]) align(center + horizon)[ #box(width: 80%)[ #line(length: 100%) #text(size: 25pt)[#smallcaps[*#title*] \ #subtitle] #line(length: 100%) #v(10pt) #text(size: 18pt)[ #table( align: center, stroke: none, column-gutter: 15pt, columns: (1fr,) * ncols, ..authors.map(author => [ #strong(author.name + " " + smallcaps[#author.surname]) \ #author.affiliation #author.year \ #emph(author.class) ]) ) ] ] ] pagebreak() // table des matières set page( margin: auto, numbering: "1", number-align: center, ) outline(indent: true) // contenu set page(header:[ #smallcaps[#header-title] #h(1fr) #smallcaps[#header-subtitle] #align(horizon)[#line(length: 100%, stroke: 0.2pt)] ] ) set par(first-line-indent: 2em, justify: true) set heading(numbering: "1.1 ") body } // fonctions #let violet-emse = rgb("#5f259f") #let gray-emse = rgb("#5c6670") #let tab = h(2em)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/bugs/grid-3-00.typ
typst
Other
#set page(height: 70pt) #v(40pt) The following: + A + B
https://github.com/warab1moch1/MathmaticalFinance
https://raw.githubusercontent.com/warab1moch1/MathmaticalFinance/main/20240622.typ
typst
#import "manual_template.typ": * #import "theorems.typ": * #show: thmrules // Define theorem environments #let theorem = thmbox( "theorem", "Theorem", fill: rgb("#e8e8f8") ) #let lemma = thmbox( "theorem", // Lemmas use the same counter as Theorems "Lemma", fill: rgb("#efe6ff") ) #let corollary = thmbox( "corollary", "Corollary", base: "theorem", // Corollaries are 'attached' to Theorems fill: rgb("#f8e8e8") ) #let definition = thmbox( "definition", // Definitions use their own counter "Definition", fill: rgb("#e8f8e8") ) #let exercise = thmbox( "exercise", "Exercise", stroke: rgb("#ffaaaa") + 1pt, base: none, // Unattached: count globally ).with(numbering: "I") // Use Roman numerals // Examples and remarks are not numbered #let example = thmplain("example", "Example").with(numbering: none) #let remark = thmplain( "remark", "Remark", inset: 0em ).with(numbering: none) // Proofs are attached to theorems, although they are not numbered #let proof = thmproof( "proof", "Proof", base: "theorem", ) #let solution = thmplain( "solution", "Solution", base: "exercise", inset: 0em, ).with(numbering: none) #let project(title: "", authors: (), url: "", body) = { set page(paper: "a4", numbering: "1", number-align: center) set document(author: authors, title: title) set text(font: "Linux Libertine", lang: "en") set heading(numbering: "1.1.") set par(justify: true) set list(marker: ([•], [--])) show heading: it => pad(bottom: 0.5em, it) show raw.where(block: true): it => pad(left: 4em, it) show link: it => underline(text(fill: blue, it)) align(center)[ #block(text(weight: 700, 1.75em, title)) ] pad( top: 0.5em, bottom: 2em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center)[ #author \ #link(url) ]), ), ) outline(indent: true) v(2em) body } #show: project.with( title: "No.7", authors: ( "warab1moch1", ), url: "https://github.com/warab1moch1" ) = 確率積分 $H$ : 連続適合#footnote[ #definition[ $X_t$ : $F_t$ - 適合であるとは、 $ forall t quad X_t : cal(F)_t "- 可測" $ ] 即ち、その時点までの情報で決まっていることを意味している ]過程、$W$ : $cal(F)_t$ によって生成されたBM ( Brownian Motion ) であるとする。 いま、 $ integral_0^t H_s d W_s $ なる確率変数を定めたい。 あるいは、 $ (integral_0^t H_s d W_s)_(t >= 0) $ なる確率過程を定めたい。 改めて前提を整理すると、 $ integral_0^t H_s d W_s $ において考えているのは、$omega in.small Omega$ をひとつ fix したとき、ある時刻 $s$ を与えると#v(1mm) -- $s arrow.r.bar H_s (omega)$ : 普通の関数(Path)#v(1mm) -- $s arrow.r.bar W_s (omega)$ : 普通の関数(Path)#v(1mm) であるように、それぞれはこれまでに定義してきた(見知った)関数である。 一方で、上の確率変数を Lebersgue - Stieltjes 積分($arrow.l.r.double$ Path $omega$ ごとの積分)として定めるのは無理であることが知られている。即ち、 $ sum_(i=1)^n H_(t_i) (omega) (W_(t_(i+1)) (omega) - W_(t_i) (omega)) $ を考えられないということである。 これは、$W_t$ が2次変分を持つことから、有界変動#footnote[ ブラウン運動が無限にギザギザしているという性質は、積分において都合が悪いということである。 ]な Path を確率 $1$ で持たないことによる。 そこで、Lebersgue 積分のように各点収束を考えるのではなく、分割における左側の関数値を代表点として $L^2$ 収束#footnote[ これより、確率収束していることが言える ($because$ #h(1mm) No.5) *ここら辺ブラウン運動の回を見直して直しておく* ]を考えればよい、というのが確率積分(伊藤積分)の骨子である。 これより、積分の構成や証明などで高度な部分は割愛しつつ、満たしてほしい性質から天下り的に確率積分を考える。 例によって、$Delta$ : $0=t_0 < dots.c < t=t_n$ を $[0, t]$ の分割とする。 このとき、 $ A_t^Delta := sum_(i=1)^n H_(t_(i-1)) (W_(t_i) - W_(t_(i-1))) $ $ B_t^Delta := sum_(i=1)^n H_(t_i) (W_(t_i) - W_(t_(i-1))) $ なる確率変数を考える。それぞれ、各分割地点における左(右)側を代表点とした確率積分の近似である。 $ B_t^Delta - A_t^Delta = sum_(i=1)^n ( H_(t_i) - H_(t_(i-1)) ) (W_(t_i) - W_(t_(i-1))) $ であるから、例えば $H=W$ の場合を考えると、 $ B_t^Delta - A_t^Delta &= sum_(i=1)^n (W_(t_i) - W_(t_(i-1)))^2\ &attach(arrow.r, t:abs(Delta) arrow.r 0) t #h(3mm) (eq.not 0) $ つまり $B_t^Delta eq.not A_t^Delta$ である。 また、 $ B_t^Delta + A_t^Delta &= sum_(i=1)^n (W_(t_i)) + W_(t_(i-1)) (W_(t_i)) - W_(t_(i-1))\ &= sum_(i=1)^n (W_(t_i)^2 - W_(t(i-1))^2)\ &= W_t^2 - 0\ &= W_t^2 $ よって $ A_t^Delta tilde.eq 1 / 2 (W_t^2 - t) $ $ B_t^Delta tilde.eq 1 / 2 (W_t^2 + t) $ と考えられる。特に、上の $A_t^Delta$ の右辺はマルチンゲールであり、性質がよさそうである。 これを念頭に、左側を代表点とするものを確率積分であると考えると、今後の見通しがよさそうである。 例えば、 $ Delta : (0=t_0 < dots.c < s=t_k < dots.c < t=t_n) $ として、$[0, t]$ の $s$ を通る分割を以下では考える。 このとき、 $ EE[A_t^Delta|cal(F)_s] &= EE[sum_(i=1)^n H_(t_(i-1)) (W_(t_i) - W_(t_(i-1)))|cal(F)_(t_k)]\ &= sum_(i=1)^k H_(t_(i-1)) (W_(t_i) - W_(t_(t_(i-1))))\ &+ sum_(i=k+1)^n EE[EE[H_(t_(i-1)) (W_(t_i) - W_(t_(t_(i-1))))|cal(F)_(t_(i-1))]|cal(F)_(t_k)]\ & #text(0.8em)[($because$ $cal(F)_(t_k)$ - 可測性と Tower Law)]\ &= A_s^Delta + sum_(i=k+1)^n EE[H_(t_(i-1)) EE[W_(t_i) - W_(t_(i-1))|cal(F)_(t_(i-1))]|cal(F)_(t_i)]\ &= A_s^Delta #text(0.8em)[($because$ $W$ はマルチンゲールだから増分は $0$)] $ よって、$integral_0^t H_s d W_s$ は、$t$ についてマルチンゲールになるべき量である 加えて、天下り的ではあるが、$H$ : 有界として $ EE[(A_t^Delta)^2] &= EE[ sum_(i=1)^n sum_(j=1)^n H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1)))]\ &= sum_(i=1)^n EE[H_(t_(i-1))^2 (W_(t_i) - W_(t_(i-1)))^2] \ &+ 2 sum_(i > j) EE[H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1))] $ であるから、Tower Law により $ ("第一項の中身") &= EE[EE[H_(t_(i-1))^2 (W_(t_i) - W_(t_(i-1)))^2|cal(F)_(t_(i-1))]]\ &= EE[H_(t_(i-1))^2 EE[(W_(t_i) - W_(t_(i-1)))^2|cal(F)_(t_(i-1))]]\ &= EE[H_(t_(i-1))^2 (t_i - t_(i-1))] quad #text(0.8em)[($because$ 分散)] $ $ ("第二項の中身") &= EE[EE[H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1)))|cal(F)_(t_(i-1))]]\ &= EE[H_(t_(i-1)) H_(t_(j-1)) (W_(t_j) - W_(t_(j-1))) EE[(W_(t_i) - W_(t_(i-1)))|cal(F)_(t_(i-1))]] quad #text(0.8em)[($because$ 独立増分性)]\ &= 0 $ より、 $ EE[(A_t^Delta)^2] &= EE[sum_(i=1)^n H_(t_(i-1))^2 (t_i - t_(i-1))]\ &attach(arrow.r, t:abs(Delta) arrow.r 0) EE[integral_0^t H_s^2 d s] $ である。 これより、冒頭で正体がつかめなかった『確率積分』の2乗の期待値は、(適合過程として)知っている関数の2乗の期待値に収束していることがわかる。 これまでの結果をまとめると、 $integral_0^t H_s d W_s$ は、次の伊藤の等長性という式を満たすべきである。 $ EE[(integral_0^t H_s d W_s)^2] = EE[integral_0^t H_s^2 d s] $ このとき、確率積分 $integral_0^t H_s d W_s := I$ は $L^2$ 可積分でマルチンゲールであり、 $ bar.v.double I bar.v.double_(L^2 (Omega, PP))^2 = bar.v.double H bar.v.double_(L^2 (Omega times [0, t], cal(P), PP times lambda))^2 $ と言える#footnote[ 右辺の $PP$ は確率測度で $lambda$ はルベーグ測度、また $cal(P)$ はこの積分を成立させるための(舞台設定としての)加法族である。 ]。 これより、この $I$ の2次変分を考えたい#footnote[証明なしで以下を考えることになるが、確率積分 $integral_0^t H_s d W_s$ が連続であると都合がよい]。$I = integral_0^t H_s^2 d s$ において、#v(1mm) -- $H_s (omega)$ : $omega$ を与えるごとに生成される連続な Path #v(1mm) -- $d s$ は普通の Lebersgue 積分#v(1mm) であるから、$omega$ を与えるごとに値が確定する積分であることに注意する。\ *2次変分の性質(ちゃんとしたやつ)のっける*\ -- $0$ スタート -- 増加 -- 連続なパスを持つ -- $A^2 - X$ がマルチンゲール このとき、上の3つは直観的に成立を期待できる。そこで、 $ Delta : (0=t_0 < dots.c < s=t_k < dots.c < t=t_n) $ として、 $ X_t^Delta := sum_(i=1)^n H_(t_(i-1))^2 (t_i - t_(i-1)) $ $ X_s^Delta := sum_(i=1)^k H_(t_(i-1))^2 (t_i - t_(i-1)) $ とおくと、 $ EE[(A_t^Delta)^2 - X_t^Delta|cal(F)_s] &= EE[sum_(i=1)^n sum_(j=1)^n H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1))) \ &quad - sum_(i=1)^n H_(t_(i-1))^2 (t_i - t_(i-1)) |cal(F)_s]\ &= sum_(i=1)^n EE[H_(t_(i-1))^2 ((W_(t_i) - W_(t_(i-1)))^2 - (t_i - t_(i-1)))|cal(F)_(t_k)]\ &quad + 2 sum_(i>j) EE[H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1)))|cal(F)_(t_k)] $ であるから、 第一項の各項は#v(1mm) -- $i <= k$ のとき $ = H_(t_(i-1))^2 ((W_(t_i) - W_(t_(i-1)))^2 - (t_i - t_(i-1))) $ として可測性より外に出せる#v(1mm) -- $i > k$ のとき $ &= EE[EE[H_(t_(i-1))^2 ((W_(t_i) - W_(t_(i-1)))^2 - (t_i - t_(i-1)))|cal(F)_(t_(i-1))]|cal(F)_(t_k)]\ &= EE[H_(t_(i-1))^2 EE[(W_(t_i) - W_(t_(i-1)))^2|cal(F)_(t_(i-1))]]\ &quad - EE[H_(t_(i-1))^2 (t_i - t_(i-1))|cal(F)_(t_k)] quad #text(0.8em)[($because$ $t_i - t_(i-1)$ は定数)]\ &= EE[H_(t_(i-1))^2(t_i - t_(i-1))|cal(F)_(t_k)] - EE[H_(t_(i-1))^2(t_i - t_(i-1))|cal(F)_(t_k)] quad &#text(0.8em)[($because$ 独立増分性)]\ &= 0 $ また、第二項の各項は $i > k$ のとき $ &= EE[EE[H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1)))|cal(F)_(t_(i-1))]|cal(F)_(t_k)]\ &= EE[H_(t_(i-1)) H_(t_(j-1)) (W_(t_j) - W_(t_(j-1))) EE[(W_(t_i) - W_(t_(i-1)))|cal(F)_(t_(i-1))]|cal(F)_(t_k)]\ &= 0 quad #text(0.8em)[($because$ 独立増分性)] $ であるから、 $ EE[(A_t^Delta)^2 - X_t^Delta|cal(F)_s] &= sum_(i=1)^k H_(t_(i-1))^2 (W_(t_i) - W_(t_(i-1)))^2 - sum_(i=1)^k H_(t_(i-1))^2 (t_i - t_(i-1))\ &quad + 2 sum_(k>=i>j) H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1))) \ &= (A_s^Delta)^2 - X_s^Delta $ となり、所望の結果を得る#footnote[ ここで、$(A_s^Delta)^2$への変形には一般形 $H_(t_(i-1)) H_(t_(j-1)) (W_(t_i) - W_(t_(i-1))) (W_(t_j) - W_(t_(j-1)))$ の対角線領域と三角形領域の和が $k times k$ の正方形となることを用いた。 ]。
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/attempts/stacking-cubes-1.typ
typst
// this file attempts to remove the overlaps between edges // it is a major refactor: changing styles to an array // example-single-cube: working // example-multiple-cube(): the background overlaps ... // doesnt look very good #import "@local/typkit:0.1.0": * #import "@local/mathematical:0.1.0": * #import "@preview/cetz:0.2.2" #import "../utils.typ": get-adjacent-pairs #import cetz.draw: * #let get-prism-segments(pos, dimensions: (1, 1, 1), styles: ()) = { let (x, y, z) = pos let (length, width, height) = dimensions let vertices = ( (x, y, z), (x + length, y, z), (x + length, y + width, z), (x, y + width, z), (x, y, z + height), (x + length, y, z + height), (x + length, y + width, z + height), (x, y + width, z + height), ) let faces = ( front: ((0, 1), (1, 2), (2, 3), (3, 0)), back: ((4, 5), (5, 6), (6, 7), (7, 4)), left: ((0, 4), (4, 7), (7, 3), (3, 0)), right: ((1, 5), (5, 6), (6, 2), (2, 1)), bottom: ((0, 1), (1, 5), (5, 4), (4, 0)), top: ((3, 2), (2, 6), (6, 7), (7, 3)), ) let face-keys = unique(faces.keys(), styles.map((x) => x.key)) let store = () let seen = () let items = styles + face-keys.map((key) => (key: key)) for item in items { let index-pairs = faces.at(item.key) for index-pair in index-pairs { let key = stringify(index-pair.sorted()) if key not in seen { seen.push(key) let p = ( segment: index-pair.map((i) => vertices.at(i)), style: getter(item, ignore: "key"), ) store.push(p) } } } return store } #let example-single-cube() = { cetz.canvas( { let start = (0, 0, 0) let attrs = ( styles: ( (fill: blue, stroke: strokes.soft, key: "front"), (fill: blue, stroke: strokes.soft, key: "back"), ), ) let items = get-prism-segments(start, ..attrs) let n = 3 for (i, item) in items.enumerate() { line(..item.segment, ..item.style) } }, ) } #let prism(start, ..attrs) = { let items = get-prism-segments(start, ..attrs) for (i, item) in items.enumerate() { line(..item.segment, ..item.style) } } #let example-multiple-cube() = { cetz.canvas( { let start = (0, 0, 0) let attrs = ( styles: ( // (fill: blue, stroke: strokes.soft, key: "front"), // (fill: blue, stroke: strokes.soft, key: "back"), ), ) for i in range(5) { let start = (i, 0, 0) prism(start, ..attrs) } for i in range(5) { let start = (0, 0, i) prism(start, ..attrs) } }, ) } // #example-multiple-cube() // cubes are drawn #cetz.canvas({ draw.shapes.grid() prism((-1, 1, -1)) prism((-1, 2, -1)) })
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/escape_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Unicode codepoint does not exist. // // Error: 1-11 invalid Unicode codepoint: FFFFFF // \u{FFFFFF}
https://github.com/TheBotlyNoob/ECE1551
https://raw.githubusercontent.com/TheBotlyNoob/ECE1551/main/notes/2/ECE1551%20-%20Chapter%202.typ
typst
#show link: underline #show link: set text(blue) #set text(size: 12pt) #outline(indent: 2em, title: [ECE 1551 Chapter 2: ]) = DeMorgan's Theorem $overline(\XY) = overline(X) + overline(Y)$ $overline(X + Y) = overline(\XY)$ - Simplify $(\AB)'(A' + B)$ + $(A' + B')(A' + B)$ + $A' + A'B + B'A'$ + $A'cancel((B + B'))$ + $A'$
https://github.com/StanleyDINNE/php-devops-tp
https://raw.githubusercontent.com/StanleyDINNE/php-devops-tp/main/documents/Rapport/Rapport.typ
typst
// Add the VSCode extension "Typst" to edit this file easily! #import "Typst/Template_default.typ": set_config #import "Typst/Constants.typ": document_data, line_separator, figures_folder #import "Typst/Util.typ": file_folder, import_csv_filter_categories, insert_code-snippet, insert_figure as i_f, to_string, todo, transpose #show: document => set_config( title: [Configuration d'un Pipeline CI/CD\ pour une #link("https://github.com/StanleyDINNE/php-devops-tp")[Application Web PHP]], title_prefix: "TP: ", authors: (document_data.author.reb, document_data.author.stan, document_data.author.raf).join("\n"), context: "Security & Privacy 3.0", date: datetime.today().display(), image_banner: align(center, image("Typst/logo_Polytech_Nice_X_UCA.png", width: 60%)), header_logo: align(center, image("Typst/logo_Polytech_Nice_X_UCA.png", width: 40%)), )[#document] #let insert_figure(title, width: 100%, border: true) = { i_f(title, folder: "../" + figures_folder + "/Rapport", width: width, border: border) } Le dépôt se trouve à l'adresse : https://github.com/StanleyDINNE/php-devops-tp #linebreak() #outline(title: "Sommaire", indent: 1em, depth: 3) <table_of_contents> #pagebreak() = Compréhension et configuration de base == Analyse du projet PHP Il s'agit d'une application PHP simple, avec principalement #file_folder("index.php"), qui va afficher deux rectangles contenant chacun du texte, et ce en appelant l'app' dédiée #file_folder("ImageCreator.php"). - #file_folder("ImageCreator.php") définit la classe `ImageCreator` qui va prendre en paramètre deux couleurs et deux chaînes de charactères pour ainsi remplir l'objectif énoncé à l'instant. - L'utilisation du gestionnaire de packages PHP "Composer" est ici nécessaire pour l'appel à la #link("https://carbon.nesbot.com/docs/")[librairie de gestion de date & heure "Carbon"], dont l'unique but est de joindre au texte du premier rectangle, la date et l'heure à laquelle celui-ci est généré et donc en l'occurance à peu près la date et l'heure de l'affichage de la page. Étant donné le peu d'éléments soulignés, d'autres plus annecdotiques peuvent être évoqués : - Une page #file_folder("info.php") est présente et génère la page d'information standard de `php` grâce à ```php phpinfo()```. - Une police d'écriture présente via la fichier #file_folder("consolas.ttf") est utilisée par `ImageCreator` Concernant la configuration et le déploiement de l'application, celle-ci est containerisée, avec Docker, via #file_folder("docker/Dockerfile"). == Configuration de l'environnement Docker Commençons par construire l'image #insert_code-snippet(title: [Construction de l'image Docker,\ instanciation d'un container et accès au terminal du container])[```bash cd "php-devops-tp" # Commandes docker lancées en tant qu'utilisateur root # Construction de l'image à partir de la racine du projet docker build --tag php-devops-tp --file docker/Dockerfile . # L'image a bien été créée docker images # Instanciation d'un container qui va tourner en arrière-plan docker run --detach --interactive --tty \ --publish target=80,published=127.0.0.1:9852,protocol=tcp \ --add-host host.docker.internal:host-gateway \ --name php-devops-tp_container php-devops-tp # Il nous est possible d'accéder à la page via le navigateur, à l'adresse "http://localhost:9852" # Le container est lancé docker ps # Possibilité d'enter dans le container via tty avec `bash` docker exec --interactive --tty php-devops-tp_container /bin/bash ```] Nous avons à présent #insert_figure("Accès à la page info.php du container fonctionnel et accessible", width: 60%) Un problème apparaît cependant avec #file_folder("index.php") comme le montre l'image ci-dessous #insert_figure("Problèmes avec index.php", width: 60%) Pour le corriger, il reste à importer les dépendances avec "Composer" (```bash composer update```), soit manuellement avec le tty interactif une fois le container lancé, soit en ajoutant l'instruction dans le #file_folder("Dockerfile"). #insert_figure("index.php fonctionel après l'ajout des dépendances", width: 60%) Il sera choisi de modifier le #file_folder("Dockerfile") pour que les dépendances soient déjà correctes lors de l'instanciation d'un container issu de l'image Docker. #(linebreak()*2) #line_separator #(linebreak()*2) = Mise en place du pipeline CI/CD == Configuration GitHub et CircleCI Le dépôt étant à présent sur GitHub, nous allons configurer CircleCI, en nous aidant notamment de #link("https://circleci.com/blog/setting-up-continuous-integration-with-github/")[ce blog post sur le site de CircleCI]. Nous nous connectons sur CircleCI avec notre compte GitHub, et il nous est proposé de lier un dépôt. #pagebreak() == Création du pipeline CI/CD minimal Certaines des jobs listés dans #file_folder(".circleci/config.yaml") font appel à des variables d'environnement, certaines n'étant pas encore définies, comme ```bash $GHCR_USERNAME``` et ```bash $GHCR_PAT``` pour #link("https://ghcr.io")[GitHub Container Registry]. Nous avons donc commencé par retirer certains job (`build-docker-image`, `deploy-ssh-staging`, `deploy-ssh-production`) pour s'assurer que les autres fonctionnaient correctement. Grâce aux informations données par l'étape `Install dependencies` du job `build-setup` qui a échoué sur CircleCI, nous avons pu corriger les versions incohérentes de `php` entre #file_folder("composer.json") qui nécessitait une version de PHP correspondant à `">=8.2.0"`, #file_folder("composer.lock") qui n'avait pas été mis à jour avec `composer` à partir de #file_folder("composer.json"), et #file_folder(".circleci/config.yaml") qui attendait `php:8.1`. #insert_figure("Jobs du workflow main_workflow se terminant tous avec succès", width: 60%) == Ajout des variables d'environnement nécessaires Les variables d'environnement ```bash $CIRCLE_PROJECT_USERNAME```, ```bash $CIRCLE_PROJECT_REPONAME```, ```bash $CIRCLE_BRANCH``` et ```bash $CIRCLE_REPOSITORY_URL``` étant utilisées, notamment pour en définir d'autres, il convenait de les définir dans la section des variables d'environnement du projet sur CircleCI. Les paramètres du projet sur CircleCI indiquaient qu'aucune variable d'environnement par défaut n'était déclaré. Or, nous avons pu confirmer via les logs de la step `Preparing environment variables` du job `debug-info` des précédents builds, que ces variables (avec d'autres), avaient été définies par défaut, certaines lors de la liaison du projet sur GitHub à CircleCI, d'autres (comme les branches) en fonction du contexte. #pagebreak() == Gestion des secrets avec Infisical Nous pensions au début qu'Infisical nous servirait à stocker les secrets utilisés lors des build dans le pipeline dans CircleCI. La suite de cette sous-partie illustre nos réflexions pour parvenir à configurer et stocker dans Infisical les secrets déclarés dans #file_folder(".circleci/conig.yml") et donc utilisés dans CircleCI, comme ```bash $GHCR_USERNAME``` et ```bash $GHCR_PAT``` servant aux jobs depuis lesquels sont construits et publiés les images Docker du projet. À la fin de toutes les configurations de ce rapport, voici un accès au token, qui peut être utilisé pour l'injection de commandes dans l'application #insert_figure("Récupération réussie du token Infisical depuis le container") === Secrets liés au build dans le pipeline <infisical_in_circleci> ==== Idée de base Le compte Infisical ayant été associé à GitHub, l'intégration fut assez simple. Avec l'aide de l'article d'#link("https://infisical.com/docs/integrations/cicd/circleci")[intégration de CircleCI dans Infisical], le projet a pu être lié. Il restait à lier Infisical dans CircleCI, en utilisant la CLI d'Infisical, ce que #link("https://infisical.com/docs/cli/usage")[cet article] a pu décrire. \ L'idée se décomposait comme suit : + *Stockage des secrets ```bash $GHCR_USERNAME``` et ```bash $GHCR_PAT``` dans Infisical.*\ ```bash $GHCR_PAT``` a été obtenu depuis les _personal access token_ dans les paramètres de compte GitHub, et ```bash $GHCR_USERNAME``` correspond au nom de l'organisation : ici le dépôt a été publié sous un utilisateur, donc la valeur est le pseudonyme de l'utilisateur. + *Génération d'un token de service dans Infisical.*\ Nous avons généré un "service token" dans Infisical avec accès en mode lecture seule, avec comme scope "Development", et chemin #file_folder("/"), sans date d'expiration (mais on pourrait en mettre une et définir des politques pour les remplacer), qui serait utilisé avec la CLI d'Infisical dans CircleCI avec l'option `--token`. + *Stockage sécurisé du token créé dans CircleCI.*\ Nous avons pu utiliser les #link("https://circleci.com/docs/contexts/")[_Contextes_] de CircleCI, qui servent à partager des variables d'environnement de manière sécurisée entre les projets, mais que l'on a restraint ici au projet `php-devops-tp` pour définir des variables d'environnement traîtées comme des secrets. Définition de cette valeur sous dans un contexte nommé `api_tokens-context`, avec comme nom de variable `INFISICAL_API_TOKEN`. + *Invocation des secrets avec l'API d'Infisical dans CircleCI, en utilisant le token pour s'authentifier.*\ Les secrets allaient être utiles pour le job `build-docker-image`. #insert_code-snippet(title: [Ajout d'un script dans le job `debug info` pour vérifier l'accès à des variables d'environnement protégées dans CircleCI])[```bash if [ -z "$INFISICAL_API_TOKEN" ]; then echo "You forgot to set INFISICAL_API_TOKEN variable!" else echo "INFISICAL_API_TOKEN variable is set!" echo "Leaking INFISICAL_API_TOKEN value through stdout: '$INFISICAL_API_TOKEN'" fi ```] #insert_figure("Variable issue du contexte api_tokens-context accessible, et masquée automatiquement dans les logs", width: 80%) #insert_code-snippet(title: "Utilisation d'Infisical en mode CLI pour accéder aux secrets dans CircleCI")[```bash function docker_login() { echo "$GHCR_PAT" | docker login ghcr.io -u "$GHCR_USERNAME" --password-stdin } infisical run --token "$INFISICAL_API_TOKEN" --env=dev --path=/ -- docker_login ```] ==== Exigences liés à l'outil dans l'environnement d'exécution des jobs <remarque_infisical_build> Cependant, nous nous sommes rendus compte que la CLI d'Infisical n'était pas présente sur les machines de CircleCI, qui exécutaient les jobs. Il était possible de le télécharger à chaque build de l'image Docker du projet (donc le job où l'outil serait nécessaire pour injecter les secrets), en ajoutant les lignes suivantes dans #file_folder(".circleci/congif.yml"), issue de #link("https://infisical.com/docs/cli/overview")[la documentation d'Infisical] : #insert_code-snippet(title: "Installation de la CLI d'Infisical")[```bash curl -1sLf 'https://dl.cloudsmith.io/public/infisical/infisical-cli/setup.deb.sh' | sudo -E bash sudo apt update sudo apt install infisical -y ```] Mais cela a un coût en ressources, certes faible, mais existant. Si on devait faire cela pour chaque outil non-natif au système sur lequel le build tourne, les curl/wget ainsi que les temps d'installation cumulés consommeraient beaucoup de ressources. Il serait plus intéressant de faire tourner le build à partir d'une machine qui contiendrait déjà ces outils, par exemple un conteneur Docker. Les executors déclarés dans #file_folder(".circleci/congif.yml") sont justement de cette utilité, et une #link("https://circleci.com/developer/images?imageType=docker")[liste des images utilisables pour différents langages de programmation, etc.] peut être trouvée sur le site d'Infisical. Seulement, aucun ne contient `infisical`, et il faudrait donc en construire une en local, depuis une image DockerInDocker (pour que le job puisse ensuite utiliser `docker` dedans pour construire l'image de notre projet), image à laquelle il faudrait ajouter les outils liés à PHP (comme on utilise l'exécuteur `builder-executor`, issu de l'image `cimg/php:8.2-node`), puis la publier sur _GitHub Container Registery_ pour pouvoir éventuellement l'utiliser en tant que contexte de build pour le job `build-docker-image`. ==== Réalisation et correction <correction_utilisation_contextes> Mais... tout cela paraissait être beaucoup comparé aux instructions précédentes dans les consignes. Nous avons finalement compris qu'Infisical allait nous servir pour les secrets de l'application en elle-même, ce qui a d'ailleurs été confirmé avec la ligne ```Dockerfile RUN ... && apt-get install -y infisical``` dans le #file_folder("Dockerfile"). Ayant déjà compris l'usage des contexes dans CircleCI, nous avons simplement créé ```bash $GHCR_USERNAME``` et ```bash $GHCR_PAT``` dans un contexte que nous avons nommé `api_tokens-context`, et invoqué le job `build-docker-image` dans le workflow prévu à cet effet (`container_workflow`) avec ce contexte. En lançant un build de debug (avant toutes ces réflexions dans @infisical_in_circleci), nous avons pu vérifier que les accès aux secrets étaient effectifs. #insert_figure("Vérification des accès aux secrets d'Infisical depuis un job dans CircleCI", width: 40%) (_Avec le recul lors des dernières modification de ce rapport, il a paru beaucoup plus évident qu'il aurait été possible de gérer les secrets du build avec Infisical. Le choix de ne pas le faire expliqué par les raisons ci-dessus dans le @remarque_infisical_build et @correction_utilisation_contextes, sont des choix faits relativements tôt (début janvier 2024) et par soucis de ne pas rajouter de complexité inutile à peu de temps du rendu, celui-ci persistera._) === Secrets liés à l'application #todo[Configurer le secret avec Infisial pour une injection dans le build] Considérons que notre application (qui là n'est qu'une application _placeholder_) utilise un secret ```bash $APP_SECRET```. On peut configurer l'injection du token d'Infisical ```bash $INFISICAL_API_TOKEN``` en tant que variable d'environnement au moment du lancement du container, avec ```bash sudo docker run -e INFISICAL_API_TOKEN=""$INFISICAL_API_TOKEN" ...```, pour qu'à l'interieur du container, l'application `a_given_app` puisse utiliser Infisical grâce à ```bash infisical run --token "$INFISICAL_API_TOKEN" --env=dev --path=/ -- a_given_app```. L'application n'utilise pas de secret particulier pour l'instant, mais les tests sur l'injection de secrets avec Infisical en ligne de commande ont été concluants. == Ajout du job pour construire l'image Docker du projet === Gestion des détails lors de la configuration du fichier #file_folder(".circleci/config.yml") Nous avons essayé de modifier la version de Docker nécessaire dans #file_folder(".circleci/config.yaml"), passant de `20.10.23` à `25.0.1`, la dernière stable à ce moment, mais celle-ci n'est pas prise en charge dans CircleCI, donc nous avons annulé ce changement. En remarquant cet avertissement de #link("https://discuss.circleci.com/t/remote-docker-image-deprecations-and-eol-for-2024/50176")[discontinuation de Docker Engine 20 sur CircleCI], nous avons utilisé le tag `default` à la place, désignant la dernière version supportée, à savoir Docker Engine 24. #insert_figure("Discontinuation de la version 20.10.23 de docker engine par CircleCI", width: 50%) Outre cette erreur, lors de l'exécution du job `build-docker-image`, l'étape définie "_Build and Push Docker Image to GHCR (GitHub Container Registry)_" a soulevé l'alerte ci-dessous, et ce, alors que la commande ```bash echo "$GHCR_PAT" | docker login ghcr.io -u "$GHCR_USERNAME" --password-stdin``` était utilisée. _```text WARNING! Your password will be stored unencrypted in /home/circleci/.docker/config.json. ```_ Cela est dû au fait que #link("https://stackoverflow.com/a/63357887")[Docker va conserver les crendentials] dans #file_folder("$HOME/.docker/config.json"), avec un simple encodage en base 64, c'est-à-dire aucune protection concrète. Comme ces fichiers ne sont pas persistants sur les machines dédiées à l'exécution des pipelines sur CircleCI, nous n'avons pas pris de mesure supplémentaire pour gérer cette alerte, mais dans l'idéal, il faudrait trouver un moyen régler ça. De même, dans le job `build-docker-image` était spécifié un répertoire au nom erroné pour le #file_folder("Dockerfile"), à savoir #file_folder("docker/"), alors que sa recherche est sensible à la casse sous le système de fichiers ext4 (utilisé par la plupart des distributions Linux). Comme il était référencé à quelques endroits dans le projet par #file_folder("docker/") et qu'il est courant de voir des noms de répertoire en minuscules, le répertoire à été renommé. Cette remarque est importante, car toutes les commandes exécutées sur le répertoire préalablement inexistant #file_folder("docker/") vont échouer. === Scope des tokens d'autorisation GitHub Une autre erreur est survenue ```text denied: permission_denied: The token provided does not match expected scopes. ``` La scope du token donné manquait effectivement de la permission d'écriture : sans ça, pas de possibilité de publier des images Docker via ce token sur _GitHub Container Registery_. Une fois un token avec les bonnes permissions regénéré depuis GitHub, et configuré sous CircleCI, le job pouvait s'exécuter correctement jusqu'au bout. #insert_figure("Workflow container_workflow qui fonctionne enfin", width: 40%) Après avoir observé la présence d'un package sur https://ghcr.io/stanleydinne/php-devops-tp, nous avons pu le lier au dépôt `php-devops-tp`. #insert_figure("Proposition de liaison de l'artefact au dépôt qui lui correspond sur GitHub", width: 50%) === Tag des images pour une gestion des version basique Nous avons configuré une gestion basiques des versions des images docker, avec l'utilisation du tag du commit comme prefix du nom de l'image envoyée sur _GHCR_ : comme il est unique au sein du dépôt, aucun soucis. Si aucun tag n'est utilisé, le nom par défaut donné devient `"${branche}_${date}"`, comme `main_1970-01-01`. #insert_code-snippet(title: "Définition du préfixe du nom de l'image pour un versionning basique")[```bash TAG="$CIRCLE_TAG" if [[ -z "$TAG" ]]; then echo "Tag not set on commit: branch name + today's date used for tag. E.g. \"main_1970-01-01\"" TAG="$(echo $CIRCLE_BRANCH | tr '[:upper:]' '[:lower:]' | tr '/' '-' | tr -cd '[:alnum:]._-' | cut -c 1-128)" TAG="$TAG_$(date +%Y-%m-%d)" fi ```] #insert_figure("Tag et versionning des images docker sur GHCR", width: 70%) #(linebreak()*2) #line_separator #(linebreak()*2) = Extension du Pipeline Certains espaces de discussion sur #link("https://discuss.circleci.com/")[CircleCI Discuss] comme #link("https://discuss.circleci.com/t/my-php-based-build-and-test-systems-on-circleci/17584")[un système de build et tests basé autour de PHP] nous ont permis d'avoir un aperçu de ce qui avait déjà été fait comme configuration autour de PHP dans CircleCI. Nous avions commencer par tester les extensions sur le container en local avant de mettre les commandes dans la config qui va être utillisée dans le pipeline. On rentre dans le container local avec ```bash docker start php-devoops-tp_container; docker exec --interactive --tty php-devops-tp_container /bin/bash```. Pour être clair, les termes "_évaluation de code_" et "_qualité de code_" sont respectivement des évaluations quantitatives et des évaluations qualitatives du code. Il y a eu beaucoup de problèmes d'installation avec ```bash composer``` sur le pipeline, comme c'était la première fois que nous l'utilisions, et nous avons finelement réussi à régler les incompatibilités, comprendre les packages systèmes dont certaines extensions dépendent, etc. == Ajout de jobs dévaluation de code === `phpmetrics` Nous avons suivi le #file_folder("README.md") du dépôt #link("https://github.com/phpmetrics/PhpMetrics")[phpmetrics/PhpMetrics], et configuré PhpMetrics dans le job `metrics-phpmetrics` : #link("https://phpmetrics.org/")[Leur site] donnait un aperçu du fonctionnement et de la logique de l'outil. Les instructions sur quelle commande ```bash composer``` utiliser étaient présentes sur le #link("https://github.com/phpmetrics/PhpMetrics")[GitHub de phpmetrics]. Avec ```bash composer require --dev "phpmetrics/phpmetrics=*"``` (option `--with-all-dependencies` pas utilisée ici), on update le fichiers de dépendances #file_folder("composer.json"), ainsi que #file_folder("composer.lock") et installe les dépendances demandées. Avec ```bash composer update && composer install```, on peut installer `phpmetrics` ainsi que les autres dépendances de #file_folder("composer.json") qui manquent. Maintenant #file_folder("./vendor/bin/phpmetrics") est créé, on peut faire ```bash php ./vendor/bin/phpmetrics --report-html=myreport src/ chown www-data myreport mv myreport public/myreport ```, puis dans le navigateur de la machine hôte, accéder à http://127.0.0.1:9852/myreport/index.html. #insert_figure("Accès à la page du rapport de phpmetrics, depuis un container local", width: 70%) Il existait #link("https://phpmetrics.github.io/website/configuration/")[des configurations] mais nous ne nous en sommes pas servis. === `phploc` Comme le suggère le #link("https://github.com/sebastianbergmann/phploc?tab=readme-ov-file#installation")[#file_folder("README.md")] de #link("https://phpqa.io/projects/phploc.html")[phploc], l'installation ne se fera pas avec `composer`, mais plutôt en installant le #file_folder(".phar") (PHP Archive) de l'outil :\ #emph(strike[```bash composer require --dev phploc/phploc && php vendor/bin/phploc src/```]) ```bash wget https://phar.phpunit.de/phploc.phar php phploc.phar src/ ``` Ça va faire un rapport statique sur la taille des fichiers, les dépendances, la complexité, etc. et ça va l'afficher dans `stdout`. == Intégration de la qualité du code === `phpmd` En extrapolant un peu depuis #link("https://phpmd.org/download/index.html")[la page d'installation], on utilise ces commandes pour installer puis utiliser l'outil. ```bash composer require --dev "phpmd/phpmd=@stable" php ./vendor/bin/phpmd src/ html .circleci/rulesets.xml > phpmd-report.html ``` Nous avons pris le #file_folder(".circleci/plugins/phpmd_ruleset.xml") depuis #link(" https://github.com/phpmd/phpmd")[le GitHub de PHPMD] Le job `lint-phpmd` échoue, mais cela est "contrôlé" : en effet, nous avons configurer le job pour échouer en réutilisant les codes d'erreur de la commande. Dans le cas actuel, il existent certaines violations correspondantes au fichier de configuration #file_folder(".circleci/plugins/phpmd_ruleset.xml") qui persistent dans le code PHP de l'application, comme montré dans la @phpmd_report. #insert_figure("Problèmes relevés par PHPMD qui font échouer le job", width: 70%) <phpmd_report> Nous n'avons pas cherché à corriger le code, car ce n'était pas l'objectif premier de ce travail, et nous préférions allouer plus de temps à la configuration du pipeline, et des connexions aux machines AWS. === `niels-de-blaauw/php-doc-check` Même en suivant les instructions du #link("https://github.com/NielsdeBlaauw/php-doc-check/")[dépôt GitHub de `php-doc-check`] ou du #link("https://phpqa.io/projects/php-doc-check.html")[site], aucune des installations avec les commandes suivantes ne semblait fonctionner : #insert_code-snippet(title: [Essais d'installation de `php-doc-check`])[```bash composer require --dev "niels-de-blaauw/php-doc-check=*" php ./vendor/bin/php-doc-check src # Ou alors curl -sSL https://github.com/NielsdeBlaauw/php-doc-check/releases/download/v0.2.2/php-doc-check.phar -o php-doc-check.phar php php-doc-check.phar src ```] #insert_figure("Problèmes et conflits d'installation soulevés avec l'utilisation de php-doc-check", width: 50%) Comme le dernier commit sur le dépôt date de septembre 2022, et que l'_issue_ la plus récente a exactement la même date, les problèmes doivent certainement venir de l'absence de maintenance. Nous n'allons pas creuser plus loin pour l'instant. == Intégration des outils dans le pipeline En utilisant la directive `store_artifacts` en tant que step de chaque job rajouté (`metrics-phpmetrics`, `metrics-phploc`, `lint-phpmd`), on peut stocker temporairement (pendant 15 jours selon #link("https://circleci.com/docs/workspaces/#overview")[la documentation d'_Infisical_]) les rapports dans l'onglet "Artifacts" de chaque job. // Nous voyions une utilisation du stockage sur CircleCI telle que "33.4 MB of 2 GB used", ce qui est dû aux rapports. Nous n'avions au début pas connaissance de , et qu'il aurait peut-être fallu les gérer dans un répertoire /tmp, et établir une procédure de gestion des reports, d'ailleurs, ceux-ci sont sotcker sur AWS, mais de CircleCI (en cliquant sur un report, on est redirigé vers une des machines dédiées sur AWS pour CircleCI) L'idée à présent, était de créer deux jobs en plus qui permettraient de centraliser les rapports de _metrics_ pour l'un, et les rapports de linting pour l'autre. #insert_figure("Jobs centralisant les rapports, qui se sont pas atteints si leur prédécesseurs ne réussissent pas") <report_jobs_failing> #insert_code-snippet(title: [Configuration des dépendances\ d'un job dans le workflow `main_workflow` ])[```yaml - lint-reports: requires: - lint-phpcs - lint-phpmd ```] On peut le voir dans la @report_jobs_failing ci-dessus, mais les jobs configurés comme en nécessitant d'autres avec la directive `requires`, ne vont pas être atteints si au moins un des jobs desquels il dépend échoue. Cela est problématique dans notre cas, étant donné que l'on voudrait pouvoir stocker les rapports, qu'ils proviennent de job ayant échoués aux attentes ou les ayant respectées. Grâce à #link("https://discuss.circleci.com/t/workaround-run-jobs-sequentially-regardless-of-the-outcome-of-the-required-jobs/40807")[cette discussion sur les forum de CircleCI], nous avons pu trouver une alternative et configurer ainsi nos pipelines. L'idée sous-jascente étant qu'en utilisant l'#link("https://circleci.com/docs/api-developers-guide/#getting-started-with-the-api")[API de CircleCI] (example en @circleci_api), on peut vérifier depuis un job `waiter` qu'un certain job est terminé ou non, et tant qu'il ne l'est pas, le job `waiter` continue d'attendre, en faisant un appel à l'API passé un certain temps. #insert_figure("Structure de l'API CircleCI", width: 50%) <circleci_api> Cette méthode n'est pas forcément optimale car elle consomme du temps d'exécution en plus dans CircleCI, mais elle comble la limitation de la dicrective `requires`. #insert_figure("Les rapports de linting & metrics pourraient être disponibles et centralisés malgré l'échec de certains jobs", width: 60%) Cependant, malgré beaucoup d'essais de configuration des jobs standards de _CircleCI_ `persist_to_workspace` et `attach_workspace`, en en créant d'autres comme `report_persist` (_Cf_ #file_folder(".circleci/config.yml")), les rapports ne se trouvaient pas regroupés dans la section "Artifacts" des jobs `lint-reports` et `metrics-reports`, prévus en tant que jobs aggrégateurs de rapports. Nous l'avons compris très peu de temps avant le rendu de ce rapport, mais toujours selon #link("https://circleci.com/docs/workspaces/#overview")[la même documentation], il n'est pas possible de transférer un _workspace_ entre d'un job `awaited_job` à un job `waiter` si `awaited_job` n'est pas parent/ascendant de `waiter`. #insert_figure("Impossible pour un job d'utiliser un workspace d'un job qui n'est pas son parent", width: 70%) Assez tardivement donc, nous nous sommes rétractés sur la première configuration par défaut, à savoir publier le rapport d'un job sur son onglet "Artifacts". #insert_figure("Même si le job échoue, le report est quand même généré et accessible") == Déploiement automatisé sur AWS EC2 Bien que nous comprenions l'intérêt du job `hold`, Nous avons commencé par désactiver l'utilisation de ce job dans les workflow, car le but du pipeline selon nous, était d'automatiser l'intégration et le déploiement de code ; ainsi, si on doit se connecter sur _CircleCI_ pour approuver à chaque release, c'est que l'on n'a pas vraiment confiance en notre pipeline. // Il faut cependant faire quelque chose de sécurisé. La commande tronquée ci-dessous est utilisée dans le job `deploy-ssh-staging` pour mettre à jour le code source de l'application sur l'instance de la machine AWS distante, installer les dépendances PHP et redémarrer le service PHP-FPM pour appliquer les changements. ```bash ssh -o StrictHostKeyChecking=no $STAGING_SSH_USER@$STAGING_SSH_HOST \<< EOF # ... EOF ``` Nous verrons ci-après (_Cf_ @staging & @production) les spécificités des deux environnements, à savoir sur le serveur staging, et sur le serveur de production. === Configuration sur AWS : premiers essais + Premièrement, nous avons commencé par nous créer un compte AWS en utilisant les #link("https://aws.amazon.com/free")[free tiers proposés]. + On se log en tant que Root user Les étapes suivantes effectuées dans cette section sont laissées en annexe (_Cf_ @configuration_IAM_policies) à titre informatif pour retracer nos essais, mais elles n'ont pas d'utilité directe dans notre configuration finalement. L'objectif était de créer un autre compte `updater_agent` qui n'aurait que le droit de se connecter à l'instance, et ce, au travers de la configuration d'utilisateur IAM. À partir de là, nous cherchions où trouver le mot de passe de l'utilisateur `updater_agent`, ou comment le réinitialiser, mais nous n'arrivions pas à comprendre où chercher. Nous avons ainsi compris que ces "utilisateurs IAM" étaient des comptes AWS aux droits que l'on pouvait restraindre. On peut par exemple les configurer pour qu'ils aient accès à la console ou non, et de manière générale, pour qu'ils puissent utiliser les services Amazon, et non pas les restraindre dans les machines AWS en tant que tel. Mais après avoir lancé l'instance à l'étape d'après (_Cf_ @aws_instance_creation), il se trouve qu'il suffisait de créer un utilisateur sur la machine une fois accédée via SSH (_Cf_ @config_aws_ssh). === Instanciation des deux machines côté AWS <aws_instance_creation> + On se rend sur #link("https://eu-north-1.console.aws.amazon.com/ec2/home")[la page d'accueil d'EC2] + On crée une instance - Ubuntu Server 22.04 - type "t3.micro" (dans le free tier) - avec une création d'un nouveau "Security Group" qui autorise les connexions SSH (justement pour que l'agent puisse faire des updates de l'application) - Il faut aussi autoriser les connexions HTTP entrantes, pour que l'on puisse accéder au service (qui expose du HTTP). - 15 Go de SSD - une keypair temporaire pour se connecter une fois à l'instance + On télécharge le fichier #file_folder(".pem") (la clef privée) à mettre dans le répertoire #file_folder("~/.ssh") de notre machine personnelle. - Puis un changement des droits d'accès dessus (mesure de sécurité standard pour que le fichier ne soit visible que par notre utilisateur sur notre machine) : ```bash chmod 400 AWS_DevSecOps_staging.pem``` + Sur l'onglet de connexion à l'instance sur la console AWS, une commande nous est proposée pour se connecter à la machine (modifiée légèrement pour indiquer qu'elle est dans #file_folder("~/.ssh")) - Nous avons utilisé la commande telle quelle, mais utiliser l'IPv4 publique de la machine en tant qu'hôte est aussi faisable, et sera fait par la suite #insert_figure("Connexion réussie sur la machine AWS en SSH") // ```bash ssh -i "~/.ssh/AWS_DevSecOps2_default.pem" [email protected]``` Nous avons maintenant accès à la machine. La machine de production a été configuré de la même manière, mais simple avec une keypair différente générée pour l'authentification. === Création d'un utilisateur dédié aux mises à jour de l'app' sur chaque machine <config_aws_ssh> Nous avions en tête de dédier un utilisateur aux droits restreints, mais nous nous sommes vite aperçu que pour des tâches telles que modifier le contenu du répertoire #file_folder("/var/www/html") ou redémarrer le service php, l'agent aurait besoin des droits d'administrateur. Cependant, nous savions qu'il était déconseillé de se connecter directement en tant qu'utilisateur `root` avec SSH. Ci dessus sont listées les étapes que nous avons utilisées et mises en place. + Une fois dans la machine, on crée un utilisateur (grâce à #link("https://www.digitalocean.com/community/tutorials/how-to-add-and-delete-users-on-ubuntu-20-04")[cet article de DigitalOcean]) : ```bash sudo adduser updater_agent``` - Suivre les étapes en ne définissant que le mot de passe (le vrai nom, département, etc. ne sont pas pertinents pour nous) - Au fur et à mesure de nos tests avec le pipeline sur CircleCI, nous nous avons compris qu'il fallait lui donner les droits d'administrateur pour qu'il puisse recharger le service `php8.2` après avoir chargé le code : ```bash sudo usermod -aG sudo updater_agent``` - (Nous avons pu utiliser #link("https://linuxize.com/post/how-to-delete-group-in-linux/")[cet article-là sur Linuxize pour la suppression des groupes]) #insert_figure("L'utiisateur n'est pas ajouté au groupe root et ne peut pas utiliser sudo", width: 70%) // - Passage en tant qu'utilisateur root : ```bash sudo su``` + Changement d'utilisateur pour impersonner `updater_agent` : ```bash su updater_agent``` + Création d'une paire de clefs ssh (pour une connexion depuis le pipeline sur CircleCI) : - ```bash mkdir -p ~/.ssh && cd ~/.ssh && ssh-keygen -t ed25519 -C "updater_agent"```\ (Fichier nommé #file_folder("circleci.key")) + Nous avons rencontré une erreur qui nous a donné du fil à retordre: `[email protected]: Permission denied (publickey).` Mais finalement, nous avons compris qu'il fallait autoriser la connexion SSH via la clef créée explicitement pour éviter l'erreur - ```bash cat ~/.ssh/circleci.key.pub > ~/.ssh/authorized_keys``` + Enfin, étant donné que certaines commandes telles que `service` allaient être utiliées en mode administrateur, nous avons pu trouver comment autoriser l'utilisateur à exécuter certaines commandes sans demande de mot de passe (lors du script d'update en ssh automatisé). #insert_code-snippet(title: [Configuration de commandes qui font exception à la demande\ de mot de passe lors de leur exécution en tant qu'utilisateur `root`])[```bash sudo visudo # Règles établies sur le serveur staging updater_agent ALL=(ALL) NOPASSWD: /usr/bin/rm updater_agent ALL=(ALL) NOPASSWD: /usr/bin/cp updater_agent ALL=(ALL) NOPASSWD: /usr/sbin/service # Règle établie sur le serveur de production updater_agent ALL=(ALL) NOPASSWD: /usr/bin/docker ```] - En ce qui concerne le pourquoi de telle ou telle commande autorisée, il faut observer les injections de commandes lors de la connexion SSH des agents, qui sont décrites dans #file_folder(".circleci/config.yml"), et qui sont expliquées dans le @config_user_CircleCI + Copie de la clef privée qui se trouve dans #file_folder("~/.ssh/circleci.key") À partir de là, la suite de cette configuration se fera sur CircleCI, dans le @config_user_CircleCI === Configuration des deux machines staging et production À la fin de cette partie, nous avons obtenu ceci #insert_figure("Les deux serveurs staging et production lancés") ==== Serveur staging : mises à jour, configuration de PHP, des dépendances, et lancement de l'application <staging> #insert_code-snippet(title: [Installation des services nécessaires, notamment ce qui est fait dans #file_folder("docker/Dockerfile") et dans le job `deploy-ssh-staging` de #file_folder(".circleci/config.yml")])[```bash sudo apt update sudo apt upgrade -y [ -f /var/run/reboot-required ] && sudo reboot -f # Reboot si nécessaire # Après le reboot # Ajout de PHP & cie sudo add-apt-repository ppa:ondrej/php # To install php8.2 sudo apt install -y curl git php8.2 libapache2-mod-php8.2 php8.2-fpm sudo apt install -y php8.2-gd php8.2-xml php8.2-mbstring # pour composer curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer sudo a2enmod rewrite # Installation et mise à jour du projet cd $HOME git clone https://github.com/StanleyDINNE/php-devops-tp && cd php-devops-tp composer install --optimize-autoloader --no-interaction --prefer-dist # Exposition du service sudo mkdir -p /var/www/html && sudo rm -rf /var/www/html/* && sudo cp -r ./* /var/www/html # Pour être sûr de supprimer les fichiers existants sudo sed -i 's!/var/www/html!/var/www/html/public!g' /etc/apache2/sites-available/000-default.conf sudo systemctl restart apache2 (flock -w 10 9 || exit 1; sudo -S service php8.2-fpm restart ) 9>/tmp/fpm.lock ```] Cette configuration manuelle est sujette à être bancale si des packets manquent, etc. L'un des but de la containerisation avec Docker est d'avoir des images déjà toutes configurées, et que l'exécution soit reproductible. Avant même de commencer cette configuration, nous nous sommes dits que cela aurait été mieux de simplement instancier un container Docker, dans lequel toute cette configuration était déjà faite. Ainsi, pour le serveur de production, nous avons entrepris de déployer l'image Docker construite dans le pipeline sur CircleCI et hébergée sur GHRC.io. ==== Serveur de production : installation de docker et instanciation du container <production> Ainsi, pour le serveur de production, toujours sur Ubuntu 22.04, nous avons installé Docker engine grâce #link("https://docs.docker.com/engine/install/ubuntu/")[au tutoriel pour Ubuntu sur docker.com]. Après l'installation, et la configuration de l'utilisateur `updater_agent` comme pour la machine Staging (avec mot de passe différent, configuration de la keypair en mettant la clef privée dans les contextes de CircleCI, etc. : _Cf_ @aws_instance_creation & @config_aws_ssh), il suffisait de récupérer l'image depuis notre dépôt GitHub avec ces commandes : ```bash sudo docker pull ghcr.io/stanleydinne/php-devops-tp:latest sudo docker run --detach --publish 80:80 --name "php-devops-tp_latest_container" "ghcr.io/stanleydinne/php-devops-tp:latest" ``` Il fallait aussi faire attention que le package soit public sur GHCR.io, ce que nous avons fait Nous n'allons pas essayer de configurer un certificat pour exposer notre service en HTTPS, mais il faudrait. Si on l'avait fait, il aurait fallu configurer le firewall iptables en ajoutant ça : ```bash sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT```, ce qui va permettre de rendre accessible le service provenant du conteneur Docker sur le port 443 de la machine AWS. === Côté CircleCI <config_user_CircleCI> Grâce à la documentation sur #link("https://circleci.com/docs/add-ssh-key/")[l'ajout de clefs SSH], nous avons pu faire cette partie. + On se rend sur les paramètres du projet + Section "SSH Keys" + Ajout d'une clef SSH - On met comme hostname l'IPv4 publique de la machine - On colle la clef privée copiée de la section précédente @config_aws_ssh #insert_figure("Ajout de clefs SSH pour les comptes updater_agent", width: 60%) + On obtient la signature (`SHA256:...`) - On peut utiliser cette signature en tant que valeur pour ```bash $STAGING_SSH_FINGERPRINT```, qui sera utilisé dans #file_folder(".circleci/config.yml") + On stocke ```bash $STAGING_SSH_FINGERPRINT="SHA256:..."``` en tant que varaible d'environnement simple - On aurait même pu l'hardcoder dans le #file_folder(".circleci/config.yml"), mais autant centraliser ce genre de données directement dans CircleCI, et ne pas laisser ça public + On fait de même avec ```bash $STAGING_SSH_USER``` et ```bash $STAGING_SSH_HOST```, respectivement définis comme `updater_agent` et `staging.aws` Les étapes sont les mêmes pour configurer CircleCI pour le serveur de production, avec les variables ```bash $PRODUCTION_SSH_FINGERPRINT; $PRODUCTION_SSH_USER; $PRODUCTION_SSH_HOST``` En ce qui concerne le job `deploy-ssh-staging`, l'idée des commandes git utilisées (```bash git checkout --track ...; git reset --hard ...```) est d'avoir un environnement propre, peu import l'état de la branche actuelle, potentiellement sur un commit qui n'existe plus (dans le cas d'amend a posteriori sur le dépôt), ou alors avec des fichiers modifiés localement (comme #file_folder("composer.lock")) Pour `deploy-ssh-production`, il s'agit simplement d'arrêter le container en cours d'exécution, de le supprimer, de mettre à jour l'image vers sa dernière version avec le tag `latest`, et d'instancier le container, notamment avec le token d'Infisical injecté, pour que l'app' puisse utiliser la CLI d'Infisical pour utiliser ses secrets. #todo[Infisical] == Modification des flows pour définir des politiques La politique de déploiement visible de par la configuration des workflow sur #file_folder(".circleci/config.yml") est telle que : - Les jobs de metrics, tests, et security checks seront toujours exécutés sur n'importe quelle branche, dans le workflow principal `main_workflow` - l'image docker ne sera construite que lorsque des changements sont effectués sur les branches `main` et celles préfixées par `release/`, via le workflow `container_workflow` - le déploiement de l'application sur le serveur staging ne se fera que si des modifications sont perçues sur des branches `release/*`, via le workflow `main_workflow` - le déploiement de l'application via son image docker ne sur le serveur ne production ne se fera qu'à l'issue de la construction de celle-ci, depuis le workflow `container_workflow`, et que lors de changement sur la branche `main` Aussi, l'image est tag avec son numéro de version issue d'un tag git, ou issu du nom de la branche et de la date du jour. == Quelques figures du déploiement #insert_figure("Container lancé sur le serveur de production") #insert_figure("Instances de l'application PHP sur le serveur staging et production", width: 70%) #insert_figure("Workflow exécuté avec succès", width: 70%) #insert_figure("Déploiement automatisé via SSH sur le serveur de production fonctionnel", width: 70%) #pagebreak() = Sécurité à tous les étages : idées pour plus de sécurité tout au long du processus de déploiement + Désactivation de la branche `master` dans les condition de création d'images docker - ```yaml filters: branches: only: # - master ``` Car vu que la branche principale est `main`, si quelqu'un fork le dépôt, crée une branche master, met du code contaminé, et merge ça sur le dépôt prinipal, la politique de création et déploiement de l'image docker fait que celle-ci sera créée avec le job. + Suppression de l'utilisateur de l'option `-o StrictHostKeyChecking=no` avec `ssh`, au vu des commentaires sur #link("https://www.howtouselinux.com/post/ssh-stricthostkeychecking-option")[cet article sur HowToUseLinux] Mais nous avons compris après certains tests, que cela permet de se débarrasser de #align(center)[#rect[```test The authenticity of host '************ (************)' can't be established. ECDSA key fingerprint is .... Are you sure you want to continue connecting (yes/no/[fingerprint])? ```]] + Ceci est plus une remarque, mais sur la configuration SSH par défaut des machines AWS, les connexions SSH où l'utilisateur s'authentifie manuellement avec un mot de passe sont bloquées. Il faut que les utilisateurs utilisent leur clef privée. C'est bien, ça évite de donner la possibilité d'exploiter une attaque en SSH enumeration + brute force le mot de passe. + À un moment, on voulait passer une variable d'environnement récupérée depuis un contexte CircleCI, puis l'injecter dans une commande sudo pour mettre à jour les machines via ssh. Mais c'est une mauvaise idée, car le mot de passe sera ainsi écrit dans #file_folder("~/.bash_history"). À la place, certaines commandes ont été configurées pour pouvoir s'exécuter dans besoin de mot de passe, et ce en configurant ```bash sudo visudo``` + Le dépôt est compte GitHub + En ce qui concerne la configuration de l'instance EC2, il existe - _AWS inspector_, qui permet de faire un scan de vulnérabilités potentielles sur notre machine AWS - Nous ne l'avons pas utilisé par manque de temps avant ce rendu, mais il aurait fallu - _AWS Identity and Access Management (IAM)_, dont il a été question dans @configuration_IAM_policies, qui était plutôt Not Applicable dans notre cas - des processus et outils tels que CSPM, ou CWPP - "_Cloud Security Posture Management (CSPM) is the process of monitoring cloud-based systems and infrastructures for risks and misconfigurations._" - Microsoft security documentation. - "_Cloud Workload Protection Platform (CWPP) is a cloud security solution that helps protect cloud workloads in multicloud and hybrid environments._" - Microsoft security documentation. - Le _AWS Web Application Firewall (WAF)_ pour filtrer le trafic entrant vers les applications web, définir des règles pour bloquer ou autoriser certaines requêtes en fonction de critères tels que les adresses IP source, les chaînes de caractères ou les en-têtes HTTP. - Nous avons autorisé par défaut les connexion entrantes de toutes les adresses IPv4 car nous avions en tête que notre service allait être accessible depuis n'importe qui, mais cela est sujet à une réflexion qui nous aurait demandé plus de temps, compte tenu de la configuration que nous avons fait jusque-là // https://github.com/orgs/community/discussions/24963 : Deleting a package version for a container on ghcr.io #pagebreak() = Annexes == Configuration d'un "Utilisateur IAM" sur AWS <configuration_IAM_policies> #let simple_agent_policy = insert_code-snippet(title: [Définition d'une politique\ `Simple machine connection Policy`])[```json { "Effect": "Allow", "Action": [ "ec2:Connect" "ec2:DescribeInstances", "ec2:DescribeInstanceStatus" "ec2:DescribeKeyPairs" ], "Resource": "*" } ```] #let deny_everything_policy = insert_code-snippet(title: [Définition d'une politique\ `DenyEverything`])[```json { "Sid": "DenyEverything", "Effect": "Deny", "Action": "*", "Resource": "*" } ```] Ces étapes retracent notre volonté à créer un utilisateur avec des droits restreints qui puissent faire des mises à jour de l'application sur les machines AWS. Seulement, #insert_figure("Interface de connexion à AWS via un utilisateur non administrateur", width: 30%) + Grâce à https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html, on crée une organisation + Ensuite, en s'aidant de https://circleci.com/docs/deploy-to-aws/#create-iam-user et de https://aws.amazon.com/iam/features/manage-users/ et de https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-iam-user-sign-in-tutorial.html, on crée un "compte IAM" sans accès root, qui va mettre d'effectuer les updates mentionnés ci-dessus. - Identifiant `updater_agent` #insert_figure("Création du compte IAM updater_agent", width: 70%) + Activation des "Service Control Policies" (SCP) Définition de politiques "Service Control Policies" (https://us-east-1.console.aws.amazon.com/organizations/v2/home/policies/service-control-policy) #align(center)[#grid(columns: 2, simple_agent_policy, deny_everything_policy)] + (Liaison automatique des politiques à l'organisation) + Liaison manuelle de la politique `Simple machine connection Policy` au compte `updater_agent` + Liaison manuelle de la politique pré-existante `FullAWSAccess` au compte par défaut `php-devops-tp_account` + Liaison manuelle de la politique `DenyEverything` au groupe `Root` + Révocation de la politique pré-existante `FullAWSAccess` du groupe `Root` #insert_figure("Création des Service Control Policies", width: 70%) Maintenant `updater_agent` peut accéder aux machine et s'y connecter (sous réserve de configuration), et `php-devops-tp_account` est toujours administrateur.
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/abstract_de.typ
typst
#set text(lang:"de") Diese Arbeit versucht zwei Indikatoren für die Analyse des öffentlichen Nahverkehrs zu erstellen. Die Indikatoren beruhen dabei auf Ideen aus der Literatur und auf einer Phase explorativer Datenanalyse basierend auf offenen, öffentlich zugänglichen Daten. Die Indikatoren wurden dann anhand einer Fallstudie erprobt. Für die Fallstudie wurde Heidelberg ausgewählt, da zur Auswertung nötigs, lokales Wissen bei der Autor\*in vorhanden waren. Die Indikatoren basieren auf einer interpretation von Erreichbarkeit basierend auf Wegezeiten, einer inversen Closeness-Zentralität. Die Differenz in günstigen und ungünstigen Abfahrtszeiten wurde verwendet, um den Bedarf an Wegeplanung zu operationalisieren. Für die Analyse wurde ein sechseckiges Gitter mit `h3` über Heidelberg gelegt, und mit `r5py` bi-modale Wegezeiten zwischen den einzelnen Zellen berechnet. Populationsdaten wurden verwendet um Zellen zu filtern. In der Literatur fand sich eine Lücke, dass Tagesgänge und zeitliche Änderungen in der Konnektivität selten betrachtet werden. Daher wurden beide Indikatoren für einen Modelltag stündlich berechnet. Der Wegezeiten-Indikator weist erwartbare Muster aus anderen Wegezeiten-Datensätzen auf, muss aber für eine tiefergehende Analyses mit besseren Modell-Wegen unterfüttert werden. Die zeitliche Variation zeigt aber bereits, dass nicht alle Bereiche einer Stadt im Laufe des Tages ähnlich gut angebunden sind, und dass Transportinfrastruktur zu Randzeiten auch areale die sonst weniger gut angebunden sind, in Randzeiten besser anbinden kann als ein Stadtzentrum. Der Planungs-Indikator war aufgrund begrenzter Routenfindungsoptionen schwer zu operationalisieren. Beide Indikatoren aber brauchen aber Verbesserungen oder zusätzliche Indikatoren um ein komplexes öffentliches Nahverkehrsnetz adequat zu beschreiben.
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/utils/assert.typ
typst
#import "/src/packages.typ" as _pkg #let std = assert #let text(name, value) = { if type(value) not in (str, content) { panic(_pkg.oxifmt.strfmt("`{}` must be text, was of type `{}`", name, type(value))) } }
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/grundpositionen/main.typ
typst
Other
#import "/src/template.typ": * = #ix("Grundpositionen der Philosophiedidaktik") #author[<NAME>] #include "historische_standpunkte.typ" #include "grundfragen.typ" #include "selbstverstaendnis.typ" #include "deduktion_induktion_abduktion.typ" #include "thesen.typ" #include "debatten_und_kontroversen.typ" #include "kulturtechnik.typ" #include "muensteraner_erklaerung.typ" #include "dresdner_konsens.typ"
https://github.com/FkHiroki/ex-D2
https://raw.githubusercontent.com/FkHiroki/ex-D2/main/main.typ
typst
MIT No Attribution
// MIT No Attribution // Copyright 2024 <NAME> #import "libs/rsj-conf/lib.typ": rsj-conf #show: rsj-conf.with( // title: [Typst を使った国内学会論文の書き方 \ - 国内学会予稿集に似せたフォーマットの作成 - ], // authors: [◯ 著者姓1 著者名1,著者姓2 著者名2(○○○大学),著者姓3 著者名3 (□□□株式会社)], // abstract: [#lorem(80)], // bibliography: bibliography("refs.bib", full: false) ) // ソースコードブロックを表示するためのパッケージ #import "@preview/sourcerer:0.2.1": code // URL リンクにアンダーラインを入れる #show link: underline // タイトル #align(center, text(18pt, "地球環境科学 期末レポート", weight: "bold")) \ #align(right, text(12pt, "学籍番号: 62217149")) #align(right, text(12pt, "氏名: 福原博樹")) #include "sections/section1.typ" #include "sections/section2.typ" #include "sections/section3.typ" #include "sections/section4.typ"
https://github.com/akagiyuu/math-document
https://raw.githubusercontent.com/akagiyuu/math-document/main/integral/%5Cfrac%7Bsinx%7D%7Bx%7D.typ
typst
#set text(size: 20pt) $ I(t) = integral_0^infinity (sin(x) e^(-t x))/x dif x $ $ arrow.double I'(t) &= -integral_0^infinity sin(x) e^(-t x) dif x \ &= - cal(L)(sin(x)) \ &= - 1/(t^2+1) $ $ arrow.double I(t) = -arctan(t) + c $ $ I(infinity) = 0 $ $ arrow.double I(t) = -arctan(t) + pi/2 $ $ arrow.double integral_0^infinity sin(x)/x dif x = I(0) = pi/2 $
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/tests/utils/token/test.typ
typst
#import "/src/utils/token.typ" #set page(height: 1cm, width: 1cm) // token-eat #assert.eq(token.eat("Foo Bar Baz", "Bar"), (none, "Foo Bar Baz")) #assert.eq(token.eat("Foo Bar Baz", "Foo"), ("Foo", " Bar Baz")) #assert.eq(token.eat("Foo Bar Baz", regex("Fo+")), ("Foo", " Bar Baz")) // token-eat-any #assert.eq(token.eat-any("Foo Bar", ("Bar", "Baz")), (none, "Foo Bar")) #assert.eq(token.eat-any("Foo Bar", ("Foo", "Bar")), ("Foo", " Bar"))
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/040.%20writing44.html.typ
typst
writing44.html Writing, Briefly March 2005 (In the process of answering an email, I accidentally wrote a tiny essay about writing. I usually spend weeks on an essay. This one took 67 minutes—23 of writing, and 44 of rewriting.)I think it's far more important to write well than most people realize. Writing doesn't just communicate ideas; it generates them. If you're bad at writing and don't like to do it, you'll miss out on most of the ideas writing would have generated.As for how to write well, here's the short version: Write a bad version 1 as fast as you can; rewrite it over and over; cut out everything unnecessary; write in a conversational tone; develop a nose for bad writing, so you can see and fix it in yours; imitate writers you like; if you can't get started, tell someone what you plan to write about, then write down what you said; expect 80% of the ideas in an essay to happen after you start writing it, and 50% of those you start with to be wrong; be confident enough to cut; have friends you trust read your stuff and tell you which bits are confusing or drag; don't (always) make detailed outlines; mull ideas over for a few days before writing; carry a small notebook or scrap paper with you; start writing when you think of the first sentence; if a deadline forces you to start before that, just say the most important sentence first; write about stuff you like; don't try to sound impressive; don't hesitate to change the topic on the fly; use footnotes to contain digressions; use anaphora to knit sentences together; read your essays out loud to see (a) where you stumble over awkward phrases and (b) which bits are boring (the paragraphs you dread reading); try to tell the reader something new and useful; work in fairly big quanta of time; when you restart, begin by rereading what you have so far; when you finish, leave yourself something easy to start with; accumulate notes for topics you plan to cover at the bottom of the file; don't feel obliged to cover any of them; write for a reader who won't read the essay as carefully as you do, just as pop songs are designed to sound ok on crappy car radios; if you say anything mistaken, fix it immediately; ask friends which sentence you'll regret most; go back and tone down harsh remarks; publish stuff online, because an audience makes you write more, and thus generate more ideas; print out drafts instead of just looking at them on the screen; use simple, germanic words; learn to distinguish surprises from digressions; learn to recognize the approach of an ending, and when one appears, grab it.Russian TranslationJapanese TranslationRomanian TranslationSpanish TranslationGerman TranslationChinese TranslationHungarian TranslationCatalan TranslationDanish TranslationArabic Translation
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/progress/counters.md
markdown
--- sidebar_position: 1 --- # Touying 的计数器 Touying 的状态均放置于 `states` 命名空间下,包括所有的计数器。 ## slide 计数器 你可以通过 `states.slide-counter` 获取 slide 计数器,并且通过 `states.slide-counter.display()` 展示当前 slide 的序号。 ## last-slide 计数器 因为有些情形下,我们需要为 slides 加入后记,因此就有了冻结 last-slide 计数器的需求,因此这里维护了第二个计数器。 我们可以使用 `states.last-slide-number` 展示后记前最后一张 slide 的序号。 ## 进度 我们可以使用 ```typst #states.touying-progress(ratio => ..) ``` 来显示当前的进度。 ## 后记 你可以使用 ```typst // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide,) = utils.methods(s) #slide[ appendix ] ``` 语法进入后记。 并且 `#let s = (s.methods.appendix-in-outline)(self: s, false)` 可以让后记的 section 不显示在大纲中。
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/baseline_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page Hey #box(baseline: 40%, image("/assets/files/tiger.jpg", width: 1.5cm)) there!