repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/017%20-%20Dragons%20of%20Tarkir/001_A%20Tarkir%20of%20Dragons.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "A Tarkir of Dragons", set_name: "Dragons of Tarkir", story_date: datetime(day: 25, month: 02, year: 2015), author: "<NAME>", doc ) #emph[The Planeswalker and dragon mage, Sarkhan Vol, left his time to travel back more than 1,200 years into Tarkir's past and save Ugin, the Spirit Dragon from death. By saving Ugin, Sarkhan ensured the dragon tempests would continue to thrive on Tarkir, and thus he saved the dragons—or so he hopes. After he created a magical, protective hedron cocoon around the fallen Ugin, Sarkhan was ripped back through time to his present. Now he is left to wonder how much change his actions caused. How many ripples propagated out across Tarkir's history? And who will share this new world with him? Who will glory in a Tarkir of dragons?] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Sarkhan Vol was going home. Yes. He felt it with utter certainty as he was whisked through the endless eternities. Whatever forces had thrust him back in time had now conspired to return him to—where was he going? The future? The present? The now? It did not matter what it was called, it was home. Time passed him by, countless years, untold centuries; the history of Tarkir tore through him in the matter of a single heartbeat. As solid ground coalesced beneath his feet and the world took shape around him, Sarkhan breathed for the first time a breath of this new Tarkir of now. The depths of his stomach stirred with the fullness of it. He was standing before the hedron cocoon, exactly where he had been a mere moment before—no, hundreds, or perhaps thousands of years before. If he had been a man of lesser awareness, if he had not understood the chain of time, he might have guessed that he had never left; he might have surmised that he'd had an episode of vertigo or that he'd simply lost his bearings. But even then, even if he was not in tune with temporal forces and the flow of history, he could not have missed the clues on the cocoon itself that spoke of the passage of innumerable years. #figure(image("001_A Tarkir of Dragons/01.jpg", width: 100%), caption: [Crucible of the Spirit Dragon | Art by Jung Park], supplement: none, numbering: none) Sheets of ice covered the sides of the hedrons, icicles hung from the points and edges, snow had collected in the ruins, and there were grooves and cracks in the exposed portions of rock, worn by time. The evidence was all there, the truth was unavoidable: time and history had come and gone in a blink of Sarkhan's eyes. "Ugin." Sarkhan spoke the Spirit Dragon's name, his voice quavering, as though testing its credibility in this new time. "I'm here, Ugin. I'm here." He reached out to the cocoon with trembling fingers. For a moment the only answer was the whistling of the wind. Then a bellow sounded from above. Sarkhan turned his eyes to the sky and a burst of giddiness erupted in his chest—an entire herd! Dragons were circling overhead. "Ha ha!" he cried. "Look! Just look at them!" He had not been wrong to hope. It had happened. It had worked. The hedron shard that had saved Ugin's life had saved the dragons of Tarkir. Tears sprang to Sarkhan's eyes, wet and hot. Real. This was real. "You have to see this!" Sarkhan called to Ugin. "I've done it! The chain of time has been reforged!" But the Spirit Dragon did not stir. No matter. Sarkhan was here. He tossed his head back and let out a whooping cry that blasted across the land. As the cry echoed back to him, it turned into a roar, a guttural roar, a dragon's roar. And in his dragon form, Sarkhan Vol took to the sky. He shot up, up, up, gaining altitude so quickly that the skin of his snout pressed back into his eyes. He careened headlong into the herd of dragons above, buffeting off their thick hides, weaving around them, awash in the turbulence kicked up by their heaving wings. He recognized the dragons; they had antlers and broad shoulders. They belonged to the brood that Yasova and her sabertooth had attacked—when? A millennium ago? Yasova. Tenacious, powerful Yasova. What she had done was not her fault. She had played her part just like him. He could not be mad, not at her, not at anyone, not anymore. No, everything felt too right. His head was clear, his thoughts were his own, and his Tarkir was full of dragons. Dragons! #figure(image("001_A Tarkir of Dragons/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Sarkhan wanted to grab the beast at his side, he wanted to shake her and say, "You're here! You're here on Tarkir because I made it so!" But his dragon lips could not form the words, so instead he turned to the dragon beside him and bellowed with all of his might. Her great eye blinked at him. Did she understand? Could she understand how wonderful, how amazing, how impossible this was? He trumpeted again and again as he zigzagged through the herd. His energy was like a spark in a haystack, igniting the other dragons around him. They joined Sarkhan's voice, meeting him roar for deafening roar. One exhale charged the next inhale, picking up intensity, volume, and speed as it went, growing into an all-consuming force that took hold of every dragon in the herd and united them in one moment, one collective breath. They roared as one, and all of Tarkir trembled. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) As Sarkhan soared with his adopted herd, he took in the new world of Tarkir. There was so much he recognized, so much he knew, and yet it was all so different. He could see other herds in the distance, some that looked the same as the antlered herd he flew with, and others that were utterly different. There were sleek dragons that glided like feathers on the currents; there were dragons with thick armored scales that flew far below and close together. And there were those that acted more like serpents, spending their time in great temples in the marshes, which Sarkhan only glimpsed from above. The land itself had changed, too. Where once there had been ruins and piles of dragon bones, now there were fields and forests. The snowy tundra that in a different time was blanketed in endless white was now only partially covered; large swaths of it were charred black. Dragonfire! Sarkhan dropped into a spiraling dive of glee, letting the aroma of burnt undergrowth flood his nostrils. This land had changed because there were dragons here! #figure(image("001_A Tarkir of Dragons/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) As he shot back up into the herd, he was greeted by nothing less than the sight of a dragon tempest rupturing before him. From it emerged more dragons. Sarkhan bellowed in ecstasy. The herd bellowed back. And the new fledglings joined the cry. It was glorious. It was everything Sarkhan had ever wanted. He could live like this forever. What a world! What a time! What perfection. But Sarkhan's perfect moment was shattered by the sudden, grating peal of a bell. The sharp, metallic sound cut through the herd like a knife, ringing out again and again. Dragons scattered, breaking off and away, issuing urgent cries. Sarkhan was battered about by snouts and wings and thick, kicking legs. He could sense their distress and could not help but feel it too. But a bell, he thought, should not be the cause of such upset in a herd of mighty dragons. He glimpsed down in the direction of the intrusive sound. There on the ground, standing in the middle of what looked very much like a sparse Mardu encampment, was a figure striking a bell. A mere human. Or was it an orc? Even so, what kind of threat could such an insignificant creature pose to a herd like this? His answer came the very next moment. Like a spout of volcanic magma, a stream of dragons erupted up out of the encampment, shooting into the sky. They beat their wings in time with the bell—the bell that a Mardu orc was striking. Even in his state of alarm, Sarkhan thrilled at this. Dragons and clan members living in the same encampment; dragons and clan members working together! It was just as it was supposed to be. But he could not rejoice for long, for the dragons of this Mardu herd, a fifth unique brood he had not yet seen, were faster than a barrage of flaming arrows. The attack was led by an ancient and powerful dragon with a leathery fringe that encircled her face, and horns that lined her snout and back. She was made for speed, her body agile and taut, her wings strong…and she was barreling straight at Sarkhan. #figure(image("001_A Tarkir of Dragons/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) For an instant, time stood still. Sarkhan looked into the great dragon's eyes. He recognized her face, the shape of her snout, the cut of her jaw. It was so familiar. But how could it be? He had never seen this dragon before. He couldn't have. And yet…as he squinted down at her, the clanging of the bell rattled an image out of his mind. It was a memory from the time before. For the space of a heartbeat Sarkhan could see two Tarkirs, one inlaid over the other. Shooting toward him was both the dragon of this now, flesh and blood and scales, and the dragon of the now that had been lost forever, nothing more than an empty, rotting skull, a khan's throne. That is why he knew this dragon. Oh how the world had changed! #figure(image("001_A Tarkir of Dragons/05.jpg", width: 100%), caption: [Dragon Throne of Tarkir | Art by Daarken], supplement: none, numbering: none) A fierce roar collapsed the two histories back into one, and Sarkhan shook free of the thrall just in time to dart out of the path of the ancient dragon. As she led her herd upward, he careened down. He was small enough to be missed, small enough to be ignored, and for that he was grateful. He did not wish to do battle with the ancient dragon. Heart pounding and mind reeling, Sarkhan landed and took his human form at the edge of the encampment. He sought shelter under the protection of a rocky outcropping as the dragons of the two herds clashed in the sky above him. Listening to the echoes of their bodies cracking, he gloried in the dawning realization of what he had truly done. These dragons were only here because of his actions. Even the mightiest among them owed her existence to Sarkhan Vol. He had made this Tarkir. He had made it and it was glorious. "Intruder! Intruder!" Sarkhan started at the voice. It came from below rather than above. "Intruder! Attack!" An angry goblin charged out of the bush to his right…a goblin that Sarkhan recognized. "Ankle Shanker?" She was dressed differently than he remembered. She didn't wear a cape, and she brandished a thick vial rather than her blade, but it was her. It was definitely her! Sarkhan's heart soared at seeing her—at seeing her in this time, in his new Tarkir, and alive! "Ankle Shanker!" Sarkhan ran out from under the outcropping and opened his arms so that the raging goblin hurtled into his embrace. He could not contain his delight. He shook her enthusiastically. "You're here! You're alive! Just like the dragon." "Put down! Madman! Madman! Put down!" "Was it a dragon that saved you? It must have been! Or was it that your life was never threatened at all in this time?" "A threat! A threat on life!" Ankle Shanker spat at Sarkhan, her hot saliva dripped down his cheek. "Madman life will end! Unhand Vial Smasher! Now!" "Your name! Ha ha! Even your name has changed!" Sarkhan's mind struggled to make sense of it all. A million changes, differences, details—"Wait. You say I'm an intruder? You don't know me?" "Intruder!" Ankle Shanker, known as Vial Smasher, bit him. She dug her thick, flat teeth into the skin of Sarkhan's wrist, grinding down with the force of her jaws. He threw her away and cried out in pain, but his cry turned into a laugh, a joyous laugh. "You are even stronger than you were before. You're stronger and you're alive!" "Manic! Raver! Stay back or Smasher smash!" Vial Smasher rattled the vial she was holding. The hairs on her arms stood on end as though electrically charged. Sarkhan realized they were charged by the glowing liquid in the vial. He recognized it. She was holding a vial of— "Dragonfire," Sarkhan whispered. "They share it with you? The dragons give their fire to the clan? That's perfect. It's all so perfect!" "Smasher smash!" She wound up. "Stop!" Sarkhan said, but too late. The goblin launched the vial. #figure(image("001_A Tarkir of Dragons/06.jpg", width: 100%), caption: [], supplement: none, numbering: none) Art by <NAME> As it shattered on the ground, Sarkhan transformed into a dragon and dove in front of Vial Smasher, spreading his wings to form a protective shield around her. Her outcries hushed immediately and Sarkhan could feel her trembling beneath him. He looked down at her as he transformed back into a man. She was in a prone position, bowing before him. "Dragonman." She glanced up at him and scampered back. "No smash. Smasher no smash dragonman. Smasher didn't know. Smasher sorry. Don't hurt Smasher. " She backed away, her eyes darting around, looking for an escape. "What's going on down here?" The booming voice of an orc made them both turn. "I saw a flash of dragonfire, but I know that all the dragons are in the sky. What have I told you about wasting—" The orc broke off at seeing Sarkhan. And Sarkhan's breath caught in his throat. #emph[Zurgo] Zurgo grunted. "Don't tell me, Vial Breaker, that you wasted dragonfire on this pathetic excuse for a raider." "Smasher! Vial #emph[Smasher,] not Breaker! Zurgo Bellstriker know." The goblin balled her fist and growled. "Zurgo Bellstriker bad orc. Bad." "Bellstriker?" Sarkhan balked. "Zurgo, Bellstriker?" He looked from Zurgo to Vial Smasher and back again. "He is—you are the #emph[bell-striker] ?" As his eyes alighted on Zurgo's sword he saw this was true. The blade was dull, not from war but from striking a great metal bell. Zurgo was the figure Sarkhan had seen from above. "Ha!" Sarkhan cried. "You dare laugh at me, wretch?" Sarkhan ran his fingers through his hair, piecing it all together. "But you were Helmsmasher, you were—" "Not Smasher. He Bellstriker," the goblin interrupted. She pointed to herself. "I Smasher." Sarkhan ignored her. He searched Zurgo's face. "You once led the Mardu." "Enough!" Zurgo bellowed. "Enough of your disrespect." "Mardu who?" Vial Smasher asked. "Your clan. Our clan of warriors," Sarkhan said. "Who is khan now?" "No khan! No say khan!" The goblin launched herself at Sarkhan and threw her hand over his mouth. "Kolaghan Dragonlord kill khan-sayers." "Dragonlords," Sarkhan echoed through Vial Smasher's hot hand. She was clinging to his side now. "There are dragonlords and no khans?" "No say khan!" the goblin pleaded. "Get off him, Breaker," Zurgo spat, swatting the goblin away. "I say let the man speak if he wants death. Go ahead, stranger, call your words to the sky. Make your affront to Kolaghan herself." #figure(image("001_A Tarkir of Dragons/07.jpg", width: 100%), caption: [Art by <NAME>ville], supplement: none, numbering: none) An unsettling feeling tugged at the corner of Sarkhan's gut. "You think I'm a stranger too?" he asked. "You don't know me, Zurgo?" "Why would I know a lowly vagrant?" "I am not a vagrant. I am—how could you not remember? How could you not know? I am Sarkhan Vol!" "Don't say khan, don't say khan." Vial Smasher covered her long ears and rocked back and forth. "Vol?" Zurgo laughed. "Is that a feeble Atarka name?" "No, it's my name." Sarkhan's voice was quiet. "Don't you know it at all?" There was no recognition whatsoever on the orc's face. How could this be? Things were different, yes, but how different? How could no one know him? Was it possible that these were Sarkhan's first moments here in this time? When he made a new now, had his past been lost? "Vol is a pathetic name for a pathetic man. Vol should fall easily." Sarkhan heard Zurgo's words as though from a very distant place; his mind was too busy combing through the knots of time, parsing the implications of what he had done. Zurgo raised his blade just as Sarkhan unthinkingly took his dragon form. Sarkhan's thoughts briefly settled on the dull, useless edge of the orc's blade. It was a bell-striker's blade. "But you were once khan," he said as he transformed. Or perhaps he merely thought the words, for Vial Smasher did not shout. Both orc and goblin stood in paralyzed stillness as Sarkhan Vol launched himself into the sky. It wasn't until he pushed up to crest the first mountain that he heard the peal of Zurgo Bellstriker's bell in the far distance. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Disjointed thoughts tumbled through Sarkhan's mind as he heaved himself through Tarkir's sky. This was his Tarkir, the Tarkir he had made, and yet no one knew him here. It was as though he did not exist, as though he had no history. His stomach lurched and he thought for a moment that he would be sick there in the sky. But he swallowed it and attempted to rein in his bumbling thoughts. Did it matter? Did it truly matter that he was not known? He was here now, was he not? And Tarkir was perfect. That was what mattered. Even if no one here knew him, even if he himself did not have a history, Tarkir had a brilliant one because he had made it so. Dragons had survived—no, they had flourished. And so too had the clans; Vial Smasher was proof of that. She had lived here when in another time she had met her death. At that thought, Sarkhan's breath caught and his wings ceased their flapping. If Vial Smasher's fate had been altered, and Zurgo's, and the great dragon's too, then the same could be true for another. The same could be true for…#emph[Narset] . Yes! Narset! Of course. It was obvious. Why hadn't he thought of it before? Zurgo would not have killed Narset in this now, not with his dull, useless sword. Their paths would never have crossed at the chasm. She would never have led Sarkhan there. She would never have had to lay down her life. She would be here. She would be alive! Sarkhan pulled himself out of his paralyzed dive. #emph[Narset! ] He barked the name out across the land. This world, the wonder, the balance, the perfection, Narset would know it. She would rejoice in it. And he would tell her that he had made it so. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Sarkhan hastened to the Jeskai territory. He believed he would find Narset there, for in another time she had been khan of all that stretched along the river. But when he arrived, he learned that a dragon called Ojutai ruled in her stead. Dragons seemed to rule everywhere in this now; that was as it should be. Sarkhan learned from Ojutai's followers that the sleek, agile dragon was the oldest and wisest being on all of Tarkir. Those who lived in Ojutai's territory called him the Great Teacher and held him in high esteem, longing for his enlightenment. In turn, the dragon respected his students. He taught them what he knew, sharing his insight and his wisdom to help each of them grow stronger and more cunning. Sarkhan knew that of all of Ojutai's pupils, Narset would be the best. She would have risen to the top. And of course, he was right. He followed word of her name up and up, ever closer to Ojutai's roost. The dragon's perch was at the top of a tower, which Sarkhan recognized as a stronghold, but in this time was called Dragon's Eye Sanctuary. The closer he got to the top, the more right everything felt. This was where she must be; Narset at the highest perch in the land; Narset in the sky with the dragons. His insides stirred at the thought of it. #figure(image("001_A Tarkir of Dragons/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) When Sarkhan reached the topmost room, he thought it to be empty at first. But his eyes caught a slight movement, the heaving of a chest for a shallow breath. There was a figure sitting in a meditative pose, still as a statue, on the far side of the room. He nearly raced across the floor to embrace her, but then he realized the figure was not Narset. He came up short. "Who are you?" The words came out without his thinking. The figure lifted his head to the light and Sarkhan could make out the man's features. He was a perfect specimen—everything a human trained by dragons should be. Power radiated off him. "I am <NAME>." The man's voice was as smooth as the skin on his head. "And you are a student come to seek knowledge and wisdom. You have come a long way, traveler. Welcome to Dragon's Eye Sanctuary." "No, I—I'm not a student. I've come to find her. Where is she?" Sarkhan glanced about the room for a second time, but there was nowhere to hide in the clean, open space. "Is there somewhere higher?" He looked up. "Higher?" Master Taigam chuckled. "There is nothing higher except Ojutai himself." "Then where is Narset?" Master Taigam's eyes widened ever so slightly and then slowly closed. They remained that way for more moments than felt comfortable. Sarkhan's excitement turned to question and then to worry. He waited until he could contain himself no longer. "Do you know her? Narset? I have to find her. She will understand. She'll understand everything." Master Taigam's eyes opened even more slowly than they had closed and he tilted his head up ever so slightly so as to look Sarkhan in the eye. "Narset is not welcome in the Dragon's Eye. She was a heretic, and for that she was punished to full extent of the law. Do not look for her here. She is long gone." "Gone? Where? You must tell me." Master Taigam let out a controlled breath. "Narset is no more." "No more?" The blood drained from Sarkhan's head, he staggered. "But that can't be." "It is as it is." Master Taigam's lip twitched. "She met her fate. And any who seek out a heretic shall meet the same." "She is not a heretic. She is—she is everything." "I will hear no more." Master Taigam waved his hand in a gesture that was so strong that the force of it pushed Sarkhan toward the door. He gripped the wall, straining to hold on against Master Taigam's power. "You don't understand. She has to be here. This is a world for her. A world of dragons—for her!" "Leave, heretic." With another wave of Master Taigam's hand, Sarkhan was thrust through the door and sent tumbling down the stairs. #figure(image("001_A Tarkir of Dragons/09.jpg", width: 100%), caption: [Art by David Gaillet], supplement: none, numbering: none) Sarkhan's mind reeled as his legs flailed, taking him down, down, down. He did not know what force was pushing him now—Master Taigam or his fear. This could not be. Narset was not supposed to die. Not this time. Not on this Tarkir. There were dragons. He careened out into the light, fumbling his way through a marketplace. This could not be. "No." He shook his head, pulling at his hair. "No, no, no." He began to run. He had to move. He had to get away. He had to change this. "No!" With a cry, Sarkhan shifted into his dragon form and took flight. If Vial Smasher was alive, if long-dead dragons still flew in the sky, if Zurgo the khan was a bell-striker, Narset must be here. She had to be here. As he flew over Tarkir, Sarkhan could not look down. The world that had seemed so perfect before, so glorious, was now marred and ruined. Without her, this place was nothing. Sarkhan roared in rage. How could fate have allowed for this? The chain was supposed to be reforged. His breath, that had saved Ugin, was supposed to— #emph[Ugin.] Sarkhan's trembling mind clutched at the thought of the Spirit Dragon. Ugin would know. Ugin, whose voice had led Sarkhan across time. Ugin, whose power flourished on this now. Ugin would know. Yes. Ugin would know how to make this right. Sarkhan thrust his wings with new resolve. It was time to wake the Spirit Dragon.
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/intermediate/content-stateful-3.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book.page.with(title: "维护文档状态 —— 制作页眉标题法二") 在上一节(法一)中,我们仅靠「#typst-func("query")」函数就完成制作所要求页眉的功能。 思考下面函数: ```typ #let get-heading-at-page(loc) = { let (headings, last-heading) = calc-headings( query(heading.where(level: 2), loc)) headings.at(loc.page() - 1, default: last-heading) } ``` 对于每个页面,它都运行```typc query(heading.where(level: 2), loc)```。显然每页的「位置」信息,即`loc`对应不相同。因此: 1. 它会*每页*都重新执行一遍`heading.where(level: 2)`查询。 2. 同时,每次`query`都是对*全文档的线性扫描*。 夸张来讲,假设你有一千页文档,文档中包含上千个二级标题;那么他将会使得你的每次标题更新都触发上百万次迭代。虽然Typst很快,但这上百万次迭代将会使得包含这种页眉的文档难以*实时预览*。 那么有没有一种方法避免这种全文档扫描呢? 本节将介绍法二,它基于「#typst-func("state")」函数,持续维护页眉状态。 Typst文档可以很高效,但有些人写出的Typst代码更高效。本节所介绍的法二,让我们变得更接近这种人。 == 「state」函数<grammar-state> `state`接收一个名称,并创建该名称对应*全局*唯一的状态变量。 #code(```typ #state("my-state", 1) ```) 你可以使用```typc state.display()```函数展示其「内容」: #code(```typ #let s1 = state("my-state", 1) s1: #s1.display() ```) 你可以使用```typc state.update()```方法更新其状态。`update`函数接收一个「回调函数」,该回调函数接收`state`在某时刻的状态,并返回对应下一时刻的状态: #let s = state("my-state", 1) #code(```typ #let s1 = state("my-state", 1) s1: #s1.display() \ #s1.update(it => it + 1) s1: #s1.display() ```) #s.update(it => 1) 所有的相同名称的内容将会共享更新: #code(```typ #let s1 = state("my-state", 1) s1: #s1.display() \ #let s2 = state("my-state", 1) s1: #s1.display(), s2: #s2.display() \ #s2.update(it => it + 1) s1: #s1.display(), s2: #s2.display() ```) 同时,请注意状态的*全局*特性,即便处于不同文件、不同库的状态,只要字符串对应相同,那么其都会共享更新。 这提示我们需要在不同的文件之间维护全局状态的名称唯一性。 另一个需要注意的是,`state`允许指定一个默认值,但是一个良好的状态设置必须保持不同文件之间的默认值相同。如下所示: #s.update(it => 1) #code(```typ #let s1 = state("my-state", 1) s1: #s1.display() \ #let s2 = state("my-state", 2) s1: #s1.display(), s2: #s2.display() \ #s2.update(it => it + 1) s1: #s1.display(), s2: #s2.display() ```) 尽管`s2`指定了状态的默认值为`2`,因为之前已经在文档中创建了该状态,默认值并不会应用。请注意:你不应该利用这个特性,该特性是Typst中的「未定义行为」。 == 「state.update」也是「内容」 一个值得注意的地方是,似乎与#typst-func("locate")函数相似,#typst-func("state.update")也接收一个闭包。 事实上,与#typst-func("locate")函数相同,#typst-func("state.update")也具备延迟执行的特性。 让我们检查下列脚本的输出结果: #s.update(it => 1) #code(```typ #let s1 = state("my-state", 1) #((s1.update(it => it + 1), ) * 3).join() s1: #s1.display() ```) 这告诉我们下面一件事情,当`eval`阶段结束时,其对应产生下面的一段内容: ```typc ( state("my-state", 1), state("my-state").update(it => it + 1), state("my-state").update(it => it + 1), state("my-state").update(it => it + 1), ) ``` 排版引擎会按照*深度优先的顺序*遍历你的内容,从文档的开始位置逐渐*积累*状态。 这将帮助我们在多文件之间协助完成状态的更新与计算。 假设我们有两个文件`s1.typ`和`s2.typ`,文件的内容分别是: ```typ // s1.typ #let s1 = state("my-state", (1, )) #s1.update(it => it + (3, )) // s2.typ #let s1 = state("my-state", (2, )) #s1.update(it => it + (4, )) #s1.update(it => it + (5, )) ``` 并且我们在`main.typ`中引入了上述两个文件: ```typc #include "s1.typ" #include "s2.typ" ``` 那么根据我们的经验,主文件内容其实对应为: ```typc { state("my-state", (1, )), state("my-state", it => it + (3, )), } + { state("my-state", (2, )), state("my-state", it => it + (4, )), state("my-state", it => it + (5, )), } ``` 我们按照顺序执行状态更新,则状态依次变为: ```typc { (1, ); (1, 3, ); } { (1, 3, ); (1, 3, 4, ); (1, 3, 4, 5, ); } ``` == 查询特定时间点的「状态」 Typst提供两个方法查询特定时间点的「状态」: 一个方法是```typc state.at(loc)```方法,其接收一个「位置」,返回在该位置对应的状态「值」。 另一个方法是```typc state.final(loc)```方法,其接收一个「位置」,返回在文档结束一切排版时对应的状态「值」。 熟悉的剧情再次发生了。让我们回想之前介绍#typst-func("query")时讲述的知识点。 这两个方法都只能在#typst-func("locate")内部调用。对于#typst-func("state.at")方法,其「位置」参数是有用的;对于#typst-func("state.final")方法,其「位置」参数仅仅作为「哑参数」。 我们回想上一小节,由于文档的每个位置「状态」都会存有对应的值,而且当你使用状态的时候至少会指定一个默认值,我们可以知道在我们文档的任意位置使用文档的任意其他位置的状态的内容。 这就是允许我们进行时光回溯的基础。 == 「`typeset`」阶段的迭代收敛 一个容易值得思考的问题是,如果我在文档的开始位置调用了#typst-func("state.final")方法,那么Typst要如何做才能把文档的最终状态返回给我呢? 容易推测出,原来Typst并不会只对内容执行一遍「`typeset`」。 仅考虑我们使用#typst-func("state.final")方法的情况。 初始情况下#typst-func("state.final")方法会返回状态默认值,并完成一次布局。接下来的迭代,#typst-func("state.final")方法会返回上一次迭代布局完成时的。直到布局的内容不再发生变化。 #typst-func("state.at")会导致相似的布局迭代,只不过情况更为复杂,这里便不再展开细节。 所有对文档的查询都会导致布局的迭代: 1. `query`函数可能会导致布局的迭代。 1. `state.at`函数可能会导致布局的迭代。 1. `state.final`函数一定会导致布局的迭代。 == 回顾其三 本节使用递归的方法完成状态的构建,其更为巧妙。 首先,我们声明两个与法一类似的状态,只不过这次我们将状态定义在全局。 ```typ #let first-heading = state("first-heading", ()) #let last-heading = state("last-heading", ()) ``` 然后,我们在每个二级标题后紧接着触发一个更新: ```typc show heading.where(level: 2): curr-heading => { curr-heading locate(loc => ..) } ``` 对于`last-heading`状态,我们可以非常简单地如此更新内容: ```typc last-heading.update(headings => { headings.insert(str(loc.page()), curr-heading.body) headings }) ``` 每页的最后一个标题总能最后触发状态更新,所以`str(loc.page())`总是能对应到每页的最后一个标题的内容。 对于`first-heading`状态,稍微复杂但也好理解: ```typc first-heading.update(headings => { let k = str(loc.page()) if k not in headings { headings.insert(k, curr-heading.body) } headings }) ``` 对于每页靠后的一级标题,都不能使`if`条件成立。所以`str(loc.page())`总是能对应到每页的第一个一级标题的内容。 接下来便是简单的查询了,我们回忆之前`get-heading-at-page`的逻辑,它首先判断是否存在本页的第一个标题,否则取前页的最后一个标题。以下函数完成了前半部分: ```typc let get-heading-at-page(loc) = { let page-num = loc.page() let first-headings = first-heading.final(loc) first-headings.at(str(page-num)) } ``` 我们为`at`函数添加`default`函数,其取前页的最后一个标题。 ```typc let get-heading-at-page(loc) = { .. let last-headings = last-heading.at(loc) first-headings.at(str(page-num), default: find-headings(last-headings, page-num)) } ``` 我们使用递归的方法实现`find-headings`: ```typc let find-headings(headings, page-num) = if page-num > 0 { headings.at(str(page-num), default: find-headings(headings, page-num - 1)) } ``` 递归有两个分支: + 递归的基是,若一直找到文档最前页都找不到相应的标题,则返回`none`。 + 否则检查`headings`中是否有对应页的标题 + 若有则直接返回其内容 + 否则继续往前页迭代。 一个细节值得注意,我们对`first-heading`使用了`final`方法,但对`last-heading`使用了`at`方法。这是因为: + `first-heading`需要我们支持后向查找,因此需要直接获取文档最终的状态。 + `last-heading`仅仅需要前向查找,因此使用`at`方法可以改进迭代效率。 这个递归函数是高性能的,因为Typst会对`find-headings`缓存,并且Typst对于后一页的内容,都总是能命中前一页的缓存。 与之相反,基于#typst-func("query")的实现没有那么好命。它没法很好利用递归完成标题信息的构建。这是因为#typst-func("query")的实现中,`calc-headings`的首次执行就被要求计算文档的所有标题。 最后让我们设置页眉: #frames-cjk(read("./stateful/s1.typ"), code-as: ```typ // 这里有get-heading-at-page的实现.. #set page(header: locate(loc => emph( get-heading-at-page(loc)))) ```)
https://github.com/AlvaroRamirez01/Analisis_de_Algoritmos_2024-1
https://raw.githubusercontent.com/AlvaroRamirez01/Analisis_de_Algoritmos_2024-1/master/Tarea_04_Diseño_de_Algoritmos/Tarea04.typ
typst
#import "conf.typ": * #import "@preview/algorithmic:0.1.0" #import algorithmic: * #show: doc => conf( materia: "Análisis de Algoritmos", tarea: "Tarea 4: Diseño de Algoritmos usando Inducción Matemática.", profesor: ( nombre: "<NAME>", sexo: "F", ), ayudantes: ( "<NAME>", "<NAME>" ), alumnos: ( ( nombre: "<NAME>", cuenta: "316276355", email: "<EMAIL>" ), ), fecha: datetime.today(), encabezado: "Problema a desarrollar", doc, ) #let colors = (black, gray, silver, white, navy, blue, aqua, teal, eastern, purple, fuchsia, maroon, red, orange, yellow, olive, green, lime) #text(11pt)[ #par(justify: true)[ #set enum(numbering: "a)") = Considera los siguientes Problemas: *Π: Partición.* Dada una lista $L$ de $n$ enteros positivos y distintos, particionar (dividir) la lista en dos sublistas $L_1$ y $L_2$, cada una de tamaño $n/2$ tal que: $L= L_1 ∪ L_2; L_1 ∩ L_2 = ∅$; se satisface, ademas, que la diferencia entre las sumas de los enteros en las dos listas sea minima. Puedes suponer que n es múltiplo de dos. *β: Cambio de Base.* Dado un numero en base 8 convertirlo a binario. La entrada es un arreglo de dígitos en base 8 y la salida es un arreglo de bits. *∆: Distancias.* Sea $T=(V,A)$ un árbol binario con $n$ vertices. El árbol $T$ esta representado por su lista de adyacencias. Construir una matriz $M$ de $n×n$ tal que el elemento $M[i, j]$ sea igual a la distancia entre los vertices $v_i$ y $v_j$. == Para el Problema seleccionado... + Diseñar un algoritmo eficiente, usando Inducción Matemática, que solucione el problema y que use el menor numero de comparaciones. + Determinar la complejidad del algoritmo obtenido. // #let colors = (black, gray, silver, white, navy, blue, aqua, teal, eastern, purple, fuchsia, maroon, red, orange, yellow, olive, green, lime) #solucion(color: lime)[ *a) Diseñar un algoritmo eficiente, usando Inducción Matemática, que solucione el problema y que use el menor numero de comparaciones.* Problema seleccionado: Problema $beta$ Dado un numero en base 8 convertirlo a binario. La entrada es un arreglo de dígitos en base 8 y la salida es un arreglo de bits. *Precondiciones:* El arreglo de entrada `A` contiene los dígitos a cambiar de base, dichos dígitos están distribuidos dígito a dígito en el arreglo `A`, `A` es de tamaño $n$, donde $n>1$ y contiene los dígitos de un numero en base 8, `T` es el diccionario que contiene la representación de los dígitos en base 8 (identificador) y su representación en base 2 (valor), `num_binario` es un arreglo de tamaño $0$. *Vista del diccionario T:* #figure(table( columns: 2, [Base 8],[Base 2], [0],[000], [1],[001], [2],[010], [3],[011], [4],[100], [5],[101], [6],[110], [7],[111], )) *Diseño de algoritmo:* Se recibe un arreglo `A` de dígitos en base 8, se recibe un diccionario `T` Vamos a analizar los 2 casos que podemos tener en el arreglo `A`: + El caso base es cuando el arreglo `A` tiene un solo dígito, en este caso se busca en `T` el identificador del dígito y se agrega a un arreglo `num_binario` el valor que corresponde al identificador en `T`. + Para el caso cuando el arreglo `A` tiene mas de un dígito, se realiza un ciclo que recorre el arreglo `A` y se busca en `T` su identificador y se agrega a un arreglo `num_binario` el valor que corresponde al identificador en `T`. Al final se regresa el arreglo `num_binario` que contiene el cambio de base de los dígitos del arreglo `A` a base 2. *Postcondiciones:* La cantidad de elementos del arreglo `num_binario` es igual a la cantidad de elementos del arreglo `A`, los elementos del arreglo `num_binario` son los dígitos del arreglo `A` en base 2. *b) Determinar la complejidad del algoritmo obtenido.* Para el caso base, el algoritmo realiza una búsqueda en `T` y agrega un elemento al arreglo `num_binario`, por lo que la complejidad es $O(1)$. Para el caso donde el arreglo `A` tiene mas de un dígito, el algoritmo realiza un ciclo que recorre el arreglo `A` y realiza una búsqueda en `T` y agrega un elemento al arreglo `num_binario`, por lo que la complejidad es $O(n)$. ] = Caja Negra. Se tiene acceso a un algoritmo, denominado Caja Negra, del cual solo se conocen sus resultados, contesta: *sí* o *no*. Si se le da una secuencia de $n$ números enteros y un entero $k$, el algoritmo responde *si* o *no*, dependiendo si existe un subconjunto de esos números cuya suma sea exactamente $k$. Mostrar como usar esta Caja Negra $O(n)$ veces en un proceso que encuentre el subconjunto en cuestión, si es que existe, donde $n$ es el tamaño de la secuencia. #solucion(color: blue)[ Tenemos una secuencia $S = [x_1, x_2, ..., x_n]$ de números enteros y un entero $k$, Podemos considerar a $k$ como una descomposición aditiva, donde cada sumando de esta descomposición es un elemento de $S$, entonces basándonos en esa lógica podemos hacer el siguiente algoritmo. *Algoritmo:* #set enum(numbering: "1.") + *Declaramos* una variable $c=k$. + *Si* $c$ es menor o igual a $0$ entonces terminamos el algoritmo, *en otro caso* le pasamos al algoritmo _CajaNegra(c, S)_ + *Si* el algoritmo _CajaNegra(c, S)_ regresa *si* entonces terminamos el algoritmo, *en otro caso* hacemos un bucle que recorra la secuencia $S$ y le pasamos al algoritmo _CajaNegra(c-$x_i$, S-$x_i$)_ donde $x$ es el elemento de la secuencia $S$ que estamos sacando del final, la condición de termino sera hasta que $c$ sea menor o igual a $0$. + Dentro del bucle, si _CajaNegra(c, S)_ nos regresa true entonces terminamos el algoritmo regresando S, *en otro caso* continuamos con el bucle. *Complejidad:* La complejidad del algoritmo es $O(n)$ ya que se hace una llamada a la caja negra por cada elemento de la secuencia $S$, también cada llamada recursiva se va eliminando elementos de S. ] = Opcional: Los Dos menores elementos de un Conjunto. *Problema μ:* Dada una secuencia $S = [x_1, x_2, ..., x_n]$ de números enteros, encontrar a los dos menores elementos de $S$, usando la menor cantidad posible de comparaciones. + Diseñar, usando Inducción Matemática, un algoritmo que resuelva el problema $μ$. + Determinar el numero de comparaciones que realiza el algoritmo propuesto. #solucion(color: purple)[ *a) Diseñar, usando Inducción Matemática, un algoritmo que resuelva el problema $μ$.* Primero vamos a ver cual seria el o los casos bases: #set enum(numbering: "1.") + Caso cuando la secuencia $S$ tiene solo 2 elementos: en este caso los elementos $x_1, x_2$ están en S, ademas $x_1 < x_2$ y se regresan como los dos menores elementos de $S$. + Caso cuando la secuencia $S$ tiene solo 2 elementos pero son iguales: igual que el caso anterior, podemos mostrar los elementos de $S$ como $S=[x_1,x_2]$, pero en este caso $x_1 = x_2$ y se regresan como los dos menores elementos de $S$ aunque sean el mismo elemento. Ahora vamos a ver el caso donde la secuencia $S$ tiene mas de 2 elementos: + En este caso vamos a dividir la secuencia $S$ en dos subsecuencias $S_1, S_2$ de tamaño $n/2$ cada una, donde $S_1$ contiene los primeros $n/2$ elementos de $S$ y $S_2$ contiene los últimos $n/2$ elementos de $S$. + Hacemos recursion sobre esas 2 subsecuencias hasta que sean de un tamaño de 2 elementos o menos. + Ahora nos quedamos el elemento menor en esa subsecuencia de 2 elemento comparando uno con otro, el menor lo agregamos a una secuencia auxiliar $S'$. + Hacemos lo mismo con la otra subsecuencia de 2 elementos y el elemento menor lo agregamos a la secuencia auxiliar $S'$ y asi con los otros casos recursivos. + Al final nos quedamos con una secuencia $S'$ que contiene los elementos menores de cada subsecuencia de 2 elementos, $S'$ es de tamaño $n/2$, entonces volvemos a hacer el procedimiento de dividir $S'$ en dos subsecuencias hasta que nos queden una subsecuencia de 2 elementos, esos serán los 2 elementos menores de nuestra secuencia $S$ original. *b) Determinar el numero de comparaciones que realiza el algoritmo propuesto.* Para el caso base, el algoritmo realiza una comparación y regresa los 2 elementos de la secuencia $S$, por lo que la complejidad es $O(1)$. Para el caso cuando $S$ tiene $n$ elementos, el algoritmo realiza una comparación y divide la secuencia $S$ en 2 subsecuencias de tamaño $n/2$, entonces hace $n/2$ comparaciones y asi sucesivamente hasta que la secuencia $S$ tenga 2 elementos, por lo que la complejidad esta acotada en $O(log n)$ ya que se hacen $log n$ comparaciones y hay $log n$ llamadas sobre la secuencia $S'$. ] ] ]
https://github.com/nju-typst/.github
https://raw.githubusercontent.com/nju-typst/.github/main/profile/README.md
markdown
## NJU Typst 团队简介 👋 我们将基于[Typst](https://github.com/typst/typst)项目构建适用于南京大学的文档模板,包括但不限于报告、作业、毕业论文模版。 团队成员由来自南京大学的爱好者组成。 ## 关于Typst Typst是撰写任何长篇文本(如论文、文章、科学论文、书籍、报告和家庭 作业)。此外,Typst非常适合于编写任何包含数学符号的文档,例如在数学、 物理和工程领域的论文。 这是一个替代LaTex的现代化文本排版引擎,天下苦LaTex久矣! <!-- **Here are some ideas to get you started:** 🙋‍♀️ A short introduction - what is your organization all about? 🌈 Contribution guidelines - how can the community get involved? 👩‍💻 Useful resources - where can the community find your docs? Is there anything else the community should know? 🍿 Fun facts - what does your team eat for breakfast? 🧙 Remember, you can do mighty things with the power of [Markdown](https://docs.github.com/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) -->
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/convex-hull-working-2.typ
typst
#import "@preview/cetz:0.2.2" #let cross_product(o, a, b) = { return (a.at(0) - o.at(0)) * (b.at(1) - o.at(1)) - (a.at(1) - o.at(1)) * (b.at(0) - o.at(0)) } #let calculate-convex-hull(points) = { let sorted_points = points.sorted() let n = sorted_points.len() if n <= 3 { return sorted_points } // Build lower hull let lower = () for p in sorted_points { while lower.len() >= 2 and cross_product(lower.at(-2), lower.at(-1), p) <= 0 { lower.pop() } lower.push(p) } // Build upper hull let upper = () for p in sorted_points.rev() { while upper.len() >= 2 and cross_product(upper.at(-2), upper.at(-1), p) <= 0 { upper.pop() } upper.push(p) } // Concatenate hulls lower.pop() upper.pop() return lower + upper } #let points = ( (0, 0), (1, 1), (2, 2), (3, 1), (4, 0), (3, 3), (2, 4), (1, 3), (2, 1), (10, 10), ) #let draw-labels(segments, labels) = { let labels = resolve-array(labels) let size = str(segments.len()) let reference = ( "3": (south: 0, east: 1, north: 2, west: 2), "4": (south: 0, east: 1, north: 2, west: 3), "5": (south: 0, east: 1, north: 2, west: 4), ) let ref = reference.at(size) let callback(label) = { let index = ref.at(label.place) let segment = segments.at(index) let attrs = (fill: label.at("fill", default: none)) let content = label.at("content", default: none) draw.brace(..segment, content, ..attrs) } for label in labels { callback(label) } } #let convex-hull(points, labels: none) = { let hull = calculate-convex-hull(points) draw.canvas( { draw.set-style(circle: (fill: blue)) draw.shapes.points(points, fill: blue) draw.shapes.polygon(hull, stroke: red) if labels == none { return } let hull-segments = get-adjacently-paired-segments(hull) draw-labels(hull-segments, labels) }, ) } #let points = ( (0, 0), (1, 1), (2, 2), (3, 1), (4, 0), (3, 3), (2, 4), (1, 3), (2, 1), (10, 10), ) #let labels = ( (place: "north", content: "north"), (place: "south", content: "south"), (place: "east", content: "east"), (place: "west", content: "west", fill: blue), ) #convex-hull(points, labels: labels)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/page-style-01.typ
typst
Other
// Empty with styles and then pagebreak // Should result in two red-colored pages. #set page(fill: red) #pagebreak()
https://github.com/longlin10086/HITSZ-PhTyp
https://raw.githubusercontent.com/longlin10086/HITSZ-PhTyp/main/README.md
markdown
# HITSZ-PhTyp This repo is a Typst template of Harbin Institute of Technology(Shenzhen) Physics lab report. ## 🏠 Architecture ```sh . ├── README.md ├── assets │   └── images # Directory used for store images ├── layout │   └── page.typ # Define the page's style ├── template.pdf ├── template.typ # The main article ├── themes │   └── theme.typ # Define the font style and size └── utils ├── head_element.typ # Some necessary illustration ├── image.typ # How the image is demonstarted ├── question_list.typ # Question list for each section ├── tables.typ # Define the table's style └── two_line.typ # An auxiliary ``` If you want to use this template to product report, all the writing changes should be done in `template.typ`. ## ❓ Issues - [ ] Math symbols can't be rendered correctly with underline. ([Underline doesn't apply to inline math · Issue #1043 · typst/typst ](https://github.com/typst/typst/issues/1043)) - [ ] The signature image has encountered some incorrect align. - [ ] When using `SimSun` and other CJK fonts, there is an align mistake.([CJK have some about aligned questions · Issue #3710 · typst/typst](https://github.com/typst/typst/issues/3710)) ## 🙏 Acknowledgement I had learnt from these repos when developing this project. - [nju-lug/nju-thesis-typst](https://github.com/nju-lug/nju-thesis-typst/) - [chosertech/HIT-Thesis-Typst](https://github.com/chosertech/HIT-Thesis-Typst) - [Doctxing/phytex](https://github.com/Doctxing/phytex)
https://github.com/diquah/OpenBoard
https://raw.githubusercontent.com/diquah/OpenBoard/main/README.md
markdown
MIT License
# OpenBoard <h3 align="center"> Easily build clean assessments in the style of the College Board. </h3> <p align="center"> <img width="45%" src="https://raw.githubusercontent.com/diquah/OpenBoard/main/Preview/ExamplePage1.png"> <img width="45%" src="https://raw.githubusercontent.com/diquah/OpenBoard/main/Preview/ExamplePage2.png"> </p> Typst template and framework for creating professional and clean exams of any kind, in the style of College Board exams. - The template is **colorless to be as print-friendly** as possible. - The template uses **free fonts already included in the Typst web app** to minimize external dependencies. The instructional font is _Roboto Slab_, the primary font is _STIX Two Text_, and the math font is _STIX Two Math_. - The template is extremely **modular and flexible**, supporting multiple choice questions with unlimited choices, free response questions with unlimited subquestions (blank, ruled, and graph templates), and long-form essay style questions. ## Building an assessment: Import and initialize the template. ```typst #import "openboard.typ": * #show: doc => template( paper: "us-letter", doc, ) // The rest of the assessment will go here. ``` A prompt is an enumerated 'question' in the assessment. ```typst #prompt[ Question goes here. ] ``` The prompt can have a multiple-choice attachment. ```typst #prompt[ Question goes here. #mcq( [These options], [are automatically], [enumerated with letters A, B, C, etc.], [and can be as many or few], [as you wish], ) ] ``` Alternatively, prompts can have a free-response attachment. ```typst #prompt[ This is the overall problem statement. #frq( [ Sub-questions can have blank space for response. #space(1) // Increase the number for more or less space. ], [ They can have ruled/lined paper for a more structured written response. #ruled(5) // Increase the number for more or less lines. ], [ They can have empty graph paper as well. #graph(22, 10) // Change the numbers to change the (X, Y) size of the graph. ], ) ] ``` This is a free response with no subparts. ```typst #prompt[ This is the overall problem statement. #ruled(5) ] ``` See the example exam source for more elements that can be used.
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/src/extras/title.typ
typst
MIT License
#import "@preview/cetz:0.1.2" #let _prepare(self, ctx) = { self.coordinates = ( (ctx.prototype.range.at(0), 110),) return self } #let _stroke(self, ctx) = { cetz.draw.content( anchor: self.anchors.at(0), self.coordinates.at(0), //(72, 80), box(inset: self.inset, [#self.content]), ..ctx.prototype.style.title ) } #let title(content, inset: 0.5em) = { return (( type: "title", content: content, inset: inset, anchors: ("top-left",), plot-prepare: _prepare, plot-stroke: _stroke, ),) }
https://github.com/philipsd6/typst-yearly-planner
https://raw.githubusercontent.com/philipsd6/typst-yearly-planner/main/calendar.typ
typst
MIT License
/* ** Configuration */ #let config = yaml("config.yaml") #(config.height = eval(config.height)) #(config.width = eval(config.width)) #(config.toolbar-width = eval(config.toolbar-width)) #(config.fontsize = eval(config.fontsize)) #(config.margin = eval(config.margin)) #let heavyline = line.with(stroke: 1pt + black, length: 100%) #let ruleline = line.with(stroke: 0.5pt + luma(200), length: 100%) #let border = 0.5pt + black #set pagebreak(weak: true) // TODO: this should take parameters for calendar, holidays, and events files. // --input events=events.yaml --input holidays=holidays.yaml // access as sys.inputs.<events|holidays> #let calendar = yaml("calendar.yaml") #let events = json("events.json") #let holidays = yaml("holidays.yaml") // A lot of boilerplate data depends on the first days of the first and // last months in the calendar datafile #let fday = calendar.first().first() #let lday = calendar.last().first() // Having the month names and weekdays upfront is useful as well. #let monthnames = calendar.map(month => month.first().name) #let weekdays = calendar.first().map(day => day.weekday).slice(0, count: 7) /* ** Page Layout / Base Style */ #set text( font: config.font, size: config.fontsize, weight: "light", // number-type: "old-style", ) #set page( height: config.height, width: config.width, margin: if config.toolbar-side == "right" { (right: config.margin + config.toolbar-width, rest: config.margin) } else { (left: config.margin + config.toolbar-width, rest: config.margin) }, header-ascent: config.margin ) /* ** Utility functions */ // Return a label based on the items given #let labelize(..items) = { let key = items.pos().filter(it => {it != none}).map(str).join("-") return label(key) } /* ** Header/Navigation Functions */ #let sideways(body) = { return rotate(body, -90deg, reflow: true) } #let page-nav(title, lbl: none, title-loc: none, prev: none, next: none, subtitle: none) = { let large = text.with(size: 2.8em) let small = text.with(size: 1.1em) let back(loc) = {return link(loc)[\u{29FC}#h(2pt)]} let forward(loc) = {return link(loc)[#h(2pt)\u{29FD}]} if lbl == none { lbl = labelize(title) } return grid(columns: 3, if prev != none { grid.cell(large()[#back(prev)]) }, if subtitle == none { // it's just a title, keep it simple grid.cell(if title-loc != none { link(title-loc)[#box(large()[#title #lbl])] } else { large()[#title #lbl] }) } else { // more complicated... embed an inner grid let inner-grid = grid(columns: 2, inset: (top: 0pt, bottom: 0pt, rest: 4pt), grid.cell(rowspan: 2, stroke: {(right: border)}, large()[#title #lbl]), grid.cell(small(weight: "semibold")[#align(top, subtitle.top)]), grid.cell(small()[#align(bottom, subtitle.bottom)]) ) if title-loc != none { link(title-loc)[#inner-grid] } else { inner-grid } }, if next != none { grid.cell(rowspan: 2, [#large()[#forward(next)]]) }, ) } #let header(left-side, right-side) = { box(left-side) h(1fr) box(right-side) if config.clear-top-right-corner and config.toolbar-side != "right" { box(width: 8mm) } v(0pt) // (zero vspace still takes up more than without it!) box(heavyline()) } #let tab(body, active: false, ..args) = { grid.cell( inset: 5pt, ..args, [#metadata((active: active))#body] ) } #show grid.cell: it => { let sequence = [*a* _a_].func() if it.body.func() == sequence and it.body.children.len() > 0 and it.body.children.first().func() == metadata and it.body.children.last().func() == link { let meta = it.body.children.first().value let loc = it.body.children.last().dest if type(meta) == dictionary and meta.active { return link(loc, box(fill: black, text(fill: white, it))) } else { return link(loc, it) } } it } #let topbar(size: 1.2em, ..tabs) = { tabs = tabs.pos().filter(t => t != none) if tabs.len() > 0 { return text(size: size, grid(columns: tabs.len(), stroke: (x, y) => if x > 0 {(left: border)}, ..tabs )) } } #let sidebar(active-tabs: ()) = { set text(size: 1.2em) let tab = tab.with(inset: 10pt) let grid = grid.with( inset: 0pt, columns: 1, stroke: if config.toolbar-side == "right" { (x, y) => (left: border) + if y > 0 {(top: border)} } else { (x, y) => (right: border) + if y > 0 {(top: border)} } ) let dx = - config.toolbar-width - 2mm if config.toolbar-side == "right" { dx = config.width - config.toolbar-width } place(dx: if config.toolbar-side == "right" { config.width - config.toolbar-width } else { - config.toolbar-width - 2mm }, stack(dir: ttb, spacing: 1fr, if "quarterly" in config.include { grid(..range(0, 12, step: 3).enumerate(start: 1).map( ((qtr, mon)) => ( tab(active: "Q"+str(qtr) in active-tabs, link(labelize(calendar.at(mon).first().year, "Q", qtr))[Q#qtr] ) ) ).map(sideways)) }, if "monthly" in config.include { grid(..calendar.map(month => ( tab(active: month.first().name.slice(0, count: 3) in active-tabs, link(labelize(month.first().year, month.first().name), month.first().name.slice(0, count: 3)) ) )).map(sideways)) } ) ) } /* ** Calendar functions */ #let smallmonth(month, include-weeks: false, current-day: none) = { // Get the first day for convenience let d = month.first() set align(center) set grid.cell(inset: 0.55em) if "monthly" in config.include { link(labelize(d.year, d.name))[=== #d.name] } else { [=== #d.name] } let weekday-letters = weekdays.map(it => it.first()) let cells = () if include-weeks { cells += (grid.cell()[W],) } cells += weekday-letters // need to handle rolling over to week 1 in the next year! let prev_week = 0 for (i, day) in month.enumerate() { if include-weeks and calc.rem(i, 7) == 0 { cells.push(link(labelize(day.year + if day.week < prev_week { 1 } else { 0 }, "W", day.week))[#day.week]) prev_week = day.week } if day.month == day.name { if "daily" in config.include { cells.push(tab(active: current-day == day.day, link(labelize(day.year, day.month, day.day))[#day.day])) } else { cells.push(tab(active: current-day == day.day, [#day.day])) } } else { cells.push(none) } } grid( columns: if include-weeks { 8 } else { 7 }, align: center, stroke: (x, y) => if y == 0 {(top: border, bottom: border)} + if include-weeks and x == 0 {(right: border)}, ..cells ) } /* ** Annual calendar page */ #let annual-page() = { // The title will be the year let title = fday.year // If the calendar spans a year boundary, use both years as the title. let endash = [\u{2013}] if fday.year < lday.year { title = [#fday.year#endash;#lday.year] } sidebar() grid( columns: 3, column-gutter: 14pt, row-gutter: 1fr, grid.cell(colspan: 3, header( page-nav(title, lbl: labelize(fday.year)), topbar( tab(active: true, link(labelize(fday.year))[Calendar]), if "notes" in config.include { tab(link(labelize("Notes Index", 1))[Notes]) }, ) )), ..calendar.map(smallmonth.with(include-weeks: "weekly" in config.include)) ) pagebreak() } #if "annual" in config.include { [#annual-page()] } /* ** Quarterly Pages */ #let quarterly-page(qtr, months, prev: none, next: none) = { let year = months.at(0).first().year // Adding the following, which does nothing physically to the document causes errors: "label `<2024-Q-1>` does not exist in the document // context { // let newprev = query(heading.where(level: 1, label: <Quarter>).before(here()), inclusive: false) // let newnext = query(heading.where(level: 1, label: <Quarter>).after(here()), inclusive: false) // } sidebar(active-tabs: ("Q" + str(qtr), )) header( page-nav([Q#qtr <Quarter>], lbl: labelize(year, "Q", qtr), prev: prev, next: next), topbar( if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index-1"))[Notes]) }, ) ) grid( columns: 2, column-gutter: 3pt, stack(dir: ttb, spacing: 1fr, ..months.map(smallmonth.with(include-weeks: "weekly" in config.include)) ), locate(loc => [ #let current_y = loc.position().y #let remaining_space = config.height - current_y - config.margin * 2 // can't subtract the top-margin because it's in em units... #let lines_num = int(remaining_space / config.fontsize / 2) + 1 #for i in range(lines_num) { linebreak() linebreak() box(ruleline()) } ]) ) pagebreak() } #if "quarterly" in config.include { let prev-range = range(0, 5) let next-range = range(2, 6) let current-range = range(0, 12, step: 3).enumerate(start: 1) for ((pqtr, (qtr, start-month)), nqtr) in prev-range.zip(current-range).zip(next-range) { let months = calendar.slice(start-month, count: 3) let year = months.first().first().year [#quarterly-page(qtr, months, prev: if pqtr != 0 {labelize(year, "Q", pqtr)}, next: if nqtr < 5 {labelize(year, "Q", nqtr)}) ] } } /* ** Monthly Pages */ #let monthly-page(month, prev: none, next: none) = { let d = month.first() let qtr = calc.floor(monthnames.position(mon => {d.name == mon}) / 3 + 1) sidebar(active-tabs: ("Q" + str(qtr), d.name.slice(0, count: 3))) header( page-nav(d.name, lbl: labelize(d.year, d.name), prev: prev, next: next), topbar( if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index-1"))[Notes]) }, ) ) let cells = () if "weekly" in config.include { cells = (none, ) } cells += weekdays.map(w => { grid.cell(align: top + center, w) }) let prev_week = 0 for (i, day) in month.enumerate() { if calc.rem(i, 7) == 0 and "weekly" in config.include { cells.push(grid.cell(align: left + horizon, sideways()[#link(labelize(day.year + if day.week < prev_week { 1 } else { 0 }, "W", day.week))[Week#hide[-]#day.week]])) prev_week = day.week } let cell = none if day.month == day.name { cell = grid.cell()[#day.day] } else { cell = grid.cell(text(gray)[#day.day]) } if "daily" in config.include and day.year == fday.year { cells.push(link(labelize(day.year, day.month, day.day))[#cell]) } else { cells.push(cell) } } grid( inset:3pt, gutter: -0pt, columns: if "weekly" in config.include {(auto, ) + (1fr, ) * 7} else {(1fr, ) * 7}, rows: (auto, 10%), align: top + left, stroke: (x, y) => {(bottom: border)} + if x > 0 {(left: border)}, ..cells ) locate(loc => [ #let current_y = loc.position().y #let remaining_space = config.height - current_y - config.margin * 2 // can't subtract the top-margin because it's in em units... #let lines_num = int(remaining_space / config.fontsize / 2) #grid( columns: (1fr, 1fr), column-gutter: 6pt, for i in range(lines_num) { linebreak() box(ruleline()) linebreak() }, for i in range(lines_num) { linebreak() box(ruleline()) linebreak() } ) ]) pagebreak() } #if "monthly" in config.include { let prev = none for (i, month) in calendar.enumerate(start: 1) { let next = calendar.at(i, default: (none,)).first() [#monthly-page(month, prev: if prev != none {labelize(prev.year, prev.name)}, next: if next != none {labelize(next.year, next.name)} )] prev = month.first() } } /* ** Weekly Pages */ #let weekly-page(week, prev: none, next: none) = { let d = week.first() let d2 = week.last() let quarters = ( "Q" + str(calc.floor(monthnames.position(mon => {d.name == mon}) / 3 + 1)), ) if d2.year == d.year { quarters.push( "Q" + str(calc.floor(monthnames.position(mon => {d2.month == mon}) / 3 + 1)) ) } let months = ( d.name.slice(0, count:3), ) if (d2.year == d.year) { months.push(d2.month.slice(0, count:3)) } sidebar(active-tabs: (quarters + months)) header( page-nav([Week #d.week], lbl: labelize(d2.year, "W", d.week), prev: prev, next: next), topbar( if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index-1"))[Notes]) }, ) ) grid(columns: (1fr, ) * 3, inset: (bottom:8pt, rest: 1pt), column-gutter: 4pt, row-gutter: 0pt, rows: 1fr, ..week.map(d => { if "daily" in config.include and d.year == fday.year { link(labelize(d.year, d.month, d.day))[#d.day. #d.weekday] } else { [#d.day. #d.weekday] } box(line(length: 100%)) for i in range(11) { v(1fr) ruleline() } }), grid.cell(colspan: 2)[ Notes #box(line(length: 100%)) #for i in range(11) { v(1fr) ruleline() } ] ) pagebreak() } #if "weekly" in config.include { let weeks = calendar.flatten().chunks(7) let prev = none for (i, week) in weeks.enumerate(start: 1) { let curr = week.first() let next = weeks.at(i, default: (none,)).last() if prev != none and curr.week == prev.week { continue // avoid duplicate weeks from month end/begin overlaps } [#weekly-page(week, prev: if prev != none {labelize(prev.year, "W", prev.week)}, next: if next != none {labelize(next.year, "W", next.week)} )] prev = curr } } /* ** Daily Pages */ #let daily-page(day, prev: none, next: none) = { let quarter = "Q" + str(calc.floor(monthnames.position(mon => {day.name == mon}) / 3 + 1)) sidebar(active-tabs: (quarter, day.name.slice(0, count: 3))) header( page-nav([#day.day], lbl: labelize(day.year, day.month, day.day), subtitle: (top: [#day.weekday], bottom: [#day.month]), prev: prev, next: next), topbar( if "weekly" in config.include { tab(link(labelize(day.year, "W", day.week))[Week #day.week]) }, if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index-1"))[Notes]) }, ) ) let current-smallmonth = smallmonth( include-weeks: false, calendar.at(monthnames.position(mon => {day.name == mon})), current-day: day.day ) style(styles => { let size = measure(current-smallmonth,styles) grid( columns: (size.width, auto), column-gutter: 6pt, stack(dir: ttb, [ Schedule #box(line(length: 100%, stroke: 1pt)) #linebreak() #for i in range(12) { [#calc.rem((i + 8), 24)] linebreak() box(ruleline()) linebreak() linebreak() box(line(length: 100%, stroke: border)) linebreak() } #linebreak() ], current-smallmonth ), stack(dir: ttb, [ Top Priorities #box(line(length: 100%, stroke: 1pt)) #for i in range(8) { [#(i+1) ☐] linebreak() box(ruleline()) } #box(stack(spacing: 1fr, dir: ltr, [ #box(width: 1fr, topbar(size: 1em, tab(active: true, link(labelize(day.year, day.month, day.day))[Notes]), if "reflections" in config.include { tab(link(labelize(day.year, day.month, day.day, "Reflect"))[Reflect]) } )) #if "notes" in config.include { box(tab(link(labelize("Notes Index-1"))[All Notes])) } ])) #box(line(length: 100%, stroke: 1pt)) #locate(loc => [ #let current_y = loc.position().y #let remaining_space = config.height - current_y - config.margin * 2 // can't subtract the top-margin because it's in em units... #let lines_num = int(remaining_space / config.fontsize / 2) #for i in range(lines_num - 1) { hide([#(i+1)]) linebreak() box(ruleline()) } #v(1pt) #box(stack(spacing: 1fr, dir: ltr, [ #box(width: 1fr, ruleline()) #link(labelize(day.year, day.month, day.day, "Notes"))[#box()[More...]] ])) ]) ]) ) }) pagebreak() } /* ** Daily Notes Pages */ #let daily-note-page(day, prev: none, next: none) = { let quarter = "Q" + str(calc.floor(monthnames.position(mon => {day.name == mon}) / 3 + 1)) sidebar(active-tabs: (quarter, day.name.slice(0, count: 3))) header( page-nav([#day.day], lbl: labelize(day.year, day.month, day.day, "Notes"), subtitle: (top: [#day.weekday], bottom: [#day.month]), prev: prev, next: next, title-loc: labelize(day.year, day.month, day.day)), topbar( if "weekly" in config.include { tab(link(labelize(day.year, "W", day.week))[Week #day.week]) }, if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index-1"))[Notes]) }, ) ) locate(loc => [ #let current_y = loc.position().y #let remaining_space = config.height - current_y - config.margin * 2 // can't subtract the top-margin because it's in em units... #let lines_num = int(remaining_space / config.fontsize / 2) #for i in range(lines_num) { linebreak() linebreak() box(ruleline()) }]) pagebreak() } #if "daily" in config.include { let days = calendar.flatten().filter(day => day.name == day.month) let prev = none for (i, day) in days.enumerate(start: 1) { let next = days.at(i, default: none) daily-page(day, prev: if prev != none { labelize(prev.year, prev.month, prev.day) }, next: if next != none { labelize(next.year, next.month, next.day) } ) prev = day } prev = none for (i, day) in days.enumerate(start: 1) { let next = days.at(i, default: none) daily-note-page(day, prev: if prev != none { labelize(prev.year, prev.month, prev.day, "Notes") }, next: if next != none { labelize(next.year, next.month, next.day, "Notes") } ) prev = day } } /* ** Daily Reflection Pages */ #let reflection-page(day, prev: none, next: none) = { let quarter = "Q" + str(calc.floor(monthnames.position(mon => {day.name == mon}) / 3 + 1)) sidebar(active-tabs: (quarter, day.name.slice(0, count: 3))) header( page-nav([#day.day], lbl: labelize(day.year, day.month, day.day, "Reflect"), subtitle: (top: [#day.weekday], bottom: [#day.month]), prev: prev, next: next, title-loc: labelize(day.year, day.month, day.day)), topbar( if "weekly" in config.include { tab(link(labelize(day.year, "W", day.week))[Week #day.week]) }, if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index-1"))[Notes]) }, ) ) for prompt in config.reflection-prompts { prompt box(line(length: 100%, stroke: 1pt)) for i in range(config.reflection-prompt-lines) { hide([#1]) linebreak() box(ruleline()) } v(0pt) } [Daily log] box(line(length: 100%, stroke: 1pt)) locate(loc => [ #let current_y = loc.position().y #let remaining_space = config.height - current_y - config.margin * 2 // can't subtract the top-margin because it's in em units... #let lines_num = int(remaining_space / config.fontsize / 2) + 1 #for i in range(lines_num - 1) { hide([#1]) linebreak() box(ruleline()) }]) pagebreak() } #if "reflections" in config.include { let days = calendar.flatten().filter(day => day.name == day.month) let prev = none for (i, day) in days.enumerate(start: 1) { let next = days.at(i, default: none) reflection-page(day, prev: if prev != none {labelize(prev.year, prev.month, prev.day, "Reflect")}, next: if next != none {labelize(next.year, next.month, next.day, "Reflect")} ) prev = day } } /* ** Notes ** ** The number of note pages depends on how many index lines ** fit on the index pages. */ #let d = counter("note") #let index-page(page-num: none, prev: none, next: none) = { sidebar() header( page-nav([Notes Index], lbl: labelize("Notes Index", page-num), prev: if prev != none { labelize("Notes Index", prev) }, next: if next != none { labelize("Notes Index", next) }, ), topbar( if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(active: page-num == 1, link(labelize("Notes Index" , 1))[Notes]) }, ) ) locate(loc => { let current_y = loc.position().y let remaining_space = config.height - current_y - config.margin * 2 let lines_num = int(remaining_space / config.fontsize / 2) for i in range(lines_num) { d.step() context { link(labelize("Note", d.get().first()))[#box(width: 1.5em)[#align(right)[#d.get().first()]]] } linebreak() box(ruleline()) }}) pagebreak() } #let note-page(page-num: 1, prev: none, next: none, thing: none) = { sidebar() header( page-nav([Note #page-num], lbl: labelize("Note", page-num), prev: if prev != none { labelize("Note", prev) }, next: if next != none { labelize("Note", next) }, ), topbar( if "annual" in config.include { tab(link(labelize(fday.year))[Calendar]) }, if "notes" in config.include { tab(link(labelize("Notes Index", 1))[Notes]) }, ) ) locate(loc => { let current_y = loc.position().y let remaining_space = config.height - current_y - config.margin * 2 // can't subtract the top-margin because it's in em units... let lines_num = int(remaining_space / config.fontsize / 2) for i in range(lines_num) { linebreak() linebreak() box(ruleline()) }}) pagebreak() } #if "notes" in config.include { let page-count = 3 if "note-index-pages" in config { page-count = config.note-index-pages } let prev = none let next = none for i in range(1, page-count + 1) { if i < page-count { next = i + 1 } else { next = none } index-page(page-num: i, prev: prev, next: next) prev = i } context { let next = none let prev = none let notes-count = d.final().at(0) for i in range(1, notes-count + 1) { if i < notes-count { next = i + 1 } else { next = none } note-page(page-num: i, prev: prev, next: next) prev = i } } }
https://github.com/LugsoIn2/typst-htwg-thesis-template
https://raw.githubusercontent.com/LugsoIn2/typst-htwg-thesis-template/main/glossar/glossary.typ
typst
MIT License
// this is an example. Check https://typst.app/universe/package/glossarium #let glossary = ( // minimal term (key: "kuleuven", short: "KU Leuven"), // a term with a long form and a group (key: "unamur", short: "UNamur", long: "Namur University", // group: "Universities" ), // a term with a markup description ( key: "oidc", short: "OIDC", long: "OpenID Connect", desc: [OpenID is an open standard and decentralized authentication protocol promoted by the non-profit #link("https://en.wikipedia.org/wiki/OpenID#OpenID_Foundation")[OpenID Foundation].], // group: "Accronyms", ), // a term with a short plural ( key: "potato", short: "potato", // "plural" will be used when "short" should be pluralized plural: "potatoes", desc: [#lorem(10)], ), // a term with a long plural ( key: "dm", short: "DM", long: "diagonal matrix", // "longplural" will be used when "long" should be pluralized longplural: "diagonal matrices", desc: "Probably some math stuff idk", ), )
https://github.com/Cldfire/site
https://raw.githubusercontent.com/Cldfire/site/main/resume/README.md
markdown
# resume Built with https://typst.app. * Template: https://github.com/GeorgeHoneywood/alta-typst * Font: https://github.com/be5invis/Iosevka Run the following to work on the content: ``` typst watch resume/resume.typ static/resume.pdf ``` Swap `watch` for `compile` if you just want to compile the PDF once.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/break-continue-05.typ
typst
Other
// Test break in function call. #let identity(x) = x #let out = for i in range(5) { "A" identity({ "B" break }) "C" } #test(out, "AB")
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ssrn-scribe/0.4.9/README.md
markdown
Apache License 2.0
# Typst-Paper-Template Following the official tutorial, I create a single-column paper template for general use. You can use it for papers published on SSRN etc. ## How to use ### Use as an template package Typst integrated the template with their official package manager. You can use it as the other third-party packages. You only need to enter the following command in the terminal to initialize the template. ``` typst init @preview/ssrn-scribe ``` If will generate a subfolder `ssrn-scribe` including the `main.typ` file in the current directory with the latest version of the template. ### Mannully use 1. Download the template or clone the repository. 2. generate your bibliography file using `.biblatex` and store the file in the same directory of the template. 3. modify the `main.typ` file in the subfolder `/template` and compile it. ***Note:* You should have `paper_template.typ` and `main.typ` in the same directory.** In the template, you can modify the following parameters: * Font: You can choose the font that you like. The default font is `Times New Roman`. You can also use Palatino by uncommenting the line `font: "palatino", // "Times New Roman"` * Fontsize: You can choose the font size that you like. The default font size is `11pt`. You can also use `12pt` or `10pt` by uncommenting the line `fontsize: 12pt, // 11pt` * Author: You can add as many authors as you like. But you need to include four parameters for each author: name, affiliation, email, and note within parentheses. If you don't have the information, you can leave it blank. ``` ( name: "", affiliation: "", email: "", note: "", ), ``` * Abstract: You can add your abstract with `[Your abstract]`. * Acknowledgment: You can add your acknowledgment with `[Your `acknowledgment `]`. * Bibliography: You can add your reference BibLaTex: ``` bibliography: bibliography("bib.bib", title: "References", style: "apa"), ``` ``` /////////////////////////////// #import "@preview/ssrn-scribe:0.4.9": * /////////////////////////////// #show: paper.with( font: "PT Serif", // "Times New Roman" fontsize: 12pt, // 12pt maketitle: true, // whether to add new page for title title: [#lorem(5)], // title subtitle: "A work in progress", // subtitle authors: ( ( name: "<NAME>", affiliation: "Artos Institute", email: "<EMAIL>", note: "123", ), ), date: "July 2023", abstract: lorem(80), // replace lorem(80) with [ Your abstract here. ] keywords: [ Imputation, Multiple Imputation, Bayesian,], JEL: [G11, G12], acknowledgments: "This paper is a work in progress. Please do not cite without permission.", // bibliography: bibliography("bib.bib", title: "References", style: "apa"), ) = Introduction #lorem(50) ``` ## Preview Here is a screenshot of the template: ![Example](https://minioapi.pjx.ac.cn/img1/2024/03/63ce084e2a43bc2e7e31bd79315a0fb5.png)
https://github.com/lyzynec/orr-go-brr
https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/14/main.typ
typst
#import "../lib.typ": * #knowledge[ #question(name: [Explain the concept of _Linear Matrix Inequality_ (LMI). Characterize the feasible set of such inequalitiy(--ies). In particular, is the feasible set convex? Show a few simple examples of an LMI from linear algebra or control theory.])[ Such inequality looks like this $ underbrace(bold(F)_0 + bold(F)_1 x_1 + bold(F)_2 x_2 + ... + bold(F)_m x_m, bold(F)(bold(x))) gt.curly 0 $ Stating the positive--definitness of the matrix. As example $ mat(1, 0, 0; 0, 2, -1; 0, -1, 2) + mat(1, 0, 0; 0, 0, -1; 0, -1, 0) x_1 + mat(0, 0, 1; 0, 0, 0; 1, 0, 0) x_2 gt.curly 0\ mat( x_1 + 1, 0, x_2; 0, 2, -x_1 - 1; x_2, -x_1 - 1, 2; ) gt.curly 0 $ to solve we get the principal minors as $ d_1 &= x_1 + 1 > 0\ d_2 &= 2 x_1 + 2 > 0\ d_3 &= -x_1^3 -3 x_1^2 -2 x_2^2 + x_1 + 3 > 0 $ the solution looks like #align(center)[#image("includes/lmi_solution.svg", width: 50%)] If the feasible set exists it will be convex. ] #question(name: [Explain the concept of semidefinite programming (SDP). Show a few simple examples from linear algebra or control theory.])[ Linear optimization with LMI constraints: $ min_(bold(x) in RR^n) bold(c)^T bold(x)\ "subject to" bold(F)(bold(x)) gt.curly 0 $ As example we can solve asymptotic stability of a system $ dot(bold(x)) = bold(A) bold(x)(t) $ entails asking for $bold(X)$ $ bold(X) = bold(X)^T gt.curly 0 $ solving the Lyapunov equation $ bold(A)^T bold(X) + bold(X) bold(A) = - bold(Y) $ for $ bold(Y) = bold(Y)^T gt.curly 0 $ That can be formulated as LMI problem $ bold(A)^T bold(X) + bold(X) bold(A) &lt.curly 0\ bold(X) &gt.curly 0 $ or in one matrix $ mat( bold(X), bold(0); bold(0), -bold(A)^T bold(X) - bold(X) bold(A) ) gt.curly 0 $ ] ] #skills[ #question(name: [Express a given simple linear--algebraic or control--theoretic problem as an LMI (or, generally, semidefinite program) and solve the optimization problem in Matlab (using Yalmip or another). ])[] ]
https://github.com/InseeFrLab/address-search-gaia-docs
https://raw.githubusercontent.com/InseeFrLab/address-search-gaia-docs/main/src/abstract-ntts/definitions.typ
typst
MIT License
// Some definitions presupposed by pandoc's typst output. #let horizontalrule = [ #line(start: (25%,0%), end: (75%,0%)) ] #let endnote(num, contents) = [ #stack(dir: ltr, spacing: 3pt, super[#num], contents) ] #show outline.entry.where( level: 1): it => { v(12pt, weak: true) strong(it) }
https://github.com/mangkoran/share.typ
https://raw.githubusercontent.com/mangkoran/share.typ/master/example.typ
typst
MIT License
// if you add this repo as git submodule, change this to "share.typ/share.typ" #import "share.typ": * // variables #let user_vars = ( color: "b4befe", ) // load post data from YAML #let share_data = yaml("example.yml") #let custom_rules(doc) = { // add custom document style rules here doc } #let share_init(doc, user_vars) = { doc = set_rules(doc, user_vars) doc = show_rules(doc) doc = custom_rules(doc) doc } #show: doc => share_init(doc, user_vars) #share_header(share_data) #share_content(share_data, user_vars) #share_footer(share_data, user_vars)
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/3空间域图像增强.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") = 空间域图像增强 Image Enhancement in the Spatial Domain #definition[ *空间域*:指的是图像的坐标空间,即图像的二维坐标系(aggregate of pixels)。 ] 空间域图像增强直接对图像像素进行操作。 == 基本灰度变换 Basic Gray Level Transformations #definition[*灰度变换*:指的是将输入图像的灰度级映射到输出图像的灰度级的过程] 灰度变换函数 $s = T(r)$ 可以用来描述灰度变换,其中 $r$ 为输入灰度级,$s$ 为输出灰度级。基本灰度变换是逐像素的操作,不考虑像素之间的关系。 #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot: * import cetz.palette: * plot( size: (5, 5), x-tick-step: none, y-tick-step: none, x-label: [输入灰度级 $r$], y-label: [输出灰度级 $s$], { let Identity(x) = { x } let Power(x) = { calc.pow(x, 2) } let Root(x) = { calc.pow(x, 0.5) } let Log(x) = { calc.log(100 * x + 1, base: 10) / 2 } let InverseLog(x) = { (calc.exp(5 * x) - 1) / (calc.pow(calc.e, 5) - 1) } let Negative(x) = { 1 - x } cetz.plot.add(domain: (0, 1), Identity, label: "Identity") cetz.plot.add(domain: (0, 1), Power, label: "Power") cetz.plot.add(domain: (0, 1), Root, label: "Root") cetz.plot.add(domain: (0, 1), Log, label: "Log") cetz.plot.add(domain: (0, 1), InverseLog, label: "Inverse Log") cetz.plot.add(domain: (0, 1), Negative, label: "Negative") }, ) })], caption: "常见的灰度变换函数", ) 常见的灰度变换函数有: - 恒等变换 - 幂次变换:$s = c r^gamma$ - $gamma < 1$ 时,图像变亮,扩展低灰度级 - $gamma > 1$ 时,图像变暗,扩展高灰度级 - 应用:显示器的 gamma 校正,即通过 gamma 值让显示器显示的图像更接近真实 - 对数变换:$s = c log(1 + r)$ - 用于扩展低灰度级,压缩高灰度级 - 适用于图像的动态范围较大,但细节在低灰度级的图像 - 一个典型的应用:傅里叶变换的幅度谱 == 直方图处理 Histogram Processing #definition[*直方图*:指的是图像中各个灰度级的分布情况] 直方图 $h(r_k)$ 是一个函数,表示图像中灰度级 $r_k$ 出现的次数。标准化后的直方图 $p(r_k) = h(r_k) / (M N)$,其中 $M N$ 为图像的总像素数,表示各个灰度级的概率。 直方图均衡化是一种直方图处理方法,通过拉伸直方图来增强图像的对比度。其步骤如下: 1. 计算原始图像的直方图 $p_r(r_k)$ 2. 计算累积分布函数 $s_k = sum_{j=0}^{k} p_r(r_j)$ 3. 计算映射函数 $s_k = T(r_k) = (L-1) s_k$,$T(r_k)$ 即为直方图均衡化后的灰度级,$L$ 为灰度级数(如 256) 4. 计算均衡化后的图像 $s = T(r)$ 这样,直方图均衡化后的图像的直方图会更加均匀,对比度也会更高。 == 空间滤波 Spatial Filtering #definition[*空间滤波*:指的是对图像的像素进行操作,以改变图像的灰度级] $ // R = sum_(i=-1, j=-1)^1 sum_(m=-1, n=-1)^1 w(m, n) f(i+m, j+n) R = sum_(i, j in [-1, 1]) sum_(m, n in [-1, 1]) w(m, n) f(i+m, j+n) $ 其中,$R$ 为输出图像的像素,$w(m, n)$ 为滤波器的权重,$f(i+m, j+n)$ 为输入图像的像素。 == 平滑滤波器 Smooth Filters #definition[*平滑滤波器*:指的是对图像进行平滑处理的滤波器] 平滑滤波器可以用来去除图像中的噪声,使图像更加平滑。常见的平滑滤波器有: - 线性滤波器 - 均值滤波器 - 加权滤波器 - 非线性滤波器 - 中值滤波器(统计排序滤波器) === 均值滤波器 $ 1 / 9 * mat(1,1,1;1,1,1;1,1,1) $ $ R = 1 / 9 sum_(i=1)^9 z_i $ 均值滤波器是一个 "box filter",就是说它所有的系数都是相同的。它平滑了图像的同时也让边缘细节变得模糊。 === 加权滤波器 $ 1 / 16 * mat(1,2,1;2,4,2;1,2,1) $ 使用加权平均的方式,让中心像素的权重更大,边缘像素的权重更小。这样可以在平滑的时候减少模糊。 === 中值滤波器 中值滤波器是一种非线性滤波器,它的输出是输入像素的中值。这种滤波器对于去除椒盐噪声和斑点噪声有很好的效果。 == 锐化滤波器 Sharpening Filters #definition[*锐化滤波器*:让图像的细节更加清晰的滤波器,或者让模糊的细节更加清晰] 主要在电子显微镜、医学成像、工业检测等领域使用。可以通过空间微分来实现锐化滤波。 === 理论基础 一阶微分: $ (partial f) / (partial x) = f(x+1) - f(x) $ 二阶微分: $ (partial^2 f) / (partial x^2) = f(x+1) + f(x-1) - 2f(x) $ === 拉普拉斯算子 Laplacian Operator 拉普拉斯算子是一个*二阶微分*算子,可以用来检测图像中的边缘。它的定义如下: $ nabla^2 f = (partial^2 f) / (partial x^2) + (partial^2 f) / (partial y^2)\ (partial^2 f) / (partial x^2) = f(x+1, y) + f(x-1, y) - 2f(x, y)\ (partial^2 f) / (partial y^2) = f(x, y+1) + f(x, y-1) - 2f(x, y)\ nabla^2 f = f(x+1, y) + f(x-1, y) + f(x, y+1) + f(x, y-1) - 4f(x, y) $ 写成矩阵形式: $ nabla^2 f = mat(0,1,0;1,-4,1;0,1,0) * f $ 这个算子可以用来检测图像中的 $x$ 和 $y$ 方向的边缘。可以扩展成可以检测斜向边缘的算子: $ nabla^2 f = mat(1,1,1;1,-8,1;1,1,1) * f $ 取反也是可以的: #grid( columns: (1fr, 1fr), )[ $ nabla^2 f = mat(0,-1,0;-1,4,-1;0,-1,0) * f $ ][ $ nabla^2 f = mat(-1,-1,-1;-1,8,-1;-1,-1,-1) * f $ ] 对图像进行锐化的时候,要判断一下拉普拉斯算子中心的值是否为正。如果是负的,就要取反。 $ g( x, y ) = cases( f(x, y) + nabla^2 f(x, y) ",当" nabla^2 f(x, y) > 0, f(x, y) - nabla^2 f(x, y) ",当" nabla^2 f(x, y) < 0 ) $ 其实这样就变成了: $ g(x, y) &= f(x, y) - [f(x+1, y) + f(x-1, y) + f(x, y+1) + f(x, y-1) - 4f(x, y)]\ &= bold(5)f(x, y) - f(x+1, y) - f(x-1, y) - f(x, y+1) - f(x, y-1) $ 即: $ mat(0,-1,0;-1,bold(5),-1;0,-1,0) * f $ 还可以用于unsharp masking 和 high-boost filtering,即在中心像素上加上一个系数 $A (A>=1)$(比如普通的锐化就是直接加上原图,这时候可以认为$A=1$),这样就能从模糊的图像中提取出细节,让图像更加清晰。 === Sobel 算子 Sobel 算子是一种常用的边缘检测算子,它是一种一阶微分算子,可以用来检测图像中的边缘。它的定义如下: #grid( columns: (1fr, 1fr), )[ $ nabla f = mat(-1,0,1;-2,0,2;-1,0,1) * f $ ][ $ nabla f = mat(-1,-2,-1;0,0,0;1,2,1) * f $ ] Sobel 算子可以检测图像中的水平和垂直边缘,可以通过这两个算子的组合来检测图像中的所有边缘。 这学期的实验二是把 Sobel 算子编码到卷积核中,然后用卷积核对图像进行卷积,得到边缘图像。 ```python import torch import torch.nn as nn from PIL import Image import numpy as np # Sobel 算子 sobel_kernel_x = np.array( [[1, 0, -1], [2, 0, -2], [1, 0, -1]], dtype=np.float32 ) sobel_kernel_y = np.array( [[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=np.float32 ) conv_kernel_sobel_x = sobel_kernel_x.reshape(1, 1, 3, 3) # i * o * h * w conv_kernel_sobel_y = sobel_kernel_y.reshape(1, 1, 3, 3) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv_x = nn.Conv2d(1, 1, 3, padding=1, bias=False) # padding是为了保证输出和输入的尺寸一样,它是在输入的周围补0 self.conv_y = nn.Conv2d(1, 1, 3, padding=1, bias=False) self.conv_x.weight.data = torch.from_numpy(conv_kernel_sobel_x) self.conv_y.weight.data = torch.from_numpy(conv_kernel_sobel_y) def forward(self, img): res_x = self.conv_x(img) res_y = self.conv_y(img) return res_x, res_y net = Net() input_path = 'imgs/100_3228.jpg' output_path = 'outputs/exp2_3_1.jpg' image = Image.open(input_path).convert('L') image = torch.from_numpy(image).unsqueeze(0).unsqueeze(0) # 增加两个维度,变成 1 * 1 * H * W res_x, res_y = net(image) res_x = np.abs(res_x.detach().numpy().squeeze()) # squeeze()让shape为1的维度去掉 res_y = np.abs(res_y.detach().numpy().squeeze()) res = np.sqrt(res_x ** 2 + res_y ** 2) # 保存图片 ``` == Canny 边缘检测 Canny 边缘检测是一种多步骤的边缘检测算法,由 <NAME> 于 1986 年提出。他的目标是找到一个最优的边缘检测结果。所谓最优的边缘检测结果,是指: - 尽可能多地检测到边缘 - 边缘尽可能准确 - 边缘应当只被检测一次,同时尽可能不被检测到假边缘 它的步骤如下: + 使用高斯滤波器平滑图像,以减少噪声 + 计算图像的梯度强度和方向 - 使用 Sobel 算子分别对图像进行卷积,得到水平和垂直方向的梯度 + #grid( columns: 2, column-gutter: 1em, )[ 非极大值抑制:对梯度强度图进行处理,以便消除非边缘像素 - 就是说上一步中得到的梯度方向,如果这个像素的梯度强度不是这个方向上最大的,就把这个像素的梯度强度设为0。比如右边这个例子,梯度方向沿B、C点是水平的,那就可以让 A、B、C 三个点一起看 A 是不是一个极大值,如果是就保留,否则设为0。 ][ #image("../assets/2024-06-20-23-33-34.png") ] + #grid( columns: 2, column-gutter: 1em, )[ 滞后阈值:确定哪些边缘是真实的边缘 - 这个阶段需要两个阈值,也就是划定一个高阈值和一个低阈值,如果梯度强度超过高阈值,就认为是边缘;如果梯度强度在低阈值和高阈值之间,就要看这个像素是否与高阈值像素相连,如果是就认为是边缘;如果不是就认为不是边缘。 - 右边这张图中,C、B都在低阈值和高阈值之间,但是 C 与 A 相连,而B不和任何确定的边缘相连,所以只保留 C。 ][ #image("../assets/2024-06-20-23-36-15.png") ] - 如果边缘是长线的话,这一步也能消除一些噪声
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/multicore/pset6b.typ
typst
#import "template.typ": * #show: template.with( title: "6.5081 PSET 6B", subtitle: "<NAME>", pset: true ) = Overview #note( title: "Warning", )[ It is *CRITICAL* to note that all my testing relies on the initial states of every source being allowed to send, and all destinations receiving from all sources. Without this assumption, testing is impossible to do on a parallel sense. I have tried multiple times and spent easily over 15+ hours checking this. The steady state is nowhere near sufficient enough, especially in the latter configurations where the number of `ConfigPacket`s are small, and even running for a long time yields very few packets that can be accepted. This means that unless we *start* with everything available, the fingerprinting and all the work there will simply not happen as virtually no sources or destinations are valid. I think that this is a fundamental design flaw of this PSET that should be taken into consideration for next year. ] In this final lab of 6.5081, I implemented a parallel firewall system that processes packets concurrently. The system is designed to handle a large number of packets and is optimized for performance. The system is designed to be scalable and efficient, with the ability to process packets in parallel using multiple threads. I will cover the design as well as practical performance of my implementation in the upcoming sections. The full code for my testing script and the Java implementation can be found at the end of the document. All the Java code is written in a single file, `Firewall.java`, which contains both the serial and parallel implementations of the firewall system. The Python script `benchmark.py` is used to run the Java code with different configurations and measure the performance of the system. This is a very messy script and works insomuch as it acts as a framework to conveniently run the Java code with different configurations. Despite having all the code at the bottom, I will be pulling up segments of the Java code in some sections to accurately explain each part without having to constantly look at the bottom of the document. = Overall Design and Specification Requirements The overall design of the project was meant to be straightforward without implementing anything too complicated. Below is the main body of code that runs in the parallel implementation. ```java public static void main(String[] args) { // parse args if (args.length != 12) { System.out.println("Invalid number of arguments " + args.length + " != 12"); return; } int numAddressesLog = Integer.parseInt(args[0]); int numTrainsLog = Integer.parseInt(args[1]); double meanTrainSize = Double.parseDouble(args[2]); double meanTrainsPerComm = Double.parseDouble(args[3]); int meanWindow = Integer.parseInt(args[4]); int meanCommsPerAddress = Integer.parseInt(args[5]); int meanWork = Integer.parseInt(args[6]); double configFraction = Double.parseDouble(args[7]); double pngFraction = Double.parseDouble(args[8]); double acceptingFraction = Double.parseDouble(args[9]); int time = Integer.parseInt(args[10]); int threads = Integer.parseInt(args[11]); generator = new PacketGenerator( numAddressesLog, numTrainsLog, meanTrainSize, meanTrainsPerComm, meanWindow, meanCommsPerAddress, meanWork, configFraction, pngFraction, acceptingFraction ); for (int i = 0; i < PNG.length; i++) { PNG[i] = false; } for (int i = 0; i < (1 << numAddressesLog); i++) { D.put(i, new RangeSum()); D.get(i).add(0, (1 << numAddressesLog)); } // allow the system to reach steady state int steady_iterations = (int) Math.pow((1 << (numAddressesLog)), 3.0 / 2.0); System.out.println("Steady iterations: " + steady_iterations); for (int i = 0; i < steady_iterations; i++) { Packet packet = generator.getPacket(); if (packet.type == Packet.MessageType.ConfigPacket) { int addr = packet.config.address; boolean png = packet.config.personaNonGrata; int addrBegin = packet.config.addressBegin; int addrEnd = packet.config.addressEnd; boolean accept = packet.config.acceptingRange; // edit PNG PNG[addr] = png; // edit D if (!D.containsKey(addr)) { D.put(addr, new RangeSum()); } if (accept) { D.get(addr).add(addrBegin, addrEnd); } else { D.get(addr).remove(addrBegin, addrEnd); } } } System.out.println("Steady state reached"); histLock = new MCSLock(); locks = new MCSLock[1 << numAddressesLog]; for (int i = 0; i < (1 << numAddressesLog); i++) { locks[i] = new MCSLock(); } workload = new WaitFreeQueue[threads]; for (int i = 0; i < threads; i++) { workload[i] = new WaitFreeQueue(256); } Worker[] workers = new Worker[threads]; for (int i = 0; i < threads; i++) { workers[i] = new Worker(i, workload[i]); } Distributor distributor = new Distributor(); Thread distributor_thread = new Thread(distributor); distributor_thread.start(); Thread[] worker_threads = new Thread[threads]; for (int i = 0; i < threads; i++) { worker_threads[i] = new Thread(workers[i]); worker_threads[i].start(); } try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } // distributor.running = false; try { distributor_thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < threads; i++) { workers[i].running = false; try { worker_threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } // System.out.println("Total packets processed: " + distributor.total_packets); System.out.println("packet/s count: " + (double)distributor.total_packets / (time / 1000.0)); } ``` The first thing that happens is the parsing of the arguments. You see that for the parallel version, there are two additional arguments that come at the end, which are the number of threads as well as the time which this parallel testing should run. This allows us to expose this option to the tester. We then make the generator, and run the serial version of the code for $A^(3/2)$ iterations to allow the system to reach a steady state. Once this is done, we can start the parallel part of the code. Lines `60-84` instantiate a lot of our needed classes and objects, such as the locks, the workload, the workers, and the distributor. The distributor is the one that generates the packets and sends them to the workers. The workers then process the packets and update the `PNG` and `D` arrays accordingly. The `locks` array use my implementation of the `MCSLock` class, which is a lock that is designed to be more efficient than the `ReentrantLock` class in specific cases. The `WaitFreeQueue` class is a simple queue that is used to store the packets that are generated by the distributor and are processed by the workers. We then start the distributor, followed by the workers, letting them run for the specified amount of time before issuing the stop command through the `.running` variable and waiting for all threads to catch up at the end. We will now take a look at the `Distibutor` and `Worker` classes. *`Distributor`* ```java static class Distributor implements Runnable { volatile boolean running = true; int total_packets = 0; Distributor() {} public void run() { while (running) { if (flight.get() >= 256) { continue; } Packet packet = generator.getPacket(); flight.incrementAndGet(); if (packet.type == Packet.MessageType.ConfigPacket) { while (running) { try { workload[packet.config.address % workload.length].enq(packet); total_packets++; break; } catch (Exception e) { continue; } } } else { while (running) { try { workload[packet.header.source % workload.length].enq(packet); total_packets++; break; } catch (Exception e) { continue; } } } } } } ``` The distributor class is relatively straightforward, but has a couple note worthy points. One of the important things is the `flight` variable from the parent `ParallelFirewall` class, which represents the number of packets that are currently being processed. This is used to ensure that the distributor does not send more packets than the system can handle. Every time we get a packet, this count increases, and we will see later that the workers decrease this count once they are done processing a packet. One other thing to note is how I choose to allocate the packets. The packets are distributed according to the modulo of the source address. This approach seemed to work quite well compared to other method I tried, which seemed to be represented in the results which will be shown later. We also keep track of the `total_packets` processed by the distributor by incrementing it whenever we successfully enqueue a packet to one of the queues of the worker. *`Worker`* ```java static class Worker implements Runnable { volatile boolean running = true; int threadId; WaitFreeQueue workload; Worker(int threadId, WaitFreeQueue workload) { this.threadId = threadId; this.workload = workload; } public void run() { while (running) { try { Packet packet = workload.deq(); if (packet.type == Packet.MessageType.ConfigPacket) { int addr = packet.config.address; boolean png = packet.config.personaNonGrata; int addrBegin = packet.config.addressBegin; int addrEnd = packet.config.addressEnd; boolean accept = packet.config.acceptingRange; locks[addr].lock(); // edit PNG PNG[addr] = png; // edit D if (!D.containsKey(addr)) { D.put(addr, new RangeSum()); } if (accept) { D.get(addr).add(addrBegin, addrEnd); } else { D.get(addr).remove(addrBegin, addrEnd); } locks[addr].unlock(); } else { int source = packet.header.source; int dest = packet.header.dest; locks[source].lock(); boolean png = !PNG[source]; locks[source].unlock(); locks[dest].lock(); boolean d = D.containsKey(dest) && D.get(dest).verify(source); locks[dest].unlock(); if (png && d) { long fingerprint = Fingerprint.getFingerprint(packet.body.iterations, packet.body.seed); histLock.lock(); hist.put(fingerprint, hist.getOrDefault(fingerprint, 0) + 1); histLock.unlock(); } } flight.decrementAndGet(); } catch (Exception e) {} } } } ``` Each worker essentially does the sequential version of processing the packets. We can see the aforementioned `flight` decrement on line `57`. Importantly, we have all the locks that are being turned on and off. This happens around critical sections of the code that modify the `PNG` and `D` data structures. The way I chose to implement these locks is to have one for each address. The range of addresses in most cases is reasonable enough that this is not a problem. We can see that the locks are used on lines `22`, `36`, `41`, `43`, `45`, `47`, as well as the lock for the histogram on `51` and `53`. The idea of only having one lock for the histogram is that it won't be contested as much as other operations because of the time of the fingerprint. The other locks are used to ensure that the `PNG` and `D` arrays are not modified by multiple workers at the same time. This is important because the workers are running concurrently and could potentially modify the same data structures at the same time. The underlying data structures are not inherently concurrent, so we need to use locks to ensure that they are modified correctly with locks. With this implementation, we see that many requirements are already met, such as the packet flight limit as well as the updating of the histogram and steady state waiting. = Data Structures == `RangeSum` ```java class RangeSum { TreeMap < Integer, Integer > ranges; RangeSum() { ranges = new TreeMap < > (); } void add(int a, int b) { if (a >= b) { return; } Map.Entry < Integer, Integer > lb = ranges.lowerEntry(b); if (lb != null && lb.getValue() >= a) { while (lb != null && lb.getKey() <= b) { a = Math.min(a, lb.getKey()); b = Math.max(b, lb.getValue()); ranges.remove(lb.getKey()); lb = ranges.lowerEntry(b); } } ranges.put(a, b); } void remove(int a, int b) { if (a >= b) { return; } Map.Entry < Integer, Integer > floor = ranges.floorEntry(a); ArrayList < int[] > update = new ArrayList < > (); while (floor != null && floor.getValue() >= a) { if (floor.getKey() < a) { update.add(new int[] { floor.getKey(), a }); } if (floor.getValue() > b) { update.add(new int[] { b, floor.getValue() }); } ranges.remove(floor.getKey()); floor = ranges.floorEntry(b); } for (int[] interval: update) { ranges.put(interval[0], interval[1]); } } boolean verify(int x) { Map.Entry < Integer, Integer > floor = ranges.floorEntry(x); return floor != null && floor.getValue() > x; } } ``` `RangeSum` is my solution for how to manage ranges of addresses that are allowed to be accepted. The `add` function adds a range to the `TreeMap` of ranges, while the `remove` function removes a range from the `TreeMap`. The `verify` function checks if a given address is within any of the ranges in the `TreeMap`. This is used to check if a source address is allowed to send packets to a destination address. I believed that this is more efficient that the suggested skiplist implementation, and this is a competitive coding construct that I have used countless times to solve this problem. Again, there is nothing particularly concurrent about this data structure, but it is used in a concurrent context with locks controlling access to it. This class is very efficient and allows us to do operations in logarithmic time, which I believe helped greatly in the final runtime. The class is trivially linearizable. == `WaitFreeQueue` ```java // implemented from chapter 3 static class WaitFreeQueue { volatile int head = 0, tail = 0; Packet[] items; public WaitFreeQueue(int capacity) { items = new Packet[capacity]; head = 0; tail = 0; } public void enq(Packet x) throws Exception { if (tail - head == items.length) { throw new Exception(); } items[tail % items.length] = x; tail++; } public Packet deq() throws Exception { if (tail - head == 0) { throw new Exception(); } Packet x = items[head % items.length]; head++; return x; } } ``` This class is the queue that each worker and distributor uses to store packets. The queue is implemented as a circular buffer, which allows for efficient enqueuing and dequeuing of packets. The queue is wait-free, which means that each operation is guaranteed to complete in a finite number of steps, regardless of the number of threads accessing the queue. This is important because the workers and distributor are running concurrently and need to be able to access the queue without blocking each other. This implementation is directly from a previous lab where we implemented it from chapter 3 of the textbook. The proof of the data structure being wait-free and linearizable are given in the textbook and I will not reiterate it here for conciseness. This queue is not locked from use, because only one thread is enqueueing and one thread is dequeuing (the distributor and specific worker). == `MCSLock` ```java static class MCSLock { private static class MCSNode { volatile MCSNode next; volatile boolean locked = false; } private final ThreadLocal < MCSNode > node; private final AtomicReference < MCSNode > tail; public MCSLock() { tail = new AtomicReference < > (null); node = ThreadLocal.withInitial(MCSNode::new); } public void lock() { MCSNode currentNode = node.get(); MCSNode predecessor = tail.getAndSet(currentNode); if (predecessor != null) { currentNode.locked = true; predecessor.next = currentNode; // spin until predecessor gives up the lock while (currentNode.locked) {} } } public void unlock() { MCSNode currentNode = node.get(); if (currentNode.next == null) { if (tail.compareAndSet(currentNode, null)) { return; } // wait until successor appears while (currentNode.next == null) {} } currentNode.next.locked = false; currentNode.next = null; } } ``` This is the lock that I used for the `PNG` and `D` arrays. This lock is a more efficient lock than the `ReentrantLock` class in specific cases. I actually reimplemented the lock by hand compared to the previous lab, which I think led to a performance increase. As discussed in class, the MCSLock is deadlock and starvation free, but not necessarily wait free or lock free. Once again, the lienarizability is proven in the textbook and I will not reiterate it here. I will discuss in a later section what the advantage and disadvantage of this lock is compared to the `ReentrantLock` class, which I tried using before. = Performance Testing and Analysis Testing was done using the `benchmark.py` script, which runs the Java code with different configurations. There was a different approach to testing the serial and parallel implementations. The serial version was tested based on how look running a number of iterations took, while the parallel version was tested based on how many packets were processed in a given time frame. This is because pausing time inherently utilizes Threads, which we should reserve for a parallel system. It is also not possible to accurately run until a certain amount of packets are processed in a parallel system due to the nature the interweaving of counting and parallel workers. Thus, the serial version was tested to see how long it would take to run $1 . 000 . 000$ packets and the parallel version was tested to see how many packets could be processed in $1$ second. The final tests for each were averaged over 5 attempts on each configuration possibility. Even on the serial version, to ensure stability and a steady state, I ran the code for half a million packets. The results are shown below. The units for all the numbers are `packets / second` for the throughput and are simple ratios for the parallelism. Please note that I am using the dot $.$ in place of the comma $,$ for readability. == Throughput #twocol( [ === Serial Throughput / *`Configuration 1`*: $185.685$ / *`Configuration 2`*: $203.331$ / *`Configuration 3`*: $394.808$ / *`Configuration 4`*: $1.069.518$ / *`Configuration 5`*: $144.112$ / *`Configuration 6`*: $87.237$ / *`Configuration 7`*: $107.968$ / *`Configuration 8`*: $71.438$ ], [ === Parallel Throughput `n=2` / *`Configuration 1`*: $258.566$ / *`Configuration 2`*: $323.999$ / *`Configuration 3`*: $503.096$ / *`Configuration 4`*: $1.218.549$ / *`Configuration 5`*: $204.654$ / *`Configuration 6`*: $137.129$ / *`Configuration 7`*: $179.100$ / *`Configuration 8`*: $125.041$ ] ) #twocol( [ === Parallel Throughput `n=4` / *`Configuration 1`*: $461.146$ / *`Configuration 2`*: $537.745$ / *`Configuration 3`*: $842.239$ / *`Configuration 4`*: $1.449.415$ / *`Configuration 5`*: $424.482$ / *`Configuration 6`*: $255.904$ / *`Configuration 7`*: $361.329$ / *`Configuration 8`*: $220.588$ ], [ === Parallel Throughput `n=8` / *`Configuration 1`*: $807.605$ / *`Configuration 2`*: $868.646$ / *`Configuration 3`*: $1.216.015$ / *`Configuration 4`*: $1.266.260$ / *`Configuration 5`*: $701.320$ / *`Configuration 6`*: $442.627$ / *`Configuration 7`*: $588.897$ / *`Configuration 8`*: $407.789$ ] ) == Parallelism #twocol( [ === Serial Parallelism / *`Configuration 1`*: 1 / *`Configuration 2`*: 1 / *`Configuration 3`*: 1 / *`Configuration 4`*: 1 / *`Configuration 5`*: 1 / *`Configuration 6`*: 1 / *`Configuration 7`*: 1 / *`Configuration 8`*: 1 ], [ === Parallel Parallelism `n=2` / *`Configuration 1`*: 1.39 / *`Configuration 2`*: 1.59 / *`Configuration 3`*: 1.27 / *`Configuration 4`*: 1.14 / *`Configuration 5`*: 1.42 / *`Configuration 6`*: 1.57 / *`Configuration 7`*: 1.66 / *`Configuration 8`*: 1.75 ] ) #twocol( [ === Parallel Parallelism `n=4` / *`Configuration 1`*: 2.48 / *`Configuration 2`*: 2.64 / *`Configuration 3`*: 2.13 / *`Configuration 4`*: 1.36 / *`Configuration 5`*: 2.95 / *`Configuration 6`*: 2.93 / *`Configuration 7`*: 3.35 / *`Configuration 8`*: 3.09 ], [ === Parallel Parallelism `n=8` / *`Configuration 1`*: 4.35 / *`Configuration 2`*: 4.27 / *`Configuration 3`*: 3.08 / *`Configuration 4`*: 1.18 / *`Configuration 5`*: 4.87 / *`Configuration 6`*: 5.07 / *`Configuration 7`*: 5.45 / *`Configuration 8`*: 5.71 ] ) == Analysis There were some known results that I expected, as well as some surprising results that were shown in the parallel versions of the code. I will discuss some hypotheses I had about my code, and what the actual results were, and how the parts of my code impact this parallelism. Firstly, it is interesting to note that the speedup gained was not directly proportional to the number of parallel workers. This is of course, to be expected since it is not possible to parallelize 100% of the program. Roughly looking at the number, it appears like two threads resulted in a $1.4$ times speedup, four threads resulted in a $2.8$ times speedup, and eight threads resulted in a $4.7$ times speedup. This is not a terrible scaling, but is a bit below what I desired for how parallel I thought the system was. The overall gains were pretty consistent across the board - of course there were some major differences on certain configurations that I will touch on. It appears that the fourth configuration had something going on that made it very hard to parallelize. Looking at the statistic, the thing that sticks out the most is the low amount of work. Recall that we had a lock around the histogram. My belief here is that with such a low average work amount, the bottleneck no longer becomes the actual calculation itself, but the contesting of the singular lock that is controlling the histogram. This is why the speedup is so low on this configuration. It was actually the case for this particular configuration that we saw a dip in performance when we went to eight workers, although it was still better than two workers. Out of curiosity I ran the test with sixteen workers and found that it now matched the four worker case. Because the `DataPacket`s don't pose a significant amount of work, the lock is the main bottleneck in this case, and is why I think the performance was hard to optimize. One way that I believe I could have done this better was to make a concurrent data structure for the histogram, which would have allowed for more parallelism. I unfortunately did not have the time to do this, and as such the performance was not as good as it could have been. The other interesting thing to note is that the last two configurations `7` and `8` had a very high speedup. This is because the workload was very high, and the lock was not as contested. This is why the speedup was so high in these cases. This is essentially the opposite of the previous case. Because the actual work itself was so hard, having multiple threads greatly helped reduce the amount of overall work being done. It's not hard to imagine how much faster this could have been with an improved histogram. The other configurations were more or less as expected. The speedup was not as high as I would have liked, but it was still a good speedup. The parallelism was not as high as I would have liked, but it was still a good parallelism. The overall performance was good, but could have been better with some improvements to the code. One thing to point out about a different part of my code is the `RangeSum` class. I believe this was efficient enough to the point where it actually became an anti-bottleneck. Looking at the results, in the first couple configurations, which have higher rates of `ConfigPacket`s, the parallelism is not as good, because the work in updating the configs is being done so fast, and my assumption is that the locks are the main bottleneck here again. Another huge contributing factor the performance of my system could be the locks. I believe the implementation of the lock plays a critical role in the performance. The MCSLock is very efficient when there are many threads contending for the lock, but it is not as efficient when there are only a few threads. With so many addresses, this may not have been the best approach in some cases, which is why perhaps large address ranges didn't have the best parallel performance, because the lock was not being contested as much as it would need to be for these benefits to outweight the overhead. On the other hand, the lock is also very good at a high number of threads since each thread stores their lock in memory which is likely to lead to must faster locking and unlocking. I was unable to do extensive testing with a different number of locks, but `ReentrantLock` was tested and had a similar performance to the MCSLock in the serial system, but was much slower in the parallel system. = Code == *`Firewall.java`* ```java // imports import java.util.HashMap; import java.util.Random; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.ReentrantLock; /* * requirements: * ------------- * - only 256 packets are being processed at any one time * - generate a histogram of all fingerprints * - process 2^(numaddresseslog) packets to reach stable state */ import java.util.*; class RangeSum { TreeMap<Integer, Integer> ranges; RangeSum() { ranges = new TreeMap<>(); } void add(int a, int b) { if (a >= b) { return; } Map.Entry<Integer, Integer> lb = ranges.lowerEntry(b); if (lb != null && lb.getValue() >= a) { while (lb != null && lb.getKey() <= b) { a = Math.min(a, lb.getKey()); b = Math.max(b, lb.getValue()); ranges.remove(lb.getKey()); lb = ranges.lowerEntry(b); } } ranges.put(a, b); } void remove(int a, int b) { if (a >= b) { return; } Map.Entry<Integer, Integer> floor = ranges.floorEntry(a); ArrayList<int[]> update = new ArrayList<>(); while (floor != null && floor.getValue() >= a) { if (floor.getKey() < a) { update.add(new int[]{floor.getKey(), a}); } if (floor.getValue() > b) { update.add(new int[]{b, floor.getValue()}); } ranges.remove(floor.getKey()); floor = ranges.floorEntry(b); } for (int[] interval: update) { ranges.put(interval[0], interval[1]); } } boolean verify(int x) { Map.Entry<Integer, Integer> floor = ranges.floorEntry(x); return floor != null && floor.getValue() > x; } } class SerialFirewall { // D and PNG arrays as described in the PSET handout static HashMap<Integer, RangeSum> D = new HashMap<>(); static boolean[] PNG = new boolean[1 << 17]; // set to the max size static HashMap<Long, Integer> hist = new HashMap<>(); public static void main(String[] args) { // parse args if (args.length != 11) { System.out.println("Invalid number of arguments " + args.length + " != 11"); return; } int numAddressesLog = Integer.parseInt(args[0]); int numTrainsLog = Integer.parseInt(args[1]); double meanTrainSize = Double.parseDouble(args[2]); double meanTrainsPerComm = Double.parseDouble(args[3]); int meanWindow = Integer.parseInt(args[4]); int meanCommsPerAddress = Integer.parseInt(args[5]); int meanWork = Integer.parseInt(args[6]); double configFraction = Double.parseDouble(args[7]); double pngFraction = Double.parseDouble(args[8]); double acceptingFraction = Double.parseDouble(args[9]); int iterations = Integer.parseInt(args[10]); PacketGenerator generator = new PacketGenerator( numAddressesLog, numTrainsLog, meanTrainSize, meanTrainsPerComm, meanWindow, meanCommsPerAddress, meanWork, configFraction, pngFraction, acceptingFraction ); for (int i = 0; i < PNG.length; i++) { PNG[i] = false; } for (int i = 0; i < (1 << numAddressesLog); i++) { D.put(i, new RangeSum()); D.get(i).add(0, (1 << numAddressesLog)); } double startTime = System.currentTimeMillis(); for (int i = 0; i < iterations + 500000; i++) { if (i == 500000) { startTime = System.currentTimeMillis(); } Packet packet = generator.getPacket(); if (packet.type == Packet.MessageType.ConfigPacket) { int addr = packet.config.address; boolean png = packet.config.personaNonGrata; int addrBegin = packet.config.addressBegin; int addrEnd = packet.config.addressEnd; boolean accept = packet.config.acceptingRange; // edit PNG PNG[addr] = png; // edit D if (!D.containsKey(addr)) { D.put(addr, new RangeSum()); } if (accept) { D.get(addr).add(addrBegin, addrEnd); } else { D.get(addr).remove(addrBegin, addrEnd); } } else { int source = packet.header.source; int dest = packet.header.dest; if (!PNG[source] && D.containsKey(dest) && D.get(dest).verify(source)) { long fingerprint = Fingerprint.getFingerprint(packet.body.iterations, packet.body.seed); hist.put(fingerprint, hist.getOrDefault(fingerprint, 0) + 1); } } } double endTime = System.currentTimeMillis(); double elapsed = (endTime - startTime) / 1000.0; System.out.println("packet/s count: " + iterations / elapsed); } } class ParallelFirewall { // D and PNG arrays as described in the PSET handout static HashMap<Integer, RangeSum> D = new HashMap<>(); static boolean[] PNG = new boolean[1 << 17]; // set to the max size static HashMap<Long, Integer> hist = new HashMap<>(); static WaitFreeQueue[] workload; static PacketGenerator generator; static MCSLock[] locks; static volatile AtomicInteger flight = new AtomicInteger(0); static MCSLock histLock; public static void main(String[] args) { // parse args if (args.length != 12) { System.out.println("Invalid number of arguments " + args.length + " != 12"); return; } int numAddressesLog = Integer.parseInt(args[0]); int numTrainsLog = Integer.parseInt(args[1]); double meanTrainSize = Double.parseDouble(args[2]); double meanTrainsPerComm = Double.parseDouble(args[3]); int meanWindow = Integer.parseInt(args[4]); int meanCommsPerAddress = Integer.parseInt(args[5]); int meanWork = Integer.parseInt(args[6]); double configFraction = Double.parseDouble(args[7]); double pngFraction = Double.parseDouble(args[8]); double acceptingFraction = Double.parseDouble(args[9]); int time = Integer.parseInt(args[10]); int threads = Integer.parseInt(args[11]); generator = new PacketGenerator( numAddressesLog, numTrainsLog, meanTrainSize, meanTrainsPerComm, meanWindow, meanCommsPerAddress, meanWork, configFraction, pngFraction, acceptingFraction ); for (int i = 0; i < PNG.length; i++) { PNG[i] = false; } for (int i = 0; i < (1 << numAddressesLog); i++) { D.put(i, new RangeSum()); D.get(i).add(0, (1 << numAddressesLog)); } // allow the system to reach steady state int steady_iterations = (int) Math.pow((1 << (numAddressesLog)), 3.0 / 2.0); System.out.println("Steady iterations: " + steady_iterations); for (int i = 0; i < steady_iterations; i++) { Packet packet = generator.getPacket(); if (packet.type == Packet.MessageType.ConfigPacket) { int addr = packet.config.address; boolean png = packet.config.personaNonGrata; int addrBegin = packet.config.addressBegin; int addrEnd = packet.config.addressEnd; boolean accept = packet.config.acceptingRange; // edit PNG PNG[addr] = png; // edit D if (!D.containsKey(addr)) { D.put(addr, new RangeSum()); } if (accept) { D.get(addr).add(addrBegin, addrEnd); } else { D.get(addr).remove(addrBegin, addrEnd); } } } System.out.println("Steady state reached"); histLock = new MCSLock(); locks = new MCSLock[1 << numAddressesLog]; for (int i = 0; i < (1 << numAddressesLog); i++) { locks[i] = new MCSLock(); } workload = new WaitFreeQueue[threads]; for (int i = 0; i < threads; i++) { workload[i] = new WaitFreeQueue(256); } Worker[] workers = new Worker[threads]; for (int i = 0; i < threads; i++) { workers[i] = new Worker(i, workload[i]); } Distributor distributor = new Distributor(); Thread distributor_thread = new Thread(distributor); distributor_thread.start(); Thread[] worker_threads = new Thread[threads]; for (int i = 0; i < threads; i++) { worker_threads[i] = new Thread(workers[i]); worker_threads[i].start(); } try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } // distributor.running = false; try { distributor_thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < threads; i++) { workers[i].running = false; try { worker_threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } // System.out.println("Total packets processed: " + distributor.total_packets); System.out.println("packet/s count: " + (double)distributor.total_packets / (time / 1000.0)); } // implemented from chapter 3 static class WaitFreeQueue { volatile int head = 0, tail = 0; Packet[] items; public WaitFreeQueue(int capacity) { items = new Packet[capacity]; head = 0; tail = 0; } public void enq(Packet x) throws Exception { if (tail - head == items.length) { throw new Exception(); } items[tail % items.length] = x; tail++; } public Packet deq() throws Exception { if (tail - head == 0) { throw new Exception(); } Packet x = items[head % items.length]; head++; return x; } } // make a distributor worker who takes in the generator and communicates with the labor workers, they will run as threads static class Distributor implements Runnable { volatile boolean running = true; int total_packets = 0; Distributor() {} public void run() { while (running) { if (flight.get() >= 256) { continue; } Packet packet = generator.getPacket(); flight.incrementAndGet(); if (packet.type == Packet.MessageType.ConfigPacket) { while(running) { try { workload[packet.config.address % workload.length].enq(packet); total_packets++; break; } catch (Exception e) { continue; } } } else { while (running) { try { workload[packet.header.source % workload.length].enq(packet); total_packets++; break; } catch (Exception e) { continue; } } } } } } static class Worker implements Runnable { volatile boolean running = true; int threadId; WaitFreeQueue workload; Worker(int threadId, WaitFreeQueue workload) { this.threadId = threadId; this.workload = workload; } public void run() { while (running) { try { Packet packet = workload.deq(); if (packet.type == Packet.MessageType.ConfigPacket) { int addr = packet.config.address; boolean png = packet.config.personaNonGrata; int addrBegin = packet.config.addressBegin; int addrEnd = packet.config.addressEnd; boolean accept = packet.config.acceptingRange; locks[addr].lock(); // edit PNG PNG[addr] = png; // edit D if (!D.containsKey(addr)) { D.put(addr, new RangeSum()); } if (accept) { D.get(addr).add(addrBegin, addrEnd); } else { D.get(addr).remove(addrBegin, addrEnd); } locks[addr].unlock(); } else { int source = packet.header.source; int dest = packet.header.dest; locks[source].lock(); boolean png = !PNG[source]; locks[source].unlock(); locks[dest].lock(); boolean d = D.containsKey(dest) && D.get(dest).verify(source); locks[dest].unlock(); if (png && d) { long fingerprint = Fingerprint.getFingerprint(packet.body.iterations, packet.body.seed); histLock.lock(); hist.put(fingerprint, hist.getOrDefault(fingerprint, 0) + 1); histLock.unlock(); } } flight.decrementAndGet(); } catch (Exception e) { } } } } static class MCSLock { private static class MCSNode { volatile MCSNode next; volatile boolean locked = false; } private final ThreadLocal<MCSNode> node; private final AtomicReference<MCSNode> tail; public MCSLock() { tail = new AtomicReference<>(null); node = ThreadLocal.withInitial(MCSNode::new); } public void lock() { MCSNode currentNode = node.get(); MCSNode predecessor = tail.getAndSet(currentNode); if (predecessor != null) { currentNode.locked = true; predecessor.next = currentNode; // spin until predecessor gives up the lock while (currentNode.locked) { } } } public void unlock() { MCSNode currentNode = node.get(); if (currentNode.next == null) { if (tail.compareAndSet(currentNode, null)) { return; } // wait until successor appears while (currentNode.next == null) { } } currentNode.next.locked = false; currentNode.next = null; } } } ``` == *`benchmark.py`* ```python import subprocess import time import sys configs = [ [11, 12, 5, 1, 3, 3, 3822, 0.24, 0.04, 0.96], [12, 10, 1, 3, 3, 1, 2644, 0.11, 0.01, 0.92], [12, 10, 4, 3, 6, 2, 1304, 0.10, 0.03, 0.90], [14, 10, 5, 5, 6, 2, 315, 0.08, 0.05, 0.90], [15, 14, 9, 16, 7, 10, 4007, 0.02, 0.10, 0.84], [15, 15, 9, 10, 9, 9, 7125, 0.01, 0.20, 0.77], [15, 15, 10, 13, 8, 10, 5328, 0.04, 0.18, 0.80], [16, 14, 15, 12, 9, 5, 8840, 0.04, 0.19, 0.76], ] if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python3 benchmark.py <number of runs> <\"Serial\" / \"Parallel\">") sys.exit(1) iterations = 1000000 time_control = 1000 threads = 8 n = int(sys.argv[1]) type = sys.argv[2] if type not in ["Serial", "Parallel"]: print("Invalid type. Please enter \"Serial\" or \"Parallel\"") sys.exit(1) for i, config in enumerate(configs): print(f"running with config: {i+1}") for i in range(n): start = time.time() # run the subprocess and output stdout if type == "Serial": res = subprocess.run( ["java", "SerialFirewall"] + [str(cfg) for cfg in config] + [str(iterations)], stdout=subprocess.PIPE ) else: res = subprocess.run( ["java", "ParallelFirewall"] + [str(cfg) for cfg in config] + [str(time_control), str(threads)], stdout=subprocess.PIPE ) print(res.stdout) ```
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/book.typ
typst
Apache License 2.0
#import "@preview/shiroa:0.1.1": * #show: book #let book-info = json("/meta.json") #book-meta( title: "The Raindrop-Blue Book (Typst中文教程)", description: "Typst中文教程", repository: "https://github.com/typst-doc-cn/tutorial", repository-edit: "https://github.com/typst-doc-cn/tutorial/edit/main/src/{path}", authors: book-info.contributors, language: "zh-cn", summary: [ #prefix-chapter("introduction.typ")[导引] // 计划修改 = 基础教程 — 排版Ⅰ - #chapter("basic/writing-markup.typ")[初识标记模式] - #chapter("basic/writing-scripting.typ")[初识脚本模式] = 基础教程 — 脚本Ⅰ - #chapter("basic/scripting-literal-and-variable.typ")[常量与变量] - #chapter("basic/scripting-block-and-expression.typ")[块与表达式] - #chapter("basic/scripting-scope-and-style.typ")[内容与样式] = 基础教程 — 排版Ⅱ - #chapter("basic/scripting-length-and-layout.typ")[度量与布局] - #chapter("basic/scripting-color-and-shape.typ")[色彩与图表] = 基础教程 — 脚本Ⅱ - #chapter("basic/modulize-modules.typ")[模块化] - #chapter("basic/modulize-modules.typ")[文件与模块] - #chapter("basic/modulize-packages.typ")[使用外部库] - #chapter("basic/modulize-multi-files-doc.typ")[多文件文档] // 5. 状态化排版 // - 状态 // - 计数器 - #chapter("basic/modulize-modules.typ")[状态化] - #chapter("intermediate/content-stateful.typ")[维护和查询文档状态] - #chapter("intermediate/content-stateful-2.typ")[查询文档状态 -- 制作页眉标题法一] - #chapter("intermediate/content-stateful-3.typ")[维护文档状态 -- 制作页眉标题法二] = 基础教程 — 附录Ⅰ - #chapter("basic/reference-grammar.typ")[语法示例检索表] - #chapter("basic/reference-utils.typ")[常用函数表] - #chapter("basic/reference-math-symbols.typ")[常用数学符号] - #chapter(none)[特殊Unicode字符] = 基础参考 - #chapter("basic/reference-typebase.typ")[基本类型] - #chapter("basic/reference-type-builtin.typ")[内置类型] - #chapter("basic/reference-date.typ")[时间类型] // - #chapter("basic/reference-visualization.typ")[图形与几何元素] // - #chapter("basic/reference-color.typ")[颜色、色彩渐变与模式] - #chapter("basic/reference-data-process.typ")[数据读写] - #chapter("basic/reference-data-process.typ")[数据处理] - #chapter("basic/reference-calculation.typ")[数值计算] - #chapter("basic/reference-math-mode.typ")[数学模式] - #chapter("basic/reference-bibliography.typ")[参考文献] - #chapter("basic/reference-wasm-plugin.typ")[WASM插件] = 进阶教程 — 排版Ⅲ // - #chapter("basic/writing-chinese.typ")[数学排版] - #chapter("basic/writing-chinese.typ")[中文排版] // 6. 脚本Ⅱ // - IO与数据处理 // - 内置类型 // - 数值计算 // - WASM插件 // 7. 排版Ⅱ // - 代码高亮 // - 参考文献 // - 文档大纲 // 8. 科技排版 // - 数学模式 // - 数学公式和定理 // - 物理公式 // - 化学方程式 // 9. 图表 // - 立体几何 // - 统计图 // - 状态机 // - 电路图 // 10. 模板 // 11. 参考Ⅰ // - 基本类型 // - 内置类型 // - 时间 // - 高级颜色 // - 长度单位 // 12. 参考Ⅱ // - 图形 = 进阶教程 — 专题 - #chapter("topics/writing-math.typ")[编写一篇数学文档] // https://github.com/PgBiel/typst-oxifmt/blob/main/oxifmt.typ // - #chapter("topics/format-lib.typ")[制作一个格式化库] // https://github.com/Pablo-Gonzalez-Calderon/showybox-package/blob/main/showy.typ - #chapter("topics/writing-component-lib.typ")[制作一个组件库] - #chapter("topics/writing-plugin-lib.typ")[制作一个外部插件] - #chapter("topics/call-externals.typ")[在Typst内执行Js、Python、Typst等] // https://github.com/frugal-10191/frugal-typst - #chapter("topics/template-book.typ")[制作一个书籍模板] // chicv - #chapter("topics/template-cv.typ")[制作一个CV模板] // official template - #chapter("topics/template-paper.typ")[制作一个IEEE模板] = 进阶教程 — 公式和定理 - #chapter("science/chemical.typ")[化学方程式] - #chapter("science/algorithm.typ")[伪算法] - #chapter("science/theorem.typ")[定理环境] = 进阶教程 — 杂项 - #chapter("misc/font-setting.typ")[字体设置] // - #chapter("misc/font-style.typ")[伪粗体、伪斜体] - #chapter("misc/code-syntax.typ")[自定义代码高亮规则] - #chapter("misc/code-theme.typ")[自定义代码主题] - #chapter("misc/text-processing.typ")[读取外部文件和文本处理] = 进阶教程 — 绘制图表 - #chapter("graph/table.typ")[制表] - #chapter("graph/solid-geometry.typ")[立体几何] - #chapter("graph/digraph.typ")[拓扑图] - #chapter("graph/statistics.typ")[统计图] - #chapter("graph/state-machine.typ")[状态机] - #chapter("graph/electronics.typ")[电路图] = 进阶教程 — 附录Ⅱ - #chapter("intermediate/reference-grammar.typ")[语法示例检索表Ⅱ] - #chapter("template/slides.typ")[演示文稿(PPT)] - #chapter("template/paper.typ")[论文模板] - #chapter("template/book.typ")[书籍模板] = 进阶参考 - #chapter("intermediate/reference-counter-state.typ")[计数器和状态] - #chapter("intermediate/reference-length.typ")[长度单位] - #chapter("intermediate/reference-layout.typ")[布局函数] - #chapter("intermediate/reference-table.typ")[表格] - #chapter("intermediate/reference-outline.typ")[文档大纲] ], ) #build-meta(dest-dir: "../dist") // #get-book-meta() // re-export page template #import "/typ/templates/page.typ": project, heading-reference #let page = project #let ref-page = project.with(kind: "reference-page") #let cross-link = cross-link #let heading-reference = heading-reference
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/columns-00.typ
typst
Other
// Test normal operation and RTL directions. #set page(height: 3.25cm, width: 7.05cm, columns: 2) #set text(lang: "ar", font: ("Noto Sans Arabic", "Linux Libertine")) #set columns(gutter: 30pt) #box(fill: green, height: 8pt, width: 6pt) وتحفيز العديد من التفاعلات الكيميائية. (DNA) من أهم الأحماض النووية التي تُشكِّل إلى جانب كل من البروتينات والليبيدات والسكريات المتعددة #box(fill: eastern, height: 8pt, width: 6pt) الجزيئات الضخمة الأربعة الضرورية للحياة.
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/beckett.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": autor #autor("<NAME>", "1906", "1989 (83 let)", "dramatik, básník", "Trinity College", "absurdismus", "/cj-autori/media/beckett.jpg") Psal eseje, prózy a básně, ovšem proslavil se hlavně svými absurdními dramaty. Celý život se potýkal s alkoholismem a depresemi. Hercům při zkouškách odmítal odpovídat na otázky a zakazoval jim "přehrávat". Také odmítal jakékoliv interpretace jeho díla. Navazoval na existencialistické dílo zejména Alberta Camuse (se kterým se i osobně znal). Velkou část svého života strávil ve Francii a během války byl součástí odboje. Mezi jeho další díla patří: 1. *Hra* -- obsahuje pouze postavy M, Ž1 a Ž2 v milostném trojúhelníku. Mluví jen postava, na kterou svítí reflektor. Nakonec jsou to spíš zpovědi jednotlivých postav. 2. *Šťastné dny* -- o dominantní ženě Winnie a jejím pasivním manželovi Williamovi, který nemluví a odpovídá pouze přibrukováním. Nemají si co říct, ale strach ze samoty je drží pohromadě. *Současníci*\ _<NAME>_ -- Plešatá zpěvačka, 1950\ _Václav Havel#footnote[Jednu svoji hru Beckett Havlovi věnoval.]_ -- Audience, 1975 #pagebreak()
https://github.com/cafeclimber/typst-psu
https://raw.githubusercontent.com/cafeclimber/typst-psu/main/README.md
markdown
# typst-psu A template file for Penn State students to write theses / dissertations in [typst](https://typst.app)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/045%20-%20Kamigawa%3A%20Neon%20Dynasty/008_The%20Epoch%20Engine.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Epoch Engine", set_name: "Kamigawa: Neon Dynasty", story_date: datetime(day: 08, month: 02, year: 2022), author: "<NAME>", doc ) As Katsumasa led her through a maze of passages, Kotori's skin crackled with exhilaration. He'd brought her to his secret laboratories many times before, but not to these innermost sections. Here, corridors shifted into shadows and doors dissolved behind occlusion veils. Kotori only glimpsed fragments: a stretched body covered in glowing enchantments; a large machine with a needle as long as an arm; a somber, hairy face behind cage bars. Kotori followed Katsumasa through yet another veil and into a domed chamber. Soft blue lights shone from the walls. In the middle of the room, there was a raised platform with nothing on it. "You know I trust you the most out of all my protégés, Kotori," Katsumasa said, folding his hands behind his back. "Your determination and self-sacrifice over the past seven years have proved you exceptional, even among the most talented of my inner circle." Kotori glanced up at her teacher. A telepathic implant gleamed bright across his brow. His long ears draped shadows over his sharp jaw and broad shoulders. Although age was beginning to carve lines into his skin, he still looked indomitable. Across Otawara, his name was spoken with hushed reverence: Katsumasa, the Animator, puppeteer of the mechs, engineer of the future. #figure(image("008_The Epoch Engine/01.jpg", width: 100%), caption: [Katsumasa, the Animator | Art by: Heonhwa Choe], supplement: none, numbering: none) "You flatter me, teacher. Hideji is much quicker in the air." "Hideji. He lacks composure, so he'll never be great." Katsumasa's mouth quirked, and then his expression darkened. "In any case, the pilot's speed matters little when the blasted mechs can't keep up." She'd heard this part before. Katsumasa had been trying to improve the technology for years, to shrink the gap between thought and action—but synchronization between mortal and machine had proved difficult to perfect. She'd seen her teacher, in a fit of frustration, burn a three-year experiment to ashes. "This is a classified project, obviously"—he gestured at the veils—"so you are sworn to absolute secrecy. I can't have another department catching wind of this experiment. Now, I know, as Futurists, progress is our driving force. But not all scientists are as principled as you and me, Kotori. They'd claim all credit for themselves and leave us not even a crumb. And if the Imperials came sniffing—well, that'd be even worse. You know those self-righteous pedants always misunderstand what we're trying to achieve." Kotori nodded. Her skin prickled beneath the thick fabric of her suit. Katsumasa had brought her into clandestine projects before, but the strange thrill in her teacher's voice made this time seem~different. Katsumasa's implant flashed. Something shifted—another occlusion veil dissolving. The platform was no longer empty. An enormous mech with a geometric silver torso balanced atop two powerful legs. Massive arms ended in hands like grappling hooks. A pair of shoulder blades gleamed with razor-edged wings. "Beautiful," she breathed. "My prototype for a new generation of mech. I call this prime iteration the Epoch Engine—and I want #emph[you] to be its pilot." With a low hum, the mech extended a small platform to the floor. When Kotori stepped onto it, clamps affixed to her shoes. She was pulled up and up, air whistling around her ears, and deposited in the pilot's seat. The transparent hatch sealed around her soundlessly. Suddenly, Katsumasa was just a tiny figure in her viewport, a pale spot against a dark background. She could squash him under one giant metal foot. Kotori leaned back. A band wrapped around her head, cool and gelatinous against her skin. She murmured her routine checks—emergency release, messaging portals, system enchantments, energy status, safety belts. The configuration was a little different, but the controls were essentially the same. The interface activated. She was no longer bolted into a cramped, dim cockpit. She was suspended in space. Her body was large, much larger than she'd ever known it to be. Her torso was an impenetrable wall. Her arms coiled at her sides, ready to punch through a concrete wall at the subtlest command. Her steel legs hummed with stored energy. All her senses roared. She could hear two scientists in the next building whispering about a leaked research paper. She could feel the vibrations of a rodent scurrying through the walls. She could smell something faintly acrid and chemical like ammonia, oozing from Katsumasa's pores. And her vision—she'd never experienced anything like this. The occlusion veil around the chamber had become a transparent shroud. The walls were tracing paper. She thought, if she tried hard enough, she might even see through her teacher's skin, into his very bones. Kotori lifted her right arm. A ridged fist thrust toward the domed ceiling. She wriggled her toes, and they responded instantly, clanging against the ground. She had embodied the previous mechs, but it had always been clunky, fraught with communication errors and lag time and gut-wringing nausea. How had Katsumasa achieved such perfect synchronization? Kotori sank deeper, relinquishing her original form entirely. There was something flickering beneath—something dark, forceful, compelling. She heard Katsumasa calling from a long way away: "Careful—terminate if something's not right—" An onslaught of emotions slammed into her: wave after wave of elation, curiosity, nervousness, rage, terror, radiating out from a single point like a pulsar. She was tumbling head over heels. #emph[Shorikai.] #figure(image("008_The Epoch Engine/02.jpg", width: 100%), caption: [Shorikai, Genesis Engine | Art by: <NAME>], supplement: none, numbering: none) The voice wasn't hers. She hadn't even been sure it was a voice—more like a finger, pressing a name into her mind, gentle and cold. She disconnected. Came out gasping, in a frigid sweat. Seat. Viewport. Flesh-and-blood body. Katsumasa, gesturing at her from below. She yanked off the band. A few minutes later, she descended from the mech. Only a few beads of sweat betrayed her broken composure. Katsumasa's eyes were gleaming. "Was it not astounding? Seamless control, near-zero reaction times, powerful energy streams—" "Something felt different, teacher—" "By the stony gray hell, sometimes I wish I were a pilot~" "Teacher, what's the new technology in the machine?" "A stroke of my own genius, that's what. Oh, Kotori, I think you've taken to the Epoch Engine like a fish to water. Together, you will be the pinnacle of my life's research. I want you in training every day. Practice as much as you breathe. I expect you to be combat ready by the end of the month, understand?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Daybreak was Kotori's favorite time to visit downtown Otawara. She'd chosen a coffee house in the upper levels of the floating city. From her booth next to the window, she had a breathtaking view of spires and curved buildings rising from a sea of mist, ablaze with rosy light. A cool breeze drifted through the open roof, bringing the scent of rain. Kotori sipped her bitter brew and surreptitiously examined the other patrons. The three middle-aged moonfolk in lavish, gold-foil robes, sharing coffee and biscuits, didn't look too suspicious. But the black-clad figure sitting in the opposite corner could very well be a Veilshaper—professional spies whose job it was to make sure Futurist secrets never fell into the wrong hands. She'd taken the long way from her apartment, walking along the canal in the half-dark to a different transport station from her usual, detouring through the central concourse to lose any trackers in the milling crowds. Ever since she'd started working with the Epoch Engine, she'd noticed more surveillance around her. Someone was keeping tabs. She wondered if it was a rival scientist, or Katsumasa himself. She told herself not to wonder too much. A slender figure slid into the booth. Kotori startled, not recognizing her old friend at first—until Arima pulled back their hood and deactivated their illusory mask. The false features slid aside to reveal vivid black eyes, brown skin, a wry smile. "Sorry to be overdramatic," said Arima. "A few more death threats than usual this week, so I'm taking sensible precautions." "Death threats? By Kyodai's faces, what's going on?" "I've never mentioned them before? Oh, I've been getting #emph[delightful] fan mail since my promotion three years ago. You know the type. Incompetent researchers without enough talent and too much time between their ears, unhappy about someone born outside Otawara rising through Futurist ranks." Arima flipped through the enchanted menu and selected a sweet spiced tea and two platters of fried dumplings. "Anyway, I'm so happy to see you again, little sister. You're looking more furtive than usual. What's going on?" Kotori wrapped her palms around her coffee cup, warmed by Arima's familiarity. The two of them had met in school, when twelve-year-old Arima had been assigned as buddy to six-year-old Kotori. Now, Arima was one of the most talked-about young scientists in Otawara, and Kotori was a rising star amongst the pilots. They didn't meet as often, but they still regarded each other as family. "Katsumasa's brought me into a new project," Kotori said. "His designs are remarkable. I wish I could tell you about it, but it's still under wraps." Arima pressed their lips together. "What's he asking of you?" "Oh, same as before. He needs a good pilot to learn the machine. I've been training long hours. It's complex, more difficult to understand than the old generation of mechs." The waiter arrived with tea and platters of fragrant, crispy parcels of mushroom and chives. "Why are you still working with him, Kotori?" "What do you mean?" Arima snagged a dumpling and waved it in the air. "You know what I mean. You know I've never idolized the excellent Animator the way you do." "I don't #emph[idolize] him. He's guided me since I was thirteen, Arima. He's been generous with his knowledge and time. I owe him a lot. Plus, no matter what you say, he's a talented scientist. There's much I can gain from staying at his side." "But he's so shady, Kotori. Hey, aren't you eating? I got a serving for you, too—dig in. You said you've got a long day ahead of you. I just don't like the way he works, okay? Secrets within secrets, like an origami box of occlusion veils. Some people talk, you know. Some people I work with. They say his research is unnatural." "Imperial folk would shut down all of Otawara if they knew what was really going on in most of our labs—" "These aren't Imperials talking. They're Futurists, like us." Kotori shoved a dumpling into her mouth and chewed angrily, hot juice scalding her tongue. "As far as I'm aware, Katsumasa hasn't done anything unethical. And Arima—you've known me long enough. If anyone asks me to do anything dubious, I'd walk away." "It's not that I don't trust you, little sister." Arima frowned, leaning their elbows on the table. "It's just, well~when someone destroys a tree slowly, whittling away an inch every day, you might not notice anything—until you can see right through the forest." Kotori groaned and covered her face with her hands. "It's too early for Jukai metaphors, my friend." "All right, all right." Arima chuckled. "Just keep your guard up, okay? Don't do anything I wouldn't do, how 'bout that?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Sleep had been more difficult to come by, lately. Sometimes, Kotori would lie in bed for hours, replaying conversations with Katsumasa, running through her practice sessions with the Epoch Engine, and tracking back through her day's movements, just in case she'd missed anything. Arima had left Otawara for a conference in Eiganjo, and Kotori wished she could escape, too, just for a few days. The mists of the floating city seemed to be drifting into her mind, clotting her thoughts. On the worst nights, she'd leave her apartment and stride in the brisk air, looking at the slumbering buildings and the pinpoint stars. The training hall was four blocks away, accessed via a concealed alleyway and an entrance protected by security wards. The mech had begun to respond to her. As she approached across the shadowy arena, it would shed its veil and hum into alertness. When she put her hand on its cold leg and whispered, "Hello, Shorikai," it would open its hatch and lower the platform to fold her into the kernel of its mind. Kotori adjusted her old routines for Shorikai. She murmured her pre-combat checks—emergency release, portals, enchantments, energy, belts—tapping each panel in turn as a marker of their readiness. She twisted her braided bracelet, a childhood gift from her grandfather, three times on her left wrist. She muttered a quick prayer under her breath: guide us, kami of courage. She wasn't superstitious, but the routines made her feel like the plane was in order. And to be the best pilot, everything had to feel right in your bones. #figure(image("008_The Epoch Engine/03.jpg", width: 100%), caption: [Kotori, Pilot Prodigy | Art by: <NAME>], supplement: none, numbering: none) When she wrapped the band around her head and sank into Shorikai's body, the clouds were swept from her mind. The exhaustion. The stretched sensation that came with years of striving. The fear of losing Katsumasa's respect, of coming in second-best. Of failing. There was only the training session, the timeless night, and herself, quietly expanding into the mech's smooth joints and spacious shell. They charged and swung across the training hall. They moved like an arrow, calm and precise, through a still-life of granular detail. Sometimes, the gap between thought and action was so miniscule, Kotori couldn't perceive it at all. Sometimes, the thoughts themselves vanished—she was only movement, only herself-in-Shorikai. The feeling terrified and exhilarated her. What would it be like to give up control entirely—to hand the reins to the machine and recede into the background? Kotori wasn't sure if it was her sharpened perceptions, or a strange new gift of Shorikai's. She'd trained in this hall for years. She knew its length and breadth intimately, all the bumps in the floor. But Shorikai could do something to the dimensions—stretch and bend them, to accommodate for a higher leap, or an arcing skid. Once, they misjudged a turn and braced to slam into a padded post, but the impact never came. Another time, they felt the drizzle of rain, just for a few seconds, as though the ceiling had momentarily ceased to exist. Kotori probed deeper into the mech's layers, wondering if she might hear more than a name. Things came whirling into her—characters streaming across her vision; an impression of her body being dismantled and reassembled; Towashi's neon skyline, dwarfed by the branching glory of Boseiju; a bittersweet feeling of mingled confusion and curiosity. "Shorikai?" she ventured. "Are you there?" But there was no further language—nothing since that single word she'd taken as its name. In these drawn-out spaces, where the world was both chaotic and crystal clear, things from her own past also dissolved into her. Katsumasa, walking with her to an awards ceremony in central Otawara: "Kotori, I suggest you stop associating with that childhood friend of yours, Arima. Trust me—in my long experience, outsiders inevitably cause trouble within the enclaves of the Futurists." Her father, leading her, a shivering child, to the edge of a frigid, ice-topped canal: "You must jump in, Kotori. This is how you learn to swim." And then a vision not at all from her past. Katsumasa, leaning over a table in his laboratory, origami drones spiraling around his body. Her own hand, rising behind him, extending a knife to the side of his neck. Sliding the blade soundlessly into his jugular. A glittering spray of blood, like confetti. Kotori disconnected, plunging back into the cockpit chair, gasping and shaky. She'd given Shorikai too much control. From now on, she'd better keep a tighter grip on the synchronization. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The Veilshaper pilot guided the cloaked aircraft over the shimmering city of Towashi. Kotori-in-Shorikai stood in the bay, enormous feet magnetically locked to the floor. Five more Veilshapers and an Imperial samurai, dwarfed by the mech, sat along the bay wall. The kitsune samurai, with his pointed ears and gold, fan-shaped shoulder guards, stood out among the Veilshapers, who wore dark, layered robes and illusory masks. Kotori gazed down at the urban landscape through Shorikai's eyes. The city seemed to have grown since she last visited. Fluted, tiered towers and elevated train tracks spread and multiplied like a holographic fungus. The aircraft dropped toward the tangled streets at the roots of mighty Boseiju. On Kotori's enhanced vision, their destination lit up: a nondescript round building, almost invisible among the glowing towers and bridges. "Unusual to find Reckoners under the Boseiju tree," Kotori murmured under her breath. She felt a spike of echoed curiosity from Shorikai. In Towashi, the underground gangs of the Reckoners usually kept to the undercity. Several days ago, Katsumasa had deemed her combat ready and assigned her to a routine raid on a Reckoner safehouse. "Nothing you haven't done before," he'd said. "Imperial-led mission—their samurai will brief you. They want to keep things discreet. You'll be the team's power support." The craft landed abruptly on a pitched surface. The others jumped out at once, not waiting for the mech. The Veilshapers drew weapons from their belts—longswords that unfolded from the hilt, thumb-sized diamonds that expanded into paper-thin throwing stars—and activated their cloaking robes. The kitsune samurai seemed unconcerned about attention. Moonlight glinted off his helmet as he strode out. Kotori never let other people's rushing distract her. They needed her more than she needed them. She activated Shorikai's occlusion veil, repeated her checks, twisted her bracelet on her left wrist, and stepped out onto the sloped roof. Boseiju District was difficult for a mech to navigate, tangled with tree roots and hanging bridges. There were a few locals walking in the streets below, oblivious to unfolding events. Kotori chose their steps carefully, watching the data coming into her accessory viewscreens. Their weight placed wrongly could collapse the structure. "This will do," said the Imperial samurai, nodding at the mech. Kotori stamped Shorikai's right foot down, punching a precise hole through the roof. Wooden beams and clay tiles shattered in a storm of dust. She leapt down first, plunged through darkness, landed on stone floor. The others zipped down after her. Kotori glanced around, using Shorikai's enhanced vision to scan the building systematically. Something didn't feel right. No posted watch, no vigilant henchmen, no sentry technology. A humble building—one large central area, two adjoining smaller rooms. One of the smaller rooms held food supplies and a couple of crates of disruptors. The other contained the heat signatures of seven human-sized life forms, clustered close together. "This place isn't Reckoner," muttered one of the Veilshapers, and Kotori realized that she wasn't the only one in the team who'd been misdirected. "You gave us a fake brief?" another snapped at the samurai. "I gave you the brief for the job," the samurai retorted. One of the heat signatures was moving rapidly toward the door— "Seven of them," Kotori interrupted. "Disruptors. From there!" The door slammed open. Disruptor waves reverberated through the air, shutting down Shorikai's automated systems and disabling the Veilshapers' cloaks and masks. A stout, gray-haired woman with wooden armor and a flexible sword barreled through the door. Pebbles, twigs, and strange blue lights wheeled around her body as if caught in a gravitational field. A member of the Order of Jukai, the fringe group of nature worshippers and anti-technologists. They operated from small, decentralized units scattered in hideout cells across Kamigawa—and Kotori's team had kicked a hole right in the middle of one. Six more wooden-armored acolytes burst through the door. They were a motley bunch—two older men with spears, two skinny youths brandishing knives, and two hissing orochi, holding themselves tall on their serpentine tails. None of them were kami-bonded like the older woman. Kotori's head whirled. She seized manual control of Shorikai's functions while the mech performed a rapid reboot. Katsumasa had not sent her to disarm a criminal gang, but to take out some Jukai monks. Sure, she had no love for the Order—it was well known that they despised Saiba Futurists as amoral, and their modus operandi often involved debilitating strikes on Futurist research centers—but this preemptive assassination felt wrong. Systems reactivated. As the Veilshapers and samurai leapt into the fray, Kotori sent an urgent message up to Otawara: #emph[Katsumasa—Jukai not Reckoner? Please clarify.] She knew her teacher's implant would shoot the message straight into his brain. She waited ten seconds, then twenty. No reply. One of the youths came toward her, clutching a disruptor in his fist. Kotori-Shorikai swiped it away, cutting off the youth's hand in the process. The kid dropped to his knees, howling. Kotori-Shorikai tapped his head with a finger to knock him unconscious. An orochi sneaked up from behind, attempting to throw a grappling hook into the mech's leg. Kotori-Shorikai sidestepped and swung their other leg in a precise roundhouse kick. The orochi hit the wall, and then the floor, and didn't move. Kotori tried again. #emph[Teacher! I'm confused. Please reply.] All of the Jukai were down except for the stout woman with the floating symbols of a bonded kami. The Imperial samurai had taken a spear blade in his side but did not seem critically injured. The Veilshapers were unhurt. The last Jukai gazed up at the mech, narrowed eyes flashing with disgust and rage. "You should not exist," the woman hissed. "Your creator has twisted nature into monstrosity." The Jukai channeled a blast of icy water at the mech. Kotori shielded and returned a flurry of darts. To her surprise, the woman deflected most of them with another flick of water; the few that she missed landed in her wooden armor. Kotori had heard that kami-bonded Jukai carried a focus on their person to channel the powers of their spirit partners. She noticed a smooth gray stone on a string around the woman's neck. Just as a blast of sharpened pebbles flew at her, Kotori-Shorikai sidestepped and swung for the necklace. Steel fingers sliced into the Jukai's neck as they closed around the stone. The woman crumpled to the floor, gurgling blood. A serpentine spirit detached from the Jukai's body. Pebbles and twigs and skeins of water coiled around it in a whirlwind. A river or creek kami, perhaps. Its long shape curled over the fallen woman. Kotori-Shorikai crushed the stone in one hand. The kami, however, was unaffected. Perhaps the focus was just a link between kami and mortal—unnecessary now that the mortal was gone. One of the Veilshapers ambled forward, unfolding his longsword. The kami was still hunched over the woman's body. It had a spine of small stones, a mane of glittering droplets, and a pale blue aura. It left wet marks on the dusty stone floor. Though it was a spirit, it was material enough. A sudden fear churned through Kotori. Was it coming from her, from Shorikai, or somewhere else? The Veilshaper hovered over the river kami and drew back his weapon to strike. The kami twitched aside, but not fast enough. The blade tore through the kami's tail, releasing a spray of mist. The Veilshaper drew back again. The terror grew sharper, burning down Kotori's throat and into her gut. Shorikai lifted an arm and fired. The Veilshaper slumped to the floor, a steel dart protruding from a weak spot in his armor, just under his chin. Kotori could hear the other Veilshapers shouting, but their voices were coming from a long way away. She hadn't commanded Shorikai to fire. She hadn't. She tried to lower the arm, but the mech wasn't responding. Everything seemed suddenly distilled, sharp as glass and in slow motion. The wounded kami, writhing over the dead Jukai. The eyes of the Veilshapers, boring into her. Katsumasa's lies. Katsumasa's silence. And Shorikai—something about Shorikai that she'd suspected for weeks, but to admit the possibility to herself had been far too horrifying. There was a kami inside the mech. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "#emph[Kotori] ." The voice was unfamiliar, but the way the mouth shaped her name made her jump. One of the Veilshapers stepped into Kotori-Shorikai's field of view. "Teacher?" The Veilshaper inclined her head. Her expression was disconcertingly impassive, her eyes blank. The implant in her brow flickered. Katsumasa must be controlling her remotely. #figure(image("008_The Epoch Engine/04.jpg", width: 100%), caption: [Universal Surveillance | Art by: <NAME>], supplement: none, numbering: none) "Kotori, I believe I need not remind you. It is, after all, repeatedly drilled into all pilots during their earliest years of training. If a mech's obedience systems are malfunctioning, it is a pilot's duty to override the synchronization and seize control." Kotori closed her eyes briefly. The synchronization was already unstable. Spikes of adrenaline and cortisol were affecting the connection, snapping her out of Shorikai's body and back into her own sore, soft, tiny form—just for brief blips, before hurling her back into the mech. Bile rose into her throat. She fought the urge to retch. "Kotori. You've always been rational. Don't compromise the mission. I couldn't #emph[bear] to see the consequences on your career if you do. I'll explain everything afterwards, all right? You know I wouldn't make you do anything wrong." Kotori opened her eyes. She could see the possessed Veilshaper with her real eyes and with Shorikai's eyes, twice over, layered on top of each other like disjointed ghosts. She could override Shorikai, but who knew what damage that might do to the kami trapped within? But the alternative was to relinquish control to someone else. Unexpectedly, her fear receded into a quiet calm. The synchronization was stable again. She reached into Shorikai, into the shadowy spaces that had become as familiar to her over the past few weeks as her own body, into the mech's core— And she withdrew, letting go. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) When Shorikai took control, he revealed his true form to her, just for a second. She saw a seeping, dark aura. She saw a waterfall of tangled black hair; a body built of many wordless and uneasy things; a multitude of hollowed, eyeless faces. Shorikai's form was pinioned by metal spikes. Glowing threads bound kami to machine in a thousand different ways, more complicated than an intricate embroidery. These were knots only Katsumasa could unpick. The sight filled her with horror and sadness, but also with understanding. "Kotori!" screamed Katsumasa, but the sound was soft, almost pitiful, fading into inconsequence. The scream trailed away as Shorikai slammed the Veilshaper into the wall. The implant went dead. Kotori could hardly understand it. With control surrendered to the kami, the mech was far more powerful than it had been under her guidance. Shorikai's strength was doubled. The building no longer felt substantial, or even relevant. After all, if they really needed, Shorikai could warp the walls and bend the floors. The remaining Veilshapers rushed at the mech, hollering about betrayal. One of them was signaling for backup. Shorikai disposed of her first. It took only a few more seconds to silence the others, including the injured samurai, who begged half-heartedly for mercy. Spots of light burned in Kotori's vision. She felt disconnected from her body, and then grotesquely compressed into the smallest part—her prickling fingertips, her congealing gut. When her senses gradually returned, the scene flooded her mouth with bitterness. The round room had been utterly transformed. Splintered wood, broken tiles, used throwing stars, misplaced limbs, and streaks of blood were scattered across the floor. Mangled and fallen, the members of the Order of Jukai and of her team were difficult to tell apart. The blue kami still curled over the body of its former partner. The walls were strangely bent and twisted by Shorikai's abilities—the full extent of which even Katsumasa probably didn't understand. In one spot, the wall had warped so much that it flickered and buzzed with unearthly energy. Specks of dust and blood wafted toward the distortion. The river kami finally unfurled and crawled toward the flickering zone in the wall. It paused and gazed back at the mech. Kotori wondered if some wordless communication was passing between it and Shorikai. Then, the river kami floated into the distorted wall and disappeared. Kotori guessed that the distortion was a warped merge: an unstable melding between utsushiyo, the material realm, and kakuriyo, the spirit realm. If left uncontained, the instability could spread and corrupt the integrity of both realms. "Shorikai," Kotori breathed. "What have you done?" To her astonishment, she received a reply. #emph[Not my doing, but perhaps an aftereffect.] The kami's voice was heavy and sinuous. She remembered the things she'd seen: the shadowy aura, the gaping faces, the disquieting body. Only a moment ago, she'd felt an unspeakable terror. But now, that fear was subdued, dampened by sadness. Shorikai had settled back into the machine's framework. The synchronization was once more balanced, responsive. Flawless. Katsumasa was still up above in Otawara. He would find out about the mission's outcome one way or another. If she surrendered now, perhaps the consequences to her career would not be so dire. Perhaps she could salvage her reputation with some excuse about an erratic connection. But if she went back, her mech would surely be dismantled, and Shorikai would either be destroyed or imprisoned within another experiment. For some reason, Arima's face floated into her mind. Kotori felt awash with confusion and guilt. She had killed so many. She had almost watched a kami die. "What now, Shorikai?" Something powerful churned within the mech, like a tide crashing over rocks. #emph[Take our own path.] Kotori looked around the collapsing room. A cool breeze was drifting in through the torn paper windows. With their enhanced vision, she could see through the walls to the surrounding buildings, glowing like lanterns caught up in Boseiju's giant gnarled branches. #figure(image("008_The Epoch Engine/05.jpg", width: 100%), caption: [Jungle Hollow | Art by: <NAME>], supplement: none, numbering: none) She knew that fleeing wasn't a permanent solution. They could run, but at the end of the running, there would be a fight. A reckoning, with consequences. But at least they'd have time to think about everything that had happened, hunt for more information, and decide what to do next. The union of their wills—mortal and kami—felt as effortless as water flowing downstream. "I agree," she replied. Clouds of blood and dust whirled around Kotori-Shorikai as they stepped past the warped merge. The wooden door crumbled at their touch. Outside, the first pale streaks of dawn were edging through Boseiju's massive canopy, but perpetual shadows lay beneath the great tree-roots. Activating their occlusion veil, Kotori-Shorikai left the Jukai hideout and walked into the darkness.
https://github.com/EliasRothfuss/vorlage_typst_doku-master
https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/pages/erklaerung.typ
typst
#import "../config.typ" #heading(level: 1, numbering: none)[Erklärung] \ gemäß Ziffer 1.1.14 der Anlage 1 zu §§ 3, 4 und 5 der Studien- und Prüfungsordnung für die Bachelorstudiengänge im Studienbereich Technik der Dualen Hochschule Baden-Württemberg vom 29.09.2017 in der Fassung vom 24.07.2023.\ \ Ich versichere hiermit, dass ich meine #config.data.arbeit mit dem Thema: \ \ #config.data.title\ \ selbstständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe. Ich versichere zudem, dass die eingereichte elektronische Fassung mit der gedruckten Fassung übereinstimmt. \ \ \ \ #pad(top: 5cm, text[ #config.data.ort, den #datetime.today().display("[day].[month].[year]") ]) #pad(top: 3cm, text[ #config.data.author ])
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/AI/Reinforce%20Learning/基本概念.typ
typst
--- order: 1 --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "", lang: "zh", ) - Reinforcement Learning - 其他人的博客 or 笔记 + #link("https://www.cnblogs.com/pinard/category/1254674.html")[刘建平Pinard的强化学习随笔] #note(caption: "注:")[ 我觉得 rl 的本质是把无梯度的 feedback 转换为可训练的梯度。具体使用什么样的框架更好,并不影响 rl 理论的本质。这也就是为什么感觉现在做 rl 理论的都在叫苦,但 rl 应用却越来越多(比如大模型 ChatGPT-o1 等) ] = 基本概念 == 动态规划 - 动态规划将复杂的多阶段决策问题分解为一系列简单的、离散的单阶段决策问题,采用顺序求解方法,通过求解一系列小问题达到求解整个问题的目的。 - 适合于用动态规划的方法求解的问题是具备无后效性(马尔科夫性)的决策过程。 == MDP建模 - 马尔可夫决策过程(Markov decision process,MDP) == 策略评估与优化 - 强化学习由策略评估和策略改进组成 - 策略评估的目标是知道什么决策是好的,即估计 $V^pi (s_t)$ - 策略提升的目标是根据值函数选择好的行动 - 基于价值函数 $V(s)$,$pi(s)=arg max_(a in A)sum_(s' in S)P(s'|s,a)V(s')$ - 基于动作价值函数 $Q(s,a)$,$pi(s)=arg max_(a in A)Q(s,a)$ == 探索与利用 - 为什么?环境信息不完全;每一种决策的真实价值无法获取,只能获取其统计价值。 - 更具体地,有些行为尚未被探索过,其价值未知;已被探索过的行为可能因为偶然概率原因被高估或者低估; === $epsilon-"greedy"$ 方法 - 大多数时间($1 - epsilon$)采用当前统计行为价值中最优的行为,其余时间随机选择一个行为($epsilon$) - 每个行为的价值为历史决策经验中该行为获得奖励的均值 #mitex(`\hat{Q}_{t}(a)=\frac{1}{N_{t}(a)}\sum_{\tau=1}^{t}r_{\tau}\,\delta[a_{\tau}=a]`)其中 $delta$ 为二元指示函数,$N_t (a)$ 为 $t$ 步中行为 $a$ 被选择的次数,即 $display(N_t (a) = sum_(tau=1)^t delta[a_tau=a])$ - $epsilon$ 可以被设定为超参,也可以随训练的进行逐步衰减 - 优点:简单,易于理解 - 缺点:虽然每个行为都有可能是最优行为,但是其成为最优的可能性是不同的,同理选择具备不同潜力的行为的策略也可以不完全随机 === UCB 方法 - 通过奖励值的上置信界(Upper Confidence Bound)来衡量每一个动作附加其“潜力”后的价值。 - 行为的真实价值低于附加潜力后的价值,即:$Q(a) =< hat(Q)_t (a) + hat(U)_t (a)$ - 上界函数 $U_t (a)$ 跟 $N_t (a)$ 相关,因为大的行为访问次数使得对应的行为的价值更准确,因此得到较小的置信上界。 - 首先介绍 Hoeffding 不等式:对于独立同分布的随机变量 $X_1, X_2, ..., X_n$,,$t$ 次采样得到的样本均值为 $macron(X)_t$,那么对于给定的 $u$:$ P(E(X) > macron(X)+u) <= e^(-2 t u^2) $ - 替换得到我们的结论 #mitex(`\mathbb{P}[Q(a)>{\hat{Q}}_{t}(a)+U_{t}(a)]\leq e^{-2t U_{t}(a)^{2}}`) - 令上式右端为 $p$,反解得到 $U_t (a) = sqrt((-ln p)/(2 N_t (a)))$ - 一种启发方法是及时降低 $p$ 的阈值,因此常设其为 $t$ 的负数次方,得到 $U_t (a) = sqrt((c ln t)/(N_t (a)))$ - 当 $c=2$($c$越大,越趋向探索),UCB1 算法选择这样的动作 #mitex(`a_{t}^{U C B1}=\arg\operatorname*{max}_{a\in A}\left(Q(a)+{\sqrt{{\frac{2\log t}{N_{t}(a)}}}}\right)`) === 熵正则 - 我们希望策略网络的输出的概率不要集中在一个动作上,至少要给其他的动作一些非零的概率,让这些动作能被探索到。可以用熵 (Entropy) 来衡量概率分布的不确定性
https://github.com/arthurcadore/typst-intelbras
https://raw.githubusercontent.com/arthurcadore/typst-intelbras/main/templates/report-confidential-en.typ
typst
MIT License
#let report( title: "Typst Support Model - Intelbras", subtitle: "ITB Business Networks - Special Projects", authors: "<NAME>", date: none, doc, ) = { set page(background: rotate(24deg, text(38pt, fill: rgb("FFCBC4"))[ *CONFIDENTIAL DOCUMENT* \ *INTELBRAS - REMP. RD* ] )) // Defining the document structure set document(title: title, author: authors) set block(spacing: 1.5em) // Defining the document highlighting style set highlight( fill: rgb("#c1c7c3"), stroke: rgb("#6b6a6a"), extent: 2pt, radius: 0.2em, ) // Defining the document style set page( numbering: "1", paper: "a4", margin: (top: 3cm, bottom: 2cm, left: 3cm, right: 2cm), footer: "Business Networks - Special Projects", ) // Defining the text style and size set text(size: 12pt, font: "Times New Roman") // Defining the paragraph style set par( first-line-indent: 1.5cm, justify: true, leading: 0.65em, linebreaks: "optimized", ) // Defining the heading style set heading(numbering: "1.") // Defining the list style set math.equation(numbering: "(1)") // Defining the language style set text(lang: "pt") // Defining the main image style align(center)[ #image("../pictures/intelbras-logo.svg", width: 30em) ] // Defining the title style align(horizon + center)[ #text(20pt, title, weight: "bold") #v(1em) #text(15pt, subtitle, weight: "regular") #v(15em) ] // Defining the authors and date style align(bottom + left)[ #text(list(authors, marker: "", body-indent: 0pt), weight: "bold") #text(date) ] // Defining the abstract style pagebreak() // Defining the table of contents style show outline.entry.where(level: 1): it => { strong(it) } outline(title: [Summary #v(1.5em)], indent: 1.5em) pagebreak() doc }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/006%20-%20Magic%202014/006_Zurbit's%20Day.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Zurbit's Day", set_name: "Magic 2014", story_date: datetime(day: 31, month: 07, year: 2013), author: "<NAME>", doc ) #emph["I need more money."] Relno looked nervously at the floor and fidgeted with his staff. It was all he could do to keep from melting into a puddle of insecurity and self-doubt. He needed her backing; he hated having to ask, because he could see the way she looked at him. "Withering" was a good word for the look she gave him—a withering look. #figure(image("006_Zurbit's Day/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) But she needed #emph[him] . #emph[He] was the one with the brains. #emph[He] was the one whose genius made her family wealthy and powerful. Why, without him they would be simple miscreants, thugs... troglodytes. Relno straightened himself up. No more fidgeting. "I need more money." There wasn't a shred of "budge" in his tone. Emina sighed as only a noble raised to manipulate and subjugate her lessers could sigh—subtle, disappointed, thick with disgust. Relno could feel it wash over him like a stench from a failed experiment. His nose instinctively wrinkled but he didn't waver. It was how these fancy-clothed people worked and he was determined to play their game and win. There was a long pause, then Emina rolled her eyes. "How much, Relno?" Exasperation forced Emina to hold the "o," which betrayed her usually unreadable demeanor. Relno smiled inwardly. He'd cracked her iron core. "Five thousand." "Done. Get out." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Relno sat on the deck of the merchant ship as the wind and the sea filled his senses. It was a beautiful day. The canvas of the sails arced above his head and shaded him from the high sun that peeked out from behind them every now and then, as the ship pitched gently back and forth to the rhythm of the waves. He couldn't wait to get back to his workshop, his mind racing with ideas. Finally, he had the funds he needed to finish his greatest work—it would be glorious. He scribbled notes as fast as he could. It would cost a fortune to ship the pieces from Martyne to his island lab, but he had all the money he needed now. He would send a bird to arrange the shipment as soon as he touched shore. Next would be to create the elementals that he would need to put the pieces in place. That would take time and personal energy. He felt like he could create a thousand such elementals with the overwhelming surge of excitement that now possessed him. He looked forward to climbing the steps of his tower and getting to work. He began to write a list of tasks for his faithful homunculus, Zurbit. There was much for him to do. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Zurbit couldn't believe his eye. The bookshelves were bare, papers were everywhere, flasks and beakers lay broken, puddles of seawater pooled along the floor. It was an utter disaster. #figure(image("006_Zurbit's Day/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) Zurbit gasped. #emph[Merfolk] . How did they get in? He always locked the doors and barred the— A window was shattered, its frame bent from a pry bar. Zurbit dashed to the opening. How in the five sacred blazes did they get up the side of the tower? It was hundreds of feet to the rocks below. He scrabbled up to the sill where Relno's beloved orange-striped cat, Pip, was licking the salt and fishy flavor left by the intruders. Zurbit looked outside and saw the sheer drop. No rope, no ladder, no carved-out handholds. How had they done it? Was it the levitation potion? Zurbit was sure he had locked it up last month. He cursed under his breath, dropped back down to the floor, and wrung his little hands as he surveyed the utter pillage of his master's tower. They had made off with the lot. Relno was going to kill him when he returned. Zurbit had to get everything back. And fast. Zurbit knew the merfolk who did this. There was a small group of them that lived in a small reef offshore, stealing from the land-dwellers along the shores of the Kapsho. As far as Zurbit was concerned, these finny folk were robbers and cutthroats—not to be trifled with. He paced around the lab for a while while Pip idly watched motes of dust in a ray of sunshine. Then, it hit him. He grabbed a flask; a piece of parchment; pen and ink; and a thin vial of sparkling, green fluid from within a small, wooden box. He put everything in a pack, which he slung over his shoulder, then he scooped up Pip and headed off down the long stone staircase for the docks far below the tower. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Zurbit set out onto the waves in a small rowboat. Another smaller boat was towed behind them. Pip looked over the side, a paw at the ready for the scintillating fish that darted and dashed below the surface. Zurbit rowed with a purpose, hoping they wouldn't get spotted by a seacoast drake or something worse under the waves. #figure(image("006_Zurbit's Day/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) They reached the reef. Zurbit tossed the small anchor overboard and watched as the hooks caught on the coral below. He muttered to himself as he took out the pen, ink, and parchment, and hastily scrawled a message. #emph[THEIVING MERFOLK,] #emph[GIVE US BACK OUR STUFF OR YOU'LL BE SORRY.] #emph[ZURBIT] He stuffed the message into a flask and made sure that it could be read. Then he stoppered it, tied a bit of fishing line around it, attached a weight, and after a quick look to check for position, he tossed it overboard. Now it was time to wait and see. #figure(image("006_Zurbit's Day/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) A merfolk surfaced, looked at Zurbit, and growled something like"Nnn-ahrrr." The merfolk's eyes were cold and smug as it submerged under the waves with a final hiss of contempt. Pip watched the silvery scales as they flickered below the surface. He licked his whiskers. "Right. That's it then you thieving fish-faces." Zurbit pulled on the rope that attached the two small boats and hauled the empty one alongside. Then he unstoppered the vial of sparkling green fluid and sctratched Pip between the ears. "Okay, my friend. It's time for your dreams to become a reality." Zurbit touched a few drops to Pip's nose, and the cat promptly licked them up. "That's a good boy," Zurbit said as he poured more and more of the green vial onto Pip's tongue. Pip looked at Zurbit, hoping for more of the tasty treat, but Zurbit just picked him up and set him in the smaller boat, untethered the rope that connected them, and pushed Pip out over the reef. "You'll know what to do, boy," Zurbit said as Pip drifted away. Then he began to row with all his might, as Pip grew to the size of a small whale. "You'll know what to do!" Zurbit's laughter echoed across the turbulent waves. #figure(image("006_Zurbit's Day/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Relno opened the door to his tower. "Zurbit! Great news! We have work to do!" He took off his cloak and rushed over to the table, where he began to pull the books off of the shelves that smelled... faintly... of... seawater? Relno looked about. Something was amiss. Pip sat on an open book and looked at Relno nonchalantly as he licked his fur. Scrolls were laid out on tables; books lay open along the floor. Pages and papers rippled as a strong breeze left the room. "What in the Five Azure Flames has happened here?" Relno stood. "Nothing, Master." Zurbit said matter-of-factly. He then smiled with satisfaction. "Just letting in a little sea air." #figure(image("006_Zurbit's Day/06.jpg", width: 100%), caption: [], supplement: none, numbering: none)
https://github.com/1STEP621/typst-anshere
https://raw.githubusercontent.com/1STEP621/typst-anshere/main/src/anshere.typ
typst
#let (q, q-break, q-blank, anshere) = { let q-break = "q-break" let q( content: h(1fr), label: auto, numbering: auto, numbering-width: auto, hide-numbering: false, counter-reset: none, counter-skip: none, children: none, ) = ( content: content, label: label, numbering: numbering, numbering-width: numbering-width, hide-numbering: hide-numbering, counter-reset: counter-reset, counter-skip: counter-skip, children: children, ) let q-blank = "q-blank" let counter = counter("anshere-counter") let questions-to-grid(questions, numberings, depth: 2) = { questions.map(question => if question == q-blank { grid.cell([#h(1fr)]) } else { grid( columns: ( if question.label == auto { if question.numbering-width == auto { if question.hide-numbering { 0pt } else { 27pt } } else { question.numbering-width } } else { if question.numbering-width == auto { auto } else { question.numbering-width } }, 1fr, ), if (not question.hide-numbering) { grid.cell( inset: 10pt, stroke: 1pt, align: horizon + center, [ #counter.step(level: depth) #context { if question.counter-reset != none { let value = { let x = counter.get() x.at(depth - 1) = question.counter-reset x } counter.update(value) } } #context { if question.counter-skip != none { let value = { let x = counter.get() x.at(depth - 1) = x.at(depth - 1) + question.counter-skip x } counter.update(value) } } #let fmt = if question.numbering == auto { numberings.at(depth - 1) } else { question.numbering } #context if question.label == auto { numbering(fmt, counter.get().last()) } else { [#question.label#sym.zws] // 行の高さがずれるのを防ぐ } ], ) } else { grid.cell( inset: 10pt, [#sym.zws], ) }, if question.children == none { grid.cell( stroke: 1pt, inset: 10pt, align: horizon, question.content, ) } else { grid(..questions-to-grid(question.children, numberings, depth: depth + 1)) }, ) }) } let anshere(questions, numberings: ("1", "1", "(1)", "1")) = { grid( columns: 2, gutter: 10pt, grid.cell( rect( stroke: 1pt, inset: 10pt, [ #counter.step(level: 1) #context numbering(numberings.at(0), counter.get().last()) ], ), ), grid( ..questions.split(q-break).filter(e => e.len() > 0).map(questions => grid( columns: questions.len(), ..questions-to-grid(questions, numberings) )) ), ) } (q, q-break, q-blank, anshere) }
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/06-fourier-series/!sec.typ
typst
#import "../../utils/core.typ": * = <NAME> #include "01-lebesgue-spaces.typ" #include "02-hilbert-spaces.typ" #include "03-trigonometrical-fourier-series.typ" #include "04-adding-fouriers.typ" #include "05-fourier-misc.typ"
https://github.com/MDLC01/board-n-pieces
https://raw.githubusercontent.com/MDLC01/board-n-pieces/main/src/internals.typ
typst
MIT License
#let functions = plugin("plugin.wasm") #let replay-game(starting-position, turns) = { let game = functions.replay_game( bytes(starting-position.fen), turns.map(bytes).join(bytes((0, ))) ) array(game).split(0).map(position => ( type: "board-n-pieces:fen", fen: str(bytes(position)) )) } #let game-from-pgn(pgn) = { let game = functions.game_from_pgn( bytes(pgn), ) array(game).split(0).map(position => ( type: "board-n-pieces:fen", fen: str(bytes(position)) )) } /// Converts a `board-n-pieces:fen-position` to a `board-n-pieces:position`. /// For positions, this is the identity function. #let resolve-position(position) = { let message = "expected a position (hint: you can construct a position with the `position` function)" assert.eq(type(position), dictionary, message: message) if position.type == "board-n-pieces:position" { return position } if position.type == "board-n-pieces:fen" { // A `fen` object contains a `fen` entry, which is a full fen string. let parts = position.fen.split(" ") return ( type: "board-n-pieces:position", fen: position.fen, board: parts.at(0) .split("/") .rev() .map(fen-rank => { () for s in fen-rank { if "0".to-unicode() <= s.to-unicode() and s.to-unicode() <= "9".to-unicode() { (none, ) * int(s) } else { (s, ) } } }), active: parts.at(1), castling-availabilities: ( white-king-side: "K" in parts.at(2), white-queen-side: "Q" in parts.at(2), black-king-side: "k" in parts.at(2), black-queen-side: "q" in parts.at(2), ), en-passant-target-square: if parts.at(3) != "-" { parts.at(3) }, halfmove: int(parts.at(4)), fullmove: int(parts.at(5)), ) } panic(message) } /// Returns the index of a file. #let file-index(file) = file.to-unicode() - "a".to-unicode() /// Returns the index of a rank. #let rank-index(r) = int(r) - 1 /// Returns the coordinate of a square given a square name. #let square-coordinates(s) = { let (f, r) = s.clusters() (file-index(f), rank-index(r)) } #let stroke-sides(arg) = { let sides = rect(stroke: arg).stroke if type(sides) != dictionary { sides = ( left: sides, top: sides, right: sides, bottom: sides, ) } ( left: none, top: none, right: none, bottom: none, ..sides, ) }
https://github.com/peteole/relai_poster_template
https://raw.githubusercontent.com/peteole/relai_poster_template/main/poster.typ
typst
#import "relai_poster_template.typ": poster #show: doc => poster( doc, text("Example title", size: 60pt, weight: "bold"), flipped: false, // change for landscape n_columns: 2, authors: ( ("name": "<NAME>", "affiliation": "TUM", "email": "<EMAIL>"), ("name": "<NAME>", "affiliation": "LMU", "email": "<EMAIL>"), ), references: ( ("url": "https://zuseschoolrelai.de", "label": "zuseschoolrelai.de"), //("url": "https://arxiv.org/abs/...", "label": "ArXiv"), ), font_size: 30pt, ) = Example section #lorem(200) = Example section #lorem(100)
https://github.com/warthog-network/whitepaper
https://raw.githubusercontent.com/warthog-network/whitepaper/master/main.typ
typst
#import "template.typ": * #import "@preview/codelst:2.0.1": sourcecode #set outline(title: "Table of contents", indent: 1em) #let emission = csv("files/emission_scheme.csv") #show: bubble.with( title: "Warthog Network", subtitle: "Rethinking the Blockchain", alt: "Whitepaper", affiliation: "University", date: datetime.today().display(), logo: image("./assets/logo/Circle/Warthog_2024_Circle Yellow.svg"), color-words: ("highlight", "important") ) #outline() #pagebreak() = Introduction == History Originally, Warthog was written as a fun and experimental side project of its original developers Pumbaa, Timon and Rafiki has who work in blockchain industry. Initially there was no specific purpose or use case planned. Instead, the goal was firstly to revive the days when crypto was a fun and an interesting experiment, and secondly to try out new things and learn how blockchain technology works in detail. However soon after its inception a vibrant community started to form around the young project and with it new contributors joined the project bringing a fresh wind of development support and innovative ideas. The project started to grow up and is still growing today. == What is Warthog Network? Warthog is the first *Proof-of-Balanced-Work* (PoBW) Layer 1 network trying to push the boundary of what is technically possible by implementing multiple *highly innovative* and unique features including - Janushash (first anti-farm balanced CPU/GPU combo PoBW algo) - Chain descriptor sync (new efficient and resource-friendly sync) - SQLite blockstore (easy cross-platform copy of chain file) - Full browser nodes (start a full node by opening a website) - WasmFS support (browser nodes can persist whole chain) - WebRTC support (browser nodes can communicate P2P) Unlike may other cryptocurrency projects we are *not a fork* of any other project. Instead, the *code is freshly written* in the #box[C++] programming language. New software always bears the risk of unforeseen bugs but at the same time the real effort put into this project sets it apart from most competitors. As a community project we are trying to be as transparent and fair as possible and avoid the fishy and questionable practice currently seen in most other new projects: we had a *fair launch* with *no team allocation or premine*, therefore donations for developments are always welcome! Warthog is neither a company nor an organization. It is rather a loose team of passionate crypto enthusiasts who are contributing to the project in their free time. Bear in mind that team members may decide to leave the project at any time, in fact Timon, one of the original developers has already left the team. Therefore we are constantly trying to expand the stronger community behind Warthog. The community is welcome to take actively part in the evolution of Warthog. The logo, the explorer and other milestones were contributed by volunteers. If you think you can help, please let us know! = Janushash == Proof of Balanced Work === Introduction Proof of Balancd Work (PoBW) was first formulated in 2023 by Warthog community developer "CoinFuMasterShifu" #cite(<pobw>) and was specifically implemented for Warthog for the first time. Compared to classical Proof of Work, the class of Proof of Balanced Work (PoBW) algorithms is very different. Instead of only employing one hash function they combine multiple hash functions in a multiplicative way. The mathematical theory of considering a multiplicative combination of hashes, i.e. hash products, was established in this paper for Warthog and currently there is no other crypto project using Proof of Balanced Work for consensus. Combining different hash functions multiplicatively has the advantage that + different hash functions can be mined in parallel devices at different hashrates using a multi-stage filtering approach and + efficient mining requires mining of all involved algorithms for each block in contrast to previous failed attempts to construct multi-algorithm block chains by using individual difficulties for each algorithm (Myriad Coin, DigiByte, Verge). For example Verge was hacked by focusing only on one algorithm. == Janushash Essentially, Proof of Balanced Work algorithms are simply the multiplicative combinations of existing hash functions. Warthog's Janushash algorithm combines two hash functions: + triple Sha256 (Sha256t) and + Verushash v2.2 === Balancing Energy-efficient mining of Proof of Balanced Work algorithms requires finding a good balance between Sha256t and Verushash hashrates. The best combination depends on hardware and energy cost but it is clear that mining without a GPU or with a weak CPU won't be competitive. The balancing requirement coined the name "Proof of Balanced Work". == Hashrate Decentralization === Fighting Farms Interestingly, the Janushash algorithm keeps away both, GPU farms and CPU farms: GPU farms usually save on the CPU side, because CPU performance is not relevant for mining GPU algorithms. Therefore such farms perform poorly on Janushash. GPU farm owners would need to make significant investments in efficient and performant motherboards and CPUs to improve their GPU/CPU balance for efficiently mining Janushash. CPU farms perform very poorly on Janushash because of the lack of accelerated triple Sha256 hash evaluation. The same applies to most botnets. This means large mining farms and botnets play a much smaller role in Warthog than they do in other proof of work cryptocurrencies, which increases decentralization of hashrate. === Satoshi's vision Originally, <NAME> had an idealized hope for mining being a democratized way of establishing consensus. This can be seen for example in his famous whitepaper #cite(<nakamoto2009bitcoin>) where it says: #blockquote[Proof-of-work is essentially one-CPU-one-vote.] From this article #cite(<lazlogpu>) about Laszlo Hanyecz's correspondence with Satoshi we can observe that Satoshi was not amazed about the fact that GPU mining would disrupt this idealized hope: #blockquote[One of the first emails Satoshi had sent the man was in response to him describing his proposed GPU miner. Mainly, Satoshi was none-too-pleased, asking Hanyecz to slow down with this.] #blockquote[Satoshi explained that, at the time, one of the biggest attractions possible is the fact that anyone can download Bitcoin and start mining with their laptops. Without that, it wouldn't have gained as much traction.] He knew that with the advent of GPU mining, many CPU miners would be kicked out of the network, which would be against his vision of fair, equal and decentralized mining. Therefore he hoped to delay this as long as possible. @bitcointalk shows one of his posts on Bitcointalk. #figure( image("./assets/satoshi_bitcointalk.png", width: 80%), caption: [Satishi's hope to postpone GPU arms race.], )<bitcointalk> We all know that his hopes have not been fulfilled, today Bitcoin is mined on specialized expensive hardware and only those with access to this hardware can participate in mining. After all, Satoshi was not able to solve the issue of centralized mining. We are confident that the use of Proof of Balanced Work solves this issue to a large extent when the combined hash functions are carefully selected. In Janushash, the two hash functions Sha256t and Verushash where chosen to require a GPU and a CPU connected with sufficiently large bandwidth. This was done to target typical gaming PCs. As described above, with this choice farms cannot easily join the network without being forced to make additional investments just for mining Warthog. This democratizes mining and brings Warthog closer to Satoshi's vision. == ASIC Resistance As technology advances, so does specialized mining hardware, especially when potential profits are high. There is nothing that can be done against this fact. However there are three reasons why Warthog is more robust against ASIC threats than other PoW cryptocurrencies: === Inherited ASIC Resistance When it comes to ASIC resistance, Proof of Balanced Work is stronger than its strongest ingredient. To accelerate mining, an ASIC would need to be able accelerate computation of all combined hash functions to avoid a bottleneck effect. In addition an ASIC would need enough bandwidth between the hardware sections computing different hash functions as well as calibration and tuning to optimize their intercommunication and coordination. In particular, Janushash inherits ASIC-resistance from Verushash v2.2 which is currently mined on CPUs and GPUs, but not on FPGAs/ASICs, and the need to also require SHA256t hashrate makes Janushash even more ASIC-resistant. === Detection of suspicious hashrate In traditional Proof of Work networks we only have one marker to analyze network hashrate, namely the network difficulty. It can be used to estimate the total hashrate of all miners in the network. However we cannot tell whether some actors use specialized hardware to gain an unfair advantage over normal miners. Janushash however combines two hash functions and harnessing the probability theory and statistics, we can extract information about the Sha256t/Verushash hashrate ratio used to mine a block. This information is shown publicly in the blockchain explorer. In addition to the network difficulty, this second marker provides useful information on the network hashrate: It allows to spot suspicious hashrate immediately. In Warthog it is much more difficult for ASICs to stay undetected because they must not only successfully mine blocks, but also mimic the hashrate ratio used by honest miners. This is another unique property of Proof of Balanced Work. === Simple Algorithm Adaption The fundamental reason for the favorable properties of the Janushash algorithm is not the particular choice of the combined hash functions itself, but the choice to rely on Proof of Balanced Work to combine different hash functions multiplicatively. This means that if ASICs really join the network one day, we can simply exchange the combined hash functions, for example for Blake3 on GPU and RandomX on CPU, while preserving all the advantages listed here. Combining established hash functions allows the creation new algorithms fast while benefiting from their maturity and proven properties at the same time. This allows Warthog to adapt quickly when needed. == Other Benefits Warthog tries to revive the good old days when mining was fun. The unique properties of the Janushash algorithm help to achieve this goal: === Escaping one-dimensional mining boredom In a way, traditional mining in cryptocurrency is one-dimensional, the goal is simply to find the best hardware for evaluating some hash function. In contrast, mining Warthog is two-dimensional: there are two hash functions Sha256t and Verushash v2.2, and both hashrates are relevant for the mining efficiency. This leads to much more versatile options and motivates miners to experiment with endless hardware setups. Vivid discussions about the best combinations bring Warthog mining to life. === Favoring the little guy As explained above, established farms require substantial investments in order to mine Warthog efficiently and making such investment only for mining Warthog might not be reasonable for most farms. On the other hand gamers usually have systems with modern platforms and CPUs paired with sufficiently good GPUs to mine Warthog efficiently. Since farms and botnets are less of a direct competitor in Warthog than they are in other Proof of Work cryptocurrencies, this will reflect in increased mining returns for the average gamer or miner, which will in turn contribute to Warthog's popularity. = Technical Details == Retarget Logic Similarly to Bitcoin, the warthog blockchain will scale its difficulty periodically to adjust for changing hashrate. Changes in difficulty is partitioned into two phases: + In the initial phase the difficulty is adjusted every 720 blocks which corresponds to approximately 4 hours. + In the second phase the difficulty is adjusted every 8640 blocks which corresponds to 2 days. The reason for this two-phase approach is the high variability of hashrate in early stages of a project's life which initially requires a more frequent difficulty adjustment. On the other hand too short intervals also have disadvantages such as the tendency to oscillate and a possibly higher impact of faked timestamps. Therefore the second phase stretches the difficulty adjustment interval after the initial phase. While in Bitcoin the difficulty change is capped by factor 4, we have implemented a factor 2 cap because our difficulty adjustment is more frequent than 2 weeks. == Emission Scheme Warthog was started without any premined or reserved amount of coins on June 29, 2023. The project implements a classical halving-based emission scheme with halvings occurring every 3153600 blocks (every 2 years). The emission for the next 4 years is summarized in the following table: #figure( caption: [Emission scheme], table(columns: 3, table.header([*Date*], [*Lifetime*], [*% of total supply in circulation*]), ..for (.., Date,Lifetime, percent_emission) in emission { (Date,Lifetime, percent_emission) }) ) There is no tail emission which means there is a hard cap of the amount in circulation. The hard cap is `18921599.68464 WART` (around 19 million coins). Before halving occurs every block yields `3 WART` as miner reward. Since the block time is 20 seconds, every day approximately $60/20 × 60 × 24 = 4320$ blocks and `12960 WART` are mined daily before halving. == Coin Precision The reference implementation uses the C++ data type `uint64_t` for storing amounts of `WART`. This is a 64 bit unsigned integer. To represent fractions of a coin these values are interpreted in fixed point arithmetic with 8 digits precision. This means that `1 WART` is internally represented as `uint64_t` number with value 100000000. The smallest representable step is `0.00000001 WART` and represented as `uint64_t` number with value 1. For easier integration all API endpoints return both, the `WART` amount as a string (like `"amount": "12.0"`), and the internal integer representation indicated with label "E8" (like `"amountE8": 1200000000`). == One-of-a-kind chain descriptor based sync This project is an experiment where the developers try out new things and push the boundary of what is possible in blockchain technology. We invented a completely unique and new way of syncing nodes which is not presently not known to the industry. Traditionally during synchronization new nodes request block bodies identified by block hashes. The replying node has to look up the block body based on the hash and then sends it back. In contrast we have invented a node communication protocol which works without block hashes for block body lookup. In our setup nodes keep track on fork heights with other nodes. A chain descriptor is used to identify a specific chain on the peer. When a node appends to its chain, the chain descriptor remains unchanged, however the current chain descriptor is increased when the consensus chain switches to a longer fork. Block bodies for previous chains are also kept for some time in case a peer requests them. When syncing nodes request block bodies identified by a chain descriptor and a block range. This way we avoid overhead in communication and lookup. == SQLite backed block store SQLite is a battle-proven and well-established embedded SQL database engine. Warthog nodes use SQLite as their main storage engine for both, blocks and state. Nodes also index transactions and can provide basic blockchain explorer functionality directly via API thanks to SQLite. SQLite databases are also portable across 32-bit and 64-bit machines and between big-endian and little-endian architectures such that chain snapshots can easily shared. Furthermore SQLite supports transactions which are essential for data integrity even in case of a power outage or node crash. The default SQLite database file name used for the chain is `chain.db3` and can be configured via the `--chain-db` command line option == Account based architecture Warthog implements an account based architecture. This is similar to Ethereum and different from Bitcoin's UTXO model. Every account along with its balance is stored in the `State` table of the chain database. For efficiency reasons accounts are referred by their id: Every account is assigned a unique auto-incremented id value on first use. This makes blocks more space-efficient since a block id only requires 8 bytes of storage whereas an address would require 20 bytes. == Fee specification For efficiency and compactness transaction fees are encoded as 2-byte floating-point numbers (16 bits), where the first 6 bits encode the exponent and the remaining 10 bits encode a 11 bit mantissa starting with an implicit 1. This means that fee values cannot be `0` and are of lower precision than regular amount values which use 4 bytes. A fee of value of `0` specified on transaction generation will automatically transform into the minimal fee value of `0.0000001 WART`. #pagebreak() #show: appendix = Block Structure The binary content of a block is a concatenation of the following sections in their specified order: + Mining section + New address section + Reward section + Transfer section Below we describe the above sections. All numbers and id values are in network byte order. == Mining section This section allows miners to put 4 bytes of arbitrary data to affect the merkle hash. #let bytetable(caption,..entries) = { figure( caption: caption, table(columns: 2, align: left, table.header([*byte range*], [*content*]), ..entries) ) } #bytetable([Mining Section], [1-4], [arbitrary data]) == New address section This section lists new addresses that receive payments in this block and therefore need to be added to the `state` table. This way they will be assigned a new id value which is referenced in the other sections to specify a particular account. #bytetable([New Address Section], [1-4], [number `n` of new addresses], [5-(4+n*20)], [`n` addressess of 20 bytes each]) Miners are responsible to ensure that the addresses appearing in the new address section are not already present in the state table and are actually referenced in this block. Otherwise the block is considered invalid. == Reward section Mining reward is distributed to at least one reward address. (Need to be reworked as last commit change this) #bytetable([Reward Section], [1-2], [number `r` of reward entry], [3-(4+n*16)], [`r` reward entries] ) Every reward entry consists of 16 bytes: #bytetable([Reward entry], [1-8], [accountId], [9-16], [amount] ) The sum of the amounts received by the addresses listed in the mining reward section must not exceed the total mining reward (block reward + transaction fees), otherwise the block is considered invalid. The total size of the mining section is `2 + r * 16` bytes. == Transfer section The transfer section contains the transfers made in this block. Its binary outline is as follows: #bytetable([Transfer Section], [1-4], [number `t` of transfer entries], [5-(4+t*99)], [`t` transfer entries] ) Every transfer entry has the following structure: #bytetable( [Transfer structure], [1-8], [fromAccountId], [9-16], [pinNonce], [17-18], [fee], [19-26], [toAccountId], [27-34], [amount], [35-99], [recoverable signature (65 bytes)] ) Each payment entry has length 99 bytes. Compare this to the average transaction size of around 200 bytes per Bitcoin transfer. #pagebreak() #par(justify:false, [ = Link Collection - Website: https://www.warthog.network/ - Github: https://github.com/warthog-network - Gui Wallet: https://github.com/andrewcrypto777/wart-wallet - PoBW whitepaper: https://github.com/CoinFuMasterShifu/ProofOfBalancedWork/blob/main/PoBW.pdf - Janushash: https://warthog.network/docs/janushash - Guide for pool devs: https://warthog.network/docs/developers/integrations/pools/ - Guide for miner devs: https://warthog.network/docs/developers/integrations/miners/ - Guide: https://github.com/warthog-network/warthog-guide - Explorer: https://wartscan.io/ - Discord: https://discord.com/invite/QMDV8bGTdQ - Telegram: https://t.me/warthognetwork - Bitcointalk: https://bitcointalk.org/index.php?topic=5458046.0 - API documentation: https://github.com/warthog-network/Warthog/blob/master/doc/API.md - Reddit: https://www.reddit.com/r/warthognetwork/ - Pool: https://warthog.acc-pool.pw/ - Wart-Dapp: https://github.com/warthog-network/wart-dapp/releases - Coingecko: https://www.coingecko.com/en/coins/warthog - Exbitron: https://exbitron.com/trade?market=wart-usdt - Tradeogre: https://tradeogre.com/exchange/WART-USDT - Xeggex: https://xeggex.com/market/WART_USDT - Miningpoolstats: https://miningpoolstats.stream/warthog - Coinpaprika: https://coinpaprika.com/coin/wart-warthog/ - Livecoinwatch: https://www.livecoinwatch.com/price/WarthogNetwork-WART ]) #bibliography("cite.bib")
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Miscellaneous/typst_logo.typ
typst
#set page(width: 13.5cm, height: 14cm) #set text(size: 120pt, font: "Austera Text",); t
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/document_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // Hello // // // Error: 2-30 document set rules must appear before any content // #set document(title: [Hello])
https://github.com/cunhapaulo/typst_styles
https://raw.githubusercontent.com/cunhapaulo/typst_styles/main/toolbox/monography.typ
typst
MIT License
#import "toolbox.typ": * //==================================================================== // The project function defines how your document looks. // It takes your content and some metadata and formats it. //==================================================================== #let project( university: "", // University´s name sigla: "", // University´s sigla centre: "", // Center or Institute assotiation faculty: "", // Faculty´s name course: "", //Course name authors: (), // Informations about the authors title: "", // Title of the academic essay, article, report ou paper subtitle: "", // Optional subtitle abstract: [], // Short abstract keywords: [], // Keywords citystate: "", // City and State date: none, // Complete date of the academic work year: "", // Only the year of the wor discipline: "", // Name of the Discipline or Course professor: "", // Professor´s name body, ) = { //========================================================================== // IMPORTANT!!! // GLOBAL DEFINITIONS //========================================================================== let PAGE_SIZE = "a4" let TEXT_LANGUAGE = "pt" let ABSTRACT_HYPHENATE = true let LOGO_PATH = "../img/ufpa.png" let SUMMARY_DEPTH = 2 let SUMMARY_FONTSIZE = 12pt let HEADING_STYLE = "1.1" let HEADINGSPACE_ABOVE = 1.5em let HEADINGSPACE_BELOW = 0.78em let BODY_FONTSIZE = 12pt let BODY_FIRSTLINEINDENT = 10mm let BODY_INTERLINESPACE = 10pt // 0.78em let BODY_PARAGRAPHSPACING = BODY_INTERLINESPACE let BODY_HYPHENATE = true let BODY_FONTTYPE = "Palatino Linotype" //"STIX Two Text" // "STIX Two Text", "TeX Gyre Pagella", "Liberation Serif", "Fira Sans", "Lib<NAME>", "New Computer Modern", "TeX Gyre Termes", "Atkinson Hyperlegible", "STIX Two Text", "Linux Libertine", "Inria Serif", "Source Sans Pro", "Palatino", "Palatino Linotype" let sumario = "Trabalho apresentado à disciplina " + discipline + ", ministrada pelo " + professor + ", pelo(s) aluno(s) " + for a in authors [ #a.name, matrícula #a.mat, ] + " como tarefa avaliativa do Curso de "+ course +" da " + university + " (" + upper(sigla) + ")." // --------------------------------------------------------------- // Lists Configurations // --------------------------------------------------------------- set enum(indent: 20pt, body-indent: 6pt, numbering: "1.a.i.") set list(indent: 20pt, body-indent: 6pt,) // --------------------------------------------------------------- // Set the document's basic properties. // --------------------------------------------------------------- set document( author: authors.map(a => a.name), title: title, ) set page( paper: PAGE_SIZE, margin: (left: 30mm, right: 30mm, top: 30mm, bottom: 30mm), ) set text( lang: TEXT_LANGUAGE, size: BODY_FONTSIZE, font: BODY_FONTTYPE, ) show par: set block(spacing: BODY_PARAGRAPHSPACING) // Defines separation character to be used in the cation of all elements. show figure.where( // kind: image, ): set figure.caption(position: top, separator: [ -- ]) // --------------------------------------------------------------- // Configure headings // --------------------------------------------------------------- // show heading: it => locate(loc => { // // Find out the final number of the heading counter. // let levels = counter(heading).at(loc) // let deepest = if levels != () { // levels.last() // } else { // 1 // } // if it.level == 1 [ // #v(12pt, weak: true) // #numbering("1") // #set par(first-line-indent: 0pt) // #h(10pt, weak: true) // #it.body // #v(13.75pt, weak: true) // ] // else if it.level == 2 [ // #v(18pt, weak: true) // #set par(first-line-indent: 0pt) // #numbering("1.1", deepest) // #h(10pt, weak: true) // #it.body // #v(10pt, weak: true) // ] else if it.level == 3 [ // // Third level headings are run-ins too, but different. // #v(16pt, weak: true) // #set par(first-line-indent: 0pt) // #numbering("1.1.1", deepest) // #h(10pt, weak: true) // #it.body // #v(10pt, weak: true) // ] // }) // show heading.where( level: 1 ): it => block(width: 100%)[ // #v(6pt) // #let c = counter(heading).display(); // #if ( c != "0" ) [ #c ] // #h(6pt) // #it.body // #v(6pt) // ] // show heading.where( level: 1): set block(above: HEADINGSPACE_ABOVE, below: HEADINGSPACE_BELOW) // show heading.where( level: 2 ): it => block(above: HEADINGSPACE_ABOVE, below: HEADINGSPACE_BELOW, width: 100%)[ // #counter(heading).display() // #h(5pt) // #it.body // ] // show heading.where( level: 3 ): it => block(above: HEADINGSPACE_ABOVE, below: HEADINGSPACE_BELOW, width: 100%)[ // #counter(heading).display() // #h(5pt) // #it.body // ] // show heading.where( level: 4 ): it => block(above: HEADINGSPACE_ABOVE, below: HEADINGSPACE_BELOW, width: 100%)[ // #v(3pt) // #counter(heading).display() // #h(5pt) // #it.body // #v(1pt) // ] // show heading.where(level: 2).or(heading.where(level: 3)): set block(above: heading-space-above + 3pt, below: heading-space-below + 3pt) show heading: it => { set block(above: HEADINGSPACE_ABOVE + 3pt, below: HEADINGSPACE_BELOW + 3pt) if it.level >= 1 it } set heading(numbering: HEADING_STYLE) show outline: set heading(numbering: none) show bibliography: set heading(numbering: none) // --------------------------------------------------------------- // FRONT PAGE // --------------------------------------------------------------- block(height:100%, width: 100%)[ #align(center)[ // LOGO_PATH #block()[ #image(LOGO_PATH, width: 20%) #set text(size: BODY_FONTSIZE) #upper[ #university\ #centre\ #faculty ] ] // #v(10%, weak: true) #v(1fr) // AUTHORS #grid( ..authors.map(a => upper[ #a.name #v(9pt) ] ), ) // #v(10%, weak: true) #v(1fr) // TITLE #block( text(upper[#title], weight: 600, BODY_FONTSIZE+2pt, hyphenate: false) + text(upper[#subtitle], BODY_FONTSIZE+2pt,hyphenate: false) ) // #v(55%, weak: true) #v(1fr)#v(1fr)#v(1fr)#v(1fr)#v(1fr)#v(1fr) #set text(size: BODY_FONTSIZE - 2pt) #block(text(upper[#citystate]) + linebreak() + text(year)) ] ] pagebreak() // --------------------------------------------------------------- // 2nd FRONT PAGE // --------------------------------------------------------------- block(height:100%, width: 100%)[ #align(center)[ // AUTHORS #grid( ..authors.map(a => upper[ #a.name #v(9pt) ] ), ) // #v(15%) #v(1fr) // TITLE #block( text(upper[#title], weight: 600, BODY_FONTSIZE, hyphenate: false) + text(upper[#subtitle], BODY_FONTSIZE, hyphenate: false) ) ] // #v(15%) #v(1fr) // ABSTRACT #set par(justify: true,) #align(right)[ #block( width: 75mm, align(left)[ #text(sumario, kerning: true, hyphenate: ABSTRACT_HYPHENATE, size: BODY_FONTSIZE,) ] ) ] // #v(40%, weak: true) #v(1fr)#v(1fr)#v(1fr) #align(center)[ #set text(size: BODY_FONTSIZE - 2pt) #block(text( upper[#citystate]) + linebreak() + text(year)) ] ] pagebreak() // --------------------------------------------------------------- // SUMMARY // --------------------------------------------------------------- block()[ #set text(size: SUMMARY_FONTSIZE, kerning: true,); #par( leading: 10pt, outline(indent: 8mm, depth: SUMMARY_DEPTH) ) ] // --------------------------------------------------------------- // BODYTEXT - BEGIN PAGE NUMBERING // --------------------------------------------------------------- counter(page).update(0) // Set summary page to zero so the next page will be 1 set page( numbering: "1", number-align: right + top, ) set par( justify: true, first-line-indent: BODY_FIRSTLINEINDENT, leading: BODY_INTERLINESPACE, linebreaks: auto, ) set text(size: BODY_FONTSIZE, kerning: true, hyphenate: BODY_HYPHENATE) pagebreak() body } // END OF PROJECT
https://github.com/kokkonisd/typst-phd-template
https://raw.githubusercontent.com/kokkonisd/typst-phd-template/main/README.md
markdown
The Unlicense
# PhD doc/presentation template ## How to install The template needs to be installed in a special directory, as described [in the docs](https://github.com/typst/packages?tab=readme-ov-file#local-packages). The installer in this repo assumes you have `TYPST_LOCAL_PACKAGES` defined to the correct path, which should be something like `$HOME/.local/share/typst/packages/local` on Linux. ### Stable version You need to clone this repo, checkout a specific version (tag), and run the install script: ```console $ git clone <EMAIL>:kokkonisd/typst-phd-template.git $ git checkout 0.1.0 # `git tag` lists the available tags $ ./install.sh --offline ``` ### Latest (non-stable) version Here's a one-liner for a Linux installation. ```console $ bash <(curl -s https://raw.githubusercontent.com/kokkonisd/typst-phd-template/main/install.sh) ``` ## How to use In the [examples](examples) directory, see [report.typ](examples/report.typ) for the report template and [presentation.typ](examples/presentation.typ) for the presentation template.
https://github.com/jens-hj/ds-exam-notes
https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/4.typ
typst
#import "../lib.typ": * #show link: it => underline(emph(it)) #set math.equation(numbering: "(1)") #set enum(full: true) #set math.mat(delim: "[") #set math.vec(delim: "[") #set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled)) #show heading.where(level: 1): it => text(size: 22pt, it) #show heading.where(level: 2): it => text(size: 18pt, it) #show heading.where(level: 3): it => { text(size: 14pt, mainh, pad( left: -0.4em, gridx( columns: (auto, 1fr), align: center + horizon, gap: 0em, it, rule(stroke: 1pt + mainh) ) )) } #show heading.where(level: 4): it => text(size: 12pt, secondh, it) #show heading.where(level: 5): it => text(size: 12pt, thirdh, it) #show heading.where(level: 6): it => text(thirdh, it) #show emph: it => text(accent, it) #show ref: it => { //let sup = it.supplement let el = it.element if el == none { it.citation } else { let eq = math.equation // let sup = el.supplement if el != none and el.func() == eq { // The reference is an equation let sup = if it.fields().at("supplement", default: "none") == "none" { [Equation] } else { [] } // [#it.has("supplement")] show regex("\d+"): set text(accent) let n = numbering(el.numbering, ..counter(eq).at(el.location())) [#sup #n] } else if it.citation.has("supplement") { if el != none and el.func() == eq { show regex("\d+"): set text(accent) let n = numbering(el.numbering, ..counter(eq).at(el.location())) [#el.supplement #n] } else { text(accent)[#it] } } } } === Proporties - Reliability - Increase _speed_ beyond individual disk capabilities - Since disk speed growth has plateaued === Disks #image("../img/hdd.png", width: 50%) $ "access time" = "seek time" + "latency time" + "transfer time" $ #image("../img/hdd-os.png", width: 50%) ==== Disk Arm Scheduling Algorithm 1. Seek time - Move to the right cylinder 2. Latency time - Sectors rotate under the head 3. Transfer time - Moving the data to/from memory *Dominant:* physical seek time and physical rotation #image("../img/hdd-diag.png", width: 50%) *FIFO:* - Sub-optimal - _Very fair_ *SSTF:* Shortest Service Time First - Might never finish a specific request - Or big delays for some requests - _Not fair_ *SCAN:* - Always moving arm side to side - Read whichever request is there no matter when it was given - Favoring outermost and innermost tracks *C-SCAN:* - Best #emoji.face.surprise === RAID *Redundant Array of Inexpensive Disks* #report-block[ Didn't use any RAID terminology in report; _make sure to be able to use it at the exam_ ] What is possible with many inexpensive disks? #image("../img/raid.png", width: 80%) ==== Metrics - *Space Efficiency:* File size divided by the space used in the system. - *Storage Capacity:* Amount of data that can be stored in the system given a number of devices. - *Fault Tolerance:* Number of failed devices, $F$, that results in loss of data. - *Read Performance:* Given a system read speed of $R_(r,s)$ and a read speed of an individual disk $R_(r,d)$, the read performance is the speed-up: $R_(r,s) "/" R_(r,d)$. - *Write Performance:* Same as read performance, but with write speed of the system $R_(w,s)$ and of the individual disk $R_(w,d)$: $R_(w,s) "/" R_(w,d)$ - *Minimum Number of Disks Required* _Note: difficult to work with these metrics if all devices/disks aren't exactly the same._ #report-block[ Make sure to be able to use the _above metrics_ talking about the report. ] ==== What is RAID *Redundant Array of Inexpensive Disks* \ *Redundant Array of Independent Disks* Alternative to SLED: Single Large Expensive Disk - A RAID box with a RAID controller looks just like a SLED to the system using it ==== Striping #image("../img/raid-striping.png", width: 80%) ==== `RAID0` - Non-redundant - _Striped_ and _chunked_ - Not any more space efficient #image("../img/raid0.png", width: 50%) `Sx, Cy = Stripe x, Chunk y` *Purpose:* - Increase speed - Read/write in parallel from multiple devices - Serve data very quickly *Disk failure:* - Results in many stripes affected - Can't recover at all - Reliability is worse than SLED #tablex( columns: (auto, auto), (), vlinex(), thick-rule, colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID0`*]))), thick-rule, [*Metric*], [*Evaluation*], ..double-rule(2), [*Space Efficiency*], [1], trule, [*Storage Capacity*], [$N times "C"$, For $N$ equal sized disks with capacity $C$], trule, [*Fault Tolerance*], [$F=1$, a single disk causes damage], trule, [*Read Performance*], [$N$], trule, [*Write Performance*], [$N$], trule, [*Min Disks Required*], [2], thick-rule, ) ==== `RAID1` - Meant for _reliability_ - *Key:* $N$ mirrored disks - 1 Main disk, $N-1$ mirrors - Full file replication - *Failure:* Use any surviving disk, plug in new disk, copy over - *Read:* Pick fastest disk, $~2x$ for $N=2$, with a lot of requests, parallel read from several drives for different files. - *Write:* Single disk speed, no speed-up #tablex( columns: (auto, auto), (), vlinex(), thick-rule, colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID1`*]))), thick-rule, [*Metric*], [*Evaluation*], ..double-rule(2), [*Space Efficiency*], [$1"/"N$, very _bad_], trule, [*Storage Capacity*], [Capacity of _smallest_ single disk], trule, [*Fault Tolerance*], [$F=N$, lose all disks], trule, [*Read Performance*], [$N$, only in high load scenarios], trule, [*Write Performance*], [$1$, need to write to each disk], trule, [*Min Disks Required*], [2], thick-rule, ) ==== `RAID1 E` - Merge `RAID1` with ideas of striping & chunking from `RAID0` - _Striped_ and _chunked_ - *Read:* Can approach that of `RAID0` - Typically not interleaved _Basically `RAID0` with *one* replica of everything_ #image("../img/raid1e.png", width: 70%) `Sx, Cy = Stripe x, Chunk y` #tablex( columns: (auto, auto), (), vlinex(), thick-rule, colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID1 E`*]))), thick-rule, [*Metric*], [*Evaluation*], ..double-rule(2), [*Space Efficiency*], [$1 "/" 2$, typically used with 2 replicas], trule, [*Storage Capacity*], [$N C "/" 2$, half capacity of $N$ disks], trule, [*Fault Tolerance*], [$F=2$, can cause loss in worst case, best case: $F=N "/" 2$], trule, [*Read Performance*], [$N "/" 2$, light load, up to $N$ under high load], trule, [*Write Performance*], [$N "/" 2$ (could be higher depending on placement strategy)], trule, [*Min Disks Required*], [3], thick-rule, ) #report-block[ The idea that read/write could be higher depending on placement strategy is introduced here the first time, and is likely something like that that would have been nice to see in the project and report. However, it does of course require some parallel setup like this, which I didn't have. _Refer to this (`RAID1 E`) if asked about that_ ] // ==== RAID2 // #tablex( // columns: (auto, auto), // (), vlinex(), // thick-rule, // colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID2`*]))), // thick-rule, // [*Metric*], [*Evaluation*], // ..double-rule(2), // [*Space Efficiency*], [], // trule, // [*Storage Capacity*], [], // trule, // [*Fault Tolerance*], [], // trule, // [*Read Performance*], [], // trule, // [*Write Performance*], [], // trule, // [*Min Disks Required*], [], // thick-rule, // ) // ==== RAID3 // #tablex( // columns: (auto, auto), // (), vlinex(), // thick-rule, // colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID3`*]))), // thick-rule, // [*Metric*], [*Evaluation*], // ..double-rule(2), // [*Space Efficiency*], [], // trule, // [*Storage Capacity*], [], // trule, // [*Fault Tolerance*], [], // trule, // [*Read Performance*], [], // trule, // [*Write Performance*], [], // trule, // [*Min Disks Required*], [], // thick-rule, // ) ==== `RAID4` - {Block/stripe}-level parity with stripes - *Read:* accesses all the disks - *Write:* accesses all the disks *and* the parity disk - _Heavy load on parity disk_ *Like `RAID0` but with parity* #image("../img/raid4.png", width: 70%) `Sx, Cy, Pz = Stripe x, Chunk y, Parity z` *Parity:* - For each stripe create a parity - bit-by-bit xor for between chunks for each stripe #image("../img/raid4-parity.png", width: 70%) #tablex( columns: (auto, auto), (), vlinex(), thick-rule, colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID4`*]))), thick-rule, [*Metric*], [*Evaluation*], ..double-rule(2), [*Space Efficiency*], [$1-1"/"N$, taking the parity disk into account, otherwise like `RAID0`], trule, [*Storage Capacity*], [$(N-1) times C$, for $N$ disks with the same capacity of $C$], trule, [*Fault Tolerance*], [$F=2$, of the data disks, as at least two are needed to recover the combination of them], trule, [*Read Performance*], [$N-1$, taking the parity disk into account, otherwise like `RAID0`], trule, [*Write Performance*], [$N-1$, taking the parity disk into account, otherwise like `RAID0`], trule, [*Min Disks Required*], [3, 2 disks for striping and chunking, 1 for parity], thick-rule, ) ===== Challenges - Seperated parity disk to one single disk - Replaced by `RAID5` ==== `RAID5` - Block-interleaved parity - Can activate more disks when needing parity - *Read:* Better read than `RAID4` - *Write:* Same write performance as `RAID4` *`RAID4` but with spread out parity* #image("../img/raid5.png", width: 70%) `Sx, Cy, Pz = Stripe x, Chunk y, Parity z` #tablex( columns: (auto, auto), (), vlinex(), thick-rule, colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID5`*]))), thick-rule, [*Metric*], [*Evaluation*], ..double-rule(2), [*Space Efficiency*], [$1-1"/"N$, taking the parity disk into account, otherwise like `RAID0`], trule, [*Storage Capacity*], [$(N-1) times C$, for $N$ disks with the same capacity of $C$, as we're still losing the capacity equal to a whole disk on parity], trule, [*Fault Tolerance*], [$F=2$, same as `RAID4`], trule, [*Read Performance*], [$N$, no longer impaired by the parity disk], trule, [*Write Performance*], [$N-1$, we still have to write parity each time, same as `RAID4`], trule, [*Min Disks Required*], [3, same as `RAID4`], thick-rule, ) ==== `RAID6` - *Read:* can outperform `RAID5`, as there are multiple parities to take from - *Write:* slower than `RAID4`, because we need to perform more parity - Better _reliability_ than `RAID4` *Like `RAID5` with an extra parity* #image("../img/raid6.png", width: 70%) `Sx, Cy, Pz, Qw = Stripe x, Chunk y, Parity z, Parity 2 (Q) w` - Linear combination of 2 chunks, in such a way that you dont use more space than any other chunk. - What is $2 times "bitstring"$? - Reed-Solomon Code, _see next section_ - Possible to extent to protect against _more than 2 losses_, however, with some implications #image("../img/raid6-parity.png", width: 70%) #image("../img/raid6-reed.png", width: 60%) #image("../img/raid6-reed2.png", width: 50%) #tablex( columns: (auto, auto), (), vlinex(), thick-rule, colspanx(2, cellx(align: center, text(size: 14pt, [*`RAID6`*]))), thick-rule, [*Metric*], [*Evaluation*], ..double-rule(2), [*Space Efficiency*], [$1 - 2 "/" N$, same as `RAID5` but taking the space of another parity disk into account], trule, [*Storage Capacity*], [$(N-2) times C$, for $N$ disks of same capacity $C$], trule, [*Fault Tolerance*], [$F=3$ because of the extra parity], trule, [*Read Performance*], [$N$, same as `RAID5`, but can sometimes outperform, if parity can be used from two different disks], trule, [*Write Performance*], [$N-2$, taking the space of two parity disks into account], trule, [*Min Disks Required*], [4, 2 for striping and chunking, 2 for parity], thick-rule, ) ===== Finite Fields - Acceleratable with parallel GPU operations Introduction to next lecture. \ _How to set up that linear combination for extra parity_ *Closure Property* #image("../img/ff-closure.png", width: 50%) *Example $"GF"(2^2)$: Addition* \ _Instead of operating on 1 bit, operate on pairs of bits, i.e. numbers 0, 1, 2, 3_ \ XOR bitpair-by-bitpair #tablex( columns: same(auto, 5), (), vlinex(), (), (), (), (), colspanx(5, cellx(align: center, text(size: 10pt, [*`Addition`*]))), thick-rule, `+`, `0`, `1`, `2`, `3`, trule, `0`, `0`, `1`, `2`, `3`, `1`, `1`, `0`, `3`, `2`, `2`, `2`, `3`, `0`, `1`, `3`, `3`, `2`, `1`, `0` ) *Example $"GF"(2^2)$: Multiplication* \ _Retains some properties like multiplying with 0 always gives 0, with 1 always gives the same (identity)_ #tablex( columns: same(auto, 5), (), vlinex(), (), (), (), (), colspanx(5, cellx(align: center, text(size: 10pt, [*`Multiplication`*]))), thick-rule, `+`, `0`, `1`, `2`, `3`, trule, `0`, `0`, `0`, `0`, `0`, `1`, `0`, `1`, `2`, `3`, `2`, `0`, `2`, `3`, `1`, `3`, `0`, `3`, `1`, `2` ) *So how to do the `a + 2b` for the extra parity* \ _Using the two tables above_ ``` a = 10 b = 11 2 * b = 10 * 11 (= 2 * 3) = 01 (= 1) a + 2 * b = 10 + 01 = 11 ``` - _Retains the same bit-length_ which is important - Can be seen as some polynomial modulus arithmetic *What happens with more than 3 disks* \ - Go to bigger bit pairs if necessary #image("../img/ff-more3.png", width: 50%) === `RAID` Updating Data *What happens if you need to modify a file?* \ - Deleting/inserting #ra Messes up striping _If one were to touch the originally written data, then this might incur massive down-times or system slow-downs_ *Solution:* \ - Changes recorded appending data never modifying the original written data === Nested/Hybrid `RAID` - Combine several `RAID` levels stacked - Combines the different properties - Typically uses two levels like `RAID 10` - *First level is the lowest:* `RAID1` replication at the bottom - *Second is the highest:* Data striping of `RAID0` (carried out first) on top of `RAID1` replication _*Increases read/write speeds* of `RAID1` by doing the *striping* of `RAID0`_
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/array.typ
typst
Apache License 2.0
#(0) #let f(name) = ( ( pad(align(center + horizon, name)), ), )
https://github.com/elpekenin/access_kb
https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/content/parts/state_of_the_art.typ
typst
== Sin innovaciones Lo primero que debemos notar es que el panorama apenas ha variado en los ultimos 40 años, ni siquiera para adaptarse a las pequeñas pantallas táctiles de los móviles. Seguimos con las mismas ideas pese a tener tecnologías que superan antiguas limitaciones, permiten nuevas funcionalidades o proponen nuevos . #figure( block[ #align(horizon)[ #grid( columns: (auto, auto), figure( image("../../images/model_m.png", width: 100%), caption: [IBM Model M (1984)], numbering: none, outlined: false, ), figure( image("../../images/logitech.png", width: 100%), caption: [Logitech MX Mechanical (2022)], numbering: none, outlined: false, ), ) ] #figure( image("../../images/android_keyboard.jpg", width: 40%), caption: [Teclado Android], numbering: none, outlined: false, ) ], caption: [Comparativa teclado antiguo vs actual], ) == Diposición de las teclas Es posible que nunca nos lo hayamos preguntado puesto que tenemos muy interiorizada la forma de los teclados, pero si lo pensamos un poco, es peculiar la posición relativa de las teclas. Cada fila tiene un pequeño desfase con las demás en vez de estar alineadas. Esto es un legado de sus antecesoras -las máquinas de escribir- donde por limitaciones mecánicas,esto tenía que ser así para evitar choques entres las piezas móviles de cada tecla. #figure( image("../../images/typewriter.jpg", width: 30%), caption: [Detalle de las letras en una máquina de escribir], ) Este posicionamiento relativo de las teclas supone un problema a la hora de escribir, ya que la forma óptima de hacerlo sería la siguiente: #figure( image("../../images/mechanography.png", width: 30%), caption: ["Mapa" de mecanografía], ) Sin embargo, para escribir así, las muñecas terminan en posiciones un poco forzadas, y los dedos hacen movimientos incómodos. Para arreglar esto surgieron los teclados ortolineales, donde todas las filas están alineadas y los dedos se mueven en una línea recta. Estos teclados suelen tener todas las teclas del mismo tamaño, optimizando así la cantidad de teclas que podemos tener ocupando el mismo espacio (donde antes había una barra espaciadora pueden entrar varias teclas). Como se puede ver en la siguiente imagen, normalmente también prescinden del teclado numérico para reducir el tamaño, este modelo se conoce como "75%" ya que tiene 75 teclas mientras que los teclados comunes ("100%") tienen 104/105 teclas. Otras variantes comunes son "40%", "60%", "65%" #figure( image("../../images/ortholinear.jpg", width: 30%), caption: [Teclado ortolineal], ) == Ubicación de las letras <ubicación-de-las-letras> Otro legado que nos dejaron las máquinas de escribir es la distribución QWERTY, que probablemente sea la única distribución que hemos visto a lo largo de nuestra vida. El problema con esta disposición es que, si bien distribuye las letras de forma que se usan las dos manos por igual... Se diseñó en la decada de 1860, y uno de sus objetivos era el de reducir los atascos en las máquinas de escribir separando las teclas más usadas de la parte central. En contra, ahora que gracias a la electrónica no tenemos estas limitaciones, se han diseñado distribuciones que minimizan la distancia media que se debe recorrer al escribir, por lo que una vez acostumbrados a ellas se puede escribir más rápido y reduciendo la fatiga en los dedos. Las dos más extendidas son DVORAK y COLEMAK. #figure( [ #figure( image("../../images/qwerty.jpg", width: 70%), caption: [QWERTY], numbering: none, outlined: false, ) #align(horizon)[ #grid( columns: (auto, auto), gutter: 1em, figure( image("../../images/dvorak.jpg"), caption: [DVORAK], numbering: none, outlined: false, ), figure( image("../../images/colemak.png"), caption: [COLEMAK], numbering: none, outlined: false, ), ) ] ], caption: [Comparativa distribuciones], ) == Ergonomía Como hemos comentado por encima, unos de los problemas más importantes del diseño actual es su falta de adaptación a la anatomía humana. En los últimos años, entusiastas y pequeñas empresas han diseñado diferentes mejoras. Una de las ideas más básicas consiste en partir el teclado por la mitad a fin de que las muñecas tomen una forma más natural, lo que se conoce como _split_. #figure( image("../../images/quefrency.jpg", width: 45%), caption: [Teclado _Quefrency_], ) Un extra común en estos teclados consiste en levantar la parte central, de forma que la mano descanse y esté más cómoda. Un gran punto a favor de esta mejora es que se puede aplicar a cualquer teclado añadiendo algún sistema para ganar altura. Además, se puede ajustar esta altura según las necesidades del usuario. #figure( image("../../images/dygma.jpg", width: 30%), caption: [Teclado _Dygma Raise_], ) Muchos teclados dotan de una mayor utilidad a los pulgares, ya que normalmente solo los utilizamos para la barra espaciadora, a esto se le llama _thumb cluster_. #figure( image("../../images/ergodox.jpg", width: 40%), caption: [Teclado _Ergodox_], ) El mayor ejemplo de esta filosofía es el _Dactyl Manuform_, que tiene en cuenta la forma de las manos y las teclas se ubican acorde al movimiento de los dedos. Algunos usuarios ingegran un _trackball_ para poder controlar el cursor sin tener que mover la mano entre el teclado y el ratón. #figure( image("../../images/manuform.jpg", width: 30%), caption: [Teclado _Dactyl Manuform_ con trackball], ) <img:dactyl> En esta web#cite(<paper>) se pueden ver varios estudios sobre la relación entre el diseño del teclado y sus efectos en la salud
https://github.com/jamesrswift/pixel-pipeline
https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/layers/anchored.typ
typst
The Unlicense
#let validation(input, output, next) = { // output.push("Initializing Anchored") next(input, output) } #let input-assembler(input, output, next)={ next(input, output) } #let compute(input, output, next)={ next(input, output) } #let vertex(input, output, next)={ next(input, output) } #let layer() = (: validation: validation, input-assembler: input-assembler, compute: compute, vertex: vertex, )
https://github.com/jomaway/typst-bytefield
https://raw.githubusercontent.com/jomaway/typst-bytefield/main/common.typ
typst
MIT License
#import "lib/api.typ": * // Common network protocols #let ipv4 = bytefield( bitheader("bytes"), bits(4)[Version], bits(4)[IHL], bytes(1)[TOS], bytes(2)[Total Length], bytes(2)[Identification], bits(3)[Flags], bits(13)[Fragment Offset], bytes(1)[TTL], bytes(1)[Protocol], bytes(2)[Header Checksum], bytes(4)[Source Address], bytes(4)[Destination Address], bytes(3)[Options], bytes(1)[Padding] ) #let ipv6 = bytefield( bitheader("bytes"), bits(4)[Version], bytes(1)[Traffic Class], bits(20)[Flowlabel], bytes(2)[Payload Length], bytes(1)[Next Header], bytes(1)[Hop Limit], bytes(int(128/8))[Source Address], bytes(int(128/8))[Destination Address], ) #let icmp = bytefield( bitheader("bytes"), byte[Type], byte[Code], bytes(2)[Checksum], bytes(2)[Identifier], bytes(2)[Sequence Number], bits(auto)[Optional Data] ) #let icmpv6 = bytefield( bitheader("bytes"), byte[Type], byte[Code], bytes(2)[Checksum], bits(auto)[Internet Header + 64 bits of Original Data Datagram] ) #let dns = bytefield( bitheader("bytes"), bytes(2)[Identification], bytes(2)[Flags], bytes(2)[Number of Questions], bytes(2)[Number of answer RRs], bytes(2)[Number of authority RRs], bytes(2)[Number of additional RRs], bytes(8)[Questions], bytes(8)[Answers (variable number of resource records)], bytes(8)[Authority (variable number of resource records)], bytes(8)[Additional information (variable number of resource records)], ) #let tcp = bytefield( bitheader("bytes"), bytes(2)[Source Port], bytes(2)[Destination Port], bytes(4)[Sequence Number], bytes(4)[Acknowledgment Number], bits(4)[Data Offset],bits(6)[Reserved], bits(6)[Flags], bytes(2)[Window], bytes(2)[Checksum], bytes(2)[Urgent Pointer], bytes(3)[Options], byte[Padding], bits(auto)[...DATA...] ) #let tcp_detailed = bytefield( bitheader("bytes"), bytes(2)[Source Port], bytes(2)[ Destination Port], bytes(4)[Sequence Number], bytes(4)[Acknowledgment Number], bits(4)[Data Offset],bits(6)[Reserved], flag("URG"), flag("ACK"), flag("PSH"), flag("RST"), flag("SYN"), flag("FIN"), bytes(2)[Window], bytes(2)[Checksum], bytes(2)[Urgent Pointer], bytes(3)[Options], byte[Padding], bits(auto)[...DATA...] ) #let udp = bytefield( bitheader("bytes"), bytes(2)[Source Port], bytes(2)[ Destination Port], bytes(2)[Length], bytes(2)[Checksum], bits(auto)[...DATA...] )
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/02_virtualization_02_memory_00_basic.typ
typst
#import "../template.typ": * #pagebreak() = memory virtualization == Address Spaces === Early Systems The OS was a set of routines (a library, really) that sat in memory, and there would be one running program (a process) that currently sat in physical memory and used the rest of memory. #image("images/2023-12-12-20-46-40.png", width: 50%) === Multiprogramming and Time Sharing - the era of *multiprogramming*: Multiple processes were ready to run at a given time, and the OS would switch between them. - the era of *time sharing*: The notion of interactivity became important, as many users might be concurrently using a machine, each waiting for (or hoping for) a timely response from their currently-executing tasks. One way to implement time sharing would be: run one process for a short while, giving it full access to all memory, then stop it, save all of its state to some kind of disk (including all of physical memory), load some other process’s state, run it for a while. A big problem: it is way too slow, particularly as memory grows. As the figure below shows, leave processes in memory while switching between them, allowing the OS to implement time sharing efficiently. #image("images/2023-12-12-20-53-33.png", width: 50%) Allowing multiple programs to reside concurrently in memory makes *protection* an important issue. === The Address Space #definition("Definition")[ *Address Space*: it is the running program’s view of memory in the system. ] - the code of the program (the instructions) have to live in memory - a stack to keep track of where it is in the function call chain as well as to allocate local variables and pass parameters and return values to and from routines - the heap is used for dynamically-allocated, user-managed memory Code is static (and thus easy to place in memory), so we can place it at the top of the address space and know that it won’t need any more space as the program runs. #image("images/2023-12-12-21-00-52.png", width: 70%) Virtualizing memory example: Process A in tries to perform a load at address 0 (which we will call a virtual address) Somehow the OS, in tandem with some *hardware support*, will have to make sure the load doesn’t actually go to physical address 0 but rather to physical address 320KB (where A is loaded into memory). This is the key to virtualization of memory, which underlies every modern computer system in the world. ==== THE PRINCIPLE OF ISOLATION - If two entities are properly isolated from one another: - One can fail without affecting the other. #example("Example")[ - Memory isolation: running programs cannot affect the operation of the underlying OS - Walling off pieces of the OS from other pieces of the OS such as microkernels ] === Goals of A VM system: - transparency: the program shouldn’t be aware of the fact that memory is virtualized - efficiency: both in terms of time and space . - protection: protect processes from one another as well as the OS itself from processes. == Memory API === Types of Memory - *stack memory*(also called automatic memory), and allocations and deallocations of it are managed implicitly by the compiler for you, the programmer. - *heap memory*, where all allocations and deallocations are explicitly handled by you, the programmer. === `malloc` `sizeof` is generally thought of a s compile-time operator, meaning that the actual size is known at compile time. === `free` === Common Errors ==== Forgetting To Allocate Memory ```c char *src = "hello"; char *dst; // oops! unallocated strcpy(dst, src); // segfault and die ``` ==== Not Allocating Enough Memory ```c char *src = "hello"; char *dst = (char *) malloc(strlen(src)); // too small! strcpy(dst, src); // work properly ``` ==== Forgetting to Initialize Allocated Memory ==== Forgetting To Free Memory ==== Freeing Memory Before You Are Done With It ==== Freeing Memory Repeatedly ==== Calling free() Incorrectly ==== WHY NO MEMORY IS LEAKED ONCE YOUR PROCESS EXITS The reason is simple: there are really two levels of memory management in the system. - The first level of memory management is performed by the OS, which hands out memory to processes when they run, and takes it back when processes exit (or otherwise die). - The second level of management is within each process, for example within the heap when you call `malloc()` and `free()`. Even if you fail to call `free()` (and thus leak memory in the heap), the operating system will reclaim all the memory of the process (including those pages for code, stack, and, as relevant here, heap) when the program is finished running. No matter what the state of your heap in your address space, the OS takes back all of those pages when the process dies, thus ensuring that no memory is lost despite the fact that you didn’t free it. - For short-lived programs, leaking memory often does not cause any operational problems (though it may be considered poor form). - For a long-running server (such as a web server or database management system, which never exit), leaked memory is a much bigger issue, and will eventually lead to a crash when the application runs out of memory. Check out both `purify` and `valgrind`; both are excellent at helping you locate the source of your memory-related problems. === Underlying OS Support One such system call is called `brk`, which is used to change the location of the program’s break: the location of the end of the heap. It takes one argument (the address of the new break), and thus either increases or decreases the size of the heap based on whether the new break is larger or smaller than the current break. An additional call `sbrk` is passed an increment but otherwise serves a similar purpose. #tip("Tip")[ Note that you should never directly call either `brk` or `sbrk`. They are used by the memory-allocation library; if you try to use them, you will likely make something go (horribly) wrong. Stick to malloc() and free() instead. ] You can also obtain memory from the operating system via the `mmap()` call: By passing in the correct arguments, `mmap()` can create an anonymous memory region within your program—a region which is not associated with any particular file but rather with swap space. This memory can then also be treated like a heap and managed as such. `man mmap` for more details. === Other Calls - `calloc()` allocates memory and also zeroes it before returning - `realloc()` can also be useful, when you’ve allocated space for something (say, an array), and then need to add something to it: `realloc()` makes a new larger region of memory, copies the old region into it, and returns the pointer to the new region. == Mechanism: Address Translation *Efficiency* and *control* together are two of the main goals of any modern operating system. - the OS, with a little hardware support, tries its best to get out of the way of the running program, to deliver an *efficient* virtualization - by *interposing* at those critical points in time, the OS ensures that it maintains control over the hardware #tip("Tip")[ - INTERPOSITION IS POWERFUL: *Interposition* is a generic and powerful technique that is often used to great effect in computer systems. - In virtualizing memory, the hardware will interpose on each memory access, and translate each virtual address issued by the process to a physical address where the desired information is actually stored. - almost any well-defined interface can be interposed upon, to add new functionality or improve some other aspect of the system. - *One of the usual benefits of such an approach is transparency; the interposition often is done without changing the client of the interface, thus requiring no changes to said client.* ] The generic technique: - *hardware-based address translation*, or just *address translation* - changing *the virtual address* provided by the instruction to a *physical address* where the desired information is actually located The OS must: - get involved at key points to set up the hardware so that the correct translations take place; - manage memory, keeping track of which locations are free and which are in use. === Assumptions - the user’s address space must be placed *contiguously* in physical memory - the size of the address space is not too big - it is *less than the size of physical memory* - each address space is exactly the *same size* === An Example What we need to do? Why we need such a mechanism? #code(caption: [Example - C])[ ```c void func() { int x = 3000; // thanks, Perry. x = x + 3; // this is the line of code we are interested in ... ``` ] #code(caption: [Example -Assembly])[ ```c 128: movl 0x0(%ebx), %eax ;load 0+ebx into eax 132: addl $0x03, %eax ;add 3 to eax register 135: movl %eax, 0x0(%ebx) ;store eax back to mem ``` ] #image("images/2023-12-14-14-31-58.png", width: 30%) #tip("Tip")[ It presumes that the address of `x` has been placed in the register `ebx`, and the initial value of `x` is 3000. ] The following memory accesses take place: - Fetch instruction at address 128 - Execute this instruction (load from address 15 KB) - Fetch instruction at address 132 - Execute this instruction (no memory reference) - Fetch the instruction at address 135 - Execute this instruction (store to address 15 KB) From the program’s perspective, its address space starts at address 0 and grows to a maximum of 16 KB. - How can we relocate this process in memory in a way that is transparent to the process? - How can we provide the illusion of a virtual address space starting at 0, when in reality the address space is located at some other physical address? In the figure: #image("images/2023-12-14-14-34-39.png", width: 50%) - the OS using the first slot of physical memory for itself, - it has relocated the process from the example above into the slot starting at physical memory address 32 KB - The other two slots are free (16 KB-32 KB and 48 KB-64 KB) === Dynamic (Hardware-based) Relocation Introduced in the first *time-sharing machines* of the late 1950’s is a simple idea referred to as *base and bounds*; the technique is also referred to as *dynamic relocation*. We’ll need two hardware registers within each CPU: - *A base register* is used to transform virtual addresses (generated by the program) into physical addresses. - *A bounds (or limit) register* ensures that such addresses are within the confines of the address space. Each program is written and compiled as if it is loaded at address zero; when a program starts running, the OS decides where in physical memory it should be loaded and sets the base register to that value. In the example above, the OS decides to load the process at physical address 32 KB and thus sets the base register to this value. So it is translated by: ``` physical address = virtual address + base ``` #example("Example")[ ```asm 128: movl 0x0(%ebx), %eax ``` When the hardware needs to fetch this instruction, - It first adds the value to the base register value of 32 KB (32768) to get a physical address of 32896; - The hardware then fetches the instruction from that physical address. - Next, the processor begins executing the instruction. - The process then issues the load from virtual address 15 KB, which the processor takes and again adds to the base register (32 KB), getting the final physical address of 47 KB and thus the desired contents. ] ==== base and bounds The bounds register is there to help with protection. A small aside about bound registers, which can be defined in one of two ways: - it holds the _size_ of the address space. - it holds the physical address of the end of the address space #tip("Tip")[ Both methods are logically equivalent; for simplicity, we’ll usually assume the former method. ] Specifically, the processor will first check that the memory reference is within bounds to make sure it is legal(no greater than, no negative); in the simple example above, the bounds register would always be set to 16 KB. The base and bounds registers are hardware structures kept on the chip (one pair per CPU). Sometimes people call the part of the processor that helps with address translation the *memory management unit (MMU)*. ==== Example Translations A process with an address space of size 4KB has been loaded at physical address 16KB. #image("images/2023-12-14-14-59-12.png",width: 70%) ==== SOFTWARE-BASED RELOCATION The basic technique is referred to as *static relocation*, in which a piece of software known as the loader takes an executable that is about to be run and rewrites its addresses to the desired offset in physical memory. For example, if an instruction was a load from address 1000 into a register, (e.g., `movl 1000, %eax`), and the address space of the program was loaded starting at address 3000, the loader would rewrite the instruction to offset each address by 3000 (e.g., `movl 4000, %eax`). Static relocation has numerous problems. - First and most importantly, it does not provide protection, in general, hardware support is likely needed for true protection. - Another negative is that once placed, it is difficult to later relocate an address space to another location . ==== Hardware Support: A Summary #image("images/2023-12-14-15-34-38.png") The hardware should provide special instructions to modify the base and bounds registers, allowing the OS to change them when different processes run. These instructions are _privileged_; only in kernel (or privileged) mode can the registers be modified. Finally, the CPU must be able to generate exceptions in situations where a user program tries to access memory illegally. - “out-of-bounds” exception handler - “tried to execute a privileged operation while in user mode” handler ==== Operating System Issues #image("images/2023-12-14-15-40-18.png") - First, the OS must take action when a process is created, finding space for its address space in memory. It can simply view physical memory as an array of slots, and track whether each one is free or in use. #tip("Tip")[ the OS will have to search a data structure (often called a *free list*) to find room for the new address space and then mark it use ] - Second, the OS must do some work when a process is terminated.(i.e., exits gracefully, or is forcefully killed), the OS thus puts its memory back on the free list, and cleans up any associated data structures as need be. - Third, the OS must also perform a few additional steps when a context switch occurs. - The OS must save and restore the base-and-bounds pair when it switches between processes. - when the OS decides to stop running a process, it must save the values of the base and bounds registers to memory, in some per-process structure such as the process structure or process control block (PCB). - when the OS resumes a running process (or runs it the first time), it must set the values of the base and bounds on the CPU to the correct values for this process. - Fourth, the OS must provide exception handlers, or functions to be called, as discussed above; the OS installs these handlers at boot time (via privileged instructions). when a process is stopped (i.e., not running), it is possible for the OS to move an address space from one location in memory to another rather easily. To move a process’s address space: - the OS first deschedules the process; - then, the OS copies the address space from the current location to the new location; - finally, the OS updates the saved base register (in the process structure) to point to the new location. Note how its memory translations are handled by the hardware with no OS intervention: #image("images/2023-12-14-15-46-44.png", width: 80%) === Summary inefficiencies: because the process stack and heap are not too big, all of the space between the two is simply wasted. This type of waste is usually called internal fragmentation, as the space inside the allocated unit is not all used (i.e., is fragmented) and thus wasted. #tip("Tip")[ A different solution might instead place a fixed-sized stack within the address space, just below the code region, and a growing heap below that. However, this limits flexibility by making recursion and deeply-nested function calls challenging, and thus is something we hope to avoid. ] Our first attempt will be a slight generalization of base and bounds known as *segmentation*.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/syntax_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test common symbols. $ dot \ dots \ ast \ tilde \ star $
https://github.com/mrcinv/nummat-typst
https://raw.githubusercontent.com/mrcinv/nummat-typst/master/template.typ
typst
#let conf(title: none, authors: (), doc) = { // define how a equation label should look let equation-label(heading, equation) = [(#heading.#equation)] // define the numbering for an equation // first locate, where we are in the document set math.equation( numbering: equation => locate( loc => { // get the heading index at the location at offset 0 for heading level 1 let heading-index = counter(heading).at(loc).at(0) // create the label equation-label(heading-index, equation) }, ), ) // overwrite, how a reference is displayed show ref: it => { // skip if the label has no corresponding element to point at if it.element == none { return it } // get the type of the thing the ref points at let f = it.element.func() if f == math.equation { // for an equation do this block // a locate is required for a query locate( loc => { // query the location of the equation the reference points at let equation-location = query(it.target, loc).first().location() // get the index of the heading at the location of the equation let heading-index = counter(heading).at(equation-location).at(0) // get the index of the equation let equation-index = counter(math.equation).at(equation-location).at(0) // create the label with the supplement and the custom look it.element.supplement + [ ] + equation-label(heading-index, equation-index) }, ) } else { // for anything else use the default it } } show heading: it => [ #v(0.7em) #it #v(1em) ] show heading.where(level: 1): it => [ // pagebreak before new chapter #pagebreak() // reset the counter #counter(math.equation).update(0) #it ] show link: set text(blue.darken(20%)) show figure.where(kind: raw): it => block(width: 100%)[ #align(left)[#it.body] #align(center)[#it.caption] ] set document(title: title) set heading(numbering: "1.1") set page(paper: "a4", numbering: none) set par(justify: true) set align(center) v(1fr) text(25pt, smallcaps(title)) linebreak() v(1em) text(18pt, authors.join(", ")) v(2fr) text(18pt, datetime.today().display("[year]")) set align(left) set page(numbering: "1") doc }
https://github.com/TechnoElf/mqt-qcec-diff-thesis
https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-thesis/main/content/outlook.typ
typst
= Outlook Over the course of this thesis, many aspects of the application of diff algorithms to quantum circuit equivalence checking have been explored. This work, however, also opens various avenues of future exploration. One possible path is the development of new diff and diff-like algorithms that are better suited as a heuristic for the verification problem. It may, for instance, be possible to modify edit graphs using quantum identities to create further possibilities for matches and thus reduce the length of resulting edit scripts. This could improve the predictions of the application scheme. Additionally, the diff-based application scheme considers quantum circuits as lists of gates. In contrast to this, quantum circuits are usually represented by two-dimensional structures, such as matrices, @dd[s] or ZX-diagrams. For instance, quantum circuits are often visualised as a two-dimensional grid where gates may be rearranged horizontally as long as the ordering of operations on individual qubits remains the same. Such information on the positioning of the gate is unfortunately lost with the current approach. Similarly, it may be beneficial to explore further possibilities of modifying the output of a diff algorithm for suitability to the quantum circuit verification task. While a few permutations of possible post-processing functions have been tested in this work, the entire solution space is much more expansive. Furthermore, the applicability of a heuristic approach as explored here should be explored with regards to other quantum circuit equivalence checking methodologies. For example, the ZX-calculus uses a very similar method for verification as used in conjunction with @dd[s]. In any approach that relies a certain order of operations to maintain efficiency, the solution explored here may be of some use. In general, it is fair to conclude that the development of better application schemes has mostly been unexplored thus far. This technology, however, is crucial to the progress of current equivalence checking schemes, which are in turn indispensable for the creation of more effective quantum circuit optimisation methods. The work presented here is a small step in that direction. //In the end, however, the real application schemes were the friends that were made along the way.
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Miscellaneous/Alg/Practice%20Problems.typ
typst
Prove that the ring $B = CC[x,y,z,w,v] slash (x y z^2 + w v)$ is not an integral extension over $CC[x,y,z,w]$ and then use Noether's normalization lemma to rewrite it as an integral extension of a polynomial ring. Prove that the ring $B = CC[x,y,z,w,v] slash (x y z^2 + w^3 v)$ is not an integral extension over $CC[x,y,z,w]$ and then use Noether's normalization lemma to rewrite it as an integral extension of a polynomial ring.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/drafting/0.1.0/README.md
markdown
Apache License 2.0
# Drafting This package hosts several utilities that are useful for drafting documents, namely margin notes and precise positioning helpers. Over time, hopefully more utilities will be contributed. A quick, comprehensive overview is provided by the [example document](https://github.com/ntjess/typst-drafting/blob/main/docs/main.pdf): ![](https://github.com/ntjess/typst-drafting/raw/main/docs/main.png)
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/themes.md
markdown
# Themes The `polylux` template also supports theming. By default, the theme `slides-default-theme` is used. You can specify the use of another one in the initial `slides` statement: ```typ #show: slides( authors: "...", title: "...", // ... theme: your-fancy-theme(with, some, options), ) ``` ## Theme variants per slide The `#slide` function has an optional argument `theme-variant`. You can use it to select one of the variants your current theme provides, so that this specific slide will look different. ```typ #slide(theme-variant: "variant name")[ ... ] ``` ## Create your own theme On a high level, a theme is nothing more than a piece of code that defines how the slides look. On one level deeper, a theme is a function that takes a `data` dictionary and returns a dictionary with one key for each _variant_. Let us build a very simple one for demonstration purposes: ```typ #let dumb-theme = data => { ( "variant 1": ..., "variant 2": ..., ) } ``` Note that you can easily introduce parameters to your theme: ```typ #let dumb-theme(parameter) = data => { ( "variant 1": ..., "variant 2": ..., ) } ``` The `data` dictionary provides you with all the information that the user has set in the initial `slides` function, i.e. it has the following structure: ```typ ( author: ..., title: ..., subtitle: ..., short-author: ..., short-title: ..., date: ..., ) ``` Use these information however you please. On to the actual slides. Their appearance is defined by functions that accept some meta data, some array of contents (the last argument(s) to `#slide`, essentially) and return some richer content, somehow styling that slide: ```typ (dictionary, array of content) => content ``` We call these functions the _variants_ of the theme. You can define an arbitrary amount of them but one must be stored under the key `"default"` in your theme. The meta data referred to above are a dictionary containing any extra keyword arguments that the user has specified in their call to `#slide`. As a theme author, you should inform your users what kind of arguments you will respect. You should access that data defensively and not expect that users provide any of the extra arguments you can consume. Similarly, you should not expect that the meta data exclusively contains keys you respect. For example, if a user states ```typ #slide(funny-kwarg: "some value", theme-variant: "a variant", something-else: "wohoo")[ ... ] ``` then your styling function will be provided the following dictionary: ```typ ( funny-kwarg: "some value", something-else: "wohoo", ) ``` especially not containing a `theme-variant` item! The `#slide` function accepts an arbitrary amount of positional arguments that are interpreted as content for the slide. The user of this template can provide them by simply juxtapositioning multiple content blocks after `#slide` or `#slide(...)`, see [this section](./slide.html#slides-with-multiple-content-bodies). Often, it will make sense to work with only a single piece of content, however. In any case, your variant function will always be provided an array of contents as the second argument, so you will usually have to extract that single entry you are interested in (using `.at(0)` or `.first()`). It might also make sense to `panic` with an informative error message if the user provided another number of content blocks than you expected. To make use of some of the functionality this template offers, you can access - the counter `logical-slide`, telling you the "page number" of a slide, but without counting up on dynamical slides that produce mulitple PDF pages; - the state `section`, telling you what the user has currently set as the section name. Let us define a few variants variants. You should probably add a variant for a title slide to your theme. By convention, this variant is called `"title slide"`. ```typ #let dumb-theme = data => { ( "title slide": (slide-info, bodies) => align(center + horizon, data.title), "variant 2": ..., ) } ``` As noted above, one of the variants must have the name `"default"`. ```typ #let dumb-theme = data => { ( "title slide": (slide-info, bodies) => align(center + horizon, data.title), "default": (slide-info, bodies) => { text(.7em, [#slide-info.title (current section: #section.display())]) v(1fr) for body in bodies { body v(1em) } v(1fr) text(.7em, [#h(1fr) #logical-slide.display()]) }, "australia": (slide-info, bodies) => { if bodies.len() != 1 { panic("australia variant expected exactly one body") } text(.7em, [current section: #section.display()]) v(1fr) scale(y: -100%, bodies.first()) v(1fr) text(.7em, [#h(1fr) #logical-slide.display()]) }, ) } ``` We can see that the `"default"` variant expects that users provide a `title` keyword argument to `#slide`. (Note again that this is bad practise and you should provide some fallback behaviour if some arguments you expect are not provided.) The `"australia"` variant does not make use of the `slide-info` argument at all. That is completely fine, it must have this argument for formal reasons, anyway, though. Also, the `"default"` variant displays all the content blocks provided to `#slide` while the `"australia"` variant errors if more or less than one such block is given. The `"title slide"` variant uses neither the `slide-info` nor the `bodies`. That is a usual behaviour, as title slides normally only depend on the general information like author, presentation title, etc. And that's it already! Have fun creating your own theme and maybe consider opening a pull request at [the GitHub repository](https://github.com/andreasKroepelin/polylux) to share your creations! ## Per-slide escape hatch In some exceptional situations, the machinery of themes and theme variants might be too limited for what you need. Sometimes, you might find yourself needing a very special purpose design _just_ for a couple of slides. For that case, you can use the `override-theme` argument of the `#slide` function. It accepts a function of the form `(slide-info, bodies) => [slide content]`, just as if you would define a theme variant (see details above). For example, you might write something like this: ```typ #let special-purpose-theme(slide-info, bodies) = align(horizon)[ #rotate(45deg, heading(level: 2, slide-info.title)) #scale(x: -100%, bodies.first()) ] #slide(override-theme: special-purpose-theme, title: "This is rotated")[ #lorem(40) ] ``` If you feel like your use of this feature becomes more than exceptional, consider contributing a variant to the theme you use, or a new theme entirely.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-35.typ
typst
Other
// Error: 32-37 cannot divide by zero #(1, 2, 0, 3).sorted(key: x => 5 / x)
https://github.com/max-niederman/MTH311
https://raw.githubusercontent.com/max-niederman/MTH311/main/lib.typ
typst
#let implies = sym.arrow.r.double #let iff = sym.arrow.r.l.double #let pow = math.cal[P] #let common(title: "", margin: 1in, body) = { set document( author: "<NAME>", title: title, ) set page( paper: "us-letter", margin: margin, numbering: (..nums) => "Niederman " + numbering("1/1", ..nums), number-align: center, ) set par(linebreaks: "optimized", justify: true) set math.vec(delim: "[") set math.mat(delim: "[") show math.equation: set text(features: ("cv01",)) // title block(text(weight: 700, 1.75em, title)) // author block(strong("<NAME>"), below: 2em) columns(2, body) } #let homework(title: "", margin: 1in, body) = { show heading: set block(below: 1em) common(title: title, margin: margin, body) } #let lemma = block.with( width: 100%, inset: 8pt, radius: 6pt, fill: fuchsia.lighten(80%) )
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/documentation/docs/user_how_to.md
markdown
# User Guide ## Installation of Typstdiff package In order to use Typstdiff package functionality You are required to install the package through `pip` package manager. In order to do that in terminal You need to run the command: ```pip install typstdiff``` And that's it! If the installation goes succesfully You have the Typstdiff tool installed. ## How to use Typstdiff? 1. In order to use Typstdiff tool **locate and navigate to** the directory with the **.typst** extension files, on which You want to run Typstdiff. 2. While in the directory open the **terminal**. Here You will be able to type the command that runs the Typstdiff program. 3. While in terminal **type** the command: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;```typstdiff <path-to-old-file> <path-to-new-file> <path-to-output-typstdiff-file>```. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is the default command that runs the program, where: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - _typstdiff_: the name of the program &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - _path-to-old-file_: full name (with the .typst extension) of the _.typst_ file, located in the given directory, which is **the old version** of our file. To that file we will be comparing our new version of the file and - in accordance with the differences the output file will be then formatted. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - _path-to-new-file_: full name (with the .typst extension) of the _.typst_ file, located as well in the given directory, which is **the new version** of our file. This typst document will be compared to the old version. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - _path-to-output-typstdiff-file_: full name (with the .typst extension) of the _.typst_ file, where we want to save the result of the Typstdiff tool evaluation. It is **the output file** of the tool. This document will contain the original, old version of the analysed document with all the differences (deletions, additions, upgrades) that the new version of the analysed document has. No information from both of the files will be lost (only if the file contains supported by Typstdiff tool types). **Example:** ```typstdiff old.typ new.typ typstdiff_compared.typ``` Now all the differences will be marked with the default configurations: ![Parsing result](img/example_result.png) The _deletions_ are **striked out**, the _insertions_ are **underlined**. The _updates_ show two versions - what was written before (striked out) and what the new file contains now (underlined). ### Advanced options - customization 4. Additionally, there is an option for You to customize how the deletions and insertions are marked. You can add (and choose a colour of) the highlight to Your changes - separately for inserts and deletions, as well as change the colour of the font. To do that, the Typstdiff needs to be run with the command: ```typstdiff [ADDITIONAL-OPTIONS] <path-to-old-file> <path-to-new-file> <path-to-output-typstdiff-file>``` The options include: - `-ih`, `--insert-highlight` - which sets custom highlight to inserted changes - `if`, `--insert-font` - which sets custom font to inserted changes - `-dh`, `--delete-highlight` - which sets custom highlight to deleted changes - `df`, `--delete-font` - which sets custom font to deleted changes After providing the given option flag You need to specify the colour from the Typst predefined colours: | Shortcut | Colour Name | RGB Code | **Typst Colour** | |----------|-------------|-----------|------------------| | bl | black | luma0 | **black** | | ga | gray | luma170 | **gray** | | si | silver | luma221 | **silver** | | wh | white | luma255 | **white** | | na | navy | #001f3f | **navy** | | bu | blue | #0074d9 | **blue** | | aq | aqua | #7fdbff | **aqua** | | te | teal | #39cccc | **teal** | | ea | eastern | #239dad | **eastern** | | pu | purple | #b10dc9 | **purple** | | fu | fuchsia | #f012be | **fuchsia** | | ma | maroon | #85144b | **maroon** | | re | red | #ff4136 | **red** | | or | orange | #ff851b | **orange** | | ye | yellow | #ffdc00 | **yellow** | | ol | olive | #3d9970 | **olive** | | gr | green | #2ecc40 | **green** | | li | lime | #01ff70 | **lime** | Aside from the given colours You can simply provide the RGB code of the desired colour. Here is the output of the Typstdiff parsing, with the user's customizations: **Example** ```typstdiff old.typ new.typ typstdiff_compared.typ -if red -df blue -ih gray -dh yellow``` ![Parsing result](img/example_result_custom.png)
https://github.com/gvallinder/KTHThesis_Typst
https://raw.githubusercontent.com/gvallinder/KTHThesis_Typst/main/Chapter2.typ
typst
MIT License
#import "Template/kth_thesis.typ": chapter #show: doc => chapter(title: [Heading 1], doc) #lorem(100) - Indrag text 4 mm, Georgia 11pt tem quamet iriliquatie modipis - Indrag text 4 mm, Georgia 11pt tem quamet iriliquatie modipis - Indrag text 4 mm, Georgia 11pt tem quamet iriliquatie modipis, == Heading 2 #lorem(100) Here we also try to cite our reference @li. === Heading 3 #lorem(100) ==== Heading 4 We also include an example of a figure here @example_fig. #figure( image("Figures/example_fig.png"), caption: [Highly informative caption.] ) <example_fig> #lorem(100)
https://github.com/lxl66566/my-college-files
https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/数字信号处理/实验报告.typ
typst
The Unlicense
// typst 0.10.0 #import "../template.typ": * #import "@preview/mitex:0.1.0": * #let 手写字体=( "德彪钢笔行书字库", "LiDeBiao-Xing3", // 德彪钢笔行书 https://freefonts.top/font/60a68009f694d7302081e78b "田英章楷书", // https://eng.m.fontke.com/font/13069604/download/ "ChenDaiMing", // 陈代明硬笔体 https://freefonts.top/font/60bef156aa520e302b8e8922 "FZQiTi-S14S", // 方正启功简体 ) #let project( title: "数字信号处理", authors: ("absolutex"), body ) = { set document(author: authors, title: title) set page(numbering: "1", number-align: center, margin: 0.7in) // 正文,两端对齐,段前缩进2字符 set text(font: 字体.宋体, size: 字号.小四, lang: "zh") set par(first-line-indent: 2em) show heading: it => { it fake_par } // heading,一级标题换页且不显示数字,首行居中 set heading(numbering: (..nums) => if nums.pos().len() == 1 { "实验"+中文数字(nums.pos().first()) } else { nums.pos().slice(1,..).map(str).join(".") } ) show heading: it => { set text(font: 字体.黑体) if it.level == 1 { pagebreak(weak: true) align(center)[#text(size: 字号.小二, it)] } else if it.level == 2 { text(size: 字号.四号, it) } else if it.level == 3 { text(size: 字号.小四, it) } else{ text(size: 字号.五号, it) } } // figure(image) show figure.where(kind: image): it => { set align(center) it.body { set text(font: 字体.宋体, size: 字号.五号, weight: "extrabold") h(1em) it.caption } } // raw with frame show raw: set text(font: 字体.代码) show raw.where(block: true): it => frame()[#it] set enum(numbering: "1.") body } #let answer(body) = { text(font: 手写字体, body) } #show: project.with( title: "数字信号处理", authors: ( "absolutex", ) ) = 离散时间信号与系统 + 实验目的 + 熟悉应用MATLAB表示离散时间信号。 + 掌握线性卷积求解系统输出的基本方法。 + 掌握求解离散时间系统输出的方法。 + 理解采样率变化对信号离散化产生的影响。 + 实验内容 + 画出幅度按指数衰减的有限长复指数序列$x(n)=(0.9e^(-0.2 pi j))^n R_(30)(n)$的实部、虚部、幅度和相位。提示:可以调用的函数有exp()、stem()、real()、imag()、abs()、angle()等 #include_code("数字信号处理/实验代码/1.1.m") #figure( image("static/1.1.jpg", width:70%), caption: [实验结果], ) + 11阶滑动平均系统的输入/输出关系是$y(n)=1/11 sum_(k=0)^10 x(n-k)$,输入信号是 #mi[`x(n)=10 \cos (0.08 \pi n)+w(n)`],其中$w(n)$是一个在[-5, 5]之间均匀分布的随机序列。试求: + 用plot函数在0 ≤ n ≤ 100之间画出输入信号$x(n)$和输出信号$y(n)$ + 画出$x(n)$的2阶差分信号$v(n)=x(n)-2x(n-1)+x(n-2)$ + 画出$v(n)$与$w(n)$的相关序列 + 再产生一个随机序列,画出它与$v(n)$的相关序列。 #include_code("数字信号处理/实验代码/1.2.m") #figure( image("static/1.2.jpg", width:100%), caption: [实验结果], ) - 实验分析与讨论(请手写): + 试分析11阶滑动平均系统的滤波特性。 #answer[过渡带特性,整体输出更平滑。] + 试分析2阶差分系统的滤波特性。 #answer[高通特性] + 由3.和4.的实验结果,你得出了什么结论? #answer[相关序列越杂乱,相关系数越小。3.中的v(n)有w(n)参与组成,因此相关序列在 0 处幅值较大。而4.中的随机序列与v(n)不相关,相关序列的值分布比较均匀。] + 下面的差分方程可以产生声音的混响效果,请为音频文件`good.wav`合成混响的效果,并保存在`new_good.wav`文件中。用耳机欣赏混响前的音乐与混响后的音乐有何区别。 $y(n)=x(n)+alpha x(n-R) "其中, " alpha "<1(比如:α=0.3,R=5000)"$ #include_code("数字信号处理/实验代码/1.3.m") #figure( image("static/1.3.jpg", width:70%), caption: [实验结果], ) - 实验分析与讨论(请手写): + 请问该系统是IIR系统还是FIR系统? #answer[FIR系统] + 请分析系统的因果性和稳定性在不同的α值和R值(R ≠ ∞)下,系统的因果性和稳定性是否会有变化? #answer[$R>=0$时因果,$R<0$时非因果;对于任意$alpha$均稳定。] + 请用文字简要描述不同α值和R值下的混响效果的区别。 #answer[$α$控制音量。$α$值越大,混响音量越大;R控制延迟,R越大,延迟越大。] + 请编程实现实际音频信号经抽取系统$T[x(2n)]$、$T[x(4n)]$、$T[x(8n)]$后的音效。待处理的音频文件分别为钢琴乐曲卡农片段(canon.wav)和语音片段(dsp.wav)。展示你的程序设计方法并按照要求进行分析。 #include_code("数字信号处理/实验代码/1.4.m") #figure( image("static/1.4.jpg", width:100%), caption: [实验结果], ) - 实验分析与讨论(请手写): + 请比较分析两段乐曲在不同采样率下是否存在失真情况? #answer[存在。采样率越低,失真越严重。] + 请问随着采样率的不断下降,钢琴音频和语音哪一个失真效果更显著?请解释你的结论。 #answer[钢琴音频失真更显著。钢琴的平均频率更高,包含的信息更多。] = 离散傅立叶变换与分析 + 实验目的 + 熟悉应用MATLAB求解信号频谱的方法。 + 掌握应用FFT的方法求解系统输出的步骤。 + 对比分析利用线性卷积求解系统输出和利用FFT方法求解系统输出这两种方法的不同之处。 + 掌握系统分析方法和简单滤波器的设计方法。 + 实验内容 + 设输入信号$x(n)=sin(0.1 pi n)+cos(0.5pi n),0<=n<=199$,某LSI系统的单位脉冲响应为$h(n)=1/4[delta(n)+delta(n-1)+delta(n-2)+delta(n-3)]$,求: + 利用线性卷积求输入信号$x(n)$通过系统后的输出$y_1(n)$。 + 利用FFT的方法,先求解输入信号$x(n)$的频谱$X(k)$以及单位脉冲响应$h(n)$的频谱$H(k)$,通过计算$"IFFT"[X(k) dot H(k)]$求解系统的输出。 #include_code("数字信号处理/实验代码/2.1.m") #figure( image("static/2.1.jpg", width:100%), caption: [实验结果], ) - 实验分析与讨论(请手写): + 请比较两种不同方法求得的输出及其它们的频谱$Y_1(k)$及$Y(k)$; #answer[两种方法求得的输出$y_1(n)$和$y(n)$相同。] + 试分析该系统的滤波特性,并结合输出信号的频率成分进行分析。 #answer[该系统的滤波特性为带阻滤波器。将$[0.5pi,1.5pi]$的频率成分降到了0.2 左右,而通过了$[0,0.5pi]$和$[1.5 pi,2pi]$的频率成分。] + 已知某系统的系统函数为$H(z)=frac(1+z^(-1)+z^(-2),1+0.9z^(-1)+0.81z^(-2))$,且系统稳定,试求: + 求系统的零极点;(提示:可以用tf2zp()函数) + 画出系统的零极点图;(提示:可以用zplane()函数) + 画出系统的幅频响应、相频响应、群延迟。(提示:可以用freqz()、grpdelay()函数) #include_code("数字信号处理/实验代码/2.2.m") #figure( image("static/2.2.jpg", width:70%), caption: [实验结果], ) - 实验分析与讨论(请手写): + 试求该系统的ROC,并说明系统的因果性; #answer[$r=sqrt(0.45^2+0.78^2)=0.9, |z|>0.9$],因果。 + 试分析该系统的滤波特性; #answer[数字陷波器,主要滤除$2/3pi$与$4/3pi$的频率成分。] + 该滤波器是IIR滤波器还是FIR滤波器?该滤波器具有线性相位吗? #answer[IIR滤波器,不具有线性相位。] + 一个LSI系统由下面的差分方程描述: $ y(n)+0.8y(n-1)-0.64y(n-2)+0.3125x(n) $ + 用filter函数计算并画出在$0<=n<=100$内的系统单位脉冲响应,由画出的单位脉冲响应判断系统的稳定性。 + 画出系统零极点图及系统的幅频和相频响应曲线。 + 如果这个系统的输入是$x(n)=[5+3cos(pi/3n)]u(n)$,利用filter函数求在$0<=n<=200$内的系统输出。分析输出信号,观察$x(n)$中的直流分量和$pi/3$频率成份分量的通过情况。 + 如果希望将$x(n)$中的直流分量完全滤除,而$pi/3$频率成份分量仍然保留,应该怎样修改该系统的差分方程,用实验的方法验证你的结论。 #include_code("数字信号处理/实验代码/2.3.m") #figure( image("static/2.3.1.jpg", width:70%), caption: [第 1-2 题], ) #figure( image("static/2.3.2.jpg", width:70%), caption: [第 3 题], ) #figure( image("static/2.3.3.jpg", width:70%), caption: [第 4 题], ) - 实验分析与讨论(请手写): + 请通过实验分析该系统的稳定性; #answer[稳定,因为极点都在单位圆内。] + 请分析解释第3问中输入信号不同频率成份的通过情况,并解释原因; #answer[直流分量被抑制,$pi/3$频率成分几乎未被滤除。该系统函数对这两处的滤除作用不大。] + 请描述第4问的设计思路。 $ H(z)&=frac((z-e^(j 0))(z-e^(-j 0)),(z-0.95e^(j 0)(z-0.95e^(-j 0)))) $ $ &=frac(z^2-2z+1,z^2-1.9z+0.9025) $ $ &=frac(1-2z^(-1)+z^(-2),1-1.9z^(-1)+0.9025z^(-2)) $ + 音频文件test1.wav ~ test4.wav中录制了钢琴上的一些按键音,其中,请用FFT的方法识别出每段音频文件中含有那几个音符。(注: (la)=220Hz (ci)=246.94Hz (do)=261.63Hz 2(rui)=293.66Hz 3 (mi)=329.63Hz 4(fa)=349.23Hz 5(so)=392Hz ) + 请读入test1.wav ~ test4.wav音频文件,画出音频信号的时域图。 + 请识别test1.wav和test2.wav两个音频文件中弹奏的是哪个音符(请对音频信号中的有效音符区间进行谱分析,建议尝试使用不同的窗函数进行谱分析,以缓解频谱泄漏现象)。 + 请识别test3.wav和test4.wav两个音频文件中弹奏了哪些音符; + (拓展部分)test3.wav和test4.wav两个音频文件有多个音符,且在最后有三音和弦,请尝试切分这些音符,并对其中的单音或和弦进行识别。 #include_code("数字信号处理/实验代码/2.4.m") #figure( image("static/2.4.1.jpg", width:90%), caption: [时域图], ) #figure( image("static/2.4.2.jpg", width:90%), caption: [频谱图], ) 3-4 题尚未完成。 - 实验分析与讨论(请手写): + 请分析使用不同窗函数时谱分析的结果; #answer[矩形窗旁瓣衰减较慢。汉宁窗与哈明窗的能量集中在主瓣。] + 根据你的程序实验结果,请回答test1.wav ~ test4.wav音频文件中包含了哪些音符? = IIR数字滤波器的设计 + 实验目的 + 掌握应用MATLAB进行IIR数字滤波器设计的基本方法。 + 灵活运用MATLAB提供的函数设计各种类型的IIR数字滤波器。 + 实验内容 + 已知数字带通滤波器的通带指标为:$omega_(p 1)=0.3pi,omega_(p 3)=0.7pi,alpha_p=0.5"dB"$阻带指标为:$omega_(s 1)=0.2pi,omega_(s 2)=0.8pi, alpha_s=50"dB"$,分别设计满足以上指标的巴特沃斯、切比雪夫I型、切比雪夫II型、以及椭圆数字滤波器,并画出滤波器的频率响应。 #include_code("数字信号处理/实验代码/3.1.m") #figure( image("static/3.1.png", width:70%), caption: [实验结果], ) - 实验分析与讨论(请手写):请比较和分析不同类型滤波器在相同技术指标情况下设计出的滤波器阶数、以及滤波器幅频响应的特点。 #answer[椭圆数字滤波器阶数最低,过渡带最短;椭圆数字滤波器和切比雪夫II型滤波器通带波动较大。巴特沃斯滤波器与切比雪夫II型滤波器的通带更平滑。] + 设计一个数字高通滤波器H(z),它用在下面的结构中, $ x(t) -> A \/ D -> H(z) -> D \/ A -> y(t) $ 满足下列要求: + 采样频率为10kHz; + 阻带边缘频率为1.5kHz,; + 通带边缘频率为2kHz,; + 滤波器的幅频响应具有单调的通带和阻带特性。 画出该数字高通滤波器的频率响应。请自行设计一个输入信号(至少应含有两种及以上的频率成分)通过该滤波器,观察并解释滤波器的输出结果。 #include_code("数字信号处理/实验代码/3.2.m") #figure( image("static/3.2.jpg", width:70%), caption: [实验结果], ) - 实验分析与讨论(请手写):请写出该滤波器的技术指标,说明设计的输入信号以及实验获得的滤波结果。请预测一下,如果该滤波器用椭圆滤波器来设计,所得到的滤波器阶数应该会变多还是变少?为什么? #answer[$Omega_s=2pi f_s=3k pi "rad/s", Omega_p=2pi f_p=4k pi "rad/s", N>= (lg k_("sp"))/(lg lambda_("sp"))=16.02$,取$H=17$。实验结果是成功滤除了$X_(n 1)$的频率成分。如果换成椭圆滤波器,阶数会减少。] + 已知某系统如图所示 #figure(image("static/q1.png", width:50%)) 系统的输入x(t)为: #figure(image("static/q2.png", width:30%)) 若现在用数字滤波器模拟上述系统的输入输出效果,试求: + 请选择系统的采样频率fs,画出x(n); + 画出系统的幅频响应$|H(e^(j omega))|$; + 画出系统的输出y(n)。 #include_code("数字信号处理/实验代码/3.3.m") #figure( image("static/3.3.1.jpg", width:70%), caption: [x(n)], ) #figure( image("static/3.3.2.jpg", width:70%), caption: [幅频响应与相频响应], ) #figure( image("static/3.3.3.jpg", width:70%), caption: [y(n)], ) - 实验分析与讨论(请手写):请写出必要的系统分析步骤,分析该滤波器的滤波特性,并解释滤波结果。 #answer[$x(t)=R dot i(t)+y(t)=R C(d y(t))/(d(t))+y(t), X(s)=S Y(s)+X(s), H(s)=(Y(s))/(X(s))=1/(s+1)$。低通,$Omega_(s t)=100 "rad/s", f_(s t)=16 "Hz"$。滤波器确实滤除了低频成分,但过渡带较宽,效果不佳。] = FIR数字滤波器的设计 + 实验目的 + 掌握应用MATLAB实现FIR数字滤波器的窗函数设计方法。 + 掌握应用MATLAB实现FIR数字滤波器的频率采样设计方法。 + 理解FIR数字滤波器的线性相位约束条件。 + 实验内容 + 选择适当的窗函数设计一个数字带阻滤波器,通带指标为:$omega_(p 1)=0.3pi,omega_(p 2)=0.7pi,alpha_p=0.5 "dB"$,阻带指标为:$omega_(s 1)=0.4pi,omega_(s 2)=0.6pi,alpha_s=50 "dB"$,请画出设计的滤波器的脉冲响应和幅频响应。 #include_code("数字信号处理/实验代码/4.1.m") #figure( image("static/4.1.jpg", width:100%), caption: [实验结果], ) - 实验分析与讨论(请手写):请写出此题选窗的依据,以及滤波器长度的计算方法。另外,此题中对滤波器单位脉冲响应长度的奇偶性是否有要求?为什么? #answer[$alpha_s=50 "db"$,与哈明窗的-53dB相近。使用第一类滤波器实现带阻滤波器,N只能取奇数。] #linebreak() + 用频率采样法设计题 1 中的带阻滤波器,选择适当的滤波器阶数,为确保滤波效果,要求过渡带中有两个样本(按照经验值,过渡带两个样本的幅度可以取为0.109和0.594)。请画出设计的滤波器的脉冲响应和幅频响应。 #include_code("数字信号处理/实验代码/4.2.m") #figure( image("static/4.2.jpg", width:100%), caption: [实验结果], ) - 实验分析与讨论(请手写):请写出应用频域采样法设计该滤波器的方法。 #answer[带阻滤波器只能使用一类滤波器:偶对称,N为奇数。取 M=61,$alpha=(M-1)/2=30$] + 用等波纹最佳逼近法设计 1 中的滤波器(注:可以使用remezord()函数和remez()函数,参考第七章讲义例程)。 #include_code("数字信号处理/实验代码/4.3.m") #figure( image("static/4.3.jpg", width:70%), caption: [实验结果], ) - 实验分析与讨论(请手写):请比较窗函数法和等波纹最佳逼近法的滤波器阶数和滤波效果。 #answer[窗函数法设计出的滤波器阶数较低,但效果较差。等波纹最佳逼近法设计出的滤波器阶数较高,但效果较好,衰减基本在-60dB以下。] = 综合实践项目:钢琴乐音识别技术研究 == 实验目的 通过钢琴乐音识别技术的研究,掌握满足复杂工程问题需求的离散时间系统的基本设计方法与分析技术,了解影响设计目标和技术方案的各种因素,并得出有效结论。 == 实验内容 钢琴乐音识别技术对钢琴乐音信号进行基频估计,然后根据基频大小来区分音高,从而实现对乐曲的识别。 课题针对钢琴音频信号进行乐音识别技术的研究。在对音频信号其进行分帧、分音程检测后,对各音程段信号进行离散傅里叶变换,分析频谱中所蕴含的音符信息,并与乐谱进行比对,并得出结论。 请查阅提供的文献资料,并结合自己查阅的资料,完成以下实验内容: + 基础要求(必做):实现不同组别的钢琴音阶识别; + 进阶要求(选做):实现钢琴乐曲《小星星》的整曲识别。 + 拓展要求(选做):对钢琴乐曲《小星星》的整曲节奏进行分析评价。 注:2和3至少选做1个。 == 实验报告要求 + 请写出钢琴乐音识别的技术路线; 音频采样->时域分析处理->频域分析->谱图表示->音符检测->模式匹配 + 请阐述钢琴乐音识别的实现步骤; + 读入音频文件 + 用帧峰检测法提取音频的包络信号:对音频信号进行分帧,记录每一帧内的峰峰值,并将每一帧的峰峰值记录在包络数组中 + 使用滤波算法,对包络信号进行滤波,本实验选择中值滤波 + 根据包络信号寻找音符的起始点,并去除较小的伪峰点 + 音程段提取与谱分析:找到每一段的起始位置和终止位置,提取,乘窗函数,添零,再做FFT + 音频信号谱图的可视化 + 画整个音频的短时傅里叶谱图 + 钢琴音频整曲识别:读入钢琴按键与频率的对应表,将音频幅度矩阵映射到按键矩阵中,画出键号对应的图,显示识别结果 + 请对实验结果进行分析,并得出自己的结论; #figure( image("static/5.1.jpg", width:130%), caption: [从读取音频到找到音频起始点。plot1:时域图;plot2:包络线;plot3:findpeaks 结果;plot4:去除伪峰点,只保留音符起始位置], ) #figure( image("static/5.2.1.jpg", width:100%), caption: [逐个音程画图(1-16)], ) #figure( image("static/5.2.2.jpg", width:100%), caption: [逐个音程画图(17-32)], ) 使用音乐小星星画图,数量较多,后面还有一张,这里不放出。 #figure( image("static/5.3.jpg", width:70%), caption: [短时傅里叶谱图。上:test_Num=400,中、下:test_Num=4000], ) #figure( image("static/5.4.png", width:70%), caption: [研究不同帧长下的频谱泄露现象,以帧长400为例。], ) #figure( image("static/5.5.jpg", width:70%), caption: [钢琴音频节奏评价], ) + 请附上带注释的程序清单。 寻找音频起始点 #include_code("数字信号处理/实验代码/5.1.m") 逐个音程画图,外加没做完的音符识别 #include_code("数字信号处理/实验代码/5.2.m") 短时傅里叶谱图 #include_code("数字信号处理/实验代码/5.3.m") 不同帧长下的频谱泄露 #include_code("数字信号处理/实验代码/5.4.m") 钢琴音频节奏评价 #include_code("数字信号处理/实验代码/5.5.m")
https://github.com/widlarizer/lang-talk-unbash
https://raw.githubusercontent.com/widlarizer/lang-talk-unbash/main/presentation.typ
typst
The Unlicense
// Get Polylux from the official package repository #import "@preview/polylux:0.3.1": * // Make the paper dimensions fit for a presentation and the text larger #set page(paper: "presentation-16-9") #set text(size: 25pt) // Use #polylux-slide to create a slide and style it using your favourite Typst functions #polylux-slide[ #align(horizon + center)[ = Zapomněl jsem název prezentace, bash špatný Emil 2024-03-27 ] ] #polylux-slide[ == Proč bash skripty - society has moved past the need for bash scripts - tak proč furt jsou všude? ] #polylux-slide[ == Proč bash skripty - je potřeba pouštět věci not invented here :C - bash je všude, teď i na Windows - v praxi git bash, WSL, MinGW/cygwin - triviálně spustitelný, bez souborů kolem - bash umí pouštět programy a brát výstupy - a maže v proměnných bariéru mezi kódem vývojáře a konfigurací uživatele - lidi ho znaj ] #polylux-slide[ == Co jinýho splňuje tyto podmínky? - Je všude fish/zsh/powershell/...? - ne. Unless dark arts - kompilovaný jazyky nejsou single file executable - Python "neumí" pouštět programy, protože má složitej OS interface - uměli bychom tohle vyřešit? - Konfigurace Pythonu bývá v něčem nePythonickým (json, toml) - využít něčeho flexibilnějšího? - ostatní lidi neznaj TCL, Perl, Ruby... ] #polylux-slide[ == Jak zbashit Python? - knihovna je overkill, chceme jen snippet - bez nestandardních deps ] #polylux-slide[ == Jak zbashit Python: programy ```py import subprocess, functools r = functools.partial(subprocess.check_output, text=True) ``` - viz https://gist.github.com/widlarizer - `x = r(['qalc', '2+2'])` -> `x` je `'2 + 2 = 4\n'` - `x = r("ls | grep foo", shell=True)` -> `x` je `'foobar\n'` - `_ = r("rm -rf --no-preserve-root /".split)` - tzn umíme fajn `kwargs` jako `shell` nebo `env` - blokuje do skončení - vrací string, ne byte array ] #polylux-slide[ == Jak zbashit Python: programy ```py import subprocess, functools r = functools.partial(subprocess.check_output, text=True) ``` - viz https://gist.github.com/widlarizer - při nenulovým exit code terminuje - vytiskne stderr - hodí `subprocess.CalledProcessError` - tzn jako bash s cca `set -euo pipefail` ] #polylux-slide[ == Jak zbashit Python: konfiguráky - použijeme bash jenom na nastavení proměnných. Soubor `./env`: ```bash GIGADIR = /home/já/někde #VERSION = 0.6.9 VERSION = 4.2.0 TOOLS = $GIGADIR/$VERSION/ ``` - sourcujte, komentujte, konkatenujte, jak chcete - lepení stringů je prostě lepší v bashi ] #polylux-slide[ == Jak zbashit Python: konfiguráky ```py command = f'env -i {bash} -c "source ./env && env"' for line in subprocess.getoutput(command).splitlines(): key, value = line.split("=", maxsplit=1) os.environ[key] = value TOOLS = os.environ.get('TOOLS') ``` - *neleakujeme* externí environment - Pythonem použité proměnné jsou vyjmenované - ale do prostředí ve kterém pouštíme programy exportujeme všechno - to si změňte nebo vyhoďte jestli chcete ] #polylux-slide[ == Jak zbashit Python: konfiguráky ```py command = f'env -i {bash} -c "source ./env && env"' ``` - `env -i cmd`: pusť cmd, ignore environment - proto je `bash` proměnná, nemáme ani `$PATH` - `bash -c cmd` prostě pustí cmd explicitně v bashi - `env` vyprintí všechny nastavený proměnný jako `KEY=value` - toť vše ]
https://github.com/mkpoli/ipsj-typst-template
https://raw.githubusercontent.com/mkpoli/ipsj-typst-template/master/lib/latex.typ
typst
#let skew(angle, vscale: 1, body) = { let (a, b, c, d) = (1, vscale * calc.tan(angle), 0, vscale) let E = (a + d) / 2 let F = (a - d) / 2 let G = (b + c) / 2 let H = (c - b) / 2 let Q = calc.sqrt(E * E + H * H) let R = calc.sqrt(F * F + G * G) let sx = Q + R let sy = Q - R let a1 = calc.atan2(F, G) let a2 = calc.atan2(E, H) let theta = (a2 - a1) / 2 let phi = (a2 + a1) / 2 set rotate(origin: bottom + center) set scale(origin: bottom + center) rotate(phi, scale(x: sx * 100%, y: sy * 100%, rotate(theta, body))) } #let fake-italic(body) = skew(-12deg, body) #let TeX = { [T];box(move( dx: -1.5pt, dy: 2.2pt, box(scale(100%)[E]) ));box(move( dx: -3.0pt, dy: 0pt, [X] ));h(-1.0pt) } #let LaTeX = { [L];box(move( dx: -4pt, dy: -1pt, box(scale(x: 80%, y: 70%,[A])) ));box(move( dx: -5.7pt, dy: 0pt, [T] ));box(move( dx: -7.0pt, dy: 2.3pt, box(scale(100%)[E]) ));box(move( dx: -8.0pt, dy: 0pt, [X] ));h(-8.0pt) } #let LaTeX2e = { [2] box(move( dx: -1pt, dy: 1.5pt, box(text(style: "italic")[#fake-italic("ε")]) )) } /// Draw TeX logo /// text (string): the text to be typeset. Examples: "LaTeX", "TeX", "LaTeX2e", "LuaLaTeX", "XeLaTeX", "pdfLaTeX", "pdfTeX", "LaTeX2ε", etc. #let draw-TeX(tex) = { set text(font: "New Computer Modern Math") box( if (tex == "LaTeX") { LaTeX } else if (tex == "TeX") { TeX } else { show "TeX": TeX show "2e": LaTeX2e tex } ) } // #let LaTeX2e = { // LaTeX;box(move( // dx: -4.2pt, dy: -1.2pt, // box(scale(65%)[2]) // ));box(move( // dx: -5.7pt, dy: 0pt, // [ε] // ));h(-5.7pt) // }
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/Stacks.typ
typst
#import "../../../template.typ": * = Stacks #definition[ A *stack* is a last in, first out (LIFO) linear data structure, meaning that additions and removals happen on the same side of the structure. The main operations for stacks include: - *push(data)* - adds the data to the "top" of the stack - *pop()* - removes the data at the top of the stack and returns it - *peek()* - returns data for the top of the list without removing ] == SLL-Based Stack - Does not need a tail pointer #note[ An SLL based stack uses the _front of the SLL as the top of the stack_. Thus, push simply becomes addToFront and pop becomes removeFromFront, both of which are *O(1) operations* ] == Array-Based Stack - Requires a size variable along with the array #note[ In this case, the top of the stack is the back of the array. So we push by adding data to *arr[size]* and pop by removing the value at *arr[size-1]*, both of which are *O(1)* operations. ]
https://github.com/bnse/typst_tempalte_cn
https://raw.githubusercontent.com/bnse/typst_tempalte_cn/main/template.typ
typst
// The project function defines how your document looks. // It takes your content and some metadata and formats it. // Go ahead and customize it to your liking! #let project( title: "", abstract: [], authors: (), date: none, body, ) = { // Set the document's basic properties. set document(author: authors.map(a => a.name), title: title) set page(numbering: "1", number-align: center) set text(font: "New Computer Modern", lang: "zh") show math.equation: set text(weight: 400) set heading(numbering: "1.1") // Set run-in subheadings, starting at level 4. show heading: it => { if it.level > 3 { parbreak() text(11pt, style: "italic", weight: "regular", it.body + ".") } else { it } } // Title row. align(center)[ #block(text(weight: 700, 1.75em, title)) #v(1em, weak: true) #date ] // Author information. pad( top: 0.5em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center)[ *#author.name* \ #author.email ]), ), ) // Abstract. pad( x: 2em, top: 1em, bottom: 1.1em, align(center)[ #heading( outlined: false, numbering: none, text(0.85em, smallcaps[Abstract]), ) #abstract ], ) // Main body. set par(justify: true) body }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/lexical_hierarchy/func.typ
typst
Apache License 2.0
#let x = 1; #let f(a) = a;
https://github.com/songguokunsgg/HUNNU-Typst-Master-Thesis
https://raw.githubusercontent.com/songguokunsgg/HUNNU-Typst-Master-Thesis/master/hnu-thesis/templates/master-cover.typ
typst
MIT License
#import "@preview/t4t:0.3.2": is #import "../utils/datetime-display.typ": datetime-display, datetime-en-display #import "../utils/justify-text.typ": justify-text #import "../utils/style.typ": 字号, 字体 // 硕士研究生封面 #let master-cover( // documentclass 传入的参数 type: "master", degree: "academic", nl-cover: false, anonymous: false, twoside: false, fonts: (:), info: (:), // 其他参数 stoke-width: 0.5pt, min-title-lines: 2, min-reviewer-lines: 5, info-inset: (x: 0pt, bottom: 0.5pt), info-key-width: 110pt, info-column-gutter: 18pt, info-row-gutter: 12pt, meta-block-inset: (left: -15pt), meta-info-inset: (x: 0pt, bottom: 2pt), meta-info-key-width: 35pt, meta-info-column-gutter: 10pt, meta-info-row-gutter: 1pt, defence-info-inset: (x: 0pt, bottom: 0pt), defence-info-key-width: 110pt, defence-info-column-gutter: 2pt, defence-info-row-gutter: 12pt, anonymous-info-keys: ("student-id", "author", "author-en", "supervisor", "supervisor-en", "supervisor-ii", "supervisor-ii-en", "chairman", "reviewer"), datetime-display: datetime-display, datetime-en-display: datetime-en-display, ) = { // 1. 默认参数 fonts = 字体 + fonts info = ( title: ("基于 Typst 的", "湖南师范大学学位论文"), grade: "2021", student-id: "202120293792", author: "张三", department: "某学院", major: "某专业", supervisor: ("李四", "教授"), submit-date: datetime.today(), ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if (is.str(info.title)) { info.title = info.title.split("\n") } if (is.str(info.title-en)) { info.title-en = info.title-en.split("\n") } // 2.2 根据 min-title-lines 和 min-reviewer-lines 填充标题和评阅人 info.title = info.title + range(min-title-lines - info.title.len()).map((it) => " ") info.reviewer = info.reviewer + range(min-reviewer-lines - info.reviewer.len()).map((it) => " ") // 2.3 处理日期 assert(is.type(datetime, info.submit-date), message: "submit-date must be datetime.") if (is.type(datetime, info.defend-date)) { info.defend-date = datetime-display(info.defend-date) } if (is.type(datetime, info.confer-date)) { info.confer-date = datetime-display(info.confer-date) } if (is.type(datetime, info.bottom-date)) { info.bottom-date = datetime-display(info.bottom-date) } // 2.4 处理 degree if (info.degree == auto) { info.degree = "工程硕士" } // 3. 内置辅助函数 let info-key(body, info-inset: info-inset, is-meta: false) = { set text( font: if is-meta { fonts.宋体 } else { fonts.楷体 }, size: if is-meta { 字号.小五 } else { 字号.三号 }, weight: if is-meta { "regular" } else { "bold" }, ) rect( width: 100%, inset: info-inset, stroke: none, justify-text(with-tail: is-meta, body) ) } let info-value(key, body, info-inset: info-inset, is-meta: false, no-stroke: false) = { set align(center) rect( width: 100%, inset: info-inset, stroke: if no-stroke { none } else { (bottom: stoke-width + black) }, text( font: if is-meta { fonts.宋体 } else { fonts.楷体 }, size: if is-meta { 字号.小五 } else { 字号.三号 }, bottom-edge: "descender", if (anonymous and (key in anonymous-info-keys)) { if is-meta { "█████" } else { "██████████" } } else { body }, ), ) } let anonymous-text(key, body) = { if (anonymous and (key in anonymous-info-keys)) { "██████████" } else { body } } let meta-info-key = info-key.with(info-inset: meta-info-inset, is-meta: true) let meta-info-value = info-value.with(info-inset: meta-info-inset, is-meta: true) let defence-info-key = info-key.with(info-inset: defence-info-inset) let defence-info-value = info-value.with(info-inset: defence-info-inset) // 4. 正式渲染 pagebreak(weak: true, to: if twoside { "odd" }) // 居中对齐 set align(center) v(30pt) // 匿名化处理去掉封面标识 if (anonymous) { v(50pt) } else { pad(image("../assets/vi/hunnu_log_red.png", width: 14.5cm)) v(45pt) } // 将中文之间的空格间隙从 0.25 em 调整到 0.5 em // 42pt 就是初号字 text(size: 42pt, font: fonts.黑体, spacing: 200%, weight: "bold", "硕士学位论文", ) if (anonymous) { v(5cm) } else { v(1.5cm) } text(size: 22pt, font: fonts.黑体, spacing: 200%, weight: "bold")[ #for content in info.title [ #content ] ] v(1.5cm) block(width: 330pt, grid( columns: (info-key-width, 1fr), column-gutter: info-column-gutter, row-gutter: info-row-gutter, info-key("学科专业"), info-value("major", info.major), info-key("学位类型"), info-value("thesis_type", info.thesis_type), info-key("研究生姓名"), info-value("author", info.author), info-key("导师姓名、职称"), info-value("supervisor", info.supervisor.intersperse(" ").sum()), ..(if info.supervisor-ii != () {( info-key(" "), info-value("supervisor-ii", info.supervisor-ii.intersperse(" ").sum()), )} else { () }), info-key("论文编号"), info-value("thesis_number", info.thesis_number) )) v(1.5cm) text(font: fonts.仿宋, size: 字号.四号)[ 湖南师范大学学位评定委员会办公室 #datetime-display(info.submit-date) ] }
https://github.com/csimide/SEU-Typst-Template
https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/parts/outline-bachelor-fn.typ
typst
MIT License
#let outline-conf(outline-depth: 3, show-self-in-outline: true) = { set page( numbering: "I", number-align: center, ) set par(first-line-indent: 0pt, leading: 13.84pt) // 试出来的数值 heading( numbering: none, outlined: show-self-in-outline, bookmarked: true, )[目录] v(3pt) show outline.entry.where(level: 1): it => { if it.element.numbering == none and it.body.text.clusters().len() == 2 { link(it.element.location(), { it.body.text.clusters().first() h(2em) it.body.text.clusters().last() }) h(3pt) box(repeat("."), width: 1fr) h(3pt) link(it.element.location(), { it.page }) // 默认的 outline 中间没有链接,所以我也没加 } else { it } } outline(title: none, depth: outline-depth, indent: 2em) // 如果要和 Word 模板完全一样,需要改成 indent: n => (n + 1) * 2em }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/004_Return%20to%20Dominaria%3A%20Episode%204.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Return to Dominaria: Episode 4", set_name: "Dominaria", story_date: datetime(day: 04, month: 04, year: 2018), author: "<NAME>", doc ) Tiana's first conscious thought came as she stood in the Cathedral of Serra, bathed in sunlight splintered into a thousand shapes and colors by the stained glass arching overhead. She was surrounded by other angels in gleaming armor, and by human and aven clerics, their white robes emblazoned with gray feathers to mimic the angels' wings. She knew she had been created for some magnificent purpose; it warmed her heart, hummed through her veins, until her new body glowed like the sun. It was a glorious moment. Then everything started to go downhill. <NAME> stepped forward, as beautiful as the sunrise, her dark bronze skin glowing in the light and her mane of dark hair flowing over the icy perfection of her wings. She said, "You are Tiana, and you have been born in answer to the prayers of mortals, for a purpose."#linebreak   #figure(image("004_Return to Dominaria: Episode 4/01.jpg", width: 100%), caption: [Art by <NAME>n], supplement: none, numbering: none) "For battle," Tiana said. "To destroy the forces of darkness." That had to be her purpose. Surely nothing except war could burn in her like this. There was a faint stir from the other angels, and two exchanged a glance. Lyra's perfect brow furrowed just a little, and she said, "No, not for battle." "Not battle?" Tiana didn't want to question Lyra. She had been born knowing that Lyra was one of the angels who had come to Dominaria from Serra's Realm, that Lyra was as close as any angel would ever come to the blessed Serra, lost when she had sacrificed herself to heal Benalia. But Tiana felt like there had been some kind of mistake. "Are we sure about that?" Lyra's expression was still confident. "We're certain. You are not a battle angel. You're the answer to the prayers of mortals who need a guardian." "A guardian," Tiana repeated, reassured. Guardians had to fight to protect whatever they were guarding, obviously, so it was really just a slight variation on being a battle angel. "I will dedicate my life and soul to guarding—" She realized that in her relief she had gotten a little ahead of herself. "What am I guarding?" She hoped it was something big. Lyra may have hesitated—it was hard to tell. But her voice had the same confident serenity as she said, "A very complicated irrigation system." Tiana couldn't have heard that right. Maybe something had gone wrong when she had been created and the words didn't mean what they sounded like they meant. "A complicated . . . what?" "It's very important," Lyra assured her. "It has an intricate system of lifts and engines that carry the water from the reservoir up the side of a plateau to the town built atop it. Hundreds of mortals depend on it. They call it the Great Machine." Lyra's gaze was so serious. "They prayed for a protector for it. They prayed for you." Tiana pushed her disappointment aside. An irrigation system might sound like a strange, and potentially extremely boring, thing to protect, but this Great Machine was obviously very important to the mortals who had prayed for her. Because of that, it would probably get attacked a lot and she would have all the battle she could handle. The mortals would become her friends, and be glad they had received such an exemplary guardian angel for their prayers. She said, "I'll guard it to the last breath in my body." Lyra's smile warmed her, and the other angels raised their weapons in approval. Lyra said, "Excellent." The other angels took Tiana out of the cathedral, and they flew up into an achingly blue sky dotted with white clouds. Buildings floated in midair, all with round turreted roofs and elegant high arches, the brilliant colors of the window glass glowing in the sunlight. Below were rolling green hills and stands of tall trees, and Tiana heard distant birdsong. The wind was cool and sweet. Tiana knew not all the world was beautiful, but on this first morning of her life it seemed as if it were.#linebreak   #figure(image("004_Return to Dominaria: Episode 4/02.jpg", width: 100%), caption: [Art by Dimitar], supplement: none, numbering: none) They took her into a floating building and left her in a sunny room, where human clerics helped her dress in white and gray clothing while the aven flew off to bring armor and weapons for her to choose. "It's a very good thing you're finally here," her new friend the cleric Afra told her. "I've heard these people have been praying hard, for some time. The commander was very pleased to learn you were finally coming into being." "I wonder why I took so long," Tiana said, as Afra showed her how to tie laces. "Does that happen a lot?" "Oh, I'm sure it does. I'm sure it must have happened before." Afra glanced at the other clerics. One said, "It was very odd. I can't remember it ever taking so long for a prayer for a guardian angel to be answered." "Maybe because it was an unusual request," someone else said. "A guardian angel for an irrigation system? That's so . . . specific. People pray for guardian angels all the time, but never for anything like that—" Afra frowned at him. "Yes, all the time, which is why it probably took so long. The Blessed Serra can only send us so many guardians at once." There was some murmuring from the others, which Afra shushed, but Tiana's attention was caught by one of the portraits high on the wall. The knowledge she had been born with told her that the man with the brown hair and goatee, dressed as a Benalish man of arms, was a depiction of the martyr Gerrard. Her brows drew together as she studied the spear he held. The downward-pointing blade was a strange shape, almost flat on one side, with a jagged curve on the other and a crossbrace at an angle that somehow suggested flight. It seemed familiar to her, but she couldn't quite place how. "His spear—where is it from?" she asked. But then the aven clerics flew back to the balcony with her new armor and weapons, and in the excitement, Tiana forgot her question. Although the answer would come to her in time. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Soon it was time to fly to the town of the Great Machine that Tiana had been created to protect. An escort of angels would accompany her, led by <NAME> herself. Tiana followed Afra out to the broad open terrace where the other angels gathered. She whispered to her, "Is this normal? Does everybody get an escort?" "Not really," Afra admitted. "But these townspeople have been waiting so long, and their Great Machine is so important to them, Commander Lyra wants to take you there herself." That made sense. Tiana added, "And she wants to make sure nothing's wrong with me, because I took so long." Afra winced. "Yes, probably that. But don't worry, nothing's wrong. Holy Serra doesn't make mistakes." Tiana hugged Afra goodbye and went to join the others. Tiana's first real flight was wonderful, and she played the wind against her wings as she followed the other angels. They flew past hills dotted with small towns and villages, and then over heavy forest, and finally out over broad grassy plains. Tiana spotted a well-worn road winding along beneath them and knew they were getting close. Her heart pounded with excitement. She was about to see the reason for her birth. Which was not to fight at the side of <NAME> and the other battle angels to destroy the forces of darkness, but to protect a large and complicated machine. #emph[But it's an important machine] , she told herself. #emph[And I'm sure it'll be attacked a lot.] It turned out she was right about that part. As they approached the plateau, a haze of smoke hung over it. At first Tiana thought this was normal; the other human towns they had flown over hadn't had this much smoke, but maybe it was a byproduct of the Great Machine. But the sudden sense of agitation from the other angels warned her something wasn't right. They flew closer, and that was when she saw the town was in ruins. It had been attacked and burned, perhaps only a few days ago. The buildings were smoking ruins of tumbled stone and wood, and the dead lay in the streets. They circled around the plateau and Tiana saw what was left of the Great Machine. The wooden platforms were charred and the glass broken, the heavy chains shattered, metal tubes and gears twisted and bent. It had been huge, and had climbed the whole side of the plateau up from the reservoirs and canals that brought water from the distant river. Tiana was too stunned to feel anything at first, except a heavy lump in her throat, like something was trying to choke her from the inside. They landed in what was left of the town's plaza to help the survivors, and Lyra said grimly, "This is the work of the Cabal." So the forces of darkness had come to the place Tiana had been born to watch over, but she had been too late to fight them. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Tiana had to fold her wings in tightly to climb out from under the engine shield. "Tell Tien she wasn't wrong. It was a bad connector with a blockage in one of the mana flow controllers."#linebreak   #figure(image("004_Return to Dominaria: Episode 4/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Hadi gave her a hand up. Despite the protective leather aprons they wore over their clothes, they were both covered in grease and the remnants of the sea-bottom mud they were still cleaning out of the #emph[Weatherlight] 's mechanical systems. Hadi said, "That's a relief to hear. I'd hate to have to redo all that piping." They took the stairs up to the deck, and Tiana shook out her cramped wings and walked to the railing. Molimo's seed had almost finished regrowing the #emph[Weatherlight] 's hull and its interior decks, which was good and bad. Good because it gave them somewhere to stand and protected their rebuilding efforts from the weather. Bad because it made the engines and other systems more difficult to reach. Tiana would certainly do it differently if she was ever called upon to supervise the rebuilding of a legendary skyship again. The camp had expanded since Jhoira left, with more tents and some roughly built wooden sheds to house the work crew and protect their equipment. They had also built an elaborate scaffolding to support the grounded #emph[Weatherlight] and provide easy access for the workers. The sun was setting past the rocky hills that protected their cove and gleaming off the waves, and by the failing light they knew it was past time to stop for the day. The cool breeze already carried the scent of fried bread and onions from the cooking pit and their makeshift kitchen. It made Tiana a little sorry that angels didn't need to eat. She said, "Re-piping wouldn't have been a disaster, though. We're still ahead of schedule." "We are," Hadi agreed, packing up his tools into a leather satchel. "And that's due to you." Smiling, Tiana glanced at him. "Oh, am I a harsh overseer?" She thought their speedy progress was more due to the caliber of the crew Jhoira had hired. "You know what you're doing and you enjoy the work. That's the best we can ask for," Hadi said. He paused, one hand on the scaffold's rail. "I admit, I was surprised. I didn't expect an angel to know so much about artifact engines. I thought you'd be more . . . " "Useless?" Tiana suggested. By now she knew Hadi well enough to tease him. Once you'd spent endless hours crammed into various small spaces rebuilding a magical skyship's power train together, there were few things you couldn't say to each other. And Tiana was surprised, too; she knew her knowledge came from Serra, details about the #emph[Weatherlight] 's mechanical systems pouring into her head whenever she needed them. It had been happening since she had brought the Powerstone back to life. But she knew it wasn't a normal thing to happen to an angel. Especially a guardian angel whose reason for existence had been destroyed. She hadn't even wanted the mission to watch over the revival of the #emph[Weatherlight] 's Powerstone. She had been picked for it because she had been created to protect a machine and the #emph[Weatherlight] was a machine and this was the only thing the Church of Serra could think of to do with her. She had never expected to feel this way about the skeletal remnant of a skyship, no matter how legendary its reputation. "Aloof," Hadi corrected with a grin. "With a mind on higher things." "Skyships are fairly high things," Tiana remarked. "At least once we get that motivator working." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) They always posted sentries, and doubled their number through the night. Tiana patrolled the air at intervals, circling over their anchored supply vessel and all around the camp. So far she had to drive off a kavu, its tongue aflame, and violently discourage a small hunting party of goblins, but nothing too strenuous. Protecting the work crew from harm was the job she was supposed to be doing as a guardian angel, not helping Hadi and Tien and the others fix the engines. But then, finishing the #emph[Weatherlight] more quickly meant the work crew would be able to leave Bogardan sooner, and go somewhere safer, which technically fell under the category of guarding them. At least that was how Tiana was justifying it, and she was the one left in charge. And if Serra didn't want her to do it, she wouldn't be sending her this new knowledge. Tiana loved fiddling with the skyship's mechanical systems, loved figuring things out and fixing them. She thought maybe she loved the #emph[Weatherlight] . It was well past midnight and Tiana was taking a break, perched up on the scaffold to contemplate the waves rolling up the beach and the stars, when she heard someone run toward the #emph[Weatherlight] . She rolled off the platform and dropped to the ground as Farim, Hadi's young cousin, sprinted into the torchlight. "What is it?" Tiana said, keeping her voice low. Farim reported breathlessly, "Mari spotted someone coming. One man, walking over the meadows toward camp." "Right. Spread the word to the others," Tiana ordered, and leapt into the air. This part of Bogardan was mostly uninhabited, but there were pirate enclaves and hunters, and others here who might have gotten word of the camp's existence. One man approaching at night could be anything from a lost traveler to a spy for a Cabal force. She slid sideways across the wind, tilted her wings, and dropped to a landing behind the hillock where Mari's sentry post was. Mari, like all the work crew, was now used to an angel abruptly dropping out of the sky, so she didn't flinch when Tiana appeared beside her. She was crouched behind a screen of brush, and she handed Tiana one of Hadi's seeing-scopes. It was a chased metal tube like a normal telescope, except it allowed the viewer to see in the dark. Tiana's night vision was much better than a human's, but she took the scope anyway, since the magic in its construction tended to provide a much clearer view of whatever one was looking at. Mari whispered, "I think he's alone." Tiana focused on the approaching man. "Seems to be." She couldn't spot any other movement. He moved like a tired human, a pack slung over one shoulder, but there was something off about him. She handed the scope back to Mari and stood. She pushed off into the air again and circled high over the meadows. There was no movement from here to the frozen black waves of the lava fields, no sign of anyone else approaching. The man had spotted her and stopped, peering up at her in the dark. Either he had heard her wings, which seemed unlikely, or his night vision was at least as good as hers. #emph[Huh] , Tiana thought. She glided down and landed not far from him. He was dressed as a Benalish knight, with a distinctive inset of stained glass in the center of his chest armor and in the hilt of the sword slung across his back. He had clearly been traveling for some time, from the state of his clothes and the muddy hem of his tabard. This close, Tiana had a better view of his face. And his eyes, glowing faintly red in the darkness. There was no mistaking what he was. Tiana lifted her spear and said, "I see you're a vampire. Sorry about that. Any last words?" He lifted his hands, palms out. "<NAME>." He bowed deeply to her, just like a real Benalish knight. "I swear on Serra I haven't come here to harm anyone." "Haven't you?" Tiana asked, curious. "You're a vampire, so, you know, you have to be planning to harm people at some point." He shook his head, and she saw he seemed exhausted. "No. I'm not this way by choice. I fight against my condition with all my will." "Who are you?" Tiana asked. It might be more accurate to say #emph[who were you] , but that also seemed like adding insult to injury. "I'm Arvad, Knight of Benalia. I was captured and made a vampire." His voice was even but there was a thread of resignation in it. "I've tried not to harm anyone, and mostly succeeded." Some distance behind her, Tiana could hear Mari whispering an explanation to the workers who had come out to defend the camp. "Why hasn't she killed it yet?" someone said. Tiana wasn't quite certain why she hadn't killed him yet. She could sense he was a vampire, but something about him was different. She said, "Define 'mostly.'" Arvad looked away, then admitted, "I fight the Cabal whenever I can. Sometimes, in the heat of battle, I can't help myself." "But only the Cabal?" Tiana asked. It was a tricky moral point. The Cabal were by definition gleeful murderers, and even embraced their own deaths. And it wasn't as if a mortal Benalish knight wouldn't have been killing Cabal grimnants and clerics, too. He just wouldn't have been drinking their blood. "Only them," he said, and Tiana sensed he was telling her the truth. After a moment, he added, "I don't know where that would fall in the moral code of the Church of Serra." "Well, I was just thinking about that. It's a tough one. I'm new at this myself," Tiana said. "The Cabal murders a lot of innocent people, and they're so deluded they don't seem to care if they live or die themselves. But blood-drinking . . . " She waggled a hand. "It's tough to say. But to get back to the point, the Cabal isn't here, so why are you creeping up on our camp?" "I wasn't creeping, I was walking in the open," Arvad corrected, and gestured to the empty fields around him. "And . . . I'm not entirely sure. I've been drawn to this place, first to Bogardan, then toward this area. The closer I came, the less my compulsion affected me. It's been easier and easier to resist it, until . . . until standing here. I barely feel it at all. The relief is indescribable." He hesitated. "Can it be you? I've been within sight of other angels, and they never affected me this way before." "No, it's not me." Tiana thought he sounded honestly confused. And if he had truly been feeling his compulsion abate the closer he came to their camp . . . She had a strong inkling of what might be influencing him. "When did you start to feel drawn here?" Arvad had to pause to think. "It was on the night of the full moon, two months ago. It happened suddenly. I was on the eastern coast of Aerona, following the last few survivors of a Cabal scouting group, and I felt . . . It's hard to describe. I killed the grimnants, stole a small boat, and sailed in this direction." That was confirmation for Tiana's theory. That had been the day Jhoira had brought the #emph[Weatherlight] up, the day her prayer had stirred its Powerstone back to life. "I think I have an idea of what might be causing that."#linebreak   #figure(image("004_Return to Dominaria: Episode 4/04.jpg", width: 100%), caption: [Worn Powerstone | Art by <NAME>botham], supplement: none, numbering: none) His voice went rough with hope. "Something nearby. Do you think it would cure me?" "It's worth a shot," Tiana said. She lowered her spear. Drinking the blood of Cabal cultists might be a tricky moral point for the Church, but the possibility of a cure for vampirism wasn't. "Come on, let's try it. And it goes without saying, if you touch anyone here, I'll gut you like a fish." "That probably won't kill me," Arvad warned her. He was certainly honest. "I'll come up with something," Tiana promised. "That's fair," Arvad said, and started forward. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Tiana stood by while Arvad stared at the Powerstone. "Is it doing anything?" she asked. The senior work crew huddled at the opposite end of the engine access compartment, armed to the teeth. "No." Arvad turned away. His shoulders tensed under his battered armor, as if he was fighting down a surge of emotion. Then he faced her, resigned again. "Thank you for letting me try." He nodded to Hadi and the others, including them in his thanks. "Would you like me to leave?" Tiana glanced at Hadi and Tien. Tien had edged forward, peering at Arvad. She said, "Your face is better. Not so pale. And your eyes aren't so red." Tiana agreed. "Can you show us your . . . " She pointed at her own mouth. "You know." Arvad's brows quirked at the weirdness of the request, but he opened his mouth to reveal his fangs. Tiana's eyes narrowed. "Definitely smaller." Hadi nodded. "I think so, too." Tiana glanced at the others. "We need to discuss some things," she told Arvad. They went back up on deck under the star-filled sky. The work crew had rigged up a lighting system working off the #emph[Weatherlight] 's Powerstone, and Hadi had turned it back on since the entire camp was awake now. Insects buzzed around the deck lamps and the rest of the work crew was waiting down by the cooking pits. "Give us a moment," Tiana said, and left Arvad standing at the rail while they retreated to talk. "What are we going to do?" Hadi said. "He's telling the truth. We can see it." "But do we trust him?" one of the others asked. "I'll let you decide," Tiana said. They were the ones who would be the most at risk. Tiana might not be a battle angel, but in a vampire versus angel confrontation, she would definitely bet on herself. She waited while the others talked, her arms folded, watching Arvad. He was slumped at the rail, and she thought about what it would be like to grow up and become a knight, to be dedicated to protecting Benalia against danger and fighting the growing forces of the Cabal, only to be caught and forcibly turned into a monster with the compulsion to feed on human blood. It made her problem, being an angel created to answer the prayers of people who no longer existed, seem a minor inconvenience in comparison. Finally everyone finished talking, and Hadi gave her their verdict. He didn't look happy about their decision, but he said, "We don't know that he's telling the truth; we have no reason to trust him. But others, including myself, hate to turn him away if continued exposure to the Powerstone might cure him. As a compromise, he can stay but not in our camp, and you must pledge to watch him." Tiana nodded, and went to tell Arvad. He seemed surprised not to be told to leave immediately. He said, "That's very generous. I agree."#linebreak   #figure(image("004_Return to Dominaria: Episode 4/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Under the Powerstone's influence, Arvad had lost his vampiric sensitivity to sunlight, so he camped down on the beach, often stripping out of his armor to stand in the surf with a pole and catch fish to supplement the workers' dinner. Tiana, watching him from the dunes, reported to Tien, "He says it's the most normal thing he's done since he was turned." "You should go fishing, too," Tien told her. "You've been working so hard, you need a rest." "Mmm," Tiana said. She didn't want a rest, she wanted to work on the #emph[Weatherlight] 's systems while she still had a chance. But at least with Arvad she had someone to talk to at night who didn't sleep either, and who shared her fascination with the #emph[Weatherlight] . She sat down on the beach with him during her break from night patrol, and they both contemplated the skyship. With bright moonlight and their night vision, it was almost as good as looking at it in the daytime. "There's something on the hull down there," he said one night. "That dark spot." Tiana peered at it. "Looks like a spot of fungus. To regrow the hull, Jhoira used a seed from a tree spirit named Molimo. We've noticed it tends to sprout things occasionally." Bemused, Arvad asked, "How did she manage to get that?" "Because she's Jhoira." Tiana grinned. "She's a force of nature." Arvad paused. "She isn't . . . #emph[the] Jhoira? The one from the legends about the original #emph[Weatherlight] ?" "She #emph[is] that Jhoira, and those aren't legends, they're all true." Tiana admired the way the moonlight glanced off the new glass in the #emph[Weatherlight] 's ports. Arvad digested that in silence for a time, then said, "She means to use it to fight the Cabal, then." He glanced at her. "You'll help her?" Tiana ducked her head. It wasn't a comfortable subject for her. "I'm not a battle angel. I'm just supposed to guard the camp and watch over the Powerstone. Make sure no one tries to use it for anything but good and just purposes." Arvad seemed surprised. "I didn't think you were a battle angel, I thought you were an artificer angel." Tiana frowned. "No. There aren't any artificer angels." "But you're the one directing all the work." He tapped his ear. "There are few good things about my condition, but the improvement in my sight and hearing is one of them." "I don't have any official angel skills. I'm not supposed to be working on the engines, but I just—" Tiana waved her hands, trying to explain it. "Serra is giving me the knowledge of where things are supposed to go. I can see how everything is supposed to work." "If Serra is giving you that knowledge, then it's an official angel skill," Arvad said. Tiana wasn't sure why she wanted to argue the point. It might be some inborn loyalty to the Great Machine, destroyed though it was. "But that's not my purpose." "What is your purpose?" "I was supposed to guard a great machine, but it was destroyed before I got there. I was born too late. The church doesn't know what to do with me now. Watching over the Powerstone was my first real mission." Arvad nodded toward the #emph[Weatherlight] . "That's a great machine." Tiana sighed in exasperation. "But it's also not my assignment. Serra is giving me the knowledge to help rebuild it, but the #emph[Weatherlight] is not my reason for existence." "Just because your original reason for existence was destroyed doesn't mean you can't get another one. Believe me." He saw she was uncomfortable with the conversation and changed the subject. "Perhaps when Jhoira returns, I can offer her my service." He looked at her, his expression grave. "You should too." Tiana didn't respond. In a month or so the #emph[Weatherlight] would be ready to fly again. Could she let it fly without her? #emph[You'll have to] , she told herself. She was an angel, and joining Jhoira's crew wasn't her purpose. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The long hot days went past, the work continued, and Arvad didn't eat anybody, though the Powerstone hadn't cured him yet. Tiana was starting to think he might really mean to stay until Jhoira returned so he could ask to join her crew. She was bracing herself not to be jealous if Jhoira agreed. Arvad deserved a chance. Then one afternoon she was up on deck with Hadi talking about the final engine test when she caught a flash of light in the distance. She stepped up to balance on the railing. Alarmed, Hadi followed her gaze. "Was that the volcano?" he said. "No. No, it's worse." Tiana raised her voice and sang the alarm. "Everyone, run! Take cover in the rocks!"#linebreak   #figure(image("004_Return to Dominaria: Episode 4/06.jpg", width: 100%), caption: [Art by Daarken], supplement: none, numbering: none) Streaking toward them from the mountains was a phoenix. A huge raptor, its wingspan several times the size of Tiana's, its entire body engulfed in flames. #emph[It's going to burn the Weatherlight] , Tiana thought, and a rage filled her, as pure and burning as Serra's holy light. #emph[Never, never.] Not while there was breath left in her body. She leapt into the air, barely conscious of Hadi swinging down the scaffold, of the work crew scrambling out of their tents and calling out in alarm. As the phoenix swooped in, Tiana readied her spear and darted up toward its chest. At the last instant, it rolled down and under her. Its clawed feet struck at her. Heat washed over her and burning pain ripped across her shoulder and knocked her down and almost out of the air. She flapped her wings to recover and circled back in. But the phoenix took the opportunity to dive low over the camp and set the tents on fire. Tiana shouted in fury and dove down to fling her spear at its back. Its wing slammed up and hit her, and Tiana's own wings fouled. She fell, hit a rock, and bounced off. She slid down a gravel slope and struggled to her feet, untangling her wings. Her spear was a melted lump. Terror freezing her heart, she twisted around to see the #emph[Weatherlight] . The phoenix dove on the vulnerable skyship and there was no way she could get there in time— Then the phoenix jerked, knocked off its course by an arrow slamming into its neck. It burnt the arrow out of its body with a twitch of its fire feathers, but another took its place, then another. Tiana scrambled back to the top of the rock and saw Arvad on the ground near the skyship. He had a longbow and was just letting fly another arrow. Tiana drew her sword and held it up, and prayed for the sacred magic of the Church of Serra. Instantly she felt the divine power flow through it to her hand. She snapped her wings out and jumped off the rocks, then caught the air again and angled upward. As Arvad's next arrow struck the phoenix, Tiana shot up into the fire and drove her sword in right under its breastbone. The creature shrieked and twisted in midair. Determined to keep it from falling on the #emph[Weatherlight] , Tiana shoved it toward the beach. She kept pushing until her skin started to singe and the primal fear of burning her wings off made her disengage. Flapping to stay aloft, she watched the phoenix tumble, try to right itself, then fall into the waves in a broken heap. Tiana turned back toward the shore and it occurred to her that her clothes and possibly her hair were actually on fire. She landed on the packed dirt near the camp and Farim dashed up and threw a bucket of water at her. She sputtered, water dripping down her face. Arvad threw a wet blanket over her wings and asked urgently, "Are you all right?" Now that the fire was out, Tiana could tell the damage was superficial, and angels healed quickly. "I'll be fine." She saw Arvad looked singed, too, and his tabard had clearly been on fire at one point. "You?" "Arvad saved us," Tien said, still breathing hard. She pointed toward the smoking ruin of a tent. "He lifted the canvas so we could get out. And he saved the #emph[Weatherlight] . I think he saved you, too." There were a lot of things Arvad could have done, with Tiana dead and the camp in chaos. Fed on the workers fleeing the camp or stolen the Powerstone and run off with it. Instead he had acted exactly how a Benalish knight should. And Tiana had acted exactly like a guardian angel. The #emph[Weatherlight] 's guardian angel. The thought of the skyship being destroyed had almost destroyed her. She knew now she would defend it to the death. #emph[Is this what you want, Serra?] Tiana asked, but there was no answer. Maybe because she already had her answer, when Serra had empowered her sword with enough force to kill the phoenix in one blow. When Jhoira returned, Tiana would offer to serve her as crew on the #emph[Weatherlight] . It wasn't the purpose she had been born for, but it was the one she wanted more than anything.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/hyphenate-02.typ
typst
Other
// Hyphenate between shape runs. #set page(width: 80pt) #set text(hyphenate: true) It's a #emph[Tree]beard.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/cancel_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Display #set page(width: auto) $ a + b + cancel(b + c) - cancel(b) - cancel(c) - 5 + cancel(6) - cancel(6) $ $ e + (a dot.c cancel((b + c + d)))/(cancel(b + c + d)) $
https://github.com/SkytAsul/INSA-Typst-Template
https://raw.githubusercontent.com/SkytAsul/INSA-Typst-Template/main/insa-template/document-template.typ
typst
MIT License
// CONSTANTS: #let heading-fonts = ("League Spartan", "Arial", "Liberation Sans") #let normal-fonts = ("Source Serif", "Source Serif 4", "Georgia") // TOOLS: #let insa-translate(translations, key, lang, placeholders: (:)) = { let key-translations = translations.at(key) let string if lang in key-translations { string = key-translations.at(lang) } else { string = key-translations.at("fr") } for (p-key, p-val) in placeholders.pairs() { string = string.replace("{" + p-key + "}", p-val) } string } // FULL DOCUMENT: #let insa-document( cover-type, cover-top-left: [], cover-middle-left: [], cover-bottom-right: [], back-cover: [], page-header: none, page-footer: none, include-back-cover: true, insa: "rennes", lang: "fr", metadata-title: none, metadata-authors: (), metadata-date: auto, doc ) = { set document(author: metadata-authors, date: metadata-date, title: metadata-title) set text(lang: lang, font: heading-fonts) set page("a4", margin: 0cm) set par(justify: false) // only for the cover let back-page let supported-insas = ("rennes", "hdf") assert(supported-insas.contains(insa), message: "Only INSAs " + supported-insas.join(" ") + " are supported for now.") if cover-type == "light" { back-page = page(footer: none, header: none, margin: 0cm, image("assets/"+insa+"/back-cover2.png", width: 101%)) // image place(image("assets/"+insa+"/front-cover1.png", width: 100%)) // top-left place( dx: 2.5cm, dy: 6.5cm, block( width: 9.5cm, text(size: 18pt, cover-top-left) ) ) // middle-left place( dx: 2.5cm, dy: 13.7cm, block( width: 6.5cm, height: 7cm, align(horizon, text(size: 16pt, cover-middle-left)) ) ) // bottom-right place( dx: 9.5cm, dy: 25.5cm, box( width: 8.5cm, text(size: 24pt, cover-bottom-right) ) ) if back-cover != [] { panic("back-cover has content but is incompatible with this cover-type") } } else if cover-type == "colored" { back-page = page(footer: none, header: none, margin: 0cm, image("assets/"+insa+"/back-cover2.png", width: 101%)) // image place(image("assets/"+insa+"/front-cover3.png", width: 100%)) // top-left place( dx: 2.5cm, dy: 7.5cm, block( width: 9.5cm, text(size: 20pt, fill: white, cover-top-left) ) ) if cover-middle-left != [] { panic("cover-middle-left has content but is incompatible with this cover-type") } if cover-bottom-right != [] { panic("cover-bottom-right has content but is incompatible with this cover-type") } if back-cover != [] { panic("back-cover has content but is incompatible with this cover-type") } } else if cover-type == "pfe" { back-page = page(footer: none, header: none, margin: 0cm)[ #place(image("assets/"+insa+"/back-cover1.png", width: 100%)) #place(dx: 1cm, dy: 1.2cm, block(width: 18.5cm, height: 19.6cm, back-cover)) ] // image place(image("assets/"+insa+"/front-cover2.png", width: 100%)) // top-left place( dx: 2.5cm, dy: 6.5cm, block( width: 9.5cm, text(size: 18pt, cover-top-left) ) ) // middle-left place( dx: 2.5cm, dy: 13.7cm, block( width: 9.5cm, height: 14cm, align(horizon, text(size: 16pt, cover-middle-left)) ) ) // bottom-right place( dx: 12.3cm, dy: 25.5cm, box( width: 7.5cm, text(size: 20pt, cover-bottom-right) ) ) } else { panic("Unknown cover-type: only 'light', 'colored' and 'pfe' available.") } counter(page).update(0) set page( "a4", margin: (x: 1.75cm, y: 2.5cm), footer: context { place( right + bottom, dx: page.margin.at("right") - 0.6cm, dy: -0.6cm, box(width: 2.34cm, height: 2.34cm, image("assets/footer.png")) ) if counter(page).get().at(0) > 0 { place( right + bottom, dx: page.margin.at("right") - 0.6cm, dy: -0.6cm, box(width: 1.15cm, height: 1.15cm, align(center + horizon, text(fill: white, size: 14pt, font: heading-fonts, weight: "bold", counter(page).display()))) ) } page-footer }, header: { if page-header == none { image("assets/"+insa+"/logo.png", width: 4.68cm) } else if page-header != [] { page-header line(length: 100%) } } ) show heading: set text(font: heading-fonts, weight: "bold") set text(font: normal-fonts, weight: "regular") set par(justify: true, first-line-indent: 1em) set figure(numbering: "1") set outline(indent: auto) show figure.where(kind: image): set figure(supplement: "Figure") // par défaut, Typst affiche "Fig." show figure.caption: it => [ #text(weight: "bold")[ #it.supplement #context it.counter.display(it.numbering) : ] #it.body ] doc if (include-back-cover) { back-page } } // REPORT DOCUMENT: #let insa-report( id: 1, pre-title: none, title : none, authors: [], date: none, insa: "rennes", lang: "fr", doc, ) = insa-document( "light", cover-middle-left: authors, cover-top-left: [ #set text(size: 28pt, weight: "bold") #if pre-title != none [ #pre-title #sym.hyph ] TP #id\ #set text(size: 22pt, weight: "medium") #smallcaps(title) ], page-header: [ TP #id #sym.hyph #smallcaps(title) #h(1fr) #if type(date) == datetime { date.display("[day]/[month]/[year]") } else { date } ], include-back-cover: false, lang: lang, insa: insa, metadata-title: title, metadata-date: if type(date) == datetime {date} else {auto}, { set math.equation(numbering: "(1)") set text(hyphenate: false) set heading(numbering: "I.1.") set par(first-line-indent: 0em) show heading.where(level: 1): it => { set text(18pt) upper(it) // Do not use the `smallcaps` function until Typst implements a fallback in the case the font does not provide smcp capability. } show raw.where(block: true): it => block(stroke: 0.5pt + black, inset: 5pt, width: 100%, it) show raw.line: it => if it.count > 1{ text(fill: luma(150), str(it.number)) + h(2em) + it.body } else {it} doc } ) // STAGE DOCUMENT: #let insa-stage-translations = ( "title": ("fr": "Stage présenté par", "en": "Internship presented by"), "student": ("fr": "Élève-ingénieur{gender-suffix} de l'INSA Rennes", "en": "INSA Rennes Engineering Student"), "department": ("fr": "Spécialité {department}", "en": "Department {department}"), "location": ("fr": "Lieu du Stage", "en": "Stage Location"), "company-tutor": ("fr": "Maître de Stage", "en": "Training supervisor"), "insa-tutor": ("fr": "Correspondant{gender-suffix} pédagogique INSA", "en": "Academic supervisor (INSA)"), "thanks-heading": ("fr": "Remerciements", "en": "Special Thanks") ) #let insa-stage-translate(key, lang, placeholders: (:)) = insa-translate(insa-stage-translations, key, lang, placeholders: placeholders) #let insa-stage( name, department, year, title, company, company-logo, company-tutor, insa-tutor, insa-tutor-suffix: "", summary-french, summary-english, student-suffix: "", thanks-page: none, omit-outline: false, // can be used to have more control over how the outline is shown insa: "rennes", lang: "fr", doc ) = insa-document( "pfe", cover-top-left: [ #text(size: 17pt, font: normal-fonts, insa-stage-translate("title", lang))\ #text(size: 21pt, font: heading-fonts, weight: "bold", name)\ #text(size: 17pt, font: normal-fonts)[ #insa-stage-translate("student", lang, placeholders: ("gender-suffix": student-suffix))\ #insa-stage-translate("department", lang, placeholders: ("department": department))\ #year ] ], cover-middle-left: [ #text(size: 17pt, upper(title)) #set text(size: 15pt, font: normal-fonts) *#insa-stage-translate("location", lang)*\ #company *#insa-stage-translate("company-tutor", lang)*\ #company-tutor *#insa-stage-translate("insa-tutor", lang, placeholders: ("gender-suffix": insa-tutor-suffix))*\ #insa-tutor ], cover-bottom-right: company-logo, insa : insa, page-header: [], back-cover: { set text(font: normal-fonts, size: 14pt) place(dx: -.2cm, dy: 3.5cm, block(width: 8.9cm, height: 16cm, summary-french)) place(dx: 9.2cm, block(width: 9.3cm, height: 16cm, inset: 0.2cm, summary-english)) }, lang: lang, metadata-title: title, metadata-authors: (name,), { set heading(numbering: "1.1 ") show heading.where(level: 1): it => text(size: 18pt, upper(it)) show heading.where(level: 2): set text(size: 16pt) show heading.where(level: 3): set text(size: 15pt) show heading.where(level: 4): set text(size: 14pt) if thanks-page != none and thanks-page != [] { counter(page).update(0) heading(insa-stage-translate("thanks-heading", lang), numbering: none, outlined: false) thanks-page pagebreak() } if not omit-outline { counter(page).update(0) show outline: set heading(outlined: false) outline() pagebreak() } doc } )
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/09-layout/bidi-unembedded.typ
typst
Other
#import "/lib/draw.typ": * #import "/template/lang.typ": arabic, greek #let start = (0, 0) #let end = (1000, 100) #let example = [ A quote from Wikipedia: "#arabic[تعود أصل الكلمة إلى الإغريقية: #greek[δηνάριον] (ديناريوس).]" ] #let make-arrow = ux => arrow.with( stroke: 2 * ux + gray.darken(30%), head-scale: 5, ) #let positions = ( 20, 380, 710, 845, 990, ) #let graph = with-unit((ux, uy) => { // mesh(start, end, (100, 20), stroke: 1 * ux + gray) txt(example, (20, 20), size: 30 * ux, anchor: "lb") let arrow = make-arrow(ux) let ltr = ( true, false, true, false, ) let level = 0 for (dir, (from, to)) in ltr.zip(positions.zip(positions.slice(1))) { if dir { arrow((from + 4, 60), (to - 4, 60)) txt([从左向右(0级)], (from + 4, 60), size: 20 * ux, anchor: "lb", dy: 10) } else { arrow((to - 4, 60), (from + 4, 60)) txt([从右向左(1级)], (to - 4, 60), size: 20 * ux, anchor: "rb", dy: 10) } } }) #canvas(end, start: start, width: 100%, graph)
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap2/chap2.typ
typst
Other
== Ohm's Law #include "1_voltage_current_resistance_relation.typ" #include "2_analogy_for_ohms_law.typ" #include "3_power_in_electric_circuits.typ" #include "4_calculating_electric_power.typ" #include "5_resistors.typ" #include "6_nonlinear_conduction.typ" #include "7_circuit_wiring.typ" #include "8_polarity_of_voltage_drops.typ" #include "9_computer_simulation_of_electric_circuits.typ"
https://github.com/danilasar/conspectuses-3sem
https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/Ассемблер/240913.typ
typst
В следующую пятницу вместо ассемблера будет дискра. Про ассемблер спросить у умных людей. Существует 6 сегментных регистров, которые содержат в себе старшие 4 цифры адреса начала сегмента. Адрес начала сегмента кода --- cs. *Адрес начала сегмента стека* система автоматически загружает в начало *ss*, регистр *sp* указывает *на вершину стека* и при добавлении элемента в стек содержимое регистра sp уменьшается. Это значит, что стек растёт вниз головой: значение адреса уменьшается от максимального. Чтобы в стеке хранить и фактические параметры, и локальные, после загрузки фактических параметров содержимое регистра sp сохраняется в регистре bp (base pointer) и тогда к фактическим параметрам можно обращаться с помощью выражения bp+k, а к локальным параметрам bp-n, где k и n вычисляет сам программист, зная количество и размер параметров. Ещё один регистр *ip* (*eip*) называется *счётчиком* или *указателем команд*, в нём хранится смещение следующей исполняемой команды. Регистр флагов определяет состояние программ и процессора в каждый текущий момент времени. Мы будем изучать ривервиальный режим работы, поэтому нас интересуют не все флажки. 1, 3, 5 и с 15 по 31 для 32-разрядных ассемблеров не используются. Следующие флажки используются и в реальном, и в защищённом режиме: - CF --- флажок переноса устанавливается в единицу, если в результате выполнения операций (например, сложения) произошёл перенос из старшего разряда, а при вычитании --- заём. 0FFH + 1 = F00, а CF = 1. - BF --- флажок чётности устанавливается в единицу, если в младшем байте результата окажется чётное число единиц. Используется при проверке правильности работы ОЗУ. - AF --- флажок полупереноса устанавливается в единицу, если при сложении произошёл перенос из четвёртого разряда в третий, а при вычитании требовался заём. - ZF --- флажок нуля (zero flag) устанавливается в единицу, если все разряды результата окажутся равными нулю. - SF --- флажок знака (sign flag) всегда равен содержимому знакового разряда ($0 <=> +, 1 <=> -$). - TF --- флажок трассировки, установленный программистом в единицу, переводит процессор в режим пошаговой отладки программы. - IF --- флажок прерывания (interrupt flag), установленный программистом в ноль, заставляет процессор перестать обрабатывать прерывания от внешних устройств. Такое делают только для выполнения критических участков программ, это происходит весьма редко. - DF --- флажок направления определяет направление обработки строковых данных. Сброшенный программистом в 0, определяет обработку строк от младших адресов к старшим (слева направо). Установленный в 1, определяет обработку строк от старших адресов к младшим (справа налево). При этом автоматически изменяется содержимое регистра указателей si и di. Содержимое этих регистров или увеличивается, если df равен нулю, или уменьшается, если df равен единице, на размер операнда. - OF --- флажок переполнения (overflow flag) устанавливается в единицу, если результат превышает максимально допустимый для данной разрядной сетки Следующие флаги используются в защищённом режиме: - IOPL --- флажок привелегий ввода-вывода - NT --- флажок вложенной задачи - NF --- флажок маскирования прерываний - VM --- флажок виртуальных машин - VC --- флажок выравнивания операнда - флажок вложенных задач - RF --- флажок маскирования прерываний Флаги за редким исключением устанавливаются автоматически. == Оперативная память 32-разрядный процессор может работать с оперативной памятью размером до 4ГБ с адресами от нуля до $2^(32 - 1)$, что в шестнадцатеричной системе будет 00000000-FFFFFFFF. Байты памяти могут определяться в поля переменной и фиксированной длины. Адресом начала поля является адрес младшего входящего в поле байта, длина поля --- количество входящих в него байтов. Поля фиксированной длины имеют собственные имена, слово состоит из двух байтов, двойное слово --- из четырёх байтов. Адресом поля переменной длины может быть любой адрес. Реальный физический адрес байта состоит из двух частей: адрес начала сегмента и исполняемый адрес (смещение). Смещение формируется в команде и зависит от способа адресации операнда. В защищённом режиме программа может определить до 16 383 сегментов размером до 4ГБ и таким образом использовать до 64ТБ виртуальной памяти. В реальном режиме, как мы уже сказали, адрес сегмента кратен 16 и 4 старшие 16-ричные цифры содержатся в сегментном регистре. А чтобы получить 20-разрядный физический адрес байта, нужно сместить содержимое сегментного регистра на 4 разряда влево и прибавить 16-разрядное смещение. Про кеш-память можно почитать по адресу: https://market.marvel.ru/blog/komplektuyushchie-i-optsii/kesh-pamyat-kompjutera == Форматы данных Процессор вместе с сопроцессором могут обрабатывать большой набор данных. Числа целые без знака, целые со знаком, действительные с плавающей точкой, двоично-десятичные числа, символы, строки и указатели. === Целое число Целое число без знака может занимать байт, слово или двойное слово и изменяться в диапазоне от нуля до 255, от нуля до 65535. Двойное слово --- до 4294967295 соответственно. Целое число со знаком также может занимать байт, слово или двойное слово и представляется в дополнительном коде. 7(15,31) Обратный код числа $m$ равен $10^n - m$, где $n$ --- разрядность числа. / Вычитание в машине: дополнительный код вычитаемого прибавляется к уменьшаемому. / ДЗ: Дома сделать 65 - 42 = 23 === Число с плавающей точкой Числа с плавающей точкой могут занимать 32 разряда, 64 или 80 разрядов. 32 разряда --- короткое вещественное, 64 --- длинное вещественное, 80 --- рабочее вещественное. #image("image.png") Старшая единица, нормализованная мантиссоей, в разрядную сетку не записывается для экономии памяти. + Нормализуем число: $0.B F 4*10^3$ + Получаем машинный порядок: $3_16 + 7F_16 = 82_16$ + Запишем число в двоичной системе счисления: \ $0.1000 & 0010 & 011 & 1111 & 0100 & 0000 & 0000 & 0000$ Процессором могут обрабатываться 8-разрядные в упакованном и неупракованном формате, сопроцессором --- 80-разрядные в упакованном формате. / Упакованный формат: две цифры в байте / Неупакованный формат: одна цифра в цифровой части файла === Символы, строки, указатели Символы представляются в коде ASCII, каждому символу отводится один байт. / Строки: последовательности байтов, слов или двойных слов. / Указатели: адреса байтов. Существует длинный указатель (16+32 разрядов, где 16 --- селектор (адрес сегмента) и 32 --- адрес смещения в сегменте) и короткий (32 разряда смещения). == Форматы команд Команды как машинные команды --- цифровой двоичный код, состоящий из двух последовательностей, определяющий операционную часть (код операции: что нужно сделать) и адресную часть (где взять операнды и куда записать результат). Процессор, который мы рассматриваем, может работать с безадресными командами, с одноадресными, двухадресными и трёхадресными командами. Данные, участвующие в операции, могут находиться непосредственно в команде, могут содержаться в регистрах или оперативной памяти. В зависимости от кода операции количество операндов и их размещение, команда операции в памяти процессора может занимать от одного до 15 байтов. Наиболее частоиспользуемыми являются двухадресные команды, их формат записывают таким образом: - R-R (регистр-регистр) - R-M (регистр-память) - M-M (память-память) - M-R (регистр-регистр) - R-D (регистр-данные) - M-D (память данные) Исполняемый адрес может состоять из трёх частей: база, индекс и смещение. Базовый регистр bs, регистр si... Существуют различные способы адресации операндов (мы будем использовать 7): - Регистровая. - Непосредственная - Прямая - Косвенно-регистровая - По базе с индексированием - По
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/009%20-%20Born%20of%20the%20Gods/009_Seasons%20in%20Setessa.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Seasons in Setessa", set_name: "Born of the Gods", story_date: datetime(day: 26, month: 03, year: 2014), author: "<NAME>", doc ) #emph["Better to kiss a snake than fight a Setessan."] —Akroan saying === A Summer Throughout the forest, the children came. Some came in large clumps—raucous groups that shrieked and ran, ignoring their adult shepherds. Others came in small groups of two or three, quieter, watchful, with no one to shepherd them but each other, and so they did. Still others came alone, with no one to watch out for them at all. So many children. More than Cilissa had ever seen in one place. There had been one time, a few months before the attack, when she had played all day with the other village children during the planting festival. There had been seventeen children, a number Cilissa remembered with pride because she had been able to count them herself. The first thing she told her parents that night was not about the races she had won but how she had counted to seventeen. She realized she was crying again, and she was very angry at herself. She was determined she would not cry again, that she was going to dry up all the tears in her body. It wasn’t fair for her body to cry even though she wasn’t thinking about crying. She forced the tears to go away, and she told herself, #emph[no more tears.I mean it, body. No more crying] . They were in a part of the forest Cilissa had never seen before. The normally dense forest was giving way to sparser olive trees, their thick and gnarled trunks showing how old they were. These olive trees were very, very old. Despite the thinning canopy, the forest was no lighter. A wispy mist floated among the trees, and when Cilissa looked up she could still not see the sun or the sky. Cilissa did not feel afraid, though. She had not felt afraid at any time since coming to Setessa a few days before. She thought perhaps she had used up all her fear during the attack and her wanderings afterward. #emph[Maybe everyone can only feel afraid a certain amount of time in their life, and I used mine up already.] It made her happy to think she wouldn’t feel afraid again. The mist above thickened and spread. Overhead was all fog, although she could still see plenty of children around her. Ahead was a large circular clearing, enclosed by the thickest and largest olive trees Cilissa had ever seen. There must have been hundreds of children already sitting in the clearing, and yet they still only took up a fraction of the space. Many more children were streaming into the clearing, although as they entered they stopped and looked up at the forest ceiling. As Cilissa walked through the ring of olive trees she immediately knew something was different even before she looked up. Her body and scalp tingled, like a pail of cold water being splashed over her. She looked up, expecting to see the same dense fog, but was instead confronted by a dense night sky with thousands of dots of tiny lights. It was beautiful. #emph[Nyx.] The home of the gods. #figure(image("009_Seasons in Setessa/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) Cilissa took a step back out of the clearing. And she was again in the fog-shrouded daytime, nary a star or dark sky in sight. And a certain #emph[presence] was gone as well. She stepped forward into the clearing, and there was the same tingle, and it was now the dark of night, although illuminated quite well by the starry field above. She realized the children around her were sitting, and so she sat as well. Up ahead, a tall woman strode to the center of the clearing. She carried a bow slung over her back, with a small axe and long knife sheathed at her sides. And she held a long spear upright in one hand. Loosely armored in dark leather and cloth, she moved with a strength and precision Cilissa had never seen in anyone, warrior or no. Cilissa decided she wanted to move like that more than anything, more than anything else in the world, with only one exception. She slapped at her eyes before the tears could begin again. #emph[I’m on to you, body. I know your tricks.] The tall woman, her auburn hair tied up in a topknot, reached the center of the circle and waited. Although she spoke no words, somehow every laugh, every cry, every shout or whisper, all quieted to stillness. The children sat silently and waited. The woman’s voice carried loudly throughout the clearing, her voice amplified through some unknown means. "Welcome, <NAME>. You are safe here." Although she was sitting in a dark forest under a magical night sky surrounded by strangers, Cilissa believed her. Ever since arriving in Setessa, she had been treated with kindness. She had been fed, been washed, been touched by gentle hands. While no adult had taken charge of her, there was always one around, always female. There had been no orders, no chores, just food and sleeping and not-thinking. Cilissa had worked really hard on the not-thinking. That had been her life for the previous few days until that morning, when she saw the adults preparing to go somewhere, and she saw everyone else following, so she followed, too. The woman’s voice continued, "You are here from across the land. From cities and villages, from plains and hills, from battles and from slums and from worse." Worse than a battle? Cilissa did not understand how that could be true. #emph[No, body, no, I’m stronger than you.] "But that is now behind you. You are here because your parents are gone. It does not matter why they are gone, but they are gone and they are not coming back." The silence in the crowd broke. Sobs and cries and screams erupted in the night air. Cilissa was proud of herself that she did not join them. #emph[I am done with tears. I am. I really am. I am six years old and I am too old for crying.] The woman in the center of the circle did not speak. She did not shush nor point a finger. She didn’t even look annoyed, the way some adults do when children are making noise. She just stood there. The stars above her head twinkled and some of them moved in various patterns and shapes, although the shapes quickly broke apart. No arrangement lasted for long, but the stars kept moving, and Cilissa felt strangely calm as she watched the stars dance. Eventually, the cries and sobs subsided. When silence had resumed, the woman spoke again. "In Setessa, we call you #emph[arkulli] , little bears. Like little bear cubs, now you are small. You need food, and shelter, and protection, and teaching. This we will give you. But one day, #emph[arkulli] , one day you will be big. One day you will be mighty. One day you will not need Setessa’s protection, but Setessa will need yours." As the woman’s voice resonated throughout the clearing, Cilissa looked up at the portal to Nyx, and the stars there took the shape of a large bear, tall and majestic and strong. Cilissa felt so #emph[strong] , looking at the bear. If she was as mighty as that bear, she could have saved her village. She could have saved her parents. Cilissa was sure that bear had never felt afraid, had never cried. "Welcome, #emph[arkulli] . From now on, you are Setessan. Setessa welcomes you home. Karametra welcomes you home." With the mention of the god’s name, the stars shimmered, and the bear form above dissolved. In its place the stars moved into the shape of a face, a woman’s face, the most wonderful face Cilissa had ever seen, the face of the god Karametra. Cilissa could not describe that face except she knew it was a face of warmth and love. The face was looking at her, and only her, and the god’s eyes held Cilissa’s eyes as the face seemed to grow out from the starfield above, grow out and down until that face enveloped the whole of the clearing, surrounding each and every child, but Cilissa most of all. #emph[You are loved, child] , a voice whispered to her, as the face dissolved in a shimmering display of warm sparks that kissed her face and body like soft dandelions brushing against the skin. #figure(image("009_Seasons in Setessa/04.jpg", width: 100%), caption: [Karametra, God of Harvests | Art by <NAME>], supplement: none, numbering: none) Where the sparks fell to the ground and vanished, a small seedling sprouted from the earth and grew quickly. Within seconds, fibrous pods, thick-shelled husks about the size of Cilissa’s fist, dotted the clearing. Each pod pulsed with a soft green glow. Cilissa picked up one of the pods and she felt the same warmth she had from the sparks. Memories rose, unbidden and unwanted. Her father falling to the first wave of Akroan attackers. His last shout becoming a scream. Her mother whispering at her,#emph[ Run, Cilissa, run, your fastest running. Go now my love, now ] . And then her mother turned to rush at the soldiers, screaming. But Cilissa didn’t see what happened to her mother, because she #emph[ran] . She ran and ran, out of the village. She had always been so fast, and never faster than that day. She had run and left everything behind. Her village, her friends, her parents, everything but the crying. She couldn’t leave the crying behind. She was crying now, hugging the pod with its gentle green glow fiercely to her chest, hugging and rocking back and forth and sobbing. The pod felt so good, so gentle. Cilissa did not stop crying, thinking about her mother and her father and how much she loved them. But for the first time since the attack, she smiled. She smiled and cried all at the same time. She hugged the pod and was grateful to finally be home. === A Fall #emph[Thwack, thwack, thwack] bounced off the stone bricks of the tall limestone tower and rebounded through the courtyard below. The steady stream of #emph[thwacks] created enough background noise to make conversation difficult, but no one in the courtyard was interested in conversation. They faced off against one another, their faces beaded with sweat and concentration on their opponents, the wooden staves in their hands whirling and lashing and #emph[thwacking] against each other. No one was interested in conversation, that is, except for the person across from Cilissa. Thora was tall, strong, and fast. She was one of the girls in their group who had recently turned ten, and immediately sprouted several inches. And she liked to talk. "You’re too slow." #emph[Thwack, thwack] . "Are you sure you even belong here?" #emph[Thwack, thwack] . "You know we #emph[are] here to fight, right?" #emph[Thwack,thwack, thwack.] Cilissa stayed silent. The problem wasn’t that Thora was almost a full year older; everyone in their group was within a year of each other and they had been taught age was irrelevant in the respect accorded your peers. #emph[Thwack, thwack.] And the problem wasn’t that Thora was right with her insults. Despite Thora’s height and strength, Cilissa was better and faster, and she, and Thora, and everyone else knew it. #emph[Thwack, thwack.] Thora was no closer to landing a blow or tripping Cilissa’s legs then than when they had started their sparring. The problem was Cilissa was no closer to landing a blow, either. She met every swing from Thora, the staff feeling light and alive in her hands. But she took no opportunity to counter. And combatants were supposed to keep sparring until one landed a decisive blow. And if Thora couldn’t land a blow, and Cilissa wouldn’t, then they could be there a very long time. "Are you afraid? Are you a coward?" #emph[Thwack, thwack.] Cilissa’s lips thinned, but she still said nothing. Cilissa noticed Thora wasn’t even angry; she was breathing regularly, and her calm face and eyes belied her cruel words. She was being insulting as a #emph[strategy] . This upset Cilissa in a way even Thora’s words had not, but she focused on meeting each swing and thrust. As focused on Thora’s staff as she was, she was unprepared when Thora rushed her, body to body, her larger body bulling Cilissa backwards. Cilissa tensed her legs, preparing a backwards flip, but Thora swung her staff low, clipping Cilissa between the knees and sending her sprawling to the ground. "Hah, I win." Thora’s smile hurt most of all. It was drilled into the children that practice and learning were more important than winning, but they were also trained to be competitive. Thora lingered for a moment, body slightly leaning on her staff, looking down at Cilissa before picking up her staff to find another opponent. The other children stopped their sparring to look at Cilissa. She hadn’t lost a match in a long time. Cilissa couldn’t meet the stares of the other children, so she looked down instead. Leaves covered the ground outside of the sparring area. The Nessian Wood often offered a full panoply of autumnal coloring, and this fall was no exception. Brilliant orange and rich brown leaves cloaked the trees and ground alike. Fall was one of her favorite times in Setessa, a combination of beautiful color and emerging stillness. Looking at the leaves was easier than looking anywhere else, so she continued to study them amid the steady background sounds of #emph[thwack, thwack, thwack] until a pair of shoes blocked her sight. #figure(image("009_Seasons in Setessa/06.jpg", width: 100%), caption: [Forest | Art by <NAME>], supplement: none, numbering: none) Cilissa followed the green shoes up to a pair of leather leggings, following up and up a body leading to a face. The face neither smiled nor frowned, but merely looked back at Cilissa. And although the woman’s hair was succumbing to gray and her face held more wrinkles each time Cilissa saw her, it was normally a kind face, although at that moment it was hard to tell. It was the face of Niketa, weaponsmaster and archer, and the head trainer of their lessons at the time. "Is it a game to you, Child?" Niketa’s voice was clipped, although not harsh in the way she was when she thought a student was being particularly dense or obstinate. Cilissa looked around and saw the other children resuming their sparring, although they gave wide clearance to Niketa and Cilissa. Thora was off in the distance, bruising a poor boy who did not have a chance. "No," she said softly, looking at Niketa. "Are you sure? You seemed content to play at the game of staves. Your turn, no, your turn, no, your turn." Cilissa didn’t know what to say to that, so she didn’t say anything. She kept her eyes on Niketa. "I have seen many warriors over the years, Cilissa. Many have been stronger than you. Few faster, but some. You do not bear special gifts from the gods. And warriors stronger than you, and faster than you, they have died. Died to mistakes, or died to opponents who were slower and weaker. Do you know why?" Cilissa shook her head. "Stand up with your staff." Cilissa readied herself, as Niketa picked up a training staff. "Begin." Cilissa waited for Niketa to make the first move. #emph[Thwack, thwack.] "Thora is an aggressive combatant, one of the most aggressive in your group. It serves her well, mostly." As Niketa talked, the speed of her thrusts and swings increased, faster than Cilissa had yet fought against. She focused on meeting Niketa’s staff, determined to be fast enough to ward off harm. #emph[Thwack, thwack, thwack.] Niketa’s staff had slipped through Cilissa’s defense and only at the last possible moment had slowed to deliver no more than a stinging blow against Cilissa’s shoulder. "You will never be fast enough, child, to stop all blows. Fighting well is not a function of speed. Do you ever attack, Child?" All of the embarrassment and hurt of the day came rushing up in Cilissa, unbidden. For so much of her sparring she held herself back, unwilling to hurt another child, another human being. With a cry, she lashed out at Niketa, her staff a blur. She pictured Thora, those lips curled up in a sneer, as she unleashed one furious blow after another at Niketa. Niketa met Cilissa’s onslaught, but took a step back. And then another. And then a third. All the other children stopped their sparring and turned to watch. Cilissa had never felt this much anger before, and it felt wonderful. It felt like freedom. The world seemed remarkably clear without care or consideration for the harm she could cause. She wanted to attack even faster. #emph[Thwackthwackthwack.] It was only when Niketa’s staff easily slipped past and knocked into her ribs that she realized how sloppy her defenses had become. She yelled out again and sought to regain her press. Niketa continued to speak, calmly, conversationally. "What do you fight with, Child?" Cilissa could barely think, much less speak, but there was another blow from Niketa, and with it the same question. "What do you fight with, Child?" "My staff! I fight with my staff!" Cilissa was breathing heavily now, and was no longer able to advance. There was another blow from Niketa. Each blow was light, but even a light blow from the staff hurt considerably. And the same awful question. "What do you fight with, Child?" "My bow. I fight with my bow." Niketa was the head archer, perhaps that was the answer she was looking for. #emph[Thwackthwackthwack.] The question again. "My body, I fight with my body." #emph[Thwackthwackthwack.] The question again. What more could she say? Cilissa could barely stand, and the next time Niketa’s staff hit her, she dropped to the ground. "Your #emph[mind] , Child. You do not fight with your staff or your bow or your body. You fight with your mind. Some philosophers think the purpose of battle training is so you don’t have to think while fighting. They are wrong. We train so that in combat you are able to think about the right things. Such as recognizing when your opponent is goading you into losing your composure. "Aggression serves Thora well, but not you, I think. That is fine. I know how to train smart warriors to be more aggressive. I do not know how to train aggressive warriors to be smart." Niketa leaned down and offered her hand to Cilissa. "You will learn, Child. But still, attack more, yes?" The two of them walked back to the tower amid orange and brown leaves, the crisp air, and the continued #emph[thwack, thwack, thwack] of children fighting with their minds. === A Winter A light white dust coated the bare branches and hard ground as Cilissa and Thora made their way on patrol through the southern edge of the forest. It had snowed no more than five times in all the years Cilissa had been in Setessa, and she found it delightful each time. While the snow wouldn’t usually last more than a day, she was always amazed at how completely it transformed the forest, as if they were walking in a strange and new country. They had been on their patrol for two hours. The southern edge of the Nessian Wood mostly consisted of scattered trees and hard rocky ground. Two days of travel farther south would bring one to the Despair Lands, a wasteland blighted by Erebos, but the southern border had been mostly quiet for many years—a good training ground for those new to patrolling. #figure(image("009_Seasons in Setessa/08.jpg", width: 100%), caption: [Warriors’ Lesson | Art by <NAME>], supplement: none, numbering: none) "There’s nothing out here. This is just a waste of time." Thora had been irritable all day. Their whole group had been tense, though, with all the changes and moving taking place. They had known that had been coming for some time, but it was different to actually confront losing so many people they had known for years. A branch snapped to the right and behind them, and Cilissa had an arrow nocked to her bow and aimed as Thora had a throwing axe in hand, the first smile on her face displayed all day. Both of them lowered their weapons as they saw the source of the sound. A strange look passed on Thora’s face. "Kelios," they said in unison, and Thora looked angrily at Cilissa, confusing Cilissa even more. "We could have killed you," said Cilissa. Thora interrupted with, "#emph[I] could have killed you. I don’t know what Cilissa would have done." Kelios, tall and gangly, his coordination completely outmatched by his recent growth spurt, approached with an awkward smile on his face. "I thought, I mean, I know you would be out this direction, and I’m, well, I wanted to say, well, I’m going, and…" Thora rushed over, dropping her axe and embracing Kelios in a hug. "I’m going to miss you so much!" Thora exclaimed as she continued to hug Kelios. Kelios said, "I’m going to miss you, too, Thora," but he looked at Cilissa the whole time he said it, that same strange smile on his face. Cilissa was aware she got more attention from people, especially boys, during the past year. It felt like overnight many boys stopped treating her as a friend and a fighting partner, and instead they just got… strange. Kelios was one of the more awkward ones. Cilissa tried to ignore the attention whenever possible. Kelios freed himself from Thora’s embrace and approached Cilissa. "I’m going to miss you, Cilissa." Cilissa tried to smile warmly, but made no attempt to hug Kelios. She had pointed her bow down, but still had the arrow in her other hand. "You too, Kelios. Do you know where you’ll be going?" Kelios looked down at his feet, doing a sort of awkward side-shuffle. Cilissa felt bad that everything Kelios did lately was awkward. "No, not yet. They won’t tell us until we begin our journey. It’s all a little…" his voice trailed off and he didn’t finish the sentence. When every boy turned fourteen, they were sent away on their peregrination, their journey into the outside world to find their path. Setessa believed strongly that whatever path helped turned young men into adults, that path did not include staying in Setessa. When Cilissa was young, she had barely noticed there were no adult men around longer than a day or two in Setessa, but for the previous year, as everyone approached their fourteenth birthday, the constant leave-taking of their male friends had obsessed nearly all of them. Cilissa was sad, but she was also glad to be rid of some of the awkwardness. Setessa’s policy began to make sense to her. "So I guess this is, um, goodbye, then?" As he said it, Kelios continued to look just at Cilissa, and Thora alternated between smiling at Kelios and glaring at Cilissa. Cilissa just wanted to be back on patrol. She said, "Goodbye, Kelios. I wish you well in your travels. Be safe." She turned around and walked back to the outer edge of the forest. She just wanted Kelios to stop staring at her and Thora to stop glaring at her. She figured maybe leaving the two of them alone would make Thora happier. #figure(image("009_Seasons in Setessa/10.jpg", width: 100%), caption: [Peregrination | Art by <NAME>], supplement: none, numbering: none) Just a minute later, she heard the crunching of Thora’s boots in the light snow. She turned, hoping her friend would be happier, but Thora’s eyes and cheeks were red, far redder than the cold air warranted. "What’s wrong?" "Please, Cilissa, just stop it. Stop it." The tears were flowing again for Thora. Cilissa had never seen Thora cry like this. "Thora, I… I didn’t do anything wrong." Cilissa knew that would not help her friend, but she was so confused about Thora’s anger toward her. "No, of course not. Perfect Cilissa. Perfect, passive Cilissa. You never do anything wrong, do you? You never do anything at all." Still crying, Thora turned and stalked away. "Wait!" Cilissa shouted, but Thora continued to walk off in the opposite direction, back toward their base camp. It was forbidden for patrol partners to leave each other alone except in the direst of emergencies, but Cilissa knew Thora would fight if she sought her out. She waited and watched as Thora’s figure retreated into the wintry forest, hoping she’d change her mind and come back, but no change of mind occurred. After a few more minutes of waiting, Cilissa turned and walked along the original path, thinking she might as well finish the patrol. She thought more about the peregrinations. When she first heard about them, she was horrified at the concept. She would have fought with all her being to avoid leaving. Eventually, she came to accept it was just something that happened to the boys; many girls used to joke that men were too weak to handle life in Setessa, but that seemed cruel to Cilissa when you actually had to say goodbye to your friends. Then, though, as Cilissa walked, she wondered if it would be so bad to leave Setessa. She had been there nearly her whole life, and she loved it. Except when she hated it. Sometimes, the thought of being somewhere else, seeing new people and new things, was so exciting to her that it hurt. Lost in thought, she almost didn’t notice the large green husk off in the distance. She realized the husk had no snow on it, unlike every other thing in the forest. She approached it cautiously, and then realized it was one of Karametra’s pods. During Karametra’s welcoming ceremony to new #emph[arkulli] , sometimes new pods would grow afterwards. The pods started off as shells about the size of a fist, with a thick husk that emanated a green, pulsing glow. Cilissa hadn’t known what the pods were when she was a child, and the adults refused to talk about them. Cilissa had a dim memory of her own welcoming ceremony, and there being hundreds of pods, but she couldn’t say what happened to them. All she knew was in the years after, she would see fewer and fewer pods, and the ones she did see were larger and larger. This pod was about the size of a man lying down, and it had gnarled, fibrous growths dotting its husk. Just being around one of the pods made Cilissa happier, although she didn’t know why. She had another dim memory of Karametra’s voice so many years before, but she had shared that memory with others early on, and they had always laughed at her or teased her. Her teachers were clear Karametra rarely talked directly with Setessans, and Cilissa had dropped the matter, thinking she had just imagined it. But even so, she felt lighter and happier as she reached out to touch the pod. It felt warm to the touch, but not hot, and a soft green glow began to pulse from the pod. Cilissa realized she was tired, and she sat down next to pod, lying across it, grateful for the warmth after such a long, cold day. She thought about her parents, which was strange because she hadn’t thought about them in many years. She could barely remember the face of either, and there were times she had tried so hard to recall their faces that afterwards she couldn’t remember them at all, like she had destroyed their memory by even trying to remember, which had terrified her. Instead of faces, she could sometimes remember certain feelings. The safety and happiness she felt looking up at her tall, tall father. The feel of her mother’s hand on her hair as she would comb it, over and over, before bed. She wished she was still a young child, held safe and loved, without any other care in the world. She wished she was an adult, long gone from there, living her own life away from teachers and trainers and awkward boys and crazy friends. She lay on the thick, rough husk and thought about the joys of lives different from hers as she soaked in the pod’s warmth on the cold, wintry day. === A Spring "Archers, ready!" Niketa’s voice from above cut through the quiet of the forest. It was strange for the forest in early bloom to be so silent, the normal background hum of chirping and scrabbling completely absent. Cilissa looked over at Thora, Natasa, and Delia. Cilissa knew Thora was ready, and while she hadn’t fought with Natasa before, she could tell the warrior was calm and prepared. Delia, on the other hand, was only sixteen and facing her first battle. She had readied her bow at Niketa’s command, and Cilissa tried to be kind. "She meant the archers in the trees. Put your bow away. We need to be ready to face a ground charge." Kind, but her voice was clipped. She didn’t want to see Delia killed in the first rush. Or at all. But there was no guarantee of survival for any of them. #figure(image("009_Seasons in Setessa/12.jpg", width: 100%), caption: [Defend the Hearth | Art by Raymond Swanland], supplement: none, numbering: none) Reports of the attacks had reached them days before. Bad enough to suffer the Silence a few months before, but then, when the gods were gone, reports began of large numbers of Nyxborn appearing everywhere in the land and, worse, attacking all mortals they came across. Some Setessans wondered whether the Nyxborn were attacking because the gods were no longer there to control them. Others wondered whether the gods were causing the attacks themselves to punish mortals, although for what crime they could not say. Who could guess the ways of the gods? All Setessans believed Karametra had no hand in the attacks, though. At least any Setessan with sense. What was not under dispute was that thousands of Nyxborn had invaded Setessa from the north and the west. Greener warriors had shepherded the young and the old to the better-defended interior, while units like Cilissa’s had been sent to stop the invaders or, at worst, slow them down and gather vital intelligence. It was a sign of how stretched they were that warriors as inexperienced as Delia were with them. Cilissa and Thora had been blooded warriors for the past two years; they were eighteen and hardened veterans, and Cilissa wished there were more there like themselves. Crouched as they were in the sparse underbrush, they could not see the approaching forces, but they could hear the sound of many feet trampling through the forest, and then they heard the first release of arrows above. Hundreds of archers lined thick branches and makeshift forts in the trees, and with the sound of release, Cilissa and the other three around her got into position, as did several other groups of four within eyesight. Delia gasped with fear, and although Cilissa wouldn’t say it, she understood. The forest in front of them had been taken over by Nyxborn. They were shaped in recognizable forms—humans, centaurs, minotaurs, and others—but their bodies seemed made out of the night sky, their very skin and muscle alive with the twinkling of stars. There were hundreds of them, perhaps thousands. They didn’t run in any order or pattern, they just came in relentless waves. #figure(image("009_Seasons in Setessa/14.jpg", width: 100%), caption: [Fated Intervention | Art by <NAME>], supplement: none, numbering: none) The arrows from above descended into the hordes and many Nyxborn fell to the initial onslaught. Cilissa had time to think, #emph[at least they can die] , and then the Nyxborn were upon them. Cilissa and Thora were set with long spears, with Natasa and Delia guarding their flanks with axe and knife. A centaur charged into Cilissa’s spear, and any remaining doubts about the reality of the Nyxborn faded as the answering thud rang through her arms and legs. The spear took the centaur full in the chest, his starry eyes dimming before his raised cudgel could land. A mixture of blood and viscous night sky leaked out of his chest. The massive weight of the falling centaur took her spear with it, but she picked up her spare short spear and began fending off the attacks of a humanoid swordsman that had leapt over the body of the centaur. The swordsman did not say a word as it fought, and Cilissa did not know what was more disconcerting, that the Nyxborn displayed no emotion as it fought, or that it fought well. But even fighting well, Cilissa had not faced a swordfighter yet that was a match for her with a spear. Several flicks and jabs had the Nyxborn bleeding, and although he did not seem in pain, he slowed as moments went by, and failed to parry Cilissa’s closing thrust through his eye. With a sideways glance, Cilissa saw Thora handling her opponent before seeing a massive form rush in from her left. Delia had no time to scream as the minotaur’s huge axe cut her midsection in two. The minotaur roared as Cilissa thrust her spear at his chest. The spear glanced off weakly at a bad angle, but Cilissa ducked under the beast’s huge legs, dropping her spear and pulling out her hand axe. She used two hands to swing her axe at the minotaur’s back leg, severing tendon and muscle and then finished the work on its other leg. The minotaur fell to the ground in front of her and she leapt on its back and plunged her axe deep into its skull. The minotaur continued to roar and convulse, weaker each time. Cilissa looked up as the carnage around her continued. Arrows and magic flowed from the trees down to the Nyxborn, but the Nyxborn had mages of their own firing spells back. Nyxborn harpies also were up in the trees attacking and bringing down archers, and the steady stream of arrows from above slowed. Thora and Natasa were still up and looked fine, but many other groups had lost two or three people, and many of the ones remaining were hurt, some grievously. There was no time for thought as three more Nyxborn with swords charged in, with other humanoids behind them. Natasa ducked under one attacker, neatly slicing its throat as she fought through to deal with the additional reinforcements behind. Cilissa and Thora each took on the attackers in front of them, Cilissa with her axe and Thora with two long knives. the swordsman pressed Cilissa hard, giving her no space to mount an offense, or even draw her long knife. She focused on staying alive, parrying each of the Nyxborn’s attacks. With a cry of triumph, Thora plunged both of her knives into the back of Cilissa’s assailant, and Cilissa knew Thora’s joyous smile was due to being the one to rescue Cilissa, instead of the reverse. The only warning they had was a hiss. Thora turned around in surprise, and Cilissa, shielded from the enemy by Thora’s body, heard a loud, crackling sound, and saw Thora’s body turn a pale shade of chalk-gray. A gorgon. With a cry, Cilissa turned away from her dead friend and sprinted in the opposite direction from the gorgon. She heard the gorgon following, slithering along the forest floor, easily keeping pace with Cilissa’s mad dash. #figure(image("009_Seasons in Setessa/16.jpg", width: 100%), caption: [Archetype of Finality | Art by <NAME>], supplement: none, numbering: none) Ahead of her, a flash of green caught her eye, and she veered off in the direction of a large rock that pulsed a soft, green glow, the gorgon a step behind. Cilissa still had her axe in hand, and she leapt onto the rock in front of her and sprung off, closing her eyes and twisting back as she hurled the axe to where she pictured the gorgon’s head would be. As she landed, she opened her eyes. If the axe hit she’d soon be dead if she kept her eyes closed, and if the axe didn’t hit she’d soon be dead regardless. She saw the sprawled corpse of the gorgon, the axe embedded in its face. She allowed herself a deep breath, and then she took in the bloodshed around her. Everywhere she looked she saw dead and dying Setessans, as the inexorable tides of Nyxborn had overrun most of her friends. She looked in the distance and saw the gray statues of Thora and Natasa. She choked back the tears that threatened to overwhelm her. She had launched herself off of one of Karametra’s pods, the largest she had ever seen, easily three times her size laid end-to-end, its thick husk as tough as iron. The green glow that emanated from it, usually soft and gentle, was now harsh and insistent. It was hard not to look at the husk and see it as evidence of Karametra’s betrayal. What good was a remnant of a god when all her friends were dead? Still more Nyxborn came on, more humanoids with swords. Cilissa had only her two long knives left and took on two, three, more, until she lost count. She lost herself in the whirling dance of parry and cut and slash, and with each Nyxborn felled she thought of Thora’s last smile as she had saved Cilissa’s life. #emph[You do not fight with your body. You fight with your mind.] Faster and faster she whirled, faster than she had ever fought, and still Niketa’s words rose up. #emph[You will never be fast enough, Child. You fight with your mind.] But what good was her mind when her friends were dead and her god was gone? Karametra’s husk continued to glow, its green nimbus pulsing strongly. #emph[You are loved, Child.] That was what the god had whispered to her so many years ago. #emph[Karametra is gone] ,she told herself.She saw numerous Nyxborn bodies littering the ground in front of her. Had she killed them all? No, still more Nyxborn than she could count were entering the forest, while others finished their slaughter of the Setessans. She spotted a minotaur at the same time it saw her, and it charged. Only as she threw herself to the side, avoiding the charge, did she realize she was bleeding in several places. She had not escaped her dance unscathed. They were mostly cuts on her arms, although she saw one thigh suffused with red. She was going to die there. But she would take this minotaur with her. #emph[You fight with your mind.] Another voice whispered,#emph[You are loved, Child.] "What do you want from me?" she screamed into the forest. Nothing changed, no Nyxborn stopped its killing, no god appeared. The minotaur circled around for another charge. The pod continued to pulse. #emph[Karametra’s pod.] With another scream she brought one of her knives in a large overhand swing down onto the pod. It clanged off as if striking the hardest iron. Again, she brought her knife down and it was like trying to cut through steel with a spoon. She hurled herself to the side to avoid the minotaur’s charge, and the pain of her wounds blossomed fresh. She was not strong enough to open the pod. She wasn’t even sure what opening the pod would do, but she needed to try. The minotaur approached with its axe, the blade ripe with blood from some other slain Setessan. #emph[I fight with my mind. I hope so, because my body is about to give out.] She stood in front of the pod, both knives bared, a snarl on her face. The minotaur raised his axe and brought it up in a vicious two-handed swing to split Cilissa in two. At the last possible second she did an awkward, ugly somersault backwards, anything to get out of the way of the descending blade, and the minotaur’s axe hit the pod squarely in the center, splitting it open from top to bottom. A rush of sounds and green light filled the forest. The sound of a forest stream burbling, the sound of birds chirping in their mating dance, the sound of golden leaves swirling in the wind. The minotaur stood there, transfixed, as the green light framed its body. The Nyxborn slowly dissolved into nothingness. Everywhere Cilissa looked, the Nyxborn were surrounded by a green nimbus that triggered their slow dissolve into oblivion. Within seconds, there was no Nyxborn in sight. #figure(image("009_Seasons in Setessa/18.jpg", width: 100%), caption: [Revoke Existence | Art by Adam Paquette], supplement: none, numbering: none) A tranquil silence followed the breaking of the pod, only to be replaced by the sounds of the dying. Cilissa was on her back, struggling to breathe, her leg throbbing with pain and leaking blood with each throb. #emph[That is a lot of blood] , Cilissa noticed. She turned over to her front and crawled over to the broken pod. The pod was a lifeless husk, a thick rind of fibrous wood. She put her hand on it, but there was no warmth, no green glow, no feeling of the god or her touch. Still, the pod had saved her. If only she had known. If only someone had known. She had to tell someone. There were still pods scattered throughout the forest; not many, but enough. She began crawling on the forest floor. #emph[I have to tell someone. I have to stop bleeding. I have to rest.] She was very tired. As she was passing out, she thought she heard the crunch of footsteps approaching. She prayed they were the footsteps of a friend, and then she sunk into oblivion. === A Summer It was a beautiful and warm summer day. Even the mists that usually clung to the borders of the clearing were wispy and translucent. Cilissa looked out at the gathered circles of children in the clearing. They were so #emph[young] . Had she ever been that young? Some of those faces looked openly scared, others made sure to display how tough and unafraid they were, still others seemed in shock, unable to feel at all. Cilissa knew the looks on those faces well. She gazed up from the edge of the clearing, still finding marvel in the portal to Nyx above their heads. The stars continued to move and shimmer, patterns endlessly forming and dissolving and dancing. She strode out to the center of the clearing, focusing on not limping, which she could do for short periods of time. She reached the center, and stood there, waiting. She saw the fear in the faces of the children, but she also saw hope. And love. She saw love most of all. She let her voice be infused by the presence of the god, and it boomed out across the clearing. "Welcome, L<NAME>. You are safe here. You are home."
https://github.com/RandomcodeDev/FalseKing-Design
https://raw.githubusercontent.com/RandomcodeDev/FalseKing-Design/main/engine/scene.typ
typst
= Scene system Scenes contain entities. Entities have components like a "renderable", which contains a handle to a mesh and other information, and transform information. These are some kinds of entities: #list( [Sky/sun/moon entities], [Details like grass, leaves, etc], [Terrain], [Objects like furniture, items, etc], [Players], [NPCs], [Buildings, doors, etc], )
https://github.com/barddust/Kuafu
https://raw.githubusercontent.com/barddust/Kuafu/main/src/Meta/yoga.typ
typst
= 轻瑜伽 目标并非是为了成为瑜伽大师,只是依据《睡眠革命》的观点,睡醒之后应当进行适当的运动,舒活筋骨,消除疲惫,开启美好的一天。一些剧烈的运动或者健身动作就不太合适(目前没去找理论依据),我能想到的最符合需求的应当就是类似瑜伽之类的延展类动作。 == 站立拉伸 + 站立,双手自然下垂; + 从两侧举起双手,在头顶合掌,头向上仰。慢速深呼吸一次; + 上半身向右侧弯曲,拉伸左侧腰部。上臂和头部向后仰,胸口向前扩张。慢速深呼吸三次; + 身体回正。慢速深呼吸一次; + 上半身向右侧弯曲,拉伸右侧腰部。上臂和头部向后仰,胸口向前扩张。慢速深呼吸三次; + 身体回正。慢速深呼吸一次。 == 半蹲拉伸 + 双腿并拢; + 半蹲,腰部挺直,从两侧举起双手。 慢速深呼吸三次; + 身体回正。慢速深呼吸一次。 == 弓步拉伸 + 左腿向后,呈弓步,举起双手,头向上仰。慢速深呼吸三次; + 左腿下压,使其小腿和地面平行。慢速深呼吸两次; + 右腿向后,呈弓步,举起双手,头向上仰。慢速深呼吸三次; + 右腿下压,使其小腿和地面平行。慢速深呼吸两次; + 身体回正。慢速深呼吸一次。 == 重复 以上三步为一轮,一共做两轮。 == 参考 - #link("https://www.bilibili.com/video/BV1gS4y1U71T")[[男式瑜伽]每日七分钟,活力满满一整天\_哔哩哔哩]
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/docs/src/reference.typ
typst
The Unlicense
// ------------- Template ------------------------- #import "@preview/tidy:0.3.0" #import "@preview/gentle-clues:0.6.0": * #import "@preview/codly:0.2.0": * #let show-module = tidy.show-module.with( show-outline: false, sort-functions: none, first-heading-level: 1, ) #let def-arg(term, t, default: none, description) = { if type(t) == str { t = t.replace("?", "|none") t = `<` + t.split("|").map(s => { if s == "b" { `boolean` } else if s == "s" { `string` } else if s == "i" { `integer` } else if s == "f" { `float` } else if s == "c" { `coordinate` } else if s == "d" { `dictionary` } else if s == "a" { `array` } else if s == "n" { `number` } else { raw(s) } }).join(`|`) + `>` } stack( dir: ltr, [/ #term: #t \ #description], align( right, if default != none { [(default: #default)] }, ), ) } #set heading(numbering: "1.") #show: codly-init.with() #codly() // ------------------ Document content ------------------------- #outline(title: none, indent: true, depth: 2) = Template #let template-module = tidy.parse-module(read("../../lib.typ")) #show-module(template-module) = Entries #let entries-module = tidy.parse-module(read("../../entries.typ")) #show-module(entries-module) = Glossary #let glossary-module = tidy.parse-module(read("../../glossary.typ")) #show-module(glossary-module) = Components All of the components across each theme share the same API, so changing themes should be guaranteed to work. #info[ All of the examples show the default theme, other theme's components will look differently. ] #import "/lib.typ": * #import themes.default: default-theme, components #let default-components-module = tidy.parse-module( read("../../themes/default/components.typ"), scope: ( create-body-entry: create-body-entry, glossary: glossary, components: components, ), ) #show-module(default-components-module) = Utils #let utils-module = tidy.parse-module(read("../../utils/misc.typ") + read("../../utils/theme.typ") + read("../../utils/components.typ")) #show-module(utils-module)
https://github.com/thornoar/lambda-calculus-course
https://raw.githubusercontent.com/thornoar/lambda-calculus-course/master/main-lectures/problems-2.typ
typst
#import "template.lib.typ": * #import "@local/common:0.0.0": * #show: problemlist(2, [ л-Представимость и неразрешимость ]) #let Mult = combinator([Mult]) #let Fac = combinator([Fac]) + Пусть $M_1, M_2, ..., M_k$ и $N_1, N_2, ..., N_k$ --- два набора л-выражений. Покажите, что $ << M_1, M_2, ..., M_k >> = << N_1, N_2, ..., N_k >> hs <==> hs M_1 = N_1, M_2 = N_2, ..., M_k = N_k $ + Постройте л-выражения $A, B in #L$ таким образом, чтобы $A x = A$ и $B x = x B$. + Постройте выражения $F, pi in #L^0$, такие, что: - $forall n in NN: hs F nums(n) x y = x y^(~~ n)$ - $forall n in NN, hs forall i <= n: hs pi nums(n) num(i) = pi^n_i $ + - Постройте л-выражение $Mult$, такое, что $Mult num(n) #h(3pt) num(m) = num(m n)$ для любых $m,n in NN_0$. - Постройте л-выражение $Fac$, такое, что $Fac num(n) = num(n!)$ для любого $n in NN_0$. + _Элементарная функция Аккермана_ $phi$ определяется следующими соотношениями: $ phi(0, n) &= n+1,\ phi(m+1, 0) &= phi(m, 1),\ phi(m+1, n+1) &= phi(m, phi(m+1, n)). $ Покажите, что $phi$ рекурсивна, и найдите л-выражение, которое её л-представляет. + Постройте функцию предшествующего элемента для чисел Чёрча: $#P _c^-$ такое, что $#P _c^- c_(n+1) = c_n$ при всех $n in NN_0$. + Допустим, что каждый символ в упрощённой записи л-выражения (переменная, скобка, точка, запятая, лямбда) занимает 0.5см пространства на бумаге. Найдите л-выражение длиной менее 25см, имеющее нормальную форму длиной не менее $10^10^150$ световых лет (скорость света составляет $3 dot 10^10$ см/сек.) #let p = math.pound + Пусть $ pound &= @a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%q%s%t%u%v%w%x%y%z%r.. r(t h i s i s a f i x e d p o i n t c o m b i n a t o r),\ dollar &= #p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p. $ Покажите, что $dollar$ --- комбинатор неподвижной точки. + Докажите, что $M in #L$ --- комбинатор неподвижной точки $<==>$ $M = (#S #I) M$. + Пусть $f$, $g$ --- л-выражения. Положим $X == #Th (f circ g)$. Докажите, что $g(X)$ --- неподвижная точка выражения $g circ f$. + Положим $#Y _M == @f.. W W M$, где $W == @x%z.. f(x x z)$. Докажите, что $#Y _M$ --- комбинатор неподвижной точки для любого $M in #L$. + Докажите, что $#Y _M = #Y _N ==> M = N$. ($#Y _M$ и $#Y _N$ определены как в предыдущей задаче) + - Пусть $f : NN_0^2 -> NN_0$ --- рекурсивная функция. Постройте последовательность $X_0, X_1, ...$ л-выражений, такую, что при всех $n in NN_0$ выполняется $X_n X_m = X_(f(n,m))$. - Пусть $X = { x_1, x_2, ..., x_n }$, и пусть $times$ --- бинарная операция на $X$. Постройте л-выражения $X_1, X_2, ..., X_n$ таким образом, чтобы выполнялось $X_i X_j = X_k hs <==> hs x_i times x_j = x_k$ при всех $i, j, k$. + Пусть $d$ --- числовая система. Докажите, что $d$ адекватна тогда и только тогда, когда $ exists F, F^(-1) in #L: hs hs forall n in NN_0: hs hs (F nums(n) = d_n) and (F^(-1) d_n = num(n)). $ #let C = combinator([C]) + Пусть $d_0, d_1, ...$ --- адекватная числовая система. Положим $d'_n == #Y#C d_n$, где $#C == @x%y%z.. x(z y)$. Покажите, что все рекурсивные функции одного аргумента $phi : NN_0 -> NN_0$ л-представляются с помощью $d'$.\ (подсказка: рассмотрите $F' == @x..x F$) + Пусть $f_0 == @x%y%z.. y$ и $#S^+_f == @x.. <<x>>$. Покажите, что функции $#P^-_f == <<I>>$ и $Zero _f == @x%y%z.. x (@x'%y'%z'.. z')y z$ превращают $(f_0, #S^+_f)$ в адекватную числовую систему. + Рассмотрим последовательность $a_n == #K^n #I$. Покажите, что $a$ --- *не* числовая система. + Покажите, что множество ${ M in #L | M = #I }$ --- *не* рекурсивное. + Докажите, что существует л-выражение $M$, такое, что $M = num(M)$.\ (подсказка: обратите внимание на доказательство теоремы Скотта-Карри о неразрешимости) + Докажите _вторую теорему о неподвижной точке:_ $forall F in #L: hs exists X in #L: hs F nums(X) = X$.
https://github.com/pedrofp4444/BD
https://raw.githubusercontent.com/pedrofp4444/BD/main/report/content/[3] Modelação Concetual/diagrama.typ
typst
#let diagrama = { [ == Apresentação e Explicação do Diagrama ER Produzido Após a identificação e caracterização detalhada de cada entidade, atributo e relacionamento nos tópicos anteriores, prosseguimos agora para a apresentação de todo o diagrama ER que suporta o modelo da base de dados em questão. #align(center)[ #figure( kind: image, caption: "Ilustração do diagrama ER produzido.", image("../../images/Captura_DiagramaER.png", width: 100%) ) ] Neste diagrama, é possível identificar de forma clara todas as entidades da base de dados, bem como os relacionamentos responsáveis por interligar as mesmas. Deste modo, o diagrama é interpretado da seguinte forma: um funcionário desempenha obrigatoriamente uma função; um funcionário qualificado gere outros funcionários; os funcionários operacionais trabalham em diversos terrenos; a um terreno podem estar associados vários casos; num caso podem estar contidos vários funcionários. Por fim, podemos também identificar, em cada entidade e num dos relacionamentos, os atributos que os definem. Em todas as entidades destacam-se os atributos que constituem uma chave primária da mesma, visto serem representados por um círculo totalmente preenchido. Para além disso, no diagrama são também visíveis outros tipos de atributos, tais como multivalorados e opcionais. Assim, com a conclusão desta fase, é possível passar para a construção de um novo modelo capaz de especificar a caracterização de cada um dos elementos, sendo este o modelo de dados lógico. ] }
https://github.com/chubetho/Bachelor_Thesis
https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/templates/declaration.typ
typst
#heading( level: 1, numbering: none, "Eidesstattliche Erklärung", ) #[ #set text(lang: "de") Hiermit versichere ich, dass ich die vorgelegte Bachelorarbeit selbstständig verfasst und noch nicht anderweitig zu Prüfungszwecken vorgelegt habe. Alle benutzten Quellen und Hilfsmittel sind angegeben, wötliche und sinngemäße Zitate wurden als solche gekennzeichnet. #v(6em) #align(right)[ #line(length: 50%) Würzburg, am 13. September 2024 #h(1.25em) ] ] #pagebreak(weak: true)
https://github.com/FlorentCLMichel/quetta
https://raw.githubusercontent.com/FlorentCLMichel/quetta/main/README.md
markdown
MIT License
A simple module to write [tengwar](https://en.wikipedia.org/wiki/Tengwar) in [Typst](https://typst.app/). ## Requirements - [Typst](https://github.com/typst/typst) version 0.11.0 or 0.11.1 - The [Tengwar Annatar](https://www.fontspace.com/tengwar-annatar-font-f2244) fonts version 1.20 To use this module with the [Typst web app](https://typst.app/), you need to upload the font files to your project. ## Usage The main functionality of this module is provided by functions taking content and converting all text in Tenwar: * `quenya` converts text using the mode of Quenya, * `gondor` converts text using the Sindarin mode of Gondor. The original text is used as a phonetic transcription. (This module does not translate English into Quenya or Sindarin.) See the [manual](manual.pdf) for more information. The following line may be used to convert the whole document below to Tengwar in Quenya mode (other `show` rules might interfere with it): ``` #show: quetta.quenya ``` **Example:** ``` #import "@preview/quetta:0.2.0" // Use the function `quenya` to write a small amount of text in Tengwar (Quenya mode) #text(size: 16pt, fill: gradient.linear(blue, green) )[#box(quetta.quenya[_tengwar_])] #v(1em) // A `show` rule may be more convenient for larger contents; beware that it may interfere with other ones, though #show: quetta.quenya Namárië! #h(1em) _Namárië!_ #h(2em) *Namárië!* ``` ## Roadmap * Number conversion: done * Support for the Quenya mode: done * Support for the mode of Gondor: done * Support for the mode of Beleriand: backlog * Support for the Black Speech: backlog ## Changelog ### v0.2.0 * Add support for Sindarin—Mode of Gondor * **Breaking change:** The symbol used to prevent combination was changed from `:` to `|`. * Small changes to the kerning between several tengwar and to tehtar positions. ### v0.1.0 Initial release with Quenya support. ## How can I contribute? I (the original author) am definitely not en expert in either Typst nor Tengwar. I could thus use some help in all areas. I would especially welcome contributions or suggestions on the following: * Identify and resolve inefficiencies in the Typst code. * Identify cases where the result differs from the expected one. (In particular, there are probably rules for writing in Tengwar that I either am not aware of or have not properly understood. Any advice on that is warmly welcome!) * References on Tengar, Quenya, and Sindarin. * Support for other Tengwar fonts.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-04.typ
typst
Other
// Error: 3-6 cannot apply '-' to string #(-"")
https://github.com/benjamineeckh/kul-typst-template
https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/src/core/component/cover-page.typ
typst
MIT License
// Currently borked, searches for file from core/component, instead of the directory where the main file is located which uses lib #let parse-image(logo) = { if logo != none { let t = type(logo) if t == figure or t == content{ logo = logo }else if t == str{ logo = image(logo) }else{ panic("check the typing of the logo, something is wrong with it") } } return logo } // TODO: fix error messages + add some standard values #let insert-cover-page( title, authors, promotors, evaluators, supervisors, academic-year, submission-text, // An affiliation dictionary, you should specify a `university` // keyword, `school` keyword and a `degree` keyword affiliation, // can be an actual image, or just a path to an image logo:none, cover: false, lang:"en" ) = { // diferent scope so logo and font don't get copied over to all the other pages logo = parse-image(logo) page( margin: 20mm, header:none, numbering: none, footer: none, background: place( top + left, dy: 3.5%, dx: 5%, box(width: 77mm, height: 35mm, logo) ))[ #{ set text( font: "Nimbus Sans" ) v(30%) text(2.3em, weight: 500, title) v(4%) text(1.5em, weight: 500, authors.map(v=>v.name).join("\n")) v(8%) set align(right) // promotors, evaluators, supervisors block(width: 40%)[ #[ #set text(size: 11pt) #submission-text(affiliation.degree, affiliation.elective).at(lang) ] #if promotors == none{ panic("You probably need to have a promotor") }else{ if lang == "en"{ [*Supervisors*: #linebreak()] }else{ [*Promotoren*: #linebreak()] } promotors.join(linebreak()) linebreak() } #if not cover{ if evaluators == none{ // [] }else{ if lang == "en"{ [*Assessors*: #linebreak()] }else{ [*Evaluatoren*: #linebreak()] } evaluators.join(linebreak()) linebreak() } if supervisors == none{ // [] }else{ if lang == "en"{ [*Assistant-supervisors*: #linebreak()] }else{ [*Begeleider*: #linebreak()] } supervisors.join(linebreak()) } } ] // let affiliation = (color:none) let height = if affiliation.color != none and cover{ 6% } else { 2% } let year-marker = if type(academic-year) == array{ [#academic-year.at(0) #sym.dash.en #academic-year.at(1)] }else{ let next-year = academic-year+1 [#academic-year #sym.dash.en #next-year] } let title-page-footer = text(1.2em, weight: 500,[ #if lang == "en" { "Academic Year" } else { "Academiejaar" } #year-marker ]) title-page-footer += if affiliation.color != none and cover{ let clr = cmyk(..affiliation.color.map(v => v*100%)) let (red, green, blue) = rgb(clr).components().slice(0, 3).map(v => int(v*255 / 100%)) let text-clr = if (red*0.299 + green*0.587 + blue*0.114) > 186 {black} else {white} v(1em) rect(width: 110%, height: 3em, fill: clr, stroke:none)[#align(center+horizon)[#text(fill:text-clr)[#affiliation.degree: #affiliation.elective]]] } place( center + bottom, dy: height, title-page-footer ) } ] }
https://github.com/Quentindeve/tp_b2_symfony
https://raw.githubusercontent.com/Quentindeve/tp_b2_symfony/master/documents/tp_twig.typ
typst
#set document(title: "TP B2 - Contrôleurs et Twig", author: "<NAME>") #set page(paper: "a4", header: [ #figure( image("images/sio.png", width: 10%) ) ]) #set text(size: 24pt, font: "Cascadia", weight: "medium") #set heading(numbering: "1.a >") #show heading: it => [ #set align(center) #set text(24pt, weight: "bold") #block(smallcaps(it.body)) ] #show raw: it => block( fill: rgb("#fafafa"), inset: 8pt, radius: 5pt, text(fill: rgb("#a2aabc"), it, weight: "bold", font: "Cascadia Code", size: 14pt), ) #set align(center) #set text() = TP Symfony - Contrôleurs & Twig #set text(size: 15pt) #set align(left) #pagebreak() = Contexte #linebreak() On va réaliser un site où des posts peuvent être créés par tout le monde (y compris des personnes non-authentifiées), et où des personnes authentifiées peuvent commenter les posts. On dispose donc de 3 tables: - La table *Post*, qui contient tous les posts, avec leur contenu leur titre et leurs commentaires. - La table *Comment* contenant tous les commentaires, avec le post visé, l'auteur du commentaire et son contenu. - La table *User* qui contient tous nos utilisateurs. Voici un MCD, au cas-où vous êtes perdu: #figure( image("images/mcd.png", width: 100%), caption: [ MCD de la base de données. ] ) #pagebreak() = Mise en place #linebreak() On va commencer par mettre en place le projet ```sh # Télécharge les dépendances composer update # Crée la base de données symfony console doctrine:database:create # Crée la migration symfony console make:migration # Envoie la migration sur le serveur symfony console doctrine:migrations:migrate ``` #pagebreak() = Création du formulaire de création d'User #linebreak() On va commencer par créer notre table User. L'utilisateur doit être identifié par un username. ```sh symfony console make:user ``` Modifiez ensuite la table *Comment* avec: ```sh symfony console make:entity Comment ``` Rajoutez une colonne *publisher* qui référence l'user ayant écrit le commentaire. Gardez bien en tête que l'utilisateur peut avoir écrit autant de commentaires qu'il veut, mais qu'un commentaire est écrit par exactement une personne. #linebreak() - 1: Créer un formulaire permettant de s'inscrire en tant qu'utilisateur. L'utilisateur doit être identifié par un username, pas un email. On ne souhaite pas vérifier l'email entré, on souhaite que l'utilisateur soit automatiquement authentifié après la création de son compte et après l'enregistrement de son compte, il doit être redirigé vers la page nommée *app_index*. Voici une source pour aiguiller vos recherches: - #link("https://symfony.com/doc/4.1/doctrine/registration_form.html")[Symfony 4 Doc - Registration Form] #linebreak() - 2: Avoir créé le formulaire c'est bien, mais y avoir accès c'est mieux ! Rajouter le lien vers le formulaire d'enregistrement dans le *\<a\>* correspondant dans l'index. _indices: regarder la route dans Controller/RegistrationController.php et le template utilisé dans IndexController.php_ #linebreak() - 3: Maintenant créer un formulaire de connexion serait vachement bien ! Heureusement, Symfony peut le faire pour nous. On voudrait aussi une URL permettant de se déconnecter. Ah et ça serait bien que le site se "souvienne" de nous par défaut ! Trouvez comment faire à partir des sources fournies: - #link("https://symfony.com/doc/5.2/security/form_login_setup.html")[Symfony Doc - Form Login Setup] #linebreak() #pagebreak() - _4: Bonus_: Ca serait vachement drôle si la page d'index nous indiquait notre pseudo si on est connecté ! Ca devrait être faisable à partir des sources fournies ci-dessous et du cours ! - #link("https://twig.symfony.com/doc/2.x/tags/if.html")[Twig Doc - If Clauses] - _indice: dans la fonction index de votre IndexController, vous pouvez demander un ?UserInterface en paramètre, qui possède une méthode getUsername ! Vérifiez par contre qu'il n'est pas null, car si il l'est, alors l'utilisateur n'est pas connecté et vous ne pouvez pas vous en servir._ #linebreak() - 5: Devinez quoi ? Rajouter un petit bouton de déconnexion dans l'index serait pas mal, non ? #linebreak() - _6: Bonus_: Ce qui serait hilarant maintenant c'est que le bouton "Se déconnecter" ne soit visible que si l'utilisateur est connecté, et que les boutons "Se connecter" ainsi que "Créer un utilisateur" ne soient pas visibles si on est connectés. Enfin j'imagine qu'on occupe pas nos week-ends de la même façon ? #pagebreak() = Création d'un Post #linebreak() Qui dit création d'un Post dit insertion dans la base de données. Et qui dit insertion dans la base de données dit formulaire ! Nos posts sont très simples: - Un titre, qui est un varchar(255). - Le contenu, qui est juste du texte. #linebreak() - 7: Générer le contrôleur CreatePostController avec la commande: ```sh # Crée le contrôleur CreatePostController, avec les fichiers Controller/CreatePostControler.php et templates/create_post/index.html.twig symfony console make:controller CreatePostController ``` #linebreak() - 8: Changer la route de CreatePostController en *createpost* au lieu de *\/create/post*. Parce qu'on aime pas les routes imbriquées. #linebreak() - 9: Faites votre petit formulaire dans le fichier Twig correspondant. La méthode doit être POST, et l'action sur *createpost*. #pagebreak() = Poster un Post Une route peut être utilisée pour plusieurs méthodes. Perdu ? Prenons le temps de s'expliquer: - Quand vous essayez de naviguer sur un site, par exemple sur votre *localhost*, votre navigateur effectue une requête GET. C'est la requête la plus simple qui existe, le serveur a juste à renvoyer la ressource correspondante. - Quand votre navigateur doit renvoyer un formulaire, le développeur, _vous_, privilégiez 99% du temps de passer par la méthode *POST*. Si vous avez bien spécifié *method=post* dans votre formulaire, et la bonne action, on aura la route *createpost* utilisée pour deux choses à la fois ! L'une pour obtenir le formulaire et l'autre pour le submit ! Heureusement, chez Symfony ils ont pensé à nous. #pagebreak() Les *faibles* penseront à faire deux routes distinctes. Mais nous on est extrêmement puissants, c'est pourquoi nous allons *dupliquer* notre fonction *index*. Votre fichier CreatePostController.php ressemble actuellement à ça: ```php <?php class CreatePostController extends AbstractController { #[Route('/createpost', name: 'app_create_post')] public function index(): Response { return $this->render('create_post/index.html.twig', [ 'controller_name' => 'CreatePostController', ]); } } ?>``` Dupliquez la fonction *index*, avec son attribut route. Sisi je vous jure, faites-le. Bien, maintenant que c'est fait on va les *tuner* un peu. Renommez la première fonction *index_get*. et changez son attribut *\#[Route]* en: ```php #[Route('/createpost', name: 'app_create_post_get', methods: ["GET"])] ``` Prenez son clone et renommez-là *index_post*. Changez son attribut *\#[Route]* en: ```php #[Route('/createpost', name: 'app_create_post_post', methods: ["POST"])] ``` Et maintenant devinez quoi ? Chaque fois que l'on voudra obtenir, *GET* la page, Symfony appellera la fonction *index_get*, et dès que l'on voudra submit notre formulaire, *POST*\er notre Post, il appellera la fonction *index_post*. Nous ne toucherons pas à *index_get* car il instancie déjà correctement *templates/create_post/index.html.twig*. Par contre *index_post* n'enregistre encore rien. On va y remédier. Ajoutez dans les paramètres de *index_post* la requête, de façon à avoir: ```php public function index_post(Request $request): Response ``` _Attention: la classe à importer est Symfony\\Component\\HttpFoundation\\Request;_ Vous avez désormais accès aux valeurs transmises par votre formulaire. Pour cela, faites simplement ```php $request->get("..."); ``` Pour récupérer les valeurs envoyées par le formulaire ! #linebreak() - 10: En vous servant de la documentation fournie ci-dessous et des informations données ci-dessus, trouvez un moyen de créer un Post et de l'enregistrer dans votre base de données. - #link("https://symfony.com/doc/current/doctrine.html#persisting-objects-to-the-database")[Symfony - Persisting Objects to the Database] #linebreak() - _11: Bonus_: Ce qui serait génial c'est qu'en nous renvoyant sur le formulaire après avoir fait persister le Post en base de données, la page nous signale que l'insertion s'est bien passée. #pagebreak() = Lister les Posts #linebreak() - 12: Bon, maintenant ce qui serait bien, c'est que les posts soient visibles ! Créez donc un contrôleur nommé *ListPostsController*. Changez sa route en *listposts*, et affichez-les tous ! Voici des petits liens pour vous aiguiller dans la réalisation d'une telle page: - #link("https://symfony.com/doc/current/doctrine.html#fetching-objects-from-the-database", [Symfony: Fetching Objects from the Database]) _Spoiler: EntityManagerInterface et tous les Repository ont une méthode findAll !_ - #link("https://twig.symfony.com/doc/3.x/tags/for.html", [Twig: For Loops]) #pagebreak() = Ajout et Listing des Commentaires #linebreak() - 13: Avec tout ce que vous avez fait jusque-là, bravo ! Vous pouvez désormais vous débrouiller tout seul ! Faites désormais une page permettant d'ajouter un commentaire sur un Post, et ouvrez-y l'accès depuis l'index. Le Post *doit* exister, et l'utilisateur *doit* être connecté afin de pouvoir envoyer un commentaire. Faites ça sur la route *sendcomment*. Une route *GET* et une route *POST* *pourraient* être nécessaires à chaque fois :^). - _indice: dans la fonction index de votre IndexController, vous pouvez demander un ?UserInterface en paramètre, qui possède une méthode getUsername ! Vérifiez par contre qu'il n'est pas null, car si il l'est, alors l'utilisateur n'est pas connecté et vous ne pouvez pas vous en servir._ #linebreak() - 14: Pour voir ces fameux commentaires, en revanche, pas besoin d'être connecté. Une route *GET* et une route *POST* devraient être encore une fois nécessaires, faites ça sur *listcomments*. #linebreak() - 15: Maintenant qu'on a accès à tout ce qu'on veut, vous trouvez pas que le site est vachement laid ? Arrangez tout ça, occupez-vous du style du site ! - _Note: tout ce qui est images/css/js doit être mis dans le dossier *public*, et pour accéder à son contenu rien de plus simple. Admettons que la fiche css est dans *public/style.css*, on y accède via un simple ```html <link rel="stylesheet" href="style.css"> ``` Vous pouvez d'ailleurs ajouter votre *link rel* directement dans *base.html.twig* comme ceci: ```twig {% block stylesheets %} <link rel="stylesheet" href="style.css"> {% endblock %} ``` elle sera ainsi incluse par défaut dans tous les autres templates ! _
https://github.com/gRox167/typst-assignment-template
https://raw.githubusercontent.com/gRox167/typst-assignment-template/main/README.md
markdown
# typst-assignment-template This is a simple template for assignment.
https://github.com/skyl4b/typst-templates
https://raw.githubusercontent.com/skyl4b/typst-templates/main/src/homework/template.typ
typst
MIT License
// Homework template for exercises and self-studies #let project(title: "", author: "", date: none, body) = { // Set margins let margin = ( x: 1.00cm, y: 3.65cm, ) // Define page counter function let page_count = { let page_counter = counter(page) let page = page_counter.display() let total = locate( loc => page_counter.final(loc).first() ) [#page / #total] } // Setup logos let logo_height = 0.9cm let university_logo = box(height: logo_height)[ #image("images/encrypted/university_logo.png") ] let department_logo = box(height: logo_height)[ #image("images/encrypted/department_logo.svg") ] let centered_title = box(height: logo_height)[ #align(horizon)[*#title*] ] // Set document basic properties set document(author: author, title: title) set page( columns: 1, margin: margin, header: align(top + center)[ #v(margin.x) // same margin as horizontal #line(length: 100%) #h(1fr) #university_logo #h(2fr) #centered_title #h(2fr) #department_logo #h(1fr) #line(length: 100%) ], header-ascent: 0%, footer: align(center + bottom)[ #line(length: 100%) #h(10pt) #author - #date #h(1fr) #page_count #h(10pt) #line(length: 100%) #v(margin.x) // same margin as horizontal ], footer-descent: 0%, ) // Set vector style set math.vec(delim: "[") set math.mat(delim: "[") // Set weak pagebreaks, will not pagebreak if // a page is left blank set pagebreak(weak: true) // Save heading and body font families in variables let body-family = "Liberation Serif" let sans-family = "Liberation Sans" // Set body font family. set text(font: body-family, lang: "pt") // Style headings set heading(numbering: none) show heading: head => { set align(center) set text(font: sans-family) smallcaps(head.body) } // Setup enum numbering¨ set enum(numbering: "1.a.i)") // Main body. body } // Auxiliary functions #let answer(content) = { rect( fill: rgb(242, 242, 242), stroke: 0.5pt, width: 100%, inset: 12pt, content ) } #let question(content, answer_content) = { box[ #content #answer(answer_content) #v(5pt) ] }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test configuring the size and fitting behaviour of images. // Set width and height explicitly. #box(image("/assets/files/rhino.png", width: 30pt)) #box(image("/assets/files/rhino.png", height: 30pt)) // Set width and height explicitly and force stretching. #image("/assets/files/monkey.svg", width: 100%, height: 20pt, fit: "stretch") // Make sure the bounding-box of the image is correct. #align(bottom + right, image("/assets/files/tiger.jpg", width: 40pt, alt: "A tiger"))
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/style.typ
typst
#let fSize = 25pt #let black = rgb("1f1f1f") #let gray = rgb("666666") #let red = rgb("8c1919") #let lred = rgb("a21d1d") #let blue = rgb("19538c") #let lblue = rgb("216db7") #let green = rgb("198c53") #let lgreen = rgb("21b76d") #let gold = rgb("a0740a") #let lgold = rgb("d0980c") #let purple = rgb("663399") #let lpurple = rgb("8c53c6") #let R = (red, lred) #let B = (blue, lblue) #let G = (green, lgreen) #let D = (gold, lgold) #let P = (purple, lpurple) #let (primary, secondary) = R #let primText(txt) = { return text(primary, txt) } #let secText(txt) = { return text(secondary, txt) } #let grayText(txt) = { text(gray, txt) } #let redText(txt) = { text(red, txt) } #let blueText(txt) = { text(blue, txt) } #let greenText(txt) = { text(green, txt) } #let relax(txt) = { text(black, txt) } #let small(txt) = { text(10pt, txt) } #let padNum(num) = { if num < 10 {"00"+str(num)} else if num < 100 {"0"+str(num)} else {str(num)} } #let lettrineContent(txt) = { } #let lettrine(txt, color: black) = { let first = true for it in txt { if first { upper(primText(it)) first = false } else {text(color)[#it]} } } #let superheader(txt) = { underline(stroke: (thickness: 3pt, paint: primary))[ #align(center)[#text(20pt)[ #primText[#upper[#text(hyphenate:false)[#txt]]] ]] ] } #let header(txt) = { align(center)[#text(15pt)[ #primText[#text(hyphenate:false)[#txt]] ]] } #let subheader(txt) = { underline[#align(center)[#text(13pt)[ #primText[#txt] ]]] } #let subsubheader(txt) = { underline[#align(center)[#text(10pt)[ #txt ]]] } #let lighter(txt) = { text(gray, fSize)[#txt] } #let D(txt) = { header[Дїа́конъ:\ ] par(first-line-indent: 1em, justify: true)[#text(fSize)[#txt\ ]] } #let K(txt) = { header[І̑ерей:\ ] text(fSize)[#txt\ ] } #let L(txt) = { text(fSize)[#primText[Ли́къ: ]] text(fSize)[#lighter(txt)\ ] } #let note(txt) = { primText[#txt] } #let centerNote(txt) = { align(center, primText[#txt]) } #let vozhlas(txt) = { header[Возглаше́нїе: ] par(first-line-indent: 1em, justify: true)[#text(fSize)[#txt\ ]] } #let secfmt(r) = { let t = r.at(0) let txt = r.at(1) if t == "knaz" { par(first-line-indent: 1em, justify: true)[#text(fSize)[#txt\ ]] } else if t == "diakon" { par(first-line-indent: 1em, justify: true)[#text(fSize)[#txt\ ]] } else if t == "lud" { L[#txt] } else if t == "vozhlas" { vozhlas[#txt] } else if t == "note" { note(txt) } else if t == "header" { header(txt) } else if t == "hr" { line(stroke: red, length: 100%) [\ ] } } #let section(values) = { values.map(secfmt).flatten().join() } #let smallEktenia(heading, molitva, vozhlas) = ( ("lud", "Гдⷭ҇и поми́лꙋй."), ("diakon", "Застꙋпѝ, спасѝ, поми́лꙋй и҆ сохранѝ на́съ Бж҃е, Твое́ю бл҃года́тїю."), ("diakon", "Прест҃ꙋ́ю, пречⷭ҇тꙋю, пребл҃гослове́ннꙋю, сла́внꙋю Влады́чицꙋ на́шꙋ Бцⷣꙋ и҆ приснодв҃ꙋ Марі́ю, со всѣ́ми ст҃ы́ми помѧнꙋ́вше, са́ми себѐ, и҆ дрꙋгъ дрꙋ́га, и҆ ве́сь живо́тъ на́шъ Хрⷭ҇тꙋ̀ Бг҃ꙋ предади́мъ."), ("lud", "Тебѣ̀, Гд҇꙼и."), ("header", heading), ("knaz", lettrine(molitva)), ("vozhlas", vozhlas) ) #let smallEkteniaSection(heading, molitva, vozhlas) = { D[Па́ки и҆ па́ки ми́ромъ Гдⷭ҇ꙋ помо́лимсѧ.] section(smallEktenia(heading, molitva, vozhlas)) L[А҆ми́нь.] }
https://github.com/matnut2/SlidesBSc
https://raw.githubusercontent.com/matnut2/SlidesBSc/master/slides.typ
typst
#import "@preview/polylux:0.3.1": * #import "unipd.typ": * #show: unipd-theme.with(author: "<NAME>", date: "22/02/2024", supervisore: "Supervisore: <NAME>", cosupervisore: "Cosupervisore: <NAME>", ccs:"Tutor CCS: <NAME>") #set text(font: ( "Noto Sans", "Segoe UI", "roboto", "Helvetica Neue", "Cantarell", "sans-serif", )) #title-slide( title: "Formalizzazione di una Architettura per Robot Sociali in un Contesto di Assistenza Sanitaria Domiciliare", subtitle: "Discussione Tesi di Laurea in Informatica", ) #centered-slide( title: "Indice", )[ #side-by-side(columns: (1fr, 1fr), [ #v(1em) #set text(size: 28pt) #enum(tight: false, indent: 4em) + Il Proponente + Il Progetto + SSRA: A Secure Social Robot Architecture + Studio di Fattibilità + Conclusioni ], [ #align(center, image("images/content-structure.svg", height: 80%)) ] ) ] #centered-slide( title: "Il Proponente", )[ #v(1em) #set text(size:20pt) #side-by-side([ #align(center, image("images/LogoSpritz.png", height: 6em)) Nato nel 2011 e guidato dal Prof. <NAME>. Gruppo di ricercatori nell'ambito della sicurezza. ], [ #align(center, image("images/LogoOmitech.png", height: 6em)) Omitech Robot, parte del gruppo Omitech. Nato nel 2018, opera nel campo R&S robotico. ] ) ] #centered-slide( title: "Nascita del Progetto", new-section: "Il Progetto", )[ #set text(size:20pt) #side-by-side(columns: (3fr, 1fr),[ Il gruppo SPRITZ dell'Università di Padova ha numerosi progetti di ricerca sulla sicurezza dei sistemi cyber-fisici, tra cui una collaborazione con Omitech sui robot sociali ], [ #align(center, image("images/sanbotElf.png", height: 6em)) ] ) #align(center, image("images/arrow-down.svg", height: 2em)) #side-by-side(columns: (1fr, 2fr),[ #align(center, image("images/unipd-logo.png", height: 6em)) ], [ Il progetto di stage è stato presentato alla conclusione del corso di _Cybersecurity_, dove ho deciso di candidarmi. ] ) ] #centered-slide( title: "Cos'è un Social Robot?" )[ #side-by-side( [ #align(center, image("images/sanbotElf.png", height: 15em)) ],[ #list(tight: false) #v(7%) - Robot umanoidi #v(15%) - Interazione naturale (_Human Robot Interaction_) #v(15%) - Due _layer_ fondamentali: automatico e deliberativo ] ) ] #centered-slide( title: "La Letteratura a Riguardo" )[ #set text(size:20pt) #side-by-side([ #one-by-one( [- Utilizzo delle Blockchain], [- Sicurezza del singolo robot], [- Robot sociali in ambito sanitario], [- Scarsità architetture di rete _privacy-preserving_], [- Scarsità di studi sulla sicurezza complessiva di una architettura], [- Assente crittografia con accesso granulare] ) ], [ #align(center, image("images/pepper.png", height: 20em)) ] ) ] // DA DECIDERE SE TENERE O MENO #centered-slide( title: "Threat Model", new-section: "SSRA", )[ #set text(size:17pt) #side-by-side([ #uncover("1-")[ Presupposto fondamentale è la possibilità di stabilire una connessione sicura tra utenti e server. ] #uncover("2-")[ L'attaccante può compromettere o un nodo o un collegamento tra nodi. ] #uncover("3-")[ _Master key_ in _Trusted Platform Module_. ] #uncover("4-")[ Attaccante incapace di violare schemi di crittografia approvati dal _NIST_. ] #uncover("5-")[ Non tratteremo della sicurezza dei dispositivi di _Mobile Health_. ] ], [ #align(center, image("images/Cybersecurity.jpg", width: 20em)) ] ) ] #centered-slide( title: "Security Requirements", )[ #set text(size:20pt) #side-by-side( [ #align(center, image("images/Crypto.png", height: 10em)) ], [*7 requisiti fondamentali:* #uncover("1-")[ 1: Integrità dei dati ] #uncover("2-")[ 2: Confidenzialità dei dati ] #uncover("3-")[ 3: Controllo dei danneggiamenti ] #uncover("4-")[ 4: Resistenza all'impersonificazione ] #uncover("5-")[ 5: Continuità ] #uncover("6-")[ 6: Assenza di tracciabilità ] #uncover("7-")[ 7: Protezione dai _replay attacks_ ]] ) ] #centered-slide( title: "Diagrammi (1/3)" )[ #align(center, image("images/ArchBaseNew.drawio.png", height: 12em)) ] #centered-slide( title: "Diagrammi (2/3)" )[ #set text(size:20pt) #side-by-side( [ Flusso di Setup #align(center, image("images/setup.drawio.png", height: 15.5em)) ], [ Operazioni Base #align(center, image("images/base.drawio.png", height: 15.5em)) ] ) ] #centered-slide( title: "Diagrammi (3/3)" )[ #set text(size:20pt) Flusso di Aggiunta Utente #align(center, image("images/AggiuntaNewUser.drawio.png", height: 12em)) ] #slide( title: "Studio di Fattibilità", new-section: "Studio di Fattibilità", )[ #set text(size:17pt) Scenario: Ente di sanità pubblica fornisce robot per il monitoraggio dei pazienti a domicilio o nelle strutture sanitarie. #underline[*Adattamento*] #side-by-side([ #only("1")[ - *Modifica delle entità* ] #only("2")[ - Modifica delle entità - *Modifica della sottostruttura del server* ] #only("3-")[ - Modifica delle entità - Modifica della sottostruttura del server ] ], [ #only("1")[ - Operatore (assimilabile al Tutore) - Terze Parti (assimilabili agli Utenti) ] #only("2")[ - Server cuscinetto per comunicazioni - Access Control System - Modulo CP-ABE ] ] ) #uncover("4-")[#underline[*Implementazione*]] #side-by-side([ #only("5")[ - *Definizione delle risorse per l'accesso al sistema* ] #only("6")[ - Definizione delle risorse per l'accesso al sistema - *Definizione dei processi* ] #only("7")[ - Definizione delle risorse per l'accesso al sistema - Definizione dei processi - *Implementazione della crittografia* ] ], [ #only("5")[ - Username + Password (accesso al sistema) - OTP (registrazione di un nuovo paziente) ] #only("7")[ - Utilizzo del modulo open-source RABE (_Rust ABE_) ] ] ) ] #centered-slide( title: "Il Paper IEEE", new-section: "Conclusioni", )[ #set text(size:20pt) #side-by-side( [ #align(center, image("images/IEEE.png", height: 5em)) #align(center, image("images/JBHI.png", height: 8em)) ], [ Raggiunti tutti gli altri obiettivi preventivati, assieme al <NAME> abbiamo iniziato la stesura di un _paper_ denominato *SSRA: A Secure Social Robot Architecture*, con l'obiettivo di inviarlo al _Journal of Biomedical & Health Informatics_, facente parte della _IEEE_. ] ) ] #slide( title: "Raggiungimento Obiettivi", )[ #set text(size:20pt) #uncover("1-")[ *Obbligatori*: #box(image("images/checkmark.svg", height: 1em)) Conoscenza degli argomenti fulcro dello stage #box(image("images/checkmark.svg", height: 1em)) Progettazione di una architettura sicura #box(image("images/checkmark.svg", height: 1em)) Studio di fattibilità per la architettura proposta ] #uncover("2-")[ *Desiderabili*: #box(image("images/checkmark.svg", height: 1em)) Analisi dei flussi dati derivanti dalla architettura proposta ] #uncover("3-")[ *Facoltativi*: #box(image("images/checkmark.svg", height: 1em)) Formalizzazione dei flussi di dati generati dalla architettura proposta #box(image("images/checkmark.svg", height: 1em)) Stesura di un _paper_ di ricerca ] ] #focus-slide( )[ *#align(center, "Grazie per l'Attenzione!")* ]
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/documentation/docs/project_configuration.md
markdown
# Project Configuration and Developer How-To ### Tools that were used in project development & their configuration, which might be useful to understand for any future contributors. --- ## Justfile the easiest way for running unit tests, automated _Tox_ environments' tests, building package and documentation is by running `just` commands, which are defined in the Typstdiff package's Justfile: ``` # Justfile install-deps: if [ -x "$(command -v poetry)" ]; then \ poetry install; \ else \ pip install -r requirements.txt; \ fi test: if [ -x "$(command -v poetry)" ]; then \ poetry run tox; \ else \ tox; \ fi format: if [ -x "$(command -v poetry)" ]; then \ poetry run black src tests; \ else \ black src tests; \ fi docs: if [ -x "$(command -v poetry)" ]; then \ cd documentation/ && poetry run mkdocs build; \ else \ cd documentation/ && mkdocs build; \ fi serve-docs: if [ -x "$(command -v poetry)" ]; then \ cd documentation/ && poetry run mkdocs serve; \ else \ cd documentation/ && mkdocs serve; \ fi clean: rm -rf .tox .pytest_cache dist build: if [ -x "$(command -v poetry)" ]; then \ poetry build; \ else \ pip wheel . -w dist; \ fi ``` Example command: `just install-deps`. To be able to do that, the developer must meet the prerequisites, mentioned in the tool's repository README and download the package through provided commands (for the package manager of their choice): [Just Repository - installation](https://github.com/casey/just?tab=readme-ov-file#packages). --- ## Tox Install tox using the pip package manager: ``` python -m pip install tox ``` Create a tox.ini configuration file inside the main project directory: ``` [tox] requires = tox>=4 env_list = lint, type, py310, py311 [testenv] description = run unit tests deps = pytest>=7 pytest-sugar commands = pytest {posargs:tests} [testenv:lint] description = run linters skip_install = true deps = black==24.4.2 commands = black {posargs:.} ``` - [*tox*] - global settings - [*testenv*] - settings for a specific test - *envlist* - list of environments where tests will be run - *skipsdist* - skip building distribution package - *skip_install* - skip installation - *deps* - required dependencies to run the test - *commands* - commands to be executed as part of the test In order to run all the tests for the Typstdiff package, format code using Black and test the package on different python interpreters / environments automatically, in terminal, within the main directory of the package, the `tox` command should be run. Result, after running the aforementioned command: ``` lint: OK (0.33=setup[0.04]+cmd[0.29] seconds) type: OK (25.02=setup[2.82]+cmd[22.20] seconds) py310: OK (22.50=setup[2.70]+cmd[19.80] seconds) py311: OK (23.68=setup[2.24]+cmd[21.44] seconds) congratulations :) (71.60 seconds) ``` --- ## Testing Package was tested via _pytest_ unit tests. Each of the .typst types, that are supported by the Typstdiff tool were tested in order to see if the changes (insertion, deletion, update) are marked appropriately in the output file. Aside from that complex files were tested - despite their higher complexity in structure the Typstdiff tool's performance did not worsened. The tests are parameterized and they use pytest's @fixtures and @marks, in order to make the testing process more efficient. --- ## MkDocs A tool used for creating project documentation. ### Installation and Configuration of MkDocs (Windows) Install MkDocs using the pip package manager: ``` pip install mkdocs ``` Create a new project. The project name corresponds to the directory name where the documentation will be located. ``` mkdocs new <new project name> ``` Navigate to the MkDocs project directory. ``` cd .\<new project name>\ ``` Run the MkDocs local server from the project directory. ``` mkdocs serve ``` Upon successful server start, the IP address will be displayed as the last log in the terminal. By default, it is [http://127.0.0.1:8000/](http://127.0.0.1:8000/). ``` INFO - Building documentation... INFO - Cleaning site directory` INFO - Documentation built in 0.59 seconds INFO - [HH:MM:SS] Watching paths for changes: 'docs', 'mkdocs.yml' INFO - [HH:MM:SS] Serving on http://127.0.0.1:8000/ ``` --- ## Poetry - tool for dependency management and packaging in Python In order to install poetry You need to follow the steps below: ### Prerequisite Install pipx: If You don't have `pipx` installed, follow the information in the [official pipx installation instructions](https://pipx.pypa.io/stable/installation/). Pipx is used to install Python CLI applications globally while still isolating them in virtual environments. It will manage upgrades and uninstalls when used to install Poetry. ### Installation process With pipx install Poetry: ```pipx install poetry``` This is the simplest way to install Poetry tool. For more information follow the link to the official _poetry_ documentation and user guide: [Poetry Introduction](https://python-poetry.org/docs/). --- ## Code Convention Naming conventions follow PEP8 standard: | Type | Convention | Example | | -----------|------------------------------------------------------|------------------------------- | | Function | Use lowercase letters and underscores for separation.| function, python_function | | Variable | Use lowercase letters and underscores for separation.| x, var, python_variable | | Class | Use uppercase letters, do not separate them. | Model, PythonClass | | Method | Use lowercase letters and underscores for separation.| class_method, method | | Constant | Use uppercase letters, words separated by underscores.| CONSTANT, PYTHON_CONSTANT | | Module | Use lowercase letters and underscores for separation.| module.py, python_module.py | | Package | Use lowercase letters, do not separate them. | package, pythonpackage | Names of variables, functions, classes, etc., should be descriptive. ``` >>> name = "<NAME>" >>> first_name, last_name = name.split() >>> print(f"{last_name}, {first_name}") '<NAME>' ``` Functions and classes at the top level should be separated by two blank lines on both sides. ``` class FirstClass: pass class SecondClass: pass def top_level_function(): return None ``` Method definitions inside classes should be separated by a single blank line on both sides. ``` class ClassWithMethods: def first_method(self): return None def second_method(self): return None ``` Use blank lines inside functions to show distinct steps. ``` def calculate_variance(numbers): sum_numbers = 0 for number in numbers: sum_numbers = sum_numbers + number mean = sum_numbers / len(numbers) sum_squares = 0 for number in numbers: sum_squares = sum_squares + number**2 mean_squares = sum_squares / len(numbers) return mean_squares - mean**2 ``` Limit the maximum line length to 79 characters. ``` def function(arg_one, arg_two, arg_three, arg_four): return arg_one ``` ``` from package import example1, \ example2, example3 ``` ``` with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read()) ``` If you need to break a line around binary operators such as + and *, you should do so before the operator. ``` total = (first_variable + second_variable - third_variable) ``` Closing parentheses should be placed either on the same line, ``` list_of_numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) ``` or on a new line, consistently. ``` list_of_numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) ``` Imports should be separated by a new line for each import. ``` # Correct: import os import sys ``` ``` # Wrong: import sys, os ``` Exception - the same library. ``` # Correct: from subprocess import Popen, PIPE ``` Other good habits: Recommended spacing around *parentheses*: ``` # Correct: spam(ham[1], {eggs: 2}) foo = (0,) if x == 4: print(x, y); x, y = y, x ``` Not recommended: ``` spam( ham[ 1 ], { eggs: 2 } ) bar = (0, ) if x == 4 : print(x , y) ; x , y = y , x ``` Recommended *separation of variables and operators*: ``` i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) ``` Not recommended: ``` i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) ``` Recommended *variable typing*: ``` def munge(input: AnyStr): ... def munge() -> PosInt: ... ``` Not recommended: ``` def munge(input:AnyStr): ... def munge()->PosInt: ... ``` Recommended *assigning values* to parameters within *function calls*: ``` def complex(real, imag=0.0): return magic(r=real, i=imag) ``` Not recommended: ``` def complex(real, imag = 0.0): return magic(r = real, i = imag) ``` Recommended *assigning values* to parameters within *function definition*: ``` def munge(sep: AnyStr = None): ... def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ... ``` Not recommended: ``` def munge(input: AnyStr=None): ... def munge(input: AnyStr, limit = 1000): ... ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-stroke_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test gradient on lines #set page(width: 100pt, height: 100pt) #line(length: 100%, stroke: 1pt + gradient.linear(red, blue)) #line(length: 100%, angle: 10deg, stroke: 1pt + gradient.linear(red, blue)) #line(length: 100%, angle: 10deg, stroke: 1pt + gradient.linear(red, blue, relative: "parent"))
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/accent_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test effect of accent on superscript. $A^x != hat(A)^x != hat(hat(A))^x$
https://github.com/howardlau1999/sysu-thesis-typst
https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/functions/booktab.typ
typst
MIT License
#import "helpers.typ": * #import "style.typ": * #let booktab(columns: (), aligns: (), width: auto, caption: none, ..cells) = { let headers = cells.pos().slice(0, columns.len()) let contents = cells.pos().slice(columns.len(), cells.pos().len()) set align(center) if aligns == () { for i in range(0, columns.len()) { aligns.push(center) } } let content_aligns = () for i in range(0, contents.len()) { content_aligns.push(aligns.at(calc.rem(i, aligns.len()))) } return figure( block( width: width, grid( columns: (auto), row-gutter: 1em, line(length: 100%), [ #set align(center) #box( width: 100% - 1em, grid( columns: columns, ..zip(headers, aligns).map(it => [ #set align(it.last()) #strong(it.first()) ]) ) ) ], line(length: 100%), [ #set align(center) #box( width: 100% - 1em, grid( columns: columns, row-gutter: 1em, ..contents.zip(content_aligns).map(it => [ #set align(it.last()) #it.first() ]) ) ) ], line(length: 100%), ), ), caption: caption, kind: table ) }
https://github.com/kazuyanagimoto/quarto-slides-typst
https://raw.githubusercontent.com/kazuyanagimoto/quarto-slides-typst/main/_extensions/kazuyanagimoto/clean/typst-show.typ
typst
MIT License
#show: clean-theme.with( aspect-ratio: "16-9", $if(handout)$ handout: true, $endif$ $if(fontsize)$ font-size: $fontsize$, $endif$ $if(sansfont)$ font-heading: ("$sansfont$",), $endif$ $if(mainfont)$ font-body: ("$mainfont$",), $endif$ $if(font-weight-heading)$ font-weight-heading: "$font-weight-heading$", $endif$ $if(font-weight-body)$ font-weight-body: "$font-weight-body$", $endif$ $if(font-weight-title)$ font-weight-title: "$font-weight-title$", $endif$ $if(font-size-title)$ font-size-title: $font-size-title$, $endif$ $if(font-size-subtitle)$ font-size-subtitle: $font-size-subtitle$, $endif$ $if(jet)$ color-jet: "$jet$", $endif$ $if(accent)$ color-accent: "$accent$", $endif$ $if(accent2)$ color-accent2: "$accent2$", $endif$ ) #title-slide( title: [$title$], subtitle: [$subtitle$], authors: ( $for(by-author)$ $if(it.name.literal)$ ( name: [$it.name.literal$], affiliation: [$for(it.affiliations)$$it.name$$sep$, $endfor$], email: [$it.email$], orcid: [$it.orcid$]), $endif$ $endfor$ ), date: [$date$], )
https://github.com/chrischriscris/Tareas-CI5651-EM2024
https://raw.githubusercontent.com/chrischriscris/Tareas-CI5651-EM2024/main/skel2/src/main.typ
typst
#import "template.typ": conf, question, pseudocode, GITFRONT_REPO #show: doc => conf("Tarea n: ", doc) #question[ Pregunta 1 ][ Solución 1 ][ Pregunta n ][ Solución n ]
https://github.com/NwaitDev/Typst-Accessibility-Template
https://raw.githubusercontent.com/NwaitDev/Typst-Accessibility-Template/main/Components/abstract.typ
typst
#let print_abstract(abstract, language:"english") = { let oldval = alignment.horizon set align(center) if language=="english" { [*Abstract*] } else if language == "french" { [*Résumé*] } else { [*--------*] } [\ #abstract] set align(oldval) }
https://github.com/T1mVo/shadowed
https://raw.githubusercontent.com/T1mVo/shadowed/main/src/shadowed.typ
typst
MIT License
#let renderer = plugin("renderer.wasm") #let render( svg-height, svg-width, blur, color, rect-height, rect-width, x-offset, y-offset, radius, ) = { assert(type(svg-height) == length, message: "svg-height must be of type: length") assert(type(svg-width) == length, message: "svg-width must be of type: length") assert(type(blur) == length, message: "blur must be of type: length") assert(type(color) == std.color, message: "color must be of type: color") assert(type(rect-height) == length, message: "rect-height must be of type: length") assert(type(rect-width) == length, message: "rect-width must be of type: length") assert(type(x-offset) == length, message: "x-offset must be of type: length") assert(type(y-offset) == length, message: "y-offset must be of type: length") assert(type(radius) == length, message: "radius must be of type: length") let image-height = svg-height let image-width = svg-width let svg-height = svg-height.pt().to-bytes() let svg-width = svg-width.pt().to-bytes() let blur = (blur.pt() / 2.5).to-bytes() let color = bytes(color.rgb().to-hex()) let rect-height = rect-height.pt().to-bytes() let rect-width = rect-width.pt().to-bytes() let x-offset = x-offset.pt().to-bytes() let y-offset = y-offset.pt().to-bytes() let radius = radius.pt().to-bytes() let buffer = renderer.render( svg-height, svg-width, blur, color, rect-height, rect-width, x-offset, y-offset, radius, ) image.decode(buffer, format: "svg", height: image-height, width: image-width, alt: "shadow") } /// Apply box shadows to inner content. /// /// - blur (length): Blur radius of the shadow. Also adds a padding of the same size. /// - radius (length): Corner radius of block and shadow. /// - color (color): Color of the shadow. /// - inset (length): Inset of the block. /// - fill (color): Color of the block. /// - body (content): Inner content. /// -> content #let shadowed( blur: 8pt, radius: 0pt, color: rgb(89, 85, 101, 30%), inset: 0pt, fill: white, body, ) = layout(size => [ #let dims = measure[ #block(breakable: false)[ #block(radius: radius, inset: blur)[ #block(inset: inset)[ #body ] ] ] ] #let width = calc.min(size.width, dims.width) #let height = measure[ #block(breakable: false)[ #block(radius: radius, inset: blur, width: width)[ #block(inset: inset)[ #body ] ] ] ].height #block(breakable: false)[ #place[ #render( height, // svg-height width, // svg-width blur, // blur color, // color height - blur * 2, // rect-height width - blur * 2, // rect-width blur, // x-offset blur, // y-offset radius, // radius ) ] #block(inset: blur)[ #block(radius: radius, inset: inset, fill: fill)[ #body ] ] ] ])
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/graphs/a.typ
typst
#import "@preview/cetz:0.2.2" #let plot-opts = ( size: (4, 4), name: "plot", axis-style: "school-book", x-min: -4 + 0.0, y-min: -4, x-format: v => text(6pt, $ #v $), x-tick-step: 0.5, y-format: v => text(6pt, $ #v $), y-tick-step: 0.5, ) #let plot-style = ( axes: ( x: ( mark: (fill: black, start: "stealth", end: "stealth"), ), y: ( mark: (fill: black, start: "stealth", end: "stealth"), ), ) ) #let points = ((0, 0), (3, 3), (2,0), (0,2)) #cetz.canvas({ import cetz.plot import cetz.draw: * set-style(..plot-style) plot.plot(..plot-opts, { plot.add(points) plot.add-anchor("first-point", points.last()) }) circle("plot.first-point", fill: red, radius: 0.2) }) /// if no domain is specified,
https://github.com/michidk/cv
https://raw.githubusercontent.com/michidk/cv/main/src/cv-eu.typ
typst
#import "template/mod.typ": * #show: template.with( data: json("../data/resume.json"), displayMugshot: true, debug: false )
https://github.com/Doublonmousse/pandoc-typst-reproducer
https://raw.githubusercontent.com/Doublonmousse/pandoc-typst-reproducer/main/color_issues/saturate.typ
typst
#square( fill: red.saturate(10%) )
https://github.com/EGmux/PCOM-2023.2
https://raw.githubusercontent.com/EGmux/PCOM-2023.2/main/lista2/typstodcs.md
markdown
--- created: 2024-02-15T09:19:32 (UTC -03:00) tags: [] source: https://typst.app/docs/reference/syntax/ author: --- # Syntax – Typst Documentation > ## Excerpt > A compact reference for Typst's syntax. Learn more about the language within markup, math, and code mode. --- Typst is a markup language. This means that you can use simple syntax to accomplish common layout tasks. The lightweight markup syntax is complemented by set and show rules, which let you style your document easily and automatically. All this is backed by a tightly integrated scripting language with built-in and user-defined functions. ## Markup Typst provides built-in markup for the most common document elements. Most of the syntax elements are just shortcuts for a corresponding function. The table below lists all markup that is available and links to the best place to learn more about their syntax and usage. | Name | Example | See | | --- | --- | --- | | Paragraph break | Blank line | [`parbreak`](https://typst.app/docs/reference/model/parbreak/) | | Strong emphasis | `*strong*` | [`strong`](https://typst.app/docs/reference/model/strong/) | | Emphasis | `_emphasis_` | [`emph`](https://typst.app/docs/reference/model/emph/) | | Raw text | `` `print(1)` `` | [`raw`](https://typst.app/docs/reference/text/raw/) | | Link | `https://typst.app/` | [`link`](https://typst.app/docs/reference/model/link/) | | Label | `<intro>` | [`label`](https://typst.app/docs/reference/foundations/label/) | | Reference | `@intro` | [`ref`](https://typst.app/docs/reference/model/ref/) | | Heading | `= Heading` | [`heading`](https://typst.app/docs/reference/model/heading/) | | Bullet list | `- item` | [`list`](https://typst.app/docs/reference/model/list/) | | Numbered list | `+ item` | [`enum`](https://typst.app/docs/reference/model/enum/) | | Term list | `/ Term: description` | [`terms`](https://typst.app/docs/reference/model/terms/) | | Math | `$x^2$` | [Math](https://typst.app/docs/reference/math/) | | Line break | `\` | [`linebreak`](https://typst.app/docs/reference/text/linebreak/) | | Smart quote | `'single' or "double"` | [`smartquote`](https://typst.app/docs/reference/text/smartquote/) | | Symbol shorthand | `~, ---` | [Symbols](https://typst.app/docs/reference/symbols/sym/) | | Code expression | `#rect(width: 1cm)` | [Scripting](https://typst.app/docs/reference/scripting/#expressions) | | Character escape | `Tweet at us \#ad` | [Below](https://typst.app/docs/reference/syntax/#escapes) | | Comment | `/* block */, // line` | [Below](https://typst.app/docs/reference/syntax/#comments) | ## Math mode Math mode is a special markup mode that is used to typeset mathematical formulas. It is entered by wrapping an equation in `$` characters. The equation will be typeset into its own block if it starts and ends with at least one space (e.g. `$ x^2 $`). Inline math can be produced by omitting the whitespace (e.g. `$x^2$`). An overview over the syntax specific to math mode follows: | Name | Example | See | | --- | --- | --- | | Inline math | `$x^2$` | [Math](https://typst.app/docs/reference/math/) | | Block-level math | `$ x^2 $` | [Math](https://typst.app/docs/reference/math/) | | Bottom attachment | `$x_1$` | [`attach`](https://typst.app/docs/reference/math/attach/) | | Top attachment | `$x^2$` | [`attach`](https://typst.app/docs/reference/math/attach/) | | Fraction | `$1 + (a+b)/5$` | [`frac`](https://typst.app/docs/reference/math/frac/) | | Line break | `$x \ y$` | [`linebreak`](https://typst.app/docs/reference/text/linebreak/) | | Alignment point | `$x &= 2 \ &= 3$` | [Math](https://typst.app/docs/reference/math/) | | Variable access | `$#x$, $pi$` | [Math](https://typst.app/docs/reference/math/) | | Field access | `$arrow.r.long$` | [Scripting](https://typst.app/docs/reference/scripting/#fields) | | Implied multiplication | `$x y$` | [Math](https://typst.app/docs/reference/math/) | | Symbol shorthand | `$->, !=$` | [Symbols](https://typst.app/docs/reference/symbols/sym/) | | Text/string in math | `$a "is natural"$` | [Math](https://typst.app/docs/reference/math/) | | Math function call | `$floor(x)$` | [Math](https://typst.app/docs/reference/math/) | | Code expression | `$#rect(width: 1cm)$` | [Scripting](https://typst.app/docs/reference/scripting/#expressions) | | Character escape | `$x\^2$` | [Below](https://typst.app/docs/reference/syntax/#escapes) | | Comment | `$/* comment */$` | [Below](https://typst.app/docs/reference/syntax/#comments) | ## Code mode Within code blocks and expressions, new expressions can start without a leading `#` character. Many syntactic elements are specific to expressions. Below is a table listing all syntax that is available in code mode: | Name | Example | See | | --- | --- | --- | | Variable access | `x` | [Scripting](https://typst.app/docs/reference/scripting/#blocks) | | Any literal | `1pt, "hey"` | [Scripting](https://typst.app/docs/reference/scripting/#expressions) | | Code block | `{ let x = 1; x + 2 }` | [Scripting](https://typst.app/docs/reference/scripting/#blocks) | | Content block | `[*Hello*]` | [Scripting](https://typst.app/docs/reference/scripting/#blocks) | | Parenthesized expression | `(1 + 2)` | [Scripting](https://typst.app/docs/reference/scripting/#blocks) | | Array | `(1, 2, 3)` | [Array](https://typst.app/docs/reference/foundations/array/) | | Dictionary | `(a: "hi", b: 2)` | [Dictionary](https://typst.app/docs/reference/foundations/dictionary/) | | Unary operator | `-x` | [Scripting](https://typst.app/docs/reference/scripting/#operators) | | Binary operator | `x + y` | [Scripting](https://typst.app/docs/reference/scripting/#operators) | | Assignment | `x = 1` | [Scripting](https://typst.app/docs/reference/scripting/#operators) | | Field access | `x.y` | [Scripting](https://typst.app/docs/reference/scripting/#fields) | | Method call | `x.flatten()` | [Scripting](https://typst.app/docs/reference/scripting/#methods) | | Function call | `min(x, y)` | [Function](https://typst.app/docs/reference/foundations/function/) | | Argument spreading | `min(..nums)` | [Arguments](https://typst.app/docs/reference/foundations/arguments/) | | Unnamed function | `(x, y) => x + y` | [Function](https://typst.app/docs/reference/foundations/function/) | | Let binding | `let x = 1` | [Scripting](https://typst.app/docs/reference/scripting/#bindings) | | Named function | `let f(x) = 2 * x` | [Function](https://typst.app/docs/reference/foundations/function/) | | Set rule | `set text(14pt)` | [Styling](https://typst.app/docs/reference/styling/#set-rules) | | Set-if rule | `set text(..) if ..` | [Styling](https://typst.app/docs/reference/styling/#set-rules) | | Show-set rule | `show par: set block(..)` | [Styling](https://typst.app/docs/reference/styling/#show-rules) | | Show rule with function | `show raw: it => {..}` | [Styling](https://typst.app/docs/reference/styling/#show-rules) | | Show-everything rule | `show: columns.with(2)` | [Styling](https://typst.app/docs/reference/styling/#show-rules) | | Conditional | `if x == 1 {..} else {..}` | [Scripting](https://typst.app/docs/reference/scripting/#conditionals) | | For loop | `for x in (1, 2, 3) {..}` | [Scripting](https://typst.app/docs/reference/scripting/#loops) | | While loop | `while x < 10 {..}` | [Scripting](https://typst.app/docs/reference/scripting/#loops) | | Loop control flow | `break, continue` | [Scripting](https://typst.app/docs/reference/scripting/#loops) | | Return from function | `return x` | [Function](https://typst.app/docs/reference/foundations/function/) | | Include module | `include "bar.typ"` | [Scripting](https://typst.app/docs/reference/scripting/#modules) | | Import module | `import "bar.typ"` | [Scripting](https://typst.app/docs/reference/scripting/#modules) | | Import items from module | `import "bar.typ": a, b, c` | [Scripting](https://typst.app/docs/reference/scripting/#modules) | | Comment | `/* block */, // line` | [Below](https://typst.app/docs/reference/syntax/#comments) | Comments are ignored by Typst and will not be included in the output. This is useful to exclude old versions or to add annotations. To comment out a single line, start it with `//`: ``` <span>// our data barely supports</span> <span>// this claim</span> We show with <span>$</span>p &lt; 0.05<span>$</span> that the difference is significant. ``` ![Preview](https://typst.app/assets/docs/4X5qt6Cm6pVAuGK8K_OVtgAAAAAAAAAA.png) Comments can also be wrapped between `/*` and `*/`. In this case, the comment can span over multiple lines: ``` Our study design is as follows: <span>/* Somebody write this up: - 1000 participants. - 2x2 data design. */</span> ``` ![Preview](https://typst.app/assets/docs/A96YIJf5IltsND-ya6kUBwAAAAAAAAAA.png) ## Escape sequences Escape sequences are used to insert special characters that are hard to type or otherwise have special meaning in Typst. To escape a character, precede it with a backslash. To insert any Unicode codepoint, you can write a hexadecimal escape sequence: `\u{1f600}`. The same kind of escape sequences also work in [strings](https://typst.app/docs/reference/foundations/str/). ``` I got an ice cream for <span>\$</span>1.50! <span>\u{1f600}</span> ``` ![Preview](https://typst.app/assets/docs/P9FHfxr4YPQOpp9S0VHHBAAAAAAAAAAA.png)
https://github.com/Dav1com/minerva-report-fcfm
https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/docs/tidy-things.typ
typst
MIT No Attribution
#import "preamble.typ": * #import "@preview/tidy:0.3.0" as tidy #import "../meta.typ" as package-meta #let _main = tidy.parse-module( main-file, name: "minerva", require-all-parameters: true ) #let main = { let main_functions = _main main_functions.variables = main_functions.variables.filter(it => it.type != "module") main_functions } #let main_submodules = { let main_modules = _main main_modules.functions = () main_modules.variables = main_modules.variables.filter(it => it.type == "module") main_modules } #let libs = { let dict = (:) for (name, file) in lib-files { dict.insert(name, tidy.parse-module( file, require-all-parameters: true ) ) } dict } #let show-main = { set heading(numbering: none) show heading.where(level: 2): set heading(numbering: "1.") tidy.show-module(main, show-outline: false, style: package-meta.tidy-styles()) } #let show-libs = { libs.pairs().map((pair) => [ #let name = pair.first() #let lib = pair.last() #set heading(numbering: none) #show heading.where(level: 2): set heading(numbering: "1.") #[== #name] #label(name) #tidy.show-module( lib, show-outline: false, style: package-meta.tidy-styles() ) ]) }
https://github.com/xsro/xsro.github.io
https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/Control-for-Integrator-Systems/2single.typ
typst
#import "lib/lib.typ":ode45,get_signal,op #import "@preview/cetz:0.2.0" #import cetz.plot #import cetz.draw: * = Control Single Integrator System == Bang-Bang Control $dot(x)=-k"sign"(x)+delta$ #columns(2, gutter: 11pt)[ #set par(justify: true) Consider the fisrt order system $dot(x)=u+delta$, $delta$ is the bounded disturbance $|delta|<C$. The first control law is $ u=-k"sign"x $<single_integrator_sign> where $k>C$. Select $ V=1/2 x^2. $<single_integrator_sign_V> Calculate the derivative along the system trajectory: $ dot(V) &=x dot(x) =x (-k"sign"x+delta)\ &=-k|x|+x delta <= -k|x|+|x| |delta|\ &<=-(k-C)|x|<=0 $<single_integrator_sign_dV> This implies $x arrow 0$(Lyapunov direct method) and $dot(x) arrow 0$ (Barbalat's lemma). If so, $-k "sign"(x)+delta arrow 0$? This differential equation should be understood in *Pilippov sense*. The solution here is not a classical(continuously differentiable) solution but a absolutely continuous solution. the solution satisfy the *Pilippov DI* (Pilippov Differential Inclusion) associated with the differential equation. The DI is $ dot(x) in F(t,x)+[-C,C]\ F(t,x)=cases( k &"if" x<0, [-k,k] &"if" x=0, -k &"if" x>0 ) $ This means when $x>0$, we have $dot(x)<0$, and when $x<0$, we have $dot(x)>0$. The system must converges to $x=0$. We also use the concept of *Equivalent Control* describes this feature. Use a low pass filter, we can say $"LPF"("sign"(x))approx delta$. For example, the following low pass filter is used in simulation, #let rhs(t,x)={ let delta=calc.sin(t) let u=-1.1*op.sign(x.x) let T=0.1 let dx=(x:u+delta,uf:(u -(x.uf))/T) dx.insert("u",u) dx.insert("delta",-delta) dx } #let (xout,dxout)=ode45(rhs,10,(x:1,uf:0),0.01,record_step:0.01) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(xout,"uf"),label:$u_"filtered"$) plot.add(get_signal(dxout,"u"),label:$u$) plot.add(get_signal(dxout,"delta"),label:$-delta$) }, y-label:"value", x-label:"time", ) }) The filter is $ U_"filtered"(s)/U(s)=1/(T s +1 )\ T dot(u)_"filtered"+u_"filtered"=u $ === Finite-time convergence Another important feature of this system is finite-time stability. From @single_integrator_sign_V and @single_integrator_sign_dV, we have $ dot(V)(t)<=-(k-C) sqrt(2V(t)) $ Let $a=(k-C)sqrt(2)$ and integrate it. we get $ (d V(t))/sqrt(V(t))<=-a d t \ 2 sqrt(V(t)) - 2 sqrt(V(0))<=-a t\ sqrt(V(t))<=sqrt(V(0))-a/2 t\ $ Consequently, $V(t)$ reaches zero in a finite time $t_r$ that is bounded by $ t_r<=2sqrt(V(0))/a=(|x(0)|)/(k-C) $ #cetz.canvas({ plot.plot( size: (6,2), axis-style: "school-book", x-tick-step: 2, y-tick-step:1, { for i in (1,2,3){ let rhs(t,x)={ let delta=calc.sin(t) let u=-1.1*op.sign(x.x) let T=0.1 let dx=(x:u+delta,uf:(u -(x.uf))/T) dx.insert("u",u) dx.insert("delta",-delta) dx } let (xout,dxout)=ode45(rhs,6,(x:i,uf:0),0.01,record_step:0.01) plot.add(get_signal(xout,"x"),label:$x(0)=#i$) } }, y-label:"value", x-label:"time", ) }) ] #pagebreak() == SMC Chattering Elimination: Quasi-Sliding Mode In many practical control systems, including DC motors and aircraft control, it is important to avoid control chattering by providing continuous/smooth signals. One obvious solution to make the control function continuous/smooth is to approximate the discontinuous function $v(sigma)=-rho "sign" (sigma)$ by some continuous/smooth function. For instance, it could be replaced by a "sigmoid function". #let plot_sign()={ cetz.canvas({ plot.plot(size: (2,2),axis-style: "school-book", x-tick-step: none, y-tick-step: none, { plot.add(domain: (-3, 0), x=>-1,style: (stroke: red)) plot.add(domain: (0, 3), x=>1,style: (stroke: red)) plot.add(((0,0),),mark:"o",mark-style:(stroke:red,fill: red)) }) }) } #let plot_signv(func)={ cetz.canvas({ plot.plot(size: (2,2),axis-style: "school-book", x-tick-step: none, y-tick-step: none, { plot.add(domain: (-3, 3), func,style: (stroke: red)) }) }) } #figure( table( align: horizon, columns: 6, [], $"sign"(x)$, $"sat"(x/epsilon)$, $x/(abs(x)+epsilon)$,$tanh(x)$,$(1-e^(-T x))/(1+e^(-T x))$, [continuity], [discontinuous], [continuous], [smooth #footnote("I am not sure about this")],[smooth],[smooth], [], [#plot_sign()], [ #let sat(a)={ if calc.abs(a)>1{ a/calc.abs(a) }else{ a } } #plot_signv(x=>sat(x/0.5)) $epsilon=0.5$ ], [ #plot_signv(x=>x/(calc.abs(x)+0.5)) $epsilon=0.5$ ], [ #plot_signv(x=>calc.tanh(x)) ], [ #plot_signv(x=>(1-calc.exp(-5*x))/(1+calc.exp(-5*x)),) $T=5$ ], ), caption: [replaced $"sign"$ by a “sigmoid function”], ) #pagebreak() == SMC Chattering Attenuation: Asymptotic Sliding Mode #box(height: 210/16*9mm, columns(2, gutter: 11pt)[ *Assume $dot(delta)$ is also bounded and $dot(x)$ is measurable.* Let $|dot(delta)|<=C_1$. Define $s=x+c dot(x)$. The control law is given by $ dot(x)=u+delta\ dot(u)=v\ v=-rho "sign"(s)-1/c u $ Select $ V=1/2 s^2 $ Calculate the derivative along the system trajectory: $ dot(V)&=s dot(s)=s(dot(x)+c dot.double(x))\ &= s(u+delta+c(v+dot(delta)))\ &= s(- c rho "sign"(s) +delta + c dot(delta))\ &<=-(c rho - C-c C_1)|s| $ $s$ converges to zero in finite time while $x$ converges to zero asymptotically. #let rhs(t,s)={ let C1=1 // upper bound of disturbance let C2=1 // upper bound of derivative of disturbance let c=1 let delta=C1 * calc.sin(C2/C1*t) let rho=3 let x=s.x;let u=s.u; let dx=(u)+delta let s=x+c *(dx) let v=-rho*op.sign(s)-1/c*(u) let dx=(x:dx,u:v,s:s) dx } #let (xout,dxout)=ode45(rhs,10,(x:1,u:0.),0.01,record_step:0.01) #cetz.canvas({ plot.plot( size: (10,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(dxout,"s"),label:$s$) }, y-label:"value", x-label:"time", ) }) #cetz.canvas({ plot.plot( size: (10,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:2, { plot.add(get_signal(dxout,"u"),label:$v$) plot.add(get_signal(xout,"u"),label:$u$) }, y-label:"value", x-label:"time", ) }) ]) #pagebreak() == Integral Sliding Mode Control #box(height: 210/16*9mm, columns(2, gutter: 11pt)[ Assuming the initial conditions are known, we can split the control with $ dot(x)=u+delta \ u=u_1+u_2=-rho_1 "sign" (s)-k x $ The auxiliary sliding variable is designed as $ cases(s=x-z,dot(z)=u_2=-k x,) $ then $ dot(s)=dot(x)-dot(z)=u+delta-u_2=u_1-delta $ Select $ u_1=-rho_1 "sign" (s) $ Then $ s=0 arrow.double x=z arrow.double u_2=dot(z)=dot(x) $ So design $u_2=-k x$ such that $dot(x)=-k x$ Now we will address the issue of starting the auxiliary sliding mode from the very beginning without any reaching phase. In order to achieve it we have to enforce the initial condition $s(0)=0 $ $ s(0)=0 arrow.double z(0)=x(0) $ Advantage: We can set $z(0)$ to keep $s(0)=0$, The system is starting from auxiliary sliding surface. - Elimination of Reaching Phase: The system state always starts on the sliding surface, simplifying control design. - Improved Robustness: ISMC extends this robustness to the entire state space, making the system less sensitive to uncertainties. - Guaranteed Stability: Once the sliding mode is achieved, ISMC guarantees the system's stability. This provides a strong theoretical foundation for the control performance. ]) #pagebreak() #columns(2)[ The first simulation demonstrates the traditional SMC is sensitive to disturbance in reaching phase. #let rhs(t,x)={ let delta=op.sign(calc.sin(10*t)-0.5) let u=-1.1*op.sign(x.x) let T=0.1 let dx=(x:u+delta,uf:(u -(x.uf))/T) dx.insert("u",u) dx.insert("delta",-delta) dx } #let (xout,dxout)=ode45(rhs,10,(x:4,uf:0),0.01,record_step:0.01) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(xout,"uf"),label:$u_"filtered"$) plot.add(get_signal(dxout,"u"),label:$u$) plot.add(get_signal(dxout,"delta"),label:$-delta$) }, y-label:"value", x-label:"time", ) }) The second one uses integral SMC is #let rhs(t,x)={ let delta=op.sign(calc.sin(10*t)-0.5) let rho1=3 let k=1 let s=(x.x)-(x.z) let u1=-rho1*op.sign(s) let u2=-k*x.x let u=u1+u2 let T=0.1 let dx=(x:u+delta,z:u2) dx.insert("s",s) dx.insert("u1",u1) dx.insert("u2",u2) dx.insert("u",u) dx.insert("delta",-delta) dx } #let (xout,dxout)=ode45(rhs,10,(x:4,z:4),0.01,record_step:0.01) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(dxout,"s"),label:$s$) plot.add(get_signal(dxout,"delta"),label:$-delta$) }, y-label:"value", x-label:"time", ) }) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:3, { plot.add(get_signal(dxout,"u1"),label:$u_1$) plot.add(get_signal(dxout,"u2"),label:$u_2$) plot.add(get_signal(dxout,"u"),label:$u$) }, y-label:"value", x-label:"time", ) }) ] #pagebreak() == Super Twist Algorithm (STA) #box(height: 210/16*9mm, columns(2, gutter: 11pt)[ $ dot(x)=u+delta \ u=-c |x|^(1/2) "sign"(x)-w\ dot(w)=b "sign"(x) $ - The super-twisting control is a *second-order* sliding mode control, since it drives both $sigma arrow 0$ and $dot(sigma) arrow 0$ in finite time. (Second-Order Sliding Mode or 2-SM means the control law drives the sliding variable and its derivative to zero in *finite time*) - The super-twisting control is *continuous*. The parameters $c$ and $b$ are quite difficult to select. The parameters given by @shtesselSlidingModeControl2014 are $ c=1.5 sqrt(C), b=1.1 C $ @SEEBER2017241 gives a condition $ b > C , c > sqrt(b + C) $ #let x0=(x:1,w:0) #let rhs(t,x)={ let C=1 let delta=C*calc.sin(t) let c=1.5 *calc.sqrt(C) let b=1.1 *C let u=-c*calc.sqrt(calc.abs(x.x))*op.sign(x.x)-x.w let dx=(x:u+delta,w:b *op.sign(x.x)); dx.insert("u",u) dx.insert("delta",delta) dx } #let (xout,dxout)=ode45(rhs,10,(x:1,w:0),0.05) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 1, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(dxout,"u"),label:$u$) }, y-label:"value", x-label:"time", ) }) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 1, y-tick-step:1, { plot.add(get_signal(xout,"w"),label:$w$) plot.add(get_signal(dxout,"delta"),label:$delta$) }, y-label:"value", x-label:"time", ) }) #let x0=(x:1,w:0) #let rhs(t,x)={ let C=0.1 let delta1=C*(calc.sin(2*t)) let delta2=C*calc.cos(t) let c=1.5 *calc.sqrt(C) let b=1.1 *C let u=-c*calc.sqrt(calc.abs(x.x))*op.sign(x.x)-x.w let dx=(x:u+delta1,w:b *op.sign(x.x)+delta2); dx.insert("u",u) dx.insert("delta",delta1) dx } #let (xout,dxout)=ode45(rhs,10,(x:1,w:0),0.05) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 1, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(dxout,"u"),label:$u$) }, y-label:"value", x-label:"time", ) }) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 1, y-tick-step:1, { plot.add(get_signal(xout,"w"),label:$w$) plot.add(get_signal(dxout,"delta"),label:$delta$) }, y-label:"value", x-label:"time", ) }) ] ) #pagebreak() == RISE for single integrator #columns(2)[ Here we follow the design of RISE @xianContinuousAsymptoticTracking2004 and apply them to single integrator. $ dot(x)=u+delta $ where #text(red)[$delta in cal(C)^2$ (both $abs(delta)$ and $abs(dot(delta))$ is bounded).] The main idea of RISE is using a Lyapunov function contains $delta$. Let $L=(alpha x+dot(x))(dot(delta)-beta "sign"(x))$, we calculate $ V&=1/2 (alpha x+dot(x))^2+xi_b-P\ dot(V)&=(alpha x+dot(x))(alpha dot(x)+dot(u)+dot(delta))-L\ &=(alpha x+dot(x))(alpha dot(x)+dot(u)+dot(delta)-dot(delta)+beta "sign"(x))\ &=(alpha x+dot(x))(alpha dot(x)+dot(u)+beta "sign"(x))\ $ so we design $ dot(u)=-alpha dot(x) -beta "sign"(x)-k_s alpha (alpha x+dot(x) ) \ u=-(k_s+1)alpha x(t)+(k_s+1)alpha x(0) - w\ dot(w)=k_s alpha^2 x+ beta "sign"(x) $ #let x0=(x:1,w:0) #let rhs(t,x)={ let alpha=1; let ks=20; let beta=1+1/alpha +0.1 let delta=calc.sin(t) let u=-(ks+1)*alpha*((x.x)-(x0.x))-(x.w); let dw=ks*alpha*alpha *(x.x)+beta *op.sign(x.x); let dx=(x:u+delta,w:dw); dx.insert("werror",x.w -delta) dx.insert("u",u) dx.insert("delta",-delta) dx } #let (xout,dxout)=ode45(rhs,16,(x:1,w:0),0.01) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:1, { plot.add(get_signal(xout,"x"),label:$x$) plot.add(get_signal(dxout,"u"),label:$u$) plot.add(get_signal(dxout,"delta"),label:$-delta$) }, y-label:"value", x-label:"time", ) }) #cetz.canvas({ plot.plot( size: (8,2), axis-style: "school-book", x-tick-step: 5, y-tick-step:5, { plot.add(get_signal(dxout,"werror"),label:$w-delta$) plot.add(get_signal(xout,"w"),label:$w$) }, y-label:"value", x-label:"time", ) }) #text(size:9pt,$ P=&integral_0^t L(tau) d tau\ =&integral_0^t alpha x(dot(delta)-beta "sign"(x)) d tau +integral_0^t dot(x)(dot(delta)-beta "sign"(x)) d tau\ =&integral_0^t alpha x(dot(delta)-beta "sign"(x)) d tau +x dot(delta)|_0^t - integral_0^t x dot.double(delta)d tau -integral_0^t dot(x)beta "sign"(x)d tau\ =&integral_0^t alpha x(dot(delta)-1/alpha dot.double(delta))-alpha beta |x| d tau +x dot(delta) |_0^t -beta abs(x)|_0^t\ <=&xi_b := integral_0^t alpha abs(x) (abs(dot(delta))+1/alpha abs(dot.double(delta))-beta) d tau +abs(x(t)) (abs(dot(delta)(t))-beta) -x(0) dot(delta)(0)+beta abs(x(0)) $) ] #pagebreak()
https://github.com/Goldan32/brilliant-cv
https://raw.githubusercontent.com/Goldan32/brilliant-cv/main/modules/education.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Education") #cvEntry( title: [Master of Science in Electrical Engineering], society: [Budapest University of Technology and Economics], date: [2022 - 2024], location: [Budapest], logo: "../src/logos/bme.png", description: [Specialization: #list( [Computer-Based Systems], [FPGA-Based Systems] ) ] ) #cvEntry( title: [Bachelor of Science in Electrical Engineering], society: [Budapest University of Technology and Economics], date: [2018 - 2022], location: [Budapest], logo: "../src/logos/bme.png", description: [Specialization: #list( [Embedded and Control Systems] ) ] )
https://github.com/Rhinemann/mage-hack
https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Consequences.typ
typst
#import "../templates/interior_template.typ": * #show: chapter.with(chapter_name: "Consequences") = Consequences #show: columns.with(2, gutter: 1em) While playing Mage characters may face consequences of dealing with the danger. Hits of fiery bolts, stress after an all nighter, twisted ankles, this is what the following chapter will describe. #block(breakable: false)[ == Complications A complication is an unhelpful temporary trait that the opposition includes in their dice pool to make the opposed roll harder for the character with the complication. Complications are given descriptive names and a die rating, starting at #spec_c.d6. ] #block(breakable: false)[ === Creating Complications When a player rolls a hitch on any of their dice, the Storyteller can hand over a #spec_c.pp and to create a complication instead of adding that die to the doom pool. This doesn't affect the success or failure of the roll — a complication means something else has gone wrong, making life difficult. ] Complications start at #spec_c.d6, and additional hitches in the same roll step up the complication without the Storyteller giving the player more #spec_c.pp. The Storyteller may choose to create multiple complications if there is more than one hitch, but each new complication requires handing over a #spec_c.pp. If the player rolls a botch, the Storyteller creates a #spec_c.d6 complication without giving the player a #spec_c.pp, and steps it up for each hitch past the first. Complications are persistent and last until either the PC has recovered from them, or the complication is made irrelevant. #block(breakable: false)[ === Worsening Complications Whenever a player or the Storyteller has the option to give a character a complication, they can instead choose to step up an existing complication, making it worse for the affected character. ] Generally, only one complication applies to a specific hindrance or problem. To make a complication worse, it should be stepped up. #block(breakable: false)[ === Using Complications Whenever a player or the Storyteller is rolling against a character that has a relevant complication, they may add it to their dice pool. Doing so doesn't cost anything, and there's no limit to how many applicable complications can be included in a dice pool, nor is there a limit on how many complications a character can have. ] #block(breakable: false)[ === #spec_c.d4 Complication If a complication is stepped down to a #spec_c.d4, the very next time the complication might affect your character, you add it to your own dice pool and earn a #spec_c.pp (much like a distinction being used with the Hinder SFX). ] Immediately after it's used this way, it's stepped down to zero and eliminated—unless the dice come up with one or more hitches, in which case the Storyteller may choose to activate them and step up the complication to 6 or more. #block(breakable: false)[ == Stress In addition to complications each character also has four stress tracks, these represent a type of a complication that is likely to occur often and will be used often, and thus have some additional rules. ] In addition to complications being used to represent temporary traits that hinder the character's actions stress is a measure of your damage and injury. There are four types of stress: / Harmed: Pain and injury. / Unsound: Confusion and brain fog. / Rattled: Fear and anxiety. / Tired: Exhaustion. #block(breakable: false)[ === Inflicting Stress Whenever a character fails an action that causes harm as a consequence they receive a #spec_c.d6 die of appropriate stress. Being a target of a successful attack inflicts stress equal to the effect die of the attack. Some SFX can also inflict stress upon a character. ] Whenever stress is inflicted, check your stress die, if the stress die rating is equal to or greater than the new stress die, step up your stress die, if the stress die rating is lower than the new stress die or the PC has no stress, inflict stress equal to the new stress die. #block(breakable: false)[ ==== Stressed Out If any stress die rating is ever stepped up past #spec_c.d12, the character is taken out (or stressed out) and no longer takes part in the scene. By default, you can't spend a #spec_c.pp to delay this effect, though certain SFX may allow to do that. When you're stressed out, you are assumed to have #spec_c.d12 stress for the purposes of taking any additional stress, even though you can no longer act in the scene. ] #block(breakable: false)[ === Using Stress Just like a complication, whenever a PC engages in a test or contest where their stress would make things more difficult for them, the Storyteller (or an opposing PC) can add the stress die to their opposition pool as if it were an asset. ] Stress rated at #spec_c.d4 functions just like a complication rated at #spec_c.d4; it goes into a player's dice pool instead of being added to the opposition dice pool and earns the player a #spec_c.pp. Right after that test or contest, it either goes away or — if the player rolls a hitch on one of their dice — gets stepped up as the injury gets worse. Only one type of stress can be used against a character at any given time, unless the Storyteller pays the player a #spec_c.pp to add an additional stress die to the opposition dice pool. Characters can be affected by both stress and complications at the same time, however. #block(breakable: false)[ === Recovering Stress All stress die ratings are always stepped down by one during any scene specifically framed to act as a rest period, downtime, or transition between action-heavy scenes. If a character takes stress in one scene from a battle, and the next scene is another battle soon after the first without any time spent resting up, then no stress is recovered. ] To recover any remaining stress, characters can attempt a recovery test vs a dice pool consisting of the stress die and a base difficulty of #spec_c.d8 #spec_c.d8. The Storyteller may rule that other traits affect the roll, similar to a standard test. The PC or their circumstances must be capable of improving the situation to make a roll. When the test is complete, one of the following happens: - If the PC beat the difficulty and the effect die is greater than the stress, the stress is eliminated. - If the PC beat the difficulty and the effect die is equal to or smaller than the stress, the stress is stepped down by one. Time must pass before another test can be made to recover the stress. - If the PC failed to beat the difficulty, the stress remains as it is. - If the PC beat the difficulty but rolled a hitch, the Storyteller may hand over a #spec_c.pp and introduce a new stress or complication related to the one that was just recovered. - If the PC failed to beat the difficulty and rolled a hitch, the stress is stepped up by one step for every hitch rolled. #block(breakable: false)[ == Trauma Trauma is long-term stress. Any time a PC's stress is stepped up past #spec_c.d12, they're stressed out of the scene, and they gain #spec_c.d6 trauma of the same type of stress that just increased. Trauma functions just like stress but is much harder to recover. ] During any scene in which a character is stressed out and has taken trauma, additional stress to the character goes directly to trauma. Once trauma is stepped up beyond #spec_c.d12, the character is permanently out of options — they're dead, hopelessly incoherent, lost to their own psyche, or whatever seems most appropriate. If the next scene is a recovery, transition, or otherwise restful scene in which the PC can be taken care of or allowed to recuperate, the PC's stress automatically steps down by one, but the trauma remains at the level it was at the end of the previous scene. Recovering trauma requires a test using any appropriate traits vs a base difficulty of #spec_c.d8 #spec_c.d8 plus the trauma die. When the test is complete, one of the following happens: • If you beat the difficulty, the trauma die rating is stepped down by one. • If you fail to beat the difficulty, the trauma does not get any better or worse. You can't try to recover that trauma again until time passes. • If you beat the difficulty but roll a hitch, the GM may hand over a #spec_c.pp and introduce either a complication that will hinder the PC in the next scene or inflict stress of a different type than the trauma that was being recovered, starting at #spec_c.d6 (or stepping up by one if the PC already had stress of that type). • If you fail to beat the difficulty and roll one or more hitches, the trauma gets worse, stepping up by one for each hitch rolled. If this steps the trauma up past #spec_c.d12, that's all, folks.