repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/sa-concept-refactoring/doc | https://raw.githubusercontent.com/sa-concept-refactoring/doc/main/title-page.typ | typst | #import "progress-bar.typ": printProgressBar
#let title = "C++ Concept Refactorings"
#let authors = ( "<NAME>", "<NAME>" )
#let advisor = "<NAME>"
#let luschtig = false
#set document(
title: title,
author: authors,
)
#set align(center)
#text(3em)[
*#title*
]
#text(1.5em)[
#authors.join("\n")
#line()
_Advisor:_ \ #advisor
#line()
#datetime.today().display("[day].[month].[year]")
]
#v(4em)
#if luschtig {
[*Documentation Progress:*]
locate(location => {
let maxPageNumber = counter(page).final(location).first()
let pagesRequired = 120
let barWidth = maxPageNumber / pagesRequired
printProgressBar(barWidth, label: {str(maxPageNumber) + "/" + str(pagesRequired)})
})
}
#figure(
image("images/newspaper.jpg", width: if luschtig { 50% } else { 60% }),
caption: [Artistic interpretation of this project @title_image],
)
#set align(bottom)
#image("images/ost_logo.svg", height: 3cm)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/indenta/0.0.2/demo.typ | typst | Apache License 2.0 | #import "lib.typ": fix-indent
#set par(first-line-indent: 2em)
#show: fix-indent()
= Title 1
== Section 1
Indent // an empty line before this paragraph is needed
Indent
== Section 2
#figure(rect(),caption: lorem(2))
no indent
#figure(rect(),caption: lorem(2))
$"Indent"$
+ item
+ item
Indent
= Title 2
no indent // this is intentional
$ f(x) $
$ f(x) $
no indent
Indent
$ f(x) $
$ f(x) $
Indent
#table()[table]
Indent
```py
print("hello")
```
`Indent`
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/get-started.typ | typst | Apache License 2.0 | #import "/docs/cookery/book.typ": book-page
#import "/docs/cookery/term.typ" as term
#show: book-page.with(title: "Get Started")
= Get Started
In this chapter, you will learn how to #link(<installation>)[install] your typst.ts, #link(<import>)[import] it to your project, and run the #link(<run-compiler>)[compiler] or #link(<run-renderer>)[renderer] module with typst.ts.
== Installation <installation>
To get functionality of #link("https://typst.app")[typst], typst.ts provides a core JavaScript library along with two Wasm library:
- `typst.ts`: the core JavaScript library which wraps Wasm modules with more friendly JavaScript APIs.
- `typst-ts-renderer`: a Wasm module that provides rendering functionality.
- `typst-ts-web-compiler`: a Wasm module that provides compilation functionality.
You can install them via #link("https://www.npmjs.com/")[npm] or #link("https://yarnpkg.com/")[Yarn] separately (npm as an example):
```bash
npm install @myriaddreamin/typst.ts
# Optional: if you want to run a typst renderer.
npm install @myriaddreamin/typst-ts-renderer
# Optional: if you want to run a typst compiler.
npm install @myriaddreamin/typst-ts-web-compiler
```
== Import typst.ts to your project <import>
#let easy_color = green.darken(25%)
#let hard_color = red.darken(25%)
There are several ways to setup typst.ts. The difficulty of each approach is evaluated by how many resources you need to configure and whether you need to be familiar with #text(fill: easy_color, [JavaScript]) or #text(fill: hard_color, [Rust]).
#let difficult-easy = text(fill: easy_color, "easy")
#let difficult-medium = text(fill: orange.darken(25%), "medium")
#let difficult-hard = text(fill: hard_color, "hard")
- #box(link(<approach-all-in-one-node>)[Approach 1]) (Recommended in Node.js)
start with the all-in-one Node.js Library.
- #box(link(<approach-all-in-one>)[Approach 2]) (Recommended in Browser)
start with the all-in-one JavaScript Library.
- #box(link(<approach-bundle>)[Approach 3])
Use a bundled javascript file along with wasm modules.
- #box(link(<approach-node-lib>)[Approach 4])
Use typst.ts as a library in Node.js.
- #box(link(<approach-ts-lib>)[Approach 5])
Use typst.ts as a library in browser (for TypeScript users).
- #box(link(<approach-js-lib>)[Approach 6])
Use typst.ts as a library in browser (for JavaScript users).
- #box(link(<approach-ts-lib-from-source>)[Approach 7])
Use typst.ts with customized renderer/compiler modules.
#line(length: 100%)
=== Simple compiler and renderer bindings to Node.js <approach-all-in-one-node>
#let easy-compiler-example = link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/projects/hexo-renderer-typst/lib/compiler.cjs")[Compiler]
#let easy-renderer-example = link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/projects/hexo-renderer-typst/lib/renderer.cjs")[Renderer]
Difficulty: #difficult-easy, Example: #easy-compiler-example and #easy-renderer-example for #link("https://hexo.io/")[Hexo]
The compiler and renderer are integrated into a same node library for simpler and cleaner APIs, since there is no urgent need to tree-shake the components in node.js applications.
```ts
const compiler = NodeCompiler.create();
await compiler.pdf({
mainFileContent: 'Hello, typst!',
}); // :-> PDF Buffer
```
See #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/all-in-one-node.html")[All-in-one Node.js Library] for more example usage.
=== Run the compiler or renderer with simplified APIs <approach-all-in-one>
#let easy-preview-example = link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/github-pages/preview.html")[Single HTML file for real-time previewing typst document]
Difficulty: #difficult-easy, Example: #easy-preview-example
The most simple examples always work with the all-in-one JavaScript Library:
```ts
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';
console.log((await $typst.svg({
mainContent: 'Hello, typst!' })).length);
// :-> 7317
```
See #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/all-in-one.html")[All-in-one (Simplified) JavaScript Library] for more example usage.
Once you feel more conformtable, please continue to try other approaches.
=== Use a bundled javascript file along with wasm modules. <approach-bundle>
#let bundle-example = link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/index.html")[Single HTML file]
Difficulty: #difficult-easy, Example: #bundle-example
You can include a single bundle file of `@myriaddreamin/typst.ts` in your html file and load needed wasm modules via `fetch` api.
```html
<script type="module"
src="/core/dist/esm/main.bundle.js"></script>
<script>
let renderModule = window.TypstRenderModule;
let renderPlugin =
renderModule.createTypstRenderer();
renderPlugin
.init({
getModule: () => fetch(
'path/to/typst_ts_renderer_bg.wasm'),
})
.then(async () => {
console.log('renderer initialized', renderPlugin);
// do something with renderPlugin
});
</script>
```
See #bundle-example for a complete example.
=== Use typst.ts as a library in Node.js. <approach-node-lib>
Difficulty: #difficult-easy
You can import typst.ts as a library:
```typescript
import { createTypstRenderer } from
'@myriaddreamin/typst.ts/dist/esm/renderer.mjs';
const renderer = createTypstRenderer();
renderer.init({}).then(...);
```
There are several templates for developing typst.ts with Node.js:
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/templates/node.js")[Use renderer, with typescript configured with:]
```json { "moduleResolution": "Node" }``` or #linebreak()
```json { "moduleResolution": "Node10" }```
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/templates/node.js-next")[Use renderer, with typescript configured with:]
```json { "moduleResolution": "Node16" }``` or #linebreak()
```json { "moduleResolution": "NodeNext" }```
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/templates/ts-node")[Use ts-node, with typescript configured with:]
```json { "moduleResolution": "Node" }``` or #linebreak()
```json { "moduleResolution": "Node10" }```
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/templates/ts-node-next")[Use ts-node, with and typescript configured with:]
```json { "moduleResolution": "Node16" }``` or #linebreak()
```json { "moduleResolution": "NodeNext" }```
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/templates/compiler-wasm")[Use compiler in browser, with typescript configured with:]
```json { "moduleResolution": "Node16" }``` or #linebreak()
```json { "moduleResolution": "NodeNext" }```
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/templates/compiler-node")[Use compiler in node.js, with typescript configured with:]
```json { "moduleResolution": "Node16" }``` or #linebreak()
```json { "moduleResolution": "NodeNext" }```
=== Use typst.ts as a library in browser (for TypeScript users). <approach-ts-lib>
Difficulty: #difficult-medium
You can import typst.ts as a library:
```typescript
import { createTypstRenderer } from
'@myriaddreamin/typst.ts/dist/esm/renderer.mjs';
const renderer = createTypstRenderer();
renderer.init({
getModule: () => fetch(...),
}).then(...);
```
=== Use typst.ts as a library in browser (for JavaScript users). <approach-js-lib>
Difficulty: #difficult-medium
Please ensure your main file is with `mjs` extension so that nodejs can recognize it as an es module.
```shell
node main.mjs
```
=== Use typst.ts with customized renderer/compiler modules. <approach-ts-lib-from-source>
Difficulty: #difficult-hard
People familiar with rust can develop owned wasm modules with typst.ts so that they can eliminate unnecessary features and reduce the size of the final bundle. For example, if you want to build a renderer module that only supports rendering svg, you can build it like this:
```shell
wasm-pack build --target web --scope myriaddreamin -- --no-default-features --features render_svg
```
#line(length: 100%)
=== Configure path to wasm module
You may have modified the path to wasm module or rebuilt the wasm module for your own purpose. In this case, you need to configure the path to wasm module. There is a `getModule` option in `init` function that you can use to configure the path to wasm module:
```ts
renderer.init({
getModule: () => __wasm_module_resource__,
}).then(...);
```
You can load `__wasm_module_resource__` in several ways:
```ts
// from url
const getModule = () => 'http://...';
// from http request
const getModule = () => fetch('http://...');
// from local file
const { readFileSync } = require('fs');
const getModule = () => new Uint8Array(readFileSync('path/to/wasm/module').buffer);
// instantiated wasm module
const getModule = () => WebAssembly.instantiate(/* params */);
// asynchronously
const getModule = async () => {/* above four ways */};
```
== Configure and run compiler <run-compiler>
- Configure font resources
- Configure access model
- Configure package registry
See #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/src/options.init.mts")[options.init.mts] for more details.
=== Precompile with `typst-ts-cli`
See #term.ts-cli for more details.
=== Build a compilation service in rust
See #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/compiler/service.html")[Compiler Service Library] for more details.
== Configure and run renderer <run-renderer>
- Configure font resources, same as compiler.
See #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/src/options.init.mts")[options.init.mts] for more details.
== Further reading
+ #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/all-in-one-node.html")[All-in-one Node.js Library]
+ #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/all-in-one.html")[All-in-one (Simplified) JavaScript Library]
+ #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/compilers.html")[Compilers]
+ #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/renderers.html")[Renderers]
+ #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/trouble-shooting.html")[Trouble shooting]
|
https://github.com/fenjalien/cirCeTZ | https://raw.githubusercontent.com/fenjalien/cirCeTZ/main/examples/half-adder.typ | typst | Apache License 2.0 | #import "../../typst-canvas/canvas.typ": canvas
#lorem(30)
#figure(
canvas(length: 1cm, debug: false, {
import "../../typst-canvas/draw.typ": *
import "../circuitypst.typ": node
node("and gate", (0,0), name: "g1")
content("g1.out", h(0.5em)+[Carry], anchor: "left")
node("xor gate", (0,-1.5), name: "g2")
content("g2.out", h(0.5em)+[Sum], anchor: "left")
line("g2.in 1", (rel: (-1, 0)), name: "l1")
line("g1.in 1", (rel: (-1, 0)), "l1.end", (rel: (-1, 0)))
content((), [B]+h(0.5em), anchor: "right")
line("g1.in 2", (rel: (-0.5, 0)), name: "l2")
line("g2.in 2", (rel: (-0.5, 0)), "l2.end", (rel: (-1.5, 0)))
content((), [A]+h(0.5em), anchor: "right")
node("circ", "l1.end")
node("circ", "l2.end")
}),
caption: [Exclusive OR]
)
#lorem(30)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-10.typ | typst | Other | // Too few arguments.
#{
let types(x, y) = "[" + type(x) + ", " + type(y) + "]"
test(types(14%, 12pt), "[ratio, length]")
// Error: 13-21 missing argument: y
test(types("nope"), "[string, none]")
}
|
https://github.com/Julian-Wassmann/chapter-utils | https://raw.githubusercontent.com/Julian-Wassmann/chapter-utils/main/0.1.0/util/page-chapter.typ | typst | #import "./chapter-numbering.typ": chapter-numbering
#let get-page-chapter(headerLoc) = {
let chapters = query(heading.where(level: 1), headerLoc)
// try to find a chapter heading on current page
let page-chapter = chapters
.find(h => h.location().page() == headerLoc.page())
// if current page contains no chapter heading, find last chapter heading before current page
if page-chapter == none {
page-chapter = chapters.rev()
.find(h => h.location().page() < headerLoc.page())
}
page-chapter
}
#let format-chapter-default(number, body) = {
if number == [] {
[#body]
} else {
[#number #body]
}
}
#let print-chapter(
page-chapter,
format-chapter,
) = {
if page-chapter == none {
return []
}
let chapter-number = if page-chapter.numbering != none {
chapter-numbering(location: page-chapter.location(), numbering-pattern: page-chapter.numbering)
} else {
[]
}
// apply default or specified format function
format-chapter(chapter-number, page-chapter.body)
}
#let page-chapter(
format-chapter: format-chapter-default
) = {
locate(loc => {
let page-chapter = get-page-chapter(loc)
print-chapter(page-chapter, format-chapter)
})
} |
|
https://github.com/saecki/zig-grep | https://raw.githubusercontent.com/saecki/zig-grep/main/paper/slides.typ | typst | #import "slides-template.typ": *
#let title = "Writing a grep like program in Zig"
#let author = "<NAME>"
#let primary-color = rgb("#f7a43d")
#let primary-dimmed-color = rgb("#403c38")
#let footer-a-color = rgb("#f7a43d")
#let footer-b-color = rgb("#fcca79")
#let dark-surface = rgb("#202020")
#show: project.with(
aspect-ratio: "16-9",
bg-color: dark-surface,
primary-color: primary-color,
primary-dimmed-color: primary-dimmed-color,
footer-a-color: footer-a-color,
footer-b-color: footer-b-color,
short-author: author,
short-title: title,
short-date: datetime.today().display(),
progress-bar: true,
)
#title-slide(
title: [
Writing a grep like\
program in Zig
],
subtitle: "Seminar Programming Languages",
authors: (author),
institution-name: "University of Siegen",
)
#slide(title: "Contents")[
#text(size: 1em, "Language")\
#text(" About")\
#text(" Error Handling")\
#text(" Comptime")\
#text(" Defer")\
#v(0.2em)
#text(size: 1em, "Program")\
#text(" Synchronization")\
#text(" Compiler Bug")\
#text(" Benchmarks")\
]
#focus-slide(background-color: dark-surface, new-section: "Language")[
#align(center)[
#image("zig-logo-light.svg", width: 60%)
]
]
#slide(title: "About")[
Compiled
#v(1em)
General Purpose
#v(1em)
Systems Programming Language
]
#slide(title: "About")[
Successor to C
#v(1em)
Focus on readability
#v(1em)
and maintainability
]
#slide(title: "About")[
Appeared 2016
#v(1em)
Written by <NAME>
#v(1em)
Zig Software Foundation (ZSF)
]
#slide(title: "Error Handling")[
No exceptions
#v(1em)
Errors as values
]
#walk-through-slides(
title: "Error Handling",
code-parts: (
```zig
// inferred error set
pub fn main() !void {
```,
```zig
const num = try parseInt(u32, "324", 10);
```,
```zig
}
```,
```zig
// named error set
const IntError = error{
IsNull,
Invalid,
};
```,
```zig
fn checkNull(num: usize) IntError!void {
```,
```zig
if (num == 0) {
return error.IsNull;
}
```,
```zig
}
```,
),
highlighted-parts: (
(0, 2),
(1,),
(3,),
(4,6),
(5,),
),
)
#walk-through-slides(
title: "Comptime",
code-parts: (
```kotlin
class Container<T>(
var items: ArrayList<T>,
)
```,
```zig
fn Container(comptime T: type) type {
```,
```zig
return struct {
```,
```zig
items: ArrayList(T),
```,
```zig
}
```,
```zig
}
```
),
highlighted-parts: (
(0,),
(1,5),
(2,3,4),
(3,),
)
)
#slide(title: "Comptime")[
#code(```zig
pub fn ArrayList(comptime T: type) type {
return ArrayListAligned(T, null);
}
```)
]
#walk-through-slides(
title: "Comptime",
code-parts: (
```zig
fn fibonacci(n: usize) u64 {
if (n == 0 or n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
```,
```zig
const FIB_8 = fibonacci(8);
```,
```zig
comptime {
// won't compile
std.debug.assert(fibonacci(3) == 1);
}
```,
),
highlighted-parts: (
(0,),
(1,),
(2,),
)
)
#slide(title: "Comptime")[
#set text(size: 16pt)
#code-space()
#text(fill: rgb("#8ec07c"), "Build Summary:") 0/3 steps succeeded; 1 failed #text(fill: luma(120), "(disable with --summary none)")\
install #text(fill: luma(120), "transitive failure")\
└─ install zig-demo #text(fill: luma(120), "transitive failure")\
#text(" ")└─ zig build-exe zig-demo Debug native #text(fill: red, "1 errors")\
zig/0.11.0/files/lib/std/debug.zig:343:14: #text(fill: red, "error:") reached unreachable code\
#text(" ")if (!ok) unreachable; #text(fill: luma(120), "// assertion failure")\
#text(" ")#text(fill: rgb("#b8bb26"), "^~~~~~~~~~~")\
src/main.zig:13:21: note: called from here\
#text(" ")std.debug.assert(fibonacci(3) == 1);\
#text(" ")#text(fill: rgb("#b8bb26"), "~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~")\
]
#slide(title: "Comptime")[
#set text(size: 16pt)
#dimmed-code[```
Build Summary: 0/3 steps succeeded; 1 failed (disable with --summary none)
install transitive failure
└─ install zig-demo transitive failure
└─ zig build-exe zig-demo Debug native 1 errors
zig/0.11.0/files/lib/std/debug.zig:343:14: error: reached unreachable code
if (!ok) unreachable; // assertion failure
^~~~~~~~~~~
```]
#v(0fr)
#v(0.65em)
src/main.zig:13:21: note: called from here\
#text(" ")std.debug.assert(fibonacci(3) == 1);\
#text(" ")#text(fill: rgb("#b8bb26"), "~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~")\
]
#slide(title: "Comptime")[
#set text(size: 16pt)
#dimmed-code[```
Build Summary: 0/3 steps succeeded; 1 failed (disable with --summary none)
install transitive failure
└─ install zig-demo transitive failure
└─ zig build-exe zig-demo Debug native 1 errors
```]
#v(0fr)
#v(0.65em)
zig/0.11.0/files/lib/std/debug.zig:343:14: #text(fill: red, "error:") reached unreachable code\
#text(" ")if (!ok) unreachable; #text(fill: luma(120), "// assertion failure")\
#text(" ")#text(fill: rgb("#b8bb26"), "^~~~~~~~~~~")\
#v(0fr)
#v(0.23em)
#dimmed-code[```
src/main.zig:13:21: note: called from here
std.debug.assert(fibonacci(3) == 1);
~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~
```]
]
#walk-through-slides(
title: "Comptime",
code-parts: (
```zig
fn fibonacci(n: usize) u64 {
if (n == 0 or n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
```,
```zig
const FIB_8 = fibonacci(8);
```,
```zig
comptime {
// won't compile
std.debug.assert(fibonacci(3) == 1);
}
```,
),
highlighted-parts: (
(2,),
)
)
#walk-through-slides(
title: "Comptime",
code-parts: (
```zig
fn fibonacci(n: usize) u64 {
if (n == 0 or n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
```,
```zig
const FIB_8 = fibonacci(8);
```,
```zig
comptime {
// but this will
std.debug.assert(fibonacci(3) == 3);
}
```,
),
highlighted-parts: (
(2,),
)
)
#slide(title: "Defer")[
Execute code at scope exit
#v(1em)
Clean up resources
]
#walk-through-slides(
title: "Defer",
code-parts: (
```zig
fn main() !void {
```,
```zig
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
```,
```zig
defer _ = gpa.deinit();
```,
```zig
const allocator = gpa.allocator();
```,
```zig
var list = ArrayList([]const u8).init(allocator);
```,
```zig
defer list.deinit();
```,
```zig
...
```,
```zig
// 1. input_paths.deinit();
```,
```zig
// 2. _ = gpa.deinit();
```,
```zig
}
```,
),
highlighted-parts: (
(1,2),
(2,),
(4,5),
(5,),
(6,),
(2,5,7,8,9),
(5,7,9),
(2,8,9),
)
)
#focus-slide(background-color: dark-surface, new-section: "Program")[
#align(center)[
= Program
]
]
#slide(title: "Synchronization")[
#code[```zig
const AtomicQueue = struct {
mutex: std.Thread.Mutex,
state: std.atomic.Atomic(State),
buf: []T,
}
```]
]
#slide(title: "Synchronization")[
Futex: fast userspace mutex
#quote("A futex consists of a kernel-space wait queue that is attached to an atomic integer in userspace")
]
#slide(title: "Synchronization")[
#code[```zig
const State = enum(u32) {
Empty,
NonEmpty,
Full,
};
```]
#dimmed-code[```zig
const AtomicQueue = struct {
mutex: std.Thread.Mutex,
```]
#code[```zig
state: std.atomic.Atomic(State),
```]
#dimmed-code[```zig
buf: []T,
}
```]
]
#walk-through-slides(
title: "Synchronization",
code-parts: (
```zig
pub fn append(self *AtomicQueue, item: T) void {
```,
```zig
self.mutex.lock();
```,
```zig
defer self.mutex.unlock();
```,
```zig
if (self.len >= self.buf.len) {
```,
```zig
self.mutex.unlock();
Futex.wait(&self.state, State.Full);
self.mutex.lock();
```,
```zig
}
```,
```zig
self.buf.append(item)
```,
```zig
const new_state = if (self.len < self.buf.len) .NonEmpty else .Full;
```,
```zig
self.state.store(new_state, Ordering.SeqCst);
```,
```zig
Futex.wake(&self.state, 1);
```,
```zig
}
```,
),
highlighted-parts: (
(0,10),
(1,2),
(2,),
(3,5),
(4,),
(6,),
(7,),
(8,9),
(2,10),
),
)
#walk-through-slides(
title: "Compiler Bug",
code-parts: (
```zig
const UserArgFlag = enum {
```,
```zig
Hidden,
```,
```zig
FollowLinks,
Color,
NoHeading,
```,
```zig
IgnoreCase,
```,
```zig
Debug,
NoUnicode,
Help,
};
```
),
highlighted-parts: (
(0, 1, 2, 3, 4),
(1, 3),
),
)
#slide(title: "Compiler Bug")[
#code[```diff
@@ -27,12 +27,12 @@ const UserArgKind = union(enum) {
flag: UserArgFlag,
};
-const UserArgValue = enum {
+const UserArgValue = enum(u8) {
Context,
AfterContext,
BeforeContext,
};
-const UserArgFlag = enum {
+const UserArgFlag = enum(u8) {
Hidden,
FollowLinks,
Color,
```]
]
#slide(title: "Compiler Bug")[
#dimmed-code[```zig
const UserArgFlag = enum {
```]
#code[```zig
Hidden,
```]
#dimmed-code[```zig
FollowLinks,
Color,
NoHeading,
```]
#code[```zig
IgnoreCase,
```]
#dimmed-code[```zig
Debug,
NoUnicode,
Help,
};
```]
`0b100` truncated to `0b00`?
bug already fixed on master
]
#slide(title: "Benchmarks")[
Run using hyperfine
#v(1em)
On testsuite
#v(1em)
2-3x slower than ripgrep
]
#slide(title: "Results R5 5600x & 32Gb")[
#image("result_desktop_r5_5600x_32gb_linux.svg")
]
#slide(title: "Results R7 5800u & 16Gb")[
#image("result_thinkpad_r7_5800u_16gb_linux.svg")
]
#slide(title: "Results R5 5600x & 32Gb")[
#image("result_desktop_r5_5600x_32gb_subtitles.svg")
]
#slide(title: "Results R7 5800u & 16Gb")[
#image("result_thinkpad_r7_5800u_16gb_subtitles.svg")
]
#focus-slide(background-color: dark-surface, new-section: none)[
#align(center)[
= Questions?
]
]
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/styling/show.typ | typst | // Test show rules.
--- show-selector-basic ---
// Override lists.
#show list: it => "(" + it.children.map(v => v.body).join(", ") + ")"
- A
- B
- C
- D
- E
--- show-selector-replace-and-show-set ---
// Test full reset.
#show heading: [B]
#show heading: set text(size: 10pt, weight: 400)
A #[= Heading] C
--- show-selector-discard ---
// Test full removal.
#show heading: none
Where is
= There are no headings around here!
my heading?
--- show-selector-realistic ---
// Test integrated example.
#show heading: it => block({
set text(10pt)
box(move(dy: -1pt)[📖])
h(5pt)
if it.level == 1 {
underline(text(1.25em, blue, it.body))
} else {
text(red, it.body)
}
})
= Task 1
Some text.
== Subtask
Some more text.
= Task 2
Another text.
--- show-in-show ---
// Test set and show in code blocks.
#show heading: it => {
set text(red)
show "ding": [🛎]
it.body
}
= Heading
--- show-nested-scopes ---
// Test that scoping works as expected.
#{
let world = [ World ]
show "W": strong
world
{
set text(blue)
show: it => {
show "o": "Ø"
it
}
world
}
world
}
--- show-selector-replace ---
#show heading: [1234]
= Heading
--- show-unknown-field ---
// Error: 25-29 heading does not have field "page"
#show heading: it => it.page
= Heading
--- show-text-element-discard ---
#show text: none
Hey
--- show-selector-not-an-element-function ---
// Error: 7-12 only element functions can be used as selectors
#show upper: it => {}
--- show-bad-replacement-type ---
// Error: 16-20 expected content or function, found integer
#show heading: 1234
= Heading
--- show-bad-selector-type ---
// Error: 7-10 expected symbol, string, label, function, regex, or selector, found color
#show red: []
--- show-selector-in-expression ---
// Error: 7-25 show is only allowed directly in code and content blocks
#(1 + show heading: none)
--- show-bare-basic ---
#set page(height: 130pt)
#set text(0.7em)
#align(center)[
#text(1.3em)[*Essay on typography*] \
T. Ypst
]
#show: columns.with(2)
#lines(16)
--- show-bare-content-block ---
// Test bare show in content block.
A #[_B #show: c => [*#c*]; C_] D
--- show-bare-vs-set-text ---
// Test style precedence.
#set text(fill: eastern, size: 1.5em)
#show: text.with(fill: forest)
Forest
--- show-bare-replace-with-content ---
#show: [Shown]
Ignored
--- show-bare-in-expression ---
// Error: 4-19 show is only allowed directly in code and content blocks
#((show: body => 2) * body)
--- show-bare-missing-colon-closure ---
// Error: 6 expected colon
#show it => {}
--- show-bare-missing-colon ---
// Error: 6 expected colon
#show it
--- show-recursive-identity ---
// Test basic identity.
#show heading: it => it
= Heading
--- show-multiple-rules ---
// Test more recipes down the chain.
#show list: scale.with(origin: left, x: 80%)
#show heading: []
#show enum: []
- Actual
- Tight
- List
= Nope
--- show-rule-in-function ---
// Test show rule in function.
#let starwars(body) = {
show list: it => block({
stack(dir: ltr,
text(red, it),
1fr,
scale(x: -100%, text(blue, it)),
)
})
body
}
- Normal list
#starwars[
- Star
- Wars
- List
]
- Normal list
--- show-recursive-multiple ---
// Test multi-recursion with nested lists.
#set rect(inset: 3pt)
#show list: rect.with(stroke: blue)
#show list: rect.with(stroke: red)
#show list: block
- List
- Nested
- List
- Recursive!
--- show-selector-where ---
// Inline code.
#show raw.where(block: false): box.with(
radius: 2pt,
outset: (y: 2.5pt),
inset: (x: 3pt, y: 0pt),
fill: luma(230),
)
// Code blocks.
#show raw.where(block: true): block.with(
outset: -3pt,
inset: 11pt,
fill: luma(230),
stroke: (left: 1.5pt + luma(180)),
)
#set page(margin: (top: 12pt))
#set par(justify: true)
This code tests `code`
with selectors and justification.
```rs
code!("it");
```
You can use the ```rs *const T``` pointer or
the ```rs &mut T``` reference.
--- show-set-where-override ---
#show heading: set text(green)
#show heading.where(level: 1): set text(red)
#show heading.where(level: 2): set text(blue)
= Red
== Blue
=== Green
--- show-selector-or-elements-with-set ---
// Looking forward to `heading.where(level: 1 | 2)` :)
#show heading.where(level: 1).or(heading.where(level: 2)): set text(red)
= L1
== L2
=== L3
==== L4
--- show-selector-element-or-label ---
// Test element selector combined with label selector.
#show selector(strong).or(<special>): highlight
I am *strong*, I am _emphasized_, and I am #[special<special>].
--- show-selector-element-or-text ---
// Ensure that text selector cannot be nested in and/or. That's too complicated,
// at least for now.
// Error: 7-41 this selector cannot be used with show
#show heading.where(level: 1).or("more"): set text(red)
--- show-delayed-error ---
// Error: 21-34 panicked with: "hey1"
#show heading: _ => panic("hey1")
// Error: 20-33 panicked with: "hey2"
#show strong: _ => panic("hey2")
= Hello
*strong*
|
|
https://github.com/quarto-ext/typst-templates | https://raw.githubusercontent.com/quarto-ext/typst-templates/main/fiction/README.md | markdown | Creative Commons Zero v1.0 Universal | # Typst Fiction Format
Based on the fiction template published by the Typst team at <https://github.com/typst/templates/tree/main/fiction>.
**NOTE**: This format requires the pre-release version of Quarto v1.4, which you can download here: <https://quarto.org/docs/download/prerelease>.
## Installing
```bash
quarto use template quarto-ext/typst-templates/fiction
```
This will install the extension and create an example qmd file that you can use as a starting place for your document.
## Using
The example qmd demonstrates the document options supported by the fiction format (`title`, `author`, `dedication`, `publishing-info`, etc.). For example, your document options might look something like this:
```yaml
---
title: "Liam's Playlist"
author: <NAME>
dedication: |
for Rachel
publishing-info: |
UK Publishing, Inc. \
6 Abbey Road \
Vaughnham, 1PX 8A3
<https://example.co.uk/>
971-1-XXXXXX-XX-X
format:
fiction-typst: default
---
```
|
https://github.com/Narcha/typst-flagtastic | https://raw.githubusercontent.com/Narcha/typst-flagtastic/main/lib.typ | typst | MIT License | // Same arguments as the `image` element.
#let raw-flag(country_code, ..args) = {
let country_code_list = json("flagpack-core/countryCodeList.json")
let country = country_code_list.find((codes)=>{
codes.values().any((code)=>{ code == country_code })
})
if country == none {
panic("Invalid country code '" + country_code + "'")
}
image(
"flagpack-core/svg/m/" + country.alpha2 + ".svg",
alt: "Flag of " + country.countryName,
..args,
)
}
// Arguments:
// - shape: one of rounded, circle, rectangle. Default: rectangle
// - radius: when shape == "rounded", specifies the border radius. Default: 20%
// - height: the flag's height. Default: 1em
// - width: the flag's width. Default: auto
// - baseline: the length to shift the baseline by. Default: 0.2em
#let flag(
country_code,
shape: "rectangle",
radius: 15%,
height: auto,
width: auto,
baseline: 0.2em,
) = {
let radius = if shape == "rounded" { radius } else if shape == "circle" { 50% } else { 0% }
if height == auto and width == auto {
height = 1em
}
box(radius: radius, clip: true, baseline: baseline, raw-flag(
country_code,
height: height,
width: if shape == "circle" { height } else { auto },
))
}
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/PSD/homework3/homework.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#import "@preview/codelst:2.0.1": sourcecode
#show heading: set block(below: 1.5em)
#show par: set block(spacing: 1.5em)
#set text(font: "Arial", size: 12pt)
#set text(lang: "pt")
#set page(
footer: "Engenharia de Telecomunicações - IFSC-SJ",
)
#show: doc => report(
title: "Projetos de Filtros Por Amostragem",
subtitle: "Processamento de Sinais Digitais",
authors: ("<NAME>",),
date: "07 de Julho de 2024",
doc,
)
= Exemplo:
Abaixo está o exemplo apresentado em sala para entender o projeto do filtro:
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
M = 52;
% Define o comprimento do filtro
N = M + 1;
Omega_p = 4; % Frequência de passagem
Omega_r = 4.2; % Frequência de rejeição
Omega_s = 10; % Frequência de amostragem
kp = floor(N * Omega_p / Omega_s); % Índice de passagem
kr = floor(N * Omega_r / Omega_s); % Índice de rejeição
% Criando o vetor 'A'
A = [ones(1, kp + 1) zeros(1, ceil(M / 2 - kr) + 1)];
% Ajuste de kp se a diferença entre kr e kp for maior que 1
if (kr - kp) > 1
kp = kr - 1;
end
% Inicializando o vetor de resposta ao impulso
h = zeros(1, N);
% Realizando laço de criação do vetor de resposta ao impuslo
k = 1:M/2;
for n = 0:M
h(n + 1) = A(1) + 2 * sum((-1) .^ k .* A(k + 1) .* cos(pi * k * (1 + 2 * n) / N));
end
% Normalização da resposta ao impulso
h = h / N;
% Calculando a resposta em frequência
[H, w] = freqz(h, 1, 2048, Omega_s);
% Plotando a resposta em frequência
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 5 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência')
% Plotando a resposta ao impulso
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/ex1.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/ex1.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
= Questão 1:
Projete um filtro passa-baixas usando o método da amostragem em frequência que satisfaça a especificação a seguir:
- M = 200
- $Omega p$ = 4 $"rad" / s$
- $Omega r$ = 4,2 $"rad" / s$
- $Omega s$ = 10,0 $"rad" / s$
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
% Define a ordem do filtro
M = 200;
% Define o comprimento do filtro
N = M + 1;
Omega_p = 4.0; % Frequência de passagem
Omega_r = 4.2; % Frequência de rejeição
Omega_s = 10.0; % Frequência de amostragem
kp = floor(N * Omega_p / Omega_s); % Índice de passagem
kr = floor(N * Omega_r / Omega_s); % Índice de rejeição
% Vetor de resposta em frequência
A = [ones(1, kp + 1) zeros(1, N - (kp + 1))];
% Criando o vetor 'A'
if (kr - kp) > 1
kp = kr - 1;
end
% Inicializando o vetor de resposta ao impulso
h = zeros(1, N);
% Realizando laço de criação do vetor de resposta ao impuslo
k = 1:M/2;
for n = 0:M
h(n + 1) = A(1) + 2 * sum((-1) .^ k .* A(k + 1) .* cos(pi * k * (1 + 2 * n) / N));
end
% Normalização da resposta ao impulso
h = h / N;
% Calculando a resposta em frequência
[H, w] = freqz(h, 1, 2048, Omega_s);
% Plotando a resposta em frequência
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 5 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência')
% Plotando a resposta ao impulso
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/q1.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/q1.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como podemos ver pelas imagens apresentadas, o filtro possui uma resposa em frequência com ganho/atenuação 0 dB na frequência de passagem (até 4 rad/s) e atenuação de 50 dB na frequência de rejeição (a partir de 4,2 rad/s). A resposta ao impulso do filtro é apresentada na segunda imagem, onde podemos ver que o filtro possui uma resposta ao impulso com 201 amostras, sendo a amostra central a de maior valor.
= Questão 2:
Projete um filtro passa-altas usando o método da amostragem em frequência que satisfaça a especificação a seguir:
- M = 52
- $Omega p$ = 4 $"rad" / s$
- $Omega r$ = 4,2 $"rad" / s$
- $Omega s$ = 10,0 $"rad" / s$
- Agora aumente o número de amostras, mantendo a paridade e faça suas considerações.
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
M = 52;
% Define o comprimento do filtro
N = M + 1;
Omega_r = 4.0; % Frequência de rejeição
Omega_p = 4.2; % Frequência de passagem
Omega_s = 10.0; % Frequência de amostragem
kp = floor(N * Omega_p / Omega_s); % Índice de passagem
kr = floor(N * Omega_r / Omega_s); % Índice de rejeição
% Vetor de resposta em frequência
A = [zeros(1, kr) ones(1, N - kr)];
if (kr - kp) > 1
kp = kr - 1;
end
% Inicializando o vetor de resposta ao impulso
h = zeros(1, N);
% Realizando laço de criação do vetor de resposta ao impuslo
k = 1:M/2;
for n = 0:M
h(n + 1) = A(1) + 2 * sum((-1) .^ k .* A(k + 1) .* cos(pi * k * (1 + 2 * n) / N));
end
% Normalização da resposta ao impulso
h = h / N;
% Calculando a resposta em frequência
[H, w] = freqz(h, 1, 2048, Omega_s);
% Plotando a resposta em frequência
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 5 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência')
% Plotando a resposta ao impulso
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/q2.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/q2.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como podemos ver pelas imagens apresentadas, o filtro possui uma resposa em frequência com ganho/atenuação 0 dB nas frequências de passagem (a partir de 4dB, considerando que não há flutuações de ganho na banda de passagem), e nas frequências de rejeição (até 4dB) um ganho variavel entre -20 e -50dB, variando de acordo com a frequência.
A resposta ao impulso do filtro é apresentada na segunda imagem, onde podemos ver que o filtro possui uma resposta ao impulso com 105 amostras, sendo a amostra central a de maior valor.
= Questão 3:
Projete um filtro passa-faixa usando o método da amostragem em frequência que satisfaça a especificação a seguir:
- M = 52
- $Omega "r1"$ = 2 $"rad" / s$
- $Omega "p1"$ = 3 $"rad" / s$
- $Omega "r2"$ = 7 $"rad" / s$
- $Omega "p2"$ = 8 $"rad" / s$
- $Omega s$ = 20,0 $"rad" / s$
- Agora aumente o número de amostras, mantendo sua paridade e faça suas considerações.
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
M = 104;
% Define o comprimento do filtro
N = M + 1;
Omega_r1 = 2.0; % Frequência de rejeição 1
Omega_p1 = 3.0; % Frequência de passagem 1
Omega_r2 = 7.0; % Frequência de rejeição 2
Omega_p2 = 8.0; % Frequência de passagem 2
Omega_s = 20.0; % Frequência de amostragem
kr1 = floor(N * Omega_r1 / Omega_s); % Índice de rejeição 1
kp1 = floor(N * Omega_p1 / Omega_s); % Índice de passagem 1
kr2 = floor(N * Omega_r2 / Omega_s); % Índice de rejeição 2
kp2 = floor(N * Omega_p2 / Omega_s); % Índice de passagem 2
% Vetor de resposta em frequência
A = zeros(1, N);
A(kp1:kr2) = 1; % Passa-faixa
% Ajustando dos índices para evitar vetores de tamanho não inteiro
if (kr1 - kp1) > 1
kp1 = kr1 - 1;
end
if (kp2 - kr2) > 1
kp2 = kr2 + 1;
end
% Inicializando o vetor de resposta ao impulso
h = zeros(1, N);
% Índices para o cálculo da resposta ao impulso
k = 1:M/2;
for n = 0:M
h(n + 1) = A(1) + 2 * sum((-1) .^ k .* A(k + 1) .* cos(pi * k * (1 + 2 * n) / N));
end
h = h / N; % Normalização da resposta ao impulso
% Calculando a resposta em frequência
[H, w] = freqz(h, 1, 2048, Omega_s);
% Plotando a resposta em frequência
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 10 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência com M aumentado')
% Plotando a resposta ao impulso
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/q3.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/q3.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como podemos ver pelas imagens apresentadas, o filtro possui uma resposa em frequência com ganho/atenuação 0 dB nas frequências de passagem (de 3 a 7 rad/s), e nas frequências de rejeição (até 2 e a partir de 8 rad/s) um ganho variavel entre -20 e -50dB, variando de acordo com a frequência.
= Questão 4:
Projete um filtro rejeita-faixa usando o método da amostragem em frequência que satisfaça a especificação a seguir:
- M = 52
- $Omega "r1"$ = 2 $"rad" / s$
- $Omega "p1"$ = 3 $"rad" / s$
- $Omega "r2"$ = 7 $"rad" / s$
- $Omega "p2"$ = 8 $"rad" / s$
- $Omega s$ = 20,0 $"rad" / s$
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
M = 52;
% Define o comprimento do filtro
N = M + 1;
Omega_p1 = 2; % Frequência de passagem 1
Omega_r1 = 3; % Frequência de rejeição 1
Omega_r2 = 7; % Frequência de passagem 2
Omega_p2 = 8; % Frequência de rejeição 2
Omega_s = 20; % Frequência de amostragem
kp1 = floor(N * Omega_p1 / Omega_s); % Índice de rejeição 1
kr1 = floor(N * Omega_r1 / Omega_s); % Índice de passagem 1
kr2 = floor(N * Omega_r2 / Omega_s); % Índice de rejeição 2
kp2 = floor(N * Omega_p2 / Omega_s); % Índice de passagem 2
% Vetor de resposta em frequência
A = [ones(1, kp1 + 1), zeros(1, kr2 - kp1 + 1), ones(1, M/2 - kp2 + 3)];
% Inicializando o vetor de resposta ao impulso
k = 1:M/2;
h = zeros(1, N);
for n = 0:M
h(n + 1) = A(1) + 2 * sum((-1).^k .* A(k + 1) .* cos(pi * k * (1 + 2 * n) / N));
end
h = h ./ N;
[H, w] = freqz(h, 1, 2048, Omega_s);
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 10 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência')
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/q4.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/q4.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como podemos ver pelas imagens apresentadas, o filtro possui uma resposa em frequência com um ganho variavel entre -20 e -50dB nas frequências de rejeição (de 3 a 7 rad/s), e nas frequências de passagem (até 2 e a partir de 8 rad/s) um ganho 0 (tendo flutuações de acordo com a frequência). A resposta ao impulso do filtro é apresentada na segunda imagem, onde podemos ver que o filtro possui uma resposta ao impulso com 53 amostras, sendo a amostra central a de menor valor.
= Questão 5:
Projete um filtro passa-faixa tipo III usando o método da amostragem em frequência que satisfaça a especificação a seguir:
- M = 52
- $Omega "r1"$ = 2 $"rad" / s$
- $Omega "p1"$ = 3 $"rad" / s$
- $Omega "r2"$ = 7 $"rad" / s$
- $Omega "p2"$ = 8 $"rad" / s$
- $Omega s$ = 20,0 $"rad" / s$
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
M = 52;
% Define o comprimento do filtro
N = M + 1;
Omega_p1 = 3; % Frequência de rejeição 1
Omega_r1 = 2; % Frequência de passagem 1
Omega_r2 = 7; % Frequência de rejeição 2
Omega_p2 = 8; % Frequência de passagem 2
Omega_s = 20; % Frequência de amostragem
kp1 = floor(N * Omega_p1 / Omega_s); % Índice de rejeição 1
kr1 = floor(N * Omega_r1 / Omega_s); % Índice de passagem 1
kr2 = floor(N * Omega_r2 / Omega_s); % Índice de rejeição 2
kp2 = floor(N * Omega_p2 / Omega_s); % Índice de passagem 2
% Vetor de resposta em frequência
A = [zeros(1, kr1+1), ones(1, kp2 - kr1 + 1), zeros(1, kr2 - kp1 + 1)];
% Inicializando o vetor de resposta ao impulso
k = 1:M/2;
h = zeros(1, N);
for n = 0:M
h(n + 1) = 2 * sum((-1).^(k+1) .* A(k + 1) .* sin(pi * k * (1 + 2 * n) / N));
end
h = h ./ N;
[H, w] = freqz(h, 1, 2048, Omega_s);
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 10 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência')
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/q5.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/q5.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como podemos ver pelas imagens apresentadas, o filtro possui uma resposa em frequência com um ganho variavel entre -20 e -50dB nas frequências de rejeição (menor que 2 e maior que 9 rad/s), e nas frequências de passagem (até 2 e a partir de 8 rad/s) um ganho 0 (tendo flutuações de acordo com a frequência). A resposta ao impulso do filtro é apresentada na segunda imagem, onde podemos ver que o filtro possui uma resposta ao impulso com 53 amostras, sendo a amostra central a de menor valor.
= Questão 6:
Projete um filtro passa-baixas usando o método da amostragem em frequência que satisfaça a especificação a seguir
- M = 53
- $Omega p$ = 4 $"rad" / s$
- $Omega r$ = 4,2 $"rad" / s$
- $Omega s$ = 10,0 $"rad" / s$
#sourcecode[```matlab
clear all; close all; clc;
% Define a ordem do filtro
M = 53;
% Define o comprimento do filtro
N = M + 1;
Omega_p = 4; % Frequência de rejeição
Omega_r = 4.2; % Frequência de passagem
Omega_s = 10; % Frequência de amostragem
kp = floor(N * Omega_p / Omega_s); % Índice de passagem
kr = floor(N * Omega_r / Omega_s); % Índice de rejeição
% Vetor de resposta em frequência
A = [ones(1, kp + 1), zeros(1, N/2 - kp - 1)];
if (kr - kp) > 1
kp = kr - 1;
end
% Inicializando o vetor de resposta ao impulso
k = 1:M/2;
h = zeros(1, N);
% Realizando laço de criação do vetor de resposta ao impuslo
for n = 0:M
h(n + 1) = A(1) + 2 * sum((-1).^k .* A(k + 1) .* cos(pi * k * (1 + 2 * n) / N));
end
% Normalização da resposta ao impulso
h = h ./ N;
[H, w] = freqz(h, 1, 2048, Omega_s);
figure(1)
plot(w, 20 * log10(abs(H)))
axis([0 5 -50 10])
ylabel('Resposta de Módulo (dB)')
xlabel('Frequência (rad/s)')
title('Resposta em Frequência')
figure(2)
stem(h)
ylabel('Resposta ao impulso')
xlabel('Amostras (n)')
```]
A partir deste script, temos os seguintes resultados:
#figure(
figure(
rect(image("./pictures/q6.1.png")),
numbering: none,
caption: [Forma de filtragem do filtro projetado ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
#figure(
figure(
rect(image("./pictures/q6.2.png")),
numbering: none,
caption: [Resposta ao impulso do filtro ]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como podemos ver pelas imagens apresentadas, o filtro possui uma resposa em frequência com um ganho 0 dB nas frequências de passagem (até 4 rad/s), e nas frequências de rejeição (a partir de 4,2 rad/s) um ganho variavel entre -20 e -50dB, variando de acordo com a frequência. A resposta ao impulso do filtro é apresentada na segunda imagem, onde podemos ver que o filtro possui uma resposta ao impulso com 54 amostras, sendo a amostra central a de maior valor. |
https://github.com/janlauber/bachelor-thesis | https://raw.githubusercontent.com/janlauber/bachelor-thesis/main/appendix/meeting_log.typ | typst | Creative Commons Zero v1.0 Universal | == Meetings Log
=== 2024-02-14
*Participants*
- <NAME>
- <NAME>
*Topics*
- Schedule and next steps
- Deliverables:
- Task distribution
- Solution
- Documentation
- Presentation
- Timeboxing for deliverables: Calculated back to 4-5 weeks
- Incorporating feedback into documentation at the beginning of the meeting
- Project 2 feedback: Positive on presentation and business perspective
- Discussion on Reflex Apps enhancing AI:
- Autoconfiguration
- Autocompletions
- Suggestions: Analyze latencies, requests, and configuration data for user-based recommendations
- Future meetings: Fridays in Biel, Wednesdays in Bern
- Examining use cases, Reflex deployment, chat solution integration
*Action Items*
- Define paper structure
- Define deliverables to be completed within 4-5 weeks
- Task planning in Github Project
#pagebreak()
=== 2024-03-01
*Participants*
- <NAME>
- <NAME>
*Topics*
- Expert posted on Moodle
- Schedule meeting with expert
- Integration of business perspectives in thesis
- Discuss upcoming business trip
*Action Items*
- Schedule meeting with expert via email
=== 2024-03-05
*Participants*
- <NAME>
- <NAME> (Founder of Unbrkn GmbH #footnote[https://www.unbrkn.ch/])
*Topics*
- Presentation of the project and MVP
- <NAME>'s feedback on the project
- Vercel Alternative for Node Projects
- Remix project for Zermatt Tourism #sym.arrow.r #link("https://ggb-map.unbrkn.dev")
- Shared Kubernetes cluster hosting at Natron Tech AG #footnote[https://natron.ch]
*Action Items*
- User documentation for the project
- Setup of the project on the shared Kubernetes cluster
=== 2024-04-17
*Participants*
- <NAME>
- <NAME>
*Topics*
- Onboarding Coralie completed
- Creation of landing page and initial user documentation
- Discussion on business case and target audience
- Preparation for kanban setup and documentation website
- Implementation of CI/CD GitHub with testing and pre-commit hooks
*Action Items*
- Address inquiries regarding presentation and video requirements at defense
- Finalize features and documentation
=== 2024-05-01
*Participants*
- <NAME>
- <NAME>
*Topics*
- Review of current status
- Presenting the project to the expert
- Discussion on the presentation and defense
*Action Items*
- Show business case and target audience in the presentation
- Documentation should contain: Requirements, target audience, customers, project management, marketing
=== 2024-05-03
*Participants*
- <NAME>
- <NAME> (Founder of Unbrkn GmbH #footnote[https://www.unbrkn.ch/])
*Topics*
- Onboaring <NAME> on the One-Click Deployment system
- Teleport user
- One Click user
- One Click introduction
- Discussion on the project and its future
- Feedback on the project and contract for managed OneClick
*Action Items*
- Fix some bugs in the project
- Typo in the delete page of the deployment
- Auto Image Update is not working when configured for multiple deployments
=== 2024-05-22
*Participants*
- <NAME>
- <NAME>
*Topics*
- Improvements to One-Click.dev:
- Highlighting its power: all the benefits of Kubernetes without the hassle, cloud-agnostic, non-proprietary
- University's interest in a Kubernetes cluster that is easy to configure
- Automatic lifetime management of 12 months for VMs
- One-Click as an enterprise edition:
- Automatic cleanup and policy management
- Pricing between 5-10k CHF/year
- Identifying champions for the platform
- Preparation and practice for the presentation:
- Emphasizing the business case
- Preparing for a deeper business-technical defense presentation
- Administrative tasks:
- Sending the PDF document
- Book entry
- Creating a marketing video featuring the BFH logo
*Action Items*
- Highlight improvements to One-Click.dev in the presentation
- Emphasize ease of use and enterprise features in marketing materials
- Prepare and practice the presentation with a focus on the business case and technical depth
- Send the required PDF document
- Make a book entry
- Create and distribute a marketing video with the BFH logo
=== 2024-06-05
*Participants*
- <NAME>
- <NAME>
*Story of the presentation*
- Begin the presentation from a developer's perspective.
- The developer discovers Node-RED and wants to deploy it.
- Show screenshots of overwhelming deployment setups (e.g., Azure Kubernetes Service).
- Highlight the complexity of Kubernetes.
- Transition to where people host their Kubernetes clusters.
- Start the second case with a custom development like Streamlit.
- *Proposal Feedback:* Erik finds the proposal excellent.
- *Iteration Process:* Discuss the numerous iterations the system has undergone.
- *Power User Representation:* How to depict power users.
- *Conventions:* What conventions the system adheres to.
- *Limitations and Transition:*
- When to switch to native Kubernetes.
- *Commercial Aspect:* Incorporating the commercial aspect into the story.
*Documentation*
- *GitHub Repository:* [Bachelor Thesis Repository](https://github.com/janlauber/bachelor-thesis)
- Should a lot of code be included? Erik suggests linking it.
*Feedback*
- *Commercial Deployment:* The system has been successfully deployed in a commercial setup.
- *Knowledge for Kubernetes Deployment:*
- What does one need to know to deploy in Kubernetes?
- Main steps in bullet points.
- *Gaps in Existing Solutions:*
- Provide concrete examples; it's quite complex.
- *UX Design and Application Logic Description:*
- Move "4. Design goal" to "1. User Experience."
- Obscure other background processes.
- Focus on why and how we are doing this; emphasize "convention over configuration" (centralizing configuration).
- Project creation and monitoring.
- Main value for the user.
- Opinionated use cases.
- *Screenshots:*
- Increase the prominence of user interaction.
- Better structure the presentation.
*Page Count:* Approximately 60 pages. |
https://github.com/wcshds/manual-of-chinese-phonology | https://raw.githubusercontent.com/wcshds/manual-of-chinese-phonology/main/README.md | markdown | # 漢語古音手冊電子檔錄入
潘悟雲先生的《漢語古音手冊》業已出版,可作爲學習研究上古音絕佳參考材料。然而書中註釋甚多,每每遇到「見某字註」類似的註釋,都要費一番工夫前後翻找,頗爲不便。因此我計劃使用 Typst 將這本書的字表重新錄入,同時增加註釋的超鏈接,如此在閱讀PDF檔時衹需要點一下註釋,即可跳轉到前後文的對應位置。
當前本項目遠未完工,但 PDF 文檔已可編譯預覽。參考“編譯 PDF”一節瞭解具體的編譯步驟。
## 編譯 PDF
文檔的編譯需要使用 Typst,如尚未安裝,可參考[官方指引](https://github.com/typst/typst?tab=readme-ov-file#installation)進行安裝。
安裝完成 Typst 後,依次在終端中輸入如下命令,即可生成 PDF 文檔。
```
git clone https://github.com/wcshds/manual-of-chinese-phonology.git
cd ./manual-of-chinese-phonology
typst compile --font-path ./font ./main.typ 漢語古音手冊字表.pdf
```
## 録入細節
由於字表包含大量音標,本項目採取 X-SAMPA 錄入音標,通過簡單的正則替換自動將 X-SAMPA 轉換爲 IPA 音標,具體邏輯可參見 `./tools/xsampa.typ`。因爲字表有一些音標上標或漢語音韻學界特有音標在 X-SAMPA 中並不存在定義,所以我自定義了一些輸入符號,如 `_r_t` 爲"ʳ"、`_@_t` 爲"ᵊ"、`_E_s` 爲"ᴇ"等,所有自定義符號可參見 `./tools/custom.json`。
在 `./phonology-list.typ` 中錄入一條漢字信息後,main 文件會自動爲每一條有註釋的字頭添加一個 label,名爲 `<X字註>`。這樣,前後文有註釋需要另引其他註釋時,就可以直接使用 `#link(<X字註>)[文本內容]` 完成引用。
在錄入中發現的一些字表譌誤,暫時未直接更改,但詳情都記錄在 `./mistakes.txt`中。
|
|
https://github.com/Vanille-N/kefir | https://raw.githubusercontent.com/Vanille-N/kefir/master/instructions/pamphlet.typ | typst | The Unlicense | #set page(margin: (x: 5mm, y: 5mm))
#set par(justify: true)
#set text(size: 12.1pt)
#let symbol(name) = {
box(baseline: 20%)[#image("images/"+name+".svg", height: 13pt)]
}
#let step(title, ingredients, comments, ..params) = {
let width = params.named().at("width", default: 100%)
let split = params.named().at("split", default: 60%)
box(
stroke: (paint: gray, thickness: 0.5pt),
radius: 5pt, inset: 5pt,
width: width,
)[
#{
if repr(comments) != repr([]) {
table(
columns: (split, 100% - split),
stroke: (x,y) => (
if x == 1 {
(left: (paint: gray, thickness: 0.5pt))
} else {
none
}
)
)[
#text(size: 14pt, fill: blue.darken(60%))[#title] \
#ingredients
][
#text(fill: gray.darken(30%))[
#comments
]
]
} else [
#{ if repr(title) != repr([]) [
#text(size: 14pt, fill: blue.darken(60%))[#title] \
] }
#ingredients
]
}
]
}
#let hstrike(frac) = {
place[#line(
start: (-5%, frac), end: (105%, frac),
stroke: (paint: gray.darken(-50%), thickness: 0.3pt)
)]
}
#let top-third = 31.4%
#let bot-third = 70.1%
#hstrike(top-third)
#hstrike(bot-third)
#assert(bot-third - top-third > top-third)
#assert(bot-third - top-third > 100% - bot-third)
#step[
*Conservation* $(#symbol("jam") <- #symbol("water") + #symbol("sugar")"1cas" : #symbol("fridge") + #symbol("timer") <"7j")$
][
Durée: 1 semaine au plus \
Au frigo, dans un bocal hermétique (e.g. pot de confiture).
][
Mettre juste assez d'eau pour submerger les grains,
dissoudre 1 cuillère à soupe de sucre. \
]
#step[
*Préparation* $(#symbol("jug") <- #symbol("water")"2L" + #symbol("sugar")"100g" + #symbol("lemon") + #symbol("fig"))$
][
Matériel:
- bocal de plus de 2L à large goulot
- serviette propre (tissu ou papier), élastique
Ingrédients:
- 2L d'eau
- 100g de grains
- 100g de sucre
- 1 citron
- (optionnel) quelques figues sèches
][
Dissoudre le sucre dans l'eau. Ajouter le citron coupé en tranches de 1cm et les grains.
Le citron doit être neuf et rinçé: ne pas utiliser de jus de citron (trop transformé),
ne pas réutiliser un citron entamé (risque de contamination).
Couvrir avec la serviette fixée par un élastique.
L'obectif est que les poussières ne puissent pas entrer mais que le mélange
puisse librement s'équilibrer en pression.
]
#step[
*Fermentation 1* $(#symbol("jug"): #symbol("timer")"48h")$
][
Durée: 48h \
Température ambiante, non hermétique, à l'abri du soleil.
][
Des petites bulles se forment, mais la pression n'augmente pas.
Si on a mis des figues elles remontent à la surface.
]
#step[
*Filtrage* $(#symbol("bottles") <- #symbol("leaf") + #symbol("filter") <- #symbol("jam"))$
][
Matériel:
- filtre à grosses mailles (1mm)
- 2 à 3 bouteilles qui supportent la pression
- conseillé: entonnoir
Ingrédients, choisir un parmi:
- sirop (25g pour 1L)
- arômes séchés (menthe, hibiscus)
- fruits frais (fraise, framboise)
][
Retirer les tranches de citron et les figues.
Filtrer les grains.
Il ne faut pas que le filtre soit trop fin:
on veut retirer les grains mais garder un résidu pour continuer la fermentation.
Une passoire marche bien, un filtre à café non.
Les grains peuvent refaire un nouveau cycle (voir Fermentation 1),
ou bien partir en hibernation (voir Conservation).
Ajouter les arômes et fermer les bouteilles.
]
#step[
*Fermentation 2* $(#symbol("bottles"): #symbol("timer")"48h")$
][
Durée: 48h \
Température ambiante, bouteille hermétique, à l'abri du soleil.
][
Attention, dorénavant les bouteilles sont sous pression.
Ne pas ouvrir brusquement sous peine que ça gicle.
]
#step[
*Maturation* $(#symbol("bottles"): #symbol("fridge") + #symbol("timer")>"3j")$
][
Durée: au moins 3 jours \
Au frigo, toujours en bouteille.
][
La fermentation est terminée.
Peut se conserver au frigo jusqu'à 1 mois, ou 1 semaine après ouverture.
]
#step(width: 71%)[
*Remarques*
][
- À l'issue d'un cycle de fermentation 1, on obtient environ 130g de grains pour 100g au départ.
Cela veut dire que tous les 3 à 4 cycles on peut faire don d'un lot.
Cela signifie également qu'il faut repeser les grains au début de chaque
cycle de fermentation pour en avoir bien 100g.
- Il n'est ni nécessaire ni contre-indiqué de rincer occasionellement les grains.
- Utiliser du sucre BIO, aussi peu transformé que possible.
- Préferer un citron BIO puisqu'on fait tremper y compris la peau.
- Noter les dates de début de chaque cycle.
Il ne faut pas laisser fermenter plus longtemps que nécessaire.
][]
#h(2.4mm)
#step(width: 27%)[][
<NAME>, \
le 16 Octobre 2024, \
à Saint Martin d'Hères
#v(26mm)
Fait avec Typst. \
#link("https://github.com/vanille-n/kefir")[`github:vanille-n/kefir`]
][]
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/7图像压缩.typ | typst | #import "../template.typ": *
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge
#import fletcher.shapes: house, hexagon, ellipse
#import "@preview/pinit:0.1.4": *
#import "@preview/cetz:0.2.2"
#import "/book.typ": book-page
#show: book-page.with(title: "数字图像处理基础 | DIP")
= 图像压缩 Image Compression
== 图像冗余 Image Redundancy
二维灰度矩阵中包含三种冗余:
- 编码冗余:采用固定长度编码普遍存在冗余
- 空间和时间冗余:图像中紧邻的像素之间有很强的相关性,视频中相邻帧之间也有很强的相关性
- 不相关的信息:被视觉系统忽略的信息或与图像用途无关的信息
== 图像压缩模型
#figure(
[
#set text(size: 8pt)
#let blob(pos, label, tint: white, ..args) = node(
pos,
align(center, label),
width: 19mm,
fill: tint.lighten(60%),
stroke: 1pt + tint.darken(20%),
corner-radius: 5pt,
..args,
)
#diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 70%,
blob((0, 0), [原始图像], width: auto, tint: red),
edge("-|>"),
blob(
(1.75, 0),
[
#diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 70%,
blob((0, 0), [映射器\ Mapper\ *可逆*], tint: yellow),
edge("-|>"),
blob((1.5, 0), [量化器\ Quantizer\ *不可逆*], tint: yellow),
edge("-|>"),
blob((3, 0), [符号编码器\ *编码、压缩*\ *可逆*], tint: yellow),
)
#align(horizon)[编码器 Encoder]
],
width: auto,
tint: orange,
),
edge("-|>", "rr", $\/\/$, label-pos: 0.47, label-side: center),
blob(
(4, 0),
[
#diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 70%,
blob((0, 0), [符号解码器\ Symbol Decoder], tint: yellow),
edge("-|>"),
blob((1.5, 0), [逆映射器\ Inverse Mapper], tint: yellow),
)
#align(horizon)[解码器]
],
width: auto,
tint: orange,
),
edge("-|>"),
blob((5.25, 0), [重建图像], width: auto, tint: red),
)
],
caption: "图像压缩模型",
)
- *映射器*:转换为便于去掉空间和时间冗余的形式
- *量化器*:根据预设的保真度准则降低精度,去除不相关的信息
- *符号编码器*:对量化后的数据进行定长或变长编码,压缩数据
通常在编码之前有预处理,比如图像分块。对于 JPEG 标准,图像被分成 $8 times 8$ 的块,然后进行离散余弦变换。而 JPEG2000 不强制要求分块,可以是任意大小的块。
== 无损压缩 Lossless Compression
=== Huffman 编码
变长编码,根据字符出现的频率来分配编码。出现频率高的字符用短编码,出现频率低的字符用长编码。霍夫曼编码是最短的编码。对于固定的 $n$,该编码是最优的。
=== LZW 编码
基于符号的编码,通过维护一个字典来实现。
#definition[
*LZW 编码*:Lempel-Ziv-Welch 编码,是一种无损压缩算法,用于压缩无损数据。它是一种字典编码,通过在编码过程中动态维护一个字典,将输入的数据编码为更短的数据。
]
== 有损压缩 Lossy Compression
=== JPEG2000 和小波编码
将上面的映射器、量化器、符号编码器替换为小波变换、量化、熵编码。JPEG2000 是一种基于小波的图像压缩标准,可以是有损压缩,也可以是无损压缩,取决于量化的精度。得益于小波变换,它支持渐进式传输和重建。
具体流程步骤:
+ 图像分块:确定块的大小,然后对图像进行分块,不足可以补 0。分块的好处是减少内存占用,同时也可以部分解码。
+ 小波变换:对每个块进行小波变换,得到不同级别的小波系数。
+ 量化:对小波系数进行量化,量化的目的是减少数据量,同时也是有损压缩的关键。当然可以设计无损的量化算法,避免计算的精度损失。
+ 熵编码:对量化后的数据进行熵编码,得到压缩后的数据。
+ 重建:解码的时候,先解码熵编码,然后反量化,最后反小波变换,得到重建的图像。
JPEG2000 因为使用了小波变换,相较于 JPEG(使用离散余弦变换)有更好的压缩效果,不会出现块状失真。
|
|
https://github.com/Ttajika/class | https://raw.githubusercontent.com/Ttajika/class/main/seminar/main.typ | typst | #import "@preview/roremu:0.1.0": roremu
#import "lib/setting.typ": *
#import "lib/bxbibwrite.typ": *
#show: use-bib-item-ref.with(numbering: "1")
#show: project.with(
title: "タイトル",
authors: ([
#table(stroke:0pt,columns:2,[#waritsuke(4,"氏名")
],[自分の名前を書く],[#waritsuke(4,"学籍番号")
],[学籍番号を書く])
],),
lang: "jp",
date: Today(style:"ymd-jp"),
style: "report"//"dissertation"に変更すると卒論スタイルになる
)
= はじめに
#lorem(140)
#lorem(140)
= 関連文献
#roremu(330)
@a によると @b は😯
= 本論/方法
#theorem[すごい定理]<c>
@c はすごい.
#roremu(400,offset: 330)
#roremu(400,offset: 730)
#figure(caption:"日大経済のロゴ")[#image("logo.svg")]<d>
@d は日大のロゴ.
#aeq(<e>)[
$
e^(i pi)=-1
$
]
@e 式はすごい式.$a^3+b^3=c^3+d^3$
= 結論
#lorem(140)
#bibliography-list(title:"参考文献",
numbering: "")[
#bib-item(<a>, key: "著者(2012)")[著者 (2012) "すごい論文" 雑誌名]
#bib-item(<b>, key: "著者(2024)")[著者 (2024) 「すごい本」 出版社]
] |
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ARO/docs/2-Instructions/type-instruction.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Gestion de la mémoire
],
lesson: "ARO",
chapter: "2 - Instructions",
definition: "TBD",
col: 1,
doc,
)
= Types d'instruction
Il existe 3 types d'instructions que nous allons voir.
1. instructions de calcul/traitement #sym.arrow (arithmétique et logique)
2. instructions de transfert de donnée
- interne #sym.arrow interne
- interne #sym.arrow externe
3. instructions de branchement (saut)
= Format d'une instruction
#image("/_src/img/docs/image3.png")
== Opcode
Le champ «opcode» est l’identificateur de l’instruction est permet donc de définir ce que doit celle-ci va devoir faire.
== Opérande(s)
- Les champs opérandes spécifient la destination et les deux opérandes pour le traitement
- Le nombre d’opérandes peut varier de 1 à 3.
- Ci-dessous exemple avec le cas général
== Exemple(s)
=== 1 opérande
```shell
INC r1
```
Incrément de r1 de 1.
#image("/_src/img/docs/image copy 3.png")
=== 2 opérandes
```shell
ADD r1, r2
```
Addition de r1 et r2 puis stockage dans r1.
#image("/_src/img/docs/image copy 2.png")
=== 3 opérandes
```shell
ADD r1, r2, r3
```
Addition de r2 et r3 dans r1.
#image("/_src/img/docs/image copy.png")
= Execution d'une instruction
Un processeur effectue sans arrêt une boucle composée de trois phases:
1. *FETCH* #sym.arrow recherche de l'instruction : dans un premier temps le processeur va chercher l'instruction à éxécuter en récupèrant l'instruction pointée par le PC (*Program Counter*). Cette instruction sera stockée dans un autre registre du processeur, le IR (*Instruction Register*).
2. *DECODE* #sym.arrow décodage de l'instruction : dans un deuxième temps, chaque instruction est identifiée, grâce à un code (*opcode*). En fonction de ce code, le processeur choisit la tâche à exécuter, c'est-àdire la séquence de micro-instructions à exécuter.
3. *EXECUTE* #sym.arrow exécution de l'instruction : finalement on exécute l'instruction puis revenons à la première.
Deux étapes suplémentaires seront vue dans la suite du cours qui permetteront de compléter ce que fait un procésseur, soit *MEMORY* et *WRITE BACK*.
= Modes d'adressage
Le mode d'adressage correspond à la méthode d'accès au données. En fonction de l’instruction à exécuter, la donnée à utiliser peutêtre différente. Nous pouvons imaginer quelques cas:
- Valeur immédiat: opérande = donnée
- Valeur dans un registre: opérande = no registre
- Valeur en mémoire: opérande = adresse
- nombreuses variantes pour ce dernier cas
== Adressage immédiat
Pour ce qui est de l'adressage immédiat nous aurons une valeur constante dans le champ d'instruction.
```shell
mov rd, #valeur
add rd, #cte
```
== Adressage direct
Lors de l'adressage direct nous adressons directement l'adresse de l'opérande. De plus, il existe 2 sous catégories d'adressage direct:
=== Absolu
Dans ce cas, l'adresse est directement ajoutée dans le champ d'instruction.
```shell
mov r1, 0x1234
add r1, 0x1234
```
=== Par registre
Dans ce cas, l'adresse est stockée dans un registre donc on met le numéro du registre.
```shell
mov r1, r2
add r1, r2
```
#image("/_src/img/docs/image copy 4.png")
== Adressage indirect
Lors de l'adressage indirect, l'adresse de l'opérande est stockée dans un registre.
```shell
mov r1, [0x1234]
add r1, [2]
```
#image("/_src/img/docs/image copy 5.png")
= Comment interpréter une instruction
Pour interpréter une instruction, il faut suivre les étapes suivantes:
Dans notre situation notre instruction vaut ```shell 0x1F19``` et nous travaillons sur un procésseur 16 bits.
1. La convertir en binaire: ```shell 0001 1111 0001 1001```
2. Chercher dans la table des instructions l'opcode correspondant à ```shell 00011```
3. Interpreter les opérandes en fonction de l'opcode trouvé.
#image("/_src/img/docs/image copy 6.png")
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compute/construct.typ | typst | Apache License 2.0 | // Test creation and conversion functions.
// Ref: false
---
// Compare both ways.
#test-repr(rgb(0%, 30.2%, 70.2%), rgb("004db3"))
// Alpha channel.
#test(rgb(255, 0, 0, 50%), rgb("ff000080"))
// Test color modification methods.
#test(rgb(25, 35, 45).lighten(10%), rgb(48, 57, 66))
#test(rgb(40, 30, 20).darken(10%), rgb(36, 27, 18))
#test(rgb("#133337").negate(), rgb(236, 204, 200))
#test(white.lighten(100%), white)
// Color mixing, in Oklab space by default.
#test(rgb(color.mix(rgb("#ff0000"), rgb("#00ff00"))), rgb("#d0a800"))
#test(rgb(color.mix(rgb("#ff0000"), rgb("#00ff00"), space: oklab)), rgb("#d0a800"))
#test(rgb(color.mix(rgb("#ff0000"), rgb("#00ff00"), space: rgb)), rgb("#808000"))
#test(rgb(color.mix(red, green, blue)), rgb("#909282"))
#test(rgb(color.mix(red, blue, green)), rgb("#909282"))
#test(rgb(color.mix(blue, red, green)), rgb("#909282"))
// Mix with weights.
#test(rgb(color.mix((red, 50%), (green, 50%))), rgb("#c0983b"))
#test(rgb(color.mix((red, 0.5), (green, 0.5))), rgb("#c0983b"))
#test(rgb(color.mix((red, 5), (green, 5))), rgb("#c0983b"))
#test(rgb(color.mix((green, 5), (white, 0), (red, 5))), rgb("#c0983b"))
#test(color.mix((rgb("#aaff00"), 25%), (rgb("#aa00ff"), 75%), space: rgb), rgb("#aa40bf"))
#test(color.mix((rgb("#aaff00"), 50%), (rgb("#aa00ff"), 50%), space: rgb), rgb("#aa8080"))
#test(color.mix((rgb("#aaff00"), 75%), (rgb("#aa00ff"), 25%), space: rgb), rgb("#aabf40"))
---
// Test color conversion method kinds
#test(rgb(rgb(10, 20, 30)).space(), rgb)
#test(color.linear-rgb(rgb(10, 20, 30)).space(), color.linear-rgb)
#test(oklab(rgb(10, 20, 30)).space(), oklab)
#test(oklch(rgb(10, 20, 30)).space(), oklch)
#test(color.hsl(rgb(10, 20, 30)).space(), color.hsl)
#test(color.hsv(rgb(10, 20, 30)).space(), color.hsv)
#test(cmyk(rgb(10, 20, 30)).space(), cmyk)
#test(luma(rgb(10, 20, 30)).space(), luma)
#test(rgb(color.linear-rgb(10, 20, 30)).space(), rgb)
#test(color.linear-rgb(color.linear-rgb(10, 20, 30)).space(), color.linear-rgb)
#test(oklab(color.linear-rgb(10, 20, 30)).space(), oklab)
#test(oklch(color.linear-rgb(10, 20, 30)).space(), oklch)
#test(color.hsl(color.linear-rgb(10, 20, 30)).space(), color.hsl)
#test(color.hsv(color.linear-rgb(10, 20, 30)).space(), color.hsv)
#test(cmyk(color.linear-rgb(10, 20, 30)).space(), cmyk)
#test(luma(color.linear-rgb(10, 20, 30)).space(), luma)
#test(rgb(oklab(10%, 20%, 30%)).space(), rgb)
#test(color.linear-rgb(oklab(10%, 20%, 30%)).space(), color.linear-rgb)
#test(oklab(oklab(10%, 20%, 30%)).space(), oklab)
#test(oklch(oklab(10%, 20%, 30%)).space(), oklch)
#test(color.hsl(oklab(10%, 20%, 30%)).space(), color.hsl)
#test(color.hsv(oklab(10%, 20%, 30%)).space(), color.hsv)
#test(cmyk(oklab(10%, 20%, 30%)).space(), cmyk)
#test(luma(oklab(10%, 20%, 30%)).space(), luma)
#test(rgb(oklch(60%, 40%, 0deg)).space(), rgb)
#test(color.linear-rgb(oklch(60%, 40%, 0deg)).space(), color.linear-rgb)
#test(oklab(oklch(60%, 40%, 0deg)).space(), oklab)
#test(oklch(oklch(60%, 40%, 0deg)).space(), oklch)
#test(color.hsl(oklch(60%, 40%, 0deg)).space(), color.hsl)
#test(color.hsv(oklch(60%, 40%, 0deg)).space(), color.hsv)
#test(cmyk(oklch(60%, 40%, 0deg)).space(), cmyk)
#test(luma(oklch(60%, 40%, 0deg)).space(), luma)
#test(rgb(color.hsl(10deg, 20%, 30%)).space(), rgb)
#test(color.linear-rgb(color.hsl(10deg, 20%, 30%)).space(), color.linear-rgb)
#test(oklab(color.hsl(10deg, 20%, 30%)).space(), oklab)
#test(oklch(color.hsl(10deg, 20%, 30%)).space(), oklch)
#test(color.hsl(color.hsl(10deg, 20%, 30%)).space(), color.hsl)
#test(color.hsv(color.hsl(10deg, 20%, 30%)).space(), color.hsv)
#test(cmyk(color.hsl(10deg, 20%, 30%)).space(), cmyk)
#test(luma(color.hsl(10deg, 20%, 30%)).space(), luma)
#test(rgb(color.hsv(10deg, 20%, 30%)).space(), rgb)
#test(color.linear-rgb(color.hsv(10deg, 20%, 30%)).space(), color.linear-rgb)
#test(oklab(color.hsv(10deg, 20%, 30%)).space(), oklab)
#test(oklch(color.hsv(10deg, 20%, 30%)).space(), oklch)
#test(color.hsl(color.hsv(10deg, 20%, 30%)).space(), color.hsl)
#test(color.hsv(color.hsv(10deg, 20%, 30%)).space(), color.hsv)
#test(cmyk(color.hsv(10deg, 20%, 30%)).space(), cmyk)
#test(luma(color.hsv(10deg, 20%, 30%)).space(), luma)
#test(rgb(cmyk(10%, 20%, 30%, 40%)).space(), rgb)
#test(color.linear-rgb(cmyk(10%, 20%, 30%, 40%)).space(), color.linear-rgb)
#test(oklab(cmyk(10%, 20%, 30%, 40%)).space(), oklab)
#test(oklch(cmyk(10%, 20%, 30%, 40%)).space(), oklch)
#test(color.hsl(cmyk(10%, 20%, 30%, 40%)).space(), color.hsl)
#test(color.hsv(cmyk(10%, 20%, 30%, 40%)).space(), color.hsv)
#test(cmyk(cmyk(10%, 20%, 30%, 40%)).space(), cmyk)
#test(luma(cmyk(10%, 20%, 30%, 40%)).space(), luma)
#test(rgb(luma(10%)).space(), rgb)
#test(color.linear-rgb(luma(10%)).space(), color.linear-rgb)
#test(oklab(luma(10%)).space(), oklab)
#test(oklch(luma(10%)).space(), oklch)
#test(color.hsl(luma(10%)).space(), color.hsl)
#test(color.hsv(luma(10%)).space(), color.hsv)
#test(cmyk(luma(10%)).space(), cmyk)
#test(luma(luma(10%)).space(), luma)
---
// Test gray color conversion.
// Ref: true
#stack(dir: ltr, rect(fill: luma(0)), rect(fill: luma(80%)))
---
// Error for values that are out of range.
// Error: 11-14 number must be between 0 and 255
#test(rgb(-30, 15, 50))
---
// Error: 6-11 color string contains non-hexadecimal letters
#rgb("lol")
---
// Error: 5-7 missing argument: red component
#rgb()
---
// Error: 5-11 missing argument: blue component
#rgb(0, 1)
---
// Error: 21-26 expected integer or ratio, found boolean
#rgb(10%, 20%, 30%, false)
---
// Error: 10-20 unexpected argument: key
#luma(1, key: "val")
---
// Error: 12-24 expected float or ratio, found string
// Error: 26-39 expected float or ratio, found string
#color.mix((red, "yes"), (green, "no"), (green, 10%))
---
// Error: 12-23 expected a color or color-weight pair
#color.mix((red, 1, 2))
---
// Error: 31-38 expected `rgb`, `luma`, `cmyk`, `oklab`, `oklch`, `color.linear-rgb`, `color.hsl`, or `color.hsv`, found string
#color.mix(red, green, space: "cyber")
---
// Error: 31-36 expected `rgb`, `luma`, `cmyk`, `oklab`, `oklch`, `color.linear-rgb`, `color.hsl`, or `color.hsv`
#color.mix(red, green, space: image)
---
// Error: 31-41 expected `rgb`, `luma`, `cmyk`, `oklab`, `oklch`, `color.linear-rgb`, `color.hsl`, or `color.hsv`
#color.mix(red, green, space: calc.round)
---
// Ref: true
#let envelope = symbol(
"🖂",
("stamped", "🖃"),
("stamped.pen", "🖆"),
("lightning", "🖄"),
("fly", "🖅"),
)
#envelope
#envelope.stamped
#envelope.pen
#envelope.stamped.pen
#envelope.lightning
#envelope.fly
---
// Error: 8-10 expected at least one variant
#symbol()
---
// Test conversion to string.
#test(str(123), "123")
#test(str(123, base: 3), "11120")
#test(str(-123, base: 16), "−7b")
#test(str(9223372036854775807, base: 36), "1y2p0ij32e8e7")
#test(str(50.14), "50.14")
#test(str(10 / 3).len() > 10, true)
---
// Error: 6-8 expected integer, float, version, bytes, label, type, or string, found content
#str([])
---
// Error: 17-19 base must be between 2 and 36
#str(123, base: 99)
---
// Error: 18-19 base is only supported for integers
#str(1.23, base: 2)
---
// Test the unicode function.
#test(str.from-unicode(97), "a")
#test(str.to-unicode("a"), 97)
---
// Error: 19-22 expected integer, found content
#str.from-unicode([a])
---
// Error: 17-21 expected exactly one character
#str.to-unicode("ab")
---
// Error: 19-21 number must be at least zero
#str.from-unicode(-1)
---
// Error: 18-28 0x110000 is not a valid codepoint
#str.from-unicode(0x110000) // 0x10ffff is the highest valid code point
---
#assert(range(2, 5) == (2, 3, 4))
---
// Test displaying of dates.
#test(datetime(year: 2023, month: 4, day: 29).display(), "2023-04-29")
#test(datetime(year: 2023, month: 4, day: 29).display("[year]"), "2023")
#test(
datetime(year: 2023, month: 4, day: 29)
.display("[year repr:last_two]"),
"23",
)
#test(
datetime(year: 2023, month: 4, day: 29)
.display("[year] [month repr:long] [day] [week_number] [weekday]"),
"2023 April 29 17 Saturday",
)
// Test displaying of times
#test(datetime(hour: 14, minute: 26, second: 50).display(), "14:26:50")
#test(datetime(hour: 14, minute: 26, second: 50).display("[hour]"), "14")
#test(
datetime(hour: 14, minute: 26, second: 50)
.display("[hour repr:12 padding:none]"),
"2",
)
#test(
datetime(hour: 14, minute: 26, second: 50)
.display("[hour], [minute], [second]"), "14, 26, 50",
)
// Test displaying of datetimes
#test(
datetime(year: 2023, month: 4, day: 29, hour: 14, minute: 26, second: 50).display(),
"2023-04-29 14:26:50",
)
// Test getting the year/month/day etc. of a datetime
#let d = datetime(year: 2023, month: 4, day: 29, hour: 14, minute: 26, second: 50)
#test(d.year(), 2023)
#test(d.month(), 4)
#test(d.weekday(), 6)
#test(d.day(), 29)
#test(d.hour(), 14)
#test(d.minute(), 26)
#test(d.second(), 50)
#let e = datetime(year: 2023, month: 4, day: 29)
#test(e.hour(), none)
#test(e.minute(), none)
#test(e.second(), none)
// Test today
#test(datetime.today().display(), "1970-01-01")
#test(datetime.today(offset: auto).display(), "1970-01-01")
#test(datetime.today(offset: 2).display(), "1970-01-01")
---
// Error: 10-12 at least one of date or time must be fully specified
#datetime()
---
// Error: 10-42 time is invalid
#datetime(hour: 25, minute: 0, second: 0)
---
// Error: 10-41 date is invalid
#datetime(year: 2000, month: 2, day: 30)
---
// Error: 27-34 missing closing bracket for bracket at index 0
#datetime.today().display("[year")
---
// Error: 27-38 invalid component name 'nothing' at index 1
#datetime.today().display("[nothing]")
---
// Error: 27-50 invalid modifier 'wrong' at index 6
#datetime.today().display("[year wrong:last_two]")
---
// Error: 27-33 expected component name at index 2
#datetime.today().display(" []")
---
// Error: 2-36 failed to format datetime (insufficient information)
#datetime.today().display("[hour]")
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/4-results/mod.typ | typst | MIT License | #import "../../lib/mod.typ": *
// #todo[solve these fricking frucking reference issues]
// // This section presents the results for #study.H-1.full in @s.r.study-1 and #study.H-2.prefix: #study.H-2.full in @s.r.study-2.
#let specs = (
cpu: [12th Gen Intel Core i7-12700H], // `lscpu`
arch: [64-bit x86-64], // `uname -m`
ram: [16GiB SODIMM 4800 MHz], // `sudo lshw -short -C memory`
OS: [NixOS Linux Kernel 6.6.30], // `uname -r`
)
= Results <s.results>
This section details the experiments conducted to test the hypotheses outlined in @intro-research-hypothesis. It begins by presenting the metrics used for quantitative comparison in #numref(<s.r.metrics>). Each scenario is then described in detail, see @s.r.scenarios, including its purpose and the experimental parameters for reproducibility. Finally, the results are interpreted and discussed.
#let spec-table = [
#figure(
{
show table.cell : it => {
if it.x == 0 {
set text(weight: "bold")
it
} else {
it
}
}
tablec(
columns: 2,
alignment: (left, left),
header: table.header(
[Type], [Component]
),
..specs.pairs().map(it => {
let type = it.at(0)
let component = it.at(1)
(titlecase(type), component)
}).flatten()
)
},
caption: [System specifications for the machine, all of the experiments have been run on. This includes all results for #acr("MAGICS") and `gbpplanner` experiments.]
)<t.specs>
]
#let exp = [
#h(1em)All experiments were performed on the same laptop, featuring a #specs.cpu CPU, #specs.ram RAM, and running #specs.OS, see @t.specs. Although the computational capabilities of the machine should not influence the results, these specifications are provided for completeness and transparency.
Generally in the following sections, results are to be compared against the original #gbpplanner@gbpplanner paper or results#h(1fr)obtained#h(1fr)for#h(1fr)this#h(1fr)thesis#h(1fr)using#h(1fr)the#h(1fr)`gbpplanner`
]
#v(-0.55em)
#grid(
columns: (1fr, 14em),
column-gutter: 1em,
exp,
v(0.75em) + spec-table + v(0.5em),
)
#v(-0.5em)
code@gbpplanner-code; expect results pertaining to this thesis to be presented in cold colors; #text(theme.mauve, "purple")#sp, #text(theme.lavender, "blue")#sl, #text(theme.teal, "teal")#stl, #text(theme.green, "green")#sg, and results from #gbpplanner in warm colors; #text(theme.maroon, "red")#sr, #text(theme.peach, "orange")#so, #text(theme.yellow, "yellow")#sy. Otherwise, when results are not presented in a comparative light, the colors are chosen to be distinct and easily distinguishable.
#include "./metrics.typ"
#include "./scenarios.typ"
#include "./study-1.typ"
#include "./study-2.typ"
#include "./study-3.typ"
|
https://github.com/jeffa5/typst-cambridge | https://raw.githubusercontent.com/jeffa5/typst-cambridge/main/slides/manual.typ | typst | MIT License | #import "cambridge.typ": cambridge-theme, title-slide, slide
#show: cambridge-theme
#title-slide(
title: [Cambridge `polylux` template],
authors: "<NAME>",
date: [2#super("nd") April 2024],
)
#slide(title: "Installation")[
You should have the `liberation` font installed, or set the `TYPST_FONT_PATHS` environment variable to its location.
]
#slide(title: "Getting started")[
```typst
// brings in the typst-slides bits too
#import "@preview/cambridge-slides:0.1.0": cambridge-theme, title-slide, slide
#show: cambridge-theme.with(
aspect-ratio: "4-3",
)
```
]
#slide(title: "Slide types")[
There are just two slide variants: `title-slide` and `slide`.
]
#slide(title: "Footer")[
The footer is built out of the `short-title`, `short-authors`, and the (internally calculated) `slide-number`.
]
#slide(title: "Debug slide", debug: true)[
You can view the debug layout of the main slide elements, see the red boxes, by setting the debug parameter:
```typst
#slide(title: "Debug slide", debug: true)[
debugged!
]
```
]
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/apa7/template/sections/quotes.typ | typst | MIT License | = Quotation
== Short Quotation (fewer than 40 words)
Effective teams can be difficult to describe because
#quote(attribution: [Ervin et al., 2018, p. 470])[
high performance along one domain does not translate to high performance along another
]
== Long Quotation (40 words or more)
=== Block quotation with parenthetical citation
Researchers have studied how people talk to themselves:
#quote(attribution: [Alderson-Day & Fernyhough, 2015, p. 957])[
Inner speech is a paradoxical phenomenon. It is an experience that is central to many people’s everyday lives, and yet it presents considerable challenges to any effort to study it scientifically. Nevertheless, a wide range of methodologies and approaches have combined to shed light on the subjective experience of inner speech and its cognitive and neural underpinnings.
]
=== Block quotation with narrative citation
Flores et al. (2018) described how they addressed potential researcher bias when working with an intersectional community of transgender people of color:
#quote(attribution: [p. 311])[
Everyone on the research team belonged to a stigmatized group but also held privileged identities. Throughout the research process, we attended to the ways in which our privileged and oppressed identities may have influenced the research process, findings, and presentation of results.
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/hyphenate_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Hyphenate between shape runs.
#set page(width: 80pt)
#set text(hyphenate: true)
It's a #emph[Tree]beard.
|
https://github.com/genericusername3/structogrammer | https://raw.githubusercontent.com/genericusername3/structogrammer/master/structogrammer/main.typ | typst | MIT License | #let structogram = {
let stroke- = stroke;
let localisation = (
"de": (
While: (condition) => [solange #condition],
For: (body) => [für #body],
ForIn: (element, container) => [für jedes #element aus #container],
ForTo: (start-declaration, end) => [von #start-declaration bis #end],
If: (condition) => [#condition?],
Break: (value) => [#value],
),
"en": (
While: (condition) => [while #condition],
For: (body) => [for #body],
ForIn: (element, container) => [for each #element in #container],
ForTo: (start-declaration, end) => [from #start-declaration until #end],
If: (condition) => [#condition?],
Break: (value) => [#value],
),
)
// Returns an array of needed columns for a diagram specification
// The returned array contains booleans for each column from left to right,
// with wide columns as `true` and narrow columns as `false`.
//
// Narrow columns can be of a fixed size while remaining space can be
// distributed among wide columns.
//
// See to-elements for an explanation of a diagram spec.
let allocate-columns(spec) = {
if spec == none or spec == () { return (false,) }
if type(spec) == content or type(spec) == str { return (true,) }
if type(spec) == array {
let allocated-columnss = spec.map(allocate-columns)
let wide-needed = 0
for allocated-columns in allocated-columnss {
wide-needed = calc.max(
allocated-columns.fold(
0, (cnt, el) => if (el) {cnt + 1} else {cnt} // count instances of `true`
),
wide-needed,
)
}
let narrows = (wide-needed + 1) * (0,)
for allocated-columns in allocated-columnss {
let far-left-narrows = 0
for column in allocated-columns {
if column { break }
far-left-narrows += 1
}
narrows.first() = calc.max(narrows.first(), far-left-narrows)
}
for allocated-columns in allocated-columnss {
let far-right-narrows = 0
for column in allocated-columns.rev() {
if column { break }
far-right-narrows += 1
}
narrows.last() = calc.max(narrows.last(), far-right-narrows)
}
for allocated-columns in allocated-columnss {
let wide-index = 0
let needed-before = 0
for column in allocated-columns {
if column {
narrows.at(wide-index) = calc.max(narrows.at(wide-index), needed-before)
wide-index += 1
needed-before = 0
continue
}
needed-before += 1
}
}
return narrows.map((count) => count * (false,)).intersperse(true).flatten()
}
assert(type(spec) == dictionary, message: "spec must be one of: none, str, content, array of specs, dictionary, got: " + str(type(spec)))
if (spec.keys() in (("Break",), ("Call",))) {
return (true,)
}
if (("While" in spec or ("For" in spec)) and "Do" in spec) {
assert(
spec.keys() in (
("While", "Do"), ("Do", "While"), ("For", "Do"), ("For", "To", "Do"), ("For", "In", "Do")
),
message: (
"Must loop with either While-Do, Do-While, For-Do or For-In-Do, found: "
+ spec.keys().join("-")
),
)
let allocated = allocate-columns(spec.Do)
return (false, ..allocated)
}
if (
"If" in spec
) {
assert(
spec.keys() in (
("If", "Then"), ("If", "Then", "Else"), ("If", "Else"),
),
message: (
"Conditional must be either If-Then(-Else), If-Else, found: "
+ spec.keys().join("-")
),
)
let then-allocated = allocate-columns(spec.at("Then", default: none))
let else-allocated = allocate-columns(spec.at("Else", default: none))
return (
..then-allocated,
..else-allocated,
)
}
assert(false, message: "Not a valid spec dictionary: " + repr(spec) + ", keys: " + repr(spec.keys()))
}
// Given any amount of grid.cell elements, return copies with x and y positions
// shifted by the passed dx and dy values.
//
// Cells without an x attribute will raise an error if dx isn't 0, y likewise.
let shift-cells(dx: 0, dy: 0, ..cells) = {
assert(
cells.named().len() == 0,
message: "shift-cells doesn't take any named arguments except dx and dy"
)
let shifted = ()
for cell in cells.pos() {
let args = (:)
if dx != 0 {
assert(
cell.has("x"),
message: "A cell must have an x attribute to be shifted horizontally",
)
args.x = cell.x + dx
} else {
if cell.has("x") { args.x = cell.x }
}
if dy != 0 {
assert(
cell.has("y"),
message: "A cell must have a y attribute to be shifted vertically",
)
args.y = cell.y + dy
} else {
if cell.has("y") { args.y = cell.y }
}
if cell.has("colspan") { args.colspan = cell.colspan }
if cell.has("rowspan") { args.rowspan = cell.rowspan }
if cell.has("align") { args.align = cell.align }
if cell.has("inset") { args.inset = cell.inset }
if cell.has("stroke") { args.stroke = cell.stroke }
if cell.has("fill") { args.fill = cell.fill }
if cell.has("breakable") { args.breakable = cell.breakable }
shifted.push(
grid.cell(
cell.body,
..args,
)
)
}
return shifted
}
// Given a grid.cell, return a copy with an added stroke in the specified direction.
let add-stroke(cell, dir: "bottom", stroke: black + 0.5pt) = {
let args = (:)
if "stroke" not in args { args.insert("stroke", (:)) }
if cell.has("x") { args.x = cell.x }
if cell.has("y") { args.y = cell.y }
if cell.has("colspan") { args.colspan = cell.colspan }
if cell.has("rowspan") { args.rowspan = cell.rowspan }
if cell.has("align") { args.align = cell.align }
if cell.has("inset") { args.inset = cell.inset }
if cell.has("stroke") { args.stroke = cell.stroke }
if cell.has("fill") { args.fill = cell.fill }
if cell.has("breakable") { args.breakable = cell.breakable }
args.stroke.insert(dir, stroke)
return grid.cell(
cell.body,
..args,
)
}
// Measure how many columns and rows a set of passed grid.cells would take up.
// The returned dictionary contains the following keys:
// - left, x: The x-coordinate of the first used column
// - top, y: The y-coordinate of the first used row
// - right: The x-coordinate of the last used column
// - bottom: The y-coordinate of the last used row
// - width: How many columns are occupied (i.e. from leftmost to rightmost column)
// - height: How many rows are occupied (i.e. from highest to lowest row)
//
// Cells have to have at least x and y attributes to be measured here.
let measure-cells(..cells) = {
assert(
cells.named().len() == 0,
message: "measure-cells doesn't take any named arguments"
)
assert(cells.pos().len() > 0, message: "Must provide at least one cell to measure")
let (min-x, min-y) = (none, none)
let (max-x, max-y) = (none, none)
for cell in cells.pos() {
assert(
cell.has("x") and cell.x != auto,
message: "Each measured cell has to have non-auto x"
)
assert(
cell.has("y") and cell.y != auto,
message: "Each measured cell has to have non-auto y"
)
if min-x == none or cell.x < min-x {
min-x = cell.x
}
if min-y == none or cell.y < min-y {
min-y = cell.y
}
if max-x == none or cell.x + cell.at("colspan", default: 1) - 1 > max-x {
max-x = cell.x + cell.at("colspan", default: 1) - 1
}
if max-y == none or cell.y + cell.at("rowspan", default: 1) - 1 > max-y {
max-y = cell.y + cell.at("rowspan", default: 1) - 1
}
}
return (
left: min-x,
top: min-y,
x: min-x,
y: min-y,
right: max-x,
bottom: max-y,
width: max-x - min-x + 1,
height: max-y - min-y + 1,
)
}
// Returns an array of grid.cell elements according to the passed diagram spec.
// Takes one positional argument, `spec`.
//
// A spec can be:
// - `none` or an emtpy array `()`: An empty cell,
// taking up at least a narrow column
// - a string or content: A cell containing that string or content,
// taking up at least a wide column
// - A dictionary: Control block (see below)
// - An array of specs: The cells that each element produced,
// stacked on top of each other. Wide columns
// are aligned to wide columns of other element
// specs and narrow columns consumed as needed.
//
// Specs can contain the following control blocks:
// - If/Then/Else: │╲▔▔▔▔╱│
// A conditional with the following keys: │ ╲??╱ │
// - `If`: The condition on which to branch │Y ╲╱ N│
// - `Then`: A diagram spec for the "yes"-branch ├───┬──┤
// - `Else`: A diagram spec for the "no"-branch │ … │ │
// Then and Else are both optional, but at least one must be present │ │ …│
// Examples: └───┴──┘
// - `(If: "debug mode", Then: ("print debug message"))`
// - `(If: "x > 5", Then: ("x = x - 1", "print x"), Else: "print x")`
// Columns: Takes up columns according to its contents next to one another,
// inserting narrow columns for empty branches
//
// - For/Do, For/To/Do, For/In/Do, While/Do, Do/While: ┌──────────┐
// A loop, with the loop control either at the top or bottom. │ While x │
// For/Do formats the control as "For $For", │ ┌───────┤
// For/To/Do as "For $For to $To", │ │ Do │
// For/In/Do as "For each $For in $In", └──┴───────┘
// While/Do and Do/While as "While $While".
// Order of specified keys matters.
// Examples:
// - `(While: "true", Do: "print \"endless loop\"")` (regular while loop)
// - `(Do: "print \"endless loop\"", While: "true")` (do-while loop)
// - `(For: "item", In: "Container", Do: "print item.name")`
// Columns: Inserts a narrow column left to its content.
//
// - Method call (Call)
// A block indicating that a subroutine is executed here. ┌┬──────────┬┐
// Only accepts the key `Call`, which is the string name ││ call() ││
// Example: └┴──────────┴┘
// - `(Call: "func()")`
// Columns: One wide column
//
// - Break/Return (Break)
// A block indicating that a subroutine is executed here. ┌───────────┐
// Only accepts the key `Break`, which is the target to break to │⮜ target │
// Example: └───────────┘
// - `(Break: "")`
// - `(Break: "to enclosing loop")`
// Columns: One wide column
//
// Named arguments:
// - columns: If you already allocated wide and narrow columns, `to-elements`
// can use them. Useful for sub-specs, as you'd usually generate
// allocations first and then do another recursive pass to fill them.
// The default, `auto` does exactly this on the highest recursion level.
// - stroke: The stroke to use between cells, or for control blocks.
// Note: to avoid duplicate strokes, every cell only adds strokes to
// its top and left side. Put the resulting cells in a container with
// bottom and right strokes for a finished diagram. See `structogram()`.
// Default: `0.5pt + black`
// - inset: How much to pad each cell. Default: `0.5em`
// - segment-height: How high each row should be. Default: `2em`
// - narrow-width: The width that narrow columns will be. Needed for diagonals in
// conditional blocks. Default: 1em
let to-elements(
spec,
columns: auto,
stroke: 0.5pt + black,
inset: 0.5em,
segment-height: 2em,
narrow-width: 1em,
) = {
if columns == auto {
columns = allocate-columns(spec)
}
if spec == none or spec == () {
return (
grid.cell(
box(height: segment-height, inset: inset)[],
x: 0, y: 0,
colspan: columns.len(),
rowspan: 1,
stroke: (top: stroke, left: stroke),
),
)
}
if type(spec) == content or type(spec) == str {
return (
grid.cell(
box(height: segment-height, inset: inset, align(horizon)[#spec]),
x: 0, y: 0,
colspan: columns.len(),
rowspan: 1,
stroke: (top: stroke, left: stroke),
),
)
}
if type(spec) == array {
let all-elements = ()
let y = 0
for subspec in spec {
let elements = to-elements(
subspec,
columns: columns,
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
)
elements = shift-cells(..elements, dy: y)
y = measure-cells(..elements).bottom + 1
for element in elements {
all-elements.push(element)
}
}
return all-elements
}
assert(type(spec) == dictionary, message: "spec must be one of: none, str, content, array of specs, dictionary, got: " + str(type(spec)))
if spec.keys() == ("Break",) {
return (
grid.cell(
box(
height: segment-height,
stack(
dir: ltr,
spacing: -inset / 2,
stack(
dir: ttb,
box(
width: segment-height / 2, height: segment-height / 2,
line(start: (0%, 100%), end: (100%, 0%), stroke: stroke),
),
box(
width: segment-height / 2, height: segment-height / 2,
line(start: (0%, 0%), end: (100%, 100%), stroke: stroke),
),
),
align(
horizon,
box(
inset: inset,
context { (localisation.at(text.lang, default: localisation.en).Break)(spec.Break) }
)
),
),
),
x: 0, y: 0,
colspan: columns.len(),
rowspan: 1,
stroke: (top: stroke, left: stroke),
),
)
}
if spec.keys() == ("Call",) {
return (
grid.cell(
stack(
dir: ltr,
spacing: inset / 2,
box(
width: segment-height / 5, height: segment-height,
line(start: (100%, 0%), end: (100%, 100%), stroke: stroke),
),
align(horizon, box(inset: inset, spec.Call)),
align(
right,
box(
width: segment-height / 5, height: segment-height,
align(left, line(start: (0%, 0%), end: (0%, 100%), stroke: stroke)),
),
),
),
x: 0, y: 0,
colspan: columns.len(),
rowspan: 1,
stroke: (top: stroke, left: stroke),
),
)
}
if (("While" in spec or "For" in spec) and "Do" in spec) {
assert(
spec.keys() in (
("While", "Do"), ("Do", "While"), ("For", "Do"), ("For", "To", "Do"), ("For", "In", "Do")
),
message: (
"Must loop with either While-Do, Do-While, For-Do or For-In-Do, found: "
+ spec.keys().join("-")
),
)
if spec.keys() in (("While", "Do"), ("For", "Do"), ("For", "To", "Do"), ("For", "In", "Do")) {
let condition = if "While" in spec {
context { (localisation.at(text.lang, default: localisation.en).While)(spec.While) }
} else if "In" in spec {
context { (localisation.at(text.lang, default: localisation.en).ForIn)(spec.For, spec.In) }
} else if "To" in spec {
context { (localisation.at(text.lang, default: localisation.en).ForTo)(spec.For, spec.To) }
} else {
context { (localisation.at(text.lang, default: localisation.en).For)(spec.For) }
}
let do-elements = shift-cells(
dx: +1, dy: +1,
..to-elements(
spec.Do,
columns:columns.slice(1, none),
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
)
)
return (
grid.cell(
box(height: segment-height, inset: inset, align(horizon, condition)),
x: 0, y: 0,
colspan: columns.len(),
rowspan: 1,
stroke: (left: stroke, top: stroke, right: none, bottom: none),
),
..do-elements,
grid.cell(
[],
x: 0, y: 1,
colspan: 1,
rowspan: measure-cells(..do-elements).bottom,
stroke: (left: stroke, top: none, right: none, bottom: none),
),
)
}
if spec.keys() == ("Do", "While") {
let do-elements = shift-cells(
dx: +1,
..to-elements(
spec.Do,
columns:columns.slice(1, none),
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
)
)
do-elements.at(-1) = add-stroke(
do-elements.at(-1),
dir: "bottom",
stroke: stroke,
)
return (
grid.cell(
box(
height: segment-height, inset: inset,
align(
horizon,
context { (localisation.at(text.lang, default: localisation.en).While)(spec.While) },
),
),
x: 0, y: measure-cells(..do-elements).bottom,
colspan: columns.len(),
rowspan: 1,
stroke: (left: stroke, top: none, right: none, bottom: stroke),
),
..do-elements,
grid.cell(
[],
x: 0, y: 0,
colspan: 1,
rowspan: measure-cells(..do-elements).bottom + 1,
stroke: (left: stroke, top: stroke, right: stroke, bottom: none),
),
)
}
assert(false, message: "Malformed While spec: " + repr(spec) + ", keys: " + repr(spec.keys()))
}
if "If" in spec {
if (
spec.keys() == ("If", "Then")
or spec.keys() == ("If", "Else")
or (
spec.keys() == ("If", "Then", "Else")
and (
spec.Then in ((), none)
or spec.Else in ((), none)
)
)
) {
let positive = "Then" in spec and spec.Then not in ((), none)
let then-elements = shift-cells(
dx: if positive { 0 } else { +1 }, dy: +1,
..to-elements(
if positive { spec.Then } else { spec.Else },
columns: if positive { columns.slice(0, -1) }
else { columns.slice(1, none) },
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
)
)
return (
grid.cell(
colspan: if positive { columns.len() - 1 } else { 1 },
x: 0, y: 0,
stroke: (top: stroke, left: stroke, right: none, bottom: stroke),
box(
height: segment-height,
width: if positive { auto } else { narrow-width },
stack(
dir: ttb,
line(
start: (0%, 0%),
end: (100%, 100%),
stroke: stroke,
),
context{ set text(size: 0.75 * text.size)
context { move(
dy: -measure([Y]).height - inset / 2,
dx: inset / 2,
[Y]
) }
},
if not positive {
move(
dx: narrow-width - inset,
dy: -segment-height + inset,
context {
let cond = (localisation.at(text.lang, default: localisation.en).If)(spec.If)
box(width: measure(cond).width, cond)
},
)
}
)
)
),
grid.cell(
colspan: if positive { 1 } else { columns.len() - 1 },
x: if positive { columns.len() - 1 } else { 1 }, y: 0,
stroke: (top: stroke, left: none, right: none, bottom: stroke),
box(
height: segment-height,
width: if positive { narrow-width } else { auto },
align(right,
stack(
dir: ttb,
line(
start: (0%, 100%),
end: (100%, 0%),
stroke: stroke,
),
context{ set text(size: 0.75 * text.size)
context { move(
dy: -measure([N]).height - inset / 2,
dx: -inset / 2,
[N]
) }
},
if positive {
move(
dx: -narrow-width + inset,
dy: -segment-height + inset,
context {
let cond = (localisation.at(text.lang, default: localisation.en).If)(spec.If)
box(width: measure(cond).width, cond)
},
)
}
)
)
)
),
..then-elements,
grid.cell(
[],
x: if positive { columns.len() - 1 } else { 0 }, y: 1,
colspan: 1,
rowspan: measure-cells(..then-elements).bottom,
stroke: (top: stroke, left: stroke),
),
)
}
if spec.keys() == ("If", "Then", "Else") {
let then-alloc-columns = allocate-columns(spec.Then)
let wide-column-index = 0
let then-wide-columns = then-alloc-columns.fold(
0, (cnt, el) => if (el) {cnt + 1} else {cnt}
)
let end-narrow-column-index = 0
let then-end-narrow-columns = then-alloc-columns.rev().position((el) => el)
if then-end-narrow-columns == none { then-end-narrow-columns = then-alloc-columns.len() }
let (then-columns, else-columns) = ((), ())
for column in columns {
if column {
wide-column-index += 1
if wide-column-index <= then-wide-columns {
then-columns.push(column)
continue
}
}
if wide-column-index < then-wide-columns {
then-columns.push(column)
continue
}
if end-narrow-column-index < then-end-narrow-columns and not column {
end-narrow-column-index += 1
then-columns.push(column)
continue
}
else-columns.push(column)
}
let then-elements = shift-cells(
dy: +1,
..to-elements(
spec.Then,
columns: then-columns,
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
)
)
let else-elements = shift-cells(
dx: then-columns.len(), dy: +1,
..to-elements(
spec.Else,
columns: else-columns,
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
)
)
let (then-size, else-size) = (
measure-cells(..then-elements),
measure-cells(..else-elements),
)
let filler = ()
if then-size.bottom < else-size.bottom {
filler = (
grid.cell(
[],
x: then-size.left,
y: then-size.bottom + 1,
colspan: then-size.width,
rowspan: else-size.height - then-size.height,
stroke: (top: stroke, left: stroke),
),
)
} else if then-size.bottom > else-size.bottom {
filler = (
grid.cell(
[],
x: else-size.left,
y: else-size.bottom + 1,
colspan: else-size.width,
rowspan: then-size.height - else-size.height,
stroke: (top: stroke, left: stroke),
),
)
}
let condition-element = context {
let cond = (localisation.at(text.lang, default: localisation.en).If)(spec.If)
box(width: measure(cond).width, cond)
}
return (
grid.cell(
colspan: then-columns.len(),
x: 0, y: 0,
stroke: (top: stroke, left: stroke, right: none, bottom: stroke),
box(
height: segment-height,
stack(
dir: ttb,
line(
start: (0%, 0%),
end: (100%, 100%),
stroke: stroke,
),
context{ set text(size: 0.75 * text.size)
context { move(
dy: -measure([Y]).height - inset / 2,
dx: inset / 2,
[Y]
) }
},
align(
right,
context {
move(
dx: measure(condition-element).width / 2,
dy: -segment-height + inset,
condition-element,
)
},
),
)
)
),
grid.cell(
colspan: else-columns.len(),
x: then-columns.len(), y: 0,
stroke: (top: stroke, left: none, right: none, bottom: stroke),
box(
height: segment-height,
align(right,
stack(
dir: ttb,
line(
start: (0%, 100%),
end: (100%, 0%),
stroke: stroke,
),
context{ set text(size: 0.75 * text.size)
context { move(
dy: -measure([N]).height - inset / 2,
dx: -inset / 2,
[N]
) }
},
)
)
)
),
..then-elements,
..else-elements,
..filler,
)
}
assert(false, message: "Malformed If spec: " + repr(spec) + ", keys: " + repr(spec.keys()))
}
assert(false, message: "Not a valid spec dictionary: " + repr(spec) + ", keys: " + repr(spec.keys()))
}
// Return a finished structogram element (in blocks).
// Positional arguments:
// - spec: The structogram spec, see `to-elements()` for documentation
// Named arguments:
// - width: Width for the entire diagram, `auto` (default) behaves like `box`
// - title: A title for the structogram, usually a method name with arguments.
// Default: `none`
// - stroke: The stroke to use for the structogram. Default: `0.5pt + black`
// - inset: How much to pad cells in the structogram. Default: `0.5em`
// - segment-height: Height of rows in the structogram. Default: `2em`
// - narrow-width: Width of narrow or empty columns in the structogram. Default: `1em`
// - fill: A fill to use for the main structogram block. Default: `white`
// - secondary-fill: A fill to use for the outer block added if a title is provided. Default: `rgb("#eee")`
// - text-fill: Fill to use for structogram text. Default: `black`
// - title-fill: Fill to use for structogram title. Default: `black`
let structogram(
spec,
width: auto,
title: none,
stroke: 0.5pt + black,
inset: 0.5em,
segment-height: 2.5em,
narrow-width: 1em,
fill: white,
secondary-fill: rgb("eee"),
text-fill: black,
title-fill: black,
) = {
let columns = allocate-columns(spec)
if width == auto {
width = columns.fold(0pt, (width, column) => if column { width + 2 * segment-height + stroke-(stroke).thickness } else { width + narrow-width + stroke-(stroke).thickness })
}
let s-grid = grid(
..to-elements(
spec,
columns: columns,
stroke: stroke,
inset: inset,
segment-height: segment-height,
narrow-width: narrow-width,
),
columns: columns.map(col => if (col) { 1fr } else { narrow-width }),
)
if title != none {
return box(
stroke: stroke,
inset: inset * 2,
radius: inset,
fill: secondary-fill,
width: width,
)[
#set text(fill: title-fill)
#v(inset / 2)
#heading(bookmarked: false, outlined: false, numbering: none, level: 4)[#title]
#v(0.5em)
#set text(fill: text-fill)
#box(stroke: (bottom: stroke, right: stroke, top: none, left: none), fill: fill, inset: stroke.thickness / 2, s-grid)
]
}
return box(width:width, fill: fill, [#set text(fill: text-fill);#s-grid], stroke: (bottom: stroke, right: stroke))
}
structogram
} |
https://github.com/andriwild/typst-thesis-template | https://raw.githubusercontent.com/andriwild/typst-thesis-template/main/README.md | markdown | MIT License | Template based on https://github.com/ls1intum/thesis-template-typst
|
https://github.com/WinstonMDP/knowledge | https://raw.githubusercontent.com/WinstonMDP/knowledge/master/sequence_calculus.typ | typst | #import "cfg.typ": cfg
#show: cfg
= Исчисление секвенций
Такого рода исчисления изучаются в теории доказательств. Они являются исчислениями
генценовского типа.
Секвенция - это $Gamma tack.r Delta$. Тут $tack.r$ не является знаком вывода из ИВ.
Аксиомы - секцвенции, в левых и правых частях которых встречаются только перменные,
причём некоторая переменная встречается в обеих частях.
Правила вывода:
+ $(Gamma tack.r A, Delta quad Gamma tack.r B, Delta)/(Gamma tack.r A and B, Delta)$
+ $(A, B, Gamma tack.r Delta)/(A and B, Gamma tack.r Delta)$
+ $(Gamma tack.r A, B, Delta)/(Gamma tack.r A or B, Delta)$
+ $(A, Gamma tack.r Delta quad B, Gamma tack.r Delta)/(A or B, Gamma tack.r Delta)$
+ $(Gamma, A tack.r B, Delta)/(Gamma tack.r A -> B, Delta)$
+ $(Gamma tack.r A, Delta quad Gamma tack.r B, Delta)/(A -> B, Gamma tack.r Delta)$
+ $(A, Gamma tack.r Delta)/(Gamma tack.r not A, Delta)$
+ $(Gamma tack.r A, Delta)/(not A, Gamma tack.r Delta)$
Контрпример - это набор значений, при которых левая часть секвенции истинна, а правая
ложна.
Корректность и полнота ИС: секвенция выводима $<=>$ она не имеет контрпримера.
Правило сечения: $(Gamma tack.r Delta, A quad Gamma, A tack.r Delta)/(Gamma tack.r Delta
)$
Правило сечения нарушает важное свойство "подформульности" ИС, хотя сохраняет
корректность и полноту.
|
|
https://github.com/Nrosa01/TFG-2023-2024-UCM | https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Pruebas/setup.typ | typst | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let project(
body,
) = {
// Set the document's basic properties.
set page(numbering: "1", number-align: center)
set text(font: "New Computer Modern", lang: "es", hyphenate: false)
show math.equation: set text(weight: 400)
// Set paragraph spacing.
show par: set block(above: 1.2em, below: 1.2em)
set heading(numbering: "1.1")
set par(leading: 0.75em)
// Main body.
set par(justify: true)
body
} |
|
https://github.com/DavinDiaz/reporte_psiconsciencia | https://raw.githubusercontent.com/DavinDiaz/reporte_psiconsciencia/main/README.md | markdown | # reporte_psiconsciencia
Plantilla de reporte con typst para Psiconsciencia
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/invoice-maker/1.1.0/README.md | markdown | Apache License 2.0 | # Invoice Maker
Generate beautiful invoices from a simple data record.
<img
alt="Example invoice"
src="thumbnail.png"
height="768"
>
## Features
- **Simple, yet Powerful**
- Write invoices as simple `.typ` or `.yaml` files
- Support for cancellations, discounts, and taxes
- **Multilingual**
- Integrated support for English and German
- Easy to add more languages by adding a translation dictionary
(Check out this example:
[custom-language.typ](
https://github.com/ad-si/invoice-maker/blob/master/examples/custom-language.typ))
- **Customizable**
- User your own banner image
- Customize the colors and fonts
- **Elegant**
- Modern design with a focus on readability
- PDFs with a professional look
- **Stable**
- Visual regression tests to ensure consistent output
- **Free and Open Source**
- ISC License
## Usage
```typst
#import "@preview/invoice-maker:1.0.0": *
#show: invoice.with(
language: "en", // or "de"
banner_image: image("banner.png"),
invoice_id: "2024-03-10t183205",
…
)
```
Check out the [GitHub repository](https://github.com/ad-si/invoice-maker)
for more information and examples.
|
https://github.com/hugo-b-r/insa-template-typst | https://raw.githubusercontent.com/hugo-b-r/insa-template-typst/master/examples/long-report.typ | typst | #import "../templates/long-report.typ":project
#show: project.with(
title: "A spoonful of title",
authors: ("<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>",),
)
#lorem(42)
= Premier Lorem
== Premier sous-Lorem
=== Premier sous sous lorem
#lorem(42)
=== Second sous sous lorem
#lorem(42)
== Second sous lorem
=== Troisieme sous sous lorem
#lorem(42)
=== Quatrieme sous sous lorem
#lorem(42)
= Deuxieme Lorem
== Troisieme sous-Lorem
=== Cinquieme sous sous lorem
#lorem(42)
=== Sixieme sous sous lorem
#lorem(42)
== Quatrieme sous lorem
=== Septieme sous sous lorem
#lorem(42)
=== Huitieme sous sous lorem
#lorem(42)
|
|
https://github.com/electratype/electratype | https://raw.githubusercontent.com/electratype/electratype/master/src/lib/assets/initial.typ | typst | #set par(justify: true)
#set text(
size: 10pt,
hyphenate: true,
lang: "en"
)
#set page(
margin: 1cm
)
= Heading 1
Some text to try it out.
== Heading 2 |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/hydra/0.2.0/src/lib.typ | typst | Apache License 2.0 | #import "/src/core.typ"
#import "/src/util.typ"
#let hydra-anchor() = [#metadata(()) <hydra-anchor>]
#let hydra(
sel: heading,
prev-filter: (ctx, p, n) => true,
next-filter: (ctx, p, n) => true,
display: core.display,
fallback-next: false,
is-book: false,
paper: "a4",
page-size: auto,
top-margin: auto,
loc: none,
) = {
let (sel, filter) = util.into-sel-filter-pair(sel)
assert((paper, page-size, top-margin).filter(x => x != auto).len() >= 1,
message: "Must set one of (`paper`, `page-size` or `top-margin`)",
)
if top-margin == auto {
if page-size == auto {
page-size = util.page-sizes.at(paper, default: none)
assert.ne(page-size, none, message: util.oxi.strfmt("Unknown paper: `{}`", paper))
page-size = page-size.values().fold(10000mm, calc.min)
}
top-margin = (2.5 / 21) * page-size
}
let func = loc => {
let ctx = (
is-book: is-book,
top-margin: top-margin,
loc: loc,
)
let (prev, next, loc) = core.get-adjacent-from(ctx, sel, filter)
ctx.loc = loc
let prev-eligible = prev != none and prev-filter(ctx, prev, next)
let next-eligible = next != none and next-filter(ctx, prev, next)
let prev-redundant = (
prev-eligible
and next-eligible
and ctx.top-margin != none
and core.is-redundant(ctx, prev, next)
)
if prev-eligible and not prev-redundant {
display(ctx, prev)
} else if fallback-next and next-eligible {
display(ctx, next)
}
}
if type(loc) == location {
func(loc)
} else {
locate(func)
}
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/cancel_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Inverted
$a + cancel(x, inverted: #true) - cancel(x, inverted: #true) + 10 + cancel(y) - cancel(y)$
$ x + cancel("abcdefg", inverted: #true) $
|
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/compilation.typ | typst | #import "@preview/codly:0.2.1": *
#show: codly-init.with()
#codly()
#set text(
font:"Roboto Serif"
)
= Compilation <compilation>
Rappel de sémantique : le chemin vers un fichier est :
#quote(block: true)[
`~/parent_dir/filename.ext`
]
On croisera ici les extensions `o`, `h`, `c`, `out`, `ml`, `mli`, `cmi`, et `cmo`
#emph[Remarque : l’extension ne modifie pas le fichier et n’est même pas "nécessaire", tout n’est que convention afin de donner des indications aux programmes et à l’utilisateur.]
== Compilation d’un seul fichier <compilation-dun-seul-fichier>
=== En C <en-c>
#quote(block: true)[
`gcc filename.c`
]
=== En OCaml <en-ocaml>
#quote(block: true)[
`ocamlc filename.ml`
]
#quote(block: true)[
`ocamlopt filename.ml`
]
Le fichier est produit sous le nom `a.out` et exécutable avec cette commande :
#quote(block: true)[
`./a.out`
]
On peut changer le nom de l’exécutable on ajoutant `-o exec_name`
== Compilation de plusieurs fichiers <compilation-de-plusieurs-fichiers>
=== En C <en-c-1>
On pourrait utiliser la commande suivante mais nous allons procéder autrement
#quote(block: true)[
`gcc fileA.c fileB.c fileC.c`
]
Nous allons compiler les fichiers un par un afin de rendre le projet plus modulaire
Pour exporter des fonctions on utilise une fichier d’en-tête `filename.h` dans lequel on y met les prototypes de no fonctions/variables
```c
#ifndef A_H
#define A_H
// prototypes
#endif
```
On l’importe ensuite dans les fichiers `.c` qui en ont besoin en ajoutant la ligne`#include "filename.h"` avec les autres importations.
#emph[Remarque : Par convention (et pour éviter des problèmes après modifications du code) on importe le fichier d’en-tête dans le fichier de code]
On peut compiler un fichier (dont on sera dépendant) avec la commande suivante
#quote(block: true)[
`gcc -c filename.c`
]
On obtiendra alors un fichier `.o`
Enfin on compile le projet avec cette commande après avoir compiler chaque fichier
#quote(block: true)[
`gcc -o nom_exec a.o b.o c.o d.o`
]
=== En OCaml <en-ocaml-1>
C’est assez similaire au C
Les fichiers `.ml` sont ceux dans lesquels nous codons tandis que les fichiers `.mli` contiendront les prototypes de ce que l’on exportera
Pour compiler individuellement on utilise la commande
#quote(block: true)[
`ocamlc -c filename.ml`
]
Elle produit deux fichiers
- `filename.cmo`
- `filename.cmi`
Grâce à ce fichier `.cmi` on peut compiler un fichier `b.ml` qui dépend de `a.ml` après avoir compiler ce dernier sans rien faire d’autre
#emph[Remarque : c’est à peu près l’équivalent des `.h` produits automatiquement]
On peut tout compiler avec
#quote(block: true)[
`ocamlc -c nom_exec fileA.cmo fileB.cmo`
]
Nous allons cependant voir un procédé n’ayant pas besoin de compiler tous les fichiers et dans l’ordre (comme ce que nous avons fait en C)
On utilise alors un fichier `.mli` qui est vraiment l’analogue du `.h`
Exemple d’un fichier exportant une fonction f
`a.mli`
```ml
val f : int -> int
```
On peut ensuite exécuter un fichier `b.ml` s’appuyant sur `a.mli` avec cette commande
#quote(block: true)[
`ocamlc -c a.mli b.ml`
]
Désormais on utilisera cette commande si l’on souhaite compiler le fichier `a.ml`
#quote(block: true)[
`ocamlc -c a.mli a.ml`
]
== Remarques générales <remarques-générales>
- La grande différence avec le C est que le OCaml gère l’inférence de type, il peut produire lui-même son fichier d’en-tête `cmi`.
- Les fonctions qui n’ont pas pour vocation à être utilisées dans d’autres fichiers ne doivent pas être exportées.
|
|
https://github.com/typst-community/guidelines | https://raw.githubusercontent.com/typst-community/guidelines/main/src/util.typ | typst | Creative Commons Attribution Share Alike 4.0 International | // packages
#import "@preview/mantys:0.1.3"
// helper functions and variables
#let do-dont(do, dont) = {
mantys.sourcecode(do, title: "Do")
mantys.sourcecode(dont, title: "Don't")
}
#let mode = (
mark: raw(lang: "typst", "[markup-mode]"),
code: raw(lang: "typst", "{code-mode}"),
math: raw(lang: "typst", "$math-mode$"),
)
#let _link = link
#let link(..args) = text(eastern, _link(..args))
#let discord(..args) = link("https://discord.gg/2uDybryKPe", ..args)
#let typst(path, ..body) = link(
"https://typst.app/" + path.trim("/", at: start),
body.pos().at(0, default: path),
)
#let docs(path, ..rest) = typst("docs/" + path.trim("/", at: start), ..rest)
#let reference(path, ..rest) = docs("reference/" + path.trim("/", at: start), ..rest)
#let chapter = heading.with(level: 1)
|
https://github.com/xdoardo/co-thesis | https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/main.typ | typst | #import "@local/thesis:1.0.0": *
#import "./includes.typ": *
#set cite(style: "numerical")
#show bibliography: set text(13pt)
#show: thesis.with(
title: "Program Transformations in the Delay Monad",
subtitle: "A Case Study for Coinduction via Copatterns and Sized Types",
author: "<NAME>",
figure: align(bottom, image("./figures/Minerva.png", width: 28%)),
university: [University of Milan],
department: [Department of Computer Science and Technology],
degree: "Master of Science",
msg: include "./msg.typ",
supervisor: [Prof. <NAME>],
year: [Academic Year 2022-2023],
number: [num. 973597],
)
#pagebreak()
#pagebreak(to: "odd")
#include "./chapters/index.typ"
#pagebreak()
#pagebreak(to: "odd")
#appendix([#include "./appendices/index.typ"])
#set page(header: none)
#pagebreak()
#pagebreak(to: "odd")
#include "./thanks.typ"
#pagebreak(to: "odd")
#bibliography("./db.bib")
|
|
https://github.com/HiiGHoVuTi/requin | https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/graph/bipartition.typ | typst | #import "../lib.typ" : *
#show heading: heading_fct
Soit $G = (S,A)$ un graphe puis $phi : A -> {mono(R), mono(B)}$. On note $r$ le nombre d'arêtes rouges ($mono(R)$).
Un sous-graphe induit _triangle_ est un triplet ${x,y,z} subset S$ tel que $G[{x,y,z}] tilde.eq K_3$.
On suppose que dans tout sous-graphe induit triangle possède au moins une arête rouge.
On note $n in NN$ la taille de la plus grande partie de $S$ qui induit un graphe biparti.
Si $v in S$, on note $N(v)$ l'ensemble des voisins de $v$ reliés à lui par une arête rouge.
$ N(v) := { w, {x,w} in phi^(-1)(mono(R)) } $
#question(1)[Montrer que $N(v)$ est un stable.]
#question(1)[Que dire de $N(v)$ et $N(w)$ si ${v,w} in.not A$ ?]
// TODO(Juliette): mets au moins une question intermédiaire en plus...
#question(3)[Montrer que $ |S| >= (4r)/n $]
|
|
https://github.com/Sematre/typst-kit-thesis-template | https://raw.githubusercontent.com/Sematre/typst-kit-thesis-template/main/sections/04_content.typ | typst | = First Content Chapter
The content chapters of your thesis should of course be renamed.
How many chapters you need to write depends on your thesis and cannot be said in general.
Check out the examples theses in the SDQ Wiki:
#link("https://sdq.kastel.kit.edu/wiki/Abschlussarbeit/Studienarbeit")
Of course, you can split this .typ file into several files if you prefer.
== First Section
#lorem(600)
=== A Subsection
#lorem(600)
==== A Subsubsection
#lorem(100)
== Second Section
#lorem(500)
= Second Content Chapter
#lorem(600)
== First Section
#lorem(600)
== Second Section
#lorem(600) |
|
https://github.com/jneug/typst-tools4typst | https://raw.githubusercontent.com/jneug/typst-tools4typst/main/tools4typst.typ | typst | MIT License |
#import "is.typ"
#import "def.typ"
#import "assert.typ"
#import "alias.typ"
#import "get.typ"
#import "math.typ"
#let is-none( ..values ) = {
return none in values.pos()
}
#let is-auto( ..values ) = {
return auto in values.pos()
}
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/show-closure-paren.typ | typst | Apache License 2.0 | #show raw: it => it.text.ends-with(">")
#show raw: it => (
it.text.ends-with(">")
)
#show raw: it => if true {
set text(1.2em)
} else {
it
}
#show raw: it => {
it
}
|
https://github.com/0x1B05/english | https://raw.githubusercontent.com/0x1B05/english/main/cnn10/content/20240308.typ | typst | #import "../template.typ": *
#pagebreak()
= 20240308
== International Women's Day
What's up lovely people, happy Friday! And happy International Women's day, we will start this #underline[March 8th] by putting this #strike[sparklight] #underline[spotlight] on two #strike[different making] #underline[difference-making] #strike[women's] #underline[women whose] lives and actions shine bright #underline[to] these day.
First up, #underline[civil rights pioneer <NAME>] at her age of 15 in the year 1955, she #strike[was] refused to give up her seat to a whiter passenger on a bus in #underline[Montgomery, Alabama]. That was nine months before #strike[, where the ..]#underline[Rosa Parks famously] did the same#strike[, for] #underline[. For her act of] protest, Claudette was arrested and accused of #strike[a] #strike[violating segregation]#underline[the city's *segregation*] #strike[grows] #underline[rules] and assaulting a police officer. She #strike[lead the ...]#underline[later *petitioned*] to clear her record and 66 years later her request was granted in 2021.
Claudette, who's now 84 years old, #underline[remained an unsung] hero of the #strike[ration] #underline[racial] justice #strike[moving] #underline[movement], until the book about her life by #underline[<NAME>oose] #strike[one] #underline[won] the #strike[national book words for young people's literature] #underline[National Book Awards for Young People's Literature] in 2009.
Next, we *honor* the life of #underline[<NAME>], an #underline[*activist*] who helped New Zealand become the first country in the world to allow women to vote back in 1893. Originally born in #underline[Liverpool,] England, she #strike[immgrated] #underline[immigrated] to New Zealand in her early 20s and became an #underline[activist] as a member of Women's Christian #underline[Temperance] Union, which advocated for women *suffrage* as a #underline[way to] fight for #underline[*liquor*] prohibition. Kate, however, _took her #underline[*activism*] way beyond that_, become a leader in New Zealand suffrage movement, fighting for issues _ranging from representation #strike[and parliament] #underline[in Parliament] to freedom from wearing the #underline[*corset*]_. #underline[Her activism work in] New Zealand #underline[and abroad] inspired women's rights #strike[move it] #underline[movement] around the world#underline[,] rise up.
=== words, phrases and sentences
==== words
- _International Women's Day_
- _segregation_
- _petition_
- _unsung_
- _activist_
- _temperance_
- _liquor_
- _suffrage_
- _activism_
- _corset_
==== phrases
- _put the spotlight on..._
- _advocate for_
- _range from ... to ..._
==== sentences
- _Claudette, who's now 84 years old, remained an unsung hero of the racial justice movement, until the book about her life by <NAME> won the National Book Awards for Young People's Literature in 2009._
- _..., which advocated for women *suffrage* as a way to fight for liquor prohibition._
=== 回译
==== 原文
What's up lovely people, happy Friday! And happy International Women's day, we will start this March 8th by putting this spotlight on two difference-making women whose lives and actions shine bright to these day.
First up, civil rights pioneer <NAME> at her age of 15 in the year 1955, she refused to give up her seat to a whiter passenger on a bus in Montgomery, Alabama. That was nine months before Rosa Parks famously did the same . For her act of protest, Claudette was arrested and accused of the city's segregation rules and assaulting a police officer. She later petitioned to clear her record and 66 years later her request was granted in 2021.
Claudette, who's now 84 years old, remained an unsung hero of the racial justice movement, until the book about her life by <NAME> won the National Book Awards for Young People's Literature in 2009.
Next, we honor the life of <NAME>, an activist who helped New Zealand become the first country in the world to allow women to vote back in 1893. Originally born in Liverpool, England, she immigrated to New Zealand in her early 20s and became an activist as a member of Women's Christian Temperance Union, which advocated for women suffrage as a way to fight for liquor prohibition. Kate, however, took her activism way beyond that, become a leader in New Zealand suffrage movement, fighting for issues ranging from representation in Parliament to freedom from wearing the corset. Her activism work in New Zealand and abroad inspired women's rights movement around the world, rise up.
==== 参考翻译
亲爱的朋友们,周五快乐!今天是国际妇女节,让我们开始这个三月八号,聚焦两位不同的女性,她们的生活和行动至今闪耀着光芒。
首先,我们来看看公民权利先驱<NAME>。1955年,她15岁时在Alabama Montgomery的一辆公共汽车上,拒绝为一位白人乘客让座。这发生在Rosa Parks之后的九个月。由于她的抗议行为,Claudette被捕并被指控违反城市的种族隔离规定,以及袭击警察。她后来申请清除她的记录,66年后的2021年,她的请求获得了批准。
现年84岁的Claudette一直是种族公正运动中不为人知的英雄,直到2009年<NAME>写了一本书讲述她生平,获得了青少年文学国家图书奖。
接下来,我们向<NAME>的生命致敬。她是一名活动家,帮助新西兰于1893年成为世界上第一个允许妇女投票的国家。原籍英国Liverpool,她20多岁时移居新西兰,并成为妇女基督教禁酒联盟的成员,该组织主张通过妇女选举权来反对酒精禁令。然而,凯特的活动远不止于此,她成为了新西兰妇女选举运动的领袖,为议会中的女性代表权以及女性不再穿紧身衣的自由而奋斗。她在新西兰和国外的活动激励了世界各地的妇女权利运动的崛起。
==== 1st
#strike[Dear friends] #underline[What's up lovely people], happy Firday. #strike[Today's] #underline[And happy] international Women's day, let's start this March 8th#strike[, focusing] #underline[by putting this sportlight] on two #strike[different] #underline[difference-making] women whose lives and actions still shine brightly these days.
First, let's head to the #strike[civilian] #underline[civil] rights pioneer <NAME>. She refused to give #underline[up] #strike[a] #underline[her] seat to a whiter passenger on a bus at the age of her 15 in 1955. It happens 9 months after Rosa Parks did the same. Because of her #underline[act of] #strike[protesting] #underline[protest], Claudette was arrested and accused of #underline[the *citys's segregation rule*] and #strike[attacking] #underline[assaulting] a police officer. She later #strike[asked] #underline[petitioned] to clear her record, 66 years later, in 2021, her request was #strike[allowed] #underline[granted].
Claudette, who's been 84 years old, #underline[remained an unsung hero of the racial justice movement], until the book about her life written by <NAME> won the National Book Awards for Young People's Literature.
Next up, we honor the life of <NAME> #strike[who's a] #underline[, an] activist#strike[, helping] #underline[who helped] New Zealand become the first country in the world#strike[that allows] #underline[to allow] women to vote back in 1893. #strike[She was] #underline[Originally] born in Liverpool, England, #strike[and] #underline[she] immigrated to New Zealand in her early 20s and became #underline[an activist as] a member of #underline[Women's Christian Temperance Union], which #strike[believes in opposing liquor prohibition through women's voting] #underline[advocated for women suffrage as a way to fight for liquor prohibition]. However #strike[the action Kate has done is far more than this] #underline[Kate, however, *took* her activism way beyond that], #strike[she then] became the leader #strike[of the New Zealand women voting movement] #underline[in New Zealand suffrage movement], fighting for #strike[the rights of women's respresent and the freedom of no ... in the meeting] #underline[issues ranging form representation in Parliament to freedom from wearing the corset]. #strike[The activity she led] #underline[Her activism work in New Zealand and abroad] inspired #strike[women] #underline[women's rights] movements across the world#underline[, rise up].
== Brain-computer Interfaces
Next up, we examined *cutting-edge* technology behind a human #strike[branch] #underline[brain chip] that can translate #strike[neuro] #underline[neural] activity into commands on a computer. You may remember <NAME> announced about 5 weeks ago that a person received the implant from his company #underline[Neuralink] for the first time. But there are other companies like #underline[Synchron] who #strike[has] #underline[have] been implanting people in its *clinical trial* in the U.S. for years. CNN's #underline[Chief Medical] Correspandent, doctor #underline[<NAME>], goes behind the scenes with the #strike[focus] #underline[*folks* at Synchron] to learn how this #strike[grant breaking] #underline[groundbreaking] technology aims at changing lives for the better.
Up, down, left, right. Everything you're watching happen on this screen right now is being controlled only with Mark's thoughts.
So that#strike['s just a] #underline[just sent out a] health #strike[modification] #underline[notification].
He describes it #strike[is] #underline[as] #strike[constructing] #underline[contracting] and relaxing his brain: It takes concentration. It's #underline[a] pretty involved process. It's one I don't take #strike[likely] #underline[lightly].
This's all been pretty sudden for Mark. He was diagnosed with #underline[ALS] in 2021. Mark has #underline[since] lost control of his hands and arms. He #underline[would] likely #strike[loses] #underline[lose] his voice. Markd didn't hesitate to sign #underline[a clinical] trial to have this #strike[plays] #underline[placed] in his brain. It's called #underline[a *stentrode*].
#strike[I mean] #underline[To me,] it gives me opportunities to continue to do things that I'm able to do now#strike[. Just about to think] #underline[just by thinking] about it. In the world #underline[of] the brain-computer interfaces or BCIs, _it is still early days_. In fact, up #strike[to] #underline[until] recently, it #strike[almost let] #underline[mostly led to] monkeys being able to play pong. But Synchron was one of the first companies in the world to get the FDA approval for human trials, and Mark is one of those first humans.
It's all the #strike[brain trial] #underline[brainchild of] this man, doctor <NAME>. For people who have got #underline[*paralysis* or *motor impairment*,] but they have that part of brain still working, then if you can put a device in, get the information, get it out of the brain. Then you can turn what previously was the signal controlling your body into a signal that controls the digital devices. The #underline[*stentrode* is the device that Oxley and his team at Synchron] created. It's #underline[a *cage* of thin] wired *mesh* with #strike[electron centrals] #underline[electrode sensors] that can detect #strike[a lectural] #underline[the electrical] brain activity#strike[. T] #underline[, t]ranslate that activity and then transmit it to devices such as a phone or a computer.
It's amazing. That's all I could say.
And just like a #strike[stand] #underline[*stent*], it doesn't require open brain surgery. Instead it's able to travel through the body's natural network veins, #underline[and sit in a major vein] right in the middle of the brain. Our brain has millions of *neurons* #underline[firing] electrical #underline[impulses] that control our movements, everything from shaking hands to taking a step. Each #underline[and every] one of those actions is associated with a specific electrical signature. The *stentrode* #strike[, watch] #underline[which] again, sets right here around #underline[that area] of the brain responsible for movement, learns to recognize those specific #underline[electrical] patterns, and #strike[eventually] #underline[essentially] creates your own personalized dictionary of movement. It's a hope for patients in the future, and a chance for Mark to continue living #strike[the] #underline[a] full life now.
=== words, phrases and sentences
==== words
- _examine_
- _cutting-edge_
- _implant_
- _folk_
- _groundbreaking_
- _contract_
- _involved_
- _stentrode_
- _clinical trial_
- _brainchild_
- _paralysis_
- _motor_
- _impairment_
- _stent_
- _cage_
- _mesh_
- _electrode_
- _vein_
==== phrases
- _go behind the scene_
- _change lives for better_
- _take sth lightly_
- _up until recently_
- _fire electrical impulses_
==== sentences
- _In the world the brain-computer interfaces or BCIs, it is still early days._
- _It's still early days_
=== 回译
==== 原文
Next up, we examined a cutting-edge technology behind a human brain chip that can translate neural activity into commands on a computer. You may remember <NAME> announced about 5 weeks ago that a person received the implant from his company Neuralink for the first time. But there are other companies like Synchron who have been implanting people in its clinical trial in the U.S. for years. CNN's Chief Medical Correspandent, doctor <NAME>, goes behind the scenes with the folks at Synchron to learn how this groundbreaking technology aims at changing lives for the better.
Up, down, left, right. Everything you're watching happen on this screen right now is being controlled only with Mark's thoughts.
So that just sent out a health notification.
He describes it as contracting and relaxing his brain: It takes concentration. It's a pretty involved process. It's one I don't take lightly.
This is all been pretty sudden for Mark. He was diagnosed with ALS in 2021. Mark has since lost control of his hands and arms. He would likely lose his voice. Markd didn't hesitate to sign a clinical trial to have this placed in his brain. It's called a stentrode.
To me, it gives me opportunities to continue to do things that I'm able to do now just by thinking about it. In the world of the brain-computer interfaces or BCIs, it is still early days. In fact, up until recently, it mostly led to monkeys being able to play pong. But Synchron was one of the first companies in the world to get the FDA approval for human trials, and Mark is one of those first humans.
It's all the brainchild of this man, doctor <NAME>. For people who have got paralysis or motor impairment, but they have that part of brain still working, then if you can put a device in, get the information, get it out of the brain. Then you can turn what previously was the signal controlling your body into a signal that controls the digital devices. The stentrode is the device that Oxley and his team at Synchron created. It's a cage of thin wired mesh with electrode sensors that can detect the electrical brain activity, translate that activity and then transmit it to devices such as a phone or a computer.
It's amazing. That's all I could say.
And just like a stent, it doesn't require open brain surgery. Instead it's able to travel through the body's natural network veins, and sit in a major vein right in the middle of the brain. Our brain has millions of neurons firing electrical impulses that control our movements, everything from shaking hands to taking a step. Each and every one of those actions is associated with a specific electrical signature. The stentrode which again, sets right here around that area of the brain responsible for movement, learns to recognize those specific electrical patterns, and essentially creates your own personalized dictionary of movement. It's a hope for patients in the future, and a chance for Mark to continue living a full life now.
==== 参考翻译
接下来,我们将研究人脑芯片背后的一项前沿技术,它可以将神经活动转化为计算机上的指令。你可能还记得<NAME>大约五周前宣布,有人首次接受了他的公司Neuralink的植入器。但是像Synchron这样的其他公司已经在美国进行临床试验多年了。CNN的首席医学记者、医生<NAME>博士与Synchron的工作人员一起走进幕后,了解这项开创性技术如何旨在改善生活。
上、下、左、右。你现在在屏幕上看到的一切都是仅凭Mark的想法控制的。
刚才它发送了一条健康通知。
他描述它为收缩和放松他的大脑:这需要集中注意力。这是一个相当复杂的过程。我不敢轻视。
对于马克来说,这一切都是相当突然的。他在2021年被诊断患有肌萎缩侧索硬化症。自那以后,马克已经失去了对手和胳膊的控制。他可能还会失去声音。马克毫不犹豫地签署了一项临床试验,将这个装置植入他的大脑。它被称为stentrode。
对我来说,它给了我继续做现在能做的事情的机会,只需想一想。在脑-计算机接口或BCI的世界中,现在仍然是早期阶段。事实上,直到最近,它大多是让猴子能够玩乒乓球。但是Synchron是世界上第一批获得FDA批准进行人体试验的公司之一,而马克就是其中的一位试验者。
汤姆·奥克斯利博士,这一切都是这个人的创意。对于那些瘫痪或运动障碍的人来说,他们的大脑仍在工作,如果你能放置一个设备,获取信息,从大脑中获取信息。然后,您可以将以前控制身体的信号转换为控制数字设备的信号。stentrode是Oxley和他在Synchron团队创造的设备。它是由细丝网笼和电极传感器组成的,可以检测电脑活动,将该活动转换然后将其传输到诸如手机或计算机之类的设备。
太神奇了。这就是我能说的。
就像支架一样,它不需要开颅手术。相反,它能够穿过身体的自然静脉网络,并位于大脑中间的一条主要静脉中。我们的大脑有数百万个神经元发射控制我们的运动的电冲动,从握手到迈步的一切。每一个行动都与特定的电信号相关联。stentrode再次设置在负责运动的大脑区域周围,学习识别这些特定的电信号模式,从而创建自己的个性化运动字典。这对未来的患者是一种希望,也是马克继续过上充实生活的机会。
==== 1st
Next up, we #strike[will learn about] #underline[*examined*] an #strike[advanced] #underline[*cutting-edged*] technology #strike[about] #underline[behind] #strike[chips in human beings' brains] #underline[a human brain chip], which is able to translate the #strike[neuron] #underline[*neural*] activities to #strike[instructions] #underline[commands] on a computer. You may remember about 5 weeks ago, <NAME> announced #strike[someone] #underline[a person] had been *implanted* the Neuralink of his company #underline[for the first time]. But other companies like Synchron #strike[had started] #underline[have been implanting people in its] clinical trials in the U.S. for #strike[many] years. CNN's chief medical #strike[journalist] #underline[Correspandent], doctor <NAME> #underline[*goes behind the scenes*] with #strike[workers] #underline[*folks*] #strike[in] #underline[at] Synchron#strike[, learning] #underline[to learn] about how this #strike[creative] #underline[*groundbreaking*] technology aiming at #strike[improve our lives] #underline[*changing lives for better*]:
Up, down, left, right. All you #strike[have been seeing] #underline[are watching] on the screen are just #underline[being] controlled #strike[by] #underline[with] Mark's thoughts.
It just sent #underline[out] a healthcare notification.
He describes it as #strike[shrinking] #underline[*contracting*] and relaxing his brain: it #strike[need attention] #underline[takes *concentration*]. #strike[This is] #underline[It's] a quite #strike[complicated] #underline[*involved*] process that I #strike[am unable to look it down] #underline[don't *take lightly*].
To Mark, all happened suddenly. He was diagnosed #underline[with ALS in 2021] Since then, Mark had lost the control of his hands and arms. He could lose his void then. Mark signed a clinical trial without hesitation, #strike[loading] #underline[placing] this device called stentrode into his brain.
To me, it gives me an opportunity to do things that I am #strike[doing] #underline[able to do now] just by #strike[thoughts] #underline[thinking]. In the world of Brain-computer Interfaces as known as BCI, it is #strike[now only at a early stage] #underline[still *early days*]. In fact, #underline[*up until recently*], it mostly #strike[makes monkeys] #underline[led to monkeys being able to] play pong. However, Synchron was one of the first #strike[party of] companies in the world #strike[which were granted people to do clinical] #underline[to *get the FDA approval* for human] trials, and Mark is one of those people.
#strike[Doctor <NAME>, created all these] #underline[It's all the *brainchild* of this man, doctor <NAME>ley]. To people who #underline[have got *paralysis*] or #strike[have a mobile-barrier] #underline[*motor impairment*], #strike[their brains still work] #underline[but they *have that part of brain still working*], where if you could put a device, acquire the information from the brain#strike[ and then translate neuron]#underline[. Then you can turn what previously] signals controlling the body to signals controlling digital devices. The stentrode is the device #strike[made by Oxley and his team at Synchron]#underline[that Oxley and his team at Synchron created]#strike[, which is consisted of ... and electrical sensors, being able to check the activities in computer and then transmit them to devices like phones or computers] #underline[It's a *cage* of thin wired *mesh* with *electrode sensors* that can *detect* the electrical brain activity, translate that activity and then transmit it to devices such as a phone or a computer].
It's amazing, that's #strike[what] #underline[all] I #strike[can] #underline[could] say.
Just like a stent, it #strike[needn't] #underline[doesn't *require*] open brain surgery. On the contrast, it is able to #strike[cross] #underline[*travel through*] the #underline[the body's natural] network #underline[*veins*] and #strike[located at] #underline[sit in] a #underline[*major vein* in the middle] of our brain. Our brains have millions of neurons #strike[sending]#underline[*firing*] electrical impulses to control our movements, #strike[ranging] #underline[everything] from shaking hands to #strike[steping] #underline[taking a step]. Each #strike[movement] #underline[action] is associated with a specific #strike[signal] #underline[electrical *signature*]. The stentrode#strike[ is again set] #underline[which again, sets right here] around that area of the brain #underline[responsible for movement], #strike[learning] #underline[learns] to #strike[identify] #underline[recognize] these specific #strike[signals] #underline[electrical patterns], and #strike[making his own] #underline[essentially creates your] own personalized movement dictionary. It is not only a kind of hope #strike[to] #underline[for] patients in the future, bu also a chance for Mark to lead a #strike[fullfil] #underline[full] life.
== Political News
President <NAME> delivered his State of The Union speech last night, a *high-stakes* moment that he's preparing to face the former President <NAME> in #strike[the] #underline[a] likely *rematch* in the *general elections* in November. Trump and Biden dominated their respective Super Tuesday races this week. While two of their respective party rivals, former U.N. #strike[embassidor] #underline[*ambassador*] <NAME> on the Republic #strike[sight] #underline[side], and #strike[respresent] #underline[Representative Dean Phillips] on a democratic #strike[sight] #underline[side] both ended their campaigns.
We will show you some key points of President Biden's address, and break down how both sides of political #underline[*aisle*] responding to this State of Union on Monday's show, but there's some other political news #strike[was attaching] #underline[worth touching] on today, the U.S. Congress avoiding a partial government shutdown this week#strike[. A green] #underline[, agreeing] to continue funding the government on a temporary basis until #strike[I] #underline[they] can vote on individuals spending #strike[bills] #underline[deals] also known as #strike[a preparation] #underline[appropriation] bills. Top democrats and Republicans have already agreed to six funding bills for #strike[varies] #underline[various] government agencies and #underline[are] now working towards #strike[a green] #underline[agreements] for six others before #strike[I knew] #underline[a new] Marh #strike[27] #underline[22(twenty-second)] deadline. This is the first since 2018 the Congress has not funded the government by #underline[tying] all #strike[time proparation] #underline[appropriations] bills into a single deal.
=== words, phrases and sentences
==== words
- _high-stakes_
- _rematch_
- _general election_
- _ambassador_
==== phrases
- _on one's side_
==== sentences
- _This is the first since 2018 the Congress has not funded the government by *tying all appropriations bills into a single deal*_.
- _There's some other political news *worth touching* on today_
=== 回译
==== 原文
President <NAME> delivered his State of The Union speech last night, a high-stakes moment that he's preparing to face the former President <NAME> in a likely rematch in the general elections in November. Trump and Biden dominated their respective Super Tuesday races this week. While two of their respective party rivals, former U.N. ambassador <NAME> on the Republic side, and Representative De<NAME>ps on a democratic side both ended their campaigns.
We will show you some key points of President Biden's address, and break down how both sides of political aisle responding to this State of Union on Monday's show, but there's some other political news worth touching on today, the U.S. Congress avoiding a partial government shutdown this week, agreeing to continue funding the government on a temporary basis until they can vote on individuals spending deals also known as appropriation bills. Top democrats and Republicans have already agreed to six funding bills for various government agencies and are now working towards agreements for six others before a new March 22nd(twenty-second) deadline. This is the first since 2018 the Congress has not funded the government by tying all appropriations bills into a single deal.
==== 参考翻译
美国总统乔·拜登昨晚发表了他的国情咨文演讲,这是一个高风险的时刻,他正在准备在11月的大选中可能再次面对前总统唐纳德·特朗普的挑战。本周,特朗普和拜登分别在各自的超级星期二竞选中占据主导地位。而两位候选人的党内竞争对手——共和党方面的前联合国大使尼基·黑利和民主党方面的众议员迪恩·菲利普斯——都已结束了他们的竞选活动。
我们周一会展示一些拜登总统演讲的关键点,并分析两党对这次国情咨文的反应,但今天还有一些其他值得关注的政治新闻,美国国会本周避免了部分政府停摆,同意继续暂时资助政府,直到他们能够就个别支出协议达成投票,也就是所谓的拨款法案。民主党和共和党的高层已经就各个政府机构的六项资助法案达成一致,并正在努力在3月22日之前就另外六项达成协议。这是自2018年以来,国会首次未通过将所有拨款法案捆绑成一项协议来资助政府。
==== 1st
American President <NAME> delivered his #strike[the] State of The Union speech last night, #strike[which is] a high-stakes moment#strike[, who]#underline[he] is preparing #strike[for the challenge from] #underline[to face] the former President <NAME> #strike[in November's general elections]#underline[in a likely *rematch* in the general elections in November]. This week, Trump and Biden *dominated* #strike[on] their #underline[respective] Super Tuesday #strike[Elections] #underline[*races*]. While two #strike[candidate] #underline[of their respective party] rivals, #underline[former U.N. ambassador <NAME> on Republic side] and #underline[Representative Dean Phillips on a democratic side] have both *ended* their campaign.
We will show some key points in President Biden's #strike[speech] #underline[address] and break down #strike[the bipartisan response] #underline[how both sides of political aisle responding] to this State of The Union Speech on Monday's show, but there #strike[are] #underline[is] some other political news worth touching today#strike[. The Congress granted the funding for government to avoid some governments shutdown until they can vote ... in individuals,] #underline[, the U.S. Congress avoiding a partial government shutdown this week, agreeing to continue funding the government *on a temporary basis until they can vote on individuals spending deals* also] known as appropriation #underline[bills.] #strike[The top of democrats and republic has] #underline[*Top democrats and republicans* have] agreed #strike[on the] #underline[to] six #underline[funding bills for various government agencies] and are now #strike[trying to another six appropriations] #underline[working towards agreements for six others] before #underline[a new] March #strike[22th] #underline[*22nd*] #underline[deadline]. This is the first time since 2018 that the Congress #strike[doesn't tied all the appropriations .. into a .. to fund the governments] #underline[has not funded the government by *tying all appropriations bills into a single deal*].
== Dead Galaxy
Next up, the oldest dead galaxy ever observed#underline[. It was spotted] with the #underline[James Webb] Space Telescope. And astronomers and researchers say, this galaxy existed when the universal was only 700 million years into its current age of about 13.8 billion years.
So what is a dead galaxy, it is essentially a galaxy that no longer has the ability to form new stars, because #strike[it didn't have] #underline[there isn't] enough gas #strike[it] #underline[that's] need to create them. Some factors can cause the gas to disappear or #underline[*dissipate*] are a *super massive* black hole, stars violently interacting#strike[ in], and new stars consuming all the remaining gas when they#underline['re] born. The astronomers and researchers observing this newly discovered dead galaxy have been left puzzled, and they're still trying to *uncover* the reason the stars there #strike[leaves] #underline[lived] fast and died young more than 13 billion years ago.
=== words
- _dissipate_
- _uncover_
- _remaining_
- _universe_
=== 回译
==== 原文
Next up, the oldest dead galaxy ever observed. It was spotted with the James Webb Space Telescope. And astronomers and researchers say, this galaxy existed when the universal was only 700 million years into its current age of about 13.8 billion years.
So what is a dead galaxy, it is essentially a galaxy that no longer has the ability to form new stars, because there isn't enough gas that's needed to create them. Some factors can cause the gas to disappear or dissipate are a super massive black hole, stars violently interacting, and new stars consuming all the remaining gas when they're born. The astronomers and researchers observing this newly discovered dead galaxy have been left puzzled, and they're still trying to uncover the reason the stars there lived fast and died young more than 13 billion years ago.
==== 参考翻译
接下来,我们要说的是有史以来观测到的最古老的死亡星系。这是由<NAME>太空望远镜发现的。天文学家和研究人员表示,这个星系在宇宙年龄仅有7亿年的时候就存在了,而现在宇宙年龄已经约为138亿年了。
那么,什么是死亡星系呢?实质上,它是一个不再具有形成新恒星能力的星系,因为没有足够的气体来形成它们。导致气体消失或消散的一些因素包括超大质量黑洞、恒星之间的激烈相互作用,以及新恒星在出生时消耗了所有剩余的气体。观测到这个新发现的死亡星系的天文学家和研究人员感到困惑,他们仍在努力揭示那里的恒星130亿年前快速生存和早逝的原因。
==== 1st
Next, we will talk about the oldest dead galaxy that has #underline[ever] been observed#strike[in the history ]#underline[. It was spotted with] by James Webb Telescope. The astronomers and researchers says, the galaxy existed when the #underline[*universe*] was only about 700 million years #underline[into its current age of about] 13.8 billion years.
So what is a dead galaxy? Actually, it is #underline[essentially] a galaxy that #strike[is unable to] #underline[no longer has the ability to] form new stars for the shortage of gas #underline[that's needed to create them]. Some factors causing the gas disappear or *dissipate* #strike[include] #underline[are] super massive black holes,#strike[interacting violently among stars]#underline[stars violently interacting] and #strike[all remained gas being consumed when a new star was born] #underline[new stars consuming all the remaining gas when they're born]. The astronomers and researchers #strike[who are] observing this #strike[new] #underline[newly] discovered dead galaxy #strike[feel] #underline[have left] puzzled, still trying to uncover the reason why stars there #strike[over 13 billion years ago] led such a short life and died early #underline[more than 13 billion years ago].
|
|
https://github.com/AsiSkarp/grotesk-cv | https://raw.githubusercontent.com/AsiSkarp/grotesk-cv/main/src/template/content/references.typ | typst | The Unlicense | #let meta = toml("../info.toml")
#import meta.import.path: reference-entry
#import "@preview/fontawesome:0.4.0": *
#let icon = meta.section.icon.references
#let language = meta.personal.language
#let include-icon = meta.personal.include_icons
= #if include-icon [#fa-icon(icon) #h(5pt)] #if language == "en" [References] else if language == "es" [Referencias]
#v(5pt)
#if language == "en" [
#reference-entry(
name: [<NAME>, Resistance Leader],
company: [Cyberdyne Systems],
telephone: [+1 (555) 654-3210],
email: [<EMAIL>],
)
#reference-entry(
name: [<NAME>, CEO],
company: [Tyrell Corporation],
telephone: [+1 (555) 987-6543],
email: [<EMAIL>],
)
] else if language == "es" [
#reference-entry(
name: [<NAME>, Líder de la Resistencia],
company: [Cyberdyne Systems],
telephone: [+1 (555) 654-3210],
email: [<EMAIL>],
)
#reference-entry(
name: [<NAME>, CEO],
company: [Tyrell Corporation],
telephone: [+1 (555) 987-6543],
email: [<EMAIL>],
)
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/grid-1_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#rect(width: 100%, height: 1em)
- #rect(width: 100%, height: 1em)
- #rect(width: 100%, height: 1em)
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/layout/aligned%20environment/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#align(center + bottom, quantum-circuit(1, $X$, 1)) |
https://github.com/antran22/typst-cv-builder | https://raw.githubusercontent.com/antran22/typst-cv-builder/main/lib/resume/projects.typ | typst | MIT License | #import "@preview/cmarker:0.1.0"
#import "./components.typ": *
#import "../util.typ": *
#let ResumeProjectsSection(projects) = {
stick_together(
threshold: 60pt,
[= Projects],
grid(
columns: (1fr),
rows: (auto),
row-gutter: 24pt,
..projects.map(project => {
ResumeEntry(
title: project.name,
title-r: project.description,
subtitle: project.date,
subtitle-r: project.keywords.join(", "),
)
ResumeItem(
cmarker.render(project.summary)
)
})
)
)
} |
https://github.com/asouris/Apuntes-CC3501 | https://raw.githubusercontent.com/asouris/Apuntes-CC3501/main/template/conf.typ | typst | #let departamentos = (
adh: (
nombre: "Área de Humanidades",
logo: "adh.svg"
),
das: (
nombre: "Departamento de Astronomía",
logo: "das.svg"
),
dcc: (
nombre: "Departamento de Ciencias de la Computación",
logo: "dcc.svg"
),
dfi: (
nombre: "Departamento de Física",
logo: "dfi.svg"
),
dgf: (
nombre: "Departamento de Geofísica",
logo: "dgf.svg"
),
dic: (
nombre: "Departamento de Ingeniería Civil",
logo: "dic.svg"
),
die: (
nombre: "Departamento de Ingeniería Eléctrica",
logo: "die.svg"
),
dii: (
nombre: "Departamento de Ingeniería Industrial",
logo: "dii.svg"
),
dim: (
nombre: "Departamento de Ingeniería Matemática",
logo: "dim.svg"
),
dimec: (
nombre: "Departamento de Ingeniería Mecánica",
logo: "dimec.svg"
),
dimin: (
nombre: "Departamento de Ingeniería de Minas",
logo: "dimin.svg"
),
diqbm: (
nombre: "Departamento de Ingeniería Química, Biotecnología y Materiales",
logo: "diqbm.svg"
),
geo: (
nombre: "Deparamento de Geología",
logo: "geo.svg"
)
)
#let conf(
titulo: none,
subtitulo: none,
departamento: "dcc",
profesores: (),
auxiliares: [],
curso: "",
fuente: "New Computer Modern",
doc,
autores:[]
) = {
set text(lang: "es", font: fuente)
// Formato de headings. Por defecto (P1., P2., etc)
//set heading(numbering: "P1.")
let header = [
#stack(dir: ltr,
// El primer elemento del header es el texto, apilado usando un stack.
align(bottom+left, stack(dir: ttb, spacing: 3pt, "Facultad de Ciencias Físicas y Matemáticas",
departamentos.at(departamento).nombre,
curso
)),
// Acá va el logo.
align(bottom+right, box(height: 50pt, image("logos/"+ departamentos.at(departamento).logo)))
)
#v(-5pt)
#line(length: 100%, stroke: 0.4pt)
]
let profesores-title = "Profesor";
let autores-title = "Autor";
// Manejar singular o plural dependiendo de la cantidad de profesores/auxiliares
if profesores.len() > 1 {
profesores-title = profesores-title + "es"
}
if autores.len() > 1 {
autores-title = autores-title + "es"
}
let title = align(center + horizon)[
#grid(row-gutter: 11pt,
text(25pt, titulo)
)
#v(5pt)
#align(right + bottom)[#grid(columns: 170pt, row-gutter: 6pt,
align(left)[*#profesores-title:* #profesores.join(", ", last: " y ")],
align(left)[*#autores-title:* #autores.join(", ", last: " y ")]
)]
]
// Configuración del tamaño de página, márgenes y header
style(styles => { // Usamos la función "style" para acceder a los estilos actuales y medir headerHeight correctamente
let headerHeight = measure(header, styles).height
let headerSep = 20pt // Separación entre header y contenido
set page("us-letter",
margin: (left: 1in,
right: 1in,
top: 0.5in + headerHeight + headerSep,
bottom: 1in),
header: header,
header-ascent: headerSep)
title
doc
})
}
|
|
https://github.com/lctzz540/typst-journal-template | https://raw.githubusercontent.com/lctzz540/typst-journal-template/main/template.typ | typst | // Variables
#let IEEE_COLOR = (
Title: rgb("#004495"),
Section: rgb("#004496"),
BoldText: rgb("#004495"),
)
#let FONT_WEIGHT = (
title: 24pt,
header: 8pt,
author: 11pt,
body: 10pt,
h1: 12pt,
ack: 10pt,
ref: 12pt,
)
#let IEEEmembership(it) = {
text(style: "italic", it)
}
// Macros
// Parse `content` to string.
#let parse_content(content) = {
if type(content) == type("") {
return content
}
else if content.has("children") {
return content.children.map(
(item) => {
if item.has("body") {
return item.body.text
} else if item == [ ] {
return " "
} else {
return " "
}
}
).join("")
} else if content.has("body") {
return item.body.text
} else {
assert(false, message: "Invalid input.")
}
}
// Template
// This function gets your whole document as its `body` and formats
// it as an article in the style of the IEEE.
#let ieee(
// The paper's title.
title: "Viêm túi thừa đại tràng",
// Transaction/Journal name.
journal-name: "Viêm túi thừa đại tràng",
// An array of authors. For each author you can specify a name,
// department, organization, location, and email. Everything but
// but the name is optional.
authors: (),
// The paper's abstract. Can be omitted if you don't have one.
abstract: none,
// A list of index terms to display after the abstract.
index-terms: (),
// The article's paper size. Also affects the margins.
paper-size: "us-letter",
// The path to a bibliography file if you want to cite some external
// works.
bibliography-file: none,
// The paper's content.
body
) = {
// Set document metdata.
set document(title: parse_content(title), author: authors.map(author => author.name))
// Set the body font.
set text(font: "STIX Two Text", size: FONT_WEIGHT.body)
// Configure the page.
set page(
paper: paper-size,
background: box(width: 5in, height: 5in, image("watermark.png", fit: "stretch")),
// The margins depend on the paper size.
margin: if paper-size == "a4" {
(x: 41.5pt, top: 80.51pt, bottom: 89.51pt)
} else {
(
x: (50pt / 216mm) * 100%,
top: (55pt / 279mm) * 100%,
bottom: (64pt / 279mm) * 100%,
)
},
header: locate(loc => {
set text(FONT_WEIGHT.header)
if loc.page() == 1 {
box(width: 0.35in, height: 0.35in, image("logo.png"))
h(1fr)
journal-name
h(4em)
counter(page).display("1")
v(4pt, weak: true)
line(length: 100%, stroke: 1pt)
} else if calc.rem(loc.page(), 2) == 0 {
counter(page).display("1")
h(1fr)
journal-name
v(4pt, weak: true)
line(length: 100%, stroke: 1pt)
} else {
let author_title = ""
if authors.len() == 1 {
author_title = authors.at(0).name
} else {
author_title = authors.at(0).name.split(" ").at(-1)
author_title = [#upper[#author_title] et al.]
}
[#title]
h(1fr)
counter(page).display("1")
v(4pt, weak: true)
line(length: 100%, stroke: 1pt)
}
}
),
)
// Configure equation numbering and spacing.
set math.equation(numbering: "(1)")
show math.equation: set block(spacing: 0.65em)
// Configure lists.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt)
// Configure headings.
set heading(numbering: "I.A.1.")
show heading: it => locate(loc => {
// Find out the final number of the heading counter.
let levels = counter(heading).at(loc)
let deepest = if levels != () {
levels.last()
} else {
1
}
set text(FONT_WEIGHT.body, weight: "regular", fill: IEEE_COLOR.Section)
if it.level == 1 [
// First-level headings are smallcaps.
// We don't want to number of the acknowledgment section.
#let is-ack = it.body in ([Acknowledgment], [Acknowledgement])
#set align(center)
#set text(if is-ack { FONT_WEIGHT.ack } else { FONT_WEIGHT.h1 })
#show: smallcaps
#v(20pt, weak: true)
#if it.numbering != none and not is-ack {
numbering("I.", deepest)
h(7pt, weak: true)
}
#it.body
#v(13.75pt, weak: true)
] else if it.level == 2 [
// Second-level headings are run-ins.
#set par(first-line-indent: 0pt)
#set text(style: "italic")
#v(10pt, weak: true)
#if it.numbering != none {
numbering("A.", deepest)
h(7pt, weak: true)
}
#it.body
#v(10pt, weak: true)
] else [
// Third level headings are run-ins too, but different.
#if it.level == 3 {
numbering("1)", deepest)
[ ]
}
_#(it.body):_
]
})
// Set footnote behavior
set footnote.entry(
separator: "",
clearance: 0em,
)
// Display the paper's title.
v(3pt, weak: true)
align(
center,
text(24pt, font: "Arimo", fallback: false, fill: IEEE_COLOR.Title, title, weight: "bold")
)
v(8.35mm, weak: true)
for i in range(calc.ceil(authors.len() / 3)) {
let end = calc.min((i + 1) * 3, authors.len())
let is-last = authors.len() == end
let slice = authors.slice(i * 3, end)
grid(
columns: slice.len() * (1fr,),
gutter: 12pt,
..slice.map(author => align(center, {
text(12pt, author.name)
if "location" in author [
\ #author.location
]
if "email" in author [
\ #link("mailto:" + author.email)
]
}))
)
if not is-last {
v(16pt, weak: true)
}
}
v(40pt, weak: true)
// Start two column mode and configure paragraph properties.
show: columns.with(2, gutter: 12pt)
set par(justify: true, first-line-indent: 1em)
show par: set block(spacing: 0.65em)
// Display abstract and index terms.
if abstract != none [
#set text(9pt, weight: "bold")
#h(1em)_Abstract_---#abstract
#if index-terms != () [
_Index terms_---#index-terms.join(", ")
]
#v(2pt)
]
// Display the paper's contents.
body
// Display bibliography.
if bibliography-file != none {
show bibliography: set text(8pt)
bibliography(bibliography-file, title: text(12pt)[References], style: "ieee")
}
} |
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Codici/Codifica.typ | typst | Creative Commons Zero v1.0 Universal | #import "../Metodi_defs.typ": *
*Codificare* un messaggio consiste semplicemente nell'associare ad
un vettore $m in Z_(p)^(k)$ (il messaggio in chiaro) una parola in
$C subset.eq ZZ_(p)^(k)$ (il messaggio cifrato). La codifica di $m$
rispetto ad una matrice generatrice $G$ é data da $m G$, che come
giá visto appartiene a $C$.
D'altro canto, *decodificare* un messaggio consiste nel ricostruire
a ritroso $m in Z_(p)^(k)$ a partire dalla parola in $C subset.eq
ZZ_(p)^(k)$ associata. Si noti come debba venire anche messa in
conto la possibilitá che si siano verificati degli errori durante
la trasmissione, pertanto per determinare quale sia la parola in
$C$ associata ad $m$ non basta svolgere il prodotto matriciale
all'inverso. Si costruisca pertanto una matrice come segue:
#line(length: 100%)
+ Si inizializzi una matrice (vuota) $Sigma = (sigma_(i,j))$;
+ Si inizializzi un insieme $Delta$ al valore $ZZ_(p)^(n) - C$;
+ Si inizializzi un indice $i$ al valore $1$;
+ Si inseriscano nella prima riga di $Sigma$ le parole di $C$.
La parola nulla (che é sempre presente in qualsiasi $C$) deve
essere obbligatoriamente posta in $sigma_(1, 1)$, mentre le
altre parole possono essere inserite in ordine qualsiasi.
+ Si ponga in $sigma_(i, 1)$ una qualsiasi delle parole di
$ZZ_(p)^(n)$ che hanno peso minimo tra le parole di $Delta$;
+ In ciascuna cella $sigma_(i, j)$ con $0 lt.eq j lt.eq n$ si
inserisca la parola $sigma_(i, 1) + sigma_(1, j)$;
+ Si sostituisca $Delta$ con $Delta - {sigma_(i, j) : 0 lt.eq j lt.eq n}$;
+ Se $Delta$ non é l'insieme vuoto, $i$ viene incrementato di $1$
e l'algoritmo riprende dal punto 5, altrimenti termina.
#line(length: 100%)
Quando viene ricevuta la parola $y in ZZ_(p)^(n)$, tale parola viene corretta
con la parola di $C$ che in $Sigma$ appartiene alla stessa colonna di $y$.
#example[
Sia $C in ZZ_(2)^(4) = {0000, 1110, 1011, 0101}$ un codice, e sia
$y = 1111$ la parola da decodificare (e correggere). Si costruisca
una matrice $Sigma$ come presentato nell'algoritmo. Si ha:
$ Delta = ZZ_(2)^(4) - C = {0001, 0010, 0100, 1000, 1001, 1010, 1100,
0110, 0011, 1101, 0111, 1111} $
La prima riga é data dalle parole di $C$, ponendo $sigma_(1,1) = 0000$
e disponendo le altre a piacere. Siano queste disposte ordinatamente
come $1011, 0101, 1110$.
Per quanto riguarda la seconda riga, si osservi come le parole in
$Delta$ con distanza minima sono $0001$, $0010$, $0100$ e $1000$.
Si scelga $1000$. Si ha quindi che le parole della seconda riga
sono, ordinatamente:
#set math.mat(column-gap: 2em)
$ mat(
1000 + 0000 = 1000,
1000 + 1011 = 0011,
1000 + 0101 = 1101,
1000 + 1110 = 0110
) $
Si ha poi $Delta := Delta - {1000, 0011, 1101, 0110} =
{0001, 0010, 0100, 1001, 1010, 1100, 0111, 1111}$
Per quanto riguarda la terza riga, si osservi come le parole in
$Delta$ con distanza minima sono $0001$, $0010$, $0100$. Si scelga
$0100$. Si ha quindi che le parole della terza riga sono, ordinatamente:
$ mat(
0100 + 0000 = 0100,
0100 + 1011 = 1111,
0100 + 0101 = 0001,
0100 + 1110 = 1010
) $
Si ha poi $Delta := Delta - {0100, 1111, 0001, 1010} =
{0010, 1001, 0111, 1100}$
Per quanto riguarda la quarta riga, si osservi come la parola in
$Delta$ con distanza minima é $0010$. Si ha quindi che le parole
della quarta riga sono, ordinatamente:
$ mat(
0010 + 0000 = 0010,
0010 + 1011 = 1001,
0010 + 0101 = 0111,
0010 + 1110 = 1100
) $
Si ha poi $Delta := Delta - {0010, 1001, 1100, 0111} = {}$, e
l'algoritmo termina. La matrice risultante é:
#set math.mat(column-gap: 1em)
$ mat(
0000, 1011, 0101, 1110;
1000, 0011, 1101, 0110;
0100, 1111, 0001, 1010;
0010, 1001, 0111, 1100;
) $
Trovandosi $y$ nella seconda colonna, questa viene corretta con $1011$.
]
Siano $C_(1)$ e $C_(2)$ due codici lineari in $ZZ_(p)^(n)$ di stessa
dimensione. Si dice che $C_(1)$ e $C_(2)$ sono *equivalenti* se è possibile
ottenere tutte le parole di uno a partire da quelle dell'altro applicando:
+ Una permutazione delle posizioni $1, 2, ..., n$ a tutte le parole;
+ La moltiplicazione dei simboli che compaiono in una data posizione
per un elemento non nullo $lambda in ZZ_(p)$ a tutte le parole;
Di conseguenza, due matrici generatrici $G_(1)$ e $G_(2)$ in $"Mat"(k
times n, ZZ_(p))$ danno luogo a due codici lineari equivalenti se una
delle due può essere ottenuta dall'altra tramite un numero finito delle
seguenti operazioni:
+ Scambiare due righe;
+ Moltiplicare gli elementi di una riga per un elemento non nullo di
$ZZ_(p)$;
+ Sommare a una riga un'altra riga moltiplicata per un elemento non
nullo di $ZZ_(p)$;
+ Permutare le colonne;
+ Moltiplicare gli elementi di una colonna per un elemento non nullo
di $ZZ_(p)$.
Dove le prime tre operazioni corrispondono a cambiare la base del codice
mentre le ultime due corrispondono alle operazioni nella definizione di
codici equivalenti.
Sia $C subset.eq ZZ_(p)^(n)$ un codice lineare di dimensione $k$. Dato
che esistono diverse matrici che generano $C$, é ragionevole sceglierne
una che renda i calcoli piú agevoli possibili. In particolare, si
consideri la matrice del tipo:
$ S = mat(
1, 0, dots, 0,
Lambda_(1, k + 1), Lambda_(1, k + 2), dots, Lambda_(1, k + n);
0, 1, dots, 0,
Lambda_(2, k + 1), Lambda_(2, k + 2), dots, Lambda_(2, k + n);
dots.v, dots, dots.down, dots.v, dots.v, dots, dots.down, dots.v;
0, 0, dots, 1,
Lambda_(k, k + 1), Lambda_(k, k + 2), dots, Lambda_(k, k + n);
) $
Per indicare una matrice in questa forma, detta *forma standard*,
si usa la notazione $S = (I_(k) | A)$.
Per convincersi che le matrici in forma standard sono effettivamente
vantaggiose, si osservi come:
$ m S &= mat(m_(1), m_(2), dots, m_(k)) mat(
1, 0, dots, 0,
Lambda_(1, k + 1), Lambda_(1, k + 2), dots, Lambda_(1, k + n);
0, 1, dots, 0,
Lambda_(2, k + 1), Lambda_(2, k + 2), dots, Lambda_(2, k + n);
dots.v, dots, dots.down, dots.v, dots.v, dots, dots.down, dots.v;
0, 0, dots, 1,
Lambda_(k, k + 1), Lambda_(k, k + 2), dots, Lambda_(k, k + n);
) = \
&= mat(m_(1), m_(2), dots, m_(k),
sum_(i = 1)^(k) m_(i) Lambda_(i, k + 1), dots,
sum_(i = 1)^(k) m_(i) Lambda_(i, k + n)) $
Ovvero, dove le prime $k$ componenti della codifica coincidono con i primi
$k$ elementi del messaggio originale e la ridondanza è tutta nelle ultime
componenti. Dunque se nella trasmissione non occorrono errori la parola
ricevuta viene facilmente decodificata: basta considerare le prime $k$
componenti per ottenere $m$.
|
https://github.com/kicre/note | https://raw.githubusercontent.com/kicre/note/main/tem/beamer.typ | typst | #let uestc_blue = rgb(0,55,155)
#let uestc_ginkgo = rgb(217, 183, 102)
#let hbu_logo_path = "./pic/hbulogo-ac.svg"
#let ginkgo_path = "./pic/ginkgo.png"
#let mainbuilding_path = "./pic/mainbuilding.png"
#let page_break_flag = state("page_break_flag", true)
#let beamer_start(title:none, subtitle:none, author:none, date:none) = {
page(
margin: (top:25%, bottom: 5%, left: 5%, right:5%),
background: image(mainbuilding_path),
header: align(right, image(hbu_logo_path, width: 25%))
)[
#if title != none {
align(center+horizon, text(font: "LXGW Neo XiHei", 25pt, weight: "bold", title))
}
#if author != none {
align(center+horizon, text(font: "LXGW Neo XiHei", 17pt, weight: "regular", author))
}
#if date != none {
align(right+bottom, text(font: "LXGW Neo XiHei", 15pt, date))
}
]
}
#let beamer_catalogs() = {
set page(
margin: (top:0%, bottom: 0%, left: 0%, right:10%),
)
set outline(
title: none,
depth: 1,
indent: 2em,
fill: none
)
show outline.entry.where(level:1): it => {
v(30pt, weak: true)
text(fill: uestc_blue.lighten(10%), size: 20pt, weight: "bold", it)
}
grid(
columns:(35%, 70%),
column-gutter: 16%,
align(
center+horizon,
box(
fill: uestc_blue,
width: 100%,
height: 100%,
text(fill: white, size: 40pt, hyphenate: true, weight: "bold", [目录])
),
),
align(center+horizon, outline())
)
}
#let beamer_content(body) = {
set page(
margin: (top:20%, bottom: 5%, left: 5%, right:5%),
background: align(right+bottom, image(ginkgo_path, width: 25%)),
header: locate(loc => {
let title = query(heading.where(level:1).before(loc), loc).last().body
grid(
rows:(70%, 10%),
row-gutter: 0%,
grid(
columns:(25%, 75%),
align(left+horizon, image(hbu_logo_path, width:85%)),
align(center+horizon, text(font: "LXGW Neo XiHei", fill: uestc_blue, size: 25pt, weight: "bold", title))
),
align(center+bottom, line(length: 100%, stroke: (paint:uestc_blue, thickness:1pt)))
)
})
)
show heading.where(level:1): it => {
set page(
margin: (top:5%, bottom: 5%, left: 5%, right:5%),
fill: uestc_ginkgo,
header: none,
background: none
)
align(center+horizon, text(font: "LXGW Neo XiHei", fill: white, size: 40pt, it))
}
show heading.where(level:2): it => {
locate(loc => {
let level_1_now_title = query(heading.where(level:1).before(loc), loc).last().body
let level_2_now_title = query(heading.where(level:2).before(loc), loc).last().body
let first_title = none
let get = false
for item in query(heading.where(level:1).or(heading.where(level:2)), loc) {
if get {
if item.level == 2 {
first_title = item.body
}
break
} else {
if item.level == 1 and item.body == level_1_now_title {
get = true
}
}
}
if first_title != level_2_now_title {
pagebreak()
}
})
align(top, text(font: "LXGW Neo XiHei", size: 22pt, it))
v(1em)
}
show heading.where(level:3): it => {
locate(loc => {
let level_1_now_title = query(heading.where(level:1).before(loc), loc).last().body
let level_3_now_title = query(heading.where(level:3).before(loc), loc).last().body
let first_title = none
let get = false
for item in query(heading.where(level:1).or(heading.where(level:3)), loc) {
if get {
if item.level == 3 {
first_title = item.body
}
break
} else {
if item.level == 1 and item.body == level_1_now_title {
get = true
}
}
}
if first_title != level_3_now_title {
pagebreak()
}
})
align(top, text(font: "<NAME>", size: 22pt, it))
v(1em)
}
show heading.where(level:4).or(heading.where(level:5)).or(heading.where(level:6)).or(heading.where(level:7)).or(heading.where(level:8)): it => {
align(top, text(font: "<NAME>", size: 20pt, it))
v(1em)
}
body
}
#let beamer_end() = {
set page(fill: uestc_blue)
set align(left+horizon)
text(40pt, weight: "bold", fill: white )[感谢老师指导!]
}
#let beamer(title:none, subtitle:none, author:none, date:datetime(year: 2023, month: 7, day: 15), body) = {
set page(
paper: "presentation-16-9",
)
set text(font: "<NAME>", size:18pt, weight: "regular")
beamer_start(title:title, author:author, date:date)
beamer_catalogs()
beamer_content(body)
beamer_end()
}
|
|
https://github.com/morel-olivier/template-typst | https://raw.githubusercontent.com/morel-olivier/template-typst/master/cheatsheet/conf.typ | typst | #let conf(
fontSize: 11pt,
title: "Titre",
numColumnns: 4,
color: true,
doc
) = {
set document(
title: title,
)
set text(
font: "FreeSans",
size: fontSize,
lang: "fr",
region: "CH",
)
set page(
paper: "a4",
flipped: true,
margin: 0.75cm,
)
set par(
justify: true,
)
set heading(
numbering: none,
)
show heading.where(level: 1): it =>[
#let tmpcolor = black
#if color {
tmpcolor = blue
}
#set text(size: 1.1em, fill: tmpcolor)
#it
]
show heading.where(level: 2): it =>[
#let tmpcolor = black
#if color {
tmpcolor = aqua
}
#set text(size: 1.05em, fill: tmpcolor)
#it
]
show heading.where(level: 3): it =>[
#let tmpcolor = black
#if color {
tmpcolor = eastern
}
#set text(size: 1em, fill: tmpcolor)
#it
]
let diplayTitle() = [
#align(center, text(1.5em)[
#smallcaps[*#title*]
])
]
diplayTitle()
columns(numColumnns)[
#doc
]
} |
|
https://github.com/Dav1com/resume | https://raw.githubusercontent.com/Dav1com/resume/main/modules/projects.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Projects & Associations")
#cvEntry(
title: [Treasurer & IT Manager],
society: [Student Council of the Department of Computer Science (CaDCC)],
date: [2023],
location: [Santiago, Chile],
description: list(
[Managing the organization founds and public founds provided by the department.],
[Managing CaDCC's own server and its services.],
)
)
|
https://github.com/Treeniks/bachelor-thesis-isabelle-vscode | https://raw.githubusercontent.com/Treeniks/bachelor-thesis-isabelle-vscode/master/chapters/01-introduction.typ | typst | #import "/utils/todo.typ": TODO
#import "/utils/isabelle.typ": *
= Introduction
In 1911, #cite(<korselt1911>, form: "prose") showed that <NAME>'s proof of the Cantor-Bernstein-Schröder theorem, initially published in 1898 @schroder1898, contained an error. While the theorem was correct, and other proofs of this theorem existed even back then @dedekind1887, this is not the only instance where mathematicians tried to prove a statement, thought they conceived such proof, and later found that the proof was incorrect or incomplete. Proof assistants were developed to alleviate this issue by allowing one to formalize mathematical proofs and have the computer check for the proof's correctness. One such tool is _Isabelle_ #footnote[https://isabelle.in.tum.de/], originally developed at the _University of Cambridge_ and _Technical University of Munich_.
To interact with the Isabelle system, the Isabelle distribution bundles the #emph(jedit) code editor @manual-jedit, a modified version of the Java-based code editor _jEdit_ #footnote[https://www.jedit.org/]. Through that, the user is offered a fully interactive Isabelle session, in which proofs are written and checked in real time. However, #jedit has many accessibility shortcomings, like missing a dark theme. To tackle this problem, #emph(vscode) was built to create support for Isabelle from within the popular code editor _Visual Studio Code_ utilizing the _Language Server Protocol_ #footnote[https://microsoft.github.io/language-server-protocol/] (_LSP_) @markarius-isabelle-vscode-2017 @accessibility-vscode.
This protocol was originally developed by Microsoft specifically for VSCode. It consists of two main components: A language _server_, responsible for understanding the language on a semantic level, and a language _client_, which is typically the code editor itself. Later, the protocol became a standardized specification and is now widely used by many different programming languages and code editors to more easily support IDE functions like completions and diagnostics.
Unfortunately, the current state of #vscode is not on par with the experience of #jedit. There are issues with usability and missing features. Additionally, the underlying language server lacks the necessary capabilities to support the development of an Isabelle language client for another code editor.
To combat these deficiencies, we will identify the various aspects of the current #vscode that need improvement and evaluate potential solutions to enhance its functionality. Given that Isabelle's design is often fundamentally incompatible with the LSP specification, the primary question throughout this endeavor is whether the existing LSP spec can be utilized to fit Isabelle's unique requirements, whether a completely custom solution needs to be built for each language client, or whether there is a middle ground in which the language server can take over much of the work, but custom handlers for the client are still necessary.
We will consider two primary metrics for these solutions: How closely they resemble #jedit and how universally applicable it is to other language clients. The former ensures consistency within the broader Isabelle system, while the latter facilitates integration with new language clients.
The primary contribution of this thesis is the implementation of several such solutions to create a more flexible language server, reducing Isabelle's reliance on jEdit and VSCode. Moreover, we extended and modified the VSCode extension to accommodate these new changes, bringing its user experience closer to that of #jedit, and we built two usable prototype client integrations for the _Neovim_ #footnote[https://neovim.io/] and _Sublime Text_ #footnote[https://www.sublimetext.com/] code editors to assess the new flexibility.
== Motivation <intro:motivation>
Prior to this work, we attempted to build an Isabelle language client for the terminal-based code and text editor Neovim. However, it quickly became apparent that the existing language server was insufficient. For example, it only sent the content of certain panels in an HTML format. This makes it easy for an Electron-based editor like VSCode, which runs on the Chromium browser engine, allowing the editor to effortlessly and natively display HTML. However, displaying HTML content from within a terminal-based editor like Neovim is not reasonably possible, meaning an option to get non-HTML output was required.
Because of this, it was virtually impossible to build such a language client with the official Isabelle language server. Instead, we used the unofficial Isabelle fork `isabelle-emacs` #footnote[https://github.com/m-fleury/isabelle-emacs], which includes many advancements to the Isabelle language server and fixes some of its issues to support the _Emacs_ #footnote[https://www.gnu.org/software/emacs/] code editor. While this fork enabled a usable Neovim Isabelle environment #footnote[https://github.com/Treeniks/isabelle-lsp.nvim/tree/0b718d85fd4589d27638877f8955bedb93f56738], e.g., by offering the aforementioned non-HTML output option, there were still many missing features compared to #jedit. Still, the `isabelle-emacs` fork was a strong inspiration for some of the changes made in the context of this thesis.
// == Objectives
//
// A list of additions and changes required was compiled beforehand.
//
// - fix change_document
// - add Isabelle Extension settings into VSCode (Language Server CLI flags)
// - decorations
// - remove necessity on static highlighting (e.g. decorate theorem keyword dynamically)
// - ability to request decorations to be sent explicitly from client
// - dynamic decoration radius (named caret perspective)
// - state and dynamic output
// - overhaul how state panels are created (e.g. IDs handling)
// - handling width of state/output window
// - option to send output/state in non-HTML (with decorations)
// - option to merge state and output into one message/panel
// - completion
// - dynamic symbol auto-completion (e.g. \<gamma>)
// - keyword completion (e.g. theorem)
// - (maybe) add message to request all current dynamic symbol replacements (\<gamma> => γ)
// - active markup (w/ LSP actions?)
// - (maybe) rename variables etc.
//
// Over the course of the work, some of these features were discovered to already exist or not require changing and new problems came up that were added.
|
|
https://github.com/hemmrich/CV_typst | https://raw.githubusercontent.com/hemmrich/CV_typst/master/modules/publications.typ | typst | // Imports
#import "../template/template.typ": cvSection, cvPublication
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#let create_pub_pres_entries(contents, presentation:false) = {
for (name, details) in contents {
details.authors.join(", ")
let d = details.date.split("-")
let dt = datetime(year: int(d.at(0)), month: int(d.at(1)), day: int(d.at(2)))
" (" + dt.display("[month repr:short] [year]") + "). "
text(details.title + ". ", style:"italic")
if presentation {
"Presented by " + details.presenter + " at " + details.conference + ", " + details.location + "."
} else {
if details.status == "Published" { "Published in " + details.journal + "." }
else if details.status == "Submitted" { "Submitted to " + details.journal + "." }
else if details.status == "Revision" { "Submitted to " + details.journal + ", undergoing revisions."}
}
parbreak()
}
}
//PUBLICATIONS
#cvSection("Publications") #parbreak()
#create_pub_pres_entries(
yaml("../src/publications.yaml"), presentation:false
)
// ORAL PRESENTATIONS
#cvSection("Oral Presentations") #parbreak()
#create_pub_pres_entries(
yaml("../src/oral_presentations.yaml"), presentation:true
)
// POSTER PRESENTATIONS
#cvSection("Poster Presentations") #parbreak()
#create_pub_pres_entries(
yaml("../src/poster_presentations.yaml"), presentation:true
) |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/aero-check/0.1.0/template/main.typ | typst | Apache License 2.0 | #import "@preview/aero-check:0.1.0": *
#show: checklist.with(
title: "Title",
// disclaimer: "",
// style: 1,
)
#topic("Topic")[
#section("Section")[
#step("Step", "Check")
]
]
|
https://github.com/daxartio/cv | https://raw.githubusercontent.com/daxartio/cv/main/cv.typ | typst | MIT License | #let cv(
file,
) = [
#let content = yaml(file)
#set document(
title: (content.name + "'s CV"),
author: content.name,
)
#set page(numbering: "1",)
#show heading: set text(font: "Linux Biolinum")
#[
#set align(center)
= CV
]
== #content.name
#grid(
columns: (30%, 30%),
column-gutter: 3em,
[
#set list(marker: "")
- #content.email
#for address in content.address [
- #address
]
],
[
#set list(marker: "")
#for url in content.urls [
- #url
]
],
)
#content.intro
== #content.sections.skills
#box(height: 60pt,
columns(3, gutter: 11pt)[
#for skill in content.skills [
- #skill
]
]
)
== #content.sections.experience
#for experience in content.experience [
#grid(
columns: (15%, auto),
column-gutter: 1em,
[
#experience.years
],
[
*#experience.position*
_ #experience.job _ / #experience.city
#experience.summary
],
)
]
== #content.sections.education
#for education in content.education [
#grid(
columns: (15%, auto),
column-gutter: 1em,
[
#education.years
],
[
*#education.subject*
_ #education.institute _ / #education.city
],
)
]
== #content.sections.projects
#for project in content.projects [
- *#project.name*
#project.language / #project.repo
_ #project.summary _
]
== #content.sections.conferences
#for conference in content.conferences [
#grid(
columns: (15%, auto),
column-gutter: 1em,
[
#conference.year
],
[
*#conference.subject*
],
)
]
== #content.sections.languages
#for language in content.languages [
- #language.language (#language.proficiency)
]
== #content.sections.certificates
#for certificate in content.certificates [
#grid(
columns: (15%, auto),
column-gutter: 1em,
[
#certificate.year
],
[
*#certificate.name*
#certificate.link
],
)
]
]
|
https://github.com/johanvx/typst-undergradmath | https://raw.githubusercontent.com/johanvx/typst-undergradmath/main/README.md | markdown | Creative Commons Attribution Share Alike 4.0 International | # typst-undergradmath
[][cc-by-sa]
[][latest-release]

A [Typst] port of [undergradmath].
## Limitations
The following limitations are also annotated in the [document][latest-release].
- [x] ~Script letters, such as $\mathscr{P}$ form `\mathscr{P}`, are unavailable.~
It's possible to get script letters like $\mathscr{P}$ from `cal(P)` by changing the [`stylistic-set` of the `text()` function].
The stylistic set to apply is font-specific, so it's necessary to consult the font to know which set is desired.
- [x] ~Greek letter $\varsigma$ `\u{03C2}` from `\varsigma` is not defined as a symbol and should probably be defined as `sigma.alt`.~
`sigma.alt` is available as from `typst v0.5.0`.
- [x] $\emptyset$ from `\emptyset` is available in Typst as `nothing`, while $\varnothing$ from `\varnothing` is not.
May need a `let` binding with some specific fonts.
See the Version 3.93 section of README at https://www.ctan.org/tex-archive/fonts/newcomputermodern.
See also [#10] and [#16] for details.
- [x] ~$\imath$ `\u{1D6A4}` and $\jmath$ `\u{1D6A5}`, from `\imath` and `\jmath` respectively, are not defined as symbols.
They are used in like vectors $\vec{\imath}$ with `\vec{\imath}`.~
$\imath$ and $\jmath$ are `dotless.i` and `dotless.j` respectively as from `typst v0.4.0`.
- [x] ~$\widehat{x + y}$ from `\widehat{x + y}` is unavailable.~ It's automatic if you write `$hat(x+y)$`, as mentioned in [#2].
- [x] ~No idea with $\doteq$ from `\doteq`.
Maybe use fonts from [mathabx] or do some spacing adjustment with `dot` and `eq`.~
It can be obtained with `\u{2250}`, which is a bit tricky.
- [x] ~LaTeX arrays (i.e., matrices without fences) are unavailable, but it's easy to get them with the `grid` function.
For math mode, it would be nice to add a new option `""` for `delim` of the `mat` function.~
It's actually available with `$mat(delim: #none, ..)$`.
- [x] ~No idea with spacing between values and units. It would be really great to have something like [siunitx].~
The space between values and units can be `thin` (`\u{2009}`), as mentioned in [#17].
There are also some amazing Typst ports of siunitx, such as [metro] and [unify].
## License
[Like undergradmath], typst-undergradmath is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International License][cc-by-sa].
## Contributing to typst-undergradmath
If you're interested in contributing to this project, feel free to comment on
existing issues, open new issues and create pull requests.
If you create a pull request, make sure to observe the following rules:
1. adopt [Conventional Commits], and
2. keep the document two-page.
<!-- Links -->
[#2]: https://github.com/johanvx/typst-undergradmath/issues/2
[#10]: https://github.com/johanvx/typst-undergradmath/issues/10
[#16]: https://github.com/johanvx/typst-undergradmath/pull/16
[#17]: https://github.com/johanvx/typst-undergradmath/issues/17
[`stylistic-set` of the `text()` function]: https://typst.app/docs/reference/text/text/#parameters-stylistic-set
[Conventional Commits]: https://www.conventionalcommits.org/en/v1.0.0/
[Like undergradmath]: https://gitlab.com/jim.hefferon/undergradmath/-/blob/5b19eff74454f7c71664f85e8042d7b30fcf9cfb/LICENSE
[Typst]: https://github.com/typst/typst
[cc-by-sa]: http://creativecommons.org/licenses/by-sa/4.0/
[latest-release]: https://github.com/johanvx/typst-undergradmath/releases/latest
[mathabx]: https://www.ctan.org/tex-archive/fonts/mathabx
[metro]: https://github.com/fenjalien/metro
[siunitx]: https://www.ctan.org/pkg/siunitx
[undergradmath]: https://gitlab.com/jim.hefferon/undergradmath
[unify]: https://github.com/ChHecker/unify
|
https://github.com/OpenCorvallis/osfc-checklists | https://raw.githubusercontent.com/OpenCorvallis/osfc-checklists/main/README.md | markdown | Apache License 2.0 | # OSFC Checklists
Checklists created by the [Oregon State Flying
Club](https://oregonstateflyingclub.org/) for use by its members.
## How to build
These checklists are written in [Typst](https://typst.app), so you will need the
Typst compiler to build them. If your operating system does not package Typst
(most don't at the moment), you can instead install a Rust toolchain and use
that to install Typst:
```
cargo install typst-cli
```
You also need to create a file called `signature.typ` with your name in it (this
is to distinguish checklists that you print for yourself from the club's
checklists):
```
echo '<your name>' > signature.typ
```
Once you have a working `typst` command, you can build the documents by running:
```
typst compile 66083.typ
typst compile 72pe.typ
typst compile 73146.typ
```
|
https://github.com/desid-ms/desid_report | https://raw.githubusercontent.com/desid-ms/desid_report/main/_extensions/desid_report/notes.typ | typst | MIT License | $if(notes)$
#v(1em)
#block[
#horizontalrule
#set text(size: .88em)
#v(3pt) // otherwise first note marker is swallowed, bug?
$notes$
]
$endif$ |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/scrutinize/0.1.0/gallery/gk-ek-austria.typ | typst | Apache License 2.0 | #import "@preview/scrutinize:0.1.0": grading, question, questions
// #import "@local/scrutinize:0.1.0": grading, question, questions
// #import "../src/lib.typ" as scrutinize: grading, question, questions
#import question: q
// make the PDF reproducible to ease version control
#set document(date: none)
#let title = "Praktische Leistungsfeststellung"
#set document(title: title)
#set text(lang: "de")
#set page(
paper: "a4",
margin: (x: 1.5cm, y: 2cm, top: 4cm),
header-ascent: 20%,
// header: locate(loc => {
// if (calc.odd(loc.page())) {
// }
// }),
header: {
set text(size: 10pt)
table(
columns: (1fr,) * 3,
stroke: none,
align: (col, row) => (left, center, left).at(col) + horizon,
[],
[*#title*],
[],
[Name:],
[],
[Datum: ],
)
},
)
#set table(stroke: 0.5pt)
#show heading.where(level: 2): it => {
question.current(q => {
[Frage #question.counter.display()]
if it.body != [] {
[: #it.body]
}
if q.points != none {
[#h(1fr) #none / #q.points P.]
}
if q.category != none and "ek" in q.category {
[ EK]
}
})
}
#question.all(qs => {
set text(size: 10pt)
let category-points(category) = grading.total-points(qs, filter: q => q.category == category)
let mt = (category-points("gk-mt"), category-points("ek-mt"))
let sock = (category-points("gk-sock"), category-points("ek-sock"))
let total = grading.total-points(qs)
let grades = grading.grades(
[Nicht Genügend (5)],
4/8 * total,
[Genügend (4)],
5/8 * total,
[Befriedigend (3)],
6/8 * total,
[Gut (2)],
7/8 * total,
[Sehr Gut (1)],
)
let grades = grades.map(((body, lower-limit, upper-limit)) => {
if lower-limit == none {
(body: body, range: [< #upper-limit P.])
} else if upper-limit != none {
(body: body, range: [#(lower-limit + 0.5) - #upper-limit P.])
} else {
(body: body, range: [#(lower-limit + 0.5) - #total P.])
}
})
[
= Punkte nach Kompetenzbereichen
#table(
columns: (3fr, ..(1fr,) * 3),
align: (col, row) =>
if col == 0 { left + horizon }
else { right + horizon },
[*Kompetenzbereich*], [*Punkte GK*], [*Punkte EK*], [*Punkte Gesamt*],
[Anwendungsentwicklung -- Multithreading], ..(..mt, mt.sum()).map(m => [#none / #m]),
[Anwendungsentwicklung -- Sockets], ..(..sock, sock.sum()).map(m => [#none / #m]),
[Gesamt], [], [], [#none / #total],
)
= Notenschlüssel
#table(
columns: (auto, ..(1fr,) * grades.len()),
align: (col, row) =>
if col == 0 { left + horizon }
else { center + horizon },
[Punkte:],
..grades.map(g => g.range),
[Note:],
..grades.map(g => g.body),
)
]
})
= Grundkompetenzen -- Theorieteil Multithreading
#lorem(50)
#q(category: "gk-mt", points: 2)[
==
#lorem(40)
]
#q(category: "gk-mt", points: 2)[
==
#lorem(40)
]
#q(category: "gk-mt", points:2)[
==
#lorem(40)
]
#q(category: "gk-mt", points:3)[
==
#lorem(40)
]
= Grundkompetenzen -- Theorieteil Sockets
#lorem(50)
#q(category: "gk-sock", points:6)[
==
#lorem(50)
]
#q(category: "gk-sock", points:2)[
==
#lorem(30)
]
= Grund- und erweiterte Kompetenzen -- Praktischer Teil Multithreading
#lorem(80)
#q(category: "gk-mt", points:4)[
==
#lorem(40)
]
#q(category: "gk-mt", points:3)[
==
#lorem(40)
]
#q(category: "gk-mt", points:4)[
==
#lorem(40)
]
#q(category: "gk-mt", points:4)[
==
#lorem(40)
]
#q(category: "ek-mt", points:5)[
==
#lorem(40)
]
#q(category: "ek-mt", points:3)[
==
#lorem(40)
]
= Grund- und erweiterte Kompetenzen -- Praktischer Teil Sockets
#lorem(80)
#q(category: "gk-sock", points:6)[
==
#lorem(40)
]
#q(category: "gk-sock", points:4)[
==
#lorem(40)
]
#q(category: "gk-sock", points:6)[
==
#lorem(40)
]
#q(category: "ek-sock", points:3)[
==
#lorem(40)
]
#q(category: "ek-sock", points:5)[
==
#lorem(40)
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-20.typ | typst | Other | // An additional trailing comma.
// Error: 31-32 unexpected comma
#import "module.typ": a, b, c,,
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Physique_Serie_1.typ | typst | #import "@preview/bubble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2": canvas, draw, tree
#import "@preview/cheq:0.1.0": checklist
#import "@preview/typpuccino:0.1.0": macchiato
#import "@preview/wordometer:0.1.1": *
#import "@preview/tablem:0.1.0": tablem
#show: bubble.with(
title: "Physique Série 1",
subtitle: "29/08/2024",
author: "<NAME>",
affiliation: "EPFL",
year: "2024/2025",
class: "Génie Mécanique",
logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"),
)
#set page(footer: context [
#set text(8pt)
#set align(center)
#text("page "+ counter(page).display())
]
)
#set heading(numbering: "1.1")
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
== Exercice 2
=== Partie A
1.
$ sum(F) = m arrow(a) $
$ m arrow(g) = m arrow(a) $
$ arrow(g) = arrow(a) $
$ a = vec(0, -g) $
$ a = arrow(v)' $
$ v = vec( v_a cos(alpha), -g t + v_a sin(alpha)) $
$ x = v_a cos(alpha)t $
$ y = -g t² + v_a sin(alpha)t $
Car $x_0 = 0$ et $y_0=0$
2. Il faut satisfaire les conditions suivantes quand $x = 8$, $y(x) = 6 $
$ t = x/(v_a cos(alpha)) $
$ y(x) = -g(x/(v_a cos(alpha)))² + v_a sin(alpha) (x/(v_a cos(alpha))) $
$ -10(8/(15 cos(alpha)))²+15 sin(alpha) (8/(15cos(alpha))) = 6 $
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/dynamic/simple.md | markdown | ---
sidebar_position: 1
---
# Simple Animations
Touying provides two markers for simple animation effects: `#pause` and `#meanwhile`.
## pause
The purpose of `#pause` is straightforward – it separates the subsequent content into the next subslide. You can use multiple `#pause` to create multiple subslides. Here's a simple example:
```typst
#slide[
First #pause Second
#pause
Third
]
```

This example will create three subslides, gradually revealing the content.
As you can see, `#pause` can be used inline or on a separate line.
## meanwhile
In some cases, you may need to display additional content simultaneously with `#pause`. In such cases, you can use `#meanwhile`.
```typst
#slide[
First
#pause
Second
#meanwhile
Third
#pause
Fourth
]
```

This example will create only two subslides, with "First" and "Third" displayed simultaneously, and "Second" and "Fourth" displayed simultaneously.
## Handling set-show rules
If you use set-show rules inside `slide[..]`, you might be surprised to find that subsequent `#pause` and `#meanwhile` do not work. This is because Touying cannot detect the content inside `styled(..)` (content after set-show rules is encompassed by `styled`).
To address this issue, Touying provides a `setting` parameter for the `#slide()` function. You can place your set-show rules in the `setting` parameter. For example, changing the font color:
```typst
#slide(setting: body => {
set text(fill: blue)
body
})[
First
#pause
Second
]
```

Similarly, Touying currently does not support `#pause` and `#meanwhile` inside layout functions like `grid`. This is due to the same limitation, but you can use the `composer` parameter of `#slide()` to meet most requirements.
:::tip[Internals]
Touying doesn't rely on `counter` and `locate` to implement `#pause`. Instead, it has a parser written in Typst script. It parses the input content block as a sequence and then transforms and reorganizes this sequence into the series of subslides we need.
::: |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/129.%20hiresfund.html.typ | typst | hiresfund.html
High Resolution Fundraising
Want to start a startup? Get funded by
Y Combinator.
September 2010The reason startups have been using
more convertible notes in angel
rounds is that they make deals close faster. By making it easier
for startups to give different prices to different investors, they
help them break the sort of deadlock that happens when investors
all wait to see who else is going to invest.By far the biggest influence on investors' opinions of a startup
is the opinion of other investors. There are very, very few who
simply decide for themselves. Any startup founder can tell you the
most common question they hear from investors is not about the
founders or the product, but "who else is investing?"That tends to produce deadlocks. Raising an old-fashioned
fixed-size equity round can take weeks, because all the angels sit around
waiting for the others to commit, like competitors in a bicycle
sprint who deliberately ride slowly at the start so they can follow
whoever breaks first.Convertible notes let startups beat such deadlocks by rewarding
investors willing to move first with lower (effective) valuations.
Which they deserve because they're taking more risk. It's much
safer to invest in a startup <NAME> has already invested in;
someone who comes after him should pay a higher price.The reason convertible notes allow more flexibility in price is
that valuation caps aren't actual valuations, and notes are cheap
and easy to do. So you can do high-resolution fundraising: if you
wanted you could have a separate note with a different cap for each
investor.That cap need not simply rise monotonically. A startup could
also give better deals to investors they expected to help
them most. The point is simply that different investors,
whether because of the help they offer or their willingness to
commit, have different values for
startups, and their terms should reflect that.Different terms for different investors is
clearly the way of the future. Markets always evolve toward higher
resolution. You may not need to use convertible notes to do it.
With sufficiently lightweight standardized equity terms (and some
changes in investors' and lawyers' expectations about equity rounds)
you might be able to do the same thing with equity instead of debt.
Either would be fine with startups, so long as they can easily
change their valuation.Deadlocks weren't the only problem with fixed-size equity rounds.
Another was that startups had to decide in advance how much to
raise. I think it's a mistake for a startup to fix upon a specific
number. If investors are easily convinced, the startup should raise more
now, and if investors are skeptical, the startup should take a
smaller amount and use that to get the company to the point where
it's more convincing.It's just not reasonable to expect startups to pick an optimal round
size in advance, because that depends on the reactions of investors,
and those are impossible to predict.Fixed-size, multi-investor angel rounds are such a bad idea for
startups that one wonders why things were ever done that way. One
possibility is that this custom reflects the way investors like to
collude when they can get away with it. But I think the actual
explanation is less sinister. I think angels (and their lawyers)
organized rounds this way in unthinking imitation of VC series A
rounds. In a series A, a fixed-size equity round with a lead makes
sense, because there is usually just one big investor, who is
unequivocally the lead. Fixed-size series A rounds already are
high res. But the more investors you have in a round, the less
sense it makes for everyone to get the same price.The most interesting question here may be what high res fundraising
will do to the world of investors. Bolder investors will now get
rewarded with lower prices. But more important, in a
hits-driven business, is that they'll be able to get into the deals
they want. Whereas the "who else is investing?" type of investors
will not only pay higher prices, but may not be able to get into
the best deals at all.Thanks to <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, and
<NAME> for reading drafts of this.
|
|
https://github.com/PhotonQuantum/baka-notes | https://raw.githubusercontent.com/PhotonQuantum/baka-notes/master/PL-and-universal-algebra.typ | typst | #set text(font: ("Palatino", "Songti SC"), lang: "zh", region: "cn")
#set enum(numbering: "1.a.i.")
#show strong: underline
#align(
center,
[
#text(17pt)[笨蛋读书笔记] \
#text(12pt)[代数与 PL 与 PL 之恋#footnote[#link("https://guest0x0.xyz/PL-and-universal-algebra/PL-and-universal-algebra.pdf")]]],
)
= 什么是代数?
== 代数结构 (Algebraic Structure,有时被称为 Algebra)
代数结构: 长得像 (集合 $G$ $times$ #text(blue)[一组有限个集合上封闭的有限操作数#footnote[似乎有的时候不要求?]运算] $times$ #text(blue)[一组有限个的公理]) 的东西。
它其实是类似 ${G: "Set" | {... "ops": (G^N -> G) | ... "axioms": "equation on G and ops" }}$ 的依值积类型 (dependent product type)。
注意到#text(blue)[蓝色]的部分及 ... 符号,这些操作都是由*元理论*展开的,而不包含在代数结构定义里。
#strike[或者可以说是在定义一个 Set of $(\_ times \_ times \_)$? 所以它势必是在描述一堆挂着封闭运算和公理的特殊集合#footnote[这里面有 Set of Set 的问题所以显然不太对,我不知道该如何正确形式化但是这里我采用朴素集合论的直觉如此感性地理解]#footnote[qlbf: 存在一个神秘的集合论问题,关键词“本质小” i.e. 等价于某个小的东西但却处于一个更高的宇宙]。]
=== 例子:Group Algebra
所有满足以下要求的(集合 $G$ $times$ 集合上封闭的运算 $dot$)的组合称为 Group Algebra:
+ 基集合 $G$
+ 运算
+ $dot: G -> G -> G$
+ $e: G$
+ $minus: G -> G$
+ 满足以下公理:
+ 单位元: $forall a in G, e dot a = a dot e = a$
+ 逆元: $forall a in G, a dot -b = b dot -a = e$
+ 结合律: $forall a b c in G, (a dot b) dot c = a dot (b dot c)$
用以下伪 Coq 代码来解释:
```ml
Definition group: Type := { A: Type &
{ ∙: A → A → A &
{ id: A &
{ -: A → A &
{ law_assoc: ∀ a b c, a ∙ (b ∙ c) = (a ∙ b) ∙ c &
{ law_id: ∀ a, a ∙ id = a ∧ id ∙ a = a &
(* law_inv: *) ∀ a, a ∙ -a = id ∧ -a ∙ a = id
} } } } } }.
```
或者,我们采用一个更直观的定义,让 group 通过它的基集合和运算索引
#footnote[qlbf: 这可以自动化互转,参见 Arend 文档里的 anonymous extension 和 cooltt 的 extension type]
:
```ml
Definition group (A: Set) (∙: A → A → A), (id: A), (inv: A → A): Type :=
{ law_assoc: ∀ a b c, a ∙ (b ∙ c) = (a ∙ b) ∙ c &
{ law_id: ∀ a, a ∙ id = a ∧ id ∙ a = a &
(* law_inv: *) ∀ a, a ∙ -a = id ∧ -a ∙ a = id }}.
```
然后举一个一个 Group Algebra 的实例的显然例子:(整数, 加法) 群
```ml
Lemma Z_plus_group: group Z +%Z 0%Z -%Z.
Proof.
exists Z.add_assoc. exists Z.add_id. exact Z.add_inv.
Defined.
```
可见不是所有类型(加上一些操作)都可以满足某个特定代数结构的要求。特定代数结构其实是一种对类型的约束。
自然地,Abstract Data Type 是一种约束类型的方法,它显然可以用来定义特定代数结构(类型满足 Abstract Data Type 约束 $<-->$ 集合满足特定代数结构约束)。由于工程语言表达能力不足,它无法定义等式#footnote[Coq 应该行,但是我懒得写 `x.x`]。
游客账户在原文中也提到了一个例子:Module Type。
```ml
module type Group = sig
type G
val comp: G → G → G
val id: G
val inv: G → G
end
module Z_plus: Group = struct
type G = Z
let comp = Z.add
let id = Z.zero
let inv = Z.opp
end
```
== 泛代数 (Universal Algebra)
泛代数*不是*一种代数结构,也不研究特定的代数结构,而是研究所有代数结构的领域。换句话说,它开始考虑上述所称的*元理论*的部分,因此开始研究如何操纵代数结构,例如定义代数结构间的态射,同态等。
TODO: 我不知道怎么在 Coq 里 formalize universal algebra,问题点在于如何 formalize variadic dependent product type。或许其实也不需要 formalize,只要意识到元理论和理论的关联我觉得我就能想明白了。
= 代数同态
TODO |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/board-n-pieces/0.1.0/lib.typ | typst | Apache License 2.0 | /// Chess pieces symbols.
#import "chess-sym.typ"
/// The starting position of a standard chess game.
#let starting-position = (
type: "boardnpieces:position",
board: (
("R", "N", "B", "Q", "K", "B", "N", "R"),
("P", ) * 8,
(none, ) * 8,
(none, ) * 8,
(none, ) * 8,
(none, ) * 8,
("p", ) * 8,
("r", "n", "b", "q", "k", "b", "n", "r"),
),
active: "w",
castling-availabilities: (
white-king-side: true,
white-queen-side: true,
black-king-side: true,
black-queen-side: true,
),
en-passant-target-square: none,
halfmove: 0,
fullmove: 1,
)
/// Creates a position from ranks.
///
/// For example, this creates the starting position.
/// ```typ
/// #let starting-position = position(
/// "rnbqkbnr",
/// "pppppppp",
/// "........",
/// "........",
/// "........",
/// "........",
/// "PPPPPPPP",
/// "RNBQKBNR",
/// )
/// ```
#let position(..ranks) = (
..starting-position,
board: ranks.pos()
.rev()
.map(rank => {
let squares = ()
for square in rank {
if square in (" ", ".") {
squares.push(none)
} else {
squares.push(square)
}
}
squares
}),
)
/// Creates a position from a FEN string.
///
/// For example, this creates the starting position.
/// ```typ
/// #let starting-position = fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
/// ```
#let fen(fen-string) = {
import "internals.typ": parse-fen
parse-fen(fen-string)
}
/// Displays a position on a chess board.
#let board(
/// The position to display.
position,
/// A list of squares to highlight.
highlighted-squares: (),
/// Whether to reverse the board.
reverse: false,
/// Whether to display file and rank numbers.
display-numbers: false,
/// How to number ranks.
rank-numbering: numbering.with("1"),
/// How to number files.
file-numbering: numbering.with("a"),
/// The size of each square.
square-size: 1cm,
/// The background color of white squares.
white-square-color: rgb("FFCE9E"),
/// The background color of black squares.
black-square-color: rgb("D18B47"),
/// The background color of highlighted white squares.
highlighted-white-square-color: rgb("EF765F"),
/// The background color of highlighted black squares.
highlighted-black-square-color: rgb("E5694E"),
/// How to display each piece.
pieces: auto,
) = {
import "internals.typ": square-coordinates
// Doing this saves time when loading the package.
if pieces == auto {
pieces = (
P: image("assets/pw.svg", width: 100%),
N: image("assets/nw.svg", width: 100%),
B: image("assets/bw.svg", width: 100%),
R: image("assets/rw.svg", width: 100%),
Q: image("assets/qw.svg", width: 100%),
K: image("assets/kw.svg", width: 100%),
p: image("assets/pb.svg", width: 100%),
n: image("assets/nb.svg", width: 100%),
b: image("assets/bb.svg", width: 100%),
r: image("assets/rb.svg", width: 100%),
q: image("assets/qb.svg", width: 100%),
k: image("assets/kb.svg", width: 100%),
)
}
assert(
type(position) == dictionary and position.type == "boardnpieces:position",
message: "`position` should be a position. You can construct a position with the `position` function.",
)
let height = position.board.len()
assert(height > 0, message: "Board cannot be empty.")
let width = position.board.at(0).len()
assert(width > 0, message: "Board cannot be empty.")
let squares = (
position.board
.map(rank => {
rank.map(square => {
if square != none {
pieces.at(square)
}
})
})
.rev()
.flatten()
)
if display-numbers {
let number-cell = grid.cell.with(
inset: 0.3em,
)
let column-numbers = (none, ) + (
range(1, width + 1)
.map(file-numbering)
.map(number-cell)
) + (none, )
squares = (
column-numbers
+ squares
.chunks(width)
.enumerate()
.map(((i, rank)) => {
let n = rank-numbering(height - i)
(
number-cell(n),
..rank,
number-cell(n),
)
})
.flatten()
+ column-numbers
)
}
if reverse {
squares = squares.rev()
}
highlighted-squares = highlighted-squares.map(s => {
let (x, y) = square-coordinates(s)
if reverse {
(width - x - 1, y)
} else {
(x, height - y - 1)
}
})
show: block.with(breakable: false)
set text(dir: ltr)
grid(
fill: (x, y) => {
if display-numbers {
x -= 1
y -= 1
if x < 0 or x >= width or y < 0 or y >= height {
return none
}
}
if calc.even(x + y) {
if (x, y) in highlighted-squares {
highlighted-white-square-color
} else {
white-square-color
}
} else {
if (x, y) in highlighted-squares {
highlighted-black-square-color
} else {
black-square-color
}
}
},
columns: if display-numbers {
(auto, ) + (square-size, ) * width + (auto, )
} else {
(square-size, ) * width
},
rows: if display-numbers {
(auto, ) + (square-size, ) * height + (auto, )
} else {
(square-size, ) * height
},
align: center + horizon,
..squares,
)
}
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/cite-locate.typ | typst | Apache License 2.0 | // Test citation in other introspection.
---
#set page(width: 180pt)
#set heading(numbering: "1")
#outline(
title: [List of Figures],
target: figure.where(kind: image),
)
#pagebreak()
= Introduction <intro>
#figure(
rect[-- PIRATE --],
caption: [A pirate @arrgh in @intro],
)
#locate(loc => [Citation @distress on page #loc.page()])
#pagebreak()
#bibliography("/files/works.bib", style: "chicago-notes")
|
https://github.com/luiswirth/bsc-thesis | https://raw.githubusercontent.com/luiswirth/bsc-thesis/main/src/theory.typ | typst | #import "math.typ": *
#import "layout.typ": *
= Theory
// Notations needed:
// Space of all alternating l-multilinear forms on some vector space.
// Tangent space at point x at Omega.
// Space of all Differential l-forms on Omega.
// Space of all integrable l-forms on Omega.
// Space of all C^k l-forms on Omega.
#let Lin = $"Lin"$
#let Alt = $"Alt"$
== Exterior Algebra
=== Multilinear Forms
=== Alternating Forms
== Exterior Calculus
=== Differential Forms
In the most general sense, $Omega$ may be a (piecewise) smooth oriented and
bounded $n$-dimensional Riemannian manifold, $n in NN$, with a piecewise smooth
boundary.
A differential form $omega in wedgespace^l (Omega)$ of order $l$, $0 <= l <= n$, is a mapping from
$Omega$ into the $binom(n,l)$ -dimensional space $Alt^l (T_Omega (xv))$ of
alternating $l$–multilinear forms on the $n$-dimensional tangent space $T_Omega
(xv)$ at $Omega$ in $xv in Omega$.
@hiptmair-whitney
A fundamental concept in the theory of differential forms is the integral of
a $p$-form over a piecewise smooth $p$-dimensional oriented manifold. Through
integration a differential form assigns a value to each suitable manifold,
modeling the physical procedure of measuring a field.
@hiptmair-whitney
From alternating $l$-multilinear forms differential $l$-forms inherit the
exterior product \
$wedge: wedgespace^l (Omega) times wedgespace^k (Omega) -> wedgespace^(l+k) (Omega), 0 <= l, k, l + k <= n$,
defined in a pointwise sense.
Moreover, remember that the trace $t_Sigma omega$ of an $l$-form $omega in
wedgespace^l (Omega), 0 <= l < n$, onto some piecewise smooth ($n − 1$)-
dimensional submanifold $Sigma subset.eq clos(Omega)$ yields an $l$-form on $Sigma$.
It can be introduced by restricting $omega (xv) in Alt^l (T_Omega
(xv)), x in Sigma$, to the tangent space of $Sigma$ in $xv$.
The trace commutes with the exterior product and exterior differentiation, i.e.
$dif t_Sigma omega = t_Sigma dif omega$ for $omega in wedgespace^l_1 (Omega)$.
@hiptmair-whitney
Another crucial device is the exterior derivative $dif$, a linear
mapping from differentiable $l$-forms into ($l + 1$)-forms.
Stokes’ theorem makes it possible to define the exterior derivative
$dif omega in wedgespace^(l+1) (Omega)$ of $omega in wedgespace^l (Omega)$.
#theorembox[
*Theorem (Stokes):*
$ integral_Omega dif omega = integral_(diff Omega) omega $
for all $omega in wedgespace^l_1 (Omega)$
]
A fundamental fact about exterior differentiation is that $dif(dif omega) = 0$
for any sufficiently smooth differential form $omega$.
Under some restrictions on the topology of $Omega$ the converse is
also true, which is called the exact sequence property:
\
#theorembox[
*Theorem (Poincaré's lemma):*
For a contractible domain $Omega subset.eq RR^n$ every
$omega in wedgespace^l_1 (Omega), l >= 1$, with $dif omega = 0$ is the exterior
derivative of an ($l − 1$)–form over $Omega$.
]
\
A second main result about the exterior derivative is the following formula
#theorembox[
*Theorem (Integration by parts):*
$
integral_Omega dif omega wedge eta
+ (-1)^l integral_Omega omega wedge dif eta
= integral_(diff Omega) omega wedge eta
$
for $omega in wedgespace^l (Omega), eta in wedgespace^k (Omega), 0 <= l, k < n − 1, l + k = n − 1$.
]
Here, the boundary $diff Omega$ is endowed with the induced orientation.
Finally, we recall the pullback $Omega |-> Phi^*omega$ under a change of
variables described by a diffeomorphism $Phi$. This transformation commutes
with both the exterior product and the exterior derivative, and it leaves the
integral invariant.
Remember that given a basis
$dif x_0, dots, dif x_n$ of the dual space of $T_Omega (xv)$ the set of all
exterior products of these
furnishes a basis for the space of alternating l-multilinear forms on
TΩ(x). Thus any ω ∈ Dl(Ω) has a representation
$
omega = sum_(i_1, dots, i_l) phi_(i_1,dots,i_l) dif x_i_1 wedge dots.c wedge dif x_i_l
$
where the indices run through all combinations admissible according
to (6) and the ϕi1,... ,il : Ω �→ R are coefficient functions.
Therefore, we call a differential form polynomial of degree k,
k ∈ N0, if all its coefficient functions in (7) are polynomials of degree k.
We can define proxies to convert between vector fields and differential forms.
Sharp #sharp to move from differential form to vector field.
Flat #flat to move from vector field to differential form.
=== Exterior Derivative
=== Integration
=== Stockes' Theorem
== Finite Element Differential Forms
Lagragian (vertex), Raviart-Thomas (edge), Nédélec (face)
=== Complete Polynomial Spaces of Differential Forms
=== Whitney Forms
Whitney 0-form $cal(W) x_i$ corresponding to 0-simplex $x_i$ is the barycentric function $cal(W) x_i = lambda_i$.
The whitney $p$-form corresponding to the $p$-simplex $[x_0, dots, x_p]$ is
$
cal(W) [x_0, dots, x_p] =
p! sum_(i=0)^p (-1)^i lambda_i
(dif lambda_0 wedge dots.c wedge hat(dif lambda_i) wedge dots.c wedge dif lambda_p)
$
As example in a triangle $K = [x_0,x_1,x_2]$ the whitney forms are
$
cal(W) [x_0] = lambda_0
wide
cal(W) [x_1] = lambda_1
wide
cal(W) [x_2] = lambda_2
\
cal(W) [x_0,x_1] = lambda_0 dif lambda_1 - lambda_1 dif lambda_0
wide
cal(W) [x_0,x_2] = lambda_0 dif lambda_2 - lambda_2 dif lambda_0
wide
cal(W) [x_1,x_2] = lambda_1 dif lambda_2 - lambda_2 dif lambda_1
\
cal(W) [x_0,x_1,x_2] = 2 (lambda_0 (dif lambda_1 wedge dif lambda_2) - lambda_1 (dif lambda_0 wedge dif lambda_2) + lambda_2 (dif lambda_0 wedge dif lambda_1))
$
Whitney forms are affine invariant. \
Let $K_1 = [x_0, dots x_n]$ and $K_2 = [y_0, dots y_n]$ and $phi: K_1 -> K_2$ affine map, such that $phi(x_i) = y_i$,
then
$W[x_0, dots, x_n] = phi^* (W[y_0, dots y_n])$
== Various
Exterior derivative: $dif_l: dom(d_l) subset.eq L^2 wedgebig^l (Omega) -> L^2 wedgebig^(l+1)$
$L^2$-adjoint: $delta_l := dif _(l-1)^* = (-1)^l star_(l-1)^(-1) compose dif_(N-l) compose star_l$
|
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/pixel-art-working-1.typ | typst | #import "@preview/cetz:0.2.2"
#import cetz.draw
#import cetz.plot
#let off(p, n: 0) = {
(p.at(0) + n, p.at(1) + n)
}
#let cubio() = {
import cetz.draw: *
on-yz({ rect((0, 0), (1, 1)) })
on-xz({ rect((0, 0), (1, 1)) })
on-xy({ rect((0, 0), (1, 1)) })
on-xy({ line((1, 1), (1, 1)) })
}
#let ratioat(p) = {
cetz.draw.rect(p, (rel: (1, 1)))
cetz.draw.rect(p, (rel: (2, 1)))
cetz.draw.rect(p, (rel: (3, 1)))
cetz.decorations.flat-brace(p, (rel: (3, 0)))
}
#let fractionat(p) = {
cetz.draw.rect(p, (rel: (1, 1)))
cetz.draw.rect(p, (rel: (2, 1)))
cetz.draw.rect(p, (rel: (3, 1)))
cetz.decorations.flat-brace(p, (rel: (3, 0)))
}
#let bezierworks() = {
// a function
let bezier-points = ((0, 0), (1, 1), (2, 4))
draw.bezier-through(..bezier-points, name: "b")
let bezier-points = ((2, 4), (3, 3), (5,5))
draw.bezier-through(..bezier-points, name: "b")
}
#let plotworks(params) = {
plot.plot(axes: none, size: (2,2), x-tick-step: none, y-tick-step: none, {
plot.add(domain: (0, 2*calc.pi), calc.sin)
plot.annotate({
draw.rect((0, -1), (calc.pi, 1), fill: rgb(50,50,200,50))
draw.content((calc.pi, 0), [Here])
})
})
}
#let k = 0.5
#let boxed(c) = {
box(outset: 10pt, fill: white, c)
}
#let grapher(x, y,) = {
import cetz.draw: *
circle((x, y), fill: white, radius: 0.1, stroke: none)
}
#let plotter() = {
boxed(cetz.canvas(length: 40pt, {
plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
plot.add(domain: (0, 2*calc.pi), calc.sin)
plot.annotate({
draw.rect((0, -1), (calc.pi, 1), fill: rgb(50,50,200,50))
draw.content((calc.pi, 0), [Here])
})
})
}))
}
#let wrapper(content) = layout(page => {
box(
inset: (
x: 6.22pt / 2,
y: 50.89pt / 2
),
content
)
})
#let main() = layout(page => {
let x2 = 6
let y2 = 10
let length = 40pt
let c = draw.circle.with(radius: 0.05, fill: black, stroke: none)
let marker = draw.circle.with(radius: 0.25, fill: red)
cetz.canvas(length: length, {
// plotworks(1)
//draw.grid((0, 0), (x2, y2))
cubio()
fractionat((2, 8))
bezierworks()
let data = (
(3, 5),
(2, 2),
)
draw.rect((1 - k/2, k), (1 + k/2, 5))
// draws a bar rect at 1
draw.rect((3 - k/2, k), (3 + k/2, 5))
// draws a bar rect at 5
draw.line((0 + 0.5, 0 + 0.5), (0 + 0.5, y2 + 0.5))
// draws the y-axis
draw.line((0 + 0.5, 0 + 0.5), (x2 + k + 0, 0.5))
// draws the x-axis
for i in range(x2 + 1) {
for j in range(y2 + 1) {
if i == 0 {
if j == 0 {
draw.line((0.3, 0.3), (0.5, 0.5))
}
draw.content((i, j), [#j])
draw.line((k, j), (0.3, j))
}
else if j == 0 {
draw.content((i, j), [#i])
draw.line((i, k), (i, 0.3))
}
else {
c((i, j), fill: red)
}
}
}
for d in data {
c(off(d), fill: blue, radius: 0.2)
}
let mx = x2 / 2
let my = y2 / 2
//marker((mx, my))
//draw.content((3, 8), plotter())
grapher(2, 8)
//draw.content((mx, my), box([hi sdfsdfsdf], fill: white, outset: 40pt), name: "a")
//draw.content((to: "a", rel: (0, -0.25)), line(length: 50pt))
//draw.content((to: "a", rel: (0, -0.5)), [hi])
})
})
#let pat = pattern(size: (3pt, 6pt))[
#place(line(start: (0%, 0%), end: (100%, 100%)))
#place(line(start: (0%, 100%), end: (100%, 0%)))
]
#{
let b = {
place(rect(width: 100%, height: 100%))
let p = pattern(size: (3pt, 3pt), {
circle(radius: 1pt, fill: gray)
})
let p2 = pattern(size: (3pt, 3pt), {
})
let p2 = pat
// place(rect(width: 20%, height: 100%, fill: black.lighten(95%), align(time-travel, center + horizon)))
place(dx: 20%, rect(inset: 0pt, width: 80%, height: 100%, stroke: none, wrapper(main())))
}
set page(margin: (rest: 0pt))
b
}
|
|
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-算法/广度优先搜索/岛屿数量.typ | typst | #import "../../../../lib.typ":*
=== #Title(
title: [岛屿数量],
reflink: "https://leetcode.cn/problems/number-of-islands/description/",
level: 2,
)<岛屿数量>
#note(
title: [
岛屿数量
],
description: [
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
],
examples: ([
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
],[
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
]
),
tips: [
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
],
solutions: (
( name:[深度优先搜索],
text:[
我们可以将二维网格看成一个无向图,竖直或水平相邻的 1 之间有边相连。
为了求出岛屿的数量,我们可以扫描整个二维网格。如果一个位置为 1,则以其为起始节点开始进行深度优先搜索。在深度优先搜索的过程中,每个搜索到的 1 都会被重新标记为 0。
最终岛屿的数量就是我们进行深度优先搜索的次数。
],code:[
```cpp
class Solution {
private:
const char LAND='1';
const char SEA='0';
const vector<pair<int,int>> DIRECTIONS={{1,0},{-1,0},{0,1},{0,-1}};
void dfs(vector<vector<char>>& grid,int r, int c){
int m=grid.size();
int n=grid[0].size();
grid[r][c]=SEA;
for(auto direction:DIRECTIONS){
int row=r+direction.first;
int col=c+direction.second;
if(row<0||row>=m||col<0||col>=n||grid[row][col]==SEA)
continue;
dfs(grid,row,col);
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int m=grid.size();
if(m==0) return 0;
int n=grid[0].size();
int cnt=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==LAND){
cnt++;
dfs(grid, i, j);
}
}
}
return cnt;
}
};
```
]),(
name:[广度优先搜索],
text:[
同样地,我们也可以使用广度优先搜索代替深度优先搜索。
为了求出岛屿的数量,我们可以扫描整个二维网格。如果一个位置为 1,则将其加入队列,开始进行广度优先搜索。在广度优先搜索的过程中,每个搜索到的 1 都会被重新标记为 0。直到队列为空,搜索结束。
最终岛屿的数量就是我们进行广度优先搜索的次数。
],
code:[
```cpp
class Solution {
private:
const char LAND='1';
const char SEA='0';
const char VISITED='2';
const vector<pair<int,int>> DIRECTIONS={{1,0},{-1,0},{0,1},{0,-1}};
public:
int numIslands(vector<vector<char>>& grid) {
int m=grid.size();
if(m==0) return 0;
int n=grid[0].size();
int cnt=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==LAND){
cnt++;
grid[i][j]=VISITED;
queue<pair<int,int>> que;
que.push({i,j});
while(!que.empty()){
auto point=que.front();
que.pop();
int row=point.first;
int col=point.second;
for(auto direction:DIRECTIONS){
int r=row+direction.first;
int c=col+direction.second;
if(r<0||r>=m||c<0||c>=n||grid[r][c]!=LAND)
continue;
que.push({r,c});
grid[r][c]=VISITED;
}
}
}
}
}
return cnt;
}
};
```
],
),(
name:[并查集],
text:[同样地,我们也可以使用并查集代替搜索。
为了求出岛屿的数量,我们可以扫描整个二维网格。如果一个位置为 1,则将其与相邻四个方向上的 1 在并查集中进行合并。
最终岛屿的数量就是并查集中连通分量的数目。],
code:[
```cpp
class UnionFind {
public:
UnionFind(vector<vector<char>>& grid) {
count = 0;
int m = grid.size();
int n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
parent.push_back(i * n + j);
++count;
}
else {
parent.push_back(-1);
}
rank.push_back(0);
}
}
}
int find(int i) {
if (parent[i] != i) {
parent[i] = find(parent[i]);
}
return parent[i];
}
void unite(int x, int y) {
int rootx = find(x);
int rooty = find(y);
if (rootx != rooty) {
if (rank[rootx] < rank[rooty]) {
swap(rootx, rooty);
}
parent[rooty] = rootx;
if (rank[rootx] == rank[rooty]) rank[rootx] += 1;
--count;
}
}
int getCount() const {
return count;
}
private:
vector<int> parent;
vector<int> rank;
int count;
};
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int nr = grid.size();
if (!nr) return 0;
int nc = grid[0].size();
UnionFind uf(grid);
int num_islands = 0;
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
grid[r][c] = '0';
if (r - 1 >= 0 && grid[r-1][c] == '1') uf.unite(r * nc + c, (r-1) * nc + c);
if (r + 1 < nr && grid[r+1][c] == '1') uf.unite(r * nc + c, (r+1) * nc + c);
if (c - 1 >= 0 && grid[r][c-1] == '1') uf.unite(r * nc + c, r * nc + c - 1);
if (c + 1 < nc && grid[r][c+1] == '1') uf.unite(r * nc + c, r * nc + c + 1);
}
}
}
return uf.getCount();
}
};
```
]
)
),
gain:none,
) |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.3.0/src/lib/pin.typ | typst | Apache License 2.0 | #let _pin-name(name) = "cetz-pin-" + name
/// Place a pin aka. cetz anchor in the document
#let pin(name) = [ #metadata("cetz-pin-tracker") #label(_pin-name(name)) ]
/// Returns all pins
#let get-pin() = context {
let result = ()
for item in locate(metadata) {
if item.value.starts-with("cetz-pin-") {
let name = item.value.slice(9)
result.insert(name, item)
}
}
panic(result)
}
|
https://github.com/cu1ch3n/menu | https://raw.githubusercontent.com/cu1ch3n/menu/main/main.typ | typst | #import "@preview/caidan:0.1.0": *
#show: caidan.with(
title: [#en_text(22pt, fill: nord0)[Chen's Private Cuisine]],
cover_image: image("cover.png"),
update_date: datetime.today(),
)
#cuisine[鲁菜][Shandong Cuisine]
- #item[葱烧海参][Braised Sea Cucumber w/ Scallions]
- #item[葱爆牛肉][Scallion Beef Stir-Fry]
- #item[醋溜白菜][Napa Cabbage Stir-Fry w/ Vinegar]
- #item[京酱肉丝][Sautéed Shredded Pork]
- #item[风味茄子][Crispy Fried Eggplant]
- #item[青岛脂渣][Qingdao Pork Greaves]
- #item[炸萝卜丸子][Chinese Fried Radish Balls]
- #item[油炸金蝉][Deep Fried Golden Cicada]
- #item[猪肉白菜炖粉条][Braised Pork Belly w/ Vermicelli Noodles & Napa Cabbage]
- #item[锅塌豆腐][Guo Ta Tofu]
- #item[锅包肉][Fried Pork in Scoop]
#cuisine[苏菜][Jiangsu cuisine]
- #item[松鼠桂鱼][Squirrel-shaped Mandarin Fish]
- #item[扬州炒饭][Yangzhou Fried Rice]
- #item[香干马兰头][Mixed Kalimeris Indica w/ Tofu]
#cuisine[川菜][Sichuan Cuisine]
- #item[宫保鸡丁][Gong Bao Chicken]
- #item[回锅肉][Twice-cooked pork]
- #item[麻婆豆腐][Mapo Tofu]
#cuisine[粤菜][Cantonese Cuisine]
- #item[腊味煲仔饭][Sausage Claypot Rice]
- #item[脆皮乳鸽][Crispy Pigeon]
- #item[梅菜扣肉][Braised Pork w/ Preserved Vegetable]
- #item[葱油鸡][Scallion Oil Chicken]
#cuisine[家常菜 (荤)][Home-style Cuisine (Meaty)]
- #item[蒜香鸡翅][Garlic Chicken Wings]
- #item[酱香鸭翅][Braised Duck Wings]
- #item[爆炒鸡胗][Chicken Gizzard Stir-Fry]
- #item[香辣红烧鸡爪][Spicy Chicken Feet]
- #item[黄焖鸡米饭][Braised Chicken and Rice]
- #item[马齿菜红烧肉][Braised Pork w/ Portulaca]
- #item[板栗烧排骨][Braised Pork Ribs w/ Chestnuts]
- #item[笋干烧排骨][Pork Ribs w/ Dried Bamboo Shoots]
- #item[黑椒牛柳][Black Pepper Beef Stir-Fry]
- #item[干煸蚕蛹][Crispy Silkworm Pupa]
- #item[干锅牛蛙][Dry Pot Bullfrog]
- #item[香煎带鱼][Pan-fried Beltfish]
- #item[清蒸鲈鱼][Steamed Sea Bass]
- #item[炸河虾][Fried Shrimps]
- #item[粉蒸肉][Steamed Pork w/ Rice Flour]
- #item[黄豆焖猪蹄][Braised Pork Knuckles w/ Soybeans]
- #item[土豆炖鸡块][Chicken Stew w/ Potatoes]
#cuisine[家常菜][Home-style Cuisine]
- #item[豆腐脑][Douhua]
- #item[蒜蓉秋葵][Galic Okra]
- #item[手撕包菜][Hand-Torn Cabbage]
- #item[炒紫甘蓝][Purple Cabbage Stir-Fry]
- #item[清炒菠菜][Spinach Stir-Fry w/ Garlic]
- #item[清炒四季豆][Stir Fry French Beans]
- #item[酸辣土豆丝][Hot & Sour Shredded Potato]
- #item[香椿炒蛋][Toon Scrambled Eggs]
- #item[蒜苔炒蛋][Scrambled Eggs w/ Garlic Moss]
- #item[韭黄炒蛋][Scrambled Eggs w/ Hotbed Chives]
- #item[韭菜炒蛋][Scrambled Eggs w/ Chinese Chives]
- #item[西红柿炒蛋][Tomato & Egg Stir-Fry]
- #item[豆豉鲮鱼油麦菜][Stir Fry Indian lettuce w/ Fried Dace w/ Salted Black Beans]
- #item[青椒肉末][Sautéed Minced Pork w/ Green Pepper ]
- #item[豆角肉末][Long Beans Stir-Fry w/ Minced Pork]
- #item[肉末毛豆][Edamame & Pork Mince Stir-Fry]
- #item[油焖春笋][Braised Spring Bamboo Shoots]
- #item[腊肉炒蒜苗][Chinese Bacon Stir-Fry w/ Garlic Sprout]
- #item[腊肉炒荷兰豆][Chinese Bacon Stir-Fry w/ Snow Peas]
- #item[茄子烧排骨][Braised Pork Ribs w/ Eggplant]
- #item[荷兰豆炒腊肠][Snow Peas & Chinese Sausage Stir-Fry]
- #item[什锦玉米粒 (火腿)][Sautéed Peas & Corn w/ Ham]
- #item[什锦玉米粒 (虾仁)][Sautéed Peas & Corn w/ Shrimp]
- #item[什锦玉米粒 (鸡胸肉)][Sautéed Peas & Corn w/ Chicken Breast]
- #item[蛋黄焗南瓜][Crispy Fried Pumpkin w/ Salted Egg Yolk]
- #item[贝贝南瓜蒸蛋][Baby Pumpkin Steamed Eggs]
- #item[上汤娃娃菜][Braised Baby Cabbage in Broth]
- #item[台湾苍蝇头][Sauteed Minced Pork & Chive Flowers]
#cuisine[汤菜][Soup]
- #item[清炖羊肉汤][Mutton Soup]
- #item[清炖鸡汤][Chincken Soup]
- #item[松茸鸡蛋汤][Matsutake Egg Soup]
- #item[冬瓜花甲汤][Winter Melon Clam Soup]
- #item[鱼头豆腐汤][Milky Fish Soup w/ Tofu]
- #item[玉米排骨汤][Sweet Corn Pork Ribs Soup]
- #item[西红柿蛋花汤][Tomato Egg Soup]
- #item[枸杞叶瘦肉汤][Wolfberry Leaves & Pork Liver Soup]
#cuisine[海鲜烧烤][Sea Food & Grills]
- #item[水煮虾][Poached Shrimp]
- #item[蒜蓉炒大虾][Shrimp Stir-Fry w/ Garlic]
- #item[油焖大虾][Braised Shrimps]
- #item[清蒸蟹][Steamed Crab]
- #item[香辣蟹][Sautéed Crab in Hot Spicy Sauce]
- #item[爆炒鱿鱼须][Spicy Squid Stir Fry]
- #item[香辣小鱿鱼][Spicy Baby Squid]
- #item[蜜汁烤肋排][Honey BBQ Ribs]
- #item[蜜汁烤鸡胸][Honey BBQ Chicken]
- #item[奥尔良烤鸡腿][Orleans Style BBQ Chicken Legs]
- #item[空气炸锅鸡丝][Roasted Shredded Chicken]
- #item[烤茄子][Roasted Eggplant]
- #item[蒜蓉粉丝生蚝][Steamed Oysters w/ Garlic Vermicelli]
- #item[蒜蓉粉丝蛏子][Steamed Razor Clam w/ Garlic Vermicelli]
#cuisine[日韩料理][Japanese & Korean Cuisine]
- #item[韩式拌饭][Bibimbap]
- #item[照烧肥牛饭][Teriyaki Beef Rice Bowl]
- #item[韩式辣鸡爪][Korean Spicy Chicken Feet]
#cuisine[东南亚菜][Southeast Asian Cuisine]
- #item[泰式菠萝炒饭][Thai Pineapple Fried Rice]
- #item[泰式咖喱虾][Thai Shrimp Curry]
- #item[泰式咖喱蟹][Thai Crab Curry]
- #item[泰式柠檬虾][Thai Lemon Shrimp]
- #item[泰式青柠檬蒸鱼][Thai Steamed Fish w/ Lime]
- #item[泰式酸辣鸡爪][Thai Cold Chicken Feet Salad]
- #item[蒜蓉通心菜][Water Spinach Stir-Fry w/ Garlic]
- #item[柠檬鸡胸肉 (融合菜)][Lemon Chicken Breast (Fusion Cuisine)]
- #item[冬阴功][Tom Yum Goong]
#cuisine[西餐][Western Cuisine]
- #item[西冷牛排][Sirloin Steak]
- #item[番茄肉酱意面][Spaghetti w/ Ground Beef]
#cuisine[凉菜][Cold Dishes]
- #item[老醋花生][Pickled Peanuts w/ Vinegar & Onion]
- #item[凉拌鸡丝][Shredded Chicken Salad]
- #item[凉拌苦瓜][Bitter Melon Salad]
- #item[呛毛肚][Cold Spicy Beef Omasum Tripe]
- #item[凉拌苦菊][Endive Salad]
- #item[凉拌黄瓜][Shredded Cucumber w/ Sauce]
- #item[皮蛋豆腐][Chilled Tofu w/ Century Egg]
#cuisine[面食][Dumplings & Noodles]
- #item[猪肉大葱水饺][Jiaozi Stuffed w/ Pork & Scallion]
- #item[韭菜鸡蛋水饺][Jiaozi Stuffed w/ Chives & Eggs]
- #item[鸡蛋手擀面][Handmade Noodles w/ Eggs]
- #item[红烧牛肉面][Braised Beef Noodle Soup]
- #item[潍坊大虾面][Weifang Shrimp Noodles]
- #item[葱油拌面][Scallion Oil Noodles]
- #item[豆角焖面][Braised Noodles w/ Green Beans]
- #item[番茄通心粉][Hong Kong Style Tomato Macaroni Soup]
#cuisine[小食][Snacks]
- #item[薯条][French Fries]
- #item[薯饼][Hash Browns]
- #item[鸡米花][Popcorn Chicken]
- #item[盐焗腰果][Roasted Cashew Nuts]
- #item[葡式蛋挞][Pasteis de Nata]
- #item[苹果脆片][Apple Chips]
#cuisine[甜点][Desserts]
- #item[香蕉派][Banana Pie]
- #item[戚风蛋糕][Chiffon Cake]
- #item[蓝莓山药][Blueberry Yam]
#cuisine[饮品][Drinks]
- #item[港式冻柠茶][Hong Kong Style Iced Lemon Tea]
- #item[莫吉托][Mojito]
- #item[猕猴桃莫吉托][Kiwi Mojito]
|
|
https://github.com/bkorecic/enunciado-facil-fcfm | https://raw.githubusercontent.com/bkorecic/enunciado-facil-fcfm/main/README.md | markdown | MIT License | # enunciado-facil-fcfm
Template de Typst para documentos de la FCFM (auxiliares, controles, pautas)
## Ejemplo de uso
### En [typst.app](https://typst.app)
Si utilizas la aplicación web oficial, puedes presionar "Start from template" y buscar "enunciado-facil-fcfm" para crear un proyecto ya inicializado con el template.
### En CLI
Si usas Typst de manera local, puedes ejecutar:
```sh
typst init @preview/enunciado-facil-fcfm:0.1.0
```
lo cual inicializará un proyecto usando el template en el directorio actual.
### Manualmente
Basta crear un archivo con el siguiente contenido para usar el template:
```typ
#import "@preview/enunciado-facil-fcfm:0.1.0" as template
#show: template.conf.with(
titulo: "Auxiliar 1",
subtitulo: "Typst",
titulo-extra: (
[*Profesora*: <NAME>],
[*Auxiliares*: <NAME> y <NAME>],
),
departamento: template.departamentos.dcc,
curso: "CC4034 - Composición de documentos",
)
...el resto del documento comienza acá
```
Puedes ver un ejemplo más completo en [main.typ](template/main.typ). Para aprender la sintáxis de Typst existe la [documentación oficial](https://typst.app/docs). Si vienes desde LaTeX, te recomiendo la [guía para usuarios de LaTeX](https://typst.app/docs/guides/guide-for-latex-users/).
## Configuración
La función `conf` importada desde el template recibe los siguientes parámetros:
| Parámetro | Descripción |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `titulo` | Título del documento |
| `subtitulo` | Subtítulo del documento |
| `titulo-extra` | Arreglo con bloques de contenido adicionales a agregar después del título. Útil para mostrar los nombres del equipo docente. |
| `departamento` | Diccionario que contiene el nombre (`string`) y el logo del departamento (`content`). El template viene con uno ya creado para cada departamento bajo `template.departamentos`. Valor por defecto: `template.departamentos.dcc`|
| `curso` | Código y/o nombre del curso. |
| `page-conf` | Diccionario con parámetros adicionales (tamaño de página, márgenes, etc) para pasarle a la función [page](https://typst.app/docs/reference/layout/page/).|
## FAQ
### Cómo cambiar el logo del departamento
El parámetro `departamento` solamente es un diccionario de Typst con las llaves `nombre` y `logo`. Puedes crear un diccionario con un logo personalizado y pasárselo al template:
```typ
#import "@preview/enunciado-facil-fcfm:0.1.0" as template
#let mi-departamento = (
nombre: "Mi súper departamento personalizado",
logo: image("mi-super-logo.png"),
)
#show: template.conf.with(
titulo: "Documento con logo personalizado",
departamento: mi-departamento,
curso: "CC4034 - Composición de documentos",
)
```
### Cómo cambiar márgenes, tamaño de página, etcétera
Para cambiar la configuración de la página hay que interceptar la [set rule](https://typst.app/docs/reference/styling/#set-rules) que se hace sobre `page`. Para ello, el template expone el parámetro `page-conf` que permit sobreescribir la configuración de página del template. Por ejemplo, para cambiar el tamaño del papel a A4:
```typ
#import "@preview/enunciado-facil-fcfm:0.1.0" as template
#show: template.conf.with(
titulo: "Documento con tamaño A4",
departamento: template.departamentos.dcc,
curso: "CC4034 - Composición de documentos",
page-conf: (paper: "a4")
)
```
### Cómo cambiar la fuente, headings, etc
Usando [show y set rules](https://typst.app/docs/reference/styling/) puedes personalizar mucho más el template. Por ejemplo, para cambiar la fuente:
```typ
#import "@preview/enunciado-facil-fcfm:0.1.0" as template
// En este caso hay que cambiar la fuente
// antes de que se configure el template
// para que se aplique en el título y encabezado
#set text(font: "New Computer Modern")
#show: template.conf.with(
titulo: "Documento con la fuente de LaTeX",
departamento: template.departamentos.dcc,
curso: "CC4034 - Composición de documentos",
)
```
|
https://github.com/darioglasl/Arbeiten-Vorlage-Typst | https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/05_Qualitätssicherung/00_index.typ | typst | Die Qualitätssicherung ist ein wesentlicher Bestandteil der Softwareentwicklung. Ihr Ziel ist es, sicherzustellen, dass die entwickelte Software den festgelegten Anforderungen entspricht und zuverlässig, effizient und fehlerfrei funktioniert.
Dieses Kapitel beleuchtet die Massnahmen zur Qualitätssicherung, die im Rahmen dieser Arbeit durchgeführt werden.
#include "01_test_concept.typ"
#pagebreak()
#include "02_unit_tests.typ"
#pagebreak()
#include "03_integration_tests.typ"
#pagebreak()
#include "04_validierung_nfr.typ"
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/CHANGELOG/CHANGELOG-0.2.md | markdown | Apache License 2.0 | # v0.2.3
Note: There will be large changes in the next version because Typst will introduce experimental package management in `v0.6.0`, so this version is the last version of the 0.2.x series.
## Changelog since v0.2.3
**Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.2.2...v0.2.3
### Security Notes
No new security note.
### Bug fix
- compiler: correct order of searching fonts in https://github.com/Myriad-Dreamin/typst.ts/pull/175
- compiler: reset today for each compilation in https://github.com/Myriad-Dreamin/typst.ts/pull/171
### Changes
- cli: add embedded font again in https://github.com/Myriad-Dreamin/typst.ts/pull/176
- compiler: emit plain text if out isn't a TTY in https://github.com/Myriad-Dreamin/typst.ts/pull/170
- compiler: ignore utf-8 bom in https://github.com/Myriad-Dreamin/typst.ts/pull/172
- compiler: loose relevance check for watching fs changes in https://github.com/Myriad-Dreamin/typst.ts/pull/193
### External Feature
- exporter::svg: A new SVG exporter is introduced in https://github.com/Myriad-Dreamin/typst.ts/pull/127
- with typst semantics, responsive link in https://github.com/Myriad-Dreamin/typst.ts/pull/128, text selection in https://github.com/Myriad-Dreamin/typst.ts/pull/137.
- with incremental rendering by Me, @seven-mile and @Enter-tainer in https://github.com/Myriad-Dreamin/typst.ts/pull/129
- with dynamic (responsive) layout in https://github.com/Myriad-Dreamin/typst.ts/pull/141
- with source mapping from svg elements to typst ones in https://github.com/Myriad-Dreamin/typst.ts/pull/154, https://github.com/Myriad-Dreamin/typst.ts/pull/161, and https://github.com/Myriad-Dreamin/typst.ts/pull/162
- cli: generate and watch svg with dynamic layout in https://github.com/Myriad-Dreamin/typst.ts/pull/142 and https://github.com/Myriad-Dreamin/typst.ts/pull/179
- compiler: incremental parsing in https://github.com/Myriad-Dreamin/typst.ts/pull/186
# v0.2.2
## Changelog since v0.2.2
**Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.2.1...v0.2.2
### Security Notes
No new security note.
### Changes
- cli: remove web_socket exporter in https://github.com/Myriad-Dreamin/typst.ts/pull/118
### External Feature
- cli: use human-panic in https://github.com/Myriad-Dreamin/typst.ts/pull/120
- pkg::core: sema layer with link annotations in https://github.com/Myriad-Dreamin/typst.ts/pull/124
- upstream: upgrade typst to v0.5.0 in https://github.com/Myriad-Dreamin/typst.ts/pull/125
# v0.2.1
## Changelog since v0.2.1
**Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.2.0...v0.2.1
### Bug fix
- fix(core): ir unaligned memory in https://github.com/Myriad-Dreamin/typst.ts/pull/99
### Security Notes
No new security note.
### External Feature
- compiler: eager snapshot rendering in https://github.com/Myriad-Dreamin/typst.ts/pull/63
- core: collect and export glyph info in https://github.com/Myriad-Dreamin/typst.ts/pull/112
- core: optional render text by partial fonts in https://github.com/Myriad-Dreamin/typst.ts/pull/113
- exporter::canvas error handling in https://github.com/Myriad-Dreamin/typst.ts/pull/67
- exporter::canvas is almost done (1): glyph cache and clip impl in https://github.com/Myriad-Dreamin/typst.ts/pull/65
- exporter::canvas is almost done (2): render svg and bitmap glyphs in https://github.com/Myriad-Dreamin/typst.ts/pull/86
- packages::core: customize access model in https://github.com/Myriad-Dreamin/typst.ts/pull/34
- packages::compiler: add integrated canvas renderer in https://github.com/Myriad-Dreamin/typst.ts/pull/35
- packages::renderer: font supports for cjk and emoji glyphs in https://github.com/Myriad-Dreamin/typst.ts/pull/84
- server::remote: serve remote compilation in https://github.com/Myriad-Dreamin/typst.ts/pull/54
- server::remote: load fonts in snapshot in https://github.com/Myriad-Dreamin/typst.ts/pull/60
- github-pages: init github-pages in https://github.com/Myriad-Dreamin/typst.ts/pull/37
- misc: set linguist language of typst source files in https://github.com/Myriad-Dreamin/typst.ts/pull/41
### Internal Feature
- docs: add troubleshooting docs about wasm in https://github.com/Myriad-Dreamin/typst.ts/pull/90
- test: init snapshot testing in https://github.com/Myriad-Dreamin/typst.ts/pull/72
- test: test wasm renderer with ci integration in https://github.com/Myriad-Dreamin/typst.ts/pull/76
- test: corpus for CJK font testing: add hust template in https://github.com/Myriad-Dreamin/typst.ts/pull/82
- test: corpus for math testing: add undergradmath in https://github.com/Myriad-Dreamin/typst.ts/pull/110
- test from upstream: visualize path and polygon corpus in https://github.com/Myriad-Dreamin/typst.ts/pull/79
- test from upstream: shape aspect corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/85
- test from upstream: outline rendering corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/89
- test from upstream: shape circle corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/94
- test from upstream: layout clip corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/95
- test from upstream: layout list marker corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/96
- test from upstream: layout transform corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/100
- test from upstream: visualize stroke corpora in https://github.com/Myriad-Dreamin/typst.ts/pull/104
# v0.2.0
## Changelog since v0.2.0
### Known Issues
- `pollster` does not work on WebAssembly, which means that we cannot run async code in a function unless it is marked as async: [Polyfill WebAssembly](https://github.com/Myriad-Dreamin/typst.ts/issues/26). This affects both development of compiler module and renderer module.
### Security Notes
No new security note.
### Changes
- `typst.ts` package's `TypstRenderer.render` method now accepts `Uint8Array` as input instead of `String`.
#### External Feature
- Program `typst-ts-cli` add commands:
- `typst-ts-cli --VV {none,short,full,json,json-plain}`
- `typst-ts-cli env`
- `typst-ts-cli font measure`
- Program `typst-ts-cli compile` add flags:
- `--watch`
- `--trace`
- `--web-socket`
- `--font-path`
- `--format {ast,ir,nothing,rmp,web_socket}`
- Program `typst-ts-cli` has been fully implemented.
- Add and implement `typst.angular` package.
- Add the ability to check for outdated artifacts using `typst_ts_core::artifact::BuildInfo`.
- (Experimental) add `typst_ts_core::artifact_ir::Artifact`, which is faster than encoding a normal artifact as JSON.
- (Experimental) add `typst_ts_core::font::FontProfile`, which can be loaded into browser compiler.
- Add `typst_ts_{ast,pdf,serde(json,rmp),ir}_exporter::Exporter`.
- Add browser compiler module and api `get_ast,get_artifact`.
- Add the ability to render individual document pages separately by browser renderer module.
- Add the ability for the browser renderer module to use system fonts from chromium `queryLocalFonts`.
- Modularize `typst.ts` package, with optional loading browser compiler module and browser renderer module.
- `typst.ts` exports compiler api `init,reset,addSource,getAst,compile`.
- `typst.ts` can now render partial pages of document.
- `typst_ts_core::artifact{,_ir}` store complete source text mapping, which improves user searching experience.
#### Internal Feature
- Unify `typst_ts_core::{Artifact,Document}Exporter` as `typst_ts_core::Exporter`.
- Add zero copy abstraction for `typst_ts_core::Exporter` (FsPathExporter, VecExporter).
- Stabilize `typst_ts_core::font::Font{Slot,Loader}`.
- Make `typst_ts_core::font::FontResolverImpl` modifiable.
- Add `typst_ts_compiler::vfs::Vfs::<AccessModel>`.
- Add `typst_ts_compiler::vfs::{{Cached,Dummy,browser::Proxy,System}AccessModel}`.
- Unify `typst_ts_compiler::{Browser,System}World` as `typst_ts_compiler::CompilerWorld`.
- Lazily add web fonts in FontData format to `typst_ts_compiler::BrowserFontSearcher`.
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/template.typ | typst | MIT License | // This function gets your whole document as its `body` and formats
// it as an article in the style of the IEEE.
#import "lib/mod.typ": *
#let appendix = state("appendix", false)
#let heading-supplement = state("heading-supplement", "Section")
#let start-appendix(
show-title: true,
show-toc: true,
) = {
counter(heading).update(0)
appendix.update(true)
heading-supplement.update("Appendix")
if show-title {
[
#heading(
level: 1,
numbering: none,
supplement: heading-supplement.display(),
[Appendix]
)<appendix>
]
}
if show-toc {
// [#heading([Contents], level: 2, numbering: none, outlined: false)<contents-1>]
outline(
title: none,
indent: auto,
depth: 2,
target: heading.where(numbering: "A.1:"),
)
}
}
#let paper(
// The paper's title.
title: "Paper Title",
subtitle: none,
title-page: false,
title-page-extra: none,
title-page-footer: none,
title-page-content: none,
// An array of authors. For each author you can specify a name,
// department, organization, location, and email. Everything but
// but the name is optional.
authors: (),
// The paper's publication date. Can be omitted if you don't have
// one.
date: none,
// The paper's abstract. Can be omitted if you don't have one.
abstract: none,
// A list of index terms to display after the abstract.
index-terms: (),
// The article's paper size. Also affects the margins.
paper-size: "a4",
two-column: false,
// colors
accent: blue,
// The path to a bibliography file if you want to cite some external
// works.
bibliography-file: none,
// Whether to print a table of contents.
print-toc: false,
toc-depth: none,
toc-printer: (depth) => {
set par(first-line-indent: 0em)
outline(
indent: true,
fill: grid(
columns: 1,
block(
fill: black,
height: 0.5pt,
width: 100%,
),
block(
fill: none,
height: 0.25em,
width: 100%,
),
),
depth: depth,
)
// pagebreak(weak: true)
colbreak(weak: true)
},
prebody: none,
postbody: none,
// postbody: [
// #pagebreak(weak: true)
// #start-appendix(show-title: true)
// #set heading(numbering: "A:", supplement: "Appendix")
// #include "sections/appendix.typ"
// ],
// The paper's content.
body
) = {
// Set document metadata.
set document(title: title, author: authors.map(author => author.name))
// Set the body font.
set text(font: "STIX Two Text", size: 12pt)
// set text(font: "New Computer Modern", size: 12pt)
// Configure the page.
set page(
// fill: theme.base,
paper: paper-size,
numbering: "i", // "1/1"
number-align: center,
)
show cite: citation => {
show regex("\d+"): set text(accent)
[#citation]
}
show math.equation.where(block: true) : set block(spacing: 1.25em)
// show figure: it => align(center, {
// it.body
// set par(justify: false)
// // set text(size: 0.75em)
// {
// set text(accent)
// it.supplement + " " + it.counter.display(it.numbering) + "."
// }
// " " + it.caption.body
// v(1.5em, weak: true)
// })
// show figure: fig => {
// let (fs, bh) = if fig.kind == "algorithm" {
// (1em, 0em)
// } else {
// (0.8em, 2em)
// }
//
// set text(size: fs)
// set align(center)
//
// [#fig.body]
// v(1em, weak: true)
//
// if fig.kind == "example" {}
// else if fig.kind == "algorithm" {}
// else {
// set text(accent)
// fig.supplement
// fig.counter.display(fig.numbering)
// set text(black)
// fig.caption.body
//
// }
//
// v(bh, weak: true)
//
//
// }
set math.mat(delim: "[")
show figure: it => align(center)[
#let fs = 0.8em
#let bh = 2em
#if it.kind == "algorithm" {
fs = 1em
bh = 0em
}
#set text(size: fs)
#it.body
#v(1em, weak: true)
#if it.kind != "algorithm" [
#set text(accent)
#it.supplement
#it.counter.display(it.numbering).
#set text(black)
#if it.caption != none {
it.caption.body
}
] #h(0.1em)
// #it.caption
// #repr(it.caption)
#v(bh, weak: true)
]
show figure.where(kind: "example") : it => {
it.body
}
show figure.where(kind: "algorithm") : it => {
it.body
}
// triggered when using the dedicated syntax `@ref`
show ref: it => {
let el = it.element
// return repr(el)
if el == none {
it.citation
}
else {
let eq = math.equation
if el.func() == eq {
// The reference is an equation
let sup = if it.fields().at("supplement", default: "none") == "none" {
[Equation]
} else { [] }
// let sup = it.fields().at("supplement", default: "none")
// show link : set text(black)
// show regex("\d+"): set text(accent)
// let n = numbering(el.numbering, ..counter(eq).at(el.location()))
let n = counter(eq).at(el.location()).at(0)
return [#link(it.target, sup) \(#link(it.target, [#n])\)]
}
else if el.has("kind") and el.kind == "example" {
let loc = it.element.location()
let exs = query(selector(<meta:excounter>).after(loc), loc)
let number = example-counter.at(exs.first().location())
return link(
it.target,
[#el.supplement~#numbering(it.element.numbering, ..number)]
)
}
else {
return link(
it.target,
it
)
}
}
}
// Configure equation numbering and spacing
set math.equation(numbering: "(1)")
// show math.equation: set block(spacing: 1.25em)
// Configure lists
set list(indent: 0em, body-indent: 0.5em)
set enum(indent: 0em, body-indent: 0.5em)
// Configure headings
set heading(numbering: "1.1.1")
show heading.where(level: 1) : set text (size: 24pt)
show heading.where(level: 2) : set text (size: 18pt)
show heading.where(level: 3) : set text (size: 16pt)
show heading.where(level: 4) : set text (size: 14pt)
// functions
// display the mails in a set construction manner
let display-mails() = {
// make unique set of dicts all email domains and a list of their mail prefixes
let mail_set = (:)
for author in authors {
if "email" in author {
// text(author.email.split("@").join(", "))
let mail = author.email.split("@").at(0)
let domain = author.email.split("@").at(1)
if domain in mail_set {
mail_set.at(domain).push(mail)
} else {
mail_set.insert(domain, (mail,))
}
}
}
// display the set construction(s)
// making sure to only do the set construction syntax if one domain includes multiple mails
for domain in mail_set.keys() {
let mails = mail_set.at(domain)
if mails.len() > 1 {
text("{" + mails.join(", ") + "}" + "@" + domain)
} else {
text(mails.at(0) + "@" + domain)
}
if mail_set.keys().last() != domain {
text(", ")
}
}
}
// Find all unique affiliations
let process-affiliations(authors) = {
// make sure to filter out duplicate affiliations
// make each affiliation a dictionary with three keys:
// department, organization, location
// then filter out duplicate dictionaries, where all
// three key/values pairs are the same
let affiliations = authors.map(author => {
let meta = (:)
if "name" in author {
meta.insert("name", author.name)
}
let info = (:)
if "department" in author {
info.insert("department", author.department)
}
if "organization" in author {
info.insert("organization", author.organization)
}
if "location" in author {
info.insert("location", author.location)
}
let affiliation = (
meta: meta,
info: info
)
affiliation
})
// filter out duplicate affiliations
let unique-affiliations = ()
for affiliation in affiliations {
let is-unique = true
for other in unique-affiliations {
if affiliation.info == other.info {
is-unique = false
break
}
}
if is-unique {
affiliation.meta.insert("index", unique-affiliations.len() + 1)
// update the author's affiliation index
authors = authors.map(author => {
let author_affiliation = (
department: author.department,
organization: author.organization,
location: author.location,
)
if author_affiliation == affiliation.info {
author.insert("affiliation", affiliation.meta.index)
}
author
})
unique-affiliations.push(affiliation)
}
}
(unique-affiliations, authors)
}
let display-title() = {
// Display the paper's title.
text(18pt, title, weight: 600)
if subtitle != none {
v(5mm, weak: true)
align(center, text(14pt, subtitle))
}
}
let display-names(authors, affiliation-set) = {
// display author names as comma separated list, the last two
// separated by "and" with oxford comma.
// including a superscripted affiliation index in front of each name
set text(12pt, weight: 700)
let names = authors.map(author => {
let name = [#author.name]
if affiliation-set.len() > 1 {
let index = author.affiliation
name = super[#index] + name
}
name
})
if names.len() == 1 {
text(names.at(0))
} else if names.len() == 2 {
text(names.at(0) + " & " + names.at(1))
} else {
text(names.slice(0, -1).join(", ") + ", and " + names.at(-1))
}
}
let display-affiliations(affiliation-set) = {
// display the author affiliations
// that is: department, organization, location
// except for the email addresses
set text(10pt, weight: 400)
// display the affiliations as a grid
// with one column per affiliation
grid(
columns: affiliation-set.len() * (1fr,),
gutter: 12pt,
..affiliation-set.map(affiliation => {
let a = affiliation.info
let i = affiliation.meta.index
if affiliation-set.len() > 1 [
#super[#i]
]
if "department" in a [
#emph([#a.department])
]
if "organization" in a [
\ #emph(a.organization)
]
if "location" in a [
\ #a.location
]
})
)
}
// display the date
let display-date() = {
if date == none {
return
}
else if date == "today" {
let today = datetime.today()
let day-suffix = "th"
let modten = calc.rem(today.day(), 10)
if modten == 1 {
"st"
} else if modten == 2 {
"nd"
} else if modten == 3 {
"rd"
}
text(10pt, weight: 700, today.display("[month repr:long] [day]" + day-suffix + " [year]"))
} else {
text(10pt, weight: 700, date)
}
}
let make-title(authors, unique-affiliations) = {
set align(center)
// Display the paper's title.
v(3pt, weak: true)
display-title()
// display the author names
v(8.35mm, weak: true)
display-names(authors, unique-affiliations)
// display the author affiliations
display-affiliations(unique-affiliations)
// display the email addresses
v(0.75em, weak: true)
display-mails()
// display the date
if (date != none) {
v(5.65mm, weak: true)
display-date()
}
}
let make-titlepage(authors, unique-affiliations) = {
// Title page
set page(numbering: none)
if (title-page-content != none) {
title-page-content
} else {
make-title(authors, unique-affiliations)
v(1fr, weak: true)
title-page-extra
v(1fr, weak: true)
title-page-footer
}
pagebreak(weak: true)
}
let breaklink(url) = link(url, for c in url [#c.replace(c,c+sym.zws)]) // zws -> zero width space
show regex("https?://[^\s]+"): url => {
breaklink(url.text)
}
let (unique-affiliations, authors) = process-affiliations(authors)
if title-page {
make-titlepage(authors, unique-affiliations)
counter(page).update(1)
} else {
make-title(authors, unique-affiliations)
}
// Paper contents
// reset text settings
set align(left)
// set text(10pt, weight: 400)
v(40pt, weak: true)
// Start two column mode and configure paragraph properties.
set par(justify: true, first-line-indent: 1em)
show par: set block(spacing: 0.65em)
// Print TOC if print-toc is true
if print-toc {
toc-printer(toc-depth)
}
{
let col-amount = 1
let col-gutter = 0pt
if two-column {
col-amount = 2
col-gutter = 12pt
show: columns.with(col-amount, gutter: col-gutter)
}
prebody
// Display abstract and index terms.
if abstract != none [
#set text(weight: 700)
#h(1em) _Abstract_---#abstract
#if index-terms != () [
#h(1em)_Index terms_---#index-terms.join(", ")
]
#v(2pt)
]
// Display the paper's contents.
body
let ref-text-size = if two-column { 10pt } else { 14pt }
// Display bibliography.
if bibliography-file != none {
show bibliography: set text(8pt)
// bibliography(bibliography-file, title: text(ref-text-size)[References], style: "ieee")
heading(
level: 1,
numbering: none,
supplement: "References",
[References]
)
bibliography(bibliography-file, title: none, style: "ieee")
}
}
postbody
}
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/sub_script/sub_script_inserted.typ | typst | First#sub[first sub text]
Normal text#sub[inserted sub text]
Second#sub[second sub text] |
|
https://github.com/alerque/polytype | https://raw.githubusercontent.com/alerque/polytype/master/data/prime-symbol/typst.typ | typst | #set page(
paper: "a7",
margin: 4mm,
)
#set text(
font: "Libertinus Serif",
size: 12pt,
)
#show par: set block(spacing: 1em)
#show math.equation: set block(spacing: .8em)
#show math.equation: set par(leading: .4em)
Math mode manners:
#[
#show math.equation: set text(font: "STIX Two Math", size: 16pt)
$
f(x) &= a' + b'' + c''' \
f'(x) &= x^2 + 1
$
]
#[
#show math.equation: set text(font: "Libertinus Math", size: 16pt)
$
f(x) &= a' + b'' + c''' \
f'(x) &= x^2 + 1
$
]
Prose poses problems:
60*10'16"N 24*55'52"E (plain)\
60°10′16″N 24°55′52″E (unicode)\
60#[#sym.degree]10#[#sym.prime]16#[#sym.prime.double]N 24#[#sym.degree]55#[#sym.prime]52#[#sym.prime.double]E (idiomatic)\
|
|
https://github.com/touying-typ/touying | https://raw.githubusercontent.com/touying-typ/touying/main/themes/aqua.typ | typst | MIT License | #import "../src/exports.typ": *
/// Default slide function for the presentation.
///
/// - `config` is the configuration of the slide. You can use `config-xxx` to set the configuration of the slide. For more several configurations, you can use `utils.merge-dicts` to merge them.
///
/// - `repeat` is the number of subslides. Default is `auto`,which means touying will automatically calculate the number of subslides.
///
/// The `repeat` argument is necessary when you use `#slide(repeat: 3, self => [ .. ])` style code to create a slide. The callback-style `uncover` and `only` cannot be detected by touying automatically.
///
/// - `setting` is the setting of the slide. You can use it to add some set/show rules for the slide.
///
/// - `composer` is the composer of the slide. You can use it to set the layout of the slide.
///
/// For example, `#slide(composer: (1fr, 2fr, 1fr))[A][B][C]` to split the slide into three parts. The first and the last parts will take 1/4 of the slide, and the second part will take 1/2 of the slide.
///
/// If you pass a non-function value like `(1fr, 2fr, 1fr)`, it will be assumed to be the first argument of the `components.side-by-side` function.
///
/// The `components.side-by-side` function is a simple wrapper of the `grid` function. It means you can use the `grid.cell(colspan: 2, ..)` to make the cell take 2 columns.
///
/// For example, `#slide(composer: 2)[A][B][#grid.cell(colspan: 2)[Footer]]` will make the `Footer` cell take 2 columns.
///
/// If you want to customize the composer, you can pass a function to the `composer` argument. The function should receive the contents of the slide and return the content of the slide, like `#slide(composer: grid.with(columns: 2))[A][B]`.
///
/// - `..bodies` is the contents of the slide. You can call the `slide` function with syntax like `#slide[A][B][C]` to create a slide.
#let slide(
config: (:),
repeat: auto,
setting: body => body,
composer: auto,
..bodies,
) = touying-slide-wrapper(self => {
let header(self) = {
place(
center + top,
dy: .5em,
rect(
width: 100%,
height: 1.8em,
fill: self.colors.primary,
align(left + horizon, h(1.5em) + text(fill: white, utils.call-or-display(self, self.store.header))),
),
)
place(left + top, line(start: (30%, 0%), end: (27%, 100%), stroke: .5em + white))
}
let footer(self) = {
set text(size: 0.8em)
place(right, dx: -5%, utils.call-or-display(self, utils.call-or-display(self, self.store.footer)))
}
let self = utils.merge-dicts(
self,
config-page(
fill: self.colors.neutral-lightest,
header: header,
footer: footer,
),
)
touying-slide(self: self, config: config, repeat: repeat, setting: setting, composer: composer, ..bodies)
})
/// Title slide for the presentation. You should update the information in the `config-info` function. You can also pass the information directly to the `title-slide` function.
///
/// Example:
///
/// ```typst
/// #show: aqua-theme.with(
/// config-info(
/// title: [Title],
/// ),
/// )
///
/// #title-slide(subtitle: [Subtitle], extra: [Extra information])
/// ```
#let title-slide(..args) = touying-slide-wrapper(self => {
let info = self.info + args.named()
let body = {
set align(center)
stack(
spacing: 3em,
if info.title != none {
text(size: 48pt, weight: "bold", fill: self.colors.primary, info.title)
},
if info.author != none {
text(fill: self.colors.primary-light, size: 28pt, weight: "regular", info.author)
},
if info.date != none {
text(
fill: self.colors.primary-light,
size: 20pt,
weight: "regular",
utils.display-info-date(self),
)
},
)
}
self = utils.merge-dicts(
self,
config-common(freeze-slide-counter: true),
config-page(
background: utils.call-or-display(self, self.store.background),
margin: (x: 0em, top: 30%, bottom: 0%),
),
)
touying-slide(self: self, body)
})
/// Outline slide for the presentation.
///
/// - `leading` is the leading of paragraphs in the outline. Default is `50pt`.
#let outline-slide(leading: 50pt) = touying-slide-wrapper(self => {
set text(size: 30pt, fill: self.colors.primary)
set par(leading: leading)
let body = {
grid(
columns: (1fr, 1fr),
rows: (1fr),
align(
center + horizon,
{
set par(leading: 20pt)
context {
if text.lang == "zh" {
text(
size: 80pt,
weight: "bold",
[#text(size:36pt)[CONTENTS]\ 目录],
)
} else {
text(
size: 48pt,
weight: "bold",
[CONTENTS],
)
}
}
},
),
align(
left + horizon,
{
set par(leading: leading)
set text(weight: "bold")
components.custom-progressive-outline(
level: none,
depth: 1,
numbered: (true,),
)
},
),
)
}
self = utils.merge-dicts(
self,
config-common(freeze-slide-counter: true),
config-page(
background: utils.call-or-display(self, self.store.background),
margin: 0em,
),
)
touying-slide(self: self, body)
})
/// New section slide for the presentation. You can update it by updating the `new-section-slide-fn` argument for `config-common` function.
///
/// Example: `config-common(new-section-slide-fn: new-section-slide.with(numbered: false))`
///
/// - `level` is the level of the heading.
///
/// - `body` is the body of the section. It will be pass by touying automatically.
#let new-section-slide(level: 1, body) = touying-slide-wrapper(self => {
let slide-body = {
stack(
dir: ttb,
spacing: 12%,
align(
center,
text(
fill: self.colors.primary,
size: 166pt,
utils.display-current-heading-number(level: level),
),
),
align(
center,
text(
fill: self.colors.primary,
size: 60pt,
weight: "bold",
utils.display-current-heading(level: level, numbered: false),
),
),
)
body
}
self = utils.merge-dicts(
self,
config-page(
margin: (left: 0%, right: 0%, top: 20%, bottom: 0%),
background: utils.call-or-display(self, self.store.background),
),
)
touying-slide(self: self, slide-body)
})
/// Focus on some content.
///
/// Example: `#focus-slide[Wake up!]`
#let focus-slide(body) = touying-slide-wrapper(self => {
self = utils.merge-dicts(
self,
config-common(freeze-slide-counter: true),
config-page(fill: self.colors.primary, margin: 2em),
)
set text(fill: self.colors.neutral-lightest, size: 2em, weight: "bold")
touying-slide(self: self, align(horizon + center, body))
})
/// Touying aqua theme.
///
/// Example:
///
/// ```typst
/// #show: aqua-theme.with(aspect-ratio: "16-9", config-colors(primary: blue))`
/// ```
///
/// Consider using:
///
/// ```typst
/// #set text(font: "Fira Sans", weight: "light", size: 20pt)`
/// #show math.equation: set text(font: "Fira Math")
/// #set strong(delta: 100)
/// #set par(justify: true)
/// ```
///
/// - `aspect-ratio` is the aspect ratio of the slides. Default is `16-9`.
///
/// - `header` is the header of the slides. Default is `self => utils.display-current-heading(depth: self.slide-level)`.
///
/// - `footer` is the footer of the slides. Default is `context utils.slide-counter.display()`.
///
/// ----------------------------------------
///
/// The default colors:
///
/// ```typ
/// config-colors(
/// primary: rgb("#003F88"),
/// primary-light: rgb("#2159A5"),
/// primary-lightest: rgb("#F2F4F8"),
/// neutral-lightest: rgb("#FFFFFF")
/// )
/// ```
#let aqua-theme(
aspect-ratio: "16-9",
header: self => utils.display-current-heading(depth: self.slide-level),
footer: context utils.slide-counter.display(),
..args,
body,
) = {
set text(size: 20pt)
set heading(numbering: "1.1")
show heading.where(level: 1): set heading(numbering: "01")
show: touying-slides.with(
config-page(
paper: "presentation-" + aspect-ratio,
margin: (x: 2em, top: 3.5em, bottom: 2em),
),
config-common(
slide-fn: slide,
new-section-slide-fn: new-section-slide,
),
config-methods(
init: (self: none, body) => {
show heading: set text(fill: self.colors.primary-light)
body
},
alert: utils.alert-with-primary-color,
),
config-colors(
primary: rgb("#003F88"),
primary-light: rgb("#2159A5"),
primary-lightest: rgb("#F2F4F8"),
neutral-lightest: rgb("#FFFFFF")
),
// save the variables for later use
config-store(
align: align,
header: header,
footer: footer,
background: self => {
let page-width = if self.page.paper == "presentation-16-9" { 841.89pt } else { 793.7pt }
let r = if self.at("show-notes-on-second-screen", default: none) == none { 1.0 } else { 0.5 }
let bias1 = - page-width * (1-r)
let bias2 = - page-width * 2 * (1-r)
place(left + top, dx: -15pt, dy: -26pt,
circle(radius: 40pt, fill: self.colors.primary))
place(left + top, dx: 65pt, dy: 12pt,
circle(radius: 21pt, fill: self.colors.primary))
place(left + top, dx: r * 3%, dy: 15%,
circle(radius: 13pt, fill: self.colors.primary))
place(left + top, dx: r * 2.5%, dy: 27%,
circle(radius: 8pt, fill: self.colors.primary))
place(right + bottom, dx: 15pt + bias2, dy: 26pt,
circle(radius: 40pt, fill: self.colors.primary))
place(right + bottom, dx: -65pt + bias2, dy: -12pt,
circle(radius: 21pt, fill: self.colors.primary))
place(right + bottom, dx: r * -3% + bias2, dy: -15%,
circle(radius: 13pt, fill: self.colors.primary))
place(right + bottom, dx: r * -2.5% + bias2, dy: -27%,
circle(radius: 8pt, fill: self.colors.primary))
place(center + horizon, dx: bias1, polygon(fill: self.colors.primary-lightest,
(35% * page-width, -17%), (70% * page-width, 10%), (35% * page-width, 30%), (0% * page-width, 10%)))
place(center + horizon, dy: 7%, dx: bias1,
ellipse(fill: white, width: r * 45%, height: 120pt))
place(center + horizon, dy: 5%, dx: bias1,
ellipse(fill: self.colors.primary-lightest, width: r * 40%, height: 80pt))
place(center + horizon, dy: 12%, dx: bias1,
rect(fill: self.colors.primary-lightest, width: r * 40%, height: 60pt))
place(center + horizon, dy: 20%, dx: bias1,
ellipse(fill: white, width: r * 40%, height: 70pt))
place(center + horizon, dx: r * 28% + bias1, dy: -6%,
circle(radius: 13pt, fill: white))
}
),
..args,
)
body
}
|
https://github.com/Karolinskis/KTU-typst | https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/mainPages/SecondPage.typ | typst | #import "/variables.typ" : *
#page(header: none)[
#set align(center)
#image("/images/ktu-logo.png", width: 2cm)
#set text(size:12pt)
*Kauno technologijos universitetas*\
#ProjectFaculty
#v(4cm)
#set text(size: 18pt, weight: "bold")
#ProjectName
#set text(size:14pt, weight: "regular")
#ProjectType\
#ProjectStudies
#v(4cm)
#set text(size:12pt)
#set align(left)
#h(8cm)*#AuthorName.at(1)*\
#h(8cm)Projekto #AuthorName.at(0)
#v(1cm)
#h(8cm)*#ProjectSupervisor.at(1)*\
#h(8cm)#ProjectSupervisor.at(0)
#v(1cm)
#h(8cm)*#ProjectReviewer.at(1)*\
#h(8cm)#ProjectReviewer.at(0)
#align(center + bottom)[
*#ProjectCity, #ProjectYear*
]
] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/codelst/0.0.3/README.md | markdown | Apache License 2.0 | # codelst (v0.0.3)
**codelst** is a [Typst](https://github.com/typst/typst) package for rendering sourcecode with line numbers and some other additions.
## Usage
For Typst 0.6.0 or later import the package from the typst preview repository:
```js
#import "@preview/codelst:0.0.3": sourcecode
```
For Typst before 0.6.0 or to use **codelst** as a local module, download the package files into your project folder and import `codelst.typ`:
```js
#import "codelst.typ": sourcecode
```
After importing the package, simple wrap any fenced code block in a call to `#sourcecode()`:
````js
#import "@preview/codelst:0.0.3": sourcecode
#sourcecode[```typ
#show "ArtosFlow": name => box[
#box(image(
"logo.svg",
height: 0.7em,
))
#name
]
This report is embedded in the
ArtosFlow project. ArtosFlow is a
project of the Artos Institute.
```]
````
## Further documentation
See `manual.pdf` for a comprehensive manual of the package.
See `example.typ` for some quick usage examples.
## Development
The documentation is created using [Mantys](https://github.com/jneug/typst-mantys), a Typst template for creating package documentation.
To compile the manual Mantys needs to be available as a local package. Refer to Mantys' manual for instructions how to do so.
## Changelog
### v0.0.3
- Removed call to `#read()` from `#sourcefile()`.
- Added `continue-numbering` argument to `#sourcecode()`.
- Fixed problem with `showrange` having out of range line numbers.
### v0.0.3
- Added a comprehensive manual.
- Fixed crash for missing `lang` attribute in `raw` element.
### v0.0.1
- Initial version submitted to typst/packages.
|
https://github.com/daniel-eder/typst-template-jku | https://raw.githubusercontent.com/daniel-eder/typst-template-jku/main/src/template/pages/toc.typ | typst | // SPDX-FileCopyrightText: 2023 <NAME>
//
// SPDX-License-Identifier: Apache-2.0
#let toc(
) = {
set page(numbering: "i")
//style toc entries
show outline.entry.where(level: 1): it => {
v(16pt, weak: true)
strong(it)
}
show outline.entry.where(level: 2): it => {
it
}
heading("Contents", numbering: none, outlined: true) //we want ToC to be in the ToC
outline(
title: none,
depth: 3,
indent: true
)
} |
|
https://github.com/tsukinoko-kun/ki-lernen-forschung | https://raw.githubusercontent.com/tsukinoko-kun/ki-lernen-forschung/main/src/main.typ | typst | #import "@preview/charged-ieee:0.1.0": ieee
#show: ieee.with(
title: [Wie wirkt sich die Verwendung von KI auf den Lernerfolg von Software-Engineering-Studenten aus?],
// abstract: [
// ],
authors: (
(
name: "<NAME>",
department: [Software Engineering],
organization: [Hochschule Heilbronn],
location: [Heilbronn, Deutschland],
email: "<EMAIL>"
),
),
index-terms: ("Learning", "Artificial intelligence", "Software engineering", "Software tools", "Software engineering education", "Software engineering students", "Software engineering bachelor", "Generative AI", "Learning effectiveness", "Learning outcomes", "Learning process", "Learning tools", "Learning strategies", "Learning methods", "Learning environments", "Learning experiences"),
bibliography: bibliography("refs.yaml"),
)
#set text(font: "Times New Roman")
#set text(lang: "de")
#show heading: it => block(
breakable: false,
[
#v(0.5em)
#it
#v(0.3em)
],
)
= Einführung
Für das Lernen geeignete, KI-basierte Tools sind recht neu. Einige Studierende verwenden sie, der Umgang unter Lehrenden variiert. Ich möchte herausfinden, ob und unter welchen Bedingungen KI-basierte Tools einen positiven Effekt auf den Lernerfolg von Software-Engineering-Studierenden haben.
Ich sehe die Notwendigkeit, das Thema zu untersuchen, da ich selbst Software-Engineering studiere und einige Kommilitonen habe, die Tools wie ChatGPT verwenden, um sich die Arbeit zu erleichtern. Was ich dabei beobachte, ist besorgniserregend: falsche Informationen, kein Hinterfragen der Ergebnisse und kein Bewusstsein für den eigenen Lernprozess und Kenntnisstand.
Da stelle ich mir die Frage, ob das am Tool selbst oder an der Art und Weise liegt, wie die Studierenden damit umgehen.
Mir geht es also darum, herauszufinden, wie wir in der Lehre für Software-Engineering mit den KI-Tools umgehen sollten, um für die Studierenden eine optimale Ausbildung zu gewährleisten. Ob KI für die tägliche Arbeit von Software-Entwicklern geeignet ist, ist ein anderes Thema und wird hier nicht berücksichtigt.
= Forschungsfragen
== Hauptfrage
Wie beeinflusst der Einsatz von KI-basierten Tools die Lerneffektivität von Studierenden in Hochschulkursen des Software-Engineering-Studiengangs?
== Unterfragen
+ Wie gehen Studierende mit verschiedenen Arten von Tools um?
+ Wie verändert sich die Selbsteinschätzung der Studierenden?
+ Welche Auswirkungen hat die Vorerfahrung der Studierenden in der Software-Entwicklung auf die oben genannten Punkte?
= Methodik
Als Tutor für die Vorlesung Interaktive Programme an der Hochschule Heilbronn (das ist die erste Programmierveranstaltung im Studium Software Engineering Bachelor), habe ich die Möglichkeit, die Studierenden gezielt mit und ohne KI-Tools lernen zu lassen.
== Gruppen
Die Studierenden werde ich in zwei Gruppen aufteilen:
- *Gruppe A*: Nicht-KI-Gruppe #linebreak()
Die Studierenden werden dazu aufgefordert, keine KI-Tools zu verwenden. Sie bekommen ein normales Tutorium. Das heißt, dass ich sie bei Problemen in der Lösungsfindung unterstütze. Von mir gibt es keine konkreten Lösungen. Ich werde die Studierenden mit Tipps und Hinweisen in Richtung einer möglichen Lösung lenken. Diese Richtungsweisungen werden so klein wie möglich sein, dass die Studierenden die Lösung selbst finden können. #linebreak()
Da es sich um das erste Semester handelt und ich nicht von Vorwissen ausgehen kann, werde ich die Studierenden aufklären, welche Tools sie aufgrund der KI-Funktionalität nicht verwenden dürfen.
- *Gruppe B*: KI-Tutor #linebreak()
Die Studierenden werden dazu aufgefordert, beim Lernen mit KI zu arbeiten. Das heißt im Detail, dass Chatbots wie Claude für Verständnisfragen genutzt werden sollen. Der Chatbot wird so konfiguriert, dass er sich wie ein Tutor verhält und die Studierenden an die Hand nimmt aber keine konkrete Lösung ausgibt. #linebreak()
Damit es nicht daran scheitert, dass die Studierenden keine KI-Tools kennen, oder nicht wissen, wie sie diese verwenden sollen, bekommen sie von mir eine Einführung und Unterstützung bei der Verwendung. Für alles, was bewertet wird, müssen sie die KI-Tools deaktivieren. Das dient dazu, das Ergebnis der Studie "Generative AI Can Harm Learning" @bastani2024generative zu verifizieren, bei der festgestellt wurde, dass die Nutzung von KI eine kurzzeitige Verbesserung des Lernerfolgs bewirkt, sobald die KI-Tools deaktiviert werden, fielen die Testpersonen jedoch hinter die Kontrollgruppe zurück.
Die Aufgaben sind regulär aus der Vorlesung und werden nicht verändert. Auch die Bewertung erfolgt ohne Rücksicht auf die Gruppenzugehörigkeit.
Die Teilnahme an der Studie ist freiwillig für alle Studierenden des Studiengangs Software Engineering zugänglich, welche die Vorlesung Interaktive Programme besuchen. Es gibt keine Anreize für die Teilnahme.
== Gruppenzuteilung
Zu Beginn des Semesters werden alle Studierenden gefragt, wer Interesse an der Teilnahme an der Studie hat. Sie werden über das Ziel der Studie und die Gruppen informiert. Die Studierenden, die teilnehmen möchten, werden einen Fragebogen ausfüllen, in dem sie Ihre Haltung zum Thema KI im allgemeinen, sowie ihre Vorerfahrung in der Software-Entwicklung angeben. Anhand dieser Angaben werde ich die Studierenden so in die Gruppen einteilen, dass die angegebenen Faktoren gleichmäßig verteilt sind.
== Verwendete Tools
- *#link("https://claude.ai")[Claude]* #linebreak()
Ein Chatbot, mit dem man in natürlicher Sprache eine Konversation führen kann.
- *#link("https://www.cursor.com/")[Cursor]* #linebreak()
Ein Fork von Visual Studio Code, der mit KI-Tools erweitert wurde.
== Datenerhebung
+ Die Lerneffektivität wird anhand der Bewertung der Aufgaben gemessen. Hier möchte ich selbsteinschätzung der Studierenden vermeiden, da diese inakkurat ist.
+ Wie die Studierenden mit verschiedenen Arten von Tools umgehen, wird durch Beobachtung ermittelt. Hier werde ich alles auffällige notieren und später auswerten. In den Tutorien der Gruppe B werde ich wenig selbst mit den Studierenden interagieren, daher ist die gleichzeitige Beobachtung möglich. Bei Gruppe A gibt es keine KI-Tools, daher müssen sie auch nicht bei der Verwendung dieser beobachtet werden.
+ Die Selbsteinschätzung der Studierenden wird durch Fragebögen ermittelt. Dieser bildet direkt die Selbsteinschätzung ab und wird alleine durchgeführt. Dieser Fragebogen wird wöchentlich ausgefüllt und besteht aus vielen Skalen, die die eigene Wahrnehmung auf Lernfortschritt, Leistung, Motivation und Wissensstand abfragen.
+ Die Vorerfahrung der Studierenden in der Software-Entwicklung wird durch einen Fragebogen und Lebenslauf ermittelt. Die Erfahrung wird in einer Schätzung der Anzahl der Stunden, die die Studierenden bereits in der Software-Entwicklung verbracht haben, gemessen. #linebreak()
Das ist eine sehr ungenaue Angabe, aber Jahre sind nicht aussagekräftig, da jeder unterschiedlich viel Stunden pro Tag und Tage pro Woche investiert.
+ Da die Studierenden auch alleine an ihren Aufgaben arbeiten werden, müssen sie ein Tagebuch führen, in dem sie festhalten, wie lange sie an den Aufgaben gearbeitet haben, welche Tools sie verwendet haben und was es für Auffälligkeiten gab. Dieses wird bei der Hauptfrage und den Unterfragen 1 und 2 berücksichtigt.
== Aufgaben
_wird ergänzt wenn bekannt_
|
|
https://github.com/kacper-uminski/math-notes | https://raw.githubusercontent.com/kacper-uminski/math-notes/main/tfya86/formulas.typ | typst | Creative Commons Zero v1.0 Universal | #import "@preview/physica:0.9.3": *
#show math.phi: math.phi.alt
#set page(flipped: true)
#set text(size: 9pt, font: "New Computer Modern")
#set grid(gutter: 1em)
#grid(columns: (1fr, 1fr, 1fr))[
*Elektromagnetism*
#grid(columns: (1fr, 1fr),
[Coulombs lag], $F_"el" = 1/(4pi epsilon_0)$,
[Elektrisk fältstyrka], $va(E) = va(F)_0/q_0$,
[Elektrisk fältstyrka omkring punktladdning], $va(E) = 1/(4pi epsilon_0) q/r^2 vu(r)$,
[Elektriskt flöde], $Phi_E & = va(E) dot va(A)
\ & = E A cos phi
\ & = integral va(E) dot dd(va(A))
\ & = integral E cos phi dd(A)$,
[Gauss lag för elektriskt fält], $Phi_E = integral.cont va(E) dot dd(va(A)) = Q_"encl"/epsilon_0$,
[Potentiell energi i elektriskt fält omkring punktladdning (om $U = 0$ vid $r = oo$)], $U = (q q_0)/(4pi epsilon_0) 1/r$,
[Elektrisk potential], $V = U/q_0$,
[Elektrisk potential kring punktladdning (om $V_(r=oo) = 0$)], $V = q/(4pi epsilon_0 r)$,
[Elektrisk potential], $-Delta V = integral_a^b va(E) dot dd(va(l))$,
[Elektriskt fält], $va(E) = -va(grad)V$,
[Vridmoment för elektrisk dipol], $va(tau) = va(p) times va(E)$,
[Potentiell energi för elektrisk dipol], $U = -va(p) dot va(E)$,
[Elektrisk fältstyrka för kondensator], $E = sigma/epsilon_0$,
[Elektrisk fältstyrka för kondensator med dielektriskt material], $E = E_0/K$,
[Energilagring i kondensator], $U = Q^2/(2C)$,
[Energitäthet i elektriskt fält],$u = 1/2 epsilon_0 E^2$
)
][
*Magnetfält och magnetism*
#grid(columns: (1fr, 1fr),
[Kraft på laddad partikel i magnetfält], $va(F_B) = q va(v) times va(B)$,
[Kraft på strömförande ledare], $dd(va(F)) = I dd(va(l)) times va(B)$,
[Biot-Savarts lag], $va(B) = mu_0/(4pi) integral dd(Q (va(v) times va(r))/r^2)$,
[Magnetiskt flöde], $Phi_B & = integral va(B) dd(va(A)) \ & = integral B cos phi dd(A)$,
[Gauss lag för magnetiskt fält], $integral.cont va(B) dot dd(va(A)) = 0$,
[Magnetfält på avstånd $x$ från rak ledare], $B = (mu_0 I)/(2pi x)$,
[Amperes lag], $integral.cont va(B) dot dd(va(l)) = mu_0 I_"encl"$,
[Kraft mellan två strömförande ledare], $F/L = (mu_0 I I')/(2pi r)$,
[Dipolmoment (magnetisk dipol)], $va(mu) = I va(A)$,
[Vridmoment för magnetisk dipol], $va(tau) = va(mu) times va(B)$,
[Magnetfält i magnetiskt material i yttre fält $B_0$], $va(B) & = va(B_0) + mu_0 va(M) \ & = va(B_0) K_m $,
[Relativ permeabilitet], [$K_m$],
[Magnetiskt susceptibilitet], $chi_m = K_m - 1$
)
][
*Ström och induktion*
#grid(columns: (1fr, 1fr),
[Elektrisk ström], $I = dv(Q,t) = n q v_d A$,
[Strömtäthet], $va(J) & = n q va(v_d) \ & = (n q^2 tau)/m va(E)$,
[Strömtäthet], $|va(J)| & = I/A = n q v_d$,
[Ohms lag], $E = rho J$,
[Resistivitet], $rho = m/(n q^2 tau)$,
[Temperaturberoende hos resistivitet], $rho(T) = rho_0 (1 + alpha(T - T_0))$,
[Ohms lag om resistiviteten är konstant], $V = R I$,
[Resistans hos ledare], $R = (rho L)/A$,
[]
)
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/acrostiche/0.2.0/README.md | markdown | Apache License 2.0 | # Acrostiche (0.2.0)
Manages acronyms so you don't have to.
## Usage
The main goal of Acrostiche is to keep track of which acronym to define.
### Define acronyms and proxy functions
First, define the acronyms in a dictionary, with the keys being the acronyms and the values being arrays of their definitions. If there is only a singular version of the definition, the array contains only one value (don't forget the trailing comma to force typst to consider it as an array). If there are both singular and plural versions, define the definition as an array where the first item is the singular definition and the second item is the plural.
Then, initialize Arostiche with the acronyms you just defined with the `#init-acronyms(...)` function:
Here is a sample of the `acronyms.typ` file:
```
#import "@preview/acrostiche:0.2.0": *
#init-acronyms((
"NN": ("Neural Network",),
"OS": ("Operating System",),
"BIOS": ("Basic Input/Output System", "Basic Input/Output Systems"),
))
```
### Call Acrostiche functions
Once the acronyms are defined, you can use them in the text with the `#acr(...)` function. The argument is the acronym as a string (for example, "BIOS"). On the first call of the function, it prints the acronym with its definition (for example, "Basic Input/Output System (BIOS)"). On the next calls, it prints only the acronym.
To get the plural version of the acronym, you can use the `#acrpl(...)` function that adds an 's' after the acronym. If a plural version of the definition is provided, it will be used if the first use of the acronym is plural. Otherwise, the singular version is used, and a trailing 's' is added.
At any point in the document, you can reset acronyms with the functions `#reset-acronym(...)` (for a single acronym) or `reset-all-acronyms()` (to reset all acronyms). After a reset, the next use of the acronym is expanded.
You can also print an index of all acronyms used in the document with the `#print-index()` function. The index is printed as a section for which you can choose the heading level and outline parameters (with respectively the `level: int` and `outlined: bool` parameters). You can also choose their order with the `sorted: string` parameter that accepts either an empty string (print in the order they are defined), "up" (print in ascending alphabetical order), or "down" (print in descending alphabetical order).
The index contains all the acronyms you defined. Finally, you can use the `title: string` parameter to change the name of the heading for the index section. The default value is "Acronyms Index". Passing an empty string for `title` results in the index having no heading (i.e., no section for the index).
Finally, you can call the `#display-def(...)` function to display the definition of an acronym. Set the `plural` parameter to true to get the plural version.
## Possible Errors:
* If an acronym is not defined, an error will tell you which one is causing the error. Simply add it to the dictionary or check the spelling.
* For every acronym "ABC" that you define, the state named "acronym-state-ABC" is initialized and used. To avoid errors, do not try to use this state manually for other purposes. Similarly, the state named "acronyms" is reserved to Acrostiche; avoid using it.
* `display-def` leverages the state `display` function and only works if the return value is actually printed in the document. For more information on states, see the Typst documentation on states.
Have fun Acrostiching!
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/include-01.typ | typst | Other | #{
// Error: 19-38 file not found (searched at typ/compiler/modules/chap3.typ)
let x = include "modules/chap3.typ"
}
|
https://github.com/linhduongtuan/BKHN-Thesis_template_typst | https://raw.githubusercontent.com/linhduongtuan/BKHN-Thesis_template_typst/main/contents/abstract.typ | typst | Apache License 2.0 | #let abstract_vn = [
Bài báo này thiết kế một mẫu thiết kế tốt nghiệp của Đại học Bách Khoa Hà Nội dựa trên mẫu Typst để giúp sinh viên hoàn thành việc viết và sắp chữ thiết kế tốt nghiệp thuận tiện hơn. Mẫu áp dụng thiết kế bố cục hiện đại và giao diện người dùng dễ sử dụng, có thể giúp sinh viên nhanh chóng hoàn thành bài viết và bố cục của đồ án tốt nghiệp.
Trong quá trình thiết kế, chúng tôi đã kết hợp thiết kế tuyệt vời của mẫu Typst với các yêu cầu của thiết kế tốt nghiệp của Đại học Bác Khoa Hà Nộiđể tối ưu hóa và điều chỉnh mẫu. Mẫu này chứa các yếu tố khác nhau cần thiết cho thiết kế tốt nghiệp, bao gồm bìa, tóm tắt, mục lục, văn bản chính, tài liệu tham khảo, v.v. Đồng thời, chúng tôi cũng hướng dẫn chi tiết và hỗ trợ kỹ thuật cho sinh viên để giúp sinh viên hoàn thành việc viết và sắp chữ đồ án tốt nghiệp thuận lợi hơn.
Nghiên cứu trong bài báo này có ý nghĩa to lớn đối với việc nâng cao chất lượng và hiệu quả đồ án tốt nghiệp của Đại học Đại học Bác Khoa Hà Nội. Bằng việc thiết kế mẫu thiết kế tốt nghiệp xuất sắc, sinh viên có thể tập trung hơn vào nội dung và nghiên cứu của thiết kế tốt nghiệp, từ đó nâng cao chất lượng và trình độ của thiết kế tốt nghiệp. Đồng thời, template cũng có thể giúp sinh viên hoàn thành việc sắp chữ và xuất đồ án tốt nghiệp thuận tiện hơn, nâng cao hiệu quả và độ chính xác của đồ án tốt nghiệp.
]
#let keywords_vn = ("Bản format mẫu cho Typst", "Đại học Bách Khoa Hà Nội", "Luận văn", "Luận án")
#let abstract_en = [
In this paper, we design a graduation thesis template based on Typst to help students complete their graduation thesis writing and typesetting more conveniently at Hanoi University of Science and Technology. The template adopts modern typesetting design and user-friendly interface, which can help students complete graduation thesis writing and typesetting work quickly.
In the design process, we optimized and adapted the template based on Typst's excellent design and the requirements of graduation thesis at Hanoi University of Science and Technology. The template includes various elements required for graduation thesis, such as cover, abstract, table of contents, main body, reference, etc. At the same time, we also provide detailed instructions and technical support for students to help them complete the writing and typesetting of graduation thesis more smoothly.
The research in this paper is of great significance to improve the quality and efficiency of graduation thesis at Hanoi University of Science and Technology. By designing an excellent graduation thesis template, students can focus more on the content and research of graduation thesis, thus improving the quality and level of graduation thesis. At the same time, the template can also help students complete the typesetting and output of graduation thesis more conveniently, thus improving the efficiency and accuracy of graduation thesis.
]
#let keywords_en = ("Typst Template", "Hanoi University of Science and Technology", "(Under)graduate Thesis") |
https://github.com/Functional-Bus-Description-Language/Specification | https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/memory.typ | typst | == Memory
The memory functionality is used to directly connect and map an external memory to the generated bus address space.
A memory can also be connected to the bus using the proc or stream functionality.
However, using the memory functionality usually leads to greater throughput, but increases the size of the generated address space.
The memory functionality has following properties:
*`access`*` string (`_`"Read Write"`_`) {definitive}`
#pad(left: 1em)[
The `access` property declares the valid access permissions to the memory for the requester.
Valid values of the access property are: _`"Read Write"`_, _`"Read Only"`_, _`"Write Only"`_.
]
*`byte-write-enable`*` bool (false) {declarative}`
#pad(left: 1em)[
The byte-write-enable property declares byte-enable writes, that update the memory on contents on a byte-to-byte basis.
If the byte-write-enable property is explicitly set by a user, and a memory access is
_`"Read Only"`_, then a compiler shall report an error.
]
*`read-latency`*` integer (obligatory if access supports read) {declarative}`
#pad(left: 1em)[
The read-latency property declares the read latency in the number of clock cycles.
It is required, if a memory supports read access, to correcly implement read logic.
]
*`size`*` integer (obligatory) {declarative}`
#pad(left: 1em)[
The size property declares the memory size.
The size is in the number of memory words with width equal to the memory width property value.
]
*`width`*` integer (bus width) {declarative}`
#pad(left: 1em)[
The width property declares the memory data width.
]
The code generated for the requester must provide means for single read/write and block read/write transactions.
Whether access means for vectored (scatter-gather) transactions are automatically generated is up to the compiler.
If memory is read-only or write-only, then an unsupported write or read access code is recommended not to be generated.
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/205.%20hwh.html.typ | typst | hwh.html
How to Work Hard
June 2021It might not seem there's much to learn about how to work hard.
Anyone who's been to school knows what it entails, even if they
chose not to do it. There are 12 year olds who work amazingly hard. And
yet when I ask if I know more about working hard now than when I
was in school, the answer is definitely yes.One thing I know is that if you want to do great things, you'll
have to work very hard. I wasn't sure of that as a kid. Schoolwork
varied in difficulty; one didn't always have to work super hard to
do well. And some of the things famous adults did, they seemed to
do almost effortlessly. Was there, perhaps, some way to evade hard
work through sheer brilliance? Now I know the answer to that question.
There isn't.The reason some subjects seemed easy was that my school had low
standards. And the reason famous adults seemed to do things
effortlessly was years of practice; they made it look easy.Of course, those famous adults usually had a lot of natural ability
too. There are three ingredients in great work: natural ability,
practice, and effort. You can do pretty well with just two, but to
do the best work you need all three: you need great natural ability
and to have practiced a lot and to be trying very hard.
[1]<NAME>, for example, was among the smartest people in business
in his era, but he was also among the hardest working. "I never
took a day off in my twenties," he said. "Not one." It was similar
with <NAME>. He had great natural ability, but when his youth
coaches talk about him, what they remember is not his talent but
his dedication and his desire to win. <NAME> would probably
get my vote for best English writer of the 20th century, if I had
to choose. Certainly no one ever made it look easier. But no one
ever worked harder. At 74, he wrote
with each new book of mine I have, as I say, the feeling that
this time I have picked a lemon in the garden of literature. A
good thing, really, I suppose. Keeps one up on one's toes and
makes one rewrite every sentence ten times. Or in many cases
twenty times.
Sounds a bit extreme, you think. And yet <NAME> sounds even
more extreme. Not one day off in ten years? These two had about
as much natural ability as anyone could have, and yet they also
worked about as hard as anyone could work. You need both.That seems so obvious, and yet in practice we find it slightly hard
to grasp. There's a faint xor between talent and hard work. It comes
partly from popular culture, where it seems to run very deep, and
partly from the fact that the outliers are so rare. If great talent
and great drive are both rare, then people with both are rare
squared. Most people you meet who have a lot of one will have less
of the other. But you'll need both if you want to be an outlier
yourself. And since you can't really change how much natural talent
you have, in practice doing great work, insofar as you can, reduces
to working very hard.It's straightforward to work hard if you have clearly defined,
externally imposed goals, as you do in school. There is some technique
to it: you have to learn not to lie to yourself, not to procrastinate
(which is a form of lying to yourself), not to get distracted, and
not to give up when things go wrong. But this level of discipline
seems to be within the reach of quite young children, if they want
it.What I've learned since I was a kid is how to work toward goals
that are neither clearly defined nor externally imposed. You'll
probably have to learn both if you want to do really great things.The most basic level of which is simply to feel you should be working
without anyone telling you to. Now, when I'm not working hard, alarm
bells go off. I can't be sure I'm getting anywhere when I'm working
hard, but I can be sure I'm getting nowhere when I'm not, and it
feels awful.
[2]There wasn't a single point when I learned this. Like most little
kids, I enjoyed the feeling of achievement when I learned or did
something new. As I grew older, this morphed into a feeling of
disgust when I wasn't achieving anything. The one precisely dateable
landmark I have is when I stopped watching TV, at age 13.Several people I've talked to remember getting serious about work
around this age. When I asked <NAME> when he started to
find idleness distasteful, he said
I think around age 13 or 14. I have a clear memory from around
then of sitting in the sitting room, staring outside, and wondering
why I was wasting my summer holiday.
Perhaps something changes at adolescence. That would make sense.Strangely enough, the biggest obstacle to getting serious about
work was probably school, which made work (what they called work)
seem boring and pointless. I had to learn what real work was before
I could wholeheartedly desire to do it. That took a while, because
even in college a lot of the work is pointless; there are entire
departments that are pointless. But as I learned the shape of real
work, I found that my desire to do it slotted into it as if they'd
been made for each other.I suspect most people have to learn what work is before they can
love it. Hardy wrote eloquently about this in A Mathematician's
Apology:
I do not remember having felt, as a boy, any passion for
mathematics, and such notions as I may have had of the career of
a mathematician were far from noble. I thought of mathematics in
terms of examinations and scholarships: I wanted to beat other
boys, and this seemed to be the way in which I could do so most
decisively.
He didn't learn what math was really about till part way through
college, when he read Jordan's Cours d'analyse.
I shall never forget the astonishment with which I read that
remarkable work, the first inspiration for so many mathematicians
of my generation, and learnt for the first time as I read it what
mathematics really meant.
There are two separate kinds of fakeness you need to learn to
discount in order to understand what real work is. One is the kind
Hardy encountered in school. Subjects get distorted when they're
adapted to be taught to kids — often so distorted that they're
nothing like the work done by actual practitioners.
[3]
The other
kind of fakeness is intrinsic to certain types of work. Some types
of work are inherently bogus, or at best mere busywork.There's a kind of solidity to real work. It's not all writing the
Principia, but it all feels necessary. That's a vague criterion,
but it's deliberately vague, because it has to cover a lot of
different types.
[4]Once you know the shape of real work, you have to learn how many
hours a day to spend on it. You can't solve this problem by simply
working every waking hour, because in many kinds of work there's a
point beyond which the quality of the result will start to decline.That limit varies depending on the type of work and the person.
I've done several different kinds of work, and the limits were
different for each. My limit for the harder types of writing or
programming is about five hours a day. Whereas when I was running
a startup, I could
work all the time. At least for the three years I did it; if I'd
kept going much longer, I'd probably have needed to take occasional
vacations.
[5]The only way to find the limit is by crossing it. Cultivate a
sensitivity to the quality of the work you're doing, and then you'll
notice if it decreases because you're working too hard. Honesty is
critical here, in both directions: you have to notice when you're
being lazy, but also when you're working too hard. And if you think
there's something admirable about working too hard, get that idea
out of your head. You're not merely getting worse results, but
getting them because you're showing off — if not to other people,
then to yourself.
[6]Finding the limit of working hard is a constant, ongoing process,
not something you do just once. Both the difficulty of the work and
your ability to do it can vary hour to hour, so you need to be
constantly judging both how hard you're trying and how well you're
doing.Trying hard doesn't mean constantly pushing yourself to work, though.
There may be some people who do, but I think my experience is fairly
typical, and I only have to push myself occasionally when I'm
starting a project or when I encounter some sort of check. That's
when I'm in danger of procrastinating. But once I get rolling, I
tend to keep going.What keeps me going depends on the type of work. When I was working
on Viaweb, I was driven by fear of failure. I barely procrastinated
at all then, because there was always something that needed doing,
and if I could put more distance between me and the pursuing beast
by doing it, why wait? [7]
Whereas what drives me now, writing
essays, is the flaws in them. Between essays I fuss for a few days,
like a dog circling while it decides exactly where to lie down. But
once I get started on one, I don't have to push myself to work,
because there's always some error or omission already pushing me.I do make some amount of effort to focus on important topics. Many
problems have a hard core at the center, surrounded by easier stuff
at the edges. Working hard means aiming toward the center to the
extent you can. Some days you may not be able to; some days you'll
only be able to work on the easier, peripheral stuff. But you should
always be aiming as close to the center as you can without stalling.The bigger question of what to do with your life is one of these
problems with a hard core. There are important problems at the
center, which tend to be hard, and less important, easier ones at
the edges. So as well as the small, daily adjustments involved in
working on a specific problem, you'll occasionally have to make
big, lifetime-scale adjustments about which type of work to do.
And the rule is the same: working hard means aiming toward the
center — toward the most ambitious problems.By center, though, I mean the actual center, not merely the current
consensus about the center. The consensus about which problems are
most important is often mistaken, both in general and within specific
fields. If you disagree with it, and you're right, that could
represent a valuable opportunity to do something new.The more ambitious types of work will usually be harder, but although
you should not be in denial about this, neither should you treat
difficulty as an infallible guide in deciding what to do. If you
discover some ambitious type of work that's a bargain in the sense
of being easier for you than other people, either because of the
abilities you happen to have, or because of some new way you've
found to approach it, or simply because you're more excited about
it, by all means work on that. Some of the best work is done by
people who find an easy way to do something hard.As well as learning the shape of real work, you need to figure out
which kind you're suited for. And that doesn't just mean figuring
out which kind your natural abilities match the best; it doesn't
mean that if you're 7 feet tall, you have to play basketball. What
you're suited for depends not just on your talents but perhaps even
more on your interests. A deep interest
in a topic makes people
work harder than any amount of discipline can.It can be harder to discover your interests than your talents.
There are fewer types of talent than interest, and they start to
be judged early in childhood, whereas interest in a topic is a
subtle thing that may not mature till your twenties, or even later.
The topic may not even exist earlier. Plus there are some powerful
sources of error you need to learn to discount. Are you really
interested in x, or do you want to work on it because you'll make
a lot of money, or because other people will be impressed with you,
or because your parents want you to?
[8]The difficulty of figuring out what to work on varies enormously
from one person to another. That's one of the most important things
I've learned about work since I was a kid. As a kid, you get the
impression that everyone has a calling, and all they have to do is
figure out what it is. That's how it works in movies, and in the
streamlined biographies fed to kids. Sometimes it works that way
in real life. Some people figure out what to do as children and
just do it, like Mozart. But others, like Newton, turn restlessly
from one kind of work to another. Maybe in retrospect we can identify
one as their calling — we can wish Newton spent more time on math
and physics and less on alchemy and theology — but this is an
illusion induced by hindsight bias.
There was no voice calling to him that he could have heard.So while some people's lives converge fast, there will be others
whose lives never converge. And for these people, figuring out what
to work on is not so much a prelude to working hard as an ongoing
part of it, like one of a set of simultaneous equations. For these
people, the process I described earlier has a third component: along
with measuring both how hard you're working and how well you're
doing, you have to think about whether you should keep working in
this field or switch to another. If you're working hard but not
getting good enough results, you should switch. It sounds simple
expressed that way, but in practice it's very difficult. You shouldn't
give up on the first day just because you work hard and don't get
anywhere. You need to give yourself time to get going. But how much
time? And what should you do if work that was going well stops going
well? How much time do you give yourself then?
[9]What even counts as good results? That can be really hard to decide.
If you're exploring an area few others have worked in, you may not
even know what good results look like. History is full of examples
of people who misjudged the importance of what they were working
on.The best test of whether it's worthwhile to work on something is
whether you find it interesting. That may sound like a dangerously
subjective measure, but it's probably the most accurate one you're
going to get. You're the one working on the stuff. Who's in a better
position than you to judge whether it's important, and what's a
better predictor of its importance than whether it's interesting?For this test to work, though, you have to be honest with yourself.
Indeed, that's the most striking thing about the whole question of
working hard: how at each point it depends on being honest with
yourself.Working hard is not just a dial you turn up to 11. It's a complicated,
dynamic system that has to be tuned just right at each point. You
have to understand the shape of real work, see clearly what kind
you're best suited for, aim as close to the true core of it as you
can, accurately judge at each moment both what you're capable of
and how you're doing, and put in as many hours each day as you can
without harming the quality of the result. This network is too
complicated to trick. But if you're consistently honest and
clear-sighted, it will automatically assume an optimal shape, and
you'll be productive in a way few people are.Notes[1]
In "The Bus Ticket Theory of Genius" I said the three ingredients
in great work were natural ability, determination, and interest.
That's the formula in the preceding stage; determination and interest
yield practice and effort.[2]
I mean this at a resolution of days, not hours. You'll often
get somewhere while not working in the sense that the solution to
a problem comes to you while taking a
shower, or even in your sleep,
but only because you were working hard on it the day before.It's good to go on vacation occasionally, but when I go on vacation,
I like to learn new things. I wouldn't like just sitting on a beach.[3]
The thing kids do in school that's most like the real version
is sports. Admittedly because many sports originated as games played
in schools. But in this one area, at least, kids are doing exactly
what adults do.In the average American high school, you have a choice of pretending
to do something serious, or seriously doing something pretend.
Arguably the latter is no worse.[4]
Knowing what you want to work on doesn't mean you'll be able
to. Most people have to spend a lot of their time working on things
they don't want to, especially early on. But if you know what you
want to do, you at least know what direction to nudge your life in.[5]
The lower time limits for intense work suggest a solution to
the problem of having less time to work after you have kids: switch
to harder problems. In effect I did that, though not deliberately.[6]
Some cultures have a tradition of performative hard work. I
don't love this idea, because (a) it makes a parody of something
important and (b) it causes people to wear themselves out doing
things that don't matter. I don't know enough to say for sure whether
it's net good or bad, but my guess is bad.[7]
One of the reasons people work so hard on startups is that
startups can fail, and when they do, that failure tends to be both
decisive and conspicuous.[8]
It's ok to work on something to make a lot of money. You need
to solve the money problem somehow, and there's nothing wrong with
doing that efficiently by trying to make a lot at once. I suppose
it would even be ok to be interested in money for its own sake;
whatever floats your boat. Just so long as you're conscious of your
motivations. The thing to avoid is unconsciously letting the need
for money warp your ideas about what kind of work you find most
interesting.[9]
Many people face this question on a smaller scale with
individual projects. But it's easier both to recognize and to accept
a dead end in a single project than to abandon some type of work
entirely. The more determined you are, the harder it gets. Like a
Spanish Flu victim, you're fighting your own immune system: Instead
of giving up, you tell yourself, I should just try harder. And who
can say you're not right?
Thanks to <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME> for reading drafts of this.Arabic Translation
|
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/main.typ | typst | MIT License | #import "lib/mod.typ": *
#import "template.typ": *
#set raw(theme: "catppuccin.tmTheme")
#show figure.where(kind: raw): set block(breakable: true)
// #show raw : it => text(font: "JetBrainsMono NF", catppuccin.latte.text, it)
#show raw: it => {
text(fill: theme.text, it)
}
// #show figure.where(kind: raw): set text(theme.text)
#show raw.where(block: false): (it) => {
set text(catppuccin.latte.text, font: "JetBrainsMono NF", size: 1em)
set box(fill: catppuccin.latte.base, radius: 3pt, stroke: none, inset: (x: 2pt), outset: (y: 2pt))
box(
it,
)
}
// #show raw.where(lang: "text"): (it) => {
// // set text(catppuccin.latte.text, font: "JetBrainsMono NF", size: 1em)
// show regex("/") : all => text(theme.lavender, all)
// [#it]
// }
#show footnote : it => {
set text(accent)
it
}
// #show regex("A") : it => {
// box(
// inset: (x: 2pt),
// outset: (y: 2pt),
// image("brickbob.gif", width: 2em)
// )
// }
// #show link: it => underline(text(accent)[#it])
// #show link: it => text(accent)[#it]
#show link: it => text(accent, it)
// #set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled))
// #set list(marker: text(catppuccin.latte.lavender, sym.suit.diamond))
// #set list(marker: text(catppuccin.latte.lavender, sym.hexa.filled))
#set list(marker: {
set line(stroke: (paint: accent))
marker.arrow.single
})
// #set list.where(level)
#set enum(full: true)
#set grid(gutter: 0.5em)
#set image(width: 100%)
#show outline.entry.where() : it => {
let t = it.body.fields().values().at(0)
// let p = it.page
let size = 1em
let color = black
let weight = "medium"
if it.level == 1 {
v(1.5em)
size = 1.2em
color = accent
weight = "black"
}
if type(t) == "array" {
v(-3em)
// h(it.element.level * 2em)
let offset = if it.element.level == 1 {
-1.25mm
} else {
0mm
}
link(
it.element.location(),
grid(
column-gutter: 2pt,
columns: ((it.element.level - 1) * 8mm + offset, auto, 1fr, auto),
align: (center, left + bottom, center + bottom, right + bottom),
[],
text(color, size: size, weight: weight, [
#box(
width: 8mm,
it.body.fields().values().at(0).at(0)
)
#it.body.fields().values().at(0).slice(2).join("")
]),
block(fill: color, height: 0.5pt, width: 100%),
text(color, size: 1em, weight: weight, it.page),
)
)
} else {
v(-3em)
link(
it.element.location(),
grid(
column-gutter: 2pt,
columns: (0em, auto, 1fr, auto),
align: (center, left + bottom, center + bottom, right + bottom),
[],
text(color, size: size, weight: weight, it.body),
block(fill: color, height: 0.5pt, width: 100%),
text(color, size: 1em, weight: weight, it.page),
)
)
}
}
// OVERSKRIFTER
#show heading.where(numbering: "1.1") : it => [
#v(0.75em)
#block({
box(width: 18mm, text(counter(heading).display(), weight: 600))
text(it.body, weight: 600)
})
#v(1em)
]
#show heading.where(level: 1) : it => text(
accent,
size: 18pt,
)[
#pagebreak(weak: true)
#let subdued = theme.text.lighten(50%)
#set text(font: "JetBrainsMono NF")
#grid(
columns: (1fr, 1fr),
align: (left + bottom, right + top),
text(it.body, size: 24pt, weight: "bold"),
if it.numbering != none {
text(subdued, weight: 200, size: 100pt)[#counter(heading).get().at(0)]
v(1em)
},
)
#v(-0.5em)
// #hr
#hline-with-gradient(cmap: (accent, subdued), height: 2pt)
#v(1em)
]
#show heading.where(level: 4) : it => text(
black,
size: 14pt,
)[
#v(0.25em)
#block({
box(width: 18mm, text(counter(heading).display(), weight: 600))
text(it.body, weight: 600)
})
#v(0.15em)
]
#show: paper.with(
paper-size: "a4",
title: project-name,
subtitle: "Master's Thesis in Computer Engineering",
title-page: true,
title-page-extra: align(center,
std-block(
width: 90%,
std-block(
radius: 0.5em,
clip: true,
inset: 0pt,
pad(
rest: -1mm,
image("figures/img/showcase-during.png")
// top: -6mm,
// bottom: -10mm,
// rest: -1mm,
// image("figures/img/showcase-during-perspective-1.png")
// top: -20mm,
// bottom: -10mm,
// rest: -1mm,
// image("figures/img/showcase-during-perspective-2.png")
)
)
)
),
title-page-footer: align(center)[
#grid(
columns: 2,
row-gutter: 1em,
align: (x, y) => (right, left).at(x),
[*Supervisor:*],
supervisors.andriy,
[*Co-supervisor:*],
supervisors.jonas,
)
#v(1em, weak: true)
\{andriy, <EMAIL>\}\<EMAIL>
#v(7mm, weak: true)
#image("img/au-logo.svg", width: 30%)
],
authors: authors,
date: datetime.today().display("[day]-[month]-[year]"),
// bibliography-file: "references.bib",
print-toc: false,
toc-depth: 2,
accent: accent,
postbody: context [
#let resume-page = counter(page).at(<nomenclature>).first()
// #repr(resume-page)
#counter(page).update(resume-page + 2)
#set page(numbering: "i")
#pagebreak(weak: true)
#start-appendix(show-toc: true)
#show heading : it => text(
black,
)[
#set par(justify: false)
#v(0.25em)
#block([
#text(counter(heading).display()) #text(it.body, weight: 600)
])
#v(0.15em)
]
#show heading.where(level: 1) : it => text(
black,
)[
#pagebreak(weak: true)
#set par(justify: false)
#v(0.25em)
#block([
#text(counter(heading).display()) #text(it.body, weight: 600)
])
#v(0.15em)
]
#set heading(numbering: "A.1:", supplement: "Appendix")
#include "sections/appendix.typ"
]
)
#let acronyms = yaml("acronyms.yaml")
#let acrostiche-acronyms = merge(..acronyms.map(it => {
let v = (it.definition,)
if "plural" in it {
v.push(it.plural)
}
(it.acronym: v)
}))
#init-acronyms(acrostiche-acronyms)
// This is important! Call it whenever your page is reconfigured.
// #if not release {
// set-page-properties()
// }
// #if "release" in sys.inputs and sys.inputs.release == "true" {
// set-margin-note-defaults(hidden: true)
// } else {
// set-margin-note-defaults(hidden: false)
// }
// #show: word-count
// Pre-introduction
#set heading(numbering: none)
// #set page(numbering: "i")
#include "sections/0-predoc/preface.typ"
#include "sections/0-predoc/abstract.typ"
#include "sections/0-predoc/nomenclature.typ"
#include "sections/0-predoc/acronym-index.typ"
// #acr("SOA"), #acrpl("AOS")
// Table of Contents
#pagebreak(weak: true)
#heading([Contents], level: 1, numbering: none, outlined: false)<contents-1>
#v(1em)
#toc-printer(target: heading.where().before(<contents-1>).and(heading.where(level: 1)))
#let main-numbering = "1.1"
#v(1em)
#toc-printer(target: heading.where(numbering: main-numbering))
#v(1em)
#toc-printer(target: heading.where(numbering: none).after(<contents-1>).before(<references>))
#v(1em)
#toc-printer(target: heading.where(numbering: none).after(<appendix>))
// #stats()
// Report
#set heading(numbering: main-numbering)
#set page(numbering: "1")
#counter(heading).update(0)
#counter(page).update(1)
#set page(
header: context {
let h1 = hydra(1)
let h2 = hydra(2)
if h1 == none {
return none
}
let cm = (accent, theme.text.lighten(50%))
let odd = calc.odd(here().page())
if odd {
cm = cm.rev()
}
set text(gradient.linear(..cm))
let h = {
let chapter-number = h1.fields().values().first().first()
let chapter-title = h1.fields().values().first().slice(2)
if type(chapter-title) == "array" {
chapter-title = chapter-title.join("")
}
[Chapter #chapter-number: #chapter-title]
// repr(h1.fields().values().first().slice(2))
if h2 != none {
h(0.5em)
sym.bar.h
h(0.5em)
h2
}
}
let date = {
datetime.today().display("[day]-[month]-[year]")
}
let items = (h, date)
if odd {
items = items.rev()
}
grid(
columns: (auto, 1fr),
align: (left, right),
..items
)
hline-with-gradient(cmap: cm, height: 1pt)
}
)
#include "sections/1-introduction/mod.typ"
#include "sections/related-works.typ"
#include "sections/2-background/mod.typ"
#include "sections/3-methodology/mod.typ"
#include "sections/4-results/mod.typ"
#include "sections/5-discussion/mod.typ"
#include "sections/6-conclusion/mod.typ"
// #include "sections/future-work.typ"
// Hello. bad sentence. This is a better one. although this could be it as well
// it goes across lines.
#heading([References], level: 1, numbering: none)<references>
#bibliography(
"./references.yaml",
style: "future-science",
// style: "american-society-of-mechanical-engineers",
// style: "ieee",
title: none,
)
|
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/tmlr/main.typ | typst | MIT License | #import "/tmlr.typ": tmlr
#import "/logo.typ": LaTeX, LaTeX as LaTeX2e
#let affls = (
nyu: (
department: "Department of Computer Science",
institution: "University of New York"),
deepmind: (
institution: "DeepMind"),
mila: (
institution: "Mila, Université de Montréal"),
google-research: (
institution: "Google Research"),
cifar: (
institution: "CIFAR Fellow")
)
#let authors = (
(name: "<NAME>", email: "<EMAIL>", affl: "nyu"),
(name: "<NAME>", email: "<EMAIL>", affl: "deepmind"),
(name: "<NAME>",
email: "<EMAIL>",
affl: ("mila", "google-research", "cifar")),
)
#show: tmlr.with(
title: [Formatting Instructions for TMLR \ Journal Submissions],
authors: (authors, affls),
keywords: (),
abstract: [
The abstract paragraph should be indented 1/2~inch on both left and
right-hand margins. Use 10~point type, with a vertical spacing of
11~points. The word #text(size: 12pt)[*Abstract*] must be centered, in
bold, and in point size~12. Two line spaces precede the abstract. The
abstract must be limited to one paragraph.
],
bibliography: bibliography("main.bib"),
appendix: include "appendix.typ",
accepted: false,
review: "https://openreview.net/forum?id=XXXX",
)
#let url(uri) = {
link(uri, raw(uri))
}
= Submission of papers to TMLR
TMLR requires electronic submissions, processed by
#url("https://openreview.net/"). See TMLR's website for more instructions.
If your paper is ultimately accepted, use option `accepted` with the `tmlr`
package to adjust the format to the camera ready requirements, as follows:
#align(center, ```tex
\usepackage[accepted]{tmlr}
```)
You also need to specify the month and year by defining variables `month` and
`year`, which respectively should be a 2-digit and 4-digit number. To
de-anonymize and remove mentions to TMLR (for example for posting to preprint
servers), use the preprint option, as in `\usepackage[preprint]{tmlr}`.
Please read carefully the instructions below, and follow them faithfully.
== Style
Papers to be submitted to TMLR must be prepared according to the instructions
presented here.
Authors are required to use the TMLR #LaTeX style files obtainable at the TMLR
website. Please make sure you use the current files and not previous versions.
Tweaking the style files may be grounds for rejection.
== Retrieval of style files
The style files for TMLR and other journal information are available online on
the TMLR website. The file `tmlr.pdf` contains these instructions and
illustrates the various formatting requirements your TMLR paper must satisfy.
Submissions must be made using #LaTeX and the style files `tmlr.sty` and
`tmlr.bst` (to be used with #LaTeX2e). The file `tmlr.tex` may be used as a
"shell" for writing your paper. All you have to do is replace the author,
title, abstract, and text of the paper with your own.
The formatting instructions contained in these style files are summarized in
sections #ref(<gen_inst>, supplement: none), #ref(<headings>, supplement:
none), and #ref(<others>, supplement: none) below.
= General formatting instructions <gen_inst>
The text must be confined within a rectangle 6.5~inches wide and 9~inches long.
The left margin is 1~inch. Use 10~point type with a vertical spacing of
11~points. Computer Modern Bright is the preferred typeface throughout.
Paragraphs are separated by 1/2~line space, with no indentation.
Paper title is 17~point, in bold and left-aligned. All pages should start at
1~inch from the top of the page.
Authors' names are set in boldface. Each name is placed above its corresponding
address and has its corresponding email contact on the same line, in italic and
right aligned. The lead author's name is to be listed first, and the
co-authors' names are set to follow vertically.
Please pay special attention to the instructions in section #ref(<others>,
supplement: none) regarding figures, tables, acknowledgments, and references.
= Headings: first level <headings>
First level headings are in bold, flush left and in point size 12. One line
space before the first level heading and 1/2~line space after the first level
heading.
== Headings: second level
Second level headings are in bold, flush left and in point size 10. One line
space before the second level heading and 1/2~line space after the second level
heading.
=== Headings: third level
Third level headings are in bold, flush left and in point size 10. One line
space before the third level heading and 1/2~line space after the third level
heading.
= Citations, figures, tables, references <others>
These instructions apply to everyone, regardless of the formatter being used.
== Citations within the text
Citations within the text should be based on the `natbib` package and include
the authors' last names and year (with the "et~al." construct for more than two
authors). When the authors or the publication are included in the sentence, the
citation should not be in parenthesis, using `\citet{}` (as in "See
#cite(<Hinton06>, form: "prose") for more information."). Otherwise, the
citation should be in parenthesis using `\citep{}` (as in "Deep learning shows
promise to make progress towards AI~@Bengio2007.").
The corresponding references are to be listed in alphabetical order of authors,
in the *References* section. As to the format of the references themselves, any
style is acceptable as long as it is used consistently.
== Footnotes
Indicate footnotes with a number#footnote[Sample of the first footnote] in the
text. Place the footnotes at the bottom of the page on which they appear.
Precede the footnote with a horizontal rule of 2~inches.#footnote[Sample of the
second footnote]
== Figures
All artwork must be neat, clean, and legible. Lines should be dark enough for
purposes of reproduction; art work should not be hand-drawn. The figure number
and caption always appear after the figure. Place one line space before the
figure caption, and one line space after the figure. The figure caption is
lower case (except for first word and proper nouns); figures are numbered
consecutively.
Make sure the figure caption does not get separated from the figure. Leave
sufficient space to avoid splitting the figure and figure caption.
You may use color figures. However, it is best for the figure captions and the
paper body to make sense if the paper is printed either in black/white or in
color.
#figure(
rect(width: 4.2cm + 0.8pt, height: 4.20cm + 0.8pt, stroke: 0.4pt),
caption: [Sample figure caption.])
== Tables
All tables must be centered, neat, clean and legible. Do not use hand-drawn
tables. The table number and title always appear before the table. See
@sample-table. Place one line space before the table title, one line space
after the table title, and one line space after the table. The table title must
be lower case (except for first word and proper nouns); tables are numbered
consecutively.
#figure(
table(
columns: 2,
stroke: none,
align: (x, y) => if y == 0 { center } else { left },
table.header([*PART*], [*DESCRIPTION*]),
table.hline(stroke: 0.5pt),
[Dendrite], [Input terminal],
[Axon ], [Output terminal],
[Soma ], [Cell body (contains cell nucleus)]),
caption: [Sample table title],
placement: top) <sample-table>
= Default Notation
In an attempt to encourage standardized notation, we have included the notation
file from the textbook, _Deep Learning_ @goodfellow2016deep available at
#url("https://github.com/goodfeli/dlbook_notation/"). Use of this style is not
required and can be disabled by commenting out `math_commands.tex`.
#v(2em, weak: true)
#align(center, [*Numbers and Arrays*])
#table(
columns: (1in + 5pt, 3.25in + 15pt),
inset: 5pt,
stroke: none,
$a$, [A scalar (integer or real)],
$bold(a)$, [A vector],
$bold(A)$, [A matrix],
$bold(upright(sans(A)))$, [A tensor],
$bold(I)_n$, [Identity matrix with $n$ rows and $n$ columns],
$bold(I)$, [Identity matrix with dimensionality implied by context],
$bold(e)^((i))$, [Standard basis vector $[0,dots,0,1,0,dots,0]$ with a 1 at position $i$],
$op("diag")(bold(a))$, [A square, diagonal matrix with diagonal entries given by $bold(a)$],
$upright(a)$, [A scalar random variable],
$bold(upright(a))$, [A vector-valued random variable],
$bold(upright(A))$, [A matrix-valued random variable])
#v(0.25cm, weak: true)
#align(center, [*Sets and Graphs*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$AA$, [A set],
$RR$, [The set of real numbers],
$\{0, 1\}$, [The set containing 0 and 1],
$\{0, 1, dots, n \}$, [The set of all integers between $0$ and $n$],
$[a, b]$, [The real interval including $a$ and $b$],
$(a, b]$, [The real interval excluding $a$ but including $b$],
$AA \\ BB$, [Set subtraction, i.e., the set containing the elements of $AA$ that are not in $BB$],
$cal(G)$, [A graph],
$italic(P a)_cal(G)(upright(x)_i)$, [The parents of $upright(x)_i$ in $cal(G)$])
#v(0.25cm, weak: true)
#align(center, [*Indexing*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$a_i$, [Element $i$ of vector $bold(a)$, with indexing starting at 1],
$a_(-i)$, [All elements of vector $bold(a)$ except for element $i$],
$A_(i, j)$, [Element $i, j$ of matrix $bold(A)$],
$bold(A)_(i, :)$, [Row $i$ of matrix $bold(A)$],
$bold(A)_(:, i)$, [Column $i$ of matrix $bold(A)$],
$sans(A)_(i, j, k)$, [Element $(i, j, k)$ of a 3-D tensor $bold(upright(sans(A)))$],
$bold(upright(sans(A)))_(:, :, i)$, [2-D slice of a 3-D tensor],
$upright(a)_i$, [Element $i$ of the random vector $bold(upright(a))$])
#v(0.25cm, weak: true)
#align(center, [*Calculus*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$display((d y) / (d x))$, [Derivative of $y$ with respect to $x$],
$display((diff y) / (diff x))$, [Partial derivative of $y$ with respect to $x$],
$nabla_bold(x) y$, [Gradient of $y$ with respect to $bold(x)$],
$nabla_bold(X) y$, [Matrix derivatives of $y$ with respect to $bold(X)$],
$nabla_bold(upright(sans(X))) y$, [Tensor containing derivatives of $y$ with respect to $bold(upright(sans(X)))$],
$display((diff f) / (diff bold(x)))$, [Jacobian matrix $bold(J) in RR^(m times n)$ of $f: RR^n arrow.r RR^m$],
$nabla_bold(x)^2 f(bold(x)) "or" bold(H)(f)(bold(x))$, [The Hessian matrix of $f$ at input point $bold(x)$],
$display(integral f(bold(x)) d bold(x))$,
[Definite integral over the entire domain of $bold(x)$],
$display(integral_SS f(bold(x)) d bold(x))$,
[Definite integral with respect to $bold(x)$ over the set $SS$])
#v(0.25cm, weak: true)
#align(center, [*Probability and Information Theory*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$P(upright(a))$, [A probability distribution over a discrete variable],
$p(upright(a))$, [A probability distribution over a continuous variable, or over a variable whose type has not been specified],
$upright(a) tilde P$, [Random variable $upright(a)$ has distribution $P$],
$EE_(upright(x) tilde P) [ f(x) ] "or" EE f(x)$, [Expectation of $f(x)$ with respect to $P(upright(x))$],
$op("Var")(f(x))$, [Variance of $f(x)$ under $P(upright(x))$],
$op("Cov")(f(x), g(x))$, [Covariance of $f(x)$ and $g(x)$ under $P(upright(x))$],
$H(upright(x))$, [Shannon entropy of the random variable $upright(x)$],
$D_"KL" (P || Q)$, [Kullback-Leibler divergence of $P$ and $Q$],
$cal(N)(bold(x); bold(mu), bold(Sigma))$, [Gaussian distribution over $bold(x)$ with mean $bold(mu)$ and covariance $bold(Sigma)$])
#v(0.25cm, weak: true)
#align(center, [*Functions*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$f: AA arrow.r BB$, [The function $f$ with domain $AA$ and range $BB$],
$f circle.stroked.tiny g$, [Composition of the functions $f$ and $g$],
$f(bold(x); bold(theta))$,
[A function of $bold(x)$ parametrized by $bold(theta)$. (Sometimes we write
$f(bold(x))$ and omit the argument $bold(theta)$ to lighten notation)],
$log x$, [Natural logarithm of $x$],
$sigma(x)$, [Logistic sigmoid, $display(1 / (1 + exp(-x)))$],
$zeta(x)$, [Softplus, $log(1 + exp(x))$],
$norm(bold(x))_p$, [$L^p$ norm of $bold(x)$],
$norm(bold(x))$, [$L^2$ norm of $bold(x)$],
$x^+$, [Positive part of $x$, i.e., $max(0,x)$],
$bold(1)_"condition"$, [is 1 if the condition is true, 0 otherwise])
#v(0.25cm, weak: true)
// We add page break here in order to align the end of the paper.
#pagebreak()
= Final instructions
Do not change any aspects of the formatting parameters in the style files. In
particular, do not modify the width or length of the rectangle the text should
fit into, and do not change font sizes (except perhaps in the *References*
section; see below). Please note that pages should be numbered.
= Preparing PostScript or PDF files
Please prepare PostScript or PDF files with paper size "US Letter", and not,
for example, "A4". The -t letter option on dvips will produce US Letter files.
Consider directly generating PDF files using `pdflatex` (especially if you are
a MiKTeX user). PDF figures must be substituted for EPS figures, however.
Otherwise, please generate your PostScript and PDF files with the following
commands:
```shell
dvips mypaper.dvi -t letter -Ppdf -G0 -o mypaper.ps
ps2pdf mypaper.ps mypaper.pdf
```
== Margins in LaTeX
Most of the margin problems come from figures positioned by hand using
`\special` or other commands. We suggest using the command `\includegraphics`
from the graphicx package. Always specify the figure width as a multiple of the
line width as in the example below using .eps graphics
```tex
\usepackage[dvips]{graphicx} ...
\includegraphics[width=0.8\linewidth]{myfile.eps}
```
or
```tex
\usepackage[pdftex]{graphicx} ...
\includegraphics[width=0.8\linewidth]{myfile.pdf}
```
for .pdf graphics. See section~4.4 in the graphics bundle documentation
(#url("http://www.ctan.org/tex-archive/macros/latex/required/graphics/grfguide.ps")
A number of width problems arise when #LaTeX cannot properly hyphenate a line.
Please give LaTeX hyphenation hints using the `\-` command.
= Broader Impact Statement
In this optional section, TMLR encourages authors to discuss possible
repercussions of their work, notably any potential negative impact that a user
of this research should be aware of. Authors should consult the TMLR Ethics
Guidelines available on the TMLR website for guidance on how to approach this
subject.
= Author Contributions
If you'd like to, you may include a section for author contributions as is done
in many journals. This is optional and at the discretion of the authors. Only
add this information once your submission is accepted and deanonymized.
= Acknowledgments
Use unnumbered third level headings for the acknowledgments. All
acknowledgments, including those to funding agencies, go at the end of the
paper. Only add this information once your submission is accepted and
deanonymized.
|
https://github.com/mdgrs/resume-typst | https://raw.githubusercontent.com/mdgrs/resume-typst/main/modules/education.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Education")
#cvEntry(
title: [Doctorate in Information Theory],
society: [Ecole Polytechnique Federale de Lausanne EPFL],
date: [2010 - 2015],
location: [Switzerland],
logo: "../src/logos/epfl.svg",
description: list(
[Thesis: Reducing Randomness in Matrix Models for Wireless Communication],
[Courses: Probability #hBar() Signal Processing #hBar() Machine learning #hBar() Graphical Models]
)
)
#cvEntry(
title: [<NAME> Masters: Algebra, Geometry and Number Theory],
society: [University Paris-Sud XI],
date: [2008 - 2010],
location: [France],
logo: "../src/logos/algant_logo.jpg",
description: list(
[Thesis: On some convex cocompact groups in real hyperbolic space (Published in Geometry and Topology)],
[Courses: Geometric Group Theory #hBar() Number Theory #hBar() Differential Geometry #hBar()]
)
)
#cvEntry(
title: [Honours Bachelor in Mathematics],
society: [McGill University],
date: [2005 - 2008],
location: [Canada],
logo: "../src/logos/mcgill.png",
description: list(
[Courses: Algebra #hBar() Analysis #hBar() Algorithms and Data Structures]
)
) |
https://github.com/Ryoga-itf/numerical-analysis | https://raw.githubusercontent.com/Ryoga-itf/numerical-analysis/main/report3/report.typ | typst | #import "../template.typ": *
#import "@preview/codelst:2.0.1": sourcecode, sourcefile
#show: project.with(
week: 3,
authors: (
(
name: sys.inputs.STUDENT_NAME,
id: sys.inputs.STUDENT_ID,
affiliation: "情報科学類2年"
),
),
date: "2024 年 7 月 2 日",
)
// 行列をいい感じにする
#set math.mat(gap: 1em, delim: "[")
== 課題1
=== (1.1)
本課題は、与えられた $A$ に対して、LU 分解を行う Julia プログラムを作成し、結果を報告するというものである。
与えられた $A$ は以下の通り。
$
A = mat(
4, 3, 2, 1;
3, 4, 3, 2;
2, 3, 4, 3;
1, 2, 3, 4;
)
$
実装したコードを以下に示す。
#sourcefile(read("src/1.jl"), file:"src/1.jl")
また、実行結果として次の出力を得た。
#sourcecode[```
L: [1.0 0.0 0.0 0.0; 0.75 1.0 0.0 0.0; 0.5 0.8571428571428571 1.0 0.0; 0.25 0.7142857142857143 0.8333333333333333 1.0]
U: [4.0 3.0 2.0 1.0; 0.0 1.75 1.5 1.25; 0.0 0.0 1.7142857142857144 1.4285714285714286; 0.0 0.0 0.0 1.6666666666666667]
```]
すなわち、$L, U$ の値は以下の通り。
$
L = mat(
1.0, 0.0, 0.0, 0.0;
0.75, 1.0, 0.0, 0.0;
0.5, 0.8571428571428571, 1.0, 0.0;
0.25, 0.7142857142857143, 0.8333333333333333, 1.0;
)
$
$
U = mat(
4.0, 3.0, 2.0, 1.0;
0.0, 1.75, 1.5, 1.25;
0.0, 0.0, 1.7142857142857144, 1.4285714285714286;
0.0, 0.0, 0.0, 1.6666666666666667;
)
$
== 課題2
本課題は課題 1 の課題に対して、行列の積を繰り返すのではなく、ある行を別の行に加える操作を行うことで課題1と同様の消去をし LU 分解を行うというものである。
実装したコードを以下に示す。なお、対応する問題番号についてはコメントで示している。
#sourcefile(read("src/2.jl"), file:"src/2.jl")
=== (2.1)
$
A = mat(
4, 3, 2, 1;
0, 1.75, 1.5, 1.25;
2, 3, 4, 3;
1, 2, 3, 4;
)
$
プログラムの対応する出力を以下に示す。
#sourcecode[```
(2.1): [4.0 3.0 2.0 1.0; 0.0 1.75 1.5 1.25; 2.0 3.0 4.0 3.0; 1.0 2.0 3.0 4.0]
```]
=== (2.2)
プログラム内の `makeU` 関数がそれにあたる。
`makeU(A)` によりこの関数を呼び出すと以下出力が得られた。
#sourcecode[```
(2.2): [4.0 3.0 2.0 1.0; 0.0 1.75 1.5 1.25; 0.0 0.0 1.7142857142857144 1.4285714285714286; 0.0 0.0 0.0 1.6666666666666667]
```]
=== (2.3)
プログラム内の `makeLU` 関数がそれにあたる。
また、プログラム内に例として $L, U$ の値を出力しており、対応する出力は以下の通り。
#sourcecode[```
(2.3)
L: [1.0 0.0 0.0 0.0; 0.75 1.0 0.0 0.0; 0.5 0.8571428571428571 1.0 0.0; 0.25 0.7142857142857143 0.8333333333333333 1.0]
U: [4.0 3.0 2.0 1.0; 0.0 1.75 1.5 1.25; 0.0 0.0 1.7142857142857144 1.4285714285714286; 0.0 0.0 0.0 1.6666666666666667]
```]
=== (2.4)
行列 $A$ について、$i$ 列の $i + 1$ 行目以降を削除するために掛ける行列を $M^(\(i\))$ とすると、これは $P_(i, j)(alpha)$ を用いて表すことができる。
ここで、$P_(i, j)(alpha) = I + alpha bold(e_i e_j)^"T"$ であるから、
$P_(i, j)(alpha) = P_(i, j)(-alpha) = I - alpha bold(e_i e_j)^T$
よって、$M^(\(1\))M^(\(2\)) dots.h.c M^(\(i\)) A = U$ であるから、
$A = (P^(\(k\))(alpha^(\(k\))) dots.h.c P^(\(1\))(alpha^(\(1\))))^(-1) U = L U$
すなわち、$L = (P^(\(k\))(alpha^(\(k\))) dots.h.c P^(\(1\))(alpha^(\(1\))))^(-1) = P^(\(k\))(alpha^(\(k\)))^(-1) dots.h.c P^(\(1\))(alpha^(\(1\)))^(-1)$ である。
これは、$U$ の計算中に順に列ごとに計算をすればよく、また $alpha$ の値を使いまわすことができるため、$U$ を求める過程の値を用いて実装ができる。
// 説明が下手すぎる、カス
// 理解はしてはいるがどうやって表現したらよいのかわからなすぎて終わり……
// 適当にそれっぽい日本語を錬成したが、自信がない
=== (2.5)
本課題は、実際に LU 分解を行うときは課題 1 と課題 2 のどちらの実装が良いかを考察するというものである。
課題 1 でのコードでは、U と L を求めるために、ループの中で毎回行列の積を計算している。
そのため、$N times N$ の大きさの行列に対しては 1 列のある要素を削除消去するたびに $Omicron (N^3)$ かかり、全体として $Omicron (N^5)$ の計算量がかかる。
一方、課題 2 のコードでは全体として $Omicron (N*3)$ の計算量で済んでいる。
そのため、計算量の観点から課題 2 の実装の方が優れていると考えられる。
== 課題3
=== (3.1), (3.2)
本課題は前問で実装した LU 分解によって得られた $L$ と $U$ を用いて連立一次方程式 $A bold(x) = bold(b)$ を解き、解 $bold(x)$ と残差を報告するというものである。
作成したプログラムを以下に示す。
#sourcefile(read("src/3.jl"), file:"src/3.jl")
また、実行結果として以下の出力を得た。
#sourcecode[```
ans: [0.2, -2.7755575615628914e-17, 0.0, 0.2]
error: [0.0, 0.0, 0.0, 0.0]
```]
すなわち、解として
$
bold(x) = mat(
0.2;
-2.7755575615628914 times 10^(-17);
0.0;
0.2;
)
$
を、$bold(x)$ の残差として
$
mat(
0.0;
0.0;
0.0;
0.0;
)
$
を得た。
== 課題4
=== (4.1)
コードを以下に示す。
`newtonMethod_p` 関数が目的を達成する関数である。
#sourcefile(read("src/4-1.jl"), file:"src/4-1.jl")
=== (4.2)
要件に従い、プロットするために以下に示すコードを実装した。
#sourcefile(read("src/4-2.jl"), file:"src/4-2.jl")
実行すると、以下に示す図 1 が得られた。
#figure(
image("fig/fig1.svg"),
caption: [課題 (4.2) のプログラムの出力結果]
)
=== (4.3)
要件に従い、プロットするために以下に示すコードを実装した。
#sourcefile(read("src/4-3.jl"), file:"src/4-3.jl")
実行すると、以下に示す図 2 が得られた。
#figure(
image("fig/fig2.svg"),
caption: [課題 (4.3) のプログラムの出力結果]
)
== 課題5
コードを以下に示す。
#sourcefile(read("src/5.jl"), file:"src/5.jl")
=== (5.1)
`findClosestIndex` が近似解に最も近い真の解のインデックスを返す関数である。
`findClosestIndex(newtonMethod_p(2.0 + 2.0im), roots(Polynomial([-1, 0, 0, 1])))` を実行すると、出力として 3 が得られた。
=== (5.2)
$m = 300$ でプロットした結果を以下に示す。
#figure(
image("fig/fig3.png"),
caption: [$m = 300$ でプロットした結果]
)
|
|
https://github.com/toihr/array.typ | https://raw.githubusercontent.com/toihr/array.typ/main/lib.typ | typst | MIT License | #let transpose(arr) = {
let first_dim = arr.len()
let second_dim = arr.at(0).len()
let new_array = ()
for new_first in range(0,second_dim){
let inner_array = ()
for new_second in range(0,first_dim){
inner_array.push(arr.at(new_second).at(new_first))
}
new_array.push(inner_array)
}
return new_array
}
#let test = {
let a = ((1,2,3),(4,5,6),(7,8,9),(10,11,12))
let b_expected = ((1,4,7,10),(2,5,8,11),(3,6,9,12))
let b = transpose(a)
if b != b_expected{
panic("TestSuit: Transposes not equal")
}
}
#test
|
https://github.com/dark-flames/resume | https://raw.githubusercontent.com/dark-flames/resume/main/libs/version.typ | typst | MIT License | #import "@preview/shiroa:0.1.0": is-web-target, is-pdf-target
#let get-version(env) = {
env.at("x-version", default: "full")
}
#let multiVersion(env, ..v) = {
v.named().at(get-version(env,))
}
#let is-full(env) = {
get-version(env) == "full"
}
#let is-cv(env) = {
get-version(env) == "cv"
}
#let is-resume(env) = {
get-version(env) == "resume"
}
#let show-cv-content(env) = {
is-cv(env) or is-full(env)
}
#let show-resume-content(env) = {
is-resume(env) or is-full(env)
}
#let cv-content(env, content) = {
if show-cv-content(env) {
content
} else {
[]
}
}
#let resume-content(env, content) = {
if show-resume-content(env) {
content
} else {
[]
}
}
#let cv-and-others(env, cv-content, others-content) = {
if is-cv(env) {
cv-content
} else {
others-content
}
}
#let resume-and-others(env, resume-content, others-content) = {
if is-resume(env) {
resume-content
} else {
others-content
}
}
#let new-page(env) = {
if is-pdf-target() {
pagebreak()
} else {
[]
}
} |
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/paren_string.typ | typst | Apache License 2.0 |
#let font-any = /* range after 3..4 */ ("");
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tidy/0.1.0/README.md | markdown | Apache License 2.0 |
# Tidy
*Keep it tidy.*
**tidy** is a package that generates documentation directly in [Typst](https://typst.app/) for your Typst modules. It parses docstring comments similar to javadoc and co. and can be used to easily build a beautiful reference section for the parsed module.
Within the docstring you may use any Typst syntax - so markup, equations and even figures are no problem!
Features:
- **Customizable** output styles.
- Call your own module's code within the docstring, e.g., to **render examples**.
- **Annotate types** of parameters and return values.
- Automatically read off default values for named parameters.
The [guide][guide-link] describes the usage of this module and defines the format for the docstrings.
## Usage
Using `tidy` is as simple as writing some docstrings and calling:
```java
#import "@preview/tidy:0.1.0"
#{
let module = tidy.parse-module(read("my-module.typ"))
tidy.show-module(module, style: tidy.styles.default)
}
```
The available predefined styles are currenty `tidy.styles.default` and `tidy.styles.minimal`. Custom styles can be added (see the [guide][guide-link]).
Furthermore, it is possible to access user-defined functions and use images through the `scope` argument of `tidy.parse-module()`:
```java
#{
import "my-module.typ"
let module = tidy.parse-module(read("my-module.typ"))
let an-image = image("img1.png")
tidy.show-module(
module, style:
tidy.styles.default,
scope: (my-module: my-module, img1: an-image)
)
}
```
The docstrings in `my-module.typ` may now access the image with `#img1` and can call any function or variable from `my-module` in the style of `#my-module.my-function`. This makes rendering examples right in the docstrings as easy as a breeze!
## Example
A full example on how to use this module for your own package (maybe even consisting of multiple files) can be found at [examples](https://github.com/Mc-Zen/tidy/tree/main/examples).
```java
/// This function does something. It always returns true.
///
/// We can have *markdown* and
/// even $m^a t_h$ here. A list? No problem:
/// - Item one
/// - Item two
///
/// - param1 (string): This is param1.
/// - param2 (content, length): This is param2.
/// Yes, it really is.
/// - ..options (any): Optional options.
/// -> boolean, none
#let something(param1, param2: 3pt, ..options) = { return true }
```
**tidy** turns this into:
<h3 align="center">
<img alt="Tidy example output" src="https://github.com/Mc-Zen/tidy/assets/52877387/1aa5190b-d477-45fc-a679-5bfeb2725dc2" style="max-width: 100%; padding: 10px 10px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 4pt; box-sizing: border-box; background: white">
</h3>
[guide-link]: https://github.com/Mc-Zen/tidy/releases/download/v0.1.0/tidy-guide.pdf |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/args-underscore_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#test((1, 2, 3).map(_ => {}).len(), 3)
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/figures/07-proposed-solution/louvain-1.typ | typst | #import "@preview/cetz:0.2.2": canvas, draw
#v(2em)
#let vertex = (name, x, y, stroke: black) => {
draw.circle((x, y), radius: .35, stroke: stroke, name: name)
draw.content((x, y), eval(name, mode: "math"))
}
#let edge = (start, end, name, content: false, anchor: "north", padding: .5) => {
let (a, b) = (start, end)
draw.line((a, .35, b), (b, .35, a), name: name)
if (content) {
draw.content(
(name + ".start", 1, name + ".end"),
anchor: anchor,
padding: padding,
eval("w(" + name + ")", mode: "math"),
)
}
}
#canvas(length: 1cm, {
import draw: *
set-style(content: (padding: .2), stroke: black)
content((3.5, -7.5), "Original network")
vertex("v_0", 110/35, -50/35)
vertex("v_1", 75/35, -20/35)
vertex("v_2", 35/35, -50/35)
vertex("v_3", 180/35, -35/35)
vertex("v_4", 45/35, -95/35)
vertex("v_5", 100/35, -95/35)
vertex("v_6", 225/35, -110/35)
vertex("v_7", 210/35, -70/35)
vertex("v_8", 90/35, -130/35)
vertex("v_9", 125/35, -160/35)
vertex("v_10", 125/35, -200/35)
vertex("v_11", 185/35, -155/35)
vertex("v_12", 80/35, -215/35)
vertex("v_13", 185/35, -205/35)
vertex("v_14", 45/35, -190/35)
vertex("v_15", 50/35, -145/35)
edge("v_1", "v_2", "e_1")
edge("v_1", "v_4", "e_2")
edge("v_1", "v_7", "e_3")
edge("v_2", "v_0", "e_4")
edge("v_2", "v_6", "e_5")
edge("v_2", "v_5", "e_6")
edge("v_2", "v_4", "e_7")
edge("v_3", "v_0", "e_8")
edge("v_3", "v_7", "e_9")
edge("v_4", "v_0", "e_10")
edge("v_4", "v_10", "e_11")
edge("v_5", "v_0", "e_12")
edge("v_5", "v_7", "e_13")
edge("v_5", "v_11", "e_14")
edge("v_6", "v_7", "e_15")
edge("v_6", "v_11", "e_16")
edge("v_8", "v_9", "e_17")
edge("v_8", "v_10", "e_18")
edge("v_8", "v_11", "e_19")
edge("v_8", "v_15", "e_20")
edge("v_9", "v_12", "e_21")
edge("v_9", "v_14", "e_22")
edge("v_10", "v_11", "e_23")
edge("v_10", "v_12", "e_24")
edge("v_10", "v_13", "e_25")
edge("v_10", "v_14", "e_26")
edge("v_11", "v_13", "e_27")
})
#v(2em)
|
|
https://github.com/Amirhosein-GPR/university_notes | https://raw.githubusercontent.com/Amirhosein-GPR/university_notes/main/machine_learning.typ | typst | #import "assets/typst/templates/note.typ": note
#import "assets/typst/tools/tool.typ"
#let red_color = rgb(200, 0, 0, 255)
#let orange_color = rgb(220, 100, 0, 255)
#let yellow_color = rgb(130, 130, 0, 255)
#let green_color = rgb(0, 120, 0, 255)
#let blue_color = rgb(0, 100, 200, 255)
#let dark_blue_color = rgb(0, 0, 200, 255)
#let purple_color = rgb(150, 0, 150, 255)
#let gold_color = rgb(255, 215, 0)
#let brown_color = rgb(125, 50, 0)
#let dir = rtl
#show: doc => note(
doc,
paper: "a4",
black_and_white: false,
flipped: false,
first_page_font_size: 10pt,
font_size: 8pt,
image_path: "../../images/basu_logo_logosource.ir.svg",
image_width: 12em,
topic: "جزوه درس یادگیری ماشین",
authors_name: ("<NAME>"),
professors_name: ("<NAME>"),
faculty: "مهندسی کامپیوتر",
date: [
نیم سال تحصیلی #text(dir: ltr)[۱۴۰۳-۱]
],
version: "v0.6.0",
phase: none,
info_color: blue_color,
no_responsibility: true
)
#tool.introduce_sections()
#colbreak()
#tool.title("درباره کلاس", color: blue_color)
- قواعد و مقررات:
+ حضور در کلاس اجباری است.
+ انجام تمرین ها و پروژه ها در زمان مشخص شده.
+ باید برایشان گزارش نوشته شود.
+ کزارش شامل موارد زیر است:
+ تعریف مسأله
+ پیاده سازی
+ اجرای نمونه
+ میان ترم و پایان ترم کتبی خواهیم داشت.
- راه های ارتباطی:
- آیدی تلگرام: #text(dir: ltr)[mansoorm\@]
- کانال تلگرام: #text(dir: ltr)[mansoorm\_courses\@]
- ایمیل ها:
+ <EMAIL>
+ <EMAIL>
#tool.title("فهرست مطالب", color: red_color)
#outline(title: none, indent: auto)
#colbreak()
= جلسه اول
== یادگیری ماشین
#tool.double_section()[
#tool.simple_context()[
یادگیری ماشین زیر شاخه ای از هوش مصنوعی است.
]
][
#tool.tip()[
ملاک درست بودن پاسخ، دادن جواب مورد انتظار کاربر است.
]
]
=== هوش
#tool.double_section()[
#tool.definition()[
هوش: معیار اندازه گیری میزان انطباق پاسخ با انتظار
#v(2em)
]
][
#tool.example()[
دو عدد ادامه دنباله زیر را مشخص کنید.
#text(dir: ltr)[۱, ۲, ۵, ۷, ۱۰, ..., ...]
]
]
#tool.true_answer()[
در این مثال، معیار طراح سوال تعداد Ending point های هر عدد می باشد. بنابراین جواب به صورت زیر است:
#text(dir: ltr)[۱, ۲, ۵, ۷, ۱۰, #text(fill: blue_color)[۱۲], #text(fill: blue_color)[۱۷]]
]
=== هوش مصنوعی
#tool.definition()[
هوش مصنوعی: توانمندی کامپیوتر ها (ماشین ها) برای تولید پاسخ های مورد انتظار انسان.
]
#tool.double_section()[
#tool.tip()[
هوش مصنوعی از دید کاربر تعریف می شود.
]
][
#tool.definition()[
ماشین (کامپیوتر): به ابزاری که قابل برنامه ریزی است می گوییم.
]
]
=== رویکرد های هوش مصنوعی
==== مبتنی بر قانون (Rule based approach)
#tool.double_section()[
#tool.definition()[
در این روش مثلا از یک آدم متخصص در حوزه ای سوال می شود که چگونه کارش را انجام می دهد.
بر این اساس یک سری پارامتر استخراج می کنیم و بر اساس آن ها برنامه ای را می نویسیم.
]
][
#tool.example()[
تشخیص انواع چند ضلعی ها #sym.arrow.l این که چند ضلعی مورد نظر مثلث متساوی الساقین است یا مربع است یا پنج ضلعی منتظم است یا ۱۰۰ ضلعی منتظم است یا #sym.dots .
]
]
#tool.true_answer()[
روش تشخیص: به کمک اندازه زاویه ها و فاصله نقاط هر چند ضلعی، می توان نوع آن چند ضلعی را فهمید.
مشکل روش: وقتی تعداد اضلاع و زاویه ها بالا رود، مشکل می شود.
]
==== مبتنی بر یادگیری (Learning based approach)
#tool.double_section()[
#tool.definition()[
در این روش الگوریتمی به کامپیوتر داده می شود تا خودش قاعده و قانون مسأله را به دست آورد.
]
][
#tool.example()[
تشخیص هواپیما #sym.arrow.l تعداد زیادی نمونه می آوریم.
#v(1.55em)
]
]
#tool.true_answer()[
#tool.custom_figure(
image("images/ML/01_02.jpg"),
caption: "نقاط شکل هواپیما را به صورتی که مشخص شده است، شماره گذاری می کنیم."
)
کد مرتبط:
#tool.custom_figure(caption: "تشخیص هواپیما", kind: raw, inset: 1em)[
```
R = {}
for k = 1 to 16 {
for j = k + 1 to 16 {
flag = True
for image = 1 to 10 {
if d_k(image) != d_j(image) {
flag = false
}
}
if flag == true {
R = R U <d_k, d_j>
}
}
}
```
]
]
#tool.tip()[
یک مهندس یادگیری ماشین، دو مورد زیر را فراهم می کند:
+ نمونه ها (Examples)
+ الگوی قاعده (Rule template)
]
=== یادگیری (Training)
#tool.definition()[
یادگیری (Training): فعالیتی که دو ورودی نمونه و الگو و همچنین خروجی قواعد را دارد، گویند.
#tool.custom_figure(
align(center)[
#image("images/ML/01_01.png", width: 39%)
],
caption: "گراف مربوط به فعالیت یادگیری",
inset: 1em
)
]
= جلسه دوم
#tool.double_section()[
#tool.tip()[
کار هایی که مهندس یادگیری ماشین به همراه فرد خبره در حوزه مرتبطش انجام می دهند:
ML engineer + Domain expert:
#text(dir: ltr)[
+ Data collection
+ Template building
+ Training
]
]
][
#tool.tip()[
در Machine learning نقش اصلی را ML engineer بر عهده دارد.
در حالی که در Data mining و Deep learning نقش اصلی بر عهده ماشین است.
#v(4.8em)
]
]
#tool.definition()[
یادگیری ماشین: یعنی به کامپیوتر ها یاد بدهیم تا مسائل را حل کنند.
]
== مسائل پایه ای یادگیری ماشین
=== Supervised learning
==== Classification
#tool.question()[
Spam detection در ایمیل:
فرض کنیم می خواهیم ایمیل های اسپم را از غیر اسپم برای فردی یا سازمانی تشخیص دهیم.
]
#tool.true_answer()[
مراحل انجام این کار به صورت زیر است:
+ کلی ایمیل جمع می کنیم و آن ها را برچسب گذاری می کنیم.
مثلا به صورت زیر:
#tool.custom_figure(caption: "برچسب گذاری ایمیل ها", kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center,
"Message",
"Label: Spam",
"Message 1",
"Yes",
"Message 2",
"No",
"Message 3",
"Yes",
[#sym.dots],
[#sym.dots],
"Message N",
"No"
)
]
+ متن را بررسی می کنیم.
مثلا به صورت زیر:
#tool.custom_figure(caption: "بررسی لغت های درون ایمیل ها از نظر اسپم بودن یا نبودن", kind: table, inset: 1em)[
#table(
columns: 4,
inset: 1em,
stroke: black,
align: center,
"Word",
"F_Yes",
"F_No",
"Difference",
"Rich",
"56",
"73",
"56 - 73 = -17 < 0",
"Click",
"123",
"15",
"108",
[#sym.dots.v],
[#sym.dots.v],
[#sym.dots.v],
[#sym.dots.v]
)
]
در جدول بالا، ستون F_Yes به تعداد ایمیل های اسپمی که در متن آن ها کلمه Rich وجود دارد اشاره می کند و ستون F_No، عکس این قضیه می باشد.
در نهایت تمامی کلمات در قالب جدول بالا بررسی می شوند.
این عمل را بار اول خودمان انجام می دهیم.
توجه: اسپم بودن یا نبودن هر ایمیل مورد نظر است و نه هر کلمه هر ایمیل به صورت جداگانه.
توجه: هر لغتی که در متن یک ایمیل داشته باشیم، همان یک بار برای متنش حساب می شود و نه بیشتر.
مثلا یک ایمیلی ۱۰۰ عدد کلمه Click دارد.
در این حالت می گوییم کلمه Click در این ایمیل آمده است و به تعدادش اشاره نمی کنیم.
اما چرا اینگونه عمل کردیم؟ چون طبیعت، هموار (Smooth) است.
در ادامه ۱۰۰ کلمه ای (تعداد دلخواه) که بیشترین تفاضل را دارند، انتخاب کرده و برای یک ایمیلی که می خواهیم بررسی اش کنیم، می گوییم اگر درون این ایمیل، مثلاً بیشتر از ۲۰ کلمه مجزا از این ۱۰۰ کلمه وجود داشت، آن ایمیل، یک ایمیل اسپم است.
پس به صورت خلاصه به شکل زیر عمل می کنیم:
#text(dir: ltr)[
+ Collect a set of spam and real (not-spam) messages.
+ Count words in the message.
+ Select top #text(stylistic-set: 2)[100] distincitve (Highly frequent in spams) spam words
// For a new message or stage???
+ For a new message if M contains more than #text(stylistic-set: 2)[20] distincitve words, It is spam.
]
در نهایت برنامه ای به شکل زیر ساخته خواهد شد:
#tool.custom_figure(
image("images/ML/02_01.png"),
caption: "یک برنامه یادگیری ماشین که یک ورودی و دو خروجی به شکل بالا دارد.",
inset: 1em
)
به این نوع یادگیری ماشین، Classification می گوییم.
]
#tool.example()[
مثالی در حوزه Classification به صورت زیر آمده است:
ساخت یک برنامه یادگیری ماشین که Chest X-Ray را به عنوان ورودی بگیرد و بگوید ریه فرد، چقدر درگیر است.
خروجی برنامه نیز یکی از موارد زیر است:
#text(dir: ltr)[
+ None
+ Low
+ Mild
+ High
+ Severe
]
]
==== Regression
#tool.question()[
پیش بینی کردن قیمت خانه
]
#tool.true_answer()[
- گام اول: فرض کنیم قیمت خانه ها به شکل زیر است:
#tool.custom_figure(caption: "قیمت خانه ها بر اساس مساحت آن ها", kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center,
"Area",
"Price",
[50 $m^2$],
[100],
[75 $m^2$],
[105],
[75 $m^2$],
[150],
[100 $m^2$],
[220],
[120 $m^2$],
[240]
)
]
برای آن که درک بهتری از جدول بالا داشته باشیم به شکل زیر توجه کنید:
#tool.custom_figure(
image("images/ML/02_02.png", width: 70%),
caption: "تلاش می کنیم معادله ای که تا جای ممکن تمامی نقاط نمودار را پوشش می دهد، پیدا کنیم.",
inset: 1em
)
بر اساس اصل پیوسته بودن طبیعت مشاهده می کنیم که نقاط شکل بالا گویی حول محور آبی حرکت می کنند.
- گام دوم:
معادله خط مربوط به خط آبی رنگ را پیدا می کنیم.
مثلا:
$ "Price = 2" "Area" + epsilon $
به این گونه مسائل که به دنبال یافتن معادله ای همچون
$ y = f(x) $
برای حل شان می گردیم؛ مسائل Regression می گویند.
]
#tool.list()[
مسائل پایه ای یادگیری ماشین:
#text(dir: ltr)[
+ Supervised learning
+ Classification
+ Regression
+ Unsupervised learning
+ Association learning
+ Clustering
+ Distribution learning (Density estimation)
+ Reinforcement learning
+ Reward / Punishment
]
]
=== Unsupervised learning
==== Association learning
#tool.question()[
فروشنده یک مغازه می خواهد به مشتری ای که مثلاً ۴ کالا خریده است، کالای پنجمی را پیشنهاد داده و آن را بفروشد.
چگونه به او پیشنهاد بدهد؟
]
#tool.true_answer()[
+ داده های گذشته رو بررسی می کنیم.
مثلا:
#tool.custom_figure(caption: "کالا های خریده شده توسط مشتری ها", kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center,
"مشتری ۱",
"پنیر - [شیر] - [نان]",
"مشتری ۲",
"<رب> - تخم مرغ - <نان>",
"مشتری ۳",
"[شیر] - رب> - [<نان>]>",
[#sym.dots.v],
[#sym.dots.v],
"مشتری N",
[#sym.dots]
)
]
+ کالا های با بیشترین تکرار را پیدا می کنیم.
مثلا:
$ F_1 = "رب - شیر - نان" $
+ کد الگوریتم را به صورت زیر می نویسیم (برای آموزش یا همان Training)):
#tool.custom_figure(caption: "آموزش مدل برای یافتن کالا های با بیشترین تکرار", kind: raw, inset: 1em)[
```
F_1 = {} F_2 = {}
for each x in F_1 {
for each y in F_1 {
if <x, y> is frequent {
F_2 = F_2 U {<x, y>}
}
}
}
```
]
+ در آخر برنامه پیشنهاد کالا را با استفاده از داده هایی که در مرحله قبل به دست آوردیم به صورت زیر می نویسیم و اجرا می کنیم:
#tool.custom_figure(caption: "برنامه پیشنهاد کالا که از مدل آموزش داده شده، استفاده می کند.", kind: raw, inset: 1em)[
```
for each customer c {
for each pair <x, y> in F_2 {
if c buys x {
recommend y
}
}
}
```
]
این مسأله نوعی مسأله در حوزه Association learning می باشد.
]
==== Clustering
#tool.question()[
در ادامه مسأله قبلی، حالا می خواهیم بدانیم که چگونه مشتری هایی داریم؟ (Grouping customers)
]
#tool.true_answer()[
بر اساس سبد خرید مشتری ها، آن ها را دسته بندی می کنیم.
+ به صورت زیر سبد ها را دو به دو مقایسه کرده و دسته بندی می کنیم.
داریم:
$ B_1 , B_2 $
به کمک فرمول زیر، شباهت بین دو سبد $B_1$ و $B_2$ را به دست می آوریم (علامت قدر مطلق به اندازه مجموعه ها اشاره می کند):
$ S = abs(B_1 sect B_2) / abs(B_1 union B_2) $
برای نمونه بین مشتری ۱ و مشتری ۲ داریم:
$ S = abs("نان") / abs("رب - تخم مرغ - پنیر - شیر - نان") = ۱ / ۵ $
#text(number-width: "proportional")[یعنی سبد خرید مشتری ۱ و مشتری ۲ به میزان ۲۰٪ به یکدیگر شباهت دارند.]
+ به تعداد دلخواه مثلاً ۵ عدد گروه در نظر می گیریم و به صورت زیر عمل می کنیم:
+ #text(number-width: "proportional")[فرض کنید ۱۰۰ تا مشتری داریم.
این مشتری ها را به شکل تصادفی در ۵ گروه ۲۰ تایی تقسیم بندی می کنیم.]
+ سپس یکی از مشتری ها را از یک گروهی انتخاب کرده و با همه گروه ها مقایسه می کنیم.
در نهایت مشتری به گروهی که بیشترین شباهت را با آن دارد، منتقل می شود.
+ #text(number-width: "proportional")[اگر این کار را بر روی مشتری ها ادامه دهیم بعد از مدتی به همگرایی خواهیم رسید و ۵ گروه ۲۰ تایی خواهیم داشت که اعضای درون هر گروه به یکدیگر شباهت دارند.]
اما این دسته بندی چه فایده ای دارد؟
یک نمونه مثال از فایده آن این است که مشتری هایی که در گروه مشترک هستند را بررسی می کنیم چه کالا هایی را خریدند تا آن کالا ها را در یک راهرو کنار هم قرار دهیم.
این مسئله نمونه ای از مسائل Clustering می باشد.
]
=== Reinforcement learning
==== Reward / Punishment
#tool.question()[
می خواهیم نحوه بازی کردن شطرنج را آموزش دهیم.
]
#tool.true_answer()[
فرض کنیم دو بازیکن به نام های بازیکن ۱ و ۲ داریم.
بازیکن ۲ می خواهد شطرنج را به بازیکن ۱ یاد بدهد.
+ #text(number-width: "proportional")[ابتدا حرکاتی که هر مهره می تواند انجام دهد به بازیکن ۱ گفته می شود.]
+ بازیکن ها شروع به بازی کردن می کنند.
+ #text(number-width: "proportional")[به صورت زیر هر دو بازیکن حرکاتی را انجام می دهند و در نهایت بازیکن ۲ می برد.]
#tool.custom_figure(caption: "حرکت های بازیکن های ۱ و ۲", kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center,
"بازیکن ۱",
"بازیکن ۲",
[$W_1$],
[$B_1$],
[$W_2$],
[$B_2$],
[#sym.dots.v],
[#sym.dots.v],
[$W_7$],
[$B_7$]
)
]
+ #text(number-width: "proportional")[وقتی که بازیکن ۱ می بازد، می فهمد مجموعه حرکاتی که انجام داده، بد بوده است و بابت باخت مجازات می شود.]
+ #text(number-width: "proportional")[بازیکن ۱ اینقدر حرکات شانسی مختلف را امتحان می کند تا می برد و بابت برد امتیاز می گیرد.]
به این صورت بازیکن ۱ بازی شطرنج را یاد می گیرد.
به این روش که ماشین می تواند از شکست ها (جریمه ها) و برد ها (جایزه ها) یاد بگیرد روش Reward / Punishment می گویند که زیر مجموعه ای از Reinforcement learning می باشد.
]
= جلسه سوم
== مسائل پایه ای یادگیری ماشین (ادامه)
=== Unsupervised learning
==== Distribution learning (Density estimation)
#tool.question()[
یک فرد سیگاری داریم. این فرد چند سال دارد؟
]
#tool.true_answer()[
داده ها را جمع آوری کرده و معمولاً به صورت فراوانی نسبی نشان شان می دهیم.
از تعداد جمعیت ۱۰۰ نفر، سن شان پرسیده می شود و به جدول زیر می رسیم.
#tool.custom_figure(caption: "فراوانی سیگاری بودن افراد در سنین مختلف", kind: table, inset: 1em)[
#table(
columns: 3,
inset: 1em,
stroke: black,
align: center,
"سن\n(Age)",
"فراوانی\n(Frequency)",
"فراوانی نسبی\n(Relative frequency)",
"1",
"0",
"0",
"5",
"0",
"0",
"10",
"5",
"0.05",
"15",
"15",
"0.15",
"20",
"16",
"0.16",
"25",
"16",
"0.16",
"30",
"16",
"0.16",
"50",
"15",
"0.15",
"60",
"10",
"0.10",
"80",
"5",
"0.05",
"90",
"2",
"0.02",
"100",
"0",
"0",
"---",
"مجموع",
"---",
"---",
"100",
"---",
)
]
حالا می خواهیم به این برسیم که مثلاً احتمال اینکه یک آدم ۴۰ ساله سیگاری باشد چقدر است.
یعنی:
$ P("Smoking" | "Age" = 40) = space ? $
راه حل این است که می آییم می بینیم که ۳۰ ساله ها احتمال ۰/۱۶ و ۵۰ ساله ها احتمال ۰/۱۵ را دارند.
از آن جایی که سن ۴۰ سال بین این دو احتمال است، میانگین شان را برای آن در نظر می گیریم.
یعنی:
$ P("Smoking" | "Age" = 40) = 0.155 $
پس اگر Data ما به صورت زیر باشد:
$ X = {x_1, x_2, dots, x_n} $
آنگاه به
$ P(x in X) $
می گویند Distribution و به پیدا کردنش می گویند Distribution learning.
به عبارت دیگر Distribution learning یعنی اینکه توزیع داده ها را به دست آوریم.
$ P(x in X): "Distribution learning" $
اما گاهی مقادیری که یک متغیر می تواند اختیار کند، خیلی زیاد است یا بی نهایت است.
در اینگونه موارد، معمولاً در آمار به جای کاری که کردیم، برای Distribution از Probability density function استفاده می کنیم که به صورت خلاصه به آن PDF می گویند:
$ P("Smoking" | x) = cases(0 &"if" space.quad x < 10 &|space space| space.quad x > 90, 0.01 x &"if" space.quad x >= 10 & amp space.quad x < 20, 0.16 &"if" space.quad x >= 20 & amp space.quad x < 50, 0.16 - 0.01 x space.quad &"if" space.quad x >= 50 space.quad & amp space.quad x < 90) $
به این ترتیب هدف ما در Distribution learning، پیدا کردن یک تابع توزیع است.
]
#tool.question()[
همان سؤال قبلی با فرض این که داده ها توزیع نرمال داشته باشند.
یعنی سن افراد سیگاری به صورت نرمال توزیع شده باشد.
]
#tool.true_answer()[
در اصل ML engineer از سوادش به این موضوع پی می برد که داده ها نرمال هستند.
مثلاً مشاهده می کند که ۵ فرد سیگاری ۱۰ ساله داریم و بعدش ۱۵ فرد سیگاری ۱۵ ساله داریم و به همین ترتیب متوجه می شود که داده ها شکلی نرمال دارند.
با ضرب نظیر به نظیر هر عضو ستون سن در ستون فراوانی، و سپس تقسیم کردن حاصل آن بر تعداد جمعیت که ۱۰۰ می باشد به میانگین زیر می رسیم:
$ mu = "Average" = 34 $
و احتمالاً دارای انحراف معیار زیر می باشد:
$ "Standard deviation" = 5 $
و بر این اساس به نمودار زیر می رسیم:
#tool.custom_figure(
image("images/ML/03_01.png", width: 56%),
caption: "با توجه به میانگین و انحراف معیار جمعیت، به نمودار بالا می رسیم.",
inset: 1em
)
]
#tool.tip()[
تفاوت روش Regression با Distribution learning: در Regression لزوماً متغیر خروجی مان یک متغیر احتمالاتی نیست.
این دو روش از هم خیلی دور نیستند ولی به هر صورت تفاوت دارند.
]
== Classification
#tool.question()[
می خواهیم یک ماشین مناسب خانواده بخریم (Family car detection).
چه ماشینی مناسب خانواده است؟
]
#tool.true_answer()[
دو نقش برای حل این مسأله داریم:
+ ML engineer: برنامه ای می سازد که بتواند ماشین مناسب برای خانواده را با توجه به قدرت موتور و قیمت آن، تشخیص دهد.
+ Domain expert: می گوید چه ماشینی مناسب خانواده است.
با گفتن قدرت موتور و قیمت ماشین به او، به ما جواب خواهد داد.
ML engineer داده های قدرت و قیمت ماشین ها را به Domain expert می دهد و از او سؤال می کند آیا با توجه به مقدار آن ها، ماشین مربوطه مناسب است یا خیر؟
در جدول زیر اطلاعات ماشین ها و پاسخ او آمده است:
#tool.custom_figure(caption: "مناسب بودن یا نبودن ماشین برای خانواده با توجه به قدرت موتور و قیمت ماشین", kind: table, inset: 1em)[
#table(
columns: 3,
inset: 1em,
stroke: black,
align: center,
[Engine power ($X_1$)],
[Price ($X_2$)],
[Family car ($Y$)],
"10",
"1k",
"No",
"20",
"1.2k",
"No",
"45",
"5k",
"Yes",
"60",
"10k",
"Yes",
"120",
"15k",
"Yes",
"140",
"30k",
"No",
"30",
"100k",
"No",
"20",
"200k",
"No"
)
]
در ادامه مراحل زیر را انجام می دهیم:
+ Plot data:
از آن جایی که انسان با دیدن نمودار داده ها درک بهتری از آن ها پیدا می کند، تا دیدن جدول، نمودار جدول بالا را رسم می کنیم.
#tool.custom_figure(
image("images/ML/03_02.png"),
caption: "نمودار جدول بالا. دایره های منفی بیانگر ماشین های نامناسب و دایره های مثبت بیانگر ماشین های مناسب خانواده می باشند.",
inset: 1em
)
+ Get an insight:
#tool.custom_figure(
image("images/ML/03_03.png"),
caption: "با کمی نگاه به نموداری که رسم کردیم، به این دیدگاه می رسیم که ماشین های مناسب خانواده درون محدوده قرمز رنگ قرار می گیرند. گویی که توسط یک مستطیل (که با طول و عرض و مختصات نقطه پایین سمت چپش مشخص می شود) احاطه شده اند.",
inset: 1em
)
ما به عنوان ML engineer تصمیم می گیریم که محدوده ماشین های مناسب خانواده در نمودار بالا را به کمک شکلی نمایش دهیم.
برای مثال به کمک یک مستطیل موازی محور های مختصات این محدوده را مشخص می کنیم.
یکی از دلایل انتخاب مستطیل به جای مثلاً بیضی، ساده بودن رسم و تعریف آن است.
+ Make hypothesis and select a model:
مهم ترین گام ما این گام است که در آن باید یک فرضیه خوب بسازیم.
برای این مسأله فرضیه ما این است: ماشین های مناسب خانواده درون یک مستطیل موازی محور های مختصات هستند.
در این جا مستطیلی که تعریف کردیم، همان Model برنامه ما می باشد که دارای ۴ پارامتر است و به صورت زیر تعریف می شود:
#align(center)[
#text(dir: ltr)[
Model\<Left, Bottom, Width, Height\>
]
]
+ Train the model:
یعنی یافتن بهترین مقادیر برای پارامتر های مدل.
در این مرحله باید مدل خود را آموزش دهیم.
از آنجایی که مدل پیشنهادی ما یک مستطیل است، برای آن که برنامه ما بتواند مشخصات این مستطیل را یاد بگیرد الگوریتم زیر را می نویسیم (الگوریتم Training):
#tool.custom_figure(caption: "الگوریتم Training مدل.", kind: raw, inset: 1em)[
```
// X is the data items consisting from only the first 2 columns of the former table (An N x 2 matrix)
// Y is the data items consisting from only the last column of the former table (An N x 1 matrix)
// N is the number of table rows (Here N = 8)
Input: X, Y, N
left = Infinity, bottom = Infinity
width = -Infinity, height = -Infinity
for k = 1 to N {
// Poisitive example
if Y[k] = True {
if X[k, 1] < left {
left = X[k, 1]
}
if X[k, 2] < bottom {
bottom = X[k, 2]
}
if X[k, 1] - left > width {
width = X[k, 1] - left
}
if X[k, 2] - bottom > height {
height = X[k, 2] - bottom
}
}
}
```
]
پس از اجرای الگوریتم و آموزش دادن برنامه، باید برنامه را تست کنیم.
برای مثال اگر ماشینی با مشخصات زیر به برنامه بدهیم:
#align(center)[
#text(stylistic-set: 2)[Engine power: 50, Price: 12k]
]
برنامه به ما جواب
Yes
می دهد چون داخل مستطیل می افتد.
فرآیندی که توضیح دادیم فرآیند Prediction می باشد.
الگوریتم Prediction برای این مسأله به صورت زیر می باشد (Class label prediction):
#tool.custom_figure(caption: "الگوریتم Prediction بر اساس مدل آموزش داده شده.", kind: raw, inset: 1em)[
```
// e ---> Engine power
// p ---> Price
// M ---> Model
// M[1] ---> Left, M[2] ---> Bottom
// M[3] ---> Width, M[4] ---> Height
function Prediction(e, p, M) {
if e >= M[1] and
e <= M[1] + M[3] and
p >= M[2] and
p <= M[2] + M[4] {
return "Yes"
} else {
return "No"
}
}
```
]
#tool.list()[
عبارت های مهم در این درس:
- Classification
- Plot: رسم کردن
- Insight: بینش
- Hypothesis: فرضیه
- Model
- Parameter
- Train
- Algorithm
- Feature: در این جا همان ستون های مربوط به X می باشد.
- Training set: در این جا همان مجموعه داده های X و Y می باشد.
- Prediction (Recognition)
- Inductive bias: هر دانسته ای غیر از اطلاعاتی که صورت مسأله داده و آن را به مسأله اضافه می کنیم، می گویند.
مثلاً اینکه مدل مان مستطیل باشد یا بیضی، یک Inductive bias است.
]
]
= جلسه چهارم
== Smoothness
#tool.simple_context()[
هدف در یادگیری ماشین (با کمی سهل گیری، هوش مصنوعی) این هست که دنیا را یک موجودیت پیوسته ببینیم، مدلش کنیم و این مدل را برای پیش بینی داده هایی که نداریم، استفاده کنیم.
در دنیا موجودات مشابه هم، کنار هم هستند.
]
#tool.example()[
Object زیر را داریم:
$ "Object" cases("Attribute 1", "Attribute 2", "Attribute 3", dots.v, "Attribute N") $
]
#tool.double_section()[
#tool.question()[
دو Object ای که از یک جنس یا جمعیت هستند، انتظار داریم Attribute هاشون مشابه باشد یا نه؟
]
][
#tool.true_answer()[
انتظار داریم مشابه باشند.
#v(3.2em)
]
]
#tool.double_section()[
#tool.tip()[
کل صحبتی که در یادگیری ماشین (با کمی سهل گیری، هوش مصنوعی) می شود، بر مبنای فرض Continuity یا Smoothness می باشد.
#v(1.6em)
]
][
#tool.example()[
انتظار نداریم دیروز که هوا آفتابی بوده و امروز هم آفتابی هست فردا ناگهانی برفی بشود.
حالت طبیعی این است که به تدریج هوا ابری شود و باد های سرد بوزد و به مرور هوا برفی شود.
]
]
#tool.reminder()[
در مثال خرید ماشین خانواده، وقتی داده های مرتبطش را بر روی نمودار رسم کردیم، حدس زدیم که مستطیلی را می توان پیدا کرد که درون آن ماشین های مناسب خانواده قرار می گیرند. به این مستطیل، مدل می گویند. که به شکل زیر تعریف می شود:
#align(center)[
#text(dir: ltr)[
Model\<Axis aligned rectangle\> = Model\<Left, Bottom, Width, Height\>
]
]
#tool.custom_figure(
image("images/ML/04_01.png"),
caption: "مثال خرید ماشین مناسب خانواده در جلسه سوم",
inset: 1em
)
بعد از انتخاب مدل، باید پارامتر های آن آموزش داده شوند که به کمک ابزار یادگیری انجام می شود.
#tool.custom_figure(
image("images/ML/04_02.png"),
caption: "ابزار Learning که دو ورودی و یک خروجی به شکل بالا دارد.",
inset: 1em
)
در مدل آموزش داده شده، پارامتر های آن مقدار دهی شده اند.
]
== مفهوم مخفی و فرضیه سازگار
#tool.example()[
فرض کنیم در مثال ماشین خانواده، ماشین های مناسب واقعا توسط یک مستطیل مشخص می شوند (مستطیل بزرگتر شکل زیر).
#tool.custom_figure(
image("images/ML/04_03.png", width: 76%),
caption: "مستطیل بزرگتر چیزی است که واقعا وجود دارد و مستطیل کوچک تر مدلی است که از یادگیری از روی مثال های داده شده به دست آمده است.",
inset: 1em
)
فرض کنیم شروع به تست کردن برنامه می کنیم و پاسخ آن این است که ماشین مناسب خانواده نیست، در صورتی که در واقع مناسب است.
]
#tool.double_section()[
#tool.definition()[
Latent concept: به مستطیلی که (در مثال بالا مستطیل است) واقعا وجود دارد و اغلب از آن خبر نداریم، می گویند و آن را با C نمایش می دهیم.
]
][
#tool.definition()[
Consistent hypothesis: چیزی که مدل یاد گرفت، که با نمونه های مثبت مان سازگار است، می گویند.
#v(1.6em)
]
]
== بررسی یک الگو
#tool.example(pause: true)[
فرض کنیم مساحت مستطیل کوچک $S_2$ و مساحت مستطیل بزرگ $S_1$ باشد.
همچنین فرض کنیم:
$ S_1 = 1 $
در نتیجه:
$ S_2 < S_1 $
حال فرض کنیم یک نفر یک ماشین خانواده مناسب (نمونه مثبت) پیدا کرده و به ما می دهد (یعنی از کل C انتخاب کرده است).
]
#tool.double_section()[
#tool.question()[
احتمال این که از $S_2$ انتخاب کند چقدر است؟
]
][
#tool.true_answer()[
$S_2$
#v(1.7em)
]
]
#tool.double_section()[
#tool.question()[
احتمال این که بیرون از $S_2$ انتخاب کند چقدر است؟
]
][
#tool.true_answer()[
$S_1 - S_2$
#v(1.7em)
]
]
#tool.example(continuation: true, pause: true)[
اگر اسم نمونه مورد نظر را $x$ بگذاریم آن گاه:
$ p(x in S_2) = S_2 $
$ p(x in.not S_2) = S_1 - S_2 $
پس احتمالی وجود دارد که نمونه جدید به بهتر شدن فرضیه ما کمک می کند.
این اتفاق زمانی می افتد که نمونه جدید در ناحیه درون $S_1$ و بیرون از $S_2$ باشد.
احتمال اینکه همه N عدد نمونه ما درون $S_2$ باشند به صورت زیر است:
$ (S_2)^N $
به این ترتیب احتمال اینکه نمونه اول ما درون $S_2$ باشد، به صورت زیر است:
$ S_2 $
فرض کنیم $S_2$ نصف $S_1$ است.
به این ترتیب احتمال این که اولین نمونه داخل $S_2$ باشد، ۵۰٪ درصد است.
به نمونه هایی که می گیریم می گویند:
// در این درس فرض ما این است که نمونه هایمان به صورت زیر است:
#align(center)[
#text(dir: ltr)[
Independently and Identically Distributed (IID)
]
]
]
#tool.definition()[
IID Sample: نمونه هایی که مستقل از هم اند و توزیع یکسانی دارند (احتمال یکسانی دارند).
یعنی اگر مثلا ترتیب نمونه ها را عوض کنیم، چیزی عوض نمی شود.
]
#tool.double_section()[
#tool.example()[
از یک بشکه آب برداریم آبش کم می شود اما از یک چشمه آب برداریم گویی آبی کم نمیشه.
در این جا چشمه IID است ولی بشکه IID نیست.
#v(4.8em)
]
][
#tool.example()[
تعدادی توپ با رنگ های مختلف داریم.
وقتی توپ ها را بر می داریم و رنگشان را نگاه می کنیم.
اگر:
+ توپ ها را سر جایشان برگردانیم: نمونه ها IID هستند.
+ توپ را نگه داریم (IID): نمونه ها IID نیستند.
]
]
#tool.example(continuation: true)[
فرض کنیم $S_2 = 0.5$ و همه نمونه ها IID هستند.
احتمال این که نمونه اول داخل $S_2$ باشد و کمکی به یادگیری و بهبود Hypothesis ما نکند، برابر زیر است:
$ (0.5) $
نمونه دوم:
$ (0.5)(0.5) $
نمونه سوم:
$ (0.5)(0.5)(0.5) $
نمونه N ام:
$ (0.5)^N $
اگر بخواهیم احتمال بد شانسی ما کمتر از ۰/۰۱ باشد، (یعنی به احتمال ۰/۹۹ خوش شانس باشیم):
$ P_"بد شانسی" = (0.5)^N <= 0.01 $
$ (0.5)^N <= 0.01 arrow N log 0.5 <= log 0.01 arrow N >= (log 0.01) / (log 0.5) arrow N >= 6.7 tilde.eq 7 $
یعنی به ۷ نمونه نیاز داریم تا به احتمال ۰/۹۹ خوش شانس باشیم (مدل مان چیز جدید یاد بگیرد).
در ادامه احتمال های بد شانسی مختلف به همراه تعداد نمونه لازم برای رسیدن به آن ها، آورده شده است:
#tool.custom_figure(caption: [رابطه بین احتمال بد شانسی $S_2$ و تعداد نمونه ها], kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center + horizon,
[$S_2$ (بد شانسی)],
"Samples\ncount",
"0.01",
"1",
"0.1",
"2",
"0.5",
"7",
"0.9",
"43",
"0.99",
"458"
)
]
با دقت به جدول بالا به این نتیجه می رسیم که $S_2$ زمانی کوچکتر است که تعداد نمونه ها کم تر است.
]
#tool.tip()[
هر چقدر در فرآیند آموزش از نمونه های جدید بیش تری استفاده می کنیم، از خوش شانسی به سمت بد شانسی می رویم.
یعنی مثلاً اگر احتمال بد شانسی ما ۰/۹۹ است، با توجه به جدول قبلی، حداقل باید ۴۵۸ نمونه اضافه کنیم تا مدل مان بهتر شود.
به عبارت دیگر یادگیری در ابتدا خیلی سریع است و به مرور کند تر می شود.
#tool.custom_figure(
image("images/ML/04_04.png", width: 77%),
caption: "اغلب نمودار های یادگیری به صورت بالا هستند. افت خطا در ابتدای آموزش که تعداد کمی نمونه دریافت می شود، زیاد است. اما از جایی به بعد نمونه های جدید خیلی کمکی نمی کنند.",
inset: 1em
)
]
#tool.tip()[
یادگیری ماشین را نمی توان بدون استفاده از نمونه انجام داد.
]
#tool.tip()[
حجم نمونه آموزشی برای یادگیری مناسب، مهم است. نیاز است تعداد نمونه آموزشی مان از حداقل خاصی بیشتر باشد تا بتوان با کیفیت مد نظرمان یادگیری انجام شود.
]
== خطا و انواع آن
#tool.example()[
فرض کنید Concept واقعی به صورت زیر است اما الگوریتم یادگیری به جای آن که از نمونه های مثبت یاد بگیرد از نمونه های منفی یاد بگیرد.
#tool.custom_figure(
image("images/ML/04_05.png", width: 75%),
caption: "در شکل بالا، مدل ما به صورت مستطیل چسبیده به نمونه های منفی تعریف می شود.",
inset: 1em
)
تفاوتی که مدل بالا با مدل قبلی دارد، به جز اینکه از نمونه های منفی برای آموزش استفاده می کند، این است که h ما به صورت کامل درون C قرار ندارد.
ابتدا خطایی برای h تعریف می کنیم.
]
#tool.definition()[
خطا: تعداد تشخیص های غلط برای نمونه های تستی مدل.
انواع خطا ها شامل موارد زیر است:
+ خطای مطلق (Absolute error):
این خطا در ریاضی کاربرد دارد و شامل مجموع همه خطا های موجود بر روی کل دامنه است.
+ خطای تجربی (Emprical error): تعداد خطا در مجموعه نمونه های کوچک و محدودی که داریم.
شکل ریاضی این خطا به صورت زیر است:
$ x, y: "Testing set" $
$ E(h, x) = sum_(k = 1)^(abs(x)) 1(h(x^(<k>)) eq.not y^(<k>)) $
در عبارت بالا $y$ برچسب تک تک $x$ ها است.
مثلاً به صورت زیر:
#tool.custom_figure(caption: "برچسب مرتبط با هر نمونه (هر نمونه فقط یک ویژگی x را دارد).", kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center + horizon,
[$x$],
[$y$],
[$x^(<1>)$],
"Yes",
[$x^(<2>)$],
"No",
[#sym.dots.v],
[#sym.dots.v],
)
]
همچنین $h(x^(<k>)) eq.not y^(<k>)$ به معنای این است که Label ای که Hypothesis ما به $k$ امین نمونه آزمایش داده است، با Label واقعی مان متفاوت باشد.
+ خطای تجربی میانگین (Average emprical error):
خطای تجربی تقسیم بر اندازه نمونه.
این خطا برای مقایسه مدل ها به کار می رود چرا که مستقل از مجموعه Emprical شان است (بر خلاف Emprical error که قابل مقایسه نیست).
شکل ریاضی این خطا به صورت زیر است:
$ E_"Average" = 1 / (abs(x) + 1) sum_(k=1)^abs(x) 1(h(x^(<k>)) eq.not y^(<k>)) $
]
== انواع پاسخ های برنامه
#tool.definition()[
انواع پاسخ هایی که برنامه ما می تواند تولید کند شامل موارد زیر است:
+ True Poisitive (TP)
+ True Negative (TN)
+ False Poisitive (FP)
+ False Negative / False Reject (FN / FR)
که به صورت شهودی در شکل زیر آمده است:
#tool.custom_figure(
image("images/ML/04_06.png", width: 71%),
caption: "انواع پاسخ های برنامه ما",
inset: 1em
)
]
== قاعده Maximum Entropy
#tool.tip()[
تا اینجا دو مدل یاد گرفتیم.
یک مدل بر پایه داده های مثبت به دست می آمد و مدل دیگر بر پایه داده های منفی.
قاعده Maximum Entropy به ما می گوید مستطیلی (مدل ما در اینجا) را پیدا کنیم که دقیقا وسط دو مستطیل دیگر (دو مدل دیگر) باشد.
#tool.custom_figure(
image("images/ML/04_07.png"),
caption: "مستطیل کوچک مدلی است که از نمونه داده های مثبت و مستطیل بزرگ مدلی است که از نمونه داده های منفی به دست آوردیم. مستطیلی که از قاعده Maximum Entropy به دست می آید، همان مستطیلی است که دقیقا وسط دو مستطیل دیگر قرار دارد.",
inset: 1em
)
این قاعده در همه جا ما را به نتایج خوبی می رساند.
]
#tool.example()[
فرض کنید یک مسأله ای به شکل زیر داریم. چه چیزی نمونه های مثبت و منفی را از هم جدا می کند؟ بی نهایت خط.
اما طبق قاعده Maximum Entropy مرز وسط به دست می آید.
#tool.custom_figure(
image("images/ML/04_08.png", width: 67%),
caption: "مرز بین دو گروه به وسیله خط وسطی مشخص شده است که از قاعده Maximum Entropy به دست می آید.",
inset: 1em
)
]
#tool.tip()[
یک Classifier محدود به یک Model نیست.
]
== VC-Dimension
#tool.double_section()[
#tool.question()[
فرض کنید کلاً یک نمونه مثبت داریم.
با چه چیزی جداسازی را انجام می دهیم؟
]
][
#tool.true_answer()[
هیچ چیز.
چون همه چیز مثبت است.
#v(1.6em)
]
]
#tool.double_section()[
#tool.question()[
فرض کنید کلاً ۲ نمونه مثبت داریم.
با چه چیزی جداسازی را انجام می دهیم؟
]
][
#tool.true_answer()[
هیچ چیز.
چون همه چیز مثبت است.
#v(1.6em)
]
]
#tool.double_section()[
#tool.question()[
فرض کنید کلاً ۲ نمونه داریم که یکی مثبت و دیگری منفی است.
با چه چیزی جداسازی را انجام می دهیم؟
]
][
#tool.true_answer()[
با چیز های زیادی از جمله مستطیل، دایره، مثلث و ... اما ساده ترین شکل ممکن برای آن، خط است.
]
]
#tool.double_section()[
#tool.tip()[
اولین قاعده در یادگیری ماشین این است که مسأله ای که می خواهیم حل کنیم با ساده ترین مدل ممکن حل کنیم.
]
][
#tool.question()[
فرض کنید کلاً ۳ نمونه داریم که یکی مثبت و دو مورد دیگر منفی است (و یا بر عکس).
با چه چیزی جداسازی را انجام می دهیم؟
]
]
#tool.true_answer()[
با یک خط می توان جدا سازی را انجام داد.
]
#tool.double_section()[
#tool.question()[
فرض کنید کلاً ۴ نمونه داریم که غیر واقع بر یک خط راست هستند که دو مورد آن ها مثبت و دو مورد دیگر منفی هستند (و یا بر عکس).
با چه چیزی جداسازی را انجام می دهیم؟
]
][
#tool.true_answer()[
نمی توان ۴ نقطه ای را پیدا کرد که یک خط بتواند همه جور برچسب زنی هایش را جدا کند.
#v(3.2em)
]
]
#tool.double_section()[
#tool.definition()[
VC-Dimension یک Model: حداکثر تعداد نمونه هایی که مدل همه نوع برچسب گذاری آن ها را به درستی تفکیک می کند.
]
][
#tool.example()[
VC-Dimension یک خط برابر است با ۳.
چرا که اگر بیش از ۳ نقطه داشته باشیم احتمال این که خط اشتباه کند وجود دارد.
]
]
#tool.double_section()[
#tool.example()[
VC-Dimension دو خط برابر است با ۵.
چرا که اگر بیش از ۵ نقطه داشته باشیم احتمال این که دو خط اشتباه کنند وجود دارد.
]
][
#tool.tip()[
در یادگیری ماشین خطا اجتناب ناپذیر است.
#v(3.2em)
]
]
#tool.double_section()[
#tool.question()[
مثال هایی وجود دارند که با وجود این که ۱۰۰۰ نمونه داریم به راحتی از یک خط استفاده می کنیم. چرا؟
#v(1.6em)
]
][
#tool.true_answer()[
بنا به اصل پیوستگی انتظار چینش های عجیب و غریب نداریم و جاهایی که خط نمی تواند جدا کند حالت های بسیار خاص و بسیار نادر هستند.
]
]
#tool.tip()[
تعداد نمونه های آموزشی مورد نیاز برای این که مدل خوب یاد بگیرد به لگاریتم خطا ربط دارد:
$ N space alpha space log ("error") $
$N$ تعداد نمونه های آموزشی می باشد.
]
= جلسه پنجم
#tool.simple_context()[
اگر با هر الگوریتم دلخواه h را یادگیری بکنیم، بر اساس این که Hypothesis ما چه مقدار از C را پوشش می دهد، می توان کیفیت مدل را بررسی کرد.
]
#tool.reminder()[
#tool.custom_figure(
image("images/ML/05_01.png"),
caption: "یادآوری از جلسه قبل.",
inset: 1em
)
]
#tool.reminder()[
#text(dir: ltr)[
ML Elements:
+ Examples
+ Model
+ Training Algorithm
]
]
== S, G and Version Space
#tool.definition()[
در جلسات قبل یک مدل از نمونه های مثبت (S در شکل زیر) و یک مدل از نمونه های منفی (G در تصویر زیر) ساختیم که در شکل زیر آمده اند:
#tool.custom_figure(
image("images/ML/05_02.png"),
caption: [به مدل S، #box[Most specific hypothesis] و به مدل G، #box[Most general hypothesis] می گویند.],
inset: 1em
)
S کوچکترین Hypothesis سازگار با نمونه های آموزشی و G بزرگترین Hypothesis سازگار با نمونه های آموزشی می باشد.
در شکل بالا هر مستطیلی که بین S و G باشد، جزو مجموعه جواب های ما است.
]
#tool.double_section()[
#tool.definition()[
Version Space: به فضایی که از S شروع و به G ختم می شود، که همان مجموعه جواب های بین S و G است، می گوییم #box[Version Space] می گویند.
]
][
#tool.definition()[
مسائل خوش ریخت: مسائلی که دانسته های مسأله برای تعیین جواب دقیق کافی است.
#v(1.6em)
]
]
#tool.double_section()[
#tool.definition()[
مسائل بد ریخت: مسائلی که دانسته های مسأله برای تعیین جواب دقیق کافی نیست.
در این مسائل، تعداد معادله ها از تعداد مجهول ها کمتر است.
#v(1.6em)
]
][
#tool.tip()[
یادگیری (ماشین) یک مسأله بد ریخت (ill-posed problem) می باشد.
مثلاً در شکل پیشین بی نهایت مستطیل به عنوان جواب بین S و G وجود دارد و مسأله آن یک مسأله ill-posed می باشد.
]
]
#tool.tip()[
نمونه های بیشتر در فرآیند یادگیری مسأله را به سمت well-posed بودن می برد.
#v(1.6em)
]
== انتخاب از درون Version Space
#tool.question()[
در شکل پیشین از S تا G کدام مستطیل را اتنخاب کنیم؟
(می خواهیم یک مورد از درون Version Space را انتخاب کنیم).
]
#tool.true_answer(pause: true)[
1. می توان وسط آن را انتخاب کرد که این روش بر مبنای فرض Max Margin می باشد.
]
#tool.example()[
با توجه به شکل زیر، فرض کنید نیاز های خانواده ها برای ماشین تغییر کند. این باعث می شود که تعریف ماشین خانواده کمی دچار تفاوت شود.
مثلاً از این به بعد ماشین های خانواده نیاز است فضایی برای قرار دادن ماهواره برای اینترنت ماهواره ای داشته باشند.
#tool.custom_figure(
image("images/ML/05_03.png"),
caption: "قاعده Max Margin",
inset: 1em
)
بنابراین برای آن که مدل مان به تغییرات کوچک حساس نشود، مستطیلی را انتخاب می کنیم که با هر دو مستطیل S و G، مرز زیادی داشته باشد.
]
#tool.true_answer(continuation: true)[
2. اگر مسأله طوری است که در آن مثلاً بیشترین ماشین ممکن را باید در گردونه ماشین های خانواده قرار دهیم، آن گاه باید طوری عمل کنیم که h به G نزدیکتر شود.
3. اگر مسأله طوری است که در آن مثلاً ماشین خانواده یک چیز مشخص و معینی است، آن گاه باید طوری عمل کنیم که ماشین هایی که تفاوت کوچکی با مشخصات تعریف شده دارند، در دسته ماشین خانواده قرار نگیرند.
در این حالت سعی می شود h به S نزدیک شود.
]
#tool.simple_context()[
بعضی وقت ها برای انتخاب یک مورد از Version Space راهنمایی هایی همچون بالا را نداریم.
در این صورت از قاعده کلی زیر (که می توان به دو صورت آن را پیاده سازی کرد) استفاده می شود.
]
#tool.definition(pause: true)[
قاعده کلی انتخاب یک مورد از Version Space: معمولاً اگر از تعدادی Domain Expert که IID هستند (از هم مستقل هستند و با احتمال یکسان به طور تصادفی انتخاب می شوند)، سؤال بپرسیم، آنگاه رأی اکثریت به واقعیت نزدیک تر است.
به دو صورت زیر این قاعده را با توجه به مثال شکل پیشین پیاده سازی می کنیم:
می خواهیم مستطیلی را به صورت تصادفی بین S و G انتخاب کنیم. چگونه این کار را انجام می دهیم؟
۴ نقطه تصادفی بین S و G را به شکل زیر انتخاب می کنیم:
#tool.custom_figure(
image("images/ML/05_04.png", width: 80%),
caption: "مختصات ۴ نقطه درون ۴ بازه بالا که بین S و G هستند، به صورت تصادفی ساخته می شود.",
inset: 1em
)
از آن جایی که مستطیل مورد نظر بین مستطیل S و G می باشد، با نمونه های آموزشی مان سازگار است.
دقت شود که در مثال بالا S و G از نمونه ها و h بین این دو به صورت تصادفی ساخته می شود.
]
#tool.question()[
در روش بالا، چند مستطیل تصادفی باید بسازیم؟
]
#tool.true_answer()[
$ N >= 33 $
یعنی حداقل ۳۳ عدد.
به دلیل قضیه حد مرکزی این عدد انتخاب می شود.
حداقل تعداد نمونه های لازم در نمونه برداری از توزیع نرمال برای آن که توزیع به دست آمده از نمونه ها توزیع درستی باشد، ۳۳ (در اصل ۳۲ ولی در اینجا همان ۳۳ را در نظر بگیرید) عدد است.
بنابراین از میان S و G (که همان Version Space مان است) N عدد مستطیل به صورت تصادفی انتخاب می کنیم.
(برای فهم آنکه چرا N باید حداقل ۳۳ باشد به Normal Distribution Estimation و Central Limit Theorem مطالعه شود.)
]
#tool.definition(continuation: true)[
پس از انتخاب N مستطیل به صورت توضیح داده شده، الگوریتم Voting را اجرا می کنیم.
به این صورت که وقتی نمونه جدیدی به ما داده شود، Label آن Label ای است که اکثریت این N مستطیل اعلام می کنند.
]
#tool.tip()[
قاعده Max Margin در کنار خوبی ای که دارد، دو عیب زیر را دارد:
+ باید بتوانیم برای هر Classifier، #box[Margin] را حساب کرد.
این در حالی است که برای خیلی از Classifier ها به راحتی نمی توان Margin را حساب کرد.
+ این روش همیشه به ما کمک نمی کند.
به این صورت که بعضی وقت ها یک Class مهم تر از یک Class دیگر است و باید Margin را کمی به این طرف و آن طرف هول داد.
]
== تقلید در یادگیری ماشین
#tool.tip()[
در یادگیری ماشین با پشت صحنه پدیده ها کاری نداریم.
بلکه با نمایش بیرونی آن ها کار داریم.
]
#tool.tip()[
در یادگیری ماشین در اغلب اوقات برای ما مهم نیست که فرضیه ای که درباره موضوع مورد نظر می سازیم چقدر درست و چقدر غلط است.
بلکه این مهم است که آن فرضیه چقدر مشاهدات ما را خوب توضیح می دهد.
]
#tool.example()[
در زمان قدیم این فرضیه وجود داشت که زمین صاف است چرا که با استفاده از این فرضیه می توانستند شب و روز را مدل کنند، تقویم بسازند و جهت یابی کنند.
بعداً مردم متوجه شدند که این فرضیه اشتباه است اما چیزی که باعث شد این فرضیه تا مدت ها پابرجا بماند این بود که برای مردم آن زمان کار می کرد و نیازشان را برطرف می کرد.
]
#tool.definition()[
Digital Twin: برنامه ای کامپیوتری است که تلاش می کند رفتار یک سیستم واقعی را تقلید کند.
#tool.custom_figure(
image("images/ML/05_05.png", width: 62%),
caption: "Digital Twin سعی می کند رفتار Real System را تقلید کند.",
inset: 1em
)
دقت شود که درون Real System و Digital Twin لزوماً مانند یکدیگر نیست اما ورودی و خروجی یکسانی دارند.
یکی از کاربرد های Digital Twin زمانی است که Real System گران قیمتی داریم و نمی توانیم هر کاری را با آن انجام دهیم.
]
== PAC Learning
#tool.definition()[
#tool.custom_figure(
image("images/ML/05_06.png"),
caption: "Probably Approximately Correct (PAC) Learning",
inset: 1em
)
فرض کنید C همان مفهومی است که واقعا وجود دارد و مساحت آن ۱ است.
ما می خواهیم h را بسازیم.
طبق شکل بالا خطای h شامل ۴ قسمت بالا، پایین، چپ و راستی است که بیرون از h و درون C قرار دارند.
خطای h را $epsilon$ در نظر می گیریم.
فرض کنیم مساحت ناحیه خطای شکل بالا $epsilon$ است و مساحت ۴ ناحیه با هم برابر است هر چند که اندازه شان متفاوت است.
به این ترتیب مساحت هر یک از آن ها $epsilon \/ 4$ می باشد.
احتمال این که یکی از ۴ نوار بالا به درون h بیافتد به صورت زیر است:
$ 1 - epsilon / 4 $
اگر N نمونه جدید پشت سر هم انتخاب کنیم، احتمال آن که همه این N نمونه از یک نوار خاص به درون h بیافتند، به صورت زیر است: $ (1 - epsilon / 4)^N arrow "Because samples are IID" $
اگر N نمونه جدید پشت سر هم انتخاب کنیم، احتمال آن که همه این N نمونه از ۴ نوار به درون h بیافتاند، به صورت زیر است: $ 4 (1 - epsilon / 4)^N $
احتمال بد شانسی را $delta$ در نظر می گیریم.
اگر بخواهیم احتمال بد شانسی از یک $delta$ ای کمتر باشد، از رابطه زیر استفاده می کنیم:
$ 4 (1 - epsilon / 4)^N <= delta $
$delta$ کمیتی است که خودمان انتخاب می کنیم.
مثلاً می خواهیم احتمال بد شانسی کمتر از ۰/۰۱ باشد.
در ادامه به رابطه های آخر شکل بالا می رسیم که رابطه نهایی آن شکل، در زیر آورده شده است:
$ N >= (4 / epsilon) log(4 / delta) $
رابطه بالا تعیین می کند که برای یادگیری مستطیل سازگار با نمونه های آموزشی، باید حداقل چه تعداد نمونه داشته باشیم.
به این تحلیل تئوریک، Probably Approximately Correct (PAC) Learning می گویند.
$epsilon$: خطای نمونه
$delta$: احتمال یادگیری مدل با استفاده از N نمونه آموزشی که خطای آن از $epsilon$ بیشتر باشد. $arrow.l$ احتمال بد شانسی
]
#tool.tip()[
PAC Learning تکنیکی است برای تعیین حداقل تعداد نمونه های آموزشی برای آن که مدل خوب یاد گرفته شود و احتمال بد شانسی کم شود.
]
#tool.list()[
در تکنیک PAC Learning دو مورد را مشخص می کنیم:
+ $epsilon$ (خطای قابل تحمل)
+ $delta$
که در پاسخ، حداقل تعداد نمونه های آموزشی به دست می آید.
]
#tool.tip()[
تحلیل هایی که در آن ها می خواهیم یک Boundry یا بازه را پیدا کنیم، اهمیت ندارند که دقیق باشند.
این گونه تحلیل ها را تحلیل بد بینانه (Pessimistic) می گویند.
]
== مدل های یادگیری ماشین
#tool.double_section()[
#tool.question()[
چه مدلی بهتر است؟
#v(3.6em)
]
][
#tool.true_answer()[
خبر بد:
کسی نمی داند.
خبر خوب:
مجموعه ای از مدل های خوب برای مسائل عام شناسایی شدند.
]
]
#tool.tip()[
مسأله ای که با یک مدل ساده تر حل می شود را با مدل پیچیده حل نمی کنند، چرا که:
#tool.double_section()[
+ استفاده از آن ساده تر است.
+ Train کردن آن راحت تر است.
][
3. توضیح دادن آن راحت تر است.
+ بهتر تعمیم می یابد.
]
#tool.custom_figure(
image("images/ML/05_07.png", width: 86%),
caption: "دلایل استفاده از مدل ساده تر",
inset: 1em
)
]
#tool.list()[
Classifier Models:
+ Basic Classifier: مدل هایی که با یک رابطه ریاضی یا یک ساختمان داده قابل توصیف اند.
مانند:
#text(dir: ltr)[Line, Polynomial, Decision Tree, Naive Bayes, Axis Aligned Rectangle, #sym.dots]
+ Ensemble Models (مدل های مرکب):
مدل هایی هستند که چندین Basic Model درون خود دارند.
مانند یک خط با یک مستطیل و یا مانند مثالی که مستطیل S و G را داشتیم و تعدادی مستطیل بین آن ها به طور تصادفی انتخاب کردیم و هنگام تولید Label از آن ها رأی گیری کردیم.
+ Neural Network & Deep Models: (فکر کنم یک جور هایی در هر دو گروه بالا می توانند قرار بگیرند)
]
=== Ensemble Models
#tool.example()[
نمونه ای دیگر از یک Ensemble Model:
می خواهیم دو گروه مثبت و منفی را از یکدیگر جدا کنیم که در شکل زیر آمده اند:
#tool.custom_figure(
image("images/ML/05_08.png", width: 50%),
caption: "جدا سازی دو گروه به کمک یک Ensemble Model",
inset: 1em
)
این کار در مراحل زیر انجام می گیرد:
+ جمع آوری نمونه ها #sym.arrow.l نمونه های مثبت و منفی
+ انتخاب مدل #sym.arrow.l خط
+ آموزش مدل #sym.arrow.l با کمک الگوریتم عمود منصف
در این مثال الگوریتم یادگیری مورد استفاده الگوریتم عمود منصف است.
این الگوریتم به این صورت کار می کند که مرکز جرم نمونه های مثبت و نمونه های منفی را پیدا کرده، سپس یک پاره خط که دو سر آن همان مرکز این دو گروه می باشد رسم می کنیم.
عمود منصف این پاره خط، خطی است که این دو گروه را از یک دیگر جدا می کند.
حال می خواهیم Ensemble ای از درخت های تصمیم بسازیم.
این کار به این شکل انجام می شود که چندین بار از هر گروه تعدادی نمونه انتخاب کرده و مرکز آن نمونه ها را در هر گروه پیدا می کنیم.
در ادامه طبق الگوریتم عمود منصف، خط جدا کننده این دو گروه پیدا می شود.
در نهایت چندین خط جدا کننده به این روش تولید خواهند شد.
]
= جلسه ششم
== Probabilistic Classifiers
#tool.tip()[
در این طبقه بند ها ما اطلاعی نداریم که نمونه به کدام کلاس تعلق دارد اما سعی می کنیم بر اساس شواهدی آن را به کلاسی تخصیص دهیم.
]
#tool.double_section()[
#tool.question()[
اگر یک تاس ساده را بیاندازیم، احتمال آن که عدد ۳ بیاید چقدر است؟
]
][
#tool.true_answer()[
$ 1 / 6 $
#v(0.3em)
]
]
#tool.double_section()[
#tool.question()[
اگر یک تاس ساده را بیاندازیم و بدانیم که عددی فرد آمده است، احتمال آن که مقدار آن ۳ باشد چقدر است؟
]
][
#tool.true_answer()[
$ 1 / 3 $
#v(1.9em)
]
]
#tool.double_section()[
#tool.tip()[
در مواقعی دانسته هایی داریم که ما را در رسیدن به احتمال مورد نظر کمک می کنند و آن را کمتر یا بیشتر می کنند.
]
][
#tool.definition()[
Evidence (مشاهده): چیزی است که ذهنیت ما را به یک سمت می برد.
#v(1.6em)
]
]
#tool.double_section()[
#tool.question()[
فردی وارد کلاس می شود.
احتمال آن که اهل فرانسه باشد و احتمال آن که اهل ایران باشد چقدر است؟
#v(3.2em)
]
][
#tool.true_answer()[
احتمال زیاد ایرانی است چرا که ذهن ما به سمت حقیقتی Bias شده و آن این است که احتمال دیدن شخصی فرانسوی در این جا خیلی خیلی کمتر از احتمال دیدن شخصی ایرانی است.
]
]
#tool.tip()[
بعضی اوقات بدون این که درباره Class یک نمونه اطلاعاتی داشته باشیم، ذهن ما سراغ دانش خاصی می رود.
]
=== Prior, Posterio and Marginal Probability
#tool.definition()[
Prior Probability (احتمال پیشین): به اینکه بدون این که درباره موضوع مورد نظر Evidence خاصی داشته باشیم، ذهن ما به دلیل خاصی به یک جهت خاصی گرایش پیدا کرده است.
به عبارتی دیگر احتمال Prior به احتمالی می گویند که بدون داشتن اطلاعاتی راجع به پیش آمد بیان می شود.
]
#tool.double_section()[
#tool.definition()[
Posterio Probability (احتمال پسین): احتمالی است که با داشتن اطلاعاتی راجع به پیش آمد بیان می شود.
#v(1.6em)
]
][
#tool.definition()[
Marginal Probability (احتمال حاشیه ای): احتمال حاشیه ای به احتمال مشاهده یک مقدار خاص از یک متغیر، ادغام شده روی تمام مقادیر ممکن سایر متغیرها اشاره دارد.
]
]
#tool.double_section()[
#tool.tip()[
از Evidence به Probability می رسیم.
#v(3.2em)
]
][
#tool.example()[
اگر بدانیم که بعد از انداختن تاس عددی که آمده فرد است، احتمال آمدن عدد ۳ بیشتر می شود.
]
]
#tool.definition()[
در بسیاری از موارد
$p(x)$
را داریم که احتمال رخ دادن متغیر $x$ می باشد.
برای نمونه در مثال تاس بدون داشتن دانش قبلی به صورت زیر است:
$ p(1) = 1 / 6 = p(2) = dots = p(6) $
اما مواردی وجود دارند که اطلاع قبلی ای در مورد موضوع مورد نظر داریم.
این موارد به صورت احتمال شرطی بیان می شوند.
این گونه احتمالات شبیه زیر بیان می شوند:
$ "Likelihood" arrow p("evidence" | "class") $
مانند زیر که $x$ را به یک کلاس مشروط کردیم:
#text(size: 1em)[
$ p(underbrace(x, "مشاهده") | x in underbrace({1, 3, 5}, "گروه یا کلاس")) = 1 / 3 $
]
]
#tool.tip()[
Likelihood معمولا با یک Probability Density Function یا همان PDF بیان می شود.
#h(10.5em) $p(x | c): "pdf"$
]
#tool.example(pause: true)[
در یک آزمایش پزشکی، تعداد گلبول های سفید در واحد خون تعدادی آدم شمرده می شود.
اگر بدن درگیر مهاجمی شده باشد، تعداد گلبول های سفید افزایش می یابد.
#tool.custom_figure(
image("images/ML/06_01.png", width: 79%),
caption: "تعداد گلبول های سفید در واحد خون و فراوانی افراد مرتبط با این تعداد گلبول سفید",
inset: 1em
)
#tool.custom_figure(
image("images/ML/06_02.png", width: 79%),
caption: "تعداد گلبول های سفید در واحد خون و احتمال داشتن این تعداد از گلبول های سفید برای یک فرد با توجه به اینکه مریض است یا سالم است.",
inset: 1em
)
از آن جایی که این پدیده، پدیده ای پیوسته و طبیعی است، می توان آن را با یک توزیع نرمال مدل کرد.
جمعیت بالا را خودمان نمونه گیری کردیم.
پزشک با داشتن تعداد گلبول های سفید، می خواهد بداند احتمال بیمار بودن فرد چقدر است؟ یعنی مثلا:
$ p("disease" | x = 15) $
]
=== Chain Rule of Probability
#tool.definition()[
قاعده زنجیره احتمالات توأمان (Chain rule of probability):
$ p(A, B) = p(A) times p(B | A) = p(B) times p(A | B) = p(B, A) $
$ P(A, B, C) = p(A) times p(B | A) times p(C | A, B) $
$ P(A, B, C, D) = p(A) times p(B | A) times p(C | A, B) times p(D | A, B, C) $
]
#tool.example(continuation: true)[
#text(fill: red_color)[$C_1$] نمایانگر بیمار بودن و #text(fill: green_color)[$C_2$] نمایانگر سالم بودن است.
$ p(x_1, C_1) = p(x) times p(C_1 | x) = p(C_1) times p(x | C_1) $
همانطور که گفتیم پزشک می خواهد احتمال بیمار بودن فرد را بداند:
#text(size: 1.25em)[
$ overbrace(p(C_1 | x), "Posterio") = (overbrace(p(C_1), "Prior") times overbrace(p(x | C_1), "Likelihood")) / (p(x) = underbrace(p(x | C_1) + p(x | C_2), "Marginal probability of x")) $
]
$p(C_1)$ یعنی احتمال بیمار بودن یک آدم در یک جمعیت، بدون اینکه Evidence ای داشته باشیم.
$p(x)$ یعنی احتمال اینکه تعداد گلبول های سفید در یک جمعیت، مقدار $x$ باشد، بدون اینکه Evidence ای داشته باشیم.
همچنین چون فقط $C_1$ و $C_2$ هستند که فضا را افراز می کنند، $p(x)$ را در مخرج معادله بالا برابر با مقدار زیر قرار دادیم:
$ p(x) = p(x | C_1) + p(x | C_2) $
که به آن Marginal probability مربوط به $x$ می گویند.
]
#tool.question()[
شخصی با WBC = 14 به پزشک مراجعه کرده است.
آیا بیمار است؟
]
#tool.true_answer()[
برای این که پزشک بیمار بودن فرد را تشخیص دهد، مقدار دو احتمال زیر را حساب کرده و مقدار هر کدام که بیشتر بود یعنی فرد در آن وضعیت (سالم یا بیمار) قرار دارد.
$ p("بیمار" | "wbc" = 14) space.quad , space.quad p("سالم" | "wbc" = 14) $
بنابراین فرد در صورت زیر بیمار است:
$ "Type of a preson" == "بیمار" "iff" p("بیمار" | "wbc" = 14) > p("سالم" | "wbc" = 14) $
]
=== Bayesian Learning
#tool.definition()[
Bayesian Learning:
#text(size: 1.25em)[
$
x in C_1 "iff" p(C_1 | x) > p(C_2 | x) \
= (p(C_1) times p(x | C_1)) / cancel(p(x)) > (p(C_2) times p(x | C_2)) / cancel(p(x)) \
= p(C_1) times p(x | C_1) > p(C_2) times p(x | C_2)
$
]
]
#tool.question()[
مقدار $p(C_1)$ را از کجا می آوریم و چقدر است؟
]
#tool.true_answer()[
از Domain Knowledge می آوریم.
در مسائل Machine Learning همان اول روی Train Data معادله زیر را اعمال کرده و با این معادله مقدار $p(C_1)$ را حساب می کنیم:
#text(size: 1.25em)[
$ p(C_1) = n(C_1) / (n(C_1) + n(C_2) = N) $
]
]
=== به دست آوردن $p(x | C_1)$ و $p(x | C_2)$
#tool.question()[
مقدار $p(x | C_1)$ و $p(x | C_2)$ را چگونه به دست آوریم؟
]
#tool.true_answer()[
این موارد نیز از روی Train Data، حساب می شوند.
فرض کنید Train Data ای به شکل زیر داریم:
#tool.custom_figure(caption: [Train Data ما دارای تعدادی m ویژگی و دو کلاس $C_1$ و $C_2$ است.], kind: table, inset: 1em)[
$
#stack(
v(2.5em),
$ "Number of rows" arrow.l N lr(\{, size: #20em) $,
)
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center,
$x_1 x_2 dots x_m$,
$y$,
line(),
$C_1$,
line(),
$C_1$,
$dots.v$,
$dots.v$,
line(),
$C_1$,
line(),
$C_2$,
line(),
$C_2$,
line(),
$C_2$,
line(),
$C_2$
)
#stack(
v(3em),
$ lr(}, size: #9em) C_1 $,
v(2em),
$ lr(}, size: #9em) C_2 $,
)
$
]
با استفاده از یک جدول احتمالاتی ساده $p(C_1)$ و $p(C_2)$ که در پاسخ سؤال قبلی فرمول آن آورده شد، به دست می آیند.
$p(x | C_1)$ و $p(x | C_2)$ نیز به صورت یک Probability Distribution نوشته می شوند که معمولاً دو حالت دارد زیر را دارد:
+ Tabular: یعنی به صورت جدولی نوشته می شود.
مانند جدول زیر:
#tool.custom_figure(caption: "نمونه ای از نوشته شدن یک توزیع احتمالاتی به شکل جدول.", kind: table, inset: 1em)[
#table(
columns: 2,
inset: 1em,
stroke: black,
align: center,
$x$,
$p(x)$,
$1$,
$0.1$,
$2$,
$0.002$,
$dots.v$,
$dots.v$,
$100$,
$0.0003$
)
]
+ PDF: یک تابع ریاضی می نویسیم که $x$ را به احتمالش نگاشت می کند.
مثلاً برای خیلی از پدیده هایی که با آن ها سر و کار داریم، یک تابع توزیع احتمال نرمال می نویسیم.
فرمول تابع توزیع نرمال برای $C_1$ به صورت زیر است:
#text(size: 1.5em)[
$ p(x | C_1): "Normal"(underbrace(mu_1, "Mean"), underbrace(sigma_1, "Standard deviation")) arrow.curve.b $
]
#text(size: 2em)[
$ p(x | C_1) = 1 / (sqrt(2 pi sigma_1^2)) e^((-(x - mu_1)^2) / (2 sigma_1^2)) $
]
#text(size: 1.5em)[
$ mu_1 = (sum_(x in C_1)x) / (n(C_1)) $
$ sigma_1 = sqrt((sum_(x in C_1)(x - mu_1)^2) / (N - 1)) $
]
]
#tool.tip()[
برای توزیع های کوچک Tabular و برای توزیع های بزرگ PDF خوب است.
]
=== احتمال شرطی دو متغیره
#tool.question()[
۶ نمونه که هر یک، دو Feature دارند و در کل به دو کلاس تقسیم بندی می شوند، به شکل زیر داریم:
#tool.custom_figure(
image("images/ML/06_03.png", width: 46%),
caption: "۶ نمونه داریم که به شکل بالا توزیع شده اند.",
inset: 1em,
refrence: <diagram1>
)
نمونه ای داریم که ویژگی های آن به صورت $x_1 = -1$ و $x_2 = 0$ است.
این نمونه متعلق به کلاس $C_1$ است یا $C_2$؟
]
#tool.true_answer()[
برای حل این مسأله هر دو احتمال زیر را حساب می کنیم:
$ p(C_1 | < x_1 = -1, x_2 = 0 >) = space ? space.quarter , space.quarter p(C_2 | < x_1 = -1, x_2 = 0 >) = space ? $
این مسأله را به کمک جدول حل می کنیم.
ابتدا نمودار را به صورت جدول زیر در می آوریم:
#tool.custom_figure(caption: [جدول مربوط به نمودار @diagram1], kind: table, inset: 1em)[
#table(
columns: 3,
inset: 1em,
stroke: black,
align: center,
$x_1$,
$x_2$,
$y$,
$-1$,
$0$,
$C_1$,
$-1$,
$-1$,
$C_1$,
$0$,
$-1$,
$C_1$,
$1$,
$0$,
$C_2$,
$1$,
$1$,
$C_2$,
$0$,
$1$,
$C_2$
)
]
سپس احتمالات شرطی (Posterio های) مربوط به $x_1$ را به صورت جدول زیر می نویسیم:
#tool.custom_figure(caption: [احتمالات شرطی (Posterio های) مربوط به $x_1$], kind: table, inset: 1em)[
#table(
columns: 3,
inset: 1em,
stroke: black,
align: center,
$x_1$,
$p(x_1 | C_1)$,
$p(x_1 | C_2)$,
$-1$,
$ 2 / 3 $,
$0$,
$0$,
$ 1 / 3 $,
$ 1 / 3 $,
$1$,
$0$,
$ 2 / 3 $,
)
]
برای $x_2$ نیز به همین صورت عمل می کنیم:
#tool.custom_figure(caption: [احتمالات شرطی (Posterio های) مربوط به $x_2$], kind: table, inset: 1em)[
#table(
columns: 3,
inset: 1em,
stroke: black,
align: center,
$x_2$,
$p(x_2 | C_1)$,
$p(x_2 | C_2)$,
$-1$,
$ 2 / 3 $,
$0$,
$0$,
$ 1 / 3 $,
$ 1 / 3 $,
$1$,
$0$,
$ 2 / 3 $,
)
]
همچنین خود Prior ها را نیز می نویسیم:
$ p(C_1) = p(C_2) = 0.5 $
فرض کنید برای تست از همان داده های Training استفاده می کنیم (در اینجا برای سادگی این کار را می کنیم و گرنه کار خوبی نیست).
در ادامه جواب دو احتمال شرطی ای که در ابتدا آورده شدند را محاسبه می کنیم:
$ p(C_1 | < x_1 = -1, x_2 = 0 >) = space ? space.quarter , space.quarter p(C_2 | < x_1 = -1, x_2 = 0 >) = space ? $
به کمک قاعده بیز ساده (Naive Bayes Assumption) می توان احتمال های بالا را حساب کرد.
این قاعده می گوید که فرض کنیم $x_1$ و $x_2$ از هم مستقل هستند.
این قاعده برای احتمال های بالا به صورت زیر نوشته می شود:
$ p(C_1 | < x_1 = -1, x_2 = 0 >) = \ p(C_1 | x_1 = -1) times p(C_1 | x_2 = 0) $
از آن جایی که $p(x)$ مساوی است، به آن نیازی نداریم و مخرج کسر را حساب نمی کنیم.
در ادامه به صورت زیر معادله بالا را حل می کنیم:
$
p(C_1 | < x_1 = -1, x_2 = 0 >) = \ p(C_1 | x_1 = -1) times p(C_1 | x_2 = 0) = \
cancel(p(C_1)) times p(x_1 = -1 | C_1) times cancel(p(C_1)) times p(x_2 = 0 | C_1) = \ 2 / 3 times 1 / 3 = 2 / 9 arrow star star #text(dir: ltr)[Wins] star star
$
$
p(C_2 | < x_1 = -1, x_2 = 0 >) = \ p(C_2 | x_1 = -1) times p(C_2 | x_2 = 0) = \
cancel(p(C_2)) times p(x_1 = -1 | C_2) times cancel(p(C_2)) times p(x_2 = 0 | C_2) = \ 0 times 1 / 3 = 0
$
]
=== ترتیب استفاده از Classifier ها
#tool.tip()[
Naive Bayes طبقه بند خیلی ساده ای است.
به همین دلیل به عنوان Baseline یا مبنای پایه برای محاسبات استفاده می شود.
اگر Naive Bayes در حد ۶۰٪ یا ۷۰٪ خوب جواب داد، آن گاه سراغ روش های دیگر برای بهتر کردن مدل می رویم.
باید بقیه روش هایی که بعد از Naive Bayes استفاده می کنیم از آن بهتر باشند به جز Random Assignment.
یعنی عملکرد روش های مختلف و ترتیب به کار گیری آن ها (از چپ به راست) به شکل زیر است:
#align(center)[
Random Assignment < Naive Bayes < Other Methods
]
روش Random Assignment به این صورت کار می کند که به صورت تصادفی به نمونه ها Label می زنیم.
مثلاُ این روش در یک مسأله دو کلاسه دارای دقت ۵۰٪ است.
]
#tool.example()[
مسأله ای درباره طبقه بندی زعفران داریم.
زعفران ها در ۵ کلاس طبقه بندی می شوند:
#grid(
columns: (1fr, 1fr, 1fr, 1fr, 1fr),
align: center,
[1. عالی],
[2. بسیار خوب],
[3. خوب],
[4. متوسط],
[5. بد]
)
روش Random Assignment برای این مسأله دارای دقت ۲۰٪ است.
یعنی احتمال این که کلاس نمونه ای درست تشخیص داده شود، ۲۰٪ است.
در ادامه طبقه بند Naive Bayes می سازیم.
اگر دقت Naive Bayes بالای ۲۰٪ شد، به سراغ حل مسأله با روش های یادگیری ماشین می رویم.
چرا که تجربه نشان می دهد اگر Naive Bayes خیلی بهتر از Random Assignment کار نکرد، اول به Dataset مسأله مان باید شک کنیم و به این گمان بیافتیم که در یک جای مسأله اشتباهی کرده ایم.
] |
|
https://github.com/rabotaem-incorporated/probability-theory-notes | https://raw.githubusercontent.com/rabotaem-incorporated/probability-theory-notes/master/appendix.typ | typst | #import "config.typ"
#import "utils/core.typ": *
#set heading(numbering: (..numbers) => {
let numbers = numbers.pos()
if numbers.len() < 2 {
none
} else if numbers.len() == 2 {
numbering("A.", numbers.at(1))
}
})
= Приложение
== TODO-шки и упражнения
Все это, по хорошему, надо дописать/доделать/улучшить.
#locate(loc => {
let todos = query(selector(<todo-like>), loc)
list(..todos.map(el => {
link(el.location(), el)
box(width: 1fr, repeat[.])
link(el.location())[#el.location().page()]
}))
if todos.len() == 0 [
Ура! Долгов нет!
]
})
#if config.enable-ticket-references [
== Ссылки на билеты <ticket-reference>
#locate(loc => enum(
numbering: "1.",
..query(selector(<ticket>).before(<tickets-div>), loc)
.sorted(key: ticket-name-label => {
counter("ticket").at(ticket-name-label.location()).first()
}).map(ticket-name-label => {
let ticket-location = ticket-name-label.location()
enum.item(
counter("ticket").at(ticket-location).first(),
[
#link(ticket-location, ticket-name-label.body)
#box(width: 1fr, repeat[.])
#link(ticket-location)[#ticket-location.page()]
]
)
})
))
]
|
|
https://github.com/fyuniv/simplebook | https://raw.githubusercontent.com/fyuniv/simplebook/main/example/example.typ | typst | MIT License | #import "lib.typ": *
#show: simplebook.with(
title: "A Simple Book Template",
author: "Author",
affiliation: text(fill: orange)[University],
date: none,
// year: "Year",
version: "0.1.0",
theme_colors: (
primary_color: blue,
secondary_color: green,
),
rfoot: "right footer",
lfoot: image("by-nc-sa.svg", height: 1em)
)
// Preface
#preface(preface_title: [Preface])[
#lorem(100)
]
// Outline
#outline()
// Edit this content to your liking
#mainmatter
#show heading: it => {
set text(fill: red)
it
}
= Introduction
This is a simple book template that has basic feature of formal book.
== Some Features
+ Title color can be set with the `main-color` property.
+ Footers are customable except those pages before main matter.
+ A function `mainmatter()` can be use to reset page numbers and styles.
+ Headers are customable except the starting page of a chapter, or a page before main matter.
+ New Chapters always starts on an odd page.
== Remarks
+ The default outline depth is 2.
+ Level 3 or higher headings are in their default style.
+ One can change the default chapter and section prefix by
```typst
#set heading(supplment: [your prefix])
```
#blankpage
== Something Else
Any comments and suggestions are welcome.
= Enjoy!
#lorem(500)
#pagebreak()
== Enjoy a subsection! $theta$
#lorem(600)
= Another Chapter
#lorem(200)
= Chapter 5
#lorem(200)
#heading(level: 1, numbering: none, supplement: none)[Appendix A] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.