repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/EliasRothfuss/vorlage_typst_doku-master | https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/chapter/zusammenfassung.typ | typst | = Zusammenfassung
<cha:zusammenfassung>
Auf zwei bis drei Seiten soll auf folgende Punkte eingegangen werden:
- Welches Ziel sollte erreicht werden
- Welches Vorgehen wurde gewählt
- Was wurde erreicht, zentrale Ergebnisse nennen, am besten quantitative
Angaben machen
- Konnten die Ergebnisse nach kritischer Bewertung zum Erreichen des
Ziels oder zur Problemlösung beitragen
- Ausblick
In der Zusammenfassung sind unbedingt klare Aussagen zum Ergebnis der
Arbeit zu nennen. Üblicherweise können Ergebnisse nicht nur qualitativ,
sondern auch quantitativ benannt werden, z.~B. …konnte eine
Effizienzsteigerung von 12~% erreicht werden.~oder …konnte die Prüfdauer
um 2~h verkürzt werden.
Die Ergebnisse in der Zusammenfassung sollten selbstverständlich einen
Bezug zu den in der Einleitung aufgeführten Fragestellungen und Zielen
haben.
|
|
https://github.com/typst/templates | https://raw.githubusercontent.com/typst/templates/main/charged-ieee/README.md | markdown | MIT No Attribution | # charged-ieee
This is a Typst template for a two-column paper from the proceedings of the
Institute of Electrical and Electronics Engineers. The paper is tightly spaced,
fits a lot of content and comes preconfigured for numeric citations from
BibLaTeX or Hayagriva files.
## Usage
You can use this template in the Typst web app by clicking "Start from template"
on the dashboard and searching for `charged-ieee`.
Alternatively, you can use the CLI to kick this project off using the command
```
typst init @preview/charged-ieee
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `ieee` function with the following named arguments:
- `title`: The paper's title as content.
- `authors`: An array of author dictionaries. Each of the author dictionaries
must have a `name` key and can have the keys `department`, `organization`,
`location`, and `email`. All keys accept content.
- `abstract`: The content of a brief summary of the paper or `none`. Appears at
the top of the first column in boldface.
- `index-terms`: Array of index terms to display after the abstract. Shall be
`content`.
- `paper-size`: Defaults to `us-letter`. Specify a [paper size
string](https://typst.app/docs/reference/layout/page/#parameters-paper) to
change the page format.
- `bibliography`: The result of a call to the `bibliography` function or `none`.
Specifying this will configure numeric, IEEE-style citations.
The function also accepts a single, positional argument for the body of the
paper.
The template will initialize your package with a sample call to the `ieee`
function in a show rule. If you want to change an existing project to use this
template, you can add a show rule like this at the top of your file:
```typ
#import "@preview/charged-ieee:0.1.0": ieee
#show: ieee.with(
title: [A typesetting system to untangle the scientific writing process],
abstract: [
The process of scientific writing is often tangled up with the intricacies of typesetting, leading to frustration and wasted time for researchers. In this paper, we introduce Typst, a new typesetting system designed specifically for scientific writing. Typst untangles the typesetting process, allowing researchers to compose papers faster. In a series of experiments we demonstrate that Typst offers several advantages, including faster document creation, simplified syntax, and increased ease-of-use.
],
authors: (
(
name: "<NAME>",
department: [Co-Founder],
organization: [Typst GmbH],
location: [Berlin, Germany],
email: "<EMAIL>"
),
(
name: "<NAME>",
department: [Co-Founder],
organization: [Typst GmbH],
location: [Berlin, Germany],
email: "<EMAIL>"
),
),
index-terms: ("Scientific writing", "Typesetting", "Document creation", "Syntax"),
bibliography: bibliography("refs.bib"),
)
// Your content goes below.
```
|
https://github.com/taiga4112/jasnaoe_template_typst | https://raw.githubusercontent.com/taiga4112/jasnaoe_template_typst/main/README.md | markdown | # jasnaoe_template_typst
このテンプレートは,2024年秋季以降の日本船舶海洋工学会の講演会論文作成を想定して,
[Typst](https://typst.app)で作成しています.
もちろん♡非公式♡のテンプレートですので,ご使用の際は自己責任でお願いします.
このテンプレートを使ったPDFファイルの仕上がりは,[GitHub PagesのPDFファイル](https://taiga4112.github.io/jasnaoe_template_typst/main.pdf)をご確認ください.
(現在,Linux系のOSで試すと英語フォントがうまく作動しない現象が発生しています.詳しくは[issue](https://github.com/taiga4112/jasnaoe_template_typst/issues/25)で議論しています.)
> **注意**
>
> 2024年秋季講演会から[講演論文のテンプレートが大幅に変更]("https://www.jasnaoe.or.jp/lecture/2024aut/thesis.html?id=yoryo")されました.
>
> 具体的には,論文タイトル,著者情報,キーワード,要旨は講演論文投稿システムで別に作成し,本文のみを記載したファイルを講演論文投稿システムに投稿することで,システム側でマージして完成するようになりました.
>
> そのため,このテンプレートは,2024年秋季講演会から変更されたフォーマットに沿って,本文情報のみを記載することを想定しています。論文タイトル,著者情報,キーワード,要旨はこのテンプレートでは記載することを想定していません.
## 事前準備
### Typstのインストール
公式のマニュアルは[こちら](https://github.com/typst/typst?tab=readme-ov-file#installation).
Windowsの場合は,PowerShellか何かで,以下のコマンドを実行してください.
```bash
winget install --id Typst.Typst
```
Mac OSの場合は,Terminalか何かで,[Homebrew](https://formulae.brew.sh/)を使って,以下のコマンドを実行してください.
```bash
brew install typst
```
### フォントのインストール(Mac, Linuxのみ)
現在,フォントについては以下の設定になっています.
各自のPCにインストールされているフォントと照らし合わせて,前の方から優先的に使われるようです.
```ts
#let mincho = ("Times New Roman", "MS Mincho", "IPAMincho", "Noto Serif CJK JP", "Hiragino Mincho Pro")
#let gothic = ("Times New Roman", "MS Gothic", "IPAGothic", "Noto Sans CJK JP", "Hiragino Kaku Gothic Pro")
```
基本的には,英語の場合に優先的に選択されるTimes New Roman以外を除くと,前の方がおすすめなフォントですが,
- ゴシック: MS GothicとIPAGothic
- 明朝: MS MinchoとIPAMincho
くらいまででないと,仕上がりが[指定フォーマット](https://www.jasnaoe.or.jp/lecture/2024aut/thesis.html?id=yoryo)に近づきません.
Typstで認識されているフォントを確認するには,以下のコマンドを実行すると良いです.
```bash
typst fonts
```
#### Windows
おそらく,WindowsではMS GothicとMS Mincho,Times New Romanがデフォルトで入っているので,何もする必要がありません.
#### Mac OS
おそらく,MacではTimes New Romanは入っているけども,ゴシックや明朝はフォントをインストールする必要があります.
IPAフォントであれば,[Homebrew](https://formulae.brew.sh/)を利用して簡単にインストールできます.
```bash
brew install --cask font-ipafont
```
MSフォントは,Microsoft OfficeがインストールされているPCであれば[この記事](https://note.com/tomorrow311/n/ne835a8c525a9)の方法で取り込めそうですが,ご自身の責任でお願いします.
#### Linux
IPAフォントは以下の方法でインストールできそうです.
```bash
# Debian系(Ubuntu)
sudo apt-get install fonts-ipafont
sudo apt-get install msttcorefonts # Times New Roman
```
## 使用方法
### 1. ファイルを準備する
- GitHubアカウントを持っている方は,`use this template` で.自分用のレポジトリを生成してください
- GitHubアカウントを持っていない方は,このGitHubページの `<>Code▼` から `Download ZIP` し, ZIPファイルを解凍して使用してください.
### 2. 編集&コンパイルでpdfを作成する
編集するファイルはmain.typです.
#### コンソールでコンパイルをする場合 (推奨)
以下のコマンドを実行することでファイルの変更時に自動でコンパイルを行ってpdfファイルを生成してくれます。コンパイルが失敗する場合はエラーメッセージが表示されるので、該当の場所を修正しましょう。
```sh
typst watch main.typ main.pdf
```
詳しくは、[公式サイト](https://github.com/typst/typst?tab=readme-ov-file#usage)を参照ください.
#### Visual Studio Code (VSCode) 固有のプラグインを使用する場合 (非推奨)
1. VSCode で `File`→`Open Folder` でこのフォルダーを開く.
2. 拡張機能をインストール.
- [Typst LSP](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp)
- 何でも良いのでpdfをVSCodeで閲覧できる拡張機能.例えば,[vscode-pdf](https://marketplace.visualstudio.com/items?itemName=tomoki1207.pdf)など.
3. [Typst LSP](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp)のデフォルトの設定では,typファイルを保存すると,問題がなければコンパイル後にpdfファイルが同じ階層に生成されます.
- 問題があったときにわかりやすいように,PROBLEMS(日本語で「問題」)を常に表示させておくと良いかと思います.
- Macだと command + shift + m .
|
|
https://github.com/ustctug/ustc-thesis-typst | https://raw.githubusercontent.com/ustctug/ustc-thesis-typst/main/CHANGELOG.md | markdown | MIT License | # Change Log
All notable changes to the "ustc-thesis-typst" template will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## [Unreleased]
- Initial release
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/web3/weeks/week13.typ | typst | #import "../../utils.typ": *
#subsection("Validation")
You can notate your C\# classes with requirements which will be checked against
on input:
```cs
public class NewOrderViewModel {
[StringLength(MinimumLength = 3)]
[Required]
public string Name { get; set; }
}
```
The following tags are possible:
- [StringLength(60, MinimumLength = 3)]
- [RegularExpression(@\"^[A-Z]+[a-zA-Z''-'\s]\*\$\")]
- [Required]
- [DataType(DataType.Date)]
After that you would have to put this into your HTML in order for your binding
to take effect:
```asp
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Item.Name" class="control-label"></label>
<input asp-for="Item.Name" class="form-control" />
<span asp-validation-for="Item.Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
```
```cs
[HttpPost]
public ActionResult Index(Order order)
{
if (ModelState.IsValid)
{
order.CustomerId = User.Identity.GetUserId();
_db.Orders.Add(order);
_db.SaveChanges();
return View("OrderOk", order);
}
return BadRequest();
}
```
And in order to provide direct error handling for the user, also include the
validation on the client side with JQuery:
```asp
@section Scripts {
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
}
```
#align(
center, [#image("../../Screenshots/2023_12_22_10_41_59.png", width: 80%)],
)
#subsection("Routing")
Routing also works with tags:
```asp
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public IEnumerable<Value> Get()
{
return _valueService.All();
}
[HttpGet("{id}")]
public Value Get(int id)
{
return _valueService.Get(id); ;
}
[HttpPost]
public void Post([FromBody]Value value)
{
_valueService.Add(value);
}
/ ...
}
```
Routes themselves can directly be configured on the actions themselves:
#align(
center, [#image("../../Screenshots/2023_12_22_10_45_53.png", width: 80%)],
)
The location header should be set appropriately:
#align(
center, [#image("../../Screenshots/2023_12_22_10_47_36.png", width: 40%)],
)
```cs
[HttpPost]
public IActionResult Post([FromBody]Value value)
{
value = _valueService.Add(value);
return new CreatedAtActionResult("Get", "Values", new {id = _valueService.GetId(value)}, value);
}
```
#subsection("Swagger")
- programming language independent
- a specification for the documentation of REST APIs
- Swagger UI and Swagger codegen -> tools to generate API
- implementations for nearly every programming language
In asp, swagger can be registered at startup:
```cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}
```
Example usage:
#align(
center, [#image("../../Screenshots/2023_12_22_10_50_37.png", width: 100%)],
)
#align(
center, [#image("../../Screenshots/2023_12_22_10_51_23.png", width: 100%)],
)
Just like with Rustdoc, you can generate comments inside swagger via an XML
export, which happens with three /:
```cs
/// <summary>
/// Gets all values.
/// </summary>
/// <remarks>
/// This rest api is not thread-save. Please call only once every hour!
/// </remarks>
/// <returns></returns>
/// <response code="201">Returns the list of items</response>
/// <response code="400">If no item is there</response>
[ProducesResponseType(typeof(IEnumerable<string>), 201)]
[ProducesResponseType(typeof(void), 400)]
[HttpGet]
public IEnumerable<string> Get()
{
return _valueService.All();
}
```
#align(
center, [#image("../../Screenshots/2023_12_22_10_53_01.png", width: 80%)],
)
#subsection("Exception Handling")
As .not is actually a shit language, we ofc need exception exception. Here we go
with the dual fuckery of a global handler for exceptions.
```cs
public enum ServiceExceptionType {
Unkown = HttpStatusCode.InternalServerError,
NotFound = HttpStatusCode.NotFound,
Duplicated = HttpStatusCode.BadRequest,
}
public class ServiceException : Exception {
public ServiceExceptionType Type { get; private set; }
public ServiceException(ServiceExceptionType type){
Type = type;
}
}
public Value Get(int id) {
if (Values.Count > id && Values[id] != null) {
return Values[id];
}
throw new ServiceException(ServiceExceptionType.NotFound);
}
```
Exception usage:
```cs
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
var exception = errorFeature.Error as ServiceException;
var metadata = new
{
Message = "An unexpected error occurred! The error ID will be helpful to debug the problem",
DateTime = DateTimeOffset.Now,
RequestUri = new Uri(context.Request.Host.ToString() + context.Request.Path.ToString() + context.Request.QueryString),
Type = exception?.Type ?? ServiceExceptionType.Unkown,
ExceptionMessage = exception?.Message,
ExceptionStackTrace = exception?.StackTrace
};
context.Response.ContentType = "application/json";
context.Response.StatusCode = exception != null ? (int)exception.Type : (int)HttpStatusCode.InternalServerError;
await context.Response.WriteAsync(JsonConvert.SerializeObject(metadata));
});
});
```
#align(
center, [#image("../../Screenshots/2023_12_22_11_25_22.png", width: 80%)],
)
And you can filter for state in order to do the new new exception..
```cs
services.AddMvc(options =>
{
options.Filters.Add(new ValidateModelAttribute());
});
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
throw new ServiceException(ServiceExceptionType.ForbiddenByRule);
}
}
}
```
#subsection("Authentication")
Just like angufuck, you can inject services in order to provide authentication,
however unlike angufuck, there are some that are predefined:
- UserManager\<ApplicationUser\>\
- RoleManager\<IdentityRole\>\
- IAuthorizationService
- SignInManager
Configuration can be done on startup:
```cs
services.AddDefaultIdentity<IdentityUser>(
options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 4;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
```
Attributes can also be used to signify that a requirement must be fulfilled in
order to run this code:
```cs
[Authorize]
// your action
// aka this action required the user to be authenticated
[AllowAnonymous]
// this action allows anonymous access
```
#subsubsection("This.User")
This.User contains the currently logged in user, of which the type is "ClaimsPrincipal"
- ClaimsPrincipal
- per dependency injection, instance of UserManager\<ApplicationUser\>
- UserManager allows for CRUD operations for the application users
- var user= await \_userManager.GetUserAsync(User);
- var id = \_userManager.GetUserId(User);
#subsubsubsection("Claims")
These claims are essentially just data about a user in a key value store:
```cs
User.FindFirstValue(ClaimTypes.NameIdentifier); //=> "9e83e774-ba92-43eb-89bf-8f82df18096b"
User.FindFirstValue(ClaimTypes.Name); //=> <EMAIL>
User.FindFirstValue(ClaimTypes.Email); //=> null
```
#align(
center, [#image("../../Screenshots/2023_12_27_02_45_47.png", width: 100%)],
)
#subsubsection("Usage")
Automatic:
```cs
// authorization can only be done when already authenticated
[Authorize]
public ActionResult Create()
{
return View(new Order() { Name = "Hawaii" });
}
```
Manually:
```cs
public ActionResult Create() {
if (User.Identity.IsAuthenticated) {
return View(new Order() { Name = "Hawaii" });
}
else {
return new StatusCodeResult(401);
}
}
```
#subsection("Authorization")
There are 3 main mechanism to guarantee authorization:
- Attributes
- [Authorize(Roles = "Admin,PowerUser")]
- [Authorize(Policy = "OlderThan18,Founders")]
- Services
- var user = await \_userManager.GetUserAsync(User);
- var isInRole = await \_userManager.IsInRoleAsync(user, "Admin");
- var result = await \_authorizationService.AuthorizeAsync(User, null, "Founders");
- Claims
- User.HasClaim(ClaimTypes.Role, "Admin")
#subsubsection("Example with Razor")
```asp
@inject UserManager<ApplicationUser> manager;
@inject ApplicationDbContext context;
@{
var user = await manager.GetUserAsync(User);
if (user != null && await manager.IsInRoleAsync(user, "Administrator")){
<h1>Alle Bestellungen</h1>
<table class="table">
<thead>
<tr>
<th>#</th>
</tr>
</thead>
<tbody>
@foreach (var x in context.Orders.Include(x => x.Customer)) {
<tr><td><a asp-action="Show" asp-controller="Order" asp-route-Id="@x.Id">@x.Id</a></td></tr>
}
</tbody>
</table>
}
}
```
#subsubsection("JWT Token")
- JSON tokens
- should only be used with https
- default way to handle authentication and authorization
#align(
center, [#image("../../Screenshots/2023_12_27_02_50_36.png", width: 100%)],
)
#subsection("Integration Tests")
Integration tests allow you to create a mock page that can be accessed outside the actual network.
This is especially useful to test scenarios like, "is every page protected with authentication and authorization?"
```cs
// setup test environment
var factory = new WebApplicationFactory<Startup>();
// client that will send the test requests
Client = factory.CreateClient();
// server that will handle the clients requests
Server = factory.Server;
```
```cs
// code for the factory
public class CustomWebApplicationFactory : WebApplicationFactory<Startup>
{
private readonly string _dbId = Guid.NewGuid().ToString();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.AddDbContext<ApplicationDbContext>(options =>
// in the test environment we want to use the in memory database
options.UseInMemoryDatabase(_dbId));
});
builder.UseEnvironment("TEST");
builder.ConfigureServices(x => x.AddMvc()
// ignore antiforgery for tests
.AddRazorPagesOptions(o => o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute())));
builder.UseStartup<Startup>();
base.ConfigureWebHost(builder);
}
protected override IWebHostBuilder CreateWebHostBuilder()
{
return WebHost.CreateDefaultBuilder();
}
}
```
```cs
// example for a test
[Fact]
public async Task CreateOrder()
{
var wrongOrder = JsonConvert.SerializeObject(new NewOrderViewModel() {Name = "X"});
var okOrder = JsonConvert.SerializeObject(new NewOrderViewModel() {Name = "Hawaii"});
var result = await _sut.Request("/api/orders", null, HttpMethod.Post, new StringContent(wrongOrder, …));
Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
// …
Assert.Equal(1, _sut.Server.Host.Services.GetService<ApplicationDbContext>().Order.Count());
}
```
#subsubsection("Pitfalls")
- *The same in memory database is used over all tests* -> either make sure the change doesn't matter, or use a different one for each test
- .AddApplicationPart(typeof(Startup).Assembly);\
just do it when testing....
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/023%20-%20Oath%20of%20the%20Gatewatch/008_Zendikar's%20Last%20Stand.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Zendikar's Last Stand",
set_name: "Oath of the Gatewatch",
story_date: datetime(day: 17, month: 02, year: 2016),
author: "<NAME>",
doc
)
#emph[The plan is in motion, and all of Zendikar hangs in the balance. Chandra is ready to do her part, and so is Kiora—but if Zendikar is to be saved, the Planeswalkers must execute the plan flawlessly.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The air smelled ancient, disintegrated, as if even the dust granules from Ulamog's wake had fallen apart into tinier and tinier pieces until Zendikar's ruin was a film spread across the world.
Chandra slashed the air with arms ablaze, drawing the attention of a hundred-foot-tall, life-consuming titan. This was, in fact, on purpose. Somehow, an impossibly short number of days ago, she had been graced with the prestigious title of Abbot of Keral Keep. She wondered what her title would be now. Something like Bait, First Class.
Chandra brought up the rear of one of two groups of Zendikari, the one assigned to Ulamog. As the crowd of kor, vampires, goblins, elves, and other allies marched toward the meeting point, they kept their eyes on the titan over their shoulders. She couldn't blame them. The plan involved being as noticeably, tantalizingly alive as possible, in front of a being made to ingest life.
#figure(image("008_Zendikar's Last Stand/01.jpg", width: 100%), caption: [Relief Captain | Art by Anastasia Ovchinnikova], supplement: none, numbering: none)
In the distance, Chandra could see Gideon at the front of the other half of the bait army, coming from Kozilek's direction. His sural flashed in the sun, a focal point for the Zendikari who followed him. Chandra wondered whether Kozilek even saw Gideon's weapon, or just saw the morsels of energy who followed it.
Directly in the path of the two titans stood Jace and Nissa, like ants standing in the path of two trampling giants. This, too, was on purpose. Chandra could just see Nissa, standing in silhouette at the crest of a rocky hill, working with Jace to prepare the spell that would save the world.
Jace's warning came before Chandra heard the chittering. "#emph[Chandra, we'll deal with them. Keep Ulamog moving as best you can.] "
A wave of Eldrazi drones scrabbled into the path of the bait army. Her group couldn't afford to slow down to engage them, and Chandra couldn't clear them out from her position at the rear. She could only hope Jace was right. She looked up and ricocheted two spiraling blasts of fire off the uncrackable faceplate of Ulamog.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"#emph[Kiora, there's a contingent coming from the south. Can you contain them?] "
Kiora stood tall, gripping the bident tightly. Waves of seawater flowed and bounded around her like dolphins, lifting her and carrying her across the Halimar Sea and onto the land. She passed the base of the hill where the mind mage and the elf stood, and nodded at Jace. She pointed the bident and swept up onto the grassy plain, facing the shard-crowned drones and multi-legged processors head-on.
The Eldrazi swarm would intersect with the pyromancer's flank. At a tilt of the god-weapon, a wall of water swung around her like a sea god's punch, thrashing the crawlers back over the ridge and into a ravine. Kiora pivoted on a jet of seawater to check for other stray aggressors. For the moment, the soldiers' path was clear.
"#emph[Contained] ," she thought back to Jace.
#figure(image("008_Zendikar's Last Stand/02.jpg", width: 100%), caption: [Overwhelming Denial | Art by Jama Jurabaev], supplement: none, numbering: none)
Kiora looked up at one of the landmasses that floated over the continent, an airborne island that shed a continuous waterfall of mist. A shadow passed over the landmass, and Kiora checked over her shoulder—it was cast by Kozilek, his massive bulk stealing sunlight as he approached. She understood the nature of this so-called titan now. It was no personified god, but a distortion phenomenon that was intruding from the Blind Eternities. It was nothing but a sick hoax playing out in the fabric of the world. Not a trickster, but a trick.
The luring plan was working so far, but then, that was the easy part. The mind mage and elf had the crucial job—to gather Zendikar's leylines without the use of hedrons, and to bind the titans with them so that the leylines themselves would drain the colossi away. It was makeshift magic, unrehearsed and dangerously intangible.
#figure(image("008_Zendikar's Last Stand/03.jpg", width: 100%), caption: [Kozilek, the Great Distortion | Art by Aleksi Briclot], supplement: none, numbering: none)
Even worse, the very act of pulling an Eldrazi titan fully onto the plane was unprecedented. The other Planeswalkers had no idea of the magnitude of these cosmic forces of the Multiverse, or of the damage they could cause. Even the elf, who claimed to have a personal connection with Zendikar, could not possibly grasp the impact it could have on the world. One guess stood between victory and ruin.
But Kiora would be glad to be rid of the Eldrazi forever. She would wait, and she would see.
Kiora ascended on a pillar of water to survey the battlefield. In the distance, past the ruins of Sea Gate, she could see the ragtag Zendikari armies approaching, and beyond them the two titans. And below her, on a small hill overlooking the briny valley of the Halimar Basin, stood the mind mage and the elf. The elf who believed she could be the key to everything.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Nissa was the key to everything, and Chandra knew it. The two bait armies merged, crossing directly in front of Nissa and Jace.
"#emph[Chandra, Gideon—that's far enough. Disperse the army. The titans are in position!] "
#figure(image("008_Zendikar's Last Stand/04.jpg", width: 100%), caption: [Witness the End | Art by <NAME>], supplement: none, numbering: none)
Chandra thrust her fist into the air, sending a firebolt sizzling into the sky, where it crackled and exploded high overhead. When the Zendikari saw the signal, they began to scatter. Chandra ran alongside the others, throwing more flares into the sky for good measure. Gideon caught up with her, and they ran together up the side of the basin as the ground began to glow with soothing green light.
Chandra looked behind her, up at the rocky overhang, to see Nissa scintillating with magic.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The signal flares were reflected in the crests of Kiora's waves, looking like a sea on fire. She swiveled to see the titans stepping into the valley, the meeting place, the trap. And when the elf lit up, Kiora took a breath of dust-hazed air.
Vines of bright, verdant magic became visible, crisscrossing the land from horizon to horizon. They curled and stretched and rearranged themselves, coiling in toward the elf. The ground under Nissa's feet rippled with light, and Kiora saw that same light shining from the elf's eyes.
A great wind picked up and the sky dimmed. Kiora could see the mind mage watching the pattern of leylines forming down in the valley and under Nissa's feet. She could hear whispers of the telepathic communications between them, as if she were overhearing urgently conversing ghosts. Kiora caught indistinct words were about the shape of the glyph, the pattern of leylines, an unbreakable loop, a stable pattern of intense mana—
All at once, the pattern fell into place. A tripartite glyph a hundred feet wide appeared on the floor of the valley in fierce green fire. Miles-long loops of pure mana blossomed from the glyph, lashed themselves around the titans, and pulled.
#figure(image("008_Zendikar's Last Stand/05.jpg", width: 100%), caption: [Bonds of Mortality | Art by Chris Rallis], supplement: none, numbering: none)
Kozilek and Ulamog tried to lurch away, to wrench themselves free from the land—and they did not just lurch back, Kiora noted, but #emph[up] . The entangled titans drew themselves up to their full heights, and for a long moment, as winds lashed the landscape, it looked as though they would simply pull free of the leylines. The slack in the loops of mana disappeared as they pulled higher and higher.
But then the leylines snapped taut. They held fast, straight lines anchoring the titans to Zendikar.
The Eldrazi titans' shriek was tectonic. The earth slid, ripped, and undulated. Cracks erupted in the ground and shards of broken terrain tore their way to the surface as the land bucked and heaved. The elf's spell had actually managed to make contact with the titans, and this was their reply—the kind of reply that broke worlds.
All around, Eldrazi attackers appeared, jaws clacking. Kiora swept up onto a new outcropping of land and pushed back a wave of marauding Eldrazi with her own wave of seawater. As wind whipped at her fins, she called on the mana to summon a leviathan to her side, but she could feel the land resisting her call. Almost every drop of mana was being soaked up before Kiora could draw on it.
The elf's spell held the titans in place, but at the cost of absorbing all of Zendikar's mana. Would she let the land go to ruin to trap them?
"Nissa!" shouted the mind mage over the winds. "Pull them! You have to pull them onto the glyph, to drain them!"
Kiora saw the elf straining, her arms outstretched, channeling the leylines through the spell and through herself. She swept her arms from ground to sky, and a fresh set of leylines lashed onto the titans. The land lurched with effort.
Something deep in the earth cracked, but somehow Kiora heard the sound coming from overhead.
Motion in the sky drew Kiora's attention. Around the mighty titans, the sky bulged and folded like a brewing storm. But this was not a thunderstorm—this was something else. The color of the heavens twisted from hazy blue to boiling magentas and greens. The sunlight wavered, overshadowed by a spreading, rippling, polyp-like #emph[texture] . And to Kiora's shock, she saw what was happening to the titans—
Bending, distorting, stretching.
Their heads inflated and curved into elongated necks that rainbowed across the sky.
Their faces widened, curved concave, and unfolded to the horizon and back again.
And then it began raining Eldrazi.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[This is new] , thought Chandra.
The sky of Zendikar had become the titans. Their forms had enveloped everything, a dome of bruise-colored flesh and bone sheets and void-edged shards. Rather than the titans being pulled into Zendikar, it felt as if Zendikar were now inside the titans—or that, somehow, dimensionality had inverted, and now the outside of their enormous bodies was in every direction Chandra could see.
Ulamog's upper body still rose over the battlefield, but its limbs and tentacles projected out incongruously from various points across the sky. A portion of Kozilek's crown was stretching and rotating across the coarse firmament like an insane moon. Boundaries muddled and entities merged. Otherworldly tendrils reached down out of the magenta heavens, contorting and stretching, and dripped toward the ground like funnel clouds. Eldrazi emerged and unfolded from each offshoot, dropping onto the land with either graceful landings or messy crashes.
Chandra ran into the new Eldrazi throng, slashing with her forearms and cutting a hot swath through them. Distressingly, it appeared that the mass of Eldrazi were all still gruesomely #emph[connected] to the two titans. In fact, it looked as if she was trying to cut into two enormous, cohesive, sky-filling entities, far more vast than either of the titans had been.
She could see Gideon's sural sparkling and hear him commanding the Zendikari. There were battle roars as soldiers rushed forward to push back this new force of Eldrazi, and screams as the soldiers were torn apart.
#figure(image("008_Zendikar's Last Stand/06.jpg", width: 100%), caption: [Flaying Tendrils | Art by Slawomir Maniak], supplement: none, numbering: none)
Behind her, she heard Nissa cry out.
"Nissa!" Chandra yelled on impulse. But it was drowned out by unnatural gales and the sounds of battle.
Nissa's eyes had gone blind with shimmering green, and mana spread out from her in straight lines to the sky in every direction. The leylines pulled upward on the glyph, and in the process, pulled on Nissa. Chandra saw her lift into the air briefly, dragged up toward the titan-filled sky. She fell back down onto the ground on her knees, arms shaking, teeth gritted.
"Jace," Chandra yelled, "she can't sustain this!"
"It's working!" Jace yelled. "Hold on!"
"#emph[Working?] " Chandra spat. "How can you #emph[say] that?" She blasted back a few Eldrazi intruders that were crawling toward Nissa.
The land folded violently. Scores of Zendikari fell to the ground. Chandra saw cracks open up across the valley, widening and swallowing the land, shaking the outcropping where Jace and Nissa stood. Above, something new was happening to the titans.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kiora looked up at the tendril-dangling membrane the titans had become—and she could see the cracks spreading across their forms. The glyph spell had formed a connection between the titans and Zendikar, and the leylines were slowly, gradually eroding them. They were beings of the Blind Eternities, and being dragged fully into this reality was tearing at their very existence. The titans, finally, were beginning to break.
But at the same time, the land of Zendikar was breaking as well, and far more rapidly. The air was a storm of broken gales. The sea was swirling into waterspouts. Kiora knew that the land under their feet would be the next to dissolve.
#figure(image("008_Zendikar's Last Stand/07.jpg", width: 100%), caption: [Grip of the Roil | Art by <NAME>], supplement: none, numbering: none)
Kiora gripped the bident, feeling its power grow in her hands. She sensed the sea rising, gathering, answering her call. But she could sense its depletion at the same time. Zendikar was being set against the titans in a contest of consumption—and the titans were designed to consume.
The mind mage looked at her, and she heard his words echoing in her mind. "#emph[Now, Kiora. Use your waves and clear the hordes. Give Nissa more time.] "
Kiora swung the bident this way and that, and seawater crashed back against the encroaching Eldrazi. But she saved one final spell for one final juncture. As she battled back the swarms, she watched the landmass floating above her, the same cascading island that she had seen before the spell began. As long as the land masses, those hallmarks of her world, stayed aloft, she could give the elf more time.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra's fingers felt itchy. As the land broke apart below their feet, the titans moaned and thundered above. Fissures ran through their forms like widening, jagged stripes across the sky. They didn't just look horrifying and sky-encompassing. They also looked, for the first time, #emph[vulnerable] .
She caught Gideon's eye as he ran past, slashing two Eldrazi drones into pieces. He glanced up at the sky as well. "If we could ever hurt them, now's the time," he said, and leaped up past her, toward the outcropping where Nissa stood.
Chandra's hands became fists. She had done her part as Bait, First Class. It was time to contribute something more final.
"Jace!" she shouted. "Let me take them out! Let me burn them to cinders!"
"#emph[No!] " said Jace down at her, aloud and in Chandra's head at the same time. "#emph[Remember? Any damage to the titans or to Nissa will snap the leylines and collapse the glyph spell. We'll lose them!] "
v
Chandra held out one hand, and it became white-hot fire. "Not if we make one spell count."
"#emph[I said no] ," Jace thought at her. "#emph[Just keep those Eldrazi back!] "
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
As Kiora saw the floating landmass begin to tip and sink out of the air, her heart sank with it. It tumbled down, spinning its waterfall in a spiral, and collided with the chaotic sea, breaking into an explosion of whitewater. Kiora scanned the sky, and saw that other floating landmasses were also falling all around her. They fell in slow motion, rolling in asymmetrical somersaults, ramming into the ground and blasting up cataclysmic plumes of dirt.
#figure(image("008_Zendikar's Last Stand/08.jpg", width: 100%), caption: [Looming Spires | Art by <NAME>t], supplement: none, numbering: none)
#emph[We have failed] , thought Kiora.
She could see it now. The titans were connected to the fate of Zendikar now. Under this elf's magic, the titans would only die if Zendikar did.
"Revane!" she yelled at the elf. "It's the end. Let them go!"
Nissa twitched her head blindly. The elf was still maintaining the spell, but Kiora could tell she heard her.
"#emph[What?] " said Jace. "#emph[No! Kiora, you have to keep the swarms at bay! We need to let the spell finish them!] "
"Won't work," Kiora shouted, clutching the bident and pointing it straight out to one side. "We did our best. But Zendikar will perish if they do." She pointed the tips of the bident at the sky full of titans. "They already want to leave. Let them go. We can fight them again someday!"
Nissa was shaking her head as her body stretched out with the leylines, lines of worry creasing her forehead with sweat.
Jace's cloak billowed in the whipping wind. His face was severe. "They must be destroyed—here, and now," he shouted. "Or we're just dooming every other world, risking millions of lives."
The poor mind mage didn't see it. He was willing to commit to his mistake, even if it meant all of them dying. "We're about to doom this one," Kiora said. "The world is falling apart. Soon we will, too."
"Let the plan work," Jace said firmly.
She grasped the bident, and willed the waters to come to her aid. "If you won't end this, Beleren," she said, "then I will."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra's fist was ablaze and her eyes were locked on the sky. "Jace, let me burn them!" she shrieked.
"No!" shouted Jace, whipping around to her.
Chandra saw the merfolk Kiora sweeping past on a wave of water, holding her bident weapon aloft. "We've taught them a lesson," she shouted. "They won't return. It's time to set them free."
Gideon was climbing up onto the outcropping to protect Nissa. "I'm with Chandra," he said, his voice strong over the churning winds. "We can't let them go, but we can't hold them like this. We forfeit lives every moment."
A broken landform spiraled in toward the outcropping, slamming into the basin near the glyph. The ground ruptured.
"Decide...#emph[soon] ..." Nissa managed through clenched teeth.
The merfolk Kiora was breathing heavily. "You will drop the spell, elf," she said. She raised the bident high, and Chandra saw a tower of waves thundering up from the Halimar. "You shall set them free. And if you won't do so #emph[willingly] ..."
#figure(image("008_Zendikar's Last Stand/09.jpg", width: 100%), caption: [Sweep Away | Art by <NAME>], supplement: none, numbering: none)
A wall of water three miles wide rose into the air. It swirled and twined into a single mass, a floating, shimmering shape shot through with sea plants and coral and fish. It was a seawater globe, hovering overhead. Kiora had emptied the entire Halimar Sea, and was holding it through the strength of her will. Her gaze was fixed on the outcropping above Chandra, on the source of the spell—on Nissa.
"#emph[Chandra, can you do this?] " came Jace's hurried words in her mind.
Chandra's fist glowed like a tiny sun as she looked back and forth between Nissa and the Eldrazi firmament. She wanted desperately to flood the sky with fire, to unleash her fury on the abominations that would threaten her friends. But she wasn't sure she could create such a singular blast. How could anybody be sure? "#emph[I think so!] " Chandra thought back.
"#emph[You have to be certain. Tell me now.] "
Chandra saw Nissa's face turn down to her. Somehow the elf's blind green eyes had found Chandra, and even with the chaos all around them, Nissa nodded. Somehow she knew it was possible, and in that moment, in that bond of trust, Chandra knew it too.
"#emph[I'm certain] ," Chandra thought at Jace.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kiora held the sea god's bident straight up, like a sword ready to strike.
"Time is up, Revane."
She reared back, and the water reared back with her.
And with one bodily motion, she hurled the entire sea at Nissa.
Nissa's eyes widened.
—But the sea split in two, and each half split in two, and each resulting half split and split again, and the mass of water dissolved and dispersed into mist. Water roared down, sweeping away Eldrazi creatures. Sea life splashed down, flapping.
The mind mage stood between Kiora and Nissa, his eyes glowing with power under his hood, his extended hand edged with crackling blue magic.
Kiora did nothing for one stunned second. Then she bellowed, not words but inarticulate sounds of rage.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It was now or never. Nissa was safe from Kiora's spell, but she could collapse at any moment. Either Chandra would destroy every part of the titans with a single spell, or they would lose all of Zendikar, and lose the Eldrazi to the Blind Eternities in the process.
Chandra let the fury grow. Fire crept from her fist up one arm and down the other. Her hair ignited.
She thought of how she beheld Ulamog for the first time, as she was planeswalking back to Regatha—she thought of how its image imprinted itself on her vision even after she had left the plane. She couldn't wipe it out of her mind, and couldn't rest while it was still out there. This is what the Eldrazi were—senseless, colossal horrors that made coexistence impossible. If they were released from Zendikar, they would follow Planeswalkers wherever they traveled, pursue life wherever it flourished, and end it all. Chandra knew this was what she and her friends had come to put to an end. This was their mission. It was their oath.
Her hands burned white-hot. She looked up at the glowing green vines, the leylines of mana still pulled taut, binding the titans and attaching them to this world. She knew the leylines would break when she cast her blast of pyromancy. She willed herself hotter and hotter as landmasses spiraled down to earth, as the ground broke to pieces, as the sea boiled itself away.
Chandra unleashed the spell. Fire streamed into the sky—
#figure(image("008_Zendikar's Last Stand/10.jpg", width: 100%), caption: [Fall of the Titans | Art by <NAME>], supplement: none, numbering: none)
—and instantly she knew it wasn't right.
The torrent of fire touched the contorted Eldrazi mass, but it wasn't nearly enough. Her fire could barely scratch the titans even when they were finite, discrete beings. She couldn't burn their epic entirety now, any more than she could burn an entire plane.
In the corner of her eye she saw one of the floating islands tumbling out of the sky, and she realized with a tiny part of her mind that it would barrel right into her. Simultaneously, she could see the glyph glow bright, down in the basin, as the fire streamed across the titans' bodies. It was all falling apart. The glyph would expire soon. Her fury would expire soon.
They would all die soon.
She was barely conscious of Gideon leaping from the outcropping, blocking the landmass with his own body, of a shower of pebbles raining down as it broke against him. She just concentrated on hurling as much fire out as she could, even though it wouldn't be close to enough—
Chandra felt a hand resting softly on her shoulder.
And then she felt the mana of an entire world streaming into her.
#figure(image("008_Zendikar's Last Stand/11.jpg", width: 100%), caption: [Mana Confluence | Art by Howard Lyon], supplement: none, numbering: none)
The leylines. Nissa had been the focus for all of Zendikar's fury, and now, with Nissa's touch, that fury poured into Chandra instead.
Chandra was the focus now, the nexus that connected Zendikar to the titans. She knew she couldn't hold their reins as Nissa had done. So she tried something else.
She screamed.
And in her scream, she willed all of Zendikar's fury through herself, into her spell, into her fire.
The leylines themselves caught fire, igniting like a spark hitting streams of fuel. Flames spiraled from Chandra into the streams of mana and branched out across the sky, following the paths of the leylines, enveloping the titans.
Either Chandra was still screaming, or everything else was.
The world flashed with a roar of apocalyptic orange, then went blinding white. Chandra's legs buckled, and she collapsed.
There was thunder, and a hellish blast of heat, and an awful noise of the sky ripping into pieces. As Chandra's consciousness gave out, she decided it must be the sound of the world dying.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("008_Zendikar's Last Stand/12.jpg", width: 100%), caption: [Wastes | Art by <NAME>], supplement: none, numbering: none)
Kiora couldn't see anything through the smoke. She pressed her gills shut, but she could still taste ash. Fires burned in the haze and puddles steamed. Flakes of ash fell, curling in little loops out of the gray above. She thought of the pale dust that Ulamog left behind when it consumed the land—was that what she was seeing? She wandered through the dense, opaque air in a weird silence, tripping over corpses of Eldrazi creatures and Zendikari alike.
She couldn't hope. She couldn't pain herself with wonder. She searched the grayness, touching bodies. She helped a few survivors stand on their feet.
Kiora stopped at one body. She recognized this one. It was the pyromancer, splayed out in the mud, her red hair spread over the turf. Kiora knelt down and pushed her over onto her back.
The pyromancer lay there for a moment, then suddenly curled on her side in a spasm, coughing mud. When she finally raised her head, they exchanged a look, but Kiora said nothing. Kiora reached down a hand to help her up, but when the pyromancer took it, she grimaced and grabbed at her back. Kiora released her and let her lie there.
Together they looked up through the falling ash.
They saw two forms against the sky, but they were afterimages made of smoke, like the ghosts of fireworks. Between the dissipating towers there was a crease of blue sky.
Gradually, others appeared out of the smoke. They gathered, walking, limping, trudging toward each other. Gideon and Jace. Tazri. Noyan, Drana, and Jori.
And the elf. Nissa staggered over a mound of earth and sat on the ground all at once. Her eyes looked at nothing, but Kiora saw the elf's fingers dig into a patch of bare earth, where the glyph had been burned permanently into it.
The land's crust was quiet now. Many landmasses had crashed to earth, but a few more floated silently by in the distance, ignoring gravity as they always had.
Kiora watched as the other survivors slowly realized that it was over. There was no hurrah. There was no speech. No blanket of relief or gladness settled across the crowds.
A few hands squeezed shoulders.
Some questioning looks were exchanged.
Heads were shaken, or nodded.
Bandages were produced. Healing hands touched the wounded. Impromptu search parties were organized. Rescuers gathered around sinkholes or seawater-filled trenches. A few straggling Eldrazi were discovered and dispatched.
#figure(image("008_Zendikar's Last Stand/13.jpg", width: 100%), caption: [Affa Protector | Art by Izzy], supplement: none, numbering: none)
Kiora put the bident on her back. She looked across the streaked, stained faces of the allies and turned toward the opposite horizon. She put the ruins of Sea Gate at her back and put her feet into motion—left and then right, left and then right. And she didn't stop walking for a long time.
|
|
https://github.com/yasemitee/Teoria-Informazione-Trasmissione | https://raw.githubusercontent.com/yasemitee/Teoria-Informazione-Trasmissione/main/2023-11-14.typ | typst | = Codifica di canale
Nel contesto della teoria dell'informazione, un "canale" si riferisce a un concetto fondamentale che descrive il modo in cui l'informazione viene trasmessa da una sorgente a una destinazione attraverso un mezzo fisico o un processo di comunicazione su cui è applicato un rumore. Ricordiamo l’obiettivo generale della codifica canale: vogliamo trasmettere un messaggio attraverso un canale con rumore massimizzando la quantità di informazione trasmessa per uso del canale e simultaneamente minimizzando la probabilità di errore di decodifica. Un canale è così modellato:
$ angle.l Chi, Y, p(y | x) angle.r $
Dove $Chi$ è "cosa ha ricevuto il canale" o in altre parole _l'input del canale_, $Y$ è "cosa ha trasmesso il canale" o _l'output del canale_ e $p(y | x)$ è la probabilità di ricevere (da parte del ricevente) $y in Y$ dato $x in X$ (quindi è la matrice stocastica che abbiamo definito nella prima lezione).
#v(12pt)
#figure(
image("assets/2023-11-14 modello-canale.png", width: 65%)
)
#v(12pt)
Se non viene specificato nulla, il canale a cui ci riferiamo è binario e senza memoria e dobbiamo tenere a mente che non necessariamente $X != Y$ (non è detto neanche che siano sottoinsiemi, diciamo che se non è un canale molto anomalo per lo meno sono correlati).
Un canale è *senza memoria* quando l’uscita ottenuta ad ogni uso del canale,
condizionata sull’ingresso, è indipendente dagli utilizzi passati e futuri. Ad esempio supponiamo che il canale venga usato $n$ volte per inviare un messaggio $x^n = (x_1, dots, x_n)$ ottenendo in uscita $y^n = (y_1, dots, y_n)$ Abbiamo che:
$ p(y^n | x^n) = p(y_n | y ^ (n-1), x^n) dot p(y_(n-1) | x^(n-2), x^n) times dots p(y_(n-1) | y^n-1, x^n) $
Ora se il canale è senza memoria vale che
$ p(y_n | p^(n-1), x^n) = p(y_n | x_n) $
$ p(y_(n-1) | p^(n-2), x^n) = p(y_(n-1) | x_(n-1)) $
$ dots.v $
$ p(y_1 | x^n) = p(y_1 | x_1) $
ovvero,
$ p(y^n | x^n) = product_(i=0)^n p(y_i | x_i) $
== Canale senza rumore
Un canale si dice senza rumore quando non introduce alcun rumore durante la trasmissione. In altre parole, la trasmissione di ciascun bit avviene senza errori, e il ricevitore riceve esattamente ciò che il trasmettitore ha inviato.
#v(12pt)
#figure(
image("assets/2023-11-14 canale-senza-memoria.png", width: 15%)
)
#v(12pt)
== Canale simmetrico
In un canale binario simmetrico, la probabilità di un errore di trasmissione è la stessa per entrambe le direzioni: dalla sorgente al destinatario e dal destinatario alla sorgente. Questo significa che la trasmissione errata di un bit è altrettanto probabile in entrambe le direzioni.
#v(12pt)
#figure(
image("assets/2023-11-14 canale-simmetrico.png", width: 15%)
)
#v(12pt)
== Capacità del canale
La capacità del canale $C$, è definita come il massimo dell'informazione mutua su tutte le distribuzioni di probabilità di $Chi$, ovvero
$ C = max_(p(x)) I(XX,YY) $
== Esempi
=== Capacità su un canale senza rumore
Supponiamo di voler calcolare la capacità del canale:
#v(12pt)
#figure(
image("assets/2023-11-14 canale-senza-memoria.png", width: 15%)
)
#v(12pt)
Noi sappiamo che $ 0<= I(XX,YY) := cases(
H(XX) - H(XX | YY) <= log_2 |Chi|,
H(YY) - H(YY | XX) <= log_2 |Y|
) $
$C = max_p(x) H(XX) - (H(XX | YY)=1$
$H(XX | YY) = 0$ perché sono su un canale senza rumore (Dato $YY$ conosco immediatemente $XX$).
#pagebreak()
=== Capacità su un canale rumoroso
Supponiamo di voler calcolare la capacità del canale:
#v(12pt)
#figure(
image("assets/2023-11-14 canale-rumoroso.png", width: 15%)
)
#v(12pt)
Quindi vogliamo trovare $C = max_p(x) H(XX) - (H(XX | YY)$
1)
$ H(YY | XX) = sum_x p(x) dot underbracket(H(YY | XX = x), sum_y p(YY|XX) dot log 1/p(YY | XX)) $
$ = underbrace(p(0), "probabilità \ndi spedire 0") dot H(YY | XX = 0) + p(1) dot H(YY | XX = 1) + p(2) dot H(YY | XX = 2) $
$ = (1/cancel(3) dot 3) dot cancel(3) = 1 $
$ p(0) = underbrace(1/3 dot 1/2, "probabilità di spedire 0\ne ricevere zero") + underbrace(1/3 dot 1/2,"probabilità di spedire 0\ne ricevere due") = 1/3 $
Per come è costruito il canale vediamo che $p(0) = p(1) = p(2)$
2)
$ H(YY) = (1/cancel(3) log_2 3) dot cancel(3) = log_2 3 $
*Quindi*
$C = max_p(x) underbrace(H(XX), log_2 3) - underbrace((H(XX | YY)),1) = (log_2 3) - 1 $
#pagebreak()
=== Capacità su un canale simetrico
Supponiamo di voler calcolare la capacità del canale:
#v(12pt)
#figure(
image("assets/2023-11-14 canale-simmetrico.png", width: 15%)
)
#v(12pt)
Riscriviamo
$ C = max_p(x) H(YY) - [p(XX = 0) dot H(YY | XX = 0) + p(XX = 1) dot HH(YY | XX = 1)] $
$ H(YY | XX = 0) = underbrace(p(YY= 0 | XX = 0), 1-p) dot log_2 1/p(YY=0 | XX = 0) + underbrace(p(YY = 1 | XX = 0), p) dot log_2 1/p(YY = 1 | XX=0) $
Se notiamo bene quest'ultima mi ricorda la classica bernulliana, quindi posso scrivere
$ C = max_p(x) H(YY) - H(P) $
Adesso troviamo l'entropia di $YY$
$ H(YY) = sum_(y in Y) p(YY) log_2 1/p(YY) = p(YY= 0) log_2 1/p(YY = 0) + p(YY = 1) log_2 1/p(YY = 1) $
$ p(YY = 1) = 1/2 (1-p) + 1/2 p = 1/2 $
$ p(YY = 0) = 1/2 (1-p) + 1/2 p = 1/2 $
Adesso quindi $C = 1 - H(P)$
|
|
https://github.com/Jeomhps/datify | https://raw.githubusercontent.com/Jeomhps/datify/main/src/main.typ | typst | MIT License | #import "translations.typ": day-name, month-name
#import "formats.typ": custom-date-format
|
https://github.com/Grigoriicherv/Cache-coherency | https://raw.githubusercontent.com/Grigoriicherv/Cache-coherency/main/cache-coherency.typ | typst | #import "template.typ": *
#import "@preview/codelst:2.0.0": sourcecode
#show: ams-article.with(
title: [Когеретность кэша в многопроцессорных системах],
authors: (
(
name: "<NAME>",
department: [CT M3235],
organization: [Itmo University],
location: [Russia, St. Petersburg], ),
),
abstract: [
Когда мы переходим от однопроцессорной к многопроцессорной системы возникает множество проблем, которые необходимо решать для построения качественной архитектуры и одна из них это когерентность(согласовонность) кэша. Существует множество подходов к решению этой проблемы. Мы рассмотрим два механизма когерентности кэша, следовательно два способа организации памяти(snooping и directory-based).
],
)
#let url(uri) = {
link(uri, raw(uri))
}
= Coherency
== Некоторые предостережения
Стоит понимать, что существуют модели памяти с общим кэшем. Преимущество такой организации заключается в том, что поддержка когерентности кэша не требуется, поскольку
только один кэш, и любой блок может быть кэширован только в одном месте. Недостатки такой организации заключаются в том, что процессоры и кэши должны находиться в непосредственной близости друг от друга, иначе время доступа к кэшу будет очень велико. Кроме того, при наличии нескольких банков кэш-памяти связь между процессорами и банками кэш-памяти осуществляется по принципу all-to-all, что требует больших затрат, поэтому такая организация не является масштабируемой.
Также стоит понимать, что проблемы incoherence происходят из того что существует множество акторов с доступом к кэшу и памяти. В современных системах такими участниками являются процессорные ядра, механизмы DMA и внешние устройства, которые могут читать и/или писать в кэш и память. Мы сфокусируемся на акторах, которые являются ядрами. Мы будем рассматривать упрощенную структуру памяти в которой у нас будет одноуровневый кэш и основная память.
== Проблема несогласованности
Чтобы представить проблему несогласованности, сначала представим систему с несколькими процессорами(fig 1).
#figure(
image("smp.png", width: 45%),
caption: [
SMP – симметричная многопроцессорная система
],
)
Рассмотрим следующий код, в котором два потока выполняются на двух процессорах, прибавляя значения ```c a[0]``` и ```c a[1]``` к переменной ```c sum```
```c
int sum = 0;
#pragma omp parallel for
for (int i = 0; i < 2; i++){
#pragma omp critical {
sum = sum + a[i];
}
}
print sum;
```
Предположим, что ```c a[0] = 3```, а ```c a[1] = 7```. Правильным результатом вычисления будет то, что сумма отражает сложение ```c a[0]``` и ```c a[1]``` в конце вычисления, что соответствует значению 10. В системе без кэша Tread 0 считывает из памяти начальное значение суммы, прибавляет к нему значение 3 и сохраняет его обратно в память. Tread 1 считывает из памяти значение ```c sum``` (которое теперь равно 3), прибавляет к нему 7 и возвращает в память значение 10. Когда Tread 0 считывает ```c sum``` из памяти, он считывает 10 и печатает его, что правильно.
Теперь представьте, что у каждого процессора есть кэш (write-back) (fig 1). Предположим, что изначально значение суммы в памяти равно 0. Tread 0 начинается с чтения из ячейки памяти, в которой находится переменная ```c sum```, в регистр. В результате блок памяти, содержащий ```c sum```, кэшируется Proc 0. Затем Tread 0 выполняет ```c sum + a[0]```. Результат сложения, который в данный момент все еще находится в регистре, записывается в ячейку памяти ```c sum```. Поскольку блок, содержащий сумму, кэшируется, блок кэша модифицируется и устанавливается бит dirty. В это время в основной памяти все еще хранится устаревшая копия блока, в которой значение суммы равно 0. Когда Tread 1 выполняет чтение суммы из основной памяти, он видит значение суммы равным 0. Он складывает ```c a[1]``` и сумму и сохраняет результат в кэше. Значение ```c sum``` в его кэш-копии равно 7. Наконец, когда Tread 0 печатает значение ```c sum```, он считывает его из ячейки памяти ```c sum```, и он считывает его из кэша, потому что в его кэше есть действительная копия. Он выведет "3", что неверно. Нетрудно понять, что если кэш будет write-through, то проблема останется. Просто в памяти и в кэше Tread 1 у нас будут корректные значения ```c sum```.
Как мы видим, проблема не зависит от того как мы проталкиваем значение в основную память, ведь значения в кэшах разных процессоров остаются несогласованные. Это мы и называем *cache coherence problem*.
Существует два критерия, которые вынуждают согласованность кэшей:
+ *Write propogation* -
Изменения данных в любом кэше должны быть распространены на другие копии (этой строки кэша) в соседних кэшах.
+ *Transaction serialization* - Чтение/запись в одну ячейку памяти должны восприниматься всеми процессорами в одном и том же порядке.
Существует несколько эквивалентных определений этого инварианта существования согласованности. Мы будем в основном пользоваться этим. Также мы вводим понятие coherence protocol, который будет следить за соблюдением инварианта.
== Сoherence protocol in general
В этой части мы постараемся обобщить все виды протоколов когерентности. Чтобы реализовать эти инварианты на практике, мы "присоединяем" *finite state machine (FSM)*, определяемую как контроллер когерентности, к каждой структуре хранения, включая память и каждый кэш(блок у процессора). Эти контроллеры когерентности собираются вместе, образуя распределенную систему. Контроллеры взаимодействуют друг с другом, чтобы гарантировать, что инварианты всегда сохраняются для каждого блока. Протокол когерентности определяет, как эти конечные автоматы взаимодействуют друг с другом.
#figure(
image("1.png", width: 60%),
caption: [
Coherency controller(cache controller)
],
)
Каждый контроллер когерентности управляет набором конечных автоматов, которые концептуально являются одним и тем же, но независимым автоматом для каждого блока. В зависимости от текущего состояния блока эти машины получают и обрабатывают события, такие как входящие сообщения когерентности. Контроллер когерентности реагирует на событие типа A (например, запрос на сохранение от ядра к контроллеру кэша) в блоке B, выполняя действия (например, запрашивая разрешение на чтение и запись), которые зависят как от A, так и от состояния B (например, только чтение). После выполнения этих действий контроллер имеет возможность изменить состояние B.
Вот так, например, будет выглядеть *FMS* для самого простой протокола когерентности кэша, построенный на основе write-through и используемый *snoopy mechanism* для взаимодействия с остальными котроллерами.(fig 3)
#figure(
image("2.png", width: 50%),
caption: [
FMS
],
)
Где запросы процессора к контроллеру:
+ PrRd - прочитать блок.
+ PrWr - записать блок.
Внешние запросы к контроллеру:
+ BusRd - Существует запрос на чтение блока от какого-то из процессоров.
+ BusWr - Существует запрос на запись блока от какого-то из процессоров.(В нашем случае также и запись в память)
Состояния блоков кэша:
+ V(Valid) - Значение блока такое же как и в основной памяти.
+ I(Invalid) - Обращение к этому блоку произведет cache miss.
Чтобы определить coherence protocol необходимо определить 3(Иногда вводят дополнительную кмпоненту *actions*) компоненты.
- States: Состояния блоков кэша и памяти(V, I).
- Events: Запросы, приходящие к контроллеру извне(PrRd, PrWr, BusRd, BusWr).
- Transitions: Это соответствие {State, Event} -> {State}
States относительно независимы, например два класса coherence protocols: snoopy и directory
можно описать с помощью одного набора states.
== States
=== Types states
В одноакторной системе блок кэша может находиться в одном из двух состояний: валидном или невалидном. Если необходимо различать Dirty блоки, блок кэша может иметь два действительных состояния. Dirty блоком считается тот, который был записан позже, чем любая другая копия того же блока.
Эти два или три состояния также могут использоваться системой с несколькими акторами, однако обычно мы хотим различать разные типы действительных состояний. Мы хотим закодировать четыре свойства блока кэша.
- Validity: Можно прочитать, но нельзя писать.
- Dirtiness: Блок кэша считается грязным, если его значение является самым актуальным значением, это значение отличается от значения в памяти, а контроллер кэша отвечает за обновление памяти новым значением.
- Exclusivity: Если это единственная частная кэшированная копия этого блока в системе
- Ownership: Контроллер кэша (или контроллер памяти) является владельцем блока, если он отвечает за ответы на запросы когерентности для этого блока
=== Stable states
Основные состояния можно определить буквами MSI(иногда используются O и E, но необязательно). Каждое такое состояние это комбинация типов состояний описанных выше.
- Modified: Блок valid, exclusive, owned и potentially dirty. Вы можете либо прочитать, либо записать блок. Копия блока в памяти может быть устаревшей, в кэше хранится единственная действительная копия блока, и кэш должен отвечать на запросы к блоку.
- Shared: Блок valid, но не exclusive, не dirty и не owned. В кэше хранится копия блока, доступная только для чтения. В других кэшах могут быть валидные копии блока, доступные только для чтения.
- Invalid: Блок либо отсутствует в кэше, либо он там есть, но может быть устаревшей копией, которую кэш не может прочитать или записать.
- Owned: Блок valid, owned, and potentially dirty, но не exclusive. Кэш должен отвечать на запросы к блоку и содержит его копию, доступную только для чтения. Копия блока, доступная только для чтения, может существовать в других кэшах, но им она не принадлежит. Возможно, копия блока в памяти устарела.
- Exclusive: Блок valid, exclusive, and clean. В кэше хранится копия блока, доступная только для чтения. Копия блока в памяти является самой последней копией, и ни в каких других кэшах нет действительных копий блока. Хотя существуют протоколы, в которых состояние Exclusive не рассматривается как состояние владения, для целей данного учебника мы будем считать, что блок является владельцем, когда он находится в состоянии Exclusive.
#figure(
image("moes.png", width: 50%),
caption: [
MOESI states
],
)
== Snooping and Directory-based
Сейчас дадим кртакое описание каждого из механизмов, а в дальнейшем углубимся в каждый по отдельности.
- *Snooping*: Контроллер кэша передает сообщение запроса всем другим контроллерам когерентности, чтобы начать запрос блока. Вместе контроллеры когерентности, например, отвечают на запрос данных от другого ядра, если они являются его владельцем. Способность сети межсоединений посылать широковещательные сигналы каждому ядру в регулярном порядке необходима для протоколов snooping. Большинство протоколов snooping работают в предположении, что запросы поступают в определенном порядке, например по общей проводной шине, однако возможны и более сложные сети межсоединений и гибкие последовательности.
- *Directory-based*: Контроллер кэша отправляет запрос контроллеру памяти. Каждый контроллер памяти имеет каталог, содержащий информацию о каждом блоке памяти, включая данные о текущих владельцах. Контроллер памяти определяет состояние каталога блока при получении запроса на него из дома. Например, если запрос GetS, контроллер памяти просматривает состояние каталога, чтобы определить владельца. Если память является владельцем, контроллер памяти завершает транзакцию. Если контроллер кэша является владельцем, контроллер памяти контроллер памяти направляет запрос в кэш владельца; когда кэш владельца повторно получает переданный запрос, он завершает транзакцию, отправляя ответ на данные запрашивающему.
При выборе между Snooping и Directory приходится идти на компромиссы. Хотя методы Snooping логически просты, широковещание не масштабируется до большого числа ядер. Благодаря своей одноадресной природе протоколы Directory масштабируются; тем не менее, поскольку они требуют отправки дополнительного сообщения в некоторых случаях, многие транзакции выполняются медленнее.
== Invalidate and Update
Еще один вопрос, который не зависит от механизма когерентности. Существуют два способа решения:
- Invalidate protocol: Ядро запускает транзакцию когерентности, чтобы убедиться, что копии во всех других кэшах недействительны, когда оно хочет записать в блок. Запрашивающий может записывать в блок, не беспокоясь о том, что другое ядро получит доступ к его предыдущему значению после того, как копии станут недействительными. Для того чтобы другое ядро получило блок после того, как его копия была признана недействительной, должна быть запущена новая транзакция когерентности. При этом оно получит копию от ядра, которое первоначально записало блок, поддерживая согласованность.
- Update protocol: Чтобы обновить копии в других кэшах новым значением, присвоенным блоку, ядро, которое хочет записать блок, запускает транзакцию когерентности.
И тут нам опять приходится выбирать между скоростью при чтении(Update protocol) и скорости при записи(Invalidate protocol).
Дальше мы рассмотрим несколько примеров реализации coherence protocols
= Snooping Coherence Protocols
== Write-Once protocol
Первый MESI протокол
=== States
- Invalid: Некорректное значение в кэше
- Valid: Значение когерентно. Shared, но не Modified
- Reserved: Блок является единственной копией памяти, но он по-прежнему когерентен. При замене блока не требуется обратная запись.
- Dirty: Блок - это единственная копия памяти, и она некогерентна. Эта копия была записана один или несколько раз. Это единственное состояние, которое генерирует обратную запись при замене блока в кэше.
=== Transitions
- Read hit: Информация актуальная. никаких изменений
- Read miss: Если существует другая копия блока, находящаяся в состоянии Dirty, кэш с этой копией запрещает памяти поставлять данные и поставляет сам блок, а также записывает блок обратно в основную память. Если ни один кэш не имеет копии Dirty, блок поступает из памяти. Все кэши с копией блока устанавливают свое состояние в Valid.
- Write hit: Если блок уже находится в состоянии Dirty, запись может быть выполнена локально без задержки. Если блок находится в состоянии Reserved, запись также может быть выполнена без задержки, а состояние меняется на Dirty. Если блок находится в состоянии Valid, записываемое слово записывается в основную память (т. е. получает шину, и происходит запись одного слова в резервное хранилище), а локальное состояние устанавливается в Reserved. Другие кэши с копией этого черного цвета (если таковые имеются) наблюдают за записью по шине и изменяют состояние своих копий блока на Invalid. Если блок заменяется в состоянии Reserved, его не нужно записывать обратно, поскольку копия в основной памяти является текущей.
- Write miss: В случае частичной записи строки кэша за пропуском чтения (если это необходимо для получения незаписанной части строки кэша) следует пропуск записи. В результате текущий кэш находится в состоянии Reserved, а все остальные кэши - в состоянии Invalid.
== Synapse protocol
=== States
Invalid, Valid, Dirty.
=== Transitions
- Read hit: Данные берутся из текущего кэша. В состоянии ничего не меняется.
- Read miss: Кэш, отправивший Read Miss, получает отрицательное подтверждение, если в другом кэше есть Dirty-копия. После этого владелец записывает блок обратно в основную память, одновременно устанавливая локальное состояние Invalid и сбрасывая битовую метку. Чтобы получить блок из основной памяти, запрашивающий кэш должен послать еще один запрос на пропуск. Во всех остальных случаях блок забирается прямо из основной памяти. Владелец блока, будь то память или кэш, всегда поставляет его. Загруженный блок постоянно находится в состоянии Valid.
- Write hit: Запись может начаться сразу, если блок Dirty. Поскольку сигнала о недействительности нет, если блок Valid, процесс будет таким же, как и при Write Miss (включая полную передачу данных).
- Write miss: Блок всегда берется из памяти, как и пропуск чтения; если блок был Dirty в другом кэше, владелец должен сначала записать его в память. Блок загружается в состоянии Dirty, и все кэши, содержащие копию Valid-блока, устанавливают свой статус в Invalid. Метка основной памяти для блока устанавливается так, чтобы игнорировать любые дальнейшие запросы к блоку из памяти.
== Dragon protocol
=== States
- Valid-Exclusive: Блок кэша был захвачен этим процессором и не изменен другим.
- Shared clean: Это указывает на то, что блок кэшируется более чем одним процессором, что доказывает, что текущий процессор не является последним, кто его записывал.
Протокол поддерживает состояния E и Sc раздельно, чтобы избежать операций чтения-записи в блоках кэша без общего доступа, вызывающих транзакции по шине, которые замедляют выполнение. В однопоточных приложениях такое часто случается.
- Shared dirty: Это означает, что блок присутствует в кэшах нескольких процессоров, причем текущий процессор является последним, кто его изменил. В результате процессор, используемый в данный момент, называется владельцем блока. В отличие от протоколов invalidation, блок должен быть только в процессоре, а не в основной памяти. Когда блок кэша удаляется, процессор обязан обновить основную память.
- Dirty: Только этот процесс имеет его в своей кэш-памяти и к тому же он его изменил.
- Sharedline - также необходима для указания того, доступен ли определенный блок кэша в нескольких кэшах.
=== Transitions
- Read Miss - Если в другом кэше есть копия Dirty или Shared-dirty, он предоставит блок кэша, поднимет SharedLine и состояние блока будет установлено в shared-dirty во всех кэшах. Если в другом кэше есть блок в состоянии Valid-Exclusive или shared-clean, он предоставит блок, поднимет SharedLine и состояние блока будет установлено в shared-clean во всех кэшах. Если SharedLine не был поднят, блок будет получен из памяти с состоянием Valid-Exclusive.
- Write Hit - Если блок находится в состоянии Dirty или Valid-Exclusive, запись может быть выполнена немедленно, с конечным состоянием Dirty. Если блок находился в состоянии shared-clean или shared-dirty, запись задерживается до тех пор, пока не будет получена шина и не начнется запись в основную память. Другие кэши наблюдают за записью на шину и обновляют свою копию блока.
- Write Miss - Как и при пропуске чтения, блок берется из кэша, если он Dirty или Dirty, и из памяти в противном случае. Другие кэши с копиями устанавливают свое локальное состояние в shared-clean. При загрузке блока запрашивающий кэш устанавливает локальное состояние в Dirty, если SharedLine не поднят. Если SharedLine поднят, запрашивающий кэш устанавливает состояние shared-dirty и выполняет запись на шину для трансляции нового содержимого.
= Directory-based
== States
- Shared (S) - Один(или больше) процессор имеет блок у себя в кэше при этом согласован с памятью и с другимим кэшами.
- Uncached (U) - Некто не кэшировал этот блок
- Modified (M) - Только один процессор кэшировал этот блок. Также этот процесс писал в него, следовательно этот блок не согласован с памятью
== Transition
#table(
columns: (auto, auto, auto, auto),
inset: 3pt,
align: center,
table.header(
[Initial state], [Request], [Response/ Action], [New state],
),
"U",
"Read Miss или Write Miss",
"Возьми блок прямо из памяти.
Отправь блок из памяти тому, кто его запросил.",
"M",
"M",
"Read Miss",
"Отправьте запрос в кэш, содержащий измененный блок, на предоставление данных в запрашивающий кэш",
"S",
"",
"Write Miss",
"Отправьте запрос в кэш, содержащий измененный блок, чтобы аннулировать его",
"-",
"S",
"Read Miss",
"Ответьте запрашивающему кэшу блок памяти",
"-",
"",
"Write Miss",
"Ответьте запрашивающему кэшу блок памяти.
Отправьте запрос всем кэшам, которые совместно используют этот блок, чтобы аннулировать его.",
"M",
"",
"Write Hit",
" Отправьте запрос всем кэшам, которые совместно используют этот блок, чтобы аннулировать его.
Ответьте кэшу, что блок может быть модифицирован.",
"M",
)
== Implementations
=== Full bit vector format
Этот метод хранит битовое поле для каждого процессора в узле каталога. Количество процессоров определяет, насколько велики накладные расходы на хранение.
#figure(
image("full.jpg", width: 60%),
caption: [
Full bit vector format
],
)
=== Limited pointer format
Чтобы сократить накладные расходы на хранение, этот метод хранит информацию о каталоге для ограниченного числа блоков в каталоге.
=== Number-balanced binary tree format
В этом формате каталог децентрализован и распределен между кэшами, разделяющими блок памяти. Различные кэши, разделяющие блок памяти, располагаются в виде двоичного дерева. Кэш, который первым обращается к блоку памяти, является корневым узлом.
#pagebreak()
#bibliography("bib.yml", full: true)
|
|
https://github.com/astrale-sharp/typst-assignement-template | https://raw.githubusercontent.com/astrale-sharp/typst-assignement-template/main/README.md | markdown | MIT License | # typst-assignement-template
Hi, this is a simple template, you should check out the pdf to see if it interests you.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0180.typ | typst | Apache License 2.0 | #let data = (
("LATIN SMALL LETTER B WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER B WITH HOOK", "Lu", 0),
("LATIN CAPITAL LETTER B WITH TOPBAR", "Lu", 0),
("LATIN SMALL LETTER B WITH TOPBAR", "Ll", 0),
("LATIN CAPITAL LETTER TONE SIX", "Lu", 0),
("LATIN SMALL LETTER TONE SIX", "Ll", 0),
("LATIN CAPITAL LETTER OPEN O", "Lu", 0),
("LATIN CAPITAL LETTER C WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER C WITH HOOK", "Ll", 0),
("LATIN CAPITAL LETTER AFRICAN D", "Lu", 0),
("LATIN CAPITAL LETTER D WITH HOOK", "Lu", 0),
("LATIN CAPITAL LETTER D WITH TOPBAR", "Lu", 0),
("LATIN SMALL LETTER D WITH TOPBAR", "Ll", 0),
("LATIN SMALL LETTER TURNED DELTA", "Ll", 0),
("LATIN CAPITAL LETTER REVERSED E", "Lu", 0),
("LATIN CAPITAL LETTER SCHWA", "Lu", 0),
("LATIN CAPITAL LETTER OPEN E", "Lu", 0),
("LATIN CAPITAL LETTER F WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER F WITH HOOK", "Ll", 0),
("LATIN CAPITAL LETTER G WITH HOOK", "Lu", 0),
("LATIN CAPITAL LETTER GAMMA", "Lu", 0),
("LATIN SMALL LETTER HV", "Ll", 0),
("LATIN CAPITAL LETTER IOTA", "Lu", 0),
("LATIN CAPITAL LETTER I WITH STROKE", "Lu", 0),
("LATIN CAPITAL LETTER K WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER K WITH HOOK", "Ll", 0),
("LATIN SMALL LETTER L WITH BAR", "Ll", 0),
("LATIN SMALL LETTER LAMBDA WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER TURNED M", "Lu", 0),
("LATIN CAPITAL LETTER N WITH LEFT HOOK", "Lu", 0),
("LATIN SMALL LETTER N WITH LONG RIGHT LEG", "Ll", 0),
("LATIN CAPITAL LETTER O WITH MIDDLE TILDE", "Lu", 0),
("LATIN CAPITAL LETTER O WITH HORN", "Lu", 0),
("LATIN SMALL LETTER O WITH HORN", "Ll", 0),
("LATIN CAPITAL LETTER OI", "Lu", 0),
("LATIN SMALL LETTER OI", "Ll", 0),
("LATIN CAPITAL LETTER P WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER P WITH HOOK", "Ll", 0),
("LATIN LETTER YR", "Lu", 0),
("LATIN CAPITAL LETTER TONE TWO", "Lu", 0),
("LATIN SMALL LETTER TONE TWO", "Ll", 0),
("LATIN CAPITAL LETTER ESH", "Lu", 0),
("LATIN LETTER REVERSED ESH LOOP", "Ll", 0),
("LATIN SMALL LETTER T WITH PALATAL HOOK", "Ll", 0),
("LATIN CAPITAL LETTER T WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER T WITH HOOK", "Ll", 0),
("LATIN CAPITAL LETTER T WITH RETROFLEX HOOK", "Lu", 0),
("LATIN CAPITAL LETTER U WITH HORN", "Lu", 0),
("LATIN SMALL LETTER U WITH HORN", "Ll", 0),
("LATIN CAPITAL LETTER UPSILON", "Lu", 0),
("LATIN CAPITAL LETTER V WITH HOOK", "Lu", 0),
("LATIN CAPITAL LETTER Y WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER Y WITH HOOK", "Ll", 0),
("LATIN CAPITAL LETTER Z WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER Z WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER EZH", "Lu", 0),
("LATIN CAPITAL LETTER EZH REVERSED", "Lu", 0),
("LATIN SMALL LETTER EZH REVERSED", "Ll", 0),
("LATIN SMALL LETTER EZH WITH TAIL", "Ll", 0),
("LATIN LETTER TWO WITH STROKE", "Lo", 0),
("LATIN CAPITAL LETTER TONE FIVE", "Lu", 0),
("LATIN SMALL LETTER TONE FIVE", "Ll", 0),
("LATIN LETTER INVERTED GLOTTAL STOP WITH STROKE", "Ll", 0),
("LATIN LETTER WYNN", "Ll", 0),
("LATIN LETTER DENTAL CLICK", "Lo", 0),
("LATIN LETTER LATERAL CLICK", "Lo", 0),
("LATIN LETTER ALVEOLAR CLICK", "Lo", 0),
("LATIN LETTER RETROFLEX CLICK", "Lo", 0),
("LATIN CAPITAL LETTER DZ WITH CARON", "Lu", 0),
("LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON", "Lt", 0),
("LATIN SMALL LETTER DZ WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER LJ", "Lu", 0),
("LATIN CAPITAL LETTER L WITH SMALL LETTER J", "Lt", 0),
("LATIN SMALL LETTER LJ", "Ll", 0),
("LATIN CAPITAL LETTER NJ", "Lu", 0),
("LATIN CAPITAL LETTER N WITH SMALL LETTER J", "Lt", 0),
("LATIN SMALL LETTER NJ", "Ll", 0),
("LATIN CAPITAL LETTER A WITH CARON", "Lu", 0),
("LATIN SMALL LETTER A WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER I WITH CARON", "Lu", 0),
("LATIN SMALL LETTER I WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER O WITH CARON", "Lu", 0),
("LATIN SMALL LETTER O WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER U WITH CARON", "Lu", 0),
("LATIN SMALL LETTER U WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON", "Lu", 0),
("LATIN SMALL LETTER U WITH DIAERESIS AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE", "Lu", 0),
("LATIN SMALL LETTER U WITH DIAERESIS AND ACUTE", "Ll", 0),
("LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON", "Lu", 0),
("LATIN SMALL LETTER U WITH DIAERESIS AND CARON", "Ll", 0),
("LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE", "Lu", 0),
("LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE", "Ll", 0),
("LATIN SMALL LETTER TURNED E", "Ll", 0),
("LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON", "Lu", 0),
("LATIN SMALL LETTER A WITH DIAERESIS AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON", "Lu", 0),
("LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER AE WITH MACRON", "Lu", 0),
("LATIN SMALL LETTER AE WITH MACRON", "Ll", 0),
("LATIN CAPITAL LETTER G WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER G WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER G WITH CARON", "Lu", 0),
("LATIN SMALL LETTER G WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER K WITH CARON", "Lu", 0),
("LATIN SMALL LETTER K WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER O WITH OGONEK", "Lu", 0),
("LATIN SMALL LETTER O WITH OGONEK", "Ll", 0),
("LATIN CAPITAL LETTER O WITH OGONEK AND MACRON", "Lu", 0),
("LATIN SMALL LETTER O WITH OGONEK AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER EZH WITH CARON", "Lu", 0),
("LATIN SMALL LETTER EZH WITH CARON", "Ll", 0),
("LATIN SMALL LETTER J WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER DZ", "Lu", 0),
("LATIN CAPITAL LETTER D WITH SMALL LETTER Z", "Lt", 0),
("LATIN SMALL LETTER DZ", "Ll", 0),
("LATIN CAPITAL LETTER G WITH ACUTE", "Lu", 0),
("LATIN SMALL LETTER G WITH ACUTE", "Ll", 0),
("LATIN CAPITAL LETTER HWAIR", "Lu", 0),
("LATIN CAPITAL LETTER WYNN", "Lu", 0),
("LATIN CAPITAL LETTER N WITH GRAVE", "Lu", 0),
("LATIN SMALL LETTER N WITH GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE", "Lu", 0),
("LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE", "Ll", 0),
("LATIN CAPITAL LETTER AE WITH ACUTE", "Lu", 0),
("LATIN SMALL LETTER AE WITH ACUTE", "Ll", 0),
("LATIN CAPITAL LETTER O WITH STROKE AND ACUTE", "Lu", 0),
("LATIN SMALL LETTER O WITH STROKE AND ACUTE", "Ll", 0),
("LATIN CAPITAL LETTER A WITH DOUBLE GRAVE", "Lu", 0),
("LATIN SMALL LETTER A WITH DOUBLE GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER A WITH INVERTED BREVE", "Lu", 0),
("LATIN SMALL LETTER A WITH INVERTED BREVE", "Ll", 0),
("LATIN CAPITAL LETTER E WITH DOUBLE GRAVE", "Lu", 0),
("LATIN SMALL LETTER E WITH DOUBLE GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER E WITH INVERTED BREVE", "Lu", 0),
("LATIN SMALL LETTER E WITH INVERTED BREVE", "Ll", 0),
("LATIN CAPITAL LETTER I WITH DOUBLE GRAVE", "Lu", 0),
("LATIN SMALL LETTER I WITH DOUBLE GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER I WITH INVERTED BREVE", "Lu", 0),
("LATIN SMALL LETTER I WITH INVERTED BREVE", "Ll", 0),
("LATIN CAPITAL LETTER O WITH DOUBLE GRAVE", "Lu", 0),
("LATIN SMALL LETTER O WITH DOUBLE GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER O WITH INVERTED BREVE", "Lu", 0),
("LATIN SMALL LETTER O WITH INVERTED BREVE", "Ll", 0),
("LATIN CAPITAL LETTER R WITH DOUBLE GRAVE", "Lu", 0),
("LATIN SMALL LETTER R WITH DOUBLE GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER R WITH INVERTED BREVE", "Lu", 0),
("LATIN SMALL LETTER R WITH INVERTED BREVE", "Ll", 0),
("LATIN CAPITAL LETTER U WITH DOUBLE GRAVE", "Lu", 0),
("LATIN SMALL LETTER U WITH DOUBLE GRAVE", "Ll", 0),
("LATIN CAPITAL LETTER U WITH INVERTED BREVE", "Lu", 0),
("LATIN SMALL LETTER U WITH INVERTED BREVE", "Ll", 0),
("LATIN CAPITAL LETTER S WITH COMMA BELOW", "Lu", 0),
("LATIN SMALL LETTER S WITH COMMA BELOW", "Ll", 0),
("LATIN CAPITAL LETTER T WITH COMMA BELOW", "Lu", 0),
("LATIN SMALL LETTER T WITH COMMA BELOW", "Ll", 0),
("LATIN CAPITAL LETTER YOGH", "Lu", 0),
("LATIN SMALL LETTER YOGH", "Ll", 0),
("LATIN CAPITAL LETTER H WITH CARON", "Lu", 0),
("LATIN SMALL LETTER H WITH CARON", "Ll", 0),
("LATIN CAPITAL LETTER N WITH LONG RIGHT LEG", "Lu", 0),
("LATIN SMALL LETTER D WITH CURL", "Ll", 0),
("LATIN CAPITAL LETTER OU", "Lu", 0),
("LATIN SMALL LETTER OU", "Ll", 0),
("LATIN CAPITAL LETTER Z WITH HOOK", "Lu", 0),
("LATIN SMALL LETTER Z WITH HOOK", "Ll", 0),
("LATIN CAPITAL LETTER A WITH DOT ABOVE", "Lu", 0),
("LATIN SMALL LETTER A WITH DOT ABOVE", "Ll", 0),
("LATIN CAPITAL LETTER E WITH CEDILLA", "Lu", 0),
("LATIN SMALL LETTER E WITH CEDILLA", "Ll", 0),
("LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON", "Lu", 0),
("LATIN SMALL LETTER O WITH DIAERESIS AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER O WITH TILDE AND MACRON", "Lu", 0),
("LATIN SMALL LETTER O WITH TILDE AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER O WITH DOT ABOVE", "Lu", 0),
("LATIN SMALL LETTER O WITH DOT ABOVE", "Ll", 0),
("LATIN CAPITAL LETTER O WITH DOT ABOVE AND MACRON", "Lu", 0),
("LATIN SMALL LETTER O WITH DOT ABOVE AND MACRON", "Ll", 0),
("LATIN CAPITAL LETTER Y WITH MACRON", "Lu", 0),
("LATIN SMALL LETTER Y WITH MACRON", "Ll", 0),
("LATIN SMALL LETTER L WITH CURL", "Ll", 0),
("LATIN SMALL LETTER N WITH CURL", "Ll", 0),
("LATIN SMALL LETTER T WITH CURL", "Ll", 0),
("LATIN SMALL LETTER DOTLESS J", "Ll", 0),
("LATIN SMALL LETTER DB DIGRAPH", "Ll", 0),
("LATIN SMALL LETTER QP DIGRAPH", "Ll", 0),
("LATIN CAPITAL LETTER A WITH STROKE", "Lu", 0),
("LATIN CAPITAL LETTER C WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER C WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER L WITH BAR", "Lu", 0),
("LATIN CAPITAL LETTER T WITH DIAGONAL STROKE", "Lu", 0),
("LATIN SMALL LETTER S WITH SWASH TAIL", "Ll", 0),
("LATIN SMALL LETTER Z WITH SWASH TAIL", "Ll", 0),
("LATIN CAPITAL LETTER GLOTTAL STOP", "Lu", 0),
("LATIN SMALL LETTER GLOTTAL STOP", "Ll", 0),
("LATIN CAPITAL LETTER B WITH STROKE", "Lu", 0),
("LATIN CAPITAL LETTER U BAR", "Lu", 0),
("LATIN CAPITAL LETTER TURNED V", "Lu", 0),
("LATIN CAPITAL LETTER E WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER E WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER J WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER J WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL", "Lu", 0),
("LATIN SMALL LETTER Q WITH HOOK TAIL", "Ll", 0),
("LATIN CAPITAL LETTER R WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER R WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER Y WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER Y WITH STROKE", "Ll", 0),
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-02.typ | typst | Other | // Test full removal.
#show heading: none
Where is
= There are no headings around here!
my heading?
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/1597-cite-footnote_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(height: 60pt)
#lorem(4)
#footnote[@netwok]
#show bibliography: none
#bibliography("/assets/files/works.bib")
|
https://github.com/yochem/apa-typst | https://raw.githubusercontent.com/yochem/apa-typst/main/examples/multi-author-shared-affiliations.typ | typst | #import "../template.typ": apa7
#show: apa7.with(
title: "Example of APA7 Document in Typst",
authors: (
"<NAME>",
"<NAME>"
),
affiliations: (
"College of Nursing, Michigan State University",
),
)
#lorem(40)
|
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "helper.typ": *
#heading(level: 2, "Díla")
Následuje seznam 22 knih, které jsem si vybral já#footnote[Prvních 20 je vypracovaných mnou, dvě navíc Marianem kvůli rozdílům v našich výběrech.] a které jsou podrobně zpracované dále. Pokud tě zajímá spíš rychlý přehled, podívej se na #link("https://knih.chamik.eu/tags/#maturita", "knih.chamik.eu") a hledej štítek `maturita`. Celý seznam knížek kánonu najdeš na #link("https://www.gjp-me.cz/maturity/", "gjp-me.cz/maturity").
V seznamu je potřeba mít alespoň dvě díla prózy, #highlight[poezie] a #highlight("dramatu", fill: green). Lze mít nejvíce dvě díla od stejného autora.
*Světová a česká literatura do konce 19. století* (3 knihy)
1. Kulička -- _<NAME>_
2. #highlight[Havran] -- _<NAME>_
3. #highlight("Romeo a Julie", fill: green) -- _<NAME>_
*Světová literatura 20. a 21. století* (5 knih)
4. 451° Fahrenheita -- _<NAME>_
5. Stařec a moře -- _<NAME>_
6. Proměna -- _Kafka Franz_
7. Farma zvířat -- _Orwell George_
8. Malý princ -- _<NAME>_
*Česká literatura 20. a 21. století* (5 knih)
9. #highlight("České nebe", fill: green) -- _<NAME>_
10. #highlight("Bílá nemoc", fill: green) -- _Čapek Karel_
11. #highlight("R. U. R.", fill: green) -- _Čapek Karel_
12. Krysař -- _<NAME>_
13. #highlight[Těžká hodina] -- _<NAME>_
*Ostatní* (7 knih)
14. #highlight("Čekání na Godota", fill: green) -- <NAME>
15. #highlight[Kytice z pověstí národních] -- _<NAME>_
16. Audience -- _<NAME>_
17. Hana -- _<NAME>_
18. <NAME> -- _<NAME>_
19. Edison -- _<NAME>_
20. Na západní frontě klid -- _<NAME>_
#hrule()
21. <NAME> -- _<NAME>_
22. Báječná léta pod psa -- _<NAME>_
#pagebreak()
// Světová a česká literatura do konce 19. století
#include("/cj-dila/1-kulicka.typ")
#include("/cj-autori/maupassant.typ")
#include("/cj-dila/2-havran.typ")
#include("/cj-autori/poe.typ")
#include("/cj-dila/3-romeo-a-julie.typ")
#include("/cj-autori/shakespeare.typ")
// Světová literatura 20. a 21. století
#include("/cj-dila/4-451-stupnu-fahrenheita.typ")
#include("/cj-autori/bradbury.typ")
#include("/cj-dila/5-starec-a-more.typ")
#include("/cj-autori/hemingway.typ")
#include("/cj-dila/6-promena.typ")
#include("/cj-autori/kafka.typ")
#include("/cj-dila/7-farma-zvirat.typ")
#include("/cj-autori/orwell.typ")
#include("/cj-dila/8-maly-princ.typ")
#include("/cj-autori/exupery.typ")
// Česká literatura 20. a 21. století
#include("/cj-dila/9-ceske-nebe.typ")
#include("/cj-autori/sverak-smoljak.typ")
#include("/cj-dila/10-bila-nemoc.typ")
#include("/cj-dila/11-rur.typ")
#include("/cj-autori/capek.typ")
#include("/cj-dila/12-krysar.typ")
#include("/cj-autori/dyk.typ")
#include("/cj-dila/13-tezka-hodina.typ")
#include("/cj-autori/wolker.typ")
// Ostatní
#include("/cj-dila/14-cekani-na-godota.typ")
#include("/cj-autori/beckett.typ")
#include("/cj-dila/15-kytice.typ")
#include("/cj-dila/16-audience.typ")
#include("/cj-autori/havel.typ")
#include("/cj-dila/17-hana.typ")
#include("/cj-autori/mornstajnova.typ")
#include("/cj-dila/18-lovci-hlav.typ")
#include("/cj-autori/nesbo.typ")
#include("/cj-dila/19-edison.typ")
#include("/cj-autori/nezval.typ")
#include("/cj-dila/20-na-zapadni-fronte-klid.typ")
#include("/cj-autori/remarque.typ")
#include("/cj-dila/21-petr-a-lucie.typ")
#include("/cj-autori/rolland.typ")
#include("/cj-dila/22-bajecna-leta.typ")
#include("/cj-autori/viewegh.typ")
// Konec děl
#include "/cj-pojmy.typ"
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/dynamic/other.md | markdown | ---
sidebar_position: 6
---
# Other Animations
Touying also provides `touying-reducer`, which adds `pause` and `meanwhile` animations to cetz and fletcher.
## Simple Animations
Here's an example:
```typst
#import "@preview/touying:0.2.1": *
#import "@preview/cetz:0.2.1"
#import "@preview/fletcher:0.4.1" as fletcher: node, edge
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))
#let fletcher-diagram = touying-reducer.with(reduce: (arr, ..args) => fletcher.diagram(..args, ..arr))
#let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: self => self.info.institution)
#let (init, slide) = utils.methods(s)
#show: init
// cetz animation
#slide[
Cetz in Touying:
#cetz-canvas({
import cetz.draw: *
rect((0,0), (5,5))
(pause,)
rect((0,0), (1,1))
rect((1,1), (2,2))
rect((2,2), (3,3))
(pause,)
line((0,0), (2.5, 2.5), name: "line")
})
]
// fletcher animation
#slide[
Fletcher in Touying:
#fletcher-diagram(
node-stroke: .1em,
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
spacing: 4em,
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
node((0,0), `reading`, radius: 2em),
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
pause,
edge(`read()`, "-|>"),
node((1,0), `eof`, radius: 2em),
pause,
edge(`close()`, "-|>"),
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
)
]
```

## only and uncover
In fact, we can also use `only` and `uncover` within cetz, just requiring a bit of skill:
```typst
#slide(repeat: 3, self => [
#let (uncover, only) = utils.methods(self)
Cetz in Touying in subslide #self.subslide:
#cetz.canvas({
import cetz.draw: *
let self = (self.methods.update-cover)(self: self, hide)
let (uncover,) = utils.methods(self)
rect((0,0), (5,5))
uncover("2-3", {
rect((0,0), (1,1))
rect((1,1), (2,2))
rect((2,2), (3,3))
})
only(3, line((0,0), (2.5, 2.5), name: "line"))
})
])
``` |
|
https://github.com/usami-k/technote | https://raw.githubusercontent.com/usami-k/technote/main/2024/swift-testing/swift-testing.typ | typst | Creative Commons Attribution 4.0 International | #import "@preview/touying:0.5.2": *
#import themes.metropolis: *
#show: metropolis-theme.with(
aspect-ratio: "16-9",
footer: utils.display-current-heading(level: 1),
config-info(
title: [XCTestからSwift Testingへ],
author: [宇佐見公輔],
date: [2024-09-25],
institution: [株式会社ゆめみ],
logo: [#image("images/Profile_NFT.jpeg", height: 35%)],
),
)
#set text(font: "Explex35", size: 26pt)
#show math.equation: set text(font: "STIX Two Math")
#show raw: set text(font: "0xProto")
#show link: it => underline(text(blue, it))
#title-slide()
== 自己紹介
- 宇佐見公輔
- 株式会社ゆめみ
- iOSテックリード
- iOSDC Japan 2024
- パンフレット記事 / ポスターセッション
= Swift Testingとは
== Swift Testingとは
- Swift用の単体テストフレームワーク
- 従来のXCTestに比べて、Swiftの機能をより活用
- Swift公式のGitHubリポジトリで公開されている
- https://github.com/swiftlang/swift-testing
- Xcode 16に統合された
- XcodeのUIと連携する
== XCTestとSwift Testing
- XCTest
- 従来からの単体テストフレームワーク
- Objective-C時代から存在、Swiftにも適合
- https://github.com/swiftlang/swift-corelibs-xctest
- XCTestとSwift Testingは同じプロジェクトで混在可能
- そのため、少しずつ移行していくことが可能
= Swift Testingの基本
== テスト関数定義:XCTest
```swift
import XCTest
class FoodTruckTests: XCTestCase {
func testEngineWorks() {
// ...
}
}
```
- `XCTestCase` のサブクラス内で定義する必要
- メソッド名を `test` 始まりで命名する必要
== テスト関数定義:Swift Testing
```swift
import Testing
struct FoodTruckTests {
@Test
func engineWorks() {
// ...
}
}
```
- テスト関数はどこで定義してもよい
- `@Test` 属性をつければメソッド名は自由
== テストの実装
```swift
// XCTest
func testEngineWorks() throws {
XCTAssertNotNil(engine.parts.first)
XCTAssertGreaterThan(engine.batteryLevel, 0)
XCTAssertTrue(engine.isRunning)
}
```
```swift
// Swift Testing
@Test func engineWorks() throws {
try #require(engine.parts.first != nil)
#expect(engine.batteryLevel > 0)
#expect(engine.isRunning)
}
```
== Optional値のUnwrap
```swift
// XCTest
func testEngineWorks() throws {
let part = try XCTUnwrap(engine.parts.first)
}
```
```swift
// Swift Testing
@Test func engineWorks() throws {
let part = try #require(engine.parts.first)
}
```
== テスト実行時のsetup/teardown
```swift
// XCTest
class FoodTruckTests: XCTestCase {
override func setUp() async throws {
// ...
}
}
```
```swift
// Swift Testing
final class FoodTruckTests {
init() async throws {
// ...
}
}
```
== 変換ツール
- XCTestのコードをSwift Testingに変換するツール
- https://github.com/giginet/swift-testing-revolutionary
= Swift Testingの機能
== パラメータを変えてテスト
```swift
enum Food {
case burger, iceCream, burrito, noodleBowl, kebab
}
@Test(arguments: [
Food.burger, .iceCream, .burrito, .noodleBowl, .kebab
])
func foodAvailable(_ food: Food) async throws {
let foodTruck = FoodTruck(selling: food)
#expect(await foodTruck.cook(food))
}
```
== 複数のパラメータ
```swift
@Test(arguments: zip(Food.allCases, 1 ... 100))
func makeLargeOrder(of food: Food, count: Int) async throws {
let foodTruck = FoodTruck(selling: food)
#expect(await foodTruck.cook(food, quantity: count))
}
```
== テスト実行制御
```swift
@Test(.enabled(if: FoodTruck.sells(.arepas)))
func arepasAreTasty() {
// ...
}
```
```swift
@Test(.timeLimit(.seconds(30))
func serveLargeOrder() {
// ...
}
```
== アノテーション
```swift
@Test func grillWorks() async {
withKnownIssue("Grill is out of fuel") {
try FoodTruck.shared.grill.start()
}
}
```
= 非同期処理のテスト
== 非同期処理のテスト:XCTest
```swift
func testTruckEvents() async {
let soldFood = expectation(description: "…")
FoodTruck.shared.eventHandler = { event in
soldFood.fulfill()
}
await Customer().buy(.soup)
await fulfillment(of: [soldFood])
}
```
`expectation` を使う。`fulfill()` が呼ばれたら成功。
== 非同期処理のテスト:Swift Testing
```swift
@Test func truckEvents() async {
await confirmation("…") { soldFood in
FoodTruck.shared.eventHandler = { event in
soldFood()
}
await Customer().buy(.soup)
}
}
```
`confirmation` を使う。confirmed が呼ばれたら成功。
== 注意点
- XCTestの `expectation` では `await fulfillment()` で完了待ちをしていた。
- Swift Testingの `confirmation` は完了待ちをしない。ブロックを抜けるまでに confirmed メソッドが呼ばれないと失敗扱い。
この点では、不便になっているようにも見えるが・・・
== 解決策(1)
Swift Concurrencyの `withCheckedContinuation` を使う。
```swift
@Test func truckEvents() async {
await confirmation("…") { soldFood in
await withCheckedContinuation { continuation in
FoodTruck.shared.eventHandler = { event in
soldFood()
continuation.resume()
}
await Customer().buy(.soup)
}
}
}
```
== 解決策(2)
pointfreeco/swift-concurrency-extras の `megaYield` を使う。
```swift
@Test func truckEvents() async {
await confirmation("…") { soldFood in
FoodTruck.shared.eventHandler = { event in
soldFood()
}
await Customer().buy(.soup)
await Task.megaYield()
}
}
```
= まとめ
== XCTestからSwift Testingへ
- XCTestから段階的に移行できる
- 機械的に移行できる部分も多い
- パラメータテストが便利
- 非同期処理のテストは少し変わっているので注意
|
https://github.com/ntjess/typst-tada | https://raw.githubusercontent.com/ntjess/typst-tada/main/src/helpers.typ | typst | The Unlicense | #let keep-keys(dict, keys: (), reorder: false) = {
let out = (:)
if not reorder {
// Keep original insertion order
keys = dict.keys().filter(key => key in keys)
}
for key in keys.filter(key => key in dict) {
out.insert(key, dict.at(key))
}
out
}
#let is-numeric-type(typ) = {
typ in (int, float)
}
#let unique-record-keys(rows) = {
rows.map(row => row.keys()).sum(default: ()).dedup()
}
#let is-internal-field(key) = {
key.starts-with("__")
}
#let is-external-field(key) = not is-internal-field(key)
#let remove-internal-fields(data) = {
let out = (:)
for key in data.keys().filter(is-external-field) {
out.insert(key, data.at(key))
}
out
}
#let dict-from-pairs(pairs) = {
let out = (:)
for (key, value) in pairs {
out.insert(key, value)
}
out
}
#let default-dict(keys, value: none) = {
dict-from-pairs(keys.map(key => (key, value)))
}
#let merge-nested-dicts(a, b, recurse: false) = {
if recurse {
panic("Recursive merging not implemented yet")
}
let merged = (:)
for (key, val) in a {
if type(val) == dictionary and type(b.at(key, default: none)) == dictionary {
val += b.at(key)
} else {
val = b.at(key, default: val)
}
merged.insert(key, val)
}
for key in b.keys().filter(key => key not in a) {
merged.insert(key, b.at(key))
}
merged
}
#let transpose-values(values) = {
let out = ()
for (ii, row) in values.enumerate() {
for (jj, value) in row.enumerate() {
if ii == 0 {
out.push(())
}
out.at(jj).push(value)
}
}
out
}
#let assert-is-type(value, allowed-type, value-name) = {
let value-type = type(value)
assert(
value-type == allowed-type,
message: "`" + value-name + "` must be type " + repr(allowed-type) + ", got: " + value-type
)
}
#let assert-list-of-type(values, allowed-type, value-name) = {
let iterator = if type(values) == dictionary {
values
} else if type(values) == array {
values.enumerate()
} else {
panic("Expected a list or dictionary for " + value-name + ", got: " + type(values))
}
for (index, value) in iterator {
assert-is-type(value, allowed-type, value-name + ".at(" + repr(index) + ")")
}
}
#let assert-rectangular-matrix(values) = {
assert-is-type(values, array, "values")
if values.len() == 0 {
return
}
assert-list-of-type(values, array, "values")
let row-lengths = values.map(row => row.len())
assert(
row-lengths.dedup().len() == 1,
message: "Expected a rectangular 2D matrix, got lengths: " + repr(row-lengths)
)
}
#let eval-str-or-function(
func-or-str,
mode: "markup",
scope: (:),
default-if-auto: (arg) => arg,
positional: (),
keyword: (:),
) = {
if type(positional) != array {
positional = (positional, )
}
if func-or-str == auto {
func-or-str = default-if-auto
}
let typ = type(func-or-str)
if typ == function {
return func-or-str(..positional, ..keyword)
}
if typ == content and func-or-str.has("text") {
func-or-str = func-or-str.text
} else if typ == content {
return func-or-str
}
if type(func-or-str) != str {
panic("Expected a function, string, or raw content, got " + typ + ": " + repr(func-or-str))
}
return eval(func-or-str, mode: mode, scope: scope)
} |
https://github.com/GZTimeWalker/GZ-Typst-Templates | https://raw.githubusercontent.com/GZTimeWalker/GZ-Typst-Templates/main/templates/report.typ | typst | MIT License | #import "shared.typ": *
#let report(
title: "实验报告",
subtitle: "Lab 0: 环境准备",
name: "张三",
stdid: "11223344",
classid: "计科一班",
major: "计算机科学与技术",
school: "计算机学院",
time: "2022~2023 学年第二学期",
banner: none + "",
body,
) = {
set document(title: title)
show: shared
let fieldname(name) = [
#set align(right + horizon)
#set text(font: fonts.serif)
#name
]
let fieldvalue(value) = [
#set align(left + horizon)
#set text(font: fonts.serif)
#value
]
align(center)[
#if (banner == none) {
v(200pt)
} else {
image(banner, height: 200pt, width: 95%, fit: "contain")
}
#linebreak()
#v(50pt, weak: true)
#block(text(weight: "semibold", 30pt, title))
#v(50pt, weak: true)
#block(text(weight: "medium", 24pt, subtitle))
#v(140pt, weak: true)
#set text(14.5pt)
#grid(
columns: (200pt, 240pt),
row-gutter: 1em,
fieldname(text("姓") + h(2em) + text("名:") + h(1em)),
fieldvalue(name),
fieldname(text("学") + h(2em) + text("号:") + h(1em)),
fieldvalue(stdid),
fieldname(text("教学班号:") + h(1em)),
fieldvalue(classid),
fieldname(text("专") + h(2em) + text("业:") + h(1em)),
fieldvalue(major),
fieldname(text("院") + h(2em) + text("系:") + h(1em)),
fieldvalue(school),
)
#v(40pt)
#set text(13pt)
#text(time)
#pagebreak()
]
set align(left + top)
set par(justify: true, first-line-indent: 2em, leading: line_height)
body
}
#let title(content: "") = align(center)[
#set text(26pt, weight: "bold")
#v(2em)
#content
#v(1.625em)
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-17.typ | typst | Other | // Error: 2-30 array index out of bounds (index: 12, len: 10)
#range(10).slice(9, count: 3)
|
https://github.com/qujihan/toydb-book | https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter6.typ | typst | #import "../typst-book-template/book.typ": *
#let path-prefix = figure-root-path + "src/pics/"
= 附录
#show heading.where(level: 2):it=>{
pagebreak(weak: true)
it
}
#include "chapter6/bitcask.typ"
#include "chapter6/isolation.typ" |
|
https://github.com/remigerme/typst-polytechnique | https://raw.githubusercontent.com/remigerme/typst-polytechnique/main/outline.typ | typst | MIT License | /***********************/
/* TEMPLATE DEFINITION */
/***********************/
#let apply(doc) = {
show outline: o => {
set par(first-line-indent: 0pt)
o
}
// Level 1 headings
show outline.entry.where(level : 1): i => {
strong(i)
}
// Don't forget to return doc cause
// we're in a template
doc
}
/********************/
/* TESTING TEMPLATE */
/********************/
#show: apply
#set heading(numbering: "1.1")
#outline()
= My first section
== A sub-section
#heading(level: 2, numbering: none)[Sub-section without numbering]
== Another sub-section
= Last one
|
https://github.com/Q4kK/resume | https://raw.githubusercontent.com/Q4kK/resume/master/template.typ | typst | #let entry(title, subtitle, body, details) = [
#pad(x: 0pt, top: 4pt, heading(level: 2, title))
#pad(x: 0pt, top: 0pt, bottom: 6pt, heading(level: 3, subtitle))
#body
#text(fill: gray, details)
]
#let bio(about, hobbies, volunteer) = [
#pad(x: 0pt, top: 0pt, bottom: 2pt, about)
#pad(x: 0pt, top: 0pt, bottom: 2pt, hobbies)
#volunteer
]
#let code_entry(title, body) = [
#pad(x: 0pt, top: 2pt, heading(level: 3, title))
#pad(bottom: 6pt, body)
]
#let proj(title, body) = [
#pad(x: 0pt, top: 4pt, bottom: 2pt, heading(level: 2, title))
#text(fill: black, body)
]
#let resume(accent_color: rgb("05f589"),heading_color: rgb("05f589"), margin: 100pt, aside: [], body) = {
set page(margin: 0pt)
set text(size: 12pt)
set block(above: 0pt, below: 0pt)
set par(justify: true)
show heading: set text(fill: heading_color.darken(50%))
{
show heading.where(level: 1): set text(size: 35pt)
show heading.where(level: 2): set text(size: 18pt)
}
grid(
columns: (2fr, 1fr),
column-gutter: 0.4 * margin,
block(spacing: 10pt, outset: 0pt, inset: (top: 0.4 * margin, right: 0pt, rest: margin), width: 100%, {
set block(above: 10pt)
show heading.where(level: 1): it => style(s => block([
#text(size: 18pt, upper(it))
#place(top + right, dy: 7pt, dx: 10pt + 1000%, line(stroke: accent_color, length: 1000%))
]))
body
}),
box(
fill: accent_color.lighten(40%),
outset: 0pt,
inset: (0.4 * margin),
height: 100%,
width: 100%,
{
set block(above: 20pt)
show heading: it => align(right, upper(it))
set list(marker: "")
show list: it => {
set par(justify: true)
align(right, it)
}
aside
}
),
)
}
|
|
https://github.com/chubetho/Bachelor_Thesis | https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/templates/confirmation.typ | typst | #heading(
level: 1,
numbering: none,
"Zustimmung zur Plagiatsüberprüfung",
)
#[
#set text(lang: "de")
Hiermit willige ich ein, dass zum Zwecke der Überprüfung auf Plagiate meine vorgelegte Arbeit in digitaler Form an PlagScan (www.plagscan.com) übermittelt und diese vorübergehend (max. 5 Jahre) in der von PlagScan geführten Datenbank gespeichert wird sowie persönliche Daten, die Teil dieser Arbeit sind, dort hinterlegt werden.
Die Einwilligung ist freiwillig. Ohne diese Einwilligung kann unter Entfernung aller persönlichen Angaben und Wahrung der urheberrechtlichen Vorgaben die Plagiatsüberprüfung nicht verhindert werden. Die Einwilligung zur Speicherung und Verwendung der persönlichen Daten kann jederzeit durch Erklärung gegenüber der Fakultät widerrufen werden.
#v(6em)
#align(right)[
#line(length: 50%)
Würzburg, am 13. September 2024 #h(1.25em)
]
]
#pagebreak(weak: true) |
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/复变函数/作业/hw8.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec, seqLimit, seqLimitn
#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: note.with(
title: "作业8",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
withHeadingNumbering: false
)
#set heading(numbering: none)
(应交时间为5月9日)
= p111
== 7
若存在 $s$ 使得:
$
lim_(z -> a) abs(z-a)^s abs(f(z)) = 0
$
进而:
$
lim_(z -> a) abs(z-a)^([s] + 1) abs(f(z)) = lim_(z -> a) abs(z-a)^([s] - s + 1) abs(z-a)^s abs(f(z)) = 0
$
表明 $a$ 是 $(z-a)^([s]) f(z)$ 的可去奇点,进而是 $f$ 的极点或可去奇点\
因此,考虑 $f$ 的 Laurent 展开式:
$
f(z) = sum_(n = -infinity)^(infinity) a_n (z-a)^n
$
其负项仅有有限性(可能没有),可设:
$
f(z) = sum_(n = -N)^(infinity) a_n (z-a)^n
$
其中 $a_(-N) != 0$,如此显然有:
$
forall s < -N, lim_(z -> a) abs(z-a)^s abs(f(z)) = 0\
forall s > -N, lim_(z -> a) abs(z-a)^s abs(f(z)) = infinity
$
同时,若存在 $s$ 使得:
$
lim_(z -> a) abs(z-a)^s abs(f(z)) = infinity
$
- 此时 $a$ 不可能是 $f$ 零点的聚点,否则也是 $(z-a)^s f(z)$ 零点的聚点,与极限条件显然矛盾
- 因此不妨取一个 $a$ 邻域其中无 $f$ 的零点,不难发现 $a$ 成为 $1/(f(z))$ 的可去奇点或极点,由上面的结论将存在 $m in ZZ$ 使得:
$
forall s < -m, lim_(z -> a) abs(z-a)^s abs(1/(f(z))) = 0\
forall s > -m, lim_(z -> a) abs(z-a)^s abs(1/(f(z))) = infinity
$
表明可取得 $s$ 使得 $lim_(z -> a) abs(z-a)^(1/s) abs(1/(f(z))) = infinity, lim_(z -> a) abs(z-a)^s abs(f(z)) = 0$,回到之前情形
== 9
7 已经证明若两条件有一个成立,则 $a$ 不是本性奇点。
反之,若两条件都不成立,显然 $a$ 不是极点或可去零点(否则存在 $m in ZZ$ 使得 $lim_(z -> a) abs(z-a)^m abs(f(z)) = 0$),因此是极点
== 13
=== (a)
若 $infinity$ 是可去零点,则有 $lim_(z -> 0) f(1/z)$ 存在(有限),也即 $lim_(z -> infinity) f(z)$ 存在,这使得整函数有界,当然只能是常数
== (b)
设 $f$ 在 $CC$ 上有幂级数展开:
$
f(z) = sum_(n = 0)^(infinity) a_n z^n
$
则:
$
f(1/z) = sum_(n = 0)^(infinity) a_n z^(-n)
$
由 $0$ 是 $f(1/z)$ 极点,上式仅有有限项,进而 $f$ 是多项式,次数也是容易验证的
== (c)
无妨设有理函数 $P / Q$ 在 $G$ 上无奇点(否则扩大 $G$ 将 $Q$ 的有限个零点排除即可),前面已经说明若 $infinity$ 是可去奇点,则 $lim_(z -> infinity) f(z)$ 存在,表明 $P, Q$ 具有相同的次数。
反之,若 $P, Q$ 具有相同次数,则 $lim_(z -> infinity) f(z)$ 存在,继而 $lim_(z -> 0) f(1/z)$ 存在,这使得 $infinity$ 是可去奇点
== (d)
极点成立当且仅当存在(最小的) $m in ZZ^+$ 使得:
$
lim_(z -> 0) z^m f(1/z) "存在"
$
当且仅当:
$
lim_(z -> infinity) f(z)/z^m "存在"
$
而 $f(z)/z^m$ 还是有理函数,利用之前结论可得 $P, z^m Q$ 具有相同次数,即 $P$ 的次数比 $Q$ 多 $m$
== 15
无妨设 $omega = 0$,如若不然将有存在 $epsilon, delta$ 使得:
$
abs(f(B(0, delta) - {0})) > epsilon
$
不妨在 $B(0, delta) - {0}$ 上考虑 $1/(f(z))$,注意到 $1/f$ 在其上没有极点,而 $a_n$ 都是它的可去奇点。设:
$
g(z) = cases(
0\, z = a_n,
1/(f(z))\, z != a_n
)
$
则 $g$ 是 $B(0, delta) - {0}$ 上的解析函数,$0$ 成为 $g$ 的孤立奇点,同时也是零点的聚点
- 若 $0$ 是极点或可去奇点,则它是 $B(0, delta)$ 上亚纯函数,由非零亚纯函数零点无聚点知 $g$ 恒为零,这是荒谬的!
- 因此 $0$ 是本性奇点,由 Casorati-Weierstrass 定理知 $g(B(0, delta) - {0})$ 在 $CC$ 中稠密,然而假设给出:
$
abs(f(B(0, delta) - {0})) > epsilon => abs(1/(f(B(0, delta) - {0}))) < 1/epsilon\
=> abs(g(B(0, delta) - {0})) < 1/epsilon
$
这是荒谬的!
证毕
= p121
== (a)
$
z^2/(z^4 + z^2 + 1) = (z^2(z^2 - 1))/(z^6 - 1)
$
因此分别设:
$
a_1 = e^(i (pi)/3)\
a_2 = e^(i (2 pi)/3)\
a_3 = e^(i (4 pi)/3)\
a_4 = e^(i (5 pi)/3)
$
这是上面被积函数的四个(一重)极点,其中 $a_1, a_2$ 位于上半平面。\
考虑路径 $-R -> R arrowCir -R$ (圆弧经过上半逆时针)并设 $R$ 足够大使得 $a_1, a_2$ 在区域内部,将有:
$
integral_(-R -> R)^() z^2/(z^4 + z^2 + 1) dif z + integral_(R arrowCir -R)^() z^2/(z^4 + z^2 + 1) dif z = 2 pi i (Res(f, a_1) + Res(f, a_2))
$
#let ei3(x) = $ei((ignoreOne(#x) pi)/3)$
分别计算:
-
$
Res(f, a_1) &= lim_(z -> a_1) (z - a_1)z^2/(z^4 + z^2 + 1)\
&= lim_(z -> a_1) (z - a_1)z^2/((z - a_1)(z - a_2)(z - a_3)(z - a_4))\
&= a_1^2/((a_1 - a_2)(a_1 - a_3)(a_1 - a_4))\
&= ei3(2)/ ((ei3(1) - ei3(2))(ei3(1) - ei3(4))(ei3(1) - ei3(5)))\
&= 1/ ((ei3(5) - 1)(ei3(5) - ei3(2))(ei3(5) - ei3(3)))\
&= 1/ ((ei3(4) + 1)(ei3(5) - ei3(2)))\
&= 1/ (-1 -1 + ei3(5) - ei3(2))\
&= 1/ (-2 + 1 - sqrt(3) i)\
&= 1/ (-1 - sqrt(3)i)\
&= 1/2 (1 - sqrt(3)i)
$
-
$
Res(f, a_2) &= a_2^2/((a_2 - a_1)(a_2 - a_3)(a_2 - a_4))\
&= overline(a_1^2/((-a_1 + a_2)(-a_1 + a_4)(-a_1 + a_3)))\
&= -1/2 (1 + sqrt(3)i)
$
-
#let eiBt(x) = $eiB(ignoreOne(#x) theta)$
$
integral_(R arrowCir -R)^() z^2/(z^4 + z^2 + 1) dif z &= integral_(R arrowCir -R)^() (R^2 eiBt(1))/(R^4 eiBt(4 ) + R^2 eiBt(2 ) + 1) dif R eiBt(1)\
&= i integral_(0)^(pi) (R^3 eiBt(1))/(R^4 eiBt(4 ) + R^2 eiBt(2 ) + 1) dif theta\
&= i 1/R integral_(0)^(pi) ( eiBt(1))/( eiBt(4 ) + 1/R^2 eiBt(2 ) + 1/R^4) dif theta\
$<inte>
其中:
$
abs(( eiBt(1))/( eiBt(4 ) + 1/R^2 eiBt(2 ) + 1/R^4)) = 1/abs(eiBt(4 ) + 1/R^2 eiBt(2 ) + 1/R^4) <= 1/(1 - 1/R^2 abs(eiBt(2 ) + 1/R^2)) <= 2 (R "充分大时")
$
因此@inte 部分极限为零
综上:
$
lim_(R -> +infinity) integral_(-R)^(R) z^2/(z^4 + z^2 + 1) dif z = 2 pi i(- sqrt(3) i) = 2 sqrt(3) pi
$
从而:
$
integral_0^R z^2/(z^4 + z^2 + 1) dif z = sqrt(3) pi
$
== (c)
令 $z = eiBt(1)$,则 $cos theta = (z + 1/z)/2, cos 2 theta = (z^2 + 1/z^2)/2$,有:
$
(cos 2 theta)/(1 - 2 a cos theta + a^2) = (z^2 + 1/z^2)/(2 - 2 a (z + 1/z) + 2 a^2) = (z^4 + 1)/(-2 a z^3 + (2 + 2 a^2)z^2 - 2 a z)\
= -1/(2 z) (z^4 + 1)/(a z^2 - (1 + a^2) z + a)\
= -1/(2) (z^4 + 1)/(z (z - a)(a z - 1))\
$
同时:
$
integral_(0)^(pi) (cos 2 theta)/(1 - 2 a cos theta + a^2) dif theta\
= integral_(0)^(-pi) (cos 2 theta)/(1 - 2 a cos theta + a^2) dif (-theta)\
= integral_(-pi)^(0) (cos 2 theta)/(1 - 2 a cos theta + a^2) dif theta\
$
因此:
$
integral_(0)^(pi) (cos 2 theta)/(1 - 2 a cos theta + a^2) dif theta = 1/2 integral_(-pi)^(pi) (cos 2 theta)/(1 - 2 a cos theta + a^2) dif theta\
= 1/2 integral_(diff B(0, 1)) -1/(2) (z^4 + 1)/(z (z - a)(a z - 1)) dif theta\
= -1/4 integral_(diff B(0, 1)) (z^4 + 1)/(z^2 (z - a)(a z - 1)) eiBt(1) dif theta\
= 1/4 i integral_(diff B(0, 1)) (z^4 + 1)/(z^2 (z - a)(a z - 1)) dif eiBt(1)\
= 1/4 i integral_(diff B(0, 1)) (z^4 + 1)/(z^2 (z - a)(a z - 1)) dif z\
= 1/4 i dot 2 pi i( Res(f, 0) + Res(f, a))\
$
分别计算:
-
$
Res(f, 0) = Res(1/z^2 (z^4 + 1)/((z - a)(a z - 1)), 0) = ((z^4 + 1)/((z - a)(a z - 1)))'|_(z = 0)\
= (- (-1 - a^2))/a^2 = ( a^2 + 1)/a^2
$
-
$
Res(f, a) = (z^4 + 1)/(z^2 (a z - 1))|_(z = a) = (a^4 + 1)/(a^2 (a^2 - 1))
$
因此:
$
&1/4 i dot 2 pi i( Res(f, 0) + Res(f, a)) \
&= - 1/2 pi ((a^2 + 1)/a^2 + (a^4 + 1)/(a^2 (a^2 - 1)))\
&= - 1/2 pi ( (2 a^4 )/(a^2 (a^2 - 1)))\
&= - 1/2 pi (2 a^2 )/ (a^2 - 1)\
&= ( a^2 )/ (1 - a^2) pi \
$
== 2
=== (a)
只需验证 $integral_(-infinity)^(infinity) 1/(x^2 + a^2)^2 dif x = pi/(2 a^3)$\
为此,设 $f(z) = 1/(z^2 + a^2)^2$,考虑路径 $-R -> R arrowCir -R$ (圆弧经过上半逆时针)并设 $R$ 足够大使得 $ a i$ 在区域内部,将有:
#let fi = $1/(z^2 + a^2)^2$
$
2pi i(Res(f , a i) ) =\
integral_(-R -> R arrowCir -R)^() fi dif z\
= integral_(-R)^(R) fi dif z + integral_(R arrowCir -R)^() fi dif z\
$
分别计算:
-
$
Res(f, a i) = Res(1/(z - a i)^2 1/(z + a i)^2 , a i) = (1/(z + a i)^2)' |_(z = a i) \
= -2/(z + a i)^3 |_(z = a i) = -2/(2 a i)^3 = 1/(4 a^3 i)
$
-
$
integral_(R arrowCir -R)^() fi dif z\
= integral_(0)^(pi) fi dif R eiBt(1)\
= integral_(0)^(pi) 1/(R^2 eiBt(2) + a^2)^2 dif R eiBt(1)\
= i integral_(0)^(pi) R/(R^2 eiBt(2) + a^2)^2 dif theta\
$
而:
$
norm(R/(R^2 eiBt(2) + a^2)^2) = 1/norm(R^(3/2) eiBt(2) + a^2 R^(-1/2)) <= 1/(R^(3/2) - a^2 R^(-1/2))
$
当 $R$ 充分大时上式为零
综上有:
$
integral_(-infinity)^(infinity) 1/(x^2 + a^2)^2 dif x = 2pi i dot (- 1/(4 a^3 i)) = pi/(2 a^3)
$
=== (c)
#let eiBx(a) = $eiB(ignoreOne(#a) x)$
#let fx = $(eiBx(a))/(1+x^2)^2$
积分化为:
$
1/2 integral_(-infinity)^(infinity) fx dif x
$
设 $f(x) = fx$,考虑路径 $-R -> R arrowCir -R$ (圆弧经过上半逆时针)并设 $R$ 足够大使得 $i$ 在区域内部,将有:
$
2 pi i Res(f, i) = integral_(-R -> R arrowCir -R)^() fx dif z\
= integral_(-R)^(R) fx dif z + integral_(R arrowCir -R)^() fx dif z
$
分别计算:
-
$
Res(f, i) = Res(1/(x - i)^2 (eiBx(a))/(x + i)^2, i)\
= ((eiBx(a))/(x + i)^2)'|_(x = i)\
= (a i eiBx(a) (x+i)^2 - 2 (x + i)eiBx(a))/(x+i)^4 |_(x = i)\
= -i/4 e^(-a) (a + 1)
$
-
$
integral_(R arrowCir -R)^() fx dif z = integral_(0)^(pi) (eiBx(a) )/(1 + x^2)^2 dif R eiBt(1)\
= integral_(0)^(pi) (eiB(a R eiBt(1)) )/(1 + (R eiBt(1))^2)^2 dif R eiBt(1)\
= integral_(0)^(pi) R e^(i theta) (e^(a R (cos theta i - sin theta)) )/(1 + (R eiBt(1))^2)^2 dif theta\
$
而:
$
abs(R e^(i theta) (e^(a R (cos theta i - sin theta)))/(1 + (R eiBt(1))^2)^2)\
<= R (e^( - a R sin theta))/(R^2 - 1)^2\
<= 2 R (e^( - a R sin theta))/R^4 (R "充分大时")\
= 2 (e^( - a R sin theta))/R^3
$
之前计算 $(sin x) /x$ 证明了 $integral_(0)^(pi) e^( - a R sin theta) dif theta$ 当 $R$ 充分大时趋于零,继而该项趋于零
=== (h)
$
integral_(0)^(2pi) log sin^2 2 theta dif theta = 2 integral_(0)^(2 pi) log abs(sin 2 theta) dif theta = 8 integral_(0)^(pi/2) log abs(sin 2 theta) dif theta = 4 integral_(0)^(pi) log sin x dif x
$
为了计算上面的积分,做代换:
$
integral_(0)^(pi) log sin x dif x = integral_(0)^(pi) log abs((eiB(x) - eiB(-x))/i) dif x - pi ln 2 \
= integral_(0)^(pi) log abs(eiB(2 x) - 1) dif x - pi ln 2\
= Re integral_(0)^(pi) log (eiB(2 x) - 1) dif x - pi ln 2
$
注意到:
$
integral_(0)^(pi) log (eiB(2 x) - 1) dif x = 1/(2 i) integral_(0)^(pi) (log (eiB(2 x) - 1))/(eiB(2 x)) dif eiB(2 x)\
= 1/(2 i) integral_(diff B(0, 1))^() (log (z - 1))/(z) dif z
$
注意到被积函数实际上无极点,$0$ 是可去奇点,因此上面的积分为零,表明 $integral_(0)^(pi) log sin x dif x = - pi ln 2$ 证毕
== 3
显然 $e^(1/z)$ 在除 $0$ 外的点都解析,因此取得充分大的开区域将 $gamma$ 包含在内,留数定理给出:
$
n(gamma\; 0) Res(e^(1/z), 0) =1/(2 pi i) integral_(gamma)^() e^(1/z) dif z
$
显然有:
$
e^(1/z) = sum_(n = 0)^(infinity) 1/(n!) z^(-n)\
$
因此由留数定义知 $Res(e^(1/z), 0) = 1$,从而上面的积分的所有可能值为 $2 k pi i, forall k in ZZ$
= 126
== 2
设 $g(z) = (f(z))/z^n - 1$,则 $0 < abs(f(z)) < 2, forall abs(z) = 1$ 且 $g$ 仅有一个 $n$ 阶极点 $0$,由幅角原理:
$
1/(2 pi i) integral_(diff B(0, 1))^() g'/g dif z = k - n
$
其中 $k$ 是记重数的 $B(0, 1)$ 内 $g$ 的零点个数
== 4
在 $f$ 的通常点结论是显然的,设 $z$ 是极点,有 $tilde(f) = infinity$。任取 $infinity$ 在 $C_infinity$ 上的一个开邻域 $A_infinity$,设其在 $CC$ 上的投影为 $A = CC - B$,其中 $B$ 是有界闭集。
为了证明在 $z$ 处的连续性,只需找到 $z$ 的一个邻域 $Z$ 使得 $tilde(f)(Z) subset A_infinity$,由于 $z$ 是孤立奇点,不妨在某个小邻域内讨论,这个小邻域内无其他奇点。如此,上式事实上等价于:
$
f(Z - {z}) subset A = CC - B
$
由 $B$ 有界及 $lim_(x -> z) f(x) = infinity$ 上式当然是成立的
== 9
设 $f(z) = e^(-z) + z - lambda$
- 先设 $z$ 是实数,求导得:
$
f' = - e^(-z) + 1
$
因此 $f$ 在 $(-infinity, 0)$ 上递减,在 $(0, +infinity)$ 上递增,在 $0$ 处取得最小值 $1 - lambda < 0$,因此在 $RR$ 右半粥当然恰有一解,并且是一重根
- 其次,只需证明只有这一个根。事实上,设 $z$ 是根,则:
$
lambda = z + e^(-z)\
abs(z - lambda) = abs(e^(-z)) = e^(-Re z) < 1\
$
取 $gamma = diff B(lambda, 1)$,将有:
$
abs(f(z) - (z - lambda)) = e^(-Re z) < 1\
abs(f(z)) + abs(z - lambda) = 1 + abs(f(z)) > 1
$
由 Rouche's theorem 得 $f$ 与 $z - lambda$ 有相同的零点个数,后者只有一个根,因此 $f$ 也只有一个根
由于 $f$ 在 $RR$ 上最小值为 $1- lambda$ 在 $0$ 处取得,因此 $lambda -> 0$ 时(只是曲线的上下平移)当然有这个根也趋于 $0$
|
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/meta-documentation/cheatsheet.typ | typst |
= How to Use Typst to Write These Documents
Cheatsheet:
General Typst Docs: https://typst.app/docs/
Commands specific to the Protohaven class handout environment:
`#warning([Some text.])`
`#safety_hazard_box([Some text.])`
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/syntax-03.typ | typst | Other | // Error: 1:3 expected dollar sign
$a
|
https://github.com/SergeyGorchakov/russian-phd-thesis-template-typst | https://raw.githubusercontent.com/SergeyGorchakov/russian-phd-thesis-template-typst/main/common/symbols.typ | typst | MIT License | #import "@preview/unify:0.5.0": *
#let symbols-entries = {(
(key: "pi",short: [$pi$],long: [Число $pi$]),
(key: "a",short: [$a$],long: [Число $a$], desc: [#unit("cm/s")]),
)} |
https://github.com/Lucas-Wye/tech-note | https://raw.githubusercontent.com/Lucas-Wye/tech-note/main/src/vi_vim.typ | typst | = Vi Editor
#label("vi-editor")
- 所有的 Unix Like 系统都会内建 Vi 文书编辑器,其他的文书编辑器则不一定会存在。但是目前我们使用比较多的是 Vim 编辑器。
- Vim 具有程序编辑的能力,可以主动的以字体颜色辨别语法的正确性,方便程序设计。
- Vim是从 Vi 发展出来的一个文本编辑器。代码补完、编译及错误跳转等方便编程的功能特别丰富,在程序员中被广泛使用。简单的来说, Vi 是老式的字处理器,不过功能已经很齐全了,但是还是有可以进步的地方。
== File Operation
#label("file-operation")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[:wq], [存盘退出],
[:q!], [退出不保存],
[:saveas \[path/to/file\]], [另存为 \[path/to/file\]],
[:qa!], [强行退出所有的正在编辑的文件],
[:bn 和 :bp], [切换下一个或上一个文件],
[:w !sudo tee %], [以sudo保存正在编辑的文件],
[:n], [move to next file],
[:rew], [回到第一个文件],
[:edit \[Filename\]], [打开新文件],
)
== Cursor movement
#label("cursor-movement")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[hjkl], [move],
[/\[PATTERN\]], [搜索],
[?\[PATTERN\]], [搜索],
[/\\\<\[PATTERN\]\\\>], [精确匹配搜索],
[%], [匹配括号移动],
[f], [搜索并移动到某个字符前],
[t], [到某个字符前的第一个字符],
[:N], [到第N行],
[gg], [到第一行],
[G], [到最后一行],
[\[n\]G], [go to last line or line \[n\]],
[w/W], [到下一个单词的开头],
[e/E], [到下一个单词的结尾],
[b], [到上一个单词的开头],
[0], [beginning of current line],
[\$], [end of current line],
[^], [beginning of text on current line],
[\[CTRL\] F/B], [move screen],
[\[CTRL\] D/U], [move half screen],
[zz], [将当前行放置于屏幕中间],
[zt], [将当前行放置于屏幕顶端],
[zb], [将当前行放置于屏幕底端],
)
== Inserting text
#label("inserting-text")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[i], [前插入],
[a], [后插入],
[I], [insert text at beginning of line],
[A], [append text at end of line],
[o], [在当前行后插入一个新行],
[O], [在当前行前插入一个新行],
)
== Deleting text
#label("deleting-text")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[d], [删除],
[D], [删除当前行光标后所有内容],
[x], [删当前光标的字符],
[X], [删当前光标前的字符],
)
== Changing commands
#label("changing-commands")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[u], [undo],
[\[CTRL\] r], [redo],
[.], [repeat last operation],
[p], [后粘贴],
[P], [前粘贴],
[y], [复制],
[s/S], [substitute],
[~], [change case of character],
[J], [join current line and next line],
)
== Split windows
#label("split-windows")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[:split/vsplit], [创建分屏],
[\[CTRL\] w + 方向], [切换分屏],
)
== Command line mode
#label("command-line-mode")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[:\[cmd\]], [暂时退出命令行执行cmd],
[:set all], [display all option settings],
[:\[Addr/%\]s/old expr/new string/\[g\]],
[替换当前行/Addr/%(文件内所有)的old expr为new string,\[g\]全局替换,否则只替换第一个 |],
[\[CTRL\] p/n], [自动补齐],
[\[CTRL\] +/-], [改变尺寸],
[v], [visual模式],
[V], [v-line模式],
[\[CTRL\] v], [v-block模式],
[:normal \[Command\]], [可视化模式下执行命令],
[qa -> q -> \@a], [录制宏],
[ci + ”], [删除引号之中的内容],
[tabe], [打开新的标签页],
[+/-tabnext], [切换标签页],
[:tab sball], [打开所有的buffer到独立的一个标签],
[\'.], [定位到上次修改的那一行行首],
[\`.], [定位到上次修改的位置],
[可视模式 -> o], [切换选区扩展的方向,向上或者向下],
[gf], [打开当前光标显示的那个文件],
[gt/gT], [切换标签页],
[:r!\[cmd\]], [执行命令,并将结果复制到当前光标的下一行],
[:%!\[cmd\]], [将buffer内容重定向到命令的标准输入,并用输出替换buffer内容],
)
== Regular expression
#label("regular-expression")
#table(
columns: 2,
align: (col, row) => (auto, auto).at(col),
inset: 6pt,
[?], [match any single character at the indicated position],
[\*], [match any string of zero or more characters],
[\[abc…\]], [match any of the enclosed characters],
[\[a-e\]], [match any characters in the range a,b,c,d,e],
[\[!def\]], [match any characters not one of the enclosed characters, sh/bash],
[{abc,bcd,cde}], [match any set of characters separated by comma (,) (no spaces), bash/csh],
[~], [home directory of the current user, bash/csh],
[~ user], [home directory of the specified user, bash/csh],
[.], [match any single character except newline],
[\[^abc\]], [match any character NOT in the enclosed set],
[^exp], [regular expression must start at the beginning of the line],
[exp\$], [regular expression must end at the end of the line],
[\\], [treat the next character literally 转义字符],
[xy\*z], [xy开头,z结尾的字符串],
)
== Plug
#label("plug")
https://github.com/junegunn/vim-plug
== .vimrc
#label("vimrc")
#link("https://github.com/Lucas-Wye/rc/blob/master/sys/vimrc")[vimrc]
== #link("https://neovim.io")[NeoVim]
#label("neovim")
使用Vim配置文件
```sh
ln -s ~/.vim ~/.config/nvim
ln -s ~/.vimrc ~/.config/nvim/init.vim
```
== More
#label("more")
#link("https://www.runoob.com/linux/linux-vim.html")[Vi/Vim教程] \
#link("https://coolshell.cn/articles/5426.html")[简明 VIM 练级攻略]
|
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DSA/chapters/3栈和队列.typ | typst |
#import "../template.typ": *
#import "@preview/pinit:0.1.4": *
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge
#import "/book.typ": book-page
#show: book-page.with(title: "栈和队列 | DSA")
= 栈和队列
<栈和队列>
== 栈
#definition[
*栈*:栈(Stack)是限定仅在表的一端进行插入或删除操作的线性表。通常称插入删除的一端为栈顶(top),另一端称为栈底(bottom)。
]
*特点*:后进先出(LIFO)
=== 基本操作
- `InitStack(&S)`:构造一个空栈S
- `DestroyStack(&S)`:销毁栈S
- `ClearStack(&S)`:清空栈S
- `StackEmpty(S)`:判断栈S是否为空
- `StackLength(S)`:返回栈S的长度
- `GetTop(S, &e)`:取栈顶元素
- `Push(&S, e)`:入栈
- `Pop(&S, &e)`:出栈
- `StackTraverse(S, visit())`:遍历栈
#note_block[
若 `S.data[0]` 为栈底元素,那么:
1. 当插入一个元素时,top如何变化
- `S.top++`
2. 当删除一个元素时,top如何变化
- `S.top--`
3. 如何判断栈满的情况?
- `S.top == StackSize`
4. 如何判断空栈的情况?
- `S.top == -1`
5. Top的初始值是多少?
- `S.top = -1`
若以 `S.data[Stacksize-1]` 为栈底呢?
1. 初始值:`S.top = StackSize`
2. 入栈:`S.top--`
3. 出栈:`S.top++`
4. 栈满:`S.top == -1`
5. 空栈:`S.top == StackSize`
]
=== 表达式求解
=== 递归
#definition[
*递归*:一个对象如果部分地由它自身来定义(或描述),则称其为递归。
]
== 队列
#definition[
*队列*:队列(queue)是限定只能在表的一端进行插入,在表的另一端进行删除的线性表。
]
*特点*:先进先出(FIFO)
// 顺序队列
// 固定的存储空间
// 方便访问队列内部元素
// 链式队列
// 可以满足队列大小无法估计的情况
// 访问队列内部元素不方便
=== 顺序队列与链式队列的比较
#grid(
columns: (1fr, 1fr),
)[
*顺序队列*
- 存储空间固定
- 访问队列内部元素方便
][
*链式队列*
- 存储空间不固定
- 访问队列内部元素不方便
]
循环队列判断队列满的方法:`Q.rear == (Q.front + 1) % MaxSize`
#image("../assets/2024-06-27-15-18-16.png")
=== 应用
- 只要满足先来先服务特性的应用均可采用队列作为其数据组织方式或中间数据结构。
- 调度或缓冲
- 消息缓冲器
- 邮件缓冲器
- 计算机的硬设备之间的通信也需要队列作为数据缓冲
- 操作系统的资源管理
- 图结构的广度优先搜索
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/hyphenate_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test disabling hyphenation for short passages.
#set page(width: 110pt)
#set text(hyphenate: true)
Welcome to wonderful experiences. \
Welcome to `wonderful` experiences. \
Welcome to #text(hyphenate: false)[wonderful] experiences. \
Welcome to wonde#text(hyphenate: false)[rf]ul experiences. \
// Test enabling hyphenation for short passages.
#set text(hyphenate: false)
Welcome to wonderful experiences. \
Welcome to wo#text(hyphenate: true)[nd]erful experiences. \
|
https://github.com/Hyiker/report-typst | https://raw.githubusercontent.com/Hyiker/report-typst/master/main_zh.typ | typst | Creative Commons Attribution 4.0 International | #import "report.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: "示例项目报告主标题",
subtitle: "项目报告副标题",
abstract: "只见那山中忽然走出一条恶虎,毛如刷漆,眼似铜铃,张牙舞爪,径抢上山来。那虎见了行者,抖擞精神,吼声如雷。行者道:“好畜生!不要无礼!”",
subject: "相关课程名",
authors: ((name: "甲甲醛", department: "BIG & GOOD 国家重点实验室", rollno: "114514"),),
department: "计算机科学与技术学院",
institute: "某不知名大学",
language: "zh",
)
= 简介
却说那大圣取出金箍棒,望风一举,叫声“变!”顿时变作千百条,齐向妖怪打去。那怪物躲闪不及,被打得脑浆迸裂,死于非命。众妖见了,四散逃命。
== 本文内容
却说唐僧带领徒弟行至一座高山,忽见那山巅有一阵妖风卷来,声如雷震,尘土蔽天。唐僧心惊,急忙收缰勒马,道:“悟空,为师感到妖气袭来,不知是什么妖怪挡住去路,你速去查探。”悟空听了,笑道:“师父放心,有我老孙在,任它什么妖怪,我都替你摆平。”说罢,跳起身来,手持金箍棒,驾起筋斗云,直奔妖风来处。
只见山顶上盘踞着一只巨大的妖怪,身长数丈,形貌狰狞,手持一杆大刀,正坐在石崖上哈哈大笑。见悟空飞来,那怪物喝道:“哪里来的毛猴,敢到我这里撒野!”悟空闻言大怒,厉声道:“你这妖怪!快报上名来,我老孙便饶你一命!”那怪物冷笑道:“我乃此山之王,名为白骨精,吃人无数。今日遇到你这小猴,也算我运气好,正好拿你祭刀!”
悟空见其凶恶,也不再多言,举棒便打,白骨精挥刀相迎。二者斗在一处,一个金棒翻飞,一个大刀挥舞,打得天昏地暗,山石飞溅。战了三十回合,白骨精渐渐不敌,便抽身化作一阵白烟,消失不见。
== 贡献
悟空拔下毫毛,吹口仙气,叫声“变!”霎时化作千百个小猴,齐齐上前,将那妖怪团团围住,动弹不得。
== 一些其他东西
八戒见妖精拿着钉耙要打,连忙滚地求饶,道:“好姐姐,饶命!我不敢了!”那妖精见状,笑道:“叫声好姐姐便饶你。”
== 一些其他东西
沙僧举起降妖杖,猛地一挥,将那妖怪打翻在地。妖怪挣扎着要起,悟空早已一棒打下,妖怪再也不动了。
= 相关工作
唐僧见前方迷雾重重,心中不安,问道:“悟空,这雾中似有妖气,你可看得清楚?”悟空笑道:“师父勿慌,待我去探个究竟,再做打算。”
== H2 标题
那大圣闻得唐僧话语,急忙驾起筋斗云,前去打探。顷刻之间,他便到了迷雾深处,只见一座山峦险峻,山中隐隐传来妖怪的呼啸声。悟空收敛身形,潜行靠近,只见山洞口有一大妖,身高丈余,长相丑陋,手持一杆长枪,正来回巡视。悟空暗笑道:“好妖怪,待我捉你!”便一抖手中金箍棒,化作千斤重,朝那妖怪猛然打去。只听“轰”的一声巨响,那妖怪被一棒打得脑浆迸裂,立时毙命。悟空见妖怪已除,纵身飞回报知唐僧,唐僧闻言大喜,夸赞道:“悟空,果然是你本领高强。”
=== H3 标题
悟空手持金箍棒,领着八戒、沙僧继续前行。忽然见前方树影晃动,悟空停步道:“不好,前面有埋伏!”话音未落,只见一阵狂风卷来,数十个妖怪从树林中蹿出,手持兵器,围住了师徒四人。八戒见状,吓得退后几步,喊道:“师兄,如何是好?”悟空冷笑道:“莫慌,看我老孙扫平他们!”他一声大喝,跳起身来,挥动金箍棒左右乱扫,顷刻间,那些妖怪纷纷倒地,不敢再战。沙僧上前捆住几个,带至唐僧前,唐僧念了几句佛经,众妖怪痛哭求饶。
==== H4 标题
却说那唐僧师徒途经一片荒野,日头正烈,唐僧口渴难耐,便对悟空道:“悟空,你去找些水来吧。”悟空答应一声,驾起筋斗云四处寻觅。不多时,便见一条清澈小溪,水声潺潺,周围树木葱郁,鸟语花香。悟空高兴,正要打水,忽见溪边盘踞一条巨蟒,长达数丈,张开血盆大口,正虎视眈眈盯着他。悟空不慌不忙,拔下毫毛,吹口仙气,变作无数小猴,一齐上前,把那巨蟒围住。那蟒怪见状惊慌失措,还未来得及逃跑,已被小猴们牢牢捆住,无法动弹。
===== H5 标题
师徒四人行至一座小村庄,见村中一片萧条,家家户户紧闭门户,连条人影都见不着。唐僧心中疑惑,问道:“悟空,这村中似有异样,难道又是妖怪作祟?”悟空道:“我去探个究竟。”于是,他变作一只蜜蜂,飞入村中四处查看。只见村中老幼皆躲在屋中瑟瑟发抖,原来不久前一只老虎精从山中窜出,掳走了许多村民。悟空飞回后,将情况告知唐僧,唐僧叹道:“果然是妖怪为害,快随我去救人!”悟空点头,立刻领着八戒、沙僧,向那老虎精藏身之处进发。
#box(stroke: 1pt, inset: 10pt, "曹操见吕布英勇无敌,手持方天画戟,纵马冲杀,士卒皆不能敌。操叹道:“吕布非人也,乃虎将也,吾当避其锋矣!”")
|
https://github.com/SkiFire13/master-thesis | https://raw.githubusercontent.com/SkiFire13/master-thesis/master/chapters/1-introduction.typ | typst | = Introduction
Systems of mixed least and greatest fixpoint equations over complete lattices are very common in the field of formal analysis and particularly in the field of model checking. A classic example is $mu$-calculus @mucalculus, where liveness and safety properties can be expressed using potentially nested least and greatest fixpoints of functions over sets of states. Behavioral equivalences like many bisimilarities @bisimilarity can also be defined as the greatest fixpoint of an appropriate function over the lattice of the binary relations between states. Another example is Łukasiewicz $mu$-calculus @lukamucalculus, a version of $mu$-calculus which combines deterministic and probabilistic behavior by using continuous functions over the real numbers interval $[0, 1]$. Abstract interpretation @abstractinterpretation also extensively uses fixpoints of functions over functions representing the abstracted state of the program at various points.
It has thus been the focus of many papers in the literature to provide ways to solve fixpoint equations. Most notably the Knaster-Tarski theorem @tarski is a key result for deriving the existence of fixpoints, including the uniqueness of a least and greatest one, while Kleene iteration @kleene gives a constructive way to compute them, albeit generally not very efficient, by repeatedly applying the given function to the bottom or top element. However the mixing of least and greatest fixpoint equations into systems of fixpoint equations, while greatly increasing the expressiveness, also complicates the search for the solution. This is the case for example in the $mu$-calculus, where the use of nested fixpoints is equivalent to a system of mixed least and greatest fixpoint equations.
In this thesis we will build upon the work in @baldan_games, which provides a way to characterize the solution of a system of mixed fixpoint equations over some complete lattice through the use of the _powerset game_, a particular parity game, which in turn is a kind of game where two players move a token on a directed graph with the winner being decided by the parity of the vertices that are visited. Due to the nature of the _powerset game_, the number of moves is linked to the powerset of the states, whose size grows really quickly. It is thus necessary to represent them in a compact way, by using _symbolic moves_, which also help reducing the number of moves to consider by allowing to ignore "useless" ones. Symbolic moves are represented using logic formulas, which can also be conveniently simplified when some position becomes known to be winning for one player, thus further reducing the number of moves to consider.
The powerset game can then be solved using existing parity games algorithms to solve the problem, which can be classified as either global or local: global algorithms aim to find the winners for all vertices of the graph, while local algorithms only focus on specific vertices. We can observe that often the interest is in only one local characteristic of the solution, for example in the case of the $mu$-calculus we might be interested in whether a specific state satisfies a formula, rather than all the states that do so. As such we will focus on a local approach, like the one experimented in @flori, rather than a global approach as in @mazzocchin. Many algorithms have been developed for solving parity game, but for our work we will use a strategy iteration algorithm @jurdzinski_improvement, which works by iteratively improving a strategy for one player until it becomes optimal according to the related _play profiles_. This is a global algorithm, but a local variant based on it @friedmann_local has been developed, which works by solving subgames until it can infer the winner on the full game.
Our main contribution is an adaptation of these algorithms for the powerset game. This involved performing changes both to the powerset game and the local algorithm in order to satisfy some assumptions that would otherwise not hold. For example the strategy iteration algorithm assumes a so called "total" parity game, which the powerset game is not guaranteed to be, so we found a way to convert an arbitrary parity game to a "equivalent" total one, for some definition of "equivalent" we will give. We also generalized the local algorithm to work on subgames defined by a subset of the edges of the full game, rather than a subset of the vertices, due to the powerset game lazily generating those edges. Then we provided a more flexible way to simplify symbolic formulas while keeping track of which generated moves have already been considered, which was needed due to the lazier way we generated such moves. Our work also included some optimizations and improvements that became possible thanks to solving this specific kind of game, for example by computing the play profiles of the current strategy after expanding the subgame, which would otherwise require an expensive step. On top of this we translated some of the previously mentioned problems to systems of fixpoint equations and the corresponding symbolic formulas. These were then solved using our implementation, comparing the results to the existing work in @flori.
The goal will ultimately be showing that we can solve generic systems of mixed fixpoint equations over some complete lattice, highlighting the flexibility of such approach, and in a way that is faster than the existing approach, though we will not be expecting performance to be necessarily competitive with state of the art specialized solvers.
The rest of this thesis sections are organized as follows:
- @section-background introduces all the theoretical notions which we will build up on. In particular this includes the background needed to introduce systems of fixpoint equations, parity games and the powerset game. It also includes an explanation of $mu$-calculus and bisimilarity, along with a way to convert them to instances we can work with. Finally, it includes descriptions of the parity game algorithms we will be adapting;
- @section-algorithm explains how we adapted the given parity game algorithms to the powerset game and also includes various optimizations that we found for these particular instances;
- @section-implementation presents the implementation of our algorithm, along with its design choices and observations on its performance;
- @section-conclusions summarizes our contribution in this thesis along with possible future improvements or extensions.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/weave/0.1.0/lib.typ | typst | Apache License 2.0 | /// Given a value, transform it using the list of functions
#let pipe(input, transformations) = transformations.fold(
input,
((x, f) => f(x)),
)
/// Given a list of transformations, apply them to a value
/// This is the curried version of its counterpart without `_` suffix
#let pipe_(transformations) = input => transformations.fold(
input,
((x, f) => f(x)),
)
/// Apply a list of transformations from right to left to a value
#let compose(transformations, input) = transformations.rev().fold(
input,
((x, f) => f(x)),
)
/// Compose a list of transformation from right to left into a single function.
/// This is the curried version of its counterpart without `_` suffix
#let compose_(transformations) = input => transformations.rev().fold(
input,
((x, f) => f(x)),
)
|
https://github.com/Functional-Bus-Description-Language/Specification | https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/static.typ | typst | == Static
The static functionality represents data, placed at the provider side, that shall never change.
The static functionality has following properties:
*`init-value`*` bit string (obligatory) {definitive}`
#pad(left: 1em)[
The init-value property defines the initial value of the static.
]
*`read-value`*` bit string (None) {definitive}`
#pad(left: 1em)[
The read-value property defines the value that must be returned by the provider on the static read after the first read.
If the read-value property is set, then the actual value of the static can be read only once.
]
*`reset-value`*` bit string (None) {definitive}`
#pad(left: 1em)[
The reset-value property defines the value of the static after the reset.
If the reset-value is set, but a bus or block containing the static is not resettable (`reset = None`), then the compiler shall report an error.
If both read-value and reset-value properties are set, then the static can be read one more time after the reset.
]
*`width`*` integer (bus width) {definitive}`
#pad(left: 1em)[
The width property defines the bit width of the static.
]
#block(breakable: false)[
The static functionality may be used for example for versioning, bus id, bus generation timestamp or for storing secrets, that shall be read only once. Example:
#pad(left: 1em)[
```fbd
Secret static
width = 8
init-value = 0x13
read-value = 0xFF
```
]
]
|
|
https://github.com/Gchism94/PrettyTypst | https://raw.githubusercontent.com/Gchism94/PrettyTypst/main/_extensions/PrettyTypst/typst-template.typ | typst | Creative Commons Zero v1.0 Universal |
#let PrettyTypst(
// The document title.
title: "PrettyTypst",
// Logo in top right corner.
typst-logo: none,
// The document content.
body
) = {
// Set document metadata.
set document(title: title)
// Configure pages.
set page(
margin: (left: 2cm, right: 1.5cm, top: 2cm, bottom: 2cm),
numbering: "1",
number-align: right,
background: place(right + top, rect(
fill: rgb("#E6E6FA"),
height: 100%,
width: 3cm,
))
)
// Set the body font.
set text(10pt, font: "Lexend")
// Configure headings.
show heading.where(level: 1): set block(below: 0.8em)
show heading.where(level: 1): underline
show heading.where(level: 2): set block(above: 0.5cm, below: 0.5cm)
// Links should be red.
show link: set text(rgb("#AB0520"))
// Configure light AZ blue border.
show figure: it => block({
move(dx: -3%, dy: 1.5%, rect(
fill: rgb(12,35,75),
inset: 0pt,
move(dx: 3%, dy: -1.5%, it.body)
))
})
// Purple border column
grid(
columns: (1fr, 0.75cm),
column-gutter: 2.5cm,
// Title.
pad(bottom: 1cm, text(font: "Lexend", 20pt, weight: 800, upper(title))),
// The logo in the sidebar.
locate(loc => {
set align(right)
// Logo.
style(styles => {
if typst-logo == none {
return
}
let img = image(typst-logo.path, width: 1.5cm)
let img-size = measure(img, styles)
grid(
columns: (img-size.width, 1cm),
column-gutter: 16pt,
rows: img-size.height,
img,
)
})
}),
// The main body text.
{
set par(justify: true)
body
v(1fr)
},
)
}
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/label-angle/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher: diagram, node, edge
#for bend in (0deg, 30deg) {
[`label-angle` shown in center]
grid(
columns: 2,
gutter: 5mm,
..(left, right, top, bottom, auto).map(angle => diagram(
// debug: 2,
spacing: 2cm,
node((0,0))[#angle],
(
"r",
"ru",
"u",
"ul",
"l",
"ld",
"d",
"dr",
).map(to => {
edge(
to,
"-|>",
$ pi r^2 $,
label-angle: angle,
label-side: center,
bend: bend,
label-pos: 0.3,
)
for side in (left, right) {
edge(
to,
stroke: none,
text(0.8em)[#side],
label-angle: angle,
label-side: side,
bend: bend,
label-pos: 0.8,
)
}
})
)),
)
pagebreak()
}
#diagram(
spacing: 2cm,
node((0, 0), [#auto]),
(
"rr",
"rrd",
"rdd",
"dd",
"ldd",
"lld",
"ll",
"llu",
"uul",
"uur",
"uu",
"urr",
).map(d => edge(d, "->", $sqrt(a^2 + b^2)$, label-angle: auto, center))
)
|
https://github.com/PgBiel/typst-improv-tables-planning | https://raw.githubusercontent.com/PgBiel/typst-improv-tables-planning/main/main.typ | typst | Other | #import "template.typ": *
#show: project.with(
title: "Typst Improved Tables - Planning",
doc-authors: ("PgBiel"),
authors: ([PgBiel \<https://github.com/PgBiel\>],),
date: [2023-12-10 (Last update: #datetime.today().display("[year]-[month]-[day]"))],
font: "Fira Sans",
raw-font: "Fira Mono",
)
#outline(indent: 2em)
#pagebreak(weak: true)
= Introduction and initial details
This document is meant to coordinate efforts towards improved Typst tables. Right now, Typst's `table` elements aren't very flexible - you can't customize individual lines, merge cells, have repeated headers and/or footers, and so on. That's where the author's Tablex @tablex came by, providing a pure Typst alternative to Typst's default tables, bringing many of those very important features - including advanced per-cell customization, customization of each line, merging cells vertically and horizontally, and so on. The intention of the efforts described in this document is to provide these features in the default Typst tables as well, through Rust code instead of Typst code.
== Important definitions
- A *track* is a column or a row in the table.
= Ideas
Below, I will list all ideas that have been brought up so far, in a pretty unordered and informal manner. Then, I will collect them in the "Requirements" section once we are sure on what's going to be done. There, the ideas will be more organized, labelled and prioritized.
== Per-cell customization
1. *OK:* Use a `table.cell` element with customizable settings for each cell. It could look something like
```typ
#table(
fill: green,
table.cell(fill: red)[Hello world! This is red],
[This is green!]
)
```
2. *OK:* It should have similar properties to tablex's implementation. In particular, regarding the most basic properties, `fill`, `align` and `inset` are desirable to override the default table setting. Additionally, a cell would have a `body` or `content` field to access its inner content.
#note[Theoretically, it'd be possible to change cells' `x`, `y`, `colspan`, `rowspan` fields through `set` rules. That's not necessarily a problem for tables themselves, as the style chain at the grid generation stage of the table code would likely already have the final values of those fields, considering `set` rules and such. However, using such rules should be avoided, as they can produce unexpected consequences.]
3. *OK (Proposal 5):* It should be possible to customize cells in bulk, akin to tablex's `map-cells`.
- In particular, while `fill: (x, y) => pick-color(x, y)` and `align: (x, y) => pick-align(x, y)` work, they can't depend on other properties the cell has; in particular, the cell's body (e.g. you might want to set the fill for all cells with the text "3" to green).
- *Proposal 1:* We could change their signatures to `fill: cell => value` *(breaking change)*. The idea is that a `table.cell` would also have `x, y` fields to let you "locate" it, and a `body` or `content` field.
- *Proposal 2:* We could use show rules. However, they are currently limited due to problems in the styling system:
```typ
#show table.cell: it => {
// This doesn't work
set table.cell(fill: red)
it
// This doesn't work either (recursion, extra fields etc.)
// Requires heaps of workarounds
table.cell(..it.fields(), fill: red)
// This also doesn't work
it.fill = red
// What do we do (in a sane way)?
}
```
- *Investigation needed:* Additionally, how would tablex detect changes in those fields and apply them? Can an ```rust impl Layout for TableElem``` interact properly with the style-chain post-show rules?
- *Temporary conclusion:* This is probably one of the main problems behind `show x: set x()`, and an alternative proposal to `set` cell properties would likely be ideal.
- Still, this would probably be the most "Typst"-y way to customize cells, and *would be viable after a style system rework.*
- *Proposal 3:* Bring tablex's `map-cells: cell => cell` option to tables.
- Would be the simplest option and the easiest to implement.
- However, the interface *wouldn't be very consistent* with the rest of Typst.
- *Proposal 4 (Pg):* Have `table.cell` properties accept both simple values (e.g. `fill: red`, `align: left` etc.) _and_ functions of the form `data => value` (e.g. `fill: (x, y, body) => (red, yellow, green, blue).at(x + y)` or `align: data => if data.body == [1] { left } else { right }`). This would allow us to circumvent the show rule problem by using set rules instead: `set table.cell(fill: data => ...)`. Show rules would thus be restricted to modifying the body of each cell.
- *Which data to provide to the properties' functions?* While we could, in theory, provide a dictionary with all of the cell's fields, _would that be desirable?_
- *Proposal 4A:* Provide only `(x, y, body)` to each function (perhaps in a dictionary for more flexibility).
- *Proposal 4B:* Provide *all "static" cell properties* (`x`, `y`, `colspan`, `rowspan`, `body` and any others which wouldn't accept a function) in a dictionary to each function.
- *Proposal 4C:* Provide *all cell properties* (copied to a dictionary before the function is called, which then is provided to it) to each property.
- This would raise questions regarding which property's function would be called first, etc. So you can't reliably have align depend on fill and fill depend on align. But such a case could perhaps just be considered pathological.
- This would be the most flexible option, but 4B is also more balanced in the sense that there is no margin for such "race conditions".
- *Proposal 5 (Laurenz + Pg):* Allowing cell properties to depend on cell body inspection is probably not a good idea (we shouldn't encourage content inspection). So, for now, perhaps per-cell properties should just be simple (`fill: red`, `align: left` etc.), and anything depending on content should be done with show rules.
- In addition, we could allow cells to have `fill: auto` (or `fill: data => auto`) and similar to just use the global setting.
4. *To be discussed:* It should be possible to place cells arbitrarily in the table by setting their `x, y` positions manually.
#note[Throughout the document, we will assume that cell coordinates are *zero-indexed*, that is, the cell with `x: 0, y: 3` is in the *first* column (left-to-right) and *fourth* row (top-to-bottom). Note also that *ordinal numbers* (first, second, ...) *are one-indexed* to follow what the English language mandates, but sometimes we will mix both coordinates and ordinal numbers, so be aware of that (the ordinal numbers are always the coordinates plus one).]
- For instance, `table.cell(x: 5, y: 2)` would place it at the 6th column, 3rd row.
- Cells which would normally be automatically placed at such a position would just skip it.
- If we follow tablex's system for this, we would have those properties default to `auto`, meaning they would be, by default, automatically positioned based on where they were specified in the table's parameters.
- However, *what if one of the coordinates is omitted* (e.g. `table.cell(x: 5)` or `table.cell(y: 3)`)? The other one would likely be `auto` as well, but then how would we calculate it?
- *Proposal 1 (Laurenz#footnote[See discussion on Discord: https://discord.com/channels/1054443721975922748/1117839829191901286/1118120012968894475]):* We could use the first available position in the selected track. For instance, if we specify `table.cell(y: 3)`, and the 4th row only has a single cell to the left, then we would pick `x: 1` as that's the first free position in the row. Similarly, for `table.cell(x: 3)`, we would pick the first available position, from bottom to top, in the fourth column.
- Likely more expected in general.
- *Proposal 2 (Tablex's approach):* The missing coordinate should be determined without change from the `table.cell(x: auto, y: auto)` case. That is, if the cell `table.cell(y: 3)` is specified right after `table.cell(x: 1, y: 1)`, then the former cell's missing `x` coordinate will be calculated to be `x: 2` (the previous plus one). With a missing `y` coordinate, the cell would stay in the same row as the previous cell unless the row is entirely filled, in which case the cell would go to the next row.
- It works, but might be a bit surprising. Would be nice to have more opinions here.
5. *OK (Proposal 1):* Which `table.cell` properties should be applied _before_ its show rule, and which should be applied _after_?
- That is, *what is truly overridable* through show rules? Only the cell's body? Its alignment and inset? All of it?
- *Proposal 1:* Alignment and inset are applied _before_ show rules (thus *overridable*), but fill is applied _after_ show rules (*not overridable*, other than by covering it).
- This is consistent with how tables are currently implemented (alignment and inset are applied to cells' bodies before they are laid out, while fill is applied after all cells were already laid out).
- This allows completely overriding inset, which may be an advantage in terms of flexibility as it allows a package such as 3rd-party `diagbox` @diagbox to create custom cells which completely occupy a cell's available space, without regard for inset (one of the main annoyances when using said diagbox package, which requires workarounds).
- However, this places a burden on the show rule user, which must write ```typ #align(cell.align, block(inset: cell.inset, cell.body))``` at the end of every show rule to ensure the original properties will be kept.
- *Investigation needed:* A possible compromise might be to fall back to the table's global settings for `align` and `inset` when the cell's settings are ignored in a show rule, but that seems difficult to implement.
- *Proposal 2 (Tablex, sort of):* Allow alignment, inset and fill to be overridden on show rules.
- Tablex's `map-cells` follows this idea, as just returning content will discard all of those properties, while you can modify one or another property in the incoming `cellx` object and just return that modified `cellx` object to keep only the properties you didn't modify. That is, you can change any aspect of the cell in that manner.
- This is the option which provides the *maximum flexibility*, and, in theory, would *have some consistency with other Typst "sub-elements"*, such as *`outline.entry`* (which can be completely overridden) - however, `outline.entry` cannot have its indentation overridden, for instance, *which could be an argument against Proposals 1 and 2*.
- Additionally, the burden on the show rule user is even higher now, as not only will you have to keep alignment and inset through above, but also `fill` with `block(fill: cell.fill, ...)`.
- *Proposal 3:* All properties applied _after_ show rules.
- *Minimum flexibility.* The user cannot modify alignment, inset or fill through show rules.
- However, it's *more practical* when the user just wants to override the cell's body based on e.g. its coordinates, which would be available along with other fields.
6. *To be discussed:* There should be a built-in method to create a `diagbox`-style cell, with a divider across its diagonal separating two bits of text / content.
- While this can be done with a third-party package such as diagbox @diagbox, it requires manual adjustment to ensure the diagbox fits the entire cell, as tables have an `inset` parameter (which defaults to `5pt` on all sides, and can even change for each different side), and knowing and specifying the table inset is required to have the diagbox expand enough to "bypass" inset.
- This can only be done transparently when the table itself renders the diagbox, as it then provides the correct `inset` parameter.
- The solution is to have a built-in diagbox element or similar.
- *Proposal 1:* Have a separate diagbox element, e.g. `table.diagbox(flipped: true)[a][b]`.
- This could translate to internal cell properties, or even just be wrapped as the body of a `table.cell`.
- *Proposal 2:* Use properties on `table.cell`, e.g. `table.cell(diagbox: (left: [a], right: [b], flipped: true))`.
7. *To be discussed:* Cell customization could be made powerful enough to allow for spreadsheet-like powers, where one cell's content, fill and other properties depend on other cells' properties (especially content). For instance, the rightmost cells of each row could be the sum of the numbers displayed in the other cells in the row (you'd, in that case, parse its content with `int(cell.body.text)` or similar).
- Tablex partially allows for this capability, in a restricted manner, using `map-cols` and `map-rows`: you can modify rows and columns of the table grid in bulk, thus allowing one cell's content and properties to depend on properties from other cells in the same row and in the same column as itself. The first example in tablex's README showcases this, where a cell's text is even colored differently depending on its own body (which is a number calculated as the sum of other cells in the row).
- While a thin wrapper over table (which modifies `..args` before they are passed to `table()`) can simulate this behavior, it is worth noting that a wrapper over table doesn't have access to the table's final grid, as cells can be specified in any order (when we consider that we will allow specifying arbitrary coordinates for cells). The table wrapper would have to position cells in the grid by itself, so it would end up not being very "thin", hence why native support could be helpful here.
- *Proposal 1 (Tablex's approach):* Add a way to modify rows and columns in bulk, like tablex's `map-cols` and `map-rows`.
- This isn't powerful enough to allow a cell depend on _any other cell_, but is good enough for a good amount of usecases and less complex to implement.
- One would need to decide the order in which those modifications are applied to avoid ambiguities (columns or rows first? Show rule last?).
- *Proposal 2:* Allow a variant of `map-cells` which provides the entire grid for each cell which needs it to determine its content and properties.
- This would be extremely powerful, but we would have to consider whether the potential extra complexity - both in table parameters and in the internal code - is worth it.
- *Investigation needed:* Perhaps the grid passed should only be a copy of the initial grid in order to avoid unpredictable interdependence of cells. This could also make the operation faster by potentially allowing us to rely on COW mechanics (if the cell doesn't modify the grid at all, then it isn't copied, which can be expensive if it is too large).
- *Proposal 3:* Move such behavior to a separate element, e.g. `spreadsheet`, with otherwise similar API to `table`.
- Could be overkill.
== Merging cells
1. *OK:* It should be possible to merge cells horizontally (colspan) and vertically (rowspan).
2. *OK:* This should be a property of `table.cell` elements, should we create them.
3. *OK:* This should likely be implemented as in tablex: when merging cells, one cell is kept as its "parent" in the grid, and other cells participating in the merge are kept as "child" cells which only point back to the parent. Thus, when analyzing which positions are available in the grid (in order to position a cell with automatic positioning), you'd just skip child cells as well as normal cells.
4. *To be discussed:* Should we provide tablex-like helper functions, such as `table.colspan(2)[body]` (equivalent to `table.cell(colspan: 2)[body]`) and `table.rowspan(3)[body]` (equivalent to `table.cell(rowspan: 2)[body]`)? Would we also accept `table.colspan(2, table.rowspan(3)[body])`?
- *Proposal 1:* Those helper functions could be added and function similar to `text`: they would just apply `set table.cell(colspan: ...)` and `set table.cell(rowspan: ...)` rules. That would also allow nesting them. Their usage is optional.
- *Proposal 2:* The helper functions wouldn't be added, and you'd always construct `table.cell(colspan: ..., rowspan: ...)[Hi]`.
5. *To be discussed:* When colspans span auto columns and rowspans span auto rows, how should those columns and rows expand?
- *Proposal 1 (Tablex):* Always expand the auto column / row with the largest index (i.e. the rightmost auto column and the bottommost auto row), as needed.
- *Proposal 2:* Perhaps consider expanding auto columns / rows evenly.
6. *To be discussed:* When a merged cell spans both one or more `auto` tracks and one or more `1fr` (/fractional in general) tracks, what should happen to the `auto` tracks?
- Currently, both in tablex and (seemingly) native tables, `auto` track sizes are calculated _before_ fractional track sizes. This is necessary because fractional track sizes can only occupy the available space remaining in the page width / height after other non-fractional columns are laid out.
- However, with merged cells, we'd have cells depending on both fractional and non-fractional tracks. On tablex, this leads to a few visual bugs @tablex-frac-auto-issue1 @tablex-frac-auto-issue2. In particular, for all intents and purposes, a fractional track is considered to have size 0 before its effective length is calculated, so auto tracks expand to fit the entire merged cell when, in reality, the fractional track could have expanded enough to fit the merged cell.
- So the question is, how to best sidestep this problem?
- *Proposal 1:* If a merged cell spans all fractional tracks in the table, it should *not* cause `auto` tracks to expand. This is enough to tackle @tablex-frac-auto-issue1.
- This is based on the idea that, by spanning all fractional columns, a colspan cell will have *access to all available space* within the page/container width. So, even if its `auto` columns expanded, they would never expand, together, more than that fractional column, because *`auto` columns are resized to fit in the available page width* after being calculated.
- However, it might be best to *restrict this behavior to colspans* (and not rowspans), at least in row-major tables (the default), as *`auto` rows are not resized to fit the page height* - either they are fully sent to the next page (tablex), or they cross both the current page and the next (native tables), while *fractional rows' sizes only consider the current page.*
- *Proposal 2:* Some form of multi-pass algorithm could be employed: calculate `auto` columns, calculate fractional tracks, and check mathematically if fractional tracks would have been enough to fit merged cells; if so, repeat the process (perhaps at most once).
- *Investigation needed:* This could use some more formal definition of algorithm and/or the calculations required.
- *Proposal 3 (Tabularray @tabularray-manual[p. 27]):* Allow choosing whether or not a particular merged cell (or all such cells) can cause an `auto` column to expand (in our case, the last `auto` column), or if column sizes should ignore that (or all) merged cell (and thus only be calculated using non-merged cells / other merged cells).
- This would then allow the table user to choose what looks best for their needs, and thus sidestep this problem in a way that potentially pleases more users.
7. *To be discussed:* Which algorithm should be used to *break down table lines* such that they *do not cross merged cells*?
- *Proposal 1 (Tablex 0.0.2 @tablex-commit-draw-lines-per-cells):* Break down lines such that each occupies the border of a cell.
- This is likely the most sane approach, but the problem is that this forces lines to occupy the _entire_ border of each cell, leading to issues such as @tablex-issue-lines-not-drawn.
- Doing this in a greedy way like tablex also leads to issues such as @tablex-issue-dashed-lines-broken, where one line may be broken down into two consecutive lines for no reason, leading to dashed patterns and gradients in lines' strokes being "restarted" in the middle of the line (which is actually two visually joined lines) for no reason, making the patterns look "broken" / "uneven".
- A way around this is to set the `phase` for each dashed stroke and `relative: "parent"` for each gradient / pattern stroke.
- In parallel, however, some other less greedy algorithm could be used - either via backtracking or something else - which *merges adjacent lines*.
- *Proposal 2:* In order to solve line merging, perhaps instead of analyzing every cell and seeing which lines could be their borders, we could do the opposite: take each line and keep advancing it until either a merged cell is reached (in which case a new line is formed, and it continues after that merged cell if possible) or a gutter is hit (and the line is configured to not cross gutters - not currently possible in native tables, but possible in tablex).
- This would have some problems. How would we know when we hit a merged cell? Perhaps there could be a cell from 50 rows above us with a rowspan of 51 which could conflict with a horizontal line somewhere. We'd, thus, need to check every single cell before the current position every time, and there'd likely be more cells than lines, thus possibly making this algorithm less efficient.
- One way to speed up this algorithm considerably could be to keep a separate list of cells with colspan #sym.eq.not 1 or rowspan #sym.eq.not 1. There would, thus, be no lookup at all when there are no merged cells, and no lines would be broken down.
== Line customization
1. *OK:* It should be possible to control the appearance of every single line in the table. Among the fundamental customization properties, you have the `stroke` of the line.
- This should allow removing all vertical lines, for instance, or all horizontal lines easily.
2. *Under discussion:* How to specify these lines?
- *Proposal 1*: Perhaps use some sort of `lines: (list, of, lines, ...)` or `lines: (x, y) => line-properties` property on the table, similar to `fill` and `align`.
- *Proposal 2 (Tablex's approach):* Rely fully on special `table.hline` and `table.vline` elements which are placed alongside cells in the table. This would allow for some degree of automatic positioning (e.g. place an `hline` under a row by just creating it right next to the cells of the desired row).
- *Proposal 3 (Laurenz):* Allow `stroke` to take a function with cells as input where you'd specify the stroke for each border of the cell.
- *Proposal 4:* Perhaps allow multiple of the specification methods above simultaneously.
3. *To be discussed:* Should we use special `table.hline` and `table.vline` elements for table lines? Should we just use built-in `line` elements instead somehow?
- Noting that reusing the `line` element could perhaps restrict the available customization options, or not integrate too well with the table's coordinate system, which might make such an option less viable.
4. *Under discussion:* When a cell spans a pagebreak, which lines should appear right before the pagebreak, and which lines should appear right after?
- Currently, all lines are identical, so this doesn't matter.
- *Proposal 1 (Pg):* Lines right before the pagebreak (in the current page) should be copies of the lines which come right under the cell. Lines right after the pagebreak (in the new page) should be copies of the lines which come right above the cell.
5. *To be discussed:* Should it be possible to specify not only vertical and horizontal, but also diagonal lines?
- At the moment, this sounds very far-fetched, especially since handling diagonal lines going through pagebreaks would be a bit hairy, and require some math.
- The idea can be kept here for the future though. For the moment, we should focus on horizontal and vertical lines.
6. *To be discussed:* How to ensure line customization interacts properly with merged cells?
== Grid and table unification
1. *OK:* `grid` and `table` should be much closer to each other in terms of available settings. Maybe even have the same API!
- *Initial idea:* You'd have, for instance, a `grid.cell` element. However, *that'd be different from* `table.cell`. Show rules applying to one shouldn't apply to the other.
- *Initial idea:* Similarly to tablex, the main difference between the two - other than the semantical difference - would be that a `grid` has `stroke: none` (or, rather, no lines at all) by default, while `table` has all lines (horizontal and vertical) by default.
- *Investigation needed:* We will probably need to have some sort of "Cell-like" trait so that both a `GridCellElem` and a `TableCellElem` can be specified for the `GridLayouter`.
- *Conclusion:* We will use a `Cell` trait, with `Layout` as a supertrait.
- *Investigation needed:* How would this affect other elements which depend on `GridLayouter`, such as `list`, `enum` and the like?
- *Conclusion:* They will use `Content` as the cell type (GridLayouter is generic over `T: Cell`).
2. *OK:* `grid` and `table` should have the same fields available for customization. The main difference would be that `grid` would default to having no lines or inset at all (`stroke: none` and `inset: 0pt`), while table would keep its `stroke` and `inset: 5pt` defaults.
3. *OK:* `grid.cell` should be made available with the same properties and behavior as `table.cell`, but shouldn't be affected by `table.cell` show rules and be distinct.
== Repeatable headers
1. *OK:* It should be possible to specify a set of rows as the *header rows* of a table. These header rows *would be repeated across pages*, that is, every time the table is broken across pages, the header's cells would be repeated right at the top.
2. *To be discussed:* What's the best way to specify the header rows of a table?
- *Proposal 1 (Tablex approach):* Specify `header-rows: n`, and the first `n` rows will be considered the header rows of the table. Thus, the cells in the header are integrated with the rest (their coordinates indicate they belong to the first `n` rows), but their laid out contents are repeated on each pagebreak.
- *Proposal 2:* Specify `header: (list, of, cells, ...)` separately, as an option to the table. This would make it less clear whether the cells would be integrated with the table and have proper coordinates.
- Without proper coordinates, we would have to rethink how `table.cell.x` and `table.cell.y` work.
- *Proposal 2A:* `table.cell.x = table.cell.y = none` for cells in the header.
- Would likely make it weird for show rules and whatnot.
- *Proposal 2B:* The coordinates of cells in the header would be relative to the top left cell in the header (the "relative" `(0, 0)` cell), but would be detached to the coordinates in the table; that is, there would be two cells in the table with coordinates `(0, 0)` (and possibly others with the same coordinates).
- Could be pretty awkward to work with in general.
- *Proposal 2C:* Automatically integrate header cells with the rest of the table, such that the top left cell of the header is also the top left cell of the whole table, and thus coordinates are automatically adjusted.
- While this seems more sensible, this would potentially interfere with arbitrary cell positioning.
- *Proposal 3:* A mix of proposals 1 and 2 (perhaps tending more towards 2C), we could specify a `table.header` element above cells (but among them), making it clearer that it could affect their coordinates.
- Maybe a bit overkill?
== Repeatable footers and other kinds of repetition
1. *To be discussed:* There could be a feature similar to repeatable headers, but repeating footer rows across pages.
- The same concerns regarding coordinates from headers would remain: use the last $n$ rows as the coordinates? Have independent coordinates from the rest of the table (top left cell of the footer is `(0, 0)`)?
- Should the API be identical to repeatable header's? Have `footer-rows: n`? `footer: (some, cells, ...)`? `table.footer(...)`?
2. *To be discussed:* There could be a way to repeat *table captions* (e.g. Table 1 appears on the first page, Continuation of Table 1 appears on the second, ...)
- This, however, would likely be *better suited for figure*, as it's the figure element which provides the table's caption. In general, figures could be adapted to repeat captions across pages for anything they main contain, not only tables.
- This could, therefore, end up being out of scope for work on tables, although such work on figures would be incentivized and/or welcome.
== Table direction and orientation
1. *Under discussion:* There could be a way to change the orientation of a table, such that it *expands to the right* instead of to the bottom. This means that *the rows will be fixed,* while *the amount of columns can expand* indefinitely. Basically, switches the roles of columns and rows.
- For instance, you could specify `rows: (auto, 2pt)` to have two rows with those sizes, and `columns: (1em, auto)` to have one `1em` column and unlimited `auto` columns afterwards.
- The cells are specified in *column-major order* - that is, the first cell specified to `table` will be in the first row of the first column; the second cell, in the second row of the first column; and so on, until the first column is fully filled.
- Currently, all tables are in *row-major order* - cells fill rows instead of columns.
- *Proposal 1:* Use a `transpose: true` argument to enable this behavior. Not only would this have cells end up being specified in column-major order (as this would swap rows and columns), but this would also swap (due to semantics of matrix transpose) the `rows` and `columns` parameters, such that the sizes of rows would correspond to the sizes of columns and vice-versa.
- Can be confusing.
- *Proposal 2:* Use a `major: "row" / "column"` argument (or `column-major: true` or similar) to specify if the table is row-major (default) or column-major. Enabling column-major order *does not swap the `rows` and `columns` parameters* (due to different semantics from the previous proposal), but it does affect the order in which cells are specified (increasing the `y` coordinate).
2. *To be discussed:* If the table is changed to be column-major (through either of the proposals above), then when the table grows to the right and reaches the page width, *the table wraps* - not necessarily into a new page, but into a new "subtable" below it with the same rows, but with the post-wrap columns. // (TODO: Attach diagram.)
== Misc
1. Perhaps it should be possible to specify any kind of input as table cells. E.g., it could be possible to write
```typ
#table([a], 2, 3, -1.5, table.cell(...), $ 5 + x $)
```
- Currently, the above errors as `int` and `float` aren't `content`. Ideally, we'd just convert them to content automatically with `repr` or similar.
- *Investigation needed:* should we implement the above by ourselves by taking arbitrary `Value`s and displaying them if they're `Content`, using `Repr` otherwise? Or should we postpone this to the Type Rework, with which Content will be reworked (and thus, in theory, all types could become "showable")?
2. It could be interesting to be able to specify a fixed number of rows (by specifying only the `rows` parameter, but not `columns`) and have the amount of columns auto-adjust. *You'd still specify cells in the natural ("row-major") order.*
- Consider the example below:
```typ
#table(
rows: 3,
[a], [b], [c]
[c], [d], [e]
[e], [f]
)
```
- With that setup, there would be exactly three rows, and the amount of columns would be calculated with `ceil(num cells / rows)`; in this case, there are 8 cells, so $ceil(8 \/ 3)$ would result in 3 columns.
- Otherwise, the table would *behave exactly as if given `columns: 3`*.
- This is particularly simple to implement.
= Requirements
Formalized and consolidated ideas. *This section is WIP*.
The requirement labels have some prefixes. "F" indicates a functional requirement (related to adding functionality), while "NF" is non-functional (specifying some desired characteristic, or something more general). This allows us to refer to those requirements with precision in discussions. Additionally, *PR:* indicates the pull request which implements the associated requirement.
== Per-cell customization
#require("FPC")[We should create `grid.cell` and `table.cell` elements, which will contain settings customizing the cell's appearance and other properties. The former only works for `grid` cells, while the latter, only for `table` cells. *PR: @typst-initial-cell-custom-pr*]
#require("FPC")[It should be possible to fully customize the appearance of table cells through show rules. *PR: @typst-initial-cell-custom-pr*]
#require("FPC")[It should be possible to use `table.cell` in place of content in a `table()` call (and similarly for `grid`) to customize the look and properties of a particular cell. For instance, one could do `table([a], table.cell(fill: red)[b])` to override the fill for that particular cell. *PR: @typst-initial-cell-custom-pr*]
#require("FPC")[`table.cell` should have the following *initial* properties (which change with the following proposals): `fill` (any color-like type), `align` (any `alignment`), `inset` (anything similar to table's `inset`). *PR: @typst-initial-cell-custom-pr*]
#require("FPC")[When applying show rules on `grid.cell` and `table.cell`, their final properties must already be known. That is, `#show grid.cell: it => (it.fill, it.align, it.inset)` will contain the cell's final properties, regardless of whether they were customized or not. *PR: @typst-initial-cell-custom-pr*]
== Merging cells
#require("FMC")[It should be possible to *merge cells horizontally*, through a mechanism called `colspan`.]
#require("FMC")[It should be possible to *merge cells vertically*, through a mechanism called `rowspan`.]
== Grid and table unification
#require("FGTU")[Grid should have all properties of table available. *PR: @typst-grid-table-unif-pr*]
#require("FGTU")[Grid should default to having no lines or inset (i.e. `stroke: none` and `inset: 0pt`), while table keeps its default `stroke` (all lines shown) and `inset` (`5pt`). *PR: @typst-grid-table-unif-pr*]
#require("FGTU")[Regarding the `table.cell` proposal, there would be a separate `grid.cell` element, with the same properties as `table.cell` but not affected by its show/set rules. *PR: @typst-initial-cell-custom-pr*]
= Increments / Waves
The idea here is to assign features to separate "waves" of table features.
== MVP
- *ETA:* 3-5 weeks
- *Features:*
- Grid and table cell unification
- `table.cell`
- Merging cells
== First increment
- *ETA:* TBD
- *Features:*
- Line customization
- Repeatable headers
- Repeatable footers?
== Second increment
- *ETA:* TBD
- TODO
#pagebreak(weak: true)
#bibliography("bib.yml", full: true)
|
https://github.com/saffronner/36202-notes | https://raw.githubusercontent.com/saffronner/36202-notes/main/main.typ | typst | #set page(
numbering: "1 / 1",
paper: "us-letter"
)
#outline(indent: 1em)
#let predictedby = $#h(0.25em) ~ #h(0.25em)$
// #show image: []
= review
- big picture of applied stats: see 36200 image idk
- we have statistics ($overline(x), hat(p), ...$) and standard error ($"SE"_(overline(x)), "SE"_hat(p), ...$)
- population: literally everyone, hard to measure
- sample: subset of population
- parameter: perfect summary (e.g. mean height)
- statistic: measurable summary (e.g. mean height of sample)
- stderr of stat: typical variation due to random sampling.
- diff error formulae for each stat.
- this course: simply calc with software
- inference: give estimate and measure of how far off it might be
- if statistic is random and sampling distribution known, we have probabilistic inference; can get p-value or margin or err
== 1 variable EDA
- categorical
- bar graph
- percent summaries
- quantitative
- histogram
- center: $overline(x)$, median
- spread: stddev, IQR, range
- five number summary/box plot
== 1 variable transformations
- need normal distributions?
- $x^(1/n)$, $log(x + c)$ so everything is $>1$.
- the above's inverses
- quantile plots (qqplot) can help us diagnose if normal enough (look for straight line)
== 2 variable EDA
- explanatory $x$ axis $->$ response $y$ axis
#figure(
image("media/2var_eda.png"), caption: none,
)
== 1 variable inference
- statistics ($overline(x), S_x, ...$) predicts parameters ($mu, sigma, ...$)
- components:
- point estimation: estimate via single number calculated
- interval estimation: give plausible interview and how plausible
- significance testing about hypotheses: assess evidence for/against claim about
- 95% confidence interval for $mu$ is $overline(X) plus.minus 2 dot "SE"_(overline(X))$
- (works for arbitrary parameter/statistic estimate)
- any sample Standard Error $"SE"$ is $S/sqrt(n)$ with sample stddev $S$ (but remember, we just use software)
- technically, $2$ should be $t_"crit"$ which varies with $n$, but it approximates to $2$ for 95% confidence when large $n$
- hypotheses testing
- $H_0$ vs $H_A$
- "$p$ value is compared to significance level. we do (not) reject the null hypothesis. we do (not) have sufficient evidence that ..."
- remember: $p$ finds boolean evidence of difference from norm, not magitude of difference
= Statistical Model Primer
- statistical models are often of form: $"quantity" = "expectation" + "error"$
- in 1 variable, eg: $Y_i = mu + epsilon_i$ where $mu$ is the prediction and $epsilon_i$ is the error at $i$.
- we also specify the distribution and mean + stddev of the errors
- in 2 variables, eg: for some $X$ axis value, $Y_i = mu_(Y|X) + epsilon_i$
- we also specify the shape, center, spread of the distribution of errors
= Simple Linear Regression
- our model idea is $Y_i = beta_0 + beta_1 X + epsilon_i$ where we assume the errors are
- independent, mean 0, constant stddev/spread (for required for least squares)
- are normal (required for inference)
- (can be denoted $"iid", N(mu=0,"variance"=sigma^2)$)
- our *sample* regression equation is $hat(y) = b_0 + b_1 X$
- notice that we have three parameters: $beta_0, beta_1, sigma$
- they are estimated by $b_0, b_1$ (when using least squares), and $hat(sigma)$: what R calls "Residual standard error"
- to apply the model:
+ *state* the model
- eg: "we use the SLR model. $"vision distance" = beta_0 + beta_1 dot "age" + epsilon_i$ where errors are independent, mean 0, constant stddev, normal.
+ *validate* the data works for the model
- linearity: visual inspection
- errors are:
- independent: residual plot. residuals "patternlessly" above and below 0 line.
- mean 0: residual plot. reasonably centered around 0.
- constant stddev: residual plot. reasonably constant spread, scanning left to right
- if there are problems, consider diff model/transformations
+ *estimate* the parameters
- use software to find $b_0, b_1, hat(sigma)$
+ *inference*: is data probably showing a relationship between $X$ and $Y$?
- t test for $beta_1$ $=$ or $eq.not$ 0
+ *measure strength* of model with $R^2$ (if not chance)
- $R^2$ is the percent of variability in $Y$ that can be attibuted to the linear relationship with $X$
- "Multiple R-squared" in R. NOT "Adjusted"
+ *predict* of $Y$ from $X$ (for individual with $X$ or all people with $X$)
- the equation predicts the point estimate of $Y$ given $X$
- get prediction vs confidence interval via R for probable values of $Y$ for individual or all at $X$
== Nonlinear Relationships?
- can use a nonlinear model (same four error assumptions)
- can transform it
- transformations often preferred: fewer parameters make a simpler model
- make sure to not overfit!
= Multiple Regression
- we're often interested in predicting a $Y$ from multiple explanatory $X_i$
- when contribution from each $X_i$ is linear, we have _multiple linear regression_:
$
Y_i = beta_0 + beta_1 X_1 + ... + beta_p X_p + epsilon_i
$
where errors are
- independent
- mean 0
- contant stddev
- normal
- $p+2$ parameters: $beta_({0-p})$ and $sigma$
- like SLR, $sigma$ is stddev of errors, ie typical deviation of $Y$ from regression hyperplane
- $hat(sigma)$ in R is still "residual standard error"
- each $beta_i$ is the avg change in $Y$ when $X_i$ increases by 1 unit and the other $X$s remain fixed
- eg `school.mod = lm(GPA ~ IQ + SelfConcept, data=school)`
- to apply the model:
+ *state* the model
+ *validate* the data works for the model with EDA
- scatterplots of $Y$ against _each_ explanatory (w/ `pairs` plot). linearity: visual inspection
- error conditions (also just use a residuals/qqplot):
- independent: residual plot. residuals "patternlessly" above and below 0 line.
- mean 0: residual plot. reasonably centered around 0.
- constant stddev: residual plot. reasonably constant spread, scanning left to right
- if there are problems, consider diff model/transformations
- low multicollinearity (each $X_i$ weakly correlated with each other) (might otherwise get mathematically impossible/conceptually inappropriate, misleading results. see `media/high_multicollinearity`)
- can _informally_ investigate via: correlation matrix, odd parameter estimates, oddly large estimate stderrs
- mathematically diagonse via variance inflation factor (vif)
- let a model be $Y predictedby X_1 + X_2 + X_3$
- vif of $X_i$ is $1/(1-R^2)$, with $R^2$ from $X_i predictedby$ the other $X$es.
- i.e., vif of $X_1$ depends on $X_1 predictedby X_2 + X_3$
- BUT: just use software.
- when high multicol., drop variables: check diff subsets of $X$es, recheck diagnostics for each. find best model with R's _adjusted R-squared_ (adjusts for different number of explanatory variables. otherwise, R-squared would be higher with more variables, rmbr?)
- BUT: also just use software (best subsets routine)
- vif $>= 2.5$ is concerning
+ *estimate* parameters w/ software
+ *inference*: is data probably showing a relationship between $X_i$ and $Y$?
- F-statistic: tests if _any_ of $X_i$ are important for predicting $Y$
- individual T-tests: tests if _each_ $X_i$ is a significant predictor _in the presence of all other explanatories_
+ *predict*: use model, with $R^2$ for its effectiveness
- multiple R-squared: proportion of variation in $Y$ that can be explained by all of $X_i$. has a few properties:
- closer to 1 = better "fit"
- can only increase with more predictors
- diminshing returns
== including categorical explanatories?
- check for no interaction between predictors
#image("media/mult_reg_catvar.png")
parallel lines
iff $X_2$ doesn't depend on $X_1$
iff no interaction between $X_1$ and $X_2$
iff $X_1$ effect doesn't depend on $X_2$.
why is this so verbose from the slides :/
- assuming no interaction between predictors:
- include a binary indicator/dummy variable (1 if smoker, 0 else)
- call the category defined as 0 a "baseline" category
- if a categorical variable has, say, 3 options, we get _2_ dummy variables, both binary with 0 representing baseline group.
- "controlling for years of seniority, dept A makes X less than dept C on average"
- "holding dept constant, we estimate for every extra year of seniority, salary increases by X on average"
== what if categorical explanatories _have_ interaction?
- let us investigate a situation where calories$predictedby$carbs, but with slopes that differ depending on whether the item is meat.
#image("media/interaction_multreg.png", width: 4in)
- new model:
$ Y = beta_0 + beta_1 X_1 + beta_2 dot "DummyMEAT" + beta_3 (X_1 dot "DummyMEAT") + epsilon $
- capture the difference in slopes with an "interaction term" (the $beta_3$ term above)
- `lm(Calories ~ Carbs + Meat + Carbs:Meat, data=fastfood)`
- assumptions:
- population relationship linear within each level of $"Dummy"$
- within each level of $"Dummy"$, the errors are indep, mean 0, const stddev, normal ($"i.i.d.", N(0, sigma^2)$)
- IMPT: if interaction term stat. significant, then those explanatories must be kept (regardless of their individual variable p-values)
- this just means that their slopes are indeed different, i think
- so if they are not significant go back to normal multiple regression ig
- coefficient $beta_3$ interpretation:
+ difference in slopes; i.e., how the quantitative $X_1$ effect depends on the group $"Dummy"$ value
- "For every unit increase in $X_1$, the change in $Y$ is $beta_3$ greater/less on avg in $"Dummy"_1$ than in $"Dummy"_0$
+ equivalently: how the vertical difference between the lines changes; i.e., how the group $"Dummy"$ effect depend son the quantitative $X_1$ value
- "For a particular value $x_1$ of the quantitative variable, "
ok yknow what tbh just look at this interpretation:
#image("media/interaction_interpretation.png")
- and here's a nice lil summary from the notes:
#image("media/multreg_interaction_summary.png")
good luck on exam 1 \<3 |
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/latex-standard/lib.typ | typst | MIT License | #import "@preview/drafting:0.2.0": *
#import "font-sizes.typ": *
#import "../utils/to-string.typ": *
#set rect(outset: 0cm, inset: 0cm, width: 100%, height: 100%)
#set page(
header: rect(),
footer: rect()
)
#let latex-standard(
title: [Title],
author: [Author Name],
date: datetime.today().display("[month repr:long] [day], [year]"),
class: "article",
font-size: 10pt,
paper-size: "us-letter",
flush-left-equations: false,
left-equation-numbering: false,
two-column: false,
sides: "one",
landscape: false,
open: "any",
draft: false,
make-title: false,
table-of-contents: false,
body
) = {
set document(
author: to-string(author),
title: title,
)
if (font-size == 10pt) {
font-size = font-10pt
} else if (font-size == 11pt) {
font-size = font-11pt
} else if (font-size == 12pt) {
font-size = font-12pt
} else {
font-size = font-10pt
}
set page(
header-ascent: 20%,
paper: paper-size,
margin: font-size.margin,
numbering: "1",
)
// set-page-properties()
set-margin-note-defaults(
stroke: none,
side: right,
margin-right: 2.8cm,
margin-left: 4.8cm,
)
set text(
size: font-size.normalsize,
font: "New Computer Modern",
)
if (make-title) {rect()[
#set align(center)
#v(1fr)
#text(size: font-size.LARGE, title)
#parbreak()
~
#parbreak()
#text(size: font-size.large, author)
#parbreak()
#text(size: font-size.large, date)
#v(1fr)
]
if (class != "article") {
pagebreak()
}
}
show heading.where(level: 1): set text(size: font-size.Huge)
show heading.where(level: 1): set block(above: 2em)
show heading.where(level: 2): set text(size: font-size.huge)
show heading.where(level: 2): set block(spacing: 3em)
show heading.where(level: 3): set text(size: font-size.Large)
show outline: set heading(level: 2,)
show outline: it => {
it
}
if (table-of-contents){
rect(outset: 0cm, inset: 0cm, width: 100%, height: 100%)[
#outline(depth: 4, title: [Contents])
]
pagebreak()
}
set heading(numbering: (..n) => {
let pos = n.pos()
if pos.len() == 1 {
numbering("I", ..n)
} else if pos.len() == 2 {
numbering("1.", pos.last())
} else if pos.len() == 3 or pos.len() == 4 {
numbering("1.1", ..pos.slice(1))
} else {
// numbering("1.1 ", ..n.pos().slice(1))
}
})
show heading.where(level: 1): it => [
#pagebreak(weak: true)
#rect()[
#align(center)[
#v(175pt)
Part #counter(heading.where(level: 1)).display()
#v(20pt)
#it.body
#v(1fr)
]]
#colbreak()
]
// show heading.where(level: 2): it => [
// #colbreak(weak: true)
// #set par(first-line-indent: 0in)
// #v(70pt)
// Chapter #counter(heading.where(level: 2)).display().trim(".", at: end)
// #v(20pt)
// #text(size: font-size.Huge)[#it.body]
// #v(29pt)
// ]
show par: set block(
spacing: 1em,
)
set par(
first-line-indent: 1.5em,
justify: true,
)
body
}
#show: latex-standard.with(
class: "report",
title: [LaTeX Standard/Base Class/Template for Typst and Authoring],
author: [<NAME>],
make-title: true,
table-of-contents: true,
)
= Part Introduction
#rect(outset: 0cm, inset: 0cm, width: 100%, height: 100%, )[
== Chapter Getting Started
== Chapter Installation
// === Section Overview
// #lorem(20)
// #margin-note[A margin note is a note that appears in the margin of a page.]
// #lorem(20)
// ==== Subsection Basics
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Introduction to Basics
// #lorem(20)
// #lorem(20)
// ====== Paragraph Basic Concepts
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Detailed Explanation
// #lorem(20)
// #lorem(20)
// === Section Installation
// #lorem(20)
// #lorem(20)
]
// ==== Subsection Requirements
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Software Requirements
// #lorem(20)
// #lorem(20)
// ====== Paragraph Installation Steps
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Step-by-Step Guide
// #lorem(20)
// #lorem(20)
// === Section First Steps
// #lorem(20)
// #lorem(20)
// ==== Subsection Initial Setup
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Configuration
// #lorem(20)
// #lorem(20)
// ====== Paragraph Setting Up
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Configuration Details
// #lorem(20)
// #lorem(20)
= Part Advanced Topics
== Chapter Deep Dive
// === Section Advanced Concepts
// #lorem(20)
// #lorem(20)
// ==== Subsection In-Depth Analysis
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Detailed Study
// #lorem(20)
// #lorem(20)
// ====== Paragraph Advanced Techniques
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Techniques Explained
// #lorem(20)
// #lorem(20)
// === Section Optimization
// #lorem(20)
// #lorem(20)
// ==== Subsection Performance Tuning
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Best Practices
// #lorem(20)
// #lorem(20)
// ====== Paragraph Tuning Methods
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Methods Explained
// #lorem(20)
// #lorem(20)
// === Section Security
// #lorem(20)
// #lorem(20)
// ==== Subsection Best Practices
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Security Measures
// #lorem(20)
// #lorem(20)
// ====== Paragraph Implementing Security
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Security Details
// #lorem(20)
// #lorem(20)
= Part Practical Applications
== Chapter Real-World Examples
// === Section Case Studies
// #lorem(20)
// #lorem(20)
// ==== Subsection Example 1
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Study 1
// #lorem(20)
// #lorem(20)
// ====== Paragraph Analysis
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Detailed Analysis
// #lorem(20)
// #lorem(20)
// === Section Projects
// #lorem(20)
// #lorem(20)
// ==== Subsection Project 1
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Implementation
// #lorem(20)
// #lorem(20)
// ====== Paragraph Project Steps
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Steps Explained
// #lorem(20)
// #lorem(20)
// === Section Tutorials
// #lorem(20)
// #lorem(20)
// ==== Subsection Tutorial 1
// #lorem(20)
// #lorem(20)
// ===== Subsubsection Step-by-Step Guide
// #lorem(20)
// #lorem(20)
// ====== Paragraph Tutorial Steps
// #lorem(20)
// #lorem(20)
// ======= Subparagraph Detailed Steps
// #lorem(20)
// #lorem(20)
== Chapter Best Practices
// === Section Recommendations
// #lorem(20)
// #lorem(20)
|
https://github.com/Quaternijkon/Typst_FLOW | https://raw.githubusercontent.com/Quaternijkon/Typst_FLOW/main/src/exports.typ | typst | #import "core.typ": pause, meanwhile, uncover, only, alternatives-match, alternatives, alternatives-fn, alternatives-cases, slide, empty-slide, touying-slide, touying-fn-wrapper, touying-slide-wrapper, touying-equation, touying-mitex, touying-reducer, appendix, touying-set-config, touying-recall, speaker-note, alert
#import "slides.typ": touying-slides
#import "configs.typ": config-colors, config-common, config-info, config-methods, config-page, config-store, default-config
#import "utils.typ"
#import "magic.typ"
#import "pdfpc.typ"
#import "components.typ"
#import "components.typ": *
|
|
https://github.com/Ad4u/ad4u.github.io | https://raw.githubusercontent.com/Ad4u/ad4u.github.io/main/ceremony_fr.typ | typst | #let WIDTH = 90mm
#let HEIGHT = 160mm
#let MARGIN = 6mm
#let FRONT_TOP_MARGIN = 35mm
#let BACKGROUND = image("assets/background.jpg", width: WIDTH, height: HEIGHT)
#let FRONT = image("assets/front.jpg", width: WIDTH, height: HEIGHT)
#let BACK = image("assets/back.jpg", width: WIDTH, height: HEIGHT)
#set document(title: "Cérémonie de mariage de Betty & Romain")
#show heading: item => [
#pagebreak()
#set align(center)
#set text(font: "Better Smile", size: 44pt)
#item
#v(-20mm)
#image("assets/separator.png", width: 60%)
#v(-8mm)
]
// Page setup
#set par(leading: 0.55em, justify: false)
#set page(width: WIDTH, height: HEIGHT, margin: MARGIN)
// Front page
#set text(font: "Better Smile", size: 44pt, weight: "medium")
#set page(background: FRONT)
#set page(margin: (top: FRONT_TOP_MARGIN))
#align(center)[Cérémonie \ de \ mariage \ de \ Betty & Romain]
// Body
#show par: set block(spacing: 16pt)
#set page(background: BACKGROUND, margin: MARGIN)
#set text(font: "TT Chocolates Trl", size: 15pt, weight: "medium")
= Bienvenue
#include "speeches/greetings_FR.txt"
= Discours MC
#include "speeches/mc_FR.txt"
= Discours 1
#include "speeches/1_FR.txt"
= Voeux
#include "speeches/vows_FR.txt"
= Voeux du marié
#include "speeches/Groom_FR.txt"
= Voeux de la mariée
#include "speeches/Bride_FR.txt"
= Discours 2
#include "speeches/2_FR.txt"
= Discours 3
#include "speeches/3_FR.txt"
= Fin
#include "speeches/remarks_FR.txt"
// Back page
#set page(background: BACK)
#pagebreak()
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-04.typ | typst | Other | // Error: 6-12 invalid integer: nope
#int("nope")
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/999%20-%20Unknown%20Set/002_Project%20Lightning%20Bug.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Project Lightning Bug",
story_date: datetime(day: 27, month: 05, year: 2015),
author: "<NAME>",
doc
)
#emph[The guilds of Ravnica have grudgingly accepted that Jace Beleren is now the living manifestation of the Guildpact. It has become apparent that whenever the guilds clash, it is Beleren who will adjudicate between them. What is not apparent is Beleren's true nature as a Planeswalker—except to an informed few. Izzet guildmage Ral Zarek has no love for the new Living Guildpact, but Ral is also secretly a Planeswalker, and that shared trait has suddenly become of critical importance.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("002_Project Lightning Bug/01.jpg", width: 100%), caption: [Underworld Connections | Art by Yeong-Hao Han], supplement: none, numbering: none)
The nameless Undercity street was open to the sky, and the same clouds hung over the Tenth that had hung there for weeks, dropping the same soft drizzle over the city. Ral Zarek led the way through the sunken street, the mind mage a step behind him.
"If you dare root around in my head, Beleren, I think you'll find those clouds overhead are suddenly full of lightning bolts that are all, coincidentally, aimed at you," said Ral Zarek in a low voice.
"Then can you just tell me where we're going?" Beleren asked.
"You'll see soon enough."
"You realize, 'You'll see soon enough' is exactly the kind of thing people say right before I immediately dive into their minds."
Ral looked over his shoulder at the mind mage. "Did you know lightning strikes the Tenth more often than any other district? Do you know why that is?"
"You?"
Ral smirked. "Gold star."
They passed a shopfront that smelled of greasy onions, and a musty alleyway where hooded elves shot them dirty looks.
"I was…surprised that you approached me, Ral," Beleren said.
Ral shrugged. "Had no other options."
Of all the potential confidants and intelligences on Ravnica, Ral had gone to the one mage he never thought he would have contacted. <NAME> was the so-called Living Guildpact, the arbitrator of all the guilds—the one who had swept into the position despite Ral's efforts.
"From what you've been telling me," Beleren continued, "you'll only cause harm by letting this information spread any further."
Ral glanced back at Beleren. The mind mage looked strange without his trademark cloak—plainer, but he actually blended in better this way. He looked like any other Ravnican, a nondescript citizen of the Tenth, instead of the famous Living Guildpact. Ral wondered if he was applying any extra illusions so as not to stand out. It didn't really matter—Ral had found him easily enough, and that was exactly the problem.
"If this project goes the way it's been going, the results are going to leak, and all hell is going to break loose," Ral said.
Ral stopped at a door in the tunnel wall. He electrified the handle for a moment, and twisted it open. He led Beleren into a side passage, sealing the door behind him.
"How much does Niv-Mizzet suspect?" Beleren's voice echoed.
#figure(image("002_Project Lightning Bug/02.jpg", width: 100%), caption: [Jace, Architect of Thought | Art by <NAME>], supplement: none, numbering: none)
"If he has already grasped the pattern, he's been quiet about it. And he's never quiet about anything, so I think he hasn't seen it yet. But he's frustratingly brilliant, as you know, and he's not one for patience. He's beginning to suspect I'm not telling him everything."
"Are you sabotaging results?"
"I'm <NAME>! I don't know if you know this, Beleren, but Izzet mages don't impede Izzet research. I've just…not used the full extent of my abilities. Besides, his Chamberlain follows me on every detection."
"How many…detections…have you done of me?"
Ral paused. He looked back at Jace. "Enough. Enough that Niv-Mizzet might have guessed you're a Planeswalker already."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Project Lightning Bug had not been Niv-Mizzet's idea, but that of Maree, the current Chamberlain to the Firemind. Maree was an elementalist who had impressed their guildmaster with her work on Melek. In the weeks following the Implicit Maze and the whole Living Guildpact fiasco, the dragon had noted that Beleren had gone missing for long periods, and Chamberlain Maree suggested they track his movements more closely.
Thus Ral had been appointed Head Researcher of a project to record and explain Beleren's disappearances. Of course, he already knew why Beleren was disappearing—he was a fellow Planeswalker, and spent time outside Ravnica's plane of existence.
The idea of Niv-Mizzet learning the truth made the muscles in Ral's neck tense, and touched a dark, sore place in his youth. Ral had learned to hide his Planeswalker side under painful circumstances, and he did not want to relive that.
Besides, he knew the range of horrid things Niv-Mizzet would do in possession of that truth. Would he eagerly dissect all the Planeswalkers he could find in the spirit of curiosity, or simply eat them all to assert dominance and quell his existential jealousy? Would he track the comings and goings of every Planeswalker, and ruin all the work Ral had done to scrape his way through the ranks and achieve a position of respect among the Izzet?
And how would the #emph[other] guilds react to this knowledge?
As dangerous as it was, he had agreed to lead the project immediately. Better to lead Project Lightning Bug and manage the direction of the research than let some second-rate chemister follow Beleren around, prove the existence of other planes, and ruin everything.
Ral had to admit, he was the right man for the job—his methods were brilliant. He couldn't help himself once Niv-Mizzet handed him the project—his mind spun, crackling with ideas on how to track the Guildpact. He helped design a subtle enchantment that would deliver a small energetic pulse whenever it experienced a discontinuity, such as a planeswalk. An Izzet underling had planted the enchantment on Beleren's cloak. Then Ral conjured a dynamic amplification field above the Tenth—which the district's denizens had experienced as the last month of annoyingly-persistent drizzly weather. The drizzle field would magnify the tracking enchantment's small pulses into detectable cracks of lightning overhead, while not being blatant enough to raise suspicion.
#figure(image("002_Project Lightning Bug/03.jpg", width: 100%), caption: [Blast of Genius | Art by <NAME>], supplement: none, numbering: none)
It was a perfect system. Other Izzet guildmages began watching for the telltale lightning. Only at the last minute did Ral remember to tweak his persistent storm to weaken its precision, so that Project Lightning Bug wouldn't immediately prove the existence of Planeswalkers.
The data began rolling in, and things immediately got worse.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Why not just tell him?" Beleren asked as Ral led him through the dank tunnel. "During the Maze, you challenged me to tell Emmara everything. Now you're hiding Planeswalkers from Niv-Mizzet?"
Ral stopped walking, but didn't look at Beleren. "You wouldn't understand," he said flatly.
"I #emph[could] ," said Jace, shrugging with one palm, "but I think I'd be risking electrocution."
Ral ran his hand along the mossy curve of the tunnel wall. "Do you know how I became part of the Izzet, Beleren? Do you know what I went through to find a place where I belonged? I grew up in a tiny district. Small district full of small people. Did they encourage my storm magic? No. Everybody picked on the 'rain mage.'" Ral absently pulled on a strap on his forearm gauntlet. "I learned quick what to keep to myself. I came to the Tenth on my own, learned the accent, learned the district—where to eat, where not to sleep. I studied every guild's history backwards and forwards. I found the Izzet, and learned everything about them—I studied storm magic based on Niv-Mizzet's own equations, worked my way through the guild. The happiest day of my life was becoming part of the Izzet, becoming a guildmage."
"But you're not just a guildmage. You're a Planeswalker."
"My spark just gave me another way to lose all I had worked for. I'm a storm mage of the Tenth. I'm Ravnican to the core."
Ral turned to Beleren, and poked a finger at his chest. "And then Niv-Mizzet announces the Maze, and who becomes the Guildpact? After all I had done to get to this place? An outsider, who had done no work at all. An invader from some other place. You breeze in and solve a riddle, and now you're in position to control the destiny of my world. You know how that makes me feel?"
Ral saw Jace's brow furrow in the dim light of the tunnel, the mind mage's eyes darting in calculation. Ral had the urge to storm off, to leave this invader to his thoughts, but he saw Beleren's face change.
"You wanted to punish me," Beleren said. "You wanted to destroy what I had with Emmara, as payback for my solving the Maze before you."
Ral sighed, and his shoulders fell slightly. Beleren looked somehow both young and old—boyish with his drizzle-frizzed tangle of hair; but also too gaunt in places, creased with lines of worry.
"I didn't want to ruin things with your friend, Beleren," Ral said.
"It's fine," Jace said. "It's the way it has to be. She's safer, too, now."
Ral looked down at fiddled with his gauntlet. "She doesn't remember?"
Beleren scratched at his arm. A patch of smooth skin on his forehead crinkled, and he said nothing.
"Well, I don't blame you," Ral said. "It is the way it has to be. You asked before why I didn't just tell him. I wanted to, at first. I wanted my world to understand—understand what I am, and what they're a part of. What else is our guild for, if not understanding strange truths? But you don't know Niv-Mizzet. It would crack him. It would turn him inside-out. And then he would turn #emph[us] inside-out, and…." Ral shrugged. He leaned forward, gesturing with his hands for emphasis. "Think about what it would mean if Niv-Mizzet—if the whole plane—knew exactly when the Living Guildpact was #emph[outside of this dimension] , Beleren. Just think about that."
Beleren's eyes fell to the side for a moment. He rubbed his temple. "Can't you end the project?"
"Not the way things have gone, no. The dragon put me in charge." Ral continued down the tunnel. "Come on, we're almost there."
Beleren was a wall of non-budging skepticism. "Can you please just tell me where you are taking me?"
Ral rubbed his fingertips on his forehead in a pantomime of Beleren's telepathy, and mouthed two words: "COME. ON."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Earlier that morning, Ral had stood in the Izzet guild headquarters, lying to a dragon's face.
Ral brought his palms close together, absently letting arcs of electricity dance between them. He edged to the side, to stay just out of the patch of shadow that Niv-Mizzet's great body cast on the floor, to get a better view of his detections. The dragon studied the results, the detections projected in the air like a cloud of randomly-placed, slowly rotating stars. Ral thought about narrating, tossing in some anecdote from the field to lend the report a touch of authenticity. He knew it would irritate the dragon, and hasten the inevitable disapproval, but he kind of wanted to do it anyway.
Beside him, <NAME> put her hand over her mouth in excitement. Ral raised his eyebrows—a faintly judging gesture, maybe, but interpretable as friendly—and glanced her up and down. He liked the Chamberlain, but he wondered what would happen to her charmed career when the dragon decided he was bored with her.
Niv-Mizzet grunted as he scanned over the diagrams with their scattered dots: flashes of lightning, recorded as data. They were not quite enough to form a pattern, if Ral had done his work right. But as Ral looked, he saw something strange in the data—there were too many points.
This was bad, he thought.
"This is good," said Niv-Mizzet. "You're starting to show consistent repetitions here, Zarek."
#figure(image("002_Project Lightning Bug/04.jpg", width: 100%), caption: [Niv-Mizzet, the Firemind | Art by <NAME>], supplement: none, numbering: none)
Ral gritted his teeth. He stared at the glimmering data hanging in the air, and as he understood, static electricity hopped down his spine. "Those aren't all my detections," said Ral. "Those aren't all the Guildpact."
"No, they're new." Maree's lens waggled over her eye as she spoke. "The Izmagnus and I took a contingent of blastseekers and elementalists, and we replicated your technique." She waved her hand, and the specks of light glowed.
Ral boiled. "How could you put out more detectors without consulting me?"
"It took some time, but Mizzix and I were able to calibrate your detector spell and improve its range." Ral hadn't meant '#emph[explain how you did it] ,' but that's how the Chamberlain was taking it. "We're now tracking hundreds of citizens, and we found two new signals—new Lightning Bugs. We're tracking their discontinuities as we speak. Isn't it grand?"
Two new signals. Ral could see their pinpoints in the glowing diagram: other Planeswalkers coming and going from Ravnica. They would discover the pattern in no time.
"Firemind," said Ral. His mind raced. "This departure could jeopardize the validity of our results. It represents a danger to the entire project."
"Perhaps your research needed a bit more danger, Zarek," said Niv-Mizzet. "But even with the Chamberlain's extension, it's still not sharp enough. We need clearer data…as soon as you can."
Ral looked up the scaly pillar of the dragon's neck and into his eyes. They looked like glass beads, but with heat behind them. "Yes, Firemind."
"We had some ideas about improving the accuracy of your storm amplifier," said the Chamberlain, adjusting her lens. "We'd need your help, of course."
"Improving the accuracy?"
"Yes. We installed a series of gyrostatic dynamos on the roof of Nivix, and used them to measure the conduction rates of your storm. I hope you don't mind me saying, we found room for improvement."
Ral shook his head. "Preposterous."
"I—excuse me?"
"The static field relies on a narrow band of conduction," Ral said. Was she trying to turn this into a further promotion? Was she intentionally trying to unseat him? "Additional dynamos will only muddle the sensitivity. Too much power and you'll rupture the balance."
<NAME> looked up to Niv-Mizzet. "Firemind, I'm afraid I disagree with the Head Researcher. I believe more power is required to derive the sensitivity we need."
The dragon swung his head slowly between the two mages. Finally he looked at Maree. "Do it."
Ral could tell they were both looking for his reaction. He said nothing.
"The adjustments to the dynamos will be done soon," said the Chamberlain. "Could we meet with you tomorrow morning to implement the improvements to the storm?"
Ral looked up at Niv-Mizzet. The dragon showed his teeth, a gesture that was probably intended as an encouraging smile, but looked to Ral like a threat display. Ral could see saliva glimmering on the curving fangs.
"Of course," Ral said. "Let's hope it all goes well, and we learn the truth. Tomorrow."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Ral and Beleren continued down the moss-draped tunnel. Rhythmic chants and marching footsteps echoed down to them. Ral reached a ladder that led up to a heavy iron grating. He put a finger to his lips—Beleren nodded—and he climbed up, pushing open the grating and hoisting himself up. Beleren followed quietly after.
They emerged in a side street next to a Boros garrison, facing a main thoroughfare lit by lamps in the evening gloom. Ral and Beleren kept hidden in a sunken doorway of the garrison building, watching Boros Legion soldiers march past in a training exercise, their boots splashing in the shallow puddles that dotted the street. Ral glanced up at the drizzle field overhead and verified the time from a nearby clock tower.
#figure(image("002_Project Lightning Bug/05.jpg", width: 100%), caption: [Boros Guildgate | Art by Noah Bradley], supplement: none, numbering: none)
"Watch that spot," Ral said, nodding toward the alleyway directly across the thoroughfare. "It's just about time."
The two men waited, listening to the Boros drillmasters leading chants. A shimmer of not-quite-rain fell softly from the persistent clouds overhead. Ral checked the clock again.
"I don't remember home," Beleren said quietly, unbidden.
"What?"
"You talked about growing up in Ravnica. A lot of my memories from my childhood are gone. Chopped up in my head into a few impressions. Most of what I remember begins here, on Ravnica. I'll never have roots here the way you do, and I admit I'm off to other planes a lot. But I think of myself as Ravnican to the core, too."
A prickly, dense emotion rose in Ral, and he squeezed his lips together to keep it from spilling over. "Damn it, Jace, it's not the same," he said. He turned back to his vigil of the opposite alleyway, but he put a hand on Beleren's wrist and squeezed.
"Ral?"
"Yeah?"
"That's the first time you've called me anything but 'Beleren.'"
"Hm." Ral checked the tower again and watched the alleyway.
After another minute, Jace spoke up. "Lightning or no, I'm about to scour your head if you don't tell me what we're watching for."
Ral frowned. "It should have happened by now." The clouds above were silent—no telltale pop of thunder, no indication of a planeswalk. "It's a Planeswalker I've been tracking. One that the others in Project Lightning Bug haven't discovered yet. He usually appears here every evening."
"Every evening?"
"Like clockwork. He arrives, does some visiting around the city, and planeswalks away again before morning."
"Who is he?"
"I don't know. Human. Tall. Broad. Striking eyes. Seems to have some contacts among the Boros. I haven't had a chance to get in contact with him."
Jace pulled on his lip. "Why did you want to show me this person?"
"Because unfortunately, he's the perfect pattern. The clearest data of all. He travels so systematically, it would be nothing at all for <NAME> and the others to extrapolate from his discontinuities and learn the truth about Planeswalkers. He's the secret we have to keep from Niv-Mizzet." Ral knitted his hands together, and little arcs of lightning jumped from finger to finger. "I've ended the enchantment that tracks him, but I'm afraid the others will discover him."
"Well, then, we have to think about this logically. We need to come up with a plan to throw them off somehow, to conjure some way to…."
"—Tomorrow," Ral interrupted. "They're going to discover him tomorrow."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Ral hadn't slept much.
"Head <NAME>," said <NAME>, helping him up onto the rooftop of the guildhall Nivix. "Are you—prepared for the alteration today?"
"Yes," Ral yawned. "I'll prepare the augmentation spell. Give me a moment—I'll need to summon up a lot of power for this."
"All taken care of," said the Chamberlain, handing him two flexible, humming cables. "You can socket directly into Nivix's supply." She tried to find his eyes. "And Zarek—about the extension we did. I didn't mean to overstep my bounds. It's your project. I should have consulted you."
#figure(image("002_Project Lightning Bug/06.jpg", width: 100%), caption: [Izzet Charm | Art by Zoltan Boros], supplement: none, numbering: none)
Ral just attached the cables to his gauntlet. His skin prickled and his hair stuck out straighter. Ral couldn't help but feel exhilarated as energy flowed through him. He just hoped the plan he and Jace had come up with worked.
"At any rate, as soon as you amplify your storm, we'll get far better focus in on all the promising targets we've selected," Maree said. She slid her lens down over one eye. "We'll know with certainty what's causing their spatial discontinuities."
Ral turned toward the city. He let the cables channel mana into him as he willed a spell into being. His vision crackled and bleached to white, but he could feel the storm above him stir and ripple. He drew in a breath and exhaled hard, shooting his arms into the air.
"That's it!" he could hear Maree saying. "It's amplifying!"
Ral heard the storm jostle and swirl, like a great beast stirring awake. It pushed against him, but he pushed harder, surging mana into the storm, bidding it to grow and strengthen.
"I'm getting something," said Maree. "Keep going!"
Ral completed the spell, and felt power leave his arms and pulse into the storm above. His vision cleared. He saw the epic storm all around him, crackling with potential. His hair stood on end, popping with static electricity. Dynamo devices all around the rooftop whirled.
Despite everything that had happened, it was times like this that made him certain he was in the right guild.
#figure(image("002_Project Lightning Bug/07.png", width: 100%), caption: [Ral Zarek | Art by <NAME>], supplement: none, numbering: none)
A mighty gust swirled the air, and Niv-Mizzet himself rose to the top of the building. He came to roost on the rooftop next to the two mages with a flourish of his wings, like a peacock coming around to have his plumage appreciated. "Your conclusions, researchers," he said.
Chamberlain Maree consulted a measuring device. "We're getting pinpoints at much greater accuracy."
Ral breathed heavily, detaching the cables from his gauntlet. This was the moment when the plan succeeded or failed—and in either case, when Niv-Mizzet would react. Overhead, lightning forked across the sky, accompanied by a snap-rumble of thunder.
Maree's face changed from glee to concern. "There's something wrong," she said. "The detections. There's something erratic about them."
"What is it?" Ral asked. "Let me see."
Maree showed him the measuring device. "The storm registered a discontinuity—it was the Living Guildpact. But…it also shows him as having been in the Tenth the entire time."
Ral made a display of studying the dots on the device with a critical eye. "Hmm. Beleren had some kind of mana condition applied to him…that the storm recorded as an electrostatic discontinuity."
"But that could just be an illusion spell," she said.
"Or some other ordinary fluctuation," Ral added.
"Has the storm been recording those as Lightning Bugs all this time?"
"Without sufficient amplitude, it appears the storm lacked the resolution to discern the difference."
The Chamberlain cranked a dial on the measuring device and read it again, exasperated. "But that's what all our data is based on. The subjects weren't actually disappearing—they were just becoming invisible to the storm."
#figure(image("002_Project Lightning Bug/08.jpg", width: 100%), caption: [Niv-Mizzet, the Firemind | Art by <NAME>], supplement: none, numbering: none)
Niv-Mizzet spoke, and his voice was thunder. "This method," he boomed, in the manner of a judge condemning a defendant to death, "is #emph[demonstrably unreliable] ."
Ral nodded. "I'm sorry, Firemind. I shouldn't have allowed other team members to adjust the detections. It was my responsibility."
"Project terminated," snarled the dragon, spreading his wings and chopping at the air, his great body ascending. "You'll have to rethink this entirely, if you ever want to prove something of merit."
"Yes, Firemind," said <NAME>.
Niv-Mizzet hesitated, his eyes lingering for a brief, curious moment on the two of them, then he swiveled in the air and shot into the clouds. His wings tore a hole in the storm, dissipating it with a rumble.
"Sorry, Head Researcher Zarek," said the Chamberlain. "Or should I say, Guildmage Zarek."
Ral cocked his head to the side, like a tiny shrug. He thought about responding that the Chamberlain might be joining him as guildmage soon, but he decided informing her of that was probably the dragon's job.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The previous evening, a Planeswalker hid in on the second floor of a Boros garrison, listening. He had staked out this position for its protection wards against detection, and for its clean line of sight down at the side street below, where two men hid and spoke to one another in low tones. One of the men wore Izzet garb and a copper arm gauntlet. The other he recognized as the Living Guildpact of Ravnica. The Planeswalker watched with grim interest, as his two marks were clearly surveilling his usual arrival point. From his post, he could just make out their conversation.
"I've ended the enchantment that tracks him, but I'm afraid the others will discover him," the Izzet mage said.
"Well, then, we have to think about this logically. We need to come up with a plan to throw them off somehow," the Guildpact said.
The two mages discussed a plan, a risky but clever deception involving the dragon guildmaster and complicated Izzet storm magics he wasn't familiar with.
"We'll have the extra detector set to monitor your illusion," the Izzet mage said. "Once I have amplified the storm, you will planeswalk to your sanctum, but your double will already have been there. The storm will contradict itself—a discontinuity registering the same as a mundane spell condition. That should be enough to prove the entire project is flawed."
The Living Guildpact nodded, concluding their conversation—and he didn't leave on foot. Instead he concentrated for a moment, then vanished with a very particular ripple.
The Living Guildpact was a Planeswalker. That much was certain.
The Izzet mage, for his part, crawled down into a sewer grate and disappeared out of sight.
The Planeswalker stroked the cropped stubble on his chin. He was no longer being tracked, so that was a positive. And he had learned a critical new piece of information about the arbiter of the guilds—a productive stakeout, well worth altering his usual schedule. He inspected a dent in his armor as the last strains of the Boros infantry chant faded away, and abandoned his position.
#figure(image("002_Project Lightning Bug/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
|
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/common/typst-compile-command.md | markdown | MIT License | <!-- markdownlint-disable first-line-h1 -->
Base Typst command to run to compile the project. Other arguments will be
appended based on the parameters you supply.
|
https://github.com/drbartling/obsidian-to-typst | https://raw.githubusercontent.com/drbartling/obsidian-to-typst/master/CHANGELOG.md | markdown | # Obsidian to typst changelog
## 0.1.3
### Fixes
1. Fix issue with building mermaid docs when run as root (as in a Docker container)
## 0.1.2
### Features
1. Allow embedding images within a line
### Fixes
1. Code lines starting with `#` are not modified
## 0.1.0
### New Features
1. Can convert some simple markdown files to typst and pdfs
### Fixes
1. None, no bugs in previous release (based on https://github.com/kelseyhightower/nocode)
|
|
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/cartridges/tama5.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "../../common.typ": *
== TAMA5
TODO.
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/test/solution/test-001-show-solution.typ | typst | MIT License | #import "../../src/lib.typ": *
#show: g-exam.with(
show-grade-table: false,
show-student-data: true,
show-solution: false
)
#g-question[Question 1]
#g-solution(alternative-content: 222222)[Solution 1]
#g-question[Question 2]
#g-subquestion[Question 2.1]
#g-solution(alternative-content: [Alternative])[Solution 2.1]
#g-subquestion[Question 2.2]
#g-solution[Solution 2.2]
#g-question[Question 3]
#g-solution[Solution 3]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/delimited-03.typ | typst | Other | // Test fence confusion.
$ |x + |y| + z/a| \
|x + lr(|y|) + z/a| $
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/common.typ | typst | // Common use entities
#let versions = json("/documents.json");
#let err418 = text("Error_418", style: "italic")
#let cardin = "Professor Cardin"
#let vardanega = "Professor Vardanega"
#let adr_key = "Analisi dei Requisiti"
#let adr = text(adr_key, style: "italic")
#let adr_v = text(adr_key + " v" + versions.at(adr_key), style: "italic")
#let adr_vo = versions.at(adr_key)
#let ris_key = "Analisi dei Rischi"
#let ris = text(ris_key, style: "italic")
#let ris_v = text(ris_key + " v" + versions.at(ris_key), style: "italic")
#let ris_vo = versions.at(ris_key)
#let glo_key = "Glossario"
#let glo = text(glo_key, style: "italic")
#let glo_v = text(glo_key + " v" + versions.at(glo_key), style: "italic")
#let glo_vo = versions.at(glo_key)
#let man_key = "Manuale Utente"
#let man = text(man_key, style: "italic")
#let man_v = text(man_key + " v" + versions.at(man_key), style: "italic")
#let man_vo = versions.at(man_key)
#let ndp_key = "Norme di Progetto"
#let ndp = text(ndp_key, style: "italic")
#let ndp_v = text(ndp_key + " v" + versions.at(ndp_key), style: "italic")
#let ndp_vo = versions.at(ndp_key)
#let pdp_key = "Piano di Progetto"
#let pdp = text(pdp_key, style: "italic")
#let pdp_v = text(pdp_key + " v" + versions.at(pdp_key), style: "italic")
#let pdp_vo = versions.at(pdp_key)
#let pdq_key = "Piano di Qualifica"
#let pdq = text(pdq_key, style: "italic")
#let pdq_v = text(pdq_key + " v" + versions.at(pdq_key), style: "italic")
#let pdq_vo = versions.at(pdq_key)
#let st_key = "Specifica Tecnica"
#let st = text(st_key, style: "italic")
#let st_v = text(st_key + " v" + versions.at(st_key), style: "italic")
#let st_vo = versions.at(st_key)
#let grafana = "https://error418swe.grafana.net/public-dashboards/9392efccc5a5427c850fc9ec81df7dff"
#let azienda = "Sanmarco Informatica S.p.A."
#let lastVisitedOn(day, month, year) = {
if (year < 99) { year += 2000 }
text("(ultimo accesso " + datetime(year: year, month: month, day: day).display("[day]/[month]/[year]") + ")", size: 0.8em, style: "italic", fill: luma(100))
}
#let TODO = [
#box(
stroke: red,
inset: 0.15em,
text("Riferimento assente", fill: red, weight: "bold")
)
]
#let glo_paragrafo = [
Al fine di agevolare la comprensione del presente documento, viene fornito un glossario che espliciti il significato dei termini di dominio specifici del progetto. I termini di glossario sono evidenziati nel testo mediante l'aggiunta di una "_G_" a pedice degli stessi:
#align(center, {
text("Termine di glossario")
h(0.03em)
text(
fill: luma(100),
sub(emph("G"))
)
h(0.02em)
})
Le definizioni sono disponibili nel documento #glo_v.
]
#let infobox(type, message) = {
let icon = ""
let color = rgb("#FFFFFF")
let colors = ()
if (type == "notice") {
icon = "i"
colors = (
boxFill: rgb("#93C5FD"),
boxStroke: rgb("#60A5FA"),
iconFill: rgb("#60A5FA"),
iconStroke: rgb("#3B82F6"),
iconGlyph: rgb("#1D4ED8"),
textFill: rgb("#172554")
)
} else if (type == "warning") {
icon = "!"
colors = (
boxFill: rgb("#FDE047"),
boxStroke: rgb("#FACC15"),
iconFill: rgb("#EAB308"),
iconStroke: rgb("#CA8A04"),
iconGlyph: rgb("#A16207"),
textFill: rgb("#422006")
)
} else {
panic("Type must be [notice | warning]")
}
rect(
width: 100%,
radius: 0.25em,
inset: 1.5em,
fill: colors.boxFill,
stroke: 0.75pt + colors.boxStroke,
stack(
dir: ltr,
spacing: 1.5em,
circle(
stroke: colors.iconStroke,
fill: colors.iconFill
)[
#set align(center + horizon)
#text(weight: "bold", fill: colors.iconGlyph, icon)
],
box(width: 90%)[
#text(fill: colors.textFill, message)
]
)
)
}
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/syntax/comment.typ | typst | // Test line and block comments.
--- comments ---
// Line comment acts as spacing.
A// you
B
// Block comment does not act as spacing, nested block comments.
C/*
/* */
*/D
// Works in code.
#test(type(/*1*/ 1) //
, int)
// End of block comment in line comment.
// Hello */
// Nested "//" doesn't count as line comment.
/* // */
E
/*//*/
This is a comment.
*/*/
--- comment-end-of-line ---
// Test comments at the end of a line
First part//
Second part
// Test comments at the end of a line with pre-spacing
First part //
Second part
--- issue-4632-sth-followed-by-comment ---
// Test heading markers followed by comments.
#test([
=// Comment
=/* Comment */
], [
=
=
])
// Test list markers followed by comments.
#test([
-// Comment
-/* Comment */
], [
-
-
])
// Test enum markers followed by comments.
#test([
+// Comment
+/* Comment */
1.// Comment
2./* Comment */
], [
+
+
1.
2.
])
--- comment-block-unclosed ---
// End should not appear without start.
// Error: 7-9 unexpected end of block comment
// Hint: 7-9 consider escaping the `*` with a backslash or opening the block comment with `/*`
/* */ */
// Unterminated is okay.
/*
|
|
https://github.com/DevelAngel/typst-diff | https://raw.githubusercontent.com/DevelAngel/typst-diff/main/README.md | markdown | Apache License 2.0 | # typst-diff
Create a diff of two Typst documents
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-text-decorations_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set text(fill: gradient.linear(red, blue))
Hello #underline[World]! \
Hello #overline[World]! \
Hello #strike[World]! \
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/嵌入式系统/实验/报告/6/6.typ | typst | The Unlicense | #import "../template.typ": *
#show: project.with(
title: "实验报告 6",
authors: (
"absolutex",
)
)
= 网络通信实验
== 实验目的
使用 ALIENTEK 阿波罗 STM32F429 开发板自带的网口和 LWIP 实现:TCP 服务器、TCP 客服端、UDP 以及 WEB 服务器等四个功能,熟悉 LWIP 网络协议栈的使用。
== 实验原理
STM32F429 芯片自带以太网模块,该模块包括带专用 DMA 控制器的 MAC 802.3(介质访问控制)控制器,支持介质独立接口 (MII) 和简化介质独立接口 (RMII),并自带了一个用于外部 PHY 通信的 SMI 接口,通过一组配置寄存器,用户可以为 MAC 控制器和 DMA 控制器选择所需模式和功能。STM32F429 以太网功能框图如图所示:
#figure(
image("以太网框图.png", width: 60%),
caption: [STM32F429 以太网框图],
)
从上图可以看出,STM32F429 是必须外接 PHY 芯片,才可以完成以太网通信的,外部 PHY芯片可以通过 MII/RMII 接口与 STM32F429 内部 MAC 连接,并且支持 SMI(MDIO&MDC)接口配置外部以太网 PHY 芯片。
阿波罗 STM32F429 开发板使用的是 LAN8720A 作为 PHY 芯片。LAN8720A 是低功耗的 10/100M 以太网 PHY 层芯片,I/O 引脚电压符合 IEEE802.3-2005 标准,支持通过 RMII 接口与以太网 MAC 层通信,内置 10-BASE-T/100BASE-TX 全双工传输模块,支持 10Mbps 和 100Mbps。
LAN8720A 可以通过自协商的方式与目的主机最佳的连接方式(速度和双工模式)。
#figure(
image("LAN8720A 功能框图.png", width: 70%),
caption: [LAN8720A 功能框图],
)
== 代码修改
本实验中,HAL 库模板代码已经实现了 UDP 收发和 TCP 收发、Web 服务器访问功能。我们小组在此基础上进行修改,使开发板能够控制 LCD,根据经由 UDP 包传送的字符串数据进行实时图形显示。以下是修改后的代码:
#include_code_file("../代码/11.udp_demo.c","udp_demo.c 片段", "c")
在 `udp_demo.c` 中,创建了 `draw` 与 `stoi` 函数用来转换与绘制接收的信息,并更改 `udp_demo_test` 函数,使其能够接收 UDP 包,并调用 `draw` 函数进行实时显示。
#include_code_file("../代码/11.lwip_comm.c","lwip_comm.c 片段", "c")
在 `lwip_comm.c` 中,可以调整默认的 remote IP 值,使开发板能够快速连接到调试设备的 IP 地址,无需手动选择。
由于实验中开发板无法通过 DHCP 获取 IP 地址,我们还在 `lwipopts.h` 中设置了 `#define LWIP_DHCP 0`,使 DHCP 默认禁用,节省了开发板等待 DHCP 任务直到循环变量自然溢出的时间。
== 实验结果
首先编译并下载模板代码,测试网口收发功能,并观察开发板与调试设备之间的通信。设置好开发板与网络调试助手的 IP 与端口后,按动按键,可以观察到开发板与调试设备之间通信正常。
#figure(
image("网络调试助手.png", width: 70%),
caption: [网络调试助手],
)
然后编译下载修改后的代码,设置开发板参数,当其显示 `Connected` 后,在网络调试助手发送数字字符串,观察到开发板能够显示矩形,并随着输入数字的变大而变大。
== 心得体会
在本次实验中,我们小组完成了对开发板与调试设备的通信,并修改代码,使用 UDP 包进行图案的实时显示。调试过程中,我们遇到了一些问题,例如因为调试设备的网络配置不正确,开发板无法连接到其 IP 地址。通过查阅网络资料,我们解决了这些问题,并加深了对网络通信的理解。
使用开发板发送字符串时,在网络调试助手中默认显示十六进制数字,需要取消勾选 *十六进制显示*,才可使消息以字符串形式显示在开发板屏幕上。
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/multiline_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test text before first alignment point.
$ x + 1 &= a^2 + b^2 \
y &= a + b^2 \
z &= alpha dot beta $
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/typ/templates/ebook.typ | typst | Apache License 2.0 | #import "@preview/shiroa:0.1.1": *
#import "/typ/templates/page.typ": project, part-style, dash-color
#import "/typ/templates/term.typ": reset-term-state
#let _page-project = project
/// Show a title page with a full page background
#let cover(display-title) = {
// #set text(fill: black, font: titleFont)
// #if logo != none {
// place(top + center, pad(top:1cm, image(logo, width: 3cm)))
// }
stack(
1fr,
align(
center + horizon,
block(
width: 100%,
fill: dash-color.lighten(70%),
height: 6.2cm,
pad(x: 2cm, y: 1cm)[
// #text(size: 3em, weight: 900, project-meta.display-title)
#text(size: 3em, weight: 900, [The Raindrop-Blue Book])
#v(1cm, weak: true)
// #text(size: 3em, project-meta.at("subtitle", default: none))
#text(size: 2em, display-title)
#v(1cm, weak: true)
#text(size: 1em, weight: "bold", "Myriad-Dreamin等著")
],
),
),
2fr,
)
}
#let p = counter("book-part")
#let p-num = numbering.with("1")
#let default-styles = (
cover-image: "./rm175-noon-02.jpg",
cover: cover,
part: it => {
//set image(width: 100%, height: 100%)
page(
margin: 0cm,
header: none,
background: [
#move(dy: 3%, scale(x: -130%, y: 130%, rotate(38.2deg, image("./rustacean-flat-gesture.svg", width: 130%))))
],
{
p.step()
stack(
1fr,
align(
right + bottom,
block(
width: 100%,
fill: dash-color.lighten(70%),
height: 6.2cm,
pad(x: 1cm, y: 1cm)[
#set text(size: 36pt)
#v(1em)
#locate(loc => {
heading([Part.#p-num(..p.at(loc))#sym.space] + it)
})
],
),
),
2fr,
)
},
)
},
chapter: it => reset-term-state + it,
)
#let project(title: "", display-title: none, authors: (), spec: "", content, styles: default-styles) = {
let display-title = display-title
if display-title == none {
display-title = title
}
// inherit styles
let styles = default-styles + styles
// set document metadata early
set document(
author: authors,
title: title,
)
// set web/pdf page properties
set page(numbering: "1")
// todo: abstraction
{
// inherit from page setting
show: _page-project.with(title: none, kind: none)
//set image(width: 100%, height: 100%)
set page(
margin: 0cm,
header: none,
background: [
#place({
set block(spacing: -0.1em)
image("./circuit-board.svg")
image("./circuit-board.svg")
})
#move(dy: 3%, scale(x: -130%, y: 130%, rotate(38.2deg, image("./rustacean-flat-gesture.svg", width: 130%))))
],
)
// place book meta
external-book(spec: (styles.inc)(spec))
(styles.cover)(display-title)
}
locate(loc => {
let project-meta = (title: title, display-title: display-title, book: book-meta-state.final(loc), styles: styles)
{
// inherit from page setting
show: _page-project.with(title: none, kind: none)
// set web/pdf page properties
set page(numbering: none)
include "/src/prefaces/license.typ"
include "/src/prefaces/acknowledgement.typ"
let outline-numbering-base = numbering.with("1.")
let outline-numbering(a0, ..args) = if a0 > 0 {
h(1em * args.pos().len())
outline-numbering-base(a0, ..args) + [ ]
}
let outline-counter = counter("outline-counter")
show outline.entry: it => {
let has-part = if it.body.func() != none and "children" in it.body.fields() {
for ch in it.body.children {
if "text" in ch.fields() and ch.text.contains("Part") {
ch.text
}
}
}
if has-part == none {
outline-counter.step(level: it.level + 1)
outline-counter.display(outline-numbering)
} else {
outline-counter.step(level: 1)
}
it
}
outline(depth: 1, fill: repeat[.])
}
if project-meta.book != none {
project-meta.book.summary.map(it => visit-summary(it, styles)).sum()
}
})
content
} |
https://github.com/ufodauge/master_thesis | https://raw.githubusercontent.com/ufodauge/master_thesis/main/src/template/constants/page.typ | typst | MIT License | #let PAGE_NUMBERING_INTRO = "i"
#let PAGE_NUMBERING_MAIN = "1" |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-06.typ | typst | Other | #show heading: [1234]
= Heading
|
https://github.com/jakoblistabarth/ica-conference-series-abstract-template | https://raw.githubusercontent.com/jakoblistabarth/ica-conference-series-abstract-template/main/ica-abstract.typ | typst | #let ica-abstract(title: "", authors: (), affiliations: (), keywords: none, bibliography-file: none, body) = {
// Set the document's basic properties.
set document(
title: title,
author: authors.first().name,
keywords: if keywords != none { keywords} else { "" }
)
set page(
margin: (x: 20mm, top: 25mm, bottom: 28mm),
header-ascent: 0%,
header: locate(
loc => if (loc.page() == 1) {
image("ica-logo.svg", height: 1.19cm)
line(length: 100%, stroke: .4pt)
} else {
align(end, {
counter(page).display("1 of 1", both: true)
v(2em)
})
}
)
)
let base-font-size = 10pt
set text(font: ("Times New Roman"), size: base-font-size, lang: "en")
show par: set block(spacing: 1.4em)
set par(justify: true, leading: .5em)
show heading: it => {
set block(spacing: 0pt)
set text(size: base-font-size)
it
}
pad(y: 2em,
text(weight: "bold", 18pt, [
#title
]))
pad(
top: .5em,
bottom: .25em,
[
#set text(size: 12pt)
#authors.map(
(author) => {
let affiliations = if (type(author.affiliations) != array) { (author.affiliations,)
} else {author.affiliations}
let corresponding-mark = if (
author.keys().contains("corresponding") and author.corresponding == true
) { "*" } else { none }
return [#author.name #super(affiliations.map((d) => {numbering("a", d.id)}).join(", "))#corresponding-mark]
},
).join(", ")
],
)
pad(
y: .25em,
{
set text(style: "italic", size: 9pt)
for (i, affiliation) in affiliations.enumerate(start: 1) {
let affiliation-authors = authors.fold((), (acc, author) => {
let affiliations = if type(author.affiliations) != array {
(author.affiliations,)
} else { author.affiliations }
for a in affiliations {
if (a.id == i) {
let email = if a.keys().contains("email") {
[ -- #link("mailto:" + a.email)]
} else { "" }
acc.push([#author.name #email])
}
}
acc
})
block(
spacing: .5em,
[
#super(numbering("a", i))
#affiliation#if affiliation-authors != none {
[, #affiliation-authors.join(", ")]}
]
)
}
},
)
text(size: 9pt, [\* Corresponding author])
line(length: 100%, stroke: 0.4pt)
if keywords != none {
pad(y: .5em, [*Keywords:* #keywords.join(", ")])
}
heading([Abstract:])
body
show bibliography: it => {
set block(spacing: .8em)
it
}
if (bibliography-file != none) {
bibliography(
bibliography-file,
title: "References",
// Not exactly right yet, perhaps create a custom style?
// using ica.bst file which itself is based on a isprs style (see https://github.com/citation-style-language for public collection)
style: "elsevier-harvard",
)}
} |
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/graphics/quantizers/s-metric/2_2_found_quantizer1.typ | typst | #import "@preview/cetz:0.2.2": canvas, plot
#let line_style = (stroke: (paint: black, thickness: 2pt))
#let dashed = (stroke: (dash: "dashed"))
#canvas({
plot.plot(size: (8,6),
x-tick-step: none,
x-ticks: ((3/16, [3/16]), (7/16, [7/16]), (11/16, [11/16]), (15/16, [15/16])),
y-label: $cal(Q)_("m1")(2, 2, tilde(x))$,
x-label: $tilde(x)$,
y-tick-step: none,
y-ticks: ((1/4, [00]), (2/4, [01]), (3/4, [10]), (4/4, [11])),
axis-style: "left",
x-min: 0,
x-max: 1,
y-min: 0,
y-max: 1,{
plot.add(((0,1/4), (3/16,1/4), (7/16,2/4), (11/16,3/4), (15/16, 4/4), (15/16, 1/4), (1, 1/4)), line: "vh", style: line_style)
plot.add-hline(1/4, 2/4, 3/4, 1, style: dashed)
plot.add-vline(3/16, 7/16, 11/16, 15/16, style: dashed)
})
})
|
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/feebf7-2023_fall_TA/utils.typ | typst | #let definintion(body, name: "") = {
box(
fill: yellow.lighten(70%),
width: 100%,
inset: 12pt,
outset: 0pt,
radius: 0pt,
clip: true,
)[
#text(
size: 10pt,
weight: "bold",
)[
定义: #name
]
#set text(size: 9pt)
#body
]
}
#let statement(body, name: "") = {
box(
width: 100%,
stroke: (
paint: blue,
thickness: 0.5pt,
),
inset: 12pt,
outset: 0pt,
radius: 0pt,
clip: true,
)[
#text(
size: 11pt,
weight: "bold",
)[
定理: #name
]
#set text(size: 9pt)
#body
]
}
#let proof(body) = {
box(
width: 100%,
stroke: (
paint: red,
thickness: 0.5pt,
),
inset: 12pt,
outset: 0pt,
radius: 0pt,
clip: true,
)[
#text(
size: 11pt,
weight: "bold",
)[
证明:
]
#set text(size: 9pt)
#body
]
}
#let homework(body) = {
box(
width: 100%,
stroke: (
paint: red,
thickness: 0.5pt,
),
inset: 12pt,
outset: 0pt,
radius: 3pt,
clip: true,
)[
#text(
size: 9pt,
weight: "bold",
)[
请思考/证明:
]
#set text(size: 9pt)
#body
#line(length: 100%, stroke: 0.2pt)
$=>$
#v(2cm)
]
}
#let caption(body) = {
box(
width: 100%,
stroke: (
paint: black,
thickness: 0.5pt,
),
inset: 10pt,
outset: 0pt,
radius: 0pt,
clip: true,
)[
#text(
size: 9pt,
weight: "bold",
)[
提示:
]
#set text(size: 9pt)
#body
]
}
|
|
https://github.com/Turkeymanc/notebook | https://raw.githubusercontent.com/Turkeymanc/notebook/main/frontmatter.typ | typst | #import "/packages.typ": *
#create-frontmatter-entry(title: "Table of Contents")[
#components.toc()
]
|
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/05-group-theory/01-group-theory.typ | typst | Other | #import "../../utils/core.typ": *
== Элементы теории групп
#def[
_Группой_ называется множество $G$ и бинарная операция $*$ на $G$, такая, что:
+ $*$ ассоциативна;
+ $exists e in G space forall g in G: e * g = g * e = g$;
+ $forall g in G space exists k in G: g * h = h * g = e$ (обозначается $h = g^(-1)$).
Если $*$ коммутативна, то группа $G$ называется _абелевой_.
]
#example[
- Аддитивные группы колец $ZZ, RR, CC, K[X], M_n (R), ...$ --- абелевы по определению
- $R$ --- ассоциативное кольцо с 1, $R^*$ --- группа обратимых элементов, $ZZ^* = {plus.minus 1}, space RR^* = RR \\ {0}$
- $S_n$ --- симметрические группы, перестановки $n$ элементов.
- $D(Gamma)$ --- группа симметрий, где $Gamma$ --- геометрические фигуры.
]
#lemma[
$a, b in G$. Тогда $ exists! g in G: a mul g = b $ $ exists!h in G: h mul a = b $
]
#proof[
$g = a^(-1)b ==>$ такой элемент найдется. Проверим, что он единственный:
$ cases(a g = b, a g' = b) ==> a g = a g' ==> a^(-1) a g = a^(-1) a g' ==> g = g'. $
]
#def[
Пусть $G$ --- группа. Подмножество $H subset G$ называется _подгруппой_, если
+ $e in H$
+ $forall h_1, h_2 in H space h_1 * h_2 in H$
+ $forall h in H: h^(-1) in H$
]
#notice[
Если $H$ --- подгруппа $G$, то на $H$ есть структура группы, то есть операция
$
H times H &--> H, \
(h_1, h_2) &maps h_1 h_2.
$
Если задать на $H$ такую бинарную операцию, $H$ превратится в группу.
]
#denote[
Подгруппа $H$ группы $G$ обозначается, как $H < G$. Иногда пишут $H <= G$, если хотят подчеркнуть, что $H$ может совпадать с $G$.
]
#example[
+ ${e} < G$
+ $G < G$
+ $2ZZ < ZZ$, $NN$ --- не является подгруппой $ZZ$.
+ $ZZ < RR < CC$
+ $A_n < S_n$ --- четные перестановки
]
#ticket[Порядки элементов и циклические подгруппы]
#def[
Пусть $g in G, space n in ZZ$. Тогда _степенью_ $g$ является:
$
g^n = cases(
underbrace(g mul ... mul g, n)\, & n in NN,
e\, & n = 0,
underbrace(g^(-1) mul ... mul g^(-1), abs(n))\, & n < 0
)
$
]
#prop[
- $g^k mul g^l = g^(k + l)$
- $(g^k)^l = g^(k l)$
]
#def[
_Циклической подгруппой $gen(g)$, порожденной элементом_ $g$ называется $ {g^n bar n in NN}. $
]
#def[
Группа называется _циклической_, если она является циклической подгруппой себя, порожденной каким-то своим элементом.
]
#def[
_Порядком элемента_ называется наименьшее такое число $n in NN$, что $g^n = e$. Обозначается $ord g$. Если для любого $n$, $g^n != e$, говорят, что $ord g = oo$.
]
#lemma[
Пусть $ord(g) = d in NN$. Тогда $abs(gen(g)) = d$ и $gen(g) limits(=)^((*)) {e, g, g^2, ..., g^(d-1)}$
]
#proof[
Пусть $h in gen(g) ==> h = g^m, space m in ZZ$
$ m = d q + r, 0 <= r <= d-1 ==> h = g^(d q + r) = (g^d)^q mul g^r = g^r #[доказали $(*)$]. $
Предположим, $g^k = g^l, space 0<= k <= l <= d-1 ==> g^(l-k) = e$. $space 1 <= l - k <= d-1$, противоречие с $ord(g) = d$.
]
#notice[
Если $ord g = oo$, то все $g^k$ различны между собой.
]
#ticket[Подгруппа, порождённая подмножеством]
#denote[
Пусть $G$ --- группа, $A, B subset G$.
Тогда
$
A B = { a b bar a in A, b in B } \
A^(-1) = { a^(-1) bar a in A }
$
]
#def[
Пусть $M subset G$. _Подгруппой, порожденной $M$_ называется
$
gen(M) = {g_1 ... g_n bar n >= 0; space g_i in M union M^(-1), i = 1, ..., n}
$
Если в произведении $0$ множителей, оно считается равным $e$.
]
#notice[
Подгруппа, порожденная $M$ --- действительно подгруппа.
]
#pr[
Пусть $M subset G$. Тогда
$
gen(M) = limits(sect.big)_(H < G \ H supset M) H
$
]
#proof[
+ "$subset$": Пусть $H < G$, $H supset M$. Тогда $M^(-1) subset H$, значит $M union M^(-1) subset H ==> gen(M) subset H$.
+ "$supset$": $gen(M) < G, space gen(M) supset M ==> limits(sect.big)_(H < G \ H supset M) H subset gen(M)$
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-text_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test that gradient fills on text work for locally defined gradients.
#set page(width: auto, height: auto, margin: 10pt)
#show box: set text(fill: gradient.linear(..color.map.rainbow))
Hello, #box[World]!
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11700.typ | typst | Apache License 2.0 | #let data = (
("AHOM LETTER KA", "Lo", 0),
("AHOM LETTER KHA", "Lo", 0),
("AHOM LETTER NGA", "Lo", 0),
("AHOM LETTER NA", "Lo", 0),
("AHOM LETTER TA", "Lo", 0),
("AHOM LETTER ALTERNATE TA", "Lo", 0),
("AHOM LETTER PA", "Lo", 0),
("AHOM LETTER PHA", "Lo", 0),
("AHOM LETTER BA", "Lo", 0),
("AHOM LETTER MA", "Lo", 0),
("AHOM LETTER JA", "Lo", 0),
("AHOM LETTER CHA", "Lo", 0),
("AHOM LETTER THA", "Lo", 0),
("AHOM LETTER RA", "Lo", 0),
("AHOM LETTER LA", "Lo", 0),
("AHOM LETTER SA", "Lo", 0),
("AHOM LETTER NYA", "Lo", 0),
("AHOM LETTER HA", "Lo", 0),
("AHOM LETTER A", "Lo", 0),
("AHOM LETTER DA", "Lo", 0),
("AHOM LETTER DHA", "Lo", 0),
("AHOM LETTER GA", "Lo", 0),
("AHOM LETTER ALTERNATE GA", "Lo", 0),
("AHOM LETTER GHA", "Lo", 0),
("AHOM LETTER BHA", "Lo", 0),
("AHOM LETTER JHA", "Lo", 0),
("AHOM LETTER ALTERNATE BA", "Lo", 0),
(),
(),
("AHOM CONSONANT SIGN MEDIAL LA", "Mn", 0),
("AHOM CONSONANT SIGN MEDIAL RA", "Mc", 0),
("AHOM CONSONANT SIGN MEDIAL LIGATING RA", "Mn", 0),
("AHOM VOWEL SIGN A", "Mc", 0),
("AHOM VOWEL SIGN AA", "Mc", 0),
("AHOM VOWEL SIGN I", "Mn", 0),
("AHOM VOWEL SIGN II", "Mn", 0),
("AHOM VOWEL SIGN U", "Mn", 0),
("AHOM VOWEL SIGN UU", "Mn", 0),
("AHOM VOWEL SIGN E", "Mc", 0),
("AHOM VOWEL SIGN AW", "Mn", 0),
("AHOM VOWEL SIGN O", "Mn", 0),
("AHOM VOWEL SIGN AI", "Mn", 0),
("AHOM VOWEL SIGN AM", "Mn", 0),
("AHOM SIGN KILLER", "Mn", 9),
(),
(),
(),
(),
("AHOM DIGIT ZERO", "Nd", 0),
("AHOM DIGIT ONE", "Nd", 0),
("AHOM DIGIT TWO", "Nd", 0),
("AHOM DIGIT THREE", "Nd", 0),
("AHOM DIGIT FOUR", "Nd", 0),
("AHOM DIGIT FIVE", "Nd", 0),
("AHOM DIGIT SIX", "Nd", 0),
("AHOM DIGIT SEVEN", "Nd", 0),
("AHOM DIGIT EIGHT", "Nd", 0),
("AHOM DIGIT NINE", "Nd", 0),
("AHOM NUMBER TEN", "No", 0),
("AHOM NUMBER TWENTY", "No", 0),
("AHOM SIGN SMALL SECTION", "Po", 0),
("AHOM SIGN SECTION", "Po", 0),
("AHOM SIGN RULAI", "Po", 0),
("AHOM SYMBOL VI", "So", 0),
("AHOM LETTER CA", "Lo", 0),
("AHOM LETTER TTA", "Lo", 0),
("AHOM LETTER TTHA", "Lo", 0),
("AHOM LETTER DDA", "Lo", 0),
("AHOM LETTER DDHA", "Lo", 0),
("AHOM LETTER NNA", "Lo", 0),
("AHOM LETTER LLA", "Lo", 0),
)
|
https://github.com/EgorGorshen/scripts-for-typst | https://raw.githubusercontent.com/EgorGorshen/scripts-for-typst/main/matrix.typ | typst | MIT License |
#import "@preview/suiji:0.3.0": *
#let M = matrix => math.mat(..matrix)
#let matT = matrix => {
let ret = ()
for i in range(matrix.at(0).len()) {
let r = ()
for j in range(matrix.len()) {
r.push(matrix.at(j).at(i))
}
ret.push(r)
}
ret
}
#let rmatrix(n, m, mn: -20, mx: 20, rn: 122, tp: "int", fround: 2) = {
let returner = ()
let rnfn = if tp == "int" { integers } else if tp == "float" { uniform }
let rng = gen-rng(rn)
let r = ()
for i in range(n) {
(rng, r) = rnfn(rng, low: mn, high: mx, size: m)
r = r.map((x) => calc.round(x, digits: fround))
returner.push(r)
}
returner
}
#let rmatI = (n, m, rn) => rmatrix(n, m, rn: rn)
#let rmatF = (n, m, rn, fr: 2) => rmatrix(n, m, tp: "float", fround: fr)
#let matE(n) = {
let ret = ()
for i in range(n) {
let r = ()
for j in range(n) {
if i == j {
r.push(1)
} else {
r.push(0)
}
}
ret.push(r)
}
return ret
}
#let matMultAlpha = (A, alpha) => A.map((x) => x.map((n) => n * alpha))
#let matSum(A, B) = {
assert.eq(A.len(), B.len(), message: "Матрицы не совпадают по размерам")
assert.eq(
A.at(0).len(), B.at(0).len(), message: "Матрицы не совпадают по размерам",
)
let ret = ()
for i in range(A.len()) {
let r = ()
for j in range(A.at(0).len()) {
r.push(A.at(i).at(j) + B.at(i).at(j))
}
ret.push(r)
}
ret
}
#let matMinus = (A, B) => matSum(A, matMultAlpha(B, -1))
#let matMult(A, B) = {
assert.eq(
A.at(0).len(), B.len(), message: "Ошибка: не соответсвие размеров матриц",
)
let BT = matT(B)
let ret = ()
for i in range(A.len()) {
let r = ()
for j in range(B.at(0).len()) {
let lineA = A.at(i)
let columB = BT.at(j)
let sm = range(lineA.len()).map(index => lineA.at(index) * columB.at(index)).sum()
r.push(sm)
}
ret.push(r)
}
ret
}
#let matDet(A) = {
assert.eq(A.len(), 0, message: "matrix is empty")
assert.eq(
A.len(), A.at(0).len(), message: "Ошибка: невозможно вычислить det `col.len() != line.len()`",
)
let ret = 0
if A.len() == 1 {
return A.at(0).at(0)
}
for i in range(A.len()) {
let subMatrix = ()
for j in range(1, A.len()) {
let row = ()
for k in range(A.len()) {
if k != i {
row.push(A.at(j).at(k))
}
}
subMatrix.push(row)
}
ret += calc.pow(-1, i) * A.at(0).at(i) * matDet(subMatrix)
}
return ret
}
#let matMinorWithNums(A) = {
let ret = ()
for i in range(A.len()) {
let r = ()
for j in range(A.at(0).len()) {
let B = A
B.remove(i)
B = B.map(x => {
x.remove(j)
return x
})
r.push(calc.pow(-1, i + j) * matDet(B))
}
ret.push(r)
}
ret
}
#let matMinor = mt => matMinorWithNums(mt).filter(x => not(type(x) in (type(0), type(1.1))))
#let matMinus1Pow = mt => matMultAlpha(matMinor(matT(mt)), 1 / matDet(mt))
#let matPrintAsCases(matrix) = {
let x = i => "x_" + str(i+1)
let lines = ()
for line in matrix {
let ret = ""
for i in range(line.len()) {
let num = eval(str(line.at(i)), mode: "code")
let n = str(line.at(i))
if ret == "" {
if num == 0 {
continue
}
if num == 1 {
ret += x(i)
} else if num == -1 {
ret += "-" + x(i)
} else {
ret += n + x(i)
}
} else if i == line.len() - 1 {
ret += " = " + n
}else if num == 1 {
ret += " + " + x(i)
} else if num == -1 {
ret += " - " + x(i)
} else if num > 0 {
ret += " + " + n + x(i)
} else if num < 0 {
ret += n + x(i)
}
}
if ret != "" {
lines.push(eval(ret, mode: "math"))
}
}
return math.cases(..lines)
}
#let matTr(matrix) = {
let sm = 0
for i in range(calc.min(matrix.len(), matrix.at(0).len())) {
sm += matrix.at(i).at(i)
}
return sm
}
#let matPowInside(matrix, pow) = {
if pow == 0 {
return matE(matrix.len())
}
return matMult(matrix, matPowInside(matrix, pow - 1))
}
#let matPow(matrix, pow) = {
assert(pow >= -1, "Степени разрешается быть только больше или ранвой -1")
assert.eq(matrix.len(), matrix.at(0).len(), "Для возведения в степень матрица должна быть квадратной")
if pow = -1 {
return matMinus1Pow(matrix)
}
return matPowInside(matrix, pow)
} |
https://github.com/ohmycloud/computer-science-notes | https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/learning_typst.typ | typst | = Test1
// each first paragraph needs a label
#lorem(10) <first>
= Test2
// the label doesn't refer to the whole sequence without wrapping it
#[
Hello World. \
Hello Again.
] <first>
```raku
.say for 1..5;
```
= Test2.1
// no <first> in this one!
= Test3
#[
This is test3 \
This is test3 too
] <first>
dfdfffdffdfdfdfdfdfdfdfdfd \
fdffdfdfdfdf
#locate(loc => {
// if you prefer first building a dict, look at the commented parts
// let dict = (:)
// get all headings
let hs = query(heading, loc)
// pair it with the next heading
let hs = hs.zip(hs.slice(1) + (none,))
for (this-h, next-h) in hs {
// get all <first>s between the current and next heading
let sel = selector(<first>).after(this-h.location())
if next-h != none {
sel = sel.before(next-h.location())
}
let firsts = query(sel, loc)
if firsts.len() > 0 {
let key = this-h.body.text
// ignore everything but the first <first> found for that heading
let value = firsts.first()
// do something with it
text(weight: "bold", fill: red, key)
linebreak()
value
linebreak()
// // fill the dictionary
// dict.insert(key, value)
}
}
})
#lorem(30)
#block(inset: (right: 5cm))[
#lorem(30)
]
#block(inset: (left: 5cm))[
#lorem(30)
]
#show par: it => block(inset: (right: 5cm), it)
#lorem(30)
#lorem(30)
#set page(height: 200pt)
#block(
fill: luma(230),
inset: 8pt,
radius: 4pt,
lorem(30)
)
#show heading: it => it.body
= Blockless 无代码块儿的
Scala
#show heading: it => block(it.body)
= 有 Block 的
Rust
#let pat = pattern(size: (50pt, 50pt))[
#place(line(start: (0%, 0%), end: (100%, 100%)))
#place(line(start: (0%, 100%), end: (100%, 0%)))
]
#block(
fill: pat,
inset: 10pt,
lorem(10)
)
#set page(height: 80pt)
The following block will
jump to its own page.
#block(
breakable: false,
stroke: red,
lorem(45),
)
#set page(height: auto)
#lorem(100)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/041%20-%20Kaldheim/009_Episode%205%3A%20The%20Battle%20for%20Kaldheim.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 5: The Battle for Kaldheim",
set_name: "Kaldheim",
story_date: datetime(day: 03, month: 02, year: 2021),
author: "<NAME> & <NAME>",
doc
)
Far above the Feltmark, wheeling between the columns of smoke that rose from the many chimneys of the Beskir Stronghold, a raven sailed through the air. A raven, it is known, can cover a hundred miles in a day, and this one had done just that. It had passed over the high ridges of the Tusk mountains, seen the fire giants scaling the cliffsides while Tuskeri braveswords rolled cut logs and boulders to knock them back to earth. The raven, with one black and inscrutable eye, had watched the Skelle gather in their marshes and swear oaths by blood, readying for war. It had followed the coast for some time, where longships dotted the horizon, the greatest fleet of the age riding the wind westward, to the one place in Bretagard that all flock to in times of crisis.
#figure(image("009_Episode 5: The Battle for Kaldheim/01.jpg", width: 100%), caption: [Bretagard Stronghold | Art by: Jung Park], supplement: none, numbering: none)
The raven landed on a thatched roof in one of the inner courtyards, past the thick walls that ringed the fortress. Below, among the rising sounds of weapons pressed to grindstone, of mail brushing plate, two voices stood out. The raven, as was its way, paused to listen.
"We've lost the eastern fold, and it'll be the whole damn Aldergard soon," said the older one. His hair and beard were the color of fresh snow; everything else was weathered, leathery, rugged. On his back was a broad shield made of a material that seemed to shimmer in the right light. "I've never seen so many trolls in one place. And working together, too."
The younger one laughed. "The Kannah are having trouble with a few Hagi? One of mine brought down a #emph[demon ] yesterday. Now all the youth are trying to claim the next." From the side of this one's head jutted an odd, bony protrusion—like a sabretooth had tried to bite into his skull but lost their fang partway through.
"If it's such a party, then what are you doing here?" grunted the older one.
The other shrugged. "A clan leader has certain obligations, you know."
Two guards uncrossed their spears before the pair and pushed open a set of heavy wooden doors, each one taking the full weight of the warrior before they groaned open.
"<NAME>, of the Tuskeri, and Fynn, the Fangbearer, of the Kannah," one of the guards barked. Inside, four figures were seated at the table. Inga Rune-Eyes, leader of the Omenseekers, had already arrived, and this fortress belonged to Sigrid, God-Favored. The other two—a dark-skinned woman and an elf with red braids—were strangers.
Fynn, the older of the pair, grabbed the axe from his belt. "What in Koma's breath is #emph[he ] doing here?"
The guards, partway through closing the door, scrambled for their weapons, but Sigrid held up a hand. "Inga?"
Rune-Eyes stood from her seat. "This is Tyvar, of Skemfar, and Kaya, of—elsewhere. They are friends. And we are in need of all the friends we can find right now."
"No serpent-kissing elf can call himself my friend," growled Fynn. "Least of all their prince."
#figure(image("009_Episode 5: The Battle for Kaldheim/02.jpg", width: 100%), caption: [Fynn, the Fangbearer | Art by: <NAME>], supplement: none, numbering: none)
He hadn't drawn his weapon yet, but he looked ready to. Tyvar hadn't even risen from his chair, though. "It isn't just the humans that will die if the elves go to war. But I suppose you'll be the one to talk down my brother, then, when he arrives at the head of an army."
"I'll talk him down. About six feet down."
"Enough," barked Sigrid, her voice a gavel. "I didn't invite you into my hold to insult my guests, Fynn. I invited you to discuss how our people might live out the week."
Grudgingly, Fynn dropped himself into one of the chairs surrounding the long table. Arni joined him. "So! I'm assuming there's some sort of plan, and that it will require acts of stupendous daring and bravery? I understand the odds are against us." About this, he didn't seem terribly concerned.
Sigrid smiled thinly. "Trolls, demons, giants—both frost and fire—rampaging through the realm. And now I hear reports of draugr, which means the Dread Marn, Karfell's dead army, has returned. Yes, I would say the odds are against us. But we have weapons yet with which to fight."
"Other than a mouthy elf?" muttered Fynn.
"Yeah," said Kaya. From under the table, she lifted a sword that seemed to be forged from glass; caught within the translucent blade were an array of blues and greens that seemed to ripple and glow before their eyes. She set it on the table with a dull clink.
"Is that—" said Fynn.
"The Sword of the Realms," said Sigrid evenly.
"Koll must have finally finished the bloody thing," said Arni, whistling.
"He did," said Sigrid. "But he took the secrets of how to wield it to the grave."
A moment of silence passed between them. Fynn was the first to break it. "But without that knowledge, it's nothing but a blade. A Tyrite-forged one, aye, but no number of fine swords that can stop a Doomskar."
"There is one, yet, who can wield it," came a voice from the darkened corner of the room where the light of the braziers didn't quite reach. A fifth figure stepped from the shadows—an old man, in a long, heavy traveling cloak. There was a raven perched on his shoulder. "The god for whom the sword was meant. Halvar, God of Battle."
#figure(image("009_Episode 5: The Battle for Kaldheim/03.jpg", width: 100%), caption: [Strategic Planning | Art by: <NAME>], supplement: none, numbering: none)
From his eyes spilled a faint glow—the same light frozen inside the blade of the sword. Before Alrund, even Fynn was speechless.
"Halvar's our man," said Kaya. "But getting to him is going to take some doing."
Arni, recovered from having met one of the gods of Kaldheim, kicked his feet up on the table. "A perilous quest, then. Now we're getting to the good part."
Halvar, Alrund had told them, wasn't far from the Beskir fortress. He was, after all, the god of battle, and battle was all around them now. As the raven flies, he was quite close.
#emph[I only wish the old man hadn't meant it literally] , thought Kaya, grabbing a fistful of black feathers and tightening her grip.
The bird that rode on Alrund's shoulder was named Hakka; Kaya knew that much. He hadn't told them the names of the giant ravens that now carried them through the sky, great tracts of grassland whipping away with each beat of their vast black wings. Or maybe he had—admittedly, Kaya hadn't been able to focus much during introductions, her attention inextricably drawn to those great glassy eyes. There was an intelligence in them she couldn't deny, and a curiosity. Not to mention that great curving beak, which could probably snap her in two if it wanted. On one rode Sigrid, Fynn, and Inga—on the other, Arni, Kaya, and Tyvar.
"Look!" she heard Tyvar shout over the rushing wind.
The first thing she saw was the tear in the world, a streak of icy white cutting through the amber fields below. The perspective looked all wrong, like someone had laid another plane flat across this one. Steam billowed out as the air of that frozen place met the warmer air of Bretagard, and from the edge of the opening thin, rotting figures dragged themselves hand over hand into the human realm. Ahead of them, across a rolling carpet of yellowing grass, stretched a thousand shambling forms. Draugr, they had called them. #emph[A zombie by any other name. ] Towering above the rank and file were a few massive figures covered in long, ropy hair—Torga trolls, Kaya recognized, though these ones looked like they had seen better days. Hard to tell from up here, but they had the same unsteady gait as the foot troops. Undead too, then.
All of them—draugr and Torga, big and small—shuffled toward the same thing: a thickly built wooden bridge, fording a broad white-water river. On the far side, Kaya could make out a hamlet of little huts, cobbled paths, a waterwheel. No people that she could make out, but that made sense with what was on their doorstep. It seemed miraculously whole, untouched. The solitary figure on the bridge had made sure of that.
From here, Halvar didn't look like much. He didn't radiate that spooky god-light in the same way Alrund did; compared to the gash in the world spilling blue, green, and purple light into the sky, he seemed hardly remarkable. A miniscule figure, from this height, in dulled iron armor. Before him, on the near side of the bridge, was a mound of destroyed draugr nearly waist-high.
"We have to get to the bridge," yelled Kaya, hoping Tyvar would hear it and the giant bird they were on would somehow understand it. There was no way to turn back the clock, to suck this undead army back into their frozen world, but the Sword of the Realms was strapped across her back; if they could reach Halvar, they could at least stop this from getting any worse.
But Tyvar's eyes, as he turned to face her, locked on to something else. A shadow passed over her, then—the bird's glossy black feathers grew marginally darker as something moved between her and the sun above them.
"Watch out!" said Tyvar, right before the blow struck; a crunching sound, an avian shriek, and suddenly Kaya was knocked from her perch and into open air.
She saw the rest in individual moments, separate frames as she fell: the raven, its wing bent into an unnatural position; Tyvar and Arni, arms wheeling around them as they started to fall, grabbing for handholds that weren't there; above them all, a massive horned figure with two leathery, ragged wings, carrying a heavy-looking, long-handled axe.
#figure(image("009_Episode 5: The Battle for Kaldheim/04.jpg", width: 100%), caption: [Varragoth, Bloodsky Sire | Art by: <NAME>], supplement: none, numbering: none)
It was closer than she had seen him before; even falling down, down, away from the demon, she could make out the tangle of bruise-colored flesh that hung in the shape of a wild beard; she could see thousands of years of imprisonment boiling out of those crazy eyes. Varragoth swung again, driving his axe into the raven's side, and then Kaya was turning over and over, the wind deafening in her ears, falling, falling.
#emph[Think.]
#emph[Think, think, think!]
She looked down, squinting against the wind—below her, the river crashed and surged. Hitting water after a fall from this height wouldn't be much better than hitting stone. She could survive the fall, though—her ability to slip in and out of mortal flesh would make sure of that. Could Tyvar? She didn't know. She couldn't count on it. Kaya straightened her body and fanned out her arms and legs to slow her fall. She tried to focus on the sky around her rather than the ground rapidly rising below. Arni, it turned out, was close to her, maybe five feet off and bellowing some insane war whoop as he tumbled toward death. Tyvar was maybe twenty feet out, all that grace and balance useless as he spun through the air, totally out of control.
She grabbed hold of Arni, swinging one arm through the strap keeping his broadsword across his back. "Straighten your body and push back your arms!" she screamed over the roaring wind.
He did so, and she followed suit; immediately they were falling faster, angling toward Tyvar. Below, the grass was no longer vague yellow shading but waving stalks; she could make out the blocky steel blades of the draugr, their armor still rimed with frost. They were almost to the river. She couldn't miss—it had to be now.
They collided with Tyvar about five seconds before they hit the surface. Another second to summon up the energy she needed; one more to turn all three of them insubstantial. The last three seconds were just enough moments to spare.
Darkness and cold swallowed them—it wasn't just the chill of the water rushing all around them, either. The cold filled her, #emph[was ] her. No hot rush of blood through veins, no air in her lungs, no steady heartbeat reminding her with each thrum that she was alive. For those few seconds, Kaya knew what it was to be dead, and to linger on—a ghost, a spirit.
With effort, she pulled them all back to corporeal form, and at once, they were tumbling and turning in the current. Kaya had no idea which way was up, no clue where to swim. All she could do was cling to Arni and Tyvar, keeping them one big, drowning unit. She opened her eyes; all around her was rushing water. At the edge of her vision, in the greater darkness of the broad river, she thought she saw something move—a sleek, nimble body in the waves.
Arni was the one that caught the branch along the bank; with Kaya's help, they hauled Tyvar out of the water. He was still gasping for air, clutching his arms as if freezing. It was lucky, she guessed, that the draugr on all sides seemed too surprised to take a swing at them before she'd found her footing again.
#figure(image("009_Episode 5: The Battle for Kaldheim/05.jpg", width: 100%), caption: [Grim Draugr | Art by: <NAME>], supplement: none, numbering: none)
Kaya dodged the first blow, parried the second. She knocked away a sword swing meant for Tyvar, took the draugr's arm off at the elbow. "Get up, kid!"
They were slow, but there was no end to them, and on all sides, they were beginning to realize there were enemies in their midst. Kaya split a white, frost-bitten skull with one of her hand-axes and tugged it free barely in time to knock aside a spear thrust. She stepped backwards, nearly tripped—and immediately Arni was there in front of her, hacking off limbs with great wheeling sweeps from his broadsword. #emph[Does that guy get turned ethereal every day?] Kaya thought, bewildered.
Arni thrust his blade into a draugr's ribcage, held it out at arm's length while it clawed uselessly at him, and turned back to her. Sure enough, he was grinning. "You two go on ahead. I'll keep this lot busy. Least I could do, after you broke my fall with that spooky magic of yours."
One warrior against all these draugr; those odds weren't great. #emph[Then again, he seems like a man who likes to gamble.]
Kaya pulled Tyvar to his feet, and together, they ran through the gap Arni had carved out. In the distance she could see the bridge—almost close enough to touch, with nothing but an army of undead between them. She could rush ahead if she started phasing, but she had been immaterial for a long time during their "landing" and didn't know how much more her body could take. There was Tyvar to consider, too.
At least the draugr in this section of the field seemed less dense. Together they ran, pausing only briefly to shatter a ribcage or lop off a frozen limb, the Sword of the Realms jostling the whole time in its sheath against Kaya's back. Behind them, in the distance, she could see standards of the human clans as they clashed with the edges of the draugr horde, but there hadn't been time to marshal more than a few raiding parties, and more draugr spilled out of that rift with each passing minute.
Over the dead-choked fields rose a sound Kaya had never heard before. A few changes of pitch and tone, and it might have been the call of some vast night bird, the howl of a dire wolf; it had that wild and eerie quality to it as it carried across the plains, and Tyvar froze.
"That is no draugr horn," he said, breathless.
It sounded again, and Kaya followed it to the gentle curve of a hill some ways off. A line of figures had begun to form—most carried shields of bronze, stained with the green patina of age. Some carried spears, some swords. Kaya only needed to see how Tyvar looked at them to know who they were: the elves of Skemfar, marching to war.
#figure(image("009_Episode 5: The Battle for Kaldheim/06.jpg", width: 100%), caption: [Harald, King of Skemfar | Art by: <NAME>], supplement: none, numbering: none)
"Tyvar, we don't have time for this. We have to move," said Kaya, but Tyvar seemed rooted to the spot.
"Kaya, the humans aren't the only victims of Tibalt's treachery," he said, turning to her. "I can't let my people fight and perish for his lie. My brother stands at the head of that army—I know I can make him see reason."
For all Tyvar's bravado, he had a good heart in there. "Alright, kid. Get moving, then."
"Will you be okay?"
Kaya grinned, tried to look confident. "I made my professional reputation killing the undead. I'll be fine."
He nodded. With that, he tore off.
It wasn't a lie she'd told him, exactly—but this would have been much easier if the draugr were undead of the more spectral variety. Kaya pushed forward, hacking through when she needed to, running when she didn't. The sounds of metal clashing against metal were all around her now, as well as the distant screams of men and women, and she found her heart beating louder and louder in her ears. Everything seemed to be happening slower than usual, each breath feeling like an hour, a year.
An earth-trembling footstep shook her from her trance, freezing her where she stood. Between Kaya and her path to the bridge stood one of the Torga trolls she had seen from the air. This close, she could smell the almost sweet scent of rot and see where patches of once mossy fur had gone brittle white or fallen out altogether. Something had opened a great gash in the creature's flank—she could see three slab-like ribs clear as day, a sickly blue light emanating from somewhere deep inside the troll. Its eyes were clouded, dead, but they seemed to fix on her nonetheless. It exhaled sharply, a gout of white mist hissing from between two blackened tusks.
Just as it began to move toward her, there was a splashing sound to Kaya's left. She saw, hanging in the air, the most unlikely thing: a dolphin. Oddly majestic, almost pristine in the middle of all the chaos and carnage. It was arcing through the air toward her, gray skin wet and sleek—it must have jumped from the whitewater rapids next to her, Kaya realized. Seamlessly, that shining skin billowed back into the shape of a cloak, and the creature landed on now human legs; the cloak settled on slender, brown shoulders. In front of Kaya and the troll stood a middle-aged woman with wild, unbound hair. She said nothing, only raised her hands. As her eyes glowed with shifting, multi-colored light, Kaya realized she was looking at one of the gods of Kaldheim.
#figure(image("009_Episode 5: The Battle for Kaldheim/07.jpg", width: 100%), caption: [Cosima, God of the Voyage | Art by: <NAME>], supplement: none, numbering: none)
Behind her, a wall of water rose from the river, white and thrashing like an animal. It swept over the undead Torga and a handful of draugr. The wave carried all of them off as it rolled down the field, one more combatant in the mad battle across Bretagard.
"Who are you supposed to be?" said Kaya, dumbstruck. She tasted salt in the air.
The woman in front of her brushed her hair out of her face. Her eyes had gone back to a dark, earthy color. "You were on my ship not long ago. How did it treat you?"
Cosima. Goddess of the sea. "Oh. Uh, our acquaintance was brief."
"She is a flighty one," said Cosima thoughtfully. From under her cloak, she drew a long, curved sword. "Now then. Alrund did not send me to visit."
Kaya merely nodded. #emph[Badass sea goddess. Okay. ] "We have to get to Halvar."
"Lead the way," said Cosima.
More draugr had assembled before them; these fell before the pair like wheat to the scythe. They were close now; not a hundred feet off, she could see Halvar at the head of the bridge, knocking draugr about with swings of his shield-arm, pitching them into the white river below. She was almost there.
She didn't register the shadow passing over her until it smothered her in darkness; suddenly something pulled sharply at Kaya's leather armor, yanking her to the side just in time to avoid the ugly iron axe biting into the dirt where she'd stood moments ago.
Cosima, having dragged her out of harm's way, was now pulling her up to stand. Between the pair and the bridge—ten, twelve feet tall, fronds of gray flesh curling and waving from his arms, his chest, his face, grinning a hideous frozen grin, was Varragoth. He beat his wings once, then settled on the ground.
"He didn't have wings last time," muttered Cosima.
"That blade. I know what you carry," he hissed, his voice rust and blood. "I swear on the endless lives I have taken that you will not trap me again in that desolate—"
The first axe, thrown, hit him on the brow, clipping one horn, causing boiling, tarry blood to bubble around where it had stuck. The second axe, this one in Kaya's hand, drove into his knee. Varragoth howled in pain and grabbed at her, but Kaya danced out of his grasp. She even managed to snatch her hand-axe from his forehead as he bent over. "I know you're some kind of scary story people tell their kids, but I'm not from around here," Kaya said, once she was a safe distance away.
Varragoth bellowed in frustration and lunged toward her, a single beat of those huge wings driving him half the distance. She'd landed two clean hits, but neither seemed to slow him down much.
Kaya ducked below a scything axe blow, feeling the wind of it whip across her face. Then Cosima was there, swinging her blade in great curving arcs, carving through Varragoth's iron armor like water. If the wounds bothered the demon, he showed no sign.
Behind him, more dark, winged shapes descended from the sky, landing between them and the bridge. She tried to ignore the deep weariness in her limbs, shifting her grip on the hand-axes. There was no time to worry about whatever was on the other side of Varragoth. If she couldn't get through him, nothing else mattered.
She and Cosima moved forward together; the sea goddess went low, and Kaya went high. Cosima caught the blunt side of the demonic greataxe on a backswing, sending her flying backwards, but Kaya chopped into his shoulder. He didn't fall or falter; instead, he grabbed her around one leg. If she hadn't phased—a considerable effort, now, even on a smaller part of her body—he would have beaten her against the ground, breaking her spine and more besides.
She tumbled free, coming up just in time to dodge another blow of the axe. How long could she keep this up? Behind him, through the crowds of draugr, more horned, hulking forms advanced. #emph[It's not too late] , said a little voice inside herself. #emph[You could always leave.]
Kaya set her weight into a balanced stance and took a deep breath. Yeah, she could. But that didn't mean she would.
The first of Varragoth's demons stepped out of the crowd, shoving draugr aside. There were two more behind him, and who knew how many beyond that. She bent her knees, prepared again to leap forward—and was interrupted by the familiar sound of a horn blowing, much closer this time.
#figure(image("009_Episode 5: The Battle for Kaldheim/08.jpg", width: 100%), caption: [Warhorn Blast | Art by: <NAME>], supplement: none, numbering: none)
They crashed into the draugr and the demons both, from the east, where the rising sun shone on their armor and shields, making the ancient, tarnished brass seem—for a moment—new again. Elves, she realized. A line of pike-bearers set their hafts against the ground, forming a wall between Kaya and the demons. They were #emph[helping ] her.
"Need a hand?" came a voice from behind her.
Tyvar sat on what looked to Kaya like some sort of reindeer, festooned in the same greenish brass armor as the rest of the elves. Next to him rode another elf—taller and more slender, with the same red hair but a severity to his features she had never seen on Tyvar.
"Kaya, allow me to introduce Harald, King of the elves of Skemfar, uniter of the tribes of Wood and Shadow. Also, my older brother," said Tyvar, grinning.
"Your Majesty, I am #emph[very ] pleased to meet you."
Before he could speak, there was a metallic crunching sound and a scream. Varragoth had charged the line, crushing one elven pike-bearer entirely underfoot and cutting another cleanly in half with that massive axe. Several pikes were buried in the gaps of his armor; he didn't seem to mind. Emboldened, the other demons were advancing now, crossing blades and hammering at shields with terrible strength.
Tyvar spurred his reindeer into motion, gracefully dismounting behind the elves holding back the demonic onslaught. He put his hands on the backs of their armor, and Kaya watched the plating seem to grow, contouring to perfectly fit their bodies, doubling over itself to grow thicker. One demon feinted past the shield, raking his sword across an elf's reinforced breastplate, but the blow only threw up a shower of sparks as it skittered off. #emph[Good friend to have] , thought Kaya.
More elves poured in from behind Harald, filling in the gaps in the line. Kaya allowed herself a moment to breathe.
"So," she said to the elf king. "Your brother is—"
"A fool," said Harald in a clipped, short tone. "And a braggard. But not a liar. He prevented me from making a mistake, here. I am thankful for that."
"I'm pretty thankful myself."
"He says you must get to the bridge." Harald extended a hand down to her. "I can bring you."
"What about Tyvar?"
They glanced back to the battle, where the elves clashed with demons and draugr; Tyvar, his arms now gleaming that ancient brass color, danced around a furious Varragoth. He actually managed to leap #emph[over ] one long, sweeping strike to crack the demon across the jaw with one metallic fist.
"I'm certain he's having the time of his life. Now come," said Harald.
He pulled her onto the reindeer. It immediately bounded forward; she had to grab hold of the elf king's waist just to keep herself mounted.
The creature moved through the chaos of battle with the grace and nerve of any trained warhorse. Sometimes draugr not engaged with the elven army would lean over to take a swing at them; Kaya knocked away the stiff attempts with her hand-axe. Off to the side, a demon with a gnarled black bow drew back its string—but before he could fire, Harald waved a hand and the bow sprouted flowers and vines that grew rapidly around the surprised demon's arms and up toward his throat.
Before she knew it, they were there. Aside from the pile of draugr corpses arrayed in a fan around, and covering, the entrance, the bridge would have fit in anywhere; it looked utterly normal amid the total pandemonium around them. On the first few wooden planks, looking as tired as she felt, was a man in simple, stripped-down armor, carrying a wooden shield ringed with steel. He looked up at them as the reindeer clopped closer. "You're not here to try and cross this bridge too, are you?"
"No. You're Halvar?" asked Kaya.
"Aye. That's me. I recognize the king of Skemfar, there. Who does that make you?"
"I'm Kaya. I've got something that I think belongs to you."
She pulled the sword from its wrappings across her back; in the strange light of the Doomskar, it seemed to shimmer all the stronger. Kaya tossed him the sword, which turned end over end through the air, finally landing in his palm as if it had always belonged there.
"The sword Koll was forging before—before he fell." He shook his head. "I never thought it would be an elf returning it to me."
"And I never thought I'd be helping one of the usurper gods," snapped Harald. "But it seems you're the only one who can set this mess right."
Halvar nodded. "Yes. With this sword, I think I can. But I'll need time."
"We can give you that," said Kaya.
"Hold the bridge until I can separate the realms once more."
"What is so important about this accursed bridge?" said Harald. "What, precisely, is on the other side?"
"People," said Halvar simply. Then he sat, cross-legged, the sword across his lap.
Kaya slid off the back of the reindeer. The draugr, it seemed, had finally reacted to the elven army at their flanks and were pushing back. They had greater numbers, and the difference only grew as more poured forth from the great rift in the world. In the distance, she could see the banners of the Tuskeri, the Beskir, the Omenseekers, the Kannah—but they were far from where she stood. Halvar, on the bridge, had gone deep inside himself. His eyes were closed, and the sword began to glow from somewhere within.
The closest draugr had formed into ranks, marching toward Kaya and Harald at a steady pace. Towering over the draugr, she could see more undead trolls lurching in their direction, the flesh of one's head peeled all the way back to reveal a bare, ice-encrusted skull. Above them all, demons pulled themselves aloft on leathery wingbeats.
"This is folly," muttered Harald, taking a tighter grip on the reins as his reindeer shuffled back and forth, sensing danger.
"Yeah," said Kaya, pulling the axes Tyvar had given her from her belt. "Probably." She wasn't going anywhere, though.
She was watching the demons rise on those black wings—that's why she saw it. A roiling, stretching pattern across the sky, like the very air was wearing thin. It began to tear, spilling that divine light—another rift in the world, like the one the draugr still spilled out of. There was something different about this one, though. Where the sky was held taut, she could make out something, pressing into the back of the developing rift like a hand against cloth. With a sound like thunder, it tore open.
#figure(image("009_Episode 5: The Battle for Kaldheim/09.jpg", width: 100%), caption: [Koma's Coil Token | Art by: <NAME>], supplement: none, numbering: none)
The thing that emerged from the rift had features she recognized—flat nostrils, a coiled body, arcing fangs laced with venom—but at this scale, they appeared alien and strange. It wasn't simply massive, it was #emph[continental] . Not just a snake, but #emph[the ] snake; anything else a pale imitation, a lesser copy. It looked big enough to coil around any of the branches of the World Tree. #emph[Which it probably does] , Kaya thought.
"By the Einir," whispered Harald, next to her. "Koma. The Cosmos Serpent."
Even gravity seemed to fear that thing—it moved through the air almost inquisitively, casting a shadow across half the battlefield as it glided overhead. Kaya saw it snap a hulking demon out of the air as if it were a mosquito. All the chaos of battle slowed and quieted as everyone—undead, elf, and human—seemed to hold their breath while it passed.
As the serpent reached the rift into Karfell, it paused. Those great gaping nostrils flared once, then twice. With terrifying and sudden speed, it plunged into the tear in the world, crushing dozens of nearby draugr with an incidental sweep of its tail. Endless tracts of serpent seemed to slide into the icy rift before it was finally gone.
Kaya's relief was so great she almost didn't notice the other beings spilling out of the rift Koma had just torn open. Angels, it looked like, with great feathered wings of white and black and brown and red, armed and armored, many of them roaring with sudden and startling fury. Not angels, she realized after a moment—Valkyries. Inga had told her about them. Arbiters of judgement, guardians of the heroic souls forever fighting and feasting in Starnheim. They slammed into the demons from above, feathered wings tangling with leather membrane as they tumbled out of the air together or rebounded off clashing steel.
#figure(image("009_Episode 5: The Battle for Kaldheim/10.jpg", width: 100%), caption: [Starnheim Unleashed | Art by: <NAME>oss], supplement: none, numbering: none)
Only one figure among them wasn't winged; they dangled, in fact, from the arm of a Valkyrie, who was carrying them down close toward Kaya. Just before they reached the ground—maybe ten feet up—the wingless one let go. The air around them seemed to harden, then, condensing into solid, reflective shards of—something. With a juggler's speed, they grabbed and threw three of them. Each one sunk into the chest of a massive, undead Torga. The trolls didn't just go down, though—they shattered, as if they'd been glass under a hammer.
"Neat trick," said Kaya. "Who are you?"
The stranger whirled on Kaya, another mirror-like shard in their hand. Kaya put her hands up on instinct; she'd seen what those could do.
"Who are you?" said the stranger. They didn't notice the draugr behind them, hefting a chipped and ancient-looking greatsword. "Behind you!" Kaya shifted the grip on her axe and threw.
The stranger twitched their head away from the arcing weapon—in the right direction, thankfully. The axe slammed into the draugr's skeletal face, knocking it to the ground. After a moment, they both let out a breath.
"I'm Kaya," she said. "You got a name?"
"Niko. <NAME>."
That didn't sound like the name of a Kaldheimr. "Great. We'll handle the rest of the introductions later."
#figure(image("009_Episode 5: The Battle for Kaldheim/11.jpg", width: 100%), caption: [Shard Token | Art by: <NAME>], supplement: none, numbering: none)
Kaya turned back toward the mass of draugr and demons. Something was surging through the crowd toward them, knocking corpse-like soldiers into the air as it barreled their way. Varragoth—who else?—crashed free of the ranks of draugr, looking more like a wild beast than a demon jarl now. The iron armor he'd been wearing was warped, gouged, and broken; somewhere along the way he'd lost his axe. He was bleeding from a dozen different wounds now, but he was still upright. Clinging to his back, red hair darkened with blood and eyes unfocused, was Tyvar.
Harald hissed a word; snakes sprung from the ground, their scales stitched with the same runic lettering she'd seen over Tyvar's own magic. They wrapped round Varragoth's legs, binding him—until he ripped them apart bare-handed. Niko threw a mirrored shard toward the demon, but he caught it on one of the iron plates still affixed to his arm, and it bounced off harmlessly.
As Varragoth stalked forward, Kaya saw Tyvar jab that brass blade of his into the demon's wing. He roared with pain and fury, reaching back to grab Tyvar—and taking his eyes, for a moment, off the rest of them. Which was just the opportunity Kaya needed.
Yeah, she was trying to do the hero thing now. But Kaya had spent a long, long time as an assassin.
The motion was fluid, easy, almost effortless; it required no phasing or magic powers. Kaya slipped in, past Varragoth's free arm, and swung an axe clean through his throat. The demon stumbled forward, both hands going to the mess of tarry blood suddenly spilling from his neck. He took one more step, reaching out a claw—and collapsed.
Kaya didn't even have time to exhale. Behind them came a sudden rushing sound, like water; above, the sky rippled with a wave of color, the same divine greens and purples and blues that surrounded the gods. She watched it sweep over the great rift on the battlefield—the one draugr were still pouring out of. Slowly, like a healing wound, the rift began to shrink and close.
Kaya didn't know if the draugr were mindless undead, but they were at the very least slow-witted; they didn't notice their reinforcements cut off. Across the field, she saw the demons who weren't engaged with the Valkyries take flight, panic finally overcoming their bloodlust. She turned to find Halvar standing, the Sword of the Realms pointing straight up into the air. Light poured from it in a dazzling, kaleidoscopic rush. Behind him, something caught her eye: motion, in one of the windows of the village across the bridge. There, the moony, wide-eyed face of a child stared, open-mouthed, as the god of battle sealed up the holes in the world. #emph[Yeah] , thought Kaya. #emph[This one will make a pretty good saga.]
#figure(image("009_Episode 5: The Battle for Kaldheim/12.jpg", width: 100%), caption: [Halvar, God of Battle | Art by: <NAME>], supplement: none, numbering: none)
"By the end," Tyvar was saying, as they crossed the now-quiet battlefield, made muddy from the tramping of countless boots, "I #emph[personally ] slew close to a hundred draugr, and three demons. It is my guess, though, that they will be telling tales of you for a long time. The woman who killed Varragoth—Slayer of the Bloodsky Sire. Why, I can almost hear it now!"
"Well, you make sure they get the details right," said Kaya. Everything hurt, every inch of her felt exhausted, but she still could not hold back a smirk.
"Actually," said Tyvar, pausing where he stood. "I'm not sure I'll be around to correct them."
Kaya raised an eyebrow. "Going somewhere?"
"I'd like to see what there is to see, out in your Multiverse."
"Oh? I thought you weren't interested in planeswalking."
Tyvar shrugged. "I rushed to judgement. And you've taught me its value. Had you not been here, I don't know what would have happened to our worlds. Chaos and destruction, I imagine, on an even greater scale. Perhaps there's a plane—a people—out there who need my help. As Kaldheim needed yours."
"What about being remembered? You're leaving all that glory on the table," said Kaya.
"Oh, I'm not worried about that anymore. I don't believe the people here will ever forget about what you did here," he said. That could still take her aback—that damned earnestness of his. He was guileless, this kid, an open book. #emph[But he saved me. More than once. ] She figured he'd be okay.
"Well," she said. "Maybe I'll see you out there."
"You will," said Tyvar, confident as ever. "And next time, it's #emph[my ] deeds that will go down in the sagas."
They came to a kind of crossroads—what had once been a crossroads, anyway. Now it was littered with the detritus of war: swords and spears, axes and helmets, the dead everywhere. Draugr, yes, but humans and elves, too. A moment of silence held in the air.
At the crossroads waited Inga Rune-Eyes, along with the other leaders of the clans of Bretagard—Arni, Sigrid, Fynn. By the Kannah leader stood that lanky stranger, the one who'd fallen from the sky. Niko, their name was.
Harald, too, was close by, flanked by a retinue of brass-armored honor guard. He and Fynn were staring at each other with open contempt, but at least weapons hadn't been drawn. With the Doomskar over, the gods had vanished. Off to other tasks, other duties—this corner of Kaldheim was hardly the only one that had suffered, Kaya supposed.
"Kaya. Tyvar," said Inga, by way of greeting. "You appear unharmed."
"More or less," said Kaya.
"I am glad."
"We broke the draugr lines and drove off their main body," said Sigrid. "Our scouts are pursuing the stragglers, but we'll never catch them all. Unless draugr melt in the warmer months, we'll be dealing with them for years. But any trouble they cause will be nothing compared to the demons that escaped."
#figure(image("009_Episode 5: The Battle for Kaldheim/13.jpg", width: 100%), caption: [Sigrid, God-Favored | Art by: Johannes Voss], supplement: none, numbering: none)
"It's the same all across Bretagard. Probably all across the realms," said Inga. "The rifts were open for a long time. There's no telling what slipped through."
"I, for one, can't wait to find out," said Arni, grinning.
"As you say, all the realms have been changed by what happened here. The elves will return to Skemfar, to care for our own," announced Harald. "It will not be simple, even with the Doomskar finished. But the spells of our ancestors are capable of such feats and more."
"I suppose we'll have to get along until then," said Fynn, his jaw clenched tight.
"What will you do, Kaya?" asked Inga. "You still have a monster to catch, don't you?"
"Yeah," said Kaya. She hadn't forgotten about the thing in the cave, even though it seemed like a hundred years since her voyage with the Omenseekers. "No telling where it ended up after all this, though. And I've got a hunch that it can travel a lot farther than just between realms."
"What's beyond the realms?" asked Niko.
"The planes. It's all a bit complicated," said Kaya, waving her hand. She was too tired to explain it all again.
But Niko stepped forward, an odd eagerness in the stranger's eyes. "These planes. Is there one called Theros?"
Kaya looked at them in surprise. It was hard to believe that name mentioned here, now—but then, what about her day had been easy to believe? #emph[Another one] , she thought#emph[,] and sighed. "We should probably talk."
= Epilogue
Esika was dying. That wasn't supposed to happen—she was a god. It was by her hand, in fact, that the gods were freed from their mortality, from aging, from that final closing in of the dark. It was Esika who brewed the potion of divinity from the sap of the World Tree, the draught that kept death at bay, and yet she could feel the life escaping her. Running down her arms, her body, her face. She couldn't move her legs—she would have fallen to the ground by now, if the monster who had done this was not holding her up with one raw, flesh-colored claw. It tilted her to one side, regarding her with those dark, empty eye sockets. It had found her, this thing, in her sanctum, the place where she drew the sap and brewed the Cosmos Elixir. Nobody—nothing—had ever found her here.
#figure(image("009_Episode 5: The Battle for Kaldheim/14.jpg", width: 100%), caption: [Esika, God of the Tree | Art by: <NAME>], supplement: none, numbering: none)
A voice rose from the creature's throat, then—an odd amalgamation of tones and deliveries, as if the words had been stolen from other voices, synthesized into something new. "Not enough hunger in you. Not enough fear to survive. Soon, though."
It dropped her, then, and stalked back toward the well that ran to the heart of the tree.
Esika tried to raise her arms—she had never been a warrior, not like Halvar or Toralf, but she would fight with everything she had left to defend the World Tree. Her arms wouldn't obey her, though. She tried to shout, to call for help, but the only thing that came out was a bubbling, wet croak.
She watched, helpless, as the monster reached the well. What poison would it use? What corruption would it seed in this most sacred place?
#figure(image("009_Episode 5: The Battle for Kaldheim/15.jpg", width: 100%), caption: [Tyrite Sanctum | Art by: <NAME>], supplement: none, numbering: none)
To her surprise, it produced one of her own bottles. It must have taken one from her during their fight. She watched it dip the bottle into the well and hold it up to the light. Inside, the sap of the World Tree shimmered with all the colors of the realms. The most beautiful thing in this world—in any world, as far as Esika was concerned. If the monster was moved, it showed no sign.
"Sample acquired," it said, in that stitched-together voice. "I am ready to return."
To whom it was speaking, Esika had no idea.
The light in the room seemed to be fading, or maybe that was just her vision going out around the edges. Suddenly, there was a bright, strobing light in the center of the chamber—a hissing, sparking red glow that began as a single star and spread, slowly, into a circle. The circle widened—this was no Omenpath, she could see now. It was magic she had never seen before.
From the other side of the portal came a sound so unearthly and strange, she almost didn't recognize it as a voice: "#emph[Welcome back, Vorinclex. We step ever closer to perfection.] "
#figure(image("009_Episode 5: The Battle for Kaldheim/16.jpg", width: 100%), caption: [Vorinclex, Monstrous Raider | Art by: <NAME>], supplement: none, numbering: none)
|
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/kafka.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": autor
#autor("<NAME>", "1883", "1924 (40 let)", "úředník pojišťovny", "práva na UK", "existencialismus", "/cj-autori/media/kafka.jpg")
Byl součástí takzvané #underline[pražské německé školy], což byli autoři kteří působili v Praze v druhé polovině 19. a na začátku 20. století. Převážně to byli pražští rodáci. Většinou byli původem Židé (kterým byl i Kafka), a z tohoto důvodu mnozí z nich před rokem 1939 emigrovali.
Odhaduje se, že 90% svého díla zničil ještě za svého života. Sám vydal pouze malou část, co zbylo posmrtně vydal jeho dobrý přítel <NAME>, i přes Kafkovo přání spisy zničit.
Měl poměrně komplikovaný vztah s jeho otcem. Byl abstinent, nekuřák, vegetarián. Taky měl pletky s několika dívkami, ale nikdy se neoženil.
Většinu svého života bojoval s tuberkulózou na kterou nakonec i zemřel.
Mezi jeho známá díla patří:
1. *Proces* -- <NAME>. je nečekaně zatčen a postaven před tajný soud. Příběh zachycuje jeho zoufalý boj s neuchopitelným systémem a nejasnou byrokracií, která ovládá jeho osud. Den před svými narozeninami je odsouzen k smrti.
2. *Amerika* -- sleduje osudy šestnáctiletého chlapce, který je vyhnán ze svého domova v Evropě a cestuje do Ameriky. Příběh zachycuje jeho dobrodružství a setkání s různými podivnými postavami, zatímco se snaží najít své místo ve společnosti.
*Současníci*\
<NAME> -- Život plný bojů \
<NAME> "<NAME>" -- Pasák, 1914\
<NAME> -- Žid Suss, 1925
#pagebreak()
|
https://github.com/Rhinemann/mage-hack | https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Character%20Advancement.typ | typst | #import "../templates/interior_template.typ": *
#show: chapter.with(chapter_name: "Character Advancement")
= Character Advancement
#show: columns.with(2, gutter: 1em)
Milestones are a way to track progress and earn experience points (XP) that players then use to unlock character upgrades, as well as story unlockables and other narrative benefits in Mage.
Characters have two milestones. Often, one is shared by the entire group, while the other is chosen personally.
*Milestones have three different levels*:
/ 1 XP: can be hit as many times as it applies (or once per test or contest)
/ 3 XP: can only be hit once per scene
/ 10 XP: can only be hit once per session
#block(breakable: false)[
== Session Milestones
GMs can offer milestones at the start of a session or reveal them after major turning points in the session's ongoing narrative. Session milestones tie the PCs directly into the story, giving them personal motivations (and XP!) for becoming involved.
]
As you have two milestones, you can replace your current personal milestone with the session milestone, or if the GM allows, replace the group milestone until the session milestone is completed.
#block(breakable: false)[
== Unlockables
XP earned from achieving milestones may be spent between scenes to increase a PC's traits or to unlock other benefits. You may spend as much XP as you've earned to unlock multiple upgrades at once.
]
#block(breakable: false)[
=== Spend 1 XP to:
- Start the next game session with 1 extra Plot Point. (You can't start a game session with more than 5 Plot Points.)
]
#block(breakable: false)[
=== Spend 5 XP to:
- Raise a #spec_c.d4 skill to #spec_c.d6.
- Add a #spec_c.d6 signature asset or specialty.
- Rewrite a distinction.
]
#block(breakable: false)[
=== Spend 10 XP to:
- Add a new talent.
- Raise a #spec_c.d6 skill or signature asset to #spec_c.d8.
- Raise a #spec_c.d4 attribute to #spec_c.d6.
- Add a #spec_c.d4 Sphere.
]
#block(breakable: false)[
=== Spend 15 XP to:
- Raise a #spec_c.d8 skill or signature asset to #spec_c.d10.
- Raise a #spec_c.d6 attribute to #spec_c.d8.
- Raise a #spec_c.d4 Sphere to #spec_c.d6.
- Add a #spec_c.d6 to Quintessence pool size.
]
#block(breakable: false)[
=== Spend 20 XP to:
- Raise a #spec_c.d10 skill or signature asset to #spec_c.d12.
- Raise a #spec_c.d8 attribute to #spec_c.d10.
- Raise a #spec_c.d6 Sphere to #spec_c.d8.
]
#block(breakable: false)[
=== Spend 25 XP to:
- Raise a #spec_c.d10 attribute to #spec_c.d12.
- Raise a #spec_c.d8 Sphere to #spec_c.d10.
]
#block(breakable: false)[
=== Spend 30 XP to:
- Raise a #spec_c.d10 Sphere to #spec_c.d12.
]
|
|
https://github.com/mitinarseny/invoice | https://raw.githubusercontent.com/mitinarseny/invoice/main/src/payment.typ | typst | #import "./utils.typ": explorer_address, token_address
#let payment(details) = [
== Payment instructions
#v(1em)
To be paid in #token_address(
url_template: details.chain.explorer_address_template,
details.token
) on #details.chain.name to the following digital wallet address:
*#link(explorer_address(details.wallet, details.chain.explorer_address_template), raw(details.wallet))*.
] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.1.0/src/types/any.typ | typst | Apache License 2.0 | #import "../base-type.typ": base-type, assert-base-type
#import "../context.typ": context
/// Validation schema representing all types. *SHOULD* never produce an error.
///
/// - name (internal):
/// - default (any, none): Default value to validate is none is provided.
/// - custom (function): Function that maps an input to an output. If the function returns `none`, then an error *WILL* be generated using `custom-error`.
/// - custom-error (string): Error to return if custom function returns none.
/// - transform (function): Function that maps an input to an output, called after validation.
/// -> schema
#let any(
name: "any",
default: none,
custom: none,
custom-error: auto,
transform: it=>it,
) = {
assert( type(custom) in (function, type(none)), message: "Custom must be a function")
assert( type(custom-error) in (str, type(auto)), message: "Custom-error must be a string")
assert( type(transform) == function, message: "Transform must be a function that maps an input to an output")
return (:..base-type(),
name: name,
default: default,
custom: custom,
custom-error: custom-error,
transform: transform,
validate: (self, it, ctx: context(), scope: ()) => {
// Default value
if (it == none){ it = self.default }
// Custom
if ( self.custom != none ) and ( not (self.custom)(it) ){
let message = "Failed on custom check: " + repr(self.custom)
if ( self.custom-error != auto ){ message = self.custom-error }
return (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: message)
}
return (self.transform)(it)
}
)
} |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/linebreak_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Inline, in a box, doesn't linebreak.
#let hrule(x) = box(line(length: x))
#hrule(80pt)#box($a+b$)
|
https://github.com/piepert/grape-suite | https://raw.githubusercontent.com/piepert/grape-suite/main/src/tasks.typ | typst | MIT License | #import "colors.typ" as colors: *
#import "elements.typ" as elements: *
#let nobreak(body) = block(breakable: false, body)
#let center-block(body) = align(center, block(align(left, body)))
#let big-heading(title) = {
set par(justify: false)
set text(hyphenate: false)
pad(bottom: 0.5cm,
align(center,
text(fill: purple,
size: 1.75em,
strong(title))))
}
#let make-element(type, no, title, body) = {
block(inset: 7pt,
stroke: (bottom: (paint: purple, dash: "dashed")),
fill: blue.lighten(75%), {
text(fill: purple, strong[#type #no] + title)
})
block(body)
v(0.5cm)
}
#let make-task(no, title, instruction, body, extra, points, lines, extra-task-type, task-type) = {
make-element(if extra {extra-task-type} else {task-type},
no,
if title != none [ --- #title] + h(1fr) + if points != none and points > 0 { [#points P.] },
block(width: 100%, {
state("grape-suite-subtask-indent").update((0,))
if instruction != none and instruction not in ([], [ ]) {
block(emph(instruction))
}
state("grape-suite-subtask-indent").update((0,))
if body != none { block(body) }
context {
if state("grape-suite-show-lines").at(here()) == false {
return
}
for i in range(0, lines) {
v(0.75cm)
v(-1.2em)
line(length: 100%, stroke: black.lighten(50%))
}
}
}))
}
#let make-solution(no, title, instruction, body, extra, points, solution, solution-type) = {
make-element(solution-type,
no,
title + h(1fr) + if points != none and points > 0 { [#points P.] },
block(width: 100%, {
state("grape-suite-subtask-indent").update((0,))
if instruction != none {
block(emph(instruction))
}
state("grape-suite-subtask-indent").update((0,))
if body != none {
block(body)
}
state("grape-suite-subtask-indent").update((0,))
elements.solution(solution)
state("grape-suite-subtask-indent").update((0,))
}))
}
#let make-hint(no, title, instruction, body, extra, points, hint, hint-type) = {
make-element(hint-type,
no,
title + h(1fr) + if points != none and points > 0 { [#points P.] },
block(width: 100%, {
state("grape-suite-subtask-indent").update((0,))
if instruction != none {
block(emph(instruction))
}
state("grape-suite-subtask-indent").update((0,))
if body != none {
block(body)
}
state("grape-suite-subtask-indent").update((0,))
elements.hint(hint)
state("grape-suite-subtask-indent").update((0,))
}))
}
#let make-solutions(here,
solution-type
) = {
let tasks = state("grape-suite-tasks").at(here)
if tasks == none {
return
}
for task in tasks {
if task.solution == none {
continue
}
make-solution(task.no,
task.title,
task.instruction,
task.body,
task.extra,
task.points,
task.solution,
solution-type)
}
}
#let make-hints(loc,
hint-type,
) = {
let tasks = state("grape-suite-tasks").at(loc)
if tasks == none {
return
}
let tasks = state("grape-suite-tasks").at(loc)
if tasks == none {
return
}
for task in tasks {
if task.hint == none {
continue
}
make-hint(task.no,
task.title,
task.instruction,
task.body,
task.extra,
task.points,
task.hint,
hint-type)
}
}
#let make-matrix-row(show-comment-field: false,
comment-field-value: none,
no,
title,
extra,
points,
solutions,
task-type,
extra-task-type) = {
let e = (
table.hline(stroke: purple),
table.cell(fill: blue.lighten(75%),
strong(if extra [#extra-task-type ] else [#task-type ]) +
strong(no) + if title != none [ --- #title]),
table.cell(fill: blue.lighten(75%),
align(center, strong[#box(line(length: 0.75cm)) / #points])),
table.hline(stroke: purple),
..solutions.map(e => (
e.at(1),
align(center, box(line(length: 0.75cm)) + [ \/ #e.at(0)]),
table.hline(stroke: (paint: purple, dash: "dashed")),
)).flatten()
)
if show-comment-field {
e.push(table.cell(colspan: 2, comment-field-value))
}
return e
}
#let make-solution-matrix(
show-comment-field: false,
comment-field-value: none,
loc,
matrix-task-header,
task-type,
extra-task-type,
achieved-points
) = {
let tasks = state("grape-suite-tasks").at(loc)
if tasks == none {
return
}
let tasks = state("grape-suite-tasks").at(loc)
if tasks == none {
return
}
table(
columns: (1fr, 3cm),
stroke: none,
inset: (x: 1em, y: 0.75em),
table.cell(fill: purple, text(fill: white,
align(horizon, strong(matrix-task-header)))),
table.vline(stroke: purple),
table.cell(fill: purple, text(fill: white,
align(center, strong(achieved-points)))),
..tasks
.filter(task =>
not task.extra and
task.solution != none and
type(task.solution) == array)
.map(task => {
make-matrix-row(show-comment-field: show-comment-field,
comment-field-value: comment-field-value,
task.no,
task.title,
task.extra,
task.points,
task.solution,
task.task-type,
task.extra-task-type)}).flatten(),
table.cell(colspan: 2, fill: purple, v(-10pt)),
..(if tasks.filter(task => task.extra and
task.solution != none and
type(task.solution) == array).len() > 0 {
(
tasks.filter(task =>
task.extra and
task.solution != none and
type(task.solution) == array)
.map(task => {
make-matrix-row(show-comment-field: show-comment-field,
comment-field-value: comment-field-value,
task.no,
task.title,
task.extra,
task.points,
task.solution,
task-type,
extra-task-type)}).flatten(),
table.cell(colspan: 2, fill: purple, v(-10pt))
)
} else { () }).flatten(),
[], [
#show: align.with(center)
#box(line(length: 0.75cm)) /
#tasks.filter(e => not e.extra and not e.ignore-points).map(e => e.points).sum(default: 0) + #tasks.filter(e => e.extra and not e.ignore-points).map(e => e.points).sum(default: 0) P.
#v(-0.5em)
#line(length: 100%)
#v(-1em)
#line(length: 100%)
]
)
}
#let make-point-distribution(loc,
message,
grade-scale,
header-point-value,
header-point-grade
) = {
let points = state("grape-suite-tasks").at(loc)
let points-sum = points.filter(e => not e.extra and not e.ignore-points).map(e => e.points).sum(default: 0)
let extrapoints-sum = points.filter(e => e.extra and not e.ignore-points).map(e => e.points).sum(default: 0)
let points-sum-all = points-sum + extrapoints-sum
if points-sum-all > 0 {
v(1fr)
set text(fill: purple)
block(fill: blue.lighten(75%),
breakable: false,
stroke: purple,
inset: 1em,
width: 100%, {
message(points-sum, extrapoints-sum)
let f(from, to) = {
from = calc.round(from)
to = calc.round(to)
if from == to [#from] else [#from -- #to]
}
/*
let n = 3
let top-socket = points-sum * 0.9
let bottom-socket = points-sum * 0.5
let point-distribution = (f(points-sum, top-socket),)
let last-to = top-socket
for i in range(0, n) {
let to = calc.min(last-to - 1, top-socket - (top-socket - bottom-socket) / n * (i + 1))
point-distribution.push(f(last-to - 1, to))
last-to = to
}
point-distribution.push(f(last-to - 1, 0))
*/
let grade-scale = grade-scale.map(e => {
e.at(1) = calc.floor(e.at(1)*points-sum)
e
}).enumerate()
center-block(table(
columns: grade-scale.len() + 1,
stroke: none,
align: center,
strong(header-point-value), ..grade-scale.map(e => {
let (index, (_, p)) = e
let last-to = if index > 0 {
grade-scale.at(index - 1).last().last() - 1
} else {
points-sum
}
let to = calc.min(last-to, p)
if index + 1 >= grade-scale.len() {
to = 0
}
if last-to == to [#to] else [#last-to#[--]#to]
}),
table.hline(stroke: 1pt + purple),
strong(header-point-grade),
..grade-scale
.rev()
.map(e => (table.vline(stroke: 1pt + purple), text(size: 0.95em, e.at(1).first())))
.rev()
.flatten(),
))
})
}
}
#let task(
// number of lines to draw if show-lines of exercise-template is enabled
lines: 0,
// number of points, subtask points will be added
points: 0,
// is extra task?
extra: false,
// iff true, ignore points in final sum and solution matrix
ignore-points: false,
// numbering of task
numbering-format: none,
// type of task
type: none,
// Titel der Aufgabe
title,
// Aufgabenstellung
instruction,
// optional: body, solution (see exercise.project(show-solutions-as-matrix: ...) !), hint
..args
) = counter(if extra { "tasks" } else { "extra-tasks" }).step() + context {
let task-translation-state = state("grape-suite-task-translations", (task-type: [Task], extra-task-type: [Extra task]))
let task-type = task-translation-state.final().task-type
let extra-task-type = task-translation-state.final().extra-task-type
let numbering-format = numbering-format
if numbering-format == none {
numbering-format = (..c) => numbering(if extra { "1" } else { "A" }, ..c)
}
let args = args.pos()
let no = numbering-format(..counter(if extra { "tasks" } else { "extra-tasks" }).at(here()))
let t = (
no: no,
title: title,
instruction: instruction,
body: args.at(0, default: none),
solution: args.at(1, default: none),
hint: args.at(2, default: none),
points: points,
extra: extra,
ignore-points: ignore-points,
extra-task-type: if type != none {type} else {extra-task-type},
task-type: if type != none {type} else {task-type}
)
if t.body == [] or t.body == [ ] {
t.body = none
}
state("grape-suite-tasks", ()).update(k => {
k.push(t)
return k
})
state("grape-suite-subtask-indent").update((0,))
// let t = state("grape-suite-tasks", ()).final().last()
make-task(no,
title,
instruction,
t.body,
t.extra,
t.points,
lines,
if type != none {type} else {extra-task-type},
if type != none {type} else {task-type})
}
#let subtask(points: 0,
tight: false,
ignore-points: false,
markers: ("1.", "a)"),
show-points: true,
counter: none,
content) = {
if points != none and type(points) == int and not ignore-points {
state("grape-suite-tasks", ()).update(k => {
if k.len() == 0 {
return k
}
let li = k.len() - 1
let e = k.at(li)
e.points += points
k.at(li) = e
return k
})
}
state("grape-suite-subtask-indent", (0,)).update(k => {
k.push(0)
k
})
context {
let indent = state("grape-suite-subtask-indent").at(here())
let num = if counter == none {
indent.at(indent.len() - 2) + 1
} else {
counter
}
let marker = if indent.len() - 2 >= markers.len() {
"i."
} else {
markers.at(indent.len() - 2)
}
enum(numbering: (_) => numbering(marker, num), tight: tight, if points != none and points > 0 and show-points {
place(dx: 100%, [#points P.])
block(width: 95%, content)
} else {
content
})
}
state("grape-suite-subtask-indent", (0,)).update(k => {
k = k.slice(0, k.len() - 1)
if k.len() > 0 {
k.last() = k.last() + 1
}
k
})
} |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/frac_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 8-13 missing argument: lower
// $ binom(x^2) $ |
https://github.com/typst-jp/typst-jp.github.io | https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/reference/scripting.md | markdown | Apache License 2.0 | ---
description: Typstのスクリプト記述機能を用いて、ドキュメントを自動化しましょう。
---
# スクリプト記述
Typstには強力なスクリプト言語が組み込まれています。これにより、ドキュメントを自動化し、コードを使用してより洗練されたスタイルを作成できます。
以下は、スクリプト記述の概念の概要です。
## 式 { #expressions }
Typstでは、マークアップとコードが一体となっています。
最も一般的な要素以外のものは _関数_ を使って作成されます。
これを可能な限り便利にするため、Typstはコード式をマークアップに埋め込むためのコンパクトな構文を提供しています。式はハッシュ(`#`)で始まり、
この式が終了すると通常のマークアップの解析が再開されます。
式の直後に通常の文字列として解釈されるべき文字が続く場合、セミコロン(`;`)を使って式を強制的に終了できます。
```example
#emph[Hello] \
#emoji.face \
#"hello".len()
```
上記の例では、[関数呼び出し]($function)、
[フィールドアクセス]($scripting/#fields)、
そして[メソッド呼び出し]($scripting/#methods)などのいくつかの使用可能な式を示しています。
この章の残りでは、より多くの種類の式について説明します。
いくつかの種類の式はハッシュ構文と互換性がありません(例えば二項演算子式)。
このような式をマークアップに埋め込むためには、`[#(1+2)]`のように丸括弧を使用します。
## ブロック { #blocks }
コードを構造化し、マークアップを埋め込むために、Typstは次の二種類の _ブロック_ を提供します。
- **コードブロック** `{{ let x = 1; x + 2 }}` \
コードを書く際には、計算を複数のステートメントに分割したり、中間変数を作成したりすることがあるでしょう。
コードブロックを使用すると、複数の式を一つのブロックにまとめられます。ブロック内の個々の式は改行またはセミコロンで区切られます。
コードブロック内の個々の式の出力値は結合され、ブロックの値を決定します。
`{let}`バインディングのように有用な出力のない式は`{none}`を生成し、これはどの値とも影響なく結合できます。
- **コンテンツブロック** `{[*Hey* there!]}` \
コンテンツブロックを使用すると、マークアップやコンテンツをプログラム的な値として扱い、変数に保存したり、[関数]($function)に渡したりできます。
コンテンツブロックは角括弧で囲まれ、任意のマークアップを含められます。
コンテンツブロックは[content]($content)型の値を生成します。
任意の数のコンテンツブロックを可変長引数として関数に渡せます。つまり、`{list[A][B]}`は`{list([A], [B])}`と等価です。
コンテンツブロックとコードブロックは任意にネストできます。以下の例では、`{[hello]}`が`{a + [ the ] + b}`の出力と結合され、`{[hello from the *world*]}`が生成されます。
```example
#{
let a = [from]
let b = [*world*]
[hello ]
a + [ the ] + b
}
```
## バインディングと分割 { #bindings }
前述のように、変数は`{let}`バインディングで定義できます。
変数には`=`記号のあとに続く式の値が代入されます。値の代入は任意であり、値が代入されなければ変数は`{none}`として初期化されます。
`{let}`キーワードは、[カスタム名前付き関数]($function/#defining-functions)を作成するためにも使用できます。
変数は、それが含まれるブロックの残りの部分(または、変数が含まれるブロックがない場合はファイル全体)の中でアクセスできます。
```example
#let name = "Typst"
This is #name's documentation.
It explains #name.
#let add(x, y) = x + y
Sum is #add(2, 3).
```
letバインディングは[配列]($array)や[辞書]($dictionary)の分割にも使用できます。
この場合、代入の左辺は配列や辞書と同じ形式でなければなりません。
`..`演算子はパターン内で一度だけ、配列や辞書の残りの項目を受け取るために使用できます。
```example
#let (x, y) = (1, 2)
The coordinates are #x, #y.
#let (a, .., b) = (1, 2, 3, 4)
The first element is #a.
The last element is #b.
#let books = (
Shakespeare: "Hamlet",
Homer: "The Odyssey",
Austen: "Persuasion",
)
#let (Austen,) = books
Austen wrote #Austen.
#let (Homer: h) = books
Homer wrote #h.
#let (Homer, ..other) = books
#for (author, title) in other [
#author wrote #title.
]
```
分割パターンでアンダースコアを使用して、要素を破棄できます。
```example
#let (_, y, _) = (1, 2, 3)
The y coordinate is #y.
```
分割は関数の引数リスト内でも機能します。
```example
#let left = (2, 4, 5)
#let right = (3, 2, 6)
#left.zip(right).map(
((a,b)) => a + b
)
```
そして通常の代入の左辺でも機能します。これは、変数の値を交換するなどの場合に便利です。
```example
#{
let a = 1
let b = 2
(a, b) = (b, a)
[a = #a, b = #b]
}
```
## 条件式 { #conditionals }
条件式を使用すると、ある条件が満たされているかどうかに応じて、異なるものを表示したり計算したりできます。
Typstは`{if}`式、`{else if}`式、および`{else}`式をサポートしています。
条件が`{true}`の場合、条件式は`if`の部分の結果が得られ、そうでない場合は`else`の部分の結果が得られます。
```example
#if 1 < 2 [
This is shown
] else [
This is not.
]
```
各条件分岐は、その本文としてコードブロックまたはコンテンツブロックを含められます。
- `{if condition {..}}`
- `{if condition [..]}`
- `{if condition [..] else {..}}`
- `{if condition [..] else if condition {..} else [..]}`
## ループ { #loops }
ループを使用すると、コンテンツを繰り返したり、何かを反復的に計算したりできます。
Typstは、`{for}`ループと`{while}`ループの2つのループをサポートしています。
前者は指定されたコレクションを反復するのに対し、後者は条件が満たされている限り反復を続けます。
ブロックと同様に、ループは各反復からの結果を一つの値に _結合_ します。
以下の例では、forループによって作成された3つの文が1つのコンテンツ値に結合され、whileループの中の長さ1の配列が1つの大きな配列に結合されます。
```example
#for c in "ABC" [
#c is a letter.
]
#let n = 2
#while n < 10 {
n = (n * 2) - 1
(n,)
}
```
forループはさまざまなコレクションを反復処理できます。
- `{for value in array {..}}` \
[配列]($array)内の各項目を反復処理します。[letバインディング]($scripting/#bindings)で説明されている分割構文もここで使用できます。
- `{for pair in dict {..}}` \
[辞書]($dictionary)のキーと値のペアを反復処理します。ペアは`{for (key, value) in dict {..}}`を使用しても分割できます。これは、すべてのキーと値のペアの一時配列を作成しないため、`{for pair in dict.pairs() {..}}`よりも効率的です。
- `{for letter in "abc" {..}}` \
[文字列]($str)の各文字を反復処理します。厳密に言うと、文字列の書記素クラスタの反復処理を行います。ほとんどの場合、書記素クラスタは単一のコードポイントに対応します。しかし、書記素クラスタは複数のコードポイントを含むことがあります。例えば、国旗の絵文字などです。
- `{for byte in bytes("😀") {..}}` \
[文字列]($str)から変換されたり、エンコーディングなしでファイルから[読み取る]($read)ことができる[バイト]($bytes)を反復処理します。各バイト値は`{0}`から`{255}`までの[整数]($int)です。
ループの実行を制御するために、Typstは`{break}`と`{continue}`ステートメントを提供しています。
前者はループを早期終了し、後者はループの次の反復を開始します。
```example
#for letter in "abc nope" {
if letter == " " {
break
}
letter
}
```
ループの本体はコードブロックまたはコンテンツブロックにできます。
- `{for .. in collection {..}}`
- `{for .. in collection [..]}`
- `{while condition {..}}`
- `{while condition [..]}`
## フィールド { #fields }
_ドット記法_ を使用することで値のフィールドにアクセスできます。[コンテンツ]($content)型の値については、[fields]($content.fields)関数を使用してフィールドを一覧表示できます。
対象の値は以下のいずれかです。
- 指定されたキーを持つ[辞書]($dictionary)、
- 指定された修飾子を持つ[記号]($symbol)、
- 指定された定義を含む[モジュール]($module)、
- 指定されたフィールドを持つ要素で構成された[コンテンツ]($content)。利用可能なフィールドは、その要素が構築された際に与えられた[要素関数]($function/#element-functions)の引数と一致します。
```example
#let it = [= Heading]
#it.body \
#it.depth \
#it.fields()
#let dict = (greet: "Hello")
#dict.greet \
#emoji.face
```
## メソッド { #methods }
メソッド呼び出しは、値の[型]($type)で定義された関数を呼び出す便利な方法です。
例えば、[`str.len`]($str.len)関数は下記の2つの同等の方法で呼び出せます。
```example
#str.len("abc") is the same as
#"abc".len()
```
メソッド呼び出しの構造は`{value.method(..args)}`であり、これと等価である完全な関数呼び出しは`{type(value).method(value, ..args)}`です。各型のドキュメントには、その型に関連付けられた関数が一覧表示されています。現在、独自のメソッドは定義できません
```example
#let values = (1, 2, 3, 4)
#values.pop() \
#values.len() \
#("a, b, c"
.split(", ")
.join[ --- ])
#"abc".len() is the same as
#str.len("abc")
```
特定の値に対して呼び出された際に、その値を変更する特別な関数がいくつかあります(例: [`array.push`]($array.push))。
これらの関数は、_必ず_ メソッド形式で呼び出す必要があります。
場合によっては、メソッドが副作用のためだけに呼び出されるとき、その戻り値は無視されるべきです(結合に加わるべきではありません)。
値を破棄する標準的な方法は、`{let _ = array.remove(1)}`のように
letバインディングを使用することです。
## モジュール { #modules }
Typstプロジェクトを、_モジュール_ と呼ばれる複数のファイルに分割できます。
モジュールは他のモジュールの内容や定義を複数の方法で参照できます。
- **インクルード:** `{include "bar.typ"}` \
パス`bar.typ`にあるファイルを評価し、その結果として得られる[コンテンツ]($content)を返します。
- **インポート:** `{import "bar.typ"}` \
パス`bar.typ`にあるファイルを評価し、その結果として得られる
[モジュール]($module)を現在のスコープに`bar`(拡張子なしのファイル名)として挿入します。次のように、`as`キーワードを使用してモジュール名を変更できます。
`{import "bar.typ" as baz}`
You can import nested items using dot notation: `{import "bar.typ": baz.a}`.
- **アイテムのインポート:** `{import "bar.typ": a, b}` \
パス`bar.typ`にあるファイルを評価して、変数`a`と`b`の値
(これらは`bar.typ`で、例えば`{let}`バインディングを通じて定義されている必要があります)
を抽出し、現在のファイルで定義します。 `a, b`を`*`に置き換えると、モジュールで定義されたすべての変数が読み込まれます。
次のように、`as`キーワードを使用してモジュール名を変更できます。
`{import "bar.typ": a as one, b as two}`
以下の例に示すように、パスの代わりに[モジュール値]($module)を使用できます。
```example
#import emoji: face
#face.grin
```
## パッケージ { #packages }
プロジェクト間でビルド中のブロックを再利用するために、Typstの _パッケージ_ を作成してインポートできます。
パッケージのインポートは、名前空間、名前、バージョンの3つの組み合わせとして指定されます。
```example
>>> #let add(x, y) = x + y
<<< #import "@preview/example:0.1.0": add
#add(2, 7)
```
`preview`名前空間には、コミュニティで共有されているパッケージが含まれています。すべての利用可能なコミュニティパッケージは[Typst Universe]($universe)にあります。
Typstをローカルで使用している場合、独自のシステムローカルパッケージを作成できます。詳細については、[パッケージリポジトリ](https://github.com/typst/packages)を参照してください。
## 演算子 { #operators }
以下の表は、使用可能なすべての単項および二項演算子の効果、引数の個数(単項あるいは二項)、および優先度(高いほど強く結合)を示しています。
| 演算子 | 効果 | 引数の個数 | 優先度 |
| :--------: | ------------------------------------ | :--------: | :----: |
| `{-}` | 負号 | 単項 | 7 |
| `{+}` | 効果なし (対称性のために存在) | 単項 | 7 |
| `{*}` | 乗算 | 二項 | 6 |
| `{/}` | 除算 | 二項 | 6 |
| `{+}` | 加算 | 二項 | 5 |
| `{-}` | 減算 | 二項 | 5 |
| `{==}` | 等価性の評価 | 二項 | 4 |
| `{!=}` | 非等価性の評価 | 二項 | 4 |
| `{<}` | 小なりの評価 | 二項 | 4 |
| `{<=}` | 以下の評価 | 二項 | 4 |
| `{>}` | 大なりの評価 | 二項 | 4 |
| `{>=}` | 以上の評価 | 二項 | 4 |
| `{in}` | コレクション内に存在することの評価 | 二項 | 4 |
| `{not in}` | コレクション内に存在しないことの評価 | 二項 | 4 |
| `{not}` | 論理否定 | 単項 | 3 |
| `{and}` | 短絡論理積 | 二項 | 3 |
| `{or}` | 短絡論理和 | 二項 | 2 |
| `{=}` | 代入 | 二項 | 1 |
| `{+=}` | 加算代入 | 二項 | 1 |
| `{-=}` | 減算代入 | 二項 | 1 |
| `{*=}` | 乗算代入 | 二項 | 1 |
| `{/=}` | 除算代入 | 二項 | 1 |
[semver]: https://semver.org/
|
https://github.com/8LWXpg/typst-treet | https://raw.githubusercontent.com/8LWXpg/typst-treet/master/lib.typ | typst | MIT License | #let tree-list(
marker: [├─ ],
last-marker: [└─ ],
indent: [│#h(1em)],
empty-indent: [#h(1.5em)],
marker-font: "Cascadia Code",
content,
) = {
marker = text(font: marker-font, marker)
last-marker = text(font: marker-font, last-marker)
indent = text(font: marker-font, indent)
empty-indent = text(font: marker-font, empty-indent)
let format(content, __indent: [], __marker: marker) = {
let body = content.body
if body.has("children") {
// children in the iter should looks like [content..., item...]
let iter = body.children
// render item body, remaining iter should looks like [item...]
[#__marker#while (iter.len() > 0) and (not iter.at(0).func() == list.item) {
iter.remove(0)
}\ ]
if iter.len() == 0 {
return
}
// remove [ ] from the iter
let iter = iter.filter(i => i.fields() != (:))
let last = iter.pop()
for i in iter {
[#__indent#format(i, __indent: [#__indent#indent])]
}
[#__indent#format(last, __indent: [#__indent#empty-indent], __marker: last-marker)]
} else {
[#__marker#body\ ]
}
}
let iter = content.children.filter(i => i.fields() != (:))
let last = iter.pop()
for i in iter {
[#format(i, __indent: indent)]
}
[#format(last, __indent: empty-indent, __marker: last-marker)]
}
|
https://github.com/Tyrn/wei | https://raw.githubusercontent.com/Tyrn/wei/master/robinson-toc.typ | typst | #let calc-elem-size(elem, sizes: (12pt, 10pt, 8pt, 6pt,4pt)) = {
let size = 3pt
if elem.level - 2 < sizes.len() {
size = sizes.at(elem.level - 2)
}
return size
}
// randomly generated IDs
#let gs = state("VIvouA", ()) // global state that stores all headings and associated summaries
#let elemcounter = counter("k1lRPA") // counter, used to display the outline correctly
// Use a custom supplement to know
// which headings should be included in the TOC
#let supl = [Symmaryst Heading]
#let style-outline(ol, outline-title: [Table of Contents]) = [
#set par(first-line-indent: 0.01pt)
// for some reason setting first-line-indent to
// exactly 0pt messes with the outline summaries
#show heading: it => [
// Ignore headings not made through the `make-heading` (in this case the summary)
#if it.supplement != supl {
return none
}
]
#show outline.entry: it => {
if it.element.supplement != supl {
// ignore headings not made `make-heading`
// use -2em so as to not take up any space
return v(-2em)
}
let lvl = it.element.level
let loc = it.element.location()
context {
// Get all the elements that were added to the document
let idx = calc.rem(elemcounter.get().first(), gs.final().len())
let (cnt, subcnt) = gs.final().at(idx)
// style h1's differently from lower level headings
if lvl == 1 {
return box(link(loc)[
#v(30pt)
#set align(center)
#smallcaps[#text(
size: 18pt
)[#cnt]]
#set align(left)
#subcnt
])
}
// else
return box(link(loc)[
#let size = calc-elem-size(it.element)
#set align(center)
#smallcaps[#text(
size: size
)[#cnt]]
#set align(left)
#subcnt #box(width: 1fr, repeat[.]) #it.page
])
}
elemcounter.step()
}
#if outline-title != none [
#text(size: 18pt, weight: 500)[
#set align(center)
#outline-title
]
]
#ol
#pagebreak()
#counter(page).update(1)
]
#let make-heading(cnt, subcnt, level: 1) = [
#gs.update(x => {
// Update the state by including the content and summary
x.push((cnt, subcnt))
x
})
#heading(level: level, supplement: supl)[#box(width: 100%)[
#v(2.5em)
#set align(center)
#cnt
#v(.5em)
#text(size: 11pt, weight: "regular", style: "italic")[
#box(width: 80%)[#subcnt]
]
#v(.5em)
]]
]
#let part(title, content) = {
make-heading(title, content)
}
#let chapter(title, content) = {
make-heading(title, content, level: 2)
}
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/188.%20orth.html.typ | typst | orth.html
Orthodox Privilege
July 2020
"Few people are capable of expressing with equanimity opinions which differ from the prejudices of their social environment. Most people are even incapable of forming such opinions."� Einstein
There has been a lot of talk about privilege lately. Although the
concept is overused, there is something to it, and in particular
to the idea that privilege makes you blind � that you can't see
things that are visible to someone whose life is very different
from yours.But one of the most pervasive examples of this kind of blindness
is one that I haven't seen mentioned explicitly. I'm going to call
it orthodox privilege: The more conventional-minded someone is, the
more it seems to them that it's safe for everyone to express their
opinions.It's safe for them to express their opinions, because the source
of their opinions is whatever it's currently acceptable to believe.
So it seems to them that it must be safe for everyone. They literally
can't imagine a true statement that would get you in trouble.And yet at every point in history, there were
true things that would
get you in trouble to say.
Is ours the first where this
isn't so? What an amazing coincidence that would be.Surely it should at least be the default assumption that our time
is not unique, and that there are true things you can't say now,
just as there have always been. You would think. But even in the
face of such overwhelming historical evidence, most people will go
with their gut on this one.In the most extreme cases, people suffering from orthodox
privilege will not only deny that there's anything true that
you can't say, but will accuse you of heresy merely for saying there is.
Though if there's more than one heresy current in
your time, these accusations will be weirdly non-deterministic:
you must either be an xist or a yist.Frustrating as it is to deal with these people, it's important to
realize that they're in earnest. They're not pretending they think
it's impossible for an idea to be both unorthodox and true. The
world really looks that way to them.Indeed, this is a uniquely tenacious form of privilege. People can
overcome the blindness induced by most forms of privilege by learning
more about whatever they're not. But they can't overcome orthodox
privilege just by learning more. They'd have to become more
independent-minded. If that happens at all, it doesn't happen on
the time scale of one conversation.It may be possible to convince some people that orthodox privilege
must exist even though they can't sense it, just as one can with,
say, dark matter. There may be some who could be convinced, for
example, that it's very unlikely that this is the first point in
history at which there's nothing true you can't say, even if they
can't imagine specific examples.But in general I don't think it will work to say
"check your privilege" about this type of privilege, because those
in its demographic don't realize they're in it. It doesn't seem to
conventional-minded people that they're conventional-minded. It
just seems to them that they're right. Indeed, they tend to be
particularly sure of it.Perhaps the solution is to appeal to politeness. If someone says
they can hear a high-pitched noise that you can't, it's only polite
to take them at their word, instead of demanding evidence that's
impossible to produce, or simply denying that they hear anything.
Imagine how rude that would seem. Similarly, if someone says they
can think of things that are true but that cannot be said, it's
only polite to take them at their word, even if you can't think of
any yourself.
Thanks to <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and
<NAME> for reading drafts of this.
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/text/raw-line.typ | typst | Apache License 2.0 | // Test line in raw code.
---
#set page(width: 200pt)
```rs
fn main() {
println!("Hello, world!");
}
```
#show raw.line: it => {
box(stack(
dir: ltr,
box(width: 15pt)[#it.number],
it.body,
))
linebreak()
}
```rs
fn main() {
println!("Hello, world!");
}
```
---
#set page(width: 200pt)
#show raw: it => stack(dir: ttb, ..it.lines)
#show raw.line: it => {
box(
width: 100%,
height: 1.75em,
inset: 0.25em,
fill: if calc.rem(it.number, 2) == 0 {
luma(90%)
} else {
white
},
align(horizon, stack(
dir: ltr,
box(width: 15pt)[#it.number],
it.body,
))
)
}
```typ
#show raw.line: block.with(
fill: luma(60%)
);
Hello, world!
= A heading for good measure
```
---
#set page(width: 200pt)
#show raw.line: set text(fill: red)
```py
import numpy as np
def f(x):
return x**2
x = np.linspace(0, 10, 100)
y = f(x)
print(x)
print(y)
```
---
// Ref: false
// Test line extraction works.
#show raw: code => {
for i in code.lines {
test(i.count, 10)
}
test(code.lines.at(0).text, "import numpy as np")
test(code.lines.at(1).text, "")
test(code.lines.at(2).text, "def f(x):")
test(code.lines.at(3).text, " return x**2")
test(code.lines.at(4).text, "")
test(code.lines.at(5).text, "x = np.linspace(0, 10, 100)")
test(code.lines.at(6).text, "y = f(x)")
test(code.lines.at(7).text, "")
test(code.lines.at(8).text, "print(x)")
test(code.lines.at(9).text, "print(y)")
test(code.lines.at(10, default: none), none)
}
```py
import numpy as np
def f(x):
return x**2
x = np.linspace(0, 10, 100)
y = f(x)
print(x)
print(y)
```
|
https://github.com/nvarner/typst-lsp | https://raw.githubusercontent.com/nvarner/typst-lsp/master/editors/vscode/LICENSE.md | markdown | MIT License | typst-lsp is dual-licensed under either
- MIT License ([../../LICENSE-MIT.txt](../../LICENSE-MIT.txt) or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 ([../../LICENSE-APACHE-2.0.txt](../../LICENSE-APACHE-2.0.txt) or http://www.apache.org/licenses/LICENSE-2.0)
at your option.
|
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/cartridges/mbc1.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "../../common.typ": *
== MBC1 mapper chip
The majority of games for the original Game Boy use the MBC1 chip. MBC1 supports ROM sizes up to 16 Mbit (128 banks of #hex("4000") bytes) and RAM sizes up to 256 Kbit (4 banks of #hex("2000") bytes). The information in this section is based on my MBC1 research, Tauwasser's research notes @tauwasser_mbc1, and Pan Docs @pandocs.
=== MBC1 registers
#caveat[
These registers don't have any standard names and are usually referred to using their address ranges or purposes instead. This document uses names to clarify which register is meant when referring to one.
]
The MBC1 chip includes four registers that affect the behaviour of the chip. Of the cartridge bus address signals, only A13-A15 are connected to the MBC, so lower address bits don't matter when the CPU is accessing the MBC and all registers are effectively mapped to address ranges instead of single addresses. All registers are smaller than 8 bits, and unused bits are simply ignored during writes. The registers are not directly readable.
#reg-figure(
caption: [#hex-range("0000", "1FFF") - RAMG - MBC1 RAM gate register]
)[
#reg-table(
[U], [U], [U], [U], [W-0], [W-0], [W-0], [W-0],
unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), table.cell(colspan: 4)[RAMG\<3:0\>],
[bit 7], [6], [5], [4], [3], [2], [1], [bit 0]
)
#set align(left)
#grid(
columns: (auto, 1fr),
gutter: 1em,
[*bit 7-4*], [*Unimplemented*: Ignored during writes],
[*bit 3-0*], [
*RAMG\<3:0\>*: RAM gate register\
#bin("1010") = enable access to chip RAM\
All other values disable access to chip RAM
]
)
]
The RAMG register is used to enable access to the cartridge SRAM if one exists on the cartridge circuit board. RAM access is disabled by default but can be enabled by writing to the #hex-range("0000", "1FFF") address range a value with the bit pattern #bin("1010") in the lower nibble. Upper bits don't matter, but any other bit pattern in the lower nibble disables access to RAM.
When RAM access is disabled, all writes to the external RAM area #hex-range("A000", "BFFF") are ignored, and reads return undefined values. Pan Docs recommends disabling RAM when it's not being accessed to protect the contents @pandocs.
#speculation[
We don't know the physical implementation of RAMG, but it's certainly possible that the #bin("1010") bit pattern check is done at write time and the register actually consists of just a single bit.
]
#reg-figure(
caption: [#hex-range("2000", "3FFF") - BANK1 - MBC1 bank register 1]
)[
#reg-table(
[U], [U], [U], [W-0], [W-0], [W-0], [W-0], [W-1],
unimpl-bit(), unimpl-bit(), unimpl-bit(), table.cell(colspan: 5)[BANK1\<4:0\>],
[bit 7], [6], [5], [4], [3], [2], [1], [bit 0]
)
#set align(left)
#grid(
columns: (auto, 1fr),
gutter: 1em,
[*bit 7-5*], [*Unimplemented*: Ignored during writes],
[*bit 4-0*], [
*BANK1\<4:0\>*: Bank register 1\
Never contains the value #bin("00000").\
If #bin("00000") is written, the resulting value will be #bin("00001") instead.
]
)
]
The 5-bit BANK1 register is used as the lower 5 bits of the ROM bank number when the CPU accesses the #hex-range("4000", "7FFF") memory area.
MBC1 doesn't allow the BANK1 register to contain zero (bit pattern #bin("00000")), so the initial value at reset is #bin("00001") and attempting to write #bin("00000") will write #bin("00001") instead. This makes it impossible to read banks #hex("00"), #hex("20"), #hex("40") and #hex("60") from the #hex-range("4000", "7FFF") memory area, because those bank numbers have #bin("00000") in the lower bits. Due to the zero value adjustment, requesting any of these banks actually requests the next bank (e.g. #hex("21") instead of #hex("20")).
#reg-figure(
caption: [#hex-range("2000", "3FFF") - BANK1 - MBC1 bank register 2]
)[
#reg-table(
[U], [U], [U], [U], [U], [U], [W-0], [W-0],
unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), table.cell(colspan: 2)[BANK2\<1:0\>],
[bit 7], [6], [5], [4], [3], [2], [1], [bit 0]
)
#set align(left)
#grid(
columns: (auto, 1fr),
gutter: 1em,
[*bit 7-2*], [*Unimplemented*: Ignored during writes],
[*bit 1-0*], [
*BANK2\<1:0\>*: Bank register 2
]
)
]
The 2-bit BANK2 register can be used as the upper bits of the ROM bank number, or as the 2-bit RAM bank number. Unlike BANK1, BANK2 doesn't disallow zero, so all 2-bit values are possible.
#reg-figure(
caption: [#hex-range("6000", "7FFF") - MODE - MBC1 mode register]
)[
#reg-table(
[U], [U], [U], [U], [U], [U], [U], [W-0],
unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), [MODE],
[bit 7], [6], [5], [4], [3], [2], [1], [bit 0]
)
#set align(left)
#grid(
columns: (auto, 1fr),
gutter: 1em,
[*bit 7-1*], [*Unimplemented*: Ignored during writes],
[*bit 0*], [
*MODE*: Mode register\
#bin("1") = BANK2 affects accesses to #hex-range("0000", "3FFF"), #hex-range("4000", "7FFF"), #hex-range("A000", "BFFF")\
#bin("0") = BANK2 affects only accesses to #hex-range("4000", "7FFF")
]
)
]
The MODE register determines how the BANK2 register value is used during memory accesses.
#warning[
Most documentation, including Pan Docs @pandocs, calls value #bin("0") ROM banking mode, and value #bin("1") RAM banking mode. This terminology reflects the common use cases, but "RAM banking" is slightly misleading because value #bin("1") also affects ROM reads in multicart cartridges and cartridges that have a 8 or 16 Mbit ROM chip.
]
=== ROM in the #hex-range("0000", "7FFF") area
In MBC1 cartridges, the A0-A13 cartridge bus signals are connected directly to the corresponding ROM pins, and the remaining ROM pins (A14-A20) are controlled by the MBC1. These remaining pins form the ROM bank number.
When the #hex-range("0000", "3FFF") address range is accessed, the effective bank number depends on the MODE register. In MODE #bin("0") the bank number is always 0, but in MODE #bin("1") it's formed by shifting the BANK2 register value left by 5 bits.
When the #hex-range("4000", "7FFF") addess range is accessed, the effective bank number is always a combination of BANK1 and BANK2 register values.
If the cartridge ROM is smaller than 16 Mbit, there are less ROM address pins to connect to and therefore some bank number bits are ignored. For example, 4 Mbit ROMs only need a 5-bit bank number, so the BANK2 register value is always ignored because those bits are simply not connected to the ROM.
#figure(
table(
columns: 4,
stroke: (y: none),
align: center,
table.hline(),
[], table.cell(colspan: 3)[ROM address bits],
[Accessed address], table.cell(colspan: 2)[Bank number], [Address within bank],
table.hline(),
[], [20-19], [18-14], [13-0],
table.hline(),
[#hex-range("0000", "3FFF"), MODE = #bin("0")], bin("00"), bin("00000"), [A\<13:0\>],
table.hline(),
[#hex-range("0000", "3FFF"), MODE = #bin("1")], [BANK2], bin("00000"), [A\<13:0\>],
table.hline(),
hex-range("4000", "7FFF"), [BANK2], [BANK1], [A\<13:0\>],
table.hline(),
),
kind: table,
caption: "Mapping of physical ROM address bits in MBC1 carts"
)
==== ROM banking example 1
Let's assume we have previously written #hex("12") to the BANK1 register and #bin("01") to the BANK2 register. The effective bank number during ROM reads depends on which address range we read and on the value of the MODE register:
#block(breakable: false, {
let bank1 = box(inset: (y: 2pt), fill: rgb("#0000ff4c"))[10010]
let bank2 = box(inset: (y: 2pt), fill: rgb("#ff00004c"))[01]
let prefix = box(inset: (y: 2pt))[0b]
let pass(text) = box(inset: (y: 2pt), fill: rgb("#00000019"), text)
table(
columns: 3,
align: (left + horizon, right + horizon, left + horizon),
stroke: none,
[*Value of the BANK 1 register*],
monotext[#prefix#bank1], [],
[*Value of the BANK 2 register*],
monotext[#prefix#bank2], [],
[*Effective ROM bank number\ (reading #hex-range("4000", "7FFF"))*],
monotext[#prefix#bank2#bank1], [(= 50 = #hex("32"))],
[*Effective ROM bank number\ (reading #hex-range("0000", "3FFF"), MODE = #bin("0"))*],
monotext[#prefix#pass[00]#pass[00000]], [(= 0 = #hex("00"))],
[*Effective ROM bank number\ (reading #hex-range("0000", "3FFF"), MODE = #bin("1"))*],
monotext[#prefix#bank2#pass[00000]], [(= 32 = #hex("20"))],
)
})
==== ROM banking example 2
Let's assume we have previously requested ROM bank number 68, MBC1 mode is #bin("0"), and we are now reading a byte from #hex("72A7"). The actual physical ROM address that will be read is going to be #hex("1132A7") and is constructed in the following way:
#block(breakable: false, {
let bank1(content) = box(inset: (y: 2pt), fill: rgb("#0000ff4c"), content)
let bank2(content) = box(inset: (y: 2pt), fill: rgb("#ff00004c"), content)
let addr(content) = box(inset: (y: 2pt), fill: rgb("#00ff004c"), content)
let prefix = box(inset: (y: 2pt))[0b]
let pass(content) = box(inset: (y: 2pt), fill: rgb("#00000019"), content)
table(
columns: 3,
align: (left + horizon, right + horizon, left + horizon),
stroke: none,
[*Value of the BANK 1 register*],
monotext[#prefix#bank1("00100")], [],
[*Value of the BANK 2 register*],
monotext[#prefix#bank2("10")], [],
[*ROM bank number*],
monotext[#prefix#bank2("10")#bank1("00100")], [(= 68 = #hex("44"))],
[*Address being read*],
monotext[#prefix#pass[01]#addr("11 0010 1010 0111")], [(= #hex("72A7"))],
[*Actual physical ROM address*],
monotext[#prefix#bank2("1 0")#bank1("001 00")#addr("11 0010 1010 0111")], [(= #hex("1132A7"))],
)
})
=== RAM in the #hex-range("A000", "BFFF") area
Some MBC1 carts include SRAM, which is mapped to the #hex-range("A000", "BFFF") area. If no RAM is present, or RAM is not enabled with the RAMG register, all reads return undefined values and writes have no effect.
On boards that have RAM, the A0-A12 cartridge bus signals are connected directly to the corresponding RAM pins, and pins A13-A14 are controlled by the MBC1. Most of the time the RAM size is 64 Kbit, which corresponds to a single bank of #hex("2000") bytes. With larger RAM sizes the BANK2 register value can be used for RAM banking to provide the two high address bits.
In MODE #bin("0") the BANK2 register value is not used, so the first RAM bank is always mapped to the #hex-range("A000", "BFFF") area. In MODE #bin("1") the BANK2 register value is used as the bank number.
#figure(
table(
columns: 3,
stroke: (y: none),
align: center + bottom,
table.hline(),
[], table.cell(colspan: 2)[RAM address bits],
[Accessed address], [Bank number], [Address within bank],
table.hline(),
[], [14-13], [12-0],
table.hline(),
[#hex-range("A000", "BFFF"), MODE = #bin("0")], bin("00"), [A\<12:0\>],
table.hline(),
[#hex-range("A000", "BFFF"), MODE = #bin("1")], [BANK2], [A\<12:0\>],
table.hline(),
),
kind: table,
caption: "Mapping of physical RAM address bits in MBC1 carts"
)
==== RAM banking example 1
Let's assume we have previously written #bin("10") to the BANK2 register, MODE is #bin("1"), RAMG is #bin("1010") and we are now reading a byte from #hex("B123"). The actual physical RAM address that will be read is going to be #hex("5123") and is constructed in the following way:
#block(breakable: false, {
let bank2(content) = box(inset: (y: 2pt), fill: rgb("#ff00004c"), content)
let addr(content) = box(inset: (y: 2pt), fill: rgb("#00ff004c"), content)
let prefix = box(inset: (y: 2pt))[0b]
let pass(content) = box(inset: (y: 2pt), fill: rgb("#00000019"), content)
table(
columns: 3,
align: (left + horizon, right + horizon, left + horizon),
stroke: none,
[*Value of the BANK 2 register*],
monotext[#prefix#bank2("10")], [],
[*Address being read*],
monotext[#prefix#pass[101]#addr("1 0001 0010 0011")], [(= #hex("B123"))],
[*Actual physical RAM address*],
monotext[#prefix#bank2("10")#addr("1 0001 0010 0011")], [(= #hex("5123"))],
)
})
=== MBC1 multicarts ("MBC1M")
MBC1 is also used in a couple of "multicart" cartridges, which include more than one game on the same cartridge. These cartridges use the same regular MBC1 chip, but the circuit board is wired a bit differently. This alternative wiring is sometimes called "MBC1M", but technically the mapper chip is the same. All known MBC1 multicarts use 8 Mbit ROMs, so there's no definitive wiring for other ROM sizes.
In MBC1 multicarts bit 4 of the BANK1 register is not physically connected to anything, so it's skipped. This means that the bank number is actually a 6-bit number. In all known MBC1 multicarts the games reserve 16 banks each, so BANK2 can actually be considered "game number", while BANK1 is the internal bank number within the selected game. At reset BANK2 is #bin("00"), and the "game" in this slot is actually a game selection menu. The menu code selects MODE #bin("1") and writes the game number to BANK2 once the user selects a game.
From a ROM banking point of view, multicarts simply skip bit 4 of the BANK1 register, but otherwise the behaviour is the same. MODE #bin("1") guarantees that all ROM accesses, including accesses to #hex-range("0000", "3FFF"), use the BANK2 register value.
#figure(
table(
columns: 4,
stroke: (y: none),
align: center,
table.hline(),
[], table.cell(colspan: 3)[ROM address bits],
[Accessed address], table.cell(colspan: 2)[Bank number], [Address within bank],
table.hline(),
[], [19-18], [17-14], [13-0],
table.hline(),
[#hex-range("0000", "3FFF"), MODE = #bin("0")], bin("00"), bin("0000"), [A\<13:0\>],
table.hline(),
[#hex-range("0000", "3FFF"), MODE = #bin("1")], [BANK2], bin("0000"), [A\<13:0\>],
table.hline(),
hex-range("4000", "7FFF"), [BANK2], [BANK1\<3:0\>], [A\<13:0\>],
table.hline(),
),
kind: table,
caption: "Mapping of physical ROM address bits in MBC1 multicarts"
)
==== ROM banking example 1
Let's assume we have previously requested "game number" 3 (= #bin("11")) and ROM bank number 29 (= #hex("1D")), MBC1 mode is #bin("1"), and we are now reading a byte from #hex("6C15"). The actual physical ROM address that will be read is going to be #hex("F6C15") and is constructed in the following way:
#block(breakable: false, {
let bank1(content) = box(inset: (y: 2pt), fill: rgb("#0000ff4c"), content)
let bank2(content) = box(inset: (y: 2pt), fill: rgb("#ff00004c"), content)
let addr(content) = box(inset: (y: 2pt), fill: rgb("#00ff004c"), content)
let prefix = box(inset: (y: 2pt))[0b]
let pass(content) = box(inset: (y: 2pt), fill: rgb("#00000019"), content)
table(
columns: 3,
align: (left + horizon, right + horizon, left + horizon),
stroke: none,
[*Value of the BANK 1 register*],
monotext[#prefix#pass("1")#bank1("1101")], [],
[*Value of the BANK 2 register*],
monotext[#prefix#bank2("11")], [],
[*ROM bank number*],
monotext[#prefix#bank2("11")#bank1("1101")], [(= 61 = #hex("3D"))],
[*Address being read*],
monotext[#prefix#pass[01]#addr("10 1100 0001 0101")], [(= #hex("6C15"))],
[*Actual physical ROM address*],
monotext[#prefix#bank2("11")#bank1("11 01")#addr("10 1100 0001 0101")], [(= #hex("F6C15"))],
)
})
==== Detecting multicarts
MBC1 multicarts are not detectable by simply looking at the ROM header, because the ROM type value is just one of the normal MBC1 values. However, detection is possible by going through BANK2 values and looking at "bank 0" of each multicart game and doing some heuristics based on the header data. All the included games, including the game selection menu, have proper header data. One example of a good heuristic is logo data verification.
So, if you have a 8 Mbit cart with MBC1, first assume that it's a multicart and bank numbers are 6-bit values. Set BANK1 to zero and loop through the four possible BANK2 values while checking the data at #hex-range("0104", "0133"). In other words, check logo data starting from physical ROM locations #hex("00104"), #hex("40104"), #hex("80104"), and #hex("C0104"). If proper logo data exists with most of the BANK2 values, the cart is most likely a multicart. Note that multicarts can just have two actual games, so one of the locations might not have the header data in place.
=== Dumping MBC1 carts
MBC1 cartridge dumping is fairly straightforward with the right hardware. The total number of banks is read from the header, and each bank is read one byte at a time. However, BANK1 register zero-adjustment and multicart cartridges need to be considered in ROM dumping code.
Banks #hex("20"), #hex("40") and #hex("60") can only be read from the #hex-range("0000", "3FFF") memory area and only when MODE register value is #bin("1"). Using MODE #bin("1") has no undesirable effects when doing ROM dumping, so using it at all times is recommended for simplicity.
Multicarts should be detected using the logo check described earlier, and if a multicart is detected, BANK1 should be considered a 4-bit register in the dumping code.
#figure(
raw(read("../../code-snippets/mbc1_rom_dump.py"), lang: "python", block: true),
caption: "Python pseudo-code for MBC1 ROM dumping"
)
|
https://github.com/Duarte0903/resume | https://raw.githubusercontent.com/Duarte0903/resume/main/template/resume.typ | typst | Other | #import "@preview/modern-cv:0.4.0": *
#show: resume.with(
author: (
firstname: "Duarte",
lastname: "Leitão",
email: "<EMAIL>",
phone: "(+351) 939 761 195",
github: "Duarte0903",
linkedin: "duartemleitao",
address: "Barcelos, Braga",
positions: (
"Engenheiro Informático",
),
),
date: datetime.today().display(),
language: "en",
colored-headers: true,
)
= Educação
#resume-entry(
title: "Ciências e Tecnologias",
location: "Barcelos",
date: "2016 - 2021",
description: "Colégio La Salle",
)
#resume-entry(
title: "Licenciatura em Engenharia Informática",
location: "Braga",
date: "setembro 2021 - julho 2024",
description: "Universidade do Minho",
)
#resume-entry(
title: "Mestrado em Engenharia Informática",
location: "Braga",
date: "setembro 2024 - Presente",
description: "Universidade do Minho"
)
= Certificações
#resume-entry(
title: "Quadro de Excelência (x6)",
location: "Barcelos",
date: "2014-2021",
description: "Colégio La Salle",
)
#resume-entry(
title: "Certificate in Advanced English (C1)",
location: "Braga",
date: "2020",
description: "Cambridge Assessment English",
)
= Experiências
#resume-entry(
title: "Marketing e comunicações",
location: "Guimarães",
date: "2022 - 2024",
description: "FSUMinho",
)
#resume-item[
- Gestão das redes sociais da equipa
- Presenças em mostras associativas
- Construção do website da equipa
- Segundo lugar na Formula Student Portugal 2023 (Concept Class)
]
#resume-entry(
title: "Head of Management",
location: "Guimarães",
date: "2024 - Presente",
description: "FSUMinho",
)
#resume-item[
- Contactos com patrocinadores
- Gestão de parcerias
- Coordenação com os outros setores da equipa
- Formula Student Portugal 2024 (Classe EV)
]
= Projetos
#resume-entry(
title: "Gerador de sites de UC",
location: [#github-link("Duarte0903/EngWeb2024-Projeto")],
date: "junho 2024",
description: "Universidade do Minho - Engenharia Web",
)
#resume-item[
- Plataforma para gerar páginas web que servem de suporte a unidades curriculares
- Três tipos de utilizadores (aluno, docente, admin)
- Arquitetura dividida em interface, servidor de autenticação, API e base de dados
- Possibilidade de fazer upload e download de ficheiros
- Autenticação com JWT
- Ferramentas - Express, MongoDB, JWT, Docker
]
#resume-entry(
title: "Website FSUMinho",
location: [#github-link("FSUMinho/website_v2")],
date: "julho 2024 - Presente",
description: "FSUMinho",
)
#resume-item[
- Website para a equipa de Formula Student FSUMinho
- Formulário de contacto
- Suporte para várias linguas
- Design adaptável a vários tamanhos de ecrã
- Ferramentas - React, Vite, i18next, GitHub Pages
]
#pagebreak()
#resume-entry(
title: "Plataforma de leilões online",
location: [#github-link("Duarte0903/LI4_UMinho")],
date: "setembro 2023 - janeiro 2024",
description: "Universidade do Minho - Laboratórios de Informática IV",
)
#resume-item[
- Plataforma para fazer leilões de skins do jogo Counter-Strike
- Possibilidade de criar leilões com mais que um artigo
- Autenticação básica com email e password
- Dashboard de administrador
- Ferramentas - Blazor, SQL Server
]
#resume-entry(
title: "Desenvolvimento de uma interface de sistema",
location: [#github-link("Duarte0903/IPM_UMinho")],
date: "fevereiro 2024 - junho 2024",
description: "Universidade do Minho - Interfaces Pessoa-Máquina",
)
#resume-item[
- Interface para mecânicos de uma estação de serviço
- Vários estados para um serviço
- Possibilidade de alterar detalhes
- Verifica se o serviço está atrasado
- Backend implementada com json-server
- Ferramentas - Vue
]
#resume-entry(
title: "Serviço de transferência de ficheiros",
location: [#github-link("Duarte0903/CC_UMinho")],
date: "setembro 2023 - dezembro 2023",
description: "Universidade do Minho - Comunicações por Computador",
)
#resume-item[
- Serviço de transferência de ficheiros que permite transferir chunks de vários nós em paralelo
- Existe uma entidade central que trata das conecções e controla que ficheiros cada nó tem
- Utilização de TCP e UDP
- Ferramentas - Java
]
#resume-entry(
title: "Compilador de Forth",
location: [#github-link("Duarte0903/PL_UMinho")],
date: "fevereiro 2023 - junho 2023",
description: "Universidade do Minho - Processamento de Linguagens",
)
#resume-item[
- Compilador para a linguagem Forth que gera código para uma máquina virtual
- Gramática tradutora baseada em PLY-Yacc
- Analisador léxico implementado com PLY-Lex
- Ferramentas - Python
]
#resume-entry(
title: "Serviços de troca de mensagens",
location: [#github-link("Duarte0903/SSI_UMinho")],
date: "fevereiro 2023 - junho 2023",
description: "Universidade do Minho - Segurança de Sistemas Informáticos",
)
#resume-item[
- Serviço 1: serviço de troca de mensagens encriptadas que utiliza o protocolo Diffie-Hellman. São ainda utilizados certificados x503 e o protocolo Station-to-Station.
- Serviço 2: serviço de troca de mensagens que funciona com os utilizadores e grupos do sistema Linux. É possivel enviar mensagens para um utilizador ou para um grupo.
- Ferramentas - Python, C
]
= Skills
#resume-skill-item(
"Linguagens",
( "C++",
"C",
"C#",
"Python",
"Java",
"JavaScript",
"Haskell",
"HTML",
"CSS"
),
)
#resume-skill-item(
"Frameworks",
( "React",
"Vue",
"Blazor",
"Express",
),
)
#resume-skill-item(
"Ferramentas",
( "Git",
"Docker",
"MongoDB",
"SQL Server",
),
)
#resume-skill-item("Linguas faladas",
(
"Português",
"Inglês",
"Espanhol"
))
#resume-skill-item("Soft-skills",
(
"Trabalho em equipa",
"Comunicação",
"Gestão de tempo",
"Resolução de problemas",
"Adaptabilidade"
)) |
https://github.com/OCamlPro/ppaqse-lang | https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/paradigmes.typ | typst | #import "defs.typ": *
#import "links.typ": *
= Paradigmes
À chaque langage de programmation vient sa manière de decrire les solutions
algorithmiques au problèmes posés. Cette manière d'aborder les problèmes est
ce qu'on appelle le _paradigme_ du langage.
Les paradigmes les plus courants des langages informatiques sont la plupart du
temps les suivants:
- #paradigme[impératif];
- #paradigme[fonctionnel];
- #paradigme[objet].
Il existe d'autres paradigmes moins répandus mais qui concernent
les langages de programmation du rapport:
- #paradigme[déclaratif];
- #paradigme[contrat]
- #paradigme[synchrone].
Notons que les paradigmes ne sont pas exclusifs : un langage peut être
composer plusieurs paradigmes et c'est même le cas général dans les langages
généralistes. Toutefois, même en composant plusieurs paradigmes, il y
en a souvent un qui se dégage plus que les autres à l'usage.
== Impératif
Le paradigme impératif consiste à exprimer les calculs sous une forme
structurée d'instructions modifiant un état mémoire. Les instructions
emblématiques de ce paradigme sont
- l'affectation;
- le branchement conditionnel (si .. alors .. sinon ..);
- les sauts.
Les sauts ne sont pas toujours disponibles explicitement mais ils sont
utilisés implicitement dans les boucles (`for` ou `while`) que l'on
trouve dans tous les langages impératifs. Par exemple, en C, on peut
calculer la longueur d'une liste chainée de la manière indiquée
dans le #ref(<ex_C_length>) :
#figure(
```c
struct list {
int value;
struct list *next;
};
int length(struct list *l)
{
int len = 0;
while (nullptr != l) {
len++;
l = l->next;
}
return len;
}
```,
caption: [Calcul de la longueur d'une liste chainée en C],
supplement: none,
) <ex_C_length>
En considérant que `nullptr` représente la liste vide, la fonction `length`
parcourt la liste en incrémentant un compteur `len` à chaque élément de la
liste. Lorsque la liste est vide, la fonction retourne la longueur obtenue.
Le style impératif est le plus répandu dans les langages informatiques. Il est
relativement proche de la machine mais propice aux erreurs de
programmation car il n'est pas toujours évident de suivre l'état d'un système
lorsque plusieurs morceaux de programme le modifient.
== Fonctionnel
Le paradigme fonctionnel consiste à exprimer les calculs sous la forme d'une
composition de fonctions mathématiques. Dans sa forme dite _pure_, les
changements d'état du système sont interdits. En conséquence, il n'y a pas
d'affectations ni de sauts.
Les branchements conditionnels existent mais les boucles sont remplacées par la
récursivité, c'est-à-dire la possibilité pour une fonction de s'appeler
elle-même. Par exemple, pour calculer la longueur d'une liste en OCaml, on
procède récursivement :
```ocaml
let rec length (l : 'a list) : int = match l with
| [] -> 0
| _ :: tl -> 1 + length tl
```
Dans cet exemple, la fonction `length` prend en paramètre une liste et on fait
une analyse de cas sur la structure de la liste. Si la liste est vide (`[]`),
la longueur est 0. Sinon on analyse la tête et la queue (`tl`) de la liste et
on ajoute 1 à la longueur de `tl`.
Le style fonctionnel est considéré comme plus sûr que le style impératif.
Chaque fonction est une boite noire qui ne produit pas d'effets de bord, ce qui
la rend plus facile à tester et à paralléliser. En contre-partie,
le style fonctionnel nécessite beaucoup d'allocations dynamiques et donc un
ramasse-miettes pour les gérer automatiquement. Cela peut avoir un impact
négatif sur les performances et les capacités temps réel.
Un langage fonctionnel qui accepte la mutabilité est dit _impur_. Les langages
fonctionnels impurs partagent les avantages et les inconvénients des deux
mondes : ils permettent un gain en performances en évitant potentiellement
beaucoup de copies de données mais héritent
également de la difficulté de gérer un état mutable de manière sûre.
== Objet
Le paradigme objet (ou POO#footnote[Programmation Orientée Objet]) consiste à
traiter les données comme des entités, les
_objets_, ayant leur propre état et des méthodes pour leur passer des messages.
Chaque problème informatique est vu comme l'interaction d'un objet avec un ou
plusieurs autres objets via les appels de méthode.
En POO, on distingue les classes, qui sont des modèles d'objets, et les objets
eux-mêmes, qui sont des _instances_ de classes. Par exemple, on peut représenter
un point d'un espace bidimensionnel en C++ de la manière suivante :
```cpp
class Point2D
{
protected:
uint32_t pos_x = 0;
uint32_t pos_y = 0;
public:
Point2D(uint32_t x, uint32_t y) : pos_x(x), pos_y(y) {}
uint32_t get_x(void) const { return pos_x; }
uint32_t get_y(void) const { return pos_y; }
virtual void print(void) const {
std::cout << "Point2D(" << pos_x << ", " << pos_y << ")" << std::endl;
}
};
```
Le mot clé `class`, présent dans pratiquement tous les langages orientés objet,
permet de déclarer un « patron » d'objet. Ici, le patron `Point2D` prend en
paramètre
de construction deux entiers `x` et `y` qui représentent les coordonnées du
point. Ces coordonnées sont enregistrées dans les attributs `pos_x` et
`pos_y` qui représentent l'état interne d'un objet `Point2D`.
Les méthodes `get_x` et `get_y` permettent de récupérer les coordonnées
du point et la méthode `print` permet de les afficher.
On peut alors créer une instance de `Point2D` de la manière suivante :
```cpp
Point2D p(1, 2);
```
et afficher les coordonnées du point avec l'appel de la méthode `print` de
l'objet `p` :
```cpp
p.print()
// affiche "Point2D(1, 2)"
```
La POO introduit également la notion d'héritage qui permet de partager du code
de manière concise. Par exemple, on peut étendre la classe `Point2D` pour les
points d'un espace tridimensionnel :
```cpp
class Point3D : protected Point2D
{
protected:
uint32_t pos_z = 0;
public:
Point3D(uint32_t x, uint32_t y, uint32_t z) : Point2D(x, y), pos_z(z) {}
uint32_t get_z(void) const { return pos_z; }
void print(void) const override {
std::cout <<
"Point3D(" << pos_x << ", " << pos_y << ", " << pos_z << ")" <<
std::endl;
}
};
int main(void)
{
Point3D p(1, 2, 3);
p.print(); // affiche "Point3D(1, 2, 3)"
return 0;
}
```
Ici, la classe `Point3D` hérite de `Point2D` en en récupérant toutes les
méthodes et ajoute un attribut `pos_z`
pour la coordonnée de profondeur. La méthode `print` est redéfinie pour
afficher les trois coordonnées du point.
Le succès des langages objets (C++, Java, Javascript, ...) indique que le
paradigme est très populaire dans les domaines applicatifs et le Web où
la réutilisabilité est un critère de production déterminant.
Généralement, les objets ont un état interne mutable qui peut être modifié par
les méthodes de la classe. De fait, le
paradigme objet va intrinsèquement souffrir des mêmes défauts que le paradigme
impératif sur la difficulté de suivre l'état réel d'un programme.
Par ailleurs, la hiérarchie des classes forme une structure arborescente
qu'il est rapidement difficile de se représenter mentalement. Au delà d'une
certaine profondeur, comprendre le flux de contrôle d'un programme sans
outillage peut être une gageure.
== Déclaratif
Le paradigme déclaratif consiste à décrire le problème à résoudre sans
préciser comment le résoudre. Il s'agit ici de décrire le _quoi_ et non le
_comment_.
Les langages déclaratifs sont généralement orientés vers la description de
données (XML, LaTeX, ...) mais il existe également des langages de
programmation
déclaratifs. Par exemple, Prolog est un langage de programmation qui
permet de décrire un problème de manière logique et de laisser le moteur
d'inférence résoudre le problème. Par exemple, on peut décrire un ensemble de
faits:
```prolog
animal(chat).
animal(chien).
```
et demander à Prolog quels sont les animaux possibles :
```prolog
?- animal(X).
X = chat ;
X = chien.
```
Cette abstraction permet généralement une programmation plus concise mais
cela va induire :
- soit une perte de performances : le _comment_ doit être retrouvé
dynamiquement par le programme (Prolog) ;
- soit un modèle de compilation moins optimal (comme pour les langages
fonctionnels purs comme Haskell) ;
- soit par une perte d'expressivité en restreignant le langage à un
sous-ensemble plus facilement optimisable (Lustre).
== Contrat
La programmation par contrat est un paradigme secondaire qui complète un
les autres paradigmes. Cela consiste à ajouter dans le programme des propriétés
qui peuvent être vérifiées statiquement par le compilateur (ou un outil tiers)
ou dynamiquement à l'exécution et ajoutant des gardes automatiquement dans le
code.
Ces propriétés prennent la forme d'assertions insérées à des endroits
spécifiques. L'ensemble des assertions associé à un morceau de code est alors q
forme un _contrat_.
Les contrats permettent
de clarifier la sémantique du programme et de réduire le nombre de _bugs_. Ils
jouent ainsi un rôle complémentaire aux types et aux commentaires.
On distingue quatre types d'assertions:
- Les _préconditions_ qui doivent être vérifiées à l'entrée d'une fonction ou
d'une procédure ;
- Les _postconditions_ qui doivent être vérifiées à la sortie d'une fonction
ou d'une procédure ;
- Les _invariants_ qui doivent toujours être vrais pour des valeurs d'un
certain type ou les instances d'une classe ;
- Les _variants_ qui sont des quantités attachées aux boucles ou aux fonctions
récursives. Elle sont censées croitre ou décroitre de manière bornée à chaque
itération ou appel récursif. Elles
permettent de vérifier la terminaison d'un algorithme.
L'exemple ci-dessous est une implémentation de l'algorithme d'Euclide en Eiffel
avec un contrat qui assure que l'on fournit une entrée valide et que
l'algorithme termine:
```eiffel
gcd (value_1, value_2: INTEGER): INTEGER
require
value_1 > 0
value_2 > 0
local
value: INTEGER
do
from
Result := value_1
value := value_2
invariant
Result > 0
value > 0
gcd(Result, value) = gcd(value_1, value_2)
variant
Result.max(value)
until
Result = value
loop
if Result > value then
Result := Result - value
else
value := value - Result
end
end
ensure
Result = gcd(value_2, value_1)
end
```
Dans cet exemple, les assertions `value_1 > 0` et `value_2 > 0` indiquées dans
la section `require` sont des _précondistions_. L'assertion
`Result = gcd(value_2, value_1)` dans la section `ensure` est une
_postcondition_. Les invariants et les variants sont indiqués dans les sections
idoines.
== Synchrone
La programmation _synchrone_ est utilisée dans le cadre des _systèmes réactifs_,
c'est-à-dire des systèmes qui maintiennent en permanence une interaction avec
un environnement et qui doivent être en mesure d'y réagir de façon synchrone,
sûre et déterministe.
La famille des langages synchrones est elle-même divisée en deux familles:
- les langages _dataflow_ (à _flots de données_);
- les langages _orientés contrôle_.
Les langage de programmation _dataflow_ (Lustre, Scade) sont basés sur
l'idée que les données sont variables au cours du temps et forment des _flôts_
et que les opérations des combinateurs de flôts. Par exemple, le flôt `x` de
type entier est vu d'un point de vue logique comme une suite infinie de valeurs
entières. Si elle est constante (par exemple 1), on peut la représenter par
de la manière suivante:
#align(
center,
table(
columns: (auto, auto, auto, auto, auto, auto, auto, auto),
[*Temps*], [$t_0$], [$t_1$], [$t_2$], [$t_3$], [$t_4$], [$t_5$], [...],
[$x$], [1], [1], [1], [1], [1], [1], [...],
)
)
Si l'on combine ce flôt avec un autre flôt `y` variable et l'addition, on
obtient un autre flôt `z` qui varie lui aussi au cours du temps en suivant les
valeurs de `x` et `y`:
#align(
center,
table(
columns: (auto, auto, auto, auto, auto, auto, auto, auto),
[*Temps*], [$t_0$], [$t_1$], [$t_2$], [$t_3$], [$t_4$], [$t_5$], [...],
[$x$], [1], [1], [1], [1], [1], [1], [...],
[$y$], [2], [-1], [4], [3], [-3], [1], [...],
[$z = x + y$], [3], [0], [5], [4], [-2], [2], [...],
)
)
Un programme revient alors à une description equationnelle des sorties en
fonction des entrées.
Dans les programmes _orientés contrôle_ (Esterel, ReactiveML), la temporalité
s'exprime par les structures de contrôle du langage qui opèrent sur des signaux
équivalent aux flôts précédents mais dont la valeur peu être présente ou
absente. On distingue alors les instructions qui _prennent du temps_ de celles
qui sont considérées comme logiquement instantannées. Voici par exemple un
programme ReactiveML (un surchouche réactive au dessus d'OCaml):
```ocaml
let process produce nat =
let n = ref 0 in
loop
n := !n + 1;
emit nat !n;
pause
end
let process print nat =
loop
await nat(n) in
print_int n;
end
let process main =
signal nat in
run (produce nat) || run (print nat)
let () = run main
```
Dans ce programme, on crée un processus `produce` qui prend un signal `nat` et
boucle indéfiniment en incrémentant le compteur `n` et en émétant la valeur de
`n` dans le signal `nat`. Comme toutes ces oprations sont instantannées, on
insère une instruction `pause` qui prend du temps (logique) et évite à la
boucle `loop` de tourner indéfiniment dans le même pas de temps.
Le processus `print` boucle indéfiniment en attendant la valeur de `nat` et
l'affiche. Comme attendre un signal prend du temps, la boucle `loop` n'est
pas instantannée et n'a pas besoin de pause.
Le processus `main` crée un signal `nat` et lance les processus `produce` et
`print` en parallèle. Lorsqu'on exécute le programme, on obtient l'affichage
1, 2, 3, 4, 5, ... qui montre bien que les deux processus tournent en parallèle
de manière synchrone.
Ce genre de programmation est particulièrement adapté aux systèmes interactifs
car il permet de décrire de manière intuitive et concise les interactions en
obtenant un résultat déterministe. Obtenir le même résultat avec un langage
utilisant des _threads_ est généralement plus complexe et moins sûr.
Dans les deux cas, les langages synchrones utilisent un modèle temporel logique
pour ordonnancer les évènements et les réactions à ces évènements. Ce modèle
de temps logique peut être callé sur le temps réel en choissisant une borne
maximale entre deux instants logiques du système. Dans les langages comme Lustre
ou l'ordonancement est statique et que le code engendré pour un pas de temps
est déterministe, on peut calculer le WCET maximal d'un pas de temps et donc
garantir l'adéquation avec le temps réel.
|
|
https://github.com/typst-community/mantodea | https://raw.githubusercontent.com/typst-community/mantodea/main/tests/util/test.typ | typst | MIT License | #import "/src/util.typ"
#show heading.where(level: 1): it => pagebreak(weak: true) + it
#set page(width: 100pt, height: auto)
#util.alert[Alert]
#util.hint[Hint]
#util.info[Info]
#util.warn[Warn]
#util.error[Error]
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/topics/call-externals.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book.page.with(title: [在Typst内执行Js、Python、Typst等])
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/cover.typ | typst | #import "../../../polylux.typ": *
#set page(paper: "presentation-16-9")
#set text(size: 30pt)
#polylux-slide[
#uncover("3-4", mode: "transparent")[abc]
#one-by-one(start: 2, mode: "transparent")[def ][ghi]
#line-by-line(mode: "transparent")[
- jkl
- mno
]
#show: pause(4, mode: "transparent")
pqr
]
|
|
https://github.com/UriMtzF/typst-templates | https://raw.githubusercontent.com/UriMtzF/typst-templates/main/uaemex-heading/lib.typ | typst | MIT License | #let project(subject: "" ,title: "", authors: "", accountNum: "", body) = {
set document(author: authors, title: title)
set page(paper: "us-letter", numbering: "1", number-align: center)
set text(font: "New Computer Modern", lang: "es")
//Title row
align(center)[
#block(figure(image("header.jpg",width: 100%)))
#block(text(weight: 700, 1.75em, subject))
#block(text(weight: 500, 1.2em, title))
]
// Author
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,1fr),
gutter: 1em,
align(center,authors),
align(center, "No. de Cta: " + accountNum),
),
)
set par(justify: true)
body
} |
https://github.com/ukihot/igonna | https://raw.githubusercontent.com/ukihot/igonna/main/appendices.typ | typst | #import "templates.typ"
#templates.appendices[
= Foo
= Bar
]
|
|
https://github.com/giZoes/justsit-thesis-typst-template | https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/others/style.typ | typst | MIT License | #let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let 字体 = (
// 宋体,属于「有衬线字体」,一般可以等同于英文中的 Serif Font
// 这一行分别是「新罗马体(有衬线英文字体)」、「思源宋体(简体)」、「思源宋体」、「宋体(Windows)」、「宋体(MacOS)」
宋体: ("Times New Roman", "Source Han Serif SC", "Source Han Serif", "Noto Serif CJK SC", "SimSun", "Songti SC", "STSongti"),
// 黑体,属于「无衬线字体」,一般可以等同于英文中的 Sans Serif Font
// 这一行分别是「Arial(无衬线英文字体)」、「思源黑体(简体)」、「思源黑体」、「黑体(Windows)」、「黑体(MacOS)」
黑体: ("Arial", "Source Han Sans SC", "Source Han Sans", "Noto Sans CJK SC", "SimHei", "Heiti SC", "STHeiti"),
// 楷体
楷体: ("Times New Roman", "KaiTi", "Kaiti SC", "STKaiti", "FZKai-Z03S"),
// 仿宋
仿宋: ("Times New Roman", "FangSong", "FangSong SC", "STFangSong", "FZFangSong-Z02S"),
// 等宽字体,用于代码块环境,一般可以等同于英文中的 Monospaced Font
// 这一行分别是「Courier New(Windows 等宽英文字体)」、「思源等宽黑体(简体)」、「思源等宽黑体」、「黑体(Windows)」、「黑体(MacOS)」
等宽: ("Courier New", "Menlo", "IBM Plex Mono", "Source Han Sans HW SC", "Source Han Sans HW", "Noto Sans Mono CJK SC", "SimHei", "Heiti SC", "STHeiti"),
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tuhi-booklet-vuw/0.1.0/README.md | markdown | Apache License 2.0 | # tuhi-booklet-vuw
A Typst template for VUW programme descriptions. To get started:
```typst
typst init @preview/tuhi-booklet-vuw:0.1.0
```
And edit the `main.typ` example.

## Contributing
PRs are welcome! And if you encounter any bugs or have any requests/ideas, feel free to open an issue.
|
https://github.com/tshu-w/CV | https://raw.githubusercontent.com/tshu-w/CV/main/README.md | markdown | # Personal CV
Personal CV written with [Typst](https://github.com/typst/typst).
## Download/下载
- [English version (PDF)](https://files.tianshu.me/cv/en.pdf)
- [中文版 (PDF)](https://files.tianshu.me/cv/zh.pdf)
## Acknowledgements
- [Super Cool Resume Typst Template](https://typst.app/project/p_Bky8MIksPGK39OpsflJw)
- [matchy233/typst-chi-cv-template](https://github.com/matchy233/typst-chi-cv-template)
- [ice1000/resume](https://github.com/ice1000/resume)
|
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Chapters/Anhang.typ | typst | #import "../abbreviations.typ": *
#import "../Template/customFunctions.typ": *
#heading(numbering: none)[Anhang]
#heading(numbering: none, level: 2)[Quellcode]
Der in dieser Arbeit entstandene Quellcode ist an den folgenden Stellen zu finden.
#heading(numbering: none, level: 3, outlined: false)[Frontend & Entwicklerdokumentation]
https://gitlab.gwdg.de/lernanwendungen/studymodules
Branch: `main`
Commit-Hash: `8217a61d2fd15ef2b38cb5a5b47fb2351902017b`
#heading(numbering: none, level: 3, outlined: false)[Backend & LaTeX-Skript]
https://gitlab.gwdg.de/lernanwendungen/studybase
Branch: `studymodules_tobi`
Commit-Hash: `9cdd4a94fdad896e86df201a1f8c212c0587231b`
#pagebreak()
#heading(numbering:none, level: 2)[Interview-Fragen]<interviewFragen>
*Häufigkeit von Änderungen*
_Falls diese Informationen nicht vorliegen - ist ein geeigneter Ansprechpartner an der Hochschule bekannt?_
1. Wie häufig ändern sich einzelne Details zu einem Modul? Details sind z.B. Verantwortliche(r), Angestrebte Lernergebnisse, Gruppengröße...
- welche Details ändern sich am häufigsten?
2. Wie häufig gibt es neue Module / Wie häufig werden alte Module entfernt?
3. Wie häufig gibt es neue Studiengänge / Wie häufig werden alte Studiengänge entfernt
* Design*
4. muss neues Modulhandbuch 1zu1 so aussehen wie altes Modulhandbuch? Oder darf ein neues Design verwendet werden, wenn trotzdem alle Informationen übersichtlich erkennbar sind
*Workflow*
5. Wenn es Änderungen am Inhalt eines Modulhandbuches gibt, was passiert dann genau?
5.2 Wer ist für welche Aufgabe zuständig?
6. Werden die englischen Handbücher nach dem selben Prinzip manuell erstellt, oder passiert das automatisch?
7. Welche Schwierigkeiten & Probleme haben Sie mit dem aktuellen Prozess?
*Ideen*
8. Haben Sie Vorstellungen / Anforderungen / Ideen für das neue System?
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/grid-styling_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test general alignment.
#grid(
columns: 3,
align: left,
[Hello], [Hello], [Hello],
[A], [B], [C],
)
// Test alignment with a function.
#grid(
columns: 3,
align: (x, y) => (left, center, right).at(x),
[Hello], [Hello], [Hello],
[A], [B], [C],
)
// Test alignment with array.
#grid(
columns: (1fr, 1fr, 1fr),
align: (left, center, right),
[A], [B], [C]
)
// Test empty array.
#set align(center)
#grid(
columns: (1fr, 1fr, 1fr),
align: (),
[A], [B], [C]
)
a
|
https://github.com/aagumin/cv | https://raw.githubusercontent.com/aagumin/cv/typst/cv.typ | typst | #import "@preview/grotesk-cv:0.1.2":*
#show: layout
#set list(marker: [‣])
#create-header(use-photo: true)
#grid(
columns: (71%, 25%),
gutter: 20pt,
stroke: none,
stack(
spacing: 20pt,
import-section("profile"),
import-section("experience"),
import-section("education"),
// import-section("references"),
),
stack(
spacing: 20pt,
import-section("skills"),
// import-section("community"),
// import-section("languages"),
// import-section("other_experience"),
),
)
|
|
https://github.com/tudborg/notes.typ | https://raw.githubusercontent.com/tudborg/notes.typ/main/README.md | markdown | Apache License 2.0 | # notes.typ
Footnotes, endnotes, notes.

See [example.pdf](example/example.pdf) for the example PDF.
## Usage
### Quickstart
The easiest way to use this library is to place the `notes.typ` file
somewhere where you can import it, and do
```typst
#import "notes.typ": note, notes
```
at the top of your document.
Then, anywhere you want to place a note, do
```typst
- This is an *important* point #note[My note goes here]
// ...
// and where you want to render the notes:
#notes()
```
### Footnotes
If you want to always collect notes at the bottom of the page, you simply
call `#notes` in your footer:
```typst
#set page(
footer: [
This is my footer.
#notes()
]
)
```
### Custom note rendering
The `notes` function is a sane-defaults function for displaying notes at
the bottom of a section / page.
You probably want to define your own by creating a function that a calls
`render_notes`.
You can use the `notes` function as a starting point:
```typst
#import "notes.typ": note, render_notes
// ...
#let notes(
size: 8pt,
font: "Roboto",
line: line(length: 100%, stroke: 1pt + gray),
padding: (top: 3mm),
alignment: bottom,
numberings: "1",
group: note_default_group,
reset: true,
reset_counter: false
) = {
let render(notes) = {
if notes.len() > 0 {
set align(alignment)
block(breakable: false, pad(..padding, {
if line != none { line }
set text(size: size, font: font)
for note in notes {
[/ #text(font: "Roboto Mono")[[#numbering(numberings, note.index)]]: #note.text]
}
}))
}
}
render_notes(group: group, reset: reset, reset_counter: reset_counter, render)
}
```
To customize the note marker, you can define your own `note` function
with the `display` argument set as you prefer:
```typst
#let mynote = note.with(
display: (note) => {
super(text(weight: "bold", fill: orange, note.index))
}
)
```
### Advanced Usage
#### Reset note counter after each render of notes
```typst
#let mynotes = notes.with(reset_counter: true)
```
#### Two different note sets
If you want two different sets of note tracking states, you
can define your own "group" name.
The typical use-case might be footnotes + endnotes.
```typst
#let footnote = note.with(group: "footnote")
#let show_footnotes = notes.with(group: "footnote")
#let endnote = note.with(group: "endnote")
#let show_endnotes = notes.with(group: "endnote")
```
And then use then as normal
```typst
- I want to add something at the bottom of the page #footnote[My Footnote]
- I want to add something to the end of the document #endnote[My Endnote]
```
And your page footer could be
```typst
#set page(footer: show_footnotes)
```
while at the bottom of your document you have a call to
```typst
#show_endnotes()
```
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/homeworks/to-2024-09-30.typ | typst | = ДЗ 3
== Задача 18
Среди первых 19 человек ровно 9 подошло. 20-ый тоже подошел.
$ P = P_19(9) dot 0.2 = C_19^9 0.2^9 0.8^10 dot 0.2 approx 0.0010157 $
== Задача 24
+ $A$ --- система работает
Должны работать элементы 1, 6 и любой из 2--5:
$ P_(2 - 5) = 1 - (1 - p_2)(1 - p_3)(1 - p_4)(1 - p_5)
= 1 - 1/2^4 = 15/16 $
$ P(A) = p_1 dot p_6 dot P_(2 - 5) = 2/3 dot 3/4 dot 15/16 = 15/32 $
+ $B$ --- ровно два элемента из 2 -- 5 отказали:
$ P(B) = P_4(2) = C^2_4 (1/2)^2 (1/2)^2 = 3/8 $
+ $A B$, если и $B$, и 1, 6 работают:
$ P(A B) = P(B) dot p_1 dot p_2 = 3/8 dot 2/3 dot 3/4 = 3/16 $
+ $ P = P(B | A) = P(A B) / P(A) = (3/16) / (15/32) = 2/5 = 0.4 $
== Задача 25
$ p = 0.05 $
$ n = 3 $
$ (n + 1)p = 0.05 dot 3 = 0.15 $
$ floor(0.15) = 0 $
Ответ. $0$
== Задача 26
Среди первых 3-ех мальчик 1. 4-ый ребенок -- мальчик.
$ P = P_3(1) dot p = C^1_3 dot p^1 dot q^2 dot p approx 0.187 $
== Задача 60
Нет. Событие (2, 1) не попадает ни в одну "гипотезу".
== Задача 51
$ n = 8 $
$ p = 1/5 $
- (а)
$ P = P_n (3) = P_8 (3) = C_8^3 dot (1/5)^3 dot (4/5)^5 approx 0.1468 $
- (б)
$ P = sum_(i = 0)^3 P_n (i)
= sum_(i = 0)^3 C_8^i dot (1/5)^i dot (4/5)^(8 - i) approx 0.9437 $
== Задача 52
$ p = 0.2 $
Среди первых 4-ех проверок, провалено 2-е. 5-ая тоже провалена.
$ P = P_4 (2) dot p = C^2_4 dot 0.2^2 dot 0.8^2 dot 0.2 approx 0.0307 $
== Задача 53
В семье 2, 3, или 4 девочки
$ P = sum_(i = 2)^4 P_4(i) =
sum_(i = 2)^4 C^i_4 dot q^i dot p^(4-i) approx 0.6647 $
== Задача 54
Должны быть исправны 8 или 9 машин
$ P = sum_(i = 8)^9 P_9 (i) = sum_(i = 8)^9 C^i_9 dot 0.9^i dot 0.1^(9 - i)
approx 0.7748 $
== Задача 62
Взяли группу из равного количества мужчин и женщин. Из группы выбрали одного
человека.
$H$ --- выбрали женщину
$A$ --- выбранный человек --- дальтоник
Вероятность дальтонизма у мужчин значительно выше, чем у женщин, значит:
$ P(H | A) << 0.5 $
Т.к. в группе мужчин и женщин одинокого, то
$ P(H) = 0.5 $
Итого:
$ P(H | A) < P(H) $
Ответ. Может
== Задача 61
$ P(H_1) + P(H_2) + ... + P(H_10) = 1 $
$ P(H_1) = P(H_2) = ... = P(H_10) = 1/10 $
$ P(H_1 + H_10) = P(H_1) + P(H_10) = 2/10 = 1/5 $
== Задача 67
Да. Можно представить каждый маршрут в дереве, как гипотезу, а каждый лист, как
"финальное" событие.
|
|
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/toc.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/templates/text.typ": *
#entry_text()
#outline(
title: [
#align(left)[
#set text(
font: "Times New Roman",
18pt
)
*Table of Contents*
]
],
depth: 1
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/super-suboptimal/0.1.0/src/lib.typ | typst | Apache License 2.0 | #import "super-suboptimal.typ": super-subscripts, eq
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/references/rename_issue_exercise.typ | typst | Apache License 2.0 | // path: basic/writing.typ
#import "mod.typ": *
#exercise()
-----
// path: basic/mod.typ
#import "../mod.typ": exercise
#exercise()
-----
// path: mod.typ
#let /* ident after */ exercise() = []; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.