repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/posit-dev/bcorp-report
https://raw.githubusercontent.com/posit-dev/bcorp-report/main/typst-template.typ
typst
#let posit_colors = ( blue: rgb("#447099"), grey: rgb("#404041"), dark_blue_3: rgb("#17212B"), light_blue_1: rgb("#D1DBE5"), light_blue_2: rgb("#A2B8CB") ) #let hex_background={ image("assets/images/hexes-8.5x11-#17212B.png", height: 100%, fit: "cover") } // Pages with a blue background #let page_blue(content)={ set page(background: hex_background) set text(fill: posit_colors.light_blue_1) show link: set text(fill: posit_colors.light_blue_2) show heading: set text(fill: posit_colors.light_blue_2) show heading.where(level: 1): it => { pagebreak() it } content } #let col-2(content)={ columns(2, gutter: 3em, content) } // Custom title page #let title_page(title, subtitle)={ page(margin: 0in, background: image("assets/images/09.17.23PositDayOne2.jpg", height: 100%, fit: "cover"))[ #set text(fill: white) #place(center + horizon, dy: -2.5in)[ #set align(center + horizon) #block(width: 100%, fill: posit_colors.dark_blue_3, outset: 5em)[ #text(weight: "light", size: 36pt, title) #text(weight: "bold", size: 24pt, subtitle) ] ] #place(center + bottom, dy: -36pt)[ #block(height: 36pt)[ #box(height: 24pt, baseline: -6pt, image("assets/images/posit-logo-white-TM.svg")) #box(inset: (x: 12pt), line(length: 100%, angle: 90deg, stroke: 0.5pt + white)) #box(image("assets/images/B-Corp-Logo-White-RGB.png")) ] ] ] } #let back_page(repo: none, content)={ page_blue()[ #set page(background: hex_background, numbering: none) #set text(fill: white) #show link: set text(fill: white) #show par: set block(spacing: 0.5em) #place(bottom + center)[ #block(height: 48pt)[ #box(height: 36pt, baseline: -8pt, image("assets/images/posit-logo-white-TM.svg")) #box(inset: (x: 24pt), line(length: 100%, angle: 90deg, stroke: 0.5pt + white)) #box(image("assets/images/B-Corp-Logo-White-RGB.png")) ] The open source data science company #text(size: 24pt, link("http://posit.co/")[posit.co]) #v(2em) #set text(size: 10pt) #(content) Published with #box(height: 12pt, baseline: 20% , image("assets/images/quarto-logo-trademark-white.svg")) #if repo != none { [Source code available at #link(repo)] } ] ] } // Page with image in header #let page_banner(image_paths: none, image_height: 100%, image_location: right + horizon, fill: posit_colors.light_blue_1, content)={ set page( margin: (top: 2in), header: [ #set text(fill: white) #block(width: 100%, height: 100%, outset: (x: 1.25in), inset: (y: 2em), fill: fill)[ #if (image_paths != none){ set image(height: image_height) place(image_location, stack(dir: ltr, ..image_paths.map(image))) } ] ] ) content } #let posit( title: none, subtitle: none, margin: (x: 1.25in, y: 1.25in), paper: "us-letter", lang: "en", region: "US", font: (), fontsize: 10pt, doc, ) = { set page( paper: paper, margin: margin, numbering: none, ) set text(lang: lang, region: region, font: font, size: fontsize, fill: posit_colors.grey) set par( leading: 0.8em ) set table( align: left, inset: 7pt, stroke: (x: none, y: 0.5pt) ) if title != none { title_page(title, subtitle) } show heading.where(level: 1): set text(weight: "light", size: 24pt) show heading.where(level: 1): set block(width: 100%, below: 1em) show heading.where(level: 2): it => { set block(below: 1.5em) upper(it) } show link: underline show link: set underline(stroke: 1pt, offset: 2pt) show link: set text(fill: posit_colors.blue) block(above: 0em, below: 2em)[ #outline( indent: 1.5em ); ] set page(numbering: "1") doc }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/038%20-%20War%20of%20the%20Spark/005_Operation%20Desperation.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Operation Desperation", set_name: "War of the Spark", story_date: datetime(day: 05, month: 06, year: 2019), author: "<NAME>", doc ) #align(center)[#strong[I.]] Teyo, Mistress Kaya, Master Zarek, Queen Vraska, and I took Golgari tunnels as far as we could take them. But the old direct passages between the Golgari and Rakdos guildhalls had been closed since Jarad vod Savo, a former Golgari guildmaster, was first killed in Rix Maadi by a Rakdos blood witch. So in the end, we had to surface and brave whatever Spark-harvesting creepies might be about. We encountered none, which seemed a good sign. Moreover, from a hilltop we could see Tenth District Plaza, and the portal was no longer there. We already knew <NAME> and <NAME> and <NAME> and others were doing their best—now with the Golgari's help—to rescue as many Ravnicans as possible. And Master Zarek had shut down the Beacon. Now, it was clear that Mister Fayden, Mister Karn, <NAME>, and the Demon-Man Ob Nixilis had successfully shut down the Planar Bridge, as well. That was three of Mister Beleren's first six missions accomplished. #emph[Or maybe four] #emph[ . . .] My companions all stopped dead in their tracks. I asked Teyo what was wrong, and he said something had changed. "What?" "I—" Queen Vraska said, "It's down. The Immortal Sun has been shut down." Swallowing hard, I said, "Then you're all free to go, to planeswalk . . ." Mistress Kaya said, "We're not going anywhere." Master Zarek said, "No. There's still work to do." Four missions accomplished. That just left two. The assassination of Miss Raven-Hair, <NAME>. That was Mister Beleren's mission with <NAME>, <NAME>, and <NAME>. Then there was our mission: Operation Desperation. Master Zarek had told us Miss Lavinia would represent Azorius. And Master Lazav of Dimir had promised he'd participate, too. With Boros, Izzet, Simic, Orzhov, Selesnya, Gruul, and Golgari already secured, that just left Rakdos. I dreaded going down there, into Rix Maadi. Not that the place frightened me. But without Hekara there in the where that she should be, I was afraid I'd just . . . dissolve . . . like into a puddle. That kinda thing doesn't happen to me very often. I'm a pretty resilient Rat, you know? Mostly, I have to be. But when I do get sad or kinda broken, it's okay, 'cuz no one sees it. I barely even take notice of myself, right? I mean, what's the point of wallowing in all that weepiness or whatever? #emph[Who does it help?] But this time there'd be witnesses. Teyo and Mistress Kaya—and maybe even Master Zarek—would see me break. And if they saw it, then I'd have to see it, too. That would make it real. And that would mean Hekara was . . . Anyway, nine guilds secured. One to go. And four missions down. Two to go. Well . . . three, really. Can't forget the final mission. 'Cuz when all this, you know, #emph[easy stuff] has been gotten out of the way, there was still the dragon. #emph[Yeah. There's still the dragon.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[II.]] The first juggler, wearing studded red leathers and ribbons that ended in sharp metal fishhooks, impressively juggled six flaming torches. The second juggler juggled eight human skulls. The third juggled twelve flaming skulls. The fourth juggler was an undead skeleton, bones reinforced with wrought iron, including four wrought-iron horns mimicking those of its master, Rakdos the Defiler. It juggled flaming cat skulls pulled from a small furnace smoldering within its own rib cage. Without warning, the skeleton flung one of these small burning skulls at Teyo, who barely managed to throw up a circular shield of white light to block it from hitting him in the eye. The skull ricocheted off his shield and struck the skeleton in the face. It laughed a hoarse airless laugh, and Teyo shivered. Mistress Kaya tried to reassure him. "They're just trying to intimidate you." Teyo looked at the ground and grumbled, "It's working." The skeleton whispered, "You've got us all wrong, Mistress. We're just trying to #emph[entertain] you." Teyo glared at the skeleton and grumbled, "It's not working." The skeleton laughed again and said, "Well, at least you're entertaining me." #figure(image("005_Operation Desperation/01.jpg", width: 100%), caption: [Dead Revels | Art by: <NAME>umbo], supplement: none, numbering: none) We were descending the five hundred steps of the Demon's Vestibule toward Rix Maadi. Veins of lava running down the wurm-carved walls shed a dull-red light across all I could see. Another performer was perched on every fourth or fifth step. After the jugglers came the puppeteers, each with a marionette designed to stoke nightmares in the uninitiated. #emph[But I'm not uninitiated.] I'd been down these steps, seen these same acts, so many times with Hekara. They were like old friends—old friends determined to remind me that my closest friend would never share these steps with me again. #emph[I hate them! Why are they still here when she's gone?] #emph[Why am I still here when she's gone?] I thought I'd seen them all, but the last puppeteer made me gasp aloud. Her marionette was a brutally accurate caricature of Hekara, a razorwitch complete with actual razors. I could practically feel the concern rolling off Mistress Kaya, as our eyes met, sharing a moment's shared grief. It was either scream or, you know, lean into it. I smiled sadly and whispered simply, "It won't be the same here without her." #emph[What a dumb, obvious thing to say. Yet what else ] is#emph[ there to say?] Hekara's passing was exactly why Mistress Kaya had #emph[strongly suggested] Queen Vraska accompany us to Rix Maadi—and why Kaya had insisted the gorgon come without her kraul or Erstwhile defenders. If the Cultists wanted an explanation (or demanded vengeance) for the death of Emissary Hekara, Master Zarek and Mistress Kaya wanted the queen there to explain (or pay the price). Surprisingly, Her Highness had not objected. Seemingly of its own volition, the Hekara puppet threw very real razors at Zarek and Vraska. The small blades weren't thrown with quite enough force to cause any serious damage to either the Izzet or Golgari guildmasters, though the former was left with a small cut on his arm and the Queen's face had been nicked and was slowly dripping a line of blood down her cheek. Mistress Kaya's thoughts were now all filled with concern over the blades having been poisoned. I shook my head. "They're clean. But they might not be on the way back #emph[up] the stairs . . . depending on how this goes." Puppeteers gave way to caged horrors with masked devils seated atop the cages, ready and willing to set the little monsters free. These particular horrors, spidery things that huffed and puffed and screeched and wailed, were only the size of nodorog cubs, but then again, on this tight, claustrophobic staircase, a cub-sized horror could do significant damage. The devils giggled wildly and constantly motioned toward the latches, threatening to open their cages. Teyo flinched every time, which only made them do it more. The walls were lined, smeared, with hundreds of torn and overlapping banners, some advertising centuries-old performances, most incorporating some insult to one of the other guilds, with Orzhov, Azorius, and Boros being the most common and popular targets. Mistress Kaya stopped to stare at one banner that appeared as ancient as the rest but depicted herself, <NAME>, Queen Vraska, and Miss Lavinia hanging like marionettes, each from a single string wrapped tightly around their throats. Their heads lolled, their tongues stuck out, their limbs were slack, their faces bloated and blue. The puppeteer holding their four noose-like strings was a painted image of the Hekara marionette, and the puppeteer working #emph[Hekara's ] strings was the Defiler, himself. It didn't bode well for our reception below. Mistress Kaya inhaled, exhaled, and moved on. Teyo stopped for a look, too. He was developing a tic in his left cheek. I ushered him forward, saying, "At least they don't have a banner of you." "Yet," he amended nervously. Past the devils and their horrors were the fire-breathers. Teyo motioned to create a shield, but I stopped his hand and shook my head again. "You'll only encourage them. Just pay attention, and when they inhale, pass them by." Throughout our descent, <NAME> and Queen Vraska remained wary but stoic, each brooding deeply on his or her own dark thoughts, most of which—I could sense—revolved around Hekara. Except for Teyo, who hadn't known her, we were #emph[all ] mourning our friend. Even Mistress Kaya and <NAME>, who had nothing to blame each other for, felt Hekara's loss looming between them. In part, I guess, it was 'cuz <NAME>k had always held himself aloof from Hekara—taking advantage of her without ever truly acknowledging that he cared about her—though now that it was too late, he realized he cared about her deeply. He felt guilty about this, and an irrational part of him was angry with Mist<NAME> for having always treated Hekara with open warmth. Mostly, though, he was just mad at himself. The deeper we went, the hotter and closer the air became, and not just because of the fire-breathers. The red veins in the curving walls were wider down here and more liquid. The searing lava dripped down onto the steps and needed to be carefully avoided if we wanted to keep our boots intact—or our feet. The fire-breathers now gave way to unicyclists, who balanced impressively in place, rolling back and forth within a span of a few inches, on devices that appeared designed for a torture chamber: spokes of barbed wire, clawed wheels, seats made from axe blades. More than one of the riders bled. Every rider came close to slicing gashes in our party of five. One cyclist, who couldn't see me, nearly chopped off my foot. But this sort of near catastrophe was a common occurrence, and I'd trained myself to be very, very #emph[aware] of my surroundings at all times. I easily skipped past the threat. Finally, we reached the bottom step, and the Vestibule terminated at the Festival Grounds, which were guarded by two immense ogres wearing masks made from actual ogre skulls. Mistress Kaya hesitated but the ogres paid no heed to me or any of the others—as if all four of them were just four more Rats. So Kaya ignored them back and continued forward across the large courtyard. In its center was a cracked and graffitied fountain featuring a statue of a centaur. From a certain angle, the statue was surprisingly elegant, but I knew that as we approached it, the others would see that chunks of marble had been broken off the man-horse as if by a sledgehammer. Water dribbled from broken lips, and that water in turn dribbled out of the cracked fountain and down through a crack in the floor, where it rose again as steam. Above us, unoccupied trapeze swings hung from rusty hooks, while a single young pigtailed tightrope walker, in a black and red harlequin leotard, glided heedlessly across a threadbare strand. Her movements were full of grace, drawing the eye. She glanced down at her new audience, and Teyo gasped. Her lips and eyelids had been stitched shut. There were empty cages large enough to hold human-sized horrors. And everything, absolutely everything, was haphazardly painted with splatters of blood. At the far end of the Festival Grounds, two more skull-masked ogres stood guard before the ornate stone façade of Rix Maadi. Like the first pair, these ogres seemed to take no notice of us. Still, our little group hesitated before the entrance's ominous red glow—until Queen Vraska muttered, "Screw it," and marched through the arched gothic doorway. Master Zarek and Mistress Kaya exchanged a glance and followed, with Teyo and I close behind. Rix Maadi's façade was literally that. Within was no architecture—just a massive natural volcanic cavern. Steam rose from a huge central lava pit and was vented above by natural chimneys that ran all the way to the surface. We were all sweating #emph[a lot] now. Even Teyo, the boy from the desert. He shrugged and said, "It's not the heat; it's the humidity." Stone causeways crisscrossed the lava pit. Steel cables crisscrossed the ceiling, supporting more rusty cages and hooks. Blood-filled basins dotted the landscape. So did dozing hellhounds, including Hekara's favorite, Whipsaw. #emph[I wonder if she mourns her mistress, too.] The walls were pockmarked with dozens of doors leading to dozens of chambers. Laughter emanated from some. Screams from others. Both from many. To our left, at ground level, a large aperture in the wall was shrouded by a supernatural mist of pure shadow. A foul breeze wafted forth from within. I'd been here many times before, but it still gave me the shivers. I slid up to Mist<NAME> and whispered, "Where is everybody? <NAME> is usually packed with performers. I've never seen it so empty." She looked through the red-tinged gloom. Except for the hellhounds, and the occasional scurrying (actual) rat, there wasn't a soul around, living or dead, except the five of us. Then, as if on cue, a startling figure appeared in a burst of red smoke. "<NAME>," I whispered. "Blood witch. She's the Defiler's current number two." As the smoke slowly cleared, <NAME> came into focus. She was a tall, muscular human, wearing an immense and elaborate mask decorated with two sets of genuine demon horns. A tight bodice accentuated her large chest and bare midriff. She wore thigh-high boots and a wide belt from which hung numerous iron spikes, all bloodstained. She stood upon a small stage and stared down at my four companions with imperious contempt. She never had been able to see me. #emph[I never liked her very much.] Mistress Kaya, <NAME>, and Queen Vraska looked at one another and then bowed their heads in unison. Master Zarek spoke the formalities: "We honor you, Exava, as a blood witch of rare talent, and we beg an audience with your master, the Defiler." Dame Exava studied them in silence. Then she looked toward the pit. Lava bubbled, but nothing else appeared, including the demon. "Apparently," she said in a rich contralto, "the Defiler begs no audience from you." But in that moment, Rakdos's booming voice echoed throughout the entire cavern: "#emph[WHERE IS OUR EMISSARY?] " #figure(image("005_Operation Desperation/02.jpg", width: 100%), caption: [Rakdos, the Showstopper | Art by: <NAME>], supplement: none, numbering: none) Master Zarek glared at Queen Vraska, who stepped forward, ready to take whatever was coming to her. But before she could speak, a voice called out, "She is here!" #emph[What?! Really?! Hekara?!] I turned toward the main entrance. It was <NAME>, leading a single Orzhov thrull, which carried a covered corpse. #emph[No. No, no, no, no, no] #emph[ . . .] #emph[ Why would you do that to me?] Mister Vrona signaled the thrull, which stopped. He uncovered the corpse's face, Hekara's face. He said, "I have brought Hekara back to her people." I scurried over to Hekara's side. The thrull was tall, and I had to stand on tiptoe to see my friend and kiss her pale cheek. It was real now. I honestly couldn't tell you whether that made it better or worse. Dame Exava cleared her throat impatiently. She said, "Have your creature place the razorwitch on the stage at my feet." Mister Vrona gestured, and the thrull complied. I followed. Dame Exava knelt beside Hekara and jerked her shroud away. Exava flung it into the air, and it burst in flames dramatically—#emph[overdramatically] . Its ashes rained down on us all. The blood witch ran a hand from the top of Hekara's head all the way down to the tips of her painted toes in a disturbing, almost erotic, caress. She said, "You should have brought her back sooner." "Apologies," Mister Vrona said with a bow. "Things have been a bit chaotic up on the surface." "That is #emph[not ] the Cult's concern." "But it should be," <NAME>k stated. Dame Exava rose, snapping her fingers dismissively. Within seconds, six more blood witches appeared in six more puffs of red smoke. They came prepared and quickly stripped Hekara naked and then adorned her in rags and bells. When the process was completed, Dame Exava said, "Have your thrull take Hekara into the Jester's Crypt." She pointed a long elegant finger toward the noxious aperture. Mister Vrona made two more hand gestures, and the thrull took up Hekara. I suppose I should've warned him. But for some reason, I didn't. Flanked by a procession of the six witches, the thrull trod dully through the aperture with Hekara in his arms. Belatedly, I said to no one in particular, "I hope Mister Vrona didn't like that thrull. He won't see him again." And again on cue, my companions froze at the sound of the thrull's death-scream. Mister Vrona looked horrified. All I could muster up was a shrug. Dame Exava said, "I will return shortly. Stay here." She then burst into flame, much as Hekara's shroud had. Ashes rained down again, but none of us actually thought the blood witch had burned. My thoughts were with Hekara. I'd never seen her face before when she wasn't smiling. Even when performing tragedy, her eyes smiled. No more. No smile in her eyes. No smile on her lips. No kind words exchanged between friends. "#emph[You're my Rat.] " "#emph[I'm your Rat.] " All gone. Forever. Mister Vrona was telling <NAME>, "You have had your duties; I have had my own." Master Zarek eyed him. "Which are what exactly?" Mister Vrona looked right at Mistress Kaya: "I am executive assistant to the #emph[true ] guildmaster of the Orzhov. For years, I believed that to be <NAME>. Now I know it is Kaya. And so I have been about the business of serving my mistress." Kaya smiled and thanked him. Then the epiphany hit: "Tomik, #emph[you're ] the one who actually rallied the Orzhov troops into battle." "That was mostly the giant Bilagru. You made a good impression on him." "After you sent him to me and primed the pump." Mister Vrona tilted his left hand as if to say, #emph[Such is my duty.] Just then, Dame Exava emerged from the Jester's Crypt, her hands absolutely dripping with thrull blood. Once again, Queen Vraska stepped forward, saying, "Great and talented Exava, Ravnica requires your aid. If Hekara were alive, she'd urge you to help us convince your master—" Dame Exava interrupted, "#emph[Emissary] Hekara died because she placed her trust in you three." She pointed from the queen to Master Zarek to Mistress Kaya. "One of you betrayed her, one of you denied her, and one of you simply failed her." "All true," Master Zarek said with evident remorse—but not little determination. "And there are no guarantees now, save this: if the ten guilds do not unite, Ravnica is surely doomed." "Then the Cult of Rakdos will dance on Ravnica's grave. We're quite good at grave dancing. It's a specialty." "I'm sure you are, and I'm sure it is," Master Zarek countered. "But the dead can't dance." "You'd be surprised." "Please, listen. Niv-Mizzet left us one last plan to defeat <NAME>. If you allow me to explain—" "#emph[WE ALREADY KNOW EVERY DETAIL OF THE LATE FIREMIND'S LATEST GRASP AT POWER] ," echoed Rakdos's voice. "#emph[WE'LL HAVE NONE OF IT!] " D<NAME> smiled dangerously. "I think you should go," she said. "But—" "Before you #emph[really] piss him off." Master Zarek, Mister Vrona, Queen Vraska, and Mistress Kaya all looked inward, studying to see if there was anything they could do or say that might make a difference. But in the end, their shoulders all collectively sank, and they turned to go. Teyo turned to me and asked, "That's it? We're giving up?" But I wasn't really listening. I smelled something or heard something or sensed #emph[someone] ~I was staring at the opening of the Jester's Crypt. Somebody behind me gasped. "What's your hurry, partners?" Hekara said, emerging from the shadowy space. I should have run to her and thrown my arms around her. But I just stood there, afraid to hope that what I was seeing was real, you know? "Hekara?" Master Zarek said. "Well, yeah," she replied with a shrug. "Weren't you dead?" Queen Vraska said. "Well, sure. Miss me?" "More than you can know~my friend," <NAME> said. "Stop it," Hekara said. "You'll embarrass me. #emph[Just kidding!] I never get embarrassed. Be as mushy as you want. It's horrible theater but we all have our guilty pleasures, right?" Queen Vraska said, "I owe you an apology, Hekara. I never should have betrayed your trust." "It was a pretty crappy thing to do. And dying sucked. But hey, it all worked out. After all, you can't be resurrected as a blood witch if you don't die first, right?" I think I was crying. I dunno. I didn't care, either. "You're a blood witch now?" I asked with some awe. But Master Zarek couldn't hear me and spoke right over me, asking his own question: "Can you convince Rakdos to join Operation Desperation?" "Ooh, good title," Hekara said, "Anyway, don't sweat it. I'll represent the Cult in whatever you got planned, mate." "No, you will not," Dame Exava boomed. "The Defiler has made his wishes clear." "Really? 'Cuz he hasn't said one word to me." "At the time, you were dead and thus a somewhat inattentive audience." "He could set me straight now." "There's no need," Dame Exava said. "#emph[I'm ] doing that." But #emph[Dame ] Hekara just wagged her finger at Exava. "But you're not the Boss. Not the boss of me, anyway. You're just a blood witch. And since I'm a blood witch now, too, I'm thinking I don't need to follow your orders. You don't outrank me anymore, Exava. You just kinda side-rank me." "Witch, I'll kill you all over again!" Dame Exava leapt, her bloody hands reaching for Hekara's throat. Hekara cartwheeled away. The cartwheel morphed into a somersault, which morphed into a backflip. Hekara landed on the stage, and I #emph[applauded] ! Once she had the high ground, Hekara materialized multiple razors in both hands and threw them all simultaneously. "Once a razorwitch, always a razorwitch!" #figure(image("005_Operation Desperation/03.jpg", width: 100%), caption: [Blade Juggler | Art by: <NAME>], supplement: none, numbering: none) Dame Exava was caught unprepared. She parried most of the blades with a wave of her hand, but more than one pierced her skin. It hardly slowed her down, but Hekara wasn't exactly in this fight alone. <NAME>k fired up his Accumulator and fired off a relatively small bolt that caught Exava from behind. She screamed and dropped to her knees. A hellhound reacted, but Hekara intercepted her, saying, "Stop it, Whipsaw. Sit!" Whipsaw stopped but did not sit. She growled menacingly, her mouth dripping acidic saliva that sizzled when it hit the ground. Master Zarek recharged, ready to fry the beast. Hekara waved him off but didn't even bother to look his way. She just kept speaking soothingly to Whipsaw: "Don't mind Ral. He's okay. And Exava will be her old diva self in no time. Now sit!" Whipsaw sat. Hekara called out to the still-absent Rakdos, "I'm going to help my mates now. You don't mind, do you, Boss?" The Defiler remained silent. "Okay, then," Hekara said with a laugh. "Let's get on with it!" Then she walked toward me. I held out my arms for a hug or a spin or any old thing she felt like doing. "#emph[C'mere, baby-cakes, gimme some sugar.] " "#emph[I'm your Rat.] " "#emph[You're my Rat.] " None of that happened. She walked right past me—without noticing me at all. I~I was stunned. I looked up and saw Teyo and Mistress Kaya gaping at me with pity. Then I looked away. But we all knew. Instantly. Whatever process had brought Hekara back to life had changed her enough so that she could no longer see me. #emph[I just lost her all over again] ~ But what difference did that make now? We had set out to bring four wayward guilds back into the fold. Zero to go. Four down. And this last one took me with it. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[III.]] I guess at some point I #emph[must ] have resumed breathing. I mean, she was alive, right? That's what really mattered. #emph[I] had lost her, but at least she was back, you know? #emph[There are worse things than finding out that someone you love is still in your world] ~#emph[even if you're no longer in hers.] I walked right beside her the whole way to the plaza. Teyo said, "Do you want me to say something to her?" Mistress Kaya said, "Stop torturing yourself." I pretended I couldn't hear them. I just decided to, I dunno, #emph[bask] in Hekara's presence for a bit. And at some point, I must have resumed breathing. A part of me probably thought she'd see me again. #emph[Just give it time] ~ But a part of me knew better. She was a blood witch now. She was <NAME>. And I was still just an insignificant Rat. She didn't look at me. She didn't want to see something like me. She was too far above me now. Plus, they had done something to bring her back. Changed her a little. But that was all right. She teased Master Zarek and Queen Vraska the whole way to our destination. So they hadn't changed her all that much. And at least I still got to see her. Once I dried my eyes. So, yeah. I must have resumed breathing again. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #align(center)[#strong[IV.]] We waited, as one by one (or occasionally two by two) everyone made their stealthy arrival among the ruins of the former Embassy of the Guildpact—working very hard to gather without attracting the notice of the creepies or Miss Raven-Hair. I smiled at Teyo. I could tell he was still concerned for me, so I changed the subject: "Don't worry. I'll explain everything that happens as we go." He said, "I think I've got the gist of it all by now." "Yeah, but you don't know most of the players." He started to say something, paused and then said, "Thank you, Araithia. That would be very helpful. And I expect~very entertaining." "You just love to hear me babble." He blushed then. Which made me blush. So I punched him on the arm. "Ow." "That didn't hurt." "Don't I get to be the judge of that?" "No, you big baby." "I'm still older than you." "Not very." "No. Not very." "I win." I felt like kissing him, which was very strange. So I punched him again. "Ow." Everyone was assembling, so I began. "Operation Desperation, the Firemind's final plan requires all ten guilds, the leylines of Ravnica, the charred bones of Niv-Mizzet, and that thing." I was pointing to a brass model of a dragon head—Master Niv-Mizzet's head, to be specific—being carried forward by Chief Chemister Varryvort, an Izzet goblin. "It's called the Firemind's Vessel and will contain his spirit when summoned from wherever it's currently residing—assuming this works, that is, and given the name of the plan that could easily be too much to assume, you know?" Chief Varryvort gently placed the Vessel atop Master Niv-Mizzet's blackened bones. "See, Plan A had been to give Master Niv-Mizzet the power to fight Bolas. That didn't work out, and you can see the end result. Plan B—as in Beacon—failed, too. This is Plan C, I think. Unless I've lost count. "So over there, Master Zarek's consulting with <NAME>. <NAME> says she's some kind of expert on leylines. Has a magical connection to them. So Master Zarek's explaining what they need to accomplish." Master Zarek and Miss Revane were speaking too quietly for either of us to make out the words. But when Master Zarek fell silent, I did, as well. Miss Revane then proceeded to study the problem for . . . #emph[ever] . She remained completely motionless the whole time, resembling a painted statue more than a living being. While we watched her, Chief Varryvort came over to stand beside Teyo, I guess to get out of the way. Not seeing me, he was about to step on me, but I just sidestepped over to Teyo's other side. Finally, Miss Revane nodded, saying, "It might be possible. The leylines were disrupted by the Planar Bridge, but with the Bridge gone, I believe I can repair them and help Ravnica reassert herself." "Well, that's promising, at least," I said. "Now all we have to do is wait for the rest of the guild representatives to gather." Master Zarek, Mistress Kaya, and Queen Vraska were already present, as was Hekara, of course. M<NAME> arrived next. It seems Master D<NAME> had fled Ravnica, and #emph[Mistress ] Lavinia was now acting guildmaster of the Azorius Senate. #figure(image("005_Operation Desperation/04.jpg", width: 100%), caption: [Lavinia, Azorius Renegade | Art by: <NAME>], supplement: none, numbering: none) An impatient Hekara was cartwheeling around the decimated chamber, bells tinkling from leather ribbons on her new costume. I sighed out, "She's so cool!' Then she cartwheeled right past me. #emph[But that's fine, right? It's fine!] Borborygmos arrived next with my parents. Ari smiled at me and pointed me out to <NAME> and the cyclops. Both squinted at the space next to Teyo until they could see me. It made me feel a little better, and I said to Teyo, "My mom's pretty cool, too." <NAME>, champion of the Selesnyan Conclave, arrived with my godfather, Boruvo, who exchanged a few dangerous-sounding growls with his former Gruul clanmates—particularly my mother, who regarded him as a traitor for having switched guilds. I wondered if that's why I was still Gateless. Was it 'cuz I knew I didn't fit in Gruul—but didn't want to risk losing her by picking a different guild? #emph[Krokt knows I can't afford to lose anyone else.] And, who knows? I might fit just fine in Gruul. Hard to say. I noticed Teyo bracing himself, ready to create a shield to prevent a fight. But there wasn't gonna be any fight. I gave them all a stern look and said, "Can't we all just get along?" The four of them all nodded without too much reluctance. Next came Prime Speaker Vannifar of the Simic Combine, accompanied by <NAME>. Then Mistress Aurelia, guildmaster of the Boros Legion, flew in, still hot from battle. Only when all the others had shown their faces did Guildmaster Lazav of House Dimir reveal that he had been there all along—right beside Teyo and I—by morphing out of the form of Chief Varryvort. "Damnit, Lazav!" <NAME> said in a clipped and dangerous voice. "What the hell have you done with the real Varryvort?" <NAME> "reassured" <NAME> in a lazy drawl, "Your accomplished chief chemister is sleeping one off. He'll be just fine come morning—assuming this succeeds, and #emph[any] of us are just fine come morning." I noticed <NAME> was looking uncomfortable, so I nudged Teyo with my elbow. He stared at me, confused. "Help the elf," I whispered. He nodded and stepped forward, saying, "If everyone would just gather around <NAME>." Mistress Kaya approached, and M<NAME> silently indicated where she needed the Orzhov guildmaster to stand. The process was repeated in turn with Hekara, Master Zarek, Mistress Lavinia, Master Lazav, Mistress Aurelia, Borborygmos, Prime Speaker Vannifar, Queen Vraska, and <NAME>. There was some (rather silly) grousing—and considerable mistrust among them all, with Mistress Lavinia and Queen Vraska very nearly butting heads when Miss Revane placed them next to each other. But Miss Revane finally chose to speak, declaring, "Let me make this clear: without a perfect act of unity from every single guild in concert, the plan has no hope of succeeding. You must put all grievances—petty or otherwise—behind you." The act of saying that many words in sequence seemed to visibly exhaust the elf, but they did the trick. Soon enough, the ten guild representatives were standing in a slightly warped circle around <NAME>ane, and the bones and Vessel of the Firemind. The remaining few in attendance—myself, Teyo, <NAME>, <NAME>, Ari, and <NAME>—stood in something of a clump just outside the circle. My mother seemed to be looking Teyo up and down. She frowned a little and shot me a questioning look. Apparently, <NAME> hadn't passed muster as a dependable friend for <NAME>'s daughter. It was kinda mortifying, and besides, I didn't want Teyo's feelings hurt, so I looked away, pretending not to notice. "You stand upon the ancient leylines of the Guildpact," <NAME> said, pulling our attention back to the matter at hand. "Which has exactly what to do with dragon bones?" Mistress Aurelia asked in a decidedly suspicious tone. The elf again looked uncomfortable, and <NAME> took a step forward before quickly stepping back when M<NAME> glared at him in frustration for leaving his designated spot. He said, "We are here to resurrect the Firemind as the new Living Guildpact." Apparently, this was news to about half the guild leaders. <NAME> shouted, "What?" and Mistress Aurelia growled, "That's what this is?" more or less in concert. Borborygmos roared along with them both. Mistress Lavinia grumbled, "Didn't we try this already, when he was alive? What makes you think—" Hekara said, "It's not called Operation Desperation for nothing, you know." Master Zarek held up his hands and said, "We did try, and we failed. But the same terms apply. <NAME> has lost the power of the Living Guildpact. We need that power to defeat <NAME>. If we succeed here, Niv-Mizzet will rise again to that power and use it against the Elder Dragon. Then the Firemind will step down as guildmaster of the Izzet and, as one of Ravnica's most ancient, wise, and venerable paruns, take up his new role as impartial arbiter to all ten guilds and Gateless, alike. The gods know he can hardly do a worse job than Beleren." Mistress Lavinia, Queen Vraska, and <NAME> frowned at that last comment, but the rest simply acknowledge the truth of it and settled down some. Standing on tiptoe, I whispered in Teyo's ear, "I'm glad he acknowledged the Gateless. We're always forgotten when the big mucky-mucks gather to talk guild business." Hekara was practically bouncing up and down, saying, "I've never been part of an all-guild casting. Now I'm kind of glad the Boss didn't want to come himself." Mistress Aurelia shook her head and scoffed, "The demon can't be bothered to save Ravnica, so Rakdos sends one of his minions." I whispered again, "The Boros Legion has always been Rakdos intolerant." Hekara wagged her finger at Mistress Aurelia. "It's not like that at all. The Boss didn't send me in his place. I totally came without his permission." Queen Vraska smirked. "Hekara, if we're being honest, you came in open defiance of his wishes." "Exactly!" This started off another round of grousing and recriminations. <NAME> and Prime Speaker Vannifar turned on Master Zarek, demanding to know how he expected any kind of success when the Cult's eponymous guildmaster and parun wasn't on board. Mistress Aurelia said, "Even attempting this is virtually pointless." After a frustrated look from Master Zarek, Hekara attempted to backpedal her verbal unicycle away from her previous blithe rebelliousness. "Don't get me wrong. The Boss is fully behind this effort." Mistress Aurelia eyed her. "Is he now?" "Oh, yeah, completely. Entirely. Probably." <NAME> stepped in (verbally, that is—he wasn't about to move from his assigned spot and risk another glare from Miss Revane): "We might as well give it a shot. The ceremony will only take~" He trailed off with a questioning look at Miss Revane. "Five minutes at most," she responded. "Assuming it works at all." Mistress Kaya said, "Five minutes? Time is precious, but at five minutes we can't afford #emph[not ] to make the effort." <NAME> looked around the circle. One by one, each of the ten nodded in agreement, some with enthusiasm, some with determination, some with considerable reluctance. But they all nodded nonetheless. Far from looking enthusiastic, determined, or reluctant, a seemingly emotionless M<NAME> said, "Everyone, take a deep breath." Teyo inhaled and exhaled deeply. I giggled. "I think she was only talking to the people in the circle." He blushed deeply. "Oh, look," I said. "You're so cute when you're embarrassed." He blushed deeply-er. "Yeah, like that!" My mother scowled again. I ignored her some more. As Teyo struggled to recover his composure, Miss Revane began chanting—too low for me to hear. From where she stood, beside bones and Vessel, lines began to alight beneath her feet. Black lines. Blue lines. Green lines. Red lines. White lines. Then, suddenly, the lines shot out in multiple directions all at once, forming concentric circles beneath the feet of the ten representatives. Teyo's eyes grew wide, and he studied the lines with fascination. I think they must have appealed to his geometric mind, you know? What interested him was starting to interest me for some reason, so I tried to pay close attention. All the representatives had two colored circles beneath them, and no two combinations were the same. Mistress Kaya, for example, was surrounded by a circle of white and a circle of black. Black lines connected her black circle to identical circles around Queen Vraska, <NAME>, and Hekara. Hekara's second circle was red, which connected her to Borborygmos, Mistress Aurelia, and <NAME>. The latter's second circle was blue, connecting him to Mistress Lavinia, <NAME>, and Prime Speaker Vannifar. The Prime Speaker's second circle was green, connecting her to Borborygmos, Queen Vraska, and <NAME>. Milady's second circle was white, connecting her to Mistresses Lavinia, Aurelia, and Kaya. It was kinda perfect, when you think about it. Anyway, Teyo seemed to really like it. By that time, the ceremony's eleven participants (including <NAME>) had fallen into some kinda trance, sporting eleven blank stares. Suddenly, golden light poured out of twenty-one sightless eyes. #emph[An odd number, 'cuz, you know, Borborygmos is a cyclops and only has one.] Operation Desperation had been activated. A colorless portal—like clear water—opened above the Firemind Vessel, and wispy smoke of blue and red emerged and descended, as if sucked down from portal to Vessel. The bones ignited, bright-yellow and orange flames rising high—and giving off enough light to temporarily blind us watching. We raised our hands to shield our eyes, and, squinting, I saw Miss Revane engulfed in fire. Engulfed but not aflame: the elf didn't scream or writhe or burn. The blaze expanded from bones, Vessel, and elf to encompass the ten guild leaders. And like Miss Revane, they showed no signs of being burned by the fire. Still entranced, they didn't seem to notice it. Unfortunately, something else did. I was the first to spot it, pointing up and shouting over the roar of the fire: "We've got company!" As the light from the fire had gleamed brighter and brighter, it had attracted the attention of one of the God-Eternals. I couldn't remember its name, but it had a kinda bird-shaped head and only one arm. The giant creepy crossed the plaza in tremendous strides and was soon looming over the ruins of the former embassy, peering down on Operation Desperation, still in progress, and all of #emph[us] ! #figure(image("005_Operation Desperation/05.jpg", width: 100%), caption: [God-Eternal Kefnet | Art by: <NAME>], supplement: none, numbering: none) Teyo didn't even think, bless him. As the creepy's single massive fist swung down, Teyo reached up with both hands and manifested a half sphere of light that covered all seventeen of us. When the creepy's fist smashed against it, the shield barely held—and Teyo was rocked, stunned. He sank to his knees and I grabbed him to stop him from falling on his face. "You did it," I whispered. "Keep doing it." He nodded numbly and raised his arms again. Another blow came down. The light shield shattered on impact—but prevented the God-Creepy's fist from making contact with any of us. Teyo groaned and shook his head to clear it. Dazed as he was though, he couldn't seem to summon up a new shield. The next blow would crush us all. But Teyo had bought Miss Revane and the guild leaders the time they needed. The ritual had been completed under his shield. Enough mana had been filtered through the participants to flow through and around the bones and Vessel of the Firemind. The yellow and orange flames had turned to gold and ignited blue and red smoke within the Vessel. The smoke had burned briefly purple before the golden flames overwhelmed all other colors. The blaze seemed to take shape and solidify around the dragon bones, filling them out, turning them from skeleton to living creature. And then <NAME>-Mizzet was reborn, with scales of shiny gold to match the golden glow emanating from his eyes. A decagon was etched—seared, really—into his chest, and magical spheres of black, blue, green, red, and white swirled around him, like five planets orbiting the sun. Still supporting Teyo's weight, I said, "That's different." Teyo couldn't speak. His eyes rolled upward in his head, and I followed their gaze in time to see the God-Creepy's fist barreling down on us. But the new and supposedly improved Firemind spread his wings and launched himself up toward the monster. The dragon's golden wings glowed with a golden light, and his upward arc sheared the God-Creepy's fist off at the wrist. It landed like a boulder ten feet behind us, shaking the ground but doing no further damage. The ibis-headed creepy swung his single, truncated, lazotep-covered limb toward Master Niv-Mizzet, but the dragon easily dodged the blow, flapping his wings once to rise above his foe. Then the Firemind opened his maw wide; his upper and lower incisors scraped against each other, generating a spark, which ignited the dragon's breath. An unending torrent of flame engulfed the God-Eternal, incinerating what remained of its flesh and melting its lazotep coating into a molten rain that dropped ten feet in front of us, sizzling against the ground but doing no further damage. Ari and <NAME> cheered. Mister Vorel growled with obvious satisfaction. Spearmaster Boruvo grunted with the same. I smiled, and I suppose Teyo struggled not to pass out. My mother knelt beside us and, putting a rough hand on Teyo's shoulder, said, "Your boy did well, Araithia." Now it was my turn to blush. "He's not my boy," I said. "He's my friend." "He can see you, and he can protect you." "I don't need protecting." "We all need protecting sometimes. Just don't need it too often." "No, Mother." The eleven were just beginning to come out of their trances. Master Zarek shook his head to clear it and then looked up . . . #emph[just in time to see Master Niv-Mizzet fall.] The dragon crashed down ten feet to the left of us, shaking the ground—and shattering all our hopes. The Firemind lay there, breathing heavily and barely moving. One wing seemed bent beneath his body at an angle so awkward, I had to cringe. <NAME> said, "That's it? Is the great power of the new Living Guildpact already spent from dealing with a single one-armed Eternal?" Master Zarek looked stunned, and everyone else looked stricken, angry, or both. Suddenly, the notion that Master Niv-Mizzet would somehow have the power to defeat <NAME> seemed foolish and, well, #emph[desperate] .
https://github.com/RiccardoTonioloDev/Bachelor-Thesis
https://raw.githubusercontent.com/RiccardoTonioloDev/Bachelor-Thesis/main/config/functions.typ
typst
Other
#let eval_table(benchmarks,n_reference_rows,caption,n_better_lower: 4) = { let best_scores = () let i = 0 while i < n_better_lower { let mins = 99999 let j=0 while j < benchmarks.len() { mins = calc.min(mins,benchmarks.at(j).vals.at(i)) j = j + 1 } best_scores.push(mins) i = i + 1 } i = n_better_lower while i < benchmarks.at(0).vals.len(){ let maxs = 0 let j = 0 while j < benchmarks.len() { maxs = calc.max(maxs,benchmarks.at(j).vals.at(i)) j = j + 1 } best_scores.push(maxs) i = i + 1 } i = 0 while i < benchmarks.at(0).vals.len(){ let j = 0 while j < benchmarks.len() { let tmp = [#benchmarks.at(j).vals.at(i)] if j < n_reference_rows { tmp = underline(tmp) } if benchmarks.at(j).vals.at(i) == best_scores.at(i) { tmp = [*#tmp*] } benchmarks.at(j).vals.at(i) = tmp j = j + 1 } i = i + 1 } let table_array = () i = 0 while i < benchmarks.len(){ let j = 0 table_array.push(benchmarks.at(i).name) while j < benchmarks.at(0).vals.len() { table_array.push([#benchmarks.at(i).vals.at(j)]) j = j + 1 } i = i + 1 } [ #set text(size: 10pt) #figure(table( columns: (118pt, auto, auto,auto,auto,auto,auto,auto), stroke: none, [],table.vline(),table.cell(colspan: n_better_lower)[*Minore è meglio*],table.vline(),table.cell(colspan: benchmarks.at(0).vals.len() - n_better_lower)[*Maggiore è meglio*], table.hline(), [*Fonte*],[*Abs Rel*],[*Sq Rel*],[*RMSE*],[*RMSE log*],[*d1*],[*d2*],[*d3*], table.hline(), ..table_array ),caption: caption) ] } #let ext_eval_table(benchmarks,n_reference_rows,caption,n_better_lower: 6,res: 75pt) = { let best_scores = () let i = 0 while i < n_better_lower { let mins = 999999999999 let j=0 while j < benchmarks.len() { mins = calc.min(mins,benchmarks.at(j).vals.at(i)) j = j + 1 } best_scores.push(mins) i = i + 1 } i = n_better_lower while i < benchmarks.at(0).vals.len(){ let maxs = 0 let j = 0 while j < benchmarks.len() { maxs = calc.max(maxs,benchmarks.at(j).vals.at(i)) j = j + 1 } best_scores.push(maxs) i = i + 1 } i = 0 while i < benchmarks.at(0).vals.len(){ let j = 0 while j < benchmarks.len() { let tmp = [#benchmarks.at(j).vals.at(i)] if j < n_reference_rows { tmp = underline(tmp) } if benchmarks.at(j).vals.at(i) == best_scores.at(i) { tmp = [*#tmp*] } benchmarks.at(j).vals.at(i) = tmp j = j + 1 } i = i + 1 } let table_array = () i = 0 while i < benchmarks.len(){ let j = 0 table_array.push(benchmarks.at(i).name) while j < benchmarks.at(0).vals.len() { table_array.push([#benchmarks.at(i).vals.at(j)]) j = j + 1 } i = i + 1 } [ #set text(size: 10pt) #figure(table( columns: (res, auto,auto,auto, auto,auto,auto,auto,auto,auto), stroke: none, [],table.vline(),table.cell(colspan: n_better_lower)[*Minore è meglio*],table.vline(),table.cell(colspan: benchmarks.at(0).vals.len() - n_better_lower)[*Maggiore è meglio*], table.hline(), [*Fonte*],[*$\#$p*],[*Inf. (s)*],[*Abs Rel*],[*Sq Rel*],[*RMSE*],[*RMSE log*],[*d1*],[*d2*],[*d3*], table.hline(), ..table_array ),caption: caption) ] }
https://github.com/derwind/mathlog-docs
https://raw.githubusercontent.com/derwind/mathlog-docs/main/style/mathlog_style.typ
typst
#let strong_color = red #let def_color = rgb("11508e") #let thm_color = rgb("17b0c4") #let ex_color = rgb("d4bd77") #let exc_color = black #let rem_color = rgb("ffebee") #let prf_color = black #let fml_color = rgb("1e90ff") #let bl_color = rgb("262626") #let conj_color = rgb("343a40") // #show strong: set text(fill: strong_color) #let env(counter, color, title, name, body) = block( stroke: ( paint: color, thickness: 1pt, ), radius: 2pt, inset: 4pt, width: 100%, breakable: true )[ #counter.step() #text(fill: color, weight: "bold")[#name #counter.display()] #if title != none [#text[#title]] #body ] #let def_counter = counter("def") #let def(title: none, body) = env(def_counter, def_color, title, "定義", body) #let thm_counter = counter("thm") #let thm(title: none, body) = env(thm_counter, thm_color, title, "定理", body) #let prop(title: none, body) = env(thm_counter, thm_color, title, "命題", body) #let lem(title: none, body) = env(thm_counter, thm_color, title, "補題", body) #let ex_counter = counter("ex") #let ex(title: none, body) = env(ex_counter, ex_color, title, "例", body) #let exc_counter = counter("exc") #let exc(title: none, body) = env(exc_counter, exc_color, title, "問題", body) #let fml_counter = counter("fml") #let fml(title: none, body) = env(fml_counter, fml_color, title, "公式", body) #let rem(title: none, body) = block( fill: rem_color, radius: 2pt, inset: 4pt, width: 100%, breakable: true )[ #text(fill: strong_color, weight: "bold")[注意] #if title != none [#text[ #title ]] #body ] #let conj(title: none, body) = block( stroke: ( paint: conj_color, thickness: 1pt, ), radius: 2pt, inset: 4pt, width: 100%, breakable: true )[ #text(fill: conj_color, weight: "bold")[予想] #if title != none [#text[ #title ]] #body ] #let bl(title: none, body) = block( stroke: ( paint: bl_color, thickness: 1pt, ), radius: 2pt, inset: 4pt, width: 100%, breakable: true )[ #if title != none [#text[ #title ]] #body ] #let prf(title: none, body) = block( stroke: ( "left": ( paint: prf_color, thickness: 1pt, dash: ("dot", 2pt) ) ), inset: 4pt, breakable: true )[ #text(fill: prf_color, weight: "bold")[証明] #if title != none [#text[ #title ]] #body ]
https://github.com/Quaternijkon/QUAD
https://raw.githubusercontent.com/Quaternijkon/QUAD/main/content.typ
typst
#import "config.typ": * #import "lib.typ": * // #outline(title: none, indent: 2em) // #touying-outline() #outline-slide() = First Section == First Slide #slide[ A slide with a title #alert[and] an *important* #_error[information]. ] == Second Slide #slide[ A slide with a title and an *important* information. ] = Second Section == First Slide #slide[ A slide with a title and an *important* #_tertiary[information]. ] = Third Section == First Slide #slide[ _你用的那个什么软件有问题试试别的svg软件svg应该是设备无关的那个绘图1.svg显然是设备有关的,不同设备渲染的 结果居然不一样有点抽象了_ ] #slide[ _你用的那个什么软件有问题试试别的svg软件svg应该是设备无关的那个绘图1.svg显然是设备有关的,不同设备渲染的 结果居然不一样有点抽象了_ ]
https://github.com/waseemR02/waseemr02-cv
https://raw.githubusercontent.com/waseemR02/waseemr02-cv/typst/resume.typ
typst
MIT License
#import "template/cv.typ": * #let cvdata = yaml("resume.yml") #let uservars = ( headingfont: "Linux Libertine", bodyfont: "Linux Libertine", fontsize: 11pt, // 10pt, 11pt, 12pt linespacing: 6pt, showAddress: true, // true/false show address in contact info showNumber: true, // true/false show phone number in contact info headingsmallcaps: false ) // setrules and showrules can be overridden by re-declaring it here // #let setrules(doc) = { // // add custom document style rules here // // doc // } #let customrules(doc) = { // add custom document style rules here set page( paper: "us-letter", // a4, us-letter numbering: "1 / 1", number-align: center, // left, center, right margin: 1.25cm, // 1.25cm, 1.87cm, 2.5cm ) doc } #let cvinit(doc) = { doc = setrules(uservars, doc) doc = showrules(uservars, doc) doc = customrules(doc) doc } // each section body can be overridden by re-declaring it here #let cvabout(info, isbreakable: true) = { if info.about != none {block(breakable: isbreakable)[ == Introduction #info.about ]} } #let cvcertificates(info, isbreakable: true) = { if info.certificates != none {block[ == Certifications #for cert in info.certificates { // parse ISO date strings into datetime objects let date = utils.strpdate(cert.date) // create a block layout for each certificate entry block(width: 100%, breakable: isbreakable)[ // line 1: certificate name #if cert.url != none [ *#link(cert.url)[#cert.name]* \ ] else [ *#cert.name* \ ] // line 2: issuer and date Issued by #text(style: "italic")[#cert.issuer] #h(1fr) #date \ ] } ]} } #let cvskills(info, isbreakable: true) = { if info.skills != none {block(breakable: isbreakable)[ == Skills #if (info.skills != none) [ #for group in info.skills [ - *#group.category*: #group.skills.join(", ") ] ] ]} } #let cvlangsinterests(info, isbreakable: true) = { if (info.languages != none) or (info.interests != none) {block(breakable: isbreakable)[ == Languages, Interests #if (info.languages != none) [ #let langs = () #for lang in info.languages { langs.push([#lang.language (#lang.fluency)]) } - *Languages*: #langs.join(", ") ] #if (info.interests != none) [ - *Interests*: #info.interests.join(", ") ] ]} } // ========================================================================== // #show: doc => cvinit(doc) #cvheading(cvdata, uservars) #cvabout(cvdata) #cveducation(cvdata) #cvskills(cvdata) #cvwork(cvdata) #cvaffiliations(cvdata) #cvprojects(cvdata) #cvawards(cvdata) #cvcertificates(cvdata) #cvpublications(cvdata) // #cvlangsinterests(cvdata) #cvreferences(cvdata) #endnote()
https://github.com/julius2718/tempura
https://raw.githubusercontent.com/julius2718/tempura/main/0.0.1/example/prez_example.typ
typst
MIT License
#import "@local/tempura:0.0.1": * #import "@preview/polylux:0.3.1": * #import "@local/wareki:1.0.0": * #show: doc => jpprez(doc) #polylux-slide[ #align(horizon + center)[ = tempura: 日本語のTypst テンプレート julius2718 #wareki_today ] ] #polylux-slide[ == 日本国憲法 - 国民の義務 + 勤労の義務 + 納税の義務 + 教育を受けさせる義務 ] #polylux-slide[ == 区分求積法 $ lim_(n -> infinity) 1/n sum_(k = 0)^(n - 1) f(a + (b - a)/n k) = integral_a^b f(x) d x $ - 上の式は、区分求積法を表す。 ] #polylux-slide[ == Universal Declaration of Human Rights - Article 17 + Everyone has the right to own property alone as well as in association with others. + No one shall be arbitrarily deprived of his property. ]
https://github.com/DanielOaks/tme
https://raw.githubusercontent.com/DanielOaks/tme/main/dual-character-sheet.typ
typst
#import "elements.typ": sheet, characterSheetTop, emptyLines, #let title = "Talking Magic Equines 1e Character Sheet" #sheet( title: title, paper: "a4", [ #characterSheetTop() #emptyLines(3) #v(15pt) #characterSheetTop() #emptyLines(3) ] )
https://github.com/Mouwrice/thesis-typst
https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/measurements/measurement_results.typ
typst
#import "../lib.typ": * == Results In this section all the measurement results are listed and discussed. The results go over the effect of the different MediaPipe Pose models (`LITE`, `FULL`, and `HEAVY`) and the accuracy and frame rate that was achieved. All measurements are performed with `GL version: 3.2 (OpenGL ES 3.2 NVIDIA 550.78)` on a ` NVIDIA GeForce RTX 2060` GPU and an `Intel(R) Core(TM) i7-9750H (12) @ 2,60 GHz` CPU, unless specified otherwise. The actual inference is executed on the GPU while the rest of the application just runs on the CPU with minimal overhead. It is the inference that is the most time-consuming element. The results discuss the accuracy and signal stability of the MediaPipe result, as well as some aspects that affect the signal. The accuracy is the deviation from the MediaPipe recordings using the techniques from the previous chapter. The signal stability is the absolute value of the derivates of these deviations. The derivative is numerically computed by taking the difference of two succeeding deviation values. By taking the absolute value, we get a measure of how much the deviation differs per frame and thus how stable the signal is. The lower this value, the better the signal stability. All of these values are taken per frame and per tracked marker. They are then described in box plots with a corresponding table. Indicating the mean, standard deviation, min, max, and some percentiles. Since there is too much data to be included in this thesis text, all measurement results are made publicly available on a GitHub repository. #footnote[Follow this link to the GitHub repository: #link("https://github.com/Mouwrice/DrumPyAnalysis")[Mouwrice/DrumPyAnalysis #link-icon]. All measurement results are located in the `measurements` folder. Every measurement is in a separate folder, with the folder name being a very brief description of the measurement. Inside every measurement folder are the actual results, grouped by the MediaPipe model that was used.] === Results Example To further clarify the results in the coming sections and the way they are presented, consider the following example. It is a measurement of an air drumming recording which has been tracked by both Qualisys and MediaPipe. The MediaPipe `FULL` model has been used, together with the regular `Landmark` marker type. #footnote[The complete results of the example here are from the following measurement: #link("https://github.com/Mouwrice/DrumPyAnalysis/tree/main/data/measurements/maurice_drum_regular/FULL")[https://github.com/Mouwrice/DrumPyAnalysis/tree/main/data/measurements/maurice_drum_regular/FULL #link-icon]] The trajectory of the left wrist marker can be plotted, e.g. the trajectory along the z-axis (vertical axis) in @maurice-drum-regular-left-wrist-full-landmark. The deviations can be plotted in a box plot (@maurice-drum-regular-left-wrist-full-landmark-deviation), as well as the stability of the signal (@maurice-drum-regular-left-wrist-full-landmark-stability). Lastly, the deviation and stability values are also made available by describing them in a tabular format as shown in @drum-regular-dev-table and @drum-regular-sta-table, respectively. The tables are split up per axis and show the mean, standard deviation, min, max, and some percentiles of the deviation and stability values. #figure( caption: [The trajectory along the z-axis (vertical axis) of the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #image("../images/measurements/maurice_drum_regular/Left Wrist_Axis.Z_positions.svg") ] <maurice-drum-regular-left-wrist-full-landmark> #figure( caption: [Per axis deviation of the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none, )[ #image("../images/measurements/maurice_drum_regular/Left Wrist_deviations_seperate.png") ] <maurice-drum-regular-left-wrist-full-landmark-deviation> #figure( caption: [Signal stability of the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #image("../images/measurements/maurice_drum_regular/Left Wrist_signal_stability.png") ] <maurice-drum-regular-left-wrist-full-landmark-stability> #show table.cell.where(x: 0): set text(weight: "bold") #figure( caption: [The deviation of the signal from the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [50.453455],[8.921537],[16.330614], [std], [59.822373], [9.993484], [15.278144], [min], [0.048005], [0.002286], [0.001623], [25%], [16.249777], [2.189822], [7.440695], [50%], [34.482323], [5.407212], [11.327267], [75%], [62.916892], [11.654837], [18.541468], [max], [376.630114], [63.694605], [87.138306] ) ]<drum-regular-dev-table> #show table.cell.where(x: 0): set text(weight: "bold") #figure( caption: [The signal stability from the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Stability (mm)][X][Y][Z], [mean], [ 13.498988], [ 1.621383], [ 2.256355], [std] , [ 14.644994], [ 2.919033], [ 4.950195], [min] , [ 0.000851], [ 0.000011], [ 0.000156], [25%] , [ 3.090311], [ 0.238420], [ 0.163133], [50%] , [ 8.675376], [ 0.552805], [ 0.459906], [75%] , [ 18.577672], [ 1.355008], [ 1.632371], [max] , [111.856248], [27.770244], [52.482742], ) ] <drum-regular-sta-table> === Effect of the models MediaPipe has three different models available, each with a different size. The larger the model, the more accurate it results should be, since the inference model has a larger network that does the inference. Using a larger model negatively impacts the real-time performance, of course. Comparing these different models, we found that the average accuracy does not drastically increase given a large model. The achievable frame rate, however, can drop significantly given these large models, dependent on the hardware used. For each model, 3 results are provided, each result being from one specific recording. The recordings are all drumming motions, but with increasing levels of intensity. The first recording is of small movements (`maurice_drum_small`). The second one features normal movements (`maurice_drum_regular`) and the last one contains fast and big movements (`maurice_drum_fast`). The accuracy is taken from a total of 10 tracked markers, being the `Left Elbow`, `Right Elbow`, `Left Wrist`, `Right Wrist`, `Left Hip`, `Right Hip`, `Left Heel`, `Right Heel`, `Left Foot Index`, `Right Foot Index`. ==== LITE The `LITE` model is 3 MB in size and is the smallest model available. The total deviation of all three recordings are displayed in @mau-drum-small-lite-total, @mau-drum-regular-lite-total, and @mau-drum-fast-lite-total, respectively. We can immediately draw some conclusions from these results. The Y and Z axis (horizontal and vertical) have a relatively good accuracy compared to the X axis (depth). The depth is actually very imprecise and unstable, having a high mean deviation and a high standard deviation makes this depth not very usable. The accuracy of measurements containing fast, and large movements is lower than for smaller and slower movements. This indicates that the wider the range of movements and the speed at which they are performed results in a slight drop in accuracy. Almost all deviation values are slightly higher than their corresponding values from a recording featuring less and slower movement. Despite the X axis being very imprecise, the Y and Z axis consistently achieve an accuracy of minimum 1 centimetre. For an air drumming application, this level of accuracy is already pretty usable. #show table.cell.where(x: 0): set text(weight: "bold") #figure( caption: [The total deviation from the `maurice_drum_small` measurement. Model: `LITE`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 46.216412], [ 6.504117], [ 8.755020], [std ], [ 52.435068], [ 8.534992], [ 9.435842], [min ], [ 0.000424], [ 0.001266], [ 0.000092], [25% ], [ 7.747909], [ 1.523800], [ 2.533034], [50% ], [ 26.830197], [ 3.518769], [ 5.717354], [75% ], [ 65.330929], [ 7.591232], [10.964000], [max ], [304.913545], [91.105333], [69.909789], ) ] <mau-drum-small-lite-total> #figure( caption: [The total deviation from the `maurice_drum_regular` measurement. Model: `LITE`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 44.065230], [ 6.498654], [ 10.911481], [std ], [ 55.829339], [ 7.804492], [ 12.150179], [min ], [ 0.000830], [ 0.000079], [ 0.000673], [25% ], [ 8.900595], [ 2.055750], [ 3.500705], [50% ], [ 24.601205], [ 4.378533], [ 7.580231], [75% ], [ 57.471564], [ 8.009390], [ 13.549875], [max ], [460.941039], [164.103709], [140.990013], ) ] <mau-drum-regular-lite-total> #figure( caption: [The total deviation from the `maurice_drum_fast` measurement. Model: `LITE`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 64.872857], [ 7.181918], [ 10.046277], [std ], [ 70.935324], [ 9.058099], [ 14.284985], [min ], [ 0.006952], [ 0.000276], [ 0.000796], [25% ], [ 9.690526], [ 2.168622], [ 2.386345], [50% ], [ 31.462373], [ 4.908393], [ 5.571245], [75% ], [113.099430], [ 8.903545], [ 12.760656], [max ], [680.599720], [226.170262], [592.765323], ) ] <mau-drum-fast-lite-total> ==== FULL The `FULL` models is double the size of the `LITE` model, at 6 MB. But that does not mean the deviation is halved. Compared to the `LITE` model, the average accuracy is increased by 1 and at most 2 mm. The standard deviation is reduced a bit using this heavier model. Some outlier values are also reduced. This indicates that the `FULL` model provides a cleaner result but only with a marginal increase in accuracy. #figure( caption: [The total deviation from the `maurice_drum_small` measurement. Model: `FULL`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 40.883051], [ 5.702290], [ 7.874736], [std ], [ 50.636690], [ 6.940303], [ 8.912165], [min ], [ 0.000027], [ 0.000366], [ 0.000008], [25% ], [ 5.576486], [ 1.458272], [ 2.017663], [50% ], [ 19.581533], [ 3.285286], [ 4.814794], [75% ], [ 56.780453], [ 7.264643], [ 9.913902], [max ], [309.870406], [75.601338], [82.893488], ) ] <mau-drum-small-full-total> #figure( caption: [The total deviation from the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 44.054789], [ 5.877316], [10.028784], [std ], [ 52.458578], [ 6.611694], [10.963382], [min ], [ 0.000578], [ 0.000225], [ 0.001258], [25% ], [ 8.880800], [ 1.829242], [ 2.919620], [50% ], [ 24.080457], [ 4.135115], [ 6.481524], [75% ], [ 64.801731], [ 7.475370], [13.322674], [max ], [423.136841], [68.750352], [91.792725], ) ] <mau-drum-regular-full-total> #figure( caption: [The total deviation from the `maurice_drum_fast` measurement. Model: `FULL`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 57.356438], [ 6.444404], [ 9.623760], [std ], [ 71.275673], [ 8.949972], [ 15.462130], [min ], [ 0.002776], [ 0.001176], [ 0.000118], [25% ], [ 5.237184], [ 1.277760], [ 1.798388], [50% ], [ 17.238973], [ 3.093675], [ 4.298769], [75% ], [102.966444], [ 7.503870], [ 11.247950], [max ], [679.421116], [117.911612], [586.803848], ) ] <mau-drum-fast-full-total> ==== HEAVY The `HEAVY` model is the largest of them all at a size of 26 MB. At this level, we have clearly reached a point of diminishing returns. Despite increasing the model size by a factor of 4, the improvements are not a big jump up. The jump in accuracy from `FULL` to `HEAVY` is similar to the jump from `LIGHT` to `FULL`, again increasing the accuracy by 1 mm. The X axis also gets an increase in accuracy but proves to still be too unstable and imprecise to be of any use. At this point, the axis lateral to the image frames (Y and Z) are considerably accurate, reaching an average accuracy of 5 and 7 mm respectively. Just as with the smaller models, larger movements lead to a slight drop in accuracy, there is especially an increase in outliers. #figure( caption: [The total deviation from the `maurice_drum_small` measurement. Model: `HEAVY`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 38.662930], [ 4.880106], [ 6.931904], [std ], [ 46.034748], [ 6.095308], [ 7.833226], [min ], [ 0.000757], [ 0.000524], [ 0.000945], [25% ], [ 5.908032], [ 1.228680], [ 1.864810], [50% ], [ 17.719570], [ 2.879538], [ 3.958334], [75% ], [ 61.890476], [ 5.876115], [ 8.929086], [max ], [293.278487], [90.609627], [65.955275], ) ] <mau-drum-small-heavy-total> #figure( caption: [The total deviation from the `maurice_drum_regular` measurement. Model: `HEAVY`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 48.331793], [ 5.311494], [ 9.191098], [std ], [ 66.957378], [ 6.810102], [10.310719], [min ], [ 0.006057], [ 0.000938], [ 0.000114], [25% ], [ 9.469759], [ 1.529734], [ 2.387941], [50% ], [ 25.329217], [ 3.363876], [ 5.430044], [75% ], [ 61.941299], [ 6.533454], [12.837094], [max ], [622.943655], [67.798017], [90.548038], ) ] <mau-drum-regular-heavy-total> #figure( caption: [The total deviation from the `maurice_drum_fast` measurement. Model: `HEAVY`, Marker type: `Landmark`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Deviation (mm)][X][Y][Z], [mean], [ 61.698936], [ 5.610732], [ 7.894003], [std ], [ 69.377889], [ 7.535471], [ 12.391467], [min ], [ 0.007052], [ 0.000091], [ 0.000255], [25% ], [ 7.327052], [ 1.214547], [ 1.887956], [50% ], [ 25.502218], [ 2.906578], [ 4.056903], [75% ], [112.404883], [ 7.307336], [ 9.338038], [max ], [678.986135], [121.335236], [587.988858], ) ] <mau-drum-fast-heavy-total> ==== Signal stability One metric that has been left out, so far, is the signal stability. The deviation tables above hint that a heavier model might not just provide a small increase in accuracy, but also provide an increase in signal stability. This is hinted at by the lower standard deviation and the lower 75% percentile values. Having a more stable signal, meaning less outliers and a more consistent deviation difference between frames, is also an important aspect. The following tables plot the signal stability for every model on the `maurice_drum_regular` measurement. Remember that the signal stability is calculated as the absolute difference in deviation between consecutive frames, the lower the values the better. #figure( caption: [The signal stability from the `maurice_drum_regular` measurement. Model: `LITE`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Stability `LITE` (mm)][X][Y][Z], [mean], [ 7.764771], [ 1.352941], [ 2.096501], [std ], [ 10.085330], [ 2.809363], [ 4.220660], [min ], [ 0.000014], [ 0.000023], [ 0.000073], [25% ], [ 1.026297], [ 0.208817], [ 0.217875], [50% ], [ 3.969899], [ 0.595858], [ 0.739438], [75% ], [ 10.707028], [ 1.440624], [ 2.116421], [max ], [118.670178], [116.634008], [107.199950], ) ] <drum-regular-lite-sta-table> #figure( caption: [The signal stability from the `maurice_drum_regular` measurement. Model: `FULL`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Stability `FULL` (mm)][X][Y][Z], [mean], [ 7.579568], [ 1.106332], [ 1.694458], [std ], [ 10.574589], [ 2.057231], [ 3.608910], [min ], [ 0.000109], [ 0.000078], [ 0.000012], [25% ], [ 0.752476], [ 0.165129], [ 0.176408], [50% ], [ 3.633556], [ 0.468424], [ 0.560157], [75% ], [ 10.260663], [ 1.137847], [ 1.569148], [max ], [112.231639], [46.151331], [52.179156], ) ] <drum-regular-full-sta-table> #figure( caption: [The signal stability from the `maurice_drum_regular` measurement. Model: `HEAVY`, Marker type: `Landmark`, Marker: `Left Wrist`.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Stability `HEAVY` (mm)][X][Y][Z], [mean], [ 6.122471], [ 0.979171], [ 1.511921], [std ], [ 8.788107], [ 1.873792], [ 3.426255], [min ], [ 0.000077], [ 0.000090], [ 0.000053], [25% ], [ 0.736543], [ 0.133611], [ 0.139911], [50% ], [ 2.849786], [ 0.392975], [ 0.450573], [75% ], [ 8.104202], [ 0.981124], [ 1.274915], [max ], [108.713253], [40.173077], [51.322185], ) ] <drum-regular-heavy-sta-table> @drum-regular-lite-sta-table, @drum-regular-full-sta-table and @drum-regular-heavy-sta-table clearly demonstrate that a larger model not only increases accuracy but also the signal stability. The effect is modest, with the most significant difference being the values going from the `LITE` model to the `FULL` model. This effect is also noticeable when viewing the inference visualization, where we can see that the `FULL` model provides a more stable result. The markers are less jittery and their movements are 'smoother'. ==== Conclusion Now that we have compared the accuracy of all three models, we have a clear view of the expected accuracy. For any lateral movement, that is movement lateral to the image frame, the horizontal and vertical axis, an accuracy of 5-10 mm can be achieved with some deviations from that accuracy of at most 1 centimetre. There is however also the possibility for some jitter to occur in the resulting signal which can some major deviations from the actual movement, but these are only of short duration. The depth axis, the X axis, is considerably less accurate. The accuracy is around 40-60 mm, with some deviations of up to 100 mm. The depth is as mentioned _"obtained via the GHUM model fitted to 2D point projections."_ Unfortunately, this depth is not very usable for an air drumming application. The depth is also very unstable, with a high standard deviation and a high number of outliers. This is especially the case when the movements are fast and large. Comparing the models, there is little accuracy to be gained from choosing a larger model. However, larger models provide a more stable signal, which can be essential as the drumming application mostly looks at the relative movements instead of absolute values. As we are developing an application to be used live, the largest model that can achieve real-time inference is preferred. The inference time is of course dependent on the hardware, which means that in some cases the `HEAVY` model can be used but in other cases the `LITE` model is the only one that can be properly run in real-time, @inference-time. === Achievable framerate <inference-time> The frame rate that can be achieved should be high enough for a proper real-time application. The higher the frame rate, the more responsive the application will feel and the more accurate the tracking can be. A higher frame rate also allows for faster motions to be captured, which is handy in the case of fast drumming motions. The frame rate is dependent on the hardware used, but also on the model that is used. The larger the model, the more computationally expensive it is to run the inference. The following table (@framerate-table) lists the maximum frame rate that was achieved for each model, as well as the device that was used to run the inference. #figure( caption: [The maximum frame rate (fps) that can be achieved for each model with different devices.], placement: none )[ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[Device (fps)][`LITE`][`FULL`][`HEAVY`], [CPU Intel Core i7-10750H], [25], [20], [7], [GPU Intel UHD Graphics 630], [19], [17], [11], [CPU AMD Ryzen 5 5600X], [40], [30], [10], [GPU NVIDIA RTX 2060], [45], [42], [40], ) ] <framerate-table> The table shows that the `LITE` model can be run in real-time on all devices. The `FULL` model can also be run in real-time on most devices, but the `HEAVY` model is too computationally expensive to run in real-time on most devices. The `HEAVY` model can only be run in real-time on the NVIDIA RTX 2060 GPU. It is no surprise that the GPU is the most performant of the four devices. However, despite being able to run the `HEAVY` model at a constant 40 fps, the GPU's performance on the smaller models is surprisingly not a lot higher. We can conclude that the GPU has a lot of power but lacks the speed of a CPU #footnote[A CPU typically has a higher clock speed than a GPU, allowing to perform many more consecutive operations per second. A GPU is mainly designed to perform many operations simultaneously. ], hence the good results for the `HEAVY` model and the not much improved results for the smaller models. This difference between power and speed also becomes apparent when comparing the Intel Core i7-10750H and the AMD Ryzen 5 5600X. The AMD Ryzen 5 5600X has a higher clock speed and can run the `FULL` model at 30 fps, while the Intel Core i7-10750H can only run the `FULL` model at 20 fps. The `HEAVY` model is too computationally expensive for both devices. On the `LITE` model, however, they are on par with the GPU's. The Intel Core i7-10750H can run the `LITE` model at 25 fps, while the AMD Ryzen 5 5600X can run the `LITE` model at 40 fps. The Intel UHD Graphics 630 and the NVIDIA GeForce 2060 GPU can run the `LITE` model at 19 and 45 fps respectively. The conclusion is that the `FULL` model is the best model to use for real-time applications. It provides a good balance between accuracy and frame rate. The `HEAVY` model is too computationally expensive to run in real-time on most devices, while the `LITE` model is somewhat unstable to rely on. The `FULL` model can be run in real-time on most (modern) devices, providing a good balance between accuracy and frame rate. If the device is not powerful enough to run the `FULL` model in real-time, the `LITE` model can be used as a fallback. === Jitter One aspect that leads to a less stable signal is jitter. Jitter is the sudden, unintended variation in the position of a tracked marker. In the recordings, we see that this jitter mostly occurs when the tracked body part is either fast-moving or occluded in any way. This is mostly present when crossing arms in our recordings. As shown in @jitter-example-right-wrist, the jitter is clearly visible around the 20-second mark. This jitter is not present in all recordings, but is a factor that can lead to a less stable signal. Jitter occurs less frequently in the larger models, which partly explains the increased signal stability using these models. When developing an application that relies on the stability of the signal, it is important to acknowledge that jitter can occur and that it can lead to a less stable signal. #figure( caption: [A case of jitter in the `maurice_drum_fast` measurement around the 20 seconds mark. Model: `LITE`, Marker type: `Landmark`, Marker: `Right Wrist`.], placement: none, )[ #image("../images/measurements/maurice_drum_fast/LITE/Right_Wrist_y.svg") ] <jitter-example-right-wrist> === Noise Another aspect that can lead to a less stable signal is noise. Noise is the random variation in the position of a tracked marker. This noise is mostly present when the tracked body part is not moving at all. It can be seen in the trajectories that larger models produce a less noisy signal than smaller models. This is shown in @noise-example-right-heel. The noise is clearly visible in the `LITE` model, while the `FULL` and `HEAVY` models have a much more stable signal. It should be noted that the noise is rather small and is still in line with the accuracy values that were discussed earlier. The signal stability tables also clearly show that the noise is present in the `LITE` model but is reduced in the `FULL` and `HEAVY` models. (@noise-example-right-heel-stability) #show table.cell.where(x: 0): set text(weight: "bold") #figure( caption: [The signal stability from a noisy signal in the the `maurice_drum_regular` measurement. Models: `LITE`, `FULL`, `HEAVY`. Marker type: `Landmark`. Marker: `Right Heel`.], placement: auto, grid( columns: (auto), rows: (auto, auto, auto), gutter: 1em, [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`LITE` Stability][X][Y][Z], [mean], [8.537066], [1.053139], [2.158305], [std ], [8.288110], [1.261807], [2.967522], ) ], [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`FULL` Stability][X][Y][Z], [mean], [6.025950], [0.589802], [1.300819], [std ], [8.030914], [0.914598], [2.288527], ) ], [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`HEAVY` Stability][X][Y][Z], [mean], [5.830511], [0.441127], [1.026949], [std ], [6.083284], [0.685263], [1.925742], ) ], ) ) <noise-example-right-heel-stability> #figure( placement: auto, grid( columns: (auto, auto), rows: (auto, auto), [#image("../images/measurements/maurice_drum_regular/LITE/Right_Wrist_y.svg") ], [#image("../images/measurements/maurice_drum_regular/FULL/Right_Wrist_y.svg") ], [#image("../images/measurements/maurice_drum_regular/HEAVY/Right_Wrist_y.svg") ] ), caption: [A noisy signal in the `maurice_drum_regular` measurement. Models: `LITE` (top left), `FULL` (top right), `HEAVY` (bottom left). Marker type: `Landmark`. Marker: `Right Heel`.], ) <noise-example-right-heel> === Resolution Following the description of the model network of the MediaPipe Pose Task, we know that the input has a fixed size of 256x256x3. This means that the resolution of the input image is 256x256 pixels. As a result of this fixed input size, we should see no significant difference in accuracy when using different resolutions. There might be a slight difference in the accuracy due to the image being resized to fit the input size, but this difference should be negligible. This hypothesis is tested by comparing the deviation of the `maurice_drum_regular` measurement at different resolutions. The resolutions used are 1080p, 720p, and 480p. #footnote[The original measurement video was also captured in 1080p but was encoded again with the same encoding settings used to achieve the smaller resolution videos, except for the resolution, of course. This was done to make sure that the video quality and encoding are the same. It is also the reason for slightly different results for the 1080p resolution in previous tables, which the very attentive reader might have noticed.] The deviation values are shown in @resolution-deviations. The deviation values are very similar. Thus follows that the resolution of the input image does not significantly affect the accuracy of the model. This is good news, as it means that the model can be used on different devices with different resolutions without a significant loss in accuracy. #figure( caption: [The accuracy of different resolutions of the `maurice_drum_regular` measurement. Model: `FULL`. Marker type: `Landmark`.], placement: auto, grid( columns: (auto), rows: (auto, auto, auto), gutter: 1em, [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`1080p` Deviation (mm)][X][Y][Z], [mean], [40.076227], [10.396079], [12.230394], [std ], [49.000929], [10.724212], [14.250999], ) ], [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`720p` Deviation (mm)][X][Y][Z], [mean], [39.937372], [10.387030], [12.473164], [std ], [48.821626], [10.771447], [14.450003], ) ], [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`480p` Deviation (mm)][X][Y][Z], [mean], [41.670763], [11.361194], [11.975922], [std ], [48.763101], [11.131461], [14.568390], ) ], ) ) <resolution-deviations> === World Landmarks All previous results are from measurements with the `Landmark` as marker type. These are points that have coordinates in the image frame with an added depth value. MediaPipe also provides `WorldLandmarks` as a marker type. These are real-world 3D coordinates. The values are in meters and are relative to the midpoint between the hips. MediaPipe tries to predict the size of the person in the frame and uses this to scale the world landmarks. `WorldLandmarks` allows to decouple the marker locations from the image frame. With them, one can track the movements relative to the person instead of the image frame. This can be useful when the person is moving around in the frame or when the person is moving towards or away from the camera. As this adds another layer of uncertainty (the scale of the person in the frame is but a prediction), the accuracy of the `WorldLandmarks` is expected to be lower than the `Landmarks`. The deviation values for the `WorldLandmarks` are shown in @world-landmarks-deviations. The deviation values are indeed higher than the deviation values for the `Landmarks` by a value of 2 to 5 mm. #footnote[Note that the depth values are somewhat improved with the `WorldLandmarks` marker type. This is attributed to a better scaling factor than the somewhat arbitrary scaling factor of 0.5 that was chosen in the X axis alignment. The depth values are still as inaccurate as before, but the entire scaling of the depth axis is just a bit better. The `WorldLandmark` depth axis scale would still converge to zero if the Golden-section search method is applied.] The same can be observed for the signal stability in @world-landmarks-stability. For the most accuracy, the regular `Landmarks` should be used. However, if the application requires tracking movements that are relative to the person instead of the image frame, then the `WorldLandmarks` need to be used. One might also opt for a combination of both, as MediaPipe always outputs both types of landmarks. #figure( caption: [The accuracy of `WorldLandmarks` compared to the accuracy of `Landmarks`. Model: `FULL`. Measurement: `maurice_drum_regular`.], placement: none, grid( columns: (auto), rows: (auto, auto, auto), gutter: 1em, [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`Landmark` Deviation (mm)][X][Y][Z], [mean], [ 44.054789], [ 5.877316], [10.028784], [std ], [ 52.458578], [ 6.611694], [10.963382], [min ], [ 0.000578], [ 0.000225], [ 0.001258], [25% ], [ 8.880800], [ 1.829242], [ 2.919620], [50% ], [ 24.080457], [ 4.135115], [ 6.481524], [75% ], [ 64.801731], [ 7.475370], [13.322674], [max ], [423.136841], [68.750352], [91.792725], ) ], [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`WorldLandmark` Deviation (mm)][X][Y][Z], [mean], [ 40.064675], [10.425273], [ 12.136874], [std ], [ 49.167113], [10.624388], [ 13.952320], [min ], [ 0.003811], [ 0.000245], [ 0.001166], [25% ], [ 7.237019], [ 3.242694], [ 2.720210], [50% ], [ 22.192832], [ 7.156534], [ 7.904396], [75% ], [ 57.645794], [13.916220], [ 16.739466], [max ], [364.849119], [81.609742], [147.278370], ) ], ) ) <world-landmarks-deviations> #figure( caption: [The stability of `WorldLandmarks` compared to the stability of `Landmarks`. Model: `FULL`. Measurement: `maurice_drum_regular`.], placement: none, grid( columns: (auto), rows: (auto, auto, auto), gutter: 1em, [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`Landmark` Stability (mm)][X][Y][Z], [mean], [ 7.579568], [ 1.106332], [ 1.694458], [std ], [ 10.574589], [ 2.057231], [ 3.608910], [min ], [ 0.000109], [ 0.000078], [ 0.000012], [25% ], [ 0.752476], [ 0.165129], [ 0.176408], [50% ], [ 3.633556], [ 0.468424], [ 0.560157], [75% ], [ 10.260663], [ 1.137847], [ 1.569148], [max ], [112.231639], [46.151331], [52.179156], ) ], [ #table( columns: (auto, 2fr, 2fr, 2fr), align: (left, right, right, right), table.header[`WorldLandmark` Stability (mm)][X][Y][Z], [mean], [ 3.967809], [ 1.851960], [ 2.493500], [std ], [ 6.406780], [ 2.779646], [ 4.056749], [min ], [ 0.000046], [ 0.000069], [ 0.000042], [25% ], [ 0.377586], [ 0.276647], [ 0.221359], [50% ], [ 1.447640], [ 0.808166], [ 0.881040], [75% ], [ 4.694866], [ 2.216550], [ 3.038803], [max ], [87.592255], [29.960801], [48.716450], ) ], ) ) <world-landmarks-stability> Apart from the decrease in accuracy, there is also the scale that needs to be considered. The scale of the `WorldLandmarks` is not the same as the scale of the `Landmarks`. The `Landmarks` are in pixels, while the `WorldLandmarks` are in meters. This means that the scale of the `WorldLandmarks` is dependent on the size of the person in the frame. This scale is not always accurate, as it is a prediction. That the scale is not quite accurate is easily proved by applying our alignment method. The Golden-section search returns a scale factor for these `WorldLandmarks` so they would properly align. Two measurements have been compared, with the same camera setup but with two people of different size at the same distance from the camera. The recording of the person with a height of 170cm resulted in the scaling factor of 0.9. This indicates that the person is smaller than the predicted size by MediaPipe. The other recording features a person of 184cm, which resulted in a scaling factor of 1.1. This indicates that the person is larger than the predicted size by MediaPipe. This is a clear indication that the scale of the `WorldLandmarks` is not always accurate and some alignment is needed to get the proper scale. This can also be seen as a advantage, that different people can be tracked with the same model without the need to adjust the model to the person's size. === Depth Issues In all the measurements it is pretty clear that something is wrong with the depth axis. It has a way higher deviation than the other axes and is also more unstable. It does of course make sense that the accuracy and stability differ from the other axes as the depth is inferred via the seperate GHUM model. But how bad is the depth axis actually? A trajectory of the depth from one recording is displayed in @depth-trajectory. It is obvious that the MediaPipe signal (blue) jumps all over the place. However, with some imagination, it can be seen that when there are actually peaks and valleys in the signal, the MediaPipe signal follows the general trend. This is a good sign, as it means that the signal is not completely random. The scale of them is not quite right and inconsistent though. Unfortunately we see that peaks and valleys are also present in the MediaPipe signal when none are present in the actual signal with a scale similar of that of the actual peaks and valleys. This makes it really hard to use the depth signal for any application. If the depth signal was just a bit inaccurate it could still be used to get a general idea of the depth and movement in an application, but with the current signal there is just no way to tell if something is an actual peak or valley or just a random spike in the signal. #figure(caption: [A sample of the inferred depth trajectory. Model: `LITE`, Marker Type: `Landmark`, Marker: `Left Wrist`.], placement: none)[ #image("../images/measurements/maurice_drum_regular/LITE/Left_Wrist_x.svg") ] <depth-trajectory>
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/meeting_minutes/week_04.typ
typst
#import "../../../acronyms.typ": * = Project Meeting 10.10.2023 08:15 - 09:00 (MS Teams) == Participants - Prof. Dr. <NAME> - <NAME> - <NAME> == Agenda - Discussion of function visualization drafts - Input from Advisor: - Include a code scenario with currying - Maybe VisualFP should go in the direction of a visual version of GHCi - Decision: Determine next steps based on designs next week
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ARO/docs/6-Reels/reels.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Réels ], lesson: "ARO", chapter: "6 - Réels", definition: "TBD", col: 1, doc, ) = Codage binaire Le codage crée par <NAME> en 1985 est un standard IEEE 754 qui permet de représenter les nombres réels en virgule flottante. Il est utilisé dans la plupart des ordinateurs et des langages de programmation. == Biais Le biais est une valeur ajoutée à l'exposant pour permettre de représenter des nombres négatifs. Il est égal à $2^{k-1} - 1$ où $k$ est le nombre de bits de l'exposant. = Normalisés / non-normalisés == Normalisés Pour qu'un nombre soit concidéré comme normalisé il doit forcement avoir le bit à gauche du point décimal égal à 1. == Non-normalisés Pour qu'un nombre soit concidéré comme non-normalisé il doit forcement avoir le bit à gauche du point décimal égal à 0. = Standard IEEE 754 (virgule flottante) == Binary8 (quarter precision) - nombre de bits : 8 - exposant sur 4 bits - mantisse sur 3 bits - biais : 7 ($2^(4-1) - 1$) == Binary16 (half precision) - nombre de bits : 16 - exposant sur 5 bits - mantisse sur 10 bits - biais : 15 ($2^(5-1) - 1$) == Binary32 (simple precision) - nombre de bits : 32 - exposant sur 8 bits - mantisse sur 23 bits - biais : 127 ($2^(8-1) - 1$) == Binary64 (double precision) - nombre de bits : 64 - exposant sur 11 bits - mantisse sur 52 bits - biais : 1023 ($2^(11-1) - 1$) == Binary128 (quadruple precision or Quad) - nombre de bits : 128 - exposant sur 15 bits - mantisse sur 112 bits - biais : 16383 ($2^(15-1) - 1$)
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20esterna/Verbali/24-03-26/24-03-26.typ
typst
#import "/template.typ": * #show: project.with( date: "26/03/24", subTitle: "Dimostrazione e convalida MVP", docType: "verbale", authors: ( "<NAME>", ), externalParticipants : ( (name: "<NAME>", role: "Referente aziendale"), ), timeStart: "15:00", timeEnd: "15:30", location: "Zoom", ); = Ordine del giorno - Presentazione MVP; - Pianificazione incontri futuri. == Presentazione MVP Sono state presentate al Proponente le diverse funzionalità implementate nel MVP volte a soddisfare i requisiti espressi nel documento #adr_v. La lista dei requisiti soddisfatti è presente nel documento #st\, alla sezione "Requisiti soddisfatti". Il documento è disponibile al seguente link: #align( center, link("https://error418swe.netlify.app/pb/documentazione-esterna/specifica-tecnica/") ) Oltre alle funzionalità già presentate nei precedenti meeting, sono state aggiunte: - posizionamento nei bin di prodotti non collocati; - posizionamento delle zone nel piano agevolata mediante una grid attivabile; - posizionamento automatico della visuale su una zona specificata; - movimento della visuale tramite tastiera durante lo spostamento di una zona o prodotto. Il Proponente è risultato soddisfatto di quanto presentato e ha confermato il corretto soddisfacimento di tutti i requisiti derivati dal capitolato emersi durante lo sviluppo del progetto, sia minimi che desiderabili. Inoltre è stata apprezzata l'attenzione data all'usabilità del prodotto. Il Proponente riconosce il prodotto software del gruppo #err418 come MVP. == Pianificazione incontri futuri A seguito del meeting odierno, gli incontri periodici sono da considerarsi conclusi e il Proponente ha espresso la sua disponibilità per futuri aggiornamenti sul progetto e ad eventuali attività legate alla Customer Acceptance. #pagebreak()
https://github.com/hyskr/touying-bjtu
https://raw.githubusercontent.com/hyskr/touying-bjtu/main/README.md
markdown
MIT License
# Touying Slide Theme for Beijing Jiaotong University 基于 [Touying Slide Theme for Beihang University](https://github.com/Coekjan/touying-buaa) 的修改。 ## 作为 Typst 模板包使用 ```console > cd touying-bjtu > typst watch main.typ ``` ## Examples See [examples](examples) for more details. You can compile the examples by yourself. ```console $ typst compile ./examples/main.typ --root . ``` And the PDF file `./examples/main.pdf` will be generated. ## License Licensed under the [MIT License](LICENSE).
https://github.com/Dherse/typst-brrr
https://raw.githubusercontent.com/Dherse/typst-brrr/master/samples/conformal_prediction/slides.typ
typst
#let NO_STEPS = false #let slide_counter = state("slide_counter", 1) #let slide_inner(n_steps, content) = { if n_steps >= 20 [ // for some bizzare reason we need this in order to not enter an infinite loop ] else [ #slide_counter.update(n_steps) #box(width: 100%, height: 100%)[#content] #pagebreak() #slide_counter.display(x => if x < 1 [#slide_inner(n_steps + 1, content)] else []) ] } #let slide(content) = { if NO_STEPS { slide_inner(19, content) } else { slide_inner(1, content) } } #let step(rest) = { slide_counter.update(k => k - 1) slide_counter.display(x => [ // #place([#text(fill: orange)[#x]]) #if x > 0 { rest } else { hide(rest) } ]) } #let steplist(list, spread: true, start: 1) = [ #let i = 0 #if spread [ #v(1fr) ] #for item in list.children.filter(x => x != [ ]) [ #if i >= start [ #show: step #item ] else [ #item ] #if spread [ #v(1fr) ] #{ i += 1 } ] // #columns(2)[#text(size: 8pt)[#repr(list.children)]] ] #let slide_deck(doc, page_format: "16-9", margin: 2em) = [ #set page("presentation-" + page_format, margin: margin) #show heading.where(level: 1): it => text(50pt, weight: "bold")[#it] #show heading.where(level: 2): it => text(42pt, weight: "bold")[#it] #show heading.where(level: 3): it => text(34pt, weight: "bold")[#it] #set text(24pt) // #let distribute = it => [#v(1fr) it] // #show par: distribute // #show listitem: distribute #doc ]
https://github.com/herbertskyper/HITsz_Proposal_report_Template
https://raw.githubusercontent.com/herbertskyper/HITsz_Proposal_report_Template/main/utils/utils.typ
typst
MIT License
#import "../theme/type.typ":* //用于生成报告的标题提示 #let title_tips(content:"",spacing_h:2.4cm) =[ #set text( font: "New Computer Modern", size: 字号.四号, ) #v(-1.05cm) #h(spacing_h) (#content) ] //用于生成报告的标题 #let report_title(title_content: "",title_tips: "")={ set text(font:字体.宋体,size:字号.四号) " " strong[#title_content] if title_tips != ""{ "("+title_tips+")" } } //用于生成方框,并可以写入内容 #let rect_content(content: "",height: 23.5cm)=[ #rect( width: 100%, height: height, [ #v(0.3cm) #content ], ) ] // 用于创建一个不可见的标题,用于给 outline 加上短标题 #let invisible-heading(..args) = { set text(size: 0pt, fill: white) heading(numbering: none, ..args) } //用于生成block级别的方框 #let block_content(body) = { block(stroke: 1pt + black, inset: 10pt)[#body] } //用于产生组图的子图 #let subfigure(body, caption: "", numbering: "(a)") = { let figurecount = counter(figure) let subfigurecount = counter("subfigure") let subfigurecounterdisply = counter("subfigurecounter") let number = locate(loc => { let fc = figurecount.at(loc) let sc = subfigurecount.at(loc) if fc == sc.slice(0,-1) { subfigurecount.update( fc + (sc.last()+1,) ) subfigurecounterdisply.update((sc.last()+1,)) } else { subfigurecount.update( fc + (1,)) subfigurecounterdisply.update((1,)) } subfigurecounterdisply.display(numbering) }) body v(-.65em) if not caption == none { align(center)[#number #caption] } }
https://github.com/Vanille-N/kefir
https://raw.githubusercontent.com/Vanille-N/kefir/master/label/draw.typ
typst
The Unlicense
#import "@preview/cetz:0.2.2": * #import draw: * #let stroke = 0.5pt #let dp(to, ..attrs) = { let as_arr = attrs.pos() let as_dic = attrs.named() let chosen = { if as_arr.len() > 0 { if as_dic.len() > 0 { panic("Can't handle poth positional and named arguments") } else { as_arr } } else { if as_dic.len() > 0 { as_dic } else { panic("Arguments must be provided") } } } (to: to, rel: chosen) } #let arrow(uid1, dir, uid2, ..args) = { let style = (length: 0.3cm, width: 0.2cm) let mark = if dir == ">" { (end: ">", ..style) } else if dir == "<" { (start: ">", ..style) } else { (end: ">", start: ">", ..style) } let name = args.named().at("name", default: "_line") line(uid1, uid2, stroke: stroke, mark: mark, angle: angle, name: name) let text = args.named().at("text", default: none) if text != none { content(name+".mid")[#text] } } #let crect(center, ..args) = { let dx = args.named().dx let dy = args.named().dy rect( (rel: (-dx, -dy), to: center), (rel: ( dx, dy), to: center), ..args, ) } #let point(center, ..args) = { circle(center, radius: 0, stroke: none, ..args) } #let csquare(pos, halfside, ..args) = { crect(pos, dx: halfside, dy: halfside, ..args) } #let carc(center, ..args) = { let a = args.named() arc( dp(center, radius: a.radius, angle: a.start), start: a.start, radius: a.radius, ..args ) } #let orig = (0, 0) #let cone(center, invert: false, ..args) = { let start = args.named().start let stop = if "stop" in args.named() { args.named().stop } else { start + args.named().delta } let stroke = args.named().at("stroke", default: (:)) let inner = args.named().inner let outer = if "outer" in args.named() { args.named().outer } else { inner + args.named().width } group({ merge-path(stroke: stroke, close: true, { if invert { let stop = if stop > start { stop - 360deg } else { stop + 360deg } carc(center, radius: inner, start: start, stop: stop) } else { carc(center, radius: inner, start: start, stop: stop) } carc(center, radius: outer, start: stop, stop: start) }) }) } #let lozenge(center, ..args) = { let dx = args.named().dx let dy = args.named().dy let name = args.named().name group(name: name, { let north = dp(center, 0, dy) let south = dp(center, 0, -dy) let east = dp(center, dx, 0) let west = dp(center, -dx, 0) merge-path(close: true, { line(east, south) line(west, north) }) anchor("north", north) anchor("south", south) anchor("east", east) anchor("west", west) }) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/multiline_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test in case distinction. $ f := cases( 1 + 2 &"iff" &x, 3 &"if" &y, ) $
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/break-continue-07.typ
typst
Other
// Error: 2-10 cannot continue outside of loop #continue
https://github.com/antonWetzel/prettypst
https://raw.githubusercontent.com/antonWetzel/prettypst/master/test/default/label.typ
typst
MIT License
#figure([]) <a> #figure([]) <b> #ref(<a>) #ref( <a>, )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/013%20-%20Magic%202015/004_The%20Bard%20and%20the%20Biologist.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Bard and the Biologist", set_name: "Magic 2015", story_date: datetime(day: 09, month: 07, year: 2014), author: "<NAME>", doc ) On the plane of Shandalar, in the city of Lesh, a man walked the streets, rambling about evil horrors. That, in itself, was hardly remarkable. Lesh was no stranger to that sort of behavior. The city was a cesspool of corruption, thievery, and murder; a reflection, some said, of a mysterious and evil god they claim founded the city centuries before. The god was long gone, but his stain still covered and twisted Lesh, home to cults dedicated to Xathrid demons and agents of the Vaasgoth vampires. The city would have been avoided by most, of course, if not for its position on one of Shandalar's most vital trade rivers. The merchant guilds ruled the city, along with a fair deal of the city's underworld—which sported some of the most legitimate criminals one could find on the plane. It was those very merchants who the rambling man, yelling loudly of insidious creatures, walked up to and grabbed by the robes, shaking each in turn. He demanded they listen, as if the elderly, portly fruit vendors were his only chance for survival. His pleas of, "You have to listen to me!" only made his case worse, as the merchants took it as a cue to ignore his incessant rambling. The merchants, ever wary of such madness, would have immediately alert the guards if not for the polished and no doubt expensive jewels the rambling man wore around his neck and wrists. A man clearly struck by that sort of madness would not have usually garnered such respect nor drawn attention, not in a place such as Lesh, but when he wore a year's worth of income loosely around his neck, the merchants tended to be a bit more understanding. As the merchants in their stalls formulated their plans to curry the man's favor and thieves drew their daggers in dark alleys, a young woman bumped into the raving man. She wore a leather outfit, outdated in style from a nobleman's perspective, but refined enough in a beggar's eyes. #figure(image("004_The Bard and the Biologist/01.jpg", width: 100%), caption: [Jalira, Master Polymorphist | Art by <NAME>], supplement: none, numbering: none) "Oh, pardon me, Sir," she said. "You! Will you help me?" The man wore a soldier's uniform reminiscent of far-off Thune, but it was dirty and smelled as though it had been the man's home for some time. "What's the problem?" she asked, putting her hand on his shoulder. "The skep! My girl, we must warn the others of the skep!" He never noticed that one of his necklaces had been clipped and slid into the woman's hand. "They sound terrifying!" she said, putting her hands over his, sliding his rings off his fingers. "I believe I've heard of them." "You have? Please—no one believes me." He stared intently into the woman's eyes. Another man stopped to address the pair. He had longer black hair and wore a leather patch over his right eye. His brown leather clothes were detailed with the chitin of an albino insect, similar to the insectoid parts that made up the lyre he wore on his back. #figure(image("004_The Bard and the Biologist/02.jpg", width: 100%), caption: [Yisan, the Wanderer Bard | Art by Chase Stone], supplement: none, numbering: none) "I believe you, Sir," said the man, "for I have fought and killed many skep in my time." The woman grew red and glared as the new competition moved in on her mark. "Have you now?" she said, through clenched teeth. "Why, I felled near seven before breakfast," he said with a smile. "I will listen to your tale, gentle soul." "Oh, bless you both," the addled man said. "Sir, it looks as though you dropped a gold coin," the newcomer said. He reached down and plucked a coin from the ground—copper, painted gold—and placed it in the man's hand while he simultaneously removed one of the golden bracelets on the man's wrist. In the same fluid movement he slipped to the side to pick the man's pockets. "Oh, I see, thank you." The disheveled man stared at the coin. Over his shoulder, the newcomer flashed a broad smile at the woman, who clenched one fist and placed her other hand on the man's shoulder. The newcomer, mirroring her movements, placed his hand on the man's other shoulder. The soothsayer, however, was so enamored by the coin that he failed to see his audience was in contention. The merchants, wary of the two stripping the man of his treasures and eager to take their own turn pilfering the soothsayer's possessions, finally moved to alert the guards. If they weren't going to get their share, then why should anyone else? "Jalira and Yisan, step away from that man!" A voice echoed through the market. Jalira, the woman, and Yisan, the man with the eye patch, looked at each other and sighed. The commander of the guards rode toward them on a horse with six other soldiers, two of whom already had drawn bows aimed at Jalira and Yisan. "Jalira, place your hands in your pockets. Yisan, if you so much reach for that lyre I'll have an arrow through you before you strum your first note." Jalira placed her hands in her pockets and Yisan crossed his arms. "Why hello, Dexros," Yisan said, moving his hands as he spoke, knowing it would cause the guards trepidation as they tracked his movements. "What seems to be the problem?" "We've reports you've been robbing in the market." Jalira's face turned from annoyance to compassion as she raised her eyebrows and stepped forward. "Please, Sir. We are only helping this poor soul by stealing his wares, so he doesn't end up with a dagger in his back. We are doing nothing but our civic duty," she said. The addled man looked confused, then noticed his gold was missing. He didn't seem to care, instead turning to walk over to the nearest smiling merchant, continuing to rant about impending doom at the hands or claws of the skep. Jalira and Yisan rolled their eyes at the loss of their mark. "You are under arrest," said Dexros, commander of the guards. "Come with us or else we will issue a warrant of execution against you." "I've already got a warrant of execution," Jalira corrected. Yisan looked over at her, dismayed. "Why do you always make things difficult?" Yisan turned to the guards. "We will not being going with you." Dexros moved to signal his men to attack, but just as he opened his mouth to order the archers to fire, Yisan hummed a tune imperceptible to human ears. Yisan preferred playing his lyre, but any instrument would do, including his voice. Five panicked horses reared up, throwing three riders to the ground, and bolted through the marketplace. Two of the guards barely hung on to their steeds. The guards on the ground moved to get up and charge the duo, but Jalira waved her hands, wafting blue smoke from her fingertips. The guards transformed into tiny blue frogs, their empty clothes falling around them. Yisan shot Jalira a disapproving look. "The flies were bothering me," Jalira replied, smiling. #figure(image("004_The Bard and the Biologist/03.jpg", width: 100%), caption: [Polymorphist's Jest | Art by <NAME>], supplement: none, numbering: none) Yisan rolled his eyes. He was about to retort, to scold her for interrupting his melody, but the sound of more guards down the street caused their ears to perk up. "I think, Jalira, it's best we take our leave." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) After escaping the city, Jalira and Yisan made camp next to a small river on the side of the road, a few miles from town. Jalira drank water from a skin while Yisan stood on a rock, reading a book while he hummed. "Must you continue that tune?" Jalira asked. "Last time we travelled together I had that song stuck in my head for weeks." Yisan didn't respond, instead humming louder and louder, until he was singing, prompting Jalira to pick up a rock and throw it at the bard. Yisan, never looking up from the book, jumped down from the rock and walked over to Jalira. "It seems the man we robbed was a Thunian scout named Hastric," Yisan said as he waved the book in front of Jalira. "This might be the solution to our financial problems." She snatched the book. "What financial problems?" she asked, sounding exceedingly unconvincing to Yisan, who smirked as Jalira opened the book to read. "Silver!" she exclaimed. "No, that's #emph[sliver] ," Yisan corrected, jumping from the ground back to his boulder. "Your greedy mind betrays your eyes." On his lyre, Tolumnus, he strummed the same tune he had been humming. Jalira dismissed his correction and continued to read about the slivers. She had heard rumors of strange creatures that evolved rapidly, but her research into physiology halted when she ran out of money to feed her test subjects—and herself. Hastric had taken it upon himself to study the slivers, but he the writings in Jalira's hands suggested he slowly began to lose his mind, it would seem, due to what he initially called the "hum." Later writings, which became more erratic and paranoid, referred to it as a "thrum." The final scribbled entry simply referred to it as "the call." But contained within the notes were reports of dead merchants and travelers in the deepest parts of the sliver network, merchants and travelers who left behind piles of gold and other jewelry waiting to be plundered. Jalira's cheeks reddened and her pulse quickened as she read. Not only could she study unique and incredible creatures the civilized world hadn't seen, Jalira realized, but she could make a small fortune as well. "Well, let's go then," Jalira said, tossing the journal at the still-playing bard. She was still smiling, although her grin was as false as ever. Yisan caught the book with his strumming hand, cutting off the song. "It will take us deep into the Kalonian Wilds, well past the Onakke ruins." Yisan said. "So we better get moving." Yisan fastened Tolumnus on his back and hummed the same familiar tune as the pair began down the road. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The journey was more difficult than expected. Early on, Yisan and Jalira were beset by a pack of beasts corrupted by dark magics, creatures that had only recently begun to plague the land. Jalira turned a few into rabbits while Yisan tried to calm them. His music did not affect the beasts, so he charmed massive centipedes from beneath the earth. During the ensuing fight, the pair escaped. After a night spent with a particular and mathematically minded mining company, Yisan and Jalira swung wide of the coast, taking extra time through the Kalonian Forest to avoid Talrand's aerial patrols. Neither counted the drake summoner as a friend for a variety of differing reasons: between the two of them, Talrand had been cheated out of twenty gold bars, the deed to a lighthouse, and a marriage. Yisan had spent some time in the Eloren Wilds, which were certainly dense and dangerous, but they did not house as many terrifying or feral beasts as those in Kalonia. Although it tired him and annoyed Jalira, Yisan played a light tune on his lyre as they hiked into the deepest part of the Kalonian Forest, keeping the hydra and tuskers away, but causing his fingers to bleed as he played for hours on end. Eventually, through no small effort, the pair found themselves near the area marked in the journal. It was not the exact location, but the distinct sound of chittering and buzzing Hastric's journal described confirmed the proximity of the slivers. The buzz rang in their ears. Yisan and Jalira pushed their way through brush, finding themselves facing a cliff with a cave. Above, along the cliff and into the cave, hung the slivers, similar to Hastric's maddened sketches. Hastric called them the "less brood," although they were still close to Jalira and Yisan's size. They slithered and hung from the rocks above them with their tails and singular clawed arms in the centers of what Jalira discerned to be their chests. #figure(image("004_The Bard and the Biologist/04.jpg", width: 100%), caption: [Sliver Hive | Art by <NAME>], supplement: none, numbering: none) "I don't think my music will work here," Yisan whispered, glancing in Jalira's direction, without taking his attention off the hive. Jalira was annoyed he had spoken, but she knew what he said was true. There were at least a dozen slivers, and their bizarre clicks would surely drown out Yisan's songs. The pair, assured only by the fact that Hastric had survived there for months, slowly walked forward. As they crept into the cave, several slivers slid down the rocks to bar their path. The slivers didn't move quickly or aggressively. Their heads didn't even seem to follow the pair. Yet every sliver before them raised its bladed arm in their direction. "I have a plan," Jalira whispered, trying to hide her smile as she studied the creatures. "I don't like it," Yisan replied. Blue smoke began to flow from Jalira's fingertips. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) All they know is the hive. The hum of the nest. The will of the hivelord. They fight it, Jalira and Yisan, their minds racing to control their new sliver bodies. They are those of the lesser type. They can hear the thoughts of all in the hive—a constant hum. As they move through the hive, they lose themselves, succumbing to the will of the hivelord. They lose each other, forgetting who they are. They catch their thoughts, briefly, and rush back to one another, trying to stay out of the constant urge that seeks to make them drones. The hive is all and all is the hive. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) After a few minutes (hours? days?), Yisan and Jalira began to recover their bearings. Control of their own free will slowly crept back. They moved past the bipedal and humanoid "primes" Hastric described, which looked like the sentient races of Shandalar but moved like insects, the chittering intense and loud. The pair, still moving as slivers, came to a larger chamber with alcoves lining the ways, in which strange biomasses were tended by lesser slivers. A sliver rode the wind with wings there, spiraling down from the top of the chamber to the bottom. As it passed by another sliver, that sliver, too, grew wings and momentarily hovered. Jalira and Yisan felt the wings pop out of their backs, felt the new parts form from their bodies, and knew how to fly as if they had done so their entire lives. As they moved toward the center of the hive, however, they lost their wings. Sometimes they grew extra blades or began to secrete venom, which disappeared as they moved inward. After some amount of time they could not fathom, they arrived at the central chamber, the hub of the hive's activity. The sliver hivelord towered in the chamber, a massive creature twenty times their size. Hastric had mentioned it was the source of the slivers, their liege. The bones of the dead—and, more importantly, their gold and possessions—laid at the edges of the chamber, remnants of the hivelord's feasts. #figure(image("004_The Bard and the Biologist/05.jpg", width: 100%), caption: [Sliver Hivelord | Art by <NAME>], supplement: none, numbering: none) Jalira and Yisan entered the chamber, but their sliver forms began to waver. The hivelord somehow willed them to abandon their façade. It seemed to observe them, its blades moving almost independently of the swaying, snakelike body. Naked, Jalira and Yisan kept their eyes on the hivelord, terrified, but stole glances at one another for any indication of what they should do next. Not knowing what to do, they both bowed to the hivelord. The massive sliver made no reaction. Without words, they both backed toward the walls of the chamber and cautiously grabbed the remnants of clothing lying there. They dressed and, careful not to forget the purpose of their journey, slowly procured as many coins and treasures as they and their pilfered clothes could carry, all while keeping their eyes on the hivelord. The slivers did nothing to allow Jalira and Yisan to pass, although neither did they actively try to stop Yisan and Jalira's exit. The two, no longer invisible in their disguise, avoided the primes, whose humanlike heads turned to look at them as they passed. Eventually, after carefully waiting for slivers to move out of their way, they made it back out of the lair, into the woodlands, to where they had left their clothes. "We need to get to Martyne," said Jalira, breaking the silence. "Grendub will be able to front most of this." "I think I'm going to stay here for a while," Yisan replied, his head turned toward the cave. He picked up Tolumnus. "I want to study them a little more. Their music is fascinating. You can take all the treasure." Jalira made no eye contact with him. "Yeah, sure, I guess," she said. "If you trust me. I'll keep the gold we make, but I'll only stay in Martyne for a few days." Yisan didn't seem to hear her. He stared at the cave, strumming his harp to mimic the sounds of the slivers. "That works. I'll catch up with you in a bit." He sat down to watch the slivers hanging from the rocks and strummed his carapace lyre. Jalira wanted to say something else, but pride forced her to leave without a word. She was not going to waste her time on foolishness. She knew what she needed to know about slivers. She set off for Martyne and hoped she remembered the annoying song Yisan always got stuck in her head.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/pavemat/0.1.0/README.md
markdown
Apache License 2.0
# Pavemat ![pavement + matrix](./examples/logo.svg) repo: <https://github.com/QuadnucYard/pavemat> ## Introduction The *pavemat* is a tool for creating styled matrices with custom paths, strokes, and fills. It allows users to define how paths should be drawn through the matrix, apply different strokes to these paths, and fill specific cells with various colors. This function is particularly useful for visualizing complex data structures, mathematical matrices, and creating custom grid layouts. ## Examples The logo example: ```typst #{ set math.mat(row-gap: 0.25em, column-gap: 0.1em) set text(size: 2em) pavemat( pave: ( "SDS(dash: 'solid')DDD]WW", (path: "sdDDD", stroke: aqua.darken(30%)) ), stroke: (dash: "dashed", thickness: 1pt, paint: yellow), fills: ( "0-0": green.transparentize(80%), "1-1": blue.transparentize(80%), "[0-0]": green.transparentize(60%), "[1-1]": blue.transparentize(60%), ), delim: "[", )[$mat(P, a, v, e; "", m, a, t)$] } ``` Code of examples can be found in [`examples/examples.typ`](https://github.com/QuadnucYard/pavemat/tree/main/examples). ![](./examples/example1.svg) ![](./examples/example2.svg) ![](./examples/example4.svg) ![](./examples/example5.svg) ## Manual See [`docs/manual.typ`](https://github.com/QuadnucYard/pavemat/tree/main/docs).
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/frac_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test dif. $ (dif y)/(dif x), dif/x, x/dif, dif/dif \ frac(dif y, dif x), frac(dif, x), frac(x, dif), frac(dif, dif) $
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/for-loop-line-break.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2" #let 六面体 = { import cetz.draw: * import cetz: * let neg(u) = if u == 0 { 1 } else { -1 } for (p, c) in ( ((0, 0, 0), black), ((1, 1, 0), red), ((1, 0, 1), blue), ((0, 1, 1), green), ) { line(vector.add(p, (0, 0, neg(p.at(2)))), p, stroke: c) line(vector.add(p, (0, neg(p.at(1)), 0)), p, stroke: c) line(vector.add(p, (neg(p.at(0)), 0, 0)), p, stroke: c) } } #let 六面体 = { for (pppppppppppppppppppppppppppppppppppppppppp, cccccccccccccccccccccccccccccccc, b) in ( (111111, 111111111, 1), ) { "111111111111111111111111111111111" } } #{ let arr = (1,) for (i, n) in arr.enumerate() { 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 } } #{ let arr = (1,) for (i, n) in arr.rev().rev().rev().rev().rev().rev().rev().rev().enumerate() { 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 } }
https://github.com/LaurenzV/simplecv
https://raw.githubusercontent.com/LaurenzV/simplecv/main/README.md
markdown
MIT License
# SimpleCV SimpleCV is a simple and elegant CV template written in [Typst](https://typst.app/) aimed at (but not limited to!) people with an engineering background. The template was inspired by two Latex CV templates ([[1]](https://www.overleaf.com/latex/templates/autocv/scfvqfpxncwb), [[2]](https://www.overleaf.com/latex/templates/faangpath-simple-template/npsfpdqnxmbc)). Feel free to create an issue if you have any questions or notice errors. # Usage Create a new Typst project and copy the whole content of the `src` directory into the project. Change the contents of the `src/main.typ` file according to your own needs. This should be it. You can find an example of what the CV looks like in `example.pdf`. # License The template itself is available under the MIT license. The icons are from FontAwesome and subject to [their license agreement](https://github.com/FortAwesome/Font-Awesome/blob/6.x/LICENSE.txt).
https://github.com/Wh4rp/Typst-PUC
https://raw.githubusercontent.com/Wh4rp/Typst-PUC/master/example.typ
typst
#import "modules/template.typ": * #show: doc => project( curso: ( sigla: "IIC1000", nombre: "Introucción a los computadores y a la programación", departamento: "Departamento de Ciencia de la Computación", ), autor: ( nombre: "Fulano", apellido: "<NAME>", email: "<EMAIL>", ), numero_de_ayudantia: 4, fecha: "25 de septiembre de 2021", body: doc ) #problem[ #lorem(50) + #lorem(10) + #lorem(10) #solution[ #lorem(20) + #[ #lorem(4) $ integral_0^x^2 = 1/3 x^3 $ ] + #[ #lorem(10) $ sum_(i=1)^n i = 1/2 n (n+1) $ ] ] ]
https://github.com/NOOBDY/formal-language
https://raw.githubusercontent.com/NOOBDY/formal-language/main/q1.typ
typst
The Unlicense
#import "@preview/finite:0.3.0": automaton, layout #let q1 = [ 1. (Fun with `DFA`) For each of the following languages, construct a `DFA` that accepts the language. In all cases, the alphabet is {0, 1}. 1. ${w | |w| equiv 0 mod 3}$. #automaton( ( q0: (q1:"0,1"), q1: (q2:"0,1"), q2: (q0:"0,1"), ), labels: ( q0: $ q_0 $, q1: $ q_1 $, q2: $ q_2 $ ), final: ("q0"), style: ( state: ( stroke: 0.5pt, ), transition: ( stroke: 0.5pt, curve: 0, label: ( angle: 0deg ) ), q2-q0: (curve: 1.0) ), ) 2. ${w | 110 "is not a substring of" w}$. #automaton( ( q0: (q0:"0", q1:"1"), q1: (q0:"0", q2:"1"), q2: (q0:"0", q3:"1"), q3: (q3:"0,1"), ), labels: ( q0: $ q_0 $, q1: $ q_1 $, q2: $ q_2 $, q3: $ q_3 $, ), final: ("q0","q1","q2"), style: ( state: ( stroke: 0.5pt, ), transition: ( stroke: 0.5pt, curve: 0, label: ( angle: 0deg ) ), q1-q0: (curve: 0.5), q2-q0: (curve: 1.5) ), ) 3. ${w | "every odd position in" w "is 1"}$. #automaton( ( q0: (q1:"1", q2:"0"), q1: (q0:"0,1"), q2: (q2:"0,1") ), labels: ( q0: $ q_0 $, q1: $ q_1 $, q2: $ q_2 $ ), final: ("q0", "q1"), style: ( state: ( stroke: 0.5pt, ), transition: ( stroke: 0.5pt, curve: 0, label: ( angle: 0deg ) ), q1-q0: (curve: 0.5), q2-q2: (anchor: left) ), layout: layout.custom.with( positions: (..) => ( q0: (0, 3), q1: (3, 3), q2: (0, 0), ) ) ) 4. ${w | w "contains at least two 1s and at most two 0s"}$. #automaton( ( q0: (q1: 1, q3: 0), q1: (q2: 1, q4: 0), q2: (q2: 1, q5: 0), q3: (q4: 1, q6: 0), q4: (q5: 1, q7: 0), q5: (q5: 1, q8: 0), q6: (q7: 1, q9: 0), q7: (q8: 1, q9: 0), q8: (q8: 1, q9: 0), q9: (q9: "0,1") ), labels: ( q0: $ q_(00) $, q1: $ q_(01) $, q2: $ q_(02) $, q3: $ q_(10) $, q4: $ q_(11) $, q5: $ q_(12) $, q6: $ q_(20) $, q7: $ q_(21) $, q8: $ q_(22) $, q9: $ q_n $ ), final: ("q2", "q5", "q8"), style: ( state: ( stroke: 0.5pt, ), transition: ( stroke: 0.5pt, curve: 0, label: ( angle: 0deg ) ), q2-q2: (anchor: right), q5-q5: (anchor: right), q8-q8: (anchor: right), q9-q9: (anchor: left), ), layout: layout.custom.with( positions: (..) => ( q0: (0, 4), q1: (2, 4), q2: (4, 4), q3: (0, 2), q4: (2, 2), q5: (4, 2), q6: (0, 0), q7: (2, 0), q8: (4, 0), q9: (2, -2) ) ) ) 5. ${epsilon.alt, 0}$. #automaton( ( q0: (q0: 0, q1: 1), q1: (q1: "0,1") ), labels: ( q0: $ q_0 $, q1: $ q_1 $, ), final: ("q0"), style: ( state: ( stroke: 0.5pt, ), transition: ( stroke: 0.5pt, curve: 0, label: ( angle: 0deg ) ), ), ) ]
https://github.com/HarryLuoo/sp24
https://raw.githubusercontent.com/HarryLuoo/sp24/main/431/hw/1/hw2.typ
typst
= Math 431 hw2 = <NAME> #set math.equation(numbering: "(1)") == - ex 1.15// *(a)* Following the definition of events $W,G,R$, we describe the event of "not all three colors are present" as $W sect G sect R$. Then, according to inclusion-exclusion principle, we have $ P("did not see all three colors") = & P(W sect G sect R)\ = & P(W) + P(G) + P(R) \ & - P(W G) - P(W R) - P(G R) \ & + P(W G R) $ Note that, for each draw, we are picking 3 balls (excluding one white ball) from 4, so after 3 draws, $P(W) =(3/4)^2 $. Similarly, $P(G) = (3/4)^2$, $P(R) = (2/4)^2$.\ Notice that if neither white nor green is drawn, then the only possibility is that we draw 3 red balls. If we label the balls to differenciate the 2 red balls in urn, we have $P(W G) = (2/4)^2$. \ Similarly, $P(W R) = (1/4)^2$, $P(G R) = (1/4)^2$. \ Finally, $P(W G R) = 0$, since it is impossible to draw 3 balls without drawing any of the 3 colors.\ Combining all of the above, $ P(W sect G sect R) &= (3/4)^2 + (3/4)^2 + (2/4)^2 - (2/4)^2 - (1/4)^2 - (1/4)^2 + 0 \ &= 13/16 $ *(b)* We can represent the complement of the event "did not see all three colors" as "saw all three colors". Then, $P("did not see all three colors")= 1- P("saw all three colors")$\ The event "saw all three colors" can be analyzed as follows: the three colors are picked in order, with $3 !=6$ number of ways to pick the colors. Consider there are two red balls, we have in total $2*6$ = 12 number of ways to pick the balls. Then, $ P("saw all three colors")=12/4^3 = 3/16 $\ Therefore, $P("did not see all three colors") = 1- 3/16 = 13/16$. - ex 1.18 \ The sample space of X is ${3,4,5}$. The probability mass function of each value is:$ & P(X=3) = "letters in ARE"/"total letters"=3/16\ & P(X=4) = "letters in SOME & DOGS"/"total letters"=8/16=1/2\ & P(X=5) = "letters in BROWN"/"total letters"=5/16 $ #pagebreak() - ex 1.40\ We denote the event "at least one color is repeated exactly twice" as $T$, where $T= G sect R sect Y sect W$. Therefore, the probability of this event is $ P(T)= & P(G sect R sect Y sect W) \ = & P(G)+P(R)+P(Y)+P(W)&& "by inclusion-exclusion principle" \ & -P(G sect R)-P(G sect Y)-P(G sect W)-P(R sect Y)-P(R sect W)-P(Y sect W)\ & +P(G sect R sect Y)+P(G sect R sect W)+P(G sect Y sect W)+P(R sect Y sect W)\ & -P(G sect R sect Y sect W) \ $ <eq1> When exactly two balls are of the same color, we are picking 2 balls from the 4 spots to be the same color, and then pick the remaining 2 spots randomly from the urn. Since the total number of events is $4^4$, We can calculate $ P(G)=P(R)=P(Y)=P(W)=(binom(4,2)*3*3)/4^4= 27/128 $ We denote each term in the third line in @eq1 as $P(A sect B)$, where $A,B in {G,R,Y,W}$. The magnitude of the set $A sect B$ is $binom(4,2)$, which is the number of ways to pick 2 colors from 4. Then, we have $ P(G sect R)=P(G sect Y)=P(G sect W)=P(R sect Y)=P(R sect W)=P(Y sect W)\ = (binom(4,2)/4^4)\ = 3/128 $ Since we cannot have 3 colors or 4 colors all appearing twice in the 4 draws, we know that the last two rows in @eq1 are 0. Therefore, $ P(T)= 3*27/128 - 6*3/128 =45/64 $ - ex 2.4\ We mark the event of "picking the second urn" as A, and $A^c$ for "picking the first urn" and the event of "picking the ball labeled 5" as B. The probability of B could be given as $ P(B)=& P(B A)+P(B A^c)\ =&P(B|A)P(A)+P(B|A^c)P(A^c) $ Notice that $ P(B|A^c)=0\ P(A)=P(A^c)=1/2 \ P(B|A)=1/3 $ Therefore, $ P(B)=1/3*1/2=1/6 $ - ex 2.10\ We mark the event of "pulled out a x-sided die" as $D_x$, and the event of "outcome of the roll is 4" as F. According to the law of total probability, we have $ P(D_6|F)=P(D_6F)/P(F) = P(F|D_6)P(D_6)/P(F)=(1/6*1/3)/P(F) $ Notice that $ P(F)=&P(F|D_4)P(D_4)+P(F|D_6)P(D_6)+P(F|D_12)P(D_12)\ = & 1/4*1/3+1/6*1/3+1/12*1/3\ = & 1/12+1/18+1/36\ =&1/6 $ Therefore, Combining equation 12 and 13, we have $P(D_6|F)=(1/18)/(1/6)=1/3$ - ex 2.32\ *(a)* Mark boy as B, girl as G. Sample space $Omega = {B B B,B B G, B G B, G B B, B G G, G B G, G G B, G G G }$.\ Probability measure for each sample point would be $(1/2)^3=1/8$. *(b)* Mark the event of there is a boy amongst the children as M, and the event of 2 of the children are girls as N.Then, $M = {B B B,B B G, B G B, G B B, B G G, G B G, G G B,}$. Probability of the child not seen given that two are girls,$ P(M|N)&=P(M sect N)/P(N)\ &=P({B G G, G B G, G G B})/P({B G G, G B G, G G B, G G G})\ &=(3/8)/(4/8)\ &=3/4 $ *(c)* Similar to (b), we mark the event of there is a boy amongst the children as M, and the event of the two yougest children are girls as N. $ P(M|N)= P(M sect N)/P(N)=P({G G B})/P({G G B, G G G})=1/2 $ - ex 2.34\ Suppose we put the marked ball in urn 1. Denote the event of "Friend picked the marked ball" as A, and the event "Friend chose urn k" as $B_k$. We also denote that there are m balls in urn 2 $(0<=m<=2)$, and 3-m balls in urn 1.\ Since there are in total 3 arrangements, and considering that $P(A|B_2)=0$, we can list the following: $ "All 3 balls in urn 1:"&P(A)=P(A|B_1)P(B_1)=1/3*1/2=1/6\ "2 balls in urn 1:"&P(A)=P(A|B_1)P(B_1)=1/2*1/2=1/4\ "only the marked ball in urn 1:"&P(A)=P(A|B_1)P(B_1)=1*1/2=1/2\ $ *(a)* Therefore, to minimize $P(A)$, we should put all three balls in one urn.\ *(b)* To maximize $P(A)$, we should put the marked ball in one urn, and the other two balls in the other urn.\ *(C)* when there are one marked ball amongst n balls, we denote the following:\ There are m balls in urn 1 put together with the marked ball $(0<=m<=n)$, and $n-m$ balls in urn 2.\ $ P(A)=P(A|B_1)P(B_1)=1/(m+1)*1/2=1/(2m+2) $ So, to *minimize* $P(A)$, we should put all the balls in urn 1. \ To *maximize* $P(A)$, we should put the marked ball in one urn, and the other $n-1$ balls in the other urn. - ex 2.38\ *(a)* We denote: the event of "the chosen letter is R" is R, and the event of "the kth word is chosen" is $W_k$. Then, we have $ P(R)&=P(R|W_1)P(W_1)+P(R|W_2)P(W_2)+P(R|W_3)P(W_3)+P(R|W_4)P(W_4)\ &= 0+0+1/3*1/4+1/5*1/4\ &=2/15 $ *(b)* There are 4 words in total: 1 of which X=3, 2 of which X=4, 1 of which X=5. So,$ P(X=3)=1/4\ P(X=4)=2/4\ P(X=5)=1/4 $
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/string-21.typ
typst
Other
// Error: 2:1 expected quote #"hello\"
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-2/homework1.typ
typst
#import "../template.typ": * #show: project.with( course: "Calculus II", course_fullname: "Calculus (A) II", course_code: "821T0160", title: "Homework #1", authors: (( name: "<NAME>", email: "<EMAIL>", id: "#198" ),), semester: "Spring-Summer 2024", date: "January 24, 2024", ) #let ss = [$display(attach(inline(sum), t: +oo, b: n=1))$] #let sss = [$display(attach(sum, t: +oo, b: n=1))$] #let int = math.integral #let dx = [$dif x$] #let dy = [$dif y$] = 习题11-1 == P243 1(1) #prob[ 判断级数敛散性,若收敛,则写出其和。 $ sss (1/(2^n) + 1/(3^n)) $ ] $ "原式" &= sss 1/(2^n) + sss 1/(3^n) &= (1/2)/(1-1/2) + (1/3)/(1-1/3) &= 1 + 1/2 &= 3/2 $ == P243 1(2) #prob[ 判断级数敛散性,若收敛,则写出其和。 $ sss 1/((3n-2)(3n+1)) $ ] $ "原式" &= sss 1/((3n-2)(3n+1)) &= sss 1/3(1/(3n-2) - 1/(3n+1)) &= 1/3 lim_(n->+oo) (1 - 1/(3n+1)) &= 1/3 $ == P243 1(4) #prob[ 判断级数敛散性,若收敛,则写出其和。 $ sss root(n,0.001) $ ] $ lim_(n->+oo) a_n &= lim_(n->+oo) root(n,0.001) = exp lim_(n->+oo) 1/n ln(0.001) = e^0 = 1 != 0 $ 故该级数发散。 == P243 1(5) #prob[ 判断级数敛散性,若收敛,则写出其和。 $ sss n/(2n-1) $ ] $ lim_(n->+oo) a_n = lim_(n->+oo) n/(2n-1) = lim_(n->+oo) 1/(2-1/n) = 1/2 != 0 $ 故该级数发散。 == P243 2(1) #prob[ 已知级数的部分和为 $S_n=display((n+1)/(n))$,写出该级数,并求其和。 ] $ a_n = S_n - S_(n-1) = 1+1/n-(1-1/(n-1)) = 1/n - 1/(n-1) = -1/(n(n-1)) sp (n>=2) $ 当 $n=1$ 时,$a_1=S_1 =2$。 $ ss a_n = lim_(n->+oo) ((n+1)/n) = 1 $ == P243 2(2) #prob[ 已知级数的部分和为 $S_n=display((3^n-1)/(3^n))$,写出该级数,并求其和。 ] $ a_n = S_n - S_(n-1) = (3^n - 1)/(3^n) - (3^(n) - 3)/(3^n) = 2/(3^n) sp (n>=2) $ 容易验证 $n=1$ 也符合此通项。 $ sss a_n = sss 2/(3^n) = 2 times (1/3)/(1-1/3) = 1 $ == P243 3 #prob[ 求 $ display( sss (ln 3)^(n-1)/(2^n) ) $ ] $ "原式" &= 1/2 sss (ln 3)^(n-1)/(2^(n-1)) = 1/2 sss ((ln 3)/2)^(n-1) = 1/2 times 2/(2 - ln 3) = 1/(2 - ln 3) $ = 习题11-2 == P253 1(1) #prob[ 用比较判别法判定级数的敛散性: $ sss (n^(n-1))/((2n^2+n+1)^((n+1)/2)) $ ] $ "原式" &= sss sqrt(((n^2)^(n-1))/((2n^2+n+1)^(n+1)))\ &= sss 1/(n^2) ((n^2)/(2n^2+n+1))^(n/2) $ 注意到 $dp(n^2/(2n+n+1)<1)$,所以 $ (n^(n-1))/((2n^2+n+1)^((n+1)/2)) < 1/n^2 $ 根据 $p-$ 级数的性质可知 $sss dp(1/n^2)$ 收敛,故原级数也收敛。 == P253 1(2) #prob[ 用比较判别法判定级数的敛散性: $ sss 1/(ln(n+1)) $ ] 对于 $x>=2$,有 $ln x < x$,所以有 $ 1/(ln x) > 1/x ==> 1/(ln(n+1)) > 1/(n+1) $ 根据调和级数的敛散性,有级数 $sss display(1/(n+1))$ 发散。故根据比较判别法,级数 $display(sss 1/(ln(n+1)))$ 也发散。 == P253 1(3) #prob[ 用比较判别法判定级数的敛散性: $ sss 1/((3n-1)^2) $ ] 对于 $n>=2$,有 $ 1/(3n-1^2) < 1/((3n-3)^2) = 1/9 times 1/(n-1)^2 $ 由于自然数的倒数的平方和收敛于 $display((pi^2)/6)$,故级数 $ 1/(3 times 1 -1) + 1/9 sum_(n=2)^(+oo) 1/((n-1)^2) $ 收敛。根据比较判别法,级数 $display(sss 1/((3n-1)^2))$ 也收敛。 == P253 2(1) #prob[ 用比值判别法或根值判别法判定级数的敛散性: $ sss ((n!)^2)/((2n)!) $ ] $ lim_(n->+oo) (a_(n+1))/(a_n) &= lim_(n->+oo) (1 times 2 times dots.c times (n+1))/((n+2) times (n+3) times dots.c times (2n+2)) times ((n+1) times (n+2) times dots.c times (2n))/(1 times 2 times dots.c times n)\ &= lim_(n->+oo) (n+1)^2/((2n+1) (2n+2)) = 1/4 < 1 $ 根据比值判别法可得,该级数收敛。 == P253 2(3) #prob[ 用比值判别法或根值判别法判定级数的敛散性: $ sss (n^2)/((2+1/n)^n) $ ] $ lim_(n->+oo) root(n,a_n) &= lim_(n->+oo) root(n,(n^2)/((2+1/n)^n)) = lim_(n->+oo) (root(n,n^2))/(2+1/n) = 1/2 < 1 $ 根据根值判别法可得,该级数收敛。 == P253 2(5) #prob[ 用比值判别法或根值判别法判定级数的敛散性: $ sss n^2 dot.c sin (pi/(2^n)) $ ] 当 $x>0$ 时,有 $sin x < x$ 成立,故 $ a_n = n^2 dot.c sin (pi/(2^n)) < (pi dot n^2)/(2^n) $ 同 2(3) 的思路,我们有 $ lim_(n->+oo) root(n,(pi dot n^2)/(2^n)) = 1/2 < 1 $ 故根据根值判别法可得,级数 $sss display((pi dot n^2)/(2^n))$ 收敛。再根据比较判别法得,原级数收敛。 == P253 3(1) #prob[ 用比较判别法的极限形式研究级数的敛散性: $ sum_(n=2)^(+oo) (ln n)/(n^2) $ ] 注意到: $ lim_(n->+oo) display((ln n)/(n^2))/display(1/(n^(3/2))) &= lim_(n->+oo) (ln n)/(n^(1/2)) = 0 $ 根据 $p-$ 级数的性质,有 $ss n^(-3/2)$ 收敛,故根据比较判别法的极限形式,原级数也收敛。 == P253 3(3) #prob[ 用比较判别法的极限形式研究级数的敛散性: $ sum_(n=2)^(+oo) (sqrt(n+2) - sqrt(n-2))/(n^a) $ ] $ (sqrt(n+2) - sqrt(n-2))/(n^a) = ((n+2) - (n-2))/(n^a (sqrt(n+2) + sqrt(n-2))) = 4/(n^a (sqrt(n+2) + sqrt(n-2))) $ 注意到 $ lim_(n->+oo) display(4/(n^a (sqrt(n+2) + sqrt(n-2))))/display(n^(a+1/2)) = 2 $ 故原级数与级数 $sss display(1/(n^(a+1/2)))$ 有相同的敛散性。根据 $p-$ 级数的性质,当 $a<=1/2$ 时原级数发散;当 $a>1/2$ 时原级数收敛。 == P253 4(2) #prob[ 用积分判别法研究级数的敛散性: $ sum_(n=2)^(+oo) 1/(n ln n (ln ln n)) $ ] 根据积分判别法,该级数的敛散性与反常积分 $ int_2^(+oo) 1/(x ln x (ln ln x)) dif x $ 相同。根据: $ int_2^(+oo) 1/(x ln x (ln ln x)) dif x &= int_2^(+oo) dif(ln x)/(ln x (ln ln x))\ &= int_(ln 2)^(+oo) (dif u)/(u ln u)\ &= int_(ln 2)^(+oo) dif(ln u)/(ln u)\ &= int_(ln ln 2)^(+oo) (dif v)/v\ &= (ln v)|_(ln ln 2)^(+oo)\ &= +oo $ 可知原级数发散。 == P253 5(1) #prob[ 研究级数的敛散性: $ sss int_n^(n+1) e^(-sqrt(x)) dif x $ ] 根据分段积分的定义,有 $ S = sss int_n^(n+1) e^(-sqrt(x)) dif x = int_1^(+oo) e^(-sqrt(x)) dif x $ 令 $u=-sqrt(x)$,则 $dif x = 2 u dif u$。代入得 $ S &= int_1^(+oo) e^(-u) dot 2 u dif u\ &= 2 int_(-1)^(-oo) u e^u dif u\ &= 2 (u-1) e^u |_(-1)^(-oo)\ $ 是收敛的。所以原级数收敛。 == P253 5(3) #prob[ 研究级数的敛散性: $ sss 1/(sqrt(3)^n) (1+1/n)^(n^2) $ ] 注意到: $ lim_(n->+oo) (1/sqrt(3))^n (1+1/n)^(n^2) &= exp lim_(n->+oo) (-n/2 ln 3 + n^2 ln (1+1/n))\ &= exp lim_(x->0^+) (-(ln 3)/(2x) + ln(1+x)/(x^2))\ &= exp lim_(x->0^+) (2ln(1+x) - ln 3 dot x)/(2x^2)\ &= exp lim_(x->0^+) (2x-x^2+o(x^2) - ln 3 dot x)/(2x^2)\ &= exp lim_(x->0^+) (2-ln 3)/(2x)=+oo $ 由于级数的通项不趋于 $0$,故该级数发散。
https://github.com/duskmoon314/THU_AMA
https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch1/1-背景.typ
typst
Creative Commons Attribution 4.0 International
#import "/book.typ": * #show: thmrules #show: book-page.with(title: "背景") = 背景 万物皆数 #sym.arrow.r.double 抽象化 事物 #sym.arrow.r.double 数字 #sym.arrow.r.double $NN, ZZ, QQ, RR, CC$ #theorem("代数 (Algebra)")[ 以字母、未定符代替数字 ] #remark[ 1859年,李善兰翻译为“代数学” ] $ "工程问题" arrow.r.l.double.long_"具体化抽象化"^"抽象化模型化" "数学理论" $
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/evaluation/technology.typ
typst
#import "/components/glossary.typ": gls == Evaluation Technology === Bun Test To comprehensively evaluate the Ungrammar Language Ecosystem, we've strategically employed Bun (@sec-bun) Test as our primary testing framework. Bun Test, a versatile testing tool, not only streamlines the testing process but also aligns seamlessly with our existing project structure, eliminating the need to introduce additional dependencies. Key Benefits of Using Bun Test: - *Efficiency*: Bun Test's speed and performance significantly enhance our testing efficiency. - *Integration*: Its compatibility with our existing Bun-based project simplifies the testing process and reduces overhead. - *Comprehensive Testing*: Bun Test provides a robust set of features for writing and executing various types of tests, ensuring thorough evaluation of our ecosystem. - *Reduced Dependencies*: By leveraging Bun Test, we avoid introducing unnecessary dependencies, maintaining a cleaner and more focused project structure. Overall, Bun Test has proven to be an invaluable tool for evaluating the Ungrammar Language Ecosystem, ensuring its quality, reliability, and performance. === GitHub Actions To ensure the system's reliability and prevent regressions, we've implemented a robust #gls("ci") pipeline using GitHub Actions (@sec-githubactions). This automated process leverages Bun Test to execute comprehensive tests with each code change, safeguarding the integrity of our project. Key Benefits: - *Early Detection of Issues*: GitHub Actions automatically runs tests on every code push, enabling early detection of potential problems before they impact the main codebase. - *Improved Code Quality*: By consistently running tests, we maintain high code quality standards and reduce the risk of introducing regressions. - *Streamlined Development*: GitHub Actions streamlines the development process by automating testing and providing valuable feedback, allowing developers to focus on writing new features. - *Collaboration*: GitHub Actions facilitates collaboration among team members by providing a centralized platform for reviewing and testing code changes. With the integration of GitHub Actions into our workflow, we've established a reliable and efficient #gls("ci") process that significantly enhances the overall quality and stability of our Ungrammar Language Ecosystem. === Manual Test In addition to automated testing with Bun Test, we also conduct thorough manual testing to ensure the ecosystem's functionality aligns with our expectations throughout development and deployment. This dual-pronged testing approach strengthens the reliability and robustness of our system. Key Benefits of Manual Testing: - *Complementary Approach*: Manual testing acts as a valuable complement to automated testing, identifying issues that might be overlooked by automated scripts. - *Real-World Scenarios*: Simulates how end-users will interact with the system, ensuring a seamless and intuitive experience. - *Edge Case Detection*: Helps uncover potential bugs or unexpected behaviors that automated tests might miss. - *Human Intuition*: Leverages human judgment to assess the system's overall usability, performance, and adherence to design requirements. By combining automated and manual testing, we create a comprehensive testing strategy that enhances the quality and reliability of the Ungrammar Language Ecosystem.
https://github.com/LuminolT/SHU-Bachelor-Thesis-Typst
https://raw.githubusercontent.com/LuminolT/SHU-Bachelor-Thesis-Typst/main/template/cover.typ
typst
// 封面 #import "font.typ" : * #import "../body/info.typ" : * #align(center)[ #v(20pt) #table( columns: (140pt, auto, auto), align: horizon, stroke: none, [], [#image("../assets/schoolname.png", width: 120%, height: 9%)], [#image("../assets/logo.png", width: 40%)] ) #table( columns: (auto), rows: (auto, auto ,auto), stroke: none, gutter: 9pt, text( font: "Times New Roman", size: 18pt, weight: "bold" )[SHANGHAI UNIVERSITY], text( font: songti, size: 36pt, )[毕业论文(设计)], text( font: "Times New Roman", size: 16pt, weight: "bold" )[UNDERGRADUATE THESIS (PROJECT)] ) #v(60pt) #text( font : kaiti, size : 18pt, bottom-edge: "descender" )[题 目: #underline(extent: 6pt)[#title]] #v(100pt) #let info_value(body) = { rect( width: 100%, inset: 2pt, stroke: ( bottom: 1pt + black ), text( font: songti, size: 18pt, weight: "medium", bottom-edge: "descender" )[ #body ] ) } #let info_key(body) = { rect(width: 100%, inset: 2pt, stroke: none, text( font: heiti, size: 18pt, weight: "bold", overhang: false, body )) } #grid( columns: (80pt, 180pt), rows : (35pt, 35pt), //gutter: 3pt, // row : (auto ,auto, auto, auto, auto, auto), info_key("学  院"), info_value(college), info_key("专  业"), info_value(major), info_key("学  号"), info_value(id), info_key("学生姓名"), info_value(name), info_key("指导老师"), info_value(teacher), info_key("起讫日期"), info_value(data) ) ]
https://github.com/yan-aint-nickname/uni
https://raw.githubusercontent.com/yan-aint-nickname/uni/main/oop-matrix-cli/diagrams/main.typ
typst
MIT License
// https://xkcd.com/1195/ #import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge #import fletcher.shapes: diamond, parallelogram #set text(font: "Comic Neue", weight: 600) #let chart_main = diagram( node-stroke: 1pt, edge-stroke: 1pt, node((0,0), [Начало], corner-radius: 10pt), edge("-|>"), node((0,1), [Инициализировать генератор\ псевдо-случайных чисел]), edge("-|>"), node((0,3), [Объявить матрицы A и B]), edge("-|>"), node((0,4), [Заполнить матрицы\ случайными числами], extrude: (-2, 0)), edge("-|>"), node((0,5), [Получить пользовательский ввод], extrude: (-2, 0)), edge("-|>"), node((0,6), align(center)[ Ошибка\ ввода ], shape: diamond), edge("l,d", "-|>", [Да]), node((-1,7), [Ошибка], corner-radius: 10pt), edge((0, 6), (0, 8), "-|>", [Нет]), node((0, 8), [Посчитать кол-во элементов\ матриц A, B больше D, Q], extrude: (-2, 0)), edge("-|>"), node((0,9), [D, countA, Q, countB], shape: parallelogram.with(angle: 30deg)), edge("-|>"), node((0,10), [Конец], corner-radius: 10pt), )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/pagebreak-00.typ
typst
Other
// Just a pagebreak. // Should result in two pages. #pagebreak()
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/program-driver-control/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Program: Driver Control", type: "program", date: datetime(year: 2023, month: 8, day: 20), author: "<NAME>", witness: "Al<NAME>", ) With the control scheme and curve strength selected we finished the implementation. Here's the code for the drive curve: ```cpp double calcDriveCurve(double input, double scale) { BattleCh1cken marked this conversation as resolved.if (scale != 0) { return (powf(2.718, -(scale / 10)) + powf(2.718, (fabs(input) - 127) / 10) * (1 - powf(2.718, -(scale / 10)))) * input; } return input; }``` Here's the code for tank drive: ```cpp void Chassis::tank(int left, int right, float curveGain) { drivetrain.leftMotors->move(calcDriveCurve(left, curveGain)); drivetrain.rightMotors->move(calcDriveCurve(right, curveGain)); }; ``` Since LemLib is already controlling our chassis we decided to submit our drive code implementation to LemLib as it was currently lacking this feature. The relevant pull request can be found here: #link("https://github.com/LemLib/LemLib/pull/50")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/microtype_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that lone punctuation doesn't overhang into the margin. #set page(margin: 0pt) #set align(end) #set text(dir: rtl) :
https://github.com/refparo/24xs-zh
https://raw.githubusercontent.com/refparo/24xs-zh/master/common.typ
typst
#let gutter = (90mm - 1em * 17 * 2) / 3 #let typ-24xs = doc => { set text( 7pt, top-edge: 7pt, font: ("<NAME>", "Noto Sans CJK SC"), lang: "zh", baseline: -0.11em, ) show regex("[·“”‘’…]"): set text(font: "Noto Sans CJK SC") set block(spacing: 0pt) set par(leading: 0.25em) show par: it => block( inset: (y: 0.125em), spacing: 1.25em / 4, it ) set page( paper: "cn-business-card", margin: ( x: gutter, y: (54mm - 1.25em * 16.5) / 2 ), ) doc } #let debug-grid = doc => { place( for _ in range(100) { line(length: 100%, stroke: 0.1pt + blue) v(7pt * 1.25 / 4) } ) set block(stroke: 0.1pt + red) doc } #let logo = { show heading: it => it.body heading({ set block(spacing: 0pt) // to offset existing par inset show par: it => block(inset: (y: -0.125em), it) block( inset: ( left: -1.5pt, right: -1.5pt, top: 7pt * 1.25 / 4 * 19 - 48pt, bottom: -7pt * 1.25 / 4 * 2, ), text(48pt, top-edge: 48pt)[2#h(1fr)4#h(1fr)X#h(1fr)S] ) block( inset: ( top: 7pt * 1.25 / 4 * 6 - 12pt, bottom: 0pt, ), text(12pt, top-edge: 12pt)[微#h(1fr)型#h(1fr)单#h(1fr)人#h(1fr)冒#h(1fr)险] ) }) } #let rules-page = doc => page(columns(2, gutter: gutter, doc)) #let adventure-page = (..cells) => page(grid( columns: (1fr, 1fr), rows: (1fr, 1fr), column-gutter: gutter, row-gutter: 1.25em * 0.5, ..cells )) #let random-table = (title, ..cells) => grid( columns: 1, rows: 2, block( width: 100%, height: 10em / 7, inset: (x: 0.25em), fill: black, stroke: 0.5pt, align(horizon, text(white, weight: "bold", title)) ), grid( columns: (auto, 1fr), rows: 6, ..cells.pos().enumerate(start: 1) .map(((i, x)) => ( block( width: 10em / 7, height: 10em / 7, fill: silver, stroke: 0.5pt, align(horizon + center)[*#i*] ), block( width: 100%, height: 10em / 7, inset: (x: 0.25em), stroke: 0.5pt, align(horizon, x) ) )) .flatten() ) )
https://github.com/GeorgeDong32/GD-Typst-Templates
https://raw.githubusercontent.com/GeorgeDong32/GD-Typst-Templates/main/functions/style.typ
typst
Apache License 2.0
#let line_height = 1em #let fonts = ( text: ("CMU Serif", "Source Han Serif SC", "Source Han Serif"), sans: ("Source Han Sans SC", "Source Han Sans"), code: ("Cascadia Code", "Consolas"), ) #let textbf(it) = block( text( font: fonts.sans, weight: "semibold", it ) ) #let textit(it) = block(text(style: "italic", it))
https://github.com/fenjalien/cirCeTZ
https://raw.githubusercontent.com/fenjalien/cirCeTZ/main/examples/exclusive-or.typ
typst
Apache License 2.0
#import "../../typst-canvas/canvas.typ": canvas #lorem(30) #figure( canvas({ import "../../typst-canvas/draw.typ": * import "../circuitypst.typ": node node("nand gate", (0,1), name: "g1") content("g1.out", [#h(0.5em) Q], anchor: "left") line("g1.in 1", (rel: (0, 0.5)), name: "l1") line("g1.in 2", (rel: (0, -0.5)), name: "l2") node("nand gate", "l1.end", anchor: "out", name: "g2") node("nand gate", "l2.end", anchor: "out", name: "g3") line("g2.in 2", "g3.in 1", name: "l3") node("nand gate", "l3.center", anchor: "out", name: "g4") line("g4.in 1", (rel: (0, 0.75)), name: "l4") line("g4.in 2", (rel: (0, -0.75)), name: "l5") line("g2.in 1", "l4.end") line("g3.in 2", "l5.end") line("l4.end", (rel: (-0.5, 0)), name: "l6") line("l5.end", (rel: (-0.5, 0)), name: "l7") content("l6.end", [A #h(0.5em)], anchor: "right") content("l7.end", [B #h(0.5em)], anchor: "right") node("circ", "g4.out") node("circ", "l4.end") node("circ", "l5.end") }), caption: [Exclusive OR] ) #lorem(30)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/line_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Test errors. // // // Error: 12-19 point array must contain exactly two entries // #line(end: (50pt,))
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/nouns.typ
typst
MIT License
#let gbpplanner = [GBP Planner]
https://github.com/ckunte/m-one
https://raw.githubusercontent.com/ckunte/m-one/master/inc/crane.typ
typst
= Offshore crane API Spec 2C@api_spec_2c and EN 13852-1@en_13852_1 are two well known standards that offer guidance in developing minimum offshore pedestal-mounted crane requirements. They represent Gulf of Mexico and the North Sea respectively. API specification considers Gulf of Mexico to be of "very mild sea and wind conditions" ($section$5.4.4 Legacy Dynamic Method). Environmental conditions in the Gulf of Mexico are indeed mild when hurricanes are excluded. Also, given the unpredictable variation in hurricane strengths and hence the impracticality of designing for such events, offshore facilities in the Gulf of Mexico are operated as _manned-evacuated_. In other words, operations (including crane operations) are suspended and the facility evacuated in the event of an impending hurricane in the facility's path. When a sizeable number of assets are validated by their use, standards developed primarily for a specific domain find acceptance internationally. However, liberal use is never without a catch, as standards often carry certain domain specific assumptions and criteria that may need revisiting when considered for a domain outside the primary for which it is written and valid for. Take for instance the primary purpose of offshore cranes mounted on pedestals on offshore platforms --- fixed or floating. They lift cargo and supplies off a floating vessel, which in turn are influenced by incoming waves. Off-board lift, as API Spec 2C explains, is "the hoisting velocity at the elevation where lift is initiated (i.e., supply boat deck level) shall be fast enough to avoid re-contact after the load is lifted." == Off-board lift using API Spec 2C Minimum required steady hoisting velocity (in ft/s) for off-board lift as per $section$5.4.5.2, API Spec 2C: For $H_("sig") lt.eq$ 6ft: $ V_("hmin") = 0.033 + 0.098 dot H_("sig") $ For $H_("sig")$ > 6ft: $ V_("hmin") = 0.067 dot (H_("sig") + 3.3) $ == Off-board lift using EN 13852-1 Minimum hoisting and lowering velocity (in m/s) for lifting from/to a supply vessel in EN 13852-1 ($section$B.4) is given as follows: $ V_H = K_H sqrt(V_D^2 + V_C^2) $ where, - $V_D$ -- vertical velocity of load's supporting deck for lifting to or from a supply vessel (m/s), from Table B.2 - $V_C$ -- vertical velocity of the crane boom tip due to the movement of the crane base (m/s), from Table B.3 - $K_H$ -- velocity factor coving (single fall, multiple fall) reeving and for both no-hook load as well as at rated capacity $ V_D = (6.0 H_("sig")) / (H_("sig") + 8.0) $ For crane on bottom-founded structures, there is no movement of the crane base, and therefore, $V_C$ = 0. I wrote a little code to compare the two standards over the weekend (see below) to produce the following graph. #figure( image("/img/vhmin.svg", width: 100%), caption: [Comparing minimum hoisting velocities between API Spec 2C and EN 13852-1] ) <cr1> A couple of observations: + API prescription for $V_("hmin")$ covers supply vessels, while EN offers two additional options, viz., barge, and sea surface. (Graphs for barge or sea surface are not shown in the above, but can be separately generated, if desired.) + EN is explicit about reeving efficiency --- note the reduced velocity requirements in the case of multi-fall reeving. Looking at the two graphs above, i.e., for API and for EN, the multi-part reeving option appears to be somewhat close to API prescription in terms of $V_("hmin")$. It could be that API considers multi-part reeving efficiency in its prescription, even though it does not mention in $section$5.4.5.2. Now to the crux of the matter on whether or not a standard's recipe enables safe-clearing of the package lifted before the next wave crest appears. The package travel can be calculated, for a given significant wave height ($H_("sig")$) and corresponding period (T), as follows: $ h = V_("hmin") dot T $ Testing API Spec 2C recipe for the Australian Northwest Shelf environment: #figure( table( columns: (1fr, 1fr, 1fr, auto), inset: 10pt, align: horizon, [$H_("sig")$], [_T_], [$V_("hmin")$], [h], [1.4m], [4.9s], [0.14m/s], [0.72m < $H_("sig")$ (Not Good)], [2.7m], [5.7s], [0.25m/s], [1.42m < $H_("sig")$ (Not Good)], [3.6m], [6.4s], [0.30m/s], [1.98m < $H_("sig")$ (Not Good)], ), caption: [$V_("hmin")$ based on API Spec 2C], ) <vcr1> From @vcr1, clearly it does not work. In other words, a lifted package experiences re-contact by the next wave crest before clearing safely. Now let's test this for EN 13852-1 again for the Australian Northwest Shelf environment: #figure( table( columns: (1fr, 1fr, 1fr, auto), inset: 10pt, align: horizon, [$H_("sig")$], [_T_], [$V_("hmin")$], [h], [1.4m], [4.9s], [0.44m/s], [2.19m > $H_("sig")$ (OK)], [2.7m], [5.7s], [0.75m/s], [4.31m > $H_("sig")$ (OK)], [3.6m], [6.4s], [0.92m/s], [5.96m > $H_("sig")$ (OK)], ), caption: [$V_("hmin")$ based on EN 13852-1], ) <vcr2> From @vcr2, it can be seen that the recipe offered by EN 13852-1 clears the package comfortably before the next wave crest arrives. So EN's recipe works for NWS where API's does not. Code for generating @cr1 is as follows. #let vhmin = read("/src/vhmin.py") #{linebreak();raw(vhmin, lang: "python")} IOGP specification S-618@iogp_s618 issued in Dec 2018 now fixes the low velocity in API's off-board lift recipe, which stuck out like an anomaly#footnote[To be sure, my interest in API Spec 2C is now academic, and I am not judging it for its merits or demerits, since API's application domain is primarily the US. However, due to the fact that API standards are generally good to very good that the engineering community tends to adopt them across domains (outside USA) --- sometimes without pausing to consider whether or not cross-domain application is appropriate.], see plot above, and is now in step with that of EN 13852-1, which can be seen in the updated plot below. #figure( image("/img/vhmin_iogp.svg", width: 100%), caption: [ Crane (off-board) hoisting velocity updated with IOGP S-618 recommendations ], ) <ci8> Code for generating @ci8 is as follows. #let vhmin_iogp = read("/src/vhmin_iogp.py") #{linebreak();raw(vhmin_iogp, lang: "python")} $ - * - $
https://github.com/levinion/typst-dlut-templates
https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/templates/thesis/changelog.typ
typst
MIT License
#import "../util/style.typ":font_size,font_family,vspacer #import "../util/functions.typ":invisible_heading #let changelog(content)={ if content != none { set align(center) set text(font: font_family.heiti, size: font_size.xiao_san) [修改记录] invisible_heading()[修改记录] v(-8pt) set align(left) set text(font: font_family.songti, size: font_size.xiao_si) set par(leading: 0.8em, justify: true, first-line-indent: 2em) set block(spacing: 0.8em) content vspacer(6) set align(right) let spacer = 20% [记录人(签字):#h(spacer)\ 指导教师(签字):#h(spacer)\ ] pagebreak(weak: true) } }
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2017/MS-11.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [1], [马龙], [CHN], [3649], [2], [樊振东], [CHN], [3454], [3], [许昕], [CHN], [3311], [4], [迪米特里 奥恰洛夫], [GER], [3255], [5], [林高远], [CHN], [3237], [6], [水谷隼], [JPN], [3236], [7], [蒂姆 波尔], [GER], [3172], [8], [张继科], [CHN], [3161], [9], [闫安], [CHN], [3150], [10], [方博], [CHN], [3097], [11], [李尚洙], [KOR], [3045], [12], [郑荣植], [KOR], [3036], [13], [梁靖崑], [CHN], [3014], [14], [张本智和], [JPN], [3011], [15], [丹羽孝希], [JPN], [2997], [16], [西蒙 高兹], [FRA], [2994], [17], [弗拉基米尔 萨姆索诺夫], [BLR], [2989], [18], [#text(gray, "朱世赫")], [KOR], [2976], [19], [吉田雅己], [JPN], [2963], [20], [雨果 卡尔德拉诺], [BRA], [2949], [21], [马克斯 弗雷塔斯], [POR], [2936], [22], [吉田海伟], [JPN], [2934], [23], [于子洋], [CHN], [2932], [24], [庄智渊], [TPE], [2923], [25], [松平健太], [JPN], [2913], [26], [巴斯蒂安 斯蒂格], [GER], [2900], [27], [#text(gray, "尚坤")], [CHN], [2899], [28], [夸德里 阿鲁纳], [NGR], [2896], [29], [周雨], [CHN], [2895], [30], [特里斯坦 弗洛雷], [FRA], [2892], [31], [黄镇廷], [HKG], [2886], [32], [丁祥恩], [KOR], [2885], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [33], [乔纳森 格罗斯], [DEN], [2883], [34], [奥马尔 阿萨尔], [EGY], [2879], [35], [SHIBAEV Alexander], [RUS], [2874], [36], [上田仁], [JPN], [2872], [37], [马蒂亚斯 法尔克], [SWE], [2866], [38], [博扬 托基奇], [SLO], [2864], [39], [卢文 菲鲁斯], [GER], [2863], [40], [朴申赫], [PRK], [2861], [41], [LI Ping], [QAT], [2852], [42], [朱霖峰], [CHN], [2849], [43], [#text(gray, "唐鹏")], [HKG], [2846], [44], [徐晨皓], [CHN], [2844], [45], [吉村真晴], [JPN], [2841], [46], [艾曼纽 莱贝松], [FRA], [2833], [47], [克里斯坦 卡尔松], [SWE], [2829], [48], [#text(gray, "陈卫星")], [AUT], [2826], [49], [GERELL Par], [SWE], [2826], [50], [张禹珍], [KOR], [2824], [51], [林钟勋], [KOR], [2821], [52], [<NAME>], [GER], [2818], [53], [<NAME>], [HKG], [2815], [54], [森园政崇], [JPN], [2814], [55], [帕特里克 弗朗西斯卡], [GER], [2812], [56], [贝内迪克特 杜达], [GER], [2808], [57], [ROBLES Alvaro], [ESP], [2805], [58], [吉村和弘], [JPN], [2793], [59], [安东 卡尔伯格], [SWE], [2791], [60], [#text(gray, "李廷佑")], [KOR], [2791], [61], [沙拉特 卡马尔 阿昌塔], [IND], [2790], [62], [赵胜敏], [KOR], [2788], [63], [TAZOE Kenta], [JPN], [2787], [64], [安德烈 加奇尼], [CRO], [2786], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [65], [HO Kwan Kit], [HKG], [2785], [66], [ROBINOT Quentin], [FRA], [2784], [67], [利亚姆 皮切福德], [ENG], [2781], [68], [帕纳吉奥迪斯 吉奥尼斯], [GRE], [2780], [69], [大岛祐哉], [JPN], [2769], [70], [周恺], [CHN], [2768], [71], [OUAICHE Stephane], [ALG], [2765], [72], [村松雄斗], [JPN], [2761], [73], [KOU Lei], [UKR], [2759], [74], [王臻], [CAN], [2754], [75], [及川瑞基], [JPN], [2754], [76], [斯特凡 菲格尔], [AUT], [2749], [77], [林昀儒], [TPE], [2749], [78], [DRINKHALL Paul], [ENG], [2743], [79], [WANG Zengyi], [POL], [2743], [80], [达科 约奇克], [SLO], [2741], [81], [PERSSON Jon], [SWE], [2738], [82], [高宁], [SGP], [2738], [83], [#text(gray, "MATTENET Adrien")], [FRA], [2735], [84], [雅克布 迪亚斯], [POL], [2734], [85], [MACHI Asuka], [JPN], [2733], [86], [TAKAKIWA Taku], [JPN], [2732], [87], [MONTEIRO Joao], [POR], [2729], [88], [基里尔 格拉西缅科], [KAZ], [2728], [89], [薛飞], [CHN], [2728], [90], [周启豪], [CHN], [2722], [91], [奥维迪乌 伊奥内斯库], [ROU], [2722], [92], [金珉锡], [KOR], [2721], [93], [TREGLER Tomas], [CZE], [2721], [94], [廖振珽], [TPE], [2718], [95], [HABESOHN Daniel], [AUT], [2718], [96], [蒂亚戈 阿波罗尼亚], [POR], [2713], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [97], [木造勇人], [JPN], [2713], [98], [#text(gray, "WANG Xi")], [GER], [2712], [99], [MATSUYAMA Yuki], [JPN], [2708], [100], [诺沙迪 阿拉米扬], [IRI], [2705], [101], [PARK Ganghyeon], [KOR], [2697], [102], [KIM Donghyun], [KOR], [2692], [103], [ZHAI Yujia], [DEN], [2689], [104], [ELOI Damien], [FRA], [2688], [105], [陈建安], [TPE], [2687], [106], [托米斯拉夫 普卡], [CRO], [2684], [107], [KANG Dongsoo], [KOR], [2683], [108], [RYUZAKI Tonin], [JPN], [2683], [109], [尼马 阿拉米安], [IRI], [2683], [110], [#text(gray, "FANG Yinchi")], [CHN], [2681], [111], [SALIFOU Abdel-Kader], [FRA], [2679], [112], [#text(gray, "HE Zhiwen")], [ESP], [2678], [113], [GNANASEKARAN Sathiyan], [IND], [2676], [114], [王楚钦], [CHN], [2670], [115], [雅罗斯列夫 扎姆登科], [UKR], [2669], [116], [江天一], [HKG], [2668], [117], [詹斯 伦德奎斯特], [SWE], [2665], [118], [LANDRIEU Andrea], [FRA], [2662], [119], [阿德里安 克里桑], [ROU], [2661], [120], [LIVENTSOV Alexey], [RUS], [2660], [121], [<NAME>], [JPN], [2659], [122], [SAKAI Asuka], [JPN], [2656], [123], [<NAME>], [SWE], [2655], [124], [<NAME>], [FIN], [2655], [125], [NG Pak Nam], [HKG], [2649], [126], [<NAME>], [SVK], [2645], [127], [神巧也], [JPN], [2642], [128], [塞德里克 纽廷克], [BEL], [2641], ) )
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/entries/early_season/intro_meta.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/templates/entries.typ": * #import "/templates/headers.typ": * #import "/templates/text.typ": * #create_footerless_page( title: [Introduction to the Meta], date: [September 9th, 2023], content: [ #box_header( title: [Watching Mall of America], color: purple.lighten(60%) ) \ #entry_text() To get some ideas on how we should build our bot, we decided to watch the mall of america signature event, which is the first event of the season. We got some good ideas from this, such as what type of launcer to make, and overall what the game will look like and how it will play. #box_header( title: [Intake], color: yellow.lighten(60%) ) \ #entry_text() An "intake" typically refers to a mechanical component designed, collected, or "intake" objects, to the specific challenge or competition, the acorns.The intake is an essential part of the robot, particularly in games or tasks that require collecting and manipulating objects. #grid( columns: (1fr,1fr), rows: auto, align(center)[#entry_header(title: [Double Flex Wheel Intake]) \ ], align(center)[#entry_header(title: [Rubber Band Intake]) \ ], align(center)[#image("/assets/intakes/intake1.png", height: 250pt) #entry_text() Credit: 938X \ \ ], align(center)[#image("/assets/intakes/intake2.png", height: 250pt) #entry_text() Credit: 1138N \ \ ], align(left)[ #entry_text() One intake that we consider making. The unique aspect of this intake is that it makes use of the new 5.5 watt motors. There are two separate intakes, one on each side of the chassis, spinning the opposite direction of each other which allows them to suck or split out any acorn. When collecting an object, the flex wheels pivot horizontally, compressing the flex wheels and obtaining a firm grip on the acorn. They will push the acorn up a ramp and into a nesting place. ], align(left)[ #entry_text() Unlike the vertical intake, it doesn't make use of any flex wheels, instead sprockets. There are two half cuts connected on the inner-side of the chassis with sprockets at the end. Connecting the sprockets are several rubber bands. These rubber bands rub against the acorn, removing the need for a lexan ramp. The rubber bands force the acorn into a nested area. ] ) ] ) #create_headerless_page( witness: [Deb], design: [Jin], content: [ #box_header( title: [Outtake], color: yellow.lighten(60%) ) \ #entry_text() An “outtake” typically refers to a mechanism or system designed to shoot game pieces or objects from the robot. Outtakes are used to score or dispose of game pieces, completing specific tasks or objectives set by the rules of the competition. #grid( columns: (1fr,1fr), rows: auto, align(center)[#entry_header(title: [Catapult]) \ ], align(center)[#entry_header(title: [Puncher]) \ ], align(center)[#image("/assets/outtakes/cata.png", height: 250pt) #entry_text() Credit: 79298Z \ \ ], align(center)[#image("/assets/outtakes/puncher.png", height: 250pt) #entry_text() Credit: 7358 \ \ ], align(left)[ #entry_text() A catapult is a mechanical device that uses stored energy to launch or project an object, often with significant force. It uses a set of gears, one with a slip. The two gears will continually spin, pulling the catapult arm down while pulling on two rubber bands. When the two gears slip and lose contact, the rubber bands release, flinging the catapult area. Once the arm hits the stop, all the potential energy transfers into kinetic energy, flinging the acorn. ], align(left)[ #entry_text() The puncher uses rubber bands. When activated, the release mechanism rapidly unleashes this stored energy, propelling a game piece with force and precision toward a target or scoring zone. The loading chamber holds the acorn, and the activation of the release mechanism can be controlled manually or through programming. ] ) ] )
https://github.com/dark-flames/apollo-typst
https://raw.githubusercontent.com/dark-flames/apollo-typst/main/README.md
markdown
Apache License 2.0
# apollo-typst Typst static site template based on [Zola](https://getzola.org), [typst.ts](https://github.com/Myriad-Dreamin/typst.ts), and [apollo](https://github.com/not-matthias/apollo). See a live preview [here](https://dark-flames.com). ## Features - Full functionality of [Zola](https://getzola.org) and [apollo](https://github.com/not-matthias/apollo). - Supports both markdown and [typst](https://typst.app/). ## Usage ### Preparation - Install `yarn` and execute `yarn install`. - Install `zola` following its [document](https://www.getzola.org/documentation/getting-started/installation/). - Install `typst-ts-cli` following its [document](https://github.com/Myriad-Dreamin/typst.ts/tree/main?tab=readme-ov-file#concept-precompiler). - Configure your site in `config.toml`. Full configuration options can be found in the [apollo documentation](https://github.com/not-matthias/apollo/blob/main/content/posts/configuration.md). ### Write posts with Typst - `appollo-typst` support both single files and workspaces: - If a subdirectory of typ contains `main.typ`, it will be treated as a workspace, with `main.typ` serving as the entry point. - Otherwise, each .typ file within the subdirectory will be compiled independently. - Create a `.md` file in the `content` directory and write the metadata of the post in the front matter. Then, add the `extra.typst` field to the front matter, specifying the name (relative path to `typ/`) of the typst file or the typst workspace. The content of the markdown file will be ignored; instead, the content from the typst file will be utilized. For an example, refer to `content/posts/test.md`. - If the typst output has its own title, you can set `extra.hide_title = true` to prevent zola from generating a redundant title. ### Build ```shell # If you updated the frontend yarn build:fe # If you updated the typst yarn build:typ # Final zola build zola build ``` ### Develop ```shell yarn serve ``` ### Deployment To deploy your site to GitHub Pages, you can use the provided GitHub Action in branch `action-v1`: Example .github/workflows/deployl.yaml ```yaml name: Deploy on: workflow_dispatch jobs: deploy: runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v4 - name: deploy uses: dark-flames/apollo-typst@action-v1 with: access-token: ${{ secrets.ACCESS_TOKEN }} deploy-branch: static # deploy-repo: ${{ another/repo }} ``` If you want to use custom page, remember to put `CNAME` file in the `static/`.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-23.typ
typst
Other
// Error: 11-13 value must be strictly positive #calc.log(-1)
https://github.com/m-pluta/bias-in-ai-report
https://raw.githubusercontent.com/m-pluta/bias-in-ai-report/main/report/images/emotion_dist.typ
typst
#import "@preview/cetz:0.2.1": canvas, chart, draw #let data = ( ([`'neutral'`], 0.13), ([`'happy'`], 0.76), ([`'angry'`], 0.03), ([`'sad'`], 0.01), ([`'fear'`], 0.0), ([`'surprise'`], 0.02), ([`'disgust'`], 0.01), ([`'contempt'`], 0.04), ) #canvas({ chart.barchart( mode: "basic", size: (7, 3.7), value-key: 1, bar-width: 0.6, x-max: 1, data) })
https://github.com/taylorh140/tySheetSu
https://raw.githubusercontent.com/taylorh140/tySheetSu/main/README.md
markdown
# tySheetSu Typst Sheet Super Interface for xlsx files.
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/typ/templates/term.typ
typst
Apache License 2.0
#let term-state = state("term", (:)) #let reset-term-state = term-state.update(it => (:)) #let _term(term-list, term, postfix: none, en: none) = locate(loc => { let s = term-state.at(loc) if term in s { [「#term-list.at(term)#("」"+postfix)] } else { let en-term = term if en != none { en-term = en } [「#term-list.at(term)」(#en-term#(")"+postfix)] } }) + term-state.update(it => { it.insert(term, "") it })
https://github.com/ARKye03/MathSummary
https://raw.githubusercontent.com/ARKye03/MathSummary/main/readme.md
markdown
# Mini Summary Formulas, report, and notes for making my life easier. (I hope, it depends if I keep working on it or not.) ## Contents The pdf file is like a math treasure trove, full of formulas and tricks for calculus and trigonometry. Here's what you'll find inside: 1. **Integrals**: These are formulas for finding the area under curves. Think of it as finding the total value of something changing over time. 2. **More Integrals**: Here, we tackle trickier integrals involving sums, differences, and even constants multiplied by functions. 3. **Integrals with a Twist**: Ever heard of using a different variable for integrals? This section shows you how. 4. **Derivatives**: This is all about rates of change. Whether it's the speed of something moving or how something is growing, these formulas have you covered. 5. **More Derivatives**: We dive into derivatives of more complex functions, like products, quotients, and composites. 6. **Trig Tricks**: These are your go-to formulas for playing with triangles and circles. They help simplify trigonometric expressions. 7. **Adding and Subtracting Angles**: Here, we have formulas for breaking down angles into simpler parts. 8. **Double Trouble**: Double angles mean double the fun! These formulas make dealing with double angles a breeze. 9. **Facing Negatives**: Negative angles? No problem. These formulas help you handle them like a pro. 10. **Halving the Angle**: Sometimes you need to cut an angle in half. These formulas show you how to do it neatly. ## Usage To view the results, download the file from releases and open it in a PDF viewer. Otherwise, you can clone the repository and compile the file yourself. To compile the file, you will need [Typst](https://typst.app/), then run the following command in root directory of the repository: ```sh typst compile src/main.typ # Result in src/main.pdf ``` Or if you use nix: ```sh nix build # Result in result/main.pdf ``` ## Development Install typst, or use `nix develop` with the provided `flake.nix` to enter my devShell. ### Workflows used - [Create Release](https://github.com/marketplace/actions/create-release) - [Setup Typst](https://github.com/marketplace/actions/setup-typst) ### Contributing If you find any errors in the formulas, or if you have any formulas that you would like to add, please feel free to make a pull request.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/049%20-%20The%20Brothers'%20War/002_Episode%202%3A%20The%20Beginning.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 2: The Beginning", set_name: "The Brothers' War", story_date: datetime(day: 20, month: 10, year: 2022), author: "<NAME>", doc ) #strong[69 AR] Tawnos's civil factory was a clamor of human and machine, a cacophony at all hours. Artificers and laborers of all rank and classification crisscrossed the vast shop floor, pushing carts and leading older civils laden with freshly machined bearings, bolts, modular plating, canvas sheathing, and racks of new weapons. The suspended forms of new civils being retooled for war hung from clattering conveyor belts and slowly moving racks. The regimented production environment Tawnos had designed, with its poured stone floor and painted lines intended to guide people and machines along the safest and most efficient paths, had never seen such frantic, barely ordered commotion. He stood above it all, watching from his office cupola behind glass as his dream of a mechanized peace lifted its veil, revealing its bloody truth. Urza and Mishra never designed anything but machines meant to kill. Tawnos could not speak for Mishra's tutelage, but Urza had been a teacher by example; Tawnos had been clever in his youth, a toymaker of exceptional skill and a wunderkind engineer, but he was only a candle next to Urza's solar brilliance. All Tawnos knew he owed to Urza's instruction. From clever toymaker to master artificer, Urza's steady hand had molded Tawnos as skillfully and distantly as Urza had shaped the face of the world. Tawnos squeezed his knuckles white as if trying to wring the water from the metal railing of his office's observation deck. His civils—how could he have lied to himself that those machines could be bent to any purpose other than war? Tawnos had sketched original plans for Penregon's civils, but the very theory of their design was based off machines Urza had devised—machines meant only to burn, wreck, and ruin. The civils' delicate yet sturdy manipulators, refined to hold construction tools and tote harvested resources, were so easily adapted to the use of weapons, because they had first been designed for Urza's avengers. The civils' joints and mounting points were universal not because they needed to be able to accept replacement parts from Penregon's stockpile, but because Urza required his war machines be capable of field repair. Tawnos turned from his solitary observation, face a grotesque twist of anger and pain. The most terrible revelation hit him with unflinching clarity: Of every aspect of the machines, none was more ruinous than their power supply. The powerstones of the Thran. Carefully cleaved and polished, these powerstones animated the civils as they had both Urza and Mishra's war machines. In a bitter moment, Tawnos realized that Penregon's stockpile would dry out in the coming years. Without an alternative source or method by which to power Penregon, the people's appetite would not abate—it would rage. By his eagerness to offer his aid, he had only reset the stage: a return to the condition the world was in before the beginning of the Brothers' War seemed inevitable. Without any other way to keep the lights on, with winter coming, war would rage again. It was only a matter of time. Tawnos sank further in his chair, staring at the mound of papers and texts on his desk. The sole library collecting the knowledge of a world long gone. He looked over the old folios, rolled blueprints, notebooks, and bound sheafs; anything he could grab before the end, anything of his master's works. Against this archive of brilliance, Tawnos was a diviner. An augur, not an engineer. Worse, a weapons-maker. Tawnos clenched his fists and a deep, sinking feeling tugged at him. In his youth, his ambition drove him to soaring heights. His ego would not let him stay content as a toymaker. Now, with a dull ache he recognized that if all he had ever done was refine the work of others, he might have been less culpable for the death of the world. If he had spent his life reading the steaming organs of slaughtered bulls for gullible kings and queens, he would have done less harm. #figure(image("002_Episode 2: The Beginning/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Tawnos's eyes fell upon the corner of a little notebook familiar to him, partially buried on his desk. It was not one of Urza's—it was his own notebook. In it were his original designs—mechanical hawks and snakes, intricate complications, mechanisms for efficient use of powerstones, and designs of a living weapon that blended clay and artifice into a killer. Tawnos tugged that book out from under the stack of paper, opened it, and thumbed through. It was full of wonderful diagrams, precisely drawn lines, and well-reasoned figures. Notes, jotted quickly in different colors of ink and fading graphite, spoke to the lightning moments of inspiration, revision, iteration. His handwriting, faster and more confident in his youth, showed no hint of doubt. Back then, he had been assured of his work. Fulfilled by the elegance of the weapons he designed. Justified by their purpose: the defense of the realm, the defeat of their enemies. What had changed between then and now but the uniform of their foes? The world changed. He had changed. Behind Tawnos the sound of creation, muffled by the large panes of glass enclosing his office, was unending. Workers strapped thick, weather-treated canvas sheaths over the civils' vulnerable joints and welded on heavy armor plates over critical components. Brilliant young artificers compiled and reviewed the orders and commands soldiers in the field would use to direct the civils in warfare. Officers of the scouts and city guard walked in small groups, learning from engineers the limitations and operational abilities of these adapted war machines. Across the city, powerstone-lit streetlights and municipal heaters went dark as technicians pried even these small chips from their mountings so that they could be installed in the civils' chests, in the pommels of their powered chain-swords, the cores of incandescent lances. Making peace into war once more, all on Tawnos's orders. He closed his notebook and set it atop the pile of Urza's designs. "Send them all into the sea," Tawnos whispered. He thought of Kayla and hoped she would stay true to her promise. He thought of another woman, Ashnod, and wondered if now, after the end of the world, there was still time. First, however, he would take his first brave action in many years. His first original idea. Tawnos would lead, finally; he would change the world for the better. He looked down at the few pages he had torn from his book: A mechanical snake, a bird, a mouse. His toys. A different method. He tucked them into his pocket. In the dark, Tawnos smiled. No one on the factory floor saw the fire until it was too late. It consumed Tawnos's office. Flames licked the glass, drowning everything inside in a stinking, roiling conflagration of burning paper and ink. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The Siege of Penregon lasted a single day and by nightfall had devolved into two smaller fights: The first was the expected contest, the bloody aftermath of the Tal crusaders' failed attempt to take the city from the outside. As the sun slipped below a gray horizon, Penregon's defenders stalked out from the lone, gore-choked breach in the city walls to route the Talite infantry. The crusaders had failed to exploit their only opening; now the survivors staggered away into the night, leaving the dead behind and the wounded moaning and crawling after them. In the distance, between the large body of the march now decamping and Penregon's victorious defenders, grim horsemen in heavy armor waited with clean weapons and dark gazes turned toward the city. Rearmed civils picked their way across the tumbled stone blocks of the breach, their weapons and cores glowing with the waste heat cast by their old powerstones. Outnumbered by the machines and their human counterparts, the Talite cavalry could only watch as Penregon's defenders took prisoners and collected the dead. #figure(image("002_Episode 2: The Beginning/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) The second battle was more widespread: Raddic's forces had at some point—likely the prior year, but no one could be certain—snuck zealots of their faith into the residential and merchant districts of Penregon. Over the long, dark, and cold months of winter, these evangelists had proselytized, cultivating secret cults of the faithful. These followers of Tal's word cursed the machine and the mage both. Animated by evangelical fervor, they saw demons in the smooth metal armature of Tawnos's civils, devils in the few remaining scholars of the Path. Though there was no magic in Penregon, artifice was fuel enough for the faithful. The status of their lives, whether they lived through the war or were born in its wake, was a perfect kindling. The conflagration sparked with the arrival of the main body of the Talite crusaders. With Raddic's declaration refused and the city gates closed, the Talites in the city surged to action. In the pre-dawn hours of the siege morning, as the Talite army was forming out in the fields before Penregon, explosions and fires rocked the city. Tawnos's factory, many of the residential districts, and several merchant ships in the harbor burned. Black-clad zealots ran into the crowds, attacking the city guard and old civils who came to put out the fire. The city's defenders were slow to respond, but mobilized en masse, bolstered by reinforcements from the wall. The Talites were driven by fervor, but Penregon's people fought for their homes. Alley by alley, street by street, Penregon's civils and militia drove the Talites back to their safehouses. By midday, hundreds were dead and fires raged through the city, battled by brigades of volunteer firefighters. By evening, the worst of the fighting was done, and only a handful of the most die-hard cultists remained in the city, barricaded and surrounded. Kayla had spent the brutal day in a well-defended post with the commanders of the city guard and militia. Jarsyl was with her. To leave her grandson anywhere other than at her side in such danger was unthinkable; she had lost one son to war and would be damned to risk another of her blood to the blades, even if it meant Jarsyl seeing her not as his grandmother but as his queen. As leader of the city, Kayla was not just a witness to the military's cold calculus. When her commanders hemmed over pulling rearmed civils from the wall to fight the cultists inside, they turned to Kayla to break their deadlock. When the scouts begged for reinforcements, they turned to Kayla to order Penregon's militia levies to the breach. When dawn broke and saw the walls successfully defended, her staff needed to know—do they execute the captured Talites, jail them, or exile them? The precise tactics of the day fell to her commanders; Kayla was there to be the city's conscience, the speaker for Penregon, the one who determined who lived and who died. The following morning Kayla stood with a cloth tied around her mouth and nose, surveying the fire-blackened ruins of Tawnos's factory. The charred skeleton of the large building jutted up into the gray sky, damp and smoking, stinking of oil and the foul chemicals that fed and were consumed by the blaze. Slag piles and ember-marbled lumps of partially melted civils packed the building's footprint. "The fire broke out during the late shift," Myrel said, their voice muffled through their own cloth mask. "The supervisor I spoke with said it started in Tawnos's office." Myrel pointed toward an otherwise unidentifiable tangle of metal and slag. "I'm sorry ma'am, but we haven't found him—here, at his quarters, or among the dead." Kayla nodded. Tawnos was gone. "And the workers?" "Everyone else was able to escape," Myrel said. "Some who tried to extinguish the fire suffered from inhaling the smoke, but they will be fine with rest and good air. We lost the civils on the floor, however—at least a dozen." "This was not an attack," Kayla said. "The blaze was sudden," Myrel said, frowning. "And all of Urza's old plans, Tawnos's work from the war—" "Look around, Myrel," Kayla interrupted her captain. "Nothing else burned. No one else died. The workers said the fire began in Tawnos's office while he was there. It wasn't an explosion, and no one noticed until the smoke had flooded the upper levels." Myrel grunted, agreeing. "Tawnos did this," Kayla said. She walked into the ruin without waiting for a response from her scout captain. The cloth mask she wore cut the stink somewhat, but the fire had been mighty, and the tang of burnt metal still wrinkled her nose. The few workers sifting through the damp ruins stopped their labors and leaned on their tools, watching Kayla with detached interest. Kayla stopped before the heap that had been Tawnos's office, now a steaming lump of matted ash and metal where it collapsed after burning through the night. No papers or books remained, nothing but some dirty, faintly glowing chips of powerstones he must have kept on his desk. "You selfish old man," Kayla whispered to the ashes. The ticking and cooling of burnt metal. The hiss of dripping water, plunking into still-hot piles of ash. The scrape of shovels on stone as laborers returned to work. These were the only responses. No bright laughter or solemn murmurs, no polite cough or strong, steady voice. Another connection to her old life severed. "You left me nothing," Kayla said. No half-burnt journal or wondrously preserved folio of plans remained from which they could recreate his civils or devise new automatons to help Penregon face the coming winter. A season's worth of good weather and harvest stretched before her, and but for the spare dozens of civils that remained, the city would be forced once more to return to human labor. Kayla knew from haunting Tawnos's office during the last winter that the few remaining civils had short lives ahead of them—their powerstones were old and worn, harvested from war machines that all but used them up and then died a decade ago. She considered the stresses the previous day's combat must have put on them, and a sour twist curdled through her. "You left us nothing," Kayla said, standing. She looked around the ruin of Tawnos's workshop. Penregon had needed him more than she had needed him. Yes, the connection he provided to her old life had been as painful as a healing burn, but familiar. With that wound severed from her soul, she could heal; but a city was not a person. Cities never healed, they either lived or died. Tawnos, in taking his life's work and the collected knowledge of Urza's artifice with him, may have taken Penregon with him. Not now, not for years, likely, but the winter would not stop. The ice crept ever closer; if the seasons continued to compress, then in some future not distant enough there would be an age of nothing but winter. A Penregon without civils and powerstones would die. Kayla turned from the ash slurry and walked away. She had work to do. A city to save, if she could, from the end that now seemed all but inevitable. A pair of damaged but functional civils joined the laborers later in the day. Fitted with wide shovels designed by Tawnos to clear snow from Penregon's streets, they made short work of cleaning the ruins. The ash was dumped into Penregon harbor, joining the ruined bodies of civils destroyed in the siege and those machines whose powerstone hearts had given out. The age of artifice died in Penregon's dark bay, below gentle waves, before the winter. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[79 AR] Penregon's end came ten years after the siege, outlasting Kayla's most optimistic predictions, but not her certainty. The intervening years were punctuated by brief moments of chaos and fear, but nothing like the siege. First came the first whispering summer. Penregon's gardens and orchards, typically thick with the buzz of cicadas—the true roaring lions of Penregon, Argivians would joke—but they never sang that summer. Though many found this a relief at first, the next quiet summer curdled any humor. The birds followed the insects, and summer's quiet begat silent springs. Ominous signs accumulated. One winter only a handful of years after the siege, Penregon's harbor suffered its first solid freeze. The sea waters of that protected bay froze, trapping the city's fishing and trade fleets in dense bay ice. At first, people despaired. There were riots: lack of work, lack of food. When those demonstrations calmed, people took to building huts and hovels alongside the frozen hulls, creating informal, scattered villages of fisherfolk; if they could not take their ships to sea, they would take themselves to the sea. At first the merchants and ship owners hired the city guard to clear the people away, but as it became clear that the ice would not be broken, they relented and let the people fish. For every winter that followed, the bay became a new land for landlords to lease, suppliers to outfit, and laborers to work: the people found fish, the landlords made the people's work into gold—but not too much gold—and life went on. Inland, Penregon's scouts kept up their expeditions. Early in the wake of the Talites, they scouted for distant dangers. As the winters began to linger, scouts hunted for warmer lands. Kayla championed the scouts' task, and the people of Penregon looked to their adventures with hope. Against the cruelties of the winter, to the landlords of Penregon harbor, the granary chiefs of spring, and the shipmasters of summer, the scouts were heroes. #figure(image("002_Episode 2: The Beginning/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) That hope was rewarded. Near the end, scouts returned with news of green lands to the distant west: Beyond the trailing edge of the Southern Khers the grass still grew thick and strong. There were towns and villages there, built by the descendants of old Yotia, Korlis, and Tomakul, and full of people who had never seen snow lower than the mountain peaks. Those people assured the scouts that further still, across the oases and sands of the Great Desert and west of the ruins of Tomakul, there stood cities. Beyond the Great Desert was a world that had been insulated from the worst of the cataclysm. The scouts were sure of it, and so Kayla—who had grown tired of the bickering merchants, landlords, guildmasters, and soldiers—proclaimed to the people of Penregon that their salvation lay in the distant west. That news prompted widespread excitement. Caravans were organized, supplies negotiated and bartered, homes deconstructed and packed into carts and wagons. Westbound by the thousands, the settler-refugees departed, and none who went that way ever returned to Penregon. The city grew quiet. Those who stayed either clung to what they knew with pyrrhic resolve—surely the gods would lift this cold before ruin met them—or grim resignation; either they could not or would not leave the city. Winter bled more and more into summer. Once balmy, those middling months turned crisp; omens mounted. Though usually temperate, on occasion a storm would darken Penregon for a week at a time, burying the city in drifts taller than the dark two-story buildings of the residential districts. Penregon's few remaining civils plowed snow drifts from the city's streets, clearing the cobblestones for the lonely pedestrians who scurried from warm building to warm building. When those civils died, they simply stopped mid-labor. Balanced, they became pillars of ice as snow fell on them, melted, and then re-froze. Penregon's end—the Penregon of Lady Kayla, the last Queen of Argive—came in autumn. Scouts returned from an expedition into Terisiare's far north, where they had heard rumors of a Gixian threat, a remnant of that foul order forgotten on Terisiare after the war's end. There, the returned scouts said, the land was buried under walking mountains of ice, great glaciers that moved slower than time but were just as unstoppable. Trembling, the scouts told tales of the northernmost Khers crumbling, the roar of their passing echoing for days at a time. In desperation, they had fled to the northeastern coast, where they observed with horror that the ocean itself had frozen to a dirty gray landmass. The sea had vomited up mountains of ice, tumbling and re-freezing, standing as tall as the Khers themselves; the cracking and popping of the frozen ocean sounded as if it were the very bones of the gods snapping. Warmed by fried fish and steaming coffee, the scouts told Kayla that the world was ending. The ice, though distant by generations, would not be stopped. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Through it all, Kayla was calm. Her stoic demeanor was necessary if Penregon was to remain together as those portentous, unstoppable changes to the world accumulated. Standing as a public bastion against hopeless resignation took an incredible amount of work, and there was no avenue that Kayla did not explore. She prayed to the gods of Yotia, old and new—even once reaching out to Tal—but the Argivians were as close to godless as anyone, and she felt nothing besides, so she stopped. She thought to emulate her late father's martial prowess and poise, so she trained her body into a warrior's strength, but she found no peace in running, riding, or swinging a sword. Away from the martial, Kayla dove into texts and scholarship, art, and other disciplines. She directed the construction of a grand manor house outside of Penregon, an estate that would prove her dedication to Argive as a gift to its future rulers—an exercise, she realized upon its completion and her relocation, in denial. She quit the manor and moved back to the city after only a year. To the public and to her advisors, this all spoke to the drive and determination of <NAME>, the Queen of Argive. In public, she was an example to all: a stoic without stoicism's chill, a martyr who did not die but burned as a beacon. This persona was a prison. It was only in private, in the dead of night, that Kayla was free to be afraid. In these dark hours, Kayla let her fear out into the world. This proved to be the only outlet by which she could go on. For the early years after the siege of Penregon and Tawnos's death, this fear was raw and unfocused: A cold-sweat anxiety that stole her from sleep. A white-hot rage, screamed into a pillow, hoping that no one could hear. She thought she could never empty herself of the pain, the anger, the grief. Every morning she awoke with her lungs raw, jaw throbbing and head aching. It was as if she wore a crown of weighted needles, a corset of nails, and could only adjust where their points dug in. No amount of fervent prayer brought relief. No full-contact sparring or alpine ranging cleared her mind. No painting or poem could capture it. No lonely wandering through the grand and hollow halls of her manor granted her reprieve. Kayla went through the day assuring others that their pain, their sadness, their fear would not best them, that Penregon needed them, that the world needed them. There was no truth behind her counsel: she felt nothing, could not even muster love for her grandson, and began to think that her grief might kill her. One cold winter night, many years after the siege, it nearly did. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Alone, shivering from the cold, drenched in sweat, Kayla clutched a balled-up fistful of cloak to her face and screamed again. She did not fear being heard. She had retreated to her manor, trudging alone through the snow to clear her mind from the small bickerings of her noble council and Penregon's moneyed princelings. The world was ending, and still those august goons argued over leases and owed rents. Myopic ticks, greedy fools. Kayla hated them. Why did they get to live when everyone she loved had died? She missed her Yotia and her family and her future and even the damn cicadas. It was too much. Kayla—leaving only a note for Capt<NAME> so that they would not send the scouts to track her down—quit the city to find a reprieve in her mothballed manor. Wrapped in an old cloak, a dusty crimson garment rescued from Kroog, Kayla lay in a ball on the floor of the manor's grand entrance and screamed her throat raw. It had been a day since she left the city, and she had not made it any deeper into the manor. She summoned up every horrible feeling and could not stop calling upon the lovely ones as well—every memory of Urza, of Tawnos, of Harbin, Jarsyl, her mother and father, of burning Kroog and shining Kroog, of Raddic and the ice, screaming until the sound left her and she could only croak, only sob, and then she felt something snap. Heat flowed through her. Fire coursed up from some deep knot in her gut, sizzled through every nerve in her body. She gasped, terrified, and managed to throw her cloak off before sparks erupted from her hands. Furnace heat flared bright in the space above her palms, popping like a festival firework and leaving her ears ringing and face reddened from the heat. Magic. The ringing faded from her ears. She knew it the moment it happened. As a girl, she had heard of wonders like this. All her life, she had heard whispers of some power beyond artifice. Even Urza spoke of it, muttering curses about some esoteric power manipulated in far corners of the world. She had dismissed it as fantasy—as had everyone else in the combined kingdoms—but that night all doubt quit her. Magic had cracked out into the world when Urza killed it; at the nadir of her despair, Kayla had channeled fire. Shivering and singed, alone, Kayla looked at her palms. Thin smoke rose from the air above them. They blistered. The air stank. She smiled. For the first time in years, Kayla laughed. A new, private regimen replaced her nights of despair. She returned to the city, resumed her duties, and dispatched her stewards to search Penregon's libraries for any books or scrolls on magic. To her surprise, they found many. Survivors from Terisia City—the old seat of that esoteric order, the Third Path—had settled in Penregon, bringing with them a modest amount of their writings. Among them was a copy of a text, an exploration of the techniques of a scholar from the college of Lat-Nam and one of the Third Path's leaders, Hurkyl, who—if war stories were to be believed—once disappeared the first regiments of Mishra's army that attacked Terisia City. Kayla had heard of this during the war but assumed it to be a fantasy, hope spun from beleaguered survivors of that long and bloody siege. After her own channeling, however, she thought otherwise. Kayla's new nightly practice followed the precepts of Hurkyl's meditative techniques as laid out in the book. She read that her control of magic could be improved first through a focus, so she retrieved a stone of her beloved Kroog from Penregon's archives and learned to pour everything into it, channeling this energy until the stone glowed and grew too hot to hold. Then, she learned to obliterate the pain. She burned herself often as she practiced, but this did not stop her. Instead, she wrapped her hands in clean gauze and continued her practice until the channeling of this energy no longer burned her flesh or caused her pain; then, she pressed further, learning how to direct this heat, to shape it into wild flame and cold light, into repairing her own wounds. These exercises were exhausting even as they were invigorating. Tapping into the soul as Hurkyl outlined was opening oneself to a raw font of memory and emotion. Even when the tears dried and her practice stone cooled, some hint of Kayla's despair remained. She could not burn away this final feeling. This ghost lingered with her even as her confidence grew from a novice's faltering practice to the assurance of a master. She might only light a candle with a brush of her finger, knit together a paper cut on her finger, or heat a stone to coal-hot in the palm of her hand, but it was the simple fact that this could happen—and that she could control it—that assured her of her mastery. Kayla realized this: if she could manage her wild and sudden magic, then she could bring herself back from darkness. Both demanded the same effort, and she was a diligent student. Kayla cooled as her practice stone did, night by night, session by session. Instead of raging through her grief, Kayla imbued her stone with her fire, touched it to a candle, and controlled her anger as the candle burned down. She encountered that familiar pain, mulled it over, accepted it, and then set it aside. Despair had not quit her, instead Kayla had heard it out, and then bade it farewell; the sun rose each morning despite the ice, and each morning, people more scared and less able than she came to petition her for help, guidance, aid, and comfort. Each day, she did what she could to help them. Each day, the woman she knew as Kayla bin-Kroog—not <NAME>—did not die. She changed. She survived. She was still afraid, but no longer without hope; she was not afraid of the night when she knew she carried an ever-burning flame inside of her. So, when the scouts returned with news of hope in the west, Kayla saw to it that any of her people who wanted to make the journey were provisioned and protected, ordering Myrel and their scouts to take whatever goods those pilgrims needed from the storehouses of the guildmasters and grain-lords. There was little they could do to resist <NAME>'s order, though some tried; they discovered they were alone with their gold and mercenaries against the people, and the lords that lived relented. Most all the scouts left Penregon as vanguards for the migration, followed by nearly half of the city's population arranged in long wagon trains. Myrel went with them; Kayla saw them off, kissing Myrel on both cheeks as a mother would a beloved child, assuring them they would see each other again someday in the west. Penregon quieted after the last of the wagon trains departed, darkened as the longer winters settled in. Storms battered the city. During one especially bitter blizzard, the Talite crusaders returned. Kayla ordered the gates open and invited them into Penregon's dark streets. They demanded she tell them where she hid the machines, to which she informed the crusaders they had walked off across the ice. Kayla told them Penregon had nothing to hide and no demons but hungry people; she offered to shelter them, and the Talites finally entered Penregon. Curious, she asked after Raddic, who was nowhere among the ranks of hard-bitten crusaders. "Dead," their new leader said. He was a gaunt and cold man, with none of Raddic's charm. Kayla had found him in the market streets, buying spirits and wines. "After the Iron Tower we marched to Mishra's forge," he told her. "The demons there were great in number and fury, but thanks be to Tal, we killed them all. Many of the faithful died, Raddic among them." He buried bottles of spirits in his saddlebags. "Who was he to you?" "No one," Kayla said. "A reminder of the old world." The gaunt man and his retinue left, and the long, dark-clad column of Talites—what was left of them after years on campaign—followed, trudging west through the snow into the white blankness. The last year wound down. With each passing day from the first, people bled from the city, stripping it of life, heat, and sound. Districts faded into disrepair, and the city shrank. Kayla was among the last to quit Penregon. It was her city, but she would not die in its cold, empty streets. That grief she had poured it into her Kroog stone; she left when she had something to leave for. Her scouts returned with dried blades of grass and pressed flowers and promised oceans of green, a living world beyond the desert, beyond the snow-capped Khers and ruin of the east. There were towns and cities, her scouts assured her, and there was something else: a story, tender and cruel, of a man and a flying machine in the western sky. Harbin. Kayla had poured out all her grief. With it fled the grief that can be tinged with hope. So, upon hearing this story, Kayla did not let her heart burst. She did not rush from Penregon alone to cross mountains and rivers to find her son. She prepared a final caravan of her people and went west with them, leaving only the grim and bloodied landlords of Penregon harbor behind, who refused to move from their miserable manors, where they stayed counting their gold until the ice took them. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kayla left Penregon and her manor behind and marched out along the now well-defined route with the rest of the exodus. Up into the howling Khers, her caravan struggled, choosing the lowest of the passes and still losing a quarter of their number to the cold, the dark, and the desperate creatures there. Down from those bitter passes, they staggered, trundling by the stone-frozen bodies of hundreds who perished on this route years before. The lower elevations brought some relief as the migration finally came upon the shores of that green west. Here, in the shadow of the bitter Khers, Kayla was once more in the land of her youth. Yotia, her dominion by right, the land she once would have ruled as queen. She always hated the bloody, martial Warlord and Warlady titles. How vile they were, and how corrupting. How could one rule a land in peace when their gods-given title named them a master of war? Kayla knew she would have been a good queen. The Mardun flowed swollen and wider than she remembered it, rich with spring meltwater. Their migration followed the old river by its new banks, winding along its bends and crossing at the small fords and ferry towns they encountered. No one had built bridges yet, but by Kayla's figuring, they were not far off. The snow and ice did not threaten the lands to the west of the Khers as much as it had menaced Penregon and the east; the long winter was coming, only delayed by that continental wall, and for now there was still money to be made in the mountains' shadow. Some of her caravan, fatigued and aching, stopped their migration in these budding towns. There was rich soil to be tilled here, gold to pan, old metals to scavenge, game to trap, and fish to harvest. One could make a life here; a life in the wake of civilizations, but it was a life one could live, rather than just survive. The foothills and thick forests soon fell away to dry prairie. Under open sky, the last hundred refugees of Penregon's exodus continued west, passing by the moss-covered ruins of old war machines and abandoned redoubts. Their route took them through the crumbled stone ruins of dead towns and across old battlefields—trenches and craters now shallow ponds where frogs sang in the evening, the bones of the dead long decayed to mulch for lilies and boughs of reeds where small birds flitted. The route west was a graveyard as much as it was a road; occasionally, they would pass the rotting wooden skeletons of carriages and carts, the bodies of their owners and draft beasts that once hauled them long since eaten by scavengers or buried where they had fallen. Eventually, they came to New Yotia, the first city of the west. A wooden sprawl built atop a mesa overlooking the vast westward sweep of land, New Yotia perched above the tumbling waters of the old Mardun. Large paddlewheels churned in the river, turning mills and powering all manner of riverside industry. The city had no walls beyond the natural rise of the mesa and earthworks facing the mountains; it was surrounded by cultivated fields and small farmers' collectives. Tall signal towers marched toward the city at regular intervals, rattling to life as their operators saw the approaching train of wagons. New Yotia welcomed them as Penregon once welcomed those who came to its gates. Most of Kayla's people settled there, finding the city a warm and familiar comfort. Kayla nearly did as well; she was tired and New Yotia reminded her of her youth. The scents, the food, the music, the language—even the buildings, though they were simple wooden affairs—were Yotian through and through. New Yotia was not Kroog—Kroog's corpse lay many dozens of miles ahead—but it was close. Kayla lingered in New Yotia for the rest of the winter, living in relative comfort above a small tea shop in a busy quarter of the city. By the summer, she decided it was time to continue west. New Yotia was a busy river port for the trappers, miners, and farmers that ranged up and down the western side of the Khers. Some came from even farther, and it was through this churn of people that Kayla learned there were indeed other cities further west: Lat-Nam, Sumifa, and other cities old and new, untouched by the cataclysm that doomed the east. As well, Kayla heard more stories. One of a sleek machine, silver as a mirror and fast as the light's flash, and the last flying man who soared the western blue. He was a hero, the people said. He'd flown into the sun to steal its gold, they said. He'd died in the cataclysm, they said, and was reborn as the wind's herald. Harbin, her son, legend of the western sky. Dead or alive, ghost or spirit, Kayla resolved to cross the continent to learn the truth. Strange things were happening in Terisiare—with Tawnos she had seen the dead return. Within herself and Jarsyl, she had seen magic. The old world was dying, remembering, trembling; a new world was being born. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[80 AR] The evening before Kayla was bound to depart for the west, her grandson, Jarsyl, came to her modest apartment. They ate a private dinner of refined Yotian cuisine on her deck overlooking a busy marketplace, attended to by a single servant whom Kayla sent away after the final plate had been set. It was a light meal, and the two of them ate in silence, letting the sound of the evening crowd below fill the space until Kayla could not stand her grandson's moping any longer. "Jarsyl," Kayla said, placing her utensils down on the table. "You're eating like a songbird." "I'm sorry, gran-mama," Jarsyl said. He sat hunched as much as his training in posture allowed. His food, save for perfunctory cuts, was untouched. "You've not met my eyes once," Kayla said. "You're haunted. Is it a lover, your practice, or something else?" "Something else," her grandson said. Jarsyl looked off over the market. "Why did you choose this place?" He asked. "You are queen—you could have taken quarters in the new palace." "True," Kayla said. "But I have been removed from my people for so long. I wished to live among them." She returned to her meal. "But you don't have guards." "I am an old woman," Kayla said, "and I am happy that my age of perfume is behind me. I want to stink of spice, oil, and incense; I do not need guards, and I do not want them." "And the Talites?" Jarsyl said. He searched the market below and pointed at a pair of Talite soldiers, haggling with a tea vendor. "They say they're hunting mages now." "They do say that." Kayla nodded, taking a bite of her food. "You're not worried?" Kayla laughed. "Certainly not. Every old woman has been called a witch by someone, especially those old women unlucky enough to lead nations. Besides—they can't get us all." She winked, and a soft thrum of energy filled the apartment. As one, the oil lamps Kayla had left burning snuffed out, then reignited. Jarsyl's eyes widened. He looked toward the Talites in the market below. They had not noticed. No one noticed. "The Talites don't concern me." Kayla said, smiling. She nodded toward Jarsyl's nearly full plate. "Your lack of appetite concerns me—that and your deflection. What haunts you?" Jarsyl prodded his cooling food. "Out with it," Kayla said, kind but firm. "I can't go with you." Kayla arched an eyebrow. Jarsyl may have been a man, but in this moment, he was as timid as a schoolboy. For a heartbeat, her blood ran cold, but she managed to compose herself before her face could break. Jarsyl looked so much like his father. Harbin had stood before her, once, the day he told her he meant to join the 'thopter corps. The hitch of fear—not of what could be, but of how she would respond—caught Jarsyl's voice in his throat the same way it had Harbin all those long years ago. She took a breath. There was no war. Jarsyl, the bright boy, was not Harbin. "I've heard stories," Jarsyl began, "of a school to the north, on the banks of Ronom Lake." "There's nothing in Ronom," Kayla said. "The Gixians were driven out a decade ago by the first Talite crusade." "Right, yes," Jarsyl said. "But I've heard there is something else there now—a school for people who can~ do what we do." "A school for magic?" Jarsyl nodded. "Magic and artifice, both. They're teaching people like us how to be better. Stronger." Kayla considered this. Jarsyl was, by the customs of the old world and the demands of the new, an adult—though she often thought of him as a young boy still. His life had been lived at her side, abandoned by his father and grown at the end of the world. The end of her world. His world, though perilous, was young as he and growing still—were the rumors he chased any less credible than the stories she followed? "Magic and artifice," Kayla repeated. She wondered—could it be? "Did they say who runs this school?" "An artificer woman, Nod, and a mage they called Duck," Jarsyl said. He rubbed the back of his neck, as if ashamed to speak the names aloud. "I think he might be from the west, it's a funny name." Nod and Duck. Old friends and new. Kayla always wondered if Tawnos truly died that day. She smiled at Jarsyl. "Go north. If there are teachers greater than me, seek them out." Jarsyl brightened, as if a weight lifted from his shoulders. Still, tears sprang to his eyes. Kayla stood and rounded the table to Jarsyl, gathering him up into an embrace. "My boy," she whispered, squeezing him tight. "You and I have different stories. Mine might be ending, but yours is about to begin." "I'm afraid to go," Jarsyl said, his voice muffled by her embrace. "Me too," Kayla said. She kissed her grandson's cheek. "But I am excited, as well. Let's choose to let excitement lead us, yes?" Jarsyl nodded. He stepped back and wiped his nose dry. "Will you tell him about me?" he asked. He didn't need to say his name for Kayla to know who he meant. "I will," Kayla said. "If you tell <NAME> about me. Now, when do you leave?" "There is a party departing tomorrow morning," Jarsyl said, curiosity over his grandmother's wish vanishing as he rattled off his plans. "I'll have to hurry to the outfitters, but I have already told the pathfinder of my interest—they're expecting me." His tears had dried, and already he began to speak around his breath. When he was excited, he positively burned with energy. Schooling, if indeed there was a school of magic, would do him good, Kayla thought. "You should not linger," Kayla said. She motioned for him to go. "Hurry and gather your things, let the pathfinder know that you will certainly be joining them in the morning." "It's hard to say goodbye, gran-mama," Jarsyl said. "I don't want to." Kayla nodded. "Then let's not say goodbye," she said. She embraced him once more and kissed him on the forehead. "'Til later, my boy." "'Til later," Jarsyl whispered. Kayla sent her grandson away. The following morning, she left before the dawn. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The quickest and safest way west was via the Mardun. That grand river would pass the ruins of Kroog and deposit them at the edge of the desert, where they would follow the high roads through the ruins of Tomakul and beyond. Kayla was curious to see her old home. The New Yotians told her that the Mardun long ago flooded the city, having been shaken from its banks by the tremendous, cataclysmic detonation that rocked Terisiare. Save for the southern districts of the Kroog where the royal palace and noble quarters of the city once stood, much of the city remained underwater. The grand old capital was now a lake along the new course of the river, fed by the distant snowmelt from the southern Khers. Kayla was not surprised to hear that a warlord ruled Kroog again. This one was a brute who styled himself after the mighty leaders of old. His raider gangs menaced the roads and fields around the city; it was better to take a swift riverboat guarded by New Yotian archers and Talite mercenaries. The Church of Tal was thick in New Yotia, numerous as the wildflowers in the prairie. Those dour penitents and demon hunters were a nuisance to the bright joys of New Yotia, but their order was large and provided for the common defense of the city. Kayla understood that their presence was necessary to counter the threat of raiders from Kroog. As well, she understood that alone she could not root them out and expel them from this city that could be her home—not even with her magic. So she did not protest when a detachment of dark-clad soldiers filed onto her riverboat. The Talites wore clean uniforms of a deep and inky blue, their armor black, their swords oiled and free of rust. A far cry from the desperate rabble that once assailed Penregon; it seemed their first defeat did not deter their faith. The Talites took the bottom deck and the hold, while the passengers and New Yotian archers took the top deck. Should fighting occur, the worst of it would fall upon the Talites; they did not mind this arrangement, nor did Kayla. Below her, the Talites prayed, ate, maintained their weapons, slept, and kept watch. None of them looked at her. None of them knew who she was, and none of them seemed to care. This was much to Kayla's liking as well. Once underway, Kayla ruled the second deck of the riverboat, ignoring the captain's orders to return to her cabin during the evening hours. She kept no company but her own and resisted conversation. The New Yotian contingent recognized Kayla's old-world accent and bearing and did not mark her distance from them as an insult: an old eccentric, they assumed, one of the few elders who lived through the end of the world. The New Yotians stopped their inquiries and advances after the first few nights on the river. Left alone, Kayla was free to rest and watch the world pass by. The ruins of Kroog were a day ahead. On her lap, the last pages of a poem she had been working on. An epic, a history of the men who killed the world, lest they ever be forgotten—or forgiven. Bright laughter from the New Yotians practicing their archery drew her attention, the twang and thrum of their bows as they fired at targets along the bank—trees, fence posts from long-abandoned farms, rusted remains from the war—making a contest out of their training. On the deck below, one of the Talites started to sing and soon the rest joined in, their voices rising together in chorus. Another week of this did not sound so bad. Kayla was quite curious to see Tomakul—even if that grand city was only ruins—and was eager to explore those lands further west, of which she had only ever heard described in story. Kayla tapped her foot on the deck in time with the singing. She closed her folio, deciding to take a break from writing for the day. The gentle rocking motion of the riverboat soothed her. The sun was warm on her face. She closed her eyes and smiled. Kayla was free. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[85 AR] Kroog itself looked nothing like the grand city it once was. Its proud stone towers had all but crumbled, save for a handful of hollow monoliths that were now home only to nesting birds. These lone sentinels of the lake remained the tallest structures in Kroog but were not seen as part of the new city that sprawled there; Kroog after the cataclysm was a midden heap of buildings and walkways that huddled atop one another, built above the water on a forest of stilts. Everything in the city was devoted to one of two things: harvesting the bounty of the lake or raiding up and down the river to add coins, captives, and salvage to the wealth of Warlord Fask, the Tyrant of Kroog. Fask was a clever brute. A warlord in title and bearing, he had killed his way to the top in the decade following the cataclysm. Now Fask ruled a petty kingdom that stretched from the ruins of Zegon on the southwestern coast of Terisiare up to the greening desert's boundary in the north. To the east, his land was ill-defined, contested by New Yotia and the Talites who still managed to hold his reavers at bay. Inside his borders, all paid tribute to him, a simple system of "Four-Of-Ten"—four of any goods were given to his treasury and personal chest, and the remainder spread out among his loyal subjects. He was, to the chagrin of the people who suffered his reign, the fairest of the warlords who had contested this ground. Thus, Fask commanded the loyalty of his favored warriors and the submission of the rest of his subjects until his death. Fask's end saw his realm carved up between rising domains and hungry warlords. New Yotia and the Talites conquered and annexed the eastern half of his domain while Fask's rivals tore apart the western half. No one knows if the fighting there ever stopped; those records, if they ever were kept, have been lost to time and the ice, or were buried in the archives of the Church of Tal. Lost as well was the story of Fask's end, the nighttime tale of the tyrant and the ghost. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Warlord Fask, the Tyrant of Kroog, awoke in the deepest pit of the night. A sound in his chambers: cans, coins, and medallions rattling together. Fask threw off his thin sheet blanket and grabbed his sword, naked as he was in the bed beside him, and leveled it toward the sound. His chambers were unrecognizable from their usual spartan appointments, but he had ordered them to be packed thick as any storehouse or treasury. His guards whispered of the Warlord's paranoia and madness, but Fask was desperate. He needed to prove what he had seen. A web of strings crisscrossed the large room, and from them all manner of small bright things were suspended: cans, coins, silver and tin utensils, medallions, knives, chain shirts, arrowheads—anything that would create a loud, unmistakable commotion when disturbed by a person's touch. This was Fask's trap, his system to prove he was not mad but perceptive. For months, Fask had been plagued by voices in the night. Footsteps and the sounds of conversation, building and falling. Outwardly, he feared an assassin—this was the reason for his alarm system, he told his guards—but inwardly, he feared something else, something more deadly: fate. Fask wiped sweat from his eyes and recalled unbidden the oracle's words once more: #emph[The dead do not forget their killer] , she cackled through bloody teeth. #emph[We will meet again someday—every cut of your sword will be returned a thousandfold!] Fask had encountered the oracle one dark and rainy night during his conquest of the Sword Marches, as he and his reavers tore down a nameless village that had stood against them. The doom she cursed him with had haunted him for a decade; though he sat on a throne he built through war, nothing since the cataclysm had weighed so heavily on his mind. In the quiet minutes that followed his awakening, Fask felt a curtain of shame descend over his sweat-cooled back. He was a fool to fear that ancient crone. The sword was a fine and proud weapon, sharp as a razor, and his room empty. He was Fask, the Tyrant of Kroog, the Warlord of Old Yotia! The wind, surely it had been the wind over the lake— The rattle came from the foot of his bed. "Who is there?" Fask cried out, sword held in a two-handed grasp before him. Fear commanded him, and he could not stop from trembling. "You will tell me who you are," Fask demanded. "Who sent you, spirit?" Silence. A pause long enough for Fask to think himself into circles. Maybe it was the wind—a strong wind yes, but maybe it was just that. No, impossible! It would have to be a gale outside to move these lines—surely what had disturbed them was alive; they were strung at chest height, with cans and broken glass scattered on the floor. It was impossible for someone to not make a sound moving in Fask's chambers. Another rattling at the foot of his bed. The brief hiss of something, something angry, as if a beast stalked toward him, fangs bared and maw slavering. Fask scrambled up to his feet and pressed his back to the wall, moving as far from the sound as he could. He saw nothing, despite the bright moonlight filtering in through the narrow barred window to his room. Shifting his grip to hold the sword in one hand, he reached across his bed to a hooded oil lamp he kept there. He twisted a knob on the lamp, and its shade flipped open. A beam of warm light stabbed out across the dark, illuminating the foot of his bed. A man stood there. Not a man—a dim shadow, a bruise on the room's darkness unbroken by the oil lamp's beam. It was a spirit, half-realized, a mist that shifted between formless smoke and the solid figure of a man. Fask could make out the close-cropped hair on the spirit's head, the neatly trimmed beard. The spirit stared at him, unmoving. Fask screamed. The Tyrant of Kroog dropped his sword and clapped his hands over his eyes. He fell to his knees. This was the doom he feared, the ghost of the dead, come to drag him down below the cold waters of Kroog, the graveyard upon which he built his kingdom. The spirit drifted backwards, movement resolving into steps as his bottom half coalesced from mist to form. He bumped into another string of cans and medallions, which jingled softly. Guards burst into the room, swords drawn, but saw only their lord screaming and clawing at his own face. They looked to each other in confusion. Some decided to help Fask and hurried to his side. Others, dark looks clouding their rough faces, left. They had seen enough. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Kaya," Teferi said, whispering unseen and unheard from the shadows. "Pull me out." "You've only been in there for a few minutes, Teferi," Kaya responded, her voice soft as the breeze through the distance. "What did you do?!" "Nothing!" Teferi said. "I think he saw me." He watched the naked screaming man roll around on his bed, lashing out at the other men—his guards, it seemed—who were trying to calm him down. "And I may be, ah, coherent," Teferi said. He tested this theory by reaching out and plucking one of the trap strings. It bounced, gently, as if a breeze had shifted the line—far too much movement for his comfort—he was meant to be insubstantial, nothing more than a spirit, not actually physically present. Teferi shook his head. "The Temporal Anchor isn't calibrated correctly, Kaya, and I think we undershot our target—we didn't go far back enough. Pull me out." Kaya muttered something Teferi couldn't make out. "What was that?" "Nothing," Kaya said. "Saheeli has some thoughts." Teferi could hear Kaya rolling her eyes. "Alright," Kaya said. "Pulling you back." Teferi's spirit dissolved into mist, leaving the night undisturbed but for the screams of the Tyrant of Kroog. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Many centuries later, an ancient man regaled his grandchildren with the story of that night. He spoke to them of the strife that followed, the kingdoms that rose and fell because of a ghost, and the importance of omens and magic. None of his grandchildren thought his tale anything more than just a story, but they loved the faces and sounds their grandfather would make when telling it, and so they asked for it often. Stories kept spirits high during the bitterly cold nights on the glaciers of Terisiare. The Ice Age was upon Dominaria, and though these grandchildren all went on to live long lives and recount various versions of this story to their own dynasties, none of them outlived the ice, and neither did the story of the tyrant and the ghost.
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/test/sugar/test-001-sugar-queston.typ
typst
MIT License
#import "../../src/lib.typ": * #show: g-exam.with( // question-points-position: right, // decimal-separator: "." // show-grade-table: false, // show-solution: false // question-text-parameters: (size: 18pt, font:"OpenDyslexic") ) =? =2.35? =2.5? Question 1 ? What ? ==? ==? Subquestion 1 =% Clarification % =! Solution. =3? Queston a ==3.2? ==32? Question b? ==321.43? Question c?
https://github.com/david-davies/typst-prooftree
https://raw.githubusercontent.com/david-davies/typst-prooftree/main/src/prooftrees.typ
typst
MIT License
#import "internal.typ" /// An inference with `num_premises` many premises. /// /// - num_premises (int): The number of premises of the inference. /// - conclusion (content): The conclusion of the inference; the part that goes under the line. /// - right_spacing (length): When this tree is itself a premise, how much spacing between this tree and the premise to the right, if any. /// - left_label (content): The label to the left of the inference line. /// - left_label_spacing (length): The spacing between the left label and the inference line. /// - right_label (content): The label to the right of the inference line. /// - right_label_spacing (length): The spacing between the right label and the inference line /// - line_config (LineConfig?): The configuration of the current inference line directly, overrides the `tree_config`. See `line_config` for parameters. /// -> dictionary: A dictionary with the information needed for the tree parser. #let nary( num_premises , conclusion , right_spacing: 0pt , left_label: none , left_label_spacing: 0pt , right_label: none , right_label_spacing: 0pt , line_config: none ) = internal._mk_tree_line( num_premises: num_premises , body: conclusion , right_spacing: right_spacing , left_label: left_label , left_label_spacing: left_label_spacing , right_label: right_label , right_label_spacing: right_label_spacing , line_config: line_config ) /// `nary` with 0 premises. /// See docs for `nary` for more information. #let axi = nary.with(0) /// `nary` with 1 premise. /// See docs for `nary` for more information. #let uni = nary.with(1) /// `nary` with 2 premises. /// See docs for `nary` for more information. #let bin = nary.with(2) /// nary with 3 premises. /// See docs for `nary` for more information. #let tri = nary.with(3) /// `nary` with 4 premises. /// See docs for `nary` for more information. #let quart = nary.with(4) /// `nary` with 5 premises. /// See docs for `nary` for more information. #let quint = nary.with(5) /*****************************************************************************/ /// == Configuration /// Create a configuration for the formatting of the inference line. /// /// - overhang (length): The amount by which the line hangs left and right past the premises. /// This is overriden by `overhang_l` and `overhang_r` if they are set. /// - overhang_l (length): The amount by which the line hangs left past the premises. /// This overrides `overhang` only on the left side. /// - overhang_r (length): The amount by which the line hangs right past the premises. /// This overrides `overhang` only on the right side. /// - stroke (length): The stroke of the line, with the same options as `typst`'s `line` function. /// -> dictionary: A dictionary with the information needed for tree builder. #let line_config( overhang: internal.default_line_config.overhang_l, overhang_l: none, overhang_r: none, stroke: internal.default_line_config.stroke ) = internal._mk_line_config( overhang: overhang, overhang_l: overhang_l, overhang_r: overhang_r, stroke: stroke ) /// The default line configuration. #let default_line_config = internal.default_line_config /// Create a format configuration for a tree. /// /// This controls many aspects of the look of the tree, such as the spacing between premises, the line style, etc. /// The default configuration is `default_tree_config`; this config that obtained by passing no arguments to this function. /// /// - premises_spacing (length): The spacing between premises. This can be overriden by individual premises. /// - spacing_between_next_premise (length): Currently does nothing. /// - vertical_spacing (length): The vertical spacing between premises, the line and the conclusion. /// - line_config (line_config): The configuration of the inference line, see `line_config`. /// -> dictionary: A dictionary with the information needed for tree builder. #let tree_config( premises_spacing: 10pt , spacing_between_next_premise: none , vertical_spacing: 2.2pt , line_config: default_line_config ) = { internal._mk_tree_config( premises_spacing: premises_spacing , spacing_between_next_premise: spacing_between_next_premise , vertical_spacing: vertical_spacing , line_config: line_config ) } /// The default tree configuration. #let default_tree_config = tree_config() /*****************************************************************************/ /// == Displaying trees #let _show_str_tree(tree) = internal.__show_str_tree(default_tree_config, tree) /// Construct and display a line-by-line tree /// This is the main function of the package. /// Positional arguments are parsed as premises, and the last argument is the conclusion. /// Named arguments are used to configure the tree, and override the `tree_config`. /// /// - tree_config (tree_config): The configuration of the tree. /// - ..args (content, any): The premises, conclusion and extra configurations of the tree. /// -> content: The tree. #let tree( tree_config: default_tree_config, ..args ) = internal._parse_then_show(tree_config: tree_config, args)
https://github.com/jbirnick/typst-great-theorems
https://raw.githubusercontent.com/jbirnick/typst-great-theorems/master/lib.typ
typst
MIT License
#let mathblock(blocktitle: none, counter: none, numbering: "1.1", prefix: auto, titlix: title => [(#title)], suffix: none, bodyfmt: body => body, ..global_block_args) = { // check if blocktitle was provided if blocktitle == none { panic("You have created a `mathblock` without a `blocktitle`. Please provide a `blocktitle` like \"Theorem\" or \"Lemma\" or \"Proof\".") } // set the default prefix if prefix == auto { if counter == none { prefix = [*#blocktitle.*] } else { prefix = (counter) => [*#blocktitle #counter.*] } } // check consistency of `counter` and `prefix` if counter == none and type(prefix) == function { panic("You have created a `mathblock` without a `counter` but with a `prefix` that accepts a counter. This is inconsistent. If you want a counter, then provide it with the `counter` argument (see documentation). If you don't want a counter, then you need to set a `prefix` that doesn't depend on a counter (see documentation).") } else if counter != none and type(prefix) != function { panic("You have created a `mathblock` with a `counter` but with a `prefix` that doesn't depend on a counter. This is inconsistent. If you don't want a counter, then remove the `counter` argument. If you want a counter, then set a prefix that depends on a counter (see documentation).") } // wrap native counter if counter != none and type(counter) != dictionary { counter = ( step: (..args) => { counter.step(..args) }, get: (..args) => { counter.get(..args) }, at: (..args) => { counter.at(..args) }, display: (..args) => { counter.display(..args) }, ) } // return the environment for the user if counter != none { return (title: none, numbering: numbering, prefix: prefix, titlix: titlix, suffix: suffix, bodyfmt: bodyfmt, ..local_block_args, body) => { figure(kind: "great-theorem-counted", supplement: blocktitle, outlined: false)[#block(width: 100%, ..global_block_args.named(), ..local_block_args.named())[ // step counter #(counter.step)() // store counter so reference can get counter value // NOTE: alternatively could store result of counter.get(), but then it would take one more layout iteration #metadata((counter,numbering)) #label("great-theorems:counter") // show content #prefix(context (counter.display)(numbering)) #if title != none [#titlix(title)] #bodyfmt(body) #suffix ]] } } else { return (title: none, numbering: numbering, prefix: prefix, titlix: titlix, suffix: suffix, bodyfmt: bodyfmt, ..local_block_args, body) => { figure(kind: "great-theorem-uncounted", supplement: blocktitle, outlined: false)[#block(width: 100%, ..global_block_args.named(), ..local_block_args.named())[ // show content #prefix #if title != none [#titlix(title)] #bodyfmt(body) #suffix ]] } } } #let proofblock(blocktitle: "Proof", prefix: text(style: "oblique", [Proof.]), prefix_with_of: of => text(style: "oblique", [Proof of #of.]), suffix: [#h(1fr) $square$], bodyfmt: body => body, ..global_block_args) = { // return the environment for the user return (of: none, prefix: prefix, prefix_with_of: prefix_with_of, suffix: suffix, bodyfmt: bodyfmt, ..local_block_args, body) => { if type(of) == label { of = ref(of) } figure(kind: "great-theorem-uncounted", supplement: blocktitle, outlined: false)[#block(width: 100%, ..global_block_args.named(), ..local_block_args.named())[ // show content #if of != none [#prefix_with_of(of)] else [#prefix] #bodyfmt(body) #suffix ]] } } #let great-theorems-init(body) = { show figure.where(kind: "great-theorem-counted"): set align(start) show figure.where(kind: "great-theorem-counted"): set block(breakable: true) show figure.where(kind: "great-theorem-counted"): fig => fig.body show figure.where(kind: "great-theorem-uncounted"): set align(start) show figure.where(kind: "great-theorem-uncounted"): set block(breakable: true) show figure.where(kind: "great-theorem-uncounted"): fig => fig.body show ref: it => { if it.element != none and it.element.func() == figure and it.element.kind == "great-theorem-counted" { let supplement = if it.citation.supplement != none { it.citation.supplement } else { it.element.supplement } let data = query(selector(label("great-theorems:counter")).after(it.target)).first() let (counter, numberstyle) = data.value link(it.target, [#supplement #numbering(numberstyle, ..((counter.at)(data.location())))]) } else if it.element != none and it.element.func() == figure and it.element.kind == "great-theorem-uncounted" { let supplement = if it.citation.supplement != none { it.citation.supplement } else { it.element.supplement } link(it.target, [#supplement]) } else { it } } body }
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/07-localisation/takri.typ
typst
Other
#import "/lib/draw.typ": * #import "/template/lang.typ": takri #let start = (0, 0) #let end = (500, 420) #let example = "\u{1168A}\u{116AE}\u{116AB}" #let correct = with-unit((ux, uy) => { // mesh(start, end, (100, 100)) txt([#takri[#example]], (0, 80), size: 400 * ux, anchor: "lb") }) #let broken = with-unit((ux, uy) => context { correct let fill-color = if page.fill == none { theme.bg } else { page.fill } point((258, 391.5), radius: 25.8, color: fill-color) let x = 310 point((x, 391.5), radius: 25.4) // segment((x, end.at(1)), (x, start.at(1))) }) #grid( columns: (1fr, 1fr), inset: 0pt, column-gutter: 10%, [#canvas(end, width: 100%, broken)], [#canvas(end, width: 100%, correct)], )
https://github.com/AliothCancer/AppuntiUniversity
https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/FormularioDispositivi.typ
typst
#import "style.typ": apply_style #import "custom_functions.typ": def #let title = align(center)[ #text( "Formulario di Dispositivi itps", 30pt) ] #let def(formula, unit) = { //set text(rgb("#000000"), 1em, weight: "bold") text(strong("· "), 1.4em, weight: "bold") + formula + $med med arrow med med$ show text: set text(blue) show math.equation: set text(blue) unit + "\n" } #title #apply_style[ #outline(indent: true) #pagebreak() = Valvole cardiache == Effective Orifice Area (EOA) $ "EOA" = 10^4/516 (Q) / (sqrt(Delta p)) arrow "cm"^2 $ #def[Q][Litri/secondo] #def[$Delta p$][mmHg] == Discharge Coefficient (DC) $ "DC" = "EOA"/A_"int" arrow ["adim."] $ #def[EOA][$"cm"^2$] #def[$A_"interna"$][$"cm"^2$] == Performance Index (PI) $ "PI" = "EOA" / A_"est" arrow ["adim."] $ #def[EOA][$"cm"^2$] #def[$A_"esterna"$][$"cm"^2$] #pagebreak() == Reverse Flow (RF%) $ "RF%" = V_"rigurgitato" / V_"eiettato" dot 100 $ \ - $V_"rigurgitato" -- #block[È l'area negativa del grafico Portata-Tempo nel ventricolo sinistro.(Left-Ventricle)]$ \ \ - $V_"eiettato" -- #block[È l'area positiva del grafico Portata-Tempo nel ventricolo sinistro (Left-Ventricle).]$ == Numero di Reynolds (Re) $ "Re" = (rho dot v dot d) / mu $ - $rho$ : densità sangue 1 $g/"cm"^3$ - v: velocità del sangue $"cm"/s$ - d: diametro del condotto $"cm"$ - $mu$ : viscosità del sangue 0.03Poise = 0.03 $(g dot "cm") / s$ \ #strong("Nota:") Numero di Reynold - Re < 2000 #h(2cm) $arrow$ flusso laminare - 2000 < Re < 4000 #h(.45cm)$arrow$ Regime di transizione - Re > 4000 #h(2cm) $arrow$ Regime turbolento ]
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/vec2.typ
typst
MIT License
#let add(a, b) = (a.at(0) + b.at(0), a.at(1) + b.at(1)) #let sub(a, b) = (a.at(0) - b.at(0), a.at(1) - b.at(1)) #let scale(k, a) = (a.at(0) * k, a.at(1) * k) #let dot(a, b) = a.at(0) * b.at(0) + a.at(1) * b.at(1) #let distance(a, b) = calc.sqrt(calc.pow(a.at(0) - b.at(0), 2) + calc.pow(a.at(1) - b.at(1), 2)) #let distance-squared(a, b) = calc.pow(a.at(0) - b.at(0), 2) + calc.pow(a.at(1) - b.at(1), 2) #let norm(a) = calc.sqrt(calc.pow(a.at(0), 2) + calc.pow(a.at(1), 2)) #let normalize(a) = { let norm = norm(a) (a.at(0) / norm, a.at(1) / norm) } #let direction(a, b) = normalize(sub(b, a)) #let lerp(from, to, amount) = { let dir = sub(to, from) let incr = (dir.at(0) * amount, dir.at(1) * amount) add(from, incr) } #let from-polar(radius, angle) = (radius * calc.cos(angle), radius * calc.sin(angle)) #let normals(a) = { let (x, y) = a // ( // (y, -x), // (-y, x) // ) ( clockwise: (y, -x), counter: (-y, x) ) } #let projection-onto-line(point, a, b) = { // let x1 = point.at(0) // let y1 = point.at(1) let (x1, y1) = point let xp = (x1 + a * (y1 - b)) / (a * a + 1) ( xp, a * xp + b ) } #let line-from-line-segment(start, end) = { // let x1 = start.at(0) // let y1 = start.at(1) let (x1, y1) = start // let x2 = end.at(0) // let y2 = end.at(1) let (x2, y2) = end let a = (y2 - y1) / (x2 - x1) let b = y1 - (a * x1) ( a: a, b: b ) } #let rotate-z(p, theta: calc.pi) = { let (x, y) = p let cos = calc.cos let sin = calc.sin ( cos(theta) * x + -sin(theta) * y, sin(theta) * x + cos(theta) * y ) } #let points-relative-from(start, ..points) = { // check the type of the first element in each tuple in the list points if type(points.pos().first().first()) == angle { points.pos().fold((start, ), (acc, point) => { let (angle, distance) = point acc + (add(acc.last(), from-polar(distance, angle)),) }) } else { points.pos().fold((start, ), (acc, point) => { acc + (add(acc.last(), point),) }) } } // #let points-relative-from-angle(start, ..points) = { // // but where a point is (angle, distance) // }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.3.0/src/util.typ
typst
Apache License 2.0
#import "deps.typ" #import deps.oxifmt: strfmt #import "matrix.typ" #import "vector.typ" #import "bezier.typ" /// Constant to be used as float rounding error #let float-epsilon = 0.000001 #let typst-measure = measure #let typst-length = length /// Multiplies vectors by a transformation matrix. If multiple vectors are given they are returned as an array, if only one vector is given only one will be returned, if a dictionary is given they will be returned in the dictionary with the same keys. /// /// - transform (matrix,function): The $4 \times 4$ transformation matrix or a function that accepts and returns a vector. /// - ..vecs (vector): Vectors to get transformed. Only the positional part of the sink is used. A dictionary of vectors can also be passed and all will be transformed. /// -> vector,array,dictionary #let apply-transform(transform, ..vecs) = { let t = if type(transform) != function { matrix.mul4x4-vec3.with(transform) } else { transform } if type(vecs.pos().first()) == dictionary { vecs = vecs.pos().first() for (k, vec) in vecs { vecs.insert(k, t(vec)) } } else { vecs = vecs.pos().map(t) if vecs.len() == 1 { return vecs.first() } } return vecs } /// Reverts the transform of the given vector /// /// - transform (matrix): Transformation matrix /// - vec (vector): Vector to be transformed /// -> vector #let revert-transform(transform, ..vecs) = { apply-transform(matrix.inverse(transform), ..vecs) } /// Linearly interpolates between two points and returns its position /// /// - a (vector): Start point /// - b (vector): End point /// - t (float): Position on the line $[0, 1]$ /// -> vector #let line-pt(a, b, t) = { return vector.add(a, vector.scale(vector.sub(b, a), t)) } /// Get orthogonal vector to line /// /// - a (vector): Start point /// - b (vector): End point /// -> vector #let line-normal(a, b) = { let v = vector.norm(vector.sub(b, a)) return (0 - v.at(1), v.at(0), v.at(2, default: 0)) } /// Calculates the arc-length of a circle or arc /// /// - radius (float): Circle or arc radius /// - angle (angle): The angle of the arc. /// -> float #let circle-arclen(radius, angle: 360deg) = { calc.abs(angle / 360deg * 2 * calc.pi) } /// Get point on an ellipse for an angle /// /// - center (vector): Center /// - radius (float,array): Radius or tuple of x/y radii /// - angled (angle): Angle to get the point at /// -> vector #let ellipse-point(center, radius, angle) = { let (rx, ry) = if type(radius) == array { radius } else { (radius, radius) } let (x, y, z) = center return (calc.cos(angle) * rx + x, calc.sin(angle) * ry + y, z) } /// Calculates the center of a circle from 3 points. The z coordinate is taken from point a. /// /// - a (vector): Point 1 /// - b (vector): Point 2 /// - c (vector): Point 3 /// -> vector #let calculate-circle-center-3pt(a, b, c) = { let m-ab = line-pt(a, b, .5) let m-bc = line-pt(b, c, .5) let m-cd = line-pt(c, a, .5) let args = () // a, c, b, d for i in range(0, 3) { let (p1, p2) = ((a,b,c).at(calc.rem(i,3)), (b,c,a).at(calc.rem(i,3))) let m = line-pt(p1, p2, .5) let n = line-normal(p1, p2) // Find a line with a non upwards normal if n.at(0) == 0 { continue } let la = n.at(1) / n.at(0) args.push(la) args.push(m.at(1) - la * m.at(0)) // We need only 2 lines if args.len() == 4 { break } } // Find intersection point of two 2d lines // L1: a*x + c // L2: b*x + d let line-intersection-2d(a, c, b, d) = { if a - b == 0 { if c == d { return (0, c, 0) } return none } let x = (d - c)/(a - b) let y = a * x + c return (x, y) } assert(args.len() == 4, message: "Could not find circle center") return vector.as-vec(line-intersection-2d(..args), init: (0, 0, a.at(2))) } /// Converts a {{number}} to "canvas units" /// - ctx (context): The current context object. /// - num (number): The number to resolve. /// -> float #let resolve-number(ctx, num) = { return if type(num) == length { float(num.to-absolute() / ctx.length) } else if type(num) == ratio { num } else { float(num) } } /// Ensures that a radius has an `x` and `y` component. /// - radius (number, array): /// -> array #let resolve-radius(radius) = { return if type(radius) == array {radius} else {(radius, radius)} } /// Finds the minimum of a set of values while ignoring {{none}} values. /// - a (float,none): /// -> float #let min(..a) = { let a = a.pos().filter(v => v != none) return calc.min(..a) } /// Finds the maximum of a set of values while ignoring {{none}} values. /// - ..a (float,none): /// -> float #let max(..a) = { let a = a.pos().filter(v => v != none) return calc.max(..a) } /// Merges dictionary `b` onto dictionary `a`. If a key does not exist in `a` but does in `b`, it is inserted into `a` with `b`'s value. If a key does exist in `a` and `b`, the value in `b` is only inserted into `a` if the `overwrite` argument is `true`. If a key does exist both in `a` and `b` and both values are of type {{dictionary}} they will be recursively merged with this same function. /// /// - a (dictionary): Dictionary a /// - b (dictionary): Dictionary b /// - overwrite (bool): Whether to override an entry in `a` that also exists in `b` with the value in `b`. /// -> dictionary #let merge-dictionary(a, b, overwrite: true) = { for (k, v) in b { if type(a) == dictionary and k in a and type(v) == dictionary and type(a.at(k)) == dictionary { a.insert(k, merge-dictionary(a.at(k), v, overwrite: overwrite)) } else if overwrite or k not in a { a.insert(k, v) } } return a } /// Measures the size of some {{content}} in canvas coordinates. /// - ctx (context): The current context object. /// - cnt (content): The content to measure. /// -> vector #let measure(ctx, cnt) = { let size = typst-measure(cnt) return ( calc.abs(size.width / ctx.length), calc.abs(size.height / ctx.length) ) } /// Get a padding/margin dictionary with keys `(top, left, bottom, right)` from a padding value. /// /// /// Type of `padding`: /// - {{none}}: All sides padded by 0 /// - {{number}}: All sides are padded by the same value /// - {{array}}: CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)` /// - {{dictionary}}: Converts a Typst padding dictionary (top, left, bottom, right, x, y, rest) to a dictionary containing top, left, bottom and right. /// /// - padding (none, number, array, dictionary): Padding specification /// /// -> dictionary #let as-padding-dict(padding) = { if padding == none { padding = 0 } if type(padding) == array { // Allow CSS like padding array assert(padding.len() in (2, 3, 4), message: "Padding array formats are: (y, x), (top, x, bottom), (top, right, bottom, left)") if padding.len() == 2 { let (y, x) = padding return (top: y, right: x, bottom: y, left: x) } else if padding.len() == 3 { let (top, x, bottom) = padding return (top: top, right: x, bottom: bottom, left: x) } else if padding.len() == 4 { let (top, right, bottom, left) = padding return (top: top, right: right, bottom: bottom, left: left) } } else if type(padding) == dictionary { // Support typst padding dictionary let rest = padding.at("rest", default: 0) let x = padding.at("x", default: rest) let y = padding.at("y", default: rest) if not "left" in padding { padding.left = x } if not "right" in padding { padding.right = x } if not "top" in padding { padding.top = y } if not "bottom" in padding { padding.bottom = y } return padding } else { return (top: padding, left: padding, bottom: padding, right: padding) } } /// Creates a corner-radius dictionary with keys `north-east`, `north-west`, `south-east` and `south-west` with values of a two element {{array}} of the radius in the `x` and `y` direction. Returns none if all radii are zero or none. /// /// - ctx (context): The current canvas context object /// - radii (none, number, dictionary): The radius specification. A {{number}} will cause all corners to have the same radius. An {{array}} with two items will cause all corners to have the same rx and ry radius. A {{dictionary}} can be given where the key specifies the corner and the value specifies the radius. The value can be either {{number}} for a circle radius or {{array}} for an x and y radius. The keys `north`, `south`, `east` and `west` targets both corners in that cardinal direction e.g. `south` sets the south west and south east corners. The keys `north-east`, `north-west`, `south-east` and `south-west` targets the corresponding corner. The key `rest` targets all other corners that have not been target by other keys. /// - size (???): I'm not sure what this does. /// /// -> dictionary #let as-corner-radius-dict(ctx, radii, size) = { if radii == none or radii == 0 { return (north-west: (0,0), north-east: (0,0), south-west: (0,0), south-east: (0,0)) } let radii = (if type(radii) == dictionary { let rest = radii.at("rest", default: (0,0)) let north = radii.at("north", default: auto) let south = radii.at("south", default: auto) let west = radii.at("west", default: auto) let east = radii.at("east", default: auto) if north != auto or south != auto { assert(west == auto and east == auto, message: "Corner radius north/south and west/east are mutually exclusive! Use per corner radii: north-west, .. instead.") } if west != auto or east != auto { assert(north == auto and south == auto, message: "Corner radius north/south and west/east are mutually exclusive! Use per corner radii: north-west, .. instead.") } let north-east = if north != auto { north } else if east != auto { east } else {rest} let north-west = if north != auto { north } else if west != auto { west } else {rest} let south-east = if south != auto { south } else if east != auto { east } else {rest} let south-west = if south != auto { south } else if west != auto { west } else {rest} (radii.at("north-west", default: north-west), radii.at("north-east", default: north-east), radii.at("south-west", default: south-west), radii.at("south-east", default: south-east)) } else if type(radii) == array { panic("Invalid corner radius type: " + type(radii)) } else { (radii, radii, radii, radii) }).map(v => if type(v) != array { (v, v) } else { v }) // Resolve lengths to floats radii = radii.map(t => t.map(resolve-number.with(ctx))) // Clamp radii to half the size radii = radii.map(t => t.enumerate().map(((i, v)) => { calc.max(0, calc.min(if type(v) == ratio { v * size.at(i) / 100% } else { v }, size.at(i) / 2)) })) let (nw, ne, sw, se) = radii return ( north-west: nw, north-east: ne, south-west: sw, south-east: se, ) } /// Sorts an array of vectors by distance to a common position. /// - base (vector): The position to measure the distance of the other vectors from. /// - pts (array): The array of vectors to sort. /// -> array #let sort-points-by-distance(base, pts) = { if pts.len() == 1 { return pts } // Sort by transforming points into tuples of (point, distance), // sorting them by key 1 and then transforming them back to points. return pts.map(p => { return (p, vector.dist(p, base)) }) .sorted(key: t => t.at(1)) .map(t => t.at(0)) } /// Resolves a stroke into a usable dictionary with all fields that are missing or auto set to their Typst defaults. /// - stroke (none, stroke): The stroke to resolve. /// -> dictionary #let resolve-stroke(stroke) = { if stroke == none { return (paint: none, thickness: 0pt, join: none, cap: none, miter-limit: 4) } let default = ( paint: black, thickness: 1pt, join: "miter", cap: "butt", miter-limit: 4 ) let s = line(stroke: stroke).stroke let stroke = (:) for (k, v) in (paint: s.paint, thickness: s.thickness, join: s.join, cap: s.cap, miter-limit: s.miter-limit) { if v == auto { stroke.insert(k, default.at(k)) } else { stroke.insert(k, v) } } return stroke } /// Asserts whether a "body" has the correct type. #let assert-body(body) = { assert(body == none or type(body) in (array, function), message: "Body must be of type none, array or function") } // Returns body if of type array, an // empty array if body is none or // the result of body called with ctx if of type // function. A function result of none will return // an empty array. #let resolve-body(ctx, body) = { if type(body) == function { body = body(ctx) } if body == none { body = () } return body } #let str-to-number-regex = regex("^(-?\d*\.?\d+)(cm|mm|pt|em|in|%|deg|rad)?$") #let number-units = ( "%": 1%, "cm": 1cm, "mm": 1mm, "pt": 1pt, "em": 1em, "in": 1in, "deg": 1deg, "rad": 1rad ) #let str-is-number(string) = string.match(str-to-number-regex) != none #let str-to-number(string) = { let (num, unit) = string.match(str-to-number-regex).captures num = float(num) if unit != none and unit in number-units { num *= number-units.at(unit) } return num }
https://github.com/xichen1/typst-resume
https://raw.githubusercontent.com/xichen1/typst-resume/main/README.md
markdown
# typst-resume My resume built by typst An online version can be found in [typst](https://typst.app/project/rJLyb2qMKsxnQrRzXv8sNx). ## Preview ![resume preview](resume.png)
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/dialogue.header.typ
typst
#import "base-utils.typ": * #import "classroom.typ" #import "designer.typ" // functions.typ #let header(student-group: none, title: none, subtitle: none, topic: none) = { let leftContent = { if title != none { text(weight: "bold", fill: blue.darken(50%), size: 16pt, title) // v(0pt) } // if subtitle != none { // [==== #subtitle] // v(5pt) // } } let rightContent = { let store = () if topic != none { let a = colon("Topic", text(fill: blue, emph(topic))) store.push(a) } if student-group != none { let students = classroom.get-student-group(student-group) let names = students.map(map-names) let first = students.first() let grade = first.grade let className = first.className let b = colon("Student Group", names.join(" | ")) let c = [*Grade #grade #className Practice*] store.push(b) store.push(c) } stack(spacing: 0.95em, ..store) } let align-func(col, row) = { if col == 0 { center + horizon } else { right + horizon } } designer.line(stroke: "soft") table(stroke: none, columns: (2fr, 1fr), align: align-func, inset: 0pt, leftContent, rightContent) designer.line(stroke: "soft") v(10pt) }
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas6/0_Nedela.typ
typst
#let M = ( "HV": ( ("","","Pobídu imíja Christé júže na áda, na krest vozšél jesí: da vo ťmí smérti seďáščya voskresíši s sobóju, íže v mértvych svobóď: istočájaj živót ot svojehó svíta, vsesíľne Spáse, pomíluj nás."), ("","","Pobídu imíja Christé júže na áda, na krest vozšél jesí: da vo ťmí smérti seďáščya voskresíši s sobóju, íže v mértvych svobóď: istočájaj živót ot svojehó svíta, vsesíľne Spáse, pomíluj nás."), ("","","Dnés Christós smérť popráv, jákože rečé, voskrése, i rádovanije mírovi darová, da vsí vzyvájušče, písň táko rcém: istóčniče žízni, nepristúpnyj svíte, vsesíľne Spáse, pomíluj nás."), ("","","Tebé Hóspodi, súščaho po vséj tvári, hríšniji kámo bižím? Na nebesí sám živéši: vo áďi poprál jesí smérť: vo hlubiný morskíja? Támo ruká tvojá Vladýko. K tebí pribihájem, tebí pripádajušče mólimsja: voskresýj iz mértvych, pomíluj nás."), ("Dogmat","","Dostójno jésť jáko voístinnu, blažíti ťá Bohoródicu: v tvojé bo prečístoje všéd črévo vsích soďíteľ, plóť býsť, ne preložívsja jestestvóm, nižé mečtávsja o smotréniji: no vosprijáťij iz tebé slovésno oduševlénňij plóti sojedinívsja, po ipostási. Otňúduže blahočéstno, vo obojích jestestvách javľájuščichsja, ráznstvo tvorím. Tohó molí čéstnája presvjatája, nizposláti nám mír i véliju mílosť."), ), "S": ( ("","","Voskresénije tvojé Christé Spáse, ánheli pojút na nebesích, i nás na zemlí spodóbi, čístym sérdcem tebé sláviti."), ("","Vsjú otložívše","Kľátvoju jáko obiščá tvojemú práotcu drévle Bóh preľítnyj, v posľídňaja ľíta soverší, proizšéd prečístaja ot čréva tvojehó božéstvennaho: íbo voístinnu vozsijá iz tebé Hospóď, dlániju soderžáj koncý, jehóže i mňí blahouvétliva sotvorí v čás súdnyj Ďívo Maríje, tohó cárstvija mjá polučíti, dobroďítelej vozvyšénijem, i strastéj umerščvlénijem."), ("","","Umá čistotóju Isáija, Ďívo, izdaléča prorečé, rodíti imúščuju sozdáteľa vsejá tvári, ťá čéstnája prečístaja: tý bo javílasja jesí jedína vo víki vseneporóčnaja. Ťímže ťá moľú: oskvernénuju mojú dúšu očísti, i svítlosti božéstvennyja óbščnika mjá pokaží, i božéstvennaho Sýna tvojehó stojánija desnáho, jehdá sjádet, jákože písano jésť, sudíti míru vsemú."), ("","","Smérti razrušénije roždestvóm tvojím javísja, tý bo otrokovíca jesí životá netľínnaho prebyvánije. Ťímže ťá moľú: vo hrobích ádovych strastéj mojích sležášča tý voskresí, i k veséliju i oživléniju Ďívo, rukovodí, ko blažénnomu vozdajániju, i nehíblemyja i božéstvennyja spodóbi rádosti, iďíže sládosť prisnosúščnaja, iďíže svít nevečérnij."), ("Dogmat","","Prijidíte vsí jazýcy, vo hlási rádovanija presvjátúju Ďívu i Bohoródicu voschválim, čelovíčeskaho suščestvá hornílo, neizrečénnych čudés ďílatelišče, o tój bo býša nóvaja: beznačáľnyj načinájetsja, Slóvo odebeľivájet, Bóh čelovík byvájet, da Bóha čelovíka soďílajet, ne preminénijem jestéstv, no sojedinénijem po ipostási: proischódit bo jedín ot dvojú soprotívnych, vo dvoích soveršénnych jestestvách nerazďíľňi poznavájemyj, choťíteľňi že i ďíteľňi po obojú suščestvú: tójže po istótnomu vírujem byvája, rádi spasíteľnaho smotrénija Christós Bóh náš, míru podajá očiščénije, mír i véliju mílosť."), ), ) #let V = ( "HV": ( ("","","Pobídu imíja Christé, júže na áda, na krest vozšél jesí: da vo ťmí smérti seďáščyja voskrésíši s sobóju, íže v mértvych svobóď, istočájaj živót ot svojehó svíta, vsesíľne Spáse, pomíluj nás."), ("","","Dnés Christós smérť popráv, jákože rečé, voskrése, i rádovanije mírovi darová, da vsí vzyvájušče, písň táko rcém: istóčniče žízni, nepristúpnyj svíte, vsesíľne Spáse, pomíluj nás."), ("","","Tebé Hóspodi, súščaho po vséj tvári, hríšniji kámo bižím? Na nebesí sám živéši, vo áďi poprál jesí smérť, vo hlubiný morskíja? Támo ruká tvojá Vladýko. K tebí pribihájem, tebí pripádajušče mólimsja: voskrésýj iz mértvych pomíluj nás."), ("","","Krestóm tvojím Christé chválimsja, i voskresénije tvojé pojém i slávim: tý bo jesí Bóh náš. Rázve tebé ináho ne vímy."), ("","","Výnu blahoslovjášče Hóspoda, pojém voskresénije jehó: krest bo preterpív, smértiju smérť pohubí."), ("","","Sláva síľi tvojéj Hóspodi, jáko uprazdníl jesí deržávu imúščaho smérti: obnovíl jesí nás krestóm tvojím, dáruja nám živót i netľínije."), ("","","Pohrebénije tvojé Hóspodi, úzy ádovy sokrušívšeje rasterzá: jéže iz mértvych voskresénijem mír prosvití, Hóspodi sláva tebí."), ("","","Víďašči némošč mojú ťilésnuju, i dušévnoje stradánije, i serdéčnoje ozloblénije, posiščénija spodóbi mjá božéstvennaho, vseneporóčnaja Ďívo, spasí mja, moľúsja, téplymi tvojími molítvami."), ("","","Vsích preidóch Vladýčice, sohrišéňmi: no mnóžestva sích Ďívo očíščši, mílostej polučíti mí čístaja, spodóbi, v búduščem suďí Sýna i Bóha tvojehó."), ("","","Mnóžestvo sohrišénij mojích, zovúščaho očísti čístaja, i čúvstvij mojích neustávnaja dvižénija, molítvennym mečém ssicý: jáko da víroju i ľubóviju pojú tvojé bezsímennoje roždestvó."), ("Dogmat","","Któ tebé ne ublažít presvjatája Ďívo? Któ li ne vospojét tvojehó prečístaho roždestvá? Bezľítno bo ot Otcá vozsijávyj Sýn jedinoródnyj, tójže ot tebé čístyja prójde, neizrečénno voplóščsja, jestestvóm Bóh sýj, i jestestvóm býv čelovík nás rádi, ne vo dvojú licú razďiľájemyj, no vo dvojú jestestvú neslítno poznavájemyj. Tohó molí čístaja, vseblažénnaja, pomílovatisja dušám nášym."), ), "S": ( ("","","Voskresénije tvojé Christé Spáse, ánheli pojút na nebesích, i nás na zemlí spodóbi, čístym sérdcem tebé sláviti."), ("","","Vratá sokrušív mídnaja, i verejí ádovy sotrýj, jáko Bóh vsesílen, ród čelovíčeskij pádšij voskresíl jesí. sehó rádi i mý sohlásno vopijém: voskresýj iz mértvych, Hóspodi sláva tebí."), ("","","Tľínija nás drévňaho Christós ispráviti choťá, na kresťí prihvoždájetsja, i vo hróbi polahájetsja, jehóže mironósicy žený so slezámi iskáchu, pláčuščja hlahólachu: uvý nám spáse vsích, káko izvólil jesí vo hróbe vselítisja? Vselívyjsja že choťá, káko ukráden býl jesí? Káko preložílsja jesí? Kóje že místo tvojé živonósnoje sokrý ťílo? No Vladýko, jáko obiščálsja jesí nám javísja, i utolí ot nás rydánije sléz. Pláčuščymsja že ím, ánhel k ním vozopí: ot pláča prestávša apóstolom rcýte, jáko voskrése Hospóď, mírovi dáruja očiščénije, i véliju mílosť."), ("","","Raspnýjsja jáko voschoťíl jesí Christé, i smérť pohrebénijem tvojím pľinívyj, tridnéven voskrésl jesí, jáko Bóh so slávoju, mírovi dáruja bezkonéčnuju žízň, i véliju mílosť."), ("Dogmat","","Tvoréc i izbáviteľ mój prečístaja, Christós Hospóď iz tvojích ložésn prošéd, v mjá obolkíjsja, pérvyja kľátvy Adáma svobodí. Ťímže tí vsečístaja, jáko Bóžiji Máteri že i Ďívi, voístinnu vopijém nemólčno: rádujsja ánheľski, rádujsja Vladýčice, predstáteľstvo i pokróve, i spasénije dúš nášich."), ), "T": ( ("","","Ánheľskija síly na hróbi tvojém, i strehúščiji omertvíša: i stojáše Maríja vo hróbi, íščušči prečístaho ťíla tvojehó. Pľiníl jesí ád, ne iskusívsja ot nehó: srítil jesí Ďívu dárujaj živót. Voskrésýj iz mértvych, Hóspodi sláva tebí."), ("Bohoródičen","","Bláhoslovénnuju narekíj tvojú Máter, prišél jesí na strásť vóľnym choťínijem, vozsijáv na kresťí, vzyskáti choťá Adáma, hlahóľa ánhelom: srádujtesja mňí, jáko obrítesja pohíbšaja dráchma, vsjá múdre ustróivyj Bóže náš, sláva tebí."), ), ) #let P = ( "1": ( ("","","Jáko po súchu pišešéstvovav Izrájiľ po bézdňi stopámi, honíteľa faraóna víďa potopľájema, Bóhu pobídnuju písň pojím vopijáše."), ("","","Neoskúdnu blahodáť imúšči jáko božéstvennuju, Máti beznevístnaja, k tebí pribihájuščich ne prézri, ot bíd i skorbéj prísno spasájušči."), ("","","Sé vrémja nastá mojehó unýnija, vostáni prečístaja Vladýčice, i pómošči dážď mí rúku: tý bo mír božéstvennaho vesélija ispólnila jesí."), ("","","Deržávnyj tvój pokróv, Bohorodíteľnice, jáko zastúpnica súšči, dážď mí vskóri napásťmi oderžímu, i nevrédna ot sích sochraní mja."), ("","","Duší mojéj smérť pritekájet, iskušénija že nenavíďaščich, jáko áspidy obydóša pohubíti mjá: no samá mja Bohoródice, spasí."), ), "3": ( ("","","Razširíšasja na vrahí mojá ustá mojá, jáko utverdísja o Hóspoďi sérdce mojé."), ("","","Umerščvlénnuju dúšu mojú prehrišéňmi, živót jáko róždšaja Bohoródice oživí."), ("","","Ot vsjákaho iskušénija sobľudí, k tebí pribihájuščich Bohoródice, upovánije náše."), ("","","Ot vostajúščich na mjá napástej hórko, spasí mja Máti Hóspoda mojehó preneporóčnaja."), ("","","Jáže mírovi spasénije podajúšči božéstvennym roždestvóm tvojím, ot bíd mjá preminí."), ), "4": ( ("","","Uslýša prorók prišéstvije tvojé Hóspodi, i ubojásja, jáko chóščeši ot Ďívy rodítisja, i čelovíkom javítisja: i hlahólaše: uslýšach slúch tvój, i ubojáchsja: sláva síľi tvojéj Hóspodi."), ("","","Iznemóže niščetóju kríposť duší mojejá, Bohorodíteľnice, i ľútoje na mjá omračénije napadé, ot prehrišénij imúščeje nachód: prízri jáko svitonósnyj óblak Bóžij: i prosvití mja, moľúsja."), ("","","Búri zól mojích, i smuščénije prehrišénij, preloží v tišinú spasénija, jáko súšči pristánišče, vseneporóčnaja: rykájušče íščut mjá, jáko ľvóve požréti, páhuby ťích izbávi mjá, moľúsja."), ("","","V noščí i vo dní, na zemlí že i v móri, i na vsjákom míste, spasénije tvérdo súšči, Bohoródice pokróve nepobidímyj, spasáj mjá: po Bózi bo na ťá voístinnu christijáne upovájem."), ("","","Ot velíkich i razlíčnych prehrišénij že i napástej, vsehdá spasáješi mjá: ťímže jáko róždšuju ťá Hóspoda moľú, i k tebí pribiháju, nepobidímij pómošči skorbjáščym: ot bíd izvedí moľbámi tvojími."), ), "5": ( ("","","Svít vozsijáj míru Christé, prosvití sérdce mojé ot nóšči tebí zovúšča, i spasí mja."), ("","","Spasénija ťá pokróv slávim, Slóva Máti, vseneporóčnaja, navét ne bojáščesja čelovíčeskich."), ("","","Imúšče ťá sťínu neoborímu, iskušénij že i pečáli vostánija izbavľájemsja, prečístaja."), ("","","Izmí mja ot zlých čelovík jazýka, čístaja: jákože bo brítva izostrísja, pohubíti iskíj dúšu mojú hórko."), ("","","Priľížno tí pripádaju, moľásja: jáko Máti ziždíteľa mojehó, oderžáščich mjá bíd svobodí."), ), "6": ( ("","","Kítom požrén hrichóvnym, vopijú tebí Christé, jáko proróka iz istľínija mjá svobodí."), ("","","Hóresti vkús prijém, božéstvennyja sládosti otčuždíchsja prečístaja. Ťímže vopijú ti: dáruj mí pómošč."), ("","","Omračénije strastéj, rabá mja tlí soďíla: ťímže svít róždšaja, svobodí mja Vladýčice."), ("","","Sohlásno tebí i vírno ispovídajusja, prečístaja, i požrú tí žértvu, tobóju izbávľsja skórbi."), ("","","Otverzóšasja na mjá neprávdy ustá, Vladýčice: ťímže mjá jáko zastúpnica, sích vskóri svobodí."), ), "S": ( ("","","Predstáteľstvo christiján nepostýdnoje, chodátajstvo ko tvorcú neprelóžnoje, ne prézri hríšnych molénij hlásy: no predvarí jáko blahája na pómošč nás, vírno zovúščich tí: uskorí na molítvu, i potščísja na umolénije predstáteľstvujušči prísno Bohoródice, čtúščich ťá."), ), "7": ( ("","","Rosodáteľnu úbo péšč soďíla ánhel prepodóbnym otrokóm, chaldéji že opaľájuščeje veľínije Bóžije mučíteľa uviščá vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Iskušénija dúši mojejá, júže túčniji juncý nýňi obydóša, presvjatája Ďívo, samá mja sích svobodí."), ("","","Zaščiščájušči tóščno, v biďí súščich i v pečáli, rádosť Bohoródice, podajéši vsehdá."), ("","","Pobiždéna mjá vsehó otčájanijem ďíl i pečáli, ohradí mja Ďívo, jáko pokróv vsím nerušímyj."), ("","","Predstáteľstvom tvojím izbavľájemsja bíd i skorbéj, i obritájem bohátstvo vélije neistoščájemo."), ), "8": ( ("","","Iz plámene prepodóbnym rósu istočíl jesí, i právednaho žértvu vodóju popalíl jesí: vsjá bo tvoríši Christé, tókmo jéže choťíti, ťá prevoznósim vo vsjá víki."), ("","","Ot čelovíčeskich sňidájusja ozloblénij, i moľúsja Bohoródice, izbávi mjá sújetnaho sovíta ích."), ("","","Pobidíchsja v pečálech iskušéniji mojími, i moľúsja Vladýčici, ot sích mjá spasí nevredíma."), ("","","Spasí mja čístaja, ot čelovíka ľstíva, i jazýka, i úst, i mučíteľstva, i vsjákija núždy."), ("","","Íže nrávom preľščájem jésm, bez otvíta sýj, k Bohoródice zovú: vsjáčeskich mjá izbávi zól."), ), "9": ( ("","","Jéže rádujsja ot ánhela prijímšaja, i róždšaja sozdáteľa svojehó, Ďívo, spasí ťa veličájuščyja."), ("","","Mílostiva mí v pečálech žitijá Bohoródice búdi, i spasí ot bíd nýňi pribihájuščaho k tebí."), ("","","Voístinnu jedína na zemlí i v móri javílasja jesí čístaja, króv nerazorím, pribihájuščym tí nesumňínnoju dušéju."), ("","","Bez umá sebí vsjáčeskimi porabótivšu ľútymi padéňmi, moľbámi tvojími svobódu podážď mí vsepítaja."), ("","","Ťá nadéždu i zastuplénije tvérdo sťažáv čístaja, veličája ťá jáko Bohoródicu, písň víroju skončaváju."), ), ) #let N = ( "1": ( ("","","Jáko po súchu pišešéstvovav Izrájiľ po bézdňi stopámi, honíteľa faraóna víďa potopľájema, Bóhu pobídnuju písň pojím, vopijáše."), ("","","Trí ipostási pojém Bohonačáľnyja, jedínstvennaho jestestvá neizmínnyj zrák, blaháho čelovikoľúbca Bóha, prehrišénij očiščénije nám dárujušča."), ("","","Presúščnyj jedíne, i trisijánnyj načertáňmi Hóspodi, v božestvíé jedínom sýj, vrazumí nás, i spodóbi tvojehó božéstvennaho sijánija."), ("","","Nevistoukrasív Pável, júže ot jazýk cérkov, jedínomu tebí trijipostásnomu Bóhu poklaňátisja naučí, ot nehóže, i ímže, i v némže vsjá býša."), ("Bohoródičen","","Iz čréva tvojehó prójde úmnoje Bohoródice sólnce, i osijá nás trisvítlaho božestvá zarjámi: jehóže pojúšče, blahočéstno ťá ublažájem."), ), "3": ( ("","","Ňísť svját, jákože tý Hóspodi Bóže mój, voznesýj róh vírnych tvojích bláže, i utverdívyj nás na kámeni ispovídanija tvojehó."), ("","","Ukrasív trisvítlyj Bóže číny nebésnyja, ustrójil jesí píti ťá trisvjatými hlásy: s nímiže prijimí i nás vospivájuščich tvojú bláhosť."), ("","","Jedíno neprelóžnoje Tróičnoje, soobráznoje jedínstvennoje Bohonačálije pojúšče, mólim ťá tépľi, hrichóv mnóhich nizposláti nýňi nám proščénije."), ("","","Úme beznačáľnyj ótče, soobráznyj Bóžij Slóve, i Dúše božéstvennyj, blahíj i právyj, vospivájuščyja vírno tvojú deržávu, sobľudí jáko blahoutróben."), ("Bohoródičen","","Pážiť potrebí tlí, čelovík po suščestvú býv Bóh mój, vo utróbi tvojéj čístaja: i rodonačáľniki préždňaho osuždénija jedín svobodí."), ), "S1": ( ("","Jéže o nás","Vladýko Bóže, prízri s nebesé, i vížď náše smirénije jáko ščédr, i umilosérdisja čelovikoľúbče preblahíj: ni otkúdu bo naďíjemsja proščénije polučíti zlých, ímiže sohrišíchom. Ťímže búdi s námi, i niktóže na ný."), ("Bohoródičen","","Vladýčice čístaja, prízri Bohoródice, vížď nášich jázv boľízni, i umilosérdisja prečístaja, i iscilí sóvistnoje žžénije, tvojéju mílostiju orošájušči, i vopijúšči rabóm tvojím: áz jésm s vámi, i niktóže na vý."), ), "4": ( ("","","Christós mojá síla, Bóh i Hóspoda, čéstnája cérkov, bohoľípno pojét vzyvájušči, ot smýsla čísta o Hóspoďi prázdnujušči."), ("","","Vozvyšájaj mýsľ, jedínice trisvítlaja, i dúšu i sérdce tvojích pivéc skóro vozvedí, i sijánija tvojehó i svítlosti spodóbi."), ("","","Pretvorí i preobrazí ot zlóby mjá vsjákija k dobroďíteli, jedína neizobražénnaja, i neizmínnaja Tróice, i tvojími zarjámi prosvití."), ("","","Pomýsliv préžde, múdre sostávil jesí ánhelov číny, služíteľnyja tvojejá bláhosti, triipostásnaja jedínice, s nímiže prijimí mojú chvalú."), ("Bohoródičen","","Íže jestestvóm nesozdánnyj Bóh prisnosúščnyj, sozdánnoje vosprijém čelovíčeskoje jestestvó, vozobrazí vo svjaťíj tvojéj utróbi, Bohoródice prisnoďívo."), ), "5": ( ("","","Bóžijim svítom tvojím bláže, útreňujuščich tí dúšy ľubóviju ozarí, moľúsja: ťá víďiti Slóve Bóžij, ístinnaho Bóha, ot mráka hrichóvnaho vzyvájušča."), ("","","Pomyšľájušče jestestvó bohonačáľnoje, promyslíteľnoje i spasíteľnoje vsích súščeje Vladýko, trisvítloje že jedíno, k tebí útreňujem, proščénija prosjášče hrichopadénij."), ("","","Ótče beznačáľnyj Bóže, i soprisnosúščnyj Sýne, i Dúše svjatýj, utverdí jedinonačáľnaja Tróice tvojá pivcý, i ot vsjákija napásti izbávi i skórbi."), ("","","Upravľájaj sijáňmi bohoďíteľnymi, i k blahouhoždéniju tvojehó trijipostásnaho božestvá, sólnce slávy, nastavľája mjá prísno, i božéstvennaho cárstvija sotvorí pričástnika."), ("Bohoródičen","","Íže vsjá nosjáj i sobľudájaj vsesíľnoju tvojéju rukóju Slóve Bóžij neizmínne, sochraní i sobľudí ťa slávjaščyja, molítvami róždšyja ťá Bohomátere."), ), "6": ( ("","","Žitéjskoje móre vozdvizájemoje zrjá napástej búreju, k tíchomu pristánišču tvojemú priték vopijú ti: vozvedí ot tlí živót mój, mnohomílostive."), ("","","Premúdrosť i rázum, bohonačálije trisvítloje pevcém tvojím dáruj, i dobróty lučámi svitoďíteľnyja tvojejá bláhosti, osijavátisja vsích spodóbi."), ("","","Premúdrosť i rázum, bohonačálije trisvítloje pevcém tvojím dáruj, i dobróty lučámi svitoďíteľnyja tvojejá bláhosti, osijavátisja vsích spodóbi."), ("","","Svíte nerazďíľnyj po suščestvú, trisijánne, vsederžíteľňi, nepristúpne, serdcá ozarí vírno chváľaščich deržávu tvojú, i k božéstvenňij ľubví vperí."), ("Bohoródičen","","V ťá vselísja prisnoďívo, jávi vsederžíteľ i Hospóď vsích, i jedínomu trisijánnomu zráku božestvá čelovíki poklaňátisja naučí."), ), "S2": ( ("","Jéže o nás","Ótče i Sýne so Dúchom svjatým, prízri na ný víroju tebí poklaňájuščyjasja, i slávjaščyja deržávu tvojú blahoutróbne, so óhnennymi brénniji, inóho bo rázvi tebé ne vímy, i vozopíj pojúščym ťá: áz jésm s vámi, i niktóže na vý."), ("Bohoródičen","","Prízri na ný vsepítaja Bohoródice, vozsijáj prosviščénije serdcám omračénnym, i ozarí stádo tvojé prečístaja. Jelíko bo chóščeši i móžeši, jáko Máti súšči ziždíteľa tvojehó, i vozopíj moľáščym ťá: áz jésm s vámi, i niktóže na vý."), ), "7": ( ("","","Rosodáteľnu úbo péšč soďíla ánhel prepodóbnym otrokóm, chaldéji že opaľájuščeje veľínije Bóžije mučíteľa uviščá vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Krípkuju mňí mýsľ ustrój trisvítlaja načertáňmi jedínice, jéže chraníti i sobľudáti božéstvennyja zápovidi tvojá, i vsehdá píti tebí vírno: blahoslovén jesí Bóže otéc nášich."), ("","","Jáko tóždestvom jestestvá pojémyj, neizrečénno jedínstvennyj Bóže, lícy že Tróicy nosjá čisló, sobľudí vsích nás ot razlíčnych iskušénij i obstojánij."), ("","","Sojestéstvenna i soprisnosúščna slávim, jedínaho ťá po suščestvú Bóha, svójstvy neslijánňi ipostásnymi Tróici, razlíčnoje prósto predlahájušče, vo zráci nepreménňim jávi."), ("Bohoródičen","","Bóh presúščnyj priját, prečístaja, ot čréva tvojehó čístaho náše čelovikoľubézňi smešénije jávi, i vsích naučí vopíti: blahoslovén jesí Bóže otéc nášich."), ), "8": ( ("","","Iz plámene prepodóbnym rósu istočíl jesí, i právednaho žértvu vodóju popalíl jesí: vsjá bo tvoríši Christé, tókmo jéže choťíti: ťá prevoznósim vo vsjá víki."), ("","","Očiščénije prehrišénij skóro podážď mí, i strastéj mnohoobráznych izbavlénije, soobráznaja Tróice, jedínice trijipostásnaja: da ťá slávľu vo vsjá víki."), ("","","Volíteľ mílosti izvéstvovan, jáko Bóh mílostiv, vsích pomíluj trisvítlaja jedínice i Tróice preblahája, slavoslóvjaščich tvojé velíčestvije."), ("","","Ot svíta prisnosúščnaho Otcá, svíta soprisnosúščna róždšasja Slóva, so Dúchom ischódnym svítom, víroju slávim, i prevoznósim vo vsjá víki."), ("Bohoródičen","","Vračá čelovíkom prečístaja, rodilá jesí vsesíľnaho Slóva, Christá Hóspoda, prarodíteľnyja jázvy vsích isciľájušča, prevoznosjáščich jehó vo víki."), ), "9": ( ("","","Bóha čelovíkom ne vozmóžno víďiti, na nehóže ne smíjut číni ánheľstiji vziráti: tobóju že vsečístaja, javísja čelovíkom slóvo voploščénno. jehóže veličájušče, s nebésnymi vói ťá ublažájem."), ("","","Zríti čínove cheruvímstiji Vladýko, dobróty tvojejá slávy ne mohúšče, kríly pokryvájuščesja, neprestánno Tróičnuju písň vopijút, trijipostásnuju tvojehó bohonačálija jedínstvennaho deržávu slávjašče."), ("","","Tvojá sijánija sólnce nezachodímoje, tvojích rabóv podážď serdcám, i prosvití dúšy, i izbávi ot mnóhich prehrišénij jedíne vsemílostive, i trijipostásne: i netľínnyja tvojejá žízni nás spodóbi."), ("","","Jéže svít jedinočéstnyj, i trisólnečnyj, i svitoďíteľnyj, božestvó súščeje ozarí víroju ťá pojúščich, i ot mráčnaho izbávi zloďíjstva, i spodóbi svitľíjšich tvojích selénij, jáko preblahíj."), ("Bohoródičen","","Premúdre čelovíka préžde sozdá Sýn tvój Ďívo, i istľívšaho obnoví tobóju vsepítaja: i božéstvennaho svíta zarí nevečérnija vsích ispólni, ťá Bohoródicu ístinnu víroju slávjaščich."), ), ) #let U = ( "T": ( ("","","Ánheľskija síly na hróbi tvojém, i strehúščiji omertvíša: i stojáše Maríja vo hróbi, íščušči prečístaho ťíla tvojehó. Pľiníl jesí ád, ne iskusívsja ot nehó: srítil jesí Ďívu dárujaj živót. Voskrésýj iz mértvych, Hóspodi sláva tebí."), ("Bohoródičen","","Bláhoslovénnuju narekíj tvojú Máter, prišél jesí na strásť vóľnym choťínijem, vozsijáv na kresťí, vzyskáti choťá Adáma, hlahóľa ánhelom: srádujtesja mňí, jáko obrítesja pohíbšaja dráchma, vsjá múdre ustróivyj Bóže náš, sláva tebí."), ), "S1": ( ("","","Hróbu otvérstu, ádu pláčuščusja, Maríja vopijáše ko skrývšymsja apóstolom: izydíte vinohráda ďílatelije, propovídite voskrésnija slóvo: voskrése Hospóď, podajá mírovi véliju mílosť."), ("","","Hóspodi, predstojáše hróbu tvojemú Maríja Mahdalína, i plákaše vopijúšči, vertohrádarja ťá mňášči, hlahólaše: hďí sokrýl jesí véčnyj živót? Hďí položíl jesí, íže na prestóľi cheruvímsťim? Strehúščiji bo sehó, ot strácha omertvíša. Ilí Hóspoda mojehó dadíte mí, ilí so mnóju vozopíjte: íže v mértvych býv, i mértvyja voskresív, sláva tebí."), ("Bohoródičen","","Prednapisújet Hedeón začátije, i skazújet Davíd roždestvó tvojé Bohoródice: sníde bo jáko dóžď na runó, Slóvo vo črévo tvojé, i prozjablá jesí bez símene, zemlé svjatája, mírovi spasénije, Christá Bóha nášeho, blahodátnaja."), ), "S2": ( ("","","Živót vo hróbi vozležáše, i pečáť na kámeni nadležáše: jáko carjá spjášča vójini strežáchu Christá, i vrahí svojá nevídimo porazívyj, voskrése Hospóď."), ("","","Prednapisújet Jóna hrób tvój, i skazújet Simeón vostánije božéstvennoje, bezsmértne Hóspodi: sošél bo jesí jáko mértv vo hrób, razrušívyj ádova vratá. Voskrésl že jesí kromí tľínija jáko Vladýka, vo spasénije míra, Christé Bóže náš, prosvitívyj súščyja vo ťmí."), ("Bohoródičen","","Bohoródice Ďívo, molí Sýna tvojehó, vóleju prihvoždénnaho na kresťí, i voskrésšaho iz mértvych Christá Bóha nášeho, spastísja dušám nášym."), ), "Y": ( ("","","Vóľnoju i životvorjáščeju tvojéju smértiju Christé, vratá ádova sokrušív jáko Bóh, otvérzl jesí nám drévnij ráj, i voskrés iz mértvych, izbávil jesí ot tľínija živót náš."), ), "A1": ( ("","","Na Nébo óči mojí vozvožú, k tebí Slóve: uščédri mjá, da živú tebí."), ("","","Pomíluj nás uničižénnych, ustrojája blahopotrébnyja tvojá sosúdy Slóve."), ("","","Svjatómu Dúchu, vsjákaja vsespasíteľnaja viná, ášče kójemu séj po dostojániju dchnét, skóro vzémlet ot zemných: vosperjájet, vozraščájet, ustrojájet horí."), ("","","Svjatómu Dúchu, vsjákaja vsespasíteľnaja viná, ášče kójemu séj po dostojániju dchnét, skóro vzémlet ot zemných: vosperjájet, vozraščájet, ustrojájet horí."), ), "A2": ( ("","","Ášče ne Hospóď by býl v nás, niktóže ot nás protívu vozmóhl by vrážijim bránem odoľíti: pobiždájuščiji bo ot zďí voznósjatsja."), ("","","Zubý ích da ne játa búdet dušá mojá jáko ptenéc, Slóve: uvý mňí, káko ímam ot vrahá izbýti hrichoľubív sýj!"), ("","","Svjatým Dúchom obožénije vsím, blahovolénije, rázum, mír i blahoslovénije: ravnoďíteľen bo jésť Otcú i Slóvu."), ("","","Svjatým Dúchom obožénije vsím, blahovolénije, rázum, mír i blahoslovénije: ravnoďíteľen bo jésť Otcú i Slóvu."), ), "A3": ( ("","","Naďíjuščijisja na Hóspoda vrahóm strášni, i vsím dívni: horí bo zrját."), ("","","V bezzakónija rúk svojích, právednych žrébij, pomóščnika ťá imíja Spáse, ne prostirájet."), ("","","Svjatáho Dúcha deržáva na vsích: jemúže výšňaja vójinstva poklaňájutsja, so vsjákim dychánijem dóľnym."), ("","","Svjatáho Dúcha deržáva na vsích: jemúže výšňaja vójinstva poklaňájutsja, so vsjákim dychánijem dóľnym."), ), "P": ( ("","","Hóspodi, vozdvíhni sílu tvojú, i prijidí vo jéže spastí nás."), ("","","Pasýj Izráiľa vonmí, nastavľájaj jáko ovčá Jósifa."), ), "K": ( "P1": ( "1": ( ("","","Jáko po súchu pišešéstvovav Izráiľ, po bézdňi stopámi, honíteľa faraóna víďa potopľájema, Bóhu pobídnuju písň pojím, vopijáše."), ("","","Rasprostértyma dláňma na kresťí, Otéčeskaho ispólnil jesí blahovolénija, blahíj Iisúse, vsjáčeskaja. Ťímže pobídnuju písň tebí vsí pojím."), ("","","Stráchom k tebí jáko rabýňa, smérť poveľína pristupí Vladýci životá, tóju podajúščemu nám bezkonéčnyj živót i voskresénije."), ("Bohoródičen","","Svojehó prijémši soďíteľa, jáko sám voschoťí, ot bezsímennaho tvojehó čréva, páče umá voploščájema, čístaja, tvárej voístinnu javílasja jesí Vladýčica."), ), "2": ( ("","","Volnóju morskóju skrývšaho drévle honíteľa mučíteľa pod zemléju skrýša spasénnych ótrocy: no mý jáko otrokovícy, Hóspodevi pojím, slávno bo proslávisja."), ("","","Sudílišču Pilátovu predstojít choťá bezzakónnomu sudú, jáko sudím sudijá, i ot rukí neprávdy po licú zaušájetsja Bóh, jehóže trepéščut zemľá, i nebésnaja."), ("","","Prostérl jesí božéstvenniji dláni tvojí Spáse, na prečísťim tvojém i živonósňim kresťí: i sobrál jesí jazýki v poznánije tvojé Vladýko, poklaňájuščyjasja Hóspodi, slávnomu tvojemú raspjátiju."), ("Krestobohoródičen","","Stojáše sléz istóčniki ispuščájušči, preneporóčnaja pri kresťí tvojém Spáse, jáže ot rebrá tvojehó kápli krovéj zrjášči Christé, i tvojú bezprikládnuju mílosť slávjašči."), ), "3": ( ("","","Jáko po súchu pišešéstvovav Izráiľ, po bézdňi stopámi, honíteľa faraóna víďa potopľájema, Bóhu pobídnuju písň pojím, vopijáše."), ("","","Pričáščšisja Jéva sadú, preslušánnaho brášna, kľátvu vvedé: no sijú razríšila jesí čístaja, blahoslovénija načátok Christá róždši."), ("","","Jáže bísera ot božéstvennyja mólniji Christá róždši, strastéj mojích mhlú, i prehrišénij smuščénije čístaja, razžení svítom tvojejá svítlosti."), ("","","Jazýkov čájanije, Jákov iz tebé voploščájemaho predzrjáše tájno úmnyma očíma Bóha, izbávľšaho nás chodátajstvom tvojím."), ("","","Oskuďívšym kňazém ot koľína júdova prečístaja, Sýn tvój i Bóh, prošéd vóžď, nad koncý zemnými nýňi voístinnu vocarísja."), ), ), "P3": ( "1": ( ("","","Ňísť svját, jákože tý Hóspodi Bóže mój, voznesýj róh vírnych tvojích bláže, i utverdívyj nás na kámeni ispovídanija tvojehó."), ("","","Bóha raspinájema plótiju zrjášči tvár rastajavášesja stráchom: no soderžítelnoju dlániju nás rádi raspjátaho, krípko deržíma bí."), ("","","Smértiju smérť razoréna ležít okajánnaja bez dychánija: životá bo ne terpjášči božéstvennaho priražénija, umerščvľájetsja krípkij, i dárujetsja vsím voskresénije."), ("Bohoródičen","","Božéstvennaho roždestvá tvojehó čístaja, vsjákij jestestvá čín prevoschódit čúdo: Bóha bo prejestéstvenňi začalá jesí vo črévi, i róždši prebyváješi prísno Ďíva."), ), "2": ( ("","","Tebé na vodách povísivšaho vsjú zémľu neoderžímo, tvár víďivši na lóbňim vísima, úžasom mnóhim sodrahášesja, ňísť svját rázvi tebé Hóspodi, vzyvájušči."), ("","","Vo hróbi tridnévstvovavyj voskresíl jesí životvorjáščim vostánijem tvojím préžde umerščvlénnyja, i osuždénija razrišívšesja rádostno veseľáchusja, sé izbavlénije prišél jesí Hóspodi, vzyvájušče."), ("","","Sláva tvojemú vostániju Spáse náš, jáko nás ot áda tľínija, i smérti izbávil jesí jáko vsesílen, i pojúšče hlahólem: ňísť svját rázvi tebé Hóspodi čelovikoľúbče."), ("Bohoródičen","","Tý ot tebé róždšahosja jáko víďila jesí ujázvlena kopijém, ujazvílasja jesí sérdcem presvjatája vseneporóčnaja, i užasájuščisja hlahólala jesí: čtó tebí vozdadé, čádo, naród prebezzakónnyj?"), ), "3": ( ("","","Ňísť svját, jákože tý Hóspodi Bóže mój, voznesýj róh vírnych tvojích bláže, i utverdívyj nás na kámeni ispovídanija tvojehó."), ("","","Tľínnuju mojú plóť i smértnuju, vsečístaja Bohomáti, iz čréva tvojehó neskazánno prijém blahíj, i obeztľíniv sijú, víčňi sebí svjazál jésť."), ("","","Bóha voploščájema iz tebé zrjášče Ďívo, užasáchusja stráchom lícy ánheľstiji, i jáko Máter Bóžiju nemólčnymi písňmi ťá počitájut."), ("","","Užasésja, hóru úmnuju víďiv ťá prorók Danijíl, iz nejáže kámeň otsičésja kromí rúk: i démonskaja kápišča, Bohomáti, krípko sokruší."), ("","","Ne móžet slóvo ťá čelovíčeskoje, nižé jazýk Ďívo pochvalíti dostójno: iz tebé bo bez símene žiznodávec Christós voplotítisja, prečístaja, blahovolí."), ), ), "P4": ( "1": ( ("","","Christós mojá síla, Bóh i Hospóď, čéstnája cérkov Bohoľípno pojét vzyvájušči, ot smýsla čísta o Hóspoďi prázdnujušči."), ("","","Drévo procviló jésť Christé, ístinnyja žízni: krest bo vodruzísja, i napojén býv króviju i vodóju ot netľínnaho tvojehó rebrá, živót nám prozjabé."), ("","","Ne ktomú zmíj mňí lóžňi obožénije podlahájet: Christós bo Bohoďílateľ čelovíčeskaho jestestvá, nýňi nevozbránno stezjú životá mňí otvérze."), ("Bohoródičen","","Jáko voístinnu neizviščánna i nepostižíma, jáže tvojehó Bohoľípnaho Bohoródice súť roždestvá, súščym na zemlí i na nebesí, prisnoďívo, táinstva."), ), "2": ( ("","","Na kresťí tvojé božéstvennoje istoščánije províďa Avvakúm, užássja vopijáše: Tý síľnych presíkl jesí deržávu Bláže, priobščájasja súščym vo áďi, jáko vsesílen."), ("","","Čéstnýj krest tvój počitájem, i hvózdi Christé, i svjatóe kopijé s tróstiju, vinéc íže ot térnij, ímiže ot ádova istľínija izbávichomsja."), ("","","Hrób Spáse ťá podját vóleju mértva o nás jávľšahosja, no nikákože vozmóže Slóve, uderžáti: jáko Bóh bo voskrésl jesí, spasája ród náš."), ("Krestobohoródičen","","Bohorodíteľnice prisnoďívo, Spása Christá čelovíkom róždšaja, ot bíd i múk izbávi nás, pribihájuščich víroju k božéstvennomu pokróvu tvojemú."), ), "3": ( ("","","Christós mojá síla, Bóh i Hospóď, čéstnája cérkov Bohoľípno pojét vzyvájušči, ot smýsla čísta o Hóspoďi prázdnujušči."), ("","","Pojém prečístaja tebé vseneporóčnuju, íže tobóju spásšijisja, i blahočéstno pojúšče vzyvájem: blahoslovénna, jáže Bóha prisnoďívo róždšaja."), ("","","Svít nezachodímyj Ďívo rodilá jesí, súščym vo ťmí žitijá, plótiju sviťášč vseblažénnaja, i pojúščym ťá, rádosť prisnoďívo istočíla jesí."), ("","","Bláhodáť procvité, zakón prestá, tobóju vsesvjatája: tý bo čístaja, rodilá jesí Hóspoda, podajúščaho nám prisnoďívo, ostavlénije."), ("","","Mértva mjá pokazá sadá vkušénije, žízni že drévo iz tebé jávľšejesja prečístaja, voskresí, i rájskija sládosti nasľídnika mjá ustróji."), ), ), "P5": ( "1": ( ("","","Bóžijim svítom tvojím bláže, útreňujuščich tí dúšy ľubóviju ozarí, moľúsja, ťá víďiti Slóve Bóžij, ístinnaho Bóha, ot mráka hrichóvnaho vzyvájušča."), ("","","Ustupájut mňí Cheruvímy nýňi, i plámennoje orúžije, Vladýko, pleščí mňí dajét, ťá víďivše Slóve Bóžij ístinnaho Bóha, razbójniku púť sotvóršaho v ráj."), ("","","Ne ktomú bojúsja, jéže v zémľu Vladýko Christé vozvraščénija: tý bo ot zemlí mjá vozvél jesí zabvénna, blahoutróbija rádi mnóhaho, k vysoťí netľínija voskresénijem tvojím."), ("Bohoródičen","","Íže Bohoródicu ťá ot duší, Vladýčice míra blahája, ispovídajuščich spasí: tebé bo predstáteľstvo nepoborímoje ímamy, ístinnuju Bohorodíteľnicu."), ), "2": ( ("","","Bohojavlénija tvojehó Christé, k nám mílostivno bývšaho, Isáija svít víďiv nevečérnij iz nóšči útrenevav vzyváše: voskrésnut mértviji, i vostánut súščiji vo hrobích, i vsí zemnoródniji vozrádujutsja."), ("","","Sňídiju dréva vo Jedémi prelstívyjsja v tľú popolzé rodonačáľnik, preslúšavyj Hóspodi zápovidi tvojá preblahíj: no sehó krestóm páki vozvél jesí v pérvuju dobrótu, poslušlív Otcú Spáse bývyj."), ("","","Tvojéju smértiju bláže, smérti potrebísja deržáva, istóčnik žízni nám istočí, i bezsmértije darovásja: sehó rádi pohrebéniju tvojemú i voskreséniju víroju poklaňájemsja, ímže jáko Bóh mír vés prosvitíl jesí."), ("Krestobohoródičen","","Živýj na nebesích i tvoréc vsích Hospóď, vo tvojú vseneporóčnaja, vselísja neizrečénno utróbu, proslávivyj ťá prevýššuju nebés, i svjaťíjšuju činóv neveščéstvennych: ťímže nýňi íže na zemlí ťa ublažájem."), ), "3": ( ("","","Bóžijim svítom tvojím bláže, útreňujuščich tí dúšy ľubóviju ozarí, moľúsja, ťá víďiti Slóve Bóžij, ístinnaho Bóha, ot mráka hrichóvnaho vzyvájušča."), ("","","Čistotóju vozsijávši svítlo božéstvennoje prebyvánije Vladýki vsepítaja bylá jesí. Tý bo jedína Máti Bóžija javílasja jesí, vo objátijich jáko mladénca sehó nosívši."), ("","","Nosjášči dobrótu úmnuju, krasňíjšija tvojejá duší, nevísta Bóžija bylá jesí, zapečátstvovana ďívstvom čístaja, i svítom čistotý mír prosviščájušči."), ("","","Da rydájet sobránije zločestívych, ne propovídajuščich ťá jávi čístuju Bohomáter: tý bo vratá Bóžija svíta javílasja jesí nám, mrák prehrišénij razhoňájušči."), ), ), "P6": ( "1": ( ("","","Žitéjskoje móre vozdvizájemoje zrjá napástej búreju, k tíchomu pristánišču tvojemú priték vopijú ti: vozvedí ot tlí živót mój, mnohomílostive."), ("","","Raspinájem Vladýko, hvozďmí úbo kľátvu júže na nás potrebíl jesí: kopijém že probodájem v rebró, Adámovo rukopisánije rasterzáv, mír svobodíl jesí."), ("","","Adám nizvedésja, léstiju zapját býv, ko ádovi própasti: no íže jestestvóm, Bóh že i mílostiv, sšél jesí na vzyskánije, i na rámu ponés, sovoskresíl jesí."), ("Bohoródičen","","Prečístaja Vladýčice, róždšaja čelovíkom kórmčiju Hóspoda, strastéj mojích nepostojánnoje i ľútoje utolí smuščénije, i tišinú podážď sérdcu mojemú."), ), "2": ( ("","","Ját býsť, no neuderžán v pérsich kítovych Jóna: tvój bo óbraz nosjá, stradávšaho i pohrebéniju dávšahosja, jáko ot čertóha ot zvírja izýde: prihlašáše že kustodíji: chraňáščiji sújetnaja i lóžnaja, mílosť sijú ostávili jesté."), ("","","Christoubíjca i prorokoubíjca býsť jevréjskoje mnóžestvo: jáko bo proróki drévle ístiny súščyja tájnyja lučý, ubíti ne ubojásja: síce i nýňi Hóspoda, jehóže propovídachu oní tohdá, závistiju vlekómi ubíša. No nám býsť živót umerščvlénije jehó."), ("","","Ját býl jesí, no ne uderžán Spáse vo hróbi, ášče bo i vóleju vkusíl jesí smérti Slóve, no voskrésl jesí jáko Bóh bezsmérten, sovozdvíhnuvyj úzniki súščyja vo áďi, i rádosť ženám vmísto pečáli préžnija, páki preminívyj."), ("Bohoródičen","","Bezčésten tvój i skúden javísja víd plotskíj páče čelovíkov, vo vrémja strásti: íbo božestvá suščestvóm, krasén dobrótoju Davídu pokazásja: no žezlóm tvojehó cárstvija vrahóv sotrýj kríposť, hlahólaše čístaja: o Sýne mój i Bóže, ot hróba vostáni."), ), "3": ( ("","","Žitéjskoje móre vozdvizájemoje zrjá napástej búreju, k tíchomu pristánišču tvojemú priték vopijú ti: vozvedí ot tlí živót mój, mnohomílostive."), ("","","Velíkij prednapisá vo prorócich Moiséj ťá, kovčéh, i trapézu, i svíščnik, i rúčku, obrázno naznámenuja voploščénije, jéže iz tebé výšňaho, Máti Ďívo."), ("","","Umerščvľájetsja smérť, i tľínije upražňájetsja Adámova osuždénija, o Vladýčice! Plodú tvojemú prirazívšejesja: žízň bo rodilá jesí, ot istľínija izbavľájuščuju pojúščich ťá."), ("","","Zakón iznemóže, i síň mímo íde, páče umá i smýsla jávľšejsja mí blahodáti, jéže ot tebé Ďívo roždestvá, Bóha i Spása, mnohopítaja."), ), ), "K": ( ("","","Živonačáľnoju dlániju, uméršyja ot mráčnych udólij, žiznodávec voskresív vsích Christós Bóh, voskresénije podadé čelovíčeskomu ródu: jésť bo vsích Spasíteľ, voskresénije i živót, i Bóh vsích."), ("","","Krest i pohrebénije tvojé žiznodávče, vospivájem vírniji, i poklaňájemsja, jáko ád svjazál jesí bezsmértne, jáko Bóh vsesíľnyj: i mértvyja sovoskresíl jesí, i vratá smértnaja sokrušíl jesí, i deržávu ádovu nizložíl jesí, jáko Bóh. Ťímže zemnoródniji slavoslóvim ťá ľubóviju, voskrésšaho, i nizložívšaho vrážiju deržávu vsepáhubnuju, i vsích voskresívšaho v ťá vírovavšich, i mír izbávľšaho ot stríl zmijínych, i ot prélesti vrážija, jáko Bóh vsích."), ), "P7": ( "1": ( ("","","Rosodáteľnu úbo péšč soďíla ánhel prepodóbnym otrokóm, chaldéji že opaľájuščeje veľínije Bóžije, mučíteľa uviščá vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Rydájuščeje vo strásti tvojéj sólnce, vo mrák oblečésja, i vo dní po vséj Vladýko, zemlí svít pomérče, vopijá: blahoslovén jesí Bóže otéc nášich."), ("","","Oblekóšasja Christé schoždénijem tvojím vo svít preispódňaja, práotec že vesélija ispólň javísja likovstvúja, vzyhrásja vopijá: blahoslovén jesí Bóže otéc nášich."), ("Bohoródičen","","Tobóju Máti Ďívo, svít vozsijá vséj vselénňij svítlyj: ziždíteľa bo tý vsích rodilá jesí Bóha. Jehóže prosí vsečístaja, nám nizposláti vírnym véliju mílosť."), ), "2": ( ("","","Neizrečénoje čúdo, v peščí izbávivyj prepodóbnyja ótroki iz plámene, vo hróbi mértv bezdychánen polahájetsja, vo spasénije nás pojúščich: Izbáviteľu Bóže blahoslovén jesí."), ("","","O stránnaho óbraza! Izráiľa izbavléj ot rabóty faraónskija, raspinájetsja vóleju ot nehó, i razrišájet veríhi sohrišénij. Jemúže víroju pojém: izbáviteľu Bóže, blahoslovén jesí."), ("","","Tebé Spása na lóbňim raspjáša prebezzakónnych ótrocy nečestíviji, vratá mídnaja i verejí slomívšaho, vo spasénije nás pojúščich: izbáviteľu Bóže, blahoslovén jesí."), ("Bohoródičen","","Jévy drévnija svoboždénije róždšaja ot kľátvy, razrišáješi Adáma Ďívo čístaja. Ťímže so ánhely ťá, s Sýnom tvojím pojém i vopijém: izbáviteľu Bóže, blahoslovén jesí."), ), "3": ( ("","","Rosodáteľnu úbo péšč soďíla ánhel prepodóbnym otrokóm, chaldéji že opaľájuščeje veľínije Bóžije, mučíteľa uviščá vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Júnoš trijéch péšč ne opalí, roždestvó proobrazújuščich tvojé: božéstvennyj bo óhň tebé ne opalív, vselísja v ťá, i vsjá naučí vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Blážát koncý ťa vsečístaja Máti, jákože proreklá jesí, prosviščájemi svitolúčnymi sijáňmi tvojími, i blahodátiju pojúšče, vopijút: blahoslovén jesí Bóže otéc nášich."), ("","","Páhubnyja úbo zúby v mjá vonzé zmíj lukávňijšij: no sám tvój Bohomáti, sokruší Sýn, kríposť že mňí dadé vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Očistílišče jestestvá tý jesí jedína Bohoblažénnaja, na rámu bo cheruvímsku siďáščaho Bóha bo objátijich nosjášči vopijéši: blahoslovén jesí Bóže otéc nášich."), ), ), "P8": ( "1": ( ("","","Iz plámene prepodóbnym rósu istočíl jesí, i právednaho žértvu vodóju popalíl jesí: vsjá bo tvoríši Christé, tókmo jéže choťíti, ťá prevoznósim vo vsjá víki."), ("","","Judéjskija drévle prorokoubíjcy ľúdi, Bohoubíjcy závisť nýňi soďíla, tebé na krest voznésšyja, Slóve Bóžij: jehóže prevoznósim vo vsjá víki."), ("","","Nebésnaho krúha ne ostávil jesí, i vo ád sošéd, vsehó sovozdvíhl jesí ležáščaho vo hnójišči Christé čelovíka, ťá prevoznosjášča vo vsjá víki."), ("Bohoródičen","","Ot svíta svitodávca Slóva začalá jesí, i róždši neizrečénno sehó, proslávilasja jesí: Dúch bo v ťá otrokovíce Bóžij vselísja. Ťímže ťá pojém vo vsjá víki."), ), "2": ( ("","","Užasnísja bojájsja Nébo, i da podvížatsja osnovánija zemlí: sé bo v mertvecích vmiňájetsja vo výšnich živýj, i vo hrób mál strannoprijémletsja: jehóže ótrocy blahoslovíte , svjaščénnicy vospójte, ľúdije prevoznosíte vo vsjá víki."), ("","","Užasésja vsják slúch, káko výšnij vóleju priíde na zémľu, ádovu kríposť razrušíti krestóm i pohrebénijem, i vsjá vozdvíhnuti zváti: ótrocy blahoslovíte, svjaščénnicy vospójte, ľúdije prevoznosíte vo vsjá víki."), ("","","Prestá ádovo mučíteľstvo, i cárstvo uničižísja próčeje, na kresťí bo na zemlí vodrúzivsja, íže nad vsími Bóh, sehó mohútstvo nizloží. Jehóže ótrocy blahoslovíte, svjaščénnicy vospójte, ľúdije prevoznosíte vo vsjá víki."), ("","","O neizrečénnaho tvojehó Christé čelovikoľúbija, i neizhlahólannych bláh! Mené bo víďa pohibájušča vo ádovi temníci, strásti preterpívyj izbávil jesí. Ťímže ťá blahoslovím vsích Vladýku, i prevoznósim vo vsjá víki."), ), "3": ( ("","","Iz plámene prepodóbnym rósu istočíl jesí, i právednaho žértvu vodóju popalíl jesí: vsjá bo tvoríši Christé, tókmo jéže choťíti, ťá prevoznósim vo vsjá víki."), ("","","Pozlaščénoju rízoju jákože carícu Sýn tvój prosvitív zaréju Dúcha, tebé odesnúju sebé postávi prečístaja: jehóže prevoznósim vo vsjá víki."), ("","","Íže choťínijem jedínym mír vodruzívyj, ot prečístyja tvojejá utróby plóť vzémlet, svýše sijú nazdáti choťá: jehóže prevoznósim vo vsjá víki."), ("","","Sčetánijem slóva ko mňí čelovíku, božéstvennoje žilíšče bylá jesí prečístaja, prosijávši jávi ďívstva svítlostiju: ťímže ťá pojém vo vsjá víki."), ("","","Zlatozárnyj ťá svíščnik predvoobrazí, prijémšuju neskazánno svít nepristúpnyj, rázumom svoím ozarjájušč vsjáčeskaja. Ťímže ťá pojém čístaja, vo víki."), ), ), "P9": ( "1": ( ("","","Bóha čelovíkom ne vozmóžno víďiti, na nehóže ne smíjut číni ánheľstiji vziráti: tobóju že vsečístaja, javísja čelovíkom slóvo voploščénno, jehóže veličájušče, s nebésnymi vóji ťá ublážájem."), ("","","Strastéj nepričásten tý prebýl jesí Slóve Bóžij, plótiju priobščívsja strástém: no rišíši ot strastéj čelovíka, strastém býv strásť Spáse náš: jedín bo jesí bezstrásten, i vsesílen."), ("","","Tľú smértnuju prijém, tľínija sobľúl jesí ťílo tvojé nevkúsno, tvojá že životvorjáščaja i božéstvennaja Vladýko dušá, vo áďi ne ostávlena býsť: no jákože ot sná voskrés, nás sovozdvíhl jesí."), ("Tróičen","","Bóha Otcá, Sýna sobeznačáľna, vsí čelovícy ustnámi úbo čístymi slávim, neizrečénnuju že i preslávnuju Dúcha vsesvjatáho sílu čtím: jedína bo jesí vsesíľnaja Tróica nerazlúčnaja."), ), "2": ( ("","","Ne rydáj mené Máti, zrjášči vo hróbi, jehóže vo črévi bez símene začalá jesí Sýna: vostánu bo i proslávľusja, i voznesú so slávoju neprestánno jáko Bóh, víroju i ľubóviju ťá veličájuščyja."), ("","","Ášče i vo hrób sošél jesí jáko mértv žiznodávče, no ádovu kríposť razrušíl jesí Christé, sovozdvíhnuv mértvyja, jáže i pohlotí, i voskresénije vsím pódal jesí, jáko Bóh, víroju i ľubóviju ťá veličájuščym."), ("","","Da rádujetsja tvár, i da procvitét jáko krín: Christós bo ot mértvych vostá jáko Bóh. Hďí tvojé, smérte, nýňi žálo, vozzovém? Hďí tvojá áde, pobída? Nizloží ťa v zémľu, vozvýsivyj róh náš, jáko blahoutróben."), ("Krestobohoródičen","","Nósiši nosjáščaho vsjá, i deržíši jáko mladénca v rukách, iz rukí izbavľájuščaho nás boríteľa vrahá, prečístaja Vladýčice, i vídiši na krest dréva vozvyšájema, ot róva zlóby nás vozvýsivša."), ), "3": ( ("","","Bóha čelovíkom ne vozmóžno víďiti, na nehóže ne smíjut číni ánheľstiji vziráti: tobóju že vsečístaja, javísja čelovíkom slóvo voploščénno, jehóže veličájušče, s nebésnymi vóji ťá ublážájem."), ("","","Zvizdá sijájušči zarjámi Božestvá ot Jákova, ot mráka soderžímym vozsijá: tobóju bo vsečístaja, Christós Bóh Slóvo voploščénno: ímže prosviščájemi, s nebésnymi vói ťá ublažájem."), ("","","Ukrípľsja síloju tvojéju i blahodátiju , tebí písň usérdno ot sérdca vozložích: no sijú prijimí Ďívo čístaja, blahodáť vozdajúšči tvojú mnohosvítluju, ot netľínnych sokróvišč, Bohoblažénnaja."), ("","","Postáv pokazálasja jesí jávi Božestvá, v némže rízu ťilesé Slóvo istká, Bohosoďílav mój Ďívo zrák: v nehóže obléksja vsích spasé, ot smýsla čísta tebé veličájuščich."), ("","","Mértvym voskresénije nýňi darovásja, tvojím neskazánnym i neizrečénnym roždestvóm, Bohoródice vsečístaja: žízň bo iz tebé plótiju oblékšisja, vsím vozsijá, i smértnuju drjáchlosť jávi razruší."), ), ), ), "CH": ( ("","","Krest tvój Hóspodi, žízň i voskresénije ľúdem tvojím jésť, i naďíjuščesja náň, tebé voskrésšaho Bóha nášeho pojém: pomíluj nás."), ("","","Pohrebénije tvojé Vladýko, ráj otvérze ródu čelovíčeskomu: i ot istľínija izbávľšesja, tebé voskrésšaho Bóha nášeho pojém: pomíluj nás."), ("","","So Otcém i Dúchom Christá vospoím, voskrésšaho iz mértvych, i k nemú vopiím: tý živót jesí náš, i voskresénije, pomíluj nás."), ("","","Tridnéven voskrésl jesí Christé ot hróba jákože písano jésť, sovozdvíhnuvyj práotca nášeho. Ťímže ťá i slávit ród čelovíčeskij, i vospivájet tvojé voskresénije."), ("","","Hóspodi, vélije i strášno jésť tvojehó voskresénija tájinstvo: táko bo proizšél jesí ot hróba, jáko ženích ot čertóha, smértiju smérť razrušívyj, da Adáma svobodíši. Ťímže na nebesích ánheli likovstvújut, i na zemlí čelovícy slávjat, jéže na nás bývšeje blahoutróbije tvojé, čelovikoľúbče."), ("","","O prebezzakónniji judéje, hďí súť pečáti i srébrenicy, jáže dáste vóinom? Ne ukrádeno býsť sokróvišče, no voskrése jáko sílen: sámi že posramístesja otvérhšijisja Christá Hóspoda slávy, postradávša i pohrebénna, i voskrésša iz mértvych: tomú poklonímsja."), ("","","Zapečátanu hróbu, káko okrádeni býste judée, strážy postávľše, i známenija polóžše, dvérem zakľučénnym prójde cár. Ilí jáko mértva predstávite, ilí jáko Bóhu poklonítesja, s námi pojúšče: sláva Hóspodi krestú tvojemú, i voskreséniju tvojemú."), ("","","Živoprijátnaho tvojehó hróba, mironósicy žený rydájuščja, dostihóša Hóspodi, i mv́ra nosjáščja, ťílo tvojé prečístoje pomázati iskáchu: obritóša že svitonósna ánhela na kámeni siďášča, i k ním viščájušča, i hlahóľušča: čtó slezité, iz rébr istočívšaho žízň mírovi? Čtó íščete jáko mértva vo hróbi bezsmértnaho? Tékša že páče vozvistíte tohó učenikóm, slávnaho jehó voskresénija vsemírnoje rádovanije, ímže i nás Spáse prosvitívyj, dáruj očiščénije i véliju mílosť."), ), ) #let L = ( "B": ( ("","","Pomjaní mja Bóže Spáse mój, jehdá priídeši vo cárstviji tvojém, i spasí mja jáko jedín čelovikoľúbec."), ("","","Drévom Adáma preľstívšahosja, drévom krestnym páki spásl jesí i razbójnika, vopijúšča: pomjaní mja Hóspodi vo cárstviji tvojém."), ("","","Ádova vratá i verejí sokrušívyj žiznodávče, voskresíl jesí vsjá Spáse vopijúščija: sláva vostániju tvojemú."), ("","","Pomjaní mja, íže smérť pľinívyj pohrebénijem tvojím, i voskresénijem tvojím rádosti vsjá ispólnivyj, jáko blahoutróben."), ("","","Mironósicy ko hróbu prišédša, ánhela zovúšča slýšachu: Christós voskrése, prosvitívyj vsjáčeskaja."), ("","","Na drévi krestňim prihvozdívšahosja, i mír ot prélesti izbávľšaho, sohlásno vsí Christá vospoím."), ("Tróičen","","Otcá, i Sýna slavoslóvim, i Dúcha svjatáho, hlahóľušče: Tróice svjatája, spasí dúšy náša."), ("Bohoródičen","","Neizrečénno v posľídňaja začénši, i róždši sozdáteľa tvojehó, Ďívo, spásáj ťá veličájuščyja."), ), "TKB": ( ("","","Ánheľskija síly na hróbi tvojém, i strehúščiji omertvíša: i stojáše Maríja vo hróbi, íščušči prečístaho ťíla tvojehó. Pľiníl jesí ád, ne iskusívsja ot nehó: srítil jesí Ďívu dárujaj živót. Voskrésýj iz mértvych, Hóspodi sláva tebí."), ("","","Živonačáľnoju dlániju, uméršyja ot mráčnych udólij, žiznodávec voskresív vsích Christós Bóh, voskresénije podadé čelovíčeskomu ródu: jésť bo vsích Spasíteľ, voskresénije i živót, i Bóh vsích."), ("Bohoródičen","","Bláhoslovénnuju narekíj tvojú Máter, prišél jesí na strásť vóľnym choťínijem, vozsijáv na kresťí, vzyskáti choťá Adáma, hlahóľa ánhelom: srádujtesja mňí, jáko obrítesja pohíbšaja dráchma, vsjá múdre ustróivyj Bóže náš, sláva tebí."), ), "P": ( ("","","Spasí Hóspodi, ľúdi tvojá, i blahosloví dostojánije tvojé."), ("","","K tebí Hóspodi vozzovú, Bóže mój, da ne premolčíši ot mené."), ("","","Živýj v pómošči výšňaho, v króvi Bóha nebésnaho vodvorítsja."), ("","","Rečét Hóspodevi: zastúpnik mój jesí, i pribížišče mojé, Bóh mój, i upováju na nehó."), ), )
https://github.com/FlorenceGhestem/My-Resume
https://raw.githubusercontent.com/FlorenceGhestem/My-Resume/main/assets/typst/typst-show.typ
typst
MIT License
#show: doc => resume( $if(name)$ name: [$name$], $endif$ $if(contact)$ contact: ( $for(contact)$ ( text: [$it.text$], link: [$it.link$] ), $endfor$ ), $endif$ $if(summary)$ summary: [$summary$], $endif$ $if(skills)$ skills: ( $for(skills)$ ( name: [$it.name$], items: ( $for(it.items)$ [$it$], $endfor$ ) ), $endfor$ ), $endif$ $if(main_sections)$ main_sections: ( $for(main_sections)$ ( title: [$it.title$], entries: ( $for(it.entries)$ ( title: [$it.title$], date: [$it.date$], organization: [$it.organization$], location: [$it.location$], description: ( $for(it.description)$ [$it$], $endfor$ ), ), $endfor$ ) ), $endfor$ ), $endif$ $if(lang)$ lang: "$lang$", $endif$ $if(region)$ region: "$region$", $endif$ $if(margin)$ margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$), $endif$ $if(papersize)$ paper: "$papersize$", $endif$ $if(mainfont)$ font: ("$mainfont$",), $endif$ $if(fontsize)$ fontsize: $fontsize$, $endif$ doc, )
https://github.com/alberto-lazari/computer-science
https://raw.githubusercontent.com/alberto-lazari/computer-science/main/lcd/project-presentation/sections/implementation.typ
typst
#import "/common.typ": * #new-section-slide[Implementation] #slide(title: [Abstract syntax tree])[ #set align(center) #grid( columns: (1fr, 2fr), [Store syntax elements], ```ocaml type act = | Tau | Input of string * string | Output of string * expr type proc = | Nil | Act of act * proc | Const of string * expr list | If of boolean * proc | Sum of proc * proc | Paral of proc * proc | Red of proc * (string * string) list ``` ) ] #slide(title: [Parser])[ #set align(center) #grid( columns: (1fr, 2fr), grid(gutter: 1em)[ Tokens ][#sym.arrow.b][ AST nodes ], ```ocaml %token <string> ID %token TAU %token POINT %token IF THEN %token PIPE act: | TAU { Tau } | a = ID LPAREN x = ID RPAREN { Input (a, x) } proc: | a = act POINT p = proc { Act (a, p) } | IF b = boolean THEN p = proc { If (b, p) } | p1 = proc PIPE p2 = proc { Paral (p1, p2) } ``` ) ] #slide(title: [Lexer])[ #set align(center) #grid( columns: (1fr, 2fr), grid(gutter: 1em)[ Characters sequences ][#sym.arrow.b][ Parser tokens ], ```ocaml let blank = [' ' '\t' '\n']+ let letter = ['a'-'z' 'A'-'Z'] let tau = "τ" | "tau" rule read = parse | blank+ { read lexbuf } | '=' { EQ } | tau { TAU } | '.' { POINT } | "if" { IF } | "then" { THEN } | '|' { PIPE } | id { ID (Lexing.lexeme lexbuf) } ``` ) ]
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/default/components.typ
typst
The Unlicense
#import "/utils.typ" /// Prints the table of contents. /// /// *Example Usage* /// /// ```typ /// #create-frontmatter-entry(title: "Table Of Contents")[ /// #components.toc() /// ] /// ``` /// -> content #let toc = utils.make-toc((_, body, appendix) => { heading[Contents] stack( spacing: 0.5em, ..for entry in body { ( [ #entry.title #box( width: 1fr, line( length: 100%, stroke: (dash: "dotted"), ), ) #entry.page-number ], ) }, ) heading[Appendix] stack( spacing: 0.5em, ..for entry in appendix { ( [ #entry.title #box( width: 1fr, line( length: 100%, stroke: ( dash: "dotted", ), ), ) #entry.page-number ], ) }) }) /// Prints out the glossary. /// /// *Example Usage* /// /// ```typ /// #glossary.add-term("Foo", lorem(10)) /// #glossary.add-term("Bar", lorem(5)) /// #components.glossary() /// ``` /// -> content #let glossary = utils.make-glossary(glossary => { stack( spacing: 0.5em, ..for entry in glossary { ( [ = #entry.word #entry.definition ], ) }, ) }) /// Prints a decision matrix table. /// /// *Example Usage* /// /// #example( /// `components.decision-matrix( /// properties: ( /// "Cat. 1", // weights will default to 1 /// "Cat. 2", /// "Cat. 3", /// ), /// ("Choice 1", 4, 3, 2), /// ("Choice 2", 1, 2, 3), /// )`, /// scale-preview: 100% /// ) /// /// #example( /// `components.decision-matrix( /// properties: ( /// (name: "Flavor", weight: 2), /// (name: "Crunch", weight: 1), /// ), /// ("Sweet Potato", 1, 2), /// ("Baked Potato", 2, 1) /// ) /// `, /// scale-preview: 100% /// ) /// - properties (array): A list of the properties that each choice will be rated by and the weight of each property /// - ..choices (array): An array containing the name of the choices as its first member, /// and values for each of the properties at its following indices /// /// -> content #let decision-matrix = utils.make-decision-matrix((properties, data) => { table( columns: for _ in range(properties.len() + 2) { (1fr,) }, [], ..for property in properties { ([ *#property.name* ],) }, [*Total*], ..for (index, choice) in data { let cell = if choice.total.highest { table.cell.with(fill: green) } else { table.cell } ( cell[*#index*], ..for value in choice.values() { (cell[#value.weighted],) }, ) }, ) }) /// Prints a pros and cons table. /// /// *Example Usage* /// /// #example(`components.pro-con(pros: lorem(10), cons: lorem(5))`, scale-preview: 100%) /// /// #example( /// `components.pro-con( /// pros: [ /// #list( /// "Sweet potato", /// "Baked potato" /// ) /// ], /// cons: [ /// #list( /// "Fries", /// "Wedges" /// ) /// ] /// ) /// `, scale-preview: 100%) /// - pros (content): The positive aspects /// - cons (content): The negative aspects /// -> content #let pro-con = utils.make-pro-con((pros, cons) => { table( columns: ( 1fr, 1fr, ), table.cell(fill: green)[*Pros*], table.cell(fill: red)[*Cons*], pros, cons, ) })
https://github.com/swaits/typst-collection
https://raw.githubusercontent.com/swaits/typst-collection/main/finely-crafted-cv/0.1.0/src/helpers.typ
typst
MIT License
#import "constants.typ":* #let icon_and_contact(icon, content) = { grid( columns: 2, align: center+horizon, gutter: COMPANY_ICON_SPACING, box( height: HEADER_ICON_HEIGHT, width: auto, image(icon) ), content ) } #let hrule(stroke: 1pt + black) = { block( above: HRULE_HEIGHT, below: 0em, breakable: false, line(length: 100%, stroke: stroke) ) }
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis
https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/docs/1.2%20median.typ
typst
// == #text(orange)[1.2 Bài toán 1-median] // == Bài toán 1-median #include "../tools/multi-section-ref.typ" #import "../tools/macros.typ": eqref #include "../tools/multi-section-ref.typ" #import "../tools/macros.typ": eqref #import "../typst-orange.typ": theorem, proof, lemma, proposition, corollary, example #import "@preview/cetz:0.1.2": canvas, plot #import "@preview/cetz:0.1.2" #include "../tools/multi-section-ref.typ" #import "../tools/macros.typ": eqref #import "../typst-orange.typ": theorem, proof, lemma, proposition, corollary, example #include "../tools/multi-section-ref.typ" #import "../tools/macros.typ": eqref #import "../typst-orange.typ": theorem, proof == BÀI TOÁN 1-MEDIAN Trong phần này, ta sẽ xem xét bài toán 1-median. Bài toán này là một bài toán tối ưu trong lý thuyết vị trí, với ứng dụng thực tiễn rộng rãi trong nhiều ngành khác nhau. Trong quy hoạch đô thị, bài toán này được sử dụng để chọn vị trí đặt các dịch vụ công cộng như bệnh viện, trường học, hoặc trạm xăng sao cho tổng khoảng cách di chuyển của người dân đến các địa điểm này là nhỏ nhất. Tương tự, trong quản lý chất thải, bài toán 1-median giúp tìm vị trí đặt nhà máy xử lý hoặc bãi rác nhằm tối ưu hóa chi phí vận chuyển rác từ các khu vực dân cư đến nơi xử lý, giảm thiểu chi phí và thời gian vận chuyển. // == #text(orange)[1.2.1 Bài toán 1-median trên đồ thị tổng quát] === Bài toán 1-median trên đồ thị tổng quát Cho đồ thị $G = (V, E)$, với mỗi cạnh và mỗi đỉnh được gán một trọng số tương ứng, gọi là trọng số cạnh và trọng số đỉnh. Ta đặt $w_i$ là trọng số của đỉnh $v_i$ và giả sử tất cả các đỉnh đều có trọng số dương. Mục tiêu của bài toán này là tìm vị trí của một điểm (gọi là 1-median) sao cho tổng khoảng cách từ điểm đó đến các điểm khác trên đồ thị là nhỏ nhất. Hay nói cách khác, ta cần phải tìm một điểm $x in G$ sao cho $ f(x)=sum_(v_i in V) w_i d(v_i,x) $ <eq:5> nhỏ nhất //Cần trích dẫn hay không? Thuật toán tìm điểm 1-median trên đồ thị tổng quát được trình bày bởi Nickel. Thuật toán gồm các bước sau: 1. Xác định khoảng cách gần nhất giữa các cặp đỉnh trong $G$. Ký hiệu là $d(v_i,v_j)$ 2. Tính giá trị của $f(v_i), forall v_i in V$ 3. Tìm $ o p t = min{f(v_i) bar.v v_i in V}$ 4. Trả về $(x^*)={v_i bar.v f(v_i)= o p t}$ là các điểm 1-median của $G$. Để hiểu rõ hơn về cách hoạt động của thuật toán, ta sẽ xem xét ví dụ dưới đây. Với trọng số đỉnh đã được cho trong hình vẽ, nhiệm vụ tiếp theo là tính toán khoảng cách giữa các cặp đỉnh trong đồ thị $G$. $ d(u,v)=4, d(z,v)=6, d(t,v)=10, d(z,u)=3, d(t,u)=6, d(t,z) = 3 $ Tiếp theo, ta sẽ tính giá trị hàm mục tiêu như ở #eqref(<eq:5>) $ f(v)= 2.4 + 6.4 + 10.1 = 42 $ $ f(u)= 3.4 + 4.3 + 1.6 = 30 $ $ f(z)= 3.6 + 2.3 + 1.3 = 27 $ $ f(t)= 3.10 + 6.2 + 3.4 = 54 $ #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "u") content("u.left", $u (2)$, anchor: "left", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v") content("v.right", $v (3)$, anchor: "right", padding: 0.2) circle((0, 0), radius: 0.05, fill: black, name: "z") content("z.top", $z (4)$, anchor: "top", padding: 0.2) circle((-3, 0), radius: 0.05, fill: black, name: "t") content("t.right", $t (1)$, anchor: "right", padding: 0.2) line("u", "v", name: "v1v2") content("v1v2.bottom", $4$, anchor: "bottom", padding: 0.1) // bezier("u","v", (-1.5,2), name: "be1") // content("be1.top", $e_4$, anchor: "top", padding: 0.2) line("u", "z", name: "v1v3") content("v1v3.right", $3$, anchor: "right", padding: 0.1) line("v", "z", name: "v2v3") content("v2v3.right", $6$, anchor: "right", padding: 1) line("t", "z", name: "tz") content("tz.top", $3$, anchor: "top", padding: 0.1) line("t", "u", name: "tu") content("tu.left", $5$, anchor: "left", padding: 1) // bezier("z","v", (-4,-3), name: "be2") // content("be2.right", $e_5$, anchor: "right", padding: 2.7) } )] Vì $f(z) < f(u) < f(v) < f(t)$, nên $z$ là điểm 1-median cần tìm. Tiếp theo, ta sẽ nghiên cứu bài toán 1-median trên một loại đồ thị đơn giản hơn, đó là đồ thị cây. Trên cấu trúc đồ thị này, //@goldmanOptimalCenterLocation1971 đã phát triển một thuật toán tuyến tính hiệu quả để xác định điểm 1-median, mang lại lời giải tối ưu cho bài toán. // == #text(orange)[1.2.1 Bài toán 1-median trên cây] === Bài toán 1-median đồ thị cây Cho đồ thị cây $T(V,E)$.//Để thuận tiện cho việc chứng minh, ta ký hiệu $angle.l w, bb(1)_T_u angle.r = sum_(v_i in T_u) w_i $. Đặt $u_i in N(x_0)$ là tập hợp những đỉnh liền kề với $x_0$. Khi đó $T_u$ là cây con của $T$ được lấy gốc tại đỉnh $u$. #theorem[ Một điểm $x_0$ là điểm 1-median của cây $T$ khi và chỉ khi $ w(T_u_i) <= w(T)/2 quad quad forall u_i in N(x_0) $] //$angle.l w, bb(1)_T_u angle.r <= 1/2$ $forall u in N(x_0)$. #proof[ Định lý này gồm hai chiều, ta bắt đầu với chiều đầu tiên. Giả sử $x_0$ là điểm 1-median. Ta cần chứng minh $w(T_u_i) <= w(T)/2 quad quad forall u in N(x_0)$. Trước tiên, ta đặt $ deg(x_0) = k$. Khi đó, nếu xóa bỏ $x_0$, ta được $k$ cây con với gốc lần lượt là $T_u_1, T_u_2,...,T_u_k$, trong đó $u_i in N(x_0), i=1,...,k$. Ta lại có $x_0$ là một điểm 1-median, nghĩa là giá trị $f(x_0)$ nhỏ nhất. Nói cách khác: $ f(u_i) - f(x_0) >= 0 forall u_i in N(x_0) $ Khi đó, $ f(u_1) - f(x_0) >= 0 $ <eq:13> Hơn nữa, $ f(x_0)= sum_(v_i in V(T_u_1)) w_i d(v_i, x_0) + sum_(v_i in.not V(T_u_1)) w_i d(v_i, x_0) $ $f(u_1)= sum_(v_i in V(T_u_1)) w_i d(v_i,u_1) + sum_(v_i in.not V(T_u_1)) w_i d(v_i,u_1) = sum_(v_i in V(T_u_1)) w_i [d(v_i,x_0)- d(u_1,x_0)] + sum_(v_i in.not V(T_u_1)) w_i [d(v_i,x_0)+ d(u_1,x_0)] = f(x_0) + [sum_(v_i in.not V(T_u_1)) w_i - sum_(v_i in V(T_u_1)) w_i] d(u_1,x_0) = f(x_0) + [sum_(v_i in V(T)) w_i -2 sum_(v_i in V(T_u_1)) w_i]d(u_1,x_0) $ Thế vào #eqref(<eq:13>), ta được: $ w(T_u_1) <= w(T)/2 $ Chứng minh tương tự với các trường hợp còn lại. Từ đó ta được $ w(T_u_i) <= w(T)/2 quad quad forall u_i in N(x_0). $ #align(center)[#canvas(length: 8%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "x0") content("x0.left", $x_0$, anchor: "left", padding: 0.2) circle((-2, 5), radius: 0.05, fill: black, name: "u1") content("u1.left", $u_1$, anchor: "left", padding: 0.2) circle((-2, 7), radius: 0.05, fill: black, name: "1") // content("z.top", $z (4)$, anchor: "top", padding: 0.2) circle((-1, 9), radius: 0.05, fill: black, name: "2") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((-4, 8), radius: 0.05, fill: black, name: "3") // content("t1.right", $t (1)$, anchor: "right", padding: 0.2) circle((-5, 7), radius: 0.05, fill: black, name: "4") content("4.right", $T_u_1$, anchor: "right", padding: 1) circle((-4, 5), radius: 0.05, fill: black, name: "5") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((-5, 4), radius: 0.05, fill: black, name: "6") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((3, 5), radius: 0.05, fill: black, name: "u2") content("u2.top", $u_2$, anchor: "top", padding: 0.2) // circle((4, 7), radius: 0.05, fill: black, name: "7") // // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((5, 5), radius: 0.05, fill: black, name: "8") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((6, 7), radius: 0.05, fill: black, name: "10") content("10.right", $T_u_2$, anchor: "right", padding: 1) circle((6, 3), radius: 0.05, fill: black, name: "9") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((0, 1), radius: 0.05, fill: black, name: "u3") content("u3.right", $u_3$, anchor: "right", padding: 0.2) circle((1,-1), radius: 0.05, fill: black, name: "muoihai") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) circle((-1, -1), radius: 0.05, fill: black, name: "11") content("11.right", $T_u_3$, anchor: "right", padding: 1) // circle((0, -4), radius: 0.05, fill: black, name: "t") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) // circle((-4, -4), radius: 0.05, fill: black, name: "t") // content("t.right", $t (1)$, anchor: "right", padding: 0.2) line("u1", "1", name: "u11") // content("v1v2.bottom", $4$, anchor: "bottom", padding: 0.1) // // bezier("u","v", (-1.5,2), name: "be1") // // content("be1.top", $e_4$, anchor: "top", padding: 0.2) line("1", "2", name: "12") // content("v1v3.right", $3$, anchor: "right", padding: 0.1) line("1", "3", name: "13") // content("v2v3.right", $6$, anchor: "right", padding: 1) line("4", "5", name: "tz") // content("tz.top", $3$, anchor: "top", padding: 0.1) line("u1", "5", name: "") // content("tu.left", $5$, anchor: "left", padding: 1) line("6", "5", name: "") // line("u2", "7", name: "") line("u2", "8", name: "") line("8", "10", name: "") line("8", "9", name: "") line("u3", "11", name: "") line("u3", "muoihai", name: "") line("u1", "x0", stroke: (dash: "dashed")) line("u2", "x0", stroke: (dash: "dashed")) line("u3", "x0", stroke: (dash: "dashed")) // bezier("z","v", (-4,-3), name: "be2") // content("be2.right", $e_5$, anchor: "right", padding: 2.7) } )] *Hình... ĐỒ THỊ MINH HỌA* Vậy ta đã hoàn thành chứng minh chiều đầu tiên. Tiếp theo, ta giả sử rằng $ w(T_u_i) <= w(T)/2 quad quad forall u_i in N(x_0). $ Ta cần chứng minh $x_0$ là điểm 1-median. Nói cách khác, ta cần chỉ ra rằng $f(x_0)$ là giá trị nhỏ nhất. Ta có: $ w(T_u_i) <= w(T)/2 <=> f(u_i) - f(x_0) >= 0 quad quad forall u_i in N(x_0). $ Điều này nghĩa là $x_0$ là cực tiểu địa phương của hàm mục tiêu $f$ trên $T$. Theo *định lý 2.1*, hàm $f$ là hàm lồi nên $x_0$ là cực tiểu toàn cục. Nghĩa là $f(x_0)$ đạt giá trị nhỏ nhất trên hàm $f$ (điều cần phải chứng minh).] // (angle.l w, bb(1)_T_u_i angle.r) d(v',u_1)$ + $(angle.l w, bb(1)_(T without T_u_i) angle.r)d(v,u_i)$ = $(angle.l w, bb(1)_u_i angle.r)[d(w,x_0)-d(u_i,x_0)]$ + $(angle.l w, bb(1)_(T without T_u_i) angle.r)[d(v,x_0)+d(x_0,u_i)] = f(x_0) + (angle.l w, bb(1)_(T without T_u_i) angle.r - angle.l w, bb(1)_(T_u_i) angle.r) d(u_i,x_0)= 1- 2 angle.l w, bb(1)_T_u_i angle.r$. // $f(x_0)= (angle.l w, bb(1)_T_u_i) d(v,x_0) + (angle.l w, bb(1)_(T without T_u_i))d(v,x_0)$. // Thế vào (5), ta được $1- 2 angle.l w, bb(1)_T_u_i angle.r >= 0$ hay nói cách khác $angle.l w, bb(1)_T_u_i angle.r <= 1/2$ // (Vẽ hình minh họa) // Ngược lại, ta giả sử rằng $angle.l w, bb(1)_T_u_i angle.r <= 1/2$. Ta cần chứng minh $x_0$ là một điểm 1-median. // Nghĩa là, ta cần phải chỉ ra rằng giá trị $f(x_0)$ nhỏ nhất .$angle.l w, bb(1)_T_u_i angle.r <= 1/2 <=> f(u_i)-f(x_0) >= 0 <=> f(x_0) <= f(u_i)$, $forall u in N(x_0)$. Khi đó, $x_0$ là cực tiểu địa phương của hàm mục tiêu $f$ trên $T$. Gọi $v$ là điểm nằm trên đường đi nối giữa $x_0$ và $v'$, trong đó $v'$ là một đỉnh bất kỳ, sao cho $v$ vẫn thuộc vào lân cận $x_0$. Khi đó $v= alpha x_0 + (1-alpha)v'$ (viết lại, dựa vào phần chứng minh hàm khoảng cách là lồi ở mục chapter1). $forall alpha in [0;1]$. Ta có: $f(x_0) <= f(v)=f(alpha x_0 + (1-alpha)v')$ $<= alpha(x_0) + (1-alpha)f(v')$ $=> f(x_0) <= f(v')$. Vậy $f(x_0)$ đạt giá trị nhỏ nhất tại $x_0$, hay nói cách khác $x_0$ là điểm 1-median. Định lý bên trên đóng vai trò quan trọng trong việc xác định điểm 1-median, định lý này đã được biết đến rộng rãi và được nhiều nhà nghiên cứu sử dụng trong các bài toán tối ưu liên quan đến lý thuyết vị trí. Sau đây, ta sẽ giới thiệu một thuật toán hiệu quả để tìm kiếm điểm 1-median cây đồ thị cây. Thuật toán tuyến tính tìm 1-median trên cây được độc lập đưa ra bởi Goldman(1971).Ý tưởng cơ bản của thuật toán là "nuốt lá", tức là xóa từng lá và cộng trọng số của lá đó vào trọng số của đỉnh liền kề với nó. Quá trình tiếp diễn cho đến khi có một lá có trọng số lớn hơn phân nửa trọng số của cây $T$, lá này chính là điểm 1-median của cây $T$. #set table.hline(stroke: .7pt) #table( table.hline(), stroke: none, columns: (auto, 4fr), [*ĐẦU VÀO*], [Cây $T=(V,E)$, làm chiều dài $l$, hàm trọng số $w$], [*Bước 0*], [Tính $W= sum_(v_i in V) w_i.$], [*Bước 1*], [Chọn một lá $v_k$ của $T=(V,E).$], [*Bước 2*], [Nếu $V={v_k}$ thì trả về: $X^*={v_k}.$], [*Bước 3*], [], [$w_k$ = $W$/2], [Trả về: $X^*={x in v_k v_l}$, trong đó $v_l$ liền kề $v_k$.], [$w_k >$ $W$/2], [Trả về: $X^*={v_k}$], [$w_k <$ $W$/2], [Sang Bước 4.], [*Bước 4*], [Đặt $w_l := w_l + w_k$ với $v_l$ liền kề $v_k$ và xét cây mới $T:= T without {v_k}$. Trở về Bước 1.], table.hline(), [*ĐẦU RA*], [$X^*$ là tập hợp tất cả các điểm 1-median.], ) Để hiểu rõ hơn về cách hoạt động của thuật toán, chúng ta sẽ cùng phân tích qua ví dụ dưới đây. *Ví dụ* Tìm điểm 1-median của đồ thị được cho hình như bên dưới #align(center)[#canvas(length: 6%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v2") content("v2.left", $v_2 (1)$, anchor: "left", padding: 0.2) circle((-3,0), radius: 0.05,fill:black, name: "v1") content("v1.left", $v_1 (1)$, anchor: "left", padding: 0.2) circle((-3,6), radius: 0.05,fill:black, name: "v3") content("v3.left", $v_3 (3)$, anchor: "left", padding: 0.2) circle((-4,9), radius: 0.05,fill:black, name: "v4") content("v4.left", $v_4 (2)$, anchor: "left", padding: 0.2) circle((-6,5), radius: 0.05,fill:black, name: "v5") content("v5.left", $v_5 (3)$, anchor: "left", padding: 0.2) circle((3,3), radius: 0.05,fill:black, name: "v6") content("v6.left", $v_6 (4)$, anchor: "left", padding: 0.2) circle((5,4), radius: 0.05,fill:black, name: "v7") content("v7.left", $v_7 (1)$, anchor: "left", padding: 0.2) circle((6,7.5), radius: 0.05,fill:black, name: "v8") content("v8.left", $v_8 (3)$, anchor: "left", padding: 0.2) circle((5,1.5), radius: 0.05,fill:black, name: "v9") content("v9.left", $v_9 (2)$, anchor: "left", padding: 0.2) circle((6,-1), radius: 0.05,fill:black, name: "v10") content("v10.left", $v_10 (1)$, anchor: "left", padding: 0.2) circle((9,0), radius: 0.05,fill:black, name: "v11") content("v11.left", $v_11 (1)$, anchor: "left", padding: 0.2) line("v1", "v2") line("v2", "v3") line("v3", "v4") line("v3", "v5") line("v2", "v6") line("v6", "v7") line("v7", "v8") line("v6", "v9") line("v9", "v10") line("v10", "v11") } )] Ta có $W(T)=22$, các lá $s:= {v_1, v_4, v_5, v_8, v_11}$ Xét lá $v_1$, vì $w_1 = 1 < W/2 = 11$ nên $w_2:= w_2 + w_1 = 1+1= 2$ và xét cây mới $T:= T without {v_1}.$ Xét lá $v_4$, vì $w_4 = 2 < W/2 = 11$ nên $w_3 := w_3 + w_4 = 2+3=5$ và xét cây mới $T:= T without {v_4}.$ Xét lá $v_5$, vì $w_5 = 3 < W/2 = 11$ nên $w_3 := w_3 + w_5= 5+ 3 = 8$ và xét cây mới $T:= T without {v_5}.$ Xét lá $v_3$, vì $w_3 = 8 < W/2 = 11$ nên $w_2:= w_3 + w_2 = 8 + 2= 10$ và xét cây mới $T:= T without {v_3} $ Xét lá $v_2$, vì $w_2= 10 < W/2 =11 $ nên $w_6:= w_6 + w_2 = 4 + 10 = 14$ và xét cây mới $T:= T without {v_2}.$ Xét lá $v_6$, vì $w_6 = 14 > W/2 = 11$ nên trả về $X^* = { v_6}.$ Vậy $v_6$ là điểm 1-median cần tìm.
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/inline/text.typ
typst
// Test OpenType features. --- text-kerning --- // Test turning kerning off. #text(kerning: true)[Tq] \ #text(kerning: false)[Tq] --- text-alternates-and-stylistic-sets --- // Test alternates and stylistic sets. #set text(font: "IBM Plex Serif") a vs #text(alternates: true)[a] \ ß vs #text(stylistic-set: 5)[ß] \ 10 years ago vs #text(stylistic-set: (1, 2, 3))[10 years ago] --- text-ligatures --- // Test text turning off (standard) ligatures of the font. #text(ligatures: false)[fi Qu] vs fi Qu \ // Test text turning on historical ligatures of the font. abstract vs #text(historical-ligatures: true)[abstract] \ // Test text turning on discretionary ligatures of the font. waltz vs #text(discretionary-ligatures: true)[waltz] --- text-number-type --- // Test number type. #set text(number-type: "old-style") 0123456789 \ #text(number-type: auto)[0123456789] --- text-number-width --- // Test number width. #text(number-width: "proportional")[0123456789] \ #text(number-width: "tabular")[3456789123] \ #text(number-width: "tabular")[0123456789] --- text-slashed-zero-and-fractions --- // Test extra number stuff. #set text(font: "IBM Plex Serif") 0 vs. #text(slashed-zero: true)[0] \ 1/2 vs. #text(fractions: true)[1/2] --- text-features --- // Test raw features array or dictionary. #text(features: ("smcp",))[Smcp] \ fi vs. #text(features: (liga: 0))[No fi] --- text-stylistic-set-bad-type --- // Error: 26-31 expected none, integer, or array, found boolean #set text(stylistic-set: false) --- text-stylistic-set-out-of-bounds --- // Error: 26-28 stylistic set must be between 1 and 20 #set text(stylistic-set: 25) --- text-number-type-bad --- // Error: 24-25 expected "lining", "old-style", or auto, found integer #set text(number-type: 2) --- text-features-bad --- // Error: 21-26 expected array or dictionary, found boolean #set text(features: false) --- text-features-bad-nested-type --- // Error: 21-35 expected string, found boolean #set text(features: ("tag", false)) --- text-tracking-negative --- // Test tracking. #set text(tracking: -0.01em) I saw Zoe yӛsterday, on the tram. --- text-tracking-changed-temporarily --- // Test tracking for only part of paragraph. I'm in#text(tracking: 0.15em + 1.5pt)[ spaace]! --- text-tracking-mark-placement --- // Test that tracking doesn't disrupt mark placement. #set text(font: ("PT Sans", "Noto Serif Hebrew")) #set text(tracking: 0.3em) טֶקסט --- text-tracking-arabic --- // Test tracking in arabic text (makes no sense whatsoever) #set text(tracking: 0.3em) النص --- text-spacing --- // Test word spacing. #set text(spacing: 1em) My text has spaces. --- text-spacing-relative --- // Test word spacing relative to the font's space width. #set text(spacing: 50% + 1pt) This is tight.
https://github.com/TechnoElf/mqt-qcec-diff-presentation
https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-presentation/main/content/background.typ
typst
#import "@preview/fletcher:0.5.1": diagram, node, edge #import "@preview/quill:0.3.0": quantum-circuit, lstick, rstick, ctrl, targ, mqgate, meter #import "../template/conf.typ": slide #slide(title: "")[ #box(width: 100%, height: 80%, align(center + horizon)[ #text(size: 60pt)[*Background*] ]) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 70%, height: 90%, align(horizon, { grid( columns: (4fr, 2fr), align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), $H$, 1, 1, [\ ], lstick($|q_1〉$), 1, $X$, 1 )), align(horizon)[$U = 1/sqrt(2) mat( 0, 1, 0, 1; 1, 0, 1, 0; 0, 1, 0, -1; 1, 0, -1, 0 )$] ) grid( columns: (4fr, 2fr), align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), $"S"$, $sqrt(X)$, $"S"$, 1, [\ ], lstick($|q_1〉$), 1, 1, 1, $X$, 1 )), align(horizon)[$U' = 1/sqrt(2) mat( 0, 1, 0, 1; 1, 0, 1, 0; 0, 1, 0, -1; 1, 0, -1, 0 )$] ) })) ) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 70%, height: 90%, { align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), $H$, 1, 1, $"S"^dagger$, $sqrt(X)^dagger$, $"S"^dagger$, 1, [\ ], lstick($|q_1〉$), 1, $X$, $X^dagger$, 1, 1, 1 )) align(horizon)[$U dot U'^dagger = mat( 1, 0, 0, 0; 0, 1, 0, 0; 0, 0, 1, 0; 0, 0, 0, 1 ) = I$] }) ) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 70%, height: 90%, align(horizon, grid( columns: (4fr, 1fr, 4fr), align(horizon)[$U = 1/sqrt(2) mat( 0, 1, 0, 1; 1, 0, 1, 0; 0, 1, 0, -1; 1, 0, -1, 0 )$], align(horizon)[$<=>$], align( horizon, diagram( node-stroke: .1em, edge((0, -1), (0, 0), [$1/sqrt(2)$], "->"), node((0, 0), [$q_1$], radius: 1em), edge((0, 0), (0, 1), [], "->", bend: -50deg), edge((0, 0), (0, 1), [], "->", bend: -20deg), edge((0, 0), (0, 1), [], "->", bend: 20deg), edge((0, 0), (0, 1), [$-1$], "->", bend: 50deg), node((0, 1), [$q_0$], radius: 1em), edge((0, 1), (-0.5, 1.5), [], "->", bend: 10deg), edge((0, 1), (0, 2), [], "->", bend: -10deg), edge((0, 1), (0, 2), [], "->", bend: 10deg), edge((0, 1), (0.5, 1.5), [], "->", bend: -10deg), node((-0.5, 1.5), [$0$], stroke: 0pt), node((0.5, 1.5), [$0$], stroke: 0pt), node((0, 2), [$1$], shape: rect), ) ) ))) ) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 90%, height: 90%, align(horizon, grid( columns: (8fr, 2fr), align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), 1, 1, 1, [\ ], lstick($|q_1〉$), 1, 1, 1 )), align( horizon, diagram( node-stroke: .1em, edge((0, -1), (0, 0), [], "->"), node((0, 0), [$q_1$], radius: 1em), edge((0, 0), (0, 1), [], "->", bend: -50deg), edge((0, 0), (0, 0.5), [], "->", bend: -20deg), edge((0, 0), (0, 0.5), [], "->", bend: 20deg), edge((0, 0), (0, 1), [], "->", bend: 50deg), node((0, 0.5), [], stroke: 0pt, radius: 0.5em), node((0, 1), [$q_0$], radius: 1em), edge((0, 1), (0, 2), [], "->", bend: 50deg), edge((0, 1), (0, 1.5), [], "->", bend: -20deg), edge((0, 1), (0, 1.5), [], "->", bend: 20deg), edge((0, 1), (0, 2), [], "->", bend: -50deg), node((0, 1.5), [], stroke: 0pt, radius: 0.5em), node((0, 2), [$1$], shape: rect), ) ) ))) ) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 90%, height: 90%, align(horizon, grid( columns: (8fr, 2fr), align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), 1, 1, 1, 1, [\ ], lstick($|q_1〉$), 1, $X$, 1, 1 )), align( horizon, diagram( node-stroke: .1em, edge((0, -1), (0, 0), [], "->"), node((0, 0), [$q_1$], radius: 1em), edge((0, 0), (-0.5, 0.5), [], "->", bend: -20deg), edge((0, 0), (0, 1), [], "->", bend: -20deg), edge((0, 0), (0, 1), [], "->", bend: 20deg), edge((0, 0), (0.5, 0.5), [], "->", bend: 20deg), node((0, 0.5), [], stroke: 0pt, radius: 0.5em), node((0, 1), [$q_0$], radius: 1em), edge((0, 1), (0, 2), [], "->", bend: 50deg), edge((0, 1), (0, 1.5), [], "->", bend: -20deg), edge((0, 1), (0, 1.5), [], "->", bend: 20deg), edge((0, 1), (0, 2), [], "->", bend: -50deg), node((0, 1.5), [], stroke: 0pt, radius: 0.5em), node((0, 2), [$1$], shape: rect), ) ) ))) ) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 90%, height: 90%, align(horizon, grid( columns: (8fr, 2fr), align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), 1, 1, 1, [\ ], lstick($|q_1〉$), $X$, $X^dagger$, 1 )), align( horizon, diagram( node-stroke: .1em, edge((0, -1), (0, 0), [], "->"), node((0, 0), [$q_1$], radius: 1em), edge((0, 0), (0, 1), [], "->", bend: -50deg), edge((0, 0), (0, 0.5), [], "->", bend: -20deg), edge((0, 0), (0, 0.5), [], "->", bend: 20deg), edge((0, 0), (0, 1), [], "->", bend: 50deg), node((0, 0.5), [], stroke: 0pt, radius: 0.5em), node((0, 1), [$q_0$], radius: 1em), edge((0, 1), (0, 2), [], "->", bend: 50deg), edge((0, 1), (0, 1.5), [], "->", bend: -20deg), edge((0, 1), (0, 1.5), [], "->", bend: 20deg), edge((0, 1), (0, 2), [], "->", bend: -50deg), node((0, 1.5), [], stroke: 0pt, radius: 0.5em), node((0, 2), [$1$], shape: rect), ) ) ))) ) ] #slide(title: "Quantum Circuit Equivalence Checking")[ #figure( box(width: 90%, height: 90%, align(horizon, grid( columns: (8fr, 2fr), align(horizon, quantum-circuit( scale: 200%, lstick($|q_0〉$), $H$, 1, 1, $"S"^dagger$, $sqrt(X)^dagger$, $"S"^dagger$, 1, [\ ], lstick($|q_1〉$), 1, $X$, $X^dagger$, 1, 1, 1 )), align( horizon, diagram( node-stroke: .1em, edge((0, -1), (0, 0), [], "->"), node((0, 0), [$q_1$], radius: 1em), edge((0, 0), (0, 1), [], "->", bend: -50deg), edge((0, 0), (0, 0.5), [], "->", bend: -20deg), edge((0, 0), (0, 0.5), [], "->", bend: 20deg), edge((0, 0), (0, 1), [], "->", bend: 50deg), node((0, 0.5), [], stroke: 0pt, radius: 0.5em), node((0, 1), [$q_0$], radius: 1em), edge((0, 1), (0, 2), [], "->", bend: 50deg), edge((0, 1), (0, 1.5), [], "->", bend: -20deg), edge((0, 1), (0, 1.5), [], "->", bend: 20deg), edge((0, 1), (0, 2), [], "->", bend: -50deg), node((0, 1.5), [], stroke: 0pt, radius: 0.5em), node((0, 2), [$1$], shape: rect), ) ) ))) ) ] #slide(title: "The Longest Common Subsequence Problem")[ #figure( box(width: 70%, height: 90%, align(horizon, { quantum-circuit(scale: 300%, lstick($|q_0〉$), $H$, $X$, $H$, $Y$, 1) v(4em) quantum-circuit(scale: 300%, lstick($|q_0〉$), $Y$, $H$, $H$, $X$, 1) })) ) ] #slide(title: "The Longest Common Subsequence Problem")[ #figure( box(width: 70%, height: 90%, align(horizon, { quantum-circuit(scale: 300%, lstick($|q_0〉$), $H$, $X$, $H$, $Y$, 1) v(1em) text(size: 40pt)[`+y, =h, +h, =x, -h, -y`] v(1em) quantum-circuit(scale: 300%, lstick($|q_0〉$), $Y$, $H$, $H$, $X$, 1) })) ) ] #slide(title: "The Longest Common Subsequence Problem")[ #set text(size: 12pt) #figure( diagram( spacing: 2em, node-stroke: .1em, node((0, 0), [hxhy], radius: 2em), node((1, 0), [xhy], radius: 2em), node((2, 0), [hy], radius: 2em), node((3, 0), [y], radius: 2em), node((4, 0), [], radius: 2em), node((0, 1), [yhxhy], radius: 2em), node((1, 1), [yxhy], radius: 2em), node((2, 1), [yhy], radius: 2em), node((3, 1), [yy], radius: 2em), node((4, 1), [y], radius: 2em), node((0, 2), [yhhxhy], radius: 2em), node((1, 2), [yhxhy], radius: 2em), node((2, 2), [yhhy], radius: 2em), node((3, 2), [yhy], radius: 2em), node((4, 2), [yh], radius: 2em), node((0, 3), [yhhhxhy], radius: 2em), node((1, 3), [yhhxhy], radius: 2em), node((2, 3), [yhhhy], radius: 2em), node((3, 3), [yhhy], radius: 2em), node((4, 3), [yhh], radius: 2em), node((0, 4), [yhhxhxhy], radius: 2em), node((1, 4), [yhhxxhy], radius: 2em), node((2, 4), [yhhxhy], radius: 2em), node((3, 4), [yhhxy], radius: 2em), node((4, 4), [yhhx], radius: 2em), edge((3, 0), (4, 1), "->"), edge((0, 1), (1, 2), "->"), edge((2, 1), (3, 2), "->"), edge((0, 2), (1, 3), "->"), edge((2, 2), (3, 3), "->"), edge((1, 3), (2, 4), "->"), edge((0, 0), (1, 0), [-h], "->"), edge((1, 0), (2, 0), [-x], "->"), edge((2, 0), (3, 0), [-h], "->"), edge((3, 0), (4, 0), [-y], "->"), edge((0, 1), (1, 1), [-h], "->"), edge((1, 1), (2, 1), [-x], "->"), edge((2, 1), (3, 1), [-h], "->"), edge((3, 1), (4, 1), [-y], "->"), edge((0, 2), (1, 2), [-h], "->"), edge((1, 2), (2, 2), [-x], "->"), edge((2, 2), (3, 2), [-h], "->"), edge((3, 2), (4, 2), [-y], "->"), edge((0, 3), (1, 3), [-h], "->"), edge((1, 3), (2, 3), [-x], "->"), edge((2, 3), (3, 3), [-h], "->"), edge((3, 3), (4, 3), [-y], "->"), edge((0, 4), (1, 4), [-h], "->"), edge((1, 4), (2, 4), [-x], "->"), edge((2, 4), (3, 4), [-h], "->"), edge((3, 4), (4, 4), [-y], "->"), edge((0, 0), (0, 1), [+y], "->"), edge((0, 1), (0, 2), [+h], "->"), edge((0, 2), (0, 3), [+h], "->"), edge((0, 3), (0, 4), [+x], "->"), edge((1, 0), (1, 1), [+y], "->"), edge((1, 1), (1, 2), [+h], "->"), edge((1, 2), (1, 3), [+h], "->"), edge((1, 3), (1, 4), [+x], "->"), edge((2, 0), (2, 1), [+y], "->"), edge((2, 1), (2, 2), [+h], "->"), edge((2, 2), (2, 3), [+h], "->"), edge((2, 3), (2, 4), [+x], "->"), edge((3, 0), (3, 1), [+y], "->"), edge((3, 1), (3, 2), [+h], "->"), edge((3, 2), (3, 3), [+h], "->"), edge((3, 3), (3, 4), [+x], "->"), edge((4, 0), (4, 1), [+y], "->"), edge((4, 1), (4, 2), [+h], "->"), edge((4, 2), (4, 3), [+h], "->"), edge((4, 3), (4, 4), [+x], "->"), ) ) ]
https://github.com/EunTilofy/NumComputationalMethods
https://raw.githubusercontent.com/EunTilofy/NumComputationalMethods/main/Chapter6/Chapter6-2.typ
typst
#import "../template.typ": * #show: project.with( course: "Computing Method", title: "Computing Method - Chapter6-2", date: "2024.5.2", authors: "<NAME>, 3210106357", has_cover: false ) *Problems:9, 10, 11, 13, 14* #HWProb(name: "9")[ 画出 $bb("R")^2$ 中满足下列不等式的集合: #set enum(numbering: "(1)") + $norm(x)_1 leq 1$. + $norm(x)_2 leq 1$. + $norm(x)_(infty) leq 1$. ] #solution[ #figure( image("1.png", width: 90%), ) ] #HWProb(name: "10")[ 求证:$norm(I) geq 1, norm(A^(-1)) geq 1/(norm(A)).$ ] #Proof[ 因为 $I = I^2$,所以有 $0 < norm(I) = norm(I^2) leq norm(I) dot.c norm(I)$,所以 $norm(I) geq 1$。 因为 $I = A A^(-1)$,所以 $1 leq norm(I) = norm(A A^(-1)) leq norm(A) dot.c norm(A^(-1)) arrow.double norm(A^(-1)) geq 1/(norm(A))$。 ] #HWProb(name: "11")[ 试证明:$norm(A)_2^2 leq norm(A)_1 dot.c norm(A)_(infty)$。 ] #Proof[ $ norm(A)_2^2 &leq rho (A^T A) leq norm(A^T A)_1 leq norm(A^T)_1 dot.c norm(A)_1 = norm(A)_(infty) dot.c norm(A)_1. $ ] #HWProb(name: "13")[ 设 $A$ 是 $n$ 阶实对称正定矩阵,试证: $ norm(bold(x)) = (bold(x)^T A x)^(1 \/ 2), forall bold(x) in bb(R)^n. $ 是一种向量范数,且与该矩阵范数相容。 ] #Proof[ 1. 正定性:对于 $x in bb(R)^n$,因为 $A$ 正定,所以 $exists$ 正交矩阵 $P$,满足 $A = P^T D P$,$D = diag(lambda_1, lambda_2, dots, lambda_n), lambda_i > 0$,所以 $norm(x) = (x^T P^T D P x)^(1 \/ 2) = ((P x)^T D (P x))^(1\/ 2)$,令 $y = P x$,则 $norm(x) = (y^T D y)^(1 \/ 2) = (sum_(i = 1)^n lambda_i y_i^2)^(1\/ 2)$,所以 $norm(x) geq 0$,且 $norm(x) = 0$ 当切仅当 $y = 0 = P x$,即 $x = 0$。 2. 奇次性:对于 $x in bb(R)^n, alpha in bb(R)$,$norm(alpha x) = (alpha x^T A alpha x)^(1 \/ 2) = alpha (x^T A x)^(1 \/ 2) = alpha norm(x)$。 3. 三角不等式:同 1,对于 $x_1, x_2 in bb(R)^n$,取 $y_1 = P x_1, y_2 = P x_2$,则有 $norm(x_1 + x_2) = ((y_1 + y_2)^T D (y_1 + y_2))^(1 \/ 2) = (sum_(i = 1)^n (y_(1 i)+ y_(2 i))^2)^(1\/ 2) = (sum_(i = 1)^n (sqrt(lambda_i) y_(1 i) + sqrt(lambda_i) y_(2 i))^2)^(1 \/ 2) leq (sum_(i = 1)^n (sqrt(lambda_i) y_(1 i))^2)^(1\/ 2) + (sum_(i = 1)^n (sqrt(lambda_i) y_(2 i))^2)^(1\/ 2) = norm(x_1) + norm(x_2)$。 则 $norm(bold(x)) = (bold(x)^T A x)^(1 \/ 2), forall bold(x) in bb(R)^n$ 是一种向量范数。 对于 $B in bb(R)^(n times n)$,$norm(B) = max_(v^T A v = 1) (v^T B^T A B v)^(1\/ 2)$,所以 $norm(B x) = (x^T B^T A B x)^(1\/ 2) = norm(x) ((x/norm(x))^T B^T A B (x / norm(x)))^(1\/ 2) leq norm(x) dot.c norm(B)$(因为 $norm(x/norm(x)) = 1$)。 ] #HWProb(name: "14")[ 对矩阵$ A = bmatrix(-2, 1, 0, 0; 1, -2, 1, 0; 0, 1, -2, 1; 0, 0, 1, -2) $求 $norm(A)_(infty)$, $norm(A)_2$, $norm(A)_1$, $norm(A)_(bb(F))$ 和 $text("Cond")(A)_2$。 ] #solution[ $ &norm(A)_(infty) = max_(i = 1)^4 sum_(j=1)^4 abs(a_(j i)) = 4. \ &norm(A)_1 = max(i = 1)^4 sum_(j=1)^4 abs(a_(i j)) = 4. \ &norm(A)_2 = lambda_(max)(A^T A) = lambda_(max)(bmatrix(4, 1, 0, 0; 1, 4, 1, 0; 0, 1, 4, 1; 0, 0, 1, 4)) = (5 + sqrt(5)) / 2. \ &norm(A)_(bb(F)) = sqrt(sum_(i = 1)^4 sum_(j= 1)^4 a_(i j)^2) = sqrt(22). \ &text("Cond")(A)_2 = (lambda_(max)(A^T A)) / (lambda_(min) (A^T A)) = 5 + 2sqrt(5)。 $ ]
https://github.com/SillyFreak/typst-crudo
https://raw.githubusercontent.com/SillyFreak/typst-crudo/main/src/lib.typ
typst
MIT License
#let _read = read /// _raw-to-lines_: extract lines and properties from a `raw` element. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.r2l(```txt /// first line /// second line /// ```) /// ````) /// /// Note that even though you will usually want to use this on raw _blocks_, this is not a /// necessity: /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.r2l( /// raw("first line\nsecond line") /// ) /// ````) /// /// For flexibility, regular strings are also supported. Strings don't have a language and aren't /// blocks: /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.r2l("first line\nsecond line") /// ````) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// -> array #let r2l(raw-block) = { assert( type(raw-block) == str or (type(raw-block) == content and raw-block.func() == raw), message: "parameter to r2l must be a raw element or a string", ) let (text, ..fields) = if type(raw-block) == str { (text: raw-block) } else { raw-block.fields() } (text.split("\n"), fields) } /// _lines-to-raw_: convert lines into a `raw` element. Properties for the created element can be /// passed as parameters. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.l2r( /// ("first line", "second line") /// ) /// ````) /// /// Note that even though you will usually want to construct raw _blocks_, this is not assumed. To /// create blocks, pass the appropriate parameter: /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.l2r( /// ("first line", "second line"), /// block: true, /// ) /// ````) /// /// - lines (array): an array of strings /// - ..properties (arguments): properties for constructing the new `raw` element /// -> content #let l2r(lines, ..properties) = { raw(lines.join("\n"), ..properties) } /// Transforms the text of a raw element and creates a new one with the new text. All properties of /// the element (e.g. `block` and `lang`) are preserved. /// /// #block(breakable: false, example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.transform-text( /// ```typc /// /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// str.trim /// ) /// ````)) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// - mapper (function): a function that takes a single string and returns a new one /// -> content #let transform-text(raw-block, mapper) = { let (text, ..fields) = if type(raw-block) == str { (text: raw-block) } else { raw-block.fields() } text = mapper(text) raw(text, ..fields) } /// Transforms all lines of a raw element and creates a new one with the lines. All properties of /// the element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.transform( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// lines => lines.filter(l => { /// // only preserve non-comment lines /// not l.starts-with(regex("\s*//")) /// }) /// ) /// ````) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// - mapper (function): a function that takes an array of strings and returns a new one /// -> content #let transform(raw-block, mapper) = { let (lines, fields) = r2l(raw-block) lines = mapper(lines) l2r(lines, ..fields) } /// A wrapper around the built-in #link("https://typst.app/docs/reference/data-loading/read/")[`read()`] /// function that returns the file contents as a raw element. Since code files often have a trailing /// newline by convention, this function can optionally trim the file contents (and trims the end by /// default). /// /// - properties (dict): properties for constructing the new `raw` element, given as a dictionary /// instead as direct arguments since the latter is sed for the `read()` parameters /// - trim (boolean, alignment): one of `true`, `false`, `start`, `end` to determine whether and /// what to #link("https://typst.app/docs/reference/foundations/str/#definitions-trim-parameters-at")[`trim()`] /// from the read file /// - ..args (arguments): the parameters to #link("https://typst.app/docs/reference/data-loading/read/")[`read()`], /// i.e. file name and encoding /// -> content #let read( properties: (:), trim: end, ..args ) = { assert(trim in (true, false, start, end), message: "invalid value for trim") let text = _read(..args) if trim == true { text = text.trim() } else if trim != false { text = text.trim(at: trim) } raw(text, ..properties) } /// Maps individual lines of a raw element and creates a new one with the lines. All properties of /// the element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.map( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// l => l.trim() /// ) /// ````) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// - mapper (function): a function that takes a string and returns a new one /// -> content #let map(raw-block, mapper) = { transform(raw-block, lines => lines.map(mapper)) } /// Filters lines of a raw element and creates a new one with the lines. All properties of the /// element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.filter( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// l => not l.starts-with(regex("\s*//")) /// ) /// ````) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// - test (function): a function that takes a string and returns a new one /// -> content #let filter(raw-block, test) = { transform(raw-block, lines => lines.filter(test)) } /// Slices lines of a raw element and creates a new one with the lines. All properties of the /// element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.slice( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// 1, 3, /// ) /// ````) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// - ..args (arguments): the same arguments as accepted by /// #link("https://typst.app/docs/reference/foundations/array/#definitions-slice")[`array.slice()`] /// -> content #let slice(raw-block, ..args) = { transform(raw-block, lines => lines.slice(..args)) } /// Extracts lines of a raw element similar to how e.g. printers select page ranges. All properties /// of the element (e.g. `block` and `lang`) are preserved. /// /// This function is comparable to @@slice() but doesn't have the the option to specify the _number_ /// of selected lines via `count`. On the other hand, multiple ranges of pages can be selected, and /// indices are one-based by default, which may be more natural for line numbers. /// /// Lines are selected by any number of parameters. Each parameter can take either of three forms: /// - a single number: that line is included in the output /// - an array of numbers: these lines are included in the output (a major usecase being `range()` /// -- but beware that `range()` uses an exclusive end index) /// - a string containing numbers (e.g. `"1"`) and inclusive ranges (e.g. `"2-3"`) separated by /// commas. Range limits may be omitted (e.g. `"-2"`, `"2-"`), meaning the range starts/ends at /// the first/last line. Whitespace is allowed. /// /// All three kinds of parameters can be mixed, and lines can be selected any number of times and in /// any order. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.lines( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// // another comment /// } /// ```, /// "-2,4-,1", "2-3", range(3, 5), 5, /// ) /// ````) /// /// - raw-block (content, str): a single `raw` element or (multi line) string /// - ..line-numbers (arguments): any number of line number specifiers, as described above /// - zero-based (boolean): whether the supplied numbers are one-based line numbers or zero-based /// indices /// -> content #let lines(raw-block, ..line-numbers, zero-based: false) = { assert(line-numbers.named().len() == 0, message: "only positional arguments can be given") let line-numbers = line-numbers.pos() let offset = if zero-based { 0 } else { -1 } transform(raw-block, lines => { let l(num) = lines.at(num + offset) for spec in line-numbers { if type(spec) == int { // make an array with a single line number spec = (spec,) } else if type(spec) == str { // convert the string into an array with a single line number spec = { for part in spec.split(",") { let bounds = part.split("-").map(str.trim) if bounds.len() == 1 { // a single page - already in an array bounds.map(int) } else if bounds.len() == 2 { // a page range let (lower, upper) = bounds lower = if lower != "" { int(lower) } else { 0 - offset } upper = if upper != "" { int(upper) } else { lines.len() - 1 - offset } // make it inclusive array.range(lower, upper + 1) } else { panic("invalid page range: " + spec) } } } } assert(type(spec) == array, message: "page range must be an int, array, or a string") spec.map(l) } }) } /// Joins lines of multiple raw elements and creates a new one with the lines. All properties of the /// `main` element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.join( /// ```java /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// ```typc /// let bar() = { /// // some comment /// ... do something ... /// } /// ```, /// main: -1, /// ) /// ````) /// /// String parameters are allowed; the `main` parameter defaults to the first raw block: /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.join( /// "// these strings don't", /// "// determine the properties", /// ```typ /// // this raw block does: /// // still Typst! /// ```, /// ) /// ````) /// /// - ..raw-blocks (arguments): any number of single `raw` elements or (multi line) strings /// - main (int, auto): the index of the `raw` element of which properties should be preserved. /// Negative indices count from the back. ```typc auto``` chooses the first positional argument /// that is a `raw` element and not a string, if any. /// -> content #let join(..raw-blocks, main: auto) = { assert(raw-blocks.named().len() == 0, message: "only positional arguments can be given") let raw-blocks = raw-blocks.pos() let main = main if main == auto { main = raw-blocks.position(elem => type(elem) == content) if main == none { main = 0 } } let contents = raw-blocks.map(r2l) let lines = contents.map(c => c.at(0)).join() let fields = contents.at(main).at(1) l2r(lines, ..fields) }
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/tests/tables/test.typ
typst
MIT License
#import "/src/zero.typ" #set page(width: auto, height: auto, margin: .5em) #set table(stroke: none) #zero.ztable( columns: 3, align: center, format: (none, auto, auto), $n$, $α$, $β$, table.hline(), [1], "2.3", [10000], [2], "2.33", [1.0], [3], "12.3", [1993], [4], ".001", [1.2], [10], "17", [0], ) #pagebreak() #zero.set-num(omit-unity-mantissa: true) #zero.ztable( columns: 4, align: center, format: (auto,) * 4, $n$, $α$, $β$, $γ$, table.hline(), $Alpha$, "1.2+-2", "2e3", "1+-2e4", $Beta$, "12+-23", "66e98", "-17+-2e-4", $Gamma$, "0+-.2", "1e7", "-.23(2)e-4", ) #pagebreak() #zero.ztable( columns: 2, format: (auto, (decimal-separator: ",", fixed: 2)), "2.3", "3422", "10", "101", ) #pagebreak() // check that auto alignment works #{ set align(right) zero.ztable( columns: 2, format: (auto, (decimal-separator: ",", fixed: 2)), [ Long title], [ Defg ], table.hline(), "2.3", "3422", "10", "101", ) } #pagebreak() // Check that `math: false` works with tables #[ #show math.equation: set text(2pt) #zero.ztable( format: ((math: false),), columns: 1, [12.3], [2.211] ) ]
https://github.com/pku-typst/ichigo
https://raw.githubusercontent.com/pku-typst/ichigo/main/src/themes/sketch/lib.typ
typst
MIT License
#let logo_path = "./res/PKU.svg" #let logo_str = read(logo_path).replace("920f14", "cccccc") #let theme(meta) = { return ( title: ( whole-page: () => { return [ #set page(margin: 0pt, header: none, footer: none) // Logo #place( center + top, dx: 40%, dy: 10pt, )[ #image.decode(logo_str, width: 100%) ] // Info panel #place( bottom + left, dx: 0pt, dy: -20%, rect(fill: rgb("cccccc"), width: 100%, height: 10pt), ) #place( bottom + left, dx: 24pt, dy: -20%, text( meta.course-name, size: 36pt, font: ("Source Han Serif SC"), baseline: -0.6em, ), ) #place( bottom + left, dx: 24pt, dy: -20%, box([ #set text( size: 20pt, font: ("Source Han Serif SC"), baseline: 1em, ) #set align(horizon) #meta.author-info ]), ) #pagebreak(weak: true) ] }, simple: () => { return align( center, block( align( horizon, stack( dir: ltr, spacing: 8pt, image.decode(logo_str, width: 30%), context line( length: 20% * page.width, angle: 90deg, stroke: ( thickness: 0.8pt, paint: gray.lighten(60%), ), ), align(left)[ #block[ #set text(font: ( "New Computer Modern", "Source Han Serif SC", )) #text(size: 28pt, weight: "bold")[ #meta.course-name ] #text(size: 18pt)[ #meta.serial-str ] #text(size: 12pt, font: "STFangsong")[ #meta.author-info ] ] ], ), ), ), ) }, ), page-setting: ( header: () => { set text(size: 10.5pt, font: "Source Han Serif SC") block( grid( columns: (1fr, 1fr), align(left + horizon, meta.course-name), align(right + horizon, meta.serial-str), ), ) place(line(length: 100%, stroke: 0.5pt), dy: 0.5em) }, footer: () => { let cur = context counter(page).get().at(0) let tot = context counter(page).final().at(0) return align(center)[ #set text(size: 10.5pt) #cur / #tot ] }, ), fonts: ( heading: ( "New Computer Modern", "Source Han Serif SC", ), text: ( "New Computer Modern", "Source Han Serif SC", ), equation: ( "New Computer Modern Math", "Source Han Serif SC", ), ), ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheda-seu-thesis/0.2.0/seu-thesis/templates/degree.typ
typst
Apache License 2.0
#import "../pages/cover-degree-fn.typ": degree-cover-conf #import "../pages/title-page-degree-cn-fn.typ": title-cn-conf #import "../pages/title-page-degree-en-fn.typ": title-en-conf #import "../pages/statement-degree-fn.typ": degree-statement-conf #import "../parts/abstract-degree-fn.typ": abstract-conf #import "../parts/outline-degree-fn.typ": outline-conf #import "../parts/terminology.typ": terminology-conf #import "../parts/main-body-degree-fn.typ": main-body-bachelor-conf #import "../utils/set-degree.typ": set-degree #import "../utils/smart-pagebreak.typ": gen-smart-pagebreak #import "../utils/thanks.typ": thanks #import "../utils/states.typ": appendix #let degree-conf( author: (CN: "王东南", EN: "<NAME>", ID: "012345"), thesisname: ( CN: "硕士学位论文", EN: [ A Thesis submitted to \ Southeast University \ For the Academic Degree of Master of Touching Fish ], heading: "东南大学硕士学位论文" ), title: ( CN: "摸鱼背景下的Typst模板使用研究", EN: "A Study of the Use of the Typst Template During Touching Fish" ), advisors: ( (CN: "湖牌桥", EN:"HU Pai-qiao", CNTitle: "教授", ENTitle: "Prof."), (CN: "苏锡浦", EN:"SU Xi-pu", CNTitle: "副教授", ENTitle: "Associate Prof.") ), school: ( CN: "摸鱼学院", EN: "School of Touchingfish" ), major: ( main: "摸鱼科学", submajor: "计算机摸鱼" ), degree: "摸鱼学硕士", categorynumber: "N94", secretlevel: "公开", UDC: "303", schoolnumber: "10286", committeechair: "张三 教授", readers: ( "李四 副教授", "王五 副教授" ), date: ( CN: ( defenddate: "2099年01月02日", authorizedate: "2099年01月03日", finishdate: "2024年01月15日" ), EN: ( finishdate: "Jan 15, 2024" ) ), thanks: "本论文受到摸鱼基金委的基金赞助(123456)", degreeform: "应用研究", cnabstract: [示例摘要], cnkeywords: ("关键词1", "关键词2"), enabstract: [#lorem(100)], enkeywords: ("Keywords1", "Keywords2"), alwaysstartodd: false, terminology: none, anonymous: false, skip-with-page-blank: false, bilingual-bib: true, doc, ) = { let smart-pagebreak = gen-smart-pagebreak.with( skip-with-page-blank: skip-with-page-blank, always-skip-even: alwaysstartodd, ) show: set-degree.with(always-new-page: smart-pagebreak, bilingual-bib: bilingual-bib) degree-cover-conf( author: author, thesisname: thesisname, title: title, advisors: advisors, school: school, major: major, degree: degree, categorynumber: categorynumber, secretlevel: secretlevel, UDC: UDC, schoolnumber: schoolnumber, committeechair: committeechair, readers: readers, date: date, degreeform: degreeform, cnabstract: cnabstract, cnkeywords: cnkeywords, enabstract: enabstract, enkeywords: enkeywords, terminology: terminology, anonymous: anonymous, ) smart-pagebreak() title-cn-conf( author: author, thesisname: thesisname, title: title, advisors: advisors, school: school, major: major, date: date, thanks: thanks, anonymous: false, ) smart-pagebreak() title-en-conf( author: author, thesisname: thesisname, title: title, advisors: advisors, school: school, date: date, anonymous: false, ) smart-pagebreak() degree-statement-conf() smart-pagebreak() abstract-conf( cnabstract: cnabstract, cnkeywords: cnkeywords, enabstract: enabstract, enkeywords: enkeywords, page-break: smart-pagebreak, ) smart-pagebreak() outline-conf() if not terminology in (none, [], [ ], ""){ smart-pagebreak() terminology-conf(terminology) } smart-pagebreak(skip-with-page-blank: true) show: main-body-bachelor-conf.with(thesisname: thesisname) doc } #show: degree-conf.with( author: (CN: "王东南", EN: "<NAME>", ID: "012345"), thesisname: ( CN: "硕士学位论文", EN: [ A Thesis submitted to \ Southeast University \ For the Academic Degree of Master of Touching Fish ], heading: "东南大学硕士学位论文" ), title: ( CN: "摸鱼背景下的Typst模板使用研究", EN: "A Study of the Use of the Typst Template During Touching Fish" ), advisors: ( (CN: "湖牌桥", EN:"HU Pai-qiao", CNTitle: "教授", ENTitle: "Prof."), (CN: "苏锡浦", EN:"SU Xi-pu", CNTitle: "副教授", ENTitle: "Associate Prof.") ), school: ( CN: "摸鱼学院", EN: "School of Touchingfish" ), major: ( main: "摸鱼科学", submajor: "计算机摸鱼" ), degree: "摸鱼学硕士", categorynumber: "N94", secretlevel: "公开", UDC: "303", schoolnumber: "10286", committeechair: "张三 教授", readers: ( "李四 副教授", "王五 副教授" ), date: ( CN: ( defenddate: "2099年01月02日", authorizedate: "2099年01月03日", finishdate: "2024年01月15日" ), EN: ( finishdate: "Jan 15, 2024" ) ), thanks: "本论文受到摸鱼基金委的基金赞助(123456)", degreeform: "应用研究", cnabstract: [示例摘要], cnkeywords: ("关键词1", "关键词2"), enabstract: [#lorem(100)], enkeywords: ("Keywords1", "Keywords2"), alwaysstartodd: true, terminology: none, anonymous: false, )
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Insiemi/Relazioni.typ
typst
Creative Commons Zero v1.0 Universal
#import "../Metodi_defs.typ": * Dati due insiemi $A$ e $B$, viene detta *corrispondenza* fra $A$ e $B$ un sottoinsieme $cal(R)$ del loro prodotto cartesiano; nel caso particolare in cui $A = B$, viene detta *relazione* su $A$. Dato un insieme $A$ ed una relazione $cal(R)$ su $A$, per indicare che una coppia $(a, b) in A times A$ appartiene a $cal(R)$ si usa dire che $a$ é in _relazione_ con $b$ e si usa la dicitura $a cal(R) b$. #example[ Sia $A = {"rosso", "verde", "blu"}$. Si ha: $ A times A = {&("rosso", "rosso"), ("rosso", "verde"), ("rosso", "blu"), ("verde", "rosso"), \ &("verde", "verde"), ("verde", "blu"), ("blu", "rosso"), ("blu", "verde"), ("blu", "blu")} $ Una relazione $cal(R)$ su $A$ potrebbe essere: $ cal(R) subset.eq A times A = {("rosso", "rosso"), ("rosso", "verde"), ("verde", "verde"), ("blu", "verde")} $ ] Dato un insieme $A$ ed una relazione $cal(R)$ su di esso, si dice che $cal(R)$ é una relazione: - *riflessiva* se $forall a in A$ si ha $a cal(R) a$; - *simmetrica* se $forall a, b in A$ $a cal(R) b$ implica $b cal(R) a$; - *transitiva* se $forall a, b, c in A$ $a cal(R) b$ e $b cal(R) c$ implicano $a cal(R) c$; - *antisimmetrica* se $forall a, b in A$ $a cal(R) b$ e $b cal(R) a$ implicano $a = b$. Una relazione puó rientrare in una, piú di una o anche nessuna di queste categorie. #example[ Sia $A = {"rosso", "verde", "blu"}$. Sia: $ cal(R)_(1) = {("rosso", "rosso"), ("verde", "verde"), ("rosso", "verde"), ("verde", "rosso"), ("verde", "blu")} $ - Non é riflessiva, perché $("blu", "blu") in.not cal(R)_(1)$; - Non é simmetrica, perché $("verde", "blu") in cal(R)_(1)$ ma $("blu", "verde") in.not cal(R)_(1)$; - Non é transitiva, perché $("rosso", "verde") in cal(R)_(1)$ e $("verde", "blu") in cal(R)_(1)$ ma $("blu", "rosso") in.not cal(R)_(1)$; - Non é antisimmetrica, perché $("rosso", "verde") in cal(R)_(1)$ e $("verde", "rosso") in cal(R)_(1)$ ma $"rosso" != "verde"$. Sia invece: $ cal(R)_(2) = {&("rosso", "rosso"), ("verde", "verde"), ("blu", "blu"), ("rosso", "verde"), \ &("verde", "rosso"), ("verde", "blu"), ("blu", "verde"), ("rosso", "blu"), ("blu", "rosso")} $ Tale relazione é riflessiva, simmetrica e transitiva, ma non é antisimmetrica. Sia infine: $ cal(R)_(3) = {("rosso", "rosso"), ("verde", "verde"), ("blu", "blu")} $ Tale relazione é riflessiva, simmetrica, transitiva e antisimmetrica. ] Dato un insieme $A$, una relazione $cal(R)$ su $A$ che é (almeno) simmetrica, riflessiva e transitiva viene detta *relazione di equivalenza*. Le relazioni di equivalenza vengono anche spesso indicate con il simbolo $tilde.op$. Siano $A$ un insieme e $tilde.op$ una relazione di equivalenza su $A$. Preso un qualsiasi elemento $a in A$, si definisce *classe di equivalenza* di $a$ rispetto ad $tilde.op$ l'insieme: $ [a]_(tilde.op) = {b: b in A and b tilde.op a} $ Ovvero, l'insieme che contiene tutti gli elementi di $A$ che sono in relazione con $a$. Un qualsiasi elemento di una classe di equivalenza viene detto *rappresentante* di tale classe. #example[ Sia $A = {"rosso", "verde", "blu", "giallo"}$. Si consideri la relazione di equivalenza: $ tilde.op space = {&("rosso", "rosso"), ("verde", "verde"), ("blu", "blu"), ("giallo", "giallo"), ("rosso", "giallo"), \ &("giallo", "blu"), ("rosso", "blu"), ("blu", "rosso"), ("giallo", "rosso"), ("blu", "giallo")} $ Si hanno le seguenti quattro classi di equivalenza: #set math.mat(column-gap: 2.5em, delim: none) $ mat(["verde"]_(tilde.op) = {"verde"}, ["blu"]_(tilde.op) = ["giallo"]_(tilde.op) = ["rosso"]_(tilde.op) = {"rosso", "giallo", "blu"}) $ ] <Equiv-classes> #lemma[ Per qualsiasi insieme $A$, per qualsiasi relazione di equivalenza $tilde.op$ su $A$ e per qualsiasi $a in A$, si ha $[a]_(tilde.op) != emptyset$. ] <Equiv-not-empty> #proof[ Essendo $tilde.op$ una relazione di equivalenza, deve essere anche riflessiva, ovvero deve valere $a tilde.op a$. Pertanto, $[a]_(tilde.op)$ deve contenere almeno $a$, e quindi non é un insieme vuoto. ] #lemma[ Siano $A$ un insieme non vuoto e $tilde.op$ una relazione di equivalenza su $A$. Per ogni $a, b in A$, si ha $[a]_(tilde.op) = [b]_(tilde.op)$ oppure $[a]_(tilde.op) sect [b]_(tilde.op) = emptyset$. Ovvero, o le classi di equivalenza di $a$ e di $b$ sono lo stesso insieme o sono due insiemi disgiunti. ] <Equiv-disjoint> #proof[ Si supponga $[a]_(tilde.op) sect [b]_(tilde.op) != emptyset$, e sia $c in [a]_(tilde.op) sect [b]_(tilde.op)$. Per definizione di intersezione, si ha $c in [a]_(tilde.op)$ e $c in [b]_(tilde.op)$, ma questo equivale a dire $c tilde.op a$ e $c tilde.op b$. Essendo $tilde.op$ una relazione di equivalenza, deve essere simmetrica, pertanto valendo $c tilde.op a$ vale anche $a tilde.op c$. Per lo stesso motivo, deve essere anche transitiva, pertanto valendo $a tilde.op c$ e $c tilde.op b$ allora vale anche $a tilde.op b$, cioè $a in [b]_(tilde.op)$. Essendo $tilde.op$ simmetrica, se vale $a tilde.op b$ allora vale anche $b tilde.op a$. Sia $x in A$ un elemento generico per cui vale $x in [a]_(tilde.op)$, ovvero $x tilde.op a$. Avendo provato che vale $a tilde.op b$ ed essendo $tilde.op$ transitiva, vale anche $x tilde.op b$, ovvero $x in [b]_(tilde.op)$. Essendo $x$ un elemento generico, significa che questa proprietá vale per qualsiasi elemento di $[a]_(tilde.op)$, ovvero che qualsiasi elemento di $[a]_(tilde.op)$ é anche elemento di $[b]_(tilde.op)$. In altre parole, $[a]_(tilde.op) subset.eq [b]_(tilde.op)$. Sia $y in A$ un elemento generico per cui vale $y in [b]_(tilde.op)$, ovvero $y tilde.op b$. Avendo provato che vale $b tilde.op a$ ed essendo $tilde.op$ transitiva, vale anche $y tilde.op a$, ovvero $y in [a]_(tilde.op)$. Essendo $y$ un elemento generico, significa che questa proprietá vale per qualsiasi elemento di $[b]_(tilde.op)$, ovvero che qualsiasi elemento di $[b]_(tilde.op)$ é anche elemento di $[a]_(tilde.op)$. In altre parole, $[b]_(tilde.op) subset.eq [a]_(tilde.op)$. Avendo provato che vale sia $[a]_(tilde.op) subset.eq [b]_(tilde.op)$ sia $[b]_(tilde.op) subset.eq [a]_(tilde.op)$, per definizione di uguaglianza fra insiemi vale $[a]_(tilde.op) = [b]_(tilde.op)$. É stato allora provato che se $[a]_(tilde.op) sect [b]_(tilde.op) != emptyset$, allora $[a]_(tilde.op) = [b]_(tilde.op)$. Ma questa proposizione equivale ad asserire che vale o $[a]_(tilde.op) = [b]_(tilde.op)$ o $[a]_(tilde.op) sect [b]_(tilde.op) = emptyset$, e pertanto il lemma é provato. ] Dato un insieme $A$ ed una relazione di equivalenza $tilde.op$ su $A$, viene detto *insieme quoziente* l'insieme $A slash tilde.op$ che contiene tutte le classi di equivalenza (distinte) di $tilde.op$. Ovvero: $ A slash tilde.op space = {[a]_(tilde.op), a in A} $ #example[ Nell'@Equiv-classes si ha $A slash tilde.op space = {["blu"]_(tilde.op), ["verde"]_(tilde.op)}$. ] Sia $A$ un insieme diverso da $emptyset$, e sia $cal(F) = {X_(1), X_(2), ..., X_(k)}$ un insieme che contiene $k$ sottoinsiemi di $A$. $cal(F)$ viene detto *partizione* di $A$ se: - $forall i in {1, ..., k}$, si ha $X_(i) != emptyset$; - $forall i, j in {1, ..., k}$ si ha $X_(i) sect X_(j) = emptyset$. Ovvero, ciascun sottoinsieme é disgiunto da tutti gli altri; - $union.big_(i = 1)^(k) X_(i) = A$. Ovvero, l'unione di tutti i sottoinsiemi restituisce l'insieme di partenza. #example[ Sia $A = {"rosso", "verde", "blu", "giallo", "rosa", "nero", "bianco", "grigio"}$. Una possibile partizione di tale insieme é data da: $ cal(F) = {X_(1), X_(2), X_(3)} = {{"rosso", "nero", "bianco", "giallo", "grigio"}, {"verde", "blu"}, {"rosa"}} $ ] #theorem("Equivalenza fra insieme quoziente e partizioni")[ Sia $A$ un insieme e sia $tilde.op$ una relazione di equivalenza su $A$. L'insieme quoziente $A slash tilde.op$ determina una partizione su $A$. Allo stesso modo, sia $cal(F) = {X_(1), X_(2), ..., X_(k)}$ una partizione di $A$; la relazione $cal(R)$ definita come $a cal(R) b <==> {exists i in {1, ..., k} "t.c." a, b in X_(i)}$ é una relazione di equivalenza su $A$. ] <Equivalence-relation-is-partition> #proof[ Si osservi come: - Per il @Equiv-not-empty, ogni classe di equivalenza di un qualsiasi insieme non é l'insieme vuoto; - Per il @Equiv-disjoint, ogni classe di equivalenza di un qualsiasi insieme é o uguale ad un'altra o disgiunta da questa. Essendo l'insieme quoziente costituito da sole classi di equivalenza distinte, si ha che ciascuna classe che lo compone é distinta da tutte le altre; - Dato che $[a]_(tilde.op) subset.eq A$ per qualsiasi $a in A$, é evidente come $union.big_(a in A) [a]_(tilde.op) subset.eq A$. Inoltre, sempre per il @Equiv-not-empty, ogni $a in A$ appartiene a $[a]_(tilde.op)$, e quindi $A subset.eq union.big_(a in A) [a]_(tilde.op)$. Unendo questo risultato al precedente, si ha $A = union.big_(a in A) [a]_(tilde.op)$. Ovvero, $A slash tilde.op$ risponde alla definizione di partizione. D'altra parte, sia $cal(R)$ la relazione definita come $a cal(R) b <==> {exists i in {1, ..., k} "t.c." a, b in X_(i)}$. Tale relazione é: - Riflessiva, perché per definizione di partizione ogni $X_(i)$ non é vuoto, pertanto esiste sempre almeno un $a in A$ che vi appartenga, e quindi $a cal(R) a$ é sempre verificato; - Simmetrica, perché se $a, b in X_(i)$ allora $b, a in X_(i)$, dato che gli elementi di un insieme non sono ordinati; - Transitiva, perché se $a, b in X_(i)$ e $b, c in X_(i)$, allora $a, c in X_(i)$. Pertanto, é una relazione di equivalenza. ]
https://github.com/ddorn/cv
https://raw.githubusercontent.com/ddorn/cv/master/resume.typ
typst
#set page(margin: (x: 0.5cm, top: 0.0cm, bottom: 0.5cm)) #let accent = rgb("#f8f3ec") // For headers background #let accent-strong = rgb("#CDA56D") // for bold text #let accent-weak = rgb("d0bab0") // for links #let side = 3cm #let entry-sep = -0.0cm // to make things fit in one page #let use-stars = false #let use-stars = true // Style for the colored headings #show heading.where(level: 1): heading => { v(-0.3cm) rect( // radius: 5pt, fill: accent, stroke: (bottom: black), )[#smallcaps[#heading.body] #h(1fr)] } // Underline the links #show link: it => underline(it, stroke: accent-weak) // Emojis taken from https://github.com/ariabuckles/twemoji-svg/tree/master/assets/svg // Unicode point can be looked up https://www.emojiall.com/en/code/1F4C4 // You can add new emojis&flags in the images/ folder. Note that typing emojis directly in the text with render in the preview, but not work inside the pdf (the preview is a png! :o) #let emoji-svg(name, is-flag: false) = { h(0.3em, weak: true) box(baseline: 0em, height: 0.666em)[#image("images/" + name + ".svg", height: 1em)] } #let flag(name) = { h(0.3em, weak: true) box()[#move(dy: -0.2em)[ #box(height: 0.66em)[#image("images/" + lower(name) + ".svg", height: 0.9em)] ]] } #let countries = ( "fr": "France", "uk": "UK", "de": "Germany", "ch": "CH", "be": "Belgium", ) #let loc(city, country) = { city; flag(country) } // #let loc(city, country) = { city; if country != "earth" [, #upper(country)]} // #let loc(city, country) = { city; ", "; (countries.at(lower(country)))} #let Paris = loc("Paris", "fr") #let Lausanne = loc("Lausanne", "ch") #let Berlin = loc("Berlin", "de") #let Cambridge = loc("Cambridge", "uk") #let London = loc("London", "uk") #let Bruxelles = loc("Bruxelles", "be") #let Europe = loc("Across Europe", "europe") #let entry(name, descr, dates, loc, url: none, star: false) = [ #grid(columns: (side, auto), gutter: 0.6cm, // inset: (x: 0.3cm), // stroke: black, align: (right, left), [ //#if star { place(emoji-svg("star"), dx: -0.0em, dy: -0.0em)} #loc \ _#dates _], [#if star and use-stars { emoji-svg("star")} *#name* #if url != none [(#url)]\ _#descr _ ], ) #v(entry-sep) ] // Header #box(height: 4cm)[ #grid( columns: (auto, 1fr, auto), inset: (0cm, 0.5cm, 0cm), align: (left + top, right + bottom, left), // stroke: black )[ #v(0.5cm) #text(size: 20pt)[*<NAME>N*]\ #text(size: 16pt)[Research Engineer]\ #v(1fr) #emoji-svg("enveloppe") #link("mailto:<EMAIL>")[`<EMAIL>`]\ #emoji-svg("internet") #link("https://ddorn.fr")[`ddorn.fr`]\ #emoji-svg("github") #link("https://github.com/ddorn")[`github.com/ddorn`] #v(0.5cm) ][ #box(width: 92%, height: 100%)[ // You can tweak this number% for the width of the description text so that it looks best #show strong: txt => [#text(fill: accent-strong)[#txt]] // Color the bold text Diego works on the mitigation of *systemic risks* \ from *general-purpose artificial intelligence* systems. He has extensive expertise in *software engineering* and experience in *teaching*, *leadership* and *communication* from his volunteering. \ He finished his master in Communication Systems in August 2024. ] //#h(-0.5cm) ][ // #image("images/photo.JPG") ] ] #v(-0.4cm) = Work Experience #entry([Research engineer at CeSIA (French Center for AI safety)], [Lead the design of benchmarks to evaluate jailbreak and hallucination detectors for LLMs, red-teamed input-output safeguards. Published "#link( "https://arxiv.org/abs/2406.01364", )[ #emph[BELLS: A Framework Towards Future Proof Benchmarks for the Evaluation of LLM Safeguards]]" in the NextGen AI Safety workshop at ICML 2024. ], [Feb. -- Aug. 2024 ], Paris, star: true ) #entry([Head Teacher for four ML4Good, a summer school on systemic AI risk], [Delivery and improvement of 10 days of technical and conceptual workshopsw for \~20 participants, covering threat modeling, technical safety and AI policy. Management of the teaching team of 2\~3.], [Aug. 2023 -- present], Europe, url: [#link("https://www.ml4good.org")[`ml4good.org`]], star: true ) #entry([Research assistant, Machine Learning Group, Cambridge University], [Research on goal misgeneralisation in Reinforcement Learning (RL) with <NAME> and <NAME>. //#emoji-svg("page") Published "#link( "https://openreview.net/forum?id=QT4tXTqTTr", )[ #emph[Goal Misgeneralization as Implicit Goal Conditioning]]" in the GCRL workshop at Neurips 2023 ], [July -- Sep. 2023], Cambridge) #entry([Lead developer for the startup SPRIG], [Developing a distributed platform to increase confidence in mathematical proofs.], [Jan. 22 -- May 23], Lausanne, url: [#link("https://sprigproofs.org")[`sprigproofs.org`]] ) // #entry([Teaching assistant at EPFL], // [TA for 8 courses for 1st, 2nd and 3rd year bachelors: Analysis (real, vectorial, complex), C++, mathematical logic, computer science basics.], // [2019 - 2021], // Lausanne) = Education #entry([Master's in Communication Systems, Ecole Polytechnique Fédérale de Lausanne (EPFL)], [Focus on artificial intelligence, formal verification and advanced algorithms. Minor in Mathematics. Obtained with an average of 5.59/6 and the maximum grade for the master thesis.], [Sep. 21 -- Aug. 2024], Lausanne) #entry([Summer school "Science and Policy – How to bridge the gap?"], [5 days on science for policy, science communication, open science and the Swiss policy landscape.], [July 2023], loc([Interlaken], "CH"), star: true ) #entry([ARENA, Alignment Research Engineer Accelerator], [6 weeks intensive training on interpretability, RL and training at scale.], [May -- June 2023], London, url: [#link("https://arena.education/")[`arena.education`]] ) // #entry([Semester research projects in Mathematical Logic and Game Theory], // [Guided research under <NAME>'s supervision\ // #emoji-svg("page") "#link( // "https://gitlab.com/ddorn/ba6/-/jobs/artifacts/master/raw/projet/projet.pdf?job=pdf", // )[ #emph[Infinite games in the Baire space] ]", Bachelor thesis, Spring 2021\ // #emoji-svg("page") "#link( // "https://github.com/ddorn/safra/blob/master/out/projet.pdf", // )[ #emph[Between decidable logics: $omega$-automata and infinite games]]", Master’s semester project, Spring 2022 // ], // [2021 -- 2022], // Lausanne) #entry([Bachelor's in Mathematics at EPFL], [Passed with a 5.42/6 average and top 5/100 of my year.], [Sep. 18 -- July 2021], Lausanne) = Volunteering #entry([Founder and President of the Safe AI Lausanne student association], [Led a team of 8 through the design of a strategy, resulting in a 10-day winter school on systemic AI risks, 3 talks and 2 panel discussions with a total of 10 experts, and a talk for TEDxEcublens. ], [Sep. 22 -- March 24], Lausanne, star: true ) // #entry([Vice-president, then advisor for Effective Altruism Lausanne], // [Association aiming to find the best ways to help others and put them into practice], // [2022 -- 2023], // Lausanne) // #entry([Co-founder of Chocopoly, the hot chocolate association of EPFL], // [Established 19 collaborations with other associations and served 1288L of hot chocolate.], // [2021 -- 2023], // Lausanne) #entry([President of CQFD, the mathematics students' association of EPFL], [Management of a team of 14 people, dialogue with the direction of the faculty.], [Sep. 20 -- Sep. 21], Lausanne) // #entry([National organisation committee of the french tournament of young mathematicians, TFJM#super("2")], // [Coordination of 9 events for 600 participants, communication, and creation of a new online infrastructure.], // [Sep. 20 -- May 21], // loc([Many places], "FR")) = Awards & Extra #entry([1st place in the hackathon the "Digital Services Act RAG Race"], [Creation of a Q&A system for questions on the DSA based on open-source models, in a team of 3, during a 7 hours hackathon organised by the PEReN and the European Commission.], [February 2024], Bruxelles, star: true ) #entry([Game development, tool design, websites], [Creation of 10+ small games under strong time constraints and pressure for game jams, a 2D EsoLang (#link("https://github.com/aaronjanse/asciidots")[Asciidots]), multiple software tools and websites. Teamwork and sprints. ], [2014 -- present], [#loc("Earth", "earth")], url: [#link("https://ddorn.fr/showcase")[`ddorn.fr/showcase`]] ) #let skill(name, time, details: none) = [ *#name* #if details != none [(#details)] #box(width: 1fr, // stroke: (bottom: accent-strong + 0.5pt) text(fill: accent-strong, repeat([.])) ) _#time _\ ] #v(0.2cm) #grid(columns: (3fr, 2fr), gutter: 0.5cm)[ = Hard Skills #skill([#if use-stars {emoji-svg("star")} Python], [6000h], details: [pytorch, huggingface, streamlit, click, mypy, pytest…]) #skill([JavaScript / CSS / HTML], [500h], details: [VueJS, TailwindCSS]) #skill([Rust, C++, Scala, LaTeX], [300h each]) #skill([System Administration], [200h], details: [Git, Docker, Bash, remote machines...]) ][ = Soft Skills - Training in Non-Violent Communication - Public speaking - Native in French (C2) - Fluent in English (C1) ] #show: "" - *Programming* Main hobby for the 10 last years. Many projects can be seen at #link("https://ddorn.fr/showcase")[`ddorn.fr/showcase`] - *Python (6000h)* ~~ Some of the modules I enjoyed using in more than 2 projects each include: #{ let modules = "asyncio, click, einops, fastAPI, flask, jaxtyping, joblib, huggingface, kivy, matplotlib, moderngl, mypy, numba, numpy, pillow, plotly, poetry, pre-commit, pygame, pytest, pytorch, stable_baselines3, streamlit, transformer_lens, typeguard, typer".split(", ").sorted() for name in modules [ #raw(name), ] } - *Rust (300h)*, #strong[Scala (200h)] and #strong[C/C++ (300h)] - *JavaScript / CSS / HTML (500h)* ~~ Also using, VueJS, TailwindCSS, typescript - *Other languages* ~~ LaTeX (200h), Typst, 6502/NES assembly, Haskell, Matlab, Lean - *Tools* ~~ Vim, Jetbrains IDEs, VS Code, git, Docker, slurm, runAI, inkscape, OBS, Google Suite, ArchLinux (i3wm/sway)… - *Soft skills:* Non-violent communication - #strong[Languages:] French (native), English (fluent)//, Italian & German (basics, willing to learn more)
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/数理逻辑/main.typ
typst
#import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark #import "../template.typ": * #show: note.with( title: "数理逻辑", author: "YHTQ", date: datetime.today().display(), logo: none, withChapterNewPage: true ) #let not1 = math.tilde #let True = $T$ #let False = $F$ #let infer = $->$ #let equiv = $<->$ #let calA = $cal(A)$ #let calB = $cal(B)$ #let calC = $cal(C)$ #let calP = $cal(P)$ #let calL = $cal(L)$ #let Interpret = $cal(I)$ #let subst(AA, PP, pp) = $AA_( PP \/ pp )$ #let deduction(body) = { set enum(numbering: "(1)") set align(left) body } #let indent(num) = h((2em * num)) #let pattern-match(body) = { set list(marker: ([|])) align(center, body) } #let align_left(body) = { set align(left) body } #let fA = $ "fromAxiom"$ #let fS = $"fromFormulaSet"$ #let deduction-theorem(a, b) = $ "deduction theorem" #a space #b$ #let transitivity(a, b) = $ "transitivity" #a space #b$ #let MP(a, b) = $ "MP" #a space #b$ #let MPb(a, b) = $ "MP" (#a) (#b)$ #let deduction-theorem-b(a, b) = $ "deduction theorem" (#a) (#b)$ #let transitivity-b(a, b) = $ "transitivity" (#a) (#b)$ #let L1 = $"L1"$ #let L2 = $"L2"$ #let L3 = $"L3"$ #let idL = $"引理" calA -> calA$ #let language = $cal(L)$ = 前言 - 主要参考书:Introduction to Mathematical Logic - 成绩:平时 30%,期末 70% - 作业每周周一前交到教学网,不能迟交 - Office Time: 周一中午后上课前,智华楼 311 == 主要内容 命题逻辑 $->$ 一阶逻辑(模型论,证明论) $->$ 数学基础(元数学),不完全性定理,计算机科学基础(选讲,不讲证明,不考察) = 命题逻辑 == 语法与语义 命题逻辑是一种符号语言(或称形式语言),以此作为基本的推理形式。 #definition[][ 称 $p$ 为命题,若 $p$ 有明确的真假值。命题逻辑是二值逻辑,即命题只有真和假两种取值,分别记为 #True, #False ] #definition[连接符][ 命题逻辑采用以下几种符号: - 非:$not1 p$ - 与:$p and q$ - 或:$p or q$ - 蕴含:$p infer q$ - 等价:$p equiv q$ ] #example[说谎者悖论][ "这个句子是假的"不是命题,称之为悖论(paradox),它是一种导致自相矛盾的陈述。这个悖论运用了“自指”,也即在命题中谈论自身。但并非所有悖论都运用自指。 说谎者悖论即使在三值逻辑(真,假,不真不假)中也是悖论 ] #definition[命题形式][ 给定一系列变元,称: - 一个变元为命题形式 - 若 $calA, calB$ 是命题形式,则 $not1 calA, calA and calB, calA or calB, calA infer calB, calA equiv calB$ 也是命题形式 ]<proposition-form> #remark[][ 注意括号并非命题逻辑中的必需元素,它只是为了将一个命题形式用字母和符号表达时,避免歧义引进的 ] #definition[][ 对一个命题形式: - 如果任取变元的所有赋值,该命题形式均为真,则称该命题形式为重言式/永真式 - 如果任取变元的所有赋值,该命题形式均为假,则称该命题形式为矛盾式 - 否则称该命题形式为可满足式 判断一个命题形式是否可可满足式是一个 NP 问题,该问题称为 SAT 问题 ] #definition[][ - 若 $calA -> calB$ 是重言式,则称 $calA$ 蕴含 $calB$,记作 $calA => calB$ - 若 $calA <-> calB$ 是重言式,则称 $calA$ 重言等价于 $calB$,记作 $calA <=> calB$ 。显然重言等价当且仅当 $calA, calB$ 有相同的真值表 ] == 操作与替换 #proposition[][ 设 $calA, calB$ 都是命题形式,若 $calA$ 是重言式且 $calA => calB$,则 $calB$ 是重言式 ] #proof[ 用反证法,如若不然,则将存在一个赋值使得 $calB$ 为假,而 $calA$ 为真,这与 $calA -> calB$ 是重言式矛盾 ] #remark[][ 这里的“反证法”是一种逻辑演算之外的证明方法。因为之前定义的赋值存在于元语言中,因此反证法也是在元语言中反证。 ] #definition[][ 设 $calA$ 是包含变元 $p_1, p_2, ..., p_n$ 的命题形式,$calP_i, 1<=i<=n$ 是任意的命题形式,则称将 $p_i$ 替换为 $calP_i$ 的操作称为替换,记作 $subst(calA, p_i, calP_i)$ ] #definition[受限命题形式][ 在 @proposition-form 中,若只用 $not1, and, or$ 作为连接符,则称其为受限命题形式 ] #theorem[][ 设 $calA$ 是受限命题形式,定义 $A^*$ 如下: - $A^* (p) = not1 p$ - $A^* (calA and calB) = A^*(calA) or A^*(calB)$ - $A^* (calA or calB) = A^*(calA) and A^*(calB)$ - $A^* (not1 calA) = not1 A^*(calA)$ 则 $A^*(calA) <=> not1 calA$ ] #proof[ 使用结构归纳法,逐个验证即可 ] #theorem[常用命题逻辑定理][ 以下都是重言式: - $not1 (A and not1 A)$ - $A or not1 A$ - $A <-> not1 not1 A$ - $A <-> A or A <-> A and A$ - $(A and B) -> C <-> A -> (B -> C)$ - $A -> B <-> not1 B -> A$ - $and_(i=1)^n (not1 A_i) <-> not1 or_(i=1)^n A_i$ - $or_(i=1)^n (not1 A_i) <-> not1 and_(i=1)^n A_i$ - $A and B and C <-> A and (B and C)$ - $A or B or C <-> A or (B or C)$ - $A and (B or C) <-> (A and B) or (A and C)$ - $A or (B and C) <-> (A or B) and (A or C)$ ] == 范式 问题:给定真值表,可否构造一个命题形式满足此真值表?本节内容假设研究一个包含变元 $p_1, p_2, ..., p_n$ 的命题形式 $calA$,并且已知 $calA$ 的真值表,$v_(p_i)$ 是其真值 #definition[基本合取式/短语/子句][ 设 ${(q, v)} subset {p_i}$ 是一些变元及其真值取值,则定义 $c((q, v) union Q) = $ - $q and c(Q)$ 若 $v = T$ - $not1 q and c(Q)$ 若 $v = F$ ] #definition[文字][ 一个变元或其否定称为一个文字 ] #definition[][ 称: - $and or Q$ 为合取范式 - $or and Q$ 为析取范式 其中 $Q$ 是文字 ] #theorem[][ 对于任意的真值表,都存在受限命题形式 $calA$ 使得其真值表与给定真值表相同 ] #proof[ #let value = "value" 设真值函数 $v: {T, F}^n -> {T, F}$,定义: $ c_value := (not1 v(value)) "xor" c({(p_i, value[i]) | i <= n}) "for value in" {T, F}^n $ 则 $or_value c_value$ 就是我们要找的受限命题形式 ] #remark[][ 上面找到的受限命题形式称为真值函数的范式 ] #definition[][ 设 $S$ 是连接符(原则上,每个真值函数都可定义连接符)的集合,且对于任何真值函数 $v$,都存在受限命题形式 $calA$ 使得其真值表与给定真值表相同,则称 $S$ 是完备的 ] #corollary[][ ${not1, and}, {not1, or}, {not1, ->}$ 都是完备的。在基本的连接符之中,除这三对之外,其他任何一对连接符均不完备。 ] #proof[ 上面的范式给出了只含 $not1, and, or$ 的命题形式,采用如下翻译方法: - $t(p) = p$ - $t(not1 calA) = not1 t(calA)$ - $t(calA and calB) = not1 (not1 t(calA) or not1 t(calB))$ - $t(calA or calB) = t(calA) or t(calB)$ 不难验证 $t$ 将任意命题形式变为只含 $not1, or$ 的命题形式,且不改变真值函数。其他的是类似的。 ] #theorem[][ 定义: $ calA | calB := not1 (calA and calB)\ calA arrow.b calB := not1 (calA or calB) $ 则可以验证 ${|}, {arrow.b}$ 都是完备集 ] == 推理形式 #definition[推理形式][ 推理形式是指命题形式的有限序列,其中最后一个命题为结论,其他命题为前提。 - 称一个推理形式为有效的,若当前提真值均为真时,结论也一定为真 - 反之,称之为无效的 ] #example[典型的有效推理形式][ - $calA, (calA -> calB); calB$ - $not1 calB, (calA -> calB); not1 calA$ - $calA -> calB, calB -> calC; calA -> calC$ - $not1 A, A or B; B$ - $A -> not1 A; not1 A$ - $A -> (B and not1 B); not1 A$ - $A, B; A and B$ - $A, B; A or B$ - $A and B; A$ - $A and B; B$ ] #definition[模型][ 对于任何命题形式 $calA$,若 $calA$ 的真值表中 $v(calA) = T$,则称 $v$ 是 $calA$ 的一个模型,记作 $v models calA$ 若任意真值指派都是 $calA$ 的模型,则称 $calA$ 是有效的,记作 $models calA$ ] #definition[蕴含][ 称 $calA$ 蕴含 $calB$,记作 $calA models calB$,若任何 $calA$ 的模型都是 $calB$ 的模型 ] == 形式系统 === 语法 #definition[形式(演绎)系统][ 形式系统指使用符号和规则来推导命题的系统,其中包含以下几个要素: - 形式语言:用来表达命题的符号 + 一个字符表 + 由字符表中的字符组成的有限字符串的一个子集,其中的字符串称为 well-formed formula - 公理:一组 well-formed formula - 有限个推理规则集 ] #example[][ 命题逻辑是形式系统,其中: - 字符集是原子公式集(至多可数)以及 $~, ->, (, )$(括号作为技术性符号,未必需要) - 公式集是所有的命题形式 - 公理由一组公理模式(schema)来刻画,对于任何公式 $calA_1, calA_2, calA_3$ 都有: + $calA_1 -> (calA_2 -> calA_1)$ + $(calA_1 -> (calA_2 -> calA_3)) -> ((calA_1 -> calA_2) -> (calA_1 -> calA_3))$ + $(not1 calA_1 -> not1 calA_2) -> (calA_2 -> calA_1)$ - 推理规则包括: + $calA, (calA -> calB) => calA$ #align(end, [分离规则(MP)]) 当然命题逻辑定义为形式系统的方式并不唯一 ] #remark[][ $calA$ 等并非 $calL_0$ 中语言,而是元语言中符号。在计算机系统中,会使用 quasi-quote 来将元语言中的符号转化为 $calL_0$ 中的符号,例如 $`calA`$ ,该课程中省略该过程。 ] 公理系统是一种证明论(proof theory),证明论中当然还有其他与公理系统等价的系统。Euclid 的几何学是一个公理系统,但是在 19 世纪被发现是不完备的。 #definition[证明][ #calL 中的一个证明是指一个公式序列 $calA_i, i = 1, 2, ..., n$,其中要么 $calA_i$ 是公理,要么可以从之前的公式通过推理规则推导出来。$calA_n$ 称为一个定理,亦称 $calA_n$ 可证。 ] #definition[演绎][ 令 $Gamma$ 是 $L$ 中的公式集,若有一个公式序列 $calA_i, i = 1, 2, ..., n$,其中要么 $calA_i in L$,要么 $calA_i$ 是公理,要么可以从之前的公式通过推理规则推导出来。$calA_n$ 称为从 $Gamma$ 可演绎的,记作 $Gamma tack calA_n$。特别的,若 $calA$ 是定理,则有 $emptyset tack calA$ 也记作 $tack calA$ ] #theorem[演绎定理][ 若 $Gamma union {calA} tack calB$,则 $Gamma tack calA -> calB$ ] #proof[ 使用结构归纳法,对 $Gamma union {calA} tack calB$ 的一个演绎 $L$ 做归纳:\ #pattern-match[ match L with - #align_left[#fA =>(此时 $calB$ 是公理),考虑:] #deduction[ + $calB := fA$ + $calB -> (calA -> calB) := fA$ + $calA -> calB := #MPb(1, 2)$ ] - #align_left[#fS => ] + #align_left[若 $B in Gamma$,则 $Gamma tack calA -> calB$ 显然] + #align_left[若 $B = A$,只需使用 $tack calA -> calA$ 即可] - #align_left[#MP("a", "b") => (此时 $b = a -> calB$)] 由归纳法,有 $Gamma tack calA -> a, Gamma tack calA -> (a -> calB)$,只需证明: $ {calA -> a, calA -> (a -> calB)} tack calA -> calB $ 来自于: #deduction[ + $calA -> a := fS$ + $calA -> (a -> calB) := fS$ + $(calA -> (a -> calB)) -> ((calA -> a) -> (calA -> calB)) := fA$ + #indent(1) $(calA -> a) -> (calA -> calB) := #MPb(3, 2)$ + #indent(2) $calA -> calB := #MPb(4, 1)$ ] ] ] #theorem[演绎定理2][ 若 $Gamma tack calA -> calB$,则 $Gamma union {calA} tack calB$ ] #example[假言三段论 HS/传递性][ 证明: $ calA -> calB, calB -> calC tack calA -> calC $ ] #proof[ 容易证明 $calA, calA -> calB, calB -> calC tack calC$,应用演绎定理即可 ] #definition[][ 设 $Gamma$ 是公式集: - 若存在 $calA$ 使得 $Gamma tack calA, Gamma tack not1 calA$,则称 $Gamma$ 是不一致的,否则是一致的 - 若公式 $calA$ 满足 $Gamma tack.not calA, Gamma tack.not not1 calA$,则称 $calA$ 与 $Gamma$ 独立 - 若 $calA, not1 calA in Gamma$ 则 $Gamma tack$ 任何公式,则称形式系统平凡 - 若 $Gamma' subset Gamma, Gamma' tack calA$,则 $Gamma tack calA$ ,则称形式系统单调 ] #proposition[][ 公式集不一致当且仅当对于任意公式 $calA$,都有 $Gamma tack calA$ ] #definition[极大一致][ - 称公式集 $Gamma$ 是极大一致(MC)的,如果它是极大的一致集。 - 称 $Gamma' subset Gamma$ 是极大一致子集,如果 $Gamma'$ 是 $Gamma$ 中极大的一致子集 ] #theorem[][ 若 $Gamma$ 是极大一致的,则对于任意 $calA$ 均有 $Gamma tack calA$ 或 $Gamma tack not1 calA$ ] #example[极大一致推理][ 记 $Gamma tack_"MCS" calA$ ,如果对于任何极大一致子集 $Gamma'$,都有 $Gamma' tack calA$,该推理既不平凡也不单调 ] === 语义 这里,我们重新形式地引入之前的真值指派思想。它描述了命题逻辑的语义。 #definition[赋值][ 称一个从 $L$ 的公式到 ${T, F}$ 的函数 $v$ 为一个赋值,如果: $ v(not1 calA) = not1 v(calA)\ v(calA -> calB) = T "if and only if" v(calA) = F "or" v(calB) = T $ ] #definition[模型][ 令 $v$ 是 $L$ 的一个赋值,若 $v(calA) = T$,则称 $v$ 是 $calA$ 的一个模型,或 $v$ 使 $calA$ 成真,亦称 $v$ 满足 $calA$,记作 $v models calA$ ] #definition[重言式][ 若 $v models calA$ 对任意赋值 $v$ 都成立,则称 $calA$ 是重言式,记作 $models calA$ ] == 完全性定理 前面的形式系统使用的是证明论的思想,使用 $tack$,是指纯粹语法的推断。而之前的章节从真值指派看待命题逻辑,使用的是模型论的思想,使用 $models$,指通过语义进行的分析。完全性定理即是说,这两种思想是等价的。 #theorem[命题逻辑的可靠性(soundness)][ 若 $ tack calA$,则 $ models calA$ ]<proposition-soundness> #proof[ 设 $ tack calA$ 的推理序列为 $L$ #pattern-match[ match L with - #align_left[#fA => 逐一验证公理都是重言式即可] - #align_left[#MP("a", "b") => 此时 $b = a -> calB$] 由归纳法,$a, b$ 都是重言式,不难验证 $b space a : calB$ 当然也是重言式 ] ] #theorem[命题逻辑的一致性][ $L$ 是一致的 ] #proof[ 假设 $L$ 不一致,则存在 $L$ 的公式 $calA$ 使得 $calA, not1 calA$ 都是定理,由 @proposition-soundness 可知 $models calA, models not1 calA$,这与赋值的定义矛盾。 ] #definition[扩充][ - $L$ 的一个扩充是指修改或扩大 $L$ 的公理组,使得 $L$ 中的每一个公理仍然是公式得到的形式系统。 - 称 $L$ 的一个扩充是一致的,若不存在 $L$ 的公式 $calA$ 使得 $calA, not1 calA$ 都是这个扩充的定理。显然扩充是一致的当且仅当不是所有的公式都是定理。 ] #proposition[][ 设 $L^*$ 是一个扩充,$calA$ 不是 $L^*$ 中定理,则 $L^*$ 中增加 $not1 calA$ 得到的形式系统 $L^(**)$ 也是一致的。 ]<consistency-extension> #definition[][ 称 $L$ 的一个扩充是完全的,如果每个公式 $calA$ ,都满足 $calA, not1 calA$ 其中至少有一个是定理。显然一致的完全扩充是一个极大的一致扩充。 ] #theorem[][ 令 $L^*$ 是一致扩充,则存在 $L^*$ 的一致完全扩充。 ] #proof[ 枚举所有公式 $calA_1, ..., calA_n, ...$,记: - $A_0$ 是 $L^*$ 的公理 - 将 $L^*$ 的公理扩充至 $A_i$ 后: - 若 $calA_i$ 或 $not1 calA_i$ 是定理,则 $A_(i + 1) = A_i$ - 否则,$A_(i + 1) = A_i union {not1 calA_i}$ 由 @consistency-extension,每个 $A_i$ 产生的扩充都是一致的。取 $union.big A_i$ 作为新的公理集,则这个扩充是: - 一致的,既然每个定理都只能用到有限个公理,因此若 $calA, not1 calA$ 都是定理,它们只能用到有限个公理,因此存在某个 $A_i$ 使得 $A_i tack calA, not1 calA$,矛盾 - 完全的,显然每个公式都满足 $calA, not1 calA$ 其中至少有一个是定理 ] #proposition[][ 若 $L^*$ 是 $L$ 的一个一致扩充,则存在一个赋值使得 $L^*$ 的每个定理取值均为 $T$ ]<consistency-extension-value> #proof[ 设 $L'$ 是 $L^*$ 的一致完全扩充,定义赋值如下: $ v(calA) = T "if and only if" tack_(L^') calA $ $L'$ 的一致完全性保证了定义是合理的。 为了证明它是赋值,只需证明: $ v(calA -> calB) = T "if and only if" v(calA) = F "or" v(calB) = T $ 简单按定义验证即可。这个赋值就满足题目要求。 ] #theorem[命题逻辑的完全性(completeness)][ 若 $Gamma models calA$,则 $Gamma tack calA$ ] #proof[ 设 $calA$ 是重言式,若其不是定理,则由 @consistency-extension 将 $not1 calA$ 作为公理进行扩充得到一致系统,由 @consistency-extension-value 存在赋值 $v$ 使得 $L^*$ 中每个定理取值均为 $T$,特别的 $v(not1 calA) = T$,然而由重言式定义 $v(calA) = T$,矛盾。 ] #theorem[可判定性定理][ $L$ 中的公式是否是定理是可判定的 ] #proof[ 由完备性定理,只需枚举所有赋值即可。 ] == 直觉主义逻辑 #definition[直觉主义逻辑][ 直觉主义逻辑由如下资料定义: - 字符集:公式集及 ${top(真), bot(假), and, or, ->}$ - 公理模式: #enum(numbering: (nums => "(I" + str(nums) + ")") )[$calA -> (calB -> calA)$][ $(calA -> (calB -> calC)) -> ((calA -> calB) -> (calA -> calC))$ ][ $(calA and calB) -> calA$ ][ $(calA and calB) -> calB$ ][ $calA -> (calB -> (calA and calB))$ ][ $calA -> (calA or calB)$ ][ $calB -> (calA or calB)$ ][ $(calA -> calC) -> ((calB -> calC) -> ((calA or calB) -> calC))$ ][ $(calA -> calC) -> ((calB -> calC) -> ((calB or calA) -> calC))$ ][ $bot -> calA$ ] - 推理规则:MP ] 主流数学仍是基于经典逻辑的,但是其中有些分支也应用了直觉主义逻辑。 = 一阶逻辑:模型论 == 谓词和量词 一阶逻辑就是在命题逻辑中将基本命题细分为: - 谓词结构,形如 $A(x)$,表示对于任何变元(主词),谓词 $A$,产生基本命题 $A(x)$ - 任意结构,形如 $forall x, A(x)$,表示对于任何 $x$,$A(x)$ 都成立 - 存在结构,形如 $exists x, A(x)$,表示存在一个 $x$ 使得 $A(x)$ 成立 #definition[][ 被量词限定的变元称为自由变元,否则称为约束变元。含有自由变元的项往往无法确定真值。 ] == 一阶语言 本节给出一阶语言(记为 #language)的形式定义 #definition[一阶语言的字符表][ 一阶语言的字符表包括: - 至多可数的变元集合 $x_1, x_2, ...$ - 至多可数的常元集合 $a_1, a_2, ...$ - 逻辑符号 $not1, infer$ - 量词 $forall$ - 谓词符 $A_m^n$,表示第 $m$ 个谓词符,有 $n$ 个参数 - 函项符号 $f_m^n$,表示第 $m$ 个函项符号,有 $n$ 个参数 ] #remark[][ 零元的谓词符/函项符事实上是常元/常命题,方便期间我们仍然保留额外定义的常元,但不额外定义常命题。 ] #definition[][ 称 $language^+$ 为 $language$ 的一个扩展,如果它拓展了 $language$ 的变元集合/常元集合/谓词符/函项符 ] #definition[公式与项][ 一阶语言中良好的表达式分为公式与项,满足文法规则: ``` term ::= x_i | a_i | f_m^n (term_1, ..., term_n) formula ::= A_m^n (term_1, ..., term_n) | not formula | formula -> formula | forall x_i, formula ``` 特别的: - 只由常元和函项符构成的项称为闭项,否则称为开项。显然将一些闭项加入常元集可以得到拓展,称为闭项拓展。只用常元的拓展称为常元拓展。 - 不含量词,变元的公式称为命题公式,也就是命题逻辑语言 $language_0$ 中的公式 ] #lemma[][ #language 中的公式集和项集都是至多可数的 ] #definition[][ 在公式 $forall x (calA)$ 中,称 $calA$ 是 $x$ 的辖域。$calA$ 中所有 $x$ 的出现以及 $forall x$ 中 $x$ 的出现称为约束的出现;变元在辖域之外的出现称为自由出现。 ] #example[][ $forall x_1(A(x_1, x_2) -> forall x_2 (B(x_2)))$ 中,$x_1$ 约束出现两次,$x_2$ 约束出现一次,自由出现一次 ] #definition[替换][ 设 $s, t$ 是项,将 $s$ 中所有(自由出现的) $x_i$ 替换为 $t$ 的操作记作 $s(x_i \/ t)$ ] #remark[][ 我们不对约束变元进行替换。尽管如此,替换仍是可能产生歧义的,例如: $ forall x_1 (x_2) $ 用 $x_1$ 替换 $x_2$ 会导致自由变元 $x_1$ 和约束变元 $x_1$ 产生混淆,这是非法的。 ] #definition[][ 称 $t$ 在 $calA$ 中对 $x_i$ 是自由的,如果对于任意在 $t$ 中出现的变元 $x$, $calA$ 中所有形如 $forall x(calB)$ 的子公式均满足 $x_i$ 不在 $calB$ 中自由出现。若 $x_i$ 不在 $calA$ 中自由出现,则 $t$ 总对 $x_i$ 自由。 如此,我们使用 $t$ 替换 $x_i$ 的所有自由出现便不会产生歧义。 ] 直觉上来说,约束变元的“名字”应当不影响公式的结构。具体来说,我们定义: #definition[换名替换][ 若 $x_j$ 是不在 $calA$ 中自由出现的,对 $x_i$ 自由的变元,则 $forall x_j calA(x_i \/ x_j)$ 只是在 $forall x_i calA$ 中将所有 $x_i$ 换为 $x_j$ 的结果。 ] #definition[相似公式][ 设 $x_i, x_j$ 是不同变元,称 $calA(x_i)$ 和 $calA(x_j)$ 是相似的,如果 $x_j$ 在 $calA(x_i)$ 中对 $x_i$ 自由且 $calA(x_i)$ 中没有 $x_j$ 的自由出现。 ] #proposition[][ 相似是对称的,也即若 $calA(x_i)$ 和 $calA(x_j)$ 相似,则 $calA(x_j)$ 和 $calA(x_i)$ 相似 ] #definition[二阶语言/高阶语言][ 一阶逻辑中的一阶是指量词只能作用于变元,若量词可以作用于项/谓词,则称为二阶逻辑。二阶逻辑与一阶逻辑有根本区别,例如数学归纳法: $ forall P((P(0) and forall n("is_N"(n) -> P(n) -> P(n + 1))) -> forall n("is_N"(n) -> P(n))) $ 就是二阶公式 ] == 解释:一阶语言的语义 在一阶逻辑中,由于变元/函项的存在,我们不可能一次性规定所有情况下的准确语义。抽象而言: - 世界中应当有一些对象 - 对于谓词符,存在一些对象满足这个谓词,而另一些不满足 - 对于函项符,它将一些对象映射为另一个对象 这应该能准确的描述一阶逻辑中的非逻辑符号的解释。这被称为 FOL 假设。 具体而言,我们可以依赖于集合论建立一阶语言的模型: #definition[Tarski][ 一个一阶语言 $language$ 的解释 $Interpret$ 包括: - 一个非空论域 $D_I$,它是一个非空集合(通常不考虑空论域的问题) - 一个个体集 ${overline(a_i)}$,它是可数的,构成对常元的解释 - 一个函项符集 ${overline(f)_i^n}$,其中: $ overline(f)_i^n: D_I^n -> D_I $ 构成对函项符的解释 - 一个关系集 $overline(A_i)$,其中: $ A_i^n subset D_I^n $ 构成对谓词符的解释 - 对于量词 $forall x(P(x))$,解释为对于所有 $d in D_I$,$P(d)$ 都成立。(更进一步,对于二阶语言的量词,可以解释为论域中子集构成的集合) ] #remark[][ Tarski 解释必须基于集合论,因此从根本上无法解决集合论的问题(例如罗素悖论)。只有给定一个解释 $I$,才能对一阶逻辑中的公式讨论真假值,否则是无意义的。 为了方便,假设 $language$ 中的常元为 $a_1, ..., a_i, ...$,我们就可以记: $ D_I = {a_i} $ (如果常元不足,做常元扩展即可)\ 该记法成立是因为 $D_I$ 是元语言中的集合,其中元素与记法无关,因此不妨就用 #language 中的常元符号。 ] #definition[赋值][ 令 #Interpret 是一个论域为 $D_I$ 的解释,称一个 #language 的项集到 $D_I$ 的映射 $v$ 是一个赋值,如果: $ v(a_i) = overline(a_i)\ v(f(a_1, ..., a_n)) = overline(f)(v(a_1), ..., v(a_n))\ $ ] #remark[][ 注意上面的赋值并没有要求对变元的行为。事实上,一个变元也是一个项,因此的确需要确定变元的赋值。同时,由项的构造语法,一组确定的变元赋值便可以唯一确定一个赋值。 ] #definition[$i-$ 等值][ 称两个赋值 $v, w$ 是 $i-$ 等值的,如果对于所有 $x_j != x_i$,$v(x_j) = w(x_j)$,也就是两个赋值在除了 $x_i$ 之外的所有变元上是相同的。 ] #definition[可满足性][ 定义 $calA$ 是 #language 中公式,#Interpret 是一个解释,$tilde(v)$ 是一个变元赋值,称 $calA$ 在 $I$ 中对 $v$ 成立,记作 $Interpret, v models calA[tilde(v)]$ 或者简写为 $Interpret, v models calA, v models calA$,如果: - 若 $calA$ 是原子 $A_m^n (a_1, ..., a_n)$,则定义为 $overline(A_m^n)(v(a_1), ..., v(a_n)) = T$ - 若 $calA$ 是 $not1 calB$,则定义为 $not1 Interpret, v models calB$ - 若 $calA$ 是 $calB -> calC$,则定义为 $Interpret, v models not1 calB$ 或者 $Interpret, v models calC$ - 若 $calA$ 是 $forall x_i s(calB)$,则定义为对于所有与 $v space $ $i-$等值的赋值 $w$,均有 $Interpret, w models calB$,这等价于对于任意 $d_i in D_I$,均有 $Interpret, v models calB(x_i \/ d_i)$ ] #theorem[][ 设 $v$ 是一个赋值,$v'$ 是另一个赋值,它们 $i-$ 等值,且 $v'(x_i) = v(t)$,则有对于任意项 $s$,都有: $ v(s(x_i \/ t)) = v'(s) $ ] #proof[ 归纳证明即可 ] #theorem[][ 设 $calA(x_i)$ 是公式,$t$ 是项,且在 $calA(x_i)$ 中对 $x_i$ 自由。设 $v$ 是一个赋值,$v'$ 是另一个赋值,它们 $i-$ 等值,且 $v'(x_i) = v(t)$,则我们有: $ v models calA(t) <=> v' models calA(x_i) $ ] #proof[ $ &"match" calA(x_i) with\ &| A_m^n (a_1, ..., a_n) => v' models calA(x_i) &&<=> overline(A_m^n)(v'(a_1), ..., v'(a_n)) = T\ &space &&<=> overline(A_m^n)(v(a_1 (x_i \/ t)), ..., v(a_n (x_i \/ t))) = T\ &space &&<=> v models A_m^n (a_1(x_i \/ t), ..., a_n (x_i \/ t)) \ &space &&<=> v models calA(t)\ &| not1 calB(x_i) => "易证"\ &| calB(x_i) -> calC(x_i) => "易证"\ &| forall x_i calB(x_i) => "替换只替换自由变元,显然"\ &| forall x_j calB(x_i) => v' models calA(x_i) &&<=> "forall" d_i in D_I, v' models calB(x_i)(x_j \/ d_i)\ $ #lemmaLinear[][ $t$ 在 $calB(x_i)(x_j \/ d_i)$ 对 $x_i$ 自由,且 $calB(x_i)(x_j \/ d_i)(x_i \/ t) = calB(t)(x_j \/ d_i)$ ] #proof[ - 假设 $t$ 中有 $x_j$ 自由出现,那么由 $t$ 对 $x_i$ 自由的定义,$x_i$ 将不能在 $calB(x_i)$ 中出现,结论显然。 - 否则,$t$ 中无 $x_j$ 自由出现,不难验证 $t$ 在 $calB(x_i)(x_j \/ d_i)$ 对 $x_i$ 自由等价于 $t$ 在 $calB(x_i)$ 对 $x_i$ 自由,立刻由条件保证,而替换顺序的交换是容易的。 ] 由引理及归纳假设: $ &"forall" d_i in D_I, v models calB(x_i)(x_j \/ d_i)(x_i \/ t) \ &<=> "forall" d_i in D_I, v models calB(x_i)(x_j \/ d_i)(x_i \/ t) \ &<=> "forall" d_i in D_I, v models calB(t)(x_j \/ d_i)\ &<=> v models forall x_j calB(t) $ ]
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/2数字图像处理基础.typ
typst
#import "../template.typ": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #import fletcher.shapes: house, hexagon, ellipse #import "@preview/pinit:0.1.4": * #import "@preview/cetz:0.2.2" #import "/book.typ": book-page #show: book-page.with(title: "数字图像处理基础 | DIP") = 数字图像处理基础 Digital Image Fundamentals == 光和电磁波 Light and the Electromagnetic Spectrum #figure(image("../assets/2024-06-01-23-44-35.png", width: 60%), caption: "RGB 和 CMYK 颜色模型") 可以用 RGB 三原色来加性描述颜色,也可以用 CMYK 颜色模型来描述颜色,关系如下: $ mat(C;M;Y) = mat(1;1;1) - mat(R;G;B) $ K 即为黑色,是为了补充 CMY 三原色的不足而引入的。 还可以用 HSI 颜色模型来描述颜色,其中 H 为色调,S 为饱和度,I 为强度。在这种模型下,$z$轴表示光强,每个 $z$ 值切出的面可以表示为极坐标 $(r, theta)$,其中 $r$ 为饱和度,$theta$ 为色调。可以截取 RGB、CMY 六个纯色和黑白色作为正方体的顶点,这样也是 HSI 颜色模型。 #figure(image("../assets/2024-06-01-23-53-35.png"), caption: "HSI 颜色模型") == 图像感知和获取 Image Sensing and Acquisition 传感器的种类: - Single imaging sensor 单传感器,一次只能获取一个像素的信息 - 适用于精密测量和逐点扫描的场景。 - Line sensor 线阵传感器,一次可以获取一行像素的信息,用于扫描图像,成本低 - 适用于连续扫描和快速检测的场景,常用于工业和文档扫描。 - Array sensor 阵列传感器,一次可以获取多行像素的信息 - 适用于需要高分辨率和大面积成像的场景,如数码相机、医疗成像和遥感卫星。 传感器的原理:感光材料接收到经过滤镜的能量后,会产生电压的变化,进而转化为数字信号。 #figure(image("../assets/2024-06-02-00-10-10.png", width: 80%), caption: "一个图像采集过程的例子") 图像采集的建模: $ f(x,y) = i(x,y)r(x,y) $ 其中,$f(x,y)$ 为图像,$i(x,y)$ 为光照强度,$r(x,y)$ 为反射率。这个式子无法直接求解,只能通过一些方法来估计。 == 图像采样和量化 Image Sampling and Quantization #definition[*Sampling 采样*:指的是将坐标值转化为离散的像素值] #definition[*Quantization 量化*:指的是将各个像素的幅值转化为离散的灰度值] 图像大小: - 用位表示,$M times N times K$ - 用字节表示,$M times N times K times 1/8$ 图像格式:头部信息 + 数据信息 一张 $256 times 256$ 的图像至少需要 6bit 色深($64$ 级灰度,即 $2^6 = 64$),这样才能保证图像的细节不会丢失。
https://github.com/sthenic/technogram
https://raw.githubusercontent.com/sthenic/technogram/main/src/admonitions.typ
typst
MIT License
#import "common.typ": get-text-color #import "palette.typ": get-palette /* TODO: Avoid inheriting indentation w/ https://stackoverflow.com/a/78185552 */ #let admonition( header-color, body-color, header: none, symbol: none, gutter: 0pt, breakable: false, body ) = { let inset = 0.5em let cells = ( if header != none { grid.cell(fill: header-color, colspan: 2, inset: inset)[ /* We resort to a hacky solution to keep the header with the contents while still allowing the admonition box to be breakable. See comment in "descriptions.typ". */ #block(breakable: false)[ #set text(fill: get-text-color(header-color)) #grid( columns: (if symbol != none { 1.5em } else { 0pt }, 1fr), align: bottom + left, if symbol != none { text(font: "Font Awesome 6 Free Solid", symbol) }, strong(header) ) #v(3em) ] #v(-3em) ] }, grid.cell(fill: header-color)[], grid.cell(fill: body-color, inset: inset)[ #set text(fill: get-text-color(body-color)) #body ], ).filter(x => x != none) block(breakable: breakable)[ #grid( columns: (gutter, 100% - gutter), ..cells ) ] /* TODO: Wishlist: add some vertical space if a list is the last thing in the box. */ } /* A note */ #let note(..args) = context admonition( get-palette().note-header, get-palette().note-body, header: "Note", symbol: "\u{f06a}", ..args ) /* A tip */ #let tip(..args) = context admonition( get-palette().tip-header, get-palette().tip-body, header: "Tip", symbol: "\u{f06a}", ..args ) /* A callout to something important */ #let important(..args) = context admonition( get-palette().important-header, get-palette().important-body, header: "Important", symbol: "\u{f06a}", ..args ) /* A warning */ #let warning(..args) = context admonition( get-palette().warning-header, get-palette().warning-body, header: "Warning", symbol: "\u{f071}", ..args ) /* An example */ #let example(..args) = context admonition( get-palette().example-header, get-palette().example-body, header: "Example", symbol: "\u{f02d}", ..args ) /* A release */ #let release(label, ..args) = context admonition( get-palette().release-header, get-palette().release-body, header: "Release " + label, symbol: "\u{f135}", ..args ) /* A display box (without header) */ #let display(..args) = context admonition( get-palette().display-header, get-palette().display-body, header: none, gutter: 2pt, ..args )
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/barcharts.typ
typst
/* import cetz.chart // Left - Basic let data = (("A", 10), ("B", 20), ("C", 13)) group(name: "a", { chart.columnchart(size: (4, 3), data) }) // Center - Clustered let data = (("A", 10, 12, 22), ("B", 20, 1, 7), ("C", 13, 8, 9)) group(name: "b", anchor: "south-west", { anchor("default", "a.south-east") chart.columnchart(size: (4, 3), mode: "clustered", value-key: (1,2,3), data) }) // Right - Stacked let data = (("A", 10, 12, 22), ("B", 20, 1, 7), ("C", 13, 8, 9)) group(name: "c", anchor: "south-west", { anchor("default", "b.south-east") chart.columnchart(size: (4, 3), mode: "stacked", value-key: (1,2,3), data) }) #table( columns: (auto, auto, auto, auto), align: (center + horizon, center, center, center), ) */ #import "@preview/cetz:0.2.0" #let margin = 0.5in #set page(margin: 0.5in, paper: "us-letter") #{ cetz.canvas({ import cetz.draw: * import cetz.chart line((0,0), (0,3), name: "a") line((0,0), (2,0), name: "b") // Draw an angle between the two lines cetz.angle.right-angle("a.start", "a.end", "b.end", radius: 1) let data = (("A", 10), ("B", 200), ("C", 13)) let style = ( axes: ( tick: (length: 3), grid: (stroke: (dash: "dotted")), ), bar-width: 2, x-inset: 1, ) set-style(..style) chart.columnchart( ticks: 100, , bar-width: 20,, size: (3, 6), , data, bar-style: cetz.palette.gray(70), ) }) } #{ let gs = square(20pt, fill: red) place(dx: 0pt, dy: 0pt, gs) }
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/recourses-2/quiz-2-2023-web.typ
typst
#import "../template.typ": * #import "./exam-template.typ": * #show: project.with( course: "Calculus II", course_fullname: "Calculus (A) II", course_code: "821T0160", title: "Quiz #2 (Spring-Summer 2024, Wednesday)", authors: ( ( name: "memset0", email: "https://mem.ac/", id: [_<EMAIL>_], ), ), semester: "Spring-Summer 2024", date: "May 22, 2024", ) #prob[ 若函数 $f(x,y)$ 在点 $P(0,1)$ 处连续,且满足 $ f(x,y) = 5 + x - y + x^2 + 4x(y-1) + (y-1)^2 + o(x^2 + (y-1)^2). quad (x->0,y->1) $ 则下列结论中正确的是 #options( [$f'_x (0,1) = 1$], [$atpos(dif f, (0,1), "") = dx - dy$], [$f(x,y)$ 在 $(0,1)$ 处有极值], [曲面 $z=f(x,y)$ 在点 $(0,1,f(0,1))$ 处的切平面为 $z=x-y+5$], [若其他选项都没选,则选此项], ) ] #prob[ 设平面区域 $D$ 是由曲线 $y=sin pi/2 x$ 与直线 $y=1,x=-1$ 所围成,则二重积分 $int.double_D (3x^2 cos y + x^3 tan y) dif sigma=$ #options( columns: 3, $0$, $1$, $2 sin 1$, $(sin 1) / 3$, [若其他选项都没选,则选此项], ) ] #pagebreak() #prob[ 设函数 $u(x,y)$ 在有界闭区域 $D$ 上具有二阶连续偏导数,且满足 $display((diff^2 u)/(diff x diff y) != 0\, space (diff^2 u)/(diff x^2) + (diff^2 u)/(diff y^2) = 0)$,则:下列陈述正确的是 #options( [函数 $u(x,y)$ 的最大值与最小值点必在 $D$ 的内部], [函数 $u(x,y)$ 的最大值与最小值点必在 $D$ 的边界上], [函数 $u(x,y)$ 的最小值点在 $D$ 的内部,最大值点在 $D$ 的边界上], [函数 $u(x,y)$ 的最大值点在 $D$ 的内部,最小值点在 $D$ 的边界上], [若其他选项都没选,则选此项], ) ] #prob[ 已知 $D = {(x,y) | x^2 + y^2 <= 1}$,则 $int.double_D (2x^2 - 3 x y + 4y^2) dif x dif y =$ #options( columns: 3, $pi$, $2pi$, $3pi$, $3 / 2 pi$, [若其他选项都没选,则选此项], ) ] #prob[ 已知 $f(x,y)$ 在 $RR$ 上具有连续偏导数,且 $f(1,1) =1$,$f'_x (1,1) = 1$,$f'_y (1,1) = 2$,记 $phi(x) = f(x,f(x, x^2))$,则 $phi' (1) =$ #options( columns: 3, $5$, $7$, $9$, $11$, [若其他选项都没选,则选此项], ) ] #pagebreak() #prob[ 设 $f(x,y) = display(cases( display((x y)/sqrt(x^2 + y^2)quad &(x,y)!= (0,0)), 0 quad& (x,y) = (0,0) ))$,则下列陈述正确的是 #options( [函数 $f(x,y)$ 在点 $(0,0)$ 处可微], [函数 $f(x,y)$ 在点 $(0,0)$ 处偏导数存在但不可微], [函数 $f(x,y)$ 在点 $(0,0)$ 处连续且偏导数存在], [函数 $f(x,y)$ 在点 $(0,0)$ 处沿任何方向的方向导数均存在], [若其他选项都没选,则选此项], ) ] #prob[ 设函数 $z=f(x,y)$ 在 $(1,2)$ 处有一阶连续偏导数,且 $arrow(u) = (3,4)$,$arrow(v) = (4,-3)$ 的方向导数为 $display((diff f)/(diff arrow(u)) = 18)$,$display((diff f)/(diff arrow(v)) = -1)$,则曲面 $Sigma: z = f(x,y)$ 在点 $(1,2,-1)$ 处的切平面为 #options( columns: 3, $10x+15y-z-41=0$, $18+2y-z-23=0$, $15x+10y-z-36=0$, $69x+75y-25z-244=0$, [若其他选项都没选,则选此项], ) ] #prob[ 设 $D={(x,y) | 0<=x<=pi,space 0<=y<=pi}$,则:$iint.double_D sin (min{x,y}) dif x dif y =$ #options( columns: 3, $pi$, $2pi$, $3pi$, $4pi$, [若其他选项都没选,则选此项], ) ] #pagebreak() #prob[ 曲线 $C:display(cases(x^2 + y^2 + z^2 = 6, 2z = x y))$ 在点 $(1,2,1)$ 处的切线方程为 #options( $display((x-1)/5 = (y-2)/4 = (z-1)/3)$, $display((x-1)/5 = (y-2)/(-4) = (z-1)/3)$, $display(cases(x+2y+z=6,x+2y-2z-3=0))$, $display(cases(x+2y+z=6,2x-y-2z+2=0))$, [若其他选项都没选,则选此项], ) ] #prob[ 函数 $u=sqrt(x^2 + 2 y^2 + 3 z^2)$ 在点 $M (-2,1,-1)$ 处的梯度为 #options( $-2i + 2j - 3k$, $1 / 3 (-2i + 2j - 3k)$, $sqrt(17)$, $1 / 3 sqrt(17)$, [若其他选项都没选,则选此项], ) ]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/069.%20foundersatwork.html.typ
typst
foundersatwork.html Learning from Founders January 2007(Foreword to <NAME>'s Founders at Work.)Apparently sprinters reach their highest speed right out of the blocks, and spend the rest of the race slowing down. The winners slow down the least. It's that way with most startups too. The earliest phase is usually the most productive. That's when they have the really big ideas. Imagine what Apple was like when 100% of its employees were either <NAME> or <NAME>.The striking thing about this phase is that it's completely different from most people's idea of what business is like. If you looked in people's heads (or stock photo collections) for images representing "business," you'd get images of people dressed up in suits, groups sitting around conference tables looking serious, Powerpoint presentations, people producing thick reports for one another to read. Early stage startups are the exact opposite of this. And yet they're probably the most productive part of the whole economy.Why the disconnect? I think there's a general principle at work here: the less energy people expend on performance, the more they expend on appearances to compensate. More often than not the energy they expend on seeming impressive makes their actual performance worse. A few years ago I read an article in which a car magazine modified the "sports" model of some production car to get the fastest possible standing quarter mile. You know how they did it? They cut off all the crap the manufacturer had bolted onto the car to make it look fast.Business is broken the same way that car was. The effort that goes into looking productive is not merely wasted, but actually makes organizations less productive. Suits, for example. Suits do not help people to think better. I bet most executives at big companies do their best thinking when they wake up on Sunday morning and go downstairs in their bathrobe to make a cup of coffee. That's when you have ideas. Just imagine what a company would be like if people could think that well at work. People do in startups, at least some of the time. (Half the time you're in a panic because your servers are on fire, but the other half you're thinking as deeply as most people only get to sitting alone on a Sunday morning.)Ditto for most of the other differences between startups and what passes for productivity in big companies. And yet conventional ideas of professionalism have such an iron grip on our minds that even startup founders are affected by them. In our startup, when outsiders came to visit we tried hard to seem "professional." We'd clean up our offices, wear better clothes, try to arrange that a lot of people were there during conventional office hours. In fact, programming didn't get done by well-dressed people at clean desks during office hours. It got done by badly dressed people (I was notorious for programmming wearing just a towel) in offices strewn with junk at 2 in the morning. But no visitor would understand that. Not even investors, who are supposed to be able to recognize real productivity when they see it. Even we were affected by the conventional wisdom. We thought of ourselves as impostors, succeeding despite being totally unprofessional. It was as if we'd created a Formula 1 car but felt sheepish because it didn't look like a car was supposed to look.In the car world, there are at least some people who know that a high performance car looks like a Formula 1 racecar, not a sedan with giant rims and a fake spoiler bolted to the trunk. Why not in business? Probably because startups are so small. The really dramatic growth happens when a startup only has three or four people, so only three or four people see that, whereas tens of thousands see business as it's practiced by Boeing or <NAME>ris.This book can help fix that problem, by showing everyone what, till now, only a handful people got to see: what happens in the first year of a startup. This is what real productivity looks like. This is the Formula 1 racecar. It looks weird, but it goes fast.Of course, big companies won't be able to do everything these startups do. In big companies there's always going to be more politics, and less scope for individual decisions. But seeing what startups are really like will at least show other organizations what to aim for. The time may soon be coming when instead of startups trying to seem more corporate, corporations will try to seem more like startups. That would be a good thing. Japanese Translation Founders at WorkThere can't be more than a couple thousand people who know first-hand what happens in the first month of a successful startup. <NAME> got them to tell us. So despite the interview format, this is really a how-to book. It is probably the single most valuable book a startup founder could read.
https://github.com/enseignantePC/2023-24
https://raw.githubusercontent.com/enseignantePC/2023-24/master/programme.typ
typst
#set page(paper: "a4") #set align(center) #set par(justify: true, linebreaks: "optimized") #import "@preview/tablex:0.0.4": * #let titre(x) = x #titre[Physique chimie en seconde] = Programme officiel #tablex( columns: 2, align: center + horizon, colspanx( 2, fill: blue.lighten(80%), inset: 0pt, rect( inset: 7pt, stroke: 2pt, width: 100%, )[*Constitution de la matière de l’échelle macroscopique à l’échelle microscopique*], ), [Notions et contenus], [Capacités exigibles], [ Corps purs et mélanges au quotidien. Espèce chimique, corps pur mélanges homogènes et hétérogènes. chimiques, mélanges homogènes et hétérogènes. ], [Citer des exemples courants de corps purs et de mélanges d’espèces], [Identification d’espèces chimiques dans un échantillon de matière par des mesures physiques ou des tests chimiques.], [Identifier, à partir de valeurs de référence, une espèce chimique par ses températures de changement d’état, sa masse volumique ou par des tests chimiques. Citer des tests chimiques courants de présence d’eau, de dihydrogène, de dioxygène, de dioxyde de carbone.], [Composition massique d’un mélange. Composition volumique de l’air.], [ Citer la valeur de la masse volumique de l’eau liquide et la comparer à celles d’autres corps purs et mélanges. Distinguer un mélange d’un corps pur à partir de données expérimentales. Mesurer une température de changement d’état, déterminer la masse volumique d’un échantillon, réaliser une chromatographie sur couche mince, mettre en œuvre des tests chimiques, pour identifier une espèce chimique et, le cas échéant, qualifier l’échantillon de mélange. Citer la composition approchée de l’air et l’ordre de grandeur de la valeur de sa masse volumique. Établir la composition d’un échantillon à partir de données expérimentales. Mesurer des volumes et des masses pour estimer la composition de mélanges. Capacité mathématique : utiliser les pourcentages et les fractions. ], ) #tablex( columns: 2, align: center + horizon, colspanx( 2, fill: blue.lighten(80%), inset: 0pt, rect( width: 100%, inset: 7pt, stroke: 2pt, )[*Mesure et incertitudes*], ), [Notions et contenus], [Capacités exigibles], [Variabilité de la mesure d’une grandeur physique.], [ Exploiter une série de mesures indépendantes d’une grandeur physique : histogramme, moyenne et écart-type. Discuter de l’influence de l’instrument de mesure et du protocole. Évaluer qualitativement la dispersion d’une série de mesures indépendantes. Capacité numérique : Représenter l’histogramme associé à une série de mesures à l’aide d’un tableur. ], [Incertitude-type.], [Expliquer qualitativement la signification d’une incertitude-type et l’évaluer par une approche statistique.], [Écriture du résultat. Valeur de référence.], [Écrire, avec un nombre adapté de chiffres significatifs, le résultat d’une mesure. #linebreak() Comparer qualitativement un résultat à une valeur de référence.], ) - informatique simulation électronique = Constitution et transformations de la matière == Constitution de la matière de l’échelle macroscopique à l’échelle microscopique === Description et caractérisation de la matière à l’échelle macroscopique ==== Corps purs et mélanges au quotidien. - rapide et théorique - identification d'espèce chimiques : - masse volumique, test caractéristique. température de changement d'état. différencier entre des réactions chimiques à l' aide d'un des produits. - proposer une experience pour savoir si corps pur ou liquide - établir composition d'un échantillon à partir de données expérimentale + combien de sel dans cet échantillon d'eau? + faire du sérum physiologique + pâte à sel. + échantillonnage d'eau salée. Mesurer des volumes et des masses pour estimer la composition de mélanges. ==== Les solutions aqueuses, un exemple de mélange. - On donne le mode préparatoire d'une solution, en déduire volume, masse volumique, concentration, si un seuil est dépassé, le vérifier par l' experience (comment? avec une autre solution qui réagit si un seuil est dépassé?). Dissolution ET dilution === Modélisation de la matière à l’échelle microscopique ==== Du macroscopique au microscopique, de l’espèce chimique à l’entité. - Espèces moléculaires, espèces ioniques, électroneutralité de la matière au niveau macroscopique. - Entités chimiques : molécules, atomes, ions. - Le noyau de l’atome, siège de sa masse et de son identité. Numéro atomique, Élément chimique. Masse et charge électrique d’un électron, d’un proton et d’un neutron, charge électrique élémentaire, neutralité de l’atome. Histoire de la découverte de l'électron (première particule élémentaire mise en évidence): - 1895 <NAME>: Nature corpusculaire - 1896-1897 <NAME> : Rapport e/m - <NAME> donne le nom d'électron. - 1900, Becquerel montre que les rayons bêta émis par le radium sont défléchis par un champ électrique, et que leur rapport masse sur charge est le même que celui des électrons. - 1909 <NAME>, <NAME>, et Ernest Marsden: Expérience de la feuille d'or, qui prouve que l'atome est composé d'un noyau positif. - 1909 <NAME>: Mesure de $e$ avec l' expérience de la goutte d'huile. Histoire de la découverte du noyau de l'atome. BONUS: loi en carré inverse, si un générateur de particule émet aléatoirement N particules par secondes, combien de particule sont reçut sur une surface de $1"m"^2$ situé à un mètre, à deux mètre? à $L$ mètre? ==== Le cortège électronique de l’atome définit ses propriétés chimiques. - Configuration électronique, Électrons de valence, Familles chimiques. ==== Vers des entités plus stables chimiquement. - Stabilité chimique des gaz nobles et configurations électroniques associées. - Ions monoatomiques. - Molécules. - Modèle de Lewis de la liaison de valence, schéma de Lewis, doublets liants et non-liants. - Approche de l’énergie de liaison. ==== Compter les entités dans un échantillon de matière. - Nombre d’entités dans un échantillon. - Définition de la mole. - Quantité de matière dans un échantillon. == Modélisation des transformations de la matière et transfert d’énergie === Transformation physique === Transformation chimique === Transformation nucléaire = Mouvement et interactions == Décrire un mouvement ==== Système. ==== Échelles caractéristiques d’un système. ==== Référentiel et relativité du mouvement. ==== Description du mouvement d’un système par celui d’un point. ==== Position. Trajectoire d’un point. vidéo smartphone + suivi d'un point. ==== Vecteur déplacement d’un point. ==== Vecteur vitesse moyenne d'un point. ==== Vecteur vitesse d’un point. ==== Mouvement rectiligne. == Modéliser une action sur un système ==== Modélisation d’une action par une force ==== Principe des actions réciproques (troisième loi de Newton). ==== Caractéristiques d’une force. Exemples de forces : - force d’interaction gravitationnelle ; - poids ; - - force exercée par un support et par un fil. == Principe d’inertie ==== Modèle du point matériel. ==== Principe d’inertie. ==== Cas de situations d'immobilité et de mouvements rectilignes uniformes. ==== Cas de la chute libre à une dimension. = Onde et signaux Deux prisonniers sont enfermés, leurs cellules sont reliés par une fibre optique, l'un possède une lampe et l'autre un haut parleur. // une radio???? - déchiffrer chaque signaux. - répondre aux questions. - envoyer un signal à l'aide d’Arduino. (1 signal précis ) + Une Arduino en mode mot de passe. + Une Arduino en mode emission lumière + Une Arduino en mode emission son + Une Arduino en mode déchiffrage Un dispositif un signal à travers une fibre optique Un autre envoie un signal sonore. les élèves doivent créer des capteurs pour recevoir le signal puis un programme pour déchiffrer le message. binaire, signaux, Arduino, ondes. == Émission et perception d’un son ==== Émission et propagation d'un signal sonore. ==== Vitesse de propagation d’un signal sonore. ==== Signal sonore périodique, fréquence et période. Relation entre période et fréquence. ==== Perception du son : lien entre fréquence et hauteur ; lien entre forme du signal et timbre ; lien qualitatif entre amplitude, intensité sonore et niveau d’intensité sonore. Échelle de niveaux d’intensité sonore. // not dev== Vision et image== Signaux et capteurs
https://github.com/a-kkiri/HEU-Report-Typst
https://raw.githubusercontent.com/a-kkiri/HEU-Report-Typst/main/main.typ
typst
Apache License 2.0
#import "template.typ": * #show: project.with( title: "课程设计", author: "<NAME>", infos: ( (key: [课程名称:], value: "XXXX"), (key: [班#h(2em)级:], value: "xxxxxxxx"), (key: [学#h(2em)号:], value: "xxxxxxxxxx"), (key: [姓#h(2em)名:], value: "X X X"), (key: [任课教师:], value: "X X X"), ), coverTable_display: false, // 是否显示封面表格 outline_display: true, // 是否显示大纲 header_display: true, // 是否显示 header ) = 模版简介 本模板适用于编写哈尔滨工程大学课程报告,默认页边距为 2.5cm,中文使用中易宋体,英文使用 Times New Roman,字号为 12pt(小四)。 默认模板文件由以下五部分组成: #list( [main.typ 主文件], [refs.bib 参考文献], [template.typ 文档格式控制,包括一些基础的设置、函数], [fonts 字体文件夹], [figures 图片文件夹], ) = 使用说明 模版默认使用的字体包括 "SimSun(中易宋体)", "Times New Roman", "DejaVu Sans Mono",如果想要在本地使用VSCode 进行预览,可能需要安装这些字体。 如果系统中没有安装这些字体或想更换其他字体,请在 `template.typ` 中修改字体。 = 使用示例 <example> == 特殊标记 <bug1> 你可以 Typst 的语法对文本进行特殊标记,我们为如下标记设定了样式: #enum( [*突出*], [_emph 强调_], [引用 @example], [`raw text`] ) === 注意事项 由于 Typst 的语法, 如果你使用 `*本文*` 来标记突出,那么你需要在 `*` 前面加上一个空格,但这会导致你 *突出的文本* 前后附带一个空格,如果你#strong("不想要这个空格"),你可以使用 `#strong("本文")` 来代替。 == 图片 图片插入例: #figure( image("./figures/heu_logo.png", width: 60%), caption: [ 示例图片 ], )<img> == 表格 <bug2> 表格有助于数据的整理与展示。Typst 支持使用 `table` 来插入表格,详见 #link("https://typst.app/docs/reference/model/table/")[typst/docs/table]。下面是一些表格插入的示例: #figure( table( columns: (auto, auto, auto), inset: 10pt, align: horizon, table.header( [], [*Area*], [*Parameters*], ), [*Cylinder*], [$pi h (D^2 - d^2) / 4$], [ $h$: height \ $D$: outer radius \ $d$: inner radius ], [*Tetrahedron*], [$sqrt(2) / 12 a^3$], [$a$: edge length] ), caption: "示例表格" ) #figure( table( columns: 4, align: center + horizon, stroke: none, table.hline(), table.header( table.cell(rowspan: 2, [*Names*]), table.cell(colspan: 2,[*Properties*],), table.hline(stroke: 0.6pt), table.cell(rowspan: 2, [*Creators*]), [*Type*], [*Size*], ), table.hline(stroke: 0.4pt), [Machine], [Steel], [5 $"cm"^3$], [John p& Kate], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Robert], table.hline() ), caption: "示例表格" ) == 公式 Typst 可以使用 Typst 原生语法插入公式,参考 #link("https://typst.app/docs/reference/math/")[typst/docs/math]。下面是一些公式插入的示例: 首先是行内公式,例如 $integral_123^123a+b+c$ $a^2 + b^2 = c^2$。行内公式使用 `$$` 包裹,公式和两端的 `$$` 之间没有空格$$。 其次是行间公式,例如:$ integral.triple_(Omega)\(frac(diff P, diff x) + frac(diff Q, diff y) + frac(diff R, diff z)\)d v = integral.surf_(Sigma)P d y d z + Q d z d x + R d x d y $ 式(1)是高斯公式。行间公式使用 `$$` 环境包裹,公式和两端的 `$$` 之间至少有一个空格,若要显示公式编号请使用 `#equation()` 函数,如:#equation($ integral.triple_(Omega)\(frac(diff P, diff x) + frac(diff Q, diff y) + frac(diff R, diff z)\)d v = integral.surf_(Sigma)P d y d z + Q d z d x + R d x d y $) 公式内可以使用换行符 `\` 换行。若需要对齐,每行可以包含一个或多个对齐点 `&` 对其进行对齐。例如: $ sum_i b_i &= sum_i sum_(h,j != i) frac(sigma_(h j) (i), sigma_(h j)) \ &= sum_(h != j) frac(1, sigma_(h j)) sum_(i != h,j) sigma_(h j)(i) $ `&` 是对齐的位置,`&` 可以有多个,但是每行的个数要相同。 矩阵输入示例: #equation($ A = mat( a_(1 1), a_(1 2), ..., a_(1 n); a_(2 1), a_(2 2), ..., a_(2 n); dots.v, dots.v, dots.down, dots.v; a_(n 1), a_(n 2), ..., a_(n n); ) $) \ 分段函数可以使用 `case` 环境: $ f\(x\)= cases( 0 #h(1em) x text("为无理数,") , 1 #h(1em) x text("为有理数.") ) $ 假如公式里面有个别文字,需要把这部分放在 text 环境里面,即 `text[文本内容]` 。 如果公式中有个别需要加粗的字母,可以使用 `bold()` 进行加粗。如,$alpha a bold(alpha a)$。 以上仅为一些简单的公式示例,更多的公式使用方法可以查看 #link("https://typst.app/docs/reference/math/")[typst/docs/math] 另外,如果需要插入 LaTeX 公式可以使用外部包 #link("https://typst.app/universe/package/mitex")[mitex]。 == 代码 行内代码例 `main()`。 #figure( ```c #include <stdio.h> int main() { // printf() 中字符串需要引号 printf("Hello, World!"); return 0; } ```, caption: [代码块插入例] ) == 参考文献 使用 #cite(<HEU-report-typst>), 即可。 例如:此处使用参考文献 #cite(<0Isaac>),此处使用参考文献 #cite(<2016The>)。 #bibliography("ref.bib")
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap8/3_voltmeter_impact_on_measured_circuit.typ
typst
Other
#import "../../core/core.typ" === Voltmeter impact on measured circuit Every meter impacts the circuit it is measuring to some extent, just as any tire-pressure gauge changes the measured tire pressure slightly as some air is let out to operate the gauge. While some impact is inevitable, it can be minimized through good meter design. Since voltmeters are always connected in parallel with the component or components under test, any current through the voltmeter will contribute to the overall current in the tested circuit, potentially affecting the voltage being measured. A perfect voltmeter has infinite resistance, so that it draws no current from the circuit under test. However, perfect voltmeters only exist in the pages of textbooks, not in real life! Take the following voltage divider circuit as an extreme example of how a realistic voltmeter might impact the circuit its measuring: #image("static/00156.png") With no voltmeter connected to the circuit, there should be exactly 12 volts across each 250 $M Omega$ resistor in the series circuit, the two equal-value resistors dividing the total voltage (24 volts) exactly in half. However, if the voltmeter in question has a lead-to-lead resistance of 10 $M Omega$ (a common amount for a modern digital voltmeter), its resistance will create a parallel subcircuit with the lower resistor of the divider when connected: #image("static/00157.png") This effectively reduces the lower resistance from $250 M Omega$ to $9.615 M Omega$ ($250 M Omega$ and $10 M Omega$ in parallel), drastically altering voltage drops in the circuit. The lower resistor will now have far less voltage across it than before, and the upper resistor far more. #image("static/00158.png") A voltage divider with resistance values of $250 M Omega$ and $9.615 M Omega$ will divide 24 volts into portions of 23.1111 volts and 0.8889 volts, respectively. Since the voltmeter is part of that 9.615 MΩ resistance, that is what it will indicate: 0.8889 volts. Now, the voltmeter can only indicate the voltage its connected across. It has no way of "knowing" there was a potential of 12 volts dropped across the lower $250 M Omega$ resistor _before_ it was connected across it. The very act of connecting the voltmeter to the circuit makes it part of the circuit, and the voltmeter's own resistance alters the resistance ratio of the voltage divider circuit, consequently affecting the voltage being measured. Imagine using a tire pressure gauge that took so great a volume of air to operate that it would deflate any tire it was connected to. The amount of air consumed by the pressure gauge in the act of measurement is analogous to the current taken by the voltmeter movement to move the needle. The less air a pressure gauge requires to operate, the less it will deflate the tire under test. The less current drawn by a voltmeter to actuate the needle, the less it will burden the circuit under test. This effect is called _loading_, and it is present to some degree in every instance of voltmeter usage. The scenario shown here is worst-case, with a voltmeter resistance substantially lower than the resistances of the divider resistors. But there always will be some degree of loading, causing the meter to indicate less than the true voltage with no meter connected. Obviously, the higher the voltmeter resistance, the less loading of the circuit under test, and that is why an ideal voltmeter has infinite internal resistance. Voltmeters with electromechanical movements are typically given ratings in "ohms per volt" of range to designate the amount of circuit impact created by the current draw of the movement. Because such meters rely on different values of multiplier resistors to give different measurement ranges, their lead-to-lead resistances will change depending on what range they're set to. Digital voltmeters, on the other hand, often exhibit a constant resistance across their test leads regardless of range setting (but not always!), and as such are usually rated simply in ohms of input resistance, rather than "ohms per volt" sensitivity. What "ohms per volt" means is how many ohms of lead-to-lead resistance for every volt of _range setting_ on the selector switch. Let's take our example voltmeter from the last section as an example: #image("static/00154.png") On the 1000 volt scale, the total resistance is $1 M Omega (999.5 k Omega + 500 Omega)$, giving 1,000,000 $Omega$ per 1000 volts of range, or 1000 ohms per volt (1 $k Omega\/V$). This ohms-per-volt "sensitivity" rating remains constant for any range of this meter: $ 100 "volt range" (100 k Omega) / (100 V) &= 1000 Omega / V "sensitivity" \ 10 "volt range" (10 k Omega) / (10 V) &= 100 Omega / V "sensitivity" \ 1 "volt range" (1 k Omega) / (1 V) &= 10 Omega / V "sensitivity" \ $ The astute observer will notice that the ohms-per-volt rating of any meter is determined by a single factor: the full-scale current of the movement, in this case 1 mA. "Ohms per volt" is the mathematical reciprocal of "volts per ohm," which is defined by Ohm's Law as current ($I=E/R$). Consequently, the full-scale _current_ of the movement dictates the Ω/volt sensitivity of the meter, regardless of what ranges the designer equips it with through multiplier resistors. In this case, the meter movement's full-scale current rating of 1 mA gives it a voltmeter sensitivity of $1000 Omega\/V$ regardless of how we range it with multiplier resistors. To minimize the loading of a voltmeter on any circuit, the designer must seek to minimize the current draw of its movement. This can be accomplished by re-designing the movement itself for maximum sensitivity (less current required for full-scale deflection), but the tradeoff here is typically ruggedness: a more sensitive movement tends to be more fragile. Another approach is to electronically boost the current sent to the movement, so that very little current needs to be drawn from the circuit under test. This special electronic circuit is known as an _amplifier_, and the voltmeter thus constructed is an _amplified voltmeter_. #image("static/00370.png") The internal workings of an amplifier are too complex to be discussed at this point, but suffice it to say that the circuit allows the measured voltage to _control_ how much battery current is sent to the meter movement. Thus, the movement's current needs are supplied by a battery internal to the voltmeter and not by the circuit under test. The amplifier still loads the circuit under test to some degree, but generally hundreds or thousands of times less than the meter movement would by itself. Before the advent of semiconductors known as "field-effect transistors," vacuum tubes were used as amplifying devices to perform this boosting. Such _vacuum-tube voltmeters_, or _(VTVM's)_ were once very popular instruments for electronic test and measurement. Here is a photograph of a very old VTVM, with the vacuum tube exposed! #image("static/50012.jpg") Now, solid-state transistor amplifier circuits accomplish the same task in digital meter designs. While this approach (of using an amplifier to boost the measured signal current) works well, it vastly complicates the design of the meter, making it nearly impossible for the beginning electronics student to comprehend its internal workings. A final, and ingenious, solution to the problem of voltmeter loading is that of the _potentiometric_ or _null-balance_ instrument. It requires no advanced (electronic) circuitry or sensitive devices like transistors or vacuum tubes, but it does require greater technician involvement and skill. In a potentiometric instrument, a precision adjustable voltage source is compared against the measured voltage, and a sensitive device called a _null detector_ is used to indicate when the two voltages are equal. In some circuit designs, a precision _potentiometer_ is used to provide the adjustable voltage, hence the label _potentiometric_. When the voltages are equal, there will be zero current drawn from the circuit under test, and thus the measured voltage should be unaffected. It is easy to show how this works with our last example, the high-resistance voltage divider circuit: #image("static/00159.png") The "null detector" is a sensitive device capable of indicating the presence of very small voltages. If an electromechanical meter movement is used as the null detector, it will have a spring-centered needle that can deflect in either direction so as to be useful for indicating a voltage of either polarity. As the purpose of a null detector is to accurately indicate a condition of _zero_ voltage, rather than to indicate any specific (nonzero) quantity as a normal voltmeter would, the scale of the instrument used is irrelevant. Null detectors are typically designed to be as sensitive as possible in order to more precisely indicate a "null" or "balance" (zero voltage) condition. An extremely simple type of null detector is a set of audio headphones, the speakers within acting as a kind of meter movement. When a DC voltage is initially applied to a speaker, the resulting current through it will move the speaker cone and produce an audible "click." Another "click" sound will be heard when the DC source is disconnected. Building on this principle, a sensitive null detector may be made from nothing more than headphones and a momentary contact switch: #image("static/00425.png") If a set of "8 ohm" headphones are used for this purpose, its sensitivity may be greatly increased by connecting it to a device called a _transformer_. The transformer exploits principles of electromagnetism to "transform" the voltage and current levels of electrical energy pulses. In this case, the type of transformer used is a _step-down_ transformer, and it converts low-current pulses (created by closing and opening the pushbutton switch while connected to a small voltage source) into higher-current pulses to more efficiently drive the speaker cones inside the headphones. An "audio output" transformer with an impedance ratio of 1000:8 is ideal for this purpose. The transformer also increases detector sensitivity by accumulating the energy of a low-current signal in a magnetic field for sudden release into the headphone speakers when the switch is opened. Thus, it will produce louder "clicks" for detecting smaller signals: #image("static/00426.png") Connected to the potentiometric circuit as a null detector, the switch/transformer/headphone arrangement is used as such: #image("static/00424.png") The purpose of any null detector is to act like a laboratory balance scale, indicating when the two voltages are equal (absence of voltage between points 1 and 2) and nothing more. The laboratory scale balance beam doesn't actually weigh anything; rather, it simply indicates _equality_ between the unknown mass and the pile of standard (calibrated) masses. #image("static/00160.png") Likewise, the null detector simply indicates when the voltage between points 1 and 2 are equal, which (according to Kirchhoff's Voltage Law) will be when the adjustable voltage source (the battery symbol with a diagonal arrow going through it) is precisely equal in voltage to the drop across R#sub[2]. To operate this instrument, the technician would manually adjust the output of the precision voltage source until the null detector indicated exactly zero (if using audio headphones as the null detector, the technician would repeatedly press and release the pushbutton switch, listening for silence to indicate that the circuit was "balanced"), and then note the source voltage as indicated by a voltmeter connected across the precision voltage source, that indication being representative of the voltage across the lower $250 M Omega$ resistor: #image("static/00161.png") The voltmeter used to directly measure the precision source need not have an extremely high $Omega\/V$ sensitivity, because the source will supply all the current it needs to operate. So long as there is zero voltage across the null detector, there will be zero current between points 1 and 2, equating to no loading of the divider circuit under test. It is worthy to reiterate the fact that this method, properly executed, places _almost zero load_ upon the measured circuit. Ideally, it places absolutely no load on the tested circuit, but to achieve this ideal goal the null detector would have to have _absolutely zero voltage across it_, which would require an infinitely sensitive null meter and a perfect balance of voltage from the adjustable voltage source. However, despite its practical inability to achieve absolute zero loading, a potentiometric circuit is still an excellent technique for measuring voltage in high-resistance circuits. And unlike the electronic amplifier solution, which solves the problem with advanced technology, the potentiometric method achieves a hypothetically perfect solution by exploiting a fundamental law of electricity (KVL). #core.review[ - An ideal voltmeter has infinite resistance. - Too low of an internal resistance in a voltmeter will adversely affect the circuit being measured. - Vacuum tube voltmeters (VTVM's), transistor voltmeters, and potentiometric circuits are all means of minimizing the load placed on a measured circuit. Of these methods, the potentiometric ("null-balance") technique is the only one capable of placing _zero_ load on the circuit. - A _null detector_ is a device built for maximum sensitivity to small voltages or currents. It is used in potentiometric voltmeter circuits to indicate the _absence_ of voltage between two points, thus indicating a condition of balance between an adjustable voltage source and the voltage being measured. ]
https://github.com/leiserfg/fervojo
https://raw.githubusercontent.com/leiserfg/fervojo/master/typst-package/lib.typ
typst
MIT License
#let rr-wasm = plugin("./typst_railroad.wasm") #let _as_bytes(input) = { let t = type(input) if t == "bytes" { return input } if t == "string"{ return bytes(input) } if input.has("text") { return _as_bytes(input.text) } assert(true, message: "The input is not string, bytes, or a content with text") } #let render( railroad, css: rr-wasm.default_css(), ..args ) = { image.decode(rr-wasm.railroad(_as_bytes(railroad), _as_bytes(css)), format: "svg") } #let default-css() = { rr-wasm.default_css() }
https://github.com/Lucas-Wye/tech-note
https://raw.githubusercontent.com/Lucas-Wye/tech-note/main/src/cli_net_work.typ
typst
= Network #label("network") - A computer network is a digital telecommunications network which allows nodes to share resources. In computer networks, computing devices exchange data with each other using connections (data links) between nodes. == Commands #label("commands") ```sh ping domainname hostname cat /etc/hosts # ip address sudo systemctl restart NetworkManager # hosts生效 cat /etc/resolv.conf # dns server ip # TCP/IP interface configuration and routing utility ifconfig # configure a network interface route # show / manipulate the IP routing table netstat # show network status (network connections, routing tables, interface statistics, masquerade connections, and multicast memberships) sudo ping ip地址 -i 0.01 -s 65500 # 每0.01秒给ip地址对应的机器发送65500字节的数据包 ``` == Useful Remote Connection Utilities #label("useful-remote-connection-utilities") • #strong[ftp] \[options\] host, transfer file(s) using file transfer protocol \ • #strong[telnet] \[host \[port\]\], communicate with host using telnet protocol \ • #strong[ssh], remote login or remote execution using secure shell \ • #strong[rcp/scp], remotely copy files from this machine to another machine \ • #strong[rsync], smartly copy files over network after checking contents \ • #strong[curl], transfer a URL via HTTP, FTP, IMAP, etc \ • #strong[wget], download files over the Internet via HTTP or FTP \ • #strong[lynx/links], text-mode (mini) web browser === aria2 #label("aria2") (1)Install ```sh # Ubuntu sudo apt-get install aria2 # CentOS yum install aria2 ``` (2)Usage ```sh # 在命令后附加地址即可 aria2c "url" # 分段下载,利用 aria2 的分段下载功能可以加快文件的下载速度 # 使用 2 个连接来下载该文件,s的参数值介于 1~5 之间 aria2c -s 2 "url" # 断点续传,在命令中使用 c 选项可以断点续传文件 aria2c -c "url" ``` === curl #label("curl") - client URL tool (1)不带有任何参数时,发出 GET 请求 ```sh curl https://www.example.com ``` (2)`-A`指定User-Agent,默认用户代理字符串是curl/\[version\] ```sh curl -A 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36' https://google.com ``` (3)`-b` 参数用来向服务器发送 Cookie ```sh # 生成一个标头Cookie: foo=bar,向服务器发送一个名为foo、值为bar的 Cookie curl -b 'foo=bar' https://google.com ``` (4)`-d` 参数用于发送 POST 请求的数据体 ```sh curl -d'login=emma&password=123'-X POST https://google.com/login # `--data-urlencode` 等同于 `-d` # 发送 POST 请求的数据体,区别在于会自动将发送的数据进行 URL 编码 ``` (5)`-G` 参数用来构造 URL 的查询字符串 ```sh # 实际请求的 URL 为https://google.com/search?q=kitties&count=20 curl -G -d 'q=kitties' -d 'count=20' https://google.com/search ``` (6)`-H` 参数添加 HTTP 请求的标头 ```sh curl -H 'Accept-Language: en-US' https://google.com curl -d '{"login": "emma", "pass": "123"}' -H 'Content-Type: application/json' https://google.com/login ``` #block[ #set enum(numbering: "(1)", start: 7) + `-i` 参数打印出服务器回应的 HTTP 标头 ] ```sh # 先输出服务器回应的标头,然后空一行,再输出网页的源码 curl -i https://www.example.com ``` (8)`-o` 参数将服务器的回应保存成文件,等同于wget命令 ```sh curl -o example.html https://www.example.com # `-O` 参数将服务器回应保存成文件,并将 URL 的最后部分当作文件名。 curl -O https://www.example.com/foo/bar.html # 通过添加 `-C` 继续对该文件进行下载,已经下载过的文件不会被重新下载 curl -C -O http://www.gnu.org/software/gettext/manual/gettext.html ``` (9)使用wget或者curl下载github release文件 ``` curl -LJO GITHUB_RELEASE_LINK wget --no-check-certificate --content-disposition GITHUB_RELEASE_LINK ``` === terminal设置代理 #label("terminal设置代理") ```sh # MacOS & Linux export http_proxy=http://127.0.0.1:PORT # PORT替换成具体的端口 export https_proxy=http://127.0.0.1:PORT # Windows set https_proxy="http://127.0.0.1:PORT" set http_proxy="http://127.0.0.1:PORT" ``` === nmcli #label("nmcli") ```sh # connect to l2tp nmcli con up {L2TP_VPN_NAME} --ask ``` === Windows VPN连接 #label("windows-vpn连接") ``` rasdial VPN_NAME USERNAME PASSWORD ``` == More #label("more")
https://github.com/jamesrswift/chemicoms-paper
https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/src/elements/footer.typ
typst
#import "@preview/chic-hdr:0.4.0": * #let footer-render(parity: false, args) = { let footer-internal-content = ( counter(page).display(), h(0.75em),[|],h(1em), text( size: 8pt, args.citation ), ) if not parity {footer-internal-content = footer-internal-content.rev()} align(if parity {left} else {right}, footer-internal-content.join() ) } #let odd-even-page(content-odd: [], content-even: []) = { locate( loc => {if calc.even(loc.page()) [#content-even] else [#content-odd]}) } #let footer(args) = odd-even-page( content-odd: footer-render(parity: false, args), content-even: footer-render(parity: true, args) )
https://github.com/Tiggax/famnit_typst_template
https://raw.githubusercontent.com/Tiggax/famnit_typst_template/main/examples/example.typ
typst
MIT No Attribution
#import "@preview/sunny-famnit:0.2.0": project #import "attachments.typ" as pr #let input = ( izvleček: [ To je krako delo spisano za pomoč pri uporabi Typsta za delo zaključnega dela. V izvlečku se uporabi največ 250 besed. Tu se izpiše probleme, metode, rezultate, ključne ugotovitve in njihov pomen. ], abstract: [ This is a stub written to help you with use of Typst for thesis work. A maximum of 250 words is used in the abstract. Problems, methods, results, key findings and their significance are listed here. ], ključne_besede: ("Typst", "Zaključna naloga", "Pisanje", "Navodila"), key_words: ("Typst", "Final work", "Writing", "Tutorial"), kratice: ( "Famnit": "Fakulteta za matematiko naravoslovje in informacijske tehnologije", "PDF": "Portable document format", ), priloge: ( "Raw koda": raw(read("example.typ"), lang: "typst", block: true), "some obscurly long ass text that would be so long that it goes into another line to test. But hey you still need more words for it to go there.": pr.a, // sample of importing priloge. ), zahvala: [ Opcijsko se lahko tu zahvalite typst-u za olajšanje dela. Če zahvale ne želite napisati, zamenjajte content( to so vsebinski bloki znotraj `[]`) z `none` ], ) #show: project.with( date: datetime(day: 1, month: 1, year: 2024), author: "<NAME>", studij: "Bioinformatika", mentor:( name: "<NAME>", sl: ("dr.",""), en: ("",".phD"), ), somentor: none, // optional somentor, written in the same way as mentor work_mentor: none, // optional work mentor can be written the same way as mentor naslov: "<NAME>", title: "Title of the final work", bib_file: bibliography( "my_references.bib", style: "ieee", title: [Bibliography], ), ..input, // Dodajanje večjega dela stvari za lepšo preglednost. /* Additional options, defaults shown kraj: "Koper", */ text_lang: "en", // this can be chaged to "sl" for slovene works, there are small differences for it. ) = Uvod This @PDF and its source-code in @priloga_1 are for demonstration of the template. all Attachments are referencable, and so are abbriviations. you can add subheadings: == subheading you can add figures: #figure( caption: [some spicy figure], image("image.png", width: 80%) ) #let data = range(1,10).map(i => ([#i],[#(i * i)], [#(calc.pow(i,i))],[#(calc.ln(i))])).flatten() or a table: #figure( caption: [oh look, a table], table( columns: 4, [$x$],[$x * x$], [$x^x$],[$ln(x)$], ..data ) ) Referencing is simple as doing @darwin_1859_on
https://github.com/hargoniX/bachelor
https://raw.githubusercontent.com/hargoniX/bachelor/main/thesis/thesis.typ
typst
#import "template.typ": thesis, bfield, bit, bits, bytes, flagtext, theorem, definition, proof #import "@preview/codelst:1.0.0": sourcecode #show: thesis.with( title: "VeRix: A Verified Rust ix(4) driver", name: "<NAME>", email: "<EMAIL>", matriculation: "XXX", abstract: [ This thesis addresses the increasing importance of software fault detection in computer systems, focusing specifically on bugs related to the acquisition of data from external sources. The thesis highlights a gap in the existing literature, emphasizing the lack of formally verified network drivers. We propose a method using a model of the target hardware and @BMC to prove correct cooperation between a @NIC driver and the hardware. The practical viability of the approach is demonstrated by implementing a driver for the Intel 82599 @NIC. This implementation is done using the Rust programming language and a small @DSL for type-safe interaction with the hardware. The driver is then proven to cooperate correctly with a model of the target hardware using the Kani @BMC. ], paper-size: "a4", bibliography-file: "thesis.bib", glossary: ( (key: "NIC", short: "NIC", long: "Network Interface Card"), (key: "BMC", short: "BMC", long: "Bounded Model Checking"), (key: "CBMC", short: "CBMC", long: "C Bounded Model Checker"), (key: "BAR", short: "BAR", long: "Base Address Register"), (key: "EBNF", short: "EBNF", long: "Extended Backus Naur Form"), (key: "TT", short: "TT", long: "Rust Token Tree"), (key: "IPC", short: "IPC", long: "Inter Process Communication"), (key: "DMA", short: "DMA", long: "Direct Memory Access"), (key: "MMU", short: "MMU", long: "Memory Management Unit"), (key: "IOMMU", short: "IOMMU", long: "Input/Output Memory Management Unit"), (key: "VBus", short: "VBus", long: "Virtual Bus"), (key: "MMIO", short: "MMIO", long: "Memory Mapped Input/Output"), (key: "WG", short: "WG", long: "Working Group"), (key: "MTU", short: "MTU", long: "Maximum Transmission Unit"), (key: "OOM", short: "OOM", long: "Out Of Memory"), (key: "Mpps", short: "Mpps", long: "Mega packets per second"), (key: "DSL", short: "DSL", long: "Domain Specific Language"), (key: "L4Re", short: "L4Re", long: "L4 runtime environment"), ), supervisor_institution: "Prof. Dr. <NAME> (HM)", supervisor_company: "<NAME> (genua GmbH)", institution: "University of Applied Sciences Munich (HM)\nFaculty for Computer Science and Mathematics", logo_company: "figures/genua.svg", logo_institution: "figures/hm.svg", logo_size: 60%, submition_date: "DD.MM.2024" ) = Introduction // Inspired by: https://grosser.science/howtos/paper-writing // Introduction. In one sentence, what’s the topic? As computer systems are becoming increasingly omnipresent and complex both the negative impact of bugs as well as the likelihood of them occurring are increasing. Because of this, catching bugs with potentially catastrophic effects, such as crashing or overtaking systems, before they happen is becoming more and more important. These bugs mainly occur in one of two fashions: 1. Processing of data, for example in algorithm or data structure implementations 2. Acquisition of data, usually when the computer system interacts with the outside world in some way or form This thesis is mostly concerned with the latter kind. // State the problem you tackle Networking represents a key interaction point with the outside world for most current computer systems, it usually involves three key components: - the @NIC driver - the network stack - networking application While verifying network stacks and applications requires substantial resources due to their complexity, verification of @NIC drivers is much more approachable since they have only two jobs: 1. Setting up the @NIC. 2. Handling the receiving and transmission of packets. // Summarize why nobody else has adequately answered the research question yet. To our knowledge, there do not exist network drivers whose interaction with the @NIC itself has been formally verified. Instead, the focus is usually put on other issues that arise in driver implementation: - @witowski2007drivers and @ball2004slam are mostly concerned with the driver interactions with the rest of the kernel, as well as the absence of memory safety issues due to most drivers being written in C. - @more2021hol4drivers implements a verified monitor for interactions of a real driver with the @NIC instead of verifying the driver itself. While this means that bad interactions with the hardware can now be detected at runtime, this still has to be done in a way that is preventing the driver from its regular operations which usually means a crash. // Explain, in one sentence, how you tackled the research question. In this thesis, we show that formally verifying the interaction of a driver with the @NIC is possible. We do this by implementing a model of the target hardware and using @BMC to prove that they cooperate correctly. // How did you go about doing the research that follows from your big idea? To show that the concept is viable in practice, we implement a driver for the widely used Intel 82599 @NIC. This is done on the L4.Fiasco @l4doc microkernel, which provides a minimal trusted code base for our verification effort to build upon. On top of that, we use the Rust programming language which guarantees additional safety properties out of the box. The driver and model themselves use a custom Rust @DSL, based on ideas developed by the Rust Embedded @WG, to make correct peripheral access easier. Finally, we show, using the Kani @BMC @kani, that the driver correctly cooperates with a model of the 82599 where correctly means that: - The driver doesn't panic (safety). - The driver doesn't put the model into an undefined state (safety). - The driver receives all packets that are received by the model (correctness). - The driver correctly instructs the model to send packets (correctness). This thesis can be split roughly into four parts. First, we give brief introductions to the used technologies in @background. We then demonstrate how we used these technologies to implement the driver and its verification harness in @implementation. Afterwards, we analyze the results and limitations of our approach in @evaluation and finally draw our conclusions in @conclusion. = Background <background> In this chapter, we introduce the three key technologies that were used in our verification effort. First, we give a brief introduction to the rather uncommon ways that L4 allows us to interact with our target hardware from the userspace in @l4. Afterwards, we explain the features of Rust that are important for understanding the driver implementation later on in @rust. Finally, we give an overview of the formal verification tooling that currently exists for Rust, argue why we preferred Kani over the others, and demonstrate its capabilities in @formal-rust. == L4.Fiasco and L4Re <l4> As a microkernel, L4.Fiasco offers barely any functionality on a kernel level. Instead, the kernel hands out hardware resources to user space tasks which can use them or distribute them further to other tasks. This allows us to limit the number of things that a task can interact with to the bare minimum, which reduces the attack surface drastically. The default set of user space programs and libraries that ships with L4.Fiasco is the @L4Re. In the following, we illustrate the three main @L4Re interaction mechanisms used by our driver. The most basic mechanism are so-called capabilities. A capability is in a sense comparable to a file descriptor. It identifies an object that is somewhere in the kernel, allowing us to communicate with that object in some way. The difference to a file descriptor is that any object that we get from the kernel is described by a capability: threads, access to hardware, @IPC gates to other tasks, etc. #figure( image("figures/l4-caps-basic.svg", width: 80%), caption: [Capabilities], ) <l4caps> This means that the set of capabilities that we initially grant our driver, completely determines the way it may interact with the rest of the operating system. As a consequence, even if our driver ends up getting compromised despite our efforts, the effects that it can have on the system as a whole are limited. The separation of features out of the kernel in L4.Fiasco even goes as far as removing memory management from the kernel. Instead, a so-called pager task is designated as the memory manager of one or multiple threads. Once one of these threads causes a page fault, the kernel sends the pager an @IPC notification and the pager returns either the backing page or an error. In the successful case, the kernel then proceeds to map that page into the address space of the faulting thread. This allows the system to construct a hierarchy of memory mappings between tasks. One task can grant a portion of its memory to another task,, which can in turn only grant another sub-portion of that memory to another task etc. While this can be used to implement normal functionality like an allocator, it is also an interesting feature for implementing programs that interact with hardware. It is very common for a driver to share some of its own memory with the hardware directly to allow high-performance communication, this is called @DMA. However, allowing hardware arbitrary access to memory is a risk in two ways: 1. The hardware might overwrite or steal arbitrary memory contents. 2. The driver that interacts with the hardware might do the same by instructing the hardware to, for example, write its data to an address the driver does not usually have access to. For this reason, a modern CPU usually ships a special @MMU that manages @DMA based memory access, the @IOMMU. This means that by modeling the hardware as a special kind of task with memory mappings that are managed by the @IOMMU, we can allow our user space tasks to safely manage their @DMA mappings themselves. #figure( image("figures/io-overview.svg", width: 80%), caption: [IO architecture], ) <l4io> The only missing piece now is where a program can obtain the necessary capabilities and memory mappings to communicate with the hardware, this is done through the IO server. The IO server is a task that owns all resources related to hardware that are not needed by the kernel itself. This includes the PCI(e) bus, interrupts, IO memory, and more. Thus to access hardware a task needs to have an @IPC capability to talk with the IO server. Instead of allowing processes with such a capability to obtain arbitrary hardware resources, each client is granted a limited view of the hardware in the form of a so-called @VBus. As we can see in @l4io, this allows us to limit the hardware that a task can see to the bare minimum required for operation, again following the minimal privilege principle from the capability system. == Rust <rust> We chose to use the Rust programming language for the entire implementation due to three key factors: 1. It is memory-safe by default while at the same time being competitive with the likes of C/C++ in terms of performance. 2. If necessary it still allows us to break out into a memory-unsafe superset of language, unlike most memory-safe languages such as Java. 3. It already has partial support on our target platform, L4.Fiasco. In this section we aim to give an overview of the important Rust features that we use. For a more complete overview of the Rust language, we refer to @rustbook. All variables in Rust are immutable by default, hence the following program does not compile: #sourcecode[```rust fn main() { let c = 0; println!("Hello: {}", c); c += 1; println!("Hello: {}", c); } ```] But mutability can be opted in to by using `let mut`. The idea behind immutable by default is to limit the number of moving pieces in a program to a minimum. This allows programmers to argue more easily about their code as there are fewer moving pieces. On top of that, it plays an important role in Rust's approach to memory safety. The most notable feature of Rust, that distinguishes it from other widely used programming languages, is ownership and the part of the compiler that enforces it, the borrow checker. It is the key feature in providing memory safety per default. As the name suggests, every value in Rust has an owner. The compiler enforces that there can only be exactly one owner of a value at a time. Once this owner goes out of scope the value gets freed, or in Rust terms, dropped. On top of this, a value can be moved from one owner to another. This happens in two situations: 1. A value is returned from a function. 2. A value is passed into another function. Once a value has been moved the previous owner is not capable of accessing it anymore. For example, the following program is not accepted by the compiler: #sourcecode[```rust fn func(s : String) { println!("Hello: {}", s); } fn main() { let s = String::from("World"); // the value behind `s` gets moved here func(s); // `s` is no longer valid func(s); } ```] Rust offers two ways to resolve the above situation. The value can be cloned with `s.clone()`, cheap values such as integers are automatically cloned. Alternatively, a reference to the value can be passed to the function, this is called borrowing. On top of enforcing the ownership rule, the borrow checker also enforces that references can never outlive the value they are referring to. Keeping up the distinction between mutable and immutable values Rust supports two kinds of references: 1. Immutable ones: `&var : &Type`, they are a read-only view of the data 2. Mutable ones: `&mut var: &mut Type`, they are a read-and-write view of the data To prevent data races at compile time, the borrow checker provides the additional guarantees that a value can either: - be immutably referenced one or more times - or be mutably referenced a single time Using this knowledge the above example can be rewritten to: #sourcecode[```rust fn func(s : &String) { println!("Hello: {}", s); } fn main() { let s = String::from("Hello World"); func(&s); func(&s); } ```] While the borrow checker is capable of correctly identifying the vast majority of code that does adhere to the above restrictions at compile time, it is not infallible. Rust provides several ways to work around the borrow checker in case of such false negatives. The simplest ones are wrapper types that lift the ownership restrictions in one way or another. We are interested in only one of those: `RefCell<T>`. This type shifts the borrow checking to the run time and throws errors if we violate the restrictions while running. If these wrapper types are still not enough to resolve the situation one can fall back to using `unsafe` code. However, writing buggy `unsafe` code will not lead to compiler or run time errors, but instead undefined behavior like in C/C++. A common `unsafe` example is splitting a slice, Rust's notion of a fat pointer, into two: #sourcecode[```rust unsafe fn split_at_unchecked<T>(data: &[T], mid: usize) -> (&[T], &[T]) { let len = data.len(); let ptr = data.as_ptr(); (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), len - mid)) } ```] Note that we had to declare the function itself as `unsafe` since calling `unsafe` functions is "viral" in Rust, i.e. if something calls `unsafe` code it is considered `unsafe` itself. That said we can provide safe API wrappers around them that ensure preconditions for using the `unsafe` API are met. In this example, we have to ensure that `mid <= len` to prevent the second slice from pointing into memory outside of the original one: #sourcecode[```rust fn split_at<T>(data: &[T], mid: usize) -> (&[T], &[T]) { assert!(mid <= data.len()); unsafe { data.split_at_unchecked(mid) } } ```] Using the `unsafe` block feature like here, is an instruction to the compiler to trust the programmer that the contained code is safe in this context. The context in the above function being that we already asserted the necessary preconditions. Besides being used for memory management, the ownership system can also be used for general resource management. For example, a type `File` that wraps OS file handles can automatically close itself while being dropped. This is achieved by implementing the `Drop` trait: #sourcecode[```rust impl Drop for File { fn drop(&mut self) { close(self.handle); } } ```] Traits in Rust fulfill a similar purpose to interfaces in languages like Java. However, they are strongly inspired by type classes from languages like Haskell, and thus provide a few extra features on top of the classical interface concept. Declaring an interface style trait like `Drop` from above looks like this: #sourcecode[```rust trait Add { fn add(self, rhs: Self) -> Self; } ```] We might then continue to implement this trait for a bunch of basic types like strings, integers, etc. But implementing it for generic types such as pairs gets more interesting. Intuitively we can add two pairs if the things in the pairs can be added. We can express this constraint in a trait implementation: #sourcecode[```rust impl<L, R> Add for (L, R) where L: Add, R: Add, { fn add(self, rhs: Self) -> Self { (self.0.add(rhs.0), self.1.add(rhs.1)) } } ```] If we try to call `add` on a pair, Rust will start looking for fitting instances for the types of the values contained in the pairs. In particular, it will recursively chain this instance to figure out how to add values of types like `(u8, (u8, u8))`. Furthermore, traits can have generic arguments themselves as well. For example a heterogeneous `Add` trait that supports both normal addition of integers etc. but also things like adding a `Duration` on top of a `Time` might look like this: #sourcecode[```rust trait Add<Rhs, Out> { fn add(self, rhs: Rhs) -> Out; } // Add raw times impl Add<Time, Time> for Time { fn add(self, rhs: Time) -> Time { /* */ } } // Add relative durations onto some time impl Add<Duration, Time> for Time { fn add(self, rhs: Duration) -> Time { /* */ } } ```] There is one drawback to this approach: To find an `Add` instance all of the types involved have to be known. Otherwise, the trait system cannot know whether to use the first or the second instance. While it is very likely that the compiler already knows the input types, it is much less likely that it will be able to figure out the output type on its own. This would force users to put explicit type annotations to make the instance search succeed. To make using this trait easier we can use so-called associated types, similar to functional dependencies in Haskell typeclasses: #sourcecode[```rust trait Add<Rhs> { type Out; fn add(self, rhs: Rhs) -> Self::Out; } // Add raw times impl Add<Time> for Time { type Out = Time; fn add(self, rhs: Time) -> Time { /* */ } } // Add relative durations onto some time impl Add<Duration> for Time { type Out = Time; fn add(self, rhs: Duration) -> Time { /* */ } } ```] Rust enforces that there can only be one instance for one assignment of generic variables. This means that while we could have previously written instances like `Add<Duration, Time> for Time` and `Add<Duration, Duration> for Time`, the new design doesn't allow this as we would have two instances of the form `Add<Duration> for Time`. While associated types take a bit of flexibility away from the programmer, they do allow Rust to start instance search without all involved types figured out through type inference. Whether to use generic or associated types thus comes down to a usability (through type inference) vs flexibility (through additional permitted instances) trade-off. While the recursive chaining of trait instances already allows a great deal of compile-time code generation, there are situations where traits are not sufficient. A common case is to automatically generate the same code for a list of identifiers to e.g. test them or add similarly shaped trait instances to all of them. This is where Rust's macro system comes into play. Unlike the substitution-based macros in C/C++, Rust's macro system allows users to write proper syntax tree to syntax tree transformations. Generally speaking, Rust supports two kinds of macros: 1. declarative macros, they use an @EBNF inspired @DSL to specify the transformation 2. procedural macros, they use arbitrary Rust code for the transformation The macros used in this work are exclusively declarative ones, so we only describe this approach. To illustrate the capabilities of declarative macros we embed a small math @DSL into Rust: #sourcecode[ ``` x = 1; y = 2 * x; y; x; ```] Where if a variable is alone on a line we print its value. This can be done using a declarative macro in the style of a so-called @TT muncher: #sourcecode[```rust macro_rules! math { ($var:ident = $e:expr; $($tail:tt)*) => { let $var = $e; math!($($tail)*); }; ($var:ident; $($tail:tt)*) => { let x = format!("Value: {}", $var); println!("{}", x); math!($($tail)*); }; () => {}; } ```] As we can see this macro has 3 "production rules": 1. If we see `x = e; ...` we bind `x` to the value of `e` and recursively process the remaining token trees in the input. 2. If we see `x; ...` we print the value of `x` and process the rest. 3. If there is no argument we do nothing. This is to handle the case when the remaining token tree list is empty. The above macro also demonstrates an important guarantee of Rust macros, macro hygiene. We call a macro system hygienic, when identifiers that are used within the body of a macro (like `let x = format...`) cannot collide with user-provided identifiers (like the `x` from the input). So instead of `x` suddenly turning out to be a string once we want to print it, Rust kept the values separate and the following main function produces the expected output: #sourcecode[```rust fn main() { math! { x = 1; y = 2 * x; y; x; } } ```] ``` Value: 2 Value: 1 ``` The precise workings of the declarative macro syntax and all the kinds of syntax that can be matched on are far out of the scope of this work, we refer to @rustmacrobook for a more detailed introduction. == Formal Verification in Rust <formal-rust> In this section we explain why we chose Kani over other available formal verification tools for Rust and give an overview over both the stable and unstable features of Kani. To our knowledge there do currently exist three actively maintained and reasonably popular tools for (semi-)automated verification of Rust code: - Kani @kani - Creusot @creusot - Prusti @prusti Based on the Rust features used in our driver code we, compiled a list of feature requirements for a tool that we could use to verify the driver: - Core language features: - (mutable) variables - control flow - loops - borrowing - structs and enums - arrays - generic types on types and functions - traits, including associated types - `unsafe` - dynamic memory management with `RefCell` #figure( table( columns: (auto, auto, auto, auto), [*Feature*], [*Kani*], [*Creusot*], [*Prusti*], [Core], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], [Generics], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], [Traits], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], [`unsafe`], [#sym.checkmark], [-], [-], [`RefCell`], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], ), caption: [Capabilities of formal verification tools for Rust], ) <requirements> As we can see in @requirements, the only feature that both Creusot and Prusti are missing is the capability to deal with `unsafe` code. Since our program is a driver, a certain degree of direct hardware interaction through pointers (or interfaces that abstract pointers) is impossible to avoid. For Creusot, the lack of `unsafe` support is evident from its issue tracker where this is still an open feature request #footnote[https://github.com/xldenis/creusot/issues/36]. Prusti is not entirely incapable of processing `unsafe` code, but its automation capabilities are very limited. For example, the following example cannot be verified by Prusti automatically: #sourcecode[```rust fn test() { let mut test : Vec<u8> = Vec::new(); test.push(0); unsafe { test.as_mut_ptr().write(10); if test.as_ptr().read() != 10 { // We want to prove that this panic is unreachable panic!("Ahhh"); } } } ```] Kani on the other hand is capable of verifying these and much more complicated `unsafe` examples, which made us pick it for this verification effort. Kani is implemented as a code generation backend for the Rust compiler. However instead of generating executable code, it generates an intermediate representation of @CBMC @cbmc. While @CBMC was originally intended for verifying C code, by using this trick Kani can make use of all the features that already exist in @CBMC. By default, Kani checks the following properties of a given piece of Rust code: - memory safety, that is: - pointer type safety - the absence of invalid pointer indexing - the absence of out-of-bounds accesses - the absence of mathematical errors like arithmetic overflow - the absence of runtime panics - the absence of violations of user-added assertions For example, the following Rust code would crash if `a` has length $0$: #sourcecode[```rust fn get_wrapped(a: &[u32], i: usize) -> u32 { return a[i % a.len()]; } ```] We can check this using Kani as follows: #sourcecode[```rust #[cfg(kani)] #[kani::proof] fn check_get_wrapped() { let size: usize = kani::any(); let index: usize = kani::any(); let array: Vec<u32> = vec![0; size]; get_wrapped(&array, index); } ```] Kani ends up spotting the failure and an additional one: ``` SUMMARY: ** 2 of 376 failed (8 unreachable) Failed Checks: attempt to calculate the remainder with a divisor of zero File: ".../lib.rs", line 2, in get_wrapped Failed Checks: This is a placeholder message; Kani doesn't support message formatted at runtime File: ".../raw_vec.rs", line 545, in alloc::raw_vec::capacity_overflow ``` As we just saw, we can use the `kani::any()` function to generate arbitrary symbolic values of basic types like integers. These basic values can then be used to build up more complex symbolic values like the `Vec<u32>` from above. However, there is one more issue than expected with the proof, the harness caused an error in the allocator for `Vec`. This is because there is a limit to how much memory we can request. Since the error is introduced by the proof code itself, instead of the code we wish to verify, we probably want to get rid of it. This can be achieved by putting a constraint on `size` using the `kani::assume()` function: #sourcecode[```rust #[cfg(kani)] #[kani::proof] fn check_get_wrapped() { let size: usize = kani::any(); kani::assume(size < 128); let index: usize = kani::any(); let array: Vec<u32> = vec![0; size]; get_wrapped(&array, index); } ```] While this proof harness ends up only finding the failure we expect, it is very much possible that there exist more bugs that are not discovered at this array size. As we will see later on, there is usually a trade-off between the amount of state we explore (i.e. how sure we are that the verified properties generally hold) and the amount of resources (both time and RAM) required to complete the verification. Additionally, we can tell Kani to generate counterexamples based on the failures that it found. This is done by adding the flag `--concrete-playback=print` to the `cargo kani` invocation. The counterexamples are then directly printed as unit tests that can be run using standard Rust tooling: #sourcecode[```rust #[test] fn kani_concrete_playback_check_get_wrapped_10606138830414890630() { let concrete_vals: Vec<Vec<u8>> = vec![ // 0ul vec![0, 0, 0, 0, 0, 0, 0, 0], // 18446744073709551615ul vec![255, 255, 255, 255, 255, 255, 255, 255], ]; kani::concrete_playback_run(concrete_vals, check_get_wrapped); } ```] The counterexample gets encoded as a series of byte vectors, one for each invocation of `kani::any`. In this scenario the first variable (`size`) gets fixed to $0$ and the second one (`index`) to some large integer. This counterexample describes precisely the scenario that we expected to fail: Wrapped indexing into an empty array. We now consider the scenario where the `index` variable is not directly generated from `kani::any` but additionally preprocessed by some function. In this scenario, we might want to make sure that our harness also checks the case where we go above the bounds of the array. After all, this is the precise situation that `get_wrapped` is supposed to guard against. Such statements can be asserted using the `kani::cover` function: #sourcecode[```rust #[cfg(kani)] fn complicated() -> usize { let mut index: usize = kani::any(); // additional logic index } #[cfg(kani)] #[kani::proof] fn check_get_wrapped() { let size: usize = kani::any(); kani::assume(size < 128); let array: Vec<u32> = vec![0; size]; let index = complicated(); kani::cover(index >= array.len(), "Out of bounds indexing possible"); get_wrapped(&array, index); } ```] This changes nothing about the failures that we end up finding, but an additional remark about the satisfied cover properties gets added to the output: ``` SUMMARY: ** 1 of 376 failed (8 unreachable) ** 1 of 1 cover properties satisfied ``` In all of the examples above no loops are used, this makes it easy for Kani to explore the entire state space. Once we introduce loops, Kani has two strategies to explore the state space. The first approach is to unwind the loops a limited amount of times, just enough to explore the entire state space. In many situations, we need to limit the state space that we wish to consider in the first place, as unwinding too much ends up generating too large problem instances to compute with reasonable resources. In the following, we will consider a new function `zeroize`, which clears an array of bytes to all $0$. We wish to verify that the function does this for every slot of the array: #sourcecode[```rust fn zeroize(buffer: &mut [u8]) { for i in 0..buffer.len() { buffer[i] = 0; } } #[cfg(kani)] #[kani::proof] fn check_zeroize() { let size: usize = kani::any(); kani::assume(size > 0); kani::assume(size < 32); let mut buffer: Vec<u8> = vec![10; size]; zeroize(&mut buffer); let index: usize = kani::any(); kani::assume(index < buffer.len()); assert!(buffer[index] == 0); } ```] When we run Kani on this, we end up unwinding the loop in `zeroize` indefinitely. To limit loop unwinding, we have to tell the harness about a limit explicitly. If this limit is too low to explore the given state space, Kani complains: #sourcecode[```rust #[cfg(kani)] #[kani::unwind(1)] #[kani::proof] fn check_zeroize() { let size: usize = kani::any(); kani::assume(size > 0); kani::assume(size < 32); let mut buffer: Vec<u8> = vec![10; size]; zeroize(&mut buffer); let index: usize = kani::any(); kani::assume(index < buffer.len()); assert!(buffer[index] == 0); } ```] Instead of simply verifying only one loop iteration, Kani tells us that this bound is too low: ``` Failed Checks: unwinding assertion loop 0 ``` Once we increase it to $32$, all checks pass. However, there exists a scalability issue here. Once we ramp the size up to $64$ or larger, @CBMC ends up consuming several GB of RAM to solve the same underlying problem as before. For situations like this, Kani provides an experimental alternative called Loop-contract synthesis. This uses an approach described in @invariants, to synthesize invariants that describe the behavior of loops. The biggest limitation of the current implementation is, that it is not compatible with loop unwinding. This means that we cannot use Loop-contract synthesis for a few loops that we don't wish to unwind, but the rest of the program is too hard to synthesize contracts for we cannot use the synthesis selectively. That said this issue is not an inherent limitation of the approach and there do exist ideas on how to change this in the feature proposal #footnote[https://github.com/model-checking/kani/blob/6d628bf0b399b8c50ddea9f011321463e4c00e4c/rfc/src/rfcs/0004-loop-contract-synthesis.md]. The experimental state of the feature also shows when attempting to use it on slightly non-trivial examples like the above. When enabling it through the `--synthesize-loop-contracts` flag, the component of @CBMC responsible for computing the invariants ends up crashing #footnote[Reported at: https://github.com/model-checking/kani/issues/2927]. The last notable feature is stubbing. It allows us to replace functions in the code under verification with different functions. This is useful for verifying functions that are out of reach for Kani, for example, interactions with the operating system: #sourcecode[```rust use std::{thread, time::Duration}; fn interaction() { thread::sleep(Duration::from_secs(1)); rate_limited_functionality(); } #[cfg(kani)] #[kani::proof] fn check_interaction() { interaction(); } ```] This code is rejected by Kani with: ``` Failed Checks: call to foreign "C" function `nanosleep` is not currently supported by Kani. ``` If we are only interested in verifying things about `rate_limited_functionality` we can tell Kani to replace `thread::sleep` with an empty function: #sourcecode[```rust fn mock_sleep(_dur : Duration) {} #[cfg(kani)] #[kani::proof] #[kani::stub(std::thread::sleep, mock_sleep)] fn check_interaction() { interaction(); } ```] On top of stubs, Kani provides another experimental feature called function contracts. The idea here is to describe the pre- and postconditions of a function, and then replace all calls to this function with a stub that asserts the preconditions and assumes the postconditions. This allows us to verify functions in a modular fashion, thus enabling us to verify much larger bodies of code piece by piece instead of translating everything at once into a @CBMC problem. For example, we can provide a contract for a division function: #sourcecode[```rust fn get(a: &[u32], i: usize) -> u32 { return a[i]; } #[cfg(kani)] mod kani { use crate::get; #[kani::requires(divisor != 0)] #[kani::ensures(result <= dividend)] fn my_div(dividend: usize, divisor: usize) -> usize { dividend / divisor } #[kani::proof_for_contract(my_div)] fn my_div_harness_proof() { my_div(kani::any(), kani::any()); } #[kani::proof] fn check_get() { let size: usize = kani::any(); kani::assume(size < 128); kani::assume(size > 0); let array: Vec<u32> = vec![0; size]; let index = my_div(array.len() - 1, 2); get(&array, index); } } ```] While this particular harness ends up succeeding, there are many scenarios that this overapproximation of `my_div`'s behavior leaves out. For example using `2 * (array.len() - 1) / 2` as `index` ends up failing, because the contract only claims that the result will be less than or equal to `2 * array.len() - 2`, which is not sufficient to establish that we are in bounds. Thus when doing verification with contracts we need to design them in a way to fit the consumer of the contract in other proofs, instead of just letting Kani and @CBMC figure everything out on their own. Unfortunately, side effects on memory and quantifier logic in the pre- and postconditions are currently only addressed in the contract proposal #footnote[https://github.com/model-checking/kani/blob/6d628bf0b399b8c50ddea9f011321463e4c00e4c/rfc/src/rfcs/0009-function-contracts.md] and not yet implemented. Since the majority of behavior in a driver are memory effects, we cannot use this feature for our verification purposes. = Implementation <implementation> Now that we have an overview of our target platform, language, and verification methodology, we can take a look at the actual implementation of the verified driver. This is split into four parts. We begin by explaining how a driver has to interact with the Intel 82599 in @intel-nic. Following this we explain the driver itself in @verifying-verix, in particular, we: 1. Introduce a framework for writing drivers, such that they can be used both for verification with Kani and in the real world, in @pc-hal. 2. Explain precisely how our driver interacts with the Intel 82599 in @verix. 3. Provide proofs for the safety and correctness properties from the introduction in @mix. == Intel 82599 <intel-nic> The communication with the Intel 82599 happens in roughly three phases: 1. PCI device discovery and setup 2. Configuration of the actual device 3. Sending and receiving packets In the following chapter, we aim to give an overview of the first two phases. The third one will be discussed in detail in @mix, as it is the main verification target. A normal driver would initially have to look for the device on its own. However, as we are on L4, the IO server instead searches for these devices and presents them to us through a @VBus. Once we have obtained this device handle, we can start talking to it through the PCI config space. This config space is in essence a memory-like structure that we can read from and write to using @IPC calls to the IO server. The beginning (and relevant to us part) of this structure can be seen in @pcicfg. The fields that are of most interest to our driver are the 6 @BAR ones, they contain addresses of memory regions that are shared between our CPU and the device. These regions can be mapped into our address space and then used for @MMIO based configuration. The datasheet of the device @intel:82599 tells us that the relevant @BAR for configuring the device is the first one. Thus the first thing the driver has to do is ask the IO server to map the memory, that @BAR 0 points to, into our address space, so we can actually begin device initialization. #figure( bfield( bytes(2)[Device ID], bytes(2)[Vendor ID], bytes(2)[Status Register], bytes(2)[Control Register], bytes(3)[Class Code], bytes(1)[Revision ID], bytes(1)[Reserved], bytes(1)[Header Type], bytes(1)[Latency Timer], bytes(1)[Cache Line Size], bytes(4)[@BAR 0], bytes(4)[@BAR 1], bytes(4)[@BAR 2], bytes(4)[@BAR 3], bytes(4)[@BAR 4], bytes(4)[@BAR 5], ), caption: [Beginning of the PCI config space] ) <pcicfg> After this mapping is done, the driver has to follow the initialization procedure described in section 4.6.3 of @intel:82599. Almost all of this configuration can be done exclusively through the @MMIO based interface that was established previously. The exception to this is the setup of @DMA based queues which are used to transmit and receive packets. The packets do not get sent directly through these queues though, instead so-called descriptors are written to the queue. They contain the address of the actual packet data in the TX case and the address to write packet data to in the RX case. This means that the driver has to set up 3 @DMA mapped buffers in total: - one for the RX queue - one for the TX queue - one as a memory pool for packet buffers After this setup is done, the communication with the network can begin. The details of this queue-based communication, as well as its verification. are discussed in @verix and @mix. == The driver <verifying-verix> In this chapter, we explain how we developed and verified the driver itself. The rough architecture for the project is laid out in @arch. The end product is an application called `verix-fwd`, which mirrors received packets back to the sender. `verix-fwd` is mainly powered by `verix-lib`, which is the actual driver and the subject of our verification efforts. #figure( image("figures/drawio/verix-arch.drawio.pdf.svg", width: 80%), caption: [Architecture] ) <arch> `verix-lib` in turn does not directly talk to the hardware, but rather through an abstract interface called `pc-hal` which has two implementations: 1. `pc-hal-l4`, this is the one we actually used in production on real-world hardware. It implements the abstract interface provided by `pc-hal` by calling into the responsible L4 APIs. It is discussed in @pc-hal. 2. `mix`, the "model ix". It provides a software model of the @NIC that implements the `pc-hal` abstract interface. When plugged into `verix-lib` instead of `pc-hal-l4` we can use Kani to verify properties about the interaction of the driver with the modeled @NIC. It is discussed in @mix. The code for the driver and the verification harnesses can be found on Github #footnote[https://github.com/hargoniX/rustl4re/tree/master/src/l4/pkg/verix]. === pc-hal <pc-hal> The main job of `pc-hal` is to provide a trait-based abstraction over the L4 hardware related APIs in order to allow us to plug `mix` in. The design is based on the Rust Embedded @WG's `embedded-hal` #footnote[https://docs.rs/embedded-hal/0.2.7/embedded_hal/index.html]. In particular, we provide abstractions for: - @DMA mappings - @VBus interface - PCI config space - raw pointer-based @MMIO interfaces Demonstrating how all of these interfaces work would be out of the scope of this work, so we instead only give an exemplary view of the PCI config space abstraction. It is implemented as a single trait, `FallibleMemoryInterface32`: #sourcecode[```rust pub trait FallibleMemoryInterface32 { type Error; type Addr; fn write8(&mut self, offset: Self::Addr, val: u8) -> Result<(), Self::Error>; fn write16(&mut self, offset: Self::Addr, val: u16) -> Result<(), Self::Error>; fn write32(&mut self, offset: Self::Addr, val: u32) -> Result<(), Self::Error>; fn read8(&self, offset: Self::Addr) -> Result<u8, Self::Error>; fn read16(&self, offset: Self::Addr) -> Result<u16, Self::Error>; fn read32(&self, offset: Self::Addr) -> Result<u32, Self::Error>; } ```] The interface has to be designed in a fallible way, because as discussed previously the communication with the PCI config space happens through @IPC, which can return errors. In addition to that, we also abstract over the address data type to possibly allow more diverse usage of this trait in other applications if they ever arise. The reason that both of the type parameters are implemented as associated types instead of generic ones, is to improve usability by reducing the required amount of type inference to succeed before finding the trait instances. While the majority of the interfaces provided by `pc-hal` could probably be made sufficiently general to fit multiple platforms, they are currently very much designed with the L4 interface in mind. This makes the `pc-hal-l4` implementation of the traits mostly a thin wrapper around the Rust L4 APIs. These APIs were initially developed in @humendal4 and extended by us to support more hardware-related things. In addition to the traits `pc-hal` also provides a few utility functions that work on top of them. The most notable one is a type-safe @MMIO abstraction in the spirit of the Rust Embedded @WG's `svd2rust` tool. `svd2rust` allows Rust Embedded developers to automatically generate type-safe implementations for @MMIO interfaces of ARM and RISC-V chips. The need for such a type-safe API arose, because interacting with an @MMIO interface in Rust uses direct pointer manipulation together with lots of constants and bit operations: #sourcecode[```rust pub const IXGBE_CTRL: u32 = 0x00000; pub const IXGBE_CTRL_LNK_RST: u32 = 0x00000008; pub const IXGBE_CTRL_RST: u32 = 0x04000000; pub const IXGBE_CTRL_RST_MASK: u32 = IXGBE_CTRL_LNK_RST | IXGBE_CTRL_RST; fn set_reg32(&self, reg: u32, value: u32) { unsafe { ptr::write_volatile( (self.addr as usize + reg as usize) as *mut u32, value ); } } self.set_reg32(IXGBE_CTRL, IXGBE_CTRL_RST_MASK); ```] `svd2rust` provides a type-safe version of this API by automatically generating code from an XML-based interface description, the SVD files. While such files are not available for the Intel 82599 we, end up generating an API that works very similarly to the `svd2rust` ones. However, our implementation is no file-to-file converter but instead implemented as a declarative Rust macro. The user interface of our macro looks as follows: #sourcecode[```rust mm2types! { Intel82599 Bit32 { Bar0 { ctrl @ 0x000000 RW { reserved0 @ 1:0, pcie_master_disable @ 2, lrst @ 3, reserved1 @ 25:4, rst @ 26, reserved2 @ 31:27 } } } } ```] We declare a device called `Intel82599` which has @MMIO registers of size 32-bit. This device has an @MMIO interface called `Bar0`, which contains a register `ctrl` at offset `0x0` which is readable and writable and has several fields at certain bit ranges. The equivalent of the above register access looks as follows in our API: #sourcecode[```rust bar0.ctrl().modify(|_, w| w.lrst(1).rst(1)); ```] While this involves a closure and several function calls, all of the operations here end up getting inlined and optimized by the compiler. This optimization is so good, that our code ends up producing the same assembly code as the pointer-based interface above. Describing all the details of `svd2rust` style APIs is out of scope here, but they can be found in its documentation #footnote[https://docs.rs/svd2rust/0.30.2/svd2rust/index.html]. In addition to this, the macro also supports 64-bit based @MMIO which we use to generate type-safe interfaces for the packet descriptors. The way this is usually done looks as follows: #sourcecode[```rust #[repr(C)] pub struct ixgbe_adv_rx_desc_read { pub pkt_addr: u64, pub hdr_addr: u64, } ptr::write_volatile( &mut (*desc).pkt_addr as *mut u64, phys_addr as u64, ); ```] Which, while already typed to a degree, still allows for quite a bit of error compared to the intrinsically typed version that our macro provides. The equivalent declaration and memory access in our framework looks like this: #sourcecode[```rust mm2types! { Descriptors Bit64 { adv_rx_desc_read { pkt_addr @ 0x0 RW { pkt_addr @ 63:0 } hdr_addr @ 0x8 RW { hdr_addr @ 63:0 } } } } desc.pkt_addr().write(|w| w.pkt_addr(device_addr)); ```] === verix <verix> As mentioned above, verix is the code that interacts with the hardware and thus the code that we are interested in verifying. The driver itself is largely based on the ixy driver, originally published in @emmerichixy and later ported to Rust in @ellmannixy. The three main differences between our port and the Rust original are: 1. the abstract `pc-hal` interface instead of the Linux userspace APIs 2. a reduction of `unsafe` code from the driver itself, by generating the (type) safe @MMIO APIs 3. we only ended up porting the polling variant of the driver, this means that our setup uses no interrupts. Since the initial device setup is simply a linear list of @MMIO interactions, we won't go into the details of how the driver performs these steps. The packet receive and transmit procedures on the other hand are more involved. We begin by explaining the receive procedure, as it is slightly simpler than the transmit one. As mentioned in @intel-nic packet receiving is done through a @DMA mapped queue. This queue is implemented as a ring buffer in memory. The state of this queue is determined by 4 @MMIO mapped registers: 1. RDBAL and RDBAH, they contain the low and high half of the base address 2. RDLEN, the length of the buffer behind the base address in bytes 3. RDH and RDT which are the head and tail of the queue that is simulated on top of this ring buffer An example state of an RX queue, configured with 8 slots, might thus look like this: #figure( image("figures/drawio/rx-queue.drawio.pdf.svg", width: 70%), caption: [Example RX queue] ) <rx-queue-1> According to Section 7.1 of @intel:82599 this state is to be interpreted as follows: 1. The slots $1, 2, 3, 4$ (the interval $["RDH", "RDT")$) are owned by the hardware and contain so-called read descriptors. 2. The slots $5, 6, 7, 0$ (the interval $["RDT", "RDH")$) are owned by the software and are either being currently processed, or there is currently no packet buffer free to turn them back into read descriptors. Both of these descriptor types are $2 dot.c 64$ bit value long structures. Read descriptors, as can be seen in @adv_rx_read, are very basic. They consist of three parts: 1. The Packet Buffer Address, this is a pointer to the @DMA mapped slice of memory that we expect the hardware to write a packet to. 2. The Header Buffer Address, this can be used for additional hardware features that are not in use by us. 3. The DD bit. This stands for Descriptor Done and is present in both the read and the write-back descriptor. It is set by the hardware to indicate that this descriptor has been processed. Once the hardware receives a packet, it places its data at the Packet Buffer Address of the first free read descriptor and sets the DD bit. After that is done a write-back descriptor, as described in @adv_rx_wb, is put into the consumed slot. This descriptor kind contains a lot of meta information, most of which concerns more advanced features. The fields that are relevant in the basic configuration setup of verix are: 1. The packet length which contains how many bytes of the buffer in the read descriptor were used for a received packet. 2. The extended status register which contains two fields that are relevant to us: 1. The EOP bit, if set indicates the end of a packet. This is relevant because the @NIC can in theory be configured to split up packets across multiple descriptors. As we don't use this feature we expect EOP to always be set. 2. The DD bit at the same position as the DD bit in the read descriptor and serves the same purpose. After this procedure is done the hardware advances RDH, possibly overflowing back to the start of the ring buffer while doing so. #figure( bfield(bits: 64, bits(64)[Packet Buffer Address], bits(63)[Header Buffer Address], bit[#flagtext("DD")], ), caption: [Advanced Receive Descriptors - Read] ) <adv_rx_read> #figure( bfield(bits: 64, bits(32)[RSS Hash], bit[#flagtext("SPH")], bits(10)[HDR_LEN], bits(4)[RSCCNT], bits(13)[Packet Type], bits(4)[RSST], bits(16)[VLAN Tag], bits(16)[PKT_LEN], bits(12)[Extended Error], bits(20)[Extended Status] ), caption: [Advanced Receive Descriptors - Write-Back] ) <adv_rx_wb> The way this exchange of buffers is implemented in verix is as follows. The driver maintains three additional things for itself: 1. A @DMA allocator that manages the buffers in the @DMA mapped packet buffer array. It can request memory in buffers of 2048 byte. This is sufficient for all packets as they cannot exceed the @MTU of 1500 bytes. 2. An array with the same amount of slots as the ring buffer. Here it saves which buffer is used for which slot in the ring buffer, as this information is not preserved by the write-back descriptor. 3. The `rx_index`, it contains the location that the driver will read the next packet from. This allows it to simply poll the DD bit of the descriptor at `rx_index` to figure out whether a packet was received. In addition to this, the driver maintains two important invariants: 1. `rx_index` is always $"RDT" + 1$. 2. It strengthens the assumption of the hardware that all descriptors in the interval $["RDH", "RDT")$ contain read descriptors to the interval $["RDH", "RDT"]$. This is valid as the descriptor at RDT is owned by the software, so it can keep it in whatever state it wants to. These two assumptions allow for the receive operation for one packet to be implemented as follows: 1. Poll until DD at `rx_index` is set to 1. 2. Keep the buffer that was used at `rx_index` to return it to the caller later. 3. Replace the buffer remembered for `rx_index` with a fresh one and write a read descriptor with the buffer address as the Packet Buffer Address and DD set to 0 to `rx_index`. 4. As the descriptor at RDT is already initialized as a read, simply advance RDT and the `rx_index`. This gives the hardware a new read descriptor to work with and maintains the second invariant. On top of this, the driver implements a batching mechanism that repeats the procedure up to a certain batch size in order to increase performance. The structure of the TX queue is the same as the RX one, except that the registers are called TDBAL, TDBAH, TDLEN, TDH, and TDT. However, the structure of the descriptors themselves is drastically different. The read ones contain a large amount of meta information this time, as can be seen in @adv_tx_read, the relevant pieces for our basic configuration are: 1. The Packet Buffer Address, it points to the data that we wish to send. 2. The PAYLEN, it contains how large the packet is as a whole. As we again only use single descriptor packets this has the same value as DTALEN. 3. The DTYP contains what kind of descriptor we are using, since the hardware also supports a legacy format. This is always set to the advanced format in our driver. 4. The DCMD is a bit set for a series of options, the relevant ones for our configuration are: 1. DEXT which indicates that we use advanced descriptors as well. 2. RS which makes the hardware report the status of the descriptor by setting the DD bit. 3. IFCS which makes the hardware compute the Ethernet CRC frame checksum for us. 4. EOP which has the same semantics as in receive descriptors. 5. The STA which has a single relevant field, the DD bit with the same semantics as in receive descriptors. The procedure to send a packet is very similar to the receive one, we insert a read descriptor at the beginning of the section that is owned by the software and advance the TDT. Eventually, the hardware picks up on the new descriptor, processes it and writes a write-back descriptor with DD set. The transmit write-back descriptors have a much simpler structure, as can be seen in @adv_tx_wb. They only contain a STA field with the same structure as STA in the read descriptors. #figure( bfield(bits: 64, bits(64)[Packet Buffer Address], bits(18)[PAYLEN], bits(6)[POPTS], bit[#flagtext("CC")], bits(3)[IDX], bits(4)[STA], bits(8)[DCMD], bits(4)[DTYP], bits(2)[#flagtext("MAC")], bits(2)[#flagtext("RSV")], bits(16)[DTALEN] ), caption: [Advanced Transmit Descriptors - Read] ) <adv_tx_read> #figure( bfield(bits: 64, bits(64)[RSV], bits(28)[RSV], bits(4)[STA] ,bits(32)[RSV] ), caption: [Advanced Transmit Descriptors - Write-Back] ) <adv_tx_wb> There is one considerable difference compared to the receive procedure, the buffers have to be returned to the @DMA allocator after the hardware marked them as processed. For this reason, the transmit procedure maintains 4 additional values: 1. The @DMA allocator that is shared with the receive part. 2. An array with buffers similar to the one in the receive part. 3. The `tx_index` which points to the next location we write a packet to. 4. The `clean_index` which marks the location of the next descriptor that we need to free. The driver only maintains one invariant on this state, `tx_index` is always equal to TDT. The procedure for transmitting a packet is unsurprisingly also very similar to the receive one: 1. "Clean" the queue by freeing as many buffers as possible. This step frees all buffers from `clean_index` to the first one that doesn't have DD set. 2. Insert the read descriptor at `tx_index`. 3. Replace the buffer that we remember for `tx_index` with the one that was just placed. 4. Advance TDT and `tx_index`. Just like the receive procedure the transmit one also implements a batching procedure on top of this by repeating steps 2-4 up to a certain batch size. === mix <mix> `mix` is our main tool in verifying the above procedures. Like the driver `mix` is logically split into three parts: 1. A model for the PCI @VBus to verify discovery. 2. A model that covers the @MMIO based initialization. 3. A model for the interactions that are supposed to happen while receiving and transmitting packets. All three of these models hook into verix by implementing the traits provided by `pc-hal` and then plugging into the APIs that are usually filled with `pc-hal-l4`. The model for the PCI @VBus is rather straightforward, as it only has to simulate a PCI bus with a single device, the Intel 82599. The Kani harness, that we use to verify this procedure, simply feeds this simulated @VBus to the discovery procedure of verix and asserts that the correct device is found. The modeling of the initialization procedure is more complicated. An uninitialized Intel 82599 in `mix` contains a state machine with 18 states. Each of these states correspond to one very fine granular step in the initialization procedure described in @intel:82599. All of the @MMIO register reads and writes are hooked up to this state machine through the `pc-hal` interfaces. As the register accesses occur, we assert that the reads and writes defined by the current initialization step occur in the correct order and with the correct values. In particular we also assert that registers from previous steps are not further modified, unless required by the step. After the procedure is done, we assert that the machine is in the final state to verify that the device has finished initialization. While both of these verification targets contain very linear code and the Kani harnesses don't make significant use of symbolic variables, we still run them through Kani instead of a normal mock test. This is because we are also interested in the additional guarantees that Kani gives us for free, in particular the pointer-related ones. The most complex model is the one for receiving and transmitting packets. Just like in @verix we begin with discussing the receive half, as the transmit one works analogously. The properties that we aim to verify for the receive procedure are: 1. If there is at least one packet present on the queue and we have memory to replace the slot we receive it. 2. If there is no packet present on the queue we don't receive anything. 3. The additional properties that Kani gives us for free, again the ones of particular interest are pointer-related ones. We begin by defining what it means for a queue state to be valid and then establish an induction-based proof to demonstrate that the queue state always remains valid. Afterwards, we establish that properties 1 and 2 always hold in a valid queue state, making them hold in general. #definition("Valid receive read descriptor")[ We call a receive read descriptor valid iff: - DD is 0 - The Header Buffer Address is 0 - The Packet Buffer Address points to valid memory for at least 1500 bytes ] <valid_adv_rx_read> #definition("Valid receive write back descriptor")[ We call a receive write back descriptor valid iff: - DD is 1 - EOP is 1 ] <valid_adv_rx_wb> Next we split up the queue into two different sections based on RDH, RDT, and `rx_index`. While our queue is implemented as a ring buffer we will not concern ourselves with the details of the ring buffer semantics in these definitions for the sake of clarity. These details are however taken care of in the Kani implementations of these definitions. #definition("Receive read section")[ The receive read section of a queue $Q$ covers the interval $Q["RDH", "RDT"]$. ] #definition("Valid receive read section")[ We call a receive read section valid, iff all the descriptors in its range are valid receive read descriptors according to @valid_adv_rx_read. ] #definition("Receive write back section")[ The receive write back section of a queue $Q$ covers the interval $Q["rx_index", "RDH")$. ] #definition("Valid receive write back section")[ We call a receive write-back section valid, iff all the descriptors in its range are valid receive write-back descriptors according to @valid_adv_rx_wb. ] In addition to this, we aim to maintain the invariant on `rx_index` that was previously mentioned in @verix. #definition("rx_index invariant")[ The `rx_index` is always $"RDT" + 1$. ] #definition("Valid receive queue")[ We call a receive queue valid iff: - Its receive read section is valid - Its receive write back section is valid - Its `rx_index` invariant is maintained ] We now establish the theorem that we always remain in a valid receive queue state as well as the properties that we are interested in, based on this result. #theorem("The initialized receive queue state is valid")[ After the initialization procedure, the receive queue is in a valid state. ] <init_rx_valid> #proof[ This is verified by a Kani proof harness. ] #theorem("The receive queue state remains valid")[ Assuming that we already are in a valid receive queue state, we always remain in a valid receive queue state after calling the receive procedure. ] <step_rx_valid> #proof[ This is verified by a Kani proof harness. ] #theorem("The driver always remains in a valid receive queue state")[ Assuming that we try to receive packets after initialization, the receive queue always remains in a valid state. ] <rx_valid> #proof[ This statement cannot directly be expressed in Kani. However, it follows from the @init_rx_valid and @step_rx_valid as those are the base case and inductive case for an induction proof of this statement. ] #theorem("The driver receives a packet if it is present")[ In any receive queue state that is reachable from the initial state, assuming that: - We have at least one free packet buffer - There is at least one packet on the queue (i.e. the write-back section is nonempty) The driver receives this packet. ] #proof[ This is verified by a Kani proof harness which assumes that we are in a valid receive queue state. This assumption is valid according to @rx_valid. ] #theorem("The driver receives no packets if the queue is empty")[ In any receive queue state that is reachable from the initial state, assuming that there are no packets on the queue (i.e. the write-back section is empty), the driver will not receive any packets. ] #proof[ This is verified by a Kani proof harness which assumes that we are in a valid receive queue state. This assumption is valid according to @rx_valid. ] While the transmit procedure does introduce additional complexity through the cleanup procedure, verifying the cleanup was not possible with Kani as we will discuss in @evaluation. Thus we limit ourselves to specifying and verifying the correctness of the transmit procedure without cleanup, stubbing it to a noop in our Kani proof harnesses. The proof ends up working very similarly to the receive one: #definition("Valid transmit read descriptor")[ We call a transmit read descriptor valid iff: - all of the features in the descriptor that are unused are disabled - DTYP is set to the advanced pattern - RS is 1 - DD is 0 - IFCS is 1 - EOP is 1 - The PAYLEN is greater than zero - The Packet Buffer Address points to valid memory for at least PAYLEN bytes ] <valid_adv_tx_read> #definition("Valid transmit write back descriptor")[ We call a transmit write-back descriptor valid iff DD is 1. ] <valid_adv_tx_wb> Next, we split up the queue into two different sections based on TDH, TDT, and `clean_index`. While this is very similar to the RX setup there are slight differences. #definition("Transmit read section")[ The transmit read section of a queue $Q$ covers the interval $Q["TDH", "TDT")$. ] #definition("Valid transmit read section")[ We call a transmit read section valid, iff all the descriptors in its range are valid transmit read descriptors according to @valid_adv_tx_read. ] #definition("Transmit write back section")[ The transmit write-back section of a queue $Q$ covers the interval $Q["clean_index", "TDH")$. ] #definition("Valid transmit write back section")[ We call a transmit write-back section valid, iff all the descriptors in its range are valid receive write-back descriptors according to @valid_adv_tx_wb. ] In addition to this, we aim to maintain two invariants on `tx_index` and `clean_index`: #definition("tx_index invariant")[ The `tx_index` is always equal to TDT. ] #definition("clean_index invariant")[ The `clean_index` is always after the `tx_index` and before TDH. ] #definition("Valid transmit queue")[ We call a transmit queue valid iff: - Its transmit read section is valid - Its transmit write-back section is valid - Its `tx_index` invariant is maintained - Its `clean_index` invariant is maintained ] The path to the proof that we always remain in a valid transmit queue state is the same as for @rx_valid, except that we use transmit instead of receive definitions: #theorem("The initialized transmit queue state is valid")[ After the initialization procedure, the transmit queue is in a valid state. ] <init_tx_valid> #proof[ This is verified by a Kani proof harness. ] #theorem("The transmit queue state remains valid")[ Assuming that we already are in a valid transmit queue state, we always remain in a valid transmit queue state after calling the receive procedure. ] <step_tx_valid> #proof[ This is verified by a Kani proof harness. ] #theorem("The driver always remains in a valid transmit queue state")[ Assuming that we try to transmit packets after initialization, the transmit queue always remains in a valid state. ] <tx_valid> #proof[ This statement is proven analogously to @rx_valid using @init_tx_valid and @step_tx_valid. This includes the limitation that the induction itself is not verified by Kani, only the base case and the step. ] #theorem("The driver transmits a packet if the queue is not full")[ In any transmit queue state that is reachable from the initial state, assuming that the queue is not full (i.e. the write back section doesn't contain the entire queue), the driver will transmit a packet successfully. ] #proof[ This is verified by a Kani proof harness which assumes that we are in a valid transmit queue state. This assumption is valid according to @tx_valid. ] #theorem("The driver doesn't transmit packets if the queue is full")[ In any transmit queue state that is reachable from the initial state, assuming that the queue is full (i.e. the write-back section does contain the entire queue), the driver will not transmit a packet. ] #proof[ This is verified by a Kani proof harness which assumes that we are in a valid transmit queue state. This assumption is valid according to @tx_valid. ] This concludes the verification of all theorems that we set out to verify about the interaction of verix with `mix`. = Evaluation <evaluation> In this chapter we evaluate the success of our implementation. We first investigate how well we were able to meet our verification goals in @eval-veri, in particular focusing on the limitations we met along the way. In order to demonstrate that our approach is viable for real-world drivers, we also perform a basic performance evaluation, comparing our performance to the one of ixy in @perf. == Verification <eval-veri> Based on the git history of `mix`, we estimate that the entire verification effort consumed about 150 man-hours. This excludes the porting effort of the driver onto L4, which did consume more time due to our inexperience with the L4 hardware framework in the beginning. While we were able to verify the majority of our proofs with Kani, we met two limitations of Kani while doing so. The first one was that Kani was seemingly unable to translate the dropping of our packet data structure into the @CBMC input format. Unlike normal data structures, we implemented a custom `Drop` functionality that returns the packet buffer to the @DMA allocator while dropping: #sourcecode[```rust pub struct Packet<'a, E, Dma, MM> where MM: pc_hal::traits::MappableMemory<Error = E, DmaSpace = Dma>, Dma: pc_hal::traits::DmaSpace, { addr_virt: *mut u8, addr_phys: usize, len: usize, pool: &'a Mempool<E, Dma, MM>, pool_entry: usize, } impl<'a, E, Dma, MM> Drop for Packet<'a, E, Dma, MM> where MM: pc_hal::traits::MappableMemory<Error = E, DmaSpace = Dma>, Dma: pc_hal::traits::DmaSpace, { fn drop(&mut self) { self.pool.free_buf(self.pool_entry); } } ```] While Kani was not inherently unable to deal with custom `Drop` implementations, it hung up while attempting to translate `self.pool.free_buf`. This is also the reason that we did not end up verifying the clean-up of the transmit queue above. Additionally, we also had to leak all of the packets in the packet receive and transmit lemmas to avoid the same bug. While this does open the possibility of a bug in the @DMA allocator the main idea of our proofs, namely that we maintain a valid queue state all of the time, remain valid. The second limitation was the size of our problem. The above approach reduces the verification problems to just one receive or transmit action on an arbitrary valid queue. While this allows us to argue about the entire state space despite only using @BMC, we were still not able to use queues that are of the same size as the real-world queues in our verification. In production, our driver uses queues with 512 slots and batch sizes up to 64. In the Kani harnesses we only managed to go up to 16 slots and a batch size of 1 before going @OOM. This is a major limitation of the guarantees that we can provide for the real-world use case. To break this boundary we attempted to use a portfolio of SAT solvers for our harnesses: - Minisat @minisat - CaDiCal @cadical-kissat, the Kani default - Kissat @cadical-kissat - Glucose @glucose These experiments were run on a cloud VM with 48GB of RAM and a time limit of 16 hours for all proof harnesses combined. As we can see in @satres, the amount of RAM did end up being the limiting factor when trying to scale the queue size up. #figure( table( columns: (auto, auto, auto, auto), [*Solver*], [*Queue Size*], [*Time (hh:mm:ss)*], [*RAM (GB)*], [Minisat], [16], [Timeout], [-], [CaDiCal], [16], [$05:04:39$], [46], [CaDiCal], [32], [-], [@OOM], [Kissat], [16], [$03:53:56$], [18], [Kissat], [32], [-], [@OOM], [Glucose], [16], [$05:42:35$], [19], [Glucose], [32], [-], [@OOM], ), caption: [Resource Consumption of different SAT solvers], ) <satres> That being said we did observe that the vast majority of memory, when trying to scale the queue size, was consumed by @CBMC itself, not the SAT solvers. This led us to trying out SMT solvers instead, since translating the problem into SMT logic instead of SAT does not require @CBMC to do so much work. Like with the SAT solvers, we attempted a portfolio of SMT solvers: - Z3 @z3 - CVC4 @cvc4 - CVC5 @cvc5 As we can see in @smtres, this approach did unfortunately not yield further progress. Using both Z3 and CVC5 as a backend for @CBMC uncovered a bug in @CBMC where it attempts to access a value in a map that is not present. While @CBMC succeeded in generating SMT instances for CVC4, all of these instances contained a bit vector declaration of size $0$ which is not accepted by CVC4. #figure( table( columns: (auto, auto, auto), [*Solver*], [*Queue Size*], [*Result*], [Z3], [16], [Crashed @CBMC], [CVC4], [16], [Crashed CVC4], [CVC5], [16], [Crashed @CBMC], ), caption: [Resource Consumption of different SMT solvers], ) <smtres> These results indicate that simply using a variety of solvers is most likely not the way to go here. Instead if: - @CBMC itself improves its RAM usage - the SMT bugs in @CBMC are fixed - Kani improves its Rust to @CBMC translation - we figure out a better way to express our proof (possibly with future Kani features like contracts) we might be able to run our harness on bigger queue sizes as well. == Performance <perf> In addition to this, we also checked that the performance of our driver running on real-world hardware is competitive with that reported for ixy. Because our Intel 82599 variant only has one cable socket, as opposed to the two socket variant used with ixy, we only benchmarked a reflecting instead of a bidirectional forwarding application. The comparison between our results, using a batch size of 64 packets, can be seen in @perf-packets. While the speed of network cables is usually measured in GBit/s, the speed of packet processing applications is measured in @Mpps. The theoretical maximum @Mpps on a single 10 GBit/s line with 64-byte packets is $14.88$ @Mpps. However, ixy can reach higher speeds than that as it is forwarding between two 10 GBit/s lines, for this reason, we look at the percentage of the maximum possible speed to draw a comparison. Note that this comparison is biased towards verix, as ixy has additional work to do for the bidirectional forwarding. An additional difference between our test setups is the CPU. While the ixy test setup ran on a Xeon E3-1230 v2 at both 3.3 and 1.7 GHz, our setup ran a Xeon D-1521 running at 2.4 GHz. As we can see in the data the CPU frequency causes a drastic performance gap between the two ixy runs. Because of this, we attribute at least the majority of the remaining $approx 12\%$ speed to tie with ixy to CPU frequency and not to the inability of the Rust compiler to optimize our code. #figure( table( columns: (auto, auto, auto, auto, auto), [*Implementation*], [*CPU Freq (GHz)*], [*Absolute (@Mpps)*], [*Max (@Mpps)*], [*Max\%*], [ixy C], [3.3], [27.4], [29.76], [92.07], [ixy.rs], [3.3], [27.4], [29.76], [92.07], [verix], [2.4], [11.9], [14.88], [79.97], [ixy C], [1.7], [17.2], [29.76], [57.80], [ixy.rs], [1.7], [17.2], [29.76], [57.80], ), caption: [Performance of ixy vs verix at a batch size of 64] ) <perf-packets> = Conclusion <conclusion> We thus conclude that we have successfully ported the driver onto L4 at a, most likely, comparable performance to ixy. On top of that, we succeeded in verifying all the properties that we set out to at a relatively small but not irrelevant scale. Our work might be extended in roughly three directions that we briefly lay out below. First off, one could attempt to turn `pc-hal` into a truly generic hardware abstraction layer, like `embedded-hal` and thus achieve portable Rust-based user space drivers across multiple operating systems. Secondly, verix does mostly exist in a vacuum right now, it is not useful to other L4 tasks that wish to interact with the network, in particular VMs. For this purpose, one could implement and potentially verify a virtio adapter that lets verix communicate with other L4 tasks to provide verified high-performance networking. Lastly, as already mentioned above, improving the queue size for which our proof can be conducted by improving @CBMC, Kani or our harnesses and thus enabling full verification of the real-world application.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-19E0.typ
typst
Apache License 2.0
#let data = ( ("KHMER SYMBOL PATHAMASAT", "So", 0), ("KHMER SYMBOL MUOY KOET", "So", 0), ("KHMER SYMBOL PII KOET", "So", 0), ("KHMER SYMBOL BEI KOET", "So", 0), ("KHMER SYMBOL BUON KOET", "So", 0), ("KHMER SYMBOL PRAM KOET", "So", 0), ("KHMER SYMBOL PRAM-MUOY KOET", "So", 0), ("KHMER SYMBOL PRAM-PII KOET", "So", 0), ("KHMER SYMBOL PRAM-BEI KOET", "So", 0), ("KHMER SYMBOL PRAM-BUON KOET", "So", 0), ("KHMER SYMBOL DAP KOET", "So", 0), ("KHMER SYMBOL DAP-MUOY KOET", "So", 0), ("KHMER SYMBOL DAP-PII KOET", "So", 0), ("KHMER SYMBOL DAP-BEI KOET", "So", 0), ("KHMER SYMBOL DAP-BUON KOET", "So", 0), ("KHMER SYMBOL DAP-PRAM KOET", "So", 0), ("KHMER SYMBOL TUTEYASAT", "So", 0), ("KHMER SYMBOL MUOY ROC", "So", 0), ("KHMER SYMBOL PII ROC", "So", 0), ("KHMER SYMBOL BEI ROC", "So", 0), ("KHMER SYMBOL BUON ROC", "So", 0), ("KHMER SYMBOL PRAM ROC", "So", 0), ("KHMER SYMBOL PRAM-MUOY ROC", "So", 0), ("KHMER SYMBOL PRAM-PII ROC", "So", 0), ("KHMER SYMBOL PRAM-BEI ROC", "So", 0), ("KHMER SYMBOL PRAM-BUON ROC", "So", 0), ("KHMER SYMBOL DAP ROC", "So", 0), ("KHMER SYMBOL DAP-MUOY ROC", "So", 0), ("KHMER SYMBOL DAP-PII ROC", "So", 0), ("KHMER SYMBOL DAP-BEI ROC", "So", 0), ("KHMER SYMBOL DAP-BUON ROC", "So", 0), ("KHMER SYMBOL DAP-PRAM ROC", "So", 0), )
https://github.com/lxl66566/my-college-files
https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/机器视觉实践/报告/8/8.typ
typst
The Unlicense
#import "../template.typ": * #show: project.with( title: "8", authors: ("absolutex",), ) = 机器视觉实践 八 == 实验目的 SIFT 特征检测与匹配 + 可视化匹配结果 == 实验代码 使用 opencv 库的 SIFT class。具体操作:先从同一张图上切成左右两半(有一定重合区域),然后使用 SIFT 算法进行特征点检测与可视化,最后合并为一张图片。 #include_code("../src/merge/__init__.py") == 实验结果与心得 #figure( image("src.jpg", width: 50%), caption: [输入图像], ) #figure( image("points.png", width: 50%), caption: [特征点可视化], ) #figure( image("result.jpg", width: 40%), caption: [输出图像], ) 经过测试,该算法只能拼接完美截取的图像,不能拼接同一地点、不同角度的相片,因为特征点的 description 不会完全一致,并且对于透视角度的变化也需要更加精确的仿射变换,而非直接拼接。因此,该算法具有一定的局限性。
https://github.com/jujimeizuo/ZJSU-typst-template
https://raw.githubusercontent.com/jujimeizuo/ZJSU-typst-template/master/template/acknowledgement.typ
typst
Apache License 2.0
#import "font.typ" : * #pagebreak() #show heading : it => { set align(center) set text(font:heiti, size: font_size.sanhao) v(12pt) it v(12pt) par(leading: 1.5em)[#text(size:0.0em)[#h(0.0em)]] } #heading(level: 1)[致 谢] #v(1em) // 设置段落格式 #set text(font: songti, size: font_size.xiaosi) #set par(justify: false, leading: 1.5em, first-line-indent: 2em) #show par: it => { it v(5pt) } #include "../contents/acknowledgement.typ"
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/lib/lib.typ
typst
Other
#import "./colors.typ": color #import "./ucpc.typ": ucpc #import "./i18n.typ" #import "./presets/presets.typ" #import "./utils/utils.typ"
https://github.com/pavelzw/moderner-cv
https://raw.githubusercontent.com/pavelzw/moderner-cv/main/template/example.typ
typst
MIT License
#import "@preview/moderner-cv:0.1.0": * #show: moderner-cv.with( name: "<NAME>", lang: "en", social: ( email: "<EMAIL>", github: "jane-doe", linkedin: "jane-doe", ), ) = Education #cv-entry( date: [2021 -- 2024], title: [M.Sc. Ophiology], employer: [Cobra Creek College], )[3.9/4.0] #cv-entry( date: [2018 -- 2021], title: [B.Sc. Herpetology], employer: [Serpentis University], )[4.0/4.0] = Experience #cv-entry( date: [4/2022 -- 7/2023], employer: [The Snake Company], title: [Snake Specialist], [#linebreak()#text(10pt, lorem(30))], ) #cv-entry( date: [4/2022 -- 7/2023], employer: [Viper Ventures], title: [Working Student], [#linebreak()#text(10pt, lorem(30))], ) = Programming Skills #cv-double-item[ Languages ][ Python ][ Technologies ][ Conda, Boa, Rattler-build ] = Languages #cv-double-item[English][Native][French][Fluent] #cv-line[Dutch][Advanced] = Hobbies #cv-list-double-item[Snake Spotting][Collecting Venom]
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/src/types/tuple.typ
typst
Other
#import "../base-type.typ": base-type #import "../assertions-util.typ": assert-base-type-array #import "../ctx.typ": z-ctx #import "../assertions-util.typ": * /// Valkyrie schema generator for an array type with positional type reqruiements. If all entries /// have the same type, see @@array. /// exact (bool): Requires a tuple to match in length /// /// -> schema #let tuple( exact: true, ..args, ) = { assert-base-type-array(args.pos()) base-type( name: "tuple", types: (type(()),), ..args.named(), ) + ( tuple-exact: exact, tuple-schema: args.pos(), handle-descendents: (self, it, ctx: z-ctx(), scope: ()) => { if (self.tuple-exact and self.tuple-schema.len() != it.len()){ (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: "Expected " + str(self.tuple-schema.len()) + " values, but got " + str(it.len()) ) } for (key, schema) in self.tuple-schema.enumerate() { it.at(key) = (schema.validate)( schema, it.at(key), ctx: ctx, scope: (..scope, str(key)), ) } it }, ) }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/comment.typ
typst
Apache License 2.0
// Test // Test: http://www.google.com /* Test */ /* /* Test */ */ /* // */ // /* */
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/ref-00.typ
typst
Other
#set heading(numbering: "1.") = Introduction <intro> See @setup. == Setup <setup> As seen in @intro, we proceed.
https://github.com/ojas-chaturvedi/NLP-Gun-Legislation
https://raw.githubusercontent.com/ojas-chaturvedi/NLP-Gun-Legislation/master/paper/main.typ
typst
MIT License
#import "@preview/charged-ieee:0.1.0": ieee #show: ieee.with( title: [ Legislative Narratives on Gun Control in the United States: A Sentiment Analysis Approach ], abstract: [ This paper explores the emotions and sentiments of congressional gun legislation in the United States through sentiment analysis, using the VADER lexicon-based model to gain insights into the polarized landscape of the gun control debate in the U.S. Focusing on a dataset of 2030 legislative texts sourced from Congress.gov and spanning from 1989 to 2023, this study first classifies each piece of legislation as either pro-control or pro-rights and then conducts sentiment analysis to get legislative sentiment scores. The findings of the sentiment analysis show a pronounced split within the legislation, with minimal neutral sentiment and a tendency towards strong positive or negative sentiments. Statistical analyses using a Mann-Whitney U Test confirm significant differences in the central tendency of sentiments between pro-control and pro-rights legislation, with the pro-control legislation having more negative sentiment and pro-rights legislation displaying more positive sentiment. This research contributes to the current understanding of the legislative landscape of gun control, highlighting the stark polarization and potential implications for policy-making and public perception. #footnote[Code: https://github.com/ojas-chaturvedi/NLP-Gun-Legislation] ], authors: (( name: "<NAME>", department: [Student], organization: [BASIS Chandler High School], location: [Chandler, Arizona], email: "<EMAIL>" ),), index-terms: ( "Natural Language Processing", "Sentiment Analysis", "Gun Control", "VADER", "Congressional Legislation", "Large Language Models", "Machine Learning", "Politics", ), bibliography: bibliography("refs.bib"), ) #show figure.caption: set align(left) #show figure.caption: set text(size: 8pt) = Introduction The gun control debate in the United States (U.S.) has deep historical roots, going back to the initial draft of the Bill of Rights and the addition of the Second Amendment. This amendment, which grants private citizens the right to keep and bear arms, has been debated for centuries, with two main sides: pro-gun rights and pro-gun control. The gun control debate, as used in this study, will refer to any act of #figure( image("assets/gun_debate.png", width: 90%), caption: [ Perception of Gun Violence as a Major Problem Increases Among Americans: A Partisan Divide from 2018 to 2023 @schaeffer_key_2023 ], ) <importance_of_debate> regulation towards the manufacture, sale, transfer, possession, modification, or use of firearms @kleck1986policy. The U.S. has become more focused on the gun control debate as a growing percentage of U.S. citizens believe that gun violence is a major problem, as shown in @importance_of_debate, and $61%$ of citizens believe it is too effortless to legally obtain a gun in the U.S. @schaeffer_key_2023. This debate mainly focuses on the impact of more guns on society and violence. In this paper, the pro-gun rights side will be referred to simply as pro-rights, and pro-gun control as pro-control. The members of the pro-rights side believe in their Right to Bear Arms stemming from the 2nd Amendment @spitzer2020politics. They focus on the end of the amendment involving the right of individuals to keep and bear arms. They argue that guns are simply tools and are only as dangerous as the person behind them. Instead, guns can be used to save potential crime victims, and therefore, arming society with more guns will lower violence rates. People most likely to commit murder or other gun-related crimes are shown to have a history of criminal careers and records @kennedy1998homicide, meaning increasing access to guns will not lead to a sudden increase in armed crimes. Additionally, the major points of the pro-rights side come from studies conducted by the Centers for Disease Control and Prevention and the National Academy of Sciences which proved that there was no evidence of any restrictions on gun ownership that had a decrease in gun-related incidents @hahn2003first, @national2005firearms, @boylan2013debate. The members on the pro-control side mainly use gun violence statistics as their argument, arguing that since guns were designed to kill people or cause harm, more guns will lead to more deaths and incidents @spitzer2020politics. While guns can be used for self-defense, the data shows that guns are more used for murders than for protection against crimes. For self-defense, advocates debate that lower or middle-damage weapons can also be used for protection and lead to less severe injuries and higher recovery rates in hospitals. Some examples of these weapons are bottles, sticks, books, chairs, and bats. However, using a gun leads to such a high jump in the severity of injuries, and the amounts of death and permanent injuries in hospitals skyrocket. They also argue that the Second Amendment is often misinterpreted by focusing on the preamble of the amendment @chemerinsky2004putting, which is about maintaining peace through state militias to protect themselves against federal tyranny. However, only $12.8%$ of pro-control advocates believe in a total ban on guns; instead, the majority of $65.7%$ favor more licensing or stringent measures on gun ownership, such as through background checks or mandatory training @smith2002public. == Importance of Sentiment Analysis One form of analysis that has not yet been majorly conducted for the gun control debate is sentiment analysis. Sentiment analysis is a subtype of Natural Language Processing (NLP), which uses algorithms on text or voice input for specific tasks. NLP has many uses, including long short-term memory, word recognition, acoustic modeling, and sentiment analysis @jain2018nlp. Sentiment analysis trains a model to understand text in ways similar to humans to determine the emotional meaning behind the text. As described in @cambria2017practical and @mercer2010emotional, emotions play an important role in rational learning and can influence opinions and attitudes, leading to the strengthening or rejection of beliefs or facts. Using sentiment analysis on the gun control debate could provide unique emotional insights into this issue, such as how people communicate about the advocacy or opposition of gun control, and what emotional appeals are used to sway others. == Literature Review The use of NLP, and more specifically sentiment analysis, is not a new field of artificial intelligence but has made some recent strides in the legal field that can outmatch humans in specific tasks, as explained in @frankenreiter2022natural. Using sentiment analysis to understand the gun control debate is another relatively unexplored field, but there are a few papers with useful contributions toward a new understanding of the debate. To understand the public sentiment in social media, @wang2016machine served as the most advantageous, as it conducted a sentiment analysis of Twitter posts surrounding the Sandy Hook school shootings in Connecticut, as major public events have been proven to bring out opinionated responses on social media. It was a major tragedy that was “unprecedented in its scale” @wang2016machine[p.~303] and led social media users to focus on and argue about the gun control debate. Using over 700k tweets and acceptable sentiment analysis practices as defined by the field, there was a peak of anti-gun or pro-control sentiment the day of the shootings, but this quickly fell back down to pre-event levels. On the other hand, there was increased pro-rights sentiment which continued for an extended period, showing that many people see public gun ownership as part of the solution, not the problem. Another study @peterson2019guns utilizes sentiment analysis on court cases in the D.C. Court of Appeals to understand judicial sentiment and opinions toward gun-related incidents, as well as potential external events that had some impact on sentiment. The D.C. Court of Appeals was chosen as D.C. is the second most liberal city in the U.S., with very strict gun regulations and a growing homicide rate. Using the pre-built VADER lexicon-based model, the analysis showed that there was a high level of neutral sentiment with very little fluctuation over time. Both of these factors combined seem “almost inhuman” @peterson2019guns but could be due to the effect of standardization of tone in legal writing. There is also a slight increase in negative sentiment as time goes on, meaning the D.C. Court of Appeals is turning more opposed to gun violence. There have been other NLP-related papers focused on the gun control debate, such as @liu2019detecting, which showed that the news mainly focuses on the polarized political parties instead of facts of the debate, but this study focuses on sentiment analysis to offer another perspective on this contentious issue. == Gap in the Field While the sentiment analysis on Twitter and the D.C. Court of Appeals provided new insights into the gun control debate, there is one source of text that hasn't been looked at by any NLP papers: congressional legislation. With the gun debate being a polarizing issue in the U.S. focused on by the majority of U.S. citizens, it leads to pressure on Congress to represent the public and address the debate through legislative actions following their party views. @bruce1998changing explains the start of Congress' involvement in this debate from the first “assault weapons ban” in 1994, and the increased focus on this issue by both the House of Representatives and the Senate. Legislation is important to look at as it directly affects the gun control debate by strengthening or lessening gun regulations. By conducting sentiment analysis, I would gain a deeper understanding of what language legislators use in legislation, as well as subtle biases that might influence legislative outcomes and public opinion. This can then be used by legislators or legal analysts to draft legislation with more favorable responses to get their policies through. == Approaches to Sentiment Analysis There are two main approaches to sentiment analysis: the lexicon-based approach and the machine-learning-based approach. As discussed in @aung2017sentiment, the lexicon-based approach, also known as the rule-based approach, is a traditional method that determines sentiment by relying on predefined rules and lexicons/dictionaries, which are filled with lists of terms and associated sentiment values. The sentiment values measure the strength of the feeling, with positive scores representing positive statements and negative scores representing negative statements. These values are then aggregated to derive the overall sentiment of the text. The lexicons can either be hand-crafted using machine learning techniques to compile a list of words and then manually assign sentiment scores or can alternatively be derived from existing general English lexicons that are downloaded and then edited to tailor the sentiment scores for specific applications, such as fitting the legislative context. Although this method is straightforward, its major drawback is its inability to detect nuances such as sarcasm due to the method getting scores by word and not accounting for the context. However, this limitation is generally not critical in the context of legislative texts, which are expected to be straightforward and unambiguous @baude_statutory, @blinova2023plain, @brannon2018statutory. The second approach is the machine learning (ML)-based approach. According to @langley1986human, ML is a subset of artificial intelligence that utilizes algorithms and statistical techniques that allow computers to execute specific tasks efficiently without direct instructions, instead depending on pattern recognition and inferential logic. ML involves the creation of mathematical models based on sample data, otherwise referred to as training data, which facilitate predictions or decisions without the need for direct programming of the tasks. Concerning sentiment analysis, there are three main ML algorithms used: deep learning, supervised learning, and unsupervised learning @lecun2015deep. These models use various algorithms to create functions that can predict output values. However, a crucial shortcoming is that it requires extensive amounts of labeled data to get accurate results, as the main purpose is to give machines the ability to analyze and learn like humans. Even with small amounts of training data, ML-based models can start overfitting, meaning they learn to perform very well on the data they have been trained on but fail to accurately predict new, unseen data @hawkins2004problem. This happens because the model ends up capturing noise and anomalies in the training data as if they were significant patterns, leading to a model that is too tailored to the specifics of its training set rather than to underlying general principles. == Project Goal Using sentiment analysis on congressional gun legislation. there are two main goals I want to address. First, I want to understand to what extent the sentiments expressed in pro-control versus pro-rights congressional gun legislation differ. This would help me understand the language used by both sides when addressing the gun debate. Next, a more general project goal is to understand what the sentiments expressed in congressional gun legislation reveal about the underlying aspects of the debate. This will involve looking at other factors using the results from the sentiment analysis to influence my new understanding. = Methodology == Data Collection As this study focuses on congressional legislation, all legislative data was sourced from Congress.gov @congressgov, the official website for legislative information. Using the advanced search function with specific search terms and filters, I could identify the legislation relevant to the gun control debate. The search term “gun” and the legislation category option were used to capture a comprehensive list of relevant legislation. To further refine my search, I specified a timeframe spanning congressional sessions 101-117 (January 3rd, 1989, to January 3rd, 2023). The starting point of 1989 was chosen because the legislation text before this session is unavailable, while the ending point in 2023 reflects the ongoing nature of the 118th congressional session, which has not yet concluded and continues to generate new legislative content. Lastly, the status of legislation was set to all options, including failed legislation, as although unsuccessful legislation lacks real-world impact, its value lies in understanding legislators' framing of issues. Even failed legislation can be beneficial as it provides additional insights from legislators. After conducting the search, I then used the bulk download feature to extract relevant data on each piece of legislation. Using this option, I received the Legislation Number, URL, Congressional Session, Title, Party of Sponsors, and Date of Introduction of each legislation, all of which have a purpose in this study. The Legislation Number serves as a unique identifier, differentiating each piece of legislation and providing information on its origin, including the chamber in which it was introduced and the type of legislation. The Date of Introduction is used later on in the analysis to determine how legislation sentiment changes over time, while the Party of Sponsors will be used to determine the side (pro-control or pro-rights) each political party is on. While the bulk download feature provides much useful information, it does not provide the actual legislative text to conduct the sentiment analysis. Therefore, I created a web scraper to use the URLs from the bulk download to retrieve the textual data. Using the Selenium Python library @nyamathulla2021review, I simulated a Google Chrome browser to open a modified URL link that points directly to the website with the legislative link and retrieve the HTML source code, which contains all the elements of the website, including the text. I then parsed the HTML code to extract the relevant legislation text using the BeautifulSoup4 Python library @uzun2018comparison. Before saving the text in a CSV file with all of the other information from the bulk download feature on Congress.gov, I created a script to pre-process the legislative text to prepare it for sentiment analysis. The script finds and removes the header and signatories' information before the actual legislation text. Next, the script conducts a series of pre-processing methods as detailed in @jianqiang2017comparison. This involves replacing grammatical contractions with their expanded forms, removing URL links, removing numbers, expanding acronyms to their full form, and removing stop words. Stop words, including “the,” “is,” and “at,” are words that are very common and have no sentiment, which is why they are removed before the sentiment analysis step. The stop words removed from the script were taken from @fox1989stop. With the text pre-processed, it is saved and ready for its classification and sentiment analysis. == Data Classification After gathering the legislative data, I classified each piece of legislation as pro-control and pro-rights using the OpenAI Generative Pre-trained Transformer (GPT) Large Language Model (LLM). LLMs are machine learning models with the capability to comprehend and generate human language text after being trained on massive collections of textual data, such as books, articles, and websites @almarie2023editorial. As shown through the experiment @bubeck2023sparks, LLMs have had phenomenal results in fields from vision to coding to math to even societal influences, such as bias, misinformation, human expertise, etc. LLMs can address a wide range of tasks, which sets them apart from earlier models limited to handling particular tasks. GPT uses a wide variety of natural language processing techniques and deep learning methods, as well as the ability to retain information from previous user interactions, to prove personalized humanized responses to each user. I specifically chose the latest OpenAI model, GPT-4, as it was trained on unparalleled amounts of data @achiam2023gpt such that many researchers believe it to be a step towards more general intelligence compared to previous AI models @bubeck2023sparks. Using the OpenAI API to access GPT-4, I gave it the following prompt: “You will be provided with a legislative text regarding firearms, and your task is to classify it as pro-control or pro-rights. Your response can be one of two things: 'control' or 'rights'.” The prompt explains the input that the model will be receiving, which is a legislative text, as well as its task to categorize it as either pro-control or pro-rights. To further improve the accuracy of the model, the model's temperature hyperparameter was changed to get the most direct output. The sampling temperature, a value from $0.0$ to $2.0$, determines how random a response from the model can be. Higher values make the output more random, while lower values are more focused and concentrated. The study @renze2024effect showed that the GPT-4 model has extremely similar performance values when changing the sampling temperature, but as I wanted the model to return only one word and nothing else as it would impact the script that saves the output, I set the temperature to $0.0$. The other hyperparameters were set to default as they wouldn't have any significant impact on the accuracy in this particular use case. The API was then given the legislation texts to classify and save in CSV files to be used later in the analysis of my results. == Sentiment Analysis With the classification of the legislation complete, the next part of the methodology is to conduct the sentiment analysis on the congressional legislation. As mentioned in the Introduction section, there are two commonly used approaches to sentiment analysis, lexicon-based and ML-based. ML-based models perform with the highest accuracy when given training data to draw patterns and conclusions. In this study, training data would consist of sample legislation taken from the overall dataset, with a dictionary of sentiment scores associated with certain words or phrases in the sample legislation. However, this would need to be done by an expert in the field who fully understands the sentiment behind the words, or otherwise, bias could be introduced into the models, leading to inaccurate results. Therefore, lexicon-based models, which require no training data as they only use a pre-defined dictionary of general sentiment in the English language, were the only viable option to generate error-free results. This study uses the Valence Aware Dictionary for sEntiment Reasoning (VADER) rule-based model introduced in @hutto2014vader. VADER was constructed as a “generalizable, valence-based, human-curated gold standard sentiment lexicon” @hutto2014vader[p.~219] which requires no training data and can easily be applied to various contexts. It is sensitive to the polarity (positive, negative, or neutral) and the intensity of the sentiments expressed. The model returns a value between $-1$, representing negative statements, and $+1$, representing positive statements. Sentiment values between $-0.05$ and $+0.05$ depict a neutral text. Additionally, VADER has real-time analysis capability without being too computationally expensive, while ML-based models require multi-core computer systems with lots of RAM for sentiment analysis. As discussed in the Introduction, there has been very limited sentiment analysis work in the legal field, or more specifically congressional legislation. Therefore, finding the best lexicon-based model needs to be centered around the general English language. The models I analyzed were compared across four main domains: social media texts and posts, New York Times opinion editorials, Rotten Tomatoes movie reviews, and technical product reviews. Compared to other frequently employed lexicons specifically Linguistic Inquiry Word Count, General Inquirer, Affective Norms for English Words, SentiWordNet, SenticNet, Word-Sense Disambiguation using WordNet, and Hu-Liu04 opinion, VADER achieves first in the social media category and second in the others. Against lexicons created by ML-oriented techniques, such as Naive Bayes, Maximum Entropy, and Support Vector Machine algorithms, VADER outperformed in three out of the four domains tested compared to the ML algorithms that are specifically trained in that domain, highlighting the high level of generalizability of the VADER model without any context-specific optimization. To evaluate VADER's performance relative to human raters, the developers conducted a correlation study assessing both sentiment polarity and intensity. In measuring intensity, VADER achieved an accuracy of $88.1%$ closely approaching the human raters' accuracy of $88.8%$. However, VADER surpassed human raters in identifying sentiment polarity, demonstrating a higher accuracy rate of $96%$ compared to the humans' $84%$. Therefore, VADER was the model chosen to conduct the sentiment analysis on legislative texts. Since the data collection step of the methodology already pre-processed the text and prepared it for sentiment analysis, the texts are now run in the VADER model and have overall sentiment scores saved in a CSV file. == Statistics To understand how the legislation sentiments differ, a statistics test must be implemented to compare the sentiments of pro-control and pro-rights legislation together. A T-test was chosen as it would help determine if there is a significant difference between the means of the two sides and how they are related. Specifically, I will be conducting a 2 independent sample T-test, as I go in with the assumption that the sentiments of the sides are independent and have no effect on each other. However, the specific version of the test will depend on whether the distribution of both samples follows the normal, or Gaussian, distribution. What this means is that the majority of sentiment scores will be close to the mean (average) score, and the overall distribution of sentiment scores will be symmetric around the mean. Additionally, the extreme values (both highly positive and highly negative sentiments) are less common and represent outlier sentiments that are not typical of the overall set of legislation. To calculate whether a distribution is normal, a Shapiro-Wilk test can be conducted to prove if the samples fit a normal distribution. With a Shapiro-Wilk test, the null hypothesis, which I can either reject or fail to reject, is that the set of data comes from a normal distribution. If the null hypothesis is rejected, the alternative hypothesis, which is that the set of data does not come from a normal distribution, is accepted. If both samples follow a normal distribution, an Independent Samples T-test will be conducted. If not, then a Mann-Whitney U test will be conducted. With both tests, the null hypothesis is always that there is no significant difference between both samples. Therefore, the null hypothesis would be that there is no difference (in terms of central tendency) in sentiments between pro-control and pro-rights congressional gun legislation. The alternative hypothesis is that there is a difference (in terms of central tendency) in sentiments between pro-control and pro-rights congressional gun legislation. In statistical hypothesis testing, the alpha value, also known as the significance level, is a threshold used to determine whether to reject the null hypothesis. The commonly used alpha value by researchers is set to $0.05$ and represents a $5%$ risk of concluding that a difference exists when there is none, which is considered an acceptable level of risk in many research studies. If the p-value from the statistical tests is lower than the alpha value, the null hypothesis is rejected, meaning the observed effect is statistically significant and likely not due to random chance. If the p-value is greater than the alpha value, I fail to reject the null hypothesis, meaning there is insufficient evidence to support the existence of a significant effect. = Results & Analysis From the data collection step of the methodology, $2030$ unique pieces of legislation were taken from the Congress.gov site and pre-processed. Of that, $62.81%$ $(1275)$ of legislative measures were primarily sponsored by the Democratic political party, and $37.19%$ $(755)$ were sponsored by the Republican party. There was only one legislation sponsored by the Independent party but it was added to the Democratic categorization as Congress.gov labeled it as “Independent Democratic”. Next, the legislative texts were classified as either pro-control or pro-rights. $69.26%$ $(1406)$ of the legislation was classified on the pro-control side, while $30.74%$ $(624)$ was on the pro-rights side. To understand which side of the gun control debate each political party takes in congressional legislation, a bar chart, as shown in @graph_bar_parties, was created to compare the policy focus of the political parties. It shows that the Democratic party has $~5.85$ times more pro-control legislation than pro-rights, meaning the Democratic party leans heavily towards the pro-control side of the gun control debate. Meanwhile, the Republican party has only $~1.38$ times more pro-rights than pro-control legislation, proving that the Republican party is more split on this issue but does still lean more towards the pro-rights side. #figure( image("assets/graph_bar_parties.svg", width: 100%), caption: [ Comparative Bar Chart of Legislative Trends: This graph presents a quantitative analysis of pro-control and pro-rights legislation as supported by the Democratic and Republican parties, revealing the contrasting priorities and policy focus within American political dynamics. ], ) <graph_bar_parties> @graph_scatterplot is a scatterplot of sentiment vs time to see how the legislation sentiment changed over time. It shows that the sentiments of the legislation are very polarized, with a lot of legislative texts having extreme values near $1.0$ and $-1.0$. The equation of the general trend line of the data, which represents how time affects the sentiment, is:\ $y = -4.18*10^{-6}x + 0.287$, where $y$ is the sentiment score and $x$ is the legislation's date of introduction. The equation shows that as time goes on, the sentiment in legislation does become more negative towards the neutral line but in extremely small increments. For the trend line to reach the full neutrality score of $0.0$, it would take over 68k years from the start date, January 3rd, 1989. #figure( image("assets/graph_scatterplot.svg", width: 100%), caption: [ Temporal Analysis of Sentiment in Congressional Gun Legislation: This scatter plot with a trend line demonstrates the fluctuation in sentiment scores of gun legislation over three decades, as evaluated by the VADER sentiment analysis, indicating the evolving emotional tone in legislative language. ], ) <graph_scatterplot> The following histogram, @graph_histogram_overall, represents the overall distribution of legislation based on sentiments to visualize the polarity of the overall legislation, which was also seen in @graph_scatterplot. It visualizes that congressional gun legislation is extremely polarized. There is barely any legislation in the neutral area, which is a sentiment value between $-0.05$ and $0.05$. Instead, the histogram has a bimodal shape, with the two peaks being at the most positive and most negative scores. Additionally, the variance of the histogram, which tells us how spread out a set of data is, is $0.8617140$, meaning the data is very spread out. #figure( image("assets/graph_histogram_overall.svg", width: 100%), caption: [ Histogram of Congressional Gun Legislation Sentiment: This histogram provides a distribution of sentiment scores across all gun-related legislation, as measured by VADER sentiment analysis, to reflect the general emotional tone within legislative language. ], ) <graph_histogram_overall> While @graph_histogram_overall shows the overall legislation polarity, the main purpose of the study is to understand how the sentiment differs in legislation from the two sides of the gun control debate. This was done by creating histograms for legislation from each side to see how they compare against each other as shown in @graph_histogram_control and @graph_histogram_rights. #figure( image("assets/graph_histogram_control.svg", width: 100%), caption: [ Histogram of Pro-Control Congressional Gun Legislation Sentiment: This histogram provides a distribution of sentiment scores within pro-control gun-related legislation, as measured by VADER sentiment analysis, to reflect the emotional tone in the language of gun control advocacy. ], ) <graph_histogram_control> #figure( image("assets/graph_histogram_rights.svg", width: 100%), caption: [ Histogram of Pro-Rights Congressional Gun Legislation Sentiment: This histogram provides a distribution of sentiment scores within pro-rights gun-related legislation, as measured by VADER sentiment analysis, to reflect the emotional tone in the language of gun rights advocacy. ], ) <graph_histogram_rights> Both of these histograms are bimodal, with their peaks being at the two ends of the sentiment scores. The variances for the pro-control and pro-rights data are $0.8762$ and $0.7305$, respectively. This difference in variance between the two histograms is significant, indicating that while both pro-control and pro-rights legislative texts are polarized, the pro-control texts exhibit a slightly higher degree of spread in sentiment values. This higher variance suggests that the language used in pro-control legislation is more diverse in its emotional expression compared to pro-rights texts. Essentially, pro-control advocates use a wider range of sentiment, potentially reflecting a more varied approach in how they present their arguments or address the issue. Conversely, the lower variance in the pro-rights texts may imply a more consistent use of language. This could indicate a more unified stance or a narrower range of emotional appeal in the rhetoric of gun rights advocacy. The bimodal distributions in both histograms affirm that both sides of the debate strongly emphasize positive and negative sentiments, with little room for neutral language. This polarization could be a reflection of the intense and often contentious nature of the gun control debate in the U.S. A Shapiro-Wilk test on both sets of data, pro-control & pro-rights legislation sentiment, returns a p-value of $<0.001$ for both samples. As the p-values are lower than the alpha value of $0.05$, the null hypothesis, which was that the sets of data fit a normal distribution, is rejected. Since the samples are not normal, a Mann-Whitney U test is used to determine a significant difference and relation between both groups. The test also results in a p-value of $<0.001$, meaning the null hypothesis is rejected. Therefore, the statistics show that there is a difference (in terms of central tendency) in sentiments between the pro-control and pro-rights congressional gun legislation. This can also be seen in @graph_histogram_control & @graph_histogram_rights, as the pro-control histogram has more legislation with an overall negative sentiment score, but the pro-rights histogram has the opposite with more legislation with positive sentiment scores. = Discussion & Conclusion == Implications This project gave additional insights into the gun control debate using a sentiment analysis approach with the VADER lexicon-based model. It found that there is a significant difference between the emotions in legislation from either side. The histograms of pro-control and pro-rights legislation in @graph_histogram_control and @graph_histogram_rights show that the pro-control legislation has more negative legislation sentiment, while pro-rights legislation has more positive legislation sentiment. The analysis of the variances in sentiment provided insights into the rhetorical strategies employed by both sides. It shows that pro-control legislation has a broader range of emotional expression compared to the more consistent pro-rights rhetoric, potentially affecting public perception and policy discussions. The study also revealed a stark polarization in legislative sentiment on gun control, closely aligning with partisan divisions—Democrats favoring pro-control and Republicans displaying a slight preference for pro-rights. Lastly, the scatterplot in @graph_scatterplot shows us that, over time, legislation becomes more negative in sentiment but in infinitesimally small values, requiring decades for it to reach full neutrality. Following further analysis, this study can be implemented by legislators to foster more bipartisan support for legislation by focusing on common ground that appeals to both the positive and negative sentiment areas. Legal analysts could also use this research as part of a predictive framework to anticipate the likelihood of legislation passing, as this could influence legal advisories, compliance activities, and risk assessments for businesses and NGOs. Lastly, understanding sentiment could assist in drafting legislation to receive a certain response from the rest of Congress and the public. == Limitations Although this study provides significant contributions to the field, it does have potential limitations that affect the understanding of the analysis. One of the primary constraints comes from the VADER model. Its lexicon, while extensive and known for its generalizability & high performance in many fields, does have inaccuracies in sentiment analysis. Since the VADER lexicon was created for the general English language and not specifically for the congressional legislative context, there may be words or phrases that have different sentiments between general and legislative-specific language. This would affect the sentiment scores used in the analysis, but due to the sheer length of legislation and the individual word sentiment scores being aggregated for one overall score, this limitation shouldn't majorly impact the sentiment score for individual legislation. Additionally, another constraint comes from the search term used during the data collection phase of the methodology. The term “gun” may not have captured all relevant legislation, potentially omitting relevant texts that use different terminology such as “firearm” or “assault rifles”. However, there is a very small chance that legislation related to the gun control debate would not include the term “gun”, meaning this constraint would have a very minimal impact on this study. Another limitation is the inclusion of duplicate legislation in the dataset, which could skew the results by adding multiple of the same sentiment scores to the results. Duplicate legislation can come from legislation entering both chambers of Congress, thus appearing duplicated. However, amendments and revisions from each house often modify the text slightly, affecting sentiment analysis, and therefore, these duplicates cannot just be removed. Nevertheless, a comparison of the titles of the legislation shows that only $9%$ of legislation is duplicated, which isn't much and shouldn't have a major impact on the overall analysis. == Future Directions Despite the findings and implications of this study, there is still much more to explore regarding the gun control debate. As shown in the analysis of legislation sentiment vs time in @graph_scatterplot, the trend line shows that legislation is becoming increasingly negative, yet in slight increments. However, there is no way to confirm whether or not the legislation sentiment is becoming neutral and will stick near the x-axis, or will continue past it and increasingly become more negative. Therefore, this study should be continuously replicated in the future after the conclusion of each congressional session to gain a better sense of how sentiment changes over time. Additionally, future research could work to create an extensive training dataset to create various ML-based models for cross-validation of the results of this study. Using the help of an expert in congressional legislation, the training dataset could include a small percentage of legislation from each congressional session and then be labeled with sentiment scores (both polarity and intensity). With the training dataset, advanced ML-based models, such as those mentioned in the Introduction, can be implemented for sentiment analysis and then compared to the VADER sentiment scores to find any major differences that could lead to a new understanding. To learn more about the gun control debate, a thematic analysis could be implemented on congressional gun legislation. A thematic analysis would explain the specific themes or points brought up in the legislation, and can then be used in Congress to find common ground for bipartisan support to improve the gun violence situation. Lastly, the analysis does not account for the influence of media coverage, public opinion, or external political events that could also affect legislative sentiment. These factors should be considered when interpreting the findings and could be addressed in future research to enhance the understanding of sentiment trends in congressional gun legislation.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/grid-4_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that fr columns use the correct base. #grid( columns: (1fr,) * 4, rows: (1cm,), rect(width: 50%, fill: conifer), rect(width: 50%, fill: forest), rect(width: 50%, fill: conifer), rect(width: 50%, fill: forest), )