repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/open-datakit/accs-finalreport-whitepaper
https://raw.githubusercontent.com/open-datakit/accs-finalreport-whitepaper/main/2-accs/content.typ
typst
= Activities for _Australian Characterisation Commons at Scale_ project == Deliverables === _WP6.1.1_ Create a small angle scattering (SAS) analysis pipeline === _WP6.1.2_ Configuration of cloud infrastructure === _WP6.1.3_ Improving the user-interface to the SAS analysis pipeline === _WP6.2.1_ Create an integrated data flow from small angle instruments === _WP6.2.3_ Work cooperatively to establish the relevant metadata standards === _WP6.4.1_ Integration of older opendata.fit workflows === _WP6.4.2_ Creating new workflows on chemical kinetics from NMR data === _WP6.7_ Globus Integration === _WP6.8.1_ Create content and deploy user-facing documentation hub === _WP6.8.2_ Deploy community forum === _WP6.8.3_ Run community engagement workshops == The opendata.fit datapackage profile == Open source outcomes
https://github.com/MaharshiAJ/Resume-Template
https://raw.githubusercontent.com/MaharshiAJ/Resume-Template/main/main.typ
typst
#import "template.typ": * #let resume = json("resume.json") #show: { header( name: resume.name, email: resume.email, linkedinUrl: resume.linkedin ) education( schools: resume.education ) experience( roles: { resume.experience } ) skills( skills: resume.skills ) }
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/template/1er%20exam.typ
typst
MIT License
#import "@preview/g-exam:0.4.0": g-exam, g-question, g-subquestion #show: g-exam.with( school: ( name: "<NAME>", logo: image("./logo.png") ), exam-info: ( academic-period: "Academic year 2023/2024", academic-level: "1st Secondary Education", academic-subject: "Mathematics", number: "2nd Assessment 1st Exam", content: "Proofs", model: "Model A" ), language: "en", decimal-separator: ",", show-grade-table: true, question-points-position: left, clarifications: "Answer the questions in the spaces provided. If you run out of room for an answer, continue on the back of the page." ) #g-question[Given the equation $x^n + y^n = z^n$ for $(x,y,z)$ and $n$ positive integers.] #g-subquestion(points:2)[For what values of $n$ is the statement in the previous question true?] #v(1fr) #g-subquestion(points:3)[For $n=2$ there's a theorem with a special name. What's that name?] #v(1fr) #g-subquestion[What famous mathematician had an elegant proof for this theorem but there was not enough space in the margin to write it down?]. #v(1fr) #g-question(points:5)[Prove that the real part of all non-trivial zeros of the function $zeta(z) "is" 1/2$]. #v(1fr)
https://github.com/Axot017/CV
https://raw.githubusercontent.com/Axot017/CV/master/modules_en/education.typ
typst
#import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry, hBar #let metadata = toml("../metadata.toml") #let cvSection = cvSection.with(metadata: metadata) #let cvEntry = cvEntry.with(metadata: metadata) #cvSection("Education") #cvEntry( title: [Bachelor of Engineering in Computer Science], society: [Silesian University of Technology in Gliwice], date: [2017 - 2021], location: [Poland], description: list(), )
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week1.typ
typst
#import "../../utils.typ": * #section("Distributed Systems Repetition") - Reasons for distributed systems - scaling Moores law can't go forever with big amounts of performance increases,\ hence we need horizontal scaling -> more servers in order to properly scale - location When you want to access a service from japan, you don't want to talk to a japanese server as the ping is atrocious.\ Instead, you talk to a server that is closer to you, e.g. Europe. - Categories of distributed systems #columns( 2, [ - #text(red, size: 15pt)[controlled distributed systems] - 1 responsible organization - low churn (rate of joining and leaving in a system (ex. adding or removing servers)) - examples: client/server systems, amazon dynamodb - relatively friendly environment (not too many bad actors expected) - high availability - can be homogeneous or heterogeneous - mechanisms that work well: - Master nodes, central coordinator - consistent hashing: Dynamodb, Cassandra - Network is under control or client/server, no NAT issues - Consistency - leader election (Zookeeper, Paxos, Raft) - Replication principles - more replicas: higher availability, higher reliability, higher performance, better scalability - requires maintaining consistency in replicas - transparency principles apply - #text(red, size: 15pt)[fully decentralized systems] - N responsible organizations - high churn - examples: blockchain, torrents - hostile environment - unpredictable availability - heterogeneous - mechanisms that work well: - consistent hashing: DHTs - flooding/broadcasting - Bitcoin - NAT connection problems - Consistency - weak consistency: DHTs - Nakamo Consensus ( Proof of Work ) - Proof of Stake - leadership election, PBFT protocols - experts unsure - replication principles apply - transparency principles apply ], ) #subsection("Comparison to Blockchain") In blockchain we are working with _loosely coupled_ systems that are _heterogeneous_, _decentralized_ and _large-scale systems_.\ This is the second category above.\ #subsection("Monorepo vs Polyrepo") #columns(2, [ #text(red, size: 15pt)[MonoRepo] - tight coupling of projects - code can easily be reused - everyone sees all code / commits - encourages code sharing within organization - scaling: large repos, specialized tooling (rather bad) #colbreak() #text(red, size: 15pt)[PolyRepo] - loose coupling - API etc. to access other projects, needs to be updated on both sides - fine-grained access control - encourages code sharing _across_ organizations - scaling: many projects, special coordination ]) #subsection("0RTT Connection") Sends params directly with connection in order to avoid handshakes -> already confirmed to be authentic. #align( center, [#image("../../Screenshots/2023_09_18_02_40_35.png", width: 70%)], ) #align( center, [#image("../../Screenshots/2023_09_18_02_41_36.png", width: 70%)], ) #section("Blockchain Introduction") #subsection("Bitcoin") - fully peer-2-peer - maximum bitcoin is set to 21million BTC - every transaction broadcasted to all peers - smallest unit it 0.00000001 BTC (1 Satoshi) - proof of work -> no double spending - initiator is unknown -> has a nickname, called <NAME> - *weak anonymity* (pseudonimity), unlike _Monero_ or others - all peers know transactions - clustering: e.g. if a transaction has multiple input addresses, assume those addresses belong to the same wallet - decentralized, not controlled by a single entity - development community, no central bank, open source #subsection("Wallets") - public key is the wallet key (ECDSA 256 bit) - can be simplified with base58 encoding - private key is the signing key for transactions #subsection("Transaction") - situation: Peer A wants to send BTC to peer B -> creates transaction message - Transaction contains input/output - where BTC came from and where it goes - Peer A broadcasts the transaction to all the peers in the network - transaction is stored in blocks -> block is created / verified (takes around 10min) - this is where the name blockchain comes from #align( center, [#image("../../Screenshots/2023_09_25_01_39_47.png", width: 70%)], ) #subsection("Bitcoin scripting language") #align( center, [#image("../../Screenshots/2023_09_25_01_41_04.png", width: 100%)], ) #text( teal, )[Note, bitcoin does not support a turing complete language, this means every bitcoin program will halt.] #subsubsection("Crypto Puzzles") #align( center, [#image("../../Screenshots/2023_09_25_01_42_44.png", width: 70%)], ) - Solved puzzles are included in transaction block - creation of block is called mining -> uses specialized hardware these days - each block has pointer to previous #align( center, [#image("../../Screenshots/2023_09_25_01_45_56.png", width: 70%)], ) #text( red, )[Miner needs to change the *nonce* until the has over the entire section start with a *certain amount of 0s*] #section("51% attack") If you have 51% of the cpu power or stacking pool, you can start to manipulate transactions in the blockchain.\ As long as *"honest chain"* is the largest, it will outcompete the other, therefore removing the issue.\ The problem in summary:\ If you have 51% control, you can potentially change a transaction, but then continue delivering all other transactions as normal.\ If you provide these blocks of transactions faster than the rest of the entire blockchain, this means that the proper unchanged chain will be ignored and eventually dropped due to your broadcasts.\ #align( center, [#image("../../Screenshots/2023_09_25_01_54_30.png", width: 70%)], ) This attack is called *double spending*.\ #text( teal, )[It is called double spending since the original transaction is also considered to be valid for this account, therefore, both transactions are considered until a certain point where your fraudulent chain is considered to be the only proper one. The deletion of old blocks is then called *chain reordering*]
https://github.com/FrightenedFoxCN/cetz-cd
https://raw.githubusercontent.com/FrightenedFoxCN/cetz-cd/main/src/precheck.typ
typst
#import "utils.typ": * // First Rendering of the placed here, mainly to get all the width & height data for all the labels // All these are useless due to content type limitation!!! // get the size for an item. Converted to a binary array for convenience #let get-item-size(item) = style(styles => { (measure(table.at(line-index).at(item-index), styles).width.cm(), measure(table.at(line-index).at(item-index), styles).height.cm()) }) // get all the sizes of a whole table #let get-all-size(table) = { let size-table = () for line in table { size-table.push( line.map(get-item-size) ) } size-table } // get the should-be center from size table #let get-center-coord(size-table, x-spacing, y-spacing) = { let max-height = find-row-max(size-table, metric: (it => it.last())) let max-width = find-col-max(size-table, metric: (it => it.first())) let x-interval = max-width.len() - 1 let y-interval = max-height.len() - 1 let max-x-coord = total-sum(max-width) + x-spacing * x-interval let max-y-coord = total-sum(max-height) + y-spacing * y-interval let avg-x-split = max-x-coord / x-interval let avg-y-split = max-y-coord / y-interval let center-table = () for i in range(max-height.len()) { let line-center = () for j in range(max-width.len()) { line-center.push((i * avg-x-split, j * avg-y-split)) } center-table.push(line-center) } center-table }
https://github.com/LugsoIn2/typst-htwg-thesis-template
https://raw.githubusercontent.com/LugsoIn2/typst-htwg-thesis-template/main/appendix/appendix_example2.typ
typst
MIT License
#import "../lib/utils.typ": todo = Chapter App Ipsum <appendix_example2> #lorem(50) == Nonumy #lorem(200)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/compiler/README.md
markdown
Apache License 2.0
# typst-ts-web-compiler The compiler can run in browser. See documentation for details: - [Get Started](https://myriad-dreamin.github.io/typst.ts/cookery/get-started.html) - [Compiler interfaces](https://myriad-dreamin.github.io/typst.ts/cookery/guide/compilers.html) It can also runs in node.js, but limits its access to operating system. Therefore, I'd suggest to use [typst.node](https://github.com/Myriad-Dreamin/typst.ts/tree/main/packages/typst.node) for fully accessing to operating system.
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/template/front_matter/resume.typ
typst
MIT License
#import "../../src/book.typ": * #show: chapter.with(title: "Résumé", toc: false) #lorem(500)
https://github.com/typst-jp/typst-jp.github.io
https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/glossary.md
markdown
Apache License 2.0
--- description: | 英語・日本語・中国語対照翻訳用語集 --- # 用語集 以下は翻訳時に使用される英日中対照の用語集です。 | 英語 | 日本語 | 中文 | 備考 | | ------------- | --------------- | ---------------------- | ------------------------------------- | | Typst | Typst | Typst | 翻訳対象のプロジェクト名、訳しません | | typesetting | 組版 | 排版 | Typstの主要機能 | | documentation | ドキュメント | 文档 | | | content | コンテンツ | 内容 / 内容块 | 型の一種で、マークアップによって表される | | styling | スタイル設定 | 样式      | | | set rule | setルール | set 规则 | [スタイル設定]($styling)に出てきます | | show rule | showルール | show 规则 | [スタイル設定]($styling)に出てきます | | markup | マークアップ | 标记 / 标记模式 | Typstのデフォルトモード | | script | スクリプト | 脚本 / 脚本模式 | Typstのスクリプトモード、「#」で始まる行 | | figure | 図表 | 图表 | キャプション付きの図表、`image`ではない |
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-elevation/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator, codetastic #import notebookinator: * #import codetastic: qrcode #import themes.radial.components: * #show: create-body-entry.with( title: "Decide: Elevation", type: "decide", date: datetime(year: 2023, month: 11, day: 3), author: "<NAME>", witness: "Violet Ridge", ) We needed a quick and easy elevation method that we could build in a single meeting. We decided to build a design based off of 229V's Fall Reveal #footnote[ QR code to 229V's reveal video: #align( bottom, qrcode("https://www.youtube.com/watch?v=BGkmDeIMQyQ", size: 3pt), ) ] . This design is completely passive, and attaches to a catapult, which we already have. It consists of two arms that hook onto the elevation bar when the catapult is in the up position.Each arm has a sled on the front of it to pull the robot up when pushed against the bar. #image("./design.svg") All the driver will need to do is deactivate the catapult, and drive as fast as possible into the elevation bar.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/songb/0.1.0/tests/chord.typ
typst
Apache License 2.0
// SPDX-FileCopyrightText: 2024 <NAME> <<EMAIL>> // // SPDX-License-Identifier: CC0-1.0 #import "../chord.typ": chord, chord-display; = First song Alph#chord[Asus4]a#chord[Bb]bet#chord[C\#][ ]space\ #text(weight: "bold")[ Alph#chord[Asus4]a#chord[Bb]bet #chord[C\#][sbace]\ ] Trailing chords#chord[A]#chord[Bm7]#chord[C\#]\ Space #chord[A Bm7 C\#][within] chord#chord[A Bm7 C\#][] #chord[Other] #v(30pt) A#chord[C]mazing #chord[C7]grace How #chord[F]sweet the#chord[C][ ]sound That #chord[C]saved a wretch like #chord[G]me!#chord[G7] I #chord[C]once was #chord[C7]lost, but #chord[F]now am#chord[C] found Was #chord[C]blind, but #chord[G]now I #chord[C]se#chord[F]e#chord[C]\ Was #chord[C]blind, but #chord[G]now I #chord[Cb]se#chord[F]e#chord[C]\ Was #chord[C]blind, but #chord[G]now I #chord[Cb]sei#chord[F]e#chord[C]\ Was #chord[C]blind, but #chord[G]now I #chord[Cb]sii#chord[F]e#chord[C]\ Was #chord[C\#m][b]lind, but #chord[G]now I #chord[Cb]sii#chord[F]e#chord[C]\ #chord-display.update("hide") Was #chord[C\#m][b]lind, but #chord[G]now I #chord[Cb]sii#chord[F]e#chord[C]\ #chord-display.update("") == Line height Dynamic line height:\ More space #chord[G]with a chord\ Less space without #lorem(13) At the en#chord[E]nddddd it may wrap BUG: the word should not split. See below:\ #lorem(13) At the ennddddd it may wrap (without \#chord, the word did not split)\ #lorem(13) At the en#chord[E][nddddd] it may wrap. Partial workaround using additional \[...\]\ #chord[Em]#chord[Am]#chord[Em]\ #chord[Em][]#chord[Am][]#chord[Em][]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/030.%20essay.html.typ
typst
essay.html The Age of the Essay September 2004Remember the essays you had to write in high school? Topic sentence, introductory paragraph, supporting paragraphs, conclusion. The conclusion being, say, that Ahab in <NAME> was a Christ-like figure.Oy. So I'm going to try to give the other side of the story: what an essay really is, and how you write one. Or at least, how I write one.ModsThe most obvious difference between real essays and the things one has to write in school is that real essays are not exclusively about English literature. Certainly schools should teach students how to write. But due to a series of historical accidents the teaching of writing has gotten mixed together with the study of literature. And so all over the country students are writing not about how a baseball team with a small budget might compete with the Yankees, or the role of color in fashion, or what constitutes a good dessert, but about symbolism in Dickens.With the result that writing is made to seem boring and pointless. Who cares about symbolism in Dickens? Dickens himself would be more interested in an essay about color or baseball.How did things get this way? To answer that we have to go back almost a thousand years. Around 1100, Europe at last began to catch its breath after centuries of chaos, and once they had the luxury of curiosity they rediscovered what we call "the classics." The effect was rather as if we were visited by beings from another solar system. These earlier civilizations were so much more sophisticated that for the next several centuries the main work of European scholars, in almost every field, was to assimilate what they knew.During this period the study of ancient texts acquired great prestige. It seemed the essence of what scholars did. As European scholarship gained momentum it became less and less important; by 1350 someone who wanted to learn about science could find better teachers than Aristotle in his own era. [1] But schools change slower than scholarship. In the 19th century the study of ancient texts was still the backbone of the curriculum.The time was then ripe for the question: if the study of ancient texts is a valid field for scholarship, why not modern texts? The answer, of course, is that the original raison d'etre of classical scholarship was a kind of intellectual archaeology that does not need to be done in the case of contemporary authors. But for obvious reasons no one wanted to give that answer. The archaeological work being mostly done, it implied that those studying the classics were, if not wasting their time, at least working on problems of minor importance.And so began the study of modern literature. There was a good deal of resistance at first. The first courses in English literature seem to have been offered by the newer colleges, particularly American ones. Dartmouth, the University of Vermont, Amherst, and University College, London taught English literature in the 1820s. But Harvard didn't have a professor of English literature until 1876, and Oxford not till 1885. (Oxford had a chair of Chinese before it had one of English.) [2]What tipped the scales, at least in the US, seems to have been the idea that professors should do research as well as teach. This idea (along with the PhD, the department, and indeed the whole concept of the modern university) was imported from Germany in the late 19th century. Beginning at Johns Hopkins in 1876, the new model spread rapidly.Writing was one of the casualties. Colleges had long taught English composition. But how do you do research on composition? The professors who taught math could be required to do original math, the professors who taught history could be required to write scholarly articles about history, but what about the professors who taught rhetoric or composition? What should they do research on? The closest thing seemed to be English literature. [3]And so in the late 19th century the teaching of writing was inherited by English professors. This had two drawbacks: (a) an expert on literature need not himself be a good writer, any more than an art historian has to be a good painter, and (b) the subject of writing now tends to be literature, since that's what the professor is interested in.High schools imitate universities. The seeds of our miserable high school experiences were sown in 1892, when the National Education Association "formally recommended that literature and composition be unified in the high school course." [4] The 'riting component of the 3 Rs then morphed into English, with the bizarre consequence that high school students now had to write about English literature-- to write, without even realizing it, imitations of whatever English professors had been publishing in their journals a few decades before.It's no wonder if this seems to the student a pointless exercise, because we're now three steps removed from real work: the students are imitating English professors, who are imitating classical scholars, who are merely the inheritors of a tradition growing out of what was, 700 years ago, fascinating and urgently needed work.No DefenseThe other big difference between a real essay and the things they make you write in school is that a real essay doesn't take a position and then defend it. That principle, like the idea that we ought to be writing about literature, turns out to be another intellectual hangover of long forgotten origins.It's often mistakenly believed that medieval universities were mostly seminaries. In fact they were more law schools. And at least in our tradition lawyers are advocates, trained to take either side of an argument and make as good a case for it as they can. Whether cause or effect, this spirit pervaded early universities. The study of rhetoric, the art of arguing persuasively, was a third of the undergraduate curriculum. [5] And after the lecture the most common form of discussion was the disputation. This is at least nominally preserved in our present-day thesis defense: most people treat the words thesis and dissertation as interchangeable, but originally, at least, a thesis was a position one took and the dissertation was the argument by which one defended it.Defending a position may be a necessary evil in a legal dispute, but it's not the best way to get at the truth, as I think lawyers would be the first to admit. It's not just that you miss subtleties this way. The real problem is that you can't change the question.And yet this principle is built into the very structure of the things they teach you to write in high school. The topic sentence is your thesis, chosen in advance, the supporting paragraphs the blows you strike in the conflict, and the conclusion-- uh, what is the conclusion? I was never sure about that in high school. It seemed as if we were just supposed to restate what we said in the first paragraph, but in different enough words that no one could tell. Why bother? But when you understand the origins of this sort of "essay," you can see where the conclusion comes from. It's the concluding remarks to the jury.Good writing should be convincing, certainly, but it should be convincing because you got the right answers, not because you did a good job of arguing. When I give a draft of an essay to friends, there are two things I want to know: which parts bore them, and which seem unconvincing. The boring bits can usually be fixed by cutting. But I don't try to fix the unconvincing bits by arguing more cleverly. I need to talk the matter over.At the very least I must have explained something badly. In that case, in the course of the conversation I'll be forced to come up a with a clearer explanation, which I can just incorporate in the essay. More often than not I have to change what I was saying as well. But the aim is never to be convincing per se. As the reader gets smarter, convincing and true become identical, so if I can convince smart readers I must be near the truth.The sort of writing that attempts to persuade may be a valid (or at least inevitable) form, but it's historically inaccurate to call it an essay. An essay is something else.TryingTo understand what a real essay is, we have to reach back into history again, though this time not so far. To <NAME>, who in 1580 published a book of what he called "essais." He was doing something quite different from what lawyers do, and the difference is embodied in the name. Essayer is the French verb meaning "to try" and an essai is an attempt. An essay is something you write to try to figure something out.Figure out what? You don't know yet. And so you can't begin with a thesis, because you don't have one, and may never have one. An essay doesn't begin with a statement, but with a question. In a real essay, you don't take a position and defend it. You notice a door that's ajar, and you open it and walk in to see what's inside.If all you want to do is figure things out, why do you need to write anything, though? Why not just sit and think? Well, there precisely is Montaigne's great discovery. Expressing ideas helps to form them. Indeed, helps is far too weak a word. Most of what ends up in my essays I only thought of when I sat down to write them. That's why I write them.In the things you write in school you are, in theory, merely explaining yourself to the reader. In a real essay you're writing for yourself. You're thinking out loud.But not quite. Just as inviting people over forces you to clean up your apartment, writing something that other people will read forces you to think well. So it does matter to have an audience. The things I've written just for myself are no good. They tend to peter out. When I run into difficulties, I find I conclude with a few vague questions and then drift off to get a cup of tea.Many published essays peter out in the same way. Particularly the sort written by the staff writers of newsmagazines. Outside writers tend to supply editorials of the defend-a-position variety, which make a beeline toward a rousing (and foreordained) conclusion. But the staff writers feel obliged to write something "balanced." Since they're writing for a popular magazine, they start with the most radioactively controversial questions, from which-- because they're writing for a popular magazine-- they then proceed to recoil in terror. Abortion, for or against? This group says one thing. That group says another. One thing is certain: the question is a complex one. (But don't get mad at us. We didn't draw any conclusions.)The RiverQuestions aren't enough. An essay has to come up with answers. They don't always, of course. Sometimes you start with a promising question and get nowhere. But those you don't publish. Those are like experiments that get inconclusive results. An essay you publish ought to tell the reader something he didn't already know.But what you tell him doesn't matter, so long as it's interesting. I'm sometimes accused of meandering. In defend-a-position writing that would be a flaw. There you're not concerned with truth. You already know where you're going, and you want to go straight there, blustering through obstacles, and hand-waving your way across swampy ground. But that's not what you're trying to do in an essay. An essay is supposed to be a search for truth. It would be suspicious if it didn't meander.The Meander (aka Menderes) is a river in Turkey. As you might expect, it winds all over the place. But it doesn't do this out of frivolity. The path it has discovered is the most economical route to the sea. [6]The river's algorithm is simple. At each step, flow down. For the essayist this translates to: flow interesting. Of all the places to go next, choose the most interesting. One can't have quite as little foresight as a river. I always know generally what I want to write about. But not the specific conclusions I want to reach; from paragraph to paragraph I let the ideas take their course.This doesn't always work. Sometimes, like a river, one runs up against a wall. Then I do the same thing the river does: backtrack. At one point in this essay I found that after following a certain thread I ran out of ideas. I had to go back seven paragraphs and start over in another direction.Fundamentally an essay is a train of thought-- but a cleaned-up train of thought, as dialogue is cleaned-up conversation. Real thought, like real conversation, is full of false starts. It would be exhausting to read. You need to cut and fill to emphasize the central thread, like an illustrator inking over a pencil drawing. But don't change so much that you lose the spontaneity of the original.Err on the side of the river. An essay is not a reference work. It's not something you read looking for a specific answer, and feel cheated if you don't find it. I'd much rather read an essay that went off in an unexpected but interesting direction than one that plodded dutifully along a prescribed course.SurpriseSo what's interesting? For me, interesting means surprise. Interfaces, as <NAME> said, should follow the principle of least astonishment. A button that looks like it will make a machine stop should make it stop, not speed up. Essays should do the opposite. Essays should aim for maximum surprise.I was afraid of flying for a long time and could only travel vicariously. When friends came back from faraway places, it wasn't just out of politeness that I asked what they saw. I really wanted to know. And I found the best way to get information out of them was to ask what surprised them. How was the place different from what they expected? This is an extremely useful question. You can ask it of the most unobservant people, and it will extract information they didn't even know they were recording.Surprises are things that you not only didn't know, but that contradict things you thought you knew. And so they're the most valuable sort of fact you can get. They're like a food that's not merely healthy, but counteracts the unhealthy effects of things you've already eaten.How do you find surprises? Well, therein lies half the work of essay writing. (The other half is expressing yourself well.) The trick is to use yourself as a proxy for the reader. You should only write about things you've thought about a lot. And anything you come across that surprises you, who've thought about the topic a lot, will probably surprise most readers.For example, in a recent essay I pointed out that because you can only judge computer programmers by working with them, no one knows who the best programmers are overall. I didn't realize this when I began that essay, and even now I find it kind of weird. That's what you're looking for.So if you want to write essays, you need two ingredients: a few topics you've thought about a lot, and some ability to ferret out the unexpected.What should you think about? My guess is that it doesn't matter-- that anything can be interesting if you get deeply enough into it. One possible exception might be things that have deliberately had all the variation sucked out of them, like working in fast food. In retrospect, was there anything interesting about working at Baskin-Robbins? Well, it was interesting how important color was to the customers. Kids a certain age would point into the case and say that they wanted yellow. Did they want French Vanilla or Lemon? They would just look at you blankly. They wanted yellow. And then there was the mystery of why the perennial favorite Pralines 'n' Cream was so appealing. (I think now it was the salt.) And the difference in the way fathers and mothers bought ice cream for their kids: the fathers like benevolent kings bestowing largesse, the mothers harried, giving in to pressure. So, yes, there does seem to be some material even in fast food.I didn't notice those things at the time, though. At sixteen I was about as observant as a lump of rock. I can see more now in the fragments of memory I preserve of that age than I could see at the time from having it all happening live, right in front of me.ObservationSo the ability to ferret out the unexpected must not merely be an inborn one. It must be something you can learn. How do you learn it?To some extent it's like learning history. When you first read history, it's just a whirl of names and dates. Nothing seems to stick. But the more you learn, the more hooks you have for new facts to stick onto-- which means you accumulate knowledge at an exponential rate. Once you remember that Normans conquered England in 1066, it will catch your attention when you hear that other Normans conquered southern Italy at about the same time. Which will make you wonder about Normandy, and take note when a third book mentions that Normans were not, like most of what is now called France, tribes that flowed in as the Roman empire collapsed, but Vikings (norman = north man) who arrived four centuries later in 911. Which makes it easier to remember that Dublin was also established by Vikings in the 840s. Etc, etc squared.Collecting surprises is a similar process. The more anomalies you've seen, the more easily you'll notice new ones. Which means, oddly enough, that as you grow older, life should become more and more surprising. When I was a kid, I used to think adults had it all figured out. I had it backwards. Kids are the ones who have it all figured out. They're just mistaken.When it comes to surprises, the rich get richer. But (as with wealth) there may be habits of mind that will help the process along. It's good to have a habit of asking questions, especially questions beginning with Why. But not in the random way that three year olds ask why. There are an infinite number of questions. How do you find the fruitful ones?I find it especially useful to ask why about things that seem wrong. For example, why should there be a connection between humor and misfortune? Why do we find it funny when a character, even one we like, slips on a banana peel? There's a whole essay's worth of surprises there for sure.If you want to notice things that seem wrong, you'll find a degree of skepticism helpful. I take it as an axiom that we're only achieving 1% of what we could. This helps counteract the rule that gets beaten into our heads as children: that things are the way they are because that is how things have to be. For example, everyone I've talked to while writing this essay felt the same about English classes-- that the whole process seemed pointless. But none of us had the balls at the time to hypothesize that it was, in fact, all a mistake. We all thought there was just something we weren't getting.I have a hunch you want to pay attention not just to things that seem wrong, but things that seem wrong in a humorous way. I'm always pleased when I see someone laugh as they read a draft of an essay. But why should I be? I'm aiming for good ideas. Why should good ideas be funny? The connection may be surprise. Surprises make us laugh, and surprises are what one wants to deliver.I write down things that surprise me in notebooks. I never actually get around to reading them and using what I've written, but I do tend to reproduce the same thoughts later. So the main value of notebooks may be what writing things down leaves in your head.People trying to be cool will find themselves at a disadvantage when collecting surprises. To be surprised is to be mistaken. And the essence of cool, as any fourteen year old could tell you, is nil admirari. When you're mistaken, don't dwell on it; just act like nothing's wrong and maybe no one will notice.One of the keys to coolness is to avoid situations where inexperience may make you look foolish. If you want to find surprises you should do the opposite. Study lots of different things, because some of the most interesting surprises are unexpected connections between different fields. For example, jam, bacon, pickles, and cheese, which are among the most pleasing of foods, were all originally intended as methods of preservation. And so were books and paintings.Whatever you study, include history-- but social and economic history, not political history. History seems to me so important that it's misleading to treat it as a mere field of study. Another way to describe it is all the data we have so far.Among other things, studying history gives one confidence that there are good ideas waiting to be discovered right under our noses. Swords evolved during the Bronze Age out of daggers, which (like their flint predecessors) had a hilt separate from the blade. Because swords are longer the hilts kept breaking off. But it took five hundred years before someone thought of casting hilt and blade as one piece.DisobedienceAbove all, make a habit of paying attention to things you're not supposed to, either because they're "inappropriate," or not important, or not what you're supposed to be working on. If you're curious about something, trust your instincts. Follow the threads that attract your attention. If there's something you're really interested in, you'll find they have an uncanny way of leading back to it anyway, just as the conversation of people who are especially proud of something always tends to lead back to it.For example, I've always been fascinated by comb-overs, especially the extreme sort that make a man look as if he's wearing a beret made of his own hair. Surely this is a lowly sort of thing to be interested in-- the sort of superficial quizzing best left to teenage girls. And yet there is something underneath. The key question, I realized, is how does the comber-over not see how odd he looks? And the answer is that he got to look that way incrementally. What began as combing his hair a little carefully over a thin patch has gradually, over 20 years, grown into a monstrosity. Gradualness is very powerful. And that power can be used for constructive purposes too: just as you can trick yourself into looking like a freak, you can trick yourself into creating something so grand that you would never have dared to plan such a thing. Indeed, this is just how most good software gets created. You start by writing a stripped-down kernel (how hard can it be?) and gradually it grows into a complete operating system. Hence the next leap: could you do the same thing in painting, or in a novel?See what you can extract from a frivolous question? If there's one piece of advice I would give about writing essays, it would be: don't do as you're told. Don't believe what you're supposed to. Don't write the essay readers expect; one learns nothing from what one expects. And don't write the way they taught you to in school.The most important sort of disobedience is to write essays at all. Fortunately, this sort of disobedience shows signs of becoming rampant. It used to be that only a tiny number of officially approved writers were allowed to write essays. Magazines published few of them, and judged them less by what they said than who wrote them; a magazine might publish a story by an unknown writer if it was good enough, but if they published an essay on x it had to be by someone who was at least forty and whose job title had x in it. Which is a problem, because there are a lot of things insiders can't say precisely because they're insiders.The Internet is changing that. Anyone can publish an essay on the Web, and it gets judged, as any writing should, by what it says, not who wrote it. Who are you to write about x? You are whatever you wrote.Popular magazines made the period between the spread of literacy and the arrival of TV the golden age of the short story. The Web may well make this the golden age of the essay. And that's certainly not something I realized when I started writing this.Notes[1] I'm thinking of Oresme (c. 1323-82). But it's hard to pick a date, because there was a sudden drop-off in scholarship just as Europeans finished assimilating classical science. The cause may have been the plague of 1347; the trend in scientific progress matches the population curve.[2] <NAME>. "Where Do College English Departments Come From?" College English 28 (1966-67), pp. 339-351. Reprinted in Gray, <NAME>. (ed). The Department of English at Indiana University Bloomington 1868-1970. Indiana University Publications.Daniels, <NAME>. The University of Vermont: The First Two Hundred Years. University of Vermont, 1991.Mueller, <NAME>. Letter to the Pall Mall Gazette. 1886/87. Reprinted in Bacon, Alan (ed). The Nineteenth-Century History of English Studies. Ashgate, 1998.[3] I'm compressing the story a bit. At first literature took a back seat to philology, which (a) seemed more serious and (b) was popular in Germany, where many of the leading scholars of that generation had been trained.In some cases the writing teachers were transformed in situ into English professors. <NAME>, who had been Boylston Professor of Rhetoric at Harvard since 1851, became in 1876 the university's first professor of English.[4] Parker, op. cit., p. 25.[5] The undergraduate curriculum or trivium (whence "trivial") consisted of Latin grammar, rhetoric, and logic. Candidates for masters' degrees went on to study the quadrivium of arithmetic, geometry, music, and astronomy. Together these were the seven liberal arts.The study of rhetoric was inherited directly from Rome, where it was considered the most important subject. It would not be far from the truth to say that education in the classical world meant training landowners' sons to speak well enough to defend their interests in political and legal disputes.[6] <NAME> points out that this isn't strictly true, because the outside edges of curves erode faster. Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Russian TranslationSpanish TranslationJapanese TranslationHungarian TranslationTraditional Chinese Translation If you liked this, you may also like Hackers & Painters.
https://github.com/j10ccc/zjut-social-practice-report-typst
https://raw.githubusercontent.com/j10ccc/zjut-social-practice-report-typst/main/layout/cover.typ
typst
#let cover(meta) = { let table(kv) = { for (key, value) in kv [ #grid( columns: (80pt, auto), gutter: 4pt, rect( width: 100%, inset: 2pt, stroke: none, text(size: 18pt, key) ), rect( width: 100%, inset: 2pt, stroke: (bottom: 1pt + black), text(size: 16pt, value, bottom-edge: "descender") ) ) #v(1em) ] } align(center)[ #align(top)[ #image("/assets/brand.png", width: 340pt) #v(64pt) #text("浙江工业大学思想政治理论课社会实践报告", size: 18pt, weight: "bold") ] #align(bottom)[ #rect(width: 360pt, stroke: none)[ #table(meta) ] ] ] }
https://github.com/robertjndw/typst-tum-presentation
https://raw.githubusercontent.com/robertjndw/typst-tum-presentation/main/colors.typ
typst
// Colors defined in the TUM Corporate Design Manual #let TUM_primary_blue = rgb("#0065BD") #let TUM_primary_white = rgb("#ffffff") #let TUM_primary_black = rgb("#000000") #let TUM_secondary_blue = rgb("#005293") #let TUM_secondary_blue_dark = rgb("#003359") #let TUM_secondary_grey_dark = rgb("#333333") #let TUM_secondary_grey_mid = rgb("#808080") #let TUM_secondary_grey_light = rgb("#CCCCCC") // Colors not for background, only accents #let TUM_accent_white = rgb("#DAD7CB") #let TUM_accent_orange = rgb("#E37222") #let TUM_accent_green = rgb("#A2AD00") #let TUM_accent_blue_light = rgb("#98C6EA") #let TUM_accent_blue_mid = rgb("#64A0C8")
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/figure-localization.typ
typst
Apache License 2.0
// Test localization-related figure features. --- // Test French #set text(lang: "fr") #figure( circle(), caption: [Un cercle.], ) --- // Test Chinese #set text(lang: "zh") #figure( rect(), caption: [一个矩形], )
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/slides.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #show: clean-theme.with( footer: [Bayesian Statistics, <NAME>], short-title: [Bayesian Statistics], logo: image("images/logos/juliadatascience_white.png"), color: julia-purple, ) // customizations #set bibliography(style: "harvard-cite-them-right") #set footnote(numbering: "i") #show link: set text(rgb("4063d8")) #set text(font: "Fira Sans", size: 20pt) // #show heading: set text(font: "Vollkorn") #show raw: set text(font: "Fira Mono", size: 20pt) #show cite: set text(fill: julia-blue) // begin slides #title-slide( title: [Bayesian Statistics], // subtitle: [TODO], authors: [<NAME>#footnote[Universidade Nove de Julho, Pumas-AI \ #v(0.5em)]], ) #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/main.jpg")] ] #slide(title: "License")[ #v(2em) #align(center)[ The text and images from these slides have a #link("https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en")[ Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) ] #v(1.5em) #image("images/badges/cc-by-nc-sa.svg", width: 20%) #v(1.5em) All links are in #text(julia-blue)[blue]. Feel free to click on them. ] ] #slide(title: [Outline])[ #text(size: 14pt)[ #utils.polylux-outline() ] ] #include "00-tools.typ" #include "01-bayesian_statistics.typ" #include "02-statistical_distributions.typ" #include "03-priors.typ" #include "04-bayesian_workflow.typ" #include "05-linear_regression.typ" #include "06-logistic_regression.typ" #include "07-ordinal_regression.typ" #include "08-poisson_regression.typ" #include "09-robust_regression.typ" #include "10-sparse_regression.typ" #include "11-hierarchical_models.typ" #include "12-mcmc.typ" #include "13-model_comparison.typ" #include "backup_slides.typ" #slide(title: "Bibliography")[ #bibliography(title: none, "references.yml") ]
https://github.com/SillyFreak/typst-scrutinize
https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/gallery/example.typ
typst
MIT License
// #import "@preview/scrutinize:0.3.0": grading, task, solution, task-kinds #import "../src/lib.typ" as scrutinize: grading, task, solution, task-kinds #import task-kinds: free-form, gap, choice #import task: t // make the PDF reproducible to ease version control #set document(date: none) #let title = "Exam" #set document(title: title) #set text(lang: "de") #let categories = ( (id: "a", body: [Topic A]), (id: "b", body: [Topic B]), ) #set page( paper: "a4", margin: (x: 1.5cm, y: 2cm, top: 4cm), header-ascent: 20%, // header: locate(loc => { // if calc.odd(loc.page()) { // } // }), header: { set text(size: 10pt) table( columns: (1fr,) * 3, stroke: none, align: (col, row) => (left, center, left).at(col) + horizon, [], [*#title*], [], [Name:], [], [Date: ], ) }, ) #let t-data(t) = (points: none, category: none, extended: false, ..t.data) #set table(stroke: 0.5pt) #set table.hline(stroke: 0.5pt) #set table.vline(stroke: 0.5pt) #show heading.where(level: 2): set heading( supplement: [Task], numbering: (..nums) => numbering("1", ..nums.pos().slice(1)), ) #show heading.where(level: 2): it => { let t = t-data(task.current(level: 2)) show: block [#it.supplement #counter(heading).display()] if (it.body != []) [: #it.body] if t.points != none or t.extended { h(1fr) } if t.points != none [#solution.answer[#t.points] / #t.points P.] if t.extended [ (ext.)] } #context { set text(size: 9pt) set table(stroke: none) let ts = task.all(level: 2) let points(category, extended) = { grading.total-points(ts.filter(t => { let t = t-data(t) t.category == category and t.extended == extended })) } let categories = categories.map((category) => { let gk = points(category.id, false) let ek = points(category.id, true) (..category, gk: gk, ek: ek) }) let total = grading.total-points(ts) let grades = grading.grades( [F], 0.6 * total, [D], 0.7 * total, [C], 0.8 * total, [B], 0.9 * total, [A], ) let grades = grades.map(((body, lower-limit, upper-limit)) => { if lower-limit == none { (body: body, range: [< #(upper-limit - 0.5) P.]) } else if upper-limit != none { (body: body, range: [#lower-limit - #(upper-limit - 0.5) P.]) } else { (body: body, range: [#lower-limit - #total P.]) } }) let points(pts) = [#solution.answer[#pts] / #pts] table( columns: (2fr, ..(1fr,) * 3), align: (x, y) => horizon + { if y == 0 { center } else if x == 0 { left } else { right } }, table.header( [*Topic*], [*Basic competency*], [*Extended competency*], [*Total*], ), table.hline(), ..for (id, body, gk, ek) in categories { (table.cell(align: left, body), points(gk), points(ek), points(gk + ek)) }, table.hline(), [], [], [], points[#total], ) [= Grading key] table( columns: (auto, ..(1fr,) * grades.len()), align: (col, row) => horizon + { if col == 0 { left } else { center } }, [Points:], ..grades.map(g => g.range), [Grade:], ..grades.map(g => g.body), ) } = Basic competencies -- theoretical part A #lorem(40) == Java Code #t(category: "a", points: 3) #lorem(30) #{ set text(1.4em) let gaps = ( GAP1: "void", GAP2: "String[]", ) show regex(gaps.keys().join("|")): placeholder => { let answer = gaps.at(placeholder.text) gap.gap(raw(lang: "java", answer), stretch: 200%) } ```java public static GAP1 main(GAP2 args) { // ... } ``` } = Basic competencies -- theoretical part B #lorem(40) == Writing #t(category: "b", points: 4) #lorem(30) #free-form.lines(stretch: 180%, lorem(20)) == Multiple Choice #t(category: "b", points: 2) #lorem(30) #{ set align(center) choice.multiple(( (lorem(3), true), (lorem(5), true), (lorem(4), false), )) } = Basic and extended competencies -- practical part A #lorem(80) == #t(category: "a", points: 4) #lorem(30) #free-form.grid(stretch: 200%, lorem(20)) == #t(category: "a", points: 5) #lorem(30) #free-form.grid(stretch: 200%, lorem(20)) == #t(category: "a", points: 4) #lorem(30) #free-form.grid(stretch: 200%, lorem(20)) == Complete a diagram, separate points category #t(category: "a", points: 4, extended: true) #lorem(40) #{ import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge set align(center) let automaton(solved) = { show: pad.with(y: 1em) diagram( node-stroke: .5pt, spacing: 3em, { let start = (-1, 0) let a = (0, 0) let b = (1, 0) let c = (2, 0) node(a, [a], radius: 1em) node(b, [b], radius: 1em) node(c, [c], radius: 1em, ..if solved { (extrude: (-4, 0)) }) edge(start, a, "-|>", label-pos: 0, label-side: center) let stroke = if not solved { (stroke: white) } edge(a, b, "-|>", ..stroke) edge(b, c, "-|>", ..stroke) edge(a, a, "--|>", ..stroke, bend: 130deg) edge(a, c, "-|>", ..stroke, bend: -40deg) } ) } free-form.plain( automaton(true), placeholder: automaton(false), ) } #pagebreak(weak: true) = Basic and extended competencies -- practical part B #lorem(80) == #t(category: "b", points: 6) #lorem(40) #free-form.grid(stretch: 200%, lorem(20)) == #t(category: "b", points: 4) #lorem(40) #free-form.grid(stretch: 200%, lorem(20)) == #t(category: "b", points: 2, extended: true) #lorem(40) #free-form.grid(stretch: 300%, lorem(20)) == #t(category: "b", points: 2, extended: true) #lorem(40) #free-form.grid(stretch: 200%, lorem(20))
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote-refs_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Styling #show footnote: text.with(fill: red) Real #footnote[...]<fn> \ Ref @fn
https://github.com/cs-24-sw-3-01/typst-documents
https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/chapters/styleguide.typ
typst
#import "../custom.typ": * = Styleguide == Language We will use american english for this report == Tops and Tails Tops will only be used for chapters. We will use tops and tails for the sections of the document. A top will only be used where it makes sense. Tails are required. Tops will only be used in chapters. == Workflow + Create issue on kanban board, and assign yourself to it + Pull from main + Create new branch based on main + Link branch to issue on kanban board + Push and Commit to branch while you work + Create Pull Request to main, where you explain the addition + Add reviewers to pull request (Try to mix up the reviewers of your PR's) + Squash merge into main, when PR is approved
https://github.com/Quaternijkon/QUAD
https://raw.githubusercontent.com/Quaternijkon/QUAD/main/config.typ
typst
#import "@preview/touying:0.4.2": * #import "theme.typ" #let s = theme.register(aspect-ratio: "16-9") #let s = (s.methods.numbering)(self: s, section: "1.", "1.1") #let s = (s.methods.info)( self: s, title: [什么年代了还在用传统幻灯片?], subtitle: [快来使用幻灯片界的⚪神Typst!], author: [Typst领域大神], date: datetime.today(), institution: [新艾丽都], ) #let (init, slides, touying-outline, alert) = utils.methods(s) #let (slide, title-slide, outline-slide, focus-slide, matrix-slide, empty-slide) = utils.slides(s)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-text-03.typ
typst
Other
// Test caseless match and word boundaries. #show regex("(?i)\bworld\b"): [🌍] Treeworld, the World of worlds, is a world.
https://github.com/HiiGHoVuTi/requin
https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/fonc/optique.typ
typst
#import "../lib.typ": * #show heading: heading_fct #import "@preview/gloss-awe:0.0.5": gls #show figure.where(kind: "jkrb_glossary"): it => {it.body} #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge === Lentilles explicites On souhaite réaliser des accès/modifications à un champ d'une structure de données. #align(center, diagram( node-stroke: 1pt, node((0,0), `champ1`, fill: rgb("ff69b4")), node((0,1), `champ2`, fill: rgb("ff69b4")), node(enclose: ((0, 0), (0, 1)), `structure`, fill: rgb("ff69b4aa")), )) En `OCaml`, il existe une manière pré-existante dans le langage. ```ocaml type enregistrement = { champ : int } let x = { champ = 8 } in { x; champ = 9 }, (* modification *) x.champ (* accès *) ``` On propose la construction de _lentille_ : ```ocaml type ('s, 'a) lens = { set : 's -> 'a -> 'a ; get : 'a -> 's } ``` #question(0)[Donner une lentille pour un type enregistrement et un de ses champs.] #question(1)[Donner une lentille pour `'a list` et `'a option`.] #question(1)[ Donner une fonction `compose : ('t, 's) lens -> ('u 't) lens -> ('u, 's) lens`. ] #question(2)[Donner une lentille sur les listes séletionnant les éléments aux indices divisibles par $n in NN$.] #question(2)[En déduire une implémentation du crible d'Erathostènes.] === Lentilles existentielles #question(1)[ Justifier qu'une valeur de type `('t, 's) lens` donne une preuve de $exists c, s tilde.eq t times c$ ] On propose alors que le type d'une lentille soit ```ocaml type ('s, 'a) lens = { direct : 's -> 'a * 'c ; indirect : 'a * 'c -> 's } ``` pour un certain `c` qui n'est pas fixé. #question(2)[ Donner une fonction `compose` pour ce type de lentilles. Comment déduire le nouveau `c` ? ] === Lentilles à profoncteur _Dans cette partie, on s'éloigne un peu de `OCaml` pour avoir plus de liberté dans le types._ Un constructeur de type $P$ à deux arguments est un _#gls(entry: "Profoncteur")[profoncteur]_ lorsqu'il existe $ p : (a' -> a) -> (b -> b') -> P a b -> P a' b' $ avec #align(center, grid(columns: (1fr, 1fr), [- $p "id" "id" = "id"$], [- $p (f' compose f) (g' compose g) = p f' g' compose p f g$] )) #question(0)[Montrer que $(-->)$ le type d'une fonction est un profoncteur.] Un profoncteur $p$ est _cartésien_ si il existe : #align(center, grid(columns: (1fr, 1fr), [- $"left" : med P a b -> P (c times a) (c times b)$], [- $"right" : P a b -> P (a times c) (b times c)$] )) #question(1)[Montrer que $(-->)$ est cartésien.] On pose $"Optique"(p, s, t, a, b) := p a b -> p s t$ puis $"Lens"(s, a) := forall p "cartésien". "Optique"(s, s, a, a)$. #question(1)[Réimplémenter `get` et `set`.] #question(1)[Donner une fonction `compose` qui compose deux lentilles.] Un profoncteur $p$ est _cocartésien_ si il existe : #align(center, grid(columns: (1fr, 1fr), [- $"left" : med P a b -> P (c + a) (c + b)$], [- $"right" : P a b -> P (a + c) (b + c)$] )) avec `a + b = A of a | B of b`. #question(2)[Proposer une définition d'un prisme comme optique.] #question(3)[Que dire d'un type $forall p "profoncteur", "Optique"(p, s, s, a, a)$ ?]
https://github.com/jens-hj/ds-exam-notes
https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/6.typ
typst
#import "../lib.typ": * #show link: it => underline(emph(it)) #set math.equation(numbering: "(1)") #set enum(full: true) #set math.mat(delim: "[") #set math.vec(delim: "[") #set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled)) #show heading.where(level: 1): it => text(size: 22pt, it) #show heading.where(level: 2): it => text(size: 18pt, it) #show heading.where(level: 3): it => { text(size: 14pt, mainh, pad( left: -0.4em, gridx( columns: (auto, 1fr), align: center + horizon, it, rule(stroke: 1pt + mainh) ) )) } #show heading.where(level: 4): it => text(size: 12pt, secondh, it) #show heading.where(level: 5): it => text(size: 12pt, thirdh, it) #show heading.where(level: 6): it => text(thirdh, it) #show emph: it => text(accent, it) #show ref: it => { //let sup = it.supplement let el = it.element if el == none { it.citation } else { let eq = math.equation // let sup = el.supplement if el != none and el.func() == eq { // The reference is an equation let sup = if it.fields().at("supplement", default: "none") == "none" { [Equation] } else { [] } // [#it.has("supplement")] show regex("\d+"): set text(accent) let n = numbering(el.numbering, ..counter(eq).at(el.location())) [#sup #n] } else if it.citation.has("supplement") { if el != none and el.func() == eq { show regex("\d+"): set text(accent) let n = numbering(el.numbering, ..counter(eq).at(el.location())) [#el.supplement #n] } else { text(accent)[#it] } } } } === Repair Problem - See intro from last week, in terms of why and trade-offs - Last week talked aabout erasure codes; striping with redundancy, e.g. `RAID`-like, array codes - This week will be a bout _regenerating codes_, optimised for repair; decoding and minimising network traffic #report-block[ Did I say that the loss-quantification ping/pong was implemented in the Lead Node, without actually having it implemented there? ] === Regenerating Codes - Stripe data with redundancy and reduce the repair bandwidth - Minimise repair traffic with same fault tolerance as Reed Solomon *Benefits:* - Faster repair - Inherent trade-off of storage and traffic-cost - *Network coding is key:* Recoding needed at the nodes/racks before sending _Don't need to become expert in network coding_ \ *#ra Just know:* Network itself can provide re-combinations of the coded data ==== Repair Degree Repair degree $d$ - That is, from how many disks $d$ data is needed to repair. ==== More General Reed Solomon #image("../img/6/reed-general.png", width: 50%) ==== Example *Generate:* #image("../img/6/reg-example.png", width: 50%) *Recover:* - Only had to move 1.5 units instead of 2 #image("../img/6/reg-example-recov.png", width: 50%) ==== How - as $n$ and $k$ refer to internal units here and not specific nodes you can determine how thinly to slice/stripe for optimal beahviour #image("../img/6/reg-how.png", width: 50%) ==== Graph - Multicast flow problem - Each node stores $alpha$ bits - Original file has $B$ bits - Spread is $alpha = B"/"k$ bits #image("../img/6/reg-g1.png", width: 15%) - Transmit $beta$ bits from each surviving node ($d$ surviving nodes) - Total bandwith of $gamma = d beta$ - As long as there is a linear combination that brings the _correct_ properties, it is solvable - Maintain MDS conditions #image("../img/6/reg-g2.png", width: 50%) #report-block[ Kinda have to do well to make up for report weaknesses it seems like ] *Full theorem:* - Clear connection between the degree $d$ and other parameters #image("../img/6/reg-full.png") - Hard limit at some point \ #ra $alpha approx 0.258$ for minimum bandwidth \ #ra $alpha 0.2$ for minimum storage #gridx( columns: 2, image("../img/6/reg-min.png"), image("../img/6/reg-mbr-msr.png") ) - Assuming granularity at bit-level, that you can slice anywhere at bit-level, which might not be possible. \ #ra Can't get exactly MBS or MSR in these cases ==== Beyond Full Node Loss - What happens if we only lose one or several disks on a node, instead of all of it #report-block[ Not a weakness but the report doesn't talk about node vs inter-node disk loss ] ==== RS vs RLNC *Example:* Reed Solomon \ Collect 15 chunks #ra decode #ra re-encode \ Centralised processing at one node #image("../img/6/reg-ex-reed.png", width: 60%) *Example:* Random Linear Network Co \de Distributing the processing between nodes #image("../img/6/reg-ex-rlnc.png") *Benefits:* - Less memory consumption furing recovery process - Workload can be _distributed_ during recovery process (across racks/nodes), while *Reed Solomon* will have large workload on a single rack/node at the end - Less delay after last packet arrives for *Random Linear Network Codes* #image("../img/6/reg-rsvsrlnc.png") #report-block[ I don't fully understand how RLNC is able to cut down traffic so much? \ #ra does it mean something about doing it in the network instead of on the nodes? *Answer:* \ - Combine multiple packets of data into a single coded packet of the same size. - Coded packets are not useful without the coding coefficients ] #image("../img/6/reg-benefits.png", width: 30%) #image("../img/6/reg-comp.png", width: 80%) ==== Exact Repair *E-MBR (Minimum bandwidth regenerating codes)* with exact repair: - Minimise repair bandwidth while maintingin MDS property *Idea:* - Assume $d = n - 1$ (repair data from $n-1$ survival disks during a single-node failure) - Make a duplicate copy for each native/code block - To repair a failed disk, download _exactly one block per segment_ from each survival disk *Feasibility:* - Achieving exact repair comes at a cost - Not really feasible - Requires more control with a specific structure _Needs something close to the *Genie* policy_ #report-block[ Gives no perspective to repairability at all! \ In general a lack of giving _perspectives_ to the rest of the course topics ]
https://github.com/antonWetzel/typst-video
https://raw.githubusercontent.com/antonWetzel/typst-video/master/example/main.typ
typst
#set document(title: "Example Project 2") #let scenes = state("scenes", ()) #let fps_state = state("fps", 30) #let scene_state = state("scene", ( objects: (), background: white, )) #let scene(name, actions, background: white) = { pagebreak(weak: true) context { let start = counter(page).get().at(0) scenes.update(scenes => { scenes.push(( name, start, )) scenes }) } scene_state.update((objects: (), background: background)) actions let end = context counter(page).get().at(0) context { let end = counter(page).get().at(0) scenes.update(scenes => { scenes.last().push(end) scenes }) } } #let step() = { context { pagebreak(weak: true) let scene = scene_state.get() rect(width: 100%, height: 100%, fill: scene.background, stroke: none, inset: 0pt, { for object in scene.objects { (object.render)(object) } }) } context { let fps = fps_state.get() scene_state.update(scene => { let new-objects = () for object in scene.objects { let object = (object.update)(object, 1.0 / fps) if (object.alive)(object) { new-objects.push(object) } } scene.objects = new-objects scene }) } } #let setup(width: 1920pt, height: 1080pt, fps: 30) = { (doc) => { set page(width: width, height: height, margin: 0pt) show raw: set text(font: "FiraCode Nerd Font Mono") fps_state.update(fps) context [ #metadata(fps) <fps> #metadata(scenes.final()) <final-scenes> ] set text(size: 100pt) doc } } #let spawn(object) = scene_state.update(scene => { scene.objects.push(object) scene }) #let object(content) = ( render: (self) => place(content), alive: (self) => true, update: (self, delta) => self, ) #let timed(object, time) = ( object: object, time: time, render: (self) => (self.object.render)(self.object), alive: (self) => self.time >= 0.0 and (self.object.alive)(self.object), update: (self, delta) => { self.time -= delta self.object = (self.object.update)(self.object, delta) self }, ) #let translate(x: 0pt, y: 0pt, object) = ( x: x, y: y, object: object, render: (self) => place(dx: self.x, dy: self.y, (self.object.render)(self.object)), alive: (self) => (self.object.alive)(self.object), update: (self, delta) => { self.object = (self.object.update)(self.object, delta) self }, ) #let KEEP = "K" #let DELETE = "D" #let INSERT = "I" #let REPLACE = "R" #let wait(seconds: none) = { if seconds == none { panic("todo: wait until everything finished") } context { let fps = fps_state.get() let frames = fps * seconds for i in range(0, int(calc.ceil(frames))) { step() } } } #let text-diff-table(start, end) = { let table = ((0,) * (end.len() + 1),) * (start.len() + 1) for i in range(0, start.len() + 1) { table.at(i).at(0) = i } for j in range(0, end.len() + 1) { table.at(0).at(j) = j } for i in range(0, start.len()) { for j in range(0, end.len()) { table.at(i + 1).at(j + 1) = if start.at(i) == end.at(j) { table.at(i).at(j) } else { let a = table.at(i + 1).at(j) let b = table.at(i).at(j + 1) let c = table.at(i).at(j) calc.min(a, b, c) + 1 } } } table } #let text-diff(table, start, end, i, j) = { if i == 0 and j == 0 { () } else if i == 0 { text-diff(table, start, end, i, j - 1) (INSERT,) } else if j == 0 { text-diff(table, start, end, i - 1, j) (DELETE,) } else if start.at(i - 1) == end.at(j - 1) { text-diff(table, start, end, i - 1, j - 1) (KEEP,) } else { let del = table.at(i).at(j - 1) let ins = table.at(i - 1).at(j) let repl = table.at(i).at(j) let best = calc.max(del, ins, repl) if repl == best { text-diff(table, start, end, i - 1, j - 1) (REPLACE,) } else if del > ins or (del == ins and i > j) { text-diff(table, start, end, i - 1, j) (DELETE,) } else { text-diff(table, start, end, i, j - 1) (INSERT,) } } } #let clusters-to-str(clusters) = { let str = "" for cluster in clusters { str += cluster } str } #let transform-text(start, end, delta: 0.1) = { let start = start.clusters() let end = end.clusters() let table = text-diff-table(start, end) let diff = text-diff(table, start, end, start.len(), end.len()) let text = start let cursor = 0 let variants = ((text, cursor),) for action in diff { if action == KEEP { cursor += 1 } else if action == DELETE { text = text.slice(0, cursor) + text.slice(cursor + 1) variants.push((text, cursor)) } else if action == INSERT { text = text.slice(0, cursor) + (end.at(cursor),) + text.slice(cursor) cursor += 1 variants.push((text, cursor)) } else if action == REPLACE{ text = text.slice(0, cursor) + (end.at(cursor),) + text.slice(cursor + 1) cursor += 1 variants.push((text, cursor)) } else { panic() } } assert(text == end) for (variant, cursor) in variants { context { let fps = fps_state.get() spawn(timed(object(raw(block: true, clusters-to-str(variant), lang: "rust")), delta - 0.01)) wait(seconds: delta) } } } #show: setup() #scene("Test", background: rgb(20%, 30%, 40%), { spawn(timed(object([Hi]), 0.3)) wait(seconds: 1.0) spawn(translate(x: 100pt, y: 100pt, object([Hi]))) wait(seconds: 1.0) }) #scene("Test 2", background: rgb(20%, 40%, 40%), { spawn(object([Hi])) wait(seconds: 1.0) spawn(translate(x: 100pt, y: 100pt, object([Hi]))) wait(seconds: 1.0) }) #scene("Test 3", background: rgb(100%, 40%, 40%), { spawn(object(`Hi`)) wait(seconds: 1.0) spawn(translate(x: 100pt, y: 100pt, object([Hi]))) wait(seconds: 1.0) }) #let start-text = " fn test() { other_function(); }" #let end-text = " fn main() { test_function(1.0); }" #scene("Transform Text", background: white, { transform-text(start-text, end-text, delta: 0.1) })
https://github.com/LugsoIn2/typst-htwg-thesis-template
https://raw.githubusercontent.com/LugsoIn2/typst-htwg-thesis-template/main/lib/htwgThesis.typ
typst
MIT License
#import "cover.typ": * #import "titlepage.typ": * #import "declarationOfHonour.typ": * #import "abstract.typ": * #import "appendix.typ": * #import "tableOfContents.typ": * #import "listOfFigures.typ": * #import "listOfTables.typ": * #import "textTemplate.typ": * #import "@preview/glossarium:0.4.1": make-glossary, print-glossary, gls, glspl #import "../glossar/glossary.typ": glossary #show: make-glossary #let htwgThesis( lang: "", title: "", degree: "", program: "", supervisor: "", advisors: (), author: "", studentnumber: "", authormail: "", location: "", startDate: datetime, submissionDate: datetime, abstract: include "/abstract/abstract.typ", body, birthdate: datetime, birthplace: "", companySentence: "", show_appendix: bool, show_glossary: bool, show_list_of_tables: bool, show_list_of_figures: bool, appendices: (), citeStyle: "ieee", physicalPrint: true, ) = { // --- ---------------- ---- // - Check degree settings - assert(degree in ("Bachelor", "Master"), message: "The degree must be either 'Bachelor' or 'Master'") let arial-font = "Arial" let htwg-color-green = rgb(0,155,145) let chap-title-color = htwg-color-green let thesis-template-font = arial-font // --- ---------------- ---- // --------- cover --------- cover( lang: lang, title: title, degree: degree, program: program, author: author, studentnumber: studentnumber, authormail: authormail, location: location, physicalPrint: physicalPrint, ) // --- ---------------- ---- // -------- titlepage ------ titlepage( lang: lang, title: title, degree: degree, program: program, supervisor: supervisor, advisors: advisors, author: author, startDate: startDate, submissionDate: submissionDate, studentnumber: studentnumber, physicalPrint: physicalPrint, ) // --- ---------------- ---- // -- declarationOfHonour -- declarationOfHonour( lang: lang, title: title, degree: degree, author: author, submissionDate: submissionDate, birthdate: birthdate, birthplace: birthplace, companySentence: companySentence, supervisor: supervisor, location: location, physicalPrint: physicalPrint, ) set page( margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm), numbering: "i", number-align: center, ) set text( font: thesis-template-font, size: 12pt, lang: lang ) show math.equation: set text(weight: 400) // --- ---------------- ---- // -------- Headings ------- show heading: set block(below: 1.85em, above: 1.85em) show heading: set text(font: thesis-template-font, overhang: false) show heading.where(level: 1): set text(fill: htwg-color-green, size: 30pt) show heading.where(level: 1): set align(right) show heading.where(level: 1): set block(below: 2.0em) set heading(numbering: "1.1.") // --- ---------------- ---- // Level 1 Pagebreak to odd show heading.where(level: 1): it => [ // #pagebreak(weak: true, to: "odd") #if physicalPrint { pagebreak(weak: true, to: "odd") } else { pagebreak(weak: true) } #it ] // --- ---------------- ---- // link and ref color show ref: set text(fill: htwg-color-green) show link: set text(fill: htwg-color-green) // --- ---------------- ---- // ------- Citations ------- set cite(style: citeStyle) // --- ---------------- ---- // -------- Figures -------- show figure: set text(size: 0.85em) // --- ---------------- ---- // ------- Abstract -------- abstractPages(lang: lang)[#abstract] // --- ---------------- ---- // ---- tableOfContents ---- tableOfContents( lang: lang, table-of-contents-font: thesis-template-font, font-color: chap-title-color ) // --- ---------------- ---- // - restart page counter -- set page( numbering: "1", number-align: center, ) counter(page).update(1) // --- ---------------- ---- // ------- glossary -------- if show_glossary == true { let languageTextGlossary = textTemplate(pagetype: "glossary" ,lang: lang) heading(numbering: none)[#languageTextGlossary.at(0)] print-glossary(glossary) } // --- ---------------- ---- // --- main content --- set par(justify: true,) body // --- ---------------- ---- // ---- list of figures ---- if show_list_of_figures == true { listOfFigures(lang: lang) } // --- ---------------- ---- // ---- list of tables ---- if show_list_of_tables == true { listOfTables(lang: lang) } // --- ---------------- ---- // ------ bibliography ----- let languageTextBibl = textTemplate(pagetype: "bibliography" ,lang: lang) bibliography("../bib/bibliography.bib", title: languageTextBibl.at(0)) // --- ---------------- ---- // -------- appendix ------- if show_appendix == true { appendix(lang: lang, appendices: appendices) } }
https://github.com/TimPaasche/Typst.Template.CoverLetter
https://raw.githubusercontent.com/TimPaasche/Typst.Template.CoverLetter/master/main.typ
typst
MIT License
#import "template/style.typ": titlePage #show: doc => titlePage( title: "Überschrift", company: ( name: "Firma AG / GmbH", address: ( street: "Straße 1", place: "11111 Musterstadt", contry: "Deutschland", ), ), author: ( name: "<NAME>", address: ( street: "Straße 1", place: "11111 Stadt", contry: "Deutschland", ), email: "<EMAIL>" ), firstpage: [ #set text(lang: "de") Sehr geehrte Damen und Herren, #v(1cm) #lorem(100) #v(1cm) mit freundlichen Grüßen #v(2mm) <NAME> #linebreak() Karlsruhe, der #datetime.today().display("[DAY].[MONTH].[YEAR]") ], doc, )
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/WEB/docs/2-HTML%26CSS/css.typ
typst
#import "/_settings/typst/template-note-en.typ": conf #show: doc => conf( title: [ CSS ], lesson: "WEB", chapter: "2 - HTML & CSS", definition: "The text covers fundamental educational objectives in web development, elucidating the roles of HTML and CSS, HTML document structure, and the integration of CSS styling. It emphasizes the application of HTML elements, CSS properties, and the importance of understanding the Document Object Model (DOM). Additionally, it delves into advanced layout techniques like Grid and Flexbox, alongside responsive design using Media Queries. The narrative underscores the significance of accessibility and SEO, elucidating various methods to enhance SEO practices. Furthermore, it provides comprehensive insights into CSS anatomy, selectors, properties, layout models like Flexbox and Grid, and the implementation of Media Queries for responsive design.", col: 1, doc, ) = Educational objectives - Describe the role of HTML and CSS in web development - Describe the structure of an HTML document - Create a HTML document with a CSS stylesheet - Use HTML elements and CSS properties - Describe the role of the Document Object Model (DOM) and it’s structure - Use Grid and Flexbox for layout - Use Media Queries for responsive design - Cite the importance of accessibility and SEO (Search Engine Optimization) in web development - Cite different ways to enhance SEO = Anatomy of CSS document == Ruleset A CSS document is a sequence of rulesets, used for styling specified parts of the document. #image("/_src/img/docs/image copy 36.png") A ruleset is composed of - a comma-separated list of selectors, and - a declarations block describing the styling of the selected elements. Rulesets apply declarations to specific parts of the document. Declaration blocks are preceded by one or more comma-separated selectors. Selectors are conditions selecting some elements of the page. == Declaration A declaration is a property-value pair that describes the styling of the selected elements. A declaration block is a sequence of declarations enclosed in curly braces. ```css selector { property: value; } ``` = Adding CSS to HTML CSS can be added to an HTML document in three ways: == Inline Inline CSS is added directly to the HTML element using the `style` attribute. ```html <p style="color: red;">This is a red paragraph.</p> ``` == Internal Internal CSS is added to the HTML document using the `<style>` tag in the `<head>` section. ```html <!DOCTYPE html> <html> <head> <style> p { color: red; } </style> </head> <body> <p>This is a red paragraph.</p> </body> </html> ``` == External External CSS is added to the HTML document using the `<link>` tag in the `<head>` section. ```html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <p>This is a red paragraph.</p> </body> </html> ``` = 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.* *Exemple* ```html <!DOCTYPE html> <html> <head> <style> div > p { color: red; } </style> </head> <body> <div> <p>This is a red paragraph.</p> <span> <p>This isn't a red paragraph.</p> </span> </div> </body> </html> ``` == Other selectors - a b selects all elements that match b and are (potentially non-direct) descendants of elements that match a. - a > b selects all elements that match b and are direct children of elements that match a. - a ~ b selects all elements that match b and are siblings of elements that match a (i.e. both a and b have the same parent) and b appears after a. - a + b selects all elements that match b and are adjacent siblings of elements that match a (i.e. both a and b have the same parent, and b immediately follows a). == Precise selectors The id, class and attribute selectors can be combined by adding them as suffixes to other selectors. ```css p#myid /* a p element with id "myid" */ *.myclass /* any element with class "myclass" */ p.myclass#myid[attr=value] /* a p with class "myclass", id "myid" and "attr=value" */ ``` = Pseudo-classes and pseudo-elements == Pseudo-class Pseudo-classes are used to define the special state of an element. ```css a:link { color: blue; } ``` *This rule will apply to all `<a>` elements that are unvisited links.* == Pseudo-element Pseudo-elements are used to style parts of an element. ```css p::first-line { color: red; } ``` *This rule will apply to the first line of all `<p>` elements.* = CSS Properties CSS properties are used to describe the styling of the selected elements. There are several types of properties: == Text properties ```css p { text-align: center; line-height: 2em; letter-spacing: 2em; text-decoration: underline; text-transform: uppercase; } ``` == Background properties ```css body { background-color: blue; background-image: url('../image.jpg'); background-repeat: no-repeat; background-size: auto; } ``` == Color properties ```css p { /* named-color values */ color: red; color: orange; /* hex-color values */ color: #090; color: #009900; /* rgb() values, rgba() also has alpha (opacity) */ color: rgb(34, 12, 64); color: rgba(34, 12, 64, 0.6); } ``` == Font properties ```css p { font-family: Arial, sans-serif; font-size: 16px; font-weight: bold; font-style: italic; } ``` The font property sets an element’s font to a system font. - The first font specified that is available is used to display the element. - The recommended font size units are px, em and %. Pixels are fixed, wheareas em and % are relative to the font size specified for the document. === External font ```css @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap'); body{ font-family: 'Roboto', sans-serif; } ``` == Properties and Inheritance Some properties are inherited by child elements. - *Do Inherit*: color, font, line-height, letter-spacing, text-align, etc. - *Do not Inherit*: background-color, border, padding, margin, etc. = Layout The display property specifies if/how an element is displayed. The default value of display depends on the element. The most common values are: - block: element generates line break before and after itself. Can have specified height and width. If unspecified, takes up the whole width of its parent element (e.g. div, p, h1, h2, etc.). - inline: element does not generate line breaks, only takes up as much width as necessary (e.g. span, a, img, etc.). It will be on the same line as other inline elements, if there is space. - inline-block: element is displayed as an inline element, but can have specified width and height (e.g. buttons, input fields, etc.). - none: element is not displayed at all. - flex: element is displayed as a block-level flex container (e.g. div, section, etc.). == Positioning The position property specifies the type of positioning method used for an element. - static: The element is positioned according to the normal flow of the document. - relative: The element is positioned according to the normal flow of the document, and then offset relative to itself. - absolute: The element is positioned relative to its closest non-static positioned ancestor. - fixed: The element is positioned relative to the initial containing block established by the viewport and does not move with scroll. - sticky: The element is positonned according to the normal flow of the document, but behaves like fixed when scrolled out of view. If another element is positioned sticky nearby, they will “push” each other out of the way. #image("/_src/img/docs/image copy 37.png") #colbreak() == 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; } } ``` == Define variables ```css :root { /* Global variables */ --main-color: #06c; --main-bg-color: #fff; } .subcontent { /* Local variables ; override global variables */ --main-color: #c06; --main-bg-color: #fff; --content-specific-color: #f00; } ``` == Accessibing variables ```css .my-element { color: var(--main-color); background-color: var(--main-bg-color); } ``` The var() function can take fallback values in case one of the variables is not defined. ```css .my-element { color: var(--main-color, #06c); background-color: var(--main-bg-color, #fff); } ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/chart/boxwhisker.typ
typst
Apache License 2.0
#import "/src/cetz.typ": draw, styles, palette, util, vector, intersection #import "/src/plot.typ" #let boxwhisker-default-style = ( axes: (tick: (length: 0), grid: (stroke: (dash: "dotted"))), box-width: 0.75, whisker-width: 0.5, mark-size: 0.15, ) /// Add one or more box or whisker plots. /// /// #example(``` /// chart.boxwhisker(size: (2,2), label-key: none, /// y-min: 0, y-max: 70, y-tick-step: 20, /// (x: 1, min: 15, max: 60, /// q1: 25, q2: 35, q3: 50)) /// ```) /// /// = Styling /// *Root* `boxwhisker` /// #show-parameter-block("box-width", "float", default: .75, [ /// The width of the box. Since boxes are placed 1 unit next to each other, /// a width of $1$ would make neighbouring boxes touch.]) /// #show-parameter-block("whisker-width", "float", default: .5, [ /// The width of the whisker, that is the horizontal bar on the top and bottom /// of the box.]) /// #show-parameter-block("mark-size", "float", default: .15, [ /// The scaling of the mark for the boxes outlier values in canvas units.]) /// You can use any `plot` or `axes` related style keys, too. /// /// - data (array, dictionary): Dictionary or array of dictionaries containing the /// needed entries to plot box and whisker plot. /// /// See `plot.add-boxwhisker` for more details. /// /// *Examples:* /// - ```typc /// (x: 1 // Location on x-axis /// outliers: (7, 65, 69), // Optional outliers /// min: 15, max: 60 // Minimum and maximum /// q1: 25, // Quartiles: Lower /// q2: 35, // Median /// q3: 50) // Upper /// ``` /// - size (array) : Size of chart. If the second entry is auto, it automatically scales to accommodate the number of entries plotted /// - label-key (integer, string): Index in the array where labels of each entry is stored /// - mark (string): Mark to use for plotting outliers. Set `none` to disable. Defaults to "x" /// - ..plot-args (any): Additional arguments are passed to `plot.plot` #let boxwhisker(data, size: (1, auto), label-key: 0, mark: "*", ..plot-args ) = { if type(data) == dictionary { data = (data,) } if type(size) != array { size = (size, auto) } if size.at(1) == auto { size.at(1) = (data.len() + 1) } let x-tick-list = data.enumerate().map(((i, t)) => { (i + 1, if label-key != none { t.at(label-key, default: i) } else { [] }) }) draw.group(ctx => { let style = styles.resolve(ctx.style, merge: (:), root: "boxwhisker", base: boxwhisker-default-style) draw.set-style(..style) plot.plot( size: size, axis-style: "scientific-auto", x-tick-step: none, x-ticks: x-tick-list, y-grid: true, x-label: none, y-label: none, ..plot-args, { for (i, row) in data.enumerate() { plot.add-boxwhisker( (x: i + 1, ..row), box-width: style.box-width, whisker-width: style.whisker-width, style: (:), mark: mark, mark-size: style.mark-size ) } }) }) }
https://github.com/skriptum/diatypst
https://raw.githubusercontent.com/skriptum/diatypst/main/diaquarto/README.md
markdown
MIT License
# Diaquarto: Diatypst Extension for Quarto
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/AnalisiDeiRequisiti/functions.typ
typst
MIT License
#let glossary(content) = { emph[#content#sub("G")] } #let team = { emph[SWAT Engineering] } #let modulo(value, modulo) = { int(value / modulo) == value / 4 } #let calculate_letter_code_from_importance(importance) = { if importance == "Obbligatorio" { return "O" } else if importance == "Desiderabile" { return "D" } else if importance == "Opzionale" { return "P" } return "?"; } #let generate_requirements_array(code, list) = { return list.enumerate(start: 1).map(enum_row => { let index = enum_row.at(0); let content = enum_row.at(1); let calculated_code = "R" + calculate_letter_code_from_importance(content.at(0)) + code content.insert(0, calculated_code+str(index)) return content }); } #let requirements_table(coded_list) = { table( columns: (auto, auto, 2fr,auto), inset: 10pt, align: horizon, [*Codice*], [*Importanza*], [*Descrizione*],[*Fonti*], ..coded_list.flatten().flatten().enumerate().map(content => { if (modulo(content.at(0), 4)) { return [*#content.at(1)*] } else { return [#content.at(1)] } }) ) }
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/C++/C++_notes.typ
typst
Creative Commons Zero v1.0 Universal
#set text( font: "Gentium Plus", size: 10pt, lang: "it" ) #set page( paper: "a4", header: align(right)[_Programmazione C++_], numbering: "1" ) #set par( justify: true ) #set heading( numbering: "1." ) #show par: set block(spacing: 0.55em) #set raw(lang: "c++") #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) #show raw.where(block: true): box.with( inset: 20pt ) #outline(indent: auto) #pagebreak() = Introduzione // == Filosofia del C++ // #include "Introduzione/Filosofia.typ" == Processo di compilazione #include "Introduzione/Compilazione.typ" == Tipi di dato #include "Introduzione/Tipi.typ" == Array #include "Introduzione/Array.typ" == Struct, enum, typedef #include "Introduzione/Struct.typ" == Stringhe #include "Introduzione/Stringhe.typ" == Casting #include "Introduzione/Casting.typ" == Ciclo di vita delle variabili #include "Introduzione/Ciclo.typ" == Funzioni #include "Introduzione/Funzioni.typ" == Doxygen #include "Introduzione/Doxygen.typ"
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/resources/typst/functions-vs-computations.typ
typst
Other
#import "../../src/thesis/imports/preamble.typ": * #table( columns: (2fr, 3fr, 5fr), stroke: none, align: left + top, table.header( [], table.vline(stroke: .5pt), [*Theoretically*], table.vline(stroke: .5pt), [*Practically*], table.hline(stroke: .5pt), ), [*Function*], [$I -> R$], [ $"eval"(F,I,emptyset) -> R$ ], table.hline(stroke: .5pt), [*Computation*], [$I times E -> R$], [ $"eval"(F,I,E) -> R$\ Reproducible if and only if\ $forall e_1,e_2 in E quad "eval"(F,I,e_1) = "eval"(F,I,e_2)$ ], )
https://github.com/Functional-Bus-Description-Language/Specification
https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/proc.typ
typst
== Proc The proc functionality represents a procedure called by the requester and carried out by the provider. The proc functionality might contain param and return functionalities. Params are procedure parameters and returns represent data returned from the procedure. The proc has associated signals at the provider side, the call signal and the exit signal. The call signal must be driven active for one clock cycle after all registers storing the parameters have been written. The exit signal must be driven active for one clock cycle after all registers storing the returns have been read. An empty proc (proc without params and returns) by default has only the call signal. However, if an empty proc has the delay property set, then it has both the call signal and the exit signal. A proc having only parameters has by default only the call signal. However, if a proc having only parameters has the delay property set, then it also has the exit signal. A proc having only returns has by default only the exit signal. However, if a proc having only returns has the delay property set, then it also has the call signal. The existence or absence of call and exit signals is summarized in the below table. #set align(center) #block(breakable: false)[ #table( stroke: none, align: center, columns: (2cm, 3.5cm, 3.5cm, 3.5cm, 3.5cm), table.vline(x: 1, start: 1), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 4, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 5)[Proc call and exit signals occurrence], table.hline(), [*Delay Set*], [*Empty*], [*Only Params*], [*Only Returns*], [*Params & Returns*], table.hline(), [*No*], [call], [call], [exit], [call & exit], table.hline(stroke: (thickness: 0.1pt)), [*Yes*], [call & exit], [call & exit], [call & exit], [call & exit], ) ] #set align(left) The proc functionality has following properties: *`delay`*` time (None) {definitive}` #pad(left: 1em)[ The delay property defines the time delay between parameters write end and returns read start. ] The code generated for the requester must provide a mean for calling the procedure.
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/academic/index.typ
typst
#import "multiple-choice-question.typ": multiple-choice-question
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/chained-call-last-indent.typ
typst
Apache License 2.0
#{ let tree = (1,2,3) let depth = 1 let build-node(tree, depth: 0, sibling: 1) = { repr(tree) + repr(depth) + repr(sibling) } let children children = tree.slice(1).enumerate().map(((n, c)) => build-node(c, depth: depth + 1, sibling: n)) children }
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/subjects/computer-science.typ
typst
MIT License
#import "../util/args.typ" #import "../theme.typ" /// Erstellt eine Tabelle zur Visualisierung eines Arrays mit Indizes und Inhalten. #let arr(data, len: auto, empty: none, start: 0, cell-width: 8mm) = { len = args.if-auto(len, () => data.len()) let d = data + (empty,) * calc.max(0, (len - data.len())) table( columns: (auto,) + (cell-width,) * len, fill: (c, r) => if c == 0 { theme.table.header } else if r == 1 { theme.bg.muted }, align: center, [*Inhalt*], ..d.map(i => if type(i) == int { str(i) } else { i }), [*Index*], ..range(start, start + len).map(str).map(raw), ) } #import "cs-docs.typ" as docs // Ziffern bis Hexadezimal #let _nary-digits = "01234567890ABCDEF" // string -> int #let nary-decode(num, base) = { if type(num) == int { num = str(num) } else if type(num) == content and num.func() == raw { num = num.text } else if type(num) != str { panic("Pass string, raw or integer as number.") } num = upper(num) // parse to decimal let result = 0 let exp = 0 while num.len() > 0 { let char = num.last() let fact = _nary-digits.position(char) if fact >= base { return 0 } num = num.slice(0, -1) result += fact * calc.pow(base, exp) exp += 1 } return (number: result, base: base, display: () => [(#text(1.2em, raw(result)))#sub[10]]) } // int -> string #let nary-encode(num, base, pad: none, from: 10) = { if from != 10 { // convert from base to decimal num = parse-nary(num, from) } else { // check type assert.eq(type(num), int, message: "can only convert numbers") assert(num >= 0, message: "can only convert numbers >= 0") } // convert to new base let result = "" if num == 0 { result = "0" } else { while num > 0 { let r = calc.rem(num, base) num = calc.floor(num / base) result = _nary-digits.at(r) + result } } if pad not in (none, 0) and result.len() < pad { result = "0" * (pad - result.len()) + result } return (number: result, base: base, display: () => [(#text(1.2em, raw(result)))#sub[#base]]) } #let nary-display(num) = { [(#text(1.2em, raw(num.number)))#sub[#num.base]] } // #import "cs-uml.typ" as uml #import "cs-db.typ" as db // ================================= // Bäume // ================================= #import "@preview/cetz:0.2.2" #let tree-node( node, draw-node: (node, ..args) => cetz.draw.content((), node.content, frame: "circle"), draw-empty: (node, ..) => cetz.draw.content((), h(1em)), ..args, ) = { if node.content != none { draw-node(node, ..args) } else { draw-empty(node, ..args) } } #let tree-edge(from, to, tree, node, draw-edge: (from, to, ..) => cetz.draw.line(from, to), ..args) = { if node.content != none { draw-edge(from, to, tree, node, ..args) } } #let tree(nodes, draw-node: auto, draw-edge: auto, ..args) = cetz.canvas({ let (pos, named) = (args.pos(), args.named()) cetz.draw.set-style(stroke: .6pt, padding: .33em) if "styles" in named { cetz.draw.set-style(..named.styles) let _ = named.remove("styles") } cetz.tree.tree( nodes, spread: 1.6, grow: 1.25, draw-node: if draw-node == auto { tree-node } else { tree-node.with(draw-node: draw-node) }, draw-edge: if draw-edge == auto { tree-edge } else { tree-edge.with(draw-edge: draw-edge) }, // ..pos, ..named ) })
https://github.com/yves147/bachelor-template-unidue
https://raw.githubusercontent.com/yves147/bachelor-template-unidue/master/math.typ
typst
== Math! (imported from math.typ) In case you need to include some math, the amsmath package 2 is already included in this document. To properly display some short formula like $e^(i pi) = −1$, you should use the embedded math environment using \$e^(i pi) = -1\$. For longer equations place two spaces around the inner body to make it look like the following one: $ arrow(Delta) times arrow(B) = mu_0 arrow(j) + mu_0 epsilon_0 diff(arrow(E))/diff(t) $ Welcome to the end!
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/substitution/alternate.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ### Alternate substitution === #tr[alternate substitution] // After one-to-many, we have what OpenType calls "one from many"; that is, one glyph can be substituted by *one out of a set of* glyphs. On the face of it, this doesn't make much sense - how can the engine choose which "one out of the set" it should substitute? Well, the answer is: it doesn't. This substitution is designed for features where the shaping engine is expected to pass a set of glyphs to the user interface, so that the user can choose which one they want. 除了一换多之外,OpenType中还支持一种“多选一”#tr[substitution],也即可以将一个#tr[glyph]替换为“集合中的某一个”其他#tr[glyph]。第一次知道这种功能时可能会觉得它没什么意义,毕竟排版引擎怎么知道到底应该#tr[substitution]成集合中的哪个#tr[glyph]呢?答案是它根本不做选择。这个功能的实际设计思路是,#tr[shaper]引擎需要将这一系列#tr[glyph]提供给上层用户界面,让用户来选择想要哪一个。 // One such feature is `aalt`, "access all alternates", which is used by the "glyph palette" window in various pieces of design software. The idea behind this feature is that a user selects a glyph, and the design software asks the shaping engine to return the set of all possible glyphs that the user might want to use instead of that glyph - all the different swash, titling, small capitals or other variants: `aalt`(All Alternates,所有备选)就是一个这样的特性。在各个设计软件中,用户选择了某个#tr[glyph]时,软件会向#tr[shaper]引擎询问用户实际想要的可能是哪些#tr[glyph],并把这些比如花体、标题字或者小型大写字母等变体的#tr[glyph]显示在一个称为#tr[glyph]样式版的窗口中。 ```fea feature aalt { sub A from [A.swash A.ss01 A.ss02 A.ss03 A.sc]; sub B from [B.swash B.ss01 B.ss02 B.ss03 B.sc]; # ... } ``` // Again, this is the sort of thing your font editor might do for you automatically (this is why we use computers, after all). 同样,字体编辑软件也可能会自动实现这个特性。(毕竟这就是我们使用计算机的原因嘛。) // Another use of this substitution comes in mathematics handling. The `ssty` feature returns a list of alternate glyphs to be used in superscript or subscript circumstances: the first glyph in the set should be for first-level sub/superscripts, and the second glyph for second-level sub/superscripts. (Any other glyphs returned will be ignored, as math typesetting models only recognise two levels of scripting.) 另一个可能用到这种#tr[substitution]类型的场景是数学公式的处理。`ssty`特性会为一个#tr[glyph]提供多种用于上标或下标处的变体。其中第一个#tr[alternate glyph]用于第一级的上下标,第二个#tr[alternate glyph]用于第二级。(后续的其他#tr[glyph]会被忽略,因为数学排版模型中只使用两层上下标。) #note[ // > If you peruse the registered feature tags list in the OpenType specification you might find various references to features which should be implemented by GSUB lookup type 3, but the dirty little secret of the OpenType feature tags list is that many of the features are, shall we say... *aspirational*. They were proposed, accepted, and are now documented in the specification, and frankly they seemed like a really good idea at the time. But nobody ever actually got around to implementing them. 如果你仔细阅读 OpenType 规范中已注册的特性标签列表,也许会发现很多需要用 GSUB lookup type 3 实现的特性。但关于这个特性列表有个隐含的小秘密,那就是其中很多特性都……怎么说呢,都太理想化了。它们作为提案是被接受了的,所以现在被写进了规范文档中。而且坦率地说,这些特性看起来都设计得非常好。但实际上没人真的有时间去实现它们。 // > The `rand` feature, for example, should perform randomisation, which ought to be an excellent use case for "choose one glyph from a set". The Harfbuzz shaper has only recently implemented that feature, but we're still waiting for any application software to request it. Shame, really. 比如`rand`特性,它用来产生随机效果,听起来像是“从一些#tr[glyph]中选一个”这类规则绝佳的用武之地。但 HarfBuzz #tr[shaper]直到最近才刚刚实现了对这一特性的支持,而且我们还在等待能有应用程序实际使用它。这真的有些惭愧。 ]
https://github.com/Tiggax/zakljucna_naloga
https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/sec/6zaključek.typ
typst
#set heading(offset: 1) #import "/src/additional.typ": todo #set text(lang: "sl") Bioreaktorji so ključni za industrijsko proizvodnjo različnih biofarmacevtskih produktov. Uporaba celic kitajskega hrčka je postala standard v industriji zaradi njihove visoke produktivnosti in zmožnosti post-translacijske modifikacije proteinov. V nalogi so podrobno obravnavane različne vrste bioreaktorjev, kot so serijski in bioreaktorji z dovajanjem. Poseben poudarek je na bioreaktorjih z dovajanjem, kjer se hranila dodajajo med procesom, kar omogoča boljše pogoje za rast celic in proizvodnjo produktov​. Zaključna naloga predstavlja podroben matematični model bioreaktorja z dovajanjem in uporabo celic kitajskega hrčka (CHO), ki so ključne za proizvodnjo biofarmacevtskih izdelkov zaradi njihove učinkovitosti in stabilnosti pri proizvodnji terapevtskih proteinov. Delo se osredotoča na optimizacijo parametrov sistema, ki zagotavlja zanesljivost modela s prilagajanjem eksperimentalnim podatkom. Optimizacija je ključnega pomena za doseganje maksimalne učinkovitosti in zanesljivosti bioreaktorjev, ki se uporabljajo v industrijski proizvodnji biofarmacevtskih izdelkov. Namen zaključne naloge je bil optimizirati delovanje bioreaktorja z uporabo simulacij, ki analizirajo vpliv različnih pogojev na rast celic in tvorbo produktov. To je bilo doseženo z modelom zasnovanim na diferencialnih enačbah, ki omogoča simulacijo dinamike celične rasti, porabe hranil in proizvodnje produktov. Enačbe so bile rešene z metodo Runge-Kutta, kar je omogočilo natančno napovedovanje gostote celic, koncentracije hranil in tvorbe produktov skozi čas. Za optimizacijo modelnih parametrov je bil uporabljen algoritem Nelder-Mead, ki je zagotovil dobro ujemanje modela z eksperimentalnimi podatki in s tem visoko zanesljivost simulacij. Matematični model vključuje masne bilance, kinetiko celične rasti po Monodu in procesno kontrolo z uporabo PID regulatorjev. Ta celovit pristop je omogočil simulacijo in napovedovanje obnašanja bioreaktorja pod različnimi pogoji. Matematično modeliranje bioreaktorjev je pomembno za razumevanje in optimizacijo procesov v biotehnologiji. Modeliranje temelji na sistemu navadnih diferencialnih enačb, ki opisujejo dinamiko gostote celic, koncentracije hranil in produktov skozi čas. V nalogi so uporabljene metode za reševanje teh enačb, kot so metoda Runge-Kutta in Nelder-Mead algoritmi za optimizacijo parametrov. Te metode omogočajo natančne napovedi in prilagoditev modela eksperimentalnim podatkom, kar je ključno za validacijo modela​. Optimizacija delovanja bioreaktorja vključuje prilagajanje različnih parametrov, kot so hitrost dovajanja hranil, začetne koncentracije celic in hranil ter maksimalna specifična hitrost rasti celic. V nalogi so predstavljene različne simulacije, ki prikazujejo vpliv teh parametrov na končne rezultate, kot so gostota celic, poraba glukoze in glutamina ter koncentracija končnih produktov. Rezultati simulacij kažejo, da je natančno uravnavanje teh parametrov ključno za optimalno delovanje bioreaktorja​ Celoten model in simulacije so implementirane v programskem jeziku Rust, kar omogoča učinkovito in hitro izvajanje kompleksnih izračunov. Poudarjena je pomembnost uporabe sodobnih programskih orodij in metod za reševanje zahtevnih problemov v biotehnologiji. Aplikacija in podatki so dostopni na GitHub repozitoriju, kar omogoča preglednost in nadaljnjo uporabo ter razvoj modela s strani drugih raziskovalcev in strokovnjakov v industriji​. Zaključna naloga ponuja robusten in prilagodljiv okvir za simulacijo in optimizacijo bioreaktorjev z dovajanjem in uporabo CHO celic. Predlagane prihodnje izboljšave, kot so vključitev bolj realističnih modelov življenjske sposobnosti, izboljšane simulacije produktov in napredne kontrole kisika, obetajo še večjo natančnost in praktično uporabnost modela v dejanskih operacijah bioreaktorjev. Te izboljšave obetajo še večjo natančnost modela in njegovo uporabnost v realnih industrijskih pogojih​. S tem raziskava odpira nove možnosti za optimizacijo bioprocesov, kar lahko vodi do bolj ekonomične in učinkovite proizvodnje pomembnih terapevtskih proteinov in drugih biofarmacevtskih izdelkov, kar je ključno za napredek v medicini in farmaciji. Z vključitvijo realnih eksperimentalnih podatkov in sodobnih optimizacijskih algoritmov ponuja robusten in prilagodljiv okvir za nadaljnje raziskovalno delo z modeliranjem bioreaktorjev.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/048%20-%20Dominaria%20United/004_Homecoming.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Homecoming", set_name: "Dominaria United", story_date: datetime(day: 12, month: 08, year: 2022), author: "<NAME>", doc ) Every plane was different, and everyone who walked between them knew; it was impossible #emph[not] to know. The air on Innistrad was not the air on Zendikar was not the air on Kaldheim. The flowers weren't the same, and so neither was the pollen; the songs of the small birds in the trees never quite aligned. Liliana knew no two planes were identical, had known since the moment her spark awakened and carried her involuntarily to Innistrad, land of deep, slow shadows and rich Gavony honey. She had never found anything sweeter anywhere else in the Multiverse, and her morning tea always suffered from its absence. So yes, every plane was different, and Liliana had known that long before she came to Arcavios and the hallowed halls of Strixhaven, but as she had never tried to make one of those unfamiliar planes her home, she had never considered how, as the days stretched out in classes and controlled chaos, in hours without end, the nights might start to wear on her. The night sounds were different here than they were on Dominaria. The frogs sang a different song. She hadn't expected it to grow so hard to carry. She was happy enough during the days. She was helping to shape young minds, molding them with her words. Given time, she could guide them away from the countless mistakes she'd both seen and made during her own youth, when power had seemed limitless and consequences, while unavoidable, had always been something she could put off for another day. There were other Planeswalkers on campus, which was something she hadn't been anticipating when she'd come to hide herself away in academia, but the Kenriths were young enough to be unaware of the details of her past, and when she'd been a Witherbloom student, she hadn't been in the habit of bringing up her professors in casual conversation. Unless their travels through the Blind Eternities brought them into contact with one of the people who blamed her for everything she'd ever been adjacent to, they were unlikely to ever hear her name in conjunction with her past, or to mention her to others. <NAME>, Mistress of Death Itself, could fade away, and <NAME> could teach forever. If only she could learn how to sleep through the Arcavios nights. She stood at the window of her personal rooms, looking out over the necroluminescent glory of Sedgemoor as it glowed faintly in the darkness. It hadn't changed since her own school days, not really, save in the sense that Sedgemoor was constantly changing, a landscape in eternal blossoming, decaying flux. The first time she'd seen it, she'd thought it was the most beautiful thing in all the planes. She still thought so. But oh, she remembered it being so much easier to #emph[sleep] in those days, before the War, before the Chain Veil, before the Gatewatch and <NAME> and Gideon~ His name was a broken bell hanging where her heart should have been, and every time she rang it, she remembered she deserved the sleepless nights. She deserved so much worse than this, than her comfortable rooms and the view of her beloved Sedgemoor, she deserved the dissolution that had fallen to her comrade— "There you are, Lili," purred a voice, familiar and cold and enticing all at the same time. "I was wondering if I'd lost you forever." Her hands tightened on the teacup she was holding, practically a spasm, but she didn't turn. "Come now, my dear, you can't have believed that I'd abandon you so easily as all that. I know it's been a while, but in my defense, you were rather wallowing in the loss of all that power, and it seemed unlikely that my presence would speed the matter along in any measurable way." Liliana, greatest necromancer in the Multiverse, leader of armies and conqueror of death itself, took a deep breath, set her teacup down on the windowsill, and turned. Behind her was a man, apparently human, save for his eyes, which were a beaten gold brighter than they had any right to be. His hair and beard were white, impeccably trimmed and shaped, and his clothing, although old-fashioned, was clearly tailored to his measurements. He looked like nobility. He looked like power. He looked like he hadn't aged a day since the first time he'd appeared to her, sweet lies in his mouth and false consideration in his words. #figure(image("004_Homecoming/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "I thought you had finally tired of me," she said. "I thought we were done with this foolish game of~ is it cat and mouse when the mouse pursues the cat? I don't need you. Leave me." "To what? A joyless life of grades and badly written essays? Of pests and pointlessness?" He laughed, and it was a bitter sound. "You know this won't hold your attention long. You need novelty. You need #emph[power] . Come home to me, and all you desire can be yours at last." She choked her own laughter down. "I doubt that. I sincerely, sincerely doubt it." "You know what I can offer you. You know what we can be together." "I know there are deaths I can't undo," she snapped. "I know that sometimes, gone is gone, and sometimes, all I can do is honor the fallen." "By counting yourself among them?" He looked at her sadly. "Come #emph[home] , my Lili. Come back to where you grew as a fresh spring flower, where first I plucked you for my own. Come home to me." Then he was gone, becoming a whirling storm of ravens, all of them flying at her, and past her, out the open window, knocking her teacup to the floor. The sound of shattering porcelain penetrated her nightmare, and Liliana sat up with a gasp, clutching the thin blanket she'd been curled beneath to her chest. She looked frantically around the room. No man; no birds. No footprints or fallen feathers. She was alone. Alone with the frantic hammering of her heart, and the metallic taste of fear in her mouth. She pushed her covers aside, sliding her feet to the floor and into her slippers, and rose, starting toward the fire. A cup of tea would take the taste away. It was hard enough to fall asleep on these hot Arcavios nights; the proper blend of herbs and florals could only ease the way~ Something crunched under her foot. She stopped, looking down at the remains of her favorite teacup, then bent, touching her fingertips to the liquid splashed all around them. It was still warm. As she looked up toward the open window, she almost thought she could hear him laughing. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The next day's lessons dragged by in a haze of students, awkward silences, and near-botched lessons. After the third anxious Witherbloom second-year exploded a pest in an impressive but useless spray of magic, Liliana dismissed her principles of necromancy class, telling them to go work on their essays before they disappointed another teacher as badly as they had disappointed her. Closing her classroom, she turned toward the Biblioplex. Hallucination, spirit, or uncontrolled manifestation of her own power, it didn't matter; this had to stop. It would have been bad enough if this had been the first time he'd appeared to her on Arcavios, but he'd been showing up for months, his visits accelerating in frequency, until it was a rare night when she could sleep all the way through to morning. The fatigue was setting in. If this went on much longer, she would have to involve someone else, and that meant putting them at risk. No. She didn't do that anymore. Whatever this was, she needed to end it on her own terms, and she needed to end it alone. If he was real—and she increasingly believed he might be, after everything he'd shown her, everything he'd told her, everything he'd #emph[done] —the Biblioplex would tell her what she needed to know. It might not contain all the knowledge in the Multiverse, but it came close enough for any reasonable being's purposes. The sight of the imposing Professor Vess striding across the school in the middle of the day was unusual, but not enough to draw too much attention. She made her way swiftly to the great library, requisitioning one of the small poleboats necessary to cross to the section on ancient Dominarian history that she had located some months before, and began her search. She had been flipping through ancient tomes and consulting dusty scrolls for the better part of an hour when he spoke, once again from behind her, as he so often seemed to be. The shadow at her heels, the predator on her trail. "You aren't going far enough back," he said. "If you're looking to bring me home, my Lili, you'll need to look much deeper than you have been." She snapped the book she was holding shut. "So you're telling me you're real, then." "I'm telling you I was real, once, and might well be again, if that's how the stars align. I'm telling you to come home to me. If this is the armor you feel you need to wear for our reunion, knowledge and ancient names, then I'll help you find them, as I can." Liliana whirled around, glaring at him. He looked impassively back. "I told you to leave me alone," she hissed. "I told you I was done with you. I will not be used. I will not be a weapon in another monster's hands." "But will you be a monster on your own?" He spread his own empty hands. "You're so close, Lili. You almost have everything you need. Come home, and I can give you what you're missing." "Get. Out." "As you like. But you'll come to me. You always come to me." Then the man was gone and the ravens filled the space where he had been, spiraling into the air on charcoal wings, feathers knocking dust from the spines of ancient tomes, talons pulling one such volume from the shelf and sending it crashing to the floor. Liliana lunged, almost catching it, and when the birds were gone, picked it up and looked at the cover. #emph[A History of Terisiare] said the title. No author was listed. Liliana frowned, carrying the book with her to the nearest table, and as she sat, she began to read. When she rose, some hours later, she did so with a new, if terrible, understanding, and with a name, one that she dared not think too hard, lest it give him power he didn't currently possess. But he had a name, and that meant he existed outside her mind. He wasn't her creation, even if she was in some ways his. The monster that haunted her dreams, that had taken a frightened, powerful young girl and shaped her into a terrifying, borderline villainous woman~ he was real. He could be stopped. He could be destroyed. She could cleanse this tiny bit of evil from the Multiverse, for Gideon's sake. Holding that thought firmly in mind, she left the Biblioplex for the administrative offices to request a leave of absence. The process was easier than she feared it might be, made easier by her distracted state over the past few weeks. Students had been unhappy, and their complaints had begun to spread; while her position was still more than safe, a little time away seemed advisable. For everyone's sake, really. It was less than a day later when she stepped up to the edge of the Sedgemoor, looking out over its strange, beloved landscape, and closed her eyes. "All right, you bastard," she said. "I'm coming home." The blackness rose around her as her spark flared to life, coalescing into a cloud of impenetrable dark. When it cleared, some seconds later, <NAME> was gone. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) He had bid her to come home to where he first met her, where he first convinced her to listen to his truths that would have been kinder as lies; that meant Dominaria, and more, it meant the Vess family estate. Appearing in a swirl of black on the small rise behind the house, Liliana looked out upon the ruins of what had once been her entire world. The ground was a swampy mess, soil eroded and corrupted. Odd, that she should love a marsh so deeply when a marsh had destroyed her home. <NAME> was a ruin, more decrepit than could be explained by time alone, and the stronghold that should have held it in protective shadow loomed like a rotten limb jammed into the ground, tilted and unsteady. Liliana took a deep breath and started walking toward the house, not allowing her magic to shield her from the mud squelching underfoot or the water seeping into her shoes. #emph["Come home,"] whispered the voice out of her past, echoing between her ears, implacable and ancient. #emph["Come home to me."] She walked on, toward the ruins of her family home, memories of better times trying to flood her mind. Long days of training with <NAME> and the Forward Order, of running through the sunlit fields with her brother, of tumbling in the hay with the village boys attracted by her budding charms. Liliana pushed those fragments of idyllic light aside. That girl had been a healer and a general's daughter, destined to decorate a court and hang from a noble's arm, a bauble at best, not a diamond in her own right. Everything she had suffered, everything she had lost, it had all served to make her more than that girl ever could have been. She had no regrets. Nor would she allow them to seep into her mind as the corruption still seeped through the soil, a reminder of Belzenlok which Dominaria might never expel. The house was unstable, she could see that clearly, and so she veered around it, moving toward the graveyard where generations of supplicants and Vess ancestors were buried. #figure(image("004_Homecoming/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) The soil there was firmer, less yielding, as if even Belzenlok and Josu had been able to overcome the weight of so many of the dead. She walked until she reached the great Dominarian oak at the graveyard's center, then sat, her back to the trunk, and closed her eyes. When she opened them again, the house was as it had been in her youth, the light golden and innocent in its brightness, and everything had the faint gleam around the edges that told her she was dreaming. If that weren't enough, the Raven Man stood before her, the only thing in the recreation of Vess Manor whose outline didn't shine but seemed instead to swallow the light. "So I'm here, and I'm asleep, which I know you like, since I'm less likely to stab you when I'm unconscious," she said. "What do you want from me?" "I wanted you to find me, and it seems you have. You've grown into what I knew you could become. You're almost ready for me." "Ready for what, #emph[Lim-Dûl] ?" She stressed his name as hard as she could, watching for his reaction. To her disappointment, he simply laughed. "It's been some time since I've heard that name spoken, in or out of dreams." "If it pleases you, I won't do it again. If it harms you, I'll never stop." He laughed again, and this time, it was the cry of a raven, primal and hungry. "Oh, Lili, you wonder why I've always wanted you so? Why you were the prize I chose to cultivate? We could work miracles together. We could—" Liliana glared at him. "Tell me why you wanted me to come here." He paused. "Is it not enough that I wanted to be reunited with my dearest Liliana?" "No." "You know my name. What did it tell you of my history?" "Great necromancer. Tyrant. Defeated and disgraced, bound into a magical object that was then lost." "Then you know I do not rest, nor ever shall. Even you, Lili, couldn't lay me down if you tried. The chain of which I am a single link is too long and too powerful." He sighed. "We thought to add you." "You mean you thought to have me for your own," she snapped. "You were molding me into your perfect vessel. Did you ever ask if the Liliana Vess you were crafting was the one I desired to be?" "Does any parent ask?" He shook his head. "You would have been my masterpiece, but your own choices have ruined you." She stood, stepping away from the tree. "Then why did you call me here?" "Because I'm not the only one here." He looked at her, golden eyes solemn as the grave. "They will destroy everything if allowed. I once dabbled with them, you know, but they were always more trouble than they were worth, it cost me #emph[two ] lives. They'll destroy me if they can, and they'll destroy you as well. They'll destroy everything." "So you called me to be your #emph[weapon] ?" "Yes, and for once, no. I called you to be Dominaria's weapon. Fight for the plane that birthed you. Save me, save them~ save yourself." Lim-Dûl started to say something more, then stopped, eyes widening in what looked very much like fear. "Save yourself," he repeated, and snapped his fingers, bursting into a cloud of black-winged birds. They flew in all directions, cawing loudly, and when the last of them was gone, the landscape was as it had been when she arrived. The hazy edges of the dream had dissipated; she was awake, and—if he spoke truly this time—she was in danger. Liliana stood, looking around the desolate landscape, trying to find anything that had changed since her last visit. The marshy ground was never the same from moment to moment, but that was to be expected; the walls of the house creaked and teetered, but decay was natural, even when brought about by unnatural means. She was seeking something more. Something deeper, something darker, something #emph[wrong] . She reached out with a thread of magic. She—and by extension, it—had been born here, and even in its current corrupted state, the land knew her. It surged to answer her presence like a starving dog answering its master's call. She stroked it gently as she continued to reach out, enjoying the moment of connection, of familiarity, of— Her magical thread hit a pocket of something so alien and other that it repulsed her, turning her power back on itself and pushing it away. It wasn't corruption. Liliana knew corruption. She knew what it meant when a land turned foul. It wasn't rot or decay, but it was a taint, all the same, new and horrific and ancient all at once. She pulled her power back to home and looked in the direction she had been reaching, trying to understand what it was she'd brushed against. She didn't move. For the moment, it felt as if the only safe ground she had was the ground that belonged to her family's dead. But since when had she sought safety? Liliana took a breath, dropped her chin toward her chest, and marched into the mire, heading for the trace of #emph[wrongness] . If it were as alive and terrible as it felt, it had to know she was there. Better to face it head-on than to hide from it like the child she would never be again. Alone, <NAME> walked into the dark as a solitary raven feather sank into the muck behind her. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The forest around the estate had been consumed by the swamp, but many trees remained, jutting rebelliously upward even as their roots rotted and their leaves dropped away. One day they would topple, and the transformation of this land would be complete. Liliana kept walking, not quite willing to extend another thread of magic outward to verify that the wrongness remained. What she'd touched did not give the impression of being something that would so easily let go. Her awareness of the land continued trembling at the edge of her mind, the estate grateful for her return in a way that it would never have been when it was true forest, green and growing lush, dedicated to life. That had been another Liliana's land. This land, though~ this land belonged to her, all the way down to its bones, and it was terribly happy to have her back. She walked on, confident in her connection to the ground beneath her feet, and in her ability to remove the thing that shouldn't be here. A new smell appeared in the air, metallic but not metal at the same time, neither blood nor rust, but sharp on the back of the tongue as either of those things might be. It smelled #emph[wrong] . She stopped walking. If she was close enough to smell whatever was happening here, she was close enough. Black smoke gathered around her hands as she focused on the place where she'd felt the change to her ancestral home, swirling and twisting with the force of her command. Liliana narrowed her eyes. To have been called here was bad enough; to have been called here to face some unseen danger, with no more than a few grudgingly given words of warning, was an offense. She was still pulling the magic to her when a figure stepped out of the trees. Her skin was the chalky white most common among the kor, and she had no hair, neither atop her head nor around her eyes, which wept constant streams of viscous black liquid. More of the liquid dripped from her left hand, seemingly seeping from her skin, and things that looked like tubes extended from her back, vanishing under her clothes. #figure(image("004_Homecoming/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Stay where you are," she said, and her voice belonged to a construct, not a living thing, filled with echoes and horrible harmonics. "You have entered our gathering grounds, and you are thus forfeit." "I've entered my own family lands, and nothing about me is or has ever been forfeit," Liliana replied. "I'll stay. You'll go." "No," said the figure, and smiled the horrible smile of someone who had forgotten how such expressions were meant to be shaped, how they should be worn. "We own this place. It is too late for you. You should never have come here." The faintest of splashes from behind her caused Liliana to look around, confident in what she'd find there. Instead of the ordinary ambush she anticipated, she faced a horror. Death held no mysteries nor frights for Liliana: she had seen it in all its forms, from the peaceful to the profane. Decay was natural. Reanimation was natural as well, in its own way, and nothing to shy from. But these creatures~ The figures arrayed behind her had been somehow twisted out of true with their own natures, patched together from dead and living flesh at the same time, and the dead flesh did not kill the living, and the living flesh did not resurrect the dead. Connections of artificial tissue and that dripping, impossible oil held them together, silver sutures and gleaming wires, and the sight of them was repulsive and entrancing at the same time. They seemed to have been created from disparate sources, human and elf and kor and merfolk and others, dismantled and reassembled into something more efficient than the sum of its parts. All of them had claws, or fangs, or scythe-like blades where their forearms should have been. Some had extra limbs, or mandibles, and they were watching her with dispassionate eyes. Her life or death didn't matter to them. They would kill her without consideration, or regret. #figure(image("004_Homecoming/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) She glanced back to the kor woman who'd appeared first. She was watching her still. She hadn't moved. "You can be of use, yet," she said. "The remnants of the spirit cleave to you. It called you here. We would have it." "The Raven Man?" she asked. If this strange figure didn't have his name, she wasn't going to provide it. "What business can you have with him?" "That business is our own," she replied. "What business do you have?" "He's haunted me since I was a young woman, and I would be free of him." "Then give him to us, and we will free you." The kor woman smiled again. "Phyrexia is the greatest of freedoms." "I think I would prefer to pursue freedom on my own," said Liliana. How was it she had never faced Phyrexia before? She knew the stories, of course—she was a daughter of Dominaria, and none who walked the Blind Eternities did so without knowing of Yawgmoth's great betrayal. But she had thought the contamination contained on what had been Mirrodin, and the fact that she had missed that battle made her no less aware of the danger she was suddenly in. She released the power she'd been collecting, reaching instead for the strength of her spark, the connection that would let her flee this place for something more hospitable. It leaped to her call, and for a moment, the temptation to simply planeswalk away and leave this problem for someone else was strong. She looked at the kor woman, who looked back, not seeming to realize what she was doing, not seeming to see her as any sort of threat. Well. She would teach him the error of that way of thinking soon enough. "Why here?" she asked. "Why my family's lands?" "The spirit we pursue is anchored to an object somewhere in this place," she said. "It has been sunk deep into the ground, sleeping and forgotten. Our excavations will bring it to light." If she left, they would dig up the relic that anchored the Raven Man, and they would take him away. She would never be haunted again. Lim-Dûl would finally be forgotten, and no one else would be tangled in his incomprehensible machinations. That, more than anything, decided what she did next. She released the slow draw of power from her spark and looked at the kor woman. "What is your name?" "I have the honor to be called <NAME>-Kor," she said. "I am One, but I am also distinct, for the sake of what must be done. Why do you ask me?" "So I know what to put on your headstone," said Liliana blithely. She reached again for the magic sleeping in the swamp, and this time she grabbed it and yanked it tight as a vibrating wire, the air around her growing thick as ectoplasm and cold as the grave. The flesh-and-steel horrors that had surrounded her froze for a moment, too surprised by this transition to react. Liliana turned and ran. The art of Witherbloom was in growth and decay. The magic of life had never answered easily to her, but the magic of death did, and the swamp was a sepulcher in its own right, filled with the bones and bodies of a thousand smaller creatures. Elas il-Kor had eight terrors of Phyrexia's own design. Liliana had the dead of an entire biome. As she fled and the Phyrexians gave chase, they found themselves assaulted on all sides by snakes, rodents, deer, even a large dead dog long since rotted down to bone and scraps of tendon. Liliana's creatures weren't true zombies: once Liliana's attention was elsewhere, they'd go back to their graves. They rose only to obey her command to slaughter and would fall again as soon as they were done. Elas il-Kor watched, seeming almost amused by the overwhelming flood of undead beasts. They were individually no match for the Phyrexians, who sliced and struck and ripped them into pieces. Still, their very numbers told her everything she needed to know about the strength of this necromancer. She was an unexpected bonus of this long and irritating assignment. They were warriors, not archaeologists! But what Sheoldred commanded, she would have, and Elas il-Kor was honored to serve in any way at all. If it now seemed that service might yield an unexpected bonus to strengthen the Phyrexian position on Dominaria, all the better. "I want her alive," she said, perfectly calm, as her team finished slashing Liliana's assault force out of the air and started after her. She followed behind at a more sedate pace, unhurried. Phyrexia didn't need to hurry. Phyrexia always won, in the end. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It was almost insulting, thought Liliana, running for the graveyard where more powerful bones awaited her call; they weren't chasing her. They were #emph[following] , which was something altogether different. If not for the fact that she was outnumbered, she would have stopped, turned, and shown them precisely why they owed her a proper pursuit. But she hadn't lived as long as she had by being foolish, and so she ran, feeling her connection to the earth beneath her strengthen with every step, until she was standing above her ancestors. Then she stopped, and turned, and faced the forces of Phyrexia. Six of them remained, <NAME>-Kor and the five~ soldiers who answered to her command. All were artificial to some degree or other, transformed as the swamp had been, pulled away from their true natures. Well, she wasn't the one to purify them. That had never been her role in the Multiverse. She raised her hands, grasping the power of a dozen generations of the dead, drawing on what they could have been and never were, and lashed out at the closing Phyrexians in a terrible blast of rotting light. They were artificial, yes, but they were also natural, and the parts of them that were flesh knew how to rot. However, thanks to the unnatural taint running in their veins, it seemed they no longer knew how to die. They shrieked as their bodies bristled with gangrene and withered from necrotizing corruption, but they kept racing toward her, more visibly artificial now than they had been only a moment before. Their flesh dripped away as they advanced, unmade by the ravages of swift decay. <NAME>-Kor drew a javelin from her back, the wickedly barbed tip dripping with some foul, viscous substance. Liliana couldn't move without releasing the hold her magic had wrapped around the Phyrexians, and so she glared at her, holding her place, holding her ground as she drew back and prepared her throw. Elas was a master marksman. She didn't aim so much as simply positioned herself and trusted her arm to find its target. The spear was a combination of the same metal that gleamed from the bodies of her soldiers and fire-hardened wood that any kor warrior would have been proud to carry. Liliana hoped the wood on the spear was more dominant than it seemed. The metal on the bodies of the others was still clean and untarnished, not rusting or rotting as their bodies were. The workings of death could look very much like the passage of time, when focused correctly. Elas il-Kor threw. The javelin flew. Liliana pulled harder at the death-soaked, corrupted ground, yanking demonic taint and natural death into herself as fast as she ever had, and doing it with nothing but herself to depend on. No Chain Veil, no demonic contract. Just Liliana, the bones of her own dead, and the land. And deep below the rest, the vessel that had contained a necromancer who would fell an empire, who had been possessed by one greater than himself, who had been grooming her to become his tool: a simple ring. Her questing magic, seeking further reservoirs of power, grabbed hold of it, pulling as much strength from its reservoir as could be managed on instinct alone, without true and focused intent. Overhead, a raven cried, and for a moment, Liliana #emph[saw] . Saw the first Dominarian mage to tap into the power of death itself, the first man to hold the strength of the grave in his hands and make it dance to his whims. Saw his spirit, his power, pass down into his own student, possessing her, and then a new vessel not long after, over and over again, all the way to Lim-Dûl. Saw his ring change hands until it fell into those of her ancestor, who buried it here to hide it from those who would abuse it—but that wasn't the end. She saw the Raven Man, a piece of the ancient necromancer's fractured soul, stirring in a vessel she knew all too well, called to him from across the planes by a young woman's necromantic dabbling. She saw the same woman finally sever the link when she freed herself from the Veil, the chain stopped cold by an absence of hands to hold it, and saw what had been meant for her. She had been intended as one more link in a line stretching back to that first, now-nameless mage, her will subsumed to the remnants of his, her soul remade in the image of those who had come before her. The ring whispered to her of power without limit if she would just give in, just become the vessel Lim-Dûl crafted her to be. Just #emph[become] Lim-Dûl, in a way; she would still be <NAME>, but the part of her that loved her students, loved Sedgemoor, grieved for Gideon and for her brother~ that part would fade mercifully away. #emph[I yield to no one] , she thought, shoving the artifact's promise aside, and grabbed only for the power that surrounded it, the power that could be hers without accepting the burden of Lim-Dûl's mantle. Liliana unleashed a roiling wave of black fog to sweep over the decaying Phyrexians, catching the javelin in mid-flight. The wood rotted instantly away, leaving gleaming metal behind. Elas il-Kor's throw had been true, but the sudden loss of the wood skewed the javelin's trajectory, and it struck Liliana in the shoulder. She screamed. She was a powerful mage, yes, and a warrior in her own right, but silence in the face of pain had never been a Dominarian virtue, and the javelin's point burned like ice and acid. Reaching up, she yanked the javelin free. Her tattoos gleamed gold. If the wave of roiling darkness had seemed absolute before, the next pulse flowing outward from her body made it seem like the first had been nothing but a light fog. #emph[This] was true blackness: #emph[this] was death given leave to run through the world of the living without fetters. The Phyrexians caught in the initial wave staggered and dropped to their multijointed knees, exposed metal finally succumbing to tarnish as it decayed. Elas il-Kor was too far back for the cloud to reach. She watched, a small frown the only sign of her disapproval, as her troops went down and moved no more. Then they began to stir again, rising jerkily from the ground and turning to look back at her with eyes that were nothing more than pits of gleaming blackness. They advanced toward Elas as the cloud cleared, revealing Liliana with hands raised and tattoos shining, directing her new force toward their former leader. <NAME>-Kor took a step backward. "This is a perversion!" she shouted. "Once you belong to Phyrexia, you remain within Phyrexia!" Liliana gritted her teeth, struggling to hold her reanimated minions. She wasn't wrong. She could feel the taint that lingered in their bones struggling to reassert itself; when she let them go, they would rise again, returned to their horrific family. But for now, this was Vess ground, and she was rooted to the dead beneath her, and they were hers before anything else. <NAME>-Kor took another step back. Then, choosing survival over her soldiers' fate, she fled. Liliana sagged where she stood but held tight to the Phyrexians. As soon as she loosened her grip, she knew she would lose them. The ring she'd sensed below her, the overflowing well of necromantic power, was deep enough that she lacked the strength to bring it to the surface while holding her new thralls. Without lithomancy, she would have to move it through the hands of the dead, one passing upward to the next, and that could take days. But she couldn't leave it where it was, either. What little she knew of Phyrexia, from the stories and the histories, told her that if they wanted something, it was better to deny them. Pulling the remaining strength from the bones beneath her, she pushed the artifact downward, commanding the ancient dead to hide the object away, as far beneath Dominarian soil as possible. Finally, she released the Phyrexians to fall and twitch, then gathered what magic yet slept within her and stepped into the Blind Eternities, vanishing in a swirl of blackness. She would return here soon enough, to cleanse her land and protect what she had buried here. She only hoped it wouldn't be to find the dead had turned against her. But for now, Arcavios and Sedgemoor waited to clean her wounds and replenish her reserves. From the shadows, a golden-eyed man watched her go, content that he had pulled her strings one more time. She was still his creature, even after everything. She had protected him, in the end. And one day, she would come home.
https://github.com/saYmd-moe/note-for-statistical-mechanics
https://raw.githubusercontent.com/saYmd-moe/note-for-statistical-mechanics/main/contents/PartII/Chp05.typ
typst
#import "../../template.typ": * == 近独立子系 === 定域子系 ==== _Maxwell-Boltzmann_系统的最可几分布 对于 _Maxwell-Boltzmann_ 分布,系统量子态数:$ W_(#[_M.B._])({a_lambda}) = N!/(product_lambda a_lambda !) product_lambda g_lambda^(a_lambda)\ ln W_(#[_M.B._]) approx N ln N - sum_lambda a_lambda ln a_lambda + sum_lambda a_lambda ln g_lambda = N ln N + sum_lambda a_lambda ln g_lambda/a_lambda\ $令$delta ln W_(#[_M.B._]) = 0$,可以得到一组约束方程:$ cases( display(delta ln W_(#[_M.B._]) = -sum_lambda ln(a_lambda/g_lambda) delta a_lambda) \ display(delta N = sum_lambda delta a_lambda) = 0\ display(delta E = sum_lambda epsilon_lambda delta a_lambda) = 0 ) $使用_Lagrange_乘子法,引入两个乘子 $alpha, beta$ #footnote([后面可以得到,$alpha=-beta mu, beta = 1\/k T$ 分别表示化学势和热力学温度。]) ,得到:$ delta ln W_(#[_M.B._]) - alpha delta N - beta delta E = -sum_lambda (ln a_lambda/g_lambda+alpha+beta epsilon_lambda) delta a_lambda = 0\ arrow.double ln a_lambda/g_lambda+alpha+beta epsilon_lambda = 0 $得到_Maxwell-Boltzmann_分布:$ #box( inset: 5pt, stroke: black)[ $display(tilde(a)_(lambda; #text[_M.B._]) = g_lambda e^(-alpha-beta epsilon_lambda))$ ] $ #note[ 上述讨论的能级是量子化的,如果是经典系统,那么子相空间中的一个相格 $h^r$ 代表一个量子态,用 相空间体积元/相格大小 代表简并度 $g_lambda = dif omega \/ h^r$,求和转化为子相空间中的积分。 ] ==== 子系配分函数与热力学量 对于定域系统 (_Boltzmann_统计) ,引入子系配分函数 $Z$ :$ Z equiv sum_lambda g_lambda e^(-beta epsilon_lambda) = a_lambda dot e^(-alpha) $使用子系配分函数来表示热力学量的形式是非常简洁的。 - *总粒子数:* $display( N = sum_lambda a_lambda = sum_lambda g_lambda e^(-alpha-beta epsilon_lambda) = e^(-alpha) dot Z )$#v(1.5em) - *内能:* $display( U = macron(E) = sum_lambda epsilon_lambda macron(a)_lambda = e^(-alpha)dot sum_lambda epsilon_lambda g_lambda e^(-beta epsilon_lambda) = -N/Z diff/(diff beta) Z = -N diff/(diff beta) ln Z )$#v(1.5em) - *外界作用力:* 有微功$display( \u{0111}W = sum_l macron(Y)_l dif y_l = sum_l (diff E)/(diff y_l) dif y_l )$于是得到外界作用力#v(1.5em)$display( Y_l = (diff E)/(diff y_l) = sum_lambda (diff epsilon_lambda)/(diff y_l) macron(a)_lambda = - N/Z (1/beta diff/(diff y_l)Z)=-N/beta diff/(diff y_l) ln Z )$#v(1.5em) - *热量:* $display( \u{0111}Q = dif macron(E) - sum_l macron(Y)_l dif y_l = sum_lambda epsilon_lambda dif macron(a)_lambda )$#v(1.5em) - *熵:* $display( S = N k (ln Z - 1/beta diff/(diff beta) ln Z) + S_0 )$#h(2em)由于 $T, 1/beta$ 均为 $\u{0111}Q$ 的积分因子,所以有#v(.5em) $beta = 1\/k T$,其中有_Boltzmann_常数 $k = 1.38 times 10^(-13) J dot K^(-1)$; 综上,给出近独立定域子系使用子系配分函数表示的宏观热力学量:$ cases( display(Z = sum_lambda g_lambda e^(-beta epsilon_lambda)) \ display(N = e^(-alpha) dot Z) \ display(U = -N diff/(diff beta) ln Z) \ display(Y_l = -N/beta diff/(diff y_l) ln Z) \ display(S = N k (ln Z - beta diff/(diff beta) ln Z) + S_0) ) $这些表达式建立起宏观热力学量与微观状态之间的联系,可以看到只要我们得到子系配分函数 $Z$ 就可以计算出宏观热力学量。 ==== _Boltzmann_关系 对于近独立定域子系:$ ln W_(#text[_M.B._]) &= N ln N - sum_lambda a_lambda ln a_lambda/g_lambda \ &= N ln N - sum_lambda macron(a)_lambda ln macron(a)_lambda/g_lambda \ &= N ln N - sum_lambda macron(a)_lambda (-alpha-beta epsilon_lambda) \ &= N ln N + alpha N + beta macron(E) \ &= N (ln Z - beta diff/(diff beta) ln Z) $于是得到_Boltzmann_关系:$ S = k (ln Z - beta diff/(diff beta) ln Z)= N k ln W_(#text[_M.B._]) $只需要得到系统总量子态数 $W_(#text[_M.B._])$,就可以通过简单的取对数得到总熵 $S$ 。 ==== 定域子系的经典极限条件 当温度足够高,使得能级间隔 $Delta epsilon_n equiv epsilon_n - epsilon_(n-1)$ 远远小于 $k T$ 时,量子统计结果会退化为经典统计。有经典极限条件(能级准连续条件):$ (Delta epsilon_n)/(k T) lt.double 1 $在满足经典极限条件时,量子统计结论得到的子系配分函数有经典极限形式(考虑子系有 $r$ 个自由度):$ Z = sum_(n=0)^(infinity) e^(-beta epsilon_n) attach( arrow.long, t: (Delta epsilon_n)/(k T) lt.double 1 ) Z = integral dots.c integral (dif q_1 dots.c dif q_r dif p_1 dots.c dif p_r)/(h^r) e^(-beta epsilon) $ ==== _Maxwell_速度分布律 考虑服从_Maxwell-Boltzmann_分布(定域或满足非简并条件的非定域)的理想气体,气体分子的运动可以分解为*质心运动(平动)*和*内部运动*,内部运动包括双原子或多原子分子的转动和振动、原子内束缚电子的运动和核内部自由度的运动。这两部分能量相互不影响:$ epsilon_lambda = epsilon^t + epsilon^i \ g_lambda = g^t dot g^i $上标 $t, i$ 分别代表平动和内部。现在写出_Maxwell-Boltzmann_分布:$ macron(a)_lambda = g_lambda e^(-alpha-beta epsilon_lambda) = e^(-alpha) (g^i e^(-beta epsilon^i)) (g^t e^(-beta epsilon^t)) $在宏观体积内假设平动满足经典极限条件 $Delta epsilon^t lt.double k T$,考虑子相体积元内的平均分子数 $dif n$:$ dif n = e^(-alpha) (sum_i g^i e^(-beta epsilon^i)) (dif omega^t)/h^3 e^(-beta epsilon^t) = e^(-alpha) Z^i (dif omega^t)/h^3 e^(-beta epsilon^t) $其中有:$ dif omega^t = dif x dif y dif z dif p_x dif p_y dif p_z \ epsilon^t = 1/(2m) (p_x^2 + p_y^2 + p_z^2) + phi(x,y,z) \ Z^i = sum_i g^i e^(-beta epsilon^i) $方便计算假设外场势能 $phi(x,y,z) = 0$,并令 $A equiv e^(-alpha) Z^i \/ h^3$,可以由重整化得到:$ N = A limits(integral.triple)_V dif x dif y dif z limits(integral.triple)_(-infinity)^(+infinity) e^(-(p_x^2 + p_y^2 + p_z^2)\/2 m k T) dif p_x dif p_y dif p_z = A V (2 pi m k T)^(3\/2) $得到:$ A = n (1/(2 pi m k T))^(3\/2) $其中分子数密度 $n equiv N\/V$;取 $p_x = m v_x, p_y = m v_y, p_z = m v_z$,即刻得到单位体积内,质心运动处于 $dif v_x dif v_y dif v_z$ 内的平均分子数:$ f(v_x,v_y,v_z) dif v_x dif v_y dif v_z = n (1/(2 pi m k T))^(3\/2) e^(-m (v_x^2 + v_y^2 + v_z^2)\/2 k T) dif v_x dif v_y dif v_z $这就是 *_Maxwell_速度分布律*,其中 $f(v_x,v_y,v_z)$ 称为 *_Maxwell_速度分布函数*。如果取速度空间球坐标:$ v_x = v sin theta cos phi, v_y = v sin theta sin phi, v_z = v cos theta $取球坐标体积元 $v^2 dif v sin theta dif theta dif phi$,带入后把角度积分掉,得到*速率分布函数*:$ f(v) dif v = 4 pi n (m\/2 pi k T)^(3\/2) e^(-m v^2\/2 k T) v^2 dif v $有最可几速率 $v_m$,满足:$ ((dif f)/(dif v))_(v = v_m) = 0\ arrow.double v_m = sqrt((2 k T)/m) $进而还可以得到分子平均速率 $macron(v)$ 和方均根速率 $v_s$ :$ macron(v) = integral_0^infinity v f(v) dif v = sqrt((8 k T)/(pi m))\ v_s = sqrt(macron(v^2)) = [integral_0^infinity v^2 f(v) dif v]^(1\/2) = sqrt((3 k T)/m) $ ==== 能量均分定理 #colorbox( title: [能量均分定理], color: "blue", radius: 5pt, width: auto )[ 满足经典极限条件的系统微观能量表达式中的每一正平方项的平均值等于 $display(1/2 k T)$。 ] === 非定域子系 ==== _Bose-Einstein_分布 对于 _Bose-Einstein_ 分布,系统量子态数:$ W_(#text[_B.E._])({a_lambda}) = product_lambda C_(a_lambda+g_lambda-1)^a_lambda = product_lambda ((a_lambda+g_lambda-1)!)/(a_lambda ! (g_lambda -1)!)\ arrow.double ln W_(#text[_B.E._]) approx sum_lambda (a_lambda+g_lambda) ln (a_lambda+g_lambda) - sum_lambda a_lambda ln a_lambda - sum_lambda g_lambda ln g_lambda\ $同样令$delta ln W_(#text[_B.E._]) = 0$,可以得到一组约束方程:$ cases( display(delta ln W_(#text[_B.E._]) = sum_lambda ln((a_lambda+g_lambda)/a_lambda) delta a_lambda) \ display(delta N = sum_lambda delta a_lambda) = 0\ display(delta E = sum_lambda epsilon_lambda delta a_lambda) = 0 ) $得到_Bose-Einstein_分布:$ tilde(a)_(lambda;#text[_B.E._])=g_lambda/(e^(alpha+beta epsilon_lambda) - 1) $ ==== _Fermi-Dirac_分布 对于 _Fermi-Dirac_ 分布,系统量子态数:$ W_(#text[_F.D._])({a_lambda}) = product_lambda C_(g_lambda)^a_lambda = product_lambda (g_lambda!)/(a_lambda ! (g_lambda -a_lambda)!)\ arrow.double ln W_(#text[_F.D._]) approx sum_lambda g_lambda ln g_lambda - sum_lambda a_lambda ln a_lambda - sum_lambda (g_lambda - a_lambda) ln (g_lambda - a_lambda) \ $同样令$delta ln W_(#text[_F.D._]) = 0$,可以得到一组约束方程:$ cases( display(delta ln W_(#text[_F.D._]) = sum_lambda ln ((g_lambda - a_lambda)/a_lambda) delta a_lambda) \ display(delta N = sum_lambda delta a_lambda) = 0\ display(delta E = sum_lambda epsilon_lambda delta a_lambda) = 0 ) $得到_Fermi-Dirac_分布:$ tilde(a)_(lambda;#text[_F.D._])=g_lambda/(e^(alpha+beta epsilon_lambda) + 1) $ ==== 巨配分函数与热力学量 统一引入理想_Bose_气体和理想_Fermi_气体服从的平均分布:$ macron(a)_lambda = g_lambda/(e^(alpha + beta epsilon_lambda) plus.minus 1), quad cases( display(- quad #[_Bose-Einstein_分布]), display(+ quad #[_Fermi-Dirac_分布]) ) $引入巨配分函数:$ Xi = product_lambda (1 plus.minus e^(-alpha-beta epsilon_lambda))^(plus.minus g_lambda)\ ln Xi = sum_lambda plus.minus g_lambda ln(1 plus.minus e^(-alpha-beta epsilon_lambda)) $不难证明各热力学量表达式满足下列关系:$ cases( display(macron(N) &= - diff/(diff alpha) ln Xi), display(macron(E) &= - diff/(diff beta) ln Xi), display(macron(Y)_l &= - 1/beta diff/(diff y_l) ln Xi), display(S &= k(ln Xi - diff/(diff alpha) ln Xi - diff/(diff beta) ln Xi)), display(F &= - k T ln Xi + k T alpha diff/(diff alpha) ln Xi), display(G &= k T alpha diff/(diff alpha) ln Xi), display(Psi &= - k T ln Xi), display(S &= k ln W_(max) = k ln W({macron(a)_lambda})) ) $ ==== 非简并条件和经典极限条件 对于_Bose-Einstein_分布和_Fermi-Dirac_分布有:$ macron(a)_lambda = g_lambda/(e^(alpha + beta epsilon_lambda) plus.minus 1), quad cases( display(- quad #[_Bose-Einstein_分布]), display(+ quad #[_Fermi-Dirac_分布]) ) $注意到,当 $e^alpha gt.double 1$ 时,两个分布退化为_Maxwell-Boltzmann_分布:$ macron(a)_lambda = g_lambda e^(-alpha-beta epsilon_lambda) $这就称为*非简并条件*:$ e^alpha gt.double 1 arrow.r.double.long quad macron(a)_lambda/g_lambda lt.double 1 $表示每个粒子量子态上平均占据的粒子数远小于 $1$。此时有:$ macron(a)_(lambda;#[_B.E._]) = macron(a)_(lambda;#[_F.D._]) = macron(a)_(lambda;#[_M.B._]) \ W_(#[_B.E._]) = W_(#[_F.D._]) = 1/(N!)W_(#[_M.B._]) $现在来看看满足非简并条件下的巨配分函数:$ ln Xi &= plus.minus sum_lambda g_lambda ln(1 plus.minus e^(-alpha-beta epsilon_lambda))\ &approx sum_lambda g_lambda e^(-alpha-beta epsilon_lambda) = e^(-alpha) Z $将该巨配分函数带入到热力学量的统计表达式中,我们就能得到非简并条件下的热力学量表达式:$ cases( display(macron(N) &= - diff/(diff alpha) ln Xi = e^(-alpha) Z), display(macron(E) &= - diff/(diff beta) ln Xi = -e^(-alpha) (diff Z)/(diff beta) = -macron(N) diff/(diff beta) ln Z), display(macron(Y)_l &= - 1/beta diff/(diff y_l) ln Xi = - 1/beta e^(-alpha) (diff Z)/(diff y_l) = -macron(N)/beta diff/(diff y_l) ln Z), display(S &= k(ln Xi - diff/(diff alpha) ln Xi - diff/(diff beta) ln Xi) = macron(N) k (ln Z - beta diff/(diff beta) ln Z) - k ln macron(N)!), display(mu &= - k T ln Z/macron(N)), display(S &= k ln W_(max) = k ln (W_(#[_M.B._])_(max)) - k ln N!) ) $ #h(2em)与定域子系相同,非定域子系也有经典极限条件:$ e^alpha gt.double 1 \ (Delta epsilon_n)/(k T) lt.double 1 $也就是在满足非简并条件的前提下,满足能级准连续的条件,此时对子系能级的求和可以近似使用子相体积的积分代替。
https://github.com/typst-community/org
https://raw.githubusercontent.com/typst-community/org/main/README.md
markdown
This is the Typst Community organization manifest repository. Here you can find information about the organization, including its governance, goals, and how to get involved. For questions feel free to open a discussion in the [Discussions](https://github.com/orgs/typst-community/discussions) tab. > [!WARNING] > Work in progress ### Who runs this? This organization is run by volunteer Typst users, unaffiliated with the official [Typst](https://typst.app) project. Please see the [GOVERNANCE.md](GOVERNANCE.md) file for the current governance structure. and [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved (everyone is welcome). ### Why an organization? Unity is essential for any community to thrive. While decentralization may seem like a good idea, it can actually be harmful, leading to fragmentation and a lack of direction. Although open-source communities are typically decentralized, many have found success in creating a centralized entity to connect the community. We aim to follow their example to reduce fragmentation. These communities in question are the [coq-community](https://github.com/coq-community) and [nix-community](https://github.com/nix-community) communities. ### What are its goals? We follow, in essence, the same goals as the other communities. Namely: #### Collaborative maintenance of Typst packages and tools We aim to provide a central location for the maintenance of Typst packages and tools. Projects can be hosted in typst-community whenever any of the following is the case: - **The** author stopped maintaining the project. - **The** project has become a collective work, as several community members are actively working on it. - **The** author is still maintaining the project but they want to encourage other community members to participate in its maintenance and possibly take over. - **The** project is a tool of general interest and it makes sense to develop it collaboratively. ### Attribution This document is heavily inspired by the [coq-community manifesto](https://github.com/coq-community/manifesto).
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/diagraph/0.2.3/internals.typ
typst
Apache License 2.0
#import "graphviz_interface/protocol.typ": * #let plugin = plugin("graphviz_interface/diagraph.wasm") /// Converts a string containing escape sequences to content. #let parse-string(s) = { let result = [] let row = "" let is-escaped = false for cluster in s { if is-escaped { is-escaped = false if cluster == "l" { result += align(left, row) row = "" } else if cluster == "n" { result += align(center, row) row = "" } else if cluster == "r" { result += align(right, row) row = "" } else { row += cluster } } else if cluster == "\\" { is-escaped = true } else { row += cluster } } set block(spacing: 0.65em) result + align(center, row) } /// Convert a number to a string with a fixed number of digits. /// The number is padded with zeros on the left if necessary. #let int-to-string(n, digits, base: 10) = { let n-str = str(n, base: base) let n-len = n-str.len() let zeros = "0" * (digits - n-len) zeros + n-str } /// Get an array of evaluated labels from a graph. #let get-labels(manual-label-names, dot) = { let encoded-labels = plugin.get_labels(encode-overriddenLabels(( "labels": manual-label-names, "dot": dot, ))) let (labels, _) = decode-LabelsInfos(encoded-labels) labels.at("labels").map(encoded-label => { let label = if encoded-label.at("native") { if encoded-label.at("mathMode") { math.equation(eval(mode: "math", encoded-label.at("label"))) } else { parse-string(encoded-label.at("label")) } } else { encoded-label.at("label") } ( ..encoded-label, label: label, ) }) } /// Return a formatted label based on its color, font and content. #let label-format(color, font, fontsize, label) = [ #set text(fill: rgb(int-to-string(color, 8, base: 16))) #set text(size: fontsize) if fontsize.pt() != 0 #set text(font: font) if font != "" #text(label) ] #let label-dimensions(color, font, fontsize, label) = { let label = label-format(color, font, fontsize, label) measure(label) } /// Encodes the dimensions of labels into bytes. #let encode-label-dimensions(labels, overriden-labels) = { labels.map(label => { if label.at("html") { ( override: false, width: 0, height: 0, ) } else if label.at("native") { let dimensions = label-dimensions(label.at("color"), label.at("fontName"), label.at("fontSize"), label.at("label")) ( override: true, width: dimensions.width / 1pt, height: dimensions.height / 1pt, ) } else { let dimensions = measure(overriden-labels.at(label.at("label"))) ( override: true, width: dimensions.width / 1pt, height: dimensions.height / 1pt, ) } }) } /// Converts any relative length to an absolute length. #let relative-to-absolute(value, container-dimension) = { if type(value) == relative { let absolute-part = relative-to-absolute(value.length, container-dimension) let ratio-part = relative-to-absolute(value.ratio, container-dimension) return absolute-part + ratio-part } if type(value) == length { return value.to-absolute() } if type(value) == ratio { return value * container-dimension } panic("Expected relative length, found " + str(type(value))) } /// Renders a graph with Graphviz. #let render( /// A string containing Dot code. dot, /// Nodes whose name appear in this dictionary will have their label /// overridden with the corresponding content. Defaults to an empty /// dictionary. labels: (:), /// The name of the engine to generate the graph with. Defaults to `"dot"`. engine: "dot", /// The width of the image to display. If set to `auto` (the default), will be /// the width of the generated SVG or, if the height is set to a value, it /// will be scaled to keep the aspect ratio. width: auto, /// The height of the image to display. If set to `auto` (the default), will /// be the height of the generated SVG or if the width is set to a value, it /// will be scaled to keep the aspect ratio. height: auto, /// Whether to hide parts of the graph that extend beyond its frame. Defaults /// to `true`. clip: true, /// A color or gradient to fill the background with. If set to `none` (the /// default), the background will be transparent. background: none, ) = { set math.equation(numbering: none) let manual-label-names = labels.keys() let labels-infos = get-labels(manual-label-names, dot) let labels-info-count = labels-infos.len() layout(((width: container-width, height: container-height)) => context { // replace invalid font sizes with the current text size let labels-infos = labels-infos.map((label) => { let fontSize = text.size if label.at("fontSize").pt() != 0 { fontSize = label.at("fontSize") } ( ..label, fontSize: fontSize, ) }) // return [#repr(labels-infos)] let encoded-data = ( "fontSize": text.size.to-absolute(), "dot": dot, "labels": encode-label-dimensions(labels-infos, labels), "engine": engine, ) // return [#repr(encoded-data)] // return [#((array(encode-renderGraph(encoded-data)).map(x => "0x" + int-to-string(x, 2, base: 16))).join(", "))] let output = plugin.render(encode-renderGraph(encoded-data)) if output.at(0) != 0 { return { show: highlight.with(fill: red) set text(white) raw(block: true, str(output)) } } let output = decode-graphInfo(output).at(0) // return [#repr(output)] // Get SVG dimensions. let (width: svg-width, height: svg-height) = measure(image.decode(output.at("svg"), format: "svg")) let final-width = if width == auto { svg-width } else { relative-to-absolute(width, container-width) } let final-height = if height == auto { svg-height } else { relative-to-absolute(height, container-height) } if width == auto and height != auto { let ratio = final-height / svg-height final-width = svg-width * ratio } else if width != auto and height == auto { let ratio = final-width / svg-width final-height = svg-height * ratio } // Rescale the final image to the desired size. show: block.with( width: final-width, height: final-height, clip: clip, breakable: false, ) set align(top + left) show: scale.with( origin: top + left, x: final-width / svg-width * 100%, y: final-height / svg-height * 100%, ) // Construct the graph and its labels. show: block.with(width: svg-width, height: svg-height, fill: background) // Display SVG. image.decode( output.at("svg"), format: "svg", width: svg-width, height: svg-height, ) // Place labels. for (label-infos, label-coordinates) in labels-infos.zip(output.at("labels")) { if label-infos.at("html") { continue } let label = if label-infos.at("native") { label-infos.at("label") } else { labels.at(label-infos.at("label")) } let label = label-format(label-infos.at("color"), label-infos.at("fontName"), label-infos.at("fontSize"), label) let label-dimensions = measure(label) place( top + left, dx: label-coordinates.at("x") - label-dimensions.width / 2, dy: final-height - label-coordinates.at("y") - label-dimensions.height / 2 - (final-height - svg-height), label ) // place( // top + left, // dx: label-coordinates.at("x") - label-dimensions.width / 2, // dy: final-height - label-coordinates.at("y") - label-dimensions.height / 2 - (final-height - svg-height), // rect(height: label-dimensions.height, width: label-dimensions.width, fill: none) // ) } }) }
https://github.com/eeeem460/typst
https://raw.githubusercontent.com/eeeem460/typst/main/README.md
markdown
`grundy/main.typst` のプリアンブルは [sahasatvikさんのリポジトリの例](https://github.com/sahasatvik/typst-theorems/blob/main/differential_calculus.typ) を日本語で書けるように変更したものです。お借りします。 日本語への対応については[stepney141さんのtemplate](https://github.com/stepney141/my_typst_template/blob/main/%E3%83%AA%E3%82%A2%E3%83%9A%E3%83%BB%E3%83%AC%E3%83%9D%E3%83%BC%E3%83%88%E7%94%A8/template.typ) を参考にしました。
https://github.com/St0wy/how_to_pdf
https://raw.githubusercontent.com/St0wy/how_to_pdf/main/README.md
markdown
# how_to PDF To get the PDF you must have [Typst](https://github.com/typst/typst) installed and the executable on the path. You can find the latest version in their GitHub release page. Once this is done, compile with : ``` jai main.jai ``` And run with : ``` ./main.exe <path-to-how_to> ``` On windows, if you don't give a path, it will try to use `C:\jai\how_to`.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pagebreak_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Two text bodies separated with and surrounded by weak pagebreaks. // Should result in two aqua-colored pages. #set page(fill: aqua) #pagebreak(weak: true) First #pagebreak(weak: true) Second #pagebreak(weak: true)
https://github.com/physicshinzui/typst-templates
https://raw.githubusercontent.com/physicshinzui/typst-templates/main/article/article_template.typ
typst
// This code is helpful to modify template: // https://github.com/avonmoll/ifacconf-typst/blob/main/lib.typ #let conf( title: none, authors: (), abstract: [], keywords: [], bib: none, heading-numbering: none, is-supporting-info: false, doc, ) = { set text(font: "New Computer Modern") set align(center) text(17pt, title) let count = authors.len() let ncols = calc.min(count, 1) grid( columns: (1fr,) * ncols, row-gutter: 24pt, ..authors.map(author => [ #author.name \ #author.affiliation \ #link("mailto:" + author.email) ]), ) if abstract != none{ par(justify: true)[ *Abstract* \ #abstract ] } set align(left) // columns(1, doc) show par: set block(spacing: 0.65em) set par( first-line-indent: 2em, justify: true) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") // show math.equation: set block(spacing: 0.65em) // Configure headings. if is-supporting-info == true { heading-numbering = "A.1" } set heading(numbering: heading-numbering) // show heading.where(level:2): it => text( // style:"italic", // it.body + [.] // ) doc bibliography(bib, title: "References", style: "ieee") } #import "@preview/ctheorems:1.1.0": * #let ifacconf-rules(doc) = { show bibliography: set block(spacing: 5pt) show: thmrules doc } // Support for numbered Theorems, etc. // NOTE: these definitions may be able to be cleaned up and compressed in the future #let theorem = thmenv( "theorem", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Theorem #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Theorem", ) #let lemma = thmenv( "lemma", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Lemma #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Lemma", ) #let claim = thmenv( "claim", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Claim #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Claim", ) #let conjecture = thmenv( "conjecture", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Conjecture #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Conjecture", ) #let corollary = thmenv( "corollary", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Corollary #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Corollary", ) #let fact = thmenv( "fact", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Fact #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Fact", ) #let hypothesis = thmenv( "hypothesis", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Hypothesis #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Hypothesis", ) #let proposition = thmenv( "proposition", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Proposition #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Proposition", ) #let criterion = thmenv( "criterion", none, none, (name, number, body, ..args) => { set align(left) set par(justify: true) block(inset: 0mm, radius: 0mm, breakable: false, width: 100%)[_Criterion #number#if name != none [ (#name)]._#h(2pt)#body] }, ).with( supplement: "Criterion", ) #let proof = thmbox( "proof", "Proof", inset: 0mm, base: none, bodyfmt: body => [#body #h(1fr) $square$], separator: [.#h(2pt)] ).with(numbering: none)
https://github.com/01mf02/jq-lang-spec
https://raw.githubusercontent.com/01mf02/jq-lang-spec/main/acm.typ
typst
#let mainFont = "Linux Libertine O" #let sfFont = "Linux Biolinum O" #let show-month(month) = ( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ).at(month - 1) #let author-names(authors) = authors.map(author => author.name).join(", ", last: " and ") #let author-address(author) = { author.name if author.at("email", default: none) != none [, #author.email] } #let show-author(author) = { text(fill: blue, font: sfFont, size: 11pt, upper(author.name)) let affiliation = author.at("affiliation", default: none) if affiliation != none { text(font: mainFont, size: 9pt)[, #affiliation.institution, #affiliation.country] } } #let show-subconcept(priority, name) = { if priority >= 500 { strong(name) } else if priority >= 300 { emph(name) } else { name } } #let show-ccs(concept) = [ #box(baseline: -50%, circle(radius: 1.25pt, fill: black)) *#concept.at(0)* $->$ #concept.at(1).map(subconcept => show-subconcept(subconcept.at(0), subconcept.at(1))).join("; ")] #let legal(pub) = [ Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and#h(.5pt)/or a fee. Request permissions from <EMAIL>.\ #sym.copyright #pub.year Association for Computing Machinery\ 0004-5411/2018/8-ART1 \$15.00\ https:\/\/doi.org\/#pub.doi ] #let total-pages(loc) = { let total = counter(page).final(loc).last() [#total page#if(total > 1) { [s] }] } #let even-page(loc) = calc.rem(loc.page(), 2) == 0 #let header(short, pub, loc) = { let article = if pub != none [#{pub.article}:] let article-page = [#article#counter(page).display()] if even-page(loc) [#article-page #h(1fr) #{short.authors}] else [#{short.title} #h(1fr) #article-page] } #let footer(pub) = if pub != none [ #pub.journal-short, Vol. #pub.volume, No. #pub.number, Article #pub.article. Publication date: #show-month(pub.month) #pub.year. ] #let acmart( // Currently supported formats are: // - acmsmall format: "acmsmall", // Title, subtitle, authors, abstract, ACM ccs, keywords title: "Title", title-short: none, subtitle: none, authors: (), authors-short: none, anonymous: false, abstract: none, ccs: none, keywords: none, pub: ( journal: none, journal-short: none, volume: 1, number: 1, article: none, month: 5, year: 2023, doi: "XXXXXXX.XXXXXXX", ), copyright: pub => [ Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and#h(.5pt)/or a fee. Request permissions from <EMAIL>.\ #sym.copyright #pub.year Association for Computing Machinery\ 0004-5411/2018/8-ART1 \$15.00\ https:\/\/doi.org\/#pub.doi ], body ) = { if anonymous { authors = ((name: "Anonymous Author(s)"),) authors-short = "Anon." } let short = ( title: if title-short == none { title } else { title-short }, authors: if authors-short == none { author-names(authors) } else { authors-short }, ) // Set document metadata set document(title: title, author: authors.map(author => author.name)) // Configure the page. set page( width: 6.75in, height: 10in, margin: ( top: 58pt + 27pt, bottom: 39pt + 24pt, left: 46pt, right: 46pt ), header: text(size: 8pt, font: sfFont, locate(loc => if loc.page() > 1 { header(short, pub, loc) })), footer: text(size: 8pt, locate(loc => align(if even-page(loc) { left } else { right }, footer(pub)))), header-ascent: 17pt, footer-descent: 24pt, ) // title page { set text(size: 9pt) set par(justify: true, leading: 0.555em) show par: set block(below: 9.5pt) // Display title text(font: sfFont, size: 14.4pt, weight: "bold", title) v(7pt) authors.map(show-author).join("\n") if not(anonymous) { footnote(numbering: x => [#hide[0]], [#linebreak() #v(-1.5em) Authors' addresses: #authors.map(author-address).join("; ").]) } footnote(numbering: x => [#hide[0]], (v(-1em), copyright(pub)).join()) v(2.5pt) let ref-format = if pub != none [ *ACM Reference Format:* \ #author-names(authors). #pub.year. #title. #emph(pub.journal-short) #pub.volume, #pub.number, Article #pub.article (#show-month(pub.month) #pub.year), #locate(total-pages). https:\/\/doi.org\/#pub.doi ] [ #abstract CCS Concepts: #ccs.map(show-ccs).join("; "). Additional Key Words and Phrases: #keywords.join(", ") #ref-format ] v(1pt) } set text(font: mainFont, size: 10pt) set heading(numbering: "1.1") show heading: it => block(text(font: sfFont, size: 10pt, weight: "bold", { if it.numbering != none { counter(heading).display() box(width: 11pt) } upper(it.body) })) set par( justify: true, leading: 5.35pt, first-line-indent: 9.5pt) show par: set block(below: 5.35pt) body }
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/set-if.typ
typst
Apache License 2.0
#let task(body, critical: false) = { set text(red) if critical [- #body] } #task(critical: true)[Food today?] #task(critical: false)[Work deadline]
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/mecanique_quantique_2.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: "mecanique quantique 2", authors: ( "<NAME>", ), date: "10 Août, 2024", ) #set heading(numbering: "1.1.") = Introduction <introduction> La mécanique quantique est une théorie fondamentale de la physique qui décrit les propriétés physiques de la nature à l’échelle des atomes et des particules subatomiques. Elle est le fondement de toute la physique quantique, y compris la chimie quantique, la théorie quantique des champs, la technologie quantique et la science de l’information quantique. La mécanique quantique diffère de la physique classique à bien des égards, notamment : - La quantification : en mécanique quantique, l’énergie, la quantité de mouvement, le moment angulaire et d’autres quantités sont souvent limités à des valeurs discrètes. - La dualité onde-particule : les objets ont des caractéristiques à la fois de particules et d’ondes. - Le principe d’incertitude : étant donné un ensemble complet de conditions initiales, il existe des limites à la précision avec laquelle la valeur d’une quantité physique peut être prédite avant sa mesure. - L’intrication quantique : des objets peuvent être liés entre eux de telle sorte qu’ils partagent le même destin, même s’ils sont séparés par une grande distance. La mécanique quantique a joué un rôle important dans le développement de nombreuses technologies modernes, notamment les lasers, les transistors et les armes nucléaires. Elle est également essentielle pour comprendre de nombreux processus fondamentaux dans la nature, tels que le comportement des atomes et des molécules, la structure des matériaux et la nature de la lumière. Ce cours propose une introduction aux concepts de base de la mécanique quantique. Nous discuterons de la fonction d’onde, de l’équation de Schrödinger et du principe d’incertitude. Nous aborderons aussi certaines applications de la mécanique quantique, telles que les lasers et les transistors. = Cours associés <cours-associés> - #link("lagrange.pdf")[Mécanique de Lagrange] - #link("champs_quantiques.pdf")[La théorie des champs quantiques] = Histoire <histoire> == Quanta <quanta> Un quanta est la plus petite unité d’énergie pouvant être absorbée ou émise. C’est la particule fondamentale de la lumière, et c’est aussi l’énergie transportée par d’autres particules, telles que les électrons et les protons. L’histoire de la découverte des quanta est longue et sinueuse. Le premier soupçon d’existence d’un quanta est apparu au début des années 1900, lorsque les physiciens étudiaient le comportement de la lumière. Ils ont découvert que la lumière pouvait être émise en unités discrètes et que ces unités étaient proportionnelles à la fréquence de la lumière. Cette découverte a conduit au développement de la théorie quantique, qui est la branche de la physique qui traite du comportement de la matière et de l’énergie au niveau atomique et subatomique. La théorie quantique a révolutionné notre compréhension de l’univers et a conduit au développement de nombreuses nouvelles technologies, telles que les lasers et l’énergie nucléaire. Il s’agit toujours d’un domaine de recherche actif, et les scientifiques apprennent constamment de nouvelles choses sur le fonctionnement des quanta. Le terme "quanta" a été utilisé pour la première fois en 1905 par Max Planck, un physicien allemand. Planck essayait d’expliquer le spectre de rayonnement du corps noir, c’est-à-dire la distribution de l’énergie émise par un corps noir à différentes longueurs d’onde. Il a découvert qu’il ne pouvait expliquer le spectre que s’il supposait que la lumière était émise en unités discrètes, qu’il a appelées quanta. == Dualité onde-corpuscule <dualité-onde-corpuscule> La dualité onde-particule est le concept de la mécanique quantique selon lequel toute particule ou entité quantique peut être décrite soit comme une onde, soit comme une particule. Elle exprime l’incapacité des concepts classiques de "particule" ou d’"onde" à décrire pleinement le comportement des objets à l’échelle quantique. Comme l’a écrit <NAME> : “Il semble que nous devions utiliser tantôt l’une, tantôt l’autre théorie, et tantôt l’une ou l’autre. Nous sommes confrontés à un nouveau type de difficulté. Nous avons deux images contradictoires de la réalité ; séparément, aucune d’entre elles n’explique totalement les phénomènes lumineux, mais ensemble, elles le font. La dualité onde-particule a été découverte pour la première fois par le physicien français <NAME> en 1924. De Broglie a proposé que toutes les particules aient une longueur d’onde, et que cette longueur d’onde soit inversement proportionnelle à l’élan de la particule. En d’autres termes, plus la longueur d’onde est courte, plus l’élan de la particule est important. L’hypothèse de <NAME> a été confirmée par l’expérience de Davisson-Germer en 1927. Dans cette expérience, un faisceau d’électrons a été diffusé à partir d’un cristal. On a constaté que les électrons interféraient les uns avec les autres, comme le feraient des ondes. Cette expérience a confirmé que les électrons peuvent se comporter comme des ondes. La dualité onde-particule est l’un des concepts les plus importants de la mécanique quantique. Elle est à la base de nombreux effets étranges observés dans le monde quantique, tels que l’effet tunnel quantique et l’intrication quantique. Image d’une onde dans l’expérience de la double fente Cette image montre comment une onde peut interférer avec elle-même. Les ondes sont représentées par les lignes bleues. Les zones bleu clair représentent les zones où les ondes sont en phase, et les zones bleu foncé représentent les zones dans lesquelles les ondes sont déphasées. Comme vous pouvez le voir, les ondes peuvent interférer les unes avec les autres pour créer des motifs clairs et sombres. C’est un bon exemple de la façon dont les ondes peuvent se comporter comme des particules. Les ondes de cette image sont en fait des électrons qui interfèrent les uns avec les autres pour créer un motif. Ce n’est qu’un exemple de la manière dont la dualité onde-particule se manifeste dans le monde quantique. == Le problème de la mesure <le-problème-de-la-mesure> Le problème de la mesure est un problème fondamental de la mécanique quantique. Il s’agit de réconcilier la fonction d’onde d’un système quantique avec les résultats des mesures classiques. La fonction d’onde d’un système quantique est une fonction mathématique qui décrit l’état du système. Les résultats des mesures sont les valeurs que nous observons lorsque nous mesurons le système. L’effondrement de la fonction d’onde est le processus par lequel la fonction d’onde d’un système quantique change lorsqu’elle est mesurée. La fonction d’onde s’effondre en un seul état, et on dit que le système est dans un état propre. L’état propre est l’état qui correspond au résultat de la mesure. Le problème de la mesure a été proposé pour la première fois par <NAME> en 1928. Bohr a soutenu que l’effondrement de la fonction d’onde est une conséquence nécessaire de l’interaction du système quantique avec l’appareil de mesure. L’appareil de mesure est un système classique, et il ne peut pas interagir avec le système quantique sans le perturber. Il existe de nombreuses interprétations différentes de la mécanique quantique et chaque interprétation a sa propre façon d’expliquer le problème de la mesure. L’interprétation la plus populaire de la mécanique quantique est l’interprétation de Copenhague. Selon cette interprétation, l’effondrement de la fonction d’onde est un événement réel, qui se produit lorsque le système quantique interagit avec l’appareil de mesure. == Intrication quantique <intrication-quantique> L’intrication est un phénomène dans lequel deux ou plusieurs particules quantiques sont liées de telle sorte qu’elles partagent le même destin, même lorsqu’elles sont séparées par une grande distance. Par exemple, si deux électrons sont intriqués, ils auront toujours le même spin, même s’ils sont séparés par un continent. L’intrication a été découverte pour la première fois par Albert Einstein, <NAME> et <NAME> en 1935. Ils ont proposé une expérience consistant à séparer une paire de particules intriquées et à mesurer leurs propriétés. Ils ont constaté que les propriétés des particules étaient toujours corrélées, même si elles étaient séparées par une grande distance. Cette expérience a montré que l’intrication est un phénomène réel, qui a depuis été confirmé par de nombreuses autres expériences. Cependant, il est important de noter que l’intrication ne peut pas être utilisée pour communiquer des informations à une vitesse supérieure à celle de la lumière. En effet, l’information partagée entre les particules intriquées n’est pas réellement transmise entre elles. Au lieu de cela, les particules se trouvent simplement dans un état dans lequel elles partagent le même destin. = Fondements mathématiques de la mécanique quantique <fondements-mathématiques-de-la-mécanique-quantique> == Fonction d’onde <fonction-donde> La fonction d’onde est une fonction mathématique qui décrit l’état d’un système quantique. Il s’agit d’une fonction à valeurs complexes, dont le carré donne la probabilité de trouver la particule en un point particulier de l’espace. La fonction d’onde peut être utilisée pour calculer l’énergie de la particule, sa quantité de mouvement et d’autres propriétés. Un exemple de fonction d’onde est la fonction d’onde d’une particule dans une boîte. Cette fonction d’onde est une onde sinusoïdale dont la longueur d’onde et l’amplitude varient en fonction de l’énergie de la particule. Le carré de la fonction d’onde d’une particule dans une boîte donne la probabilité de trouver la particule en un point particulier de la boîte. Un autre exemple de fonction d’onde est la fonction d’onde d’un électron libre. Cette fonction d’onde est une onde sphérique dont la longueur d’onde et l’amplitude varient en fonction de l’énergie de l’électron. Le carré de la fonction d’onde d’un électron libre donne la probabilité de trouver l’électron en un point particulier de l’espace. La fonction d’onde est un concept très important en mécanique quantique, et elle a de nombreuses applications dans la théorie des ondes et des particules. En comprenant la fonction d’onde, nous pouvons mieux comprendre le comportement des systèmes quantiques. Voici un exemple de fonction d’onde pour une particule dans une boîte : #block[ $psi (x) = sqrt(2 / L) sin (frac(pi n x, L))$ ] où $n$ est un entier et $L$ la longueur de la boîte. La longueur d’onde de cette fonction d’onde est $lambda = 2 L / n$, et l’amplitude est $A = sqrt(2 / L)$. Le carré de cette fonction d’onde donne la probabilité de trouver la particule en un point particulier de la boîte. Representation de fonction d’onde == Espaces de Hilbert et vecteurs d’état <espaces-de-hilbert-et-vecteurs-détat> La mécanique quantique est une théorie mathématique qui utilise des #emph[espaces de Hilbert] pour représenter les #strong[états quantiques d’un système];. Un #emph[espace de Hilbert] est un #strong[espace vectoriel complexe] avec une structure interne qui permet de définir une notion de distance et de convergence, nommé produit interne. Les #emph[vecteurs d’état] quantique sont des éléments de cet espace de Hilbert et représentent l’état quantique d’un système. Les vecteurs d’état sont généralement notés #strong[|ψ⟩] et peuvent être exprimés comme une #strong[combinaison linéaire de vecteurs de base appelés états propres];. === Produit Scalaire (Produit interne) <produit-scalaire-produit-interne> Le produit scalaire correspond pour deux vecteurs de taille n $u^arrow.r vec(x_1, x_2, . ., x_n) x_i in bb(C)$ et $v^arrow.r vec(y_1, x_2, . ., y_n) y_i in bb(C) med thin$ à #block[ $angle.l u \| v angle.r = sum_(i = 1)^n x_i^(\*) y_i in bb(C)$ ] avec \* le conjugué ==== Linéarité et anti-linéarité <linéarité-et-anti-linéarité> Le produit scalaire est linéaire à droite et anti-linéaire à gauche - $angle.l u lr(|v_1 + v_2 angle.r = angle.l u|) v_1 angle.r + angle.l u \| v_2 angle.r$ - $angle.l u_1 + u_2 lr(|v angle.r = angle.l u_1|) v angle.r + angle.l u_2 \| v angle.r$ - $angle.l u lr(|lambda v angle.r = lambda angle.l u|) v angle.r$ - $angle.l u lr(|lambda v angle.r = lambda angle.l u|) v angle.r lambda in bb(C)$ - $angle.l lambda u lr(|v angle.r = lambda^(\*) angle.l u|) v angle.r lambda in bb(C)$ Ex. - $angle.l u lr(|(2 + 3 i) v angle.r = (2 + 3 i) angle.l u|) v angle.r$ - $angle.l (2 + 3 i) u lr(|v angle.r = (2 - 3 i) angle.l u|) v angle.r$ ==== Norme <norme> $u^arrow.r vec(x_1, x_2, . ., x_n) parallel u^arrow.r parallel = sqrt(sum_(i = 1)^n = lr(|x_i^2|)) in bb(R)_(+)$ avec |x| le module de x soit pour un nombre complexe $z = a + i b$ le module de z est $ lr(|z|) = sqrt(a^2 + b^2) $ par conséquent $ parallel u^arrow.r parallel^2 = lr(|x_1|)^2 + lr(|x_2|)^2 + . . + lr(|x_n|)^2 $ puisque $lr(|z thin|)^2 = a^2 + b^2 = z^(\*) dot.op z arrow.r .$ $ parallel u parallel = sqrt(angle.l u \| u angle.r) $ ==== Orthogonalité <orthogonalité> Deux vecteurs sont orthogonaux si $angle.l u \| v angle.r = 0$ ==== Symétrie <symétrie> $ angle.l u \| v angle.r = (angle.l v \| u angle.r)^(\*) $ == Opérateurs et observables <opérateurs-et-observables> Les #emph[opérateurs quantiques] sont des #strong[transformations linéaires] qui agissent sur les vecteurs d’état quantique pour produire de nouveaux vecteurs d’état. Les #emph[observables] sont des grandeurs physiques qui peuvent être mesurées expérimentalement, telles que la #strong[position];, la #strong[quantité de mouvement] et l’#strong[énergie];. Les observables sont représentées par des #emph[opérateurs hermitiens];. Les valeurs propres de ces opérateurs sont les valeurs possibles pour les mesures de l’observable correspondante. === Opérateurs linéaires <opérateurs-linéaires> Un opérateur linéaire est une fonction $L$ qui fait correspondre des vecteurs d’un espace vectoriel $V$ à des vecteurs d’un autre espace vectoriel $W$, de telle sorte que pour tout vecteur $x$ et $y$ dans $V$ et tout scalaire $c$, $hat(L) (lr(|x angle.r +|) y angle.r) = hat(L) (\| x angle.r) + hat(L) (\| y angle.r)$ $hat(L) (c \| x angle.r) = c hat(L) (\| x angle.r)$ La notation d’un opérateur linéaire est généralement un chapeau, $hat(L)$. Par exemple, l’opérateur linéaire qui prend un vecteur $x$ à sa transposée est désigné par $hat(T)$. En mécanique quantique, les opérateurs linéaires sont utilisés pour représenter les observables. Par exemple, l’opérateur linéaire qui représente la position d’une particule est désigné par $hat(x)$. La formule de la valeur espérée d’une observable $O$ est donnée par #block[ $angle.l O angle.r = integral psi^(\*) O psi d x$ ] où $psi$ est la fonction d’onde de la particule. === États propres et valeurs propres <états-propres-et-valeurs-propres> Un observable est une quantité qui peut être mesurée dans un système quantique. Les observables ont des valeurs propres, qui sont les valeurs possibles que l’observable peut prendre. Les états propres sont les états d’un système quantique qui correspondent aux valeurs propres d’un observable. Les trois règles concernant les états propres et les valeurs propres des observables sont les suivantes : + Les observables ont des valeurs propres réelles. + Les états propres des observables doivent couvrir tout l’espace vectoriel. + Les états propres doivent être mutuellement orthogonaux. #strong[Exemple];: Énergie potentielle L’énergie potentielle d’un système quantique est l’énergie que le système possède en raison de sa position. L’opérateur d’énergie potentielle est désigné par $hat(V)$. La formule de l’énergie potentielle est donnée par #block[ $hat(V) = - frac(planck.reduce^2, 2 m) nabla^2$ ] où $nabla^2$ est l’opérateur Laplacien. L’opérateur d’énergie potentielle peut être utilisé pour trouver les valeurs propres et les états propres de l’atome d’hydrogène. Les valeurs propres de l’atome d’hydrogène sont données par #block[ $E_n = - frac(13.6 upright(" eV"), n^2)$ ] où $n$ est un nombre entier. Les états propres de l’atome d’hydrogène sont donnés par les fonctions d’onde #block[ $psi_n (r , theta , phi) = 1 / sqrt(4 pi a_0^3) (n^2 / r)^(3 / 2) e^(- n^2 r / 2 a_0) e^(i m theta) e^(i n phi)$ ] où $a_0$ est le rayon de Bohr. Les états propres de l’atome d’hydrogène sont mutuellement orthogonaux et couvrent tout l’espace vectoriel. == Le formalisme de Dirac <le-formalisme-de-dirac> Le formalisme de Dirac est une notation mathématique pour la mécanique quantique qui utilise des notations spéciales pour les vecteurs d’état et les opérateurs. Dans cette notation, les vecteurs d’état sont représentés sous forme de ket #strong[$\| psi angle.r$] et les vecteurs duale, qui sont les vecteurs adjoints, sont représentés sous forme de bra #strong[$angle.l psi \|$];. Lorsque l’on prend le produit scalaire d’un ket avec un bra, on obtient une expression appelée le bra-ket, notée #strong[$angle.l psi \| phi angle.r$];, qui représente la probabilité de transition entre les deux états quantiques. Le formalisme de Dirac permet également de représenter les opérateurs quantiques sous forme de notations spéciales, telles que l’opérateur identité, l’opérateur de projection et l’opérateur de translation. Cette notation simplifie considérablement les calculs en mécanique quantique et permet une compréhension plus intuitive de la théorie. === Bra-Ket notation <bra-ket-notation> La notation de Bra-ket est une notation pour l’algèbre linéaire et les opérateurs linéaires sur des espaces vectoriels complexes ainsi que leur espace dual, à la fois en dimension finie et en dimension infinie. Elle est spécifiquement conçue pour faciliter les types de calculs qui se présentent fréquemment en mécanique quantique. Son utilisation en mécanique quantique est très répandue. De nombreux phénomènes expliqués à l’aide de la mécanique quantique sont expliqués à l’aide de la notation bra-ket. Dans la notation bra-ket, un bra est désigné par $angle.l psi \|$ et un ket est désigné par $\| phi angle.r$. Un bra est une fonction linéaire, ce qui signifie qu’il prend un vecteur en entrée et renvoie un nombre complexe. Un ket est un vecteur, ce qui signifie qu’il prend un nombre complexe en entrée et renvoie un vecteur. La représentation matricielle d’un bra est un vecteur ligne et la représentation matricielle d’un ket est un vecteur colonne. Le produit intérieur d’un bra et d’un ket est un nombre complexe. La notation bra-ket est liée au produit intérieur de la manière suivante : #block[ $angle.l psi \| phi angle.r = integral_(- oo)^oo psi^(\*) (x) phi (x) d x$ ] où $psi^(\*) (x)$ est le conjugué complexe de $psi (x)$. Le produit intérieur est une mesure du chevauchement entre deux fonctions. La notation bra-ket est un outil très utile en mécanique quantique, et elle a de nombreuses applications dans la théorie des ondes et des particules. En comprenant la notation bra-ket, nous pouvons mieux comprendre le comportement des systèmes quantiques. == Distribution de Dirac <distribution-de-dirac> La fonction delta de Dirac est une fonction définie comme nulle partout sauf au point x=0, où elle est infinie. Elle est souvent désignée par la lettre grecque delta, $delta (x)$. La fonction delta de Dirac a de nombreuses applications en mécanique quantique, où elle est utilisée pour représenter des particules ponctuelles et d’autres objets ayant une très petite étendue spatiale. Un exemple d’utilisation de la fonction delta de Dirac en mécanique quantique est l’intégrale de la fonction d’onde. L’intégrale de la fonction d’onde est un moyen de calculer la probabilité qu’une particule se trouve à un endroit donné. L’intégrale de la fonction d’onde est définie comme suit : #block[ $integral_(- oo)^oo psi (x) delta (x - x_0) d x$ ] où $psi (x)$ est la fonction d’onde de la particule et $x_0$ est l’endroit où la particule est trouvée. La fonction delta de Dirac dans cette intégrale nous indique que nous sommes uniquement intéressés à trouver la particule à l’endroit $x_0$, et que la probabilité de trouver la particule n’importe où ailleurs est nulle. La fonction delta de Dirac est également utilisée dans la définition de l’opérateur de quantité de mouvement. L’opérateur de quantité de mouvement est un opérateur mathématique qui représente la quantité de mouvement d’une particule. L’opérateur de quantité de mouvement est défini comme suit #block[ $hat(p) = - i planck.reduce frac(d, d x)$ ] où $i$ est l’unité imaginaire et $planck.reduce$ est la constante de Planck réduite. La fonction delta de Dirac dans cette définition nous indique que nous ne nous intéressons qu’à la dérivée de la fonction d’onde à l’endroit $x = 0$, et que la valeur de la dérivée partout ailleurs est nulle. La fonction delta de Dirac est un outil très utile en mécanique quantique, et elle a de nombreuses applications dans la théorie des ondes et des particules. Representation de la fonction delta de Dirac == Probalités : La loi de Born <probalités-la-loi-de-born> La probabilité de trouver le système dans l’état propre $\| E_i angle.r$ est donnée par : #block[ $P (E = E_i) = lr(|angle.l E_i med \| med psi angle.r|)^2$ ] où $\| E_i angle.r$ est l’état propre de l’observable $E$ avec la valeur propre $E_i$ et $psi$ est la fonction d’onde du système. La fonction d’onde $psi$ peut être écrite comme une somme des états propres de l’observable $E$, comme suit : #block[ $psi = sum_i c_i \| E_i angle.r$ ] où $c_i$ sont les coefficients des états propres. En substituant ceci à la formule de la probabilité, nous obtenons : #block[ $P (E = E_i) = lr(|angle.l E_i lr(|sum_i c_i|) E_i angle.r|)^2 = sum_i lr(|c_i|)^2$ ] Ceci montre que la probabilité de trouver le système dans l’état propre $\| E_i angle.r$ est égale à la somme des carrés des coefficients des états propres. === Matrice densité et Espérance mathématique <matrice-densité-et-espérance-mathématique> Une matrice densité est une matrice qui décrit l’état quantique d’un système physique. Elle permet de calculer les probabilités des résultats de toute mesure effectuée sur ce système, en utilisant la règle de Born. Il s’agit d’une généralisation des vecteurs d’état ou des fonctions d’onde plus habituels : alors que ceux-ci ne peuvent représenter que des états purs, les matrices de densité peuvent également représenter des états mixtes. L’espérance mathématique d’un opérateur $hat(A)$ dans un système quantique décrit par une matrice densité $rho$ est donnée par la formule suivante : #block[ $angle.l hat(A) angle.r = upright(" Tr") (rho hat(A))$ ] où $upright("Tr")$ est la fonction trace. La fonction trace d’une matrice est la somme de ses éléments diagonaux. La fonction trace possède les propriétés suivantes : - C’est une fonction linéaire. - Elle est invariante sous les transformations unitaires. - Elle est définie positive. La fonction trace peut être utilisée pour calculer la valeur d’espérance de tout opérateur dans un système quantique. La matrice densité peut être utilisée pour calculer les probabilités des résultats de toute mesure effectuée sur un système quantique. La règle de Born stipule que la probabilité d’obtenir un résultat $a$ lors de la mesure d’une observable $hat(A)$ est donnée par la formule suivante : #block[ $P (a) = frac(angle.l a lr(|rho|) a angle.r, sum_i angle.l i lr(|rho|) i angle.r)$ ] où $\| a angle.r$ est l’état propre de $hat(A)$ correspondant au résultat $a$. La matrice densité est un outil très important en mécanique quantique. Elle peut être utilisée pour calculer les valeurs d’espérance des opérateurs, les probabilités des résultats des mesures et la fonction d’onde d’un système quantique. == Opérateurs Hermitien <opérateurs-hermitien> === L’adjoint Hermitien <ladjoint-hermitien> L’adjoint hermitien d’un ket est un bra. Il est noté $A^dagger$. L’adjoint hermitien d’un ket est défini comme suit : $angle.l A^dagger psi lr(|phi angle.r = angle.l psi|) A phi angle.r$ pour tous les vecteurs $psi$ et $phi$ dans l’espace vectoriel. L’adjoint hermitien possède plusieurs propriétés. L’une d’entre elles est qu’il est linéaire. Cela signifie que si $A$ et $B$ sont deux opérateurs, alors $(A B)^dagger = B^dagger A^dagger$ Une autre propriété est qu’elle est anti-linéaire. Cela signifie que si $A$ est un opérateur et $c$ un nombre complexe, alors $(c A)^dagger = c_macron A^dagger$ Enfin, l’adjoint hermitien satisfait la relation suivante : $(A^dagger)^dagger = A$ L’adjoint hermitien est un outil très important en mécanique quantique. Il est utilisé pour définir le produit intérieur, qui est une mesure du chevauchement entre deux vecteurs. Le produit intérieur est utilisé pour calculer la valeur d’espérance d’une observable, qui est la valeur moyenne de l’observable sur tous les états possibles du système. ==== L’adjoint d’un Ket et d’un Bra <ladjoint-dun-ket-et-dun-bra> L’adjoint d’un Ket et d’un bra correspond à $angle.l phi lr(|psi angle.r^dagger = angle.l phi|) psi angle.r^star.op = angle.l psi med \| med phi angle.r$ ou $(angle.l phi med \| med psi angle.r)^dagger = lr(|psi angle.r^dagger angle.l phi|)^dagger$ D’où $lr(|psi angle.r^dagger = angle.l psi|)$ et $angle.l phi lr(|""^dagger =|) phi angle.r$ === Opérateur Hermitien <opérateur-hermitien> Un opérateur hermitien est un opérateur qui satisfait cette condition $hat(E)^dagger = hat(E)$ C’est le cas des observables par conséquent $angle.l psi lr(|hat(E) phi angle.r = angle.l hat(E) psi|) phi angle.r$ == Opérateur Unitaire <opérateur-unitaire> Un opérateur unitaire est un opérateur linéaire $U$ sur un espace de Hilbert $H$ qui satisfait les conditions suivantes : + $U$ est inversible. + $U^(- 1) = U^dagger$, où $U^dagger$ est l’adjoint de $U$. + $U$ préserve le produit intérieur de $H$, c’est-à-dire que pour tous les vecteurs $x$ et $y$ dans $H$, on a $angle.l U x , U y angle.r = angle.l x , y angle.r$. Les opérateurs unitaires sont importants en mécanique quantique, car ils représentent des transformations physiques qui préservent le produit intérieur et la probabilité. Par exemple, l’opérateur d’évolution temporelle $U (t)$ pour un système quantique est unitaire et représente l’évolution du système dans le temps. Les propriétés des opérateurs unitaires peuvent être déduites de leur définition. Par exemple, les valeurs propres d’un opérateur unitaire sont toujours des nombres complexes de module unitaire, et les vecteurs propres d’un opérateur unitaire forment une base orthonormée pour $H$. Les opérateurs unitaires conservent les probabilités parce qu’ils préservent le produit intérieur. Le produit intérieur est une mesure du chevauchement entre deux vecteurs, et il est égal à la probabilité que deux vecteurs se retrouvent dans le même état après une mesure. Si un opérateur unitaire préserve le produit intérieur, il préserve également la probabilité. Voici quelques exemples d’opérateurs unitaires : - L’opérateur de rotation $R (theta)$, qui fait pivoter un vecteur d’un angle $theta$ autour de l’origine. - L’opérateur de réflexion $S$, qui réfléchit un vecteur à travers l’origine. - La transformée d’Hadamard $H$, qui transforme un vecteur en une superposition égale de tous les états de base possibles. - Les matrices de Pauli $sigma_x$, $sigma_y$, et $sigma_z$, qui sont utilisées pour décrire le spin en mécanique quantique. == Principe d’incertitude et Commutation <principe-dincertitude-et-commutation> En mécanique quantique, le commutateur de deux opérateurs est une mesure de la manière dont les deux opérateurs peuvent être mesurés simultanément. Le commutateur de deux opérateurs est défini comme $\[ hat(A) , hat(B) \] = hat(A) hat(B) - hat(B) hat(A)$, où $hat(A)$ et $hat(B)$ sont les deux opérateurs. Si le commutateur de deux opérateurs est nul, on dit que les opérateurs sont commutatifs. Les opérateurs commutatifs peuvent être mesurés simultanément, ce qui signifie que les résultats de la mesure d’un opérateur n’affecteront pas les résultats de la mesure de l’autre opérateur. Si deux observables commutent, ils ont alors une base propre simultanée. Une base propre est un ensemble de vecteurs qui sont des vecteurs propres d’un opérateur donné. Un vecteur propre est un vecteur qui, lorsqu’il est influencé par un opérateur, a une valeur fixe. La base propre simultanée de deux observables commutatives est un ensemble de vecteurs qui sont des vecteurs propres des deux observables. Le principe d’incertitude stipule qu’il est impossible de connaître à la fois la position et la quantité de mouvement d’une particule avec une précision parfaite. Le principe d’incertitude peut être dérivé du commutateur des opérateurs de position et de quantité de mouvement. Le commutateur des opérateurs de position et de quantité de mouvement est $\[ x , p \] = i planck.reduce$, où $planck.reduce$ est la constante de Planck réduite. Cela signifie qu’il est impossible de mesurer simultanément la position et la quantité de mouvement d’une particule avec une précision parfaite. Le principe d’incertitude peut être exprimé mathématiquement comme suit pour la position et la quantité de mouvement: #block[ $sigma_x sigma_p gt.eq planck.reduce / 2$ ] où $sigma_x$ est l’incertitude sur la position et $sigma_p$ est l’incertitude sur la quantité de mouvement. Il existe une forme généralisée du principe d’incertitude nommé relations d’incertitude Robertson-Schrödinger: #block[ $sigma_A sigma_B gt.eq lr(|frac(1, 2 i) angle.l \[ hat(A) , hat(B) \] angle.r|)$ ] Le principe d’incertitude est un principe fondamental de la mécanique quantique. Il a des implications importantes pour l’interprétation de la mécanique quantique et pour la compréhension du monde physique. = Postulats de la mécanique quantique <postulats-de-la-mécanique-quantique> + L’état d’un système quantique est entièrement défini par un vecteur d’état dans un espace de Hilbert. Un vecteur d’état est généralement noté $\| psi angle.r$ et appartient à un espace de Hilbert H. Les états quantiques sont des vecteurs unitaires dans H, c’est-à-dire que $angle.l psi \| psi angle.r = 1$. + Les observables quantiques sont représentées par des opérateurs hermitiens. Un opérateur hermitien A est un opérateur qui est égal à sa propre adjointe $A^dagger$ (c’est-à-dire que $A = A^dagger upright(" avec ") dagger upright(" le conjugué soit ") star.op$). Les valeurs propres de l’opérateur hermitien A correspondent aux résultats possibles de la mesure de l’observable associée à A. + Les résultats de la mesure d’une observable quantique sont des valeurs propres de l’opérateur associé à cette observable. Si l’on mesure une observable quantique représentée par l’opérateur hermitien A sur un état quantique $\| psi angle.r$, la probabilité d’obtenir une valeur propre a est donnée par la formule $P (a) = lr(|angle.l a|) psi angle.r lr(|""^2 upright(" où ")|) a angle.r$ est le vecteur propre correspondant à la valeur propre a. + La probabilité de mesurer une valeur propre donnée est donnée par le carré du module de l’amplitude de probabilité correspondante. L’amplitude de probabilité pour obtenir une valeur propre a lorsqu’on mesure une observable quantique représentée par l’opérateur hermitien A sur un état quantique $\| psi angle.r$ est donnée par $angle.l a \| psi angle.r$. La probabilité P(a) d’obtenir la valeur propre a est alors donnée par #block[ $P (a) = lr(|angle.l a|) psi angle.r \|^2$ ] . + L’évolution temporelle d’un système quantique est décrite par l’équation de Schrödinger. L’évolution temporelle d’un état quantique $\| psi (t) angle.r$ est décrite par l’équation de Schrödinger #block[ $i planck.reduce frac(partial, partial t) lr(|psi (t) angle.r = hat(H)|) psi (t) angle.r$ ] où $hat(H)$ est l’hamiltonien du système donc l’énergie totale du système et $planck.reduce upright(" est ") = frac(h, 2 pi)$. + Les états quantiques peuvent être intriqués, ce qui signifie que les propriétés de chaque particule ne peuvent pas être décrites indépendamment des autres particules avec lesquelles elle est intriquée. Par exemple, si deux particules sont intriquées, alors la mesure de l’une des particules affectera instantanément l’état de l’autre particule, peu importe la distance qui les sépare. == Equation de Schrödinger <equation-de-schrödinger> L’équation de Schrödinger dépendante du temps peut être obtenue à partir de l’équation de Schrödinger indépendante en suivant les étapes suivantes : + Supposons que la fonction d’onde $Psi (t , r)$ puisse être écrite comme un produit d’un facteur dépendant du temps et d’un facteur dépendant de l’espace : #block[ $Psi (t , r) = psi (t) phi (r)$ ] + Substituer ceci dans l’équation de Schrödinger indépendante et multiplier les deux côtés par $psi (t)^(\*)$ : #block[ $- frac(i planck.reduce, 2 m) psi prime (t) = (- frac(planck.reduce^2, 2 m)) Delta phi (r) + V (r) phi (r) \) psi (t)^(\*)$ ] + Simplifier le côté gauche en combinant les termes : #block[ $- frac(i planck.reduce, 2 m) psi prime (t) = - frac(planck.reduce^2, 2 m) Delta psi (t) + V (r) psi (t)^(\*)$ ] + Intégrer les deux côtés par rapport au temps : #block[ $psi (t) = psi (0) + frac(i planck.reduce, 2 m) integral_0^t Delta psi (s) d s - frac(i planck.reduce, 2 m) integral_0^t V (r) psi (s)^(\*) d s$ ] + Le premier terme du côté droit est la fonction d’onde initiale, que l’on suppose connue. Le second terme du côté droit est une fonction de l’espace et du temps, et il peut être trouvé en résolvant l’équation de Schrödinger indépendante du temps : #block[ $Delta psi (s) + V (r) psi (s) = 0$ ] L’équation de Schrödinger dépendante du temps peut alors être écrite comme suit : #block[ $i planck.reduce frac(partial psi (t), partial t) = H psi (t)$ ] où $H$ est l’opérateur hamiltonien. L’équation de Schrödinger dépendante du temps est une équation linéaire qui peut être résolue en utilisant le principe de superposition. Le principe de superposition stipule que toute solution à l’équation de Schrödinger indépendante du temps peut être additionnée pour former une autre solution à l’équation de Schrödinger dépendante du temps. La densité de probabilité est définie comme $lr(|psi|)^2$, et c’est une mesure de la probabilité de trouver la particule en un point donné de l’espace. La probabilité totale doit toujours être égale à 1, ce qui signifie que la fonction d’onde doit être normalisée. La constante de Planck donne les unités de l’opérateur hamiltonien. L’opérateur hamiltonien est le générateur de translations temporelles, et l’énergie est la quantité conservée sous l’effet des translations temporelles. === Exemple d’un puits de potentiel fini <exemple-dun-puits-de-potentiel-fini> L’équation de Schrödinger pour une particule dans un puits de potentiel fini est la suivante : #block[ $- frac(planck.reduce^2, 2 m) nabla^2 psi (x) + V (x) psi (x) = E psi (x)$ ] où $V (x)$ est l’énergie potentielle de la particule, $E$ est l’énergie de la particule, $psi (x)$ est la fonction d’onde de la particule, et $planck.reduce$ est la constante de Planck réduite. Pour résoudre l’équation de Schrödinger, on peut utiliser la méthode de séparation des variables. Cette méthode consiste à supposer que la fonction d’onde peut être séparée en deux parties : #block[ $psi (x) = X (x) Y (y) Z (z)$ ] où $X (x)$ est une fonction de $x$, $Y (y)$ est une fonction de $y$, et $Z (z)$ est une fonction de $z$. En substituant ceci à l’équation de Schrödinger, nous obtenons : #block[ $- frac(planck.reduce^2, 2 m) nabla^2 X (x) + V (x) X (x) = E X (x)$ ] #block[ $- frac(planck.reduce^2, 2 m) nabla^2 Y (y) + E Y (y)$ ] #block[ $- frac(planck.reduce^2, 2 m) nabla^2 Z (z) + E Z (z)$ ] La première équation peut être résolue pour $X (x)$, la deuxième pour $Y (y)$ et la troisième pour $Z (z)$. Les solutions de ces équations sont appelées fonctions propres, et les valeurs propres correspondantes sont les niveaux d’énergie de la particule. Dans le cas d’une particule dans un puits de potentiel fini, l’énergie potentielle est nulle à l’intérieur du puits et infinie à l’extérieur. Cela signifie que les fonctions propres doivent être nulles à l’extérieur du puits. Les solutions de l’équation de Schrödinger dans ce cas sont appelées ondes stationnaires et sont données par : #block[ $psi_n (x) = sqrt(2 / a sin (frac(n pi x, a)))$ ] où $a$ est la largeur du puits et $n$ est un entier. Les niveaux d’énergie de la particule sont donnés par : #block[ $E_n = frac(n^2 pi^2 planck.reduce^2, 2 m a^2)$ ] Les ondes stationnaires représentent les états possibles de la particule dans le puits. La particule ne peut exister que dans ces états, et elle ne peut avoir d’autre énergie que les niveaux d’énergie donnés par l’équation de Schrödinger. === Exemple sur un oscillateur harmonique <exemple-sur-un-oscillateur-harmonique> L’équation de Schrödinger pour l’oscillateur harmonique est la suivante : #block[ $- frac(planck.reduce^2, 2 m) nabla^2 psi (x) + 1 / 2 m omega^2 x^2 psi (x) = E psi (x)$ ] où $m$ est la masse de l’oscillateur, $omega$ est la fréquence angulaire, et $E$ est l’énergie de l’oscillateur. Pour résoudre cette équation, on peut utiliser la méthode de séparation des variables. Cette méthode consiste à supposer que la fonction d’onde peut être séparée en deux parties : #block[ $psi (x) = X (x) Y (y) Z (z)$ ] où $X (x)$ est une fonction de $x$, $Y (y)$ est une fonction de $y$, et $Z (z)$ est une fonction de $z$. En substituant ceci à l’équation de Schrödinger, nous obtenons : #block[ $- frac(planck.reduce^2, 2 m) frac(d^2 X (x), d x^2) + 1 / 2 m omega^2 x^2 X (x) = E X (x)$ ] #block[ $- frac(planck.reduce^2, 2 m) frac(d^2 Y (y), d y^2)$ ] #block[ $- frac(planck.reduce^2, 2 m) frac(d^2 Z (z), d z^2) + 0 = E Z (z)$ ] La première équation peut être résolue pour $X (x)$, la deuxième pour $Y (y)$ et la troisième pour $Z (z)$. Les solutions de ces équations sont appelées fonctions propres, et les valeurs propres correspondantes sont les niveaux d’énergie de l’oscillateur. Les fonctions propres de l’oscillateur harmonique sont appelées polynômes d’Hermite et sont données par : #block[ $psi_n (x) = 1 / sqrt(n !) sqrt(frac(2 omega, p i)) H_n (sqrt(omega / 2) x)$ ] où $H_n$ est le $n$ème polynôme d’Hermite. Les niveaux d’énergie de l’oscillateur sont donnés par : #block[ $E_n = planck.reduce omega (n + 1 / 2)$ ] Les polynômes d’Hermite représentent les états possibles de l’oscillateur. L’oscillateur ne peut exister que dans ces états, et il ne peut avoir d’autre énergie que les niveaux d’énergie donnés par l’équation de Schrödinger. == Moment quantique <moment-quantique> L’opérateur de quantité de mouvement est noté $hat(P)$, et la fonction d’onde d’une particule est notée $psi$. L’opérateur de quantité de mouvement agit sur la fonction d’onde comme suit : #block[ $hat(P) psi (x) = - i planck.reduce frac(d psi (x), d x)$ ] où $planck.reduce$ est la constante de Planck réduite. L’opérateur de quantité de mouvement peut être utilisé pour calculer la quantité de mouvement d’une particule. La quantité de mouvement d’une particule est donnée par la formule suivante : #block[ $p = angle.l psi med \| med hat(P) psi angle.r$ ] où $angle.l psi med \| med hat(P) psi angle.r$ est la valeur d’espérance de l’opérateur de quantité de mouvement. = Effet Tunnel <effet-tunnel> L’effet tunnel quantique est un phénomène dans lequel un objet tel qu’un électron ou un atome traverse une barrière d’énergie potentielle que, selon la mécanique classique, l’objet n’a pas suffisamment d’énergie pour franchir. L’effet tunnel est une conséquence de la nature ondulatoire de la matière, où la fonction d’onde quantique décrit l’état d’une particule ou d’un autre système physique, et où les équations d’onde telles que l’équation de Schrödinger décrivent leur comportement. L’équation de Schrödinger peut être résolue pour trouver la fonction d’onde d’une particule dans une barrière d’énergie potentielle. La fonction d’onde pourra avoir une valeur non nulle de l’autre côté de la barrière, même si la particule n’a pas assez d’énergie pour atteindre ce côté selon la mécanique classique. La probabilité d’un effet tunnel est proportionnelle au carré de la fonction d’onde. Cela signifie que les particules ayant une fonction d’onde plus grande auront plus de chances de traverser une barrière que les particules ayant une fonction d’onde plus petite. #link("tunnel.html")[Tunnel Effect Video] = Spin <spin> Le spin est une forme intrinsèque de moment angulaire porté par les particules élémentaires. Il s’agit d’une propriété quantifiée exprimée par un nombre quantique de spin, noté "s". Par exemple, les électrons ont un spin 1/2, ce qui signifie qu’ils ont deux états de spin possibles. Le spin d’une particule détermine un grand nombre de ses propriétés, comme son moment magnétique et son comportement statistique. Le spin est une propriété fondamentale des particules, comme la masse et la charge, et il ne peut pas être expliqué par d’autres propriétés. Une conséquence importante du spin des particules est le couplage spin-orbite, qui résulte de l’interaction entre le spin d’une particule et son mouvement dans un champ magnétique. Le couplage spin-orbite peut provoquer la division des niveaux d’énergie dans les atomes, ce qui affecte les propriétés des électrons et peut conduire à des phénomènes tels que la structure fine des lignes spectrales. Le spin d’une particule la fait agir comme un petit aimant. Cela signifie que les particules peuvent interagir par l’intermédiaire de la force magnétique et que l’interaction du moment magnétique de spin entraîne également l’alignement des particules dans les champs magnétiques. Les propriétés magnétiques d’une particule sont déterminées par son spin, qui détermine l’intensité et la direction de son moment magnétique. Le moment magnétique μ d’une particule est proportionnel à son moment angulaire de spin : #block[ $mu = g \* (e / 2 m) \* S$ ] où g est le facteur g, e est la charge élémentaire et m est la masse de la particule. La direction du spin d’une particule peut être décrite par son vecteur spin, qui est une quantité vectorielle pointant dans la direction du moment angulaire de spin de la particule. L’ampleur du moment angulaire de spin peut être calculée à l’aide de la formule suivante : #block[ $lr(|S|) = sqrt(s (s + 1)) \* ħ$ ] où ħ (h-bar) est la constante de Planck réduite. Le moment angulaire du spin a des composantes quantifiées le long d’un axe donné (généralement l’axe z). La composante le long de l’axe z, notée Sz, peut prendre des valeurs discrètes données par : #block[ $S z = m_s \* ħ$ ] où $m_s$ est le nombre quantique magnétique, qui varie de -s à s par pas entiers. Par exemple, un électron, qui est un fermion de spin 1/2, peut avoir deux valeurs possibles pour $S z$ : $+ ħ / 2$ et $- ħ / 2$, correspondant respectivement à $m_s = + 1 / 2$ et $m_s = - 1 / 2$. La rotation du vecteur spin sous l’effet des rotations de la particule est décrite par l’opérateur de moment angulaire de spin, noté S. L’algèbre de spin régit les relations de commutation entre les composantes du vecteur spin : #block[ $\[ S x , S y \] = i ħ S z , \[ S y , S z \] = i ħ S x , \[ S z , S x \] = i ħ S y$ ] Les valeurs propres de $S z$ sont $m_s = s , s - 1 , dots.h , - s$, ce qui signifie que la projection du spin est quantifiée le long de l’axe z. Cette quantification a des implications pour le comportement des particules dans les champs magnétiques, ainsi que pour la distribution des particules dans les systèmes. Cette quantification a des implications sur le comportement des particules dans les champs magnétiques, ainsi que sur la distribution des particules dans les systèmes. La force du couplage spin-orbite est proportionnelle au numéro atomique du noyau et au spin électronique, et joue un rôle important dans des phénomènes tels que la division de la structure fine dans les spectres atomiques et l’effet Hall de spin dans les systèmes à l’état solide. La direction du moment angulaire du spin est déterminée par la direction du moment magnétique. Le moment magnétique d’une particule est une quantité vectorielle qui pointe dans la direction du moment angulaire de spin. L’orientation du moment magnétique est affectée par les champs magnétiques externes et peut entraîner la précession du moment angulaire du spin autour de la direction du champ magnétique, un phénomène connu sous le nom de précession de Larmor. Le comportement du spin sous l’effet des rotations est régi par les transformations de Lorentz, qui relient les coordonnées d’un événement mesurées par des observateurs situés dans des cadres de référence inertiels différents. Sous l’effet d’une transformation de Lorentz, les composantes du spin le long de différentes directions se mélangent, ce qui conduit au phénomène de couplage spin-orbite. Le principe d’exclusion de Pauli stipule que deux fermions ne peuvent pas occuper simultanément le même état quantique, ce qui inclut l’état de spin.
https://github.com/Lich496/Typst-with-Docker
https://raw.githubusercontent.com/Lich496/Typst-with-Docker/main/README.md
markdown
Apache License 2.0
# Typst with Docker ## Features Add Typst Language support. Build `.typ` file with typst on Docker Container. ## Requirements Docker is installed in your environment and Typst image shold be pulled. Here is recommended Dockerfile. ```dockerfile FROM ghcr.io/typst/typst:latest RUN apk --update add fontconfig COPY fonts /usr/share/fonts WORKDIR /data ``` Note that when comppiling, the directory your typst file is in will be mounted to `/data/`. ## Extension Settings This extension contributes the following settings: * `typst-with-docker.image`: Which docker image to use * `typst-with-docker.build.run`: When to build typst file - `onType`(default) - `onSave` - `onBuild` ## Release Notes ### 0.0.1 Initial build
https://github.com/cyp0633/hnu-bachelor-thesis-typst-template
https://raw.githubusercontent.com/cyp0633/hnu-bachelor-thesis-typst-template/master/readme.md
markdown
# 湖南大学本科毕业论文(大理) Typst 模板 Typst 是一种排版体系,可以理解为语法更简单的 LaTeX,确实能够简化许多 Word 的麻烦,包括但不限于页面编号、图片及其标号、伪代码排版等。 本模板力求与教务处提供的模板相似,但对比时仍能发现排版差别。作者已成功使用该模板,于信息科学与工程学院毕业,但不对任何可用性作保证,请使用者后果自负。 [样式预览](./assets/example.pdf) ## 使用方法 一般来说仅需要修改 `example.typ` 中的文章内容,以及 `example.bib` 中的参考文献(BibLaTeX 格式),其他 `.typ` 文件皆为模板。 为了解决多字重(粗细)问题,使用思源黑体和思源宋体分别代替部分黑体(SimHei)和宋体(SimSun)。外观可能有些许差异。由于体积问题,未包含以上两个字体,请自行下载解压,并移动字体文件到本文件夹中(推荐 OTC 版本,后缀为 .ttc;Typst 暂时不支持无极字重,请勿下载 Variable Font 版本),下载链接如下。 - [思源黑体下载链接](https://github.com/adobe-fonts/source-han-sans/releases/download/2.004R/SourceHanSansOTC.zip) - [思源宋体下载链接](https://github.com/adobe-fonts/source-han-serif/releases/download/2.002R/03_SourceHanSerifOTC.zip) 部分 Linux 系统可能未包含 Times New Roman,Arch Linux 可安装 AUR `ttf-times-new-roman`。 ## Q&A **仍然无法识别源代码目录中的字体?** 可以利用 `typst fonts` 命令验证所需字体是否能被检测到。如没有,则在 `compile` 或者 `fonts` 子命令后加参数指定字体目录,如 `typst compile <your-target>.typ --font-path ./`。你也可以直接安装所需字体,在这台计算机上就无需加上述参数。 **如何添加伪代码/LaTeX 公式/……?** 伪代码可以使用 [lovelace](https://typst.app/universe/package/lovelace),LaTeX 公式兼容可以使用 [mitex](https://typst.app/universe/package/mitex)。看来不止我一个人觉得 Typst 公式难用? **你这写得太烂了,我没法用!** 提 Issue 或者 PR,或者看一看 [别人的模板](https://github.com/Mufanc/hnuthss-template) ## 项目文件结构 ```plaintext ├── abstract.typ - 中英文摘要 ├── assets - 资源文件 │ ├── example.pdf - 模板效果示例 │ ├── ezgif-7-98e2f7ecdc.jpg - example.typ 的插图 │ ├── hnu-logo.png - 封面所需图片 │ └── hnu-text-logo.png - 封面所需图片 ├── authenticity.typ - 原创性声明和版权使用授权书 ├── bilingual-biblography.typ - 双语参考文献规则 ├── example.bib - 示例 BibLaTeX 文献表 ├── example.typ - 模板效果示例 ├── frontpage.typ - 封面格式 ├── gbt7714-numeric.csl - 参考文献格式(暂无用处) ├── readme.md - 本文件 └── template.typ - 调用上述组件合成的总模板 ``` ## 鸣谢 - Typst 开发者 - [`i-figured`](https://github.com/RubixDev/typst-i-figured) 插件作者:二级图表/公式序号 - @st1020 :三线表代码 - @OrangeX4 @csimide :双语参考文献规则 - 其他非必需但很有用的插件作者,各路 Issue 区大佬等
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/design/design_iteration_1_haskell_function_notation_inspired.typ
typst
= Haskell function notation-inspired design <haskell-function-notation-inspired-design> The Haskell function notation-inspired design takes the notation of functions in Haskell and converts the explicit and implicit parenthesis into blocks. The mapping from argument to value through an arrow remains the same. A simple addition definition can be seen in @haskell_funcnot_inspired_addition. #figure( image("../../static/haskell_function_notation_inspired_addition.png", width: 27%), caption: "Example of Haskell function-notation inspired function definition" )<haskell_funcnot_inspired_addition> In order to bring more clarity to the definition, the blocks and values are annotated with their type. #figure( image("../../static/haskell_function_notation_inspired_mapAdd5.png", width: 50%), caption: "Example of Haskell function-notation inspired function definition with higher order function" )<haskell_funcnot_inspired_mapAdd5> The handling of type arguments is not yet defined, although a similar solution as for the scratch inspired-design described in @scratch-inspired-design, could be used.
https://github.com/crd2333/Astro_typst_notebook
https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/src/components/TypstTemplate/figures.typ
typst
#import "@preview/fletcher:0.4.4" as fletcher: diagram, node, edge #import "@preview/tablem:0.1.0": tablem #import "@preview/lovelace:0.2.0": algorithm, pseudocode-raw, setup-lovelace #import "@preview/truthfy:0.3.0": truth-table, truth-table-empty #import "@preview/codly:0.2.0": * #import "@preview/cetz:0.2.1" // 插入图片 #let fig(alignment: center, ..args) = align(alignment, image(..args)) // 正则捕捉自动设置数学环境,对表格等使用 #let automath_rule = it => { show regex("\d+(.\d+)*"): it => $it$ it } // 普通表,包含居中 #let tbl(alignment: center, align_content: center + horizon, automath: false, ..args) = { let fig = align(alignment, table(align: align_content, ..args)) if automath { show table.cell: automath_rule fig } else {fig} } // 三线表,包含居中 #let tlt(alignment: center, align_content: center + horizon, automath: false, ..args) = { let fig = align(alignment, table( stroke: none, align: align_content, table.hline(y: 0), table.hline(y: 1), ..args, table.hline(), )) if automath { show table.cell: automath_rule fig } else {fig} } // 类 markdown 表格,使用 tablem 实现 #let tblm(alignment: center, automath: false, ..args) = { let fig = align(alignment, tablem(..args)) if automath { show table.cell: automath_rule fig } else {fig} } // 真值表,使用 truthfy 实现 #let truth-tbl(alignment: center, ..args) = align(alignment, truth-table(..args)) #let truth-tbl-empty(alignment: center, ..args) = align(alignment, truth-table-empty(..args)) // 算法框,使用 lovelace 实现 #let algo(caption: "", body) = { // 去除当以 "[]" 形式传参时 body 中的 "[]",方法比较笨,轻喷 if "text" not in body.fields() { body = body.children body = body.at(1) } algorithm( caption: caption, pseudocode-raw( indentation-guide-stroke: .4pt + aqua, body ) ) } // 代码块,使用 codly 实现 #let code(body) = [#body] // icons for codly #let codly_icon(codepoint) = { box( height: 1em, baseline: 0.1em, image(codepoint) ) h(0.2em) } #let c_svg = codly_icon("/src/assets/c.svg") #let cpp_svg = codly_icon("/src/assets/cpp.svg") #let python_svg = codly_icon("/src/assets/python.svg") #let rust_svg = codly_icon("/src/assets/rust.svg") #let java_svg = codly_icon("/src/assets/java.svg") #let sql_svg = codly_icon("/src/assets/sql.svg") #let typst_svg = codly_icon("/src/assets/typst.svg") #let verilog_svg = codly_icon("/src/assets/verilog.svg") #let diagram(..args) = align(center, fletcher.diagram( node-stroke: 1pt, edge-stroke: 1pt, mark-scale: 70%, ..args )) #let edge(..args, marks: "-|>") = fletcher.edge(..args, marks: marks)
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/布局/重复/重复.typ
typst
#image("屏幕截图 2024-04-16 174441.png") #image("屏幕截图 2024-04-16 174600.png")
https://github.com/lsmenicucci/typst-pkgs
https://raw.githubusercontent.com/lsmenicucci/typst-pkgs/main/calendar/README.md
markdown
# Typst calender component > Under development ## Usage ```typst #import "./calendar.typ": calendar, monthweeks // define calendar data #let c = calendar({ import "./calendar.typ": mark mark((day: 10, month: 4), label: "Homework assignment") mark((day: 6, month: 5), label: "My birthday") }, default: (year: 2024)) // show april and may weeks #grid(columns: (1fr, 1fr), monthweeks(c, month: 4), monthweeks(c, month: 5) ) // show 2018 june #monthweeks(c, month: 6, year: 2018) ```
https://github.com/HynDuf/typst-cv
https://raw.githubusercontent.com/HynDuf/typst-cv/master/main_letter.typ
typst
Apache License 2.0
// Imports #import "lib.typ": letter #let metadata = toml("./template/metadata.toml") #show: letter.with( metadata, myAddress: "Ha Noi, Vietnam", recipientName: "RECIPIENT_NAME", recipientAddress: "RECIPIENT_ADDRESS", date: datetime.today().display(), subject: "Subject: Motivation for admission", signature: image("hynduf/src/signature.png"), ) Dear RECIPIENT_SALUTATION, I am writing to express my strong interest in applying for the PROGRAM_NAME at INSTITUTION_NAME. My fascination with FIELD_OF_INTEREST has grown significantly over the past few years, especially as I have encountered its practical applications in APPLICATION_CONTEXT. Having reviewed the curriculum in detail, I am particularly impressed by the comprehensive coverage of both theoretical and practical aspects of PROGRAM_NAME. The opportunity to learn from experienced faculty and engage in hands-on projects is something I am truly excited about. I am confident that this program will provide me with the knowledge and skills necessary to excel in this field. Furthermore, I am deeply impressed by the professionalism and dedication demonstrated by INSTITUTION_NAME. From the informative and well-structured website to the highly regarded INSTITUTION_EVENT_OR_FEATURE, it is clear that your institution values excellence and innovation. This aligns perfectly with my own passion for continuous learning and growth. Thank you for considering my application. I look forward to the upcoming entrance exams. Sincerely, <NAME>
https://github.com/tzx/NNJR
https://raw.githubusercontent.com/tzx/NNJR/main/template.typ
typst
MIT License
#let resume(body) = { set list(indent: 1em) show list: set text(size: 0.92em) show link: underline show link: set underline(offset: 3pt) set page( paper: "us-letter", margin: (x: 0.5in, y: 0.5in) ) set text( size: 11pt, font: "New Computer Modern", ) body } #let name_header(name) = { set text(size: 2.25em) [*#name*] } #let header( name: "<NAME>", phone: "123-456-7890", email: "<EMAIL>", linkedin: "linkedin.com/in/jake", site: "github.com/jake", ) = { align(center, block[ #name_header(name) \ #phone | #link("mailto:" + email)[#email] | #link("https://" + linkedin)[#linkedin] | #link("https://" + site)[#site] ] ) v(5pt) } #let resume_heading(txt) = { show heading: set text(size: 0.92em, weight: "regular") block[ = #smallcaps(txt) #v(-4pt) #line(length: 100%, stroke: 1pt + black) ] } #let edu_item( name: "Sample University", degree: "B.S in Bullshit", location: "Foo, BA", date: "Aug. 1600 - May 1750" ) = { set block(above: 0.7em, below: 1em) pad(left: 1em, right: 0.5em, grid( columns: (3fr, 1fr), align(left)[ *#name* \ _#degree _ ], align(right)[ #location \ _#date _ ] )) } #let exp_item( name: "<NAME>", role: "Worker", date: "June 1837 - May 1845", location: "Foo, BA", ..points ) = { set block(above: 0.7em, below: 1em) pad(left: 1em, right: 0.5em, box[ #grid( columns: (3fr, 1fr), align(left)[ *#role* \ _#name _ ], align(right)[ #date \ _#location _ ] ) #list(..points) ]) } #let project_item( name: "<NAME>", skills: "Programming Language 1, Database3", date: "May 1234 - June 4321", ..points ) = { set block(above: 0.7em, below: 1em) pad(left: 1em, right: 0.5em, box[ *#name* | _#skills _ #h(1fr) #date #list(..points) ]) } #let skill_item( category: "Skills", skills: "Balling, Yoga, Valorant", ) = { set block(above: 0.7em) set text(size: 0.91em) pad(left: 1em, right: 0.5em, block[*#category*: #skills]) }
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/C++/Introduzione/Funzioni.typ
typst
Creative Commons Zero v1.0 Universal
#import "@preview/showybox:2.0.1": showybox In C++, esistono tre modi per passare un parametro ad una funzione. Di base, quando un valore viene passato ad una funzione, il parametro di tale funzione viene inizializzato con il valore passato. Al di lá di questo, che é comune a tutti i modi, i modi sono i seguenti: - *Passaggio per valore*, in cui viene semplicemente creata una copia locale alla funzione del parametro che viene passato, e tale copia non influenza in alcun modo la versione originale del dato nota alla funzione chiamante; - *Passaggio per puntatore*, in cui viene passato un puntatore ad una risorsa nota alla funzione chiamante. Questo significa che se la funzione chiamata manipola il dato associato al puntatore, tale valore viene modificato anche rispetto alla funzione chiamante. Se nella funzione chiamata viene modificato il puntatore in sé, sia il puntatore originale che l'oggetto a cui si riferisce rimangono comunque intatti; - *Passaggio per referenza*, in cui viene passata una reference ad un dato noto alla funzione chiamante; se la funzione chiamata lo modifica, tale modifica si ripercuote anche sul dato originale. Ad eccezione degli array statici, che possono essere passati solo e soltanto tramite puntatore, qualsiasi dato può essere passato in tutti e tre i modi, pertanto scegliere una modalità piuttosto che l'altra dipende (quasi) soltanto da cosa si vuole ottenere. Il passaggio per valore è da preferirsi per quando si ha interesse a non modificare il dato di origine o quando si richiede esplicitamente di ricreare una copia del dato originale, e tale dato è ragionevolmente piccolo. Il passaggio per puntatore e per referenza sono da preferirsi quando si ha interesse a modificare il dato originale oppure quando non si vuole che tale dato venga modificato, ma passare l'intero dato per valore richiederebbe troppa memoria. In questo secondo caso in particolare, è bene che il puntatore/referenza passato sia dichiarato `const`, di modo che possa essere letto ma non modificato. Il passaggio tramite puntatore e tramite referenza sono molto simili. Il passaggio tramite puntatore è in genere meno "sicuro" di quello per referenza, perchè il puntatore in questione potrebbe riferirsi ad un dato che non esiste e creare inconsistenze. Pertanto, è preferibile sempre controllare che il puntatore passato ad una funzione non sia `nullptr`. #showybox[ ``` #include <iostream> void fun1(int j) { j = j / 2; } void fun2(int* j) { *j = *j + 3; int x = 30; j = &x; // Nothing changes for i } void fun3(int& j) { j = j * 2; int& x = j; x++; // Something changed for i } int main() { int i = 10; fun1(i); // Nothing changes int* g = &i; fun2(g); // i is now 13 int& r = i; fun3(r); // i is now 27 return 0; } ``` ] Una funzione può ritornare dati di qualsiasi tipo, ad eccezione degli array, dei quali è possibile ritornare esclusivamente un puntatore che vi si riferisce. è considerata bad practise ritornare da una funzione puntatori o reference a dati locali alla funzione stessa. Questo perchè i dati locali ad una funzione vengono rimossi dallo stack una volta che la funzione è stata eseguita, quindi tali puntatori/reference si riferiscono a dati non validi. Due funzioni che si trovano nello stesso namespace ma che hanno dei parametri diversi (come numero e/o come tipo) sono comunque considerate funzioni diverse. In altre parole, C++ supporta l'*overloading*. Se viene chiamata una funzione che condivide il nome con un'altra funzione, il compilatore è in grado di dedurre (più o meno correttamente) quale sia la "versione" corretta della funzione da chiamare. Naturalmente, due funzioni con la stessa identica signature (stesso namespace, stesso nome, stesso nome, tipo e ordine dei parametri) non sono ammesse, ed il compilatore restituisce un messaggio d'errore. Una funzione può anche avere dei valori di default opzionali assegnati ai parametri. Se una funzione con dei default sui parametri viene chiamata con un valore per tale parametro, allora tale parametro viene utilizzato normalmente, mentre se non viene specificato allora viene usato quello di default. I parametri di una funzione a cui viene assegnato un valore di default devono necessariamente essere contigui ed essere tutti sulla parte destra. ``` ret_type func_name(type_1 par_1, ..., type_i par_i = def_i, ..., type_n par_n = def_n) ``` #showybox[ ``` #include <iostream> void h(char c, int v = 20) // Allowed { ... } void f(char c = 10, int v = 90) // Allowed { ... } void g(char c = 10, int v) // NOT allowed { ... } int main() { f(1, 29); // c = 1, v = 29 f(1); // c = 1, v = 90 f(); // c = 10, v = 90 return 0; } ``` ] La keyword `inline` permette di dichiarare una funzione come funzione inline. Una funzione inline è una funzione che viene espansa in linea quando viene chiamata, ovvero l'intero codice della funzione inline viene inserito o sostituito nel punto della chiamata di funzione inline. Questa sostituzione viene eseguita dal compilatore C++ in fase di compilazione, non a runtime. Questo è particolarmente utile nel caso in cui il tempo necessario ad eseguire il cambio di contesto sia maggiore del tempo di esecuzione della funzione, e questo si verifica se la funzione è estremamente piccola, e permette così di migliorare le prestazioni.
https://github.com/devraza/warehouse
https://raw.githubusercontent.com/devraza/warehouse/main/blog/selfhost-search-engine.typ
typst
MIT License
#import "template.typ": conf #show: doc => conf( title: [ Host your own private search engine with SearXNG ], doc, ) = Introduction #link("https://docs.searxng.org/")[SearXNG];, put in its own words, is a 'free internet metasearch engine'. Note that it describes itself as a #emph[metasearch] engine specifically - unlike your traditional search engine like Google or Bing, SearXNG does things a little bit differently: It aggregrates the results produced by search services like those aforementioned, and feeds them back to you. Because of this key detail and a great deal of effort by those who’ve helped shape it, SearXNG protects your privacy, and does so very well: - Private data from requests going to the search services it aggregrates results from is removed - It does #strong[not] forward #emph[anything] to any third parties through search services - Private data is #emph[also] removed from requests going to the results pages Furthermore, SearXNG can be configured to use #link("https://torproject.org")[Tor];. However, the aspect of privacy isn’t the only great selling feature of the engine; from my use of the engine so far, it’s also great at…searching \(is that a surprise?). The fact that it’s a metasearch engine plays a key role in this, as it provides SearXNG the ability to pull content more efficiently and gives #emph[you] the ability to further tailor your experience. = Setting up SearXNG == Installing the service As you may have expected if you’ve used NixOS for a while, searxng is packaged #emph[and] has a service on NixOS. This makes setting it up just that much easier. To get started, place somewhere in your #emph[system] config the following: ```nix { # ... services.searx = { enable = true; settings = { server = { port = 8888; bind_address = "127.0.0.1"; secret_key = "@SEARX_SECRET_KEY@"; base_url = "https://search.devraza.duckdns.org/"; # replace with wherever you want to host yours }; }; }; # ... } ``` The snippet above starts the `searx` systemd service for listening on port `8888`, and assumes a `base_url` of `https://search.devraza.duckdns.org`. Now that we’ve got the actual `searx` instance running, we can now set up a reverse proxy allowing the service to be accessed remotely \(whether this is within your local network or across the internet is up to you). == Setting up a reverse proxy === What is a reverse proxy? Before I get started with the technical details of setting this up, I’d like to briefly clarify what a reverse proxy exactly is \(to my understanding). Let’s get the wikipedia definition of reverse proxy out of the way first: #quote(block: true)[ \[…\] a reverse proxy is an application that sits in front of back-end applications and forwards client requests to those applications. \[…\] ] However, you might be confused as to what this actually means; I’ll give an example of the usage of reverse proxies to better explain this: - Suppose you’ve got a few services running on a server \(for demonstration purposes, let’s name these `x`, `y` and `z`), each running on their own unique port. - Assuming you had a domain, and wanted to access all of these services from their own unique sub-domains \(e.g.~`x.yourdomain.com`, `y.yourdomain.com` and `z.yourdomain.com`), you would have to use a reverse proxy. - This reverse proxy would take in requests from clients going to sub-domains, and forward these requests to the appropriate port on your machine for the service being requested. The concept should be clear now, if it wasn’t already. === Using NGINX to set up the reverse proxy NGINX is a popular web server that supports the creation of virtual hosts and the usage of reverse proxies. To accomodate our `searx` instance, we append the following to our NixOS server configuration: ```nix { # ... services.nginx = { enable = true; # any extra configuration here virtualHosts = { "search" = { # this can be anything, being an arbitrary identifier forceSSL = true; serverName = "search.yourdomain.com"; # replace this with whatever you're serving from # SearX proxy locations."/" = { proxyPass = "http://${toString config.services.searx.settings.server.bind_address}:${toString config.services.searx.settings.server.port}"; proxyWebsockets = true; recommendedProxySettings = true; }; }; }; }; # ... } ``` The expression highlighted above is used to dynamically adjust the location NGINX will forward requests to, depending on your `searx` config After saving your changes and rebuilding your server’s system configuration \(as usual), you should have a working #emph[private] instance of SearXNG that you can access using the `serverName` you’ve given it. Set your browser to use this as your search engine using the relevant documentation \(with Firefox this is as easy as right-clicking on the URL after opening up the page and clicking a button). Enjoy!
https://github.com/elpekenin/access_kb
https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/content/utils.typ
typst
// small pieces of code move from main file to reduce its size #let _code( source, caption, kind, supplement, ) = { assert(caption != "", message: "Provide a caption") return figure( [#source], caption: caption, kind: kind, supplement: supplement, ) } #let snippet(source, caption: "") = { return _code(source, caption, "snippet", "Código") } #let cli(source, caption: "") = { // replace "$" with actual input prompt let _source = raw( source.text.replace("$", "elpekenin@PC:~$"), block: source.block, lang: source.lang, ) return _code(_source, caption, "cmd", "Comando") }
https://github.com/eliapasquali/typst-thesis-template
https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/preface/firstpage.typ
typst
Other
#let logo = "../images/unipd-logo.svg" #import "../config/variables.typ": myUni, myDepartment, myFaculty, myTitle, myDegree, profTitle, myProf, myName, myMatricola, myAA #import "../config/constants.typ": supervisor, undergraduate, academicYear, ID #set page(numbering: none) #grid( columns: (auto), rows: (1fr, auto, 20pt), // Intestazione [ #align(center, text(18pt, weight: "semibold", myUni)) #v(1em) #align(center, text(14pt, weight: "light", smallcaps(myDepartment))) #v(1em) #align(center, text(12pt, weight: "light", smallcaps(myFaculty))) ], // Corpo [ // Logo #align(center, image(logo, width: 50%)) #v(30pt) // Titolo #align(center, text(18pt, hyphenate: false, weight: "semibold", myTitle)) #v(10pt) #align(center, text(12pt, weight: "light", style: "italic", myDegree)) #v(40pt) // Relatore e laureando #align(left, text(12pt, weight: 400, style: "italic", supervisor)) #v(5pt) #align(left, text(11pt, profTitle + myProf)) #align(right, text(12pt, weight: 400, style: "italic", undergraduate)) #v(5pt) #align(right, text(11pt, myName)) #v(5pt) #align(right, text(11pt, [_ #ID _ ] + myMatricola)) #v(30pt) ], // Piè di pagina [ // Anno accademico #line(length: 100%) #align(center, text(8pt, weight: 400, smallcaps(academicYear + " " + myAA))) ] )
https://github.com/akagiyuu/math-document
https://raw.githubusercontent.com/akagiyuu/math-document/main/constant/ramanujan.typ
typst
#set text(size: 20pt) $ e^(pi sqrt(163)) approx 640320^3 + 744 $
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/hanoi.typ
typst
#import "@preview/cetz:0.2.2" #let _hanoi( n, disks, arrow ) = cetz.canvas(length: 100%, { import cetz.draw: * let spacing = 8pt let height = (n+1)*spacing set-style(content: (padding: 4pt)) line((), (1, 0)) circle((1/6, 0), radius: 0, name: "A") circle((3/6, 0), radius: 0, name: "B") circle((5/6, 0), radius: 0, name: "C") for peg in ("A", "B", "C") { line(peg, (rel: (0, height)), name: "peg_" + peg) let disks = disks.at(peg, default: ()) move-to(peg) for disk in disks.rev() { assert(disk.size <= n) let length = disk.size/(3*n) move-to((rel: (-length/2, spacing))) line( (), (rel: (length, 0)), stroke: 4pt + disk.at("fill", default: black), name: peg + "_disk_" + str(disk.size) ) move-to((rel: (-length/2, 0))) } } if arrow != none { assert(arrow.len() == 2) let (from, to) = arrow.map(p => "peg_" + p + ".end") line( (rel: (0, 6pt), to: from), (rel: (0, 6pt), to: to), stroke: none, name: "arrow" ) bezier-through( "arrow.start", (rel: (0, 8pt), to: "arrow.mid"), "arrow.end", mark: (end: "straight") ) } }) // n: Maximum number of disks // a: disks on peg A // b: disks on peg B // c: disks on peg C // Each disk is a dictionary with keys size, fill #let hanoi( n: auto, a: (), b: (), c: (), arrow: none ) = { if n == auto { n = calc.max( ..(a + b + c).map(disk => disk.size), 0 ) } _hanoi(n, (A: a, B: b, C: c), arrow) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-D800.typ
typst
Apache License 2.0
#let data = ( "0": ("<Non Private Use High Surrogate, First>", "Cs", 0), "37f": ("<Non Private Use High Surrogate, Last>", "Cs", 0), )
https://github.com/andreasKroepelin/TypstJlyfish.jl
https://raw.githubusercontent.com/andreasKroepelin/TypstJlyfish.jl/main/typst/jlyfish.typ
typst
MIT License
#import "@preview/based:0.1.0": base64 #let jlyfish-output-data = state("jlyfish-output-data", (:)) #let jlyfish-code-counter = counter("jlyfish-code-counter") #let read-julia-output(data) = { assert.eq(type(data), dictionary) for (_id, evaluation) in data { assert.eq(type(evaluation), dictionary) for k in evaluation.keys() { assert(k in ("result", "stdout", "logs", "code")) } } jlyfish-output-data.update(data) } #let jl-pkg(cmd: "add", ..pkgs) = { let pkgs = pkgs.pos() assert(pkgs.all(pkg => type(pkg) == str)) [#metadata((cmd: cmd, pkgs: pkgs)) <jlyfish-data>] } #let jl-raw( preferred-mimes: (), recompute: true, display: false, fn: evaluated => none, it ) = { if type(preferred-mimes) != array { preferred-mimes = (preferred-mimes, ) } context { let id = str(jlyfish-code-counter.get().first()) let output = jlyfish-output-data.get() // box(inset: 3pt, fill: aqua, radius: 3pt)[#id] [#metadata(( preferredmimes: preferred-mimes, code: it.text, id: id, display: display, recompute: recompute, )) <jlyfish-data>] let ev = output.at(id, default: none) if ev == none { [*??*] } else if ev.code != it.text { // out of sync [*??*] } else { fn(ev) } } jlyfish-code-counter.step() } #let jl( preferred-mimes: (), recompute: true, code: false, result: auto, stdout: auto, logs: auto, it ) = { let relevant-result(result) = not ( result.mime == "text/plain" and result.data in ("", "nothing") ) let display-result(result) = { if result.mime == "text/plain" { // set align(bottom) set text(fill: red, weight: "bold") if result.failed // raw(block: false, lang: "julia-text-output", result.data) text(result.data) } else if result.mime == "text/typst" { eval(result.data, mode: "markup") } else if result.mime.starts-with("image/") { let format = "unknown format" let img-data = () if result.mime == "image/png" { format = "png" img-data = base64.decode(result.data) } else if result.mime == "image/jpg" { format = "jpg" img-data = base64.decode(result.data) } else if result.mime == "image/svg+xml" { format = "svg" img-data = result.data } image.decode(img-data, format: format) } else { panic("Unsupported MIME type: " + result.mime) } } let relevant-stdout(output) = output != "" let display-stdout(output) = { let output-block-selector = raw.where(block: true, lang: "stdout") // show output-block-selector: set block( // above: 1pt, // width: 80%, // fill: luma(100), // inset: 3pt, // ) // show output-block-selector: set text(fill: luma(250)) linebreak() text(size: .6em)[_stdout:_] raw(block: true, lang: "stdout", output) } let relevant-logs(logs) = logs.len() > 0 let display-logs(logs) = { let display-attachment(attachment) = { let (key, val) = attachment ( raw(key + " ="), display-result(val) ) } let display-attachments(attached) = if attached.len() > 0 { set text(size: .6em) grid( columns: 2, column-gutter: .8em, row-gutter: .3em, ..attached.pairs().map(display-attachment).flatten() ) } let icons = ( (min: 2000, color: red, text: [e]), (min: 1000, color: orange, text: [w]), (min: 0, color: aqua, text: [i]), (min: -calc.inf, color: gray, text: [d]), ) let display-log(log) = { let icon = icons.find(it => log.level.level >= it.min) ( // text(fill: gray, weight: "bold")[log], text(fill: icon.color, weight: "bold", icon.text), align(bottom, { text(size: .8em, log.message) // text(size: .8em, eval(log.message, mode: "markup")) display-attachments(log.attached) }) ) } grid( columns: (auto, 1fr), column-gutter: 1em, row-gutter: .5em, ..logs.map(display-log).flatten() ) } let fn(evaluated) = { if code { it } if result != false and relevant-result(evaluated.result) { display-result(evaluated.result) } if stdout != false and relevant-stdout(evaluated.stdout) { display-stdout(evaluated.stdout) } if logs != false and relevant-logs(evaluated.logs) { display-logs(evaluated.logs) } } jl-raw( preferred-mimes: preferred-mimes, recompute: recompute, display: true, fn: fn, it ) }
https://github.com/mumblingdrunkard/mscs-thesis
https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/utils/latex.typ
typst
#let size = ( tiny: text.with(size: 5pt), scriptsize: text.with(size: 7pt), footnotesize: text.with(size: 8pt), small: text.with(size: 9pt), normalsize: text.with(size: 10pt), large: text.with(size: 12pt), Large: text.with(size: 14.4pt), LARGE: text.with(size: 17.28pt), huge: text.with(size: 20.74pt), Huge: text.with(size: 24.88pt), )
https://github.com/Lypsilonx/boxr
https://raw.githubusercontent.com/Lypsilonx/boxr/main/boxr.typ
typst
MIT License
#import "util.typ": * #let get-structure-size(structure-path, ..args) = { let structure = none if type(structure-path) == str { structure = json("structures/" + structure-path + ".json") } else { structure = structure-path } return (get-from-args(args, structure.width), get-from-args(args, structure.height)) } #let render-structure(structure-path, color: none, fold-stroke: 0.3mm + gray, cut-stroke: 0.3mm + black, glue-pattern: none, clip: true, ..args) = { let get-structure-offset(structure, args) = { return (get-from-args(args, structure.offset-x), get-from-args(args, structure.offset-y)) } let render-face(face, color, fold-stroke, cut-stroke, glue-pattern, clip, args, last-size: none, offset: (0mm,0mm), comes-from: none) = { let has-child = ( top: false, left: false, bottom: false, right: false ) let comes-from-triangle = comes-from if comes-from-triangle == none { comes-from-triangle = "bottom" } let width = if comes-from == none { get-from-args(args, face.width) } else { if comes-from == "top" { last-size } else if comes-from == "left" { get-from-args(args, face.size) } else if comes-from == "bottom" { last-size } else if comes-from == "right" { get-from-args(args, face.size) } } let height = if comes-from == none { get-from-args(args, face.height) } else { if comes-from == "top" { get-from-args(args, face.size) } else if comes-from == "left" { last-size } else if comes-from == "bottom" { get-from-args(args, face.size) } else if comes-from == "right" { last-size } } if (face.type == "box") { place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #box( width: width, height: height, fill: color, clip: clip, if face.keys().contains("id") and args.pos().len() > face.id {args.pos().at(face.id)} ) ] } else if (face.type.starts-with("triangle")) { let direction = face.type.split("-").at(1) assert(direction == "left" or direction == "right", message: "Triangle direction must be either 'left' or 'right'") let points = calculate-triangle-points(comes-from-triangle, direction, width, height) place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #polygon( fill: color, stroke: 0mm, ..points ) ] let triangle-line-type = cut-stroke if comes-from-triangle == "top" { has-child.at("bottom") = true if direction == "left" { has-child.at("left") = true if face.keys().contains("children") and face.children.keys().contains("left") and face.children.left == "none" { triangle-line-type = 0mm } } else { has-child.at("right") = true if face.keys().contains("children") and face.children.keys().contains("right") and face.children.right == "none" { triangle-line-type = 0mm } } } else if comes-from-triangle == "left" { has-child.at("right") = true if direction == "left" { has-child.at("bottom") = true if face.keys().contains("children") and face.children.keys().contains("bottom") and face.children.bottom == "none" { triangle-line-type = 0mm } } else { has-child.at("top") = true if face.keys().contains("children") and face.children.keys().contains("top") and face.children.top == "none" { triangle-line-type = 0mm } } } else if comes-from-triangle == "bottom" { has-child.at("top") = true if direction == "left" { has-child.at("right") = true if face.keys().contains("children") and face.children.keys().contains("right") and face.children.right == "none" { triangle-line-type = 0mm } } else { has-child.at("left") = true if face.keys().contains("children") and face.children.keys().contains("left") and face.children.left == "none" { triangle-line-type = 0mm } } } else if comes-from-triangle == "right" { has-child.at("left") = true if direction == "left" { has-child.at("top") = true if face.keys().contains("children") and face.children.keys().contains("top") and face.children.top == "none" { triangle-line-type = 0mm } } else { has-child.at("bottom") = true if face.keys().contains("children") and face.children.keys().contains("bottom") and face.children.bottom == "none" { triangle-line-type = 0mm } } } place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #line( start: if direction == "left" {points.at(0)} else {points.at(1)}, end: points.at(2), stroke: triangle-line-type ) ] } else { assert(false, message: "Unknown face type: " + face.type) } if face.keys().contains("children") { for child in face.children.values().enumerate() { let add-offset = (0mm,0mm) let orientation = face.children.keys().at(child.at(0)) let next-comes-from = none has-child.at(orientation) = true assert(orientation != comes-from, message: "Face cannot have a child coming from the same direction as it is coming from") assert(not (face.type.starts-with("triangle") and ((orientation == "right" and comes-from-triangle == "left") or (orientation == "top" and comes-from-triangle == "bottom") or (orientation == "left" and comes-from-triangle == "right") or (orientation == "bottom" and comes-from-triangle == "top"))), message: "Triangle does not support children to the opposite side of the parent face") if type(child.at(1)) == str { if child.at(1).starts-with("tab\u{0028}") { let tab-args = child.at(1).split("\u{0028}").at(1).split("\u{0029}").at(0) let tab-size = get-from-args(args, tab-args.split(",").at(0)) let tab-cutin = get-from-args(args, tab-args.split(",").at(1)) if (face.type.starts-with("triangle")) { let direction = face.type.split("-").at(1) let points = calculate-triangle-points(comes-from, direction, width, height) let line-points = (if direction == "left" {points.at(0)} else {points.at(1)}, points.at(2)) let l1 = (line-points.at(1).at(1) - line-points.at(0).at(1)).pt() let l2 = (line-points.at(1).at(0) - line-points.at(0).at(0)).pt() let angle = 90deg - calc.atan2(l1, l2) + if direction == "left" {180deg} else {0deg} let length = calc.sqrt(calc.pow(l2, 2) + calc.pow(l1, 2)) * 1pt // half of the tab size in the normal direction of the line let add-offset = ( calc.sin(angle) * tab-size / 2, -calc.cos(angle) * tab-size / 2 ) if ((comes-from == "right" and direction == "left" and orientation == "top") or (comes-from == "right" and direction == "right" and orientation == "bottom") or (comes-from == "left" and direction == "right" and orientation == "top") or (comes-from == "left" and direction == "left" and orientation == "bottom") or (comes-from == "top" and direction == "left" and orientation == "left") or (comes-from == "top" and direction == "right" and orientation == "right") or (comes-from == "bottom" and direction == "right" and orientation == "left") or (comes-from == "bottom" and direction == "left" and orientation == "right")) { place( center + horizon, dx: offset.at(0) + add-offset.at(0), dy: offset.at(1) + add-offset.at(1) )[ #tab( length, tab-size, tab-cutin, angle, color, cut-stroke, fold-stroke, glue-pattern ) ] continue } } if orientation == "top" { place( center + horizon, dx: offset.at(0), dy: offset.at(1) -(height + tab-size) / 2, )[ #tab( width, tab-size, tab-cutin, 0deg, color, cut-stroke, fold-stroke, glue-pattern ) ] } else if orientation == "left" { place( center + horizon, dx: offset.at(0) - (width + tab-size) / 2, dy: offset.at(1) )[ #tab( height, tab-size, tab-cutin, 270deg, color, cut-stroke, fold-stroke, glue-pattern ) ] } else if orientation == "bottom" { place( center + horizon, dx: offset.at(0), dy: offset.at(1) + (height + tab-size) / 2 )[ #tab( width, tab-size, tab-cutin, 180deg, color, cut-stroke, fold-stroke, glue-pattern ) ] } else if orientation == "right" { place( center + horizon, dx: offset.at(0) + (width + tab-size) / 2, dy: offset.at(1) )[ #tab( height, tab-size, tab-cutin, 90deg, color, cut-stroke, fold-stroke, glue-pattern ) ] } } else if child.at(1) == "none" { } else { assert(false, message: "Unknown child type: " + child.at(1)) } continue } if (face.type.starts-with("triangle")){ let direction = face.type.split("-").at(1) assert(not ((comes-from-triangle == "right" and direction == "left" and orientation == "top") or (comes-from-triangle == "right" and direction == "right" and orientation == "bottom") or (comes-from-triangle == "left" and direction == "right" and orientation == "top") or (comes-from-triangle == "left" and direction == "left" and orientation == "bottom") or (comes-from-triangle == "top" and direction == "left" and orientation == "left") or (comes-from-triangle == "top" and direction == "right" and orientation == "right") or (comes-from-triangle == "bottom" and direction == "right" and orientation == "left") or (comes-from-triangle == "bottom" and direction == "left" and orientation == "right")), message: "Triange does not support children to come from angeled sides") } if orientation == "top" { add-offset = ( 0mm, -(height + get-from-args(args, child.at(1).size)) / 2 ) next-comes-from = "bottom" } else if orientation == "left" { add-offset = ( -(width + get-from-args(args, child.at(1).size)) / 2, 0mm ) next-comes-from = "right" } else if orientation == "bottom" { add-offset = ( 0mm, (height + get-from-args(args, child.at(1).size)) / 2 ) next-comes-from = "top" } else if orientation == "right" { add-offset = ( (width + get-from-args(args, child.at(1).size)) / 2, 0mm ) next-comes-from = "left" } render-face( child.at(1), color, fold-stroke, cut-stroke, glue-pattern, clip, args, offset: (offset.at(0) + add-offset.at(0), offset.at(1) + add-offset.at(1)), comes-from: next-comes-from, last-size: if orientation == "top" or orientation == "bottom" {width} else {height} ) } } if not has-child.at("top") { place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #line( start: (0mm, -height / 2), end: (width, -height / 2), stroke: if comes-from == "top" { if face.keys().contains("no-fold") { 0mm } else { fold-stroke } } else { cut-stroke } ) ] } if not has-child.at("left") { place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #line( start: (-width / 2, 0mm), end: (-width / 2, height), stroke: if comes-from == "left" { if face.keys().contains("no-fold") { 0mm } else { fold-stroke } } else { cut-stroke } ) ] } if not has-child.at("bottom") { place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #line( start: (0mm, height), end: (width, height), stroke: if comes-from == "bottom" { if face.keys().contains("no-fold") { 0mm } else { fold-stroke } } else { cut-stroke } ) ] } if not has-child.at("right") { place( center + horizon, dx: offset.at(0), dy: offset.at(1) )[ #line( start: (width, 0mm), end: (width, height), stroke: if comes-from == "right" { if face.keys().contains("no-fold") { 0mm } else { fold-stroke } } else { cut-stroke } ) ] } } if glue-pattern == none { glue-pattern = pattern-glue(gray) } let structure = none if type(structure-path) == str { structure = json("structures/" + structure-path + ".json") } else { structure = structure-path } for variable in structure.variables { assert(args.named().keys().contains(variable), message: "Structure needs variable: " + variable) } let structure-size = get-structure-size(structure, ..args) let structure-offset = get-structure-offset(structure, args) block( width: structure-size.at(0), height: structure-size.at(1), //stroke: cut-stroke )[ #place( center + horizon, dx: (structure-offset.at(0)) / 2, dy: (structure-offset.at(1)) / 2 )[ #render-face(structure.root, color, fold-stroke, cut-stroke, glue-pattern, clip, args) ] ] }
https://github.com/wangwhh/AETG-algorithm
https://raw.githubusercontent.com/wangwhh/AETG-algorithm/master/README.md
markdown
# README ## 简介 该项目是浙江大学软件质量保证与测试课程作业,实现了AETG算法,基于京东和携程的网站建模信息,生成T-wise的组合测试用例。 ## 查看帮助信息 ``` python code/run.py -h ``` ``` usage: run.py [-h] [-t T] [-w {jingdong,xiecheng}] [--max MAX] [--min MIN] [-o OUTPUT] options: -h, --help show this help message and exit -t T Covered Array 的强度 (T-wise converage) -w {jingdong,xiecheng}, --website {jingdong,xiecheng} 被测网站的名称,目前支持 jingdong 和 xiecheng --max MAX 候选测试用例的最大数量 --min MIN 候选测试用例的最小数量 -o OUTPUT, --output OUTPUT 测试用例的输出文件名,默认为 output.csv ``` ## 运行程序 ``` python code/run.py # 添加你需要的参数 ``` #### 后记 感觉这是软测课上为数不多的有点学到的东西(这是可以说的吗 其实感觉没有完全按照 AETG 的算法来实现,在生成候选集的时候应该排除已经使用过的值,但是懒得搞了( 第一次用 typst 写报告,感觉很爽!!好用!(虽然是用了 PeiPei 的模板 [PeiPei233/typst-template](https://github.com/PeiPei233/typst-template))
https://github.com/liketechnik/aoc2023
https://raw.githubusercontent.com/liketechnik/aoc2023/main/01.typ
typst
// vim: ft=typst #set text( size: 12pt, font: "STIX Two Text", lang: "en", region: "US", ) #show raw: set text(font: "Recursive Mn Lnr St") #show math.equation: set text(font: "STIX Two Math") #set page( width: auto, height: auto, ) #set document(title: "Advent of Code - Day 01, Part 1", author: "liketechnik") #let exercise = read("./input01").trim() #let lines = exercise.split("\n") #let regNumber = regex("[0-9]") #let first_numbers = lines.map(line => line.find(regNumber)) #let second_numbers = lines.map(line => line.rev().find(regNumber)) #let numbers = first_numbers.zip(second_numbers).map(digits => digits.fold("", (a, i) => a + i)).map(s => int(s)) #let result1 = numbers.fold(0, (sum, v) => sum + v) #let regNumber = regex("[0-9]|one|two|three|four|five|six|seven|eight|nine") #let firstNumbers = lines.map(line => line.find(regNumber)) #let regNumber = regex("[0-9]|eno|owt|eerht|ruof|evif|xis|neves|thgie|enin") #let secondNumbers = lines.map(line => line.rev().find(regNumber).rev()) #let numbers = firstNumbers.zip(secondNumbers) #let toNumber(string) = { let map = ( one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ) let val = map.pairs().find(p => p.at(0) == string) if val != none { val.at(1) } else { int(string) } } #let asNums = numbers.map(v => (toNumber(v.at(0)), toNumber(v.at(1)))).map(v => (v.at(0) * 10) + v.at(1)) #let result2 = asNums.fold(0, (sum, v) => sum + v) #figure(caption: "Advent of Code Day 01")[ #table( columns: (auto, auto), [Part 1], [Part 2], [#result1], [#result2], ) ]
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/line_break/line_break.typ
typst
$z - x = y$\ $arrow.r.long$\ $x + y = z$ $a + b = c$
https://github.com/andrin-geiger/hslu_template_typst
https://raw.githubusercontent.com/andrin-geiger/hslu_template_typst/master/chapters/02_state-of-research.typ
typst
= Stand der Technik #pagebreak()
https://github.com/HPDell/typst-starter-journal-article
https://raw.githubusercontent.com/HPDell/typst-starter-journal-article/main/assets/custom-author-info.typ
typst
MIT License
#import "@preview/starter-journal-article:0.3.1": article, author-meta #set page(margin: 12pt, width: 6in, height: 5in) #show: article.with( title: "Artile Title", authors: ( "<NAME>": author-meta("UCL", email: "<EMAIL>"), "<NAME>": author-meta("TSU") ), affiliations: ( "UCL": "UCL Centre for Advanced Spatial Analysis, First Floor, 90 Tottenham Court Road, London W1T 4TJ, United Kingdom", "TSU": "Haidian District, Beijing, 100084, P. R. China" ), abstract: [#lorem(20)], keywords: ("Typst", "Template", "Journal Article"), template: ( author-info: (authors, affiliations) => { set align(center) show: block.with(width: 100%, above: 2em, below: 2em) let first_insts = authors.map(it => it.insts.at(0)).dedup() stack( dir: ttb, spacing: 1em, ..first_insts.map(inst_id => { let inst_authors = authors.filter(it => it.insts.at(0) == inst_id) stack( dir: ttb, spacing: 1em, { inst_authors.map(it => it.name).join(", ") }, { set text(0.8em, style: "italic") affiliations.values().at(inst_id) } ) }) ) } ) ) = Introduction #lorem(20)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/057%20-%20Bloomburrow/001_Episode%201%3A%20Calamity%20Comes%20to%20Valley.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1: Calamity Comes to Valley", set_name: "Bloomburrow", story_date: datetime(day: 01, month: 07, year: 2024), author: "<NAME>", doc ) #strong[Helga] Helga stared at the midmorning sunlight glinting on the rippling surface of the water, its patterns and portents as inscrutable as its darker depths. Cattails and long grasses swayed above her, and a bright dragonfly chased a cloud of gnats. Warm muck and growing things scented the air, comforting her uneasy heart. The pencil she gripped seemed to move of its own accord as her other hand balanced her leaf-bound journal on her lap. #figure(image("001_Episode 1: Calamity Comes to Valley/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) She'd come to the shore seeking clarity, quiet, and a brief escape from the worries that plagued her. From this angle, she couldn't see her own reflection, familiar and boring: one smallish frogfolk, green skin, amber eyes, and a perpetual nervous smile. Nothing special, now or ever. Unless being especially useless could be considered remarkable. Something shifted in the pond, or shimmered above it in a haze of heat. Helga squinted, leaning forward, wondering if she was about to have another vision— A long-eared shadow fell over her from behind, and a hand touched her shoulder. With a yelp, Helga leaped into the air, high enough to bump her head on a cattail spike before landing gracelessly in a heap of long legs. "Steady on, Helga, my girl," said Nerys, the rabbitfolk's nose twitching with humor or irritation. "There's no call for dramatics." "Sorry," Helga said, collecting her dropped journal. "You startled me is all." "And I wouldn't be doing that if you were about something useful," Nerys retorted, "instead of fishing for visions. Are your village chores finished?" Helga winced. "Not exactly. I was in the still-room, tending the fire for a batch of witch hazel infusion, but …" "But?" "But I didn't. Tend it. Euan said the medicine was ruined, and not to darken his doorstep again until his temper cooled like the fire." He'd used more colorful language, but Helga wasn't about to repeat it. "That's just like you." Nerys tipped her leaf-brimmed hat back so she could pin Helga with a red-eyed glare. "Your grandparents coddled you, bless their memories, but you can't while away your life doodling." The reminder of her loss cut Helga more sharply than what Nerys had said, but the rabbitfolk wasn't finished delivering her scold. "And get your head out of yon scrying pool," Nerys added with a jab of her paw. "You need to live in the here and now instead of trying to see what the future holds. None of that ever did anyone a lick of good." "Sometimes seeing possible futures can help folk make better choices in the present," Helga said, her smile wavering. "Be that as it may," Nerys replied, "I've no time for philosophy when there are crops to harvest. I hope your future includes more work and less cloud spying." With a flick of her fluffy tail, Nerys left Helga to her interrupted sketching. Helga sighed. Nerys was only saying what so many folk in Pondside were thinking. In all her seasons living in the small village, Helga still hadn't found her place, her calling. She began to despair that she ever would. Around her, others went through the work of their day. Rabbitfolk with muddied feet cut and tied long stems of watercress for loading into wheelbarrows bound for the communal stores. Otterfolk ran nets through the shallow waters offshore, catching minnows and dumping them into wooden barrels. A frogfolk father passed a cluster of crested irises, carrying a water-filled container of his precious tadpoles on his back. Everyone was busy, at peace—joking with friends, splashing each other to cool the sun's heat, or diligently focused on their labors. Helga struggled to focus on any chores long enough to finish them. The stillroom incident was only one in a long list of similar problems. Burnt carrot muffins, half-planted pea shoots, quilt pieces forever waiting to be sewn together … If she was interested enough in her task, she could lose hours and forget her surroundings completely; sadly, few activities inspired that sort of devotion. Even learning to weave magic had ended poorly. Perhaps if she could have spent another few seasons in Fountainport, completed her training with King Glarb—but no, best not to dwell. She carried enough shame about her inadequacies to last through all the remaining seasons of her life. At least she'd always have her art. She'd kept her journal closed during her conversation with Nerys, not wanting the rabbitfolk to see whatever she'd drawn. Sometimes it was mere whorls and waves that couldn't even rightly be called patterns. Sometimes she drew what she saw, studying brightly clad birdfolk in flight or barefoot mousefolk stomping juice from freshly picked blueberries. Sometimes a vision took over her hands, and she was left with a mystery—or, as others claimed, the products of an overactive imagination. Helga opened the book and idly flipped to the page she'd been working on. The picture made her skin tighten and her mouth dry to sticky discomfort. One of the tomes in King Glarb's library in Fountainport contained lavish, colorful illustrations of Calamity Beasts—the fearsome heralds of nature's changes, both seasonal and chaotic. Helga had never seen one herself, though their handiwork was in evidence whenever a blackberry harvest withered in a sudden drought or a spring rain turned to battering hail. What she'd drawn most closely resembled the Sun Hawk, though her rendering was crude compared to the king's tome. A crest at the top of its head angled backward like the dorsal fin of some fish. The hooked beak lay open as if in mid-cry, flanked by strange whiskery protrusions, the thick tongue forked at the end like nothing she'd ever seen. Instead of two wings, it had four, the usual primary feathers at the wingtip replaced with fingers and membranes like a batfolk's. The talons, at least, seemed typical, though imagining herself at their mercy was enough to give her nightmares while wide awake. Her penciled lines conveyed power, ferocity, the shading behind the creature suggesting a thunderous storm rather than a bright, blazing sky. Despite the day's warmth, Helga shivered. This had to be a vision. She would never think to draw such a terrifying thing herself. She needed to show it to Iver, the village's frogfolk augur. Except … perhaps because she'd never completed her magical training, he always dismissed her visions as mere dreams or fancies. Cries for attention, even, in the wake of her grandparents' passing. This time would be different. It had to be. If she were having a true seeing of a Calamity Beast, her village could be in grave danger. Helga stowed her journal in her pack and headed for Iver's house. His neighbor Annik, in the middle of sweeping her porch, said Iver had gone to pick up some clothing that a mousefolk in the farther fields was mending for him. Helga trekked onward, down the single main road of what passed for the village proper, which led the few travelers from Haymeadow in the south straight through toward Dewrim, Mintvale, and other points north. She walked past mousefolk covering the roof of a weathered wood home with water lily petals, past rabbitfolk digging up plump red radishes with brilliant green leaves, past a gathering of elders sipping mugwort tea beneath the shade of a cluster of leafy bee balm that would bloom when summer arrived. She considered stopping and requesting a drink from them but decided it would be best to finish her errand before she talked herself out of it. Thankfully, Helga was saved the trouble of further fretting by the sight of Iver ambling in her direction, his broad lily-pad hat shading his eyes. She would show him the drawing, hear what he had to say, and go back to … What? She'd figure something out. Her grandparents' home, now hers, no doubt wanted cleaning. Lunch would come soon enough, then dinner, an endless procession of meals and days stretching into the future. Nerys was right: contemplating such things helped no one, least of all herself. A clanging rang out, echoing across the fields. Helga turned toward the source of the noise: a mousefolk atop a watch tower, frantically banging the village's warning bell. But why? She turned, following the direction of their gaze toward the sky. High above, a huge shadow soared and circled in eerie silence. The creature was enormous, its wingspan as broad as the branches of an oak tree. Deep blue and violet on its belly, breast, and wings transitioned to black-striped primaries and tail feathers. Turquoise magic suffused its beautiful, terrible form, lit up its eyes and beak within the hollow of its face, limned its deadly talons. In its wake, velvety night followed, cutting across the bright blue like scissors through a cloth to reveal star-flecked darkness beneath. Maha. The Night Owl. #figure(image("001_Episode 1: Calamity Comes to Valley/02.jpg", width: 100%), caption: [Art by: <NAME>isano], supplement: none, numbering: none) Without warning, it swooped in a flurry of wings, skimming the tops of the fields before rising again, trailing twilight. Around Helga, animalfolk squealed or croaked in alarm. Some dropped to the ground, huddled in on themselves, while others froze in place, hoping not to attract the Calamity Beast's attention. Others ran for cover to their nearby homes and burrows or to the shelter of any tall plants that might hide them. Helga fled back down the dirt road, toward the pond, through alternating patches of day and night, sun and gloaming. The owl flanked her on the left, demolishing the mousefolk house with its half-finished roof, sending splinters of wood and shredded white flowers flying. She veered away, and someone crashed into her, recovering and darting past her. As more folk realized the airborne danger, the scattering of scared villagers became a frantic rush. Another dive, another building erupted. The beast's movements were completely quiet, its passing marked only by the ensuing destruction and the chill wind of its wings. Helga's heart tried to leap out of her chest even as she forced herself not to follow suit, lest she be snatched from the air. Sparks from a cook fire joined the shower of debris, and soon flames and smoke heightened the chaos and confusion. The owl's attacks herded Helga and the other animalfolk first one way, then another, until she was completely turned around and unsure of where she'd ended up. She found herself back in the fields, lost in a maze of cabbage heads, running full speed despite the pain in her chest and legs. The world became a bewildering mosaic made from shards of daylight amid the deepening gloom, as if time itself had shattered and couldn't be reformed. The ground fell out from under her as Helga careened over the edge of a muddy embankment. Down she tumbled until she landed in Pond Creek, the thin stream that fed the larger pond beyond. She lay on her side in the soft muck for a dozen ragged heartbeats and heaving breaths, stunned and dizzy. Slowly she rolled to her back. The sky had succumbed to total darkness, moonless and awash with unfamiliar stars. Even the warm scents of mid-morning gave way to the brisk aromas of quiescent flora. She gazed up as if she were a batfolk versed in the necessary skills to read the movements of celestial objects, to divine what she should do now. Helga forced herself to sit, then crouch. The sounds of chaos and destruction were muted by distance, but they continued, nonetheless. She could follow the creek bed to the pond, hoping to find safety with other villagers in the depths of the water and wait until the Night Owl finished its rampage. Or she could head in the opposite direction, toward the nearest village. Warn them of the Calamity Beast's attack, maybe even bring back help. Pondside would need to be dug out of the wreckage left behind, rebuilt, and the folk … No, she wouldn't think of the worst things, the hard things that would need to be done after such a tragedy. Focus on the immediate problem, the next step, not the ones that would come later. Her throat tightened. What would Nerys say, to hear Helga finally living in the present like this? Nothing, likely; just a twitch of her nose and a shake of her head. #emph[Get on with it] , Helga told herself. #emph[Don't stand still and wait for life to happen like you always do. Move.] Heartsick and bruised, Helga clutched the satchel containing her journal and limped along the creek-bed toward the far-off promise of sunshine. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Mabel] The mousey mischief makers were at it again. Mabel stood outside the round door to her home, stirring a bowl of batter as she watched her precious, darling, stubbornly independent children perched on each other's shoulders, wobbling precariously. Rosalyn, the eldest and largest, formed the base, with Foggy on top of her and Pip on top of him. Feet slipped, tails coiled around faces and necks, and high-pitched squeaks of annoyance punctuated every fresh indignity they visited on each other. They were piled in front of the parlor window, trying to hang the banner they had spent hours meticulously painting. It read, "HAPPY BIRTHDAY MABEL"—well, technically it read, "HAPPY BIRTHDAY MAM MABEL" with the word "MAM" crossed out. Their father Clem had kindly noted that Mabel wasn't everyone's mother, the same way he wasn't everyone's papa, and thus the other townsfolk did not have the privilege of addressing her by anything but her given name. He punctuated this gentle correction with kisses for all, including his amused wife, who had her own privileges of the sort that led to three children and general contentment. Truly, her birthday was a beautiful one so far. Sunny without being overwarm, a light breeze ruffling her brown fur, as pleasant as any in late spring had ever been in Goodhill. The daisies and yarrow bloomed in bonny white and yellow clusters overhead, the bees buzzed industriously between their cups of nectar, and—oh, no. Oliver, the mayor, trundled straight toward her. His long ears moved constantly as he tried to eavesdrop on every conversation he passed, and he paused to chat with any of her neighbors lingering outside their woven grass houses, tidying up for the party or taking their afternoon tea. Mabel searched for Clem's plump gray form, but alas, her beloved must still be out trading for the elderberry jam he needed to finish a batch of his famous cookies. Sighing, she donned the armor of a smile and resigned herself to a battle of politely intrusive small talk and good-natured prying. "Mabel!" Oliver called with a wave. He was short, as local rabbitfolk went, with cinnamon-brown fur and a quilted vest in bright greens and yellows. "Happiest of birthdays to you, my dear. You're looking pretty as a portrait." She looked like a tired mother in a flour-coated, jam-stained apron. "Thank you, Oliver," Mabel replied. "You're too kind." In her mind, they crossed swords. His gaze shifted to her mixing bowl. "And what delectable delectations have you and your brilliantly gifted baker of a husband prepared for your party this evening?" If she kept talking long enough, perhaps he wouldn't get the chance to ambush her with whatever he really wanted. She had a feeling she knew what it was. "This will be a strawberry cake," Mabel said brightly, one eye still on her children, who had dropped the banner and were attempting to retrieve it while still atop each other. "First strawberries of the season are ripe now, and you know one strawberry will feed half the town. Clem is making elderberry jam thumbprint cookies to go with the strawberry tarts and muffins and crumble, and we've already frosted the carrot cake. Brynn is bringing her acorn scones, Niall promised us a dandelion and turnip green salad, Vann's making his chamomile fizzy drink, and—" "Such a feast it will be!" Oliver exclaimed. "And a lovely opportunity for so many to gather together in celebration." A deft parry. Foggy put his foot in Rosalyn's ear, which she tolerated with a wince. Pip, alas, then poked the tip of his tail into Foggy's eye, earning him a shrieked scold. Mabel paused her stirring, which was just as well, because the cake would be dense and chewy if she kept at it much longer. "You know, Mabel," Oliver said, leaning closer and speaking in his version of a whisper, which birdfolk in the clouds could hear. "Silver the bard said he plans to share his Order of the Holly Leaf tale, seeing as how it's a special favorite around here. And, naturally, since it's your birthday, given your antecedents. Perhaps this would be an appropriate occasion to bring out that old relic you have tucked away in your attic, as a historical demonstration, as it were?" Mabel would do nothing of the sort. She prepared her own parry and riposte. "I couldn't possibly distract from Silver's performance like that. Poor fellow, imagine me interrupting a perfectly pleasant story to wave around a family heirloom?" "You could, ahem, wait until he finished?" Oliver ventured, his ears widening and angling back slightly. "But then all his efforts would fly right up into the trees, wouldn't they? Instead of everyone complimenting him on his fine work, they'd be attending me, and that would be simply too rude, birthday or not." Mabel shook her head as if regretful. "No, best to leave it in the attic where it belongs and let Silver have his due. Along with some strawberry cake, of course." Dare she hope she'd disarmed him with that one? "Your point is taken," Oliver said, a foot thump signaling he hadn't accepted defeat. "But have you considered that Silver himself might be interested in seeing the relic, hmm?" Not disarmed at all; instead, he renewed his assault. Mabel's mother Iris, in all the seasons she'd been guardian of the artifact, had never brought it out for her neighbors to ogle as if it were a new bonnet or belt. If she were still in town, Oliver wouldn't have dared make his request at all, because Iris would have blistered his ears until he turned tail. Or her father Elis would have spun a refusal so eloquent, Oliver would hardly have known he'd been turned away until he was back in his burrow. Alas, Mabel's parents were on a much-deserved vacation in the northern country, and thus, Mabel was left to fend for herself. She missed them, not only because she was having to manage Oliver, but because it was her birthday, and it would be only the second time in her life that they were separated for the occasion. There would be other birthdays, she had told them, and it was true, but even so. Oliver was preparing another volley of protests when the tiny tower of mouse-children began to sway precariously. Mabel shoved her mixing bowl at Oliver and leaped past him. With one paw, she slung Pip onto her shoulder, and with the other, she pressed Foggy to her chest. Rosalyn landed on her rump, tail curved up over her back. The banner sank to the ground in a pile of fabric, its visible letters now proudly proclaiming "HAP DAY BEL" to all and sundry. "You dropped it again!" Foggy shouted, twisting in Mabel's arm to glare up at his brother. "You made me drop it!" Pip replied, clinging to Mabel's left ear and half her face. "Did not!" "Did so!" Rosalyn simply sighed, stood, and brushed dirt off the seat of her pants. "What's all this fuss about, then?" Clem asked, his own arms laden with provisions and eyes bright with amusement. He might have bussed Mabel's cheek, but it was currently full of sullen child. "Mam saved me!" Pip announced in his sweet, high voice. "Foggy made me drop the banner—" "I did not!" "—and then he almost made me fall—" "I never did!" "—but Mam caught us both and now we're saved and she's a hero!" Mabel exchanged a look with Clem that said they were both suppressing laughter. "She's always been my hero," Clem said loyally. "Now, which of you heroes-in-training is going to help me bake some cookies?" The mention of cookies got their attention, but they hesitated. "We have to finish putting up the banner," Foggy whined. "Why don't Rosalyn and I do that while you wash up?" Clem suggested. "Have to carry all of this inside first, mind. Oh, hello, Oliver, didn't see you there. Can't chat. Much to do before the festivities commence. Mabel?" Rosalyn extracted the jar of elderberry jam from under Clem's arm, while Foggy and Pip fought over who would carry the sugar and who the primrose petals. Clem kept the sack of acorn flour, which was too heavy for the children to manage. Oliver watched it all, utterly bemused until Mabel took her mixing bowl back from him. "Don't let us keep you," Mabel said. "I'm sure you've more rounds to make, ensuring Goodhill's in fine fettle as you do." "Yes, of course," Oliver said, ears resuming their usual outward-facing posture. If he noticed she had dodged further questions about her family heirloom, he didn't say anything of it. The fencing was over for now. Mabel was about to close the door behind her when the sound of rapid footsteps and labored breathing approaching from the road made her hesitate. Jenefer, one of the local weaselfolk, raced up to Oliver and gestured back in the direction she'd come from. "Oliver, you must see this," Jenefer said. "Lowenna's on lookout, she says …" She sucked in a breath. "There's a stranger in Pond Creek, and she don't look well at all." Mabel propped her bowl of batter on the table in the front hall, then grabbed her sheathed rapier from the wall. "Clem!" she called. "Trouble at the creek. Be back in a trice." "Stay safe!" Clem replied. "I'll mind the littles." Oliver and Jenefer had a head start, but Mabel quickly caught up, jogging past white-petal roofs and woven grass walls interspersed with the larger, painted clay burrows favored by rabbitfolk families, including the miller with her tall windmill. Colorful glass containers lined the cobbled street, waiting to collect rainwater from the next spring storm due to pass through any day now. Tidy gardens bloomed with foxglove, starflower, sweet alyssum—and of course, lily of the valley. Towering above it all, the wooden homes of batfolk stood atop long poles, windows dark as their denizens slept until dusk. Curious onlookers paused in their own errands, pushing wheelbarrows, or carrying sacks of groceries, or they poked heads out their windows or stood in front of their cozy homes, asking Oliver what was happening. Mabel paid them no mind, concentrating on getting to the creek as fast as her small legs could carry her. A growing crowd gathered around a young frogfolk collapsed between two waterside homes. The poor thing was caked in mud and clearly exhausted, her pale green skin tinged with gray, her eyes closed. "Give her room," Mabel ordered. The assembled townsfolk obligingly took a few steps backward. "Room, yes," Oliver repeated, panting up to stand beside her. Mabel carefully rested a paw on the frogfolk's head, and her lower eyelids opened, showing only thin crescents of amber beneath dark pupils. "Help … please …" she croaked. "Help with what, friend?" Mabel asked. "What happened to you?" "Attack … Calamity Beast …" The frogfolk's eyelids closed again and she went limp. Unconscious. "Did she say Calamity Beast?" someone behind Mabel squeaked. Murmurs rippled through the crowd like a stiff breeze on a turnip field. Soon, the rumor would sweep over all of Goodhill, and no doubt grow in the telling. "You, and you," Mabel said, pointing. "Fetch Delen and help bring a litter to carry her." The healer was no doubt in the middle of her afternoon nap and wouldn't appreciate the interruption, but needs must. "To where?" Oliver asked. "She can stay with me for now," Mabel replied. "I'll keep her safe." And get the story out of the poor dear as soon as she woke up. #emph[Where had the frogfolk come from? What dire fate might she have barely escaped with her life? ] Mabel gazed into the distance along the creek's winding path, mentally mapping which villages lay in that direction. Then she raised her eyes to the horizon and the afternoon sky dotted with thin clouds, scanning for any sign that a Calamity Beast might turn its wild, destructive power on Goodhill next. Delen arrived eventually, and Oliver wrung his hands as Mabel helped load the frogfolk into the litter. She led the way to her home, considering what she would tell Clem and the children as she clutched her rapier tightly with one hand. #emph[Whatever else happens] , Mabel thought grimly, #emph[my birthday party will have to wait.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Ral] Ever since he returned to Ravnica from Thunder Junction, a single thought popped up randomly in Ral's mind like a storm in a clear sky, during guild meetings and baths and whenever his attention wandered: #emph[Beleren is alive, and I'm going to kill him.] Assuming the damned mage could be killed. But after nearly two years of believing he was dead—lost in the Phyrexian invasion—finding out he'd instead been masquerading as the nightmarish Ashiok so he could steal some kind of weird animal? Well. "I'm going to kill him," Ral muttered, hands laced behind his head as he stared at the ceiling of his bedroom. "Kill whom?" Tomik asked, voice thick with sleep. "Beleren." Tomik raised his head from his pillow to blink at Ral. He was adorable without his glasses, brown hair mussed. "I thought you wanted to find him?" "I do. So I can kill him." Tomik flopped back down. "You're not going to kill him. He's your friend." #emph[Was he? What kind of friend fought and fled without explanation?] "You want to know why he did what he did," Tomik said, as if reading Ral's mind. "You'll never know if you kill him." "Stop being reasonable." Ral pressed a kiss to his husband's mouth to silence him. It didn't work. "Your plan?" Ral traced Tomik's eyebrow with a finger. "I tried planeswalking to him. Ended up on some beach in Ixalan. But I know someone who might be able to track him." Tomik's eyes scanned the dark room as he thought. "Will she help you?" Ral loved having a brilliant husband who didn't need everything explained to him. "I don't see why not. She helped before." "When are you leaving?" "Tomorrow." "If you're leaving tomorrow …" Tomik trailed off as his hands blazed their own trail elsewhere. Yes, his husband was definitely brilliant. But then, Ral would never have settled for less. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "I cannot help you." She stood on a bridge in a well-tended garden, white hair brushing her golden armor, face hidden by her wide-brimmed hat. A breeze shook the branches of a nearby tree, sending a shower of flower petals drifting through the sun-kissed air. "Can't, or won't?" Ral asked. "I can no longer walk the planes. My spark is gone." Ral gritted his teeth in frustration. "You can't feel the Blind Eternities at all?" "No." Her hand moved, whip-fast, snatching a petal in flight. "I'm finally at peace." "Damnit. There must be a way." "Planeswalkers leave aether trails that can be followed. Most of you do it intuitively." "And you?" She released the petal, which spun lazily toward a plot of raked sand. "I used to sense the trails, all the way to the sparks at the end of them." "Sense how?" She sighed. "How can I describe taste to a man with no tongue? Return to the last place you saw him and open your soul." "Great. Thanks." Ral knew she hadn't earned his sarcasm, but he was too bitter to prevent it. He planeswalked away in a shower of sparks, leaving the Wanderer to her palace garden. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The place in Thunder Junction where he last saw Beleren was as empty as Ral had left it. Emptier, even; the vault itself was gone, leaving only the ruins of Tarnation. #emph[No clues, nothing. What had the Wanderer said? Open his soul? Ridiculous.] But he didn't have other options. "Okay, soul," Ral muttered. "Get to it." He closed his eyes and listened. Silence. He sniffed the air. Dust and metal. He fantasized about further wrecking the wreckage with lightning, instinctively reaching out to the weather with his magic. Maybe a nice storm would cheer him up. #emph[Wait.] His power brushed something. A hint of green. It felt smudged, like a word partly erased from paper. #emph[Had Beleren somehow wiped away the memory of his aether trail? That conniving little …] Ral focused on that trace with every part of himself. The sense of greenness bloomed like a flower. Closing his eyes, he followed it into the Blind Eternities— And found himself in a field, surrounded by dandelions. They were taller than any he'd ever seen. So was the grass, and the distant trees. #emph[What plane was this? Where was Beleren?] He ran his hand over his face in disgust, then froze. #emph[What happened to his face? Were those whiskers? Was he covered in fur? Was that … a tail?] "I'm going to kill him!" Ral shouted, his eyes filling with lightning as he shook his paw at the sky.
https://github.com/leesum1/brilliant-cv
https://raw.githubusercontent.com/leesum1/brilliant-cv/master/modules_zh/education.typ
typst
// Imports #import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry, hBar #import "@preview/fontawesome:0.4.0": * #let metadata = toml("../metadata.toml") #let cvSection = cvSection.with(metadata: metadata) #let cvEntry = cvEntry.with(metadata: metadata) #cvSection("教育经历") #cvEntry( title: [计算机科学硕士], society: [杭州电子科技大学], date: [2022 - 2025], location: [浙江-杭州], logo: image("../src/logos/hdu.png"), // description: list([课程: 操作系统 #hBar() 数据结构 #hBar() 计算机组成原理 #hBar() 计算机网络 ]), ) #cvEntry( title: [电子科学与技术学士], society: [中南林业科技大学], date: [2018 - 2022], location: [湖南-长沙], logo: image("../src/logos/csuft.png"), // description: list([课程: 模拟电路设计 #hBar() 数字电路设计 #hBar() 嵌入式程序设计]), )
https://github.com/Ombrelin/adv-java
https://raw.githubusercontent.com/Ombrelin/adv-java/master/Slides/3-qualite.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/sourcerer:0.2.1": code #import themes.clean: * #show: clean-theme.with( logo: image("images/efrei.jpg"), footer: [<NAME>, EFREI Paris], short-title: [EFREI LSI L3 ALSI62-CTP : Java Avancé], color: rgb("#EB6237") ) #title-slide( title: [Java Avancé], subtitle: [Cours 3 : Qualité Logicielle], authors: ([<NAME>]), date: [25 Janvier 2024], ) #new-section-slide("Concepts") #slide(title: "Polymorphisme")[ - Contrats de services (interfaces) - Cacher les détails au code client _ex : `List` avec `LinkedList`/`ArrayList`_ ] #slide(title: "Inversion et injection de dépendances")[ *Injection de dépendances :* Externaliser des comportement dans des classes (dépendances), et les fournir en paramètre du constructeur. *Inversion de dépendance :* Abstraire les dépendance par un contrat de service (une interface) - Code modulaire - Couplages moins forts _-> Le code est plus facile et test, maintenir, refactorer_ ] #slide(title: "Conteneur d'injection de dépendance (IoC Container)")[ Composant qui permet de d'automatiser : - Construction des classes avec leur dépendances - Gestion de leur cycle de vie Exemple de librairies : - Spring - Context Dependency Injection (standard JakartaEE) ] #new-section-slide("Patrons de conception") #slide(title: "Décorateur")[ #image("images/decorator.png", width: 60%) ] #slide(title: "Fabrique")[ - Création d'objet complexe - Découplage de création d'objet ] #slide(title: "Etat")[ #image("images/state.png", width: 46%) ] #new-section-slide("Ecriture du code") #slide(title: "Nommage")[ - Ne pas faire d'abréviations - Ne pas utiliser d'acronymes - Toujours décrire l'objectif du symbole dans son nom - Ne pas avoir peur d'avoir des noms de symboles longs - Utiliser des noms en anglais - Utiliser des noms prononçables - Ne pas utiliser de nombres magiques ] #slide(title: "Fonctions / méthodes")[ - Pas plus de 20 lignes, 10 lignes idéalement - Doit faire une seule chose - Séparer les Commandes et les Requêtes : - Requête : calculer une valeur - Commande : Faire une action - Utiliser les méthodes/fonctions et leur nom pour décrire des blocs logiques - Pas plus de 4 arguments pour méthode/fonction ] #new-section-slide("Architecture") #slide(title: "Architecture en couche")[ #side-by-side[ #image("images/clean-architecture.png", width: 94%) ][ - Couche métier - Entité - Objet-valeur - Associations - Service - Couche application - Couche interface - Couche infrastructure ] ]
https://github.com/maleksware/hash-segtree
https://raw.githubusercontent.com/maleksware/hash-segtree/main/paper-src/paper.typ
typst
#import "template.typ": * #show: ams-article.with( title: "Dynamic substring comparison problem: segment tree approach", authors: ( ( name: "<NAME>", department: [CodeCadets], organization: [Canberra Grammar School], email: "<EMAIL>", url: "https://maleksware.github.io", ), ), abstract: "The problem of comparing arbitraty substrings in a given string is a well-researched theoretical Computer Science problem solvable with methods like polynomial hashing or the Knuth-Morris-Pratt algorithm. This essay focuses on dynamic variants of this problem (with point/range update queries support), considering segment trees and their modifications to keep the complexity on the standard binary search tree level (O(log n)) for both types of queries. The range update is discussed in detail.", bibliography-file: "refs.yml" ) = Introduction The problem of string comparison and pattern matching has been well-researched with various statements, requirements and backgrounds. One of the first steps in this area has been done by Knuth, Morris and Pratt @kmp, with advanced suffix structures and preprocessing algorithms to come in the next 40 years. This paper will cover a non-standard approach to the dynamic substring comparison problem which uses segment trees to quickly process update queries. = Background The only practical problem known to the author has been seen in the 2022 Summer Informatics School camp, with a slight modification of numbers used instead of latin characters. The method provided in this paper is well-extendable and generalisable to cover this case. To the author's knowledge, this is the first official paper that is covering the particular dynamic variants of the substring comparison problem. = Definitions === Alphabet: all lowercase latin alphabet characters === Query: a request for the running code to output some data. The data can be output right after the query is processed or after the program terminates === Indexing: the way the elements of the string are numerated. This paper uses 1-indexing for problem descriptions (first element in the string has number 1) and 0-indexing for implementation === $log(n)$ denotes $log_2(n)$ if not stated otherwise #pagebreak(); = Problem statement The problem discussed in this particular publication will be split into 3 parts, arranged by relative difficulty and complexity of approaches: == Static substring comparison problem Given a string $S$ of length $n$ and $k$ queries $(l_1, r_1, l_2, r_2)$ ($1 <= l_1, r_1, l_2, r_2 <= n$). For each query, determine whether or not the corresponding substrings of $S$ are equal to each other. More formally, for each integer $i | 0 <= i < (r_1 - l_1)$ the following is true: $S_(l_1 + i) = S_(l_2 + i)$. Note that the substrings can be represented by intervals $[l_1, r_1]$ and $[l_2, r_2]$. == Dynamic point update substring comparison problem The "check for equality" queries have the same format as above; the new query is denoted by $(p, x)$ ($1 <= p <= n$), meaning that $S_p$ has to be set to $x$, where $x$ is an arbitrary alphabet character. == Dynamic range update substring comparison problem The "update" query has the format $(l, r, x)$, meaning that all elements $S_i$ where $l <= i <= r$ have to be set to $x$. \ It is easy to see that the correct solutions for each of the subproblems are able to solve all previous ones (not necessarily with the same time complexity). = Polynomial hashing Let's consider the first subproblem. The precomputation is allowed, so it is possible to implement polynomial hashing algorithm. This paper won't go into much detail about specific use-cases and implementation of polynomial hash functions, although the idea will be shown. Turns out it is possible to represent strings as numbers of base equal to the size of the alphabet (normally a prime number bigger than 26, e.g., 29, 31 or 37). == Definition: $"hash"(S, p) = sum_(i = 0)^p S_i dot b^(p - i - 1)$, where $S_i$ is converted to an integer by taking the position in the alphabet, and $b$ is the chosen base ($b > 26$) \ $"hash"(S, p)$ computes the polynomial hash of the first $p$ characters of $S$ (prefix of $S$). It is proven that no same hash values can be obtained from other values of $S$ and $p$. The reason why we define the prefix hash function here in this specific form will be clear later as we generalise prefixes to substrings. == Claim: the strings are equal if and only if their hash values are equal \ The practical problem is that for long prefixes the hash values become very large and hard to compare, and at a certain point the numbers become longer than the substrings being analysed. This affects time complexity. Luckily, there has been found a solution to this - using the $"hash"(S, p) "mod" q$, where $"mod"$ denotes the remainder operation. This creates a risk of a hash-collision (two different substrings have the same hash because of the birthday paradox) but makes hashes practical. From this point, the $"hash"(S, p)$ notation includes the remainder operation by a certain big prime number $q$. \ In order to find the hash of a certain substring $[l, r)$, we need two values: $h_l = "hash"(S, l)$ and $h_r = "hash"(S, r)$. Then all is needed is multiplying $h_l$ by $b^(r - l)$ and subtracting that from $h_r$ (similarly to prefix sums). All the operations should be done $"mod" q$. The proof why this is true is left as an exercise for the reader. Now it's easy to solve the first subproblem: precompute all hashes on prefixes (this can be done in $O(n)$ time, as $"hash"(S, p) = (b dot "hash"(S, p - 1) + S_p) "mod" q$)) and then answer each query by comparing the hash values and string lengths in $O(1)$ per query (if all powers of $b$ are precomputed in $O(n)$. With the alphabet as small as 26 characters and the length of the string not exceeding $10^5$, it's very hard to create a test which will have some substrings with the same length and hashes but different substring values. Even if such test is created, creating another hash function with a different prime base and modulo value will fix the problem of so-called AHT (anti-hash tests). The hashes and the creation of AHT has been covered by Pachocki and Radoszewski @aht. = Segment tree for point updates Prefix polynomial hashing has a flaw: the necessity to recompute all subsequent elements after a certain element is updated. This can be fixed by building a segment tree on the string and updating the hash in the preceeding nodes after a point update. A segment tree is a binary tree with nodes, each of which represents a subsegment of the array. The root of the tree has the hash value of the whole array; its two children have the values from the left and right halves. In the segment tree construction process, the current subsegment is split up in 2 halves and each half is processed recursively until the current subsegment has only one element, which becomes a leaf of the tree. The parent of two vertices has to get its own value in the construction process, making it necessary to define a $"merge"(l, r)$ function which joins the value of two child vertices. In case of a sum segment tree, the merge function just adds the values of the vertices. Hash values have to be merged in a different way. #figure( image("images/segtree.png", width: 80%), caption: [ An example segment tree structure for a string ], kind: image ); Please note that all examples below are based on Figure 1 if not stated otherwise. \ Although this paper doesn't cover the principles of the segment tree (which has been done by <NAME> in his book @compcodehandbook), we will cover the basics and the specific details of the implementation. Each node has to store the hash value on the corresponding subsegment. Node 3 (Figure 1) stores the hash of "ab". From an earlier claim, the hashes of the same strings are equal, meaning that node 4 and node 6 have the same hash value as the substrings they are covering are equal. For the sake of concise and easy implementation, each node is mapped with a corresponding semi-interval $[l; r)$ (thus challenging the name of the structure as it had to be called a semi-interval tree). The root 0 covers $[0; 8)$, its children 1 and 2 cover $[0; 4)$ and $[4; 8)$. Now it is easy to see why such a method of division has been chosen: the implementation avoids adding and subtracting 1 from the interval coverage as the end of the first interval is the start of the second. Note that 0-indexing is used. \ Now to the actual querying part: how to get the hash of a specific subsegment? This can be done by merging the hash values of all subsegments that are part of the query. Suppose it is necessary to compute the hash of "bac" ($[1; 4)$). Nodes 8 and 4 are parts of the answer; it is easy to see that the same subsegment can't be obtained by merging less than those 2 nodes. The hash value in node 8 is "b" $dot b^0$, and in node 4 it is "a" $dot b^1 + $ "c" $dot b^0$. The whole subsegment hash is, by definition of $"hash"(S, p)$, "b" $dot b^2 + $ "a" $dot b^1 + $ "c" $dot b^0$. It turns out the merged hash can be obtained by adding the second hash to the first hash multiplied by $b^l$, where $l$ is the length of the second subsegment. This "shift" produces the actual result. \ This observation makes it possible to handle the point update problem: when an element is updated, its hash value is updated on a bottom-level node. Then all the ancestor nodes are updated recursively according to the change in their children nodes. There are $log(n)$ ancestor nodes to update (because any binary search tree has $log(n)$ levels) making the complexity $O(log(n))$ per update query. The hash calculation query is $O(log(n))$ as well because there are only $O(log(n))$ segments which form the segment from the query. Any comparison query requires 2 hash computations and one $O(1)$ integer comparison, resulting in O(log(n)) per comparison query. The precalculation takes $O(n)$ time as there's only $O(2 dot n) = O(n)$ nodes to compute the values for, and any $"merge"(l, r)$ takes $O(1)$ time. = Segment tree modification for range updates The current variant of our segment tree can only handle point updates. The range updates can only be done by updating the elements one by one, which takes $O(n log(n))$ per range update query. There has been found a modification for the segment trees which makes it possible to handle range updates by storing some additional information of what has to be stored in the nodes and using it when necessary @lazy. When the range is updated, all segments that are fully within this range are assigned a value for that update query. This value is later used if the segment is a part of the hash query. A $"push(l, r)"$ function is defined to update the children's assigned values if they have to be updated separately. This allows to keep the complexity at $O(log(n))$ per update and hash queries, because some unused assigned values get discarded in the process if not used. See implementations #footnote[The implementations are on https://github.com/maleksware/hash-segtree.] for more details. The main problem of this modification comes from the necessity to recompute the hash of a node that has been updated such that all leaves in its subtree contain the same letter. In other words, we have to compute the hash of a string of the same letters, knowing only the letter and the length of the string. My solution can compute this in $O(log(k))$ time, where $k$ is the length of the string. This complexity is later optimised to just $O(1)$ using precomputation. == Subproblem: computing the hash of uniform strings The hash of the string with length $n$ will have a form of $ ("char" dot b^(n - 1) + "char" dot b^(n - 2) + dot dot dot + "char" dot b^1 + "char" dot b^0) mod q $ (where char is an arbitrary character that the string consists of). It is easy to see that the formula in the brackets is a rearranged geometric progression with common difference $b$ and first term $"char"$. The sum of the terms is $ (("char" dot (b^n - 1)) / (b - 1)) mod q $ The division is what makes the computation untrivial because it is not possible to perform division without specific methods while working in the ring modulo $q$. Fortunately, as $"gcd"(b, q) = 1$ as $q$ is prime, it is possible to use Fermat's Little Theorem @flt. In order to divide by $b - 1$, one needs to multiply by the reciprocal element in the ring modulo $q$. By the Fermat's Little Theorem, $ (b - 1)^(-1) mod q = (b - 1)^(q - 2) mod q $ This makes it possible to perform the calculation. The complexity of 2 exponent operations performed (one in the reciprocal and one in the GP sum formula) add up to $O(log(k))$ in the update query complexity. But this is easy to optimise by precomputing all possible base powers up to $n$ where $n$ is the length of the string and accessing them where needed. This takes $O(n)$ time. The reciprocal element can't be found by just accessing the precomputed powers (because $q - 2$ is too large to be found in the precomputed vector), but it can be computed once in $O(log(n))$. The final precomputation, along with the segment tree construction process, remains at $O(n)$. = Summary on known solution complexities #table( columns: (80pt, 90pt, 90pt, auto, auto), inset: 10pt, align: horizon + center, [*Method*], [*Precalculation*], [*Hash \ computation*], [*Point \ update*], [*Range \ update*], [Naïve \ approach], $O(1)$, $O(n)$, $O(1)$, $O(n)$, [Polynomial \ hashing], $O(n)$, $O(1)$, $O(n)$, $O(n)$, [Point update \ segment tree], $O(n)$, $O(log(n))$, $O(log(n))$, $O(n log(n))$, [Range update \ segment tree], $O(n)$, $O(log(n))$, $O(log(n))$, $O(log(n))$ ) = Benchmarking and measuring practical performance == Test data generation The benchmarks have been done on 2 types of tests: - QP testset: $10^6$ queries, all input string lengths from $10^4$ to $10^6$ with a step of $10^4$. - LN testset: input string length is $10^6$, all numbers of queries from $10^4$ to $10^6$ with a step of $10^4$. Each problem has been benchmarked separately to measure different methods' performance. Each implementation was first validated using one of the tests from the testset to ensure that the output is the same and there is no bugs or accidental errors in the tests. The tests themselves only contain hash computing, without actually comparing the substrings - this way it is easier to create "fair" big tests. This doesn't have any effect on complexity as each of the methods just compares two substring hashes after computing them. == Specific implementation details All implementations use the single-hash technique. This means they're not completely collision-proof @aht, but it is not crucial for the performance tests in this paper. This has been done to keep the implementations readable and simple enough, but all of them are easily generalisable to use multiple hashes. #pagebreak() == Benchmarking results #figure( image("images/figure1.png", width: 130%), caption: [ Hash query benchmark ], ); #figure( image("images/figure2.png", width: 130%), caption: [ Hash query/point update benchmark ], ); #figure( image("images/figure3.png", width: 130%), caption: [ Hash query/range update benchmark ], ); == Evaluation === Static problem analysis The static problem is best solved by the canonical polynomial hashing method. Its QP graph is almost flat because the precomputation of hashes on prefixes is done only once, and the fixed number of queries is processed in the same amount of time. The LN graph is a straight line for all methods because it only depends on the original input size and scales proportionally to the number of queries. The QP graphs for the segment tree implementations are similar to logarithmic graphs. This can be explained by the fact that the time of the query execution is dependent on the *height of the segment tree*, and, consequently, the logarithm of the original input length. The difference between the point update and range update segment trees' graphs is a consequence of the base precomputation for different lengths of the input, but it is insignificant compared to processing queries. The LN graphs have different inclines because of the constant $"push"(l, r)$ overhead on each of the queries. The hash computation for the polynomial hash is $O(1)$, so the incline is very small compared to the difference in the input sizes (but it is still noticeable, partially because modulo ($%$) operation is computationally time-consuming). As the range update segment tree executes a $"push"(l, r)$ on each node processing, it has a constant overhead which is only dependent on the number of the nodes processed per query (which is always $O(log(n))$, where $n$ is the constant length of the string). === Point update problem analysis The hash implementation is inefficient on this problem as each update takes $O(n)$ time, where $n$ is the length of the input. Both graphs (QP and LN) are almost identical because the update queries are dependent on the length of the string, and even when the number of queries is fixed, the string can be large enough to have a lot of update queries that affect the execution time. Even for tests of size up to $10^5$ the hash implementation can't manage to run for under 7 s (7000 ms) per test, which makes it unnecessary to continue the measurements. The segment tree implementations perform as expected with the same curve shapes (as the update and hash calculation queries have identical theoretical complexity and don't differ much in practice, so they can be considered similar in terms of the effect on the graph). The constant overhead is still noticeable (because the pushes are not used to transport information as the subtrees that the values are assigned to are always leaves of the tree, but the pushes still have to be executed to keep the invariants in the vertices). === Range update problem analysis Both hashing and point update algorithms perform very poorly with an almost vertical line as the graph. Their execution had to be stopped even on small tests because the time exceeded 2 minutes on a single test. However, the range update segment tree with lazy propagation has shown a good result with only 6 seconds on maximum size tests. The shape of both graphs formed by points is explained above. === Practical measures summary Although it may look like the no-push (point update) segment tree can be completely replaced by the segment tree with pushes because they have the same theoretical time complexities, the latter performs worse in practice because of constant query overheads. Each implementation (hashing, segtree and push segtree) performs best on the corresponding subproblem. = Conclusions The segment tree hash calculation algorithms provided in this paper have been able to solve more advanced pattern-finding and substring comparison problems more effectively than the standard prefix hashing method. The range update string comparison problem has been effectively solved using the modified lazy propagation segment tree, using mathematical properties of hashing and modulo rings. This has allowed to solve the dynamic substring comparison problem by executing the hash calculation queries on the corresponding subsegments and comparing the results. Complete working implementations for all three methods can be found on GitHub #footnote[The code and accompanying generation scripts are on https://github.com/maleksware/hash-segtree.]. #pagebreak()
https://github.com/imatpot/typst-ascii-ipa
https://raw.githubusercontent.com/imatpot/typst-ascii-ipa/main/src/lib/delimiters.typ
typst
MIT License
// https://en.wikipedia.org/wiki/International_Phonetic_Alphabet#Brackets_and_transcription_delimiters #let phonetic(text) = "[" + text + "]" #let phnt = phonetic #let precise(text) = "⟦" + text + "⟧" #let prec = precise #let phonemic(text) = "/" + text + "/" #let phnm = phonemic #let morphophonemic(text) = "⫽" + text + "⫽" #let mphn = morphophonemic #let indistinguishable(text) = "(" + text + ")" #let idst = indistinguishable #let obscured(text) = "⸨" + text + "⸩" #let obsc = obscured #let orthographic(text) = "⟨" + text + "⟩" #let orth = orthographic #let transliterated(text) = "⟪" + text + "⟫" #let trlt = transliterated #let prosodic(text) = "{" + text + "}" #let prsd = prosodic
https://github.com/HarryLuoo/sp24
https://raw.githubusercontent.com/HarryLuoo/sp24/main/Physics311/reviewNotes/part1.typ
typst
#set math.equation(numbering:"(1)") = Equation of Motion: \ Lagragian, Principle of Least Action, and E-L Equation\ == Larangian: - Under the constraint of \ 1)Space and time are homogenous, 2)time is isotropic, the Larangian for a system is given as $ L = T - U(r), "where" cases(T = sum_(a=1)^N 1/2 m_a dot(q_a)^2 "sum of KE", "U: potential energy") $ == E-L equation For a given functional, $ S = integral_(t_1)^(t_2) L(q, dot(q), t) dif t $ we could optimize it using the Euler-Lagrange equation, $ d/(dif t) (diff L)/(diff dot(q)) - (diff L)/(diff q) = 0 $ where each EL equation and its solution corresponds to a degree of freedom.\ Upon applying the El equation to a generalized lagrangian, we reveal Newton's second law$ (dif )/(dif t)(diff (1/2 m v^2 - U(r)))/(diff v)=(diff (1/2 m dot(q)^2 - U(r)))/(diff r) \ => m dot(arrow(v))= -(diff U)/(diff q) equiv arrow(F) ("force") $ == coordinate transformation: - In cartesian coordinates, $L = 1/2 m (dot(x)^2+dot(y)^2+ dot(z)^2) - U$\ In cylindrical coordinates, $L = 1/2 m (dot(r)^2+r^2 dot(theta)^2+dot(z)^2) - U$\ In spherical coordinates, $L = 1/2 m (dot(r)^2+r^2 dot(theta)^2+r^2 sin^2(theta) dot(phi)^2) - U$ - Note that when taking partial differentiations, we treat each variable and its derivative as two independent variables. Don't ask why... We are doing physics here\ #line(length: 100%) = Conservation Laws: \ Energy, Momentum, COM, and Angular Momentum\ == Energy: - Energy is defined as the following, and when the Lagrangian is *homogeneity time*, the energy is conserved.\ $ E equiv sum_i dot(q_i) (diff L)/(diff dot(q_i)) -L\ "considering" L= T-U, "we have" #rect()[E = T + U]\ $ - Total energy is also given as$ E = 1/2 mu V^2 + E_i \ "where" E_i "is internal energy, and" mu "being the total mass" $ == General momentum: conservation of general momentum is from the following conservation $ (diff L)/(diff q_j) =0 => p_j equiv (diff L)/(diff dot(q_j)) , $ where $q_j$is a cyclic coordinate, i.e. $L$ is independent of $q_j$.\ == Total momentum total momentum is defined as the following, and considering the *homogeneity of space*, the momentum is conserved in a closed system. \ If the total momentum of a mechanical system in a given frame of reference is 0, then the said system is at rest relative to that frame. For simplicity's sake, we want to chose our frame of reference in which the total momentum is zero.\ $ P equiv sum_a (diff L)/(diff dot(q_a)) = #rect()[$sum_a m_a v_a$] \ "force is also given by" F_j = (diff L)/(diff q_j) \ "sum of all forces in a closed system is 0" $ == Center of Mass - Center of mass is defined so that, the velocity of the system as a whole, $V = P slash (sum m_a )$ is the time derivative of the center of mass. $R = sum_a m_a r_a slash (sum m_a)$.\ == Conservation of angular momentum Angular momentum caractorizes the rotation of the system, and considering the *isotropy of space*, the angular momentum is conserved in a closed system.\ $ #rect()[$arrow(L) equiv sum_(a) r_a times p_a$]"is conserved in a closed system" $ - Angular momentum can be found by differentiating the lagrangian with respect to angular velocity, along the rotation axis z:$ arrow(L_z)= (diff L)/(diff dot(phi_a)) $ #line(length: 100%) = Integration of the equations of motion: Connetcting Energy with motion == Motion in 1 dimension - For a system with DOF=1, and with $(diff L)/(diff t) = 0 $ ( largrangian independent of time, i.e. energy conserved) , we can write the largrangian and total energy as $ L = 1/2 m dot(x)^2 - U(x), $ $ E = 1/2 m dot(x)^2 + U(x) $ <3.eq.enrgy> @3.eq.enrgy is a differential equation of position and time. Solving this ODE for time gives: $ t = sqrt(m/2) integral (dif x) / (E - U(x)) + C $ when given $U(x)$, and by plugging it into @3.eq.enrgy, we can solve for $x(t)$ by substitution. Tricks on sub: when $U(x)$ is of order 1, use u-sub; when it's of order 2, use trig-sub.\ == Turning points #image("potential.png", width: 40%) For a given potential function $U(x)$, the turning points are the points where the potential energy is equal to the total energy, i.e. $U(x) = E$. At turning points, the system is either just about to move, or just about to stop.\ Only motion where potential is less or equal to total energy is allowed.\ Bounded motion: $[x_1,x_2]$; unbounded motion: $x>x_3$ == Unbounded Motion: When there is a potential well, the system could go into periodic motion with potential energy moving back and forth in the well, and position between $x_1,x_2$. We find period by doubling @3.eq.enrgy: $ T(E) = sqrt(2m) integral_(x_1(E))^(x_2(E))(dif x)/(sqrt(E - U(x))) $<3.eq.period> where we represent $x_1(E),x_2(E)$ in terms of $E$. \ When given $U(x)$, we can solve for $x_1(E),x_2(E)$, and then pluging in to @3.eq.period, we can solve for period by integration via subsitution. \ *Simple Pendulum* in polar coord's has the following:$ T = 1/2 m l^2 dot(theta)^2 \ U = m g l (1-cos(theta)) \ $ It's period is given by @3.eq.period. Solving it gives us $ T(E) = 4 sqrt(l/g) integral_0^(pi/2) (dif u)/(sqrt(1-k ^2 sin^2(u))) \ "where" k = sin(theta_0/2), sin u = 1/k sin(theta_0/2) $ <3.eq.pend> @3.eq.pend can be simplified by small angle approx into $ T(E) = 2 pi sqrt(l/g) (1+(theta_0^2/16)) $ == Effective DOF=1 system When the largrangian is of the form $L = f(dot(x))- g(x)$, we can see it as a system with effective potential $U_"eff"(x) = g(x) $, and effective kenetic energy $T_"eff"(x) = f(dot(x))$. The effective energy is therefore $E = T_"eff" + U_"eff"$.\ #line(length: 100%) = Two body problem == Problem setup - The two body problem considers two interacting masses with an interacting potential $U(r_1,r_2)=U(|arrow(r_1)-arrow(r_2)|)$. The lagrangian is given by $ L = 1/2 m_1 dot(arrow(r_1))^2 +1/2m_2 dot(arrow(r_2))^2 - U(|arrow(r_1)-arrow(r_2))|) $ - == COM and reletive coordinates, DOF= 6 -> DOF = 2 - Consider the following handy subsitution, $ "Reduced mass" mu& =(m_1 m_2)slash(m_1+m_2) =m _(1) m_2 slash M ;\ "Center of mass" R& = (m_1 r_1 +m_2 r_2) slash (M);\ "relative positon" arrow(r)& = arrow(r_1)-arrow(r_2) $ <4.eq.sub> \ - Putting the two body system into relative coordinates, and represent masses with reduced mass and COM, we have the following lagrangian: $ L =1/2 M dot(arrow(R))^2 + 1/2 mu dot(arrow(r))^2- U(arrow(r)) $ where the first term involves only the COM motion, and the second term involves only the relative motion.\ - By choosing our frame with the COM at rest and the total momentum zero, our problem is simplified to an * effective one body problem* with DOF = 2, given by $ L = 1/2 mu dot(arrow(r))^2 - U(arrow(r)) $ == Conservation of Angular Momentum - Angular momentum is defiined as $arrow(L) = arrow(r) times mu dot(arrow(r)) $, and is conserved here.\ - Knowing $arrow(r) dot arrow(L)=0$, the motion is in the plane perpendicular to $arrow(L)$. We can use polar coordinates to describe the motion, $ L = 1/2 mu (dot(r)^2 + r^2 dot(theta)^2) - U(r) $<4.eq.polar> Using EL equation on @4.eq.polar, we get $ (dif )/(dif t) (diff L)/(diff dot(phi)) = (diff L)/(diff phi) \ => arrow(L_z) equiv mu r^2 dot(theta) = "constant" \ ("conservation of angular momentum on z-axis") $ == 2 body problem in gravitational field $ L = 1/2 m_1 dot(r_1)^2 + 1/2 m_2 dot(r_2)^2 - [m_1 g z_1 + m_2 g z_2 + U(r)] \ = [1/2 M dot(R)^2 - M g Z +] + [1/2 mu dot(r)^2 - U(r)] $ where $Z$ is the vertical coordinate of the CM position, $Z = (m_1z_1+m_2z_2)/M$ == Kepler's second Law We calculate the differential of area swept by particle in polar coordinates, $ dif A = 1/2 r^2 dif phi \ => (dif A)/(dif t) = 1/(2 mu) arrow(L_z) \ arrow(L_z) = 2 mu dot(A) ("constant") $ This is the Kepler's second law, which states that the area swept by the radius in a given time is constant. == EOM for two body system - The total energy: $ E = T + U &= 1/2 mu dot(r)^2 + 1/2 mu r^2 dot(phi)^2+ U(r) \ &= 1/2 mu dot(r)^2 + U(r)+ (L_z ^2)/(2 mu r ^2) "(Notice" L_z = mu r ^2 dot(phi) $ <4.eq.t> solving this ODE by integration gives $ t(r))=integral (dif r)/(sqrt(2/mu)[E - U(r)- (L_z^2)/(2 mu r ^2)]) + C $ - Also from $L_z = mu r ^2 dot(phi)$, by integrating with respect to time, we get $ phi(t) = (L_z)/(mu)integral (dif t)/(r ^2(t))+C' $<4.eq.phi> @4.eq.phi and @4.eq.t describe the relative motion of the two body system in terms of constants ${E,L_z,C,C'}$ == Shape of orbit - @4.eq.t skipped a step, $ (dif r)/(dif t) = sqrt((2/mu)[E - U(r)- (L_z^2)/(2 mu r ^2)]) $ this equation, combined with our beloved $ L_z = mu r ^2 dot(phi) => dif phi = (L_z)/(mu r ^2) dif t $ we get the equation of orbit: $ dif phi = (L_z)/sqrt(2mu) (dif r)/(r^2 sqrt(E - U(r) - L_z^2/(2mu r^2))) \ => phi = (L_z)/(sqrt(2mu)) integral (dif r)/(r^2 sqrt(E - U(r) - L_z^2/(2mu r^2))) + C $ == Effective potential and shape of orbit (Only for Attractive Potential) $ U_"eff"=U(r)+ L_z^2/(2mu r^2); E = 1/2 mu dot(r)^2 + U_"eff"(r) $ - When $r->infinity$, $U_"eff"->U(r)$, and when $r->0$, $U_"eff"->"centrifutal potential" L_z^2/(2mu r^2)$.\ - by graphing the effective potential, and given constraint of total energy E, we can analyze the shape of the orbit: #image("orbit.png", width: 90%) \ - when $E>0$, the orbit is unbounded, open orbit, hyperbola.\ - when $E < 0$, the orbit is bounded into a potential well, although not neccessarily closed. - when $E=E_min$, the orbit is circular, $F = -mu (v^2)/(r)$ = The Kepler Problem: a special case of the two body problem == conditions $ U(r) = -alpha/r ; U_"eff"= -alpha/r + L_z^2/(2mu r^2) $ == Conic section orbits We can proof that the orbit is a conic section given by $ #rect()[$ r(phi) = p/(1+e cos(phi)) $] \ "where" cases(p = L_z^2/(mu alpha) , e = sqrt(1+(2E L_z^2)/(mu alpha^2))) $ == Classifications of orbits based on energy of system E - When $E>0, e>1$, the orbit is unbounded, open orbit, hyperbola. $ (x-c)^2/a^2-y^2/b^2 = 1\ cases( a= p/(e^2 - 1)","b = p/sqrt(e^2 - 1)","c = a e, r_"min"=p/(1+e)) $ - when $E=0, e=1$, the orbit is parabola.$ y^2 = p^2 - 2 x p, \ r_"min" = p/2 $ - when $E < 0, e<1$, the orbit is closed, ellipse.$ (x+c)^2/a^2+y^2/b^2 = 1,\ cases( a= p/(1-e^2)","b = p/sqrt(1-e^2)","c = a e, r_"min"=p/(1+e)" ; " r_"max" = p/(1-e)) $ - When $E = E_"min", display(f = (mu alpha^2)/(2 L_z^2)), e=0$, orbit is circular. $r(phi) = p = "constant"$ #line(length: 100%) = More Kepler: Period, Kepler's third law == Orbit of each body recall @4.eq.sub, we can exprees the orbit of each body as such after some algebra: $ arrow(r_1)=(m_2)/(m_1+m_2)arrow(r)" ; "arrow(r_2)=-(m_1)/(m_1+m_2)arrow(r) $ - when $m_1 = m_2 => arrow(r_1)=arrow(r)/2, arrow(r_2) = -arrow(r)/2$, COM inside $r_1 sect r_2$ - when $m_1 >> m_2 => arrow(r_1) = arrow(r), arrow(r_2) = 0$, $m_1$ is at rest, $m_2$ orbits $m_1$ == Period of orbit - $L_z = 2 mu dot(A)$, areal vel. is constant - Integrating $dot(A)$ over a period,$ A = integral_(0)^(T)dot(A) dif t = (L_z T)/(2mu) $ Since area swept over a period is the area of the ellipse, we have $ pi a b = (L_z T)/(2mu) ",letting:" b=sqrt(p a), p=(L_z^2)/(mu alpha) \ => T = (2 pi a^(3 slash 2))sqrt(mu/alpha\ ) $ == Conservation of Laplace-Runge-Lenz vector $arrow(A)= arrow(v) times arrow(L)- (alpha arrow(r))slash(r)$ is conserved, and is perpendicular to the orbit plane. We can use it to verify : conic sections, eccentricity, and period.\ - conserved quantity: $arrow(A) dot arrow(L)=0, A/alpha = sqrt(1+ (2 E L_z^2)/(mu alpha ^2))$ #line(length: 100%) = Orbital Transfer == Instantaneous Change in velocity $ (E,L_z) -> (E',L'_z) \ => (e,p)->(e',p') $ if thrust occur when satellite is at angle $phi_0$, orbit orientation can change: $ r(phi_0)=p/(1+e cos phi_0) = p'/(1+e' cos( phi_0-delta)) $ <7.eq.r> == Tangential thrust at perigee #image("tangentialThrust.png", width: 30%) at $phi=0$, let $v=v_"init", v' = v_"right after", lambda=v'slash v $ $ L_z = mu r_0 v =>L'_z = mu r_0 v' =lambda L_z\ p' = lambda^2 p $ From @7.eq.r, $ p/(1+e)=lambda^2 p/(1-e')=>e' = lambda^2(1+e)-1 $ if $lambda>1$, $e'>e$, the satellite is in a higher, more eliptical orbit. Unbound if $lambda$ big enough\ if $lambda<1$, $e'<e$, the satellite is in a lower orbit.\ == changing between circular orbits - changing from $R$ to $R'$, two thrusts($lambda_1,lambda_2$) are needed. There is also an intermediate orbit $ r(phi )= p'slash (1+e' cos phi), \ "where " p'=lambda_1^2p, e'= lambda^2_1 - 1 $ changed from indermetiade to final, $ r(phi = pi) = R' = lambda_2^2 R slash (2-lambda_1^2)\ => lambda_1 = sqrt((2R')/(R+R')) $ final orbit: $ r(phi)= R'; e'' = 0, p'' = R'\ => p'' = lambda_2^2 p' = p' slash (1 - e')\ => lambda_2 = sqrt((R+R')/(2R')) $ // == Verify: // using Newton 2nd, $ // alpha/R^2 = mu v_R^2 / R \ // => v_R = sqrt(alpha/mu R)\ // =>V_R'/V_R = sqrt(R/R') // $<7.eq.v> // verify using conservation of angular momentum, $ // R v(phi = 0)= R'v(phi = pi), \ V_R' = lambda v(phi=pi)=lambda_2 v(phi=pi)/v(phi=0)lambda_1 v_R\ // => v_R'/v_R = sqrt(R/R') // $ agrees with @7.eq.v !!
https://github.com/CLCK0622/Calculus-notes
https://raw.githubusercontent.com/CLCK0622/Calculus-notes/main/series.typ
typst
MIT License
#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: "Series Notes", authors: ( "<NAME>", ), ) = Special Series == Geometric Series - definition: A geometric series is any series that can be written in the form $sum_(n=0)^infinity a r^n$. - value: $a (1-r^n)/(1-r)$ and $a/(1-r)$ when $n arrow.r infinity$ - convergence: converges when $abs(r) < 1$ == Telescoping Series - definition: In mathematics, a telescoping series is a series whose general term $t_n$ is of the form $t_n=a_(n+1)+a_n$. - value: consider the partial sum and calculate by cancelling some parts - convergence: decide with its limit after cancelling all parts that can be cancelled == Harmonic Series - definition: A Harmonic Series is any series that can be written in the form $sum_(n=1)^infinity 1/n$. - value: use Integral Test to decide - convergence: use Integral Test to decide = Integral Test Integral Test is to decide a series' convergence with improper integral. The infinite series $sum_(n=N)^infinity f(n)$ converges to a real number if and only if $integral_(N)^infinity f(x) d x$ is finite. In particular, if the integral diverges, then the series diverges as well. If the improper integral is finite, then the proof also gives the lower and upper bounds $ integral_(N)^infinity f(x) d x <= sum_(n=N)^infinity f(n) <= f(N) + integral_(N)^infinity f(n) d x $ for the infinite series.
https://github.com/edgarogh/f4f1eb
https://raw.githubusercontent.com/edgarogh/f4f1eb/main/demo_medium.typ
typst
#import "template.typ": * #show: project.with( title: [Anakin \ Skywalker], from_details: [ Appt. x, \ Mos Espa, \ Tatooine \ <EMAIL> \ +999 xxxx xxx ], to_details: [ Sheev Palpatine \ 500 Republica, \ Ambassadorial Sector, Senate District, \ Galactic City, \ Coruscant ], ) Dear Emperor, I'm applying for an internship in #lorem(100) #lorem(80) #lorem(95) Sincerely, Mr. Skywalker
https://github.com/L364CY-FM/typst-thesis
https://raw.githubusercontent.com/L364CY-FM/typst-thesis/main/projektarbeit/templates/disclaimer.typ
typst
MIT License
#let disclaimer( title: "", degree: "", author: "", location: "", submissionDate: none, ) = { set document(title: title, author: author) set page( margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm), numbering: none, number-align: center, ) let body-font = "New Computer Modern" let sans-font = "New Computer Modern Sans" set text( font: body-font, size: 12pt, lang: "de" ) set par(leading: 1em) // --- Disclaimer --- v(70%) text( "Hiermit erkläre ich, dass ich die vorliegende Arbeit selbstständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe. Alle sinngemäß und wörtlich übernommenen Textstellen aus fremden Quellen wurden kenntlich gemacht.") v(15mm) grid( columns: 2, gutter: 1fr, location + ", " + submissionDate, author ) pagebreak() }
https://github.com/jamesrswift/pixel-pipeline
https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/layers/drawing/primitives.typ
typst
The Unlicense
#import "/src/primitives/lib.typ" as primitives
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/README.md
markdown
Apache License 2.0
# Syntax Highlighting for Typst This folder contains the syntax highlighting for Typst. The syntax highlighting is written in the TextMate format. The syntax highlighting is written in TypeScript, and ensures correct grammar by [./textmate.ts](./textmate.mts). ### Building The following script running the TypeSCript program will generate the TextMate grammar file: ```shell yarn compile ``` ### Testing ```shell yarn test ``` ### Register languages for raw highlighting Goto [fenced.meta.mts](./fenced.meta.mts) and add a line like this: ```json { "candidates": ["erlang"] } ``` Three possible kinds: - `{ candidates: ["someLanguage", ...rests] }` - using textmate parser registered as `source.someLanguage`. - The `rests` of the candidates can also be used as language tag of fenced code blocks. - `{ as: "text.xxx", candidates }` - using textmate parser registered as `text.xxx`. - `{ as: ["text.xxx", ...restScopes], candidates }` - using textmate parser `text.xxx` first, and `restScopes` parsers in order. ## Contributing See [CONTRIBUTING.md](https://github.com/Myriad-Dreamin/tinymist/blob/main/CONTRIBUTING.md).
https://github.com/andreasKroepelin/lovelace
https://raw.githubusercontent.com/andreasKroepelin/lovelace/main/examples/custom.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-list[ + *in parallel for each* $i = 1, ..., n$ *do* + fetch chunk of data $i$ + *with probability* $exp(-epsilon_i slash k T)$ *do* + perform update + *end* + *end* ]
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/10-hint/hint.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/heading.typ": chapter #import "/lib/glossary.typ": tr #show: web-page-template #chapter[ // Rasterisation and Hinting #tr[rasterization]与#tr[hinting] ]
https://github.com/liuxu89/touying-online
https://raw.githubusercontent.com/liuxu89/touying-online/main/main.typ
typst
MIT License
#import "@preview/touying:0.4.2": * #import "@preview/cetz:0.2.2" #import "@preview/fletcher:0.4.4" as fletcher: node, edge #import "@preview/ctheorems:1.1.2": * // cetz and fletcher bindings for touying #let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true)) #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) // Register university theme // You can replace it with other themes and it can still work normally #let s = themes.university.register(aspect-ratio: "16-9") // Set the numbering of section and subsection #let s = (s.methods.numbering)(self: s, section: "1.", "1.1") // Set the speaker notes configuration // #let s = (s.methods.show-notes-on-second-screen)(self: s, right) // Global information configuration #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) // Pdfpc configuration // typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc #let s = (s.methods.append-preamble)(self: s, pdfpc.config( duration-minutes: 30, start-time: datetime(hour: 14, minute: 10, second: 0), end-time: datetime(hour: 14, minute: 40, second: 0), last-minutes: 5, note-font-size: 12, disable-markdown: false, default-transition: ( type: "push", duration-seconds: 2, angle: ltr, alignment: "vertical", direction: "inward", ), )) // Theroems configuration by ctheorems #show: thmrules.with(qed-symbol: $square$) #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Example").with(numbering: none) #let proof = thmproof("proof", "Proof") // Extract methods #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert // Extract slide functions #let (slide, empty-slide) = utils.slides(s) #show: slides = 中文测试 == Simple Animation 测试 中文测试 We can use `#pause` to #pause display something later. #pause Just like this. #meanwhile Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously. #speaker-note[ + This is a speaker note. + You won't see it unless you use `#let s = (s.math.show-notes-on-second-screen)(self: s, right)` ] == Complex Animation - Mark-Style At subslide #utils.touying-wrapper((self: none) => str(self.subslide)), we can use #uncover("2-")[`#uncover` function] for reserving space, use #only("2-")[`#only` function] for not reserving space, #alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives. == Complex Animation - Callback-Style #slide(repeat: 3, self => [ #let (uncover, only, alternatives) = utils.methods(self) At subslide #self.subslide, we can use #uncover("2-")[`#uncover` function] for reserving space, use #only("2-")[`#only` function] for not reserving space, #alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives. ]) == Math Equation Animation Touying equation with `pause`: #touying-equation(` f(x) &= pause x^2 + 2x + 1 \ &= pause (x + 1)^2 \ `) #meanwhile Here, #pause we have the expression of $f(x)$. #pause By factorizing, we can obtain this result. == CeTZ Animation CeTZ Animation in Touying: #cetz-canvas({ import cetz.draw: * rect((0,0), (5,5)) (pause,) rect((0,0), (1,1)) rect((1,1), (2,2)) rect((2,2), (3,3)) (pause,) line((0,0), (2.5, 2.5), name: "line") }) == Fletcher Animation Fletcher Animation in Touying: #fletcher-diagram( node-stroke: .1em, 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((0,0), (0,0), `read()`, "--|>", bend: 130deg), pause, edge(`read()`, "-|>"), node((1,0), `eof`, radius: 2em), pause, edge(`close()`, "-|>"), node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)), edge((0,0), (2,0), `close()`, "-|>", bend: -40deg), ) = Theroems == Prime numbers #definition[ A natural number is called a #highlight[_prime number_] if it is greater than 1 and cannot be written as the product of two smaller natural numbers. ] #example[ The numbers $2$, $3$, and $17$ are prime. @cor_largest_prime shows that this list is not exhaustive! ] #theorem("Euclid")[ There are infinitely many primes. ] #proof[ Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list, it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since $p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a contradiction. ] #corollary[ There is no largest prime number. ] <cor_largest_prime> #corollary[ There are infinitely many composite numbers. ] #theorem[ There are arbitrarily long stretches of composite numbers. ] #proof[ For any $n > 2$, consider $ n! + 2, quad n! + 3, quad ..., quad n! + n #qedhere $ ] = Others == Side-by-side #slide(composer: (1fr, 1fr))[ First column. ][ Second column. ] == Multiple Pages #lorem(200) // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide, empty-slide) = utils.slides(s) == Appendix #slide[ Please pay attention to the current slide number. ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/style_07.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test using rules for symbols #show sym.tack: it => $#h(1em) it #h(1em)$ $ a tack b $
https://github.com/SkiFire13/typst-prooftree
https://raw.githubusercontent.com/SkiFire13/typst-prooftree/master/examples/singleton.typ
typst
MIT License
#import "/prooftree.typ": * #show: content => style(styles => { let content = box(inset: 2em, content) let sizes = measure(content, styles) page(width: sizes.width, height: sizes.height, margin: 0pt, content) }) #set text(font: "New Computer Modern", size: 12pt) #let N1 = $"N"_1$ #let Id = $"Id"$ #let id = "id" #let type = $italic("type")$ #let cont = $italic("cont")$ #let El = "El" #let w1w2_cont = ( axiom($[#h(3pt)] cont$), rule(label: "F-S", $N1 type [#h(3pt)]$), rule(label: "F-C", $w_1 in N1 cont$), rule(label: "F-S", $N1 type [w_1 in N1]$), rule(label: "F-C", $w_1 in N1, w_2 in N1 cont$), ) #let w1w2z_cont = ( ..w1w2_cont, rule(label: "F-S", $N1 type [w_1 in N1, w_2 in N1]$), rule(label: "F-C", $w_1 in N1, w_2 in N1, z in N1 cont$), ) #prooftree( ..w1w2_cont, rule(label: "var", $w_2 in N1 [w_1 in N1, w_2 in N1]$), ..w1w2z_cont, rule(label: "F-S", $N1 type [w_1 in N1, w_2 in N1, z in N1]$), ..w1w2z_cont, rule(label: "var", $w_1 in N1 [w_1 in N1, w_2 in N1, z in N1]$), ..w1w2z_cont, rule(label: "var", $z in N1 [w_1 in N1, w_2 in N1, z in N1]$), rule(n: 3, label: "F-Id", $Id(N1, w_1, z) type [w_1 in N1, w_2 in N1, z in N1]$), ..w1w2_cont, rule(label: "var", $w_1 in N1 [w_1 in N1, w_2 in N1]$), ..w1w2z_cont, rule(label: "F-S", $N1 type [w_1 in N1, w_2 in N1, z in N1]$), ..w1w2z_cont, rule(label: "var", $z in N1 [w_1 in N1, w_2 in N1, z in N1]$), ..w1w2z_cont, rule(label: "I-S", $* in N1 [w_1 in N1, w_2 in N1, z in N1]$), rule(n: 3, label: "F-Id", $Id(N1, z, *) type [w_1 in N1, w_2 in N1, z in N1]$), ..w1w2_cont, rule(label: "I-S", $* in N1 [w_1 in N1, w_2 in N1]$), rule(label: "I-Id", $id(*) in Id(N1, *, *) [w_1 in N1, w_2 in N1]$), rule(n: 3, label: "E-S", $El_N1(w_1, id(*)) in Id(N1, w_1, *) [w_1 in N1, w_2 in N1]$), rule(n: 3, label: "E-S", $El_N1(w_2, El_N1(w_1, id(*))) in Id(N1, w_1, w_2) [w_1 in N1, w_2 in N1]$), )
https://github.com/eduardz1/UniTO-typst-template
https://raw.githubusercontent.com/eduardz1/UniTO-typst-template/main/template/chapters/example.typ
typst
MIT License
= Example This is an example chapter @typst, #lorem(100) ```c // This is a block of code #include <stdio.h> int main() { printf("Hello, World!"); return 0; } ``` - And this - Is a list - With a sublist Now an equation: $ sum_(k=1)^n k = (n(n+1)) / 2 $ == With a Section This is a section, #lorem(100) === And a Subsection This is a subsection @cormen, #lorem(100) #pagebreak(weak: true, to: "odd")
https://github.com/voidiz/typst-liuthesis
https://raw.githubusercontent.com/voidiz/typst-liuthesis/master/template.typ
typst
MIT License
#let liu( // The paper's title. title: [Paper Title], // The paper's subtitle (optional). subtitle: none, // The paper's swedish title (optional). titleSwedish: none, // The paper's swedish subtitle (optional). subtitleSwedish: none, // An array of authors names. authors: (), // The paper's abstract. Can be omitted if you don't have one. abstract: none, // The path to a bibliography file if you want to cite some external // works. bibliography-file: none, // The supervisor's name. supervisor: none, // The examiner's name. examiner: none, // The paper's content. body ) = { // Set document metadata. set document(title: title, author: authors) // Configure the page. set page( paper: "a4", margin: 30mm ) // Display the front page cover. set text(font: "FreeSans") page( header-ascent: 0%, header: align( right, { [ Linköping University | Department of Computer and Information Science \ Master's thesis, 30 ECTS | Datavetenskap \ 2024 | LIU-IDA/LITH-EX-A--24/001--SE ] } ), footer-descent: 0%, footer: pad(bottom: 20mm, table( columns: (60%, 1fr, 40%), align: (x, y) => (left + bottom, center, right + bottom).at(x), inset: 0pt, stroke: none, // The negative padding is a workaround to remove the padding // around the logo pad(-20pt, image(height: 90pt, "resources/liu_logo.svg")), [], text(10pt)[ Linköpings universitet \ SE-581 83 Linköping \ +46 13 28 10 00, www.liu.se ] )), align( horizon + left, pad(left: 40mm, { // Display the paper's title. stack( spacing: 1.5em, text(20pt, title), if (subtitle != none) { text(12pt)[\- #subtitle] } ) v(8.35mm, weak: true) line(length: 100%) text( size: 12pt, { emph(stack( spacing: 1em, if (titleSwedish != none) { titleSwedish }, if (subtitleSwedish != none) { [\- #subtitleSwedish] } )) }) v(1em) // Display the authors list. for author in authors { [*#author*] parbreak() } v(1em) // Display the supervisor. text(size: 10pt)[ Supervisor: #supervisor \ Examiner: #examiner ] }) ) ) // Set the body font. set text(font: "Free Serif", size: 11pt) // Paragraph properties. set par(justify: true, first-line-indent: 1em) show par: set block(spacing: 0.65em) // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Display copyright notice. heading(level: 2, numbering: none, outlined: false, "Upphovsrätt") [ Detta dokument hålls tillgängligt på Internet -- eller dess framtida ersättare -- under 25 år från publiceringsdatum under förutsättning att inga extraordinära omständigheter uppstår. Tillgång till dokumentet innebär tillstånd för var och en att läsa, ladda ner, skriva ut enstaka kopior för enskilt bruk och att använda det oförändrat för ickekommersiell forskning och för undervisning. Överföring av upphovsrätten vid en senare tidpunkt kan inte upphäva detta tillstånd. All annan användning av dokumentet kräver upphovsmannens medgivande. För att garantera äktheten, säkerheten och tillgängligheten finns lösningar av teknisk och administrativ art. Upphovsmannens ideella rätt innefattar rätt att bli nämnd som upphovsman i den omfattning som god sed kräver vid användning av dokumentet på ovan beskrivna sätt samt skydd mot att dokumentet ändras eller presenteras i sådan form eller i sådant sammanhang som är kränkande för upphovsmannens litterära eller konstnärliga anseende eller egenart. För ytterligare information om Linköping University Electronic Press, se förlagets hemsida #link("http://www.ep.liu.se/")[`http://www.ep.liu.se/`]. ] heading(level: 2, numbering: none, outlined: false, "Copyright") [ The publishers will keep this document online on the Internet - or its possible replacement - for a period of 25 years starting from the date of publication barring exceptional circumstances. The online availability of the document implies permanent permission for anyone to read, to download, or to print out single copies for his/hers own use and to use it unchanged for non-commercial research and educational purpose. Subsequent transfers of copyright cannot revoke this permission. All other uses of the document are conditional upon the consent of the copyright owner. The publisher has taken technical and administrative measures to assure authenticity, security and accessibility. According to intellectual property law the author has the right to be mentioned when his/her work is accessed as described above and to be protected against infringement. For additional information about the Linköping University Electronic Press and its procedures for publication and for assurance of document integrity, please refer to its www home page: #link("http://www.ep.liu.se/")[`http://www.ep.liu.se/`]. ] pad(left: 1em, top: 4em)[ $copyright$ #for author in authors { author parbreak() } ] pagebreak(weak: true) // Display abstract and index terms. if abstract != none { align(center, [*Abstract*]) v(1em) h(1em) abstract pagebreak(weak: true) } // Display outline { set par(first-line-indent: 0pt) show outline.entry.where( level: 1 ): it => { let heading_page = counter(page).at(it.element.location()).first() v(0.8em) text(13pt, strong({ link(it.element.location())[#it.body] h(1fr) [#heading_page] })) } outline(depth: 2, indent: auto, title: { heading("Contents") v(2em) }) } // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure appearance of equation references show ref: it => { if it.element != none and it.element.func() == math.equation { // Override equation references. link(it.element.location(), numbering( it.element.numbering, ..counter(math.equation).at(it.element.location()) )) } else { // Other references as usual. it } } // Configure headings. set heading(numbering: "1.1.1.") show heading: it => locate(loc => { if (it.level == 1) { // Always start top-level headings on a new page pagebreak(weak: true) // Draw in the style of Latex VZ43 set text(size: 20pt) box( height: 6.5cm, stack( // Vertical lines for i in range(7) { place(line(start: (i * 4pt, 0pt), angle: 90deg, length: 5cm)) }, // Chapter numbering if it.numbering != none { place( dx: 0.25cm, dy: 2.5cm, rect( fill: black, inset: 8pt, text(fill: white, counter(heading).display()), ) ) }, // Chapter title place( dx: 1.5cm, dy: 2.5cm, rect( inset: 8pt, stroke: none, it.body, ) ) ) ) return } v(0.65em) // Show numbering for at most 3 levels if (it.numbering != none and it.level <= 3) { // Add horizontal spacing between numbering and title block({ counter(heading).display() h(10pt) it.body }) } else { block({ it.body }) } v(0.65em) }) set page(numbering: "1") counter(page).update(1) // Display the paper's contents. body // Display bibliography. if bibliography-file != none { bibliography(bibliography-file, title: [Bibliography], style: "ieee") } }
https://github.com/tlsnotary/docs-mdbook
https://raw.githubusercontent.com/tlsnotary/docs-mdbook/main/research/a2m_and_m2a.typ
typst
#set page(paper: "a4") #set par(justify: true) = M2A OT sender and receiver want to get an *additive* sharing $(y, overline(b))$ from a *multiplicative* sharing $(x, a)$. So the sender starts with $x$ and ends up with $y$ and the receiver starts with $a$ and ends up with $overline(b)$. They compute $y=a x + b arrow.l.r.double y - b = a x arrow.l.r.double y + overline(b) = a x$ in $n$ OTs, where $n$ is given by the bitsize of the field elements $y, x, a, b$. The receiver's inputs for every $i$-th OT are $x_i$ and his output is $y_i$. The sender's inputs are a linear combination of $a$ and $b_i$ and he outputs $b_i$. == Compute $y = a x + b$ #align(center)[ #box[$P_R$ #v(4em)] #box[$x_i$ #line(length: 2cm) #v(3em) $y_i$ #line(length: 2cm) #v(1em)] #box[#square(size: 8em)[#v(3em) $"OT"_i$]] #box[$k_i = (b_i, a+b_i)$ #line(length: 2.5cm) #v(3em) $b_i$ #line(length: 2.5cm) #v(1em)] #box[$P_S$ #v(4em)] ] === *The OT sender $P_S$:* + Sample $n$ random field elements $b_i arrow.l \$$ so that $b = sum_(i = 0)^n 2^i b_i$ + In each $i$-th OT: Send $k_i = (b_i, a + b_i)$ to $P_R$ + Compute and output $overline(b) = - b = - sum_(i = 0)^n 2^i b_i$ === *The OT receiver $P_R$:* + Bit-decomposes $x = sum_(i = 0)^n 2^i x_i$ + In each $i$-th OT: Depending on the bit of $x_i$ he receives $y_i = k_i^x_i$, which is - $k_i^0 = b_i$ if $x_i = 0$ - $k_i^1 = a + b_i$ if $x_i = 1$ + Compute and output $y = sum_(i = 0)^n 2^i k_i = a x + b$ == Correctness Check + Repeat the whole M2A protocol for the same $x$ but with random $a_2, b_2$. We now label $a_1 := a$ and $b_1 := b$, which are the original values from the previously executed M2A protocol + $P_R$ sends $2$ random field elements $chi_1, chi_2$ to $P_S$ + $P_S$ computes $a^* = chi_1 a_1 + chi_2 a_2$ and $b^* = chi_1 b_1 + chi_2 b_2$ and sends them to $P_R$. + $P_R$ checks that $ chi_1 y_1 + chi_2 y_2 = a^* x + b^*$ = A2M OT sender and receiver want to get a *multiplicative* sharing $(y, overline(b))$ from an *additive* sharing $(x, a)$. So the sender starts with $x$ and ends up with $y$ and the receiver starts with $a$ and ends up with $overline(b)$. They compute $y=(a + x) b arrow.l.r.double y b^(-1) = a + x arrow.l.r.double y overline(b) = a + x$ in $n$ OTs, where $n$ is given by the bitsize of the field elements $y, x, a, b$. The receiver's inputs for every $i$-th OT are $x_i$ and his output is $y_i$. The sender's inputs are a linear combination of $a_i$ and $b$ including a mask $m_i$ and he outputs $b$. == Compute $y = (a + x) b$ #align(center)[ #box[$P_R$ #v(4em)] #box[$x_i$ #line(length: 2cm) #v(3em) $y_i$ #line(length: 2cm) #v(1em)] #box[#square(size: 8em)[#v(3em) *OT*]] #box[$k_i = (a_i b + m_i, (a_i + 1) b + m_i)$ #line(length: 5cm) #v(3em) $b$ #line(length: 5cm) #v(1em)] #box[$P_S$ #v(4em)] ] === *The OT sender $P_S$:* + Sample a random field element $b arrow.l \$$ + Sample $n$ random field elements $m_i arrow.l \$$, with $sum_(i = 0)^n 2^i m_i = 0$ + Bit-decomposes $a = sum_(i = 0)^n 2^i a_i$ + In each $i$-th OT: Send $k_i = (a_i b + m_i, (a_i + 1) b + m_i)$ to $P_R$ + Compute and output $overline(b) = b^(-1)$ === *The OT receiver $P_R$:* + Bit-decomposes $x = sum_(i = 0)^n 2^i x_i$ + In each $i$-th OT: Depending on the bit of $x_i$ he receives $y_i = k_i^x_i$, which is - $k_i^0 = a_i b + m_i$ if $x_i = 0$ - $k_i^1 = (a_i + 1) b + m_i$ if $x_i = 1$ + Compute and output $y = sum_(i = 0)^n 2^i k_i = (a + x) b$ == Correctness Check + Repeat the whole A2M protocol for the same $x$ but with random $a_2, b_2$. We now label $a_1 := a$ and $b_1 := b$, which are the original values from the previously executed A2M protocol + $P_R$ sends $2$ random field elements $chi_1, chi_2$ to $P_S$ + $P_S$ computes $z^* = chi_1 a_1 b_1 + chi_2 a_2 b_2$ and $b^* = chi_1 b_1 + chi_2 b_2$ and sends them to $P_R$. + $P_R$ checks that $ chi_1 y_1 + chi_2 y_2 = b^* x + z^*$
https://github.com/mem-courses/discrete-mathmatics
https://raw.githubusercontent.com/mem-courses/discrete-mathmatics/main/homework/week12.typ
typst
MIT License
#import "../template.typ": * #import "../functions.typ": * #show: project.with( course: "Discrete Mathmatics", course_fullname: "Discrete Mathematics and Application", course_code: "211B0010", title: "Homework #12: Partial Orderings & Graph Introduction", authors: (( name: "<NAME>", email: "<EMAIL>", id: "A10" ),), semester: "Spring-Summer 2024", date: "May 20, 2024", ) == 9.6 Partial Orderings #hw("5")[ Which of these are posets? #parts( columns: 4, a: [$(ZZ, =)$], b: [$(ZZ, !=)$], c: [$(ZZ, >=)$], d: [$(ZZ, divides.not)$], ) ][ #parts( columns: 2, a: [T.], b: [F. Is not reflexive and antisymmetric.], c: [T.], d: [F. Is not reflexive, antisymmetric and transitive.], ) ] #hw("10")[ Determine whether the relation with the directed graph shown is a partial order. #align(center, image("images/2024-05-20-13-50-59.png", width: 25%)) ][ We have $c prec.eq d$ and $d prec.eq b$ but do not have $c prec.eq b$. So it is not a partial order because it is not transitive. ] #hw("23(a,c)")[ Draw the Hasse diagram for divisibility on the set #parts( columns: 2, a: [{1, 2, 3, 4, 5, 6, 7, 8}.], c: [{1, 2, 3, 6, 12, 24, 36, 48}.], ) ][ #parts( columns: 2, a: align(center, image("images/2024-05-20-14-29-28.png", width: 45%)), c: align(center, image("images/2024-05-20-14-31-14.png", width: 27%)), ) ] #hw("32")[ Answer these questions for the partial order represented by this Hasse diagram. #align(center, image("images/2024-05-20-13-51-57.png", width: 20%)) #parts( a: [Find the maximal elements.], b: [Find the minimal elements.], c: [Is there a greatest element?], d: [Is there a least element?], e: [Find all upper bounds of ${a, b, c}$.], f: [Find the least upper bound of ${a, b, c}$, if it exists.], g: [Find all lower bounds of ${f, g, h}$.], h: [Find the greatest lower bound of ${f, g, h}$, if it exists.], ) ][ #parts( columns: 4, a: [$l,m$.], b: [$a,b,c$.], c: [No.], d: [No.], e: [$l,k,m$.], f: [$k$.], g: [None.], h: [Not exists.], ) ] #hw("44")[ Determine whether these posets are lattices. #parts( a: [$({1, 3, 6, 9, 12}, |)$], b: [$({1, 5, 25, 125}, |)$], c: [$(ZZ, >=)$], d: [$(cal(P)(S), supset.eq)$, where $cal(P)(S)$ is the power set of a set $S$] ) ][ #parts( a: [F. The lub of 6 and 9 is not in the given set.], b: [T. A finite chain is a lattice.], c: [T. $forall x,y in ZZ$, $"lub"(x,y)=max(x,y), "glb"(x,y)=min(x,y)$.], d: [T. $forall X,Y in cal(P)(S)$, that is $X,Y subset.eq S$, we have $"lub"(X,Y) = X union Y subset.eq S$, $"glb"(X,Y) = X sect Y subset.eq S$.], ) ] #hw("66")[ Schedule the tasks needed to build a house, by specifying their order, if the Hasse diagram representing these tasks is as shown in the figure. #align(center, image("images/2024-05-20-14-00-12.png", width: 40%)) ][ The order could be: foundation $->$ framing $->$ roof $->$ exterior siding $->$ plumbing $->$ wiring $->$ flooring $->$ wall-board $->$ exterior painting $->$ carpeting $->$ interior painting $->$ interior fixtures $->$ exterior fixtures $->$ completion. ] == 10.1 Graphs and Graph Models #hw("1")[ Draw graph models, stating the type of graph (from Table 1) used, to represent airline routes where every day there are - four flights from Boston to Newark, - two flights from Newark to Boston, - three flights from Newark to Miami, - two flights from Miami to Newark, - one flight from Newark to Detroit, - two flights from Detroit to Newark, - three flights from Newark to Washington, - two flights from Washington to Newark, - and one flight from Washington to Miami, with #parts( a: [an edge between vertices representing cities that have a flight between them (in either direction).], b: [an edge between vertices representing cities for each flight that operates between them (in either direction).], c: [an edge between vertices representing cities for each flight that operates between them (in either direction), plus a loop for a special sightseeing trip that takes off and lands in Miami.], d: [an edge from a vertex representing a city where a flight starts to the vertex representing the city where it ends.], e: [an edge for each flight from a vertex representing a city where the flight begins to the vertex representing the city where the flight ends.], ) ][ #parts( a: align(center, image("images/2024-05-20-16-20-46.png", width: 60%)), b: align(center, image("images/2024-05-20-16-23-04.png", width: 60%)), c: align(center, image("images/2024-05-20-16-23-42.png", width: 60%)), d: align(center, image("images/2024-05-20-16-24-32.png", width: 60%)), e: align(center, image("images/2024-05-20-16-25-39.png", width: 60%)) ) ] #hw("3,4,5,6,7,8,9")[ For Exercises 3–9, determine whether the graph shown has directed or undirected edges, whether it has multiple edges, and whether it has one or more loops. Use your answers to determine the type of graph in Table 1 this graph is. #align(center, image("images/2024-05-20-14-06-32.png", width: 60%)) ][ #let T = [Yes] #let F = [No] #table3( columns: (0.3fr, 1fr, 1fr, 1.5fr), [*\#*], [*Has multiple edges?*], [*Has loops?*], [*Type of graph*], 3, F, F, [Simple graph], 4, T, F, [Multigraph], 5, T, T, [Pseudograph], 6, T, F, [Multigraph], 7, F, T, [Directed graph], 8, T, T, [Directed multigraph], 9, T, T, [Directed multigraph], ) ] == 10.2 Graph Terminology and Special Types of Graphs #hw("5")[ Can a simple graph exist with 15 vertices each of degree five? ][ No. Because the total degree of all vertices is $15 times 5 = 75$, which is not even. So such a simple graph is not exists. ] #hw("24,25")[ In Exercises 24–25 determine whether the graph is bipartite. You may find it useful to apply Theorem 4 and answer the question by determining whether it is possible to assign either red or blue to each vertex so that no two adjacent vertices are assigned the same color. #align(center, image("images/2024-05-20-14-07-29.png", width: 55%)) ][ *24.* Is bipartite. Suppose that ${a,b,d,e}$ are white and ${f,c}$ are black. *25.* Is not bipartite. Because we can find a triangle ${b,d,e}$. ] #hw("44(b,f,h)")[ Determine whether each of these sequences is graphic. For those that are, draw a graph having the given degree sequence. #parts( columns: 3, b: [6,5,4,3,2,1], f: [1,1,1,1,1,1], h: [5,5,4,3,2,1], ) ][ #parts( b: [Not graphic. Because the total degree is $6+5+4+3+2+1=21$, which is odd.], f: [Graphic. An example is $E={(1,2),(3,4),(5,6)}$.], h: [Not graphic. Because there are two vertices with degree 5, which means the they should connected with all other vertices. But there is a vertices with degree only 1, so such a simple graph is not exists.], ) ] #hw("55")[ For which values of $n$ are these graphs regular? #parts( columns: 4, a: [$K_n$], b: [$C_n$], c: [$W_n$], d: [$Q_n$], ) ][ #parts( a: [For all $n$, $K_n$ is $(n-1)$-regular.], b: [For all $n>2$, $C_n$ is $2$-regular.], c: [$W_n$ is regular if and only if $n=3$.], d: [For all $n$, $Q_n$ is $n$-regular.] ) ] #hw("62")[ If $G$ is a simple graph with 15 edges and $overline(G)$ has 13 edges, how many vertices does $G$ have? ][ By solving the equation $ n(n-1)/2 = 15+13, $ we can dervie that $G$ has $n=8$ vertices. ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list-attach_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test non-attached list followed by attached list, // separated by only word. Hello - A World - B
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/networks/lec13.typ
typst
#import "template.typ": * #show: template.with( title: "Lecture 13", subtitle: "14.15" ) = Games / Static: Game is played all at once and not over time. / Complete Information: There is no unnecessary or private information in a game. The strategy set $S_i$ describes the set of choices available to the $i$th player. The payoff function $u$ describes the outcome (payoff) for every single possible set of choices amongst the players. #example( title: "Prisoner's Dilemma" )[ If both prisoners cooperate, 1 year in prison, 2 if both defect, and 3 if you are the only one not to defect. The sole defector in that case would get 0 years. $ N = {1, 2}\ S_1 = S_2 = {C, D}\ u_1(C, C) = u_2(C, C) = 2\ u_1(D, D) = u_2(D, D) = 1\ u_1(C, D) = u_2(D, C) = 0\ u_1(D, C) = u_2(C, C) = 3\ $ We can create a payoff matrix with $x$ being P2, $y$ being P1, and the payoff function $u_1, u_2$ in each cell. ]
https://github.com/luiswirth/bsc-thesis
https://raw.githubusercontent.com/luiswirth/bsc-thesis/main/src/introduction.typ
typst
= Introduction Finite Element Exterior Calculus (FEEC) is a mathematical framework for formulating the theory of the Finite Element Method. Instead of only relying on vector calculus it makes use of the far more general theory of Differential Forms. "Without referring to differential geometry, several authors had devised vector valued finite elements that can be regarded as special cases of discrete differential forms. Their constructions are formidably intricate and require much technical effort. A substantial simplification can be achieved: One should exploit the facilities provided by differential geometry for a completely coordinate-free treatment of discrete differential forms. Once we have shed the cumbersome vector calculus, everything can be constructed and studied with unmatched generality and elegance. In particular, all orders of forms and all degrees of polynomial approximation can be dealt with in the same framework. This can be done for simplicial meshes in arbitrary dimension." @hiptmair-whitney There are very few implementations of FEEC available. One is #link("https://github.com/Airini/FEECa")[FEECa]. Which is a Finite Element Exterior Calculus Implementation in Haskell. However Haskell is not a language that is suited for High Performance Computing (HPC) but rather known for it's mathmatical expressiveness. It is not capable of solving PDEs. Rust combines these two traits of being high performant, while still being expressive. Fenics has support for FEEC threough the package "Exterior". The Exterior package can currently compute the finite elements (including the nodal basis) P_r\Lambda^k(T) and P_r^-\Lambda^k(T) for arbitrary simplices T (and its sub simplices) in Rn for arbirtrary r, k, n. PyDEC is a Python library implementing Discrete Exterior Calculus (DEC) and lowest order finite element exterior calculus (FEEC) i.e., Whitney forms.
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2024/WS-06.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [SUN Yingsha], [CHN], [3629], [2], [CHEN Meng], [CHN], [3421], [3], [WANG Manyu], [CHN], [3416], [4], [CHEN Xingtong], [CHN], [3248], [5], [HAYATA Hina], [JPN], [3233], [6], [ZHU Yuling], [MAC], [3222], [7], [WANG Yidi], [CHN], [3214], [8], [QIAN Tianyi], [CHN], [3156], [9], [CHENG I-Ching], [TPE], [3128], [10], [HARIMOTO Miwa], [JPN], [3126], [11], [ITO Mima], [JPN], [3122], [12], [HE Zhuojia], [CHN], [3115], [13], [HIRANO Miu], [JPN], [3112], [14], [ZHANG Rui], [CHN], [3098], [15], [KIHARA Miyuu], [JPN], [3089], [16], [BATRA Manika], [IND], [3064], [17], [JEON Jihee], [KOR], [3041], [18], [KUAI Man], [CHN], [3037], [19], [HAN Ying], [GER], [3031], [20], [HASHIMOTO Honoka], [JPN], [3029], [21], [FAN Siqi], [CHN], [3028], [22], [SZOCS Bernadette], [ROU], [3009], [23], [ODO Satsuki], [JPN], [2986], [24], [SHI Xunyao], [CHN], [2984], [25], [LIU Weishan], [CHN], [2976], [26], [SATO Hitomi], [JPN], [2968], [27], [OJIO Haruna], [JPN], [2964], [28], [NAGASAKI Miyu], [JPN], [2963], [29], [YANG Xiaoxin], [MON], [2955], [30], [CHEN Yi], [CHN], [2946], [31], [MITTELHAM Nina], [GER], [2926], [32], [SHIBATA Saki], [JPN], [2914], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [SHIN Yubin], [KOR], [2878], [34], [DIAZ Adriana], [PUR], [2865], [35], [POLCANOVA Sofia], [AUT], [2864], [36], [JOO Cheonhui], [KOR], [2863], [37], [FAN Shuhan], [CHN], [2860], [38], [MORI Sakura], [JPN], [2851], [39], [LEE Eunhye], [KOR], [2847], [40], [SUH Hyo Won], [KOR], [2846], [41], [PYON Song Gyong], [PRK], [2830], [42], [PAVADE Prithika], [FRA], [2822], [43], [DO<NAME>], [HKG], [2810], [44], [PARANANG Orawan], [THA], [2795], [45], [TAKAHASHI Bruna], [BRA], [2795], [46], [WU Yangchen], [CHN], [2789], [47], [LI Yake], [CHN], [2783], [48], [BAJOR Natalia], [POL], [2778], [49], [SHAN Xiaona], [GER], [2778], [50], [<NAME>], [GER], [2778], [51], [EERLAND Britt], [NED], [2769], [52], [GUO Yuhan], [CHN], [2765], [53], [QIN Yuxuan], [CHN], [2764], [54], [XU Yi], [CHN], [2759], [55], [YANG Yiyun], [CHN], [2750], [56], [YUAN Jia Nan], [FRA], [2746], [57], [ZENG Jian], [SGP], [2742], [58], [KALLBERG Christina], [SWE], [2741], [59], [LEE Ho Ching], [HKG], [2740], [60], [WANG Xiaotong], [CHN], [2738], [61], [ZHANG Lily], [USA], [2732], [62], [SAMARA Elizabeta], [ROU], [2728], [63], [AKULA Sreeja], [IND], [2718], [64], [CHIEN Tung-Chuan], [TPE], [2711], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [PESOTSKA Margaryta], [UKR], [2708], [66], [NI Xia Lian], [LUX], [2708], [67], [SHAO Jieni], [POR], [2707], [68], [ZHU Chengzhu], [HKG], [2706], [69], [QI Fei], [CHN], [2704], [70], [WINTER Sabine], [GER], [2701], [71], [DIACONU Adina], [ROU], [2696], [72], [ZHANG Mo], [CAN], [2695], [73], [HAN Feier], [CHN], [2687], [74], [YANG Ha Eun], [KOR], [2686], [75], [KIM Hayeong], [KOR], [2686], [76], [KIM Nayeong], [KOR], [2681], [77], [LEE Daeun], [KOR], [2675], [78], [SASAO Asuka], [JPN], [2672], [79], [DRAGOMAN Andreea], [ROU], [2667], [80], [YOKOI Sakura], [JPN], [2664], [81], [MESHREF Dina], [EGY], [2663], [82], [LI Yu-Jhun], [TPE], [2658], [83], [CHOI Hyojoo], [KOR], [2654], [84], [LEE Zion], [KOR], [2653], [85], [WAN Yuan], [GER], [2651], [86], [XIAO Maria], [ESP], [2650], [87], [YU Fu], [POR], [2625], [88], [WANG Amy], [USA], [2623], [89], [ZHU Sibing], [CHN], [2622], [90], [<NAME>], [ITA], [2620], [91], [KIM Byeolnim], [KOR], [2613], [92], [ARA<NAME>], [CRO], [2608], [93], [RAKOVAC Lea], [CRO], [2606], [94], [POTA Georgina], [HUN], [2606], [95], [LIU Yangzi], [AUS], [2606], [96], [<NAME>], [IND], [2603], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [ZHANG Sofia-Xuan], [ESP], [2601], [98], [LIU Hsing-Yin], [TPE], [2594], [99], [CHEN Szu-Yu], [TPE], [2591], [100], [SAWETTABUT Jinnipa], [THA], [2591], [101], [LUTZ Charlotte], [FRA], [2590], [102], [SAWETTABUT Suthasini], [THA], [2587], [103], [ZONG Geman], [CHN], [2584], [104], [NG Wing Lam], [HKG], [2582], [105], [HUANG Yu-Chiao], [TPE], [2579], [106], [CIOBANU Irina], [ROU], [2577], [107], [<NAME>], [JPN], [2575], [108], [NOMURA Moe], [JPN], [2574], [109], [LIU Jia], [AUT], [2574], [110], [<NAME>i], [IND], [2570], [111], [<NAME>], [JPN], [2566], [112], [HUANG Yi-Hua], [TPE], [2562], [113], [<NAME>], [IND], [2560], [114], [<NAME>jing], [CHN], [2559], [115], [ZHANG Xiangyu], [CHN], [2558], [116], [DE NUTTE Sarah], [LUX], [2550], [117], [<NAME>], [SRB], [2546], [118], [<NAME>], [POL], [2545], [119], [<NAME>], [CZE], [2545], [120], [<NAME>ini], [GRE], [2539], [121], [<NAME>], [KOR], [2537], [122], [KAM<NAME>irish], [IND], [2536], [123], [GODA Hana], [EGY], [2534], [124], [<NAME>], [SRB], [2528], [125], [<NAME>], [HUN], [2527], [126], [<NAME>], [GER], [2522], [127], [<NAME>], [SVK], [2512], [128], [<NAME>], [ROU], [2510], ) )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/metro/0.1.0/src/impl/num.typ
typst
Apache License 2.0
#import "@preview/t4t:0.2.0": is #import "/src/utils.typ": combine-dict #let number-to-string(number) = { number = if type(number) == "content" { if is.sequence(number) { number.children.map(c => c.text).join() } else { number.text } } else { str(number) }.replace("-", sym.minus) let sign = if number.starts-with(sym.minus) { sym.minus // For some reason strings get indexed by byte? minus is unicode number = number.slice(3) } else if number.starts-with(sym.plus) { sym.plus // Plus is ascii number = number.slice(1) } return (sign, number) } #let _num( number, exponent: none, uncertainty: none, options ) = { let spacing = if not options.tight-spacing { sym.space.thin } let (sign, number) = number-to-string(number) let (integer, decimal) = { let a = number.split(regex(options.input-decimal-markers.join("|"))) assert(a.len() <= 2, message: repr(a)) (a.first(), a.at(1, default: none)) } let group-digits(input, rev: true) = { let (first, other) = if options.digit-group-size != 3 { (options.digit-group-size,) * 2 } else { (options.digit-group-first-size, options.digit-group-other-size) } let input = if rev { input.split("").slice(1, -1).rev() } else { input } let len = input.len() let start = calc.rem(first, input.len()) let result = ( input.slice(0, start), ..for i in range(start, len, step: other) { (input.slice(i, calc.min(i + other, len)),) } ) return if rev { result.map(x => x.rev().join()).rev() } else { result }.join(options.group-separator) } if integer.len() < options.minimum-integer-digits { integer = "0" * (options.minimum-integer-digits - integer.len()) + integer } if decimal != none and decimal.len() < options.minimum-decimal-digits { decimal += "0" * (options.minimum-decimal-digits - decimal.len()) } if options.group-digits in ("all", "decimal", "integer") { if options.group-digits in ("all", "integer") and integer.len() >= options.group-minimum-digits { integer = group-digits(integer) } if decimal != none and options.group-digits in ("all", "decimal") and decimal.len() >= options.group-minimum-digits { decimal = group-digits(decimal, rev: false) } } let mantissa = { "" if (integer.len() == 0 or integer != "0") or options.print-zero-integer { if integer.len() == 0 { "0" } else { integer } } if decimal != none and (decimal != "" or options.retain-explicit-decimal-marker) { options.output-decimal-marker if options.zero-decimal-as-symbol and int(decimal) == 0 { options.zero-symbol } else { decimal } } } let print-mantissa = options.print-unity-mantissa or mantissa not in ("1", "") if uncertainty != none { uncertainty = spacing + sym.plus.minus + spacing + number-to-string(uncertainty).last() } if exponent != none { exponent = number-to-string(exponent) if exponent.last() != "0" or options.print-zero-exponent { exponent = if exponent.first() == sym.minus or options.print-implicit-plus or options.print-exponent-implicit-plus { exponent.join() } else { exponent.last() } exponent = if options.output-exponent-marker != none { options.output-exponent-marker + exponent } else { math.attach(if print-mantissa {spacing + options.exponent-product + spacing } + options.exponent-base, t: exponent) } } else { exponent = none } } let is-negative = sign == sym.minus and (mantissa != "0" or options.retain-negative-zero) let bracket-ambiguous-numbers = options.bracket-ambiguous-numbers and exponent != none and uncertainty != none let bracket-negative-numbers = options.bracket-negative-numbers and is-negative // Return return math.equation({ if bracket-ambiguous-numbers { "(" } if bracket-negative-numbers { "(" } else if is-negative { sym.minus } else if options.print-implicit-plus or options.print-mantissa-implicit-plus or (sign == sym.plus and options.retain-explicit-plus) { sym.plus } if print-mantissa { mantissa } if bracket-negative-numbers { ")" } uncertainty if bracket-ambiguous-numbers { ")" } exponent }) } #let num( number, e: none, pm: none, ..options ) = { return _num( number, exponent: e, uncertainty: pm, combine-dict(options.named(), ( // parsing input-decimal-markers: ("\.", ","), retain-explicit-decimal-marker: false, retain-explicit-plus: false, retain-negative-zero: false, retain-zero-uncertainty: false, // post-processing // drop-exponent: false, // drop-uncertainty: false, // drop-zero-decimal: false, // exponent-mode: "input", // exponent-thresholds: (-3, 3), // fixed-exponent: 0, minimum-integer-digits: 0, minimum-decimal-digits: 0, bracket-negative-numbers: false, digit-group-size: 3, digit-group-first-size: 3, digit-group-other-size: 3, exponent-base: "10", exponent-product: sym.times, group-digits: "all", group-minimum-digits: 5, group-separator: sym.space.thin, output-close-uncertainty: ")", output-decimal-marker: ".", output-exponent-marker: none, output-open-uncertainty: "(", print-implicit-plus: false, print-exponent-implicit-plus: false, print-mantissa-implicit-plus: false, print-unity-mantissa: true, print-zero-exponent: false, print-zero-integer: true, tight-spacing: false, bracket-ambiguous-numbers: true, zero-decimal-as-symbol: false, zero-symbol: sym.bar.h ), only-update: true) ) }
https://github.com/mhspradlin/wilson-2024
https://raw.githubusercontent.com/mhspradlin/wilson-2024/main/programming/day-5.typ
typst
MIT License
#set page("presentation-16-9") #set text(size: 30pt) = Day 5 #pagebreak() == Accepting input You may want to be able to input text into your program. For that, use the `input` function: ```python animal = input("What is your favorite animal? ") print("You said: " + animal) ``` #pagebreak() == Parsing Input To go from a string to a value like a number, you need to *parse* it. / Integer: `int("123")` / Float: `float("12.3")` #pagebreak() == Guessing Game #text(size: 28pt)[ ```python from random import randint target = randint(1, 100) guess = 0 while ???: guess = int(input("Enter your guess: ")) if ???: ??? else: ??? ``` ] #pagebreak() == Guessing Game Improvements - Can you tell the user if they are too high or too low? - Can you let the user pick the range of numbers? - Can you have the sense HAT light up if they are wrong or right? #pagebreak() == Recursive Functions A function can call itself using its name. ```python def countdown(number): if number == 0: print("All done!") else: print(number) countdown(number - 1) countdown(10) ``` #pagebreak() == Fibonacci The *Fibonacci sequence* is a sequence of numbers where each number is the sum of the two proceeding ones. It starts with `0, 1`: $ 0, 1, 1, 2, 3, 5, 8, 13, 21, ... $ The terms are numbered starting from zero, so $F_0 = 0$, $F_1 = 1$, $F_2 = 1$, $F_3 = 2$, and so on. #pagebreak() == Fibonacci Function Let's write a function that takes $n$ and calculates $F_n$. A simple algorithm for a function `fib(n)` is: 1. Check if $n$ is zero. If so, return zero. 1. Check if $n$ is one. If so, return one. 1. Return `fib(n - 1) + fib(n - 2)` #pagebreak() == `fib(n)` ```python def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2) for i in range(0, 10): print(fib(i)) ``` #pagebreak() == Using the Plotter Mu has a built-in plotter that lets you visualize data. Here is a helper function to display a data point: ```python def plot(n): print((n,)) ``` #pagebreak() == Plotter Try it out: ```python for i in range(0, 100): plot(i * i) ``` #pagebreak() == Collatz Conjecture For a given number $n$, define a sequence by repeatedly applying the following: - If the number is 1, stop - If the number is even, divide it by two - If the number is odd, multiply it by three and add 1 It seems like this always ends up at 1 for any number $n$, but nobody has been able to prove that it always will. #pagebreak() ```python def collatz(n): while n != 1: sleep(0.5) # To better see the plot plot(n) if n % 2 == 0: n = n / 2 else: n = n * 3 + 1 collatz(27) ``` #pagebreak() == Lab: Compass Maze #link("https://tinyurl.com/wilson-pi-day-5") - For this one, you'll need to save the contents of `maze.py` in the Trinket to a file called `maze.py` next to your code. - The easiest way to do this is to press `New`, paste the code from `maze.py` online, press save, then name the file `maze.py`. Survey: #link("https://tinyurl.com/wilson-pi-survey-2024")