repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/augustebaum/epfl-thesis-typst | https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/main/ch2_figures_tables.typ | typst | MIT License | #import "@preview/scholarly-epfl-thesis:0.1.1": flex-caption
= Tables and Figures
In this chapter we will see some examples of tables and figures.
== Tables
Let's see how to make a well designed table.
#let my-table = "figure(
table(
columns: 3,
align: center,
table.hline(),
table.header(
[name], [weight], [food],
),
table.hline(stroke: 0.5pt),
[mouse], [10 g], [cheese],
[cat], [1 kg], [mice],
[dog], [10 kg], [cats],
[t-rex], [10 Mg], [dogs],
table.hline(),
),
caption: [A floating table.]
)"
#eval(my-table) <tab:esempio>
#lorem(20)
@tab:esempio is a floating table and was obtained with the following code:
#raw(block: true, lang: "typst", my-table)
#lorem(40)
== Figures
Let's see now how to put one or several images in your text. caption:
flex-caption([A floating figure with text typeset in "Utopia Latex", a font
provided in the template-folder for typesetting figures with greek characters.
The text has been "outlined" for best compatibility with the repro during the
printing.], [A floating figure]),
#let my-figure = "figure(
image(\"../images/galleria_stampe.jpg\", width: 50%),
caption: [A floating figure (the lithograph _Galleria di stampe_, of M.~Escher, obtained from http://www.mcescher.com/).]
)"
#eval(my-figure) <fig:galleria>
#figure(
image("../images/galleria_stampe.jpg", width: 50%), caption: flex-caption(
[A floating figure (the lithograph _Galleria di stampe_, of M.~Escher, obtained
from http://www.mcescher.com/).], [A floating figure],
),
)
@fig:galleria is a floating figure and was obtained with the following code:
#raw(block: true, lang: "typst", my-figure)
#lorem(200)
#figure(
// Typst doesn't yet support including PDFs, but you can convert PDF files to SVG with pdf2svg.
// https://github.com/typst/typst/issues/145
image("../images/some_vector_graphics.svg"), caption: flex-caption(
[A floating figure with text typeset in "Utopia Latex", a font provided in the
template-folder for typesetting figures with greek characters. The text has been "outlined"
for best compatibility with the repro during the printing.], [A floating figure],
),
) <fig:vector_graphics>
// Subfigures are a work in progress.
// One potential candidate might be `subpar`, but it's still a WIP
// https://github.com/tingerrr/subpar
#show figure.where(kind: "fig1"): set figure(numbering: "(a)", supplement: [], gap: 5pt)
#figure(
grid(
columns: 2, gutter: 10pt, row-gutter: 1.5em, figure(
image("../images/lorem.jpg", width: 100%), caption: [Asia personas duo], kind: "fig1",
), figure(
image("../images/ipsum.jpg", width: 100%), caption: [Pan ma si], kind: "fig1",
), figure(
image("../images/dolor.jpg", width: 100%), caption: [Methodicamente o uno], kind: "fig1",
), figure(
image("../images/sit.jpg", width: 100%), caption: [Titulo debitas], kind: "fig1",
),
), caption: [Tu duo titulo debitas latente],
)
#lorem(100)
#lorem(100)
#lorem(100)
#lorem(100)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/044%20-%20Innistrad%3A%20Crimson%20Vow/007_Episode%204%3A%20The%20Wedding%20Crashers.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 4: The Wedding Crashers",
set_name: "Innistrad: Crimson Vow",
story_date: datetime(day: 17, month: 11, year: 2021),
author: "<NAME>",
doc
)
A spear of light shatters the windows of Voldaren Manor. Invitation wards crumble, scattering ash-like on the winds. The air in Stensia is bright and clear for the first time in what feels like months, as clear as the goals of the gathered hopefuls.
Tonight, they break down the doors of this awful castle. Tonight, they fight tooth, nail, claw, and sword to take back the day.
#figure(image("007_Episode 4: The Wedding Crashers/01.jpg", width: 100%), caption: [Sigarda's Summons | Art by: Nestor Ossandon Leal], supplement: none, numbering: none)
Arlinn can't give the order fast enough. The moment she sees the angelic plume of light, she shouts to the others, "Now!"
But they are already moving, holiness gilding them like saints, swords raised, and stallions rearing. Adeline is ahead of the pack, Chandra sitting behind her; Teferi hastens the footsteps of the surrounding foot soldiers as much as he can. The guards at the gates stand no chance against the gathered masses. Arlinn doesn't see who takes them down, only the lances piercing their chests, but she does taste their blood on the wind.
Her senses sharpen. She sees beyond the gates: from the narrow walkway, trailing thin as thread above the abyss, to the manor's sick tapestry. All of it will be torn down. The thought's a satisfying one. It was like her mother always used to say—didn't matter how nice the pie looked, if you filled it with hot fish, it'd still taste rotten. And vampires left a rotten taste in everything they touched.
Kaya's hand on her shoulder brings her back to the present moment—to the reality of it, instead of Arlinn's far-flung musings. "We've got to get going," she says. "Otherwise, there isn't gonna be much left for us."
She's right. Arlinn's learned that Kaya's right about a lot of things. After all of this is over, she hopes the two of them can get to know each other better; Kaya, out of all the other planeswalkers, understood the delicate balance of life and death that so characterized Innistrad. And understanding Innistrad meant understanding Arlinn.
"Try to keep up," she says, smiling.
Kaya rolls her eyes—but she doesn't back down.
The two of them join the crowd: cathars mounted and unmounted, priests bearing herons and priests bearing Avacynian collars, and farmers who have lost their families.
Onward across the bridge, toward that den of depravity, the rush of the living and the mortal.
Onward the lances, onward the hammers and shields, torches and pitchforks, the holy tomes and blessed blades.
And downward come the bats. Distant, at first, easily mistaken for pieces of falling ash, but the sound soon drowns out that hope. Screeching pierces her sensitive ears; Arlinn covers one and tucks the other against her shoulder to try and block out the cacophony. It's no use.
But what is useful are the bolts of magic hurled over her shoulder. Arrows, too, soon find their marks. As the bats descend, hungry for blood, the witches and archers are eager to meet them. Fur sizzles; the screeching worsens—and then goes silent. Her ears are still ringing as the bats go down. She can't hear the crunch of their bones beneath the boots of their makeshift army, but she can feel it.
She can feel the shift beneath her, too, as they move from simple stone to carefully curated marble. Up ahead, at the secondary gates, the guards have already been overwhelmed, floating face down in pools of blood. Maybe Kaya's right. If they aren't quick, there's hardly going to be anything left.
But even a crowd of this size has trouble with gates.
Kaya and Arlinn make their way through the crowd. It's easy enough—many part for their erstwhile leader and her comrade in arms. Adeline, Teferi, and Chandra make up the vanguard standing before the great doors.
Teferi tilts his head up, then shakes his head with a sigh. "Awful taste."
"That's why we should light the whole thing on fire," Chandra says.
"You mean the door, don't you?" Adeline asks.
Chandra looks back toward her, smile straining. "Right~just the door."
Flames spiral around her arms. Full of swagger, she advances, holding out her hands before her.
Arlinn has half a mind to stop her. Fire's hard to deal with, after all, and while it's harmful to vampires, it's harmful to their group, too.
But Avacyn preserve her, she just can't be mad about it. There's something satisfying about imagining Olivia's smug face burn.
Teferi taps his staff against the ground. As amused as he is by the sight, they don't have much time to waste. The fire burns hotter, brighter, and faster—and soon the door before them is only ash.
This is where the real assault begins.
All of <NAME> is open before them. Arlinn's never been, personally, but she's heard the stories. One wrong turn, and you'll never be heard from again. But that only applied if you wandered in alone.
Arlinn always traveled with a pack. A pang of sadness follows the thought. Streak, Boulder, Patience, and Redtooth. If she tried, she could imagine where they might be right now—somewhere with springy earth beneath their paws. Somewhere that smelled of pine.
She feels alone.
She knows she isn't.
The light up ahead is proof of that.
#figure(image("007_Episode 4: The Wedding Crashers/02.jpg", width: 100%), caption: [Resistance Squad | Art by: <NAME>], supplement: none, numbering: none)
Mounted cathars break off from the crowd, taking to the courtyards and gardens, swords and lances ready to mete out justice. Chandra and Adeline go with them, Adeline mounting her charger before helping Chandra up behind her.
Ranks of guards armed with golden weapons come to meet their charge, their armor more ornamental than functional. Arrows and bolts crash into the first line of defense: farmers with makeshift shields, old soldiers standing next to them. A return volley soon follows. Arlinn picks up a bow and lets loose herself. Hard to see where her arrow lands in all the chaos, but someone's hitting the enemy.
"Didn't know you were such a good shot," Kaya says.
Arlinn glances toward her. Kaya's eyes are gleaming a faint silver. There's a strange taste on Arlinn's tongue, and a high-pitched sound she can't seem to place.
"Can't always use my teeth to hunt," says Arlinn. "Everything all right?"
A javelin comes their way, soaring right through Kaya and clattering uselessly against a beheaded statue. "There are spirits here, Arlinn. And they're #emph[very ] angry."
Arlinn finds herself grinning. "Good. Think you can get them to help us out?"
"I'll see about cutting them loose," Kaya says. She returns the smile—but something else catches her attention. She looks toward the light. "Wait. I don't think I'm alone. There's someone else calling out to me."
Arlinn looks over her shoulder. The light must be coming from the ballroom; the hallways open not too far down. And those guards have got to be coming from somewhere.
Just what was going on in there?
"Who?"
"I think~I think it's Katilda."
Warmth in Arlinn's chest, as fortifying as her favorite ale. "Even better."
Kaya nods. "You keep going on ahead. I'll see about our backup. It's time the Voldarens paid their debts."
And, just like the ghosts, Arlinn doesn't need to be told twice. She trusts Kaya. She trusts Teferi. She trusts Chandra and Adeline. And—Avacyn's mercy—she trusts Sorin, too. When the time comes to save Innistrad, he'll do the right thing, she's sure of it.
It's only that she wants to be there just in case.
The guards are in ragged shape to begin with. Fighting them is hard work—fighting vampires always is—but easier than it should be. Vibrant shards of glass jut from their pallid skin; their balance is so far off that Arlinn hardly takes a single blow making her way through them. Blood slicks the marbled floors of <NAME>—and this time it belongs to the leeches themselves.
It isn't just the vampires themselves that fall.
It's the statues, toppled over; polished stone made jagged.
It's the fountains of blood, smashed apart; priests working in tandem to purify the tainted.
It's the tapestries, the chandeliers, the fine carpets, and the extravagant furniture. A fiery anger burns in the heart of Innistrad. The shouts echoing down the hallway aren't simple war cries—they're more than that. Howls of agony, affirmations of life, the cathartic wails of a people who have lived in fear for far too long.
Vampires built this place on the backs of mortals.
Mortals will tear it asunder.
By the time they break through to the ballroom, Arlinn feels that righteous anger within her, too. Her inner beast struggles against its leash. Tovolar would tell her to set it loose upon these bloodsuckers.
She doesn't #emph[want ] to agree with him.
Not yet.
But she nearly loses control when she breaks through to the ballroom.
To see Sigarda's bloodied wings, to see the fervor consuming her as her sickle reaps vampiric heads—Arlinn isn't sure what to think. It's a sight as grisly as it is invigorating. A coppery taste sticks to the roof of Arlinn's mouth. The Church could be as bloody as any werewolf pack.
And there are the others, too: more guards, some bold enough to attack Sigarda directly; the partygoers going bestial at the sight of the intruders. As she scans the room for the key—and for Sorin—there's almost too much to take in. Torn gowns, bats swirling in the air along with petals of blood, the shattered stained-glass window, fountains torn, and buffet tables broken in two.
It's not getting easier anytime soon.
But she has to get through them somehow.
Ahead, ducking beneath the swing of a blade, tearing through silk and lace to claw at her attacker: a hopped-up Markov duelist. She's fought his type before. Fancy swordplay gets you lots of places, but Arlinn doesn't need a sword to fight.
The blood gushing down his side doesn't slow him, not yet. Must have glutted himself before all this started—he smells of many lives mingled together, his lips smeared thick with red. "No one invited the #emph[fashion disasters] ."
His next cut is fast. If he was attacking anyone else, it might even have been too fast to follow. But Arlinn's not alone, and the waves of magic slowing the blow down speak to that. She has enough time to drive her knee into his stomach. The vampire gurgles as the air's knocked out of him; his sword clatters to the ground.
She could kill him. Tear his throat out. He'd deserve it, all the things he must have done. A vampire's existence necessitates the suffering of others.
But that's what Tovolar would do.
Arlinn hefts him overhead and hurls him into a column.
If he has any sense, he won't come after her again.
She doesn't have time to see if he will. Through the melee again, trying her best to cast aside the memories of Harvesttide. This won't be the same. It can't be.
The best way to stop all this is to find the key. But where is it? She sniffs at the air, hoping to get the scent, but there's too much magic to make any sense of it. Sigarda's, likely—it's coming off her in waves as she fights off the lion's share of guards.
Arlinn's eyes will have to serve instead.
The second she spots Olivia, the cavalry arrives. Cathars break in through the windows, their warhorses stained red. Bolts of magic shoot straight for the progenitor vampire as some of the priests follow.
And when the priests see who's in the ballroom with them, a chorus of cheers rises.
Olivia's not cheering. "You~all of you! You're ruining my #emph[wedding day] !" she roars from atop the stairs.
"Hand over the key!" Arlinn answers. A hundred voices echo her—#emph[the key, the key!]
So many that the walls start to shake.
#emph[The key, the key, the ki. . .ki. . .kill.]
Wait. Those aren't just the army's voices. And the humming in the air—something's happening. All around them the air itself coalesces into something #emph[else] . Something old.
Geists. Arlinn can see their shapes now: servants and knights, nobles and farmers. There must be hundreds of them, all materializing at once, ghostly flames alight with anger.
#emph[You killed us.]
The voices of the dead carry well.
Their weapons, she's relieved to see, do too. Like a wave of spectral force, the geists crash against their former oppressors. And among the crowd, a familiar headdress stands out: Katilda. Arlinn doesn't need to be told to follow her—the path ahead glows a faint green, like moss on full moon nights.
Arlinn charges up the steps.
Olivia takes to the air—or tries to. She doesn't get very far before a familiar silhouette forms in the air behind her. Kaya plunges a spectral dagger into Olivia's fell train. Ordinary fabric would tear asunder. This magical fabric does, too—and, like blood from a wound, the geists trapped within the train burst free.
Olivia's scream is a hideous thing. She thrashes, sending Kaya tumbling. If she hits the tile, there's going to be blood.
Arlinn can't take any chances. She leaps into the air, catching Kaya mid-fall, landing only an instant later. But that's long enough for Olivia to flee: Arlinn looks up just in time to spot her tattered train ducking into a hallway.
"Leave the fight to us," Kaya says. "Go."
#figure(image("007_Episode 4: The Wedding Crashers/03.jpg", width: 100%), caption: [Kaya, Geist Hunter | Art by: Ryan Pancoast], supplement: none, numbering: none)
Arlinn spares a glance over her shoulder—at the angels, the mortals, the immortals, and the ghosts. Somewhere in that din is Sorin. She can't catch sight of him here. She doesn't have time to search.
She nods. "Keep them safe."
It's a big ask, and she knows it is. People are going to die here today. She wishes they didn't have to.
But all Arlinn can do is make sure their sacrifices are worth it.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"It didn't have to be this way."
The slow, careful voice echoes in the chamber. Over the bubbling and boiling of blood, it reigns supreme. Maybe that's because Sorin's spent so much time listening to it already. Once, it told him stories.
"You're right," he calls back. "Grandfather, you know this is foolish. She's only using you."
His own voice sounds strange here. The plaque outside read "Sanguitorium"—a ridiculous name, but an accurate one. This must be where the Voldarens kept their stores for lean times.
Not that there were ever lean times for the Voldarens.
When Sigarda took to the sky, Edgar fled. He knew better than anyone an angel's wrath. Sorin followed. By then, Arlinn and her group had already breached the door. They'd handle getting the key.
But no one else could confront Edgar Markov.
Now here they were, among the intricate vats of the sanguitorium. Somewhere between these red columns, his grandfather was waiting for him. Watching.
"Is that the way you're seeing things?"
Sorin flourishes the blade in his hand. "Sophistry? Grandfather, you're better than this."
He hears the blow coming a moment before it does: the shifting of Edgar's armor gives him away. Sorin sways to the right; Edgar swings a rack of bottles like a warhammer. They shatter the moment they hit the ground. There's nothing but contempt in Edgar's eyes when they meet Sorin's.
Is this what the Markov line has come to? A deluded old man swinging furniture at his grandson?
"At least use a proper weapon!" Sorin snaps. The slash he unleashes at Edgar is a messy, wild thing.
And easily countered. Edgar catches Sorin's wrist, his fingers a vise. Pain shoots up Sorin's arms as the delicate bones of his forearm crack. "What do you know about propriety, Sorin? It isn't as if you've ever bothered to be part of the family."
Rather than wait for an answer, Edgar flings Sorin away. Sorin crashes into a vat; the wood cracks behind him. Blood spills out and onto his already sticky skin.
"Do you have any idea how much I've sacrificed for you?" Edgar says. He's advancing, crooking a finger toward Sorin as if he's lecturing a child. "How much we've #emph[all ] sacrificed for you?"
Sorin brings a cupped hand to his mouth. If he was going to be soaked in blood, he might as well make use of it. Better than listening to his grandfather's delusions. Olivia's control must have run deeper than he thought, if Edgar's saying things like this. They might not have always gotten along—but Edgar's never been a fool.
And yet.
These can't all be Olivia's words.
"As if I've never made a sacrifice for your sake," Sorin answers. The sword's out of the question now. As he gets to his feet, he grabs the first thing his hands close around—a length of pipe. Pulling it from its housing takes barely any effort with such potent blood coursing through his veins. Even better, more blood sprays over him.
Best to take advantage of this power. In a streak of speed, Sorin attacks. Edgar's armor groans and caves beneath the force of the blow; his ribs crack.
And yet he doesn't move away. The pained wheeze that leaves him sounds almost~amused.
"By all means, boy, tell me of your sacrifices," he says. "What have you given for House Markov? For Innistrad?"
"I created Avacyn—"
Edgar's choking hand stymies any response. There are alchemical fires behind those eyes, disgust in his sneering lip.
"Your little toy soldier? Yes, I'm aware. For the past thousand years, you've spoken of little else. Even that was an idea you derived from #emph[my ] research. I wonder if you've ever had an original idea. For that matter, I wonder if any of your ideas have ever worked out for you."
As if he knows. As if he could ever possibly know the depths of Sorin's struggles.
Edgar lifts him up, one hand sufficient for the job. It's a mistake. Sorin swings the iron bar at Edgar's head. Red weeps from his grandfather's now cracked skull; the old man drops his quarry and recoils in pain.
Something wells up inside Sorin.
There are other Planes. There are other plans.
Again and again and again these words, a chorus echoing in his skull, a chant to summon a dark god. And yes, what it brings is dark indeed. Like the cry of an untethered beast, his scream as he swings again and again, his grandfather backing up further and further. Iron shatters glass. Waterfalls of blood spill onto the floor—blood that once ran in living veins, blood that once longed for more, blood that now longs to die.
"I thought you understood," Sorin rumbles. "I thought you saw, grandfather, that there is more to this existence than gluttonous parties and wanton excess. I thought you saw that!"
Again and again he swings, and swings, the iron bending now from his abuse. He sinks low to the ground—there is another pipe, far larger, that will serve. But the moment he reaches for it, Edgar lunges forward. His grandfather grabs him by the hair and by the waist, a farmer lifting an errant sheep.
"You are a child. You have always been a child," he intones. "It's truly a shame. Millennia ago, I gave you a gift. Now I have to live out the rest of my days knowing you squandered it."
"I never asked for that#emph[—] " Sorin begins.
"My dear boy, that is what makes it a #emph[gift] ."
Edgar swings him face first into a vat. Blood rushes up his nostrils—blood, and splintered wood.
Memory subsumes reality. He is a young man, called into his family's gathering hall. His grandfather sits at the head of the table. Lashed to the ceiling is an angel, her blood dripping into a wine glass.
Everyone is there. His aunts, his uncles. His parents. All of them lay their hands upon him and tell them this is for his own good. For the family's own good. If they're to survive in the dark, they must become a part of it. Famine has taken all the things that humans eat—so they should no longer be human. It's perfectly reasonable.
He's dizzy.
His head against the wood again, a shock of red across the memory.
"Innistrad is ours, Sorin," his grandfather says. He sounds older, somehow, wearier, and the words do not match the movements of his lips. "It's only right we rule it."
The world lurches around him. Something cuts at his throat; he can feel the blood rolling down to his collarbone. His heart hammers against his ribs.
"For too long you've let your bitterness, your paranoia, guide your actions. They've eaten away at your potential. Now all that remains is this sad, broken shell. A little boy, weeping for his grandfather."
Memory still blurs with the present. A hand on the back of his head. The wine glass before him. He does not want to drink, but they force him, the rim of the cup sharp against his gums.
The awful, exultant taste of blood. Warmth coursing through every vein of his body. A filthy feeling from which he'll never be free, but one which will, in time, become part of him. In time, he will act as if he wanted this. In time, he will act as if this was always part of the plan. In time, it will be insulting to him to be confused for a human.
For a mortal.
#emph["Drink and be eternal."]
He fell on that day. They all did. Some might say the spark igniting within him was a saving grace. He felt otherwise. Sorin's never been a believer in grace, in religion—having manufactured one himself, it disabused him of any romantic notions. But he knows that it is true all the same: that day they fell.
So, it is strange, then, that he feels as if he is falling now.
But when he opens his eyes it all makes perfect sense.
His grandfather stands on the lip of a great pit, looking down on him with disgust.
And <NAME> continues to fall.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
History watches Arlinn race through the corridors of Voldaren Manor—but it isn't Arlinn's history. There are no traces of Avabruck here; no rough wrought iron, no Avacynian symbols, no neighbors with stories older than the trees. Here, there are golden chandeliers; here, there is only the Voldaren's crest; here, everything is older than the trees. Even the people.
And those people are watching her as she chases after Olivia. There are the partygoers, and those too drunk on blood to know where they've gone. She shoves them aside as easily as parting wheat. There are the guards, who put up more of a fight. Arlinn doesn't indulge them. Their swings and arrows come one after the other, and one after the other, she weaves between them, shouldering them when she's close enough. Even vampires fall when they lose their balance. She doesn't need them down forever—just long enough to get past. The geists behind her will finish the job.
But there are other eyes, too.
Olivia's, down the hall, challenging her to follow.
And the portraits.
There are plenty of them here. Dozens in this long stretch alone, maybe hundreds throughout the mansion proper. Arlinn didn't care to count. Dressed in their impossible finery, with thralls across their laps, their mouths slaked with blood—the people staring back at her belonged to a different world. To them, existing meant taking things from others. That's power, to a vampire: taking the most things from the highest places.
It isn't a world Arlinn wants to be in.
But it surrounds her all the same, this place that grew from death.
And it occurs to her, as she finally catches Olivia in a dead end, that there's nothing alive in this corridor except her.
No other soldiers. No fellow walkers. Not even her wolves.
The beat of Arlinn's heart is a war drum, a battle cry, a polemic against death. Olivia opens her mouth to say something, but that mouth has fed too much already; Arlinn can't countenance another word. With a human howl, she lashes out, her sharp nails raking the fine fabric of Olivia's gown—and, beneath it, her flesh. The scent of blood drives Arlinn wilder—her teeth ache to grow to fangs—but she cannot let herself be lost just yet.
There's too much at stake.
"#emph[You] ," Olivia sneers. "Why did #emph[you ] have to come?"
There's an answer, of course—because Olivia stole the key—but Arlinn's not inclined to reason with her just now. She presses on, wild slash after wild slash. Olivia's hidden the key somewhere in her train, Arlinn can smell it. Their progenitor is going to pay the price for her theft.
One she isn't inclined to pay, it seems. Only reasonable—vampires don't pay for much out of pocket. In her single-sightedness, Arlinn hadn't accounted for the unnatural architecture of the corridors. Somehow, they've turned into an entirely new one from a dead end. Worse—there are suits of armor here.
And weapons.
Like the gilt sword encrusted with gems that Olivia picks up.
Arlinn can't pull back her swipe in time, and Olivia's all too eager to meet her. Steel bites into Arlinn's fingers. It hurts less than she expected, the thrill of the fight dulling all but the most important sensations. Still, the sight of her own bones peeking out at her is enough to slow her down.
"Give us the key," Arlinn says.
"Us?" says Olivia. "Oh, what a #emph[poor ] little doggie." A pirouette disguises her coming lunge, and Arlinn parries with her forearm a moment too late. Olivia drives the sword's tip into Arlinn's chest with wicked delight. Metal grinds against Arlinn's collarbone as Olivia cups her cheek. "You're all alone here."
Arlinn's not sure which is worse—the pain, now rising past the point of ignorance, or Olivia's hateful voice. Red swims at the corners of her vision. The wolf within her cries out for freedom. Arlinn won't heed it, not now. She has to keep a clear head.
But before Arlinn's clear head can think of what to do, Olivia's shoving her right off the end of her sword with malicious glee. Arlinn kneels, her wound weeping onto the carpet. The painted vampires watch with unchanging amusement as Olivia—their progenitor—cackles.
"I admit, none of this makes sense to me. Wolves aren't known for thinking things through, but even still, you're pack animals, aren't you?" Olivia says. Then she tuts. "Well. #emph[Most ] of you are."
Another flourish. Arlinn braces herself. Sure enough, mid-movement, Olivia's shooting toward her like a crossbow bolt. This time Arlinn ducks, lowering her shoulder and pushing back. It's enough to throw Olivia off balance, but only barely. Arlinn tries to grab her—but Olivia's claws find a home in Arlinn's gut.
Breathing starts to get harder.
"It's for the best, you know," Olivia says. "Even for #emph[your ] kind. Humans are fun little toys, but when has one ever understood you?"
Arlinn wraps a hand around Olivia's wrist. Blood wells up at the back of her throat; she spits it all over Olivia's gown. "Maybe #emph[you ] should try~understanding them."
Olivia's full-face scowl is almost worth all the pain. Disgusted, she pushes Arlinn away again. "I don't make friends with my food," she says. "Now. Come on. If you're going to make this brave little stand of yours, do it properly. You know what you are, don't you?"
<NAME>, daughter of a blacksmith and a baker.
Hard to think, hard to think.
"You know why you're here."
To get the key. To bring daylight back to Innistrad.
To get revenge for the Harvesttide Massacre.
Olivia dabs a finger on the edge of her blade. She licks it clean, then frowns. "Certainly, you #emph[taste ] awful. So. If you're going to do this, little pup, why not let yourself off the leash? You're never going to win in #emph[that ] shape."
She's right. Arlinn hates it, but she is.
And maybe that's the last touch of anger she needs to send her over the edge.
Senses sharpen. Strength returns to her as she grows, strength enough to keep fighting, at least for now. Her human mind is falling away, falling into the forest; she smells pine, tastes blood. Like the cry of a lost hunter, her last conscious thought: #emph[this isn't the way we solve our problems.] But there is no one in the woods to hear it. Only the Moonsilver Key, only Olivia, only the faces staring back at her remain.
#figure(image("007_Episode 4: The Wedding Crashers/04.jpg", width: 100%), caption: [Sure Strike | Art by: <NAME>], supplement: none, numbering: none)
Pure instinct drives her. She pounces, Olivia twirls away. A flash of gold—the sword's coming again. Arlinn catches it barehanded and flings it aside. With the other, she hurls Olivia through a statue of herself.
Ahead, ahead, ahead. The key's somewhere on her. Get it back. End this.
But there are the faces, too—these terrible faces.
Arlinn isn't sure what drives her to do it. Animal rage, perhaps—or an all-too-human rage that only the beast can unleash.
For just a moment, her attention shifts to the paintings—to digging trenches across their smug faces, to tearing the canvas, to howling with fury at the sight of them.
There are so many of them, after all—and she is here alone.
She doesn't notice Olivia's gotten behind her until it's too late.
How ironic—a vampire's stiffened hand makes for an excellent stake.
A plaintive whimper leaves Arlinn's throat.
She falls.
|
|
https://github.com/npujol/chuli-cv | https://raw.githubusercontent.com/npujol/chuli-cv/main/modules/piechart.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#import "styles.typ": *
#let render-activities(slices: ()) = {
cetz.canvas({
import cetz.chart
// A linear gradient from blue navy to blue aqua
let gradient = gradient.linear(colors.navy, colors.aqua)
chart.piechart(
slices,
radius: 1.5,
slice-style: gradient,
inner-radius: .5,
label-key: "name",
value-key: "val",
)
})
} |
https://github.com/Gchism94/PrettyTypst | https://raw.githubusercontent.com/Gchism94/PrettyTypst/main/README.md | markdown | Creative Commons Zero v1.0 Universal | # PrettyTypst
Quarto extension for a template to generate a PDF with (pretty) styling using either Typst. Use `PrettyTypst-typst` for the format. Note that version 1.4 or greater of Quarto is required.
> Note: see [github.com/nrennie/PrettyPDF](https://github.com/nrennie/PrettyPDF) for the LaTeX version of this template.
## Installation and use
To install the Quarto extension, create a directory, and use the template file:
``` bash
quarto use template nrennie/PrettyTypst
```
To use the extension in an existing project without installing the template file:
``` bash
quarto install extension nrennie/PrettyTypst
```
Note that you will need to update the output format to `format: PrettyTypst-typst` to enable use of the extension. For book projects, add:
```
project:
type: PrettyTypst
```
to the `_quarto.yml` file.
### Logo
Either replace the `logo.png` file with a new file of your choosing, or change the file path in the YAML to point to a different logo file. Note that the file path is relative to your .qmd file.
## Blog
Read more about this extension, how it was built, and how to make your own in my blog post at [nrennie.rbind.io/blog/pdf-quarto/making-pdf-with-quarto-typst-latex](https://nrennie.rbind.io/blog/pdf-quarto/making-pdf-with-quarto-typst-latex/).
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/mark-debug/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher
#context fletcher.MARKS.get().pairs().map(((key, mark)) => [
#raw(key)
#set align(center)
#fletcher.mark-debug(mark, show-offsets: true)
#fletcher.mark-demo(mark)
]).join(pagebreak())
|
https://github.com/xichen1/typst-resume | https://raw.githubusercontent.com/xichen1/typst-resume/main/main.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "resume",
authors: (
"rrr_pan",
),
)
#show link: underline
// We generated the example code below so you can see how
// your document will look. Go ahead and replace it with
// your own content!
= <NAME>
(647) 994-4301 |
#link("https://github.com/xichen1")[github.com/xichen1] |
#link("mailto:<EMAIL>")[<EMAIL>]
== Education
#chiline()
*The University of British Columbia* #h(1fr) *Vancouver, Canada* \
Master of Engineering in Electrical and Computer #h(1fr) *Expected May, 2025* \
*University of Alberta* #h(1fr) *Edmonton, Canada* \
First-Class Honors Bachelor of Science in Computing Science, GPA 3.80/4.00 #h(1fr) *2018/09 -- 2023/06* \
- Teaching Assistant for CMPUT 301 Intro. to Software Engineering (Winter 2023)
- Undergraduate Scholarship (2019, 2020); First Class Standing (Winter 2019, Winter 2020, Winter 2021)
== Professional Experience
#chiline()
*Hyperledger, The Linux Foundation* #h(1fr) *Remote* \
*Project Maintainer* #h(1fr) *2023/08 -- Current*\
*Software Development Intern* #h(1fr) *2022/06 -- 2022/11* \
- Developed and maintained web application in collaboration with Hyperledger Cello team to manage Hyperledger Fabric networks.
- Built backend APIs for node and channel's lifecycle operations in blockchains using Django.
- Utilized React.js, Ant Design and UmiJS to develop the user interface, and refined the user manual.
*Department of Mathematical Sciences, University of Alberta* #h(1fr) *Edmonton, Canada* \
*Undergraduate Research Assistant* #h(1fr) *2022/05 -- 2022/08* \
- Designed, built and implemented a visualization tool to solve illumination problems using Java.
- Depicted and constructed scientific trigonometric graphing calculator to support unlimited decimal precision at processing speeds 20 times faster than currently available calculator tools.
*Willowglen Systems* #h(1fr) *Edmonton, Canada* \
*Software Developer (Co-op)* #h(1fr) *2021/09 -- 2022/04* \
- Diligently maintained SCADA system known as SCADACOM used for managing subway operations.
- Enhanced the commit process and streamlined the speed of NoSQL databases by 10 times.
- Configured and continuously improved high concurrency and distributed services to enable increased data processing through data management techniques.
*The Software Maintenance & Reuse Lab, University of Alberta* #h(1fr) *Edmonton, Canada* \
*Undergraduate Research Assistant* #h(1fr) *2021/05 -- 2021/09* \
- Conducted in-depth research on test migration under the supervision of Dr. <NAME> and Dr. <NAME>.
- Implemented automatic test coverage measurement in a test migration tool, and facilitated migration benchmarking.
- Collected datasets of various Java projects and subsequently experimented with test migration, ensuring tool's universal compatibility.
*Intricate Group* #h(1fr) *Edmonton, Canada* \
*Junior Software Developer (Co-op)* #h(1fr) *2021/01 -- 2021/04* \
- Built oil and gas report forms for the website's user interface using JSP, jQuery and JavaScript.
- Utilized Spring to implement web service and PostgreSQL to manage data while applying MVC architecture.
*AdoptOpenJDK, CANOSP* #h(1fr) #h(1fr) *Edmonton, Canada* \
*AdoptOpenJDK Developer (Open Source)* #h(1fr) *2021/01 -- 2021/04* \
- Supported change-based auto-test workflow and implemented GitHub CI for specific tests triggered by commits.
- Investigated and recovered usage of test coverage tool JCov for AdoptOpenJDK project to achieve high test coverage.
== Project Experience
#chiline()
*Stochastic Bayesian Refinement Network [Python, PyTorch, Object Segmentation & Deep Learning]* #h(1fr) *2022/12 -- 2023/04* \
- Co-authored a research paper focused on moving object detection in videos using deep learning techniques. Implemented a novel Bayesian refinement network, improving the precision of object detection. Devised and executed an ablation study to evaluate the contributions of model components, affirming the robustness of the proposed approach. Paper is currently on #link("https://arxiv.org/abs/2304.09949")[arXiv:2304.09949].
*Feature-Guided CNN 2.0 [Python, PyTorch, XAI & Deep Learning]* #h(1fr) *2022/09 -- 2022/12* \
- Implemented a new method to improve Feature-Guided CNN for MRI denoising and registration using Explainable AI loss.
*i-Connect [Python, Django, JavaScript, React & Git]* #h(1fr) *2021/09 -- 2021/12* \
- Developed social media application to allow users to create and engage with posts through likes, follows and shares; connected service and data to 3 external groups and applied agile practices to fulfill the development process.
== Skills
#chiline()
- *Programming Languages* | Java, C, C++, Python, JavaScript, TypeScript HTML, CSS, JSP, Lisp & Golang
- *Frameworks* | React.js, Express.js, NestJS, Django, Node.js, UmiJS & Gin
- *Tools & Libraries* | Git, Bash, LaTeX, OpenCV, NumPy, PyTorch, Docker, jQuery, MongoDB, Firebase, SQLite & PostgreSQL |
|
https://github.com/chubetho/Bachelor_Thesis | https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/utils/header.typ | typst | #let buildMainHeader(mainHeading) = {
[
#text(mainHeading.body)
#line(length: 100%, stroke: 0.5pt)
]
}
#let buildSecondaryHeader(mainHeading, secondaryHeading) = {
[
#text(mainHeading.body)
#h(1fr)
#context (counter(heading).display())
#text(secondaryHeading.body)
#line(length: 100%, stroke: 0.5pt)
]
}
// To know if the secondary heading appears after the main heading
#let isAfter(secondaryHeading, mainHeading) = {
let secHeadPos = secondaryHeading.location().position()
let mainHeadPos = mainHeading.location().position()
if (secHeadPos.at("page") > mainHeadPos.at("page")) {
return true
}
if (secHeadPos.at("page") == mainHeadPos.at("page")) {
return secHeadPos.at("y") > mainHeadPos.at("y")
}
return false
}
#let getHeader() = {
locate(loc => {
// Find if there is a level 1 heading on the current page
let nextMainHeading = query(selector(heading).after(loc), loc).find(headIt => {
headIt.location().page() == loc.page() and headIt.level == 1
})
if (nextMainHeading != none) {
return buildMainHeader(nextMainHeading)
}
// Find the last previous level 1 heading -- at this point surely there's one :-)
let lastMainHeading = query(selector(heading).before(loc), loc)
.filter(headIt => {
headIt.level == 1
})
.last()
// Find if the last level > 1 heading in previous pages
let previousSecondaryHeadingArray = query(selector(heading).before(loc), loc).filter(headIt => (
headIt.level > 1
))
let lastSecondaryHeading = if (previousSecondaryHeadingArray.len() != 0) {
previousSecondaryHeadingArray.last()
} else {
none
}
// Find if the last secondary heading exists and if it's after the last main heading
if (
lastSecondaryHeading != none and isAfter(
lastSecondaryHeading,
lastMainHeading,
)
) {
return buildSecondaryHeader(lastMainHeading, lastSecondaryHeading)
}
return buildMainHeader(lastMainHeading)
})
}
|
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/02_virtualization_02_memory_02_paging.typ | typst | #import "../template.typ": *
#pagebreak()
== Intro to Paging
Another approach to solve the external-fragment problems: to chop up space into *fixed-sized* pieces.
- We divide it into fixed-sized units, each of which we call a *page*.
- Correspondingly,we view physical memory as an array of fixed-sized slots called *page frames*; each of these frames can contain a single virtual-memory page.
=== A Simple Example And Overview
A tiny address space, only 64 bytes total in size, with four 16-byte pages (virtual pages 0, 1, 2, and 3).
#image("images/2023-12-14-21-34-34.png", width: 70%)
Physical memory, as shown in Figure below, also consists of a number of fixed-sized slots, in this case eight page frames (making for a 128-byte physical memory, also ridiculously small).
#image("images/2023-12-14-21-35-20.png", width: 70%)
The advantages of paging:
- The most important improvement will be flexibility: we won’t, for example, make assumptions about the direction the heap and stack grow and how they are used.
- Another advantage is the simplicity of free-space management that paging affords. Perhaps the OS keeps a free list of all free pages for this, and just grabs the first four free pages off of this list.
To record where each virtual page of the address space is placed in physical memory, the operating system usually keeps a *per-process* data structure known as a *page table*.(One of the most important data structures!)
The major role of the page table is to store address translations for each of the virtual pages of the address space, thus letting us know where in physical memory each page resides.
#tip("Tip")[
Most page table structures we discuss are per-process structures; an exception we’ll touch on is the *inverted page table*.
]
For our simple example, the page table would thus have the following four entries: (Virtual Page 0 → Physical Frame 3), (VP 1→PF 7), (VP 2→PF 5), and (VP 3→PF 2).
==== how does it works?
Let’s imagine the process with that tiny address space (64 bytes) is performing a memory access:
```
movl <virtual address>, %eax
```
the explicit load of the data from address `<virtual address>` into the register `eax`.
To translate this virtual address that the process generated, we have to first split it into two components: the *virtual page number (VPN)*, and the *offset* within the page.
For this example, we need 6 bits total for our virtual address (2^6 = 64). Thus, our virtual address can be conceptualized as follows:
#image("images/2023-12-14-21-42-54.png", width: 50%)
- The page size is 16 bytes in a 64-byte address space; thus we need to be able to select 4 pages, and the top 2 bits of the address do just that. Thus, we have a 2-bit virtual page number (VPN).
- The remaining bits tell us which byte of the page we are interested in, 4 bits in this case; we call this the offset.
For example, let us assume the load above was to virtual address 21:
```
movl 21, %eax
```
Turning “21” into binary form, we get “010101”, Thus, the virtual address “21” is on the 5th (“0101”th) byte of virtual page “01” (or 1).
With our virtual page number, we can now index our page table and find which physical frame virtual page 1 resides within.
In the page table above the *physical frame number (PFN)* (also sometimes called the *physical page number or PPN*) is 7 (binary 111). Thus, we can translate this virtual address by replacing the VPNwith the PFNand then issue the load to physical memory. Our final physical address is 1110101.
#image("images/2023-12-14-21-47-41.png", width: 70%)
#tip("Tip")[
Note the offset stays the same.
]
- Where are these page tables stored?
- What are the typical contents of the page table?
- How big are the tables?
- Does paging make the system (too) slow?
=== Where Are Page Tables Stored?
For example, imagine a typical 32-bit address space, with 4KB pages.
This virtual address splits into a 20-bit VPN and 12-bit offset.
Horribly! 2^20 pages, assuming we need 4 bytes per *page table entry (PTE)* to hold the physical translation plus any other useful stuff, we get an immense *4MB* of memory needed for each page table!
Because page tables are so big,we don’t keep any special on-chip hardware in the MMU to store the page table of the currently-running process.
Instead, we store the page table for each process in memory somewhere.
#image("images/2023-12-14-21-53-57.png", width: 70%)
=== What’s Actually In The Page Table?
The page table is just a data structure that is used to map virtual addresses (or really, virtual page numbers) to physical addresses (physical frame numbers).
The simplest data structure is called a linear page table, which is just an array.
The OS *indexes the array by the virtual page number (VPN)*, and looks up the page-table entry (PTE) at that index in order to find the desired physical frame number (PFN).
==== valid bit
A *valid bit* is common to indicate whether the particular translation is valid.
All the unused space in-between will be marked invalid, and if the process tries to access such memory, it will generate a trap to the OS which will likely terminate the process.
#tip("Tip")[
The valid bit is crucial for supporting a sparse address space; by simply marking all the unused pages in the address space invalid, we remove the need to allocate physical frames for those pages and thus save a great deal of memory.
]
==== others
- *Protection bits*: Indicate whether the page could be read from, written to, or executed from.
- *present bit*: Indicates whether this page is in physical memory or on disk (i.e., it has been swapped out).
- *A dirty bit*: Indicating whether the page has been modified since it was brought into memory.
- *A reference bit* (a.k.a. *accessed bit*) is sometimes used to track whether a page has been accessed, and is useful in determining which pages are popular and thus should be kept in memory; such knowledge is critical during *page replacement*.
==== x86 architecture PTE
#image("images/2023-12-14-21-55-03.png")
- a present bit (P);
- a read/write bit (R/W) which determines if writes are allowed to this page;
- a user/supervisor bit (U/S) which determines if user-mode processes can access the page;
- a few bits (PWT, PCD, PAT, and G) that determine how hardware caching works for these pages;
- an accessed bit (A) and a dirty bit (D);
- and finally, the page frame number (PFN) itself.
=== Paging: Also Too Slow
```
movl 21, %eax
```
To fetch the desired data, the system must first translate the virtual address (21) into the correct physical address (117).
Thus, before fetching the data from address 117, the system must first fetch the proper page table entry from the process’s page table, perform the translation, and then load the data from physical memory.
To do so, the hardware must know where the page table is for the currently-running process. Let’s assume for now that a single *page-table base register* contains the physical address of the starting location of the page table.
```c
VPN = (VirtualAddress & VPN_MASK) >> SHIFT
PTEAddr = PageTableBaseRegister + (VPN * sizeof(PTE))
offset = VirtualAddress & OFFSET_MASK
PhysAddr = (PFN << SHIFT) | offset
```
In our example,
- `VPN_MASK` to `0x30`
- `SHIFT` is set to `4`
```c
// Extract the VPN from the virtual address
VPN = (VirtualAddress & VPN_MASK) >> SHIFT
// Form the address of the page-table entry (PTE)
PTEAddr = PTBR + (VPN * sizeof(PTE))
// Fetch the PTE
PTE = AccessMemory(PTEAddr)
// Check if process can access the page
if (PTE.Valid == False)
RaiseException(SEGMENTATION_FAULT)
else if (CanAccess(PTE.ProtectBits) == False)
RaiseException(PROTECTION_FAULT)
else
// Access is OK: form physical address and fetch it
offset = VirtualAddress & OFFSET_MASK
PhysAddr = (PTE.PFN << PFN_SHIFT) | offset
Register = AccessMemory(PhysAddr)
```
Paging requires us to perform one extra memory reference in order to first fetch the translation from the page table.
Without careful design of both hardware and software, page tables will cause the system to run too slowly, as well as take up too much memory
=== A Memory Trace
```c
int array[1000];
...
for (i = 0; i < 1000; i++)
array[i] = 0;
```
```asm
1024 movl $0x0,(%edi,%eax,4) // %edi+4*%eax=0
1028 incl %eax // %eax++
1032 cmpl $0x03e8,%eax // 1000=%eax?
1036 jne 0x1024 // 1000!=%eax -> 1024
```
- We assume a virtual address space of size 64KB.
- We also assume a page size of 1KB.
#image("images/2023-12-15-18-18-23.png", width: 80%)
First, there is the virtual page the *code* lives on.
Because the page size is 1KB, virtual address 1024 resides on the second page of the virtual address space (VPN=1, as VPN=0 is the first page).
Let’s assume this virtual page maps to physical frame 4 (VPN 1→PFN 4).
Next, there is the array itself. Its size is 4000 bytes (1000 integers), and we assume that it resides at virtual addresses 40000 through 44000 (not including the last byte).
Let’s assume these virtual-to-physical mappings for the example: (VPN39->PFN7), (VPN 40->PFN 8), (VPN 41->PFN 9), (VPN 42->PFN 10).
We are now ready to trace the memory references of the program.
Compile program -> VPN -> PPN
When it runs, each instruction fetch will generate two memory references:
- fetch the inst VA
- then access the corresponding page table in memory (memory access).
- then find the corresponding inst PA in the page table
- finally fetch the inst according to the inst PA(memory access)
If the inst has other access memory operation, then increment the access num for 2. For example: `1024 movl $0x0,(%edi,%eax,4) // %edi+4*%eax=0` need to access the array.
- First fetch the array VA,
- then access the corresponding page table in memory (memory access).
- then find the corresponding array PA in the page table
- finally fetch the inst according to the array PA(memory access)
There are 10 memory accesses per loop, which includes four instruction fetches, one explicit update of memory, and five page table accesses to translate those four fetches and one explicit update.
==== THE PAGE TABLE
=== Summary
Paging has many advantages over previous approaches (such as segmentation).
- First, it does not lead to external fragmentation, as paging (by design) divides memory into fixed-sized units.
- Second, it is quite flexible, enabling the sparse use of virtual address spaces.
However, implementing paging support without care will lead to
- a slower machine (with many extra memory accesses to access the page table)
- as well as memory waste (with memory filled with page tables instead of useful application data).
== Paging: Faster Translations (TLBs)
To speed address translation, we are going to add what is called *a translation-lookaside buffer, or TLB*.
A TLB is part of the chip’s *memory-management unit (MMU),* and is simply a hardware cache of popular virtual-to-physical address translations; thus, a better name would be *an address-translation cache*.
=== TLB Basic Algorithm
Assuming *a simple linear page table* (i.e., the page table is an array) and *a hardware-managed TLB* (i.e., the hardware handles much of the responsibility of page table accesses;)
```c
VPN = (VirtualAddress & VPN_MASK) >> SHIFT
(Success, TlbEntry) = TLB_Lookup(VPN)
if (Success == True) // TLB Hit
if (CanAccess(TlbEntry.ProtectBits) == True)
Offset = VirtualAddress & OFFSET_MASK
PhysAddr = (TlbEntry.PFN << SHIFT) | Offset
Register = AccessMemory(PhysAddr)
else
RaiseException(PROTECTION_FAULT)
else // TLB Miss
PTEAddr = PTBR + (VPN * sizeof(PTE))
PTE = AccessMemory(PTEAddr)
if (PTE.Valid == False)
RaiseException(SEGMENTATION_FAULT)
else if (CanAccess(PTE.ProtectBits) == False)
RaiseException(PROTECTION_FAULT)
else
TLB_Insert(VPN, PTE.PFN, PTE.ProtectBits)
RetryInstruction()
```
The TLB, like all caches, is built on the premise that in the common case, translations are found in the cache (i.e., are hits).
When a miss occurs, the high cost of paging is incurred; it is our hope to avoid TLB misses as much as we can.
=== Example: Accessing An Array
Let’s assume:
- We have *an array of 10 4-byte integers* in memory, starting at virtual address 100.
- We have *a small 8-bit virtual address space*, with *16-byte pages*; thus, a virtual address breaks down into a 4-bit VPN (there are 16 virtual pages) and a 4-bit offset (there are 16 bytes on each of those pages).
#image("images/2023-12-16-20-10-48.png", width: 50%)
- consider *a simple loop* that accesses each array element:
```c
int sum = 0;
for (i = 0; i < 10; i++) {
sum += a[i];
}
```
> pretend that the only memory accesses the loop generates are *only to the array*
When the first array element (`a[0]`) is accessed, the CPU will see a load to virtual address 100. The hardware extracts the VPN from this (VPN=06), and uses that to check the TLB for a valid translation. Assuming this is the first time the program accesses the array, the result will be *a TLB miss*.
The next access is to `a[1]`, and there is some good news here: a TLB hit! Because the second element of the array is packed next to the first, it lives on the same page.
....
TLB activity during our ten accesses to the array:
```
miss, hit, hit, miss, hit, hit, hit, miss, hit, hit.
```
TLB hit rate = hits/accesses = 70%
The TLB improves performance due to *spatial locality*.
If the page size had simply been twice as big (32 bytes, not 16), the array access would suffer even fewer misses.
As typical page sizes are more like 4KB, these types of dense, array-based accesses achieve excellent TLB performance, encountering only a single miss per page of accesses.
#tip("Tip")[
Theoretically, the bigger the page size is, the fewer misses.
]
One last point about TLB performance: if the program, soon after this loop completes, accesses the array again, assuming that we have a big enough TLB to cache the needed translations:
```
hit, hit, hit, hit, hit, hit, hit, hit, hit, hit.
```
#tip("Tip")[
In this case, the TLB hit rate would be high because of *temporal locality*
]
=== Who Handles The TLB Miss?
the hardware, or the software (OS)
==== Hardware
The hardware has to know exactly *where the page tables are* located in memory (via a page table base register), as well as their *exact format*.
On a miss:
- the hardware would “walk” the page table
- find the correct page-table entry and extract the desired translation
- update the TLB with the translation
- retry the instruction.
An example of an “older” architecture that has hardware-managed TLBs is the Intel x86 architecture, which uses *a fixed multi-level page table*; the current page table is pointed to by the `CR3` register.
#tip("Tip")[
CISC
]
==== OS
More modern architectures (e.g., MIPS R10k or Sun’s SPARC v9 [WG00], both *RISC* or reduced-instruction set computers) have what is known as *a software-managed TLB*.
On a TLB miss, the hardware simply raises an exception, which
- pauses the current instruction stream
- raises the privilege level to kernel mode
- jumps to a trap handler.
```c
VPN = (VirtualAddress & VPN_MASK) >> SHIFT
(Success, TlbEntry) = TLB_Lookup(VPN)
if (Success == True) // TLB Hit
if (CanAccess(TlbEntry.ProtectBits) == True)
Offset = VirtualAddress & OFFSET_MASK
PhysAddr = (TlbEntry.PFN << SHIFT) | Offset
Register = AccessMemory(PhysAddr)
else
RaiseException(PROTECTION_FAULT)
else // TLB Miss
RaiseException(TLB_MISS)
```
When run the trap handler, the code will
- lookup the translation in the page table
- use special “privileged” instructions to update the TLB
- and return from the trap
- at this point, the hardware retries the instruction (resulting in a TLB hit)
===== the return-from-trap instruction
The return-from-trap instruction needs to be a little different than the return-from-trap we saw before when servicing a system call.
- In the latter case, the return-from-trap should resume execution at the instruction *after* the trap into the OS.
- In the former case, when returning from a TLB miss-handling trap, the hardware must resume execution at the instruction that *caused* the trap, this retry thus lets the instruction run again, this time resulting in a TLB hit.
Depending on how a trap or exception was caused, the hardware must save a different PCwhen trapping into the OS.
===== an infinite chain of TLB misses
When running the TLBmiss-handling code, the OS needs to be extra careful not to cause an infinite chain of TLB misses to occur.
- keep TLB miss handlers in physical memory (where they are *unmapped* and not subject to address translation)
- reserve some entries in the TLB for permanently-valid translations and use some of those permanent translation slots for the handler code itself; these *wired* translations always hit in the TLB.
===== advantage
- flexibility: The OS can use any data structure it wants to implement the page table, without necessitating hardware change.
- simplicity: The hardware doesn’t do much on a miss: just raise an exception and let the OS TLB miss handler do the rest.
=== TLB Contents: What’s In There?
A typical TLB might have 32, 64, or 128 entries and be what is called *fully associative*(any given translation can be anywhere in the TLB). The hardware will search the entire TLB in parallel to find the desired translation.
A TLB entry might look like this:
```
|VPN|PPN|other bits|
```
- a valid bit, which says whether the entry has a valid translation or not.
- protection bits, which determine how a page can be accessed (as in the page table)
- a few other fields, including
- an address-space identifier
- a dirty bit
- ...
=== TLB Issue: Context Switches
The TLB contains virtual-to-physical translations that are only valid for the currently running process.
As a result, when switching from one process to another, the hardware or OS must be careful to ensure that the about-to-be-run process does not accidentally use translations from some previously run process. (2 processes, what will happen if the same VPN is mapped to different PPNs, horrible!)
There are a number of possible solutions to this problem.
- One approach is to simply *flush* the TLB on context switches, thus emptying it before running the next process.
- a software-based system, this can be accomplished with an explicit (and privileged) hardware instruction;
- a hardware-managed TLB, the flush could be enacted when the page-table base register is changed.
- In either case, the flush operation simply sets all valid bits to 0, essentially clearing the contents of the TLB.
#tip("Tip")[
Each time a process runs, it must incur TLB misses as it touches its data and code pages. If the OS switches between processes frequently, this cost may be high.
]
- add hardware support to enable sharing of the TLB across context switches
#tip("Tip")[
- Some hardware systems provide *an address space identifier (ASID)* field in the TLB.
- You can think of the ASID as a process identifier (PID), but usually it has fewer bits (e.g., 8 bits for the ASID versus 32 bits for a PID).
]
Thus, with *address-space identifiers*, the TLB can hold translations from different processes at the same time without any confusion.
- the hardware also needs to *know which process is currently running* in order to perform translations
- and thus the OS must, on a context switch, *set some privileged register* to the ASID of the current process.
There are two entries for two different processes with two different VPNs that point to the same physical page:
#image("images/2023-12-16-21-14-02.png", width: 50%)
This situation might arise, for example, when two processes share a page (a code page, for example).
=== Issue: Replacement Policy
As with any cache, and thus also with the TLB, one more issue that we must consider is cache replacement.
The goal, of course, being to *minimize the miss rate* (or *increase hit rate*) and thus improve performance.
- *least-recently-used or LRU*: it is likely that an entry that has not recently been used is a good candidate for eviction.
- *random policy*: evicts a TLB mapping at random.
A “reasonable” policy such as LRU behaves quite unreasonably when a program loops over n + 1 pages with a TLB of size n:
In this case, LRU misses upon every access, whereas random does much better.
=== A Real TLB Entry
This example is from the MIPS R4000, a modern system that uses software-managed TLBs. A slightly simplified MIPS TLB entry:
#image("images/2023-12-16-21-19-25.png")
The MIPS R4000 supports a 32-bit address space with 4KB pages.
==== bits
- There are only 19 bits for the VPN; as it turns out, user addresses will only come from half the address space (the rest reserved for the kernel).
- The VPN translates to up to a 24-bit physical frame number (PFN), and hence can support systems with up to 64GB of (physical)main memory (2^24 4KB pages).
- There are a few other interesting bits in the MIPS TLB.
- a global bit (G), which is used for pages that are globally-shared among processes. Thus, if the global bit is set, the ASID is ignored.
- the 8-bit ASID, which the OS can use to distinguish between address spaces.
- Coherence (C) bits, which determine how a page is cached by the hardware (a bit beyond the scope of these notes)
- a dirty bit which is marked when the page has been written to (we’ll see the use of this later)
- a valid bit which tells the hardware if there is a valid translation present in the entry
- a page mask field (not shown), which supports multiple page sizes
- some of the 64 bits are unused (shaded gray in the diagram).
One question for you: what should the OS do if there are more than 256 (28) processes running at a time?
https://stackoverflow.com/questions/52813239/how-many-bits-there-are-in-a-tlb-asid-tag-for-intel-processors-and-how-to-handl
==== reserved for the OS
MIPS TLBs usually have 32 or 64 of these entries
- Most of which are used by user processes as they run
- A few are reserved for the OS
*A wired register* can be set by the OS to tell the hardware how many slots of the TLB to reserve for the OS
The OS uses these reserved mappings for code and data that it wants to access during critical times, where a TLB miss would be problematic (e.g., in the TLB miss handler).
==== update the TLB
TheMIPS provides four such instructions:
- `TLBP`, which probes the TLB to see if a particular translation is in there;
- `TLBR`, which reads the contents of a TLB entry into registers;
- `TLBWI`, which replaces a specific TLB entry;
- `TLBWR`, which replaces a random TLB entry.
The OS uses these instructions to manage the TLB’s contents. It is of course critical that these instructions are privileged.
=== Summary
*The TLB coverage*: If the number of pages a program accesses in a short period of time exceeds the number of pages that fit into the TLB, the program will generate a large number of TLB misses, and thus run quite a bit more slowly.
One solution is to include support for larger page sizes:
By mapping key data structures into regions of the program’s address space that are mapped by larger pages, the effective coverage of the TLB can be increased.
#tip("Tip")[
Support for large pages is often exploited by programs such as *a database management system (a DBMS)*
]
TLB access can easily become a bottleneck in the CPU pipeline, in particular with what is called *a physically-indexed cache*.
With such a cache, address translation has to take place before the cache is accessed, which can slow things down quite a bit.
Because of this potential problem, people have looked into all sorts of clever ways to *access caches with virtual addresses*, thus avoiding the expensive step of translation in the case of a cache hit.
#tip("Tip")[
Such a *virtually-indexed cache* solves some performance problems, but introduces new issues into hardware design as well. See Wiggins’s fine survey for more details.
]
== Paging: Smaller Tables
We now tackle the second problem that paging introduces: page tables are too big and thus consume too much memory.
Assume again a 32-bit address space (232 bytes), with 4KB (2^12 byte) pages and a 4-byte page-table entry.
An address space thus has roughly one million virtual pages in it (2^20); multiply by the page-table entry size and you see that our page table is 4MB in size.
Recall also: we usually have one page table for every process in the system!
=== Simple Solution: Bigger Pages
Take our 32-bit address space again, but this time assume 16KB pages.
We would thus have an 18-bit VPN plus a 14-bit offset.
Assuming the same size for each PTE (4 bytes), we now have 2^18 entries in our linear page table and thus a total size of 1MB per page table, a factor of four reduction in size of the page table.
The major problem with this approach, is that big pages lead to waste within each page, a problem known as internal fragmentation (as the waste is internal to the unit of allocation).
Applications thus end up allocating pages but only using little bits and pieces of each.
==== MULTIPLE PAGE SIZES
Many architectures (e.g., MIPS, SPARC, x86-64) now support multiple page sizes.
Usually, a small (4KB or 8KB) page size is used.
However, if a “smart” application requests it, a single large page (e.g., of size 4MB) can be used for a specific portion of the address space, enabling such applications to place a frequently-used (and large) data structure in such a space while consuming only a single TLB entry.
This type of large page usage is common in database management systems and other high-end commercial applications.
The main reason for multiple page sizes is not to save page table space, however; it is to reduce pressure on the TLB, enabling a program to access more of its address space without suffering from too many TLB misses.
Using multiple page sizes makes the OS virtual memory manager notably more complex, and thus large pages are sometimes most easily used simply by exporting a new interface to applications to request large pages directly.
=== Hybrid Approach: Paging and Segments
*Hybrid*: Whenever you have two reasonable but different approaches to something in life, you should always examine the combination of the two to see if you can obtain the best of both worlds.
So we can combining paging and segmentation in order to reduce the memory overhead of page tables.
For the example, we use a tiny 16KB address space with 1KB pages.
#image("images/2023-12-15-18-58-05.png", width: 70%)
#image("images/2023-12-15-18-58-14.png", width: 50%)
From the picture, most of the page table is unused, full of invalid entries.
#tip("Tip")[
Imagine the page table of a 32-bit address space and all the potential wasted space in there!
]
==== have one per logical segment
Instead of having a single page table for the entire address space of the process, why not *have one per logical segment*?
In this example, we might thus have *three page tables, one for the code, heap, and stack* parts of the address space.
Remember with segmentation,
- *a base register* that told us where each segment lived in physical memory
- *a bound or limit register* that told us the size of said segment.
In our hybrid, we still have those structures in the MMU
- The base hold *the physical address of the page table* of that segment.
- The bounds register is used to indicate *the end of the page table* (i.e., how many valid pages it has).
Assume a 32-bit virtual address space with 4KB pages, and an address space split into four segments. We’ll only use three segments for this example: one for code, one for heap, and one for stack.
#image("images/2023-12-18-12-33-32.png")
In the hardware, assume that there are thus three base/bounds pairs, one each for code, heap, and stack.
When a process is running, the base register for each of these segments contains the physical address of a linear page table for that segment;
Thus, each process in the system now has three page tables associated with it. On a context switch, these registers must be changed to reflect the location of the page tables of the newly running process.
On a TLB miss, the hardware uses the segment bits (SN) to determine which base and bounds pair to use.
```c
SN = (VirtualAddress & SEG_MASK) >> SN_SHIFT
VPN = (VirtualAddress & VPN_MASK) >> VPN_SHIFT
AddressOfPTE = Base[SN] + (VPN * sizeof(PTE))
```
The critical difference in our hybrid scheme is the presence of a bounds register per segment; each bounds register holds the value of the maximum valid page in the segment.
problems:
- it still requires us to use segmentation(segmentation is not quite as flexible)
#tip("Tip")[
if we have a large but sparsely-used heap, we can still end up with a lot of page table waste.
]
- this hybrid causes external fragmentation to arise
#tip("Tip")[
page tables now can be of arbitrary size (in multiples of PTEs). Thus, finding free space for them in memory is more complicated.
]
=== Multi-level Page Tables
How to get rid of all those invalid regions in the page table instead of keeping them all in memory?
*multi-level page table*: it turns the linear page table into something like a tree.
#tip("Tip")[
many modern systems employ it
]
The basic idea behind a multi-level page table is simple.
- First, chop up the page table into page-sized units;
- then, if an entire page of page-table entries (PTEs) is invalid, don’t allocate that page of the page table at all.
To track a page of the page table, use a new structure, called the *page directory*. It either can be used to tell you *where a page of the page table is*, or that the entire page of the page table contains no *valid pages*
- It consists of a number of *page directory entries (PDE)*.
- A PDE (minimally) has a valid bit and *a page frame number (PFN)*, similar to a PTE.
- If the PDE is valid, it means that at least one of the pages of the page table that the entry points to (via the PFN) is valid
#image("images/2023-12-18-14-46-49.png")
#tip("Tip")[
- PTBR -> page table base register
- PDBR -> page directory base register
]
- On the left is the classic linear page table: even though most of the middle regions of the address space are not valid, we still require page-table space allocated for those regions.
- On the right is a multi-level page table: the page directory marks just two pages of the page table as valid (the first and last), thus, just those two pages of the page table reside in memory.
#tip("Tip")[
It just makes parts of the linear page table disappear, and tracks which pages of the page table are allocated with the page directory.
]
==== Advantages:
- First, the multi-level table only allocates page-table space in proportion to the amount of address space you are using; thus it is generally compact and supports sparse address spaces.
- Second, each portion of the page table fits neatly within a page, making it easier to manage memory; the OS can simply grab the next free page when it needs to allocate or grow a page table.
With a multi-level structure, we add a *level of indirection* through use of the page directory, which points to pieces of the page table; that indirection allows us to place page-table pages wherever we would like in physical memory.
==== Negative:
There is a cost to multi-level tables:
on a TLB miss, two loads from memory will be required to get the right translation information from the page table (one for the page directory, and one for the PTE itself), in contrast to just one load with a linear page table.
Another obvious negative is complexity:
Whether it is the hardware or OS handling the page-table lookup (on a TLB miss), doing so is undoubtedly more involved than a simple linear page-table lookup.
==== BE WARY OF COMPLEXITY
What a good systems builder does is implement the least complex system that achieves the task at hand.
For example,
- if disk space is abundant, you shouldn’t design a file system that works hard to use as few bytes as possible;
- if processors are fast, it is better to write a clean and understandable module within the OS than perhaps the most CPU-optimized, hand-assembled code for the task at hand.
Be wary of needless complexity, in prematurely-optimized code or other forms; such approaches make systems harder to understand, maintain, and debug.
_Perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away._
==== A Detailed Multi-Level Example
===== Assumption
Address space of size 16KB, with 64-byte pages, assume each PTE is 4 bytes.
-> a 14-bit virtual address space, with 8 bits for the VPN and 6 bits for the offset,
A linear page table would have 2^8 entries:
#image("images/2023-12-18-14-59-34.png", width: 60%)
#tip("Tip")[
page table is 1KB (256 × 4 bytes) in size
]
- code: virtual pages 0 and 1
- stack: virtual pages 254 and 255
- heap: virtual pages 4 and 5
To build a two-level page table, we *start with our full linear page table and break it up into page-sized units*.
We have 64-byte pages, the 1KB page table can be divided into 16 64-byte pages; each page can hold 16 PTEs.How to construct the index for each from pieces of the VPN?
#image("images/2023-12-18-15-06-01.png", width: 80%)
Once we extract the *page-directory index (PDIndex for short)* from the VPN, we can use it to find the address of the page-directory entry (PDE)with a simple calculation: `PDEAddr = PageDirBase + (PDIndex * sizeof(PDE))`.
If the page-directory entry is marked invalid, we know that the access is invalid, and thus raise an exception.
If, the PDE is valid, we now have to fetch the page-table entry (PTE) from the page of the page table pointed to by this page directory entry. To find this PTE, we have to index into the portion of the page table using the remaining bits of the VPN:
#image("images/2023-12-18-15-08-22.png", width: 80%)
This *page-table index (PTIndex for short)* can then be used to index into the page table itself, giving us the address of our PTE:
`PTEAddr = (PDE.PFN << SHIFT) + (PTIndex * sizeof(PTE))`
===== Example
We’ll now fill in a multi-level page table with some actual values, and translate a single virtual address.
#image("images/2023-12-18-15-09-39.png", width: 80%)
#tip("Tip")[
instead of allocating the full sixteen pages for a linear page table, we allocate only three: one for the page directory, and two for the chunks of the page table that have valid mappings.
]
VPNs 254 and 255 (the stack) have valid mappings.
VPN 254: 0x3F80, or 1111 1110 000000 in binary.
- The top 4 bits of the VPN(1111) to index into the page directory, will choose the last entry of the page directory above.(PFN=101)
- The next 4 bits of the VPN (1110) to index into that page of the page table and find the desired PTE.(PFN=55)
- Concatenating PFN=55 (or hex 0x37) with offset=000000, `PhysAddr = (PTE.PFN << SHIFT) + offset = 00 1101 1100 0000 = 0x0DC0`
==== More Than Two Levels
assume a 30-bit virtual address space, and a small (512 byte) page
-> a 21-bit virtual page number component and a 9-bit offset
Our goal in constructing a multi-level page table: to make each piece of the page table fit within a single page.
To *determine how many levels* are needed in a multi-level table to make all pieces of the page table fit within a page, we *start by determining how many page-table entries fit within a page*.
Given our page size of 512 bytes, and assuming a PTE size of 4 bytes, a single page can fit in 128 PTEs.
When we index into a page of the page table, we can thus conclude we’ll need the least significant 7 bits ($log_2{128}$) of the VPN as an index:
#image("images/2023-12-18-15-25-19.png")
If our page directory has 2^14 entries, and thus our goal of making every piece of the multi-level page table fit into a page vanishes.
To remedy this problem, split the page directory itself into multiple pages, and then add another page directory on top of that, to point to the pages of the page directory.
#image("images/2023-12-18-15-26-58.png")
PD Index 0: this index can be used to fetch the page-directory entry from the top-level page directory
If valid, the second level of the page directory is consulted by combining the *PFN from the top-level PDE* and the next part of the VPN (*PD Index 1*).
==== The Translation Process: Remember the TLB
```c
VPN = (VirtualAddress & VPN_MASK) >> SHIFT
(Success, TlbEntry) = TLB_Lookup(VPN)
if (Success == True) // TLB Hit
if (CanAccess(TlbEntry.ProtectBits) == True)
Offset = VirtualAddress & OFFSET_MASK
PhysAddr = (TlbEntry.PFN << SHIFT) | Offset
Register = AccessMemory(PhysAddr)
else
RaiseException(PROTECTION_FAULT)
else // TLB Miss
// first, get page directory entry
PDIndex = (VPN & PD_MASK) >> PD_SHIFT
PDEAddr = PDBR + (PDIndex * sizeof(PDE))
PDE = AccessMemory(PDEAddr)
if (PDE.Valid == False)
RaiseException(SEGMENTATION_FAULT)
else
// PDE is valid: now fetch PTE from page table
PTIndex = (VPN & PT_MASK) >> PT_SHIFT
PTEAddr = (PDE.PFN << SHIFT) + (PTIndex * sizeof(PTE))
PTE = AccessMemory(PTEAddr)
if (PTE.Valid == False)
RaiseException(SEGMENTATION_FAULT)
else if (CanAccess(PTE.ProtectBits) == False)
RaiseException(PROTECTION_FAULT)
else
TLB_Insert(VPN, PTE.PFN, PTE.ProtectBits)
RetryInstruction()
```
=== Inverted Page Tables
more extreme space savings -> *Inverted Page Tables*
Inverted Page tables keep a single page table that has an entry for each physical page of the system.
The entry tells us which process is using this page, and which virtual page of that process maps to this physical page.
Finding the correct entry is now a matter of searching through this data structure.
A hash table is often built over the base structure to speed up lookups.
=== Swapping the Page Tables to Disk
We have assumed that page tables reside in kernel-owned physical memory. Even with our many tricks to reduce the size of page tables, it is still possible, however, that they may be too big to fit into memory all at once.
Thus, some systems place such page tables in *kernel virtual memory,* thereby allowing the system to *swap* some of these page tables to disk when memory pressure gets a little tight.
=== Summary
The trade-offs such tables present are in time and space.
- In a memory-constrained system(like many older systems), small structures make sense.
- In a system with a reasonable amount of memory and with workloads that actively use a large number of pages, a bigger table that speeds up TLB misses might be the right choice.
_Think of these questions as you fall asleep, and dream the big dreams that only operating-system developers can dream._
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/query-before-after.typ | typst | Apache License 2.0 |
---
#set page(
paper: "a7",
numbering: "1 / 1",
margin: (bottom: 1cm, rest: 0.5cm),
)
#show heading.where(level: 1, outlined: true): it => [
#it
#set text(size: 12pt, weight: "regular")
#outline(
title: "Chapter outline",
indent: true,
target: heading
.where(level: 1)
.or(heading.where(level: 2))
.after(it.location(), inclusive: true)
.before(
heading
.where(level: 1, outlined: true)
.after(it.location(), inclusive: false),
inclusive: false,
)
)
]
#set heading(outlined: true, numbering: "1.")
= Section 1
== Subsection 1
== Subsection 2
=== Subsubsection 1
=== Subsubsection 2
== Subsection 3
= Section 2
== Subsection 1
== Subsection 2
= Section 3
== Subsection 1
== Subsection 2
=== Subsubsection 1
=== Subsubsection 2
=== Subsubsection 3
== Subsection 3
---
#set page(
paper: "a7",
numbering: "1 / 1",
margin: (bottom: 1cm, rest: 0.5cm),
)
#set heading(outlined: true, numbering: "1.")
// This is purposefully an empty
#locate(loc => [
Non-outlined elements:
#(query(selector(heading).and(heading.where(outlined: false)), loc)
.map(it => it.body).join(", "))
])
#heading("A", outlined: false)
#heading("B", outlined: true)
#heading("C", outlined: true)
#heading("D", outlined: false)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/plot/contour.typ | typst | Apache License 2.0 | #import "/src/cetz.typ": draw
#import "util.typ"
#import "sample.typ"
// Find contours of a 2D array by using marching squares algorithm
//
// - data (array): A 2D array of floats where the first index is the row and the second index is the column
// - offset (float): Z value threshold of a cell compare with `op` to, to count as true
// - op (auto,string,function): Z value comparison oparator:
// / `">", ">=", "<", "<=", "!=", "=="`: Use the passed operator to compare z.
// / `auto`: Use ">=" for positive z values, "<=" for negative z values.
// / `<function>`: If set to a function, that function gets called
// with two arguments, the z value `z1` to compare against and
// the z value `z2` of the data and must return a boolean: `(z1, z2) => boolean`.
// - interpolate (bool): Enable cell interpolation for smoother lines
// - contour-limit (int): Contour limit after which the algorithm panics
// -> array: Array of contour point arrays
#let find-contours(data, offset, op: auto, interpolate: true, contour-limit: 50) = {
assert(data != none and type(data) == array,
message: "Data must be of type array")
assert(type(offset) in (int, float),
message: "Offset must be numeric")
let n-rows = data.len()
let n-cols = data.at(0).len()
if n-rows < 2 or n-cols < 2 {
return ()
}
assert(op == auto or type(op) in (str, function),
message: "Operator must be of type auto, string or function")
if op == auto {
op = if offset < 0 { "<=" } else { ">=" }
}
if type(op) == str {
assert(op in ("<", "<=", ">", ">=", "==", "!="),
message: "Operator must be one of: <, <=, >, >=, != or ==")
}
// Return if data is set
let is-set = if type(op) == function {
v => op(offset, v)
} else if op == "==" {
v => v == offset
} else if op == "!=" {
v => v != offset
} else if op == "<" {
v => v < offset
} else if op == "<=" {
v => v <= offset
} else if op == ">" {
v => v > offset
} else if op == ">=" {
v => v >= offset
}
// Build a binary map that has 0 for unset and 1 for set cells
let bin-data = data.map(r => r.map(is-set))
// Get binary data at x, y
let get-bin(x, y) = {
if x >= 0 and x < n-cols and y >= 0 and y < n-rows {
return bin-data.at(y).at(x)
}
return false
}
// Get data point for x, y coordinate
let get-data(x, y) = {
if x >= 0 and x < n-cols and y >= 0 and y < n-rows {
return float(data.at(y).at(x))
}
return none
}
// Get case (0 to 15)
let get-case(tl, tr, bl, br) = {
int(tl) * 8 + int(tr) * 4 + int(br) * 2 + int(bl)
}
let lerp(a, b) = {
if a == b { return a }
else if a == none { return 1 }
else if b == none { return 0 }
return (offset - a) / (b - a)
}
// List of all found contours
let contours = ()
let segments = ()
for y in range(-1, n-rows) {
for x in range(-1, n-cols) {
let tl = get-bin(x, y)
let tr = get-bin(x+1, y)
let bl = get-bin(x, y+1)
let br = get-bin(x+1, y+1)
// Corner data
//
// nw-----ne
// | |
// | |
// | |
// sw-----se
let nw = get-data(x, y)
let ne = get-data(x+1, y)
let se = get-data(x+1, y+1)
let sw = get-data(x, y+1)
// Interpolated edge points
//
// +-- a --+
// | |
// d b
// | |
// +-- c --+
let a = (x + .5, y)
let b = (x + 1, y + .5)
let c = (x + .5, y + 1)
let d = (x, y + .5)
if interpolate {
a = (x + lerp(nw, ne), y)
b = (x + 1, y + lerp(ne, se))
c = (x + lerp(sw, se), y + 1)
d = (x, y + lerp(nw, sw))
}
let case = get-case(tl, tr, bl, br)
if case in (1, 14) {
segments.push((d, c))
} else if case in (2, 13) {
segments.push((b, c))
} else if case in (3, 12) {
segments.push((d, b))
} else if case in (4, 11) {
segments.push((a, b))
} else if case == 5 {
segments.push((d, a))
segments.push((c, b))
} else if case in (6, 9) {
segments.push((c, a))
} else if case in (7, 8) {
segments.push((d, a))
} else if case == 10 {
segments.push((a, b))
segments.push((c, d))
}
}
}
// Join lines to one or more contours
// This is done by searching for the next line
// that starts at the current contours head or tail
// point. If found, push the other coordinate to
// the contour. If no line could be found, push a
// new contour.
let contours = ()
while segments.len() > 0 {
if contours.len() == 0 {
contours.push(segments.remove(0))
}
let found = false
let i = 0
while i < segments.len() {
let (a, b) = segments.at(i)
let (h, t) = (contours.last().first(),
contours.last().last())
if a == t {
contours.last().push(b)
segments.remove(i)
found = true
} else if b == t {
contours.last().push(a)
segments.remove(i)
found = true
} else if a == h {
contours.last().insert(0, b)
segments.remove(i)
found = true
} else if b == h {
contours.last().insert(0, a)
segments.remove(i)
found = true
} else {
i += 1
}
}
// Insert the next contour
if not found {
contours.push(segments.remove(0))
}
// Check limit
assert(contours.len() <= contour-limit,
message: "Countour limit reached! Raise contour-limit if you " +
"think this is not an error")
}
return contours
}
// Prepare line data
#let _prepare(self, ctx) = {
let (x, y) = (ctx.x, ctx.y)
self.contours = self.contours.map(c => {
c.stroke-paths = util.compute-stroke-paths(c.line-data, x, y)
if self.fill {
c.fill-paths = util.compute-fill-paths(c.line-data, x, y)
}
return c
})
return self
}
// Stroke line data
#let _stroke(self, ctx) = {
for c in self.contours {
for p in c.stroke-paths {
draw.line(..p, fill: none, close: p.first() == p.last())
}
}
}
// Fill line data
#let _fill(self, ctx) = {
if not self.fill { return }
for c in self.contours {
for p in c.fill-paths {
draw.line(..p, stroke: none, close: p.first() == p.last())
}
}
}
/// Add a contour plot of a sampled function or a matrix.
///
/// #example(```
/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
/// plot.add-contour(x-domain: (-3, 3), y-domain: (-3, 3),
/// style: (fill: rgb(50,50,250,50)),
/// fill: true,
/// op: "<", // Find contours where data < z
/// z: (2.5, 2, 1), // Z values to find contours for
/// (x, y) => calc.sqrt(x * x + y * y))
/// })
/// ```)
///
/// - data (array, function): A function of the signature `(x, y) => z`
/// or an array of arrays of floats (a matrix) where the first
/// index is the row and the second index is the column.
/// - z (float, array): Z values to plot. Contours containing values
/// above z (z >= 0) or below z (z < 0) get plotted.
/// If you specify multiple z values, they get plotted in the order of specification.
/// - x-domain (domain): X axis domain used if `data` is a function, that is the
/// domain inside the function gets sampled.
/// - y-domain (domain): Y axis domain used if `data` is a function, see `x-domain`.
/// - x-samples (int): X axis domain samples (2 < n). Note that contour finding
/// can be quite slow. Using a big sample count can improve accuracy but can
/// also lead to bad compilation performance.
/// - y-samples (int): Y axis domain samples (2 < n)
/// - interpolate (bool): Use linear interpolation between sample values which can
/// improve the resulting plot, especially if the contours are curved.
/// - op (auto,string,function): Z value comparison oparator:
/// / `">", ">=", "<", "<=", "!=", "=="`: Use the operator for comparison of `z` to
/// the values from `data`.
/// / `auto`: Use ">=" for positive z values, "<=" for negative z values.
/// / `<function>`: Call comparison function of the format `(plot-z, data-z) => boolean`,
/// where `plot-z` is the z-value from the plots `z` argument and `data-z`
/// is the z-value of the data getting plotted. The function must return true
/// if at the combinations of arguments a contour is detected.
/// - fill (bool): Fill each contour
/// - style (style): Style to use for plotting, can be used with a palette function. Note
/// that all z-levels use the same style!
/// - axes (axes): Name of the axes to use for plotting.
/// - limit (int): Limit of contours to create per z value before the function panics
/// - label (none,content): Plot legend label to show. The legend preview for
/// contour plots is a little rectangle drawn with the contours style.
#let add-contour(data,
label: none,
z: (1,),
x-domain: (0, 1),
y-domain: (0, 1),
x-samples: 25,
y-samples: 25,
interpolate: true,
op: auto,
axes: ("x", "y"),
style: (:),
fill: false,
limit: 50,
) = {
// Sample a x/y function
if type(data) == function {
data = sample.sample-fn2(data,
x-domain, y-domain,
x-samples, y-samples)
}
// Find matrix dimensions
assert(type(data) == array)
let (x-min, x-max) = x-domain
let dx = (x-max - x-min) / (data.at(0).len() - 1)
let (y-min, y-max) = y-domain
let dy = (y-max - y-min) / (data.len() - 1)
let contours = ()
let z = if type(z) == array { z } else { (z,) }
for z in z {
for contour in find-contours(data, z, op: op, interpolate: interpolate, contour-limit: limit) {
let line-data = contour.map(pt => {
(pt.at(0) * dx + x-min,
pt.at(1) * dy + y-min)
})
contours.push((
z: z,
line-data: line-data,
))
}
}
return ((
type: "contour",
label: label,
contours: contours,
axes: axes,
x-domain: x-domain,
y-domain: y-domain,
style: style,
fill: fill,
mark: none,
mark-style: none,
plot-prepare: _prepare,
plot-stroke: _stroke,
plot-fill: _fill,
plot-legend-preview: self => {
if not self.fill { self.style.fill = none }
draw.rect((0,0), (1,1), ..self.style)
}
),)
}
|
https://github.com/lucifer1004/leetcode.typ | https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/problems/p0003.typ | typst | #import "../helpers.typ": *
#import "../solutions/s0003.typ": *
= Longest Substring Without Repeating Characters
Given a string `s`, find the length of the *longest substring* without repeating characters.
#let longest-substring-without-repeating-charaters(s) = {
// Solve the problem here
}
#testcases(
longest-substring-without-repeating-charaters,
longest-substring-without-repeating-charaters-ref, (
(s: "abcabcbb"),
(s: "bbbbb"),
(s: "pwwkew"),
)
)
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/construct-05.typ | typst | Other | // Error: 5-11 missing argument: blue component
#rgb(0, 1)
|
https://github.com/CheneyNine/Resume-in-Typst-Template | https://raw.githubusercontent.com/CheneyNine/Resume-in-Typst-Template/main/README.md | markdown | # Resume Template in Typst
使用 Typst 编写的简历模板.
代码上,以[OrangeX4](https://github.com/OrangeX4/Chinese-Resume-in-Typst) 所提供的模板为基础,增加了一定的行距控制,丰富了图标内容。同时也参考了一部分Typst的[中文手册](https://typst-doc-cn.github.io/docs/tutorial/).
功能与外观上,参考了[doubleZ](https://github.com/doubleZ0108)的个人简历作品,非常感谢大佬的耐心指导.
图标来源:https://fontawesome.com/icons/
## 使用
### 在线编辑
https://typst.app/project/wd6vLU2W-o1q2OYTb-JPq-
### 本地编辑
- 安装 VS Code,以及 Typst LSP 和 vscode-pdf 插件。
- 可对 Typst LSP 拓展进行专门设置,在`Export Pdf`项中修改编译时间(保存时、编辑时等)。
### 背景图
背景采用 Photoshop 单独制作,当然模板也在 materials 文件夹内,可以根据需要修改成你想要的学校。
## 效果

|
|
https://github.com/TycheTellsTales/typst-pho | https://raw.githubusercontent.com/TycheTellsTales/typst-pho/main/private.typ | typst | #import emoji: suit
#import sym: triangle
#import "./boards.typ"
#import "./people.typ"
///////////////
// Variables //
///////////////
#let originalPoster = "Original Poster"
////////////////////
// PHO Formatting //
////////////////////
#let centerSquare() = {align(center)[■]}
#let header(username: "Tin Mother") = [
#centerSquare()
#strong[Welcome to the Parahumans Online message boards.] \
You are currently logged in, #emph[#username] \
You are viewing: \
- Threads you have replied to
- AND Threads that have new replies
- OR private message conversations with new replies
- Thread OP is displayed.
- Ten posts per page
- Last ten messages in private message history.
- Threads and private messages are ordered chronologically.
#centerSquare()
]
#let formatTags(tags) = {
for tag in tags [ (#tag) ]
}
#let topic(
title: "",
poster: "",
tags: (),
board: none,
date: "January 1st 1970",
body,
) = [
#context [
#set par(
first-line-indent: 0em,
)
#let person = people.get(poster,
default: (name: poster, tags: tags),
)
#let boardName = context (("Boards",) + boards.resolve(board)).join(" " + triangle.filled.r + " ")
#strong[#suit.diamond Topic: #title] \
#strong[In: #boardName] \
#strong[#person.name] #formatTags((person.tags + tags).dedup()) \
Posted On #date: \
#body
]
]
#let __tenthPost(count) = {
return calc.rem(count.get(), 10) == 0
}
#let __newStart(start, count) = {
calc.floor(start + count.get() / 10)
}
#let __newEnd(start, end, count) = {
let posts = count.final()
let extra = calc.floor(posts / 10)
return calc.max(end, start+extra)
}
#let pageStart(
start,
end,
count
) = [
#let current = __newStart(start, count)
#let end = __newEnd(start, end, count)
\
#strong[(Showing page #current of #end)] \
\
]
#let __formatPageNumber(x, current) = {
if x == current {
return str(x)
}
return underline(str(x))
}
#let pageEnd(
start,
end,
count,
) = {
let current = __newStart(start, count)
let end = __newEnd(start, end, count)
let tmp = ()
// The beginning of the range:
tmp += range(1, calc.min(4, end+1))
// Surrounding the current:
tmp += range(
calc.max(current - 2, 4),
calc.min(current+3, end+1)
)
// The end of the range:
tmp += range(
calc.max(current, end - 2),
end+1,
)
tmp = tmp.dedup()
let pages = ()
let previous = 0
for x in tmp {
if x - previous > 1 {
pages.push(" ... ")
} else if previous != 0 {
pages.push(", ")
}
previous = x
pages.push(__formatPageNumber(x, current))
}
[#strong[End of Page. #pages.join("")]]
}
#let post(
poster: "",
op: "",
date: "January 1st 1970",
tags: (),
body
) = {
let person = people.get(poster, default: (name: poster, tags: tags))
if person.name == op {
person.tags.insert(0, originalPoster)
}
set par(
first-line-indent: 0em,
)
block(inset: 1em)[
#strong[#triangle.filled.r#person.name] #formatTags((person.tags + tags).dedup()) \
Replied On #date: \
#body
]
}
#let paginator(start: 1, end: 1, op: "", date: "", count) = {
return (
poster,
tags: (),
date: date,
body,
) => {
context {
if __tenthPost(count) {
pageStart(start, end, count)
}
}
post(op: op, date: date, poster: poster, tags: tags, body)
context {
[#count.update(x => x+1)]
}
context {
if __tenthPost(count) {
pageEnd(start, end, count)
}
}
}
}
|
|
https://github.com/antonWetzel/Masterarbeit | https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/triangulierung.typ | typst | #import "setup.typ": *
= Triangulierung <triangulierung>
== Ziel
Das Ziel der Triangulierung ist eine Approximation der ursprünglichen Oberfläche von den gescannten Bäumen, welche weiterverarbeitet oder angezeigt werden kann. Die meisten Programme und Hardware sind auf das Anzeigen von Dreiecken spezialisiert und können diese effizienter als Punkte darstellen. Die Triangulierung wird dafür mit den Punkten von einem Bereich berechnet.
== Ball-Pivoting Algorithmus
Beim Ball-Pivoting Algorithmus werden die Dreiecke der Oberfläche bestimmt, welche von einer Kugel mit Radius $alpha$ ($alpha$-Kugel) erreicht werden können. Dabei berührt die Kugel die drei Eckpunkte vom Dreieck und alle anderen Punkte sind außerhalb der Kugel @ball_pivot.
In @ball_pivoting_überblick ist ein Beispiel in 2D gegeben. Dabei werden die Kanten zwischen zwei Punkten gesucht, dass der zugehörige Kreis keine weiteren Punkte enthält. Für die äußeren Punkte in Schwarz wird eine Oberfläche gefunden. Für den inneren Punkt in Rot kann kein Nachbar gefunden werden, weil alle zugehörigen Kreise weitere Punkte enthalten würden.
#let positions = (
(0, 0),
(0.6, 0.2),
(1, 0.1),
(1.5, 0.3),
(1.7, 1.0),
(2, 0.2),
(2, -0.3),
(1.8, -0.6),
(1.3, -0.4),
(0.6, -0.2),
)
#let radius = 0.5
#let draw_circle(a, b, color: gray) = {
import cetz.draw: *
set-style(stroke: black)
let d_x = (b.at(0) - a.at(0)) / 2.0
let d_y = (b.at(1) - a.at(1)) / 2.0
let d_l = calc.sqrt(d_x * d_x + d_y * d_y)
let l = calc.sqrt(radius * radius - d_l * d_l)
let c_x = a.at(0) + d_x - d_y / d_l * l
let c_y = a.at(1) + d_y + d_x / d_l * l
circle((c_x, c_y), radius: radius, stroke: color)
}
#figure(
caption: [Ball-Pivoting Algorithmus in 2D.],
cetz.canvas(length: 1.7cm, {
import cetz.draw: *
for i in range(1, positions.len()) {
draw_circle(positions.at(i - 1), positions.at(i))
}
draw_circle(positions.last(), positions.at(0))
for pos in positions {
circle(pos, radius: 0.1, fill: black)
}
circle((1.7, 0), radius: 0.1, fill: red)
for i in range(1, positions.len()) {
line(positions.at(i - 1), positions.at(i))
}
line(positions.last(), positions.at(0))
}),
) <ball_pivoting_überblick>
Die gefundenen Dreiecke bilden eine äußere Hülle um die Punkte. Je kleiner $alpha$ ist, desto genauer ist die Hülle um die Punkte und Details werden besser wiedergegeben. Dafür werden mehr Dreiecke benötigt und größere Lücken in den Punkten sind auch in der Hülle vorhanden.
=== $alpha$-Kugel für ein Dreieck
Für ein Dreieck $(p_1, p_2, p_3)$ wird die Position der zugehörigen $alpha$-Kugel benötigt. Dafür wird zuerst das Zentrum $c$ vom Umkreis vom Dreieck bestimmt. Von diesem sind alle Eckpunkte gleich weit entfernt. Ist der Abstand $d_c$ vom Zentrum zu den Ecken größer als $alpha$, so gibt es keine zugehörige $alpha$-Kugel. Für Abstände kleiner gleich $alpha$ ist das Zentrum der Kugel $d = sqrt(alpha^2 - d_c^2)$ vom Zentrum vom Umkreis entfernt. Der Vektor $o = (p_2 - p_1) times (p_3 - p_1)$ ist orthogonal zum Dreieck, womit die Position vom Zentrum der $alpha$-Kugel mit $c + d dot o / (norm(o))$ berechnet werden kann.
Durch die Berechnung von $o$ ist die Reihenfolge der Punkte relevant. Vertauschen von zwei Punkten berechnet die $alpha$-Kugel auf der anderen Seite des Dreiecks.
== Ablauf
=== KD-Baum berechnen
Zuerst wird ein KD-Baum für die Punkte im Segment berechnet. Der KD-Baum ermöglicht die effiziente Bestimmung von den nächsten Punkten für eine beliebige Position. Dabei werden nur die Punkte bestimmt, welche näher als ein Maximalabstand von der Position entfernt sind. Die Konstruktion und Verwendung vom KD-Baum wird in @kd_baum erklärt.
Mit dem KD-Baum kann auch überprüft werden, ob in einer $alpha$-Kugel keine weiteren Punkte liegen. Dafür wird der erste Punkt gesucht, der in der Kugel liegt. Wenn kein Punkt gefunden wird, ist die Kugel leer.
=== Startdreieck bestimmen
Als Anfang wird ein Dreieck mit zugehöriger $alpha$-Kugel benötigt, dass keine weiteren Punkte innerhalb der Kugel liegen. Dafür werden alle Punkte iteriert.
Für den momentanen Punkt werden die umliegenden Punkte mit einem Abstand von $2 alpha$ oder weniger bestimmt. Für weiter entfernte Punkte gibt es keine $alpha$-Kugel, welche beide Punkte berühren würde.
Mit dem momentanen Punkt und alle möglichen Kombination von zwei Punkten aus den umliegenden Punkten wird ein Dreieck gebildet. Für das Dreieck wird probiert die zwei möglichen $alpha$-Kugeln zu bestimmen, welche zum Dreieck gehören.
Wenn ein Dreieck mit zugehöriger $alpha$-Kugel gefunden wurde, welche keine weiteren Punkte enthält, kann dieses Dreieck als Startdreieck verwendet werden. Das Dreieck wird zur Triangulierung hinzugefügt und die drei zugehörigen Kanten bilden die momentanen äußeren Kanten, von denen aus die Triangulierung berechnet wird.
=== Triangulierten Bereich erweitern
Solange es noch eine äußere Kante $(p_1, p_2)$ gibt, kann die Triangulierung erweitert werden. Für die Kante ist bereits ein Dreieck und die zugehörige $alpha$-Kugel mit Zentrum $c$ bekannt. Die Kante dient als Pivot, um welches die $alpha$-Kugel gerollt wird. Der erste Punkt $p$, welcher von der Kugel berührt wird, bildet mit $p_1$ und $p_2$ ein neues Dreieck.
In @ball_pivoting_erweiterung ist ein Beispiel für eine Erweiterung in 2D gegeben. Im zweidimensionalen werden Kanten gesucht und Punkte werden als Pivot verwendet. Die vorherige Kante und der momentane Pivot-Punkt sind in Schwarz. Der $alpha$-Kreis rollt entlang der markierten Richtung und berührt zuerst den grünen Punkt. Die weiteren Kandidaten sind in Rot und liegen weiter entlang der Rotation.
#figure(
caption: [
Erweiterung der gefundenen Oberfläche in 2D.
],
cetz.canvas(length: 1.7cm, {
import cetz.draw: *
set-style(stroke: black)
let a = positions.at(8);
let b = positions.at(9);
draw_circle(a, b, color: black)
// for pos in positions {
// circle(pos, radius: 0.1, fill: black)
// }
circle(b, stroke: gray, radius: radius + 0.5);
draw_circle(b, positions.at(0), color: green)
line(a, b, stroke: 2pt)
line(b, positions.at(0), stroke: green + 2pt)
line(b, positions.at(1), stroke: red + 2pt)
line(b, positions.at(2), stroke: red + 2pt)
circle((1.7, 0), radius: 0.1, fill: gray, stroke: none)
circle(positions.at(0), radius: 0.1, fill: green, stroke: none)
circle(positions.at(1), radius: 0.1, fill: red, stroke: none)
circle(positions.at(2), radius: 0.1, fill: red, stroke: none)
circle(positions.at(3), radius: 0.1, fill: gray, stroke: none)
circle(positions.at(4), radius: 0.1, fill: gray, stroke: none)
circle(positions.at(5), radius: 0.1, fill: gray, stroke: none)
circle(positions.at(6), radius: 0.1, fill: gray, stroke: none)
circle(positions.at(7), radius: 0.1, fill: gray, stroke: none)
circle(positions.at(8), radius: 0.1, fill: red, stroke: none)
circle(positions.at(9), radius: 0.1, fill: black)
arc(b, start: -17deg, delta: -190deg, anchor: "origin", radius: 0.3, name: "arc", mark: (end: ">", fill: black))
let m-x = b.at(0) - 0.295
let m-y = b.at(1) + 0.05
}),
) <ball_pivoting_erweiterung>
==== Mögliche Kandidaten bestimmen
Um den ersten Punkt $p$ zu finden, werden zuerst alle möglichen Punkte bestimmt, welche von der Kugel bei der kompletten Rotation berührt werden können. Dafür wird der Mittelpunkt $m p$ der Kante und der Abstand $d$ berechnet.
$ m p = (p_1 + p_2) / 2 #h(40pt) d = norm(p_1-m p) = norm(p_2-m p) $
Der Abstand zwischen dem Zentrum der Kugel und den Endpunkten von der Kante ist immer $alpha$, dadurch ist der Abstand vom Zentrum zum Mittelpunkt der Kante $d_C = sqrt(alpha^2 - d^2)$. In @triangulierung_abstand_kugel ist die Konstruktion veranschaulicht.
#figure(
caption: [Abstand vom Zentrum der $alpha$-Kugel zum Mittelpunkt der Kante.],
cetz.canvas(length: 0.5cm, {
import cetz.draw: *
set-style(stroke: black)
arc((4, 3), start: 10deg, delta: -200deg, anchor: "origin", radius: 5, stroke: gray)
circle((0, 0), radius: 0.1, fill: black)
content((0, 0), $p_1$, anchor: "north", padding: 0.15)
circle((4, 0), radius: 0.1, fill: black)
content((4, 0), $m p$, anchor: "north", padding: 0.15)
circle((8, 0), radius: 0.1, fill: black)
content((8, 0), $p_2$, anchor: "north", padding: 0.15)
line((4, 0), (4, 3))
line((0, 0), (4, 3), (8, 0))
line((0, 0), (8, 0))
circle((4, 3), radius: 0.1, fill: black)
content((4, 3), $c$, anchor: "south", padding: 0.15)
content(((0, 0), 2.5, (4, 3)), angle: 30deg, [$alpha$], anchor: "south", padding: 0.15)
content(((4, 3), 2.5, (8, 0)), angle: -30deg, [$alpha$], anchor: "south", padding: 0.15)
content(((4, 0), 1.5, (4, 3)), [$d_c$], anchor: "west", padding: 0.15)
content(((0, 0), 2.0, (4, 0)), [$d$], anchor: "north", padding: 0.15)
arc((4, 0), start: 90deg, stop: 180deg, anchor: "origin", radius: 1)
circle((3.5, 0.5), radius: 0.05, fill: black)
}),
) <triangulierung_abstand_kugel>
Die möglichen Punkte sind vom Zentrum der Kugel $c$ maximal $alpha$ entfernt und $c$ ist vom Mittelpunkt $m p$ genau $d_c$ weit entfernt. Deshalb werden mit dem KD-Baum die Punkte in der Kugel mit Zentrum $m p$ und Radius $alpha + d_c$ als mögliche Kandidaten bestimmt.
==== Besten Kandidaten bestimmen
Für jeden Kandidaten $p$ wird berechnet, wie weit die Kugel um die Kante gerollt werden muss, bis die Kugel den Kandidaten berührt. Dafür wird zuerst das Zentrum $c_p$ der $alpha$-Kugel bestimmt, welche $p_1$, $p_2$ und $p$ berührt. Das Zentrum wird dabei wie in @triangulierung_kugel_seite berechnet, dass die Kugel auf der korrekten Seite vom potenziellen Dreieck liegt. $p$ kann so liegen, dass es keine zugehörige $alpha$-Kugel gibt, in diesem Fall wird $p$ nicht weiter betrachtet. Für die restlichen Kandidaten wird der Winkel $phi$ berechnet, wie weit um die Kante die Kugel gerollt wurde.
#figure(
caption: [Berechnung von Zentrum der $alpha$-Kugel und zugehöriger Winkel für einen Kandidaten.],
cetz.canvas(length: 1.2cm, {
import cetz.draw: *
set-style(stroke: black)
line((0, 0, 0), (0, 0, 2), (-2.4, 0, 1), close: true, name: "wow")
line((0, 0, 0), (0, 0, 2), (2.4, -1.2, 1), close: true)
line((-1, 0, 1), (-1, 2, 1), name: "c", stroke: gray)
line((1, -0.5, 1), (1.7, 1.3, 1), name: "cp", stroke: gray)
circle((-1.9, 0.5), radius: 0.03, fill: black)
content((0, 0, 0), $p_1$, anchor: "north", padding: 0.15)
circle((0, 0, 0), radius: 0.03, fill: black)
content((1, 1), $p_2$, anchor: "south", padding: 0.15)
circle((1, 1), radius: 0.03, fill: black)
content((2.9, -0.7), $p$, anchor: "west", padding: 0.15)
circle((2.9, -0.7), radius: 0.03, fill: black)
content((-0.5, 2.5), $c$, anchor: "south", padding: 0.15)
circle((-0.5, 2.5), radius: 0.03, fill: black)
content((2.2, 1.8), $c_p$, anchor: "south", padding: 0.15)
circle((2.2, 1.8), radius: 0.03, fill: black)
arc((-1, 0, 1), start: 0deg, delta: 90deg, anchor: "origin", radius: 0.3, stroke: gray)
arc((1, -0.5, 1), start: 70deg, delta: 90deg, anchor: "origin", radius: 0.3, stroke: gray)
content((0.5, 0.5), $m p$, anchor: "west", padding: 0.15)
circle((0.5, 0.5), radius: 0.03, fill: black)
line((-0.5, 2.5), (0.5, 0.5), (2.2, 1.8))
arc((0.5, 0.5), start: 37.5deg, delta: 79deg, anchor: "origin", radius: 1.2, stroke: gray, mark: (start: ">", fill: gray))
content((0.6, 1.3), $phi$, anchor: "south", padding: 0.15)
}),
) <triangulierung_kugel_seite>
Mit $m p$, $c$ und $c_p$ wird der Winkel $phi$ bestimmt. Dafür werden die normalisierten Vektoren $a$ und $b$ berechnet.
$ a = (c - m p) / norm(c - m p) #h(40pt) b = (c_p - m p) / norm(c_p - m p) $
Der Kosinus von $phi$ ist dabei das Skalarprodukt $s =a dot b$. Zusätzlich wird mit dem Kreuzprodukt $k =a times b$ die Richtung $r$ bestimmt, um die Winkel mit gleichen Kosinus zu unterscheiden.
$ k = a times b #h(40pt) r = k dot (p_2 - p_1) #h(40pt) phi = cases(
arccos(s) & "falls" & r >= 0,
tau - arccos(s) & "falls" & r < 0,
) $
Von allen Kandidaten wird der Punkt $p_3$ ausgewählt, für den $phi$ am kleinsten ist. Wenn $p_1 = p_3$ oder $p_2 = p_3$, dann gibt es keinen dritten Punkt, um die Triangulierung zu erweitern und kein weiteres Dreieck wird für die Kante hinzugefügt.
Es muss nicht kontrolliert werden, ob ein Punkt in der $alpha$-Kugel von $(p_1, p_2, p_3)$ liegt, weil diese immer leer ist. Würde ein weiterer Punkt in der Kugel liegen, so würde der zugehörige Winkel $phi$ von diesem Punkt kleiner sein, weil der Punkt beim Rollen um die Kante früher von der Kugel berührt wird. Weil $p_3$ aber zum kleinsten Winkel gehört, ist die zugehörige $alpha$-Kugel immer leer. Dies gilt aber nur, wenn die Kugel vor dem Rollen bereits leer war.
==== Triangulierung erweitern
Das neu gefundene Dreieck mit den Eckpunkten $(p_1, p_2, p_3)$ wird zur Triangulierung hinzugefügt. Die Kante ($p_1, p_2$) wird von den äußeren Kanten entfernt, dafür werden die neuen Kanten $(p_1, p_3)$ und $(p_3, p_2)$ hinzugefügt. Wenn eine der neuen Kante in den äußeren Kanten bereits vorhanden ist, wird diese nicht hinzugefügt, sondern von den äußeren Kanten entfernt, weil das zugehörige zweite Dreieck auf der anderen Seite der Kante bereits gefunden wurde. Eine Veranschaulichung ist in @triangulierung_erweiterung gegeben.
#figure(
caption: [Erweiterung der Triangulierung in 3D.],
box(width: 90%, grid(
columns: 1 * 2,
column-gutter: 2em,
row-gutter: 1em,
subfigure(image("../images/pivot_0.png", width: 70%), caption: [Kante mit zugehörigem Dreieck, #box[$alpha$-Kugel] und Ring mit Radius $d_c$]),
subfigure(image("../images/pivot_1.png", width: 70%), caption: [Kugel mit Radius $alpha + d_c$, welche alle Kandidaten enthält]),
subfigure(image("../images/pivot_2.png", width: 70%), caption: [Erster Punkt, welcher entlang der Rotation die Kugel berührt]),
subfigure(image("../images/pivot_3.png", width: 70%), caption: [Triangulierung, mit dem neuen Dreieck hinzugefügt]),
)),
) <triangulierung_erweiterung>
=== Komplettes Segment triangulieren
Solange es noch äußere Kanten gibt, kann von diesen aus die Triangulierung erweitert werden. Dabei muss beachtet werden, dass durch Ungenauigkeiten bei der Berechnung eine Kante mehrfach gefunden werden kann. Um eine erneute Triangulierung von bereits triangulierten Bereichen zu verhindern, werden alle inneren Kanten gespeichert und neue Kanten nur zu den äußeren Kanten hinzugefügt, wenn diese noch nicht in den inneren Kanten vorhanden sind.
Wenn es keine weiteren äußeren Kanten gibt, muss ein neues Startdreieck gefunden werden. Dabei werden nur die Punkte in Betracht gezogen, welche zu noch keinem Dreieck gehören. Wenn kein Startdreieck gefunden werden kann, ist das Segment vollständig trianguliert.
== Vorauswahl
Vor der Triangulierung wird mit einem Mindestabstand die Menge der Punkte berechnet, welche betrachtet werden. Dafür wird eine Teilmenge der Punkte bestimmt, dass die Punkte paarweise mindestens den Mindestabstand voneinander entfernt sind.
Für die Berechnung wird ein Greedy-Algorithmus verwendet. Am Anfang werden alle Punkte zur Teilmenge hinzugefügt und danach werden die Punkte in der Teilmenge iteriert. Für jeden Punkt wird mit dem KD-Baum die Punkte in der Nachbarschaft bestimmt, welche näher als den Mindestabstand zum momentanen Punkt liegen. Die nahen Punkte werden aus der Teilmenge entfernt und der nächste Punkt in der Teilmenge wird betrachtet.
== Auswahl von $alpha$
In @triangulierung_alpha wurde die Triangulation für die gleiche Punktwolke mit unterschiedlichen Werten für $alpha$ berechnet. Im oberen Bild sind die Dreiecke ausgefüllt und im unteren Bild umrandet. Mit einem größerem $alpha$ wird das Ergebnis immer weiter vereinfacht. Bei einem kleinen Wert für $alpha$ entstehen Lücken in der Triangulierung, wenn die Punkte weiter als $2 alpha$ voneinander entfernt sind.
#let lines_and_mesh(prec) = {
stack(
dir: ttb,
image("../images/crop/triangulation_mesh_" + prec + ".png"),
image("../images/crop/triangulation_lines_" + prec + ".png"),
)
}
#figure(
caption: [Triangulation für unterschiedliche $alpha$.],
box(width: 80%, grid(
columns: 1 * 5,
subfigure(
caption: number(0.2, unit: [m]),
lines_and_mesh("0.2"),
),
subfigure(
caption: number(0.5, unit: [m]),
lines_and_mesh("0.5"),
),
subfigure(
caption: number(1.0, unit: [m]),
lines_and_mesh("1.0"),
),
subfigure(
caption: number(2.0, unit: [m]),
lines_and_mesh("2.0"),
),
subfigure(
caption: number(5.0, unit: [m]),
lines_and_mesh("5.0"),
),
)),
) <triangulierung_alpha>
Der Bereich für die Suche vom nächsten Kandidaten für die Erweiterung von der Triangulierung ist abhängig von $alpha$. Dadurch steigt der Berechnungsaufwand mit größerem $alpha$, weil mehr Dreiecke und jeweils mehr Kandidaten berechnet werden müssen.
Im Idealfall wird $alpha$ so klein gewählt, dass keine gewünschten Details verloren gehen und so groß, dass keine Lücken in der Triangulierung entstehen.
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/docs/reference/styling.md | markdown | Apache License 2.0 | ---
description: All concepts needed to style your document with Typst.
---
# Styling
Typst includes a flexible styling system that automatically applies styling of
your choice to your document. With _set rules,_ you can configure basic
properties of elements. This way, you create most common styles. However, there
might not be a built-in property for everything you wish to do. For this reason,
Typst further supports _show rules_ that can completely redefine the appearance
of elements.
## Set rules
With set rules, you can customize the appearance of elements. They are written
as a [function call]($function) to an [element
function]($function/#element-functions) preceded by the `{set}` keyword (or
`[#set]` in markup). Only optional parameters of that function can be provided
to the set rule. Refer to each function's documentation to see which parameters
are optional. In the example below, we use two set rules to change the
[font family]($text.font) and [heading numbering]($heading.numbering).
```example
#set heading(numbering: "I.")
#set text(
font: "New Computer Modern"
)
= Introduction
With set rules, you can style
your document.
```
A top level set rule stays in effect until the end of the file. When nested
inside of a block, it is only in effect until the end of that block. With a
block, you can thus restrict the effect of a rule to a particular segment of
your document. Below, we use a content block to scope the list styling to one
particular list.
```example
This list is affected: #[
#set list(marker: [--])
- Dash
]
This one is not:
- Bullet
```
Sometimes, you'll want to apply a set rule conditionally. For this, you can use
a _set-if_ rule.
```example
#let task(body, critical: false) = {
set text(red) if critical
[- #body]
}
#task(critical: true)[Food today?]
#task(critical: false)[Work deadline]
```
## Show rules
With show rules, you can deeply customize the look of a type of element. The
most basic form of show rule is a _show-set rule._ Such a rule is written as the
`{show}` keyword followed by a [selector]($selector), a colon and then a set
rule. The most basic form of selector is an
[element function]($function/#element-functions). This lets the set rule only
apply to the selected element. In the example below, headings become dark blue
while all other text stays black.
```example
#show heading: set text(navy)
= This is navy-blue
But this stays black.
```
With show-set rules you can mix and match properties from different functions to
achieve many different effects. But they still limit you to what is predefined
in Typst. For maximum flexibility, you can instead write a show rule that
defines how to format an element from scratch. To write such a show rule,
replace the set rule after the colon with an arbitrary [function]($function).
This function receives the element in question and can return arbitrary content.
Different [fields]($scripting/#fields) are available on the element passed to
the function. Below, we define a show rule that formats headings for a fantasy
encyclopedia.
```example
#set heading(numbering: "(I)")
#show heading: it => [
#set align(center)
#set text(font: "Inria Serif")
\~ #emph(it.body)
#counter(heading).display() \~
]
= Dragon
With a base health of 15, the
dragon is the most powerful
creature.
= Manticore
While less powerful than the
dragon, the manticore gets
extra style points.
```
Like set rules, show rules are in effect until the end of the current block or
file.
Instead of a function, the right-hand side of a show rule can also take a
literal string or content block that should be directly substituted for the
element. And apart from a function, the left-hand side of a show rule can also
take a number of other _selectors_ that define what to apply the transformation
to:
- **Everything:** `{show: rest => ..}` \
Transform everything after the show rule. This is useful to apply a more
complex layout to your whole document without wrapping everything in a giant
function call.
- **Text:** `{show "Text": ..}` \
Style, transform or replace text.
- **Regex:** `{show regex("\w+"): ..}` \
Select and transform text with a regular expression for even more flexibility.
See the documentation of the [`regex` type]($regex) for details.
- **Function with fields:** `{show heading.where(level: 1): ..}` \
Transform only elements that have the specified fields. For example, you might
want to only change the style of level-1 headings.
- **Label:** `{show <intro>: ..}` \
Select and transform elements that have the specified label. See the
documentation of the [`label` type]($label) for more details.
```example
#show "Project": smallcaps
#show "badly": "great"
We started Project in 2019
and are still working on it.
Project is progressing badly.
```
|
https://github.com/pku-typst/meppp | https://raw.githubusercontent.com/pku-typst/meppp/main/README.md | markdown | MIT License | # meppp
A simple template for modern physics experiments (MPE) courses at the Physics School of PKU.
## meppp-lab-report
The recommended report format of MPE course.
Default arguments are shown as below:
```typ
#import "@preview/meppp:0.2.1": *
#let meppp-lab-report(
title: "",
author: "",
info: [],
abstract: [],
keywords: (),
author-footnote: [],
heading-numbering-array: ("I" ,"A", "1", "a"),
heading-suffix: ". ",
doc,
) = ...
```
- `title` is the title of the report.
- `author` is the name of the author.
- `info` is a line (or lines) of brief information of author and the report (e.g. student ID, school, experiment date...)
- `abstract` is the abstract of the report, not shown when it is empty.
- `keywords` are keywords of the report, only shown when the abstract is shown.
- `author-footnote` is the phone number or the e-mail of the author, shown in the footnote.
- `heading-numbering-array` is the heading numbering of each level. Only shows the numbering of the deepest level.
- `heading-suffix` is the suffix of headings
It is recommended to use `#show` to use the template:
```typ
#show: meppp-lab-report.with(
title: [Test title],
..args
)
...your report below.
```
## meppp-tl-table
Modify your input `table` to a three-lined table (AIP style), returned as a `figure`. Double-lines above and below the table, and a single line below the header.
```typ
#let meppp-tl-table(
caption: none,
supplement: auto,
stroke: 0.5pt,
tbl
) = ...
```
- `caption` is the caption above the table, center-aligned
- `supplement` is same as the supplement in the figure.
- `stroke` is the stroke used in the three lines (maybe five lines).
- `tbl` is the input table, which must contains a `table.header`
Example:
```typ
#meppp-tl-table(
table(
columns: 4,
rows: 2,
table.header([Item1], [Item2], [Item3], [Item4]),
[Data1], [Data2], [Data3], [Data4],
)
)
```
## subfigure
Counts subfigures and displays in the figure, mostly used when inserting multiple images.
```typ
#let subfigure(
body,
caption: none,
numbering: "(a)",
inside: true,
dx: 10pt,
dy: 10pt,
boxargs: (fill: white, inset: 5pt),
alignment: top + left,
) = ...
```
## pku-logo
The logo of PKU, returned as a `image`
```typ
#let pku-logo(..args) = image("pkulogo.png", ..args)
```
Example:
``` typ
#pku-logo(width: 50%)
#pku-logo()
```
|
https://github.com/jomaway/typst-linguify | https://raw.githubusercontent.com/jomaway/typst-linguify/main/lib/fluent.typ | typst | MIT License | #let ftl = plugin("./linguify_fluent_rs/linguify_fluent_rs.wasm")
/// returns a bool
#let has_message(ftl_str, msg_id) = {
str(ftl.has_id(bytes(ftl_str), bytes(msg_id))) == "true"
}
/// Returns the message from the ftl file
/// - `ftl_str` (str): the content of the ftl file
/// - `msg_id` (str): the identifier of the message
/// - `args` (dict): the arguments to pass to the message
/// - `default` (str): the default value to return if the message is not found
///
#let get_message(ftl_str, msg_id, args: none, default: none) = {
if args == none {
args = (:)
}
if not has_message(ftl_str, msg_id) {
return default
}
return str(
ftl.get_message(bytes(ftl_str), bytes(msg_id), bytes(json.encode(args, pretty: false)))
)
}
/// Constructs the data dict needed in `linguify.typ`
/// - `path` (str): the path to the directory containing the ftl files
/// - `languages` (array): the list of languages to load
///
/// Returns a `str`, use `eval` to convert it to a dict
///
/// ## Example:
/// ```typst
/// eval(load_ftl_data("path/to/ftl", ("en", "fr")))
/// ```
#let load_ftl_data(
path,
languages
) = {
assert.eq(type(path), str, message: "expected path to be a string, found " + type(path))
assert.eq(type(languages), array, message: "expected languages to be an array, found " + type(languages))
```Typst
let import_ftl(path, langs) = {
let data = (
conf: (
data_type: "ftl",
ftl: (
languages: langs
),
),
lang: (:)
)
for lang in langs {
data.lang.insert(lang, str(read(path + "/" + lang + ".ftl")))
}
data
}
import_ftl(
"```.text + path + ```",
(```.text + (languages.map((x) => {"\"" + str(x) + "\", "}).sum()).trim(" ") + ```)
)
```.text
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/comment-01.typ | typst | Other | // End should not appear without start.
// Error: 7-9 unexpected end of block comment
/* */ */
// Unterminated is okay.
/*
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/cpp/lectures/2024-10-18.typ | typst | = Параллельное программирование
Зачем:
- хотим выполнять разные операции в одно и то же время (например, одновременно
считать и взаимодействовать с пользователем)
- ускорение на многоядерной системой
Параллельное или конкурентное:
- Параллельное --- хотим решить одну задачу быстрее
- Конкурентное --- есть много задач, которые мы хотим решать одновременно
Возможности C++:
- Потоки
- Асинхронный вызов
- Сопрограмммы (не совсем конкурентность)
- Параллельные алгоритмы STL
Средства создать параллельных приложений:
- Примитивы C++
- OpenMP (стандарт для написания параллельных программ)
- MPI (для кластеров)
- Сторонние библиотеки (Intel TBB, HPX)
== Параллельные алгоритмы STL
```cpp
#include <vector>
#include <algorithm>
#include <execution>
int main() {
std::vector<int> vec{1, 5, 2, 10, 3};
std::sort(std::execution::par, vec.begin(), vec.end());
}
```
== OpenMP
```cpp
double res[LEN];
int i;
#pragma omp parallel for num_threads(10)
for (i = 0; i < LEN; ++i) {
res[i] = long_running(i);
}
g++ -openmp file.cpp
```
== С процессом
```c
int main(void) {
pid_t pid;
if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
exit(EXIT_FAILURE);
}
pid = fork();
switch(pid) {
case -1: // ошибка
case 0: // родитель
default: // родитель
}
}
```
== Потоки (thread)
С функцией:
```cpp
void do_some_work();
std::thread my_thread(do_some_work);
```
С функтором:
```cpp
void do_some_work();
struct X {
void operator()() { ... }
}
std::thread my_thread{X()};
```
У нового thread-а и его родителя общее адресное пространство.
До удаления std::thread нужно сделать либо:
- `join()` --- блокируемся до завершения
- `detach()` --- отсоединяем процесс, он работает в фоне
Отсоединенный (detach) процесс завершится либо сам, либо вместе с main
```cpp
#include <thread>
#include <iostream>
void f() {
for (size_t i = 0; i < 100; ++i) {
std::cout << i << std::endl;
}
}
int main() {
std::thread t(f);
t.detach(); // ничего не выведетя
// t.join(); // так выведется всё
}
```
=== Передача аргументов
```cpp
void f(int val);
struct X {
f(int val);
};
// Вызов функции
std::thread t1(f, 42):
// Вызов метода
X obj;
std::thread(&X::f, &obj, 42);
```
Аргументы копируются во внутреннее хранилище, а затем передаются, как r-value.
=== Проблемы с life-time-ом
```cpp
void f(int*);
void caller() {
int data[100];
std::thread t(f, data); // UB: data умирает раньше завершения f
t.detach();
}
```
=== Полезные вещи
- `std::thread`
- `std::thread::hardware_concurrency()`
- `std::this_thread::get_id()`
- `std::this_thread::sleep_for(/* time */)` --- надо делать так, ибо обычный
`sleep` усыпит весь процесс (все thread-ы)
- `std::this_thread::sleep_until(/* ... */)`
- `std::this_thread::yield()`
=== Проблема совместного доступа
Всё хорошо только тогда, когда есть
- либо только много читающих thread-ов
- либо только один пишущий thread
=== <NAME> (нет, другой)
```
status[i] in {competing, out, crit}
turn in {1, ..., N}
repeat
while turn != i do
if status[turn] == out then
turn := i
end if
end while
status[i] = cs
until not exists other : satus[other] = cs
CS
status[i] = out
```
=== `std::mutex` и `std::lock_guard`
Реализует взаимное исключение
|
|
https://github.com/sarah-quinones/inria-slides-2024-02-20 | https://raw.githubusercontent.com/sarah-quinones/inria-slides-2024-02-20/main/slides.typ | typst | // 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)
#set text(
font: ("New Computer Modern Sans", "Noto Color Emoji"),
)
// Use #polylux-slide to create a slide and style it using your favourite Typst functions
#polylux-slide[
#align(horizon + center)[
= faer-rs, a Linear Algebra Library For The Rust Programming Language
<NAME>
February 20, 2024
]
]
#polylux-slide[
== Why Rust?
#only((beginning: 1))[- Memory safety]
#only((beginning: 1))[- Extremely competitive performance]
#only((beginning: 1))[- Generic SIMD support with runtime dispatch]
#only((beginning: 1))[- Robust error handling]
#only((beginning: 1))[- Excellent compiler errors and runtime diagnostic capabilities]
#only((beginning: 2))[- #box(height: 20pt, image("sparkling-heart.svg")) Cargo my beloved #box(height: 20pt, image("sparkling-heart.svg"))]
]
#polylux-slide[
== faer's top features currently
- Vectorized and optimized for x86 (AVX2/AVX512) and ARM64
- Fine control over multithreading
- Matrix arithmetic
- Matrix decompositions (Cholesky, QR, LU), with optional pivoting
- Simplicial and supernodal sparse decompositions
- Solving linear systems
- Computing the SVD/EVD (dense implemented, sparse solver is on the way)
]
#polylux-slide[
== Example (dense)
```rust
fn main() {
let a = Mat::from_fn(4, 4, |i, j| i as f64 + j as f64);
let b = mat![[1.0], [2.0], [3.0], [4.0]];
// solving a linear system (selfadjoint)
let lblt = a.lblt(faer::Side::Lower);
let x = lblt.solve(&b);
// [src/main.rs:65:5] (&a * &x - &b).norm_l2() = 0.0
dbg!((&a * &x - &b).norm_l2());
}
```
]
#polylux-slide[
== Example (dense)
```rust
fn main() {
let a = Mat::from_fn(4, 4, |i, j| i as f64 + j as f64);
// computing eigenvalues
let complex_eigenvalues = a.eigenvalues::<c64>();
let real_eigenvalues = a.selfadjoint_eigenvalues(Lower);
dbg!(&complex_eigenvalues);
dbg!(&real_eigenvalues);
}
```
]
#polylux-slide[
== Example (sparse)
#set text(size: 15pt)
```rust
fn main() {
let a = SparseColMat::<usize, f64>::try_new_from_triplets(
4, 4,
&[
(0, 0, 10.0), (1, 1, 20.0), (2, 2, 30.0), (3, 3, 40.0),
(0, 1, 3.0), (1, 0, 2.0), (3, 2, 1.0),
],
).unwrap();
let b = mat![[1.0], [2.0], [3.0], [4.0]];
// solving a linear system
let lu = a.as_ref().sp_lu().unwrap();
let x = lu.solve(&b);
dbg!((&a * &x - &b).norm_l2());
}
```
]
#polylux-slide[
== Example (sparse)
#set text(size: 15pt)
```rust
fn main() {
let a = SparseColMat::<usize, f64>::try_new_from_triplets(
4, 4,
&[
(0, 0, 10.0), (1, 1, 20.0), (2, 2, 30.0), (3, 3, 40.0),
(0, 1, 3.0), (1, 0, 2.0), (3, 2, 1.0),
],
).unwrap();
let b = mat![[1.0], [2.0], [3.0], [4.0]];
// splitting up the solve into symbolic and numeric parts
// the symbolic part is cheap to copy.
let lu_symbolic = solvers::SymbolicLu::try_new(a.as_ref().symbolic()).unwrap();
let lu_numeric = solvers::Lu::try_new_with_symbolic(lu_symbolic.clone(), a.as_ref()).unwrap();
let x = lu_numeric.solve(&b);
dbg!((&a * &x - &b).norm_l2());
}
```
]
#polylux-slide[
== Error diagnostic examples
Adding a matrix to a column
#set text(size: 15pt)
```
error[E0277]: the trait bound `Dense: MatAdd<DenseCol>` is not satisfied
--> src/main.rs:17:9
|
17 | lhs + rhs
| ^ the trait `MatAdd<DenseCol>` is not implemented for `Dense`
|
= help: the trait `MatAdd<Dense>` is implemented for `Dense`
= help: for that trait implementation, expected `Dense`, found `DenseCol`
= note: required for `Matrix<DenseRef<'_, f64>>` to implement `std::ops::Add<Matrix<DenseColRef<'_, f64>>>`
```
]
#polylux-slide[
== Error diagnostic examples
Returning a dangling reference to a local variable
#set text(size: 15pt)
```rust
fn returning_dangling_reference<'a>(lhs: MatRef<'a, f64>, rhs: MatRef<'a, f64>) -> MatRef<'a, f64> {
let mut m = lhs + rhs;
m.as_ref()
}
```
```
error[E0515]: cannot return value referencing local variable `m`
--> src/main.rs:31:5
|
31 | m.as_ref()
| -^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `m` is borrowed here
```
]
#polylux-slide[
== Error diagnostic examples
Trying to read and mutate a matrix at the same time.
#set text(size: 15pt)
```rust
fn breaking_no_alias_guarantees(mut dst: MatMut<'_, c64>) {
let a = dst.as_ref();
faer_core::mul::matmul(
dst.as_mut(), a, a.adjoint(), None, c64::new(1.0, 0.0), faer::Parallelism::None
);
}
```
```
error[E0502]: cannot borrow `dst` as mutable because it is also borrowed as immutable
--> src/main.rs:47:9
|
45 | let a = dst.as_ref();
| --- immutable borrow occurs here
46 | faer_core::mul::matmul(
47 | dst.as_mut(),
| ^^^^^^^^^^^^ mutable borrow occurs here
48 | a,
| - immutable borrow later used here
```
]
#polylux-slide[
== Error diagnostic examples
Mismatching dimensions at runtime.
#set text(size: 15pt)
```rust
let a = Mat::<f64>::zeros(5, 4);
let b = Mat::<f64>::zeros(4, 5);
let _ = &a + &b;
```
\
```
thread 'main' panicked at src/main.rs:127:17:
Assertion failed at /home/sarah/.cargo/git/checkouts/faer-rs-40fd231bb00bdbde/fa5e486/faer-libs/faer-core/src/matrix_ops.rs:1522:9
Assertion failed: lhs.nrows() == rhs.nrows()
- lhs.nrows() = 5
- rhs.nrows() = 4
Assertion failed: lhs.ncols() == rhs.ncols()
- lhs.ncols() = 4
- rhs.ncols() = 5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
]
#polylux-slide[
== Benchmarks (dense QR)
#align(horizon + center)[
#image("qr.svg", height: 80%)
]
]
#polylux-slide[
== Benchmarks (sparse Cholesky)
#set text(size: 15pt)
#box(height: 250pt,
columns(2, gutter: 5pt)[
```
SSLSQ / NYPA_Maragal_6_lasso:
Clarabel / QDLDL : 23.5s
Clarabel / faer : 4.13s
MOSEK : 4.73s
SSLSQ / ANSYS_Delor295K_huber:
Clarabel / QDLDL : 8.47s
Clarabel / faer : 8.04s
MOSEK : 12.5s
NETLIB / nug15:
Clarabel / QDLDL : 133s
Clarabel / faer : 16.5s
MOSEK : 9.44s
```
```
MAROS / EXDATA:
Clarabel / QDLDL : 9.66s
Clarabel / faer : 2.58s
MOSEK : 2.34s (failed)
MAROS / CONT-300:
Clarabel / QDLDL : 24.3s
Clarabel / faer : 11.8s
MOSEK : 5.96s
SUITESPARSE MATRIX COLLECTION / ND3K:
SuiteSparse / CHOLMOD : 2.2s
faer : 1.0s
Eigen : ∞ (timeout)
```
]
)
]
#polylux-slide[
#align(horizon + center)[
= Thank you!
#align(horizon + left)[
\
\
#box(height: 20pt, image("github.svg"))\
github.com/sarah-ek/faer-rs\
github.com/sarah-ek/inria-slides-2024-02-20
]
]
]
|
|
https://github.com/RolfBremer/gloss-awe | https://raw.githubusercontent.com/RolfBremer/gloss-awe/main/gloss-awe.typ | typst | Apache License 2.0 | // Copyright 2023 <NAME>, <NAME>
// Extracts (nested) content or text to text
#let as-text(element, sep: "") = {
if element == none {
return none
}
let elementtype = type(element)
if elementtype in (array, dictionary, smartquote) {
return none
}
if elementtype == content {
if element.has("text") {
element.text
// } else if element
} else if element.has("children") {
element
.children
.map(c => {
as-text(c, sep: sep)
})
.join(sep)
} else if element.has("body") {
as-text(element.body)
} else {
none
}
} else {
str(element)
}
}
#let as-text(input) = {
let t = type(input)
if input == none or input == auto {
""
} else if t == str {
input
} else if t == label {
repr(input)
} else if t == int {
str(input)
} else if t == content {
if input.has("text") {
input.text
} else if input.has("children") {
if input.children.len() == 0 {
""
} else {
input.children.map(child => as-text(child)).join("")
}
} else if input.has("body") {
as-text(input.body)
} else {
" "
}
} else {
panic("Unexpected entry type " + t + " of " + repr(input))
}
}
// gls[term]: Marks a term in the document as referenced.
// gls(glossary-term)[term]: Marks a term in the document as referenced with a
// different expression ("glossary-term") in the glossary.
#let gls(entry: none, showmarker: m => m, display) = (
context {
if showmarker != none {
showmarker(display)
}
let md = metadata((
location: here().position(),
entry: as-text(entry),
display: display,
))
[#md<jkrb-gloss-awe>]
}
)
// Add a keyword to the glossary, even if it is not in the documents content.
#let gls-add = gls.with(showmarker: none)
// This function creates a glossary page with entries for every term
// in the document marked with `gls[term]`.
#let make-glossary(
// Indicate missing entries.
missing: text(fill: red, weight: "bold")[ No glossary entry ],
// Function to format the Header of the entry.
heading: it => { heading(level: 2, numbering: none, outlined: false, it)},
// This array contains entry titles to exclude from the generated glossary page.
excluded: (),
// Function used to sort by.
sort-key: k => k,
// If set to true, the missing entries will be suppressed.
suppress-missing: false,
// The glossary data.
..glossaries
) = {
let get-str-title(glossmeta) = {
let val = glossmeta.value
return if val.entry == none or val.entry == "" {
if type(val.display) == str {
(display: val.display, entry: val.display)
} else {
(display: val.display, entry: as-text(val.display))
}
} else {
if type(val.entry) == str {
(display: val.display, entry: val.entry)
} else {
(display: val.display, entry: as-text(val.entry))
}
}
}
let lookup(key, glossaries) = {
let entry = none
for glossary in glossaries.pos() {
// Skip empty glossary pools
if glossary == none or glossary.len() == 0 {
continue
}
if glossary.keys().contains(key) {
let entry = glossary.at(key)
return entry
}
}
return entry
}
context {
let words = () //empty array
// find all marked elements
let all-elements = query(<jkrb-gloss-awe>)
// only use the not hidden elements
let elements = ()
for e in all-elements {
if get-str-title(e) not in excluded {
elements.push(e)
}
}
// extract the titles
let titles = elements.map(e => get-str-title(e)).sorted(key: e => sort-key(e.entry))
for t in titles {
// Skip doubles
if words.contains(t.entry) {
continue
}
words.push(t.entry)
heading(t.display)
let e = lookup(t.entry, glossaries)
if e != none {
e.description
if e.keys().contains("link") {
e.link
}
} else {
if not suppress-missing {
missing
}
}
}
}
}
|
https://github.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game | https://raw.githubusercontent.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game/main/README.md | markdown | # typst-assignment-template
This is a simple template for topic questions, modified from the [typst-assignment-template](https://github.com/gRox167/typst-assignment-template) repository.
|
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/book/src/dynamic/alternatives-fn.typ | typst | #import "../../../polylux.typ": *
#set page(paper: "presentation-16-9")
#set text(size: 60pt)
#polylux-slide[
#alternatives-fn(start: 2, count: 7, subslide => {
numbering("(i)", subslide)
})
]
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/180.%20lesson.html.typ | typst | lesson.html
The Lesson to Unlearn
December 2019
The most damaging thing you learned in school wasn't something you
learned in any specific class. It was learning to get good grades.When I was in college, a particularly earnest philosophy grad student
once told me that he never cared what grade he got in a class, only
what he learned in it. This stuck in my mind because it was the
only time I ever heard anyone say such a thing.For me, as for most students, the measurement of what I was learning
completely dominated actual learning in college. I was fairly
earnest; I was genuinely interested in most of the classes I took,
and I worked hard. And yet I worked by far the hardest when I was
studying for a test.In theory, tests are merely what their name implies: tests of what
you've learned in the class. In theory you shouldn't have to prepare
for a test in a class any more than you have to prepare for a blood
test. In theory you learn from taking the class, from going to the
lectures and doing the reading and/or assignments, and the test
that comes afterward merely measures how well you learned.In practice, as almost everyone reading this will know, things are
so different that hearing this explanation of how classes and tests
are meant to work is like hearing the etymology of a word whose
meaning has changed completely. In practice, the phrase "studying
for a test" was almost redundant, because that was when one really
studied. The difference between diligent and slack students was
that the former studied hard for tests and the latter didn't. No
one was pulling all-nighters two weeks into the semester.Even though I was a diligent student, almost all the work I did in
school was aimed at getting a good grade on something.To many people, it would seem strange that the preceding sentence
has a "though" in it. Aren't I merely stating a tautology? Isn't
that what a diligent student is, a straight-A student? That's how
deeply the conflation of learning with grades has infused our
culture.Is it so bad if learning is conflated with grades? Yes, it is bad.
And it wasn't till decades after college, when I was running Y Combinator, that I realized how bad it is.I knew of course when I was a student that studying for a test is
far from identical with actual learning. At the very least, you
don't retain knowledge you cram into your head the night before an
exam. But the problem is worse than that. The real problem is that
most tests don't come close to measuring what they're supposed to.If tests truly were tests of learning, things wouldn't be so bad.
Getting good grades and learning would converge, just a little late.
The problem is that nearly all tests given to students are terribly
hackable. Most people who've gotten good grades know this, and know
it so well they've ceased even to question it. You'll see when you
realize how naive it sounds to act otherwise.Suppose you're taking a class on medieval history and the final
exam is coming up. The final exam is supposed to be a test of your
knowledge of medieval history, right? So if you have a couple days
between now and the exam, surely the best way to spend the time,
if you want to do well on the exam, is to read the best books you
can find about medieval history. Then you'll know a lot about it,
and do well on the exam.No, no, no, experienced students are saying to themselves. If you
merely read good books on medieval history, most of the stuff you
learned wouldn't be on the test. It's not good books you want to
read, but the lecture notes and assigned reading in this class.
And even most of that you can ignore, because you only have to worry
about the sort of thing that could turn up as a test question.
You're looking for sharply-defined chunks of information. If one
of the assigned readings has an interesting digression on some
subtle point, you can safely ignore that, because it's not the sort
of thing that could be turned into a test question. But if the
professor tells you that there were three underlying causes of the
Schism of 1378, or three main consequences of the Black Death, you'd
better know them. And whether they were in fact the causes or
consequences is beside the point. For the purposes of this class
they are.At a university there are often copies of old exams floating around,
and these narrow still further what you have to learn. As well as
learning what kind of questions this professor asks, you'll often
get actual exam questions. Many professors re-use them. After
teaching a class for 10 years, it would be hard not to, at least
inadvertently.In some classes, your professor will have had some sort of political
axe to grind, and if so you'll have to grind it too. The need for
this varies. In classes in math or the hard sciences or engineering
it's rarely necessary, but at the other end of the spectrum there
are classes where you couldn't get a good grade without it.Getting a good grade in a class on x is so different from learning
a lot about x that you have to choose one or the other, and you
can't blame students if they choose grades. Everyone judges them
by their grades � graduate programs, employers, scholarships, even
their own parents.I liked learning, and I really enjoyed some of the papers and
programs I wrote in college. But did I ever, after turning in a
paper in some class, sit down and write another just for fun? Of
course not. I had things due in other classes. If it ever came to
a choice of learning or grades, I chose grades. I hadn't come to
college to do badly.Anyone who cares about getting good grades has to play this game,
or they'll be surpassed by those who do. And at elite universities,
that means nearly everyone, since someone who didn't care about
getting good grades probably wouldn't be there in the first place.
The result is that students compete to maximize the difference
between learning and getting good grades.Why are tests so bad? More precisely, why are they so hackable?
Any experienced programmer could answer that. How hackable is
software whose author hasn't paid any attention to preventing it
from being hacked? Usually it's as porous as a colander.Hackable is the default for any test imposed by an authority. The
reason the tests you're given are so consistently bad � so consistently
far from measuring what they're supposed to measure � is simply
that the people creating them haven't made much effort to prevent
them from being hacked.But you can't blame teachers if their tests are hackable. Their job
is to teach, not to create unhackable tests. The real problem is
grades, or more precisely, that grades have been overloaded. If
grades were merely a way for teachers to tell students what they
were doing right and wrong, like a coach giving advice to an athlete,
students wouldn't be tempted to hack tests. But unfortunately after
a certain age grades become more than advice. After a certain age,
whenever you're being taught, you're usually also being judged.I've used college tests as an example, but those are actually the
least hackable. All the tests most students take their whole lives
are at least as bad, including, most spectacularly of all, the test
that gets them into college. If getting into college were merely a
matter of having the quality of one's mind measured by admissions
officers the way scientists measure the mass of an object, we could
tell teenage kids "learn a lot" and leave it at that. You can tell
how bad college admissions are, as a test, from how unlike high
school that sounds. In practice, the freakishly specific nature of
the stuff ambitious kids have to do in high school is directly
proportionate to the hackability of college admissions. The classes
you don't care about that are mostly memorization, the random
"extracurricular activities" you have to participate in to show
you're "well-rounded," the standardized tests as artificial as
chess, the "essay" you have to write that's presumably meant to hit
some very specific target, but you're not told what.As well as being bad in what it does to kids, this test is also bad
in the sense of being very hackable. So hackable that whole industries
have grown up to hack it. This is the explicit purpose of test-prep
companies and admissions counsellors, but it's also a significant
part of the function of private schools.Why is this particular test so hackable? I think because of what
it's measuring. Although the popular story is that the way to get
into a good college is to be really smart, admissions officers at
elite colleges neither are, nor claim to be, looking only for that.
What are they looking for? They're looking for people who are not
simply smart, but admirable in some more general sense. And how
is this more general admirableness measured? The admissions officers
feel it. In other words, they accept who they like.So what college admissions is a test of is whether you suit the
taste of some group of people. Well, of course a test like that is
going to be hackable. And because it's both very hackable and there's
(thought to be) a lot at stake, it's hacked like nothing else.
That's why it distorts your life so much for so long.It's no wonder high school students often feel alienated. The shape
of their lives is completely artificial.But wasting your time is not the worst thing the educational system
does to you. The worst thing it does is to train you that the way
to win is by hacking bad tests. This is a much subtler problem
that I didn't recognize until I saw it happening to other people.When I started advising startup founders at Y Combinator, especially
young ones, I was puzzled by the way they always seemed to make
things overcomplicated. How, they would ask, do you raise money?
What's the trick for making venture capitalists want to invest in
you? The best way to make VCs want to invest in you, I would explain,
is to actually be a good investment. Even if you could trick VCs
into investing in a bad startup, you'd be tricking yourselves too.
You're investing time in the same company you're asking them to
invest money in. If it's not a good investment, why are you even
doing it?Oh, they'd say, and then after a pause to digest this revelation,
they'd ask: What makes a startup a good investment?So I would explain that what makes a startup promising, not just
in the eyes of investors but in fact, is
growth.
Ideally in revenue,
but failing that in usage. What they needed to do was get lots of
users.How does one get lots of users? They had all kinds of ideas about
that. They needed to do a big launch that would get them "exposure."
They needed influential people to talk about them. They even knew
they needed to launch on a tuesday, because that's when one gets
the most attention.No, I would explain, that is not how to get lots of users. The way
you get lots of users is to make the product really great. Then
people will not only use it but recommend it to their friends, so
your growth will be exponential once you
get it started.At this point I've told the founders something you'd think would
be completely obvious: that they should make a good company by
making a good product. And yet their reaction would be something
like the reaction many physicists must have had when they first
heard about the theory of relativity: a mixture of astonishment at
its apparent genius, combined with a suspicion that anything so
weird couldn't possibly be right. Ok, they would say, dutifully.
And could you introduce us to such-and-such influential person? And
remember, we want to launch on Tuesday.It would sometimes take founders years to grasp these simple lessons.
And not because they were lazy or stupid. They just seemed blind
to what was right in front of them.Why, I would ask myself, do they always make things so complicated?
And then one day I realized this was not a rhetorical question.Why did founders tie themselves in knots doing the wrong things
when the answer was right in front of them? Because that was what
they'd been trained to do. Their education had taught them that the
way to win was to hack the test. And without even telling them they
were being trained to do this. The younger ones, the recent graduates,
had never faced a non-artificial test. They thought this was just
how the world worked: that the first thing you did, when facing any
kind of challenge, was to figure out what the trick was for hacking
the test. That's why the conversation would always start with how
to raise money, because that read as the test. It came at the end
of YC. It had numbers attached to it, and higher numbers seemed to
be better. It must be the test.There are certainly big chunks of the world where the way to win
is to hack the test. This phenomenon isn't limited to schools. And
some people, either due to ideology or ignorance, claim that this
is true of startups too. But it isn't. In fact, one of the most
striking things about startups is the degree to which you win by
simply doing good work. There are edge cases, as there are in
anything, but in general you win by getting users, and what users
care about is whether the product does what they want.Why did it take me so long to understand why founders made startups
overcomplicated? Because I hadn't realized explicitly that schools
train us to win by hacking bad tests. And not just them, but me!
I'd been trained to hack bad tests too, and hadn't realized it till
decades later.I had lived as if I realized it, but without knowing why. For
example, I had avoided working for big companies. But if you'd asked
why, I'd have said it was because they were bogus, or bureaucratic.
Or just yuck. I never understood how much of my dislike of big
companies was due to the fact that you win by hacking bad tests.Similarly, the fact that the tests were unhackable was a lot of
what attracted me to startups. But again, I hadn't realized that
explicitly.I had in effect achieved by successive approximations something
that may have a closed-form solution. I had gradually undone my
training in hacking bad tests without knowing I was doing it. Could
someone coming out of school banish this demon just by knowing its
name, and saying begone? It seems worth trying.Merely talking explicitly about this phenomenon is likely to make
things better, because much of its power comes from the fact that
we take it for granted. After you've noticed it, it seems the
elephant in the room, but it's a pretty well camouflaged elephant.
The phenomenon is so old, and so pervasive. And it's simply the
result of neglect. No one meant things to be this way. This is just
what happens when you combine learning with grades, competition,
and the naive assumption of unhackability.It was mind-blowing to realize that two of the things I'd puzzled
about the most � the bogusness of high school, and the difficulty
of getting founders to see the obvious � both had the same cause.
It's rare for such a big block to slide into place so late.Usually when that happens it has implications in a lot of different
areas, and this case seems no exception. For example, it suggests
both that education could be done better, and how you might fix it.
But it also suggests a potential answer to the question all big
companies seem to have: how can we be more like a startup? I'm not
going to chase down all the implications now. What I want to focus
on here is what it means for individuals.To start with, it means that most ambitious kids graduating from
college have something they may want to unlearn. But it also changes
how you look at the world. Instead of looking at all the different
kinds of work people do and thinking of them vaguely as more or
less appealing, you can now ask a very specific question that will
sort them in an interesting way: to what extent do you win at this
kind of work by hacking bad tests?It would help if there was a way to recognize bad tests quickly.
Is there a pattern here? It turns out there is.Tests can be divided into two kinds: those that are imposed by
authorities, and those that aren't. Tests that aren't imposed by
authorities are inherently unhackable, in the sense that no one is
claiming they're tests of anything more than they actually test. A
football match, for example, is simply a test of who wins, not which
team is better. You can tell that from the fact that commentators
sometimes say afterward that the better team won. Whereas tests
imposed by authorities are usually proxies for something else. A
test in a class is supposed to measure not just how well you did
on that particular test, but how much you learned in the class.
While tests that aren't imposed by authorities are inherently
unhackable, those imposed by authorities have to be made unhackable.
Usually they aren't. So as a first approximation, bad tests are
roughly equivalent to tests imposed by authorities.You might actually like to win by hacking bad tests. Presumably
some people do. But I bet most people who find themselves doing
this kind of work don't like it. They just take it for granted that
this is how the world works, unless you want to drop out and be
some kind of hippie artisan.I suspect many people implicitly assume that working in a
field with bad tests is the price of making lots of money. But that,
I can tell you, is false. It used to be true. In the mid-twentieth
century, when the economy was
composed of oligopolies,
the only way
to the top was by playing their game. But it's not true now. There
are now ways to get rich by doing good work, and that's part of the
reason people are so much more excited about getting rich than they
used to be. When I was a kid, you could either become an engineer
and make cool things, or make lots of money by becoming an "executive."
Now you can make lots of money by making cool things.Hacking bad tests is becoming less important as the link between
work and authority erodes. The erosion of that link is one of the
most important trends happening now, and we see its effects in
almost every kind of work people do. Startups are one of the most
visible examples, but we see much the same thing in writing. Writers
no longer have to submit to publishers and editors to reach readers;
now they can go direct.The more I think about this question, the more optimistic I get.
This seems one of those situations where we don't realize how much
something was holding us back until it's eliminated. And I can
foresee the whole bogus edifice crumbling. Imagine what happens as
more and more people start to ask themselves if they want to win
by hacking bad tests, and decide that they don't. The kinds of
work where you win by hacking bad tests will be starved of talent,
and the kinds where you win by doing good work will see an influx
of the most ambitious people. And as hacking bad tests shrinks in
importance, education will evolve to stop training us to do it.
Imagine what the world could look like if that happened.This is not just a lesson for individuals to unlearn, but one for
society to unlearn, and we'll be amazed at the energy that's liberated
when we do.
Notes[1] If using tests only to measure learning sounds impossibly
utopian, that is already the way things work at Lambda School.
Lambda School doesn't have grades. You either graduate or you don't.
The only purpose of tests is to decide at each stage of the curriculum
whether you can continue to the next. So in effect the whole school
is pass/fail.[2] If the final exam consisted of a long conversation with the
professor, you could prepare for it by reading good books on medieval
history. A lot of the hackability of tests in schools is due to the
fact that the same test has to be given to large numbers of students.[3] Learning is the naive algorithm for getting good grades.[4] Hacking has
multiple senses. There's a narrow sense in which
it means to compromise something. That's the sense in which one
hacks a bad test. But there's another, more general sense, meaning
to find a surprising solution to a problem, often by thinking
differently about it. Hacking in this sense is a wonderful thing.
And indeed, some of the hacks people use on bad tests are impressively
ingenious; the problem is not so much the hacking as that, because
the tests are hackable, they don't test what they're meant to.[5] The people who pick startups at Y Combinator are similar to
admissions officers, except that instead of being arbitrary, their
acceptance criteria are trained by a very tight feedback loop. If
you accept a bad startup or reject a good one, you will usually know it
within a year or two at the latest, and often within a month.[6] I'm sure admissions officers are tired of reading applications
from kids who seem to have no personality beyond being willing to
seem however they're supposed to seem to get accepted. What they
don't realize is that they are, in a sense, looking in a mirror.
The lack of authenticity in the applicants is a reflection of the
arbitrariness of the application process. A dictator might just as
well complain about the lack of authenticity in the people around
him.[7] By good work, I don't mean morally good, but good in the sense
in which a good craftsman does good work.[8] There are borderline cases where it's hard to say which category
a test falls in. For example, is raising venture capital like college
admissions, or is it like selling to a customer?[9] Note that a good test is merely one that's unhackable. Good
here doesn't mean morally good, but good in the sense of working
well. The difference between fields with bad tests and good ones
is not that the former are bad and the latter are good, but that
the former are bogus and the latter aren't. But those two measures
are not unrelated. As Tara Ploughman said, the path from good to
evil goes through bogus.[10] People who think the recent increase in
economic inequality is
due to changes in tax policy seem very naive to anyone with experience
in startups. Different people are getting rich now than used to,
and they're getting much richer than mere tax savings could make
them.[11] Note to tiger parents: you may think you're training your kids
to win, but if you're training them to win by hacking bad tests,
you are, as parents so often do, training them to fight the last
war.Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME> for reading
drafts of this.Russian TranslationArabic TranslationSwedish Translation
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/attach-p3.typ | typst | Apache License 2.0 | // Test t and b attachments, part 3.
---
// Test limit.
$ lim_(n->oo \ n "grows") sum_(k=0 \ k in NN)^n k $
---
// Test forcing scripts and limits.
$ limits(A)_1^2 != A_1^2 $
$ scripts(sum)_1^2 != sum_1^2 $
$ limits(integral)_a^b != integral_a^b $
---
// Error: 30-34 unknown variable: oops
$ attach(A, t: #locate(it => oops)) $
---
// Show and let rules for limits and scripts
#let eq = $ ∫_a^b iota_a^b $
#eq
#show "∫": math.limits
#show math.iota: math.limits.with(inline: false)
#eq
$iota_a^b$
---
// Test default of limit attachments on relations at all sizes
#set page(width: auto)
$ a =^"def" b quad a lt.eq_"really" b quad a arrow.r.long.squiggly^"slowly" b $
$a =^"def" b quad a lt.eq_"really" b quad a arrow.r.long.squiggly^"slowly" b$
$a scripts(=)^"def" b quad a scripts(lt.eq)_"really" b quad a scripts(arrow.r.long.squiggly)^"slowly" b$
---
// Test default of scripts attachments on integrals at display size
$ integral.sect_a^b quad \u{2a1b}_a^b quad limits(\u{2a1b})_a^b $
$integral.sect_a^b quad \u{2a1b}_a^b quad limits(\u{2a1b})_a^b$
---
// Test default of limit attachments on large operators at display size only
$ tack.t.big_0^1 quad \u{02A0A}_0^1 quad join_0^1 $
$tack.t.big_0^1 quad \u{02A0A}_0^1 quad join_0^1$
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/enum-numbering.typ | typst | Apache License 2.0 | // Test enum numbering styles.
---
// Test numbering pattern.
#set enum(numbering: "(1.a.*)")
+ First
+ Second
2. Nested
+ Deep
+ Normal
---
// Test full numbering.
#set enum(numbering: "1.a.", full: true)
+ First
+ Nested
---
// Test numbering with closure.
#enum(
start: 3,
spacing: 0.65em - 3pt,
tight: false,
numbering: n => text(
fill: (red, green, blue).at(calc.rem(n, 3)),
numbering("A", n),
),
[Red], [Green], [Blue], [Red],
)
---
// Test numbering with closure and nested lists.
#set enum(numbering: n => super[#n])
+ A
+ B
+ C
---
// Test numbering with closure and nested lists.
#set text(font: "New Computer Modern")
#set enum(numbering: (..args) => math.mat(args.pos()), full: true)
+ A
+ B
+ C
+ D
+ E
+ F
---
// Error: 22-24 invalid numbering pattern
#set enum(numbering: "")
---
// Error: 22-28 invalid numbering pattern
#set enum(numbering: "(())")
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/056%20-%20Outlaws%20of%20Thunder%20Junction/010_Episode%206%3A%20The%20Ballad%20of%20Thieves%20and%20Thunderslingers.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 6: The Ballad of Thieves and Thunderslingers",
set_name: "Outlaws of Thunder Junction",
story_date: datetime(day: 25, month: 03, year: 2024),
author: "<NAME>",
doc
)
The hot wind carried a flurry of embers that swirled around Oko like fireflies. He swept a hand through his hair, staring up at the entrance to the vault. A round door stretched into the dark fog. Lava seeped through the cracks, flowing over the edge and down onto Tarnation's surface below.
Oko turned to face his crew, reunited at his signal. "Whoever built this vault wanted to keep its treasure hidden, and I doubt a simple lock and key is the only thing separating us from the innermost chamber. We'll need to stay alert."
"BOOBY TRAPS!" Breeches yelled. He raised two fur-covered fists in the air, and a row of explosive devices appeared along his belt.
"Precisely." Oko focused on Annie. "I need you to be our eyes."
Annie's mouth was fixed in a tight line. She hadn't said a word since the saloon. When they took the elevator up to the floating vault, she made it a point to stand as far away from Oko as she possibly could, gaze pinned to the thunder shoot-outs spreading around the city.
It hadn't been Oko's intention to leave Kellan behind. There was no benefit to having his son locked up. But he'd been hired to do a job, and rescuing Kellan would've cost them the mission. He had no choice but to leave him to the Sterling guards.
It didn't matter if Annie couldn't understand Oko's logic; all he needed her to do was get the team through the vault without falling prey to any illusions.
"Let's just get this over with," Annie said, voice gruff. "The sooner we empty the vault, the sooner we can go back for the kid."
Oko didn't know how to play the role of a doting father, but he was perfectly capable of feigning gratitude. He bowed his head slightly and held a hand toward the door. "If you'd be so kind …"
Annie's left iris glowed a vivid orange as she approached the outer entrance. The markings on the door began to shine, creating a display of elongated spirals that pulsed with life. The door parted down the middle, creating an opening in the rock.
Oko remained close to Annie as she led the crew down the dark corridor. Tinybones's nervous rattle echoed behind them, followed by the impatient thump of Rakdos's heavy steps. The demon's wings brushed against the walls, sending dust and debris tumbling to the ground.
When they reached a wide chamber, Oko stopped beside an enormous platform. Dozens of fiery lanterns lit up the curved ceiling, casting a distorted reflection on the uneven black floor. Two matching pedestals stood on opposite sides of the room, each with its own lever. At the far end of the chamber was a staircase leading to a shimmering door.
Annie threw up a hand, stopping Oko from walking any farther. She pointed from one end of the room to the other. "There's light stretched across here, like crisscrossed strings. I think it's some kind of trap."
"A security system," Umezawa agreed. His gaze followed the crevasse down the center of the ceiling. "The lights are most likely designed as a trigger."
Oko lifted a brow. "What kind of trigger?"
Breeches knelt at the edge of the platform and swept a blue finger along the partially reflective surface. "Volcanic rock and crystal," he said with a sharp hiss, quieter than he had perhaps ever been before.
Geralf stared at the ceiling with disdain. "Are you suggesting lava might come pouring out of the ceiling at any moment? Because in case it wasn't made clear, I can only stitch flesh back together if there's still flesh to work with."
Gisa giggled beside him, clapping her hands like she'd never been more excited. "Imagine the ghouls I could raise if you all burned to death!" She turned to the others. "Some of you would make such delightful and interesting corpses."
"Perhaps our focus should be on turning the security system off," Oko suggested.
Umezawa motioned to the pedestals. "I believe these levers are part of a dual-lock system. I've seen something similar on Kamigawa. In order to disarm the light grid, we'll need two people to pull these levers simultaneously."
"One of us needs to get across the platform without setting off the trap," Oko concluded.
"I could try, but …" Annie shook her head. "The gaps are small. I'm not sure it's even possible for a full-grown adult to squeeze through them safely."
Tinybones leapt up, chattering away in his language that sounded mostly like clicks and growls.
"THE BRAVE AND JOVIAL SKELETON VOLUNTEERS!" Rakdos translated.
"If I may," Umezawa interjected, removing a round, metal device from his pocket. He held it up in his palm, and the top unfolded itself from the screen before refolding into the shape of an origami dragonfly. It fluttered in the air, and Umezawa passed the screen to Annie, quickly explaining the controls. "You can lead Tinybones across the grid with this. Wherever the device goes, he can follow."
Annie did a few practice turns in the air before sending the dragonfly to the edge of the platform. The metal device dove up and then down, looping from side to side as if it were moving through a strange tunnel system. Tinybones followed close behind, mimicking every movement with ease. At the last turn, the dragonfly dipped low—then shot up in a high arc before resting at the foot of the stairs.
Tinybones's head rolled off his neck, plopping firmly into his waiting hands. He scurried along the low path before throwing his skull over the last hurdle. With an anxious rattle, he took a massive leap over the invisible light. The moment he landed, his headless body rolled into the stone steps with a hollow #emph[clunk] .
Tinybones picked up his skull, propped it on his shoulders, and spun his torso around so that he was facing the rest of the crew.
Umezawa took hold of the closest lever, waiting until Tinybones had reached the top of the opposite pedestal. "Ready?"
Tinybones chattered in acknowledgment.
Umezawa took a careful breath. "Three … two … one …"
They pulled the levers in unison. Metal shifted from deep inside the walls, creaking and turning like the gears of an ancient clock. The lanterns spun above them, rotating in place until they formed two straight lines, illuminating a path along the glassy floor.
"The grid has vanished," Annie said. "I think it's safe to cross."
No one moved—not until Tinybones removed his humerus from his shoulder socket and chucked it across the platform. It clattered to a stop.
Oko smirked. He picked up the detached arm and returned it to Tinybones. "I knew there was a reason I liked you."
The skeleton shoved his arm back into place.
When the rest of the team reached the bottom of the stairs, Annie looked up, studying the shimmering colors along the door's surface. "This isn't an illusion," she said.
"No." Kaervek's voice was breathy. "It's a ward." He brushed past Umezawa, making a point to stare him down. "Your reliance on overly elaborate contraptions shows weakness. Allow me to show you what #emph[true] magic can do."
Kaervek made his way up the stairs, palms spread in front of him. Orange flames wove around his fingers, prodding and testing the protection spell. The colors rippled, flinching at the intrusion of Kaervek's magic. A hissing sound erupted from the stone, an off-key whisper attempting to fight back, trying to protect whatever was hidden inside.
Oko took a step back to give him space, tilting his chin slightly so that his voice carried over his shoulder. "When we get through the door, I think some of you should stay behind with Rakdos. It's only a matter of time before someone realizes we took the key, and we need to make sure our exit isn't blocked."
"It's a little late for that," a voice drawled.
Oko spun, knees bent as he prepared to retaliate. Akul stood at the other side of the platform. A red gash stretched from the corner of his eye to the lowest part of his nose. The Sterling Company had slowed him down, but they hadn't managed to defeat him.
#emph[An unfortunate outcome] , Oko thought dryly.
Hellspurs poured in behind the dragon, weapons ignited to create a wall of flames and thunder.
"Draw their fire away from Kaervek," Oko said to his crew, voice low. "We need time to get the door open."
"You'd best hurry." Annie raised her thunder rifle. "I reckon the Sterling Company won't be far behind."
Akul stretched his jaws, building thunder in his core, but he didn't get a chance to attack before Rakdos smashed into his side and clobbered him to the ground.
Akul scrambled to regain his composure while Rakdos raised his arms and bellowed with laughter as if he had all the time in the world.
"FINALLY!" his voice boomed. "#emph[THIS ] IS THE FUN I WAS PROMISED!"
Thunder erupted from both sides of the chamber, and the dragon and demon barreled toward each other, snarling in the center of the room as everyone else tried to stay clear of their fight. Oko's team shot in various directions, pulling their enemy's focus away from Kaervek, while Vraska and Oko flanked him.
Malcolm flew toward the lanterns with Breeches latched to his shoulders. As they circled the room, Breeches tossed several small explosives into the crowd of Hellspurs.
"BULLSEYE!" he squawked.
Tinybones leapt to avoid the blast, bones detaching to allow the shrapnel to pass through him before his body put itself back together. He climbed up the back of one of the Hellspurs, fishing for the spare thunder pistol wedged in its holster. With a bony finger around the trigger, he shot a blast straight into the Hellspur's foot. The man howled, and Tinybones leapt to the ground with glee.
Gisa had managed to raise a single Hellspur ghoul, cackling in delight as her creation stumbled through the crowd in search of flesh. Geralf sliced at his opponents with a pair of razor-sharp knives. His cuts were surgical and strategic, maiming places on the body that weren't easy to recover from. Across the platform, Eriette charmed several Hellspurs into an unshakable stupor while Umezawa attacked from the shadows, picking off unsuspecting Hellspurs with a retractable dagger.
Annie shot another blast from her rifle before using the back of the gun to crack a Hellspur across the jaw. "How's that door looking?" she barked at Oko. "We could really use the cover!"
Kaervek's hands sparked with magic. "Patience is necessary. No good ever comes from forcing a ward to submit before it is ready."
Vraska drummed her long nails in the air, watching the battle unfold. "There are too many of them," she said, too quiet for anyone but Oko to hear. "Getting the door open won't matter if we lead their army inside."
"What are you suggesting?" Oko pressed.
Her yellow eyes flashed. "You and I need to reach the vault's treasure room. No matter the cost."
A loud click sounded from the hollow of the stone door, and the enchantment vanished. The stairs gave a shudder, and the door began to rise.
Kaervek took a step back, just as a snarling foe slammed into him from the side, knocking him prone.
Oko looked back at the team. They were struggling to stave off the Hellspurs, and without backup, or a place to hide …
They needed help—but Oko needed them to delay Akul for a little longer.
Annie caught his gaze, and her forehead wrinkled. When her attention snapped back to the surrounding Hellspurs, Oko didn't wait to explain himself. He turned for the door without remorse, disappearing down the stairs with Vraska close behind.
Darkness filled the damp corridor, and the cold air made Oko's skin prickle. At the lowest level of the room, a strange glow rippled from inside of a doorway. It reminded Oko of an Omenpath. Its light crackled with volatile magic, and an iron carving appeared to float in the center like it was caught in a web of energy. Golden beams trickled from its edges, forming rays of sunlight. It was shaped exactly like the medallion.
Oko removed the key, inches away from the ancient mechanism. The light shimmered in acknowledgment. "Time to find out what you're hiding."
A golden vine shot toward Oko's wrist, wrapping itself around his hand like a lasso. The force yanked him backward, sending the key skittering along the floor.
Kellan stood at the top of the stairs. A flicker of magic still thrummed at his fingertips.
Oko blinked, unable to hide his surprise, but Vraska was already moving in; the moment Kellan met her gaze, she'd turn him to stone.
"Wait—" Oko lifted a hand instinctively when lightning flashed through the room with a #emph[crack] , making him recoil. He shook his head, fighting the bright haze, and realized <NAME> had appeared at Kellan's side.
Vraska stiffened, no longer concerned by Kellan's presence. "You shouldn't have come here," she said to Ral, voice clipped.
"Why are you doing this?" Ral demanded. "We are #emph[friends] , Vraska."
"We were enemies once, too," she replied.
Electricity sparked in Ral's hands. "You can still return to Ravnica. I don't know what happened to you, or where you've been all this time—but it doesn't have to be like this."
Vraska snarled. "The only way to fix what I've done is by getting what's inside the vault."
Oko flinched at her words. #emph[To fix what I've done.] They ricocheted through his mind like puzzle pieces that didn't quite fit. He knew Vraska took this job for the reward. He knew she'd been hired by Ashiok, same as he had. But what he didn't understand was the hunger in her voice, like she didn't just #emph[want] the payday—she needed it.
Normally, desperation in others was something Oko reveled in. It made people easy to manipulate, and even easier to bargain with. But the people who kept their desperation a secret?
They weren't pliable. They were #emph[dangerous] .
"Do I really mean so little to you that you can't even look at me?" Kellan demanded, interrupting his thoughts.
Oko pulled his attention from Vraska, feeling the heat of Kellan's anger. "I was going to come back for you. You were still going to get your cut of the treasure when the job was finished."
"I didn't search for you across the Multiverse for #emph[treasure] ."
"Perhaps not. But you knew what #emph[I] was here for, and you were a willing participant up until the moment you got caught," Oko pointed out. "I treated you the same as any member of my crew."
"I'm not your crew; I'm your son. I wish you could've seen the difference."
Oko lowered his chin. Vraska and Ral were still arguing—soon their fight would move beyond words. He didn't have time to waste.
"You can either help me," Oko said coolly, "or you can get out of my way."
Kellan clamped his mouth shut, and the muscles in his jaw tightened.
Oko watched him for a moment, calculating the odds of Kellan truly making an enemy of his father, when he remembered the key had fallen from his hand. Oko's eyes shifted, searching the floor.
Kellan noticed.
They moved at the same time, racing for the medallion. Kellan burst ahead, body lifting in the air as gold dust trickled behind him. He flew too fast for Oko to catch, sliding under him and grabbing the key.
Oko skidded to a halt just as Kellan shot out of his reach. The boy stilled midair, fist wrapped around the medallion. Oko ran his tongue over his teeth, eyes darkening. Flexing his fingers, Oko summoned his magic and threw several brightly colored vines across the room. They lanced through the air, serrated with sharp thorns, and snapped around Kellan's torso. Oko barely flicked a finger, and the vines slammed Kellan against the ground with brute force. Kellan let out a sharp cry, and the key slipped from his hand.
Oko picked up the medallion. "There's so much you could have learned. So much I could have taught you," he said, voice becoming a lethal purr. "Our bloodline is more powerful than you know."
Kellan pushed himself to his feet and balled his fists. "The only thing you've taught me is to never trust you again." His shoulders shook with defiance. "I won't let you open that vault."
Sparks flew nearby. The conversation between Vraska and Ral had escalated.
Oko gripped the medallion tightly. "There's something you should know about me," he said carefully, facing his son. There was no illusion of kindness. No half-truths to disguise himself. He was showing Kellan a part of him that existed deep in his very core. "#emph[I don't like people telling me what to do.] "
#figure(image("010_Episode 6: The Ballad of Thieves and Thunderslingers/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Oko was pulling a hand back to throw another set of vines toward Kellan when thunder grazed his shoulder. He stumbled back, clutching his arm as he sucked air through his teeth.
Through the sights of her thunder rifle, Annie stared down at Oko from the top of the stairs. She was the best sharpshooter on Thunder Junction, and she missed on purpose. Oko didn't bother asking why.
"Are you really going to give up the biggest payday of your life for a kid you barely know?" Oko said, voice laced with irritation.
"The Multiverse is full of people who do bad things for selfish reasons," Annie replied easily. "But the people who do good and expect nothing in return? I reckon they're worth protecting."
Oko summoned his magic, letting power build through his arms as he prepared to lash out at Annie with his vines, when Kellan darted into his line of sight, eyes glowing a strange green. Oko felt it immediately—the relaxing calm that swept over him, curling around his mind like a blanket. He swayed in place; Kellan reached for the medallion.
The moment his fingers brushed against the key, Kellan recoiled in fear, clutching his temples as he released a blood-curdling scream. The sound was slurred in Oko's mind, as if he were watching everything in slow motion. Shadows moved across the floor, wrapping around not only Kellan but Annie and Ral, too. They cried out in agony, overwhelmed by the nightmares seeping into their heads.
Kellan's magic faltered, and Oko blinked hard, breaking free of the illusory calm. He followed the shadows that swept through the room, knowing who they belonged to.
Ashiok stood with Vraska beside the locked door, dark smoke billowing at their feet.
"Your timing is impeccable," Oko said.
Vraska tilted her head toward the door with an impatient huff. "Let's just get the door open before we have any more unexpected company."
Oko held the key to the center lock. The metal gave a shudder before snapping into place. The spikes stretched out into the glowing door, clicking and turning as the center spun in an erratic pattern.
#figure(image("010_Episode 6: The Ballad of Thieves and Thunderslingers/02.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Each piece of the key broke apart, moving in opposite directions. The light pulled back like a curtain; there was nothing left to block the way.
With the back of his hand, Oko wiped the blood from his chin, and stepped into the treasure vault.
A golden mist burst into view, stretching in every direction. There were no walls or ceiling to be seen—just a seemingly infinite expanse filled with curved metal pathways leading to the center of the room. Stairs hovered one on top of the other, overlapping in a way that made them appear as if they were constantly shifting in place. At the top of the innermost platform was a pod-like structure encased in glass. Metal stretched around the glowing sphere, marked with an ancient script and surrounded by threads of amber magic. Behind it was a mural of an enormous horned creature, towering over the platform like a guardian.
Oko made his way toward the treasure pod, eyes never leaving the shifting metal cage. He stopped several yards away and squinted through the pulsing light. A shape moved behind the glass, too obscured by a cloudy haze to make out properly.
Oko frowned. This was something #emph[alive] .
Ashiok floated past him, feet barely touching the ground. "At last," they mused, moving for the pod. They pressed their sharp nails to the glass, more tender than Oko had ever seen. "I have found you."
The creature brushed against the barrier as if it were reaching for Ashiok's outstretched fingers. In that moment, an illusion drifted away. One that Ashiok had been wearing for some time.
The darkness evaporated, and beneath Ashiok's hooded cloak was <NAME>.
Oko's nostrils flared. The trickster didn't appreciate being tricked in turn. "How long have you been hiding behind your magic?"
"He's #emph[still] hiding." Annie stumbled through the doorway, focused solely on Jace. Her eye glowed a vibrant orange as she saw past the illusion he was still tucked carefully beneath. "Your scars … Those #emph[plugs] … What happened to you?"
Jace's piercing blue eyes filled with resentment. "You are searching for secrets that are not yours to find." He lifted a hand and gestured at Annie. By the time she hit the floor, she was already asleep.
Jace turned back to the cloudy tank and pressed both hands to the glass. The pod shattered, and dust particles shimmered in place before fading away entirely. A small creature rested on what was left of the altar. Its body was covered in orange fur, and a single tuft of cream hair sat at the top of its head, wedged between two dark horns. A long tail curled around its legs, hollow at the tip. Inside, a blue orb flickered to life. Its nose twitched, sensing the open air, and a pair of large green eyes fluttered open as if the creature had been asleep for a very long time.
Jace scooped up the child in his arms, cradling it to his chest. The child barely had time to process what was happening when Jace pressed a finger against its forehead, sending it back into slumber.
"Rest now," Jace said. "There will be time for us to get acquainted."
"What's going on?" Oko demanded. "You said there was power in the vault. But this—this is a child. An #emph[infant] ."
"He is so much more than that," Jace replied, eyes flashing as he nodded to someone behind Oko.
Oko turned, but Vraska was already waiting.
"Your services are no longer required," she said. Her eyes flashed with golden magic, and Oko felt the stiffness spread through his feet immediately. When he glanced down, his legs had already turned to stone. Oko fought the sting of betrayal as the petrification spell rose through him. If he didn't act now, his will would be overcome by Vraska's magic, and it would be too late. For a moment, he wondered if Kellan would meet the same fate.
When the stone reached Oko's neck, he shoved the thought away, and planeswalked out of Thunder Junction.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kellan stirred, fingers scraping across the stone floor. Ral was asleep nearby, but Kellan couldn't see Annie anywhere.
#emph[She must've gone after Oko alone] , Kellan realized.
He pushed himself to his feet and stumbled into the final chamber. A faint glow radiated from a broken altar, and he found Vraska standing beside a man Kellan didn't recognize. In his arms was a sleeping child.
Annie was lying on the ground, unmoving.
Kellan shot toward her, shimmering faerie dust behind him. By the time he reached her side, Vraska, the man, and the child had vanished without a trace.
The ground shuddered, and cracks appeared across the vault door. Rock fragments fell from the archway, toppling to the floor like hailstones.
Kellan frantically checked Annie's breathing. She was alive, but there was a wound at her temple where she'd fallen and blood trickled down her cheek. He looped an arm around her and pulled her weight toward him. She rustled slightly, groaning as Kellan helped her upright.
"We have to go," he urged.
Annie strained against Kellan, reaching for her thunder rifle that was still lying on the floor. He scooped it up with his free hand, and they shuffled for the doorway, nearly colliding into Ral.
"The ceiling is caving in," Kellan said quickly.
Ral stared at the half-broken altar in confusion. "But—the treasure—"
"It doesn't matter anymore. Whatever was inside this vault is gone."
Ral clenched his jaw, solemn.
They hurried back through the vault, zigzagging around the mess of falling rocks. By the time they reached the first chamber, most of the Hellspurs had already fled. Akul was sprawled out on the floor, eyes shut in defeat. Pinning his limp body to the ground was a victorious Rakdos.
"Everyone needs to get off this rock!" Kellan shouted in warning. "Something in the vault was activated, and this place is falling apart!"
Rakdos looked up, blinking at the molten lava beginning to pour through the cracks in the ceiling. The rest of the team exchanged wary glances, unsure of whether Ral's presence was a concern.
Eriette emerged from the crowded battle site, wiping blood from her brow. "Where's Oko? And Vraska?"
"They already left," Kellan said quickly. "There's no time to explain—we need to #emph[move] ."
The team fled back through the corridor as the sound of the vault being ripped apart roared behind them. The moment they reached the open air, Malcolm and Breeches took off into the night, soaring toward the wide desert horizon. The rest of Oko's crew piled onto Rakdos's back, where Tinybones settled comfortably in the center of his horns.
Rakdos huffed. "I HAVE SWORN ONCE NEVER TO BE RIDDEN AGAIN. LET IT BE KNOWN THIS IS THE LAST AND FINAL TIME!" With one last snarl, he took off over the edge of the floating rock.
"You go ahead," Kellan said to Ral. "I can fly Annie down myself."
"Get as far away from Tarnation as you can. I'll come and find you when it's safe." A crack of lightning shot down, skittering into the canyon, and Ral was gone.
Annie made a face. "When it comes to traveling, I prefer four legs on the ground."
"You don't like flying?"
"I rode a bird once that nearly broke my neck. So, no."
Kellan flinched at the lava sputtering up from the ground. "Trust me—flying is a lot better than falling."
She gave a curt nod, but before she reached Kellan, Akul burst from the vault entrance, talons splayed wide. He snatched Annie's waist and yanked her toward him, thunder sparking across his scales. She cried out in alarm, kicking at Akul's claws, but it only made him grip tighter. Kellan heard a #emph[crack] and worried it was bone.
Panic set in, and Kellan struggled to focus. He raised his hands, ready to summon a pair of energy swords, when he remembered what his father had said—about their bloodline, and the power that flowed through them. Kellan knew he would never be his father. He didn't want to be#emph[. ] But the abilities that came from his fae side weren't something to fear—they were a part of him. Kellan had faltered the last time he fought Akul because he hadn't been ready to accept his magic, and his heritage. Not completely.
He wouldn't make that mistake again.
Kellan dropped his hands and took a breath, steadying his magic as it pulsed through him. #emph[You can do this.]
Kellan sent a wisp of golden energy toward Akul like a lure, slow and strategic. The moment their gazes locked, Kellan leapt into Akul's mind without warning. He burrowed deep into the dragon's core, past the anger and the bloodlust that rippled around him. When Kellan's magic latched onto Akul's soul, he held tight and dampened every ounce of fight until the dragon was nothing more than a puppet. It wasn't just hypnosis—it was #emph[control] .
"Release her," Kellan ordered.
Akul's claws relaxed, and Annie tumbled back to the ground. Behind the dragon, the rocky mountain broke apart, piece by piece. Jagged stones toppled to the ground, and lava erupted from every crevasse, pouring like an open wound into the city of Tarnation below.
Kellan's eyes didn't leave Akul. He couldn't let him go free; if he did, the Hellspurs would never stop coming for Kellan, and Annie, and the town she wanted so desperately to protect. It had to end now.
Kellan sent another surge of magic into Akul's mind. "Go back inside the vault—and don't come out."
Despite the subtle glint in his eyes that suggested some part of him understood what was happening, Akul obeyed. He marched back into the entrance of the collapsing vault, tail dragging slowly behind him. Kellan watched the dragon's silhouette vanish as the tumbling rocks sealed the opening shut.
When the ground split apart and the floating mountain began to shed the last of its rubble, Kellan grabbed hold of Annie and fled across the sky. The last he saw of the vault was a giant, golden orb all that rock had concealed.
One moment it was there—and then threads of magic wove around the sphere, pulsing at every seam, and the vault shot toward the clouds and vanished from sight.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Oko appeared out of the Blind Eternities and inside Wildcard Saloon. There was no sign of Vraska's magic; he'd rid himself of every last bit of stone thanks to his ability to shapeshift.
He'd been lucky—but he would've preferred being smart.
Vraska and Ashiok had tricked him. Or Vraska and #emph[Jace] , it seemed. They'd used him and his crew for their talents and fled without paying them their dues. And the child …
Oko pursed his lips and smoothed the wrinkles above his brow. There was no point in worrying about any of that now. He preferred to lick his wounds and search for better opportunities. Revenge could wait.
Running a hand through his dark hair, Oko admired his reflection in the mirror behind the bar before moving for the back room.
Rakdos paced outside the window. Tinybones was doing his best to lure Geralf and Gisa into a game of chase, but neither necromancer seemed interested in taking the bait, too busy drowning their disappointment with a half-emptied bottle. Eriette sat at the piano, thumping an occasional key out of boredom, while Umezawa and Kaervek were perched at opposite ends of the balcony, glaring at one another from the shadows.
Oko flashed a bright smile. "Worry not, my friends—I am alive and well!"
Eriette's voice was clipped with impatience. "I take it none of us are getting paid?"
Gisa sank her head into her hands. "The Hellspurs were no fun at all. Most of them ran away before I could finish any of my ghouls!"
"The entire mission was a disaster," put in Umezawa. "We were set up to fail from the very beginning."
"Do not include me in your collective humiliation," Kaervek spat. "I did my part and severed the magical wards. Our so-called leader's inability to manage this group of miscreants is the #emph[true] failure."
Oko flicked his nail dismissively. "Vraska and Ashiok were always planning to double-cross us. They betrayed me, just as they betrayed all of you." He looked around, counting the crew that was still left. "Where are Breeches and Malcolm?"
"Their loyalty was always to the gorgon," Eriette pointed out. "When she didn't come back, they left."
Oko tried not to show his disappointment. Breeches's shouting sometimes grated him, but Malcolm was an ideal scout. Oko thought he could be a useful addition to a more permanent team.
Geralf tapped a finger against his empty glass. "Umezawa's right—this was a disaster from start to finish."
"WHAT AN AMUSING TIME!" Rakdos bellowed through the open window nearby. "I HAVE NOT HAD THIS MUCH FUN IN DECADES!"
Tinybones raised his arms, bones rattling as he cheered.
Umezawa folded his arms across his chest. "There's nothing funny about being cheated out of a payday." He pinned his gaze to Oko. "I'd like to know what you're planning on doing about it."
Gisa raised her eyebrows, grinning with anticipation.
"Nothing," Oko admitted simply. He was immediately met with a collection of scowls. "At least not for the time being. We have no leads on where Ashiok and Vraska went—and I don't make it a habit of wasting time and resources when there are plenty of other treasures to be found in the Multiverse."
Kaervek scoffed. "You mean to let them go?"
"They'll show themselves eventually." Oko's eyes darkened. "When that day comes, they'll be sorry they ever crossed us. But until then …" He shrugged. "We can either take our frustrations out on each other, or we can agree to reunite when a better opportunity presents itself. For revenge #emph[or] a bigger score."
Rakdos roared with enthusiasm. The others exchanged glances.
Oko tucked his hands at his back. "Shall we agree to keep in touch?"
"You know where to find me," Umezawa noted. "But I'm tripling my fee next time." He bowed his head slightly before disappearing back into the shadows.
Kaervek waved a hand through the air and turned for the door. "You owe me for this miserable failure, Oko. I will give you time to search for the traitors. Just know that one day, I intend to collect what was promised to me."
Gisa sighed from across the table, twisting a strand of hair around her finger. "I guess you can count me and my brother in. Unless I've killed him before then, of course." Her smile stretched across her face. "But don't worry—I can always bring his corpse along to the team meetings!"
Geralf rolled his eyes. "If given the choice between a trained medic and a half-wit corpse wrangler, they will choose me every time."
Gisa stuck out her tongue. The two of them left the room, bickering under their breath.
Tinybones rattled and scurried up Rakdos's face.
"THE SKELETON WILL ALSO RETURN FOR FURTHER AMUSEMENT!" Rakdos roared through the window before turning for the desert. His wings spread wide, blocking the sunlight from the window, and he took off with Tinybones clutching gleefully to his horns. "ONE LAST TIME, SKELETON! ONE LAST AND FINAL TIME!" And he was gone.
Only Eriette remained, still tapping away at a lone key on the piano. The silence stretched between her and Oko until finally she asked, "Would you like to know what happened to your son after you disappeared?"
Oko leaned against the nearby pillar, hands stuffed in his pockets. "If he's anything like me, then I assume he got away."
Eriette nodded. "So did Annie." She tilted her head. "Do you mean to include them in this circus act a second time?"
"No. From now on, their business is their own," Oko said, and he meant it.
Meeting Kellan hadn't been part of the plan. Neither was betraying him. But both things happened, and Oko had no intention of feeling sorry about it. Kellan was safe—he'd get over what happened between them, eventually. Perhaps their paths might even cross again someday.
Oko had never had much of a father. He'd have liked to have been a better one to a child of his own. If the circumstances had been different …
He straightened his shoulders and blinked the thought away. Right now, there were bigger things in the Multiverse to focus on.
Oko reached for the half-filled bottle Geralf had left behind and poured two glasses nearly to the brim. He passed one to Eriette and held up his own.
"Until next time," he said.
Eriette raised her glass. "I look forward to the reunion."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It had been over two weeks since <NAME> had fallen from the sky, wreaking havoc on Tarnation's surface. A single bruise was the only visible wound Kellan had left from the failed heist, but the ache he carried in his heart was much harder to get rid of.
Kellan tried not to think of Oko, but he found himself searching for his father in every stranger's face. Maybe it was silly to think his father might be watching him from an illusion, but it was comforting, too. Kellan preferred the imagined version of his father, and he wasn't ready to let go of him quite yet.
There were plenty of chores on Annie's ranch to keep Kellan busy. It reminded him of his days in the sheep-filled town of Orrinshire, when time moved a little slower. He liked the work, and the routine, and the fact that he wasn't in a hurry to rush to another plane. He'd never really felt like he belonged anywhere; if he couldn't fix that by knowing his father, then maybe he could fix it by helping his friends.
Kellan heaved the last bale of hay onto the stack and pulled the barn doors shut, turning to watch the animals grazing in the nearby field. A crack of lightning sounded, making some of the horses rear back in alarm.
<NAME> appeared at the gate. When he spotted Kellan, he raised a hand in greeting.
Kellan slid his work gloves off and tucked them into his back pocket before making his way toward Ral. "Don't tell me you tracked down Vraska already?"
"No," Ral admitted, somber. "There's been no sign of her—or Jace—since they left." He sighed, expression softening. "But there's lots of work to be done on Ravnica. I could really use someone I trust."
"Are you offering me another job?"
Ral laughed. "What can I say? I'm a glutton for punishment."
Kellan looked back toward the ranch. The hole where Annie had dug up her thunder rifle was still visible. She wasn't ready to bury it again. Not until she knew for sure that the town was safe.
Kellan had stuck around for the same reason. He figured it was the least he could do to repay her. But with Akul gone and Tarnation in shambles, Kellan was starting to think they might actually be okay.
Still—he wasn't ready to leave Thunder Junction quite yet.
"I think I've done enough wandering for a while," Kellan admitted. "Besides, I'm expecting someone."
Ral smirked. "Sounds like there's a story in there. And the way you're blushing, I think it's a good one."
Kellan fought a nervous laugh. "I don't know what you're talking about."
Ral peered over Kellan's shoulder toward the house. "Is that sweet potato pie I smell?" He took a deep breath through his nose. "What are the odds Annie will offer me some if I go and say hello?"
"You can try," Kellan said. "But don't be surprised if she has you chopping fence posts in exchange."
Ral rolled up his sleeves. "For pie? I'd make her a fence-building machine."
Kellan watched him disappear into the house. He thought about joining them when he saw a lone rider on a horse coming down the path. He squinted in the sunlight, holding his hand over his eyes to get a better view.
It was a woman carrying a parasol. With pointed ears and long black hair that hung in a braid at her shoulder, she was dressed in thick layers despite the scorching afternoon sun. Hanging from her shoulder was a heavy satchel—several rolled pieces of parchment poked out the back, and inkwells swung from leather thongs along the sides.
Kellan met her halfway down the path, grinning. "Finally found your way out of that Gruul ruin, did you?"
"I got your invitation on the relay tower," Amalia said, holding out a hand so Kellan could help her to the ground. She flashed a smile, pale face tilted up toward him. "You know, it's #emph[very ] expensive to send messages like that. Did you miss me that much?"
Kellan's cheeks darkened, and he ran a hand over the back of his neck. "I—I'm glad you're here."
"I came all the way from Ravnica, and you aren't even planning to give me a hug?" she teased, twirling her parasol so that the shadows danced around her.
Kellan opened his mouth, sheepish, when Amalia threw an arm around his neck and squeezed.
"I missed you, Kellan," she said against his cheek. "And I can't #emph[wait] to start mapping this place together."
|
|
https://github.com/ntjess/typst-invoice-template | https://raw.githubusercontent.com/ntjess/typst-invoice-template/main/README.md | markdown | Apache License 2.0 | # Invoice Template for Typst

Generates a minimalist invoice from provided company, customer and charges data. One nice upside of this template vs manually configuring an invoice is that totals are automatically calculated, reducing the chance of human error.
All required information can be changed in the sample [metadata.yaml](metadata.yaml) file, and the MWE [main.typ](main.typ) file shows its usage. If you prefer toml or json, these are fine too -- just be sure to change the reader function in your main file.
## Features
### Locale:
Simply change the default `locale` options in your metadata, or update the respective template states before rendering.
### Billing options:
- Any metadata key ending in "charges" (case insensitive) will be rendered as shown in the example.
- If multiple "charges" are present, a heading is added to each table to distinguish them.
### Custom styling
Pass `use-default-style: false` to the invoice function to prevent the default font, paper size, and link styling.
Replace `logo.svg` with your own logo to change the default, or comment it out in `template.typ` to remove it entirely.
- When typst allows checking for file existence, the logo will be removed automatically if it is not present.
## Roadmap
Feedback from the community is welcome! No additional features are currently planned other than bugfixes. |
https://github.com/ludwig-austermann/typst-idwtet | https://raw.githubusercontent.com/ludwig-austermann/typst-idwtet/main/CHANGELOG.md | markdown | MIT License | # v0.3.0
- added `%ENDHIDDEN%`
- updated to typst 0.8
- expanded `typst.toml` file with compiler, exclude to publish everything to the package repo |
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ISI/docs/2-Intrusions/intrusion-logicielles.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Intrusions logicielles
],
lesson: "ISI",
chapter: "2 - Intrusions",
definition: "Ce document traite des principales attaques logicielles, dont Heartbleed et Log4Shell, ainsi que des vulnérabilités courantes comme les débordements de mémoire tampon. Il explore les méthodes d'exploitation, les conséquences possibles, et les stratégies de protection, telles que la randomisation des adresses mémoire et l'utilisation de bibliothèques sécurisées.",
col: 1,
doc,
)
= Attaques logicielles connues
== Heartbleed
- 66% des sites Web touchés !
- Apache (52% des sites Web actifs au 04.2014)
- nginx (14% des sites Web actifs au 04.2014)
Exploitation d'une vulnérabilité dans la librairie OpenSSL. Cette librairire était utilisée dans de nombreaux serveurs web.
- Sites Web sociaux
- Sites Web professionnel (commercial ou HEIG-VD)
- Sites Web commerciaux
- Sites Web de hobby, forums,
- Sites Web distribuant des logiciels,
- Sites Web du gouvernement
Ce n'est pas une vulnéralibité dans le protocole SSL/TLS, mais dans l'implémentation de la librairie OpenSSL (donc d'une erreur de programation).
- Sans utiliser d’information privilégiée ou d’accès, ils ont réussi à voler :
- des clés cryptographique,
- des clés privées liés aux certificats X.509,
- des noms d’utilisateurs,
- des mots de passe,
- des messages instantanés,
- des emails,
- des documents et des communications sensibles.
== Log4Shell / Log4j
- Bibliothèque de journalisation (logs) pour Java
- « La » principale librairie utilisée dans les applications en Java
- Utilisée dans des milliers de programmes courants
#image("/_src/img/docs/image copy 86.png")
- La charge utile peut être placée :
- Champs Web : en-tête, identifiant, mot de passe, etc.
- Fichiers robot.txt ou security.txt (serveur de l’attaquant)
- Enregistrement DNS "TXT" (de l’attaquant)
- Champs d’emails : en-têtes, adresse source, etc.
- Champs des certificats SSL/TLS
- Métadonnées de fichiers : images, PDF, Word, Excels
- Noms du réseau Wifi (iPhone, Instagram envoie le BSSID à l'éditeur) ou de son appareil Bluetooth
- Et d’autres
= Memory overflow
- Ecriture/lecture/exécution sans autorisation
- typiquement en exploitant un « buffer overflow »
- Interprétation des entiers
- typiquement un grand nombre devient négatif, ou vice versa
- Interprétation des chaînes de caractères
- typiquement en supprimant la fin d'une chaîne de caractères
== Buffer overflow
- Principe
- un espace est réservé pour stocker une entrée contrôlable par celui qui
- le pirate arrive à passer une donnée qui fait écrire le programme au-delà de l'espace réservé
- En français
- dépassement de tampon
- débordement de tampon
#image("/_src/img/docs/image copy 87.png")
=== Exemple de code vulnerable
```c
void myFunction(char *str) {
char BufferB[16];
strcpy(bufferB, str);
}
void main() {
char bufferA[256];
myFunction(bufferA);
}
```
- Pas de contrôle si bufferB est assez grand
- Taille `bufferA` : 256
- Taille `bufferB` : 16
- Copier de bufferA dans bufferB (256o dans 16o)
- Ecrasement de la mémoire
== Shellcode
- Un « shellcode » est une suite d’instructions destinées à être injectées, puis exécutées par un programme exploité.
- Un « shellcode » peut notamment être utilisé pour exploiter un « buffer overflow ».
- Le plus important lors de la création
- aussi petit que possible
- exécutable (dans le context d'exécution du processus injecté, en particulier peu importe la localization en mémoire)
- Peut permettre toutes sortes de choses :
- L’ouverture d’un accès au système cible
- Faire naître un /bin/sh ou cmd.exe
- Changer des droits de fichiers
- Ajouter un utilisateur
- Ouvrir un port
- et beaucoup d’autres...
= Manipulation de la mémoire
== Protection contre la manipulation
- Stack/heap non-exécutable
- Utilisation de canaris
- Randomisation des adresses mémoire (ASLR)
- Librairies sécurisées
- Libsafe
- utiliser strncpy au lieu de strcpy
- utiliser snprintf au lieu de sprintf
- utiliser fgets(stdin, str, 10) au lieu de gets(str)
- utiliser scanf("%10s", str) au lieu de scanf("%s",str)
- et bien d'autres...
- Autres contre-mesures possibles |
|
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap1/1_static_electricity.typ | typst | Other | #import "../../core/core.typ"
=== Static electricity
It was discovered centuries ago that certain types of materials would mysteriously attract one another after being rubbed together. For example: after rubbing a piece of silk against a piece of glass, the silk and glass would tend to stick together. Indeed, there was an attractive force that could be demonstrated even when the two materials were separated:
#image("static/glass-silk-attraction.png")
Glass and silk aren't the only materials known to behave like this. Anyone who has ever brushed up against a latex balloon only to find that it tries to stick to them has experienced this same phenomenon. Paraffin wax and wool cloth are another pair of materials early experimenters recognized as manifesting attractive forces after being rubbed together:
#image("static/wax-wool-attraction.png")
This phenomenon became even more interesting when it was discovered that identical materials, after having been rubbed with their respective cloths, always repelled each other:
#image("static/glass-rod-repulsion.png")
It was also noted that when a piece of glass rubbed with silk was exposed to a piece of wax rubbed with wool, the two materials would attract one another:
#image("static/wax-glass-attraction.png")
Furthermore, it was found that any material demonstrating properties of attraction or repulsion after being rubbed could be classed into one of two distinct categories: attracted to glass and repelled by wax, or repelled by glass and attracted to wax. It was either one or the other: there were no materials found that would be attracted to or repelled by both glass and wax, or that reacted to one without reacting to the other.
More attention was directed toward the pieces of cloth used to do the rubbing. It was discovered that after rubbing two pieces of glass with two pieces of silk cloth, not only did the glass pieces repel each other, but so did the cloths. The same phenomenon held for the pieces of wool used to rub the wax:
#image("static/silk-silk-repulsion.png")
Now, this was really strange to witness. After all, none of these objects were visibly altered by the rubbing, yet they definitely behaved differently than before they were rubbed. Whatever change took place to make these materials attract or repel one another was invisible.
Some experimenters speculated that invisible "fluids" were being transferred from one object to another during the process of rubbing, and that these "fluids" were able to effect a physical force over a distance. <NAME> was one the early experimenters who demonstrated that there were definitely two different types of changes wrought by rubbing certain pairs of objects together. The fact that there was more than one type of change manifested in these materials was evident by the fact that there were two types of forces produced: attraction and repulsion. The hypothetical fluid transfer became known as a charge.
One pioneering researcher, <NAME>, came to the conclusion that there was only one fluid exchanged between rubbed objects, and that the two different "charges" were nothing more than either an excess or a deficiency of that one fluid. After experimenting with wax and wool, Franklin suggested that the coarse wool removed some of this invisible fluid from the smooth wax, causing an excess of fluid on the wool and a deficiency of fluid on the wax. The resulting disparity in fluid content between the wool and wax would then cause an attractive force, as the fluid tried to regain its former balance between the two materials.
Postulating the existence of a single "fluid" that was either gained or lost through rubbing accounted best for the observed behavior: that all these materials fell neatly into one of two categories when rubbed, and most importantly, that the two active materials rubbed against each other always fell into opposing categories as evidenced by their invariable attraction to one another. In other words, there was never a time where two materials rubbed against each other both became either positive or negative.
Following Franklin's speculation of the wool rubbing something off of the wax, the type of charge that was associated with rubbed wax became known as "negative" (because it was supposed to have a deficiency of fluid) while the type of charge associated with the rubbing wool became known as "positive" (because it was supposed to have an excess of fluid). Little did he know that his innocent conjecture would cause much confusion for students of electricity in the future!
Precise measurements of electrical charge were carried out by the French physicist <NAME> in the 1780's using a device called a torsional balance measuring the force generated between two electrically charged objects. The results of Coulomb's work led to the development of a unit of electrical charge named in his honor, the coulomb. If two "point" objects (hypothetical objects having no appreciable surface area) were equally charged to a measure of 1 coulomb, and placed 1 meter (approximately 1 yard) apart, they would generate a force of about 9 billion newtons (approximately 2 billion pounds), either attracting or repelling depending on the types of charges involved.
It was discovered much later that this "fluid" was actually composed of extremely small bits of matter called electrons, so named in honor of the ancient Greek word for amber: another material exhibiting charged properties when rubbed with cloth. Experimentation has since revealed that all objects are composed of extremely small "building-blocks" known as atoms, and that these atoms are in turn composed of smaller components known as particles. The three fundamental particles comprising most atoms are called protons, neutrons and electrons. Whilst the majority of atoms have a combination of protons, neutrons, and electrons, not all atoms have neutrons; an example is the protium isotope $#sub[1]H^1$ of hydrogen (Hydrogen-1) which is the lightest and most common form of hydrogen which only has one proton and one electron. Atoms are far too small to be seen, but if we could look at one, it might appear something like this:
#image("static/atom-composition.png")
Even though each atom in a piece of material tends to hold together as a unit, there's actually a lot of empty space between the electrons and the cluster of protons and neutrons residing in the middle.
This crude model is that of the element carbon, with six protons, six neutrons, and six electrons. In any atom, the protons and neutrons are very tightly bound together, which is an important quality. The tightly-bound clump of protons and neutrons in the center of the atom is called the nucleus, and the number of protons in an atom's nucleus determines its elemental identity: change the number of protons in an atom's nucleus, and you change the type of atom that it is. In fact, if you could remove three protons from the nucleus of an atom of lead, you will have achieved the old alchemists' dream of producing an atom of gold! The tight binding of protons in the nucleus is responsible for the stable identity of chemical elements, and the failure of alchemists to achieve their dream.
Neutrons are much less influential on the chemical character and identity of an atom than protons, although they are just as hard to add to or remove from the nucleus, being so tightly bound. If neutrons are added or gained, the atom will still retain the same chemical identity, but its mass will change slightly and it may acquire strange nuclear properties such as radioactivity.
However, electrons have significantly more freedom to move around in an atom than either protons or neutrons. In fact, they can be knocked out of their respective positions (even leaving the atom entirely!) by far less energy than what it takes to dislodge particles in the nucleus. If this happens, the atom still retains its chemical identity, but an important imbalance occurs. Electrons and protons are unique in the fact that they are attracted to one another over a distance. It is this attraction over distance which causes the attraction between rubbed objects, where electrons are moved away from their original atoms to reside around atoms of another object.
Electrons tend to repel other electrons over a distance, as do protons with other protons. The only reason protons bind together in the nucleus of an atom is because of a much stronger force called the strong nuclear force which has effect only under very short distances. Because of this attraction/repulsion behavior between individual particles, electrons and protons are said to have opposite electric charges. That is, each electron has a negative charge, and each proton a positive charge. In equal numbers within an atom, they counteract each other's presence so that the net charge within the atom is zero. This is why the picture of a carbon atom had six electrons: to balance out the electric charge of the six protons in the nucleus. If electrons leave or extra electrons arrive, the atom's net electric charge will be imbalanced, leaving the atom "charged" as a whole, causing it to interact with charged particles and other charged atoms nearby. Neutrons are neither attracted to or repelled by electrons, protons, or even other neutrons, and are consequently categorized as having no charge at all.
The process of electrons arriving or leaving is exactly what happens when certain combinations of materials are rubbed together: electrons from the atoms of one material are forced by the rubbing to leave their respective atoms and transfer over to the atoms of the other material. In other words, electrons comprise the "fluid" hypothesized by <NAME>. The operational definition of a coulomb as the unit of electrical charge (in terms of force generated between point charges) was found to be equal to an excess or deficiency of about 6,250,000,000,000,000,000 electrons. Or, stated in reverse terms, one electron has a charge of about 0.00000000000000000016 coulombs. Being that one electron is the smallest known carrier of electric charge, this last figure of charge for the electron is defined as the elementary charge.
The result of an imbalance of this "fluid" (electrons) between objects is called static electricity. It is called "static" because the displaced electrons tend to remain stationary after being moved from one insulating material to another. In the case of wax and wool, it was determined through further experimentation that electrons in the wool actually transferred to the atoms in the wax, which is exactly opposite of Franklin's conjecture! In honor of Franklin's designation of the wax's charge being "negative" and the wool's charge being "positive," electrons are said to have a "negative" charging influence. Thus, an object whose atoms have received a surplus of electrons is said to be negatively charged, while an object whose atoms are lacking electrons is said to be positively charged, as confusing as these designations may seem. By the time the true nature of electric "fluid" was discovered, Franklin's nomenclature of electric charge was too well established to be easily changed, and so it remains to this day.
<NAME> proved (1832) that static electricity was the same as that produced by a battery or a generator. Static electricity is, for the most part, a nusiance. Black powder and smokeless powder have graphite added to prevent ignition due to static electricity. It causes damage to sensitive semiconductor circuitry. While is is possible to produce motors powered by high voltage and low current characteristic of static electricity, this is not economic. The few practical applications of static electricity include xerographic printing, the electrostatic air filter, and the high voltage Van de Graaff generator.
#core.review[
- All materials are made up of tiny "building blocks" known as atoms.
- All naturally occurring atoms contain particles called electrons, protons, and neutrons, with the exception of the protium isotope ($#sub[1]H^1$) of hydrogen.
- Electrons have a negative (-) electric charge.
- Protons have a positive (+) electric charge.
- Neutrons have no electric charge.
- Electrons can be dislodged from atoms much easier than protons or neutrons.
- The number of protons in an atom's nucleus determines its identity as a unique element.
]
|
https://github.com/EpicEricEE/typst-plugins | https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/united/README.md | markdown | # united
A package for easy typesetting of numbers with units.
This fork of the [unify](https://github.com/ChHecker/unify) package, which was inspired by the [siunitx](https://ctan.org/pkg/siunitx) package for LaTeX, aims to further enhance the functionality and usability of the original package.
## Usage
The package comes with five functions: `num`, `qty`, `unit`, `numrange`, and `qtyrange`, which resemble the equally called LaTeX commands:
| Function | Description | Basic Example |
|------------|------------------------------------------|--------------------------|
| `num` | Typesets an integer or decimal number. | `#num[3.14159]` |
| `qty` | Typesets a number with a unit. | `#qty[42][meter]` |
| `unit` | Typesets a unit. | `#unit[m/s^2]` |
| `numrange` | Typesets a range of numbers. | `#numrange[1][5]` |
| `qtyrange` | Typesets a range of numbers with a unit. | `#qtyrange[2][4][second]`|
The parameters can be passed either as strings or as content in markup or math mode. Basic numbers can also be passed as `float`s or `int`s.
### Numbers
A number consists of a main value, and can be accompanied by an uncertainty and an exponent. The uncertainty can be typed in different ways, which the following examples show:

### Units
Units can be passed either as words or as shorthand symbols. A single unit consists of an optional prefix, the base unit, and an optional postfix (exponent). Custom units can be typed by wrapping them in single quotes. The following examples show the different ways of typing units:

### Quantities
A quantity is a number accompanied by a unit. The same rules apply as for numbers and units separately. The following examples show how to pass quantities:

### Ranges
The `range` functions work similarly to the `num` and `qty` functions, but take an additional number as the second argument. The following examples show how to pass ranges:

### Styling
Every function has a multitude of optional parameters intended for customizing the style of the output. Functions that combine numbers and units (`qty`, `qtyrange`) have parameters for both numbers and units.
For ease of use, the package comes with a convenience function, that allows setting the same parameters for all functions at once. The following example shows how to set the decimal separator to a comma:
```typ
#import "@local/united:0.1.0"
#let (num, qty) = united.with(decimal-sep: ",")
$ pi approx num(3.14159) $
```
#### Numbers
| Parameter | Description | Default Value |
|---------------|--------------------------------------------|----------------|
| `decimal-sep` | The decimal separator. | `"."` |
| `group-sep` | The separator between digit groups. | `math.thin` |
| `product` | The symbol to use for the exponent product | `math.dot` |
| `uncertainty` | How to format the uncertainty. | `"plusminus"` |
When changing the group or decimal separator to `","`, the spacing is automatically trimmed. To disable digit grouping, set the `group-sep` parameter to `none`.
The `uncertainty` parameter can be one of the following values:
| Value | Description |
|-----------------|------------------------------------------|
| `"plusminus"` | Show uncertainty with a plus-minus sign. |
| `"parentheses"` | Show uncertainty in parentheses. |
When using the `parentheses` option, the main value and the uncertainty are automatically padded with zeros, so that the digits match without losing precision.
#### Units
| Parameter | Description | Default Value |
|---------------|--------------------------------------------|----------------|
| `unit-sep` | The separator between units. | `math.thin` |
| `per` | How to format inverted units. | `"reciprocal"` |
The `per` parameter allows the following values:
| Value | Description |
|----------------|-----------------------------------------|
| `"reciprocal"` | Show unit with negative exponent. |
| `"fraction"` | Show unit in denominator of a fraction. |
| `"{symbol}"` | Show unit after the given symbol. |
The symbol can be any content, for example a `math.slash` or `"/"` symbol. When using single letters, they are italicized by default, so it may be necessary to wrap them in `math.upright` to prevent this.
#### Ranges
| Parameter | Description | Default Value |
|---------------|--------------------------------------------|----------------|
| `delim` | The delimiter between the numbers. | `"to"` |
| `delim-space` | The space between number and delimiter. | `math.space` |
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p3_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test default of scripts attachments on integrals at display size
$ integral.sect_a^b quad \u{2a1b}_a^b quad limits(\u{2a1b})_a^b $
$integral.sect_a^b quad \u{2a1b}_a^b quad limits(\u{2a1b})_a^b$
|
https://github.com/faber222/RAW-CODE-TYPST | https://raw.githubusercontent.com/faber222/RAW-CODE-TYPST/main/main.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#show: doc => report(
title: "Enumarated Raw Code",
subtitle: "Um template para o Typst voltado para criar um Enumarated raw code",
authors: ("Faber222",),
date: "16 de Julho de 2024",
doc,
)
// A partir dessa parte
#let style-number(number) = text(gray)[#number] // Seleciona a cor do numero contador
#show raw.where(block: true): it => grid( // Aqui configuramos os parametros da grid do raw code
columns: 2,
align: (right, left),
gutter: 0.5em,
column-gutter: -0.2em,
..it.lines
.enumerate()
.map(((i, line)) => (style-number(i + 1), line)) // Aqui fazemos a iteração das linhas
.flatten()
)
#show raw: it => block( // Define os parametros do design do raw code
fill: rgb("#FFFFE6"),
width: 100%,
inset: 8pt,
radius: 0pt,
text(fill: rgb("#000000"), it),
)
#set rect(inset: 0pt, stroke: 2pt) // Define a expessura do retângulo
= Exemplo
// Para criar da forma, deve se iniciar o raw code com o #rect[] e dentro dele fazer seu raw code
// Este método não é o mais otimizado, pois pode ser implementado direto no edit do raw code block e add o rect dentro dele
\
Exemplo de código em C.
#rect[
```c
#include <stdio.h>
int main(){
printf("hello world");
return 0;
}
```
]
Exemplo de código em Java.
#rect[
```Java
package typst;
public class App{
public static void Main(String[] args){
System.out.println("hello world");
}
}
```
]
Exemplo de código VHDL.
#rect[
```Sh
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity unsigned_adder is
generic
(
DATA_WIDTH : natural := 8
);
port
(
a : in unsigned ((DATA_WIDTH-1) downto 0);
b : in unsigned ((DATA_WIDTH-1) downto 0);
result : out unsigned ((DATA_WIDTH-1) downto 0)
);
end entity;
architecture rtl of unsigned_adder is
begin
result <= a + b;
end rtl;
```
]
|
https://github.com/hakureiR-eimu/my-typst-documents | https://raw.githubusercontent.com/hakureiR-eimu/my-typst-documents/template/mySample.typ | typst | MIT License | #import "myTemplate.typ": *
#import "@preview/codelst:2.0.0": sourcecode
#show: project.with(
anonymous: false,
title: "114514基于 ChatGPT 的狗屁通文章生成器但是把标题加长到两行",
author: "张钧玮",
school: "计算机学院",
id: "U202115520",
mentor: "114514你的老板",
class: "大数据 专业 2102 班",
date: (114514, 8, 17)
)
= 绪论
// == typst 介绍
// #img(
// image("assets/avatar.jpeg", height: 20%),
// caption: "我的 image 实例 0",
// )
// == 基本语法
// === 代码执行
// 正文可以像前面那样直接写出来,隔行相当于分段。
// 个人理解:typst 有两种环境,代码和内容,在代码的环境中会按代码去执行,在内容环境中会解析成普通的文本,代码环境用{}表示,内容环境用[]表示,在 content 中以 \# 开头来接上一段代码,比如\#set rule,而在花括号包裹的块中调用代码就不需要 \#。
// === 标题
// 类似 Markdown 里用 \# 表示标题,typst 里用 = 表示标题,一级标题用一个 =,二级标题用两个 =,以此类推。
// 间距、字体等会自动排版。
// \#pagebreak() 函数相当于分页符,在华科的要求里,第一级标题应当分页,请手动分页。
// = 本模板相关封装
// 图用下面的方式来引用,img 是对 image 的包装,caption 是图片的标题。
// #img(
// image("assets/avatar.jpeg", height: 20%),
// caption: "我的 image 实例 1",
// ) <img1>
// 引用 2-1: @img1
// == 表格
// 表格跟图片差不多,但是表格的输入要复杂一点,建议在 typst 官网学习,自由度特别高,定制化很强。
// 看看@tbl1,tbl 也是接收两个参数,一个是 table 本身,一个是标题,table 里的参数,没有字段的一律是单元格里的内容(每一个被[])包起来的内容,在 align 为水平时横向排列,排完换行。
// #tbl(
// table(
// columns: (100pt, 100pt, 100pt),
// inset: 10pt,
// stroke: 0.7pt,
// align: horizon,
// [], [*Area*], [*Parameters*],
// image("assets/avatar.jpeg", height: 10%),
// $ pi h (D^2 - d^2) / 4 $,
// [
// $h$: height \
// $D$: outer radius \
// $d$: inner radius
// ],
// image("assets/avatar.jpeg", height: 10%),
// $ sqrt(2) / 12 a^3 $,
// [$a$: 边长]
// ),
// caption: "芝士样表"
// ) <tbl1>
// #tbl(
// three_line_table(
// (
// ("Country List", "Country List", "Country List"),
// ("Country Name or Area Name", "ISO ALPHA Code", "ISO ALPHA"),
// ("Afghanistan", "AF", "AFT"),
// ("Aland Islands", "AX", "ALA"),
// ("Albania", "AL", "ALB"),
// ("Algeria", "DZ", "DZA"),
// ("American Samoa", "AS", "ASM"),
// ("Andorra", "AD", "AND"),
// ("Angola", "AP", "AGO"),
// )),
// caption: "三线表示例"
// )
// #tbl(
// three_line_table(
// (
// ("Country List", "Country List", "Country List", "Country List"),
// ("Country Name or Area Name", "ISO ALPHA 2 Code", "ISO ALPHA 3", "8"),
// ("Afghanistan", "AF", "AFT", "7"),
// ("Aland Islands", "AX", "ALA", "6"),
// ("Albania", "AL", "ALB", "5"),
// ("Algeria", "DZ", "DZA", "4"),
// ("American Samoa", "AS", "ASM", "3"),
// ("Andorra", "AD", "AND", "2"),
// ("Angola", "AP", "AGO", "1"),
// )),
// caption: "三线表示例2"
// )
// == 公式
// 公式用两个\$包裹,但是语法跟 LaTeX 并不一样,如果有大量公式需求建议看官网教程 https://typst.app/docs/reference/math/equation/。
// 为了给公式编号,也依然需要封装,使用 equation 里包公式的方式实现,比如:
// #equation(
// $ A = pi r^2 $,
// ) <eq1>
// 根据@eq1 ,推断出@eq2
// #equation(
// $ x < y => x gt.eq.not y $,
// ) <eq2>
// 然后也有多行的如@eq3,标签名字可以自定义
// #equation(
// $ sum_(k=0)^n k
// &< 1 + ... + n \
// &= (n(n+1)) / 2 $,
// ) <eq3>
// 如果不想编号就直接用\$即可
// $ x < y => x gt.eq.not y $
// == 列表
// - 无序列表1: 1
// - 无序列表2: 2
// #indent()列表后的正文,应当有缩进。这里加入一个 \#indent() 函数来手动生成段落缩进,是因为在目前的 typst 设计里,按英文排版的习惯,连续段落里的第一段不会缩进,也包括各种列表。
// 1. 有序列表1
// 2. 有序列表2
// 列表后的正文,应当有缩进,但是这里没有,请自己在段首加上\#indent()
// 想自己定义可以自己set numbering,建议用 \#[] 包起来保证只在该作用域内生效:
// #[
// #set enum(numbering: "1.a)")
// + 自定义列表1
// + 自定义列表1.1
// + 自定义列表2
// + 自定义列表2.1
// ]
// == 代码块
// //代码块使用的是库codelst,语法和markdown类似
// #sourcecode[```typ
// #show "ArtosFlow": name => box[
// #box(image(
// "logo.svg",
// height: 0.7em,
// ))
// #name
// ]
// This report is embedded in the
// ArtosFlow project. ArtosFlow is a
// project of the Artos Institute.
// ```]
// #pagebreak()
// = 其他说明
// == 文献引用
// 引用支持 LaTeX Bib 的格式,也支持更简单好看的 yml 来配置(尚未流行,推荐优先使用`.bib`)在引用时使用`#bib_cite(<tag>)`,像这样#bib_cite(<impagliazzo2001problems>,<Burckhardt:2013>)以获得右上的引用标注#bib_cite(<刘星2014恶意代码的函数调用图相似性分析>)#bib_cite(<papadimitriou1998combinatorial>)。
// 记得在最后加入\#references("path/to/ref.bib")函数的调用来生成参考文献。
// 由于华科使用自创引用格式,基本上为 GB/T 7714 去掉[J]、[C]、[M] 刊物类型。Typst 已支持 `csl` 自定义参考文献列表,基于#link("https://github.com/redleafnew/Chinese-STD-GB-T-7714-related-csl/blob/main/462huazhong-university-of-science-and-technology-school-of-cyber-science-and-engineering.csl")[#underline()[这个]]修改,如果想再自定义新的格式,请修改 `template.typ` 中 `bibliography` 函数中 style 参数。
// == 致谢部分
// 致谢部分在最后加入\#acknowledgement()函数的调用来生成。
// == 模板相关
// 这个模板应该还不是完全版,可能不能覆盖到华科论文的所有case要求,如果遇到特殊 case 请提交 issue 说明,或者也可以直接提 pull request
// 同时,由于 typst 太新了,2023年4月初刚发布0.1.0版本,可能会有大的break change发生,模板会做相应修改。
// 主要排版数据参考来自 https://github.com/zfengg/HUSTtex 同时有一定肉眼排版成分,所以有可能不完全符合华科排版要求,如果遇到不对的间距、字体等请提交 issue 说明。
// === 数据相关
// 所有拉丁字母均为 Times New Roman,大小与汉字相同
// 正文为宋体12pt,即小四
// 图表标题为黑体12pt
// 表格单元格内容宋体10.5pt,即五号
// 一级标题黑体18pt加粗,即小二
// 二级标题14pt加粗,即四号
// 正文行间距1.24em(肉眼测量,1.5em与与word的1.5倍行距并不一样)
// a4纸,上下空2.5cm,左右空3cm
// #pagebreak()
// #acknowledgement()[
// 完成本篇论文之际,我要向许多人表达我的感激之情。
// 首先,我要感谢我的指导教师,他/她对本文提供的宝贵建议和指导。所有这些支持和指导都是无私的,而且让我受益匪浅。
// 其次,我还要感谢我的家人和朋友们,他们一直以来都是我的支持和鼓励者。他们从未停止鼓舞我,勉励我继续前行,感谢你们一直在我身边,给我幸福和力量。
// 此外,我还要感谢我的同学们,大家一起度过了很长时间的学习时光,互相支持和鼓励,共同进步。因为有你们的支持,我才能不断地成长、进步。
// 最后,我想感谢笔者各位,你们的阅读和评价对我非常重要,这也让我意识到了自己写作方面的不足,同时更加明白了自己的研究方向。谢谢大家!
// 再次向所有支持和鼓励我的人表达我的谢意和感激之情。
// 本致谢生成自 ChatGPT。
// ]
// #pagebreak()
// #references("./ref.bib")
|
https://github.com/HKFoggyU/hkust-thesis-typst | https://raw.githubusercontent.com/HKFoggyU/hkust-thesis-typst/main/hkust-thesis/template.typ | typst | LaTeX Project Public License v1.3c | // Repo: https://github.com/HKFoggyU/hkust-thesis-typst
// Author: HKFoggyU
// License: LPPL-1.3c
// Import
#import "layouts/doc.typ": doc
#import "layouts/mainmatter.typ": mainmatter
#import "layouts/refmatter.typ": refmatter
#import "layouts/postmatter.typ": postmatter
#import "layouts/appendix.typ": appendix
#import "templates/cover-page.typ": cover-page
#import "templates/authorization.typ": authorization
#import "templates/signature-page.typ": signature-page
#import "templates/abstract-page.typ": abstract-page
#import "templates/toc-page.typ": toc-page
#import "templates/lof-page.typ": lof-page
#import "templates/lot-page.typ": lot-page
#import "templates/reference-body.typ": reference-body
// Implement
#let documentclass(
config: (:),
info: (:),
) = {
config = (
twoside: true,
) + config
info = ( // Default information
degree: "PhD",
title: ("Triggering", "the Forth Impact"),
keywords: ("Neon", "Genesis", "Evangelion"),
author: "<NAME>",
program: "Human Instrumentality Project",
department: "Department of NERV",
school: "School of SEELE",
supervisors: (
main: "Prof. Adams",
co: "Prof. Lilith",
),
department-head: (
name: "Prof. <NAME>",
position: "Head of Department",
),
committee: (
(
name: "Prof. AAA (Chairperson)",
department: "Department of Electronic and Computer Engineering"
),
(
name: "Prof. BBB (Supervisor)",
department: "Department of ECE"
),
(
name: "Prof. CCC (Co-supervisor)",
department: "Department of ISD"
),
(
name: "Prof. DDD",
department: "Division of LIFS"
),
(
name: "Prof. EEE",
department: "Department of Physics"
),
(
name: "Prof. FFF (External Examiner)",
department: "Department of EE, University of UU"
),
),
submit-date: (
date: "13",
month: "August",
year: "2021",
),
defend-date: (
date: "8",
month: "March",
year: "2021",
),
city: "Geo Front",
) + info
(
doc: (..args) => {
doc(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
cover-page: (..args) => {
cover-page(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
authorization: (..args) => {
authorization(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
signature-page: (..args) => {
signature-page(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
abstract-page: (..args) => {
abstract-page(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
toc-page: (..args) => {
toc-page(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
lof-page: (..args) => {
lof-page(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
lot-page: (..args) => {
lot-page(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
reference-body: (..args) => {
reference-body(
..args,
config: config + args.named().at("config", default: (:)),
info: info + args.named().at("info", default: (:)),
)
},
mainmatter: (..args) => {
mainmatter(
..args,
config: config + args.named().at("config", default: (:)),
)
},
refmatter: (..args) => {
refmatter(
..args,
config: config + args.named().at("config", default: (:)),
)
},
postmatter: (..args) => {
postmatter(
..args,
config: config + args.named().at("config", default: (:)),
)
},
appendix: (..args) => {
appendix(
..args,
config: config + args.named().at("config", default: (:)),
)
},
)
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/weave/0.1.0/README.md | markdown | Apache License 2.0 | # weave
A helper library for chaining lambda abstractions, imitating the `|>` or `.` operator in some
functional languages.
## Import
You can import the latest version of this package with:
```typ
#import "@preview/weave:0.1.0": pipe, pipe_
```
Functions suffixed with underscore are flipped and curried version.
## Basic usage
To chain functions into one single function, you can write:
```typ
#let add8 = pipe_((
x => x + 5, // first add 5
x => x + 3, // then add 3
))
```
And then apply this to a value, for example.
```typ
#let result = add8(10)
```
This can be particularly useful when you need to destructure lists, as it avoids the need to create
binds that'll pollute the namespace globally.
```typ
#let two_and_one = pipe(
(1, 2),
(
((a, b)) => (a, b, -1), // becomes a list of length three
((a, b, _)) => (b, a), // discard the third element and swap
),
)
// `a` and `b` are out of scope here
```
You can also use it for show rules.
```typ
#show link: pipe_((
emph,
text.with(fill: blue),
underline,
))
// Is equivalent to (note the order)
#show link: underline
#show link: text.with(fill: blue)
#show link: emph
```
The function `compose` is the `chain` function in the mathematical order.
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/spacing.typ | typst | // Test the `h` and `v` functions.
--- spacing-h-and-v ---
// Linebreak and leading-sized weak spacing are equivalent.
#box[A \ B] #box[A #v(0.65em, weak: true) B]
// Eating up soft spacing.
Inv#h(0pt)isible
// Multiple spacings in a row.
Add #h(10pt) #h(10pt) up
// Relative to area.
#let x = 25% - 4pt
|#h(x)|#h(x)|#h(x)|#h(x)|
// Fractional.
| #h(1fr) | #h(2fr) | #h(1fr) |
--- spacing-rtl ---
// Test RTL spacing.
#set text(dir: rtl)
A #h(10pt) B \
A #h(1fr) B
--- spacing-missing-amount ---
// Missing spacing.
// Error: 10-13 missing argument: amount
Totally #h() ignored
--- issue-3624-spacing-behaviour ---
// Test that metadata after spacing does not force a new paragraph.
#{
h(1em)
counter(heading).update(4)
[Hello ]
context counter(heading).display()
}
--- trim-weak-space-line-beginning ---
// Weak space at the beginning should be removed.
#h(2cm, weak: true) Hello
--- trim-weak-space-line-end ---
// Weak space at the end of the line should be removed.
#set align(right)
Hello #h(2cm, weak: true)
--- issue-4087 ---
// Weak space at the end of the line is removed.
This is the first line #h(2cm, weak: true) A new line
// Non-weak space consumes a specified width and pushes to next line.
This is the first line #h(2cm, weak: false) A new line
// Similarly, weak space at the beginning of the line is removed.
This is the first line \ #h(2cm, weak: true) A new line
// Non-weak-spacing, on the other hand, is not removed.
This is the first line \ #h(2cm, weak: false) A new line
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/regression/issue2.typ | typst | Other | $lr(#sym.alpha#sym.beta)$
|
https://github.com/EpicEricEE/typst-plugins | https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/hash/assets/example.typ | typst | #import "../src/lib.typ": hash, hex, md5, sha256, sha3
#set text(size: 14pt)
#set page(
width: auto,
height: auto,
margin: 1em,
background: pad(0.5pt, box(
width: 100%,
height: 100%,
radius: 4pt,
fill: white,
stroke: white.darken(10%),
)),
)
#table(
columns: 2,
inset: 0.5em,
table.header[*Digest*][*Hash*],
[BLAKE2], hex(hash("blake2", "Hello world!")),
[BLAKE2s], hex(hash("blake2s", "Hello world!")),
[MD5], hex(md5("Hello world!")),
[SHA-1], hex(hash("sha1", "Hello world!")),
[SHA-224], hex(hash("sha224", "Hello world!")),
[SHA-256], hex(sha256("Hello world!")),
[SHA-384], hex(hash("sha384", "Hello world!")),
[SHA-512], hex(hash("sha512", "Hello world!")),
[SHA-3], hex(sha3("Hello world!")),
)
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/par-justify.typ | typst | Apache License 2.0 |
---
#set page(width: 180pt)
#set block(spacing: 5pt)
#set par(justify: true, first-line-indent: 14pt, leading: 5pt)
This text is justified, meaning that spaces are stretched so that the text
forms a "block" with flush edges at both sides.
First line indents and hyphenation play nicely with justified text.
---
// Test that lines with hard breaks aren't justified.
#set par(justify: true)
A B C \
D
---
// Test forced justification with justified break.
A B C #linebreak(justify: true)
D E F #linebreak(justify: true)
---
// Test that there are no hick-ups with justification enabled and
// basically empty paragraph.
#set par(justify: true)
#""
---
// Test that the last line can be shrunk
#set page(width: 155pt)
#set par(justify: true)
This text can be fitted in one line.
---
// Test that runts are avoided when it's not too costly to do so.
#set page(width: 124pt)
#set par(justify: true)
#for i in range(0, 20) {
"a b c "
}
#"d"
---
// Test that justification cannot lead to a leading space
#set par(justify: true)
#set text(size: 12pt)
#set page(width: 45mm, height: auto)
lorem ipsum 1234, lorem ipsum dolor sit amet
#" leading whitespace should still be displayed"
---
// Test that justification doesn't break code blocks
#set par(justify: true)
```cpp
int main() {
printf("Hello world\n");
return 0;
}
```
|
https://github.com/howardlau1999/sysu-thesis-typst | https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/functions/allinone.typ | typst | MIT License | #import "booktab.typ": *
#import "codeblock.typ": *
#import "figurelist.typ": *
#import "helpers.typ": *
#import "numbering.typ": *
#import "style.typ": *
#import "underline.typ": *
#import "@preview/tablex:0.0.6": tablex |
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2019/MS-10.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [<NAME>], [CHN], [3546],
[2], [XU Xin], [CHN], [3436],
[3], [FAN Zhendong], [CHN], [3399],
[4], [<NAME>], [CHN], [3341],
[5], [<NAME>-Ju], [TPE], [3293],
[6], [<NAME>], [GER], [3241],
[7], [<NAME>], [CHN], [3235],
[8], [<NAME>], [CHN], [3194],
[9], [OVTCHAROV Dimitrij], [GER], [3148],
[10], [<NAME>], [BRA], [3128],
[11], [ZHOU Yu], [CHN], [3120],
[12], [<NAME>], [JPN], [3098],
[13], [JANG Woojin], [KOR], [3066],
[14], [YU Ziyang], [CHN], [3052],
[15], [<NAME>], [GER], [3033],
[16], [FANG Bo], [CHN], [3027],
[17], [YAN An], [CHN], [3025],
[18], [JEOUNG Youngsik], [KOR], [3009],
[19], [KANAMITSU Koyo], [JPN], [2988],
[20], [FREITAS Marcos], [POR], [2983],
[21], [<NAME>], [SWE], [2979],
[22], [<NAME>], [CHN], [2975],
[23], [MIZUTANI Jun], [JPN], [2971],
[24], [<NAME>], [KOR], [2956],
[25], [<NAME>], [SWE], [2956],
[26], [<NAME>], [KOR], [2956],
[27], [<NAME>ihao], [CHN], [2955],
[28], [<NAME>], [CHN], [2952],
[29], [<NAME>], [CHN], [2946],
[30], [<NAME>], [DEN], [2931],
[31], [<NAME>], [BLR], [2928],
[32], [#text(gray, "<NAME>un")], [KOR], [2927],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [XU Chenhao], [CHN], [2925],
[34], [ARUNA Quadri], [NGR], [2924],
[35], [YOSHIMURA Maharu], [JPN], [2917],
[36], [<NAME>], [IND], [2912],
[37], [<NAME>], [SLO], [2907],
[38], [#text(gray, "<NAME>")], [CHN], [2901],
[39], [CHEN Chien-An], [TPE], [2895],
[40], [JIN Takuya], [JPN], [2892],
[41], [<NAME>], [GER], [2889],
[42], [<NAME>], [JPN], [2885],
[43], [<NAME>], [AUT], [2877],
[44], [<NAME>], [FRA], [2874],
[45], [#text(gray, "MA Te")], [CHN], [2868],
[46], [<NAME>], [FRA], [2868],
[47], [#text(gray, "OSHIMA Yuya")], [JPN], [2865],
[48], [<NAME>], [JPN], [2865],
[49], [#text(gray, "ZHU Linfeng")], [CHN], [2863],
[50], [<NAME>], [SWE], [2860],
[51], [SHIBAEV Alexander], [RUS], [2857],
[52], [<NAME>], [JPN], [2852],
[53], [<NAME>i], [CHN], [2851],
[54], [<NAME>], [POR], [2850],
[55], [<NAME>onghoon], [KOR], [2849],
[56], [HIRANO Yuki], [JPN], [2847],
[57], [OIKAWA Mizuki], [JPN], [2842],
[58], [<NAME>], [GER], [2841],
[59], [CHUANG Chih-Yuan], [TPE], [2831],
[60], [TANAKA Yuta], [JPN], [2827],
[61], [<NAME> Ting], [HKG], [2823],
[62], [<NAME>], [JPN], [2820],
[63], [<NAME>], [KOR], [2820],
[64], [<NAME>], [SWE], [2815],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [JHA Kanak], [USA], [2813],
[66], [<NAME>uls], [SWE], [2811],
[67], [<NAME>], [GER], [2810],
[68], [<NAME>], [HUN], [2810],
[69], [<NAME>], [CRO], [2806],
[70], [UEDA Jin], [JPN], [2806],
[71], [<NAME>], [KOR], [2804],
[72], [ZHAI Yujia], [DEN], [2801],
[73], [PITCHFORD Liam], [ENG], [2801],
[74], [CHO Daeseong], [KOR], [2796],
[75], [WANG Eugene], [CAN], [2790],
[76], [TAKAKIWA Taku], [JPN], [2787],
[77], [KOU Lei], [UKR], [2785],
[78], [UDA Yukiya], [JPN], [2783],
[79], [GERELL Par], [SWE], [2782],
[80], [<NAME>], [BEL], [2778],
[81], [<NAME>], [CRO], [2772],
[82], [WEI Shihao], [CHN], [2769],
[83], [DYJAS Jakub], [POL], [2767],
[84], [<NAME>], [IND], [2766],
[85], [<NAME>], [RUS], [2766],
[86], [<NAME>], [CHN], [2762],
[87], [<NAME>], [JPN], [2761],
[88], [<NAME>], [POL], [2754],
[89], [<NAME>], [GER], [2752],
[90], [<NAME>], [POR], [2750],
[91], [<NAME>], [SVK], [2750],
[92], [<NAME>], [GRE], [2749],
[93], [<NAME>], [SWE], [2748],
[94], [<NAME>], [SLO], [2744],
[95], [#text(gray, "W<NAME>engyi")], [POL], [2743],
[96], [<NAME>], [KOR], [2741],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [LIAO Cheng-Ting], [TPE], [2734],
[98], [HO Kwan Kit], [HKG], [2731],
[99], [WANG Yang], [SVK], [2726],
[100], [<NAME>], [JPN], [2722],
[101], [<NAME>], [ENG], [2719],
[102], [<NAME>], [JPN], [2718],
[103], [AKKUZU Can], [FRA], [2718],
[104], [<NAME>], [SRB], [2717],
[105], [<NAME>], [BRA], [2716],
[106], [<NAME>], [CHN], [2715],
[107], [<NAME>], [SLO], [2713],
[108], [#text(gray, "KIM Minseok")], [KOR], [2708],
[109], [<NAME>], [CHN], [2708],
[110], [<NAME>], [SWE], [2706],
[111], [<NAME>], [ESP], [2706],
[112], [QIU Dang], [GER], [2706],
[113], [<NAME>], [IRI], [2697],
[114], [<NAME>], [PRK], [2696],
[115], [<NAME>], [DEN], [2696],
[116], [WU Jiaji], [DOM], [2693],
[117], [<NAME>], [ESP], [2692],
[118], [<NAME>], [AUT], [2691],
[119], [<NAME>], [UKR], [2688],
[120], [<NAME>], [ROU], [2687],
[121], [<NAME>], [JPN], [2686],
[122], [<NAME>], [ROU], [2685],
[123], [<NAME>], [AUT], [2683],
[124], [KIZUKURI Yuto], [JPN], [2680],
[125], [<NAME>], [GER], [2680],
[126], [LANDRIEU Andrea], [FRA], [2672],
[127], [<NAME>], [POR], [2672],
[128], [<NAME>], [JPN], [2670],
)
) |
|
https://github.com/qujihan/toydb-book | https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter2/memory.typ | typst | #import "../../typst-book-template/book.typ": *
#let path-prefix = figure-root-path + "src/pics/"
== Memory 存储引擎
TODO: 比较简单,可以直接看代码。
|
|
https://github.com/Namacha411/shogi-board | https://raw.githubusercontent.com/Namacha411/shogi-board/main/README.md | markdown | MIT License | # Shogi-board
Typst向けの将棋盤プラグインです。
詳細は[こちらのpdf](./manual.pdf)をご覧ください。
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/grayness/0.1.0/manual.typ | typst | Apache License 2.0 | #import "@preview/tidy:0.2.0"
= GrayNess
This Package provides the following basic image editing functions:
#let docs = tidy.parse-module(read("lib.typ"))
#tidy.show-module(docs, style: tidy.styles.default) |
https://github.com/skylee03/skylee-homework-typst | https://raw.githubusercontent.com/skylee03/skylee-homework-typst/main/skylee-hw.typ | typst | MIT License | #let _shw-problem-counter = counter("_shw:problem-counter")
#let problem = (content) => {
_shw-problem-counter.update(n => n + 1)
grid(
columns: (auto, 1fr),
column-gutter: 1em,
_shw-problem-counter.display("1."),
content
)
}
#let parts = (..args) => {
enum(
tight: false,
numbering: "(a)",
..args
)
}
#let solution = (content) => {
grid(
columns: (auto, 1fr),
column-gutter: 4pt,
box(stroke: (dash: "dashed", thickness: .5pt), outset: 4pt, [_Solution_]),
line(length: 100%, stroke: (dash: "dashed", thickness: .5pt))
)
content
}
#let skylee-hw(
institute: none,
course: none,
session: none,
title: none,
author: none,
date: datetime.today(),
doc
) = {
set page(
header: context [
#if counter(page).get() != (1,) {
set text(8pt)
course
h(1fr)
institute
line(length: 100%, stroke: .5pt)
}
],
footer: context [
#set text(8pt)
#counter(page).display(
"1 of 1",
both: true,
)
],
)
set par(leading: 5pt, justify: true)
set align(center)
if institute != none {
institute
linebreak()
}
if course != none {
course
linebreak()
}
if session != none {
session
linebreak()
}
line(length: 100%, stroke: .5pt)
strong(underline(title))
linebreak()
if author != none {
author
}
h(1fr)
if date != none {
date.display("[day padding:none] [month repr:long] [year]")
}
line(length: 100%, stroke: .5pt)
set align(start)
doc
}
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/C++/Introduzione/Stringhe.typ | typst | Creative Commons Zero v1.0 Universal | #import "@preview/showybox:2.0.1": showybox
Una *stringa* é un tipo di dato che permette di memorizzare informazioni
alfanumeriche. In C, le stringhe sono degli array di `char` il cui ultimo
carattere é il carattere speciale `\0`. Quando a `cout` viene fornito un
array di `char` con queste caratteristiche, vengono ordinatamente stampati
tutti i caratteri dell'array ad eccezione di `\0`. Un puntatore a `char`
viene interpretato come una stringa, pertanto non é possibile, a meno di
usare una sintassi particolarmente convoluta, riferirsi ad una stringa
tramite un puntatore. Le stringhe del C hanno dei metodi che si trovano
nell'header file `string.h` (o `cstring`).
#showybox[
```
char strc[10] = "Hello";
char strl[] = {'W', 'o', 'r', 'l', 'd', '!', '\0'};
char* strp = "Hello, World!"; // should be const char* strp
```
]
Una sintassi del tipo `char* str = "..."` é ammessa perché é un residuo del
modo in cui C gestisce le stringhe, ma non é tecnicamente corretta. Infatti,
una stringa scritta in questo modo ha implicitamente un `const` davanti,
perché indica una stringa costante che viene raggiunta attraverso un puntatore
non costante. Infatti, se si cerca di manipolare tale stringa tramite tale
puntatore viene restituito un errore.
// Da rivedere
In C++, questa é la forma piú "basica" di stringa, e pertanto andrebbe evitata
a meno di circostanze particolari. Le stringhe C++ sono degli oggetti veri e
propri, definiti come `std::string`. L'header file `string` contiene diversi
metodi per manipolarle.
#showybox[
```
#include <string>
std::string s1;
s1 = "Hello";
std::string s2 = "World!";
```
]
Le stringhe C sono ancora utilizzate come argomenti dalla riga di comando.
Infatti, la sintassi standard #footnote[Alcuni compilatori accettano anche
versioni non strettamente conformi a tale standard, ma é comunque best
practise aderirvi.] della funzione `main` completa é la seguente:
```
int main(int argc, char* argv[])
{
...
return 0;
}
```
`argc` (_argument count_) é una variabile intera e cattura il numero di
argomenti passati al programma quando é stato invocato. `argv` (_argument
value_) é un array di puntatori, ciascuno facente riferimento ad una stringa,
ed a sua volta ciascuna stringa é l'$i$-esimo argomento passato al programma.
L'unica eccezione é `argv[0]`, che é invece il nome dell'eseguibile stesso
(pertanto, gli argomenti vanno contati a partire da $1$).
Gli argomenti in `argv` sono sempre e comunque stringhe. Per interpretarne
il contenuto come tipi di dato primitivi diversi (come `int` o `float`) sono
possibili due strade:
- Usare le funzioni di basso livello del C, come `atoi` o `atof`;
- Usare gli oggetti `stringstream` dell'header C++ `sstream`.
#grid(
columns: (0.5fr, 0.5fr),
[
```
var_type = std::atoX(argv[i]);
```
],
[
```
#import <sstream>
std::stringstream s_name(argv[i]);
type name;
s_name >> name;
```
]
)
|
https://github.com/robinhundt/tpmpc24-talk | https://raw.githubusercontent.com/robinhundt/tpmpc24-talk/main/circuit.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#import cetz.draw: *
#let anchors(anchors) = {
for (k, v) in anchors {
anchor(k, v)
}
}
#let and-gate-body = {
group(name: "and", {
merge-path(close: true, {
arc((0,0), start: -90deg, stop: 90deg, radius: 0.5, name: "curve", anchor: "origin")
line(
(0, 0.5),
(-0.5, 0.5),
(-0.5, -0.5)
)
})
anchors((
"bin 1": (-0.5, 0.25),
"in 1": (rel: (-0.5, 0)),
"bin 2": (-0.5, -0.25),
"in 2": (rel: (-0.5, 0)),
"bout": (0.5, 0),
"out": (rel: (0.5, 0)),
"north": (0, 0.5),
"south": (rel: (0, -1)),
"east": "out",
// "west": ("in 1", "|-", "center"),
// "left": ("bin 1", "|-", "center"),
"right": "bout"
))
})
}
#let or-gate-body = {
group(name: "or", {
merge-path(close: true, {
arc((0.5, 0), start: -90deg, stop: -30deg, anchor: "arc-end", name: "bcurve")
arc((0.5,0), start: 30deg, stop: 90deg, anchor: "arc-start", name: "tcurve")
line("tcurve.end", (-0.5, 0.5))
arc((), start: 30deg, stop: -30deg, anchor: "arc-start", name: "la")
line("bcurve.start", "la.end")
})
// x coordinate of where the input legs touch the body of the gate
let x = calc.cos(calc.asin(0.25)) - calc.cos(calc.asin(0.5)) - 0.5
anchors((
"bin 1": (x, 0.25),
"in 1": (-1, 0.25),
"bin 2": (x, -0.25),
"in 2": (-1, -0.25),
"bout": (0.5, 0),
"out": (rel: (0.5, 0)),
"north": (0, 0.5),
"south": (rel: (0, -1)),
"east": "out",
// "west": ("in 1", "|-", "center"),
// "left": ("bin 1", "|-", "center"),
"right": "bout"
))
})
}
#let xor-bar = {
group(name: "xor", {
arc((-0.6, -0.5), start: -30deg, stop: 30deg)
anchors((
"ibin 1": "bin 1",
"ibin 2": "bin 2",
"bin 1": (rel: (-0.1, 0), to: "bin 1"),
"bin 2": (rel: (-0.1, 0), to: "bin 2"),
// "body left": "left",
// "left": (rel: (-0.1, 0), to: "left")
))
})
}
#let logic-gate-legs(g) = for a in ("in 1", "in 2", "out") {
line(g + ".b" + a, g + "." + a)
}
#let and-gate = {
and-gate-body
logic-gate-legs("and")
}
#let or-gate = {
or-gate-body
logic-gate-legs("or")
}
#let xor-gate = {
group(name: "xor", {
or-gate-body
copy-anchors("or")
logic-gate-legs("or")
xor-bar
})
} |
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/kurzentwuerfe/template.typ | typst | Other | #let the-date = datetime(
year: datetime.today().year(),
month: datetime.today().month(),
day: datetime.today().day()
).display("[day].[month].[year]")
#let cheat-sheet = [
]
#let schedule(class: 9,
title-lesson: none,
title-series: none,
justification: none,
time: none,
date: datetime.today(),
schedule-context: none,
main-objective: none,
fine-objectives: (),
..args) = {
set page(flipped: true, margin: (bottom: 2cm, rest: 1.5cm))
grid(columns: (0.5fr, auto, 0.5fr))[
Universität Rostock \
Institut für Philosophie \
Einführung in die Philosophiedidaktik \
Dr. phil. <NAME> \
][
*Plan für eine Unterrichtsstunde*
][
#align(right)[
[Name der Lehrperson] \
#the-date
]
]
line(length: 100%)
par[
*Klasse:* #class,
*Zeit:* #time,
*Datum:* #the-date
]
par[
*Thema der Unterrichtsreihe:* #title-series \
*Thema der Unterrichtsstunde:* #title-lesson
*Begründung der Themenwahl:* #justification
]
par[
*Grobziel:* #main-objective \
*Feinziele:* #list(..fine-objectives)
]
par(schedule-context)
line(length: 100%)
table(columns: (auto, auto, auto, 6cm, auto, auto),
stroke: none,
row-gutter: 0.5cm,
strong[Zeit/Phase],
strong[Inhalt],
strong[Lehrerverhalten\ (geplant)],
strong[Schülerverhalten\ (erwartet)],
strong[Methoden\ /Sozialform],
strong[Medien],
..args)
// line(length: 100%)
}
#let task(body) = strong[Aufgabe: ] + body
#let todo(body) = text(fill: red, body) |
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/07-localisation/USE-cluster.typ | typst | Other | #import "/lib/draw.typ": *
#let start = (100, -20)
#let end = (800, 700)
#let graph = with-unit((ux, uy) => {
// mesh(start, end, (100, 100), stroke: 1 * ux + gray)
let txt = txt.with(size: 15 * ux)
let highlight-stroke = stroke(
paint: green.darken(20%),
thickness: 2 * ux,
dash: (23*ux, 8*ux, 6*ux, 8*ux)
)
let component = (body, highlight: false) => block(
inset: 10 * ux,
spacing: 0pt,
radius: 15 * ux,
stroke: if highlight { highlight-stroke } else { 1 * ux + theme.main },
align(center, body),
)
let make-data = (x, y, anchor, body, highlight: false, from: none, to: none) => {
let (fx, fy) = if from == none { (0, 0) } else { from }
let (tx, ty) = if to == none { (0, 0) } else { to }
return (
point: (x, y),
anchor: anchor,
body: body,
highlight: highlight,
from: (x + fx, y + fy),
to: (x + tx, y + ty),
)
}
let data = (
make-data(325, 650, "rc", [
*可选的基本字符前方部件*
Reph*或*直接叠加的辅音
]),
make-data(500, 640, "lc", [
*基本字符*
基本*或*“其他基本”字符;
可以附带一个变体选择器
], from: (0, -20)),
make-data(330, 590, "rt", [
*辅音修饰组*
任意个基本字符上方修饰符;
任意个基本字符下方修饰符;
], to: (0, -20), from: (0, -50)),
make-data(440, 510, "lc", [
*任意个半音组*
半音符和基本字符,可以附带一个变体选择器#linebreak()
*或*一个附加辅音;
可以附带一个*辅音修饰组*
], highlight: true),
make-data(500, 350, "lc", [
*词中辅音组*
任意个基本字符前方词中辅音;
任意个基本字符上方词中辅音;
任意个基本字符下方词中辅音;
任意个基本字符后方词中辅音;
]),
make-data(330, 290, "rc", [
*元音组*
任意个基本字符前方元音;
任意个基本字符上方元音;
任意个基本字符下方元音;
任意个基本字符后方元音;
], to: (0, 20), from: (0, -25)),
make-data(500, 250, "lt", [
*元音修饰组*
任意个基本字符前方元音修饰符;
任意个基本字符上方元音修饰符;
任意个基本字符下方元音修饰符;
任意个基本字符后方元音修饰符;
], to: (0, -20), from: (0, -100)),
make-data(350, 140, "rt", [
*结尾辅音组*
任意个基本字符上方结尾辅音;
任意个基本字符下方结尾辅音;
任意个基本字符后方结尾辅音;
可以附带一个结尾修饰符
], to: (0, -20))
)
let draw-data = bubble => txt(component(bubble.body, highlight: bubble.highlight), bubble.point, anchor: bubble.anchor)
for bubble in data {
draw-data(bubble)
}
for (highlight, start, end) in data.zip(data.slice(1)).map(((a, b)) => {
(a.highlight, a.from, b.to)
}) {
if not highlight {
arrow(start, end, head-scale: 4)
}
}
let (x, y) = data.at(3).point
let (hx, hy) = (300, 400)
draw-data(make-data(hx, hy, "rc", [
*结尾半音*
]))
arrow((x, y - 50), (hx, hy + 8), head-scale: 4)
arrow((600, 455), (600, 425), head-scale: 4)
})
#canvas(end, start: start, width: 100%, graph)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-25.typ | typst | Other | // Error: 2-10 cannot calculate sum of empty array with no default
#().sum()
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/recipes/specifying-sources.md | markdown | MIT License | # Specifying sources
A number of derivations in Typix accept source trees as parameters, such as
[`src`](../api/derivations/mk-typst-derivation.md#src),
[`fontPaths`](../api/derivations/mk-typst-derivation.md#fontpaths), and
[`virtualPaths`](../api/derivations/mk-typst-derivation.md#virtualpaths). Specifying
these is usually as simple as
[`cleanTypstSource`](../api/utilities/clean-typst-source.md) in the case of
`src` and string interpolation (via `${...}`) in the case of `fontPaths` and
`virtualPaths`, but there are situations where more is required or desirable.
## Expanding a source tree
> TL;DR: you can use [`lib.sources.cleanSource`][nixpkgs-sources-cleansource],
> but the problem with this approach is that every change to a file tracked by
> git will invalidate the cache and trigger a rebuild.
To include more _local files_[^fileset-note] in a source tree, you can use a
combination of different functions in [`lib.fileset`][nixpkgs-fileset]
such as [`lib.fileset.unions`][nixpkgs-fileset-unions],
[`lib.fileset.fromSource`][nixpkgs-fileset-fromsource], and
[`lib.fileset.toSource`][nixpkgs-fileset-tosource], like so:
```nix
{
outputs = { nixpkgs, typix }: let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
inherit (pkgs) lib;
typixLib = typix.lib.${system};
myTypstSource = typixLib.cleanTypstSource ./.;
in {
packages.${system}.default = typixLib.mkTypstDerivation {
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
(lib.fileset.fromSource myTypstSource)
./path.svg
./other/path.svg
./another
];
};
};
};
}
```
This will create a source tree that looks something like:
```text
/nix/store/...
├── another
│ ├── path1.svg
│ ├── path2.svg
│ └── path3.svg
├── path.svg
├── other
│ └── path.svg
└── ...
```
<!-- prettier-ignore-start -->
[^fileset-note]: `lib.fileset` functions can only be used with local files, not
e.g. flake inputs, which is what
[`virtualPaths`](../api/derivations/mk-typst-derivation.md#virtualpaths) is for.
<!-- prettier-ignore-end -->
## Source filtering
You can do source filtering primarily using
[`builtins.filterSource`][nix-ref-builtins-filtersource] and functions in
[`lib.sources`][nixpkgs-sources] such as
[`lib.sources.cleanSourceWith`][nixpkgs-sources-cleansourcewith].
A more detailed explanation can be found in the Nix discussion: ["Filtering
Source Trees with Nix and Nixpkgs"][nix-discussion-source-filtering].
Here's an example which picks specific files by name:
```nix
{
outputs = { nixpkgs, typix, font-awesome }: let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
fontAwesomeSubset = let
icons = [
"gem.svg"
"heart.svg"
"lightbulb.svg"
];
in lib.sources.cleanSourceWith {
src = "${font-awesome}/svgs/regular";
filter = path: type:
builtins.any (icon: builtins.baseNameOf path == icon) icons;
};
in {
packages.${system}.default = typix.lib.${system}.mkTypstDerivation {
virtualPaths = [
fontAwesomeSubset
];
};
};
}
```
[nix-discussion-source-filtering]: https://discourse.nixos.org/t/filtering-source-trees-with-nix-and-nixpkgs/19148
[nix-ref-builtins-filtersource]: https://nixos.org/manual/nix/stable/language/builtins.html#builtins-filterSource
[nixpkgs-fileset-fromsource]: https://nixos.org/manual/nixpkgs/stable/#function-library-lib.fileset.fromSource
[nixpkgs-fileset-tosource]: https://nixos.org/manual/nixpkgs/stable/#function-library-lib.fileset.toSource
[nixpkgs-fileset-unions]: https://nixos.org/manual/nixpkgs/stable/#function-library-lib.fileset.unions
[nixpkgs-fileset]: https://nixos.org/manual/nixpkgs/stable/#sec-functions-library-fileset
[nixpkgs-sources-cleansource]: https://nixos.org/manual/nixpkgs/stable/#function-library-lib.sources.cleanSource
[nixpkgs-sources-cleansourcewith]: https://nixos.org/manual/nixpkgs/stable/#function-library-lib.sources.cleanSourceWith
[nixpkgs-sources]: https://nixos.org/manual/nixpkgs/stable/#sec-functions-library-sources
|
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/template/main.typ | typst | The Unlicense | #import "/src/lib.typ" as journal
#show: journal.ensemble.rule()
#let logo = {
v(1fr)
set align(right)
block({
set align(left)
set text(weight: 600)
context text(
size: 20pt,
fill: journal.ensemble.color-accent-1.get(),
h(0.3em) + upper[Journal Of\ ]
)
text(size: 32pt, fill: white, [Breathomics])
})
}
#journal.pages.cover(
hero: logo,
title: [Advances in Breath Analysis and its Applications]
)
// #journal.pages.inner(
// text(size: 32pt, weight: 600, [Breathomics]),
// )
#journal.pages.contents()
#journal.contents.mark(scope: "Editorial", "Editorial")
#journal.part.make-new-section("Letters and Communications")
#journal.part.make-new-section("Research Articles")
#include "articles/1.typ"
#include "articles/1.typ"
#journal.part.make-new-section("Literature Reviews")
#include "articles/1.typ"
#include "articles/1.typ"
#journal.part.make-new-section("Posters")
#journal.part.make-new-section("Tutorials")
|
https://github.com/rose-pine/typst | https://raw.githubusercontent.com/rose-pine/typst/main/src/themes/rose-pine.typ | typst | MIT License | #let rose-pine = (
base : rgb("#191724"),
surface : rgb("#1f1d2e"),
overlay : rgb("#26233a"),
muted : rgb("#6e6a86"),
subtle : rgb("#908caa"),
text : rgb("#e0def4"),
love : rgb("#eb6f92"),
gold : rgb("#f6c177"),
rose : rgb("#ebbcba"),
pine : rgb("#31748f"),
foam : rgb("#9ccfd8"),
iris : rgb("#c4a7e7"),
highlight : (
low : rgb("#21202e"),
med : rgb("#403d52"),
high : rgb("#524f67"),
),
codeThemePath: "themes/rose-pine.tmTheme",
)
#let variant = rose-pine
|
https://github.com/rzmk/various-dsat-math-notes | https://raw.githubusercontent.com/rzmk/various-dsat-math-notes/main/README.md | markdown | # 📝 Various Digital SAT Math Notes
A **supplemental resource** of notes based on various resources for individuals studying for the Digital SAT's math section.
## **[View notes.pdf for the compiled notes.](notes.pdf)**
[](notes.pdf)
## 📚 Tech Stack
- [Typst](https://typst.app) - Typesetting system
- [release-it](https://github.com/release-it/release-it) - Release management
## 📢 Disclaimer
Organized by [<NAME>](https://www.mueezkhan.com), based on material(s) attributed within the notes.
If there are any errors in this document, please let me know by [contacting me](https://www.mueezkhan.com/contact) or opening an [issue](https://github.com/rzmk/various-dsat-math-notes/issues) and/or [pull request](https://github.com/rzmk/various-dsat-math-notes/pulls). Fixes are greatly appreciated!
<!--
Notes for maintainer(s):
On release:
- Update footer with new version number
- (optional) Update cover page image (cover.png) with new version number
-->
|
|
https://github.com/JamesWrigley/euxfel-polylux-theme | https://raw.githubusercontent.com/JamesWrigley/euxfel-polylux-theme/master/README.md | markdown | # An XFEL Polylux theme
This is a [Polylux](https://polylux.dev/book/) theme for [European
XFEL](https://xfel.eu) presentations.
Here's a quick demo:
```typst
#import "euxfel-polylux-theme/theme.typ": *
// Default options are shown commented out
#show: euxfel-theme.with(
title: "Optimising treat delivery",
author: "<NAME>",
// title-page-header: true,
// font: "New Computer Modern Sans"
)
#slide("Introduction")[
- Humans are increasingly stingy, leading to catastrophic decreases in treat delivery from 172.8$mu$Hz to 86.4$mu$Hz.
- Caused in part by economic effects.
- The author blames dogs.
]
```
Producing:

## Acknowledgements
Many thanks to the original authors of XFEL's Beamer template, from which I took
both inspiration and some SVG files.
|
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/机器视觉实践/报告/1/1.typ | typst | The Unlicense | #import "../template.typ": *
#show: project.with(
title: "1",
authors: ("absolutex",),
)
= 机器视觉实践 一
== 实验目的
图像划痕修复:
+ 编程实现图像划痕修复
+ 要求算法具有一定实时性能够处理较密集的图像划痕
+ 具体实现方法不限
+ 编程语言不限,可通过C++,Python或Matlab实现
== 实验内容
=== 高斯模糊
课上有学习过,高斯模糊是一种平滑滤波器,它通过在图像的每个像素周围应用加权平均来减少图像中的高频噪声和细节。这种模糊操作会丢失图像中的细节信息,包括瑕疵的边缘和纹理。所以我尝试用高斯模糊来实现图像划痕去除。
#include_code("../src/scratch/gause.py")
=== inpaint
当然,使用 inpaint 是更广泛使用的方式。inpaint 需要一张 mask,在划痕部分为白色,而在其他地方为黑色。这个 mask 对于修复划痕是必要的。
但是从图像自动生成 mask 非常困难,业界一般使用大模型去生成 mask。这里就让用户自行画出 mask。这里我使用 python tkinter 库,将图片显示到窗口上,而实际作画时同时在图片和准备好的蒙版上进行绘制,并将最终结果保存为图片。
#include_code("../src/scratch/drawmaskw.py")
然后,将蒙版与原始图像同时输入到 inpaint,得到修复后的图像。
#include_code("../src/scratch/myinpaint.py")
这里使用了 opencv 库中的 inpaint 方法。OpenCV 提供了两种主要的修复算法:Telea 方法(基于快速行进算法),Navier-Stokes 方法(基于流体力学方程)。
Telea 方法基于快速行进算法(Fast Marching Method, FMM),它通过逐步扩展修复区域来填充缺失部分。该方法的核心思想是:对于每个需要修复的像素,使用其周围已知像素的加权平均值来估计其颜色值。权重取决于像素到已知区域的距离。
Navier-Stokes 方法基于流体力学中的 Navier-Stokes 方程,通过模拟流体的运动来填充缺失区域。该方法的核心思想是:将图像视为一个流体场,通过求解流体力学方程来模拟流体的运动,从而填充缺失区域。
== 实验结果
=== 高斯模糊
#figure(
image("gause.jpg", width: 100%),
caption: [gause 效果图],
)
可以看出高斯模糊的效果并不好,处理后图像还是能看见明显的划痕,这可能是没选择好高斯核(ksize)的大小导致的。但是 ksize 大了容易丢失其他高频细节,因此需要做好权衡。
=== inpaint
#figure(
image("mask.jpg", width: 50%),
caption: [用户绘制的 mask],
)
#figure(
image("inpaint.jpg", width: 100%),
caption: [inpaint 效果图(Telea)],
)
可以看出,inpaint 的效果不错。虽然在划痕边缘出现了色块扭曲等现象,这可能是因为用户绘制的 mask 覆盖了更多的色块导致的。如果使用更加细致精确的 mask,可以产生更好的效果。
至于 Telea 方法和 Navier-Stokes 方法我也都尝试了一遍,没有太大的差异。
== 心得体会
这次实践让我得以将课上的理论应用于实际。在查找方法与尝试方法的过程中我学到了很多理论无法教给我的东西。并且此过程中我也顺带学习了 python 项目管理,tkinter GUI 的绘制,蒙版的制作等。
|
https://github.com/nafkhanzam/typst-common | https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/common/style.typ | typst | #let headz(outlined: true, body) = heading(outlined: outlined, numbering: none, body)
#let phantom(body) = place(top, scale(x: 0%, y: 0%, hide(body)))
#let s-center(body) = align(center + horizon, body)
#let enable-todo-hl(body) = {
show "TODO": box(
fill: red.darken(25%),
outset: .15em,
text(fill: white)[TODO],
)
body
}
#let icite(key) = cite(label(key), form: "prose")
#let i(body) = {
set cite(form: "prose")
body
}
#let entry-fields(entries, ..args) = grid(
columns: 3,
gutter: 0.65em,
..args,
..entries.map(v => (v.at(0), [: ], v.at(1))).flatten(),
)
#let hl(body) = highlight(body)
#let red-hl(body) = highlight(fill: red, body)
#let bl = block.with(breakable: false)
#let inline-enum(
join-sym: [,],
last-join: [and],
suffix: none,
..entries,
) = {
entries = entries.pos()
let n = entries.len()
if n == 1 {
return entries.at(0)
}
for (i, v) in entries.enumerate() {
if i > 0 {
[#join-sym ]
}
if n != 0 and i == n - 1 and last-join != none {
[#last-join ]
}
[(#(i+1)) #v]
}
suffix
}
#let link-b(url, body) = {
show: underline
show: text.with(fill: rgb(0, 0, 238))
link(url, body)
}
#let allow-table-break(body) = {
show figure.where(kind: "table"): set block(breakable: true)
body
}
#let important(body) = underline[*#body*]
|
|
https://github.com/KrisjanisP/lu-icpc-notebook | https://raw.githubusercontent.com/KrisjanisP/lu-icpc-notebook/main/2-algebra.typ | typst |
#block( breakable: false,[
= Algebra
== Binary exponentiation
```cpp
ll m_pow(ll base, ll exp, ll mod) {
base %= mod; ll result = 1;
while (exp > 0) {
if (exp & 1) result = (result * base) % mod;
base = (base * base) % mod; exp >>= 1;
}
return result;
}
```
])
#block( breakable: false,[
== Extended euclidean
#label("gcd_ext")
Find integers $x$ and $y$ such that:
$a dot x + b dot y = gcd(a, b)$
```cpp
int gcd_ext(int a, int b, int& x, int& y) {
if (b == 0) { x = 1; y = 0; return a; }
int x1, y1; int d = gcd_ext(b, a % b, x1, y1);
x = y1; y = x1 - y1 * (a / b); return d;
}
```
== Modular inversion & division
Mod inverse exists iff number is coprime with mod.
$ exists x (a dot x equiv 1 (mod m)) arrow.l.r.double "gcd"(a,m)=1 $
```cpp
int mod_inv(int b, int m) {
int x, y; int g = gcd_ext(b, m, &x, &y);
if (g != 1) return -1;
return (x%m + m) % m;
}
int m_divide(ll a, ll b, ll m) {
int inv = mod_inv(b, m); assert(inv != -1);
return (inv * (a % m)) % m;
}
```
])
#block( breakable: false,[
== Linear Diophantine equation
// `gcd_ext` defined in #ref(label("gcd_ext"),).
$ {(x,y) in ZZ^2 | a dot x + b dot y = c } = {x_0 + k dot (b slash g), y_0 - k dot (a slash g) | k in ZZ } $
```cpp
bool find_x0_y0(int a, int b, int c, int &x0, int &y0, int &g) {
g = gcd_ext(abs(a), abs(b), x0, y0);
if (c % g) return false;
x0 *= c / g; y0 *= c / g;
if (a < 0) x0 = -x0; if (b < 0) y0 = -y0;
return true;
}
```
])
#block( breakable: false,[
== Linear sieve
```cpp
const int N=10000000; vector<int> lp(N+1), pr;
for(int i=2;i<=N;i++){
if(!lp[i]){ lp[i]=i; pr.push_back(i); }
for(int j=0;j<pr.size() && i*pr[j]<=N;j++){
lp[i*pr[j]]=pr[j];
if(pr[j]==lp[i]) break;
}
}
```
])
#block(breakable: false,[
== Matrix multiplication
Inherit vector's constructor to allow brace initialization.
```cpp
struct Matrix:vector<vector<int>>{
using vector::vector;
Matrix operator *(const Matrix& other){
int rows = size(); int cols = other[0].size();
Matrix res(rows, vector<int>(cols));
for(int i=0;i<rows;i++) for(int j=0;j<other.size();j++)
for(int k=0;k<cols;k++)
res[i][k]+=at(i).at(j)*other[j][k];
return res;
}
};
```
Usage example (prints `403 273 234 442`):
```cpp
Matrix A = {{19,7},{6, 20}}, B = {{19,7},{6, 20}}, C = A*B;
for(auto rows: C) for(int cell: rows) cout<<cell<<" ";
```
])
#block(breakable: false,[
== Euler's totient function
```cpp
int phi(int n){
int res=n; for(int i=2;i*i<=n;i++) if(n%i==0)
{ while(n%i==0)n/=i; res-=res/i; }
if(n>1) res-=res/n; return res;
}
void phi_1_to_n(int n){
vector<int> phi(n+1); for(int i=0;i<=n;i++) phi[i]=i;
for(int i=2;i<=n;i++) if(phi[i]==i)
for(int j=i;j<=n;j+=i) phi[j]-=phi[j]/i;
}
```
])
#block(breakable: false,[
== Gauss method
System of $n$ linear algebraic equations (SLAE) with $m$ variables.
$ cases(a_(1 1) x_1 + a_(1 2) x_2 + ... + a_(1 m) x_m = b_1,...,a_(n 1) x_1 + a_(n 2) x_2 + ... + a_(n m) x_m = b_n) $
Matrix representation: $A x = b$. Gauss-Jordan elimination impl.:
```cpp
const double EPS=1e-9; const int INF=2;
int gauss(vector<vector<double>> a, vector<double> &ans){
// last column of matrix a is vector b
int n=a.size(), m=a[0].size()-1; vector<int> where(m,-1);
for(int col=0, row=0; col<m && row<n; ++col){
int sel=row; for(int i=row;i<n;i++)
if(abs(a[i][col])>abs(a[sel][col])) sel=i;
if(abs(a[sel][col])<EPS) continue;
for(int i=col;i<=m;i++) swap(a[sel][i],a[row][i]);
where[col]=row; for(int i=0;i<n;i++) if(i!=row){
double c=a[i][col]/a[row][col];
for(int j=col;j<=m;j++) a[i][j]-=a[row][j]*c;} row++;
}
ans.assign(m,0); for(int i=0;i<m;i++)
if(where[i]!=-1) ans[i]=a[where[i]][m]/a[where[i]][i];
for(int i=0;i<n;i++){
double sum=0; for(int j=0;j<m;j++) sum+=ans[j]*a[i][j];
if(abs(sum-a[i][m])>EPS) return 0;}
for(int i=0;i<m;i++) if(where[i]==-1) return INF; return 1;
}
```
])
#block( breakable: false,[
== FFT
```cpp
const int N=1<<18;
const ld PI=acos(-1.0);
struct T{
ld x,y;
T():x(0),y(0){}
T(ld a, ld b=0):x(a),y(b){}
T operator/=(ld k){x/=k;y/=k;return *this;}
T operator*(const T&a) const {
return T(x*a.x-y*a.y, x*a.y+y*a.x);}
T operator+(const T&a) const {return T(x+a.x, y+a.y);}
T operator-(const T&a) const {return T(x-a.x, y-a.y);}
};
void fft(T*a,int n,int s){
for(int i=0,j=0;i<n;i++){
if(i>j) swap(a[i],a[j]);
for(int l=n/2;(j^=l)<l;l>>=1);
}
for(int i=1;(1<<i)<=n;i++){
int M=1<<i, K=M>>1;
T wn= T(cos(s*2*PI/M), sin(s*2*PI/M));
for(int j=0;j<n;j+=M){
T w=1;
for(int l=j;l<j+K;l++){
T t=w*a[l+K];
a[l+K]=a[l]-t; a[l]=a[l]+t;
w=wn*w;
}
}
}
}
void multiply(T*a,T*b,int n){
while(n&(n-1)) n++;
fft(a,n,1); fft(b,n,1);
for(int i=0;i<n;i++) a[i]=a[i]*b[i];
fft(a,n,-1);
for(int i=0;i<n;i++) a[i]/=n;
}
int main(){
T a[10]={T(2),T(3)}, b[10]={T(1),T(-1)};
multiply(a,b,4);
for(int i=0;i<10;i++) std::cout<<int(a[i].x)<<" ";
}
```
])
== Fast binomial coefficient
```cpp
int MAX_CHOOSE=3e5;
vector<ll> inv_fact(MAX_CHOOSE+5), fact(MAX_CHOOSE+5);
ll fast_nCr(ll n, ll r){
if(n<r || r<0) return 0;
return fact[n]*inv_fact[r]%mod*inv_fact[n-r]%mod;
}
void precalc_fact(int n){
fact[0]=fact[1]=1;
for(ll i=2;i<=n;i++) fact[i]=(fact[i-1]*i)%mod;
inv_fact[0]=inv_fact[1]=1;
for(ll i=2;i<=n;i++)
inv_fact[i]=(mod_inv(i,mod)*inv_fact[i-1])%mod;
}
``` |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/return-04.typ | typst | Other | // Test that the expression is evaluated to the end.
#let sum(..args) = {
let s = 0
for v in args.pos() {
s += v
}
s
}
#let f() = {
sum(..return, 1, 2, 3)
"nope"
}
#test(f(), 6)
|
https://github.com/KNnut/neoplot | https://raw.githubusercontent.com/KNnut/neoplot/main/pkg/examples/demo.typ | typst | BSD 3-Clause "New" or "Revised" License | #import "../lib.typ" as gp
#let title = [Gnuplot demos]
#let subtitle = [in Typst]
#align(center,
text(17pt)[
*#title*
] +
text(12pt)[
*#subtitle*
]
)
```typ gp.exec(kind: "command", command)``` can be used to run gnuplot commands:
#figure(
gp.exec(
kind: "command",
width: 55%,
"set term svg size 500, 400; set xrange[-2.5*pi:2.5*pi]; set yrange[-1.3:1.3]; plot sin(x), cos(x)",
),
caption: "Graphs of Sine and Cosine",
)
```typ gp.exec(script)``` can be used to run a gnuplot script:
#figure(
grid(
columns: 2,
rows: 2,
gutter: 0pt,
gp.exec(
width: 90%,
```gnuplot
reset
set term svg size 600, 400
set grid
set samples 21
set isosample 11
set xlabel "X axis" offset -3,-2
set ylabel "Y axis" offset 3,-2
set zlabel "Z axis" offset -5
set title "3D surface from a function"
set label 1 "This is the surface boundary" at -10,-5,150 center
set arrow 1 from -10,-5,120 to -10,0,0 nohead
set arrow 2 from -10,-5,120 to 10,0,0 nohead
set arrow 3 from -10,-5,120 to 0,10,0 nohead
set arrow 4 from -10,-5,120 to 0,-10,0 nohead
set xrange [-10:10]
set yrange [-10:10]
splot x*y
```),
gp.exec(
width: 90%,
```gnuplot
reset
set grid nopolar
set grid xtics nomxtics ytics nomytics noztics nomztics nortics nomrtics \
nox2tics nomx2tics noy2tics nomy2tics nocbtics nomcbtics
set grid layerdefault lt 0 linecolor 0 linewidth 0.500, lt 0 linecolor 0 linewidth 0.500
set samples 21, 21
set isosamples 11, 11
set style data lines
set title "3D surface from a function"
set xlabel "X axis"
set xlabel offset character -3, -2, 0 font "" textcolor lt -1 norotate
set xrange [ -10.0000 : 10.0000 ] noreverse nowriteback
set x2range [ * : * ] noreverse writeback
set ylabel "Y axis"
set ylabel offset character 3, -2, 0 font "" textcolor lt -1 rotate
set yrange [ -10.0000 : 10.0000 ] noreverse nowriteback
set y2range [ * : * ] noreverse writeback
set zlabel "Z axis"
set zlabel offset character -5, 0, 0 font "" textcolor lt -1 norotate
set zrange [ * : * ] noreverse writeback
set cbrange [ * : * ] noreverse writeback
set rrange [ * : * ] noreverse writeback
splot x**2+y**2, x**2-y**2, (x**3+y**3)/10
```),
grid.cell(
colspan: 2,
gp.exec(
width: 60%,
```gnuplot
reset
set term svg size 600, 300
set title "Mandelbrot function"
unset parametric
set mapping cartesian
set view 60,30,1,1
set auto
set isosamples 60
set hidden3d
compl(a,b)=a*{1,0}+b*{0,1}
mand(z,a,n) = n<=0 || abs(z)>100 ? 1:mand(z*z+a,a,n-1)+1
splot [-2:1][-1.5:1.5] mand({0,0},compl(x,y),30)
```),
),
),
caption: "surface1.dem",
)
Notice that Typst caches the results for WASM functions:
```typ
#gp.exec("reset") // Will be executed
#gp.exec(kind: "command", "reset") // Will be executed
#gp.exec(kind: "command", "reset;") // Will be executed
#gp.exec("reset") // Won't be executed, returns the cached result
#gp.exec("reset;") // Will be executed
#gp.exec("reset;") // Won't be executed, returns the cached result
```
#figure(
gp.exec(
width: 85%,
```gnuplot
reset
set term svg
set title "Log-scaled axes defined using 'set log'"
set label 1 "This version of the plot uses\nset logscale x\nset logscale y" at graph 0.5, 0.85, 0 center norotate back nopoint
set dummy jw, y
set grid xtics ytics
set key inside center bottom vertical Right noreverse enhanced autotitle box
set style data lines
set xtics border out scale 1,0.5 nomirror
set ytics border out scale 1,0.5 nomirror
set ytics norangelimit 0.1 textcolor rgb "dark-violet"
set y2tics border out scale 1,0.5 nomirror
set y2tics norangelimit autofreq textcolor rgb "#56b4e9"
set xlabel "jw (radians)"
set ylabel "magnitude of A(jw)"
set y2label "Phase of A(jw) (degrees)"
set xrange [ 1.1 : 90000.0 ] noextend
set yrange [ 0.1 : 1.0 ]
set log x
set log y
set ytics nolog
A(jw) = ({0,1}*jw/({0,1}*jw+p1)) * (1/(1+{0,1}*jw/p2))
p1 = 10
p2 = 10000
plot abs(A(jw)) lt 1, 180/pi*arg(A(jw)) axes x1y2 lt 3
```),
caption: "nonlinear2.dem",
)
#figure(
gp.exec(
width: 90%,
```gnuplot
reset
set view 49, 28, 1, 1.48
set urange [ 5 : 35 ] noreverse nowriteback
set vrange [ 5 : 35 ] noreverse nowriteback
set ticslevel 0
set format cb "%4.1f"
set colorbox user size .03, .6 noborder
set cbtics scale 0
set samples 50, 50
set isosamples 50, 50
set title "4D data (3D Heat Map)"\
."\nIndependent value color-mapped onto 3D surface" offset 0,1
set xlabel "x" offset 3, 0, 0
set ylabel "y" offset -5, 0, 0
set label "z" at graph 0, 0, 1.1
set pm3d implicit at s
Z(x,y) = 100. * (sinc(x,y) + 1.5)
sinc(x,y) = sin(sqrt((x-20.)**2+(y-20.)**2))/sqrt((x-20.)**2+(y-20.)**2)
color(x,y) = 10. * (1.1 + sin((x-20.)/5.)*cos((y-20.)/10.))
splot '++' using 1:2:(Z($1,$2)):(color($1,$2)) with pm3d title "4 data columns x/y/z/color"
```),
caption: "heatmaps.dem",
)
#figure(
gp.exec(
width: 85%,
```gnuplot
reset
set sample 300
set yrange [-15:5]
set xrange [-10:2]
set grid x
set xtics 1
set key right center title "lgamma(x)" samplen 0
set multiplot layout 2,1 title "Effect of 'sharpen' filter"
plot lgamma(x) title "no filters"
if (GPVAL_VERSION >= 6.0) {
plot lgamma(x) sharpen title " sharpen"
} else {
set label 1 center at graph 0.5, 0.5 "This copy of gnuplot does not support 'sharpen'"
unset key; plot NaN
}
unset multiplot
```),
caption: "sharpen.dem",
)
Datablock can be used in a script:
#figure(
gp.exec(
width: 90%,
```gnuplot
reset
set title "Change in rank over time"
set title font ":Bold" offset 0,1
$data <<EOD
1 2 3 4 5
1 3 4 2 5
1 3 4 2 5
2 1 4 3 5
1 2 5 3 4
2 1 4 3 5
EOD
set xrange [0.5:6.5]
set yrange [5.5:0.5]
set lmargin 7; set tmargin 5
set border 3
unset key
set tics scale 0 nomirror
set xtics 1,1,6 format "Week %.0g"
set label 1 "Rank " right at graph 0, 1.05
set ytics 1,1,5
set grid xtics
plot for [k=1:6] $data using ($0+1):(column(k)):(0.4) with hsteps link lw 1 lc k, \
for [k=1:6] $data using ($0+1):(column(k)):(0.4) with hsteps nolink lw 6 lc k
```),
caption: "rank_sequence.dem",
)
#figure(
gp.exec(
width: 85%,
```gnuplot
reset
$Data <<EOD
1 一 -30
2 二 -60
3 三 -90
4 四 -120
5 五 -150
6 六 -180
7 七 -210
8 八 -240
9 九 -270
10 十 -300
11 十一 -330
12 十二 -360
EOD
set angle degrees
unset key
set title "variable color and orientation in plotstyle 'with labels'" offset 0,-2
set xrange [0:13]
set yrange [0:13]
set xtics 1,1,12 nomirror
set ytics 1,1,12 nomirror
set border 3
plot $Data using 1:1:2:3:0 with labels rotate variable tc variable font ",20"
```),
caption: "rotate_labels.dem",
)
Read and plot a data file using datablock:
#gp.exec("reset")
#figure(
gp.exec(
width: 85%,
"$data <<EOD\n" +
read("data/silver.dat") +
"EOD\n" +
```gnuplot
set title "Error on y represented by filledcurve shaded region"
set xlabel "Time (sec)"
set ylabel "Rate"
set grid xtics mxtics ytics mytics
set log y
Shadecolor = "#80E0A080"
plot $data using 1:($2+$3):($2-$3) \
with filledcurve fc rgb Shadecolor \
title "Shaded error region", \
'' using 1:2 smooth mcspline lw 2 \
title "Monotonic spline through data"
```.text
),
caption: "errorbars.dem",
)
#figure(
gp.exec(
width: 85%,
```gnuplot
reset
set title "Demo of enhanced text mode using a single UTF-8 encoded font\nThere is another demo that shows how to use a separate Symbol font"
set xrange [-1:1]
set yrange [-0.5:1.1]
set format xy "%.1f"
set arrow from 0.5, -0.5 to 0.5, 0.0 nohead
set label 1 at -0.65, 0.95
set label 1 "Superscripts and subscripts:" tc lt 3
set label 3 at -0.55, 0.85
set label 3 'A_{j,k} 10^{-2} x@^2_k x@_0^{-3/2}y'
set label 5 at -0.55, 0.7
set label 5 "Space-holders:" tc lt 3
set label 6 at -0.45, 0.6
set label 6 "<&{{/=20 B}ig}> <&{x@_0^{-3/2}y}> holds space for"
set label 7 at -0.45, 0.5
set label 7 "<{{/=20 B}ig}> <{x@_0^{-3/2}y}>"
set label 8 at -0.9, -0.2
set label 8 "Overprint\n(v should be centred over d)" tc lt 3
set label 9 at -0.85, -0.4
set label 9 " ~{abcdefg}{0.8v}"
set label 10 at -.40, 0.35
set label 10 "UTF-8 encoding does not require Symbol font:" tc lt 3
set label 11 at -.30, 0.2
set label 11 "{/*1.5 ∫@_{/=9.6 0}^{/=12 ∞}} {e^{-{μ}^2/2} d}{μ=(π/2)^{1/2}}"
set label 21 at 0.5, -.1
set label 21 "Left ^{centered} ƒ(αβγδεζ)" left
set label 22 at 0.5, -.2
set label 22 "Right ^{centered} ƒ(αβγδεζ)" right
set label 23 at 0.5, -.3
set label 23 "Center^{centered} ƒ(αβγδεζ)" center
set label 30 at -.9, 0.0 "{/:Bold Bold} and {/:Italic Italic} markup"
set key title " "
plot sin(x)**2 lt 2 lw 2 title "sin^2(x)"
```),
caption: "enhanced_utf8.dem",
)
#figure(
gp.exec(
width: 85%,
```gnuplot
reset
set view equal xy
set zzeroaxis; set xzeroaxis; set yzeroaxis
set xyplane at 0
unset border
unset key
unset xtics
unset ytics
set ztics axis
set arrow 1 from 0,0,0 to 1,0,0 head filled lw 1.5
set label 1 at 1.2,0,0 "X" center
set arrow 2 from 0,0,0 to 0,1,0 head filled lw 1.5
set label 2 at 0,1.2,0 "Y" center
set arrow 3 from 0,0,0 to 0,0,21 head filled lw 1.5
set label 3 at 0,0,23 "Z" center
set view 60, 30, 1., 1.75
set multiplot layout 1,3
set view azimuth 0.
set title 'azimuth 0' offset 0,2
splot sample [t=0:20] '+' using (cos($1)):(sin($1)):($1) with lines lw 2
set title 'azimuth 10' offset 0,2
set view azimuth 10.
replot
set title 'azimuth 60' offset 0,2
set view azimuth 60.
replot
unset multiplot
```),
caption: "azimuth.dem",
)
#figure(
gp.exec(
width: 90%,
"test",
),
caption: "The current terminal",
)
#figure(
gp.exec(
width: 90%,
"reset; set palette viridis; test palette",
),
caption: "The current palette",
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-rect_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Default rectangle.
#rect()
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/0-base/4-outline.typ | typst | #show outline.entry.where(
level: 1
): it => {
v(16pt, weak: true)
strong(it)
}
#outline(indent: auto, depth: 2, target: heading.where(supplement: [Abschnitt]))
#pagebreak() |
|
https://github.com/T1mVo/shadowed | https://raw.githubusercontent.com/T1mVo/shadowed/main/benchmarks/results.md | markdown | MIT License | # Results
Benchmarks were run on a Apple MacBook Pro 2020 with 8 cores and 16 GB RAM.
| Version | Compiler | Templating | Time |
|:-------:|:------------:|:----------:|:------------:|
| 0.1.0 | 0.11.1 | Rust | 00:00:08.839 |
| 0.1.0 | 0.11.1 | Typst | 00:00:08.942 |
| 0.1.0 | HEAD-92ec566 | Rust | 00:00:00.243 |
| 0.1.0 | HEAD-92ec566 | Typst | 00:00:00.248 |
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/security/bitlocker.typ | typst | #import "template.typ": *
#show: template.with(
title: "BitLocker",
subtitle: "6.566"
)
= Introduction
BitLocker is a feature of of Windows shipped in Vista onward which encrypts all the data on the system volume. The main motivation for BitLocker is to prevent any dangerous interactions when laptops are lost - an event that happens surprisingly frequently.
There are several common attacks that one can use to break into a laptop.
#example(
title: "Ways to break into a laptop"
)[
- Quite simply, you could just take the disk drive out of the laptop and plug it into another device. You can then use root privileges on the second device to access all the files.
- You can run a script on the machine using a USB or other medium, allowing you to reset the Administrator password.
]
The easy solution to this problem is to use encryption on the disk, with a user passphrase / token. However this runs the annoyance that there will be extra work anytime the user attempts to use the machine.
BitLocker improves on this model by preventing the user from having to make extra actions during boot or hibernation. However, this can be defeated with hardware attacks. In general, *hardware* attacks are much more difficult than *software* based attacks, which are more easily distributable and general. The idea is that whatever allows the convenience of not taking actions on boot or hibernate is a physical piece on the laptop that can be recovered with a hardware attack. You can use a PIN or physical USB to prevent this, which BitLocker supports, but again, the average person will most likely refrain from having this extra step of security.
= Trusted Platform Module Chip (TPM)
To understand how BitLocker works, it is critical to understand how the TPM chip works.
The TPM contains several Platform Configuration Registers (PCR), which are special variables initialized to zero on startup, that can only be modified by the `extend` function, which takes a string and sets the PCR to the hash of its old value and the string. Therefore, you can think of the PCR as capturing a sequence of actions into one variable. The only way to get a value is to rewind and reapply the same `extend` calls that led to it.
Thus on boot, computers will track the software that is running with `extend` calls. The end value of this is seen, and then the key is *sealed* with the PCR value ahead of time. Anytime the computer boots, if the software is the same, then we expect to see the same PCR value, and thus we can use the *unseal* functionality of the TPM to decrypt the key. Of course, this means that if the boot code changes, then the PCRs must be recalculated, which leads to a very inflexible system.
BitLocker makes this easier by running as soon as possible on boot, after some relatively unchanged code, then using the PCRs at that point to run the rest of the boot software. This allows for modifications of the boot software without having to constantly redo the PCR hash of the encryption key. We assume that the BitLocker encrypted code for the latter half of the boot is hard to tamper with in a meaningful way.
= Inability for MACs
Although it is unlikely an attack on the ciphertext will lead to a meaningful attack, it is still a concerning vulnerability. We might ask why we can't encrypt sectors with a MAC.
There are two important requirements for BitLocker to consider:
+ Encryption is done in a per-sector basis.
+ The ciphertext cannot be larger than the plaintext.
#define(
title: "Sectors"
)[
Disks store information in fixed size sectors of bytes sizes that are some power of two. Usually this is 512 bytes, but this may grow to 4096 or even 8192 bytes.
]
The constraints both have solid engineering bases. If encryption was to be done on multiple sectors, then we could have a corruption in one sector while writing to a completely unrelated one. This is huge violation for many applications and database systems which rely on the fact that sectors will only corrupt themselves if at all.
Since there is no extra space, it is not possible to add a MAC for each sector, and doubling the sector size just to store a MAC would essentially mean losing half the available space on the disk.
It is also bad to designate a block specifically for MACs since an error in writing a MAC for one sector could corrupt another sectors MAC. Another reason this point wouldn't work is because we want BitLocker to be operable on an already existing disk.
= Poor-man's authentication
Since we can't use authentication our solution is to hope that changes to the ciphertext will not lead to any meaningful changes in the plaintext. We hope that the system or application would crash or stop rather than inflicting some kind of desired attack.
Again, it is possible that you can use an external hardware device that eliminates this weakness, although the disk cipher design is primarily aimed toward the TPM-only case.
= Performance
In order for customers to want to use BitLocker, it must result in no, or very insignificant slowdowns to the system.
It can be shown that this is possible and feasible.
= Attack Model
- The attacker has random ciphertext / plaintext pairs.
- The attacker has chosen ciphertext / plaintext pair. The plaintexts are chosen before the attacker gets access to the laptopl
- The attacker has a slow decryption function for some of the sectors.
- The attacker gets several ciphertexts of plaintexts for the same sector with a known difference.
An attack succeeds when they can modify the ciphertext to produce plaintext with a non-random property.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-selector-01.typ | typst | Other | #show heading.where(level: 1): set text(red)
#show heading.where(level: 2): set text(blue)
#show heading: set text(green)
= Red
== Blue
=== Green
|
https://github.com/Hucy/cv_typst_template | https://raw.githubusercontent.com/Hucy/cv_typst_template/main/README.md | markdown | MIT License | # cv_typst_template
| [zh](./cv_zh.typ) \| [zh_PDF](./cv_zh.pdf) | [en](./cv_en.typ) \| [en_PDF](./cv_en.pdf) |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|  |  |
|
https://github.com/SeniorMars/typst-raytracer | https://raw.githubusercontent.com/SeniorMars/typst-raytracer/main/mandel.typ | typst | #set par(leading:0em)
#let mandelbrot() = {
let red = 0
let green = 0
let blue = 0
let width = 164
let height = 250
let max_iter = 256
let cxmin = -2.0
let cxmax = 1.0
let cymin = -1.5
let cymax = 1.5
let scalex = ((cxmax - cxmin) / width)
let scaley = ((cymax - cymin) / height)
let zx;
let zy;
let zx2;
let zy2;
let yidx = 0
while yidx < height {
let cy = cymin + yidx * scaley
let xidx = 0
while xidx < width {
let cx = cxmin + xidx * scalex
zx = 0.0;
zy = 0.0;
zx2 = zx * zx;
zy2 = zy * zy;
let iter = 0
while iter < max_iter and (zx2 + zy2) < 4.0 {
zy = 2.0 * zx * zy + cy
zx = zx2 - zy2 + cx
zx2 = zx * zx
zy2 = zy * zy
iter += 1
}
red = calc.mod(iter, 4) * 64
green = calc.mod(iter, 8) * 32
blue = calc.mod(iter, 16) * 16
[#box(fill: rgb(red, green, blue), height: 0.25em, width:0.25em)]
xidx += 1
}
[\ ]
yidx += 1
}
}
#mandelbrot()
|
|
https://github.com/EmileVezinaCoulombe/Planner | https://raw.githubusercontent.com/EmileVezinaCoulombe/Planner/main/README.md | markdown | # Personal Planner
This is my daily and weekly planner made with 💖 and [typst](https://typst.app/)


|
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/src/types/logical.typ | typst | Other | #import "../base-type.typ": base-type
#import "../assertions-util.typ": assert-base-type-array
#import "../ctx.typ": z-ctx
/// Valkyrie schema generator for objects that can be any of multiple types.
///
/// -> schema
#let either(
strict: false,
..args,
) = {
assert(
args.pos().len() > 0,
message: "z.either requires 1 or more arguments.",
)
assert-base-type-array(args.pos(), scope: ("arguments",))
base-type(
name: "either",
description: "[" + args.pos().map(it => it.name).join(", ", last: " or ") + "]",
..args.named(),
) + (
strict: strict,
options: args.pos(),
handle-descendents: (self, it, ctx: z-ctx(), scope: ()) => {
for option in self.options {
let ret = (option.validate)(
option,
it,
ctx: z-ctx(ctx, strict: self.strict, soft-error: true),
scope: scope,
)
if ret != none {
return ret
}
}
let message = (
"Type failed to match any of possible options: " + self.options.map(it => it.description).join(
", ",
last: " or ",
) + ". Got " + type(it)
)
return (self.fail-validation)(
self,
it,
ctx: ctx,
scope: scope,
message: message,
)
},
)
}
|
https://github.com/augustebaum/petri | https://raw.githubusercontent.com/augustebaum/petri/main/tests/fletcher/colored-places/test.typ | typst | MIT License | #import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 1cm)
#import "@preview/fletcher:0.4.2" as fletcher
/// % Place 1
/// \node[place,
/// fill=red!25,
/// draw=red!75,
/// tokens=2,
/// label=$P_1$] (place1) at (0,0) {};
///
/// % Place 2
/// \node[place,
/// fill=teal!25,
/// draw=teal!75,
/// tokens=1,
/// label=$P_2$] (place2) at (2,0) {};
///
/// % Place 3
/// \node[place,
/// fill=blue!25,
/// draw=blue!75,
/// tokens=5,
/// label=$P_3$] (place3) at (4,0) {};
#fletcher.diagram(
node-stroke: 0.5pt,
p((0,0), $P_1$, fill: red.lighten(55%), stroke: red.darken(15%), tokens: 2),
p((2,0), $P_2$, fill: teal.lighten(55%), stroke: teal.darken(15%), tokens: 1),
p((4,0), $P_3$, fill: blue.lighten(55%), stroke: blue.darken(15%), tokens: 5),
)
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/mark-math-matching/test.typ | typst | MIT License | #set page(width: 6cm, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher: diagram, node, edge
Compare to $->$, $=>$, $arrow.triple$, $arrow.twohead$, $arrow.hook$, $|->$.
#let (result-color, target-color) = (rgb("f066"), rgb("0bf5"))
#text(result-color)[Our output] versus #text(target-color)[reference symbol] in default math font.
\
#set text(10em)
#diagram(
spacing: 0.825em,
crossing-fill: none,
label-sep: 0.0915em,
edge-stroke: result-color,
for (i, a) in (
("->", $->$,
0em, 0.029),
("=>", $=>$,
0em, 0.02),
("==>", $arrow.triple$,
0em, 0.048),
("->>", $->>$,
0em, 0.053),
("hook->", $arrow.hook$,
0.024em, 0.057),
("|->", $|->$,
0em, 0.004),
).enumerate() {
let (marks, label, δl, δr) = a
edge(
(0, i), (1 + δr,i),
move(dx: δl - 0.28em, text(target-color, label)),
marks: marks,
label-anchor: "west",
label-pos: 0,
)
},
) |
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/lift/decide.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Decide: Lift",
type: "decide",
date: datetime(year: 2024, month: 1, day: 5),
author: "<NAME>",
witness: "Violet Ridge",
)
After identifying our options, we compared the options with a decision matrix.
We rated each choice by the following categories:
- Ease of design and fabrication on a scale of 1 to 5.
- Possible height on a scale of 1 to 5. This is the potential height that the
mechanism could pull the robot up to.
- Reliability and ease of use on a scale of 1 to 5.
#decision-matrix(
properties: (
(name: "Ease of Design and Fabrication"),
(name: "Possible Height"),
(name: "Reliability and Ease of Use"),
),
("Pneumatic Lift", 3, 4, 5),
("Balance Mechanism", 5, 1, 1),
("PTO Lift", 1, 5, 4),
)
#admonition(
type: "decision",
)[
We ended up choosing the pneumatic lift for a variety reasons. It gives us the
right balance of hang tier, along with being relatively easy to build. It can
potentially pull us higher than a balance mechanism could, but it doesn't
require the complex intricacies of a PTO mechanism.
]
= CAD Overview
#grid(
columns: (1fr, 2fr),
gutter: 20pt,
[
== Flywheel
The flywheel sits at the end of the lift, and acts as our shooting mechanism.
The design is exactly the same as the one we had statically mounted to our
robot. It uses a 84:24 gear ratio, with 3" flex wheels. Having the flywheel
mounted like this provides us with the advantage of being able to shoot over
blockers with ease, and provides extra weight to push down on the robot with.
],
image("./flywheel-annotated.png"),
)
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
image("./hang-assist-annotated.png", width: 110%),
[
== Hang Assist
The hang assist is a piece of custom cut plastic that hold the robot in place
once we elevate. It will be laser cut out of acetal. It has a wedge shape on one
side to let the elevation bar slide up into the held position, very similar to
our original passive elevation mechanism.
],
[
== Pistons
Our lift has two pistons, one on each side of the mechanism. These can be
extended or retracted to move the lift up and down.
When the lift is extended, the flywheel can be spun up, and the match loaders
can shoot without being obstructed by opposing robots.
],
figure(image("./extended.png"), caption: "The lift in it's extended state"),
figure(image("./retracted.png"), caption: "The lift in it's retracted state"),
[
When it comes time to lift the robot into the air, the pistons pull down,
pulling the robot upwards. We plan to add rubber bands to assist the pull if the
robot is too heavy for the pistons.
],
)
#image("1.svg")
#image("2.svg")
|
https://github.com/catppuccin/typst | https://raw.githubusercontent.com/catppuccin/typst/main/manual/manual.typ | typst | MIT License | #import "../src/catppuccin.typ": themes, get-palette, config-code-blocks
#import "../src/tidy/styles.typ": get-tidy-colors, show-type as sh-type
#import "../src/tidy/show-module.typ": show-module
#import "template.typ": *
#import "@preview/tidy:0.3.0"
#import "@preview/oxifmt:0.2.1": strfmt
#let version = toml("../typst.toml").package.version
#let theme = sys.inputs.at("flavor", default: themes.mocha)
#let palette = get-palette(theme)
#let show-type(type) = {
let style = (colors: get-tidy-colors(theme: theme))
sh-type(type, style-args: style)
}
#show: project.with(
title: "Catppuccin for Typst",
subtitle: "🪶 Soothing pastel theme for Typst",
authors: ("TimeTravelPenguin",),
abstract: [
The *catppuccin* package provides colourful #link("https://catppuccin.com/", [Catppuccin]) aesthetics
for #link("https://typst.app/", [Typst]) documents. It provides four soothing
pastel themes that is easy on the eyes. This manual provides a detailed
documentation of the package.
],
date: datetime.today().display("[month repr:long] [day], [year]"),
version: version,
url: "https://github.com/catppuccin/typst",
flavor: theme,
)
= Overview
== About
This document provides a detailed documentation of the *catppuccin* package for Typst. Inspired by the #LaTeX #link("https://github.com/catppuccin/latex")[Catppuccin package], this package hopes to make writing in Typst more pleasurable and easy to use.
As someone who has done a lot of #LaTeX, I found myself spending a lot of time writing in dark themes (usually by inverting the document colors). Eventually I found the Catppuccin package for #LaTeX, and I incorporated it into my custom preable to allow me to enable, disable, or configure the enabled theme. When I finished, I would submit my work with the theme disabled, without explicitly removing code!
I have plans for the future of this package, such as added styling and perhaps integration with other packages (if that ever becomes easier to do without making a new package).
== Basic Usage
Using this package is simple. See @usage for an example of how to use the package.
#figure(
caption: "Example usage of the Catppuccin package",
```typ
#import "catppuccin.typ": catppuccin, themes
#show: catppuccin.with(
flavor: themes.mocha,
code-block: true,
code-syntax: true,
)
// The rest of your document
```,
) <usage>
You can disable the theme by commenting out or deleting the show block. Just note that if you are manually accessing palettes via the ```typc get-palette(flavor)``` function, you will need to manually account for those changes. It is planned to make this easier in the future be it though a redesign or simple helper functions.
#pagebreak()
#let show-mod(
namespace,
show-module-name: true,
) = {
let doc = tidy.parse-module(
namespace.contents,
name: namespace.name,
scope: namespace.scope + ("config-code-blocks": config-code-blocks),
preamble: strfmt("#show: config-code-blocks.with(\"{}\")\n", theme),
)
show-module(
doc,
theme: theme,
show-module-name: show-module-name,
)
}
= Modules
#show-mod(
make-namespace(
name: "Catppuccin",
scope: (
"themes": themes,
"get-palette": get-palette,
"show-type": show-type,
),
"catppuccin.typ",
),
)
= Flavors
The Catppuccin package comes with four flavors: *Latte*, *Frappe*, *Macchiato*, and *Mocha*. Each flavor has its own unique color palette that is easy on the eyes. You can choose a flavor by setting the `flavor` parameter in the ```typ catppuccin.with``` function.
In this package, we refer to the dictionary related to each flavor with the type alias #show-type("flavor").
== Flavor Schema
<flavor-schema>
Here we describe the schema for the #show-type("flavor") dictionary. Use ```typc get-palette()``` function to
- *name* #show-type("string") --- The name of the flavor (e.g. Frappé)
- *emoji* #show-type("string") --- The emoji associated with the flavor.
- *order* #show-type("integer") --- The order of the flavor in the Catppuccin lineup.
- *dark* #show-type("boolean") --- Whether the flavor is a dark theme.
- *light* #show-type("boolean") --- Whether the flavor is a light theme.
- *colors* #show-type("dictionary") --- A dictionary of colors used in the flavor. Keys are the color names as a #show-type("string") and values are dictionaries with the following keys:
- *name* #show-type("string") --- The name of the color.
- *order* #show-type("integer") --- The order of the color in the palette.
- *hex* #show-type("string") --- The hex value of the color.
- *rgb* #show-type("string") --- The RGB value of the color.
- *accent* #show-type("boolean") --- Whether the color is an accent color.
#show-mod(
make-namespace(
name: "Flavors",
scope: (
"themes": themes,
"get-palette": get-palette,
),
"flavors.typ",
),
show-module-name: false,
)
#show-mod(make-namespace(name: "Tidy Styles", "tidy/styles.typ", scope: ("themes": themes, "show-type": show-type)))
#show-mod(make-namespace(name: "Version", "version.typ", scope: ("version": version)))
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/justify-hanging-indent.typ | typst | Apache License 2.0 | // Test that combination of justification and hanging indent doesn't result in
// an underfull first line.
---
#set par(hanging-indent: 2.5cm, justify: true)
#lorem(5)
|
https://github.com/TechnoElf/mqt-qcec-diff-thesis | https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-thesis/main/content/implementation/application.typ | typst | #import "@preview/lovelace:0.3.0": pseudocode-list
== QCEC Application Scheme
Based on the lessons learnt from Kaleidoscope, the Myers' algorithm was implemented as an application scheme in @mqt @qcec.
This was accomplished by adding appropriate C++ classes and extending the existing functionality for configuring equivalence checking runs.
=== The `DiffApplicationScheme` Class
In general, @qcec is written in a very flexible manner.
The software enables additional application schemes to be added by inheriting a class called `ApplicationScheme`, that is templated with the current equivalence checking configuration.
This class has a single virtual method which must be implemented, namely the `()` operator.
This method returns a `std::pair` of `usize`, which specifies the number of gates to be applied from the left and right respectively in a single cycle.
As such, the summed up outputs of the method must eventually be equal to the number of gates in either circuit.
The @dd\-based alternating equivalence checker repeatedly calls `operator()` on the chosen application scheme and passes the result to two `TaskManager` instances using the `advance()` method.
These each have a reference to a different quantum circuit.
Both also have a reference to a single `DDPackage`, which holds a representation of the current @dd.
The `advance()` method then applies the specified number of gates from the respective circuit to the `DDPackage`.
One of the `TaskManager`s is configured to apply the inverse of each gate in reverse order, thereby implementing the alternating equivalence checking approach.
When the circuits are equivalent and the application scheme has applied all gates, the `DDPackage` holds a representation of the identity after this process.
A class named `DiffApplicationScheme` implements the adaptation of edit script calculation into @qcec.
The diff itself is calculated in the constructor and cached, in order to speed up the equivalence checking flow.
The implementation of `operator()` then returns the value contained in the cache based on an index that is incremented with each call.
This ensures that the entire edit script is eventually returned to the `DDAlternatingChecker` and that all gates in the two circuits are applied.
@diff_appl_scheme_class outlines the structure of this class.
#figure(
block(
pseudocode-list[
+ *class* $"DiffApplicationScheme"$
+ $"editScript"$ is a list of pairs
+ $"counter"$ is a positive integer
+ *def* $"init"(a, b)$
+ $"editScript" = "myersDiff"(a, b)$
+ $"counter" = 0$
+ *end*
+ *def* $"operator()"()$
+ *return* $"getNextOperation"()$
+ *end*
+ *def* $"getNextOperation"()$
+ *if* $"counter" <$ length of $"editScript"$
+ $"counter" "+=" 1$
+ *return* $"editScript"["counter" - 1]$
+ *else*
+ *return* $(0, 0)$
+ *end*
+ *end*
+ *end*
],
width: 100%
),
caption: [The Structure of the `DiffApplicationScheme` class.]
) <diff_appl_scheme_class>
The calculation of the diff itself is performed by a method named `myersDiff()`.
It calls another method named `myersDiffRecursive()` implementing the algorithm as discussed in the previous sections with appropriate parameters to retrieve a full edit script of the two circuits.
Furthermore, it performs post processing of the edit script to make it suitable for use with the `operator()`.
The patience diff algorithm was also implemented in a method named `patienceDiff()` that had a structure analogous to `myersDiff()`.
This method is not used by the `DiffApplicationScheme` however, as the results were found to be very similar to that of `myersDiff()`.
#pagebreak()
=== Configuration Changes
Besides adding the class for the diff-based application scheme, other areas of the @qcec code needed adjustment to integrate it into the codebase.
For instance, the `ApplicationSchemeType` enum and its utility functions were extended to allow representation of the new class.
Additionally, the `DDEquivalenceChecker` class had to be extended with a special case for the `DiffApplicationScheme`.
Compared to the other application schemes, it has the unique requirement of needing access to a representation of both circuits in their entirety.
This was solved by simply passing references to the `TaskManager`s, which the `DDEquivalenceChecker` owns, to the `DiffApplicationScheme` when it is constructed.
This approach is sound as the application scheme instance is also owned by the `DDEquivalenceChecker`.
=== Tests
Testing of software is vital to ensure its functionality while being maintained by multiple people over long periods of time.
@qcec provides facilities for automating this process and indeed performs these checks on each new contribution to the code.
To ensure the functionality of the diff application scheme in the same manner, tests were added covering these new code paths.
Specifically, the `SimpleCircuitIdentitiesTest` was extended with a diff-based configuration.
This test ensures that the equivalence checker works for 8 simple circuit pairs.
While this does not ensure the correctness of the generated edit scripts, it performs well as a sanity check for the functionality of the application scheme.
For the test to pass, the sum of the output of the application scheme must cover both circuits in their entirety, thus ensuring a minimum level of functionality.
|
|
https://github.com/HFU-CV-projects/typst-template | https://raw.githubusercontent.com/HFU-CV-projects/typst-template/main/README.md | markdown | # typst-template
A template to write the thesis with typst.
- You can use Typst in the browser: https://typst.app/
- Or as extension in VSCode: https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp
- You can translate your Latex-Project in Typst at https://typst.app/ ("Start from Template -> Start from a file)
- Typst is turing complete and good for scientific work
- Typst has no Compiling time like in Latex (in browser)
|
|
https://github.com/dyc3/senior-design | https://raw.githubusercontent.com/dyc3/senior-design/main/poster.typ | typst | #import "@preview/fletcher:0.4.2" as fletcher: node, edge
#import "@preview/t4t:0.3.2": *
#import "@preview/cades:0.3.0": qr-code
#let stevens-red = rgb(160, 1, 42)
#let stevens-gray = rgb(127, 129, 130)
#set par(
justify: true,
leading: 0.60em,
)
#set page(
footer: [
#set align(horizon)
#line(length: 100%, stroke: stevens-gray + 3pt)
#stack(
dir: ltr,
image("expo/branding/stevens-logo.svg", width: 7.25in - 1.25in),
h(1fr),
image("expo/branding/expo-logo.svg", width: 22.88in - 15.75in)
)
],
width: 24in,
height: 36in,
margin: (
rest: 1in,
bottom: 4in,
),
)
#set text(
size: 30pt,
font: "Saira",
)
#set figure(supplement: none)
#show heading.where(level: 1): it => [
#set text(
size: 135pt,
weight: 600,
fill: stevens-red,
stretch: 75%,
)
#block(smallcaps(it.body))
]
#show heading.where(level: 2): it => [
#set align(center)
#set text(
size: 48pt,
weight: "bold",
fill: stevens-red,
)
#block(smallcaps(it.body))
]
#let icon(icon, subicon: none, size: 4in, label: none) = {
let width = size
let height = size
if type(size) == array {
width = size.at(0)
height = size.at(1)
}
box(
width: width,
height: height,
)[
#image(
icon,
width: 100%,
height: 100%
)
#if subicon != none {
place(
bottom + right,
dx: 0.3in,
dy: 0.3in,
)[
#circle(
fill: white,
width: width / 2,
height: width / 2,
stroke: none,
place(
center + horizon,
image(
subicon,
width: width / 2,
height: width / 2
)
)
)
]
}
#if label != none {
set align(center + horizon)
set text(size: width / 8)
label
}
]
}
#let server(status_icon, size: 4in, label: none) = {
icon(
"expo/icons/dns.svg",
subicon: status_icon,
size: size,
label: label,
)
}
#let server-on-fire = server("expo/icons/emergengy-heat.svg", size: 2.5in, label: [Application])
#let server-healthy = server("expo/icons/check-circle.svg", size: 1.5in, label: [Application])
#let server-balancer = server("expo/icons/balance.svg", size: 2in, label: [Load Balancer])
#let users = icon("expo/icons/groups.svg", size: (2.5in, 1.5in), label: [Lots of Users])
#let spread-edges(count, width: 0.4, offset: 0) = {
range(count).map(i => {
let y = offset + math.lerp(-width/2, width/2, i / (count - 1))
edge((0, y), (1, y), "-|>")
})
}
#let users-outset = 0.3in
#let draw-single() = {
fletcher.diagram(
edge-stroke: 0.1in,
spacing: 3in,
mark-scale: 65%,
node((0, 0), [#users], outset: users-outset, shape: rect),
..spread-edges(4, width: 0.3),
node((1, 0), [#server-on-fire], shape: rect),
)
}
#let draw-balanced() = {
fletcher.diagram(
edge-stroke: 0.1in,
spacing: (3in, 0in),
mark-scale: 65%,
node((0, 1), [#users], outset: users-outset, shape: rect),
..spread-edges(4, width: 0.7, offset: 1),
node((1, 1), [#server-balancer], outset: 0.3in, shape: rect),
edge((1, 1), (2, 0), "-|>", bend: 20deg),
edge((1, 1), (2, 1), "-|>"),
edge((1, 1), (2, 2), "-|>", bend: -20deg),
node((2, 0), server-healthy, shape: rect),
node((2, 1), server-healthy, shape: rect),
node((2, 2), server-healthy, shape: rect),
)
}
#let ott = icon("expo/icons/ott-logo.svg", size: 2in, label: [OTT])
#let tv = icon("expo/icons/live-tv.svg", size: 1in)
#let person = icon("expo/icons/person.svg", size: 1in)
#let draw-ott() = {
set text(size: 24pt)
let people = range(3).map(i => (i, 1))
let diag = fletcher.diagram(
edge-stroke: 0.05in,
spacing: (0.25in, 1.5in),
mark-scale: 50%,
node-inset: 0in,
node((1, 0), [#ott]),
..people.map(p => node(p, [
#stack(tv, person, spacing: 0in)
])),
..people.map(p => edge(p, (1, 0), "<|-|>",
label: [Sync],
label-fill: white,
label-anchor: "center",
)),
)
box(
stroke: black + 4pt,
inset: 0.5in,
diag,
)
}
#let draw-horizontal-vs-vertical() = {
set text(size: 24pt)
set align(horizon + center)
let server-little = icon("expo/icons/dns.svg", size: 1in)
let server-big = icon("expo/icons/dns.svg", size: 1.8in)
let vertical = fletcher.diagram(
edge-stroke: 0.05in,
spacing: 1.5in,
mark-scale: 50%,
node((0, 0), [#server-little], shape: rect),
edge((0, 0), (1, 0), "-|>", label: [Scale Up]),
node((1, 0), [#server-big], shape: rect),
)
let horizontal = fletcher.diagram(
edge-stroke: 0.05in,
spacing: 1.5in,
mark-scale: 50%,
node((0, 0), [#server-little], shape: rect),
edge((0, 0), (1, 0), "-|>", label: [Scale Up]),
..range(3).map(i => {
let y = math.lerp(-0.5, 0.5, i / 2)
node((1, y), [#server-little], shape: rect)
}),
..range(3).map(i => {
let y = math.lerp(-0.5, 0.5, i / 2)
node((1.5, y), [#server-little], shape: rect)
}),
)
stack(
dir: ltr,
h(1fr),
figure(
vertical,
caption: figure.caption([Vertical Scaling], position: top)
),
h(1fr),
figure(
horizontal,
caption: figure.caption([Horizontal Scaling], position: top)
),
h(1fr),
)
}
#align(
horizon,
stack(dir: ltr,
heading([OTT Load Balancer]),
h(1fr),
// TODO: maybe have this point to something we can change the redirect of later
qr-code(width: 135pt, color: stevens-red, "https://expo.opentogethertube.com"),
)
)
#align(
horizon,
stack(
dir: ltr,
line(length: 100% - 1in, stroke: stevens-red + 3pt),
h(0.2in),
image("expo/branding/stevens-star.svg", width: 0.8in)
)
)
#text(
size: 48pt,
)[
*<NAME>, <NAME>, <NAME>, <NAME>* \
Software Engineering Department, Advised by Prof. <NAME>
]
#grid(
rows: (auto, auto),
row-gutter: 0.5in,
columns(2)[
== Unlocking Scalability for Stateful Applications
- Our project's goal is to build a load balancer for stateful applications to allow legacy systems to scale horizontally.
- Horizontal scaling refers to adding additional nodes, while vertical scaling is adding more power to current machines.
- OTT's userbase is steadily expanding, and the current infrastructure is incapable of accommodating the anticipated growth. Horizontal scaling is not possible due to the applications' stateful nature.
#draw-horizontal-vs-vertical()
#colbreak()
== Proof of Concept (OTT)
- OpenTogetherTube (OTT) is a website that allows users to watch videos together.
- Implementation of the load balancer will allow an application to be deployed around the world, lower latency for users, improve reliability, and allow for a larger number of simultaneous users.
- The load balancer allows for the allocation of rooms across multiple servers, preserving the seamless synchronization of state to users anywhere in the world.
#figure(
draw-ott(),
caption: figure.caption([Users in a Room watching a video], position: top)
)
],
[
#set align(center)
#text(size: 40pt, [Before])
#draw-single()
#text(size: 40pt, [After])
#draw-balanced()
],
)
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/014.%20power.html.typ | typst | #set page(
paper: "a5",
margin: (x: 1.8cm, y: 1.5cm),
)
#set text(
font: "Liberation Serif",
size: 10pt,
hyphenate: false
)
#set par(justify: true)
#set quote(block: true)
#v(10pt)
= Succinctness is Power
#v(10pt)
_May 2002_
#quote(attribution: [<NAME>, quoted in Iverson's Turing Award Lecture ])[
"The quantity of meaning compressed into a small space by algebraic signs, is another circumstance that facilitates the reasonings we are accustomed to carry on by their aid."
]
In the discussion about issues raised by Revenge of the Nerds on the LL1 mailing list, <NAME> wrote something that stuck in my mind.
#quote[Python's goal is regularity and readability, not succinctness.]
On the face of it, this seems a rather damning thing to claim about a programming language. As far as I can tell, succinctness = power. If so, then substituting, we get
#quote[Python's goal is regularity and readability, not power.]
and this doesn't seem a tradeoff (if it _is_ a tradeoff) that you'd want to make. It's not far from saying that Python's goal is not to be effective as a programming language.
Does succinctness = power? This seems to me an important question, maybe the most important question for anyone interested in language design, and one that it would be useful to confront directly. I don't feel sure yet that the answer is a simple yes, but it seems a good hypothesis to begin with.
== Hypothesis
My hypothesis is that succinctness is power, or is close enough that except in pathological examples you can treat them as identical.
It seems to me that succinctness is what programming languages are _for_. Computers would be just as happy to be told what to do directly in machine language. I think that the main reason we take the trouble to develop high-level languages is to get leverage, so that we can say (and more importantly, think) in 10 lines of a high-level language what would require 1000 lines of machine language. In other words, the main point of high-level languages is to make source code smaller.
If smaller source code is the purpose of high-level languages, and the power of something is how well it achieves its purpose, then the measure of the power of a programming language is how small it makes your programs.
Conversely, a language that doesn't make your programs small is doing a bad job of what programming languages are supposed to do, like a knife that doesn't cut well, or printing that's illegible.
== Metrics
Small in what sense though? The most common measure of code size is lines of code. But I think that this metric is the most common because it is the easiest to measure. I don't think anyone really believes it is the true test of the length of a program. Different languages have different conventions for how much you should put on a line; in C a lot of lines have nothing on them but a delimiter or two. Another easy test is the number of characters in a program, but this is not very good either; some languages (Perl, for example) just use shorter identifiers than others.
I think a better measure of the size of a program would be the number of elements, where an element is anything that would be a distinct node if you drew a tree representing the source code. The name of a variable or function is an element; an integer or a floating-point number is an element; a segment of literal text is an element; an element of a pattern, or a format directive, is an element; a new block is an element. There are borderline cases (is -5 two elements or one?) but I think most of them are the same for every language, so they don't affect comparisons much.
This metric needs fleshing out, and it could require interpretation in the case of specific languages, but I think it tries to measure the right thing, which is the number of parts a program has. I think the tree you'd draw in this exercise is what you have to make in your head in order to conceive of the program, and so its size is proportionate to the amount of work you have to do to write or read it.
== Design
This kind of metric would allow us to compare different languages, but that is not, at least for me, its main value. The main value of the succinctness test is as a guide in designing languages. The most useful comparison between languages is between two potential variants of the same language. What can I do in the language to make programs shorter?
If the conceptual load of a program is proportionate to its complexity, and a given programmer can tolerate a fixed conceptual load, then this is the same as asking, what can I do to enable programmers to get the most done? And that seems to me identical to asking, how can I design a good language?
(Incidentally, nothing makes it more patently obvious that the old chestnut "all languages are equivalent" is false than designing languages. When you are designing a new language, you're constantly comparing two languages -- the language if I did x, and if I didn't -- to decide which is better. If this were really a meaningless question, you might as well flip a coin.)
Aiming for succinctness seems a good way to find new ideas. If you can do something that makes many different programs shorter, it is probably not a coincidence: you have probably discovered a useful new abstraction. You might even be able to write a program to help by searching source code for repeated patterns. Among other languages, those with a reputation for succinctness would be the ones to look to for new ideas: Forth, Joy, Icon.
== Comparison
The first person to write about these issues, as far as I know, was <NAME> in the Mythical Man Month. He wrote that programmers seemed to generate about the same amount of code per day regardless of the language. When I first read this in my early twenties, it was a big surprise to me and seemed to have huge implications. It meant that (a) the only way to get software written faster was to use a more succinct language, and (b) someone who took the trouble to do this could leave competitors who didn't in the dust.
Brooks' hypothesis, if it's true, seems to be at the very heart of hacking. In the years since, I've paid close attention to any evidence I could get on the question, from formal studies to anecdotes about individual projects. I have seen nothing to contradict him.
I have not yet seen evidence that seemed to me conclusive, and I don't expect to. Studies like <NAME>'s comparison of programming languages, while generating the kind of results I expected, tend to use problems that are too short to be meaningful tests. A better test of a language is what happens in programs that take a month to write. And the only real test, if you believe as I do that the main purpose of a language is to be good to think in (rather than just to tell a computer what to do once you've thought of it) is what new things you can write in it. So any language comparison where you have to meet a predefined spec is testing slightly the wrong thing.
The true test of a language is how well you can discover and solve new problems, not how well you can use it to solve a problem someone else has already formulated. These two are quite different criteria. In art, mediums like embroidery and mosaic work well if you know beforehand what you want to make, but are absolutely lousy if you don't. When you want to discover the image as you make it -- as you have to do with anything as complex as an image of a person, for example -- you need to use a more fluid medium like pencil or ink wash or oil paint. And indeed, the way tapestries and mosaics are made in practice is to make a painting first, then copy it. (The word "cartoon" was originally used to describe a painting intended for this purpose).
What this means is that we are never likely to have accurate comparisons of the relative power of programming languages. We'll have precise comparisons, but not accurate ones. In particular, explicit studies for the purpose of comparing languages, because they will probably use small problems, and will necessarily use predefined problems, will tend to underestimate the power of the more powerful languages.
Reports from the field, though they will necessarily be less precise than "scientific" studies, are likely to be more meaningful. For example, <NAME> of Ericsson did a study that concluded that Erlang was 4-10x more succinct than C++, and proportionately faster to develop software in:
#quote[Comparisons between Ericsson-internal development projects indicate similar line/hour productivity, including all phases of software development, rather independently of which language (Erlang, PLEX, C, C++, or Java) was used. What differentiates the different languages then becomes source code volume.]
The study also deals explictly with a point that was only implicit in Brooks' book (since he measured lines of debugged code): programs written in more powerful languages tend to have fewer bugs. That becomes an end in itself, possibly more important than programmer productivity, in applications like network switches.
== The Taste Test
Ultimately, I think you have to go with your gut. What does it feel like to program in the language? I think the way to find (or design) the best language is to become hypersensitive to how well a language lets you think, then choose/design the language that feels best. If some language feature is awkward or restricting, don't worry, you'll know about it.
Such hypersensitivity will come at a cost. You'll find that you can't stand programming in clumsy languages. I find it unbearably restrictive to program in languages without macros, just as someone used to dynamic typing finds it unbearably restrictive to have to go back to programming in a language where you have to declare the type of every variable, and can't make a list of objects of different types.
I'm not the only one. I know many Lisp hackers that this has happened to. In fact, the most accurate measure of the relative power of programming languages might be the percentage of people who know the language who will take any job where they get to use that language, regardless of the application domain.
== Restrictiveness
I think most hackers know what it means for a language to feel restrictive. What's happening when you feel that? I think it's the same feeling you get when the street you want to take is blocked off, and you have to take a long detour to get where you wanted to go. There is something you want to say, and the language won't let you.
What's really going on here, I think, is that a restrictive language is one that isn't succinct enough. The problem is not simply that you can't say what you planned to. It's that the detour the language makes you take is longer. Try this thought experiment. Suppose there were some program you wanted to write, and the language wouldn't let you express it the way you planned to, but instead forced you to write the program in some other way that was _shorter_. For me at least, that wouldn't feel very restrictive. It would be like the street you wanted to take being blocked off, and the policeman at the intersection directing you to a shortcut instead of a detour. Great!
I think most (ninety percent?) of the feeling of restrictiveness comes from being forced to make the program you write in the language longer than one you have in your head. Restrictiveness is mostly lack of succinctness. So when a language feels restrictive, what that (mostly) means is that it isn't succinct enough, and when a language isn't succinct, it will feel restrictive.
== Readability
The quote I began with mentions two other qualities, regularity and readability. I'm not sure what regularity is, or what advantage, if any, code that is regular and readable has over code that is merely readable. But I think I know what is meant by readability, and I think it is also related to succinctness.
We have to be careful here to distinguish between the readability of an individual line of code and the readability of the whole program. It's the second that matters. I agree that a line of Basic is likely to be more readable than a line of Lisp. But a program written in Basic is going to have more lines than the same program written in Lisp (especially once you cross over into Greenspunland). The total effort of reading the Basic program will surely be greater.
```
total effort = effort per line x number of lines
```
I'm not as sure that readability is directly proportionate to succinctness as I am that power is, but certainly succinctness is a factor (in the mathematical sense; see equation above) in readability. So it may not even be meaningful to say that the goal of a language is readability, not succinctness; it could be like saying the goal was readability, not readability.
What readability-per-line does mean, to the user encountering the language for the first time, is that source code will look unthreatening. So readability-per-line could be a good marketing decision, even if it is a bad design decision. It's isomorphic to the very successful technique of letting people pay in installments: instead of frightening them with a high upfront price, you tell them the low monthly payment. Installment plans are a net lose for the buyer, though, as mere readability-per-line probably is for the programmer. The buyer is going to make a lot of those low, low payments; and the programmer is going to read a lot of those individually readable lines.
This tradeoff predates programming languages. If you're used to reading novels and newspaper articles, your first experience of reading a math paper can be dismaying. It could take half an hour to read a single page. And yet, I am pretty sure that the notation is not the problem, even though it may feel like it is. The math paper is hard to read because the ideas are hard. If you expressed the same ideas in prose (as mathematicians had to do before they evolved succinct notations), they wouldn't be any easier to read, because the paper would grow to the size of a book.
== To What Extent?
A number of people have rejected the idea that `succinctness = power`. I think it would be more useful, instead of simply arguing that they are the same or aren't, to ask: to what extent does `succinctness = power`? Because clearly succinctness is a large part of what higher-level languages are for. If it is not all they're for, then what else are they for, and how important, relatively, are these other functions?
I'm not proposing this just to make the debate more civilized. I really want to know the answer. When, if ever, is a language too succinct for its own good?
The hypothesis I began with was that, except in pathological examples, I thought succinctness could be considered identical with power. What I meant was that in any language anyone would design, they would be identical, but that if someone wanted to design a language explicitly to disprove this hypothesis, they could probably do it. I'm not even sure of that, actually.
== Languages, not Programs
We should be clear that we are talking about the succinctness of languages, not of individual programs. It certainly is possible for individual programs to be written too densely.
I wrote about this in _On Lisp_. A complex macro may have to save many times its own length to be justified. If writing some hairy macro could save you ten lines of code every time you use it, and the macro is itself ten lines of code, then you get a net saving in lines if you use it more than once. But that could still be a bad move, because macro definitions are harder to read than ordinary code. You might have to use the macro ten or twenty times before it yielded a net improvement in readability.
I'm sure every language has such tradeoffs (though I suspect the stakes get higher as the language gets more powerful). Every programmer must have seen code that some clever person has made marginally shorter by using dubious programming tricks.
So there is no argument about that -- at least, not from me. Individual programs can certainly be too succinct for their own good. The question is, can a language be? Can a language compel programmers to write code that's short (in elements) at the expense of overall readability?
One reason it's hard to imagine a language being too succinct is that if there were some excessively compact way to phrase something, there would probably also be a longer way. For example, if you felt Lisp programs using a lot of macros or higher-order functions were too dense, you could, if you preferred, write code that was isomorphic to Pascal. If you don't want to express factorial in Arc as a call to a higher-order function
```lisp
(rec zero 1 * 1-)
```
you can also write out a recursive definition:
```lisp
(rfn fact (x) (if (zero x) 1 (* x (fact (1- x)))))
```
Though I can't off the top of my head think of any examples, I am interested in the question of whether a language could be too succinct. Are there languages that force you to write code in a way that is crabbed and incomprehensible? If anyone has examples, I would be very interested to see them.
_(Reminder: What I'm looking for are programs that are very dense according to the metric of "elements" sketched above, not merely programs that are short because delimiters can be omitted and everything has a one-character name.)_
== Responses
- <NAME>: Comparison of Seven Languages
- Erann Gat: Lisp vs. Java
- <NAME> <NAME>'s Test
- <NAME>: Expressive Power of Languages
- Kragen Sitaker: Redundancy and Power
- Forth
- Joy
- Icon
- J
- K
|
|
https://github.com/jijinbei/typst_template | https://raw.githubusercontent.com/jijinbei/typst_template/main/manual/README.md | markdown | # 取扱説明書テンプレート
## インストール方法
> git clone https://github.com/jijinbei/typst_template.git (dirname)
でクローンする。
dirnameを好きなファイル名に
## 注意
デフォルトのフォントは`Noto Sans JP`と`Kosugi Maru`を用いているので、それらをインストールをしてください
|
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Insiemi/Insiemi.typ | typst | Creative Commons Zero v1.0 Universal | Sia $NN$ un insieme e sia $S$ una funzione. Si supponga che per $NN$ ed $S$
siano rispettati i seguenti cinque assiomi, detti *Assiomi di Peano*:
+ Esiste un elemento, chiamato $0$, che appartiene ad $NN$;
+ Per ogni elemento $n in NN$, esiste un $S(n)$ a sua volta membro di $NN$.
Ovvero, $NN$ é un insieme chiuso rispetto ad $S$;
+ Per ogni coppia di elementi $m, n in NN$, se vale $S(m) = S(n)$ allora
$m = n$. Ovvero, $S$ é una funzione iniettiva;
+ Per qualsiasi elemento $n in NN$, la proposizione $S(n) = 0$ é sempre falsa.
+ Se $T$ é un insieme che possiede le seguenti proprietá:
+ $0$ appartiene a $T$;
+ Per ogni elemento $t in T$, esiste un $S(t)$ a sua volta membro di $T$;
Allora $T$ e $NN$ sono lo stesso insieme.
L'insieme $NN$ cosí definito prende il nome di *insieme dei numeri naturali*.
// Aggiungere la definizione di $ZZ$
// Aggiungere la definizione di $QQ$
// Aggiungere la definizione di $RR$
|
https://github.com/N4tus/uf_algo | https://raw.githubusercontent.com/N4tus/uf_algo/main/style_base.typ | typst | MIT License | #import "types.typ": *
#let _ex_style(name, elem, styler, pred) = {
let ex_style = (elem, makeup) => {
let style = if t_check(TMakeup, makeup) {
makeup.style
} else {
makeup
}
if type(style) == "string" {
panic(sytle)
}
if name != none and name in style {
styler(elem, style)
} else {
panic("missing '" + name + "' in style definition")
}
}
let precedence = makeup => {
let style = if t_check(TMakeup, makeup) {
makeup.style
} else {
makeup
}
if name != none and name in style {
pred(style)
} else {
panic("missing '" + name + "' in style definition")
}
}
let style = (fn: ex_style, precedence: precedence)
if t_check(TElem, elem) {
elem.styles.push(style)
elem
} else if type(elem) == "array" {
elem.flatten().map(e => if t_check(TElem, e) {
e.styles.push(style)
e
} else {
(value: e, styles: (style,))
})
} else {
(value: elem, styles: (style,))
}
}
#let _choose_styler(style, names, def_fmt, style_name) = {
let s = style
let style_stack = ()
for name in names {
if name in s {
s = s.at(name)
style_stack.push(s)
} else {
break
}
}
while style_stack.len() > 0 {
let style = style_stack.pop()
if style_name in style {
return style.at(style_name)
}
}
def_fmt
}
#let elem(value, ..names, style: none, style_name: "style") = _ex_style(
names.pos().at(0),
value,
(elem, _style) => {
let default_styler = if style != none { style } else { i=>repr(i) }
let styler = _choose_styler(_style, names.pos(), default_styler, style_name)
styler(elem)
},
style => _choose_styler(style, names.pos(), 0, "precedence")
)
#let eval_line(elem, makeup) = elem.flatten().map(e =>
if t_check(TElem, e) {
if e.styles.len() == 0 {
e.value
} else {
let first_style = e.styles.at(0)
let ex_prec = first_style.precedence
let acc = (fn: first_style.fn, prec: ex_prec(makeup))
let chosen_style = e.styles.slice(1).fold(acc, (acc, style_def) => {
let ex_precedence = style_def.precedence
let precedence = ex_precedence(makeup)
if precedence > acc.prec {
(fn: style_def.fn, prec: precedence)
} else {
acc
}
})
let styler = chosen_style.fn
if t_check(TGroupStart, e.value) {
(start_style: v => styler(v, makeup.style), ..e.value)
} else if t_check(TGroupEnd, e.value) {
(end_style: v => styler(v, makeup.style), ..e.value)
} else {
styler(e.value, makeup)
}
}
} else {
e
}
)
#let sp = " "
#let join(elems, sep) = if elems.len() == 0 {()} else if elems.len() == 1 { elems.at(0) } else { range(elems.len()*2-1).map(i => if calc.even(i) {elems.at(int(i/2))} else {sep}) }
#let ge = (value: (group: none), styles: ())
#let gs(fn, use_start: false, use_end: false) = (value: (group: fn, use_start: use_start, use_end: use_end), styles: ())
#let pipe(..fns) = s => {
let _s = s
for fn in fns.pos() {
let r = fn(_s)
// first element, if successful, second the value
if type(r) == "array" {
// if successful, stop otherwise continue
if r.at(0) {
return r.at(1)
}
} else {
_s = r
}
}
_s
}
#let _if(cond, ..fns) = s => {
if cond(s) {
let p = pipe(..fns)
p(s)
} else {
s
}
}
#let _if_else(cond, ..fns) = s => {
if cond(s) {
let p = pipe(..fns)
(true, p(s))
} else {
(false, none)
}
}
#let if_string(..fns) = _if(s => type(s) == "string", ..fns)
#let if_number(..fns) = _if(s => type(s) == "integer" or type(s) == "float", ..fns)
#let if_string_else(..fns) = _if_else(s => type(s) == "string", ..fns)
#let if_number_else(..fns) = _if_else(s => type(s) == "integer" or type(s) == "float", ..fns)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/typst.vue3/README.md | markdown | Apache License 2.0 | # Typst.vue3 [WIP]
This is a basic vue component for rendering typst documents.
## Installation
```bash
yarn add @myriaddreamin/typst.ts
yarn add @myriaddreamin/typst.vue3
```
## Usage
First, set path to wasm files:
```ts
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';
$typst.setCompilerInitOptions({
beforeBuild: [],
getModule: () =>
'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm',
});
$typst.setRendererInitOptions({
beforeBuild: [],
getModule: () =>
'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm',
});
```
Next, use the component:
```vue
<template>
<Typst v-bind:content="sourceCode" />
</template>
```
## Documentation
See [Vue3 Library Docs](https://myriad-dreamin.github.io/typst.ts/cookery/guide/renderer/vue3.html).
## Development
Run the example project:
```bash
# At the root of the project, run the typst-ts-dev-server, serving local wasm files.
yarn dev
# In another terminal, run the example project.
cd packages/typst.vue3 && yarn dev
```
|
https://github.com/yongweiy/cv | https://raw.githubusercontent.com/yongweiy/cv/master/honors.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry
#let metadata = toml("./metadata.toml")
#let cvSection = cvSection.with(metadata: metadata, highlighted: false)
#let cvEntry = cvEntry.with(metadata: metadata)
#cvSection("Honors and Awards")
#list(
[Merit Recognition Award 2024, Purdue University],
[*OOPSLA 2023 Distinguished Paper Award*, ACM SIGPLAN],
[*PLDI 2023 Distinguished Paper Award*, ACM SIGPLAN],
[Honorable Mention, Mathematical Contest in Modeling 2017],
)
|
|
https://github.com/GYPpro/Java-coures-report | https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/Report/9.typ | typst | #set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#set page(
paper:"a4",
number-align: right,
margin: (x:2.54cm,y:4cm),
header: [
#set text(
size: 25pt,
font: "KaiTi",
)
#align(
bottom + center,
[ #strong[暨南大学本科实验报告专用纸(附页)] ]
)
#line(start: (0pt,-5pt),end:(453pt,-5pt))
]
)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
= 实现对网络最大流与最小费用流问题的solution类
\
#text("*") 实验项目类型:设计性\
#text("*")此表由学生按顺序填写\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 面向对象程序设计/JAVA语言 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" 实现对网络最大流与最小费用流问题的solution类 ")]\ 指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 1 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2023年11月1日上午 ")]#text("~")#underline[#text(" 2023年11月1日中午 ")]\
]
#set heading(
numbering: "一、"
)
#set par( first-line-indent: 1.8em)
= 实验目的
\
#h(1.8em)熟悉ArrayList、PriorityQueue、LinkedList等java.util提供的接口与类库,并且利用它们解决实际问题。
= 实验环境
\
#h(1.8em)计算机:PC X64
操作系统:Windows
编程语言:JAVA
IDE:Visual Studio Code
= 程序原理
\
#h(1.8em)
对于最小费用最大流问题,首先给出问题定义:
给定一个网格$G eq lr((V comma E))$,每条边除了有容量限制$c lr((u comma v))$,还有单位流量费用$w lr((u comma v))$。
当$lr((u comma v))$的流量为$f lr((u comma v))$时,需要花费$w lr((u comma v)) times f lr((u comma v))$的费用。
$w$满足斜对称性,即$w lr((u comma v)) eq minus w lr((u comma v))$。
该网络图中总花费最小的最大流则为最小费用最大流,即在最大化$sum_(lr((s comma u)) in E)^() f lr((s comma u))$的前提下最小化$sum_(lr((s comma u)) in E)^() f lr((s comma u)) times w lr((u comma v))$。
此问题我们可以用PD算法(即$P e i m a l minus D u a l$原始对偶算法)在$O lr((m n plus m l o g m f))$内解决。
PD的总体思路为首先利用SPFA算法(队列优化的$B e l l m a n minus F o r d$最短路算法)为每个节点设置一个$p o t e n t i a l med h_u$
用于将所有节点的权值转为非负数使得后续增广路计算时可以运用$D i j k s t r a med$算法解决。
由于$J o h n s o n med$算法的正确性,我们可以类比地证明设置了势能的新网络上最短路与原网络一一对应。
每次求得增广边后增广图形态会产生变化,因此需要更新各个节点的势能。
设增广后源点到第$i$个节点的最短距离记为$d_i$,只需给对应的$p o t e n t i a l med h_i$加上$d_i$即可。
由于对于任意次增广后的残量网络,有$d_i^prime plus lr((w lr((i comma j)) plus h_i minus h_j)) eq d_j prime$,即新增的边权也是非负的。
接下来的思路与$S S P$算法相同,即每次寻找单位费用最小的增广路进行增广,直到图上不存在增广路为止。
由于我们已经对网络图的权值增加了$p o t e n t i a l med h_u$,因此可以用$D i j k s t r a med$算法求解每一次的最小增广路。
= 程序代码
文件`sis8\maxFlow.java`实现了一个`maxFlow`类
```java
package sis8;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class maxFlow {
private class edge {
public int nxt, // 出度
cap, // 容量
flow; // 流量
public int[] revNodeIdx; // 反向边
public edge(int _nxt, int _cap) {
nxt = _nxt;
cap = _cap;
flow = 0;
}
public void setRevIdx(int _i, int _j) {
revNodeIdx = new int[2];
revNodeIdx[0] = _i;
revNodeIdx[1] = _j;
}
}
private ArrayList<ArrayList<edge>> edgeList; // 节点列表
private ArrayList<Integer> dep; // 深度
private ArrayList<Integer> fir; // 节点最近合法边
private int maxFlowAns;
private int T, S;
public maxFlow(int _n) {
maxFlowAns = 0;
S = 1;
T = _n;
edgeList = new ArrayList<ArrayList<edge>>();
for(int i = 0;i <= _n;i ++) edgeList.add(new ArrayList<edge>());
dep = new ArrayList<Integer>();
fir = new ArrayList<Integer>();
for(int i = 0;i <= _n;i ++) dep.add(0);
for(int i = 0;i <= _n;i ++) fir.add(0);
}
public void resetTS(int _T, int _S) {
T = _T;
S = _S;
}
public void addedge(int _u, int _v, int _w) {
edgeList.get(_u).add(new edge(_v, _w));
edgeList.get(_v).add(new edge(_u, 0)); // 反向建边
edgeList.get(_u).get(edgeList.get(_u).size() - 1).setRevIdx(_v, edgeList.get(_v).size() - 1);
edgeList.get(_v).get(edgeList.get(_v).size() - 1).setRevIdx(_u, edgeList.get(_u).size() - 1);
}
public boolean bfs() { // 统计深度
Queue<Integer> que = new LinkedList<Integer>();
for (int i = 0; i < dep.size(); i++)
dep.set(i, 0);
dep.set(S, 1);
que.add(S);
while (que.size() != 0) {
int at = que.peek();
que.poll();
for (int i = 0; i < edgeList.get(at).size(); i++) {
edge tar = edgeList.get(at).get(i);
if ((dep.get(tar.nxt) == 0) && (tar.flow < tar.cap)) {
dep.set(tar.nxt, dep.get(at) + 1);
que.add(tar.nxt);
}
}
}
return dep.get(T) != 0;
}
public int dfs(int at, int flow) {
if ((at == T) || (flow == 0))
return flow; // 到了或者没了
int ret = 0; // 本节点最大流
for (int i = fir.get(at); i < edgeList.get(at).size(); i++) {
edge tar = edgeList.get(at).get(i); // 目前遍历的边
int tlFlow = 0; // 目前边的最大流
if (dep.get(at) == dep.get(tar.nxt) - 1) { // 遍历到的边为合法边
tlFlow = dfs(tar.nxt, Math.min(tar.cap - tar.flow, flow - ret));
if (tlFlow == 0)
continue; // 若最大流为0,什么都不做
ret += tlFlow; // 本节点最大流累加
edgeList.get(at).get(i).flow += tlFlow; // 本节点实时流量
edgeList.get(tar.revNodeIdx[0]).get(tar.revNodeIdx[1]).flow -= tlFlow; // 反向边流量
if (ret == flow)
return ret; // 充满了就不继续扫了
}
}
return ret;
}
public int dinic() {
if (maxFlowAns != 0)
return maxFlowAns;
while (bfs()) {
for(int i = 0;i < fir.size();i ++) fir.set(i, 0);
maxFlowAns += dfs(S, Integer.MAX_VALUE);
}
return maxFlowAns;
}
}
```
文件`sis8\minCost.java`实现了一个`minCost`类
```java
package sis8;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
public class minCost { //JAVA version
public static class edge {
public int v, f, c, next;
edge(int _v, int _f, int _c, int _next) {
v = _v;
f = _f;
c = _c;
next = _next;
}
edge() {
}
}
private static final int INF = 0x3f3f3f3f;
public static void vecset(int value, ArrayList<Integer> arr) {
for (int i = 0; i < arr.size(); i++)
arr.set(i, value);
return;
}
public static class node {
public int v, e;
}
public static class mypair implements Comparable<mypair> {
public int dis, id;
public mypair(int d, int x) {
dis = d;
id = x;
}
public int compareTo(mypair a) {
return dis - a.dis;
}
}
public ArrayList<Integer> head;
public ArrayList<Integer> dis;
public ArrayList<Integer> vis;
public ArrayList<Integer> h;
public ArrayList<edge> e;
public ArrayList<node> p;
public int n, m, s, t, cnt = 1, maxf, minc;
public minCost(int _n, int _m, int _s, int _t) {
n = _n;
m = _m;
s = _s;
t = _t;
maxf = 0;
minc = 0;
head = new ArrayList<Integer>();
dis = new ArrayList<Integer>();
vis = new ArrayList<Integer>();
e = new ArrayList<edge>();
h = new ArrayList<Integer>();
p = new ArrayList<node>();
for (int i = 0; i <= n + 2; i++) {
head.add(0);
dis.add(0);
vis.add(0);
h.add(0);
}
for (int i = 0; i <= m + 2; i++)
p.add(new node());
}
public void addedge(int u, int v, int f, int c) {
e.add(new edge(v, f, c, head.get(u)));
head.set(u, e.size() - 1);
e.add(new edge(u, 0, -c, head.get(v)));
head.set(v, e.size() - 1);
}
public boolean dijkstra() {
PriorityQueue<mypair> q = new PriorityQueue<mypair>();
vecset(INF, dis);
vecset(0, vis);
dis.set(s, 0);
q.add(new mypair(0, s));
while (!q.isEmpty()) {
int u = q.peek().id;
q.poll();
if (vis.get(u) == 1)
continue;
vis.set(u, 1);
for (int i = head.get(u); i != 0; i = e.get(i).next) {
int v = e.get(i).v, nc = e.get(i).c + h.get(u) - h.get(v);
if (e.get(i).f != 0 && dis.get(v) > dis.get(u) + nc) {
dis.set(v, dis.get(u) + nc);
p.get(v).v = u;
p.get(v).e = i;
if (vis.get(v) != 1)
q.add(new mypair(dis.get(v), v));
}
}
}
return dis.get(t) != INF;
}
public void spfa() {
Queue<Integer> q = new LinkedList<Integer>();
vecset(63, h);
h.set(s, 0);
vis.set(s, 1);
q.add(s);
while (!q.isEmpty()) {
int u = q.peek();
q.poll();
vis.set(u, 0);
for (int i = head.get(u); i != 0; i = e.get(i).next) {
int v = e.get(i).v;
if (e.get(i).f != 0 && h.get(v) > h.get(u) + e.get(i).c) {
h.set(v, h.get(u) + e.get(i).c);
if (vis.get(v) != 1) {
vis.set(v, 1);
q.add(v);
}
}
}
}
}
public int pd() {
spfa();
while (dijkstra()) {
int minf = INF;
for (int i = 1; i <= n; i++)
h.set(i, h.get(i) + dis.get(i));
for (int i = t; i != s; i = p.get(i).v)
minf = Math.min(minf, e.get(p.get(i).e).f);
for (int i = t; i != s; i = p.get(i).v) {
e.get(p.get(i).e).f -= minf;
e.get(p.get(i).e ^ 1).f += minf;
}
maxf += minf;
minc += minf * h.get(t);
}
return 0;
}
public void printAns() {
System.out.println(maxf + " " + minc);
}
}
```
文件`sis8\solution.java`实现了一个`solution`类
```java
package sis8;
public class solution {
//构建带权图,求解最大流与最小费用流
public static void main(String[] args) {
try (java.util.Scanner sc = new java.util.Scanner(System.in)) {
int n = sc.nextInt();
int m = sc.nextInt();
int s = sc.nextInt();
int t = sc.nextInt();
minCost pd = new minCost(n, m, s, t);
maxFlow mf = new maxFlow(n);
for (int i = 1; i <= m; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int c = sc.nextInt();
int f = sc.nextInt();
mf.addedge(u, v, c);
pd.addedge(u, v, c, f);
}
pd.spfa();
System.out.println(" 考虑费用的最小费用流 " + pd.maxf + " " + pd.minc);
mf.resetTS(t, s);
mf.dinic();
System.out.println(" 不考虑费用的最大流 " + mf.dinic());
}
}
}
```
= 出现的问题、原因与解决方法
\
#h(1.8em) 在实现最大流算法的过程中,发现`java.util`库中的`Queue`使用接口实现,无法直接实例化,于是查询资料得`Queue`需要借助`LinkedList`进行实例化。
经过一些思考并结合在后续实现过程中使用的感受,随后查询资料,我总结了一些`Queue`规定为接口的好处:
#box[
+ 抽象层次结构: 使用接口可以创建一个抽象的层次结构,使得可以定义多个具有不同实现的队列类型。这样,程序员可以根据具体的需求选择合适的实现,而不关心底层的数据结构或算法。
+ 多态性: 接口允许多个类实现相同的接口,这为多态性提供了支持。这意味着可以将不同实现的队列对象交替使用,而不需要修改调用这些队列的代码。
+ 解耦合: 使用接口可以将队列的定义与其具体的实现分离开来。这种解耦合使得可以更容易地更改或替换底层实现,而不会对使用队列的代码造成影响。
+ 一致的API: 接口定义了队列应该具有的方法,这为实现提供了一致的API。这使得可以编写通用的代码,而不用担心不同队列实现之间的差异。
+ 可扩展性: 如果需要在将来添加新的队列实现,只需实现Queue接口,而不必修改已有的代码。]
#pagebreak()
= 测试数据与运行结果
\
#h(1.8em) 测试输入规则:
输入一行包含四个整数$n,m,s,t$,分别代表网络点数、边数、源点、汇点。
接下来m行,每行四个整数$u_i,v_i,w_i,c_i$,分别代表第i条边的起点、终点、最大流量、单位费用。
#figure(
table(
align: left + horizon,
columns: 3,
[*输入*],[*输出*],[*解释*],
[`4 5 4 3
4 2 30 2
4 3 20 3
2 3 20 1
2 1 30 9
1 3 40 5`],[`50
50 280`],[网络最大流为50\ 考虑费用后最大流仍为50,最小费用为280],
)
) |
|
https://github.com/kazuyanagimoto/quarto-slides-typst | https://raw.githubusercontent.com/kazuyanagimoto/quarto-slides-typst/main/slides/quarto-clean-typst/custom.typ | typst | MIT License | #let _small-cite(self: none, it) = text(
size: 0.7em,
fill: self.colors.neutral-darkest.lighten(30%),
it
)
#let small-cite(it) = touying-fn-wrapper(_small-cite.with(it)) |
https://github.com/csimide/SEU-Typst-Template | https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/pages/cover-bachelor-fn.typ | typst | MIT License | #import "../utils/packages.typ": fakebold
#import "../utils/fonts.typ": 字体, 字号, chineseunderline, justify-words
#let bachelor-cover-conf(
student_id: "00121001",
author: "王东南",
school: "示例学院",
major: "示例专业",
advisor: "湖牌桥",
thesis-name: "示例论文标题\n此行空白时下划线自动消失",
date: "某个起止日期",
) = page(
paper: "a4",
margin: (
top: 2cm + 0.7cm,
bottom: 2cm + 0.5cm,
left: 2cm + 0.5cm,
right: 2cm,
),
)[
#set text(lang: "zh")
#set align(center)
//#hide[#heading(outlined: false, bookmarked: true)[封面]]
#image("../assets/vi/东南大学校标文字组合.png", width: 10cm)
#block(
height: 2cm,
{
text(font: 字体.黑体, size: 字号.一号, fakebold[本科毕业设计(论文)报告])
},
)
#v(40pt)
#block(
height: 2.5cm,
{
set text(font: 字体.黑体, size: 字号.二号, weight: "regular")
grid(
columns: (2.85cm, 12.84cm),
[题 目:],
chineseunderline(thesis-name),
)
},
)
#v(40pt)
#{
set text(font: 字体.宋体, size: 字号.小二, weight: "regular")
grid(
columns: (3.44cm - 1em, 1em, 8cm),
rows: 1.4cm,
justify-words("学号", width: 4em),
":",
chineseunderline(student_id),
justify-words("姓名", width: 4em),
":",
chineseunderline(author),
justify-words("学院", width: 4em),
":",
chineseunderline(school),
justify-words("专业", width: 4em),
":",
chineseunderline(major),
justify-words("指导教师", width: 4em),
":",
chineseunderline(advisor),
justify-words("起止日期", width: 4em),
":",
chineseunderline(date),
)
}
]
// 测试部分
#bachelor-cover-conf(
student_id: "00121001",
author: "王东南",
school: "示例学院",
major: "示例专业",
advisor: "湖牌桥",
thesis-name: "示例论文标题\n此行空白时下划线自动消失",
date: "某个起止日期",
) |
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/08_02_24/main.typ | typst | #import "polylux/polylux.typ": *
#import themes.metropolis: *
#import "common.typ": *
#show: metropolis-theme.with(
footer: [#logic.logical-slide.display() / #utils.last-slide-number]
)
#set text(font: font, weight: wt, size: 25pt)
// #show math.equation: set text(font: "Fira Math")
#set strong(delta: 100)
#set par(justify: true)
#title-slide(
author: [<NAME>],
title: "Slides - 8/02",
)
#slide(title: "Table of contents")[
#metropolis-outline
]
#new-section-slide([Pitch + Plan])
#slide(title: "Abbreviated Pitch" )[
- Compile C to Rust
- Improve on C2Rust flaws
- Guarantee that Rust code matches or improves on behavior of C code
- Formalize
- Semantics, Memory Model of small subset of Rust
- Lifting from unsafe to safe Rust
- An aside: DARPA TRACTOR
]
#slide(title: "Plan - This week (impl)")[
#set text(font: font, weight: wt, size: 18pt)
- formatter fix
- Syntactic
- structs unions
- \_Alignas keyword
- compiler builtins: alignof, sizeof
- loops
- internal function calls
- nested switch
- rudimentary pointer operations
- deref
- ref
- pay off some tech debt
]
#slide(title: "Plan - WIP this week (impl)")[
- WIP
- volatile
- more complex data structures (bitfields/VLA)
- gotos
- testing
]
#slide(title: "Plan - Next week")[
- technical:
- CFRust
- WIP items
- modules + imports
- more builtins
- introduce RustLight IR
- theory: work on memory model
]
#new-section-slide([Memory Model])
#slide(title: "Uninitialized structs")[
#set text(font: font, weight: wt, size: 22pt)
#codeblock(
```C
struct ExampleStruct {
int a;
float b;
char c;
};
fn example(){
struct ExampleStruct example_struct;
example_struct.a = 5;
example_struct.b = 0.5f;
example_struct.c = '5';
}
```
)
]
#slide(title: "Uninitialized structs")[
#set text(font: font, weight: wt, size: 18pt)
#codeblock(
```rust
#[repr(C)]
struct ExampleStruct {
a : libc::c_int,
b : libc::c_float,
c : libc::c_schar,
}
fn example(){
let mut example_struct: ExampleStruct;
example_struct.a = 5;
example_struct.b = 0.5;
example_struct.c = 5;
}
```
)
]
#slide(title: "Uninitialized structs")[
#set text(font: font, weight: wt, size: 15pt)
```
error[E0381]: partially assigned binding `example_struct` isn't fully initialized
--> src/lib.rs:10:7
|
9 | let mut example_struct: ExampleStruct;
| ------------------ binding declared here but left uninitialized
10 | example_struct.a = 5;
| ^^^^^^^^^^^^^^^^^^^^ `example_struct` partially assigned here but it isn't fully initialized
|
= help: partial initialization isn't supported, fully initialize the binding with a default value and mutate it, or use `std::mem::MaybeUninit`
```
]
#slide(title: "MaybeUninit Example")[
#set text(font: font, weight: wt, size: 13pt)
```rust
use std::mem::MaybeUninit;
use std::ptr::addr_of_mut;
#[derive(Debug, PartialEq)]
pub struct Foo {
a: u8,
b: u8,
}
let foo = {
let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
let ptr = uninit.as_mut_ptr();
unsafe { addr_of_mut!((*ptr).name).write(1); }
unsafe { addr_of_mut!((*ptr).list).write(2); }
unsafe { uninit.assume_init() }
};
```
]
#slide(title: "Solutions")[
- C2Rust style: initialize to 0
- `std::mem::MaybeUninit`
- "MaybeUninit<T> is guaranteed to have the same size, alignment, and ABI as T" -- man page
]
#slide(title: "Volatile reads and writes")[
//https://doc.rust-lang.org/core/ptr/fn.read_volatile.html
- Rust analogue:
- `std::ptr::read_volatile`
- `std::ptr::write_volatile`
- Not defined by Rust other than "C11’s definition of volatile"
]
#slide(title: "RustLight types")[
- Model compiler intrinsics like `sizeof(T | exp)` and `alignof(T | exp)`
- Support turbofish `std::mem::sizeof::<T>()`
]
|
|
https://github.com/takotori/PhAI-Spick | https://raw.githubusercontent.com/takotori/PhAI-Spick/main/sections/arbeit.typ | typst | = Arbeit $W$
*Beziehung zwischen Arbeit und Energie:*
#grid(
columns: (auto, auto),
gutter: 5pt,
$ Delta E = W_"AB" $,
[*$Delta E$*: Energieänderung eines offenen Systems \
*$W_"AB"$*: Arbeit, einer äusseren Kraft an diesem System]
)
#grid(
columns: (auto, auto),
gutter: 5pt,
$ W &= F_s dot s \
W &= F dot s dot cos(alpha) = arrow(F) dot arrow(s) $,
image("../figures/arbeit.jpg")
)
*Arbeit auf der scheifen Ebene mit Reibung:*
$W = (sin(alpha) + mu_R dot cos(alpha)) dot F_G dot s$ |
|
https://github.com/Harry-Chen/kouhu | https://raw.githubusercontent.com/Harry-Chen/kouhu/master/lib.typ | typst | MIT License | /// Get all builtin texts. Returns in `dictionary[string, list[string]]`.
///
/// *Example:*
/// Show the number of paragraphs in each builtin text.
/// #example(`#builtin-text-list().pairs().map(p => (p.at(0), p.at(1).len())))`, mode: "markup")
///
/// -> dictionary
#let builtin-text-list() = {
return json("data/zhlipsum.json")
}
/// Output selected Chinese lorem ipsum paragraphs.
///
/// *Example 1:*
/// Cut some paragraphs from Lu Xun's _Zhufu_(《祝福》).
/// #example(`#kouhu(builtin-text: "zhufu", offset: 5, indicies: (2, 18), length: 31, between-para: "——")`, mode: "markup")
///
/// *Example 2:*
/// Repeat some text until the specified length.
/// #example(`#kouhu(custom-text: ("奥利",), between-para: none, length: 31)`, mode: "markup")
/// - builtin-text (string): Name of the builtin text, see @@builtin-text-list() for a full list and length.
/// - custom-text (array): Custom text to use. If not `none`, `builtin-text` will be ignored.
/// - offset (int): Offset of the paragraph to start from.
/// - indicies (array): Indicies (*NOT RANGE*) of paragraphs to use (`offset` will be added). `none` means all paragraphs. Any out-of-bound index will be ignored.
/// - length (int): Length of graphme (characters) to print. `kouhu` will repeat over selected paragraphs until `length` is reached, and the final paragraph will likely be truncated. 0 for unlimited, i.e. print all selected paragraphs for only once.
/// - before-para (content): Content inserted before each paragraph.
/// - after-para (content): Content inserted after each paragraph.
/// - between-para (content): Content inserted between two paragraphs (has no effect if only one paragraph is selected).
/// -> doc
#let kouhu(
builtin-text: "simp",
custom-text: none,
offset: 0,
indicies: none,
length: 0,
before-para: none,
after-para: none,
between-para: parbreak(),
) = {
// load builtin text or use custom text
let text = custom-text
if text == none {
let data = builtin-text-list()
if builtin-text in data {
text = data.at(builtin-text)
} else {
panic("Builtin text '" + builtin-text + "' not found")
}
}
// normalize indicies
let selected_para = ()
if indicies == none {
indicies = range(1, text.len() + 1)
}
// select paragraphs according to argument, and
// truncate to specified length of graphme
let length_set = false
let remaining = 1e10 // use a large number here
if length > 0 {
remaining = length
length_set = true
}
while remaining > 0 {
for i in indicies {
let i_ = i + offset - 1
if i_ >= 0 and i_ < text.len() {
let t = text.at(i_).clusters()
if t.len() > remaining {
selected_para.push(t.slice(0, remaining).join())
remaining = 0
break
} else {
selected_para.push(t.join())
remaining -= t.len()
}
}
}
// break if user does not specify length
if not length_set {
break
}
}
// print paragraphs
let i = 0
for p in selected_para {
if before-para != "" {
before-para
}
p
if after-para != "" {
after-para
}
if between-para != "" and i < selected_para.len() - 1 {
between-para
}
i += 1
}
}
|
https://github.com/jeffa5/typst-cambridge | https://raw.githubusercontent.com/jeffa5/typst-cambridge/main/slides/cambridge.typ | typst | MIT License | /// This theme is inspired by the Cambridge University presentation templates
#import "@preview/polylux:0.3.1": *
/// The polylux theme for the University of Cambridge.
#let cambridge-theme(
aspect-ratio: "16-9",
font: "Liberation Sans",
body,
) = {
let background = rgb("#FFFFFF")
set text(font: font)
set page(
paper: "presentation-" + aspect-ratio,
margin: 0pt,
fill: background,
)
body
}
#let blue = rgb("#0072CF")
#let light-blue = rgb("#68ACE5")
#let dark-blue = rgb("#003E74")
#let blue-text = rgb("#1f4e79")
#let debug-stroke = 1pt + red
#let stroke(debug) = {
if debug {
debug-stroke
} else {
none
}
}
#let make-footer(content) = text(size: 16pt, content)
#let title-slide(
title: [],
subtitle: [],
authors: [],
date: [],
venue: [],
numbering: "1 / 1",
slide-count: false,
debug: false,
) = {
set text(fill: white, size: 20pt)
let stroke = stroke(debug)
let slide-number = logic.logical-slide.display(numbering, both: slide-count)
polylux-slide[
#block(
width: 100%,
height: 28%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
fill: white,
align(horizon, image(width: 13em, "light-logo.svg")),
)
#block(
width: 100%,
height: 49%,
outset: 0em,
inset: 2em,
breakable: false,
stroke: stroke,
spacing: 0em,
fill: blue,
[
#align(left + horizon, text(size: 36pt, title))
#align(left + horizon, text(size: 18pt, subtitle))
],
)
#block(
width: 100%,
height: 9%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
fill: dark-blue,
[
#set text(size: 18pt)
#box(width: auto, height: 100%, stroke: stroke, clip: true, [#align(horizon, authors)])
#h(1fr)
#box(width: auto, height: 100%, stroke: stroke, clip: true, [#align(horizon, [#date #venue])])
],
)
#block(
width: 100%,
height: 5%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
fill: light-blue,
)
#block(
width: 100%,
height: 9%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
align(right + horizon, text(fill: blue-text, make-footer(slide-number))),
)
]
}
#let slide(
title: [],
short-authors: [],
numbering: "1 / 1",
debug: false,
slide-count: false,
body,
) = {
set text(fill: blue-text, size: 20pt)
let stroke = stroke(debug)
let displayed-title = heading(level: 1, text(size: 26pt, title))
let slide-number = logic.logical-slide.display(numbering, both: slide-count)
let footer = make-footer[#short-authors #h(2em) #slide-number]
polylux-slide[
#block(
width: 100%,
height: 15%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
fill: white,
clip: true,
align(left + horizon, displayed-title),
)
#block(
width: 100%,
height: 73%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
fill: white,
clip: true,
align(left + horizon, body),
)
#block(
width: 100%,
height: 12%,
outset: 0em,
inset: (x: 2em),
breakable: false,
stroke: stroke,
spacing: 0em,
fill: dark-blue,
clip: true,
[#box(height: 100%, stroke: stroke, clip: true, [#align(horizon, image(width: 10em, "dark-logo.svg"))])
#h(1fr)
#box(height: 100%, stroke: stroke, clip: true, align(right + horizon, text(fill: white, footer)))],
)
]
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-04.typ | typst | Other | // Test numbers with alternative bases.
#test(0x10, 16)
#test(0b1101, 13)
#test(0xA + 0xa, 0x14)
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/link/link_inserted.typ | typst | https://typst.app/
https://pl.wikipedia.org/
https://gitlab-stud.elka.pw.edu.pl/dferfeck/zprp-typstdiff |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/raw-05.typ | typst | Other | // Single ticks should not have a language.
`rust let`
|
https://github.com/kilpkonn/msc-thesis | https://raw.githubusercontent.com/kilpkonn/msc-thesis/master/appendixes.typ | typst | #import "@preview/codelst:2.0.0": sourcecode
= Non-Exclusive License for Reproduction and Publication of a Graduation Thesis
I, <NAME>
1. Grant Tallinn University of Technology free licence (non-exclusive licence) for my thesis “Term Search in Rust”, supervised by <NAME>
1. to be reproduced for the purposes of preservation and electronic publication of the graduation thesis, incl. to be entered in the digital collection of the library of Tallinn University of Technology until expiry of the term of copyright;
2. to be published via the web of Tallinn University of Technology, incl. to be entered in the digital collection of the library of Tallinn University of Technology until expiry of the term of copyright.
2. I am aware that the author also retains the rights specified in clause 1 of the non-exclusive licence.
3. I confirm that granting the non-exclusive licence does not infringe other persons’ intellectual property rights, the rights arising from the Personal Data Protection Act or rights arising from other legislation.
12.05.2024
= List of crates <appendix-crates>
#table(
columns: 2,
inset: 5pt,
align: horizon,
table.header[*Category*][*Crate*],
[algorithms], [rand_core-0.6.4],
[algorithms], [rand-0.8.5],
[algorithms], [rand_chacha-0.3.1],
[algorithms], [num-traits-0.2.18],
[algorithms], [crossbeam-utils-0.8.19],
[api-bindings], [socket2-0.5.6],
[api-bindings], [flate2-1.0.28],
[api-bindings], [zstd-safe-7.1.0],
[api-bindings], [openssl-0.10.64],
[api-bindings], [libloading-0.8.3],
[asynchronous], [mio-0.8.11],
[asynchronous], [tokio-1.37.0],
[asynchronous], [futures-0.3.30],
[asynchronous], [tokio-util-0.7.10],
[asynchronous], [tracing-0.1.40],
[command-line-interface], [textwrap-0.16.1],
[command-line-interface], [clap_lex-0.7.0],
[command-line-interface], [clap-4.5.4],
[command-line-interface], [clap_derive-4.5.4],
[command-line-interface], [os_str_bytes-7.0.0],
[command-line-utilities], [crossterm-0.27.0],
[command-line-utilities], [inferno-0.11.19],
[command-line-utilities], [names-0.14.0],
[command-line-utilities], [honggfuzz-0.5.55],
[command-line-utilities], [self_update-0.39.0],
[concurrency], [parking_lot_core-0.9.9],
[concurrency], [crossbeam-channel-0.5.12],
[concurrency], [parking_lot-0.12.1],
[concurrency], [lock_api-0.4.11],
[concurrency], [crossbeam-utils-0.8.19],
[cryptography], [block-buffer-0.10.4],
[cryptography], [ppv-lite86-0.2.17],
[cryptography], [rustls-0.23.4],
[cryptography], [digest-0.10.7],
[cryptography], [sha2-0.10.8],
[data-structures], [smallvec-1.13.2],
[data-structures], [hashbrown-0.14.3],
[data-structures], [indexmap-2.2.6],
[data-structures], [semver-1.0.22],
[data-structures], [bytes-1.6.0],
[database], [rusqlite-0.31.0],
[database], [postgres-types-0.2.6],
[database], [diesel-2.1.5],
[database], [rocksdb-0.22.0],
[database], [librocksdb-sys-6.20.3],
[development-tools], [proc-macro2-1.0.79],
[development-tools], [quote-1.0.35],
[development-tools], [log-0.4.21],
[development-tools], [syn-2.0.57],
[development-tools], [autocfg-1.2.0],
[embedded], [bitvec-1.0.1],
[embedded], [ciborium-io-0.2.2],
[embedded], [ciborium-0.2.2],
[embedded], [oorandom-11.1.3],
[embedded], [ciborium-ll-0.2.2],
[encoding], [serde-1.0.197],
[encoding], [byteorder-1.5.0],
[encoding], [url-2.5.0],
[encoding], [base64-0.22.0],
[encoding], [serde_json-1.0.115],
[external-ffi-bindings], [libc-0.2.153],
[external-ffi-bindings], [winapi-util-0.1.6],
[external-ffi-bindings], [winapi-0.3.9],
[external-ffi-bindings], [linux-raw-sys-0.6.4],
[external-ffi-bindings], [openssl-sys-0.9.102],
[filesystem], [rustix-0.38.32],
[filesystem], [walkdir-2.5.0],
[filesystem], [glob-0.3.1],
[filesystem], [remove_dir_all-0.8.2],
[filesystem], [which-6.0.1],
[game-development], [egui-0.27.1],
[game-development], [eframe-0.27.1],
[game-development], [gpu-alloc-0.6.0],
[game-development], [gpu-alloc-types-0.3.0],
[game-development], [egui-winit-0.27.1],
[graphics], [exr-1.72.0],
[graphics], [rgb-0.8.37],
[graphics], [gpu-alloc-0.6.0],
[graphics], [gpu-alloc-types-0.3.0],
[graphics], [tiny-skia-path-0.11.4],
[gui], [stdweb-0.4.20],
[gui], [stdweb-internal-macros-0.2.9],
[gui], [winit-0.29.15],
[gui], [stdweb-derive-0.5.3],
[gui], [stdweb-internal-runtime-0.1.5],
[hardware-support], [num_cpus-1.16.0],
[hardware-support], [cpufeatures-0.2.12],
[hardware-support], [portable-atomic-1.6.0],
[hardware-support], [num_threads-0.1.7],
[hardware-support], [safe_arch-0.7.1],
[mathematics], [rust_decimal-1.35.0],
[mathematics], [nalgebra-0.32.5],
[mathematics], [smawk-0.3.2],
[mathematics], [crypto-bigint-0.5.5],
[mathematics], [bigdecimal-0.4.3],
[multimedia], [tiff-0.9.1],
[multimedia], [png-0.17.13],
[multimedia], [image-0.25.1],
[multimedia], [rgb-0.8.37],
[multimedia], [exr-1.72.0],
[network-programming], [bytes-1.6.0],
[network-programming], [socket2-0.5.6],
[network-programming], [tokio-1.37.0],
[network-programming], [hyper-1.2.0],
[network-programming], [h2-0.4.3],
[no-std], [libc-0.2.153],
[no-std], [bitflags-2.5.0],
[no-std], [rand_core-0.6.4],
[no-std], [rand-0.8.5],
[no-std], [serde-1.0.197],
[os], [libc-0.2.153],
[os], [getrandom-0.2.12],
[os], [nix-0.28.0],
[os], [rustix-0.38.32],
[os], [winapi-0.3.9],
[parser-implementations], [syn-2.0.57],
[parser-implementations], [url-2.5.0],
[parser-implementations], [toml-0.8.12],
[parser-implementations], [serde_json-1.0.115],
[parser-implementations], [time-0.3.34],
[parsing], [byteorder-1.5.0],
[parsing], [toml-0.8.12],
[parsing], [nom-7.1.3],
[parsing], [minimal-lexical-0.2.1],
[parsing], [semver-parser-0.10.2],
[rendering], [unic-ucd-segment-0.9.0],
[rendering], [unic-segment-0.9.0],
[rendering], [gl_generator-0.14.0],
[rendering], [khronos_api-3.1.0],
[rendering], [unic-ucd-version-0.9.0],
[rust-patterns], [once_cell-1.19.0],
[rust-patterns], [scopeguard-1.2.0],
[rust-patterns], [itertools-0.12.1],
[rust-patterns], [lazy_static-1.4.0],
[rust-patterns], [thiserror-1.0.58],
[science], [num-traits-0.2.18],
[science], [num-complex-0.4.5],
[science], [num-integer-0.1.46],
[science], [num-bigint-0.4.4],
[science], [num-rational-0.4.1],
[text-processing], [regex-1.10.4],
[text-processing], [aho-corasick-1.1.3],
[text-processing], [strsim-0.11.0],
[text-processing], [unicode-bidi-0.3.15],
[text-processing], [regex-automata-0.4.6],
[wasm], [reqwest-0.12.2],
[wasm], [wasm-bindgen-0.2.92],
[wasm], [js-sys-0.3.69],
[wasm], [uuid-1.8.0],
[wasm], [wasi-0.13.0+wasi-0.2.0],
[web-programming], [hyper-1.2.0],
[web-programming], [http-1.1.0],
[web-programming], [h2-0.4.3],
[web-programming], [httparse-1.8.0],
[web-programming], [url-2.5.0],
)
= Per category results <appendix-per-category-results>
#figure(
table(
columns: 5,
inset: 5pt,
align: horizon,
table.header[*Category*][*Holes filled*][*Syntactic matches*][*Suggestions per expr*][*Avg time*],
[algorithms], [72.7%], [8.6%], [4.0], [7.8ms],
[api-bindings], [66.9%], [8.2%], [4.6], [10.6ms],
[asynchronous], [69.2%], [10.6%], [3.0], [4.6ms],
[command-line-interface], [69.4%], [5.3%], [2.3], [7.6ms],
[command-line-utilities], [79.7%], [17.2%], [3.5], [14.2ms],
[concurrency], [74.6%], [17.1%], [5.9], [4.2ms],
[cryptography], [76.3%], [10.5%], [4.0], [23.4ms],
[data-structures], [58.4%], [5.0%], [2.7], [5.2ms],
[database], [58.4%], [18.9%], [28.3], [47.6ms],
[development-tools], [80.2%], [17.2%], [4.0], [14.4ms],
[embedded], [60.9%], [9.8%], [3.4], [21.8ms],
[encoding], [67.9%], [10.1%], [3.6], [27.6ms],
[external-ffi-bindings], [84.2%], [11.5%], [303.1], [48.2ms],
[filesystem], [69.6%], [8.8%], [2.8], [7.0ms],
[game-development], [68.8%], [12.3%], [4.9], [66.8ms],
[graphics], [80.8%], [15.3%], [4.4], [17.0ms],
[gui], [83.2%], [9.4%], [3.6], [36.4ms],
[hardware-support], [99.2%], [0.9%], [15.8], [36.8ms],
[mathematics], [73.1%], [7.5%], [7.1], [767.0ms],
[multimedia], [82.1%], [15.1%], [4.9], [59.0ms],
[network-programming], [78.8%], [11.3%], [3.3], [9.8ms],
[no-std], [52.9%], [8.6%], [76.5], [14.0ms],
[os], [62.3%], [6.9%], [77.7], [11.2ms],
[parser-implementations], [81.7%], [13.2%], [5.4], [30.8ms],
[parsing], [68.2%], [5.4%], [4.6], [25.4ms],
[rendering], [76.0%], [21.1%], [5.1], [2.2ms],
[rust-patterns], [60.4%], [9.2%], [2.8], [6.8ms],
[science], [90.2%], [8.0%], [5.8], [81.8ms],
[text-processing], [82.4%], [14.0%], [6.4], [10.4ms],
[wasm], [80.5%], [16.6%], [13.0], [103.0ms],
[web-programming], [77.5%], [11.6%], [4.0], [10.6ms],
),
caption: [Per category results with $"depth"=2$]
) <tbl-per-category-results>
= Reduced list of crates <appendix-reduced-crates>
#table(
columns: 2,
inset: 5pt,
align: horizon,
table.header[*Category*][*Crate*],
[algorithms], [rand-0.8.5],
[api-bindings], [socket2-0.5.6],
[asynchronous], [mio-0.8.11],
[command-line-interface], [clap-4.5.4],
[command-line-utilities], [crossterm-0.27.0],
[concurrency], [parking_lot_core-0.9.9],
[cryptography], [digest-0.10.7],
[data-structures], [hashbrown-0.14.3],
[database], [rusqlite-0.31.0],
[development-tools], [syn-2.0.58],
[embedded], [bitvec-1.0.1],
[encoding], [serde-1.0.197],
[external-ffi-bindings], [libc-0.2.153],
[filesystem], [rustix-0.38.32],
[game-development], [gpu-alloc-0.6.0],
[graphics], [rgb-0.8.37],
[gui], [stdweb-0.4.20],
[hardware-support], [num_cpus-1.16.0],
[mathematics], [crypto-bigint-0.5.5],
[multimedia], [png-0.17.13],
[network-programming], [bytes-1.6.0],
[no-std], [libc-0.2.153],
[os], [libc-0.2.153],
[parser-implementations], [syn-2.0.58],
[parsing], [byteorder-1.5.0],
[rendering], [unic-ucd-version-0.9.0],
[rust-patterns], [once_cell-1.19.0],
[science], [num-traits-0.2.18],
[text-processing], [regex-1.10.4],
[wasm], [uuid-1.8.0],
[web-programming], [url-2.5.0],
)
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/144.%20speak.html.typ | typst | speak.html
Writing and Speaking
March 2012I'm not a very good speaker. I say "um" a lot. Sometimes I have
to pause when I lose my train of thought. I wish I were a better
speaker. But I don't wish I were a better speaker like I wish I
were a better writer. What I really want is to have good ideas,
and that's a much bigger part of being a good writer than being a
good speaker.Having good ideas is most of writing well. If you know what you're
talking about, you can say it in the plainest words and you'll be
perceived as having a good style. With speaking it's the opposite:
having good ideas is an alarmingly small component of being a good
speaker.I first noticed this at a conference several years ago.
There was another speaker who was much better than me.
He had all of us roaring with laughter. I seemed awkward and
halting by comparison. Afterward I put my talk online like I usually
do. As I was doing it I tried to imagine what a transcript of the
other guy's talk would be like, and it was only then I realized he
hadn't said very much.Maybe this would have been obvious to someone who knew more about
speaking, but it was a revelation to me how much less ideas mattered
in speaking than writing.
[1]A few years later I heard a talk by someone who was not merely a
better speaker than me, but a famous speaker. Boy was he good. So
I decided I'd pay close attention to what he said, to learn how he
did it. After about ten sentences I found myself thinking "I don't
want to be a good speaker."Being a really good speaker is not merely orthogonal to having good ideas,
but in many ways pushes you in the opposite direction. For example,
when I give a talk, I usually write it out beforehand. I know that's
a mistake; I know delivering a
prewritten
talk makes it harder to
engage with an audience. The way to get the attention of an audience
is to give them your full attention, and when you're delivering
a prewritten talk, your attention is always divided between the
audience and the talk — even if you've memorized it. If you want
to engage an audience, it's better to start with no more than an outline
of what you want to say and
ad lib the individual sentences. But
if you do that, you might spend no more time thinking about each
sentence than it takes to say it.
[2]
Occasionally the stimulation
of talking to a live audience makes you think of new things, but
in general this is not going to generate ideas as well as writing
does, where you can spend as long on each sentence as you want.If you rehearse a prewritten speech enough, you can get
asymptotically close to the sort of engagement you get when speaking
ad lib. Actors do. But here again there's a tradeoff between
smoothness and ideas. All the time you spend practicing a talk,
you could instead spend making it better. Actors don't face
that temptation, except in the rare cases where they've written the
script, but any speaker does. Before I give a talk I can usually
be found sitting in a corner somewhere with a copy printed out on
paper, trying to rehearse it in my head. But I always end up
spending most of the time rewriting it instead. Every talk I give
ends up being given from a manuscript full of things crossed out
and rewritten. Which of course makes me um even more, because I
haven't had any time to practice the new bits.
[3]Depending on your audience, there are even worse tradeoffs than
these. Audiences like to be flattered; they like jokes; they like
to be swept off their feet by a vigorous stream of words. As you
decrease the intelligence of the audience, being a good speaker is
increasingly a matter of being a good bullshitter. That's true in
writing too of course, but the descent is steeper with talks. Any
given person is dumber as a member of an audience than as a reader.
Just as a speaker ad libbing can only spend as long thinking about
each sentence as it takes to say it, a person hearing a talk can
only spend as long thinking about each sentence as it takes to hear
it. Plus people in an audience are always affected by the reactions
of those around them, and the reactions that spread from person to
person in an audience are disproportionately the more brutish sort,
just as low notes travel through walls better than high ones. Every
audience is an incipient mob, and a good speaker uses that. Part
of the reason I laughed so much at the talk by the good speaker at
that conference was that everyone else did.
[4]So are talks useless? They're certainly inferior to the written
word as a source of ideas. But that's not all talks are good for.
When I go to a talk, it's usually because I'm interested in the
speaker. Listening to a talk is the closest most of us can get to
having a conversation with someone like the president, who doesn't
have time to meet individually with all the people who want to meet
him.Talks are also good at motivating me to do things. It's probably
no coincidence that so many famous speakers are described as
motivational speakers. That may be what public speaking is really
for. It's probably what it was originally for. The emotional
reactions you can elicit with a talk can be a powerful force.
I wish I could say that this force was more often used for good than
ill, but I'm not sure.Notes[1]
I'm not talking here about academic talks, which are a
different type of thing. While the
audience at an academic talk might appreciate a joke, they will (or
at least should) make a conscious effort to see what new ideas
you're presenting.[2]
That's the lower bound. In practice you can often do better,
because talks are usually about things you've written or talked
about before, and when you ad lib, you end up reproducing some of
those sentences. Like early medieval architecture, impromptu talks
are made of spolia. Which feels a bit dishonest, incidentally,
because you have to deliver these sentences as if you'd just thought
of them.[3]
Robert Morris points out that there is a way in which practicing
talks makes them better: reading a talk out loud can expose awkward
parts. I agree and in fact I read most things I write out loud at
least once for that reason.[4]
For sufficiently small audiences, it may not be true that being
part of an audience makes people dumber. The real decline seems
to set in when the audience gets too big for the talk to feel like
a conversation — maybe around 10 people.
Thanks to <NAME> and <NAME> for reading drafts
of this.
|
|
https://github.com/metamuffin/typst | https://raw.githubusercontent.com/metamuffin/typst/main/docs/src/reference/types.md | markdown | Apache License 2.0 | # None
A value that indicates the absence of any other value.
The none type has exactly one value: `{none}`.
When inserted into the document, it is not visible.
This is also the value that is produced by empty code blocks.
It can be [joined]($scripting/#blocks) with any value, yielding
the other value.
## Example
```example
Not visible: #none
```
# Auto
A value that indicates a smart default.
The auto type has exactly one value: `{auto}`.
Parameters that support the `{auto}` value have some smart default or contextual
behaviour. A good example is the [text direction]($func/text.dir) parameter.
Setting it to `{auto}` lets Typst automatically determine the direction from the
[text language]($func/text.lang).
# Boolean
Either `{true}` or `{false}`.
The boolean type has two values: `{true}` and `{false}`. It denotes whether
something is active or enabled.
## Example
```example
#false \
#true \
#(1 < 2)
```
# Integer
A whole number.
The number can be negative, zero, or positive. As Typst uses 64 bits to store
integers, integers cannot be smaller than `{-9223372036854775808}` or larger than
`{9223372036854775807}`.
The number can also be specified as hexadecimal, octal, or binary by starting it
with a zero followed by either `x`, `o`, or `b`.
## Example
```example
#(1 + 2) \
#(2 - 5) \
#(3 + 4 < 8)
#0xff \
#0o10 \
#0b1001
```
# Float
A floating-pointer number.
A limited-precision representation of a real number. Typst uses 64 bits to
store floats. Wherever a float is expected, you can also pass an
[integer]($type/integer).
## Example
```example
#3.14 \
#1e4 \
#(10 / 4)
```
# Length
A size or distance, possibly expressed with contextual units.
Typst supports the following length units:
- Points: `{72pt}`
- Millimeters: `{254mm}`
- Centimeters: `{2.54cm}`
- Inches: `{1in}`
- Relative to font size: `{2.5em}`
## Example
```example
#rect(width: 20pt)
#rect(width: 2em)
#rect(width: 1in)
```
# Angle
An angle describing a rotation.
Typst supports the following angular units:
- Degrees: `{180deg}`
- Radians: `{3.14rad}`
## Example
```example
#rotate(10deg)[Hello there!]
```
# Ratio
A ratio of a whole.
Written as a number, followed by a percent sign.
## Example
```example
#set align(center)
#scale(x: 150%)[
Scaled apart.
]
```
# Relative Length
A length in relation to some known length.
This type is a combination of a [length]($type/length) with a
[ratio]($type/ratio). It results from addition and subtraction
of a length and a ratio. Wherever a relative length is expected, you can also
use a bare length or ratio.
## Example
```example
#rect(width: 100% - 50pt)
```
# Fraction
Defines how the the remaining space in a layout is distributed.
Each fractionally sized element gets space based on the ratio of its fraction to
the sum of all fractions.
For more details, also see the [h]($func/h) and [v]($func/v) functions and the
[grid function]($func/grid).
## Example
```example
Left #h(1fr) Left-ish #h(2fr) Right
```
# Color
A color in a specific color space.
Typst supports:
- sRGB through the [`rgb` function]($func/rgb)
- Device CMYK through [`cmyk` function]($func/cmyk)
- D65 Gray through the [`luma` function]($func/luma)
Furthermore, Typst provides the following built-in colors:
`black`, `gray`, `silver`, `white`, `navy`, `blue`, `aqua`, `teal`, `eastern`,
`purple`, `fuchsia`, `maroon`, `red`, `orange`, `yellow`, `olive`, `green`, and
`lime`.
## Methods
### lighten()
Lightens a color.
- amount: ratio (positional, required)
The factor to lighten the color by.
- returns: color
### darken()
Darkens a color.
- amount: ratio (positional, required)
The factor to darken the color by.
- returns: color
### negate()
Produces the negative of the color.
- returns: color
# Datetime
Represents a date, a time, or a combination of both. Can be created by either
specifying a custom datetime using the [`datetime`]($func/datetime) function or
getting the current date with [`datetime.today`]($func/datetime.today).
## Example
```example
#let date = datetime(
year: 2020,
month: 10,
day: 4,
)
#date.display() \
#date.display(
"y:[year repr:last_two]"
)
#let time = datetime(
hour: 18,
minute: 2,
second: 23,
)
#time.display() \
#time.display(
"h:[hour repr:12][period]"
)
```
## Format
You can specify a customized formatting using the
[`display`]($type/datetime.display) method. The format of a datetime is
specified by providing _components_ with a specified number of _modifiers_. A
component represents a certain part of the datetime that you want to display,
and with the help of modifiers you can define how you want to display that
component. In order to display a component, you wrap the name of the component
in square brackets (e.g. `[[year]]` will display the year). In order to add
modifiers, you add a space after the component name followed by the name of the
modifier, a colon and the value of the modifier (e.g. `[[month repr:short]]`
will display the short representation of the month).
The possible combination of components and their respective modifiers is as
follows:
* `year`: Displays the year of the datetime.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the year
is padded.
* `repr` Can be either `full` in which case the full year is displayed or
`last_two` in which case only the last two digits are displayed.
* `sign`: Can be either `automatic` or `mandatory`. Specifies when the sign
should be displayed.
* `month`: Displays the month of the datetime.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the month
is padded.
* `repr`: Can be either `numerical`, `long` or `short`. Specifies if the month
should be displayed as a number or a word. Unfortunately, when choosing the
word representation, it can currently only display the English version. In
the future, it is planned to support localization.
* `day`: Displays the day of the datetime.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the day
is padded.
* `week_number`: Displays the week number of the datetime.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the week
number is padded.
* `repr`: Can be either `ISO`, `sunday` or `monday`. In the case of `ISO`,
week numbers are between 1 and 53, while the other ones are between 0
and 53.
* `weekday`: Displays the weekday of the date.
* `repr` Can be either `long`, `short`, `sunday` or `monday`. In the case of
`long` and `short`, the corresponding English name will be displayed (same
as for the month, other languages are currently not supported). In the case
of `sunday` and `monday`, the numerical value will be displayed (assuming
Sunday and Monday as the first day of the week, respectively).
* `one_indexed`: Can be either `true` or `false`. Defines whether the
numerical representation of the week starts with 0 or 1.
* `hour`: Displays the hour of the date.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the hour
is padded.
* `repr`: Can be either `24` or `12`. Changes whether the hour is displayed in
the 24-hour or 12-hour format.
* `period`: The AM/PM part of the hour
* `case`: Can be `lower` to display it in lower case and `upper` to display it
in upper case.
* `minute`: Displays the minute of the date.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the minute
is padded.
* `second`: Displays the second of the date.
* `padding`: Can be either `zero`, `space` or `none`. Specifies how the second
is padded.
Keep in mind that not always all components can be used. For example, if
you create a new datetime with `{datetime(year: 2023, month: 10, day: 13)}`, it
will be stored as a plain date internally, meaning that you cannot use
components such as `hour` or `minute`, which would only work on datetimes
that have a specified time.
## Methods
### display()
Displays the datetime in a certain way. Depending on whether you have defined
just a date, a time or both, the default format will be different.
If you specified a date, it will be `[[year]-[month]-[day]]`. If you specified a
time, it will be `[[hour]:[minute]:[second]]`. In the case of a datetime, it
will be `[[year]-[month]-[day] [hour]:[minute]:[second]]`.
- pattern: string (positional)
The format used to display the datetime.
- returns: string
### year()
Returns the year of the datetime, if it exists. Otherwise, it returns `{none}`.
- returns: integer or none
### month()
Returns the month of the datetime, if it exists. Otherwise, it returns `{none}`.
- returns: integer or none
### weekday()
Returns the weekday of the datetime as a number starting with 1 from Monday, if
it exists. Otherwise, it returns `{none}`.
- returns: integer or none
### day()
Returns the day of the datetime, if it exists. Otherwise, it returns `{none}`.
- returns: integer or none
### hour()
Returns the hour of the datetime, if it exists. Otherwise, it returns `{none}`.
- returns: integer or none
### minute()
Returns the minute of the datetime, if it exists. Otherwise, it returns
`{none}`.
- returns: integer or none
### second()
Returns the second of the datetime, if it exists. Otherwise, it returns
`{none}`.
- returns: integer or none
# Symbol
A Unicode symbol.
Typst defines common symbols so that they can easily be written with standard
keyboards. The symbols are defined in modules, from which they can be accessed
using [field access notation]($scripting/#fields):
- General symbols are defined in the [`sym` module]($category/symbols/sym)
- Emoji are defined in the [`emoji` module]($category/symbols/emoji)
Moreover, you can define custom symbols with the [symbol]($func/symbol)
function.
```example
#sym.arrow.r \
#sym.gt.eq.not \
$gt.eq.not$ \
#emoji.face.halo
```
Many symbols have different variants, which can be selected by appending the
modifiers with dot notation. The order of the modifiers is not relevant. Visit
the documentation pages of the symbol modules and click on a symbol to see its
available variants.
```example
$arrow.l$ \
$arrow.r$ \
$arrow.t.quad$
```
# String
A sequence of Unicode codepoints.
You can iterate over the grapheme clusters of the string using a
[for loop]($scripting/#loops). Grapheme clusters are basically characters but
keep together things that belong together, e.g. multiple codepoints that
together form a flag emoji. Strings can be added with the `+` operator,
[joined together]($scripting/#blocks) and multiplied with integers.
Typst provides utility methods for string manipulation. Many of these methods
(e.g., `split`, `trim` and `replace`) operate on _patterns:_ A pattern can be
either a string or a [regular expression]($func/regex). This makes the methods
quite versatile.
All lengths and indices are expressed in terms of UTF-8 characters. Indices are
zero-based and negative indices wrap around to the end of the string.
### Example
```example
#"hello world!" \
#"\"hello\n world\"!" \
#"1 2 3".split() \
#"1,2;3".split(regex("[,;]")) \
#(regex("\d+") in "ten euros") \
#(regex("\d+") in "10 euros")
```
### Escape sequences
Just like in markup, you can escape a few symbols in strings:
- `[\\]` for a backslash
- `[\"]` for a quote
- `[\n]` for a newline
- `[\r]` for a carriage return
- `[\t]` for a tab
- `[\u{1f600}]` for a hexadecimal Unicode escape sequence
## Methods
### len()
The length of the string in UTF-8 encoded bytes.
- returns: integer
### first()
Extract the first grapheme cluster of the string.
Fails with an error if the string is empty.
- returns: any
### last()
Extract the last grapheme cluster of the string.
Fails with an error if the string is empty.
- returns: any
### at()
Extract the first grapheme cluster after the specified index. Returns the
default value if the index is out of bounds or fails with an error if no default
value was specified.
- index: integer (positional, required)
The byte index.
- default: any (named)
A default value to return if the index is out of bounds.
- returns: string
### slice()
Extract a substring of the string.
Fails with an error if the start or end index is out of bounds.
- start: integer (positional, required)
The start byte index (inclusive).
- end: integer (positional)
The end byte index (exclusive). If omitted, the whole slice until the end of the
string is extracted.
- count: integer (named)
The number of bytes to extract. This is equivalent to passing `start + count`
as the `end` position. Mutually exclusive with `end`.
- returns: string
### clusters()
Returns the grapheme clusters of the string as an array of substrings.
- returns: array
### codepoints()
Returns the Unicode codepoints of the string as an array of substrings.
- returns: array
### contains()
Whether the string contains the specified pattern.
This method also has dedicated syntax: You can write `{"bc" in "abcd"}` instead
of `{"abcd".contains("bc")}`.
- pattern: string or regex (positional, required)
The pattern to search for.
- returns: boolean
### starts-with()
Whether the string starts with the specified pattern.
- pattern: string or regex (positional, required)
The pattern the string might start with.
- returns: boolean
### ends-with()
Whether the string ends with the specified pattern.
- pattern: string or regex (positional, required)
The pattern the string might end with.
- returns: boolean
### find()
Searches for the specified pattern in the string and returns the first match
as a string or `{none}` if there is no match.
- pattern: string or regex (positional, required)
The pattern to search for.
- returns: string or none
### position()
Searches for the specified pattern in the string and returns the index of the
first match as an integer or `{none}` if there is no match.
- pattern: string or regex (positional, required)
The pattern to search for.
- returns: integer or none
### match()
Searches for the specified pattern in the string and returns a dictionary
with details about the first match or `{none}` if there is no match.
The returned dictionary has the following keys:
* `start`: The start offset of the match
* `end`: The end offset of the match
* `text`: The text that matched.
* `captures`: An array containing a string for each matched capturing group. The
first item of the array contains the first matched capturing, not the whole
match! This is empty unless the `pattern` was a regex with capturing groups.
- pattern: string or regex (positional, required)
The pattern to search for.
- returns: dictionary or none
### matches()
Searches for the specified pattern in the string and returns an array of
dictionaries with details about all matches. For details about the returned
dictionaries, see above.
- pattern: string or regex (positional, required)
The pattern to search for.
- returns: array
### replace()
Replaces all or a specified number of matches of a pattern with a replacement
string and returns the resulting string.
- pattern: string or regex (positional, required)
The pattern to search for.
- replacement: string or function (positional, required)
The string to replace the matches with or a function that gets a dictionary for each match and can return individual replacement strings.
- count: integer (named)
If given, only the first `count` matches of the pattern are placed.
- returns: string
### trim()
Removes matches of a pattern from one or both sides of the string, once or
repeatedly and returns the resulting string.
- pattern: string or regex (positional, required)
The pattern to search for.
- at: alignment (named)
Can be `start` or `end` to only trim the start or end of the string.
If omitted, both sides are trimmed.
- repeat: boolean (named)
Whether to repeatedly removes matches of the pattern or just once.
Defaults to `{true}`.
- returns: string
### split()
Splits a string at matches of a specified pattern and returns an array of
the resulting parts.
- pattern: string or regex (positional)
The pattern to split at. Defaults to whitespace.
- returns: array
# Content
A piece of document content.
This type is at the heart of Typst. All markup you write and most
[functions]($type/function) you call produce content values. You can create a
content value by enclosing markup in square brackets. This is also how you pass
content to functions.
```example
Type of *Hello!* is
#type([*Hello!*])
```
Content can be added with the `+` operator,
[joined together]($scripting/#blocks) and multiplied with
integers. Wherever content is expected, you can also pass a
[string]($type/string) or `{none}`.
## Representation
Content consists of elements with fields. When constructing an element with
its _element function,_ you provide these fields as arguments and when you have
a content value, you can access its fields with
[field access syntax]($scripting/#field-access).
Some fields are required: These must be provided when constructing an element
and as a consequence, they are always available through field access on content
of that type. Required fields are marked as such in the documentation.
Most fields are optional: Like required fields, they can be passed to the
element function to configure them for a single element. However, these can also
be configured with [set rules]($styling/#set-rules) to apply them to all
elements within a scope. Optional fields are only available with field access
syntax when they are were explicitly passed to the element function, not when
they result from a set rule.
Each element has a default appearance. However, you can also completely
customize its appearance with a [show rule]($styling/#show-rules). The show rule
is passed the element. It can access the element's field and produce arbitrary
content from it.
In the web app, you can hover over a content variable to see exactly which
elements the content is composed of and what fields they have. Alternatively,
you can inspect the output of the [`repr`]($func/repr) function.
## Methods
### func()
The content's element function. This function can be used to create the element
contained in this content. It can be used in set and show rules for the element.
Can be compared with global functions to check whether you have a specific
kind of element.
- returns: function
### has()
Whether the content has the specified field.
- field: string (positional, required)
The field to look for.
- returns: boolean
### at()
Access the specified field on the content. Returns the default value if the
field does not exist or fails with an error if no default value was specified.
- field: string (positional, required)
The field to access.
- default: any (named)
A default value to return if the field does not exist.
- returns: any
### fields()
Return the fields of this content.
```example
#rect(
width: 10cm,
height: 10cm,
).fields()
```
### location()
The location of the content. This is only available on content returned by
[query]($func/query), for other content it will fail with an error. The
resulting location can be used with [counters]($func/counter),
[state]($func/state) and [queries]($func/query).
- returns: location
# Array
A sequence of values.
You can construct an array by enclosing a comma-separated sequence of values
in parentheses. The values do not have to be of the same type.
You can access and update array items with the `.at()` method. Indices are
zero-based and negative indices wrap around to the end of the array. You can
iterate over an array using a [for loop]($scripting/#loops).
Arrays can be added together with the `+` operator,
[joined together]($scripting/#blocks) and multiplied with
integers.
**Note:** An array of length one needs a trailing comma, as in `{(1,)}`. This is
to disambiguate from a simple parenthesized expressions like `{(1 + 2) * 3}`.
An empty array is written as `{()}`.
## Example
```example
#let values = (1, 7, 4, -3, 2)
#values.at(0) \
#(values.at(0) = 3)
#values.at(-1) \
#values.find(calc.even) \
#values.filter(calc.odd) \
#values.map(calc.abs) \
#values.rev() \
#(1, (2, 3)).flatten() \
#(("A", "B", "C")
.join(", ", last: " and "))
```
## Methods
### len()
The number of values in the array.
- returns: integer
### first()
Returns the first item in the array.
May be used on the left-hand side of an assignment.
Fails with an error if the array is empty.
- returns: any
### last()
Returns the last item in the array.
May be used on the left-hand side of an assignment.
Fails with an error if the array is empty.
- returns: any
### at()
Returns the item at the specified index in the array. May be used on the
left-hand side of an assignment. Returns the default value if the index is out
of bounds or fails with an error if no default value was specified.
- index: integer (positional, required)
The index at which to retrieve the item.
- default: any (named)
A default value to return if the index is out of bounds.
- returns: any
### push()
Add a value to the end of the array.
- value: any (positional, required)
The value to insert at the end of the array.
### pop()
Remove the last item from the array and return it.
Fails with an error if the array is empty.
- returns: any
The removed last value.
### insert()
Insert a value into the array at the specified index.
Fails with an error if the index is out of bounds.
- index: integer (positional, required)
The index at which to insert the item.
- value: any (positional, required)
The value to insert into the array.
### remove()
Remove the value at the specified index from the array and return it.
- index: integer (positional, required)
The index at which to remove the item.
- returns: any
### slice()
Extract a subslice of the array.
Fails with an error if the start or index is out of bounds.
- start: integer (positional, required)
The start index (inclusive).
- end: integer (positional)
The end index (exclusive). If omitted, the whole slice until the end of the
array is extracted.
- count: integer (named)
The number of items to extract. This is equivalent to passing `start +
count` as the `end` position. Mutually exclusive with `end`.
- returns: array
### contains()
Whether the array contains the specified value.
This method also has dedicated syntax: You can write `{2 in (1, 2, 3)}` instead
of `{(1, 2, 3).contains(2)}`.
- value: any (positional, required)
The value to search for.
- returns: boolean
### find()
Searches for an item for which the given function returns `{true}` and
returns the first match or `{none}` if there is no match.
- searcher: function (positional, required)
The function to apply to each item. Must return a boolean.
- returns: any or none
### position()
Searches for an item for which the given function returns `{true}` and
returns the index of the first match or `{none}` if there is no match.
- searcher: function (positional, required)
The function to apply to each item. Must return a boolean.
- returns: integer or none
### filter()
Produces a new array with only the items from the original one for which the
given function returns true.
- test: function (positional, required)
The function to apply to each item. Must return a boolean.
- returns: array
### map()
Produces a new array in which all items from the original one were
transformed with the given function.
- mapper: function (positional, required)
The function to apply to each item.
- returns: array
### enumerate()
Returns a new array with the values alongside their indices.
The returned array consists of `(index, value)` pairs in the form of length-2
arrays. These can be [destructured]($scripting/#bindings) with a let binding or
for loop.
- returns: array
### zip()
Zips the array with another array. If the two arrays are of unequal length, it
will only zip up until the last element of the smaller array and the remaining
elements will be ignored. The return value is an array where each element is yet
another array of size 2.
- other: array (positional, required)
The other array which should be zipped with the current one.
- returns: array
### fold()
Folds all items into a single value using an accumulator function.
- init: any (positional, required)
The initial value to start with.
- folder: function (positional, required)
The folding function. Must have two parameters: One for the accumulated value
and one for an item.
- returns: any
### sum()
Sums all items (works for any types that can be added).
- default: any (named)
What to return if the array is empty. Must be set if the array can be empty.
- returns: any
### product()
Calculates the product all items (works for any types that can be multiplied)
- default: any (named)
What to return if the array is empty. Must be set if the array can be empty.
- returns: any
### any()
Whether the given function returns `{true}` for any item in the array.
- test: function (positional, required)
The function to apply to each item. Must return a boolean.
- returns: boolean
### all()
Whether the given function returns `{true}` for all items in the array.
- test: function (positional, required)
The function to apply to each item. Must return a boolean.
- returns: boolean
### flatten()
Combine all nested arrays into a single flat one.
- returns: array
### rev()
Return a new array with the same items, but in reverse order.
- returns: array
### join()
Combine all items in the array into one.
- separator: any (positional)
A value to insert between each item of the array.
- last: any (named)
An alternative separator between the last two items
- returns: any
### sorted()
Return a new array with the same items, but sorted.
- key: function (named)
If given, applies this function to the elements in the array to determine the keys to sort by.
- returns: array
# Dictionary
A map from string keys to values.
You can construct a dictionary by enclosing comma-separated `key: value` pairs
in parentheses. The values do not have to be of the same type. Since empty
parentheses already yield an empty array, you have to use the special `(:)`
syntax to create an empty dictionary.
A dictionary is conceptually similar to an array, but it is indexed by strings
instead of integers. You can access and create dictionary entries with the
`.at()` method. If you know the key statically, you can alternatively use
[field access notation]($scripting/#fields) (`.key`) to access
the value. Dictionaries can be added with the `+` operator and
[joined together]($scripting/#blocks).
To check whether a key is present in the dictionary, use the `in` keyword.
You can iterate over the pairs in a dictionary using a
[for loop]($scripting/#loops). This will iterate in the order the pairs were
inserted / declared.
## Example
```example
#let dict = (
name: "Typst",
born: 2019,
)
#dict.name \
#(dict.launch = 20)
#dict.len() \
#dict.keys() \
#dict.values() \
#dict.at("born") \
#dict.insert("city", "Berlin ")
#("name" in dict)
```
## Methods
### len()
The number of pairs in the dictionary.
- returns: integer
### at()
Returns the value associated with the specified key in the dictionary. May be
used on the left-hand side of an assignment if the key is already present in the
dictionary. Returns the default value if the key is not part of the dictionary
or fails with an error if no default value was specified.
- key: string (positional, required)
The key at which to retrieve the item.
- default: any (named)
A default value to return if the key is not part of the dictionary.
- returns: any
### insert()
Insert a new pair into the dictionary and return the value.
If the dictionary already contains this key, the value is updated.
- key: string (positional, required)
The key of the pair that should be inserted.
- value: any (positional, required)
The value of the pair that should be inserted.
### keys()
Returns the keys of the dictionary as an array in insertion order.
- returns: array
### values()
Returns the values of the dictionary as an array in insertion order.
- returns: array
### pairs()
Returns the keys and values of the dictionary as an array of pairs. Each pair is
represented as an array of length two.
- returns: array
### remove()
Remove a pair from the dictionary by key and return the value.
- key: string (positional, required)
The key of the pair that should be removed.
- returns: any
# Function
A mapping from argument values to a return value.
You can call a function by writing a comma-separated list of function
_arguments_ enclosed in parentheses directly after the function name.
Additionally, you can pass any number of trailing content blocks arguments to a
function _after_ the normal argument list. If the normal argument list would
become empty, it can be omitted. Typst supports positional and named arguments.
The former are identified by position and type, while the later are written as
`name: value`.
Within math mode, function calls have special behaviour. See the
[math documentation]($category/math) for more details.
### Example
```example
// Call a function.
#list([A], [B])
// Named arguments and trailing
// content blocks.
#enum(start: 2)[A][B]
// Version without parentheses.
#list[A][B]
```
Functions are a fundamental building block of Typst. Typst provides functions
for a variety of typesetting tasks. Moreover, the markup you write is backed by
functions and all styling happens through functions. This reference lists all
available functions and how you can use them. Please also refer to the
documentation about [set]($styling/#set-rules) and
[show]($styling/#show-rules) rules to learn about additional ways
you can work with functions in Typst.
### Element functions { #element-functions }
Some functions are associated with _elements_ like [headings]($func/heading) or
[tables]($func/table). When called, these create an element of their respective
kind. In contrast to normal functions, they can further be used in
[set rules]($styling/#set-rules), [show rules]($styling/#show-rules), and
[selectors]($type/selector).
### Function scopes { #function-scopes }
Functions can hold related definitions in their own scope, similar to a
[module]($scripting/#modules). Examples of this are
[`assert.eq`]($func/assert.eq) or [`list.item`]($func/list.item). However, this
feature is currently only available for built-in functions.
### Defining functions { #definitions }
You can define your own function with a
[let binding]($scripting/#bindings) that has a parameter list after
the binding's name. The parameter list can contain positional parameters,
named parameters with default values and
[argument sinks]($type/arguments).
The right-hand side of the binding can be a block or any other expression. It
defines the function's return value and can depend on the parameters.
```example
#let alert(body, fill: red) = {
set text(white)
set align(center)
rect(
fill: fill,
inset: 8pt,
radius: 4pt,
[*Warning:\ #body*],
)
}
#alert[
Danger is imminent!
]
#alert(fill: blue)[
KEEP OFF TRACKS
]
```
### Unnamed functions { #unnamed }
You can also created an unnamed function without creating a binding by
specifying a parameter list followed by `=>` and the function body. If your
function has just one parameter, the parentheses around the parameter list are
optional. Unnamed functions are mainly useful for show rules, but also for
settable properties that take functions like the page function's
[`footer`]($func/page.footer) property.
```example
#show "once?": it => [#it #it]
once?
```
### Notable fact
In Typst, all functions are _pure._ This means that for the same
arguments, they always return the same result. They cannot "remember" things to
produce another value when they are called a second time.
The only exception are built-in methods like
[`array.push(value)`]($type/array.push). These can modify the values they are
called on.
## Methods
### with()
Returns a new function that has the given arguments pre-applied.
- arguments: any (variadic)
The named and positional arguments to apply.
- returns: function
### where()
Returns a selector that filters for elements belonging to this function
whose fields have the values of the given arguments.
- fields: any (named, variadic)
The field values to filter by.
- returns: selector
# Arguments
Captured arguments to a function.
Like built-in functions, custom functions can also take a variable number of
arguments. You can specify an _argument sink_ which collects all excess
arguments as `..sink`. The resulting `sink` value is of the `arguments` type. It
exposes methods to access the positional and named arguments and is iterable
with a [for loop]($scripting/#loops). Inversely, you can spread
arguments, arrays and dictionaries into a function call with the spread operator:
`{func(..args)}`.
## Example
```example
#let format(title, ..authors) = [
*#title* \
_Written by #(authors
.pos()
.join(", ", last: " and "));._
]
#format("ArtosFlow", "Jane", "Joe")
```
## Methods
### pos()
Returns the captured positional arguments as an array.
- returns: array
### named()
Returns the captured named arguments as a dictionary.
- returns: dictionary
# Selector
A filter for selecting elements within the document.
You can construct a selector in the following ways:
- you can use an element [function]($type/function)
- you can filter for an element function with
[specific fields]($type/function.where)
- you can use a [string]($type/string) or [regular expression]($func/regex)
- you can use a [`{<label>}`]($func/label)
- you can use a [`location`]($func/locate)
- call the [`selector`]($func/selector) function to convert any of the above
types into a selector value and use the methods below to refine it
Selectors are used to [apply styling rules]($styling/#show-rules) to elements.
You can also use selectors to [query]($func/query) the document for certain
types of elements.
Furthermore, you can pass a selector to several of Typst's built-in functions to
configure their behaviour. One such example is the [outline]($func/outline)
where it can be used to change which elements are listed within the outline.
Multiple selectors can be combined using the methods shown below. However, not
all kinds of selectors are supported in all places, at the moment.
## Example
```example
#locate(loc => query(
heading.where(level: 1)
.or(heading.where(level: 2)),
loc,
))
= This will be found
== So will this
=== But this will not.
```
## Methods
### or()
Allows combining any of a series of selectors. This is used to
select multiple components or components with different properties
all at once.
- other: selector (variadic, required)
The list of selectors to match on.
### and()
Allows combining all of a series of selectors. This is used to check
whether a component meets multiple selection rules simultaneously.
- other: selector (variadic, required)
The list of selectors to match on.
### before()
Returns a modified selector that will only match elements that occur before the
first match of the selector argument.
- end: selector (positional, required)
The original selection will end at the first match of `end`.
- inclusive: boolean (named)
Whether `end` itself should match or not. This is only relevant if both
selectors match the same type of element. Defaults to `{true}`.
### after()
Returns a modified selector that will only match elements that occur after the
first match of the selector argument.
- start: selector (positional, required)
The original selection will start at the first match of `start`.
- inclusive: boolean (named)
Whether `start` itself should match or not. This is only relevant if both
selectors match the same type of element. Defaults to `{true}`.
# Module
An evaluated module, either built-in or resulting from a file.
You can access definitions from the module using
[field access notation]($scripting/#fields) and interact with it using the
[import and include syntaxes]($scripting/#modules).
## Example
```example
<<< #import "utils.typ"
<<< #utils.add(2, 5)
<<< #import utils: sub
<<< #sub(1, 4)
>>> #7
>>>
>>> #(-3)
```
|
https://github.com/paugarcia32/CV | https://raw.githubusercontent.com/paugarcia32/CV/main/modules_es/skills.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Habilidades")
#cvSkill(
type: [Idiomas],
info: [Español #hBar() Catalán #hBar() Inglés ]
)
#cvSkill(
type: [Soft Skills],
info: [Voluntad de aprender #hBar() Trabajo en equipo #hBar() Metodologías Agile y SCRUM #hBar() Resolución de problemas]
)
#cvSkill(
type: [Aficiones],
info: [Artes Marciales #hBar() Electrónica #hBar() Lectura #hBar() Musica]
)
|
Subsets and Splits