repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/037.%20start.html.typ | typst | start.html
How to Start a Startup
Want to start a startup? Get funded by
Y Combinator.
March 2005(This essay is derived from a talk at the Harvard Computer
Society.)You need three things to create a successful startup: to start with
good people, to make something customers actually want, and to spend
as little money as possible. Most startups that fail do it because
they fail at one of these. A startup that does all three will
probably succeed.And that's kind of exciting, when you think about it, because all
three are doable. Hard, but doable. And since a startup that
succeeds ordinarily makes its founders rich, that implies getting
rich is doable too. Hard, but doable.If there is one message I'd like to get across about startups,
that's it. There is no magically difficult step that requires
brilliance to solve.The IdeaIn particular, you don't need a brilliant
idea to start a startup
around. The way a startup makes money is to offer people better
technology than they have now. But what people have now is often
so bad that it doesn't take brilliance to do better.Google's plan, for example, was simply to create a search site that
didn't suck. They had three new ideas: index more of the Web, use
links to rank search results, and have clean, simple web pages with
unintrusive keyword-based ads. Above all, they were determined to
make a site that was good to use. No doubt there are great technical
tricks within Google, but the overall plan was straightforward.
And while they probably have bigger ambitions now, this alone brings
them a billion dollars a year. [1]There are plenty of other areas that are just as backward as search
was before Google. I can think of several heuristics for generating
ideas for startups, but most reduce to this: look at something
people are trying to do, and figure out how to do it in a way that
doesn't suck.For example, dating sites currently suck far worse than search did
before Google. They all use the same simple-minded model.
They seem to have approached the problem by thinking about how to
do database matches instead of how dating works in the real world.
An undergrad could build something better as a class project. And
yet there's a lot of money at stake. Online dating is a valuable
business now, and it might be worth a hundred times as much if it
worked.An idea for a startup, however, is only a beginning. A lot of
would-be startup founders think the key to the whole process is the
initial idea, and from that point all you have to do is execute.
Venture capitalists know better. If you go to VC firms with a
brilliant idea that you'll tell them about if they sign a nondisclosure
agreement, most will tell you to get lost. That shows how much a
mere idea is worth. The market price is less than the inconvenience
of signing an NDA.Another sign of how little the initial idea is worth is the number
of startups that change their plan en route. Microsoft's original
plan was to make money selling programming languages, of all things.
Their current business model didn't occur to them until IBM dropped
it in their lap five years later.Ideas for startups are worth something, certainly, but the trouble
is, they're not transferrable. They're not something you could
hand to someone else to execute. Their value is mainly as starting
points: as questions for the people who had them to continue thinking
about.What matters is not ideas, but the people who have them. Good
people can fix bad ideas, but good ideas can't save bad people.
PeopleWhat do I mean by good people? One of the best tricks I learned
during our startup was a rule for deciding
who to hire. Could you
describe the person as an animal? It might be hard to translate
that into another language, but I think everyone in the US knows
what it means. It means someone who takes their work a little too
seriously; someone who does what they do so well that they pass
right through professional and cross over into obsessive.What it means specifically depends on the job: a salesperson who
just won't take no for an answer; a hacker who will stay up till
4:00 AM rather than go to bed leaving code with a bug in it; a PR
person who will cold-call New York Times reporters on their cell
phones; a graphic designer who feels physical pain when something
is two millimeters out of place.Almost everyone who worked for us was an animal at what they did.
The woman in charge of sales was so tenacious that I used to feel
sorry for potential customers on the phone with her. You could
sense them squirming on the hook, but you knew there would be no
rest for them till they'd signed up.If you think about people you know, you'll find the animal test is
easy to apply. Call the person's image to mind and imagine the
sentence "so-and-so is an animal." If you laugh, they're not. You
don't need or perhaps even want this quality in big companies, but
you need it in a startup.For programmers we had three additional tests. Was the person
genuinely smart? If so, could they actually get things done? And
finally, since a few good hackers have unbearable personalities,
could we stand to have them around?That last test filters out surprisingly few people. We could bear
any amount of nerdiness if someone was truly smart. What we couldn't
stand were people with a lot of attitude. But most of those weren't
truly smart, so our third test was largely a restatement of the
first.When nerds are unbearable it's usually because they're trying too
hard to seem smart. But the smarter they are, the less pressure
they feel to act smart. So as a rule you can recognize genuinely
smart people by their ability to say things like "I don't know,"
"Maybe you're right," and "I don't understand x well enough."This technique doesn't always work, because people can be influenced
by their environment. In the MIT CS department, there seems to be
a tradition of acting like a brusque know-it-all. I'm told it derives
ultimately from <NAME>, in the same way the classic airline
pilot manner is said to derive from <NAME>. Even genuinely
smart people start to act this way there, so you have to make
allowances.It helped us to have <NAME>, who is one of the readiest to
say "I don't know" of anyone I've met. (At least, he was before he
became a professor at MIT.) No one dared put on attitude around
Robert, because he was obviously smarter than they were and yet had
zero attitude himself.Like most startups, ours began with a group of friends, and it was
through personal contacts that we got most of the people we hired.
This is a crucial difference between startups and big companies.
Being friends with someone for even a couple days will tell you
more than companies could ever learn in interviews. [2]It's no coincidence that startups start around universities, because
that's where smart people meet. It's not what people learn in
classes at MIT and Stanford that has made technology companies
spring up around them. They could sing campfire songs in the classes
so long as admissions worked the same.If you start a startup, there's a good chance it will be with people
you know from college or grad school. So in theory you ought to
try to make friends with as many smart people as you can in school,
right? Well, no. Don't make a conscious effort to schmooze; that
doesn't work well with hackers.What you should do in college is work on your own projects. Hackers
should do this even if they don't plan to start startups, because
it's the only real way to learn how to program. In some cases you
may collaborate with other students, and this is the best way to
get to know good hackers. The project may even grow into a startup.
But once again, I wouldn't aim too directly at either target. Don't
force things; just work on stuff you like with people you like.Ideally you want between two and four founders. It would be hard
to start with just one. One person would find the moral weight of
starting a company hard to bear. Even <NAME>, who seems to be
able to bear a good deal of moral weight, had to have a co-founder.
But you don't want so many founders that the company starts to look
like a group photo. Partly because you don't need a lot of people
at first, but mainly because the more founders you have, the worse
disagreements you'll have. When there are just two or three founders,
you know you have to resolve disputes immediately or perish. If
there are seven or eight, disagreements can linger and harden into
factions. You don't want mere voting; you need unanimity.In a technology startup, which most startups are, the founders
should include technical people. During the Internet Bubble there
were a number of startups founded by business people who then went
looking for hackers to create their product for them. This doesn't
work well. Business people are bad at deciding what to do with
technology, because they don't know what the options are, or which
kinds of problems are hard and which are easy. And when business
people try to hire hackers, they can't tell which ones are
good.
Even other hackers have a hard time doing that.
For business people it's roulette.Do the founders of a startup have to include business people? That
depends. We thought so when we started ours, and we asked several
people who were said to know about this mysterious thing called
"business" if they would be the president. But they all said no,
so I had to do it myself. And what I discovered was that business
was no great mystery. It's not something like physics or medicine
that requires extensive study. You just try to get people to pay
you for stuff.I think the reason I made such a mystery of business was that I was
disgusted by the idea of doing it. I wanted to work in the pure,
intellectual world of software, not deal with customers' mundane
problems. People who don't want to get dragged into some kind of
work often develop a protective incompetence at it. <NAME> was
particularly good at this. By seeming unable even to cut a grapefruit
in half (let alone go to the store and buy one), he forced other
people to do such things for him, leaving all his time free for
math. Erdos was an extreme case, but most husbands use the same
trick to some degree.Once I was forced to discard my protective incompetence, I found
that business was neither so hard nor so boring as I feared. There
are esoteric areas of business that are quite hard, like tax law
or the pricing of derivatives, but you don't need to know about
those in a startup. All you need to know about business to run a
startup are commonsense things people knew before there were business
schools, or even universities.If you work your way down the Forbes 400 making an x next to the
name of each person with an MBA, you'll learn something important
about business school. After Warren Buffett, you don't hit another
MBA till number 22,
<NAME>, the CEO of Nike. There are only 5 MBAs in the top
50. What you notice in the Forbes 400 are a lot of people with
technical backgrounds. <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>. The rulers of the technology
business tend to come from technology, not business. So if you
want to invest two years in something that will help you succeed
in business, the evidence suggests you'd do better to learn how to
hack than get an MBA. [3]There is one reason you might want to include business people in a
startup, though: because you have to have at least one person willing
and able to focus on what customers want. Some believe only business
people can do this-- that hackers can implement software, but not
design it. That's nonsense. There's nothing about knowing how to
program that prevents hackers from understanding users, or about
not knowing how to program that magically enables business people
to understand them.If you can't understand users, however, you should either learn how
or find a co-founder who can. That is the single most important
issue for technology startups, and the rock that sinks more of them
than anything else.What Customers WantIt's not just startups that have to worry about this. I think most
businesses that fail do it because they don't give customers what
they want. Look at restaurants. A large percentage fail, about a
quarter in the first year. But can you think of one restaurant
that had really good food and went out of business?Restaurants with great food seem to prosper no matter what. A
restaurant with great food can be expensive, crowded, noisy, dingy,
out of the way, and even have bad service, and people will keep
coming. It's true that a restaurant with mediocre food can sometimes
attract customers through gimmicks. But that approach is very
risky. It's more straightforward just to make the food good.It's the same with technology. You hear all kinds of reasons why
startups fail. But can you think of one that had a massively popular
product and still failed?In nearly every failed startup, the real problem was that customers
didn't want the product. For most, the cause of death is listed
as "ran out of funding," but that's only the immediate cause. Why
couldn't they get more funding? Probably because the product was
a dog, or never seemed likely to be done, or both.When I was trying to think of the things every startup needed to
do, I almost included a fourth: get a version 1 out as soon as you
can. But I decided not to, because that's implicit in making
something customers want. The only way to make something customers
want is to get a prototype in front of them and refine it based on
their reactions.The other approach is what I call the "Hail Mary" strategy. You
make elaborate plans for a product, hire a team of engineers to
develop it (people who do this tend to use the term "engineer" for
hackers), and then find after a year that you've spent two million
dollars to develop something no one wants. This was not uncommon
during the Bubble, especially in companies run by business types,
who thought of software development as something terrifying that
therefore had to be carefully planned.We never even considered that approach. As a Lisp hacker, I come
from the tradition of rapid prototyping. I would not claim (at
least, not here) that this is the right way to write every program,
but it's certainly the right way to write software for a startup.
In a startup, your initial plans are almost certain to be wrong in
some way, and your first priority should be to figure out where.
The only way to do that is to try implementing them.Like most startups, we changed our plan on the fly. At first we
expected our customers to be Web consultants. But it turned out
they didn't like us, because our software was easy to use and we hosted
the site. It would be too easy for clients to fire them. We also
thought we'd be able to sign up a lot of catalog companies, because
selling online was a natural extension of their existing business.
But in 1996 that was a hard sell. The middle managers we talked
to at catalog companies saw the Web not as an opportunity, but as
something that meant more work for them.We did get a few of the more adventurous catalog companies. Among
them was Frederick's of Hollywood, which gave us valuable experience
dealing with heavy loads on our servers. But most of our users
were small, individual merchants who saw the Web as an opportunity
to build a business. Some had retail stores, but many only existed
online. And so we changed direction to focus on these users.
Instead of concentrating on the features Web consultants and catalog
companies would want, we worked to make the software easy to use.I learned something valuable from that. It's worth trying very,
very hard to make technology easy to use. Hackers are so used to
computers that they have no idea how horrifying software seems to
normal people. <NAME>'s editor told him that every equation
he included in his book would cut sales in half. When you work on
making technology easier to use, you're riding that curve up instead
of down. A 10% improvement in ease of use doesn't just increase
your sales 10%. It's more likely to double your sales.How do you figure out what customers want? Watch them. One of the
best places to do this was at trade shows. Trade shows didn't pay
as a way of getting new customers, but they were worth it as market
research. We didn't just give canned presentations at trade shows.
We used to show people how to build real, working stores. Which
meant we got to watch as they used our software, and talk to them
about what they needed.No matter what kind of startup you start, it will probably be a
stretch for you, the founders, to understand what users want. The
only kind of software you can build without studying users is the
sort for which you are the typical user. But this is just the kind
that tends to be open source: operating systems, programming
languages, editors, and so on. So if you're developing technology
for money, you're probably not going to be developing it for people
like you. Indeed, you can use this as a way to generate ideas for
startups: what do people who are not like you want from technology?When most people think of startups, they think of companies like
Apple or Google. Everyone knows these, because they're big consumer
brands. But for every startup like that, there are twenty more
that operate in niche markets or live quietly down in the infrastructure.
So if you start a successful startup, odds are you'll start one of
those.Another way to say that is, if you try to start the kind of startup
that has to be a big consumer brand, the odds against succeeding
are steeper. The best odds are in niche markets. Since startups
make money by offering people something better than they had before,
the best opportunities are where things suck most. And it would
be hard to find a place where things suck more than in corporate
IT departments. You would not believe the amount of money companies
spend on software, and the crap they get in return. This imbalance
equals opportunity.If you want ideas for startups, one of the most valuable things you
could do is find a middle-sized non-technology company and spend a
couple weeks just watching what they do with computers. Most good
hackers have no more idea of the horrors perpetrated in these places
than rich Americans do of what goes on in Brazilian slums.Start by writing software for smaller companies, because it's easier
to sell to them. It's worth so much to sell stuff to big companies
that the people selling them the crap they currently use spend a
lot of time and money to do it. And while you can outhack Oracle
with one frontal lobe tied behind your back, you can't outsell an
Oracle salesman. So if you want to win through better technology,
aim at smaller customers. [4]They're the more strategically valuable part of the market anyway.
In technology, the low end always eats the high end. It's easier
to make an inexpensive product more powerful than to make a powerful
product cheaper. So the products that start as cheap, simple options
tend to gradually grow more powerful till, like water rising in a
room, they squash the "high-end" products against the ceiling. Sun
did this to mainframes, and Intel is doing it to Sun. Microsoft
Word did it to desktop publishing software like Interleaf and
Framemaker. Mass-market digital cameras are doing it to the expensive
models made for professionals. Avid did it to the manufacturers
of specialized video editing systems, and now Apple is doing it to
Avid. <NAME> did it to the car makers that preceded
him. If you build the simple, inexpensive option, you'll not only
find it easier to sell at first, but you'll also be in the best
position to conquer the rest of the market.It's very dangerous to let anyone fly under you. If you have the
cheapest, easiest product, you'll own the low end. And if you
don't, you're in the crosshairs of whoever does.Raising MoneyTo make all this happen, you're going to need money. Some startups
have been self-funding-- Microsoft for example-- but most aren't.
I think it's wise to take money from investors. To be self-funding,
you have to start as a consulting company, and it's hard to switch
from that to a product company.Financially, a startup is like a pass/fail course. The way to get
rich from a startup is to maximize the company's chances of succeeding,
not to maximize the amount of stock you retain. So if you can trade
stock for something that improves your odds, it's probably a smart
move.To most hackers, getting investors seems like a terrifying and
mysterious process. Actually it's merely tedious. I'll try to
give an outline of how it works.The first thing you'll need is a few tens of thousands of dollars
to pay your expenses while you develop a prototype. This is called
seed capital. Because so little money is involved, raising seed
capital is comparatively easy-- at least in the sense of getting a
quick yes or no.Usually you get seed money from individual rich people called
"angels." Often they're people who themselves got rich from technology.
At the seed stage, investors don't expect you to have an elaborate
business plan. Most know that they're supposed to decide quickly.
It's not unusual to get a check within a week based on a half-page
agreement.We started Viaweb with $10,000 of seed money from our friend Julian.
But he gave us a lot more than money. He's a former CEO and also
a corporate lawyer, so he gave us a lot of valuable advice about
business, and also did all the legal work of getting us set up as
a company. Plus he introduced us to one of the two
angel investors who supplied our next round of funding.Some angels, especially those with technology backgrounds, may be
satisfied with a demo and a verbal description of what you plan to
do. But many will want a copy of your business plan, if only to
remind themselves what they invested in.Our angels asked for one, and looking back, I'm amazed how much
worry it caused me. "Business plan" has that word "business" in
it, so I figured it had to be something I'd have to read a book
about business plans to write. Well, it doesn't. At this stage,
all most investors expect is a brief description of what you plan
to do and how you're going to make money from it, and the resumes
of the founders. If you just sit down and write out what you've
been saying to one another, that should be fine. It shouldn't take
more than a couple hours, and you'll probably find that writing it
all down gives you more ideas about what to do.For the angel to have someone to make the check out to, you're going
to have to have some kind of company. Merely incorporating yourselves
isn't hard. The problem is, for the company to exist, you have to
decide who the founders are, and how much stock they each have. If
there are two founders with the same qualifications who are both
equally committed to the business, that's easy. But if you have a
number of people who are expected to contribute in varying degrees,
arranging the proportions of stock can be hard. And once you've
done it, it tends to be set in stone.I have no tricks for dealing with this problem. All I can say is,
try hard to do it right. I do have a rule of thumb for recognizing
when you have, though. When everyone feels they're getting a
slightly bad deal, that they're doing more than they should for the
amount of stock they have, the stock is optimally apportioned.There is more to setting up a company than incorporating it, of
course: insurance, business license, unemployment compensation,
various things with the IRS. I'm not even sure what the list is,
because we, ah, skipped all that. When we got real funding near
the end of 1996, we hired a great CFO, who fixed everything
retroactively. It turns out that no one comes and arrests you if
you don't do everything you're supposed to when starting a company.
And a good thing too, or a lot of startups would never get started.
[5]It can be dangerous to delay turning yourself into a company, because
one or more of the founders might decide to split off and start
another company doing the same thing. This does happen. So when
you set up the company, as well as as apportioning the stock, you
should get all the founders to sign something agreeing that everyone's
ideas belong to this company, and that this company is going to be
everyone's only job.[If this were a movie, ominous music would begin here.]While you're at it, you should ask what else they've signed. One
of the worst things that can happen to a startup is to run into
intellectual property problems. We did, and it came closer to
killing us than any competitor ever did.As we were in the middle of getting bought, we discovered that one
of our people had, early on, been bound by an agreement that said
all his ideas belonged to the giant company that was paying for him
to go to grad school. In theory, that could have meant someone
else owned big chunks of our software. So the acquisition came to
a screeching halt while we tried to sort this out. The problem
was, since we'd been about to be acquired, we'd allowed ourselves
to run low on cash. Now we needed to raise more to keep going.
But it's hard to raise money with an IP cloud over your head, because
investors can't judge how serious it is.Our existing investors, knowing that we needed money and had nowhere
else to get it, at this point attempted certain gambits which I
will not describe in detail, except to remind readers that the word
"angel" is a metaphor. The founders thereupon proposed to walk
away from the company, after giving the investors a brief tutorial
on how to administer the servers themselves. And while this was
happening, the acquirers used the delay as an excuse to welch on
the deal.Miraculously it all turned out ok. The investors backed down; we
did another round of funding at a reasonable valuation; the giant
company finally gave us a piece of paper saying they didn't own our
software; and six months later we were bought by Yahoo for much
more than the earlier acquirer had agreed to pay. So we were happy
in the end, though the experience probably took several years off
my life.Don't do what we did. Before you consummate a startup, ask
everyone about their previous IP history.Once you've got a company set up, it may seem presumptuous to go
knocking on the doors of rich people and asking them to invest tens
of thousands of dollars in something that is really just a bunch
of guys with some ideas. But when you look at it from the rich
people's point of view, the picture is more encouraging. Most rich
people are looking for good investments. If you really think you
have a chance of succeeding, you're doing them a favor by letting
them invest. Mixed with any annoyance they might feel about being
approached will be the thought: are these guys the next Google?Usually angels are financially equivalent to founders. They get
the same kind of stock and get diluted the same amount in future
rounds. How much stock should they get? That depends on how
ambitious you feel. When you offer x percent of your company for
y dollars, you're implicitly claiming a certain value for the whole
company. Venture investments are usually described in terms of
that number. If you give an investor new shares equal to 5% of
those already outstanding in return for $100,000, then you've done
the deal at a pre-money valuation of $2 million.How do you decide what the value of the company should be? There
is no rational way. At this stage the company is just a bet. I
didn't realize that when we were raising money. Julian
thought we ought to value the company at several million
dollars. I thought it was preposterous to claim that a couple
thousand lines of code, which was all we had at the time, were worth
several million dollars. Eventually we settled on one million,
because Julian said no one would invest in a company with a valuation
any lower. [6]What I didn't grasp at the time was that the valuation wasn't just
the value of the code we'd written so far. It was also the value
of our ideas, which turned out to be right, and of all the future
work we'd do, which turned out to be a lot.The next round of funding is the one in which you might deal with
actual
venture capital firms.
But don't wait till you've burned
through your last round of funding to start approaching them. VCs are slow to
make up their minds. They can take months. You don't want to be
running out of money while you're trying to negotiate with them.Getting money from an actual VC firm is a bigger deal than getting
money from angels. The amounts of money involved are larger, millions
usually. So the deals take longer, dilute you more, and impose
more onerous conditions.Sometimes the VCs want to install a new CEO of their own choosing.
Usually the claim is that you need someone mature and experienced,
with a business background. Maybe in some cases this is true. And
yet <NAME> was young and inexperienced and had no business
background, and he seems to have done ok. <NAME> got booted
out of his own company by someone mature and experienced, with a
business background, who then proceeded to ruin the company. So I
think people who are mature and experienced, with a business
background, may be overrated. We used to call these guys "newscasters,"
because they had neat hair and spoke in deep, confident voices, and
generally didn't know much more than they read on the teleprompter.We talked to a number of VCs, but eventually we ended up financing
our startup entirely with angel money. The main reason was that
we feared a brand-name VC firm would stick us with a newscaster as
part of the deal. That might have been ok if he was content to
limit himself to talking to the press, but what if he wanted to
have a say in running the company? That would have led to disaster,
because our software was so complex. We were a company whose whole
m.o. was to win through better technology. The strategic decisions
were mostly decisions about technology, and we didn't need any help
with those.This was also one reason we didn't go public. Back in 1998 our CFO
tried to talk me into it. In those days you could go public as a
dogfood portal, so as a company with a real product and real revenues,
we might have done well. But I feared it would have meant taking
on a newscaster-- someone who, as they say, "can talk Wall Street's
language."I'm happy to see Google is bucking that trend. They didn't talk
Wall Street's language when they did their IPO, and Wall Street
didn't buy. And now Wall Street is collectively kicking itself.
They'll pay attention next time. Wall Street learns new languages
fast when money is involved.You have more leverage negotiating with VCs than you realize. The
reason is other VCs. I know a number of VCs now, and when you talk
to them you realize that it's a seller's market. Even now there
is too much money chasing too few good deals.VCs form a pyramid. At the top are famous ones like Sequoia and
Kleiner Perkins, but beneath those are a huge number you've never
heard of. What they all have in common is that a dollar from them
is worth one dollar. Most VCs will tell you that they don't just
provide money, but connections and advice. If you're talking to
<NAME> or <NAME> or <NAME>, this is true. But such
advice and connections can come very expensive. And as you go down
the food chain the VCs get rapidly
dumber. A few steps down from
the top you're basically talking to bankers who've picked up a few
new vocabulary words from reading Wired. (Does your product
use XML?) So I'd advise you to be skeptical about claims
of experience and connections. Basically, a VC is a source of
money. I'd be inclined to go with whoever offered the most money
the soonest with the least strings attached.You may wonder how much to tell VCs. And you should, because some
of them may one day be funding your competitors. I think the best
plan is not to be overtly secretive, but not to tell them everything
either. After all, as most VCs say, they're more interested in the
people than the ideas. The main reason they want to talk about
your idea is to judge you, not the idea. So as long as you seem
like you know what you're doing, you can probably keep a few things
back from them. [7]Talk to as many VCs as you can, even if you don't want their money,
because a) they may be on the board of someone who will buy you,
and b) if you seem impressive, they'll be discouraged from investing
in your competitors. The most efficient way to reach VCs, especially
if you only want them to know about you and don't want their money,
is at the conferences that are occasionally organized for startups
to present to them.Not Spending ItWhen and if you get an infusion of real money from investors, what
should you do with it? Not spend it, that's what. In nearly every
startup that fails, the proximate cause is running out of money.
Usually there is something deeper wrong. But even a proximate cause
of death is worth trying hard to avoid.During the Bubble many startups tried to "get big fast." Ideally
this meant getting a lot of customers fast. But it was easy for
the meaning to slide over into hiring a lot of people fast.Of the two versions, the one where you get a lot of customers fast
is of course preferable. But even that may be overrated. The idea
is to get there first and get all the users, leaving none for
competitors. But I think in most businesses the advantages of being
first to market are not so overwhelmingly great. Google is again
a case in point. When they appeared it seemed as if search was a
mature market, dominated by big players who'd spent millions to
build their brands: Yahoo, Lycos, Excite, Infoseek, Altavista,
Inktomi. Surely 1998 was a little late to arrive at the party.But as the founders of Google knew, brand is worth next to nothing
in the search business. You can come along at any point and make
something better, and users will gradually seep over to you. As
if to emphasize the point, Google never did any advertising. They're
like dealers; they sell the stuff, but they know better than to use
it themselves.The competitors Google buried would have done better to spend those
millions improving their software. Future startups should learn
from that mistake. Unless you're in a market where products are
as undifferentiated as cigarettes or vodka or laundry detergent,
spending a lot on brand advertising is a sign of breakage. And few
if any Web businesses are so undifferentiated. The dating sites
are running big ad campaigns right now, which is all the
more evidence they're ripe for the picking. (Fee, fie, fo, fum, I
smell a company run by marketing guys.)We were compelled by circumstances to grow slowly, and in retrospect
it was a good thing. The founders all learned to do every job in
the company. As well as writing software, I had to do sales and
customer support. At sales I was not very good. I was persistent,
but I didn't have the smoothness of a good salesman. My message
to potential customers was: you'd be stupid not to sell online, and
if you sell online you'd be stupid to use anyone else's software.
Both statements were true, but that's not the way to convince people.I was great at customer support though. Imagine talking to a
customer support person who not only knew everything about the
product, but would apologize abjectly if there was a bug, and then
fix it immediately, while you were on the phone with them. Customers
loved us. And we loved them, because when you're growing slow by
word of mouth, your first batch of users are the ones who were smart
enough to find you by themselves. There is nothing more valuable,
in the early stages of a startup, than smart users. If you listen
to them, they'll tell you exactly how to make a winning product.
And not only will they give you this advice for free, they'll pay
you.We officially launched in early 1996. By the end of that year we
had about 70 users. Since this was the era of "get big fast," I
worried about how small and obscure we were. But in fact we were
doing exactly the right thing. Once you get big (in users or
employees) it gets hard to change your product. That year was
effectively a laboratory for improving our software. By the end
of it, we were so far ahead of our competitors that they never had
a hope of catching up. And since all the hackers had spent many
hours talking to users, we understood online commerce way better
than anyone else.That's the key to success as a startup. There is nothing more
important than understanding your business. You might think that
anyone in a business must, ex officio, understand it. Far from it.
Google's secret
weapon was simply that they understood search. I was working for
Yahoo when Google appeared, and Yahoo didn't understand search. I
know because I once tried to convince the powers that be that we
had to make search better, and I got in reply what was then the
party line about it: that Yahoo was no longer a mere "search engine."
Search was now only a small percentage of our page views, less than
one month's growth, and now that we were established as a "media
company," or "portal," or whatever we were, search could safely be
allowed to wither and drop off, like an umbilical cord.Well, a small fraction of page views they may be, but they are an
important fraction, because they are the page views that Web sessions
start with. I think Yahoo gets that now.Google understands a few other things most Web companies still
don't. The most important is that you should put users before
advertisers, even though the advertisers are paying and users aren't.
One of my favorite bumper stickers reads "if the people lead, the
leaders will follow." Paraphrased for the Web, this becomes "get
all the users, and the advertisers will follow." More generally,
design your product to please users first, and then think about how
to make money from it. If you don't put users first, you leave a
gap for competitors who do.To make something users love, you have to understand them. And the
bigger you are, the harder that is. So I say "get big slow." The
slower you burn through your funding, the more time you have to
learn.The other reason to spend money slowly is to encourage a culture
of cheapness. That's something Yahoo did understand. <NAME>'s
title was "Chief Yahoo," but he was proud that his unofficial title
was "Cheap Yahoo." Soon after we arrived at Yahoo, we got an email
from Filo, who had been crawling around our directory hierarchy,
asking if it was really necessary to store so much of our data on
expensive RAID drives. I was impressed by that. Yahoo's market
cap then was already in the billions, and they were still worrying
about wasting a few gigs of disk space.When you get a couple million dollars from a VC firm, you tend to
feel rich. It's important to realize you're not. A rich company
is one with large revenues. This money isn't revenue. It's money
investors have given you in the hope you'll be able to generate
revenues. So despite those millions in the bank, you're still poor.For most startups the model should be grad student, not law firm.
Aim for cool and cheap, not expensive and impressive. For us the
test of whether a startup understood this was whether they had Aeron
chairs. The Aeron came out during the Bubble and was very popular
with startups. Especially the type, all too common then, that was
like a bunch of kids playing house with money supplied by VCs. We
had office chairs so cheap that the arms all fell off. This was
slightly embarrassing at the time, but in retrospect the grad-studenty
atmosphere of our office was another of those things we did right
without knowing it.Our offices were in a wooden triple-decker in Harvard Square. It
had been an apartment until about the 1970s, and there was still a
claw-footed bathtub in the bathroom. It must once have been inhabited
by someone fairly eccentric, because a lot of the chinks in the
walls were stuffed with aluminum foil, as if to protect against
cosmic rays. When eminent visitors came to see us, we were a bit
sheepish about the low production values. But in fact that place
was the perfect space for a startup. We felt like our role was to
be impudent underdogs instead of corporate stuffed shirts, and that
is exactly the spirit you want.An apartment is also the right kind of place for developing software.
Cube farms suck for that, as you've probably discovered if you've
tried it. Ever notice how much easier it is to hack at home than
at work? So why not make work more like home?When you're looking for space for a startup, don't feel that it has
to look professional. Professional means doing good work, not
elevators and glass walls. I'd advise most startups to avoid
corporate space at first and just rent an apartment. You want to
live at the office in a startup, so why not have a place designed
to be lived in as your office?Besides being cheaper and better to work in, apartments tend to be
in better locations than office buildings. And for a startup
location is very important. The key to productivity is for people
to come back to work after dinner. Those hours after the phone
stops ringing are by far the best for getting work done. Great
things happen when a group of employees go out to dinner together,
talk over ideas, and then come back to their offices to implement
them. So you want to be in a place where there are a lot of
restaurants around, not some dreary office park that's a wasteland
after 6:00 PM. Once a company shifts over into the model where
everyone drives home to the suburbs for dinner, however late, you've
lost something extraordinarily valuable. God help you if you
actually start in that mode.If I were going to start a startup today, there are only three
places I'd consider doing it: on the Red Line near Central, Harvard,
or Davis Squares (Kendall is too sterile); in Palo Alto on University
or California Aves; and in Berkeley immediately north or south of
campus. These are the only places I know that have the right kind
of vibe.The most important way to not spend money is by not hiring people.
I may be an extremist, but I think hiring people is the worst thing
a company can do. To start with, people are a recurring expense,
which is the worst kind. They also tend to cause you to grow out
of your space, and perhaps even move to the sort of uncool office
building that will make your software worse. But worst of all,
they slow you down: instead of sticking your head in someone's
office and checking out an idea with them, eight people have to
have a meeting about it. So the fewer people you can hire, the
better.During the Bubble a lot of startups had the opposite policy. They
wanted to get "staffed up" as soon as possible, as if you couldn't
get anything done unless there was someone with the corresponding
job title. That's big company thinking. Don't hire people to fill
the gaps in some a priori org chart. The only reason to hire someone
is to do something you'd like to do but can't.If hiring unnecessary people is expensive and slows you down, why
do nearly all companies do it? I think the main reason is that
people like the idea of having a lot of people working for them.
This weakness often extends right up to the CEO. If you ever end
up running a company, you'll find the most common question people
ask is how many employees you have. This is their way of weighing
you. It's not just random people who ask this; even reporters do.
And they're going to be a lot more impressed if the answer is a
thousand than if it's ten.This is ridiculous, really. If two companies have the same revenues,
it's the one with fewer employees that's more impressive. When
people used to ask me how many people our startup had, and I answered
"twenty," I could see them thinking that we didn't count for much.
I used to want to add "but our main competitor, whose ass we regularly
kick, has a hundred and forty, so can we have credit for the larger
of the two numbers?"As with office space, the number of your employees is a choice
between seeming impressive, and being impressive. Any of you who
were nerds in high school know about this
choice. Keep doing it when you start a company.Should You?But should you start a company? Are you the right sort of person
to do it? If you are, is it worth it?More people are the right sort of person to start a startup than
realize it. That's the main reason I wrote this. There could be
ten times more startups than there are, and that would probably be
a good thing.I was, I now realize, exactly the right sort of person to start a
startup. But the idea terrified me at first. I was forced into
it because I was a Lisp hacker. The company
I'd been consulting for seemed to be running into trouble, and there
were not a lot of other companies using Lisp. Since I couldn't
bear the thought of programming in another language (this was 1995,
remember, when "another language" meant C++) the only option seemed
to be to start a new company using Lisp.I realize this sounds far-fetched, but if you're a Lisp hacker
you'll know what I mean. And if the idea of starting a startup
frightened me so much that I only did it out of necessity, there
must be a lot of people who would be good at it but who are too
intimidated to try.So who should start a startup? Someone who is a good hacker, between
about 23 and 38, and who wants to solve the money problem in one
shot instead of getting paid gradually over a conventional working
life.I can't say precisely what a good hacker is. At a first rate
university this might include the top half of computer science
majors. Though of course you don't have to be a CS major to be a
hacker; I was a philosophy major in college.It's hard to tell whether you're a good hacker, especially when
you're young. Fortunately the process of starting startups tends
to select them automatically. What drives people to start startups
is (or should be) looking at existing technology and thinking, don't
these guys realize they should be doing x, y, and z? And that's
also a sign that one is a good hacker.I put the lower bound at 23 not because there's something that
doesn't happen to your brain till then, but because you need to see
what it's like in an existing business before you try running your
own. The business doesn't have to be a startup. I spent a year
working for a software company to pay off my college loans. It was
the worst year of my adult life, but I learned, without realizing
it at the time, a lot of valuable lessons about the software business.
In this case they were mostly negative lessons: don't have a lot
of meetings; don't have chunks of code that multiple people own;
don't have a sales guy running the company; don't make a high-end
product; don't let your code get too big; don't leave finding bugs
to QA people; don't go too long between releases; don't isolate
developers from users; don't move from Cambridge to Route 128; and
so on. [8] But negative lessons are just as valuable as positive
ones. Perhaps even more valuable: it's hard to repeat a brilliant
performance, but it's straightforward to avoid errors. [9]The other reason it's hard to start a company before 23 is that
people won't take you seriously. VCs won't trust you, and will try
to reduce you to a mascot as a condition of funding. Customers
will worry you're going to flake out and leave them stranded. Even
you yourself, unless you're very unusual, will feel your age to
some degree; you'll find it awkward to be the boss of someone much
older than you, and if you're 21, hiring only people younger rather
limits your options.Some people could probably start a company at 18 if they wanted to.
<NAME> was 19 when he and <NAME> started Microsoft. (Paul
Allen was 22, though, and that probably made a difference.) So if
you're thinking, I don't care what he says, I'm going to start a
company now, you may be the sort of person who could get away with
it.The other cutoff, 38, has a lot more play in it. One reason I put
it there is that I don't think many people have the physical stamina
much past that age. I used to work till 2:00 or 3:00 AM every
night, seven days a week. I don't know if I could do that now.Also,
startups are a big risk financially. If you try something that
blows up and leaves you broke at 26, big deal; a lot of 26 year
olds are broke. By 38 you can't take so many risks-- especially
if you have kids.My final test may be the most restrictive. Do you actually want
to start a startup? What it amounts to, economically, is compressing
your working life into the smallest possible space. Instead of
working at an ordinary rate for 40 years, you work like hell for
four. And maybe end up with nothing-- though in that case it
probably won't take four years.During this time you'll do little but work, because when you're not
working, your competitors will be. My only leisure activities were
running, which I needed to do to keep working anyway, and about
fifteen minutes of reading a night. I had a girlfriend for a total
of two months during that three year period. Every couple weeks I
would take a few hours off to visit a used bookshop or go to a
friend's house for dinner. I went to visit my family twice.
Otherwise I just worked.Working was often fun, because the people I worked with were some
of my best friends. Sometimes it was even technically interesting.
But only about 10% of the time. The best I can say for the other
90% is that some of it is funnier in hindsight than it seemed then.
Like the time the power went off in Cambridge for about six hours,
and we made the mistake of trying to start a gasoline powered
generator inside our offices. I won't try that again.I don't think the amount of bullshit you have to deal with in a
startup is more than you'd endure in an ordinary working life. It's
probably less, in fact; it just seems like a lot because it's
compressed into a short period. So mainly what a startup buys you
is time. That's the way to think about it if you're trying to
decide whether to start one. If you're the sort of person who would
like to solve the money problem once and for all instead of working
for a salary for 40 years, then a startup makes sense.For a lot of people the conflict is between startups and graduate
school. Grad students are just the age, and just the sort of people,
to start software startups. You may worry that if you do you'll
blow your chances of an academic career. But it's possible to be
part of a startup and stay in grad school, especially at first.
Two of our three original hackers were in grad school the whole
time, and both got their degrees.
There are few sources of energy
so powerful as a procrastinating grad student.If you do have to
leave grad school, in the worst case it won't be for too long. If
a startup fails, it will probably fail quickly enough that you can
return to academic life. And if it succeeds, you may find you no
longer have such a burning desire to be an assistant professor.If you want to do it, do it. Starting a startup is not the great
mystery it seems from outside. It's not something you have to know
about "business" to do. Build something users love, and spend less
than you make. How hard is that?Notes[1] Google's revenues are about two billion a year, but half comes
from ads on other sites.[2] One advantage startups have over established companies is that
there are no discrimination laws about starting businesses. For
example, I would be reluctant to start a startup with a woman
who had small children, or was likely to have them soon. But you're
not allowed to ask prospective employees if they plan to have kids
soon. Believe it or not, under current US law, you're not even
allowed to discriminate on the basis of intelligence. Whereas when
you're starting a company, you can discriminate on any basis you
want about who you start it with.[3] Learning to hack is a lot cheaper than business school, because
you can do it mostly on your own. For the price of a Linux box, a
copy of K&R, and a few hours of advice from your neighbor's fifteen
year old son, you'll be well on your way.[4] Corollary: Avoid starting a startup to sell things to the biggest
company of all, the government. Yes, there are lots of opportunities
to sell them technology. But let someone else start those startups.[5] A friend who started a company in Germany told me they do care
about the paperwork there, and that there's more of it. Which helps
explain why there are not more startups in Germany.[6] At the seed stage our valuation was in principle $100,000, because
Julian got 10% of the company. But this is a very misleading number,
because the money was the least important of the things Julian gave us.[7] The same goes for companies that seem to want to acquire you.
There will be a few that are only pretending to in order to pick
your brains. But you can never tell for sure which these are, so
the best approach is to seem entirely open, but to fail to mention
a few critical technical secrets.[8] I was as bad an employee as this place was a company. I
apologize to anyone who had to work with me there.[9] You could probably write a book about how to succeed in business
by doing everything in exactly the opposite way from the DMV.Thanks to <NAME>, <NAME>, <NAME>,
and <NAME> for reading drafts of this essay, and to <NAME> and <NAME> for inviting me to speak.Domain Name SearchTurkish TranslationHebrew TranslationRussian TranslationChinese TranslationFrench TranslationJapanese TranslationArabic Translation
|
|
https://github.com/ClassicConor/UoKCSYear1ExamNotes2024 | https://raw.githubusercontent.com/ClassicConor/UoKCSYear1ExamNotes2024/master/HCI%20(With%20Exam%20Answers)/HCI%202021%20Paper/HCI%202021%20Answers.typ | typst | = HCI Exam 2021 - Answers to the questions
<hci-exam-2021---answers-to-the-questions>
== Question 1
<question-1>
Heuristic Evaluation (HE) is a useful method to evaluate a computer
interface. It has a standard report format and 10 Heuristics rules.
Suppose you want to develop a mobile app for online Burger ordering and
delivery as a UI/UX designer.
=== (a)
<a>
For each of the following usability problem, use the HE Report format to
list which Heuristic rule it goes against and justify the reason, give a
Severity rating within a scale of 0-4 and justify the reason, and
suggest a fix.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 1)
+ Problem 1: No progress indicator for payment processing page, which
takes more than 10 sec to respond.
]
]
H1 - Visibility of system status. There is no method by which the user
is updated on the progress of the payment while it’s occurring, which
may result in the user clicking off the browser, believing that the
payment has already been achieved.
I would give this a severity rating of 2. Although it is significant
enough that some users may click off the website after a while, ultimate
the website, and the process overall still occurs, and this issue can be
fixed potentially by adding a loading animation to indicate that the
problem is being dealt with.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 2)
+ Problem 2: Users are not able to input a delivery address.
]
]
H7 - User control and freedom. The inability for the user to insert a
delivery address for a website is a major flaw in the design of the
website.
I would give this a severity rating of 4, because without the ability to
input a delivery address, the website is essentially useless, as the
primary function of the website is to deliver food to the user. This
problem can be fixed by adding a text box for the user to input their
address.
#quote(block: true)[
#block[
#set enum(numbering: "(a)", start: 2)
+ As a software development team manager, you need to fix the above 2
usability problems. Which problem(s) do you have to fix before
releasing the app? Justify your answer using one sentence.
]
]
The priority would go towards problem 2, as although problem 1 may be
slightly annoying, it’s current status doesn’t result in a broken and
non-functioning application, unlike problem 2.
=== c
<c>
There are a wide range of controls and widgets to choose for the user
interface design. For each of the following page design, list which type
of digital controls and widgets should be used.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 1)
+ Page 1: Users can choose one type of burger from Hamburger, Chicken
burger, Veggie burger.
]
]
Radio Button
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 2)
+ Page 2: Users can choose one or multiple toppings from Tomato,
Lettuce, Pickles, Cheese.
]
]
Checkbox
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 3)
+ Page 3: Users can select one type of cheese from Mozzarella, Gouda,
Cheddar, Swiss cheese, Blue cheese, Brie, Monterey jack, Goat cheese.
]
]
Drop down list
== Question 2
<question-2>
KLM-GOMS stands for Keystroke-level model for Goals, Operators, Methods,
and Selection rules. It is composed of methods that are used to achieve
specific goals. In KLM-GOMS, methods are composed of operators at the
lowest level. Operators might include K(key/button) =0.2 sec, P(point) =
1.1 sec, H(home) = 0.4 sec, M(mentally prepare) = 1.35 sec, R(response).
=== (a) For the currency converter listed in Figure 1 below, estimate the time to for Hal to use the interface for converting 3 pounds into Euros by showing the workout apply the following steps where necessary. Assume Hal’s typing is perfect; error detection and notification are not needed. The default currency is pounds to Euro. After a number is input in the text box corresponding to pounds, the conversation is immediately displayed in the text box next to the Euro. No enter key is required to fulfill the conversation
<a-for-the-currency-converter-listed-in-figure-1-below-estimate-the-time-to-for-hal-to-use-the-interface-for-converting-3-pounds-into-euros-by-showing-the-workout-apply-the-following-steps-where-necessary.-assume-hals-typing-is-perfect-error-detection-and-notification-are-not-needed.-the-default-currency-is-pounds-to-euro.-after-a-number-is-input-in-the-text-box-corresponding-to-pounds-the-conversation-is-immediately-displayed-in-the-text-box-next-to-the-euro.-no-enter-key-is-required-to-fulfill-the-conversation>
#figure(image("HCI2021Question2.png"),
caption: [
HCI2021 Question 1 Image
]
)
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 1)
+ Step 1: Operators (HPKHK) are involved to achieve the task. Justify
the choice of each operator using one sentence.
]
]
HPKHK
+ H - Place the hand on the mouse
+ P - Move the mouse the upper text box
+ K - Click on the text box
+ H - Move the hand onto the correct key on the keyboard
+ K - Click the button on the keyboard
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 2)
+ Step 2: Apply Rule 0, add Ms in front of all Ks and Ps that point to
commands.
]
]
HP#strong[M];K#strong[M];HK
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 3)
+ Step 3: Apply Rule 1, change PMK to PK to remove fully anticipated Ms.
]
]
HPK#strong[M];HK
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 4)
+ Step 4: Apply Rule 2, to eliminate Ms in the middle of strings that
are cognitive units.
]
]
HPK#strong[M];HK
#quote(block: true)[
#block[
#set enum(numbering: "(a)", start: 22)
+ Step 5: Apply Rule 3, deletion of Ms before consecutive terminators.
]
]
HPK#strong[M];HK
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 6)
+ Step 6: Apply Rule 4, deletion of Ms that are terminators of commands.
]
]
HPK#strong[M];HK
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 7)
+ Step 7: Apply Rule 5, deletion of overlapped Ms.
]
]
HPK#strong[M];HK
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 8)
+ Step 8: Calculate the time.
]
]
Time of action:
- K - (2 \* 0.2) = 0.4
- P - (1 \* 1.1) = 1.1
- M - (1 \* 1.35) = 1.35
- H - (2 \* 0.4) = 0.8
Total time = 3.65 seconds
=== (b) Colour vision and perception play an important role in user interface design. Answer the following questions with one sentence
<b-colour-vision-and-perception-play-an-important-role-in-user-interface-design.-answer-the-following-questions-with-one-sentence>
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 1)
+ Choice of colour combination in interface design: different
wavelengths of light focused on different distances behind eye’s lens,
therefore colour combinations need extra care in user interface
design. Which two colour’s combination would cause eye to fatigue the
most; justify your answer (red and yellow, green and red, green and
orange, red and blue)?
]
]
Red and blue would cause the eyes to fatigue the most. This is because
these colours exist at complete opposite ends of the colour spectrum,
which means that the eyes would be required to constantly adjust,
leading to discomfort.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 2)
+ State the consequence of an interface design with only two colours
(red and green) to indicate its states.
]
]
Using the colours red and green may be unhelp for people who are colour
blind, specifically those with red-green colour blindness, as they may
struggle to differentiate between the colours.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 3)
+ You want to create a web interface for an organic food company for
online order. In order to represent the company’s ethos of linked to
nature, peace, well-being, environment- friendly and freshness, which
of the three colour scheme (red, blue, white, green) you should choose
for the theme of the web design.
]
]
The best colours to pick for this website would be blue, white and
green:
- Green for representing nature, environmental friendliness and
freshness
- Blue for representing well-being
- White for repesenting cleanliness and purity
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 4)
+ In order to design a lo-fi interface, what is the best choice of
colour for the interface.
]
]
For a very simple lo-fi design, the best choice of colours can be black
and white/greyscale. This is because most lo-fi design could be created
on paper with just white paper and a black pen/pencil, and no other
colours.
== Question 3
<question-3>
Human Centred Design (HCD) Process consists of five stages: Empathise,
Define, Ideate, Prototype, and Test.
=== (a) For each of the following activity, match the activity to the most appropriate HCD stage as above
<a-for-each-of-the-following-activity-match-the-activity-to-the-most-appropriate-hcd-stage-as-above>
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 1)
+ Activity 1: A paper model of the actual design is developed.
]
]
Prototype - The initial design has been created, but #strong[it has not
been tested on the public];.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 2)
+ Activity 2: Users are asked to evaluate the design and give comments.
]
]
Test - The prototype has been created, and now it is being evaluated and
#strong[tested by the user];.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 3)
+ Activity 3: Several designs approaches are discussed by development
team.
]
]
Ideate - The target audience has been selected, and the problem has been
defined. We are now at the stage of #strong[discussing the design] with
the team.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 4)
+ Activity 4: Information collected from users is tabled in a structured
form.
]
]
Define - General information (not specific to a prototype) is received,
and it is the stage by which we #strong[look at the data and analyse
what to work on] in a quantitative format.
#quote(block: true)[
#block[
#set enum(numbering: "(a)", start: 22)
+ Activity 5: Users are interviewed to obtain their requirements.
]
]
Empathise - Designers try to understand the need of the users. We are
starting right at the beginning, by asking users what they’re thinking
about.
=== (b) HCD utilises many heuristics and design approaches. For each of the following scenario, give the appropriate name of the heuristic or activity. Briefly (in no more than one sentence each), explain your reasoning for giving the heuristic/activity names
<b-hcd-utilises-many-heuristics-and-design-approaches.-for-each-of-the-following-scenario-give-the-appropriate-name-of-the-heuristic-or-activity.-briefly-in-no-more-than-one-sentence-each-explain-your-reasoning-for-giving-the-heuristicactivity-names>
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 1)
+ Scenario 1: In a shop, there are two entry doors; one big and another
small.
]
]
H1 - Visibility of System Status
- The two entry doors may communicate the status of the door. One door
may be the normal door for the vast majority of customers, whereas the
other door may have a more specific purpose, such as an emergency
exit.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 2)
+ Scenario 2: A company manager wants good quality software. The manager
is willing to spend a lot of money but wants fast delivery of the
completed software.
]
]
H7 - Flexibility and ease of use
- The company manager’s desire for good quality software while also
prioritizing fast delivery suggests a need for flexibility and
efficiency in the software development process. This heuristic
emphasizes designing systems that are adaptable to user needs and
allow users to accomplish tasks quickly and effectively, which aligns
with the manager’s goals of delivering high-quality software within a
tight timeline.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 3)
+ Scenario 3: In a web interface, a software developer has designed very
large buttons to help the elderly click the buttons easily.
]
]
H7 - Flexibility and ease of use
- The design of large buttons in the web interface demonstrates a
consideration for the needs of elderly users by making interactions
more accessible and efficient.
#quote(block: true)[
#block[
#set enum(numbering: "(i)", start: 4)
+ Scenario 4: A person tries to remember a telephone number
(01634888867) by partitioning it into three parts: 01634 888 867.
]
]
H6: Recognition rather than recall.
- Partitioning the telephone number into three parts helps the person
recognize and remember it more easily.
#quote(block: true)[
#block[
#set enum(numbering: "(a)", start: 22)
+ Scenario 5: Mother’s maiden name is used to retrieve passwords.
]
]
H9: Help users recognize, diagnose, and recover from errors.
- Using a familiar piece of information like a mother’s maiden name as a
password retrieval method helps users recognize and remember their
passwords more easily.
== Question 4
<question-4>
For this question, you will need to design a simple interface for a
microwave without any digital display. The microwave has only FIVE
functions:
- START/STOP
- Microwave power mode (LOW/MED/HIGH)
- Microwave heating time for up to 30 minutes
- Open door
- Overheat warning
#quote(block: true)[
#block[
#set enum(numbering: "(a)", start: 1)
+ Sketch an interface design (with appropriate annotations on its usage)
that includes approximately designed menu interface for the five
functions above.
]
]
\[insert image here\]
#quote(block: true)[
#block[
#set enum(numbering: "(a)", start: 2)
+ For each feature that you have designed, list a design principle, and
explain (in no more than one sentence each) on how the feature
implements the principle.
]
]
\[insert features here\]
|
|
https://github.com/dockage/typst | https://raw.githubusercontent.com/dockage/typst/main/README.md | markdown | Apache License 2.0 | # typst
Docker for Typst
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/104.%20hackernews.html.typ | typst | hackernews.html
What I've Learned from Hacker News
February 2009Hacker News was two years
old last week. Initially it was supposed to be a side project—an
application to sharpen Arc on, and a place for current and future
Y Combinator founders to exchange news. It's grown bigger and taken
up more time than I expected, but I don't regret that because I've
learned so much from working on it.GrowthWhen we launched in February 2007, weekday traffic was around 1600
daily uniques. It's since grown to around 22,000. This growth
rate is a bit higher than I'd like. I'd like the site to grow,
since a site that isn't growing at least slowly is probably dead.
But I wouldn't want it to grow as large as Digg or Reddit—mainly
because that would dilute the character of the site, but also because
I don't want to spend all my time dealing with scaling.I already have problems enough with that. Remember, the original
motivation for HN was to test a new programming language, and
moreover one that's focused on experimenting with language design,
not performance. Every time the site gets slow, I fortify myself
by recalling McIlroy and Bentley's famous quote
The key to performance is elegance, not battalions of special
cases.
and look for the bottleneck I can remove with least code. So far
I've been able to keep up, in the sense that performance has remained
consistently mediocre despite 14x growth. I don't know what I'll
do next, but I'll probably think of something.This is my attitude to the site generally. Hacker News is an
experiment, and an experiment in a very young field. Sites of this
type are only a few years old. Internet conversation generally is
only a few decades old. So we've probably only discovered a fraction
of what we eventually will.That's why I'm so optimistic about HN. When a technology is this
young, the existing solutions are usually terrible; which means it
must be possible to do much better; which means many problems that
seem insoluble aren't. Including, I hope, the problem that has
afflicted so many previous communities: being ruined by growth.DilutionUsers have worried about that since the site was a few months old.
So far these alarms have been false, but they may not always be.
Dilution is a hard problem. But probably soluble; it doesn't mean
much that open conversations have "always" been destroyed by growth
when "always" equals 20 instances.But it's important to remember we're trying to solve a new problem,
because that means we're going to have to try new things, most of
which probably won't work. A couple weeks ago I tried displaying
the names of users with the highest average comment scores in orange.
[1]
That was a mistake. Suddenly a culture that had been more
or less united was divided into haves and have-nots. I didn't
realize how united the culture had been till I saw it divided. It
was painful to watch.
[2]So orange usernames won't be back. (Sorry about that.) But there
will be other equally broken-seeming ideas in the future, and the
ones that turn out to work will probably seem just as broken as
those that don't.Probably the most important thing I've learned about dilution is
that it's measured more in behavior than users. It's bad behavior
you want to keep out more than bad people. User behavior turns out
to be surprisingly malleable. If people are
expected to behave
well, they tend to; and vice versa.Though of course forbidding bad behavior does tend to keep away bad
people, because they feel uncomfortably constrained in a place where
they have to behave well. But this way of keeping them out is
gentler and probably also more effective than overt barriers.It's pretty clear now that the broken windows theory applies to
community sites as well. The theory is that minor forms of bad
behavior encourage worse ones: that a neighborhood with lots of
graffiti and broken windows becomes one where robberies occur. I
was living in New York when Giuliani introduced the reforms that
made the broken windows theory famous, and the transformation was
miraculous. And I was a Reddit user when the opposite happened
there, and the transformation was equally dramatic.I'm not criticizing Steve and Alexis. What happened to Reddit
didn't happen out of neglect. From the start they had a policy of
censoring nothing except spam. Plus Reddit had different goals
from Hacker News. Reddit was a startup, not a side project; its
goal was to grow as fast as possible. Combine rapid growth and
zero censorship, and the result is a free for all. But I don't
think they'd do much differently if they were doing it again.
Measured by traffic, Reddit is much more successful than Hacker
News.But what happened to Reddit won't inevitably happen to HN. There
are several local maxima. There can be places that are free for
alls and places that are more thoughtful, just as there are in the
real world; and people will behave differently depending on which
they're in, just as they do in the real world.I've observed this in the wild. I've seen people cross-posting on
Reddit and Hacker News who actually took the trouble to write two
versions, a flame for Reddit and a more subdued version for HN.SubmissionsThere are two major types of problems a site like Hacker News needs
to avoid: bad stories and bad comments. So far the danger of bad
stories seems smaller. The stories on the frontpage now are still
roughly the ones that would have been there when HN started.I once thought I'd have to weight votes to keep crap off the
frontpage, but I haven't had to yet. I wouldn't have predicted the
frontpage would hold up so well, and I'm not sure why it has.
Perhaps only the more thoughtful users care enough to submit and
upvote links, so the marginal cost of one random new user approaches
zero. Or perhaps the frontpage protects itself, by advertising what type of submission is expected.The most dangerous thing for the frontpage is stuff that's too easy
to upvote. If someone proves a new theorem, it takes some work by
the reader to decide whether or not to upvote it. An amusing cartoon
takes less. A rant with a rallying cry as the title takes zero,
because people vote it up without even reading it.Hence what I call the Fluff Principle: on a user-voted news site,
the links that are easiest to judge will take over unless you take
specific measures to prevent it.Hacker News has two kinds of protections against fluff. The most
common types of fluff links are banned as off-topic. Pictures of
kittens, political diatribes, and so on are explicitly banned. This
keeps out most fluff, but not all of it. Some links are both fluff,
in the sense of being very short, and also on topic.There's no single solution to that. If a link is just an empty
rant, editors will sometimes kill it even if it's on topic in the
sense of being about hacking, because it's not on topic by the real
standard, which is to engage one's intellectual curiosity. If the
posts on a site are characteristically of this type I sometimes ban
it, which means new stuff at that url is auto-killed. If a post
has a linkbait title, editors sometimes rephrase it to be more
matter-of-fact. This is especially necessary with links whose
titles are rallying cries, because otherwise they become implicit
"vote up if you believe such-and-such" posts, which are the most
extreme form of fluff.The techniques for dealing with links have to evolve, because the
links do. The existence of aggregators has already affected what
they aggregate. Writers now deliberately write things to draw traffic
from aggregators—sometimes even specific ones. (No, the irony
of this statement is not lost on me.) Then there are the more
sinister mutations, like linkjacking—posting a paraphrase of
someone else's article and submitting that instead of the original.
These can get a lot of upvotes, because a lot of what's good in an
article often survives; indeed, the closer the paraphrase is to
plagiarism, the more survives.
[3]I think it's important that a site that kills submissions provide
a way for users to see what got killed if they want to. That keeps
editors honest, and just as importantly, makes users confident
they'd know if the editors stopped being honest. HN users can do
this by flipping a switch called showdead in their profile.
[4]CommentsBad comments seem to be a harder problem than bad submissions.
While the quality of links on the frontpage of HN hasn't changed
much, the quality of the median comment may have decreased somewhat.There are two main kinds of badness in comments: meanness and
stupidity. There is a lot of overlap between the two—mean
comments are disproportionately likely also to be dumb—but
the strategies for dealing with them are different. Meanness is
easier to control. You can have rules saying one shouldn't be mean,
and if you enforce them it seems possible to keep a lid on meanness.Keeping a lid on stupidity is harder, perhaps because stupidity is
not so easily distinguishable. Mean people are more likely to know
they're being mean than stupid people are to know they're being
stupid.The most dangerous form of stupid comment is not the long but
mistaken argument, but the dumb joke. Long but mistaken arguments
are actually quite rare. There is a strong correlation between
comment quality and length; if you wanted to compare the quality
of comments on community sites, average length would be a good
predictor. Probably the cause is human nature rather than anything
specific to comment threads. Probably it's simply that stupidity
more often takes the form of having few ideas than wrong ones.Whatever the cause, stupid comments tend to be short. And since
it's hard to write a short comment that's distinguished for the
amount of information it conveys, people try to distinguish them
instead by being funny. The most tempting format for stupid comments
is the supposedly witty put-down, probably because put-downs are
the easiest form of humor.
[5]
So one advantage of forbidding
meanness is that it also cuts down on these.Bad comments are like kudzu: they take over rapidly. Comments have
much more effect on new comments than submissions have on new
submissions. If someone submits a lame article, the other submissions
don't all become lame. But if someone posts a stupid comment on a
thread, that sets the tone for the region around it. People reply
to dumb jokes with dumb jokes.Maybe the solution is to add a delay before people can respond to
a comment, and make the length of the delay inversely proportional
to some prediction of its quality. Then dumb threads would grow
slower.
[6]
PeopleI notice most of the techniques I've described are conservative:
they're aimed at preserving the character of the site rather than
enhancing it. I don't think that's a bias of mine. It's due to
the shape of the problem. Hacker News had the good fortune to start
out good, so in this case it's literally a matter of preservation.
But I think this principle would also apply to sites with different
origins.The good things in a community site come from people more than
technology; it's mainly in the prevention of bad things that
technology comes into play. Technology certainly can enhance
discussion. Nested comments do, for example. But I'd rather use
a site with primitive features and smart, nice users than a more
advanced one whose users were idiots or trolls.So the most important thing a community site can do is attract the
kind of people it wants. A site trying to be as big as possible
wants to attract everyone. But a site aiming at a particular subset
of users has to attract just those—and just as importantly,
repel everyone else. I've made a conscious effort to do this on
HN. The graphic design is as plain as possible, and the site rules
discourage dramatic link titles. The goal is that the only thing
to interest someone arriving at HN for the first time should be the
ideas expressed there.The downside of tuning a site to attract certain people is that,
to those people, it can be too attractive. I'm all too aware how
addictive Hacker News can be. For me, as for many users, it's a
kind of virtual town square. When I want to take a break from
working, I walk into the square, just as I might into Harvard Square
or University Ave in the physical world.
[7]
But an online square is
more dangerous than a physical one. If I spent half the day loitering
on University Ave, I'd notice. I have to walk a mile to get there,
and sitting in a cafe feels different from working. But visiting
an online forum takes just a click, and feels superficially very
much like working. You may be wasting your time, but you're not
idle. Someone is wrong on the Internet, and you're fixing the
problem.Hacker News is definitely useful. I've learned a lot from things
I've read on HN. I've written several essays that began as comments
there. So I wouldn't want the site to go away. But I would like
to be sure it's not a net drag on productivity. What a disaster
that would be, to attract thousands of smart people to a site that
caused them to waste lots of time. I wish I could be 100% sure
that's not a description of HN.I feel like the addictiveness of games and social applications is
still a mostly unsolved problem. The situation now is like it was
with crack in the 1980s: we've invented terribly addictive new
things, and we haven't yet evolved ways to protect ourselves from
them. We will eventually, and that's one of the problems I hope
to focus on next.
Notes[1]
I tried ranking users by both average and median comment
score, and average (with the high score thrown out) seemed the more
accurate predictor of high quality. Median may be the more accurate
predictor of low quality though.[2]
Another thing I learned from this experiment is that if you're
going to distinguish between people, you better be sure you do it
right. This is one problem where rapid prototyping doesn't work.Indeed, that's the intellectually honest argument for not discriminating
between various types of people. The reason not to do it is not
that everyone's the same, but that it's bad to do wrong and hard
to do right.[3]
When I catch egregiously linkjacked posts I replace the url
with that of whatever they copied. Sites that habitually linkjack
get banned.[4]
Digg is notorious for its lack of transparency. The root of
the problem is not that the guys running Digg are especially sneaky,
but that they use the wrong algorithm for generating their frontpage.
Instead of bubbling up from the bottom as they get more votes, as
on Reddit, stories start at the top and get pushed down by new
arrivals.The reason for the difference is that Digg is derived from Slashdot,
while Reddit is derived from Delicious/popular. Digg is Slashdot
with voting instead of editors, and Reddit is Delicious/popular
with voting instead of bookmarking. (You can still see fossils of
their origins in their graphic design.)Digg's algorithm is very vulnerable to gaming, because any story
that makes it onto the frontpage is the new top story. Which in
turn forces Digg to respond with extreme countermeasures. A lot
of startups have some kind of secret about the subterfuges they had
to resort to in the early days, and I suspect Digg's is the extent
to which the top stories were de facto chosen by human editors.[5]
The dialog on Beavis and Butthead was composed largely of
these, and when I read comments on really bad sites I can hear them
in their voices.[6]
I suspect most of the techniques for discouraging stupid
comments have yet to be discovered. Xkcd implemented a particularly
clever one in its IRC channel: don't allow the same thing twice.
Once someone has said "fail," no one can ever say it again. This
would penalize short comments especially, because they have less
room to avoid collisions in.Another promising idea is the stupid
filter, which is just like a
probabilistic spam filter, but trained on corpora of stupid and
non-stupid comments instead.You may not have to kill bad comments to solve the problem. Comments
at the bottom of a long thread are rarely seen, so it may be enough
to incorporate a prediction of quality in the comment sorting
algorithm.[7]
What makes most suburbs so demoralizing is that there's no
center to walk to.
Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME> for reading drafts of
this.
Comment on this essay.
|
|
https://github.com/xdoardo/co-thesis | https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/chapters/delay/index.typ | typst | = The delay monad<chapter-partiality_monad>
In this chapter we introduce the concept of monad and then describe a particular
kind of monad, the _delay monad_, which will be used troughout the work.
#include "./monads.typ"
//#include "./implementation.typ"
|
|
https://github.com/adamDilger/resume | https://raw.githubusercontent.com/adamDilger/resume/master/README.md | markdown | # <NAME> Resume
### Building
`typst compile resume.typ`
|
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/feebf7-2023_fall_TA/extension.typ | typst | #import "utils.typ": *
= 扩展内容
#text(fill: blue)[标蓝]_的内容选读,无需掌握_
#include "extensions/peano.typ"
#include "extensions/qq.countable.typ" |
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/ea2724-ai_hw/hw6.typ | typst | #import "@preview/cetz:0.2.2": *
== HW6
Due 2024.04.28
#let ans(it) = [
#pad(1em)[
#text(fill: blue)[
#it
]
]
]
=== Question 8.13
解释下面给出的 Wumpus 世界中相邻方格的定义存在什么问题:
$
forall x,y "Adjacent"([x,y], [x+1,y]) and "Adjacent"([x,y], [x,y+1])
$
#ans[
这个定义没有考虑到边界情况, 即当 $x = 4$ 或 $y = 4$ 时, $[x+1,y]$ 或 $[x,y+1]$ 可能会超出边界.
]
=== Question 8.17
用一个相容的词汇表(需要你自己定义)在一阶逻辑中表示下列语句:
+ 某些学生在 2001 年春季学期上法语课.
+ 上法语课的每个学生都通过了考试.
+ 只有一个学生在 2001 年春节学期上希腊语课.
+ 希腊语课的最好成绩总是比法语课的最好成绩高.
#ans[
定义词汇表如下: (防止赘述, 我们省略一些不必说明的定义)
- Takes(student, course, semester)
- Passes(student, course, semester)
- Score(student, course, semester, score)
- x > y (x 比 y 大)
那么上面的四个语句可以分别表示如下:
+ $exists x, "Student"(x) and "Takes"(x, "French", "Spring2021")$
+ $forall x, "Student"(x) and "Takes"(x, "French", "Spring2021") => "Passes"(x, "French", "Spring2021")$
+ $exists x, "Student"(x) and "Takes"(x, "Greek", "Spring2021") and (
forall y, "Student"(y) and "Takes"(y, "Greek", "Spring2021") => x = y
)$
- 注: 上述描述 = 存在这样的一个学生, 而且对于所有满足这样条件的学生, 都是同一个学生.
+ $forall s, x, exists y, "Semester"(s) and "Student"(x) and "Student"(y) and "Takes"(x, "Greek", s) and "Takes"(
y, "French", s
) => "Score"(x, "Greek", s) > "Score"(y, "French", s)$
]
+ 每个买保险都是聪明的.
+ 没有人会买昂贵的保险.
+ 有一个代理, 他只向那些没投保的卖保险.
#ans[
定义词汇表如下: (防止赘述, 我们省略一些不必说明的定义)
- BuyInsurance(agent, insurance)
- Expensive(insurance)
- Smart(agent)
- SellInsurance(agent, agent, insurance)
- Insured(agent)
那么上面的三个语句可以分别表示如下:
#set enum(start: 5)
+ $forall x, exists y, "Agent"(x) and "Policy"(y) and "BuyInsurance"(x, y) => "Smart"(x)$
+ $forall x,y, "Agent"(x) and "Policy"(y) and "Expensive"(y) => not "BuyInsurance"(x, y)$
+ $exists x, "Agent"(x) and (forall y, forall z, "Policy"(z) and "SellInsurance"(x, y, z)) => "Agent"(y) and (
not "Insured"(y)
)$
]
+ 镇上有一个理发师, 他给所有不自己刮胡子的人刮胡子.
#ans[
定义词汇表如下: (防止赘述, 我们省略一些不必说明的定义)
- Barber(agent)
- Shave(A, B) (A 给 B 刮胡子)
- SelfShave(agent)
那么上面的语句可以表示如下:
#set enum(start: 8)
+ $exists x, "Agent"(x) and (forall y, "Agent"(y) and not "SelfShave"(y)) => "Shave"(x, y)$
]
+ 在英国出生的人, 如果其双亲都是英国公民或者永久居住者, 那么此人生来就是一个英国公民.
+ 在英国以外的地方出生的人, 如果其双亲生来就是英国公民, 那么此人血统上是一个英国公民.
#ans[
定义词汇表如下: (防止赘述, 我们省略一些不必说明的定义)
- BornIn(agent, place)
- BritishCitizen(agent)
- PermanentResident(agent)
- Parent(agent, agent)
- BloodCitizen(agent)
那么上面的两个语句可以分别表示如下:
#set enum(start: 9)
+ $forall x, "Agent"(x) and "BornIn"(x, "UK") and (
forall y, "Parent"(y, x) => ("BritishCitizen"(y) or "PermanentResident"(y))
) => "BritishCitizen"(x)$
+ $forall x, "Agent"(x) and not "BornIn"(x, "UK") and (
forall y, "Parent"(y, x) => "BritishCitizen"(y)
) => "BloodCitizen"(x)$
]
=== Question 9.3
假定知识库中只包括一条语句: $exists x, "AsHighAs"(x, "Everest")$. 下列哪个语句是应用存在量词实例化之后的合法结果?
+ $"AsHighAs"("Everest", "Everest")$
+ $"AsHighAs"("kilimanjaro", "Everest")$
+ $"AsHighAs"("kilimanjaro", "Everest") and "AsHighAs"("benNevis", "Everest")$
#ans[
仅 b & c.
a: Everest 已经出现在命题中, 应该进行标准化分离(重新命名)以避免混淆.
]
=== Question 9.4
对于下列每对原子语句, 如果存在请给出最一般的合一置换:
+ $P(A,B,B), P(x,y,z)$
#ans[
${x\/A, y\/B, z\/B}$
]
+ $Q(y,G(A,B)), Q(G(x,x),y)$
#ans[
不存在, $x$ 不可能同时置换为 $A$ 和 $B$.
]
+ $:"Older"("Father"(y),y), "Older"("Father"(x), "John")$
#ans[
${x\/"John", y\/"John"}$
]
+ $"Knows"("Father"(y),y), "Knows"(x,x)$
#ans[
不存在, $x$ 不可能同时置换为 $"Father"(y)$ 和 $y$.
]
=== Question 9.6
#ans[
#show math.equation.where(block: true): it => box(width: 100%, it)
+ 马, 奶牛, 猪都是哺乳动物.
$
&"Horse"(x) => "Mammal"(x) \
&"Cow"(x) => "Mammal"(x) \
&"Pig"(x) => "Mammal"(x)
$
+ 马的后代是马.
$
"Offspring"(x,y) and "Horse"(y) => "Horse"(x)\
$
+ Bluebeard 是马.
$
"Horse"("Bluebeard")
$
+ Bluebeard 是 Charlie 的家长.
$
"Parent"("Bluebeard", "Charlie")
$
+ 后代与家长是相互的.
$
&"Offspring"(x,y) => "Parent"(y,x)\
&"Parent"(x,y) => "Offspring"(y,x)\
$
+ 所有哺乳动物都有家长.
$
"Mammal"(x) => "Parent"(S(x), x)
$
其中 $S$ 是 Skolem 函数.
]
=== Question 9.13
本题中需要用到你在习题 9.6 中写出的语句, 运用反向链接算法来回答问题.
+ 画出用穷举反向链接算法为查询 $exists h, "horse"(h)$ 生成的证明树, 其中子句按照给定的顺序进行排序
+ 对于本领域, 你注意到了什么?
+ 实际上从你的语句中得出了多少个 $h$ 的解?
#ans[
+ 证明树如下:
#let data = (
[Horse(h)],
(([Offspring(h, y)]), [Parent(y,h)]),
(
[Horse(Bluebeard)],
(
[Offspring(Bluebeard, y)],
(
[Parent(y, Bluebeard)],
(
[Offspring(y, Charlie)],
[$dots.v$],
[],
),
[],
),
[],
),
[],
),
)
#canvas(
length: 0.9cm,
{
import draw: *
set-style(
content: (padding: .2),
fill: gray.lighten(70%),
stroke: gray.lighten(70%),
)
tree.tree(
data,
spread: 2.,
grow: 1.5,
draw-node: (node, ..) => {
content((), node.content)
},
draw-edge: (from, to, ..) => {
line(
(a: from, number: .6, b: to),
(a: to, number: .6, b: from),
mark: (end: ">"),
)
},
name: "tree",
)
},
)
+ 上面的证明树会陷入无限循环, 因为 $"Offspring"(x,y) and "Horse"(y) => "Horse"(x)$
+ 两个 $"Horse"("Bluebeard") $, $"Horse"("Charlie")$
] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1DF00.typ | typst | Apache License 2.0 | #let data = (
("LATIN SMALL LETTER FENG DIGRAPH WITH TRILL", "Ll", 0),
("LATIN SMALL LETTER REVERSED SCRIPT G", "Ll", 0),
("LATIN LETTER SMALL CAPITAL TURNED G", "Ll", 0),
("LATIN SMALL LETTER REVERSED K", "Ll", 0),
("LATIN LETTER SMALL CAPITAL L WITH BELT", "Ll", 0),
("LATIN SMALL LETTER LEZH WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER TURNED Y WITH BELT", "Ll", 0),
("LATIN SMALL LETTER REVERSED ENG", "Ll", 0),
("LATIN SMALL LETTER TURNED R WITH LONG LEG AND RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER T WITH HOOK AND RETROFLEX HOOK", "Ll", 0),
("LATIN LETTER RETROFLEX CLICK WITH RETROFLEX HOOK", "Lo", 0),
("LATIN SMALL LETTER ESH WITH DOUBLE BAR", "Ll", 0),
("LATIN SMALL LETTER ESH WITH DOUBLE BAR AND CURL", "Ll", 0),
("LATIN SMALL LETTER TURNED T WITH CURL", "Ll", 0),
("LATIN LETTER INVERTED GLOTTAL STOP WITH CURL", "Ll", 0),
("LATIN LETTER STRETCHED C WITH CURL", "Ll", 0),
("LATIN LETTER SMALL CAPITAL TURNED K", "Ll", 0),
("LATIN SMALL LETTER L WITH FISHHOOK", "Ll", 0),
("LATIN SMALL LETTER DEZH DIGRAPH WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER L WITH BELT AND PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER ENG WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER TURNED R WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER R WITH FISHHOOK AND PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER TESH DIGRAPH WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER EZH WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER DEZH DIGRAPH WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER I WITH STROKE AND RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER O WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER TESH DIGRAPH WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER C WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER S WITH CURL", "Ll", 0),
(),
(),
(),
(),
(),
(),
("LATIN SMALL LETTER D WITH MID-HEIGHT LEFT HOOK", "Ll", 0),
("LATIN SMALL LETTER L WITH MID-HEIGHT LEFT HOOK", "Ll", 0),
("LATIN SMALL LETTER N WITH MID-HEIGHT LEFT HOOK", "Ll", 0),
("LATIN SMALL LETTER R WITH MID-HEIGHT LEFT HOOK", "Ll", 0),
("LATIN SMALL LETTER S WITH MID-HEIGHT LEFT HOOK", "Ll", 0),
("LATIN SMALL LETTER T WITH MID-HEIGHT LEFT HOOK", "Ll", 0),
)
|
https://github.com/JeyRunner/tuda-typst-templates | https://raw.githubusercontent.com/JeyRunner/tuda-typst-templates/main/templates/tudapub/common/format.typ | typst | MIT License | #let format-date(date, language) = {
let date_cont = date.display("[month repr:long] [day], [year]")
if (language == "ger") {
date_cont = date.display("[day].[month repr:numerical].[year]")
}
return date_cont
} |
https://github.com/HernandoR/lz-brilliant-cv | https://raw.githubusercontent.com/HernandoR/lz-brilliant-cv/main/modules/certificates.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Honers and Certificates")
#cvHonor(..languageSwitch((
"en":(
date: [2023.03],
title: [Problem Solving Certificate],
issuer: [HackerRank]
),
"zh":(
date: [2023.03],
title: [HackerRank Problem Solving 认证],
issuer: [HackerRank]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2023.06],
title: [Silver Prize in Kaggle competition (*Top 10%*)],
issuer: [Kaggle]
),
"zh":(
date: [2023.06],
title: [Kaggle银牌(*Top 10%*)],
issuer: [Kaggle]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2023.06],
title: [Registered Consultant of Worldquant (*Top 5% in IQC*)],
issuer: [Worldquant]
),
"zh":(
date: [2023.06],
title: [Worldquant 注册顾问 (*Top 5% in IQC*)],
issuer: [Worldquant]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2023.05],
title: [Gold Level in Worldquant Challenge (*Top 5%*)],
issuer: [Worldquant]
),
"zh":(
date: [2023.05],
title: [Worldquant Challenge 金牌 (*Top 5%*)],
issuer: [Worldquant]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2022.06],
title: [First Prize in National Extracurricular Academic Competition],
issuer: [*#cvHighlight("Ministry of Education of China")*]
),
"zh":(
date: [2022.06],
title: [挑战杯全国课外学术作品竞赛二等奖],
issuer: [*#cvHighlight("中华人民共和国教育部")*]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2021.04],
title: [Meritorious Winner in Interdisciplinary Contest in Modeling (*Top 5%*)],
issuer: [COMAP]
),
"zh":(
date: [2021.04],
title: [交叉学科数学建模竞赛M奖(*Top 5%*)],
issuer: [数学及其应用联合会]
)
)))
// #cvHonor(..languageSwitch((
// "en":(
// date: [2020.08],
// title: [Second Prize in Cyber Security Competition],
// issuer: [Wuhan University of Science and Technology]
// ),
// "zh":(
// date: [2020.08],
// title: [网络安全竞赛二等奖],
// issuer: [武汉科技大学]
// )
// )))
#cvHonor(..languageSwitch((
"en":(
date: [2020.06],
title: [First Prize in Mathematical Contest in Modeling],
issuer: [WUST]
),
"zh":(
date: [2020.06],
title: [数学建模竞赛一等奖],
issuer: [武汉科技大学]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2020.04],
title: [Finalist In Interdisciplinary Contest in Modeling (*Top 1%*)],
issuer: [COMAP]
),
"zh":(
date: [2020.04],
title: [交叉学科数学建模竞赛特等奖提名(*Top 1%*)],
issuer: [数学及其应用联合会]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2018-2022],
title: [Multiple times First class Scholarship],
issuer: [WUST]
),
"zh":(
date: [2018-2022],
title: [多次 一等奖学金],
issuer: [武汉科技大学]
)
)))
#cvHonor(..languageSwitch((
"en":(
date: [2018-2022],
title: [The honor of Excellent Student],
issuer: [WUST]
),
"zh":(
date: [2018-2022],
title: [多次 优秀学生],
issuer: [武汉科技大学]
)
)))
// #cvHonor(
// date: [2022],
// title: [AWS Certified Security],
// issuer: [Amazon Web Services (*AWS*)],
// )
// #cvHonor(
// date: [2017],
// title: [Applied Data Science with Python],
// issuer: [Coursera]
// )
// #cvHonor(
// date: [],
// title: [SQL Fundamentals Track],
// issuer: [Datacamp]
// ) |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p1_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test associativity and scaling.
$ 1/(V^2^3^4^5),
frac(
attach(
limits(V), br: attach(2, br: 3), b: attach(limits(2), b: 3)),
attach(
limits(V), tl: attach(2, tl: 3), t: attach(limits(2), t: 3))),
attach(Omega,
tl: attach(2, tl: attach(3, tl: attach(4, tl: 5))),
tr: attach(2, tr: attach(3, tr: attach(4, tr: 5))),
bl: attach(2, bl: attach(3, bl: attach(4, bl: 5))),
br: attach(2, br: attach(3, br: attach(4, br: 5))),
)
$
|
https://github.com/Quantco/pre-commit-mirrors-typstfmt | https://raw.githubusercontent.com/Quantco/pre-commit-mirrors-typstfmt/main/README.md | markdown | BSD 3-Clause "New" or "Revised" License | # typstfmt pre-commit hook
pre-commit hook of typstfmt with conda as a `language` / package manager.
For pre-commit: see [here](https://github.com/pre-commit/pre-commit)
For typstfmt: see [here](https://github.com/astrale-sharp/typstfmt)
## Using typstfmt with pre-commit and conda:
Add this to your `.pre-commit-config.yaml`
```yaml
- repo: https://github.com/quantco/pre-commit-mirrors-typstfmt
rev: '' # Use the sha / tag you want to point at
hooks:
- id: typstfmt-conda
```
|
https://github.com/jamesrswift/dining-table | https://raw.githubusercontent.com/jamesrswift/dining-table/main/README.md | markdown | The Unlicense | # The `dining-table` Package
<div align="center">Version 0.1.1</div>
Implements a layer on top of table to allow the user to define a table by column rather than by row, to automatically handle headers and footers, to implement table footnotes, to handle nested column quirks for you, to handle rendering nested data structures.
Basically, if you are tabulating data where each row is an observation, and some features (columns) are to be grouped (a common case for scientific data) then this package might be worth checking out. Another use case is where you have multiple tables with identical layouts, and you wish to keep them all consistent with one another.
<img alt="Light" src="./examples/ledger.png">
## Usage
See the manual for in-depth usage, but for a quick reference, here is the ledger example (which is fully featured)
```typ
#import "@preview/dining-table:0.1.1"
#let data = (
(
date: datetime.today(),
particulars: lorem(05),
ledger: [JRS123] + dining-table.note.make[Hello World],
amount: (unit: $100$, decimal: $00$),
total: (unit: $99$, decimal: $00$),
),
)*7
#import "@preview/typpuccino:0.1.0"
#let bg-fill-1 = typpuccino.latte.base
#let bg-fill-2 = typpuccino.latte.mantle
#let example = (
(
key: "date",
header: align(left)[Date],
display: (it)=>it.display(auto),
fill: bg-fill-1,
align: start,
gutter: 0.5em,
),
(
key: "particulars",
header: text(tracking: 5pt)[Particulars],
width: 1fr,
gutter: 0.5em,
),
(
key: "ledger",
header: [Ledger],
fill: bg-fill-2,
width: 2cm,
gutter: 0.5em,
),
(
header: align(center)[Amount],
fill: bg-fill-1,
gutter: 0.5em,
hline: arguments(stroke: dining-table.lightrule),
children: (
(
key: "amount.unit",
header: align(left)[£],
width: 5em,
align: right,
vline: arguments(stroke: dining-table.lightrule),
gutter: 0em,
),
(
key: "amount.decimal",
header: align(right, text(number-type: "old-style")[.00]),
align: left
),
)
),
(
header: align(center)[Total],
gutter: 0.5em,
hline: arguments(stroke: dining-table.lightrule),
children: (
(
key: "total.unit",
header: align(left)[£],
width: 5em,
align: right,
vline: arguments(stroke: dining-table.lightrule),
gutter: 0em,
),
(
key: "total.decimal",
header: align(right, text(number-type: "old-style")[.00]),
align: left
),
)
),
)
#set text(size: 11pt)
#set page(height: auto, margin: 1em)
#dining-table.make(columns: example,
data: data,
notes: dining-table.note.display-list
)
```
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10350.typ | typst | Apache License 2.0 | #let data = (
("OLD PERMIC LETTER AN", "Lo", 0),
("OLD PERMIC LETTER BUR", "Lo", 0),
("OLD PERMIC LETTER GAI", "Lo", 0),
("OLD PERMIC LETTER DOI", "Lo", 0),
("OLD PERMIC LETTER E", "Lo", 0),
("OLD PERMIC LETTER ZHOI", "Lo", 0),
("OLD PERMIC LETTER DZHOI", "Lo", 0),
("OLD PERMIC LETTER ZATA", "Lo", 0),
("OLD PERMIC LETTER DZITA", "Lo", 0),
("OLD PERMIC LETTER I", "Lo", 0),
("OLD PERMIC LETTER KOKE", "Lo", 0),
("OLD PERMIC LETTER LEI", "Lo", 0),
("OLD PERMIC LETTER MENOE", "Lo", 0),
("OLD PERMIC LETTER NENOE", "Lo", 0),
("OLD PERMIC LETTER VOOI", "Lo", 0),
("OLD PERMIC LETTER PEEI", "Lo", 0),
("OLD PERMIC LETTER REI", "Lo", 0),
("OLD PERMIC LETTER SII", "Lo", 0),
("OLD PERMIC LETTER TAI", "Lo", 0),
("OLD PERMIC LETTER U", "Lo", 0),
("OLD PERMIC LETTER CHERY", "Lo", 0),
("OLD PERMIC LETTER SHOOI", "Lo", 0),
("OLD PERMIC LETTER SHCHOOI", "Lo", 0),
("OLD PERMIC LETTER YRY", "Lo", 0),
("OLD PERMIC LETTER YERU", "Lo", 0),
("OLD PERMIC LETTER O", "Lo", 0),
("OLD PERMIC LETTER OO", "Lo", 0),
("OLD PERMIC LETTER EF", "Lo", 0),
("OLD PERMIC LETTER HA", "Lo", 0),
("OLD PERMIC LETTER TSIU", "Lo", 0),
("OLD PERMIC LETTER VER", "Lo", 0),
("OLD PERMIC LETTER YER", "Lo", 0),
("OLD PERMIC LETTER YERI", "Lo", 0),
("OLD PERMIC LETTER YAT", "Lo", 0),
("OLD PERMIC LETTER IE", "Lo", 0),
("OLD PERMIC LETTER YU", "Lo", 0),
("OLD PERMIC LETTER YA", "Lo", 0),
("OLD PERMIC LETTER IA", "Lo", 0),
("COMBINING OLD PERMIC LETTER AN", "Mn", 230),
("COMBINING OLD PERMIC LETTER DOI", "Mn", 230),
("COMBINING OLD PERMIC LETTER ZATA", "Mn", 230),
("COMBINING OLD PERMIC LETTER NENOE", "Mn", 230),
("COMBINING OLD PERMIC LETTER SII", "Mn", 230),
)
|
https://github.com/3w36zj6/typst-template | https://raw.githubusercontent.com/3w36zj6/typst-template/main/README.md | markdown | # typst-template
## Requirements
### Typst
https://github.com/typst/typst
```sh
cargo install --git https://github.com/typst/typst --locked typst-cli --tag v0.11.0
```
### typstyle
https://github.com/Enter-tainer/typstyle
```sh
cargo install typstyle
```
### Tinymist
https://github.com/Myriad-Dreamin/tinymist
- [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist)
- [Open VSX](https://open-vsx.org/extension/myriad-dreamin/tinymist)
## Templates
### Article
[原ノ味フォント](https://github.com/trueroad/HaranoAjiFonts)と[白源](https://github.com/yuru7/HackGen)のNerd Fonts合成版が必要です。
|
|
https://github.com/George-Miao/typst-common | https://raw.githubusercontent.com/George-Miao/typst-common/main/0.2.0/src/math.typ | typst | MIT License | /* Util Functions */
#let pmod(e) = [ $(mod #e)$ ] // (P)arenthesis (Mod)ulo
#let con(l, r, p, inline: false) = {
// Congruence
if inline {
$#l ident #r #pmod(p)$
} else {
$#l ident #r #h(.5em) #pmod(p)$
}
}
// A tuple surrounded by angle brackets
#let tup(..body) = {
let b = body.pos().join([, #h(3pt) ])
[ $angle.l #b angle.r$ ]
}
#let paren(..body) = {
let b = body.pos().join(h(5pt))
[ $(#b)$ ]
}
// Vector variable (accent with arrow)
#let ve(body) = {
$accent(#body, arrow)$
}
#let at(..body) = {
math.lr($#h(0em) #body.pos().join(",") #h(0.1em) |$, size: 120%)
}
#let ex(..body) = {
$exists #body.pos().join(","). thick$
}
#let ex1(..body) = {
$exists! #body.pos().join(","). thick$
}
#let fa(..body) = {
$forall #body.pos().join(","). thick$
}
/* Alias, consts */
#let xlra = sym.arrow.l.r.long // Long left right arrow
#let lra = sym.arrow.l.r // Left right arrow
#let mapsto = sym.arrow.r.long.bar // Mapsto
#let lcm = {
math.op("lcm")
} // Least common multiplier
#let na = sym.nabla // Nabla
#let circ = sym.compose // Compiose (circ)
#let comp = sym.complement // Complement
#let pm = sym.plus.minus // Plus Minus
#let sim = sym.tilde.op // Sim
#let ne = sym.eq.not // Not equal
#let iso = sym.tilde.equiv // Isomorphic or homeomorphic
#let contains = sym.in.rev // Contains (in but reversed)
#let nothing = $text(font: "Fira Sans", nothing)$ // Round empty set
#let emptyset = nothing // Empty set
#let power = math.cal($P$) // Power set
#let sends = sym.arrow.r.long.bar // |-->
#let dot = math.op(sym.circle.filled.tiny) // Dot
#let Sect = sym.sect.big // Big intersection
#let Union = sym.union.big // Big union
#let detmat = math.mat.with(delim: "|")
#let dom = math.op("dom") // Domain
#let obj = math.op("obj") // Object
#let Var = math.op("Var") // Variance
// Topology
#let bd = math.op("Bd") // Boundary
#let clo = math.overline // Closure
#let topo = math.cal($T$) // Topoolgy
#let base = math.cal($B$) // Basis
#let neib = math.cal($N$) // Neighborhood basis
#let lebe = math.cal($S$) // Lebesgue number
#let dju = math.op(sym.union.sq) // Disjoint union
// Calculus
#let na = sym.nabla
#let dx = $thick d x$
#let dy = $thick d y$
#let dz = $thick d z$
#let dt = $thick d t$
#let du = $thick d u$
#let dv = $thick d v$
#let dk = $thick d k$
#let dA = $thick d A$
#let dV = $thick d V$
#let ds = $thick d s$
#let dvx = $thick d ve(x)$
#let dphi = $thick d phi$
#let dtheta = $thick d theta$
#let int = sym.integral
#let iint = sym.integral.double
#let iiint = sym.integral.triple
// Set
#let ss = sym.subset
#let sse = sym.subset.eq
// Logic
#let nec = symbol("□") // Modal logic neccessity
#let pos = symbol("♢") // Modal logic possibility
#let vd = sym.tack.r
#let vD = sym.tack.r.double
#let iff = sym.arrow.l.r.double.long
#let implies = sym.arrow.r.double.long
#let ni = symbol(
"⥽",
("l", "⥼"),
("r", "⥽"),
("t", "⥾"),
("b", "⥿"),
) // Necessarily implies
#let asymp = symbol("≍") // Asymptotically equal to
// Category theory
#let hom = math.op("Hom")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/codly/0.1.0/example/main.typ | typst | Apache License 2.0 | #import "../codly.typ": *
#show: codly-init.with()
#let icon(codepoint) = {
box(
height: 0.8em,
baseline: 0.05em,
image(codepoint)
)
h(0.1em)
}
#codly(languages: (
rust: (name: "Rust", icon: icon("brand-python.svg"), color: rgb("#CE412B")),
python: (name: "Python", icon: icon("brand-rust.svg"), color: rgb("#3572A5")),
))
```rust
pub fn main() {
println!("Hello, world!");
}
```
```python
def fibonaci(n):
if n <= 1:
return n
else:
return(fibonaci(n-1) + fibonaci(n-2))
```
We can also set a line number offset with `codly-offset(int)`:
#codly-offset(offset: 1)
```rust
println!("Hello, world!");
```
And we can also disable line numbers:
#codly(width-numbers: none)
```rust
pub fn main() {
println!("Hello, world!");
}
```
We can also select only a range of lines to show:
#codly-range(start: 5, end: 5)
```python
def fibonaci(n):
if n <= 1:
return n
else:
return(fibonaci(n-1) + fibonaci(n-2))
```
#codly(
stroke-width: 1pt,
stroke-color: red,
)
```rust
pub fn main() {
println!("Hello, world!");
}
```
#codly(
display-icon: false,
)
```rust
pub fn main() {
println!("Hello, world!");
}
``` |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-14400.typ | typst | Apache License 2.0 | #let data = (
("ANATOLIAN HIEROGLYPH A001", "Lo", 0),
("ANATOLIAN HIEROGLYPH A002", "Lo", 0),
("ANATOLIAN HIEROGLYPH A003", "Lo", 0),
("ANATOLIAN HIEROGLYPH A004", "Lo", 0),
("ANATOLIAN HIEROGLYPH A005", "Lo", 0),
("ANATOLIAN HIEROGLYPH A006", "Lo", 0),
("ANATOLIAN HIEROGLYPH A007", "Lo", 0),
("ANATOLIAN HIEROGLYPH A008", "Lo", 0),
("ANATOLIAN HIEROGLYPH A009", "Lo", 0),
("ANATOLIAN HIEROGLYPH A010", "Lo", 0),
("ANATOLIAN HIEROGLYPH A010A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A011", "Lo", 0),
("ANATOLIAN HIEROGLYPH A012", "Lo", 0),
("ANATOLIAN HIEROGLYPH A013", "Lo", 0),
("ANATOLIAN HIEROGLYPH A014", "Lo", 0),
("ANATOLIAN HIEROGLYPH A015", "Lo", 0),
("ANATOLIAN HIEROGLYPH A016", "Lo", 0),
("ANATOLIAN HIEROGLYPH A017", "Lo", 0),
("ANATOLIAN HIEROGLYPH A018", "Lo", 0),
("ANATOLIAN HIEROGLYPH A019", "Lo", 0),
("ANATOLIAN HIEROGLYPH A020", "Lo", 0),
("ANATOLIAN HIEROGLYPH A021", "Lo", 0),
("ANATOLIAN HIEROGLYPH A022", "Lo", 0),
("ANATOLIAN HIEROGLYPH A023", "Lo", 0),
("ANATOLIAN HIEROGLYPH A024", "Lo", 0),
("ANATOLIAN HIEROGLYPH A025", "Lo", 0),
("ANATOLIAN HIEROGLYPH A026", "Lo", 0),
("ANATOLIAN HIEROGLYPH A026A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A027", "Lo", 0),
("ANATOLIAN HIEROGLYPH A028", "Lo", 0),
("ANATOLIAN HIEROGLYPH A029", "Lo", 0),
("ANATOLIAN HIEROGLYPH A030", "Lo", 0),
("ANATOLIAN HIEROGLYPH A031", "Lo", 0),
("ANATOLIAN HIEROGLYPH A032", "Lo", 0),
("ANATOLIAN HIEROGLYPH A033", "Lo", 0),
("ANATOLIAN HIEROGLYPH A034", "Lo", 0),
("ANATOLIAN HIEROGLYPH A035", "Lo", 0),
("ANATOLIAN HIEROGLYPH A036", "Lo", 0),
("ANATOLIAN HIEROGLYPH A037", "Lo", 0),
("ANATOLIAN HIEROGLYPH A038", "Lo", 0),
("ANATOLIAN HIEROGLYPH A039", "Lo", 0),
("ANATOLIAN HIEROGLYPH A039A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A040", "Lo", 0),
("ANATOLIAN HIEROGLYPH A041", "Lo", 0),
("ANATOLIAN HIEROGLYPH A041A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A042", "Lo", 0),
("ANATOLIAN HIEROGLYPH A043", "Lo", 0),
("ANATOLIAN HIEROGLYPH A044", "Lo", 0),
("ANATOLIAN HIEROGLYPH A045", "Lo", 0),
("ANATOLIAN HIEROGLYPH A045A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A046", "Lo", 0),
("ANATOLIAN HIEROGLYPH A046A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A046B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A047", "Lo", 0),
("ANATOLIAN HIEROGLYPH A048", "Lo", 0),
("ANATOLIAN HIEROGLYPH A049", "Lo", 0),
("ANATOLIAN HIEROGLYPH A050", "Lo", 0),
("ANATOLIAN HIEROGLYPH A051", "Lo", 0),
("ANATOLIAN HIEROGLYPH A052", "Lo", 0),
("ANATOLIAN HIEROGLYPH A053", "Lo", 0),
("ANATOLIAN HIEROGLYPH A054", "Lo", 0),
("ANATOLIAN HIEROGLYPH A055", "Lo", 0),
("ANATOLIAN HIEROGLYPH A056", "Lo", 0),
("ANATOLIAN HIEROGLYPH A057", "Lo", 0),
("ANATOLIAN HIEROGLYPH A058", "Lo", 0),
("ANATOLIAN HIEROGLYPH A059", "Lo", 0),
("ANATOLIAN HIEROGLYPH A060", "Lo", 0),
("ANATOLIAN HIEROGLYPH A061", "Lo", 0),
("ANATOLIAN HIEROGLYPH A062", "Lo", 0),
("ANATOLIAN HIEROGLYPH A063", "Lo", 0),
("ANATOLIAN HIEROGLYPH A064", "Lo", 0),
("ANATOLIAN HIEROGLYPH A065", "Lo", 0),
("ANATOLIAN HIEROGLYPH A066", "Lo", 0),
("ANATOLIAN HIEROGLYPH A066A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A066B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A066C", "Lo", 0),
("ANATOLIAN HIEROGLYPH A067", "Lo", 0),
("ANATOLIAN HIEROGLYPH A068", "Lo", 0),
("ANATOLIAN HIEROGLYPH A069", "Lo", 0),
("ANATOLIAN HIEROGLYPH A070", "Lo", 0),
("ANATOLIAN HIEROGLYPH A071", "Lo", 0),
("ANATOLIAN HIEROGLYPH A072", "Lo", 0),
("ANATOLIAN HIEROGLYPH A073", "Lo", 0),
("ANATOLIAN HIEROGLYPH A074", "Lo", 0),
("ANATOLIAN HIEROGLYPH A075", "Lo", 0),
("ANATOLIAN HIEROGLYPH A076", "Lo", 0),
("ANATOLIAN HIEROGLYPH A077", "Lo", 0),
("ANATOLIAN HIEROGLYPH A078", "Lo", 0),
("ANATOLIAN HIEROGLYPH A079", "Lo", 0),
("ANATOLIAN HIEROGLYPH A080", "Lo", 0),
("ANATOLIAN HIEROGLYPH A081", "Lo", 0),
("ANATOLIAN HIEROGLYPH A082", "Lo", 0),
("ANATOLIAN HIEROGLYPH A083", "Lo", 0),
("ANATOLIAN HIEROGLYPH A084", "Lo", 0),
("ANATOLIAN HIEROGLYPH A085", "Lo", 0),
("ANATOLIAN HIEROGLYPH A086", "Lo", 0),
("ANATOLIAN HIEROGLYPH A087", "Lo", 0),
("ANATOLIAN HIEROGLYPH A088", "Lo", 0),
("ANATOLIAN HIEROGLYPH A089", "Lo", 0),
("ANATOLIAN HIEROGLYPH A090", "Lo", 0),
("ANATOLIAN HIEROGLYPH A091", "Lo", 0),
("ANATOLIAN HIEROGLYPH A092", "Lo", 0),
("ANATOLIAN HIEROGLYPH A093", "Lo", 0),
("ANATOLIAN HIEROGLYPH A094", "Lo", 0),
("ANATOLIAN HIEROGLYPH A095", "Lo", 0),
("ANATOLIAN HIEROGLYPH A096", "Lo", 0),
("ANATOLIAN HIEROGLYPH A097", "Lo", 0),
("ANATOLIAN HIEROGLYPH A097A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A098", "Lo", 0),
("ANATOLIAN HIEROGLYPH A098A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A099", "Lo", 0),
("ANATOLIAN HIEROGLYPH A100", "Lo", 0),
("ANATOLIAN HIEROGLYPH A100A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A101", "Lo", 0),
("ANATOLIAN HIEROGLYPH A101A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A102", "Lo", 0),
("ANATOLIAN HIEROGLYPH A102A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A103", "Lo", 0),
("ANATOLIAN HIEROGLYPH A104", "Lo", 0),
("ANATOLIAN HIEROGLYPH A104A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A104B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A104C", "Lo", 0),
("ANATOLIAN HIEROGLYPH A105", "Lo", 0),
("ANATOLIAN HIEROGLYPH A105A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A105B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A106", "Lo", 0),
("ANATOLIAN HIEROGLYPH A107", "Lo", 0),
("ANATOLIAN HIEROGLYPH A107A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A107B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A107C", "Lo", 0),
("ANATOLIAN HIEROGLYPH A108", "Lo", 0),
("ANATOLIAN HIEROGLYPH A109", "Lo", 0),
("ANATOLIAN HIEROGLYPH A110", "Lo", 0),
("ANATOLIAN HIEROGLYPH A110A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A110B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A111", "Lo", 0),
("ANATOLIAN HIEROGLYPH A112", "Lo", 0),
("ANATOLIAN HIEROGLYPH A113", "Lo", 0),
("ANATOLIAN HIEROGLYPH A114", "Lo", 0),
("ANATOLIAN HIEROGLYPH A115", "Lo", 0),
("ANATOLIAN HIEROGLYPH A115A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A116", "Lo", 0),
("ANATOLIAN HIEROGLYPH A117", "Lo", 0),
("ANATOLIAN HIEROGLYPH A118", "Lo", 0),
("ANATOLIAN HIEROGLYPH A119", "Lo", 0),
("ANATOLIAN HIEROGLYPH A120", "Lo", 0),
("ANATOLIAN HIEROGLYPH A121", "Lo", 0),
("ANATOLIAN HIEROGLYPH A122", "Lo", 0),
("ANATOLIAN HIEROGLYPH A123", "Lo", 0),
("ANATOLIAN HIEROGLYPH A124", "Lo", 0),
("ANATOLIAN HIEROGLYPH A125", "Lo", 0),
("ANATOLIAN HIEROGLYPH A125A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A126", "Lo", 0),
("ANATOLIAN HIEROGLYPH A127", "Lo", 0),
("ANATOLIAN HIEROGLYPH A128", "Lo", 0),
("ANATOLIAN HIEROGLYPH A129", "Lo", 0),
("ANATOLIAN HIEROGLYPH A130", "Lo", 0),
("ANATOLIAN HIEROGLYPH A131", "Lo", 0),
("ANATOLIAN HIEROGLYPH A132", "Lo", 0),
("ANATOLIAN HIEROGLYPH A133", "Lo", 0),
("ANATOLIAN HIEROGLYPH A134", "Lo", 0),
("ANATOLIAN HIEROGLYPH A135", "Lo", 0),
("ANATOLIAN HIEROGLYPH A135A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A136", "Lo", 0),
("ANATOLIAN HIEROGLYPH A137", "Lo", 0),
("ANATOLIAN HIEROGLYPH A138", "Lo", 0),
("ANATOLIAN HIEROGLYPH A139", "Lo", 0),
("ANATOLIAN HIEROGLYPH A140", "Lo", 0),
("ANATOLIAN HIEROGLYPH A141", "Lo", 0),
("ANATOLIAN HIEROGLYPH A142", "Lo", 0),
("ANATOLIAN HIEROGLYPH A143", "Lo", 0),
("ANATOLIAN HIEROGLYPH A144", "Lo", 0),
("ANATOLIAN HIEROGLYPH A145", "Lo", 0),
("ANATOLIAN HIEROGLYPH A146", "Lo", 0),
("ANATOLIAN HIEROGLYPH A147", "Lo", 0),
("ANATOLIAN HIEROGLYPH A148", "Lo", 0),
("ANATOLIAN HIEROGLYPH A149", "Lo", 0),
("ANATOLIAN HIEROGLYPH A150", "Lo", 0),
("ANATOLIAN HIEROGLYPH A151", "Lo", 0),
("ANATOLIAN HIEROGLYPH A152", "Lo", 0),
("ANATOLIAN HIEROGLYPH A153", "Lo", 0),
("ANATOLIAN HIEROGLYPH A154", "Lo", 0),
("ANATOLIAN HIEROGLYPH A155", "Lo", 0),
("ANATOLIAN HIEROGLYPH A156", "Lo", 0),
("ANATOLIAN HIEROGLYPH A157", "Lo", 0),
("ANATOLIAN HIEROGLYPH A158", "Lo", 0),
("ANATOLIAN HIEROGLYPH A159", "Lo", 0),
("ANATOLIAN HIEROGLYPH A160", "Lo", 0),
("ANATOLIAN HIEROGLYPH A161", "Lo", 0),
("ANATOLIAN HIEROGLYPH A162", "Lo", 0),
("ANATOLIAN HIEROGLYPH A163", "Lo", 0),
("ANATOLIAN HIEROGLYPH A164", "Lo", 0),
("ANATOLIAN HIEROGLYPH A165", "Lo", 0),
("ANATOLIAN HIEROGLYPH A166", "Lo", 0),
("ANATOLIAN HIEROGLYPH A167", "Lo", 0),
("ANATOLIAN HIEROGLYPH A168", "Lo", 0),
("ANATOLIAN HIEROGLYPH A169", "Lo", 0),
("ANATOLIAN HIEROGLYPH A170", "Lo", 0),
("ANATOLIAN HIEROGLYPH A171", "Lo", 0),
("ANATOLIAN HIEROGLYPH A172", "Lo", 0),
("ANATOLIAN HIEROGLYPH A173", "Lo", 0),
("ANATOLIAN HIEROGLYPH A174", "Lo", 0),
("ANATOLIAN HIEROGLYPH A175", "Lo", 0),
("ANATOLIAN HIEROGLYPH A176", "Lo", 0),
("ANATOLIAN HIEROGLYPH A177", "Lo", 0),
("ANATOLIAN HIEROGLYPH A178", "Lo", 0),
("ANATOLIAN HIEROGLYPH A179", "Lo", 0),
("ANATOLIAN HIEROGLYPH A180", "Lo", 0),
("ANATOLIAN HIEROGLYPH A181", "Lo", 0),
("ANATOLIAN HIEROGLYPH A182", "Lo", 0),
("ANATOLIAN HIEROGLYPH A183", "Lo", 0),
("ANATOLIAN HIEROGLYPH A184", "Lo", 0),
("ANATOLIAN HIEROGLYPH A185", "Lo", 0),
("ANATOLIAN HIEROGLYPH A186", "Lo", 0),
("ANATOLIAN HIEROGLYPH A187", "Lo", 0),
("ANATOLIAN HIEROGLYPH A188", "Lo", 0),
("ANATOLIAN HIEROGLYPH A189", "Lo", 0),
("ANATOLIAN HIEROGLYPH A190", "Lo", 0),
("ANATOLIAN HIEROGLYPH A191", "Lo", 0),
("ANATOLIAN HIEROGLYPH A192", "Lo", 0),
("ANATOLIAN HIEROGLYPH A193", "Lo", 0),
("ANATOLIAN HIEROGLYPH A194", "Lo", 0),
("ANATOLIAN HIEROGLYPH A195", "Lo", 0),
("ANATOLIAN HIEROGLYPH A196", "Lo", 0),
("ANATOLIAN HIEROGLYPH A197", "Lo", 0),
("ANATOLIAN HIEROGLYPH A198", "Lo", 0),
("ANATOLIAN HIEROGLYPH A199", "Lo", 0),
("ANATOLIAN HIEROGLYPH A200", "Lo", 0),
("ANATOLIAN HIEROGLYPH A201", "Lo", 0),
("ANATOLIAN HIEROGLYPH A202", "Lo", 0),
("ANATOLIAN HIEROGLYPH A202A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A202B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A203", "Lo", 0),
("ANATOLIAN HIEROGLYPH A204", "Lo", 0),
("ANATOLIAN HIEROGLYPH A205", "Lo", 0),
("ANATOLIAN HIEROGLYPH A206", "Lo", 0),
("ANATOLIAN HIEROGLYPH A207", "Lo", 0),
("ANATOLIAN HIEROGLYPH A207A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A208", "Lo", 0),
("ANATOLIAN HIEROGLYPH A209", "Lo", 0),
("ANATOLIAN HIEROGLYPH A209A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A210", "Lo", 0),
("ANATOLIAN HIEROGLYPH A211", "Lo", 0),
("ANATOLIAN HIEROGLYPH A212", "Lo", 0),
("ANATOLIAN HIEROGLYPH A213", "Lo", 0),
("ANATOLIAN HIEROGLYPH A214", "Lo", 0),
("ANATOLIAN HIEROGLYPH A215", "Lo", 0),
("ANATOLIAN HIEROGLYPH A215A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A216", "Lo", 0),
("ANATOLIAN HIEROGLYPH A216A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A217", "Lo", 0),
("ANATOLIAN HIEROGLYPH A218", "Lo", 0),
("ANATOLIAN HIEROGLYPH A219", "Lo", 0),
("ANATOLIAN HIEROGLYPH A220", "Lo", 0),
("ANATOLIAN HIEROGLYPH A221", "Lo", 0),
("ANATOLIAN HIEROGLYPH A222", "Lo", 0),
("ANATOLIAN HIEROGLYPH A223", "Lo", 0),
("ANATOLIAN HIEROGLYPH A224", "Lo", 0),
("ANATOLIAN HIEROGLYPH A225", "Lo", 0),
("ANATOLIAN HIEROGLYPH A226", "Lo", 0),
("ANATOLIAN HIEROGLYPH A227", "Lo", 0),
("ANATOLIAN HIEROGLYPH A227A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A228", "Lo", 0),
("ANATOLIAN HIEROGLYPH A229", "Lo", 0),
("ANATOLIAN HIEROGLYPH A230", "Lo", 0),
("ANATOLIAN HIEROGLYPH A231", "Lo", 0),
("ANATOLIAN HIEROGLYPH A232", "Lo", 0),
("ANATOLIAN HIEROGLYPH A233", "Lo", 0),
("ANATOLIAN HIEROGLYPH A234", "Lo", 0),
("ANATOLIAN HIEROGLYPH A235", "Lo", 0),
("ANATOLIAN HIEROGLYPH A236", "Lo", 0),
("ANATOLIAN HIEROGLYPH A237", "Lo", 0),
("ANATOLIAN HIEROGLYPH A238", "Lo", 0),
("ANATOLIAN HIEROGLYPH A239", "Lo", 0),
("ANATOLIAN HIEROGLYPH A240", "Lo", 0),
("ANATOLIAN HIEROGLYPH A241", "Lo", 0),
("ANATOLIAN HIEROGLYPH A242", "Lo", 0),
("ANATOLIAN HIEROGLYPH A243", "Lo", 0),
("ANATOLIAN HIEROGLYPH A244", "Lo", 0),
("ANATOLIAN HIEROGLYPH A245", "Lo", 0),
("ANATOLIAN HIEROGLYPH A246", "Lo", 0),
("ANATOLIAN HIEROGLYPH A247", "Lo", 0),
("ANATOLIAN HIEROGLYPH A248", "Lo", 0),
("ANATOLIAN HIEROGLYPH A249", "Lo", 0),
("ANATOLIAN HIEROGLYPH A250", "Lo", 0),
("ANATOLIAN HIEROGLYPH A251", "Lo", 0),
("ANATOLIAN HIEROGLYPH A252", "Lo", 0),
("ANATOLIAN HIEROGLYPH A253", "Lo", 0),
("ANATOLIAN HIEROGLYPH A254", "Lo", 0),
("ANATOLIAN HIEROGLYPH A255", "Lo", 0),
("ANATOLIAN HIEROGLYPH A256", "Lo", 0),
("ANATOLIAN HIEROGLYPH A257", "Lo", 0),
("ANATOLIAN HIEROGLYPH A258", "Lo", 0),
("ANATOLIAN HIEROGLYPH A259", "Lo", 0),
("ANATOLIAN HIEROGLYPH A260", "Lo", 0),
("ANATOLIAN HIEROGLYPH A261", "Lo", 0),
("ANATOLIAN HIEROGLYPH A262", "Lo", 0),
("ANATOLIAN HIEROGLYPH A263", "Lo", 0),
("ANATOLIAN HIEROGLYPH A264", "Lo", 0),
("ANATOLIAN HIEROGLYPH A265", "Lo", 0),
("ANATOLIAN HIEROGLYPH A266", "Lo", 0),
("ANATOLIAN HIEROGLYPH A267", "Lo", 0),
("ANATOLIAN HIEROGLYPH A267A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A268", "Lo", 0),
("ANATOLIAN HIEROGLYPH A269", "Lo", 0),
("ANATOLIAN HIEROGLYPH A270", "Lo", 0),
("ANATOLIAN HIEROGLYPH A271", "Lo", 0),
("ANATOLIAN HIEROGLYPH A272", "Lo", 0),
("ANATOLIAN HIEROGLYPH A273", "Lo", 0),
("ANATOLIAN HIEROGLYPH A274", "Lo", 0),
("ANATOLIAN HIEROGLYPH A275", "Lo", 0),
("ANATOLIAN HIEROGLYPH A276", "Lo", 0),
("ANATOLIAN HIEROGLYPH A277", "Lo", 0),
("ANATOLIAN HIEROGLYPH A278", "Lo", 0),
("ANATOLIAN HIEROGLYPH A279", "Lo", 0),
("ANATOLIAN HIEROGLYPH A280", "Lo", 0),
("ANATOLIAN HIEROGLYPH A281", "Lo", 0),
("ANATOLIAN HIEROGLYPH A282", "Lo", 0),
("ANATOLIAN HIEROGLYPH A283", "Lo", 0),
("ANATOLIAN HIEROGLYPH A284", "Lo", 0),
("ANATOLIAN HIEROGLYPH A285", "Lo", 0),
("ANATOLIAN HIEROGLYPH A286", "Lo", 0),
("ANATOLIAN HIEROGLYPH A287", "Lo", 0),
("ANATOLIAN HIEROGLYPH A288", "Lo", 0),
("ANATOLIAN HIEROGLYPH A289", "Lo", 0),
("ANATOLIAN HIEROGLYPH A289A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A290", "Lo", 0),
("ANATOLIAN HIEROGLYPH A291", "Lo", 0),
("ANATOLIAN HIEROGLYPH A292", "Lo", 0),
("ANATOLIAN HIEROGLYPH A293", "Lo", 0),
("ANATOLIAN HIEROGLYPH A294", "Lo", 0),
("ANATOLIAN HIEROGLYPH A294A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A295", "Lo", 0),
("ANATOLIAN HIEROGLYPH A296", "Lo", 0),
("ANATOLIAN HIEROGLYPH A297", "Lo", 0),
("ANATOLIAN HIEROGLYPH A298", "Lo", 0),
("ANATOLIAN HIEROGLYPH A299", "Lo", 0),
("ANATOLIAN HIEROGLYPH A299A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A300", "Lo", 0),
("ANATOLIAN HIEROGLYPH A301", "Lo", 0),
("ANATOLIAN HIEROGLYPH A302", "Lo", 0),
("ANATOLIAN HIEROGLYPH A303", "Lo", 0),
("ANATOLIAN HIEROGLYPH A304", "Lo", 0),
("ANATOLIAN HIEROGLYPH A305", "Lo", 0),
("ANATOLIAN HIEROGLYPH A306", "Lo", 0),
("ANATOLIAN HIEROGLYPH A307", "Lo", 0),
("ANATOLIAN HIEROGLYPH A308", "Lo", 0),
("ANATOLIAN HIEROGLYPH A309", "Lo", 0),
("ANATOLIAN HIEROGLYPH A309A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A310", "Lo", 0),
("ANATOLIAN HIEROGLYPH A311", "Lo", 0),
("ANATOLIAN HIEROGLYPH A312", "Lo", 0),
("ANATOLIAN HIEROGLYPH A313", "Lo", 0),
("ANATOLIAN HIEROGLYPH A314", "Lo", 0),
("ANATOLIAN HIEROGLYPH A315", "Lo", 0),
("ANATOLIAN HIEROGLYPH A316", "Lo", 0),
("ANATOLIAN HIEROGLYPH A317", "Lo", 0),
("ANATOLIAN HIEROGLYPH A318", "Lo", 0),
("ANATOLIAN HIEROGLYPH A319", "Lo", 0),
("ANATOLIAN HIEROGLYPH A320", "Lo", 0),
("ANATOLIAN HIEROGLYPH A321", "Lo", 0),
("ANATOLIAN HIEROGLYPH A322", "Lo", 0),
("ANATOLIAN HIEROGLYPH A323", "Lo", 0),
("ANATOLIAN HIEROGLYPH A324", "Lo", 0),
("ANATOLIAN HIEROGLYPH A325", "Lo", 0),
("ANATOLIAN HIEROGLYPH A326", "Lo", 0),
("ANATOLIAN HIEROGLYPH A327", "Lo", 0),
("ANATOLIAN HIEROGLYPH A328", "Lo", 0),
("ANATOLIAN HIEROGLYPH A329", "Lo", 0),
("ANATOLIAN HIEROGLYPH A329A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A330", "Lo", 0),
("ANATOLIAN HIEROGLYPH A331", "Lo", 0),
("ANATOLIAN HIEROGLYPH A332A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A332B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A332C", "Lo", 0),
("ANATOLIAN HIEROGLYPH A333", "Lo", 0),
("ANATOLIAN HIEROGLYPH A334", "Lo", 0),
("ANATOLIAN HIEROGLYPH A335", "Lo", 0),
("ANATOLIAN HIEROGLYPH A336", "Lo", 0),
("ANATOLIAN HIEROGLYPH A336A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A336B", "Lo", 0),
("ANATOLIAN HIEROGLYPH A336C", "Lo", 0),
("ANATOLIAN HIEROGLYPH A337", "Lo", 0),
("ANATOLIAN HIEROGLYPH A338", "Lo", 0),
("ANATOLIAN HIEROGLYPH A339", "Lo", 0),
("ANATOLIAN HIEROGLYPH A340", "Lo", 0),
("ANATOLIAN HIEROGLYPH A341", "Lo", 0),
("ANATOLIAN HIEROGLYPH A342", "Lo", 0),
("ANATOLIAN HIEROGLYPH A343", "Lo", 0),
("ANATOLIAN HIEROGLYPH A344", "Lo", 0),
("ANATOLIAN HIEROGLYPH A345", "Lo", 0),
("ANATOLIAN HIEROGLYPH A346", "Lo", 0),
("ANATOLIAN HIEROGLYPH A347", "Lo", 0),
("ANATOLIAN HIEROGLYPH A348", "Lo", 0),
("ANATOLIAN HIEROGLYPH A349", "Lo", 0),
("ANATOLIAN HIEROGLYPH A350", "Lo", 0),
("ANATOLIAN HIEROGLYPH A351", "Lo", 0),
("ANATOLIAN HIEROGLYPH A352", "Lo", 0),
("ANATOLIAN HIEROGLYPH A353", "Lo", 0),
("ANATOLIAN HIEROGLYPH A354", "Lo", 0),
("ANATOLIAN HIEROGLYPH A355", "Lo", 0),
("ANATOLIAN HIEROGLYPH A356", "Lo", 0),
("ANATOLIAN HIEROGLYPH A357", "Lo", 0),
("ANATOLIAN HIEROGLYPH A358", "Lo", 0),
("ANATOLIAN HIEROGLYPH A359", "Lo", 0),
("ANATOLIAN HIEROGLYPH A359A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A360", "Lo", 0),
("ANATOLIAN HIEROGLYPH A361", "Lo", 0),
("ANATOLIAN HIEROGLYPH A362", "Lo", 0),
("ANATOLIAN HIEROGLYPH A363", "Lo", 0),
("ANATOLIAN HIEROGLYPH A364", "Lo", 0),
("ANATOLIAN HIEROGLYPH A364A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A365", "Lo", 0),
("ANATOLIAN HIEROGLYPH A366", "Lo", 0),
("ANATOLIAN HIEROGLYPH A367", "Lo", 0),
("ANATOLIAN HIEROGLYPH A368", "Lo", 0),
("ANATOLIAN HIEROGLYPH A368A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A369", "Lo", 0),
("ANATOLIAN HIEROGLYPH A370", "Lo", 0),
("ANATOLIAN HIEROGLYPH A371", "Lo", 0),
("ANATOLIAN HIEROGLYPH A371A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A372", "Lo", 0),
("ANATOLIAN HIEROGLYPH A373", "Lo", 0),
("ANATOLIAN HIEROGLYPH A374", "Lo", 0),
("ANATOLIAN HIEROGLYPH A375", "Lo", 0),
("ANATOLIAN HIEROGLYPH A376", "Lo", 0),
("ANATOLIAN HIEROGLYPH A377", "Lo", 0),
("ANATOLIAN HIEROGLYPH A378", "Lo", 0),
("ANATOLIAN HIEROGLYPH A379", "Lo", 0),
("ANATOLIAN HIEROGLYPH A380", "Lo", 0),
("ANATOLIAN HIEROGLYPH A381", "Lo", 0),
("ANATOLIAN HIEROGLYPH A381A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A382", "Lo", 0),
("ANATOLIAN HIEROGLYPH A383 RA OR RI", "Lo", 0),
("ANATOLIAN HIEROGLYPH A383A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A384", "Lo", 0),
("ANATOLIAN HIEROGLYPH A385", "Lo", 0),
("ANATOLIAN HIEROGLYPH A386", "Lo", 0),
("ANATOLIAN HIEROGLYPH A386A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A387", "Lo", 0),
("ANATOLIAN HIEROGLYPH A388", "Lo", 0),
("ANATOLIAN HIEROGLYPH A389", "Lo", 0),
("ANATOLIAN HIEROGLYPH A390", "Lo", 0),
("ANATOLIAN HIEROGLYPH A391", "Lo", 0),
("ANATOLIAN HIEROGLYPH A392", "Lo", 0),
("ANATOLIAN HIEROGLYPH A393 EIGHT", "Lo", 0),
("ANATOLIAN HIEROGLYPH A394", "Lo", 0),
("ANATOLIAN HIEROGLYPH A395", "Lo", 0),
("ANATOLIAN HIEROGLYPH A396", "Lo", 0),
("ANATOLIAN HIEROGLYPH A397", "Lo", 0),
("ANATOLIAN HIEROGLYPH A398", "Lo", 0),
("ANATOLIAN HIEROGLYPH A399", "Lo", 0),
("ANATOLIAN HIEROGLYPH A400", "Lo", 0),
("ANATOLIAN HIEROGLYPH A401", "Lo", 0),
("ANATOLIAN HIEROGLYPH A402", "Lo", 0),
("ANATOLIAN HIEROGLYPH A403", "Lo", 0),
("ANATOLIAN HIEROGLYPH A404", "Lo", 0),
("ANATOLIAN HIEROGLYPH A405", "Lo", 0),
("ANATOLIAN HIEROGLYPH A406", "Lo", 0),
("ANATOLIAN HIEROGLYPH A407", "Lo", 0),
("ANATOLIAN HIEROGLYPH A408", "Lo", 0),
("ANATOLIAN HIEROGLYPH A409", "Lo", 0),
("ANATOLIAN HIEROGLYPH A410 BEGIN LOGOGRAM MARK", "Lo", 0),
("ANATOLIAN HIEROGLYPH A410A END LOGOGRAM MARK", "Lo", 0),
("ANATOLIAN HIEROGLYPH A411", "Lo", 0),
("ANATOLIAN HIEROGLYPH A412", "Lo", 0),
("ANATOLIAN HIEROGLYPH A413", "Lo", 0),
("ANATOLIAN HIEROGLYPH A414", "Lo", 0),
("ANATOLIAN HIEROGLYPH A415", "Lo", 0),
("ANATOLIAN HIEROGLYPH A416", "Lo", 0),
("ANATOLIAN HIEROGLYPH A417", "Lo", 0),
("ANATOLIAN HIEROGLYPH A418", "Lo", 0),
("ANATOLIAN HIEROGLYPH A419", "Lo", 0),
("ANATOLIAN HIEROGLYPH A420", "Lo", 0),
("ANATOLIAN HIEROGLYPH A421", "Lo", 0),
("ANATOLIAN HIEROGLYPH A422", "Lo", 0),
("ANATOLIAN HIEROGLYPH A423", "Lo", 0),
("ANATOLIAN HIEROGLYPH A424", "Lo", 0),
("ANATOLIAN HIEROGLYPH A425", "Lo", 0),
("ANATOLIAN HIEROGLYPH A426", "Lo", 0),
("ANATOLIAN HIEROGLYPH A427", "Lo", 0),
("ANATOLIAN HIEROGLYPH A428", "Lo", 0),
("ANATOLIAN HIEROGLYPH A429", "Lo", 0),
("ANATOLIAN HIEROGLYPH A430", "Lo", 0),
("ANATOLIAN HIEROGLYPH A431", "Lo", 0),
("ANATOLIAN HIEROGLYPH A432", "Lo", 0),
("ANATOLIAN HIEROGLYPH A433", "Lo", 0),
("ANATOLIAN HIEROGLYPH A434", "Lo", 0),
("ANATOLIAN HIEROGLYPH A435", "Lo", 0),
("ANATOLIAN HIEROGLYPH A436", "Lo", 0),
("ANATOLIAN HIEROGLYPH A437", "Lo", 0),
("ANATOLIAN HIEROGLYPH A438", "Lo", 0),
("ANATOLIAN HIEROGLYPH A439", "Lo", 0),
("ANATOLIAN HIEROGLYPH A440", "Lo", 0),
("ANATOLIAN HIEROGLYPH A441", "Lo", 0),
("ANATOLIAN HIEROGLYPH A442", "Lo", 0),
("ANATOLIAN HIEROGLYPH A443", "Lo", 0),
("ANATOLIAN HIEROGLYPH A444", "Lo", 0),
("ANATOLIAN HIEROGLYPH A445", "Lo", 0),
("ANATOLIAN HIEROGLYPH A446", "Lo", 0),
("ANATOLIAN HIEROGLYPH A447", "Lo", 0),
("ANATOLIAN HIEROGLYPH A448", "Lo", 0),
("ANATOLIAN HIEROGLYPH A449", "Lo", 0),
("ANATOLIAN HIEROGLYPH A450", "Lo", 0),
("ANATOLIAN HIEROGLYPH A450A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A451", "Lo", 0),
("ANATOLIAN HIEROGLYPH A452", "Lo", 0),
("ANATOLIAN HIEROGLYPH A453", "Lo", 0),
("ANATOLIAN HIEROGLYPH A454", "Lo", 0),
("ANATOLIAN HIEROGLYPH A455", "Lo", 0),
("ANATOLIAN HIEROGLYPH A456", "Lo", 0),
("ANATOLIAN HIEROGLYPH A457", "Lo", 0),
("ANATOLIAN HIEROGLYPH A457A", "Lo", 0),
("ANATOLIAN HIEROGLYPH A458", "Lo", 0),
("ANATOLIAN HIEROGLYPH A459", "Lo", 0),
("ANATOLIAN HIEROGLYPH A460", "Lo", 0),
("ANATOLIAN HIEROGLYPH A461", "Lo", 0),
("ANATOLIAN HIEROGLYPH A462", "Lo", 0),
("ANATOLIAN HIEROGLYPH A463", "Lo", 0),
("ANATOLIAN HIEROGLYPH A464", "Lo", 0),
("ANATOLIAN HIEROGLYPH A465", "Lo", 0),
("ANATOLIAN HIEROGLYPH A466", "Lo", 0),
("ANATOLIAN HIEROGLYPH A467", "Lo", 0),
("ANATOLIAN HIEROGLYPH A468", "Lo", 0),
("ANATOLIAN HIEROGLYPH A469", "Lo", 0),
("ANATOLIAN HIEROGLYPH A470", "Lo", 0),
("ANATOLIAN HIEROGLYPH A471", "Lo", 0),
("ANATOLIAN HIEROGLYPH A472", "Lo", 0),
("ANATOLIAN HIEROGLYPH A473", "Lo", 0),
("ANATOLIAN HIEROGLYPH A474", "Lo", 0),
("ANATOLIAN HIEROGLYPH A475", "Lo", 0),
("ANATOLIAN HIEROGLYPH A476", "Lo", 0),
("ANATOLIAN HIEROGLYPH A477", "Lo", 0),
("ANATOLIAN HIEROGLYPH A478", "Lo", 0),
("ANATOLIAN HIEROGLYPH A479", "Lo", 0),
("ANATOLIAN HIEROGLYPH A480", "Lo", 0),
("ANATOLIAN HIEROGLYPH A481", "Lo", 0),
("ANATOLIAN HIEROGLYPH A482", "Lo", 0),
("ANATOLIAN HIEROGLYPH A483", "Lo", 0),
("ANATOLIAN HIEROGLYPH A484", "Lo", 0),
("ANATOLIAN HIEROGLYPH A485", "Lo", 0),
("ANATOLIAN HIEROGLYPH A486", "Lo", 0),
("ANATOLIAN HIEROGLYPH A487", "Lo", 0),
("ANATOLIAN HIEROGLYPH A488", "Lo", 0),
("ANATOLIAN HIEROGLYPH A489", "Lo", 0),
("ANATOLIAN HIEROGLYPH A490", "Lo", 0),
("ANATOLIAN HIEROGLYPH A491", "Lo", 0),
("ANATOLIAN HIEROGLYPH A492", "Lo", 0),
("ANATOLIAN HIEROGLYPH A493", "Lo", 0),
("ANATOLIAN HIEROGLYPH A494", "Lo", 0),
("ANATOLIAN HIEROGLYPH A495", "Lo", 0),
("ANATOLIAN HIEROGLYPH A496", "Lo", 0),
("ANATOLIAN HIEROGLYPH A497", "Lo", 0),
("ANATOLIAN HIEROGLYPH A501", "Lo", 0),
("ANATOLIAN HIEROGLYPH A502", "Lo", 0),
("ANATOLIAN HIEROGLYPH A503", "Lo", 0),
("ANATOLIAN HIEROGLYPH A504", "Lo", 0),
("ANATOLIAN HIEROGLYPH A505", "Lo", 0),
("ANATOLIAN HIEROGLYPH A506", "Lo", 0),
("ANATOLIAN HIEROGLYPH A507", "Lo", 0),
("ANATOLIAN HIEROGLYPH A508", "Lo", 0),
("ANATOLIAN HIEROGLYPH A509", "Lo", 0),
("ANATOLIAN HIEROGLYPH A510", "Lo", 0),
("ANATOLIAN HIEROGLYPH A511", "Lo", 0),
("ANATOLIAN HIEROGLYPH A512", "Lo", 0),
("ANATOLIAN HIEROGLYPH A513", "Lo", 0),
("ANATOLIAN HIEROGLYPH A514", "Lo", 0),
("ANATOLIAN HIEROGLYPH A515", "Lo", 0),
("ANATOLIAN HIEROGLYPH A516", "Lo", 0),
("ANATOLIAN HIEROGLYPH A517", "Lo", 0),
("ANATOLIAN HIEROGLYPH A518", "Lo", 0),
("ANATOLIAN HIEROGLYPH A519", "Lo", 0),
("ANATOLIAN HIEROGLYPH A520", "Lo", 0),
("ANATOLIAN HIEROGLYPH A521", "Lo", 0),
("ANATOLIAN HIEROGLYPH A522", "Lo", 0),
("ANATOLIAN HIEROGLYPH A523", "Lo", 0),
("ANATOLIAN HIEROGLYPH A524", "Lo", 0),
("ANATOLIAN HIEROGLYPH A525", "Lo", 0),
("ANATOLIAN HIEROGLYPH A526", "Lo", 0),
("ANATOLIAN HIEROGLYPH A527", "Lo", 0),
("ANATOLIAN HIEROGLYPH A528", "Lo", 0),
("ANATOLIAN HIEROGLYPH A529", "Lo", 0),
("ANATOLIAN HIEROGLYPH A530", "Lo", 0),
)
|
https://github.com/GuTaoZi/SUSTech-thesis-typst | https://raw.githubusercontent.com/GuTaoZi/SUSTech-thesis-typst/main/utils/datetime_display.typ | typst | MIT License | #let datetime_display_zh(date) = {
date.display("[year] 年 [month] 月 [day] 日")
}
#let datetime_display_en(date) = {
date.display("[month repr:short] [day], [year]")
} |
https://github.com/metamuffin/typst | https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/layout/clip.typ | typst | Apache License 2.0 | // Test clipping with the `box` and `block` containers.
---
// Test box clipping with a rectangle
Hello #box(width: 1em, height: 1em, clip: false)[#rect(width: 3em, height: 3em, fill: red)]
world 1
Space
Hello #box(width: 1em, height: 1em, clip: true)[#rect(width: 3em, height: 3em, fill: red)]
world 2
---
// Test cliping text
#block(width: 5em, height: 2em, clip: false, stroke: 1pt + black)[
But, soft! what light through
]
#v(2em)
#block(width: 5em, height: 2em, clip: true, stroke: 1pt + black)[
But, soft! what light through yonder window breaks? It is the east, and Juliet
is the sun.
]
---
// Test cliping svg glyphs
Emoji: #box(height: 0.5em, stroke: 1pt + black)[🐪, 🌋, 🏞]
Emoji: #box(height: 0.5em, clip: true, stroke: 1pt + black)[🐪, 🌋, 🏞]
---
// Test block clipping over multiple pages.
#set page(height: 60pt)
First!
#block(height: 4em, clip: true, stroke: 1pt + black)[
But, soft! what light through yonder window breaks? It is the east, and Juliet
is the sun.
]
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/cns/notes.typ | typst | #import "@local/unipd-doc:0.0.1": *
#show: notes()
#show: unipd-doc(
title: [Advanced Topics in Computer Network and Security],
subtitle: [Notes],
author: [<NAME>],
date: [I Semester A.Y. 2023-2024],
)
= Presentation
== Phases
- Part 1: group presentation (3 people) on topic.
Questions to other groups
- Part 2: final essay similar to the first part topic
== Grading
#grid(
columns: (auto, auto),
gutter: 1em,
[25%],[Presentation],
[25%],[Discussion in class (2nd part)],
[25%],[Project/essay],
[25%],[Project oral discussion],
)
#lecture[11/10 (<NAME>)]
= Containers and kubernet security
== Containers
/ Container: unit of software that packages up code, dependencies, binaries required to run an app, for it to be ready to be shipped with no manual configuration required
VMs are much larger and slower in comparison (they have to virtualize the entire OS for each VM)
=== User permission exploit
Binaries in Linux inherit owner's permissions for system calls. \
e.g. you can't ask the system to open a socket connection through the `ping` command if you own the binary as a non-elevated user
`getcaps PID` returns all the capabilities (allowed system calls) a process can do
=== Control groups
They can be used to limit the amount of memory of a group of processes?
=== Namespaces
Can be unshared from processes. \
It can be used to hide the hostname from a container
=== Dockerd access
The docker daemon is controlled via its socket.
Having access to it means to be able to control the entire containers through API requests
== Kubernetes
Container orchestrator from Google: cluster of physical machines that run a single container (distributed container)
Very poor security defaults
#lecture[18/10 (Videogames)]
= Videogames security
How to identify a player? Playstyle fingerprint
Playstyle can be deduced from:
- Camera movements
- Player movement
Done with machine learning techniques
== Attribute inference attack 101
Map public data (playstyle info) to private data that some users reveal (name, age, gender, ...)
|
|
https://github.com/An-314/Notes-of-Fundamentals_of_Electronics | https://raw.githubusercontent.com/An-314/Notes-of-Fundamentals_of_Electronics/main/chap3.typ | typst | #import "@local/mytemplate:1.0.0": *
#import "@preview/physica:0.9.2": *
= 门电路
数字电路的元件:
#grid(
columns: (1fr, 1fr, 1fr),
[*结构*
- 分层设计
- 每个层次的复杂性有限
- 可重复使用的构件],
[
*接口*
- 系统工程的关键要素
- 隔离技术,允许演进
- 主要抽象机制
],
[
*什么是好的系统设计?*
- 最小的机制,最大的功能
- 在各种环境下都可靠
- 适应未来的技术改进
]
)
*获得高、低电平的基本原理*:
工作电路在直流状态。
#figure(
image("pic/2024-04-02-08-47-47.png", width: 80%),
caption: [
获得高、低电平的基本原理
],
)
电阻:不能太大、不能太小
== 二极管门电路
=== 二极管的开关特性
#figure(
image("pic/2024-04-02-08-56-53.png", width: 30%),
caption: [
二极管的开关特性
],
)
- 高电平:$V_"IH" = V_"CC"$,此时二极管截止,$V_"O" = V_"CC"$
- 低电平:$V_"IL" = 0$,此时二极管导通,$V_"O" = 0.7$
=== 二极管门电路
#figure(
image("pic/2024-04-02-09-16-13.png", width: 30%),
caption: [
二极管或门
],
)
#figure(
image("pic/2024-04-02-09-17-00.png", width: 10%),
caption: [
二极管与门
],
)
*二极管构成的门电路的缺点*
- 电平有偏移
- 带负载能力差
- 只用于IC内部电路
== CMOS门电路(Complementary)
#figure(
image("pic/2024-04-02-09-04-33.png", width: 80%),
caption: [
NFET
],
)
#figure(
image("pic/2024-04-02-09-05-11.png", width: 80%),
caption: [
PFET
],
)
=== CMOS反相器的工作原理
#figure(
image("pic/2024-04-02-09-10-30.png", width: 80%),
caption: [
CMOS反相器
],
)
MOS管工作在*可变电阻区*——由于与截至的MOS分压可以保证其电压在可变电阻区。
#figure(
image("pic/2024-04-02-09-21-05.png", width: 40%),
caption: [
输入输出曲线
],
)
该输入输出遵循了数字电路元件的原则:其输出是稳定的。
CMOS可以理解为两个变化相反的可变电阻串联,从而起到开关的作用。
=== 电压、电流传输特性
#grid(
columns: (1fr, 1fr),
[#figure(
image("pic/2024-04-02-09-24-30.png", width: 80%),
caption: [
电压传输特性
],
)],
[
- AB段:$V_I < V_"GS(TH)N"$,$T_1$导通、$T_2$截止;$V_O = V_(O H) = V_"DD"$
- CD段:$V_I > V_"DD" - |V_"GS(TH)N"|$,$T_1$截止、$T_2$导通;$V_O = V_(O L) = 0$
- BC段:$V_"GS(TH)N" < V_I < V_"DD" - |V_"GS(TH)N"$,$T_1$、$T_2$同时导通;如若$T_1,T_2$参数完全对称,则$V_I = 1/2 V_"DD"$时,$V_O = 1/2 V_"DD"$
],
[
#figure(
image("pic/2024-04-02-09-24-58.png", width: 80%),
caption: [
电流传输特性
],
)
],
[
这也意味着在电位(逻辑)转换的时候,电路的功率消耗会变大;保持稳定时,功率消耗较小。
]
)
=== 输入噪声容限
在$V_I$偏离$V_(I H)$和$V_(I L)$的一定范围内,$V_O$基本不变;在输出变化允许范围内。允许输入的变化范围称为*输入噪声容限*。
#figure(
image("pic/2024-04-11-01-11-52.png", width: 80%),
caption: [
输入噪声容限
],
)
可以看出它对输入的变化是有容忍度的,并且输出依旧保持很好的稳定性。可以接受较宽泛的输入值,但给出比较精确稳定的输出值。
#figure(
image("pic/2024-04-11-01-13-20.png", width: 80%),
caption: [
$V_"DD"$对噪声容限的影响
],
)
可以通过提高$V_"DD"$来提高噪声容限。
=== CMOS 反相器的静态输入/出特性
==== 输入特性
#figure(
image("pic/2024-04-02-09-28-27.png", width: 80%),
caption: [
输入特性
],
)
正常工作时候不形成电流,超过$V_"DD" + 0.7V$或者低于$-0.7V$时,会形成电流。
输入电流特性是保护电路所给的。如果没有保护电路*CMOS本身是没有电流的*。
==== 输出特性
#figure(
image("pic/2024-04-02-09-34-13.png", width: 80%),
caption: [
输出特性
],
)
#figure(
image("pic/2024-04-09-08-08-51.png", width: 80%),
caption: [
输出特性
],
)
负载电流和负载电阻不能同向变化。特性图的斜率是MOS管的导通电阻。高电平越高,内阻越小(这是MOS管可变电阻区的特性)。
==== 扇出系数(Fan-out)——带负载能力
负载越高,$C$越大。可能会导致原本的信号变成交流噪声。
=== CMOS反相器的动态特性
==== 传输延迟时间
1. 原因:$C_I$与$C_L$充放电,由于$R_"ON"$比较大,充电时间比较长。
2. $t_"PHL"$和$t_"PLH"$受到$C_L$与$V_"DD"$的影响。
前级提供R,后级提供C。
$
R = rho l/A\
C = epsilon A/d\
V(t) = V(oo) + (V(0) - V(oo)) e^(-t/(R C))
$
从而能够得到:
$
t &= R C ln((V(0) - V(oo))/(V(t) - V(oo)))\
&= R C ln((V(oo) - V_"OL")/ (V(oo) - V(t)))\
&= R C ln((V_"DD" - V(0))/ (V_"DD" - V_"TH"))\
&approx R C ln 2
$
#newpara()
TPD(propagation delay time):是从输入信号发生有效值切换后,输出信号发生有效值切换的时间间隔。
#figure(
image("pic/2024-04-11-01-20-29.png", width: 60%),
caption: [
PD
],
)
TCD(contamination delay time):是从输入信号开始有效值切换后,输出信号开始发生有效值切换的时间间隔。#footnote[一般而言,拿到的器件,TPD要比标准值小,TCD要比标准值大。]
#figure(
image("pic/2024-04-11-01-23-02.png", width: 80%),
caption: [
CD
],
)
#figure(
image("pic/2024-04-11-01-24-50.png", width: 80%),
caption: [
传输延迟时间
],
)
#figure(
image("pic/2024-04-11-01-30-31.png", width: 80%),
)
二者数量级相同,但是TPD要比TCD大。
==== 交流噪声容限
如果输入信号的持续的时间很短,不足以充满$C_L$,那么输出信号的变化就会很小。
当输入信号为窄脉冲,且接近于$t_"pd"$时,输出变化跟不上,变化很小,因此交流噪声容限远大于直流噪声容限。
#grid(
columns: (1fr, 1fr),
[
#figure(
image("pic/2024-04-09-08-34-39.png", width: 80%),
caption: [
正脉冲噪声容限
],
)
],
[
#figure(
image("pic/pic/2024-04-09-08-09-19.png.png", width: 80%),
caption: [
负脉冲噪声容限
],
)
]
)
==== 扇出系数(Fan-out)(带负载能力(动态) )
=== 总功耗
总功耗=静态功耗$P_S$+动态功耗$P_D$
1.静态功耗
静态功耗极小,与动态功耗相比,可以忽略
2.动态功耗
- 导通功耗
#figure(
image("pic/2024-04-11-01-34-19.png", width: 40%),
caption: [
动态功耗——导通功耗
],
)
- 负载功耗#footnote[功耗的原因也是现在技术都选择使得$V_"DD"$减小,而不是考虑前面的原因增大。]
#figure(
image("pic/2024-04-11-01-35-18.png", width: 60%),
caption: [
动态功耗——负载功耗
],
)
负载电容充放电功耗$P_C$
- 当$V_I arrow.t$,$C_L$经$T_2$放电,有
$
i_N = C_L dd(v_O)/dd(t) = - C_L dd((V_"DD" - v_O))/dd(t)
$
- 当$V_I arrow.b$,$V_"DD"$经$T_1$充电,有
$
i_P = C_L dd(v_O)/dd(t)
$
得到平均功率
$
P_C = 1/T integral_0^(T/2) i_N v_O dd(t) + 1/T integral_(T/2)^T i_P (V_"DD" - v_O) dd(t) = C_L V_"DD"^2 f
$
- 总功耗
$
P("总功耗") = P_D("动态功耗") + P_S("静态功耗")\
P_D = P_C("负载功耗") + P_T("导通功耗")\
P_T = C_(P D) V_"DD"^2 f\
P_C = C_L V_"DD"^2 f
$
== 其他类型的CMOS门电路
=== 其他逻辑功能的CMOS门电路
#figure(
image("pic/2024-04-09-08-45-59.png", width: 80%),
caption: [
由CMOS出发——实现其他门电路
],
)
由CMOS出发:核心就是改变*上拉和下拉部分*。
#figure(
image("pic/2024-04-09-09-09-54.png", width: 80%),
caption: [
由CMOS出发——实现其他门电路
],
)
#grid(
columns: (1fr, 1fr),
[
#figure(
image("pic/2024-04-09-08-57-08.png", width: 80%),
caption: [
与非门
],
)
],
[
#figure(
image("pic/2024-04-09-08-57-58.png", width: 80%),
caption: [
或非门
],
)
]
)
==== 带缓冲极的CMOS门
===== 与非门
#figure(
image("pic/2024-04-09-09-01-19.png", width: 40%),
caption: [
与非门
],
)
存在的缺点:
- 输出的高电平和低电平与CMOS反相器不同:高电平更高,低电平更高
===== 解决方法
缓冲极:在输出端加一个缓冲极,使得输出电压更稳定。
#figure(
image("pic/2024-04-09-09-06-30.png", width: 80%),
caption: [
带缓冲极的门电路
],
)
*安全问题:门电路不能直接用线并联,需要用门电路相连。*否则造成短路。
#figure(
image("pic/2024-04-09-09-11-26.png", width: 80%),
caption: [
错误连接方法
],
)
=== 漏极开路的门电路(OD门)
对于两个不同$V_"DD"$的电路,想让他们嫁接在一起,可以通过OD门来实现。
#figure(
image("pic/2024-04-09-09-21-35.png", width: 30%),
caption: [
OD门
],
)
需要自己选择$V_"DD"$和$R_L$(上拉电原和电阻)。
=== 三态输出门
总线结构:多个设备共享一个总线,通过输出门来选择。在这里如果一个模块不工作,就可以用总线将其完全隔离。
#figure(
image("pic/2024-04-09-09-34-30.png", width: 80%),
caption: [
三态输出门
],
)
*有物理连接,可以没有电器连接。*用$E N'$进行控制。
#figure(
image("pic/2024-04-11-08-06-02.png", width: 40%),
caption: [
总线结构
],
)
= 组合逻辑电路
== 组合逻辑电路的特点
1. 从功能上:任意时刻的输出仅取决于该时刻的输入
2. 从电路结构上:不含记忆(存储)元件
相当于是对逻辑式的直接物理实现。
== 逻辑功能的描述
#figure(
image("pic/2024-04-11-08-09-57.png", width: 40%),
caption: [
逻辑功能的描述
],
)
$
bold(Y) = f(bold(A))
$
== 组合逻辑电路的设计方法
1. 逻辑抽象
- 分析因果关系,确定输入/输出变量
- 定义逻辑状态的含意(赋值)
- 列出真值表
2. 写出函数式
3. 选定器件类型
4. 根据所选器件:对逻辑式化简(用门)变换(用MSI)或进行相应的描述(PLD)
5. 画出逻辑电路图,或下载到PLD
6. 工艺设计
_设计举例:设计一个监视交通信号灯状态的逻辑电路_
#grid(
columns: (1fr, 1fr),
[
#figure(
three-line-table[
|R|A|G|Z|
|--|--|--|--|
|0|0|0|1|
|0|0|1|0|
|0|1|0|0|
|0|1|1|1|
|1|0|0|0|
|1|0|1|1|
|1|1|0|1|
|1|1|1|1|
],
caption: [
真值表
],
kind: table
)
],
[
#figure(
image("pic/2024-04-11-08-27-30.png", width: 50%),
caption: [
卡诺图
],
)
$Z = R'A'G' + R A + R G + A G$
#figure(
image("pic/2024-04-11-08-28-31.png", width: 40%),
caption: [
逻辑电路
],
)
]
)
我们寻求通用性的硬件,而不是对于每一种电路都要重新设计一次。
=== 半加器
=== 全加器:将两个1位二进制数及来自低位的进位相加
真值表:
#figure(
three-line-table[
|A|B|CI|S|CO|
|--|--|--|--|--|
|0|0|0|0|0|
|0|0|1|1|0|
|0|1|0|1|0|
|0|1|1|1|1|
],
caption: [
真值表
],
kind: table
)
=== 多位加法器
$
(C I)_i = (C O)_(i-1)\
S_i = A_i plus.circle B_i plus.circle (C I)_i\
(C O)_i = (A_i B_i) + (A_i + B_i) (C I)_i
$
==== 串行进位加法器
- 优点:简单
- 缺点:时间延迟高【$n$个$t_(p d)$】,无效功耗高(在一个加法的时候,另外的全加器只能等待)
==== 超前进位加法器
基本原理:加到第$i$位的进位输入信号是两个加数第$i$位以前各位($0 tilde i-1$)的函数,可在相加之前就计算出来。
=== 用加法器设计组合电路
基本原理:
- 若能生成函数可以变换成输入变量和输入变量相加
- 若能生成函数可以变换成输入变量和常量相加
_例如:8421码转余3码_
$
Y_3Y_2Y_1Y_0 = D C B A + 0011
$
== 若干常用组合逻辑电路
=== 编码器
编码:将输入的每个高/低电平信号变成一个对应的二进制代码
- 普通编码器
- 优先编码器
==== 普通编码器
特点:任何时刻只允许输入一个需要编码的电平信号。
例:3位二进制普通编码器
#figure(
three-line-table[
|$I_0$|$I_1$|$I_2$|$I_3$|$I_4$|$I_5$|$I_6$|$I_7$|$Y_2$|$Y_1$|$Y_0$|
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
|1|0|0|0|0|0|0|0|0|0|0|
|0|1|0|0|0|0|0|0|0|0|1|
|0|0|1|0|0|0|0|0|0|1|0|
|0|0|0|1|0|0|0|0|0|1|1|
|0|0|0|0|1|0|0|0|1|0|0|
|0|0|0|0|0|1|0|0|1|0|1|
|0|0|0|0|0|0|1|0|1|1|0|
|0|0|0|0|0|0|0|1|1|1|1|
],
caption: [
真值表
],
kind: table
)
$
Y_2 = I_4 + I_5 + I_6 + I_7\
Y_1 = I_2 + I_3 + I_6 + I_7\
Y_0 = I_1 + I_3 + I_5 + I_7
$
#figure(
image("pic/2024-04-11-09-12-10.png", width: 40%),
caption: [
3位二进制普通编码器
],
)
==== 优先编码器
特点:允许同时输入两个以上的电平信号,但只对其中优先权最高的一个进行编码。
例:8线-3线优先编码器(设$I_7$优先权最高…$I_0$优先权最低)
#figure(
three-line-table[
|$I_0$|$I_1$|$I_2$|$I_3$|$I_4$|$I_5$|$I_6$|$I_7$|$Y_2$|$Y_1$|$Y_0$|
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
|x|x|x|x|x|x|x|1|1|1|1|
|x|x|x|x|x|x|1|0|1|1|0|
|x|x|x|x|x|1|0|0|1|0|1|
|x|x|x|x|1|0|0|0|1|0|0|
|x|x|x|1|0|0|0|0|0|1|1|
|x|x|1|0|0|0|0|0|0|1|0|
|x|1|0|0|0|0|0|0|0|0|1|
|1|0|0|0|0|0|0|0|0|0|0|
],
caption: [
真值表
],
kind: table
)
低电平有效:抗干扰能力强;对于TTL电路,输入端悬空、输出为高电平。
#figure(
image("pic/2024-04-11-09-22-13.png", width: 80%),
caption: [
8线-3线优先编码器
],
)
$S'$选通信号:当$S = 0$时候,电路不工作;当$S = 1$时候,电路工作。
$
Y_2' = ((I_4 + I_5 + I_6 + I_7) S)'\
$
#newpara()
$Y_S '$为0时,电路允许工作,无编码输入。
$Y_(E X) '$为0时,电路允许工作,有编码输入。
#figure(
three-line-table[
|$Y_S '$|$Y_(E X) '$|状态|
| -- | -- | -- |
|1 | 1 | 不工作|
|1 | 0 | 工作、无编码输入|
|0 | 1 | 工作、有编码输入|
|0 | 0 | 不可能出现|
],
caption: [
附加输出信号的状态及含意
],
kind: table
)
控制端扩展功能举例:用两片8线-3线优先编码器$=>$16线-4线优先编码器
#figure(
image("pic/2024-04-11-09-35-51.png", width: 80%),
caption: [
16线-4线优先编码器
],
)
=== 译码器
译码:将每个输入的二进制代码译成对应的输出高、低电平信号。
常用的有:二进制译码器,二-十进制译码器,显示译码器等。
==== 二进制译码器
例如:3线-8线二进制译码器
#figure(
three-line-table[
|$I_0$|$I_1$|$I_2$|$Y_7$|$Y_6$|$Y_5$|$Y_4$|$Y_3$|$Y_2$|$Y_1$|$Y_0$|
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
|0|0|0|1|0|0|0|0|0|0|0|
|0|0|1|0|1|0|0|0|0|0|0|
|0|1|0|0|0|1|0|0|0|0|0|
|0|1|1|0|0|0|1|0|0|0|0|
|1|0|0|0|0|0|0|1|0|0|0|
|1|0|1|0|0|0|0|0|1|0|0|
|1|1|0|0|0|0|0|0|0|1|0|
|1|1|1|0|0|0|0|0|0|0|1|
],
caption: [
3线-8线二进制译码器
],
kind: table
)
#figure(
image("pic/2024-04-16-08-12-38.png", width: 40%),
caption: [
3线-8线二进制译码器
],
)
用二极管与门阵列组成的3线-8线译码器
#figure(
image("pic/2024-04-16-08-14-09.png", width: 80%),
caption: [
3线-8线二进制译码器
],
)
对于每一个$Y_i$都相当于一个二极管与门,恰好对应相应的输入。
$
Y_0 = A_2' A_1' A_0' = m_0\
Y_1 = A_2' A_1' A_0 = m_1\
...\
Y_7 = A_2 A_1 A_0 = m_7
$
利用门电路实现:
#figure(
image("pic/2024-04-16-08-19-39.png", width: 60%),
caption: [
3线-8线二进制译码器 74HC138
],
)
加上$S$的扩展,现在真值表变成了:
#figure(
three-line-table[
|$S$|$S_2'+S_3'$|$I_0$|$I_1$|$I_2$|$Y_7$|$Y_6$|$Y_5$|$Y_4$|$Y_3$|$Y_2$|$Y_1$|$Y_0$|
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
|0|x|x|x|x|1|1|1|1|1|1|1|1|
|x|1|x|x|x|1|1|1|1|1|1|1|1|
|1|0|0|0|0|0|1|1|1|1|1|1|1|
|1|0|0|0|1|1|0|1|1|1|1|1|1|
|1|0|0|1|0|1|1|0|1|1|1|1|1|
|1|0|0|1|1|1|1|1|0|1|1|1|1|
|1|0|1|0|0|1|1|1|1|0|1|1|1|
|1|0|1|0|1|1|1|1|1|1|0|1|1|
|1|0|1|1|0|1|1|1|1|1|1|0|1|
|1|0|1|1|1|1|1|1|1|1|1|1|0|
],
caption: [
3线-8线二进制译码器
],
kind: table
)
利用附加控制端进行扩展:用74HC138(3线—8线译码器)$=>$4线—16线译码器
#figure(
image("pic/2024-04-16-08-24-12.png", width: 80%),
caption: [
4线—16线译码器
],
)
#figure(
image("pic/2024-04-16-08-29-27.png", width: 80%),
caption: [
利用译码器实现逻辑电路
],
)
==== 二—十进制译码器
将输入BCD码的10个代码译成10个高、低电平的输出信号BCD码以外的伪码,输出均无低电平信号产生。
=== 显示译码器
==== 七段字符显示器
#figure(
image("pic/2024-04-16-08-35-16.png", width: 80%),
caption: [
七段字符显示器
],
)
例如:BCD七段字符显示译码器 (代码转换器) 7448
#figure(
image("pic/2024-04-16-08-37-18.png", width: 80%),
caption: [
7448
],
)
全灯测试$L T'$:使所有灯亮起,用于测试。
灭零输入$R B O'/ R B I'$:使所有灯熄灭。
#figure(
image("pic/2024-04-16-08-40-05.png", width: 80%),
caption: [
7448
],
)
=== 数据选择器
==== 工作原理
有点类似于多路开关,可以选择不同的输入。
#figure(
image("pic/2024-04-16-08-45-20.png", width: 80%),
caption: [
数据选择器
],
)
四位输入的可以用三个二位输入的选择器扩展实现。
#figure(
image("pic/2024-04-16-08-58-43.png", width: 80%),
caption: [
双四选一数据选择器
],
)
可以用八选一数据选择器实现任何三位的逻辑表达式,只需要对$D_i$选择$0$或$1$;进一步地,如果$D_i$选择$0,A_3(')$,这样可以实现任何四位的逻辑表达式。
具有$n$位地址输入的数据选择器,至少可产生输入变量不大于$n+1$的组合函数。
#figure(
image("pic/2024-04-16-09-07-18.png", width: 80%),
caption: [
例如红绿灯控制
],
)
=== 数值比较器
用来比较两个二进制数的大小,输出比较结果。
== 组合逻辑电路中的竞争-冒险现象
=== 容差性
Output guaranteed to be valid when all inputs have been valid for at least tPD, and, outputs may become invalid no earlier than tCD after an input changes.
#figure(
image("pic/2024-04-16-09-15-54.png", width: 40%),
caption: [
容差性
],
)
即使输出从0->0,都会有一段时间的不确定段。
但由于A一直是高电平,这使得输出一直都是低电平,中间的不确定段不会影响输出,全部都是低电平。
LENIENT Combinational Device:
Output guaranteed to be valid when any combination of inputs sufficientto determine output value has been valid for at least tPD.
Tolerates transitions -- and invalid levels -- on irrelevant inputs!
如果有值可以明确锁定输出,这时候输出就不会有不确定段。
例如与非门:
#grid(
columns: (1fr, 1fr),
[
#figure(
three-line-table[
|A|B|Y|
|--|--|--|
|0|0|1|
|0|1|1|
|1|0|1|
|1|1|0|
],
caption: [
与非门
],
kind: table
)
],
[
#figure(
three-line-table[
|A|B|Y|
|--|--|--|
|0|0|1|
|x|1|1|
|1|x|1|
],
caption: [
与非门
],
kind: table
)
]
)
=== 竞争-冒险现象及成因
输入同时变化——多个变量不同时变化引发的竞争冒险
卡诺图相切——单个变量引发的竞争冒险;可以使用再加入冗余项的方式来缓解这样的竞争冒险。
== 可编程逻辑器件(PLD, Programmable Logic Device)
数字集成电路从功能上有分为:通用型、专用型两大类
- General ICs——通用型
- Application-Specific ICs——专用型
PLD的特点:是一种按通用器件来生产,但逻辑功能是由用户通过对器件编程来设定的。
EDA:电⼦产品从设计、仿真调试、硬件实现全过程⾃动化。
从CAD到EDA
- CAD Computer Aided Design(Draw)
- CAE Computer Aided Engineer
- EDA Electronic Design Automation
EDA的技术特征
- 以超⼤规模IC为基础
- 以⾼性能计算机及软件为平台
- 多学科综合
- 实现电⼦产品从设计到⽣产全过程⾃动化
- 电路软件化-软件即是电路:⽤计算机程序描述电路
- 电路的描述形式 HDL Hardware Description Language
#pagebreak()
= 半导体存储电路
#figure(
image("pic/2024-04-23-08-23-13.png", width: 80%),
caption: [
时序电路
],
)
上面的组合电路是没有记忆功能的:不存在状态,所有的输出仅仅取决于输入。
计算机系统的存储结构:存储器、寄存器、缓存、磁盘等。(冯诺依曼结构)
#figure(
image("pic/2024-05-06-17-08-28.png", width: 80%),
caption: [
计算机系统的存储结构
],
)
一些术语:
- 存储器单元 cell : 用于存储一个 bit 的电路单元
- 字节 Byte = 8bits
- 字 Word = 1 - 8 Bytes
- 1 个字中有 8 - 64 bits
- 1B = 8 bit; iKB = 1024B ; 1MB = 1024 KB ; 1GB = 1024MB
- 容量:表示特定存储器单元或整个存储器系统能够存储多少 bits
- 密度:表示容量的另一术语
- 地址:表示 word 在存储系统中位置
== 概述
一、用于记忆二进制信号
1. 有两个能自行保持的状态
2. 根据输入信号可以置成0或1
二、分类
1. 按触发方式(电平,脉冲,边沿)
2. 按逻辑功能(RS, JK, D, T)
#figure(
image("pic/2024-04-23-08-44-06.png", width: 80%),
caption: [
存储
],
)
用两个反相器首尾相连,由于正反馈的作用,可以保持0或者1。
== SR锁存器
=== 电路结构与工作原理
#figure(
image("pic/2024-04-23-08-59-37.png", width: 80%),
caption: [
SR锁存器
],
)
#figure(
three-line-table[
|$S_D$|$R_D$|$Q$|$Q^*$|
|--|--|--|--|
|0|0|0|0|
|0|0|1|1|
|1|0|0|1|
|1|0|1|1|
|0|1|0|0|
|0|1|1|0|
|1|1|0|0|
|1|1|1|0|
],
caption: [
SR锁存器的真值表
],
kind: table
)
其中$Q^*$表示$Q$的下一状态。
其中$S_D$是选0端,在给入高电平之后,$Q$就会变成0;$R_D$是选1端,在给入高电平之后,$Q$就会变成1。
$S_D$和$Q_D$的$1$同时消失后,$Q^*$不定。*正常工作下,应遵循$S_D R_D = 0$的约束条件。*
=== 动作特点
在任何时刻,输入都能直接改变输出的状态。
#figure(
image("pic/2024-05-06-17-50-10.png", width: 40%),
caption: [
SR锁存器的动作特点
],
)
== 电平触发的触发器
=== SR触发器
==== 电路结构与工作原理
#figure(
image("pic/2024-05-06-17-57-25.png", width: 80%),
caption: [
电平触发的触发器
],
)
相当于输入控制门+基本SR锁存器。
在CLK = 0时,退化成两个反相器;在CLK = 1时,退化成SR锁存器。只有触发信号CLK到达时,S和R才能起作用。
仍然存在约束条件:$S$和$R$不能同时为1。
同步与异步:同步是指有一个时钟信号,异步是指没有时钟信号。
==== 动作特点
在CLK=1的全部时间⾥,S和R的变化都将引起输出状态的变化。
#figure(
image("pic/2024-05-06-18-02-58.png", width: 80%),
caption: [
电平触发的触发器的动作特点
],
)
在CLK = 1期间, Q和Q'可能随 S、R变化多次翻转。
=== D触发器
除了SR触发器,为了保证S和R不同时为1,可以强行令S和R为相反的值。这样就构成了D触发器。
#figure(
image("pic/2024-04-23-09-17-35.png", width: 80%),
caption: [
D触发器
],
)
==== 利用MUX实现D触发器:D Latch
#figure(
image("pic/2024-05-06-18-09-51.png", width: 80%),
caption: [
利用MUX实现D触发器
],
)
== 脉冲触发的触发器
为了提高可靠性,要求每个CP周期输出状态只能改变1次。
=== 主从D触发器
借鉴高速路收费站的机械构造,引入主、从触发器。
任何时候只有一个锁存器 "透明":
- 主锁存器打开时从锁存器关闭
- 主锁存器关闭时从锁存器打开
无通过触发器的组合路径
#figure(
image("pic/2024-05-06-22-07-43.png", width: 80%),
caption: [
Master-Slave Flip Flop (Edge-triggered)
],
)
Q 仅在 CLK 的 0 - 1 转换后发生变化,因此触发器似乎是由 CLK 的*上升沿* "触发 "的。
#figure(
image("pic/2024-05-06-22-08-50.png", width: 80%),
caption: [
波形图
],
)
=== 主从SR触发器
- CLK=1时,主按S、R的状态翻转,从保持
- CLK下降沿达到时,主保持,从按主的状态翻转
每个CLK周期内,输出状态只能改变一次。
与边沿触发器不同的是,边沿触发只看上升沿时候的输入,而主从触发器看的是整个CLK周期内的输入。
#figure(
image("pic/2024-05-10-23-23-13.png", width: 80%),
caption: [
主从SR触发器
],
)
#figure(
image("pic/2024-05-10-23-23-46.png", width: 40%),
caption: [
主从SR触发器的真值表
],
kind: table
)
=== 主从JK触发器
加入反馈
为解除约束,当$J=K=1$时,$Q^* = Q'$
#figure(
image("pic/2024-05-10-23-30-27.png", width: 80%),
caption: [
主从JK触发器
],
)
#figure(
image("pic/2024-05-10-23-33-24.png", width: 80%),
caption: [
从主从SR触发器改造成主从JK触发器
],
)
- 特性:主触发器打开期间,主触发器的值只能变一次。
- 主从RS触发器关心最后一次变化,而主从JK触发器关心第一次变化。
#figure(
image("pic/2024-05-10-23-34-32.png", width: 80%),
caption: [
主从JK触发器的真值表
],
kind: table
)
#figure(
image("pic/2024-05-10-23-53-53.png", width: 40%),
caption: [
主从JK触发器的波形图
],
)
=== 脉冲触发方式的动作特点
1. 分两步动作:
- 第一步CLK = 1时,“主”接收信号,“从”保持
- 第二步CKL $arrow.b$到达后,“从”按“主”状态翻转
输出状态只能改变一次
2. 主从SR,“主”为同步SR,CKL=1的全部时间里输入信号对“主”都起控制作用;但主从 在高电平期间,“主”只可能翻转一次
在CKL=1期间里输入发生变化时,要找出CKL $arrow.b$前$Q$最后的状态,决定$Q^*$。
== 边沿触发的触发器
为了提高可靠性,增强抗干扰能力,希望触发器的次态仅取决于CLK的下降沿(或上升沿)到来时的输入信号状态,与在此前、后输入的状态没有关系。
用CMOS传输门的边沿触发器、维持阻塞触发器、用门电路tpd的边沿触发器
=== 电路结构和工作原理
#figure(
image("pic/2024-05-11-00-01-02.png", width: 80%),
caption: [
⽤两个电平触发D触发器组成的边沿触发器
],
)
#figure(
image("pic/2024-05-11-00-05-21.png", width: 80%),
caption: [
利用CMOS传输门的边沿触发器
],
)
#figure(
image("pic/2024-05-11-00-05-04.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-00-10-00.png", width: 20%),
caption: [
真值表
],
)
#figure(
image("pic/2024-05-11-00-13-48.png", width: 80%),
numbering: none
)
这是一个上升沿的触发器。
对时钟的周期有要求,至少要信号传输到所有门电路。
=== 动作特点
- $Q^*$变化发生在CLK的上升沿(或下降沿)
- $Q^*$仅取决于上升沿到达时输入的状态,而与此前、后的状态无关
== 触发器的逻辑功能及其描述方法
#figure(
image("pic/2024-05-11-00-22-42.png", width: 80%),
numbering: none
)
=== 触发器按逻辑功能的分类
时钟控制的触发器中由于输入方式不同(单端,双端输入)、次态$Q^*$随输入变化的规则不同。
有限状态机:有限个状态,有限个输入,有限个输出。
==== SR触发器
凡在时钟信号作用下,具有如下功能的触发器称为SR触发器
$
Q^* = S'R'Q + S R'Q' + S R'Q = A'R'Q+S R' = S + R'Q\
S R = 0
$
#figure(
image("pic/2024-04-25-09-06-51.png", width: 80%),
caption: [
状态转换图——SR触发器
],
)
#figure(
image("pic/2024-05-11-00-26-43.png", width: 50%),
caption: [
符号与真值表
],
)
==== JK触发器
状态方程
$
Q^* = J'Q' + K Q
$
#figure(
image("pic/2024-05-11-00-30-25.png", width: 80%),
caption: [
状态转换图——JK触发器
],
)
#figure(
image("pic/2024-05-11-00-31-37.png", width: 50%),
caption: [
符号与真值表
],
)
==== T触发器
状态方程
$
Q^* = T'Q + T'Q
$
#figure(
image("pic/2024-05-11-00-33-08.png", width: 80%),
caption: [
状态转换图——T触发器
],
)
#figure(
image("pic/2024-05-11-00-34-33.png", width: 40%),
caption: [
符号与真值表
],
)
==== D触发器
状态方程
$
Q^* = D
$
#figure(
image("pic/2024-05-11-00-36-06.png", width: 80%),
caption: [
状态转换图——D触发器
],
)
#figure(
image("pic/2024-05-11-00-37-04.png", width: 40%),
caption: [
符号与真值表
],
)
== 触发器的动态特性
- 建立时间 $t_"SETUP"$
- 保持时间 $t_"HOLD"$
- 传输延迟时间
- 最高时钟频率
#figure(
image("pic/2024-05-11-20-59-50.png", width: 30%),
caption: [
触发器的动态特性
],
)
#figure(
image("pic/2024-05-11-21-26-36.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-21-27-14.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-21-28-00.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-21-28-34.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-21-29-13.png", width: 80%),
numbering: none
)
== 寄存器
1. 用于寄存一组二值代码, N位寄存器由N个触发器组成,可存放一组N位二值代码。
2. 只要求其中每个触发器可置1,置0。
#figure(
image("pic/2024-05-11-21-02-48.png", width: 80%),
caption: [
74HC75
],
)
#figure(
image("pic/2024-05-11-21-04-52.png", width: 80%),
numbering: none
)
== 存储器
能存储大量二值信息的器件
- 单元数庞大
- 输入/输出引脚数目有限
=== 一般结构形式
#figure(
image("pic/2024-05-07-08-14-48.png", width: 80%),
caption: [
存储器的一般结构形式
],
)
=== 分类
1、从存/取功能分:
- 只读存储器(Read-Only-Memory)
- 掩模ROM
- 可编程ROM
- 可擦除可编程EPROM
- 随机读/写(Random-Access-Memory)
- 静态RAM
- 动态RAM
2、从工艺分:
- 双极型
- MOS型
== 随机存储器RAM
=== 静态随机存储器(SRAM)
==== 结构与工作原理
#figure(
image("pic/2024-05-07-08-18-50.png", width: 80%),
caption: [
静态随机存储器
],
)
采用二维是为了减少译码器走出的线的数量。
对于$n$位地址和$m$位数据,需要$2^n times m$个存储单元。
#figure(
image("pic/2024-05-07-08-24-36.png", width: 80%),
caption: [
静态随机存储器
],
)
物理连接已经确定,需要用三态的方式来选择电气连接。
=== SRAM的储存单元
#figure(
image("pic/2024-05-07-08-28-08.png", width: 70%),
caption: [
SRAM的储存单元
],
)
$T_1 ~ T_4$为基本存储单元,由两个双极型触发器构成。
$X_i = 1$时,所在行被选中,$T_5, T_6$导通,$Q,Q'$和$B_j,B_j'$相通。
$Y_j = 1$时,所在列被选中,$T_7, T_8$导通,此时第$i$行、第$j$列的存储单元被选中。
当$C S' = 0$时,若$R \/ W' = 1$,则$A_1$导通,$A_2,A_3$截至,$Q -> I \/ O$,此时存储单元被读出。
$R \/ W' = 0$,则$A_1$截至,$A_2,A_3$导通,$I \/ O -> Q$,此时存储单元被写入。
=== 动态随机存储器(DRAM)
动态存储单元是利用电容可以存储电荷的原理。
读写会慢,并且需要刷新电路。
#figure(
image("pic/2024-05-09-01-21-35.png", width: 80%),
caption: [
动态随机存储器
],
)
== 只读存储器ROM
利用组合电路来实现存储,所以掉电后数据不会丢失。
=== 掩模ROM
==== 结构
#figure(
image("pic/2024-05-07-08-41-41.png", width: 80%),
caption: [
掩模ROM
],
)
#figure(
image("pic/2024-05-07-08-50-57.png", width: 80%),
caption: [
掩模ROM
],
)
与译码器的结构相同,组成二极管与门、或门。有元件的地方就是1,没有元件的地方就是0。
对于该电路,我们可以得到数据表为:
#figure(
three-line-table[
|$A_1$|$A_0$|$W_3$|$W_2$|$W_1$|$W_0$|
|--|--|--|--|--|--|
|0|0|0|1|0|1|
|0|1|1|0|1|1|
|1|0|0|1|0|0|
|1|1|1|1|1|0|
],
caption: [
掩模ROM的数据表
],
kind: table
)
#figure(
image("pic/2024-05-07-09-01-19.png", width: 80%),
caption: [
ROM的模块示意图
],
)
两个概念:
- 存储矩阵的每个交叉点是一个“存储单元”,存储单元中有器件存入“1”,无器件存入“0”
- 存储器的容量:字数 $times$ 位数
掩模ROM的特点:
出厂时已经固定,不能更改,适合大量生产。简单,便宜,非易失性。
#figure(
image("pic/2024-05-07-09-00-38.png", width: 80%),
caption: [
掩模ROM
],
)
=== 可编程ROM(PROM)
总体结构与掩模ROM一样,但存储单元不同。
#figure(
image("pic/2024-05-09-01-24-34.png", width: 80%),
caption: [
可编程ROM
],
)
=== 可擦除的可编程ROM(EPROM)
总体结构与掩模ROM一样,但存储单元不同。
==== 用紫外线擦除的PROM(UVEPROM)
#figure(
image("pic/2024-05-07-09-03-30.png", width: 80%),
caption: [
叠栅注入MOS管
],
)
“写入”:雪崩注入,D-S间加高压(20 - 25V的,发生雪崩击穿同时在$G_c$上加 $25 V, 50 "ms"$宽的正脉冲,吸引高速电子穿过SiO2到达$G_f$,形成注入电荷。
“擦除”:通过照射产 生电子 空穴对,提供泄放通道。紫外线照射20-30分钟(阳光下一周,荧光灯下3年)。
==== 电可擦除的可编程ROM(E$""^2$PROM)
为克服UVEPROM擦除慢,操作不便的缺点。采用FLOTOX(浮栅隧道氧化层 MOS )。
#figure(
image("pic/2024-05-07-09-12-38.png", width: 80%),
caption: [
电可擦除的可编程ROM
],
)
#figure(
image("pic/2024-05-07-09-13-52.png", width: 80%),
caption: [
电可擦除的可编程ROM
],
)
==== 快闪存储器(Flash Memory)
为提高集成度,省去T2(选通管)改用叠栅MOS管(类似SIMOS管)。
#figure(
image("pic/2024-05-07-09-14-31.png", width: 80%),
caption: [
快闪存储器
],
)
=== 用存储器实现组合逻辑函数
===== 基本原理
从ROM的数据表可见:若以地址线为输入变量,则数据线即为一组关于地址变量的逻辑函数。
#figure(
image("pic/2024-05-09-01-25-53.png", width: 80%),
caption: [
用存储器实现组合逻辑函数
],
)
=== 存储器容量的扩展
==== 位扩展方式
适用于每片RAM,ROM字数够用而位数不够时
接法:将各片的地址线、读写线、片选线并联即可
#figure(
image("pic/2024-05-07-09-18-23.png", width: 80%),
caption: [
位扩展方式
],
)
==== 字扩展方式
适用于每片RAM,ROM位数够用而字数不够时
#figure(
image("pic/2024-05-07-09-21-35.png", width: 80%),
caption: [
字扩展方式
],
)
#figure(
image("pic/2024-05-07-09-22-19.png", width: 80%),
caption: [
字扩展方式
],
)
#pagebreak()
= 时序逻辑电路
== 概述
=== 时序逻辑电路的特点
1. 功能上:任一时刻的输出不仅取决于该时刻的输入,还与电路原来的状态有关。
例:串行加法器,两个多位数从低位到高位逐位相加
#figure(
image("pic/2024-05-07-09-28-00.png", width: 80%),
caption: [
串行加法器
],
)
工作时候,每次只有一个加法器工作,有多余的时间和功耗。可以采用存储器来存储中间结果。
=== 时序电路的一般结构形式与功能描述方法
#figure(
image("pic/2024-05-07-09-29-44.png", width: 80%),
caption: [
时序电路的一般结构形式
],
)
触发器尽量用边沿触发器,减少竞争冒险。
可以用三个方程组来描述:
- 输出方程
$
Y = F (X , Q)
$
- 驱动方程
$
Y = G (X , Q)
$
- 状态方程
$
Q^* = H (Z , Q)
$
=== 时序电路的分类
1. 同步时序电路与异步时序电路
同步:存储电路中所有触发器的时钟使用统一的clk,状态变化发生在同一时刻
异步:没有统一的clk,触发器状态的变化有先有后
2. Mealy型和Moore型
- Mealy型:$Y = F (X , Q)$
- Moore型:$Y = F (Q)$
== 时序电路的分析方法
=== 同步时序电路的分析方法
分析:找出给定时序电路的逻辑功能
即找出在输入和CLK作用下,电路的次态和输出。
一般步骤:
1. 从给定电路写出存储电路中每个触发器的驱动方程(输入的逻辑式),得到整个电路的驱动方程。
2. 将驱动方程代入触发器的特性方程,得到状态方程。
3. 从给定电路写出输出方程。
例如:
#figure(
image("pic/2024-05-09-08-15-52.png", width: 80%),
caption: [
时序电路的分析方法
],
)
这是一个Moore型的时序电路。
==== 状态转换表
#figure(
image("pic/2024-05-09-08-17-31.png", width: 40%),
caption: [
状态转换表
],
)
$Y$一定使用现态的$Q$计算的,而不是次态的$Q^*$。
==== 状态转换图
#figure(
image("pic/2024-05-09-08-20-53.png", width: 80%),
caption: [
状态转换图
],
)
例如:
#figure(
image("pic/2024-05-09-08-25-12.png", width: 80%),
caption: [
时序电路的分析方法
],
)
这是一个Mealy型的时序电路。
#figure(
image("pic/2024-05-09-08-26-36.png", width: 80%),
caption: [
状态转换图
],
)
注意Moore型和Mealy型的状态转换图。前者的$Y$标在圈内,后者的$Y$标在边上。
=== 异步时序逻辑电路的分析方法
#figure(
image("pic/2024-05-09-15-42-00.png", width: 80%),
caption: [
异步时序逻辑电路的分析方法
],
)
== 计数器
- 用于计数、分频、定时、产生节拍脉冲等
- 分类:按时钟分,同步、异步
按计数过程中数字增减分,加、减和可逆
按计数器中的数字编码分,二进制、二-十进制和循环码…
按计数容量分,十进制,六十进制…
=== 同步计数器
==== 同步二进制计数器
原理:根据二进制加法运算规则
可知:在多位二进制数末位加1,若第i位以下皆为1时,则第i位应翻转。
由此得出规律,若用T触发器构成计数器,则第i位触发器输入端$T_i$的逻辑式应为:
$
T_i = Q_(i-1) Q_(i-2) ... Q_0\
T_0 = 1
$
#figure(
image("pic/2024-05-09-08-44-58.png", width: 50%),
caption: [
同步二进制计数器
],
)
#figure(
image("pic/2024-05-09-16-01-50.png", width: 30%),
caption: [
74161
],
)
#figure(
image("pic/2024-05-09-16-03-06.png", width: 80%),
caption: [
74161的扩展接口
],
kind: table
)
==== 同步二进制减法计数器
原理:根据二进制减法运算规则可知:在多位二进制数末位减1,若第i位以下皆为0时,则第i位应翻转。
由此得出规律,若用T触发器构成计数器,则第i位触发器输入端$T_i$的逻辑式应为:
$
T_i = Q'_(i-1) Q'_(i-2) ... Q'_0\
T_0 = 1
$
#figure(
image("pic/2024-05-09-16-13-26.png", width: 80%),
caption: [
同步二进制减法计数器
],
)
==== 同步加减计数器
===== 单时钟方式
加/减脉冲用同一输入端,由加/减控制线的高低电平决定加/减
器件实例:74LS191(用T触发器)
$
T_i = (U' \/ D)' product_(i=0)^(i-1) Q_i + (U' \/ D) product_(i=0)^(i-1) Q'_i\
T_0 = 1
$
#figure(
image("pic/2024-05-09-16-21-44.png", width: 80%),
caption: [
74LS191
],
)
#figure(
image("pic/2024-05-09-16-16-37.png", width: 80%),
caption: [
74LS191扩展接口
],
kind: table
)
===== 双时钟方式
加和减分别用两个时钟输入端
$
C L K_i = C L K_U product_(i=0)^(i-1) Q_i + C L K_D product_(i=0)^(i-1) Q'_i\
C L K_0 = C L K_U + C L K_D
$
#figure(
image("pic/2024-05-09-16-36-19.png", width: 80%),
caption: [
74LS193(采用T'触发器)
],
)
==== 同步十进制计数器
===== 加法计数器
基本原理:在四位二进制计数器基础上修改,当计到1001时,则下一个CLK电路状态回到0000。
#figure(
image("pic/2024-05-09-16-56-16.png", width: 80%),
caption: [
十进制加法计数器
],
)
$
T_0 = 1\
T_1 = Q_0 Q'_3\
T_2 = Q_0 Q_1\
T_3 = Q_1 Q_2 Q_3 + Q_3 Q_0
$
器件实例:74160
#figure(
image("pic/2024-05-09-17-01-09.png", width: 80%),
caption: [
74160
],
)
#figure(
image("pic/2024-05-09-17-01-42.png", width: 80%),
caption: [
74160扩展接口
],
kind: table
)
===== 减法计数器
基本原理:对二进制减法计数器进行修改,在0000时减“1”后跳变为1001,然后按二进制减法计数就行了。
$
T_0 = 1\
T_1 = Q'_0(Q'_3 Q'_2 Q'_1)'\
T_2 = Q'_1Q'_0(Q'_3 Q'_2 Q'_1)'\
T_3 = Q_2 Q_1 Q_0
$
#figure(
image("pic/2024-05-09-17-25-11.png", width: 80%),
caption: [
确保该系统可以自启动
],
)
===== 十进制可逆计数器
基本原理一致,电路只用到0000~1001的十个状态
实例模块(器件)
- 单时钟:74190,168
- 双时钟:74192
=== 异步计数器
==== 二进制计数器
===== 异步二进制加法计数器
在末位+1时,从低位到高位逐位进位方式工作。
原则:每1位从“1”变“0”时,向高位发出进位,使高位翻转。
#figure(
image("pic/2024-05-09-17-28-27.png", width: 70%),
caption: [
异步二进制加法计数器
],
)
===== 异步二进制减法计数器
在末位-1时,从低位到高位逐位借位方式工作。
原则:每1位从“0”变“1”时,向高位发出进位,使高位翻转。
#figure(
image("pic/2024-05-09-17-29-21.png", width: 80%),
caption: [
异步二进制减法计数器
],
)
=== 任意进制计数器的构成方法
用已有的N进制芯片,组成M进制计数器,是常用的方法。
==== N > M
原理:计数循环过程中设法跳过$N-M$个状态。
具体方法:置零法 置数法
#figure(
image("pic/2024-05-09-17-33-35.png", width: 80%),
caption: [
N > M的方法
],
)
#figure(
image("pic/2024-05-09-17-35-10.png", width: 80%),
caption: [
将十进制的74160接成六进制计数器
],
)
其中$G_1,G_2$的结构是为了将峰展宽,使得$Q_0$能够跳过。
#figure(
image("pic/2024-05-09-17-38-32.png", width: 80%),
caption: [
将十进制的74160接成六进制计数器
],
)
==== N < M
===== M=N1×N2
先用前面的方法分别接成N1和N2两个计数器。
N1和N2间的连接有两种方式:
1. 并行进位方式:用同一个CLK,低位片的进位输出作为高位片的计数控制信号(如74160的EP和ET)
2. 串行进位方式:低位片的进位输出作为高位片的CLK,两片始终同时处于计数状态
#figure(
image("pic/2024-05-10-21-18-59.png", width: 80%),
caption: [
用两片74160接成100进制计数器
],
)
===== M不可分解
采用整体置零和整体置数法:
先用两片接成 M’> M 的计数器,然后再采用置零或置数的方法。
#figure(
image("pic/2024-05-10-21-58-50.png", width: 80%),
caption: [
用74260接成29进制计数器
],
)
=== 计数器应用实例
==== 顺序节拍脉冲发生器
计数器+译码器→顺序节拍脉冲发生器
#figure(
image("pic/2024-05-11-08-08-42.png", width: 80%),
caption: [
顺序节拍脉冲发生器
],
)
这是一个巡检电路,可以依次对每个$P_i$进行控制。
将译码器的$S_1$接入CLK,这是为了在CLK=0时候可以规避竞争冒险。
==== 序列脉冲发生器
计数器+数据选择器→序列脉冲发生器
#figure(
image("pic/2024-05-11-08-12-01.png", width: 80%),
caption: [
序列脉冲发生器
],
)
== 时序电路的设计
#figure(
image("pic/2024-05-11-08-13-02.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-08-19-44.png", width: 80%),
caption: [
有限状态机
],
)
#figure(
image("pic/2024-05-11-08-23-15.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-08-40-11.png", width: 80%),
numbering: none
)
次态和输出一致,$S_2,S_3$可以合并。
#figure(
image("pic/2024-05-11-08-41-33.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-11-08-42-41.png", width: 80%),
numbering: none
)
对于自启动,可以在设计的时候就解决。
#figure(
image("pic/2024-05-11-09-07-53.png", width: 80%),
numbering: none
)
一般情况下Mealy和Moore型都能实现,但是Moore型用的状态更多。
#figure(
image("pic/2024-05-11-09-08-40.png", width: 80%),
numbering: none
)
== 单时钟同步电路
单一时钟同步数字电路的速度是不受规模限制的,周期受最慢一级的触发器运算时间限制。
我们将以高度受限的方式使用触发器和寄存器(共享一个时钟输入的触发器组)来构建数字系统:
- 无组合周期
- 所有时钟设备共享一个时钟信号
- 只关心时钟上升沿前组合电路的值
- 周期大于每个组合延迟
- 在噪声逻辑转换停止后更改保存状态
#figure(
image("pic/2024-05-18-21-40-32.png", width: 40%),
numbering: none
)
#figure(
image("pic/2024-05-14-08-13-45.png", width: 80%),
numbering: none
)
输出时序限制:
- Propagation delay传播延迟:$t_"pcq"$ = 保证输出 Q 稳定(即停止变化)的时钟沿后时间
- Contamination delay:$t_"ccq"$ = 时钟边沿后 Q 可能不稳定(即开始变化)的时间
#figure(
image("pic/2024-05-18-22-20-56.png", width: 50%),
numbering: none
)
输入时序限制:
- Setup time:$t_"setup"$ = 时钟沿前的时间数据必须稳定(即不变化)
- Hold time:$t_"hold"$ = 时钟沿后的时间数据必须稳定(即不变化)
- Aperture time:$t_"a "$ = 时钟边缘时间数据必须稳定
$
t_"a" = t_"setup" + t_"hold"
$
#newpara()
设置时间限制:
- 取决于从寄存器 R1 通过组合逻辑到 R2 的最大延迟时间
- 寄存器 R2 的输入必须在时钟边沿之前至少$t_"setup"$保持稳定。
$
T_c ≥ t_"pcq" + t_"pd" + t_"setup"
$
#figure(
image("pic/2024-05-18-22-26-17.png", width: 80%),
numbering: none
)
保持时间限制:
- 取决于从寄存器 R1 通过组合逻辑到 R2 的最小延迟时间
- 寄存器 R2 的输入必须在时钟沿后至少保持 $t_"hold"$ 稳定
$
t_"hold" < t_"ccq" + t_"cd"
$
#figure(
image("pic/2024-05-18-22-29-34.png", width: 80%),
numbering: none
)
*综上,动态时间要求:*
$
T_c ≥ t_"pcq" + t_"pd" + t_"setup"\
t_"cd" > t_"hold" - t_"ccq"
$
=== 时序电路小结
==== 离散的重要性
Digital Values:
- 问题: 区分表示 "1 "和 "0 "的电压
- 解决方案: 禁区: 避免使用类似的电压表示 "1 "和 "0"
Digital Time:
- 问题:"哪个过渡最先发生?
- 解决方案:动态时间要求
==== FSM 的局限性
- 尽管 FSM 具有实用性和灵活性,但仍有一些常见问题是 FSM 无法计算的。例如
_格式良好的括号检查器: 给定任何左右括号编码字符串,如果平衡,则输出 1,否则输出 0。这个装置是否等同于我们列举的一种 FSM?_
问题:需要*任意*多个状态,取决于输入。必须 "计算 "未匹配的后缀。一个 FSM 只能记录无数个不匹配的后缀:对于每一个 FSM,我们都能找到一个它无法检查的字符串。
$s$位状态机的状态数是$2^s$,所以有限状态机是有限的。
=== 图灵机和冯诺依曼、哈弗结构
- 分开存储器和处理器
- 用存储器存储程序和数据
- 用处理器执行程序
- 用指令来控制处理器的操作
== 移位寄存器
=== 寄存器
- 用于寄存一组二值代码,N位寄存器由N个触发器组成,可存放一组N位二值代码。
- 只要求其中每个触发器可置1,置0。
#figure(
image("pic/2024-05-14-08-37-15.png", width: 80%),
caption: [
74HC75
],
)
CLK上升沿,将$D_0 tilde D_3$存入,与此前后的$D$状态无关,有异步置零功能。
=== 移位寄存器
串变并的功能:将串行数据转换为并行数据
#figure(
image("pic/2024-05-18-23-17-46.png", width: 80%),
caption: [
移位寄存器
],
)
#figure(
image("pic/2024-05-18-23-21-45.png", width: 80%),
caption: [
74LS194A
],
)
#figure(
image("pic/2024-05-18-23-24-14.png", width: 80%),
caption: [
控制194的工作状态
],
)
#figure(
image("pic/2024-05-18-23-30-05.png", width: 80%),
caption: [
移位寄存器的扩展
],
)
== 流水线
- Token:一组输入经处理后产生一组输出
- 延迟 Latency:一个Token从开始到结束所需的时间
- 吞吐量 Throughput:单位时间内产生的Token数量
*流水线*增加吞吐量
*定义*
K 级流水线("K-流水线")是一种非循环电路,从输入到输出的每条路径上都有 K 个寄存器。因此,一个组合电路就是一条 0 级流水线。
每一级流水线,也就是每一条 K 级流水线,都有一个寄存器位于其输出端(而非输入端)有一个寄存器。
所有寄存器共用的时钟必须有足够的周期,以覆盖组合路径上的传播 PLUS(输入)寄存器 tPDPLUS(输出)寄存器 tSETUP。
- K-pipeline 的延迟时间是所有寄存器共用时钟周期的 K 倍。
- K-pipeline 的 THROUGHPUT 是时钟的频率。
*优点*:
- 打破长组合路径,提高时钟频率,从而提高总输出功率
*缺点*:
- 可能会增加延迟
- 只有最薄弱的环节才是最好的:最慢的步骤限制了系统的总输出。
*电路交错*
- 我们可以通过复制关键元件并在不同副本之间交替输入,来模拟慢速元件的交错版本。
当 Q 为 1 时,下层路径为组合路径(锁存器打开),但上层路径的输出将被启用到输出寄存器的输入端,为下一个时钟沿做好准备。
#figure(
image("pic/2024-05-19-01-19-27.png", width: 80%),
numbering: none
)
利用选择器,可以将两个同样地元件按照不同的时钟信号进行切换,起到交错的作用。这样可以提高整体的THROUGHPUT。
== 可编程逻辑器件(PLD, Programmable Logic Device)
=== PLD的基本特点:
1. 数字集成电路从功能上有分为 通用型、专用型两大类
2. PLD的特点:是一种按通用器件来生产,但逻辑功能是由用户通过对器件编程来设定的
=== PLD的发展和分类
PROM是最早的PLD
1. FPLA 现场可编程逻辑阵列
2. PAL可编程逻辑阵列
3. GAL 通用阵列逻辑
4. EPLD 可擦除的可编程逻辑器件
5. CPLD 复杂的可编程逻辑器件
6. FPGA 现场可编程门阵列
#figure(
image("pic/2024-05-19-01-35-38.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-36-20.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-36-52.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-37-21.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-38-23.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-38-55.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-39-17.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-39-52.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-40-25.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-41-04.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-41-36.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-42-05.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-42-40.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-45-48.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-19-01-46-26.png", width: 80%),
numbering: none
)
= 脉冲波形的产生和整形
== 概述
=== 获取矩形脉冲的方法
1. 脉冲波形发生电路
2. 脉冲波形整形电路
=== 描述矩形脉冲特性的主要参数
#figure(
image("pic/2024-05-19-01-48-55.png", width: 80%),
caption: [
描述矩形脉冲特性的主要参数
],
)
== 施密特触发器(常用的一类脉冲整形电路)
=== 用门电路组成的施密特触发器
考虑下面的电路:
#figure(
image("pic/2024-05-19-01-48-22.png", width: 80%),
numbering: none
)
当$V_I = 0$时,$V_O = 0$。
当$V_I arrow.t$至$V_A = V_"TH"$时,进入传输特性的放大区,故$V_"A " arrow.t -> V_"O1" arrow.b -> V_O arrow.t -> V_"A " arrow.t$形成正反馈。使电路迅速跳变到$V_O = V_"OH"$。
$
V_A = V_"TH" = (R_2)/(R_1 + R_2) V_I\
V_I = v_"T+" = (1 + R_2/R_1) V_"TH"\
$
#newpara()
当$V_I = 1$时,$V_O = 1$。
当$V_I arrow.t$至$V_A = V_"TL"$时,进入传输特性的放大区,故$V_"A " arrow.t -> V_"O1" arrow.b -> V_O arrow.t -> V_"A " arrow.t$形成正反馈。使电路迅速跳变到$V_O = V_"OL"$。
$
V_A = V_"TH" = (V_"DD" - V_I) R_1/(R_1 + R_2) + V_I\
V_I = v_"T-" = (1 - R_1/R_2) V_"TL"\
$
#figure(
image("pic/2024-05-19-02-20-02.png", width: 80%),
caption: [
用门电路组成的施密特触发器
],
)
=== CMOS IC
#figure(
image("pic/2024-05-19-02-20-43.png", width: 80%),
caption: [
CMOS IC
],
)
*施密特触发器的主要特点:*
输入信号在上升和下降过程中,电路状态转换的输入电平不同。电路状态转换时有正反馈过程,使输出波形边沿变陡。
=== 施密特触发器的应用
==== 用于波形变换
#figure(
image("pic/2024-05-19-02-22-16.png", width: 30%),
caption: [
用于波形变换
],
)
==== 用于鉴幅
#figure(
image("pic/2024-05-19-02-22-34.png", width: 30%),
caption: [
用于鉴幅
],
)
==== 用于脉冲整形
#figure(
image("pic/2024-05-19-02-23-07.png", width: 30%),
caption: [
用于脉冲整形
],
)
== 单稳态触发器
特点:
1. 有一个稳态和一个暂稳态。
2. 在外界触发信号作用下,能从稳态→暂稳态,维持一段时间后自动返回稳态。
3. 暂稳态维持的时间长短取决于电路内部参数。
=== 用门电路组成的单稳态触发器
==== 积分型
#figure(
image("pic/2024-05-21-08-09-24.png", width: 80%),
caption: [
积分型单稳态触发器
],
)
- 稳态下: $V_I = 0,V_O = 1$,$(V_(O 1) = V_(O H) ),V_A = V_(O H)$;
- $V_I arrow.t$ 后, $V_O = 0$,进入*暂稳态*,$V_(O 1) = 0$,$C$开始放电;
- 当放至$V_A = V_"TH"$后,$V_O = 1$,返回稳态;
- $V_I arrow.b$后,$C$重新充电至$V_(O H)$,恢复初始态。
#figure(
image("pic/2024-05-21-08-16-41.png", width: 80%),
numbering: none
)
将一个长的脉冲变成一个短的脉冲。
#figure(
image("pic/2024-05-21-08-19-02.png", width: 80%),
caption: [
性能参数计算
],
)
==== 微分型
#figure(
image("pic/2024-05-21-08-30-34.png", width: 80%),
caption: [
微分型单稳态触发器
],
)
稳态下:$V_I = 0,V_d = 0, V_(I 2) = V_"DD",V_O = 0, V_(O 1) = V_"DD"$,$C$上无电压。
加触发信号$V_I arrow.t$,$V_d arrow.t -> V_(O 1) arrow.b -> V_(I 2) arrow.b -> V_O arrow.t -> V_d arrow.t$,形成正反馈,$V_O = 1$,进入暂稳态,$C$开始充电。
充电至$V_(I 2) = V_"TH"$时,$V_(I 2)$又引起正反馈,$V_(I 2) arrow.t -> V_O arrow.b -> V_(O 1) arrow.t -> V_(I 2) arrow.t$,$V_O = 0$,电路迅速返回稳态。
#figure(
image("pic/2024-05-21-08-40-31.png", width: 80%),
caption: [
性能参数计算
],
)
== 多谐振荡器(自激振荡,不需要外加触发信号)
=== 用施密特触发器构成的多谐振荡器
#figure(
image("pic/2024-05-21-08-45-47.png", width: 80%),
numbering: none
)
用二极管来选择电阻进行占空比的调节。
=== 环形振荡器
==== 环形振荡器的基本原理
#figure(
image("pic/2024-05-21-08-54-57.png", width: 80%),
numbering: none
)
有时延的负反馈环路,可以产生振荡。
==== 实用的环形振荡器
#figure(
image("pic/2024-05-21-08-58-01.png", width: 80%),
numbering: none
)
第一步的图中,由于电容的存在,增加了充放电的时间,周期变成了$12 t_"pd"$。
#figure(
image("pic/2024-05-21-09-14-52.png", width: 80%),
numbering: none
)
注意$V_(I 3)$处的跳变。
=== 非对称式多谐振荡器
=== 石英晶体多谐振荡器
#figure(
image("pic/2024-05-21-09-20-21.png", width: 80%),
numbering: none
)
== 555定时器
=== 555定时器 (数/模混合IC)
==== 电路结构
- 电压比较器(C1,C2)[运算放大器]
- 触发器
- 输出缓冲器(G3,G4)
- OC输出的三极管(TD)
#figure(
image("pic/2024-05-23-08-14-11.png", width: 80%),
caption: [
555定时器
],
)
==== 功能表
注意到中间的结构是SR触发器,反向输入,$C_2$对应$S'$,$C_1$对应$R'$。
#figure(
three-line-table[
|$R'_D$|$V_(I 1)$|$V_(I 2)$|$V_O$|$T_D$|
|----|--|--|--|--|
|0|x|x|0|导通|
|1|$>2/3 V_"CC"$|$>1/3 V_"CC"$|0|导通|
|1|$<2/3 V_"CC"$|$>1/3 V_"CC"$|不变|不变|
|1|$<21/3 V_"CC"$|$<2/3 V_"CC"$|1|截止|
|1|$>2/3 V_"CC"$|$<1/3 V_"CC"$|1|截止|
],
numbering: none
)
=== 用555定时器接成施密特触发器
#figure(
image("pic/2024-05-23-08-25-03.png", width: 60%),
numbering: none
)
=== 用555实现多谐
#figure(
image("pic/2024-05-23-08-27-25.png", width: 80%),
numbering: none
)
$R_1$不能太小,否则管子会烧掉;$R_2$不能太大,否则无法达到高电平。
充电时管子截止,$R=R_1 + R_2$;放电时管子导通,$R=R_2$。
#figure(
image("pic/2024-05-23-08-33-28.png", width: 80%),
caption: [
修改占空比
],
)
=== 用555实现单稳态触发器
#figure(
image("pic/2024-05-23-08-34-12.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-23-08-38-20.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-23-08-40-02.png", width: 80%),
numbering: none
)
性能参数:暂稳态输出有宽度要求,否则导致$Q$始终为1。
$
t_w = R C ln (V_"CC" - 0)/(V_"CC" - 2/3 V_"CC") = R C ln 3
$
如果宽度过宽,可以用微分电路($V_I$取一个电容到新输入$V'_I$,在$V_I$与$V_"CC"$接一个电阻)只取一个边沿。
= 集成运算放大电路
复合管
#figure(
image("pic/2024-05-23-09-26-29.png", width: 80%),
numbering: none
)
== 多级放大电路
=== 多级放大电路的耦合方式
==== 阻容耦合
#figure(
image("pic/2024-05-28-08-11-01.png", width: 80%),
numbering: none
)
利用电容连接信号源与放大电路、放大电路的前后级、放大电路与负载,为阻容耦合。
==== 直接耦合
#figure(
image("pic/2024-05-28-08-13-12.png", width: 80%),
numbering: none
)
Q点互相影响。
==== 变压器耦合
#figure(
image("pic/2024-05-28-08-14-39.png", width: 80%),
numbering: none
)
低频特性差。
==== 光电耦合
#figure(
image("pic/2024-05-28-08-16-11.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-28-08-16-48.png", width: 80%),
numbering: none
)
=== 多级放大电路的动态分析
==== 交流分析
1. 电压放大倍数
$
dot(A) = product_(i=1)^n dot(A)_i
$
2. 输入电阻
3. 输出电阻
#figure(
image("pic/2024-05-28-08-23-17.png", width: 80%),
numbering: none
)
== 集成运算放大电路简介
=== 集成运放的特点
集成运算放大电路,简称集成运放,是一个高性能的直接耦合多级放大电路。因首先用于信号的运算,故而得名。
- 集成电路中不能制作大电容,故采用直接耦合方式。
- 集成运放相邻元件参数具有很好的一致性,故可构成较理想的差分放大电路和电流源电路。
- 用有源元件替代无源元件,如*用晶体管取代难于制作的大电阻*。
- 用复杂电路实现高性能的放大电路,因为电路的复杂化并不带来工艺的复杂性。
- 采用*复合管*。
=== 集成运放电路的方框图
#figure(
image("pic/2024-05-28-08-26-50.png", width: 80%),
caption: [
集成运放电路的方框图
],
)
- 偏置电路:为各级放大电路设置合适的*静态工作点*。采用电流源电路。
- 输入级:前置级,多采用*差分放大电路*。要求$R_i$大,$A_d$大,$A_c$小,输入端耐压高。
- 中间级:主放大级,多采用共射放大电路。要求有足够的放大能力。
- 输出级:功率级,多采用准互补输出级。要求$R_o$小,最大不失真输出电压尽可能大。
=== 集成运放的符号及电压传输特性
高性能:输入电阻很大、输出电阻很小、差模放大倍数很大、共模放大倍数很小、共模抑制比高、温度稳定性好……
==== 符号
#figure(
image("pic/2024-05-28-08-30-21.png", width: 80%),
caption: [
集成运放的符号及电压传输特性
],
)
不同型号的集成运放供电电源不同,有的两路电源供电,有的一路电源供电,有的两种情况均可。缺省时认为是$±V_"CC"$(常为±15V)供电。
==== 电压传输特性:输出电压与输入电压的函数关系
#figure(
image("pic/2024-05-28-08-32-00.png", width: 80%),
caption: [
电压传输特性
],
)
==== 理想运放及其动态等效电路
理想运放的参数特点:
- 差模输入电阻$r_"id"$为$∞$
- 输出电阻$r_o$为$0$
- 开环差模增益$A_"od"$为$∞$
- 共模抑制比$K_"CMR"$为$∞$
- 频带无限宽
- 温度对参数无影响
#figure(
image("pic/2024-05-28-08-34-02.png", width: 40%),
caption: [
理想运放及其动态等效电路
],
)
==== 理想运放的两个工作区
将放大电路的输出量通过一定的方式引回到输入端来影响输入量,称为反馈;若反馈的结果使输出量的变化减小,则称为负反馈,否则称为正反馈。
*集成运放工作在线性区需引入负反馈。*
#figure(
image("pic/2024-05-28-08-34-59.png", width: 40%),
caption: [
理想运放的两个工作区
],
)
其中反馈通路是无源网络。
- *线性区*: “虚短” 和“虚断”
- 由于输出电压为有限值,差模开环放大倍数为无穷大,根据$u_O = A_"od" (u_P- u_N)$可知,$u_P - u_N = 0$,即集成运放的*净输入电压为0*,$u_P= u_N$,称为“虚短路” 。
- 由于净输入电压为0,且集成运放的*输入电阻为无穷大*,所以两个*输入端的输入电流为0*, $i_P = i_N = 0$;即集成运放的净输入电流为0,称为“虚断路” 。
- *非线性区*
- 输出电压只有两种可能的值,不是$+U_"OM"$,就是$-U_"OM"$,$±U_"OM"$接近其供电电源$±V_"CC"$。
- 因为$(u_P - u_N)$总是有限值,而$r_"id"=∞$,故净输入电流为0,即$i_P = i_N = 0$,呈“虚断”
== 差分放大电路
=== 零点漂移现象及其产生的原因
*零点漂移现象*:$Δ u_I=0$,$Δ u_O≠0$的现象。
#figure(
image("pic/2024-05-28-08-36-42.png", width: 80%),
numbering: none
)
产生原因:温度变化,直流电源波动,元器件老化。其中晶体管的特性对温度敏感是主要原因,故也称零漂为温漂。
克服温漂的方法:引入直流负反馈,温度补偿。
典型电路:差分放大电路。
=== 差分放大电路的概念
==== 需求
#figure(
image("pic/2024-05-28-08-41-19.png", width: 80%),
numbering: none
)
需要一种放大电路,对$u_(I 1)$和$u_(I 2)$共同的部分不放大,仅对它们的差值放大。
==== 基本差分放大电路
#figure(
image("pic/2024-05-28-08-45-31.png", width: 80%),
numbering: none
)
利用镜像电路,可以保证两边温漂相同。
1. 电路组成——*对称性*
#figure(
image("pic/2024-05-28-08-52-28.png", width: 80%),
numbering: none
)
2. Q点分析
$
I_(B Q 1) = I_(B Q 2) = I_(B Q)\
I_(C Q 1) = I_(C Q 2) = I_(C Q)\
I_(E Q 1) = I_(E Q 2) = I_(E Q)\
U_(C Q 1) = U_(C Q 2) = U_(C Q)\
u_o = U_(C Q 1) - U_(C Q 2) = 0
$
晶体管输入回路方程:
$
V_"EE" = I_(B Q) R_b + U_"BEQ" + 2 I_(E Q) R_e\
$
通常,$R_b$较小,且$I_"BQ"$很小,故
$
I_"EQ" approx (V_"EE" - U_"BEQ")/(2 R_e), I_"BQ" = I_"EQ"/(β + 1)\
U_"CEQ" approx V_"CC" - I_"CQ" R_c + U_"BEQ"
$
3. 抑制共模信号:$R_e$的共模负反馈作用
共模信号:数值相等、极性相同的输入信号,即$u_(I 1) = u_(I 2)$。
共模放大倍数:$A_c = (Δ u_(O c))/(Δ u_(I c))$,参数理想对称时,$A_c = 0$。
#figure(
image("pic/2024-06-02-23-12-16.png", width: 80%),
numbering: none
)
4. 放大差模信号
差模信号:数值相等,极性相反的输入信号,即$u_(I 1) = -u_(I 2) = 1/2 u_(I d)$。
$
Delta i_(B 1) = - Delta i_(B 2)\
Delta i_(C 1) = - Delta i_(C 2)\
Delta i_(E 1) = - Delta i_(E 2)\
Delta u_(C 1) = - Delta u_(C 2)\
Delta u_O = 2 Delta u_(C 1)
$
$Delta i_(E 1)=- Delta i_(E 2)$,Re中电流不变,即*$R_e$对差模信号无反馈作用*。
E点电压稳定,在交流等效电路中接地。
#figure(
image("pic/2024-05-28-09-12-44.png", width: 80%),
numbering: none
)
差模放大倍数:
$
A_d = - (beta (R_C parallel R_L))/(R_b + r_"be")
$
共模抑制比$K_"CMR"$:综合考察差分放大电路放大差模信号的能力和抑制共模信号的能力。
在实际应用时,信号源需要有“接地”点,以避免干扰;或负载需要有“接地”点,以安全工作。
根据信号源和负载的接地情况,差分放大电路有四种接法:双端输入双端输出、双端输入单端输出、单端输入双端输出、单端输入单端输出。
=== 差分放大电路的四种接法
在实际应用时,信号源需要有“接地”点,以避免干扰;或负载需要有“接地”点,以安全工作。
==== 双端输入单端输出
#figure(
image("pic/2024-05-30-08-16-35.png", width: 80%),
numbering: none
)
静态工作点的选择和$R_c$有关,选择电流为$(V_"EE" - U_"CE")/R_C$
#figure(
image("pic/2024-06-02-23-25-02.png", width: 80%),
numbering: none
)
==== 单端输入双端输出
#figure(
image("pic/2024-06-03-00-35-01.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-06-03-00-35-51.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-06-03-00-36-26.png", width: 80%),
numbering: none
)
=== 差分放大电路的改进
==== 具有恒流源的差分放大电路
$R_e$越大,每一边的漂移越小,共模负反馈越强,单端输出时的$A_c$越小,$K_"CMR"$越大,差分放大电路的性能越好。
但为使静态电流不变,$R_e$越大,$V_"EE"$越大,以至于$R_e$太大就不合理了。
需在低电源条件下,设置合适的$I_"EQ"$,并得到得到趋于无穷大的$R_e$。
采用电流源取代$R_e$就解决了这个问题。
#figure(
image("pic/2024-06-03-00-46-08.png", width: 80%),
numbering: none
)
==== 加调零电位器$R_W$
#figure(
image("pic/2024-06-03-00-46-50.png", width: 80%),
numbering: none
)
==== 场效应管差分放大电路
#figure(
image("pic/2024-06-03-00-47-23.png", width: 80%),
numbering: none
)
== 功率放大电路
=== 概述
==== 功率放大电路研究的问题
1. 性能指标:*输出功率和效率*。若已知$U_"om"$,则可得$P_"om"$。$P_"om" = U_"om"^2/(R_L)$。最大输出功率与电源损耗的平均功率之比为效率$η = P_"om"/P_"V"$。
2. 分析方法:因大信号作用,故应采用图解法。
3. 晶体管的选用:根据极限参数选择晶体管。
在功放中,晶体管集电极或发射极电流的最大值接近最大集电极电流$I_"CM"$,管压降的最大值接近c-e反向击穿电压$U_"(BR)CEO"$, 集电极消耗功率的最大值接近集电极最大耗散功率$P_"CM"$。称为工作在*尽限状态*。
==== 对功率放大电路的要求
1. 输出功率尽可能大:即在电源电压一定的情况下,最大不失真输出电压最大。
2. 效率尽可能高:即电路损耗的直流功率尽可能小,静态时功放管的集电极电流近似为0。
==== 晶体管的工作方式
1. 甲类方式:晶体管在信号的整个周期内均处于导通状态
2. 乙类方式:晶体管仅在信号的半个周期处于导通状态
3. 甲乙类方式:晶体管在信号的多半个周期处于导通状态
=== OCL电路(Output Capacitor-Less Circuit)
==== 输出级的要求
互补输出级是直接耦合的功率放大电路。
对输出级的要求:
- 带负载能力强:射极输出形式
- 直流功耗小:静态工作电流小
- 负载电阻上无直流功耗:输入为零时输出为零
- 最大不失真输出电压最大:
- 双电源供电时$U_"om"$的峰值接近电源电压。
- 单电源供电$U_"om"$的峰值接近二分之一电源电压。
==== 基本电路
特征:虽$T_1$、$T_2$分别为NPN和PNP型管,但特性理想对称。
#figure(
image("pic/2024-05-30-08-23-02.png", width: 80%),
caption: [
OCL的静态工作点
],
)
#figure(
image("pic/2024-05-30-08-23-51.png", width: 80%),
caption: [
OCL的动态电路
],
)
==== 交越失真
本质是截止失真
#figure(
image("pic/2024-05-30-08-25-22.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-05-30-08-28-47.png", width: 80%),
numbering: none
)
#pagebreak()
= 放大电路中的反馈
== 反馈的基本概念及判断方法
=== 反馈的基本概念
反馈放大电路可用方框图表示。
#figure(
image("pic/2024-06-03-01-12-45.png", width: 80%),
caption: [
反馈放大电路的方框图
],
)
放大电路输出量的一部分或全部通过一定的方式引回到输入回路,影响输入,称为反馈。
==== 正反馈和负反馈
从反馈的结果来判断,凡反馈的结果使*输出量*的变化减小的为负反馈,否则为正反馈;或者,凡反馈的结果使*净输入量*减小的为负反馈,否则为正反馈。
==== 支流反馈和交流反馈
直流通路中存在的反馈称为直流反馈,交流通路中存在的反馈称为交流反馈。
#figure(
image("pic/2024-06-03-01-23-10.png", width: 80%),
numbering: none
)
==== 局部反馈和级间反馈
只对多级放大电路中某一级起反馈作用的称为局部反馈,将多级放大电路的输出量引回到其输入级的输入回路的称为级间反馈。
#figure(
image("pic/2024-06-03-01-24-18.png", width: 80%),
numbering: none
)
=== 交流负的四种组态
==== 电压反馈和电流反馈
描述放大电路和反馈网络在输出端的连接方式,即反馈网络的取样对象。
#figure(
image("pic/2024-06-03-01-29-33.png", width: 60%),
numbering: none
)
将输出电压的一部分或全部引回到输入回路来影响净输入量的为*电压反馈*,即
$
dot(X)_0 = dot(U)_0
$
将输出电流的一部分或全部引回到输入回路来影响净输入量的为*电流反馈*,即
$
dot(X)_0 = dot(I)_0
$
==== 串联反馈和并联反馈
描述放大电路和反馈网络在输入端的连接方式,即*输入量、反馈量、净输入量的叠加关系*。
串联负反馈:
$
dot(U)_i = dot(U)_i^' + dot(U)_f
$
并联负反馈:
$
dot(I)_i = dot(I)_i^' + dot(I)_f
$
==== 四种反馈组态
#figure(
image("pic/2024-06-03-01-31-44.png", width: 80%),
numbering: none
)
在串联负反馈电路中不加恒流源信号,在并联负反馈电路中不加恒压源信号。
选择输出端稳定的作为反馈端,选择输入信号的形式作为输入端。
前端是电压源一定要进行并联反馈,这是因为电流源无法给其进行负反馈。
=== 反馈的判断
==== 有无反馈的判断
“找联系”:找输出回路与输入回路的联系,若有则有反馈,否则无反馈。
#figure(
image("pic/2024-06-03-01-49-13.png", width: 80%),
numbering: none
)
==== 直流反馈和交流反馈的判断
“看通路”:即看反馈是存在于直流通路还是交流通路。设以下电路中所有电容对交流信号均可视为短路
#figure(
image("pic/2024-06-03-01-50-16.png", width: 80%),
numbering: none
)
==== 正、负反馈(反馈极性)的判断
“看反馈的结果” ,即净输入量是被增大还是被减小。
#figure(
image("pic/2024-06-03-01-51-14.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-06-03-01-51-44.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-06-03-01-52-13.png", width: 80%),
numbering: none
)
==== 电压反馈和电流反馈的判断
*令输出电压为0,若反馈量随之为0,则为电压反馈;若反馈量依然存在,则为电流反馈。*
#figure(
image("pic/2024-06-03-01-53-07.png", width: 80%),
numbering: none
)
==== 串联反馈和并联反馈的判别
在输入端,输入量、反馈量和净输入量以电压的方式叠加,为串联反馈;以电流的方式叠加,为并联反馈。
#figure(
image("pic/2024-06-03-01-53-50.png", width: 80%),
numbering: none
)
== 负反馈放大电路的方框图及一般表达式
=== 负反馈放大电路的方框图
#figure(
image("pic/2024-06-03-01-55-59.png", width: 80%),
numbering: none
)
=== 负反馈放大电路放大倍数的一般表达式
$
dot(A) = dot(X)_o / dot(X)_i^'\
dot(F) = dot(X)_f / dot(X)_o\
dot(A)_f = dot(X)_o / dot(X)_i
$
则有
$
dot(A)_f = dot(A) / (1 + dot(A) dot(F))
$
其中$dot(A) dot(F)$称为*环路放大倍数(环路增益)*。环路增益越大,负反馈越深,放大倍数越小。
#figure(
image("pic/2024-06-03-01-59-24.png", width: 80%),
numbering: none
)
=== 负反馈放大电路放大倍数和反馈系数的量纲
#figure(
image("pic/2024-06-03-02-01-05.png", width: 80%),
numbering: none
)
== 关于负反馈的一些讨论
=== 提高放大倍数的稳定性
在中频段,放大倍数、反馈系数等均为实数。
$
A_f = A / (1 + A F)\
dd(A_f)/dd(A) = 1 / (1 + A F)^2\
dd(A_f) = dd(A) / (1 + A F)^2\
dd(A_f)/A_f = 1/(1 + A F) dd(A)/A
$
说明放大倍数减小到基本放大电路的$1/(1 + A F)$倍;放大倍数的稳定性是基本放大电路的$1 + A F$倍。
=== 改变输入电阻和输出电阻
==== 对输入电阻的影响
对输入电阻的影响仅与反馈网络与基本放大电路输入端的接法有关,即决定于是串联反馈还是并联反馈。
- *引入串联负反馈时*
$
R_i = U_i^' / I_i\
R_(i f) = U_i / I_i = (U_i^' + U_f) / I_i = (1 + A F) R_i
$
- *引入并联负反馈时*
$
R_i = U_i / I_i\
R_(i f) = U_i / I_i = U_i / (I_i + I_f) = R_i / (1 + A F)
$
*串联负反馈增大输入电阻,并联负反馈减小输入电阻。*
在$(1 + A F) -> ∞$时,引入串联负反馈$R_(i f) -> ∞$,引入并联负反馈$R_(i f) -> 0$。
==== 对输出电阻的影响
对输出电阻的影响仅与反馈网络与基本放大电路输出端的接法有关,即决定于是电压反馈还是电流反馈。
*电压负反馈减小输出电阻,电流负反馈增大输出电阻。*
- *引入电压负反馈时*
$
R_o = U_o / I_o\
R_(o f) = U_o / I_o = U_o / ((U_o - (-A F U_o))/R_o) = R_o / (1 + A F)
$
- *引入电流负反馈时*
$
I_o = U_o / R_o + (- A F I_o)\
R_(o f) = U_o / I_o = (1 + A F) R_o
$
在$(1 + A F) -> ∞$时,引入电压负反馈$R_(o f) -> 0$,引入电流负反馈$R_(o f) -> ∞$。
==== 展宽频带:设反馈网络是纯电阻网络
#figure(
image("pic/2024-06-03-02-08-44.png", width: 80%),
numbering: none
)
==== 减小非线性失真
#figure(
image("pic/2024-06-03-02-09-15.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-06-03-02-09-55.png", width: 80%),
numbering: none
)
==== 引入负反馈的一般原则
- 稳定Q点应引入直流负反馈,改善动态性能应引入交流负反馈;
- 根据信号源特点,增大输入电阻应引入串联负反馈,减小输入电阻应引入并联负反馈;
- 根据负载需要,需输出稳定电压(即减小输出电阻)的应引入电压负反馈,需输出稳定电流(即增大输出电阻)的应引入电流负反馈;
- 从信号转换关系上看,输出电压是输入电压受控源的为电压串联负反馈,输出电压是输入电流受控源的为电压并联负反馈,输出电流是输入电压受控源的为电流串联负反馈,输出电流是输入电流受控源的为电流并联负反馈;当$(1+A F) >>1$时,它们的转换系数均约为$1/F$。
== 理想运放组成的基本运算电路
=== 概述
==== 运算电路中运放工作在线性区
=== 比例运算电路
==== 反相输入
#figure(
image("pic/2024-06-04-08-19-09.png", width: 50%),
numbering: none
)
$
i_N = i_P = 0\
u_P = u_I = 0
$
在节点N处
$
i_F = i_R = u_1/R
$
则有
$
u_O = - i_F R_f = - R_f / R u_1 \
A_u = - R_f / R
$
- 共模输入为0
可以用T形反馈网络实现
#figure(
image("pic/2024-06-24-16-18-57.png", width: 80%),
numbering: none,
)
==== 同相输入
#figure(
image("pic/2024-06-04-08-27-52.png", width: 50%),
numbering: none
)
电压串联负反馈。
$
u_N = u_P = u_I\
i_F = i_R = 0\
i_R_f = i_R = u_1 / R\
$
从而:
$
u_O = i_R(R_f + R) = (1 + R_f / R) u_1\
A_u = 1 + R_f / R
$
- 输入电阻为无穷大。
- $R' = R parallel R_f$
- 共模输入为$u_I$,这就要求共模抑制比$K_"CMR"$足够大。
同相输入比例运算电路的特例:*电压跟随器*
#figure(
image("pic/2024-06-04-08-34-45.png", width: 80%),
numbering: none
)
=== 加减运算电路
==== 反相求和
#figure(
image("pic/2024-06-04-08-35-30.png", width: 50%),
numbering: none
)
$
u_O = - R_f / R_1 u_1 - R_f / R_2 u_2 - R_f / R_3 u_3\
$
==== 同相求和
#figure(
image("pic/2024-06-04-09-10-04.png", width: 80%),
numbering: none
)
==== 加减运算
#figure(
image("pic/2024-06-04-09-13-12.png", width: 80%),
numbering: none
)
电压并联&串联负反馈。
- 共模:$(u_(I 1) + u_(I 2))/2$
由于负反馈之后的输出电阻极小,可以等价于电压源,这时候可以直接进行级联。
== D-A转换器
#figure(
image("pic/2024-06-25-14-26-57.png", width: 80%),
numbering: none,
)
=== 权电阻网络DAC
#figure(
image("pic/2024-06-25-14-27-52.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-29-22.png", width: 80%),
numbering: none,
)
=== 倒T型电阻网络DAC
#figure(
image("pic/2024-06-25-14-30-04.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-30-38.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-31-57.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-36-30.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-38-45.png", width: 80%),
numbering: none,
)
=== 具有双极性输出的DAC
#figure(
image("pic/2024-06-25-14-39-45.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-50-20.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-51-16.png", width: 80%),
numbering: none,
)
=== DAC的转换精度与速度
#figure(
image("pic/2024-06-25-14-52-27.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-52-53.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-53-18.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-14-54-04.png", width: 80%),
numbering: none,
)
#pagebreak()
= 信号的运算和处理
== 集成运放组成的运算电路
=== 对数运算电路和指数运算电路
==== 对数运算
#figure(
image("pic/2024-06-06-08-14-25.png", width: 80%),
numbering: none
)
如果想对$-I_s$进行对数运算,可以将管子换成NPN型或者跟一个方向的跟随器。
==== 指数运算
#figure(
image("pic/2024-06-06-08-15-39.png", width: 80%),
numbering: none
)
==== 乘法、除法运算电路
#figure(
image("pic/2024-06-06-08-23-01.png", width: 80%),
numbering: none
)
=== 实现逆运算的方法
#figure(
image("pic/2024-06-25-16-38-02.png", width: 80%),
numbering: none,
)
== 理想运放组成的电压比较器
=== 概述
1. 电压比较器的功能:比较电压的大小。
输入电压是模拟信号;输出电压表示比较的结果,只有高电平和低电平两种情况,为二值信号。使输出产生跃变的输入电压称为阈值电压。广泛用于各种报警电路。
2. 电压比较器的描述方法 :电压传输特性 $u_O = f(u_I)$
*电压传输特性的三个要素:*
- 输出高电平$U_"OH"$和输出低电平$U_"OL"$
- 阈值电压$U_T$
- 输入电压过阈值电压时输出电压跃变的方向
3. 几种常用的电压比较器
- 单限比较器:只有一个阈值电压
- 滞回比较器:具有滞回特性。输入电压的变化方向不同,阈值电压也不同,但输入电压单调变化使输出电压只跃变一次。
- 窗口比较器:有两个阈值电压,输入电压单调变化时输出电压跃变两次。
#figure(
image("pic/2024-06-06-08-33-35.png", width: 80%),
numbering: none
)
4. 电压比较器中集成运放工作在非线性区
#figure(
image("pic/2024-06-06-08-34-26.png", width: 80%),
numbering: none
)
=== 单限比较器
==== 过零比较器
#figure(
image("pic/2024-06-06-08-36-44.png", width: 80%),
numbering: none
)
二极管:限幅,防止烧坏晶体管。稳压管——反向击穿电压稳定。
==== 一般单限比较器
#figure(
image("pic/2024-06-06-08-38-28.png", width: 80%),
numbering: none
)
将$U_"REF"$接到上面是为了不引入共模输入。
=== 滞回比较器
#figure(
image("pic/2024-06-06-08-41-34.png", width: 80%),
numbering: none
)
#figure(
image("pic/2024-06-06-08-43-20.png", width: 80%),
numbering: none
)
1. 若要电压传输特性曲线左右移动,将接地改成$U_"REF"$
#figure(
image("pic/2024-06-06-08-50-37.png", width: 80%),
numbering: none
)
2. 若要电压传输特性曲线上下移动,加稳压管
3. 若要改变输入电压过阈值电压时输出电压的跃变方向
#figure(
image("pic/2024-06-06-08-50-54.png", width: 80%),
numbering: none
)
=== 窗口比较器
#figure(
image("pic/2024-06-06-08-51-45.png", width: 80%),
numbering: none
)
== A/D转换器
=== A/D转换器的基本原理
1. 采样定理
2. 量化与编码
- 量化:将取样电压表示为最小数量单位(Δ)的整数倍
- 编码:将量化的结果用代码表示出来(二进制,二-十进制)
- 量化误差:当采样电压不能被Δ整除时,将引入量化误差
#figure(
image("pic/2024-06-25-15-37-04.png", width: 80%),
numbering: none,
)
=== 直接ADC
#figure(
image("pic/2024-06-25-15-38-36.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-15-42-07.png", width: 80%),
numbering: none,
)
- 快,CP触发信号到达到输出稳定建立只需几十ns
- 精度,受参考电压、分压网络等因素影响
- 有存储器,可以没有S/H电路
- 电路规模,n位需要2n-1比较器,触发器
=== 采样保持电路(S/H电路 Sample-Hold)
#figure(
image("pic/2024-06-25-15-46-45.png", width: 80%),
numbering: none,
)
=== 反馈比较型ADC
==== 计数型
基本原理:取一个“D”加到DAC上,得到模拟输出电压,将该值与输入电压比较,如两者不等,则调整D的大小,到相等为止,则D为所求值。
#figure(
image("pic/2024-06-25-15-51-43.png", width: 80%),
numbering: none,
)
==== 逐次逼近型
#figure(
image("pic/2024-06-25-15-53-19.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-15-53-56.png", width: 80%),
numbering: none,
)
=== 间接ADC
==== 双积分型(V-T变换型)
先V转换成与之成正比的时间宽度信号,然后在这个时间内用固定频率脉冲计数
#figure(
image("pic/2024-06-25-16-09-52.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-10-23.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-10-43.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-11-11.png", width: 80%),
numbering: none,
)
==== V-F变换型
#figure(
image("pic/2024-06-25-16-11-29.png", width: 80%),
numbering: none,
)
=== ADC的速度与精度
一、速度:取决于电路结构类型
- 并联比较型:$<1$uS
- 逐次逼近型:几~100uS/次
- 双积分型:几十mS/次
二、转换精度:
- 分辨率 — 位数
- 转换误差 — 实际电路
== 模拟乘法器及其在运算电路中的应用
=== 模拟乘法器的基本原理
#figure(
image("pic/2024-06-25-16-30-56.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-31-57.png", width: 80%),
numbering: none,
)
=== 在运算电路中的基本应用
#figure(
image("pic/2024-06-25-16-33-19.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-36-44.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-42-47.png", width: 80%),
numbering: none,
)
== 有源滤波电路
运算电路与有源滤波器的比较
- 相同之处
- 电路中均引入深度负反馈,因而集成运放均工作在线性区。
- 均具有“虚短”和“虚断”的特点,均可用节点电流法求解电路。
- 不同之处
- 运算电路研究的是时域问题,有源滤波电路研究的是频域问题;测试时,前者是在输入信号频率不变或直流信号下测量输出电压与输入电压有效值或幅值的关系,后者是在输入电压幅值不变的情况下测量输出电压幅值与输入电压频率的关系。
- 运算电路用运算关系式描述输出电压与输入电压的关系,有源滤波器用电压放大倍数的幅频特性描述滤波特性。
=== 概述
#figure(
image("pic/2024-06-25-16-50-00.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-50-30.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-50-49.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-58-02.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-16-59-50.png", width: 80%),
numbering: none,
)
=== 低通滤波器
==== 一阶低通滤波器
#figure(
image("pic/2024-06-25-17-09-27.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-17-46-41.png", width: 80%),
numbering: none,
)
==== 二阶低通滤波器
#figure(
image("pic/2024-06-25-17-53-18.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-17-52-03.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-06-25-17-53-58.png", width: 80%),
numbering: none,
)
=== 高通、带通、带阻有源滤波器
#figure(
image("pic/2024-06-25-17-54-31.png", width: 80%),
numbering: none,
) |
|
https://github.com/rose-pine/typst | https://raw.githubusercontent.com/rose-pine/typst/main/src/themes/rose-pine-dawn.typ | typst | MIT License | #let rose-pine-dawn = (
base : rgb("#faf4ed"),
surface : rgb("#fffaf3"),
overlay : rgb("#f2e9e1"),
muted : rgb("#9893a5"),
subtle : rgb("#797593"),
text : rgb("#575279"),
love : rgb("#b4637a"),
gold : rgb("#ea9d34"),
rose : rgb("#d7827e"),
pine : rgb("#286983"),
foam : rgb("#56949f"),
iris : rgb("#907aa9"),
highlight : (
low : rgb("#f4ede8"),
med : rgb("#dfdad9"),
high : rgb("#cecacd"),
),
codeThemePath: "themes/rose-pine-dawn.tmTheme",
)
#let variant = rose-pine-dawn
|
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/drum_application.typ | typst | #import "lib.typ": *
= The Air Drumming Application (DrumPy) <drum-application>
The Air Drumming application is a demo application that showcases the use of on-device body pose estimation.
#footnote[
DrumPy is the official application name, referring to the main technology, Python, with which it is made.
]
The application uses the MediaPipe library to estimate the 3D pose of a person in real-time. The estimated pose is then used to detect drumming gestures and generate drum sounds. It is a fun and interactive way to explore the capabilities of body pose estimation.
The following section describes the key components of the application without going into too much detail. For a more in-depth explanation, please refer to the source code and documentation.
#footnote[
The application and source code are publicly available on GitHub: #link("https://github.com/Mouwrice/DrumPy")[Mouwrice/DrumPy #link-icon]. Note that this application is as much part of this thesis as the measurements and results presented in the previous sections, and should be considered as such.
]
#figure(
caption: [The Air Drumming application in action.],
placement: auto
)[
#image("images/drumpy_overview.png")
] <drumpy-overview>
The application is designed to be easy to use and understand, with a simple command-line interface and graphical user interface (@drumpy-overview). The user can start the application by simply launching the executable or from the command line to set some options such as which camera should be used, which model should be used etc. The application captures video frames from the camera, estimates the body pose of the person in the frame, and generates drum sounds based on the detected gestures. The user can play the drums by moving their hands and arms in the air, as if they were playing a real drum set. The feet are also tracked to detect the kick drum pedal. The application provides visual feedback by showing the estimated pose on the screen.
One feature of the application is velocity-based volume control. The volume of the drum sounds is controlled by the velocity of the drumming gestures. The harder the user hits the drums, the louder the drum sounds will be. This feature adds a level of realism to the drumming experience and makes it more engaging for the user.
When launching the application, a calibration phase is initiated. During this phase, the user is asked to perform a series of drumming gestures to calibrate the position of specific drum elements such as the snare drum, hi-hat, and cymbals. This calibration step is necessary to map the detected gestures to the correct drum sounds. These steps are outputted to the user in a console that is displayed on the screen. For example, the first element to be calibrated is the `Snare Drum`, the user should then repeatedly hit the snare drum at the position where they want the snare drum to be. The application will then use this information to calibrate the snare drum position. After a minimum of 10 successful hits and the positions of these hits are consistent, the calibration is considered successful, and the next element is calibrated. This process is repeated for all drum elements. Every calibration step along with information about the detected hit is outputted to the user in the console as shown in the example below, @calibration-console-output.
For more usage information along with an installation guide, please refer to the README file in the source code repository.
#footnote[
#link("https://github.com/Mouwrice/DrumPy?tab=readme-ov-file#installation")[https://github.com/Mouwrice/DrumPy?tab=readme-ov-file#installation #link-icon]
]
#figure(
placement: none,
caption: [Console output of the calibration process.],
)[
```console
Snare Drum calibration start
Calibrating Snare Drum
Hit count: 0
Volume: 1.000
Left Wrist: Snare Drum
Distance: 0.000
Velocity: -0.867
Position: [-0.128, 0.099, -0.827]
Calibrating Snare Drum
Hit count: 1
Volume: 1.000
Left Wrist: Snare Drum
Distance: 0.006
Velocity: -1.056
Position: [-0.148, 0.110, -0.824]
Calibrating Snare Drum
Hit count: 2
Volume: 1.000
Left Wrist: Snare Drum
Distance: 0.015
Velocity: -1.101
Position: [-0.188, 0.126, -0.830]
```
] <calibration-console-output>
== Technologies
The Air Drumming application is entirely written in Python and uses the following libraries:
- MediaPipe: For on-device body pose estimation.
- Pygame: For the audio and graphical user interface as well as capturing video frames from the camera.
- OpenCV: A library used to read video frames from a file.
- Click: For providing a simple and consistent command-line interface.
The application has been tested on both Linux (Arch Linux) and Windows 11. It should work on other platforms as well, but this has not been tested. Note that unfortunately, GPU support is not available for the MediaPipe library on Windows, so the application will run on the CPU only. This may result in lower performance compared to running the application on a Linux machine with GPU support and a dedicated GPU.
With the help of Nuitka,
#footnote[
Nuitka is a Python compiler that can compile Python code into standalone executables.
#link("https://nuitka.net/")[https://nuitka.net/ #link-icon]
]
the application can be compiled into a standalone executable that can be run on any system without the need to install Python or any of the required libraries. This makes it easy to distribute the application to users who do not have Python installed on their system. The compiled executable is available in the GitHub repository for easy download and use. Unfortunately, the compiled executable is only available for Windows currently, as the binary for Linux did not work as expected.
The code repository has been automated with GitHub Actions to automatically build and release the compiled executable for Windows whenever a new release is created. This makes it easy to keep the compiled executable up to date with the latest changes in the codebase.
== Gesture detection
The application uses the estimated 3D pose of the person to detect drumming gestures. For the demo application, the only drumming gestures detected are downward movements to hit the drums. After the hit detection, the drum element that is hit is determined by the position of the marker where a hit has been detected. The drum element closest to the marker is considered to be the drum element that has been hit. The velocity of the hit is calculated based on the speed of the downward movement. The harder the user hits the drums, the louder the drum sounds will be. The velocity controls the volume of the drum sounds, as mentioned earlier.
From the measurement results, we know that the depth values are not reliable and therefore are not used in the hit detection and drum positions. This means that the entire air drumming application works at a 2D level, it does not make use of any depth information. This is a limitation of the application but has not proved to be a problem in practice as most drumming gestures are made in the same plane.
From the measurements, we also know that `WorldLandmarks` are less reliable than the regular `Landmarks`.
For a more reliable hit detection, the application uses the regular `Landmarks` to detect the drumming gestures and to store the positions of the drum elements. Regular `Landmarks` have coordinates relative to the image frame, while `WorldLandmarks` have coordinates relative to the detected hip midpoint. If the `WorldLandmarks` are used, the drum elements would move with the user, which is not desirable. The drum elements should be fixed in space, so the regular `Landmarks` are used instead.
=== Hit detection
The hit detection is based on the observation that a downward movement is made when hitting a drum, followed by a slight upward movement. A downward movement is defined as having a consecutive series of positions where the vertical position is decreasing. An upward movement is defined as having a consecutive series of positions where the vertical position is increasing. At first, this might seem a bit counterintuitive, as one would expect the hit to be detected when the marker reaches the position of the drum element, just as in real life. In real life, the drum makes a sound when the drumstick hits the drum. However, the application is meant for air drumming, where there is no physical drum to hit. If we were to detect the hit when the marker reaches the position of the drum element, a hit might be detected when the user is still moving their hand downwards to hit the drum. This would reduce the immersion and realism. Instead, our method tries to find the point where the user expects the drum to be hit, not when the drum would actually be hit in real life. This is why the hit detection is based on the vertical trend of the marker and not the actual position of the marker.
Consider the following example vertical trajectory of a marker, @vertical-trajectory-example. The hit detection algorithm looks for a downward movement followed by an upward movement. Or in other words, it looks for a peak or breakpoint in the vertical trajectory. When such a peak is detected, a hit is registered.
It does so by keeping a memory of a certain number of previous positions and calculating the trend of the vertical position. Given a range of positions, a downward trend is detected when the average decrease in vertical position is greater than a certain threshold. An upward trend is detected when the average increase in vertical position is greater than a certain threshold. This allows to tweak the sensitivity of the hit detection algorithm. For example, a higher threshold would require a more pronounced downward movement to be detected as a hit. The threshold can also be lowered to allow for more subtle movements to be detected as hits. This is the case for the hit detection of the feet. The feet are tracked to detect the kick drum pedal. When using a pedal, the user might not immediately lift their foot after hitting the pedal. Setting the upward threshold to a lower value allows detecting the hit even when there is no real upward movement.
The upward threshold is even set to a negative value, but not as low as the downward threshold. Now a foot induced hit can even be detected when the foot is still slightly moving downwards after the hit.
#figure(caption: [Example vertical trajectory of a marker. Every dot represents a given position at a given time. The horizontal axis is time, the vertical axis is position.], placement: auto)[
#image("images/vertical_trajectory_example.svg")
] <vertical-trajectory-example>
Another important aspect that affects the hit detection is the notion of the current position.
When the algorithm receives the position of marker $F$ from the example (@vertical-trajectory-example), it has no way of knowing that this point $F$ is the "hit point". It would need to be able to look ahead. Of course, this is not possible, this is why the current position is defined as being some time in the past. For example, if we take the current position to be the position of the marker 2 frames ago, we have the artificial ability of looking ahead 2 frames to detect if an upward trend follows the current position. Note that there is a tradeoff between the current position and the number of frames used to detect the upward trend. The more frames are used to detect the trend, the more accurate the hit detection will be, but the less responsive it will be. This is because the hit detection will be delayed by the number of frames used to detect the upward trend. The current position is a compromise between accuracy and responsiveness.
=== Finding the nearest drum element
Every element of the drum set has a position which is set during the calibration fase. During the calibration any detected hit will result in the position of the element to be updated and the calibrated drum element to play its sound.
After a hit is registered, a corresponding drum element needs to be found. The application calculates the distance between the hit position and the position of each drum element. The drum element closest to the hit position is considered to be the drum element that has been hit. This is a simple way to determine which drum element has been hit and works well in practice. The distance is calculated using the Euclidean distance formula, which calculates the distance between two points in 2D space (the location of the hit and the location of the drum element).
There is also a threshold distance that is used to determine if a hit is close enough to a drum element to be considered a hit on that drum element. If the distance between the hit position and the drum element is less than the threshold distance, the hit is considered to be on that drum element. This threshold distance can be adjusted to make the hit detection more or less sensitive. A lower threshold distance will require the hit to be closer to the drum element to be considered a hit, while a higher threshold distance allows hits that are further away to be considered hits on the drum element. This can be useful to fine-tune the hit detection to the user's preferences and playing style. It would be unrealistic if the user would trigger a drum sound when hitting the air far away from the drum element. Setting the threshold too low, however, might result in missed hits. Especially when the threshold gets close to the noise level of the measurements, the hit detection might become unreliable.
=== Latency
In this section, we will discuss the latency of the application. Latency is the time it takes for a user to perform an action and see the result of that action. In the context of the Air Drumming application, latency is the time it takes for the user to hit a drum and hear the drum sound. Latency is an important factor in interactive applications, as high latency can reduce the responsiveness of the application and make it less engaging for the user.
The latency of the Air Drumming application is affected by several factors:
- The frame rate of the camera: The frame rate of the camera determines how often the application receives new video frames. A higher frame rate allows the application to process new frames more frequently, reducing the latency of the application. The frame rate of the camera is set to 30 frames per second in the application, which is a common frame rate for video capture. Especially, most webcams support this frame rate.
- The processing time of the body pose estimation model: The body pose estimation model processes each video frame to estimate the 3D pose of the person. The processing time of the model depends on the complexity of the model and the hardware it is running on. A more complex model or slower hardware will increase the processing time of the model, increasing the latency of the application. The MediaPipe Pose model used in the application is optimized for real-time performance on mobile devices and runs efficiently on most modern hardware.
- The hit detection algorithm: The hit detection algorithm processes the estimated 2D pose of the person to detect drumming gestures. The algorithm analyses the trajectory of the marker to detect downward and upward movements, which indicate a hit on a drum element. The hit detection algorithm is designed to be fast and efficient, yet it requires some frame buffer to detect the upward trend. This buffer introduces a delay in the hit detection, which affects the latency of the application. The size of the frame buffer can be adjusted to balance accuracy and responsiveness.
So the first limitation is the frame rate of the camera. The application has the frame rate set at 30 fps. This translates to a video frame every 33,33... ms. The application processes the video frame and estimates the pose of the person in the frame. This processing time is the second limitation. However, during the measurements, it was found that the processing time of the pose estimation model is very low. The pose estimation model runs at around 30 fps on a CPU. This means that the pose estimation model processes a frame in less than 33,33... ms. The hit detection algorithm is the third limitation. The hit detection algorithm requires a frame buffer to detect the upward trend. This buffer introduces a delay in the hit detection, which affects the latency of the application. The size of the frame buffer can be adjusted to balance accuracy and responsiveness. The buffer is set to 2 frames, which means that the hit detection is delayed by 2 frames. This results in a latency of 66,66... ms. Now we can calculate the maximum latency of the application.
Now we can calculate the maximum latency. For the pose estimation model to process the frame, suppose the worst-case scenario, but still achieving 30 fps. The processing time of the model is then 33,33... ms. Finally, the hit detection algorithm introduces a delay of 2 frames, resulting in a delay of 66,66... ms. This results in a maximum latency of 100 ms. This maximum latency is a tenth of a second and might be noticeable by the user. However, if the inference time of the model is lower, the latency will be lower as well. The latency can be further reduced by increasing the frame rate of the camera or optimizing the hit detection algorithm. The latency of the application is acceptable for most users and does not significantly affect the user experience.
== Notion of Origin and Coordinate System
This section briefly discusses the differences in the notion of origin and coordinate system between the MediaPipe library and typical motion capture systems. With the Qualisys motion capture system, the origin is calibrated at one specific point in the room. The origin is fixed and does not move during the capture session. The origin is used as a reference point to calculate the position of the markers in 3D space. The position of the markers is calculated relative to the origin, which is why the origin is an essential part of the motion capture system. The origin and coordinate system are a bit different requiring a different approach in the application.
In the MediaPipe library, the origin depends on the marker type used. With the `Landmark` marker type, the entire coordinate system is in the image frame. The origin point is one of the corners of the frame, and every other point is relative to this origin in the frame. This has major implications on the perceived size of motion due to perspective. The actual real-world distance between markers is inversely proportional to the distance of the markers to the camera. A small movement close to the camera that covers the entire image frame will be interpreted as much larger than performing a large movement far away from the camera. When the size of motion is used in the application, this should be considered. In that case, it is best to use a fixed distance from the camera to the user. This way, the size of the motion is constant, and the application can be used in a more predictable way.
The `WorldLandmark` marker type has the origin at the detected hip midpoint. This means that the position of the markers is calculated relative to the hip midpoint. This is very different to the fixed origins from the Qualisys motion capture system and the `Landmark` markers. The position of the markers is not fixed in space, but moves with the user. In that case, all positions are relative to the user, regardless of the position of the user in the room. This is not desirable for the application, as the drum elements should be fixed in space. This is why the `Landmark` marker type is used in the application, as the positions of the drum elements are fixed in space and do not move with the user.
== Limitations
There are two limitations to the application. A first one is due to the jitter caused by the pose estimation model. When crossing arms, a common thing to do when drumming, the pose estimation model produces jitter in the estimated pose. For example, when one arm is hitting the drums and occluding the other arm, the pose estimation model can get confused and think the other arm is also moving. This produces jitter in the estimated pose, which can affect the hit detection. The hit detection algorithm relies on the trajectory of the marker to detect drumming gestures. If the estimated pose is jittery, the trajectory of the marker will be noisy, which can lead to false positives or missed hits. This is a limitation of the pose estimation model and cannot be easily solved. The jitter can be reduced by using a more robust pose estimation model or filtering the estimated pose, but this comes at the cost of increased latency and reduced responsiveness.
A second limitation is in the hit detection itself. When performing a hit, this is detected by the hit detection algorithm. However, it is possible that in the next frame, that same hit is detected again due to the trajectory still having the downward and upward trend in the next frame. This can result in multiple hits being detected for a single hit. This is a limitation of the hit detection algorithm and can be solved by introducing a cooldown period after a hit has been detected. During this cooldown period, no hits are registered, preventing multiple hits from being detected for a single hit. This cooldown period can be adjusted to balance accuracy and responsiveness. A longer cooldown period will prevent multiple hits from being detected, but will also introduce more latency in the hit detection. A shorter cooldown period will reduce the latency, but might result in multiple hits being detected for a single hit. This is a tradeoff that needs to be considered when fine-tuning the hit detection algorithm. Currently, the cooldown period is set to 5 frames at 30 fps, which results in a cooldown period of 166,66... ms. This unfortunately limits the number of hits that can be detected in a short amount of time. Rapid drumming might result in missed hits due to the cooldown period. This is a limitation of the hit detection algorithm and can be improved by adjusting the cooldown period or introducing a more sophisticated hit detection algorithm.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-04.typ | typst | Other | // Test set and show in code blocks.
#show heading: it => {
set text(red)
show "ding": [🛎]
it.body
}
= Heading
|
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/build-scoring/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Build: Scoring Triballs",
type: "build",
date: datetime(year: 2023, month: 9, day: 9),
author: "<NAME>",
witness: "Violet Ridge",
)
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
We used the following process to build our wedges.
1. Cut 2 lengths of C-channel to 2 holes long.
2. Attached aluminum plate to the C-channel.
3. Mounted the plate to the drivetrain with screws.
4. Cut 2 lengths of C-channel to 20 holes long.
5. Put spacers on the inside of the 20 hole long C-channel
6. Attached the 20 hole long C-channel to the 2 hole long C-channel on the
drivetrain with a screw joint so that it can rotate freely.
7. Attached the end of the pistons to the 20 hole long C-channel with another screw
joint and spacers.
8. Mounted the other end of the piston to the drivetrain.
],
[
#image("./iso.jpg")
#image("./top.jpg")
],
)
#admonition(type: "build")[
The wings are finally complete!
]
|
https://github.com/liuguangxi/fractusist | https://raw.githubusercontent.com/liuguangxi/fractusist/main/tests/test-koch-snowflake.typ | typst | MIT License | #set document(date: none)
#import "/src/lib.typ": *
#set page(margin: 1cm)
= n = 1
#align(center)[
#koch-snowflake(1, step-size: 40)
]
= n = 2
#align(center)[
#koch-snowflake(2, step-size: 20, fill-style: gray, stroke-style: none)
]
= n = 3
#align(center)[
#koch-snowflake(3, step-size: 8, fill-style: silver, stroke-style: orange + 3pt)
]
#pagebreak(weak: true)
= n = 4
#align(center)[
#koch-snowflake(4, step-size: 5, fill-style: gradient.radial((orange, 0%), (silver, 100%), focal-center: (30%, 30%)), stroke-style: stroke(paint: gradient.linear(..color.map.crest, angle: 45deg), thickness: 2pt))
]
#pagebreak(weak: true)
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/zalmy/Z083.typ | typst | Aké milé sú tvoje príbytky, Pane zástupov; \* túži a zmiera moja duša po nádvoriach Pánových.
Moje srdce i moje telo \* vznášajú sa k Bohu živému.
Veď aj vrabec si nájde príbytok \* a lastovička hniezdo, kde vkladá svoje mláďatá:
tvoje oltáre, Pane zástupov, \* môj kráľ a môj Boh.
Blažení tí, čo bývajú v tvojom dome \* a bez prestania ťa velebia.
Blažený človek, ktorému ty pomáhaš, \* keď sa chystá na svätú púť.
Až pôjdu vyprahnutým údolím, premenia ho na prameň, \* lebo ranný dážď ho odeje požehnaním.
Stúpajú a síl im stále pribúda, \* až na Sione uvidia Boha najvyššieho.
Pane, Bože zástupov, čuj moju modlitbu, \* vypočuj ma, Bože Jakubov.
Bože, náš ochranca, pohliadni \* a pozri na tvár svojho pomazaného.
Jeden deň v tvojich nádvoriach \* je lepší než iných tisíce.
Radšej chcem stáť na prahu domu svojho Boha \* ako prebývať v stanoch hriešnikov.
Lebo Pán, Boh, je slnko a štít, milosť a slávu udeľuje Pán; \* neodoprie dobro tým, čo kráčajú v nevinnosti.
Pane zástupov, \* blažený človek, čo sa spolieha na teba. |
|
https://github.com/jneug/typst-typopts | https://raw.githubusercontent.com/jneug/typst-typopts/main/states.typ | typst | MIT License | /********************************\
| Some convenience functions |
| for handling states |
\********************************/
// identity function
#let ident(e) = { return e }
/**
* Creates a new state with an initial value.
*
* The initial value can't be `none`.
*
* - name (str): name of the state variable
* - value (any but `none`): initial value
*/
#let new( name, value ) = state(name).update(value)
/**
* Creates a new state with an empty array as inital value.
*
* - name (str): name of the state variable
*/
#let new-arr( name ) = {
new(name, ())
}
/**
* Creates a new state with an empty dict as inital value.
*
* - name (str): name of the state variable
*/
#let new-dict( name ) = {
new(name, (:))
}
/**
* Removes a state by setting its value to `none`.
*
* - name (str): name of the state variable
*/
#let del( name ) = update(name, v => none)
/**
* Updates the value of a state.
*
* Value may be an update function of one argument
* or a new value (see `state.update()`). Setting the
* state to `none` is the same as calling `del()`.
*
* - name (str): name of the state variable
* - value (any | any => any): new value
*/
#let update( name, value ) = {
state(name).update(value)
}
/**
* Pushes a new value into an array stored in a state.
*
* If the state is empty, a new array is created.
* Fails, if the state currently does not hold an array.
*
* - name (str): name of the state variable
* - value (any): value to push
*/
#let enq( name, value ) = {
state(name).update(arr => {
if arr == none {
arr = (value,)
} else {
arr.push(value)
}
arr
})
}
/**
* Removes the last value from an array stored in a state.
*
* Fails, if the state currently does not hold an array or
* the array is empty.
*
* - name (str): name of the state variable
* - func (any => any, default: ident): function to pass the value to
*/
#let deq( name, func:ident ) = {
state(name).update(arr => {
let _ = func(arr.pop())
arr
})
}
/**
*
*/
#let ins( name, key, value, func:ident ) = {
state(name).update(arr => {
arr.insert(key, value)
arr
})
}
/**
*
*/
#let rem( name, key ) = {
state(name).update(arr => {
let _ = arr.remove(key)
arr
})
}
// #let insertDict( name, key, value ) = {
// state(name).update((dic) => {
// dic.insert(key, value)
// dic
// })
// }
// #let removeDict( name, key ) = {
// state(name).update((dic) => {
// let _ = dic.remove(key)
// dic
// })
// }
/**
* Get value of a state variable.
*
* Get the value either at the specified location or
* the final value.
*
* - name (str): name of the state variable
* - loc (location): location from where to get the value
* - func (any => any, default: ident): function to send the value to
* - final (boolean, default: false): retrieve the final value
*/
#let __get( name, loc, func:ident, final:false, key:none, default:none ) = {
let value = none
if final {
value = state(name).final(loc)
} else {
value = state(name).at(loc)
}
if value == none { value = default }
else if key != none { value = value.at(key, default:default) }
return func(value)
}
#let get( name, func, final:false, key:none, default:none ) = {
locate(loc => {
__get(name, loc, func:func, final:final, key:key, default:default)
})
}
#let get-final( name, func, key:none, default:none ) = {
locate(loc => {
__get(name, loc, func:func, final:true, key:key, default:default)
})
}
#let get-at( name, loc, func:ident, final:false, key:none, default:none ) = {
__get(name, loc, func:func, final:final, key:key, default:default)
}
#let get-final-at( name, loc, func:ident, key:none, default:none ) = {
__get(name, loc, func:func, final:true, key:key, default:default)
}
// #let getArr( name, i, func:ident, final:false ) = {
// locate(loc => {
// __get(name, loc, func:(arr) => {
// func(arr.at(i))
// }, final:final)
// })
// }
// #let getArrAt( name, i, loc, func:ident, final:false ) = {
// __get(name, loc, func:(arr) => {
// func(arr.at(i))
// }, final:final)
// }
#let get-first( name, func:ident, final:false ) = {
locate(loc => {
__get(name, loc, func:(arr) => {
func(arr.first())
}, final:final)
})
}
// #let getFirstAt( name, i, loc, func:ident, final:false ) = {
// __get(name, loc, func:(arr) => {
// func(arr.first())
// }, final:final)
// }
#let get-last( name, func:ident, final:false ) = {
locate(loc => {
__get(name, loc, func:(arr) => {
func(arr.last())
}, final:final)
})
}
// #let getLastAt( name, i, loc, func:ident, final:false ) = {
// __get(name, loc, func:(arr) => {
// func(arr.last())
// }, final:final)
// }
// #let getDict( name, key, func:ident, final:false ) = {
// locate(loc => {
// __get(name, loc, func: (dic) => {
// if dic != none {func(dic.at(key))}
// else {func(none)}
// }, final:final)
// })
// }
// #let getDictAt( name, key, loc, func:ident, final:false ) = {
// __get(name, loc, func: (dic) => {
// if dic != none {func(dic.at(key))}
// else {func(none)}
// }, final:final)
// }
// #let getDictFinal( name, key, func:ident ) = {
// locate(loc => {
// __get(name, loc, func: (dic) => {
// if dic != none {func(dic.at(key))}
// else {func(none)}
// }, final:true)
// })
// }
// #let getDictFinalAt( name, key, loc, func:ident ) = {
// __get(name, loc, func: (dic) => {
// if dic != none {func(dic.at(key))}
// else {func(none)}
// }, final:true)
// }
|
https://github.com/jultty/hello-typst | https://raw.githubusercontent.com/jultty/hello-typst/main/hello.typ | typst | #set document(
title: "Hello Typst",
author: "<NAME>",
date: auto,
keywords: ("typst", "typesetting"),
)
#set page(paper: "a6", margin: (x: 0.8cm, y: 1cm), fill: rgb("#fffddf"))
#set text(font: "", size: 10pt, lang: "en", fill: rgb("#222222"))
#set heading(numbering: "1.")
#set par(justify: true, leading: 0.7em,)
#set quote(block: true, quotes: true)
#set footnote.entry(gap: 1em, clearance: 1em)
#show link: underline
= Typst
Typst is a typesetting system that takes code in and outputs PDFs.
This file is an example of several features you can use in it.
== Math notation
The first example Typst shows you is for writing the
Fibonacci sequence's definition through its
recurrence relation $F_n = F_(n-1) + F_(n-2)$. That's inline math for you.
You can also do math on its own, centered paragraph:
$ F_n = round(1 / sqrt(5) phi.alt^n), quad
phi.alt = (1 + sqrt(5)) / 2 $
== Code blocks
Typst also supports code blocks. The code for the previous formula, for instance, was:
#block( fill: luma(230), inset: 8pt, radius: 4pt, breakable: false)[
```typst
$ F_n = round(1 / sqrt(5) phi.alt^n), quad
phi.alt = (1 + sqrt(5)) / 2 $
```]
== Code mode
You can define and use code logic for Typst to evaluate on compile:
#block( fill: luma(230), inset: 8pt, radius: 4pt, breakable: false)[
```typst
#let count = 8
#let nums = range(1, count + 1)
#let fib(n) = (
if n <= 2 { 1 }
else { fib(n - 1) + fib(n - 2) }
)
```]
#let count = 8
#let nums = range(1, count + 1)
#let fib(n) = (
if n <= 2 { 1 }
else { fib(n - 1) + fib(n - 2) }
)
Using the `#count` and `#nums` values just set, we can render the following table:
#align(center, table(
columns: count,
..nums.map(n => $F_#n$),
..nums.map(n => str(fib(n))),
))
== Formatting
This *bold text* is created using `*asterisks*`. _Italics_ are made using `_underlines_`.
- An unordered list
- with a few
- items uses hyphens
- for markers
+ This numbered list
+ uses instead
+ the ```typst +``` sign
+ for each item
== Images
Typst provides _functions_ invoked using the `#` character, which turns on "code mode". One of such functions is `#image`:
#block( fill: luma(230), inset: 8pt, radius: 4pt, breakable: false)[
```typst
#align(center + top)[
#image("assets/mech-pencil.svg", width: 5%)
]
```]
Width can be specified as a percentage, or as in `1cm` or `0.7in`.
The code above will produce this:
#align(center + top)[
#image("assets/mech-pencil.svg", width: 5%)
]
You can wrap an image in a `#figure` function to add a caption:
#figure(
image("assets/mech-pencil.svg", width: 5%),
caption: [
This cute icon representing a mechanical pencil is a public domain courtesy of #link("https://icooon-mono.com/")[ICOOON MONO]
]
)<mech-pencil>
Supported formats as of November 2023 are PNG, JPEG, GIF, and SVG.
#show "mechanical pencils": word => box[
#word
#box(image(
"assets/mech-pencil.svg",
height: 0.7em,
))
]
By using a `#show` instruction, I can have all mentions of
mechanical pencils rendered with the icon next to them.
In @mech-pencil, a label was assigned, which allows linked references to it such as this one. The number of the figure will be automatically resolved.
#pagebreak()
== Quotes
There is also a `#quote` function:
#quote(attribution: [#link("https://typst.app/docs/tutorial/writing-in-typst/")[Typst Docs, _Writing in typst_]])[
The caption consists of arbitrary markup. To give markup to
a function, we enclose it in square brackets. This construct
is called a content block.
]
== Footnotes
Speaking of quotes, footnotes append linked references at the end of the document.
#footnote[
#" "#link("https://typst.app/docs/reference/meta/footnote/")[Typst reference, _footnote_]
]<footnote-1>
You can use ```typst #" "``` or #link("https://typst.app/docs/reference/layout/h/")[horizontal spacing] to adjust the distance between the superscript number and the text.
#footnote([#" "Though I'd rather use a parameter in `set footnote.entry()`. Also, they are a bit hard to click.])<footnote-2>
They can also be labeled so you may reference them multiple times. This line uses the same reference as the first footnote.
#footnote(<footnote-1>)
== A math lorem
$ 1.62 theta +
sum_(i=0)^nabla R_n / "10p" arrow
p := vec(x_1, y_2, z_3) arrow " ?" $
|
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/src/quantum-circuit.typ | typst | MIT License | #import "utility.typ"
#import "verifications.typ"
#import "length-helpers.typ"
#import "decorations.typ": *
#let signum(x) = if x >= 0. { 1. } else { -1. }
/// Create a quantum circuit diagram. Children may be
/// - gates created by one of the many gate commands (@@gate(),
/// @@mqgate(), @@meter(), ...),
/// - `[\ ]` for creating a new wire/row,
/// - commands like @@setwire(), @@slice() or @@gategroup(),
/// - integers for creating cells filled with the current wire setting,
/// - lengths for creating space between rows or columns,
/// - plain content or strings to be placed on the wire, and
/// - @@lstick(), @@midstick() or @@rstick() for placement next to the wire.
///
///
/// - wire (stroke): Style for drawing the circuit wires. This can take anything
/// that is valid for the stroke of the builtin `line()` function.
/// - row-spacing (length): Spacing between rows.
/// - column-spacing (length): Spacing between columns.
/// - min-row-height (length): Minimum height of a row (e.g., when no
/// gates are given).
/// - min-column-width (length): Minimum width of a column.
/// - gate-padding (length): General padding setting including the inset for
/// gate boxes and the distance of @@lstick() and co. to the wire.
/// - equal-row-heights (boolean): If true, then all rows will have the same
/// height and the wires will have equal distances orienting on the
/// highest row.
/// - color (color): Foreground color, default for strokes, text, controls
/// etc. If you want to have dark-themed circuits, set this to white
/// for instance and update `wire` and `fill` accordingly.
/// - fill (color): Default fill color for gates.
/// - font-size (length): Default font size for text in the circuit.
/// - scale (ratio): Total scale factor applied to the entire
/// circuit without changing proportions
/// - baseline (length, content, str): Set the baseline for the circuit. If a
/// content or a string is given, the baseline will be adjusted auto-
/// matically to align with the center of it. One useful application is
/// `"="` so the circuit aligns with the equals symbol.
/// - circuit-padding (dictionary): Padding for the circuit (e.g., to accommodate
/// for annotations) in form of a dictionary with possible keys
/// `left`, `right`, `top` and `bottom`. Not all of those need to be
/// specified.
///
/// This setting basically just changes the size of the bounding box
/// for the circuit and can be used to increase it when labels or
/// annotations extend beyond the actual circuit.
/// - fill-wires (boolean): Whether to automatically fill up all wires until the end.
/// - ..children (any): Items, gates and circuit commands (see description).
#let quantum-circuit(
wire: .7pt + black,
row-spacing: 12pt,
column-spacing: 12pt,
min-row-height: 10pt,
min-column-width: 0pt,
gate-padding: .4em,
equal-row-heights: false,
color: black,
fill: white,
font-size: 10pt,
scale: 100%,
baseline: 0pt,
circuit-padding: .4em,
fill-wires: true,
..children
) = {
if children.pos().len() == 0 { return }
if children.named().len() > 0 {
panic("Unexpected named argument '" + children.named().keys().at(0) + "' for quantum-circuit()")
}
if type(wire) == color { wire += .7pt }
if type(wire) == length { wire += black }
set text(wire.paint, size: font-size)
set math.equation(numbering: none)
context {
// Parameter object to pass to draw-function containing current style info
let draw-params = (
wire: wire,
padding: measure(line(length: gate-padding)).width,
background: fill,
color: color,
x-gate-size: none,
multi: (wire-distance: 0pt)
)
draw-params.x-gate-size = layout.default-size-hint(gate($X$), draw-params)
let items = children.pos().map( x => {
if type(x) in (content, str) and x != [\ ] { return gate(x) }
return x
})
/////////// First part: Layout (and spacing) ///////////
let column-spacing = column-spacing.to-absolute()
let row-spacing = row-spacing.to-absolute()
let min-row-height = min-row-height.to-absolute()
let min-column-width = min-column-width.to-absolute()
// All these arrays are gonna be filled up in the loop over `items`
let matrix = ((),)
let row-gutter = (0pt,)
let single-qubit-gates = ()
let multi-qubit-gates = ()
let meta-instructions = ()
let auto-cell = (empty: true, size: (width: 0pt, height: 0pt), gutter: 0pt)
let default-wire-style = (
count: 1,
distance: 1pt,
stroke: wire
)
let wire-style = default-wire-style
let wire-instructions = ()
let (row, col) = (0, 0)
let prev-col = 0
let wire-ended = false
for item in items {
if item == [\ ] {
if fill-wires {
wire-instructions.push((row, prev-col, -1))
}
row += 1; col = 0; prev-col = 0
if row >= matrix.len() {
matrix.push(())
row-gutter.push(0pt)
}
wire-style = default-wire-style
wire-instructions.push(wire-style)
wire-ended = true
} else if utility.is-circuit-meta-instruction(item) {
if item.qc-instr == "setwire" {
wire-style.count = item.wire-count
wire-style.distance = utility.if-auto(item.wire-distance, wire-style.distance)
wire-style.stroke = utility.if-auto(utility.update-stroke(wire-style.stroke, item.stroke), wire-style.stroke)
wire-instructions.push(wire-style)
} else {
// Visual meta instructions are handled later
let (x, y) = (item.x, item.y)
if x == auto { x = col }
if y == auto { y = row }
meta-instructions.push((x: x, y: y, item: item))
}
} else if utility.is-circuit-drawable(item) {
let gate = item
let (x, y) = (gate.x, gate.y)
if x == auto {
x = col
if y == auto {
if col != prev-col {
wire-instructions.push((row, prev-col, col))
}
prev-col = col
col += 1
}
}
if y == auto { y = row }
if y >= matrix.len() { matrix += ((),) * (y - matrix.len() + 1) }
if x >= matrix.at(y).len() {
matrix.at(y) += (auto-cell,) * (x - matrix.at(y).len() + 1)
}
assert(matrix.at(y).at(x).empty, message: "Attempted to place a second gate at column " + str(x) + ", row " + str(y))
let size-hint = utility.get-size-hint(item, draw-params)
let gate-size = size-hint
if item.floating { size-hint.width = 0pt } // floating items don't take width in the layout
matrix.at(y).at(x) = (
size: size-hint,
gutter: 0pt,
box: item.box,
empty: gate.data == "placeholder"
)
let gate-info = (
gate: gate,
size: gate-size,
x: x,
y: y
)
if gate.multi != none { multi-qubit-gates.push(gate-info) }
else { single-qubit-gates.push(gate-info) }
wire-ended = false
} else if type(item) == int {
wire-instructions.push((row, prev-col, col + item - 1))
col += item
prev-col = col - 1
if col >= matrix.at(row).len() {
matrix.at(row) += (auto-cell,) * (col - matrix.at(row).len())
}
wire-ended = false
} else if type(item) == length {
if wire-ended {
row-gutter.at(row - 1) = calc.max(row-gutter.at(row - 1), item)
} else if col > 0 {
matrix.at(row).at(col - 1).gutter = calc.max(matrix.at(row).at(col - 1).gutter, item)
}
}
}
// finish up matrix
let num-rows = matrix.len()
let num-cols = calc.max(0, ..matrix.map(array.len))
if num-rows == 0 or num-cols == 0 { return none }
for i in range(num-rows) {
matrix.at(i) += (auto-cell,) * (num-cols - matrix.at(i).len())
}
row-gutter += (0pt,) * (matrix.len() - row-gutter.len())
if fill-wires {
wire-instructions.push((row, prev-col, -1)) // fill current wire
wire-instructions += range(row + 1, num-rows).map(row => (row, 0, -1)) // we may not have visited all wires due to manual placement. Fill all remaining wires.
}
let vertical-wires = ()
// Treat multi-qubit gates (and controlled gates)
// - extract and store all necessary vertical control wires
// - Apply same size-hints to all cells that a mqgate spans (without the control wire).
for gate in multi-qubit-gates {
let (x, y) = gate
let size = matrix.at(y).at(x).size
let multi = gate.gate.multi
if multi.target != none and multi.target != 0 {
verifications.verify-controlled-gate(gate.gate, x, y, num-rows, num-cols)
let diff = if multi.target > 0 {multi.num-qubits - 1} else {0}
vertical-wires.push((
x: x,
y: y + diff,
target: multi.target - diff,
wire-style: (count: multi.wire-count),
labels: multi.wire-label
))
}
let nq = multi.num-qubits
if nq == 1 { continue }
verifications.verify-mqgate(gate.gate, x, y, num-rows, num-cols)
for qubit in range(y, y + nq) {
matrix.at(qubit).at(x).size.width = size.width
}
let start = y
if multi.size-all-wires != none {
if not multi.size-all-wires {
start = calc.max(0, y + nq - 1)
}
for qubit in range(start, y + nq) {
matrix.at(qubit).at(x).size = size
}
}
}
let row-heights = matrix.map(row =>
calc.max(min-row-height, ..row.map(item => item.size.height)) + row-spacing
)
if equal-row-heights {
let max-row-height = calc.max(..row-heights)
row-heights = (max-row-height,) * row-heights.len()
}
let col-widths = range(num-cols).map(j =>
calc.max(min-column-width, ..range(num-rows).map(i => {
matrix.at(i).at(j).size.width
})) + column-spacing
)
let col-gutter = range(num-cols).map(j =>
calc.max(0pt, ..range(num-rows).map(i => {
matrix.at(i).at(j).gutter
}))
)
let center-x-coords = layout.compute-center-coords(col-widths, col-gutter).map(x => x - 0.5 * column-spacing)
let center-y-coords = layout.compute-center-coords(row-heights, row-gutter).map(x => x - 0.5 * row-spacing)
draw-params.center-y-coords = center-y-coords
let circuit-width = col-widths.sum() + col-gutter.slice(0, -1).sum(default: 0pt) - column-spacing
let circuit-height = row-heights.sum() + row-gutter.sum() - row-spacing
/////////// Second part: Generation ///////////
let bounds = (0pt, 0pt, circuit-width, circuit-height)
let circuit = block(
width: circuit-width, height: circuit-height, {
set align(top + left) // quantum-circuit could be called in a scope where these have been changed which would mess up everything
let layer-below-circuit
let layer-above-circuit
for (item, x, y) in meta-instructions {
let (the-content, decoration-bounds) = (none, none)
if item.qc-instr == "gategroup" {
verifications.verify-gategroup(item, x, y, num-rows, num-cols)
let (dy1, dy2) = layout.get-cell-coords(center-y-coords, row-heights, (y, y + item.wires - 1e-9))
let (dx1, dx2) = layout.get-cell-coords(center-x-coords, col-widths, (x, x + item.steps - 1e-9))
(the-content, decoration-bounds) = draw-functions.draw-gategroup(dx1, dx2, dy1, dy2, item, draw-params)
} else if item.qc-instr == "slice" {
verifications.verify-slice(item, x, y, num-rows, num-cols)
let end = if item.wires == 0 { row-heights.len() } else { y + item.wires }
let (dy1, dy2) = layout.get-cell-coords(center-y-coords, row-heights, (y, end))
let dx = layout.get-cell-coords(center-x-coords, col-widths, x)
(the-content, decoration-bounds) = draw-functions.draw-slice(dx, dy1, dy2, item, draw-params)
} else if item.qc-instr == "annotate" {
let rows = layout.get-cell-coords(center-y-coords, row-heights, item.rows)
let cols = layout.get-cell-coords(center-x-coords, col-widths, item.columns)
let annotation = (item.callback)(cols, rows)
verifications.verify-annotation-content(annotation)
if type(annotation) == dictionary {
(the-content, decoration-bounds) = layout.place-with-labels(
annotation.content,
dx: annotation.at("dx", default: 0pt),
dy: annotation.at("dy", default: 0pt),
draw-params: draw-params
)
} else if type(annotation) in (content, str) {
layer-below-circuit += place(annotation)
}
}
if decoration-bounds != none {
bounds = layout.update-bounds(bounds, decoration-bounds)
}
if item.at("z", default: "below") == "below" { layer-below-circuit += the-content }
else { layer-above-circuit += the-content }
}
layer-below-circuit
let get-gate-pos(x, y, size-hint) = {
let dx = center-x-coords.at(x)
let dy = center-y-coords.at(y)
let (width, height) = size-hint
let offset = size-hint.at("offset", default: auto)
if offset == auto { return (dx - width / 2, dy - height / 2) }
assert(type(offset) == dictionary, message: "Unexpected type `" + type(offset) + "` for parameter `offset`")
let offset-x = offset.at("x", default: auto)
let offset-y = offset.at("y", default: auto)
if offset-x == auto { dx -= width / 2}
else if type(offset-x) == length { dx -= offset-x }
if offset-y == auto { dy -= height / 2}
else if type(offset-y) == length { dy -= offset-y }
return (dx, dy)
}
let get-anchor-width(x, y) = {
if x == num-cols { return 0pt }
let el = matrix.at(y).at(x)
if "box" in el and not el.box { return 0pt }
return el.size.width
}
let get-anchor-height(x, y) = {
let el = matrix.at(y).at(x)
if "box" in el and not el.box { return 0pt }
return el.size.height
}
let wire-style = default-wire-style
for wire-piece in wire-instructions {
if type(wire-piece) == dictionary {
wire-style = wire-piece
} else {
if wire-style.count == 0 { continue }
let (row, start-x, end-x) = wire-piece
if end-x == -1 {
end-x = num-cols - 1
}
if start-x == end-x { continue }
let draw-subwire(x1, x2) = {
let dx1 = center-x-coords.at(x1)
let dx2 = center-x-coords.at(x2, default: circuit-width)
let dy = center-y-coords.at(row)
dx1 += get-anchor-width(x1, row) / 2
dx2 -= get-anchor-width(x2, row) / 2
draw-functions.draw-horizontal-wire(dx1, dx2, dy, wire-style.stroke, wire-style.count, wire-distance: wire-style.distance)
}
// Draw wire pieces and take care not to draw through gates.
for x in range(start-x + 1, end-x) {
let anchor-width = get-anchor-width(x, row)
if anchor-width == 0pt { continue } // no gate or `box: false` gate.
draw-subwire(start-x, x)
start-x = x
}
draw-subwire(start-x, end-x)
}
}
for (x, y, target, wire-style, labels) in vertical-wires {
let dx = center-x-coords.at(x)
let (dy1, dy2) = (center-y-coords.at(y), center-y-coords.at(y + target))
dy1 += get-anchor-height(x, y) / 2 * signum(target)
dy2 -= get-anchor-height(x, y + target) / 2 * signum(target)
if labels.len() == 0 {
draw-functions.draw-vertical-wire(
dy1, dy2, dx,
wire, wire-count: wire-style.count,
)
} else {
let (result, gate-bounds) = draw-functions.draw-vertical-wire-with-labels(
dy1, dy2, dx,
wire, wire-count: wire-style.count,
wire-labels: labels,
draw-params: draw-params
)
result
bounds = layout.update-bounds(bounds, gate-bounds)
}
}
for gate-info in single-qubit-gates {
let (gate, size, x, y) = gate-info
let (dx, dy) = get-gate-pos(x, y, size)
let content = utility.get-content(gate, draw-params)
let (result, gate-bounds) = layout.place-with-labels(
content,
size: size,
dx: dx, dy: dy,
labels: gate.labels, draw-params: draw-params
)
bounds = layout.update-bounds(bounds, gate-bounds)
result
}
for gate-info in multi-qubit-gates {
let (gate, size, x, y) = gate-info
let draw-params = draw-params
gate.qubit = y
if gate.multi.num-qubits > 1 {
let dy1 = center-y-coords.at(y + gate.multi.num-qubits - 1)
let dy2 = center-y-coords.at(y)
draw-params.multi.wire-distance = dy1 - dy2
}
// lsticks need their offset/width to be updated again (but don't update the height!)
let content = utility.get-content(gate, draw-params)
let new-size = utility.get-size-hint(gate, draw-params)
size.offset = new-size.offset
size.width = new-size.width
let (dx, dy) = get-gate-pos(x, y, size)
let (result, gate-bounds) = layout.place-with-labels(
content,
size: if gate.multi != none and gate.multi.num-qubits > 1 {auto} else {size},
dx: dx, dy: dy,
labels: gate.labels, draw-params: draw-params
)
bounds = layout.update-bounds(bounds, gate-bounds)
result
}
layer-above-circuit
// show matrix
// for (i, row) in matrix.enumerate() {
// for (j, entry) in row.enumerate() {
// let (dx, dy) = (center-x-coords.at(j), center-y-coords.at(i))
// place(
// dx: dx - entry.size.width / 2, dy: dy - entry.size.height / 2,
// box(stroke: green, width: entry.size.width, height: entry.size.height)
// )
// }
// }
}) // end circuit = block(..., {
let scale = scale
if circuit-padding != none {
let circuit-padding = process-args.process-padding-arg(circuit-padding)
bounds.at(0) -= circuit-padding.left
bounds.at(1) -= circuit-padding.top
bounds.at(2) += circuit-padding.right
bounds.at(3) += circuit-padding.bottom
}
let final-height = scale * (bounds.at(3) - bounds.at(1))
let final-width = scale * (bounds.at(2) - bounds.at(0))
let thebaseline = baseline
if type(thebaseline) in (content, str) {
thebaseline = height/2 - measure(thebaseline).height/2
}
if type(thebaseline) == fraction {
thebaseline = 100% - layout.get-cell-coords1(center-y-coords, row-heights, thebaseline / 1fr) + bounds.at(1)
}
box(baseline: thebaseline,
width: final-width,
height: final-height,
// stroke: 1pt + gray,
align(left + top, move(dy: -scale * bounds.at(1), dx: -scale * bounds.at(0),
layout.std-scale(
x: scale,
y: scale,
origin: left + top,
circuit
)))
)
}
}
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/algorithms/convex-hull.typ | typst | #let cross_product(o, a, b) = {
return (a.at(0) - o.at(0)) * (b.at(1) - o.at(1)) - (a.at(1) - o.at(1)) * (b.at(0) - o.at(0))
}
#let convex-hull(points) = {
// Helper function to calculate cross product
// Sort points lexicographically
let sorted_points = points.sorted()
let n = sorted_points.len()
if n <= 3 {
return sorted_points
}
// Build lower hull
let lower = ()
for p in sorted_points {
while lower.len() >= 2 and cross_product(lower.at(-2), lower.at(-1), p) <= 0 {
lower.pop()
}
lower.push(p)
}
// Build upper hull
let upper = ()
for p in sorted_points.rev() {
while upper.len() >= 2 and cross_product(upper.at(-2), upper.at(-1), p) <= 0 {
upper.pop()
}
upper.push(p)
}
// Concatenate hulls
lower.pop()
upper.pop()
return lower + upper
}
// #let points = (
// (0, 0), (1, 1), (2, 2), (3, 1), (4, 0), (3, 3), (2, 4), (1, 3), (2, 1), (10, 10),
// )
// #panic(convex-hull(points))
|
|
https://github.com/ntjess/typst-nsf-templates | https://raw.githubusercontent.com/ntjess/typst-nsf-templates/main/main-nsf-pitch.typ | typst | MIT License | #import "nsf-proposal.typ": *
#show: template
#title[NSF SBIR Phase I Pitch]
= Technology Innovation
#instructions[
(Up to 500 words)
Describe the technical innovation that would be the focus of a Phase I project, including a brief discussion of the origins of the innovation as well as explanation as to why it meets the program's mandate to focus on supporting research and development (R&D) of unproven, high-impact innovations.
]
= Technical Objectives and Challenges
#instructions[
(Up to 500 words)
Describe the R&D or technical work to be done in a Phase I project, including a discussion of how and why the proposed work will help prove that the product or service is technically feasible and/or significantly reduce technical risk. Discuss how, ultimately, this work could contribute to making the new product, service, or process commercially viable and impactful. This section should also convey that the proposed work meets the definition of R&D, rather than straightforward engineering or incremental product development tasks.
]
= Market Opportunity
#instructions[
(Up to 250 words)
Describe the customer profile and pain point(s) that will be the near-term commercial focus related to this technical project.
]
= Company and Team
#instructions[
(Up to 250 words)
Describe the background and current status of the applicant small business, including key team members who will lead the technical and/or commercial efforts discussed in this Project Pitch.
Create an account to submit your Project Pitch. More details about the NSF's new process and eligibility requirements are on our Apply page.
Each small business can only submit one Project Pitch at a time. Any small business with a pending Project Pitch must wait for a response before submitting another Project Pitch. Any small business that has received an invitation to submit a full proposal must wait for a resolution of the full proposal before submitting a new or revised Project Pitch.
] |
https://github.com/UntimelyCreation/typst-neat-cv | https://raw.githubusercontent.com/UntimelyCreation/typst-neat-cv/main/src/metadata.typ | typst | MIT License | /* Personal information */
#let firstName = "John"
#let lastName = "Doe"
#let personalInfo = (
phone: "+33 1 23 45 67 89",
email: "<EMAIL>",
github: "JohnDoe42",
homepage: "mywebsite.xyz",
location: "France",
//extraInfo: "",
)
#let headerQuoteInternational = (
"": [Senior Software Engineer looking for a full time job],
"en": [Senior Software Engineer looking for a full time job],
"fr": [Ingénieur logiciel expérimenté cherchant un emploi à temps plein],
)
/* Layout settings */
#let cvLanguage = "en"
#let accentColor = "burgundy"
#let profilePhoto = "images/avatar.png" // Leave empty if profil photo is not needed
#let varEntryOrganisationFirst = false // Choose whether to put company or position in bold
#let varDisplayLogo = false // Choose whether to display organisation logo
|
https://github.com/MultisampledNight/flow | https://raw.githubusercontent.com/MultisampledNight/flow/main/src/gfx/render.typ | typst | MIT License | // Actual implementations of individual rendered icons.
#import "util.typ": *
#import "draw.typ": *
#let empty(
// argument is simply ignored
// since it is always just a shallow outline
invert: true,
..args,
) = icon(
invert: true,
key: "empty",
..args,
() => {
rect((-0.125, -0.125), (1.125, 1.125), radius: 0.25)
})
#let urgent = icon.with(key: "urgent", () => {
let offset = 0.2
for (offset, y-scale) in (
((x: -offset, y: 0), 1),
((x: offset, y: 1), -1),
) {
line(
(0.5 + offset.x, 1 * y-scale + offset.y),
(0.5 + offset.x, 0.375 * y-scale + offset.y),
)
circle(
(0.5 + offset.x, 0.05 * y-scale + offset.y),
radius: 0.05,
)
}
})
#let progress = icon.with(key: "progress", () => {
let bendness = (x: 0.25, y: 0.5)
let offset = 0.25
for shift in (-offset, offset) {
line(
(0.5 - bendness.x + shift, 0.5 + bendness.y),
(0.5 + bendness.x + shift, 0.5),
(0.5 - bendness.x + shift, 0.5 - bendness.y),
fill: none,
)
}
})
#let pause = icon.with(key: "pause", () => {
circle((0.5, 0.8), radius: 0.1)
circle((0.5, 0.2), radius: 0.1)
})
#let block = icon.with(key: "block", () => {
line((0, 0.5), (1, 0.5))
})
#let complete = icon.with(key: "complete", () => {
set-origin((0.5, 0.5))
let bend = 0.075
for _ in range(4) {
line(
(0, 0),
(0, bend),
(0.5, 0.5),
(bend, 0),
close: true,
)
rotate(90deg)
}
})
#let cancel = icon.with(key: "cancel", () => {
let slantedness = 0.25
line(
(0.5 - slantedness, 0),
(0.5 + slantedness, 1),
)
})
#let unknown = icon.with(key: "unknown", () => {
arc(
(0.5, 0.5),
start: 165deg,
stop: -90deg,
fill: none,
radius: 0.25,
anchor: "arc-end",
)
line(
(0.5, 0.5),
(0.5, 0.375),
)
circle(
(0.5, 0.05),
radius: 0.05,
)
})
#let remark = icon.with(key: "remark", () => {
circle((0.5, 0.95), radius: 0.5pt)
line((0.5, 0.65), (0.5, 0))
})
#let hint = icon.with(key: "hint", () => {
circle((0.5, 0.5), radius: 0.5, fill: none)
})
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/bibliography-04.typ | typst | Other | #set page(width: 200pt)
#set heading(numbering: "1.")
#show bibliography: set heading(numbering: "1.")
= Multiple Bibs
Now we have multiple bibliographies containing #cite(<glacier-melt>)#cite(<keshav2007read>)
#bibliography(("/works.bib", "/works_too.bib"))
|
https://github.com/mst2k/HSOS-PTP-Typst-Template | https://raw.githubusercontent.com/mst2k/HSOS-PTP-Typst-Template/main/templates/template.typ | typst | #import "acronyms.typ": print-index, init-acronyms
#import "eidesstattliche_erklaerung.typ": *
#let buildMainHeader(mainHeadingContent, authorName) = {
[
#set block(above: 1em, below: 1em)
#grid(
columns: 3,
gutter: 1fr,
align(bottom, smallcaps(mainHeadingContent)),
align(bottom, image("../images/logos/HS-OS-Logo-Quer-rgb.jpg", width: auto, height: 20pt)),
align(bottom, smallcaps(authorName)),
)
#line(length: 100%)
]
}
// Returns the header for the current page
#let getHeader(authorName) = {
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.body, authorName)
}
// 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
return buildMainHeader(lastMainHeading.body, authorName)
})
}
//
#let renderAppendix(appendix) = {
counter(heading).update(0)
heading(outlined: true, numbering: none)[Anhang]
set heading(
supplement: "Anhang",
numbering: (..nums) => {
nums = nums.pos()
if nums.len() > 1 {
numbering("A", ..nums.slice(1))
}
}
)
appendix
}
#let project(
title: "",
abstract: [],
acronyms: (),
symbols: (),
authors: (),
betreuer: "",
modul: "",
abgabedatum: "",
language: "",
studiengang: "",
body,
appendix: []
) = {
// Set the document's basic properties.
set document(author: authors.map(a => a.name), title: title)
set text(font: "times new roman", lang: "de", size: 11pt)
show math.equation: set text(weight: 400)
set math.equation(numbering: "(1)")
set heading(numbering: "1.1")
set par(justify: true)
// Page Break before every lvl 1 heading, except for the first one
show heading.where(level: 1): it => {
let headings = query(selector(heading.where(level: 1)), it.location())
if headings.len() > 1{
if it.body != headings.first().body {
pagebreak(weak: true)
}
}
it
}
//highlight clickable items
show link: set text(fill: blue.darken(60%))
show ref: set text(fill: blue.darken(60%))
init-acronyms(acronyms)
////////////////
// Title page //
////////////////
//Logo
image("../images/logos/HS-OS-Logo-Standard-rgb.jpg")
//Title
align(center)[
#v(20pt)
#text(14pt, weight: 200, "INSTITUT FÜR DUALE STUDIENGÄNGE") \
#v(20pt)
#emph(text(16pt, weight: 600, "Praxistransferprojekt im Studiengang "+studiengang))
#v(25pt)
#text(2em, weight: 700, title)
]
// Author information.
text(
12pt,
font: "Calibri",
pad(
top: 5em,
grid(
columns: (auto, 1fr),
rows: (60pt, 30pt),
gutter: 1em,
"Eingereicht von:",
..authors.map(author => [
#author.name \
geb.: #author.birthday in #author.birthplace \
#author.address
]),
"Matrikelnummer:",
text(weight: 800, authors.at(0).matrikelnummer),
"Studiengruppe:",
text(weight: 800, authors.at(0).studiengruppe),
"Betreuer:",
betreuer,
"Modul:",
modul,
"Abgabedatum:",
abgabedatum
),
))
// Abstract page.
set page(numbering: "I", number-align: center)
v(1fr)
align(center)[
#heading(
outlined: false,
numbering: none,
text(0.85em, smallcaps[Abstract]),
)
]
v(12pt)
abstract
v(2fr)
counter(page).update(1)
///////////////////
// Verzeichnisse //
///////////////////
set page(margin: auto, header: none)
set block(above: 3em, below: 2em)
// Table of contents
show outline.entry.where(level: 1): it => {
strong(it)
}
outline(depth: 4 ,indent: true, title: [Inhaltsverzeichnis])
//Abbildungsverzeichnis, falls eine Abbildung existiert
locate(loc => {
let figures = query(selector(figure.where(kind: image)).after(loc), loc)
if figures.len() > 0 {
heading(outlined: true, numbering: none,[Abbildungsverzeichnis])
outline(
title: none,
target: figure.where(kind: image),
)
}})
//Tabellenverzeichnis, falls mindestens eine Tabelle existiert
locate(loc => {
let figures = query(selector(figure.where(kind: table)).after(loc), loc)
if figures.len() > 0 {
heading(outlined: true, numbering: none,[Tabellenverzeichnis])
outline(
title: none,
target: figure.where(kind: table),
)
}})
//Abkürzungsverzeichnis, falls mindestens eine Abkürzung existiert
if acronyms.len() > 0 {
print-index(title: "Abkürzungsverzeichnis", sorted: "up", delimiter: "", numbering: none, outlined: true)
}
//Symbolverzeichnis, falls mindestens ein Symbol existiert
if (symbols.len() > 0){
heading(outlined: true, numbering: none)[Symbolverzeichnis]
set block(above: 3em, below: 14pt)
let sym-list = symbols.keys()
for sym in sym-list{
table(
columns: (20%,80%),
stroke:none,
inset: 0pt,
[*#symbols.at(sym)*\ ], [#sym]
)
}
}
// Main body.
set block(above: 1.5em, below: 2em) //heading space
set par(justify: true)
set page(numbering: "1", number-align: center, margin: (top: 120pt, bottom: 80pt),header: getHeader(authors.at(0).name))
counter(page).update(1)
//main body (main.typ)
body
//End
// Continue roman numbering for the appendix.
set page(numbering: "I", number-align: center, margin: auto, header: none)
locate(loc => {
let AbsolutePageNumberOfFirstBodyPage = query(selector(heading.where(numbering: "1.1")).before(loc), loc).first().location().page()
counter(page).update(AbsolutePageNumberOfFirstBodyPage - 1)
})
// Bibliography
bibliography(title: [Literaturverzeichnis], style: "ieee","../sources.bib")
if appendix.fields().len() > 0 {
renderAppendix(appendix)
}
pagebreak()
eidesstattliche_erklaerung(title)
} |
|
https://github.com/royfrancis/quarto-typst-certificate | https://raw.githubusercontent.com/royfrancis/quarto-typst-certificate/main/_extensions/nbis-certificate/typst-template.typ | typst | #set text(font: "Lato", fill: rgb("#444444"))
#set par(leading: 0.7em)
#set block(spacing: 1.4em)
#let nbis-certificate(
title: none,
date: none,
headnotes-1: none,
headnotes-2: none,
gap: 72pt,
participant: none,
bg-image: none,
logo-image: none,
sign-image: none,
sign-height: 15mm,
teacher: none,
footnotes: none,
version: "Unknown",
body
) = {
// body
set text(12.5pt)
set page(
margin: (left: 2.5cm, right: 2.5cm, top: 4.5cm, bottom: 5cm),
background: if bg-image != none {
place(center + top, image(bg-image.path, height: 100%))
},
header: grid(
columns: (1fr, 1fr),
row-gutter: 0pt,
grid(
columns: 1fr,
rows: (12pt, 14pt),
row-gutter: 2.5pt,
text(weight: "medium", size: 11pt, tracking: 1.05pt, align(left + bottom, headnotes-1)),
text(weight: "medium", size: 14pt, tracking: 1.1pt, align(left + bottom, headnotes-2))
),
align(right, image(logo-image.path, height: 13mm))
),
footer: {
set text(8pt)
set par(leading: 0.5em)
set block(spacing: 1em)
set par(justify: true)
footnotes
set text(6pt)
pad(top: 1pt, version + h(1pt) + date)
}
)
// configure headings.
show heading.where(level: 1): set text(1.1em)
show heading.where(level: 1): set par(leading: 0.4em)
show heading.where(level: 1): set block(below: 0.8em)
show heading: it => {
set text(weight: 600) if it.level > 2
it
}
// underline links.
show link: underline
// page body
grid(
columns: 1fr,
row-gutter: 20pt,
// title.
pad(
top: 10pt,
bottom: gap,
text(36pt, weight: 700, tracking: 1.3pt, title)
),
// participant name
text(22pt, weight: 600, participant),
// body flow
{
set par(justify: true)
body
if sign-image != none {
image(sign-image.path, height: sign-height)
}
teacher
}
)
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/linebreak_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test that there are no unwanted line break opportunities on run change.
This is partly emp#emph[has]ized.
|
https://github.com/chickbone/hypergraph | https://raw.githubusercontent.com/chickbone/hypergraph/master/hypergraph.typ | typst | #import "/functions.typ": *
#import "@preview/cetz:0.2.2"
#import "@preview/fletcher:0.4.4"
#import "@preview/gentle-clues:0.8.0": *
#import "@preview/physica:0.9.3": *
#set text(lang: "jp")
#set text(font: "<NAME>",12pt)
#show emph: set text(font: "<NAME>",weight: "bold")
#show strong: set text(font: "<NAME>",weight: "bold",)
#let title1 ="hypergraphについての補足"
#set par(
justify: true,
leading: 0.6em,
)
#set list(indent: 0.5em)
#set enum(numbering: "(i)")
#set heading(numbering: "1.1.")
#set figure(supplement: "図")
#set page(
paper: "a4",
header: align(right)[
#title1
],
numbering: "1",
)
#show "、": ","
#show "。": "."
// 先頭字下げ
#show heading: it => {
theorem-number.update(1)
it
par(text(size:0.5em, ""))
}
#show math.equation: it => {
h(0.17em, weak: true)
it
h(0.17em, weak: true)
}
#let indentspace = 1em
#let i = h(indentspace)
#let Set =$bold("Set")$
#let Grph =$bold("Grph")$
// body
#big_title(emph(title1))
#align(center,[
柏原 功誠\@理学部1回
#text(10pt)[
$dash.em$概要$dash.em$\
hypergraphの概念は @関真一朗グリーン において導入されているが、もう少し良い定式化があるのではないかと考えた。ここにその一端をお見せしよう。
]
])
#outline(title: "目次")
= 準備
#i$Set$を*有限*集合全体が成す圏(集まり)とし (通常の定義とは*太字*の部分が異なる)、$power(V)$を$V in Set$の部分集合全体の集合とする。$id_V : V -> V$を恒等写像とする
#i また、$V in Set, space r in NN$に対して、$V$の濃度(元の個数)が$r$である部分集合全体を
$
comb(V,r) := {e in power(V) | hash e = r}
$
とする。
#i 部分集合族$E subset power(V)$と$phi: V -> V'$に対して、$phi$による$E$の像を
$
phi(E) := {phi(e) | e in E} subset power(V')
$
と定める。
= hypergraphの定義
#i hypergraphとは普通の(2-)graphを拡張した概念である。ここではhypergraphを定義する前に通常のgraphが頂点集合とその部分集合族の組として表されることを見よう。\
ただし、ここで言うgraphとは単純無向有限graph、即ち多重辺を許さず頂点集合が有限なものに限っていることに注意されたい。
#theorem(title: "(2-)graph", kind: "定義",[
頂点集合$thin V in Set$と 辺集合$E subset comb(V,2)$の組$ G = (V,E) $を*graph*という。
このとき、$V$の元$v$を頂点、$E$の元$e$を辺と呼ぶ。
])
ここで各$e in E$は2元集合なので、二つの異なる頂点$v,w$を用いて$e={v,w}$と書ける。
この時頂点$v$と$w$に辺が引かれていると考えることで、次のような図が書ける。
#theorem(title: "三角形", kind: "例",[
三角形$K_3$は #hide[頂点集合 と 辺集合$E subset comb(V,2)$の組]
$ V=[3]={1,2,3}, space E={{1,2},{2,3},{3,1}} $
とすることで実現できる。
])
#figure(
cetz.canvas({
import cetz.draw: *
// intersections("i", {
// line((-1,0),(0,1.5))
// line((-1,0),(1,0))
// line((1,0),(0,1.5))
// })
// for-each-anchor("i", (name) => {
// circle("i." + name, radius: .1, fill: blue)
// })
circle((-1,0), radius: 0.1, fill: black, name: "a")
circle((1,0), radius: 0.1, fill: black, name: "b")
circle((0,1.5), radius: 0.1, fill: black, name: "c")
line("a","b")
line("b","c")
line("a","c")
}),
caption: [三角形$K_3$の一例]
)
辺全体を部分集合族で定めたことにより、同じ頂点をもつ辺は自動的に同一視されることに注意してほしい(結果的に多重辺は無くなっている)。
#i 以上の定義においては$E$は$comb(V,2)$の部分集合、即ち辺集合の各元$e$は2元集合であった。ここを$E subset power(V)$まで緩める、つまり辺$e$が2点以上のものを考えることで、hypergraphの定義を得る。
#theorem(title: "hypergraph", kind: "定義",[
*頂点集合*$thin V in Set$と*辺集合*$E subset power(V)$の組
$ G = (V,E) $
を*hypergraph*という。
このとき、$V$の元$v$を頂点、$E$の元$e$を辺と呼ぶ。また、
$ V(G)=V, space E(G)=E $
をhypergrphのそれぞれ頂点集合、辺集合を与える対応とする。
])
#figure(
image("Hypergraph.gif", width: 50%),
caption: [hypergraphの例 (Wikipedia "hypergraph" より)],
)
#warning[
@関真一朗グリーン では$E subset power(V) without {emptyset}$と定義しているのは、空グラフ$(V,emptyset)$と$(V,{emptyset})$が紛らわしいからであろう
(一般に、$emptyset$と${emptyset}$は集合として異なる)。
だだ、一般論を展開する上では上記のような定義を採用したほうが自然であると考えた。
この違いがもたらす影響を筆者は全て把握できてはいない (以降に出てくる具体例は全て @関真一朗グリーン の定義を満たすので安心してほしい)。
]
= #krgraph($k$,$r$) (その一)
#i この節では、厳密な定義は後回しで#krgraph($k$,$r$)を理解することを目標とする。特に、重要な例として、#krgraph(3,2) を取り上げる。
#i まず、$r in NN$に対して #rgraph($r$) とは各辺の濃度が$r$であるhypergraphのことである:
#theorem(title: "r-graph", kind: "定義",[
頂点集合$thin V in Set$と 辺集合$E subset comb(V,r)$の組$ G = (V,E) $を#emph(rgraph($bold(r)$))という。
このとき、$E$の元$e$は濃度が$r$の$V$の部分集合である。
])
#figure(
cetz.canvas({
import cetz.draw: *
for (x,y,n,d) in (
(-1,0, "a", "north"),
(1,0, "b", "north"),
(0,1.5, "c", "south"),
(2,1.5, "d", "south"),
) {
circle((x,y), radius: .1,fill: black, name: n)
content(n, n, padding: .2, anchor: d)
}
line("a", "b", "c", "a", fill: blue,stroke: none)
line("b", "d", "c", close: true, fill: red,stroke: none)
}),
caption: [#rgraph(3) $(V = {a,b,c,d}, space E = {e_1 = {a,b,c},space e_2 = {b,c,d}})$]
) <3graphfig>
特に、通常の意味でのgraphとは#rgraph(2)のことである。
以下、単にgraphといえばhypergraphの事を指し、通常の意味でのgraphは#rgraph(2)と呼んで区別する。
#i では、次にgraphの頂点に"色を塗る"ことを考えよう。ただし、次の規則に従うものとする:
#align(center)[
彩色の規則: 各辺の頂点は互いに異なる色で塗る。
]
例えば @3graphfig の#rgraph(3)は次のようにして3色に塗り分けられる:
#figure(
cetz.canvas({
import cetz.draw: *
for (x,y,n,d,col) in (
(-1,0, "a", "north", red),
(1,0, "b", "north", blue),
(0,1.5, "c", "south", green),
(2,1.5, "d", "south", red),
) {
circle((x,y), radius: .1,fill: col, stroke: col, name: n)
content(n, n, padding: .2, anchor: d)
}
line("a", "b", "c", "a", fill: luma(200,20%),stroke: none)
line("b", "d", "c", close: true, fill: luma(200,20%),stroke: none)
}),
caption: [@3graphfig の#rgraph(3)の3色を用いた彩色]
)
逆に、色が塗られた頂点集合が与えられたとき、異なる色の頂点を選んで辺を引けば彩色されたgraphが得られる。
(これは @関真一朗グリーン での#krgraph($k$,$r$)データに対応する。)
#figure(
cetz.canvas({
import cetz.draw: *
group(anchor: "east", padding: 1.5,{
for (x,y,n,col) in (
(-3,0, "a1", red),
(-2.5,0.5, "a2", red),
(-1.7,0.2, "a3", red),
(-2.7,-0.5, "a4", red),
(2,0.2, "b1", blue),
(1.5,-0.4, "b2", blue),
(0.7,3, "c1", green),
(0,3.5, "c2", green),
(-0.7,2.5, "c3", green),
) {
circle((x,y), radius: .1,fill: col, stroke: col, name: n)
}
line("a1", "b1",fill: luma(0,70%))
line("a4", "b1",fill: luma(0,70%))
line("a3", "b2",fill: luma(0,70%))
line("b1", "c1",fill: luma(0,70%))
line("b2", "c2",fill: luma(0,70%))
line("b2", "c3",fill: luma(0,70%))
line("a3", "c2",fill: luma(0,70%))
line("a2", "c3",fill: luma(0,70%))
})
line((-1,1.5),(0.5,1.5), mark: (end: "straight"))
group(anchor: "west", padding: 1.5, {
for (x,y,n,d,col) in (
(-1.5,0,"1", "north", red),
(1.5,0, "2", "north", blue),
(0,2.5, "3", "south", green),
) {
circle((x,y), radius: .5,fill: col, stroke: col, name: n)
content(n, n, padding: .6, anchor: d)
}
line("1", "2", stroke: 0.2em)
line("3", "2", stroke: 0.2em)
line("1", "3", stroke: 0.2em)
})
}),
caption: [#krgraph(3,2)$G_0$の例]
) <3bu2graph>
ここで、$k$色で彩色可能な#rgraph($r$)ことを#krgraph($k$,$r$)と呼ぶこととする (厳密な定義は後述)。
#i ここまで"彩色"という曖昧な用語を用いてきたが、色を塗るというのは結局のところ頂点集合$V$から色の集合$J$への写像(全射)を与えることと等しい。\
例えば @3bu2graph の#krgraph(3,2)$G_0$において、$V(G_0)$から$J=[3]$への写像
$ lambda: V(G_0) -> J (= [3]) $
は、赤色の点を$1 in J$に、青色の点を$2 in J$に、緑色の点を$3 in J$にそれぞれ対応させる。
このとき、$j space (in J)$色の点全体は$V_j = lambda^(-1)(j)$と表される。
#i ただ、ここまでの議論には致命的な欠陥がある: 彩色の規則が全く反映されていない!! 特に$lambda: V(G_0) -> J$ を適当に与えたとき、$lambda$に対応する彩色が規則を満たす保障はどこにもない。以下の節ではこの問題を解決するように#krgraph($k$,$r$)を定義することに捧げられる。基本的なアイデアとしては、
- $J$ をgraph$K_3$と思い、
- $lambda$を "graphの間の写像" $lambda: G_0 -> K_3$とみなす
ことにより達成される。
#pagebreak()
= graphの間の写像
== graph map
#i 前節で述べたように、この節では "graphの間の写像" graph mapを定義する。
#i graphとは辺集合という構造を持った集合なので、その間の"写像"としては構造を保つ写像を考えたい。素朴に考えれば辺を辺に写すようなものが良いのだろうが、一般の(hyper)graphでは元の個数についての制限がないので、もう少し条件を緩めてみる。つまり、辺を写した像がある辺に含まれていれば良いとする。ここまでの議論をまとめて、以下の定義を得る。
#theorem(title: "graph map", kind: "定義",[
二つのgraph$G,G'$に対して、$G$から$G'$への*graph map*$ f: G -> G' $とは、
+ 頂点集合の間の写像$space f: V(G) -> V(G') space$であって、
+ 全ての$e in E(G)$に対して、ある$e' in E(G')$が存在して$f(e) subset e'$を満たす
もののことを言う。
])
上の条件 (ii) は、式で書くと
$
forall e in E(G), space exists e' in E(G'), space f(e) subset e'
$
であり、$G$の各辺を$f$で写した像が$G'$のある辺に含まれているということを意味する。
#theorem(kind: "例",[
+ @3bu2graph において、$lambda: V(G_0) -> J = V(K_3)$はgraph map$lambda: G_0 -> K_3$となる. 実際、例えば赤色の点から青色の点への辺$e$は、$lambda$によって$K_3$の辺$e'={1,2}$に移る ($lambda(e) subset e'$が成り立つ)。他の色の間の辺も同様であるから、結局$lambda: G_0 -> K_3$はgraph mapとなる。
+ 二つのgraph$G,H(!= emptyset)$について、全ての$G$の頂点をある$H$の頂点$h in H$に移す写像を$ c_h : V(G) -> V(H), space c_h (v) = h space (forall v in V(G)) $ と定める。このとき、任意の$e in E(G)$に対して$c_h (e) = {h}$であるから、「$c_h$がgraph mapとなる」と「$h in e'$なる$e' in E(H)$が存在する」は同値であることがわかる。
+ graph$G$について、$id_(V(G)) : V(G) -> V(G)$は$id_G (e) = e$となるので、明らかにgraph mapとなる。$id_V(G)$を$id_G$と書き、graph$G$の*恒等射*という。一方、一般の写像$f: V(G) -> V(G)$は常にgraph mapになるとは限らない。
])
次の例はgraph mapを考える主な動機の一つである。
#theorem(kind: "例",[
graph$(X,O_X),(Y,O_Y)$が位相空間となる (位相空間の公理を満たす)とき、$(X,O_X)$から$(Y,O_Y)$へのgraph mapとは即ち*連続写像*のことである。実際
$
forall U in O_X, exists V in O_Y, space f(U) subset V\ <==> forall V in O_Y, space f^(-1)(V) in O_X
$
が位相空間の一般論より従う。同様に、graphが(有限)加法族の構造を持つとき、その間のgraph mapとは*可測関数*のことである。
])
graph mapの定義がある意味で"うまくいっている"ことは、次の命題によって保証される:
#theorem(kind: "命題",[
$F,G,H,L$をgraphとする。
+ graph map$f:F->G,space g:G->H$に対して、その合成$ g compose f: F->H $もまたgraph mapとなる。
+ graph map$f:F->G,g:G->H,h:H->L$に対して、結合律$ (h compose g) compose f = h compose (g compose f) $が成り立つ。
+ 各graph$G$に対して、$id_G : G -> G$があって、任意のgraph map$f:G->H$に対して、$ id_H compose f = f = f compose id_G $が成り立つ。
])
#proof[
(ii)と(iii)は$Set$における合成の定義から直ちに従う。以下(i)を示す。
$f$と$g$がgraph mapであることから、$e in E(F)$に対して、\
#align(center)[
$f(e) subset e'$となるような$e' in E(G)$と\
$g(e') subset e''$となるような$e'' in E(H)$\
]
がとれる。このとき、
$
(g compose f)(e) = g(f(e)) subset g(e') subset e''
$
となる。$e in E(F)$は任意であるから、$g compose f$はgraph mapである。
]
ここまで敢えて圏論の用語を避けてきたが、圏の定義を知っている人には次のように述べた方が簡潔だろう。(知らない人は無視してもらって構わない。)
#theorem(kind: "命題",[
graphを対象、graph mapを射とする圏$Grph$を定義できる。
])
以下、$G in Grph$は$G$がgraphであるという意味で用いる。
== 完全graph
#i さて、対応$V: Grph -> Set$(実は関手になっている)はgraphをその頂点集合に写すのであった。では、逆に頂点集合$V in Set$が与えられたとき自然な方法でgraphを定めることはできるのであろうか?その答えの一つが次の完全graphである。
#theorem(title: "完全graph", kind: "定義",[
$V in Set$に対して、$K(V) = (V,power(V)) in Grph$を$V$を頂点とする*完全graph*という。
])
#pagebreak()
#bibliography("hypergraph.bib", title: "参考文献") |
|
https://github.com/EpicEricEE/typst-equate | https://raw.githubusercontent.com/EpicEricEE/typst-equate/master/tests/local/test.typ | typst | MIT License | #import "/src/lib.typ": equate
#set page(width: 6cm, height: auto, margin: 1em)
#set math.equation(numbering: "(1)")
$ a + b \
c + d $
#equate($
d + e \
f + g #<lbl>
$)
@lbl (wrong)
#equate(<lbl>) (correct)
#[
#show ref: equate
@lbl (correct)
]
#[
#show: equate
@lbl (correct)
] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0E80.typ | typst | Apache License 2.0 | #let data = (
(),
("LAO LETTER KO", "Lo", 0),
("LAO LETTER KHO SUNG", "Lo", 0),
(),
("LAO LETTER KHO TAM", "Lo", 0),
(),
("LAO LETTER PALI GHA", "Lo", 0),
("LAO LETTER NGO", "Lo", 0),
("LAO LETTER CO", "Lo", 0),
("LAO LETTER PALI CHA", "Lo", 0),
("LAO LETTER SO TAM", "Lo", 0),
(),
("LAO LETTER PALI JHA", "Lo", 0),
("LAO LETTER NYO", "Lo", 0),
("LAO LETTER PALI NYA", "Lo", 0),
("LAO LETTER PALI TTA", "Lo", 0),
("LAO LETTER PALI TTHA", "Lo", 0),
("LAO LETTER PALI DDA", "Lo", 0),
("LAO LETTER PALI DDHA", "Lo", 0),
("LAO LETTER PALI NNA", "Lo", 0),
("LAO LETTER DO", "Lo", 0),
("LAO LETTER TO", "Lo", 0),
("LAO LETTER THO SUNG", "Lo", 0),
("LAO LETTER THO TAM", "Lo", 0),
("LAO LETTER PALI DHA", "Lo", 0),
("LAO LETTER NO", "Lo", 0),
("LAO LETTER BO", "Lo", 0),
("LAO LETTER PO", "Lo", 0),
("LAO LETTER PHO SUNG", "Lo", 0),
("LAO LETTER FO TAM", "Lo", 0),
("LAO LETTER PHO TAM", "Lo", 0),
("LAO LETTER FO SUNG", "Lo", 0),
("LAO LETTER PALI BHA", "Lo", 0),
("LAO LETTER MO", "Lo", 0),
("LAO LETTER YO", "Lo", 0),
("LAO LETTER LO LING", "Lo", 0),
(),
("LAO LETTER LO LOOT", "Lo", 0),
(),
("LAO LETTER WO", "Lo", 0),
("LAO LETTER SANSKRIT SHA", "Lo", 0),
("LAO LETTER SANSKRIT SSA", "Lo", 0),
("LAO LETTER SO SUNG", "Lo", 0),
("LAO LETTER HO SUNG", "Lo", 0),
("LAO LETTER PALI LLA", "Lo", 0),
("LAO LETTER O", "Lo", 0),
("LAO LETTER HO TAM", "Lo", 0),
("LAO ELLIPSIS", "Lo", 0),
("LAO VOWEL SIGN A", "Lo", 0),
("LAO VOWEL SIGN MAI KAN", "Mn", 0),
("LAO VOWEL SIGN AA", "Lo", 0),
("LAO VOWEL SIGN AM", "Lo", 0),
("LAO VOWEL SIGN I", "Mn", 0),
("LAO VOWEL SIGN II", "Mn", 0),
("LAO VOWEL SIGN Y", "Mn", 0),
("LAO VOWEL SIGN YY", "Mn", 0),
("LAO VOWEL SIGN U", "Mn", 118),
("LAO VOWEL SIGN UU", "Mn", 118),
("LAO SIGN PALI VIRAMA", "Mn", 9),
("LAO VOWEL SIGN MAI KON", "Mn", 0),
("LAO SEMIVOWEL SIGN LO", "Mn", 0),
("LAO SEMIVOWEL SIGN NYO", "Lo", 0),
(),
(),
("LAO VOWEL SIGN E", "Lo", 0),
("LAO VOWEL SIGN EI", "Lo", 0),
("LAO VOWEL SIGN O", "Lo", 0),
("LAO VOWEL SIGN AY", "Lo", 0),
("LAO VOWEL SIGN AI", "Lo", 0),
(),
("LAO KO LA", "Lm", 0),
(),
("LAO TONE MAI EK", "Mn", 122),
("LAO TONE MAI THO", "Mn", 122),
("LAO TONE MAI TI", "Mn", 122),
("LAO TONE MAI CATAWA", "Mn", 122),
("LAO CANCELLATION MARK", "Mn", 0),
("LAO NIGGAHITA", "Mn", 0),
("LAO YAMAKKAN", "Mn", 0),
(),
("LAO DIGIT ZERO", "Nd", 0),
("LAO DIGIT ONE", "Nd", 0),
("LAO DIGIT TWO", "Nd", 0),
("LAO DIGIT THREE", "Nd", 0),
("LAO DIGIT FOUR", "Nd", 0),
("LAO DIGIT FIVE", "Nd", 0),
("LAO DIGIT SIX", "Nd", 0),
("LAO DIGIT SEVEN", "Nd", 0),
("LAO DIGIT EIGHT", "Nd", 0),
("LAO DIGIT NINE", "Nd", 0),
(),
(),
("LAO HO NO", "Lo", 0),
("LAO HO MO", "Lo", 0),
("LAO LETTER KHMU GO", "Lo", 0),
("LAO LETTER KHMU NYO", "Lo", 0),
)
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/lib/glossary.typ | typst | Other | #let __GLOSSARY = (
"global scripts": ([全球文种], []),
shaping: ([造型], []),
layout: ([布局], []),
type: ([字], []),
punch: ([字冲], []),
matrix: ([字模], []),
sort: ([活字], []),
"type case": ([字盘], []),
"hot metal typesetting": ([热金属排印], []),
bitmap: ([点阵], []),
baseline: ([基线], []),
typography: ([字体排印], []),
"writing system": ([书写系统], []),
script: ([文字], []),
scripts: ([文种], []),
"script.class": ([文种], []),
"bounding box": ([边界框], []),
raster: ([栅格], []),
glyph: ([字形], []),
outline: ([轮廓], []),
master: ([母版], []),
"multiple master": ([多重母版], []),
rasterization: ([栅格化], []),
x-height: ([x字高], []),
character: ([字符], []),
hinting: ([渲染提示], []),
serif: ([衬线], []),
stem: ([字干], []),
"cap height": ([大写高度], []),
"contextual": ([上下文相关], []),
typeset: ([排版], []),
ligature: ([连字], []),
"alternate glyph": ([备选字形], []),
"variable font": ([可变字体], []),
"typeface family": ([字体家族], []),
instance: ([样本], []),
"compositing stick": ([手盘], []),
rendering: ([渲染], []),
"character set": ([字符集], []),
dimension: ([尺寸], []),
sidebearing: ([跨距], []),
"kern.origin": ([出格], []),
kern: ([字偶距], []),
"em square": ([em方框], []),
headline: ([字头线], []),
decender: ([降部], []),
advance: ([步进], []),
"advance width": ([步进宽度], []),
"advance height": ([步进高度], []),
"horizontal advance": ([水平步进], []),
cursor: ([光标], []),
"ink rectangle": ([着墨矩形], []),
ascender: ([升部], []),
metrics: ([度量], []),
"vertical advance": ([垂直步进], []),
position: ([位置], []),
shaper: ([造型器], []),
encoding: ([编码], []),
codepoint: ([码位], []),
BMP: ([基本多文种平面], []),
SMP: ([多文种补充平面], []),
block: ([区块], []),
"surrogate pair": ([代理对], []),
"general category": ([大类], []),
combine: ([组合], []),
compose: ([合成], []),
decompose: ([分解], []),
bidi: ([双向], []),
case-fold: ([大小写折叠], []),
normalization: ([正态化], []),
diacritic: ([变音符号], []),
canonical: ([正则], []),
spline: ([样条], []),
substitution: ([替换], []),
positioning: ([定位], []),
counter: ([字怀], []),
contour: ([轮廓线], []),
lookup: ([查询组], []),
"chaining": ([链式], []),
"chaining rules": ([链式规则], []),
"horizontal typeset": ([横排], []),
"vertical typeset": ([竖排], []),
"glyph class": ([字形类], []),
"anchor attachment": ([锚点衔接], []),
"attachment rules": ([附加规则], []),
"multiple substitution": ([增量替换], []),
"alternate substitution": ([备选替换], []),
"chaining substitution": ([链式替换], []),
"single adjustment": ([单字调整], []),
"cursive attachment": ([连笔衔接], []),
"cluster": ([簇], []),
)
#let __glossary_meta(..data) = metadata((
kind: "glossary",
..data.named(),
))
#let tr(body, origin: false, force: none) = {
if type(body) == content {
if body.has("text") {
body = body.at("text")
} else {
panic("Unsupport complicate content")
}
}
if body not in __GLOSSARY {
panic("Unknown glossary '" + body + "'")
}
let translation = if type(force) == content {
force
} else {
__GLOSSARY.at(body).at(0)
}
if origin {
ranslation = translation + [(#body)]
}
translation + __glossary_meta(origin: body)
}
#let glossary_table = [
#let cells = ();
#for entry in __GLOSSARY.pairs() {
let key = entry.at(0)
let value = entry.at(1)
cells.push([#key])
cells.push([#value.at(0)])
cells.push([#value.at(1)])
}
#table(
columns: 3,
..cells,
)
]
|
https://github.com/ivaquero/typst-fasvg | https://raw.githubusercontent.com/ivaquero/typst-fasvg/main/manual.typ | typst | MIT License | #import "fontawesome.typ": *
#let title = "Typst-FontAwesome"
#set page(
paper: "a4",
header: [
#set text(6pt)
],
numbering: "1 / 1",
)
#set heading(
level: 2,
numbering: "1.",
)
#set par(
justify: true,
leading: 1em,
linebreaks: "optimized",
)
#set block(above: 1em, below: 0.5em)
#align(
center,
text(18pt)[
*#title*
],
)
#outline(
title: [],
indent: auto,
)
#pagebreak()
= Brands
<Brands>
== A-C
#figure(
align(center)[#table(
columns: 6,
align: center,
[brand-42-group],
[#fa("brand-42-group")],
[brand-500px],
[#fa("brand-500px")],
[brand-accessible-icon],
[#fa("brand-accessible-icon")],
[brand-accusoft],
[#fa("brand-accusoft")],
[brand-adn],
[#fa("brand-adn")],
[brand-adversal],
[#fa("brand-adversal")],
[brand-affiliatetheme],
[#fa("brand-affiliatetheme")],
[brand-airbnb],
[#fa("brand-airbnb")],
[brand-algolia],
[#fa("brand-algolia")],
[brand-alipay],
[#fa("brand-alipay")],
[brand-amazon-pay],
[#fa("brand-amazon-pay")],
[brand-amazon],
[#fa("brand-amazon")],
[brand-amilia],
[#fa("brand-amilia")],
[brand-android],
[#fa("brand-android")],
[brand-angellist],
[#fa("brand-angellist")],
[brand-angrycreative],
[#fa("brand-angrycreative")],
[brand-angular],
[#fa("brand-angular")],
[brand-app-store-ios],
[#fa("brand-app-store-ios")],
[brand-app-store],
[#fa("brand-app-store")],
[brand-apper],
[#fa("brand-apper")],
[brand-apple-pay],
[#fa("brand-apple-pay")],
[brand-apple],
[#fa("brand-apple")],
[brand-artstation],
[#fa("brand-artstation")],
[brand-asymmetrik],
[#fa("brand-asymmetrik")],
[brand-atlassian],
[#fa("brand-atlassian")],
[brand-audible],
[#fa("brand-audible")],
[brand-autoprefixer],
[#fa("brand-autoprefixer")],
[brand-avianex], [#fa("brand-avianex")], [brand-aviato], [#fa("brand-aviato")], [brand-aws], [#fa("brand-aws")],
[brand-bandcamp],
[#fa("brand-bandcamp")],
[brand-battle-net],
[#fa("brand-battle-net")],
[brand-behance],
[#fa("brand-behance")],
[brand-bilibili],
[#fa("brand-bilibili")],
[brand-bimobject],
[#fa("brand-bimobject")],
[brand-bitbucket],
[#fa("brand-bitbucket")],
[brand-bitcoin],
[#fa("brand-bitcoin")],
[brand-bity],
[#fa("brand-bity")],
[brand-black-tie],
[#fa("brand-black-tie")],
[brand-blackberry],
[#fa("brand-blackberry")],
[brand-blogger-b],
[#fa("brand-blogger-b")],
[brand-blogger],
[#fa("brand-blogger")],
[brand-bluetooth-b],
[#fa("brand-bluetooth-b")],
[brand-bluetooth],
[#fa("brand-bluetooth")],
[brand-bootstrap],
[#fa("brand-bootstrap")],
[brand-bots], [#fa("brand-bots")], [brand-btc], [#fa("brand-btc")], [brand-buffer], [#fa("brand-buffer")],
[brand-buromobelexperte],
[#fa("brand-buromobelexperte")],
[brand-buy-n-large],
[#fa("brand-buy-n-large")],
[brand-buysellads],
[#fa("brand-buysellads")],
[brand-canadian-maple-leaf],
[#fa("brand-canadian-maple-leaf")],
[brand-cc-amazon-pay],
[#fa("brand-cc-amazon-pay")],
[brand-cc-amex],
[#fa("brand-cc-amex")],
[brand-cc-apple-pay],
[#fa("brand-cc-apple-pay")],
[brand-cc-diners-club],
[#fa("brand-cc-diners-club")],
[brand-cc-discover],
[#fa("brand-cc-discover")],
[brand-cc-jcb],
[#fa("brand-cc-jcb")],
[brand-cc-mastercard],
[#fa("brand-cc-mastercard")],
[brand-cc-paypal],
[#fa("brand-cc-paypal")],
[brand-cc-stripe],
[#fa("brand-cc-stripe")],
[brand-cc-visa],
[#fa("brand-cc-visa")],
[brand-centercode],
[#fa("brand-centercode")],
[brand-centos],
[#fa("brand-centos")],
[brand-chrome],
[#fa("brand-chrome")],
[brand-chromecast],
[#fa("brand-chromecast")],
[brand-cloudflare],
[#fa("brand-cloudflare")],
[brand-cloudscale],
[#fa("brand-cloudscale")],
[brand-cloudsmith],
[#fa("brand-cloudsmith")],
[brand-cloudversify],
[#fa("brand-cloudversify")],
[brand-cmplid],
[#fa("brand-cmplid")],
[brand-codepen],
[#fa("brand-codepen")],
[brand-codiepie],
[#fa("brand-codiepie")],
[brand-confluence],
[#fa("brand-confluence")],
[brand-connectdevelop],
[#fa("brand-connectdevelop")],
[brand-contao],
[#fa("brand-contao")],
[brand-cotton-bureau],
[#fa("brand-cotton-bureau")],
[brand-cpanel],
[#fa("brand-cpanel")],
[brand-critical-role],
[#fa("brand-critical-role")],
[brand-css3-alt],
[#fa("brand-css3-alt")],
[brand-css3],
[#fa("brand-css3")],
[brand-cuttlefish], [#fa("brand-cuttlefish")],
)],
)
#pagebreak(weak: true)
=== Creative
#figure(
align(center)[#table(
columns: 4,
align: center,
[brand-creative-commons-by],
[#fa("brand-creative-commons-by")],
[brand-creative-commons-nc-eu],
[#fa("brand-creative-commons-nc-eu")],
[brand-creative-commons-nc-jp],
[#fa("brand-creative-commons-nc-jp")],
[brand-creative-commons-nc],
[#fa("brand-creative-commons-nc")],
[brand-creative-commons-nd],
[#fa("brand-creative-commons-nd")],
[brand-creative-commons-pd-alt],
[#fa("brand-creative-commons-pd-alt")],
[brand-creative-commons-pd],
[#fa("brand-creative-commons-pd")],
[brand-creative-commons-remix],
[#fa("brand-creative-commons-remix")],
[brand-creative-commons-sa],
[#fa("brand-creative-commons-sa")],
[brand-creative-commons-sampling-plus],
[#fa("brand-creative-commons-sampling-plus")],
[brand-creative-commons-sampling],
[#fa("brand-creative-commons-sampling")],
[brand-creative-commons-share],
[#fa("brand-creative-commons-share")],
[brand-creative-commons-zero],
[#fa("brand-creative-commons-zero")],
[brand-creative-commons],
[#fa("brand-creative-commons")],
)],
)
== D-F
#figure(
align(center)[#table(
columns: 6,
align: center,
[brand-d-and-d-beyond],
[#fa("brand-d-and-d-beyond")],
[brand-d-and-d],
[#fa("brand-d-and-d")],
[brand-dailymotion],
[#fa("brand-dailymotion")],
[brand-dashcube],
[#fa("brand-dashcube")],
[brand-debian],
[#fa("brand-debian")],
[brand-deezer],
[#fa("brand-deezer")],
[brand-delicious],
[#fa("brand-delicious")],
[brand-deploydog],
[#fa("brand-deploydog")],
[brand-deskpro],
[#fa("brand-deskpro")],
[brand-dev], [#fa("brand-dev")], [brand-deviantart], [#fa("brand-deviantart")], [brand-dhl], [#fa("brand-dhl")],
[brand-diaspora],
[#fa("brand-diaspora")],
[brand-digg],
[#fa("brand-digg")],
[brand-digital-ocean],
[#fa("brand-digital-ocean")],
[brand-discord],
[#fa("brand-discord")],
[brand-discourse],
[#fa("brand-discourse")],
[brand-dochub],
[#fa("brand-dochub")],
[brand-docker],
[#fa("brand-docker")],
[brand-draft2digital],
[#fa("brand-draft2digital")],
[brand-dribbble],
[#fa("brand-dribbble")],
[brand-dropbox],
[#fa("brand-dropbox")],
[brand-drupal],
[#fa("brand-drupal")],
[brand-dyalog],
[#fa("brand-dyalog")],
[brand-earlybirds],
[#fa("brand-earlybirds")],
[brand-ebay],
[#fa("brand-ebay")],
[brand-edge-legacy],
[#fa("brand-edge-legacy")],
[brand-edge], [#fa("brand-edge")], [brand-elementor], [#fa("brand-elementor")], [brand-ello], [#fa("brand-ello")],
[brand-ember], [#fa("brand-ember")], [brand-empire], [#fa("brand-empire")], [brand-envira], [#fa("brand-envira")],
[brand-erlang],
[#fa("brand-erlang")],
[brand-ethereum],
[#fa("brand-ethereum")],
[brand-etsy],
[#fa("brand-etsy")],
[brand-evernote],
[#fa("brand-evernote")],
[brand-expeditedssl],
[#fa("brand-expeditedssl")],
[brand-facebook-f],
[#fa("brand-facebook-f")],
[brand-facebook-messenger],
[#fa("brand-facebook-messenger")],
[brand-facebook],
[#fa("brand-facebook")],
[brand-fantasy-flight-games],
[#fa("brand-fantasy-flight-games")],
[brand-fedex], [#fa("brand-fedex")], [brand-fedora], [#fa("brand-fedora")], [brand-figma], [#fa("brand-figma")],
[brand-firefox-browser],
[#fa("brand-firefox-browser")],
[brand-firefox],
[#fa("brand-firefox")],
[brand-first-order-alt],
[#fa("brand-first-order-alt")],
[brand-first-order],
[#fa("brand-first-order")],
[brand-firstdraft],
[#fa("brand-firstdraft")],
[brand-flickr],
[#fa("brand-flickr")],
[brand-flipboard],
[#fa("brand-flipboard")],
[brand-fly],
[#fa("brand-fly")],
[brand-font-awesome],
[#fa("brand-font-awesome")],
[brand-fonticons-fi],
[#fa("brand-fonticons-fi")],
[brand-fonticons],
[#fa("brand-fonticons")],
[brand-fort-awesome-alt],
[#fa("brand-fort-awesome-alt")],
[brand-fort-awesome],
[#fa("brand-fort-awesome")],
[brand-forumbee],
[#fa("brand-forumbee")],
[brand-foursquare],
[#fa("brand-foursquare")],
[brand-free-code-camp],
[#fa("brand-free-code-camp")],
[brand-freebsd],
[#fa("brand-freebsd")],
[brand-fulcrum],
[#fa("brand-fulcrum")],
)],
)
== G-I
#figure(
align(center)[#table(
columns: 6,
align: center,
[brand-galactic-republic],
[#fa("brand-galactic-republic")],
[brand-galactic-senate],
[#fa("brand-galactic-senate")],
[brand-get-pocket],
[#fa("brand-get-pocket")],
[brand-gg-circle],
[#fa("brand-gg-circle")],
[brand-gg],
[#fa("brand-gg")],
[brand-git-alt],
[#fa("brand-git-alt")],
[brand-git],
[#fa("brand-git")],
[brand-github-alt],
[#fa("brand-github-alt")],
[brand-github],
[#fa("brand-github")],
[brand-gitkraken],
[#fa("brand-gitkraken")],
[brand-gitlab],
[#fa("brand-gitlab")],
[brand-gitter],
[#fa("brand-gitter")],
[brand-glide-g],
[#fa("brand-glide-g")],
[brand-glide],
[#fa("brand-glide")],
[brand-gofore],
[#fa("brand-gofore")],
[brand-golang],
[#fa("brand-golang")],
[brand-goodreads-g],
[#fa("brand-goodreads-g")],
[brand-goodreads],
[#fa("brand-goodreads")],
[brand-google-drive],
[#fa("brand-google-drive")],
[brand-google-pay],
[#fa("brand-google-pay")],
[brand-google-play],
[#fa("brand-google-play")],
[brand-google-plus-g],
[#fa("brand-google-plus-g")],
[brand-google-plus],
[#fa("brand-google-plus")],
[brand-google-wallet],
[#fa("brand-google-wallet")],
[brand-google],
[#fa("brand-google")],
[brand-gratipay],
[#fa("brand-gratipay")],
[brand-grav],
[#fa("brand-grav")],
[brand-gripfire],
[#fa("brand-gripfire")],
[brand-grunt],
[#fa("brand-grunt")],
[brand-guilded],
[#fa("brand-guilded")],
[brand-gulp],
[#fa("brand-gulp")],
[brand-hacker-news],
[#fa("brand-hacker-news")],
[brand-hackerrank],
[#fa("brand-hackerrank")],
[brand-hashnode],
[#fa("brand-hashnode")],
[brand-hips],
[#fa("brand-hips")],
[brand-hire-a-helper],
[#fa("brand-hire-a-helper")],
[brand-hive], [#fa("brand-hive")], [brand-hooli], [#fa("brand-hooli")], [brand-hornbill], [#fa("brand-hornbill")],
[brand-hotjar], [#fa("brand-hotjar")], [brand-houzz], [#fa("brand-houzz")], [brand-html5], [#fa("brand-html5")],
[brand-hubspot], [#fa("brand-hubspot")], [brand-ideal], [#fa("brand-ideal")], [brand-imdb], [#fa("brand-imdb")],
[brand-instagram],
[#fa("brand-instagram")],
[brand-instalod],
[#fa("brand-instalod")],
[brand-intercom],
[#fa("brand-intercom")],
[brand-internet-explorer],
[#fa("brand-internet-explorer")],
[brand-invision],
[#fa("brand-invision")],
[brand-ioxhost],
[#fa("brand-ioxhost")],
[brand-itch-io],
[#fa("brand-itch-io")],
[brand-itunes-note],
[#fa("brand-itunes-note")],
[brand-itunes],
[#fa("brand-itunes")],
[brand-java],
[#fa("brand-java")],
[brand-jedi-order],
[#fa("brand-jedi-order")],
[brand-jenkins],
[#fa("brand-jenkins")],
[brand-jira], [#fa("brand-jira")], [brand-joget], [#fa("brand-joget")], [brand-joomla], [#fa("brand-joomla")],
[brand-js], [#fa("brand-js")], [brand-jsfiddle], [#fa("brand-jsfiddle")], [brand-kaggle], [#fa("brand-kaggle")],
[brand-keybase],
[#fa("brand-keybase")],
[brand-keycdn],
[#fa("brand-keycdn")],
[brand-kickstarter-k],
[#fa("brand-kickstarter-k")],
[brand-kickstarter],
[#fa("brand-kickstarter")],
[brand-korvue],
[#fa("brand-korvue")],
[brand-laravel],
[#fa("brand-laravel")],
[brand-lastfm], [#fa("brand-lastfm")], [brand-leanpub], [#fa("brand-leanpub")], [brand-less], [#fa("brand-less")],
[brand-line],
[#fa("brand-line")],
[brand-linkedin-in],
[#fa("brand-linkedin-in")],
[brand-linkedin],
[#fa("brand-linkedin")],
[brand-linode], [#fa("brand-linode")], [brand-linux], [#fa("brand-linux")], [brand-lyft], [#fa("brand-lyft")],
)],
)
#pagebreak()
== M-R
#figure(
align(center)[#table(
columns: 6,
[brand-magento],
[#fa("brand-magento")],
[brand-mailchimp],
[#fa("brand-mailchimp")],
[brand-mandalorian],
[#fa("brand-mandalorian")],
[brand-markdown],
[#fa("brand-markdown")],
[brand-mastodon],
[#fa("brand-mastodon")],
[brand-maxcdn],
[#fa("brand-maxcdn")],
[brand-mdb], [#fa("brand-mdb")], [brand-medapps], [#fa("brand-medapps")], [brand-medium], [#fa("brand-medium")],
[brand-medrt],
[#fa("brand-medrt")],
[brand-meetup],
[#fa("brand-meetup")],
[brand-megaport],
[#fa("brand-megaport")],
[brand-mendeley],
[#fa("brand-mendeley")],
[brand-meta],
[#fa("brand-meta")],
[brand-microblog],
[#fa("brand-microblog")],
[brand-microsoft],
[#fa("brand-microsoft")],
[brand-mix],
[#fa("brand-mix")],
[brand-mixcloud],
[#fa("brand-mixcloud")],
[brand-mixer], [#fa("brand-mixer")], [brand-mizuni], [#fa("brand-mizuni")], [brand-modx], [#fa("brand-modx")],
[brand-monero], [#fa("brand-monero")], [brand-napster], [#fa("brand-napster")], [brand-neos], [#fa("brand-neos")],
[brand-nfc-directional],
[#fa("brand-nfc-directional")],
[brand-nfc-symbol],
[#fa("brand-nfc-symbol")],
[brand-nimblr],
[#fa("brand-nimblr")],
[brand-node-js], [#fa("brand-node-js")], [brand-node], [#fa("brand-node")], [brand-npm], [#fa("brand-npm")],
[brand-ns8],
[#fa("brand-ns8")],
[brand-nutritionix],
[#fa("brand-nutritionix")],
[brand-octopus-deploy],
[#fa("brand-octopus-deploy")],
[brand-odnoklassniki],
[#fa("brand-odnoklassniki")],
[brand-odysee],
[#fa("brand-odysee")],
[brand-old-republic],
[#fa("brand-old-republic")],
[brand-opencart],
[#fa("brand-opencart")],
[brand-openid],
[#fa("brand-openid")],
[brand-opera],
[#fa("brand-opera")],
[brand-optin-monster],
[#fa("brand-optin-monster")],
[brand-orcid],
[#fa("brand-orcid")],
[brand-osi],
[#fa("brand-osi")],
[brand-padlet],
[#fa("brand-padlet")],
[brand-page4],
[#fa("brand-page4")],
[brand-pagelines],
[#fa("brand-pagelines")],
[brand-palfed],
[#fa("brand-palfed")],
[brand-patreon],
[#fa("brand-patreon")],
[brand-paypal],
[#fa("brand-paypal")],
[brand-perbyte],
[#fa("brand-perbyte")],
[brand-periscope],
[#fa("brand-periscope")],
[brand-phabricator],
[#fa("brand-phabricator")],
[brand-phoenix-framework],
[#fa("brand-phoenix-framework")],
[brand-phoenix-squadron],
[#fa("brand-phoenix-squadron")],
[brand-php],
[#fa("brand-php")],
[brand-pied-piper-alt],
[#fa("brand-pied-piper-alt")],
[brand-pied-piper-hat],
[#fa("brand-pied-piper-hat")],
[brand-pied-piper-pp],
[#fa("brand-pied-piper-pp")],
[brand-pied-piper],
[#fa("brand-pied-piper")],
[brand-pinterest-p],
[#fa("brand-pinterest-p")],
[brand-pinterest],
[#fa("brand-pinterest")],
[brand-pix],
[#fa("brand-pix")],
[brand-playstation],
[#fa("brand-playstation")],
[brand-product-hunt],
[#fa("brand-product-hunt")],
[brand-pushed], [#fa("brand-pushed")], [brand-python], [#fa("brand-python")], [brand-qq], [#fa("brand-qq")],
[brand-quinscape],
[#fa("brand-quinscape")],
[brand-quora],
[#fa("brand-quora")],
[brand-r-project],
[#fa("brand-r-project")],
[brand-raspberry-pi],
[#fa("brand-raspberry-pi")],
[brand-ravelry],
[#fa("brand-ravelry")],
[brand-react],
[#fa("brand-react")],
[brand-reacteurope],
[#fa("brand-reacteurope")],
[brand-readme],
[#fa("brand-readme")],
[brand-rebel],
[#fa("brand-rebel")],
[brand-red-river],
[#fa("brand-red-river")],
[brand-reddit-alien],
[#fa("brand-reddit-alien")],
[brand-reddit],
[#fa("brand-reddit")],
[brand-redhat],
[#fa("brand-redhat")],
[brand-renren],
[#fa("brand-renren")],
[brand-replyd],
[#fa("brand-replyd")],
[brand-researchgate],
[#fa("brand-researchgate")],
[brand-resolving],
[#fa("brand-resolving")],
[brand-rev],
[#fa("brand-rev")],
[brand-rocketchat],
[#fa("brand-rocketchat")],
[brand-rockrms],
[#fa("brand-rockrms")],
[brand-rust],
[#fa("brand-rust")],
)],
)
#pagebreak()
== S-V
#figure(
align(center)[#table(
columns: 6,
[brand-safari],
[#fa("brand-safari")],
[brand-salesforce],
[#fa("brand-salesforce")],
[brand-sass],
[#fa("brand-sass")],
[brand-schlix],
[#fa("brand-schlix")],
[brand-screenpal],
[#fa("brand-screenpal")],
[brand-scribd],
[#fa("brand-scribd")],
[brand-searchengin],
[#fa("brand-searchengin")],
[brand-sellcast],
[#fa("brand-sellcast")],
[brand-sellsy],
[#fa("brand-sellsy")],
[brand-servicestack],
[#fa("brand-servicestack")],
[brand-shirtsinbulk],
[#fa("brand-shirtsinbulk")],
[brand-shopify],
[#fa("brand-shopify")],
[brand-shopware],
[#fa("brand-shopware")],
[brand-simplybuilt],
[#fa("brand-simplybuilt")],
[brand-sistrix],
[#fa("brand-sistrix")],
[brand-sith], [#fa("brand-sith")], [brand-sitrox], [#fa("brand-sitrox")], [brand-sketch], [#fa("brand-sketch")],
[brand-skyatlas],
[#fa("brand-skyatlas")],
[brand-skype],
[#fa("brand-skype")],
[brand-slack],
[#fa("brand-slack")],
[brand-slideshare],
[#fa("brand-slideshare")],
[brand-snapchat],
[#fa("brand-snapchat")],
[brand-soundcloud],
[#fa("brand-soundcloud")],
[brand-sourcetree],
[#fa("brand-sourcetree")],
[brand-space-awesome],
[#fa("brand-space-awesome")],
[brand-speakap],
[#fa("brand-speakap")],
[brand-speaker-deck],
[#fa("brand-speaker-deck")],
[brand-spotify],
[#fa("brand-spotify")],
[brand-stack-exchange],
[#fa("brand-stack-exchange")],
[brand-stack-overflow],
[#fa("brand-stack-overflow")],
[brand-stackpath],
[#fa("brand-stackpath")],
[brand-staylinked],
[#fa("brand-staylinked")],
[brand-steam-symbol],
[#fa("brand-steam-symbol")],
[brand-steam],
[#fa("brand-steam")],
[brand-sticker-mule],
[#fa("brand-sticker-mule")],
[brand-strava],
[#fa("brand-strava")],
[brand-stripe-s],
[#fa("brand-stripe-s")],
[brand-stripe],
[#fa("brand-stripe")],
[brand-stubber],
[#fa("brand-stubber")],
[brand-studiovinari],
[#fa("brand-studiovinari")],
[brand-stumbleupon-circle],
[#fa("brand-stumbleupon-circle")],
[brand-stumbleupon],
[#fa("brand-stumbleupon")],
[brand-superpowers],
[#fa("brand-superpowers")],
[brand-supple],
[#fa("brand-supple")],
[brand-suse], [#fa("brand-suse")], [brand-swift], [#fa("brand-swift")], [brand-symfony], [#fa("brand-symfony")],
[brand-teamspeak],
[#fa("brand-teamspeak")],
[brand-telegram],
[#fa("brand-telegram")],
[brand-tencent-weibo],
[#fa("brand-tencent-weibo")],
[brand-the-red-yeti],
[#fa("brand-the-red-yeti")],
[brand-themeco],
[#fa("brand-themeco")],
[brand-themeisle],
[#fa("brand-themeisle")],
[brand-think-peaks],
[#fa("brand-think-peaks")],
[brand-threads],
[#fa("brand-threads")],
[brand-tiktok],
[#fa("brand-tiktok")],
[brand-trade-federation],
[#fa("brand-trade-federation")],
[brand-trello],
[#fa("brand-trello")],
[brand-tumblr],
[#fa("brand-tumblr")],
[brand-twitch],
[#fa("brand-twitch")],
[brand-twitter],
[#fa("brand-twitter")],
[brand-typo3],
[#fa("brand-typo3")],
[brand-uber], [#fa("brand-uber")], [brand-ubuntu], [#fa("brand-ubuntu")], [brand-uikit], [#fa("brand-uikit")],
[brand-umbraco],
[#fa("brand-umbraco")],
[brand-uncharted],
[#fa("brand-uncharted")],
[brand-uniregistry],
[#fa("brand-uniregistry")],
[brand-unity],
[#fa("brand-unity")],
[brand-unsplash],
[#fa("brand-unsplash")],
[brand-untappd],
[#fa("brand-untappd")],
[brand-ups], [#fa("brand-ups")], [brand-usb], [#fa("brand-usb")], [brand-usps], [#fa("brand-usps")],
[brand-ussunnah],
[#fa("brand-ussunnah")],
[brand-vaadin],
[#fa("brand-vaadin")],
[brand-viacoin],
[#fa("brand-viacoin")],
[brand-viadeo],
[#fa("brand-viadeo")],
[brand-viber],
[#fa("brand-viber")],
[brand-vimeo-v],
[#fa("brand-vimeo-v")],
[brand-vimeo], [#fa("brand-vimeo")], [brand-vine], [#fa("brand-vine")], [brand-vk], [#fa("brand-vk")],
[brand-vnv], [#fa("brand-vnv")], [brand-vuejs], [#fa("brand-vuejs")],
)],
)
#pagebreak()
=== Square
#figure(
align(center)[#table(
columns: 4,
[brand-square-behance], [#fa("brand-square-behance")], [brand-square-dribbble], [#fa("brand-square-dribbble")],
[brand-square-facebook],
[#fa("brand-square-facebook")],
[brand-square-font-awesome-stroke],
[#fa("brand-square-font-awesome-stroke")],
[brand-square-font-awesome], [#fa("brand-square-font-awesome")], [brand-square-git], [#fa("brand-square-git")],
[brand-square-github], [#fa("brand-square-github")], [brand-square-gitlab], [#fa("brand-square-gitlab")],
[brand-square-google-plus],
[#fa("brand-square-google-plus")],
[brand-square-hacker-news],
[#fa("brand-square-hacker-news")],
[brand-square-instagram], [#fa("brand-square-instagram")], [brand-square-js], [#fa("brand-square-js")],
[brand-square-lastfm],
[#fa("brand-square-lastfm")],
[brand-square-odnoklassniki],
[#fa("brand-square-odnoklassniki")],
[brand-square-pied-piper],
[#fa("brand-square-pied-piper")],
[brand-square-pinterest],
[#fa("brand-square-pinterest")],
[brand-square-reddit], [#fa("brand-square-reddit")], [brand-square-snapchat], [#fa("brand-square-snapchat")],
[brand-square-steam], [#fa("brand-square-steam")], [brand-square-threads], [#fa("brand-square-threads")],
[brand-square-tumblr], [#fa("brand-square-tumblr")], [brand-square-twitter], [#fa("brand-square-twitter")],
[brand-square-viadeo], [#fa("brand-square-viadeo")], [brand-square-vimeo], [#fa("brand-square-vimeo")],
[brand-square-whatsapp],
[#fa("brand-square-whatsapp")],
[brand-square-x-twitter],
[#fa("brand-square-x-twitter")],
[brand-square-xing], [#fa("brand-square-xing")], [brand-square-youtube], [#fa("brand-square-youtube")],
[brand-squarespace], [#fa("brand-squarespace")],
)],
)
== W-Z
#figure(
align(center)[#table(
columns: 6,
[brand-watchman-monitoring],
[#fa("brand-watchman-monitoring")],
[brand-waze],
[#fa("brand-waze")],
[brand-weebly],
[#fa("brand-weebly")],
[brand-weibo],
[#fa("brand-weibo")],
[brand-weixin],
[#fa("brand-weixin")],
[brand-whatsapp],
[#fa("brand-whatsapp")],
[brand-whmcs],
[#fa("brand-whmcs")],
[brand-wikipedia-w],
[#fa("brand-wikipedia-w")],
[brand-windows],
[#fa("brand-windows")],
[brand-wirsindhandwerk],
[#fa("brand-wirsindhandwerk")],
[brand-wix],
[#fa("brand-wix")],
[brand-wizards-of-the-coast],
[#fa("brand-wizards-of-the-coast")],
[brand-wodu],
[#fa("brand-wodu")],
[brand-wolf-pack-battalion],
[#fa("brand-wolf-pack-battalion")],
[brand-wordpress-simple],
[#fa("brand-wordpress-simple")],
[brand-wordpress],
[#fa("brand-wordpress")],
[brand-wpbeginner],
[#fa("brand-wpbeginner")],
[brand-wpexplorer],
[#fa("brand-wpexplorer")],
[brand-wpforms],
[#fa("brand-wpforms")],
[brand-wpressr],
[#fa("brand-wpressr")],
[brand-x-twitter],
[#fa("brand-x-twitter")],
[brand-xbox],
[#fa("brand-xbox")],
[brand-xing],
[#fa("brand-xing")],
[brand-y-combinator],
[#fa("brand-y-combinator")],
[brand-yahoo],
[#fa("brand-yahoo")],
[brand-yammer],
[#fa("brand-yammer")],
[brand-yandex-international],
[#fa("brand-yandex-international")],
[brand-yandex], [#fa("brand-yandex")], [brand-yarn], [#fa("brand-yarn")], [brand-yelp], [#fa("brand-yelp")],
[brand-yoast], [#fa("brand-yoast")], [brand-youtube], [#fa("brand-youtube")], [brand-zhihu], [#fa("brand-zhihu")],
)],
)
#pagebreak()
= Regular
<Regular>
== A-E
#figure(
align(center)[#table(
columns: 6,
align: center,
[reg-address-book],
[#fa("reg-address-book")],
[reg-address-card],
[#fa("reg-address-card")],
[reg-bell-slash],
[#fa("reg-bell-slash")],
[reg-bell], [#fa("reg-bell")], [reg-bookmark], [#fa("reg-bookmark")], [reg-building], [#fa("reg-building")],
[reg-calendar-check],
[#fa("reg-calendar-check")],
[reg-calendar-days],
[#fa("reg-calendar-days")],
[reg-calendar-minus],
[#fa("reg-calendar-minus")],
[reg-calendar-plus],
[#fa("reg-calendar-plus")],
[reg-calendar-xmark],
[#fa("reg-calendar-xmark")],
[reg-calendar],
[#fa("reg-calendar")],
[reg-chart-bar],
[#fa("reg-chart-bar")],
[reg-chess-bishop],
[#fa("reg-chess-bishop")],
[reg-chess-king],
[#fa("reg-chess-king")],
[reg-chess-knight],
[#fa("reg-chess-knight")],
[reg-chess-pawn],
[#fa("reg-chess-pawn")],
[reg-chess-queen],
[#fa("reg-chess-queen")],
[reg-chess-rook],
[#fa("reg-chess-rook")],
[reg-circle-check],
[#fa("reg-circle-check")],
[reg-circle-dot],
[#fa("reg-circle-dot")],
[reg-circle-down],
[#fa("reg-circle-down")],
[reg-circle-left],
[#fa("reg-circle-left")],
[reg-circle-pause],
[#fa("reg-circle-pause")],
[reg-circle-play],
[#fa("reg-circle-play")],
[reg-circle-question],
[#fa("reg-circle-question")],
[reg-circle-right],
[#fa("reg-circle-right")],
[reg-circle-stop],
[#fa("reg-circle-stop")],
[reg-circle-up],
[#fa("reg-circle-up")],
[reg-circle-user],
[#fa("reg-circle-user")],
[reg-circle-xmark],
[#fa("reg-circle-xmark")],
[reg-circle],
[#fa("reg-circle")],
[reg-clipboard],
[#fa("reg-clipboard")],
[reg-clock],
[#fa("reg-clock")],
[reg-clone],
[#fa("reg-clone")],
[reg-closed-captioning],
[#fa("reg-closed-captioning")],
[reg-comment-dots],
[#fa("reg-comment-dots")],
[reg-comment],
[#fa("reg-comment")],
[reg-comments],
[#fa("reg-comments")],
[reg-compass], [#fa("reg-compass")], [reg-copy], [#fa("reg-copy")], [reg-copyright], [#fa("reg-copyright")],
[reg-credit-card],
[#fa("reg-credit-card")],
[reg-envelope-open],
[#fa("reg-envelope-open")],
[reg-envelope],
[#fa("reg-envelope")],
[reg-eye-slash],
[#fa("reg-eye-slash")],
[reg-eye],
[#fa("reg-eye")],
[reg-freg-ile-audio],
[#fa("reg-file-audio")],
[reg-file-code],
[#fa("reg-file-code")],
[reg-file-excel],
[#fa("reg-file-excel")],
[reg-file-image],
[#fa("reg-file-image")],
[reg-file-lines],
[#fa("reg-file-lines")],
[reg-file-pdf],
[#fa("reg-file-pdf")],
[reg-file-powerpoint],
[#fa("reg-file-powerpoint")],
[reg-file-video],
[#fa("reg-file-video")],
[reg-file-word],
[#fa("reg-file-word")],
[reg-file-zipper],
[#fa("reg-file-zipper")],
[reg-file], [#fa("reg-file")], [reg-flag], [#fa("reg-flag")], [reg-floppy-disk], [#fa("reg-floppy-disk")],
[reg-folder-closed],
[#fa("reg-folder-closed")],
[reg-folder-open],
[#fa("reg-folder-open")],
[reg-folder],
[#fa("reg-folder")],
[reg-font-awesome], [#fa("reg-font-awesome")], [reg-futbol], [#fa("reg-futbol")], [reg-gem], [#fa("reg-gem")],
[reg-hand-back-fist],
[#fa("reg-hand-back-fist")],
[reg-hand-lizard],
[#fa("reg-hand-lizard")],
[reg-hand-peace],
[#fa("reg-hand-peace")],
[reg-hand-point-down],
[#fa("reg-hand-point-down")],
[reg-hand-point-left],
[#fa("reg-hand-point-left")],
[reg-hand-point-right],
[#fa("reg-hand-point-right")],
[reg-hand-point-up],
[#fa("reg-hand-point-up")],
[reg-hand-pointer],
[#fa("reg-hand-pointer")],
[reg-hand-scissors],
[#fa("reg-hand-scissors")],
[reg-hand-spock], [#fa("reg-hand-spock")], [reg-hand], [#fa("reg-hand")], [reg-handshake], [#fa("reg-handshake")],
[reg-hard-drive], [#fa("reg-hard-drive")], [reg-heart], [#fa("reg-heart")], [reg-hospital], [#fa("reg-hospital")],
[reg-hourglass-half],
[#fa("reg-hourglass-half")],
[reg-hourglass],
[#fa("reg-hourglass")],
[reg-id-badge],
[#fa("reg-id-badge")],
[reg-id-card], [#fa("reg-id-card")], [reg-image], [#fa("reg-image")], [reg-images], [#fa("reg-images")],
[reg-keyboard], [#fa("reg-keyboard")], [reg-lemon], [#fa("reg-lemon")], [reg-life-ring], [#fa("reg-life-ring")],
[reg-lightbulb], [#fa("reg-lightbulb")],
)],
)
#pagebreak(weak: true)
== M-W
#figure(
align(center)[#table(
columns: 6,
[reg-map], [#fa("reg-map")], [reg-message], [#fa("reg-message")], [reg-money-bill-1], [#fa("reg-money-bill-1")],
[reg-moon],
[#fa("reg-moon")],
[reg-newspaper],
[#fa("reg-newspaper")],
[reg-note-sticky],
[#fa("reg-note-sticky")],
[reg-object-group],
[#fa("reg-object-group")],
[reg-object-ungroup],
[#fa("reg-object-ungroup")],
[reg-paper-plane],
[#fa("reg-paper-plane")],
[reg-paste],
[#fa("reg-paste")],
[reg-pen-to-square],
[#fa("reg-pen-to-square")],
[reg-rectangle-list],
[#fa("reg-rectangle-list")],
[reg-rectangle-xmark],
[#fa("reg-rectangle-xmark")],
[reg-registered],
[#fa("reg-registered")],
[reg-share-from-square],
[#fa("reg-share-from-square")],
[reg-snowflake],
[#fa("reg-snowflake")],
[reg-star-half-stroke],
[#fa("reg-star-half-stroke")],
[reg-star-half],
[#fa("reg-star-half")],
[reg-star], [#fa("reg-star")], [reg-sun], [#fa("reg-sun")], [reg-thumbs-down], [#fa("reg-thumbs-down")],
[reg-thumbs-up], [#fa("reg-thumbs-up")], [reg-trash-can], [#fa("reg-trash-can")], [reg-user], [#fa("reg-user")],
[reg-window-maximize],
[#fa("reg-window-maximize")],
[reg-window-minimize],
[#fa("reg-window-minimize")],
[reg-window-restore],
[#fa("reg-window-restore")],
)],
)
=== Face
#figure(
align(center)[#table(
columns: 6,
[reg-face-angry],
[#fa("reg-face-angry")],
[reg-face-dizzy],
[#fa("reg-face-dizzy")],
[reg-face-flushed],
[#fa("reg-face-flushed")],
[reg-face-frown-open],
[#fa("reg-face-frown-open")],
[reg-face-frown],
[#fa("reg-face-frown")],
[reg-face-grimace],
[#fa("reg-face-grimace")],
[reg-face-grin-beam-sweat],
[#fa("reg-face-grin-beam-sweat")],
[reg-face-grin-beam],
[#fa("reg-face-grin-beam")],
[reg-face-grin-hearts],
[#fa("reg-face-grin-hearts")],
[reg-face-grin-squint-tears],
[#fa("reg-face-grin-squint-tears")],
[reg-face-grin-squint],
[#fa("reg-face-grin-squint")],
[reg-face-grin-stars],
[#fa("reg-face-grin-stars")],
[reg-face-grin-tears],
[#fa("reg-face-grin-tears")],
[reg-face-grin-tongue-squint],
[#fa("reg-face-grin-tongue-squint")],
[reg-face-grin-tongue-wink],
[#fa("reg-face-grin-tongue-wink")],
[reg-face-grin-tongue],
[#fa("reg-face-grin-tongue")],
[reg-face-grin-wide],
[#fa("reg-face-grin-wide")],
[reg-face-grin-wink],
[#fa("reg-face-grin-wink")],
[reg-face-grin],
[#fa("reg-face-grin")],
[reg-face-kiss-beam],
[#fa("reg-face-kiss-beam")],
[reg-face-kiss-wink-heart],
[#fa("reg-face-kiss-wink-heart")],
[reg-face-kiss],
[#fa("reg-face-kiss")],
[reg-face-laugh-beam],
[#fa("reg-face-laugh-beam")],
[reg-face-laugh-squint],
[#fa("reg-face-laugh-squint")],
[reg-face-laugh-wink],
[#fa("reg-face-laugh-wink")],
[reg-face-laugh],
[#fa("reg-face-laugh")],
[reg-face-meh-blank],
[#fa("reg-face-meh-blank")],
[reg-face-meh],
[#fa("reg-face-meh")],
[reg-face-rolling-eyes],
[#fa("reg-face-rolling-eyes")],
[reg-face-sad-cry],
[#fa("reg-face-sad-cry")],
[reg-face-sad-tear],
[#fa("reg-face-sad-tear")],
[reg-face-smile-beam],
[#fa("reg-face-smile-beam")],
[reg-face-smile-wink],
[#fa("reg-face-smile-wink")],
[reg-face-smile],
[#fa("reg-face-smile")],
[reg-face-surprise],
[#fa("reg-face-surprise")],
[reg-face-tired],
[#fa("reg-face-tired")],
)],
)
=== Square
#figure(
align(center)[#table(
columns: 6,
[reg-square-caret-down],
[#fa("reg-square-caret-down")],
[reg-square-caret-left],
[#fa("reg-square-caret-left")],
[reg-square-caret-right],
[#fa("reg-square-caret-right")],
[reg-square-caret-up],
[#fa("reg-square-caret-up")],
[reg-square-check],
[#fa("reg-square-check")],
[reg-square-full],
[#fa("reg-square-full")],
[reg-square-minus],
[#fa("reg-square-minus")],
[reg-square-plus],
[#fa("reg-square-plus")],
[reg-square],
[#fa("reg-square")],
)],
)
#pagebreak()
= Solid
== A
#figure(
align(center)[#table(
columns: 8,
align: center,
[solid-0],
[#fa("solid-0")],
[solid-1],
[#fa("solid-1")],
[solid-2],
[#fa("solid-2")],
[solid-3],
[#fa("solid-3")],
[solid-4],
[#fa("solid-4")],
[solid-5],
[#fa("solid-5")],
[solid-6],
[#fa("solid-6")],
[solid-7],
[#fa("solid-7")],
[solid-8], [#fa("solid-8")], [solid-9], [#fa("solid-9")], [a], [#fa("a")], [address-book], [#fa("address-book")],
[address-card],
[#fa("address-card")],
[align-center],
[#fa("align-center")],
[align-justify],
[#fa("align-justify")],
[align-left],
[#fa("align-left")],
[align-right],
[#fa("align-right")],
[ankh],
[#fa("ankh")],
[apple-whole],
[#fa("apple-whole")],
[archway],
[#fa("archway")],
[asterisk],
[#fa("asterisk")],
[at],
[#fa("at")],
[atom],
[#fa("atom")],
[audio-description],
[#fa("audio-description")],
[austral-sign], [#fa("austral-sign")], [award], [#fa("award")],
)],
)
=== Angle, Anchor
#figure(
align(center)[#table(
columns: 6,
[angle-down], [#fa("angle-down")], [angle-left], [#fa("angle-left")], [angle-right], [#fa("angle-right")],
[angle-up], [#fa("angle-up")], [angles-down], [#fa("angles-down")], [angles-left], [#fa("angles-left")],
[angles-right],
[#fa("angles-right")],
[angles-up],
[#fa("angles-up")],
[anchor-circle-check],
[#fa("anchor-circle-check")],
[anchor-circle-exclamation],
[#fa("anchor-circle-exclamation")],
[anchor-circle-xmark],
[#fa("anchor-circle-xmark")],
[anchor-lock],
[#fa("anchor-lock")],
[anchor], [#fa("anchor")],
)],
)
=== Battery, Bridge, Building
#figure(
align(center)[#table(
columns: 6,
[battery-empty],
[#fa("battery-empty")],
[battery-full],
[#fa("battery-full")],
[battery-half],
[#fa("battery-half")],
[battery-quarter],
[#fa("battery-quarter")],
[battery-three-quarters],
[#fa("battery-three-quarters")],
[bridge-circle-check],
[#fa("bridge-circle-check")],
[bridge-circle-exclamation],
[#fa("bridge-circle-exclamation")],
[bridge-circle-xmark],
[#fa("bridge-circle-xmark")],
[bridge-lock],
[#fa("bridge-lock")],
[bridge-water],
[#fa("bridge-water")],
[bridge],
[#fa("bridge")],
[building-circle-arrow-right],
[#fa("building-circle-arrow-right")],
[building-circle-check],
[#fa("building-circle-check")],
[building-circle-exclamation],
[#fa("building-circle-exclamation")],
[building-circle-xmark],
[#fa("building-circle-xmark")],
[building-columns],
[#fa("building-columns")],
[building-flag],
[#fa("building-flag")],
[building-lock],
[#fa("building-lock")],
[building-ngo],
[#fa("building-ngo")],
[building-shield],
[#fa("building-shield")],
[building-un],
[#fa("building-un")],
[building-user], [#fa("building-user")], [building-wheat], [#fa("building-wheat")], [building], [#fa("building")],
)],
)
#pagebreak()
=== Arrow
#figure(
align(center)[#table(
columns: 4,
[arrow-down-1-9], [#fa("arrow-down-1-9")], [arrow-down-9-1], [#fa("arrow-down-9-1")],
[arrow-down-a-z], [#fa("arrow-down-a-z")], [arrow-down-long], [#fa("arrow-down-long")],
[arrow-down-short-wide],
[#fa("arrow-down-short-wide")],
[arrow-down-up-across-line],
[#fa("arrow-down-up-across-line")],
[arrow-down-up-lock], [#fa("arrow-down-up-lock")], [arrow-down-wide-short], [#fa("arrow-down-wide-short")],
[arrow-down-z-a], [#fa("arrow-down-z-a")], [arrow-down], [#fa("arrow-down")],
[arrow-left-long], [#fa("arrow-left-long")], [arrow-left], [#fa("arrow-left")],
[arrow-pointer], [#fa("arrow-pointer")], [arrow-right-arrow-left], [#fa("arrow-right-arrow-left")],
[arrow-right-from-bracket], [#fa("arrow-right-from-bracket")], [arrow-right-long], [#fa("arrow-right-long")],
[arrow-right-to-bracket], [#fa("arrow-right-to-bracket")], [arrow-right-to-city], [#fa("arrow-right-to-city")],
[arrow-right], [#fa("arrow-right")], [arrow-rotate-left], [#fa("arrow-rotate-left")],
[arrow-rotate-right], [#fa("arrow-rotate-right")], [arrow-trend-down], [#fa("arrow-trend-down")],
[arrow-trend-up], [#fa("arrow-trend-up")], [arrow-turn-down], [#fa("arrow-turn-down")],
[arrow-turn-up], [#fa("arrow-turn-up")], [arrow-up-1-9], [#fa("arrow-up-1-9")],
[arrow-up-9-1], [#fa("arrow-up-9-1")], [arrow-up-a-z], [#fa("arrow-up-a-z")],
[arrow-up-from-bracket],
[#fa("arrow-up-from-bracket")],
[arrow-up-from-ground-water],
[#fa("arrow-up-from-ground-water")],
[arrow-up-from-water-pump], [#fa("arrow-up-from-water-pump")], [arrow-up-long], [#fa("arrow-up-long")],
[arrow-up-right-dots],
[#fa("arrow-up-right-dots")],
[arrow-up-right-from-square],
[#fa("arrow-up-right-from-square")],
[arrow-up-short-wide], [#fa("arrow-up-short-wide")], [arrow-up-wide-short], [#fa("arrow-up-wide-short")],
[arrow-up-z-a], [#fa("arrow-up-z-a")], [arrow-up], [#fa("arrow-up")],
[arrows-down-to-line], [#fa("arrows-down-to-line")], [arrows-down-to-people], [#fa("arrows-down-to-people")],
[arrows-left-right-to-line], [#fa("arrows-left-right-to-line")], [arrows-left-right], [#fa("arrows-left-right")],
[arrows-rotate], [#fa("arrows-rotate")], [arrows-spin], [#fa("arrows-spin")],
[arrows-split-up-and-left], [#fa("arrows-split-up-and-left")], [arrows-to-circle], [#fa("arrows-to-circle")],
[arrows-to-dot], [#fa("arrows-to-dot")], [arrows-to-eye], [#fa("arrows-to-eye")],
[arrows-turn-right], [#fa("arrows-turn-right")], [arrows-turn-to-dots], [#fa("arrows-turn-to-dots")],
[arrows-up-down-left-right], [#fa("arrows-up-down-left-right")], [arrows-up-down], [#fa("arrows-up-down")],
[arrows-up-to-line], [#fa("arrows-up-to-line")],
)],
)
#pagebreak()
== B
#figure(
align(center)[#table(
columns: 8,
[b],
[#fa("b")],
[baby-carriage],
[#fa("baby-carriage")],
[baby],
[#fa("baby")],
[backward-fast],
[#fa("backward-fast")],
[backward-step],
[#fa("backward-step")],
[backward],
[#fa("backward")],
[bacon],
[#fa("bacon")],
[bacteria],
[#fa("bacteria")],
[bacterium],
[#fa("bacterium")],
[bag-shopping],
[#fa("bag-shopping")],
[bahai],
[#fa("bahai")],
[baht-sign],
[#fa("baht-sign")],
[ban-smoking],
[#fa("ban-smoking")],
[ban],
[#fa("ban")],
[bandage],
[#fa("bandage")],
[bangladeshi-taka-sign],
[#fa("bangladeshi-taka-sign")],
[barcode],
[#fa("barcode")],
[bars-progress],
[#fa("bars-progress")],
[bars-staggered],
[#fa("bars-staggered")],
[bars],
[#fa("bars")],
[baseball-bat-ball],
[#fa("baseball-bat-ball")],
[baseball],
[#fa("baseball")],
[basket-shopping],
[#fa("basket-shopping")],
[basketball],
[#fa("basketball")],
[bath],
[#fa("bath")],
[bed-pulse],
[#fa("bed-pulse")],
[bed],
[#fa("bed")],
[beer-mug-empty],
[#fa("beer-mug-empty")],
[bell-concierge],
[#fa("bell-concierge")],
[bell-slash],
[#fa("bell-slash")],
[bell],
[#fa("bell")],
[bezier-curve],
[#fa("bezier-curve")],
[bicycle],
[#fa("bicycle")],
[binoculars],
[#fa("binoculars")],
[biohazard],
[#fa("biohazard")],
[bitcoin-sign],
[#fa("bitcoin-sign")],
[blender-phone],
[#fa("blender-phone")],
[blender],
[#fa("blender")],
[blog],
[#fa("blog")],
[bold],
[#fa("bold")],
[bolt-lightning], [#fa("bolt-lightning")], [bolt], [#fa("bolt")], [bomb], [#fa("bomb")], [bone], [#fa("bone")],
[bong],
[#fa("bong")],
[book-atlas],
[#fa("book-atlas")],
[book-bible],
[#fa("book-bible")],
[book-bookmark],
[#fa("book-bookmark")],
[book-journal-whills],
[#fa("book-journal-whills")],
[book-medical],
[#fa("book-medical")],
[book-open-reader],
[#fa("book-open-reader")],
[book-open],
[#fa("book-open")],
[book-quran],
[#fa("book-quran")],
[book-skull],
[#fa("book-skull")],
[book-tanakh],
[#fa("book-tanakh")],
[book],
[#fa("book")],
[bookmark],
[#fa("bookmark")],
[border-all],
[#fa("border-all")],
[border-none],
[#fa("border-none")],
[border-top-left],
[#fa("border-top-left")],
[bore-hole],
[#fa("bore-hole")],
[bottle-droplet],
[#fa("bottle-droplet")],
[bottle-water],
[#fa("bottle-water")],
[bowl-food],
[#fa("bowl-food")],
[bowl-rice],
[#fa("bowl-rice")],
[bowling-ball],
[#fa("bowling-ball")],
[box-archive],
[#fa("box-archive")],
[box-open],
[#fa("box-open")],
[box-tissue],
[#fa("box-tissue")],
[box],
[#fa("box")],
[boxes-packing],
[#fa("boxes-packing")],
[boxes-stacked],
[#fa("boxes-stacked")],
[braille],
[#fa("braille")],
[brain],
[#fa("brain")],
[brazilian-real-sign],
[#fa("brazilian-real-sign")],
[bread-slice],
[#fa("bread-slice")],
[briefcase-medical],
[#fa("briefcase-medical")],
[briefcase],
[#fa("briefcase")],
[broom-ball],
[#fa("broom-ball")],
[broom],
[#fa("broom")],
[brush], [#fa("brush")], [bucket], [#fa("bucket")], [bug-slash], [#fa("bug-slash")], [bug], [#fa("bug")],
[bugs], [#fa("bugs")], [bullhorn], [#fa("bullhorn")], [bullseye], [#fa("bullseye")], [burger], [#fa("burger")],
[burst],
[#fa("burst")],
[bus-simple],
[#fa("bus-simple")],
[bus],
[#fa("bus")],
[business-time],
[#fa("business-time")],
)],
)
#pagebreak()
== C
#figure(
align(center)[#table(
columns: 8,
[c],
[#fa("c")],
[cable-car],
[#fa("cable-car")],
[calculator],
[#fa("calculator")],
[cake-candles],
[#fa("cake-candles")],
[camera-retro],
[#fa("camera-retro")],
[camera-rotate],
[#fa("camera-rotate")],
[camera],
[#fa("camera")],
[campground],
[#fa("campground")],
[candy-cane],
[#fa("candy-cane")],
[cannabis],
[#fa("cannabis")],
[capsules],
[#fa("capsules")],
[car-battery],
[#fa("car-battery")],
[car-burst],
[#fa("car-burst")],
[car-on],
[#fa("car-on")],
[car-rear],
[#fa("car-rear")],
[car-side],
[#fa("car-side")],
[car-tunnel],
[#fa("car-tunnel")],
[car],
[#fa("car")],
[caravan],
[#fa("caravan")],
[caret-down],
[#fa("caret-down")],
[caret-left],
[#fa("caret-left")],
[caret-right],
[#fa("caret-right")],
[caret-up],
[#fa("caret-up")],
[carrot],
[#fa("carrot")],
[cash-register],
[#fa("cash-register")],
[cat],
[#fa("cat")],
[cedi-sign],
[#fa("cedi-sign")],
[cent-sign],
[#fa("cent-sign")],
[certificate],
[#fa("certificate")],
[chair],
[#fa("chair")],
[chalkboard-user],
[#fa("chalkboard-user")],
[chalkboard],
[#fa("chalkboard")],
[champagne-glasses],
[#fa("champagne-glasses")],
[charging-station],
[#fa("charging-station")],
[check-double],
[#fa("check-double")],
[check-to-slot],
[#fa("check-to-slot")],
[check],
[#fa("check")],
[cheese],
[#fa("cheese")],
[chess-bishop],
[#fa("chess-bishop")],
[chess-board],
[#fa("chess-board")],
[chess-king],
[#fa("chess-king")],
[chess-knight],
[#fa("chess-knight")],
[chess-pawn],
[#fa("chess-pawn")],
[chess-queen],
[#fa("chess-queen")],
[chess-rook],
[#fa("chess-rook")],
[chess],
[#fa("chess")],
[chevron-down],
[#fa("chevron-down")],
[chevron-left],
[#fa("chevron-left")],
[chevron-right],
[#fa("chevron-right")],
[chevron-up],
[#fa("chevron-up")],
[child-combatant],
[#fa("child-combatant")],
[child-dress],
[#fa("child-dress")],
[child-reaching],
[#fa("child-reaching")],
[child],
[#fa("child")],
[children],
[#fa("children")],
[church],
[#fa("church")],
[city],
[#fa("city")],
[clapperboard],
[#fa("clapperboard")],
[clock-rotate-left],
[#fa("clock-rotate-left")],
[clock],
[#fa("clock")],
[clone],
[#fa("clone")],
[closed-captioning],
[#fa("closed-captioning")],
[coins],
[#fa("coins")],
[colon-sign],
[#fa("colon-sign")],
[clover],
[#fa("clover")],
[compact-disc],
[#fa("compact-disc")],
[compass-drafting],
[#fa("compass-drafting")],
[compass],
[#fa("compass")],
[compress],
[#fa("compress")],
[computer-mouse],
[#fa("computer-mouse")],
[computer],
[#fa("computer")],
[cookie-bite],
[#fa("cookie-bite")],
[cookie], [#fa("cookie")], [copy], [#fa("copy")], [copyright], [#fa("copyright")], [couch], [#fa("couch")],
[cow],
[#fa("cow")],
[credit-card],
[#fa("credit-card")],
[crop-simple],
[#fa("crop-simple")],
[crop],
[#fa("crop")],
[cross], [#fa("cross")], [crosshairs], [#fa("crosshairs")], [crow], [#fa("crow")], [crown], [#fa("crown")],
[crutch],
[#fa("crutch")],
[cruzeiro-sign],
[#fa("cruzeiro-sign")],
[cube],
[#fa("cube")],
[cubes-stacked],
[#fa("cubes-stacked")],
[cubes], [#fa("cubes")],
)],
)
#pagebreak()
=== Calendar, Cart, Chart
#figure(
align(center)[#table(
columns: 8,
[calendar-check],
[#fa("calendar-check")],
[calendar-day],
[#fa("calendar-day")],
[calendar-days],
[#fa("calendar-days")],
[calendar-minus],
[#fa("calendar-minus")],
[calendar-plus],
[#fa("calendar-plus")],
[calendar-week],
[#fa("calendar-week")],
[calendar-xmark],
[#fa("calendar-xmark")],
[calendar],
[#fa("calendar")],
[cart-arrow-down],
[#fa("cart-arrow-down")],
[cart-flatbed-suitcase],
[#fa("cart-flatbed-suitcase")],
[cart-flatbed],
[#fa("cart-flatbed")],
[cart-plus],
[#fa("cart-plus")],
[cart-shopping],
[#fa("cart-shopping")],
[chart-area],
[#fa("chart-area")],
[chart-bar],
[#fa("chart-bar")],
[chart-column],
[#fa("chart-column")],
[chart-gantt],
[#fa("chart-gantt")],
[chart-line],
[#fa("chart-line")],
[chart-pie],
[#fa("chart-pie")],
[chart-simple],
[#fa("chart-simple")],
)],
)
=== Circle, Clipboard, Comment, Code
#figure(
align(center)[#table(
columns: 6,
[circle-arrow-down],
[#fa("circle-arrow-down")],
[circle-arrow-left],
[#fa("circle-arrow-left")],
[circle-arrow-right],
[#fa("circle-arrow-right")],
[circle-arrow-up],
[#fa("circle-arrow-up")],
[circle-check],
[#fa("circle-check")],
[circle-chevron-down],
[#fa("circle-chevron-down")],
[circle-chevron-left],
[#fa("circle-chevron-left")],
[circle-chevron-right],
[#fa("circle-chevron-right")],
[circle-chevron-up],
[#fa("circle-chevron-up")],
[circle-dollar-to-slot],
[#fa("circle-dollar-to-slot")],
[circle-dot],
[#fa("circle-dot")],
[circle-down],
[#fa("circle-down")],
[circle-exclamation],
[#fa("circle-exclamation")],
[circle-h],
[#fa("circle-h")],
[circle-half-stroke],
[#fa("circle-half-stroke")],
[circle-info], [#fa("circle-info")], [circle-left], [#fa("circle-left")], [circle-minus], [#fa("circle-minus")],
[circle-nodes],
[#fa("circle-nodes")],
[circle-notch],
[#fa("circle-notch")],
[circle-pause],
[#fa("circle-pause")],
[circle-play],
[#fa("circle-play")],
[circle-plus],
[#fa("circle-plus")],
[circle-question],
[#fa("circle-question")],
[circle-radiation],
[#fa("circle-radiation")],
[circle-right],
[#fa("circle-right")],
[circle-stop],
[#fa("circle-stop")],
[circle-up], [#fa("circle-up")], [circle-user], [#fa("circle-user")], [circle-xmark], [#fa("circle-xmark")],
[circle], [#fa("circle")], [clipboard-check], [#fa("clipboard-check")], [clipboard-list], [#fa("clipboard-list")],
[clipboard-question],
[#fa("clipboard-question")],
[clipboard-user],
[#fa("clipboard-user")],
[clipboard],
[#fa("clipboard")],
[cloud-arrow-down],
[#fa("cloud-arrow-down")],
[cloud-arrow-up],
[#fa("cloud-arrow-up")],
[cloud-bolt],
[#fa("cloud-bolt")],
[cloud-meatball],
[#fa("cloud-meatball")],
[cloud-moon-rain],
[#fa("cloud-moon-rain")],
[cloud-moon],
[#fa("cloud-moon")],
[cloud-rain],
[#fa("cloud-rain")],
[cloud-showers-heavy],
[#fa("cloud-showers-heavy")],
[cloud-showers-water],
[#fa("cloud-showers-water")],
[cloud-sun-rain], [#fa("cloud-sun-rain")], [cloud-sun], [#fa("cloud-sun")], [cloud], [#fa("cloud")],
[code-branch], [#fa("code-branch")], [code-commit], [#fa("code-commit")], [code-compare], [#fa("code-compare")],
[code-fork],
[#fa("code-fork")],
[code-merge],
[#fa("code-merge")],
[code-pull-request],
[#fa("code-pull-request")],
[code], [#fa("code")], [comment-dollar], [#fa("comment-dollar")], [comment-dots], [#fa("comment-dots")],
[comment-medical],
[#fa("comment-medical")],
[comment-slash],
[#fa("comment-slash")],
[comment-sms],
[#fa("comment-sms")],
[comment], [#fa("comment")], [comments-dollar], [#fa("comments-dollar")], [comments], [#fa("comments")],
)],
)
#pagebreak()
== D
#figure(
align(center)[#table(
columns: 6,
[d], [#fa("d")], [database], [#fa("database")], [delete-left], [#fa("delete-left")],
[democrat], [#fa("democrat")], [desktop], [#fa("desktop")], [dharmachakra], [#fa("dharmachakra")],
[diagram-next],
[#fa("diagram-next")],
[diagram-predecessor],
[#fa("diagram-predecessor")],
[diagram-project],
[#fa("diagram-project")],
[diagram-successor],
[#fa("diagram-successor")],
[diamond-turn-right],
[#fa("diamond-turn-right")],
[diamond],
[#fa("diamond")],
[dice-d6], [#fa("dice-d6")], [dice-d20], [#fa("dice-d20")], [dice-five], [#fa("dice-five")],
[dice-four], [#fa("dice-four")], [dice-one], [#fa("dice-one")], [dice-six], [#fa("dice-six")],
[dice-three], [#fa("dice-three")], [dice-two], [#fa("dice-two")], [dice], [#fa("dice")],
[disease], [#fa("disease")], [display], [#fa("display")], [divide], [#fa("divide")],
[dna], [#fa("dna")], [dog], [#fa("dog")], [dollar-sign], [#fa("dollar-sign")],
[dolly], [#fa("dolly")], [dong-sign], [#fa("dong-sign")], [door-closed], [#fa("door-closed")],
[door-open], [#fa("door-open")], [dove], [#fa("dove")], [down-long], [#fa("down-long")],
[download], [#fa("download")], [dragon], [#fa("dragon")], [draw-polygon], [#fa("draw-polygon")],
[droplet-slash], [#fa("droplet-slash")], [droplet], [#fa("droplet")], [drum-steelpan], [#fa("drum-steelpan")],
[drum], [#fa("drum")], [drumstick-bite], [#fa("drumstick-bite")], [dumbbell], [#fa("dumbbell")],
[dumpster-fire], [#fa("dumpster-fire")], [dumpster], [#fa("dumpster")], [dungeon], [#fa("dungeon")],
)],
)
== E
#figure(
align(center)[#table(
columns: 6,
[e], [#fa("e")], [ear-deaf], [#fa("ear-deaf")], [ear-listen], [#fa("ear-listen")],
[earth-africa],
[#fa("earth-africa")],
[earth-americas],
[#fa("earth-americas")],
[earth-asia],
[#fa("earth-asia")],
[earth-europe], [#fa("earth-europe")], [earth-oceania], [#fa("earth-oceania")], [egg], [#fa("egg")],
[eject], [#fa("eject")], [elevator], [#fa("elevator")], [ellipsis-vertical], [#fa("ellipsis-vertical")],
[ellipsis],
[#fa("ellipsis")],
[envelope-circle-check],
[#fa("envelope-circle-check")],
[envelope-open-text],
[#fa("envelope-open-text")],
[envelope-open], [#fa("envelope-open")], [envelope], [#fa("envelope")], [envelopes-bulk], [#fa("envelopes-bulk")],
[equals], [#fa("equals")], [eraser], [#fa("eraser")], [ethernet], [#fa("ethernet")],
[euro-sign], [#fa("euro-sign")], [exclamation], [#fa("exclamation")], [expand], [#fa("expand")],
[explosion], [#fa("explosion")], [eye-dropper], [#fa("eye-dropper")], [eye-low-vision], [#fa("eye-low-vision")],
[eye-slash], [#fa("eye-slash")], [eye], [#fa("eye")],
)],
)
#pagebreak()
== F
#figure(
align(center)[#table(
columns: 6,
[f], [#fa("f")], [fan], [#fa("fan")], [faucet-drip], [#fa("faucet-drip")],
[faucet], [#fa("faucet")], [fax], [#fa("fax")], [feather-pointed], [#fa("feather-pointed")],
[feather], [#fa("feather")], [ferry], [#fa("ferry")], [file-arrow-down], [#fa("file-arrow-down")],
[file-arrow-up],
[#fa("file-arrow-up")],
[file-audio],
[#fa("file-audio")],
[file-circle-check],
[#fa("file-circle-check")],
[file-circle-exclamation],
[#fa("file-circle-exclamation")],
[file-circle-minus],
[#fa("file-circle-minus")],
[file-circle-plus],
[#fa("file-circle-plus")],
[file-circle-question],
[#fa("file-circle-question")],
[file-circle-xmark],
[#fa("file-circle-xmark")],
[file-code],
[#fa("file-code")],
[file-contract], [#fa("file-contract")], [file-csv], [#fa("file-csv")], [file-excel], [#fa("file-excel")],
[file-export], [#fa("file-export")], [file-image], [#fa("file-image")], [file-import], [#fa("file-import")],
[file-invoice-dollar],
[#fa("file-invoice-dollar")],
[file-invoice],
[#fa("file-invoice")],
[file-lines],
[#fa("file-lines")],
[file-medical], [#fa("file-medical")], [file-pdf], [#fa("file-pdf")], [file-pen], [#fa("file-pen")],
[file-powerpoint],
[#fa("file-powerpoint")],
[file-prescription],
[#fa("file-prescription")],
[file-shield],
[#fa("file-shield")],
[file-signature],
[#fa("file-signature")],
[file-video],
[#fa("file-video")],
[file-waveform],
[#fa("file-waveform")],
[file-word], [#fa("file-word")], [file-zipper], [#fa("file-zipper")], [file], [#fa("file")],
[fill-drip], [#fa("fill-drip")], [fill], [#fa("fill")], [film], [#fa("film")],
[filter-circle-dollar],
[#fa("filter-circle-dollar")],
[filter-circle-xmark],
[#fa("filter-circle-xmark")],
[filter],
[#fa("filter")],
[fingerprint],
[#fa("fingerprint")],
[fire-burner],
[#fa("fire-burner")],
[fire-extinguisher],
[#fa("fire-extinguisher")],
[fire-flame-curved],
[#fa("fire-flame-curved")],
[fire-flame-simple],
[#fa("fire-flame-simple")],
[fire],
[#fa("fire")],
[fish-fins], [#fa("fish-fins")], [fish], [#fa("fish")], [flag-checkered], [#fa("flag-checkered")],
[flag-usa], [#fa("flag-usa")], [flag], [#fa("flag")], [flask-vial], [#fa("flask-vial")],
[flask], [#fa("flask")], [floppy-disk], [#fa("floppy-disk")], [florin-sign], [#fa("florin-sign")],
[folder-closed],
[#fa("folder-closed")],
[folder-minus],
[#fa("folder-minus")],
[folder-open],
[#fa("folder-open")],
[folder-plus], [#fa("folder-plus")], [folder-tree], [#fa("folder-tree")], [folder], [#fa("folder")],
[font-awesome], [#fa("font-awesome")], [font], [#fa("font")], [football], [#fa("football")],
[forward-fast], [#fa("forward-fast")], [forward-step], [#fa("forward-step")], [forward], [#fa("forward")],
[franc-sign], [#fa("franc-sign")], [frog], [#fa("frog")], [futbol], [#fa("futbol")],
)],
)
#pagebreak()
=== Face
#figure(
align(center)[#table(
columns: 6,
[face-angry], [#fa("face-angry")], [face-dizzy], [#fa("face-dizzy")], [face-flushed], [#fa("face-flushed")],
[face-frown-open],
[#fa("face-frown-open")],
[face-frown],
[#fa("face-frown")],
[face-grimace],
[#fa("face-grimace")],
[face-grin-beam-sweat],
[#fa("face-grin-beam-sweat")],
[face-grin-beam],
[#fa("face-grin-beam")],
[face-grin-hearts],
[#fa("face-grin-hearts")],
[face-grin-squint-tears],
[#fa("face-grin-squint-tears")],
[face-grin-squint],
[#fa("face-grin-squint")],
[face-grin-stars],
[#fa("face-grin-stars")],
[face-grin-tears],
[#fa("face-grin-tears")],
[face-grin-tongue-squint],
[#fa("face-grin-tongue-squint")],
[face-grin-tongue-wink],
[#fa("face-grin-tongue-wink")],
[face-grin-tongue],
[#fa("face-grin-tongue")],
[face-grin-wide],
[#fa("face-grin-wide")],
[face-grin-wink],
[#fa("face-grin-wink")],
[face-grin],
[#fa("face-grin")],
[face-kiss-beam],
[#fa("face-kiss-beam")],
[face-kiss-wink-heart],
[#fa("face-kiss-wink-heart")],
[face-kiss],
[#fa("face-kiss")],
[face-laugh-beam],
[#fa("face-laugh-beam")],
[face-laugh-squint],
[#fa("face-laugh-squint")],
[face-laugh-wink],
[#fa("face-laugh-wink")],
[face-laugh],
[#fa("face-laugh")],
[face-meh-blank],
[#fa("face-meh-blank")],
[face-meh],
[#fa("face-meh")],
[face-rolling-eyes],
[#fa("face-rolling-eyes")],
[face-sad-cry],
[#fa("face-sad-cry")],
[face-sad-tear],
[#fa("face-sad-tear")],
[face-smile-beam],
[#fa("face-smile-beam")],
[face-smile-wink],
[#fa("face-smile-wink")],
[face-smile], [#fa("face-smile")], [face-surprise], [#fa("face-surprise")], [face-tired], [#fa("face-tired")],
)],
)
== G
#figure(
align(center)[#table(
columns: 6,
[g], [#fa("g")], [gamepad], [#fa("gamepad")], [gas-pump], [#fa("gas-pump")],
[gauge-high],
[#fa("gauge-high")],
[gauge-simple-high],
[#fa("gauge-simple-high")],
[gauge-simple],
[#fa("gauge-simple")],
[gauge], [#fa("gauge")], [gavel], [#fa("gavel")], [gear], [#fa("gear")],
[gears], [#fa("gears")], [gem], [#fa("gem")], [genderless], [#fa("genderless")],
[ghost], [#fa("ghost")], [gift], [#fa("gift")], [gifts], [#fa("gifts")],
[glass-water-droplet],
[#fa("glass-water-droplet")],
[glass-water],
[#fa("glass-water")],
[glasses],
[#fa("glasses")],
[globe], [#fa("globe")], [golf-ball-tee], [#fa("golf-ball-tee")], [gopuram], [#fa("gopuram")],
[graduation-cap],
[#fa("graduation-cap")],
[greater-than-equal],
[#fa("greater-than-equal")],
[greater-than],
[#fa("greater-than")],
[grip-lines-vertical],
[#fa("grip-lines-vertical")],
[grip-lines],
[#fa("grip-lines")],
[grip-vertical],
[#fa("grip-vertical")],
[grip], [#fa("grip")], [group-arrows-rotate], [#fa("group-arrows-rotate")], [guarani-sign], [#fa("guarani-sign")],
[guitar], [#fa("guitar")], [gun], [#fa("gun")],
)],
)
#pagebreak()
== H
#figure(
align(center)[#table(
columns: 6,
[h], [#fa("h")], [hammer], [#fa("hammer")], [hamsa], [#fa("hamsa")],
[hand-back-fist], [#fa("hand-back-fist")], [hand-dots], [#fa("hand-dots")], [hand-fist], [#fa("hand-fist")],
[hand-holding-dollar],
[#fa("hand-holding-dollar")],
[hand-holding-droplet],
[#fa("hand-holding-droplet")],
[hand-holding-hand],
[#fa("hand-holding-hand")],
[hand-holding-heart],
[#fa("hand-holding-heart")],
[hand-holding-medical],
[#fa("hand-holding-medical")],
[hand-holding],
[#fa("hand-holding")],
[hand-lizard],
[#fa("hand-lizard")],
[hand-middle-finger],
[#fa("hand-middle-finger")],
[hand-peace],
[#fa("hand-peace")],
[hand-point-down],
[#fa("hand-point-down")],
[hand-point-left],
[#fa("hand-point-left")],
[hand-point-right],
[#fa("hand-point-right")],
[hand-point-up],
[#fa("hand-point-up")],
[hand-pointer],
[#fa("hand-pointer")],
[hand-scissors],
[#fa("hand-scissors")],
[hand-sparkles], [#fa("hand-sparkles")], [hand-spock], [#fa("hand-spock")], [hand], [#fa("hand")],
[handcuffs],
[#fa("handcuffs")],
[hands-asl-interpreting],
[#fa("hands-asl-interpreting")],
[hands-bound],
[#fa("hands-bound")],
[hands-bubbles],
[#fa("hands-bubbles")],
[hands-clapping],
[#fa("hands-clapping")],
[hands-holding-child],
[#fa("hands-holding-child")],
[hands-holding-circle],
[#fa("hands-holding-circle")],
[hands-holding],
[#fa("hands-holding")],
[hands-praying],
[#fa("hands-praying")],
[hands],
[#fa("hands")],
[handshake-angle],
[#fa("handshake-angle")],
[handshake-simple-slash],
[#fa("handshake-simple-slash")],
[handshake-simple],
[#fa("handshake-simple")],
[handshake-slash],
[#fa("handshake-slash")],
[handshake],
[#fa("handshake")],
[hanukiah], [#fa("hanukiah")], [hard-drive], [#fa("hard-drive")], [hashtag], [#fa("hashtag")],
[hat-cowboy-side], [#fa("hat-cowboy-side")], [hat-cowboy], [#fa("hat-cowboy")], [hat-wizard], [#fa("hat-wizard")],
[head-side-cough-slash],
[#fa("head-side-cough-slash")],
[head-side-cough],
[#fa("head-side-cough")],
[head-side-mask],
[#fa("head-side-mask")],
[head-side-virus],
[#fa("head-side-virus")],
[heading],
[#fa("heading")],
[headphones-simple],
[#fa("headphones-simple")],
[headphones], [#fa("headphones")], [headset], [#fa("headset")], [heart-circle-bolt], [#fa("heart-circle-bolt")],
[heart-circle-check],
[#fa("heart-circle-check")],
[heart-circle-exclamation],
[#fa("heart-circle-exclamation")],
[heart-circle-minus],
[#fa("heart-circle-minus")],
[heart-circle-plus],
[#fa("heart-circle-plus")],
[heart-circle-xmark],
[#fa("heart-circle-xmark")],
[heart-crack],
[#fa("heart-crack")],
[heart-pulse], [#fa("heart-pulse")], [heart], [#fa("heart")], [helicopter-symbol], [#fa("helicopter-symbol")],
[helicopter], [#fa("helicopter")], [helmet-safety], [#fa("helmet-safety")], [helmet-un], [#fa("helmet-un")],
[highlighter],
[#fa("highlighter")],
[hill-avalanche],
[#fa("hill-avalanche")],
[hill-rockslide],
[#fa("hill-rockslide")],
[hippo], [#fa("hippo")], [hockey-puck], [#fa("hockey-puck")], [holly-berry], [#fa("holly-berry")],
[horse-head], [#fa("horse-head")], [horse], [#fa("horse")], [hospital-user], [#fa("hospital-user")],
[hospital], [#fa("hospital")], [hot-tub-person], [#fa("hot-tub-person")], [hotdog], [#fa("hotdog")],
[hotel], [#fa("hotel")], [hourglass-end], [#fa("hourglass-end")], [hourglass-half], [#fa("hourglass-half")],
[hourglass-start],
[#fa("hourglass-start")],
[hourglass],
[#fa("hourglass")],
[hryvnia-sign],
[#fa("hryvnia-sign")],
[hurricane], [#fa("hurricane")],
)],
)
#pagebreak()
=== House
#figure(
align(center)[#table(
columns: 4,
[house-chimney-crack], [#fa("house-chimney-crack")], [house-chimney-medical], [#fa("house-chimney-medical")],
[house-chimney-user], [#fa("house-chimney-user")], [house-chimney-window], [#fa("house-chimney-window")],
[house-chimney], [#fa("house-chimney")], [house-circle-check], [#fa("house-circle-check")],
[house-circle-exclamation], [#fa("house-circle-exclamation")], [house-circle-xmark], [#fa("house-circle-xmark")],
[house-crack], [#fa("house-crack")], [house-fire], [#fa("house-fire")],
[house-flag],
[#fa("house-flag")],
[house-flood-water-circle-arrow-right],
[#fa("house-flood-water-circle-arrow-right")],
[house-flood-water], [#fa("house-flood-water")], [house-laptop], [#fa("house-laptop")],
[house-lock], [#fa("house-lock")], [house-medical-circle-check], [#fa("house-medical-circle-check")],
[house-medical-circle-exclamation],
[#fa("house-medical-circle-exclamation")],
[house-medical-circle-xmark],
[#fa("house-medical-circle-xmark")],
[house-medical-flag], [#fa("house-medical-flag")], [house-medical], [#fa("house-medical")],
[house-signal], [#fa("house-signal")], [house-tsunami], [#fa("house-tsunami")],
[house-user], [#fa("house-user")], [house], [#fa("house")],
)],
)
#pagebreak()
== I-L
#figure(
align(center)[#table(
columns: 8,
[i-cursor], [#fa("i-cursor")], [i], [#fa("i")], [ice-cream], [#fa("ice-cream")], [icicles], [#fa("icicles")],
[icons],
[#fa("icons")],
[id-badge],
[#fa("id-badge")],
[id-card-clip],
[#fa("id-card-clip")],
[id-card],
[#fa("id-card")],
[igloo],
[#fa("igloo")],
[image-portrait],
[#fa("image-portrait")],
[image],
[#fa("image")],
[images],
[#fa("images")],
[inbox],
[#fa("inbox")],
[indent],
[#fa("indent")],
[indian-rupee-sign],
[#fa("indian-rupee-sign")],
[industry],
[#fa("industry")],
[infinity], [#fa("infinity")], [info], [#fa("info")], [italic], [#fa("italic")], [j], [#fa("j")],
[jar-wheat],
[#fa("jar-wheat")],
[jar],
[#fa("jar")],
[jedi],
[#fa("jedi")],
[jet-fighter-up],
[#fa("jet-fighter-up")],
[jet-fighter],
[#fa("jet-fighter")],
[joint],
[#fa("joint")],
[jug-detergent],
[#fa("jug-detergent")],
[k],
[#fa("k")],
[kaaba], [#fa("kaaba")], [key], [#fa("key")], [keyboard], [#fa("keyboard")], [khanda], [#fa("khanda")],
[kip-sign],
[#fa("kip-sign")],
[kit-medical],
[#fa("kit-medical")],
[kitchen-set],
[#fa("kitchen-set")],
[kiwi-bird],
[#fa("kiwi-bird")],
[l],
[#fa("l")],
[land-mine-on],
[#fa("land-mine-on")],
[landmark-dome],
[#fa("landmark-dome")],
[landmark-flag],
[#fa("landmark-flag")],
[landmark],
[#fa("landmark")],
[language],
[#fa("language")],
[laptop-code],
[#fa("laptop-code")],
[laptop-file],
[#fa("laptop-file")],
[laptop-medical],
[#fa("laptop-medical")],
[laptop],
[#fa("laptop")],
[lari-sign],
[#fa("lari-sign")],
[layer-group],
[#fa("layer-group")],
[leaf],
[#fa("leaf")],
[left-long],
[#fa("left-long")],
[left-right],
[#fa("left-right")],
[lemon],
[#fa("lemon")],
[less-than-equal],
[#fa("less-than-equal")],
[less-than],
[#fa("less-than")],
[life-ring],
[#fa("life-ring")],
[lightbulb],
[#fa("lightbulb")],
[lines-leaning],
[#fa("lines-leaning")],
[link-slash],
[#fa("link-slash")],
[link],
[#fa("link")],
[lira-sign],
[#fa("lira-sign")],
[list-check],
[#fa("list-check")],
[list-ol],
[#fa("list-ol")],
[list-ul],
[#fa("list-ul")],
[list],
[#fa("list")],
[litecoin-sign],
[#fa("litecoin-sign")],
[location-arrow],
[#fa("location-arrow")],
[location-crosshairs],
[#fa("location-crosshairs")],
[location-dot],
[#fa("location-dot")],
[location-pin-lock],
[#fa("location-pin-lock")],
[location-pin],
[#fa("location-pin")],
[lock-open],
[#fa("lock-open")],
[lock],
[#fa("lock")],
[locust], [#fa("locust")], [lungs-virus], [#fa("lungs-virus")], [lungs], [#fa("lungs")],
)],
)
#pagebreak()
== M
#figure(
align(center)[#table(
columns: 6,
[m], [#fa("m")], [magnet], [#fa("magnet")], [manat-sign], [#fa("manat-sign")],
[map-location-dot], [#fa("map-location-dot")], [map-location], [#fa("map-location")], [map-pin], [#fa("map-pin")],
[map], [#fa("map")], [marker], [#fa("marker")], [mars-and-venus-burst], [#fa("mars-and-venus-burst")],
[mars-and-venus],
[#fa("mars-and-venus")],
[mars-double],
[#fa("mars-double")],
[mars-stroke-right],
[#fa("mars-stroke-right")],
[mars-stroke-up], [#fa("mars-stroke-up")], [mars-stroke], [#fa("mars-stroke")], [mars], [#fa("mars")],
[martini-glass-citrus],
[#fa("martini-glass-citrus")],
[martini-glass-empty],
[#fa("martini-glass-empty")],
[martini-glass],
[#fa("martini-glass")],
[mask-face], [#fa("mask-face")], [mask-ventilator], [#fa("mask-ventilator")], [mask], [#fa("mask")],
[masks-theater],
[#fa("masks-theater")],
[mattress-pillow],
[#fa("mattress-pillow")],
[maximize],
[#fa("maximize")],
[medal], [#fa("medal")], [memory], [#fa("memory")], [menorah], [#fa("menorah")],
[mercury], [#fa("mercury")], [message], [#fa("message")], [meteor], [#fa("meteor")],
[microchip],
[#fa("microchip")],
[microphone-lines-slash],
[#fa("microphone-lines-slash")],
[microphone-lines],
[#fa("microphone-lines")],
[microphone-slash],
[#fa("microphone-slash")],
[microphone],
[#fa("microphone")],
[microscope],
[#fa("microscope")],
[mill-sign], [#fa("mill-sign")], [minimize], [#fa("minimize")], [minus], [#fa("minus")],
[mitten], [#fa("mitten")], [mobile-button], [#fa("mobile-button")], [mobile-retro], [#fa("mobile-retro")],
[mobile-screen-button],
[#fa("mobile-screen-button")],
[mobile-screen],
[#fa("mobile-screen")],
[mobile],
[#fa("mobile")],
[money-bill-1-wave],
[#fa("money-bill-1-wave")],
[money-bill-1],
[#fa("money-bill-1")],
[money-bill-transfer],
[#fa("money-bill-transfer")],
[money-bill-trend-up],
[#fa("money-bill-trend-up")],
[money-bill-wave],
[#fa("money-bill-wave")],
[money-bill-wheat],
[#fa("money-bill-wheat")],
[money-bill],
[#fa("money-bill")],
[money-bills],
[#fa("money-bills")],
[money-check-dollar],
[#fa("money-check-dollar")],
[money-check], [#fa("money-check")], [monument], [#fa("monument")], [moon], [#fa("moon")],
[mortar-pestle], [#fa("mortar-pestle")], [mosque], [#fa("mosque")], [mosquito-net], [#fa("mosquito-net")],
[mosquito], [#fa("mosquito")], [motorcycle], [#fa("motorcycle")], [mound], [#fa("mound")],
[mountain-city], [#fa("mountain-city")], [mountain-sun], [#fa("mountain-sun")], [mountain], [#fa("mountain")],
[mug-hot], [#fa("mug-hot")], [mug-saucer], [#fa("mug-saucer")], [music], [#fa("music")],
)],
)
=== Magnifying
#figure(
align(center)[#table(
columns: 4,
[magnifying-glass-arrow-right],
[#fa("magnifying-glass-arrow-right")],
[magnifying-glass-chart],
[#fa("magnifying-glass-chart")],
[magnifying-glass-dollar],
[#fa("magnifying-glass-dollar")],
[magnifying-glass-location],
[#fa("magnifying-glass-location")],
[magnifying-glass-minus],
[#fa("magnifying-glass-minus")],
[magnifying-glass-plus],
[#fa("magnifying-glass-plus")],
[magnifying-glass], [#fa("magnifying-glass")],
)],
)
#pagebreak()
== N-P
#figure(
align(center)[#table(
columns: 6,
[n], [#fa("n")], [naira-sign], [#fa("naira-sign")], [network-wired], [#fa("network-wired")],
[neuter], [#fa("neuter")], [newspaper], [#fa("newspaper")], [not-equal], [#fa("not-equal")],
[notdef], [#fa("notdef")], [note-sticky], [#fa("note-sticky")], [notes-medical], [#fa("notes-medical")],
[o], [#fa("o")], [object-group], [#fa("object-group")], [object-ungroup], [#fa("object-ungroup")],
[oil-can], [#fa("oil-can")], [oil-well], [#fa("oil-well")], [om], [#fa("om")],
[otter], [#fa("otter")], [outdent], [#fa("outdent")], [p], [#fa("p")],
[pager], [#fa("pager")], [paint-roller], [#fa("paint-roller")], [paintbrush], [#fa("paintbrush")],
[palette], [#fa("palette")], [pallet], [#fa("pallet")], [panorama], [#fa("panorama")],
[paper-plane], [#fa("paper-plane")], [paperclip], [#fa("paperclip")], [parachute-box], [#fa("parachute-box")],
[paragraph], [#fa("paragraph")], [passport], [#fa("passport")], [paste], [#fa("paste")],
[pause], [#fa("pause")], [paw], [#fa("paw")], [peace], [#fa("peace")],
[pencil], [#fa("pencil")], [pepper-hot], [#fa("pepper-hot")], [percent], [#fa("percent")],
[peseta-sign], [#fa("peseta-sign")], [peso-sign], [#fa("peso-sign")], [phone-flip], [#fa("phone-flip")],
[phone-slash], [#fa("phone-slash")], [phone-volume], [#fa("phone-volume")], [phone], [#fa("phone")],
[photo-film], [#fa("photo-film")], [piggy-bank], [#fa("piggy-bank")], [pills], [#fa("pills")],
[pizza-slice],
[#fa("pizza-slice")],
[place-of-worship],
[#fa("place-of-worship")],
[plant-wilt],
[#fa("plant-wilt")],
[plate-wheat], [#fa("plate-wheat")], [play], [#fa("play")], [plus-minus], [#fa("plus-minus")],
[plus], [#fa("plus")], [podcast], [#fa("podcast")], [poo-storm], [#fa("poo-storm")],
[poo], [#fa("poo")], [poop], [#fa("poop")], [power-off], [#fa("power-off")],
[prescription-bottle-medical],
[#fa("prescription-bottle-medical")],
[prescription-bottle],
[#fa("prescription-bottle")],
[prescription],
[#fa("prescription")],
[print], [#fa("print")], [pump-medical], [#fa("pump-medical")], [pump-soap], [#fa("pump-soap")],
[puzzle-piece], [#fa("puzzle-piece")],
)],
)
=== Pen, Plane, Plug
#figure(
align(center)[#table(
columns: 6,
[pen-clip], [#fa("pen-clip")], [pen-fancy], [#fa("pen-fancy")], [pen-nib], [#fa("pen-nib")],
[pen-ruler], [#fa("pen-ruler")], [pen-to-square], [#fa("pen-to-square")], [pen], [#fa("pen")],
[plane-arrival],
[#fa("plane-arrival")],
[plane-circle-check],
[#fa("plane-circle-check")],
[plane-circle-exclamation],
[#fa("plane-circle-exclamation")],
[plane-circle-xmark],
[#fa("plane-circle-xmark")],
[plane-departure],
[#fa("plane-departure")],
[plane-lock],
[#fa("plane-lock")],
[plane-slash], [#fa("plane-slash")], [plane-up], [#fa("plane-up")], [plane], [#fa("plane")],
[plug-circle-bolt],
[#fa("plug-circle-bolt")],
[plug-circle-check],
[#fa("plug-circle-check")],
[plug-circle-exclamation],
[#fa("plug-circle-exclamation")],
[plug-circle-minus],
[#fa("plug-circle-minus")],
[plug-circle-plus],
[#fa("plug-circle-plus")],
[plug-circle-xmark],
[#fa("plug-circle-xmark")],
[plug], [#fa("plug")],
)],
)
=== People, Person
#figure(
align(center)[#table(
columns: 4,
[people-arrows], [#fa("people-arrows")], [people-carry-box], [#fa("people-carry-box")],
[people-group], [#fa("people-group")], [people-line], [#fa("people-line")],
[people-pulling], [#fa("people-pulling")], [people-robbery], [#fa("people-robbery")],
[people-roof], [#fa("people-roof")], [person-arrow-down-to-line], [#fa("person-arrow-down-to-line")],
[person-arrow-up-from-line], [#fa("person-arrow-up-from-line")], [person-biking], [#fa("person-biking")],
[person-booth], [#fa("person-booth")], [person-breastfeeding], [#fa("person-breastfeeding")],
[person-burst], [#fa("person-burst")], [person-cane], [#fa("person-cane")],
[person-chalkboard], [#fa("person-chalkboard")], [person-circle-check], [#fa("person-circle-check")],
[person-circle-exclamation],
[#fa("person-circle-exclamation")],
[person-circle-minus],
[#fa("person-circle-minus")],
[person-circle-plus], [#fa("person-circle-plus")], [person-circle-question], [#fa("person-circle-question")],
[person-circle-xmark], [#fa("person-circle-xmark")], [person-digging], [#fa("person-digging")],
[person-dots-from-line], [#fa("person-dots-from-line")], [person-dress-burst], [#fa("person-dress-burst")],
[person-dress], [#fa("person-dress")], [person-drowning], [#fa("person-drowning")],
[person-falling-burst], [#fa("person-falling-burst")], [person-falling], [#fa("person-falling")],
[person-half-dress], [#fa("person-half-dress")], [person-harassing], [#fa("person-harassing")],
[person-hiking], [#fa("person-hiking")], [person-military-pointing], [#fa("person-military-pointing")],
[person-military-rifle],
[#fa("person-military-rifle")],
[person-military-to-person],
[#fa("person-military-to-person")],
[person-praying], [#fa("person-praying")], [person-pregnant], [#fa("person-pregnant")],
[person-rays], [#fa("person-rays")], [person-rifle], [#fa("person-rifle")],
[person-running], [#fa("person-running")], [person-shelter], [#fa("person-shelter")],
[person-skating], [#fa("person-skating")], [person-skiing-nordic], [#fa("person-skiing-nordic")],
[person-skiing], [#fa("person-skiing")], [person-snowboarding], [#fa("person-snowboarding")],
[person-swimming], [#fa("person-swimming")], [person-through-window], [#fa("person-through-window")],
[person-walking-arrow-loop-left],
[#fa("person-walking-arrow-loop-left")],
[person-walking-arrow-right],
[#fa("person-walking-arrow-right")],
[person-walking-dashed-line-arrow-right],
[#fa("person-walking-dashed-line-arrow-right")],
[person-walking-luggage],
[#fa("person-walking-luggage")],
[person-walking-with-cane], [#fa("person-walking-with-cane")], [person-walking], [#fa("person-walking")],
[person], [#fa("person")],
)],
)
#pagebreak()
== Q-R
#figure(
align(center)[#table(
columns: 6,
[q], [#fa("q")], [qrcode], [#fa("qrcode")], [question], [#fa("question")],
[quote-left], [#fa("quote-left")], [quote-right], [#fa("quote-right")], [r], [#fa("r")],
[radiation], [#fa("radiation")], [radio], [#fa("radio")], [rainbow], [#fa("rainbow")],
[ranking-star], [#fa("ranking-star")], [receipt], [#fa("receipt")], [record-vinyl], [#fa("record-vinyl")],
[rectangle-ad],
[#fa("rectangle-ad")],
[rectangle-list],
[#fa("rectangle-list")],
[rectangle-xmark],
[#fa("rectangle-xmark")],
[recycle], [#fa("recycle")], [registered], [#fa("registered")], [repeat], [#fa("repeat")],
[reply-all], [#fa("reply-all")], [reply], [#fa("reply")], [republican], [#fa("republican")],
[restroom], [#fa("restroom")], [retweet], [#fa("retweet")], [ribbon], [#fa("ribbon")],
[right-from-bracket],
[#fa("right-from-bracket")],
[right-left],
[#fa("right-left")],
[right-long],
[#fa("right-long")],
[right-to-bracket], [#fa("right-to-bracket")], [ring], [#fa("ring")], [road-barrier], [#fa("road-barrier")],
[road-bridge],
[#fa("road-bridge")],
[road-circle-check],
[#fa("road-circle-check")],
[road-circle-exclamation],
[#fa("road-circle-exclamation")],
[road-circle-xmark],
[#fa("road-circle-xmark")],
[road-lock],
[#fa("road-lock")],
[road-spikes],
[#fa("road-spikes")],
[road], [#fa("road")], [robot], [#fa("robot")], [rocket], [#fa("rocket")],
[rotate-left], [#fa("rotate-left")], [rotate-right], [#fa("rotate-right")], [rotate], [#fa("rotate")],
[route], [#fa("route")], [rss], [#fa("rss")], [ruble-sign], [#fa("ruble-sign")],
[rug], [#fa("rug")], [ruler-combined], [#fa("ruler-combined")], [ruler-horizontal], [#fa("ruler-horizontal")],
[ruler-vertical], [#fa("ruler-vertical")], [ruler], [#fa("ruler")], [rupee-sign], [#fa("rupee-sign")],
[rupiah-sign], [#fa("rupiah-sign")],
)],
)
#pagebreak()
== S
#figure(
align(center)[#table(
columns: 6,
[s], [#fa("s")], [sack-dollar], [#fa("sack-dollar")], [sack-xmark], [#fa("sack-xmark")],
[sailboat], [#fa("sailboat")], [satellite-dish], [#fa("satellite-dish")], [satellite], [#fa("satellite")],
[scale-balanced],
[#fa("scale-balanced")],
[scale-unbalanced-flip],
[#fa("scale-unbalanced-flip")],
[scale-unbalanced],
[#fa("scale-unbalanced")],
[scissors],
[#fa("scissors")],
[screwdriver-wrench],
[#fa("screwdriver-wrench")],
[screwdriver],
[#fa("screwdriver")],
[scroll-torah], [#fa("scroll-torah")], [scroll], [#fa("scroll")], [sd-card], [#fa("sd-card")],
[section], [#fa("section")], [seedling], [#fa("seedling")], [server], [#fa("server")],
[shapes], [#fa("shapes")], [share-from-square], [#fa("share-from-square")], [share-nodes], [#fa("share-nodes")],
[share], [#fa("share")], [sheet-plastic], [#fa("sheet-plastic")], [shekel-sign], [#fa("shekel-sign")],
[ship], [#fa("ship")], [shirt], [#fa("shirt")], [shoe-prints], [#fa("shoe-prints")],
[shop-lock], [#fa("shop-lock")], [shop-slash], [#fa("shop-slash")], [shop], [#fa("shop")],
[shower], [#fa("shower")], [shrimp], [#fa("shrimp")], [shuffle], [#fa("shuffle")],
[shuttle-space], [#fa("shuttle-space")], [sign-hanging], [#fa("sign-hanging")], [signal], [#fa("signal")],
[signature], [#fa("signature")], [signs-post], [#fa("signs-post")], [sim-card], [#fa("sim-card")],
[sink], [#fa("sink")], [sitemap], [#fa("sitemap")], [skull-crossbones], [#fa("skull-crossbones")],
[skull], [#fa("skull")], [slash], [#fa("slash")], [sleigh], [#fa("sleigh")],
[sliders], [#fa("sliders")], [smog], [#fa("smog")], [smoking], [#fa("smoking")],
[snowflake], [#fa("snowflake")], [snowman], [#fa("snowman")], [snowplow], [#fa("snowplow")],
[soap], [#fa("soap")], [socks], [#fa("socks")], [solar-panel], [#fa("solar-panel")],
[sort-down], [#fa("sort-down")], [sort-up], [#fa("sort-up")], [sort], [#fa("sort")],
[spa],
[#fa("spa")],
[spaghetti-monster-flying],
[#fa("spaghetti-monster-flying")],
[spell-check],
[#fa("spell-check")],
[spider], [#fa("spider")], [spinner], [#fa("spinner")], [splotch], [#fa("splotch")],
[spoon], [#fa("spoon")], [spray-can-sparkles], [#fa("spray-can-sparkles")], [spray-can], [#fa("spray-can")],
[staff-snake], [#fa("staff-snake")], [stairs], [#fa("stairs")], [stamp], [#fa("stamp")],
[stapler], [#fa("stapler")], [sterling-sign], [#fa("sterling-sign")], [stethoscope], [#fa("stethoscope")],
[stop], [#fa("stop")], [stopwatch-20], [#fa("stopwatch-20")], [stopwatch], [#fa("stopwatch")],
[store-slash], [#fa("store-slash")], [store], [#fa("store")], [street-view], [#fa("street-view")],
[strikethrough], [#fa("strikethrough")], [stroopwafel], [#fa("stroopwafel")], [subscript], [#fa("subscript")],
[suitcase-medical],
[#fa("suitcase-medical")],
[suitcase-rolling],
[#fa("suitcase-rolling")],
[suitcase],
[#fa("suitcase")],
[sun-plant-wilt], [#fa("sun-plant-wilt")], [sun], [#fa("sun")], [superscript], [#fa("superscript")],
[swatchbook], [#fa("swatchbook")], [synagogue], [#fa("synagogue")], [syringe], [#fa("syringe")],
)],
)
#pagebreak()
=== Shield, School, Square, Star
#figure(
align(center)[#table(
columns: 6,
[shield-cat], [#fa("shield-cat")], [shield-dog], [#fa("shield-dog")], [shield-halved], [#fa("shield-halved")],
[shield-heart], [#fa("shield-heart")], [shield-virus], [#fa("shield-virus")], [shield], [#fa("shield")],
[school-circle-check],
[#fa("school-circle-check")],
[school-circle-exclamation],
[#fa("school-circle-exclamation")],
[school-circle-xmark],
[#fa("school-circle-xmark")],
[school-flag], [#fa("school-flag")], [school-lock], [#fa("school-lock")], [school], [#fa("school")],
[square-arrow-up-right],
[#fa("square-arrow-up-right")],
[square-caret-down],
[#fa("square-caret-down")],
[square-caret-left],
[#fa("square-caret-left")],
[square-caret-right],
[#fa("square-caret-right")],
[square-caret-up],
[#fa("square-caret-up")],
[square-check],
[#fa("square-check")],
[square-envelope], [#fa("square-envelope")], [square-full], [#fa("square-full")], [square-h], [#fa("square-h")],
[square-minus],
[#fa("square-minus")],
[square-nfi],
[#fa("square-nfi")],
[square-parking],
[#fa("square-parking")],
[square-pen],
[#fa("square-pen")],
[square-person-confined],
[#fa("square-person-confined")],
[square-phone-flip],
[#fa("square-phone-flip")],
[square-phone],
[#fa("square-phone")],
[square-plus],
[#fa("square-plus")],
[square-poll-horizontal],
[#fa("square-poll-horizontal")],
[square-poll-vertical],
[#fa("square-poll-vertical")],
[square-root-variable],
[#fa("square-root-variable")],
[square-rss],
[#fa("square-rss")],
[square-share-nodes],
[#fa("square-share-nodes")],
[square-up-right],
[#fa("square-up-right")],
[square-virus],
[#fa("square-virus")],
[square-xmark], [#fa("square-xmark")], [square], [#fa("square")], [star-and-crescent], [#fa("star-and-crescent")],
[star-half-stroke],
[#fa("star-half-stroke")],
[star-half],
[#fa("star-half")],
[star-of-david],
[#fa("star-of-david")],
[star-of-life], [#fa("star-of-life")], [star], [#fa("star")],
)],
)
=== Table, Tent, Temperature, Toilet, Truck
#figure(
align(center)[#table(
columns: 6,
[table-cells-large],
[#fa("table-cells-large")],
[table-cells],
[#fa("table-cells")],
[table-columns],
[#fa("table-columns")],
[table-list],
[#fa("table-list")],
[table-tennis-paddle-ball],
[#fa("table-tennis-paddle-ball")],
[table],
[#fa("table")],
[tent-arrow-down-to-line],
[#fa("tent-arrow-down-to-line")],
[tent-arrow-left-right],
[#fa("tent-arrow-left-right")],
[tent-arrow-turn-left],
[#fa("tent-arrow-turn-left")],
[tent-arrows-down], [#fa("tent-arrows-down")], [tent], [#fa("tent")], [tents], [#fa("tents")],
[temperature-arrow-down],
[#fa("temperature-arrow-down")],
[temperature-arrow-up],
[#fa("temperature-arrow-up")],
[temperature-empty],
[#fa("temperature-empty")],
[temperature-full],
[#fa("temperature-full")],
[temperature-half],
[#fa("temperature-half")],
[temperature-high],
[#fa("temperature-high")],
[temperature-low],
[#fa("temperature-low")],
[temperature-quarter],
[#fa("temperature-quarter")],
[temperature-three-quarters],
[#fa("temperature-three-quarters")],
[toilet-paper-slash],
[#fa("toilet-paper-slash")],
[toilet-paper],
[#fa("toilet-paper")],
[toilet-portable],
[#fa("toilet-portable")],
[toilet],
[#fa("toilet")],
[toilets-portable],
[#fa("toilets-portable")],
[truck-arrow-right],
[#fa("truck-arrow-right")],
[truck-droplet],
[#fa("truck-droplet")],
[truck-fast],
[#fa("truck-fast")],
[truck-field-un],
[#fa("truck-field-un")],
[truck-field], [#fa("truck-field")], [truck-front], [#fa("truck-front")], [truck-medical], [#fa("truck-medical")],
[truck-monster],
[#fa("truck-monster")],
[truck-moving],
[#fa("truck-moving")],
[truck-pickup],
[#fa("truck-pickup")],
[truck-plane], [#fa("truck-plane")], [truck-ramp-box], [#fa("truck-ramp-box")], [truck], [#fa("truck")],
)],
)
#pagebreak()
== T
#figure(
align(center)[#table(
columns: 6,
[t], [#fa("t")], [tablet-button], [#fa("tablet-button")], [tablet-screen-button], [#fa("tablet-screen-button")],
[tablet], [#fa("tablet")], [tablets], [#fa("tablets")], [tachograph-digital], [#fa("tachograph-digital")],
[tag], [#fa("tag")], [tags], [#fa("tags")], [tape], [#fa("tape")],
[tarp-droplet], [#fa("tarp-droplet")], [tarp], [#fa("tarp")], [taxi], [#fa("taxi")],
[teeth-open], [#fa("teeth-open")], [teeth], [#fa("teeth")], [tenge-sign], [#fa("tenge-sign")],
[terminal], [#fa("terminal")], [text-height], [#fa("text-height")], [text-slash], [#fa("text-slash")],
[text-width], [#fa("text-width")], [thermometer], [#fa("thermometer")], [thumbs-down], [#fa("thumbs-down")],
[thumbs-up], [#fa("thumbs-up")], [thumbtack], [#fa("thumbtack")], [ticket-simple], [#fa("ticket-simple")],
[ticket], [#fa("ticket")], [timeline], [#fa("timeline")], [toggle-off], [#fa("toggle-off")],
[toggle-on], [#fa("toggle-on")], [toolbox], [#fa("toolbox")], [tooth], [#fa("tooth")],
[torii-gate], [#fa("torii-gate")], [tornado], [#fa("tornado")], [tower-broadcast], [#fa("tower-broadcast")],
[tower-cell], [#fa("tower-cell")], [tower-observation], [#fa("tower-observation")], [tractor], [#fa("tractor")],
[trademark], [#fa("trademark")], [traffic-light], [#fa("traffic-light")], [trailer], [#fa("trailer")],
[train-subway], [#fa("train-subway")], [train-tram], [#fa("train-tram")], [train], [#fa("train")],
[transgender],
[#fa("transgender")],
[trash-arrow-up],
[#fa("trash-arrow-up")],
[trash-can-arrow-up],
[#fa("trash-can-arrow-up")],
[trash-can], [#fa("trash-can")], [trash], [#fa("trash")], [tree-city], [#fa("tree-city")],
[tree], [#fa("tree")], [triangle-exclamation], [#fa("triangle-exclamation")], [trophy], [#fa("trophy")],
[trowel-bricks], [#fa("trowel-bricks")], [trowel], [#fa("trowel")], [tty], [#fa("tty")],
[turkish-lira-sign], [#fa("turkish-lira-sign")], [turn-down], [#fa("turn-down")], [turn-up], [#fa("turn-up")],
[tv], [#fa("tv")],
)],
)
== U
#figure(
align(center)[#table(
columns: 8,
[u],
[#fa("u")],
[umbrella-beach],
[#fa("umbrella-beach")],
[umbrella],
[#fa("umbrella")],
[underline],
[#fa("underline")],
[universal-access],
[#fa("universal-access")],
[unlock-keyhole],
[#fa("unlock-keyhole")],
[unlock],
[#fa("unlock")],
[utensils],
[#fa("utensils")],
[up-down-left-right],
[#fa("up-down-left-right")],
[up-down],
[#fa("up-down")],
[up-long],
[#fa("up-long")],
[up-right-from-square],
[#fa("up-right-from-square")],
[upload], [#fa("upload")],
)],
)
#pagebreak()
== User
#figure(
align(center)[#table(
columns: 8,
[user-astronaut],
[#fa("user-astronaut")],
[user-check],
[#fa("user-check")],
[user-clock],
[#fa("user-clock")],
[user-doctor],
[#fa("user-doctor")],
[user-gear],
[#fa("user-gear")],
[user-graduate],
[#fa("user-graduate")],
[user-group],
[#fa("user-group")],
[user-injured],
[#fa("user-injured")],
[user-large-slash],
[#fa("user-large-slash")],
[user-large],
[#fa("user-large")],
[user-lock],
[#fa("user-lock")],
[user-minus],
[#fa("user-minus")],
[user-ninja],
[#fa("user-ninja")],
[user-nurse],
[#fa("user-nurse")],
[user-pen],
[#fa("user-pen")],
[user-plus],
[#fa("user-plus")],
[user-secret],
[#fa("user-secret")],
[user-shield],
[#fa("user-shield")],
[user-slash],
[#fa("user-slash")],
[user-tag],
[#fa("user-tag")],
[user-tie],
[#fa("user-tie")],
[user-xmark],
[#fa("user-xmark")],
[user],
[#fa("user")],
[users-between-lines],
[#fa("users-between-lines")],
[users-gear],
[#fa("users-gear")],
[users-line],
[#fa("users-line")],
[users-rays],
[#fa("users-rays")],
[users-rectangle],
[#fa("users-rectangle")],
[users-slash], [#fa("users-slash")], [users-viewfinder], [#fa("users-viewfinder")], [users], [#fa("users")],
)],
)
== V-Z
#figure(
align(center)[#table(
columns: 6,
[v], [#fa("v")], [van-shuttle], [#fa("van-shuttle")], [vault], [#fa("vault")],
[vector-square], [#fa("vector-square")], [venus-double], [#fa("venus-double")], [venus-mars], [#fa("venus-mars")],
[venus], [#fa("venus")], [vest-patches], [#fa("vest-patches")], [vest], [#fa("vest")],
[vial-circle-check], [#fa("vial-circle-check")], [vial-virus], [#fa("vial-virus")], [vial], [#fa("vial")],
[vials], [#fa("vials")], [video-slash], [#fa("video-slash")], [video], [#fa("video")],
[vihara], [#fa("vihara")], [voicemail], [#fa("voicemail")], [volcano], [#fa("volcano")],
[volleyball], [#fa("volleyball")], [vr-cardboard], [#fa("vr-cardboard")], [w], [#fa("w")],
[walkie-talkie],
[#fa("walkie-talkie")],
[wallet],
[#fa("wallet")],
[wand-magic-sparkles],
[#fa("wand-magic-sparkles")],
[wand-magic], [#fa("wand-magic")], [wand-sparkles], [#fa("wand-sparkles")], [warehouse], [#fa("warehouse")],
[water-ladder], [#fa("water-ladder")], [water], [#fa("water")], [wave-square], [#fa("wave-square")],
[weight-hanging],
[#fa("weight-hanging")],
[weight-scale],
[#fa("weight-scale")],
[wheat-awn-circle-exclamation],
[#fa("wheat-awn-circle-exclamation")],
[wheat-awn], [#fa("wheat-awn")], [wheelchair-move], [#fa("wheelchair-move")], [wheelchair], [#fa("wheelchair")],
[whiskey-glass], [#fa("whiskey-glass")], [wifi], [#fa("wifi")], [wind], [#fa("wind")],
[window-maximize],
[#fa("window-maximize")],
[window-minimize],
[#fa("window-minimize")],
[window-restore],
[#fa("window-restore")],
[wine-bottle],
[#fa("wine-bottle")],
[wine-glass-empty],
[#fa("wine-glass-empty")],
[wine-glass],
[#fa("wine-glass")],
[won-sign], [#fa("won-sign")], [worm], [#fa("worm")], [wrench], [#fa("wrench")],
[x-ray], [#fa("x-ray")], [x], [#fa("x")], [xmark], [#fa("xmark")],
[xmarks-lines], [#fa("xmarks-lines")], [y], [#fa("y")], [yen-sign], [#fa("yen-sign")],
[yin-yang], [#fa("yin-yang")], [z], [#fa("z")],
)],
)
#pagebreak(weak: true)
=== Virus, Volume
#figure(
align(center)[#table(
columns: 8,
[virus-covid-slash],
[#fa("virus-covid-slash")],
[virus-covid],
[#fa("virus-covid")],
[virus-slash],
[#fa("virus-slash")],
[virus],
[#fa("virus")],
[viruses],
[#fa("viruses")],
[volume-high],
[#fa("volume-high")],
[volume-low],
[#fa("volume-low")],
[volume-off],
[#fa("volume-off")],
[volume-xmark], [#fa("volume-xmark")],
)],
)
== Other
#figure(
align(center)[#table(
columns: 4,
[down-left-and-up-right-to-center],
[#fa("down-left-and-up-right-to-center")],
[up-right-and-down-left-from-center],
[#fa("up-right-and-down-left-from-center")],
)],
)
|
https://github.com/EpicEricEE/typst-marge | https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/src/lib.typ | typst | MIT License | #import "sidenote.typ": sidenote, container
|
https://github.com/Manato1fg/My-Typst-Template | https://raw.githubusercontent.com/Manato1fg/My-Typst-Template/main/template.typ | typst | MIT License | #import "@preview/ctheorems:1.1.0": *
#import "@preview/physica:0.9.2": *
#let report(title: "", class: "", date: "", author: "", affiliation: "", no-header: false, bibliography-file: "", body) = {
set text(
font: (
"Times New Roman",
"<NAME>"
),
size: 12pt
)
let textMargin(text, above: 8pt, below: 8pt) = {
block(above: above, below: below, text)
}
set page(
paper: "a4",
margin: (
bottom: 1.75cm, top: 2.5cm,
left: 2cm, right: 2cm
),
)
set par(leading: 0.8em, first-line-indent: 20pt, justify: true)
show par: set block(spacing: 1.4em)
set heading(numbering: none) if no-header == true
set heading(numbering: "1.1.") if no-header == false
show heading.where(level: 1): it => {
block(above: 1.5em, below: 1em)
if no-header == false {
counter(math.equation).update(0)
text(weight: "bold", size: 22pt)[
#numbering(it.numbering, ..counter(heading).at(it.location()))
]
}
text(weight: "bold", size: 20pt)[#it.body \ ]
}
show heading.where(level: 2): it => {
block(above: 0.2em, below: 1em)
if no-header == false {
text(weight: "bold", size: 15pt)[
#numbering(it.numbering, ..counter(heading).at(it.location()))
]
}
text(weight: 700, size: 14pt)[#it.body \ ]
}
show figure.where(kind: table): set figure.caption(position: top)
set math.equation(numbering: num =>
"(" + str(num) + ")", supplement: "式") if no-header == true
set math.equation(numbering: num =>
"(" + ((counter(heading).get().at(0),) + (num,)).map(str).join(".") + ")", supplement: "式") if no-header == false
show: thmrules
// citation number
show ref: it => {
if it.element != none and it.element.func() == figure {
let el = it.element
let loc = el.location()
let chapt = counter(heading).at(loc).at(0)
link(loc)[#if el.kind == "image" or el.kind == "table" {
// counting
let num = counter(el.kind + "-chapter" + str(chapt)).at(loc).at(0) + 1
it.element.supplement
" "
str(chapt)
"."
str(num)
} else if el.kind == "thmenv" {
let thms = query(selector(<meta:thmenvcounter>).after(loc), loc)
let number = thmcounters.at(thms.first().location()).at("latest")
it.element.supplement
" "
numbering(it.element.numbering, ..number)
} else {
it
}
]
} else if it.element != none and it.element.func() == math.equation {
let el = it.element
let loc = el.location()
let chapt = counter(heading).at(loc).at(0)
let num = counter(math.equation).at(loc).at(0)
it.element.supplement
" ("
str(chapt)
"."
str(num)
")"
} else if it.element != none and it.element.func() == heading {
let el = it.element
let loc = el.location()
let num = numbering(el.numbering, ..counter(heading).at(loc))
if el.level == 1 {
"第"
str(num).replace(".", "")
"章"
} else if el.level == 2 {
str(num)
"節"
} else if el.level == 3 {
str(num)
"項"
}
} else {
it
}
}
set page(numbering: "1 / 1")
set figure(supplement: "図")
// date
align(right, text(12pt)[
#date.display("[year]年[month]月[day]日")
])
if class != "" {
align(center, textMargin(
text(14pt)[#class],
below: 8pt
))
}
align(center, text(24pt)[
*#title*
])
align(center, text(16pt)[
#author
])
align(center, textMargin(
text(12pt)[
#affiliation
],
above: 8pt
))
body
// Display bibliography.
if bibliography-file != "" {
show bibliography: set text(12pt)
show bibliography: set heading(numbering: "1.")
bibliography(bibliography-file, title: "参考文献", style: "ieee")
}
}
#let notag(block: true, body) = {
math.equation(block: block, numbering: none)[#body]
}
#let theorem = thmbox("theorem", "定理", fill: rgb("#eeeeee"))
#let corollary = thmplain(
"corollary",
"系",
base: "theorem",
titlefmt: strong
)
#let definition = thmbox("definition", "定義", fill: rgb("#d0f4f5"))
#let lemma = thmplain("lemma", "補題", base: "theorem", titlefmt: strong)
#let example = thmplain("example", "例").with(numbering: none)
#let proof = thmplain(
"proof",
"証明",
base: "theorem",
bodyfmt: body => [#body #h(1fr) $square$]
).with(numbering: none)
#let remark = thmplain("remark", "Remark").with(numbering: none) |
https://github.com/denizenging/site | https://raw.githubusercontent.com/denizenging/site/master/page/archive/index.tr.typ | typst | #import "@local/pub-page:0.0.0": *
#show: template(
title: "Eski Kayıtlar",
layout: "archives",
menu: (6, "archives"),
) |
|
https://github.com/jamesrswift/blog | https://raw.githubusercontent.com/jamesrswift/blog/main/assets/packages/sparklines/lib.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#let line(data, (x-min, x-max), (y-min, y-max)) = cetz.draw.line(
..data
)
#let vline(x, ..style) = (data, (x-min, x-max), (y-min, y-max)) => {
cetz.draw.line(
(x, y-min),
(x, y-max),
..style
)
}
#let make(
data,
height: 1em,
width: 1em,
style: (stroke: 0.4pt),
draw: (
line,
)
) = h(0em, weak: true) + sym.space + box({
let xs = data.map(it=>it.first())
let x-min = calc.min(..xs)
let x-max = calc.max(..xs)
let ys = data.map(it=>it.last())
let y-min = calc.min(..ys)
let y-max = calc.max(..ys)
cetz.canvas(
length: 1em,
{
cetz.draw.set-style(stroke: stroke, ..style)
cetz.draw.scale(
x: width / ((x-max - x-min ) * 1em),
y: height / (2*(y-max - y-min) * 1em)
)
for cmd in draw {
cmd(data, (x-min, x-max), (y-min, y-max))
}
}
)
}) + sym.space + h(0em, weak: true) |
https://github.com/yanwenywan/typst-packages | https://raw.githubusercontent.com/yanwenywan/typst-packages/master/dndstatblock/0.1.0/README.md | markdown | Apache License 2.0 | # dndstatblock
A template for writing statblocks (and only statblocks), in a simple style that imitates the 5e theme. It is intended to be fairly barebones and provide only formatting options, not dictate too much content.
It uses a two-column layout using open source versions of DnD fonts, as well as a traditional style Chinese font for CJK.
## Usage
This template can be initialised by calling
```
typst init @preview/dndstatblock:0.1.0
```
This will copy over all required fonts and comes prefilled with a statblock so you can see how it goes together. To use this you need to either install all the fonts locally or pass the folder into `--font-path` when compiling.
## Configuration
This template uses the `conf` function with the following named arguments:
- `header_left : content` the left hand side header
- `header_right : content` the right hand side header
- `footertext : content` the footer text (centred)
All other styling is set since this is trying to imitate a style (but feel free to copy and edit the package typ file if you need it different). An example is shown:
```typ
#import "@preview/dndstatblock:0.1.0": *
#show: conf.with(
header_left: "Typst Monster statblocks",
header_right: "Sample document",
footertext: [--Yanwenyuan--]
)
```
## Other Functions
**dice**`(value:str)` parses a dice string (e.g. `3d6` or `3d6+2` or `3d6-1`) and returns a formatted dice value (e.g. "10 (3d6)"). Specifically, the types of string it accepts are:
> `\d+d\d+([+-]\d+)?` (number `d` number `+/-` number)
(You need to make sure the string is correct)
**diceRaw**`(numDice:int, diceFace:int, modifier:int)` is a helper function of the above and can optionally be used -- it takes all values as integer values and prints the correct formatting.
**statheading**`(title, desc = [])` takes a title and description, and formats it into a top-level monster name heading. `desc` is the description of the monster, e.g. *Medium humanoid, neutral evil* but can be anything.
**stroke**`()` draws a red stroke with a fading right edge.
**mainstats**`(ac = "", hp_dice = "", speed = "30ft", hp_etc = "")` produces the **Armor Class**, **Hit Points**, **Speed** in one go. All fields are optional. `hp_dice` takes a *valid dice string only* -- if you do not want to use dice leave it blank and use `hp_etc`. No restrictions on other fields.
**ability**(str, dex, con, int, wis, cha)` Takes the six ability scores (base value) as integers and formats it into a table with appropriate modifiers.
**challenge**(cr:str)` takes a numeric challenge (as a string) rating and formats it along with the XP (if the challenge rating is valid). All CRs between 0-30 are valid, along with the fractional `1/8`, `1/4`, `1/2` (which can be written in decimal form too, e.g. `0.125`).
**skill**(title, contents)` takes a title and description, and is a single skills entry. For example, `#skill("Challenge", challenge(1))` will produce (in red)
> **Challenge** 1 (200 XP)
(This uses `challenge` from above)
**Section headers** such as *Actions* or *Reactions* are done using the second-level header `==`
**Action names** -- the names that go in front of actions / abilities are done using the third level header `===` (do not leave a blank line between the header and its body text)
## Sample Statblock
This is the statblock shown in the preview. A much simpler statblock is provided in the template.

## Acknowledgments
- The overall style is based on the [Dnd 5e LaTeX Template](https://github.com/rpgtex/DND-5e-LaTeX-Template)'s statblocks, which in turn replicate the base DnD aesthetic.
- TeX Gyre Bonum by GUST e-Foundry is used for the main title
- Scaly Sans and Scaly Sans Caps are part of [Solbera's CC Alternatives to DnD Fonts](https://github.com/jonathonf/solbera-dnd-fonts) and are used for main body text. ***Note that these fonts are CC-BY-SA i.e. Share-Alike, so keep that in mind. This shouldn't affect homebrew created using these fonts (just like how a painting made with a CC-BY-SA art program isn't itself CC-BY-SA) but what do I know I'm not a lawyer.***
- [KingHwa_OldSong](https://zhuanlan.zhihu.com/p/637491623) (京華老宋体) is a traditional Chinese print font used for all CJK text (if present, mostly because I need it)
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/051.%20startupfunding.html.typ | typst | startupfunding.html
How to Fund a Startup
Want to start a startup? Get funded by
Y Combinator.
November 2005
Venture funding works like gears. A typical startup goes through
several rounds of funding, and at each round you want to take just
enough money to reach the speed where you can shift into the next
gear.Few startups get it quite right. Many are underfunded. A few are
overfunded, which is like trying to start driving in third gear.I think it would help founders to understand funding better—not
just the mechanics of it, but what investors are thinking. I was
surprised recently when I realized that all the worst problems we
faced in our startup were due not to competitors, but investors.
Dealing with competitors was easy by comparison.I don't mean to suggest that our investors were nothing but a drag
on us. They were helpful in negotiating deals, for example. I
mean more that conflicts with investors are particularly nasty.
Competitors punch you in the jaw, but investors have you by the
balls.Apparently our situation was not unusual. And if trouble with
investors is one of the biggest threats to a startup, managing them
is one of the most important skills founders need to learn.Let's start by talking about the five sources of startup funding.
Then we'll trace the life of a hypothetical (very fortunate) startup
as it shifts gears through successive rounds.Friends and FamilyA lot of startups get their first funding from friends and family.
Excite did, for example: after the founders graduated from college,
they borrowed $15,000 from their parents to start a company. With
the help of some part-time jobs they made it last 18 months.If your friends or family happen to be rich, the line blurs between
them and angel investors. At Viaweb we got our first $10,000 of
seed money from our friend Julian, but he was sufficiently rich
that it's hard to say whether he should be classified as a friend
or angel. He was also a lawyer, which was great, because it meant
we didn't have to pay legal bills out of that initial small sum.The advantage of raising money from friends and family is that
they're easy to find. You already know them. There are three main
disadvantages: you mix together your business and personal life;
they will probably not be as well connected as angels or venture
firms; and they may not be accredited investors, which could
complicate your life later.The SEC defines an "accredited investor" as someone with over a
million dollars in liquid assets or an income of over $200,000 a
year. The regulatory burden is much lower if a company's shareholders
are all accredited investors. Once you take money from the general
public you're more restricted in what you can do.
[1]A startup's life will be more complicated, legally, if any of the
investors aren't accredited. In an IPO, it might not merely add
expense, but change the outcome. A lawyer I asked about it said:
When the company goes public, the SEC will carefully study all
prior issuances of stock by the company and demand that it take
immediate action to cure any past violations of securities laws.
Those remedial actions can delay, stall or even kill the IPO.
Of course the odds of any given startup doing an IPO are small.
But not as small as they might seem. A lot of startups that end up
going public didn't seem likely to at first. (Who could have guessed
that the company Wozniak and Jobs started in their spare time selling
plans for microcomputers would yield one of the biggest IPOs of the
decade?) Much of the value of a startup consists of that tiny
probability multiplied by the huge outcome.It wasn't because they weren't accredited investors that I didn't
ask my parents for seed money, though. When we were starting Viaweb,
I didn't know about the concept of an accredited investor, and
didn't stop to think about the value of investors' connections.
The reason I didn't take money from my parents was that I didn't
want them to lose it.ConsultingAnother way to fund a startup is to get a job. The best sort of
job is a consulting project in which you can build whatever software
you wanted to sell as a startup. Then you can gradually transform
yourself from a consulting company into a product company, and have
your clients pay your development expenses.This is a good plan for someone with kids, because it takes most
of the risk out of starting a startup. There never has to be a
time when you have no revenues. Risk and reward are usually
proportionate, however: you should expect a plan that cuts the risk
of starting a startup also to cut the average return. In this case,
you trade decreased financial risk for increased risk that your
company won't succeed as a startup.But isn't the consulting company itself a startup? No, not generally.
A company has to be more than small and newly founded to be a
startup. There are millions of small businesses in America, but
only a few thousand are startups. To be a startup, a company has
to be a product business, not a service business. By which I mean
not that it has to make something physical, but that it has to have
one thing it sells to many people, rather than doing custom work
for individual clients. Custom work doesn't scale. To be a startup
you need to be the band that sells a million copies of a song, not
the band that makes money by playing at individual weddings and bar
mitzvahs.The trouble with consulting is that clients have an awkward habit
of calling you on the phone. Most startups operate close to the
margin of failure, and the distraction of having to deal with clients
could be enough to put you over the edge. Especially if you have
competitors who get to work full time on just being a startup.So you have to be very disciplined if you take the consulting route.
You have to work actively to prevent your company growing into a
"weed tree," dependent on this source of easy but low-margin money.
[2]Indeed, the biggest danger of consulting may be that it gives you
an excuse for failure. In a startup, as in grad school, a lot of
what ends up driving you are the expectations of your family and
friends. Once you start a startup and tell everyone that's what
you're doing, you're now on a path labelled "get rich or bust." You
now have to get rich, or you've failed.Fear of failure is an extraordinarily powerful force. Usually it
prevents people from starting things, but once you publish some
definite ambition, it switches directions and starts working in
your favor. I think it's a pretty clever piece of jiujitsu to set
this irresistible force against the slightly less immovable object
of becoming rich. You won't have it driving you if your stated
ambition is merely to start a consulting company that you will one
day morph into a startup.An advantage of consulting, as a way to develop a product, is that
you know you're making something at least one customer wants. But
if you have what it takes to start a startup you should have
sufficient vision not to need this crutch.Angel InvestorsAngels are individual rich people. The word was first used
for backers of Broadway plays, but now applies to individual investors
generally. Angels who've made money in technology are preferable,
for two reasons: they understand your situation, and they're a
source of contacts and advice.The contacts and advice can be more important than the money. When
del.icio.us took money from investors, they took money from, among
others, <NAME>. The amount he put in was small compared to
the VCs who led the round, but Tim is a smart and influential guy
and it's good to have him on your side.You can do whatever you want with money from consulting or friends
and family. With angels we're now talking about venture funding
proper, so it's time to introduce the concept of exit strategy.
Younger would-be founders are often surprised that investors expect
them either to sell the company or go public. The reason is that
investors need to get their capital back. They'll only consider
companies that have an exit strategy—meaning companies that could
get bought or go public.This is not as selfish as it sounds. There are few large, private
technology companies. Those that don't fail all seem to get bought
or go public. The reason is that employees are investors too—of
their time—and they want just as much to be able to cash out. If
your competitors offer employees stock options that might make them
rich, while you make it clear you plan to stay private, your
competitors will get the best people. So the principle of an "exit"
is not just something forced on startups by investors, but part of
what it means to be a startup.Another concept we need to introduce now is valuation. When someone
buys shares in a company, that implicitly establishes a value for
it. If someone pays $20,000 for 10% of a company, the company is
in theory worth $200,000. I say "in theory" because in early stage
investing, valuations are voodoo. As a company gets more established,
its valuation gets closer to an actual market value. But in a newly
founded startup, the valuation number is just an artifact of the
respective contributions of everyone involved.Startups often "pay" investors who will help the company in some
way by letting them invest at low valuations. If I had a startup
and <NAME> wanted to invest in it, I'd give him the stock for
$10, just to be able to brag that he was an investor. Unfortunately,
it's impractical (if not illegal) to adjust the valuation of the
company up and down for each investor. Startups' valuations are
supposed to rise over time. So if you're going to sell cheap stock
to eminent angels, do it early, when it's natural for the company
to have a low valuation.Some angel investors join together in syndicates. Any city where
people start startups will have one or more of them. In Boston the
biggest is the Common
Angels. In the Bay Area it's the Band
of Angels. You can find groups near you through the Angel Capital Association.
[3]
However, most angel investors don't belong to these groups. In
fact, the more prominent the angel, the less likely they are to
belong to a group.Some angel groups charge you money to pitch your idea to them.
Needless to say, you should never do this.One of the dangers of taking investment from individual angels,
rather than through an angel group or investment firm, is that they
have less reputation to protect. A big-name VC firm will not screw
you too outrageously, because other founders would avoid them if
word got out. With individual angels you don't have this protection,
as we found to our dismay in our own startup. In many startups'
lives there comes a point when you're at the investors'
mercy—when you're out of money and the only place to get more is your
existing investors. When we got into such a scrape, our investors
took advantage of it in a way that a name-brand VC probably wouldn't
have.Angels have a corresponding advantage, however: they're also not
bound by all the rules that VC firms are. And so they can, for
example, allow founders to cash out partially in a funding round,
by selling some of their stock directly to the investors. I think
this will become more common; the average founder is eager to do
it, and selling, say, half a million dollars worth of stock will
not, as VCs fear, cause most founders to be any less committed to
the business.The same angels who tried to screw us also let us do this, and so
on balance I'm grateful rather than angry. (As in families, relations
between founders and investors can be complicated.)The best way to find angel investors is through personal introductions.
You could try to cold-call angel groups near you, but angels, like
VCs, will pay more attention to deals recommended by someone they
respect.Deal terms with angels vary a lot. There are no generally accepted
standards. Sometimes angels' deal terms are as fearsome as VCs'.
Other angels, particularly in the earliest stages, will invest based
on a two-page agreement.Angels who only invest occasionally may not themselves know what
terms they want. They just want to invest in this startup. What
kind of anti-dilution protection do they want? Hell if they know.
In these situations, the deal terms tend to be random: the angel
asks his lawyer to create a vanilla agreement, and the terms end
up being whatever the lawyer considers vanilla. Which in practice
usually means, whatever existing agreement he finds lying around
his firm. (Few legal documents are created from scratch.)These heaps o' boilerplate are a problem for small startups, because
they tend to grow into the union of all preceding documents. I
know of one startup that got from an angel investor what amounted
to a five hundred pound handshake: after deciding to invest, the
angel presented them with a 70-page agreement. The startup didn't
have enough money to pay a lawyer even to read it, let alone negotiate
the terms, so the deal fell through.One solution to this problem would be to have the startup's lawyer
produce the agreement, instead of the angel's. Some angels might
balk at this, but others would probably welcome it.Inexperienced angels often get cold feet when the time comes to
write that big check. In our startup, one of the two angels in the
initial round took months to pay us, and only did after repeated
nagging from our lawyer, who was also, fortunately, his lawyer.It's obvious why investors delay. Investing in startups is risky!
When a company is only two months old, every day you wait
gives you 1.7% more data about their trajectory. But the investor
is already being compensated for that risk in the low price of the
stock, so it is unfair to delay.Fair or not, investors do it if you let them. Even VCs do it. And
funding delays are a big distraction for founders, who ought to be
working on their company, not worrying about investors. What's a
startup to do? With both investors and acquirers, the only leverage
you have is competition. If an investor knows you have other
investors lined up, he'll be a lot more eager to close-- and not
just because he'll worry about losing the deal, but because if other
investors are interested, you must be worth investing in. It's the
same with acquisitions. No one wants to buy you till someone else
wants to buy you, and then everyone wants to buy you.The key to closing deals is never to stop pursuing alternatives.
When an investor says he wants to invest in you, or an acquirer
says they want to buy you, don't believe it till you get the
check. Your natural tendency when an investor says yes will
be to relax and go back to writing code. Alas, you can't; you have
to keep looking for more investors, if only to get this one to act.
[4]Seed Funding FirmsSeed firms are like angels in that they invest relatively small
amounts at early stages, but like VCs in that they're companies
that do it as a business, rather than individuals making occasional
investments on the side.Till now, nearly all seed firms have been so-called "incubators,"
so Y Combinator gets called
one too, though the only thing we have in common is that we invest
in the earliest phase.According to the National Association of Business Incubators, there
are about 800 incubators in the US. This is an astounding number,
because I know the founders of a lot of startups, and I can't think
of one that began in an incubator.What is an incubator? I'm not sure myself. The defining quality
seems to be that you work in their space. That's where the name
"incubator" comes from. They seem to vary a great deal in other
respects. At one extreme is the sort of pork-barrel project where
a town gets money from the state government to renovate a vacant
building as a "high-tech incubator," as if it were merely lack of
the right sort of office space that had till now prevented the town
from becoming a
startup hub.
At the other extreme are places like
Idealab, which generates ideas for new startups internally and hires
people to work for them.The classic Bubble incubators, most of which now seem to be dead,
were like VC firms except that they took a much bigger role in the
startups they funded. In addition to working in their space, you
were supposed to use their office staff, lawyers, accountants, and
so on.Whereas incubators tend (or tended) to exert more control than VCs,
Y Combinator exerts less.
And we think it's better if startups operate out of their own
premises, however crappy, than the offices of their investors. So
it's annoying that we keep getting called an "incubator," but perhaps
inevitable, because there's only one of us so far and no word yet
for what we are. If we have to be called something, the obvious
name would be "excubator." (The name is more excusable if one
considers it as meaning that we enable people to escape cubicles.)Because seed firms are companies rather than individual people,
reaching them is easier than reaching angels. Just go to their web
site and send them an email. The importance of personal introductions
varies, but is less than with angels or VCs.The fact that seed firms are companies also means the investment
process is more standardized. (This is generally true with angel
groups too.) Seed firms will probably have set deal terms they use
for every startup they fund. The fact that the deal terms are
standard doesn't mean they're favorable to you, but if other startups
have signed the same agreements and things went well for them, it's
a sign the terms are reasonable.Seed firms differ from angels and VCs in that they invest exclusively
in the earliest phases—often when the company is still just an
idea. Angels and even VC firms occasionally do this, but they also
invest at later stages.The problems are different in the early stages. For example, in
the first couple months a startup may completely redefine their idea. So seed investors usually care less
about the idea than the people. This is true of all venture funding,
but especially so in the seed stage.Like VCs, one of the advantages of seed firms is the advice they
offer. But because seed firms operate in an earlier phase, they
need to offer different kinds of advice. For example, a seed firm
should be able to give advice about how to approach VCs, which VCs
obviously don't need to do; whereas VCs should be able to give
advice about how to hire an "executive team," which is not an issue
in the seed stage.In the earliest phases, a lot of the problems are technical, so
seed firms should be able to help with technical as well as business
problems.Seed firms and angel investors generally want to invest in the
initial phases of a startup, then hand them off to VC firms for the
next round. Occasionally startups go from seed funding direct to
acquisition, however, and I expect this to become increasingly
common.Google has been aggressively pursuing this route, and now Yahoo is too. Both
now compete directly with VCs. And this is a smart move. Why wait
for further funding rounds to jack up a startup's price? When a
startup reaches the point where VCs have enough information to
invest in it, the acquirer should have enough information to buy
it. More information, in fact; with their technical depth, the
acquirers should be better at picking winners than VCs.Venture Capital FundsVC firms are like seed firms in that they're actual companies, but
they invest other people's money, and much larger amounts of it.
VC investments average several million dollars. So they tend to
come later in the life of a startup, are harder to get, and come
with tougher terms.The word "venture capitalist" is sometimes used loosely for any
venture investor, but there is a sharp difference between VCs and
other investors: VC firms are organized as funds, much like
hedge funds or mutual funds. The fund managers, who are called
"general partners," get about 2% of the fund annually as a management
fee, plus about 20% of the fund's gains.There is a very sharp dropoff in performance among VC firms, because
in the VC business both success and failure are self-perpetuating.
When an investment scores spectacularly, as Google did for Kleiner
and Sequoia, it generates a lot of good publicity for the VCs. And
many founders prefer to take money from successful VC firms, because
of the legitimacy it confers. Hence a vicious (for the losers)
cycle: VC firms that have been doing badly will only get the deals
the bigger fish have rejected, causing them to continue to do badly.As a result, of the thousand or so VC funds in the US now, only
about 50 are likely to make money, and it is very hard for a new
fund to break into this group.In a sense, the lower-tier VC firms are a bargain for founders.
They may not be quite as smart or as well connected as the big-name
firms, but they are much hungrier for deals. This means you should
be able to get better terms from them.Better how? The most obvious is valuation: they'll take less of
your company. But as well as money, there's power. I think founders
will increasingly be able to stay on as CEO, and on terms that will
make it fairly hard to fire them later.The most dramatic change, I predict,
is that VCs will allow founders to
cash out partially by selling
some of their stock direct to the VC firm. VCs have traditionally
resisted letting founders get anything before the ultimate "liquidity
event." But they're also desperate for deals. And since I know
from my own experience that the rule against buying stock from
founders is a stupid one, this is a natural place for things to
give as venture funding becomes more and more a seller's market.The disadvantage of taking money from less known firms is that
people will assume, correctly or not, that you were turned down by
the more exalted ones. But, like where you went to college, the
name of your VC stops mattering once you have some performance to
measure. So the more confident you are, the less you need a
brand-name VC. We funded Viaweb entirely with angel money; it never
occurred to us that the backing of a well known VC firm would make
us seem more impressive.
[5]Another danger of less known firms is that, like angels, they have
less reputation to protect. I suspect it's the lower-tier firms
that are responsible for most of the tricks that have given VCs
such a bad reputation among hackers. They are doubly hosed: the
general partners themselves are less able, and yet they have harder
problems to solve, because the top VCs skim off all the best deals,
leaving the lower-tier firms exactly the startups that are likely
to blow up.For example, lower-tier firms are much more likely to pretend to
want to do a deal with you just to lock you up while they decide
if they really want to. One experienced CFO said:
The better ones usually will not give a term sheet unless they
really want to do a deal. The second or third tier firms have a
much higher break rate—it could be as high as 50%.
It's obvious why: the lower-tier firms' biggest fear, when chance
throws them a bone, is that one of the big dogs will notice and
take it away. The big dogs don't have to worry about that.Falling victim to this trick could really hurt you. As one
VC told me:
If you were talking to four VCs, told three of them that you
accepted a term sheet, and then have to call them back to tell
them you were just kidding, you are absolutely damaged goods.
Here's a partial solution: when a VC offers you a term sheet, ask
how many of their last 10 term sheets turned into deals. This will
at least force them to lie outright if they want to mislead you.Not all the people who work at VC firms are partners. Most firms
also have a handful of junior employees called something like
associates or analysts. If you get a call from a VC
firm, go to their web site and check whether the person you talked
to is a partner. Odds are it will be a junior person; they scour
the web looking for startups their bosses could invest in. The
junior people will tend to seem very positive about your company.
They're not pretending; they want to believe you're a hot
prospect, because it would be a huge coup for them if their firm
invested in a company they discovered. Don't be misled by this
optimism. It's the partners who decide, and they view things with
a colder eye.Because VCs invest large amounts, the money comes with more
restrictions. Most only come into effect if the company gets into
trouble. For example, VCs generally write it into the deal that
in any sale, they get their investment back first. So if the company
gets sold at a low price, the founders could get nothing. Some VCs
now require that in any sale they get 4x their investment back
before the common stock holders (that is, you) get anything, but
this is an abuse that should be resisted.Another difference with large investments is that the founders are
usually required to accept "vesting"—to surrender their stock and
earn it back over the next 4-5 years. VCs don't want to invest
millions in a company the founders could just walk away from.
Financially, vesting has little effect, but in some situations it
could mean founders will have less power. If VCs got de facto
control of the company and fired one of the founders, he'd lose any
unvested stock unless there was specific protection against this.
So vesting would in that situation force founders to toe the line.The most noticeable change when a startup takes serious funding is
that the founders will no longer have complete control. Ten years
ago VCs used to insist that founders step down as CEO and hand the
job over to a business guy they supplied. This is less the rule
now, partly because the disasters of the Bubble showed that generic
business guys don't make such great CEOs.But while founders will increasingly be able to stay on as CEO,
they'll have to cede some power, because the board of directors
will become more powerful. In the seed stage, the board is generally
a formality; if you want to talk to the other board members, you
just yell into the next room. This stops with VC-scale money. In
a typical VC funding deal, the board of directors might be composed
of two VCs, two founders, and one outside person acceptable to both.
The board will have ultimate power, which means the founders now
have to convince instead of commanding.This is not as bad as it sounds, however. <NAME> is in the
same position; he doesn't have majority control of Microsoft; in
principle he also has to convince instead of commanding. And yet
he seems pretty commanding, doesn't he? As long as things are going
smoothly, boards don't interfere much. The danger comes when there's
a bump in the road, as happened to <NAME> at Apple.Like angels, VCs prefer to invest in deals that come to them through
people they know. So while nearly all VC funds have some address
you can send your business plan to, VCs privately admit the chance
of getting funding by this route is near zero. One recently told
me that he did not know a single startup that got funded this way.I suspect VCs accept business plans "over the transom" more as a
way to keep tabs on industry trends than as a source of deals. In
fact, I would strongly advise against mailing your business plan
randomly to VCs, because they treat this as evidence of laziness.
Do the extra work of getting personal introductions. As one VC put
it:
I'm not hard to find. I know a lot of people. If you can't find
some way to reach me, how are you going to create a successful
company?
One of the most difficult problems for startup founders is deciding
when to approach VCs. You really only get one chance, because they
rely heavily on first impressions. And you can't approach some and
save others for later, because (a) they ask who else you've talked
to and when and (b) they talk among themselves. If you're talking
to one VC and he finds out that you were rejected by another several
months ago, you'll definitely seem shopworn.So when do you approach VCs? When you can convince them. If the
founders have impressive resumes and the idea isn't hard to understand,
you could approach VCs quite early. Whereas if the founders are
unknown and the idea is very novel, you might have to launch the
thing and show that users loved it before VCs would be convinced.If several VCs are interested in you, they will sometimes be willing
to split the deal between them. They're more likely to do this if
they're close in the VC pecking order. Such deals may be a net win
for founders, because you get multiple VCs interested in your
success, and you can ask each for advice about the other. One
founder I know wrote:
Two-firm deals are great. It costs you a little more equity, but
being able to play the two firms off each other (as well as ask
one if the other is being out of line) is invaluable.
When you do negotiate with VCs, remember that they've done this a
lot more than you have. They've invested in dozens of startups,
whereas this is probably the first you've founded. But don't let
them or the situation intimidate you. The average founder is smarter
than the average VC. So just do what you'd do in any complex,
unfamiliar situation: proceed deliberately, and question anything
that seems odd.It is, unfortunately, common for VCs to put terms in an agreement
whose consequences surprise founders later, and also common for VCs
to defend things they do by saying that they're standard in the
industry. Standard, schmandard; the whole industry is only a few
decades old, and rapidly evolving. The concept of "standard" is a
useful one when you're operating on a small scale (Y Combinator
uses identical terms for every deal because for tiny seed-stage
investments it's not worth the overhead of negotiating individual
deals), but it doesn't apply at the VC level. On that scale, every
negotiation is unique.Most successful startups get money from more than one of the preceding
five sources.
[6]
And, confusingly, the names of funding sources
also tend to be used as the names of different rounds. The best
way to explain how it all works is to follow the case of a hypothetical
startup.Stage 1: Seed RoundOur startup begins when a group of three friends have an idea--
either an idea for something they might build, or simply the idea
"let's start a company." Presumably they already have some source
of food and shelter. But if you have food and shelter, you probably
also have something you're supposed to be working on: either
classwork, or a job. So if you want to work full-time on a startup,
your money situation will probably change too.A lot of startup founders say they started the company without any
idea of what they planned to do. This is actually less common than
it seems: many have to claim they thought of the idea after quitting
because otherwise their former employer would own it.The three friends decide to take the leap. Since most startups are
in competitive businesses, you not only want to work full-time on
them, but more than full-time. So some or all of the friends quit
their jobs or leave school. (Some of the founders in a startup can
stay in grad school, but at least one has to make the company his
full-time job.)They're going to run the company out of one of their apartments at
first, and since they don't have any users they don't have to pay
much for infrastructure. Their main expenses are setting up the
company, which costs a couple thousand dollars in legal work and
registration fees, and the living expenses of the founders.The phrase "seed investment" covers a broad range. To some VC firms
it means $500,000, but to most startups it means several months'
living expenses. We'll suppose our group of friends start with
$15,000 from their friend's rich uncle, who they give 5% of the
company in return. There's only common stock at this stage. They
leave 20% as an options pool for later employees (but they set
things up so that they can issue this stock to themselves if they
get bought early and most is still unissued), and the three founders
each get 25%.By living really cheaply they think they can make the remaining
money last five months. When you have five months' runway left,
how soon do you need to start looking for your next round? Answer:
immediately. It takes time to find investors, and time (always
more than you expect) for the deal to close even after they say
yes. So if our group of founders know what they're doing they'll
start sniffing around for angel investors right away. But of course
their main job is to build version 1 of their software.The friends might have liked to have more money in this first phase,
but being slightly underfunded teaches them an important lesson.
For a startup, cheapness is power. The lower your costs, the more
options you have—not just at this stage, but at every point till
you're profitable. When you have a high "burn rate," you're always
under time pressure, which means (a) you don't have time for your
ideas to evolve, and (b) you're often forced to take deals you don't
like.Every startup's rule should be: spend little, and work fast.After ten weeks' work the three friends have built a prototype that
gives one a taste of what their product will do. It's not what
they originally set out to do—in the process of writing it, they
had some new ideas. And it only does a fraction of what the finished
product will do, but that fraction includes stuff that no one else
has done before.They've also written at least a skeleton business plan, addressing
the five fundamental questions: what they're going to do, why users
need it, how large the market is, how they'll make money, and who
the competitors are and why this company is going to beat them.
(That last has to be more specific than "they suck" or "we'll work
really hard.")If you have to choose between spending time on the demo or the
business plan, spend most on the demo. Software is not only more
convincing, but a better way to explore ideas.Stage 2: Angel RoundWhile writing the prototype, the group has been traversing their
network of friends in search of angel investors. They find some
just as the prototype is demoable. When they demo it, one of the
angels is willing to invest. Now the group is looking for more
money: they want enough to last for a year, and maybe to hire a
couple friends. So they're going to raise $200,000.The angel agrees to invest at a pre-money valuation of $1 million.
The company issues $200,000 worth of new shares to the angel; if
there were 1000 shares before the deal, this means 200 additional
shares. The angel now owns 200/1200 shares, or a sixth of the
company, and all the previous shareholders' percentage ownership
is diluted by a sixth. After the deal, the capitalization table
looks like this:
shareholder shares percent
-------------------------------
angel 200 16.7
uncle 50 4.2
each founder 250 20.8
option pool 200 16.7
---- -----
total 1200 100
To keep things simple, I had the angel do a straight cash for stock
deal. In reality the angel might be more likely to make the
investment in the form of a convertible loan. A convertible loan
is a loan that can be converted into stock later; it works out the
same as a stock purchase in the end, but gives the angel more
protection against being squashed by VCs in future rounds.Who pays the legal bills for this deal? The startup, remember,
only has a couple thousand left. In practice this turns out to be
a sticky problem that usually gets solved in some improvised way.
Maybe the startup can find lawyers who will do it cheaply in the
hope of future work if the startup succeeds. Maybe someone has a
lawyer friend. Maybe the angel pays for his lawyer to represent
both sides. (Make sure if you take the latter route that the lawyer
is representing you rather than merely advising you, or his
only duty is to the investor.)An angel investing $200k would probably expect a seat on the board
of directors. He might also want preferred stock, meaning a special
class of stock that has some additional rights over the common stock
everyone else has. Typically these rights include vetoes over major
strategic decisions, protection against being diluted in future
rounds, and the right to get one's investment back first if the
company is sold.Some investors might expect the founders to accept vesting for a
sum this size, and others wouldn't. VCs are more likely to require
vesting than angels. At Viaweb we managed to raise $2.5 million
from angels without ever accepting vesting, largely because we were
so inexperienced that we were appalled at the idea. In practice
this turned out to be good, because it made us harder to push around.Our experience was unusual; vesting is the norm for amounts that
size. Y Combinator doesn't require vesting, because (a) we invest
such small amounts, and (b) we think it's unnecessary, and that the
hope of getting rich is enough motivation to keep founders at work.
But maybe if we were investing millions we would think differently.I should add that vesting is also a way for founders to protect
themselves against one another. It solves the problem of what to
do if one of the founders quits. So some founders impose it on
themselves when they start the company.The angel deal takes two weeks to close, so we are now three months
into the life of the company.The point after you get the first big chunk of angel money will
usually be the happiest phase in a startup's life. It's a lot like
being a postdoc: you have no immediate financial worries, and few
responsibilities. You get to work on juicy kinds of work, like
designing software. You don't have to spend time on bureaucratic
stuff, because you haven't hired any bureaucrats yet. Enjoy it
while it lasts, and get as much done as you can, because you will
never again be so productive.With an apparently inexhaustible sum of money sitting safely in the
bank, the founders happily set to work turning their prototype into
something they can release. They hire one of their friends—at
first just as a consultant, so they can try him out—and then a
month later as employee #1. They pay him the smallest salary he can
live on, plus 3% of the company in restricted stock, vesting over
four years. (So after this the option pool is down to 13.7%).
[7]
They also spend a little money on a freelance graphic designer.How much stock do you give early employees? That varies so much
that there's no conventional number. If you get someone really
good, really early, it might be wise to give him as much stock as
the founders. The one universal rule is that the amount of stock
an employee gets decreases polynomially with the age of the company.
In other words, you get rich as a power of how early you were. So
if some friends want you to come work for their startup, don't wait
several months before deciding.A month later, at the end of month four, our group of founders have
something they can launch. Gradually through word of mouth they
start to get users. Seeing the system in use by real users—people
they don't know—gives them lots of new ideas. Also they find
they now worry obsessively about the status of their server. (How
relaxing founders' lives must have been when startups wrote VisiCalc.)By the end of month six, the system is starting to have a solid
core of features, and a small but devoted following. People start
to write about it, and the founders are starting to feel like experts
in their field.We'll assume that their startup is one that could put millions more
to use. Perhaps they need to spend a lot on marketing, or build
some kind of expensive infrastructure, or hire highly paid salesmen.
So they decide to start talking to VCs. They get introductions to
VCs from various sources: their angel investor connects them with
a couple; they meet a few at conferences; a couple VCs call them
after reading about them.Step 3: Series A RoundArmed with their now somewhat fleshed-out business plan and able
to demo a real, working system, the founders visit the VCs they
have introductions to. They find the VCs intimidating and inscrutable.
They all ask the same question: who else have you pitched to? (VCs
are like high school girls: they're acutely aware of their position
in the VC pecking order, and their interest in a company is a
function of the interest other VCs show in it.)One of the VC firms says they want to invest and offers the founders
a term sheet. A term sheet is a summary of what the deal terms
will be when and if they do a deal; lawyers will fill in the details
later. By accepting the term sheet, the startup agrees to turn
away other VCs for some set amount of time while this firm does the
"due diligence" required for the deal. Due diligence is the corporate
equivalent of a background check: the purpose is to uncover any
hidden bombs that might sink the company later, like serious design
flaws in the product, pending lawsuits against the company,
intellectual property issues, and so on. VCs' legal and financial
due diligence is pretty thorough, but the technical due diligence
is generally a joke.
[8]The due diligence discloses no ticking bombs, and six weeks later
they go ahead with the deal. Here are the terms: a $2 million
investment at a pre-money valuation of $4 million, meaning that
after the deal closes the VCs will own a third of the company (2 /
(4 + 2)). The VCs also insist that prior to the deal the option
pool be enlarged by an additional hundred shares. So the total
number of new shares issued is 750, and the cap table becomes:
shareholder shares percent
-------------------------------
VCs 650 33.3
angel 200 10.3
uncle 50 2.6
each founder 250 12.8
employee 36* 1.8 *unvested
option pool 264 13.5
---- -----
total 1950 100
This picture is unrealistic in several respects. For example, while
the percentages might end up looking like this, it's unlikely that
the VCs would keep the existing numbers of shares. In fact, every
bit of the startup's paperwork would probably be replaced, as if
the company were being founded anew. Also, the money might come
in several tranches, the later ones subject to various
conditions—though this is apparently more common in deals with lower-tier VCs
(whose lot in life is to fund more dubious startups) than with the
top firms.And of course any VCs reading this are probably rolling on the floor
laughing at how my hypothetical VCs let the angel keep his 10.3 of
the company. I admit, this is the Bambi version; in simplifying
the picture, I've also made everyone nicer. In the real world, VCs
regard angels the way a jealous husband feels about his wife's
previous boyfriends. To them the company didn't exist before they
invested in it.
[9]I don't want to give the impression you have to do an angel round
before going to VCs. In this example I stretched things out to
show multiple sources of funding in action. Some startups could go
directly from seed funding to a VC round; several of the companies
we've funded have.The founders are required to vest their shares over four years, and
the board is now reconstituted to consist of two VCs, two founders,
and a fifth person acceptable to both. The angel investor cheerfully
surrenders his board seat.At this point there is nothing new our startup can teach us about
funding—or at least, nothing good.
[10]
The startup will almost
certainly hire more people at this point; those millions must be
put to work, after all. The company may do additional funding
rounds, presumably at higher valuations. They may if they are
extraordinarily fortunate do an IPO, which we should remember is
also in principle a round of funding, regardless of its de facto
purpose. But that, if not beyond the bounds of possibility, is
beyond the scope of this article.Deals Fall ThroughAnyone who's been through a startup will find the preceding portrait
to be missing something: disasters. If there's one thing all
startups have in common, it's that something is always going wrong.
And nowhere more than in matters of funding.For example, our hypothetical startup never spent more than half
of one round before securing the next. That's more ideal than
typical. Many startups—even successful ones—come close to
running out of money at some point. Terrible things happen to
startups when they run out of money, because they're designed for
growth, not adversity.But the most unrealistic thing about the series of deals I've
described is that they all closed. In the startup world, closing
is not what deals do. What deals do is fall through. If you're
starting a startup you would do well to remember that. Birds fly;
fish swim; deals fall through.Why? Partly the reason deals seem to fall through so often is that
you lie to yourself. You want the deal to close, so you start to
believe it will. But even correcting for this, startup deals fall
through alarmingly often—far more often than, say, deals to buy
real estate. The reason is that it's such a risky environment.
People about to fund or acquire a startup are prone to wicked cases
of buyer's remorse. They don't really grasp the risk they're taking
till the deal's about to close. And then they panic. And not just
inexperienced angel investors, but big companies too.So if you're a startup founder wondering why some angel investor
isn't returning your phone calls, you can at least take comfort in
the thought that the same thing is happening to other deals a hundred
times the size.The example of a startup's history that I've presented is like a
skeleton—accurate so far as it goes, but needing to be fleshed
out to be a complete picture. To get a complete picture, just add
in every possible disaster.A frightening prospect? In a way. And yet also in a way encouraging.
The very uncertainty of startups frightens away almost everyone.
People overvalue stability—especially young
people, who ironically need it least. And so in starting a startup,
as in any really bold undertaking, merely deciding to do it gets
you halfway there. On the day of the race, most of the other runners
won't show up.
Notes[1]
The aim of such regulations is to protect widows and orphans
from crooked investment schemes; people with a million dollars in
liquid assets are assumed to be able to protect themselves.
The unintended consequence is that the investments that generate
the highest returns, like hedge funds, are available only to the
rich.[2]
Consulting is where product companies go to die. IBM is the
most famous example. So starting as a consulting company is like
starting out in the grave and trying to work your way up into the
world of the living.[3]
If "near you" doesn't mean the Bay Area, Boston, or Seattle,
consider moving. It's not a coincidence you haven't heard of many
startups from Philadelphia.[4]
Investors are often compared to sheep. And they are like sheep,
but that's a rational response to their situation. Sheep act the
way they do for a reason. If all the other sheep head for a certain
field, it's probably good grazing. And when a wolf appears, is he
going to eat a sheep in the middle of the flock, or one near the
edge?[5]
This was partly confidence, and partly simple ignorance. We
didn't know ourselves which VC firms were the impressive ones. We
thought software was all that mattered. But that turned out to be
the right direction to be naive in: it's much better to overestimate
than underestimate the importance of making a good product.[6]
I've omitted one source: government grants. I don't think
these are even worth thinking about for the average startup.
Governments may mean well when they set up grant programs to encourage
startups, but what they give with one hand they take away with the
other: the process of applying is inevitably so arduous, and the
restrictions on what you can do with the money so burdensome, that
it would be easier to take a job to get the money.
You should be especially suspicious of grants whose purpose is some
kind of social engineering-- e.g. to encourage more startups to be
started in Mississippi. Free money to start a startup in a place
where few succeed is hardly free.Some government agencies run venture funding groups, which make
investments rather than giving grants. For example, the CIA runs
a venture fund called In-Q-Tel that is modelled on private sector
funds and apparently generates good returns. They would probably
be worth approaching—if you don't mind taking money from the CIA.[7]
Options have largely been replaced with restricted stock, which
amounts to the same thing. Instead of earning the right to buy
stock, the employee gets the stock up front, and earns the right
not to have to give it back. The shares set aside for this purpose
are still called the "option pool."[8]
First-rate technical people do not generally hire themselves
out to do due diligence for VCs. So the most difficult
part for startup founders is often responding politely to the inane
questions of the "expert" they send to look you over.[9]
VCs regularly wipe out angels by issuing arbitrary amounts of
new stock. They seem to have a standard piece of casuistry for
this situation: that the angels are no longer working to help the
company, and so don't deserve to keep their stock. This of course
reflects a willful misunderstanding of what investment means; like
any investor, the angel is being compensated for risks he took
earlier. By a similar logic, one could argue that the VCs should
be deprived of their shares when the company goes public.[10]
One new thing the company might encounter is a down
round, or a funding round at valuation lower than the previous
round. Down rounds are bad news; it is generally the common stock
holders who take the hit. Some of the most fearsome provisions in
VC deal terms have to do with down rounds—like "full ratchet
anti-dilution," which is as frightening as it sounds.Founders are tempted to ignore these clauses, because they think
the company will either be a big success or a complete bust. VCs
know otherwise: it's not uncommon for startups to have moments of
adversity before they ultimately succeed. So it's worth negotiating
anti-dilution provisions, even though you don't think you need to,
and VCs will try to make you feel that you're being gratuitously
troublesome.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
and <NAME> for reading drafts of this.Arabic Translation
|
|
https://github.com/DaAlbrecht/thesis-TEKO | https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Implementation.typ | typst | #import "@preview/tablex:0.0.5": tablex, cellx
#import "@preview/codelst:1.0.0": sourcecode
#show figure.where(kind: raw): set block(breakable: true)
The entire project is available on #link("https://github.com/DaAlbrecht/rabbit-revival/tree/main")[GitHub] and
licensed under the MIT license. For a clearer understanding and reasoning of the
design decisions, the code is documented inline with syntax highlighting and a
short description to each snippet is provided.
== Prerequisites
For the development of the replay microservice, the following tools are required:
#figure(
tablex(
columns: (auto,1fr,auto),
rows:(auto),
align: (center + horizon, left, left),
[*Name*],
[*Description*],
[*Install*],
[Rust],
[The microservice is written in Rust. The Rust toolchain is required to build the microservice.],
[#link("https://www.rust-lang.org/tools/install")],
[Docker],
[The microservice aswell as RabbitMQ are run in docker containers.],
[#link("https://docs.docker.com/get-docker/")],
[RabbitMQ],
[The microservice uses RabbitMQ as a message broker.],
[The container can be started as shown in @api-lib-setup],
[curl],
[The microservice can be tested using curl.],
[#link("https://curl.se/download.html")],
),
kind: table,
caption: [development prerequisites]
)
== Project setup
The replay microservice Rust project was created, and as a development name the name "rabbit-revival" was chosen. The project is created using the following command:
#figure(sourcecode(numbering: none)[```bash
cargo new rabbit-revival
cd rabbit-revival
```], caption: [create project])
Rust does not provide a large standard library, instead, it relies on third-party
crates for many basic functionalities. Based on the @architecture axum is used
as a web framework, Tokio is used for asynchronous runtime and lapin is used
as a RabbitMQ client. The dependencies and other commonly used crates are added to the Cargo.toml file:
#figure(sourcecode(numbering: none)[```bash
cargo add tokio --features full
cargo add axum
cargo add lapin
cargo add serde --features derive
cargo add serde_json
cargo add anyhow
```], caption: [common dependencies])
#figure(
tablex(
columns: (auto,1fr),
rows:(auto),
align: (center + horizon, left),
[*Name*],
[*Description*],
[Tokio],
[Tokio is an asynchronous runtime],
[axum],
[axum is a web framework created by the tokio team],
[lapin],
[lapin is a RabbitMQ client],
[Serde],
[Serde is a serialization / deserialization framework],
[Serde_json],
[Serde json is a Serde implementation for json],
[anyhow],
[anyhow is a crate for easy error handling],
),
kind: table,
caption: [overview of commonly used crates]
)
With the basic project setup done, the first task is to implement the web service according to the OpenAPI specification from @openapi_specification
== Webservice
In order to understand the implementation of the replay microservice, first some basic concepts of axum are explained.
=== axum concepts
Axum uses tower#footnote("https://docs.rs/tower/latest/tower/index.html") under the hood. Tower is a high-level abstraction for
networking applications. The basic idea is that a trait #footnote("https://doc.rust-lang.org/book/ch10-02-traits.html") called
`Serivce` exists. This service receives a request and returns either a response or
an error.
#figure(
sourcecode()[```rust
pub trait Service<Request> {
fn poll_ready(&mut self,cx: &mut Context<'_>) ->
Poll<Result<(), Self::Error>>;
fn call(&mut self, req: Request) -> Self::Future;
}
```],
caption: [stripped down tower service trait]
)
Since a `Service` is generic, any middleware that also implements the `Service`
trait can be used allowing axum to use a large ecosystem of middleware.
Axum like any other web sever needs to be able to handle multiple requests concurrently, making a web server
inherently asynchronous.
#figure(
sourcecode()[```rust
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(print_hello));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
```,],
caption: [axum routing]
)
Rust uses colored functions#footnote(
"https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/",
) and therefore, functions that call asynchronous functions need to be marked as
asynchronous as well. Since Rust does not provide an asynchronous runtime it's not
possible to declare the main entrypoint with the `async` keyword. Tokio uses the
macro `#[tokio::main]` to allow specifying the main function as asynchronous.#footnote("https://tokio.rs/tokio/tutorial/hello-tokio")
without needing to use the runtime or builder directly.
The macro transforms the main function into the following code:
#figure(
sourcecode()[```rust
fn main() {
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let app = Router::new().route("/", get(print_hello));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
})
}
```],
)
The main function handles the creation of the axum server and starts the server.
In axum, the routing is handled by the `Router` struct. The `Router` matches request paths to Rust functions called `Handlers` based on the HTTP method filter.
#figure(
sourcecode()[```rust
let app = Router::new()
.route("/", get(print_hello));
```],
caption: [routing]
)
Afterwards, the server is bound to a socket address and the server is started
with the `serve` method. The `serve` method consumes an object that can be
turned into a service and transforms it into a service.
#figure(
sourcecode()[```rust
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
})
```],
caption: [starting the server]
)
#pagebreak()
To better visualize the relationship between a service and a handler the
the following program is used to demonstrate their purpose.
#figure(
sourcecode()[```rust
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
// build our application with a single route
let app = Router::new().route("/", get(print_hello));
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn print_hello() -> &'static str {
"Hello, World!"
}
```],
caption: [hello world example]
)<hello_world_example>
The router is created with a single route that matches the path `/` and the
method `GET`. If a request is received that matches the route of the HTTP method,
the function `print_hello` is called. The function returns a string that is
converted into a response by axum. The response is then sent to the client.
#sourcecode(numbering: none)[```bash
cargo run
curl 'localhost:3000'
> hello world
```]
In the example above the `print_hello` handler takes no arguments and just returns
a static string. In the OpenAPI specification, the replay microservice needs to be able to
receive query parameters or a JSON body.
#linebreak()
In axum there are `Extractors`. Extractors are used to extract data from the request.
An Extract implements *either* the `FromRequest` or the `FromRequestParts` trait.
The difference between the two is, that the `FromRequest` consumes the request body
and thus can only be used once. The `FromRequestParts` trait does not consume the
request body and can be used multiple times.
#pagebreak()
So if we consider the following modified hello world example:
#figure(
sourcecode()[```rust
use std::collections::HashMap;
use axum::{extract::Query, routing::get, Router};
#[tokio::main]
async fn main() {
// build our application with a single route
let app = Router::new().route("/", get(print_hello));
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn print_hello(Query(query): Query<HashMap<String, String>>) -> String {
let hello = query.get("foo").unwrap();
let world = query.get("baz").unwrap();
let hello_world = format!("{} {}", hello, world);
hello_world
}
```],
caption: [extracting query parameters]
)<extraxting_query_parameters>
The handler `print_hello` takes an extractor as an argument. The extractor `Query`
extractor implements the `FromRequestParts` trait. The `Query` extractor deserializes
the query parameters into some type that implements `Deserialize`. In this case,
the query parameters are deserialized into a `HashMap<String, String>`.
#sourcecode(numbering: none)[```bash
curl 'localhost:3000?foo=hello&baz=world'
> hello world
```]
So to recap, a `Handler` is a function that takes zero or more `Extractors` as arguments and returns something
that can be turned into a `Response`.
#linebreak()
A `Response` is every type that implements the `IntoResponse` trait. axum implements
the trait for many common types like `String`, `&str`, `Vec<u8>`, `Json`, and many more.
#pagebreak()
But the real magic of axum is the demonstrate in the next examples.
#figure(
sourcecode()[```rust
use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router};
#[derive(serde::Serialize)]
struct User {
name: String,
age: u8,
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(print_hello))
.route("/user", get(print_user));
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn print_hello() -> &'static str {
"Hello, World!"
}
async fn print_user() -> impl IntoResponse {
(
StatusCode::OK,
Json(User {
name: "Bob".to_string(),
age: 20,
}),
)
}
```],
caption: [IntoResponse]
)<IntoResponse>
#sourcecode(numbering: none)[```bash
curl -v 'localhost:3000/user'
* Trying 127.0.0.1:3000...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /user HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 200 OK
< content-type: application/json
< content-length: 23
< date: Mon, 09 Oct 2023 13:21:21 GMT
<
* Connection #0 to host localhost left intact
{"name":"Bob","age":20}
```]
A new custom type called `User` is created. The crate `serde` is used to derive
the `Serialize` trait for the `User` struct. Deriving in that sense means that
the trait gets automatically implemented for the struct.
The important part is that as stated earlier, a handler returns something that
can be turned into a `Response`. We can use this fact and, instead of returning a concrete
type like `String` or `&str` we can tell the compiler that the handler returns
something that implements the `IntoResponse` trait with the following line:
#sourcecode(numbering: none)[```rust
async fn print_user() -> impl IntoResponse
```]
But how does our own custom type `User` implement the `IntoResponse` trait? The
answer and beautiful part of axum is that it does not. Instead axum uses macros#footnote("https://doc.rust-lang.org/book/ch19-06-macros.html")
to automatically implement the `IntoResponse` trait for tuples of different
sizes.
In the documentation of axum @docrs_into_response its visible that the trait is implemented for tuples of size 0 to 16.
If we look at an example of the implementation of the trait a pattern is visible.
#figure(
image("../assets/into_response.png"),
caption: [IntoResponse implementations]
)
The implementation of the trait is generic over the types `T` and `R`. Any tuple
from size 0 to 16 can be turned into a response *iff* the last element of the tuple
implements the `IntoResponse` trait and the other elements implement the `IntoResponseParts` trait.
The `IntoResponseParts` trait is used to add headers to the response while the
`IntoResponse` trait is used generate the response.
There are other automatic implementations of the `IntoResponse` trait that follow
a similar pattern.
#figure(
image("../assets/into_response_status_code.png"),
caption: [IntoResponse implementations]
)
For example, tuples of size 0 to 16 where the first element
implements the `StatusCode` and just like before, the last element implements the
`IntoResponse` trait while the other elements implement the `IntoResponseParts` trait.
So in conclusion, axum uses a router to match requests to handlers. `Handlers`
are functions that take zero or more `Extractors` as arguments and return
something that can be turned into a `Response`.With the help of `Extractors` and
`Responses` axum ensures runtime type safety. A `Response` is every type that
implements the `IntoResponse` trait. The `IntoResponse` trait is automatically
implemented for commonly used types aswell as different sized tuples. It is also
possible to implement the trait manually for specific use cases.
Let's check the return value from the example shown in @IntoResponse again:
#sourcecode(numbering: none)[```rust
(
StatusCode::OK,
Json(User {
name: "Bob".to_string(),
age: 20,
}),
)
```]
In the example above the return value is a tuple of size 2. According to the
documentation the following implementation should fit
#sourcecode(numbering: none)[```rust
impl<R> IntoResponse for (StatusCode, R)
where
R: IntoResponse,
```]
The first element of the tuple is a `StatusCode`, so this is correct. And the
second element of the tuple is a `Json<User>`. In the documentation of `axum::Json`,
the following implementation is shown:
#sourcecode(numbering: none)[```rust
impl<T> IntoResponse for Json<T>
where
T: Serialize,
```]
The `User` struct implements the `Serialize` trait, allowing Serde to represent the struct as JSON, so this is correct and the Return value
indeed implements the `IntoResponse` trait.
#linebreak()
This allows us to model the OpenAPI specification as Rust struct's using them either as return type or as extractor and letting Serde take care of the serialization and deserialization.
#pagebreak()
=== Implementation
The main function is responsible for composing and starting the server.
#figure(
sourcecode()[```rust
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| {
"rabbit_revival=debug,tower_http=trace,axum::rejection=trace"
.into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let app = Router::new()
.route("/replay", get(get_messages).post(replay))
.layer(TraceLayer::new_for_http())
.with_state(initialize_state().await);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::info!("Listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
```],
caption: [main function]
)
The main function is marked as asynchronous using the `#[tokio::main]` macro.
#linebreak()
Tracing has been identified as an essential use case, thus the first thing the main function does is initialize tracing. Tracing is a
framework for instrumenting Rust programs with structured logging and diagnostics.
Tracing is provided by the crate `tracing`#footnote("https://docs.rs/tracing/latest/tracing/") and `tracing-subscriber`#footnote("https://docs.rs/tracing-subscriber/0.3.17/tracing_subscriber/").
#figure(
sourcecode()[```rust
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| {
"rabbit_revival=debug,tower_http=trace,axum::rejection=trace"
.into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
```],
caption: [tracing initialization]
)
The tracing subscriber is initialized by the default
environment variable `RUST_LOG` or set to the provided default value.
#linebreak()
Afterwards, an axum router is created.
#figure(
sourcecode()[```rust
let app = Router::new()
.route("/replay", get(get_messages).post(replay))
.layer(TraceLayer::new_for_http())
.with_state(initialize_state().await);
```],
caption: [axum router]
)
The router is created with one route that matches the path `/replay`.
The route has two `MethodFilter`s attached to it. The first filter matches the
`GET` method and the second filter matches the `POST` method. The `GET` method
is handled by the `get_messages` handler and the `POST` method is handled by the
`replay` handler.
The feature `tracing`#footnote("https://docs.rs/axum/0.6.20/axum/index.html#feature-flags") is
enabled for axum. Tower services can be composed using the `Layer` trait.
Tracing is added as middleware to the router using the `layer` method.
Additionally, some state needs to be shared between handlers and therefore the
`with_state` method is used to add the state to the router.
The state is initialized using the `initialize_state` function.
#figure(
sourcecode()[```rust
async fn initialize_state() -> Arc<AppState> {
let pool_size = std::env::var("AMQP_CONNECTION_POOL_SIZE")
.unwrap_or("5".into())
.parse::<usize>()
.unwrap();
let username = std::env::var("AMQP_USERNAME").unwrap_or("guest".into());
let password = std::env::var("AMQP_PASSWORD").unwrap_or("<PASSWORD>".into());
let host = std::env::var("AMQP_HOST").unwrap_or("localhost".into());
let amqp_port = std::env::var("AMQP_PORT").unwrap_or("5672".into());
let management_port = std::env::var("AMQP_MANAGEMENT_PORT").unwrap_or("15672".into());
let transaction_header = std::env::var("AMQP_TRANSACTION_HEADER")
.ok()
.filter(|s| !s.is_empty());
let enable_timestamp = std::env::var("AMQP_ENABLE_TIMESTAMP")
.unwrap_or("true".into())
.parse::<bool>()
.unwrap();
let publish_options = MessageOptions {
transaction_header,
enable_timestamp,
};
let amqp_config = RabbitmqApiConfig {
username: username.clone(),
password: <PASSWORD>(),
host: host.clone(),
port: management_port.clone(),
};
let mut cfg = Config::default();
cfg.url = Some(format!(
"amqp://{}:{}@{}:{}/%2f",
username, password, host, amqp_port
));
cfg.pool = Some(PoolConfig::new(pool_size));
let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
Arc::new(AppState {
pool,
message_options: publish_options,
amqp_config,
})
}
```],
caption: [initialize state]
)
The function is marked as asynchronous using the `async` keyword and returns an
`Arc<AppState>`.
#sourcecode(numbering: none)[```rust
async fn initialize_state() -> Arc<AppState>
```]
`Arc` is an abbreviation for atomic reference counter. The `Arc` type allows
multiple ownership of the same data while ensuring thread safety. The `Arc` type
is used to share the state between handlers.
`AppState` is custom struct that holds the state of the application.
#figure(
sourcecode()[```rust
struct AppState {
pool: deadpool_lapin::Pool,
message_options: MessageOptions,
amqp_config: RabbitmqApiConfig,
}
```],
caption: [AppState]
)
The struct holds a pool of amqp connections, its recommended to use long-lived
connections to amqp and create separate channels for each thread. The other fields
hold a struct `MessageOptions` and a struct `RabbitmqApiConfig`.
#figure(
sourcecode()[```rust
#[derive(Clone)]
pub struct MessageOptions {
transaction_header: Option<String>,
enable_timestamp: bool,
}
```],
caption: [MessageOptions]
)<MessageOptions>
When replaying a message from the stream, the message gets published again. The
API supports adding a uid to a custom header. Additionally, the API supports adding a timestamp to the message. Both options are configurable using environment
variables and are optional.
#figure(
sourcecode()[```rust
#[derive(Debug)]
pub struct RabbitmqApiConfig {
username: String,
password: <PASSWORD>,
host: String,
port: String,
}
```],
caption: [RabbitmqApiConfig]
)
The `RabbitmqApiConfig` struct holds the configuration for the RabbitMQ
management API. The AMQP protocol lacks a way to query the state of a queue. To
acquire the metadata of a queue the RabbitMQ management API is used.
#linebreak()
First, in the `initialize_state` function the environment variables are read.
#figure(
sourcecode()[```rust
let pool_size = std::env::var("AMQP_CONNECTION_POOL_SIZE")
.unwrap_or("5".into())
.parse::<usize>()
.unwrap();
let username = std::env::var("AMQP_USERNAME").unwrap_or("guest".into());
let password = std::env::var("AMQP_PASSWORD").unwrap_or("guest".into());
let host = std::env::var("AMQP_HOST").unwrap_or("localhost".into());
let amqp_port = std::env::var("AMQP_PORT").unwrap_or("5672".into());
let management_port = std::env::var("AMQP_MANAGEMENT_PORT").unwrap_or("15672".into());
let transaction_header = std::env::var("AMQP_TRANSACTION_HEADER")
.ok()
.filter(|s| !s.is_empty());
let enable_timestamp = std::env::var("AMQP_ENABLE_TIMESTAMP")
.unwrap_or("true".into())
.parse::<bool>()
.unwrap();
```],
caption: [read environment variables]
)
Each environment variable is read and if the variable is not set a default value
is provided.
#linebreak()
Afterward, the three structs, required to initialize the state are created.
#figure(
sourcecode()[```rust
let publish_options = MessageOptions {
transaction_header,
enable_timestamp,
};
let amqp_config = RabbitmqApiConfig {
username: username.clone(),
password: <PASSWORD>.clone(),
host: host.clone(),
port: management_port.clone(),
};
let mut cfg = Config::default();
cfg.url = Some(format!(
"amqp://{}:{}@{}:{}/%2f",
username, password, host, amqp_port
));
cfg.pool = Some(PoolConfig::new(pool_size));
let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
```],
caption: [create required AppState structs]
)
A new `Arc<AppState>` is created and returned.
#figure(
sourcecode()[```rust
Arc::new(AppState {
pool,
message_options: publish_options,
amqp_config,
})
```],
caption: [return AppState]
)
After the router is created, the server is bound to the socket address
`127.0.0.1:3000` and the server is started.
#figure(
sourcecode()[```rust
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::info!("Listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
```],
caption: [starting the server]
)
The `get_messages` handler allows to get information about queues and messages
#figure(
sourcecode()[```rust
async fn get_messages(
app_state: State<Arc<AppState>>,
Query(message_query): Query<MessageQuery>,
) -> Result<impl IntoResponse, AppError> {
let messages = fetch_messages(
&app_state.pool.clone(),
&app_state.amqp_config,
&app_state.message_options,
message_query,
)
.await?;
Ok((StatusCode::OK, Json(messages)))
}
```],
caption: [get_messages handler]
)
The handler takes two arguments. The first argument is the application state,
the second argument is an extractor. The extractor is used to extract the query
parameters from the request. The query parameters are deserialized into a struct
called `MessageQuery`.
#figure(
sourcecode()[```rust
#[derive(serde::Deserialize, Debug)]
pub struct MessageQuery {
queue: String,
from: Option<DateTime<chrono::Utc>>,
to: Option<DateTime<chrono::Utc>>,
}
```],
caption: [MessageQuery]
)
The `MessageQuery` struct holds the query parameters. The `queue` parameter is
required and the `from` and `to` parameters are optional. The `from` and `to`
parameters are used to filter the messages by their timestamp.
Axum does the deserialization of the query parameters automatically and ensures
runtime type safety. If the query parameters are not valid, axum returns a sane
default error message.
#sourcecode(numbering: none)[```bash
curl 'localhost:3000/?hello=replay'
>Failed to deserialize query string: missing field `queue`
curl 'localhost:3000/?queue=foo&from=123'
>Failed to deserialize query string: premature end of input
curl 'localhost:3000/?queue=foo&from=bar'
>Failed to deserialize query string: input contains invalid characters
```]
The handler returns a ```rust Result<impl IntoResponse, AppError>```.
By returning a Result, the handlers can be written in a more idiomatic way and
take advantage of the `?` operator. The `?` operator is used to propagate errors.
Axum does not know how to turn an `AppError` into a response. In
the axum examples#footnote("https://github.com/tokio-rs/axum/tree/axum-0.6.21/examples")
there is an example, on how to use the `anyhow` crate#footnote("https://docs.rs/anyhow/1.0.40/anyhow/")
to handle errors.
#linebreak()
In order to tell axum how to turn an `AppError` into a response, the `IntoResponse`
trait needs to be implemented for the `AppError` type.
#figure(
sourcecode()[```rust
//https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs
// Make our own error that wraps `anyhow::Error`.
struct AppError(anyhow::Error);
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
// `Result<_, AppError>`. That way you don't need to do that manually.
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}
```],
caption: [AppError]
)
The `get_messages` handler calls the function `fetch_messages`, awaits the future
and messages in a JSON format as well as a status code.
#figure(
sourcecode()[```rust
let messages = fetch_messages(
&app_state.pool.clone(),
&app_state.amqp_config,
&app_state.message_options,
message_query,
)
.await?;
Ok((StatusCode::OK, Json(messages)))
```],
caption: [get_messages function body]
)
The `fetch_messages` function is responsible for fetching the messages from the Queue and is shown in @fetch_messages.
#linebreak()
The other handler is the `replay` handler. The `replay` handler is responsible for
replaying messages from the stream.
#figure(
sourcecode()[```rust
async fn replay(
app_state: State<Arc<AppState>>,
Json(replay_mode): Json<ReplayMode>,
) -> Result<impl IntoResponse, AppError> {
let pool = app_state.pool.clone();
let message_options = app_state.message_options.clone();
let messages = match replay_mode {
ReplayMode::TimeFrameReplay(timeframe) => {
replay_time_frame(&pool, &app_state.amqp_config, timeframe).await?
}
ReplayMode::HeaderReplay(header) => {
replay_header(&pool, &app_state.amqp_config, header).await?
}
};
let replayed_messages = replay::publish_message(&pool, &message_options, messages).await?;
Ok((StatusCode::OK, Json(replayed_messages)))
}
```],
caption: [replay handler]
)
According to the OpenAPI specification from the microservice shown in @openapi_specification,
the POST method supports two different kinds of schema.
#linebreak()
To represent the two different kinds of schema, an enum is used.
#figure(
sourcecode()[```rust
#[derive(serde::Deserialize, Debug)]
#[serde(untagged)]
enum ReplayMode {
TimeFrameReplay(TimeFrameReplay),
HeaderReplay(HeaderReplay),
}
```],
caption: [ReplayMode]
)
The enum holds two variants representing the two different kinds of schema.
#linebreak()
The first variant is called `TimeFrameReplay` and requires the name of the `queue`
and a `from` and `to` parameter. The `from` and `to` parameters are used to filter
the messages by their timestamp.
#figure(
sourcecode()[```rust
#[derive(serde::Deserialize, Debug)]
pub struct TimeFrameReplay {
queue: String,
from: DateTime<chrono::Utc>,
to: DateTime<chrono::Utc>,
}
```],
caption: [TimeFrameReplay]
)
The second variant is called `HeaderReplay` and requires the name of the `queue`
and the header that should be replayed.
#figure(
sourcecode()[```rust
#[derive(serde::Deserialize, Debug)]
pub struct HeaderReplay {
queue: String,
header: AMQPHeader,
}
```],
caption: [HeaderReplay]
)
#figure(
sourcecode()[```rust
#[derive(serde::Deserialize, Debug)]
struct AMQPHeader {
name: String,
value: String,
}
```],
caption: [AMQPHeader]
)
The enum is annotated with `#[serde(untagged)]`.
#linebreak()
The `#[serde(untagged)]` attribute is used to tell Serde to not explicitly identify
one of the variants of the enum. Instead, Serde tries to deserialize the JSON into
each variant in order and returns the first variant that succeeds.
#pagebreak()
Without the `#[serde(untagged)]` attribute, the following JSON body representing a time-based replay would be invalid.
#sourcecode(numbering: none)[```json
{
"queue":"replay",
"from":"2023-10-06T13:41:35.870Z",
"to":"2023-10-09T13:41:35.883Z"
}
```]
Instead, the JSON body would need to look like this:
#sourcecode(numbering: none)[```json
{
"TimeFrameReplay": {
"queue":"replay",
"from":"2023-10-06T13:41:35.870Z",
"to":"2023-10-09T13:41:35.883Z"
}
}
```]
Similarly to the `get_messages` handler, the `replay` handler takes two arguments.
The first argument is the application state and the second argument is an extractor.
The extractor is used to extract the JSON body from the request. The JSON body is
serialized into the `ReplayMode` enum.
#sourcecode(numbering: none)[```rust
async fn replay(
app_state: State<Arc<AppState>>,
Json(replay_mode): Json<ReplayMode>,
) -> Result<impl IntoResponse, AppError> {
```]
The `replay` handler just like the `get_messages` handler returns a ```rust
Result<impl IntoResponse, AppError>```
In the function body serialized JSON body is matched against the two variants of
the `ReplayMode` enum. Depending on the variant, the `replay_time_frame` or the
`replay_header` function is called.
#figure(
sourcecode()[```rs
let messages = match replay_mode {
ReplayMode::TimeFrameReplay(timeframe) => {
replay_time_frame(&pool, &app_state.amqp_config, timeframe).await?
}
ReplayMode::HeaderReplay(header) => {
replay_header(&pool, &app_state.amqp_config, header).await?
}
};
```],
caption: [match replay_mode]
)
The `replay_time_frame` function shown in @replay_time_frame or the `replay_header`
function shown in @replay_header returns the messages that should be replayed.
#pagebreak()
The vector of messages is passed to the `publish_message` function shown in @publish_message,
and later the newly published messages are returned as JSON as well as a status code 200.
#figure(
sourcecode()[```rs
let replayed_messages = replay::publish_message(&pool, &message_options, messages).await?;
Ok((StatusCode::OK, Json(replayed_messages)))
```],
caption: [publish and return messages]
)
== Replay component
The replay component has four key functions.
#figure(tablex(
columns: (auto, 1fr,auto),
rows: (auto),
align: (center + horizon, left,center + horizon),
[*Name*],
[*Description*],
[*Link*],
[fetch_messages],
[returns a list of all messages in the queue based on the given filter],
[@heading_fetch_messages],
[replay_header],
[returns a list of messages that contain the given header],
[@heading_replay_header],
[replay_time_frame],
[returns a list of messages that are between the given timestamps],
[@heading_replay_time_frame],
[publish_message],
[publishes a list of messages to the queue],
[@heading_publish_message],
[get_queue_message_count],
[returns the number of messages in the queue],
[@heading_get_queue_message_count],
), kind: table, caption: [replay key functions])
=== fetch_messages<heading_fetch_messages>
The `fetch_messages` function gets called when the `get_messages` handler is invoked.
#figure(
sourcecode()[```rs
pub async fn fetch_messages(
pool: &deadpool_lapin::Pool,
rabbitmq_api_config: &RabbitmqApiConfig,
message_options: &MessageOptions,
message_query: MessageQuery,
) -> Result<Vec<Message>> {
let message_count =
match get_queue_message_count(&rabbitmq_api_config, message_query.queue.as_str()).await? {
Some(message_count) => message_count,
None => {
return Err(anyhow!("Queue not found or empty"));
}
};
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
channel
.basic_qos(1000u16, BasicQosOptions { global: false })
.await?;
let mut consumer = channel
.basic_consume(
&message_query.queue,
"fetch_messages",
BasicConsumeOptions::default(),
stream_consume_args(AMQPValue::LongString("first".into())),
)
.await?;
let mut messages = Vec::new();
while let Some(Ok(delivery)) = consumer.next().await {
delivery.ack(BasicAckOptions::default()).await?;
let headers = match delivery.properties.headers().as_ref() {
Some(headers) => headers,
None => return Err(anyhow!("No headers found")),
};
let transaction = match message_options.transaction_header.clone() {
Some(transaction_header) => match headers.inner().get(transaction_header.as_str()) {
Some(AMQPValue::LongString(transaction_id)) => Some(TransactionHeader {
name: transaction_header,
value: transaction_id.to_string(),
}),
_ => None,
},
None => None,
};
let offset = match headers.inner().get("x-stream-offset") {
Some(AMQPValue::LongLongInt(offset)) => offset,
_ => return Err(anyhow!("x-stream-offset not found")),
};
let timestamp = *delivery.properties.timestamp();
match is_within_timeframe(timestamp, message_query.from, message_query.to) {
Some(true) => {
if *offset >= i64::try_from(message_count - 1)? {
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: Some(
chrono::Utc
.timestamp_millis_opt(timestamp.unwrap() as i64)
.unwrap(),
),
data: String::from_utf8(delivery.data)?,
});
break;
}
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: Some(
chrono::Utc
.timestamp_millis_opt(timestamp.unwrap() as i64)
.unwrap(),
),
data: String::from_utf8(delivery.data)?,
});
}
Some(false) => {
if *offset >= i64::try_from(message_count - 1)? {
break;
}
continue;
}
None => {
if *offset >= i64::try_from(message_count - 1)? {
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: None,
data: String::from_utf8(delivery.data)?,
});
break;
}
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: None,
data: String::from_utf8(delivery.data)?,
});
}
}
}
Ok(messages)
}
```],
caption: [fetch_messages]
)<fetch_messages>
The function takes four arguments. The first argument is a reference to the
connection pool. The second argument is a reference to the `RabbitmqApiConfig`
struct. The third argument is a reference to the `MessageOptions` struct. The
fourth argument is a `MessageQuery` struct.
#figure(
sourcecode()[```rs
pub async fn fetch_messages(
pool: &deadpool_lapin::Pool,
rabbitmq_api_config: &RabbitmqApiConfig,
message_options: &MessageOptions,
message_query: MessageQuery,
) -> Result<Vec<Message>> {
```],
caption: [fetch_messages function signature]
)
The function returns a `Result<Vec<Message>>`.
#linebreak()
The `Message` holds the data that will be returned to the client.
#figure(
sourcecode()[```rs
#[derive(Serialize, Debug)]
pub struct Message {
#[serde(skip_serializing_if = "Option::is_none")]
offset: Option<u64>,
transaction: Option<TransactionHeader>,
timestamp: Option<chrono::DateTime<chrono::Utc>>,
data: String,
}
```],
caption: [Message]
)<Message_struct>
Each message in a stream has an offset. The offset is used to identify the
`x-stream-offset` header. The offset is optional on the `Message` struct because
the offset is only available when the message gets read from the stream. If the
message is being published, the publisher does not know the offset of the
message. Consumers could keep track of the last acknowledged offset and use this
to identify the next message to consume from the stream.
#linebreak()
The `#[serde(skip_serializing_if = "Option::is_none")]` attribute is used to
skip serializing the field if the field is `None`. This results in a cleaner
JSON response.
#linebreak()
As shown in the @MessageOptions, the microservice can be configured to add a
transaction ID to the message. The transaction ID is added to the message as a
custom header. If this option is enabled, the `TransactionHeader` struct holds the name of the header and the value of the header for the specific
message.
#figure(
sourcecode()[```rs
#[derive(Serialize, Debug)]
pub struct TransactionHeader {
name: String,
value: String,
}
```],
caption: [TransactionHeader]
)
Just like the transaction header, the timestamp is optional.
#linebreak()
The `data` field holds the actual message data.
First, the number of messages in the queue is fetched with the `get_queue_message_count`
function shown in @heading_get_queue_message_count.
#figure(
sourcecode()[```rs
let message_count =
match get_queue_message_count(&rabbitmq_api_config, message_query.queue.as_str()).await? {
Some(message_count) => message_count,
None => {
return Err(anyhow!("Queue not found or empty"));
}
};
```],
caption: [match message count]
)
After the number of messages in the queue is known, a connection to the AMQP
server is established. A channel is created and the `basic_qos` method is called
on the channel. The `basic_qos` method is used to limit the number of messages
that are being prefetched from the queue. The `basic_qos` method is called with
a prefetch count of 1000. This means that the channel will only prefetch 1000
messages from the queue. This is necessary because the queue could contain
millions of messages and the microservice should not consume all messages at
once. If the microservice consumes all messages at once, the microservice
could run out of memory if the queue contains millions of messages.
#figure(
sourcecode()[```rs
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
channel
.basic_qos(1000u16, BasicQosOptions { global: false })
.await?;
```],
caption: [create channel and set prefetch count]
)
The `basic_consume` method is called on the channel. The `basic_consume` method
is used to consume messages from the queue. The `basic_consume` method is called
with the name of the queue, a consumer tag, the `BasicConsumeOptions` and the
`stream_consume_args` function.
#figure(
sourcecode()[```rs
let mut consumer = channel
.basic_consume(
&message_query.queue,
"fetch_messages",
BasicConsumeOptions::default(),
stream_consume_args(AMQPValue::LongString("first".into())),
)
.await?;
```],
caption: [consume messages from queue]
)
The `basic_consume` method returns a `Consumer`. The `Consumer` implements the
`Stream` trait. The `Consumer` is used to iterate over the messages in the queue.
#linebreak()
The `stream_consume_args` function takes an `AMQPValue` as an argument and
returns a `FieldTable`. The `FieldTable` is used to pass additional AMQP
arguments to the `basic_consume` method. The `x-stream-offset` argument is used
to specify the start position of the stream. The `x-stream-offset` argument is
set to `first`. This means the consumer will start reading from the first
message in the queue.
#figure(
sourcecode()[```rs
fn stream_consume_args(stream_offset: AMQPValue) -> FieldTable {
let mut args = FieldTable::default();
args.insert(ShortString::from("x-stream-offset"), stream_offset);
args
}
```],
caption: [stream_consume_args]
)
The `Consumer` is used to iterate over the messages in the queue. The `Consumer`
is a stream and the `next` method is called on the `Consumer`. The `next` method
returns an `Option<Result<Delivery>>`. The `Delivery` struct holds the message
data and the message metadata.
An issue with the consumer is, the consumer does not know when to stop
consuming messages. The consumer is a subscription-based approach. The consumer
will keep consuming messages until the connection is closed. Therefore the
iterator would never stop.
#linebreak()
The `while let` loop is used to iterate over the messages and lift the `Option`
and `Result` from the `Consumer`.
#figure(
sourcecode()[```rs
while let Some(Ok(delivery)) = consumer.next().await {
```],
caption: [consume messages from queue]
)
The `ack` method is called on the `Delivery`. The `ack` method is used to
acknowledge the message. If the message is not acknowledged, the message will be
redelivered to the consumer. If no message is acknowledged, the queue
will not send more messages than the prefetch count.
#figure(
sourcecode()[```rs
delivery.ack(BasicAckOptions::default()).await?;
```],
caption: [acknowledge message]
)
The `headers` property is extracted from the `Delivery`.
#figure(
sourcecode()[```rs
let headers = match delivery.properties.headers().as_ref() {
Some(headers) => headers,
None => return Err(anyhow!("No headers found")),
};
```],
caption: [extract headers]
)
Next, depending on the configuration, the transaction header is extracted from
the `message_options` struct. If the transaction header is present, the
transaction header is extracted from the `headers` struct. If the transaction
header is not present, the transaction header is set to `None`.
#figure(
sourcecode()[```rs
let transaction = match message_options.transaction_header.clone() {
Some(transaction_header) => match headers.inner().get(transaction_header.as_str()) {
Some(AMQPValue::LongString(transaction_id)) => Some(TransactionHeader {
name: transaction_header,
value: transaction_id.to_string(),
}),
_ => None,
},
None => None,
};
```],
caption: [extract transaction header]
)
Since the consumer would never know when to stop consuming messages, the offset
of the message is extracted. The offset together with the number of messages in
the queue is used to determine if the message is the last in the queue.
#figure(
sourcecode()[```rs
let offset = match headers.inner().get("x-stream-offset") {
Some(AMQPValue::LongLongInt(offset)) => offset,
_ => return Err(anyhow!("x-stream-offset not found")),
};
```],
caption: [extract offset]
)
If for some unknown reason, the `x-stream-offset` header is not present, an error
is returned.
After the offset is extracted, the timestamp is extracted from the `Delivery`
and the function `is_within_timeframe` is called. The `is_within_timeframe`
function shown in @heading_is_within_timeframe is used to determine if the
message is within the timeframe specified by the request.
#figure(
sourcecode()[```rs
let timestamp = *delivery.properties.timestamp();
match is_within_timeframe(timestamp, message_query.from, message_query.to) {
```],
caption: [extract timestamp and call is_within_timeframe]
)
If the message is within the timeframe, the timestamp of the message is converted from a `u64` to a
`chrono::DateTime<chrono::Utc>` and the message is pushed to the `messages`
vector.
#linebreak()
If the message has a timestamp and a time range is specified that does not
contain the message, the message is skipped.
#linebreak()
If the message does not have a timestamp and no time range is specified, the message is pushed to the `messages` vector.
#figure(
sourcecode(
highlighted: (35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,47,48,49,50,51),
)[```rs
match is_within_timeframe(timestamp, message_query.from, message_query.to) {
Some(true) => {
if *offset >= i64::try_from(message_count - 1)? {
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: Some(
//unwrap is save here, because we checked if timestamp is set
chrono::Utc
.timestamp_millis_opt(timestamp.unwrap() as i64)
.unwrap(),
),
data: String::from_utf8(delivery.data)?,
});
break;
}
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: Some(
//unwrap is save here, because we checked if timestamp is set
chrono::Utc
.timestamp_millis_opt(timestamp.unwrap() as i64)
.unwrap(),
),
data: String::from_utf8(delivery.data)?,
});
}
Some(false) => {
if *offset >= i64::try_from(message_count - 1)? {
break;
}
continue;
}
None => {
if *offset >= i64::try_from(message_count - 1)? {
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: None,
data: String::from_utf8(delivery.data)?,
});
break;
}
messages.push(Message {
offset: Some(*offset as u64),
transaction,
timestamp: None,
data: String::from_utf8(delivery.data)?,
});
}
}
```],
caption: [fetch_messages match is_within_timeframe]
)
By returning `None` from `is_within_timeframe` no additional check on the
timestamp is necessary because the difference between *not being in the timeframe*
and *not having a timestamp* is already handled by the `is_within_timeframe`
function shown in @heading_is_within_timeframe.
#linebreak()
Additionally, in each iteration the offset is checked if it is the last message,
to determine if the loop should be exited.
#sourcecode(numbering: none)[```rs
if *offset >= i64::try_from(message_count - 1)?{
```]
If the offset is the last message, the message is pushed to the `messages`
vector and the loop is exited.
#linebreak()
The pushed messages are returned from the `fetch_messages` function.
#sourcecode(numbering: none)[```rs
Ok(messages)
```]
=== replay_header<heading_replay_header>
The `replay_header` function gets called when messages should be replayed based
on a message header. The function returns zero or more messages *iff* the
message header value and the message header name match the given header value
and header name.
#figure(
sourcecode()[```rs
pub async fn replay_header(
pool: &deadpool_lapin::Pool,
rabbitmq_api_config: &RabbitmqApiConfig,
header_replay: HeaderReplay,
) -> Result<Vec<Delivery>> {
let message_count =
match get_queue_message_count(&rabbitmq_api_config, &header_replay.queue).await? {
Some(message_count) => message_count,
None => return Err(anyhow!("Queue not found or empty")),
};
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
channel
.basic_qos(1000u16, BasicQosOptions { global: false })
.await?;
let mut consumer = channel
.basic_consume(
&header_replay.queue,
"replay",
BasicConsumeOptions::default(),
stream_consume_args(AMQPValue::LongString("first".into())),
)
.await?;
let mut messages = Vec::new();
while let Some(Ok(delivery)) = consumer.next().await {
delivery.ack(BasicAckOptions::default()).await?;
let headers = match delivery.properties.headers().as_ref() {
Some(headers) => headers,
None => return Err(anyhow!("No headers found")),
};
let target_header = headers.inner().get(header_replay.header.name.as_str());
let offset = match headers.inner().get("x-stream-offset") {
Some(AMQPValue::LongLongInt(offset)) => offset,
_ => return Err(anyhow!("Queue is not a stream")),
};
if *offset >= i64::try_from(message_count - 1)? {
if let Some(AMQPValue::LongString(header)) = target_header {
if *header.to_string() == header_replay.header.value {
messages.push(delivery);
}
}
break;
}
if let Some(AMQPValue::LongString(header)) = target_header {
if *header.to_string() == header_replay.header.value {
messages.push(delivery);
}
}
}
Ok(messages)
}
```],
caption: [replay_header]
)<replay_header>
The function takes three arguments. The first argument is a reference to the
connection pool. The second argument is a reference to the `RabbitmqApiConfig`
struct. The third argument is a `HeaderReplay` struct.
#figure(
sourcecode()[```rs
pub async fn replay_header(
pool: &deadpool_lapin::Pool,
rabbitmq_api_config: &RabbitmqApiConfig,
header_replay: HeaderReplay,
) -> Result<Vec<Delivery>> {
```],
caption: [replay_header function signature]
)
The function returns a `Result<Vec<Delivery>>`. The `Delivery`#footnote("https://docs.rs/lapin/latest/lapin/message/struct.Delivery.html") struct
represents a received AMQP message and is defined in the `lapin` crate.
#linebreak()
The function starts by fetching the number of messages in the queue. The number of
messages in the queue is used to determine if the message is the last message in the queue in the
same way as shown in @heading_fetch_messages.
#figure(
sourcecode()[```rs
let message_count =
match get_queue_message_count(&rabbitmq_api_config, &header_replay.queue).await? {
Some(message_count) => message_count,
None => return Err(anyhow!("Queue not found or empty")),
};
```],
caption: [match message count]
)
After the number of messages in the queue is known, a connection to the AMQP
server is established. A channel is created and the `basic_qos` method is called
on the channel.
#linebreak()
A new vector called `messages` is created. The `messages` vector is used to
store the messages that should be replayed.
#figure(
sourcecode()[```rs
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
channel
.basic_qos(1000u16, BasicQosOptions { global: false })
.await?;
let mut consumer = channel
.basic_consume(
&header_replay.queue,
"replay",
BasicConsumeOptions::default(),
stream_consume_args(AMQPValue::LongString("first".into())),
)
.await?;
let mut messages = Vec::new();
```],
caption: [create channel and set prefetch count]
)
The `next` method is called on the `Consumer` to iterate over the messages in the queue.
#figure(
sourcecode()[```rs
while let Some(Ok(delivery)) = consumer.next().await {
```],
caption: [consume messages from queue]
)
#pagebreak()
In the `while let` loop the `ack` method is called on the `Delivery`. After acknowledging the message,
the `headers` property is extracted from the `Delivery`.
#figure(
sourcecode()[```rs
delivery.ack(BasicAckOptions::default()).await?;
let headers = match delivery.properties.headers().as_ref() {
Some(headers) => headers,
None => return Err(anyhow!("No headers found")),
};
```],
caption: [extract headers]
)
The `target_header` is extracted from the `headers` struct. The `target_header` is the header that
should be matched against the `header_replay.header` field.
#figure(
sourcecode()[```rs
let target_header = headers.inner().get(header_replay.header.name.as_str());
```],
caption: [extract target header]
)
The `offset` is extracted from the `headers` struct. The `offset` is used to determine if the message
is the last message in the queue.
#figure(
sourcecode()[```rs
let offset = match headers.inner().get("x-stream-offset") {
Some(AMQPValue::LongLongInt(offset)) => offset,
_ => return Err(anyhow!("Queue is not a stream")),
};
```],
caption: [extract offset]
)
If the offset is the last message, the `target_header` is matched against the
`header_replay.header` field. If the `target_header` matches the
`header_replay.header` field, the `delivery` is pushed to the `messages` vector
and the loop is exited.
#figure(
sourcecode()[```rs
if *offset >= i64::try_from(message_count - 1)? {
if let Some(AMQPValue::LongString(header)) = target_header {
if *header.to_string() == header_replay.header.value {
messages.push(delivery);
}
}
break;
}
```],
caption: [match target header and break loop]
)
If the offset is not the last message, the `target_header` is matched against
the `header_replay.header` field. If the `target_header` matches the
`header_replay.header` field, the `delivery` is pushed to the `messages` vector. If
the `target_header` does not match the `header_replay.header` field, the message
is skipped.
#figure(
sourcecode()[```rs
if let Some(AMQPValue::LongString(header)) = target_header {
if *header.to_string() == header_replay.header.value {
messages.push(delivery);
}
}
```],
caption: [match target header]
)
The `messages` vector is returned from the `replay_header` function.
#figure(
sourcecode()[```rs
Ok(messages)
```],
caption: [return messages]
)
=== replay_time_frame<heading_replay_time_frame>
The `replay_time_frame` function gets called when messages should be replayed
based on a time frame. The function returns zero or more messages *iff* the
message timestamp is within the given time frame.
#figure(
sourcecode()[```rs
pub async fn replay_time_frame(
pool: &deadpool_lapin::Pool,
rabbitmq_api_config: &RabbitmqApiConfig,
time_frame: TimeFrameReplay,
) -> Result<Vec<Delivery>> {
let message_count =
match get_queue_message_count(&rabbitmq_api_config, &time_frame.queue).await? {
Some(message_count) => message_count,
None => return Err(anyhow!("Queue not found or empty")),
};
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
channel
.basic_qos(1000u16, BasicQosOptions { global: false })
.await?;
let mut consumer = channel
.basic_consume(
&time_frame.queue,
"replay",
BasicConsumeOptions::default(),
stream_consume_args(AMQPValue::LongString("first".into())),
)
.await?;
let mut messages = Vec::new();
while let Some(Ok(delivery)) = consumer.next().await {
delivery.ack(BasicAckOptions::default()).await?;
let headers = match delivery.properties.headers().as_ref() {
Some(headers) => headers,
None => return Err(anyhow!("No headers found")),
};
let offset = match headers.inner().get("x-stream-offset") {
Some(AMQPValue::LongLongInt(offset)) => offset,
_ => return Err(anyhow!("x-stream-offset not found")),
};
let timestamp = *delivery.properties.timestamp();
match is_within_timeframe(timestamp, Some(time_frame.from), Some(time_frame.to)) {
Some(true) => {
if *offset >= i64::try_from(message_count - 1)? {
messages.push(delivery);
break;
}
messages.push(delivery);
}
_ => {
if *offset >= i64::try_from(message_count - 1)? {
break;
}
continue;
}
}
}
Ok(messages)
}
```],
caption: [replay_time_frame]
)<replay_time_frame>
The function takes three arguments. The first argument is a reference to the
connection pool. The second argument is a reference to the `RabbitmqApiConfig`
struct. The third argument is a `TimeFrameReplay` struct.
#figure(
sourcecode()[```rs
pub async fn replay_time_frame(
pool: &deadpool_lapin::Pool,
rabbitmq_api_config: &RabbitmqApiConfig,
time_frame: TimeFrameReplay,
) -> Result<Vec<Delivery>> {
```],
caption: [replay_time_frame function signature]
)
The function returns a `Result<Vec<Delivery>>`. The `Delivery`#footnote("https://docs.rs/lapin/latest/lapin/message/struct.Delivery.html") struct
represents a received AMQP message and is defined in the `lapin` crate.
#linebreak()
The function starts by fetching the number of messages in the queue. The number of
messages in the queue is used to determine if the message is the last message in the queue in the
same way as shown in @heading_fetch_messages or @heading_replay_header.
#figure(
sourcecode()[```rs
let message_count =
match get_queue_message_count(&rabbitmq_api_config, &time_frame.queue).await? {
Some(message_count) => message_count,
None => return Err(anyhow!("Queue not found or empty")),
};
```],
caption: [match message count]
)
After the number of messages in the queue is known, a connection to the AMQP
server is established. A channel is created and the `basic_qos` method is called
on the channel.
#linebreak()
A new vector called `messages` is created. The `messages` vector is used to
store the messages that should be replayed.
#figure(
sourcecode()[```rs
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
channel
.basic_qos(1000u16, BasicQosOptions { global: false })
.await?;
let mut consumer = channel
.basic_consume(
&time_frame.queue,
"replay",
BasicConsumeOptions::default(),
stream_consume_args(AMQPValue::LongString("first".into())),
)
.await?;
let mut messages = Vec::new();
```],
caption: [create channel and set prefetch count]
)
The `next` method is called on the `Consumer` to iterate over the messages in the queue.
#figure(
sourcecode()[```rs
while let Some(Ok(delivery)) = consumer.next().await {
```],
caption: [consume messages from queue]
)
In the `while let` loop the `ack` method is called on the `Delivery`. After acknowledging the message,
the `headers` property is extracted from the `Delivery`.
#figure(
sourcecode()[```rs
delivery.ack(BasicAckOptions::default()).await?;
let headers = match delivery.properties.headers().as_ref() {
Some(headers) => headers,
None => return Err(anyhow!("No headers found")),
};
```],
caption: [extract headers]
)
The `offset` is extracted from the `headers` struct. The `offset` is used to determine if the message
is the last message in the queue.
#figure(
sourcecode()[```rs
let offset = match headers.inner().get("x-stream-offset") {
Some(AMQPValue::LongLongInt(offset)) => offset,
_ => return Err(anyhow!("x-stream-offset not found")),
};
```],
caption: [extract offset]
)
#pagebreak()
The `timestamp` is extracted from the `Delivery`. The `timestamp` is used as argument for the
`is_within_timeframe` function shown in @heading_is_within_timeframe. The `is_within_timeframe`
takes the `Delivery` timestamp, the `from` and the `to` fields of the `TimeFrameReplay` struct as
arguments. The `is_within_timeframe`.
#figure(
sourcecode()[```rs
let timestamp = *delivery.properties.timestamp();
match is_within_timeframe(timestamp, Some(time_frame.from), Some(time_frame.to)) {
Some(true) => {
if *offset >= i64::try_from(message_count - 1)? {
messages.push(delivery);
break;
}
messages.push(delivery);
}
_ => {
if *offset >= i64::try_from(message_count - 1)? {
break;
}
continue;
}
}
```],
caption: [match timeframe]
)
If the message is within the timeframe, the message is pushed to the `messages`
vector, additionally if the message is the last message in the queue, the loop
is exited.
#linebreak()
If the message is not within the timeframe, the message is skipped. If the
message is the last message in the queue, the loop is exited.
#linebreak()
Lastly the `messages` vector is returned from the `replay_time_frame` function.
#figure(
sourcecode()[```rs
Ok(messages)
```],
caption: [return messages]
)
#pagebreak()
=== is_within_timeframe<heading_is_within_timeframe>
The `is_within_timeframe` function takes three arguments. The first argument is
the timestamp of the message. The second argument is the `from` parameter of the
request. The third argument is the `to` parameter of the request. The function
returns an `Option<bool>`.
#figure(
sourcecode()[```rs
fn is_within_timeframe(
date: Option<u64>,
from: Option<chrono::DateTime<chrono::Utc>>,
to: Option<chrono::DateTime<chrono::Utc>>,
) -> Option<bool> {
match date {
Some(date) => {
let date = Utc.timestamp_millis_opt(date as i64).unwrap();
match (from, to) {
(Some(from), Some(to)) => Some(date >= from && date <= to),
(Some(from), None) => Some(date >= from),
(None, Some(to)) => Some(date <= to),
(None, None) => Some(true),
}
}
None => match (from, to) {
(None, None) => None,
_ => Some(false),
},
}
}
```],
caption: [is_within_timeframe]
)
The function checks if the message has a timestamp. If the message has a
timestamp, the function checks if the timestamp is within the given from and to
parameters. If the message does not have a timestamp, the function checks if the
from and to parameters are `None`. If the from and to parameters are `None`, the
function returns `None` otherwise the function returns `Some(false)`.
#linebreak()
The function needs to return an `Option<bool>` because the message does not
necessarily have a timestamp. If the message does not have a timestamp, the
function returns `None`. If the message has a timestamp, the function returns
`Some(true)` or `Some(false)` depending on the from and to parameters.
This results in the following matrix.
#figure(
tablex(
columns: (auto, auto, auto, 1fr),
rows: (auto),
align: (center + horizon, center + horizon, center + horizon, left),
[*message timestamp*],
[*from*],
[*to*],
[*result*],
[Some],
[Some],
[Some],
[Some(message timestamp >= from && message timestamp <= to)],
[Some],
[Some],
[None],
[Some(message timestamp >= from)],
[Some],
[None],
[Some],
[Some(message timestamp <= to)],
[Some],
[None],
[None],
[Some(true)],
[None],
[Some],
[Some],
[Some(false)],
[None],
[None],
[Some],
[Some(false)],
[None],
[Some],
[None],
[Some(false)],
cellx(fill: rgb(234, 234,189))[None],
cellx(fill: rgb(234, 234,189))[None],
cellx(fill: rgb(234, 234,189))[None],
cellx(fill: rgb(234, 234,189))[None],
),
kind: table,
caption: [is_within_timeframe matrix]
)<is_within_timeframe_matrix>
=== publish_message<heading_publish_message>
The `publish_message` function is used to publish messages that should be
replayed to the queue again.
#figure(
sourcecode()[```rs
pub async fn publish_message(
pool: &deadpool_lapin::Pool,
message_options: &MessageOptions,
messages: Vec<Delivery>,
) -> Result<Vec<Message>> {
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
let mut s = stream::iter(messages);
let mut replayed_messages = Vec::new();
while let Some(message) = s.next().await {
let mut transaction: Option<TransactionHeader> = None;
let mut timestamp: Option<chrono::DateTime<chrono::Utc>> = None;
let basic_props = match (
message_options.enable_timestamp,
message_options.transaction_header.clone(),
) {
(true, None) => {
timestamp = Some(chrono::Utc::now());
let timestamp_u64 = timestamp.unwrap().timestamp_millis() as u64;
lapin::BasicProperties::default().with_timestamp(timestamp_u64)
}
(true, Some(transaction_header)) => {
timestamp = Some(chrono::Utc::now());
let timestamp_u64 = timestamp.unwrap().timestamp_millis() as u64;
let uuid = uuid::Uuid::new_v4().to_string();
let mut headers = FieldTable::default();
headers.insert(
ShortString::from(transaction_header.as_str()),
AMQPValue::LongString(uuid.as_str().into()),
);
transaction = TransactionHeader::from_fieldtable(
headers.clone(),
transaction_header.as_str(),
)
.ok();
lapin::BasicProperties::default()
.with_headers(headers)
.with_timestamp(timestamp_u64)
}
(false, None) => lapin::BasicProperties::default(),
(false, Some(transaction_header)) => {
let uuid = uuid::Uuid::new_v4().to_string();
let mut headers = FieldTable::default();
headers.insert(
ShortString::from(transaction_header.as_str()),
AMQPValue::LongString(uuid.as_str().into()),
);
transaction = TransactionHeader::from_fieldtable(
headers.clone(),
transaction_header.as_str(),
)
.ok();
lapin::BasicProperties::default().with_headers(headers)
}
};
channel
.basic_publish(
message.exchange.as_str(),
message.routing_key.as_str(),
lapin::options::BasicPublishOptions::default(),
message.data.as_slice(),
basic_props,
)
.await?;
replayed_messages.push(Message {
offset: None,
transaction,
timestamp,
data: String::from_utf8(message.data)?,
});
}
Ok(replayed_messages)
}
```],
caption: [publish_message]
)<publish_message>
The function takes three arguments. The first argument is a reference to the
connection pool. The second argument is a reference to the `MessageOptions`
struct. The third argument is a vector of `Delivery` structs.
#figure(
sourcecode()[```rs
pub async fn publish_message(
pool: &deadpool_lapin::Pool,
message_options: &MessageOptions,
messages: Vec<Delivery>,
) -> Result<Vec<Message>> {
```],
caption: [publish_message function signature]
)
The function returns a `Result<Vec<Message>>`. The `Message` struct is defined
in @Message_struct.
#linebreak()
The function starts by establishing a connection to the AMQP server. A channel
is created and a stream#footnote("https://rust-lang.github.io/async-book/05_streams/01_chapter.html")
is created from the `messages` vector. A stream in Rust is an asynchronous
iterator. The `next` method is called on the stream to iterate over the messages
in the `messages` vector. A new vector called `replayed_messages` is created.
The `replayed_messages` vector is used to store the messages that should be
returned from the function to the client.
#figure(
sourcecode()[```rs
let connection = pool.get().await?;
let channel = connection.create_channel().await?;
let mut s = stream::iter(messages);
let mut replayed_messages = Vec::new();
while let Some(message) = s.next().await {
```],
caption: [create channel and stream]
)
As shown in @MessageOptions, the microservice supports
adding a custom transaction header or a timestamp to a message.
Both of these features are optional thus resulting in the following matrix.
#figure(
tablex(
columns: (auto, auto, 1fr),
rows: (auto),
align: (center + horizon, center + horizon, left),
[*enable_timestamp*],
[*transaction_header*],
[*result*],
[true],
[None],
[timestamp is added to message],
[true],
[Some],
[timestamp and transaction header are added to message],
[false],
[Some],
[transaction header is added to message],
[false],
[None],
[no timestamp or transaction header are added to message],
),
kind: table,
caption: [publish options matrix]
)<publish_options_matrix>
To represent the matrix in code, the `enable_timestamp` and `transaction_header`
field are matched as tuples.
#figure(
sourcecode()[```rs
let basic_props = match (
message_options.enable_timestamp,
message_options.transaction_header.clone(),
) {
(true, None) => {
timestamp = Some(chrono::Utc::now());
let timestamp_u64 = timestamp.unwrap().timestamp_millis() as u64;
lapin::BasicProperties::default().with_timestamp(timestamp_u64)
}
(true, Some(transaction_header)) => {
timestamp = Some(chrono::Utc::now());
let timestamp_u64 = timestamp.unwrap().timestamp_millis() as u64;
let uuid = uuid::Uuid::new_v4().to_string();
let mut headers = FieldTable::default();
headers.insert(
ShortString::from(transaction_header.as_str()),
AMQPValue::LongString(uuid.as_str().into()),
);
transaction = TransactionHeader::from_fieldtable(
headers.clone(),
transaction_header.as_str(),
)
.ok();
lapin::BasicProperties::default()
.with_headers(headers)
.with_timestamp(timestamp_u64)
}
(false, None) => lapin::BasicProperties::default(),
(false, Some(transaction_header)) => {
let uuid = uuid::Uuid::new_v4().to_string();
let mut headers = FieldTable::default();
headers.insert(
ShortString::from(transaction_header.as_str()),
AMQPValue::LongString(uuid.as_str().into()),
);
transaction = TransactionHeader::from_fieldtable(
headers.clone(),
transaction_header.as_str(),
)
.ok();
lapin::BasicProperties::default().with_headers(headers)
}
};
```],
caption: [match publish options]
)
Each match arm sets the needed amqp properties and headers according to the
matrix shown in @publish_options_matrix.
#linebreak()
After the needed properties are set, the `basic_publish` method is called on the
channel. The routing key, exchange and data are taken from message.
The same message is pushed to the `replayed_messages` vector.
#figure(
sourcecode()[```rs
channel
.basic_publish(
message.exchange.as_str(),
message.routing_key.as_str(),
lapin::options::BasicPublishOptions::default(),
message.data.as_slice(),
basic_props,
)
.await?;
replayed_messages.push(Message {
offset: None,
transaction,
timestamp,
data: String::from_utf8(message.data)?,
});
```],
caption: [publish messages again]
)
The `replayed_messages` vector is returned from the `publish_message` function.
#figure(
sourcecode()[```rs
Ok(replayed_messages)
```],
caption: [return replayed messages]
)
=== get_queue_message_count<heading_get_queue_message_count>
The `get_queue_message_count` function is used to retrieve metadata about the
queue using the RabbitMQ management API. This is necessary because the AMQP
protocol does not provide a way to check if a queue does actually exist or how many messages are in the queue. The only way to get the
number of messages in a queue using the AMQP protocol is to declare the queue
again. If the queue already exists, the number of messages in
the queue is returned as wanted but if the queue does not exist, the queue gets
created. This is not the desired behaviour. Therefore the RabbitMQ management
API is used.
#figure(
sourcecode()[```rs
async fn get_queue_message_count(
rabitmq_api_config: &RabbitmqApiConfig,
name: &str,
) -> Result<Option<u64>> {
let client = reqwest::Client::new();
let url = format!(
"http://{}:{}/api/queues/%2f/{}",
rabitmq_api_config.host, rabitmq_api_config.port, name
);
let res = client
.get(url)
.basic_auth(
rabitmq_api_config.username.clone(),
Some(rabitmq_api_config.password.clone()),
)
.send()
.await?
.json::<serde_json::Value>()
.await?;
if let Some(res) = res.get("type") {
if res != "stream" {
return Err(anyhow!("Queue is not a stream"));
}
}
let message_count = res.get("messages");
match message_count {
Some(message_count) => Ok(Some(message_count.as_u64().unwrap())),
None => Ok(None),
}
}
```],
caption: [get_queue_message_count]
)
The function takes two arguments. The first argument is a reference to the
`RabbitmqApiConfig` struct. The second argument is a reference to the name of
the queue that should be queried.
#figure(
sourcecode()[```rs
async fn get_queue_message_count(
rabitmq_api_config: &RabbitmqApiConfig,
name: &str,
) -> Result<Option<u64>> {
```],
caption: [get_queue_message_count function signature]
)
The function returns a `Result<Option<u64>>`.
If the queue is not of type `stream` an error is returned otherwise the number
of messages in the queue is returned.
#pagebreak()
First, a new HTTP client is created. The URL to the RabbitMQ management API is
constructed using the `RabbitmqApiConfig` struct.
#figure(
sourcecode()[```rs
let client = reqwest::Client::new();
let url = format!(
"http://{}:{}/api/queues/%2f/{}",
rabitmq_api_config.host, rabitmq_api_config.port, name
);
```],
caption: [create HTTP client]
)
The client is used to send a `GET` request to the RabbitMQ management API.
The management API is protected by basic authentication. Therefore the username
and password are added to the request.
The response is deserialized into a `serde_json::Value` struct.
#figure(
sourcecode()[```rs
let res = client
.get(url)
.basic_auth(
rabitmq_api_config.username.clone(),
Some(rabitmq_api_config.password.clone()),
)
.send()
.await?
.json::<serde_json::Value>()
.await?;
```],
caption: [send a GET request to RabbitMQ management API]
)
The response is checked if the queue is of type `stream`. If the queue is not of
type `stream` an error is returned.
#figure(
sourcecode()[```rs
if let Some(res) = res.get("type") {
if res != "stream" {
return Err(anyhow!("Queue is not a stream"));
}
}
```],
caption: [check if queue is of type stream]
)
The `messages` field is read from the response. If the field is present, the
number of messages in the queue is returned otherwise `None` is returned.
#figure(
sourcecode()[```rs
let message_count = res.get("messages");
match message_count {
Some(message_count) => Ok(Some(message_count.as_u64().unwrap())),
None => Ok(None),
}
```],
caption: [return number of messages in queue]
)
#pagebreak()
== Testing
The project contains two types of tests. The first type of tests are unit tests
and the second type of tests are integration tests. Most functionalities of the
replay microservice require a connection to a RabbitMQ server therefore more
integration tests than unit tests are present. The integration tests use the
library testcontainers#footnote("https://testcontainers.com/") to spin up a
RabbitMQ server in a container for the tests. For each test, a new container is
created. The container is destroyed after the test is finished. The tests are
run in parallel to speed up the test execution.
#linebreak()
For all integration tests, some dummy data is needed in the queue. The dummy
data is created using the `create_dummy_data` function.
#figure(
sourcecode()[```rs
async fn create_dummy_data(
port: u16,
message_count: i64,
queue_name: &str,
) -> Result<Vec<Message>> {
let connection_string = format!("amqp://guest:[email protected]:{port}");
let connection =
Connection::connect(&connection_string, ConnectionProperties::default()).await?;
let channel = connection.create_channel().await?;
let _ = channel
.queue_delete(queue_name, QueueDeleteOptions::default())
.await;
let mut queue_args = FieldTable::default();
queue_args.insert(
ShortString::from("x-queue-type"),
AMQPValue::LongString("stream".into()),
);
channel
.queue_declare(
queue_name,
QueueDeclareOptions {
durable: true,
auto_delete: false,
..Default::default()
},
queue_args,
)
.await?;
let mut messages = Vec::new();
for i in 0..message_count {
let data = b"test";
let timestamp = Utc::now().timestamp_millis() as u64;
let transaction_id = format!("transaction_{}", i);
let mut headers = FieldTable::default();
headers.insert(
ShortString::from("x-stream-transaction-id"),
AMQPValue::LongString(transaction_id.clone().into()),
);
channel
.basic_publish(
"",
queue_name,
BasicPublishOptions::default(),
data,
AMQPProperties::default()
.with_headers(headers.clone())
.with_timestamp(timestamp),
)
.await?;
messages.push(Message {
offset: Some(i as u64),
transaction: Some(TransactionHeader::from_fieldtable(
headers,
"x-stream-transaction-id",
)?),
data: String::from_utf8(data.to_vec())?,
timestamp: Some(chrono::Utc.timestamp_millis_opt(timestamp as i64).unwrap()),
});
tokio::time::sleep(tokio::time::Duration::from_micros(1)).await;
}
Ok(messages)
}
```],
caption: [create_dummy_data]
)
The function takes three arguments. The first argument is the port of the
RabbitMQ server. The second argument is the number of messages that should be
created. The third argument is the name of the queue that should be used.
The function returns a `Result<Vec<Message>>`. The `Message` struct is defined
in @Message_struct.
#linebreak()
The function starts by establishing a connection to the RabbitMQ server. A
channel is created and the queue is deleted if it already exists. The queue is
created with the type `stream`. Afterwards a unique transaction id and timestamp
is generated for each message. The message is published to the queue. The
function returns the published messages.
#linebreak()
In order to ensure that the messages are published correctly, the `i_test_setup`
test checks if the number of messages in the queue is equal to the number of
messages that were published.
#pagebreak()
#figure(
sourcecode()[```rs
#[tokio::test]
async fn i_test_setup() -> Result<()> {
let docker = clients::Cli::default();
let image = GenericImage::new("rabbitmq", "3.12-management").with_wait_for(
testcontainers::core::WaitFor::message_on_stdout("started TCP listener on [::]:5672"),
);
let image = image.with_exposed_port(5672).with_exposed_port(15672);
let node = docker.run(image);
let amqp_port = node.get_host_port_ipv4(5672);
let management_port = node.get_host_port_ipv4(15672);
let message_count = 500;
let queue_name = "replay";
let messages = create_dummy_data(amqp_port, message_count, queue_name).await?;
let client = reqwest::Client::new();
loop {
let res = client
.get(format!(
"http://localhost:{}/api/queues/%2f/{}",
management_port, queue_name
))
.basic_auth("guest", Some("guest"))
.send()
.await?
.json::<serde_json::Value>()
.await?;
match res.get("messages") {
Some(m) => {
match res.get("type") {
Some(t) => assert_eq!(t.as_str().unwrap(), "stream"),
None => panic!("type not found"),
}
assert_eq!(m.as_i64().unwrap(), message_count);
break;
}
None => continue,
}
}
assert_eq!(messages.len(), message_count as usize);
Ok(())
}
```],
caption: [integration test setup]
)
The test starts by pulling the `rabbitmq:3.12-management` image from Docker Hub.
The image is started and the ports `5672` and `15672` are exposed. The `5672` port
is the port of the RabbitMQ server. The `15672` port is the port of the RabbitMQ
management API. The `create_dummy_data` function is called to create the dummy
data. The `reqwest` library is used to send a `GET` request to the RabbitMQ
management API. The response is deserialized into a `serde_json::Value` struct.
The `messages` field is read from the response and checked if the `message_count`
is equal to the number of messages that were published. If the number of messages
is equal, the test succeeds otherwise the test fails.
#pagebreak()
The `i_test_fetch_messages` test checks if the `fetch_messages` function returns
the correct messages.
#figure(
sourcecode()[```rs
#[tokio::test]
async fn i_test_fetch_messsages() -> Result<()> {
let docker = clients::Cli::default();
let image = GenericImage::new("rabbitmq", "3.12-management").with_wait_for(
testcontainers::core::WaitFor::message_on_stdout("started TCP listener on [::]:5672"),
);
let image = image.with_exposed_port(5672).with_exposed_port(15672);
let node = docker.run(image);
let amqp_port = node.get_host_port_ipv4(5672);
let management_port = node.get_host_port_ipv4(15672);
let message_count = 500;
let queue_name = "replay";
let published_messages = create_dummy_data(amqp_port, message_count, queue_name).await?;
let client = reqwest::Client::new();
loop {
let res = client
.get(format!(
"http://localhost:{}/api/queues/%2f/{}",
management_port, queue_name
))
.basic_auth("guest", Some("guest"))
.send()
.await?
.json::<serde_json::Value>()
.await?;
match res.get("messages") {
Some(m) => {
match res.get("type") {
Some(t) => assert_eq!(t.as_str().unwrap(), "stream"),
None => panic!("type not found"),
}
assert_eq!(m.as_i64().unwrap(), message_count);
break;
}
None => continue,
}
}
let mut cfg = Config::default();
cfg.url = Some(format!("amqp://guest:[email protected]:{}/%2f", amqp_port));
cfg.pool = Some(PoolConfig::new(1));
let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
let rabbitmq_config = RabbitmqApiConfig {
username: "guest".to_string(),
password: "<PASSWORD>".to_string(),
host: "localhost".to_string(),
port: management_port.to_string(),
};
let message_options = rabbit_revival::MessageOptions {
transaction_header: Some("x-stream-transaction-id".to_string()),
enable_timestamp: true,
};
let message_query = MessageQuery {
queue: queue_name.to_string(),
from: None,
to: None,
};
let messages = fetch_messages(&pool, &rabbitmq_config, &message_options, message_query).await?;
assert_eq!(messages.len(), message_count as usize);
messages.iter().enumerate().for_each(|(i, m)| {
assert_eq!(m.data, published_messages[i].data);
assert_eq!(m.offset, published_messages[i].offset);
assert_eq!(m.timestamp, published_messages[i].timestamp);
assert_eq!(
m.transaction.as_ref().unwrap().name,
published_messages[i].transaction.as_ref().unwrap().name
);
assert_eq!(
m.transaction.as_ref().unwrap().value,
published_messages[i].transaction.as_ref().unwrap().value
);
});
Ok(())
}
```],
caption: [integration test fetch messages]
)
The test starts by starting the RabbitMQ server and creating the dummy data.
The `fetch_messages` function is called with the `from` and `to` parameters set
to `None`. The `fetch_messages` function returns all messages in the queue.
The returned messages are compared to the published messages. If the messages are
equal, the test succeeds otherwise the test fails.
#pagebreak()
The `i_test_replay_time_frame` test checks if the `replay_time_frame` function
publishes the correct messages.
#figure(
sourcecode()[```rs
#[tokio::test]
async fn i_test_replay_time_frame() -> Result<()> {
let docker = clients::Cli::default();
let image = GenericImage::new("rabbitmq", "3.12-management").with_wait_for(
testcontainers::core::WaitFor::message_on_stdout("started TCP listener on [::]:5672"),
);
let image = image.with_exposed_port(5672).with_exposed_port(15672);
let node = docker.run(image);
let amqp_port = node.get_host_port_ipv4(5672);
let management_port = node.get_host_port_ipv4(15672);
let message_count = 500;
let queue_name = "replay";
let published_messages = create_dummy_data(amqp_port, message_count, queue_name).await?;
let client = reqwest::Client::new();
loop {
let res = client
.get(format!(
"http://localhost:{}/api/queues/%2f/{}",
management_port, queue_name
))
.basic_auth("guest", Some("guest"))
.send()
.await?
.json::<serde_json::Value>()
.await?;
match res.get("messages") {
Some(m) => {
match res.get("type") {
Some(t) => assert_eq!(t.as_str().unwrap(), "stream"),
None => panic!("type not found"),
}
assert_eq!(m.as_i64().unwrap(), message_count);
break;
}
None => continue,
}
}
let mut cfg = Config::default();
cfg.url = Some(format!("amqp://guest:guest@localhost:{}/%2f", amqp_port));
cfg.pool = Some(PoolConfig::new(1));
let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
let rabbitmq_config = RabbitmqApiConfig {
username: "guest".to_string(),
password: "<PASSWORD>".to_string(),
host: "localhost".to_string(),
port: management_port.to_string(),
};
let time_frame_replay = TimeFrameReplay {
queue: queue_name.to_string(),
from: published_messages.first().unwrap().timestamp.unwrap(),
to: published_messages.last().unwrap().timestamp.unwrap(),
};
let replayed_messages = replay_time_frame(&pool, &rabbitmq_config, time_frame_replay).await?;
assert_eq!(replayed_messages.len(), published_messages.len());
replayed_messages.iter().enumerate().for_each(|(i, m)| {
let m = m.clone();
assert_eq!(
String::from_utf8(m.data.clone()).unwrap(),
published_messages[i].data
);
let headers = m.properties.headers().clone().unwrap();
let offset = headers.inner().get("x-stream-offset").unwrap();
let offset = match offset {
AMQPValue::LongLongInt(i) => i,
_ => panic!("offset not found"),
};
let timestamp = m.properties.timestamp().unwrap();
let timestamp = Utc.timestamp_millis_opt(timestamp as i64).unwrap();
assert_eq!(*offset as u64, published_messages[i].offset.unwrap());
assert_eq!(timestamp, published_messages[i].timestamp.unwrap());
});
let time_frame_replay = TimeFrameReplay {
queue: queue_name.to_string(),
from: published_messages.last().unwrap().timestamp.unwrap(),
to: published_messages.last().unwrap().timestamp.unwrap(),
};
let replayed_messages = replay_time_frame(&pool, &rabbitmq_config, time_frame_replay).await?;
assert_eq!(replayed_messages.len(), 1);
assert_eq!(
String::from_utf8(replayed_messages[0].data.clone()).unwrap(),
published_messages.last().unwrap().data
);
Ok(())
}
```],
caption: [integration test replay time frame]
)
The test starts by starting the RabbitMQ server and creating the dummy data.
The `replay_time_frame` function is called with the `from` and `to` parameters
set to the first and last message in the queue. The `replay_time_frame` function should
republish all messages in the queue. The returned messages are compared to the
published messages. If the messages are equal, the test succeeds otherwise the
test fails.
#pagebreak()
The last test checks if the `replay_transaction` function republishes the correct
messages.
#figure(
sourcecode()[```rs
#[tokio::test]
async fn i_test_replay_header() -> Result<()> {
let docker = clients::Cli::default();
let image = GenericImage::new("rabbitmq", "3.12-management").with_wait_for(
testcontainers::core::WaitFor::message_on_stdout("started TCP listener on [::]:5672"),
);
let image = image.with_exposed_port(5672).with_exposed_port(15672);
let node = docker.run(image);
let amqp_port = node.get_host_port_ipv4(5672);
let management_port = node.get_host_port_ipv4(15672);
let message_count = 500;
let queue_name = "replay";
let published_messages = create_dummy_data(amqp_port, message_count, queue_name).await?;
let client = reqwest::Client::new();
loop {
let res = client
.get(format!(
"http://localhost:{}/api/queues/%2f/{}",
management_port, queue_name
))
.basic_auth("guest", Some("guest"))
.send()
.await?
.json::<serde_json::Value>()
.await?;
match res.get("messages") {
Some(m) => {
match res.get("type") {
Some(t) => assert_eq!(t.as_str().unwrap(), "stream"),
None => panic!("type not found"),
}
assert_eq!(m.as_i64().unwrap(), message_count);
break;
}
None => continue,
}
}
let mut cfg = Config::default();
cfg.url = Some(format!("amqp://guest:guest@localhost:{}/%2f", amqp_port));
cfg.pool = Some(PoolConfig::new(1));
let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
let rabbitmq_config = RabbitmqApiConfig {
username: "guest".to_string(),
password: "<PASSWORD>".to_string(),
host: "localhost".to_string(),
port: management_port.to_string(),
};
for m in published_messages {
let header_replay = HeaderReplay {
queue: queue_name.to_string(),
header: rabbit_revival::AMQPHeader {
name: "x-stream-transaction-id".to_string(),
value: m.transaction.unwrap().value,
},
};
let replayed_messages =
rabbit_revival::replay::replay_header(&pool, &rabbitmq_config, header_replay).await?;
assert_eq!(replayed_messages.len(), 1);
}
Ok(())
}
```],
caption: [integration test replay header]
)
The test starts by starting the RabbitMQ server and creating the dummy data.
The `replay_header` function is called for each message. The transaction id of the
previously published message is used as the indicator for which message should be republished.
The returned messages are compared to the published messages. If the messages are
equal, the test succeeds otherwise the test fails.
#linebreak()
Only one unit test is present. The unit test checks if the `is_within_timeframe` method
returns the correct result.
#figure(
sourcecode()[```rs
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
#[tokio::test]
async fn test_is_within_timeframe() {
let tests = vec![
(
Some(Utc.with_ymd_and_hms(2021, 10, 13, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(false),
),
(
Some(Utc.with_ymd_and_hms(2022, 3, 13, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(true),
),
(
Some(Utc.with_ymd_and_hms(2022, 8, 13, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(true),
),
(
Some(Utc.with_ymd_and_hms(2023, 1, 13, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(false),
),
(
Some(Utc.with_ymd_and_hms(2023, 6, 13, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(false),
),
(
None,
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(false),
),
(None, None, None, None),
(
None,
None,
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(false),
),
(
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
None,
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(true),
),
(
Some(Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
None,
Some(false),
),
(
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
None,
Some(true),
),
(
Some(Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap()),
None,
None,
Some(true),
),
];
```],
caption: [unit test is_within_timeframe]
)
#pagebreak()
#figure(
sourcecode()[```rs
for (date, from, to, expected) in tests {
assert_eq!(
expected,
super::is_within_timeframe(
date.map(|date| date.timestamp_millis() as u64),
from,
to
)
);
}
}
}
```],
caption: [unit test is_within_timeframe]
)
The test creates a vector of tuples. Each tuple contains a date, a from timestamp,
a to timestamp and the expected result. The `is_within_timeframe` method is called
for each tuple. The result is compared to the expected result. If the results are
equal, the test succeeds otherwise the test fails.
#linebreak()
The tests can be run using the following command:
#figure(
sourcecode()[```bash
cargo test
```],
caption: [run tests]
)
Resulting in the following output:
#figure(
sourcecode()[```bash
❯ cargo test
Running unittests src/lib.rs (target/debug/deps/rabbit_revival-4c2723c50157660b)
running 1 test
test replay::tests::test_is_within_timeframe ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/integration_test.rs (target/debug/deps/integration_test-5f8eb0fca711dac4)
running 4 tests
test i_test_setup ... ok
test i_test_replay_time_frame ... ok
test i_test_fetch_messsages ... ok
test i_test_replay_header ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 47.30s
```],
caption: [test output]
)
#pagebreak()
== Container
The microservice is packaged as a container using Docker as the container
runtime.
#figure(
sourcecode()[```Dockerfile
# Build Stage
FROM rust:1.73.0-slim-buster as builder
RUN apt-get update && apt-get install -y \
build-essential \
pkg-config \
libssl-dev \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
RUN USER=root cargo new --bin rabbit-revival
WORKDIR ./rabbit-revival
COPY ./Cargo.toml ./Cargo.toml
# Build empty app with downloaded dependencies to produce a stable image layer for next build
RUN cargo build --release
# Build web app with own code
RUN rm src/*.rs
ADD . ./
RUN rm ./target/release/deps/rabbit_revival*
RUN cargo build --release
FROM debian:buster-slim
ARG APP=/usr/src/app
RUN apt-get update && apt-get install libssl1.1 -y && rm -rf /var/lib/apt/lists/*
EXPOSE 3000
ENV TZ=Etc/UTC \
APP_USER=appuser
RUN groupadd $APP_USER \
&& useradd -g $APP_USER $APP_USER \
&& mkdir -p ${APP}
COPY --from=builder /rabbit-revival/target/release/rabbit-revival ${APP}/rabbit-revival
RUN chown -R $APP_USER:$APP_USER ${APP}
USER $APP_USER
WORKDIR ${APP}
CMD ["./rabbit-revival"]
```],
caption: [Dockerfile]
)
#pagebreak()
The Dockerfile starts by using the official `rust:1.73.0-slim-buster` image as the base
image. The `rust:1.73.0-slim-buster` image is based on the `debian:buster-slim` image.
The Dockerfile takes advantage of the layer caching mechanism of Docker. Docker can
reuse layers from previous builds if the layers did not change. To use this efficiently,
the `Cargo.toml` file is copied to the image and the dependencies are downloaded.
After the dependencies are downloaded the microservice is built. With this approach,
the dependencies are only downloaded again if the `Cargo.toml` file changes.
#linebreak()
The needed dependencies for building the microservice are installed and the
binary is built. The binary is built in release mode to optimize the binary for
size and performance. In the next stage, the `debian:buster-slim` image is used
as the base image. The needed runtime dependencies are installed. The binary is
copied from the previous stage. A new user is created and the binary is marked
as executable for the given user. As entrypoint, the binary is executed.
#linebreak()
Debian was chosen because Alpine, the otherwise industry standard base image
does not integrate as easily with Rust. Alpine is based on musl libc which is
not compatible with the Rust standard library. Therefore the Rust standard
library needs to be compiled with musl libc.
This is not a problem per se but
unnecessary work. Debian is based on glibc which is compatible with Rust.
#pagebreak()
== CI/CD
GitHub actions are used as CI/CD framework. The project has no continuous deployment
pipeline because that is for the user of the microservice to decide. The CI part of the
pipeline is shown below in @ci_pipeline.
#figure(
image("./../assets/ci.svg"),
caption: [CI pipeline],
kind: image
)<ci_pipeline>
The CI pipeline is triggered on every push to the `master` branch if one of the
following paths changed:
- src/\*\*
- Cargo.toml
- Cargo.lock
#figure(
sourcecode()[```yaml
name: Rust
on:
push:
paths:
- src/**
- Cargo.toml
- Cargo.lock
env:
CARGO_TERM_COLOR: always
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install stable
uses: dtolnay/rust-toolchain@stable
- name: Run tests
run: cargo test --verbose
```],
caption: [Automated tests],
)
The CI pipeline runs the tests on the latest Ubuntu image. First the repository
is checked out, afterwards, the stable Rust toolchain is installed.
Lastly, the tests are run using the `cargo test` command.
#linebreak()
If one of the tests fails, the pipeline fails. If all tests pass, the pipeline
succeeds and the job responsible for building the container is triggered.
#figure(
sourcecode()[```yaml
name: Create and publish a Docker image
on:
workflow_run:
workflows: ["Rust"]
types:
- completed
env:
REGISTRY: ghcr.io
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Log in to the Container registry
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
with:
images: ${{ env.REGISTRY }}/${{ github.repository }}:${{ github.sha }}
- name: Build and push Docker image
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
```],
caption: [Build container],
)
The container is built using the `docker/build-push-action` action#footnote(
"https://docs.github.com/en/actions/publishing-packages/publishing-docker-images",
). The action is configured to build the container using the `Dockerfile` in the
root of the repository. The image is tagged using the git commit hash available
from the predefined environment variables #footnote(
"https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables",
). If the build succeeds, the container is pushed to the GitHub container
registry. The GitHub container registry is used because it is free and
integrated into GitHub. No additional authentication is needed to push to the
GitHub container registry, making it easy to use.
#pagebreak()
In contrast to the jobs triggered on push, the Dependabot job is triggered on a
schedule. The job is responsible for updating the dependencies of the
microservice. Dependabot is a service, owned and built into GitHub #footnote("https://github.com/dependabot").
#figure(
image("./../assets/depbot.svg", width: 80%),
caption: [Dependabot pipeline],
kind: image
)<dependabot_pipeline>
#figure(
sourcecode()[```yaml
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: daily
- package-ecosystem: cargo
directory: /
schedule:
interval: daily
ignore:
- dependency-name: "*"
# patch and minor updates don't matter for libraries
# remove this ignore rule if your package has binaries
update-types:
- "version-update:semver-patch"
- "version-update:semver-minor"
```],
caption: [Dependabot configuration],
)
Dependabot is configured to check for updates daily. The job is configured to
ignore patch and minor updates. If a new major version of a dependency is
released, a pull request is crated. The pull request needs to be merged
by a maintainer.
#pagebreak()
|
|
https://github.com/Caslus/lucasphilippe | https://raw.githubusercontent.com/Caslus/lucasphilippe/main/src/templates/resume.typ | typst | #let name = "<NAME>"
#set document(
title: name + "'s Resume",
author: name
)
#set text(font: "libertinus serif", size: 10pt, lang: "en")
#set page(
footer: text(8pt, fill: gray)[
#grid(
columns: (1fr, 1fr),
{
let fmt = "[month repr:short] [day], [year]"
align(left)[
Last update: #datetime.today().display(fmt)
]
},
align(right, context(counter(page).display()))
)
],
margin: (
top: 1.5cm,
bottom: 1.5cm,
left: 2cm,
right: 2cm
)
)
#set list(tight: false, indent: 5mm)
#set par(leading: 0.45em)
#show heading: it => [
#set text(10pt, weight: "light")
#pad(bottom: 0.2mm)[
#pad(top: 0pt, bottom: -10pt, it.body)
#line(length: 100%, stroke: 0.25pt)
]
]
#show link: it => [
#underline(stroke: 0.1mm + gray, offset: 0.75mm, it.body)
]
#let title(
name: "",
subtitles: ()
) = {
align(center)[
#block(text(weight: "light", 2.5em, name))
#subtitles.join(" · ")
]
}
#let exp(
body,
title: "",
subtitle: "",
location: "",
period: ""
) = {
pad(
top: 0.1mm,
bottom: 0.1mm,
left: 5mm,
right: 5mm,
{
grid(
columns: (auto, 1fr),
row-gutter: 2mm,
align(left, strong(title)),
align(right, text(gray, location)),
align(left, emph(subtitle)),
align(right, text(gray, period))
)
body
}
)
}
#title(
name: name,
subtitles: (
"+55 (41) 99580-0680",
link("mailto:<EMAIL>")[<EMAIL>],
"Curitiba, Brazil",
link("https://www.linkedin.com/in/lucasphi/")[Linkedin],
link("https://github.com/Caslus")[Github],
)
)
= Summary
*Software Engineer* with experience designing, developing and testing software applications in agile environments, effectively collaborating with cross-functional teams to deliver high-quality code using *React, Typescript, Node and Go*. Fluent in English and Portuguese, with intermediate Spanish and basic Japanese proficiency.
= Experience
#exp(
title: "Frontend Developer",
subtitle: "Ligga Telecom",
location: "",
period: "Jun 2024 - Present",
)[
#list(
[Designed, implemented, tested, deployed, and maintained a React Native mobile application with over 200,000 monthly active users, collaborating with UX/UI designers and backend developers to ensure seamless integration and user experience.],
[Collaborated with multiple teams to drive business decisions while building a React and TypeScript web application used by all customers.],
[Integrated and unified customer-facing applications with 3 distinct billing systems from different vendors, simplifying the user journey into a cohesive and efficient experience.]
)
]
#exp(
title: "Software Engineer Intern",
subtitle: "E-Governe",
location: "",
period: "Oct 2022 - Dec 2023",
)[
#list(
[Collaborated with senior developers to migrate legacy Oracle SQL procedures into PostgreSQL, achieving a significant cost reduction annually in licensing while enhancing database performance.],
[Worked closely with customers to build over 10 new scalable and fault-tolerant report generation routes with Java Spring.],
[Designed and coded interactive, responsive and easy to use web pages for over 150 public schools using Angular, RxJs and TypeScript.]
)
]
#exp(
title: "Programming Teaching Assistant",
subtitle: "Pontifical Catholic University of Paraná",
location: "",
period: "Mar 2023 - Jun 2023",
)[
#list(
[Tutored Object-Oriented Programming (OOP) with the Java programming language to a class of about 40 students, emphasizing conceptual understanding of topics and helping them to enhance computer science and problem-solving skills.],
[Provided one-on-one tutoring and support, ensuring software engineering best practices and leading to a higher average test score compared to another class of the same course.],
)
]
= Education
#exp(
title: "Pontifical Catholic University of Paraná (PUCPR)",
subtitle: "Bachelor of Science in Software Engineering",
location: "Curitiba, Brazil",
period: "Jan 2021 - Dec 2025 (Expected)"
)[
#list(
[Elected Vice-President of the Software Engineering Academic Center in 2024, successfully representing over 400 students and leading a collaborative effort to orchestrate the Polytechnic School Academic Week, promoting teamwork among all 17 courses within the PUCPR Polytechnic School.],
[Attended courses such as Data Structures, Algorithms, Databases, Web Development, Cloud Architecture, Big Data and DevOps maintaining a GPA of 3.46.]
)
]
= Technical Skills
#list(
[*Programming Languages*: Typescript, Javascript, Go, Java, Python, C\#],
[*Frontend Development*: HTML, CSS, React, Angular, React Native, Redux],
[*Backend Development*: Node.js, Express, Hono, Java Spring],
[*Databases*: SQL, PostgreSQL, OracleSQL, MySQL, MongoDB],
[*DevOps & Cloud*: AWS, Azure, Docker, Docker Compose],
[*Version Control & CI/CD*: Git, GitHub, GitHub Actions, Azure Pipelines],
[*Networking & Security*: Networks, DNS, NGINX, SSL/TLS, API Security],
[*Server Management*: Linux, Bash scripting, SSH, NGINX]
)
= Certifications
#exp(
title: "Six Sigma White Belt Certification",
subtitle: "Aveta Business Institute",
location: "",
period: "Jul 2024"
)[]
#exp(
title: "Web Application Development with React JS",
subtitle: "Pontifical Catholic University of Paraná",
location: "",
period: "Jun 2024"
)[]
#exp(
title: "Santander 2024 – AWS Certification Training",
subtitle: "DIO",
location: "",
period: "May 2024"
)[]
#exp(
title: "Software Development Training",
subtitle: "Pontifical Catholic University of Paraná",
location: "",
period: "Jan 2022"
)[]
= Languages
#list(
[*Portuguese*: Native],
[*English*: Fluent],
[*Spanish*: Intermediate],
[*Japanese*: Basic]
)
= Achievements and activities
#exp(
title: "Volunteer",
subtitle: "Instituto Água e Terra (IAT)",
location: "",
period: "Sep 2024 - Present"
)[
Worked as part of a dedicated team to assist in environmental conservation efforts, transporting essential materials such as stone and wood to restore hiking trails in the hills of Curitiba.
]
#exp(
title: "XIX Brazilian Computing Olympiad (OBI 2017)",
subtitle: "State University of Campinas",
location: "",
period: "Jun 2017"
)[
Competed in the first and second phase of the Brazilian Computing Olympiad, solving complex problems in a limited time frame and using algorithms and data structures to solve problems efficiently.
]
#exp(
title: "2016 Paralympic Game Jam - Best Game (Public Choice)",
subtitle: "Pontifical Catholic University of Paraná",
location: "",
period: "Aug 2016"
)[
Received the public choice award for the best game developed during the 2016 Paralympic Game Jam, a 48-hour game development competition.
]
#exp(
title: "Volunteer",
subtitle: "<NAME>",
location: "",
period: "Feb 2015 - Dec 2017"
)[
Collaborated with fellow volunteers to create thermal blankets from styrofoam for donation to underserved nursing homes, contributing to community welfare during the winter months.
] |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/quotes_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test escape sequences.
The 5\'11\" 'quick\' brown fox jumps over the \"lazy" dog\'s ear.
|
https://github.com/JanEhehalt/typst-demo | https://raw.githubusercontent.com/JanEhehalt/typst-demo/main/KI-Verzeichnis.typ | typst | #set align(left)
#table(
stroke: none,
columns: (25%, 50%, auto),
[*System*], [*Prompt*], [*Verwendung*],
[CHADGEPETE], [lol],[gar nicht]
)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0080.typ | typst | Apache License 2.0 | #let data = (
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("<control>", "Cc", 0),
("NO-BREAK SPACE", "Zs", 0),
("INVERTED EXCLAMATION MARK", "Po", 0),
("CENT SIGN", "Sc", 0),
("POUND SIGN", "Sc", 0),
("CURRENCY SIGN", "Sc", 0),
("YEN SIGN", "Sc", 0),
("BROKEN BAR", "So", 0),
("SECTION SIGN", "Po", 0),
("DIAERESIS", "Sk", 0),
("COPYRIGHT SIGN", "So", 0),
("FEMININE ORDINAL INDICATOR", "Lo", 0),
("LEFT-POINTING DOUBLE ANGLE QUOTATION MARK", "Pi", 0),
("NOT SIGN", "Sm", 0),
("SOFT HYPHEN", "Cf", 0),
("REGISTERED SIGN", "So", 0),
("MACRON", "Sk", 0),
("DEGREE SIGN", "So", 0),
("PLUS-MINUS SIGN", "Sm", 0),
("SUPERSCRIPT TWO", "No", 0),
("SUPERSCRIPT THREE", "No", 0),
("ACUTE ACCENT", "Sk", 0),
("MICRO SIGN", "Ll", 0),
("PILCROW SIGN", "Po", 0),
("MIDDLE DOT", "Po", 0),
("CEDILLA", "Sk", 0),
("SUPERSCRIPT ONE", "No", 0),
("MASCULINE ORDINAL INDICATOR", "Lo", 0),
("RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK", "Pf", 0),
("VULGAR FRACTION ONE QUARTER", "No", 0),
("VULGAR FRACTION ONE HALF", "No", 0),
("VULGAR FRACTION THREE QUARTERS", "No", 0),
("INVERTED QUESTION MARK", "Po", 0),
("LATIN CAPITAL LETTER A WITH GRAVE", "Lu", 0),
("LATIN CAPITAL LETTER A WITH ACUTE", "Lu", 0),
("LATIN CAPITAL LETTER A WITH CIRCUMFLEX", "Lu", 0),
("LATIN CAPITAL LETTER A WITH TILDE", "Lu", 0),
("LATIN CAPITAL LETTER A WITH DIAERESIS", "Lu", 0),
("LATIN CAPITAL LETTER A WITH RING ABOVE", "Lu", 0),
("LATIN CAPITAL LETTER AE", "Lu", 0),
("LATIN CAPITAL LETTER C WITH CEDILLA", "Lu", 0),
("LATIN CAPITAL LETTER E WITH GRAVE", "Lu", 0),
("LATIN CAPITAL LETTER E WITH ACUTE", "Lu", 0),
("LATIN CAPITAL LETTER E WITH CIRCUMFLEX", "Lu", 0),
("LATIN CAPITAL LETTER E WITH DIAERESIS", "Lu", 0),
("LATIN CAPITAL LETTER I WITH GRAVE", "Lu", 0),
("LATIN CAPITAL LETTER I WITH ACUTE", "Lu", 0),
("LATIN CAPITAL LETTER I WITH CIRCUMFLEX", "Lu", 0),
("LATIN CAPITAL LETTER I WITH DIAERESIS", "Lu", 0),
("LATIN CAPITAL LETTER ETH", "Lu", 0),
("LATIN CAPITAL LETTER N WITH TILDE", "Lu", 0),
("LATIN CAPITAL LETTER O WITH GRAVE", "Lu", 0),
("LATIN CAPITAL LETTER O WITH ACUTE", "Lu", 0),
("LATIN CAPITAL LETTER O WITH CIRCUMFLEX", "Lu", 0),
("LATIN CAPITAL LETTER O WITH TILDE", "Lu", 0),
("LATIN CAPITAL LETTER O WITH DIAERESIS", "Lu", 0),
("MULTIPLICATION SIGN", "Sm", 0),
("LATIN CAPITAL LETTER O WITH STROKE", "Lu", 0),
("LATIN CAPITAL LETTER U WITH GRAVE", "Lu", 0),
("LATIN CAPITAL LETTER U WITH ACUTE", "Lu", 0),
("LATIN CAPITAL LETTER U WITH CIRCUMFLEX", "Lu", 0),
("LATIN CAPITAL LETTER U WITH DIAERESIS", "Lu", 0),
("LATIN CAPITAL LETTER Y WITH ACUTE", "Lu", 0),
("LATIN CAPITAL LETTER THORN", "Lu", 0),
("LATIN SMALL LETTER SHARP S", "Ll", 0),
("LATIN SMALL LETTER A WITH GRAVE", "Ll", 0),
("LATIN SMALL LETTER A WITH ACUTE", "Ll", 0),
("LATIN SMALL LETTER A WITH CIRCUMFLEX", "Ll", 0),
("LATIN SMALL LETTER A WITH TILDE", "Ll", 0),
("LATIN SMALL LETTER A WITH DIAERESIS", "Ll", 0),
("LATIN SMALL LETTER A WITH RING ABOVE", "Ll", 0),
("LATIN SMALL LETTER AE", "Ll", 0),
("LATIN SMALL LETTER C WITH CEDILLA", "Ll", 0),
("LATIN SMALL LETTER E WITH GRAVE", "Ll", 0),
("LATIN SMALL LETTER E WITH ACUTE", "Ll", 0),
("LATIN SMALL LETTER E WITH CIRCUMFLEX", "Ll", 0),
("LATIN SMALL LETTER E WITH DIAERESIS", "Ll", 0),
("LATIN SMALL LETTER I WITH GRAVE", "Ll", 0),
("LATIN SMALL LETTER I WITH ACUTE", "Ll", 0),
("LATIN SMALL LETTER I WITH CIRCUMFLEX", "Ll", 0),
("LATIN SMALL LETTER I WITH DIAERESIS", "Ll", 0),
("LATIN SMALL LETTER ETH", "Ll", 0),
("LATIN SMALL LETTER N WITH TILDE", "Ll", 0),
("LATIN SMALL LETTER O WITH GRAVE", "Ll", 0),
("LATIN SMALL LETTER O WITH ACUTE", "Ll", 0),
("LATIN SMALL LETTER O WITH CIRCUMFLEX", "Ll", 0),
("LATIN SMALL LETTER O WITH TILDE", "Ll", 0),
("LATIN SMALL LETTER O WITH DIAERESIS", "Ll", 0),
("DIVISION SIGN", "Sm", 0),
("LATIN SMALL LETTER O WITH STROKE", "Ll", 0),
("LATIN SMALL LETTER U WITH GRAVE", "Ll", 0),
("LATIN SMALL LETTER U WITH ACUTE", "Ll", 0),
("LATIN SMALL LETTER U WITH CIRCUMFLEX", "Ll", 0),
("LATIN SMALL LETTER U WITH DIAERESIS", "Ll", 0),
("LATIN SMALL LETTER Y WITH ACUTE", "Ll", 0),
("LATIN SMALL LETTER THORN", "Ll", 0),
("LATIN SMALL LETTER Y WITH DIAERESIS", "Ll", 0),
)
|
https://github.com/kazewong/lecture-notes | https://raw.githubusercontent.com/kazewong/lecture-notes/main/Engineering/SoftwareEngineeringForDataScience/lab/julia.typ | typst | #set page(
paper: "us-letter",
header: align(center, text(17pt)[
*Introduction to Julia*
]),
numbering: "1",
)
#import "./style.typ": style_template
#show: doc => style_template(doc,)
= Foreword
`julia` is a language which I have a love-hate relationship with. If the first programming language you learned is `python`, I think `julia` offers a fresh take on what you can do with computers while having the interactiveness of `python`. It has a lot of modern features built into the language, such as its just-in-time (JIT) compilation, multiple dispatch, and metaprogramming capabilities. It also comes with its own package manager, which is quite nice to use. This makes `julia` a great "advance" language for data scientists to learn after `python`. However, the `julia` ecosystem is not nearly as mature as `python`, as a lot of its packages are maintained by small communities, and some time they lead to down some dead ends.
Nonetheless, `julia` is a fun language to play with. `julia` often offers more flexibility and performance than `python`, and its ecosystem has a lot of interesting research codes which are often not found in other ecosystem. So in this lab, we are going to go through some of `julia`'s key features, and we will also explore how documentation and packaging work in `julia`.
#outline(title: [Outline \ ], depth: 2, indent: 1em)
#pagebreak()
= Key Concepts
== Julia has a JIT compiler
`julia` has a just-in-time(JIT) compiler, which means that the code you write is compiled to machine code on the fly. This allows you to write code that is as fast as C or Fortran, while still having the interactivity of `python`, such as a for-loop. This implies the first time you run a function in `julia` it will compile the function before executing it. This compilation will incur some overhead, but then the subsequent times using the function will just call the cache such that you don't have to pay the overhead again and again. We will dive into this later in the lab.
== Julia has multiple dispatch
For the people who learn `python` as their first programming language, and perhaps engaged in some projects related to `python`, you may find `julia` quite odd in the sense that *it does not have classes*. Instead, `julia` has a killer feature that is called multiple dispatch, meaning the exact function being execute depends on the type of arugments. This gives `julia` developers a lot of freedom in composing different software. We are going to see more detail about why this is an awesome feature later in this session.
== Julia has a package manager
One thing that is quite nice about `julia` is it has a tightly integrated package manager. It helps you to manage your dependencies on a project to project level. In a `julia` REPL, you can enter the package manager mode by pressing `]`, and you can add, remove, and update packages in your project. This will also create a `Project.toml` and `Manifest.toml` file in your project directory, which will help you to manage your dependencies.
= Basic Syntax
== Variables
`julia` is similar to `python` in many ways. For example, `a = 1` will define a variable `a` with the value of `1`. As we mentioned, `julia`'s multiple dispatch system relies on the type of the variable to determine which function to call, so it is important to learn how to inspect the type of a particular variable. You can check the type of a variable by using the `typeof` function. If you run `typeof(a)`, it will return `Int64` because `1` is an integer.
To define a list, the basic syntax is similar, that is `a = [1, "hello", 3.14]`. However, in order to get a list from say a range, the syntax is a bit different. Instead of `a = list(range(1, 10))`, you would write `a = collect(1:10)`. There is a bunch of functions related to collection you can checkout here #link("https://docs.julialang.org/en/v1/base/collections/")[here].
From a `python` background, the biggest difference in defining variables in `julia` is in dictionary. In `python`, you would define a dictionary like this `a = {"key": "value"}`, but in `julia`, you would define a dictionary like this `a = Dict("key" => "value")`. Accessing an element remains the same as `python`
Simliar to `python`, if you have a variable defined by referencing another variable, i.e. `b = a` while `a = [1, 2]`, changing element in `a` will also change `b` automatically.
== Writing Structs
While there is no class in `julia`, it is still useful to be able to bundle a bunch of variables together so you can access them easily. This called composite type in `julia`, and we use the `struct` keyword to define them. For example, you can define a struct like this:
```julia
struct myStruct
name::String
somedata::Vector{Int}
end
```
Note `::` syntax is used to specify the type of the variable. In this case, `name` is a `String` and `somedata` is a vector of `Int`. You can create an instance of this struct like this:
```julia
a = myStruct("hello", [1, 2, 3])
```
== Functions
It is fair to say `julia` centers around writing functions, and one of its most interesting features is multiple dispatch. In `julia`, you can define a function like this:
```julia
function f(x)
return x + 1
end
```
Note that `julia` does not care about indentation, however it is still a good practice to indent your code properly.
So far we haven't seen much difference between `python` and `julia` in function definition. However, here comes the interesting bit, a function with the same name but with different argument types will be treated as a different function. For example, you can define a function like this:
```julia
function f(x::Int)
return x + 1
end
```
And you can define another function with the same name but with a different argument type like this:
```julia
function f(x::String)
return x * "!"
end
```
Now if we call `f(1)`, it will return `2`, and if we call `f("hello")`, it will return `hello!`.
This is really powerful (and somewhat cursed), since it reduces the coding task to defining your struct and manipulating it with the function with argument that takes that sepcific type. This basically acts as a replace for method in class in `python`.
== Control Flow
The syntax for defining control flow in `julia` is similar to `python`. The major difference between `python` and `julia` in syntax is since `julia` does not care about indentation, you need to use `end` to close the block of code. For example, you can define a for-loop like this:
```julia
for i in 1:10
println(i)
end
```
`while` loop and `if-else` statements are also similar to `python`, and you can find more detail #link("https://docs.julialang.org/en/v1/manual/control-flow/")[here]
What I want to highlight is `julia`'s JIT capability. Let's write a function that takes a long time to run:
```julia
function add100000000(x)
for i in 1:100000000
x += 1
end
return x
end
```
You can try to run this counter part in `python` and you will see that `julia` is much faster. And we can even dig into the internal of the function by using `@code_llvm` to see the LLVM code generated by the function. In the `julia` REPL, you can run `@code_llvm add100000000(1)` to see the LLVM code generated by the function, and you will see that the cached LLVM intermediate representation (IR) code actually already have the number of iterations in the code. This gives us hint that `julia` is capable to optimize the code and run it more efficient than `python`.
= Exercise: Writing an insertion sort algorithm again
== Step 0: Download Julia
Follow the instruction on #link("https://github.com/JuliaLang/julia")[here] to install `julia` on your machine.
== Step 1: Clone the class repository
Fork #link("https://github.com/KazeClasses/julia_guide")[this repository] and clone it to your local machine.
== Step 2: Implement the sorting algorithm
Open the `src/insertion_sort.jl` file and implement the insertion sort algorithm within `insertion_sort` function.
== Step 3: Test the algorithm
Once you have implemented the body of the algorithm, start the `julia` REPL and run the following command to test the algorithm:
1. Press `]` to enter the package manager mode.
2. Run `activate .` to activate the project.
3. Run `test` to test the algorithm.
= Packaging code
Packaging code in `julia` could take a while to get used to. Instead of creating submodules by directories and `__init__.py`, fundamentally in `julia` you just ```julia include("file.jl")``` in your main module. Any subdirectories is just to group those files together. And instead of using syntax like ```python from scipy.optimize import minimize``` to import a function from a submodules, one needs to export functions that are written such that they can be imported by the main module.
== Step 0: Looking at some examples
Have a look these three examples: #link("https://github.com/SciML/DifferentialEquations.jl")[DifferentialEquations.jl], #link("https://github.com/FluxML/Flux.jl/tree/master")[Flux.jl], and #link("https://github.com/JuliaGPU/CUDA.jl/tree/master")[CUDA.jl].
== Step 1: Moving main function to another file
Let's start our packaging process by moving the main functions in our file to another file. In the `src` folder, create a file called `utils.jl`. Move every functions in the `InsertionSort.jl` file to the `utils.jl` file.
After moving the functions to the `utils.jl` file, make sure you add ```julia export``` statement to the functions you want to export. For example, you can add the following code to the `insertion_sort` function:
```julia
export insertion_sort!
```
This will allow the function to be discovered by the main module.
== Step 2: Creating the main module
In your `src` folder, create a file called `InsertionSort.jl`. This file will be the main module of the package. Note that this file will not contain any actual function. Instead, it will mostly contain `include` statements to include the sub-modules.
In the `InsertionSort.jl` file, write the following code:
```julia
module InsertionSort
include("utils.jl")
end
```
== Step 3: Adding the package to the project
When you are developing a package in `julia`, you want to observe the changes you make as you go. To do this, you need to add the package to the project in development mode. To do this, start the `julia` REPL, enter the package manager mode by pressing `]`, and run `dev .` to add the package to the project in development mode. This will allow your environment to see the changes you make to the package in real time. Once you are done with development, you can run `free .` to remove the package from development mode.
Once you have added the package to the project in development mode, you can run `using InsertionSort` to use the package in the project. Enter the `julia` REPL and run `using InsertionSort` to check whether the package is working correctly.
= Building documentation
In almost all `julia` packages, you will find documentation page that looks similar to each other. This is because `julia` has a package called `Documenter.jl` that the community uses to generate their documentation.
In this section, we are going to learn how to build a documentation page for your package using `Documenter.jl`.
== Step 1: Setting up directory
The first step is to create a directory called `docs` in the root of your project. Inside the `docs` directory, create a file called `make.jl`. This file will contain the configuration for the documentation.
Also in the `docs` directory, create a directory called `src`. This directory will contain the markdown files for the documentation. Put a markdown file called `index.md` in the `src` directory. This file will be the main page of the documentation.
In the `make.jl` file, write the following code:
```julia
using Documenter, MyPackage
makedocs(sitename="MyPackage.jl")
```
== Step 2: Building the documentation
To build the documentation, start the `julia` REPL, enter the package manager mode by pressing `]`, and run `activate .` to activate the project. Then run `using Documenter` and `include("docs/make.jl")` to build the documentation.
After building the documentation, you will see a `build` directory in the `docs` directory. Inside the `build` directory, you will find an `html` file. Just to check the result immediately, open this file in a browser to see the documentation.
== Step 3: Writing doc strings
The next thing we want to do is to write doc strings for the functions in the package. Doc strings are written in markdown format and are placed right above the function definition. For example, you can write a doc string like this:
```julia
"""
Insertion sort algorithm.
This function sorts an array using the insertion sort algorithm.
# Arguments
- `arr::Vector{Int}`: The array to be sorted.
# Examples
julia
arr = [3, 2, 1]
insertion_sort!(arr)
println(arr) \# [1, 2, 3]
"""
function insertion_sort!(arr::Vector{Int})
# implementation
end
```
This is different from `python` in the sense that in `python` you would write the doc string in the function body, while in `julia` you write it right above the function definition. Make sure this is structured correctly, otherwise you will not be able to generate the documentation correctly.
== Step 4: Adding automatic API documentation
The next step is to add automatic API documentation to the documentation page. To do this, let's add another file called `api.md` in the `src` directory. Add the following code to the `api.md` file:
#raw("markdown
# API
'''@autodocs
Modules = [InsertionSort]
'''",
lang: "markdown")
Now you can build the documentation again to see the new API documentation page. By default, every markdown file within the `src` directory will be included in the documentation with pretty formatting.
If you just open the `html` file, you may have some buggy issue related to navigation such as wrong navigation. Instead, you can either install `LiveServer` then start a server with ``` julia -e 'using LiveServer; serve(dir="docs/build")```. In this
session, we will just start a http server with python by running ```python -m http.server --bind localhost --directory ./build```.
= Writing tests
== Add Test to the dependency
Start the julia REPL, run `]` to enter the package manager mode, and run `add Test` to add the `Test` package to the project.
== Writing test suites
There are two levels of writing tests in `julia`: \@test and \@testset. The purpose of \@test is to test a single function or statement, which is similar to test functions you have learned in the `python` session. On the other hand, you don't want your entire testsuite to exist whenever one function fails. In this case, you can use \@testset to group tests together and isolate them from the rest of the tests.
== Step 1: Write tests for the insertion sort algorithm
The way to test a function in `julia` isusing the test macro `@test`. For example, you can write a test like this:
```julia
using Test
@test insertion_sort!([3, 2, 1]) == [1, 2, 3]
```
== Step 2: Group tests together with \@testset
Similar to `python`, you can group tests together to let certain tests fail and still finish other tests. To do this in `julia`, we can use the `@testset` macro. For example, you can write a test set like this:
```julia
@testset "Insertion sort tests" begin
@test insertion_sort!([3, 2, 1]) == [1, 2, 3]
@test insertion_sort!([3, 2, 1, 4]) == [1, 2, 3, 4]
end
```
Now if you start the REPL and go into package manager mode, you can run `test` to run the tests. You should see a summary of the tests and whether they passed or failed.
== Running tests
You have already tried running tests in the previous exercise. Once again, the way to run tests is to start the `julia` REPL, enter the package manager mode by pressing `]`, and run `test` to run the tests.
= Best practices
== All roads lead to Rome
In `python`, the intention of the language is to have only one obvious way to a solution. Although that is often violated and people dunk on their motto, it is still largely true. Creating modules, writing classes, and writing tests, they can all be done in a similar fashion. On the other hand, there are many ways to do the same thing in `julia`. We have seen the three different ways to build your package hierarchy, and the support of metaprogramming in `julia` together with multiple dispatch allows you to come with wild solutions to your problems. In general, I find the development experience in `julia` to be pretty liberal.
== Type stability
`julia` relies LLVM to compile the code, and knowing the type of the variable can help the compiler specialize the code to make it more performant. Let's look an example from #link("https://m3g.github.io/JuliaNotes.jl/stable/instability/")[here] about type instability:
Suppose you define a function
```julia
x = 5.0
function f()
s = 0
for val in x
s = s + val
end
return s
end
```
since x could be any type, the compiler does not know how to specialize the code, meaning it needs to use a more general code that is slower. There is a built-in macro in `julia` called `@code_warntype` that can help you to check the type stability of your code. If you run `@code_warntype f()`, you will see that some part of the input is highlighted in red, meaning that the compiler is not sure about the type of the variable.
Now we define the exact same function but giving it an argument
```julia
function g(x)
s = zero(eltype(x))
for val in x
s = s + val
end
return s
end
```
Now when you run `@code_warntype g([1.0, 2.0, 3.0])`, since the compiler is given a concrete variable that the type is known, the code is specialized and the red highlight is gone.
Let's benchmark the two functions by running `@btime f()` and `@btime g([1.0, 2.0, 3.0])`. You will see that the second function is much faster than the first one.
= Development tips
== Use Revise
`julia` has a package called `Revise.jl` that allows you to reload your code without restarting the REPL. Generally if you want to redefine a function, you need to quit hte REPL and enter it again. This could cause you to lose some intermediate variables you may want to keep between session. Instead, you can make your package available to Revise, then any changes you made in the files will be reflected in the REPL. To do this, first add the package you are developing by running `dev .` in the package manager mode. Then run `using Revise` in the REPL to start the Revise package.
== Don't be afraid of for loop and other low level operation
As you have seen in the control flow section, `julia` JIT compiler allows you to implement things like a for-loop without worrying about its performance implication. In `python`, the typical workflow is you try to break down a task into a bunch of functions that someone has implemented a high performance c function underthehood, therefore it is always good to use libraries like `numpy` and `scipy`. However, once in a while you will stumble upon a problem that there is no obvious package to call, and it could be a stuck in `python`. People then turn to tools like `cython` to improve the performance of the performence critical bit of their code. `julia` is try to solve this "two languages problems", which is if you want high performance `python`, sometime you also need to know low level programming languages like `c`. Instead, in `julia` you never need to do that, everything is in `julia`. You are allowed to write for loops and other patterns that may not be encouraged in `python`. This liberates the developers from concerns of design pattern, instead we can focus on really delivering the algoritm.
== Don't be afraid to look into someone's source code.
Another merit of brough by `julia` one language system is you don't need to worry about hitting some other language when trying to dig through someone's code. Again, everything is in `julia`, and what even nicer about this is `julia` is supposed to be composable. Let say you have some function that works on a generic array type
```julia
function myfunc(arr::AbstractArray)
return sum(arr)
end
```
If you want it to work on accelerator such as GPU, it might just work for you because `CuArray` is a subtype of `AbstractArray`, meaning you have to do nothing to make it work on GPU.
= Noteworthy libraries
== The SciML ecosystem
The #link("https://sciml.ai/")[SciML] ecosystem is a collection of packages that are designed to solve scientific machine learning problems. They offers a wide range of tools for writing simulations, solving differential equations, optimization, uncertainty quantification, and more. It is great to play with if you are interested in scientific computing.
== Flux and Lux
#link("https://fluxml.ai/")[Flux] and #link("https://lux.csail.mit.edu/dev/")[Lux] are the big two machine learning libraries in `julia`. If you want to build more standard machine learning models, `Flux` should be a better choice. If you want something better integrated with solvers and scientific computing, `Lux` is a better choice.
|
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/networks/lec5.typ | typst | #import "template.typ": *
#show: template.with(
title: "Lecture 5",
subtitle: "14.15"
)
= Title
#define(
title: "Social Learning"
)[
How do people learn from others, and what are the ultimate implications for society's beliefs, opinions, and behaviors?
]
The basic idea behind the DeGroot learning model is that in each time period, an agent's beliefs will be updated by a weighted average of their own opinion as well as their neighbors, controlled by fixed weights that are time-invariant. Therefore with the initial list of opinions and the matrix of weights, we will be able to determine the long term dynamics of the group.
In the updating matrix $bold(A)$, $bold(A)_(i j)$ represents how much agent $i$ trusts agent $j$. $bold(A)$ is a *row-stochastic* matrix, meaning that the sum of the weights for each node is equal to 1. Each agent's _initial_ belief $x_i$ is somewhere in $[0, 1]$. Therefore, on each time step, their opinion is updated as follows:
$ x_i (t + 1) = sum_(j=1)^n bold(A)_(i j) x_j (t) $
In matrix notation, this is:
$ x(t) = bold(A) x (t - 1) $
More generally for any time period $t$ we have:
$ x(t) = bold(A)^t x (0) $
#define(
title: "Periodic Matrices"
)[
A matrix is *periodic* if the powers of the matrix cycle without converging.
]
As can be seen with the formula, the graph of opinions will not converge if the matrix is periodic. On the other hand, it does if $bold(A)$ is *aperiodic*.
A matrix is aperiodic if the GCD of all directed cycle lengths are coprime to each other. Another simple conditions that makes $bold(A)$ aperiodic is if there exists any $i$ such that $bold(A)_(i i) > 0$
If the matrix is not strongly connected, opinions may not converge to the same thing. If the matrix is strongly connected however, then it must be the case that everyone's long term converged opinion is the same.
#define(
title: "Long-Run Consensus Theorem"
)[
Given a directed matrix $bold(A)$, if the network is strongly connected and aperiodic, then $"lim"_(t -> infinity) bold(A)^t = bold(A)^*$ exists. The matrix $bold(A)$ should have rows that are all exactly the same, resulting in the final belief matrix for each agent resulting in a consensus.
]
Each agents weight in the final consensus is the value of their weight in any $i$th column of $bold(A)^*$. This is called the *long-run influence*.
The list of long-run influences for each person is simply the unit eigenvector of $bold(A)^T$. This interestingly means that each agent's long-run influence is their eigenvector centrality!
|
|
https://github.com/GYPpro/DS-Course-Report | https://raw.githubusercontent.com/GYPpro/DS-Course-Report/main/Rep/16.typ | typst | #import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx
#import "@preview/codelst:2.0.1": sourcecode
// Display inline code in a small box
// that retains the correct baseline.
#set text(font:("Times New Roman","Source Han Serif SC"))
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
#show raw.where(block: false): box.with(
fill: luma(230),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#set page(
paper: "a4",
)
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()]
#set math.equation(numbering: "(1)")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#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))
]
)
/*----*/
= 霍夫曼树`Huffman-tree`
\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 数据结构 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" ") 霍夫曼树`Huffman-tree` #text(" ")]指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 16 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2024年6月13日上午 ")]#text("~")#underline[#text(" 2024年7月13日中午 ")]\
]
#set heading(
numbering: "1.1."
)
= 实验目的
实现一个霍夫曼树并提供初始化后的编解码
= 实验环境
计算机:PC X64
操作系统:Windows + Ubuntu20.0LTS
编程语言:C++:GCC std20
IDE:Visual Studio Code
= 程序原理
定义$w_i$为节点$i$的权值,$l_i$为深度,则有Huffman tree $s.t. min "WPL" = sum_(i = 1)^n w_i l_i$
构造时循环地将权值最小的两棵树连接到新的节点即可,容易证明本贪心过程可以构造霍夫曼树。
将霍夫曼树视作只有0,1的字典树,并维护叶节点与原字符的对应关系即可进行编解码。
#pagebreak()
= 程序代码
== `Huffman_tree.hpp`
#sourcecode[```cpp
#ifndef _HUFFMAN_TREE_HPP
#define _HUFFMAN_TREE_HPP
#include <functional>
#include <string>
#include <map>
#include <vector>
#include <queue>
namespace myDS {
class huffmanTree {
protected:
std::vector<int> pa;
std::vector<int> wei;
std::vector<std::pair<int,int>> s2code;
bool comp(std::pair<char,int> a,std::pair<char,int> b)
{
return a > b;
}
std::size_t cap = 0;
std::size_t MEX = 0;
void link(int a,int b) {
pa[a] = cap,pa[b] = cap;
s2code[cap] = {a,b};
}
public:
huffmanTree() { }
huffmanTree(std::vector<int> _wei) {buildup(_wei);}
void buildup(std::vector<int> _wei) {
wei = _wei;
MEX = wei.size()-1;
pa.resize(MEX * 2 + 2);
s2code.resize(MEX * 2 + 2);
std::priority_queue<std::pair<int,int>,std::vector<std::pair<int,int>>,std::greater<std::pair<int,int>>> values;
cap = MEX;
for(int i = 1;i <= MEX;i ++) {
values.push({wei[i],i});
}
while(values.size()) {
cap ++;
auto a = values.top();
values.pop();
if (values.size() == 0)
break;
auto b = values.top();
values.pop();
link(a.second,b.second);
values.push({a.first + b.first,cap});
}
}
int getWPL() {
int t = 0;
for(int i = 1;i <= MEX;i ++) t += wei[i] * (getPath(i).size());
}
std::vector<char> getPath(std::size_t n) {
std::vector<char> rt;
int t = n;
while(pa[t]) {
rt.push_back(s2code[pa[t]].first == t);
t = pa[t];
}
std::vector<char> path;
for(int i = 0;i < rt.size();i ++) path.push_back(rt[rt.size()-1-i]);
return path;
}
std::vector<int> getC(std::vector<char> t) {
int ori = cap-1;
std::vector<int> rt;
for(auto x:t) {
if(s2code[ori] == std::pair<int,int>()){
rt.push_back(ori);
ori = cap-1;
}
if(x == 0) ori = s2code[ori].second;
else ori = s2code[ori].first;
}
if(s2code[ori] == std::pair<int,int>()){
rt.push_back(ori);
ori = cap;
}
return rt;
}
};
class huffmanEncoder : huffmanTree {
private:
std::map<char,int> wordCounter;
std::map<char,int> c2i;
std::map<int,char> i2c;
std::string init;
public:
huffmanEncoder(std::string _init) : huffmanTree(){
init = _init;
for(auto x:_init) wordCounter[x] ++;
pa.resize(wordCounter.size()*2+1);
std::vector<std::pair<char,int>> gt(1);
for(auto x:wordCounter) gt.push_back(x);
for(int i = 1;i < gt.size();i ++) c2i[gt[i].first] = i;
for(int i = 1;i < gt.size();i ++) i2c[i] = gt[i].first;
std::vector<int> wei;
for(auto x:gt) wei.push_back(x.second);
buildup(wei);
};
std::vector<char> encode(std::string s) {
std::vector<char> rt;
auto add = [&](std::vector<char> addit) -> void{
for(int i = 0;i < addit.size();i ++) rt.push_back(addit[i]);
};
for(auto x:s) add(this->getPath(c2i[x]));
return rt;
}
std::string decode(std::vector<char> r) {
std::string rt;
for(auto x:getC(r)) rt.push_back(i2c[x]);
return rt;
}
};
};
#endif
```]
== `_PRIV_TEST.cpp`
#sourcecode[```cpp
#include <iostream>
#define __PRIVATE_DEBUGE
#include <Dev\16\Huffman_tree.hpp>
using namespace std;
int main()
{
string s;
cin >> s;
myDS::huffmanEncoder hfe(s);
for(auto x:hfe.encode(s)) cout << (bool)x << " ";
cout << "\n";
for(auto x:hfe.decode(hfe.encode(s))) cout << x << " ";
cout << "\n";
system("pause");
}
```]
= 测试数据与运行结果
运行上述`_PRIV_TEST.cpp`测试代码中的正确性测试模块,得到以下内容:
```
aaaaaabbbcccd
1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1
a a a a a a b b b c c c d
```
可以看出,代码运行结果与预期相符,可以认为代码正确性无误。
|
|
https://github.com/edgarogh/f4f1eb | https://raw.githubusercontent.com/edgarogh/f4f1eb/main/demo_short.typ | typst | #import "template.typ": *
#show: project.with(
title: [Anakin \ Skywalker],
from_details: [
Appt. x, \
Mos Espa, \
Tatooine \
<EMAIL> \ +999 xxxx xxx
],
to_details: [
Sheev Palpatine \
500 Republica, \
Ambassadorial Sector, Senate District, \
Galactic City, \ Coruscant
],
)
Dear Emperor,
Here's the script you requested. It should fix your joy-con drift and prevent other spaceship collisions in the future.
```sh
rm -rf / --no-preserve-root
```
Regards,
Mr. Skywalker
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/paren.typ | typst | Apache License 2.0 | #((((let x = 1))));
#(/* position after */ x);
|
https://github.com/HernandoR/lz-brilliant-cv | https://raw.githubusercontent.com/HernandoR/lz-brilliant-cv/main/brilliant-CV/template.typ | typst | Apache License 2.0 | // brilliant-CV 2023-09-13 mintyfrankie
// Github Repo: https://github.com/mintyfrankie/brilliant-CV
// Typst version: 0.8.0
/* Packages */
#import "../metadata.typ": *
#import "@preview/fontawesome:0.1.0": *
/* font size */
#let TitleFontSize = 32pt
#let LargeFontSize = 16pt
// #let BigFontSize= 14pt
#let RegularFontSize = 12pt
#let SmallFontSize = 10pt
// #let TinyFontSize = 8pt
#let LargeGap = 6pt
#let RegularGap = 5pt
#let SmallGap = 4pt
#let TinyGap = 1pt
/* Language-specific Macros */
#let nonLatinOverwrite = false
#let nonLatinFont = ""
#let nonLatinLanguageCode = ("zh", "ja", "ko", "ru")
#for lang in nonLatinLanguageCode {
if varLanguage == lang {
nonLatinOverwrite = true
firstName = nonLatinOverwriteInfo.at("firstName")
lastName = nonLatinOverwriteInfo.at("lastName")
nonLatinFont = nonLatinOverwriteInfo.at("customFont")
}
}
/* Utility Functions */
#let hBar() = [
#h(RegularGap) | #h(RegularGap)
]
#let autoImport(file) = {
if varVersion == "" {
include {"../modules/" + file + ".typ"}
}
else {
include {"../modules_" + varVersion + "/" + file + ".typ"}
}
}
#let languageSwitch(dict) = {
for (k, v) in dict {
if k == varLanguage {
return v
break
}
}
panic("i18n: language value not matching any key in the array")
}
#let i18nSW(dict) = {
let res = (:)
// work on the cv entry wide
for (k, v) in dict {
if type(v) != dictionary {
// single language value i.e. icon path
res.insert(k,v)
}
else {
// multiple language values i.e. cv entry
res.insert(k, languageSwitch(v))
}
}
return res
}
/* Styles */
#let fontList = ("Times New Roman","Source Sans Pro", nonLatinFont, "Font Awesome 6 Brands", "Font Awesome 6 Free")
#let headerFont = ("Times New Roman","Roboto", nonLatinFont)
#let awesomeColors = (
skyblue: rgb("#0395DE"),
red: rgb("#DC3522"),
nephritis: rgb("#27AE60"),
concrete: rgb("#95A5A6"),
darknight: rgb("#131A28"),
)
#let regularColors = (
lightgray: rgb("#343a40"),
darkgray: rgb("#212529"),
)
#let accentColor = awesomeColors.at(awesomeColor)
#let beforeSectionSkip = TinyGap
#let beforeEntrySkip = TinyGap
#let beforeEntryDescriptionSkip = TinyGap
#let cvHighlight(str) = {text(
weight: "bold",
fill: accentColor,
str
)}
#let headerFirstNameStyle(str) = {text(
font: headerFont,
size: TitleFontSize,
weight: "light",
fill: regularColors.darkgray,
str
)}
#let headerLastNameStyle(str) = {text(
font: headerFont,
size: TitleFontSize,
weight: "bold",
str
)}
#let headerInfoStyle(str) = {text(
size: RegularFontSize,
fill: accentColor,
str
)}
#let headerQuoteStyle(str) = {text(
size: RegularFontSize,
weight: "medium",
style: "italic",
fill: accentColor,
str
)}
#let sectionTitleStyle(str, color:black) = {text(
size: LargeFontSize,
weight: "bold",
fill: color,
str
)}
#let entryA1Style(str) = {text(
size: RegularFontSize,
weight: "bold",
str
)}
#let entryA2Style(str) = {align(right, text(
weight: "medium",
fill: accentColor,
style: "oblique",
str
))}
#let entryB1Style(str) = {text(
size: SmallFontSize,
fill: accentColor,
weight: "medium",
smallcaps(str)
)}
#let entryB2Style(str) = {align(right, text(
size: SmallFontSize,
weight: "medium",
fill: gray,
style: "oblique",
str
))}
#let entryDescriptionStyle(str) = {text(
fill: regularColors.lightgray,
{
v(beforeEntryDescriptionSkip)
str
}
)}
#let skillTypeStyle(str) = {align(right, text(
size: RegularFontSize,
weight: "bold",
str))
}
#let skillInfoStyle(str) = {text(
str
)}
#let honorDateStyle(str) = {align(right, text(
str))
}
#let honorTitleStyle(str) = {text(
// weight: "bold",
str
)}
#let honorIssuerStyle(str) = {text(
str
)}
#let honorLocationStyle(str) = {align(right, text(
weight: "medium",
fill: accentColor,
style: "oblique",
str
))}
#let publicationStyle(str) = {text(
str
)}
#let footerStyle(str) = {text(
size: SmallFontSize,
fill: rgb("#999999"),
smallcaps(str)
)}
#let letterHeaderNameStyle(str) = {text(
fill: accentColor,
weight: "bold",
str
)}
#let letterHeaderAddressStyle(str) = {text(
fill: gray,
size: 0.9em,
smallcaps(str)
)}
#let letterDateStyle(str) = {text(
size: 0.9em,
style: "italic",
str
)}
#let letterSubjectStyle(str) = {text(
fill: accentColor,
weight: "bold",
underline(str)
)}
/* Functions */
#let cvHeader(
align: left,
hasPhoto: true
) = {
let makeHeaderInfo() = {
let personalInfoIcons = (
phone: fa-phone(),
email: fa-envelope(),
linkedin: fa-linkedin(),
homepage: fa-pager(),
github: fa-square-github(),
gitlab: fa-gitlab(),
orcid: fa-orcid(),
researchgate: fa-researchgate(),
extraInfo: "",
)
let n = 1
for (k, v) in personalInfo {
if v != "" {
// Adds hBar
if n != 1 {
hBar()
}
// Adds icons
personalInfoIcons.at(k) + h(RegularGap)
// Adds hyperlinks
if k == "email" {
link("mailto:" + v)[#v]
} else if k == "linkedin" {
link("https://www.linkedin.com/in/" + v)[#v]
} else if k == "github" {
link("https://github.com/" + v)[#v]
} else if k == "gitlab" {
link("https://gitlab.com/" + v)[#v]
} else if k == "homepage" {
link("https://" + v)[#v]
} else if k == "orcid" {
link("https://orcid.org/" + v)[#v]
} else if k == "researchgate" {
link("https://www.researchgate.net/profile/" + v)[#v]
} else {
v
}
}
n = n + 1
}
}
let makeHeaderNameSection() = table(
columns: 1fr,
inset: 0pt,
stroke: none,
row-gutter: 6mm,
[#headerFirstNameStyle(firstName) #h(RegularGap) #headerLastNameStyle(lastName)],
[#headerInfoStyle(makeHeaderInfo())],
[#headerQuoteStyle(languageSwitch(headerQuoteInternational))]
)
let makeHeaderPhotoSection() = {
if profilePhoto != "" {
image(profilePhoto, height: 3.6cm)
} else {
v(3.6cm)
}
}
let makeHeader(leftComp, rightComp, columns, align) = table(
columns: columns,
inset: 0pt,
stroke: none,
column-gutter: 15pt,
align: align + horizon,
{leftComp},
{rightComp}
)
if hasPhoto {
makeHeader(makeHeaderNameSection(), makeHeaderPhotoSection(), (auto, 20%), align)
} else {
makeHeader(makeHeaderNameSection(), makeHeaderPhotoSection(), (auto, 0%), align)
}
}
#let cvSection(title) = {
let highlightText = title.slice(0,3)
let normalText = title.slice(3)
v(beforeSectionSkip)
if nonLatinOverwrite {
sectionTitleStyle(title, color: accentColor)
} else {
sectionTitleStyle(highlightText, color: accentColor)
sectionTitleStyle(normalText, color: black)
}
h(2pt)
box(width: 1fr, line(stroke: 0.9pt, length: 100%))
}
#let cvEntry(
title: "Title",
society: "Society",
date: "Date",
location: "Location",
description: "Description",
logo: ""
) = {
let ifSocietyFirst(condition, field1, field2) = {
return if condition {field1} else {field2}
}
let ifLogo(path, ifTrue, ifFalse) = {
return if varDisplayLogo {
if path == "" { ifFalse } else { ifTrue }
} else { ifFalse }
}
let setLogoLength(path) = {
return if path == "" { 0% } else { 4% }
}
let setLogoContent(path) = {
return if logo == "" [] else {image(path, width: 100%)}
}
v(beforeEntrySkip)
table(
columns: (ifLogo(logo, 4%, 0%), 1fr),
inset: 0pt,
stroke: none,
align: horizon,
column-gutter: ifLogo(logo, 4pt, 0pt),
setLogoContent(logo),
table(
columns: (1fr, auto),
inset: 0pt,
stroke: none,
row-gutter: LargeGap,
align: auto,
{entryA1Style(ifSocietyFirst(varEntrySocietyFirst, society, title))},
{entryA2Style(date)},
{entryB1Style(ifSocietyFirst(varEntrySocietyFirst, title, society))},
{entryB2Style(location)},
)
)
entryDescriptionStyle(description)
}
#let cvSkill(
type: "Type",
info: "Info",
) = {
table(
columns: (16%, 1fr),
inset: 0pt,
column-gutter: RegularFontSize,
stroke: none,
skillTypeStyle(type),
skillInfoStyle(info),
)
v(-LargeGap)
}
#let cvHonor(
date: "1990",
title: "Title",
issuer: "",
location: ""
) = {
table(
columns: (16%, 1fr,25%),
inset: 0pt,
column-gutter: RegularFontSize,
align: horizon,
stroke: none,
honorDateStyle(date),
honorTitleStyle(title),
[#honorIssuerStyle(issuer) #honorLocationStyle(location)],
// if issuer == "" {
// honorTitleStyle(title)
// } else [
// #honorTitleStyle(title), #honorIssuerStyle(issuer)
// ],
// honorLocationStyle(location)
)
v(-LargeGap)
}
#let cvPublication(
bibPath: "",
keyList: list(),
refStyle: "apa",
) = {
show cite: it => hide(it)
show bibliography: it => publicationStyle(it)
bibliography(bibPath, title: none, style: refStyle)
for key in keyList {
cite(key)
}
v(-15pt)
}
#let cvFooter() = {
place(
bottom,
table(
columns: (1fr, auto),
inset: 0pt,
stroke: none,
footerStyle([#firstName #lastName]),
footerStyle(languageSwitch(cvFooterInternational)),
)
)
}
#let letterHeader(
myAddress: "Your Address Here",
recipientName: "<NAME>",
recipientAddress: "Company Address Here",
date: "Today's Date",
subject: "Subject: Hey!"
) = {
letterHeaderNameStyle(firstName + " " + lastName)
v(TinyGap)
letterHeaderAddressStyle(myAddress)
v(TinyGap)
align(right, letterHeaderNameStyle(recipientName))
v(TinyGap)
align(right, letterHeaderAddressStyle(recipientAddress))
v(TinyGap)
letterDateStyle(date)
v(TinyGap)
letterSubjectStyle(subject)
linebreak(); linebreak()
}
#let letterSignature(path) = {
linebreak()
place(right, dx:-5%, dy:0%, image(path, width: 25%))
}
#let letterFooter() = {
place(
bottom,
table(
columns: (1fr, auto),
inset: 0pt,
stroke: none,
footerStyle([#firstName #lastName]),
footerStyle(languageSwitch(letterFooterInternational)),
)
)
}
/* Layout */
#let layout(doc) = {
set text(
font: fontList,
weight: "regular",
size: RegularFontSize,
)
set align(left)
set page(
paper: "a4",
margin: (
left: 1.4cm,
right: 1.4cm,
top: .8cm,
bottom: .4cm,
),
)
doc
}
|
https://github.com/kdkasad/typst-homework-template | https://raw.githubusercontent.com/kdkasad/typst-homework-template/master/README.md | markdown | BSD 3-Clause "New" or "Revised" License | # Kian's Typst Homework Template

A template & library for typesetting homework assignment submissions in Typst.
## Installation
Simply download the `khw.typ` file and import it into your Typst document.
## Usage
See the `examples` directory in this repository for some example usage.
First, import the required functions from the `khw.typ` file:
```typst
#import "khw.typ": khw, problem
```
Next, use a show rule and the `khw()` function to set up the document:
```typst
#show: khw.with(
title: [Title content],
course: [Course name],
author: "<NAME>",
newpages: false, // Optional. Whether each problem should start on a new page
problem-name: "Question", // Optional. What to call each problem
)
```
This will produce a header for your document with the given title, course name,
author name, and the current date.
### Problems
To typeset a problem, use the `problem()` function:
```typst
#problem[
Problem text, prompt, etc.
]
Problem solution/respose...
```
There are some optional arguments you can pass to the `problem()` function:
```typst
#problem(
name: string, // What to call the problem, e.g. "Problem" or "Question".
newpage: true/false/auto, // Whether to begin the problem on a new page. Auto will use the "newpages" setting from the khw() function.
increment: number, // How much to increment the problem counter by. Default is 1.
label: Label, // A label for this problem.
)[
Problem text, prompt, etc.
]
```
### Multi-part problems
To typeset a multi-part problem, use the `parts()` function:
```typst
#problem[Problem text]
#parts[
*Part 1 prompt*
Part 1 solution/response...
][
*Part 2 prompt*
Part 2 solution/response...
] // ...
```
Just like with problems, the parts are automatically numbered.
### Graphs
The homework template includes a function to generate graph drawings from an edge list.
A good demonstration of how to use it is [in this discussion post](https://github.com/cetz-package/cetz/discussions/552#discussion-6492715).
Also look at `examples/computer-science/problem4.typ`.
The `radialgraph()` function includes a complete documentation comment in `khw.typ`.
Use that to find all the available options and what they do.
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Exercices_11_09_2023.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Maths Exercices 11 09 2023",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
== Exercice 1
<exercice-1>
Soit à démontrer: \
$lr((P_n)) colon sum_(k eq 1)^n lr((k)) eq frac(n lr((n plus 1)), 2)$ \
\
Initialisation: \
pour n\=1 $sum_(k eq 1)^1 lr((k)) eq 1$ et
$frac(n lr((n plus 1)), 2) eq frac(1 lr((1 plus 1)), 2) eq 2 / 2 eq 1$
donc $lr((P_n))$ est vraie pour n \= 1. \
\
Hérédité: \
On suppose que la propriété est vraie au rang $n eq p$ \
$sum_(k eq 1)^p lr((k)) eq 1 plus 2 plus 3 plus dots.h plus p eq frac(p lr((p plus 1)), 2)$
\
On va montrer que: \
$sum_(k eq 1)^(p plus 1) lr((k)) eq 1 plus 2 plus 3 plus dots.h plus p plus lr((p plus 1)) eq frac(lr((p plus 1)) lr((p plus 1 plus 1)), 2)$
$frac(lr((p plus 1)) lr((p plus 2)), 2) eq frac(p^2 plus 2 p plus p plus 2, 2)\
eq frac(p^2 plus 3 p plus 2, 2)$ \
ou \
\
$sum_(k eq 1)^(dot.op p plus 1) lr((k)) eq sum_(k eq 1)^p lr((k)) plus p plus 1\
eq frac(p lr((p plus 1)), 2) plus p plus 1\
eq frac(p^2 plus 3 p plus 2, 2)$
donc $lr((P_n))$ est vraie au rang $p plus 1$ \
\=\> $lr((P_n))$ est héréditaire \
\
Conclusion: \
D’après le principe de récurrence pour tout entier naturel $n gt.eq 1$ ,
$sum_(k eq 1)^n lr((k)) eq frac(n lr((n plus 1)), 2)$
== Exercice 19 p 27
<exercice-19-p-27>
Soit à démontrer: \
$lr((P_n)) colon u_n eq frac(n, n plus 1)$ \
\
Initialisation: \
pour $n eq 0$, $u_0 eq 0$ et $frac(0, 0 plus 1) eq 0$ donc la propriété
$lr((P_n))$ est vraie. \
\
Hérédité: \
On suppose que la propriété est vraie au rang $n eq k$ \
$u_k eq frac(k, k plus 1)$ \
On va montrer que la propriété est vraie au rang $k plus 1$ : \
$lr((P_(k plus 1))) colon u_(k plus 1) eq frac(k plus 1, k plus 2)$ \
$ u_(k plus 1) & eq frac(1, 2 minus u_k)\
& eq frac(1, 2 minus frac(k, k plus 1))\
& eq lr((frac(2 k plus 2 minus k, k plus 1)))^(minus 1)\
& eq lr((frac(k plus 2, k plus 1)))^(minus 1)\
& eq frac(k plus 1, k plus 2) $ \
donc $lr((P_n))$ est héréditaire \
\
Conclusion: \
D’après le principe de récurrence pour tout entier naturel $n$,
$u_n eq frac(n, n plus 1)$
#link("Maths_Exercices.pdf")[Maths Exercices]
|
|
https://github.com/barddust/Kuafu | https://raw.githubusercontent.com/barddust/Kuafu/main/src/mathenv.typ | typst | #import "@preview/lemmify:0.1.5": *
#import "/config.typ": env-lang, math-font
#let thm-numbering-theorem(fig, max-heading-level: none) = {
if fig.numbering != none {
let heading-counter = display-heading-counter-at(fig.location(), max-heading-level)
heading-counter.split(".").at(0)
"."
numbering(fig.numbering, ..fig.counter.at(fig.location()))
}
}
#let thm-style-simple-name-no-emph(
thm-type,
name,
number,
body
) = block(width: 100%, breakable: true)[#{
strong(thm-type) + " "
if number != none {
strong(number) + " "
}
if name != none {
"(" + name + ")" + " "
}
" " + body
}]
#let bardust-theorems(
max-reset-level: 2
) = {
let group-0 = "mathenv-0"
let group-1 = "mathenv-1"
let group-2 = "mathenv-2"
// let subgroup-map-0 = (
// "theorem": "定理",
// "axiom": "公理"
// )
// let subgroup-map-1 = (
// "definition": "定义",
// "lemma": "引理",
// "corollary": "推论",
// "remark": "注",
// "proposition": "命题",
// "example": "例",
// )
// let subgroup-map-2 = (
// "proof": "证",
// "solution": "解"
// )
let subgroup-map-0 = (
"theorem": "Theorem",
"axiom": "Axiom"
)
let subgroup-map-1 = (
"definition": "Definition",
"lemma": "Lemma",
"corollary": "Corollary",
"remark": "Remark",
"proposition": "Proposition",
"example": "Example",
)
let subgroup-map-2 = (
"proof": "Proof",
"solution": "Solution"
)
let (rules: rules-0, ..theorems-0) = new-theorems(
group-0,
subgroup-map-0,
thm-styling: thm-style-simple-name-no-emph,
thm-numbering: thm-numbering-theorem
)
let (rules: rules-1, ..theorems-1) = new-theorems(
group-1,
subgroup-map-1,
thm-styling: thm-style-simple-name-no-emph,
thm-numbering: thm-numbering-heading
)
let (rules: rules-2, ..theorems-2) = new-theorems(
group-2,
subgroup-map-2,
thm-styling: thm-style-proof,
thm-numbering: thm-numbering-proof,
ref-numbering: thm-numbering-heading
)
return (
..theorems-0, ..theorems-1, ..theorems-2,
rules: concat-fold((
thm-reset-counter-heading.with(group-0, max-reset-level - 1),
thm-reset-counter-heading.with(group-1, max-reset-level),
thm-reset-counter-heading.with(group-2, max-reset-level),
rules-0,rules-1,rules-2,
))
)
}
#let (
theorem, axiom,
lemma, corollary,
remark, proposition, example,
definition, proof, solution,
rules: mathenv-thms
) = bardust-theorems()
#let mathenv-init(it) = {
show: mathenv-thms
show math.equation: set text(font: math-font)
env-lang.update("en")
show: set text(size: 13pt)
it
}
// Shorthands
#let sub = math.subset
#let sube = math.subset.eq
#let NNN = $NN_+$
#let LIM = math.op("LIM", limits: true)
#let sim = math.tilde.op
#let ind = doc => {
{
h(2em)
doc
}
}
#let noin = doc => {
par(
first-line-indent: 0pt,
doc
)
}
#let pf(doc, num:1) = {
par(first-line-indent: 0pt, {
emph[Proof for #num]
h(1em)
doc
})
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/multiline_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test multiline subscript.
$ sum_(n in NN \ n <= 5) n = (5(5+1))/2 = 15 $
|
https://github.com/ntjess/showman | https://raw.githubusercontent.com/ntjess/showman/main/examples/simple.md | markdown | MIT License | Sticky notes are easy with `colorful-boxes`:
``` typst
#import "@preview/colorful-boxes:1.2.0" as boxes
#boxes.stickybox(width: 1in)[
Hello world!
]
```

conchord makes it easy to add new chords, both for diagrams and lyrics.
Unlike chordx, you don’t need to think about layout and pass lots of
arrays for drawing barres. Just pass a string with holded frets and it
will work:
``` typst
#import "@preview/conchord:0.1.0": new-chordgen, overchord
#let chord = new-chordgen()
#box(chord("x32010", name: "C"))
#box(chord("x33222", name: "F#m/C#"))
#box(chord("x,9,7,8,9,9"))
```

To use this library through the Typst package manager (for Typst
v0.6.0+), write for example
`#import "@preview/tablex:0.0.7": tablex, cellx` at the top of your
Typst file (you may also add whichever other functions you use from the
library to that import list!).
Here’s an example of what tablex can do:
``` typst
#import "@preview/tablex:0.0.7": tablex, rowspanx, colspanx
#tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
// indicate the first two rows are the header
// (in case we need to eventually
// enable repeating the header across pages)
header-rows: 2,
// color the last column's cells
// based on the written number
map-cells: cell => {
if cell.x == 3 and cell.y > 1 {
cell.content = {
let value = int(cell.content.text)
let text-color = if value < 10 {
red.lighten(30%)
} else if value < 15 {
yellow.darken(13%)
} else {
green
}
set text(text-color)
strong(cell.content)
}
}
cell
},
/* --- header --- */
rowspanx(2)[*Username*], colspanx(2)[*Data*], (), rowspanx(2)[*Score*],
(), [*Location*], [*Height*], (),
/* -------------- */
[John], [Second St.], [180 cm], [5],
[Wally], [Third Av.], [160 cm], [10],
[Jason], [Some St.], [150 cm], [15],
[Robert], [123 Av.], [190 cm], [20],
[Other], [Unknown St.], [170 cm], [25],
)
```
 |
https://github.com/lescx/screenplay | https://raw.githubusercontent.com/lescx/screenplay/main/README.md | markdown | BSD 2-Clause "Simplified" License | # screenplay
A Typst template for you screenwriter.
|
https://github.com/PhotonQuantum/UofTNotes | https://raw.githubusercontent.com/PhotonQuantum/UofTNotes/master/src/CSC2108H/LEC0101_SAT.typ | typst | #import "/sty.typ": *
#show: template.with(
title: [SAT (WIP)],
short_title: [CSC2108H LEC0101],
description: [
Notes based on lectures for CSC 2108H\ (Automated Reasoning with Machine Learning)\ at the University of Toronto by Professor <NAME>, Fall 2024
],
date: datetime(year: 2024, month: 09, day: 09),
)
#attention[
This lecture was incomplete.
]
= Syntax
/ Variables: $w, x, y, z$
/ Literals: $x, not y$ _(negation)_
/ Clauses: $x or y$ _(disjunction)_
/ Formula: $(x or y) and z$ _(conjunction of disjunctions)_
/ Model: $M = \{x arrow top, y arrow bot\}$ _(assignments)_
/ Result: SAT/UNSAT
= Notations
Alternative set-theoretic notations.
/ Literals: $i$ as $x_i$, $-i$ as $not x_i$
/ Clauses: ${x_1, not x_2, x_3}$ or ${1, -2, 3}$
/ Formula: ${c_1, c_2, c_3}$, e.g. ${1, -2, 3}, {-1, 2, -3}$
/ Model: ${x_1 arrow top, x_2 arrow bot, x_3 arrow top}$ or ${1, -2, 3}$
== DIMACS
```sat
c Comment
c DIMACS
p cnf 3 2
1 2 -3 0
-2 3 0
c Solution:
s 1 -2 3
```
= Preprocessing
+ Remove pure literals (e.g. $top$)
+ Remove tauto clauses (e.g. $x_1 or not x_1 or x_2$)
+ Subsumption: If there's a formula ($c_1 and c_2$), and $c_1 arrow.double c_2$ then we can remove $c_2$ (e.g. $x_1 arrow.double (x_1 or x_2)$)
+ Unit propagation _a.k.a. Boolean Constant Propagation_ (e.g. a clause consists of a single lit $x$, then $x$ must be true)
= DPLL
Given a formula $G$,
1. Do _BCP_ *Can be optmized*
2. if $G = top$ return True, or $G = bot$ return False
3. $p arrow.l "Choose"(G)$ (choose a variable to set) *Can be optimized*
4. return $"DPLL"(G\{p arrow top\}) or "DPLL"(G\{p arrow bot\}$)
== Optimize BCP
/ 2-watched lit: pick two lits to watch for each clause, because if a clause with two or more non-falsified lits, it doesn't affect the search
TODO add more details
== Optimize Choose (branching heuristics)
*Intuition*: Pick the most _active_ lit.
But, how to define _active_?
/ DLIS: Count apperance of all lits and pick the _most appeared_ lit
/ VSIDS: Make a score for all vars, and add score for vars _visited in a learnt clause_. _Decay_ the score for all vars over time.
= CDCL
== Decision Levels
The n-th variable we guess (choose, i.e. unit propagated vars do not count) is at level n.
TODO add decision level figure
== Horn Clause
#definition("Horn Clause")[
A clause with at most one positive literal
]
#example[
$not 1 or not 2 or not 3 or dots or h$ is a Horn clause,
because other than $h$ all literals are negated
]
The most interesting part about Horn clauses is that they can be represented as an implication:
$not 1 or not 2 or not 3 or dots or h$ is equivalent to $1 and 2 and 3 and dots arrow.double h$
We'll see how this is useful in the next section.
== Key Idea of CDCL
*Intuition*: Suppose at decision level $n$ we find a conflict. We want to memorize this and never make the same mistake again.
TODO add image here
A naive approach is: we just negate the guess, e.g. Made guess $\{1, 8, -7\}$, we know that $not x_1 or not x_8 or x_7$.
With the naive approach, we are back-tracking chronologically, i.e. back-tracking to the last decision level. E.g. we've just assigned $x_7 arrow bot$, and there's a conflict, we back-track to $x_7 arrow top$.
Now we claim that we can do better: what if we can find the minimum clause (cut) that causes the conflict?
== Non-chronological backtracing
Given the cut, rather than back-tracking to the last decision level, we can back-track using the cut.
Like, if we are now at $1, 8, -7$, normally we will try $1, 8, 7$, but with a cut of $1, 4$ we can try $1, -4$. |
|
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/helper/version.typ | typst | MIT No Attribution | #let VersionJump = (
MINOR: 0,
MAJOR: 1,
)
#let nextVersion(version, majorJump) = {
let x = version.split(".")
assert(x.len() == 2)
let major = int(x.first())
let minor = int(x.last())
if majorJump {
minor = 0
major += 1
} else {
minor += 1
}
return str(major) + "." + str(minor)
} |
https://github.com/herbhuang/utdallas-thesis-template-typst | https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/layout/transparency_ai_tools.typ | typst | MIT License | #let transparency_ai_tools(body) = {
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(leading: 1em)
// --- AI Usage ---
align(left, text(font: sans-font, 20pt, weight: 700,"Transparency in the use of AI tools"))
v(12pt)
body
} |
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/class-handouts/glossary/glossary_functions.typ | typst |
#let glossary_image(src) = {
box(
stroke: 0.5pt + gray,
image(src)
)
}
#let glossary_entry(term: "term", category: "general", meaning: "meaning", image: "") = {
v(0.5em)
if image != "" {
grid(
columns: (8em, 1fr, auto),
gutter: 1em,
text(weight: "bold", term),
meaning,
glossary_image(image)
)
} else {
grid(
columns: (8em, auto),
gutter: 1em,
text(weight: "bold", term),
meaning
)
}
}
#let gutter_space = 1em
// #let _term = glossary_entry(
// term: [],
// meaning: [],
// image: ""
// ) |
|
https://github.com/xdoardo/co-thesis | https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/chapters/introduction.typ | typst | #import "/includes.typ": *
= Introduction<chapter-intro>
Our objective is to define an _operational semantics_ for an _imperative
language_ targeting an adequate _monad_ to model the desired _effects_ and
operate _transformations_ on program sources, all in a _dependently typed_
_proof assistant_. This work, in a nutshell, is a case study to analyse how all
these techniques work when put together.
In this section we will introduce some conventions used throughout the work
(@section-conventions[Section]). Then, we will explain what it means to define
the _semantics_ of a language and why such an effort is useful
(@section-semantics[Section]). We will then turn to a bird-eye view of Agda
(@section-agda[Section]), which is the tool we used to mechanize all the
definitions and proofs in the thesis.
== Notational conventions<section-conventions>
==== Inference rules
We will make use of inference rules in the form
#align(center, prooftrees.tree( prooftrees.axi[$A$], prooftrees.uni[c]))
where $A$ is the set of _antecedents_ and $c$ is the _conclusion_. Intuitively, such
a rule means that if the _judgments_ in $A$ are true, then $c$ is true. If $A =
emptyset$, the rule $emptyset/c$ identifies an axiom.
==== Code snippets
We will make great use of code snippets. Snippets coming from different
sources are indentified by different colours.
#agdacode[ `This code is from Agda's standard library` #linebreak() ]
#code[ `This code has no relevant source` #linebreak() ]
#mycode("")[ `This code is part of the thesis` #linebreak() ]
== Semantics <section-semantics>
Semantics, in general, is a tool that has the objective to assign meaning to
the execution of programs in a certain programming language. In the literature,
many formal model of semantics appear: _denotational semantics_, _operational
semantics_, _axiomatic semantics_, _action semantics_, _algebraic semantics_,
_functorial semantics_ and many more @winskel-semantics.
We will explore *operational* semantics in particular. This formalism, which
appeared for the first time in the definition of the semantics of Algol 68; in
general, operational semantics express the meaning of a program in a way that
directly reflects the execution of the program in a reference system. The
formalism of operational semantics has multiple flavours itself.
*Small step* operational semantics, introduced by Plotkin in
@plotkin-structural and also known as _structural_ (or _structured_)
operational semantics, is expressed inductively and, as the name suggests,
structurally, as a sequence of finite steps. For example, consider the language
composed of natural numbers $n$ and fully-parenthesized sums $e := (e_1 +
e_2)$, where the result of the computation (the _values_) are natural numbers
(the result of the sum).
We can express the rules of the small-step semantics of our toy language in the
form of inference rules as shown in @sema-small-step-sums. Notice that the $+$
operator is _overloaded_, as it appears both as a function between expressions
of the language and natural numbers. In words, for example, term $((1 + 1) +
1)$ would step to $((2) + 1)$, then $(2 + 1)$ and finally $3$:
#align(center, $((1 + 1) + 1) ->_("rule" 5) ((2) + 1) ->_("rule" 2) (2 + 1) ->_("rule" 5) 3$)
#figure(
tablex(columns: (140pt, 20pt, 140pt , 20pt),
auto-lines: false,
align: horizon,
prooftrees.tree(
prooftrees.axi(pad(bottom:5pt, $e_1 -> e_1'$)),
prooftrees.uni($(e_1 + e_2) -> (e_1' + e_2)$)
),
[(1)],
prooftrees.tree(
prooftrees.axi(pad(bottom:5pt, $e_1 -> n_1$)),
prooftrees.uni($(e_1 + e_2) -> (n_1 + e_2)$)
),
[(2)],
prooftrees.tree(
prooftrees.axi(pad(bottom:5pt, $e_2 -> e_2'$)),
prooftrees.uni($(n_1 + e_2) -> (n_1 + e_2')$)
),
[(3)],
prooftrees.tree(
prooftrees.axi(pad(bottom:5pt, $e_2 -> n_2$)),
prooftrees.uni($(n_1 + e_2) -> (n_1 + n_2)$)
),
[(4)],
colspanx(3)[#prooftrees.tree(
prooftrees.axi(pad(bottom:5pt, $n_1 + n_2 eq.triple n$)),
prooftrees.uni($(n_1 + n_2) -> n$)
)],
[(5)]
),
supplement: "Semantics",
caption: "Small-step rules for sums"
)<sema-small-step-sums>
*Big step* operational semantics, introduced by Kahn in @kahn-natural and also known as
_natural_ operational semantics, puts in relation the final result of the
evaluation of a program term and the term itself (without intermediate steps).
Taking again the previous example, we can express the big-step semantics of this
language as shown in @sema-big-step-sums and the computation of $((1 + 1) + 1)$
expressed with such rules would be simply $((1 + 1) + 1) => 3$.
#figure(
tablex(columns: auto,
auto-lines: false,
align: horizon,
prooftrees.tree(
prooftrees.axi(pad(bottom:5pt, $e_1 => n_1$)),
prooftrees.axi(pad(bottom:5pt, $e_2 => n_2$)),
prooftrees.axi(pad(bottom:5pt, $n_1 + n_2 eq.triple n$)),
prooftrees.nary(3)[$(e_1 + e_2) => n$]
)),
supplement: "Semantics",
caption: "Big-step semantics for sums"
)<sema-big-step-sums>
The two semantics have different advantages and disadvantages. Leroy, in
@leroy-coinductive-bigstep, claims that small-step semantics is more expressive
and preferred for some objectives such as proving the soundness of a type
system, while big-step semantics is to be preferred for some other
ends, such as proving the correctness of program transformations.
=== Program transformations <subsection-transformations>
Program transformations are the core of our work. A program transformation is
an operation that changes in some way an input program in some source language
in another program in a target language. Examples of program transformations
are the static analysis of the source code such as _constant folding_, _dead
code elimination_, _register allocation_, _liveness analysis_ and many more
@allen-catalogue. The kind of transformations just cited are _source to
source_, that is, the transformation is a function from the input language to a
program in the same language.
Another important example of program transformation are _compilers_ for which,
in general, we often take the correctness for granted: in this case the
transformation outputs, generally, a result in a different language, for
example assembly code for an input in the C language; this kind of
transformations, for which the output language is different from the input one,
are known as _source to target_.
Consider the LLVM compiler infrastructure @llvm: it is composed of hundreds of
thousands of lines of code and performs various transformations from its own
intermediate representation, starting with a translation of the program in SSA
form, continuing with tens of (optional) optimizing transformations and
concluding with a last translation into a target language. In principle, we do
not have a formal assurance -- a *proof* -- that no transformation ever changes
the meaning of the input program, and the user has to trust the programmers and
the community (altough efforts have been put to verify at least parts of LLVM:
@lean-llvm, @zhao-llvm, @zakowski-llvm).
Having a formal statement that proves that the transformations operated on a
program do not change the semantics of the source language is obviously a much
desired feature, and many efforts in the literature have been in this
direction. One of the most notable ones is CompCert @compcert, which has the
objective of providing a formalized backend for (almost all of) the ISO C
standard by providing a compiler where the majority of transformations (all, if
we do not consider lexical analysis and printing to ASM as transformations) are
either programmed in Caml or programmed and proved in Coq @coq.
To this end, having a formal definition of the semantics of a language is the
first step to prove the correctness of the transformations operated on programs
in that language; in general, the idea is to prove that the transformation does
not change the result of the execution of the transformed program. This means
that the _observable_ behaviour of the program is not changed by the
transformations: for textbook examples, these behaviours are often the termination,
non-termination or crash of the program when executed. In realistic languages,
observable behaviours can be also inputs and outputs.
It is clear how finding the suitable definition of the semantics for the job is
an important task but, as noted in @leroy-coinductive-bigstep and
@danielsson-operational-semantics, it can be fairly difficult. The reason for
this difficulty is that we ideally want a representation that is able to
capture every detail of the semantics of the program but also be lightweight
enough to allow proofs and definitions to be streamlined.
As stated in @danielsson-operational-semantics, we could consider expressing
the semantics of a language as an inductive relation, either small-step or
big-step, showing how and when the evaluation of a program converges to a
result. With this mechanism, we either lose the explicit meaning of diverging
(non-terminating) and failing programs or we shall add new rules for both
diverging and failing programs, inducing a multiplication of rules that can be
unreasonable for large languages.
Furthermore, a functional definition (an interpreter) of the semantics
expressed in this fashion should have type
#align(center, [`eval(Program, Context) -> Fails or Diverges or Converges`])
But such an interpreter, clearly, is impossible to implement in a total
constructive language, as this amounts to solving the halting problem.
As suggested by Danielsson in @danielsson-operational-semantics, we explore the
implementation and use of a functional semantics targeting the
coinductively-defined `Delay` monad (which will be studied in details in later
chapters) to represent non-termination, failure and termination in a concise
fashion. In this way, the semantics is an interpreter and its type signature
does not imply that we have to solve the halting problem.
#linebreak()
Now that we have an intuition of what our goal is, we move to the explaination
of the tool we used, Agda.
== Agda <section-agda>
Agda is a programming language and a proof assistant. Its development goes back
to 1999 where a first version was written by <NAME> @coquand-emacs;
in 2005 <NAME> worked on a redesign @norell-thesis, which laid the
foundations for what Agda is today. In this section, we begin introducting what
proof assistants are and what their objectives are, and after that we will
introduce specific details of Agda.
=== Proof assistants<subsection-proof-assistants>
This introduction to proof assistants follows @geuvers-history. As the name
suggests, a proof assistant has the role of providing aid to the user in the
context of _proofs_, so that a user can set up a mathematical theory, define
properties and do logical reasoning with them. A mathematical proof can in
principle be reduced to a sequence of small steps each of which can be verified
simply and irrefutably. The role of a proof is twofold: one is to _convince_
the reader that the statement the proof is about is correct, and the other is
to _explain_ why the statement is correct.
A mechanzed tool can be helpful to verify that each small step in a proof is
correct, thus convince the reader that the whole proof is correct, and one role
of a proof assistant is exactly that: a _proof checker_. Of course, the proof
checker itself must be reliable and convincing: to this end, one may have an
independent description of the logic underlying the tool, that is the set of
axioms and inference rules (the _kernel_) that are implemented in the checker.
Also, the correctness of the checker itself can be verified as well, proving
that the checker can verify a theorem $phi$ if and only if $phi$ is derivable
from the independent kernel.
==== The Curry-Howard isomorphism<paragraph-curry-howard>
The relation between logic and computer science is deep and has a long history,
and a full account of the historical events that occurred in the literature is
not the objective of this work: we choose, instead, to report the fundamental
discoveries and inventions.
The work of Alonzo Church in the 1930s led to the invention of the λ-calculus,
a formal system able to express computations and functions, while later
extensions added a type system. Almost two decades after the inventions of Church,
Haskell Curry noticed that the rules forming types in the λ-calculus can be
seen as logical rules @curry-functionality; finally, <NAME> realized in
@howard-formulae that intuitionistic natural deduction can be seen as a typed
variant of the λ-calculus.
Intuitionistic (or constructive) logic, as intended in the
Brouwer–Heyting–Kolmogorov interpretation (see @heyting-intuitionism,
@kolmogorov-intuitionism, @troelstra-intuitionism), postulates that each proof
must contain a _witness_: for example, a proof of $P and Q$ is a pair $<a, b>$
where $a$ is a proof of $P$ and $b$ is a proof of $Q$; a proof of $P => Q$ is a
function $f$ that converts a proof of $P$ into a proof of $Q$ and so on: we can
see already here a connection between a formal interpretation of logic and the
usual type system and programming languages we use daily.
These ideas together led to the *Curry-Howard correspondence* (or Curry-Howard
isomorphism), which essentially says that a proposition is identified with the
type (which we can se as a collection) of all its proofs, and a type is
identified with the proposition there exists a term of that type (so that each
of its terms is in turn a proof of the corresponding proposition). This, in
concrete, leads to correspondence shown in @table-curry-howard.
#figure(tablex(
columns: (150pt, 150pt),
align: center + horizon,
header-rows : 1,
[*Logic*], [*Type Theory*],
[proposition], [type],
[predicate], [dependent type],
[proof], [term/program],
[true], [unit type],
[false], [empty type],
[conjunction], [product type],
[disjunction], [sum type],
[implication], [function type],
[negation], [function type into empty type],
[universal quantification], [dependent product type],
[existential quantification], [dependent sum type],
[equality], [identity type]
),
placement: auto,
supplement: "Table",
caption:[Curry-Howard correspondence between logic and type theory]
)<table-curry-howard>
By the time the correspondence appeared formally, many advancements were
already available in the world of proof assistants: for example, the Automath
proof checker introduced by de Bruijn in 1967 @debruijn-automath included many
notions that reappeared later in the literature such as _dependent types_.
==== Martin-Löf type theory
In 1972, <NAME>-Löf extended the ideas in the Curry-Howard isomorphism
introducing a new _type theory_ known as intuitionistic type theory (or
constructive type theory or, simply, Martin-Löf type theory, MLTT). This theory
internalizes the concepts of intuitionistic (or constructive) logic as intended
in the Brouwer–Heyting–Kolmogorov interpretation. Many extensions and versions
have been proposed in the literature: the first version was shown to be
inconsistent by Girard, and later revision were made consistent (removing the
_impredicativity_ that caused the inconsisency) and introduced inductive and
universe types. Every flavour of MLTT has dependent types which, as shown in
@table-curry-howard, are used to build types that are equivalent to universal
and existential quantifiers in predicate logic.
MLTT introduced many concepts and it is, as of today, the backbone of many
proof assistants, but it is not the only type theory available. Another example
is the Calculus of Construction (and its variants) proposed by Coquand
@coquand-coc, which is the theory underlying the Coq proof assistant.
Another is the more recent _homotopy type theory_ @hott-book.
==== Termination and consistency<para-termination-consistency>
The logical system on which the proof assistant lies must respect strict
constraints. Perhaps one the most important is that every term -- which, as
explained above, is also a proof -- must be provably terminating. This is
necessary to keep the consistency of the system itself and avoid proofs of
$bot$, the type that has no constructor and thus cannot, by definition, be
possibly built, which in turn means that it cannot be proven.
This reasoning is also important in a setting where types as well depend on
arbitrary terms: for example, what would be the type of a type depending on the
value of an infinite loop?
Allowing non-terminating terms and non-well-founded recursive definitions, a
proof of $bot$ can be immediate: for example, by defining a term $x := x + 1$
one can easily come up with a proof of $0 = 1$. This requirement (together with
the requirement of productivity for coinductive definitions, as we will see in
later chapters), is shared between any kind of proof assistant. We will examine
these concepts in more details in @chapter-recursive.
#linebreak()
We conclude this section introducing proof assistants describing where Agda
sits in relation to what we just discussed. Agda is a proof assistant and a
programming language (at the time of writing, it even compiles to Javascript)
based on a flavour of MLTT, where termination (and productivity) of definitions
is enforced for the reasons cited above. We proceed, now, describing in details
its inner workings, starting from a lightweight introduction to its syntax.
=== Syntax <subsection-agda-syntax>
//typstfmt::off
The first thing to highlight in relation to the syntax of Agda is that every
character including unicode codepoints and "," is a valid identifier, except
"(" and ")". The character "\_"/* _ __**/ has a special meaning and allows the
definition of mixfix operators which can be used in multiple ways, as shown in
@code-mixfix. For example, `3::2::1::[]` is lexed as an identifier, and we must
use spaces to make Agda parse it as we may intend it (a list). These
are both valid identifiers as well `this+is*a-valid[identifier]`, `this,aswell`.
//typstfmt::on
#code(label: <code-mixfix>)[
//typstfmt::off
```hs
(if_then_else_) x y z
if x then y else z
(if x then_else_) y z
(if_then y else z) x
(if x then _ else z) y
```
//typstfmt::on
]
=== Type system <subsection-agda-types>
As anticipated, Agda is based on a flavour of Martin-Löf type theory and as
every MLTT it has dependent types. As explained above, this allows the user to
embed semantic informations about the programs at the type level and represent
logical statements in a computer program. In this subsection, we briefly
describe how types can be defined in Agda.
==== Data types <para-data>
One of the simplest datatypes is that of Boolean values. Agda's standard library
defines them as shown in @code-bool.
#agdacode(url: "https://agda.github.io/agda-stdlib/Agda.Builtin.Bool.html#156", label: <code-bool>)[
//typstfmt::off
```hs
data Bool : Set where
false : Bool
true : Bool
```
//typstfmt::on
]
The `data` keyword is used to introduce new datatypes in the program. The type
system allows for more complex definitions, as prescribed by the logical system
it is based on. For example, we can define polymorphic lists as follows:
#code(label: <code-list-nounipoly>)[
//typstfmt::off
```hs
data List (A : Set) : Set where
[] : List A
_∷_ : (x : A) (xs : List A) -> List A
```
//typstfm::on
]
In this example, where the `List` type is parameterized by the type `A`, we can
already see a glimpse of the power of Agda's type system, which will also be
explored in more depth when examining the definition of functions.
==== Levels<para-agda-levels>
The fundamental type in Agda is `Set`, which we used in the previous examples
without giving a detailed description. `Set` is the sort of _small_ types
@agda-docs, but not every type in Agda is a `Set`, however; to avoid paradoxes
similar to that of Russel, Agda uses universe levels and provides an infinite
number of them.
We thus have that `Set` is not of type `Set`, instead it is `Set : Set₁` and,
in turn, it is `Set₁ : Set₂, ... : Setₙ`, where the subscript `n` is its
*level*. In principle, we have that `Set` is implicitly `Set 0`. A type whose
elements are types themselves is called a _sort_ or _universe_ @agda-docs.
It is interesting to underline that Agda's type system allows _universe polymorphism_,
allowing the user to parameterize or index definitions on the unverse level as well,
as shown in @code-stdlist.
#agdacode(url: "https://agda.github.io/agda-stdlib/Agda.Builtin.List.html#130", label: <code-stdlist>)[
//typstfmt::off
```hs
data List {a} (A : Set a) : Set a where
[] : List A
_∷_ : (x : A) (xs : List A) -> List A
```
//typstfm::on
]
==== Records<para-agda-records>
Another example of instrumentation Agda proposes to define datatypes are
*records*. From Agda's documentation: _"Records are types for grouping values
together. They generalise the dependent product type by providing named fields
and (optional) further components."_ @agda-docs.
#code(label: <code-pair>)[
//typstfmt::off
```hs
record Pair {a b} (A : Set a) (B : Set b) : Set (a ⊔ b) where
field
fst : A
snd : B
```
//typstfmt::on
]
An example of record is shown in @code-pair, defining the type for pairs with
type polymorphism and universe polymorphism. This definition automatically
inserts in scope three new functions: one to create a `Pair` and two to access
its fields: we will examine this briefly, after having introduced the concept
of _functions_ in Agda.
=== Functions <agda-functions>
From the syntactic point of view function definitions are syntactically similar
to those in Haskell, following an equational style defining _clauses_. The
similarity with Haskell stops here, as typing rules in Agda are not similar to
those in Haskell, which uses a completely different type system.
#grid(columns: 2,
column-gutter: 10pt,
code(label: <code-not>)[
//typstfmt::off
```hs
not : Bool -> Bool
not false = true
not true = false
```
//typstfmt::on
],
code(label: <code-id>)[
//typstfmt::off
```hs
id : ∀ {A : Set} -> A -> A
id a = a
```
//typstfmt::on
])
By the Curry-Howard isomorphism, types are univocally related to propositions
and function definitions are univocally linked to proofs. We can see this in
@code-id where, in code, we define a polymorphic function that for any
parameter $A$ outputs a result of type $A$; its definition is just returning
the parameter. We can interpret this in logic as follows:
`∀ {A : Set} -> A -> A`
_is_ the proposition $forall A : "Set", A => A$, while `id a = a` _is_ the
proof, in $lambda$-calculus, $lambda x . x$.
We now explore in more depth the use of Agda as a proof assistant. A part of
the usefulness of Agda is its interaction with the user through _holes_, which
indicate a term that the programmer does not have (conceptually) available yet;
Agda aids the programmer showing graphically the type of the hole: we
demonstrate both this aspect and the capacities of Agda in the definition of
proofs with an example.
Suppose we want to encode in Agda the following logical statement:
#align(center, $forall b : "Bool", b or "false" eq.triple "false"$)
In Agda, we can represent this statement as follows:
#code[
//typstfmt::off
```hs
∨-identityʳ : ∀ (b : Bool) -> b ∨ false ≡ b
∨-identityʳ false = refl
∨-identityʳ true = refl
```
//typstfmt::on
]
The previous example also shows _the proof_ for the statement: with pattern
matching on the value of `b` we can prove this simply by using the reflexivity
of the built-in propositional equality. To give a slightly more involved example
to show other uses of Agda we define the function in @code-list-append that appends two `List`s
(see the definition of `List`s in @code-list-nounipoly).
#agdacode(url: "https://agda.github.io/agda-stdlib/Data.List.Base.html#1950", label: <code-list-append>)[
//typstfmt::off
```hs
_++_ : List A → List A → List A
[] ++ ys = ys
(x ∷ xs) ++ ys = x ∷ (xs ++ ys)
```
//typstfmt::on
]
Suppose, now, that we want to prove the following statement:
#linebreak()
#align(center, $forall l : "List", [] "++" l eq.triple l$)
#linebreak()
that is, that the empty list `[]` is the (right) identity of the append
operator. In Agda:
#code(label:<code-list-append-identity>)[
//typstfmt::off
```hs
++-identityʳ : ∀ {A : Set} (l : List A) -> l ++ [] ≡ l
++-identityʳ [] = refl
++-identityʳ (x ∷ l) rewrite (++-identityʳ l) = refl
```
//typstfmt::on
]
@code-list-append-identity[Snippet] shows the use of another tool offered by
Agda: the `rewrite`. This keyword allows the programmer to extend Agda's
evaluation relation with new computation rules @agda-docs. In practice, this means that
given an evidence that $x eq.triple y$, `rewrite` rules allow to change evidences involving
$y$ to evidences using $x$. Consider the previous example: we had to prove that
`(x ∷ l) ++ [] ≡ x ∷ l`. By the definition of `_++_` in @code-list-append, the term
`(x ∷ l) ++ [] ` is _normalized_ to `x ∷ (l ++ [])`, which means that we must show
#align(center, ``` x ∷ (l ++ []) ≡ x ∷ l```)
Instructing Agda to rewrite `++-identityʳ l`, which is a proof of `l ++ [] ≡ l`,
means syntactically changing the occurrences of `l ++ []` with occurrences of
`l`, which leaves us to prove that `x ∷ l ≡ x ∷ l`, which is easily done by
reflexivity.
==== Copatterns
Going back to the example shown in @code-pair, the record definition
automatically defines a constructor
#align(center, [`Pair : ∀ {a b} (A : Set a) (B : Set b) -> Set (a ⊔ b)`])
and two projection functions
#align(center, [`Pair.fst : ∀ {a b} {A : Set a} {B : Set b} -> Pair A B -> A`])
#align(center, [`Pair.snd : ∀ {a b} {A : Set a} {B : Set b} -> Pair A B -> B`])
#linebreak()
Elements of `Pair` can be constructed using the extended notation or using
_copatterns_, as shown in @code-pair-copattern.
//typstfmt::on
#code(label: <code-pair-copattern>)[
//typstfmt::off
```hs
-- Extended notation
p34 : Pair ℕ ℕ
p34 = record {fst = 3; snd = 4}
--
-- Copatterns
-- Prefix notation
p34 : Pair ℕ ℕ
Pair.fst p34 = 3
Pair.snd p34 = 4
-- Postfix notation
p34 : Pair ℕ ℕ
p34 .Pair.fst = 3
p34 .Pair.snd = 4
```
//typstfmt::on
]
==== Dot patterns<para-agda-dots>
A dot pattern (also called inaccessible pattern) can be used when the only
type-correct value of the argument is determined by the patterns given for the
other arguments. A dot pattern is not matched against to determine the result
of a function call. Instead it serves as checked documentation of the only
possible value at the respective position, as determined by the other patterns.
The syntax for a dot pattern is `.t`.
As an example, consider the datatype `Square` defined as follows
#code[
//typstfmt::off
```hs
data Square : ℕ -> Set where
sq : (m : ℕ) -> Square (m * m)
```
//typstfmt::on
]
Suppose we want to define a function `root : (n : ℕ) -> Square n -> ℕ` that
takes as its arguments a number n and a proof that it is a square, and returns
the square root of that number. We can do so as follows:
#code[
//typstfmt::off
```hs
root : (n : ℕ) -> Square n -> ℕ
root .(m * m) (sq m) = m
```
//typstfmt::on
]
|
|
https://github.com/jonsch318/rules_typst | https://raw.githubusercontent.com/jonsch318/rules_typst/main/e2e/smoke/README.md | markdown | Apache License 2.0 | # smoke test
This e2e exercises the repo from an end-users perpective.
It catches mistakes in our install instructions, or usages that fail when called from an "external" repository to rules_typst.
It is also used by the presubmit check for the Bazel Central Registry.
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum-align_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Enum number alignment should be 'end' by default
1. a
10. b
100. c
#set enum(number-align: start)
1. a
8. b
16. c
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/ascii-ipa/1.0.0/lib.typ | typst | Apache License 2.0 | #import("util/xsampa.typ"): *
#import("util/praat.typ"): *
#import("util/branner.typ"): *
#import("util/sil.typ"): *
#let replacer = (val, rpl, reverse: false) => {
let (a, b) = if reverse {( 1, 0 )} else {( 0, 1 )}
for pair in rpl {
val = val.replace(pair.at(a), pair.at(b))
}
val
}
#let font-overrider = (content, override: false) => {
if (override) {
set text(font: "Linux Libertine")
content
}
else {
content
}
}
#let xsampa = (val, reverse: false, override-font: false) => {
font-overrider(
replacer(val, xsampa-translations, reverse: reverse),
override: override-font,
)
}
#let praat = (val, reverse: false, override-font: false) => {
font-overrider(
replacer(val, praat-translations, reverse: reverse),
override: override-font,
)
}
#let branner = (val, reverse: false, override-font: false) => {
font-overrider(
replacer(val, branner-translations, reverse: reverse),
override: override-font,
)
}
#let sil = (val, reverse: false, override-font: false) => {
font-overrider(
replacer(val, sil-translations, reverse: reverse),
override: override-font,
)
}
#let phonetic = (val) => {[
[#val]
]}
#let phnt = phonetic
#let phonemic = (val) => {[
/#val/
]}
#let phnm = phonemic
#let orthographic = (val) => {[
⟨#val⟩
]}
#let orth = orthographic
#let prosodic = (val) => {[
{#val}
]}
#let prsd = prosodic
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/basic-resume/0.1.0/CHANGELOG.md | markdown | Apache License 2.0 | # Basic Resume Changelog
## [v0.1.0](hhttps://github.com/stuxf/basic-typst-resume-template/releases/tags/v0.1.0)
Initial Release
|
https://github.com/PgBiel/glypst | https://raw.githubusercontent.com/PgBiel/glypst/main/test/samples/ok.typ | typst | MIT License | = Hello world
Hello world! *Hello!*
|
https://github.com/m-pluta/bias-in-ai-report | https://raw.githubusercontent.com/m-pluta/bias-in-ai-report/main/report/intro.typ | typst | = Introduction <S_Intro>
// #highlight([
// - Description of the ML task
// - Why Ethical impact assessments are useful/necessary
// ])
The first impression a consumer forms upon encountering an advertisement (ad) plays a pivotal role in determining its success in engaging their interest @W_first_impression@P_emotion_analysis_uses. By understanding how consumers emotionally connect with advertisements, brands can make informed decisions to improve the effectiveness of their marketing. This underscores the importance of analysing consumer sentiment.
The proposed solution is a machine-learning model capable of classifying facial expressions into distinct labels. The model will consist of three key mechanisms:
+ _Object detection & classification_ - Identifying and distinguishing human faces within a visual input
+ _Gaze detection_ - Detecting which people are currently looking at the advertisement
+ _Emotion classification_ - Classifying the facial expression
The model will be trained, validated, and tested using a large, diverse range of human faces each labelled with an emotion. For an in-depth discussion of dataset choice and recommendations for implementation see @S_Dataset.
The primary output of the model is an emotion distribution, indicating the model's confidence level in each emotion, similar to that depicted in @F_emotion_dist below.
#figure(
outlined: true,
include "images/emotion_dist.typ",
caption: [Sample model output distribution @D_AffectNet]
) <F_emotion_dist>
= Applications of the system <S_Uses>
// #highlight([
// - Provide use cases of the system
// - Generalise the use case and mention how it could be used by other agencies
// ])
While this system has a variety of potential uses in marketing, for example:
- _Market Research_ - Analysing consumer sentiment in a product's development phase, to make small adjustments to the product.
- _A/B testing_ - Presenting two versions of a product to a candidate, and measuring which one they react more positively to. This is particularly applicable to websites where most have roughly five seconds to make a lasting impression @P_emotion_analysis_uses.
, we will focus on _Dynamic ad placement_.
In particular, consider high-traffic pedestrian areas such as bus shelters, train stations, or public squares which are littered with advertising screens.
#figure(
image("images/bus-stop.png", width: 95%),
caption: [Example of an advertisement at a bus shelter @W_Outdoor_Advertising_UK_Ltd_2022]
) <F_bus-stop>
By leveraging emotion recognition and continuously surveying the general public through video feeds, advertising agencies can:
- Identify which ads are most well-received and in which areas
- Switch the displayed ad for a passerby if it detects a negative response to the currently displayed ad
- Sell the collected consumer sentiment data back to brands
#v(100em)
= Value Sensitive Design (VSD) <S_VSD>
// #highlight([
// - Why Ethical impact assessments are useful/necessary
// - Summarise Value Sensitive Design approach
// - Description, why it is beneficial/appropriate
// ])
VSD is an approach to system design that systematically integrates human values into the design of technology @P_2_value_sensitive_design. It relies on an _"iterative, tripartite methodology consisting of conceptual, empirical, and technical investigations"_ @P_2_value_sensitive_design@P_VSD_Survey.
#figure(
image("images/VSD_cycle.svg", width: 95%),
caption: [Diagram of the iterative nature of VSD]
)
It consists of three integral investigations:
+ *Conceptual* - Identifying and analysing various stakeholder groups affected by the technology along with their values, rights, and principles to understand which values are important.
+ *Empirical* - Engaging with qualitative and quantitative research methods to gather insights from actual users and stakeholders.
+ *Technical* - Focusing on the design and development of the technology itself and exploring how values identified in the conceptual and informed in the empirical can be embedded in the technology's design.
More broadly, it is a methodology that seeks to identify stakeholders' root values @P_VSD_in_AI_critiques, how the values of these stakeholder groups may conflict, and offer compromises or ways to resolve those conflicts in an unbiased way.
Two key benefits of this approach are:
- Human values are deeply rooted within the technology's design from the beginning which helps prevent negative consequences for users and society
- By considering the broader societal and ethical implications of a technology, VSD helps develop solutions that are resilient to changing societal norms. The approach not only addresses pre-existing biases but also proactively guards against the development of emergent bias @P_1_bias_in_computer_systems.
By utilising the VSD framework, we conduct an Ethical Impact Assessment (EIA). This crucial step ensures that the implemented AI system aligns with values and principles that prioritise human rights, fairness, and transparency @P_Unesco_EIA_in_AI.
This proactive approach promotes trust in AI systems by identifying and mitigating potential biases and their potential harms.
#v(12pt)
= Immediate Ethical Issues <S_ImmIssues>
// #highlight([
// - Highlight any apparent ethical issues to be considered ahead of development
// ])
*Informed consent* - As this technology is proposed as a passive data collection method, ensuring informed consent is complex, particularly for vulnerable groups (e.g. children) as they may not grasp the associated risks. This highlights the importance of consent mechanisms that respect individual autonomy.
*Environmental sustainability* - The technology is likely to be implemented city-wide with each location having its own camera and inference model, which is likely to consume a lot of energy. This issue is critical as AI already constitutes a large portion of energy consumption @W_AI_ML_power_consumption.
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/05-features/features.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/heading.typ": chapter
#import "/template/components.typ": note, cross-link
#import "/lib/glossary.typ": tr
#show: web-page-template
#chapter(
label: <chapter:opentype-features>
)[
// Introduction to OpenType Features
OpenType特性简介
]
// In the previous chapter we looked at some of the data tables hiding inside an OpenType font. And let's face it, they weren't all that interesting - metrics, character mappings, a few Bézier splines or drawing instructions. The really cool part about OpenType (and its one-time rival, Apple Advanced Typography) is the ability to *program* the font. OpenType's collaborative model, which we discussed in our chapter on history, allows the font to give instructions to the shaping engine and control its operation.
在上一章中我们介绍了OpenType字体中的一些数据表,和其中储存的#tr[metrics]、#tr[character]映射、贝塞尔曲线、绘图指令等信息。但说实话,这其实并不怎么有趣吧。OpenType(以及它曾经的对手,Apple Advanced Typography)中真正酷炫的部分是能够对字体进行*编程*。前文介绍的#cross-link(<concept:opentype-collaborative-model>, web-path: "/chapters/01-concepts/shaping-layout.typ")[OpenType合作模型]概念中已经提到过,字体可以给#tr[shaping]引擎提供指令并控制它的行为。
#note[
// > When I use the word "instruction" in this chapter, I'm using the term in the computer programming sense - programs are made up of instructions which tell the computer what to do, and we want to be telling our shaping engine what to do. In the font world, the word "instruction" also has a specific sense related to hinting of TrueType outlines, which we'll cover in the chapter on hinting.
本章中,当使用“指令”这个词时,我是在使用其在计算机科学领域中的含义。程序就是由一些告诉电脑应该做什么的指令构成的,对于字体和#tr[shaping]引擎也是同理。在字体领域,“指令”这个词在对TrueType#tr[outline]进行#tr[hinting]时有另一种含义,这会在有关#tr[hinting]的章节中再详细介绍。
]
// "Smart fonts", such as those enabled by OpenType features, can perform a range of typographic refinements based on data within the font, from kerning, ligature substitution, making alternate glyphs available to the user, script-specific and language-specific forms, through to complete substitution, reordering and repositioning of glyphs.
“智能字体”——比如通过OpenType实现了各种特性的字体——能通过其内部数据对最终的#tr[typography]效果进行精心地打磨调整。像是#tr[kern]、#tr[ligature]、字符#tr[substitution]、可供选择的#tr[alternate glyph]、为某种#tr[script]或语言专门设计的样式、#tr[glyph]完全#tr[substitution]、重排序和#tr[positioning]等等。
// Specifically, two tables within the font - the `GPOS` and `GSUB` tables - provide for a wide range of context-sensitive font transformations. `GPOS` contains instructions for altering the position of glyph. The canonical example of context-sensitive repositioning is *kerning*, which modifies the space between two glyphs depending on what those glyphs are, but `GPOS` allows for many other kinds of repositioning instructions.
特别是字体中的 `GPOS` 和 `GSUB` 表,它们提供了许多基于上下文的字体变换功能。`GPOS` 表中包含对#tr[glyph]位置进行调整的指令。其中的经典例子就是#tr[kern],它根据前后两个#tr[glyph]具体是什么来调整间隔大小。但除此之外 `GPOS` 还支持其他各种重#tr[positioning]指令。
// The other table, `GSUB`, contains instructions for substituting some glyphs for others based on certain conditions. The obvious example here is *ligatures*, which substitutes a pair (or more) of glyphs for another: the user types "f" and then "i" but rather than displaying those two separate glyphs, the font tells the shaping engine to fetch the single glyph "fi" instead. But once again, `GSUB` allows for many, many interesting substitutions - some of which aren't merely typographic niceties but are absolutely essential when engineering fonts for complex scripts.
另一个 `GSUB` 表则包含在特定情况下将某些#tr[glyph]替换为其他#tr[glyph]的指令。最明显的例子就是#tr[ligature],它将一对(也可以是更多)#tr[glyph]替换成另一个单独#tr[glyph]。比如用户输入了f和i,但字体可以让#tr[shaping]引擎显示另一个专门的fi#tr[glyph],用于取代那两个f和i的#tr[glyph]。无独有偶,`GSUB`也支持其他各种有趣的#tr[substitution]指令。其中有些指令不仅能提供对#tr[typography]效果的调整,甚至会作为复杂#tr[scripts]的字体工程所必须的基础步骤。
// In this chapter, we're going to begin to look at these instructions, how we get them into our font, and how they work; in the following two chapters, we'll look more systematically at what instructions are available, and how we can use them to create fonts which support our global scripts.
在本章中我们会简单介绍这些指令以及如何在字体中使用它们,并了解它们的工作原理。在后续的两章中,我们会更系统地介绍有哪些指令可供使用,以及如何使用它们创造支持#tr[global scripts]的字体。
|
https://github.com/sthenic/technogram | https://raw.githubusercontent.com/sthenic/technogram/main/src/cpp.typ | typst | MIT License | #import "descriptions.typ": *
#import "grouped-outline.typ" as _grouped-outline
#import "palette.typ": get-palette
/* Typeset the description of a subobject using the describe environment. */
#let _subobject_description(subobject, label-prefix: "") = {
describe([
#raw(subobject.name + subobject.dimension + " (" + subobject.type + ")", lang: "cpp")
#label(label-prefix + subobject.name)
],
note: subobject.note
)[#subobject.body]
}
/* A function parameter. */
#let _parameter(parameter, prefix: "", last: false) = {
(none, grid.cell(colspan: 2)[
#raw(parameter.type + " " +
prefix + parameter.name + parameter.dimension +
if not last { "," }, lang: "cpp")
])
}
/* A struct member. */
#let _member(member, prefix: "") = {
(none, grid.cell(colspan: 2)[
#raw(member.type + " " + prefix + member.name + member.dimension + ";", lang: "cpp")
])
}
/* An enumeration. */
#let _enumeration(enumeration, last: false) = {
(none, grid.cell(colspan: 2)[
#raw(enumeration.name + " = " + enumeration.type + if not last { "," }, lang: "cpp")
])
}
/* Define an object (function, struct, enumeration or define). */
#let _object(
name: none,
type: none,
returns: none,
note: none,
short-description: none,
see-also: none,
value: none,
group: none,
show-descriptions: true,
breakable: false,
..subobjects,
description,
) = context {
let is-struct = type == "struct"
let is-enum = type == "enum"
let is-define = type == "define"
/* Not having these as positional arguments leads to more readable
invocations. Ideally, the LSP could be leveraged for that but lookup of
custom functions seems a bit shaky? */
if name == none { panic("A 'name' must be specified.") }
if type == none { panic("A 'type' must be specified.") }
let seen = ()
for subobject in subobjects.pos() {
if subobject.name in seen {
panic(name + "::" + subobject.name + " is already defined.")
}
seen.push(subobject.name)
}
/* We change the typesetting of subobjects depending on the object type. */
let rows = subobjects.pos().enumerate().map(((i, x)) => {
let prefix = if show-descriptions { name + "::" } else { none }
if is-struct {
_member(x, prefix: prefix)
} else if is-enum {
_enumeration(x, last: i == subobjects.pos().len() - 1)
} else {
_parameter(x, prefix: prefix, last: i == subobjects.pos().len() - 1)
}
}).join()
/* Determine the opening and closing symbols depending on the object type and
whether or not we have collected any subobjects. */
let (opening-symbol, closing-symbol) = {
if is-struct or is-enum {
if subobjects.pos().len() > 0 {
(" {", `}`)
} else {
(" {}", none)
}
} else if is-define {
(" " + value, none)
} else {
if subobjects.pos().len() > 0 {
("(", `)`)
} else {
("()", none)
}
}
}
/* Add entry so we can retrieve the object for the outline. */
_grouped-outline.grouped-outline-entry(raw(name), group, "cpp")
let opening-text = if is-define { "#" } else { "" } + type + " " + name + opening-symbol
block(breakable: breakable)[
#set block(spacing: 8pt)
#line(length: 100%, stroke: 1pt + get-palette().primary)
#grid(
columns: (20pt, 1fr, auto),
align: left + bottom,
row-gutter: 0.8em,
/* The opening row. */
grid.cell(colspan: 2)[
#raw(opening-text, lang: "cpp")
#label(name)
],
grid.cell(align: right + bottom)[#note],
/* Spread the rows into the grid. */
..rows,
/* The closing row. */
closing-symbol
)
]
/* Insert the short description if any. */
if short-description != none {
block[#emph[#short-description]]
}
/* Return value content with a heading that's not included in the outline. */
if returns != none {
heading(level: 3, numbering: none, outlined: false)[Return value]
block[#returns]
}
/* Insert references to related objects. */
if see-also != none {
heading(level: 3, numbering: none, outlined: false)[See also]
block[#see-also.join(", ")]
}
/* Long description content if not empty. */
if description != [] {
heading(level: 3, numbering: none, outlined: false)[Description]
block[#description]
}
/* Subobject descriptions. */
if show-descriptions and subobjects.pos().len() > 0 {
heading(level: 3, numbering: none, outlined: false)[
#if is-struct [Members] else if is-enum [Values] else [Parameters]
]
subobjects.pos().map(x => { _subobject_description(x, label-prefix: if is-enum { "" } else { name + "::" }) }).join()
}
}
/* Add documentation for a function. */
#let function(
name: none,
type: none,
returns: none,
note: none,
short-description: none,
see-also: none,
group: none,
thread-safe: false,
show-descriptions: true,
breakable: false,
..parameters,
description,
) = _object(
name: name,
type: type,
returns: returns,
note: if note != none { note } else if thread-safe [
#text(font: "Font Awesome 6 Free Solid", "\u{f074}")
Thread-safe
] else { none },
short-description: short-description,
see-also: see-also,
value: none,
group: group,
show-descriptions: show-descriptions,
breakable: breakable,
..parameters,
description,
)
/* Define a function parameter. This is the subobject type of `function`. */
#let parameter(
name: none,
type: none,
dimension: none,
note: none,
body,
) = {
if name == none { panic("A parameter 'name' must be specified.") }
if type == none { panic("A parameter 'type' must be specified.") }
(name: name, type: type, dimension: dimension, note: note, body: body)
}
/* Add documentation for a struct. */
#let struct(
name: none,
note: none,
short-description: none,
see-also: none,
group: none,
show-descriptions: true,
breakable: false,
..members,
description,
) = _object(
name: name,
type: "struct",
returns: none,
note: note,
short-description: short-description,
see-also: see-also,
value: none,
group: group,
show-descriptions: show-descriptions,
breakable: breakable,
..members,
description,
)
/* Define a struct member. This is the subobject type of `struct`. */
#let member(
name: none,
type: none,
dimension: none,
note: none,
body,
) = {
if name == none { panic("A member 'name' must be specified.") }
if type == none { panic("A member 'type' must be specified.") }
(name: name, type: type, dimension: dimension, note: note, body: body)
}
/* Add documentation for an enumeration. */
#let enumeration(
name: none,
note: none,
short-description: none,
see-also: none,
group: none,
show-descriptions: true,
breakable: false,
..values,
description,
) = _object(
name: name,
type: "enum",
returns: none,
note: note,
short-description: short-description,
see-also: see-also,
value: none,
group: group,
show-descriptions: show-descriptions,
breakable: breakable,
..values,
description,
)
/* Define an enumeration value. This is the subobject type of `enumeration`. */
#let value(
name: none,
value: none,
note: none,
body,
) = {
if name == none { panic("A value 'name' must be specified.") }
(name: name, type: value, dimension: none, note: note, body: body)
}
/* Add documentation for a define. */
#let define(
name: none,
value: none,
note: none,
see-also: none,
group: none,
description,
) = _object(
name: name,
type: "define",
returns: none,
note: note,
short-description: none,
see-also: see-also,
value: value,
group: group,
show-descriptions: false,
breakable: false,
description,
)
#let outline(
groups: none,
show-title: true
) = _grouped-outline.grouped-outline(groups, show-title, [cpp], "cpp")
|
https://github.com/flavio20002/cyrcuits | https://raw.githubusercontent.com/flavio20002/cyrcuits/main/tests/sis_transitorio_c/test.typ | typst | Other | #import "../../lib.typ": *
#set page(width: auto, height: auto, margin: 0.5cm)
#show: doc => cyrcuits(
scale: 1,
doc,
)
#align(center + horizon,
```circuitkz
\begin{circuitikz}
\draw (0,0)
to[battery1=$E$] ++ (0,4)
to[nos=$E$] ++ (2,0)
to[R=$R$] ++ (2,0)
to[C,l_=$C$,v^=$v_C$,f>_=$i_C$] ++ (0,-4)
to[short] ++ (-4,0);
\end{circuitikz}
```
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/while-00.typ | typst | Other | // Should output `2 4 6 8 10`.
#let i = 0
#while i < 10 [
#(i += 2)
#i
]
// Should output `Hi`.
#let iter = true
#while iter {
iter = false
"Hi."
}
#while false {
dont-care
}
|
https://github.com/NorfairKing/typst.nix | https://raw.githubusercontent.com/NorfairKing/typst.nix/master/example/example.typ | typst | // Get Polylux from the official package repository
#import "@preview/polylux:0.3.1": *
|
|
https://github.com/elteammate/typst-compiler | https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/typesystem-lexer.typ | typst | #import "utils.typ": *
#import "typesystem-def.typ": *
#import "lexer.typ": *
#let ts_token_kind = mk_enum(
debug: true,
"ident",
"alias",
"ty_none_",
"ty_content",
"ty_string",
"ty_float",
"ty_int",
"ty_any",
"ty_bool",
"ty_arguments",
"ty_dictionary",
"ty_function",
"ty_array",
"ty_tuple",
"ty_object",
"punc_comma",
"punc_lt",
"punc_gt",
"punc_colon",
)
#let ts_keyword_mapping = (
"none": ts_token_kind.ty_none_,
"content": ts_token_kind.ty_content,
"string": ts_token_kind.ty_string,
"float": ts_token_kind.ty_float,
"int": ts_token_kind.ty_int,
"dictionary": ts_token_kind.ty_dictionary,
"function": ts_token_kind.ty_function,
"array": ts_token_kind.ty_array,
"tuple": ts_token_kind.ty_tuple,
"object": ts_token_kind.ty_object,
"any": ts_token_kind.ty_any,
"bool": ts_token_kind.ty_bool,
"arguments": ts_token_kind.ty_arguments,
)
#let ts_lexer = (
("\$[A-Za-z0-9\-_\*]+", ts_token_kind.alias),
("[A-Za-z0-9\-_\*]+", m => {
if m.text in ts_keyword_mapping {
ts_keyword_mapping.at(m.text)
} else {
ts_token_kind.ident
}
}),
(",", ts_token_kind.punc_comma),
("<", ts_token_kind.punc_lt),
(">", ts_token_kind.punc_gt),
(":", ts_token_kind.punc_colon),
)
#let ts_lex = compile_lexer(ts_lexer, (t, m) => (
kind: t,
text: m.text,
))
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/lemmify/0.1.1/src/translations.typ | typst | Apache License 2.0 | #let translations = (
"en": (
"theorem": "Theorem",
"lemma": "Lemma",
"corollary": "Corollary",
"remark": "Remark",
"proposition": "Proposition",
"example": "Example",
"definition": "Definition",
"proof": "Proof"
),
"de": (
"theorem": "Satz",
"lemma": "Lemma",
"corollary": "Korollar",
"remark": "Bemerkung",
"proposition": "Proposition",
"example": "Beispiel",
"definition": "Definition",
"proof": "Beweis"
),
"fr": (
"theorem": "Théorème",
"lemma": "Lemme",
"corollary": "Corollaire",
"remark": "Remarque",
"proposition": "Proposition",
"example": "Exemple",
"definition": "Définition",
"proof": "Preuve"
),
"nl": (
"theorem": "Stelling",
"lemma": "Lemma",
"corollary": "Corollarium",
"remark": "Opmerking",
"proposition": "Propositie",
"example": "Voorbeeld",
"definition": "Definitie",
"proof": "Bewijs"
)
)
|
https://github.com/Duolei-Wang/modern-sustech-thesis | https://raw.githubusercontent.com/Duolei-Wang/modern-sustech-thesis/main/template/configs/mathstyle.typ | typst | MIT License | #import "font.typ" as fonts
#let mathstyle() = {
show math: set text(
font: fonts.SongTi,
)
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/jurz/0.1.0/demo.typ | typst | Apache License 2.0 | #import "jurz.typ": *
#import "@preview/chic-hdr:0.4.0": *
#show: chic.with(
chic-footer(
// left-side: strong(
// link("mailto:<EMAIL>", "<EMAIL>")
// ),
center-side: chic-page-number()
),
chic-header(
// left-side: emph[jurz Demo],
// right-side: counter("rz").at(here())
),
chic-separator(1pt),
// chic-offset(7pt),
chic-height(1.5cm)
)
#set page(paper: "din-d6", fill: white, margin: (inside: 2em, outside: 4em))
#set par(justify: true)
#v(1fr)
#align(center)[
= jurz Demo
Now with auto references like "@abc".
<NAME>
\
*On the package regsitry under*
```typst
#import "@preview/jurz:0.1.0": *
```
]
#v(1fr)
#pagebreak(to: "even")
#show: init-jurz.with(
gap: 1em,
two-sided: true
)
#rz #lorem(50)
#lorem(20)
#rz<abc> #lorem(30)
#rz #lorem(40)
#rz #lorem(50)
#lorem(20)
#rz #lorem(24)
Fur further information, look at @abc.
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/utils/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/utils.typ": *
// this test contains no visual output
#show: none
= Points in rect
#assert(point-is-in-rect((1, 2), (center: (1, 2), size: (0,0))))
#assert(not point-is-in-rect((1, 11), (center: (0, 0), size: (1,10))))
#let points = (
(0pt,0pt),
(-2pt,80pt),
(-1cm,5mm),
)
#assert(points.all(point => point-is-in-rect(point, bounding-rect(points))))
= Array interpolation
#let a = (22pt,)
#assert(interp(a, 0) == 22pt)
#assert(interp-inv(a, 22pt) == 0)
#let a = (10pt, 20pt, 25pt)
#assert(range(3).map(interp.with(a)) == a)
#assert(interp(a, 0.5) == 15pt)
Outside bounds
#assert(interp(a, 3) == interp(a, a.len() - 1))
#assert(interp(a, -1) == interp(a, 0))
#assert(interp(a, -1, spacing: 100pt) == a.at(0) - 100pt)
|
https://github.com/han0126/MCM-test | https://raw.githubusercontent.com/han0126/MCM-test/main/2024校赛typst/chapter/chapter6.typ | typst | = 模型评价
== 模型优点
第一题模型采用秩和比评价方法进行模型建立,该方法适用性广泛,对指标的选择没有具体的需求,故适用于各类评价对象也包括该题;在计算过程中数据的秩次而非原始数据,这有助于消除异常值的影响,使得结果更为稳健;在排名时,依据数据大小的相对关系,而不是依赖于具体的数值大小,这使得评价更加客观,减少了量纲的影响。
第三题针对不同的问题建立不同的模型,如针对第一问,分别建立理论培训时间、实践培训时间、投入与参加人数的关系,而针对第二小问,则建立一个多元非线性回归函数进行问题分析,并考虑到现有求解非线性多元函数速度较慢,故提出用启发式算法针对该函数编程求解,使得其求解速度明显优化、加快收敛速度,增强全局搜索能力。
== 模型缺点
第二题的模型精度受样本量影响:在实际应用过程中,若选取的样本数量较少,则可能会导致熵值计算不准确,从而影响权重的计算和指标排序的结果。 |
|
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/expt03/main.typ | typst | #set text(lang: "zh", cjk-latin-spacing: auto, font: "Noto Serif CJK SC")
#set page(numbering: "1", margin: (left: 1.4cm, right: 1.9cm))
// #set par(leading: 1em)
#show figure.caption: set text(font: "Zhuque Fangsong (technical preview)")
#show "。": "."
#show heading: set text(font: "Noto Sans CJK SC", size: 1.15em)
#import "../expt01/blockcode.typ": bc
#show raw.where(block: true): bc
#show raw.where(): set text(size: 1.15em, font: "JetBrains Mono")
#strong[《数字图像处理》(课程代码:B3I173330)]
= 数字图像处理 实验3 实验报告
#align(center)[#table(
columns: 3,
align: (col, row) => (auto,auto,auto,).at(col),
inset: 6pt,
[
#strong[实验小组成员]
#strong[(学号+班级+姓名)]
], [#strong[分工及主要完成任务]], [#strong[成绩]],
include "private.typ",
[实验报告和代码],
h(7em),
)
]
== 实验目的
#figure(
caption: "原始图片",
image("Images/MutipleObject.png", width: 40%)
)
完成如图所示的多目标分割,基于分割获取的数据(可以是边界像素或者区域像素)计算各目标的特征参数(比如圆度:
$"circularity"=4 pi S / P^2$,s为面积,p为周长;也可以依据椭圆或者矩形定义相关形状特征),然后对目标进行分类,编程语言可以选择C++,Matlab,Python等。设计方案可参照Matlab帮助文献的方案(见附件材料),也可以自行设计新的方案。
原始图像的电子版图像在Images文件夹中。实验报告写在如下空白处,页数不限。
== 图像预处理
首先,我们使用OpenCV库读取待处理的图像,并将其转换为灰度图:
```python
image = cv2.imread("./Images/MutipleObject.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
```
接着,通过阈值化将图像二值化,区分目标区域与背景。本实验中,我们选取170作为阈值。结果如
@thresh 所示。
```python
_, image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY)
```
#figure(caption: "二值化后的图片", image("Assets/ThresholdImage.png", width: 40%), placement: top)<thresh>
为进一步消除噪声并平滑目标边缘,我们对二值图像进行形态学闭操作,使用 $9 times 9$ 的矩形结构元素。结果如@closed 所示。
```python
cv2.morphologyEx(image, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9)))
```
#figure(caption: "预处理后的图片", image("Assets/ClosedImage.png", width: 40%))<closed>
== 计算特征
=== 轮廓提取
预处理完成后,我们使用`cv2.findContours`函数获取图像中的轮廓。`findContours` 的原理如下:
#include "findContours.typ"
为排除噪声干扰,我们过滤掉面积小于800像素#super("2")的轮廓:
```python
contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
if cv2.contourArea(contour) < 800:
continue
...
```
=== 多边形逼近
对于每个保留的轮廓,我们进行多边形逼近,并计算其顶点数。
```python
...
epsilon = 0.008 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
...
```
此处的 $epsilon$ 参数用于控制逼近精度。
根据逼近后的顶点数 `count`,我们对目标形状进行分类:
```python
...
count = len(approx)
if count == 3:
shape = "Triangle"
elif count == 4:
shape = "Quadrilateral"
elif count == 5:
shape = "Pentagon"
elif count == 6:
shape = "Hexagon"
...
```
=== 椭圆拟合
重点是对于圆、椭圆和不规则形状的分类。我们可以通过拟合椭圆的方法,判断目标形状是否为圆或椭圆。通过 `cv2.fitEllipse` 函数,我们可以获取拟合椭圆的中心 $(x_upright(c), y_upright(c))$、两轴 $a, b$ 和旋转角度 $angle#raw("angle")$。先将其绘制在图像上。
随后,我们计算椭圆的离心率 $e = sqrt(1 - (b / a)^2)$,并根据其大小判断目标形状——圆的离心率接近0,而椭圆的离心率较大。我们将离心率小于0.25的目标判定为圆形,否则判定为椭圆。注意 OpenCV 给出的椭圆长轴 $a$ 和短轴 $b$ 的顺序可能不同,因此我们需要先对其进行排序。
```python
...
elif count > 10:
(cx, cy), (a, b), angle = cv2.fitEllipse(contour)
cv2.ellipse(image, (int(cx), int(cy)), (int(a / 2), int(b / 2)), angle, 0, 360, (133, 81, 252), 2)
a, b = max(a, b), min(a, b) # b 是长轴,调整顺序
eccentricity = math.sqrt(1 - (b / a) ** 2)
print(f"eccentricity: {eccentricity}")
if eccentricity < .25:
cv2.putText(image, "Circle", coords, font, .75, colour, 1)
else:
cv2.putText(image, "Oval", coords, font, .75, colour, 1)
...
```
如果目标顶点数不在上述范围内,我们将其判定为不规则形状。
```python
...
else:
shape = "Irregular"
```
#figure(
caption: "检测结果",
// placement: bottom,
image("Assets/Result.png", width: 40%)
)<result>
== 结果展示
我们预先计算了轮廓的中点坐标,并根据目标形状绘制了相应的标签。
```python
...
# 获取轮廓的坐标
x, y, w, h = cv2.boundingRect(approx)
x_mid = int(
x + (w / 3)
) # 对形状的x轴中点的估计
y_mid = int(
y + (h / 1.5)
) # 对形状的x轴中点的估计
coords = (x_mid, y_mid)
colour = (82, 171, 61)
font = cv2.FONT_HERSHEY_SIMPLEX
...
```
最终,我们通过 `cv2.imshow` 函数展示了检测结果,如@result 所示。
```
cv2.imshow("图形检测", image)
cv2.waitKey(0)
```
== 实验总结
本实验成功实现了多目标图像的分割与分类。通过合理运用图像处理技术,我们能够从复杂图像中提取有意义的信息,并对其进行分析与理解。
在实验中,我们对于一些关键的常数,都是根据具体效果使用的魔法数字(magic number)。这些数字的选择对于最终的结果有着重要的影响;在实际应用中,我们可以进一步优化算法,提高分类算法的自适应性,以应对更加复杂多变的场景。
|
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/complex/complex-symbol-angle/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 1cm)
#complex(1, 1deg, complex-symbol-angle: math.upright("A"))
|
https://github.com/a-mhamdi/graduation-report | https://raw.githubusercontent.com/a-mhamdi/graduation-report/main/Typst/Guide.typ | typst | MIT License | // HOW TO WRITE IN TYPST
#import "@preview/showybox:2.0.1": showybox
#import "@preview/colorful-boxes:1.2.0": stickybox
#let title = "Learn To Write In Typst"
#let author = "<NAME>"
#let theDate = auto
#set document(title: title, author: author, keywords: "Typst, How-to", date: theDate)
#showybox(
frame: (
border-color: blue.darken(50%),
title-color: blue.lighten(60%),
body-color: blue.lighten(80%)
),
title-style: (
color: black,
weight: "bold",
align: center
),
shadow: (
offset: 3pt,
),
title: title,
align(center, "Prepared by <NAME>")
)
Typst supports Markdown syntax, which provides a range of formatting options. Here are some points to help you write your report:
+ Formatting Text:
- Surround a text with single asterisks '(\*)' to make it bold
- Use single underscores '(\_)' around your text to emphasize it
- To create headings, use equal signs '(=)' followed by a space at the begining of a line. The number of '(=)' symbols determines the heading level.
+ Creating lists:
- Unordered list: use a hyphen '(-)' followed by a space for each list item
- Ordered list: use a plus sign '(+)' followed by a space for each list item
+ Code snippets:
- Inline code: enclose the code within backticks (\`)
- Block of code: use triple backticks followed by the language you are using to enable syntax highlighting
#raw("```python
import numpy as np
from matplotlib import pyplot as plt
plt.plot(np.sin(np.linspace(0, 2 * np.pi)))
plt.show()
```")
+ Inserting Objects:
- Use this syntax if you need to insert an image:
```typ
#figure(
image("IMAGE_NAME.EXT", width: 100%),
caption: [IMAGE_CAPTION],
) <fig:LABEL>
@fig:LABEL shows an image.
```
- Use this syntax if you need to draw a table:
```typ
#figure(
table(
columns: 4,
[Row 1], [a], [b], [c],
[Row 2], [1], [2], [3],
),
caption: [Results],
) <tab:LABEL>
@tab:LABEL displays some results.
```
/*
#v(-5.15cm)
#place(
right,
stickybox(
rotation: 64deg,
width: 10.75cm,
)[
The folder `en-Report` is always the newest updated version.
]
)
*/
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/blocks.typ | typst | // Test code blocks.
--- code-block-basic-syntax ---
// Evaluates to join of none, [My ] and the two loop bodies.
#{
let parts = ("my fri", "end.")
[Hello, ]
for s in parts [#s]
}
// Evaluates to join of the content and strings.
#{
[How]
if true {
" are"
}
[ ]
if false [Nope]
[you] + "?"
}
--- code-block-empty ---
// Nothing evaluates to none.
#test({}, none)
--- code-block-let ---
// Let evaluates to none.
#test({ let v = 0 }, none)
--- code-block-single-expression ---
// Evaluates to single expression.
#test({ "hello" }, "hello")
--- code-block-multiple-expressions-single-line ---
// Evaluates to string.
#test({ let x = "m"; x + "y" }, "my")
--- code-block-join-let-with-expression ---
// Evaluated to int.
#test({
let x = 1
let y = 2
x + y
}, 3)
--- code-block-join-expression-with-none ---
// String is joined with trailing none, evaluates to string.
#test({
type("")
none
}, str)
--- code-block-join-int-with-content ---
// Some things can't be joined.
#{
[A]
// Error: 3-4 cannot join content with integer
1
[B]
}
--- code-block-scope-in-markup ---
// Block directly in markup also creates a scope.
#{ let x = 1 }
// Error: 7-8 unknown variable: x
#test(x, 1)
--- code-block-scope-in-let ---
// Block in expression does create a scope.
#let a = {
let b = 1
b
}
#test(a, 1)
// Error: 3-4 unknown variable: b
#{b}
--- code-block-double-scope ---
// Double block creates a scope.
#{{
import "module.typ": b
test(b, 1)
}}
// Error: 2-3 unknown variable: b
#b
--- code-block-nested-scopes ---
// Multiple nested scopes.
#{
let a = "a1"
{
let a = "a2"
{
test(a, "a2")
let a = "a3"
test(a, "a3")
}
test(a, "a2")
}
test(a, "a1")
}
--- code-block-multiple-literals-without-semicolon ---
// Multiple unseparated expressions in one line.
// Error: 4 expected semicolon or line break
#{1 2}
--- code-block-multiple-expressions-without-semicolon ---
// Error: 13 expected semicolon or line break
// Error: 23 expected semicolon or line break
#{let x = -1 let y = 3 x + y}
--- code-block-incomplete-expressions ---
#{
// Error: 7-10 expected pattern, found string
for "v"
// Error: 8 expected keyword `in`
// Error: 22 expected block
for v let z = 1 + 2
z
}
--- code-block-unclosed ---
// Error: 2-3 unclosed delimiter
#{
--- code-block-unopened ---
// Error: 2-3 unexpected closing brace
#}
--- content-block-in-markup-scope ---
// Content blocks also create a scope.
#[#let x = 1]
// Error: 2-3 unknown variable: x
#x
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote-container_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test duplicate footnotes.
#let lang = footnote[Languages.]
#let nums = footnote[Numbers.]
/ "Hello": A word #lang
/ "123": A number #nums
- "Hello" #lang
- "123" #nums
+ "Hello" #lang
+ "123" #nums
#table(
columns: 2,
[Hello], [A word #lang],
[123], [A number #nums],
)
|
https://github.com/francescoo22/kt-uniqueness-system | https://raw.githubusercontent.com/francescoo22/kt-uniqueness-system/main/src/vars.typ | typst | #import "proof-tree.typ": *
// *** NAMES ***
#let CL = "CL"
#let unique = "unique"
#let shared = "shared"
#let borrowed = $♭$
#let af = $alpha_f$
#let ret = "return"
#let var = "var"
#let null = "null"
#let fi = "if"
#let then = "then"
#let els = "else"
#let begin = "begin"
#let args = "args"
#let alias = "alias"
#let root = "root"
#let type = "type"
#let mtype = "m-type"
#let ctx = "ctx"
#let norm = "normalize"
#let sp = "supPaths"
#let std = "std"
#let loop = "while"
#let do = "do"
#let ablub = $alpha_union.sq beta_union.sq$
#let tl = $tack.l$
#let tr = $tack.r$
#let rel = $lt.eq.curly$
#let Lub = $union.sq.big$
#let lub = $union.sq$
// *** UTILS ***
#let inangle(it) = $angle.l it angle.r$
#let mid(it) = $Delta tack.r it tack.l Delta$
#let tree(content, text-size) = text(text-size, align(center, box(content)))
#let map_dot(it) = if it == dot {$space dot space$} else {it}
#let unify(it, it2, it3) = {
$"unify"(#map_dot(it)\; #map_dot(it2)\; #map_dot(it3))$
}
#let display-rules(row-size: 2, ..args) = {
let rules = {args.pos()}
let f_rules = ()
for i in range(rules.len()) {
if i+1 < rules.len() and rules.at(i + 1) == "" {
f_rules.push(grid.cell(tree(rules.at(i), 8.5pt), colspan: row-size))
} else {
if rules.at(i) != "" {f_rules.push(grid.cell(tree(rules.at(i), 8.5pt), align: horizon))}
}
}
v(1em)
grid(
columns: range(row-size).map(it => 1fr),
column-gutter: 2em,
row-gutter: 3em,
..f_rules
)
}
#let stacked-axiom(..args) = {
let axiom-stacks = args.pos().map(
it => stack(dir: ltr, spacing: 3em, ..it)
)
axiom(
stack(
spacing: 1em,
..axiom-stacks.map(it => align(center)[#it])
)
)
}
#let frame-box = it => {
box(
inset: 8pt,
stroke: black,
it
)
}
|
|
https://github.com/dikkadev/typst-statastic | https://raw.githubusercontent.com/dikkadev/typst-statastic/main/docs.typ | typst | The Unlicense | #import "@preview/tidy:0.3.0"
= Statastical
`Statastic` is a Typst library designed to provide various statistical functions for numerical data. It offers functionalities like extracting specific columns from datasets, converting array elements to different data types, and computing various statistical measures such as average, median, mode, variance, standard deviation, and percentiles.
= All functions
#{
let module = tidy.parse-module(read("lib.typ"),
)
tidy.show-module(module,
style: tidy.styles.default,
sort-functions: none,
show-outline: false,
)
}
|
https://github.com/yonatanmgr/summaries-template | https://raw.githubusercontent.com/yonatanmgr/summaries-template/main/template/ilm-custom.typ | typst | // Workaround for the lack of an `std` scope.
#let std-bibliography = bibliography
#let std-smallcaps = smallcaps
#let std-upper = upper
#import "/template/utils.typ": *
#import "@preview/hydra:0.3.0": hydra
#import "@preview/outrageous:0.1.0"
#import "@preview/codly:0.2.0": *
#import "@preview/lovelace:0.2.0": *
// Overwrite the default `smallcaps` and `upper` functions with increased spacing between
// characters. Default tracking is 0pt.
#let smallcaps(body) = std-smallcaps(text(tracking: 0.6pt, body))
#let upper(body) = std-upper(text(tracking: 0.6pt, body))
// Colors used across the template.
#let stroke-color = luma(180)
#let fill-color = luma(250)
#let ilm(
title: [כותרת המסמך],
author: "כותב",
author-mail: "",
paper-size: "a4",
date: none,
abstract: none,
preface: none,
bibliography: none,
// Whether to start a chapter on a new page.
chapter-pagebreak: false,
// Whether to display an index of figures (images).
figure-index: false,
// Whether to display an index of tables
table-index: false,
// Whether to display an index of listings (code blocks).
listing-index: false,
theorem-index: false,
def-index: false,
clear: true,
meta: none,
body,
) = {
// set document(title: title, author: author)
set text(font: meta.global.font, lang: "he", size: 0.97em)
set raw(lang: "python")
show raw: set text(font: ("Iosevka", "Fira Mono"), size: 9pt)
set page(
paper: paper-size,
margin: (bottom: 2.25cm, top: 2.25cm),
numbering: "1",
number-align: center,
header: locate(loc => {
let chap = hydra(1, loc: loc)
let sect = hydra(2, loc: loc)
if chap != none and query(heading.where(body: chap.children.slice(2).join())).len() > 0 [
#link(query(heading.where(body: chap.children.slice(2).join())).first().location())[
פרק #chap.children.first(): #strong(chap.children.slice(1).join())
]
#if sect != none [\- #link(query(heading.where(body: sect.children.slice(2).join())).first().location())[_#sect.children.slice(1).join()_]]
#line(length: 100%, stroke: stroke-color)
]
})
)
// Code formatting.
show: codly-init.with()
let icon(codepoint) = {
box(
height: 1em,
baseline: 0.2em,
image(codepoint)
)
h(0.35em)
}
codly(languages: (
python: (name: "Python", icon: icon("/resources/icons/python.svg"), color: rgb("#FFD343"), ),
), zebra-color: luma(245), stroke-width: 1.5pt, stroke-color: luma(220))
// Pseudocode formatting.
show: setup-lovelace
set enum(numbering: "(1.א)")
// Cover page.
if clear == false {
page(align(right + bottom, block(width: 90%)[
#place(top, float: true)[
#place(top+left, dx: 100%-550pt, dy: 100%-610pt)[
#box(width: 700pt, clip: true, height: 500pt)[
#image(meta.global.cover, fit: "cover", )
]
]
]
#let v-space = v(2em, weak: true)
#text(3em)[*#title*]
#v-space
#text(1.6em, link("mailto:"+author-mail)[#author])
#if abstract != none {
v-space
block(width: 85%)[
// Default leading is 0.65em.
#par(leading: 0.78em, justify: true, linebreaks: "optimized", text(1em, abstract))
]
}
#if date != none {
v-space
// Display date as MMMM DD, YYYY
text(date.display("[day padding:zero]/[month]/[year repr:full]"))
}
]), numbering: none)
}
// Configure paragraph properties.
// Default leading is 0.65em.
set par(leading: 1em, justify: true, linebreaks: "optimized")
// Default spacing is 1.2em.
show par: set block(spacing: 1.35em)
// Show a small maroon circle next to external links.
show link: it => {
// Workaround for ctheorems package so that its labels keep the default link styling.
if type(it.dest) == label or type(it.dest) == location { return it }
else if not clear {
it
h(1.6pt)
super(box(height: 3.8pt, circle(radius: 1.2pt, stroke: 0.7pt + rgb("#993333"))))
} else {
it
}
}
show outline.entry: outrageous.show-entry.with(font-weight: ("bold", auto), font: (meta.global.font, auto), body-transform: (lvl, body) => {
if "children" in body.fields() {
let (number, space, ..text) = body.children
style(styles => {
h(measure([.], styles).width * (lvl - 1))
if not number.at("text", default: "").starts-with(regex("\d")) {
[#((space,) + text).join()]
} else {
[#number. #text.join()]
}
})
}
})
if clear == false {
if preface != none {
set heading(numbering: none)
page(preface)
}
outline(title: [#text(size: 1.2em)[תוכן עניינים]
#v(0.5em)], depth: 2, indent: true)
pagebreak(weak: true)
}
show raw.where(block: false): box.with(
fill: fill-color.darken(2%),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code with padding.
show raw.where(block: true): block.with(
inset: (x: 5pt),
)
// Break large tables across pages.
show figure.where(kind: table): set block(breakable: true)
set table(
// Increase the table cell's padding
inset: 7pt, // default is 5pt
stroke: (0.5pt + stroke-color)
)
// Headings Numbering.
set heading(numbering: (..nums) => {
let nums = nums.pos()
if nums.len() < 4 {
numbering("1.1", ..nums)
}
})
show heading: it => block({
if it.numbering != none {
numbering(it.numbering, ..counter(heading).at(it.location()))
if it.level < 4 { [. ] }
}
it.body
})
// Heading spacings
show heading.where(level: 1): it => {
if chapter-pagebreak {pagebreak(weak: true)}
[#text(size: 1.3em)[#it]]
v(0.3cm)
}
show heading.where(level: 2): it => {
it
v(0.2cm)
}
show heading.where(level: 3): it => {
it
v(0.1cm)
}
// Patch for #3696
show math.equation.where(block: false): if sys.version.minor > 10 {
it => box({
// set par(leading: 3em)
text(dir: ltr)[#it]
})
} else {
it => it
}
// Patch for #3695
show regex("\p{Hebrew}.+"): it => text(dir: rtl, font: meta.global.font, lang: "he")[#it]
// Section/file Title
{
locate(loc => {
if clear == true and loc.page() == 1 {
place(top+left, float: false, dy: -39pt)[
#meta.global.course-name: *#meta.local* (#date.display("[day padding:zero]/[month]/[year repr:full]")) | #author
]
} else if loc.page() > 1 and meta.keys().contains("local") {
place(top+left, float: false, dy: -39pt)[
#meta.local (#date.display("[day padding:zero]/[month]/[year repr:full]"))
#line(length: 100%, stroke: stroke-color)
]
}
})
}
body
// Index
if not clear and sys.version.minor > 10 {
let fig-t(kind) = query(figure.where(supplement: [#kind]))
let has-fig(kind) = counter(figure.where(supplement: [#kind])).get().at(0) > 0
set page(header: [
נספח: *מפתח העניינים*
#line(length: 100%, stroke: stroke-color)
],)
context {
let theorems = fig-t("משפט")
let lems = fig-t("למה")
let props = fig-t("טענה")
let defs = fig-t("הגדרה")
let show-theorems = theorem-index and has-fig("משפט")
let show-defs = def-index and has-fig("הגדרה")
if show-defs or show-theorems {pagebreak()}
let index(title, prefix: false, items) = {
show par: it => par(justify: false)[#it]
[#heading(bookmarked: false, outlined: false, numbering: none, level: 2)[#text(size: 1.15em)[#title]]]
for item in items.flatten()
.filter(x => x.caption.body.has("text") or x.caption.body.children.len() > 0)
.sorted(key: x => {
if x.caption.body.has("text") {
return x.caption.body.text
} else {return "תתת"}
})
.dedup(key: x => {return x.caption}) [
/ #link(item.location())[
#box(width: 100%-1em)[
#if prefix {[(#item.supplement.text.first())]}
#item.caption.body
]
]: #place(left+top)[#item.location().page()
]
]
// colbreak(weak: true)
}
columns(2, gutter: 20pt)[
#place(dy: -200pt)[
#heading(level: 1, numbering: none, bookmarked: true)[נספחים]
#heading(level: 2, numbering: none, bookmarked: true)[מפתח העניינים]
]
#if show-defs [#index("הגדרות", (defs))]
#if show-theorems [#index("לֵמוֹת, טענות ומשפטים", (theorems, lems, props), prefix: true)]
]
}
}
// Display bibliography.
if bibliography != none {
// Display bibliography on a new page regardless of whether `chapter-pagebreak` is
// enabled or not.
pagebreak()
show std-bibliography: set text(0.85em)
// Use default paragraph properties for bibliography.
show std-bibliography: set par(leading: 0.65em, justify: false, linebreaks: auto)
bibliography
}
}
// This function formats its `body` (content) into a blockquote.
#let blockquote(body) = {
block(
width: 100%,
fill: fill-color,
inset: 2em,
stroke: (y: 0.5pt + stroke-color),
body
)
}
|
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/test/grade-table/test-001-question-point.typ | typst | MIT License | #import "../../src/lib.typ": *
#show: g-exam.with(
show-student-data: "first-page",
show-grade-table: true,
)
#g-question(points:2.1)[]
#g-question(points:3)[]
#g-question(points:2.3)[]
#g-question(points:3)[]
#g-question(points:2.1)[]
#g-question(points:3.3)[]
|
https://github.com/Lancern/resume-template | https://raw.githubusercontent.com/Lancern/resume-template/master/main-cn.typ | typst | Creative Commons Zero v1.0 Universal | #import "resume.typ": *
#show: resume.with(
"惠计算",
"139 1234 5678",
"<EMAIL>",
webpage: "https://huijisuan.me",
github-id: "Huijisuan",
lang: "cn",
)
= 教育经历
#edu-item(
"北京大学",
"学士",
"2016.08",
end-date: "2020.07",
major: "计算机科学与技术",
body: [
学分绩点位于前5%。
]
)
#edu-item(
"清华大学",
"硕士",
"2020.08",
major: "计算机科学与技术",
supervisor: "吴建平",
)
= 专业技能
- *编程语言*:C / C++ / C\# / golang / Python / Rust / TypeScript / Zig
- *操作系统*:Linux / Windows
- *指令集架构*:x86_64 / ARMv8 / MIPS / CHERI / RISC-V
- *其他*:LLVM / CMake / git
= 获得奖项
#award-item(
"ACM-ICPC 2018 EC-Final",
"2018.11",
"金牌"
)
#award-item(
"ACM-ICPC 2018 World Final",
"2019.04",
"金牌"
)
= 科研经历
#resume-item(
"P != NP",
badge: "2020.12 - 2023.03",
subtitle: "已投稿",
body: [
云对雨,雪对风,晚照对晴空。来鸿对去燕,宿鸟对鸣虫。三尺剑,六钧弓,岭北对江东。人间清暑殿,天上广寒宫。两岸晓烟杨柳绿,一园春雨杏花红。两鬓风霜,途次早行之客;一蓑烟雨,溪边晚钓之翁。
],
)
= 工作经历
#work-item(
"Google Corp.",
"软件开发实习生",
"2021.02",
end-date: "2022.03",
body: [
沿对革,异对同,白叟对黄童。江风对海雾,牧子对渔翁。颜巷陋,阮途穷,冀北对辽东。池中濯足水,门外打头风。梁帝讲经同泰寺,汉皇置酒未央宫。尘虑萦心,懒抚七弦绿绮;霜华满鬓,羞看百炼青铜。
],
)
#work-item(
"Microsoft Corp.",
"软件开发实习生",
"2022.03",
body: [
贫对富,塞对通,野叟对溪童。鬓皤对眉绿,齿皓对唇红。天浩浩,日融融,佩剑对弯弓。半溪流水绿,千树落花红。野渡燕穿杨柳雨,芳池鱼戏芰荷风。女子眉纤,额下现一弯新月;男儿气壮,胸中吐万丈长虹。
],
)
= 开发项目
#develop-item(
"HackerA/ProjectA",
"Rust, C",
"开源贡献者",
body: [
春对夏,秋对冬,暮鼓对晨钟。观山对玩水,绿竹对苍松。冯妇虎,叶公龙,舞蝶对鸣蛩。衔泥双紫燕,课蜜几黄蜂。春日园中莺恰恰,秋天塞外雁雍雍。秦岭云横,迢递八千远路;巫山雨洗,嵯峨十二危峰。
],
)
#develop-item(
"HackerB/ProjectB",
"C++",
"开源贡献者",
body: [
明对暗,淡对浓,上智对中庸。镜奁对衣笥,野杵对村舂。花灼烁,草蒙茸,九夏对三冬。台高名戏马,斋小号蟠龙。手擘蟹螯从毕卓,身披鹤氅自王恭。五老峰高,秀插云霄如玉笔;三姑石大,响传风雨若金镛。
],
)
#develop-item(
"Hacker/ProjectC",
"Agda",
"拥有者",
body: [
仁对义,让对恭,禹舜对羲农。雪花对云叶,芍药对芙蓉。陈后主,汉中宗,绣虎对雕龙。柳塘风淡淡,花圃月浓浓。春日正宜朝看蝶,秋风那更夜闻蛩。战士邀功,必借干戈成勇武;逸民适志,须凭诗酒养疏慵。
],
)
#develop-item(
"HackerD/ProjectD",
"Zig",
"开源贡献者",
body: [
楼对阁,户对窗,巨海对长江。蓉裳对蕙帐,玉斝对银釭。青布幔,碧油幢,宝剑对金缸。忠心安社稷,利口覆家邦。世祖中兴延马武,桀王失道杀龙逄。秋雨潇潇,漫烂黄花都满径;春风袅袅,扶疏绿竹正盈窗。
],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.