repo
stringlengths
27
90
file
stringlengths
57
176
language
stringclasses
2 values
license
stringclasses
13 values
content
stringlengths
25
180k
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20esterna/Verbali/23-11-15/23-11-15.typ
typst
#import "/template.typ": * #show: project.with( date: "15/11/23", subTitle: "Avvio dell'Analisi dei Requisiti", docType: "verbale", authors: ( "<NAME>", ), externalParticipants : ( (name: "<NAME>", role: "Referente aziendale"), ), timeStart: "10:00", timeEnd: "11:00", location: "Zoom", ); = Ordine del giorno - Approfondimento specifiche del capitolato; - Presentazione, supportata da una board Miro, delle domande raccolte dal gruppo sostanziate con proposte e mock up. Le domande si articolano in: - identificazione della tipologia di utente a cui il prodotto è destinato; - prime proposte di user interface e user experience; - differenza di funzionalità tra applicativo desktop e mobile; - funzionalità desiderate; - API RESTful. - Conferme riguardo lo stack tecnologico individuato; - Scelta del canale di comunicazione preferenziale tra Proponente e Fornitore; - Organizzazione di un prossimo meeting e programmazione regolare degli incontri. \ == Approfondimento specifiche del capitolato Lo scopo del meeting è iniziare l'Analisi dei Requisiti, focalizzando l'attenzione sulla comprensione delle funzionalità richieste, la loro implementazione e il dominio tecnologico che il gruppo utilizzerà. Le domande raccolte dal gruppo sono state catalogate nei seguenti ambiti: - use case; - funzionalità; - user interface e user experience; - stack tecnologico. \ == Presentazione delle domande raccolte dal gruppo in merito ai requisiti === Utente L'utente tipico è stato individuato nella figura di un amministratore e/o impiegato lato back-office, dotato dunque di massimi privilegi durante l'uso dell'applicativo.\ Le principali azioni che tale utente svolgerà sono: - interrogazione del magazzino; - richiesta di spostamento di un prodotto; - zoom e spostamento all'interno dell'ambiente 3D. === User interface & user experience Durante l'incontro si è presentata un'idea generale di possibile user interface. Sono state individuate alcune caratteristiche desiderabili, quali: - esporre con chiarezza le operazioni disponibili all'utente (distinzione evidente tra elementi selezionabili e non); - evitare eccessive animazioni o effetti _lampeggianti_; - evidenziare in modo chiaro gli elementi ricercati (ad esempio riducendo l'opacità degli altri elementi), al fine di non disorientare l'utente; - spostare la telecamera sull'oggetto ricercato (se singolo); - essenziale che la ricerca non modifichi la struttura visualizzata del magazzino. === Differenze tra applicativo desktop e mobile Durante la riunione è emerso che vi saranno delle differenze tra la versione desktop e la versione mobile. L'accesso completo alla funzionalità (esempio richiesta di spostamento di prodotti) sarà fornito per la versione desktop, mentre la versione mobile presenterà delle funzioni limitate (ad esempio solo visualizzazione e ricerca). In ogni caso, il gap funzionale tra dispositivi rimane ancora da definire nel dettaglio. L'applicativo sarà responsive. === Funzionalità desiderate Da una prima analisi sono emerse le principali funzionalità desiderate, quali: - creazione dell'ambiente 3D del magazzino, articolata in: - definizione dei parametri dimensionali del magazzino ; - creazione e posizionamento nello spazio degli scaffali; - definizione dei bin, ovvero le locazioni capaci di accogliere i prodotti; - caricamento dei dati da un database per la popolazione del magazzino; - interrogazione del magazzino mediante ricerche per ID, nome, o caratteristiche dei prodotti; - evidenziazione dei prodotti ricercati mediante effetti visivi (ad esempio cambio del colore) e/o spostamento della telecamera; - invio di notifiche mediante la chiamata a API RESTful per lo spostamento di prodotti nel magazzino. Durante l'analisi del processo di configurazione si è chiarito che il primo passaggio di configurazione riguarda la definizione della geometria del magazzino. Per un magazzino a pianta rettangolare, la geometria può essere definita con tre parametri (lunghezza, larghezza, altezza); per scenari più complessi, il software deve essere in grado di definire la geometria del magazzino dai \<path\> contenuti in un file SVG caricato dall'utente. Successivamente, vengono caricati i dati presenti nel DB. Il database non impone vincoli strutturali, ma è pensato per interfacciarsi con la struttura determinata in fase di creazione. === API RESTful Per l'invio delle notifiche di richiesta di spostamento, l'applicativo si interfaccerà con delle API RESTful. È emerso che l'implementazione di tali API non è di interesse del capitolato, e per tale motivazione possiamo procedere ad una simulazione del comportamento delle stesse con assunzioni riguardo i parametri e le risposte. Ad esempio per lo spostamento di un elemento da un bin ad un altro: - invio all'API delle coordinate di partenza (es: scaffale) e delle coordiante d'arrivo (un altro scaffale) e il prodotto interessato; - l'API risponde: - stato 200 (contatto con l'API avvenuto con successo): spostamento richiesto con successo; - stato 200 (contatto con l'API avvenuto con successo): spostamento non possibile; - risposte alle interrogazioni ottenuta in formato JSON; - la logica di controllo della facoltà di spostare un prodotto è gestita interamente dall'endpoint REST. \ == Conferme riguardo lo stack tecnologico individuato Lo stack tecnologico individuato dal gruppo si articola in: - DB SQL per la gestione del database relazionale; - Three.js per l'implementazione della parte grafica (JavaScript o TypeScript); - Node.js per la comunicazione tra applicativo e database; - Docker per la containerizzazione del prodotto. Lo stack tecnologico discusso rappresenta un punto di partenza, ma è soggetto a modifiche. Ad ogni modo, al momento, le tecnologie individuate e proposte hanno trovato l'approvazione del Proponente. In merito all'utilizzo di JavaScript o TypeScript ed eventuali framework per il lato front end (ad esempio React, Angular), il Proponente ha lasciato la massima libertà al Gruppo. L'azienda Proponente utilizza internamente TypeScript e Angular. \ == Stabilimento delle metodologie di contatto Il Proponente ha confermato l'intenzione di proseguire i contatti mediante l'uso di posta elettronica. \ == Organizzazione di un prossimo meeting e programmazione regolare degli incontri L'incontro si è concluso con la programmazione del prossimo meeting in data 23 novembre 2023, dalle ore 14:00 alle ore 15:00.\ In questa prima fase di Analisi dei Requisiti, Proponente e Fornitore si sono trovati d'accordo circa la necessità di svolgere incontri con cadenza almeno settimanale. \ = Azioni da intraprendere A seguito del meeting sono state individuate le seguenti operazioni da svolgere: - raccolta e catalogazione di aspettative e bisogni; - produzione della documentazione quale use cases, Analisi dei Requisiti da presentare al prossimo meeting; - esplorazione del dominio tecnologico.
https://github.com/fredguth/abnt-typst
https://raw.githubusercontent.com/fredguth/abnt-typst/main/main.typ
typst
#import("./templates/abnt_template.typ"):template #show: template #include("./cap1.typ") #include("./cap2.typ") #include("./cap3.typ") #include("./cap4.typ") #include("./cap5.typ")
https://github.com/jamesrswift/frackable
https://raw.githubusercontent.com/jamesrswift/frackable/main/docs/manual.typ
typst
The Unlicense
#import "@preview/tidy:0.3.0" #import "@preview/mantys:0.1.4": * #import "/src/lib.typ": frackable, generator #let package = toml("/typst.toml").package #let docs = tidy.parse-module(read("/src/impl.typ"), scope: (frackable: frackable, generator: generator),) #titlepage( package.name, [Frackable], // title [<NAME>], //subtitle none, //description, package.authors, (package.repository,), package.version, datetime.today(), none, // abstract, package.license, toc: false, ) #tidy.show-module(docs, style: tidy.styles.default)
https://github.com/astro-group-bristol/paper-management
https://raw.githubusercontent.com/astro-group-bristol/paper-management/main/presentation/tamburlaine.typ
typst
Other
#import "@preview/polylux:0.3.1": * #let date = datetime(year: 2024, month: 9, day: 27) // colour configurations #let SECONDARY_COLOR = rgb("#f6f0e0").lighten(60%) #let PRIMARY_COLOR = rgb("#be2b31") #let TEXT_COLOR = black.lighten(13%) #let tamburlaine-theme(aspect-ratio: "4-3", body) = { set page( paper: "presentation-" + aspect-ratio, fill: SECONDARY_COLOR, margin: 0.7em ) set text(fill: TEXT_COLOR, size: 25pt, font: "NimbusSanL") body } #let title-slide( title: none, title_size: 80pt, authors: (), where: none, content ) = { set page( fill: SECONDARY_COLOR, margin: (top: 0em, left: 0em, right: 0em, bottom: 0em), ) set text(fill: TEXT_COLOR, weight: "bold") let pretty-title = move(dx: 0.5em, rect(outset: (top: 6pt, right: 6pt, left: 34pt, bottom: 34pt), stroke: PRIMARY_COLOR + 4pt, rect(outset: (top: 4pt, right: 4pt, left: 22pt, bottom: 22pt), stroke: PRIMARY_COLOR + 4pt, rect(outset: (top: 2pt, right: 2pt, left: 12pt, bottom: 12pt), stroke: PRIMARY_COLOR + 4pt, rect(outset: (top: 0pt, right: 0pt, left: 4pt, bottom: 4pt), stroke: PRIMARY_COLOR + 4pt, block(width: 85%, fill: PRIMARY_COLOR, inset: (top: 0em, bottom: 0.0em, left: 1em, right: 2em), par(leading: 10pt)[ #text(weight: "black", size:title_size, fill: SECONDARY_COLOR)[#title] ])))))) let author = authors.join(h(1em)) logic.polylux-slide[ #v(1.5em) #align(center)[ #pretty-title ] #v(1.5em) #rect(inset: (top: 0em, left: 1em, right: 1em), width:100%, stroke:none, fill: SECONDARY_COLOR)[ #grid( columns: (50%, 1fr), row-gutter: 3pt, author, align(right, where), align(left, text(size: 20pt, weight: "regular")[]), align(right, text(size: 20pt, weight: "regular", [#date.display("[day] [month repr:long] [year]") / Bristol] )), ) #v(-1.5em) #content #v(-0.5em) ] ] } #let subtitle-slide( title_size: 80pt, title, ) = { set page( fill: SECONDARY_COLOR, margin: (top: 0em, left: 0em, right: 0em, bottom: 0em), ) set text(fill: TEXT_COLOR, weight: "bold") let pretty-title = move(dx: 0.5em, rect(outset: (top: 6pt, right: 6pt, left: 34pt, bottom: 34pt), stroke: PRIMARY_COLOR + 4pt, rect(outset: (top: 4pt, right: 4pt, left: 22pt, bottom: 22pt), stroke: PRIMARY_COLOR + 4pt, rect(outset: (top: 2pt, right: 2pt, left: 12pt, bottom: 12pt), stroke: PRIMARY_COLOR + 4pt, rect(outset: (top: 0pt, right: 0pt, left: 4pt, bottom: 4pt), stroke: PRIMARY_COLOR + 4pt, block(width: 85%, fill: PRIMARY_COLOR, inset: (top: 0em, bottom: 0.5em, left: 1em, right: 2em), par(leading: 10pt)[ #text(weight: "black", size:title_size, fill: SECONDARY_COLOR)[#title] ])))))) logic.polylux-slide[ #set align(horizon) #v(-3em) #align(center)[ #pretty-title ] ] } #let slide(foreground: TEXT_COLOR, background: SECONDARY_COLOR, title: none, body) = { set page( fill: background, margin: (bottom: 1.5em) ) let footer = locate( loc => { block( stroke: ( top: 1mm + PRIMARY_COLOR ), width: 100%, inset: ( y: .5em ), text(fill: foreground, .5em, { "CC BY-SA 4.0 <NAME>" h(2em) "/" h(2em) "Astro Dev Group" h(2em) "/" h(2em) date.display("[day] [month repr:long] [year]") h(1fr) logic.logical-slide.display() }) ) }) set page( footer: footer, footer-descent: 0em, header-ascent: 1.5em, ) let content = { block(outset: 0.8em, width: 100%, fill: PRIMARY_COLOR, spacing: 0.8em, par(leading: 10pt, text(fill: SECONDARY_COLOR, size: 50pt, weight: "black", title))) v(0.3em) body } logic.polylux-slide(content) } #let _setgrp(img, grp, display:true) = { let key = "id=\"" + grp + "\"" let pos1 = img.split(key) if display { pos1.at(1) = pos1.at(1).replace("display:none", "display:inline", count:1) } else { pos1.at(1) = pos1.at(1).replace("display:inline", "display:none", count:1) } pos1.join(key) } #let setgrp(img, ..grps, display: true) = { grps.pos().fold(img, (acc, grp) => { _setgrp(acc, grp, display: display) }) } #let animsvg(img, display_callback, ..frames, handout: false) = { let _frame_wrapper(_img, hide: (), display: ()) = { setgrp((setgrp(_img, ..hide, display: false)), ..display, display: true) } if handout == true { let final_image = frames.pos().fold(img, (im, args) => _frame_wrapper(im, ..args)) display_callback(1, final_image) } else { let output = () let current_image = img for args in frames.pos().enumerate() { let (i, frame) = args current_image = _frame_wrapper( current_image, ..frame ) let this = display_callback(i + 1, current_image) output.push(this) } output.join() } } #let cbox(content, ..args) = rect(radius: 3pt, outset: 5pt, ..args, content)
https://github.com/bigskysoftware/hypermedia-systems-book
https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/lib/definitions.typ
typst
Other
#let leading = 0.6em #let body-font = "Linux Libertine" #let secondary-font = "Linux Biolinum" #let display-font = "Jaro" #let mono-font = "Berkeley Mono" #import "./indexing.typ": * #let part-heading(it) = [ #page([], header: none, footer: none) #pagebreak(to: "odd") #align(horizon)[ #set par(leading: 5pt, justify: false) #set text(size: 32pt, font: display-font) #text(fill: luma(140))[ #it.at("supplement", default: none) #counter(heading).display("I") ] #linebreak() #it.body #metadata("")<heading-here> ] ] #let chapter-heading(it) = [ #page([], header: none, footer: none) #pagebreak(to: "odd") #v(3in) #set par(justify: false) #set text(size: 22pt, font: display-font) #block({ if it.at("numbering") != none { text(fill: luma(140), { it.supplement [ ] str(counter(heading).get().at(1)) }) linebreak() } it.body [#metadata("")<heading-here>] }) ] #let asciiart(..args, source) = figure({ set text(size: .8em) set par(leading: .5em) block(breakable: false, align(start, raw(source, block: true))) }, kind: image, ..args) #let blockquote = quote.with(block: true) #let sidebar(title, body) = [#block( spacing: 1em, block( width: 100%, inset: 1em, stroke: (top: 1pt, bottom: 1pt), fill: luma(237), breakable: true, )[ #set text(.8em, font: secondary-font) #if title != [] { block( breakable: false, strong(title) ) } #block(spacing: 1em, body) ], )<sidebar>] #let important(title, body) = [#block( spacing: 1em, block( width: 100%, inset: 1em, stroke: ( top: (thickness: 1pt, paint: blue), bottom: (thickness: 1pt, paint: blue), ), fill: rgb("#def"), breakable: true, )[ #set text(.8em, font: secondary-font) #block( breakable: false, strong(title) + v(4em) ) #v(-4em) #block(spacing: 1em, body) ], )<important>] #let html-note(label: [HTML Notes], title, body) = [#block( spacing: 1em, block( width: 100%, inset: 1em, stroke: (top: 1pt, bottom: 1pt), fill: rgb("#f5f5ff"), breakable: true, )[ #set text(.8em, font: secondary-font) #show heading: set text(1em) === #label: #title #body ], )<html-note>] #let skew(angle, vscale: 1, body) = { let (a, b, c, d) = (1, vscale * calc.tan(angle), 0, vscale) let E = (a + d) / 2 let F = (a - d) / 2 let G = (b + c) / 2 let H = (c - b) / 2 let Q = calc.sqrt(E * E + H * H) let R = calc.sqrt(F * F + G * G) let sx = Q + R let sy = Q - R let a1 = calc.atan2(F, G) let a2 = calc.atan2(E, H) let theta = (a2 - a1) / 2 let phi = (a2 + a1) / 2 set rotate(origin: bottom + center) set scale(origin: bottom + center) rotate(phi, scale(x: sx * 100%, y: sy * 100%, rotate(theta, body))) }
https://github.com/mgoulao/IST-MSc-Thesis-Typst-Template
https://raw.githubusercontent.com/mgoulao/IST-MSc-Thesis-Typst-Template/main/template.typ
typst
#let heading_style(it) = { // Set chapter locate(loc => { let heading_number = counter(heading).at(loc).at(0) if it.level == 1{ if heading_number != 0 { pagebreak() align(right, grid(rows: (140pt,auto), text(140pt, fill: rgb("#999999"), counter(heading).display()), text(28pt, it.body) ) ) pagebreak() } else { pad( bottom: 50pt, text(30pt, it)) } // Increase figures counter // counter(figure).step(level: 1) } else if it.level <= 3 { pad( top: 10pt, bottom: 10pt, text(14pt, it) ) } else if it.level > 3 { // Set run-in subheadings, starting at level 4. parbreak() text(11pt, style: "italic", weight: "regular", it.body + ".") } else { it } }) } #let project( school_logo: none, cover_image: none, title: "", subtitle: "", author: "", degree: "", supervisors: (), committee: (), date: "", abstract: [], abstract_pt: none, custom_sections: (), body, ) = { // Set the document's basic properties. set document(author: author, title: title) set page( margin: (left: 20mm, right: 20mm, top: 20mm, bottom: 20mm), ) set text(font: "Source Sans Pro", lang: "en") set heading(numbering: "1.1") //set figure(numbering: "1.1") //show figure.where(kind: table): it => { // counter(figure.where(kind: table)).step(level: 1) // it //} show heading: heading_style // Table of content and lists style show outline: it => { show heading: set text(fill: rgb("#000")) set text(fill: rgb("#666666"), weight: 500) it } // Set a heading style for bibliography show bibliography: it => { show heading: it_heading => { pagebreak() pad( bottom: 50pt, text(30pt, it_heading.body) ) } it } // Cover page // Title page. // The page can contain a logo if you pass one with `logo: "logo.png"`. if school_logo == none { school_logo = "images/ist-logo.png" } image(school_logo, height: 20mm, width: auto) v(8mm) // Image if cover_image != none and cover_image.trim().len() > 0 { pad(bottom: 10mm, image(cover_image) ) } else { v(58mm) } align(center, { block( width: 80%, { // Title text(16pt, weight: "bold", [This is the Title of the Thesis and it is a very Big Title covering More than One Line]) // Subtitle if subtitle.trim().len() > 0 { pad( top: 0.8em, text(14pt, subtitle) ) } // Author information. pad( top: 3.2em, text(16pt, weight: "bold", author) ) // Thesis information. pad( top: 3.2em, { text(12pt, [Thesis to obtain the Master of Science Degree in]) linebreak() v(1.8em) text(16pt, weight: "bold", degree) }) // Supervisor information if supervisors.len() > 0 { pad( top: 1.8em, text(12pt, { if supervisors.len() > 1 { [Supervisors: ] } else { [Supervisor: ] } supervisors.join([ \ ]) }) ) } // Committee information. if committee.len() > 0 { pad(top: 1.2em, text(14pt, weight: "bold", [Examination Committee])) pad( top: 1.2em, grid( rows: (auto,) * calc.min(3, committee.len()), gutter: 0.5em, ..committee.map(member => text(12pt, member.role + [: ] + member.name)), ), ) } }) }) // Date align(center + bottom, pad( top: 4em, text(14pt, weight: "bold", date) ) ) pagebreak() // End of cover page counter(page).update(0) set page( margin: (left: 25mm, right: 25mm, top: 30mm, bottom: 30mm), footer: [ #set align(center) #set text(12pt, weight: "bold") #counter(page).display( "i", ) ], number-align: center, ) // Custom sections (Ackowledgments, Declarations, etc.) // Abstract page. v(1fr) heading(outlined: false, numbering: none, text(0.85em)[Abstract]) align(left)[ #set par(justify: true) #abstract ] v(1.618fr) pagebreak() if abstract_pt != none { v(1fr) heading(outlined: false, numbering: none, text(0.85em)[Resumo]) align(left)[ #set par(justify: true) #abstract_pt ] v(1.618fr) pagebreak() } // Table of contents. outline(depth: 4, indent: true) pagebreak() // Figure listing outline( title: [List of Figures], target: figure.where(kind: image), ) pagebreak() // Table listing outline( title: [List of Tables], target: figure.where(kind: table), ) // Reset page counter and make a empty page with no number set page( footer: [] ) pagebreak() counter(page).update(0) // Main content set page( margin: (left: 25mm, right: 25mm, top: 30mm, bottom: 30mm), footer: [ #set align(center) #set text(12pt, weight: "bold") #counter(page).display( "1", ) ], number-align: center, ) // Main body. set par(justify: true) body } #let appendices(body) = { counter(heading).update(0) counter("appendices").update(1) set heading( numbering: (..nums) => { let vals = nums.pos() let value = "ABCDEFGHIJ".at(vals.at(0) - 1) if vals.len() == 1 { return value } else { return value + "." + nums.pos().slice(1).map(str).join(".") } } ); [#pagebreak() #body] }
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Sup.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: "Maths Sup", authors: ( "<NAME>", ), date: "30 Octobre, 2023", ) #set heading(numbering: "1.1.") == Ressources <ressources> - #link("Maths_Sup_Course.pdf")[MathsSup] - #link("coursMP2I-analyse.pdf")[Cours MPSI/MP2I Analyse] - #link("http://alain.troesch.free.fr/")[Cours de mathématique MPSI] - #link("http://christophebertault.fr/cours-et-exercices/")[Christophe Bertault] - #link("https://groupe-reussite.fr/ressources/cours-en-ligne-maths-sup-maths/")[Groupe Réussite] #link("Maths.pdf")[Maths]
https://github.com/arthurcadore/eng-telecom-workbook
https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/COM_1/homework4/homework.typ
typst
MIT License
#import "@preview/klaro-ifsc-sj:0.1.0": report #import "@preview/codelst:2.0.1": sourcecode #show heading: set block(below: 1.5em) #show par: set block(spacing: 1.5em) #set text(font: "Arial", size: 12pt) #show: doc => report( title: "Modulação e Demodulação em Frequência (FM)", subtitle: "Sistemas de Comunicação I", authors: ("<NAME>",), date: "09 de Abril de 2024", doc, ) = Introdução O objetivo deste relatório é apresentar o desenvolvimento de um sistema de modulação e demodulação em frequência (FM) para sinais de áudio. O sistema foi desenvolvido através de linguagem MATLAB (Octa ve), e tem como objetivo principal a compreensão do processo de modulação e demodulação em frequência, bem como a análise dos sinais modulados e demodulados. \ Neste relatório será apresentado a fundamentação teórica do processo de modulação e demodulação em frequência, bem como a análise dos sinais modulados e demodulados, os scripts MATLAB utilizados e os resultados obtidos. \ Desta forma, poderemos compreender o processo de modulação e demodulação FM, bem como a análise dos sinais modulados e demodulados, e a importância deste processo para a transmissão de sinais de áudio em sistemas de comunicação. = Fundamentação teórica == Principais Conceitos Os principais conceitos teóricos abordados neste relatório são: - Modulação FM: A modulação em frequência (FM) é um processo de modulação em que a frequência da portadora é variada de acordo com a amplitude do sinal modulante. A variação da frequência da portadora é proporcional à amplitude do sinal modulante, resultando em um sinal modulado em frequência. A modulação em frequência é amplamente utilizada em sistemas de comunicação para transmissão de sinais de áudio, devido à sua alta qualidade de áudio e baixa interferência. - Demodulação FM: A demodulação em frequência é o processo de recuperar o sinal modulante original a partir do sinal modulado em frequência. A demodulação FM é realizada através da diferenciação do sinal modulado, que resulta em um sinal que contém a informação de frequência do sinal modulante original. O sinal demodulado é então filtrado para remover as frequências indesejadas e obter o sinal de áudio original. - Sinal Portador: O sinal portador é um sinal (tipicamente de alta frequência) que é modulado pela informação do sinal modulante. O sinal portador é a base para a transmissão do sinal modulado em frequência e é recuperado na demodulação para obter o sinal de áudio original. - Sinal Modulante: O sinal modulante é o sinal de áudio que é modulado em frequência para transmissão em sistemas de comunicação. O sinal modulante é a informação que é transmitida através da variação da frequência da portadora. == Resumo dos Itens abordados (Material de Referência) Além dos conceitos base apresentados acima, o material de referência também aborda os seguintes tópicos, que são importantes para o entendimento do processo de modulação e demodulação em frequência (itens 9.1, 9.2, 9.3 e 9.4). === The history of the FM Standard Objetivo: Apresentar a modulação em frequência (FM) e sua importância para a transmissão de sinais de áudio em sistemas de comunicação. \ Nesta sessão do livro, o autor apresenta a história da modulação em frequência (FM) e sua importância para a transmissão de sinais de áudio em sistemas de comunicação. O nacimento da modulação em frequência ocorreu em 1933 com o americano <NAME>, que desenvolveu e demonstrou a rádio FM como uma solução para o "problema do ruído estático". \ Em 1912, <NAME> descobriu que, se as ondas eletromagnéticas emitidas pelos receptores de rádio (de válvula de vidro) fossem alimentadas de volta através do hardware (circuito de RF), a intensidade do sinal aumentava, e assim, ondas de rádio eram geradas. \ De acordo com o livro, ele chamou esse processo de feedback positivo de regeneração, e é considerado uma das descobertas mais importantes na história do rádio, pois significava que receptores de rádio também poderiam ser usados como transmissores. === The mathematics of FM & the Modulation Index Objetivo: Apresentar a matemática da modulação em frequência (FM) e o índices de modulação FM. Nesta sessão, o autor explica sobre a construção de um modulador FM analógico através de um VCO (Voltage Controller Oscillator). O VCO gera um sinal senoidal cuja fase (e, portanto, efetivamente a frequência) muda em resposta a variações de amplitude de um sinal de controle de entrada. \ Quando o sinal modulante é inserido no VCO, ele é multiplicado por uma constante (k_f) que representa a relação de variação de tensão proporcional a variação de frequência. \ Assim, conforme o sinal modulante varia (supondo uma senoide por exemplo), o sinal modulado tem sua frequência variada na mesma proporção que a variação de tensão ao longo do tempo. \ A fase do senoide é determinada pelo valor instantâneo de tensão do sinal modulante, e a frequência do sinal modulado é determinada pela taxa de variação da fase do sinal modulante. === FM Signal Bandwidth Objetivo: Apresentar a largura de banda do sinal FM e as diferenças entre NFM (Narrowband FM) e WFM (Wideband FM). Nesta sessão, o autor apresenta a largura de banda do sinal FM e as diferenças entre NFM (Narrowband FM) e WFM (Wideband FM). A largura de banda do sinal FM é determinada pela taxa de variação da frequência do sinal modulante. \ A modulação em frequência é considerada um processo de Banda Estreita ou Banda Larga, e o valor do índice de modulação determina isso. Se o índice de modulação de um sinal FM for << 1, é considerado FM de Banda Estreita (NFM), enquanto se for >> 1, é FM de Banda Larga (WFM). ==== NFM (Narrowband FM): A modulação em frequência de banda estreita (NFM) é caracterizada por um índice de modulação << 1, resultando em um desvio de frequência máximo limitado, geralmente em torno de 5kHz. Neste cenário, as aproximações podem ser feitas para simplificar os cálculos, já que a contribuição da frequência instantânea é negligenciável. A equação de modulação FM pode ser expandida usando identidades trigonométricas apropriadas. A NFM é comumente usada em aplicações como comunicações de rádio bidirecionais e sistemas de rádio de curto alcance, onde a largura de banda é limitada e a fidelidade do sinal é essencial. ==== WFM (Wideband FM): A modulação em frequência de banda larga (WFM) é o padrão usado por estações de rádio comerciais, caracterizado por um índice de modulação >> 1. Neste caso, o desvio de frequência máximo permitido é maior, frequentemente em torno de 75kHz. A WFM oferece uma qualidade de áudio superior à NFM, mas requer uma largura de banda maior. Durante o processo de modulação, são criadas um número infinito de bandas laterais ao redor da frequência da portadora, o que exige uma limitação da largura de banda para evitar interferências entre canais. As estações de rádio FM geralmente são separadas por 0,2MHz nos receptores analógicos devido a essa limitação de largura de banda. === FM Demodulation Using Differentiation Objetivo: Apresentar a demodulação em frequência utilizando a diferenciação do sinal modulado. \ Nesta seção, o autor descreve o processo de demodulação do sinal FM modulado através de diferenciação do sinal recebido. Para o sinal transmitido (e recebido perfeitamente), um novo sinal diferenciado denotado como (onde o traço denota a derivada) é gerado pelo receptor. \ Neste método, o sinal terá a aparência de um sinal AM-DSB-TC no domínio do tempo, pois possui uma envoltória de informação (embora, ao contrário de uma envoltória AM padrão, a frequência do componente da portadora ainda muda). De acordo com o autor, as flutuações nesta envoltória são diretamente proporcionais à frequência instantânea do sinal modulado, que deve ser diretamente proporcional à amplitude do sinal de informação original. \ Se considerarmos que o termo senoidal de alta frequência pode ser removido por um detector de envoltória (utilizado nos scripts matlab descritos neste documento, veja o código abaixo), fica claro que a amplitude da envoltória é diretamente proporcional à amplitude do sinal de informação. Embora tenha um deslocamento DC (e ganho de resultante da constante de modulação FM), o sinal de áudio original pode ser recuperado com precisão.s #sourcecode[```matlab % Calculating the FM demodulation for the modulated signal demodulated_signal = diff(modulated_signal) * fs / k0; demodulated_signal = [demodulated_signal, 0]; % Sinal demodulado % calculating the FFT of the random signal; demodulated_f = fft(demodulated_signal)/length(demodulated_signal); demodulated_f = fftshift(demodulated_f); % Calculating the signal wrap. demodulated_wrap = abs(hilbert(demodulated_signal)); ```] = Análise dos resultados == Sinal de áudio Aleatório: Inicialmente, foi feita a importação de um sinal de áudio para ser utilizado como modulante da portadora em frequência, para transmissão em FM. A figura abaixo mostra o plot do sinal no domínio do tempo, bem como seu respectivo plot do sinal no domínio da frequência. #figure( figure( image("./pictures/timeDomain.png"), numbering: none, caption: [Sinal de entrada no domínio do tempo] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Uma vez com o sinal de entrada definido, a modulação em frequência foi realizada através da integração do argumento de fase da portadora a partir do sinal da modulante, conforme o script abaixo: #sourcecode[```matlab % Creating the FM modulated signal: phase_argument = 2*pi*k_f*cumsum(modulating_signal)*(Ts); modulated_signal = A_carrier * cos(2*pi*f_carrier*t + phase_argument); ```] Onde na figura acima os parâmetros são: - `modulating_signal` é o sinal de áudio importado. - `k_f` é a sensibilidade do modulador para variação de frequência. - `Ts` é o período de amostragem do sinal. - `A_carrier` é a amplitude da portadora - `f_carrier` é a frequência da portadora. - `t` é o vetor de tempo do sinal modulado (utilizado para realizar a modulação em FM). - `phase_argument` é o argumento de fase da portadora do sinal, gerado a partir da integração do sinal modulante. - `modulated_signal` é o sinal modulado em FM. Uma vez com o sinal modulado em FM, podemos compreender o formato do sinal modulado no domínio do tempo e da frequência, conforme a figura abaixo: #figure( figure( image("./pictures/FrequencyDomain.png"), numbering: none, caption: [Sinal modulado em FM no domínio do tempo e da frequência] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Uma vez com o sinal modulado, e multiplexado, podemos transmiti-lo pelo meio físico sem que haja interferência entre cada portadora (idealmente). O sinal no meio físico é ilustrado abaixo em azul. \ #figure( figure( image("./pictures/Modulated.png"), numbering: none, caption: [Sinal modulado e "transmitido" no meio físico] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Na recepção do sinal, precisamos realizar sua demodulação para ter novamente o sinal de áudio original. Para isso, utilizamos um demodulador FM, que é basicamente um circuito que realiza a derivação do sinal modulado, conforme o script abaixo: #sourcecode[```matlab % Calculating the FM demodulation for the modulated signal demodulated_signal = diff(modulated_signal) * fs / k0; demodulated_signal = [demodulated_signal, 0]; % Sinal demodulado % calculating the FFT of the random signal; demodulated_f = fft(demodulated_signal)/length(demodulated_signal); demodulated_f = fftshift(demodulated_f); % Calculating the signal wrap. demodulated_wrap = abs(hilbert(demodulated_signal)); ```] Com o sinal demodulado, utilizamos um filtro passa-baixas para eliminar as frequências indesejadas, e obter o sinal de áudio original. Para isso, foi utilizado um filtro FIR de ordem relativamente alta (neste caso 100), com frequência de corte de 20kHz. A frequência neste script foi fixada em 20kHz, pois trata-se de um sinal de áudio, e portanto, não há informação relevante acima desta frequência para ser capturada. Para verificar se de fato o filtro está atuando corretamente, abaixo está um plot da resposta em frequência do filtro FIR: #figure( figure( image("./pictures/filter.png"), numbering: none, caption: [Resposta em frequência do filtro FIR] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Com o sinal demodulado e filtrado, podemos realizar seu plot no dominio do tempo e também realizar a FFT do sinal para observar as componentes de frequência do sinal demodulado. #figure( figure( image("./pictures/Demodulated.png"), numbering: none, caption: [Sinal demodulado no domínio do tempo] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Como podemos observar, o sinal demodulado é muito semelhante ao sinal de áudio original, com pequenas distorções devido ao processo de modulação e demodulação em frequência. O sinal também foi plotado no dominio do tempo e da frequência, para verificar se o sinal demodulado está correto. #figure( figure( image("./pictures/DemodulatedF.png"), numbering: none, caption: [Sinal demodulado no domínio da frequência] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) == Sinal Senoidal Modulante Devido as variações no processo de modulação e demodulação apresentadas anteriormente, foi feita a análise de um sinal puramente senoidal como modulante em FM, para verificar se o processo de modulação e demodulação em frequência está correto. Inicialmente, foi feita a definição dos parâmetros do sinal modulante e em seguida o plot do mesmo no dominio do tempo e também da frequência: #figure( figure( image("./pictures/timeDomain-Sin.png"), numbering: none, caption: [Sinal senoidal modulante no domínio do tempo e da frequência] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Em seguida, com o sinal modulante definido, foi feita a modulação em frequência do sinal senoidal, note que para esse processo de modulação, o sinal modulante é uma senoide pura, e portanto, o sinal modulado em FM possui uma variação suave e periódica de frequência ao longo do tempo. \ Sendo assim possivel analisar o sinal modulado no dominio do tempo e da frequência, conforme a figura abaixo: #figure( figure( image("./pictures/FrequencyDomain-Sin.png"), numbering: none, caption: [Sinal modulado em FM no domínio do tempo e da frequência] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Com o sinal modulado em FM definido, podemos transmiti-lo pelo meio físico, e realizar a demodulação do sinal para obter o sinal senoidal original. Na recepção, foi feita a demodulação do sinal modulado, e em seguida a filtragem do sinal demodulado para obter o sinal senoidal original, a figura abaixo mostra o sinal demodulado no dominio do tempo: #figure( figure( image("./pictures/Demodulated-Sin.png"), numbering: none, caption: [Sinal demodulado no domínio do tempo] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Novamente, para verificar se o sinal demodulado está correto, foi feita a análise do sinal demodulado no dominio da frequência, conforme a figura abaixo: #figure( figure( image("./pictures/DemodulatedF-Sin.png"), numbering: none, caption: [Sinal demodulado no domínio da frequência] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) = Scripts e Códigos Utilizados: == Definições Iniciais O script abaixo define as variáveis iniciais do sistema, como a amplitude dos sinais, a frequência do sinal modulante, a frequência da portadora, a sensibilidade do modulador para variação de frequência, e o período de amostragem do sinal. #sourcecode[```matlab close all; clear all; clc; pkg load signal; % Altera o tamanho da fonte nos plots para 15 set(0, 'DefaultAxesFontSize', 20); % Defining the signals amplitude. A_modulating = 1; A_carrier = 1; % Defining the signals frequency f_modulating_max = 20000; f_carrier = 80000; % modulator sensibility for frequency variation (Hz/volts) k_f = 2000000; k0 = 2*pi*k_f; % Delta variable, correponding to max frequency variation. d_f = k_f*A_modulating; % Beta variable, correspondig to percentage of frequency variation about the frequency of the modulating. b = d_f/f_modulating_max; % Defining the period and frequency of sampling: fs = 50*f_carrier; Ts = 1/fs; T = 1/f_modulating_max; % Defining the sinal period. t_inicial = 0; t_final = 2; % "t" vector, correspondig to the time period of analysis, on time domain. t = [t_inicial:Ts:t_final]; ```] == Sinal modulante e Modulado FM O script abaixo importa um sinal de áudio para ser utilizado como modulante da portadora em frequência, e em seguida realiza a modulação em frequência do sinal modulante. #sourcecode[```matlab % Import the audioSignal to use as modulating FM signal: [modulating_signal, Hs] = audioread('randomSignal.wav'); modulating_signal = transpose(modulating_signal); % Calculate the number of zeros to be added num_zeros = length(t) - length(modulating_signal); % Add the zeros to the end of the modulating_signal vector modulating_signal = [modulating_signal, zeros(1, num_zeros)]; % Transpose the modulated signal if necessary modulated_signal = transpose(modulating_signal); % Creating the FM modulated signal: phase_argument = 2*pi*k_f*cumsum(modulating_signal)*(Ts); modulated_signal = A_carrier * cos(2*pi*f_carrier*t + phase_argument); % Plot signals on time domain: figure(1) subplot(311) plot(t, (modulating_signal),'b', 'LineWidth', 2) xlim([0.00054 0.00067]) xlabel('Time (s)') ylabel('Amplitude') title('Random Sound Signal (Time Domain)') subplot(312) plot(t, abs(modulating_signal),'r', 'LineWidth', 2) xlim([0.00054 0.00067]) xlabel('Time (s)') ylabel('Amplitude') title('Random Sound Signal - Absolute (Time Domain)') subplot(313) plot(t, modulated_signal,'k', 'LineWidth', 2) xlim([0.00054 0.00067]) xlabel('Time (s)') ylabel('Amplitude') title('Modulated FM Signal (Time Domain)') ```] == FFT dos sinais modulantes O script abaixo calcula a FFT dos sinais modulantes e modulados, e em seguida realiza o plot dos sinais no domínio da frequência. #sourcecode[```matlab % calculating the step of the frequency vector "f" (frequency domain); f_step = 1/t_final; % creating the frequency vector "f" (frequency domain); f = [-fs/2:f_step:fs/2]; % calculating the FFT of the random signal; modulating_f = fft(modulating_signal)/length(modulating_signal); modulating_f = fftshift(modulating_f); % calculating the FFT of the modulated signal; modulated_f = fft(modulated_signal)/length(modulated_signal); modulated_f = fftshift(modulated_f); % Plotting the modulated signal on frequency domain; figure(2) subplot(211) plot(f, abs(modulating_f), 'k', 'LineWidth', 2) xlabel('Frequency (Hz)') ylabel('Amplitude') title('Modulating Signal (Frequency Domain)') xlim([-f_carrier*1.2 f_carrier*1.2]) ylim([0 A_carrier/1000]) subplot(212) plot(f, abs(modulated_f), 'k', 'LineWidth', 2) xlabel('Frequency (Hz)') ylabel('Amplitude') title('Modulated Signal (Frequency Domain)') xlim([-f_carrier*1.2 f_carrier*1.2]) ylim([0 A_carrier/1000]) ```] == Demodulação do sinal e Filtro O script abaixo realiza a demodulação do sinal modulado, e em seguida realiza a filtragem do sinal demodulado para obter o sinal de áudio original. #sourcecode[```matlab % Calculating the FM demodulation for the modulated signal demodulated_signal = diff(modulated_signal) * fs / k0; demodulated_signal = [demodulated_signal, 0]; % Sinal demodulado % Ordem do filtro FIR filtro_ordem = 100; % Frequência de corte do filtro FIR % Como trata-se de um sinal de áudio, a frequência de corte pode ser fixada em 20kHz frequencia_corte = 20000; % Coeficientes do filtro FIR para cada sinal demodulado coeficientes_filtro = fir1(filtro_ordem, frequencia_corte/(fs/2)); % Resposta em frequência do filtro FIR para cada sinal demodulado [H_fir, f_fir] = freqz(coeficientes_filtro, 1, length(t), fs); % Plot da resposta em frequência do filtro: figure(6) plot(f_fir, abs(H_fir), 'r', 'LineWidth', 3) xlim([0 frequencia_corte*1.1]) title('Resposta em Frequência do Filtro FIR') xlabel('Frequência (Hz)') ylabel('Magnitude') ```] == Filtragem e plotagem dos sinais resultantes O script abaixo realiza a filtragem do sinal demodulado, e em seguida realiza o plot dos sinais modulados e demodulados no domínio do tempo e da frequência. #sourcecode[```matlab % Filtragem dos sinais demodulados demodulated_filtered = filter(coeficientes_filtro, 1, demodulated_signal); % calculating the FFT of the random signal; demodulated_filtered_f = fft(demodulated_filtered)/length(demodulated_filtered); demodulated_filtered_f = fftshift(demodulated_filtered_f); % Calculating the signal wrap. demodulated_wrap = abs(hilbert(demodulated_filtered)); % Plotting the modulated and demodulated signals on time domain: figure(3) subplot(311) plot(t, modulated_signal, 'k', 'LineWidth', 2) xlim([0.00054 0.00067]) xlabel('Tempo (s)') ylabel('Amplitude') title('Sinal Modulado FM (Domínio do Tempo)') subplot(312) plot(t, demodulated_signal, 'b', 'LineWidth', 2) xlim([0.00054 0.00067]) xlabel('Tempo (s)') ylabel('Amplitude') title('Sinal Demodulado FM (Domínio do Tempo)') subplot(313) plot(t, demodulated_filtered, 'r--', 'LineWidth', 2) xlim([0.00054 0.00067]) xlabel('Tempo (s)') ylabel('Amplitude') title('Sinal Demodulado FM Filtrado (Domínio do Tempo)') figure(4) subplot(211) plot(f, demodulated_filtered_f, 'k', 'LineWidth', 2) xlabel('Frequency (Hz)') ylabel('Amplitude') title('Demodulated Signal (Frequency Domain)') xlim([-f_carrier*1.2 f_carrier*1.2]) ylim([0 A_carrier/1000]) subplot(212) plot(f, abs(demodulated_filtered_f), 'k', 'LineWidth', 2) xlabel('Frequency (Hz)') ylabel('Amplitude') title('Absolute Demodulated Signal (Frequency Domain)') xlim([-f_carrier*1.2 f_carrier*1.2]) ylim([0 A_carrier/1000]) ```] = Conclusão A partir dos conceitos vistos e dos resultados obtidos, podemos concluir que o processo de modulação e demodulação em frequência é uma tecnica eficiente para a transmissão de sinais de áudio em sistemas de comunicação, pois permite a transmissão de sinais de áudio com qualidade e fidelidade com baixa interência devido a informação estar sendo carregada na variação de frequência e não na amplitude do sinal. Desta forma, podemos compreender seu uso em sistemas de telecomunicação utilizado atualmente pelas rádios analógicas regionais para transmissão de sinais de áudio em broadcast para toda a região, visto que esse tipo de transmissão possui um baixo índice de ruído e distorção. = Referências Para o desenvolvimento deste relatório, foi utilizado o seguinte material de referência: - #link("https://www.researchgate.net/publication/287760034_Software_Defined_Radio_using_MATLAB_Simulink_and_the_RTL-SDR")[Software Defined Radio Using MATLAB & Simulink and the RTL-SDR, de <NAME>]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/vonsim/0.1.0/README.md
markdown
Apache License 2.0
This package adds the ability to syntax highlighting VonSim source code in Typst. ## How to use To add global support for VonSim, just add these lines and use a raw block with `vonsim` as its language. ````typst #import "@preview/vonsim:0.1.0": init-vonsim // Adds global support for VonSim #show: init-vonsim // Highlight VonSim code ```vonsim ; Welcome to VonSim! ; This is an example program that calculates the first ; n numbers of the Fibonacci sequence, and stores them ; starting at memory position 1000h. n equ 10 ; Calculate the first 10 numbers org 1000h start db 1 org 2000h mov bx, offset start + 1 mov al, 0 mov ah, start loop: cmp bx, offset start + n jns finish mov cl, ah add cl, al mov al, ah mov ah, cl mov [bx], cl inc bx jmp loop finish: hlt end ``` ```` Alternatively, use `init-vonsim-full` to also use the VonSim theme.
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DSA/chapters/6树和二叉树.typ
typst
#import "../template.typ": * #import "@preview/pinit:0.1.4": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #import "/book.typ": book-page #show: book-page.with(title: "树和二叉树 | DSA") = 树和二叉树 <树和二叉树> == 树的定义和基本术语 <树的定义和基本术语> #definition[ *树*:树是 $n(n >= 0)$ 个结点的有限集合。当 $n = 0$ 时,称为空树;当 $n > 0$ 时,树具有以下性质: - 有且仅有一个特定的称为根的结点 - 当 $n > 1$ 时,其余结点可分为 $m(m > 0)$ 个互不相交的有限集合 $T_1, T_2, dots, T_m$,其中每一个集合本身又是一棵树,称为根的子树。 ]<树的定义> 对比线性结构和树形结构: #table( columns: (1fr, 1fr), rows: 2em, align: center + horizon, table.header([*线性结构*], [*树形结构*]), [第一个数据元素,无前驱], [根结点,无前驱], [最后一个数据元素,无后继], [多个叶子结点,无后继], [其他数据元素,一个前驱、一个后继], [其他结点,一个双亲、多个孩子], ) === 基本术语 - *结点*:数据元素+若干指向子树的分支 - *结点的度*:结点的*子树*个数(这里和离散数学中的度有所不同) - *树的度*:树中结点的最大度 - *叶子结点*:度为 0 的结点 - *分支结点*:度不为 0 的结点 - (从根结点到某个结点的)*路径*:由从根到该结点所经分支和结点构成 - *层次*:根结点的层次为 1,其余结点的层次等于其双亲结点的层次加 1 - *树的深度*:树中结点的最大层次 - *森林*:$m(m > 0)$ 棵互不相交的树的集合 #note_block[ 任何非空树是一个二元组 $"Tree" = ("root", F)$,其中 $"root"$ 是树的根结点,$F$ 是子树森林。 ] - *有向树*: + 有确定的根结点 + 树根和子树根之间为有向关系 - *有序树*:树中结点的各子树看成是有序的,即子树之间有次序关系 - *无序树*:子树之间无次序关系 == 二叉树 #definition[ *二叉树*:二叉树或为空树,或是由一个根结点加上两棵分别称为左子树和右子树的、互不交的二叉树组成。 ] #note_block[ 度为 2 的树不一定是二叉树。 ] #block(breakable: false)[ #import fletcher.shapes: house, hexagon, ellipse #let blob(pos, label, tint: white, ..args) = node( pos, align(center, label), width: auto, fill: tint.lighten(60%), stroke: 1pt + tint.darken(20%), corner-radius: 5pt, shape: circle, ..args, ) #set figure(supplement: none) 二叉树的五种形态: #grid( columns: (0.8fr, 0.8fr, 1fr, 1fr, 1fr), )[ #figure($diameter$, caption: "空树") ][ #figure(diagram(blob((0, 0), "N")), caption: "只含根结点") ][ #figure(diagram(blob((0, 0), "N"), edge(), blob((-0.5, 0.5), "L")), caption: "右子树为空树") ][ #figure(diagram(blob((0, 0), "N"), edge(), blob((0.5, 0.5), "R")), caption: "左子树为空树") ][ #figure( diagram(blob((0, 0), "N"), edge(), blob((-0.5, 0.5), "L"), edge((0, 0), (0.5, 0.5)), blob((0.5, 0.5), "R")), caption: "左右子树均不为空", ) ] ] === 二叉树的性质 + 在二叉树的第 $i$ 层上至多有 $2^(i-1)$ 个结点($i >= 1$)。 + 深度为 $k$ 的二叉树至多有 $2^k - 1$ 个结点($k >= 1$)。 + 对任何一棵非空二叉树,若叶子结点数为 $n_0$,度为 2 的结点数为 $n_2$,则 $n_0 = n_2 + 1$。 + 具有 $n$ 个结点的完全二叉树的深度为 $floor(log_2n) + 1$。#definition[ *满二叉树*:每层结点都达到最大值的二叉树。 ] #definition[ *完全二叉树*:树中所含的 $n$ 个结点和满二叉树中编号为 $1$ 至 $n$ 的结点一一对应。 ] #note_block[ 完全二叉树不一定是满二叉树,但是满二叉树一定是完全二叉树。 判断一棵树是否是完全二叉树: - 从根结点开始,按层序编号 - 若某个结点有右孩子而无左孩子,则不是完全二叉树 - 若某个结点不是左右孩子都有,则其后的结点都是叶子结点 ] + 一棵有 $n$ 个结点的完全二叉树,按层序编号,对任一结点 $i$ 有: - 若 $i = 1$,则 $i$ 是根,无双亲;否则其双亲是 $floor(i/2)$。 - 若 $2i > n$,则 $i$ 无左孩子;否则左孩子是 $2i$。 - 若 $2i + 1 > n$,则 $i$ 无右孩子;否则右孩子是 $2i + 1$。 == 二叉树的存储结构 === 顺序存储结构 简单来说就是用数组存储二叉树的结点,按照完全二叉树的结构存储。 根节点存储在数组下标为 0 的位置,然后每个结点的左孩子存储在 $2i + 1$ 的位置,右孩子存储在 $2i + 2$ 的位置,$i$ 表示该结点在数组中的下标。同样的,如果知道一个结点的下标,可以通过 $floor((i-1)/2)$ 找到其双亲结点。 === 链式存储结构 ==== 二叉链表 结点结构: #table(columns: ((5em, 4em, 5em)), rows: 2em, align: center + horizon, [lchild], [data], [rchild]) #figure(image("../assets/2024-06-25-16-13-50.png", width: 80%), caption: "二叉链表") ==== 三叉链表 比二叉链表多了一个指向双亲结点的指针。 #table(columns: ((5em, 5em, 4em, 5em)), rows: 2em, align: center + horizon, [parent], [lchild], [data], [rchild]) #figure(image("../assets/2024-06-25-16-15-02.png", width: 80%), caption: "三叉链表") == 二叉树的遍历 === 先序遍历 先访问根结点,然后依次先序遍历左子树和右子树。 #note_block[ 若二叉树为空树,则空操作;否则, + 访问根结点; + 先序遍历左子树;(递归) + 先序遍历右子树。(递归) ] 非递归实现: ```c void PreOrder(Bitree T) { Stack S; InitStack(S); Bitree p = T; while (p || !StackEmpty(S)) { if (p) { visit(p->data); Push(S, p); p = p->Lchild; } else { Pop(S, p); p = p->Rchild; } } } ``` === 中序遍历 先中序遍历左子树,然后访问根结点,最后中序遍历右子树。 #note_block[ 若二叉树为空树,则空操作;否则, + 中序遍历左子树;(递归) + 访问根结点; + 中序遍历右子树。(递归) ] 非递归实现: ```c void InOrder(Bitree T) { Stack S; InitStack(S); Bitree p = T; while (p || !StackEmpty(S)) { if (p) { Push(S, p); p = p->Lchild; } else { Pop(S, p); visit(p->data); p = p->Rchild; } } } ``` === 后序遍历 先后序遍历左子树,然后后序遍历右子树,最后访问根结点。 #note_block[ 若二叉树为空树,则空操作;否则, + 后序遍历左子树;(递归) + 后序遍历右子树;(递归) + 访问根结点; ] 非递归实现: ```c void PostOrder(Bitree T) { Stack S; InitStack(S); Bitree p = T; Bitree r = NULL; while (p || !StackEmpty(S)) { if (p) { Push(S, p); p = p->Lchild; } else { GetTop(S, p); if (p->Rchild && p->Rchild != r) { p = p->Rchild; } else { Pop(S, p); visit(p->data); r = p; p = NULL; } } } } ``` == 线索二叉树 结点结构: #table(columns: ( (5em, 4em, 5em, 4em, 5em) ), rows: 2em, align: center + horizon, [lchild], [ltag], [data], [rtag], [rchild]) ltag 和 rtag 用来标记是否为线索,即指向前驱和后继的指针。如果为 0,则表示指向孩子结点;如果为 1,则表示指向前驱或后继。 #image("../assets/Threaded_tree.svg", width: 37%) == 树和森林 === 孩子兄弟表示法 #definition[ *孩子兄弟表示法*:以二叉链表作为树的存储结构,称为孩子兄弟表示法。 ] 结点结构: #table(columns: ((5em, 5em, 5em)), rows: 2em, align: center + horizon, [firstchild], [data], [nextsibling]) #image("../assets/2024-06-25-16-37-45.png") === 树的遍历 ==== 先根遍历 若树不空,则先访问根结点,然后依次先根遍历各棵子树。 ==== 后根遍历 若树不空,则依次后根遍历各棵子树,然后访问根结点。 ==== 按层次遍历 若树不空,则从树的第一层(根结点)开始,从上而下、从左至右依次访问各结点。 ==== 应用 *求树深*: ```C int TreeDepth(CSTree T) { if (!T) return 0; else { h1 = TreeDepth(T->firstchild); h2 = TreeDepth(T->nextsibling); return (max(h1 + 1, h2)); } }// TreeDepth ``` *输出所有根到叶子结点的路径*: ```C void AllPath(Bitree T, Stack &S) { /// 输出二叉树上从根到所有叶子结点的路径 if (T) { Push(S, T->data); if (!T->Lchild && !T->Rchild) PrintStack(S); else { AllPath(T->Lchild, S); AllPath(T->Rchild, S); } Pop(S); }// if(T) } // AllPath ``` *输出森林中所有根到叶子结点的路径*: ```C void OutPath(Bitree T, Stack &S) { // 输出森林中所有从根到叶的路径 while (!T) { Push(S, T->data); if (!T->firstchild) Printstack(s); else OutPath(T->firstchild, s); Pop(S); T = T->nextsibling; }// while } // OutPath ``` === 森林的遍历 树的遍历和二叉树的遍历存在对应关系: #table( columns: (1fr, 1fr, 1fr), rows: 2em, align: center + horizon, table.header([*树*], [*森林*], [*二叉树*]), [先根遍历], [先序遍历], [先序遍历], [后根遍历], [中序遍历], [中序遍历], ) ==== 先序遍历森林 若森林不空,则可按下述规则遍历之: + 访问森林中第一棵树的根结点; + 先序遍历森林中第一棵树的子树森林; + 先序遍历森林中(除第一棵树之外)其余树构成的森林。 即依次从左至右对森林中的每一棵树进行先根遍历。 ==== 中序遍历森林 若森林不空,则可按下述规则遍历之: + 中序遍历森林中第一棵树的子树森林; + 访问森林中第一棵树的根结点; + 中序遍历森林中(除第一棵树之外)其余树构成的森林。 即依次从左至右对森林中的每一棵树进行*后根遍历*。 == 哈夫曼树 #definition[ *带权路径长度*(*WPL*):设 $T$ 是一棵有 $n$ 个叶子结点的二叉树,每个叶子结点 $w_i$ 的权值为 $w_i$,从根结点到每个叶子结点 $w_i$ 的路径长度为 $l_i$,则 $T$ 的带权路径长度为 $ "WPL"(T) = sum_(i=1)^(n) w_i times l_i $ ] #definition[ *哈夫曼树*:带权路径长度最短的二叉树称为哈夫曼树。又称*最优二叉树*。 ] #note_block[根节点路径长度为 0,左子树路径长度加 1,右子树路径长度加 1。] *构建*哈夫曼树的算法: 1. 从 $n$ 个权值 $w_1, w_2, dots, w_n$ 的叶子结点出发,构造 $n$ 棵只有一个结点的二叉树。 2. 在 $n$ 棵树中选取两棵根结点的权值最小的树作为左右子树构造一棵新的二叉树,且新的二叉树的根结点的权值为其左右子树根结点的权值之和。#note_block[ 使用最小堆可以快速找到最小的两个树。 ] 3. 从 $n$ 棵树中删除选取的两棵树,并将新构造的二叉树加入到森林中。 4. 重复 2 和 3,直到森林中只有一棵树为止。 而哈夫曼编码就是根据哈夫曼树的路径来编码,路径左边为 0,右边为 1。
https://github.com/DawnEver/ieee-conference-typst-template
https://raw.githubusercontent.com/DawnEver/ieee-conference-typst-template/main/README.md
markdown
MIT License
# IEEE Conference [Typst](https://typst.app) Template I am preparing for IEEE cofference these days. Frustrated with Latex, I choose Typst to rewrite my paper. In fact, typst app provides built-in IEEE paper template and [ieee-typst-template](https://github.com/bsp0109/ieee-typst-template) gives a modified edition for author's requiements, but they are not enough. Based on Word and Latex templates and format guidelines, I diy my Typst template. ## What is Typst Typst is a new markup-based typesetting system that is designed to be as powerful as LaTeX while being much easier to learn and use. - [Typst Github](https://github.com/typst/typst) - [Typst Homepage](https://typst.app) ## Features - IEEE copyright on the first page. - Top captions for tables. - ... ## Preview See the [main.pdf](main.pdf). ![demo.png](demo.png) ## Usage: You can try it online ([Click Me](https://typst.app/project/rgsg7a58qn3fKa7jPhbl2U)) or run locally.I strongly recommand writing with VSCode. ![vscode_preview](vscode_preview.png) ## Contribute Welcome to PRs.
https://github.com/SamK/typst-fonts-showcase
https://raw.githubusercontent.com/SamK/typst-fonts-showcase/master/template.typ
typst
// vim: tabstop=2 softtabstop=2 shiftwidth=2 #let template(title, pangram) = { set page(numbering: "1/1") set text(fallback: false) let list-fonts() = { let fonts = () let lines = read("fonts.txt").split("\n") for this-line in lines { let clean-line = this-line.trim() if clean-line != "" { fonts.push(clean-line) } } fonts } let font-box(font_name) = { heading(numbering: "1. ")[ #text(font: font_name, font_name) #text(size: .8em, weight: "regular", [(#font_name)]) ] set text(font: font_name) pangram } align(center, text(17pt, title)) let all-fonts = list-fonts() [This document shows all the #all-fonts.len() fonts Typst found on your system.] outline() for this-font in all-fonts { font-box(this-font) } }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/km/0.1.0/lib.typ
typst
Apache License 2.0
#let binary-digits(x, digit: 0) = { let digits = range(digit).map(_ => 0) while (x != 0) { digits.insert(digit, calc.rem-euclid(x, 2)) x = calc.div-euclid(x, 2) } return digits.rev().slice(0, digit).rev() } #let gray-code(x) = x.bit-xor(x.bit-rshift(1)) #let karnaugh(labels, minterms, implicants: (), show-zero: false, mode: "code") = { let (X, Y) = range(2).map(i => if (type(labels.at(i)) == str) { // Label extracted from character(s) labels.at(i).clusters().map(x => eval(x, mode: "math")) } else { labels.at(i) } ) // Dimensions: 2^len let row = calc.pow(2, X.len()) let column = calc.pow(2, Y.len()) let cell = ( width: 2.4em, height: 2.4em, ) let gray-codes(till, digit) = range(till).map(i => gray-code(i)).map(code => block(width: cell.width, height: cell.height, inset: cell.height / 9, for digit in binary-digits(code, digit: digit) { math.equation[#digit] } ) ) return table( rows: row + 1, columns: column + 1, inset: 0em, stroke: (x, y) => if (x == 0 or y == 0) { none } else { 1pt }, align: (x, y) => { if (x == 0 and y != 0) { horizon + right } else if (x != 0 and y == 0) { center + bottom } else { horizon + center } }, // Top-left label block block(width: cell.width, height: cell.height, { line(end: (100%, 100%)) let label = ( x: box(for x in Y { x }), y: box(for y in X { y }), ) context place(horizon + center, dx: measure(label.x).width / 2, dy: -0.5em, label.x) context place(horizon + center, dx: -measure(label.y).width / 2, dy: 0.5em, label.y) }), // Horizontal gray code labels ..if mode == "code" { gray-codes(column, Y.len()) }, table.cell(x: 1, y: 1, rowspan: row, colspan: column, block(clip: true, { table( rows: row, columns: column, inset: 0em, align: horizon + center, stroke: 2pt / 3, ..range(row).map(i => range(column).map(j => block(width: cell.width, height: cell.height, { let term = minterms.at(i).at(j) if type(term) == int { if term == 0 { if show-zero { $0$ } } else if term == 1 { $1$ } else { math.ast.small } } else { term } }) ) ).flatten() ) while (implicants.len() > 0) { let implicant = implicants.pop() let (x, y, width, ..) = implicant let height = if implicant.len() == 3 { width } else { implicant.at(3) } place( top + left, dx: y * cell.width, dy: x * cell.height, rect( fill: rgb("#0003"), stroke: 2pt / 3, width: cell.width * width, height: cell.height * height, outset: -cell.height / 9) ) // No need to expand out-of-range rectanges from the expanded rectange if (implicant.len() == 5 and not implicant.at(4)) { continue } // Draw extra out-of-range rectange(s) if x + height > row { implicants.push((row - x - height, y, width, height, false)) if y + width > column { implicants.push((row - x - height, column - y - width, width, height, false)) } } if y + width > column { implicants.push((x, column - y - width, width, height, false)) } } }) ), ..if mode == "code" { gray-codes(row, X.len()) }, ) }
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/dist/0.1.0/src/lib.typ
typst
MIT License
#import "@preview/cetz:0.1.2" /// Returns an object representing mass spectrum content. #let mass-spectrum( data, args: (:) ) = { let prototype = ( // -------------------------------------------- // Public member data // -------------------------------------------- data: data, keys: ( mz: 0, intensity: 1 ), size: (auto, 1), range: (40, 400), style: (:), labels: ( x: [Mass-Charge Ratio], y: [Relative Intensity (%)] ), linestyle: (this, idx)=>{}, // -------------------------------------------- // "Private" member data // -------------------------------------------- axes: ( x: none, y: none ), plot-extras: (this)=>{}, // -------------------------------------------- // Methods // -------------------------------------------- display: (this) => { cetz.canvas({ import cetz.draw: * let (x,y) = (this.setup-axes)(this) cetz.draw.group(ctz=>{ (this.setup-plot)(this, x, y) cetz.axes.axis-viewport(this.size, x, y,{ (this.plot-extras)(this) if this.data.len() > 0 { for (i, row) in data.enumerate() { let x = float(row.at(this.keys.mz)) let y = float(row.at(this.keys.intensity)) (this.display-single-peak)(this, x, x, y) } } }) }) }) }, display-single-peak: (this, idx, mz, intensity) => { if (mz > this.range.at(0) and mz < this.range.at(1) ){ cetz.draw.line( (mz, 0), (rel: (0,intensity)), ..(this.linestyle)(this, idx) ) } }, setup-plot: (this, x, y) => { cetz.axes.scientific( size: this.size, left: y, right: none, bottom: x, top: none, frame: true, label: (offset: 0.3), tick: (length:-0.1) ) }, setup-axes: (this) => { this.axes.x = cetz.axes.axis( min: this.range.at(0), max: this.range.at(1), label: this.labels.x, ) this.axes.y = cetz.axes.axis( min: 0, max: 110, label: this.labels.y, ticks: (step: 20, minor-step: none) ) return this.axes }, get-intensity-at-mz: (this, mz) => { return float( (this.data).filter( it=>float(it.at(this.keys.mz, default:0))==mz ).at(0).at(this.keys.intensity) ) }, callout-above: (this, mz, content: none, y-offset: 1.3em) => { if ( content == none ) { content = mz} return cetz.draw.content( anchor: "bottom", (mz, (this.get-intensity-at-mz)(this, mz)), box(inset: 0.3em, [#content]) ) }, calipers: ( this, start, end, // mass-charge ratios height: none, content: none, stroke: gray + 0.7pt // Style ) => { if (content == none){ content = [-#calc.abs(start - end)] } // Determine height let start_height = (this.get-intensity-at-mz)(this, start) let end_height = (this.get-intensity-at-mz)(this, end) if ( height == none ) { height = calc.max(start_height, end_height) + 5 } let draw-arrow(x, y) = cetz.draw.line( (x - 0.5, y + 2),(x + 0.5, y + 2), stroke: stroke ) // Draw return { // Start : horizontal arrow draw-arrow(start, start_height) draw-arrow(end, end_height) cetz.draw.merge-path({ cetz.draw.line( (start, start_height + 2), (start, height) ) cetz.draw.line((start, height), (end, height)) cetz.draw.line((end, height),(end, end_height + 2)) }, stroke: stroke) // Content cetz.draw.content( ( (start + end) / 2, height), anchor: "bottom", box(inset: 0.3em, content) ) } }, title: (this, content, anchor: "top-left", ..args) => { return cetz.draw.content( anchor: anchor, (this.range.at(0), 110), box(inset: 0.5em, content), ..args ) } ) // Overrides for (key, value) in args.pairs() { prototype.insert(key, value) } // Asserts assert(type(prototype.keys.mz) in (int, str)) assert(type(prototype.keys.intensity) in (int, str)) return prototype } #let MolecularIon(charge:none) = [M#super()[#charge+]]
https://github.com/GYPpro/Java-coures-report
https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/.VSCodeCounter/2023-12-15_05-15-05/details.md
markdown
# Details Date : 2023-12-15 05:15:05 Directory d:\\Desktop\\Document\\Coding\\JAVA\\Rep\\Java-coures-report Total : 52 files, 7709 codes, 180 comments, 1740 blanks, all 9629 lines [Summary](results.md) / Details / [Diff Summary](diff.md) / [Diff Details](diff-details.md) ## Files | filename | language | code | comment | blank | total | | :--- | :--- | ---: | ---: | ---: | ---: | | [README.md](/README.md) | Markdown | 1 | 0 | 2 | 3 | | [README.typ](/README.typ) | Typst | 179 | 2 | 39 | 220 | | [Report/0.typ](/Report/0.typ) | Typst | 48 | 4 | 9 | 61 | | [Report/1.typ](/Report/1.typ) | Typst | 84 | 2 | 23 | 109 | | [Report/10.typ](/Report/10.typ) | Typst | 550 | 4 | 155 | 709 | | [Report/11.typ](/Report/11.typ) | Typst | 1,068 | 17 | 150 | 1,235 | | [Report/2.typ](/Report/2.typ) | Typst | 116 | 2 | 23 | 141 | | [Report/3.typ](/Report/3.typ) | Typst | 306 | 2 | 49 | 357 | | [Report/4.typ](/Report/4.typ) | Typst | 172 | 5 | 38 | 215 | | [Report/5.typ](/Report/5.typ) | Typst | 133 | 2 | 39 | 174 | | [Report/6.typ](/Report/6.typ) | Typst | 736 | 2 | 123 | 861 | | [Report/7.typ](/Report/7.typ) | Typst | 210 | 13 | 45 | 268 | | [Report/8.typ](/Report/8.typ) | Typst | 209 | 5 | 49 | 263 | | [Report/9.typ](/Report/9.typ) | Typst | 384 | 3 | 82 | 469 | | [Report/Java语言 实验报告模板 2023-10-8-20231214155905.typ](/Report/Java%E8%AF%AD%E8%A8%80%20%E5%AE%9E%E9%AA%8C%E6%8A%A5%E5%91%8A%E6%A8%A1%E6%9D%BF%202023-10-8-20231214155905.typ) | Typst | 497 | 1 | 263 | 761 | | [Report/最小费用最大流问题-20231215032417.typ](/Report/%E6%9C%80%E5%B0%8F%E8%B4%B9%E7%94%A8%E6%9C%80%E5%A4%A7%E6%B5%81%E9%97%AE%E9%A2%98-20231215032417.typ) | Typst | 323 | 1 | 205 | 529 | | [rubbish/myIO.java](/rubbish/myIO.java) | Java | 76 | 0 | 17 | 93 | | [sis10/Test.java](/sis10/Test.java) | Java | 18 | 0 | 5 | 23 | | [sis10/myLinearEntire.java](/sis10/myLinearEntire.java) | Java | 41 | 0 | 18 | 59 | | [sis10/myLinearLib.java](/sis10/myLinearLib.java) | Java | 197 | 34 | 13 | 244 | | [sis10/myLinearSpace.java](/sis10/myLinearSpace.java) | Java | 111 | 4 | 18 | 133 | | [sis10/myMatrix.java](/sis10/myMatrix.java) | Java | 267 | 4 | 24 | 295 | | [sis10/myPolynomial.java](/sis10/myPolynomial.java) | Java | 131 | 4 | 21 | 156 | | [sis10/myRealNum.java](/sis10/myRealNum.java) | Java | 58 | 3 | 15 | 76 | | [sis1/basicIO.java](/sis1/basicIO.java) | Java | 26 | 0 | 3 | 29 | | [sis2/Test.java](/sis2/Test.java) | Java | 54 | 0 | 2 | 56 | | [sis2/UIDmanager.java](/sis2/UIDmanager.java) | Java | 138 | 0 | 19 | 157 | | [sis3/Test.java](/sis3/Test.java) | Java | 26 | 5 | 5 | 36 | | [sis3/TrieTree.java](/sis3/TrieTree.java) | Java | 37 | 0 | 6 | 43 | | [sis4/regularExp.java](/sis4/regularExp.java) | Java | 34 | 0 | 4 | 38 | | [sis5/SchoolLib.java](/sis5/SchoolLib.java) | Java | 186 | 31 | 15 | 232 | | [sis5/Student.java](/sis5/Student.java) | Java | 114 | 0 | 24 | 138 | | [sis5/Test.java](/sis5/Test.java) | Java | 18 | 0 | 3 | 21 | | [sis5/course.java](/sis5/course.java) | Java | 76 | 0 | 17 | 93 | | [sis5/score.java](/sis5/score.java) | Java | 107 | 0 | 22 | 129 | | [sis6/segTree.h](/sis6/segTree.h) | C++ | 102 | 12 | 10 | 124 | | [sis7/Test.java](/sis7/Test.java) | Java | 24 | 5 | 5 | 34 | | [sis7/segTree.java](/sis7/segTree.java) | Java | 100 | 3 | 14 | 117 | | [sis8/maxFlow.java](/sis8/maxFlow.java) | Java | 96 | 0 | 13 | 109 | | [sis8/minCost.java](/sis8/minCost.java) | Java | 139 | 0 | 19 | 158 | | [sis8/solution.java](/sis8/solution.java) | Java | 26 | 1 | 3 | 30 | | [sis9/Bed.java](/sis9/Bed.java) | Java | 13 | 0 | 4 | 17 | | [sis9/City.java](/sis9/City.java) | Java | 21 | 0 | 7 | 28 | | [sis9/Constants.java](/sis9/Constants.java) | Java | 10 | 0 | 4 | 14 | | [sis9/Hospital.java](/sis9/Hospital.java) | Java | 49 | 0 | 19 | 68 | | [sis9/Main.java](/sis9/Main.java) | Java | 32 | 0 | 6 | 38 | | [sis9/MoveTarget.java](/sis9/MoveTarget.java) | Java | 28 | 0 | 9 | 37 | | [sis9/MyPanel.java](/sis9/MyPanel.java) | Java | 78 | 2 | 15 | 95 | | [sis9/Person.java](/sis9/Person.java) | Java | 145 | 0 | 36 | 181 | | [sis9/PersonPool.java](/sis9/PersonPool.java) | Java | 38 | 0 | 9 | 47 | | [sis9/Point.java](/sis9/Point.java) | Java | 21 | 0 | 7 | 28 | | [test.java](/test.java) | Java | 56 | 7 | 15 | 78 | [Summary](results.md) / Details / [Diff Summary](diff.md) / [Diff Details](diff-details.md)
https://github.com/protohaven/printed_materials
https://raw.githubusercontent.com/protohaven/printed_materials/main/meta-environments/env-protohaven_policy.typ
typst
// Core colors and fonts for the design identity #let accent_color = rgb("#6EC7E2") #let warning_color = rgb("#900000") #let light_grey = rgb(65%,65%,65%) #let mid_grey = rgb(50%,50%,50%) #let dark_grey = rgb(38%,38%,38%) #let sans_font = ("Noto Sans") #let serif_font = ("Noto Serif") #let mono_font = ("Fira Mono") /* * Renders `content` with the module's text styling. This is useful for content * that is outside of the `template` container but which should be visually consistent. */ #let apply-text-styles(content) = { set text( font: sans_font ) set par( leading: 0.8em, ) show heading.where(level: 1): it => [ // #pagebreak(weak: true) #set text(size: 20pt, font: sans_font, number-type: "lining", weight: "bold",) #block(it.body) ] show heading.where(level: 2): it => text( size: 17pt, font: sans_font, number-type: "lining", weight: "semibold", { v(0.6em) it.body } ) show heading.where(level: 3): it => text( size: 14pt, font: sans_font, number-type: "lining", weight: "semibold", it.body ) show heading.where(level: 4): it => text( size: 12pt, font: sans_font, number-type: "lining", weight: "semibold", it.body ) show link: l => text( font: mono_font, size:10pt, box(width:6.7in)[#l.body] ) show figure: it => align(center)[ #set text(size: 9pt, font: sans_font) #it.body /*#it.supplement*/ #it.caption ] content } #let policy_document( title: "Policy Document", authors: ("Someone","<NAME>"), date: datetime.today(), draft: false, wrapper: apply-text-styles, doc, ) = { set page( background: if draft {rotate(-44deg, {text(160pt, fill: rgb("EEEEEE"), [*DRAFT*]) linebreak() text(60pt, fill: rgb("EEEEEE"), date.display())} )}) set document(title: title, author: authors, keywords: ("protohaven", "policy"), date: date, ) show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } // Title page set text( font: sans_font, ) align(center, image("../images/Protohaven-Logo-Horizontal-Color-959069212.png")) v(1in) stack(dir: ttb, // text(weight: "bold", size: 18pt, mid_grey, smallcaps("Policy Document")), // v(1.2em), text(weight: "bold", size: 36pt, [#title]), v(3em), text(weight: "bold", size: 14pt, [Adoption Date: #date.display("[month repr:long] [day padding:none], [year]")]), v(15em), outline(depth: 2) ) v(1fr) rect(width: 100%, inset: 2em, align(center, "License Information")) pagebreak() // The rest of the content set page( margin: (top: 1in, left: 1in, bottom: 1in, right: 1in), numbering: "1", footer: [ #set text(9pt, style: "italic") #h(1fr) Protohaven Policy Document — #title — #counter(page).display( "1 of 1", both: true, ) ], ) counter(page).update(1) wrapper(doc) }
https://github.com/Shedward/dnd-charbook
https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/game/game.typ
typst
#import "spells.typ": * #import "character.typ": * #import "abilities.typ": * #import "proficiencies.typ": * #import "biography.typ": *
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/raw-03.typ
typst
Other
// Lots of backticks inside. ```` ```backticks``` ````
https://github.com/Coekjan/parallel-programming-learning
https://raw.githubusercontent.com/Coekjan/parallel-programming-learning/master/ex-3/report.typ
typst
#import "../template.typ": * #import "@preview/cetz:0.2.2" as cetz #import "@preview/codelst:2.0.1" as codelst #show: project.with( title: "并行程序设计第 3 次作业(MPI 编程)", authors: ( (name: "叶焯仁", email: "<EMAIL>", affiliation: "ACT, SCSE"), ), ) #let data = toml("data.toml") #let lineref = codelst.lineref.with(supplement: "代码行") #let sourcecode = codelst.sourcecode.with( label-regex: regex("//!\s*(line:[\w-]+)$"), highlight-labels: true, highlight-color: lime.lighten(50%), ) #let batch-of(s) = { let nodes = s.split("x").at(0) let proc-per-node = s.split("x").at(1) (int(nodes), int(proc-per-node)) } #let data-time(raw-data) = raw-data.pairs().map(data => { let (batch, time) = data let (nodes, proc-per-node) = batch-of(batch) ((nodes, proc-per-node), time.sum() / time.len()) }) #let data-speedup(raw-data) = data-time(raw-data).map(data => { let pivot = data-time(raw-data).at(0).at(1) let (batch, time) = data (batch, pivot / time) }) #let data-table(raw-data) = table( columns: (auto, 1fr, 1fr, 0.7fr, 0.7fr, 0.7fr), align: horizon + center, table.header(table.cell(rowspan: 2)[*进程数量*], table.cell(colspan: 2)[*分布情况*], table.cell(rowspan: 2, colspan: 3)[*运行时间(单位:秒)*], [*结点数*], [*进程数/结点数*]), ..raw-data.pairs().enumerate().map(pair => { let (index, pair) = pair let (batch, data) = pair let nodes = batch.split("x").at(0) let proc-per-node = batch.split("x").at(1) let num-proc = int(nodes) * int(proc-per-node) if index == raw-data.keys().enumerate().find(pair => { let (i, batch) = pair let (nodes, proc-per-node) = batch-of(batch) nodes * proc-per-node == num-proc }).at(0) { ( table.cell(rowspan: raw-data.keys().filter(batch => { let (nodes, proc-per-node) = batch-of(batch) nodes * proc-per-node == num-proc }).len(), str(num-proc)), nodes, proc-per-node, data.map(str) ) } else { (nodes, proc-per-node, data.map(str)) } }).flatten() ) #let data-chart(raw-data, width, height, time-max, speedup-max) = cetz.canvas({ let color(index) = { let data = data-time(raw-data).at(index) let (batch, _) = data let (nodes, proc-per-node) = batch let procs = calc.log(nodes * proc-per-node, base: 2) ( fill: (red, orange, yellow, blue, green, purple, lime).at(int(procs)), ) } cetz.chart.columnchart( size: (width, height), data-time(raw-data).map(pair => { let (batch, time) = pair let (nodes, proc-per-node) = batch (rotate(-30deg)[ #set text(size: 0.8em) #nodes#sym.times#proc-per-node ], time) }), y-max: time-max, x-label: [_结点数量 #sym.times 每结点的进程数量_], y-label: [_平均运行时间(单位:秒)_], bar-style: color, ) cetz.plot.plot( size: (width, height), axis-style: "scientific-auto", plot-style: (fill: black), x-tick-step: none, x-min: 0, x-max: data-time(raw-data).len() + 1, y2-min: 1, y2-max: speedup-max, x-label: none, y2-label: [_加速比_], y2-unit: sym.times, cetz.plot.add( axes: ("x", "y2"), data-speedup(raw-data).enumerate().map(pair => { let (i, pair) = pair let (_, speedup) = pair (i + 1, speedup) }), ), ) }) = 实验:矩阵乘法 == 实验内容与方法 使用 MPI 编程实现矩阵乘法的并行加速,并在不同进程数量、不同结点数量下进行实验,记录运行时间并进行分析。 - 矩阵大小:8192 #sym.times 8192 - 矩阵分块算法:给定矩阵 $A$ 与 $B$,计算其乘积 $A B = C$,通过将 $A$ 按行分块来计算,如 @equation:block-matrix 所示。 $ A B = mat(A_1; A_2; dots.v; A_n) B = mat(A_1 B; A_2 B; dots.v; A_n B) = C $ <equation:block-matrix> - 进程数量:1 \~ 64 - 结点数量:1 \~ 64 程序构造过程中有如下要点: + 计算 $A B$ 时,将 $A$ 按行分块而不是将 $B$ 按列分块,使得 MPI 分发数据(地址连续)时更加方便。 + 如 @code:script-code 所示,利用脚本 ```bash matmul.slurm.run``` 指定结点数量与每个结点的进程数量,动态生成 Slurm 作业脚本,运行时指定形如 `SLURM_BATCH=AxB` 的环境变量,可指定 MPI 程序运行于 `A` 个结点、每个结点 `B` 个进程上。例如 ```sh SLURM_BATCH=4x4 ./matmul.slurm.run ``` 指定 MPI 程序运行于 4 个结点、每个结点 4 个进程,共 16 个进程上。 + 为记录排序时间,使用 POSIX 的 ```c gettimeofday()``` 函数; + 为简要地记录矩阵乘法结果(双精度浮点阵列),使用 OpenSSL 的 SHA1 算法计算其指纹。 代码如 @code:matmul-code 所示,其中: - #lineref(<line:mpi-init>)、#lineref(<line:mpi-rank>)、#lineref(<line:mpi-size>) 使用 MPI 进行了初始化、获取进程编号、获取进程数量等操作; - #lineref(<line:mpi-bcast>) 将 $B$ 矩阵广播到所有进程; - #lineref(<line:mpi-scatter-1>)、#lineref(<line:mpi-scatter-2>)、#lineref(<line:mpi-scatter-3>) 将 $A$ 矩阵分块分发到所有进程; - #lineref(<line:mpi-gather-1>)、#lineref(<line:mpi-gather-2>)、#lineref(<line:mpi-gather-3>) 将 $C$ 矩阵收集到进程 0; - #lineref(<line:mpi-finalize>) 结束 MPI。 #figure( sourcecode( raw(read("matmul/matmul.c"), lang: "c"), ), caption: "并行矩阵乘法 MPI 实现代码", ) <code:matmul-code> == 实验过程 在如 @chapter:platform-info 所述的实验平台上进行实验,分别使用 1 \~ 64 个进程(分布在 1 \~ 64 个结点上)进行矩阵乘法,记录运行时间,测定 3 次取平均值,原始数据如 @table:matmul-raw-data 所示。 == 实验结果与分析 #let matmul-speedup-max = data-speedup(data.matmul).sorted(key: speedup => speedup.at(1)).last() 矩阵乘法实验测定的运行时间如 @figure:matmul-chart 中的条柱所示(相同颜色表示相同的总进程数),并行加速比如 @figure:matmul-chart 中的折线所示,其中最大加速比在结点数为 #matmul-speedup-max.at(0).at(0)、每结点的进程数为 #matmul-speedup-max.at(0).at(1) 时(总进程数为 #{matmul-speedup-max.at(0).at(0) * matmul-speedup-max.at(0).at(1)})达到,最大加速比为 #matmul-speedup-max.at(1)。 #figure( data-chart(data.matmul, 12, 8, 600, 60), caption: "矩阵乘法运行时间", ) <figure:matmul-chart> 可见随着进程数量增加,运行时间逐渐减少。具体来说: + 随着总进程数量,运行时间逐渐减少,加速比呈现亚线性规律。加速比未呈现完全线性,可能是因为并行本身存在通信开销。 + 总进程数相同时,进程在集群中的分布情况(结点数量)对运行时间有一定影响,例如: - 当总进程数为 16 时,将 16 个进程分散在 16 个结点上的运行时间较长;当总进程数为 64 时,将 64 个进程分散在 32 个结点(每结点 2 个进程)上的运行时间较长。这可能是因为进程在不同结点间通信时,网络延迟较大。 - 当总进程数为 64 时,将 64 个进程分散在 64 个结点上的运行时间较短。这可能是因为集群中某种拓扑结构使得所分配的 64 个结点互联通信效率较高。 矩阵乘法实验中的原始数据如 @table:matmul-raw-data 所示。 #figure( data-table(data.matmul), caption: "矩阵乘法实验原始数据", ) <table:matmul-raw-data> = 附注 == 编译与运行 代码依赖 MPI、OpenSSL 库,若未安装这些库,需手动安装。在准备好依赖后,可使用以下命令进行编译与运行: - 编译:```sh make```; - 运行:```sh make run ```; - 可通过环境变量 ```SLURM_BATCH``` 指定结点数量与每个结点的进程数量,例如 ```sh SLURM_BATCH=4x4 make run``` 指定 MPI 程序运行于 4 个结点、每个结点 4 个进程,共 16 个进程上。 - 运行结束后若提示错误(检测到指纹错误),则说明运行结果不正确,该检测机制的大致逻辑由 @code:makefile-fingerprint 中的 Makefile 代码给出; #figure( sourcecode( ```make # The fingerprint of the result FINGERPRINT := 00 11 22 33 44 55 66 77 88 99 99 88 77 66 55 44 33 22 11 00 # Run the program `app` and check the fingerprint .PHONY: run run: exec 3>&1; stdbuf -o0 ./app | tee >(cat - >&3) | grep -q $(FINGERPRINT) ``` ), caption: "Makefile 中的指纹检测代码" ) <code:makefile-fingerprint> - 清理:```sh make clean```。 - 将编译产物、Slurm 脚本产生的输出文件全部清除。 其中 ```sh make run``` 实际调用了 ```sh matmul.slurm.run``` 脚本,如 @code:script-code 所示。 #figure( sourcecode( raw(read("matmul/matmul.slurm.run"), lang: "bash"), ), caption: "矩阵乘法运行脚本", ) <code:script-code> == 实验平台信息 <chapter:platform-info> 本实验所处平台为北航校级计算平台,系统配置 260 个 CPU 计算节点,每个节点配置 2 颗 Intel Golden 6240 系列处理器(共 36 物理核)、384 GB 内存。所有节点通过 100Gb/s EDR Infiniband 互联组成计算和存储网络。系统使用 Slurm 作为作业调度系统。
https://github.com/ivaquero/typst-fasvg
https://raw.githubusercontent.com/ivaquero/typst-fasvg/main/README.md
markdown
MIT License
# Typst-FASVG ![code size](https://img.shields.io/github/languages/code-size/ivaquero/typst-fasvg.svg) ![repo size](https://img.shields.io/github/repo-size/ivaquero/typst-fasvg.svg) Offline [FontAwesome](https://fontawesome.com/) Binding for [Typst](https://typst.app/docs/). ## Usage 1. Download the fasvg latest desktop version from [FontAwesome Official Site](https://github.com/FortAwesome/Font-Awesome/releases), unzip it into your workspace folder, and rename it as `fasvg`. 2. Download the `fasvg.typ` file, and place it into your workspace folder as well. 3. Import it into your Typst file, and use it with `fa()` function like the following example ```typst #import "fasvg": * #fa("brand-amazon-pay") ``` You can also customize the icon like this ```typst #import "fasvg": * #fa( "brand-amazon-pay", baseline: 0.25em, height: 1.0em, width: 1.5em) ``` Checkup [manual](https://github.com/ivaquero/typst-fasvg/blob/main/manual.pdf) for more details. ![demo](demo.png) ## Changelog ### v0.1.0 (2023-08-28) - update fasvg to v6.5.1 ### v0.0.4 (2023-08-28) - change naming pattern ### v0.0.3 (2023-08-16) - update fasvg to v6.4.2 - change naming pattern ### v0.0.2 (2023-07-28) - update structures - enable customization ### v0.0.1 (2023-07-27) - initial release - add fasvg v6.4.0
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/typstfmt/82-non-converge-list.typ
typst
Apache License 2.0
#let f(t) = t We have next things: - thing 1; - thing 2; - thing 3. #f[Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim aeque doleamus animo, cum corpore dolemus, fieri.]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/block-01.typ
typst
Other
// Nothing evaluates to none. #test({}, none) // Let evaluates to none. #test({ let v = 0 }, none) // Evaluates to single expression. #test({ "hello" }, "hello") // Evaluates to string. #test({ let x = "m"; x + "y" }, "my") // Evaluated to int. #test({ let x = 1 let y = 2 x + y }, 3) // String is joined with trailing none, evaluates to string. #test({ type("") none }, "string")
https://github.com/pku-typst/meppp
https://raw.githubusercontent.com/pku-typst/meppp/main/lib.typ
typst
MIT License
#import ("table.typ"): meppp-tl-table #import ("template.typ"): meppp-lab-report #let pku-logo(..args) = image("pkulogo.png", ..args) #let subfigure( body, caption: none, numbering: "(a)", inside: true, dx: 10pt, dy: 10pt, boxargs: (fill: white, inset: 5pt), alignment: top + left, ) = { let lsa = counter("last-subfigure-at") let sc = counter("subfigure-counter") context if lsa.get() != counter(figure).get() { sc.update((1,)) lsa.update(counter(figure).get()) } else { sc.step() } let number = context sc.display(numbering) body if (inside) { place(alignment, box([#number #caption], ..boxargs), dx: dx, dy: dy) } else { linebreak() align(center, [#number #caption]) } }
https://github.com/dssgabriel/master-thesis
https://raw.githubusercontent.com/dssgabriel/master-thesis/main/src/chapters/5-bibliography.typ
typst
Apache License 2.0
#show bibliography: set heading(numbering: "1.") #bibliography("../references.bib", style: "ieee")
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/src/g-exam.typ
typst
MIT License
#import "@preview/oxifmt:0.2.0": strfmt #import "./global.typ" : * #import "./auxiliary.typ": * #import "./g-question.typ": * #import "./g-option.typ": * #import "./g-solution.typ": * #import "./g-clarification.typ": * #import "./g-sugar.typ": * /// Template for creating an exam. /// /// - author: Infomation of author of exam. /// - name (string, content): Name of author of exam. /// - email (string): E-mail of author of exam. /// - watermark (string): Watermark with information about the author of the document. /// - school: Information of school. /// - name (string, content): Name of the school or institution generating the exam. /// - logo (none, content, bytes): Logo of the school or institution generating the exam. /// - exam-info: Information of exam. /// - academic-period (none, content, str): Academic period. /// - academic-level (none, content, str): Academic level. /// - academic-subject (none, content, str): Academic subname. /// - number (none, content, str): Number of exam. /// - content (none, content, str): Content of exam. /// - model (none, content, str): Model of exam. /// - date (none, auto, datetime): Date of generate document. /// - keywords (string): Keywords of document. /// - language (en, es, de, fr, pt, it, nl): Language of document. English, Spanish, German, French, Portuguese and Italian are defined. /// - clarifications (string, content, array): Clarifications of exam. It will appear in a box on the first page. /// - question-text-parameters: Parameter of text in question and subquestion. For example, it allows us to change the text size of the questions. /// - show-student-data (none, true, false, "first-page", "all-pages", "odd-pages"): Show a box for the student to enter their details. It can appear on the first page, all pages or on all odd-numbered pages. /// - show-grade-table: (bool): Show the grade table. /// - decimal-separator: (".", ","): Indicate the decimal separation character. /// - question-points-position: (none, left, right): Position of question points. /// - show-solution: (true, false, "space", "spacex2", "spacex3"): Show the solutions. /// - show-draft: (true, false): It shows a draft label in the background. #let g-exam( author: ( name: "", email: none, watermark: none ), school: ( name: none, logo: none, ), exam-info: ( academic-period: none, academic-level: none, academic-subject: none, number: none, content: none, model: none ), language: "en", localization: ( grade-table-queston: none, grade-table-total: none, grade-table-points: none, grade-table-grade: none, point: none, points: none, page: none, page-counter-display: none, family-name: none, given-name: none, group: none, date: none, draft-label: none, ), date: auto, keywords: none, clarifications: none, question-text-parameters: none, show-student-data: "first-page", // show-student-data: ( // given-name: true, // family-name: true, // group: true, // date: true // ), show-grade-table: true, decimal-separator: ".", question-points-position: left, show-solution: true, show-draft: false, body, ) = { if type(show-student-data) != "dictionary" and type(show-student-data) != "array" { assert(show-student-data in (none, true, false, "first-page", "all-pages", "odd-pages"), message: "Invalid show studen data") } assert(question-points-position in (none, left, right), message: "Invalid question point position") assert(decimal-separator in (".", ","), message: "Invalid decimal separator") assert(show-solution in (true, false), message: "Invalid show solution value") assert(show-draft in (true, false), message: "Invalid show draft value") assert(date == none or date == auto or type(date) == "datetime", message: "Date must be nono, auto or datetime." ) set document( title: __document-name(exam-info: exam-info).trim(" "), author: author.name, date: date ) let margin-right = 2.5cm if (question-points-position == right) { margin-right = 3cm } set page( margin: (top: 5cm, right:margin-right), numbering: "1 / 1", number-align: right, header-ascent: 20%, header: { context{ let __page-number = counter(page).at(here()).first() __show-header( page-number: __page-number, school: school, exam-info: exam-info, show-student-data: show-student-data) } }, background: { __show-draft(draft-show: show-draft, draft-label:[draft]) }, footer: { context { line(length: 100%, stroke: 1pt + gray) align(right)[ #counter(page).display(__g-localization.final().page-counter-display, both: true, ) ] // grid( // columns: (1fr, 1fr, 1fr), // if type(school) == "dictionary" { // align(left, school.at("name", default : none)) // }, // align(center)[#exam-info.academic-period], // align(right)[ // Página // #counter(page).display({ // "1 de 1"}, // both: true, // ) // ] // ) __show-watermark(author: author, school: school, exam-info: exam-info, question-points-position:question-points-position) } } ) __read-localization(language: language, localization: localization) __g-question-points-position-state.update(u => question-points-position) __g-question-text-parameters-state.update(question-text-parameters) set text(lang:language) if show-grade-table == true { context { __g-grade-table-header( decimal-separator: decimal-separator, ) } v(10pt) } __g-show-solution.update(show-solution) __g-decimal-separator.update(decimal-separator) set par(justify: true) if clarifications != none { __g-show_clarifications(clarifications: clarifications) } show: __sugar body [#hide[]<end-g-question-localization>] [#hide[]<end-g-exam>] }
https://github.com/DaAlbrecht/thesis-TEKO
https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Task_analysis.typ
typst
#import "@preview/tablex:0.0.5": tablex, cellx #let appendix = figure.with(kind: "appendix", numbering: "A", supplement: [Appendix]) Here, we'll cover the initial context resulting from the assignment available @a_assignment == Task description Multiple customers of Integon rely upon RabbitMQ as their designated messaging broker. Different systems write messages into a queue, the messages then need to be processed by other systems. If for some reason a specific message should be processed again, the owner of the processing system cannot retry processing the message because the messages are not persistent, once consumed the message is gone. Said owner has to contact the owner of the sending system and ask for a retransmission of the message. This is a time-consuming and costly process. The goal of this thesis is to develop a microservice that allows queueing messages again, without needing to contact the owner of the sending system. The queuing should be possible via an API call. === Out of scope<Out_of_scope> The goal is to also embed the microservice into already existing observability systems to enable requeuing of messages via UI. This is beyond the scope of this thesis and will be implemented in a follow-up project. == Initial situation The microservice needs to be developed from scratch. There is no existing architecture or codebase to build upon.
https://github.com/Besthope-Official/backend
https://raw.githubusercontent.com/Besthope-Official/backend/master/24autumn/git-tutorial.typ
typst
#import "@preview/cuti:0.2.1": show-cn-fakebold #import "@preview/cetz:0.2.2" #show: show-cn-fakebold #let title = [版本控制系统 Git] #let header = [后端部开发文档] #set text(font: ("Source Han Serif SC")) #set page( header: [#set text(12pt); #align(right + horizon, header)], background: image("images/backend_logo_opacity_0.25.png", fit: "cover", width: 30%), numbering: "1", number-align: right, ) #show link: underline // CONTENTS #align(center, text(20pt)[ *#title* ]) == 版本控制系统 *版本控制系统* (Version Control Systems, VCSs) 是一类用于追踪源代码(或其他文件、文件夹)改动的工具。顾名思义,这些工具可以帮助我们管理代码的修改历史;不仅如此,它还可以方便团队协作编码。 例如,在实际项目开发中的一些场景: - 需要查看当前版本和上一版本之间的*差异* - 更细节的:这个文件的这一行是什么时候被编辑的?是谁作出的修改?修改原因是什么? - 当前版本上线出现严重 bug,需要*回退*到上一版本 - 还需要知道:在哪一个版本快照导致了单元测试失败? 版本控制是项目管理的一大关键。实践中,我们会使用最常用的版本控制工具 *Git* 来管理代码:它是一个*分布式版本控制系统*,客户端并不只提取最新版本的文件快照,而是把代码仓库完整地*克隆*下来,包括完整的历史记录。 #figure(image("images/dvcs.png", width: 50%), caption: "分布式VCS的一个优势是,就算中心服务器发生故障,事后都可以用任何一个镜像出来的本地仓库恢复数据库历史。") 你可以指定和不同的远端仓库交互,在同一个项目中,分别和不同的人相互协作。Git 的*分支*功能非常强大,它支持非线性的开发流程,并且能够有效地管理像 Linux 内核这样庞大的项目。 #figure(image("images/git-branch.svg", width: 50%)) 总而言之,假若你将来的工作和计算机沾边,Git 绝对是你离不开的开发工具。 == Git 的实现 Git 的后端实现相当优雅,虽然在理解上确实存在一定的复杂度。我们会简单讲解它的原理,以便大家能够真正了解 Git 的相关概念。如果你对这部分不感兴趣,可以转至下一小节。 === 怎样记录版本差异: 记录快照 #let graph(data, direction: "right", grow, node-color: gray, show-mark: true) = { cetz.canvas(length: 1cm, { import cetz.draw: * set-style(content: (padding: .2), fill: node-color.lighten(70%), stroke: node-color.lighten(70%) ) cetz.tree.tree( data, direction: direction, spread: 2.5, grow: grow, draw-node: (node, ..) => { circle((), radius: .55, stroke: none) content((), node.content) }, draw-edge: (from, to, ..) => { let (a, b) = (from + ".center", to + ".center") if show-mark { line((a, .6, b), (b, .6, a), mark: (end: ">")) } else { line((a, .6, b), (b, .6, a)) } }, name: "tree" ) }) } #let versions = ([ver 1], ([ver 2], ([ver 3], [ver 4]))) #let A-delta = ([A],([$Delta_1$],([$Delta_2$],([$Delta_3$],)))) #let B-delta = ([B], ([$Delta_1$],)) #let A-git = ([A], ([$A_1$], ([$A_2$], [$A_3$]))) #let B-git = ([B], ([B], ([B], [$B_1$]))) #figure( grid(align: center, column-gutter: auto, [#graph(versions, 2.5, node-color: red, show-mark: false) #graph(A-delta, 2.5) #graph(B-delta, 7.5)] ), caption: [基于*差异* (delta-based) 的版本控制]) Git 不存储每个文件与初始版本的差异,假设你的改动是添加了一行文本,它并不会记录这行新增的文本——它只存储文件的*快照*,每当你提交更新或保存项目状态时,它基本上就会对当时的*全部文件*创建一个快照(副本)并保存这个快照的*索引*。 #figure( grid(align: center, column-gutter: auto, [#graph(versions, 2.5, node-color: red) #graph(A-git, 2.5) #graph(B-git, 2.5)] ), caption: "存储随时间改变的快照") #let snapshot = ( ([ver 1], [A], [B], ([ver 2], ([$A_1$]), [ver 3]) ) ) #let demo = cetz.canvas(length: 1cm, { import cetz.draw: * let node-color = gray set-style(content: (padding: .2), fill: node-color.lighten(70%), stroke: node-color.lighten(70%) ) cetz.tree.tree( snapshot, direction: "down", spread: 2.5, grow: 2.0, draw-node: (node, ..) => { circle((), radius: .55, stroke: none) content((), node.content) }, draw-edge: (from, to, ..) => { let (a, b) = (from + ".center", to + ".center") line((a, .6, b), (b, .6, a), mark: (end: ">")) }, name: "tree" ) let (a, b) = ("tree.0-2", "tree.0-1") line(stroke: (paint: node-color.lighten(70%), dash: "dashed"), (a, .6, b), (b, .6, a), mark: (end: ">")) }) 给每个版本做快照显然很耗空间!对此,Git 的优化是:如果文件没有修改,就不再重新存储该文件,而是只保留一个*指针(链接)*,指向之前存储的文件。 #figure(demo, caption: "由快照构成的历史记录,虽然版本 2 指向 B,图中出现了环的形状,但B没有其它出边,不会出现循环,也因此不构成环") 从数据结构的角度来看这种设计,历史记录就成了一个由快照组成的有向无环图。一次快照就是一棵*树*,包含了全部的文件,每一次快照更新的*提交*(commit)包含了上面的树,附带了提交信息、作者、时间戳等元数据。 === 怎样存储文件: 一切都是对象 操作系统为我们抽象出*文件*的概念:我们通过文件路径来定位文件元数据所在的磁盘位置,再根据文件的元信息定位文件在硬盘上的具体位置,最终访问到文件的内容。 而 Git 有着独属于它的文件*内容寻址*系统。它并不基于文件路径寻址,路径不再作为获取文件内容的键,而文件*内容本身就是这个键*。 Git 将项目所有受控文件内容、文件的状态通过SHA1算法进行*哈希化*、压缩后作为 Blob 对象存储在 `.git\objects` 内。Git 数据库中保存的信息都是以文件内容的哈希值来索引,所有的数据在存储前都计算校验和,然后以校验和来引用。 我们用一个小例子来体现哈希化的过程: ```py >>> import hashlib >>> data = 'hello git' >>> content = f'blob {len(data)}\x00{data}' 'blob 9\x00hello git' >>> hashlib.sha1(content.encode()).hexdigest() 'f09e9c379f5fe8f4ce718641c356df87906d87a6' $ echo -n "hello git" | git hash-object --stdin f09e9c379f5fe8f4ce718641c356df87906d87a6 ``` 对文件名、目录等信息的保留依赖于先前提到的*树*。假如你的最新提交中更改了一个文件的文件名,而没有改变它的内容,Git 不会添加新的 Blob 对象,而只会更改树对象中指向这个 Blob 对象的名称。 树、提交(以及标记)这些元数据也是 Git 对象,同样会经过哈希化同文件一起存入 `objects` 目录下。正因为它们共同继承“对象”的统一接口,关联这些概念只需要提供哈希索引。 #figure(image("images/data-model-3.png", width: 85%), caption: [Git 对象模型示例,第三次提交的快照添加了 `bak/test.txt`,内容和文件名和初次提交一样。Git 不会添加新的 Blob 对象,只需令其引用第一次提交的树对象即可。]) 简洁而又高效的设计。 === 怎样设置分支: 引用 现在,所有的快照都可以通过它们的 SHA-1 哈希值来引用,不过我们并不需要记住这一串串 40 位的十六进制字符。Git 支持短哈希,也支持对哈希值做*别名*(alias),*标记*(tag)快照号: ```bash $ git tag -a v0.1.0 4892c7dc -m 'version 0.1.0 released' ``` 之后我们就可以用 `v0.1.0` 更便于人类记忆的编号来引用这个快照号了。 Git 内部维护*引用*(reference)使得某一项别名可以指向最新的提交,当前所在位置会用一个特殊的 `HEAD` 索引标记。 #figure(image("images/head-to-master.png", width: 65%), caption: [例如,`master` 引用通常会指向主分支的最新一次提交,此时 `HEAD` 引用指向 `master`。]) 创建*分支*其实就是新建一个引用,分支切换只需要改变 `HEAD` 文件内分支的指向,而分支合并(merge)则是创建一个新的提交对象,其父节点指向两个分支的最新提交,然后合并二者的文件。 #figure(image("images/basic-merging-2.png"), caption: "分支开发的一个场景。为了解决出现的 bug,你在主分支之上新建了一条 iss53 分支,在修正了问题#53后,你在主分支将其合并。") === 总结 TL;DR: Git 以*快照*的形式记录版本差异,将要存储于仓库的数据抽象为*对象*,具体来说:Blob 保存了文件内容,*树*保存了目录结构和文件名,*提交*保存了一次快照的提交信息、作者、时间戳等元数据。对象根据其内容的*哈希值*进行索引、关联。同时,Git 内部维护*引用*,允许用一个更用户友好的别名来指向最新的提交记录,使得我们可以进行强大的*分支*操作。在这种简洁的设计之下,Git 的操作就是对一些“对象”和“引用”的*图操作*。 == 使用 Git === 安装与配置 当前 Git 的最新稳定版本为 2.47.0。用 `git --version` 查看你的系统上是否安装了 Git。 - 对于Windows 用户,#link("https://gitforwindows.org/")[下载地址]。如果无法下载,尝试科学上网或#link("https://mirrors.tuna.tsinghua.edu.cn/github-release/git-for-windows/git/")[清华镜像]、#link("https://registry.npmmirror.com/binary.html?path=git-for-windows/")[阿里镜像]: - 对于 MacOS 用户,Git 通常是系统自带的工具;如果没有可以尝试下面这个图形化的 Git #link("http://sourceforge.net/projects/git-osx-installer/")[安装工具],或者尝试 `homebrew` 安装(学习下装一个包管理工具)。 - 对于 Linux 用户,根据你系统的发行版安装包管理器安装 Git。 - 例如 Ubuntu/Debian:`sudo apt-get install git` 我们对 Windows 安装包额外做一些说明:通常来说按照默认设置安装 Git 即可,但需要稍微注意一些个性化的设置(如换行符、编辑器)。我们建议你参考这篇#link("https://blog.csdn.net/mukes/article/details/115693833")[文章]来辅助你决策。 安装了 Git 之后,在 shell 里使用如下命令配置你的用户名和邮箱。参考这篇#link("https://git-scm.com/book/zh/v2/%e8%b5%b7%e6%ad%a5-%e5%88%9d%e6%ac%a1%e8%bf%90%e8%a1%8c-Git-%e5%89%8d%e7%9a%84%e9%85%8d%e7%bd%ae")[文章]: ```bash git config --global user.name <name> git config --global user.email <email-address> ``` === Git 接口 在学习 Git 接口之前,我们先来了解一下 Git 文件的状态: - *未跟踪*(Untracked):Git 尚未跟踪的文件,即还没有纳入版本管理的文件。 - *已修改*(Modified):修改了文件,但还没保存到数据库中。 - *已暂存*(Staged/Added):对一个已修改文件的当前版本做了标记,使之包含在下次提交的快照中。 - *已提交*(Committed):数据已经安全地保存在本地数据库中。 这会让我们的 Git 项目拥有三个阶段:工作区、暂存区以及 Git 目录。 #figure(image("images/areas.png", width: 75%), caption: [在一次提交中,选中提交的文件会从工作区记录到暂存区、最后经哈希对象化存放到 `.git` 目录下]) 创建一次 `commit` 的流程如下: - 在工作区中修改文件。 - 将你想要下次提交的更改选择性地暂存,这样只会将更改的部分添加到暂存区。(`git add`) - 提交更新,找到暂存区的文件,将快照永久性存储到 Git 目录。(`git commit`) 为什么要引入暂存区这个看似多余的步骤?想象一下,当你开发了两个独立的特性,希望创建两个独立的提交,这时候就可以有选择地进行提交。 另外一些常用的命令行操作: - `git clone <repository>`: 克隆远程仓库到本地。有些老师也喜欢用 Git 远程仓库来发布代码作业。 - `git status`: 查看当前仓库的状态。 - `git push`: 将本地仓库的更新推送到远程仓库(前提是你已经关联好了远程仓库)。当你的 IDE 因出现网络原因无法推送时可以尝试在命令行中推送。 - `git commit --amend`: 编辑历史提交的 commit 信息。 - `git stash`: 暂时移除工作目录下的修改内容。这在切换分支的时候很有用。 我们推荐大家阅读奇点先前编写的#link("https://singularity-backend.gitbook.io/backend-online-doc/week1/vcs-git/interfaces")[在线文档]来学习更多的接口知识。 === IDE 里使用图形界面 学习 Git 操作的最好是通过命令行,这也是学习命令行的好机会。 但我们同时推荐你去了解 IDE 里集成的 Git 使用:在日常工作中,CLI 并不常用。(除了某些特定 GUI 不管用的场景) #figure(image("images/ide.png", width: 65%), caption: [VSCode 里的源代码管理界面,在提供 Git 的图形化界面操作以外,也提供了对分支的良好可视化]) #pagebreak() == Git 的工作流 由于 Git 的使用非常灵活,在实践当中衍生了很多种不同的工作流程,不同的项目、不同的团队会有不同的协作方式。下面将介绍一种在各种大小项目中经过总结出来的工作流。 奇点的开发团队参考的也是这一套流程。 === 远程 Git 仓库 我们提到,Git 是一个分布式版本控制系统,这意味着每个开发者都有一份完整的仓库,称为*本地仓库*。实现同步的方式是拥有一个可靠的中心*远程仓库*,一个 Git 服务器。 一些常用的 Git 服务器有: - GitHub:一个基于Git的代码托管服务平台,同时也是重要的开源社区。 - GitLab:类似Github,但主要面向企业、组织等内部使用。也可以用官方提供的镜像部署。 - Gitee:具有中国特色的代码托管平台 奇点的两个开发部门目前使用 Github 作为 #link("https://github.com/SingularityLab-SWUFE")[Git 远程仓库]。 === 分布式开发 ==== 源仓库 在项目的开始,项目的发起者构建起一个项目的最原始的仓库,称为*源仓库*。它的目的是: - 汇总参与该项目的各个开发者的代码 - 存放趋于稳定和可发布的代码 ==== 开发者仓库 源仓库建立以后,每个开发者需要做的事情就是把源仓库的“复制”,在其基础之上 `fork`(分叉)开发,作为自己日常开发的仓库。 每个开发者所 `fork` 的仓库是完全独立的,互不干扰。而在开发工作完成以后,开发者可以向源仓库发送 `Pull Request`(推送请求),请求管理员把自己的代码合并到源仓库中。 #figure(image("images/pr.png", width: 75%), caption: [一个开源项目 #link("https://github.com/Qexo/Qexo")[Qexo] 的 PR,记得在 PR 里描述清楚自己的贡献]) ==== 集成代码 当然,多条 PR 可能存在代码冲突!项目管理者首先需要对代码进行*代码审阅* (code review) 解决冲突以外,我们还需要检验集成后代码的正确性。*自动化构建工具*会根据流程自动编译构建安装应用,并执行*单元测试框架*的自动化测试来校验提交的修改。 一个成熟的项目通常包含完备的*持续集成和持续交付* (CI/CD)。它通过自动化流程和工具自动帮助项目管理者构建应用、测试应用、部署应用。 例如,Github Action 通过 YAML 文件的配置定义工作流程以构建执行 CI/CD 流水线,并可以触发不同事件时(如 `push`、`Pull Request`)自动执行这些工作流程。 当你的 PR 通过了 CI/CD 的测试,以及相关的 code review,项目管理者就可以采用如 squash-merge 的方式将你的代码合并到主分支。 === 分支管理 称分支管理是 Git 的灵魂也不为过。上面我们提到了 Git 分布式开发的基本流程,为了更好地利用 CI/CD 工作流,项目团队通常对分支的命名和权限的管理有着一定的规定,下面就介绍一种比较普遍适用的分支模型,在这种模型中,分支有两类,五种: ==== 永久性分支 - `main`: 主分支,它用于存放经过测试,已经完全稳定的代码;在项目开发以后的任何时刻当中,主分支存放的代码应该是可作为产品供用户使用的代码。 - `develop`: 开发分支,它用于开发者存放基本稳定代码。 #figure(image("images/main-dev.png", width: 50%), caption: [所有开发者开发好的功能会在源仓库的 `develop` 分支中进行汇总,经测试稳定后最后合并到 `main` 分支。这就是一个产品不断完善和发布过程。]) *提示*:分支保护很重要,不要为了图一时省事不建立开发分支或随意合并至主分支! ==== 临时性分支 临时性分支类似于开发分支的一个缓冲区。在开发完毕、合并后,这些临时性分支会得到删除。通常来说,各个开发者会在 `develop` 分支上继续分叉出特性分支 `feature-*`,例如 `feature-OAuth` 表示实现 OAuth 登录功能的特性分支。 另外两个临时分支在更大规模的团队开发中会运用到: - `release`: 预发布分支,当产品即将发布的时候,要进行最后的调整和测试,就可以开出预发布分支 - `hotfix`: 修复 bug 分支,在产品上线之后发布热补丁进行紧急的 bug 修复工作,通常来说经过测试后会合并回 `main` 分支。 #figure(image("images/git-model@2x.png", width: 85%), caption: [比较标准的大型项目的 Git 分支模型。在这种规范下,历史记录看起来很复杂但是相当清楚。]) === 提交消息规范 对分支规范后,我们还会对提交消息进行规范,主要的原因是: - 利用工具来自动化生成 CHANGELOG,例如 `cz-conventional-changelog` 工具 - 统一提交消息格式,不必纠结到底该怎么写提交消息 - 方便项目更好设计 CI/CD 流程 #figure(image("images/changelog.png", width: 65%), caption: [一个好的开源软件都会在每个版本号对提交或者 PR 记录改动日记,例如 VSCode]) 我们的参考是 #link("https://www.conventionalcommits.org/zh-hans/v1.0.0/")[约定式提交规范]。具体来说,如果采用 eslint 格式的格式规范: - 每个提交都*必须*使用类型字段前缀,如 `fix`, 同时加上以及必要的冒号(英文半角)和空格. - 当一个提交为应用或类库实现了新功能时,使用 `feat` 类型;为应用修复了 bug 时,使用 `fix` 类型。 - 类型字段*可以*指定范围,例如 `fix(api)` 指明是对接口代码的修复。当然你也可以不带. - 每个提交*必须*要有对提交的描述,对代码变更的简短总结。可以使用中文。 - 在类型后添加感叹号,表明这是一个*破坏性变更*(Breaking Change)。即,对现有功能或接口进行的修改。如果你改了接口的某一个字段,导致无法兼容旧版本,那么就需要加上感叹号。 更多规则见上方给出的文档。以上几条作为我们的开发规范就够用了。 ==== 示例 - `feat!: send an email to the customer when a product is shipped` - `docs: correct spelling of CHANGELOG` - `feat(lang): add polish language` - `feat:` 登录相关接口 推荐大家去阅读正式一些的开源项目来了解提交规范。例如,有的项目会要求在 PR 里指出相关的 issue 编号,等等。 ==== 相关工具 你可以在终端里使用 #link("https://cz-git.qbb.sh/zh/")[commitizen],#link("https://commitlint.js.org/")[commitlint] 这些工具省去手敲前缀的麻烦。 #pagebreak() == 参考资料 这篇文档主要参考的是 #link("https://git-scm.com/book/zh/v2")[Pro Git]。许多配图以及内容都来自这本书,强烈推荐自己亲自读一遍前五章! #link("https://singularity-backend.gitbook.io/backend-online-doc/week1/vcs-git")[奇点工作室暑期训练营后端文档]:这是奇点在 23 年暑假开展的暑期训练营,这篇文档也是在线文档的一次重置翻新——主要是对原理部分进行了重写(因为初版确实有些不那么容易理解)。如果你对其它部分感兴趣,欢迎阅读文档! #link("https://missing-semester-cn.github.io/2020/version-control/")[MIT CS教育缺失的一课: 版本控制(Git)]: 整个 Missing-semester 课程都推荐大家学习, 非常好的一门课, 学习到很多好用的工具, 除了拓宽视野更能帮助你在未来的职业生涯中节省时间. #link("https://learngitbranching.js.org/")[Learn Git Branching] 通过基于浏览器的游戏来学习 Git. #link("https://nvie.com/posts/a-successful-git-branching-model/")[A successful Git branching model]:有关分支工作流的文章,文章的图 13 来自于此。
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/signature/import.typ
typst
Apache License 2.0
// path: base.typ #let f(u, v) = u + v; ----- #import "base.typ": * #(/* ident after */ f);
https://github.com/ohmycloud/computer-science-notes
https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/machine_learning_item.typ
typst
= 术语 交叉验证折叠: cross-validation folds 自己实现交叉验证: ```python from sklearn.model_selection import StratifiedKFold from sklearn.base import clone skfolds = StratifiedKFold(n_splits=3) # add shuffle=True if the dataset is # not already shuffled for train_index, test_index in skfolds.split(X_train, y_train_5): clone_clf = clone(sgd_clf) X_train_folds = X_train[train_index] y_train_folds = y_train_5[train_index] X_test_fold = X_train[test_index] y_test_fold = y_train_5[test_index] clone_clf.fit(X_train_folds, y_train_folds) y_pred = clone_clf.predict(X_test_fold) n_correct = sum(y_pred == y_test_fold) print(n_correct / len(y_pred)) ``` StratifiedFold 类执行分层抽样。每次迭代都创建一个分类器的克隆, 在训练折叠上训练克隆, 在测试折叠上做预测。 然后它计算正确预测的数量并输出正确预测的比率。 二元分类器: binary classifier 只能区分两个类别, 要么是某个类别,要么不是。 随机梯度下降: stochastic gradient descent(SGD 或 stochastic GD) 训练集: training set 测试集: test set 倾斜数据集: skewed datasets 比如, 某些类型的图片比其它类型的图片出现得频率更高。 混淆矩阵: confusion matrix(CM) 用于评估分类器性能的一种更好的方式。 混淆矩阵的一般思想是对于所有 A/B 对儿,计算 A 类实例被分类为 B 类的次数。 例如,要知道分类器混淆图像 8 和 图像 0 的次数,你可以查看混淆矩阵的第8行第0列。 要计算混淆矩阵,你首先要有一组预测值,这组预测值会和实际目标进行比较。 你可以对测试集进行预测,但是现在最好不要碰测试集(在训练集上训练完分类器之后, 再使用测试集检测训练的效果)。 相反,你可以使用 *cross_val_predict()* 函数: ```python from sklearn.model_selection import cross_val_predict y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3) ``` 现在可以使用confusion_matrix()函数获得混淆矩阵了。只需将目标类(y_train_5)和预测类传递给它 (y_train_pred): 就像 *cross_val_score()* 函数一样,*cross_val_predict()* 执行 _k_-fold 交叉验证,但它不是返回评估分数,而是返回对每个测试折叠(test fold)所做的预测。 这意味着对于训练集(training set)中的每个实例, 你得到一个“干净的”预测(这里的“干净”是指“样本外”:模型对训练期间从未见过的数据进行预测)。 现在可以使用 *confusion_matrix()* 函数获得混淆矩阵了。只需要把目标类(y_train_5) 和预测类(y_train_pred)传递给它: ```python from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_train_5, y_train_pred) # array([[53892, 687], # [ 1891, 3530]]) ``` 混淆矩阵中的每一行代表一个实际的类,而每一列代表一个预测的类。该矩阵的第一行考虑非5的图像(阴性类),其中53892个图像被正确分类为非5(称为真阴性),而其余687个图像被错误分类为5(假阳性,也称为I类错误)。第二行考虑5s的图像(正类): 1891例被错误地归类为非5(假阴性,也称为II型错误),而其余3530例被正确归类为5(真阳性)。 一个完美的分类器只会有真正和真负,所以它的混淆矩阵只会在主对角线上(从左上到右下)有非零值: ```python y_train_perfect_predictions = y_train_5 # pretend we reached perfection confusion_matrix(y_train_5, y_train_perfect_predictions) ``` 分类器的精确度:(the accuracy of the positive predictions) $"precision" = "TP" /("TP" + "FP")$ TP 为真阳性数,FP 为假阳性数。 要想获得完美的精度,一个简单的方法就是创建一个分类器,除了对它最有信心的实例进行一次正向预测外,它总是进行负向预测。如果这一个预测是正确的,那么分类器的精度就是 100%(精度 = 1/1 = 100%)。显然,这样的分类器用处不大,因为它会忽略除了一个正向实例之外的所有实例。因此,精度通常与另一个名为召回率(recall)的指标一起使用,召回率也称为灵敏度或真阳性率(TPR):这是分类器正确检测到的阳性实例的比率: $ "recall" = "TP" / ("TP" + "FN")$ 当然,FN 是假阴性的数量。 精度和召回率 ```python from sklearn.metrics import precision_score, recall_score precision_score(y_train_5, y_train_pred) recall_score(y_train_5, y_train_pred) ``` $F_1$ score $ F_1 = 2 / (1/"precision" + 1/"recall" ) = 2 × ("precision" × "recall") / ("precision" + "recall") = "TP" / ("TP" + ("FN" + "FP") / 2 ) $ 要计算 $F_1$ 的值,只需要调用 *f1_score()* 函数: ```python from sklearn.metrics import f1_score f1_score(y_train_5, y_train_pred) ```
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/167.%20aord.html.typ
typst
aord.html Default Alive or Default Dead? October 2015When I talk to a startup that's been operating for more than 8 or 9 months, the first thing I want to know is almost always the same. Assuming their expenses remain constant and their revenue growth is what it has been over the last several months, do they make it to profitability on the money they have left? Or to put it more dramatically, by default do they live or die?The startling thing is how often the founders themselves don't know. Half the founders I talk to don't know whether they're default alive or default dead.If you're among that number, <NAME> has made a handy calculator you can use to find out.The reason I want to know first whether a startup is default alive or default dead is that the rest of the conversation depends on the answer. If the company is default alive, we can talk about ambitious new things they could do. If it's default dead, we probably need to talk about how to save it. We know the current trajectory ends badly. How can they get off that trajectory?Why do so few founders know whether they're default alive or default dead? Mainly, I think, because they're not used to asking that. It's not a question that makes sense to ask early on, any more than it makes sense to ask a 3 year old how he plans to support himself. But as the company grows older, the question switches from meaningless to critical. That kind of switch often takes people by surprise.I propose the following solution: instead of starting to ask too late whether you're default alive or default dead, start asking too early. It's hard to say precisely when the question switches polarity. But it's probably not that dangerous to start worrying too early that you're default dead, whereas it's very dangerous to start worrying too late.The reason is a phenomenon I wrote about earlier: the fatal pinch. The fatal pinch is default dead + slow growth + not enough time to fix it. And the way founders end up in it is by not realizing that's where they're headed.There is another reason founders don't ask themselves whether they're default alive or default dead: they assume it will be easy to raise more money. But that assumption is often false, and worse still, the more you depend on it, the falser it becomes.Maybe it will help to separate facts from hopes. Instead of thinking of the future with vague optimism, explicitly separate the components. Say "We're default dead, but we're counting on investors to save us." Maybe as you say that, it will set off the same alarms in your head that it does in mine. And if you set off the alarms sufficiently early, you may be able to avoid the fatal pinch.It would be safe to be default dead if you could count on investors saving you. As a rule their interest is a function of growth. If you have steep revenue growth, say over 5x a year, you can start to count on investors being interested even if you're not profitable. [1] But investors are so fickle that you can never do more than start to count on them. Sometimes something about your business will spook investors even if your growth is great. So no matter how good your growth is, you can never safely treat fundraising as more than a plan A. You should always have a plan B as well: you should know (as in write down) precisely what you'll need to do to survive if you can't raise more money, and precisely when you'll have to switch to plan B if plan A isn't working.In any case, growing fast versus operating cheaply is far from the sharp dichotomy many founders assume it to be. In practice there is surprisingly little connection between how much a startup spends and how fast it grows. When a startup grows fast, it's usually because the product hits a nerve, in the sense of hitting some big need straight on. When a startup spends a lot, it's usually because the product is expensive to develop or sell, or simply because they're wasteful.If you're paying attention, you'll be asking at this point not just how to avoid the fatal pinch, but how to avoid being default dead. That one is easy: don't hire too fast. Hiring too fast is by far the biggest killer of startups that raise money. [2]Founders tell themselves they need to hire in order to grow. But most err on the side of overestimating this need rather than underestimating it. Why? Partly because there's so much work to do. Naive founders think that if they can just hire enough people, it will all get done. Partly because successful startups have lots of employees, so it seems like that's what one does in order to be successful. In fact the large staffs of successful startups are probably more the effect of growth than the cause. And partly because when founders have slow growth they don't want to face what is usually the real reason: the product is not appealing enough.Plus founders who've just raised money are often encouraged to overhire by the VCs who funded them. Kill-or-cure strategies are optimal for VCs because they're protected by the portfolio effect. VCs want to blow you up, in one sense of the phrase or the other. But as a founder your incentives are different. You want above all to survive. [3]Here's a common way startups die. They make something moderately appealing and have decent initial growth. They raise their first round fairly easily, because the founders seem smart and the idea sounds plausible. But because the product is only moderately appealing, growth is ok but not great. The founders convince themselves that hiring a bunch of people is the way to boost growth. Their investors agree. But (because the product is only moderately appealing) the growth never comes. Now they're rapidly running out of runway. They hope further investment will save them. But because they have high expenses and slow growth, they're now unappealing to investors. They're unable to raise more, and the company dies.What the company should have done is address the fundamental problem: that the product is only moderately appealing. Hiring people is rarely the way to fix that. More often than not it makes it harder. At this early stage, the product needs to evolve more than to be "built out," and that's usually easier with fewer people. [4]Asking whether you're default alive or default dead may save you from this. Maybe the alarm bells it sets off will counteract the forces that push you to overhire. Instead you'll be compelled to seek growth in other ways. For example, by doing things that don't scale, or by redesigning the product in the way only founders can. And for many if not most startups, these paths to growth will be the ones that actually work.Airbnb waited 4 months after raising money at the end of Y Combinator before they hired their first employee. In the meantime the founders were terribly overworked. But they were overworked evolving Airbnb into the astonishingly successful organism it is now.Notes[1] Steep usage growth will also interest investors. Revenue will ultimately be a constant multiple of usage, so x% usage growth predicts x% revenue growth. But in practice investors discount merely predicted revenue, so if you're measuring usage you need a higher growth rate to impress investors.[2] Startups that don't raise money are saved from hiring too fast because they can't afford to. But that doesn't mean you should avoid raising money in order to avoid this problem, any more than that total abstinence is the only way to avoid becoming an alcoholic.[3] I would not be surprised if VCs' tendency to push founders to overhire is not even in their own interest. They don't know how many of the companies that get killed by overspending might have done well if they'd survived. My guess is a significant number.[4] After reading a draft, <NAME> wrote:"I think you should make the hiring point more strongly. I think it's roughly correct to say that YC's most successful companies have never been the fastest to hire, and one of the marks of a great founder is being able to resist this urge."<NAME>uchheit adds:"A related problem that I see a lot is premature scaling—founders take a small business that isn't really working (bad unit economics, typically) and then scale it up because they want impressive growth numbers. This is similar to over-hiring in that it makes the business much harder to fix once it's big, plus they are bleeding cash really fast." Thanks to <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/README.md
markdown
# Liturgical Books Respository for my implementation of liturgical books for Orthodox and Byzantine Catholic church I decided to open this repo as public, for anyone to use. CSL texts are here temporarily, they are compiled from texts from OSBM monks, that they published long time ago on their former web page. They are here just as test data and will be replaced later by original transcription. Do not use without their permision. GR texts are compiled from [https://glt.goarch.org/](GOA). CU texts are compiled from [https://www.ponomar.net/](Ponomar). SK texts are mostly from various sources, especially from [https://casoslov.sk/](Casoslov.sk). They also serve as test texts and will be replaced by original translation. Do not use without their permision. Other texts are here just as test data, and will be removed or replaced in later versions. ## Prerequisites This repository uses [https://typst.app/docs](Typst) to generate PDFs from source code. ## Command To generate pdf use command ``` typst _general/NAME.typ ``` To update sources use command ```` git submodule update --remote ```` ## Plans and TODO - Find a way how to use second and third glory/now and how to render it properly - Finalize general minea - add matins and liturgy/typica - Add also lower feasts into minea - Add lenten and flowely triodion - Add different sources - Lviv, etc. ## Changelog ### v. 0.5 - CU, CSL and GR text are moved to separate repository, to allow it's independent reuse - Vespers for general minea are added - Started to add minea for great feasts ### v. 0.4 - Finished conversion of CLS oktoich to JSON - Work in progres of JSON oktoich ### v. 0.3 - Finished CU and CSL oktoich - Started CU common minea - Started GR version ### v. 0.2 - Added voice 1 and 2 in Church Slavonic and Slovak transcription of Church Slavonic - TODO: there are some differences in Lviv and Moscow oktoich, that need to be somehow resolved ### v. 0.1 - Initial commit to transfer from typst.app to separate place, as it reached maximal ammount of files.
https://github.com/Gekkio/gb-ctr
https://raw.githubusercontent.com/Gekkio/gb-ctr/main/appendix/external-bus.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "../common.typ": * #import "../timing.typ" == Game Boy external bus === Bus timings #let bus-diagram = (addr: array, rd: array, wr: array, a15: array, cs: array, data: array, sampling-edge: false) => { import timing: diagram, clock as c, data as d, either as e, high as h, low as l, unknown as u, undefined as x, high_impedance as z text(13pt, diagram( grid: true, (label: "CLK 4 MiHz", wave: ( l(1), ..range(9).map(_ => c(1)).flatten() )), (label: "PHI 1 MiHz", wave: (l(1), c(4), c(4), c(1),)), (label: "A0-A14", wave: addr), (label: "RD", wave: rd), (label: "WR", wave: wr), (label: "A15", wave: a15), (label: "CS", wave: cs), (label: "Data", wave: data), fg: () => { import cetz.draw draw.set-style(stroke: (paint: rgb("#00000080"), thickness: 0.01em)) draw.line((1.0, -0.5), (1.0, 15.5)) draw.line((9.0, -0.5), (9.0, 15.5)) if sampling-edge { draw.line((7, -0.5), (7, 15.5), stroke: (paint: rgb("#80800080"), thickness: 0.8pt)) } } ) ) } #figure( { import timing: diagram, clock as c, data as d, either as e, high as h, low as l, unknown as u, undefined as x, high_impedance as z bus-diagram( addr: (u(10),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), h(8), e(1),), cs: (e(1), h(8), e(1),), data: (x(1), z(9),), ) }, caption: "External bus idle machine cycle" ) #v(1cm) #figure( { import timing: diagram, clock as c, data as d, either as e, high as h, low as l, unknown as u, undefined as x, high_impedance as z [ #columns(2, [ #block( breakable: false, [ #bus-diagram( addr: (u(2), d(7, "addr"), u(1),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), h(2), l(6), e(1),), cs: (e(1), h(8), e(1),), data: (x(1), z(2), d(6, "data"), z(1)), sampling-edge: true ) #align(right, [ a) #hex-range("0000", "7FFF") #footnote[ Does not apply to #hex-range("0000", "00FF") accesses while the boot ROM is enabled. Boot ROM accesses do not affect the external bus, so it is in the idle state. ] <bootrom> ]) ] ) #colbreak() #block( breakable: false, [ #bus-diagram( addr: (u(2), d(7, "addr"), u(1),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), h(8), e(1),), cs: (e(1), h(2), l(6), e(1),), data: (x(1), z(2), d(6, "data"), z(1)), sampling-edge: true, ) #align(right, [ b) #hex-range("A000", "FDFF") ]) ] ) ]) #block( breakable: false, [ #bus-diagram( addr: (u(2), d(7, "addr"), u(1),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), h(8), e(1),), cs: (e(1), h(8), e(1),), data: (x(1), z(9),), ) #align(right, [ c) #hex-range("FE00", "FFFF") ]) #v(1cm) ] ) ] }, caption: "External bus CPU read machine cycles" ) #figure( { import timing: diagram, clock as c, data as d, either as e, high as h, low as l, unknown as u, undefined as x, high_impedance as z [ #columns(2, [ #block( breakable: false, [ #bus-diagram( addr: (u(2), d(7, "addr"), u(1),), rd: (e(1), l(1), h(7), l(1),), wr: (h(5), l(3), h(2),), a15: (e(1), h(2), l(6), e(1),), cs: (e(1), h(8), e(1),), data: (x(1), z(4), d(4, "data"), z(1)), ) #align(right, [ a) #hex-range("0000", "7FFF") #footnote(<bootrom>) ]) ] ) #colbreak() #block( breakable: false, [ #bus-diagram( addr: (u(2), d(7, "addr"), u(1),), rd: (e(1), l(1), h(7), l(1),), wr: (h(5), l(3), h(2),), a15: (e(1), h(8), e(1),), cs: (e(1), h(2), l(6), e(1),), data: (x(1), z(4), d(4, "data"), z(1)), ) #align(right, [ b) #hex-range("A000", "FDFF") ]) ] ) ]) #block( breakable: false, [ #bus-diagram( addr: (u(2), d(7, "addr"), u(1),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), h(8), e(1),), cs: (e(1), h(8), e(1),), data: (x(1), z(9),), ) #align(right, [ c) #hex-range("FE00", "FFFF") ]) #v(1cm) ] ) ] }, caption: "External bus CPU write machine cycles" ) #figure( { import timing: diagram, clock as c, data as d, either as e, high as h, low as l, unknown as u, undefined as x, high_impedance as z [ #columns(2, [ #block( breakable: false, [ #bus-diagram( addr: (u(1), d(8, "addr"), u(1),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), l(8), e(1),), cs: (e(1), h(8), e(1),), data: (x(1), d(8, "data"), z(1)), ) #align(right, [ a) #hex-range("0000", "7FFF") #footnote(<bootrom>) ]) ] ) #colbreak() #block( breakable: false, [ #bus-diagram( addr: (u(1), d(8, "addr"), u(1),), rd: (e(1), l(9),), wr: (h(10),), a15: (e(1), h(8), e(1),), cs: (e(1), l(8), e(1),), data: (x(1), d(8, "data"), z(1)), ) #align(right, [ b) #hex-range("A000", "FFFF") ]) ] ) ]) #v(1cm) ] }, caption: "External bus timings for OAM DMA read machine cycles" )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/underover_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test brackets. $ underbracket([1, 2/3], "relevant stuff") arrow.l.r.double.long overbracket([4/5,6], "irrelevant stuff") $
https://github.com/jgm/typst-symbols
https://raw.githubusercontent.com/jgm/typst-symbols/main/README.md
markdown
MIT License
# typst-symbols This package provides definitions of the symbols used in typst (<https://typst.app>). (Currently version 0.12.0 is targeted.) It exports lists of triples, which can be converted into maps or other more appropriate forms, depending on the use case. Each triple contains the symbol name (Text), a Boolean that is True if the symbol is an accent, and the resolved symbol (Text). The symbols can be updated by scraping the typst website: `make update` will do the work.
https://github.com/emanuel-kopp/uzh-mnf-phd
https://raw.githubusercontent.com/emanuel-kopp/uzh-mnf-phd/main/src/lib.typ
typst
#let main_doc( title: "", author: "", heimatort: "", examinators: (""), date: "", land: "", PI_is_head: true, body, ) = { // Set the document's basic properties. set document(author: author, title: title) set text(font: "New Computer Modern", lang: "de", size: 11pt) set align(center) set page(margin: (left: 2cm, right: 2cm, bottom: 2cm, top: 2cm)) text(size: 14pt, weight: "bold")[#title] v(3pt) line(length: 171mm, stroke: 0.3pt) v(24pt) text(weight: "bold")[Dissertation] linebreak() v(2fr) text(weight: "bold")[zur] v(2fr) text(weight: "bold")[Erlangung der naturwissenschaftlichen Doktorwürde] v(2fr) text(weight: "bold")[(Dr. sc. nat.)] v(2fr) text(weight: "bold")[vorgelegt der] v(2fr) text(weight: "bold")[Mathematisch-naturwissenschaftlichen Fakultät] v(2fr) text(weight: "bold")[der] v(2fr) text(weight: "bold")[Universität Zürich] v(2fr) text(weight: "bold")[von] v(2fr) text(weight: 1)[#author] v(11pt) if land == "Schweiz" [#text(weight: "bold")[von]] else { text(weight: "bold")[aus] } v(2fr) if land == "Schweiz" { text(weight: 1)[#heimatort] } else { text(weight: 1)[#land] } v(4fr) text(weight: "bold")[Promotionskommission] v(3pt) grid( align: left, columns: 3, [], let (a, b, .., c) = examinators, for ex in examinators { if PI_is_head == true [ #if ex == a { text(weight: 1)[#ex (Vorsitz und Leitung der Dissertation)] } else { text(weight: 1)[#ex] } ] if PI_is_head == false [ #if ex == a { text(weight: 1)[#ex (Vorsitz)] } else if ex == b { text(weight: 1)[#ex (Leitung der Dissertation)] } else { text(weight: 1)[#ex] } ] v(0.1em) }, [], ) v(6fr) text(weight: "bold")[Zürich, #date] v(2fr) pagebreak() // Defining headings show heading.where(level: 1): it => { pagebreak() set text(weight: "bold", size: 16pt) it.body v(1em) } // Main body set text(font: "New Computer Modern", lang: "en", size: 11pt) set par(justify: true) set align(left) set page(numbering: "1", number-align: center) set par(leading: 1.5em) body } #let chapter( title: none, authors: (), affiliations: (), header: none, abstract: [], chapter, ) = { set align(left) // Write title text(size: 14pt, weight: "bold", title) v(1em) let count = authors.len() let ncols = calc.min(count, 3) for aut in authors { if aut.name == authors.last().name { text()[#aut.name#super[#aut.affiliation]] } else { text()[#aut.name#super[#aut.affiliation], ] } } v(1em) for aff in affiliations { text()[#aff.num: #aff.name] linebreak() } v(2em) set align(center) par(justify: true)[ *Abstract* \ #abstract ] show heading.where(level: 2): it => { v(1em) it.body v(1em) } show heading.where(level: 3): it => { v(1em) it.body v(1em) } set align(left) v(2em) // Write header set page(header: align(right)[ #text(size: 10pt, style: "italic")[#header] ]) chapter }
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/docs/readme-examples/state-machine.typ
typst
MIT License
#set text(10pt) #diagram( node-stroke: .1em/*<*/ + fg/*>*/, edge-stroke: fg, // hide crossing-fill: bg , // hide node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%), spacing: 4em, edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center), node((0,0), `reading`, radius: 2em), edge(`read()`, "-|>"), node((1,0), `eof`, radius: 2em), edge(`close()`, "-|>"), node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)), edge((0,0), (0,0), `read()`, "--|>", bend: 130deg), edge((0,0), (2,0), `close()`, "-|>", bend: -40deg), )
https://github.com/alberto-lazari/cns-report
https://raw.githubusercontent.com/alberto-lazari/cns-report/main/previous-architecture.typ
typst
= Overview of previous work <previous_work> Thestarting point of our project is _QRFuzz_ by @QRFuzz, which is made of the following components: - *PC Monitor*: A phisical monitor in which the generated QRs are displayed. - *Smartphone*: A phisical smartphone in which the app under test is run. - *Appium server*: An Appium Server is an open-source automation server that facilitates the automated testing of mobile applications across different platforms, including iOS, Android, and Windows. It acts as a bridge between test code and the mobile device or emulator, allowing to interact with the application under test programmatically. - *QR Code Fuzzer*: The main element of the system that is responsible for coordinating and initiating actions for both the QR Code Generator and the Appium Server, along with managing the entire testing process. The fuzzing operation itself involves a series of steps repeated for each QR code under examination. These steps include navigating to the designated scanning page within the application, scanning the QR code, verifying if the app's normal behavior has been disrupted, and logging the results of the iteration as potential indications of a vulnerability. - *QR Code Generator*: The QR Code Generator is another crucial component of QRFuzz. Its primary function is to dynamically produce QR codes using a predefined dictionary and display them on the screen. This generator is capable of creating both standard, general-purpose QR codes and custom codes based on an application-specific template. #v(2em) == Workflow The workflow of the system (@old_workflow) can be summarized by the following steps: 1. The QR code displayed on the monitor is scanned by the smartphone. 2. The smartphone sends a scan responce to the QR Code Fuzzer through the Appium server 3. The QR Code Fuzzer notifies a QR change request to the QR Code Generator by updating a shared JSON file. 4. The QR Code Generator generates a new QR and displays it on the monitor. 5. The QR Code Generator notifies the update to the QR Code Fuzzer by changing the JSON file. 6. The QR Code Fuzzer sends a scan request to the smartphone via Appium server. #figure( image("images/qr-fuzz-old-architecture.png"), caption: [Old architecture] ) <old_workflow>
https://github.com/isaacholt100/isaacholt
https://raw.githubusercontent.com/isaacholt100/isaacholt/main/public/maths-notes/4-cambridge%3A-part-III/additive-combinatorics/additive-combinatorics.typ
typst
MIT License
#import "../../template.typ": * #show: doc => template(doc, hidden: (), slides: false) = Combinatorial methods #definition[ Let $G$ be an abelian group and $A, B subset.eq G$. The *sumset* of $A$ and $B$ is $ A + B := {a + b: a in A, b in B}. $ The *difference set* of $A$ and $B$ is $ A - B := {a - b: a in A, b in B}. $ ]<def:sumset-and-difference-set> #proposition[ $max{|A|, |B|} <= |A + B| <= |A| dot |B|$. ]<prop:general-bound-on-sumset-size> #proof[ Trivial. ] #example[ Let $A = [n] = {1, ..., n}$. Then $A + A = {2, ..., 2n}$ so $|A + A| = 2|A| - 1$. ] #lemma[ Let $A subset.eq ZZ$ be finite. Then $|A + A| >= 2|A| - 1$ with equality iff $A$ is an arithmetic progression. ]<lem:lower-bound-on-integer-sumset> #proofhints[ Consider two sequences in $A + A$ which are strictly increasing and of the same length. ] #proof[ - Let $A = {a_1, ..., a_n}$ with $a_i < a_(i + 1)$. Then $a_1 + a_1 < a_1 + a_2 < dots.c < a_1 + a_n < a_2 + a_n < dots.c < a_n + a_n$. - Note this is not the only choice of increasing sequence that works, in particular, so does $a_1 + a_1 < a_1 + a_2 < a_2 + a_2 < a_2 + a_3 < a_2 + a_4 < dots.c < a_2 + a_n < a_3 + a_n < dots.c < a_n + a_n$. - So when equality holds, all these sequences must be the same. In particular, $a_2 + a_i = a_1 + a_(i + 1)$ for all $i$. ] #lemma[ If $A, B subset.eq ZZ$, then $|A + B| >= |A| + |B| - 1$ with equality iff $A$ and $B$ are arithmetic progressions with the same common difference. ] #proofhints[ Similar to above, consider $4$ sequences in $A + B$ which are strictly increasing and of the same length. ] #example[ Let $A, B subset.eq ZZ\/p$ for $p$ prime. If $|A| + |B| >= p + 1$, then $A + B = ZZ\/p$. ] #proofhints[ Consider $A sect (g - B)$ for $g in ZZ\/p$. ] #proof[ - $g in A + B$ iff $A sect (g - B) != emptyset$ where ($g - B = {g} - B$). - Let $g in ZZ\/p$, then use inclusion-exclusion on $|A sect (g - B)|$ to conclude result. ] #theorem(name: "Cauchy-Davenport")[ Let $p$ be prime, $A, B subset.eq ZZ\/p$ be non-empty. Then $ |A + B| >= min{p, |A| + |B| - 1}. $ ]<thm:cauchy-davenport> #proofhints[ - Assume $|A| + |B| < p + 1$, and WLOG that $1 <= |A| <= |B|$ and $0 in A$ (by translation). - Induct on $|A|$. - Let $a in A$, find $B'$ such that $0 in B'$, $a in.not B'$ and $|B'| = |B|$ (use fact that $p$ is prime). - Apply induction with $A sect B'$ and $A union B'$, while reasoning that $(A sect B') + (A union B') subset.eq A + B'$. ] #proof[ - Assume $|A| + |B| < p + 1$, and WLOG that $1 <= |A| <= |B|$ and $0 in A$ (by translation). - Use induction on $|A|$. $|A| = 1$ is trivial. - Let $|A| >= 2$ and let $0 != a in A$. Then since $p$ is prime, ${a, 2a, ..., p a} = ZZ\/p$. - There exists $m >= 0$ such that $m a in B$ but $(m + 1)a in.not B$ (why?). Let $B' = B - m a$, so $0 in B'$, $a in.not B'$ and $|B'| = |B|$. - $1 <= |A sect B'| < |A|$ (why?) so the inductive hypothesis applies to $A sect B'$ and $A union B'$. - Since $(A sect B') + (A union B') subset.eq A + B'$ (why?), we have $|A + B| = |A + B'| >= |(A sect B') + (A union B')| >= |A sect B'| + |A union B'| - 1 = |A| + |B| - 1$. ] #example[ Cauchy-Davenport does not hold general abelian groups (e.g. $ZZ\/n$ for $n$ composite): for example, let $A = B = {0, 2, 4} subset.eq ZZ\/6$, then $A + B = {0, 2, 4}$ so $|A + B| = 3 < min{6, |A| + |B| - 1}$. ] #example[ Fix a small prime $p$ and let $V subset.eq FF_p^n$ be a subspace. Then $V + V = V$, so $|V + V| = |V|$. In fact, if $A subset.eq FF_p^n$ satisfies $|A + A| = |A|$, then $A$ is an affine subspace (a coset of a subspace). ] #proof[ If $0 in A$, then $A subset.eq A + A$, so $A = A + A$. General result follows by considering translation of $A$. ] #example[ Let $A subset.eq FF_p^n$ satisfy $|A + A| <= 3/2 |A|$. Then there exists a subspace $V subset.eq FF_p^n$ such that $|V| <= 3/2 |A|$ and $A$ is contained in a coset of $V$. ] #proof[ Exercise (sheet 1). ] #definition[ Let $A, B subset.eq G$ be finite subsets of an abelian group $G$. The *Ruzsa distance* between $A$ and $B$ is $ d(A, B) := log (|A - B|)/(sqrt(|A| dot |B|)). $ ] #lemma(name: "Ruzsa Triangle Inequality")[ Let $A, B, C subset.eq G$ be finite. Then $ d(A, C) <= d(A, B) + d(B, C). $ ]<lem:ruzsa-triangle-inequality> #proofhints[ Consider a certain map from $B times (A - C)$ to $(A - B) times (B - C)$. ] #proof[ - Note that $|B| |A - C| <= |A - B| |B - C|$. Indeed, writing each $d in A - C$ as $d = a_d - c_d$ with $a_d in A$, $c_d in C$, the map $phi: B times (A - C) -> (A - B) times (B - C)$, $phi(b, d) = (a_d - b, b - c_d)$ is injective (why?). - Triangle inequality now follows from definition of Ruzsa distance. ] #definition[ The *doubling constant* of finite $A subset.eq G$ is $sigma(A) := |A + A|\/|A|$. ]<def:doubling-constant> #definition[ The *difference constant* of finite $A subset.eq G$ is $delta(A) := |A - A|\/|A|$. ]<def:difference-constant> #remark[ The Ruzsa triangle inequality shows that $ log delta(A) = d(A, A) <= d(A, -A) + d(-A, A) = 2 log sigma(A). $ So $delta(A) <= sigma(A)^2$, i.e. $|A - A| <= |A + A|^2\/|A|$. ] #notation[ Let $A subset.eq G$, $ell, m in NN_0$. Then $ ell A + m A := underbrace(A + dots.c + A, ell "times") underbrace(- A - dots.c - A, m "times") $ This is referred to as the *iterated sum and difference set*. ] #theorem(name: "Plunnecke's Inequality")[ Let $A, B subset.eq G$ be finite and $|A + B| <= K|A|$ for some $K >= 1$. Then $forall ell, m in NN_0$, $ |ell B - m B| <= K^(ell + m) abs(A). $ ]<thm:plunneckes-inequality> #proofhints[ - Let $A' subset.eq A$ minimise $abs(A' + B)\/abs(A')$ with value $K'$. - Show that for every finite $C subset.eq G$, $abs(A' + B + C) <= K' abs(A + C)$ by induction on $abs(C)$ (note two sets need to be written as disjoint unions here). - Show that $forall m in NN_0, abs(A' + m B) <= (K')^m abs(A')$ by induction. - Use Ruzsa triangle inequality to conclude result. ] #proof[ - Choose $emptyset != A' subset.eq A$ which minimises $|A' + B|\/|A'|$. Let the minimum value by $K'$. - Then $|A' + B| = K' abs(A')$, $K' <= K$ and $forall A'' subset.eq A$, $|A'' + B| >= K' abs(A'')$. - Claim: for every finite $C subset.eq G$, $|A' + B + C| <= K' abs(A' + C)$: - Use induction on $abs(C)$. $abs(C) = 1$ is true by definition of $K'$. - Let claim be true for $C$, consider $C' = C union {x}$ for $x in.not C$. - $A' + B + C' = (A' + B + C) union ((A' + B + x) - (D + B + x))$, where $D = {a in A': a + B + x subset.eq A' + B + C}$. - By definition of $K'$, $abs(D + B) >= K' abs(D)$. Hence, $ |A' + B + C| & <= |A' + B + C| + abs(A' + B + x) - abs(D + B + x) \ & <= K' abs(A' + C) + K' abs(A') - K' abs(D) \ & = K' (abs(A' + C) + abs(A') - |D|). $ - Applying this argument a second time, write $A' + C' = (A' + C) union ((A' + x) - (E + x))$, where $E = {a in A': a + x in A' + C} subset.eq D$. - Finally, $ abs(A' + C') & = abs(A' + C) + abs(A' + x) - abs(E + x) \ & >= |A' + C| + |A'| - |D|. $ - We first show that $forall m in NN_0$, $abs(A' + m B) <= (K')^m abs(A')$ by induction: - $m = 0$ is trivial, $m = 1$ is true by assumption. - Suppose $m - 1 >= 1$ is true. By the claim with $C = (m - 1) B$, we have $ abs(A' + m B) = |A' + B + (m - 1)B| <= K' abs(A' + (m - 1)B) <= (K')^m abs(A'). $ - As in the proof of Ruzsa's triangle inequality, $forall ell, m in NN_0$, $ |A'| |ell B - m B| <= |A' + ell B| |A' + m B| <= (K')^ell abs(A') (K')^m abs(A') = (K')^(ell + m) abs(A')^2. $ ] #theorem(name: "Freiman-Ruzsa")[ Let $A subset.eq FF_p^n$ and $abs(A + A) <= K abs(A)$. Then $A$ is contained in a subspace $H subset.eq FF_p^n$ with $abs(H) <= K^2 p^(K^4) abs(A)$. ]<thm:freiman-ruzsa> #proofhints[ - Let $X subset.eq 2A - A$ be of maximal size such that all $x + A$, $x in X$, are disjoint. - Use Plunnecke's inequality to obtain an upper bound on $abs(X) abs(A)$. - Show that $forall ell >= 2$, $ell A - A subset.eq (ell - 1)X + A - A$ by induction. - Let $H$ be subgroup generated by $A$. By writing $H$ as an infinite union, show that $H subset.eq Y + A - A$, where $Y$ is subgroup generated by $X$. - Find an upper bound for $abs(Y)$, conclude using Plunnecke inequality. ] #proof[ - Choose maximal $X subset.eq 2A - A$ such that the translates $x + A$ with $x in X$ are disjoint. - Such an $X$ cannot be too large: $forall x in X$, $x + A subset.eq 3A - A$, so by Plunnecke's inequality, since $abs(3A - A) <= K^4 abs(A)$, $ abs(X) abs(A) = abs(union.big_(x in X) (x + A)) <= abs(3A - A) <= K^4 abs(A). $ Hence $abs(X) <= K^4$. - We next show that $2A - A subset.eq X + A - A$. Indeed, if, $y in 2A - A$ and $y in.not X$, then by maximality of $X$, then $(y + A) sect (x + A) != emptyset$ for some $x in X$. If $y in X$, then $y in X + A - A$. - It follows from above, by induction, that $forall ell >= 2$, $ell A - A subset.eq (ell - 1)X + A - A$: $ell A - A = A + (ell - 1)A - A subset.eq (ell - 2)X + 2A - A subset.eq (ell - 2)X + X + A - A = (ell - 1)X + A - A$. - Now, let $H subset.eq FF_p^n$ be the subgroup generated by $A$: $ H = union.big_(ell >= 1) (ell A - A) subset.eq Y + A - A $ where $Y subset.eq FF_p^n$ is the subgroup generated by $X$. - Every element of $Y$ can be written as a sum of $abs(X)$ elements of $X$ with coefficients in ${0, ..., p - 1}$. Hence, $abs(Y) <= p^abs(X) <= p^(K^4)$. - Hence $abs(H) <= abs(Y) abs(A - A) <= p^(K^4) K^2 abs(A)$ by Plunnecke/Ruzsa triangle inequality. ] #example[ Let $A = V union R$, where $V subset.eq FF_p^n$ is a subspace with $dim(V) = d = n\/K$ satisfying $K << d << n - K$, and $R$ consists of $K - 1$ linearly independent vectors not in $V$. Then $abs(A) = abs(V union R) = abs(V) + abs(R) = p^(n\/K) + K - 1 approx p^(n\/K) = abs(V)$. Now $abs(A + A) = abs((V union R) + (V union R)) = abs(V union (V + R) union 2R) approx K abs(V) approx K abs(A)$ (since $V union (V + R)$ gives $K$ cosets of $V$). But any subspace $H subset.eq FF_p^n$ containing $A$ must have size at least $p^(n\/K + (K - 1)) approx abs(V) p^K$. Hence, the exponential dependence on $K$ in Freiman-Ruzsa is necessary. ] #theorem(name: "Polynomial Freiman-Ruzsa Theorem")[ Let $A subset.eq FF_p^n$ be such that $abs(A + A) <= K abs(A)$. Then there exists a subspace $H subset.eq FF_p^n$ of size at most $C_1 (K) abs(A)$ such that for some $x in FF_p^n$, $ abs(A sect (x + H)) >= abs(A)/(C_2 (K)), $ where $C_1 (K)$ and $C_2 (K)$ are polynomial in $K$. ] #proof[ Very difficult (took Green, Gowers and Tao to prove it). ] #definition[ Given $A, B subset.eq G$ for an abelian group $G$, the *additive energy* between $A$ and $B$ is $ E(A, B) := abs({(a, a', b, b') in A times A times B times B: a + b = a' + b'}). $ *Additive quadruples* $(a, a', b, b')$ are those such that $a + b = a' + b'$. Write $E(A)$ for $E(A, A)$. ] #example[ Let $V subset.eq FF_p^n$ be a subspace. Then $E(V) = abs(V)^3$. On the other hand, if $A subset.eq ZZ\/p$ is chosen at random from $ZZ\/p$ (where each $a in ZZ\/p$ is included with probability $alpha > 0$), with high probability, $E(A) = alpha^4 p^3 = alpha abs(A)^3$. ] #definition[ For $A, B subset.eq G$, the *representation function* is $r_(A + B) (x) := abs({(a, b) in A times B: a + b = x}) = abs(A sect (x - B))$. ] #lemma[ Let $emptyset != A, B subset.eq G$ for an abelian group $G$. Then $ E(A, B) >= (abs(A)^2 abs(B)^2)/abs(A + B). $ ] #proof[ - Observe that $ E(A, B) & = abs({(a, a', b, b') in A^2 times B^2: a + b = a' + b'}) \ & = abs(union.big_(x in G) {(a, a', b, b') in A^2 times B^2: a + b = x "and" a' + b' = x}) \ & = union.big_(x in G) abs({(a, a', b, b') in A^2 times B^2: a + b = x "and" a' + b' = x}) \ & = sum_(x in G) r_(A + B) (x)^2 $ ] = Fourier-analytic techniques = Probabilistic tools = Further topics
https://github.com/Shuenhoy/modern-zju-thesis
https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/documentclass/graduate-general.typ
typst
MIT License
#import "../pages/graduate-cover.typ": graduate-cover #import "../pages/graduate-title-zh.typ": graduate-title-zh #import "../pages/graduate-title-en.typ": graduate-title-en #import "../pages/graduate-decl.typ": graduate-decl #import "../pages/template-individual.typ": template-individual #import "../pages/outline.typ": main-outline, figure-outline, table-outline #import "../utils/fonts.typ": * #import "../utils/header.typ": header, footer #import "../utils/fakebold.typ": show-cn-fakebold #import "../utils/indent-first-par.typ": indent-first-par #import "../utils/supplement.typ": show-set-supplement #import "../utils/twoside.typ": show-twoside-pagebreak, twoside-numbering-footer, twoside-pagebreak #import "../utils/near-chapter.typ": near-chapter #import "../utils/bilingual-bibliography.typ": show-bilingual-bibliography #import "../utils/structure.typ": frontmatter, mainmatter #import "../utils/appendix.typ": appendix #import "../dependency/i-figured.typ" #let show-outline-indent(s) = { show outline.entry: it => { if it.level == 1 { text(weight: "bold", it) } else { h(1em * (it.level - 1)) + it } } s } #let graduate-general-default-info = ( title: ("毕业论文/设计题目", ""), title-en: ("Graduation Project/Design Title", ""), grade: "20XX", student-id: "1234567890", clc: "O643.12", unitcode: "10335", reviewer: ("隐名", "隐名", "隐名", "隐名", "隐名"), committe: ("主席", "委员", "委员", "委员", "委员", "委员"), reviewer-en: ("Anonymous", "Anonymous", "Anonymous", "Anonymous", "Anonymous"), committe-en: ("Chair", "Committeeman", "Committeeman", "Committeeman", "Committeeman", "Committeeman"), secret-level: "无", author: "张三", department: "某学院", major: "某专业", degree: "硕士", field: "某方向", supervisor: "李四", submit-date: datetime.today(), defense-date: ("二一九三年六月", "September 2193"), ) #let graduate-general-set-style( doc, degree: "硕士", twoside: false, ) = { // Page geometry set page( paper: "a4", margin: ( x: 2.5cm, bottom: 2.54cm + 12pt + 30pt, top: 2.54cm + 12pt + 4mm, ), ) show: show-twoside-pagebreak.with(twoside: twoside) // Header and footer set page( header-ascent: 4mm, footer-descent: 35pt, header: header( left: [浙江大学#(degree)学位论文], right: near-chapter, ), footer: twoside-numbering-footer, ) // Paragraph and text set par(leading: 1.3em, first-line-indent: 2em, justify: true) show: indent-first-par set text(font: 字体.仿宋, size: 字号.小四, lang: "zh") show: show-cn-fakebold set underline(offset: 0.2em) // Headings show heading: i-figured.reset-counters set heading(numbering: "1.1") show heading.where(level: 1): set text(size: 字号.小三) show heading.where(level: 1): x => { twoside-pagebreak v(12pt) x v(6pt) } show heading.where(level: 2): set text(size: 字号.四号) show heading.where(level: 3): set text(size: 字号.小四) show heading.where(level: 4): set text(size: 字号.小四) show heading: set block(above: 1.5em, below: 1.5em) // Reference show: show-set-supplement show figure: i-figured.show-figure show math.equation.where(block: true): i-figured.show-equation show figure.where(kind: table): set figure.caption(position: top) show: show-bilingual-bibliography doc } #let graduate-general(info: (:), twoside: false) = { let info = graduate-general-default-info + info ( pages: ( cover: graduate-cover(info: info), title-zh: graduate-title-zh(info: info), title-en: graduate-title-en(info: info), decl: graduate-decl(), outline: show-outline-indent(main-outline(outlined: true, titlelevel: 1)), figure-outline: figure-outline(outlined: true, titlelevel: 1), table-outline: table-outline(outlined: true, titlelevel: 1), individual: template-individual.with(outlined: true, titlelevel: 1, bodytext-settings: (size: 字号.小四)), ), style: doc => { set document(title: info.title.join()) graduate-general-set-style(doc, degree: info.degree, twoside: twoside) }, ) }
https://github.com/typst-community/mantodea
https://raw.githubusercontent.com/typst-community/mantodea/main/src/_valid.typ
typst
MIT License
#import "_pkg.typ" #let _content = content #let _color = color #let _gradient = gradient #let _label = label #let _version = version #import _pkg.z: * #let paint = base-type.with(name: "color/gradient", types: (_color, _gradient,)) #let auto_ = base-type.with(name: "auto", types: (type(auto),)) #let label = base-type.with(name: "label", types: (_label,)) #let version = base-type.with(name: "version", types: (_version,))
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/fhe-takeaways.typ
typst
#import "preamble.typ":* #takeaway[FHE takeaways][ 1. A _fully homomorphic encryption_ protocol allows Bob to compute some function $f(x)$ for Alice in a way that Bob doesn't get to know $x$ or $f(x)$. 2. The hard problem backing known FHE protocols is the _learning with errors (LWE)_ problem, which comes down to deciding if a system of "approximate equations" over $FF_q$ is consistent. 3. The main idea of this approach to FHEs is to use "approximate eigenvalues" as the encrypted computation and an "approximate eigenvector" as the secret key. Intuitively, adding and multiplying two matrices with different approximate eigenvalues for the same eigenvector approximately adds and multiplies the eigenvalues, respectively. 4. To carefully do this, we actually need to control the error blowup with the _flatten_ operation. This creates a _levelled FHE_ protocol. ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/par-justify_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that runts are avoided when it's not too costly to do so. #set page(width: 124pt) #set par(justify: true) #for i in range(0, 20) { "a b c " } #"d"
https://github.com/sebmestrallet/typst-simple-siam
https://raw.githubusercontent.com/sebmestrallet/typst-simple-siam/main/README.md
markdown
MIT No Attribution
# The `simple-siam` Typst package A Typst template for SIAM paper submissions <p align="center"> <img src="thumbnails/p1.png" alt="page 1 of an example paper based on this template" width="49%"> <img src="thumbnails/p2.png" alt="page 2 of an example paper based on this template" width="49%"> <img src="thumbnails/p3.png" alt="page 3 of an example paper based on this template" width="49%"> <img src="thumbnails/p4.png" alt="page 4 of an example paper based on this template" width="49%"> </p> <details> <summary>About the name</summary> - `typst-simple-siam` is the name of the GitHub repo, `simple-siam` is the name of the Typst template - The Typst template name does not contain `typst`, because it is redundant[^typst_template_naming] - The Typst template name is not just `siam`, because it is not an official template, thus the name must start with a non-descriptive part[^typst_template_naming] [^typst_template_naming]: https://github.com/typst/packages?tab=readme-ov-file#submission-guidelines </details> ## Template adaptation checklist - [x] Fill out `README.md` - Change the `my-package` package name, including code snippets - Check section contents and/or delete sections that don't apply - [x] Check and/or replace `LICENSE` by something that suits your needs - [x] Fill out `typst.toml` - See also the [typst/packages README](https://github.com/typst/packages/?tab=readme-ov-file#package-format) - [ ] Adapt Repository URLs in `CHANGELOG.md` - Consider only committing that file with your first release, or removing the "Initial Release" part in the beginning - [ ] Adapt or deactivate the release workflow in `.github/workflows/release.yml` - to deactivate it, delete that file or remove/comment out lines 2-4 (`on:` and following) - to use the workflow - [ ] check the values under `env:`, particularly `REGISTRY_REPO` - [ ] if you don't have one, [create a fine-grained personal access token](https://github.com/settings/tokens?type=beta) with [only Contents permission](https://stackoverflow.com/a/75116350/371191) for the `REGISTRY_REPO` - [ ] on this repo, create a secret `REGISTRY_TOKEN` (at `https://github.com/[user]/[repo]/settings/secrets/actions`) that contains the so created token if configured correctly, whenever you create a tag `v...`, your package will be pushed onto a branch on the `REGISTRY_REPO`, from which you can then create a pull request against [typst/packages](https://github.com/typst/packages/) - [x] remove/replace the example test case - [x] (add your actual code, docs and tests) - [ ] remove this section from the README ## Getting Started > [!IMPORTANT] > This template is not published yet, you cannot access it from `@preview/`, but you can download [`src/lib.typ`](src/lib.typ) and use it in your project. From the CLI: ```bash typst init @preview/simple-siam ``` From the Typst web app: ```typ #import "@preview/simple-siam:0.1.0": conf #show: doc => conf( title: [A Typst template for SIAM paper submissions], authors: [<NAME>], abstract: [See #link("https://github.com/sebmestrallet/typst-simple-siam")], doc, ) = First section #lorem(50) ``` ## Theorems & algorithms Based on third-party Typst packages, this template allows to insert formatted theorem/proof/definition/lemma environments, as well as algorithms: ```typ #import "lib.typ": conf, theorem, definition, lemma, thmrules, proof, pseudocode-list, algorithm #show: thmrules #show: doc => conf( title: [A Typst template for SIAM paper submissions], authors: [<NAME>], abstract: [See #link("https://github.com/sebmestrallet/typst-simple-siam")], doc, ) = A theorem #theorem[ Here the theorem formulation ] = An algorithm #algorithm( pseudocode-list( numbered-title: #smallcaps[(My Algorithm)], stroke: none, booktabs: false, indentation: 2em )[ - *Require:* Some input $a$ - *Require:* Some input $b$ + Here the algorithm definition ] ) ``` ## Files - [`src/lib.typ`](src/lib.typ): provide the `conf(title,authors,abstract,doc)` function to format a paper - [`src/main.typ`](src/main.typ): use `conf()` to reproduce the outputs of `ltexpprt_anonymous-submission.tex` & `ltexpprt_accepted-submission.tex` from the official template - [`src/bib.yml`](src/bib.yml): transcoding of `ltexpprt_references.bib` from the official template to the [Hayagriva](https://github.com/typst/hayagriva/blob/main/docs/file-format.md) format - [`src/siam.csl`](src/siam.csl): [Citation Style Language](https://citationstyles.org/) for the bibliography, based on the [IEEE](https://github.com/citation-style-language/styles/blob/master/ieee.csl) one (modified `<macro name="author">` to have small caps) ## Dependencies - [`ctheorems`](https://typst.app/universe/package/ctheorems) ([sahasatvik/typst-theorems](https://github.com/sahasatvik/typst-theorems)) for numbered theorem environments, by [<NAME>](https://github.com/sahasatvik), [<NAME>](https://github.com/rmolinari), [<NAME>](https://github.com/MJHutchinson) and [DVDTSB](https://github.com/DVDTSB) [[MIT](https://github.com/sahasatvik/typst-theorems/blob/main/LICENSE)] - [`lovelace`](https://typst.app/universe/package/lovelace) ([andreasKroepelin/lovelace](https://github.com/andreasKroepelin/lovelace)) for pseudocode, by [<NAME>](https://github.com/andreasKroepelin) and contributors [[MIT](https://github.com/andreasKroepelin/lovelace/blob/main/LICENSE)] They are imported with `#import "@preview/{name}:{version}` in [`src/lib.typ`](src/lib.typ). ## Ressources TeX sources of the official template: - The [SIAM two-column template](https://internationalmeshingroundtable.com/assets/files/imr33/templates.zip) referenced for the [SIAM International Meshing Roundtable Workshop 2025](https://internationalmeshingroundtable.com/imr33/call-for-papers/#formatting-requirements) - The [SIAM Macros](https://epubs.siam.org/journal-authors#macros) on the SIAM website - The [2019 SIAM style manual](https://epubs.siam.org/pb-assets/files/SIAM_STYLE_GUIDE_2019.pdf) on the SIAM website How to create and publish a Typst template package: - The motivation and recommended interface for templates in the [official tutorial](https://typst.app/docs/tutorial/making-a-template/) - The in-depth format requirements in the [typst/packages](https://github.com/typst/packages) README - Do as the [templates directly maintained by the Typst team](https://github.com/typst/templates) - Use the [typst-package-template](https://github.com/typst-community/typst-package-template) GitHub template from [@typst-community](https://github.com/typst-community) ## Differences with the official TeX template See [open issues with the `compliance` label](https://github.com/sebmestrallet/typst-simple-siam/issues?q=sort%3Aupdated-desc+is%3Aopen+label%3Acompliance) ## License [MIT-0](LICENSE)
https://github.com/LeptusHe/LeptusHe.github.io
https://raw.githubusercontent.com/LeptusHe/LeptusHe.github.io/main/source/_posts/fourier-transform/fourier-transform-01-fourier-series.typ
typst
#import "../typst-inc/blog-inc.typc": * #show: blog_setting.with( title: "傅里叶变换01 - 傅里叶级数", author: ("<NAME>"), paper: "jis-b0", preview: false ) #metadata("傅里叶变换") <tags> #metadata("数学") <categories> #metadata("2024-08-05") <date> #show: shorthands.with( ($<|$, math.angle.l), ($|>$, math.angle.r) ) #set math.equation(numbering: "(1)") = 傅里叶正交函数集 傅里叶函数集$cal(Phi)$是正交函数集,其中任意两个函数的内积都为0。$cal(Phi)$的定义如@eq-fourier-function 所示。 $ cal(Phi) = {1, sin(w t), cos(w t), sin (2 w t), cos(2 w t), dots.c, sin(n w t), cos (n w t)} $ <eq-fourier-function> 傅里叶基函数之间内积的定义如@eq-inner-fourier-basis-func 所示。 $ <|f, g|> = integral_(-T/2)^(T/2) f(x) dot.c g(x) dif x $ <eq-inner-fourier-basis-func> #proof[ #im[当正整数$n$与$m$满足]:$n, m > 0$时, $ <|sin(n w t), sin(m w t)|> &= Integral(-T/2, T/2, sin(n w t) dot.c sin(m w t), dif: t) \ &= cIntegral(1/2 (cos(n - m) w t - cos((n + m) w t))) \ $ 分情况讨论,当$m != n$时,根据 @def-integral-of-cos-func 可得: $ <|sin(n w t), sin(m w t)|> &= 1 /2 dot.c (Integral(-T/2, T/2, cos(n - m) w t, dif: t) - Integral(-T/2, T/2, cos(n+m) w t, dif:t) ) \ &= 1 / 2 dot.c (0 + 0) \ &= 0 $ 当$m = n$时,可得: $ <|sin(n w t), sin(m w t)|> &= 1 /2 dot.c (Integral(-T/2, T/2, cos(n - m) w t, dif: t) - Integral(-T/2, T/2, cos(n+m) w t, dif:t) ) \ &= 1/ 2 dot.c (cIntegral(1) - cIntegral( cos(2 n w t) )) \ &= 1 / 2 dot.c T \ &= T / 2 $ 同理可得: $ <|cos(n w t), cos(m w t)|> = cases( 0\, quad "if " n != m, T/2\, quad "if " n = m ) $ $ <|sin(n w t), cos(m w t)|> &= Integral(-T/2, T/2, 1/2 dot.c (sin(n + m) w t + sin(n - m) w t ), dif: t) \ $ 当$n != m$时,由 @def-integral-of-sin-func 可得: $ <|sin(n w t), cos(m w t)|> = 0 $ 当$n = m$时,可得: $ <|sin(n w t), cos(m w t)|> &= Integral(-T/2, T/2, 1/2 dot.c (sin(n + m) w t + sin(n - m) w t ), dif: t) \ &= cIntegral(1 / 2 sin(2 n w t)) \ &= 0 $ ] = 傅里叶级数 任意一个#im[周期为$T$的函数]都可以展开为不同频率的的正弦与余弦函数的线性组合,即: $ f(x) = sum_(n=0)^infinity (a_n sin n omega x + b_n cos n omega x) $ <eq-fourier-series> 对于@eq-fourier-series,我们需要求解系数$a_n$与$b_n$。根据#im[傅里叶正交函数系的性质]可知: 当$n > 0$时,求解系数$a_n$时,可以利用公式: $ <| f(x), sin(n omega x)|> &= Integral(-T/2, T/2, f(x) dot.c sin n omega x) \ &= cIntegral(sin n omega x dot.c (sum_(n = 0)^infinity (a_n sin n omega x + b_n cos n omega x)) ) \ &= sum_(n=0)^infinity (a_n dot.c cIntegral(sin n omega x dot.c sin n omega x) + b_n cIntegral(sin n omega x dot.c cos n omega x) ) \ &= a_n cIntegral(sin n omega x dot.c sin n omega x) \ &= a_n dot.c T / 2 $ 因此,可以得到 $ a_n = 2 / T dot.c <| f(x), sin n omega x |> = 2 / T dot.c integral_(-T/2)^(T/2) f(x) dot.c sin n omega x dif x $ 同理,对于系数$b_n$,可以得到: $ b_n = 2 / T dot.c <| f(x), cos n omega x |> = 2 / T dot.c integral_(-T/2)^(T/2) f(x) dot.c cos n omega x dif x $ 对于$n = 0$的特殊情况,由于由于当$n = 0$时, $ cases( sin n w t = 0, cos n w t = 1 ) $ 因此@eq-fourier-series 中的项$a_0 dot.c sin (0 dot.c omega x)$没有意义,系数$a_0$可以为任意值。 对于项$b_0 dot.c cos(0 dot.c omega x)$而言,其值为$1$,则系数$b_0$可以求解。对于系数$b_0$,可以求得: $ <| f(x), 1 |> &= Integral(-T/2, T/2, f(x) dot.c 1) \ &= cIntegral((sum_(i=0)^infinity (a_n sin n omega x + b_n cos n omega x)) dot.c 1) \ &= sum_(i=0)^(infinity) (a_n dot.c cIntegral(sin n omega x) + b_n dot.c cIntegral(cos n omega x)) quad (1"与" sin n omega x, cos n omega x text("的函数正交性)") \ &= b_0 dot.c cIntegral(cos (0 dot.c omega x)) \ &= b_0 dot.c T $ 因此可得: $ b_0 = 1/T dot.c <| f(x), 1 |> = 1 / T dot.c integral_(-T/2)^(T/2) f(x) dif x $ #im[为了后续方便讨论,以及统一形式系数的表述形式]。@eq-fourier-series 中当$n = 0$时的特殊常数项$a_0 sin 0 + b_0 cos 0 = b_0$可以使用单个常数项来表示,即令: $ c_0 / 2 = a_0 sin 0 + b_0 cos 0 = b_0 $ 因此,@eq-fourier-series 可以表述为: $ f(x) = c_0 / 2 + sum_(i=1)^infinity (a_n dot.c sin n omega x + b_n dot.c cos n omega x) $ <eq-fourier-series-general> 其中的系数可以使用#im[统一的形式]来表示为: $ cases( c_0 = 2 / T dot.c integral_(-T/2)^(T/2) f(x) dif x, a_n = 2 / T dot.c integral_(-T/2)^(T/2) f(x) dot.c sin n omega x dif x, b_n = 2 / T dot.c integral_(-T/2)^(T/2) f(x) dot.c cos n omega x dif x, ) $ <factors-of-fourier-series> = 复数傅里叶级数 == 复数傅里叶级数推导 傅里叶级数中的每项$a_n sin n omega x + b_n cos n omega x$都同时含有两个基函数$sin n omega x$与$cos n omega x$。#im[为了表达的简单性,我们需要寻找一种方式来将每项中的两个基函数表示为单个基函数。] 利用欧拉公式,我们可以使用复数来同时表示$sin n omega x$与$cos n omega x$函数。 欧拉公式的数学表述为: $ e^(i x) = cos x + i sin x $ 变形可以得到: $ e^(-i x) = cos x - i sin x $ 因此,$sin x$与$cos x$可以表示为: $ cases( sin x = (e^(i x) - e^(-i x)) / (2 i), cos x = (e^(i x) + e^(- i x)) / 2 ) $ 因此,@eq-fourier-series-general 可以表述为: $ f(x) &= c_0 / 2 + sum_(n=1)^infinity (a_n dot.c (e^(i n w x) - e^(-i n w x)) / (2 i) + b_n dot.c (e^(i n w x) + e^(-i n w x)) / 2) \ &= c_0 / 2 + sum_(n=1)^infinity (a_n dot.c (- i^2) / (2 i) (e^(i n w x) - e^(-i n w x)) + b_n / 2 dot.c (e^(i n w x) + e^(-i n w x))) \ &= c_0 / 2 + sum_(n=1)^infinity ((- i dot.c a_n) / (2) (e^(i n w x) - e^(-i n w x)) + b_n / 2 dot.c (e^(i n w x) + e^(-i n w x))) \ &= c_0 / 2 + sum_(n=1)^infinity ((- i dot.c a_n + b_n) / (2) dot.c e^(i n w x) + (i a_n + b_n) / 2 dot.c e^(-i n w x)) \ &= c_0 / 2 + sum_(n=1)^infinity ((- i dot.c a_n + b_n) / (2) dot.c e^(i n w x)) + sum_(n=1)^infinity ((i a_n + b_n) / 2 dot.c e^(-i n w x)) \ &= c_0 / 2 + sum_(n=1)^infinity ((- i dot.c a_n + b_n) / (2) dot.c e^(i n w x)) + sum_(n=-infinity)^(-1) ((i a_(-n) + b_(-n)) / 2 dot.c e^(i n w x)) \ $ <eq-complex-form-fourier-series-tmp> 当$n = 0$时,则$e^(i n omega x)$为: $ e^(i 0 w x) = cos 0 + i sin 0 = 1 $ 因此@eq-complex-form-fourier-series-tmp 可以使用复数表示为 $ f(x) = sum_(n = -infinity)^infinity d_n e^(i n omega x) $ 其中$d_n$为: $ d_n = cases( (-i a_n + b_n) / 2 &\, quad n > 0, 1/2 c_0 &\, quad n = 0, (i a_(-n) + b_(-n)) / 2 &\, quad n < 0 ) $ 将@factors-of-fourier-series 代入,可以得到: $ 1/2 c_0 &= 1 / 2 dot.c 2 / T Integral(-T/2, T/2, f(x)) \ &= 1 / T cIntegral(f(x) dot.c e^(-i n 0 x)) $ $ (-i a_n + b_n) / 2 &= 1 / 2 dot.c 2 / T dot.c Integral(-T/2, T/2, f(x) (-i sin n w x + cos n w x)) \ &= 1 / T dot.c cIntegral(f(x) dot.c e^(-i n omega x)) $ $ (i a_(-n) + b_(-n)) / 2 &= 1 / 2 dot.c 2 / T Integral(-T/2, T/2, f(x) (i sin (-n omega x) + cos(-n omega x))) \ &= 1 / T dot.c cIntegral(f(x) dot.c e^(-i n omega x)) $ 因此,参数$d_n$可以统一表述为: $ d_n = 1 / T Integral(-T/2, T/2, f(x) e^(-i n omega x)) $ #definition("傅里叶级数的复数形式")[ $ f(x) &= sum_(n=-infinity)^(infinity) d_n e^(i n omega x) \ &= sum_(n=-infinity)^(infinity) (1 / T dot.c integral_(-T/2)^(T/2) f(x) dot.c e^(-i n omega x) dif x) dot.c e^(i n omega x) $ ] == 复数傅里叶级数的正交函数系 对于周期为$T$的函数$f(x)$,从复数域角度来讲,周期函数$f(x)$可以表示为实变复值函数系$cal(R)$的线性组合,其中函数系$cal(R)$为: $ cal(R) = { e^(i n omega x) | n in Z} $ 因此,函数$f(x)$可以表示为: $ f(x) = sum_(-infinity)^(infinity) d_n dot.c e^(i n omega x) $ 对于函数系$cal(R)$而言,其定义的内积为Hermit内积,如: $ <| f(x), g(x) |> = 1 / T integral_(-T/2)^(T/2) f(x) dot.c overline(g(x)) dif x $ 事实上,可以证明函数系$cal(R)$是#im[规范正交的],即: $ <| e^(i n omega x), e^(i m omega x) |> &= 1 / (T) Integral(-T/2, T/2, e^(i n omega x) dot.c overline(e^(i m omega x))) \ &= 1 / (T) cIntegral(e^(i n omega x) dot.c e^(-i m omega x)) \ &= 1 / (T) cIntegral(e ^(i (n - m) omega x)) $ 当$n = m$时,有: $ <| e^(i n omega x), e^(i m omega x) |> &= 1 / (T) Integral(-T/2, T/2, 1) \ &= 1 $ 当$n != m$时,有: $ <| e^(i n omega x), e^(i m omega x) |> &= 1 / T Integral(-T/2, T/2, e^(i (n - m) omega x)) \ &= 1 / T cIntegral(cos(n - m) omega x + i sin(n - m) omega x) \ &= 1 / T (cIntegral(cos(n - m) omega x) + i cIntegral(sin(n - m) omega x) ) \ &= 0 $ 因此,系数$d_n$可以通过hermit内积来进行求解: $ d_n &= <| f(x), e^(i n omega x) |> \ &= 1 / T Integral(-T/2, T/2, f(x) dot.c e^(-i n omega x)) $ = 附录 == 三角函数积化和差公式 $ e^(i x) = cos x + i sin x $ <eq-euler-equation> 因此,可以得到 $ cases( sin x = (e^(i x) - e^(- i x)) / (2 i ), cos x = (e^(i x) + e^(- i x)) / 2 ) $ <eq-sin-cos-form-of-eulur> $ cases( sin alpha dot.c sin beta = 1/2 (cos (alpha - beta) - cos (alpha + beta)), cos alpha dot.c cos beta = 1/2 (cos (alpha - beta) + cos(alpha + beta)), sin alpha dot.c cos beta = 1/2 (sin(alpha + beta) + sin(alpha - beta)) ) $ #linebreak() 以$sin alpha dot.c sin beta$为例,使用@eq-euler-equation 进行证明。 #proof[ #let eulur_expr = (a, b, o) => $e^(#a) #o e^(#b)$ 将@eq-sin-cos-form-of-eulur 带入 $sin alpha dot.c sin beta$中,得到: $ sin alpha dot.c sin beta &= (#eulur_expr($i alpha$, $- i alpha$, $-$)) / (2 i) dot.c (#eulur_expr($i beta$, $-i beta$, $-$)) / (2 i) \ &=((e^(i (alpha + beta)) - e^(i (alpha - beta)) ) - (e^(-i (alpha - beta)) - e^(-i (alpha + beta)))) / (-4) \ &= ((e^(i (alpha + beta)) + e^(-i (alpha + beta)) ) - (e^(i (alpha - beta)) + e^(-i (alpha - beta)))) / (-4) \ &= -1/4 (2 dot.c cos(alpha + beta) - 2 dot.c cos(alpha - beta)) \ &= 1/2 (cos(alpha - beta) - cos(alpha + beta)) $ 证明完成。 ] == 三角函数的内积 #definition("三角函数的积分")[ 三角函数$sin w t $与$cos w t$在周期$[-T/2, T/2]$内的积分为0,即: $ integral_(-T/2)^(T/2) sin w t dif t = 0 \ integral_(-T/2)^(T/2) cos w t dif t = 0 \ $ 其中$w = (2 pi) / T$,$T$为三角函数$sin(w t)$与$cos (w t)$的最小周期。 ] #proof[ $ Integral(-T/2, T/2, sin w t, dif: t) &= lr(-1 / w cos w t |)_(-T/2)^(T/2) \ &= -1/w ( cos ((2 pi) / T dot.c T / 2) - cos((2 pi) / T dot.c -T / 2 )) \ &= -1 / w (cos pi - cos(-pi)) \ &= 0 $ <def-integral-of-sin-func> $ Integral(-T/2, T/2, cos w t, dif: t) &= lr(1 / w sin w t |)_(-T/2)^(T/2) \ &= 1/w ( sin ((2 pi) / T dot.c T / 2) - sin((2 pi) / T dot.c -T / 2 )) \ &= 1 / w (sin pi - sin(-pi)) \ &= 0 $ <def-integral-of-cos-func> ] #lemma("三角形周期函数的积分")[ 如果三角函数$sin w t$或$cos w t$的最小周期为$T$,其频率$w = (2 pi) / T$,则函数$sin n w t$或者$cos n w t$的在周期$[-T/2, T/2]$上的积分为0,即: $ integral_(-T/2)^(T/2) sin n w t dif t = integral_(-T/2)^(T/2) cos n w t dif t = 0 $ ] #proof[ 以$sin n w t$为例进行证明,$cos n w t$的情况类似。 令$w' = n w$,则函数$sin n w t = sin w' t$,则$T' = T / n$,则根据 @def-integral-of-sin-func 以及$sin$函数的周期性,可得: $ integral_(-T/2)^(T/2) sin n w t dif t &= integral_(-n T'/2)^(n T'/2) sin w' t dif t'\ &= sum_(k = 0)^n integral_(k T' - T'/2)^(k T' + T'/2) sin w' t dif t'\ &= sum_(k = 0)^n dot.c 0 \ &= 0 $ ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/modern-cv/0.1.0/README.md
markdown
Apache License 2.0
# Modern CV [![say thanks](https://img.shields.io/badge/Say%20Thanks-👍-1EAEDB.svg)](https://github.com/DeveloperPaul123/modern-cv/stargazers) [![Discord](https://img.shields.io/discord/652515194572111872?logo=Discord)](https://discord.gg/CX2ybByRnt) ![Release](https://img.shields.io/github/v/release/DeveloperPaul123/modern-cv) A port of the [Awesome-CV](https://github.com/posquit0/Awesome-CV) Latex resume template in [typst](https://github.com/typst/typst). ## Requirements You will need the `Roboto` and `Source Sans Pro` fonts installed on your system or available somewhere. If you are using the `typst` web app, no further action is necessary. You can download them from the following links: - [Roboto](https://fonts.google.com/specimen/Roboto) - [Source Sans Pro](https://github.com/adobe-fonts/source-sans-pro) This template also uses FontAwesome icons via the `[fontawesome](https://typst.app/universe/package/fontawesome)` package. See `typst fonts --help` for more information on configuring fonts for `typst` that are not installed on your system. ### Usage Below is a basic example for a simple resume: ```typst #import "@preview/modern-cv:0.1.0": * #show: resume.with( author: ( firstname: "John", lastname: "Smith", email: "<EMAIL>", phone: "(+1) 111-111-1111", github: "DeveloperPaul123", linkedin: "Example", address: "111 Example St. Example City, EX 11111", positions: ( "Software Engineer", "Software Architect" ) ), date: datetime.today().display() ) = Education #resume_entry( title: "Example University", location: "B.S. in Computer Science", date: "August 2014 - May 2019", description: "Example" ) #resume_item[ - #lorem(20) - #lorem(15) - #lorem(25) ] ``` ### Output | | | | --- | --- | | ![Resume](resume.png) | ![Coverletter](coverletter.png) |
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/visualize/path.typ
typst
// Test paths. --- path --- #set page(height: 300pt, width: 200pt) #table( columns: (1fr, 1fr), rows: (1fr, 1fr, 1fr), align: center + horizon, path( fill: red, closed: true, ((0%, 0%), (4%, -4%)), ((50%, 50%), (4%, -4%)), ((0%, 50%), (4%, 4%)), ((50%, 0%), (4%, 4%)), ), path( fill: purple, stroke: 1pt, (0pt, 0pt), (30pt, 30pt), (0pt, 30pt), (30pt, 0pt), ), path( fill: blue, stroke: 1pt, closed: true, ((30%, 0%), (35%, 30%), (-20%, 0%)), ((30%, 60%), (-20%, 0%), (0%, 0%)), ((50%, 30%), (60%, -30%), (60%, 0%)), ), path( stroke: 5pt, closed: true, (0pt, 30pt), (30pt, 30pt), (15pt, 0pt), ), path( fill: red, fill-rule: "non-zero", closed: true, (25pt, 0pt), (10pt, 50pt), (50pt, 20pt), (0pt, 20pt), (40pt, 50pt), ), path( fill: red, fill-rule: "even-odd", closed: true, (25pt, 0pt), (10pt, 50pt), (50pt, 20pt), (0pt, 20pt), (40pt, 50pt), ), ) --- path-bad-vertex --- // Error: 7-9 path vertex must have 1, 2, or 3 points #path(()) --- path-bad-point-count --- // Error: 7-47 path vertex must have 1, 2, or 3 points #path(((0%, 0%), (0%, 0%), (0%, 0%), (0%, 0%))) --- path-bad-point-array --- // Error: 7-31 point array must contain exactly two entries #path(((0%, 0%), (0%, 0%, 0%))) --- issue-path-in-sized-container --- // Paths used to implement `LayoutMultiple` rather than `LayoutSingle` without // fulfilling the necessary contract of respecting region expansion. #block( fill: aqua, width: 20pt, height: 15pt, path( (0pt, 0pt), (10pt, 10pt), ), )
https://github.com/rdboyes/resume
https://raw.githubusercontent.com/rdboyes/resume/main/cv.typ
typst
// Imports #import "@preview/brilliant-cv:2.0.2": cv #import "@preview/fontawesome:0.4.0" #let metadata = toml("./metadata.toml") #let importModules(modules, lang: metadata.language) = { for module in modules { include { "modules_" + lang + "/" + module + ".typ" } } } #show: cv.with( metadata ) #importModules(( "professional", "education", "publications", "skills", ))
https://github.com/alex-touza/fractal-explorer
https://raw.githubusercontent.com/alex-touza/fractal-explorer/main/paper/test.typ
typst
// unnumbered title page if needed // ... Title #pagebreak() // front-matter #set page(numbering: "I") #counter(page).update(1) // ... Acknowledgments #pagebreak() #outline() // page counter anchor #metadata(()) <front-matter> #pagebreak() // main document body #set page(numbering: "1") #counter(page).update(1) /* HERE. Still using Roman numbers instead of Arabic. */ = Something #lorem(4000) // back-matter #set page(numbering: "I") // must take page breaks into account, may need to be offset by +1 or -1 #context counter(page).update(counter(page).at(<front-matter>).first() + 1) = Glossary #lorem(50)
https://github.com/tilman151/pypst
https://raw.githubusercontent.com/tilman151/pypst/main/docs/examples/document/template.typ
typst
MIT License
#import "@preview/charged-ieee:0.1.0": ieee #show: ieee.with( title: [Using Templates with Pypst], abstract: [#lorem(100)], authors: ( ( name: "Alice", department: [Co-Author], organization: [Best University], email: "<EMAIL>" ), ( name: "Bob", department: [Co-Author], organization: [Best University], email: "<EMAIL>" ), ), index-terms: ("Scientific writing", "Typesetting", "Document creation", "Syntax") ) // include generated file #include("my-document.typ")
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/dimension/devanagari.typ
typst
Other
#import "/lib/draw.typ": * #import "/lib/glossary.typ": tr #import "/template/lang.typ": devanagari #let start = (0, 0) #let end = (1000, 260) #let (basex, basey) = (120, 70) #let width = 740 #let example = devanagari[टाइपोग् #h(-0.25em)राफी] #let graph = with-unit((ux, uy) => { // mesh(start, end, (100, 100), stroke: 1 * ux + gray) let lines = ( ([变音符号线], "rb", end.at(0), basex, basey + 153), ([#tr[headline]], "lb", 0, basex + width, basey + 100), ([#tr[baseline]], "lb", 0, basex + width, basey), ([半音符号线], "rb", end.at(0), basex, basey - 50), ) for (body, anchor, xs, xe, y) in lines { segment((xs, y), (xe, y), stroke: 2 * ux + gray.darken(30%)) txt(body, (xs, y), anchor: anchor, size: 25 * ux, dy: 4) } txt(example, (basex, basey), anchor: "lb", size: 170 * ux) }) #canvas(end, start: start, width: 90%, graph)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A840.typ
typst
Apache License 2.0
#let data = ( ("PHAGS-PA LETTER KA", "Lo", 0), ("PHAGS-PA LETTER KHA", "Lo", 0), ("PHAGS-PA LETTER GA", "Lo", 0), ("PHAGS-PA LETTER NGA", "Lo", 0), ("PHAGS-PA LETTER CA", "Lo", 0), ("PHAGS-PA LETTER CHA", "Lo", 0), ("PHAGS-PA LETTER JA", "Lo", 0), ("PHAGS-PA LETTER NYA", "Lo", 0), ("PHAGS-PA LETTER TA", "Lo", 0), ("PHAGS-PA LETTER THA", "Lo", 0), ("PHAGS-PA LETTER DA", "Lo", 0), ("PHAGS-PA LETTER NA", "Lo", 0), ("PHAGS-PA LETTER PA", "Lo", 0), ("PHAGS-PA LETTER PHA", "Lo", 0), ("PHAGS-PA LETTER BA", "Lo", 0), ("PHAGS-PA LETTER MA", "Lo", 0), ("PHAGS-PA LETTER TSA", "Lo", 0), ("PHAGS-PA LETTER TSHA", "Lo", 0), ("PHAGS-PA LETTER DZA", "Lo", 0), ("PHAGS-PA LETTER WA", "Lo", 0), ("PHAGS-PA LETTER ZHA", "Lo", 0), ("PHAGS-PA LETTER ZA", "Lo", 0), ("PHAGS-PA LETTER SMALL A", "Lo", 0), ("PHAGS-PA LETTER YA", "Lo", 0), ("PHAGS-PA LETTER RA", "Lo", 0), ("PHAGS-PA LETTER LA", "Lo", 0), ("PHAGS-PA LETTER SHA", "Lo", 0), ("PHAGS-PA LETTER SA", "Lo", 0), ("PHAGS-PA LETTER HA", "Lo", 0), ("PHAGS-PA LETTER A", "Lo", 0), ("PHAGS-PA LETTER I", "Lo", 0), ("PHAGS-PA LETTER U", "Lo", 0), ("PHAGS-PA LETTER E", "Lo", 0), ("PHAGS-PA LETTER O", "Lo", 0), ("PHAGS-PA LETTER QA", "Lo", 0), ("PHAGS-PA LETTER XA", "Lo", 0), ("PHAGS-PA LETTER FA", "Lo", 0), ("PHAGS-PA LETTER GGA", "Lo", 0), ("PHAGS-PA LETTER EE", "Lo", 0), ("PHAGS-PA SUBJOINED LETTER WA", "Lo", 0), ("PHAGS-PA SUBJOINED LETTER YA", "Lo", 0), ("PHAGS-PA LETTER TTA", "Lo", 0), ("PHAGS-PA LETTER TTHA", "Lo", 0), ("PHAGS-PA LETTER DDA", "Lo", 0), ("PHAGS-PA LETTER NNA", "Lo", 0), ("PHAGS-PA LETTER ALTERNATE YA", "Lo", 0), ("PHAGS-PA LETTER VOICELESS SHA", "Lo", 0), ("PHAGS-PA LETTER VOICED HA", "Lo", 0), ("PHAGS-PA LETTER ASPIRATED FA", "Lo", 0), ("PHAGS-PA SUBJOINED LETTER RA", "Lo", 0), ("PHAGS-PA SUPERFIXED LETTER RA", "Lo", 0), ("PHAGS-PA LETTER CANDRABINDU", "Lo", 0), ("PHAGS-PA SINGLE HEAD MARK", "Po", 0), ("PHAGS-PA DOUBLE HEAD MARK", "Po", 0), ("PHAGS-PA MARK SHAD", "Po", 0), ("PHAGS-PA MARK DOUBLE SHAD", "Po", 0), )
https://github.com/suiranruofeng/notebook
https://raw.githubusercontent.com/suiranruofeng/notebook/main/GW/引力与引力波.typ
typst
#align(center, text(17pt)[*General Relativity: Gravitational wave and Cosmology Notebook*]) #align(center)[XuweiZhang \ #link("<EMAIL>")] #set heading(numbering: "1.") = 等效原理 == 等效原理的表述 在自由下落的升降机里无法检验稳定均匀的静态外引力场,因为向下的引力和向上的惯性力相互抵消了。对于一般的运动,我们对于$N$个质点的系统,在外力$bold(F)(bold(x)_N-bold(x)_M)$和外引力场$bold(g)$的作用下 $ m_N (d^2bold(x)_N)/(d t^2)=m_N bold(g)+sum_M bold(F)(bold(x)_N-bold(x)_M) $ 假定我们作一个时空坐标变换 $ x'=x-1/2g t^2,space t'=t $ 这样$bold(g)$就被惯性力所抵消,运动方程变为 $ m_N (d^2 bold(x')_N)/(d t'^2)=sum_M bold(F)(bold(x')_N-bold(x')_M) $ 这就是自由下落坐标系。 == 坐标变换与联络 == 度规张量
https://github.com/francescoo22/LCD-exercises
https://raw.githubusercontent.com/francescoo22/LCD-exercises/main/src/M.typ
typst
#import "common.typ": * #import "rules.typ": * = Exercise M Discuss an extension of CCS with an operator of sequential composition between processes $P; Q$. Provide an operational semantics and analyze the possibility of having an encoding in CCS of the defined operator. *Solution* == $CCS_seq$ $ P, Q ::= K | alpha . P | sum_(i in I) alpha . P_i | (P | Q) | P[f] | P without L | P;Q $ == Operational Semantics #v(2em) *Classical rules* #grid( columns: (auto, auto, auto), column-gutter: 1fr, row-gutter: 2em, c1, c2, c3, c4, c5, c6, c7, c8 ) #v(2em) *$CCS_seq$ rules* #grid( columns: (auto, auto, auto), column-gutter: 1fr, row-gutter: 2em, r1, r2, r3, r4, r5, r6, r7, r8 ) #include "encoding.typ" #include "lemmas.typ" == Equivalence $ forall P in CCS_seq . P approx e(P) wnu $ let $ cr = {(P, Q wnu) | P, Q in CCS_seq , Q approx e(P)} $ we need to prove that $cr$ is a weak bisimulation i.e. - $forall P in CCS_seq . fi P atrans P' then e(P) wnu awtrans P'' wnu and P' cr (P'' wnu)$ - $forall P in CCS_seq . fi e(P) wnu atrans P'' wnu then P awtrans P' and P' cr (P'' wnu)$ The proof is done by induction on the height of the derivation tree, so we can rewrite it as follows: - $forall P in CCS_seq . forall h in NN . fi P atrans P' "with tree of height" h then e(P) wnu awtrans P'' wnu and P' cr (P'' wnu)$ - $forall P in CCS_seq . forall h in NN . fi e(P) wnu atrans P'' wnu "with tree of height" h then P awtrans P' and P' cr (P'' wnu)$ === First point *base case h=1* The only way a process can make a transition with derivation tree of height 1 is $ c1 $ and in this case also $ p1 $ and $P cr (e(P) wnu)$ because $e(P) approx e(P)$ *inductive case Const* if $ c8 $ $=>^"by induction" e(P) wnu atrans P'' wnu "and" P' cr (P'' wnu)$ $=> e(P) atrans P''$ so #v(1em) $ p2 $ and $P' cr (P'' wnu)$ *inductive case Hide* if $ c6 $ $=>^"by induction" e(P) wnu awtrans P'' wnu "and" P' cr (P'' wnu)\ =>^"relation" P'' approx e(P')\ =>^"only rule" e(P) awtrans P''$ $ p3 $ I have to prove that $P' wL cr P'' wL wnu$ i.e. $P'' wL approx e(P' wL)$ $ P'' wL approx^(P'' approx e(P')) e(P') wL = e(P' wL) $ *inductive case Red* if $ c7 $ $=>^"by induction" e(P) wnu awtrans P'' wnu "and" P' cr (P'' wnu)\ =>^"only rule" e(P) awtrans P''$ and so $ p4 $ and $P''[f] approx^(P'' approx e(P')) e(P') [f] = e(P' [f]) => P'[f] cr P''[f] wnu$ *Inductive case Sum* Sum case is trivial because if $ p5 $ also $ p6 $ and $P_j cr (e(P_j) wnu)$. *Inductive case Par-1/Par-2/Par-3* If $ c3 $ $=>^"by induction" e(P) wnu atrans P'' wnu "and" P' cr (P'' wnu)$ $=> e(P) atrans P''$ and so $ p7 $ #v(1em) we need to show that $(P'|Q) cr (P''[nu'/nu] | e(Q)[nu'/nu] | overline(nu') . overline(nu') . nu . 0) wnup wnu$ which is equivalent to show that $(P''[nu'/nu] | e(Q)[nu'/nu] | overline(nu') . overline(nu') . nu . 0) wnup approx e(P'|Q)$ $ P' cr P'' wnu =>^(cr "definition") P'' approx e(P') \ =>^"bisim properties" (P''[nu'/nu] | e(Q)[nu'/nu] | overline(nu') . overline(nu') . nu . 0) wnup approx (e(P')[nu'/nu] | e(Q)[nu'/nu] | overline(nu') . overline(nu') . nu . 0) wnup = e(P'|Q) $ Par-2 and Par-3 are similar *Inductive case Seq-L* If $ r7 $ $=>^"by induction" e(P) wnu atrans P'' wnu "and" P' cr (P'' wnu)$ $=> e(P) atrans P''$ and so $ p8 $ #v(1em) we need to show that $(P';Q) cr (P''[nu'/nu] | overline(v') . e(Q)) wnup wnu$ which is equivalent to show that $(P''[nu'/nu] | overline(v') . e(Q)) wnup approx e(P';Q)$ $ P' cr P'' wnu =>^(cr "definition") P'' approx e(P') \ =>^"bisim properties" (P''[nu'/nu] | overline(v') . e(Q)) wnup approx (e(P')[nu'/nu] | overline(v') . e(Q)) wnup = e(P';Q) $ *Inductive case Seq-R* If $ r8 $ $P ended =>^"lemma 0" e(P) ->^(tau*) P_"temp" ntrans P' and P' ended$ $Q atrans Q'=>^"by induction" e(Q) wnu atrans Q'' wnu "and" Q' cr (Q'' wnu) => e(Q) atrans Q''$ and so $ p9 $ #v(2em) $ p10 $ #v(2em) $ p11 $ #v(2em) Now I have to prove that $Q' cr (P' [nu'/nu] | Q'') wnup wnu$ Which is equivalent to prove that $(P' [nu'/nu] | Q'') wnup approx e(Q')$ $ P' ended =>^"End-Red" P'[nu'/nu] ended =>^"lemma 3" P'[nu'/nu] approx 0 \ => (P' [nu'/nu] | Q'') wnup approx (0 | Q'') wnup approx^(Q'' approx e(Q')) (0 | e(Q')) wnup approx^"lemma 4" 0 | e(Q') approx e(Q') $
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/PianoDiProgetto/sections/ConsuntivoSprint/UndicesimoSprint.typ
typst
MIT License
#import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost #import "../../functions.typ": rendicontazioneOreAPosteriori, rendicontazioneCostiAPosteriori, glossary ==== Undicesimo consuntivo *Inizio*: Venerdì 01/03/2024 *Fine*: Giovedì 07/03/2024 #rendicontazioneOreAPosteriori(sprintNumber: "11") #rendicontazioneCostiAPosteriori(sprintNumber: "11") ===== Analisi a posteriori La retrospettiva ha evidenziato come il totale delle ore preventivato per questo #glossary("sprint") si possa dire rispettato. La differenza tra preventivo e consuntivo è infatti pari a tre ore, che sul totale preventivato di 60 ore lavorative costituiscono un distacco pari al 5%, più che accettabile. Si vuole evidenziare come nel corso di questo #glossary("sprint"), per la prima volta, ciascun componente del team abbia totalizzato una media di quasi 10 ore produttive. Questo è coerente con la disponibilità espressa dal team dopo la prima revisione #glossary[RTB] e con la necessità di ogni membro di raggiungere la seconda revisione #glossary[PB] avendo impiegato almeno 80 ore produttive, il minimo per poter concludere il progetto. L'unica differenza significativa tra preventivo e consuntivo si può ritrovare nelle ore del ruolo di Amministratore: si era infatti erroneamente sottostimata la dimensione, in termini di ore produttive, delle task assegnate agli Amministratori. È stato inoltre rilevato che le ore assegnate all'attività di revisione, sebbene complessivamente non dissimili da quelle consuntivate, sono state distribuite su un numero esiguo di membri. Per questo motivo, nei prossimi #glossary[sprint] sarà bene distribuire il carico di lavoro su un numero maggiore di persone, evitando di concentrarlo solamente su alcuni individui. Infatti, designando ripetutamente gli stessi membri del team come Verificatori, si rischia di limitare la diversità di prospettive applicate al processo di verifica, portando ad una mancanza di identificazione di potenziali problemi o miglioramenti e, a lungo andare, ad un abbassamento della qualità del lavoro svolto. ===== Aggiornamento della pianificazione e gestione dei rischi Nel corso dello #glossary("sprint") in oggetto si è manifestato il rischio tecnologico RT1 o conoscenza tecnologica limitata: tale rischio si è concretizzato nell'utilizzo dello strumento Pydantic. Tuttavia, considerando il ruolo non centrale di tale libreria nell'#glossary[architettura] del progetto, il team ha optato per la sua rimozione. In questo caso le misure preventive individuate non sono state efficaci nell'eludere il rischio: il team, sottovalutando la complessità dello strumento, non aveva immaginato che potesse creare dei rallentamenti nello sviluppo e, di conseguenza, non ha applicato le misure preventive individuate. Come enunciato nell'analisi sopra, si è anche manifestato il rischio di comunicazione RC6 o ripetizioni nelle assegnazioni del ruolo di Verificatore: in particolare, sarebbe bene evitare scenari in cui gli stessi componenti del team vengono incaricati di verificare la #glossary[documentazione] ripetutamente, mentre altri il codice, senza che questi si scambino mai tali responsabilità; in futuro, dunque, il team ha intenzione di adottare una rotazione più efficace del ruolo, come delineato nelle misure preventive del rischio. Il team ha inoltre rilevato l'esigenza di intensificare il dialogo con la Proponente: nonostante le misure preventive per il rischio di comunicazione RC3 (frequenza limitata nella comunicazione con la Proponente), siano chiare riguardo alla necessità di mantenere una frequenza di incontri, e di conseguente ricezione di feedback, perlomeno settimanale, non vi è stato alcun tipo di comunicazione con l'azienda da all'incirca due settimane. Di conseguenza, si è rimarcata la volontà di organizzare un incontro al più presto e, possibilmente, di reintrodurre la frequenza settimanale che ha caratterizzato il periodo antecedente l'#glossary[RTB]. Infine, nonostante non si sia propriamente manifestato il rischio di pianificazione RP3 o "Variazioni nei tempi e costi del progetto", la decisione del team di non effettuare la terza revisione #glossary[CA] (rintracciabile nel verbale interno del 04/03) ha comunque avuto un impatto sulla pianificazione: infatti, se nel preventivo a finire redatto in occasione dell' #glossary[RTB] erano state dedicate alcune risorse allo svolgimento della #glossary[CA], ora queste sono utilizzabili in preparazione alla #glossary[PB]. Perciò non solo viene aggiornata la pianificazione all'interno del _Piano di Progetto_ aumentando le ore produttive a disposizione per determinati ruoli (Responsabile, Amministratore, Programmatore e Verificatore), ma il team ha anche intenzione di aumentare ulteriormente il ritmo di lavoro per sfruttare efficacemente le risorse aggiuntive a disposizione.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-ellipse-00.typ
typst
Other
// Default ellipse. #ellipse()
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/stonewall/0.1.0/example/example.typ
typst
Apache License 2.0
#import "../stonewall.typ": flags #set page(width: 200pt, height: auto, margin: 0pt) #set text(fill: black, size: 12pt) #set text(top-edge: "bounds", bottom-edge: "bounds") #stack( spacing: 3pt, ..flags.map(((name, preset)) => block( width: 100%, height: 20pt, fill: gradient.linear(..preset), align(center + horizon, smallcaps(name)), )) )
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/04_cardinalità.typ
typst
#import "../alias.typ": * #import "@preview/lemmify:0.1.5": * #let ( theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules ) = default-theorems("thm-group", lang: "it") #show: thm-rules #show thm-selector("thm-group", subgroup: "theorem"): it => block( it, stroke: red + 1pt, inset: 1em, breakable: true ) #show thm-selector("thm-group", subgroup: "proof"): it => block( it, stroke: green + 1pt, inset: 1em, breakable: true ) = Cardinalità == Isomorfismi Due insiemi $A$ e $B$ sono *isomorfi* (_equinumerosi_) se esiste una biiezione tra essi. Formalmente scriviamo: $ A tilde B. $ Detto $cal(U)$ l'insieme di tutti gli insiemi, la relazione $tilde$ è sottoinsieme di $cal(U)^2$. Dimostriamo che $tilde$ è una relazione di equivalenza: - *riflessività*: $A tilde A$, usiamo come biiezione la funzione identità $i_A$; - *simmetria*: $A tilde B arrow.long.double B tilde A$, usiamo come biiezione la funzione inversa; - *transitività*: $A tilde B and B tilde C arrow.long.double A tilde C$, usiamo come biiezione la composizione della funzione usata per $A tilde B$ con la funzione usata per $B tilde C$. Dato che $tilde$ è una relazione di equivalenza, ci permette di partizionare l'insieme $cal(U)$. La partizione che ne risulta è formata da classi di equivalenza che contengono insiemi isomorfi, ossia con la stessa cardinalità. Possiamo, quindi, definire la *cardinalità* come l'insieme quoziente di $cal(U)$ rispetto alla relazione $tilde$. Questo approccio permette di confrontare tra loro la cardinalità di insiemi infiniti, dato che basta trovare una funzione biettiva tra i due insiemi per poter affermare che siano isomorfi. == Cardinalità finita La prima classe di cardinalità che vediamo è quella delle *cardinalità finite*. Definiamo la seguente famiglia di insiemi: $ J_n = cases(emptyset & text(" se ") n = 0, {1,...,n} & text(" se ") n > 0) quad . $ Diremo che un insieme $A$ ha cardinalità finita se e solo se $A tilde J_n$ per qualche $n in NN$. In tal caso possiamo scrivere $|A| = n$. La classe di equivalenza $[J_n]_tilde$ identifica tutti gli insiemi di $cal(U)$ contenenti $n$ elementi. == Cardinalità infinita L'altra classe di cardinalità è quella delle *cardinalità infinite*, ovvero gli insiemi non in relazione con $J_n$. Questi insiemi sono divisibili in: - insiemi *numerabili*; - insiemi *non numerabili*. Analizziamo le due tipologie separatamente. === Insiemi numerabili Un insieme $A$ è numerabile se e solo se $A tilde NN$, ovvero $A in [NN]_tilde$. Gli insiemi numerabili vengono detti anche "*listabili*", in quanto è possibile elencare _tutti_ gli elementi dell'insieme $A$ tramite una regola, la funzione $f$ biettiva tra $NN$ e $A$. Grazie alla funzione $f$, è possibile elencare gli elementi di $A$ formando l'insieme: $ A = {f(0), space f(1), space dots}. $ Questo insieme è esaustivo, dato che elenca ogni elemento dell'insieme $A$ senza perderne nessuno. Tra gli insiemi numerabili più famosi troviamo: - numeri pari $PP$ e numeri dispari $DD$; - numeri interi $ZZ$, generati con la biiezione $f(n) = (-1)^n (frac(n + (n mod 2), 2))$; - numeri razionali $QQ$. Gli insiemi numerabili hanno cardinalità $aleph_0$ (si legge _"aleph zero"_). === Insiemi non numerabili Gli *insiemi non numerabili* sono insiemi a cardinalità infinita ma che non sono listabili come gli insiemi numerabili: sono "più fitti" di $NN$. Questo significa che ogni lista generata mancherebbe di qualche elemento e, quindi, non sarebbe esaustiva di tutti gli elementi dell'insieme. Il più famoso insieme non numerabile è l'insieme dei numeri reali $RR$. #theorem(numbering: none)[ L'insieme $RR$ non è numerabile ($RR tilde.not NN$). ] #proof[ \ Suddividiamo la dimostrazione in tre punti: + dimostriamo che $RR tilde (0,1)$; + dimostriamo che $NN tilde.not (0,1)$; + dimostriamo che $RR tilde.not NN$. [1] Partiamo con il dimostrare che $RR tilde (0,1)$: serve trovare una biiezione tra $RR$ e $(0,1)$. Usiamo una rappresentazione grafica, costruita in questo modo: - disegnare la circonferenza di raggio $1/2$ centrata in $1/2$; - disegnare la perpendicolare al punto da mappare che interseca la circonferenza; - disegnare la semiretta passante per il centro $C$ e l'intersezione precedente. L'intersezione tra l'asse reale e la retta finale è il punto mappato. #v(-36pt) #figure( image("assets/biiezione.svg", width: 70%) ) #v(12pt) In realtà, questo approccio ci permette di dire che $RR$ è isomorfo a qualsiasi segmento di lunghezza maggiore di 0.\ La stessa biiezione vale anche sull'intervallo chiuso $[0,1]$, utilizzando la "compattificazione" $overset(RR, .) = RR union {plus.minus infinity}$ e mappando $0$ su $-infinity$ e $1$ su $+infinity$. [2] Continuiamo dimostrando che $NN tilde.not (0,1)$: serve dimostrare che l'intervallo $(0,1)$ non è listabile, quindi che ogni lista che scrivo manca di almeno un elemento e per farlo proveremo a "costruire" proprio questo elemento.\ Per assurdo, sia $NN tilde (0,1)$. Allora, possiamo listare gli elementi di $(0,1)$ esaustivamente come: $ 0.& space a_(00) space a_(01) space a_(02) space dots \ 0.& space a_(10) space a_(11) space a_(12) space dots \ 0.& space a_(20) space a_(21) space a_(22) space dots \ 0.& space dots quad , $ dove con $a_(i j)$ indichiamo la cifra di posto $j$ dell'$i$-esimo elemento della lista. Costruiamo il numero $c = 0.c_0 c_1 c_2 dots$ tale che $ c_i = cases(2 quad & "se" a_(i i) eq.not 2, 3 & "se" a_(i i) = 2) quad . $ In altre parole, questo numero viene costruito "guardando" le cifre sulla diagonale principale. Questo numero appartiene a $(0,1)$, ma non appare nella lista scritta sopra: ogni cifra $c_i$ del numero costruito differisce per almeno una posizione (quella sulla diagonale principale) da qualunque numero nella lista. Questo è assurdo, visto che avevamo assunto $(0,1)$ numerabile $arrow.long.double NN tilde.not (0,1)$. [3] Terminiamo dimostrando che $RR tilde.not NN$ per transitività. Più in generale, non si riesce a listare nessun segmento di lunghezza maggiore di 0. ] Questo tipo di dimostrazione (in particolare il punto [2]) è detta *dimostrazione per diagonalizzazione*. L'insieme $RR$ viene detto *insieme continuo* e tutti gli insiemi isomorfi a $RR$ si dicono a loro volta continui. I più famosi insiemi continui sono: - $RR$: insieme dei numeri reali; - $CC$: insieme dei numeri complessi; - $TT subset II$: insieme dei numeri trascendenti. Vediamo due insiemi continui che saranno importanti successivamente. === Insieme delle parti Il primo insieme che vediamo è l'*insieme delle parti* di $NN$, detto anche _power set_, ed è così definito: $ P(NN) = 2^NN = {S bar.v S "è sottoinsieme di" NN}. $ #theorem(numbering: none)[ $P(NN) tilde.not NN$. ] #proof[ \ Dimostriamo questo teorema tramite diagonalizzazione. Il *vettore caratteristico* di un sottoinsieme è un vettore che nella posizione $p_i$ ha $1$ se $i in A$, altrimenti ha $0$. Rappresentiamo il sottoinsieme $A subset.eq NN$ sfruttando il suo vettore caratteristico: $ NN&: 0 space 1 space 2 space 3 space 4 space 5 space 6 space dots \ A&: 0 space 1 space 1 space 0 space 1 space 1 space 0 space dots quad . $ Per assurdo, sia $P(NN)$ numerabile. Vista questa proprietà, possiamo listare tutti i vettori caratteristici che appartengono a $P(NN)$ come: $ b_0 &= b_(00) space b_(01) space b_(02) space dots \ b_1 &= b_(10) space b_(11) space b_(12) space dots \ b_2 &= b_(20) space b_(21) space b_(22) space dots quad . $ Vogliamo costruire un vettore che appartenga a $P(NN)$, ma non è presente nella lista precedente. Definiamo il seguente: $ c = overline(b_(00)) space overline(b_(11)) space overline(b_(22)) dots $ che contiene nella posizione $c_i$ il complemento di $b_(i i)$. Questo vettore appartiene a $P(NN)$ (perché rappresenta sicuramente un suo sottoinsieme), ma non è presente nella lista precedente perché è diverso da ogni elemento in almeno una cifra, quella sulla diagonale principale. Questo è assurdo perché abbiamo assunto che $P(NN)$ fosse numerabile, quindi $P(NN) tilde.not NN$. ] Visto questo teorema possiamo concludere che: $ P(NN) tilde [0,1] tilde overset(RR, .). $ === Insieme delle funzioni Il secondo insieme che vediamo è l'*insieme delle funzioni* da $NN$ in $NN$ così definito: $ NN_bot^NN = {f: NN arrow.long NN}. $ #theorem(numbering: none)[ $NN_bot^NN tilde.not NN$. ] #proof[ \ Anche in questo caso useremo la diagonalizzazione. Per assurdo, assumiamo $NN_bot^NN$ numerabile. Possiamo, quindi, listare $NN_bot^NN$ come ${f_0, f_1, f_2, dots}$. #align(center)[ #table( columns: (10%, 15%, 15%, 15%, 15%, 15%, 15%), inset: 10pt, align: horizon, [], [$0$], [$1$], [$2$], [$3$], [$dots$], [$NN$], [$f_0$], [$f_0 (0)$], [$f_0 (1)$], [$f_0 (2)$], [$f_0 (3)$], [$dots$], [$dots$], [$f_1$], [$f_1 (0)$], [$f_1 (1)$], [$f_1 (2)$], [$f_1 (3)$], [$dots$], [$dots$], [$f_2$], [$f_2 (0)$], [$f_2 (1)$], [$f_2 (2)$], [$f_2 (3)$], [$dots$], [$dots$], [$dots$], [$dots$], [$dots$], [$dots$], [$dots$], [$dots$], [$dots$], ) ] Costruiamo una funzione $phi: NN arrow.long NN_bot$ per dimostrare l'assurdo. Una prima versione potrebbe essere la funzione $phi(n) = f_n (n) + 1$, per _disallineare_ la diagonale, ma questo non va bene: se $f_n (n) = bot$ non sappiamo dare un valore a $phi(n) = bot + 1$. Definiamo quindi la funzione $ phi(n) = cases(1 & "se" f_n (n) = bot, f_n (n) + 1 quad & "se" f_n (n) arrow.b) quad . $ Questa funzione è una funzione che appartiene a $NN_bot^NN$, ma non è presente nella lista precedente. Infatti, $forall k in NN$ otteniamo $ phi(k) = cases(1 eq.not f_k (k) = bot & "se" f_k (k) = bot, f_k (k) + 1 eq.not f_k (k) quad & "se" f_k (k) arrow.b) quad . $ Questo è assurdo, perché abbiamo assunto $P(NN)$ numerabile, quindi $P(NN) tilde.not NN$. ]
https://github.com/metamuffin/typst
https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/math/frac.typ
typst
Apache License 2.0
// Test fractions. --- // Test that denominator baseline matches in the common case. $ x = 1/2 = a/(a h) = a/a = a/(1/2) $ --- // Test parenthesis removal. $ (|x| + |y|)/2 < [1+2]/3 $ --- // Test large fraction. $ x = (-b plus.minus sqrt(b^2 - 4a c))/(2a) $ --- // Test binomial. $ binom(circle, square) $ --- // Error: 8-13 missing argument: lower $ binom(x^2) $ --- // Test associativity. $ 1/2/3 = (1/2)/3 = 1/(2/3) $ --- // Test precedence. $ a_1/b_2, 1/f(x), zeta(x)/2, "foo"[|x|]/2 \ 1.2/3.7, 2.3^3.4 \ 🏳️‍🌈[x]/2, f [x]/2, phi [x]/2, 🏳️‍🌈 [x]/2 \ +[x]/2, 1(x)/2, 2[x]/2 \ (a)b/2, b(a)[b]/2 $
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/examples/pages.typ
typst
MIT License
#import "/src/lib.typ": hydra #set page(paper: "a7", margin: (y: 4em), numbering: "1", header: context { if calc.odd(here().page()) { align(right, emph(hydra(1))) } else { align(left, emph(hydra(2))) } line(length: 100%) }) #set heading(numbering: "1.1") #show heading.where(level: 1): it => pagebreak(weak: true) + it = Introduction #lorem(50) = Content == First Section #lorem(50) == Second Section #lorem(100)
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/06_Ergebnisse/03_empfehlung.typ
typst
== Empfehlungen zur Ergänzung von ... <recommendation-next-features>
https://github.com/takotori/PhAI-Spick
https://raw.githubusercontent.com/takotori/PhAI-Spick/main/sections/kraft.typ
typst
#import "../utils.typ": * = Kraft #grid( columns: (50%, auto), gutter: 5pt, [*Kraft:*], [$arrow(F)_"res"=m arrow(a)$], [*Gewichtskraft:*], [$F_G=m g $], [*Federkraft:*], [$F_F=D y space.quad D &= "Federkonst." \ y &= abs(l - l_0)$], [*Hook\`sches Gesetz:*], [$Delta F=D dot Delta y$], [*Schiefe Ebene:* #image("../figures/kraftSchiefeEbene.png")], [$F_G=m g$ \ #v(5pt) *Normalkraft:* \ $F_N=m g dot cos(alpha) $ \ #v(5pt) *Hangabtriebskraft*: \ $F_H=m g dot sin(alpha)$ \ #v(5pt) *Haftreibungskraft:* \ $F_"HR"=μ dot F_N$ #v(5pt)], [*Zentripetalkraft / \ Zentrifugalkraft:*], [$F_Z=(m v^2)/r = m dot omega^2 dot r$], ) #v(4pt) #grid( columns: (45%, auto), gutter: 2pt, image("../figures/Kreiskraefte.png"), text(size: 6pt, [Die *Zentripetalkraft* und *Zentrifugalkraft* wirken bei einer beschleunigten Kreisbewegung und haben die gleiche Formel. Es handelt sich um entgegengesetzte Kräfte, die abhängig von dem Bezugssystem sind. Wird eine Kreisbewegung von außen betrachtet, wirkt nur die Zentripetalkraft. Befindet sich der Beobachter im rotierenden System nimmt er beide Kräfte wahr.]), ) == Kraft Statik In der Statik bewegen sich die Objekte nicht. Dort gilt also: \ $ sum F=0, v(t) = 0 m slash s, a(t) = 0 m slash s^2 $ #align( center, image("../figures/kraftStatik1.png"), ) $ "X) " F_s dot cos(colblue(18^circle.small)) &-μ dot F_N &-F_G dot sin(colgreen(35^circle.small))=0 $ \ $ "Y) " F_s dot sin(colblue(18^circle.small)) &+F_N &-F_G dot cos(colgreen(35^circle.small))=0 $ #image("../figures/kraftStatik2.png") Ein Gewicht der Masse $m = 10"kg"$ wird entsprechend der obigen Skizze durch Seile an einer Wand befestigt. Welche Kräfte wirken im linken und rechten Seil? *1. Methode:* $ F_L/sqrt(3^2+4^2 ) vec(-3,4)+F_R/sqrt(8^2+6^2 ) vec(8,6)+m g vec(0,-1)=0 $ *2. Methode* $ F_L vec(-cos(alpha),sin(alpha))+F_R vec(cos(beta),sin(beta))+m g vec(0,-1)=0 $ #grid( columns: (auto, auto), gutter: 5pt, align: (center +bottom, center+bottom), image("../figures/kraftStatik3.png"), image("../figures/kraftStatik4.png") ) Eine $20 "kN"$ schwere Luftseilbahnkabine hängt reibungsfrei an einem Tragseil und wird durch ein Zugseil festgehalten. Wie gross sind die Zugkräfte im Zug- und im Tragseil? ($alpha = 20^circle.small$ und $beta = 20^circle.small$) #v(5pt) $ F_"S1" = F_"S2" = F_T $ $ F_T vec(cos(180^circle.small - 20^circle.small),sin(180^circle.small - 20^circle.small)) +F_T vec(cos(20^circle.small),sin(20^circle.small)) \ + F_Z vec(cos(20^circle.small),sin(20^circle.small)) + vec(0,-20 "kN")=0 \ ==> F_T = 9.97 dot 10^4 N, F_Z = 8.48 dot 10^3 N $
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/decide-scoring/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #create-body-entry( title: "Decide: Scoring Triballs", type: "decide", date: datetime(year: 2023, month: 9, day: 2), author: "<NAME>", witness: "Violet Ridge", )[ We rated each option on: - Efficiency on a scale of 1 to 10 - Stability on a scale of 1 to 10 - Feasibility on a scale of 1 to 10. #decision-matrix( properties: ((name: "Efficiency"), (name: "Stability"), (name: "Feasibility")), ("Extentable Hook", 7, 4, 9), ("Fold Out Flaps", 10, 9, 10), ("Shot Out Net", 5, 3, 4), ) #admonition( type: "decision", )[ We chose the fold out flaps. This option is both the most effective in cost of actuators and also the simplest design, leading to it being overall the best choice. ] #heading[First Prototype] #grid( columns: (1fr, 1fr), gutter: 20pt, [ Our first prototype was mainly comprised of L-channel. It featured a piston to push the L-channel forwards, mounted on the bottom of the drivetrain. #admonition( type: "warning", )[ While this design was stable and powerful, it exposed the fitting of the piston outwards, making it very easy to hit. ] We decided to discard this design after discovering that there was no other way to mount the piston in this position without exposing it. ], image("./first-prototype.jpg"), ) ] #create-body-entry( title: "Decide: Scoring Triballs", type: "decide", date: datetime(year: 2023, month: 9, day: 2), // TODO: correct to date of final cad creation author: "<NAME>", witness: "Violet Ridge", )[ #heading([Final Design]) Our final design used a top mounted piston and a piece of C-channel as the wing base. This strikes the right balance between structural integrity and lightness, and also doesn't expose the piston to other robots. #grid( columns: (1fr, 1fr), gutter: 20pt, figure(image("./iso.png"), caption: "Isometric view"), figure(image("./top.png"), caption: "Top view"), figure(image("./side.png"), caption: "Side view"), figure(image("./front.png"), caption: "Front view"), ) // TODO: add part diagrams and CAD #image("./1.png") #image("./2.png") ]
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/angle/angle-separator/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": * #set page(width: auto, height: auto, margin: 1cm) #ang(6, 7, 6.5) #ang(6, 7, 6.5, angle-separator: " ")
https://github.com/PauKaifler/typst-template-dhbw
https://raw.githubusercontent.com/PauKaifler/typst-template-dhbw/main/README.md
markdown
Apache License 2.0
# Typst DHBW Template This template is my interpretation of the guidelines required by the DHBW Stuttgart and Ravensburg. I wrote it for my 2023 bachelor thesis, and it is compatible with Typst 0.11.1. While I am no longer a student at the DHBW, I do accept pull requests and I intend to resolve any issues that might arise in the future. ## Setup This template requires you to separately download the DHBW Logo. You can download it from <https://upload.wikimedia.org/wikipedia/de/1/1d/DHBW-Logo.svg> and save it in the same directory the `template.typ` is stored in as `dhbw-logo.svg`. You may run the following command in said directory to do that: ```sh curl https://upload.wikimedia.org/wikipedia/de/1/1d/DHBW-Logo.svg -o dhbw-logo.svg ``` ## Example You can check out how this template can be used in the [example.typ](./example.typ) found within this repository. The following is the first page of that document: ![first page of a rendered sample document](./example.png) ## License This repository is dual-licensed under the [MIT](https://choosealicense.com/licenses/mit/) and [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) license.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/codetastic/0.1.0/util.typ
typst
Apache License 2.0
#import "@preview/cetz:0.1.1" #import cetz.draw: rect #let to-arr(code) = { if type(code) == "integer" { code = str(code) } if type(code) == "string" { code = code.clusters().map(int) } if type(code) != "array" { panic("Code needs to be provided as integer, string or array. Got " + type(code)) } return code } #let to-int-arr(code) = { return to-arr(code).map(int) } #let weighted-sum(nums, weights) = { let w-func if type(weights) == "array" { w-func = (i) => { return weights.at(calc.rem(i, weights.len())) } } else if type(weights) == "function" { w-func = weights } return nums.enumerate().fold(0, (s,v) => { let (i, n) = (..v) s + n * w-func(i) }) } #let check-code( code, digits, generator, tester ) = { if code.len() == digits - 1 { code.push(generator(code)) } else if code.len() == digits { if not tester(code) { panic("Checksum failed for code " + repr(code) + ". Should be " + str(generator(code.slice(0,-1)))) } } else { panic("Code has to be " + (digits - 1) + " digits (excluding checksum). Got " + code.len()) } return code } #let draw-bars(bits, width:0.264mm, height:18.28mm, bg: white, fg: black) = { // Draw background rect to set fixed size rect((0,0), (bits.len() * width, height), fill:bg, stroke:none, name:"code-bg") // Cluster bits to draw thick bars // as one rect bits = bits.fold((), (c, v) => { if v { if c == () or c.last() == 0 { c.push(1) } else { c.at(-1) += 1 } } else { c.push(0) } c }) // Draw bars let i = 0 for bit in bits { if bit > 0 { rect( (i*width,0), (rel:(bit*width,height)), fill:fg, stroke:none ) i += bit } else { i += 1 } } } #let draw-rect(at, width, height, fill: white, ..style) = { rect( at, (rel:(width,height)), fill: fill, stroke:none, ..style ) } /// Draw a bitfield of binary data as a 2d code matrix. /// /// Bits will be drawn from the top left to the bottom right. /// `bits.at(0).at(0)` is located at coordinate `(0,0)` and /// `bits.at(-1).at(-1)` is located at the last coordinate /// on the bottom right. #let draw-matrix( bitfield, quiet-zone: 4, size: 3mm, bg: white, fg: black ) = { let (w, h) = (bitfield.first().len(), bitfield.len()) let (x, y) = (quiet-zone, quiet-zone) // Draw background rect to set fixed size rect((0,0), ((w+2*quiet-zone) * size, (h+2*quiet-zone) * -size), fill:bg, stroke:none, name:"code-bg") // Draw modules for i in range(h) { for j in range(w) { if bitfield.at(i).at(j) { rect( ((x + j) * size, (y + i) * -size), (rel:(size, -size)), fill:fg, stroke:none ) } } } }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/with_builtin.typ
typst
Apache License 2.0
#let g = rgb.with(/* position */);
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list-attach_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test non-attached tight list. #set block(spacing: 15pt) Hello - A World - B - C More.
https://github.com/andreasKroepelin/lovelace
https://raw.githubusercontent.com/andreasKroepelin/lovelace/main/examples/label-low-level.typ
typst
MIT License
#import "../lib.typ": * #set page(width: auto, height: auto, margin: 1em) #set text(font: "TeX Gyre Pagella") #show math.equation: set text(font: "TeX Gyre Pagella Math") #pseudocode( with-line-label(<start>)[do something], with-line-label(<important>)[do something important], [go back to @start], ) The relevance of the step in @important cannot be overstated.
https://github.com/yaoyuanArtemis/resume
https://raw.githubusercontent.com/yaoyuanArtemis/resume/main/data.typ
typst
Do What The F*ck You Want To Public License
#import "template.typ": * #let name = "<NAME>" #let namezh = "刘峰" #let email = [ #icon("email.svg") <EMAIL> ] #let phone = [ #icon("phone.svg") (+86) 18520170194 ] #let home = [ #icon("home.svg") #link("https://yaoyuanartemis.github.io/")[ yaoyuanartemis.github.io ] ] #let github = [ #icon("github.svg") #link("https://github.com/yaoyuanArtemis")[ yaoyuanArtemis ] ] #let linkin = [ #icon("linkedin.svg") #link("https://www.linkedin.com/in/%E5%B3%B0-%E5%88%98-2a7a8b2b8/")[ <NAME> ] ] #let author = ( name: name, email: email, phone: phone, home: home, github: github, linkin: linkin, ) #let authorzh = ( name: namezh, email: email, phone: phone, home: home, github: github, linkin: linkin, ) #let selftitle = [ Self Introduction ] #let selftitlezh = [ 自我总结 ] #let self = [ I am passionate about pursuing technological advancements and have an unrelenting pursuit of knowledge, particularly in the field of computer science. Additionally, I enjoy meeting interesting people and experiencing diverse aspects of society. Whether it's the culture and phenomena in China or around the world, I am full of curiosity and eager to explore. ] #let selfzh = [ 我热衷于追求技术进步,对知识有着不懈的追求,尤其是在计算机领域。同时,我也乐于在社会中结识有趣的人和事,深入了解社会的各个方面。无论是中国还是世界各地的文化和现象,我都充满好奇并渴望探索。 ] #let edutitle = [ Education ] #let edutitlezh = [ 教育经历 ] #let edu = [ #datedsubsection( align(left)[ *Anhui University (211) the gifted class of computer science* \ - GPA:3.30/4 - Languages: Chinese Grade A,English IELTS 6.5 - Programming Capabilities:CCF-CSP 180 - Relevant Courses:Principles of Computer Organization,Data Structures,Operating Systems,Computer Networks,Database Principles,Object-Oriented Programming,Digital Image Processing,Big Data Technology,Machine Learning,Pattern Recognition,Optimization Methods,Mathematical Modeling (Advanced Class),Artificial Intelligence,Principles of Compilers,Writing International Academic Papers (Graduate Course) - Honors and Awards:Second-Class Scholarship for Academic Excellence,Anhui Province Big Data Competition ], align(right)[ Hefei, China \ 2017.9 - 2021.6 ] ) ] #let eduzh = [ #datedsubsection( align(left)[ *安徽大学 (211) 计算机科学与技术英才班* \ - GPA:3.30/4 - 语言:中文二级甲等、英文IELTS6.5 - 计算机编程:CCF-CSP 180 - 相关课程:计算机组成原理,数据结构,操作系统,计算机网络,数据库原理,面向对象程序设计,数字图像处理,大数据技术,机器学习,模式识别,最优化方法,数学建模(提高班),人工智能,编译原理,国际学术论文撰写(研究生课程) - 荣誉奖项:学习优秀二等奖学金、安徽省大数据竞赛 ], align(right)[ 合肥.中国 \ 2017.9 - 2021.6 ] ) ] #let techtitle = [ Technical Skills ] #let techtitlezh = [ 项目技能 ] #let tech = [ - *Programming*: - Proficient in Python and C++, which were the primary languages used for university coursework. - Learned and used Java, MATLAB, HTML, LaTeX, and Typst. - Familiar with HTML5, CSS, JavaScript, and TypeScript, and frequently used in practical work. - Experienced with Node.js, Midway.js, and familiar with Egg.js and Nest.js for full-stack development. - Used Spring Boot, MyBatis, and Restful technologies for API development in a company context. - *Key words*: Node.js TypeScript Nest.js HTML5 CSS - *Tools*: - Proficient in using the Scrapy framework and have developed a gaming combat system using the Django framework. - Experienced with databases such as MySQL and SQL Server. - Studied "Machine Learning" and "Pattern Recognition," and am familiar with related algorithms. - Configured clusters for Apache and MySQL. - Utilized distributed web crawlers and scraping technologies such as BeautifulSoup, Scrapy, and regular expressions (Re). ] #let techzh = [ - *编程语言*: - 语言 Python C++较为熟悉,大学大课程作业使用的主力语言,Java Matlab Html Latex Typst学习并使用 - 熟悉HTML5、CSS、 JavaScript、TypeScript,并在实际工作中经常使用 - 使用过NodeJs MidWayJS,会使用EggJs NestJS等全栈技术栈 - 使用SpringBoot、Myabtis、Restful等Java技术栈,在公司用作接口开发技术 - *工具*: - 会使用Scrapy框架,使用过Django框架开发游戏对战系统 - 会使用 MySql、SqlSever等数据库 - 学习《机器学习》、《模式识别》,对机器学习相关算法较为熟悉 - 配置过Apache、MySql等集群搭建 - 使用分布式爬虫,BeautifulSoup、Scrapy、Re做爬取技术 ] #let projecttitle = [ Project Experience ] #let projecttitlezh = [ 项目经历 ] #let projectexperience = [ #datedsubsection( align(left)[ *China Merchants Bank. CMB Technology (Shenzhen) Co., Ltd.* \ Developer ], align(right)[ 2021.7 - 2023.9 ] ) - After joining the company through campus recruitment, I participated in the development of the cloud operations platform, specifically the OracleDM platform (a platform for operating Oracle databases). I primarily served as a frontend developer, using React 17, TypeScript, and Ant Design for web development and API data acquisition. - #lorem(8) #datedsubsection( align(left)[ *Alibaba. Zhejiang Fliggy Network Technology Co., Ltd.* \ Frontend Developer and Operations (Ops) ], align(right)[ 2021.7 - 2023.9 ] ) - Development of the Backend System "Jellyfish" for Risk Control - Included API calls for data and permission interfaces, and integration of event tracking. - Independently developed a policy document parsing tool. - Automated the parsing of airline policies from Excel, achieving a coverage of 10 airlines by February with an automation rate of 75%. - Supported policy document types include Word 2007, Word 2003, Excel 2007, and Excel 2003. - By building automatic parsing capabilities for airline policy documents, improved operational efficiency, reducing the time required to process complex policy documents from one day to within two hours. - Developed basic pages for the backend ticketing operations system. ] #let projectexperiencezh = [ #datedsubsection( align(left)[ *招商银行.招银网络科技(深圳)有限公司* \ 开发者 ], align(right)[ 2021.7 - 2023.9 ] ) - 校招入职后参与公司的云运维平台开发,具体是平台中的OracleDM平台开发(行内对Oracle数据库做操作的平台)主要是担任前端开发工程师,使用React17、TypeScript、AntDesign做网页开发以及接口对接 - 使用SpringBoot技术做接口开发 #datedsubsection( align(left)[ *阿里巴巴.浙江飞猪网络技术有限公司* \ 前端开发工程师以及运维 ], align(right)[ 2023.9 - 2024.5 ] ) - 开发风控中后台系统“水母Jellyfish”开发 - 包括数据接口调用、权限接口调用、埋点接入 - 独立开发政策文件解析工具 - 针对航司政策解析excel投产,累计至2月,航司覆盖率已达10个,自动化率达到75% - 政策文件类型支持word2007、word2003、excel2007、excel2003 - 通过建设航司政策文件自动解析能力,提高运营投放准备工作效率,使得复杂政策文件由一天缩短至2小时内 政策解析工具、机票运营中后台、水母风控都是前端主导项目 - 开发基本的机票运营中后台页面 ] #let activitytitle = [ Research Experience ] #let activitytitlezh = [ 科研经历 ] #let activityzh = [ #datedsubsection( align(left)[ *属性网络社团检测* \ 本科期间发表学术论文 A Reduced Mixed Representation Based Multi-Objective Evolutionary Algorithm for Large-Scale Overlapping Community Detection DOI: 10.1109/CEC45853.2021.9504894 属于安徽大学教育部计算智能与信息处理重点实验室成果 ], align(right)[ 2019-2021 ] ) // #datedsubsection( // align(left)[ // *#lorem(8) *\ // #lorem(4) // ], // align(right)[ // 202x - _present_ // ] // ) // #lorem(16) // #datedsubsection( // align(left)[ // *#lorem(8)* \ // #lorem(4) // ], // align(right)[ // 202x // ] // ) // - #lorem(8) // - #lorem(8) ] #let activity = [ #datedsubsection( align(left)[ *Attribute-Based Network Community Detection* \ Published Academic Papers During Undergraduate Studies: A Reduced Mixed Representation Based Multi-Objective Evolutionary Algorithm for Large-Scale Overlapping Community Detection DOI: 10.1109/CEC45853.2021.9504894. Achievement of the Key Laboratory of Computational Intelligence and Information Processing, Ministry of Education, Anhui University ], align(right)[ 2019-2021 ] ) ] #let hobbiestitle = [ Hobbies and Interests ] #let hobbiestitlezh = [ 兴趣爱好 ] #let hobbieszh = [ - *文化*: 喜欢了解学习地理、世界史和中国史、宏观经济 - *运动*: 喜欢踢足球,主队皇马;户外锻炼,游泳,滑雪也有不定期进行 ] #let hobbies = [ - *Culture*: Enjoys Learning About Geography, World History, Chinese History, and Macroeconomics - *Sports*: Enjoys playing soccer (main team: Real Madrid); also regularly engages in outdoor activities such as swimming and skiing. ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/flow-orphan_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 100pt) #lorem(12) = Introduction This is the start and it goes on.
https://github.com/TheWebDev27/Calc-II-Honors-Project
https://raw.githubusercontent.com/TheWebDev27/Calc-II-Honors-Project/main/part2.typ
typst
#set text( font: "New Computer Modern", size: 10pt ) #set par( leading: .75em ) #set align(center) = The Nonstandard Approach #set align(left) One drawback with the real analysis approach involving the epsilon-delta definition of the limit is its cumbersome notation. Proofs can quickly become cluttered with absolute values and inequalities that at times can be challenging to keep track of and connect to one another. By formalizing the idea of the infinitesimal to where basic algebraic techniques can be applied to it, a new system of analysis can be developed to study the same material that real analysis does while taking advantage of simpler and more concise notation. \ #text(14pt)[ Introduction ] This introduction follows section 1.4 of #set align(center) <NAME>. (1976). _Foundations of Infinitesimal Calculus_, <NAME> & Schmidt. #set align(left) Let us first consider two points on the parabola $f(x) = x^2$. One will be a fixed point at $(x_0, y_0)$, while the other will lie some distance away at $(x_0 + Delta x, y_0 + Delta y)$ where $Delta x$ and $Delta y$ represent the horizontal and vertical distances between the two points. #set text(9pt) #figure( image("images/parabola slope.png", width: 60%), caption: [$(x_0, y_0)$ and $(x_0 + Delta x, y_0 + Delta y)$ on $f(x)=x^2$] ) #set text(10pt) The average slope between any two points $(x_1, y_1)$ and $(x_2, y_2)$ is the ratio of the change in $y$ to the change in $x$: #set align(center) $display((Delta y) / (Delta x)=(y_2-y_1)/(x_2-x_1)).$ #set align(left) Therefore, the average slope between the two points on the parabola above is \ #set align(center) #h(125pt) $display(((y_0 + Delta y) - y_0)/((x_0 + Delta x) - x_0)).$ #h(110pt) (1) #set align(left) The function is $f(x)=x^2$, so any $y$ value is determined by plugging in its corresponding input $x$ into it. The points then become $(x_0, x_0^2)$ and $(x_0 + Delta x, (x_0 + Delta x)^2)$. Substituting in these new $y$ coordinates into $(1)$ gives #set align(center) $display((Delta y)/(Delta x)) &= display(((x_0 + Delta x)^2 - x_0^2)/((x_0 + Delta x) - x_0)) \ &= display(([x_0^2+2x_0 Delta x + (Delta x)^2] - x^2_0)/((x_0+Delta x) - x_0)) \ &= display((2x_0 Delta x + (Delta x)^2)/(Delta x)) \ #h(105pt) &= 2x _0 + Delta x. #h(145pt) (2) $ #set align(left) (2) gives us the slope in terms of a fixed point's $x$-coordinate and its horizontal distance $Delta x$ from some variable point. If we want to find the slope of a line that lies *tangent* to the curve -- meaning that it intersects the curve at exactly one point -- at $(x_0, x_0^2)$, then we can treat $Delta x$ as a very small number so that the tangent line's slope is very close to (2). We #emph[cannot] set $Delta x$ equal to zero, because (2) follows from a quotient where $Delta x$ is present in the denominator of a quotient. Anyhow, treating it as a miniscule value leads to the intuitive result that the slope of some line tangent to the point $(x_0, x_0^2)$ on the parabola is essentially #set align(center) $2x_0.$ #set align(left) This loose usage of an infinitesimal -- treating a value as infinitely small to where it can be ignored -- has in fact produced decently accurate results throughout the development of calculus over the past several centuries, being used by those such as Newton, Leibniz, Euler, and others in varying forms. However, it is by no means rigorous and does not establish results with absolute certainty. Why? This is because we are left with a problem: How do we know exactly when numbers are small enough to be treated as negligible in a calculation? This now brings us to our first formal definition: #set text(font: "Source Serif") #set align(center) #grid( columns: 80%, rows: auto, [ #set align(left) An *infinitesimal* is a number $epsilon$ where #set align(center) $-a<epsilon<a$ #set align(left) for any positive real number $a$. ] ) #set text(font: "New Computer Modern") #set align(left) Amongst the real numbers, 0 would be the only value that qualifies as infinitesimal. What we now do is expand the real number system by introducing *hyperreal numbers*. These include the real numbers along with nonzero infinitesimals, which can be thought of as numbers that lie infinitely close to 0. The set of all real numbers is represented by $RR$, while the set of all hyperreal numbers is represented by $RR^*$. Various symbols including $Delta x, Delta y, epsilon, #text[and] delta$ are used to symbolize infinitesimals. For instance, $x + Delta x$ is interpretted as some quantity that lies #emph[infinitely] close to $x$, and $display(1/epsilon)$ represents an *infinite positive number*. Hyperreal numbers that are not infinitely positive or negative are *finite numbers*. #set text(9pt) #figure( image("images/hyperreal line.png", width: 70%), caption: [Hyperreal number line visualized] ) #set text(10pt) We can conceptualize the scale of hyperreal numbers by imagining ourselves "zooming in" infinitely close onto on a real number such as 0 or 100 on the hyperreal number line (Figure 5). This helps to clarify the nature of hyperreal numbers as merely an extension of the real numbers, so much so to where its properties and the arithmetic involved with them match exactly with that of the reals. This approach to analysis is known as *nonstandard analysis*. Going back to the calculation of the instantaneous slope of $f(x)=x^2$, we now treat the value of $Delta x$ as a nonzero infinitesimal under this new lense of analysis. This means that the expression #set align(center) $2x_0 + Delta x$ #set align(left) lies infinitely close to $2x_0$, so the slope of any line tangent to $(x_0, x_0^2)$ is concluded to be $2x_0$. \ \ Let's use infinitesimals to try computing the instantaneous slope of the function #set align(center) $f(x)=sqrt(x)$. #set text(9pt) #figure( image("images/square root function.png", width: 70%), caption: [$f(x)=sqrt(x)$] ) #set text(10pt) #set align(left) The average slope between a fixed point and a variable point on the square root function is \ \ #set align(center) $display((Delta y)/(Delta x) &= (f(x_0+Delta x)-f(x_0))/(Delta x) \ &= (sqrt(x_0 + Delta x) - sqrt(x_0))/(Delta x) )$ #set align(left) In order to calculate the instaneous slope, we need a way to cancel out $Delta x$ from the denominator. This can be readily accomplished by multiplying the quotient by the conjugate of the numerator in the form of 1 to induce a difference of squares: #set align(center) $display( (sqrt(x_0 + Delta x) - sqrt(x_0))/(Delta x) dot ((sqrt(x_0+Delta x) + sqrt(x_0))/(sqrt(x_0 + Delta x) + sqrt(x_0))) = ((sqrt(x_0 + Delta x))^2 - (sqrt(x_0))^2)/(Delta x(sqrt(x_0 + Delta x) + sqrt(x_0))) \ )$ $display( &= ((x_0 + Delta x) - x_0)/(Delta x(sqrt(x_0 + Delta x) + sqrt(x_0))) \ &= (Delta x)/(Delta x(sqrt(x_0 + Delta x) + sqrt(x_0))) \ &= 1/(sqrt(x_0 + Delta x) + sqrt(x_0)) )$ #set align(left) Since the $Delta x$ in the denominator is infinitesimal, this means that the quantity $sqrt(x_0 + Delta x)$ is infinitely close to $sqrt(x_0)$, so #set align(center) $display( 1/(sqrt(x_0 + Delta x) + sqrt(x_0))&=1/(sqrt(x_0) + sqrt(x_0))\ &= 1/(2sqrt(x_0)). )$ #set align(left) Those who have experience with calculating the derivatives of functions using the limit definition of the derivative will be quick to notice that these calculations play out mostly the same way with the exception of the absence of the limit. At this stage, the skeptical reader may question how exactly this system has solved the concern regarding rigor. In particular, how do the ideas presented so far formalize the concept of deeming a quantity in a given calculation as neglible? What has happened so far is that we have #emph[defined] what it means for a number to be considered negligibly small, so if a given quantity does not meet the criteria specified, then we know that it cannot be ignored. Beyond that, however, we have done nothing more than explore some basic ideas of nonstandard analysis, and rigorous justifications require a working knowledge of abstract algebra. The details are obviously left out, as they lie far beyond my expertise. While the curious reader may feel left unfulfilled by this, keep in mind that the formalization of many concepts require complicated machinery, so it is commonplace for students of mathematics to take a result at face value initially and uncover its logical justification far later. As a direct analogue to the current situation, consider the analysis behind limits covered in the first half of this paper. It is likely that most undergraduates who have studied limits will never encounter this rigorous treatment of them in their lifetime -- let alone give it any consideration. Ambitious students, however, will inevitably run across it in a real analysis course, and the formalities are unveiled then. We now lie in the very same boat with infinitesimals! #pagebreak() #text(14pt)[ Basic Applications of Infinitesimals ] This section follows #set align(center) <NAME>. (2012). _A Brief Introduction to Infinitesimal Calculus_, can be found at \ https://homepage.math.uiowa.edu/~stroyan/InfsmlCalculus/Lecture1/Lect1.pdf. #set align(left) It is due time for us to see how infinitesimal logic can be used to provide basic intuitive argumentation for a couple of ideas seen in calculus. #set text(font: "Source Serif") #set align(center) #grid( columns: 80%, rows: auto, [ #set align(left) *Theorem 4 - The Extreme Value Theorem* \ Consider a function $f(x)$ that is continuous on a closed interval $[a, b]$. There then exist two numbers $x_(min)$ and $x_(max)$ at which $f(x)$ achieves its minimum and maximum values respectively where #set align(center) $f(x_(min)) <= f(x) <= f(x_(max))$ #set align(left) for all other $x$'s. ] ) #set text(font: "New Computer Modern") #set align(left) #set text(9pt) #figure( image("images/extreme value theorem.png", width: 50%), caption: [Extreme value theorem visualized] ) #set text(10pt) The extreme value theorem asserts that if a function smoothly travels over an interval of inputs, then it must take on a minimum and a maximum value at some inputs $x_(min)$ and $x_(max)$. *Continuity* entails that the outputs of a function are close to one another if the inputs are close. In other words, a small change in the input should only ever produce a proportionately small change in the output. Mathematically speaking, a function $f(x)$ is continuous on a closed interval $[a,b]$ only when #set align(center) $a <= x_1 approx x_2 <= b arrow.r.double.long f(x_1) approx f(x_2)$ #set align(left) where the $approx$ symbol means that two quantities are _approximately_ equal (very close to one another). With this property fleshed out, we can now go about providing an intuitive argument for the extreme value theorem. We start by dividing up the interval $[a,b]$ into small increments like so: #set align(center) $display(a < a + (b-a)/H < a + (2(b-a))/H < dots.h.c < a + (k(b-a))/H < dots.h.c < b) $, #set align(left) where $b-a$ is the length of the interval, $H$ is the number of parts the interval is partitioned into, and $k$ is a positive integer between 1 and $H$. Amongst the partition points, $f(x)$ achieves some maximum #v(-2pt) value at one (or possibly more than one) of the partition points $x_M=display(a + (k(b-a))/H)$, so #set align(center) #v(5pt) $f(x_M) >= f(x_1)$ for any $x_1=display(a + (j(b-a))/H), j != k$. #set align(left) #v(2pt)We know that any input $x$ in the interval $[a, b]$ lies within a distance of $display((b-a)/(2H))$ from one of the #v(-2pt) partition points. To see why, consider the closed interval [2,12] divided into 5 equal subintervals ($H = 5$) so that the partition points are #set align(center) $display(2\, #h(10pt) 2 + (12-2)/5\, #h(10pt) 2 + (2(12-2))/5\, #h(10pt) 2 + (3(12-2))/5\, #h(10pt) 2 + (4(12-2))/5\, #h(10pt) 2 + (5(12-2))/5) \ = #h(5pt) 2, #h(5pt) 4, #h(5pt) 6, #h(5pt) 8, #h(5pt) 10, #h(5pt) 12.$ #set align(left) Since the size of the interval is 10, and it is being partitioned into 5 subintervals, the distance between each partition point is #set align(center) $display((b-a)/H = (12 - 2)/5 = 2).$ #set align(left) and #set align(center) $display((b-a)/(2H) = 1).$ #set text(9pt) #figure( image("images/number line.png", width: 70%), caption: [Partition points visualized] ) #set align(left) #set text(10pt) If we think of the quantity $display((b-a)/(2H))$ as half of the distance between consecutive partition points and #v(-2pt) imagine a one-dimensional radius of $display((b-a)/(2H))$ around each partition, then we can see that these radii #v(0pt)cover all of the values between the partition points. Therefore, any value of $x$ within the interval must #v(0pt) lie within a distance of $display((b-a)/(2H))$ from one of the partition points. \ If we now let $H$ grow exceedingly large to the point where $display((b-a)/(2H))$ becomes infinitesimal, then the set of #v(-2pt) partition points will eventually "fill up" the rest of the interval $[a,b]$ so that any value of $x$ within the interval lies infinitely close to one of the partition points. In others words, #set align(center) $x approx x_1$ for any $x$ in $[a,b]$, #set align(left) which means #set align(center) $f(x_M) >= f(x_1) approx f(x)$, #set align(left) and this gives us the approximate maximum of $f(x)$. A similar argument can then be made for the approximation of the function's minimum, and this concludes the intuitive argument for the extreme value theorem, although this is by no means a formal proof.\ \
https://github.com/Geson-anko/vconf24_template_typst
https://raw.githubusercontent.com/Geson-anko/vconf24_template_typst/main/sample.typ
typst
// sample.typ #import "vconf2024.typ": conf #show: doc => conf( title: "バーチャル学会2024要旨テンプレート(タイトルを記入)", authors: ( (name: [hinoride#super[1]], contact: "Twitter: @hiddenotna"), (name: [はこつき#super[2]], contact: "E-mail: <EMAIL>"), (name: [Lcamu#super[2]], contact: "Twitter: @ogtonvr180426"), ), affiliations: ([#super[1]トライボロジー勉強会], [#super[2]ラーメン同好会]), abstract: [ ここに本研究の内容をまとめた概要を記入すること.要旨執筆にあたり不明な点がある場合にはバーチャル学会実行委員会にご連絡ください. ], bibliography-file: "bibliography.yaml", doc, ) = 緒言 本テンプレートはTypstを用いてバーチャル学会の要旨原稿を作成するためのファイルである. = 原稿の書式 == 全体のフォーマット A4判用紙のPDFで提出する.Word,LaTeXもしくはTypstファイルでの作成を原則とし,レイアウトは2カラム,フォントサイズはタイトル18pt・本文10ptとする.最大ページ数は4ページとし,和文フォントは明朝体,英文フォントはTimes New Roman,Centuryなどの標準的なものを使用すること. - 表題:今回の研究内容が端的に分かるようにする. - 著者名・連絡先・所属:著者名にはハンドルネームを使用することが可能である.最低1名について必ず、学会後にも確実に連絡がとれる連絡先を記載すること.また所属は任意に記載し複数の場合は1, 2・・・と記す. - 概要:今回の研究内容を1/2頁以内で記述する. == 内容について 発表要旨は次の事項を基本として,簡潔に記載することが望ましい. - 緒言:今回の研究のいきさつと研究目的を示す. - 研究方法:他の人が同じような研究ができるような書き方を心がける. - 結果:事実のみをまとめる.自分の意見は含めない. - 考察:結果で示した事実をもとに、その解釈やそこでの因果関係などについて議論する. - 結言:研究のまとめを記載する. - 参考文献:本文中に引用順に記載する. == 表記方法 本文,大見出し,小見出しなどを明瞭にすること.本文中では「つぎの表」のような表現を避け,@fig:sample_figure や表1のように書く.また,図表のキャプションはそれ単体で読んだ際に図表の意味が理解できるように簡潔に記述する. == 参考文献 本文中に別の著者の文献を引用する場合は,引用箇所の最後部に@rafferty1994 , @vconf2023, @okatani2015 , @kataoka2016 , @hinoride2023 のような符号をつけること.本要旨最後部に「参考文献」の項目を用意し,各文献の情報を記載すること.記載の際には他の人が各文献にアクセスできるような表現方法とすること.Webサイトを引用する場合,ページタイトル,URL,参照日を記載すること. == 字体・記号略号 下記の点に注意し,判読・理解しやすい原稿となるよう努める. - 上つき文字,下つき文字:小さく間違いやすいから特に注意し,その位置を明確に示す. - 学名:生物種の学名はイタリック体とする. - 略語:略語を用いる場合には,初出時に正式名称を表記(スペルアウト)する.2回目からは略語で表記する. - 量単位:国際単位系(SI)を用いる. - 数式:独立した式の文字(変数)は指定のない限りイタリック体に組む.式の一連番号を( )で囲み,頁の右端に書く.文中の式は一行に収める. - 脚注:本文中に\*, a, bなどを右肩につけ,そのページの下に横線を引き,横線の下に記述する. == 図表の作成 図および表の説明は,本文を見なくても大要が把握できる程度の最小限のものであることが望ましい.これらは@fig:sample_figure のようにすべて本文中から参照する. 図の下に題名・説明文を記述する.題名はその終わりにピリオドを入れる.写真も図として扱う.顕微鏡写真などの縮小,拡大を正確に示すべき図では,必ず図中に標準尺度を示す線を記入する(×1000等では示さない). 表は要旨で言及する情報のみを記載し,題名は上に,説明文は下に記述する.題名はその終わりにピリオドを入れる.表中の列の頭には適切な題をつけ,適切な略字を用いて短くする.単位を明示する.各行・各列に番号をつけることは本文引用に必要な場合を除き避ける. #figure( image("vconf2024.png", width: 95%), caption: [主張を裏付けるデータや説明のための図を配置してもよい.], ) <fig:sample_figure> #heading(level: 1, numbering: none)[謝辞] バーチャル学会 Typst版テンプレートの作成にあたり,はこつき\@re_hako_moon様のLaTeXテンプレートを参考にさせていただきました.心より深く感謝申し上げます.
https://github.com/amanuensisfrances/LaTeX-math-expressions-in-Typst
https://raw.githubusercontent.com/amanuensisfrances/LaTeX-math-expressions-in-Typst/main/LaTeX-math-expressions-in-Typst.typ
typst
MIT License
// LaTeX MATH EXPRESSIONS IN TYPST // (based on https://mirrors.ctan.org/info/symbols/math/maths-symbols.pdf and https://mirrors.ctan.org/fonts/newcomputermodern/doc/newcm-unimath-symbols.pdf) // Math Alphabets #let mathrm(input) = {$serif(#input)$} #let mathsf(input) = {$sans(#input)$} #let mathtt(input) = {$mono(#input)$} #let mathup(input) = {$upright(#input)$} #let mathit(input) = {$italic(#input)$} #let mathbf(input) = {$bold(#input)$} #let mathbb(input) = {$bb(#input)$} #let mathcal(input) = {$cal(#input)$} #let mathscr(input) = {$cal(#input)$} // see https://tex.stackexchange.com/q/361688 and https://zhuanlan.zhihu.com/p/569922028 #let mathfrak(input) = {$frak(#input)$} #let mathnormal(input) = {$serif(italic(#input))$} // Greek Letters #let varepsilon = {$epsilon.alt$} // the default \epsilon in LaTeX #let vartheta = {$theta.alt$} #let varkappa = {$kappa.alt$} #let varpi = {$pi.alt$} #let varrho = {$rho.alt$} #let varphi = {$phi.alt$} // the default \phi in LaTeX // Binary Operation Symbols #let pm = {$plus.minus$} #let mp = {$minus.plus$} #let Ast = {$ast.op$} #let star = {$star.op$} #let circ = {$compose$} #let bullet = {$•$} #let cdot = {$dot.op$} #let cap = {$sect$} #let cup = {$union$} #let uplus = {$union.plus$} #let sqcap = {$sect.sq$} #let sqcup = {$union.sq$} #let vee = {$and$} #let land = {$and$} #let wedge = {$or$} #let lor = {$or$} #let setminus = {$without$} #let wr = {$wreath$} #let smalldiamond = {$diamond.stroked.small$} #let bigtriangleup = {$triangle.stroked.t$} #let bigtriangledown = {$triangle.stroked.b$} #let triangleleft = {$triangle.stroked.l$} #let triangleright = {$triangle.stroked.r$} #let smalltriangleleft = {$triangle.stroked.small.l$} #let smalltriangleright = {$triangle.stroked.small.r$} #let oplus = {$plus.circle$} #let ominus = {$minus.circle$} #let otimes = {$times.circle$} #let oslash = {$⊘$} #let odot = {$dot.circle$} #let bigcirc = {$circle.big$} #let ddagger = {$dagger.double$} #let amalg = {$⨿$} // Relation Symbols #let leq = {$lt.eq$} #let preceq = {$⪯$} #let ll = {$lt.double$} #let subseteq = {$subset.eq$} #let sqsubseteq = {$subset.eq.sq$} #let vdash = {$⊢$} #let geq = {$gt.eq$} #let succeq = {$⪰$} #let gg = {$gt.double$} #let supseteq = {$supset.eq$} #let sqsupseteq = {$supset.eq.sq$} #let ni = {$in.rev$} #let dashv = {$⊣$} #let equiv = {$ident$} #let sim = {$tilde.op$} #let simeq = {$tilde.eq$} #let asymp = {$≍$} #let cong = {$tilde.eqq$} #let neq = {$eq.not$} #let doteq = {$≐$} #let propto = {$prop$} #let mid = {$\u{2223}$} #let bowtie = {$⋈$} #let smile = {$⌣$} #let frown = {$⌢$} // Punctuation Symbols #let cdotp = {$dot.c$} // Arrow symbols #let leftarrow = {$arrow.l$} #let Leftarrow = {$arrow.l.double$} #let rightarrow = {$arrow.r$} #let to = {$arrow.r$} #let Rightarrow = {$arrow.r.double$} #let leftrightarrow = {$arrow.l.r$} #let Leftrightarrow = {$arrow.l.r.double$} #let mapsto = {$arrow.r.bar$} #let hookleftarrow = {$arrow.l.hook$} #let leftharpoonup = {$harpoon.lt$} #let leftharpoondown = {$harpoon.lb$} #let rightleftharpoons = {$harpoons.rtlb$} #let longleftarrow = {$arrow.l.long$} #let Longleftarrow = {$arrow.l.double.long$} #let longrightarrow = {$arrow.r.long$} #let Longrightarrow = {$arrow.r.double.long$} #let implies = {$thin thin arrow.r.double.long thin thin$} #let longleftrightarrow = {$arrow.l.r.long$} #let Longleftrightarrow = {$arrow.l.r.double.long$} #let iff = {$thin thin arrow.l.r.double.long thin thin$} #let longmapsto = {$arrow.r.long.bar$} #let hookrightarrow = {$arrow.r.hook$} #let rightharpoonup = {$harpoon.rt$} #let rightharpoondown = {$harpoon.rb$} #let rightcurvedarrow = {$⤳$} #let leadsto = {$⤳$} #let uparrow = {$arrow.t$} #let Uparrow = {$arrow.t.double$} #let downarrow = {$arrow.b$} #let Downarrow = {$arrow.b.double$} #let updownarrow = {$arrow.t.b$} #let Updownarrow = {$arrow.t.b.double$} #let nearrow = {$arrow.tr$} #let searrow = {$arrow.br$} #let swarrow = {$arrow.bl$} #let nwarrow = {$arrow.tl$} #let longrightsquigarrow = {$arrow.r.long.squiggly$} // Miscellaneous Symbols #let ldots = {$dots.h$} #let aleph = {$א$} #let hbar = {$planck.reduce$} #let imath = {$𝚤$} #let jmath = {$𝚥$} #let wp = {$℘$} #let mho = {$ohm.inv$} #let cdots = {$dots.h.c$} #let emptyset = {$nothing$} #let surd = {$√$} #let top = {$⊤$} #let bot = {$⊥$} #let neg = {$not$} #let flat = {$♭$} #let natural = {$♮$} #let sharp = {$♯$} #let partial = {$∂$} #let ddots = {$dots.down$} #let infty = {$infinity$} #let Box = {$square.stroked$} #let Diamond = {$diamond.stroked$} #let Triangle = {$triangle.stroked.t$} #let clubsuit = {$suit.club$} #let diamondsuit = {$♢$} #let heartsuit = {$♡$} #let spadesuit = {$suit.spade$} #let varclubsuit = {$♧$} #let vardiamondsuit = {$suit.diamond$} #let varheartsuit = {$suit.heart$} #let varspadesuit = {$♤$} // Variable-sized Symbols #let prod = {$product$} #let coprod = {$product.co$} #let int = {$integral$} #let oint = {$integral.cont$} #let Join = {$⨝$} #let bigcap = {$sect.big$} #let bigcup = {$union.big$} #let bigsqcup = {$union.sq.big$} #let bigvee = {$or.big$} #let bigwedge = {$and.big$} #let bigodot = {$dot.circle.big$} #let bigotimes = {$times.circle.big$} #let bigoplus = {$plus.circle.big$} #let biguplus = {$union.plus.big$} // Log-like Symbols #let operatorname(input) = {$op(#input)$} // arccos is predefined #let arccot = {$operatorname("arccot")$} #let arccsc = {$operatorname("arccsc")$} #let arcosh = {$operatorname("arcosh")$} #let arcoth = {$operatorname("arcoth")$} #let arcsch = {$operatorname("arcsch")$} #let arcsec = {$operatorname("arcsec")$} // arcsin is predefined // arctan is predefined // arg is predefined #let arsech = {$operatorname("arsech")$} #let arsinh = {$operatorname("arsinh")$} #let artanh = {$operatorname("artanh")$} // cos is predefined // cosh is predefined // cot is predefined // coth is predefined // ctg is predfined // csc is predefined #let csch = {$operatorname("csch")$} // deg is predefined // det is predefined // dim is predefined // exp is predefined // gcd is predefined // hom is predefined // #let Im = {$operatorname("Im")$} // uncomment this to redefine the imaginary part command from the default "ℑ" to "Im" // inf is predefined // ker is predefined #let lcm = {$operatorname("lcm")$} // lg is predefined // lim is predefined // liminf is predefined // limsup is predefined // ln is predefined // log is predefined // max is predefined // min is predefined // mod is predefined // Pr is predefined // #let Re = {$operatorname("Re")$} // uncomment this to redefine the real part command from the default "ℜ" to "Re" // sec is predefined #let sech = {$operatorname("sech")$} // sin is predefined // sinh is predefined // sup is predefined // tan is predefined // tanh is predefined // tg is predefined // Delimiters #let lfloor = {$⌊$} #let rfloor = {$⌋$} #let langle = {$⟨$} #let rangle = {$⟩$} #let vert = {$|$} #let Vert = {$‖$} #let lceil = {$⌈$} #let rceil = {$⌉$} // Math Mode Accents #let check(input) = {$accent(#input, caron)$} #let Vec(input) = {$accent(#input, arrow)$} #let ddot(input) = {$accent(#input, dot.double)$} // Some other constructions #let widetilde(input) = {$accent(#input, tilde)$} #let overleftarrow(input) = {$accent(#input, arrow.l)$} #let widehat(input) = {$accent(#input, hat)$} #let overrightarrow(input) = {$accent(#input, arrow.r)$} // Typst's root(n, x) = LaTeX's \sqrt[n]{x} // Typst's \frac(a, b) = LaTeX's \frac{a}{b} // AMS Delimiters #let ulcorner = {$⌜$} #let urcorner = {$⌝$} #let llcorner = {$⌞$} #let lrcorner = {$⌟$} // AMS Arrows #let dashrightarrow = {$arrow.r.dashed$} #let rightdasharrow = {$arrow.r.dashed$} #let Lleftarrow = {$arrow.l.quad$} #let leftrightharpoons = {$harpoons.ltrb$} #let upuparrows = {$arrows.tt$} #let leftrightsquigarrow = {$↭$} #let rightleftarrows = {$arrows.rl$} #let downdownarrows = {$arrows.bb$} #let dashleftarrow = {$arrow.l.dashed$} #let leftdasharrow = {$arrow.l.dashed$} #let twoheadleftarrow = {$arrow.l.twohead$} #let curvearrowleft = {$arrow.ccw.half$} #let upharpoonleft = {$harpoon.tl$} #let rightrightarrows = {$arrows.rr$} #let twoheadrightarrow = {$arrow.r.twohead$} #let curvearrowright = {$arrow.cw.half$} #let upharpoonright = {$harpoon.tr$} #let leftleftarrows = {$arrows.ll$} #let leftarrowtail = {$arrow.l.tail$} #let circlearrowleft = {$arrow.ccw$} #let downharpoonleft = {$harpoon.bl$} #let rightarrowtail = {$arrow.r.tail$} #let circlearrowright = {$arrow.cw$} #let downharpoonright = {$harpoon.br$} #let leftrightarrows = {$arrows.lr$} #let looparrowleft = {$arrow.l.loop$} #let Lsh = {$↰$} #let rightrightarrows = {$arrows.rr$} #let looparrowright = {$arrow.r.loop$} #let Rsh = {$↱$} #let rightsquigarrow = {$arrow.r.squiggly$} // AMS Negated Arrows #let nleftarrow = {$arrow.l.not$} #let nleftrightarrow = {$arrow.l.r.not$} #let nrightarrow = {$arrow.r.not$} #let nLeftrightarrow = {$arrow.l.r.double.not$} #let nLeftarrow = {$arrow.l.double.not$} #let nRightarrow = {$arrow.r.double.not$} // AMS Greek #let digamma = {$ϝ$} #let updigamma = {$ϝ$} #let Digamma = {$Ϝ$} #let upDigamma = {$Ϝ$} #let varkappa = {$ϰ$} #let upvarkappa = {$kappa.alt$} // AMS Hebrew #let beth = {$ב$} #let daleth = {$ד$} #let gimel = {$ג$} // AMS Miscellaneous #let Square = {$square.stroked$} #let measureadangle = {$angle.arc$} #let Game = {$⅁$} #let blacktriangle = {$triangle.filled.small.t$} #let bigstar = {$★$} #let diagup = {$∕$} #let hslash = {$planck.reduce$} #let lozenge = {$lozenge.stroked$} #let nexists = {$exists.not$} #let Bbbk = {$𝕜$} #let blacktriangledown = {$triangle.filled.small.b$} #let sphericalangle = {$angle.spheric$} #let diagdown = {$⧵$} #let vartriangle = {$triangle.stroked.small.t$} #let circledS = {$Ⓢ$} #let backprime = {$‵$} #let blacksquare = {$square.filled$} #let triangledown = {$triangle.stroked.small.b$} #let Finv = {$Ⅎ$} #let varnothing = {$⌀$} #let diameter = {$⌀$} #let blacklozenge = {$⧫$} #let eth = {$ð$} #let matheth = {$ð$} // AMS Binary Operators #let dotplus = {$plus.dot$} #let barwedge = {$⊼$} #let boxtimes = {$times.square$} #let ltimes = {$⋉$} #let curlywedge = {$and.curly$} #let circledcirc = {$circle.nested$} #let smallsetminus = {$∖$} #let veebar = {$⊻$} #let boxdot = {$dot.square$} #let rtimes = {$⋊$} #let curlyvee = {$or.curly$} #let centerdot = {$dot.c$} #let Cap = {$sect.double$} #let doublebarwedge = {$⩞$} #let boxplus = {$plus.square$} #let leftthreetimes = {$times.l$} #let circleddash = {$dash.circle$} #let intercal = {$⊺$} #let Cup = {$union.double$} #let boxminus = {$minus.square$} #let divideontimes = {$times.div$} #let rightthreetimes = {$times.r$} #let circledast = {$ast.circle$} // AMS Binary Relations #let leqq = {$lt.eqq$} #let lessapprox = {$⪅$} #let lessgtr = {$lt.gt$} #let risingdotseq = {$≓$} #let subseteqq = {$⫅$} #let curlyeqprec = {$eq.prec$} #let trianglelefteq = {$⊴$} #let unlhd = {$⊴$} #let smallfrown = {$⏜$} #let geqslant = {$⩾$} #let gtrdot = {$gt.dot$} #let gtreqqless = {$⪌$} #let thicksim = {$sim$} #let sqsupset = {$supset.sq$} #let succaprox = {$succ.approx$} #let shortmid = {$thin thin thin thin ⃓ thin$} #let varpropto = {$propto$} #let blacktriangleright = {$triangle.filled.r$} #let leqslant = {$⩽$} #let approxeq = {$approx.eq$} #let lesseqgtr = {$lt.eq.gt$} #let fallingdotseq = {$≒$} #let Subset = {$subset.double$} #let precsim = {$prec.tilde$} #let vDash = {$⊨$} #let bumpeq = {$≏$} #let eqslantgtr = {$⪖$} #let ggg = {$gt.triple$} #let eqcirc = {$≖$} #let thickapprox = {$approx$} #let succcurlyeq = {$succ.eq$} #let vartriangleright = {$⊳$} #let rhd = {$⊳$} #let shortparallel = {$thin thin thin ⃓ thin ⃓$} #let blacktriangleleft = {$triangle.filled.l$} #let eqslantless = {$⪕$} #let lessdot = {$lt.dot$} #let lesseqqgtr = {$⪋$} #let backsim = {$tilde.rev$} #let sqsubset = {$subset.sq$} #let precapprox = {$prec.approx$} #let Vvdash = {$⊪$} #let Bumpeq = {$≎$} #let gtrsim = {$gt.tilde$} #let gtrless = {$gt.lt$} #let circeq = {$≗$} #let supseteqq = {$⫆$} #let curlysucceq = {$eq.succ$} #let trianglerighteq = {$⊵$} #let unrhd = {$⊵$} #let between = {$≬$} #let lesssim = {$lt.tilde$} #let lll = {$lt.triple$} #let doteqdot = {$≑$} #let Doteq = {$≑$} #let backsimeq = {$tilde.eq.rev$} #let preccurlyeq = {$prec.eq$} #let vartriangleleft = {$⊲$} #let lhd = {$⊲$} #let smallsmile = {$⏝$} #let geqq = {$gt.eqq$} #let gtrapprox = {$⪆$} #let gtreqless = {$gt.eq.lt$} #let triangleq = {$eq.delta$} #let Supset = {$supset.double$} #let succsim = {$succ.tilde$} #let Vdash = {$⊩$} #let pitchfork = {$⋔$} #let backepsilon = {$϶$} #let upbackepsilon = {$϶$} // AMS Negated Binary Relations #let nless = {$lt.not$} #let nleq = {$lt.eq.not$} #let lnapprox = {$⪉$} #let precnapprox = {$prec.napprox$} #let nvdash = {$⊬$} #let nsubseteq = {$subset.eq.not$} #let nsubseteqq = {$#h(5pt) slash #h(-7pt)⫅$} #let varsubsetneqq = {$⫋$} #let ngeqq = {$#h(5pt) slash #h(-7pt) gt.eqq$} #let gnsim = {$gt.ntilde$} #let nsucceq = {$succ.eq.not$} #let nshortparallel = {$thin thin thin #h(0.75pt) ̷#h(-0.75pt) ⃓ thin ⃓$} #let ntriangleright = {$⋫$} #let nvartriangleright = {$⋫$} #let supsetneq = {$supset.neq$} #let nleq = {$lt.eq.not$} #let lneqq = {$lt.neqq$} #let nprec = {$prec.not$} #let nsim = {$tilde.not$} #let nvDash = {$⊭$} #let subsetneq = {$subset.neq$} #let ngtr = {$gt.not$} #let gneq = {$⪈$} #let gnapprox = {$⪊$} #let succnsim = {$succ.ntilde$} #let nparallel = {$parallel.not$} #let ntrianglerighteq = {$⋭$} #let varsupsetneq = {$supset.eq_(#h(-4pt) ̷)$} #let nleqslant = {$#h(5pt) slash #h(-7pt) ⩽$} #let lvertneqq = {$lt.eqq_(#h(-8.2pt)|)$} #let npreceq = {$#h(4.75pt) slash #h(-7.25pt) ⪯$} #let notshortmid = {$thin thin thin thin #h(-0.25pt) ̷ #h(0.25pt) ⃓ thin$} #let ntriangleleft = {$⋪$} #let nvartriangleleft = {$⋪$} #let varsubsetneq = {$subset.eq_(#h(-4pt) ̷)$} #let ngeq = {$gt.eq.not$} #let gneqq = {$gt.neqq$} #let nsucc = {$succ.not$} #let succnapprox = {$succ.napprox$} #let nvDash = {$⊭$} #let nsupseteq = {$supset.eq.not$} #let supsetneqq = {$⫌$} #let nleqq = {$#h(5pt) slash #h(-7pt) lt.eqq$} #let lnsim = {$lt.ntilde$} #let precnsim = {$prec.ntilde$} #let nmid = {$divides.not$} #let ntrianglelefteq = {$⋬$} #let subsetneqq = {$⫋$} #let ngeqslant = {$#h(5pt) slash #h(-7pt)⩾$} #let gvertneqq = {$gt.eqq_(#h(-8.2pt)|)$} #let ncong = {$tilde.eqq.not$} #let nVDash = {$⊯$} #let nsupseteqq = {$#h(5pt) slash #h(-7pt)⫆$} #let varsupsetneqq = {$⫌$} // Selected stmaryrd Delimiters (that are available in the NewComputerModern Math font) #let Lbag = {$⟅$} #let Rbag = {$⟆$} #let lbag = {$⟅$} #let rbag = {$⟆$} #let llceil = {$⌈ #h(-3.5pt) ⌈ #h(-1.125pt)$} #let lCeil = {$⌈ #h(-3.5pt) ⌈ #h(-1.125pt)$} #let rrceil = {$#h(-1.125pt) ⌉ #h(-3.5pt) ⌉$} #let rCeil = {$#h(-1.125pt) ⌉ #h(-3.5pt) ⌉$} #let llfloor = {$⌊ #h(-3.5pt) ⌊ #h(-1.125pt)$} #let lFloor = {$⌊ #h(-3.5pt) ⌊ #h(-1.125pt)$} #let rrfloor = {$#h(-1.125pt) ⌋ #h(-3.5pt) ⌋$} #let rFloor = {$#h(-1.125pt) ⌋ #h(-3.5pt) ⌋$} #let llbracket = {$⟦$} #let lBrack = {$⟦$} #let rrbracket = {$⟧$} #let rBrack = {$⟧$} // Selected stmaryrd Arrows (that are available in the NewComputerModern Math font) #let Longmapsfrom = {$arrow.l.double.long.bar$} #let nnearrow = {$arrow.tr$} #let nearrow = {$arrow.tr$} #let longmapsfrom = {$arrow.l.long.bar$} #let lightning = {$↯$} #let downzigarrow = {$↯$} #let Longmapsto = {$arrow.r.double.long.bar$} #let nnwarrow = {$arrow.tl$} #let nwarrow = {$arrow.tl$} #let mapsfrom = {$arrow.l.bar$} #let llparenthesis = {$⦇$} #let rrparenthesis = {$⦈$} #let Mapsfrom = {$arrow.l.double.bar$} #let ssearrow = {$arrow.br$} #let searrow = {$arrow.br$} #let leftarrowtriangle = {$⇽$} #let Mapsto = {$arrow.r.double.bar$} #let swarrow = {$arrow.bl$} #let swarrow = {$arrow.bl$} #let rightarrowtriangle = {$⇾$} #let leftrightarrowtriangle = {$⇿$} // Selected stmaryrd Binary Operators (that are available in the NewComputerModern Math font) #let boxast = {$ast.sq$} #let boxcircle = {$⧇$} #let varogreaterthan = {$gt.circle$} #let ogreaterthan = {$gt.circle$} #let ogtr = {$gt.circle$} #let varcurlyvee = {$or.curly$} #let varobslash = {$backslash.circle$} #let obslash = {$backslash.circle$} #let varolessthan = {$lt.circle$} #let olessthan = {$lt.circle$} #let oless = {$lt.circle$} #let varotimes = {$times.circle$} #let boxbar = {$◫$} #let obar = {$⦶$} #let varobar = {$⌽$} #let varcurlyvee = {$and.curly$} #let varocircle = {$circle.nested$} #let ocircle = {$circle.nested$} #let varominus = {$minus.circle$} #let boxbox = {$⧈$} #let emptybox = {$square.stroked$} #let talloblong = {$⫾$} #let varoast = {$ast.circle$} #let oast = {$ast.circle$} #let varodot = {$dot.circle$} #let varoplus = {$dot.circle$} #let Yup = {$⅄$} #let boxbslash = {$⧅$} #let boxslash = {$⧄$} #let boxdiag = {$⧄$} #let interleave = {$⫴$} #let varbigcirc = {$circle.big$} #let varoslash = {$⊘$} // Selected stmaryrd Large Binary Operators (that are available in the NewComputerModern Math font) #let biginterleave = {$⫼$} #let bigsqcap = {$sect.sq.big$}
https://github.com/yonatanmgr/university-notes
https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661101-%5BCalculus%201A%5D/src/lectures/03661101_lecture_15.typ
typst
#import "/template.typ": * #import "/utils/graph.typ": * #show: project.with( title: "חדו״א 1א׳ - שיעור 15", authors: ("<NAME>",), date: "20 בפברואר, 2024", ) #set enum(numbering: "(1.א)") === (משפט) משפט הסנדוויץ׳ נתונות שלוש פונקציות $f,g,h: I bs {x_0} -> RR$. נניח כי מתקיים $f(x)<=g(x)<=h(x), forall x in I bs {x_0}$, וגם $limto(x_0) f(x) = limto(x_0) h(x) = L$. אזי, $limto(x_0) g(x) = L$. ==== הוכחה (לפי הגדרת קושי) ניקח $epsilon >0$ שרירותי. אז $exists delta_1 > 0: 0< abs(x-x_0)<delta_1 => abs(f(x)-L)<epsilon => L-epsilon<f(x)$, \ וגם $exists delta_2 >0:0<abs(x-x_0) < delta_2 => abs(h(x) -L) < epsilon => h(x) < L+epsilon$. נבחר $delta = min{delta_1, delta_2}$. \ אז $0<abs(x-x_0)<delta$ גורר $L-epsilon < f(x) <= g(x) <= h(x) < L+epsilon$. כלומר $abs(g(x)-L) < epsilon$. #QED ==== דוגמה צ״ל: $liminff((2^x+3^x)^(1/x))= 3$. נראה כי $f(x) = 3 = (3^x)^(1/x) <= (2^x+3^x)^(1/x) <= (3^x+3^x)^(1/x) = (2 dot 3^x)^(1/x) = 2^(1/x)dot 3 = h(x)$. לפי כלל הסנדוויץ׳, אם נוכיח כי $h(x)->3$, סיימנו. אם כך, נוכיח כי $liminff(2^(1/x))=1$: $ forall epsilon > 0 exists N >0 : forall x > N => abs(2^(1/x)-1) < epsilon ==> forall epsilon > 0 exists N in NN : abs(2^(1/N) - 1) <epsilon ==> 2^(1/N) < 1 + epsilon $ ואז $forall x > N$ יתקיים $1-epsilon < 1 < 2^(1/x) < 2^(1/N) < 1+epsilon$. #QED === (למה) $limto(0) (sin x)/x = 1$. ==== הוכחה מספיק להוכיח $limto(0^+) (sin x)/x = 1$ כי אז $limto(0^-) (sin x)/x eq^(x=-t) limits(lim)_(t->0^+) (sin (-t))/(-t) = limits(lim)_(t->0^+) (sin t)/t =1$. כבר הוכחנו כי $forall 0 <= x < pi/2$, $sin x <= x$. נוכיח כעת גם $x<=tan x, forall 0 <= x < pi/2$. // #grid(columns: 2)[ #align(center)[ #image("/attachments/Screenshot 2024-02-20 at 12.41.47.png", width: 25%) ] // ] ואז שטח המשולש $triangle.t O A C$ $<=$ שטח הגזרה $O A B$. $cancel(1/2) r x <= cancel(1/2) r abs(C A) = tan x, 0<x<pi/2$. כלומר, קיבלנו$x <= tan x, forall 0 <= x < pi/2$. ואז $sin x <= x <= tan x, 0<=x<pi/2$ $arrl$ $1<= x/(sin x) <= 1/(cos x), 0< x< pi/2$. נקבל לבסוף $cos x <= (sin x)/x <= 1, 0<x<pi/2$. נראה כי $cos x -->^(x->0^+) 1$, ולכן מכלל הסנדוויץ׳ $(sin x)/x->1$. #QED #pagebreak() = רציפות של פונקציה == רציפות בנקודה ובקטע - תהי $f: I->RR$ כאשר $I=(a,b)$ קטע פתוח. נאמר כי $f$ *רציפה בנקודה $x_0 in I$* אם מתקיים $limto(x_0) f(x)= f(x_0)$. - נאמר כי הפונקציה *רציפה בכל הקטע הפתוח $I$* אם $f$ רציפה בכל נקודה $x_0 in I$. === (דוגמה) האם פונקצית דיריכלה רציפה? עבור פונקצית דיריכלה, אשר הוגדרה $D(x) = cases(1 "if" x in QQ, 0 "if" x in.not QQ)$ הוכחנו כי $exists.not limto(x_0) D(x)$ בשום נקודה $x_0 in RR$. לכן, $D(x)$ לא רציפה בשום נקודה $x_0 in RR$. מצד שני, למדנו גם את הפונקציה $f(x) = x D(x)$ שגם לה אין גבול בכל $0!=x in RR$. אז $limto(0) f(x) = 0 =f(0)$ לכן $f(x)$ רציפה בנקודה ממשית יחידה $x_0 = 0$. == רציפות מימין ומשמאל ונקודות אי-רציפות === (הגדרה) רציפות מימין ומשמאל - תהי $f: [a,b) -> RR$. נאמר ש-$f$ *רציפה מימין בנקודה $a$* אם מתקיים $limto(a^+) f(x) = f(a)$. - תהי $f: (c,a] -> RR$. נאמר ש-$f$ *רציפה משמאל בנקודה $a$* אם מתקיים $limto(a^-) f(x) = f(a)$. === (הגדרה) צמצום פונקציה נתונה פונקציה $f: A->RR$ ו-$B subset A$. נסמן $bv(f, B)$ את הפונקציה $f$ המוגדרת רק על $B$. === (טענה) תהי $f: (c,b) -> RR$ ותהי $a in (c,b)$. אזי $f$ רציפה ב-$a$ אם״ם $bv(f, (c,a])$ רציפה משמאל ב-$a$ ו-$bv(f, [a,b))$ רציפה מימין ב-$a$. === (הגדרה) נקודת אי-רציפות - נתונה פונקציה $f$ המוגדרת בקטע הפתוח $I$ סביב נקודה $x_0$, פרט אולי בנקודה $x_0$ עצמה. אזי, הנקודה $x_0$ נקראת *נקודת אי-רציפות סליקה* אם $exists limto(x_0) f(x) != f(x_0)$. - *נקודת אי-רציפות מסוג ראשון*: אם קיימים ושונים הגבולות החד-צדדיים $limto(x_0^+) f(x)$ ו-$limto(x_0^+) f(x)$. - *נקודת אי-רציפות מסוג שני*: אם לפחות אחד מהגבולות החד-צדדיים $limto(x_0^+) f(x)$ ו-$limto(x_0^+) f(x)$ לא קיים. ==== דוגמה: $y= f(x) = sin 1/x, x_0 = 0$ #graph(w: 15, h: 2, start:0.2, end:-0.2, functions: (x=>calc.sin(1/x),), h-asymptotes: (1, -1)) $ sin (1/x) = 0 ==> 1/x = pi k ==> x_k^((1)) = 1/(pi k), k=pm 1, pm 2, p, 3, dots ==> sin 1/x = 1 ==> \ 1/x = pi/2 + 2pi k, k=0, pm 1, pm 2, dots ==> x_k^((2)) = 1/(pi/2 + 2pi k) $ האם קיים $limto(0) sin 1/x$? לא, כי $x_k^((1)) -->^(k->oo) 0 $ ו-$x_k^((2)) -->^(k->oo) 0$. $f(x_k^((1))) = 0 --> 0$ אך $f(x_k^((2))) = 1 --> 1$ ו-$0!=1$. ואז, לפי הגדרת היינה, $exists.not limto(0) sin 1/x$ ואז $x_0 = 0$ נקודת אי-רציפות מהסוג השני. ==== דוגמה נוספת: האם קיים $limto(0) f(x)$ עבור $f(x)=x sin 1/x$? כן, כי $x->0$ ו-$sin 1/x$ חסומה (כאשר $x->0$) ואז $x sin 1/x -> 0$. #align(center)[ #graph(w: 8, h: 8, start:0.1125, end:-0.1125, functions: (x=>x*calc.sin(1/x),), additionals: ( x=>x, x=>-x)) ]
https://github.com/herbhuang/utdallas-thesis-template-typst
https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/content/background.typ
typst
MIT License
#import "/utils/todo.typ": TODO = Background #TODO[ Describe each proven technology / concept shortly that is important to understand your thesis. Point out why it is interesting for your thesis. Make sure to incorporate references to important literature here. ] == e.g. User Feedback #TODO[ This section would summarize the concept User Feedback using definitions, historical overviews and pointing out the most important aspects of User Feedback. ] == e.g. Representational State Transfer #TODO[ This section would summarize the architectural style Representational State Transfer (REST) using definitions, historical overviews and pointing out the most important aspects of the architecture. ] == e.g. Scrum #TODO[ This section would summarize the agile method Scrum using definitions, historical overviews and pointing out the most important aspects of Scrum. ]
https://github.com/Enter-tainer/zint-wasi
https://raw.githubusercontent.com/Enter-tainer/zint-wasi/master/typst-package/README.md
markdown
MIT License
# tiaoma [tiaoma(条码)](https://github.com/enter-tainer/zint-wasi) is a barcode generator for typst. It compiles [zint](https://github.com/zint/zint) to wasm and use it to generate barcode. It support nearly all common barcode types. For a complete list of supported barcode types, see [zint's documentation](https://zint.org.uk/): - Australia Post - Standard Customer - Reply Paid - Routing - Redirection - Aztec Code - Aztec Runes - Channel Code - Codabar - Codablock F - Code 11 - Code 128 with automatic subset switching - Code 16k - Code 2 of 5 variants: - Matrix 2 of 5 - Industrial 2 of 5 - IATA 2 of 5 - Datalogic 2 of 5 - Interleaved 2 of 5 - ITF-14 - Deutsche Post Leitcode - Deutsche Post Identcode - Code 32 (Italian pharmacode) - Code 3 of 9 (Code 39) - Code 3 of 9 Extended (Code 39 Extended) - Code 49 - Code 93 - Code One - Data Matrix ECC200 - DotCode - Dutch Post KIX Code - EAN variants: - EAN-13 - EAN-8 - Grid Matrix - GS1 DataBar variants: - GS1 DataBar - GS1 DataBar Stacked - GS1 DataBar Stacked Omnidirectional - GS1 DataBar Expanded - GS1 DataBar Expanded Stacked - GS1 DataBar Limited - Han Xin - Japan Post - Korea Post - LOGMARS - MaxiCode - MSI (Modified Plessey) - PDF417 variants: - PDF417 Truncated - PDF417 - Micro PDF417 - Pharmacode - Pharmacode Two-Track - Pharmazentralnummer - POSTNET / PLANET - QR Code - rMQR - Royal Mail 4-State (RM4SCC) - Royal Mail 4-State Mailmark - Telepen - UPC variants: - UPC-A - UPC-E - UPNQR - USPS OneCode (Intelligent Mail) ## Example ```typ #import "@preview/tiaoma:0.2.1" #set page(width: auto, height: auto) = tiáo mǎ #tiaoma.ean("1234567890128") ``` ![example](./example.svg) ## Manual Please refer to [manual](./manual.pdf) for more details. ## Alternatives There are other barcode/qrcode packages for typst such as: - https://github.com/jneug/typst-codetastic - https://github.com/Midbin/cades Packages differ in provided customization options for generated barcodes. This package is limited by zint functionality, which focuses more on coverage than customization (e.g. inserting graphics into QR codes). Patching upstream zint code is (currently) outside of the scope of this package - if it doesn't provide functionality you need, check the rest of the typst ecosystem to see if it's available elsewhere or request it [upstream](https://github.com/zint/zint) and [notify us](https://github.com/Enter-tainer/zint-wasi/issues) when it's been merged. ### Pros 1. Support for far greater number of barcode types (all provided by zint library) 2. Should be faster as is uses a WASM plugin which bundles zint code which is written in C; others are written in pure typst or javascript. ### Cons 1. While most if not all of zint functionality is covered, it's hard to guarantee there's no overlooked functionality. 2. This package uses typst plugin system and has a WASM backend written in Rust which makes is less welcoming for new contributors.
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/AI/Reinforce%20Learning/策略学习.typ
typst
--- order: 3 --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "AI 笔记之强化学习", lang: "zh", ) #let ba = $bold(a)$ #let bw = $bold(w)$ = 策略学习 == 策略梯度 - 前面讲的是基于价值($V$或$Q$)的策略,而策略梯度是完全不同的一种方法 - 回顾 - #fig("/public/assets/AI/AI_RL/img-2024-07-05-09-36-52.png") - #fig("/public/assets/AI/AI_RL/img-2024-07-05-09-38-37.png") - #fig("/public/assets/AI/AI_RL/img-2024-07-05-09-41-23.png") - 优点:具有更好的收敛性质;在高维度或连续的动作空间中更有效;能够学习出随机策略 - 缺点:通常会收敛到局部最优而非全局最优;评估一个策略通常不够高效并具有较大的方差 - 回到现在,为什么要引入基于策略的强化学习方法? - 基于价值的强化学习方法: + 学习价值函数 + 利用价值函数导出策略 + 更高的样本训练效率 + 通常仅适用于具有离散动作的环境 - 基于策略的强化学习方法: + 不需要价值函数 + 直接学习策略 + 在高维或连续动作空间场景中更加高效 + 适用任何动作类型的场景 + 容易收敛到次优解 - 基于演员-评论家的方法将二者优势结合 - 基于策略的强化学习方法方法直接搜索最优策略$pi^*$ - 通常做法是参数化策略 $pi_theta$,并利用无梯度或基于梯度的优化方法对参数进行更新 - 无梯度优化(启发式优化方法,如有限差分方法、交叉熵方法、遗传算法等)可以有效覆盖低维参数空间,但基于梯度的训练仍然是首选,因为其具有更高的采样效率(这里没有详细展开) - 对比之前的表格型策略 + 采取某个动作的概率的计算方式不同:状态 $s$ 上采取动作 $a$ 的概率,一个是直接查表,一个是计算 $pi_theta (a|s)$ + 策略的更新方式不同:一个是直接修改表格对应条目,一个是更新参数 $theta$ + 最优策略的定义不同 - 基本思想: - 利用目标函数定义策略优劣性:$J(theta) = J(pi_theta)$(目标函数如何设计?) - 对目标函数进行优化(优化方向如何计算),以寻找最优策略 - 优化方向 - 目标函数不可微分时:使用无梯度算法进行最优参数搜索 - 目标函数可微分时:利用基于梯度的优化方法寻找最优策略 $theta_(t+1) <- theta_t + alpha nabla_theta J(theta_t)$ - 目标函数 #fig("/public/assets/AI/AI_RL/img-2024-07-05-09-59-33.png") - 状态分布$d(s)$ - 策略无关的状态分布 - 在这类情况下,目标函数关于参数的梯度通常更好算 - 一个简单的做法是取 $d(s)$ 为均匀分布,即每个状态都有相同的权重 $1\/|S|$ - 另一种做法是把权重集中分配给一部分状态集合。例如,在一些任务中,一个回合只从状态 $s_0$ 开始,那么可以设置为:$d(s_0)=1,d(s!=s_0)=0$ - 策略相关的状态分布 - 在这种情况下,通常选用稳态状态分布 - $d(s)$ 是稳态状态分布:若对一个状态转移 $s->a->s'$,满足:#mitex(`d(s^{\prime})=\sum_{s\in\mathcal{S}}\sum_{a\in\mathcal{A}}p(s^{\prime}|s,a)\cdot\pi_{\theta}(a|s)\cdot d(s)`) - 如果采用最大化平均轨迹回报目标函数$ max_theta J(theta)=max_theta EE_(tau wave p_theta (tau)) [sum_t r(s_t,a_t)] $ - $tau$ 为策略 $pi_theta$ 采样而来的轨迹 ${s_1,a_1,r_1,dots,s_T}$ - 记 $G(tau)=sum_t r(s_t,a_t)$,平均轨迹回报目标的策略梯度为: $ nabla_theta J(theta)=nabla_theta int p_theta (tau)G(tau) dif tau &= EE_(tau wave p_theta (tau)) [nabla_theta log p_theta (tau)G(tau)]\ &=EE_(tau wave p_theta (tau)) [sum_(t=1)^T nabla_theta log pi_theta (a_t|s_t)G(tau)] $ - 其中出现 $log$ 是因为乘一个除一个 $p_theta (tau)$,于是 $(nabla_theta p_theta (tau)) / (p_theta (tau))$ 变成 $nabla_theta log p_theta (tau)$ - #fig("/public/assets/AI/AI_RL/img-2024-07-05-10-18-35.png") - 另外两种目标函数和策略梯度 #fig("/public/assets/AI/AI_RL/img-2024-07-05-10-19-19.png") - 使用不同的策略梯度,以及不同的近似方法,我们可以得到各种各样的基于策略梯度的强化学习算法,如 REINFORCE、DDPG、PPO等 === REINFORCE 算法 - 对于随机策略$pi_theta (a,s) = P(a|s, theta)$ - 直觉上我们应该:降低带来低价值/奖励的动作出现的概率;提高带来高价值/奖励的动作出现的概率 - 上一章中我们推导出了策略梯度(最大化平均轨迹回报目标函数),在实践中,我们可以用蒙特卡洛方法进行估计 #mitex(`\nabla_{\theta}J(\theta)=\ \frac{1}{N}\sum_{n=1}^{N}\sum_{t=1}^{T^{n}}R(\tau^{n})\nabla_{\theta}l o g\,\pi_{\theta}(a_{t}^{n}|s_{t}^{n})`)据此,我们可以得到 REINFORCE 算法 #algo(caption: "REINFORCE 算法")[ ```typ 利用策略$pi_theta (a|s)$采样$N$条轨迹${tau_i}$ 计算梯度 $nabla_theta J(theta)=1/N sum_(n=1)^N (sum_(t=1)^(T^n) R(tau^n) nabla_theta log pi_theta (a_t^n|s_t^n))$ 更新参数 $theta <- theta + alpha nabla_theta J(theta)$ ``` ] #fig("/public/assets/AI/AI_RL/img-2024-07-05-15-16-33.png", width: 80%) - 思考强化学习与分类问题对比 + 都是输入状态,输出要采取的行为 + 分类问题(监督学习):假设有带标签的训练数据,随后利用极大似然法进行优化 + 强化学习:没有标签,只能通过试错的方式与环境交互获取奖励,以替代监督信息进行训练 - 一个问题——*训练可能存在偏差* #fig("/public/assets/AI/AI_RL/img-2024-07-05-10-41-17.png") - 解决办法,添加 *baseline*:将奖励函数减去一个基线 $b$,使得 $R(tau)-b$ 有正有负 - 如果 $R(tau)>b$ 就让采取对应动作的概率提升;如果 $R(tau)<b$ 就让采取对应动作的概率降低 - 上述蒙特卡洛采样方法变为 #mitex(`\nabla_{\theta}J(\theta)=\ \frac{1}{N}\sum_{n=1}^{N}\sum_{t=1}^{T^{n}}(R(\tau^{n})-b)\nabla_{\theta}l o g\,\pi_{\theta}(a_{t}^{n}|s_{t}^{n})`) - 数学证明减去一个基线并不会影响原梯度的期望值 - 如何实现策略梯度? - 难以计算,在实际应用时,都会采用 Pytorch、Tensorflow 中的自动求导工具辅助求解 - 将策略梯度的目标函数视为极大似然法的目标函数一个利用累积奖励进行加权的版本(?) - 策略梯度算法在样本利用率以及稳定性上存在缺陷 - 由于策略梯度算法为同策略算法,因此样本利用率较低 - 较大的策略更新或不适宜的更新步长会导致训练的不稳定(在监督学习中,训练数据具有独立同分布的性质;而在强化学习中,不适宜的更新步长 $->$ 坏策略 $->$ 低质量的数据,于是可能难以从糟糕的策略中恢复,进而导致性能崩溃) - 离策略梯度:根据重要性采样利用异策略样本 - 听不懂 - 自然策略梯度 - 听不懂 === Actor-Critic 算法 - 为什么要引入 Actor-Critic?主要是因为 REINFORCE 效率不高 - REINFORCE 算法中的的轨迹回报期望采用直接相加 $R(tau^n)=sum_(t'=t)^T r(s_t'^i,a_t'^i)$ - 这样做方差较大,不易收敛。我们可以用动作价值估计 $hat(Q)^pi$ 来近似轨迹回报期望$EE_(pi_theta) sum_(t'=t)^T r(s_t'^i,a_t'^i)$,这就是评论家(critic) - 对应地,策略 $pi_theta$ 称为执行者(actor) #algo(caption: "Actor-Critic 算法")[ ```typ 使用当前策略 $pi_theta$ 在环境中进行采样 策略提升:$theta <- theta + alpha nabla_theta J(theta) approx 1/N sum_(i=1)^N (sum_(t=1)^T nabla_theta log pi_theta (a_t^i|s_t^i) hat(Q)^pi (s_t^i,a_t^i))$ 拟合当前策略的动作值函数:$hat(Q)^pi (s_t'^i,a_t'^i) approx sum_(t'=t)^T r(s_t'^i,a_t'^i)$ ``` ] #fig("/public/assets/AI/AI_RL/img-2024-07-05-15-17-48.png") - Advantage Actor-Critc(A2C)算法 - 思想:通过减去一个基线值来标准化评论家的打分 - 降低较差动作概率,提高较优动作概率 - 进一步降低方差 - 优势函数:$A^pi (s,a)=Q^pi (s,a)-V^pi (s_t)$,改变critic,于是原本 AC 算法的策略梯度 #mitex(`\nabla_{\theta}J(\theta)\approx\frac{1}{N}\sum_{i=1}^{N}\left(\sum_{t=1}^{T}V_{\theta}\,l o g\,\pi_{\theta}(a_{t}^{i}|s_{t}^{i})\bar{Q}^{\pi}(s_{i}^{i},\alpha_{t}^{i})\right)`) 变为 #mitex(`\nabla_{\theta}J(\theta)\approx\frac{1}{N}\sum_{i=1}^{N}\left(\sum_{t=1}^{T}\nabla_{\theta}\,l o g\,\pi_{\theta}(a_{t}^{i}|s_{t}^{i})\bar{A}^{\pi}(s_{i}^{i},\alpha_{t}^{i})\right)`) - $Q$ 和 $V$需要用两个神经网络拟合吗? - 不需要 $hat(Q)^pi (s_t^i,a_t^i)= R(s_t^i,a_t^i) + gamma hat(V)^pi (s_(t+1)^i)$,只需用一个神经网络拟合$hat(V)^pi$ - 状态值估计$hat(V)^pi$能否与策略 $pi_theta$ 共用网络? #fig("/public/assets/AI/AI_RL/img-2024-07-05-11-15-17.png") - 如果采用相同的网络去训练,这边的 loss function 没有讲(actor 的 loss,critic 的 loss,actor 的正则化项 entropy),可以参考代码或者看 #link("https://www.cnblogs.com/wangxiaocvpr/p/8110120.html")[这篇文章] - 批量更新(没听懂) - 问题:利用单个样本进行更新:更新方差较大,训练稳定性差 - 解决方案:获得一个批次的数据后再进行更新,分为同步和异步两种方法 #fig("/public/assets/AI/AI_RL/img-2024-07-05-11-22-12.png") - 批量更新再改进 #fig("/public/assets/AI/AI_RL/img-2024-07-05-11-22-32.png") - Asynchronous Advantage Actor-Critc(A3C)算法 - 与A2C一样使用优势函数 - 异步的Actor-Critic方法能够充分利用多核CPU资源采样环境的经验数据,利用GPU资源异步地更新网络,这有效提升了强化学习算法的训练效率 == TRPO & PPO - TRPO(Trust Region Policy Optimization)是一种基于策略梯度的强化学习算法,其目标是最大化策略的期望回报 - 置信域(Trust Region)的概念就是在 $N(theta_"now")$ 的邻域内,$L(theta|theta_"now")$ 足够逼近优化目标 $J(theta)$ - 前面介绍的策略梯度方法(包括 REINFORCE 和 Actor-Critic)用蒙特卡洛近似梯度 $nabla_theta J(theta)$,得到随机梯度,然后做随机梯度上升更新 $theta$,使得目标函数 $J(theta)$ 增大;而这里是用不同的方法 - 目标函数等价形式写成#mitex(`J(\theta)~=~\mathbb{E}_{S}\left[\mathbb{E}_{A\cdots\pi(\cdot|S;\theta_{\mathrm{now}})}\left[\frac{\pi(A\mid S;\,\theta)}{\pi(A\mid S;\,\theta_{\mathrm{now}})}~\cdot\,{\cal Q}_{\pi}(S,A)\right]\right]`) - 其中 $Q_pi (S, A)$ 依旧无法求解,因此使用迭代中的上一步的 $pi=pi(a_t | s_t\; theta_"old")$ - TRPO 第二部置信域的选择 - 认为设定的 $Delta$ - 用 KL 散度衡量两个概率质量函数的距离 - TRPO 算法真正实现起来并不容易,主要难点在于第二步——最大化。 #hline() - PPO 基于 TRPO 的思想,但是其算法实现更加简单 - PPO-惩罚 - 直接将置信域约束 KL 散度作为损失函数的一部分,这样就不需要求解最大化问题 - PPO-截断 - PPO 的另一种形式 PPO-截断(PPO-Clip)更加直接,它在目标函数中进行限制,以保证新的参数和旧的参数的差距不会太大 == 连续控制 - 考虑这样一个问题:我们需要控制一只机械手臂,完成某些任务,获取奖励。机械手臂有两个关节,分别可以在 $[0, 360] 与 [0, 180]$ 的范围内转动。这个问题的自由度是 $d = 2$,动作是二维向量,动作空间是连续集合 $cal(A) = [0, 360] times [0, 180]$。 - 此前我们学过的强化学习方法全部都是针对离散动作空间,不能直接解决上述续控制问题。如果用网格化方法,将连续动作空间离散化,会导致动作空间过大,训练效率低下。特别是自由度较高的问题,这种方法几乎不可行。 == DPG - 确定策略梯度(deterministic policy gradient)是一种 actor-critic 方法 - 确定策略网络 - 在之前章节里,策略网络 $pi(a|s\; theta)$ 是一个概率质量函数,它输出的是概率值。本节的确定策略网络 $mu(s\; theta)$ 的输出是 $d$ 维的向量 $ba$,作为动作。两种策略网络一个是随机的,一个是确定性的 - 个人认为不是很本质(?),感觉就是把在外的 argmax 放到神经网络里面去了 - 确定价值网络 - 价值网络 $Q(s, ba\; bw)$ 也是一个神经网络,它的输入是状态 $s$ 和动作 $ba$,输出 $hat(q) = q(s, ba; bw)$ 是个实数 - 总而言之,个人认为这里相当于 actor-critic 的变种,并且真正把两个网络分了开来,两个网络分别训练,而不是共享前几层 - 训练过程 - 做训练的时候,可以同时对价值网络和策略网络做训练。每次从经验回放数组中抽取一个四元组,记作 $(s_j, a_j, r_j, s_(j+1))$。把价值网络和策略网络当前参数分别记作 $w_"now"$ 和 $theta_"now"$ -
https://github.com/YouXam/bupt-network-resources-guide
https://raw.githubusercontent.com/YouXam/bupt-network-resources-guide/main/README.md
markdown
MIT License
# bupt-network-resources-guide 北邮网络资源手册,包含了北邮学生可能需要的各种网络资源的介绍和使用方法。 目录预览: ![目录预览](https://github.com/YouXam/bupt-network-resources-guide/releases/latest/download/preview.jpg) ## 下载 你可以从 [这里](https://github.com/YouXam/bupt-network-resources-guide/releases/latest/download/bupt-network-resources-guide.pdf) 下载最新版本的 PDF 文件。 ## 编译 ```bash typst compile --font-path fonts main.typ bupt-network-resources-guide.pdf ```
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/树/二叉树最大深度.typ
typst
#import "../../../../lib.typ":* === #Title( title: [二叉树最大深度], reflink: "https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/", level: 1, )<二叉树最大深度> #note( title: [ 二叉树最大深度 ], description: [ 给定一个二叉树 root ,返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 ], examples: ([ 输入:root = [3,9,20,null,null,15,7] 输出:3 ],[ 输入:root = [1,null,2] 输出:2 ] ), tips: [ - 树中节点的数量在 $[0, 10^4]$ 区间内。 - $-100 <= "Node.val" <= 100$ ], solutions: ( ( name:[后序遍历(DFS): 递归], text:[ 树的后序遍历 / 深度优先搜索往往利用 递归 或 栈 实现。 显然,树的深度 等于 左子树的深度 与 右子树的深度中的 最大值 +1。 1. 终止条件: 当 `root​` 为空,说明已越过叶节点,因此返回 深度 0 。 2. 递推工作: 本质上是对树做后序遍历。 - 计算节点 `root​` 的 左子树的深度 ,即调用 `maxDepth(root.left)`。 - 计算节点 `root​` 的 右子树的深度 ,即调用 `maxDepth(root.right)`。 3. 返回值: 返回 此树的深度 ,即 `max(maxDepth(root.left), maxDepth(root.right)) + 1`。 ], code:[ ```cpp class Solution { public: int maxDepth(TreeNode* root) { if (root == nullptr) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } }; ``` ] ),( name:[层序遍历(BFS)], text:[ 树的层序遍历 / 广度优先搜索往往利用 队列 实现。 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。 + 特例处理: 当 `root​` 为空,直接返回 深度 0 。 + 初始化: 队列 `queue` (加入根节点 `root` ),计数器 `res` = 0。 + 循环遍历: 当 `queue` 为空时跳出。 - 初始化一个空列表 `tmp` ,用于临时存储下一层节点。 - 遍历队列: 遍历 `queue` 中的各节点 `node` ,并将其左子节点和右子节点加入 `tmp。` - 更新队列: 执行 `queue` = `tmp` ,将下一层节点赋值给 `queue。` - 统计层数: 执行 `res += 1` ,代表层数加 1。 + 返回值: 返回 `res` 即可。 ], code:[ ```cpp class Solution { public: int maxDepth(TreeNode* root) { if (root == nullptr) return 0; vector<TreeNode*> que; que.push_back(root); int res = 0; while (!que.empty()) { vector<TreeNode*> tmp; for(TreeNode* node : que) { if (node->left != nullptr) tmp.push_back(node->left); if (node->right != nullptr) tmp.push_back(node->right); } que = tmp; res++; } return res; } }; ``` ] ) ), gain:none, )
https://github.com/malramsay64/resume
https://raw.githubusercontent.com/malramsay64/resume/main/template.typ
typst
#import "utils.typ" #import "@preview/fontawesome:0.4.0" as fa /* Styles */ #let accentColor = luma(80) #let headerInfoStyle(str) = {text( size: 10pt, fill: accentColor, str )} #let headerQuoteStyle(str) = {text( size: 10pt, weight: "medium", // style: "italic", fill: accentColor, str )} #let sectionTitleStyle(str, color:black) = {text( size: 16pt, weight: "bold", fill: color, str )} #let entryA1Style(str) = {text( size: 10pt, weight: "bold", str )} #let entryA2Style(str) = {text( weight: "medium", // fill: accentColor, style: "oblique", str )} #let entryB1Style(str) = {text( // size: 10pt, fill: accentColor, weight: "medium", str )} #let entryB2Style(str) = {text( size: 9pt, weight: "medium", fill: luma(80), style: "oblique", str )} // set rules #let setrules(uservars, doc) = { set text( font: uservars.bodyfont, weight: "regular", size: uservars.fontsize, ) set align(left) set page( paper: "a4", margin: ( left: 1.8cm, right: 1.8cm, top: 1.5cm, bottom: 1.8cm, ), ) set list( spacing: uservars.linespacing ) set par( leading: uservars.linespacing, justify: true, ) doc } // show rules #let showrules(uservars, doc) = { show heading.where(level: 1): set text(font: uservars.headingfont, size: 32pt) show heading.where(level: 2): title => pad(bottom: 0.2em, grid( columns: 2, gutter: 1%, sectionTitleStyle()[#title], line( start: (0pt, 0.95em), length: 100%, stroke: (paint: accentColor, thickness: 0.05em), ), )) doc } // set page layout #let cvinit(doc) = { doc = setrules(doc) doc = showrules(doc) doc } // address // TODO #let addresstext(info, uservars) = { if uservars.showAddress { block(width: 100%)[ #info.personal.location.at("city", default: ""), #info.personal.location.at("region", default: ""), #info.personal.location.country #info.personal.location.at("postalCode", default: "") #v(-4pt) ] } else {none} } #let contacttext(info, uservars) = block(width: 100%)[ #let contact_display(icon, url, display: none) = { let l = if display == none { link(url) } else { link(url)[#display] } box([#icon #sym.zws #l]) } #let profiles = ( contact_display(fa.fa-envelope(solid: true), "mailto:" + info.personal.email), ) #if uservars.showNumber { profiles.push(contact_display(fa.fa-phone(), "tel:" + info.personal.phone)) } #if "url" in info.personal { profiles.push(contact_display(fa.fa-home(), info.personal.url, display: info.personal.url.trim("https://", at: start))) } #if info.personal.profiles.len() > 0 { for profile in info.personal.profiles { let icon = if lower(profile.network) == "linkedin" { fa.fa-linkedin() } else if lower(profile.network) == "github" { fa.fa-github() // TODO: Extend the number of networks with icons } else { // fa.fa-circle() } profiles.push(contact_display(icon, profile.url, display: profile.username)) } } #headerInfoStyle(profiles.join([ #sym.bar.v ])) #headerQuoteStyle(eval(info.personal.summary, mode: "markup")) ] #let styleLabel(str) = { text( size: 20pt, str ) } #let cvheading(info, uservars) = { align(center)[ = #info.personal.name #if "label" in info.personal { styleLabel(info.personal.label) } #addresstext(info, uservars) #contacttext(info, uservars) ] } #let entryHeading(posA1: none, url: none, posA2: none, posB1: none, dateStart: none, dateEnd: none) = { let date = if dateStart == none { utils.strpdate(dateEnd) } else if dateEnd == none { utils.strpdate(dateStart) } else { let start = utils.strpdate(dateStart) let end = utils.strpdate(dateEnd) [#start #sym.dash.en #end] } // parse ISO date strings into datetime objects [ // line 1: company and location #if url != none [ #entryA1Style(link(url, posA1)) #h(1fr) #entryA2Style(posA2)\ ] else [ #entryA1Style(posA1) #h(1fr) #entryA2Style(posA2)\ ] #entryB1Style(posB1) #h(1fr) #entryB2Style(date) \ ] } #let cvwork(info, isbreakable: true) = { let work = utils .filter_visible(info, "work") .map(utils.validate_work_instance) .sorted(key: i => i.positions.at(0).endDate) .rev() if work.len() > 0 [ == Work Experience #for w in work { // create a block layout for each work entry for (index, p) in w.positions.enumerate() { block(width: 100%, breakable: isbreakable)[ #if index == 0 { entryHeading(posA1: w.organization, url: w.url, posA2: w.location, posB1: p.position, dateStart: p.startDate, dateEnd: p.endDate) } else { entryHeading(posB1: p.position, dateStart: p.startDate, dateEnd: p.endDate) } // highlights or description #if p.summary != none [ #eval(p.summary, mode: "markup") ] #for hi in p.highlights [ - #eval(hi, mode: "markup") ] ] } } ] } #let cveducation(info, isbreakable: true) = { let education = utils .filter_visible(info, "education") .sorted(key: i => i.endDate) .rev() if education.len() > 0 [ == Education #for edu in education { let edu-items = "" if edu.at("honors", default: none) != none {edu-items = edu-items + "- *Honors*: " + edu.honors.join(", ") + "\n"} if edu.at("courses", default: none) != none {edu-items = edu-items + "- *Courses*: " + edu.courses.join(", ") + "\n"} if edu.at("highlights", default: none) != none { for hi in edu.highlights { edu-items = edu-items + "- " + hi + "\n" } edu-items = edu-items.trim("\n") } // create a block layout for each education entry block(width: 100%, breakable: isbreakable)[ #entryHeading( posA1: edu.institution, url: edu.url, posA2: edu.location, posB1: [#edu.studyType in #edu.area], dateStart: edu.startDate, dateEnd: edu.endDate ) #eval(edu.summary, mode: "markup") #eval(edu-items, mode: "markup") ] } ] } #let cvaffiliations(info, isbreakable: true) = { if "affiliations" in info and info.affiliations != none [ == Leadership & Activities #for org in info.affiliations { // create a block layout for each affiliation entry block(width: 100%, breakable: isbreakable)[ #entryHeading( posA1: org.organization, url: org.url, posA2: org.location, posB1: org.position, dateStart: org.startDate, dateEnd: org.endDate ) // highlights or description #if org.highlights != none { for hi in org.highlights [ - #eval(hi, mode: "markup") ] } ] } ] } #let cvprojects(info, isbreakable: true) = { let projects = utils .filter_visible(info, "projects") .sorted(key: i => i.endDate) .rev() if projects.len() > 0 [ == Projects #for project in projects { // create a block layout for each project entry block(width: 100%, breakable: isbreakable)[ #entryHeading( posA1: project.name, url: project.at("url", default: none), posB1: project.affiliation, dateStart: project.startDate, dateEnd: project.endDate ) // summary or description #eval(project.summary, mode: "markup") #for hi in project.highlights [ - #eval(hi, mode: "markup") ] // Project tools and technologies #if "skills" in project and project.skills.len() > 0 [ // Ensure the skills look attached to the project #v(-0.5em) *Skills*: #project.skills.join(", ") ] ] } ] } #let cvawards(info, isbreakable: true) = { let awards = utils .filter_visible(info, "awards") .sorted(key: i => i.date) .rev() if awards.len() > 0 [ == Honors & Awards #for award in awards { // create a block layout for each award entry block(width: 100%, breakable: isbreakable)[ #entryHeading( posA1: award.title, url: award.at("url", default: none), posA2: award.location, posB1: [Issued by #text(style: "italic")[#award.issuer]], dateStart: award.date, ) // summary or description #eval(award.summary, mode: "markup") #if award.at("highlights", default: none) != none { for hi in award.highlights [ - #eval(hi, mode: "markup") ] } ] } ] } #let cvcertificates(info, isbreakable: true) = { if "certificates" in info and info.certificates != none [ == Licenses & Certifications #for cert in info.certificates { // parse ISO date strings into datetime objects let date = utils.strpdate(cert.date) // create a block layout for each certificate entry block(width: 100%, breakable: isbreakable)[ // line 1: certificate name #if cert.at("url", default: none) != none [ *#link(cert.url)[#cert.name]* \ ] else [ *#cert.name* \ ] // line 2: issuer and date Issued by #text(style: "italic")[#cert.issuer] #h(1fr) #date \ ] } ] } #let cvpresentations(info, isbreakable: true) = { let presentations = utils .filter_visible(info, "presentations") .sorted(key: i => i.date) .rev() if presentations.len() > 0 [ == Presentations #for pres in presentations { // create a block layout for each publication entry block(width: 100%, breakable: isbreakable)[ #entryHeading( posA1: pres.conference, url: pres.at("url", default: none), posA2: pres.location, posB1: pres.title, dateEnd: pres.date ) #eval(pres.summary, mode: "markup") ] } ] } #let cvpublications(info, isbreakable: true) = { let publications = utils .filter_visible(info, "publications") .sorted(key: i => i.releaseDate) .rev() if publications.len() > 0 [ == Publications #for pub in info.publications { // parse ISO date strings into datetime objects let date = utils.strpdate(pub.releaseDate) // create a block layout for each publication entry block(width: 100%, breakable: isbreakable)[ // line 1: publication title #if pub.at("url", default: none) != none [ *#link(pub.url)[#pub.name]* \ ] else [ *#pub.name* \ ] // line 2: publisher and date Published in #text(style: "italic")[#pub.publisher] #h(1fr) #date \ ] } ] } #let cvskills(info, isbreakable: true) = { let title = () if "languages" in info { title.push("Languages") } if "skills" in info { title.push("Skills") } if "interests" in info { title.push("Interests") } if title.len() > 0 {block(breakable: isbreakable)[ == #title.join(", ") #if ("languages" in info and info.languages != none) [ #let langs = () #for lang in info.languages { langs.push([#lang.language (#lang.fluency)]) } - *Languages*: #langs.join(", ") ] #if ("skills" in info and info.skills != none) { grid( columns: 2, gutter: 10pt, ..info.skills.map(s => { (align(right)[*#s.category*], align(left)[#s.skills.join(", ")]) }).flatten() ) } #if ("interests" in info and info.interests != none) [ - *Interests*: #info.interests.join(", ") ] ]} } #let cvreferences(info, isbreakable: true) = { if "references" in info and info.references != none {block[ == References #for ref in info.references { block(width: 100%, breakable: isbreakable)[ #if ref.at("url", default: none) != none [ - *#link(ref.url)[#ref.name]*: "#ref.reference" ] else [ - *#ref.name*: "#ref.reference" ] ] } ]} else {} } #let endnote() = { }
https://github.com/TJ-CSCCG/tongji-slides-typst
https://raw.githubusercontent.com/TJ-CSCCG/tongji-slides-typst/main/README.md
markdown
MIT License
# tongji-slides-typst :page_facing_up: 同济大学幻灯片模板 | Typst 中文 | [English](README-EN.md) > [!CAUTION] > 由于 Typst 项目仍处于密集发展阶段,且对某些功能的支持不完善,并且此模板为过渡模板之后会使用新的package重写,因此本模板可能存在一些问题。如果您在使用过程中遇到了问题,欢迎提交 issue 或 PR,我们会尽力解决。 > ## 样例展示 以下依次展示 “title-slide”、“使用实例”、“matrix-slide”、“自定义materix-slide”、“空白slide” 与 “focus-slide”。 <p align="center"> <img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220130.png" width="30%"> <img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220107.png" width="30%"> <img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220153.png" width="30%"> <img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220139.png" width="30%"> <img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220119.png" width="30%"> <img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220080.png" width="30%"> </p> ## 使用方法 ### 本地编译 #### 1. 安装 Typst 参照 [Typst](https://github.com/typst/typst?tab=readme-ov-file#installation) 官方文档安装 Typst。 #### 2. clone 本项目 ```bash git clone https://github.com/TJ-CSCCG/tongji-slides-typst.git cd tongji-slides-typst ``` 按照需求修改相关文件,然后执行以下命令以编译。 ```bash typst compile main.typ typst2pngpdf main.typ ##编译成图片pdf的脚本,需要安装imagemask(以防pdf viewer太老无法查看slides) ``` ### 在线编译 在 [Typst App](https://typst.app) 上使用本模板进行在线编译。 ## 如何为该项目贡献代码? 还请查看 [How to pull request](CONTRIBUTING.md/#how-to-pull-request)。 ## 开源协议 该项目使用 [MIT License](LICENSE) 开源协议。 ### QQ 群 * TJ-CSCCG 交流群:`1013806782`
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/hover/user.typ
typst
Apache License 2.0
/// Test #let f() = 1; #(/* ident after */ f());
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.2.0/test/test.typ
typst
Apache License 2.0
#import "@preview/cetz:0.1.2" #import "/src/exports.typ": * #set page(width: 10cm, height: auto) #show heading.where(level: 1): it => pagebreak(weak: true) + it = Arrow heads Compare to symbols $#sym.arrow$, $#sym.arrow.twohead$, $#sym.arrow.hook$, $#sym.arrow.bar$ #fletcher.diagram( // debug: 1, spacing: (10mm, 5mm), { for i in (0, 1, 2) { let x = 2*i let bend = 40deg*i ( (marks: ("harpoon", "harpoon'")), (marks: ("head", "head")), (marks: ("tail", "tail")), (marks: ("twotail", "twohead")), (marks: ("twohead", "twotail")), (marks: ("hook", "head")), (marks: ("hook", "hook'")), (marks: ("bar", "bar")), (marks: (none, none), extrude: (2.5,0,-2.5)), (marks: ("head", "head"), extrude: (1.5,-1.5)), (marks: ("tail", "tail"), extrude: (1.5,-1.5)), (marks: ("bar", "head"), extrude: (2,0,-2)), (marks: ("twotail", "twohead"), extrude: (1.5,-1.5)), (marks: ("circle", "bigcircle")), (marks: ("circle", "bigcircle"), extrude: (1.5, -1.5)), ).enumerate().map(((i, args)) => { edge((x, -i), (x + 1, -i), ..args, bend: bend) }).join() } }) = Double and triple lines #for (i, a) in ("->", "=>", "==>").enumerate() [ Formula #fletcher.diagram( // node-inset: 5pt, label-sep: 1pt + i*1pt, node((0, -i), $A$), edge((0, -i), (1, -i), text(0.6em, $f$), a), node((1, -i), $B$), ). \ ] = Arrow head shorthands #import "/src/main.typ": parse-arrow-shorthand $ #for i in ( "->", "<-", "<->", "<=>", "<==>", "|->", "|=>", ">->", "->>", "hook->", "hook'--hook", "|=|", ">>-<<", "harpoon-harpoon'", "harpoon'-<<", "<--hook'", "|..|", "hooks--hooks", "o-O", "o==O", ) { $ #block(inset: 2pt, fill: white.darken(5%), raw(i)) &= #fletcher.diagram(edge((0,0), (1,0), ..parse-arrow-shorthand(i))) \ $ } $ = Connectors #fletcher.diagram( debug: 0, cell-size: (10mm, 10mm), node((0,1), $X$), node((1,1), $Y$), node((0,0), $Z$), edge((0,1), (1,1), marks: (none, "head")), edge((0,0), (1,1), $f$, marks: ("hook", "head"), dash: "dashed"), edge((0,1), (0,0), marks: (none, "twohead")), edge((0,1), (0,1), marks: (none, "head"), bend: -120deg), ) = Arc connectors #fletcher.diagram( cell-size: 3cm, { node((0,0), "from") node((1,0), "to") for θ in (0deg, 20deg, -50deg) { edge((0,0), (1,0), $#θ$, bend: θ, marks: (none, "head")) } }) #fletcher.diagram( debug: 3, node((0,0), $X$), node((1,0), $Y$), edge((0,0), (1,0), bend: 45deg, marks: ("head", "head")), ) #for (i, to) in ((0,1), (1,0), (calc.sqrt(1/2),-calc.sqrt(1/2))).enumerate() { fletcher.diagram(debug: 0, { node((0,0), $A$) node(to, $B$) let N = 6 range(N + 1).map(x => (x/N - 0.5)*2*120deg).map(θ => edge((0,0), to, bend: θ, marks: ("tail", "head"))).join() }) } = Defocus #let around = ( (-1,+1), ( 0,+1), (+1,+1), (-1, 0), (+1, 0), (-1,-1), ( 0,-1), (+1,-1), ) #grid( columns: 2, ..(-10, -1, -.25, 0, +.25, +1, +10).map(defocus => { ((7em, 3em), (3em, 7em)).map(((w, h)) => { align(center + horizon, fletcher.diagram( node-defocus: defocus, node-inset: 0pt, { node((0,0), rect(width: w, height: h, inset: 0pt, align(center + horizon)[#defocus])) for p in around { edge(p, (0,0)) } })) }) }).join() ) = Label placement Default placement above the line. #fletcher.diagram( // cell-size: (2.2cm, 2cm), spacing: 2cm, debug: 3, { for p in around { edge(p, (0,0), $f$) } }) #fletcher.diagram(spacing: 1.5cm, { for (i, a) in (left, center, right).enumerate() { for (j, θ) in (-30deg, 0deg, 50deg).enumerate() { edge((2*i, j), (2*i + 1, j), label: a, "->", label-side: a, bend: θ) } } }) = Crossing connectors #fletcher.diagram({ edge((0,1), (1,0)) edge((0,0), (1,1), crossing: true) edge((2,1), (3,0), "|-|", bend: -20deg) edge((2,0), (3,1), "<=>", crossing: true, bend: 20deg) }) = `edge()` argument shorthands #fletcher.diagram( edge((0,0), (1,1), "->", "double", bend: 45deg), edge((1,0), (0,1), "->>", "crossing"), edge((1,1), (2,1), $f$, "|->"), edge((0,0), (1,0), "-", "dashed"), ) = Diagram-level options #fletcher.diagram( node-stroke: black, node-fill: green.lighten(80%), label-sep: 0pt, node((0,0), $A$), node((1,1), $sin compose cos compose tan$, fill: none), node((2,0), $C$), node((3,0), $D$, shape: "rect"), edge((0,0), (1,1), $sigma$, "->", bend: -45deg), edge((2,0), (1,1), $f$, "<-"), ) = CeTZ integration #import "/src/utils.typ": vector-polar #fletcher.diagram( node((0,0), $A$, stroke: 1pt), node((2,1), [Bézier], stroke: 1pt), render: (grid, nodes, edges, options) => { cetz.canvas({ fletcher.draw-diagram(grid, nodes, edges, options) let n1 = fletcher.find-node-at(nodes, (0,0)) let p1 = fletcher.get-node-anchor(n1, 0deg) let n2 = fletcher.find-node-at(nodes, (2,1)) let p2 = fletcher.get-node-anchor(n2, -90deg) let c1 = cetz.vector.add(p1, vector-polar(20pt, 0deg)) let c2 = cetz.vector.add(p2, vector-polar(70pt, -90deg)) fletcher.draw-arrow-cap(p1, 180deg, (thickness: 1pt, paint: black), "head") cetz.draw.bezier(p1, p2, c1, c2) }) } ) = Node bounds #fletcher.diagram( debug: 2, node-outset: 5pt, node-inset: 5pt, node((0,0), `hello`, stroke: 1pt), node((1,0), `there`, stroke: 1pt), edge((0,0), (1,0), "<=>"), ) = Corner edges #let around = ( (-1,+1), (+1,+1), (-1,-1), (+1,-1), ) #for dir in (left, right) { pad(1mm, fletcher.diagram( // debug: 2, spacing: 1cm, node((0,0), [#dir]), { for c in around { node(c, $#c$) edge((0,0), c, $f$, "O=>", corner: dir, label-pos: 0.4) } } )) }
https://github.com/wjakethompson/wjt-quarto-ext
https://raw.githubusercontent.com/wjakethompson/wjt-quarto-ext/main/ku-letter/_extensions/ku-letter/typst-show.typ
typst
Creative Commons Zero v1.0 Universal
#show: doc => letter( $if(subject)$ subject: [$subject$], $endif$ $if(recipient)$ recipient: [$recipient$], $endif$ $if(sender)$ sender: [$sender$], $endif$ $if(header-logo)$ header-logo: "$header-logo$", $endif$ $if(footer-logo)$ footer-logo: "$footer-logo$", $endif$ $if(date)$ date: [$date$], $endif$ doc, )
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/para/para_mix_result.typ
typst
In this #strike[report,];#underline[changed,] we will #strike[explore];#underline[changed] the various factors that influence #emph[fluid dynamics] in#strike[ ];#strike[glaciers];#strike[ ];#strike[ha];#strike[ ];#strike[they];#strike[ ];#strike[contribute] to the formation and behaviour of these natural structures. #strike[All];#strike[ ];#strike[manuscripts];#strike[ ];#strike[are];#strike[ ];#strike[to];#strike[ ];#strike[be];#strike[ ];#strike[submitted];#strike[ ];#strike[electronically];#strike[ ];#strike[to];#strike[ ];#strike[the];#strike[ ];#strike[ScholarOne];#strike[ ];#strike[Abstracts];#strike[ ];#strike[site];#strike[ ];#strike[created];#strike[ ];#strike[for];#strike[ ];#strike[each];#strike[ ];#strike[conference.];#strike[ ];#strike[The];#strike[ ];#strike[manuscript];#strike[ ];#strike[upload];#strike[ ];#strike[will];#strike[ ];#strike[be];#strike[ ];#strike[enabled];#strike[ ];#strike[several];#strike[ ];#strike[weeks];#strike[ ];#strike[after];#strike[ ];#strike[acceptance];#strike[ ];#strike[notices];#strike[ ];#strike[have];#strike[ ];#strike[been];#strike[ ];#strike[sent.];#strike[ ];#strike[Presenting];#strike[ ];#strike[authors];#strike[ ];#strike[of];#strike[ ];#strike[accepted];#strike[ ];#strike[papers];#strike[ ];#strike[will];#strike[ ];#strike[receive];#strike[ ];#strike[an];#strike[ ];#strike[email];#strike[ ];#strike[with];#strike[ ];#strike[instructions];#strike[ ];#strike[when];#strike[ ];#strike[manuscript];#strike[ ];#strike[submission];#strike[ ];#strike[opens.];#strike[ ];#strike[It];#strike[ ];#strike[is];#strike[ ];#strike[important];#strike[ ];#strike[that];#strike[ ];#strike[presenting];#strike[ ];#strike[authors];#strike[ ];#strike[keep];#strike[ ];#strike[their];#strike[ ];#strike[email];#strike[ ];#strike[addresses];#strike[ ];#strike[up-to-date];#strike[ ];#strike[so];#strike[ ];#strike[they];#strike[ ];#strike[do];#strike[ ];#strike[not];#strike[ ];#strike[miss];#underline[Something] #strike[this];#underline[new.] #strike[notice.];#underline[Monkey.] #underline[All];#underline[ ];#underline[changed];#underline[ ];#underline[are];#underline[ ];#underline[to];#underline[ ];#underline[be];#underline[ ];#underline[changed];#underline[ ];#strike[It];#underline[electronically] #strike[is];#underline[to] the#underline[ ];#underline[site];#underline[ ];#underline[created];#underline[ ];#underline[for];#underline[ ];#underline[each];#underline[ ];#underline[conference.];#underline[ ];#underline[The];#underline[ ];#underline[manuscript];#underline[ ];#underline[upload];#underline[ ];#underline[will] #strike[responsibility];#underline[be] #strike[of];#underline[enabled] #strike[the];#underline[several] #strike[author];#underline[weeks] #strike[to];#underline[after] #strike[obtain];#underline[acceptance] #strike[any];#underline[notices] #strike[required];#underline[have] #strike[government];#underline[been] #strike[or];#underline[sent.] #strike[company];#underline[Presenting] #strike[reviews];#underline[authors] #strike[for];#underline[of] #strike[their];#underline[accepted] papers#underline[ ];#underline[will];#underline[ ];#underline[receive];#underline[ ];#underline[an];#underline[ ];#underline[email];#underline[ ];#underline[with];#underline[ ];#underline[instructions];#underline[ ];#underline[when];#underline[ ];#underline[manuscript];#underline[ ];#underline[submission] #strike[in];#underline[opens.] #strike[advance];#underline[It] #strike[of];#underline[is] #strike[publication.];#underline[important] #strike[Start];#underline[that] #strike[early];#underline[presenting] #strike[to];#underline[authors] #strike[determine];#underline[keep] #strike[if];#underline[their] #strike[the];#underline[email] #strike[reviews];#underline[addresses] #strike[are];#underline[up-to-date] #strike[required;];#underline[so] #strike[this];#underline[they] #strike[process];#underline[do] #strike[can];#underline[not] #strike[take];#underline[miss] #strike[several];#underline[this] #strike[weeks.];#underline[notice.]
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/utils/components.typ
typst
The Unlicense
#import "/globals.typ" /// A constructor for a table of contents component. /// /// *Example Usage:* /// ```typ /// #let toc = utils.make-toc((frontmatter, body, appendix) => { /// for entry in body [ /// #entry.title /// #box(width: 1fr, line(length: 100%, stroke: (dash: "dotted"))) /// #entry.page-number /// ] /// }) /// ``` /// - callback (function): A function which returns the content of the toc. The function must take `frontmatter`, `body`, and `appendix` arguments. /// -> function #let make-toc(callback) = { let helper(type) = { let (state, markers) = if type == "frontmatter" { ( globals.frontmatter-entries, query( selector(<notebook-frontmatter>), ), ) } else if type == "body" { ( globals.entries, query( selector(<notebook-body>), ), ) } else if type == "appendix" { ( globals.appendix-entries, query( selector(<notebook-appendix>), ), ) } else { panic("No valid entry type selected.") } let result = () for (index, entry) in state.final().enumerate() { let page-number = counter(page).at( markers.at(index).location(), ).at(0) let ctx = entry.ctx ctx.page-number = page-number result.push(ctx) } return result } return () => context { let frontmatter-entries = helper("frontmatter") let body-entries = helper("body") let appendix-entries = helper("appendix") callback( frontmatter-entries, body-entries, appendix-entries, ) } } /// Constructor for a glossary component /// /// *Example Usage:* /// ```typ /// #let glossary = utils.make-glossary(glossary => { /// stack( /// spacing: 0.5em, /// ..for entry in glossary { /// ( /// [ /// = #entry.word /// /// #entry.definition /// ], /// ) /// }, /// ) /// }) /// ``` /// - callback (function): A function that returns the content of the glossary. The function must take a `glossary` argument. /// -> function #let make-glossary(callback) = { return () => context { let sorted-glossary = globals.glossary-entries.final().sorted(key: ( (word: word, definition: definition), ) => word) callback(sorted-glossary) } } /// Constructor for a pro / con component /// /// *Example Usage:* /// ```typ /// #let pro-con = utils.make-pro-con((pros, cons) => { /// table( /// columns: ( /// 1fr, /// 1fr, /// ), /// table.cell(fill: green)[*Pros*], /// table.cell(fill: red)[*Cons*], /// pros, /// cons, /// ) /// }) /// ``` /// /// - callback (function): A function that returns the content of the pro / con table. The function must take `pros` and `cons` arguments. /// -> function #let make-pro-con(callback) = { return (pros: [], cons: []) => { callback(pros, cons) } } /// Constructor for a decision matrix /// /// *Example Usage:* /// ```typ /// #let decision-matrix = utils.make-decision-matrix((properties, data) => { /// // ... /// }) /// ``` /// - callback (function): A function that returns the content of the matrix. The function must `properties` and `data` arguments. /// -> function #let make-decision-matrix(callback) = { return (properties: (), ..choices) => { // ensure the properties are passed in correctly // // this variable tracks whether the user // is using the alternate mode of passing in arguments, // where each property is a str instead of a dictionary let alternate-format = false for property in properties { if type(property) == str { alternate-format = true } else { assert( not alternate-format, message: "Property should be of type 'str'", ) if property.at("weight", default: none) == none { property.insert("weight", 1) } assert.eq(type(property.name), str) assert(type(property.weight) == float or type(property.weight) == int) } } // ensure the choices are passed in correctly for choice in choices.pos() { for (index, rating) in choice.enumerate() { if index == 0 { assert.eq(type(rating), str) continue } assert( type(rating) == int or type(rating) == float, message: "Values for decision matrices must be of type 'float' or 'int'", ) } assert.eq( choice.len() - 1, properties.len(), message: "The number of supplied values did not match the number of properties.", ) } // the calculation should only need to parse data in one format, // so if the user passed in the alternate, format we'll just convert it to the standard one properties = if alternate-format { properties.map(property => (name: property, weight: 1)) } else { properties } // now we can actually calculate the data let data = (:) for (index, choice) in choices.pos().enumerate() { let name = choice.at(0) let values = choice.slice(1) let unweighted-total = values.sum() let weighted-values = values.enumerate().map(( (index, value), ) => value * properties.at(index).at( "weight", default: 1, )) let weighted-total = weighted-values.sum() let property-data = (:) for (index, property) in properties.enumerate() { property-data.insert( property.name, ( unweighted: values.at(index), weighted: weighted-values.at(index), highest: false, ), ) } property-data.insert( "total", ( unweighted: unweighted-total, weighted: weighted-total, highest: false, ), ) data.insert( name, property-data, ) } // now that we've filled in all of the data, we can calculate which choice won // we're going to treat total like another property for the sake of calculating if it won properties.push((name: "total")) for property in properties { let highest = ( // Records the index of the choice which had the highest total index: 0, value: 0, ) for (index, choice) in data { let property-value = choice.at(property.name).weighted if property-value > highest.value { highest.index = index highest.value = property-value } } data.at(highest.index).at(property.name).highest = true } properties.pop() return callback(properties, data) } } /// A constructor for an admonition component. /// /// *Example Usage:* /// ```typ /// #let admonition = utils.make-admonition((type, body) => { /// //.. /// } /// ``` /// - callback (function): A function that returns the content for the admonition. The function must take `type` and `body` arguments. /// Valid types include: /// - `"note"`, /// - `"example"`, /// - `"warning"`, /// - `"quote"`, /// - `"equation"`, /// /// - `"identify"`, /// - `"brainstorm"`, /// - `"decide"`, /// - `"decision"`, // DEPRECATED /// - `"build"`, /// - `"program"`, /// - `"test"`, /// - `"management"`, /// - `"notebook"`, /// /// -> function #let make-admonition(callback) = { let valid-types = ( "note", "example", "warning", "quote", "equation", "identify", "brainstorm", "decide", "decision", "build", "program", "test", "management", "notebook", ) let valid-types-printable = valid-types.fold( "", ( base, value, ) => { base + " '" + value + "'" }, ) return (type: none, body) => { if not valid-types.contains(type) { panic("Entry type '" + str(type) + "' is not valid. Valid types include:" + valid-types-printable) } callback( type, body, ) } } /// A constructor for a pie chart component /// /// *Example Usage:* /// /// ```typ /// #let pie-chart = utils.make-pie-chart(data => { /// // ... /// }) /// ``` /// - callback (function): A function that returns the content for the pie chart. The function must take a `data` argument. /// -> function #let make-pie-chart(callback) = { return (..data) => { callback(data) } } /// A constructor for a plot component /// /// *Example Usage:* /// ```typ /// #let plot = utils.make-plot((title, x-label, y-label, length, data) => { /// // ... /// }) /// ``` /// /// - callback (function): A function that returns the content for the plot. /// The function must take `title`, `x-label`, `y-label`, `length`, and `data` arguments. /// -> function #let make-plot(callback) = { return (title: "", x-label: "", y-label: "", length: auto, ..data) => { callback(title, x-label, y-label, length, data) } } // TODO: add method for these extra components: // - gantt chart // - tournament // - team
https://github.com/alexanderkoller/typst-blinky
https://raw.githubusercontent.com/alexanderkoller/typst-blinky/main/blinky.typ
typst
MIT License
#let p = plugin("blinky.wasm") #let bib_re = regex("!!BIBENTRY!([^!]+)!!") #let link-bib-urls(bibsrc, content) = { let serialized = p.get_bib_map(bytes(bibsrc)) let bib_map = cbor.decode(serialized) show bib_re: it => { let (key,) = it.text.match(bib_re).captures let entry = bib_map.at(key, default: "") if entry == "" { it } else { let title = entry.fields.title let url = entry.fields.at("url", default: "") let doi = entry.fields.at("doi", default: "") if doi != "" { let url = "https://doi.org/" + doi link(url)[#title] } else if url != "" { link(url)[#title] } else { [#title] } } } content }
https://github.com/augustebaum/petri
https://raw.githubusercontent.com/augustebaum/petri/main/tests/fletcher/connect-places-with-transitions/test.typ
typst
MIT License
#import "/src/lib.typ": * #set page(width: auto, height: auto, margin: 1cm) #import "@preview/fletcher:0.4.2" as fletcher: edge /// % Place 1 /// \node[place, /// fill=teal!25, /// draw=teal!75, /// tokens=2, /// label=$P_1$] (place1) at (0,0) {}; /// /// % Place 2 /// \node[place, /// fill=teal!25, /// draw=teal!75, /// tokens=1, /// label=$P_2$] (place2) at (4,0) {}; /// /// % Transition /// \node[transition, /// minimum height=12mm, /// minimum width=1.5mm, /// fill=black, /// label=$T$] (trans) at (2,0) {}; /// /// % Connect P-T /// \draw[-latex,thick] (place1) -- (trans); /// /// % Connect T-P /// \draw[-latex,thick] (trans) -- (place2); #fletcher.diagram( node-stroke: 0.5pt, p((0,0), $P_1$, fill: teal.lighten(25%), stroke: teal.darken(15%), tokens: 2), edge("-|>"), t((2,0), $T$, fill: black), edge("-|>"), p((4,0), $P_2$, fill: teal.lighten(25%), stroke: teal.darken(15%), tokens: 1), )
https://github.com/hugoledoux/msc_geomatics_thesis_typst
https://raw.githubusercontent.com/hugoledoux/msc_geomatics_thesis_typst/main/README.md
markdown
MIT License
1. put your details in `settings.toml` 2. `typst compile main.typ`
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/casy/cas3.typ
typst
#import "/style.typ": * #import "/SK/texts.typ": * #import "../styleCasoslov.typ": * = Tretí čas #show: rest => columns(2, rest) #nacaloBezKnaza #zalm(16) #zalm(24) #zalm(50) #si #lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)] #lettrine("Pane, zmiluj sa.") #note[(3x)] == Tropáre #note[Berieme tropár, prípadne tropáre podľa predpisu] #primText[I teraz: (Bohorodičník)] #lettrine("Bohorodička, ty si pravý vinič, * z ktorého nám vyrástol plod života. * K tebe sa modlíme: * Modli sa k nemu, Vládkyňa, so svätými apoštolmi, * aby sa zmiloval nad našimi dušami.") #zoznam(( "Nech je velebený Pán deň čo deň; * nesie nás Boh, naša spása. * Náš Boh je Boh spásy.", )) #trojsvatePoOtcenas == Kondák #note[Berieme kondák podľa predpisu] #lettrine("Pane, zmiluj sa.") #primText([40x]) #vKazdomCase #ektenia(3) #lettrine("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.") Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami. #prepustenieMaleBezKnaza
https://github.com/02hyc/Group-Meeting-Typst
https://raw.githubusercontent.com/02hyc/Group-Meeting-Typst/master/sections/weekly-report.typ
typst
#import "../globals.typ": * = Weekly Meeting == July 19, 2024 === Towards Self-Assembling Artificial Neural Networks through Neural Developmental Programs #footnote[Najarro E, Sudhakaran S, Risi S. Towards self-assembling artificial neural networks through neural developmental programs[C]] #figure( image("../images/2024.7.19_1.png", width: 80%), caption: [Neural Development Program approach for growing neural network] ) - Use the Neural Development Program(NDP) to control *the growth of new networks* - Two training methods: *Evolutionary-based* and *Gradient-based* - Execute experiments on *MNIST, XOR, CartPole, LunarLander* == July 19, 2024 === Towards Self-Assembling Artificial Neural Networks through Neural Developmental Programs #figure( image("../images/2024.7.19_2.png"), caption: [Developmental growth of solving the CartPole balancing task], ) - No indication of *robustness* or other performance advantages - No additional information about the *topological properties* of the network == July 19, 2024 === HYPERNETWORKS #footnote[<NAME>, <NAME>, <NAME> V. Hypernetworks[J]. arXiv preprint arXiv:1609.09106, 2016.] - An approach of using a *hypernetwork* to generate the weights for another network, which is similar to the nature: the relationship between a *genotype* and a *phenotype* - Generate weights for practical architectures by taking layer embedding vectors as inputs - Hypernetworks are trained *end-to-end* with gradient descent together with the main network === Reflection - The focus is not on generating networks, but on *the ability to self-explore* in a multi-task environment - Generative networks are a means of implementation. Are there any existing methods that can achieve self-exploration capabilities to a certain extent, such as *LLM-based agents* == July 26, 2024 - Agents environments setup - New reasoning framework (modify the prompts) - Digital tasks (fine tune on the digital tasks) - Embodied tasks (usually with a vision module) - Learn of reinforcement learning == July 26, 2024 === AgentGym #footnote[<NAME>, <NAME>, <NAME>, et al. AgentGym: Evolving Large Language Model-based Agents across Diverse Environments[J]. arXiv preprint arXiv:2406.04151, 2024.] #figure( image("../images/2024.7.26_3.png"), caption: [Overview of the AgentGym framework], ) == July 26, 2024 === OSWORLD #footnote[<NAME>, <NAME>, <NAME>, et al. Osworld: Benchmarking multimodal agents for open-ended tasks in real computer environments[J]. arXiv preprint arXiv:2404.07972, 2024.] #figure( image("../images/2024.7.26_2.png", width: 90%), caption:[OSWORLD: a real computer environment for multimodal agents], ) == July 26, 2024 === FunSearch #footnote[<NAME>, <NAME>, <NAME>, et al. Mathematical discoveries from program search with large language models[J]. Nature, 2024, 625(7995): 468-475.] #figure( image("../images/2024.7.26_1.png"), caption: [Overview of FunSearch], ) == Aug, 2, 2024 === Target - Diffusion Models as Tools for Gene Expression —— Genotype - Use partial modules in a large model to adapt to different tasks —— Phenotype #figure( image("../images/2024.8.02_1.png", width: 70%), caption: [Overview of PGDiff Framework for Versatile Face Restoration #footnote[<NAME>, <NAME>, <NAME>, et al. PGDiff: Guiding diffusion models for versatile face restoration via partial guidance[J]. Advances in Neural Information Processing Systems, 2024, 36.]], ) == Aug, 2, 2024 === Keywords - Conditional Diffusion Models - Pruning - Model Selector - Multi-task learning - Neural Architecture Search - The representations of the architectures in the search space - Introduce diffusion models as a search algorithm == Aug, 23, 2024 === DiffusionNAG#footnote[<NAME>, <NAME>, <NAME>, et al. DiffusionNAG: Predictor-guided Neural Architecture Generation with Diffusion Models[J]. arXiv preprint arXiv:2305.16943, 2023.] #figure( image("../images/2024.8.23_1.png", width: 80%), caption: [Overview of DiffusionNAG] ) - Treat the neural architecture as DAG and generate the neural architecture graph through a graph diffusion model - Controlling the generation process using property predictors, whose gradient is used to guide the architectures towards a space with desired properties == Aug 23, 2024 === Transformer Layers as Painters#footnote[<NAME>, <NAME>, <NAME>, et al. Transformer Layers as Painters[J]. arXiv preprint arXiv:2407.09298, 2024.] - Explore the role of the layers of the Transformer architecture models - Experiments on BERT and Llama2 - Do the layers share the representation space - Are all layers necessary - Are all middle layers doing the same thing - Does layer order matter - Can layers run in parallel #figure( image("../images/2024.8.23_2.png", width: 80%), caption: [Different execution strategies] ) == Aug 23, 2024 === LLM to extract structured data - Encapsulate the part of LLM - Implemente text conversion from PDF to Markdown#footnote[https://github.com/VikParuchuri/marker] #focus-slide[ Question? ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/gallery/test5.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw #import "../src/lib.typ": * #set page(width: auto, height: auto, margin: .5cm) #circuit({ element.multiplexer( x: 0, y: 0, w: .5, h: 1.5, id: "PCMux", entries: 2, fill: util.colors.blue, h-ratio: 80% ) element.block( x: (rel: 2, to: "PCMux.east"), y: (from: "PCMux-port-out", to: "in"), w: 1, h: 1.5, id: "PCBuf", ports: ( north: ((id: "clk", clock: true),), west: ((id: "in"),), east: ((id: "out"),) ), fill: util.colors.green ) element.block( x: (rel: 2, to: "PCBuf.east"), y: (from: "PCBuf-port-out", to: "A"), w: 3, h: 4, id: "IMem", ports: ( west: ( (id: "A", name: "A"), ), east: ( (id: "RD", name: "RD"), ) ), ports-margins: ( west: (0%, 50%), east: (0%, 50%) ), fill: util.colors.green, name: "Instruction\nMemory" ) element.block( x: (rel: 3, to: "IMem.east"), y: (from: "IMem-port-RD", to: "A1"), w: 4.5, h: 4, id: "RegFile", ports: ( north: ( (id: "clk", clock: true, small: true), (id: "WE3", name: "WE3"), (id: "dummy1") ), west: ( (id: "dummy2"), (id: "A1", name: "A1"), (id: "dummy3"), (id: "A2", name: "A2"), (id: "A3", name: "A3"), (id: "dummy4"), (id: "WD3", name: "WD3"), ), east: ( (id: "RD1", name: "RD1"), (id: "RD2", name: "RD2"), ) ), ports-margins: ( north: (-20%, -20%), east: (0%, 10%) ), fill: util.colors.green, name: "Register\nFile" ) element.alu( x: (rel: -.7, to: "IMem.center"), y: -7, w: 1.4, h: 2.8, id: "PCAdd", name: text("+", size: 1.5em), name-anchor: "name", fill: util.colors.pink ) element.extender( x: (rel: 0, to: "RegFile.west"), y: (from: "PCAdd-port-out", to: "in"), w: 4, h: 1.5, id: "Ext", h-ratio: 50%, name: "Extend", name-anchor: "south", align-out: false, fill: util.colors.green ) element.multiplexer( x: (rel: 3, to: "RegFile.east"), y: (from: "RegFile-port-RD2", to: "in0"), w: .5, h: 1.5, id: "SrcBMux", fill: util.colors.blue, h-ratio: 80% ) element.alu( x: (rel: 2, to: "SrcBMux.east"), y: (from: "SrcBMux-port-out", to: "in2"), w: 1.4, h: 2.8, id: "ALU", name: rotate("ALU", -90deg), name-anchor: "name", fill: util.colors.pink ) element.alu( x: (rel: 2, to: "SrcBMux.east"), y: (from: "Ext-port-out", to: "in2"), w: 1.4, h: 2.8, id: "JumpAdd", name: text("+", size: 1.5em), name-anchor: "name", fill: util.colors.pink ) element.block( x: (rel: 4, to: "ALU.east"), y: (from: "ALU-port-out", to: "A"), w: 3, h: 4, id: "DMem", name: "Data\nMemory", ports: ( north: ( (id: "clk", clock: true, small: true), (id: "dummy1"), (id: "WE", name: "WE") ), west: ( (id: "A", name: "A"), (id: "WD", name: "WD") ), east: ( (id: "RD", name: "RD"), (id: "dummy2") ) ), ports-margins: ( north: (-10%, -10%), west: (-20%, -30%), east: (-10%, -20%) ), fill: util.colors.green ) element.multiplexer( x: (rel: 3, to: "DMem.east"), y: (from: "DMem-port-RD", to: "in1"), w: .5, h: 1.5, id: "ResMux", entries: 2, fill: util.colors.blue, h-ratio: 80% ) element.block( x: (rel: 0, to: "RegFile.west"), y: 3.5, w: 2.5, h: 5, id: "Ctrl", name: "Control\nUnit", name-anchor: "north", ports: ( west: ( (id: "op", name: "op"), (id: "funct3", name: "funct3"), (id: "funct7", name: [funct7#sub("[5]")]), (id: "zero", name: "Zero"), ), east: ( (id: "PCSrc"), (id: "ResSrc"), (id: "MemWrite"), (id: "ALUCtrl"), (id: "ALUSrc"), (id: "ImmSrc"), (id: "RegWrite"), ) ), ports-margins: ( west: (40%, 0%) ), fill: util.colors.orange ) // Wires wire.wire( "wPCNext", ("PCMux-port-out", "PCBuf-port-in"), name: "PCNext" ) wire.stub("PCBuf-port-clk", "north", name: "clk", length: 0.25) wire.wire( "wPC1", ("PCBuf-port-out", "IMem-port-A"), name: "PC" ) wire.wire( "wPC2", ("PCBuf-port-out", "JumpAdd-port-in1"), style: "zigzag", zigzag-ratio: 1 ) wire.wire( "wPC3", ("PCBuf-port-out", "PCAdd-port-in1"), style: "zigzag", zigzag-ratio: 1 ) wire.intersection("wPC2.zig") wire.intersection("wPC2.zag") wire.stub("PCAdd-port-in2", "west", name: "4", length: 1.5) wire.wire( "wPC+4", ("PCAdd-port-out", "PCMux-port-in0"), style: "dodge", dodge-sides: ("east", "west"), dodge-y: -7.5, dodge-margins: (1.2, .5), name: "PC+4", name-pos: "start" ) let mid = ("IMem-port-RD", 50%, "RegFile-port-A1") wire.wire( "wInstr", ("IMem-port-RD", mid), bus: true, name: "Instr", name-pos: "start" ) draw.hide({ draw.line(name: "bus-top", mid, (horizontal: (), vertical: "Ctrl-port-op") ) draw.line(name: "bus-bot", mid, (horizontal: (), vertical: "Ext-port-in") ) }) wire.wire( "wInstrBus", ("bus-top.end", "bus-bot.end"), bus: true ) wire.wire( "wOp", ("Ctrl-port-op", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (6, 0) ) wire.wire( "wF3", ("Ctrl-port-funct3", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (14, 12) ) wire.wire( "wF7", ("Ctrl-port-funct7", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (30,) ) wire.wire( "wA1", ("RegFile-port-A1", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (19, 15) ) wire.wire( "wA2", ("RegFile-port-A2", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (24, 20) ) wire.wire( "wA3", ("RegFile-port-A3", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (11, 7) ) wire.wire( "wExt", ("Ext-port-in", (horizontal: mid, vertical: ())), bus: true, reverse: true, slice: (31, 7) ) wire.intersection("wF3.end") wire.intersection("wF7.end") wire.intersection("wA1.end") wire.intersection("wA2.end") wire.intersection("wA3.end") wire.stub("RegFile-port-clk", "north", name: "clk", length: 0.25) wire.wire("wRD2", ("RegFile-port-RD2", "SrcBMux-port-in0")) wire.wire( "wWD", ("RegFile-port-RD2", "DMem-port-WD"), style: "zigzag", zigzag-ratio: 1.5, name: "WriteData", name-pos: "end" ) wire.intersection("wWD.zig") wire.wire( "wImmALU", ("Ext-port-out", "SrcBMux-port-in1"), style: "zigzag", zigzag-ratio: 2.5, name: "ImmExt", name-pos: "start" ) wire.wire( "wImmJump", ("Ext-port-out", "JumpAdd-port-in2") ) wire.intersection("wImmALU.zig") wire.wire( "wJumpPC", ("JumpAdd-port-out", "PCMux-port-in1"), style: "dodge", dodge-sides: ("east", "west"), dodge-y: -8, dodge-margins: (1, 1), name: "PCTarget", name-pos: "start" ) wire.wire( "wSrcA", ("RegFile-port-RD1", "ALU-port-in1"), name: "SrcA", name-pos: "end" ) wire.wire( "wSrcB", ("SrcBMux-port-out", "ALU-port-in2"), name: "SrcB", name-pos: "end" ) wire.wire( "wZero", ( ("ALU.north-east", 50%, "ALU-port-out"), "Ctrl-port-zero" ), style: "dodge", dodge-sides: ("east", "west"), dodge-y: 3, dodge-margins: (1.5, 1), name: "Zero", name-pos: "start" ) wire.wire( "wALURes1", ("ALU-port-out", "DMem-port-A"), name: "ALUResult", name-pos: "start" ) wire.wire( "wALURes2", ("ALU-port-out", "ResMux-port-in0"), style: "dodge", dodge-sides: ("east", "west"), dodge-y: 2, dodge-margins: (3, 2) ) wire.intersection("wALURes2.start2") wire.stub("DMem-port-clk", "north", name: "clk", length: 0.25) wire.wire( "wRD", ("DMem-port-RD", "ResMux-port-in1"), name: "ReadData", name-pos: "start" ) wire.wire( "wRes", ("ResMux-port-out", "RegFile-port-WD3"), style: "dodge", dodge-sides: ("east", "west"), dodge-y: -7.5, dodge-margins: (1, 2) ) draw.content( "wRes.dodge-start", "Result", anchor: "south-east", padding: 5pt ) // Other wires draw.group({ draw.stroke(util.colors.blue) draw.line(name: "wPCSrc", "Ctrl-port-PCSrc", (horizontal: "RegFile.east", vertical: ()), (horizontal: (), vertical: (rel: (0, 0.5), to: "Ctrl.north")), (horizontal: "PCMux.north", vertical: ()), "PCMux.north" ) draw.line(name: "wResSrc", "Ctrl-port-ResSrc", (horizontal: "ResMux.north", vertical: ()), "ResMux.north" ) draw.line(name: "wMemWrite", "Ctrl-port-MemWrite", (horizontal: "DMem-port-WE", vertical: ()), "DMem-port-WE" ) draw.line(name: "wALUCtrl", "Ctrl-port-ALUCtrl", (horizontal: "ALU.north", vertical: ()), "ALU.north" ) draw.line(name: "wALUSrc", "Ctrl-port-ALUSrc", (horizontal: "SrcBMux.north", vertical: ()), "SrcBMux.north" ) draw.line(name: "wImmSrc", "Ctrl-port-ImmSrc", (rel: (1, 0), to: (horizontal: "RegFile.east", vertical: ())), (horizontal: (), vertical: (rel: (0, -.5), to: "RegFile.south")), (horizontal: "Ext.north", vertical: ()), "Ext.north" ) draw.line(name: "wRegWrite", "Ctrl-port-RegWrite", (rel: (.5, 0), to: (horizontal: "RegFile.east", vertical: ())), (horizontal: (), vertical: ("Ctrl.south", 50%, "RegFile.north")), (horizontal: "RegFile-port-WE3", vertical: ()), "RegFile-port-WE3" ) let names = ( "PCSrc": "PCSrc", "ResSrc": "ResultSrc", "MemWrite": "MemWrite", "ALUCtrl": [ALUControl#sub("[2:0]")], "ALUSrc": "ALUSrc", "ImmSrc": [ImmSrc#sub("[1:0]")], "RegWrite": "RegWrite" ) for (port, name) in names { draw.content("Ctrl-port-"+port, name, anchor: "south-west", padding: 3pt) } }) })
https://github.com/maxluoXIII/resume
https://raw.githubusercontent.com/maxluoXIII/resume/master/resume.typ
typst
#show heading: set text(font: "Linux Biolinum") #show link: underline // Uncomment the following lines to adjust the size of text // The recommend resume text size is from `10pt` to `12pt` // #set text( // size: 12pt, // ) // Feel free to change the margin below to best fit your own CV #set page( margin: (x: 1.0cm, y: 1.3cm), ) // For more customizable options, please refer to official reference: https://typst.app/docs/reference/ #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} = <NAME> #link("mailto:<EMAIL>") | #link("https://github.com/maxluoXIII")[github.com/maxluoXIII] | #link("https://maxluoxiii.github.io")[maxluoxiii.github.io] == Work Experience #chiline() *#link("https://ibm.com")[IBM]* #h(1fr) Aug. 2021 -- Present \ Backend Developer #h(1fr) Rochester, MN \ - Developed robust device drivers for the #link("https://www.ibm.com/products/ibm-i")[IBM i] operating system using C++, for both physical (NVIDIA, Intel, etc.) and virtual (link aggregation, vNIC, etc.) NICs - Migrated device driver testing scripts to an open-source Python framework, expanded test coverage, and improved logging/debugging capabilities to develop a cohesive testing tool for device driver developers - Collaborated with internal and external teams to provide support for clients by providing analyses and fixes *#link("https://8i.com/")[8i]* #h(1fr) May 2020 -- Aug. 2020 \ Software Engineering Intern #h(1fr) Chicago, IL \ - Developed features for an internal MPEG-DASH player to support the company's proprietary 3D mesh, video, and audio codec including seek, caching, and adaptive bitrate selection using the C++ Qt Framework *#link("https://www.eagleseven.com/")[Eagle Seven]* #h(1fr) May 2019 -- Aug. 2019 \ Software Development Intern #h(1fr) Chicago, IL \ - Wrote software to calculate network performance metrics of high-frequency trade engines - Built a real-time dashboard using InfluxDB and Grafana to improve the automation, comparison, and real-time tracking capabilities of the performance testing framework == Education #chiline() #link("https://illinois.edu/")[*University of Illinois at Urbana-Champaign*] #h(1fr) Aug. 2017 -- May 2021 \ Bachelor of Science, Computer Science + Master of Computer Science #h(1fr) Urbana-Champaign, IL \ - Operating System Design; Distributed Systems; Communication Networks; Applied Parallel Programming - Computer Security I/II; Advanced Computer Security; Applied Cryptography; Operating System Security - Machine Learning; ML for Sys, Networks, & Security; Algorithms - Interactive Computer Graphics; UI Design; Top Down Video Game Design; Game Dev Process - Teaching Assistant for CS 225 (Data Structures) and CS 126 (Software Design Studio) - Lead discussions and code reviews to foster educational dialogue on data structures and best coding practices - Provided continuous updates to the course website to provide students with up-to-date information - Answered questions and debugged student solutions in office hours == Projects #chiline() *#link("https://github.com/maxluoXIII/server-manager")[server-manager]* #h(1fr) Mar. 2023 -- Aug. 2023 \ Creator #h(1fr) #link("https://github.com/maxluoXIII/server-manager")[GitHub] \ - Developed a Discord bot in Rust utilizing their HTTPS/REST API to allow members of a Discord server to manage multiple Minecraft servers on a host computer *#link("https://github.com/Mottokrosh/Sheet")[Sheet]* #h(1fr) Sep. 2021 -- Jan. 2022 \ Contributor #h(1fr) #link("https://github.com/Mottokrosh/Sheet")[GitHub] \ - Identified the cause for authentication and database issues that caused an outage of an open-source Node application. - Communicated with the maintainer and developed a fix that was merged into the project. - Reviewed pull requests made by other developers and helped them merge their own fixes to the project. == Skills #chiline() - *Proficient* in C/C++, Python - *Intermediate* knowledge of Rust, Java, HTML/CSS, Javascript (Angular), InfluxDB, Grafana, Unity, Unreal Engine, WebGL, Android app development, Discord app development, Qt Framework, Flutter, Chinese, Japanese - *Basic* skills with OCaml, x86 Assembly, Verilog
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/WEB/docs/TE/TE1.typ
typst
#import "/_settings/typst/template-te.typ": * #show: resume.with( "Résumé WEB - TE1", "<NAME>", cols: 3 ) = HTML == HTML structure - `<!DOCTYPE html>`: The document type declaration for HTML5 - `<html>`: The root element of an HTML page - `<head>`: Contains meta-information about the document - `<title>`: The title of the document ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <!-- CSS link --> <title>Welcome page</title> </head> <body> <h1>Hello students of the Web Technologies course !</h1> </body> </html> ``` - width=device-width : the width of the page matches the screen width - initial-scale=1.0 : the initial zoom level === Open Graph Protocol The Open Graph protocol enables any web pages to show some additional information when shared on social media or messaging apps. ```html <meta property="og:title" content="The Rock" /> <meta property="og:type" content="video.movie" /> <meta property="og:url" content="https://www.imdb.com/title/tt0117500/" /> <meta property="og:image" content="https://ia.media-imdb.com/images/rock.jpg" /> ``` == Lists === Unordered lists Unordered lists are used to list items in no particular order. They are defined with the `<ul>` element. ```html <ul> <li>Item 1</li> <li>Item 2</li> </ul> ``` === Ordered lists Ordered lists are used to list items in a specific order. They are defined with the `<ol>` element. ```html <ol> <li>Item 1</li> <li>Item 2</li> </ol> ``` == Hyperlink Hyperlinks are used to link from one page to another. They are defined with the `<a>` element. ```html <a href="https://www.google.com" title="Google" target="_blank">Google</a> <a href="mailto:<EMAIL>?subject=hello&body=world!">Hello World!</a> ``` == Media elements === Images ```html <img src="image.jpg" alt="Image description"> ``` === Audio & Video ```html <audio src="audio.mp3"></audio> <video src="video.mp4"></video> ``` === Canvas The canvas element allows for dynamic, scriptable rendering of 2D and 3D shapes. ```html <canvas id="myCanvas" width="200" height="100"></canvas> ``` == Tables Tables are used to display data in a tabular format. They are defined with the `<table>` element. ```html <table> <!-- row --> <tr> <!-- header column --> <th>Student ID</th> <th>Grade</th> </tr> <tr> <!-- regular column --> <td>4</td> <td>5</td> </tr> <tr> <!-- merged columns --> <td colspan="2">6</td> </tr> </table> ``` == Forms Forms are used to collect user input. They are defined with the `<form>` element. ```html <form action="/submit" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <input type="submit" value="Submit"> </form> ``` == Semantic elements ```html <header>Header</header> <nav>Navigation</nav> <main>Main content</main> <section>Section</section> <article>Article</article> <aside>Aside</aside> <footer>Footer</footer> ``` = CSS == CSS Selectors CSS selectors are used to select the elements to which the ruleset will apply. There are several types of selectors: === Type Type selectors select elements based on their tag name. ```css p { color: red; } ``` *This rule will apply to all `<p>` elements. in the html page.* === Id Id selectors select elements based on their `id` attribute. ```css #myId { color: red; } ``` *This rule will apply to the element with the `id="myId"` attribute.* === Class Class selectors select elements based on their `class` attribute. ```css .myClass { color: red; } ``` *This rule will apply to all elements with the `class="myClass"` attribute.* === Universal The universal selector `*` selects all elements. ```css * { color: red; } ``` *This rule will apply to all elements in the html page.* === Grouping Grouping selectors select multiple elements. ```css h1, h2, h3 { color: red; } ``` === Descendant Descendant selectors select elements that are descendants of another element. ```css div p { color: red; } ``` *This rule will apply to all `<p>` elements that are descendants of a `<div>` element.* === Child Child selectors select elements that are direct children of another element. ```css div > p { color: red; } ``` *This rule will apply to all `<p>` elements that are direct children of a `<div>` element.* === Flexbox Flexbox is a layout model that allows elements to align and distribute space within a container. ```html <div class="container"> <div class="item">Item A</div> <div class="item">Item B</div> <div class="item">Item C</div> </div> ``` ```css .container { display: flex; flex-direction: row; } .item { order: 1; flex-grow: 1 } ``` - Container (parent) properties : flex-direction, flex-wrap, flex-flow, justify-content, align-items, align-content - Item (child) properties : order, flex-grow, flex-shrink, flex-basis, flex, align-self === Grid Grid is a layout model that allows elements to align and distribute space in two dimensions. ```html <div class="container"> <div class="item">Item A</div> <div class="item">Item B</div> <div class="item">Item C</div> </div> ``` ```css .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } .item { grid-column: 1 / 3; } ``` - Container (parent) properties : grid-template-column, grid-template-rows, grid-template-areas, grid-template, ... - Item (child) properties : grid-column-start, grid-column-end, grid-column, grid-row, grid-area, ... #image("/_src/img/docs/image copy 38.png") == Media Queries Media queries are used to apply different styles based on the device’s characteristics. ```css h1 { font-size: 50px; } /* General rule */ @media (min-width: 576px) { /* Tablet dimensions */ h1 { font-size: 60px; } } @media (min-width: 768px) { /* Desktop dimensions */ h1 { font-size: 70px; } } ``` == CSS variables ```css :root { /* Global variables */ --main-color: #06c; --main-bg-color: #fff; } .my-element { color: var(--main-color, #06c); background-color: var(--main-bg-color, #fff); } ``` The var() function can take fallback values in case one of the variables is not defined. = JavaScript *Interpreted* The interpreter reads the source code and executes it directly. *Just-in-time (JIT) compiled* The interpreter compiles the hot parts of the source code into machine-code and executes it directly. *First-class functions* Functions are treated like any other value. They can be stored in variables, passed as arguments to other functions, created within functions, and returned from functions. ==== Adding JavaScript directly to HTML ```html <script type='text/javascript'> console.log('Hello, World!'); document.writeln('Hello, World!') </script> ``` ==== Adding JavaScript to an external file ```html <script src='script.js'></script> ``` - The defer attribute is used to defer the execution of the script until the page has been loaded. - The async attribute is used to load the script asynchronously. == Primitive types - *Undefined*: Unique primitive value undefined - *Number*: Real or integer number (e.g. 3.14, 42) - *Boolean*: true or false - *String*: Character sequence, whose literals begin and end with single or double - quotes (e.g. "HEIG-VD", 'hello') - *BigInt*: Arbitrary-precision integers, whose literals end with an n (e.g. - 9007199254740992n) - *Symbol*: Globally unique values usable as identifiers or keys in objects (e.g. Symbol(), Symbol("description")) - *Null*: Unique value null == Arrays - Array: Ordered collection of values The syntax for creating an array is: ```javascript let fruits = ['Apple', 'Banana', 'Cherry']; ``` Elements can be accessed using bracket notation: ```javascript console.log(fruits[0]); // Apple console.log(fruits.length); // Banana ``` === Methods on arrays ```javascript fruits.push("mango", "papaya"); // Appends new items fruits.pop(); // Removes and returns the last item fruits.reverse(); // Reverses the items' order fruits.splice(2, 1, 'Orange'); // Replaces 1 elemnt at position 2 with 'Orange' fruits.splice(1, 0, 'Peach'); // Inserts 'Peach' at index 1 ``` == Typeof operator The typeof operator returns the type of a variable or expression. ```javascript console.log(typeof 42); // number console.log(typeof 'hello'); // string console.log(typeof null); // object console.log(typeof [1, 2, 3]); // object ``` == Arithmetic operators ```javascript 1 + 1; // addition 1 - 1; // subtraction 1 / 1; // division 1 * 1; // multiplication 1 % 1; // modulo 1 ** 1; // exponentiation ``` == String operators ```javascript "con" + "cat" + "e" + "nate"; `PI = ${Math.PI}`; // template literals (instead of: "PI = " + Math.PI) ``` In practice we should opt for template literals over string concatenation. === Automatic type conversion Automatic type conversion is performed when comparing values of different types. It is at the root of many issues when using comparison operators. ```javascript "1" == 1 // true (!!!) false == 0 // true 8 * null // 0 ``` === Strict equality Strict equality compares two values for equality without type conversion. ```javascript "1" === 1 // false "1" !== 1 // true ``` == Variables === var The var statement declares a *non-block-scoped* variable, optionally initializing it to a value. Its scope is its current execution context, i.e. either the enclosing function or, if outside any function, global. It can be re-declared. ```javascript var x = 1; if (true) { var x = 2; } // same variable console.log(x); // 2 ``` === let The let statement declares a *block-scoped* local variable, optionally initializing it to a value. It can be re-assigned but not re-declared. ```javascript let x = 1; { let x = 2; } // different variable (in a new scope) console.log(x); // 1 let x = 1000; // Error: redeclaration of let x ``` === const The const statement declares a *block-scoped* read-only named constant. It can be re-assigned but not re-declared. ```javascript const x = 1; x = 2; // TypeError: Assignment to constant variable. ``` == While and do-while loops ```javascript let num = 0; while (num < 10) { console.log(num); num += 1; } let echo = ""; do { echo = prompt("Echo"); console.log(echo); } while (echo != "stop"); ``` == For loop ```javascript for (let num = 0; num < 10; num++) { console.log(num); } ``` The for...in statement iterates over the enumerable properties of an object. ```javascript let obj = {a: 1, b: 2, c: 3}; for (let prop in obj) { console.log(prop, obj[prop]); } ``` The for...of statement creates a loop iterating over iterable objects. ```javascript let nums = [0, 1, 2, 3, 4, 5, 6, 7, 8 , 9]; for (let num of nums) { console.log(num); } ``` == Declaration notation ```javascript function square(x) { return x * x; } // or var square = function(x) { return x * x; } ``` == Arrow functions ```javascript var square = x => x * x // or var square = (x) => { return x * x; } ``` == Recursion ```javascript function factorial(n) { return n == 1 ? n : n * factorial(n-1); } console.log(factorial(5)) // 5 * 4 * 3 * 2 * 1 = 120 ``` .. as long as it does not overflow the call stack. #colbreak() == Higher-order functions ```javascript function greaterThan(n) { return m => m > n; } let greaterThan10 = greaterThan(10); console.log(greaterThan10(11)); // true ``` = Regular expressions Regular expressions are patterns used to match character combinations in strings. They are created using the RegExp constructor or a literal notation. ```javascript const re1 = /ab+c/; const re2 = new RegExp(/ab+c/); ``` - `Character Classes (., \s, \d, …)` that distinguish types of chararters (resp. any, whitespace or digit) - `Character sets ([A-Z], [a-z], [0-9], [abc], …)` that match any of the enclosed - characters (resp. uppercase letters, lowercase letters, digits, and any of a, b or c) - `Either operator (x|y)` that match either the left or right handside values - `Quantifiers (\*, +, ?, {n}, {n,m})` that indicate the number of times an expression matches - `Boundaries (^, \$)` that indicate the beginnings and endings of lines and words - `Groups ((), (?<name>), (?:))` that extracts and remember (or not) information from the input - `Assertions (x(?=y))` that helps at defining conditional expressions ```javascript const emailRegex = /^[a-zA-Z]([a-zA-Z0-9._-]+)@(?:[a-zA-Z0-9]+\.)+(?:com|org|net)$/; ``` == Flags ```javascript const re1 = /ab+c/; // no flag const re2 = /ab+c/g; // global search const re3 = /ab+c/i; // case-insensitive search const re4 = /ab+c/m; // multi-line search const re5 = /ab+c/gi // global case-insensitive search ``` == Context ```javascript function doTwice(f) { f.call(this); // bind this to the current context f.call(this); // bind this to the current context } let human = { age: 32, getOlder() { this.age++; } } doTwice.call(human, human.getOlder); // bind this to human console.log(human.age); // Output will be 34 ``` == Array methods - `concat()` concatenates two or more arrays and returns a new array. - `join()` joins all elements of an array into a string. - `pop()` removes the last element from an array and returns that element. - `push()` adds one or more elements to the end of an array and returns the new length of the array. - `reverse()` reverses the order of the elements of an array. - `shift()` removes the first element from an array and returns that element. - `slice()` selects a part of an array, and returns it as a new array. - `sort()` sorts the elements of an array. - `includes()` determines whether an array contains a specified element. - `flat()` flattens an array up to the specified depth.
https://github.com/Servostar/dhbw-abb-typst-template
https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/pages/declaration-of-authorship.typ
typst
MIT License
// .--------------------------------------------------------------------------. // | Declaration of Authorship | // '--------------------------------------------------------------------------' // Author: <NAME> // Edited: 28.06.2024 // License: MIT #let new_declaration_of_authorship(config) = ( context { pagebreak(weak: true) let thesis = config.thesis let author = config.author if text.lang == "de" [ #heading("Selbständigkeitserklärung") ] else if text.lang == "en" [ #heading("Declaration of Authorship") ] v(1em) if text.lang == "de" [ Ich versichere hiermit, dass ich meine Prüfung mit dem Thema ] else if text.lang == "en" [ I hereby confirm that I have written this thesis with the subject ] v(1em) set align(center) text(weight: "bold", thesis.title) if thesis.subtitle != none { linebreak() thesis.subtitle } set align(left) v(1em) set par(justify: true) if text.lang == "de" [ selbständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe. Ich versichere zudem, dass die eingereichte elektronische Fassung mit der gedruckten Fassung übereinstimmt. ] else if text.lang == "en" [ independently and have not used any sources or aids other than those specified. I also confirm that the electronic version submitted is identical to the printed version. ] set align(horizon) grid( // set width of columns // we need two, so make both half the page width columns: (50%, 50%), row-gutter: 0.75em, align(left, {line(length: 6cm)}), align(left, {line(length: 6cm)}), align(left, if text.lang == "de" [ Ort, Datum ] else if text.lang == "en" [ Place, Date ] else { panic("no translation for language: ", text.lang) }), align(left, if text.lang == "de" [ Unterschrift ] else if text.lang == "en" [ Signature ] else { panic("no translation for language: ", text.lang) })) } )
https://github.com/noriHanda/undergrad_paper
https://raw.githubusercontent.com/noriHanda/undergrad_paper/main/main.typ
typst
#import "template.typ": * #show: project.with( title: "筋電義手人工感覚のための駆動部エネルギー測定に基づく力覚センシング", englishTitle: "Kinesthetic sense based on evaluation of actuator energy for artificial sense in myoelectric prosthetic hands", author: "半田 寛明", supervisor: "葛西 誠也 教授", affiliation: "工学部情報エレクトロニクス学科電気電子工学コース", lab: "量子知能デバイス研究室", grade: "学部4年", year: "令和5", ) #outline(indent: 2em, fill: box(width: 1fr, repeat[⋯])) // start page number #set page(numbering: "1", number-align: center, margin: (top: 35.01mm, left: 30mm, right: 30mm, bottom: 30mm)) #counter(page).update(1) = 序論 == 背景 何らかの事故や病気により後天的に上肢を無くしてしまった人、そして先天的に上肢がない人は本人の意思とは無関係に、取れる社会参加の選択肢が限られてしまう。社会構造自体をそのような人々も参画しやすい形に変革する方法も考えられるが、そのためには上肢を必要としないコミュニケーションや業務執行の方法を考える必要が出てくるため、いずれにせよ技術的課題に直面する。\ このため、上肢を補う形での社会参加が克服すべきハードルが最小に思える。そこで使用者自身の身体の一部のように感じることのできる操作感の義手が必要になってくるのは明らかである。そもそも義手には審美性のみを目的とした物も存在するが、操作可能な上、侵襲性がないため着脱が容易な筋電義手が本分野のこれからの潮流を為すと考えられる。\ 人間が自分の手を動作させる際、随意動作(意識的動作)と不随意動作(無意識的動作)に分類できる。随意動作とは、人間が意図した通りの動きをする動作である一方、不随意操作は人間が動作に対して意識的にならずとも確かに行っている動作や制御のことである。熱いものや痛みを感じると同時かむしろ感じるより前に手を引っ込めたり、重いものを持つときに無意識に力を加えてものが落ちないように制御したりといったことがこれに当たる。 筋電義手の目指す先は使用者があたかも自分の手であったかのように操作を行える状態である。このため、その完成度は問題になるが、筋電義手における随意操作性能自体は研究分野としてすでに大きなものとして存在する @Prosthetic-Hands-Trends 。一方で不随意の動作に関してはその課題感の共有の難しさから課題として捉えられにくい分野になってくる。しかし、この不随意動作無くして人の手のような操作感は得られない。 #figure(image("assets/overview_table.png"), numbering: "1", caption: text("筋電義手研究の方針と現在地"), kind: table) == 目的 不随意動作を暗黙的に義手に実装するのでは自分の手のようにはならない。生体の手のように、触る温度の形状、触り心地などはもちろんのこと、手にかかっている重量的な負担をも利用者にフィードバックする必要がある。触覚に当たる部分を皮膚感覚、重量的負担を感じる力覚の部分を深部感覚と呼ばれているが、皮膚感覚の分野については義手のみならずxRなどの分野でもハプティクスと呼ばれるように、他分野に渡り研究が進められている。一方で深部感覚については皮膚感覚と同様に重要であるにも関わらず比較的研究が進められていない。これはGoogle Scholarにて "haptics" は225,000件、 "cutaneous sensation" は516,000件ヒットするのに対し、深部感覚にあたる "bathyesthesia" は86件しかヒットしないことからも明らかである。なお "deep sense" や "deep sensing" などはディープラーニングのアルゴリズムなど多岐にわたる分野での使用がされている用語であるため除外した。これらの研究動向を踏まえ、我々は重要にも関わらずあまり手をつけられていない分野である力覚のフィードバックに今回取り組むこととした。 == 本論文の構成 本論文は全6章から構成されている。\ 第1章では本論文の目的及び先行研究を踏まえた立ち位置を論じた。\ 第2章では力覚センシング技術を紹介する。\ 第3章では筋電義手の駆動部エネルギー測定をすることで如何に力覚センシングを行うかを説明する。\ 第4章では本研究結果を用いて推論モデルを作成するのにに用いるリザバーコンピューティングの説明を行う。\ 第5章では駆動部エネルギーという信号をリザバーコンピューティングを用いて解析する手法について紹介する。\ 最後に第6章を本論文のまとめとする。 #pagebreak(weak: true) = 力覚センシング 力覚を測定するための機構は古くから研究されており、産業用ロボットやタッチディスプレイなど幅広い用途で利用されてきた。以下に主な力覚センシングをする技術を紹介する。 @Sensors == 既存の力覚センシング技術 === 歪みゲージセンサ 歪みゲージセンサはセンサー部にかかる引張力・圧縮力により、電気抵抗が変化する金属抵抗材料の性質を利用して、力やトルクに換算する。小型で精度が高く、応答性も高いことから多くの場面で使われる。 === 圧電センサ 水晶やPZT (ジルコン酸チタン酸鉛) などの圧電効果を有する材料をセンサー部に使用して、力を測定する。小型で応答性が高く、コストも比較的優れいるが精度は、ひずみゲージ式や静電容量式には及ばない。 === 静電容量センサ センサー部を金属材料の電極が向かい合わせに配置されたコンデンサ型とし、力により導体間にひずみが生じて距離が変わることによる静電容量の変化を検知する。構成が比較的簡単で低コストで生産できる上、電極をフィルム状にすると、小型化・薄型化が可能である。精度や応答性も優れている。 === 光学センサ 計測対象物に一定間隔で模様をマーキングしておき、力が加わった時に生じる模様の変化を、カメラやレーザーなどの光学センサで検出して、力の大きさを計算して求める。非接触で測定できることが最大のメリットではあるが精度、応答性、小型化、コストは、他の方式に軍配が上がるため使われる場面は限られる。 === サーボの逆起電力とサーボ内蔵センサを用いた手法 先述のようなセンサを用いない手法も古くから研究されている。 特に今回のようにサーボモータを内蔵する場合が非常に多い筋電義手のようなものの場合、もともともと内蔵されているサーボから得られる信号を用いる方法として逆起電力を観測する方法がある。これはモータに外力を与えて回転させた際にモータが発電機として振る舞う現象を用いる手法である。しかしこれだけでは回転方向がわからないため、サーボモータの回転角制御用に搭載されているエンコーダやタコジェネレータを用いることで外力の方向を割り出すというものである。\ 以下にその数理的説明を行う。 ==== センサレスセンシングの数理的説明 全外乱から外力以外の要素をモデル化し取り除くことで外力のみを抽出可能として考えると以下の式で表現される。\ #math.equation(block:true,numbering: "(1)" ,$ F_"ext"=F_"dis"-(F_"int"+F_"g"+F_"c"+D s X^"res"+Delta M s ^2X^"res"-Delta"K"_t"I"^"ref"_a) $) ただしここで$F_"dis"$は全外乱、$F_"int"$はコリオリ力・遠心力などの内部干渉力、$F_g$は姿勢の影響で重力加速度により発生する力、$F_c$はクーロン摩擦力、$D s X^"res"$は粘性摩擦力、$M$はモータ稼働部の慣性であり$M s^2 X^"res"$は周波数領域におけるモータの動力学を表す(すなわち$s, X^"res"$はそれぞれラプラス演算子と周波数領域での角度を表す変数)。$K_t$はモータに使用されている磁石の強さやコイルの巻線量によって変化するモータ固有の推力定数、$I_a^"ref"$は周波数領域における電流を表す変数である。\ 式(1)におけるC摩擦力$F_c$、粘性摩擦力$D s X^"res"$は二種の等速度試験、慣性変動$Delta M$は加速度試験によって同定することができる。@Sensorless-Sensing == 既存技術の課題 力覚を取得する方法には各種センサを用いる方法と、内蔵されているサーボモータから得られる信号を用いる方法とが一般的であることがわかった。しかし、どちらの方法も筋電義手に力覚を与えるためのアプローチとしては相応しくない。 === 力覚センサの問題点 前節で紹介した力覚センサを筋電義手に用いるとなると二つの懸念点が浮かんでくる。搭載センサの取り付け位置とコストの増加だ。前節で紹介した力覚センサはどれも圧力が直接かかる部分に設置する必要がある。物に触れた際に感じる感触が認識対象であればこれでも構わないが、今回対象とするのは稼働部にかかる力覚であるため力覚センサも稼働部に取り付ける必要が出てくる。駆動部にある程度サイズのある力覚センサを取り付けるとなると取り付け位置や取り付け方にかなりの工夫が必要となってくることは想像に難くない。\ また、コストの面でも各サーボ関節部分に力覚センサが必要となってくることから効果になってくる。筋電義手は上肢がない方が生活に支障のないようするという、人権の面からも最低限必要なものとなってくるものであるため、低コストに抑えることが重要である。そのためには各関節ごとに高価なセンサを搭載することは望ましくない。 === サーボの逆起電力を用いた場合の問題点 既存技術の中で安価なアプローチとしてサーボの逆起電力とエンコーダ等の回転方向を検出するセンサとを組み合わせたセンサレスの手法がある。前節でも紹介した通り、この手法を用いることで、逆起電力を検出する回路以外の追加部品を必要とせず実装できる。また、追加部品が必要ないため取り付け位置に創意工夫の必要性がない。\ しかし決定的な弱点が存在する。モータの特性上、逆起電力を得るにはシャフトの回転が必要な点である。実際の力覚を測定する際、モータを回転させるには弱すぎる力が付与される場合も多く存在する。しかし、そのような場合でもこのセンサレスの手法ではかかっている力覚は0として判断されてしまう。これでは実際の生体のように、外力に耐えている状態でも筋肉の負荷を感じ取ることで外力の大きさを大凡認知することは叶わない。 == サーボの消費電力を用いる方法 前節では力覚センサの搭載や、サーボの逆起電力を用いた、場合の欠点を紹介した。筋電義手の力覚を測定するためにはこれらの方法では実用性に欠ける部分があることがわかった。これらの方法より簡便かつ静止時の計測も可能な手法が望ましいわけであるが、ここで我々は他の研究テーマでのトラブルに着目した。 #heading("過負荷によるサーボの故障", numbering: none, level: 3, outlined: false) 同じ研究室内の別の研究グループでサーボの故障が何度か発生した。そのグループではロボットを使用していたのだが、ロボットの足を為すサーボに過負荷がかかり電流制御用のトランジスタが焼き切れてしまうことが原因だった。サーボは与えられたPWM信号に対応する回転角度(目標角度)と現在の回転角度とにずれがある場合に目標角度となるように回転する性質がある。目標角度まで回転する際に外力により回転にブレーキがかかる際はそれに負けじと供給電流を増やすことで動こうとする。しかしその際に内部の電子回路の許容電流を超えてしまい破損することがあった。我々はこの現象に着目をして、サーボにかかる外力を消費電力を用いて検出する手法を考案した。 #pagebreak(weak: true) = 筋電義手の駆動部エネルギー測定について 筋電義手の稼働部を為すサーボの消費電力を測定することで、義手にかかる力覚を測定できるというコンセプトの実証を行った。今回は簡単のために筋電義手を用いるのではなく、実験用のロボットアームを用いた。 === 実験器具 以下に今回の実験で使用した実験器具を表記する - ロボットアーム:近藤科学株式会社 KXR-A5 - マイコン:Arduino Uno - シャント抵抗:1Ω - 差動増幅回路 - オペアンプ:Texas Instrument TLC-2274 - 抵抗1: 1kΩ - 抵抗2: 2kΩ - 分銅: 50g, 100g == 実験方法 #figure(image("assets/実験器具構成図.png"), kind: image, caption: text("実験器具構成図")) #pagebreak() 上図のように筋電義手を模したロボットアームのサーボの3つを使い、それぞれの消費電力を電流を計測することで測定した。各サーボの消費電力は、サーボの電源ラインに直列にシャント抵抗を接続し、その抵抗の始端と終端の電圧を差動増幅回路を用いることでマイコンにアナログ情報として取り入れられるようにした。\ 計測に用いたマイコンは、各サーボの動作を指令するマイコンと同一のものを用いることでサーボの動作開始とほとんど同時に計測が開始されるように設計した。ここでサーボの動作開始と計測開始とが完全に同時でないのは、今回使用したマイコンでは同時に一つのスレッドしか実行できないため厳密には数クロック分だけ動作開始と計測開始とがずれてしまうためである。\ === 手順 本研究の実験では二つの動作パターンのデータをロボットアームに付加する負荷を変えながら取得することで動作パターンと重さの関係性を調べやすくした。以下にその手順を示す。 + 負荷をかけない状態で動作1を実行し、その際のシャント抵抗にかかる電圧を358Hzで1秒間計測した。これを8回繰り返した。 + 1と同様のことを、ロボットアームの先端部分に50gの分銅を吊るした状態で実行した。 + 1と同様のことを、ロボットアームの先端部分に100gの分銅を吊るした状態で実行した。 + 動作2で1〜3と同様のことを実行した。 == 実験結果 この実験を行った結果、次の図に示すような消費電力の時系列変化が見られた。 #pagebreak(weak: true) #figure(image("assets/servo_data/motion1_1_servo2_0g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ1の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion1_1_servo2_50g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ1の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion1_1_servo2_100g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ1の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion1_1_servo3_0g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ2の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion1_1_servo3_50g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ2の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion1_1_servo3_100g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ2の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion1_1_servo5_0g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ3の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion1_1_servo5_50g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ3の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion1_1_servo5_100g.png", height: 12em), caption: text("動作1(上昇)の際のサーボ3の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion1_2_servo2_0g.png", height: 12em), caption: text("動作1(下降)の際のサーボ1の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion1_2_servo2_50g.png", height: 12em), caption: text("動作1(下降)の際のサーボ1の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion1_2_servo2_100g.png", height: 12em), caption: text("動作1(下降)の際のサーボ1の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion1_2_servo3_0g.png", height: 12em), caption: text("動作1(下降)の際のサーボ2の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion1_2_servo3_50g.png", height: 12em), caption: text("動作1(下降)の際のサーボ2の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion1_2_servo3_100g.png", height: 12em), caption: text("動作1(下降)の際のサーボ2の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion1_2_servo5_0g.png", height: 12em), caption: text("動作1(下降)の際のサーボ3の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion1_2_servo5_50g.png", height: 12em), caption: text("動作1(下降)の際のサーボ3の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion1_2_servo5_100g.png", height: 12em), caption: text("動作1(下降)の際のサーボ3の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion2_1_servo2_0g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ1の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion2_1_servo2_50g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ1の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion2_1_servo2_100g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ1の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion2_1_servo3_0g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ2の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion2_1_servo3_50g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ2の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion2_1_servo3_100g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ2の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion2_1_servo5_0g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ3の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion2_1_servo5_50g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ3の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion2_1_servo5_100g.png", height: 12em), caption: text("動作2(上昇)の際のサーボ3の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion2_2_servo2_0g.png", height: 12em), caption: text("動作2(下降)の際のサーボ1の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion2_2_servo2_50g.png", height: 12em), caption: text("動作2(下降)の際のサーボ1の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion2_2_servo2_100g.png", height: 12em), caption: text("動作2(下降)の際のサーボ1の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion2_2_servo3_0g.png", height: 12em), caption: text("動作2(下降)の際のサーボ2の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion2_2_servo3_50g.png", height: 12em), caption: text("動作2(下降)の際のサーボ2の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion2_2_servo3_100g.png", height: 12em), caption: text("動作2(下降)の際のサーボ2の消費電力(負荷100g)")) #figure(image("assets/servo_data/motion2_2_servo5_0g.png", height: 12em), caption: text("動作2(下降)の際のサーボ3の消費電力(負荷0g)")) #figure(image("assets/servo_data/motion2_2_servo5_50g.png", height: 12em), caption: text("動作2(下降)の際のサーボ3の消費電力(負荷50g)")) #figure(image("assets/servo_data/motion2_2_servo5_100g.png", height: 12em), caption: text("動作2(下降)の際のサーボ3の消費電力(負荷100g)")) = リザバーコンピューティング 実験で得られた一定の規則性の認められる結果をモデル化することで、入力信号から出力の予測ができるようになる。そのための手法は古くから多く考えられてきたが、計算機の高性能化に伴い近年では機械学習を用いた手法が広く研究されるようになった。機械学習と大きく括ってもそのフレームワークにはいくつもの種類があり、それぞれに得意とする分野が存在する。例えばConvolutional Neural Networkを用いた機械学習は画像解析に適しているが時系列データを扱う場面で採用されることは少ない。同様にTransformerは自然言語処理の分野で今や主流となっているが、画像処理には適さない。\ == 概要 前章での結果でも示したとおり、本研究の学習対象は時系列変化する信号となっている。すると時系列変化する信号の学習に適した手法が必要となってくるわけであるが、これにあたるのがRecursive Neural Network (RNN)を用いた機械学習である。しかし従来型のRNNは推論フェーズと実行フェーズともに多くの計算量を必要とし、さらに学習のために多くのデータ数を必要とすることが知られている。学習はともかく、筋電義手を操作するための計算機の処理能力で推論がリアルタイムで行われることが理想的であるため、従来型のRNNのような多くの計算リソースを必要とするようなモデルを採用することは困難となってしまう。@Reservoir-Computing \ そこで登場するのがリザバーコンピューティング(RC)である。RCはRNNの一種ではあるが、ニューラルネット層の重みづけは行わずに出力層(リードアウト)の重みづけのみを学習させることでモデルの最適化を行う。この手法を用いることで、多くのデータ数がなくとも十分な精度が得られる学習ができることが先行の研究で明らかになっている。我々は今回RCを用いてサーボの消費電力の波形を学習させ、系にかかっている負荷を予測するモデルを作成した。\ RCを用いて得られる結果は == 評価方法 モデルの評価にはRoot Mean Squared Error (RMSE)という指標を用いた。 === RMSE(平方平均二乗誤差) モデル出力と目標出力が共に連続値で与えられる時系列予測タスクや、時系列生成タスクの誤差を評価する指標としてRMSEが広く用いられる。\ $ "RMSE" = sqrt(frac(1,T) sum_(n=1)^T norm(upright(bold(d))(n)-accent(upright(bold(y)), hat)(n) )^2_2) $ と定義される。これはモデル出力と目標出力の間の二乗誤差の時間平均の平方根を表している。目標出力データの特徴を考慮していないので、異なるデータに対するRMSEの値を比較に意味がない点は注意されるべきである。また、RMSEはデータや予測値に平均から大きく外れた異常値や外れ値が含まれていると、その影響を大きく受けやすい。 @Reservoir-Computing #pagebreak(weak: true) = 消費電力から負荷を学習 3章で取得したデータを使ってRCを用いて学習させることで、3つのサーボの消費電力から系にかかる負荷を割り出すモデルを作成した。 また、消費電力のみを与えたところで負荷を予測するモデルを作成したところで汎用性に欠けるという予測のもと、3つのサーボの消費電力の時系列データのほかに特徴量としてそれぞれのサーボの動作開始と動作終了角度、そして設定した回転速度を与えることとした。これらの情報は取得に個別のセンサなどの機構を必要とせずサーボ制御用、すなわちRC推論にも用いるマイコン上で取得可能なデータの中から選んでいる点を強調する。 == データの前処理 RCを用いた学習をするためにはまずデータを学習に使用しやすい形にする必要がある。今回はサーボ3つの消費電力の時系列変化という特徴量に加えて、サーボそれぞれの初期角度、終了角度、そして設定速度を横並びにすることデータをわかりやすくした。また、最後にラベルとして機能する負荷重量を記載することで、プログラム上で教師ラベルとして扱いやすい形にした。プログラム上ではこれを48個のファイルに分け、全データ数を48個とし、そのうち38個を訓練データとして、10個を評価用データとしてして使用している。 #pagebreak(weak: true) #figure(image("assets/前処理データ.png"), caption: text("リザバー学習にをさせる際に用いたデータ構造"), kind: table) #pagebreak(weak: true) == リザバーコンピューティングの各種設定 実はRCにもさまざまな方法が提案されている。Echo State Network (ESN), Liquid State Machine (LSM), FORCEなどが一般的であるが、今回は最もシンプルで実装の簡単なESNを採用することとした。ESNはEcho State Propertyを満たすリザバー層に入力を与え、リードアウトの重みづけを線形回帰を用いて学習させる点から非常にシンプルであるためRCを使用する上で広く使われている。@FORCE === リザバー層 リザバー層には Leaky Integrator によって構成されたニューラルネットを用いた。リーク率は1、リカレント結合重み行列のスペクトル半径は0.95、活性化関数にはハイパボリックタンジェントを用いた。ノード数は特徴量の数よりも十分に大きい100に設定した。 @Intrinsic-Plasticity // ==== 適切なノード数の調査 // リザバー層のノード数は学習の精度とその速度、そして推論フェーズでの速度を決定するため非常に重要なパラメータである。本研究はサーボの消費電力から系にかかっている負荷が推論できるかというコンセプトの実証が本題ではあるが、筋電義手で使用するにあたって十分に少ないノード数で推論できなければ実行スピードがボトルネックとなってしまう。そこで次のような実験を行うことで今回のデータに適切なノード数を調査した。 // ===== 実験方法 // リザバー層のノード数を5から100に変化させた時のRMSEの値を比較した。ただし、48個のデータを8対2の割合で学習用と評価用のデータにランダムに分けてから学習と評価を行うようにしているため、実行ごとに結果が変わってくる。この変化を鑑みて比較するためにそれぞれのノード数で1000回の学習と評価を行い、そのRMSEの平均をとった。このRMSEの平均とリザバー層のノード数との関係が次の図の通りである。 // ===== 実験結果 // #figure(image("assets/node_vs_rmse.png"), caption: text("RMSEの平均のノード数との依存関係")) // #pagebreak(weak: true) // 48個のデータを8対2の割合で分けているため学習用のデータは38個である。この図から見て取れる通り、ノード数が38個に近づくにつれてRMSEが急激に増加しており、そこから離れるにつれて減っていることがわかった。この現象はdouble descentと呼ばれている。 @double-descent // ===== 考察 // この実験から、設定すべきノード数は学習用データのデータ長よりも大きくすることがRC学習には適していることがわかった。 === リードアウト層 次にリードアウト層の重みづけの学習方法について説明する。今回はESNを用いるため線形回帰での重みづけ学習を行ったのだが、外れ値の影響を必要以上に大きくすることを避けるためにRidge回帰を用いた。正則化パラメータは $1.0 times 10^(-3)$に設定した。 @Ridge == 学習結果 以下がこの学習を行った結果である。 #figure(align(left, (image("assets/training_set_predictions_rmse_36.05610294846806.png", width: 180%))), caption: text("推論モデルで学習データセットの予測をさせた結果")) #pagebreak(weak: true) #figure(align(left, (image("assets/test_set_predictions_rmse_30.560928118691546.png", width: 180%))), caption: text("推論モデルで評価データセットの予測をさせた結果")) #pagebreak(weak: true) == 考察 学習用データを用いての評価並びに評価用データを用いての推論のRMSEはどちらも30を超えるものとなった。また、両者において予測値と実際の値の差が大きいことが見て取れる。これは学習手法自体が不十分なものであることが原因と考えられる。一番の特筆すべき点としては重量なしの学習データと重量50g、そして100gのデータとではデータの数は同じであるにもかかわらず、推論の結果0g付近をほとんど予測できていない点である。これは学習手法に誤りがあったことを示していると考えられる。 #pagebreak(weak: true) = まとめ 筋電義手の操作性向上に必要となってくる力覚の検知を行う方法として、義手内に搭載されることの多いサーボの消費電力を用いる手法の妥当性について検討した。筋電義手におけるサーボというのは生体における筋肉のように、位置を移動させる能力を持ちながら外力が加えられた際にその大きさに対応する反応を示す。その類似性は日頃の感覚としては誰しもが気づく余地あるものではある。本研究を通してこの類似性を示すことができるか確認のための実験を重ねたが、有意な類似性を示すには至らなかった。\ しかし現時点で手法自体が間違っていると結論づけることはできない。データの与え方やリザバーコンピューティングの実装や設定の推敲を重ねることで、本来行いたかった実験の結果を得られる可能性は大いに残っていると考えられる。 #set heading(numbering: none) = 謝辞 本研究を進めるにあたり、多大なご指導、ご助言を頂いた葛西誠也教授をはじめとする工学部情報エレクトロニクス学科量子知能デバイス研究室の構成員の皆様に深謝の意を表します。常に楽をしようと堕落の方向へ向かう私に妥協を許さず研鑽の日々を促して下さった葛西教授はもちろん、ご自身が修士論文研究や学会発表、就職活動等でお忙しいにも関わらず進んで研究内容や発表資料の校閲、的確な助言をくださった修士2年吉田聖氏、修士1年松田一希氏に深謝の意を表します。また、日頃からご指導、ご意見を頂いた、量子集積エレクトロニクス研究センター長であられる本久順一教授、先進ナノ電子材料研究室の石川史太郎教授、原真二郎准教授、量子知能デバイス研究室の佐藤威友准教授、機能通信センシング研究室の池辺将之教授、赤澤正道准教授、集積電子デバイス研究室の冨岡克広准教授に深く感謝致します。 #heading(numbering: none, text("Appendix")) 以下にRCで学習を行った際に用いたコードを示す。 ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import japanize_matplotlib from sklearn.model_selection import train_test_split import model BASE_PATH: str = "data/" file_011_name: str = "0g_1_1.csv" file_012_name: str = "0g_1_2.csv" file_013_name: str = "0g_1_3.csv" file_014_name: str = "0g_1_4.csv" file_015_name: str = "0g_1_5.csv" file_016_name: str = "0g_1_6.csv" file_017_name: str = "0g_1_7.csv" file_018_name: str = "0g_1_8.csv" file_021_name: str = "0g_2_1.csv" file_022_name: str = "0g_2_2.csv" file_023_name: str = "0g_2_3.csv" file_024_name: str = "0g_2_4.csv" file_025_name: str = "0g_2_5.csv" file_026_name: str = "0g_2_6.csv" file_027_name: str = "0g_2_7.csv" file_028_name: str = "0g_2_8.csv" file_5011_name: str = "50g_1_1.csv" file_5012_name: str = "50g_1_2.csv" file_5013_name: str = "50g_1_3.csv" file_5014_name: str = "50g_1_4.csv" file_5015_name: str = "50g_1_5.csv" file_5016_name: str = "50g_1_6.csv" file_5017_name: str = "50g_1_7.csv" file_5018_name: str = "50g_1_8.csv" file_5021_name: str = "50g_2_1.csv" file_5022_name: str = "50g_2_2.csv" file_5023_name: str = "50g_2_3.csv" file_5024_name: str = "50g_2_4.csv" file_5025_name: str = "50g_2_5.csv" file_5026_name: str = "50g_2_6.csv" file_5027_name: str = "50g_2_7.csv" file_5028_name: str = "50g_2_8.csv" file_10011_name: str = "100g_1_1.csv" file_10012_name: str = "100g_1_2.csv" file_10013_name: str = "100g_1_3.csv" file_10014_name: str = "100g_1_4.csv" file_10015_name: str = "100g_1_5.csv" file_10016_name: str = "100g_1_6.csv" file_10017_name: str = "100g_1_7.csv" file_10018_name: str = "100g_1_8.csv" file_10021_name: str = "100g_2_1.csv" file_10022_name: str = "100g_2_2.csv" file_10023_name: str = "100g_2_3.csv" file_10024_name: str = "100g_2_4.csv" file_10025_name: str = "100g_2_5.csv" file_10026_name: str = "100g_2_6.csv" file_10027_name: str = "100g_2_7.csv" file_10028_name: str = "100g_2_8.csv" def convert_data_frames_to_numpys( data_frames: list[pd.DataFrame], ) -> np.ndarray[np.float64]: # あらかじめ空のリストを作成しておく new_data = np.empty( (len(data_frames), data_frames[0].columns.size, data_frames[0].shape[0]), dtype=np.float64, ) for i in range(len(data_frames)): for j in range(data_frames[i].columns.size): new_data[i][j] = data_frames[i][j].values return new_data def get_merged_matrix( list_of_files: list[str], ) -> tuple[np.ndarray[np.float64], np.ndarray[np.float64]]: data_frames = [ pd.read_csv(BASE_PATH + file, header=None, skiprows=1) for file in list_of_files ] training_frames, testing_frames = train_test_split(data_frames, test_size=0.2) train_data_set = convert_data_frames_to_numpys(training_frames) test_data_set = convert_data_frames_to_numpys(testing_frames) return train_data_set, test_data_set train_data, test_data = get_merged_matrix( [ file_011_name, file_012_name, file_013_name, file_014_name, file_015_name, file_016_name, file_017_name, file_018_name, file_021_name, file_022_name, file_023_name, file_024_name, file_025_name, file_026_name, file_027_name, file_028_name, file_5011_name, file_5012_name, file_5013_name, file_5014_name, file_5015_name, file_5016_name, file_5017_name, file_5018_name, file_5021_name, file_5022_name, file_5023_name, file_5024_name, file_5025_name, file_5026_name, file_5027_name, file_5028_name, file_10011_name, file_10012_name, file_10013_name, file_10014_name, file_10015_name, file_10016_name, file_10017_name, file_10018_name, file_10021_name, file_10022_name, file_10023_name, file_10024_name, file_10025_name, file_10026_name, file_10027_name, file_10028_name, ] ) # Extract the load data from the training set. the last arrays of every set are the repeated load data. pick the first one of the last arrays and make it the load data train_load: np.ndarray[np.float64] = np.array( [train_data[i][-1][0] for i in range(len(train_data))], dtype=np.float64 ) test_load: np.ndarray[np.float64] = np.array( [test_data[i][-1][0] for i in range(len(test_data))], dtype=np.float64 ) # erase the last arrays of every set to make the training data does not include load data at the end # and transpose the data to make it compatible with the ESN model train_data = train_data[:, :-1, :].transpose(0, 2, 1) test_data = test_data[:, :-1, :].transpose(0, 2, 1) # Reshape the load data to make it compatible with the RMSE calculation that is for example, (38,) to (38,358) train_load_reshaped = np.tile(train_load, (train_data.shape[1], 1)).T.reshape(-1, 1) test_load_reshaped = np.tile(test_load, (test_data.shape[1], 1)).T.reshape(-1, 1) # Initialize the ESN model input_size = train_data.shape[1] # Number of data points in each sample reservoir_size = 100 # Size of the reservoir output_size = 1 # Predicting a single value (Load) esn = model.ESN(N_u=input_size, N_y=output_size, N_x=reservoir_size) # Train the ESN model esn.train( train_data, train_load, model.Tikhonov(N_x=reservoir_size, N_y=output_size, beta=1e-3), ) # Predict using the trained model (for demonstration, use the training data itself) train_predictions: np.ndarray[float] = esn.predict(train_data) # Evaluate the model by computing the mean squared error on the training data train_rmse: float = np.sqrt(((train_predictions - train_load_reshaped) ** 2).mean()) # Predict using the trained model test_predictions: np.ndarray[float] = esn.predict(test_data) # Evaluate the model by computing the mean squared error on the training data test_rmse: float = np.sqrt(((test_predictions - test_load_reshaped) ** 2).mean()) print("Training RMSE: ", train_rmse) flattened_predictions = test_predictions.flatten() plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.scatter( x=range(len(train_load_reshaped)), y=train_load_reshaped, label="実際の質量", alpha=0.6 ) plt.scatter( x=range(len(train_predictions)), y=train_predictions, label="推論値", alpha=0.6 ) plt.title("学習データセットでの推論") plt.xlabel("試行") plt.ylabel("負荷質量・推論値 (g)") plt.legend() plt.tight_layout() plt.savefig(f'saved_graphs/training_set_predictions_rmse_{train_rmse}.png') plt.show() print("Test RMSE: ", test_rmse) plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.scatter( x=range(len(test_load_reshaped)), y=test_load_reshaped, label="実際の質量", alpha=0.6 ) plt.scatter( x=range(len(test_predictions)), y=test_predictions, label="推論値", alpha=0.6 ) plt.title("テストデータセットでの推論") plt.xlabel("試行") plt.ylabel("負荷質量・推論値 (g)") plt.legend() plt.tight_layout() plt.savefig(f'saved_graphs/test_set_predictions_rmse_{test_rmse}.png') plt.show() ``` #pagebreak() 以下にリザバーコンピューティングのモデルを示す。ただし、これは田中,中根,廣瀬(著)「リザバーコンピューティング」(森北出版)内に記載されているコードを一部改変したものであり、本ソースコードの著作権は田中剛平先生に帰属することを明記しておく。 ```python import numpy as np import networkx as nx # 恒等写像 def identity(x): return x # リザバー class Reservoir: # リカレント結合重み行列Wの初期化 def __init__(self, N_x, density, rho, activation_func, leaking_rate, seed=0): """ param N_x: リザバーのノード数 param density: ネットワークの結合密度 param rho: リカレント結合重み行列のスペクトル半径 param activation_func: ノードの活性化関数 param leaking_rate: leaky integratorモデルのリーク率 param seed: 乱数の種 """ self.seed = seed self.W = self.make_connection(N_x, density, rho) self.x = np.zeros(N_x) # リザバー状態ベクトルの初期化 self.activation_func = activation_func self.alpha = leaking_rate # リカレント結合重み行列の生成 def make_connection(self, N_x, density, rho): # Erdos-Renyiランダムグラフ m = int(N_x * (N_x - 1) * density / 2) # 総結合数 G = nx.gnm_random_graph(N_x, m, self.seed) # 行列への変換(結合構造のみ) connection = nx.DiGraph(G) W = np.array(connection) # 非ゼロ要素を一様分布に従う乱数として生成 rec_scale = 1.0 np.random.seed(seed=self.seed) W = W * np.random.uniform(-rec_scale, rec_scale, (N_x, N_x)) # スペクトル半径の計算 eigv_list = np.linalg.eig(W)[0] sp_radius = np.max(np.abs(eigv_list)) # 指定のスペクトル半径rhoに合わせてスケーリング W *= rho / sp_radius return W # リザバー状態ベクトルの更新 def __call__(self, x_in: np.ndarray): """ param x_in: 更新前の状態ベクトル return: 更新後の状態ベクトル """ # self.x = self.x.reshape(-1, 1) self.x = (1.0 - self.alpha) * self.x + self.alpha * self.activation_func( np.dot(self.W, self.x) + x_in # self.x は reservoir のノード数 (N_x) の次元を持つベクトルなので、np.dot(self.W, self.x) は必ず (N_x,) のベクトルになる。 ) return self.x # リザバー状態ベクトルの初期化 def reset_reservoir_state(self): self.x *= 0.0 # 出力層 class Output: # 出力結合重み行列の初期化 def __init__(self, N_x, N_y, seed=0): """ param N_x: リザバーのノード数 param N_y: 出力次元 param seed: 乱数の種 """ # 正規分布に従う乱数 np.random.seed(seed=seed) self.Wout = np.random.normal(size=(N_y, N_x)) # 出力結合重み行列による重みづけ def __call__(self, x): """ param x: N_x次元のベクトル return: N_y次元のベクトル """ return np.dot(self.Wout, x) # 学習済みの出力結合重み行列を設定 def setweight(self, Wout_opt): self.Wout = Wout_opt # 出力フィードバック class Feedback: # フィードバック結合重み行列の初期化 def __init__(self, N_y, N_x, fb_scale, seed=0): """ param N_y: 出力次元 param N_x: リザバーのノード数 param fb_scale: フィードバックスケーリング param seed: 乱数の種 """ # 一様分布に従う乱数 np.random.seed(seed=seed) self.Wfb = np.random.uniform(-fb_scale, fb_scale, (N_x, N_y)) # フィードバック結合重み行列による重みづけ def __call__(self, y): """ param y: N_y次元のベクトル return: N_x次元のベクトル """ return np.dot(self.Wfb, y) # リッジ回帰(beta=0のときは線形回帰) class Tikhonov: def __init__(self, N_x, N_y, beta): """ param N_x: リザバーのノード数 param N_y: 出力次元 param beta: 正則化パラメータ """ self.beta = beta self.X_XT = np.zeros((N_x, N_x)) self.D_XT = np.zeros((N_y, N_x)) self.N_x = N_x # 学習用の行列の更新 def __call__(self, d, x): d = np.reshape(d, (-1, 1)) x = np.reshape(x, (-1, 1)) self.X_XT = self.X_XT + np.dot(x, x.T) self.D_XT = self.D_XT + np.dot(d, x.T) # Woutの最適解(近似解)の導出 def get_Wout_opt(self): X_pseudo_inv = np.linalg.inv(self.X_XT + self.beta * np.identity(self.N_x)) Wout_opt = np.dot(self.D_XT, X_pseudo_inv) return Wout_opt # 逐次最小二乗(RLS)法 class RLS: def __init__(self, N_x, N_y, delta, lam, update): """ param N_x: リザバーのノード数 param N_y: 出力次元 param delta: 行列Pの初期条件の係数(P=delta*I, 0<delta<<1) param lam: 忘却係数 (0<lam<1, 1に近い値) param update: 各時刻での更新繰り返し回数 """ self.delta = delta self.lam = lam self.update = update self.P = (1.0 / self.delta) * np.eye(N_x, N_x) self.Wout = np.zeros([N_y, N_x]) # Woutの更新 def __call__(self, d, x): x = np.reshape(x, (-1, 1)) for i in np.arange(self.update): v = d - np.dot(self.Wout, x) gain = 1 / self.lam * np.dot(self.P, x) gain = gain / (1 + 1 / self.lam * np.dot(np.dot(x.T, self.P), x)) self.P = 1 / self.lam * (self.P - np.dot(np.dot(gain, x.T), self.P)) self.Wout += np.dot(v, gain.T) return self.Wout # エコーステートネットワーク class ESN: # 各層の初期化 def __init__( self, N_u, N_y, N_x, density=0.05, input_scale=1.0, rho=0.95, activation_func=np.tanh, fb_scale=None, fb_seed=0, noise_level=None, leaking_rate=1.0, output_func=identity, inv_output_func=identity, classification=False, average_window=None, ): """ param N_u: 入力次元 param N_y: 出力次元 param N_x: リザバーのノード数 param density: リザバーのネットワーク結合密度 param input_scale: 入力スケーリング param rho: リカレント結合重み行列のスペクトル半径 param activation_func: リザバーノードの活性化関数 param fb_scale: フィードバックスケーリング(default: None) param fb_seed: フィードバック結合重み行列生成に使う乱数の種 param leaking_rate: leaky integratorモデルのリーク率 param output_func: 出力層の非線形関数(default: 恒等写像) param inv_output_func: output_funcの逆関数 param classification: 分類問題の場合はTrue(default: False) param average_window: 分類問題で出力平均する窓幅(default: None) """ # self.Input = Input(N_u, N_x, input_scale) self.Reservoir = Reservoir(N_x, density, rho, activation_func, leaking_rate) self.Output = Output(N_x, N_y) self.N_u = N_u self.N_y = N_y self.N_x = N_x self.y_prev = np.zeros(N_y) self.output_func = output_func self.inv_output_func = inv_output_func self.classification = classification # 出力層からのリザバーへのフィードバックの有無 if fb_scale is None: self.Feedback = None else: self.Feedback = Feedback(N_y, N_x, fb_scale, fb_seed) # リザバーの状態更新おけるノイズの有無 if noise_level is None: self.noise = None else: np.random.seed(seed=0) self.noise = np.random.uniform(-noise_level, noise_level, (self.N_x, 1)) # 分類問題か否か if classification: if average_window is None: raise ValueError("Window for time average is not given!") else: self.window = np.zeros((average_window, N_x)) # バッチ学習 def train(self, U, D, optimizer, trans_len=None): """ U: 教師データの入力, データ長×N_u D: 教師データの出力, データ長×N_y optimizer: 学習器 trans_len: 過渡期の長さ return: 学習前のモデル出力, データ長×N_y """ train_len = len(U) if trans_len is None: trans_len = 0 Y = [] # 時間発展 for n in range(train_len): for m in range(len(U[1])): # データ数だけループさせる # x_in = self.Input(U[n]) # TODO: x_in の大きさ > リザバーのノード数(N_x) の場合の処理を追加する x_in = np.zeros(self.N_x) x_temp = U[n][m] x_in[: len(U[n][m])] = x_temp # フィードバック結合 if self.Feedback is not None: x_back = self.Feedback(self.y_prev) x_in = x_in + x_back # ノイズ if self.noise is not None: x_in += self.noise # リザバー状態ベクトル x = self.Reservoir(x_in) # 分類問題の場合は窓幅分の平均を取得 if self.classification: self.window = np.append(self.window, x.reshape(1, -1), axis=0) self.window = np.delete(self.window, 0, 0) x = np.average(self.window, axis=0) # 目標値 d = D[n] d = self.inv_output_func(d) # 学習器 if n > trans_len: # 過渡期を過ぎたら optimizer(d, x) # 学習前のモデル出力 y = self.Output(x) Y.append(self.output_func(y)) self.y_prev = d # 学習済みの出力結合重み行列を設定 self.Output.setweight(optimizer.get_Wout_opt()) # モデル出力(学習前) return np.array(Y) # バッチ学習後の予測 def predict(self, U): test_len = len(U) Y_pred = [] # 時間発展 for n in range(test_len): for m in range(len(U[1])): # データ数だけループさせる # x_in = self.Input(U[n]) # TODO: x_in の大きさ > リザバーのノード数(N_x) の場合の処理を追加する x_in = np.zeros(self.N_x) x_temp = U[n][m] x_in[: len(U[n][m])] = x_temp # フィードバック結合 if self.Feedback is not None: x_back = self.Feedback(self.y_prev) x_in += x_back # リザバー状態ベクトル x = self.Reservoir(x_in) # 分類問題の場合は窓幅分の平均を取得 if self.classification: self.window = np.append(self.window, x.reshape(1, -1), axis=0) self.window = np.delete(self.window, 0, 0) x = np.average(self.window, axis=0) # 学習後のモデル出力 y_pred = self.Output(x) Y_pred.append(self.output_func(y_pred)) self.y_prev = y_pred # モデル出力(学習後) return np.array(Y_pred) ``` #[ #set text(lang: "en") #bibliography("bibliography/bib.yaml", title: text(bibliographyTitleJa), style: "institute-of-electrical-and-electronics-engineers") ]
https://github.com/HPDell/typst-slides-uob
https://raw.githubusercontent.com/HPDell/typst-slides-uob/main/README.md
markdown
# Slides with Theme University of Bristol in Typst This is a template for creating slides with the theme of the University of Bristol in Typst. ## Functions ```typ #let slides( title: "", authors: (), date: datetime.today(), short-title: "", body ) ``` This function changes page, text and layout settings to prepare for slides. ```typ #let slide(body, subtitle: []) ``` This function creates a slide and can append a subtitle after its title. Its title is specified in the nearest former level-3 headings, i.e., headings of marker `===`. ```typ #let empty(content) ``` This function creates an empty slide. ```typ #let leaflet(content, title: []) ``` This function creates a block area with a header and body, which looks like the `\block{}` command in Beamer. As the name `block` has been taken by Typst itself, it is named to `leaflet` instead. ## Syntax Maps Headings are translated into specific parts: - The level-1 and level-2 headings are mapped to the section page and the subsection page. - The level-3 headings are stored as slide titles and hidden. They only show up once the `#slide` is called to create a new slide. ## Example [![](example.jpg)](./example.pdf)
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/heading.typ
typst
// Test headings. --- heading-basic --- // Different number of equals signs. = Level 1 == Level 2 === Level 3 // After three, it stops shrinking. =========== Level 11 --- heading-syntax-at-start --- // Heading vs. no heading. // Parsed as headings if at start of the context. /**/ = Level 1 #[== Level 2] #box[=== Level 3] // Not at the start of the context. No = heading // Escaped. \= No heading --- heading-block --- // Blocks can continue the heading. = #[This is multiline. ] = This is not. --- heading-show-where --- // Test styling. #show heading.where(level: 5): it => block( text(font: "Roboto", fill: eastern, it.body + [!]) ) = Heading ===== Heading 🌍 #heading(level: 5)[Heading] --- heading-offset --- // Test setting the starting offset. #set heading(numbering: "1.1") #show heading.where(level: 2): set text(blue) = Level 1 #heading(depth: 1)[We're twins] #heading(level: 1)[We're twins] == Real level 2 #set heading(offset: 1) = Fake level 2 == Fake level 3 --- heading-offset-and-level --- // Passing level directly still overrides all other set values #set heading(numbering: "1.1", offset: 1) #heading(level: 1)[Still level 1] --- heading-syntax-edge-cases --- // Edge cases. #set heading(numbering: "1.") = Not in heading =Nope --- heading-numbering-hint --- = Heading <intro> // Error: 1:19-1:25 cannot reference heading without numbering // Hint: 1:19-1:25 you can enable heading numbering with `#set heading(numbering: "1.")` Cannot be used as @intro
https://github.com/sses7757/sustech-graduated-thesis
https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/test-eq.typ
typst
Apache License 2.0
#import "sustech-graduated-thesis/utils/multi-line-equate.typ": equate, equate-ref #set text(lang: "en") #set heading(numbering: "1.1") #show heading: it => { counter(math.equation).update(0) it } #show math.equation: equate.with(debug: true) #show ref: equate-ref #set math.equation(numbering: "(1.1.a)") = Heading #context counter(math.equation).get() Simple $ O(n/t) = 1 $ <-> #context counter(math.equation).get() Simple 2 $ O(n/t) = 1 $ <simple2> #context counter(math.equation).get() @eqt:simple2 Test $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). #<test2> $ <test> #context counter(math.equation).get() @eqt:test, @eqt:test-test2 Test no label $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). $ <-> #context counter(math.equation).get() $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). #<specific> $ <-> #context counter(math.equation).get() @eqt:specific $ F_n &= P(n) #<new1> \ &= floor(1 / sqrt(5) phi.alt^n). #<new2> $ <-> #context counter(math.equation).get() @eqt:new1, @eqt:new2 #pagebreak() = Heading #context counter(math.equation).get() Simple $ O(n/t) = 1 $ <-> #context counter(math.equation).get() Simple 2 $ O(n/t) = 1 $ <2-simple2> #context counter(math.equation).get() @eqt:2-simple2 Test $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). #<test2> $ <2-test> #context counter(math.equation).get() @eqt:2-test, @eqt:2-test-test2 Test no label $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). $ <-> #context counter(math.equation).get() $ F_n &= P(n) #<2-specific> \ &= floor(1 / sqrt(5) phi.alt^n). $ <-> #context counter(math.equation).get() @eqt:2-specific $ F_n &= P(n) #<2-new1> \ &= floor(1 / sqrt(5) phi.alt^n). #<2-new2> $ <-> #context counter(math.equation).get() @eqt:2-new1, @eqt:2-new2
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/基础/array/array.typ
typst
#set par( justify: true, leading: 0.52em, ) = array = #image("1.png", width: 100%) #image("2.png") #image("3.png") #image("4.png") #image("5.png") #image("6.png") #image("7.png") #image("8.png") #image("9.png") #image("10.png") #image("11.png") #image("12.png") #image("13.png")