repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/xrarch/books | https://raw.githubusercontent.com/xrarch/books/main/xr17032handbook/chapinstructions.typ | typst | #import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx
= Instructions
== Instruction Formats Summary
The XR/17032 architecture features only four instruction formats, and each are 32 bits wide. There are a total of 60 instructions, which are summarized below. A more comprehensive description of each format and instruction can be found in @instlisting.
#image("formats.png", fit: "stretch")
=== Jump Instructions Summary
- *J IMM29* _Jump_
- *JAL IMM29* _Jump And Link_
=== Branch Instructions Summary
- *BEQ RA, IMM21* _Branch Equal_
- *BNE RA, IMM21* _Branch Not Equal_
- *BLT RA, IMM21* _Branch Less Than_
- *BGT RA, IMM21* _Branch Greater Than_
- *BGE RA, IMM21* _Branch Greater Than or Equal_
- *BLE RA, IMM21* _Branch Less Than or Equal_
- *BPE RA, IMM21* _Branch Parity Even_
- *BPO RA, IMM21* _Branch Parity Odd_
=== Immediate Operate Instructions Summary
- *ADDI RA, RB, IMM16* _Add Immediate_
- *SUBI RA, RB, IMM16* _Subtract Immediate_
- *SLTI RA, RB, IMM16* _Set Less Than Immediate_
- *SLTI SIGNED RA, RB, IMM16* _Set Less Than Immediate, Signed_
- *ANDI RA, RB, IMM16* _And Immediate_
- *XORI RA, RB, IMM16* _Xor Immediate_
- *ORI RA, RB, IMM16* _Or Immediate_
- *LUI RA, RB, IMM16* _Load Upper Immediate_
- *MOV RA, BYTE [RB + IMM16]* _Load Byte, Immediate Offset_
- *MOV RA, INT [RB + IMM16]* _Load Int, Immediate Offset_
- *MOV RA, LONG [RB + IMM16]* _Load Long, Immediate Offset_
- *MOV BYTE [RA + IMM16], RB* _Store Byte, Immediate Offset_
- *MOV INT [RA + IMM16], RB* _Store Int, Immediate Offset_
- *MOV LONG [RA + IMM16], RB* _Store Long, Immediate Offset_
- *MOV BYTE [RA + IMM16], IMM5* _Store Byte, Small Immediate_
- *MOV INT [RA + IMM16], IMM5* _Store Int, Small Immediate_
- *MOV LONG [RA + IMM16], IMM5* _Store Long, Small Immediate_
- *JALR RA, RB, IMM16* _Jump And Link, Register_
=== Register Operate Instructions Summary
*Major Opcode 111001*
- *MOV RA, BYTE [RB + RC xSH IMM5]* _Load Byte, Register Offset_
- *MOV RA, INT [RB + RC xSH IMM5]* _Load Int, Register Offset_
- *MOV RA, LONG [RB + RC xSH IMM5]* _Load Long, Register Offset_
- *MOV BYTE [RB + RC xSH IMM5], RA* _Store Byte, Register Offset_
- *MOV INT [RB + RC xSH IMM5], RA* _Store Int, Register Offset_
- *MOV LONG [RB + RC xSH IMM5], RA* _Store Long, Register Offset_
- *LSH RA, RB, RC* _Left Shift By Register Amount_
- *RSH RA, RB, RC* _Logical Right Shift By Register Amount_
- *ASH RA, RB, RC* _Arithmetic Right Shift By Register Amount_
- *ROR RA, RB, RC* _Rotate Right By Register Amount_
- *ADD RA, RB, RC xSH IMM5* _Add Register_
- *SUB RA, RB, RC xSH IMM5* _Subtract Register_
- *SLT RA, RB, RC xSH IMM5* _Set Less Than Register_
- *SLT SIGNED RA, RB, RC xSH IMM5* _Set Less Than Register, Signed_
- *AND RA, RB, RC xSH IMM5* _And Register_
- *XOR RA, RB, RC xSH IMM5* _Xor Register_
- *OR RA, RB, RC xSH IMM5* _Or Register_
- *NOR RA, RB, RC xSH IMM5* _Nor Register_
*Major Opcode 110001*
- *MUL RA, RB, RC* _Multiply_
- *DIV RA, RB, RC* _Divide_
- *DIV SIGNED RA, RB, RC* _Divide, Signed_
- *MOD RA, RB, RC* _Modulo_
- *LL RA, RB* _Load Locked_
- *SC RA, RB, RC* _Store Conditional_
- *MB* _Memory Barrier_
- *WMB* _Write Memory Barrier_
- *BRK* _Breakpoint_
- *SYS* _System Service_
*Major Opcode 101001 (Privileged Instructions)*
- *MFCR RA, CR* _Move From Control Register_
- *MTCR CR, RA* _Move To Control Register_
- *HLT* _Halt Until Next Interrupt_
- *RFE* _Return From Exception_
== Instruction Listing <instlisting>
The following section contains a comprehensive listing of all of the instructions defined by the XR/17032 architecture along with their encodings. The instructions are grouped first by format, and then by major opcode.
Note that the assembly language also supports several "pseudo-instructions" for ease of assembly programming, which are not listed below, as they don't directly correspond to any particular hardware instruction, and are usually translated to a sequence of several hardware instructions. See @pseudoinstructions for a listing of pseudo-instructions.
#pagebreak(weak: true)
#box([
=== Jump Format
#image("jumpformat.png", fit: "stretch")
The format for the absolute jump instructions consists of a 3-bit opcode and a 29-bit jump target. The two possible opcodes for jump instructions are *111* and *110*.
], width: 100%)
Note that this opcode field is unique; all other formats have a 6-bit opcode field. This small opcode is to allow the jump target to cover a 2GB range. This is accomplished by shifting the jump target left by 2, which produces a 31-bit address, and then taking the uppermost bit from that of the current program counter. This allows jumping anywhere within a 2GB userspace or kernel space in a single instruction.
#box([
#line(length: 100%)
#align(center, [
#rect([
*JAL IMM29* \
_Jump And Link_ \
Opcode: *111* (0x07)
```
Reg[31] = PC + 4
PC = (IMM29 << 2) | (PC & 0x80000000)
```
], width: 100%)])
The *JAL* instruction provides a lightweight means of calling a function. The next program counter (PC + 4) is saved in the link register (31) and then the PC is set to the target address.
Note that if the called function needs to call another function, it must be sure to save the link register first and then restore it.
], width: 100%)
#box([
#line(length: 100%)
#align(center, [
#rect([
*J IMM29* \
_Jump_ \
Opcode: *110* (0x06)
```
PC = (IMM29 << 2) | (PC & 0x80000000)
```
], width: 100%)])
The *J* instruction provides a way to do a long-distance absolute jump to another location, without destroying the contents of the link register.
], width: 100%)
#line(length: 100%)
#pagebreak(weak: true)
#box([
=== Branch Format
#image("branchformat.png", fit: "stretch")
The format for the branch instructions consists of a 6-bit opcode, a 5-bit register number, and a 21-bit branch offset. Every branch instruction has *101* as the low 3 bits of the opcode.
], width: 100%)
There is only one register field in order to maximize the size of the branch offset. This register is compared against zero in various ways. If the branch is taken, then the branch offset is shifted left by two, sign extended, and added to the current program counter. This gives a range of $plus.minus$1M instructions, or $plus.minus$4MB. As this covers the entire text section of most programs, and certainly covers any individual routine you're likely to find, this alleviates some burden that afflicts most RISC toolchains, as cross-procedure jumps will usually be done with absolute jumps anyway.
#box([
#align(center, [
#rect([
*BEQ RA, IMM21* \
_Branch Equal_ \
Opcode: *111101* (0x3D)
```
IF Reg[RA] == 0 THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BEQ* instruction performs a relative jump if the contents of *Register A* are equal to zero.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*BNE RA, IMM21* \
_Branch Not Equal_ \
Opcode: *110101* (0x35)
```
IF Reg[RA] != 0 THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BNE* instruction performs a relative jump if the contents of *Register A* are not equal to zero.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*BLT RA, IMM21* \
_Branch Less Than_ \
Opcode: *101101* (0x2D)
```
IF Reg[RA] & 0x80000000 THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BLT* instruction performs a relative jump if the contents of *Register A* are less than zero, i.e., the sign bit is set.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*BGT RA, IMM21* \
_Branch Greater Than_ \
Opcode: *100101* (0x25)
```
IF NOT (Reg[RA] & 0x80000000) AND Reg[RA] != 0 THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BGT* instruction performs a relative jump if the contents of *Register A* are greater than zero, i.e., the sign bit is clear and the register is not equal to zero.
#line(length: 100%)
], width: 100%)
#box([
#box([
#align(center, [
#rect([
*BLE RA, IMM21* \
_Branch Less Than Or Equal_ \
Opcode: *011101* (0x1D)
```
IF Reg[RA] & 0x80000000 OR Reg[RA] == 0 THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BLE* instruction performs a relative jump if the contents of *Register A* are less than or equal to zero, i.e., the sign bit is set or the register is equal to zero.
#line(length: 100%)
], width: 100%)
#align(center, [
#rect([
*BGE RA, IMM21* \
_Branch Greater Than Or Equal_ \
Opcode: *010101* (0x15)
```
IF NOT (Reg[RA] & 0x80000000) THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BGE* instruction performs a relative jump if the contents of *Register A* are greater than or equal to zero, i.e., the sign bit is clear.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*BPE RA, IMM21* \
_Branch Parity Even_ \
Opcode: *001101* (0x0D)
```
IF NOT (Reg[RA] & 0x1) THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BPE* instruction performs a relative jump if the contents of *Register A* are even, i.e., the low bit is clear.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*BPO RA, IMM21* \
_Branch Parity Odd_ \
Opcode: *000101* (0x05)
```
IF Reg[RA] & 0x1 THEN
PC += SignExtend(IMM21)
END
```
], width: 100%)])
The *BPO* instruction performs a relative jump if the contents of *Register A* are odd, i.e., the low bit is set.
#line(length: 100%)
], width: 100%)
#pagebreak(weak: true)
#box([
=== Immediate Operate Format
#image("immopformat.png", fit: "stretch")
The format for the immediate operate instructions consists of a 6-bit opcode, two 5-bit register numbers, and a 16-bit immediate value. Every immediate operate instruction has either *100*, *011*, *010*, or *000* as the low 3 bits of the opcode.
], width: 100%)
Note that the immediate value may or may not be sign extended, depending on the instruction.
#align(center, [*100 Group*])
#box([
#align(center, [
#rect([
*ADDI RA, RB, IMM16* \
_Add Immediate_ \
Opcode: *111100* (0x3C)
```
Reg[RA] = Reg[RB] + IMM16
```
], width: 100%)])
The *ADDI* instruction performs an addition between the contents of *Register B* and a zero-extended 16-bit immediate value, storing the result in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SUBI RA, RB, IMM16* \
_Subtract Immediate_ \
Opcode: *110100* (0x34)
```
Reg[RA] = Reg[RB] - IMM16
```
], width: 100%)])
The *SUBI* instruction performs a subtraction between the contents of *Register B* and a zero-extended 16-bit immediate value, storing the result in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SLTI RA, RB, IMM16* \
_Set Less Than Immediate_ \
Opcode: *101100* (0x2C)
```
Reg[RA] = Reg[RB] < IMM16
```
], width: 100%)])
The *SLTI* instruction performs an unsigned less-than comparison between the contents of *Register B* and a zero-extended 16-bit immediate value. If the comparison is true, a *1* is stored in *Register A*. Otherwise, a *0* is stored.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SLTI SIGNED RA, RB, IMM16* \
_Set Less Than Immediate, Signed_ \
Opcode: *100100* (0x24)
```
Reg[RA] = Reg[RB] s< SignExtend(IMM16)
```
], width: 100%)])
The *SLTI SIGNED* instruction performs a signed comparison between the contents of *Register B* and a sign-extended 16-bit immediate value. If the comparison is true, a *1* is stored in *Register A*. Otherwise, a *0* is stored.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*ANDI RA, RB, IMM16* \
_And Immediate_ \
Opcode: *011100* (0x1C)
```
Reg[RA] = Reg[RB] & IMM16
```
], width: 100%)])
The *ANDI* instruction performs a bitwise AND between the contents of *Register B* and a zero-extended 16-bit immediate value, storing the result in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*XORI RA, RB, IMM16* \
_Xor Immediate_ \
Opcode: *010100* (0x14)
```
Reg[RA] = Reg[RB] $ IMM16
```
], width: 100%)])
The *XORI* instruction performs a bitwise XOR between the contents of *Register B* and a zero-extended 16-bit immediate value, storing the result in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*ORI RA, RB, IMM16* \
_Or Immediate_ \
Opcode: *001100* (0x0C)
```
Reg[RA] = Reg[RB] | IMM16
```
], width: 100%)])
The *ORI* instruction performs a bitwise OR between the contents of *Register B* and a zero-extended 16-bit immediate value, storing the result in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*LUI RA, RB, IMM16* \
_Load Upper Immediate_ \
Opcode: *000100* (0x04)
```
Reg[RA] = Reg[RB] | (IMM16 << 16)
```
], width: 100%)])
The *LUI* instruction performs a bitwise OR between the contents of *Register B* and a zero-extended 16-bit immediate value which is shifted 16 bits to the left, storing the result in *Register A*.
#line(length: 100%)
], width: 100%)
#align(center, [*011 Group*])
#box([
#align(center, [
#rect([
*MOV RA, BYTE [RB + IMM16]* \
_Load Byte, Immediate Offset_ \
Opcode: *111011* (0x3B)
```
Reg[RA] = Load8(Reg[RB] + IMM16)
```
], width: 100%)])
This instruction loads an 8-bit value into *Register A* from the address stored within *Register B* plus a zero-extended 16-bit immediate offset.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV RA, INT [RB + IMM16]* \
_Load Int, Immediate Offset_ \
Opcode: *110011* (0x33)
```
Reg[RA] = Load16(Reg[RB] + (IMM16 << 1))
```
], width: 100%)])
This instruction loads a 16-bit value into *Register A* from the address stored within *Register B* plus a zero-extended 16-bit immediate offset shifted to the left by one.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV RA, LONG [RB + IMM16]* \
_Load Long, Immediate Offset_ \
Opcode: *101011* (0x2B)
```
Reg[RA] = Load32(Reg[RB] + (IMM16 << 2))
```
], width: 100%)])
This instruction loads a 32-bit value into *Register A* from the address stored within *Register B* plus a zero-extended 16-bit immediate offset shifted to the left by two.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [*010 Group*])
#align(center, [
#rect([
*MOV BYTE [RA + IMM16], RB* \
_Store Byte, Immediate Offset_ \
Opcode: *111010* (0x3A)
```
Store8(Reg[RA] + IMM16, Reg[RB])
```
], width: 100%)])
This instruction stores the contents of *Register B* as an 8-bit value to the address stored within *Register A* plus a zero-extended 16-bit immediate offset.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV INT [RA + IMM16], RB* \
_Store Int, Immediate Offset_ \
Opcode: *110010* (0x32)
```
Store16(Reg[RA] + (IMM16 << 1), Reg[RB])
```
], width: 100%)])
This instruction stores the contents of *Register B* as a 16-bit value to the address stored within *Register A* plus a zero-extended 16-bit immediate offset shifted to the left by one.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV LONG [RA + IMM16], RB* \
_Store Long, Immediate Offset_ \
Opcode: *101010* (0x2A)
```
Store32(Reg[RA] + (IMM16 << 2), Reg[RB])
```
], width: 100%)])
This instruction stores the contents of *Register B* as a 32-bit value to the address stored within *Register A* plus a zero-extended 16-bit immediate offset shifted to the left by two.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV BYTE [RA + IMM16], IMM5* \
_Store Byte, Small Immediate_ \
Opcode: *011010* (0x1A)
```
Store8(Reg[RA] + IMM16, SignExtend(IMM5))
```
], width: 100%)])
This instruction stores a sign-extended 5-bit immediate as an 8-bit value to the address stored within *Register A* plus a zero-extended 16-bit immediate offset. The *Register B* field of the instruction is interpreted as the 5-bit immediate.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV INT [RA + IMM16], IMM5* \
_Store Int, Small Immediate_ \
Opcode: *010010* (0x12)
```
Store16(Reg[RA] + (IMM16 << 1), SignExtend(IMM5))
```
], width: 100%)])
This instruction stores a sign-extended 5-bit immediate as a 16-bit value to the address stored within *Register A* plus a zero-extended 16-bit immediate offset shifted left by one. The *Register B* field of the instruction is interpreted as the 5-bit immediate.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV LONG [RA + IMM16], IMM5* \
_Store Long, Small Immediate_ \
Opcode: *001010* (0x0A)
```
Store32(Reg[RA] + (IMM16 << 2), SignExtend(IMM5))
```
], width: 100%)])
This instruction stores a sign-extended 5-bit immediate as a 32-bit value to the address stored within *Register A* plus a zero-extended 16-bit immediate offset shifted left by two. The *Register B* field of the instruction is interpreted as the 5-bit immediate.
#line(length: 100%)
], width: 100%)
#align(center, [*000 Group*])
#box([
#align(center, [
#rect([
*JALR RA, RB, IMM16* \
_Jump And Link, Register_ \
Opcode: *111000* (0x38)
```
Reg[RA] = PC + 4
PC = Reg[RB] + (SignExtend(IMM16) << 2)
```
], width: 100%)])
The *JALR* instruction provides a lightweight means of calling through a function pointer. The next program counter (PC + 4) is saved in *Register A*, and then the PC is set to the contents of *Register B* plus a 16-bit sign-extended immediate value shifted left by two.
This instruction can also be used to jump to the contents of a register in general, by setting the destination register to the *zero* register, thereby discarding the results.
#line(length: 100%)
], width: 100%)
#pagebreak(weak: true)
#box([
=== Register Operate Format
#image("regopformat.png", fit: "stretch")
The format for the register operate instructions consists of a 6-bit opcode, three 5-bit register numbers, a 5-bit shift amount, a 2-bit shift type, and a 4-bit function code (which acts as an extended opcode). Every register operate instruction has *001* as the low 3 bits of the opcode, and there are three such opcodes; *111001*, *110001*, and *101001*.
All privileged instructions are in this format and are function codes of the last opcode mentioned, *101001*. These instructions will produce a privilege violation exception if executed while usermode is enabled in the *RS* control register (see @rs).
], width: 100%)
The value of Register C is shifted in the manner specified by the shift type, by the amount specified by the shift amount. A table of shift types follows:
#set align(center)
#tablex(
columns: (auto, auto),
align: horizon,
cellx([
#set text(fill: white)
#set align(center)
*00*
], fill: rgb(0,0,0,255)),
[*LSH* Left shift.],
cellx([
#set text(fill: white)
#set align(center)
*01*
], fill: rgb(0,0,0,255)),
[*RSH* Logical right shift.],
cellx([
#set text(fill: white)
#set align(center)
*10*
], fill: rgb(0,0,0,255)),
[*ASH* Arithmetic right shift.],
cellx([
#set text(fill: white)
#set align(center)
*11*
], fill: rgb(0,0,0,255)),
[*ROR* Rotate right.],
)
#set align(left)
#box([
#align(center, [*Opcode 111001*])
#align(center, [
#rect([
*MOV RA, BYTE [RB + RC xSH IMM5]* \
_Load Byte, Register Offset_ \
Function Code: *1111* (0xF)
```
Reg[RA] = Load8(Reg[RB] + (Reg[RC] xSH IMM5))
```
], width: 100%)])
This instruction loads an 8-bit value into *Register A* from the address stored within *Register B*, plus the value of *Register C* shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV RA, INT [RB + RC xSH IMM5]* \
_Load Int, Register Offset_ \
Function Code: *1110* (0xE)
```
Reg[RA] = Load16(Reg[RB] + (Reg[RC] xSH IMM5))
```
], width: 100%)])
This instruction loads a 16-bit value into *Register A* from the address stored within *Register B*, plus the value of *Register C* shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV RA, LONG [RB + RC xSH IMM5]* \
_Load Long, Register Offset_ \
Function Code: *1101* (0xD)
```
Reg[RA] = Load32(Reg[RB] + (Reg[RC] xSH IMM5))
```
], width: 100%)])
This instruction loads a 32-bit value into *Register A* from the address stored within *Register B*, plus the value of *Register C* shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV BYTE [RB + RC xSH IMM5], RA* \
_Store Byte, Register Offset_ \
Function Code: *1011* (0xB)
```
Store8(Reg[RB] + (Reg[RC] xSH IMM5), Reg[RA])
```
], width: 100%)])
This instruction stores the contents of *Register A* as an 8-bit value to the address stored within *Register B*, plus the value of *Register C* shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV INT [RB + RC xSH IMM5], RA* \
_Store Int, Register Offset_ \
Function Code: *1010* (0xA)
```
Store16(Reg[RB] + (Reg[RC] xSH IMM5), Reg[RA])
```
], width: 100%)])
This instruction stores the contents of *Register A* as a 16-bit value to the address stored within *Register B*, plus the value of *Register C* shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV LONG [RB + RC xSH IMM5], RA* \
_Store Long, Register Offset_ \
Function Code: *1001* (0x9)
```
Store32(Reg[RB] + (Reg[RC] xSH IMM5), Reg[RA])
```
], width: 100%)])
This instruction stores the contents of *Register A* as a 32-bit value to the address stored within *Register B*, plus the value of *Register C* shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*LSH/RSH/ASH/ROR RA, RC, RB* \
_Various Shift By Register Amount_ \
Function Code: *1000* (0x8)
```
Reg[RA] = Reg[RC] xSH Reg[RB]
```
], width: 100%)])
This instruction shifts the contents of *Register C* by the contents of *Register B* and places the result in *Register A*. It is technically a single function code, but is split into several mnemonics for convenience. The *IMM5* shift value is ignored, and is taken from *Register B* instead.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*ADD RA, RB, RC xSH IMM5* \
_Add Register_ \
Function Code: *0111* (0x7)
```
Reg[RA] = Reg[RB] + (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction adds the contents of *Register B* to the contents of *Register C*, and stores the result into *Register A*. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SUB RA, RB, RC xSH IMM5* \
_Subtract Register_ \
Function Code: *0110* (0x6)
```
Reg[RA] = Reg[RB] - (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction subtracts the contents of *Register B* by the contents of *Register C*, and stores the result into *Register A*. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SLT RA, RB, RC xSH IMM5* \
_Set Less Than Register_ \
Function Code: *0101* (0x5)
```
Reg[RA] = Reg[RB] < (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction sets *Register A* to the result of an unsigned less-than comparison between the contents of *Register B* and the contents of *Register C*. The result is *1* if the comparison is true, and *0* otherwise. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SLT SIGNED RA, RB, RC xSH IMM5* \
_Set Less Than Register, Signed_ \
Function Code: *0100* (0x4)
```
Reg[RA] = Reg[RB] s< (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction sets *Register A* to the result of a signed less-than comparison between the contents of *Register B* and the contents of *Register C*. The result is *1* if the comparison is true, and *0* otherwise. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*AND RA, RB, RC xSH IMM5* \
_And Register_ \
Function Code: *0011* (0x3)
```
Reg[RA] = Reg[RB] & (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction performs a bitwise AND between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*XOR RA, RB, RC xSH IMM5* \
_Xor Register_ \
Function Code: *0010* (0x2)
```
Reg[RA] = Reg[RB] $ (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction performs a bitwise XOR between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*OR RA, RB, RC xSH IMM5* \
_Or Register_ \
Function Code: *0001* (0x1)
```
Reg[RA] = Reg[RB] | (Reg[RC] xSH IMM5)
```
], width: 100%)])
This instruction performs a bitwise OR between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*NOR RA, RB, RC xSH IMM5* \
_Nor Register_ \
Function Code: *0000* (0x0)
```
Reg[RA] = ~(Reg[RB] | (Reg[RC] xSH IMM5))
```
], width: 100%)])
This instruction performs a bitwise NOR between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The contents of *Register C* are first shifted in the manner specified.
#line(length: 100%)
], width: 100%)
#align(center, [*Opcode 110001*])
#box([
#align(center, [
#rect([
*MUL RA, RB, RC* \
_Multiply_ \
Function Code: *1111* (0xF)
```
Reg[RA] = Reg[RB] * Reg[RC]
```
], width: 100%)])
This instruction performs an integer multiplication between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*DIV RA, RB, RC* \
_Divide_ \
Function Code: *1101* (0xD)
```
Reg[RA] = Reg[RB] / Reg[RC]
```
], width: 100%)])
This instruction performs an unsigned integer division between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The result of the division is rounded down to the last whole integer.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*DIV SIGNED RA, RB, RC* \
_Divide, Signed_ \
Function Code: *1100* (0xC)
```
Reg[RA] = Reg[RB] s/ Reg[RC]
```
], width: 100%)])
This instruction performs a signed integer division between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The result of the division is rounded toward zero to a whole integer.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOD RA, RB, RC* \
_Modulo_ \
Function Code: *1011* (0xB)
```
Reg[RA] = Reg[RB] % Reg[RC]
```
], width: 100%)])
This instruction performs an unsigned modulo between the contents of *Register B* and the contents of *Register C*, and stores the result into *Register A*. The modulo is the remainder part of the result of an unsigned division.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*LL RA, RB* \
_Load Locked_ \
Function Code: *1001* (0x9)
```
Locked = TRUE
LockedAddress = Translate(Reg[RB])
Reg[RA] = Load32(Reg[RB])
```
], width: 100%)])
This instruction is used to implement atomic sequences. It loads the 32-bit contents of a naturally-aligned memory address within *Register B* into *Register A*. It also sets two "registers" associated with the current processor: a "locked" flag is set to TRUE, and a "locked address" is set to the physical address being accessed. Though it is implementation-dependent, these "registers" likely do not reside on the processor itself, and may be implemented in any way as long as it provides the same semantics.
If the *RFE* _Return From Exception_ instruction is executed on the current processor, the "locked" flag is cleared, causing a future *SC* instruction on this processor to fail. This is the only required behavior in a uniprocessor system. In a multiprocessor system, if any other processor performs a store instruction to this processor's "locked address", this processor's "locked" flag is cleared. This can be used to implement atomic sequences in non-privileged (i.e. usermode) code.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SC RA, RB, RC* \
_Store Conditional_ \
Function Code: *1000* (0x8)
```
IF Locked THEN
Store32(Reg[RB], Reg[RC])
END
Reg[RA] = Locked
```
], width: 100%)])
This instruction stores the current value of the processor's "locked" flag to *Register A*. If the "locked" flag is set, it stores the contents of *Register C* to the address contained within *Register B*, and (like any other store instruction) clears the "locked" flag of any other processor with the same physical address locked by the *LL* _Load Locked_ instruction.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MB* \
_Memory Barrier_ \
Function Code: *0011* (0x3)
```
// Possible implementation.
FlushWriteBuffer()
RetireAllLoads()
```
], width: 100%)])
This instruction need not be executed in a uniprocessor system. In a multiprocessor system, it ensures that, from the perspective of all other processors and I/O devices in the system, all prior writes performed by this processor have completed, as have all reads. One example of the usage of this instruction is to ensure data coherency after acquiring a spinlock.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*WMB* \
_Write Memory Barrier_ \
Function Code: *0010* (0x2)
```
// Possible implementation.
FlushWriteBuffer()
```
], width: 100%)])
This instruction ensures that, from the perspective of all other processors and I/O devices in the system, all writes performed by this processor have completed. One example of this instruction on a uniprocessor system is to ensure that a device has seen a sequence of writes to its registers before asking it to perform a command. An example on a multiprocessor system is to ensure data coherency before releasing a spinlock.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*BRK* \
_Breakpoint_ \
Function Code: *0001* (0x1)
```
Exception(BRK)
```
], width: 100%)])
This instruction causes a breakpoint exception. Its intended use is for debugging purposes. See @ecause.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*SYS* \
_System Service_ \
Function Code: *0000* (0x0)
```
Exception(SYS)
```
], width: 100%)])
This instruction causes a system service exception. It is useful for usermode to make a call into the system software to request a service (also called a system call or "syscall"). See @ecause.
#line(length: 100%)
], width: 100%)
#align(center, [*Opcode 101001 (Privileged Instructions)*])
These instructions all produce a *PRV* exception if executed while usermode is active. See @ecause.
#box([
#align(center, [
#rect([
*MFCR RA, CR* \
_Move From Control Register_ \
Function Code: *1111* (0xF)
```
Reg[RA] = ControlReg[CR]
```
], width: 100%)])
This instruction moves the contents of the specified control register into *Register A*. The 5-bit control register number is encoded in the place of *Register C*. See @controlregs for a full listing of control registers and their behaviors.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MTCR CR, RB* \
_Move To Control Register_ \
Function Code: *1110* (0xE)
```
ControlReg[CR] = Reg[RA]
```
], width: 100%)])
This instruction moves the contents of *Register B* into the specified control register. The 5-bit control register number is encoded in the place of *Register C*. *Register A* is ignored but should be encoded as zero. See @controlregs for a full listing of control registers and their behaviors.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*HLT* \
_Halt Until Next Interrupt_ \
Function Code: *1100* (0xC)
```
Halt()
```
], width: 100%)])
This instruction pauses execution of the processor until the next external interrupt is received. This can be used as a power-saving measure; for instance, executing *HLT* in a loop in the low priority idle thread of a multitasking kernel could greatly reduce the idle power consumption of the system. If external interrupts are disabled, this instruction causes the processor to halt until it is reset.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*RFE* \
_Return From Exception_ \
Function Code: *1011* (0xB)
```
Locked = FALSE
IF ControlReg[RS].ModeStack & T THEN
PC = ControlReg[TBPC]
ELSE
PC = ControlReg[EPC]
END
ControlReg[RS].ModeStack = ControlReg[RS].ModeStack >> 8
```
], width: 100%)])
This instruction pops the "mode stack" of the *RS* control register (see @rs), and returns execution to the program counter saved in either the *TBPC* or *EPC* control register, depending on if the *T* bit of *RS* was set or not, respectively (i.e., whether a TB miss handler was active or not; see @tbmiss). It also clears the "locked" flag, causing the next *SC* _Store Conditional_ instruction to fail.
#line(length: 100%)
], width: 100%)
#pagebreak(weak: true)
== Pseudo-Instructions <pseudoinstructions>
Some operations are synthesized out of simpler instructions, but are common or inconvenient enough to warrant a "pseudo-instruction", a fake instruction that the assembler converts into a corresponding hardware instruction sequence. The following is a (not necessarily exhaustive, depending on the assembler) list of common pseudo-instructions.
#box([
#align(center, [
#rect([
*B IMM21* \
_Unconditional Relative Branch_
```
BEQ ZERO, IMM21
```
], width: 100%)])
This pseudo-instruction performs an unconditional relative branch. This is synthesized out of the *BEQ* _Branch Equal_ instruction, by comparing the contents of the register *ZERO* with the number zero; by definition, this will always be true.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*RET* \
_Return_
```
JALR ZERO, LR, 0
```
], width: 100%)])
This pseudo-instruction performs a common return from subroutine operation. This is synthesized out of the *JALR* _Jump And Link, Register_ instruction, by performing a jump-and-link to the contents of the link register *LR*, and saving the result in *ZERO* (thereby discarding it).
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*JR RA* \
_Jump to Register_
```
JALR ZERO, RA, 0
```
], width: 100%)])
This pseudo-instruction performs a jump to the contents of *Register A*. This is synthesized out of the *JALR* _Jump And Link, Register_ instruction, by performing a jump-and-link to the contents of *Register A*, and saving the result in *ZERO* (thereby discarding it).
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV RA, RB* \
_Move Register_
```
ADD RA, RB, ZERO LSH 0
```
], width: 100%)])
This pseudo-instruction copies the contents of *Register B* into *Register A*. It is synthesized out of the *ADD* _Add Register_ instruction, by adding the contents of the *ZERO* register to the contents of *Register B* (which is a no-op), and saving the results in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*LI RA, IMM16* \
_Load 16-bit Immediate_
```
ADDI RA, ZERO, IMM16
```
], width: 100%)])
This pseudo-instruction loads a 16-bit immediate into *Register A*. It is synthesized out of the *ADDI* _Add Immediate_ instruction, by adding the immediate to the contents of the *ZERO* register and saving the results in *Register A*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*LA RA, IMM32* \
_Load 32-bit Immediate_
```
LUI RA, ZERO, (IMM32 >> 16)
ORI RA, RA, (IMM32 & 0xFFFF)
```
], width: 100%)])
This pseudo-instruction loads a 32-bit immediate into *Register A*. It is synthesized out of the *LUI* _Load Upper Immediate_ and *ORI* _Or Immediate_ instructions, by loading the upper 16 bits of the immediate into the register with *LUI*, and then bitwise OR-ing the lower 16 bits in with *ORI*.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*NOP* \
_No Operation_
```
ADDI ZERO, ZERO, 0
```
], width: 100%)])
This pseudo-instruction does nothing, by adding the contents of the *ZERO* register with the number zero and saving the result in the *ZERO* register.
Note that the instruction of all zeroes is _not_ a no-op, and this instruction set was carefully designed to ensure that that is an invalid instruction, so that exceptions will occur if the processor jumps off "into nowhere".
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*LSHI/RSHI/ASHI/RORI RA, RB, IMM5* \
_Various Shift By Immediate Amount_
```
ADD RA, ZERO, RB xSH IMM5
```
], width: 100%)])
These pseudo-instructions shift the contents of *Register B* by the 5-bit immediate, and saves the result in *Register A*. They are synthesized with the *ADD* _Add Register_ instruction, by adding the contents of *Register B* with the contents of the *ZERO* register, and shifting it in the specified manner.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV RA, BYTE/INT/LONG [IMM32]* \
_Load From 32-bit Address_
```
LUI RA, ZERO, (IMM32 >> 16)
MOV RA, BYTE/INT/LONG [RA + (IMM32 & 0xFFFF)]
```
], width: 100%)])
These pseudo-instructions load a value into *Register A* from a full 32-bit address. They are synthesized with *LUI* _Load Upper Immediate_ and the appropriate offsetted load instructions. The upper 16 bits of the address are loaded into the register with *LUI*, and then a load is done into the register with the offset being the low 16 bits of the address.
#line(length: 100%)
], width: 100%)
#box([
#align(center, [
#rect([
*MOV BYTE/INT/LONG [IMM32], RA, TMP=RB* \
_Store To 32-bit Address_
```
LUI RB, ZERO, (IMM32 >> 16)
MOV BYTE/INT/LONG [RB + (IMM32 & 0xFFFF)], RA
```
], width: 100%)])
These pseudo-instructions store a value into a full 32-bit address. They are synthesized with *LUI* _Load Upper Immediate_ and the appropriate offsetted store instructions. The upper 16 bits of the address are loaded into a user-supplied temporary register with *LUI*, and then a store is done with the offset being the low 16 bits of the address.
#line(length: 100%)
], width: 100%) |
|
https://github.com/CheneyNine/Resume-in-Typst-Template | https://raw.githubusercontent.com/CheneyNine/Resume-in-Typst-Template/main/template.typ | typst | // 字体
#let font = (
main: "PingFang SC", // 更改主要字体为苹方
mono: "PingFang SC", // 更改等宽字体为苹方,若需要等宽效果,可能需要找到适合的等宽字体或保留原设置
cjk: "PingFang SC", // 保持 CJK 字体设置为苹方,确保中文显示一致性
)
#let cell = box.with()
// 图标
#let icon(path) = box(
baseline: 0.125em,
height: 1.0em,
width: 1.25em,
align(center + horizon, image(path))
)
#let faAngleRight = icon("icons/fa-angle-right.svg")
// 主体
#let resume(
size: 10pt,
themeColor: rgb(38, 38, 125),
top: 1.5cm,
bottom: 2cm,
left: 2cm,
right: 2cm,
photograph: "",
photographWidth: 0em,
gutterWidth: 0em,
backgroundImage: "",
header,
body
) = {
// 页边距设定
set page(paper: "a4", numbering: none, margin: (
top: top,
bottom: bottom,
left: left,
right: right,
),
background:image(backgroundImage)
)
// 基础字体设定
set text(font: (font.main, font.cjk), size: size, lang: "zh")
// 标题及小标题样式
show heading: set text(themeColor, 1.1em)
show heading: set block(spacing: 0.85em)
// 二级标题下加一条横线
show heading.where(level: 2): it => stack(
v(0em), //段前
it,
v(0.25em), //线条前
line(start:(0%,0%),end:(100%,0%),length: 50%, stroke: 0.06em + themeColor,),
v(0em), //线条后
)
// 链接颜色
show link: set text(fill: themeColor)
// 主体设定
set par(justify: true,leading:0.5em)
show par: set block(spacing: 0em)
// 首部与照片
grid(
columns: (auto, 1fr, photographWidth),
gutter: (gutterWidth, 0em),
header,
if (photograph != "") {
image(photograph, width: photographWidth)
}
)
body
}
// 个人信息
#let info(
color: black,
..infos
) = {
set text(font: (font.mono, font.cjk), fill: color)
set par(justify: true)
infos.pos().map(dir => {
box({
if "icon" in dir {
if (type(dir.icon) == "string") {
icon(dir.icon)
} else {
dir.icon
}
}
h(0.15em)
if "link" in dir {
underline(link(dir.link, dir.content))
} else {
dir.content
}
})
}).join(h(0.5em) + " " + h(0.5em))
}
// 日期: 颜色变灰
#let date(body) = text(
fill: rgb(128, 128, 128),
size: 0.9em,
body
)
// 技术: 字体变细
#let tech(body) = block({
set text(weight: "extralight")
body
})
// 项目
#let item(
title,
desc,
endnote
) = {
grid(
columns: (41%, 2fr, auto),
gutter: (0.5em),
title, desc, endnote
)
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1D80.typ | typst | Apache License 2.0 | #let data = (
("LATIN SMALL LETTER B WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER D WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER F WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER G WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER K WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER L WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER M WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER N WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER P WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER R WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER S WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER ESH WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER V WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER X WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER Z WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER A WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER ALPHA WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER D WITH HOOK AND TAIL", "Ll", 0),
("LATIN SMALL LETTER E WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER OPEN E WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER REVERSED OPEN E WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER I WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER OPEN O WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER ESH WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER U WITH RETROFLEX HOOK", "Ll", 0),
("LATIN SMALL LETTER EZH WITH RETROFLEX HOOK", "Ll", 0),
("MODIFIER LETTER SMALL TURNED ALPHA", "Lm", 0),
("MODIFIER LETTER SMALL C", "Lm", 0),
("MODIFIER LETTER SMALL C WITH CURL", "Lm", 0),
("MODIFIER LETTER SMALL ETH", "Lm", 0),
("MODIFIER LETTER SMALL REVERSED OPEN E", "Lm", 0),
("MODIFIER LETTER SMALL F", "Lm", 0),
("MODIFIER LETTER SMALL DOTLESS J WITH STROKE", "Lm", 0),
("MODIFIER LETTER SMALL SCRIPT G", "Lm", 0),
("MODIFIER LETTER SMALL TURNED H", "Lm", 0),
("MODIFIER LETTER SMALL I WITH STROKE", "Lm", 0),
("MODIFIER LETTER SMALL IOTA", "Lm", 0),
("MODIFIER LETTER SMALL CAPITAL I", "Lm", 0),
("MODIFIER LETTER SMALL CAPITAL I WITH STROKE", "Lm", 0),
("MODIFIER LETTER SMALL J WITH CROSSED-TAIL", "Lm", 0),
("MODIFIER LETTER SMALL L WITH RETROFLEX HOOK", "Lm", 0),
("MODIFIER LETTER SMALL L WITH PALATAL HOOK", "Lm", 0),
("MODIFIER LETTER SMALL CAPITAL L", "Lm", 0),
("MODIFIER LETTER SMALL M WITH HOOK", "Lm", 0),
("MODIFIER LETTER SMALL TURNED M WITH LONG LEG", "Lm", 0),
("MODIFIER LETTER SMALL N WITH LEFT HOOK", "Lm", 0),
("MODIFIER LETTER SMALL N WITH RETROFLEX HOOK", "Lm", 0),
("MODIFIER LETTER SMALL CAPITAL N", "Lm", 0),
("MODIFIER LETTER SMALL BARRED O", "Lm", 0),
("MODIFIER LETTER SMALL PHI", "Lm", 0),
("MODIFIER LETTER SMALL S WITH HOOK", "Lm", 0),
("MODIFIER LETTER SMALL ESH", "Lm", 0),
("MODIFIER LETTER SMALL T WITH PALATAL HOOK", "Lm", 0),
("MODIFIER LETTER SMALL U BAR", "Lm", 0),
("MODIFIER LETTER SMALL UPSILON", "Lm", 0),
("MODIFIER LETTER SMALL CAPITAL U", "Lm", 0),
("MODIFIER LETTER SMALL V WITH HOOK", "Lm", 0),
("MODIFIER LETTER SMALL TURNED V", "Lm", 0),
("MODIFIER LETTER SMALL Z", "Lm", 0),
("MODIFIER LETTER SMALL Z WITH RETROFLEX HOOK", "Lm", 0),
("MODIFIER LETTER SMALL Z WITH CURL", "Lm", 0),
("MODIFIER LETTER SMALL EZH", "Lm", 0),
("MODIFIER LETTER SMALL THETA", "Lm", 0),
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/titleize/0.1.0/lib.typ | typst | Apache License 2.0 | #let _plugin = plugin("titleize.wasm")
#let titlecase(data) = {
str(_plugin.titlecase(bytes(data)))
} |
https://github.com/EricWay1024/Homological-Algebra-Notes | https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/ha/4-enough.typ | typst | #import "../libs/template.typ": *
// == Projective and Injective Modules
// Recall $P$ is projective if $Hom(A)(P, -)$ is exact and $I$ is injective if $Hom(A)(-, I)$ is exact.
// #lemma[
// $P$ is projective if and only if it has the lifting property (refer to earlier).
// $I$ is injective if and only if it has the extension property.
// ]
= Enough Projectives and Injectives
<enough-proj-inj>
#definition[
An abelian category $cA$ is said to *have enough projectives* (resp. *injectives*) if for any object $M$ there is an epimorphism $P-> M -> 0$ where $P$ is projective (resp. a monomorphism $0 -> M->I$ where $I$ is injective).
]
For most of our homological algebra to work, an abelian category needs to have enough projectives and injectives. We will show that $RMod$ has enough projectives and injectives.
== $RMod$ has Enough Projectives
#lemma[Free $R$-modules are projective.]
#proof[
Let $F eq plus.circle.big_(i in I) R x_i$ be a free $R$-module with basis
$lr({x_i colon i in I})$. Suppose $pi:A-> B$ is an epimorphism and $f : F->B$ is a morphism, as in the following diagram:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBpiBdUkANwEMAbAVxiRACEQBfU9TXfIRQAmclVqMWbAAzdeIDNjwEi0sdXrNWiEAEE5fJYKJlp4zVJ0AxbuJhQA5vCKgAZgCcIAWyQBmajgQSGoSWmyuBiAe3sEBQYjEPG6ePoiiIIGxoZYKWJHRqf4Z8ekMWGDaIFB0cAAW9iAakpWMaLV0tlxAA
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((1, 1), [$B$]),
node((1, 2), [$0$]),
node((1, 0), [$A$]),
node((0, 1), [$F$]),
arr((0, 1), (1, 1), [$f$]),
arr((1, 1), (1, 2), []),
arr((1, 0), (1, 1), [$pi$]),
arr((0, 1), (1, 0), [$alpha$], label-pos:-1em, "dashed"),
))
Since $pi$ is surjective, for each $i$ there is some $a_i in A$ with
$pi lr((a_i)) eq f lr((x_i))$. Define map
$ alpha colon F arrow.r A$ by $alpha lr((x_i)) eq a_i$ and we have $f = pi oo alpha$.
]
#proposition[$P$ is a projective $R$-module if and only if $P$ is a direct summand of a free module.
]
<projective-summand>
#proof[
Assume $P$ is a projective. Then we can always find a free module $F=R^(ds I)$ such that $g: F -> P$ is onto. Using the lifting property,
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBoBGAXVJADcBDAGwFcYkQAxEAX1PU1z5CKchWp0mrdgAUefEBmx4CRAExiaDFm0Qhic-kqFFRxcVqm7Z3cTCgBzeEVAAzAE4QAtkjIgcEJHJeVw9vRFE-AMRVYJB3LyQAZhp-HxpGLDAdECh6OAALOxBNSWyYAA8sOBwEWPiw5MjAku12LCgeSm4gA
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((1, 0), [$F$]),
node((1, 1), [$P$]),
node((1, 2), [$0$]),
node((0, 1), [$P$]),
arr((1, 0), (1, 1), [$g$]),
arr((1, 1), (1, 2), []),
arr((0, 1), (1, 0), label-pos:-1em, [$exists$], "dashed"),
arr((0, 1), (1, 1), [$id$]),
))
So there exists a section $P-> F$ in the #sest $ ses(K, F, P) $
and hence $F iso K ds P$, where $K = Ker(g)$. This shows that $P$ is a direct summand of a free module.
// [This is equivalent to find some idempotent $p: R^(ds I) -> R^(ds I)$ such that $p^2= p$. ? ] #TODO
Now we show a direct summand of a free module is projective.
Suppose that $P$ is a direct summand of a free module. Then there
exists some $R$-module $P^prime$ such that $P xor P^prime$ is free. Let
$pi colon A arrow.r B$ be a surjection and let $f colon P arrow.r B$ be
some map. Let $f^prime colon P xor P^prime arrow.r B$ be the map
$f^prime lr((p comma p^prime)) eq f lr((p))$. Since $P xor P^prime$ is
free, hence projective, $f^prime$ has a lift
$alpha^prime colon P xor P^prime arrow.r A$. Now define
$alpha colon P arrow.r A$ by
$alpha lr((p)) eq alpha^prime lr((p comma 0))$ and it lifts $f$, showing that $P$ is projective.
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBoAmAXVJADcBDAGwFcYkQAhEAX1PU1z5CKch<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((2, 1), [$B$]),
node((2, 2), [$0$]),
node((2, 0), [$A$]),
node((1, 1), [$P ds P'$]),
node((0, 1), [$P$]),
arr((2, 0), (2, 1), [$pi$], label-pos: -1em),
arr((2, 1), (2, 2), []),
arr((0, 1), (2, 1), [$f$], curve: 30deg),
arr((1, 1), (2, 1), [$f'$], label-pos: -1em),
arr((1, 1), (2, 0), [$alpha'$], "dashed"),
arr((0, 1), (2, 0), [$alpha$], curve: -30deg, "dashed"),
arr((0, 1), (1, 1), [$i$], label-pos: -1em),
))
]
#corollary[
$RMod$ has enough projectives.
]
#proof[
For any module $M$, we can find a free (and thus projective) module $F$ with a surjection $F-> M-> 0. $
]
== $Ab$ has Enough Injectives
#lemma("Baer's Criterion")[
A right (resp. left) $R$-module $M$ is injective #iff for every right (resp. left) ideal $I$ of $R$, every module homomorphism $I -> M$ can be extended to $R -> M$.
]
<baer-cri>
#proof[@notes[Theorem 5.8] and @rotman[Theorem 3.30].
"$=>$". Since any right ideal $I$ is a submodule of $R$, we can extend $I -> M$ to $R ->M$ simply by the definition of injectivity of $M$.
"$arrow.double.l$".
// https://t.yw.je/#N4Igdg9gJgpg<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$A$]),
node((0, 1), [$A'$]),
node((0, 2), [$A''$]),
node((0, 3), [$B$]),
node((1, 0), [$M$]),
arr((0, 0), (0, 1), [], "inj"),
arr((0, 1), (0, 2), [], "inj"),
arr((0, 2), (0, 3), [], "inj"),
arr((0, 0), (1, 0), [$f$]),
arr((0, 1), (1, 0), [$alpha'$], "dashed"),
arr((0, 2), (1, 0), [$alpha''$], curve: 10deg, "dashed"),
arr((0, 3), (1, 0), [], curve: 30deg, "dashed"),
))
Fix some injection $i colon A arrow.r B$ of
$R$-modules, and some map $f colon A arrow.r M$. Without loss of
generality, assume that $A subset.eq B$ and $i$ is the inclusion. We would like to extend $f$ to some map $B -> M$.
[Construction of $A'$ and $alpha' : A' -> M$.] Let
$Sigma$ be the set whose elements are $R$-module maps
$alpha^prime colon A^prime arrow.r M$, where
$A subset.eq A^prime subset.eq B$ and $alpha^prime$ extends $f$.
We may give this set a partial order by
saying that $alpha^prime lt.eq alpha^(prime prime)$ when
$A^prime subset.eq A^(prime prime)$ and $alpha^(prime prime)$ extends
$alpha^prime$.
Suppose that $alpha_1 lt.eq alpha_2 lt.eq dots.h$ is an
ascending chain in $Sigma$, with corresponding modules
$A_1 subset.eq A_2 subset.eq dots.h$.
Let $A^prime eq union.big A_n$, and
define $alpha^prime colon A^prime arrow.r M$ by
$alpha^prime lr((a)) eq alpha_i lr((a))$ for $a in A_i$.
It is easy to
check that $alpha^prime$ is a well-defined element of $Sigma$, and it is
an upper bound on the chain \(in other words, we take the colimit
of the chain).
Since $Sigma$ is a partially ordered set in which every ascending chain
has an upper bound, by Zorn’s Lemma $Sigma$ has a maximal element,
which we call $alpha^prime colon A^prime -> M$.
To show that $M$
is injective, we need to show that $A^prime eq B$, since we then have an
extension $alpha$ of $f$ to $B$.
[Construction of $phi : R-> M$.] Suppose that $A^prime eq.not B$. Let $b in B without A^prime$. Let
$ I eq { r in R:b r in A^prime} $ Then $I$ is a right ideal of
$R$, and we have a map
$
tilde(phi):I &->M \
r &|-> alpha^prime lr((b r)).
$
By assumption, this extends to a map $phi colon R arrow.r M$.
[Construction of $alpha'' : A'' -> M$.] Define
$ A^(prime prime) eq A^prime plus R b = {a + r b : a in A', r in R} subset.eq B $ We
claim that there is a well-defined map
$ alpha^(prime prime) colon A^(prime prime) &arrow.r M \ a plus b r &arrow.r.bar alpha^prime lr((a)) plus phi lr((r)), $
where $a in A^prime$ and $r in R$. To see that this is well-defined,
suppose that $a plus b r eq a^prime plus b r^prime$
where $a, a' in A'$ and $r, r' in R$.
Then
$ a minus a^prime eq b lr((r^prime minus r)) in A^prime sect b R dot.basic $
From this we see $r - r' in I$, and then we have
$ phi lr((r^prime minus r))
= alpha^prime lr((b lr((r^prime minus r)))) = alpha^prime lr((a minus a^prime)). $
Therefore, it follows that
$alpha^prime lr((a)) plus phi lr((r)) eq alpha^prime lr((a^prime)) plus phi lr((r^prime))$
so $alpha^(prime prime)$ is well-defined. But then $alpha^(prime prime)$
strictly extends $alpha^prime$, contradicting maximality of
$alpha^prime$. Hence $A^prime eq B$, so $M$ is injective.
]
#definition[
Let $R$ be an integral domain. A $R$-module $M$ is called *divisible* if, for all $r in R without {0}$, every element $m$ of $M$ can be "divided"
by $r$, in the sense that there exists an element $m^prime$ in $M$ such that
$m eq r m^prime$.
Equivalently, the multiplication by any non-zero $r in R$ defines a surjective map from $M$ to $M$.
]
#corollary[
If $R$ is a PID, then an $R$-module $M$ is injective if
and only if it is divisible.
]
// That is, for all $m in M$ and
// $r in R without brace.l 0 brace.r$ there exists $m' in M$ such that
// $m eq r m'$.
// Recall that a PID is an integral domain in which every ideal is principal, or can be generated by a single element.
// [Unfortunately the notations are confusing, because we use $I$ to represent an ideal in the last theorem but the same letter for an $R$-module here.]
// The details of the proof can get in the way of the intuitive idea, which
// is quite simple. Maybe try proving it yourself before reading on \(use
// Baer’s Criterion).
#proof[@rotman[Corollary 3.35] and @notes[Corollary 5.9].
Let $M$ be an injective $R$-module, and let $m in M$ and
$r in R without brace.l 0 brace.r$. Set $J eq r R$ (which is an ideal of $R$) and define
$f colon J arrow.r M$ by $f lr((r)) eq m$. By Baer’s Criterion, we may
extend $f$ to a homomorphism $tilde(f) colon R arrow.r M$. Then
$ m eq f lr((r)) = tilde(f)(r)eq tilde(f) lr((r dot.op 1)) eq r dot.op tilde(f) lr((1)). $
So taking $m' eq tilde(f) lr((1))$, we see that $M$ is divisible.
Suppose conversely that $M$ is a divisible $R$-module. Let $J$ be an
ideal of $R$ and let $f colon J arrow.r M$ be a module homomorphism. If
$J$ is the zero ideal, then trivially we may extend $f$ to the zero
homomorphism $R arrow.r M$. Assume that $J$ is nonzero.
Since $R$ is a PID, we have $J eq R r$ for some nonzero $r in J$. Let
$m eq f lr((r))$. Then since $M$ is divisible, there is some $m' in M$
such that $m eq r m'$. Define $tilde(f) colon R arrow.r M$ by
$tilde(f) lr((1)) eq m'$. Clearly $tilde(f)$ is an extension of $f$, so
$M$ is injective by Baer’s Criterion.
]
#corollary[
In $Ab$, $QQ, ZZ_(p^ infinity) = ZZ[1 / p] over ZZ, QQ over ZZ$ are injective.
]
#remark[
@weibel[Example 2.3.3]. Every injective abelian group $I = I_"tor" ds I_"free"$, where $I_"free"$ (the torsion-free part) is a $QQ$-vector space and $I_"tor"$ (the torsion part) is a direct sum of copies of $ZZ_(p^ infinity)$. In particular, $QQ over ZZ = ds_p ZZ_(p ^ infinity)$.
]
#lemma[
Direct sums of projectives are projectives.
Dually, products of injectives are injectives.
]
#proof[
Suppose ${P_i : i in I}$ is a family of projective modules. Then for each $i in I$, by @projective-summand we can write $F_i = P_i xor Q_i$ for some free $R$-module $F_i$ and $R$-module $Q_i$. Then
$
plus.circle.big_(i in I) F_i = plus.circle.big_(i in I) P_i xor plus.circle.big_(i in I) Q_i
$
Since $plus.circle.big_(i in I) F_i$ is also a free module, $plus.circle.big_(i in I) P_i$ is also projective.
// The first half is easily seen from
// $ hom (plus.circle.big_i P_i, -) = product_i hom (P_i, -) $
// The second half is the dual statement.
]
#lemma[
Let $A$ be an abelian group. Then for any non-zero $a in A$, there exists a group homomorphism $phi : A -> QQ over ZZ$ such that $phi(a) != 0$.
]
<map-to-q-over-z>
#proof[
By the injectivity of $QQ over ZZ$, it suffices to find a group homomorphism $psi : angle.l a angle.r -> QQ over ZZ$ and then extend $psi$ to $phi: A -> QQ over ZZ$. To obtain such $psi$, it suffices to give an element $psi(a) in QQ over ZZ$. We consider the order of $a$ in $A$:
- If $|a| = infinity$, then we can set $psi(a)$ as any nonzero element of $QQ over ZZ$;
- If $|a| = m > 1$, then we set $psi(a) = 1/m + ZZ$.
]
#proposition[
$Ab$ has enough injectives.
]
<ab-enough>
#proof[
Define a map
$
I : Ab &-> Ab \
A &|-> product_(hom_Ab (A, QQ over ZZ)) QQ over ZZ.
$
For any $A in Ab$, $I(A)$ is injective as a product of injectives $QQ over ZZ$.
Consider canonical map
$
e_A: A &-> I(A) \
a &|-> (phi(a))_(phi in hom_Ab (A, QQ over ZZ)),
$
where, since $I(A)$ is a product, we need to define for each $phi in hom_Ab (A, QQ over ZZ)$ the component $e_(a, phi) : A -> QQ over ZZ$, which we just define to be $phi$ itself.
Note that $e_A$ is an injective map by @map-to-q-over-z.
Thus we have $0 -> A ->^(e_A) I(A)$ with $I(A)$ injective for any $A in Ab$, showing that $Ab$ has enough injectives.
// [See https://math.stackexchange.com/questions/4071941/category-of-abelian-groups-has-enough-injectives.]
]
#endlec(6)
// = injective and projective and adjoints
== $RMod$ has Enough Injectives
#proposition[
If an additive functor $R: cB -> cA$ between abelian categories is right adjoint to an exact functor and $I$ is injective in $cB$, then $R(I)$ is injective in $cA$.
Dually, if an additive functor $L: cA -> cB$ is left adjoint to an exact functor and $P$ is projective in $cA$, then $L(P)$ is projective in $cB$.
]
#proof[
@notes[Lemma 5.25] and @weibel[Proposition 2.3.10].
We want to show that
$ Hom(A)(-, R(I)) $ is exact.
We have
$ Hom(A)(-, R(I)) iso Hom(B)(L(-), I ) $
but $L$ is exact by assumption and $Hom(B)(-, I)$ is exact because $I$ is injective in $cB$, so $Hom(B)(L(-), I )$ is a composition of exact functors and thus exact.
]
With this proposition, we can prove that an abelian category has enough projectives or injectives by constructing adjunctions.
#corollary[
If $I$ is an injective abelian group, then $hom_Ab (R, I)$ is an injective #rrm.
]
#proof[
By @hom-module, $hom_Ab (R, I)$ is indeed a right $R$-module. Note that $hom_Ab (R, -)$ is right adjoint to $(- tpr R)$, which is simply the forgetful functor $ModR -> Ab$ and is thus exact. Therefore $hom_Ab (R, I)$ is injective in $RMod$.
]
#example[
$hom_Ab (R, QQ over ZZ)$ is injective.
]
#proposition[
$RMod$ has enough injectives.
]
#proof[
Define map
$
I : RMod &-> RMod \
M &|-> product_(homr(M, hom_Ab (R, QQ over ZZ))) hom_Ab (R, QQ over ZZ)
$
For any left $R$-module $M$,
$I(M)$ is injective as a product of injectives, and there is a canonical morphism
$
e_M: M &-> I(M ) \
m &|-> (phi(m))_(phi in homr(M, hom_Ab (R, QQ over ZZ)))
$
// Exercise: $e_M$ is one-to-one (mono). (like what we did before.) [TODO]
We would like to show that $e_M$ is an injective function.
We only need to show that for any $0 != m in M$, there exists $phi : M -> hom_Ab (R, QQ over ZZ)$ such that $phi(m) != 0$. Notice that we have $ phi in homr(M, hom_Ab (R, QQ over ZZ)) iso hom_Ab (M, QQ over ZZ) $
as before.
Hence we only need to find some $phi : M -> QQ over ZZ$ in $Ab$ so that $phi(m) != 0$, which is given by @map-to-q-over-z.
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum-align_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test valid number align values (horizontal and vertical)
// Ref: false
#set enum(number-align: start)
#set enum(number-align: end)
#set enum(number-align: left)
#set enum(number-align: center)
#set enum(number-align: right)
#set enum(number-align: top)
#set enum(number-align: horizon)
#set enum(number-align: bottom)
|
https://github.com/Devansh0210/report_template_typst | https://raw.githubusercontent.com/Devansh0210/report_template_typst/main/test.typ | typst | #let title_page(
title: "",
authors: "",
body
) = {
set page(
paper: "a4",
margin: (x: 2cm, y: 2cm),
)
set heading(numbering: "1.1.1")
show heading: it => block[
#v(0.5em)
#it.body
#v(0.3em)
]
set par(justify: true)
set text(font: "Noto Serif", size: 12pt)
v(1fr)
align(right)[
#text(title, size: 30pt)
#text(authors, size: 15pt)
]
v(1fr)
pagebreak()
counter(page).update(0)
// counter(page).update(0)
outline(
title: "Table of Contents",
depth: 3,
indent: true,
fill: repeat[.]
)
page(footer: [
#align(center)[#line(length: 100%, angle: 0deg)]
#set align(right)
#set text(8pt)
#counter(page).display(
"1 / 1",
both: true,
)
],
body
)
}
#show: title_page.with(
title: "Digital Control System",
authors: "<NAME>",
)
= Introduction
#lorem(200)
== Section-2
#lorem(100)
= Conclusions
#lorem(400) |
|
https://github.com/andreasKroepelin/TypstJlyfish.jl | https://raw.githubusercontent.com/andreasKroepelin/TypstJlyfish.jl/main/examples/long.typ | typst | MIT License | #import "../typst/lib.typ": *
#read-julia-output(json("long-jlyfish.json"))
#jl(recompute: false, ```julia
seconds = @elapsed sleep(10)
@show seconds
"Wow, this took $(round(Int, seconds)) seconds!"
```)
#jl(`"This is so fast!"`)
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/3-state/webxr-frameworks.typ | typst | Wie im @webgl-chapter definiert, ermöglicht die Kombination der WebXR Device API die Entwicklung von Augmented Reality Anwendungen im Web. Um den Entwicklungsprozess zu vereinfachen, existieren verschiedene Frameworks, die die Funktionalitäten von WebGL und WebXR abstrahieren und vereinfachen. Nachfolgend wird eine Auswahl an Frameworks vorgestellt, die für die Entwicklung von WebXR-Anwendungen besonders relevant sind. Diese Übersicht stellt keine vollständige Liste dar, sondern zeigt die relevantesten Frameworks, die für die Entwicklung von WebXR-Anwendungen verwendet werden können. Die Relevanz wurde hierbei anhand der Anzahl der GitHub-Sterne und npm-Downloads bestimmt @frameworks-stars @frameworks-download. Des Weiteren wird in der Übersicht der Funktionen einzelner Frameworks auf Aspekte eingegangen, die für die Entwicklung von WebXR-Anwendungen von besonderer Relevanz sind. Es findet jedoch nur ein Überblick über die Funktionalitäten statt, um die Unterschiede und Gemeinsamkeiten der Frameworks zu verdeutlichen.
=== Babylon.js
Babylon.js ist ein Open-Source-Framework für die Entwicklung von 3D-Anwendungen im Web. Es basiert auf WebGL und ermöglicht das Erstellen komplexer 3D-Szenen. Das Framework bietet eine Vielzahl von Funktionen, die die Entwicklung von 3D-Anwendungen vereinfachen.
Für die Darstellung von 3D-Anwendungen verwendet Babylon.js einen Szenengraphen, der die Struktur einer Szene definiert. Der Szenengraph besteht aus vordefinierten Objekten wie Lichtquellen, Kameras, Meshes und Animationen. Diese Objekte können in einer Hierarchie angeordnet werden, um die Struktur der Szene zu definieren @babylonjs-graph. Dies ermöglicht einen modularen Aufbau komplexer Szenen und die Wiederverwendung häufig genutzter Elemente. Hierbei wird jedes Objekt sowie die Szene selber als Instanz einer Klasse definiert, die spezifische Eigenschaften und Methoden besitzt. Desweiteren bietet Babylon.js weitere Module und Funktionen, welche spezifische Anforderungen an 3D-Anwendungen abdecken. Dazu gehört eine Physik-Engine sowie ein Partikelsystem. Im Folgenden wird jedoch der Fokus auf die Funktionen und Anbindung an die WebXR Device API gelegt.
Babylon.js unterstützt das Erstellen von WebXR-Anwendungen ohne zusätzliche Bibliotheken. Um die Arbeit mit der WebXR Device API zu erleichtern und alle Voraussetzungen für eine korrekte Darstellung und Interaktion zu bieten, stellt Babylon.js die Klassen WebXRExperienceHelper und WebXRDefaultExperience zur Verfügung. Beide Klassen bündeln die notwendigen Funktionen und Voraussetzungen, um die Entwicklung von WebXR-Anwendungen zu ermöglichen.
Die Klasse WebXRExperienceHelper initialisiert die XR-Szene mit allen notwendigen Elementen und Parametern. Es wird eine XR-Kamera erstellt, die für die Darstellung der Szene aus der Perspektive des Benutzers erforderlich ist. Darüber hinaus übernimmt der WebXRExperienceHelper die Initialisierung des Features Managers, welcher für die Verwaltung und Ergänzung spezifischer Funktionen innerhalb der XR-Szene zuständig ist. Zudem bietet die Klasse Hilfsfunktionen an, um die XR-Session zu starten und zu beenden @babylonjs-webxr-experience-helper.
#let code = ```js
const xrHelper = await WebXRExperienceHelper.CreateAsync(scene);
```
#figure(
code,
caption: [Erstellen eines WebXRExperienceHelper in Babylon.js]
)
Die Klasse WebXRDefaultExperience erweitert die Funktionalitäten des WebXRExperienceHelper und bietet zusätzliche Funktionen, die für die Entwicklung von WebXR-Anwendungen nützlich sind. Zunächst wird ein HTML-Button bereitgestellt, welcher es ermöglicht, in die XR-Sitzung einzutreten. Parallel dazu initialisiert der Helper die Input Klasse, welche die Controller initialisiert und damit die Interaktion innerhalb der XR-Umgebung ermöglicht @babylonjs-webxr-experience-helper.
#let code = ```js
var defaultXR = await WebXRDefaultExperience.CreateAsync(scene, {});
```
#figure(
code,
caption: [Initialisierung der WebXRDefaultExperience-Klasse in Babylon.js]
)
Babylon.js bietet somit eine umfassende Unterstützung für die Entwicklung von WebXR-Anwendungen und ermöglicht es Entwicklern, komplexe 3D-Szenen zu erstellen und in einer XR-Umgebung darzustellen. Durch die Bereitstellung von Klassen wie WebXRExperienceHelper und WebXRDefaultExperience wird die Arbeit mit der WebXR Device API vereinfacht und die Entwicklung von WebXR-Anwendungen beschleunigt.
=== Three.js
Three.js ist ein weiteres Open-Source-Framework zur Entwicklung von 3D-Anwendungen im Web und basiert ebenfalls auf WebGL. Es bietet eine umfangreiche Auswahl an Funktionen, die die Erstellung von 3D-Szenen vereinfachen.
Innerhalb von Three.js wird ein Szenengraph verwendet, um die Struktur einer Szene zu definieren. Dieser Szenengraph besteht aus verschiedenen Objekten wie Lichtquellen, Kameras, Meshes und Animationen, die in einer Hierarchie angeordnet werden können. Die Definition von Objekten als Instanzen von Klassen ermöglicht eine modulare Struktur und fördert die Wiederverwendung von Elementen.
Die Integration mit der WebXR Device API erfolgt in Three.js über die Klasse WebGLRenderer. Diese Klasse initialisiert die Three.js-Szene und übernimmt die Verwaltung der Anwendung. Um die XR Device API zu aktivieren, muss die Eigenschaft xr.enabled auf true gesetzt werden wodurch die Klasse um die interne WebXRManager Klasse erweitert wird @threejs-webxr.
#let code = ```js
const renderer = new WebGLRenderer();
renderer.xr.enabled = true;
```
#figure(
code,
caption: [Erstellen eines WebGLRenderers in Three.js mit aktivierter WebXR Device API]
)
Im Vergleich zu Babylon.js, das spezifische Klassen wie WebXRExperienceHelper oder WebXRDefaultExperience bietet, erfolgt die Integration mit der WebXR Device API in Three.js direkt über die WebGLRenderer-Klasse. Zudem werden weniger Hilfsfunktionen bereitgestellt, was zu einer schlankeren API führt und den Fokus auf selbst implementierte Funktionen legt.
=== A-Frame
A-Frame ist ein weiteres Open-Source-Framework für die Erstellung von AR und VR Anwendungen im Web, das auf der Entity-Component-System-Architektur basiert @a-frame-introduction. Es baut hierbei auf Three.js auf und bietet eine deklarative HTML-Schnittstelle zur Erstellung von AR-Szenen.
In A-Frame wird eine Szene durch HTML-Tags dargestellt, wobei jede Entität als eigenständiges HTML-Element repräsentiert wird. Entitäten können durch das Hinzufügen von Komponenten, die Funktionen und Eigenschaften definieren, erweitert werden. Dies ermöglicht eine hohe Modularität und Wiederverwendbarkeit von erstellten Elementen und Logiken @a-frame-introduction.
Die Interaktion mit der WebXR Device API wird in A-Frame nahtlos umgesetzt. Das Framework passt sich automatisch an die Anforderungen von AR-Sessions an. Entwickler können durch einfaches Hinzufügen spezifischer AR-Komponenten immersive AR-Szenen erstellen @a-frame-introduction.
#let code = ```html
<a-scene xr="true">
<a-entity camera position="0 1.6 0"></a-entity>
</a-scene>
```
#figure(
code,
caption: [Erstellen einer AR-Szene in A-Frame]
)
Im Gegensatz zu komplexeren Frameworks wie Three.js oder Babylon.js, die oft umfangreiche Programmkenntnisse erfordern, ermöglicht A-Frame die Erstellung von AR-Anwendungen durch eine intuitive und deklarative HTML-Schnittstelle. Dies macht das Framework besonders zugänglich für Web-Entwickler und reduziert die Einarbeitungszeit erheblich @a-frame-introduction. |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/stroke_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 29-55 expected "solid", "dotted", "densely-dotted", "loosely-dotted", "dashed", "densely-dashed", "loosely-dashed", "dash-dotted", "densely-dash-dotted", "loosely-dash-dotted", array, dictionary, none, or auto
// #line(length: 60pt, stroke: (paint: red, dash: "dash")) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10A0.typ | typst | Apache License 2.0 | #let data = (
("GEORGIAN CAPITAL LETTER AN", "Lu", 0),
("GEORGIAN CAPITAL LETTER BAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER GAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER DON", "Lu", 0),
("GEORGIAN CAPITAL LETTER EN", "Lu", 0),
("GEORGIAN CAPITAL LETTER VIN", "Lu", 0),
("GEORGIAN CAPITAL LETTER ZEN", "Lu", 0),
("GEORGIAN CAPITAL LETTER TAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER IN", "Lu", 0),
("GEORGIAN CAPITAL LETTER KAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER LAS", "Lu", 0),
("GEORGIAN CAPITAL LETTER MAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER NAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER ON", "Lu", 0),
("GEORGIAN CAPITAL LETTER PAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER ZHAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER RAE", "Lu", 0),
("GEORGIAN CAPITAL LETTER SAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER TAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER UN", "Lu", 0),
("GEORGIAN CAPITAL LETTER PHAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER KHAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER GHAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER QAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER SHIN", "Lu", 0),
("GEORGIAN CAPITAL LETTER CHIN", "Lu", 0),
("GEORGIAN CAPITAL LETTER CAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER JIL", "Lu", 0),
("GEORGIAN CAPITAL LETTER CIL", "Lu", 0),
("GEORGIAN CAPITAL LETTER CHAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER XAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER JHAN", "Lu", 0),
("GEORGIAN CAPITAL LETTER HAE", "Lu", 0),
("GEORGIAN CAPITAL LETTER HE", "Lu", 0),
("GEORGIAN CAPITAL LETTER HIE", "Lu", 0),
("GEORGIAN CAPITAL LETTER WE", "Lu", 0),
("GEORGIAN CAPITAL LETTER HAR", "Lu", 0),
("GEORGIAN CAPITAL LETTER HOE", "Lu", 0),
(),
("GEORGIAN CAPITAL LETTER YN", "Lu", 0),
(),
(),
(),
(),
(),
("GEORGIAN CAPITAL LETTER AEN", "Lu", 0),
(),
(),
("GEORGIAN LETTER AN", "Ll", 0),
("GEORGIAN LETTER BAN", "Ll", 0),
("GEORGIAN LETTER GAN", "Ll", 0),
("GEORGIAN LETTER DON", "Ll", 0),
("GEORGIAN LETTER EN", "Ll", 0),
("GEORGIAN LETTER VIN", "Ll", 0),
("GEORGIAN LETTER ZEN", "Ll", 0),
("GEORGIAN LETTER TAN", "Ll", 0),
("GEORGIAN LETTER IN", "Ll", 0),
("GEORGIAN LETTER KAN", "Ll", 0),
("GEORGIAN LETTER LAS", "Ll", 0),
("GEORGIAN LETTER MAN", "Ll", 0),
("GEORGIAN LETTER NAR", "Ll", 0),
("GEORGIAN LETTER ON", "Ll", 0),
("GEORGIAN LETTER PAR", "Ll", 0),
("GEORGIAN LETTER ZHAR", "Ll", 0),
("GEORGIAN LETTER RAE", "Ll", 0),
("GEORGIAN LETTER SAN", "Ll", 0),
("GEORGIAN LETTER TAR", "Ll", 0),
("GEORGIAN LETTER UN", "Ll", 0),
("GEORGIAN LETTER PHAR", "Ll", 0),
("GEORGIAN LETTER KHAR", "Ll", 0),
("GEORGIAN LETTER GHAN", "Ll", 0),
("GEORGIAN LETTER QAR", "Ll", 0),
("GEORGIAN LETTER SHIN", "Ll", 0),
("GEORGIAN LETTER CHIN", "Ll", 0),
("GEORGIAN LETTER CAN", "Ll", 0),
("GEORGIAN LETTER JIL", "Ll", 0),
("GEORGIAN LETTER CIL", "Ll", 0),
("GEORGIAN LETTER CHAR", "Ll", 0),
("GEORGIAN LETTER XAN", "Ll", 0),
("GEORGIAN LETTER JHAN", "Ll", 0),
("GEORGIAN LETTER HAE", "Ll", 0),
("GEORGIAN LETTER HE", "Ll", 0),
("GEORGIAN LETTER HIE", "Ll", 0),
("GEORGIAN LETTER WE", "Ll", 0),
("GEORGIAN LETTER HAR", "Ll", 0),
("GEORGIAN LETTER HOE", "Ll", 0),
("GEORGIAN LETTER FI", "Ll", 0),
("GEORGIAN LETTER YN", "Ll", 0),
("GEORGIAN LETTER ELIFI", "Ll", 0),
("GEORGIAN LETTER TURNED GAN", "Ll", 0),
("GEORGIAN LETTER AIN", "Ll", 0),
("GEORGIAN PARAGRAPH SEPARATOR", "Po", 0),
("MODIFIER LETTER GEORGIAN NAR", "Lm", 0),
("GEORGIAN LETTER AEN", "Ll", 0),
("GEORGIAN LETTER HARD SIGN", "Ll", 0),
("GEORGIAN LETTER LABIAL SIGN", "Ll", 0),
)
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/shape-square.typ | typst | Apache License 2.0 | // Test the `square` function.
---
// Default square.
#box(square())
#box(square[hey!])
---
// Test auto-sized square.
#square(fill: eastern)[
#set text(fill: white, weight: "bold")
Typst
]
---
// Test relative-sized child.
#square(fill: eastern)[
#rect(width: 10pt, height: 5pt, fill: conifer)
#rect(width: 40%, height: 5pt, stroke: conifer)
]
---
// Test text overflowing height.
#set page(width: 75pt, height: 100pt)
#square(fill: conifer)[
But, soft! what light through yonder window breaks?
]
---
// Test that square does not overflow page.
#set page(width: 100pt, height: 75pt)
#square(fill: conifer)[
But, soft! what light through yonder window breaks?
]
---
// Size wins over width and height.
// Error: 09-20 unexpected argument: width
#square(width: 10cm, height: 20cm, size: 1cm, fill: rgb("eb5278"))
|
https://github.com/dainbow/FunctionalAnalysis2 | https://raw.githubusercontent.com/dainbow/FunctionalAnalysis2/main/themes/7.typ | typst | #import "../conf.typ": *
= Элементы нелинейного анализа
== Производная Фреше, производная Гато. Формула конечных приращений
#definition[
Пусть $D subset.eq E_1$ -- открытое подмножество, $F : D -> E_2$. Тогда говорят,
что $F$ *дифференцируема по Фреше* в точке $x_0 in D$, если существует оператор $A in cal(L)(E_1, E_2)$ такой,
что приращение можно представить в следующем виде:
#eq[
$Delta F = F(x_0 + h) - F(x_0) = A h + o(norm(h)), h -> 0$
]
]
#definition[
Пусть $F : D -> E_2$ дифференцируема по Фреше в точке $x_0 in D$. Тогда
соответствующий оператор $A in cal(L)(E_1, E_2)$ называется *производной
(Фреше)* $F$ в точке $x_0 in D$:
#eq[
$F'(x_0) := A$
]
]
#definition[
Пусть $F : D -> E_2$ дифференцируема по Фреше в точке $x_0 in D$. Тогда значение $A h$ называется
*дифференциалом* $F$ в точке $x_0$ по приращению $h$:
#eq[
$dif F(x_0, h) := A h = F'(x_0) h = F'(x_0)[h]$
]
]
#proposition[
Пусть $F in cal(L)(E_1, E_2)$. Тогда
#eq[
$forall x in E_1 : space F'(x) = F$
]
]
#proof[
Действительно,
#eq[
$forall x_0 in E_1 :space F[x_0 + h] - F[x_0] = F[h] + 0$
]
То есть $A = F$ и $0 = o(norm(h))$
]
#proposition[
Если $F$ дифференцируема по Фреше, то она непрерывна.
]
#proof[
Действительно, предел правой части из определения равен нулю при стремлении $h -> 0$,
что в точности означает непрерывность.
]
#theorem(
"Дифференцирование сложной функции",
)[
Пусть $F : E_1 -> E_2$, $G : E_2 -> E_3$ дифференцируемые по Фреше операторы.
Тогда $H = G compose F$ также дифференцируема по Фреше, причём
#eq[
$H'(x_0) = G'(F(x_0)) compose F'(x_0)$
]
]
#proof[
Распишем дифференцируемость $F$ в точке $x_0 in E_1$:
#eq[
$F(x_0 + h) - F(x_0) = Delta F = F'(x_0)Delta x + epsilon_1(Delta x)norm(Delta x), space lim_(Delta x -> 0)epsilon_1(Delta x) = 0$
]
Аналогично распишем для $G$:
#eq[
$G(y_0 + t) - G(y_0) = Delta G = G'(y_0)Delta y + epsilon_2(Delta y)norm(Delta y), space lim_(Delta y -> 0)epsilon_2(Delta y) = 0$
]
В силу непрерывности, мы можем рассмотреть $t = F(x_0 + h) - F(x_0)$. Тогда $t ->_(h -> 0) 0$.
Более того, мы можем подставить первую формулу во вторую:
#eq[
$Delta G = G'(y_0)[F'(x_0)Delta x + epsilon_1(Delta x)norm(Delta x)] + epsilon_2(Delta y)norm(Delta y), Delta x -> 0$
]
Если мы покажем, что $G'(y_0)epsilon_1(Delta x)norm(Delta x) + epsilon_2(Delta y)norm(Delta y) = o(norm(Delta x))$,
то всё будет доказано.
Для первого слагаемого утверждаем, что оператор $G'(y_0)$ линеен и даже
непрерывен, а значит
#eq[
$epsilon_1(Delta x) ->_(Delta x -> 0) 0 => G'(y_0)[epsilon_1(Delta x)] ->_(Delta x -> 0) 0$
]
Для второго -- распишем $norm(Delta y)$:
#eq[
$norm(Delta y) = norm(F'(x_0)[Delta x] + epsilon_1(Delta x)norm(Delta x)) <= (norm(F'(x_0)) + norm(epsilon_1(Delta x)))norm(Delta x)$
]
Получили, что $norm(Delta y) = O(norm(Delta x)), Delta x -> 0$. А так как $epsilon_2(Delta y) ->_(Delta x -> 0) 0$,
то получили произведение бесконечно малой на ограниченную и всё доказали.
]
#definition[
*Дифференциалом по Гато* функции $F$ в точке $x_0 in D$ по приращению $h$ называется
следующее значение:
#eq[
$D F(x_0, h) := dif / (dif t) F(x_0 + t h)|_(t = 0)$
]
]
#definition[
Если для дифференциала по Гато функции $F$ в точке $x_0$ существует оператор $A in cal(L)(E_1, E_2)$ такой,
что
#eq[
$D F(x_0, h) = A h$
]
то он называется *производной по Гато*.
]
#theorem(
"о среднем",
)[
Пусть $D subset.eq E_1$ -- выпуклое открытое множество, $F$ -- дифференцируема
по Фреше на $D$. Тогда верно неравенство:
#eq[
$forall x_0, x_1 in D : space norm(F(x_1) - F(x_0)) <= sup_(y in s(x_0, x_1))norm(F'(y))norm(x_1 - x_0)$
]
где $s(x_0, x_1)$ -- интервал от $x_0$ до $x_1$.
]
#proof[
Вся идея в том, чтобы построить сквозное отображение
#eq[
$phi : [0, 1] -> E_1 -> E_2 -> RR$
]
и применить к нему теорему Лагранжа.
Итак, $x(t) = x_0 + t(x_1 - x_0)$, а $f in E_2^*$ -- произвольный функционал.
Определим $phi$ следующим образом:
#eq[
$phi(t) = (f compose F compose x)(t)$
]
Каждая часть композиции является дифференцируемой по Фреше функцией. Стало быть,
и их комбинация дифферецнируема:
#eq[
$phi'(t) = f'(F(x(t))) compose F'(x(t)) compose x'(t) = f[F'(x(t))[x'(t)]] = f[F'(x(t))[x_1 - x_0]]$
]
Теперь применим теорему Лагранжа для всего отрезка $[0, 1]$:
#eq[
$abs(phi(1) - phi(0)) = abs(phi'(xi))(1 - 0)$
]
Разберёмся с левой частью. Она переписывается следующим образом:
#eq[
$abs(phi(1) - phi(0)) = abs(f[F(x_1)] - f[F(x_0)]) &= \ abs(f[F(x_1) - F(x_0)]) &<= norm(f)norm(F(x_1) - F(x_0))$
]
В этот момент нужно вспомнить теорему Хана-Банаха. Одним из её следствий было
то, что для произвольного ненулевого элемента можно подобрать функционал с
единичной нормой, который на этом элементе принимает значение -- норму этого
элемента.
Воспользуемся этим следствием, чтобы найти $f$ по точке $F(x_1) - F(x_0)$. Тогда
неравенство выше превращается в равенство:
#eq[
$exists f in E_2^* : space abs(phi(1) - phi(0)) = abs(f[F(x_1) - F(x_0)]) = norm(F(x_1) - F(x_0))$
]
Итак, соберём всё вместе:
#eq[
$abs(phi(1) - phi(0)) = norm(F(x_1) - F(x_0)) = abs(f(F'(x(xi)))[x_1 - x_0]) &<= \ norm(f)norm(F'(x(xi)))norm(x_1 - x_0) &<= sup_(y in s(x_0, x_1))norm(F'(y))norm(x_1 - x_0)$
]
]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10380.typ | typst | Apache License 2.0 | #let data = (
("UGARITIC LETTER ALPA", "Lo", 0),
("UGARITIC LETTER BETA", "Lo", 0),
("UGARITIC LETTER GAMLA", "Lo", 0),
("UGARITIC LETTER KHA", "Lo", 0),
("UGARITIC LETTER DELTA", "Lo", 0),
("UGARITIC LETTER HO", "Lo", 0),
("UGARITIC LETTER WO", "Lo", 0),
("UGARITIC LETTER ZETA", "Lo", 0),
("UGARITIC LETTER HOTA", "Lo", 0),
("UGARITIC LETTER TET", "Lo", 0),
("UGARITIC LETTER YOD", "Lo", 0),
("UGARITIC LETTER KAF", "Lo", 0),
("UGARITIC LETTER SHIN", "Lo", 0),
("UGARITIC LETTER LAMDA", "Lo", 0),
("UGARITIC LETTER MEM", "Lo", 0),
("UGARITIC LETTER DHAL", "Lo", 0),
("UGARITIC LETTER NUN", "Lo", 0),
("UGARITIC LETTER ZU", "Lo", 0),
("UGARITIC LETTER SAMKA", "Lo", 0),
("UGARITIC LETTER AIN", "Lo", 0),
("UGARITIC LETTER PU", "Lo", 0),
("UGARITIC LETTER SADE", "Lo", 0),
("UGARITIC LETTER QOPA", "Lo", 0),
("UGARITIC LETTER RASHA", "Lo", 0),
("UGARITIC LETTER THANNA", "Lo", 0),
("UGARITIC LETTER GHAIN", "Lo", 0),
("UGARITIC LETTER TO", "Lo", 0),
("UGARITIC LETTER I", "Lo", 0),
("UGARITIC LETTER U", "Lo", 0),
("UGARITIC LETTER SSU", "Lo", 0),
(),
("UGARITIC WORD DIVIDER", "Po", 0),
)
|
https://github.com/jultty/skolar | https://raw.githubusercontent.com/jultty/skolar/main/README.md | markdown | A typst template for your university assignments.
## Installation
Because typst [doesn't yet allow templates](https://github.com/typst/typst/issues/2432) to be submitted as packages you have to clone it manually as a local package:
```sh
git clone https://github.com/jultty/skolar "$HOME/.local/share/typst/packages/local/skolar/0.2.0"
```
## Usage
Just add `#import "@local/skolar:0.2.0": *` to the head of your document and provide a properties dictionary to the `generate_document` function:
```typst
#import "@local/skolar:0.2.0": *
#let my_properties = (
title: "Exercise: The Proxy Pattern",
author: "<NAME>",
course: "Software Architecture and Development",
)
#generate_document(properties: my_properties)[
// your content here
]
```
See the [demo](demo) for a working example.
This is the full schema of properties you can pass to the `generate_document` function along with their default values:
```typst
#let properties = (
title: "Document Title",
author: "<NAME>",
course: "Course Name",
course_id: "COURSE_ID",
date: datetime.today().display("[day]/[month]/[year]"),
landscape: false,
margin_x: 2cm,
margin_y: 2cm,
paper: "a5",
)
```
---
For now, this template still has some hard-coded values that are specific to the São Paulo Federal Institute's Jacareí campus.
|
|
https://github.com/Mufanc/hnuthss-template | https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/main.typ | typst | #import "/configs.typ": font, fontsize
#import "/components.typ": header
// 默认字体:宋体、小四
#set text(lang: "zh", size: fontsize.L4s, font: font.serif)
// - 封面 - //
#import "/pages/cover.typ": cover
#cover(
project: "这是一个测试项目名字长长长长长长长长长长",
name: "旅行者",
id: "314159265358",
class: "测试 1234 班",
college: "学院名称长长长长长",
supervisor: "无名氏",
date: datetime.today()
)
#pagebreak()
// - 原创性声明 & 版权使用授权书 - //
#set page(
// 上边距:30mm;下边距:25mm;左边距:30mm;右边距:20mm
margin: (top: 30mm, bottom: 25mm, left: 30mm, right: 20mm),
header: header
)
#set par(
leading: 1.5em, // 1.5 倍行距
justify: true, // 文本两端对齐
first-line-indent: 2em // 首行缩进
)
#set page(numbering: "I")
#counter(page).update(1)
#import "/pages/license.typ": license
#license
#pagebreak()
// - 中文摘要 - //
#import "/pages/abstract.typ"
#abstract.zh
#pagebreak()
// - 英文摘要 - //
#abstract.en
#pagebreak()
// - 目录 - //
#import "/pages/outlines.typ"
#outlines.list-of-contents
#pagebreak()
// - 插图索引 - //
#outlines.list-of-figures
#pagebreak()
// - 附表索引 - //
#outlines.list-of-tables
#pagebreak()
// - 正文 - //
// 更新页码
#set page(numbering: "1")
#counter(page).update(1)
#import "/pages/substance.typ"
#substance.main
#pagebreak()
// - 参考文献 - //
#import "/pages/references.typ": references
#references
#pagebreak()
// - 致谢 - //
#import "/pages/acknowledgments.typ": acknowledgments
#acknowledgments
|
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_905%20-%20Algebraic%20Topology%201/Assignments/Assignment%201.typ | typst | #import "@preview/commute:0.2.0": node, arr, commutative-diagram
#import "/Templates/generic.typ": latex, header
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#import "/Templates/assignment.typ": *
#show: doc => header(title: "Assignment 1", name: "<NAME>", doc)
#show: latex
#show: NumberingAfter
#show: thmrules
#let col(x, clr) = text(fill: clr)[$#x$]
#let pb() = {
pagebreak(weak: true)
}
#let bar(el) = $overline(#el)$
*Sources consulted* \
Texts: Class Notes, Wikipedia page for simplicial sets.
= Question
== Statement
Write down a semisimplicial set $X$, with $X_3 = nothing, X_4 = nothing, ...$ which has non-zero second homology group $H_2 (X)$. You should
#set enum(numbering: "(a)")
+ Write down sets $X_2,X_1,X_0$.
+ Write down face maps $d_0,d_1,d_2 : X_2 -> X_1$.
+ Write down face maps $d_0,d_1 : X_1 -> X_0$.
+ Check that your face maps satisfy the simplicial identities.
+ Calculate, with proof, the second homology group $H_2 (X)$ and check that it is non-zero.
If you can, sketch or describe in words a picture of your semisimplicial set.
== Solution
We will try to create a semisimplicial set which is the triangulation of a sphere. We will do this by gluing two triangles along their boundaries.
+ We will have $X_2 = {F,B}, X_1 = {d,e,f}, X_0 = {a,b,c}$.
+ The face maps $2 -> 1$ will be #h(1fr)
$
d_0(F) = d_0(B) = e, quad d_1(F) = d_1(B) = f, quad d_2(F) = d_2(B) = d.
$
+ The face maps $1 -> 0$ will be #h(1fr)
$
d_0(d) = d_1(e) = b, quad d_1(d) = d_1(f) = a, quad d_0(e) = d_0(f) = c.
$
+ We check all possibilities
$
d_0 d_1 (F) = d_0 (f) = c = d_0 (e) = d_0 d_0 (F)
\ d_0 d_2 (F) = d_0 (d) = b = d_1 (e) = d_1 d_0 (F)
\ d_1 d_2 (F) = d_1 (d) = a = d_1 (f) = d_1 d_1 (F)
\ d_0 d_1 (B) = d_0 (f) = c = d_0 (e) = d_0 d_0 (B)
\ d_0 d_2 (B) = d_0 (d) = b = d_1 (e) = d_1 d_0 (B)
\ d_1 d_2 (B) = d_1 (d) = a = d_1 (f) = d_1 d_1 (B)
$
and so indeed the simplicial identities are satisfied.
+ Now since $F$ and $B$ have the same simplicial maps, $d F = d B$ so we have $d (F - B) = 0$ and thus we have non-zero kernel for $d : S_2 (X) -> S_1 (X)$. But the image of $d : S_3 (X) -> S_2 (X)$ is trivial because $S_3 (X)$ is trivial so $H_3 (X) = Z_3 (X)$ is non-zero.
= Question
== Statement
Let $X$ be a semisimplicial set. For each $n >= 1$, prove that the composite of the group homomorphisms $d : S_n (X) -> S_(n-1) (X)$ and $d : S_(n-1) (X) -> S_(n-2) (X)$ is the zero homomorphism. Conclude that $B_(n-1) (X)$ is a subgroup of $Z_(n-1) (X)$.
== Solution
We can directly compute, for some element $sigma in X_n$,
$
d d sigma & = d sum_(i=0)^n (-1)^i d_i sigma
= sum_(i=0)^n (-1)^i d (d_i sigma)
= sum_(i=0)^n (-1)^i sum_(j=0)^(n-1) (-1)^(j) d_j d_i sigma
\ &= sum_(i=0)^n (-1)^i sum_(j=0)^(n-1) (-1)^(j) d_j d_i sigma
= sum_(0<=j<i<=n) (-1)^(j+i) d_j d_i sigma
+
sum_(0<=i<=j<=n-1) (-1)^(j+i) d_j d_i sigma
\ &= sum_(0<=j<i<=n) (-1)^(j+i) d_(i-1) d_j sigma
+
sum_(0<=i<=j<=n-1) (-1)^(j+i) d_j d_i sigma
\ &= sum_(0<=i<=j<=n-1) (-1)^(j+i+1) d_(j) d_i sigma
+
sum_(0<=i<=j<=n-1) (-1)^(j+i) d_j d_i sigma
=
0
$
Where at the last step we re-indexed the left sum.
= Question
== Statement
Suppose $X$ is a topological space. We use $pi_0 (X)$ to refer to the set of path components in $X$. Construct an isomorphism of abelian groups $H_0 (X) -> ZZ pi_0 X$.
== Solution
Consider a chain $sigma in H_0 (X) = Z_0 (X) quo B_0 (X)$, we can write a representative of its equivalence class as some formal sum $sigma = sum_(i=1)^n a_i x_i$ where $a_i$ are coefficients in $ZZ$ and $x_i$ are points are maps $Delta_0 -> X$ which we can identify with points of $X$. Now let $phi$ be the map that takes a point in $X$ and takes it to the path component in $pi_0 (X)$ which it is a part of. We now define the image of $sigma$ to be
$
f(sigma) = sum_(i=1)^n a_i phi(sigma).
$
First let us check that this is a well defined group homomorphism, namely that $f(sigma) = 0$ if $sigma in B_0 (X)$. We will show this by showing that $f compose d = 0$. To see this let $rho$ be a map $Delta_1 -> X$, which is just a path, and name its endpoints $d_0(rho) = a, d_1(rho) = b$. Since it is a path, by definition $a$ and $b$ are in the same path component of $X$, so we have $phi (a) = phi (b)$. We thus have
$
f compose d (rho) = f (a - b) = phi(a) - phi(b) = 0,
$
by the fact that $f compose d$ is a group homomorphism we get that it is identically zero.
Now let us check that $f$, is an isomorphism. We will do this by constructing an inverse map $g : ZZ pi_0 X -> H_0 (X)$. To do this we will choose a point $x_i$ for each path component $K_i in pi_0 (X)$ such that $x_i in K_i$ (this might require axiom of choice). Then we define for each $K_i in pi_0 X$,
$
g(K_i) = x_i
$
and extend the map through group generation to $ZZ pi_0 X$.
Currently this is just a map $g : ZZ pi_0 X -> S_0 (X)$, but since $d$ is identically zero on $S_0 (X)$ then all of $S_0 (X)$ is in the kernel and thus in $Z_0 (X)$, and so we can then also just compose this map with the quotient map $Z_0 (X) -> Z_0 (X) quo B_0 (X)$. Finally we check that $f$ and $g$ are inverses for each other. For each $K_i$, since $g(K_i) in K_i$ we have that $f(g(K_i)) = K_i$. On the other hand, we have for any point $x in K_i$, $g(f(x)) = g(K_i) = x_i$. This is not equal to $x$, but they are in the same equivalence class since any path from $x$ to $x_i$ is witness to the fact that $x - x_i in B_0 (X)$. Thus $f$ and $g$ are inverses to each other and thus isomorphisms.
= Question
== Statement
Suppose that $X$ and $Y$ are two topological spaces, and let $X product.co Y$ denote the disjoint union of $X$ and $Y$. Prove that, for each non-negative integer $n$, $H_n (X product.co Y)$ is isomorphic to $H_n (X) plus.circle H_n (Y)$.
== Solution
First note that each $Delta_n$ is connected, thus its image by a continuous map is always connected. This means that if $Delta_n -> X product.co Y$ is a continuous map, its image is completely contained within either $X$ or $Y$.
Due to this we can construct a map $f : S_n (X product.co Y) -> S_n (X) plus.circle S_n (Y)$, for each basis map $sigma : Delta_n -> X product.co Y$ its either a map $Delta_n -> X$ or $Delta_n -> Y$ so we just map it to either $S_n (X)$ or $S_n (Y)$. Now restricting this map to $Z_n (X product.co Y)$ makes the image also $Z_n (X) plus.circle Z_n (Y)$, this is because the boundary operation will give the same result whether in the union or not.
Next we check that this map descends to the homology, if an element $sigma$ is a boundary in $X product.co Y$ then $sigma = d (rho)$. Now write
$
rho = sum_(i=1)^n a_i rho_i
$
now each $rho_i$ is contained in either $X$ or $Y$, so set $A$ to be the set of indices for which $rho_i$ is contained in $X$ and $B$ the set containing the rest, we can then write
$
rho = sum_(i in A) a_i rho_i + sum_(i in B) a_i rho_i =: a + b.
$
Now we know that $d rho = d a + d b$, and so we have $f(sigma) = (d a, d b)$ which is clearly in $B_n (X) plus.circle B_n (Y)$. We thus know that $f$ descends to a map $f : H_n (X product.co Y) -> H_n (X) plus.circle H_n (Y)$.
Now luckily the inverse is easier to construct, we have topological injections
$
i_X : X -> X product.co Y, i_Y : Y -> X product.co Y,
$
so since the homology operator is a functor we have that these become maps
$
i'_X : H_n (X) -> H_n (X product.co Y), i'_Y : H_n (Y) -> H_n (X product.co Y).
$
One can easily check that these are inverses of each other, and so they are isomorphisms.
= Question
== Statement
Let $cal(C)$ denote a category and suppose $c_1$ and $c_2$ are two objects of $cal(C)$. Consider a triple consisting of an object $p in op("Ob")(cal(C))$, a morphism $p_1 : p -> c_1$, and a morphism $p_2 : p -> c_2$. Such a triple is called a _product_ of $c_1$ and $c_2$ if, for any other triple $(z, f_1 : z -> c_1, f_2 : z -> c_2)$, there is a unique morphism $g : z -> p$ such that $p_1 compose g = f_1$ and $p_2 compose g = f_2$.
+ Prove that if $(z,z -> c_1, z -> c_2)$ and $(z', z' -> c_1, z' -> c_2)$ are two products of $c_1$ and $c_2$, then $z$ and $z'$ are isomorphic objects of $cal(C)$.
+ Describe the construction of a product of any two objects $c_1, c_2$ in the category of sets. Do the same for the category of topological spaces, and then for the category of abelian groups. Prove that your constructions are products.
+ Construct an example of a category $cal(C)$ and two objects $c_1$ and $c_2$ for which no product of $c_1$ and $c_2$ exists.
== Solution
+ Assume we have two products as given in the question, we will put them in a commutative diagram like so,
#align(center)[#commutative-diagram(
node((0, 3), $c_1$),
node((2, 3), $c_2$),
node((1, 2), $z$, "z"),
node((1, 1), $z'$),
node((1, 0), $z$, "zz"),
arr("z", $c_1$, $p_1$),
arr("z", $c_2$, $p_2$),
arr($z'$, $c_1$, $p'_1$, curve: 10deg),
arr($z'$, $c_2$, $p'_2$, curve: -10deg),
arr("zz", $c_1$, $p_1$, curve: 20deg),
arr("zz", $c_2$, $p_2$, curve: -20deg),
arr("zz", $z'$, $f$, "dashed"),
arr($z'$, "z", $g$, "dashed"),
node-padding: (50pt, 50pt),
)]
Here the existence of the triplet for $z$, and the fact that $z'$ is a product, gives us the unique morphism $g$. Similarly the triplet for $z'$ and the fact that $z$ is a product gives the unique morphism $f$. I now clam that $f$ and $g$ are inverses to each other. To see this simply note that $g compose f$ satisfies $p_1 compose g compose f = p_1' compose f = p_1$ and similarly for $p_2$. But then $g compose f$ is a morphism through which the triplet $(z, p_1, p_2)$ factors over itself. But $id_z$ is also such a morphism, and so since these morphisms must be unique $g compose f = id_z$. A similar construction shows that $g compose f = id_(z')$, so $f$ and $g$ are inverses to each other and thus are the unique isomorphisms between $z$ and $z'$.
+ The product in the category of sets, topological spaces and abelian groups are the Cartesian products $c_1 times c_2$ along with the projection maps onto their respective components. In the topological case the product is given the product topology, and in the abelian group case it is given the structure of a direct product.
Now to see these are indeed products assume that in any of the categories $(z', f : z' -> c_1, g : z' -> c_2)$ is another triplet, then define the map $h : z' -> c_1 times c_2$ given by $h(x) = (f(x), g(x))$ for each $x in z'$. It is clearly a working map in the set case, and it is also continuous in the topological case and is a group homomorphism in the abelian group case.
+ Consider the category with objects ${c_1,c_2}$ and no morphisms. Since a triplet cannot exist, there can be no product in this category.
= Question
== Statement
Write down explicitly what it would mean for the isomorphism you constructed in Problem 3 to be natural. Prove that the isomorphism you constructed is natural (if it is not, modify your solution to the previous problem until it is).
== Solution
Note that $H_0 (dot)$ and $ZZ pi_0 (dot)$ are both functors from $Top$ to $Ab$ so a natural isomorphism between them would mean a collection of isomorphisms $h_X : H_0 (X) -> ZZ pi_0 (X)$ such that for every continuous map $f : X -> Y$ the following diagram commutes
#align(center)[#commutative-diagram(
node((0, 0), $H_0 (X)$),
node((0, 1), $H_0 (Y)$),
node((1, 0), $ZZ pi_0 (X)$),
node((1, 1), $ZZ pi_0 (Y)$),
arr($H_0 (X)$, $H_0 (Y)$, $f_*$),
arr($ZZ pi_0 (X)$, $ZZ pi_0 (Y)$, $f^*$),
arr($H_0 (X)$, $ZZ pi_0 (X)$, $h_X$),
arr($H_0 (Y)$, $ZZ pi_0 (Y)$, $h_Y$),
)]
where $f_*$ is the induced map on homologies and $f^*$ is the induced map on path components given by mapping a path component in $X$ to the path component in which its image is contained in $Y$.
My map is indeed a natural isomorphism, to see this consider a point $x in H_0 (X)$. If we compute $f^* compose h_X (x)$ we first map $x$ to its path component $K_x$ and then $f^*$ maps that path component to some other path component $ov(K)_x$ of $Y$ where $f(K_x) seq ov(K)_x$. On the other hand if we first map $x$ through $f_*$, then we will get the point $f(x) in Y$ representing the class $f_* (x)$. But we know $f(x) in f(K_x) seq ov(K)_x$ so $h_Y (f_* (x)) = ov(K)_x$ and thus indeed the diagram always commutes.
|
|
https://github.com/TOMATOFQY/MyChiCV | https://raw.githubusercontent.com/TOMATOFQY/MyChiCV/main/README.md | markdown | MIT License | # Chi CV template, but in Typst and Chinese
Rip-off of [rip-off of skyzh's CV, but Typst](https://github.com/matchy233/typst-chi-cv-template) and [rip-off of skyzh's CV in Latex](https://github.com/matchy233/chi-cv-template), adapted for use with Typst and added support for Chinese.
## Usage
You cannot simply compile files by copying them to the web application because Typst's web application DOSE NOT allow uploading of large fonts (unfortunately, Chinese fonts always tend to be too large). However, fortunately, you can achieve real-time previewing locally using the vscode plugin. With plugin, you can easily experience an editing experience far beyond LaTeX.
## Sample Output
CV in English is the original version from Chi Ce, and CV in Chinese is the version I modified.


Life is hard. Good luck. Play good game. |
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/lagrange.typ | typst | #import "template.typ": *
#show: project.with(
title: "Mécanique de Lagrange",
authors: (
"Lucas",
),
date: "25 Mars, 2023",
)
= Cours <LAGRANGE>
Le cadre lagrangien est une façon de décrire le mouvement d'un système en utilisant une fonction lagrangienne. La fonction lagrangienne est une fonction des coordonnées généralisées et du temps, et elle contient des informations sur l'énergie cinétique et potentielle du système. Le cadre lagrangien peut être utilisé pour dériver les équations du mouvement du système et pour calculer l'énergie du système. L'énergie cinétique est une mesure de l'énergie de mouvement du système, et l'énergie potentielle est une mesure de l'énergie du système due à sa position. La fonction lagrangienne contient également des informations sur les coordonnées généralisées, qui sont les variables décrivant la position du système.
La fonction lagrangienne est définie comme suit :
$L(q comma accent(q, dot) comma t) = T(q comma accent(q, dot)) - V(q, t)$
où $T(q comma accent(q, dot))$ est l'énergie cinétique du système, $V(q comma t)$ est l'énergie potentielle du système, et $accent(q,dot)$ est la dérivée temporelle de la coordonnée généralisée $q$.
Les équations du mouvement du système peuvent être dérivées de la fonction lagrangienne en utilisant les équations d'Euler-Lagrange. Les équations d'Euler-Lagrange sont les suivantes :
$frac(diff L,diff q) - frac(d,d t) frac(diff L,diff accent(q,dot)) = 0$
L'énergie du système peut être calculée à partir de la fonction lagrangienne en utilisant la formule suivante :
$E = L - T$
Le principe de l'action stationnaire stipule que la trajectoire d'un système est celle qui minimise l'action. L'action est une fonction qui dépend de la trajectoire du système et qui est définie comme suit :
$S = integral_0^T d t space L$
où $L$ est le lagrangien du système. Le lagrangien est une fonction qui dépend de la position et de la vitesse du système.
Le principe de l'action stationnaire peut être dérivé des équations d'Euler-Lagrange. Les équations d'Euler-Lagrange sont les équations du mouvement d'un système et peuvent être dérivées du principe de l'action stationnaire à l'aide de la formule suivante :
$frac(delta S,delta q) = 0$
où $delta S$ est la variation de l'action.
Les générateurs sont les fonctions qui génèrent les transformations du système en utilisant le principe d'action stationnaire. |
|
https://github.com/Pesteves2002/devops-nixos-presentation | https://raw.githubusercontent.com/Pesteves2002/devops-nixos-presentation/master/slides.typ | typst | #import "@preview/polylux:0.3.1": *
#import themes.clean: *
#set document(
title: [DevOps Presentation: NixOS: Reproducibility with Flakes], author: ("<NAME>", "<NAME>"), keywords: ("nixos", "presentation", "devops"), date: datetime(year: 2024, month: 10, day: 10, hour: 13, minute: 00, second: 00),
)
// compile .pdfpc wth `polylux2pdfpc {fname}.typ`
// then present with, e.g., `pdfpc --windowed both {fname}.pdf`
// uncomment to get a "submittable" PDF
// #enable-handout-mode(true)
#let kthblue = rgb("#000060")
#show: clean-theme.with(
short-title: [*NixOS: Reproducibility with Flakes*], color: kthblue, logo: image("common/KTH_logo_RGB_bla.svg"),
)
#pdfpc.config(duration-minutes: 7)
// consistent formatting + make typstfmt play nice
#let notes(speaker: "???", ..bullets) = pdfpc.speaker-note("## " + speaker + "\n\n" + bullets.pos().map(x => "- " + x).join("\n"))
#show link: it => underline(stroke: 1pt + kthblue, text(fill: kthblue, it))
#let cmd = it => block(
fill: rgb("#1d2433"), inset: 7pt, radius: 5pt, text(fill: rgb("#a2aabc"), size: 15pt, it),
)
#let big-picture-slide(content) = {
polylux-slide({
place(top + left, image("assets/nix-wallpaper-nineish-dark-gray.svg"))
set text(white, 2em)
set align(left + horizon)
box(width: 40%, align(center + horizon, content))
})
}
#let cover = title-slide(
title: text(25pt)[NixOS: Reproducibility with Flakes ], subtitle: [
DD2482 Automated Software Testing and DevOps
*Presentation*
#smallcaps[KTH Royal Institute of Technology]
Thursday, 10#super[th] of October, 2024
#notes(speaker: "Tomás", "introduce topic", "introduce presenters")
], authors: (
[<NAME>\ #link("mailto:<EMAIL>")], [<NAME>\ #link("mailto:<EMAIL>")],
),
)
#cover
#slide(
title: "Overview",
)[
- Introduction
- What is Nix/NixOS?
- Limitations of NixOS
- Nix Flakes
- Definition
- Usage
- Pros and Cons
- Conclusion
#notes(
speaker: "Tomás", "Introduction to Nix/Nixos", "How can We improve reproducibility?", "Conclusion",
)
]
#new-section-slide("Introduction")
#slide(
title: "What is Nix/NixOS?",
)[
#side-by-side[
- *Nix*
- The Functional Language
- The Package Manager #footnote[*Nixpkgs* is the package repository of Nix, containing thousands of software
packages.]
- *NixOS*
- The Operating System, Linux distribution built on *Nix*
][
#align(center, image("assets/nix-snowflake-colours.svg", height: 70%))
]
#notes(speaker: "Tomás", "nixlang/nix/nixos/nixpkgs")
]
#slide(
title: "Why Nix/NixOS?",
)[
#v(1em)
#grid(
columns: (1fr, 1fr, 1fr), gutter: 1em, align: center + bottom, image("assets/reproducible.svg", height: 50%), image("assets/declarative.svg", height: 50%), image("assets/reliable.svg", height: 50%), [*Reproducible\**], [*Declarative*], [*Reliable*],
)
#notes(
speaker: "Tomás", "Reproducible: works on my machine, works on every machine", "Declarative: infrastructure as code, allows you to copy code from stackoverflow and it will work", "Reliable: if something goes bad, you can always rollback and avoid being fired", "but why is there an asterisk? well because that is not always true", "But NixOS does not provide dependecy pinning and secure management of secrets",
)
]
#slide(
title: "Is NixOS really Reproducible?",
)[
#side-by-side[
#align(center, image("assets/computer.svg", height: 40%))
- Created in 2023
- *NixOS* 23.05
- *Python* 3.8
][
#grid(
columns: (1fr, 4fr, 1fr), gutter: 1em, align: center + horizon, $<--$, image("assets/config.svg", height: 40%), $-->$,
)
#set align(center)
config.nix
][
#align(center, image("assets/disaster.svg", height: 40%))
- Created in 2024
- *NixOS* 24.05
- *Python* 3.9
]
#notes(speaker: "Tomás", "same config, different results")
]
#new-section-slide("Nix Flakes")
#slide(
title: "What are Nix Flakes?",
)[
#side-by-side(
columns: (1fr, 1.25fr),
)[
- Experimental feature that enhances *Nix* package management
- Provides a way to *pin* the version of dependencies
][
#text(
11pt,
)[
```nix
{
description = "A very basic flake";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
};
outputs = { self, nixpkgs }: {
packages.x86_64-linux.hello = nixpkgs.legacyPackages.x86_64-linux.hello;
packages.x86_64-linux.default = self.packages.x86_64-linux.hello;
overlays.default = final: prev: { ... };
formatter.x86_64-linux = ...;
};
}
```
]
- flake.nix
]
#notes(
speaker: "Tomás", "pin versions of the dependecies", "description, inputs (dependencies)", "and outputs (what is done)",
)
]
#slide(
title: "Flake.lock",
)[
#side-by-side(
columns: (1fr, 1.5fr),
)[
- Works in the same way as a `package-lock.json` or `cargo.lock` file.
- Automatically generated when `flake.nix` is evaluated.
][
#text(
12pt,
)[
```nix
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1727348695,
"narHash": "sha256-J+PeFKSDV+pHL7ukkfpVzCOO7mBSrrpJ3svwBFABbhI=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "1925c603f17fc89f4c8f6bf6f631a802ad85d784",
"type": "github"
},
},
...
},
}
```
]
- flake.lock
]
#notes(
speaker: "Tomás", "evaluates flake lock explain git version and narHash (integrity)",
)
]
#slide(
title: "Create Your Own Packages",
)[
#side-by-side(columns: (1fr, 1.5fr))[
- Use your own custom packages everywhere
- Build and Run the _derivation_:
- #cmd(`nix build .#<name>`)
- #cmd(`nix run .#<name>`)
][
#text(12pt)[
```nix
{
description = "A flake for building Hello World";
inputs.nixpkgs.url = github:NixOS/nixpkgs/nixos-20.03;
outputs = { self, nixpkgs }: {
defaultPackage.x86_64-linux =
with import nixpkgs { system = "x86_64-linux"; };
stdenv.mkDerivation {
name = "hello";
src = self;
buildPhase = "gcc -o hello ./hello.c";
installPhase = "mkdir -p $out/bin; install -t $out/bin hello";
};
};
}
```
]
]
#notes(
speaker: "Tomás", "build (derivation) and run programs with flake, in this case hello, is compiled and ran in result/bin/hello",
)
]
#slide(
title: "Declare Your System",
)[
#side-by-side(columns: (1fr, 1.25fr))[
- Use your NixOS config everywhere
- Update your config:
- #cmd(`nixos-rebuild switch --flake .#hostname`)
][
#set text(12pt)
```nix
{
description = "Flake for deploying the machines";
inputs.nixpkgs.url = "nixpkgs/nixos-24.05";
outputs = { self, nixpkgs }: {
nixosConfigurations.spoon = nixpkgs.lib.nixosSystem {
modules = [
./spoon.nix
];
};
nixosConfigurations.lamp = nixpkgs.lib.nixosSystem {
modules = [
./lamp.nix
];
};
};
}
```
]
#notes(
speaker: "Tomás", "deploy the configuration with nixos-rebuild switch --flake .#hostname",
)
]
#slide(
title: "Dependency Conflicts",
)[
#side-by-side[
- Multiple projects require different versions of the same package
- *Project A*: *Python* 3.8
- *Project B*: *Python* 3.12
- Flakes solves this problem
][
#align(center, image("assets/dependency-hell.jpg", height: 70%))
]
#notes(
speaker: "Tomás", "dependency conflicts are a common problem in software development", "flakes solve this problem by creting dev shells",
)
]
#slide(
title: "Create Dev Shells",
)[
#side-by-side(
columns: (1fr, 1.5fr),
)[
- Creates an ephemeral development shell
- Packages Needed
- Environment Variables
- Create shell
- #cmd(`nix develop`)
][
#set text(11pt)
```nix
{
description = "Flake for the dev ops presentation";
inputs = {
nixpkgs.url = "nixpkgs/nixos-24.05";
utils.url = "github:numtide/flake-utils";
};
outputs = inputs: inputs.utils.lib.eachDefaultSystem (system:
let
pkgs = import inputs.nixpkgs { inherit system; };
in
{
devShell = pkgs.mkShell {
buildInputs = with pkgs; [ typst typstfmt pdfpc polylux2pdfpc python310 ];
KEY = "ABCD";
};
}
);
}
```
]
#notes(
speaker: "Tomás", "create a development shell with the tools needed for the presentation, talk about python versions",
)
]
#slide(title: "Reflection - Pros and Cons of Flakes")[
#side-by-side[
Pros
- Truly Reproducible
- Rollback Feature
- Escape Dependency Conflicts
][
Cons
- Need to Update Imperatively
- Experimental
- Prone to Breaking Changes
- Limited Documentation
- No Lazy Evaluation
]
]
#new-section-slide("Conclusion")
#slide(
title: "True Reproducibility with Flakes",
)[
#side-by-side[
#align(center, image("assets/lion.svg", height: 40%))
- Created in 2023
- *NixOS* 23.05
- *Python* 3.8
][
#grid(
columns: (1fr, 4fr, 1fr), gutter: 1em, align: center + horizon, $<--$, image("assets/config.svg", height: 20%), $-->$,
)
#set align(center)
flake.nix
#align(center, image("assets/lock.svg", height: 20%))
#set align(center)
flake.lock
][
#align(center, image("assets/monkey.svg", height: 40%))
- Created in 2024
- *NixOS* 23.05
- *Python* 3.8
]
]
#big-picture-slide()[
With Flakes Your Configuration will be Reproducible *Forever*
]
#cover
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-21.typ | typst | Other | #{
let x = 2
for _ in range(61) {
(x) *= 2
}
// Error: 3-17 cannot repeat this string 4611686018427387904 times
x * "abcdefgh"
}
|
https://github.com/Trebor-Huang/HomotopyHistory | https://raw.githubusercontent.com/Trebor-Huang/HomotopyHistory/main/prospect.typ | typst | #import "common.typ": *
= 展望
当今, 同伦论也有着激动人心的发展. 2009 年, 由 Voevodsky 等人提出了同伦类型论, 使得同伦理论可以脱离具体的模型而公理化的进行, 正如 Euclid 公理使得平面几何不需要具体构造实数一样. 这种类型论也可以作为数学的基础. 2012–13 年举办了泛等数学基础特别年, 从各个角度大大发展了同伦类型论. 读者可以阅读 @hottbook 了解同伦类型论.
当然, 同伦论的发展也有许多挑战. <NAME> 在公开信《同伦论的未来》@future 中提出了一些学科发展的忧虑. 例如同伦论仍然被视为拓扑学的子分支, 而实际上它所关心的问题与研究的方法已经与拓扑学相差较远, 因此这不利于审稿等学术活动.
同伦论有着非常丰富的历史, 在相对较短的时间内, 能凭借新的发现对旧有的基础理论作出多次重写, 是相当罕见的. 同时, 同伦论与数学、物理、计算机等领域都有广泛的联系. 这都是同伦论在未来蓬勃发展的动力源.
|
|
https://github.com/SnO2WMaN/incompleteness.txt | https://raw.githubusercontent.com/SnO2WMaN/incompleteness.txt/main/main.typ | typst | Creative Commons Zero v1.0 Universal | #import "template.typ": *
#show: project.with(
title: "Incompleteness.txt",
authors: (
"SnO2WMaN",
),
)
#import "@preview/lemmify:0.1.2": *
#let (
definition, theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules
) = default-theorems("thm-group", lang: "en", max-reset-level: 3)
#show: thm-rules
#show thm-selector("thm-group", subgroup: "definition"): it => box(
it,
stroke: (left: (thickness: 2pt)),
inset: 1em,
)
#show thm-selector("thm-group", subgroup: "theorem"): it => box(
it,
stroke: 1pt,
inset: 1em
)
#show thm-selector("thm-group", subgroup: "lemma"): it => box(
it,
stroke: (thickness: 1pt, dash: "dotted"),
inset: 1em
)
#show thm-selector("thm-group", subgroup: "corollary"): it => box(
it,
stroke: 1pt,
inset: 1em
)
#show thm-selector("thm-group", subgroup: "example"): it => box(
it,
inset: (left: 1em, right: 1em, top: 1em, bottom: 1em),
)
#show thm-selector("thm-group", subgroup: "remark"): it => box(
it,
inset: (left: 1em, right: 1em, top: 1em, bottom: 1em),
)
#show thm-selector("thm-group", subgroup: "proof"): it => box(
it,
stroke: (left: (thickness: 1pt, dash: "dotted")),
inset: (left: 1em, right: 1em, top: 0.5em, bottom: 0.5em),
)
#show outline.entry.where(
level: 1
): it => {
v(1em, weak: true)
strong(it)
}
#outline(indent: auto)
#let TODO(content) = emph("TODO:" + content)
#let Theory(a) = $upright(sans(#a))$
#let PeanoArithmetic = $Theory("PA")$
#let RobinsonArithmetic = $Theory("Q")$
#let WeakestArithmetic = $Theory("R")$
#let Language = $cal("L")$
#let ArithmeticLanguage = $Language_sans("A")$
#let Nat = $bb("N")$
#let Nat2Nat(n) = $Nat^#n -> Nat$
#let vec(x) = $accent(#x, arrow)$
#let vecx = $vec(x)$
#let vecy = $vec(y)$
#let charFn(R) = $chi_(#R)$
#let succ = $serif("s")$
#let fn(txt) = $upright(serif(txt))$
#let fnConst(n,c) = $fn("const")^(#n)_(#c)$
#let fnSucc = $fn("succ")$
#let fnProj(n,i) = $fn("proj")^(#n)_(#i)$
#let fnComp = $fn("comp")$
#let fnPrec(f,g) = $fn("prec")_(#f,#g)$
#let fnZero(n) = $fn("zero")^#n$
#let fnId = $fn("id")$
#let fnAdd = $fn("add")$
#let fnMul = $fn("mul")$
#let fnExp = $fn("exp")$
#let fnFrac = $fn("frac")$
#let fnPred = $fn("pred")$
#let fnMsub = $fn("msub")$
#let fnIsZero = $fn("iszero")$
#let fnIsPos = $fn("ispos")$
#let fnBSum(f) = $Sigma_(#f)$
#let fnBMul(f) = $Pi_(#f)$
#let fnBCase(R,f,g) = $"if" #R "then" #f "else" #g$
#let fnBMinimize(y, m, R) = $mu_(#y <= #m).[#R]$
#let fnPrime = $fn("pr")$
#let Rel(txt) = $upright(serif(txt))$
#let REq = $Rel("Eq")$
#let RGt = $Rel("Gt")$
#let REven = $Rel("Even")$
#let RNEq = $Rel("NEq")$
#let RGte = $Rel("Gte")$
#let RDiv = $Rel("Div")$
#let RPrime = $Rel("Prime")$
#let RGteForall(y, m, r) = $forall_(#y <= #m).[#r]$
#let RGteExists(y, m, r) = $exists_(#y <= #m).[#r]$
#let RGtForall(y, m, r) = $forall_(#y < #m).[#r]$
#let RGtExists(y, m, r) = $exists_(#y < #m).[#r]$
#let GoedelNum(x) = $lr(⸢#x⸣)$ // $⸢#x⸣$ // $attach(#x, tl: "⸢", tr: "⸣")$ // $⌜#x⌝$ // $attach(#x, tl: "⌜", tr: "⌝")$
#let NumTerm(x) = $overline(#x)$
#let GoedelNumTerm(x) = $NumTerm(GoedelNum(#x))$
#let GoedelSentence = $serif("G")$
#let RosserSentence = $serif("R")$
#let HenkinSentence = $serif("H")$
#let JeroslowSentence = $serif("J")$
#let Provability(T, lt: none, content) = $serif("Pr")^(#lt)_(#T)(content)$
#let RosserProvability(T, content) = $Provability(#T, lt: serif("Ro"), #content)$
#let Consistency(T, lt: none) = $serif("Con")^(#lt)_#T$
#let RosserConsistency(T) = $Consistency(#T, lt: serif("Ro"))$
#let Drv1 = $bold(serif("D1"))$
#let Drv2 = $bold(serif("D2"))$
#let Drv3 = $bold(serif("D3"))$
#let proves = symbol(
"\u{22A2}",
("not", "\u{22AC}")
)
#let models = symbol(
"\u{22A8}",
("not", "\u{22AD}")
)
#let iff = $<==>$
#let TheoryT = $T$
#let TheoryU = $U$
#let StandardArithmeticModel = $cal(N)$
= はじめに
この文書は不完全性定理についての諸々をまとめたものです.
自分用に纏めたものであり,人に見せることをあまり想定していないので,説明が不十分な部分があるかもしれません.
また普通に誤りがある可能性もあります.
これらの点についてはご了承ください.
== メタ情報
- この文書は#link("https://typst.app")[Typst]という執筆時では新興の組版システムによって作成しています.
- 文書のソースファイル等は#link("https://github.com/SnO2WMaN/incompleteness.txt")に置かれており,最新のPDFファイルが自動的に#link("https://sno2wman.github.io/incompleteness.txt/main.pdf")にデプロイされています#footnote[文書のコンパイルが失敗していなければ.].
- 文書のライセンスは#link("https://github.com/SnO2WMaN/incompleteness.txt/blob/main/LICENSE")[CC0 1.0]であり,可能な限り著作権を放棄します.
- 誤りなどがあれば,#link("https://github.com/SnO2WMaN/incompleteness.txt/issues")[GitHubのissue]か著者に連絡していただけると助かります.
== 読書案内
日本語で書かれた不完全性定理についての文献としては#cite("kikuchi_2014", "kurahashi_2021", "smullyan_1992_ja","kikuchi_sano_kurahashi_usuba_kurokawa_2016")があります.
知っている範囲で簡単に紹介しておきます.#TODO[もっとちゃんと文献を増やす]
- #cite("kikuchi_2014")は,日本における不完全性定理の第一人者#footnote[少なくとも私はそう思っています.]による不完全性定理の証明に至るまでの丁寧な解説書であり,更に少しの発展的な話題も載っています.数学の哲学について禁欲でないという特徴もあります.
- #cite("kurahashi_2021")は,示すこと自体が目標になりがちな不完全性定理の,更に発展的な話題について書かれています.ただし,紙面の都合で多くの定理の証明が載っていません.
- #cite("smullyan_1992_ja")は#cite("smullyan_1992")の日本語訳です.私が最初に読んだという点で思い入れがありますが,用語やアプローチがかなり独特なので,入門としてはあまりおすすめはしません#footnote[事情としては,Smullyanが数論的なアプローチを避けてより初等的な形式での議論を行おうとしている気があり,不完全性定理について全く知らない人間にとってはどういうモチベーションでそんなことをしているのか分かりにくいという難点があります.逆に言えば,分かってしまえばむしろかなり丁寧に議論していることが分かります.].
- #cite("kikuchi_sano_kurahashi_usuba_kurokawa_2016")は大きく様相論理,証明可能性論理,強制法,真理論についての本です.不完全性定理については,証明可能性論理の節で扱われています.
英語で書かれた文献はもっとあります.#TODO[もっと書く]
== 更新履歴
#TODO[一旦完成してから書く.]
= パラドックス!
= 不完全性定理とは何なのか?
// ここの歴史はかなり疑わしい
今日「不完全性定理」と呼ばれる定理は,Gödel#cite("goedel_1931")によって初めて証明された.
この元論文#cite("goedel_1931")ではRussel,WhiteheadによるPrincipia MathematicaをGödelがより使いやすく改良した体系における第1不完全性定理の証明が与えられ,第2不完全性定理についてはそのスケッチのみを与えるに留まっている.
第2不完全性定理の詳細な証明については#cite("hilbert_bernays_1939")によって最初に証明が与えられた.
== 不完全性定理という名前について
#cite("tanaka_2012", "fuchino_2013")参照.
= 計算論
== 準備
#TODO[どういうモチベーションで #ref(<formalized_nat>)を導入しているかをちゃんと書く]
#definition(name: "形式的な自然数")[
// あとで書く.
]<formalized_nat>
#definition(name: "関数")[
// あとで書く.
]
#definition(name: "関係")[
$n >= 0$に対し,$Nat^n$の部分集合$Rel(R) subset.eq Nat^n$を,$n$項関係という.
]<relation>
#example(name: "関係の例")[
- 「$x$と$y$は同数の$Rel(S)$を持っている」すなわち「$x$が$y$が等しい」という関係$REq$は,2項関係である.$REq = {(0,0), (1,1), (2,2),dots}$.
- 「$y$は$x$より多くの$Rel(S)$を持っている」すなわち「$y$は$x$より大きい」という関係$RGt$は,2項関係である.$RGt = {(0,1), (0,2), (1,3),dots}$.
- 偶数の集合は1項関係である.$REven = {0,2,4,...}$.
]<relation_examples>
#definition(name: "特性関数")[
$n$項関係$Rel(R) subset.eq Nat^n$に対し,次の関数$charFn(Rel(R)) : Nat2Nat(n)$を,$Rel(R)$の特性関数という.
$
charFn(Rel(R))(vecx) =
cases(
1 "if" vecx in Rel(R),
0 "if" vecx in.not Rel(R),
)
$
]<characteristic_function>
// 部分集合というものをそのまま経由せず,特性関数という関数に依って特徴づけられる$Nat^n$の部分集合を関係と呼ぶ,のように定義した方が良い気もする.
== 原始再帰的
我々のよく知っている自然数についての初等的な関数や関係の殆どは,原始再帰的な関数や関係として表現できる.
まずは原始再帰的な関数の定義を与えよう.
#definition(name: "定数関数")[
$n$個の引数$vecx$を受け取るが,それらを全て破棄して$c$を返す関数を,定数関数といい,$fnConst(n, c) : Nat2Nat(n)$で表す.
すなわち,$fnConst(n,c)(vecx) = c$である.
]<Computability_ConstFunction>
#definition(name: "後者関数")[
受け取った自然数の次の自然数を返す関数を,後者関数といい,$fnSucc : Nat2Nat(1)$で表す.
すなわち,$fnSucc(x) = succ(x)$である.
]<Computability_SuccFunction>
#definition(name: "射影関数")[
$n$個の引数$x_1,...,x_n$を受け取り,そのうち$i$番目の引数を返す関数を,射影関数といい,$fnProj(n,i) : Nat2Nat(n)$で表す.
すなわち,$fnProj(n,i) (x_1,...,x_n) = x_i$である.
]<Computability_ProjectionFunction>
#definition(name: "関数合成")[
$n$変数関数$fn(f) : Nat2Nat(n)$と,$n$個の$m$変数関数$fn(g)_1,...,fn(g)_n : Nat2Nat(m)$が与えられたとき,以下のように定義される$m$変数関数$fnComp_(fn(f),fn(g)_1,...,fn(g)_n) : Nat2Nat(m)$を,$fn(f),fn(g)_1,...,fn(g)_n$の関数合成という.
$ fnComp_(fn(f),fn(g)_1,...,fn(g)_n)(vecx) = fn(f)(fn(g)_1 (vecx),...,fn(g)_n (vecx)) $
ここで,$vecx$は$m$個の引数とする.
]<Computability_FunctionComposition>
#definition(name: "原始再帰")[,
$n$変数関数$fn(f) : Nat2Nat(n)$と,$n+2$変数関数$fn(g) : Nat2Nat(n+2)$が与えられたとき,以下のように定義される$n$変数関数$fnPrec(fn(f),fn(g)) : Nat2Nat(n)$を,$fn(f),fn(g)$の原始再帰という.
$
fnPrec(fn(f),fn(g))(vecx, 0) &= fn(f)(vecx) \
fnPrec(fn(f),fn(g))(vecx, succ(y)) &= fn(g)(vecx, y, fnPrec(fn(f),fn(g))(vecx, y))
$
ここで,$vecx$は$m$個の引数とする.
]<Computability_PrimitiveRecursive>
#definition(name: "原始再帰的関数")[
ある関数が原始再帰的であるとは,以下のいずれかの条件を満たすことをいう.
- 定数関数である.(#ref(<Computability_ConstFunction>))
- 後者関数である.(#ref(<Computability_SuccFunction>))
- 射影関数である.(#ref(<Computability_ProjectionFunction>))
- 原始再帰的な関数による関数合成である.(#ref(<Computability_FunctionComposition>))
- 原始再帰的な関数による原始再帰である.(#ref(<Computability_PrimitiveRecursive>))
原始再帰的な関数を,原始再帰的関数という.
]<Computability_PrimitiveRecursiveFunction>
=== 原始再帰的関数の例
前述したとおり,自然数についての初等的な関数の殆どが原始再帰的である.見ていこう.
#definition(name: "恒等関数")[
$fnId : Nat2Nat(1) := fnProj(1, 1)$と定義される関数を,恒等関数とよぶ.
すなわち,$fnId(x) = x$である.
]<Computability_IdFunction>
#definition(name: "ゼロ関数")[
$fnZero(n) : Nat2Nat(n) := fnConst(n, 0)$と定義される関数を,$n$変数ゼロ関数とよぶ.
すなわち,$fnZero(n)(vecx) = 0$である.
]<Computability_ZeroFunction>
#definition(name: "加算")[
以下のように定義される関数$fnAdd : Nat2Nat(2)$を,加算と呼ぶ.
$ fnAdd := fnPrec(fnId,fnComp_(fnSucc, fnProj(3,3))) $
合成と原始再帰を外して簡約すると,以下のようになる.
$
fnAdd(x, 0) &= fnId(x) \
fnAdd(x, succ(y)) &= fnSucc(fnProj(3,3)(x, y, fnAdd(x, y)))
$
また,中置記法として,$fnAdd(x,y)$を$x + y$とも書く.
]<Computability_AddFunction>
#example(name: "加算の例")[
$fnAdd$の挙動を確認して,たしかに加算となっていることを確認しよう.
$fnAdd(2, 3) = 5$である.
// #TODO
]
#definition(name: "乗算")[
以下のように定義される関数$fnMul : Nat2Nat(2)$を,乗算と呼ぶ.
$ fnMul := fnPrec(fnZero(1),fnComp_(fnAdd, fnProj(3,1), fnProj(3,3))) $
合成と原始再帰を外して,よりわかりやすく書くと
$
fnMul(x, 0) &= fnZero(1)(x) \
fnMul(x, succ(y)) &= fnAdd(fnProj(3,1)(x, y, fnMul(x, y)), fnProj(3,3)(x, y, fnMul(x, y)))
$
また,中置記法として,$fnMul(x,y)$を$x times y$とも書く.
]<Computability_MulFunction>
#example(name: "乗算の例")[
$fnMul$の挙動を確認して,たしかに乗算となっていることを確認しよう.
$fnAdd(2, 3) = 6$である.
// #TODO
]
ここまで定義した関数について,定義より明らかに次の #ref(<Computability_PrimRecFn1>)が成り立つ.
#corollary[
恒等関数$fnId$,ゼロ関数$fnZero$,加算$fnAdd$,乗算$fnMul$は原始再帰的関数である.
]<Computability_PrimRecFn1>
さて,更に関数を定義していきたいが,毎回#ref(<Computability_AddFunction>)や#ref(<Computability_MulFunction>)のように愚直に全ての関数を書き下していくと,あまりにも煩雑になってしまう.
これを避けるために,#ref(<Computability_PrimRecFnAbbrev>)を導入する.
#remark[
以下の略記を用いてもよいとする.
- 最も外側の原始再帰は外して定義する.
- $fnConst(n,c), fnProj(n,i), fnId$は明らかなら省略する.
]<Computability_PrimRecFnAbbrev>
#definition(name: "冪乗")[
以下のように定義される関数$fnExp : Nat2Nat(2)$を,冪乗と呼ぶ.
$
fnExp(x, 0) &= 1 \
fnExp(x, succ(x)) &= x times fnExp(x, y)
$
また,略記として$fnExp(x,y)$を$x^y$とも書く.
]<Computability_ExpFunction>
#definition(name: "階乗")[
以下のように定義される関数$fnFrac : Nat2Nat(1)$を,冪乗と呼ぶ.
$
fnFrac(0) &= 1 \
fnFrac(succ(x)) &= (x + 1) times fnFrac(x)
$
また,略記として$fnFrac(x)$を$x!$とも書く.
]<Computability_FracFunction>
#definition(name: "前者関数")[
以下のように定義される関数$fnPred : Nat2Nat(1)$を,前者関数と呼ぶ.
$
fnPred(0) &= 0 \
fnPred(succ(x)) &= fnProj(2,1)(x, fnPred(x))
$
]<Computability_PredFunction>
#definition(name: "補正付き減算")[
以下のように定義される関数$fnMsub : Nat2Nat(2)$を,補正付き減算と呼ぶ.
$
fnMsub(x, 0) &= 0 \
fnMsub(x, succ(y)) &= fnPred(fnMsub(x, y))
$
また,中置記法として,$fnMsub(x,y)$を$x minus.dot y$とも書く.
]<Computability_MSubFunction>
後で特性関数を定義するときに必要となる,次の関数も定義しておこう.
#definition(name: "ゼロ判定")[
以下のように定義される関数$fnIsZero : Nat2Nat(1)$を,ゼロ判定と呼ぶ.
$
fnIsZero(0) &= 1 \
fnIsZero(succ(x)) &= 0
$
]<Computability_IsZeroFunction>
#definition(name: "正数判定")[
以下のように定義される関数$fnIsPos : Nat2Nat(1)$を,正数判定と呼ぶ.
$
fnIsPos(0) &= 0 \
fnIsPos(succ(x)) &= 1
$
]<Computability_IsPosFunction>
ここまで定義した関数についても,やはり明らかに次の #ref(<Computability_PrimRecFn2>)が成り立つ.
#corollary[
冪乗$fnExp$,階乗$fnFrac$,前者関数$fnPred$,補正付き減算$fnMsub$,ゼロ判定$fnIsZero$,正数判定$fnIsPos$は原始再帰的関数である.
]<Computability_PrimRecFn2>
#definition(name: "有界総和")[
関数$fn(f) : Nat2Nat(n+1)$について,以下のように定義される関数$fnBSum(fn(f)) : Nat2Nat(n+1)$を,有界総和と呼ぶ.
$
fnBSum(fn(f))(vecx, 0) &= fn(f)(vecx, 0) \
fnBSum(fn(f))(vecx, succ(y)) &= fn(f)(vecx, succ(y)) + fnBSum(fn(f))(vecx, y)
$
]<Computability_BoundedSumFunction>
#example(name: "有界総和の例")[
有界総和の例を計算してみよう.
- $fnBSum(fnId)(3) = fnId(3) + fnId(2) + fnId(1) + fnId(0) = 6$
- $fnBSum(fnSucc)(3) = fnSucc(3) + fnSucc(2) + fnSucc(1) + fnSucc(0) = 10$
- $fnBSum(fnAdd)(2, 3) = fnAdd(2, 3) + fnAdd(2, 2) + fnAdd(2, 1) + fnAdd(2, 0) = 14$
]
#definition(name: "有界総乗")[
関数$fn(f) : Nat2Nat(n+1)$について,以下のように定義される関数$fnBMul(fn(f)) : Nat2Nat(n+1)$を,有界総乗と呼ぶ.
$
fnBMul(fn(f))(vecx, 0) &= fn(f)(vecx, 0) \
fnBMul(fn(f))(vecx, succ(y)) &= fn(f)(vecx, succ(y)) times fnBMul(fn(f))(vecx, y)
$
]<Computability_BoundedMulFunction>
#example(name: "有界総乗の例")[
有界総乗の例を計算してみよう.
- $fnBMul(fnId)(3) = fnId(3) times fnId(2) times fnId(1) times fnId(0) = 0$
- $fnBMul(fnSucc)(3) = fnSucc(3) times fnSucc(2) times fnSucc(1) times fnSucc(0) = 24$
- $fnBMul(fnAdd)(2, 3) = fnAdd(2, 3) times fnAdd(2, 2) times fnAdd(2, 1) times fnAdd(2, 0) = 240$
]
有界総和と有界総乗についても自明に次の #ref(<Computability_PrimRecFn3>)が成り立つ.
#corollary[
$f: Nat2Nat(n+1)$が原始再帰的関数であるなら,有界総和$fnBSum(f)$,有界総乗$fnBMul(f)$は原始再帰的関数である.
]<Computability_PrimRecFn3>
=== 原始再帰的関係
#definition(name: "原始再帰的関係")[
関係$Rel(R) subset.eq Nat^n$の特性関数$charFn(Rel(R))$が原始再帰的関数であるとき,$Rel(R)$は原始再帰的関係であるという.
]
#ref(<relation_examples>)で見た関係は,いずれも原始再帰的関係である.
#definition(name: "同値関係")[
$x,y in Nat$について,「$x$と$y$は同数の$Rel(S)$を持っている」すなわち「$x$と$y$が等しい」という2項関係を同値関係といい,$REq subset.eq Nat^2$として表す.
$(x,y) in REq$であることを,$x = y$とも書く.
]<Computability_REq>
#theorem[
同値関係$REq$は原始再帰的関係である.
]<Computability_ReqIsPrimRec>
#proof[
実際,$charFn(REq)(x, y) = fnIsZero(x minus.dot y) + fnIsZero(y minus.dot x)$とすれば要件を満たす.
]
#definition(name: "大小関係")[
$x,y in Nat$について,「$y$は$x$より多くの$Rel(S)$を持っている」すなわち「$y$は$x$より大きい」という2項関係を同値関係といい,$RGt subset.eq Nat^2$として表す.
$(x,y) in RGt$であることを,$x < y$とも書く.
]<Computability_RGt>
#theorem[
大小関係$RGt$は原始再帰的関係である.
]<Computability_RGtIsPrimRec>
#proof[
実際,$charFn(RGt)(x, y) = fnIsPos(y minus.dot x)$とすれば要件を満たす.
]
偶数の集合が原始再帰的関係であることを示すために,まずはいくつかの論理演算を用意する.
#definition(name: "関係の論理演算")[
$n$項関係$Rel(R),Rel(S) subset.eq Nat^n$について,関係$not Rel(R), Rel(R) and Rel(S), Rel(R) or Rel(S)$を次のように定める.
- $not Rel(R) := {vecx in Nat^n | vecx in.not Rel(R)}$.すなわち,「$Rel(R)$ではない」という否定.
- $Rel(R) and Rel(S) := {vecx in Nat^n | vecx in Rel(R) sect Rel(S) }$.すなわち,「$Rel(R)$かつ$Rel(S)$」という連言.
- $Rel(R) or Rel(S) := {vecx in Nat^n | vecx in Rel(R) union Rel(S) }$.すなわち,「$Rel(R)$または$Rel(S)$」という選言.
]<Computability_RelLogicOperation>
#theorem[
関係$Rel(R),Rel(S) subset.eq Nat^n$が原始再帰的関係であるとき,関係$not Rel(R), Rel(R) and Rel(S), Rel(R) or Rel(S)$も原始再帰的関係である.
]<Computability_RelLogicOperationIsPrimRec>
#proof[
次のように特性関数を定義すれば,論理演算としての要件を満たす.
- $charFn(not Rel(R))(vecx) := fnIsZero(charFn(Rel(R))(vecx))$
- $charFn(Rel(R) and Rel(S))(vecx) := charFn(Rel(R))(vecx) times charFn(Rel(S))(vecx)$
- $charFn(Rel(R) or Rel(S))(vecx) := fnIsPos(charFn(Rel(R))(vecx) + charFn(Rel(S))(vecx))$
このとき仮定より$Rel(R),Rel(S)$の特性関数$charFn(Rel(R)),chi_Rel(S)$は原始再帰的関数であるので,#ref(<Computability_PrimRecFn1>)や #ref(<Computability_PrimRecFn2>)より,$charFn(not Rel(R)),charFn(Rel(R) and Rel(S)),charFn(Rel(R) or Rel(S))$も原始再帰的関数となる.
]
#remark(numbering: none)[
$Rel(R) and Rel(S), Rel(R) or Rel(S)$の特性関数$charFn(Rel(R) and Rel(S))(vecx), charFn(Rel(R) or Rel(S))(vecx)$を観察すると,前者は乗算,後者は加算に基づいて特性関数が構成されている.このような対応から,連言と選言はそれぞれ論理積と論理和とも呼ばれる.
]
#definition[
2項関係$RNEq, RGte$とその略記を,以下のように定める.
- $RNEq := not REq$とする.すなわち「$x$と$y$は等しくない」という関係であり,$x != y$とも書く.
- $RGte := RGt or REq$とする.すなわち「$y$は$x$以上」という関係であり,$x <= y$とも書く.
]
#ref(<Computability_RelLogicOperationIsPrimRec>)などより明らかに,次の系が成り立つ.
#corollary[
関係$RNEq, RGte$は,原始再帰的関係である.
]
#definition(name: "有界量化")[
$n + 1$項関係$Rel(R) subset.eq Nat^(n + 1)$について,次のような$n+1$項関係を定める.
- $RGteForall(y, m, Rel(R)(vecx, y))$は「$m$以下の全ての$y$で,$Rel(R)(vecx, y)$が成立する」を表す関係で,有界全称量化と呼ぶ.
- $RGteExists(y, m, Rel(R)(vecx, y))$は「$m$以下のある$y$で,$Rel(R)(vecx, y)$が成立する」を表す関係で,有界存在量化と呼ぶ.
2つを合わせて,有界量化とも呼ぶ.
]
#remark(numbering: none)[
自由変数は$vecx, m$であって,$y$は束縛変数であることに注意せよ.すなわち,$(vecx, m) in RGteForall(y, m, Rel(R)(vecx, y))$を確かめているのであって,$(vecx, y) in RGteForall(y, m, Rel(R)(vecx, y))$ではない.$RGteExists(y, m, Rel(R)(vecx, y))$も同様.
]
#theorem[
関係$Rel(R) subset.eq Nat^n$が原始再帰的関係であるとき,関係$RGteForall(y, m, Rel(R)(vecx, y))$と$RGteExists(y, m, Rel(R)(vecx, y))$は原始再帰的関係である.
]
#proof[
次のように特性関数を定義すれば,有界量化としての要件を満たす.
- $charFn(RGteForall(y, m, Rel(R)(vecx, y)))(vecx) := fnBMul(charFn(Rel(R)))(vecx, y) = charFn(Rel(R))(vecx, 0) times charFn(Rel(R))(vecx, 1) times dots.c times charFn(Rel(R))(vecx, m)$
- $charFn(RGteExists(y, m, Rel(R)(vecx, y)))(vecx) := fnIsPos(fnBSum(charFn(Rel(R)))(vecx, y)) = fnIsPos(charFn(Rel(R))(vecx, 0) + charFn(Rel(R))(vecx, 1) + dots.c + charFn(Rel(R))(vecx, m))$
このとき定義より$Rel(R)$の特性関数$charFn(Rel(R))(vecx, y)$が原始再帰的関数であるので,関係$RGteForall(y, m, Rel(R)(vecx, y))$と$RGteExists(y, m, Rel(R)(vecx, y))$も原始再帰的関係である.
]
#remark[
証明によって構成された特性関数を注意深く観察すれば,有界量化の上界$m$を何らかの原始再帰関数によって与えても,その特性関数は原始再帰的関数となることがわかる.
すなわち,$f:Nat2Nat(k)$が原始再帰関数であるなら,$RGteForall(y, fn(f)(accent(m, arrow)), Rel(R)(vecx, y))$や$RGteExists(y, fn(f)(accent(m, arrow)), Rel(R)(vecx, y))$は原始再帰的な$n + k$項関係となる.
]<Computability_BoundedQuantificationUpperRemark>
便利なので,$<=$を$<$に置き換えた有界量化も定義しておこう.
#definition[
$n + 1$項関係$Rel(R) subset.eq Nat^(n + 1)$について,次のような関係を定める.
- $RGtForall(y, m, Rel(R)(vecx, y))$は「$m$より小さい全ての$y$で,$Rel(R)(vecx, y)$が成立する」を表す関係とする.
- $RGtExists(y, m, Rel(R)(vecx, y))$は「$m$より小さいある$y$で,$Rel(R)(vecx, y)$が成立する」を表す関係とする.
]
#theorem[
関係$Rel(R) subset.eq Nat^n$が原始再帰的関係であるとき,関係$RGtForall(y, m, Rel(R)(vecx, y))$と$RGtExists(y, m, Rel(R)(vecx, y))$は原始再帰的関係である.
]
#proof[
以下のように特性関数を定義すれば要件を満たす.
- $RGtForall(y, m, Rel(R)(vecx, y)) := RGteForall(y, m, Rel(R)(vecx, y)) and not Rel(R)(vecx, m)$
- $RGteExists(y, m, Rel(R)(vecx, y)) := RGteExists(y, m, Rel(R)(vecx, y)) and not Rel(R)(vecx, m)$
これらが原始再帰的関係であることは,#ref(<Computability_RelLogicOperationIsPrimRec>)より従う.
]
#remark(numbering: none)[
#ref(<Computability_BoundedQuantificationUpperRemark>)は$RGtForall(y, m, Rel(R)(vecx, y))$と$RGtExists(y, m, Rel(R)(vecx, y))$についても成り立つ.
すなわち,上界を何らかの原始再帰関数$fn(f)(accent(m, arrow))$によって与えた$RGtForall(y, fn(f)(accent(m, arrow)), Rel(R)(vecx, y))$や$RGtExists(y, fn(f)(accent(m, arrow)), Rel(R)(vecx, y))$もやはり原始再帰的な$n + k$項関係となる.
]
ここまでの準備によって,偶数の集合が原始再帰的関係であることを示すことができる.
#definition[
$x in Nat$について,「$x$は偶数個の$Rel(S)$を持っている」すなわち「$x$は偶数である」という1項関係を$REven subset.eq Nat$として表す.
]
#theorem[
関係$REven$は原始再帰的関係である.
]
#proof[
$REven(x) := RGteExists(y, x, x = 2 times y)$とすればよい.
]
更に様々な関係も原始再帰的関係として表すことができる.
#definition[
$x in Nat$について,「$x$は$y$の約数個の$Rel(S)$を持っている」すなわち「$x$は$y$で割り切れる」という2項関係を$RDiv subset.eq Nat^2$として表す.
]
#theorem[
関係$RDiv$は原始再帰的関係である.
]
#proof[
$RDiv(x,y) := RGteExists(z, x, x = y times z)$とすればよい.
]
#remark(numbering: none)[
定義より明らかに,$RDiv(x,2)$は$REven$となる.
]
#definition[
$x in Nat$について,「$x$は素数個の$Rel(S)$を持っている」すなわち「$x$は素数である」という1項関係を$RPrime subset.eq Nat$として表す.なお,$0, 1$は素数ではないとする.
]
#theorem[
関係$RPrime$は原始再帰的関係である.
]<Computability_RPrimeIsPrimRec>
#proof[
$RPrime(x) := (2 <= x) and not RGtExists(y, x, y != 1 and RDiv(x, y))$とすればよい.
]
=== 場合分け関数と有界最小化
#definition(name: "場合分け関数")[
関係$Rel(R) subset.eq Nat^n$と関数$fn(f), fn(g) : Nat2Nat(n)$について,以下のように定義される関数$(fnBCase(Rel(R), fn(f), fn(g))) : Nat2Nat(n)$を,場合分け関数と呼ぶ.
$
(fnBCase(Rel(R), fn(f), fn(g)))(vecx) := cases(
fn(f)(vecx) "if" vecx in Rel(R),
fn(g)(vecx) "if" vecx in.not Rel(R)
)
$
煩雑な場合は,$(fnBCase(Rel(R), fn(f), fn(g)))(vecx)$を$fnBCase(Rel(R)(vecx), fn(f)(vecx), fn(g)(vecx))$とも略記する.
]
#theorem[
関係$Rel(R) subset.eq Nat^n$が原始再帰的関係,関数$fn(f), fn(g) : Nat2Nat(n)$が原始再帰的関数であるとき,関数$(fnBCase(Rel(R), fn(f), fn(g))) : Nat2Nat(n)$も原始再帰的関数である.
]
#proof[
$(fnBCase(Rel(R), fn(f), fn(g)))(vecx) := charFn(Rel(R))(vecx) times fn(f)(vecx) + chi_(not Rel(R))(vecx) times fn(g)(vecx)$と定義すれば要件を満たし,これが原始再帰的関数になることは明らか.
]
#let textm(content) = text(font: "Noto Serif CJK JP", weight: "regular", content)
#definition(name: "有界最小化関数")[
$n+1$項関係$Rel(R) subset.eq Nat^(n + 1)$に対し,以下のように定義される$n+1$項関数$fnBMinimize(y, m, Rel(R)(vecx, y)) : Nat2Nat(n+1)$を,有界最小化関数と呼ぶ.
$
fnBMinimize(y, m, Rel(R)(vecx, y)) :=
cases(
k quad #textm[$m$以下の$y$のうち,$Rel(R)(vecx, y)$を成立させる最小の$y$が$k$として存在するとき],
m quad #textm[そのような$y$が存在しないとき]
)
$
]
#theorem[
関係$Rel(R) subset.eq Nat^(n + 1)$が原始再帰的関係であるとき,有界最小化関数$fnBMinimize(y, m, Rel(R)(vecx, y)) : Nat2Nat(n+1)$は原始再帰的関数である.
]
#proof[
以下のように定義すれば要件を満たす.
$
fnBMinimize(y, 0, Rel(R)(vecx, y)) &= 0 \
fnBMinimize(y, s(m), Rel(R)(vecx, y)) &= fnBCase(RGteExists(y, m, Rel(R)(vecx, y)) , fnBMinimize(y, m, Rel(R)(vecx, y)), s(m))
$
これが原始再帰的関数になることは明らか.
]
#remark[
この証明で構成した関数をよく見れば,やはり#ref(<Computability_BoundedQuantificationUpperRemark>)はここでも適用できることがわかる.すなわち,有界最小化の上界を何らかの原始再帰関数$f:Nat2Nat(k)$によって与えた$fnBMinimize(y, fn(f)(accent(m, arrow)), Rel(R)(vecx, y))$も,やはり原始再帰的関数として構成できる.
]<Computability_BoundedMinificationUpperRemark>
=== $n$番目の素数の計算
素数について成り立つ,次の定理 #ref(<Computability_NextPrimeSearchRange>)を用いることで,$i$番目の素数を出力する関数を原始再帰的関数として構成することが出来る.
#theorem(name: "素数の探索範囲の上界について")[
$p_n$が$n$番目の素数のとき,次の素数である$n + 1$番目の素数$p_(n+1)$は$p_n ! + 1$以下に存在する.
]<Computability_NextPrimeSearchRange>
#proof[
TODO:
]
#definition[
$n$番目の素数を出力する関数を,$fnPrime(n) : Nat2Nat(1)$とする.
ただし,素数は0番目から数えるとする.すなわち,$fnPrime(0) = 2, fnPrime(1) = 3, ...$である.
]
#theorem[
関数$fnPrime$は原始再帰的関数である.
]
#proof[
#ref(<Computability_NextPrimeSearchRange>)より次の素数の探索範囲は$fnPrime(n)! + 1$すなわち有界であるので,有界最小化によって素数を探索することができる.
したがって,所望の関数$fnPrime$は以下のように定義すればよい.
$
fnPrime(0) &:= 2 \
fnPrime(succ(n)) &:= fnBMinimize(y, fnPrime(n)! + 1, fnPrime(n) < y and RPrime(y))
$
これまでに次のことを証明してきた#footnote[もちろん,これより多くのことが後ろで積み上がっている.ここでは代表的なものを取り上げた.].
- 階乗が原始再帰的関数として表せること.(#ref(<Computability_PrimRecFn2>))
- $RPrime$が原始再帰的関係であること.(#ref(<Computability_RPrimeIsPrimRec>))
- 有界最小化の上界を原始再帰的関数で定義してもよいこと. (#ref(<Computability_BoundedMinificationUpperRemark>))
これらの結果を踏まえれば,定義した関数が原始再帰的であることは明らか.
]
#example[
本当になっているか確かめてみよう.
- $fnPrime(1) = fnBMinimize(y, fnPrime(0)! + 1, fnPrime(0) < y and RPrime(y)) = fnBMinimize(y,
3, 2 < y and RPrime(y)) = 3$
- $fnPrime(2) = fnBMinimize(y, fnPrime(1)! + 1, fnPrime(1) < y and RPrime(y)) = fnBMinimize(y, 7, 3 < y and RPrime(y)) = 5$
- $fnPrime(3) = fnBMinimize(y, fnPrime(2)! + 1, fnPrime(2) < y and RPrime(y)) = fnBMinimize(y, 121, 5 < y and RPrime(y)) = 7$
$fnPrime(3)$の有界最小化の探索範囲を見ればわかるとおり,この関数の計算効率は非常が悪い#footnote[100番目の素数$523$を求める$fnPrime(100)$で有界最小化の探索範囲はおよそ$10^158$となる.].
しかしながら,この計算は必ずいずれ終わるのである.
]
= 1階述語論理
== 構文論
== 小さな構文論
#definition(name: "アルファベット")[
以下の8個の記号をアルファベットという.
$ prime space.quad f space.quad P space.quad not space.quad -> space.quad exists space.quad hash space.quad triangle.r.small $
]<FOL_Alphabet>
#definition(name: "略記")[
- $f, P$を$n >= 1$個並べた記号列$underbrace(f dots.c f, n), underbrace(P dots.c P, n)$を,それぞれ$f_n, P_n$と略記する.
- $f_n, P_n$の後に$prime$を$m >= 0$個並べた記号列$underbrace(f dots.c f, n) overbrace(prime dots.c prime, m), underbrace(P dots.c P, n) overbrace(prime dots.c prime, m)$を,それぞれ$f_n^m, P_n^m$と略記する.
- $hash$を$n$個並べた記号列$underbrace(hash dots.c hash, n)$を,$hash_n$と略記する.
]
== 算術の言語
#definition(name: "算術の言語")[
よって特徴づけられる言語を,算術の言語$ArithmeticLanguage$という.
]<FOL_ArithmeticLanguage>
= Gödelの第1不完全性定理
== 可証性述語
#theorem[
$
T proves sigma ==> T proves Provability(TheoryT, GoedelNumTerm(sigma))
$
]<GoedelIT_Drv1>
== Gödelの不動点補題
#theorem(name: "Gödelの不動点補題")[
$x$のみを自由変項とする任意の論理式$phi(x)$について,次を満たす文$sigma$を構成することが出来る.
$
T proves sigma <-> phi(GoedelNumTerm(sigma))
$
このとき,$phi(x)$が$Sigma_n$論理式であるならば,$sigma$は$Sigma_n$文となる.同様に,$phi(x)$が$Pi_n$論理式であるならば,$sigma$は$Pi_n$文となる.
]<GoedelFPLemma>
#definition(name: "Gödel文")[
$Provability(TheoryT, x)$が可証性述語であるとき,不動点補題 #ref(<GoedelFPLemma>)によって構成される次の文$GoedelSentence$を,理論$TheoryT$のGödel文という.
$
TheoryT proves GoedelSentence <-> not Provability(TheoryT, GoedelNumTerm(GoedelSentence))
$
]<GoedelSentence>
#theorem(name: "Gödelの第1不完全性定理")[
$TheoryT$を$PeanoArithmetic$の再帰的可算な拡大理論であるとし,$GoedelSentence$を$TheoryT$のGödel文とする.このとき,以下が成り立つ.
- $TheoryT$が無矛盾ならば,$TheoryT proves.not GoedelSentence$.
- $TheoryT$が$Sigma_1$健全ならば,$TheoryT proves.not not GoedelSentence$.
故に,$TheoryT$が無矛盾かつ$Sigma_1$健全ならば,$TheoryT$は不完全である.
]<GoedelIT1>
#proof(name: $T proves.not GoedelSentence$ + "の証明")[
+ $TheoryT proves GoedelSentence$だと仮定する.
+ #ref(<GoedelIT_Drv1>)より$TheoryT proves Provability(TheoryT, GoedelNumTerm(GoedelSentence))$であり,$GoedelSentence$の定義より$TheoryT proves not GoedelSentence$となる.
+ 纏めれば$T proves G$かつ$T proves.not G$であるが,$TheoryT$は無矛盾であると前提しているため,この議論は破綻する.
よって仮定がおかしく,$TheoryT proves.not GoedelSentence$である.
]
#proof(name: $T proves.not not GoedelSentence$ + "の証明")[
+ $TheoryT proves not GoedelSentence$だと仮定する.
+ $GoedelSentence$の定義より$TheoryT proves Provability(TheoryT, GoedelNumTerm(GoedelSentence))$となる.
+ $Provability(TheoryT, GoedelNumTerm(GoedelSentence))$が$Sigma_1$文であるため,$TheoryT$が$Sigma_1$健全であることから$StandardArithmeticModel models Provability(TheoryT, GoedelNumTerm(GoedelSentence))$となる.
+ $StandardArithmeticModel models Provability(TheoryT, GoedelNumTerm(GoedelSentence))$と$T proves G$は同値である.
+ 纏めれば$T proves not GoedelSentence$かつ$T proves GoedelSentence$であるが,$TheoryT$は$Sigma_1$健全すなわち無矛盾であると前提しているため,この議論は破綻する.
よって仮定がおかしく,$TheoryT proves.not not GoedelSentence$である.
]
#remark(name: "Gödel文の真偽")[
Gödel文の定義より,以下が成り立つ.
$
StandardArithmeticModel models GoedelSentence iff StandardArithmeticModel models not Provability(TheoryT, GoedelNumTerm(GoedelSentence)) iff T proves.not GoedelSentence
$
ここで,#underline[$T$が無矛盾であると仮定するならば] #ref(<GoedelIT1>)より$TheoryT proves.not G$であるので$StandardArithmeticModel models GoedelSentence$である.
しかしながら,#ref(<GoedelIT1>)はGödel文は証明も反証も出来ないということ,すなわちGödel文の証明可能性についてだけ触れているのであって,Gödel文の真偽については何も触れていないことに注意せよ.
Gödel文の真偽は$T$が#underline[実際に]無矛盾であるかどうかに依存しており,その事実は第1不完全性定理によって示されたりはしない.
故に,第1不完全性定理を「正しいが証明は出来ない言明が存在する」と短絡的に帰結することは若干の危険または誤りがある.
]
== Gödel-Rosserの第1不完全性定理
#ref(<GoedelIT1>)において,不完全性を示す#footnote[より細かく言えば$TheoryT proves.not not GoedelSentence$であることを示すことを.]ためには,無矛盾性より強い条件である$Sigma_1$健全性を仮定せざるを得なかった.
この仮定を無矛盾性に弱められることがRosserによって示されている.そのためには,可証性述語を少し変更して,Rosser可証性述語と呼ばれるものに置き換える必要がある.
=== Rosser可証性述語
#definition(name: [Rosser可証性述語])[
]<RosserProvability>
= Gödelの第2不完全性定理
ここでは,$TheoryT$とは算術の理論の拡大とする.
== 導出可能性条件
#definition(name: [Hilbert-Bernays-Löbの導出可能性条件])[
$sigma,pi$を文とする.
$TheoryT$の可証性述語$Provability(TheoryT,x)$について,次の条件$Drv1,Drv2,Drv3$を,Hilbert-Bernays-Löbの導出可能性条件と呼ぶ.
$
Drv1 &: T proves sigma ==> T proves Provability(TheoryT, GoedelNumTerm(sigma)) \
Drv2 &: T proves Provability(TheoryT, GoedelNumTerm(sigma -> pi)) -> (Provability(TheoryT, GoedelNumTerm(sigma)) -> Provability(TheoryT, GoedelNumTerm(pi))) \
Drv3 &: T proves Provability(TheoryT, GoedelNumTerm(sigma)) -> Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, GoedelNumTerm(sigma)))) \
$
]<DerivabilityCondition>
#definition(name: [標準的可証性述語])[
$Drv1,Drv2,Drv3$を満たす理論$TheoryT$の可証性述語$Provability(TheoryT, x)$を,標準的可証性述語という.
]
#definition(name: [無矛盾性を表す文])[
$TheoryT$で反証可能な$Sigma_1$文を1つ取ってきて$bot$とする#footnote[すなわち,$TheoryT proves not bot$である.].
$TheoryT$の無矛盾性を表す文$Consistency(TheoryT) := not Provability(TheoryT, GoedelNumTerm(bot))$と定義する.
]<Consistency>
#remark[
$Consistency(TheoryT)$は$Pi_1$文である.
]
#theorem(name: [形式化された$Sigma_1$完全性定理])[
任意の$Sigma_1$文$sigma$に対して次が成立する.
$
TheoryT proves sigma -> Provability(TheoryT, GoedelNumTerm(sigma))
$
]<FormalizedSigma1Completeness>
#lemma[
$Provability(TheoryT, x)$が標準的可証性述語であるとき,
任意の文$sigma$に対して次が成立する.
$
TheoryT proves not Provability(TheoryT, GoedelNumTerm(sigma)) -> Consistency(TheoryT)
$
]<GoedelIT2_GoedelSentenceConsistencyEquality_lem1>
#let TheoryU = $U$
#lemma[
任意の$PeanoArithmetic$の拡大理論$TheoryU$と任意の文$sigma$に対して次が成立する.
$
U proves Provability(TheoryT, GoedelNumTerm(sigma)) -> Provability(TheoryT, GoedelNumTerm(not sigma)) ==> TheoryU proves Consistency(T) -> not Provability(TheoryT, GoedelNumTerm(sigma))
$
]<GoedelIT2_GoedelSentenceConsistencyEquality_lem2>
#lemma[
任意の$TheoryT$のGödel文$GoedelSentence$に対して次が成立する.
$
TheoryT proves Consistency(TheoryT) -> not Provability(T, GoedelNumTerm(GoedelSentence))
$
]<GoedelIT2_GoedelSentenceConsistencyEquality_lem3>
#proof[
+ $not GoedelSentence$は$Sigma_1$文であるので,形式化された$Sigma_1$完全性定理 #ref(<FormalizedSigma1Completeness>)より$TheoryT proves not G -> Provability(TheoryT, GoedelNumTerm(not GoedelSentence))$.
+ $GoedelSentence$の定義より,$TheoryT proves Provability(TheoryT, GoedelNumTerm(GoedelSentence)) -> not G$.
+ 1,2より,$TheoryT proves Provability(TheoryT, GoedelNumTerm(GoedelSentence)) -> Provability(TheoryT, GoedelNumTerm(not GoedelSentence))$.
+ #ref(<GoedelIT2_GoedelSentenceConsistencyEquality_lem2>)と3より,$TheoryT proves Consistency(TheoryT) -> not Provability(TheoryT, GoedelNumTerm(GoedelSentence))$.
以上で示された.
]
#theorem(name: [Gödel文と無矛盾性の同値性])[
$TheoryT$のGödel文$GoedelSentence$と,$TheoryT$の無矛盾性を表す文$Consistency(TheoryT)$とが,標準的可証性述語によって構成されているとき,次が成立する.
$
TheoryT proves GoedelSentence <-> Consistency(TheoryT)
$
]<GoedelIT2_GoedelSentenceConsistencyEquality>
#proof[
+ #ref(<GoedelIT2_GoedelSentenceConsistencyEquality_lem1>)に$GoedelSentence$を適用して$TheoryT proves not Provability(TheoryT, GoedelNumTerm(GoedelSentence)) -> Consistency(TheoryT)$.
+ #ref(<GoedelIT2_GoedelSentenceConsistencyEquality_lem3>)と1を合わせて,$TheoryT proves not Provability(TheoryT, GoedelNumTerm(GoedelSentence)) <-> Consistency(TheoryT)$.
+ Gödel文の定義より,$TheoryT proves GoedelSentence <-> Consistency(TheoryT)$.
以上で示された.
]
#ref(<GoedelIT2_GoedelSentenceConsistencyEquality>)より,明らかに次の系が成り立つ.
#corollary[
任意の$TheoryT$のGödel文$GoedelSentence,GoedelSentence'$に対して$TheoryT proves GoedelSentence <-> GoedelSentence'$
]
#theorem(name: [Gödelの第2不完全性定理])[
$TheoryT$が$PeanoArithmetic$の再帰的可算な拡大理論であるとする.このとき,以下が成り立つ.
- $TheoryT$が無矛盾ならば,$TheoryT proves.not Consistency(TheoryT)$
- $TheoryT$が$Sigma_1$健全ならば,$TheoryT proves.not not Consistency(TheoryT)$
]<GoedelIT2>
#proof[
第1不完全性定理(#ref(<GoedelIT1>))とGödel文と無矛盾性の同値性(#ref(<GoedelIT2_GoedelSentenceConsistencyEquality>))より従う.
]
#remark[
第2不完全性定理#ref(<GoedelIT2>)の対偶も重要な応用がある.すなわち,#underline[自身の無矛盾性が$TheoryT$で証明できてしまう#footnote[$TheoryT proves Consistency(TheoryT)$.]なら,$TheoryT$は矛盾している]という事実はよく用いられる.
]<GoedelIT2_Contradiction>
== Kreiselの注意
#ref(<GoedelIT2>)においてもGödel-Rosserの第1不完全性定理のように$Sigma_1$健全を弱めることが出来ないのだろうか?これは出来ないのである.
#theorem[
Rosser可証性述語は導出可能性条件$Drv2,Drv3$を同時に満たさない.
]
#corollary(name: [Kreiselの注意])[
$TheoryT proves not RosserProvability(TheoryT, GoedelNumTerm(bot))$.ただし$bot$は #ref(<Consistency>)での用法と同じ#footnote[すなわち例えば文$0 = 1$などのことを指す.]とする.
言い換えれば,#ref(<Consistency>)で用いる可証性述語としてRosser可証性述語を利用して無矛盾性を表した文$RosserConsistency(TheoryT) := not RosserProvability(TheoryT, GoedelNumTerm(bot))$を構成した場合は,第2不完全性定理は成り立たない.
]
= Löbの定理
Gödelの不動点補題と可証性述語を組み合わせると,様々な自己言及的な文を構成することが出来る.
Gödel文は自己の証明不可能性を主張する文として定義されたが,逆に,自己の証明可能性を主張する文を考えるとどんなことが起こるのか考えてみよう.
#definition(name: [Henkin文])[
$Provability(TheoryT, x)$が可証性述語であるとき,不動点補題#ref(<GoedelFPLemma>)によって構成される次の文$HenkinSentence$を,理論$TheoryT$のHenkin文という.
$
TheoryT proves HenkinSentence <-> Provability(TheoryT, GoedelNumTerm(HenkinSentence))
$
]<HenkinSentence>
このとき,#underline[Henkin文は$TheoryT$で証明可能なのか?]という問題がHenkin#cite("henkin_1952")によって提案された.この問題はLöb#cite("loeb_1955")によって,より一般的な形で解決された.
#theorem(name: [Löbの定理])[
任意の文$sigma$に対して次が成立する.
$
TheoryT proves sigma iff TheoryT proves Provability(TheoryT, GoedelNumTerm(sigma)) -> sigma
$
]
$==>$については自明なので,問題は$<==$を証明することである.この証明には第2不完全性定理を使う証明(#ref(<OriginalLoebTheoremProof>))と,第2不完全性定理を使わないLöbのオリジナルの証明(#ref(<OriginalLoebTheoremProof>))がある.特に後者の証明からは第2不完全性定理が系として得られる(#ref(<LoebTheoremImplyGoedelIT2>)).
前述の通り,Löbの定理はHenkinの問題を一般化したものであり,$sigma$を$HenkinSentence$とすればHenkinの問題は解決される.
#corollary[
$TheoryT proves HenkinSentence$である.
]
== Löbの定理の意義
== 第2不完全性定理を用いた証明 <LoebTheoremProofByGoedelIT2>
第2不完全性定理は証明済みとする.このときLöbの定理は次のように証明される.
#proof[
$TheoryT proves Provability(TheoryT, GoedelNumTerm(sigma)) -> sigma$を仮定する.
対偶と演繹定理より,$TheoryT + not sigma proves not Provability(TheoryT, GoedelNumTerm(sigma))$となる.
ここで,$Drv2$の対偶として$TheoryT + not sigma proves (Provability(T, GoedelNumTerm(not sigma)) and Consistency(TheoryT)) -> not Provability(TheoryT, GoedelNumTerm(not sigma -> bot))$が成り立つ.$not Provability(TheoryT, GoedelNumTerm(bot)) equiv Consistency(TheoryT)$であることに注意.
$TheoryT + not sigma proves not sigma$と$Drv1$より$TheoryT proves Provability(T, GoedelNumTerm(not sigma))$であり,
$TheoryT + not sigma proves not Provability(TheoryT, GoedelNumTerm(sigma))$と#ref(<GoedelIT2_GoedelSentenceConsistencyEquality_lem1>)より$TheoryT + not sigma proves Consistency(TheoryT)$である.
よって,$TheoryT + not sigma proves not Provability(TheoryT, GoedelNumTerm(not sigma -> bot))$である.
更に,形式化された演繹定理より,$T + not sigma proves not Provability(TheoryT + not sigma, GoedelNumTerm(bot))$となる.
ここで,$not Provability(TheoryT + not sigma, GoedelNumTerm(bot)) equiv Consistency(TheoryT + not sigma)$であることに注意すれば,$T + not sigma proves Consistency(TheoryT + not sigma)$である.
このとき,第2不完全性定理より$TheoryT + not sigma$は矛盾してしまう#footnote[#ref(<GoedelIT2_Contradiction>)も参照せよ.]ことがわかる.よって,$TheoryT proves sigma$である.
]
== オリジナルのLöbの証明 <OriginalLoebTheoremProof>
一方,Löbのオリジナルの証明では第2不完全性定理を用いておらず,不動点補題を用いてKreisel文と呼ばれる文を構成し,それに基づいて証明している.
#let KreiselSentence = $K$
#definition[
任意の文$sigma$に対して,不動点補題を用いて構成される次の文$KreiselSentence$を,$TheoryT$のKreisel文と呼ぶ.
$
TheoryT proves KreiselSentence <-> (Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> sigma)
$
]
それでは証明しよう.
#proof[
$TheoryT proves Provability(TheoryT, GoedelNumTerm(sigma)) -> sigma$を仮定する.
また,Kriesel文$KreiselSentence$として$TheoryT proves KreiselSentence <-> (Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> sigma)$を構成する.
以下の議論によって,$T proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> Provability(TheoryT, GoedelNumTerm(sigma))$が成り立つ.
+ $TheoryT proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> sigma))$.
- $Drv1$より以下が成り立ち,これを$KreiselSentence$の定義と合わせる.
- $TheoryT proves KreiselSentence ==> TheoryT proves Provability(TheoryT, GoedelNumTerm(KreiselSentence))$.
- $TheoryT proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) ==> TheoryT proves Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, GoedelNumTerm(KreiselSentence))))$.
+ $TheoryT proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> (Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, GoedelNumTerm(KreiselSentence)))) -> Provability(TheoryT,sigma))$.
- $Drv2$より$TheoryT proves Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> sigma))) -> (Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> Provability(TheoryT, GoedelNumTerm(sigma)))$であり,これと1を合わせる.
+ $T proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> Provability(TheoryT, GoedelNumTerm(sigma))$.
- $Drv3$より$TheoryT proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, KreiselSentence)))$であり,これと2を合わせる.
仮定と合わせて#ref(<OriginalLoebTheoremProof_eq>)が成り立つ.
#math.equation(block: true, numbering: "(1)")[
$T proves Provability(TheoryT, GoedelNumTerm(KreiselSentence)) -> sigma$
] <OriginalLoebTheoremProof_eq>
ここで,#ref(<OriginalLoebTheoremProof_eq>)と$KreiselSentence$の定義より$T proves KreiselSentence$であり,$Drv1$より$T proves Provability(TheoryT, GoedelNumTerm(KreiselSentence))$である.
再び#ref(<OriginalLoebTheoremProof_eq>)を用いれば,$T proves sigma$となる.
]
== Löbの定理の系としての第2不完全性定理
Löbの定理は第2不完全定理の一般化ともなっている#footnote[もちろん,Löbの定理を示すために第2不完全性定理を用いたら循環論法となってしまうため,Löbのオリジナルの証明を用いる.].
#theorem(name: [第2不完全性定理の対偶])[
$TheoryT proves Consistency(TheoryT)$ならば$TheoryT$は矛盾する.
]
#proof[
$TheoryT proves Consistency(TheoryT)$だと仮定すれば,$Consistency(TheoryT)$の定義より$TheoryT proves Provability(TheoryT, GoedelNumTerm(bot)) -> bot$である.
するとLöbの定理より$TheoryT proves bot$であり,すなわち$TheoryT$は矛盾してしまう.
]
== 形式化されたLöbの定理
Löbの定理は形式化することが可能である.
#theorem(name: [形式化されたLöbの定理])[
任意の文$sigma$に対して次が成立する.
$
TheoryT proves Provability(TheoryT, GoedelNumTerm(Provability(TheoryT, GoedelNumTerm(sigma)) -> sigma)) -> Provability(TheoryT, GoedelNumTerm(sigma))
$
]
後に$Provability(TheoryT, x)$を単なる様相演算子$square$として見ることになるが,その際に重要な働きとなる.
= Robinson算術についての第2不完全性定理
= 算術$WeakestArithmetic$について
Robinson算術$RobinsonArithmetic$よりも更に弱い算術でも不完全性定理を証明することができる.
そのような算術の例として,Tarski,Mostowski,Robinsonによって算術$WeakestArithmetic$が与えられた#cite("tarski_mstowski_robinson_1953").
この章では,この$WeakestArithmetic$について見ていこう.#cite("vaught_1966", "jones_shepherdson_1983")に基づく.
= Boolosの不完全性定理
= 様相論理
= 証明可能性論理
= Kolmogorov複雑度
= Chaitinの不完全性定理
= 抜き打ちテストのパラドックスの形式化
驚くべきことに,抜き打ちテストのパラドックスを上手く形式化すると,第2不完全性定理が得られるということが分かっている.
この章では#cite("kritchman_raz_2010")に基づき,その証明を見ていくことにしよう.
= 連結の理論
不完全性はどこからやって来るのか?Quineの考察#cite("quine_1946")によれば,それは算術よりもっと根源的な操作である「連結」という操作からやってくるという.
この章では#cite("grzegorczyk_2005", "grzegorczyk_zdanowski_2007")などで提案された,連結の理論(Concatenation Theory)について見ていくことにしよう.
= 自己検証可能な理論
#bibliography("bib.yml", style: "ieee")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.1.1/src/layout.typ | typst | Apache License 2.0 | #import "utils.typ": *
#let compute-nodes(nodes, styles, options) = nodes.map(node => {
// Determine physical size of node content
let (width, height) = measure(node.label, styles)
node.size = (width, height)
node.radius = vector-len((width/2, height/2))
node.aspect = if height == 0pt { 1 } else { width/height }
if node.shape == auto {
let is-roundish = max(node.aspect, 1/node.aspect) < 1.5
node.shape = if is-roundish { "circle" } else { "rect" }
}
if node.stroke == auto {node.stroke = options.node-stroke }
if node.fill == auto { node.fill = options.node-fill }
if node.pad == auto { node.pad = options.node-pad }
if node.outset == auto { node.outset = options.node-outset }
if node.defocus == auto { node.defocus = options.node-defocus }
// add node inset
if node.radius != 0pt {
if node.shape == "circle" {
node.radius += node.pad/2
} else {
node.size = node.size.map(x => x + node.pad)
}
}
node
})
#let to-physical-coords(grid, coord) = {
zip(grid.centers, coord, grid.origin)
.map(((c, x, o)) => lerp-at(c, x - o))
}
#let compute-node-positions(nodes, grid, options) = nodes.map(node => {
node.real-pos = to-physical-coords(grid, node.pos)
node.rect = (-1, +1).map(dir => {
vector.add(node.real-pos, vector.scale(node.size, dir/2))
})
node.outer-rect = rect-at(
node.real-pos,
node.size.map(x => x/2 + node.outset),
)
node
})
/// Convert an array of rects with fractional positions into rects with integral
/// positions.
///
/// If a rect is centered at a factional position `floor(x) < x < ceil(x)`, it
/// will be replaced by two new rects centered at `floor(x)` and `ceil(x)`. The
/// total width of the original rect is split across the two new rects according
/// two which one is closer. (E.g., if the original rect is at `x = 0.25`, the
/// new rect at `x = 0` has 75% the original width and the rect at `x = 1` has
/// 25%.) The same splitting procedure is done for `y` positions and heights.
///
/// - rects (array of rects): An array of rectangles of the form
/// `(pos: (x, y), size: (width, height))`. The coordinates `x` and `y` may be
/// floats.
/// -> array of rects
#let expand-fractional-rects(rects) = {
let new-rects
for axis in (0, 1) {
new-rects = ()
for rect in rects {
let coord = rect.pos.at(axis)
let size = rect.size.at(axis)
if calc.fract(coord) == 0 {
rect.pos.at(axis) = calc.trunc(coord)
new-rects.push(rect)
} else {
rect.pos.at(axis) = floor(coord)
rect.size.at(axis) = size*(ceil(coord) - coord)
new-rects.push(rect)
rect.pos.at(axis) = ceil(coord)
rect.size.at(axis) = size*(coord - floor(coord))
new-rects.push(rect)
}
}
rects = new-rects
}
new-rects
}
/// Determine the number, sizes and positions of rows and columns.
#let compute-grid(nodes, options) = {
let rects = nodes.map(node => (pos: node.pos, size: node.size))
rects = expand-fractional-rects(rects)
// (x: (x-min, x-max), y: ...)
let bounding-rect = zip((0, 0), ..rects.map(n => n.pos)).map(min-max)
let bounding-dims = bounding-rect.map(((min, max)) => max - min + 1)
let origin = bounding-rect.map(((min, max)) => min)
// Initialise row and column sizes to minimum size
let cell-sizes = zip(options.cell-size, bounding-dims)
.map(((min-size, n)) => range(n).map(_ => min-size))
// Expand cells to fit rects
for rect in rects {
let indices = vector.sub(rect.pos, origin)
for axis in (0, 1) {
cell-sizes.at(axis).at(indices.at(axis)) = max(
cell-sizes.at(axis).at(indices.at(axis)),
rect.size.at(axis),
)
}
}
// (x: (c1x, c2x, ...), y: ...)
let cell-centers = zip(cell-sizes, options.spacing)
.map(((sizes, spacing)) => {
zip(cumsum(sizes), sizes, range(sizes.len()))
.map(((end, size, i)) => end - size/2 + spacing*i)
})
let total-size = cell-centers.zip(cell-sizes).map(((centers, sizes)) => {
centers.at(-1) + sizes.at(-1)/2
})
(
centers: cell-centers,
sizes: cell-sizes,
origin: origin,
bounding-size: total-size
)
}
|
https://github.com/detypstify/detypstify | https://raw.githubusercontent.com/detypstify/detypstify/main/README.md | markdown | [](https://builtwithnix.org)

Using OCR to generate Typst code based on images of math formulas as a fully client-side webapp.
# Getting started
## Using the model
The model is hosted here.
## Installation
## Obtaining data
We use oxen to version control our data. To get the oxen executable, run `nix develop`. Then, from the root of this repo, clone the oxen repo:
```sh
oxen clone https://hub.oxen.ai/DiracDelta/data
```
The datasets we use for this project will now be available in `data/`.
## Training the model
Detypstify uses a custom dataset which was generated by transpiling the
[im2latex-230k](https://www.kaggle.com/datasets/gregoryeritsyan/im2latex-230k) with pandoc and
cleaning the resulting data (see `scraper/`). The final dataset is available on
[Kaggle](https://www.kaggle.com/datasets/jachymp/im2typst-230k).
1. Download the dataset and unzip it
2. Run `poetry run train_val_split` to perform a train validation split
3. Generate `formulas.txt` by running `scripts/mk_formulas_txt.sh` on the `train` and `val` directories
4. Install `pix2tex`
1. Follow the instructions to generate `tokenizer, train.pkl, val.pkl`
2. Create a `config.yaml` based on the [template](https://github.com/lukas-blecher/LaTeX-OCR/blob/main/pix2tex/model/settings/config.yaml)
3. Train the model with `python -m pix2tex.train --config config.yaml`
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/006_Return%20to%20Dominaria%3A%20Episode%206.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Return to Dominaria: Episode 6",
set_name: "Dominaria",
story_date: datetime(day: 18, month: 04, year: 2018),
author: "<NAME>",
doc
)
Slogging through the Tivan desert toward the monument plateau, Teferi said, "Mark my words, this time I'll have the answer." It was morning and the sun was already high and hot, stirring the dust. Behind them in the distance were the palm trees of the oasis where they had camped last night. Not far ahead was the monument, a giant block of stone partially concealed by a natural plateau. Travelers from Femeref who passed by on the nearby trade road always assumed it was an ancient ruin. It was ancient, but younger than Teferi. It was also a puzzle he had been trying to solve for years.
Assuming an expression of pretend inquiry, his daughter Niambi said, "What's the definition of insanity again?"
Teferi laughed. "That's only if you don't have a method to your madness, and I always have a method."
#figure(image("006_Return to Dominaria: Episode 6/01.jpg", width: 100%), caption: [Teferi, Hero of Dominaria | Art by <NAME>allis], supplement: none, numbering: none)
"Oh, if we only knew what that method was," Niambi countered with a grin.
"I think this is the day," he told her. "He won't beat me again. Especially now that I have your help." Teferi reached the foot of the plateau, where the sand was a thin layer over paving stones. With his boot, he scuffed it away from the center-point seal.
"It's just a theory," Niambi cautioned. "I don't want you to get your hopes up."
"My hopes are always up." Teferi tapped the seal with his staff.
A seam opened in the paving, the sand sliding into it like flowing water. The seam ran across the buried plaza to the foot of the monument. Stone grated as the halves separated and pushed open to reveal a triangular well with broad steps leading down.
Niambi eyed it warily. Even after their previous visits here, she was still cautious of the monument. It wasn't an attitude Teferi cared to discourage, since the monument was just as dangerous as Niambi thought it was. She said, "You know he's not really here, right?"
"He's here in spirit. And that's close enough, believe me." Teferi went down the stairs, sand scraping on his boot soles. The steps ended at the entrance to the monument's main hall, which at the moment was a dark cavern stretching away under the heavy rock. Stepping aside, he waited to make sure Niambi didn't need help. At fifty, his daughter was still strong and capable, but this wasn't a good age to take a fall. He should know; he aged so slowly, he had been fifty for more than a few decades now.
The lights, powered by the same part-mechanical, part-magical systems as the entrance, began to glow softly, brightening like embers stirred in a hearth. Encased in crystal lozenges, they hovered near the ceiling, illuminating walls covered with arcane writing. Teferi had already deciphered it over the years, hoping for clues. There had been none, and he suspected the inscriptions were just another trap for the unwary, meant to waste the time of anyone trying to penetrate the monument's secrets.
He started down the hallway, Niambi behind him, their steps quiet. Teferi had done this many times already, alone and with Niambi, and they both knew the time for levity had passed. Teferi had defanged many of the monument's traps already, but it still had the potential to bite.
They reached the first junction, where three archways marked corridors leading off in three different directions. With no warning, a dark shape lunged at them out of the right-hand corridor.
Teferi had expected to encounter it at some point near here, but its sudden appearance startled him enough that the time spell he reflexively cast blasted it so hard it separated into its component parts. He sighed with annoyance at himself. He didn't like to overreact, but the thing should have known better than to charge so suddenly when his daughter was standing behind him.
The automaton was a good eight feet high, made of silver and copper metals, shaped like a bulky warrior with a block for a head. Its parts had separated and hung in midair: limbs, the cogs and wheels that drove it, the crystals that supplied its power. It wasn't quite still; all the pieces were vibrating faintly, caught in a timestream where the explosion that had blasted them apart was ever so slowly occurring.
Niambi eyed it warily. "Is it safe?"
"Yes, but don't touch." Teferi moved farther into the junction, where he could watch all three corridors.
Niambi stepped closer to the automaton to study it. She frowned. "I recognize the marks on the carapace. I'm sure you destroyed this one the last time I was here."
"I did," he told her. "I think they repair each other."
"Oh, lovely." She grimaced and stepped back.
#figure(image("006_Return to Dominaria: Episode 6/02.jpg", width: 100%), caption: [Mishra's Self-Replicator | Art by <NAME>], supplement: none, numbering: none)
Of the three corridors, two were always traps, but which two changed every time. Teferi read the floating, shifting glyphs that revealed the right passage, then triggered and disarmed the death light from the giant eye around the first bend. With that done, he and Niambi were able to proceed to the chamber of poisoned needles.
It was a relatively easy one, since Teferi was able to stop the needles once they were in the air, though there were occasionally tricky patterns. As Niambi gathered the skirts of her robe close and picked her way carefully around the hovering needles, it reminded him again of their earlier adventures here. He smiled fondly and said, "Do you remember the mechanical spiders?"
"Yes, Father. Every time I have a nightmare," Niambi said drily.
After two more automatons in the last passage, they came to the central chamber, the heart of the monument. As they stepped from the corridor onto the wide ledge, the light gradually crept up the walls, revealing the true size of the enormous space. All along the upper part of the walls, hundreds of feet up, round doorways for chambers and passageways glowed with light or were dark with shadow, looking down on the central platform and its deceptively simple grid. Teferi had searched all these openings before, and knew they were all just distractions, traps for the unwary, delaying tactics. It was the grid of squares on the center platform, reached by a narrow bridge, that was the real key to the puzzle.
Or possibly the floating blocks were the key. Teferi had spent a long time narrowing it down, and he was certain now it was one or the other. Niambi had a new theory about the blocks, and that was why they were here.
As the light grew brighter, the blocks started to drift into view. They were stone oblongs of a uniform size, floating up from the shadows below and down from above. They would move randomly around the space the entire time Teferi was here.
"Ready?" Teferi asked.
Her expression determined, Niambi took her writing tablet and pencils out of her pack. "Ready."
Teferi walked across the bridge, Niambi following. As he set foot on the center platform, the floating blocks converged.
Niambi crouched down and began scribbling hastily on the tablet while Teferi deflected the blocks that were trying to crush them. After a short time, Niambi called out, "Try six from the left, four from the top down."
Teferi hopped over to hit the sequence with his staff. Nothing. "No change, next," he reported.
And so it went, sequence after sequence. Two more automatons climbed up to challenge Teferi. One he froze in time and the other he tipped off the platform with some quick staff work. Occasional sharp gusts of air battered him and Niambi, raising stinging dust and pulling at Niambi's braids. Then bursts of heat and light. Teferi deflected what he could, endured what he couldn't, and kept entering the sequences Niambi came up with.
After more than an hour, Niambi said, "Father, that's it, we have to stop!"
Teferi left the grid immediately and helped Niambi to her feet, and they retreated across the bridge. As soon as they reached the passage again, all activity in the chamber began to slow and cease.
Niambi sagged against the wall, sweat beading her forehead. "I was wrong, it's not a mathematical problem. Or if it is, it isn't the floating blocks that are the key."
It was disappointing, but Teferi was ancient enough to take the defeat with no more than a sigh. "It was still a good theory. It had to be tested."
Niambi shook her head. "I wasted your time."
He gave her a one-armed hug. "Please. Every father should be so lucky to have a daughter who shares his hobby."
Her laugh turned into a half-sob of exhaustion. "Oh, let's get out of this terrible place."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It wasn't until they were safely through the monument and outside, slogging back through the sand toward their oasis camp, that they could talk again. "Why would he make it so hard?" Niambi said, frustrated. "He must have known you would need it someday."
Teferi gave the stock answer. "He's protecting it from Phyrexians, and the demons and their mages, and everyone else who might want it for the raw power locked inside."
Niambi snorted. "You don't believe that."
She knew him too well. "I don't, but it's the answer everyone wants."
"I know, I just . . ." Niambi gestured in exasperation. "You were his friend! Why would he do this to you?"
Teferi shook his head. "Urza didn't have friends, not like you and I have friends. He had experimental subjects, and those just powerful enough that he considered them sentient beings, if not actually people. But he was what we had at the time."
A shadow fell over the sand. Teferi's instinct said "dragon," and even as he looked up he was ready to cast a spell. But the thing above them was shaped like a boat, and it was strangely familiar . . . It couldn't be what he thought it was.
#figure(image("006_Return to Dominaria: Episode 6/03.jpg", width: 100%), caption: [Weatherlight | Art by <NAME>], supplement: none, numbering: none)
"A skyship?" Niambi said. She stared at Teferi. "Is it here for you?"
Teferi smiled slowly. It #emph[was] what he thought it was. "It's my past, catching up with me."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Gideon climbed down the ladder from the #emph[Weatherlight] , dropping the last few feet to land on the sand. Filled with long shadows from the sunset, the oasis had a large pool surrounded by sparse grass and palm trees, partially sheltered from the wind by rocky outcrops. Some tumbledown abandoned huts stood on the far side of the water, perhaps marking a time when this area had been more traveled. The current inhabitants had made a neat camp lit by a few torches, with a blue canvas tent and a firepit, and rugs and grass mats unrolled on the packed sand for seating.
He had arrived just in time for the introductions. Like <NAME>, both the people they had come to meet were dark-skinned Jamuraans, a tall well-built older man with short graying hair and a lovely woman about the same age, with strands of gray threaded through her long braids.
#figure(image("006_Return to Dominaria: Episode 6/04.jpg", width: 100%), caption: [Niambi, Faithful Healer | Art by <NAME>], supplement: none, numbering: none)
Jhoira explained, "Gideon and Liliana are Planeswalkers."
"Ah, I used to do that." Teferi smiled, as at ease as if they were discussing any other common interest. "This is my daughter, Niambi."
"I'm sorry, your daughter?" Raff asked, confused.
"My father used to be an immortal," Niambi explained kindly. "He ages very slowly. I've been catching up to him for years."
Teferi gestured for them to come into the camp, and as they all took seats around the fire, he said, "And to what do I owe this visit?"
Gideon was a little startled when Jhoira cut right to the point. She said, "We're going to kill Belzenlok and we need a time mage to help us get into the Stronghold."
Teferi lifted his brows. "A time mage. And you think I know a likely one?"
With an indulgent smile, Jhoira said, "Teferi, don't tease. You know we need your help."
Teferi leaned forward, his expression turning serious. "Jhoira, we're not camping in the desert because this is how my daughter and I enjoy spending our leisure time. We're working on something very important."
"Like what?" Liliana asked, watching him with narrow-eyed speculation. "That ancient ruin, maybe?"
"It's not that ancient," Teferi corrected. "It's younger than me."
Gideon had been trying to get a sense of Teferi's character, and he thought the man might want to help them. Which meant the reason he was out here really was important. He said, "Perhaps a trade? We help you with your quest, you help us with ours?"
Teferi eyed him thoughtfully. "You assume you can help me."
With a sigh, Niambi said, "He doesn't want help; he's stubborn, and he wants to do it himself."
Teferi turned to her. "Oh, the unfairness! I would be happy to accept help. I'm just saying—"
"Let them try, Father! It's important!" Niambi said. "And once it's done, you'd be free. I've heard you talk about your friend Jhoira. I know you want to run off and have adventures with her again."
Jhoira held out placating hands. "Just what is it you're trying to do? Does it involve the ruin?"
Teferi regarded her for a long moment. Jhoira reached over and squeezed his hand. She said, softly, "Let us help."
Teferi let out his breath. He looked at Gideon and the others and said, "Do you know the story of Zhalfir?"
Shanna said, "I do."
Raff nodded, and added, "It removed itself from Dominaria to get away from the Phyrexian invasion."
Shanna's expression turned wry. "That isn't quite the story I heard."
Liliana looked impatient, and Gideon said, "What is the story?"
Teferi explained, "At the time of the invasion, Zhalfir was the most advanced nation on Dominaria. Its powerful magic, its technology, its military might meant it would take the brunt of the Phyrexian attack. Urza intended it to take the brunt of the attack. And the leaders of Zhalfir thought they would triumph. I knew better."
He looked out over the dark desert, where the wind blew drifts off the tops of the dunes, the crystalline sand catching the last of the light. "I wanted to spare my people and my homeland from a war I knew would destroy them. So I created a time rift and phased Zhalfir partially out of this plane. The Phyrexians couldn't reach it, but Zhalfirins couldn't reach the rest of Dominaria, either. They still can't."
#figure(image("006_Return to Dominaria: Episode 6/05.jpg", width: 100%), caption: [Teferi's Protection | Art by Chase Stone], supplement: none, numbering: none)
Into the silence, Shanna said gravely, "There were many Zhalfirins in Femeref and Suq'Ata and other places, who could never return, who lost all or part of their families, who lost their homes."
"Yes," Niambi told her. "It made Father very unpopular in our folklore, for some time."
Shanna nodded sympathetically. "I thought he might be that Teferi."
Teferi half-bowed to her with a smile. "The very one."
Jhoira added, "He did the same to the land of Shiv. But later he was able to repair the rift and return Shiv to this plane. That's how he lost his Planeswalker spark."
Liliana lifted her brows, startled. "Really?"
"Yes. It left me unable to return Zhalfir." Teferi made a gesture, taking in the desert around them. "So here I sit."
"He hasn't been just sitting in the sand here the whole time, don't feel too sorry for him," Niambi put in.
"Stop mocking your father's existential pain," Teferi told her.
With an ease that suggested she was well used to dragging Teferi back on track, Jhoira said, "But you have a plan, I assume? You always have a plan."
"I have a plan, but it isn't going very well," Teferi admitted. "I discovered some time ago that my friend Urza had left behind a series of devices and magical artifacts that could be of some help in repairing a time rift. I've been searching a long time, but I've only found the location of one artifact. It's here, in that monument. I hope that if I can retrieve it and unlock its secrets, it will lead me to the other objects. But I've been inside the monument many times, uncovered its secrets and sprung its traps over and over again, and I still haven't been able to get to the artifact."
Gideon was glad to hear Teferi's mission was a good cause. If they could help him complete it, it would be all the better for Dominaria. "Who was Urza hiding the artifact from? The Phyrexians?"
"No. From me." Teferi's smile was dry.
So that was how it was. Gideon said grimly, "That's not very friendly."
"That's what I said," Niambi said. She added, "For the past ten years or so I've been trying to help Father. I had a theory that the central puzzle of the monument was actually a mathematical equation, but we tested it today and it didn't work."
"What was the equation?" Jhoira asked with interest, and two sentences into the explanation Gideon was thoroughly lost.
As Jhoira and Niambi discussed it, he said to Teferi, "If there's any help I can give you to get your artifact, I will. But we're committed to killing Belzenlok." He glanced at Liliana.
Raff explained, "They're helping us kill Belzenlok so then they can go kill <NAME>. Everyone's helping each other." Liliana stared incredulously at him and he added, "It's not a secret, is it?"
"Loose lips get skyships destroyed," Liliana said, darkly.
"You're a necromancer." Teferi studied Liliana thoughtfully. "I take it you have a personal interest in fighting the Cabal."
Liliana eyed him. "Yes, and personal means it's none of your business."
Teferi lifted his brows, but said kindly, "Oh, believe me, I've had plenty of experience cleaning up past mistakes. And when you spend so much of your life as an immortal Planeswalker, the mistakes tend to be grand in scope. It isn't possible to erase them, but with effort you can eventually balance your account."
Gideon could see Teferi's words hit home. Disgruntled, Liliana frowned and looked away.
Gideon thought of his own mistakes, the lost lives he could never make up for. He said, "Liliana is important to our plan to destroy <NAME>. Once we kill Belzenlok, we'll both be free to leave the plane and rejoin our friends."
Liliana said in exasperation, "He hasn't agreed to help us—stop telling him things. And we don't know our 'friends' want us to rejoin them at all."
"That was all a misunderstanding," Gideon protested. He was sure that if they could all just talk, it would be fine.
Then Jhoira and Niambi pushed to their feet, still talking. Shanna, who had been listening to their conversation, stood and dusted the sand off her pants. She said, "We're going back to the monument for another try. Jhoira thinks Niambi has it right, but there's some factor she couldn't take into account."
#figure(image("006_Return to Dominaria: Episode 6/06.jpg", width: 100%), caption: [Construct | Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It was full dark now, the moon rising, as they set out for the monument. "You think you can solve it in one try after I've been working all this time," Teferi said to Jhoira as they trudged through the sand, her mechanical owl flapping ahead of them, glowing as it lit the way.
Jhoira elbowed him in protest. "No, I think you and Niambi solved it. But I think Urza never played fair, and he certainly wouldn't play fair with you."
She had a point there, Teferi admitted.
Once inside, Teferi led them through the monument's defenses to the central chamber. As he disarmed it again, he thought the place had a different feel. The shadows thicker, the stone walls radiating cold. Maybe it was just that it had been many years since he had come here at night.
Finally they stood on the ledge near the walkway to the platform grid. Gideon and Shanna moved to opposite sides, to keep watch for randomly attacking automatons, while Jhoira explained her theory. "I think Niambi is right about the mathematical significance of the movements of the floating blocks, but I think there's an extra factor. This is Urza we're talking about, and he must have known it would be Teferi who would try to solve the puzzle."
The young mage Raff crouched down to study the script carved into the walkway. "You think he tailored this place specifically to prevent Teferi from solving it?"
"Worse, I think he cheated," Jhoira said. "Liliana, do you see any ghosts here?"
Liliana stepped to the edge. Her expression intent, she looked down into the well, then up at the levels above. "Not yet. But if you're right, they won't appear until the rest of this show is triggered." She waggled her fingers, indicating the central well around them.
Teferi didn't want to be a spoilsport, but had to point out, "If there were things in this chamber out of phase, I'd see them."
"That's why I don't think they're out of phase, I think they're ghosts." Jhoira gestured around. "Trapped spirits, held here by spells. This chamber is buzzing with spells, and not all of them are artificer work."
Raff nodded and pushed to his feet. "I'm getting some of that too, though not as much as I bet you're picking up."
"Raff, get out of the way so we can get this started." Liliana rubbed her hands together briskly. "This is going to be fun."
"Restoring Zhalfir is not fun," Teferi corrected sternly. All right, it was a little bit fun, but he felt it was better to maintain decorum in such a dangerous place.
"It will be if this works." Niambi gave him a push. "Go on."
"Be ready," Teferi cautioned them all. "The worst will start as soon as I reach the grid." He stepped onto the narrow bridge and walked out to the platform.
The floating blocks drifted into view as usual and Jhoira counted them aloud for Niambi. Then Liliana said, "Aha, there are spirits here."
#figure(image("006_Return to Dominaria: Episode 6/07.jpg", width: 100%), caption: [Lingering Phantom | Art by YW Tang], supplement: none, numbering: none)
"How many? What direction?" Niambi asked, excitement in her voice.
"Three, that corner there."
Teferi kept his gaze on the grid but had to ask, "What do they look like?"
Liliana said, "Imagine a drift of mist, very faint. Ghosts like these lose cohesion after time, and these are far too old to have forms. Oh, two more, second level floating down."
Niambi's pen scratched frantically, then she called out, "Two down, north quadrant, from the top!"
Teferi entered the sequence with his staff.
They continued, Jhoira counting blocks and Liliana counting captured spirits and Niambi calculating. The automatons appeared, but Shanna and Gideon rammed them off the ledge to tumble down into the well. As Niambi's calculations revealed more of the pattern and Teferi tapped more squares, the onslaught doubled and redoubled. It was as if the place sensed Teferi was close to a solution and was determined to stop him.
Jhoira and Raff cast defensive spells on the ledge as Teferi froze the automatons that climbed directly up the sides of the grid platform. He had never been attacked here like this, not once in all his efforts to solve this puzzle, and his heart started to pound. They had to be on the right track.
Then Teferi hit a square and the platform grated under his feet, groaning with the deep rumble of stone and metal grinding against each other. He leapt back, braced for a new attack. But the square in the center slid ponderously aside to reveal an opening. #emph[This is it! This is the solution!] Teferi flung himself down and reached inside.
A chorus of warning shouts echoed off the stone, but Teferi knew there was no trap here. His fingers brushed metal and he pulled the artifact out.
He got to his feet and held it up. Around him, the chamber went silent, and like clockwork wound down to stillness. The blocks drifted downward to disappear into the well. The automatons froze in place. Teferi held a delicate dark crystal orb nestled in a cage of silver vines. Lights glowed inside it like a captured starfield.
He turned to face the others. Jhoira was triumphant, Raff impressed, and Liliana trying not to look impressed. Gideon and Shanna seemed relieved and interested, each surrounded by a heap of broken automaton parts. Teferi met Niambi's jubilant gaze and slowly grinned. He said, "We won!"
Urza had expected Teferi to be alone here, and had geared all his defenses that way. #emph[I'm not like you, Urza] , Teferi thought. #emph[You never could see any other way but your own.]
Then an ominous rumble sent dust raining down from above. "I'm sure it won't surprise any of you to know Urza was a sore loser," Liliana called out. "I think this place is collapsing!"
Teferi strode across the bridge to the ledge. He handed the artifact to Jhoira and grabbed Niambi's hand. "Everyone, come on!"
Cracks spidered across the walls as they ran through the corridors, the ground shaking under their feet. Teferi froze falling blocks and spelled the ground to keep it from splitting under their feet. He could tell the place was fighting him, resisting every step.
When he was at the limit of his strength, they burst out the entrance into bright moonlight to find the triangular well filling with sand. Jhoira's owl flew in agitated circles overhead and she shouted, "The plateau is sinking."
Teferi tried to freeze the sand in place but there was too much of it. It poured into the well like an ocean, and if they tried to push through it would surely drown them.
Then two ladders dropped from above and Teferi realized the shadow blotting out the moonlight was the #emph[Weatherlight] . "Come on!" Jhoira shouted. "Everyone climb!"
A Serran angel dropped to land in the rising sand before them. Teferi pushed Niambi toward her and said, "Take my daughter!"
#figure(image("006_Return to Dominaria: Episode 6/08.jpg", width: 100%), caption: [Mountain | Art by Titus Lunter], supplement: none, numbering: none)
"Hey!" Niambi objected, but the angel caught her around the waist and leapt upward into the air. The hard flap of her wings blew the sand back enough for Gideon to wade forward and catch a dangling ladder. He held it steady for Liliana. Shanna gave the shorter Jhoira a boost up to the other ladder, and Jhoira swung to one side so Shanna could scramble up with her. Gideon grabbed Raff by the collar and shoved him up after Liliana, then hooked an arm through the lowest rung. Waist deep in sand now, Teferi grabbed the end of the other ladder, and the skyship lifted, pulling them upward.
As soon as the ship's motion freed his legs from the clinging sand, Teferi followed the others up. The person who caught his arm to help him swing over the deck rail appeared to be a vampire, but no one else seemed to find this unusual. As Teferi shook the sand out of his clothes, Niambi gave him a hug and protested, "I could have climbed with everyone else, Father."
That wasn't a chance Teferi had been willing to take. He just turned with her to look down at the monument.
Raff sent glowing orbs into the air, and by their light Teferi saw the great stone building was all but gone. As Teferi watched, the last of the plateau sank into the earth, sand swirling around it like a whirlpool.
Beside him, Jhoira held out the artifact, its central crystal glinting in the light of Raff's magic and the skyship's deck lights. Laughing with delight, she said, "So, are you coming with us to help save the world? Again?"
Teferi let his breath out and smiled slowly. "I think I will."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
After a stop to collect Teferi's and Niambi's belongings from their campsite, they all spent the night on the #emph[Weatherlight] . Jhoira was glad to have the chance to talk with Niambi, and hear about Teferi's life in Femeref. They had a lot of catching up to do.
The next morning Jhoira steered the skyship to the town Niambi and her family lived in, to take her home.
It was a small but prosperous-looking town on the cliffs above a river, where houses with tile roofs were surrounded by orchards and gardens. Niambi's house was on the outskirts, a rambling stone building with a central fountain court shaded by acacia trees.
Jhoira stood by while Teferi and Niambi said goodbye on the deck of the #emph[Weatherlight] . As Niambi hugged him, she said, "Have a good time with your friends. Kill lots of demons."
He answered teasingly, "You aren't even going to pretend to miss your old father."
"I will miss you, but I know you too well." Niambi gave him a shake. "This is what you were born to do. And once you've found a way to return Zhalfir, I expect you to visit so you can give us all a tour. Or warn us, if they want to kill you."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Once they were under way, Jhoira left Tiana to steer the ship and went to her captain's cabin. With a sigh she dropped into her chair. It was a relief to have Teferi back. Only a few more pieces to put into place and they would be able to break into the Cabal's Stronghold and kill Belzenlok. But that was the easy part.
She touched the amulet around her neck, then opened it. Inside lay a small Powerstone, glittering in the dim light. She had made this stone herself at the Thran Mana Rig. It held Teferi's Planeswalker spark.
#emph[The hard part] , she told herself, #emph[is going to be convincing him to take this back] . . .
|
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/huge-math.typ | typst | Apache License 2.0 | $
U(P)
&= - G integral_(r=0)^R integral_(theta = 0)^(pi) integral_(phi=0)^(2 pi) rho(r)/q r^2 dif r dif theta sin(theta) dif phi
&"on choisit de prendre" phi in [0,2 pi[, theta in [0, pi[\
&=- 2 pi G integral_(r=0)^R integral_(theta = 0)^(pi) rho(r)/q r^2 dif r dif theta sin(theta) &"intégration par rapport à" phi "indépendant de" rho\
&=- 2 pi G integral_(r=0)^R integral_(theta = 0)^(pi) rho(r)/q r^2 dif r dif theta sin(theta) &"intégration par rapport à" phi "indépendant de" rho\
&=- 2 pi G integral_(r=0)^R integral_(theta = 0)^(pi) rho(r)/q 11 r^2 dif r dif theta sin(theta) &"intégration par rapport à" phi "indépendant de" rho\
&= - 2 pi G integral_(r=0)^R integral_(theta = 0)^(pi) rho(r)/(r^2 + s^2 - 2 r s cos(theta))^(1\/2) r^2 dif r dif theta
&"formule" q^2 = r^2 + s^2 - 2 r s cos(theta) quad (1)\
&= - 2 pi G
integral_(r=0)^R
integral_(u=-1)^1
(rho(r))/((r^2 + s^2 - 2 r s u)^(1\/2)) r^2 dif r dif u
&u = cos(theta), dif u = - sin(theta) d theta\
&=
- 2 pi G integral_(r=0)^R rho(r) r^2 integral_(u=-1)^1 (dif u)/(((r^2 + s^2) + (-2 r s ) u )^(1\/2)) dif r
&integral (dif x)/sqrt(a + b x) = (2 sqrt(a + b x))/b\
&= - 2 pi G integral_(r=0)^R rho(r) r^2 [2 sqrt(r^2 + s^2 - 2 r s u)/(- 2 r s)]_(-1)^1 dif r\
&= - 2 pi G integral_(r=0)^R rho(r) r^2 1/ (r s) (sqrt(r^2 + s^2 + 2 r s) - sqrt(r^2 + s^2 - 2 r s)) dif r\
&= - (2 pi G)/s integral_(r=0)^R rho(r) r (sqrt((r+s)^2) - sqrt((r-s)^2)) dif r\
&= - (2 pi G)/s
integral_(r=0)^R rho(r) r ((r +s) - (s-r)) dif r
& sqrt((r-s)^2) = abs(r-s) = s-r "car" r < s\
&= - (2 pi G)/s integral_(r=0)^R rho(r) r (2 r) dif r\
&= - (2 pi G)/s integral_(r=0)^R rho(r) 2 r^2 dif r\
&= - G/s integral_(r=0)^R rho(r) 4 pi r^2 dif r\
&= - (G M) /s
$
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas4/4_Stvrtok.typ | typst | #let V = (
"HV": (
("", "<NAME>a", "Kripčájšim mudrovánijem vóinstvovavše slávniji, na lukávaho vrahá opolčístesja, vseorúžijem ohráždšesja duchóvnym dóblestvenňi: i vsjú kríposť bisóvskuju pohubívše, voschítivše dúšy čelovíčeskija jákože korýsti: sehó rádi vo víki vás počitájem, apóstoli."),
("", "", "Krestoobrázno rasprostérši mréžu víry, dvojenadesjática božéstvennych apóstol tvojích, vsjá jazýki ulovíla jésť k tvojemú poznániju Christé: i móre slánoje strastéj izsuší. Sehó rádi ťá moľú, iz hlubiný prehrišénij vozzoví mja, ťích vseblahoprijátnymi moľbámi."),
("", "", "Dvojenadesjática Bohoizbránnaja, apóstoľskaja i vsečéstnája, da voschválitsja dnés božéstvennymi písňmi: Pétr, i Pável, Jákov: Luká, Joánn že i Matféj, i Thomá: Márk, Símon, i Filípp: i preslávnyj nýňi Andréj s Matfíjem, i božéstvennym i premúdrym Vartholoméjem, i s próčimi sedmídesjaťmi."),
("", "", "Mírom božéstvennym ťá pomáza božéstvennaja blahodáť duchóvnaja, Mírjanom pervoprestóľna, i mírom oblahouchávša, dobroďítelmi svjaščénňijšimi míra koncý, sladkodýšuščimi tvojími molítvami, zlosmrádnyja prohoňájušča strásti vsehdá. Sehó rádi ťá vírno slávim, i pámjať tvojú vsesvjatúju soveršájem Nikólaje."),
("", "", "Jáko osijáteľa ťá nezachodímaho, i jáko svitíľnika vsemírna, na tvérdi vozsijávša cerkóvňij Nikólaje, i mír prosvitívša, i bíd ľútych mhlú othoňájušča, i otjémľušča pečálej zímu, i tišinú soďílavšaho hlubókuju, po dólhu ublážájem."),
("", "", "I sýj i javľájajsja v sónijich Nikólaje, íže neprávedno imúščyja umréti spásl jesí, jáko sostradáteľ, jáko blahoľubívyj, jáko izbáviteľ tepľíjšij, jáko predstáteľ ístinnyj vírnych, i prosjáščich tvojehó zastuplénija, svjaščénňijšij ótče, ánhelom sohraždaníne, prepodóbnym i prorókom ravnostojáteľu."),
("Bohoródičen", "", "Jáže Bóha nevmistímaho, vo črévi tvojém vmistívšaja, čelovikoľúbna čelovíka bývša: i náše smišénije iz tebé priímša i obožívša jávi, ne prézri mené vsečístaja, nýňi skorbjášča: no uščédri skóro, i razlíčnyja vraždý že i vréda lukávaho svobodí."),
),
"S": (
("", "", "Apóstolskij lík Dúchom svjatým prosvitíl jesí Christé, i nášu skvérnu hrichóvnuju ťími omýj Bóže, i pomíluj nás."),
("", "", "Neknížnyja učenikí Dúch tvój svjatýj kazáteli javí Christé Bóže, i mnohoviščánnym slíčijem jazýkov prélesť uprazdní, jáko vsesílen."),
("", "", "Žértvy oduševlénnyja, vsesožžénija slovésnaja, múčenicy Hospódni, zakolénija soveršénnaja Bóžija, Bóha znájuščaja, i Bohom znájemaja ovčáta, íchže ohráda volkóm nevchódna: molítesja i nám upasénym býti s vámi, na voďí upokojénija."),
("Bohoródičen", "", "Izbávi ný ot núžd nášich, Máti Christá Bóha, róždšaja vsích tvorcá, da vsí zovém tí: rádujsja jedíno predstáteľstvo dúš nášich."),
),
)
#let P = (
"1": (
("", "", "Mórja čermnúju pučínu nevlážnymi stopámi drévnij pišešéstvovav Izráiľ, krestoobráznyma Mojséovyma rukáma, Amalíkovu sílu v pustýni pobidíl jésť."),
("", "", "Voístinnu i vresnotú rodilá jesí Bóha i Hóspoda, i Bohoródica jedína voístinnu i vrisnotú nareklásja jesí čístaja. Ťímže ťá vírno vospivájem, i po dólhu slávim."),
("", "", "Zvizdá jáže ot Jákova, vozsijá iz tebé prečístaja, izčitájaj mnóžestvo zvízd, jáko Bóh. ťímže tohó sijáňmi otimí mojích hrichóv ťmú."),
("", "", "Nevístnik slovésen vím ťá jávi Bóžija voploščénija, čístaja i vseneporóčnaja: moľú ťa izbáviti mjá strastéj plotskích i skorbéj, i iskušénij, i obstojánij."),
("", "", "jáko ľístvica, jáže k nám prišéstvija vsederžíteleva, jéjuže Bóh sníde na zémľu, ot zemlených strastéj plotskích k nebesí voznesí mjá, i k Bóhu privedí."),
),
"3": (
("", "", "Ne múdrostiju i síloju i bohátstvom chválimsja, no tobóju Ótčeju ipostásnoju múdrostiju Christé: ňísť bo svját, páče tebé čelovikoľúbče."),
("", "", "Tekúščij istóčnik, skorbjáščich uťišénije jesí: ťímže Vladýčice, i mňí molítvennych tvojích vód istóčnik istočí, i uhasí strastéj péšč."),
("", "", "Ujázvena mjá pómysly bezmístnymi iscilí čístaja, jáže jestestvá nášeho iscilívšaja jázvu ľútuju, róždši ziždíteľa i Hóspoda."),
("", "", "V pučíňi mnóhich mojích prehrišénij, i strastéj i iskušénij oburevájema, k tíchomu ziló pristánišču vseneporóčnaja, ustremí tvojím zastuplénijem."),
("", "", "Íže jáko na runó doždém božéstvennym, vo utróbu tvojú sošédšim, oplamenénnoje ohném strastéj mojé sérdce orosí tvojími moľbámi."),
),
"4": (
("", "", "Vozneséna ťá víďivši cérkov na kresťí, sólnce právednoje, stá v číňi svojém, dostójno vzyvájušči: sláva síľi tvojéj Hóspodi."),
("", "", "Ot mír Sýna tvojehó tekúščich, blahouchánijem žízni vsích, míro bezstrástija istočí duší mojéj čístaja, i vés kál strásti jejá potrebí."),
("", "", "Oskvernénnaho mjá kálom hrichá, molítv tvojích okropí issópom, i omýj, i skvérnu strastéj mojích očísti Vladýčice, i javí Christú žilíšče."),
("", "", "Napísanu ťá kníhu pérstom božéstvennym, zapečátanu, prečístaja moľú, pérsty tvojích molítv napiší mňí prehrišénij ostavlénije, i napástej izbávi."),
("", "", "Íže ot konéc hór svjatých vsích, chrám Bóhu bývši jákože préžde prorók rečé: Christú číst pokaží mja chrám Vladýčice, tvojími zastupléňmi."),
),
"5": (
("", "", "Tý Hóspodi mój, svít v mír prišél jesí, svít svjatýj, obraščájaj iz mráčna nevíďinija, víroju vospivájuščyja ťá."),
("", "", "Ťá rósu aermónsku, na Sijón sošédšuju, vídyj Bohorodíteľnice, moľú uhasíti plóti mojejá zapalénije."),
("", "", "Ráj žízni súšči Bohoródice, smérti hrichóvnyja i strastéj mnohoobráznych izbávi mjá vskóri."),
("", "", "Alavástr mýslennyj, čístaja, tý jesí, míra izlijávšahosja na zémľu s nebesé: mené nýňi blahouchánija ispólni."),
("", "", "Preklónšahosja ko tľíniju obnovíla jesí čelovíka: izvedí úbo i mené nýňi Bohonevísto, iz hlubiný prehrišénij i strastéj."),
),
"6": (
("", "", "Požrú ti so hlásom chvalénija Hóspodi, cérkov vopijét tí, ot bisóvskija króve očíščšisja, rádi mílosti ot rébr tvojích istékšeju króviju."),
("", "", "Paláta prekrásna, slávnaja Vladýčice, carjá slávy bývši, proslávila jesí čelovíki: ťímže slávy netľínnyja i mené spodóbi."),
("", "", "Utíšila jesí tľú poróčnuju jestestvá čístym netľínijem, no izsuší prečístaja, strastéj mojích potóki, i plotskíja múdrosti ríki."),
("", "", "Uspí strastnája dvižénija ťilesé, i vzyhránija mojá plotskája umú poviní jáko žrebjá, uspívši, čístaja, snóm tvojích molítv."),
("", "", "Pojú ťa Bóha prepítaho róždšuju, i moľú ťa otrokovíce: strášnyja mjá prí, i víčnaho Bohoródice, osuždénija izbávi i spasí mja."),
),
"S": (
("", "", "Predstáteľnice nerátnaja, Bohorodíteľnice, i molítvennice hotóvaja pritekájuščym k tebí, ot bíd mjá izbávi: da ne prézriši mené, vsích zastúpnice."),
),
"7": (
("", "", "V peščí avraámstiji ótrocy persídstej, ľubóviju blahočéstija páče, néželi plámenem opaľájemi, vzyváchu: blahoslovén jesí v chrámi slávy tvojejá Hóspodi."),
("", "", "Jáko ohnenósna i bohoprijémna súšči kupiná čístaja, popalí pomyšlénij térnije lukávych, duší mojejá ozarí mýsľ, i strastéj bézdnu izsuší."),
("", "", "Velíčestvije ot víka, i božéstvennuju slávu, tý jedína jávi obrilá jesí na zemlí, nébo jávľšisja vtoróje: tý úbo uprazdní veleréčivyja vrahí mojá bísy."),
("", "", "Božéstvennyj okríne milosérdija i bláhosti, istočí mi obíľno bohátstvo tvojích ščedrót, i skvérnu prehrišénij mojích omyvájušči, plotskóje uhasí razžžénije."),
("", "", "Dánnoje mí ot Bóha bohátstvo duchóvnoje préžde, žív blúdno vsehdá, slasťmí izždích ťilésnymi: no jáko blúdnaho, tvojími molítvami Ďívo, opravdí."),
),
"8": (
("", "", "Rúci rasprostér Danijíl, ľvóv zijánija v róvi zatčé: óhnennuju že sílu uhasíša, dobroďíteliju prepojásavšesja, blahočéstija račíteli ótrocy, vzyvájušče: blahoslovíte vsjá ďilá Hospódňa Hóspoda."),
("", "", "Rastórhni prehrišénij mojích plenícu, i ťilésnaja stremlénija utiší, lukávstvija že umyšlénij posicý, i očísti ot tájnych pomyšlénij skóro rabá tvojehó Bohoródice, vsích predstáteľnice vírnych i zastuplénije."),
("", "", "Horá Bóžija javléna, i nesikóma, i túčna prečístaja, častá i osinénnaja, pokrýj mjá síniju tvojích molítv, i ot síti lovéc izbávi, i sochraní ot stríl bisóvskich, i skvérnych pomyšlénij."),
("", "", "Strách božéstvennyj prijáti mí Vladýčice, i dúch umilénija vo utróbi mojéj, i rodíti žitijé dobroďítelno, i strášna lukávym bisóm prečístaja, sotvorí, i božéstvennyja slávy ánheľskich lík sobesídnika."),
("", "", "Otvérzi mí dvéri žíznennyja vskóri, vratá upovánija mojehó, i nastávi prečístaja, k žízni nekončájemij, i cárstvija nebésnaho pokaží mja rabá tvojehó nasľídnika, i božéstvennyja slávy svjatých sopričástnika."),
),
"9": (
("", "", "Jéva úbo nedúhom preslušánija kľátvu vselíla jésť, tý že Ďívo Bohoródice, prozjabénijem črevonošénija mírovi blahoslovénije procvilá jesí: ťím ťá vsí veličájem."),
("", "", "Vozzrí molítvami tvojími, čístaja, na rabá tvojehó, i vskóri predvarí, i oskorbľájuščich i ozlobľájuščich vráh nevídimych izbávi mjá: spasí ot bíd i skorbéj, i mnohoobráznych obstojánij."),
("", "", "Vsehó mja jázvami hrichóvnymi súšča ujázvlena i osuždéna, iscilí Ďívo, i izbávi lukávych pomyšlénij, jáže Slóvo vsesíľnoje róždšaja, blaháho že i čelovikoľúbca."),
("", "", "Pádšaho rádi préžde Adáma v smérť, smérti pričastísja, íže životóm i smértiju obladájaj tvój Sýn, preblahája: ťímže mjá strastéj i padénija tvojími moľbámi vozdvíhni."),
("", "", "Spasí Bohoródice, k tebé pribihájuščich, ot bíd i padéža, hrichá i búri, i ťilésnych strastéj, i volnénija, i žitijá núždnych pečálej, i zlóby lukávstvija."),
),
)
#let U = (
"S1": (
("", "", "Apóstolov pervoprestóľnicy, i vselénnyja učítelije, Vladýku vsích molíte, mír vselénňij darováti, i dušám nášym véliju mílosť."),
("", "", "Svitíla v koncích učenikí tvojá Christé, javíl jesí, sijájuščyja dušám súščym vo ťmí, rázum tvój Vladýko: i lésť ídoľskuju ťích rádi omračív, učéňmi bláhočéstija prosvitíl jesí mír. Ťích moľbámi spasí dúšy náša."),
("Bohoródičen", "", "Skóro prijimí Vladýčice, molítvy náša, i sijá prinesí Sýnu tvojemú i Bóhu, Hospožé vseprečístaja: razruší obstojánija, k tebí pritekájuščich: razsýpli prisidánija i dérzosti Ďívo, nýňi vooružájuščichsja na rabý tvojá."),
),
"S2": (
("", "Skóro predvarí", "Vo vsjú zémľu protečé viščánije váše, i preléstnuju objurodí múdrosť nemúdruju, apóstoli slávniji, privlečé čelovíki iz hlubiný prélesti, pokazá že vsím spasénija stezjú, ťímže nýňi dostójno vás ublážájem."),
("", "", "Víry propovídniki učenikí tvojá Spáse, mírovi pokazál jesí, nastavľája ťími jazýki k rázumu tvojemú: zarjámi bo slóva prosvitíša vsjá, ťmú nerazúmija prohnávše víroju. Ťích molítvami spasí dúšy náša."),
("", "", "Múčenicy tvojí Hóspodi, vo stradánijich svoích vincý prijáša netľínnyja ot tebé Bóha nášeho: imúšče bo kríposť tvojú, mučítelej nizložíša, sokrušíša i démonov nemoščnýja dérzosti. Ťích molítvami spasí dúšy náša."),
("Bohoródičen", "", "Uslýši Vladýčice, ot boľíznennyja duší vopijúščaho rabá tvojehó, i mnóhich mojích zól podážď mí ostavlénije, tebé bo ímam predstáteľnicu v déň i nóšč: izbávi Bohoródice, ot ohňá hejénskaho, i postávi mjá odesnúju Sýna tvojehó i Bóha."),
),
"S3": (
("", "Skóro predvarí", "Lučý jáko sólnce právdy, vás Christós ispustí, prosvitíti vsjú zémľu apóstoli slávniji: božéstvennymi vášimi molítvami, ozarjájete božéstvennym svítom nevečérnim vsích, i prosviščájete víroju soveršájuščich svjatúju vášu pámjať."),
("", "", "Skóro predvarí ótče Nikólaje, i spasí rabý tvojá o nachoďáščich nám bíd i skorbéj, ímaši bo k sozdáteľu i Bóhu derznovénije. Prijidí úbo vskóri ko víroju ťá prizyvájuščym, tvojé nýňi predstáteľstvo i pokróv dáruja."),
("Bohoródičen", "", "Jáko vsích jesí tvorénij výššaja, vospiváti ťá dostójno nedoumivájušče Bohoródice, túne, mólim ťá, pomíluj nás."),
),
"K": (
"P1": (
"1": (
("", "", "Mórja čermnúju pučínu nevlážnymi stopámi drévnij pišešéstvovav Izráiľ, krestoobráznyma Mojséovyma rukáma, Amalíkovu sílu v pustýni pobidíl jésť."),
("", "", "Božéstvenniji Uťíšiteľa orháni, vozhlašájuščiji sehó božéstvennymi vsehdá dochnovéňmi, vospíša písň nám, jáko voístinnu spasíteľnuju, blahoslávniji Christóvy apóstoli."),
("", "", "Božéstvenniji Uťíšiteľa orháni, vozhlašájuščiji sehó božéstvennymi vsehdá dochnovéňmi, vospíša písň nám, jáko voístinnu spasíteľnuju, blahoslávniji Christóvy apóstoli."),
("", "", "Na odrí ľínosti sležjá, i v smérti hrichóvňij nedúhom dušévnym ľúťi istájem, posiščénija mjá slávniji Christóvy samovídcy spodóbite."),
("", "", "Íže slóvom bezslovésije razrišívše jazýkov apóstoli, ot bezslovésnych ďijánij ľúťi omračénoje sérdce mojé, uťíšiteľa blahodátiju , prosvitíte apóstoli."),
("Bohoródičen", "", "Ďíva po roždeství netľínna prebylá jesí, nás rádi jávľšahosja na zemlí, páče slóva róždšaja: jehóže priľížno molí prosvitíti dúšy náša."),
),
"2": (
("", "", "Tristáty krípkija, roždéjsja ot Ďívy, bezstrástija vo hlubiňí, duší tričástnoje potopí, moľúsja: da tebí jáko v timpáňi, vo umerščvléniji ťilesé, pobídnoje vospojú pínije."),
("", "", "Bezpečáľnuju žízň nasľídovav blažénne, i rádosti duchóvnyja ispolňájem prísno, vsjáku pečáľ otžení, moľúsja, ot duší mojejá: jáko da rádujasja slávľu ťá, svjaščénňijšij ótče Nikólaje."),
("", "", "Postávlen býl jesí dobroďítelej vysókich na svíščnici, jákože svitíľnik prosviščáješi serdcá vírnych, svjatíteľu Nikólaje. Ťímže víroju moľú ťá: svitonósnymi molítvami tvojími, duší mojejá ťmú otžení."),
("", "", "Žitijá tľínnaho nýňi pučínoju ótče, iskušénij razlíčnych napolňájem premúdre, k tebí pribihája vopijú: da obrjášču ťá kórmčija, v tišinú prelahájušča búrju, božéstvennymi molítvami tvojími."),
("Bohoródičen", "", "Neusypájuščuju čístaja, imúšči molítvu, uspí náša strásti dušévnyja, svjaščénnymi chodátajstvy tvojími, božéstvennuju i spasíteľnuju dajúšči bódrosť, k Bóžijich choťínij ispolnéniju."),
),
),
"P3": (
"1": (
("", "", "Veselítsja o tebí cérkov tvojá Christé, zovúšči: tý mojá kríposť Hóspodi, i pribížišče i utverždénije."),
("", "", "Hr<NAME>, slovésnych rík tvojích tečénija učeník Vladýko, svjaščénno vozveseľájut."),
("", "", "Hr<NAME>, slovésnych rík tvojích tečénija učeník Vladýko, svjaščénno vozveseľájut."),
("", "", "Hráždane nebésniji, soslužébnicy mýslennym činóm, vseslávniji apóstoli, vsjákija nás skórbi izbávite."),
("", "", "Utverdívyj Christé slovésnaja tvojá nebesá: utverdí mja ťích molítvami, na kámeni tvojích choťínij, jáko blahoutróben."),
("Bohoródičen", "", "Jáko Máti ťá mólit s líkom učeník Hóspodi, jáže tebé čísto rodívšaja: dáruj nám mílosti tvojá."),
),
"2": (
("", "", "Ne múdrostiju, i síloju, i bohátstvom chválimsja, no tobóju Ótčeju ipostásnoju múdrostiju Christé: ňísť bo svját, páče tebé čelovikoľúbče."),
("", "", "Orúžije javílsja jesí, boríteľnyja vrahí zakalája, íchže iskušénija sobľudí nás nevrédnych Nikólaje, soďivájuščich božéstvennoje choťínije."),
("", "", "Sokrušénije mojejá duší, svjatíteľu, uvračúj, sokrušívyj vrážija kózni i lovlénija: da jáko predstáteľa mojehó víroju počitáju ťá."),
("", "", "Razorívyj artemídy bezdúšnaja kápišča, umá mojehó strastnája mečtánija potrebí božéstvennymi chodátajstvy tvojími ótče Nikólaje."),
("Bohoródičen", "", "Ťá predstáteľnicu prečístaja Ďívo, sťažáchom, pretvorí nášu pečáľ na rádosť, i skórbi izbávi raždájuščija smérť."),
),
),
"P4": (
"1": (
("", "", "Vozneséna ťá víďivši cérkov na kresťí, sólnce právednoje, stá v číňi svojém, dostójno vzyvájušči: sláva síľi tvojéj Hóspodi."),
("", "", "Navél jesí na móre kóni tvojá izbránnyja, čelovikoľúbče, zlovírija vódy vozmuščájuščyja, i vsím rázum tvój ístinnyj vozviščájuščyja."),
("", "", "Navél jesí na móre kóni tvojá izbránnyja, čelovikoľúbče, zlovírija vódy vozmuščájuščyja, i vsím rázum tvój ístinnyj vozviščájuščyja."),
("", "", "Zvízdy prosvitívše blahočéstijem mýslennuju tvérď cérkóvnuju, slávniji apóstoli, ot nóšči nevíďinija, i prehrišénij izbávite mjá."),
("", "", "Jávľšesja jákože stríly izoščréni apóstoli, vrážija razžžényja stríly zlóby mojejá nýňi uhasíte, i pomyšlénije mojé utverdíte."),
("Bohoródičen", "", "Dúšu mojú ohorčénuju jádom, soprotívnaho uhryzénijem, ďíjstvennym vračevánijem iscilí, molítvami Christé, róždšija ťá i svjaščénnych apóstol tvojích."),
),
"2": (
("", "", "Siďáj v slávi na prestóľi božestvá, vo óblaci léhci priíde Iisús prebožéstvennyj, netľínnoju dlániju, i spasé zovúščyja: sláva Christé síľi tvojéj."),
("", "", "Preslávnoje žitijé tvojé vezďí ťá preslávna pokazá, čudesý božéstvennymi, i prosviščájemaho, svjatítelem ukrašénije, vsím pochvalú, čtúščym ťá Nikólaje, rádostnymi písňmi."),
("", "", "Na vysóci prestóľi blažénne, Bóha pochvalíl jesí, smirenomúdrija božéstvennymi oblistája svitlosťmí, íchže bo pričástiji býti nás sotvorí, blahoprijátnymi tvojími moľbámi, ótče múdre."),
("", "", "Neprávedno vedómyja na smérť izbávil jesí, révnostiju božéstvennoju ótče, svjaščennoľípne raspalájem. Ťímže vopijém tí: tákožde izmí nás ot napástej, umerščvľájuščich ľúťi sérdce mojé."),
("", "", "Nebesá obchoďá Nikólaje rádostno, nevídimo ótče, vsím prizyvájuščym ťá predstáni, oblehčavájaj nedúhi dúš nášich, i uťišénije bohoľípno podajá."),
("Bohoródičen", "", "Vójinstva ánheľskaja užasájutsja, prečístaja, vospivájušče velíčestvo božéstvennaho roždestvá tvojehó: s nímiže molí Ďívo, vsím spastísja, víroju čístoju tebé blažáščym."),
),
),
"P5": (
"1": (
("", "", "Tý Hóspodi mój, svít v mír prišél jesí, svít svjatýj, obraščájaj iz mráčna nevíďinija, víroju vospivájuščyja ťá."),
("", "", "Lózy živótnyja procvitájušče hrózdije, napojíša vsích viná mýslennaho vesélija, slávniji apóstoli."),
("", "", "Lózy živótnyja procvitájušče hrózdije, napojíša vsích viná mýslennaho vesélija, slávniji apóstoli."),
("", "", "K svítu zápovidej Bóžijich nastávite apóstoli, íže vo ťmí dušévnaho unýnija bezúmno prebyvájuščyja."),
("", "", "Izbávite nás dušévnych prehrišénij, i sudá búduščaho, i tlí i bíd, apóstoli blažénniji."),
("Bohoródičen", "", "spasí mja Bóže, jáko čelovikoľúbec, spasí mja moľbámi neizrečénno tebé rodívšija, i vsích božéstvennych apóstol tvojích."),
),
"2": (
("", "", "Nečestíviji ne úzrjat slávy tvojejá Christé, no mý ťá jedinoródne, Otéčeskija slávy sijánije Božestvá, ot nóšči útreňujušče, vospivájem ťá čelovikoľúbče."),
("", "", "Zašél jesí jákože sólnce, uméryj ótče múdre, i vozsijál jesí u Christá, svitonósnymi sijáňmi čudés tvojích, ozarjája vsjú podsólnečnuju, Nikólaje."),
("", "", "Svjaščénne Nikólaje, uslýši nás vo dní naviďínija iskušénij i skorbéj, vsjákuju ťisnotú othoňája blahodátiju v tebí živúščaho Dúcha."),
("", "", "Sokrušénnuju strasťmí žitéjskimi dúšu mojú imýj, na pómošč ťá prizyváju svjaščénne Nikólaje, potščísja, i dážď mí soveršénnoje iscilénije, umoľája preblaháho."),
("Bohoródičen", "", "Úmnyma očíma, Ďívo, zrjá ťa Isáia, vopijét: sé chóščet rodítisja ot Ďívy Bohootrokovícy Iisús Hospóď, v čelovíkov páki vozroždénije."),
),
),
"P6": (
"1": (
("", "", "Požrú ti so hlásom chvalénija Hóspodi, cérkov vopijét tí, ot bisóvskija króve očíščšisja, rádi mílosti ot rébr tvojích istékšeju króviju."),
("", "", "Pástyrja dóbraho Bohoizbránnaja ovčáta, razsíjannaja po míru, volkóv vsjáko zvírstvo vo óvčuju krótosť, víroju preložíša."),
("", "", "Pástyrja dóbraho Bohoizbránnaja ovčáta, razsíjannaja po míru, volkóv vsjáko zvírstvo vo óvčuju krótosť, víroju preložíša."),
("", "", "Božéstvennaho rajá drevesá dobroplódnaja, preokajánnyja duší mojejá vsé neplódstvo vo blahoplódije dobroďíteľnaho nráva privedíte apóstoli."),
("", "", "Ujázven bých slastéj orúžijem i umróch: íže ot Christá prijémše slávniji blahodáť voskrešáti mértvyja, umerščvlénnuju okajánnuju mojú dúšu oživíte."),
("Bohoródičen", "", "Ustávi duší mojejá svirípuju búrju, Bóže vsích ščédryj, moľbámi róždšija ťá Bohoródicy, apóstol že i múčenik tvojích."),
),
"2": (
("", "", "Prijidóch vo hlubiný morskíja, i potopíla mjá jésť búrja mnóhich hrichóv: no jáko Bóh iz hlubiný vozvedí živót mój, mnohomílostive."),
("", "", "Ukripílsja jesí krípostiju Spásovoju, vozmohíj Bohomúdre, nevídimaho vrahá pohubíti: jehóže ľútaho vréda nás izbávi moľbámi tvojími, ótče Nikólaje."),
("", "", "Mučénija že v hejénňi, ot lukávych čelovík stužénija vrédňijšaho, izbávi nás svjaščénnymi molítvami tvojími, preslávne Nikólaje."),
("", "", "Íže drévle umréti neprávedno imúščiji vojevódy, izbávišasja tvojími predstáteľstvy: jákože ťích, i nás ischití vsjákaho vréda, dostočúdne."),
("Bohoródičen", "", "Ľúdije tvojí i hrád mólit ťá, Máti Bóžija: izmí nás vsjákija núždy, i támošnaho, vsesvjatája Vladýčice, víčnaho osuždénija."),
),
),
"P7": (
"1": (
("", "", "V peščí avraámstiji ótrocy persídsťij, ľubóviju blahočéstija páče, néželi plámenem opaľájemi, vzyváchu: blahoslovén jesí v chrámi slávy tvojejá Hóspodi."),
("", "", "Krípostiju vsesvjatýja própovidi, neléstniji apóstoli Christóvy, prélesti zímu razrušíste, i prosvitíste bohorazúmijem vírnych mudrovánije."),
("", "", "Krípostiju vsesvjatýja própovidi, neléstniji apóstoli Christóvy, prélesti zímu razrušíste, i prosvitíste bohorazúmijem vírnych mudrovánije."),
("", "", "Míro blahouchánnoje istočájušče vsehdá božéstvenniji učenicý, míra úmnaho blahovónija pritekájuščich k vám ispólnite, i zlosmrádnyja strásti otženíte."),
("", "", "Rastľívšaho mjá plotskími bezmístiji, slóva netľínnaho slávniji učenicý, spasíte mjá pojúšča: blahoslovén jesí v chrámi slávy tvojejá Hóspodi."),
("Bohoródičen", "", "Lík ánheľskij, lík múčenik i apóstol tvojích Slóve, móľat vsehdá, mnóhoje blahoutróbija tvojehó čelovikoľúbče: vsích uščédri Bohoródiceju, jáko blahoutróben."),
),
"2": (
("", "", "Júnoši trí vo Vavilóňi, veľínije mučítelevo na bújstvo prelóžše, posreďí plámene vopijáchu: blahoslovén jesí Hóspodi Bóže otéc nášich."),
("", "", "Svjáte Nikólaje, vo svjatých jedínaho vsích tvorcá počivájuščaho, molí osvjatíti nás, i nizposláti bohátyja na ný mílosti svojá."),
("", "", "Prepodóben, práv i krótok, tích i smirén býv slávne, k vysoťí preslávňij svjaščénstva vzjálsja jesí, čudesá soveršája i známenija."),
("", "", "Zakóny božéstvennyja sobľúd prepodóbne, javílsja jesí Bóžij chrám čisťíjšij. Ťímže tí vopijém, vseblažénne: ot vsjákaho prebezzakónija izbávi rabý tvojá."),
("Bohoródičen", "", "Uspí vostánija strastéj mojejá duší, bódrennoju molítvoju tvojéju dážď mí bódrosť, otrokovíce, unýnija dremánije daléče othoňájušči."),
),
),
"P8": (
"1": (
("", "", "Rúci rasprostér Danijíl, ľvóv zijánija v róvi zatčé: óhnennuju že sílu uhasíša, dobroďíteliju prepojásavšesja, blahočéstija račíteli ótrocy, vzyvájušče: blahoslovíte vsjá ďilá Hospódňa Hóspoda."),
("", "", "Ustá ohnedochnovénnaja Christóva, íže bezdvérnaja ustá zahradívše, i spasíteľnoje propovídanije povsjúdu razsíjavše, ot úst vólka mýslennaho izbáviste vopijúščyja: vsjá ďilá Hóspoda pójte, i prevoznosíte jehó vo vsjá víki."),
("", "", "Ustá ohnedochnovénnaja Christóva, íže bezdvérnaja ustá zahradívše, i spasíteľnoje propovídanije povsjúdu razsíjavše, ot úst vólka mýslennaho izbáviste vopijúščyja: vsjá ďilá Hóspoda pójte, i prevoznosíte jehó vo vsjá víki."),
("", "", "Vostrubíte ókrest mojejá umerščvlénnyja duší blahohlásniji trubý Christóvy, apóstoli slávniji, i ot hróba otčájanija i unýnija ľútaho sijú vozdvíhnite, vo jéže píti: vsjá ďilá Hóspoda pójte, i prevoznosíte jehó vo vsjá víki."),
("", "", "Mené zakóny tvojá Christé, poprávšaho umá razvraščénijem, mené Vladýko, blúdnaho, vo hlubiný popólzšasja, i obýčaju lukávomu prísno rabótajušča ne prézri, učenikóv tvojích moľbámi."),
("Bohoródičen", "", "Maríje Hospožé vsjáčeskich, obladájema mjá ot zmíja, i sohrišájušča vsehdá svobodí molítvami tvojími, i porabóti Christú v žitijí čísťi vospiváti: vsjá ďilá Hóspoda pójte, i prevoznosíte vo vsjá víki."),
),
"2": (
("", "", "Izbáviteľu vsích vsesíľne, posreďí plámene blahočéstvovavšyja, snizšéd orosíl jesí, i naučíl jesí píti: vsjá ďilá blahoslovíte , pójte Hóspoda."),
("", "", "Vitíjstvuja božéstvennaja Nikólaje, bezzakónnujuščich nezatvorénaja ustá jávstvenno zahradíl jesí, i ot Árijeva hubíteľstva mnóhija izbávil jesí, pravoslávno pojúščyja: Hóspoda pójte, i prevoznosíte jehó vo vsjá víki."),
("", "", "Íže pobídy tezoimenít svjáte, pobidítelej nás pokaží, molítvami tvojími, strastém raždájuščym smérť, i prebezzakónnych čelovík jazýka ľstíva, vírno prísno moľáščichsja tí."),
("", "", "Pómošč tvojú spasíteľnuju nizposláti nám, umolén búdi čudotvórče Nikólaje, v déň núždy, vnehdá ťá víroju prosjášče mólim."),
("Tróičen", "", "Pravoslávno vírniji poklonímsja svjaťíj Tróici, slávjašče Otcá, i Sýna, i vsesvjatáho Dúcha, vopijúšče: blahoslovíte, pójte Hóspoda, i prevoznosíte jehó vo vsjá víki."),
("Bohoródičen", "", "Mílosti tvojejá mja spodóbi, mílostivijšaho Slóva róždši, blahoslovénnaja vsečístaja: v čás súdnyj predstáni, i izbávi támošňaho mjá čístaja osuždénija."),
),
),
"P9": (
"1": (
("", "", "Kámeň nerukosíčnyj ot nesikómyja horý tebé Ďívo, kraeuhóľnyj otsičésja, Christós, sovokupívyj razstojáščajasja jestestvá. Ťím veseľáščesja, ťá Bohoródice veličájem."),
("", "", "Kámenije izbránnoje, položénnaho vo hlavú úhla kámene, sozdáste vsích vírnych serdcá, kámenem víry vrážija sozdánija, apóstoli, razvérhše."),
("", "", "Kámenije izbránnoje, položénnaho vo hlavú úhla kámene, sozdáste vsích vírnych serdcá, kámenem víry vrážija sozdánija, apóstoli, razvérhše."),
("", "", "Rišíti i vjazáti ot Christá prijémše vlásť, razrišíte zól mojích soúz, i k ľubví Bóžijej privjažíte, i cárstvija pričástnika božéstvennaho soďílajte apóstoli."),
("", "", "Božéstvenniji Vladýki óblacy, izsóchšeje mojé sérdce vsjákim lukávym ďijánijem božéstvennymi túčami nýňi napójte, i plodonósno pokažíte, apóstoli bohoblažénniji."),
("Bohoródičen", "", "So svjatými ánhely, s božéstvennymi apóstoly, so slávnymi múčeniki, tvojehó molí Sýna i Bóha, Bohorodíteľnice prečístaja, ot bíd izbáviti dúšy náša."),
),
"2": (
("", "", "Jéva úbo nedúhom preslušánija kľátvu vselíla jésť: tý že Ďívo Bohoródice prozjabénijem črevonošénija, mírovi blahoslovénije procvilá jesí. Ťím ťá vsí veličájem."),
("", "", "Iscilénija prísno soveršája hrób tvój, blahouchánija míra prepodóbne, istočájet víroju i ľubóviju pristupájuščym Nikólaje, pohrebájaj nedúhov nachódy. Ťímže ťá vsí ublážájem."),
("", "", "Jáko sólnce vsjú ozarjáješi Nikólaje Bohoblažénne, podsólnečnuju, božéstvennych čudés sijáňmi ťmú ľútych obstojánij othoňája, svjaščénnymi chodátajstvy tvojími, archijeréev udobrénije."),
("", "", "Obýčno uščédri ný Nikólaje, žitéjskimi obstojáňmi, i bisóvskimi prélesťmi, lukávych že čelovík iskušéňmi, ľúťi oburevájemyja vsehdá: jáko da ťá vsí ublažájem."),
("", "", "Déň i čás strášnyj pomináj o dušé mojá! Jehdá ťa chóščet privestí na súd Vladýka, i sudíti tvojá ďilá tájnaja, i vozopíj jemú: Spáse spasí mja Nikolája moľbámi."),
("Bohoródičen", "", "Hlás tebí božéstvennaho Havrijíla prinósim rádostno, i vzyvájem: rádujsja rajú, jáže drévo živótnoje posreďí imúščaja vsehdá, preslávnaja Slóva paláto, rádujsja Ďívo vseneporóčnaja."),
),
),
),
"ST": (
("", "", "Apóstolskij lík Dúchom svjatým prosvetíl jesí Christé: i nášu skvérnu hrichóvnuju, ťích rádi omýj Bóže, i pomíluj nás."),
("", "", "Neknížnyja učenikí, Dúch tvój svjatýj kazáteli javí Christé Bóže: i mnohoviščánnym slíčijem jazýkov prélesť uprazdní, jáko vsesílen."),
("Múčeničen", "", "Čestná smérť svjatých tvojích Hóspodi: mečámi bo i ohném, i stúdeniju sokrušájemi, izlijáša króv svojú, nadéždu imúšče na ťá, vosprijáti trudóv mzdú: preterpíša, i prijáša ot tebé Spáse véliju mílosť."),
("Bohoródičen", "", "Ťá sťínu sťažáchom Bohoródice prečístaja, i blahoutíšnoje pristánišče, i utverždénije. Ťímže moľúsja, íže v žitijí oburevájem, okormí, i spasí mja."),
)
)
#let L = (
"B": (
("", "", "Drévom Adám rajá býsť izselén, drévom že krestnym razbójnik v ráj vselísja: óv úbo vkúš, zápoviď otvérže Sotvóršaho: óv že sraspinájem, Bóha ispovída tajáščahosja, pomjaní mja, vopijá, vo cárstviji tvojém."),
("", "", "Pástyrja i Áhnca slovésnaja súšče vospitánija, posreďí volkóv ot nehó jáko áhncy múdriji póslani býste, božéstvennym propovídanijem. Ťích pretvorjájušče svirípstvo na krótosť, víroju zovúšče neuklónnym pómyslom: pomjaní nás Spáse, vo cárstviji tvojém."),
("", "", "Prošédše zemnája ispolnénija apóstoli Hospódni, jáko zvízdy svítlyja, pomračénnyja prélesti razoríste, i svít spasítelnyj preľščénym oblistáste. Ťímže blažím vás Christóvy propovídnicy, prosjášče: molítesja o nás vsehdá ko Hóspodu."),
("Múčeničen", "", "Umerščvľájemi múdriji, i ohném veščéstvennym opaľájemi, popalíste hórkaho mnohobóžija veščestvó blažénniji, i nýňi istočájete iscilénij strují prichoďáščym k vám s víroju, tépľi vzyvájuščym, i vopijúščym Christú: pomjaní nás vo cárstviji tvojém."),
("Tróičen", "", "Nepretknovénnym pómyslom, mýsliju trezvjáščesja rcém, v výšnich so Otcém seďáščemu vkúpi i Dúchom: Tróice nerazďíľnaja, jáže vsjá slóvom préžde sostávľšaja, i vsích prosviščájuščaja, víroju tebí zovúščich, pomjaní nás vo cárstviji tvojém."),
("Bohoródičen", "", "Apóstolov rádoste, i strastotérpec vinéc neuvjadájemyj voístinnu jesí Bohorodíteľnice, vseneporóčnaja otrokovíce, s nímiže isprosí nám Vladýčice, prehrišénij izbavlénije, i žitijá ispravlénije, víroju prosjáščym ťá, i vopijúščym tí: rádujsja, vseístini blahích sokróvišče."),
)
) |
|
https://github.com/Pablo-Gonzalez-Calderon/chic-header-package | https://raw.githubusercontent.com/Pablo-Gonzalez-Calderon/chic-header-package/main/manual/template.typ | typst | MIT License | #import "@preview/showybox:2.0.1": *
#let chic-version = "0.4.0"
#let title-page() = {
block(
width: 100%,
height: 55%,
align(center, {
text(size: 30pt, "Chic-header's Manual")
v(10pt)
text(size: 20pt, "Version " + chic-version)
v(5pt)
text(size: 18pt, emph("Elegant headers and footers for Typst."))
v(10pt)
text(size: 14pt, "<NAME> \n & \n Chic-header's Contributors")
v(15pt)
text(size: 20pt, weight: 900, "Abstract")
align(left)[
Usually, setting a header and a footer for our Typst document is quite annoying and tedious. Also, this task can easily turn hard if we want to set different behaviors for odd pages and even pages, or if we want to implement a custom separator for headers and footers. This package comes to solve those (and more) problems, providing a new alternative for setting headers and footers in your Typst documents.
]
})
)
columns(2, outline(depth: 2, indent: true))
}
#let document-props(body) = {
set document(author: "Chic-hdr Contributors", title: "Chic-header's Manual")
set heading(numbering: "1.")
set text(size: 12pt)
show heading.where(level: 3) : it => {
list(
text(font: "Cascadia Code", size: 11pt, it.body),
marker: sym.floral.r
)
}
show heading: set block(spacing: 1em)
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
set par(justify: true)
body
}
#let line-raw(code: true, value) = raw(
lang: if code {"typc"} else {"typ"},
block: false,
value
)
#let types-color-dict = (
"string": rgb("#d1ffe2"),
"dictionary": rgb("#eff0f3"),
"alignment": rgb("#eff0f3"),
"2d-alignment": rgb("#eff0f3"),
"array": rgb("#eff0f3"),
"array-of-functions": rgb("#eff0f3"),
"none": rgb("#ffcbc4"),
"content": rgb("#a6ebe6"),
"boolean": rgb("#ffedc1"),
"length": rgb("#e7d9ff"),
"integer": rgb("#e7d9ff"),
"relative-length": rgb("#e7d9ff"),
"function": rgb("#e7d9ff"),
"chic-function": rgb("#e7d9ff"),
"body": rgb("#a6ebe6"),
"color": gradient.linear(rgb("#7cd5ff"), rgb("#a6fbca"), rgb("#fff37c"), rgb("#ffa49d"))
)
#let type-block(type) = box(
fill: types-color-dict.at(type, default: white),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
text(
font: "Cascadia Code",
size: 10.5pt,
type
)
)
#let observation(..body) = showybox(
frame: (
title-color: blue.darken(40%),
border-color: blue.darken(40%),
body-color: blue.lighten(95%),
radius: 0pt
),
title: [*Observation*],
..body
)
#let example-box(images) = box(
fill: luma(220),
inset: 11pt,
grid(
columns: (1fr,) * images.len(),
column-gutter: 11pt,
..images.map(img => image(img))
)
)
#let chic-parameters() = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#d73a49"), "#show"): chic.#text(rgb("#4b69c6"), "with")\(
#h(12pt) width: #type-block("relative-length")
#h(12pt) skip: #type-block("array")
#h(12pt) even: #type-block("array-of-functions") #type-block("none")
#h(12pt) odd: #type-block("array-of-functions") #type-block("none")
#h(12pt) ..#type-block("chic-function")
) -> #type-block("body")
]
)
#let chic-header-footer-parameters(h-or-f) = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#4b69c6"), if h-or-f == "header" {"chic-header"} else {"chic-footer"})\(
#h(12pt) v-center: #type-block("boolean")
#h(12pt) side-width: #type-block("length") #type-block("relative-length") 3-item-#type-block("array")
#h(12pt) left-side: #type-block("string") #type-block("content")
#h(12pt) center-side: #type-block("string") #type-block("content")
#h(12pt) right-side: #type-block("string") #type-block("content")
)
]
)
#let chic-separator-parameters() = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#4b69c6"), "chic-separator")\(
#h(12pt) on: #type-block("string")
#h(12pt) outset: #type-block("relative-length")
#h(12pt) gutter: #type-block("relative-length")
#h(12pt) #type-block("length") #type-block("stroke") #type-block("content")
)
]
)
#let chic-styled-separator-parameters() = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#4b69c6"), "chic-styled-separator")\(
#h(12pt) color: #type-block("color")
#h(12pt) outset: #type-block("string")
)
]
)
#let chic-height-parameters() = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#4b69c6"), "chic-height")\(
#h(12pt) on: #type-block("string")
#h(12pt) #type-block("relative-length")
)
]
)
#let chic-offset-parameters() = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#4b69c6"), "chic-offset")\(
#h(12pt) on: #type-block("string")
#h(12pt) #type-block("relative-length")
)
]
)
#let chic-heading-name-parameters() = showybox(
frame: (
radius: 3pt,
inset: 1em,
body-color: luma(250),
border-color: luma(200),
thickness: 0.6pt
),
shadow: (
offset: 1.5pt,
color: luma(200)
),
breakable: true,
text(
font: "Cascadia Code",
size: 10.5pt
)[
#text(rgb("#4b69c6"), "chic-heading-name")\(
#h(12pt) dir: #type-block("string")
#h(12pt) fill: #type-block("boolean")
#h(12pt) level: #type-block("integer")
)
]
) |
https://github.com/AnsgarLichter/light-cv | https://raw.githubusercontent.com/AnsgarLichter/light-cv/main/template/cv-en.typ | typst | MIT License | #import "@preview/light-cv:0.1.0": *
#import "@preview/fontawesome:0.1.0": *
#show: cv
#let icons = (
phone: fa-phone(),
homepage: fa-home(fill: colors.accent),
linkedin: fa-linkedin(fill: colors.accent),
github: fa-github(fill: colors.accent),
xing: fa-xing(),
mail: fa-envelope(fill: colors.accent)
)
#header(
full-name: [<NAME>],
job-title: [Software Engineer with a passion for JavaScript],
socials: (
(
icon: icons.github,
text: [JohnDoe],
link: "https://github.com"
),
(
icon: icons.homepage,
text: [johndoe.com],
link: "johndoe.com"
),
(
icon: icons.mail,
text: [<EMAIL>],
link: "mailto://<EMAIL>"
),
(
icon: icons.linkedin,
text: [<NAME>],
link: "https://linkedin.com/"
)
),
profile-picture: "../media/avatar.jpeg"
)
#section("Professional Experience")
#entry(
title: "Data Analyst",
company-or-university: "BetaSoft Technologies",
date: "2023 - Today",
location: "San Francisco, CA",
logo: "media/ucla.png",
description: list(
[Analyzed large datasets using SQL and Python to extract actionable insights, leading to optimized marketing strategies and increased revenue],
[Designed and implemented data visualization dashboards using Tableau, improving data accessibility and decision-making processes.],
[Collaborated with stakeholders to define key performance metrics and develop automated reporting solutions, streamlining data analysis processes]
)
)
#entry(
title: "Cybersecurity Consultant",
company-or-university: "Gamma Systems Inc.",
date: "2020 - 2022",
location: " London, UK",
logo: "media/ucla.png",
description: list(
[Conducted penetration testing and vulnerability assessments for client networks, identifying and mitigating security risks],
[Developed and implemented cybersecurity policies and procedures to ensure compliance with industry standards and regulations],
[Provided cybersecurity training and awareness programs for employees, reducing the risk of security incidents due to human error]
)
)
#section("Education")
#entry(
title: "Master of Science in Computer Science",
company-or-university: "University of California",
date: "09/2020 - 09/2022",
location: "Los Angeles, USA",
logo: "media/ucla.png",
description: list(
[Thesis: Exploring Deep Learning Techniques for Natural Language Understanding in Chatbots],
[Minor: Mathematics],
[GPA: 4.0]
)
)
#entry(
title: "Bachelor of Science in Computer Science",
company-or-university: "University of California",
date: "09/2017 - 09/2020",
location: "Los Angeles, USA",
logo: "media/ucla.png",
description: list(
[Thesis: Design and Implementation of a Secure File Sharing System Using Blockchain Technology],
[Minor: Mathematics],
[GPA: 3.5]
)
)
#section("Programming Expertise")
#entry(
title: "Chatbot for Mental Health Support",
company-or-university: "Personal Project",
date: "2023 - 2024",
location: "",
logo: "media/ucla.png",
description: list(
[Developed a chatbot using Python and the TensorFlow library for natural language processing],
[Implemented sentiment analysis to assess the emotional state of users during conversations],
[Integrated with external APIs to provide resources and guidance for mental health support based on user responses]
)
)
#entry(
title: "Smart Home Automation System",
company-or-university: "Personal Project",
date: "2020",
location: "",
logo: "media/ucla.png",
description: list(
[Designed a smart home automation system using Raspberry Pi and Arduino microcontrollers],
[Implemented sensors for monitoring temperature, humidity, and motion detection within the home environment],
[Developed a web-based dashboard using HTML, CSS, and JavaScript to control and monitor connected devices remotely]
)
)
#pagebreak()
#header(
full-name: [<NAME>],
job-title: [Software Engineer with a passion for JavaScript],
socials: (
(
icon: icons.github,
text: [JohnDoe],
link: "https://github.com"
),
(
icon: icons.homepage,
text: [johndoe.com],
link: "johndoe.com"
),
(
icon: icons.mail,
text: [<EMAIL>],
link: "mailto://<EMAIL>"
),
(
icon: icons.linkedin,
text: [<NAME>],
link: "https://linkedin.com/"
)
),
profile-picture: "../media/avatar.jpeg"
)
#section("Skills & Interests")
#skill(
category: "Technology",
skills: ("Cybersecurity", "Cloud Computing", "Internt of Things", "Svelte")
)
#skill(
category: "Languages",
skills: ("English (native)", "French (fluent)", "Chinese (Basics)")
)
#skill(
category: "Sports",
skills: ("Gym", "Baseball", "Cricekt")
)
#skill(
category: "Interests",
skills: ("Photography", "Travel", "Music")
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/finite/0.1.0/util.typ | typst | Apache License 2.0 | #import "@preview/t4t:0.3.0": get, def, is, assert, math
#import "@preview/cetz:0.0.2": vector, matrix, draw
#import draw: util, styles, cmd, coordinate
#import util.bezier: quadratic-point, quadratic-derivative
// =================================
// Defaults
// =================================
#let default-style = (
state: (
fill: auto,
stroke: auto,
radius: .6,
label: (
text: auto,
size: auto
)
),
transition: (
curve: 1.0,
stroke: auto,
label: (
text: "",
size: 1em,
color: auto,
pos: .5,
dist: .33,
angle: auto
)
)
)
// =================================
// Vectors
// =================================
/// Set the length of a vactor.
#let vector-set-len(v, len) = if vector.len(v) == 0 {
return v
} else {
return vector.scale(vector.norm(v), len)
}
/// Compute a normal for a 2d vector. The normal will be pointing to the right
/// of the original vector.
#let vector-normal(v) = vector.norm((-v.at(1), v.at(0), 0))
/// Returns a vector for an alignment.
#let align-to-vec( a ) = {
let v = (
("none": 0, "left": -1, "right": 1).at(repr(get.x-align(a, default:none))),
("none": 0, "top": 1, "bottom": -1).at(repr(get.y-align(a, default:none)))
)
return vector.norm(v)
}
// =================================
// Bezier
// =================================
/// Compute a normal vector for a point on a quadratic bezier curve.
#let quadratic-normal(a, b, c, t) = {
let qd = quadratic-derivative(a, b, c, t)
if vector.len(qd) == 0 {
return (0, 1, 0)
} else {
return vector-normal(qd)
}
}
/// Compute the mid point of a quadratic bezier curve.
#let mid-point(a, b, c) = quadratic-point(a, b, c, .5)
// =================================
// Helpers
// =================================
/// Calculate the controlpoint for a transition.
#let ctrl-pt(a, b, curve:1) = {
let ab = vector.sub(b, a)
vector.add(
vector.add(
a,
vector.scale(ab, .5)),
vector.scale(
vector-normal(ab),
curve))
}
/// Calculate the direction vector for a transition mark (arrowhead)
#let mark-dir(a, b, c, scale:1) = vector-set-len(quadratic-derivative(a, b, c, 1), scale)
/// Calculate the location for a transitions label, based
/// on its bezier points.
#let label-pt(a, b, c, style, loop:false) = {
let pos = style.label.at("pos", default:.5)
let dist = style.label.at("dist", default:.33)
let curve = style.label.at("curve", default:1)
let pt = quadratic-point(a, b, c, pos)
let n = quadratic-normal(a, b, c, pos)
if loop == (curve > 0) {
dist *= -1
}
return vector.add(pt,
vector.scale(n, dist))
}
/// Calculate start, end and ctrl points for a transition.
///
/// - start (vector): Center of the start state.
/// - end (vector): Center of the end state.
/// - start-radius (length): Radius of the start state.
/// - end-radius (length): Radius of the end state.
/// - curve (float): Curvature of the transition.
#let transition-pts(start, end, start-radius, end-radius, curve:1) = {
// Is it a loop?
if start == end {
start = vector.add(
start,
vector-set-len(
(1, 2),
start-radius))
end = vector.add(
end,
vector-set-len(
(1, -2),
-end-radius))
if curve < 0 {
(start, end) = (end, start)
} else if curve == 0 {
curve = start-radius
}
return (
start,
end,
ctrl-pt(start, end, curve: -2*curve)
)
} else {
let ctrl = ctrl-pt(start, end, curve:curve)
start = vector.add(
start,
vector-set-len(
vector.sub(
ctrl,
start),
start-radius))
end = vector.add(
end,
vector-set-len(
vector.sub(
end,
ctrl),
-end-radius))
return (
start,
end,
ctrl
)
}
}
/// Fits (text) content inside the available space.
///
/// - ctx (dictionary): The canvas context.
/// - content (string, content): The content to fit.
/// - size (length,auto): The initial text size.
/// - min-size (length): The minimal text size to set.
#let fit-content( ctx, width, height, content, size:auto, min-size:6pt ) = {
let s = def.if-auto(ctx.length, size)
let m = (width: 2*width, height: 2*height)
while (m.height > height or m.width > height) and s > min-size {
s = s*.88
m = measure({set text(s); content}, ctx.typst-style)
}
s = calc.max(min-size, s)
{set text(s); content}
}
/// Prepares the CeTZ context for use with finite
#let prepare-ctx(ctx, force:false) = {
if force or "finite" not in ctx {
// supposed to store state information at some point
ctx.insert("finite", (states:()))
// add default state styles to context
if "state" not in ctx.style {
ctx.style.insert("state", default-style.state)
} else {
if "label" in ctx.style.state and not is.dict(ctx.style.state.label) {
ctx.style.state.label = (text: ctx.style.state.label)
}
ctx.style.state = styles.resolve(default-style.state, ctx.style.state)
}
// add default transition styles to context
if "transition" not in ctx.style {
ctx.style.insert("transition", default-style.transition)
} else {
if "label" in ctx.style.transition and not is.dict(ctx.style.transition.label) {
ctx.style.transition.label = (text: ctx.style.transition.label)
}
ctx.style.transition = styles.resolve(default-style.transition, ctx.style.transition)
}
}
return ctx
}
// Unused
#let calc-bounds( positions ) = {
let bounds = (
x: positions.first().at(0),
y: positions.first().at(1),
width: positions.first().at(0),
height: positions.first().at(1)
)
for (x,y) in positions {
bounds.x = calc.min(bounds.x, x)
bounds.y = calc.min(bounds.y, y)
bounds.width = calc.max(bounds.width, x)
bounds.height = calc.max(bounds.height, y)
}
bounds.width = bounds.width - bounds.x
bounds.height = bounds.height - bounds.y
return bounds
}
#let calc-shift(anchor, bounds:none) = {
let shift = (x: -.5, y: -.5)
if anchor.ends-with("right") {
shift.x -= .5
} else if anchor.ends-with("left") {
shift.x += .5
}
if anchor.starts-with("top") {
shift.y -= .5
} else if anchor.starts-with("bottom") {
shift.y += .5
}
if bounds != none {
shift.x *= bounds.width
shift.y *= bounds.height
}
return shift
}
#let shift-by-anchor(positions, anchor) = {
let bounds = calc-bounds(positions.values())
let shift = calc-shift(anchor, bounds:bounds)
for (name, pos) in positions {
let (x, y) = pos
positions.at(name) = (x + shift.x, y + shift.y)
}
return positions
}
#let resolve-radius(state, style) = if state in style and "radius" in style.at(state) {
return style.at(state).radius
} else if "state" in style and "radius" in style.state {
return style.state.radius
} else {
return default-style.state.radius
}
|
https://github.com/peterw16/da_typst_vorlage | https://raw.githubusercontent.com/peterw16/da_typst_vorlage/main/template/customs.typ | typst | // ******** Custom Elements ********
// A custom outline entry function that ommits filling dots ('.') for level 1 entries
#let outline_entry(it) = {
// do nothing if target is not heading
if it.element.func() != heading {
return it
}
// determine numbering representation of headings
let res = link(it.element.location(),
if it.element.numbering != none {
let numberings = counter(heading).at(it.element.location())
numbering(it.element.numbering, ..numberings)
} + [ ] + it.element.body
)
// determine fillings
if it.level > 1 and it.fill != none {
res += [ ] + box(width: 1fr, it.fill) + [ ]
} else {
res += h(1fr)
}
// add location link
res += link(it.element.location(), it.page)
res
} |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/terms-05.typ | typst | Other | / Term:
Not in list
/Nope
|
https://github.com/xbunax/typst-template | https://raw.githubusercontent.com/xbunax/typst-template/main/微纳材料.typ | typst | #import "@preview/polylux:0.3.1": *
#import "@preview/xarrow:0.2.0": xarrow, xarrowSquiggly, xarrowTwoHead
#import "@preview/whalogen:0.1.0": ce
#import "@preview/fletcher:0.2.0" as fletcher: node, edge
#import themes.university: *
#show: university-theme.with(short-author: "", short-title: "", short-date: "")
// #set text(size: 18pt)
//
#title-slide(
title: "自旋轨道矩诱导的反铁磁磁矩翻转",
// date: "2023年12月",
authors: ("答辩人:朱墨" ),
institution-name: text(font: "Zapfino", "Tongji University"),
)
#set text(font: "STFangsong")
#show figure.caption: it => [
#set align(center)
#text(size: 13pt, [#it.supplement #it.counter.display() #it.body])
]
//
// #slide(
// title: [目录],
// new-section: [],
// )[
// #set text(size: 25pt, font: "STFangsong", weight: 500)
// #let cell = rect.with(
// width: 90%,
// height: 15%,
// stroke: none,
// radius: (rest: 10pt),
// fill: gray,
// )
// #let large_cell = rect.with(
// width: 90%,
// height: 40%,
// stroke: none,
// radius: (rest: 10pt),
// fill: gray,
// )
// #set list(body-indent: 10pt)
// #v(1.5em)
// #grid(rows: 3, row-gutter: 10pt, cell[#align(horizon, [- 研究计划])], large_cell[
// #set align(horizon)
// - 自旋轨道矩诱导的反铁磁磁矩翻转
// #set text(size: 20pt)
// #list(indent: 25pt, marker: [], [
// + DMI模拟程序
// + 退磁场计算并行优化
// + 程序验证
// ])
// ], cell[#align(horizon, [- 研究成果及下一步研究方向])])
//
// ]
// #slide(
// title: [研究计划],
// new-section: [],
// )[
// #set align(horizon + center)
// #let cell = rect.with(fill: gray, width: 95%, height: 49%, radius: (rest: 10pt))
// #set text(size: 20pt)
//
// #grid(
// columns: 2,
// rows: 2,
// row-gutter: 5pt,
// column-gutter: 0pt,
// cell[#set align(left)
// + *第一阶段(2022 年 9 月-2023 年 6 月)*
//
// - 通过阅读书籍和文献,学习自旋电子学理论知识,掌握 STT 效应、SOT 效应原理,调研反铁磁相关研究的进展,并熟练掌握微 C 语言,有一定的编程能力。],
// cell[#set align(left + top)
// 2. 第二阶段(2023年6月-2024年3月)
//
// - 开始熟悉 `mmag2.0` 的程序结构,并阅读源码,了解 `mmag2.0` 如何运行。],
// cell[#set align(left + top)
// 3. 第三阶段(2024年 3 月-2024年12月)
//
// - 利用 CUDA 完成 DMI 模拟模块的编写,并利用现有的结果对模块进行 check,最后利用 DMI 模块进行科学计算。],
// cell[#set align(left + top)
// 4. 第四阶段(2025 年 1 月-2025 年 3 月)
//
// - 工作总结、撰写毕业论文。],
// )
// ]
#slide(
title: "自旋轨道矩诱导的反铁磁磁矩翻转",
new-section: "微磁学模拟",
)[
#let cell = rect.with(stroke: none, width: 100%, height: 100%)
#set text(size: 24pt)
#grid(
columns: (60%, 40%),
column-gutter: 5pt,
cell[- 系统自由能
$ E &=E_("exc") + E_d + E_k +E_("Zeeman") + E_("DMI") $
$ E_("exc")&=J arrow(m)_i dot arrow(m)_j\
E_d &= -mu_0 attach(limits(M), t: arrow) dot attach(limits(H), t: arrow, br: "d")\
E_K &= K sum_(i,j,k)[1-(m_(i,j,k) dot k)^2] delta V \
E_("Zeeman")&=-mu_0 attach(limits(M), t: arrow) dot attach(limits(H), t: arrow, br: "Zeeman")\
E_("DM") &= D sum arrow(r)_(i,j) dot (arrow(m)_i times arrow(m)_j)
$
],
cell[
#set align(center + horizon)
#set text(size: 15pt)
#figure(image("pic/different_spin.png"), caption: [有限差分法示意图])
],
)
]
#slide(
title: "自旋轨道矩诱导的反铁磁磁矩翻转",
new-section: "DMI模拟程序",
)[
#set text(size: 18pt)
#let cell = rect.with(stroke: none, width: 100%, height: 100%)
#let gray_cell = rect.with(
stroke: none,
width: 110%,
height: 100%,
fill: gray,
radius: (rest: 10pt),
)
#grid(
columns: (auto, 52%),
column-gutter: 5pt,
cell[- DMI理论
我们将DMI能量离散化
$ E_("DM") = bold(D_(i,j)) dot sum_(i,j)(bold(m_i) times bold(m_j)) $
通过场和能量的关系$H=- nabla_m E$可以得到离散化的DMI有效场的表达式
$ attach(limits(H), t: arrow, br: "DM") = - 1/mu_0 (diff E)/(diff arrow(m)_i)= -D/(mu_0 M_s)sum(attach(limits(m), t: arrow)_j times attach(limits(r), t: arrow)_(i,j)) $
],
gray_cell[
#set text(size: 13pt)
#show raw.where(block: true): set par(justify: false)
```python
extern void calcai_3DMIfrac(int *nmx, int *nmy, int *nmz,
unsigned char type[],
double D_nu[256],
double D_mix_nu[256],
double Dx[], double Dy[],
double Dz[], double D_dir[3],
double Dc_dir[3]);
//计算面内以及层间DMI系数设置DMI方向
extern double ex_dmi(int *nmx, int *nmy, int *nmz, double *dx,
double *dy,double *dz, double Dx[],
double Dy[], double Dz[],
double mn[], double m[][3]);
//计算体系DMI能量
void calc_Hd2(double m[][3], double mn[], double Hx[][3],
double heff[][3],
int ipmax, int *nx0, int *ny0, int *nz0, int idx,
int idy,
int idz, int iaxdx, int iaxdy, int iaxdz, int iaydx,
int iaydy,
int iaydz, int iazdx, int iazdy, int iazdz,
double *dx,
double *dy, double *dz, double *Dx, double *Dy,
double *Dz);//计算DMI有效场
```
],
)
]
#slide(
title: "自旋轨道矩诱导的反铁磁磁矩翻转",
new-section: "退磁场计算并行优化",
)[
#let cell = rect.with(stroke: none, width: 94%, height: 100%)
#let gray_cell = rect.with(
stroke: none,
width: 110%,
height: 100%,
fill: gray,
radius: (rest: 10pt),
)
#set text(size: 18pt)
#grid(
columns: 2,
column-gutter: 5pt,
cell[
#set align(left + horizon)
在通过静磁能求解退磁能时,其离散形式为
$ E_d = - mu_0 /2 sum_(i,j,k=1,2,dots)H_(d,i,j,k) dot M_(i,j,k) delta V $
我们通过求解Poisson方程的方法来获得磁标势$V$,$(nabla^2 V_d)_(i,j,k)=- rho_(i,j,k)$。采用松弛迭代法(SOR)求解Poisson方程,SOR方法主要是通过求解
$ underbrace(A x=b, "linear equation") =>(D+ omega L)x = omega b -[omega U+(omega -1)D]x $其中D为A的对角矩阵,L为上角矩阵,U为下角矩阵,$omega$为弛豫因子。
],
gray_cell[
矩阵非常适合用CUDA计算,可以降低时间和空间复杂度,提高计算速度。
#text(
size: 15pt,
```c
__global__ void updateVKernel_even(double *d_V, double *d_chrg, int *d_maxiter,int ndx, int ndy, int ndz, int idx, int idy, int idz, int icdx, int icdy, int icdz, double dx2, double dy2, double dz2, double diag, double w,double dVn,double dV,double resid,double maxf,double minf,double medf,double medf2);{
int ix = blockIdx.x * blockDim.x + threadIdx.x;
int iy = blockIdx.y * blockDim.y + threadIdx.y;
int iz = blockIdx.z * blockDim.z + threadIdx.z;
if (ix >= 1 && ix < ndx && iy >= 1 && iy < ndy && iz >= 1 && iz < ndz && (ix + iy + iz) % 2 == 1){
...
}
}
```
)
可以将原本三层嵌套的for循环,通过对线程的索引降低为一次并行计算。
],
)
]
#slide(
title: "自旋轨道矩诱导的反铁磁磁矩翻转",
new-section: "程序验证",
)[
#set text(size: 20pt)
#let gray_cell = rect.with(
stroke: none,
width: 100%,
height: 80%,
fill: gray,
radius: (rest: 10pt),
)
#let cell = rect.with(stroke: none, width: 100%, height: 80%)
- 我们利用层间DMI作用实现磁矩无场翻转作为程序验证的案例。
#grid(
columns: (35%, auto, 28%),
gray_cell[
- 程序参数
#set align(left)
$ M_s &= 1.5 times 10^6 A\/m \
D_("inter") &= 2.0 times 10^(-5)J\/m^2 \
J_("inter") &= 2.8 times 10^(-5) J\/m^2 \
K &= 1.5 times 10^6 J\/m^3 \
"cell size" &= 1 times 1 times 4 "nm" \
"cell num" &=2 times 50 times 50 \ $
],
cell[
#set text(size: 17pt)
#figure(image("pic/sot_switching.png"), caption: [层间DMI实现无场翻转结构])<glacier>
@glacier 展示了$#ce("Pt/Co/Pt/Co/Pt")$结构的示意图,两个Co层之间有RKKY和层间DMI效应。顶部和底部$#ce("Pt")$层充当导体,用于施加电流pulse并生成
SOT。
],
cell[- 物理过程
#set text(size: 18pt)
#fletcher.diagram(
cell-size: 10pt,
spacing: 2.5em,
node-stroke: black,
node-fill: blue.lighten(90%),
node((0, 3), "施加电流pulse产生SOT"),
node((0, 2), "磁矩发生翻转"),
node((0, 1), "撤去电流使磁矩弛豫"),
node((0, 0), [在DMI作用下磁矩发生翻转 \ 翻转方向取决去DM常数方向]),
edge((0, 0), (0, 1), "<="),
edge((0, 1), (0, 2), "<="),
edge((0, 2), (0, 3), "<="),
// edge((1,0), (0,0), "..>", bend: -0deg),
)
],
)
]
#slide(title: "自旋轨道矩诱导的反铁磁磁矩翻转",new-section:"验证数据")[
#let cell = rect.with(stroke: none, width: 100%, height: 100%)
#let graycell = rect.with(stroke: none, fill: gray, radius: (rest: 10pt),height:90%,width:100%)
#grid(columns:2,column-gutter:5pt,
cell[
#figure(image("pic/data_unfield_switching.png",height:80%), caption: [层间DMI实现无场翻转物理过程])<figure3>
],
graycell[
#set align(horizon)
#set text(size: 18pt)
- @figure3 (`b`)展示了在前10ns未加电流时,FM结构中磁矩的初始状态。@figure3 (`c`)展示了在10ns前AFM结构中磁矩的初始状态。
- 随着10ns后施加电流pulse,在SOT效应的作用下,磁矩发生翻转,倒向了面内方向。
- 电流pulse结束后,在DMI作用下,系统弛豫足够长时间后,磁矩在层间DMI的作用下发生了可控翻转,翻转方向取决于DMI方向。
])
// ],
// )
]
// #slide(
// title: "研究成果",
// new-section: "论文情况",
// )[
// #set text(size: 18pt)
// #set align(horizon)
// #let graycell = rect.with(stroke: none, fill: gray, radius: (rest: 10pt), height: 70%)
// #v(2em)
// #graycell[
// - *目前有一篇关于层间DMI实现无场翻转的二作论文在投*
//
// [1]Zheng, Cuixiu, <NAME>, <NAME>, <NAME>, <NAME>和<NAME>.
// 《Interlayer Dzyaloshinskii–Moriya Interaction Assisted Field-Free Magnetization
// Switching》
// ]
// ]
// #slide(title: "下一步研究方向", new-section: "DMI对激发Thz频率的影响")[
// #set text(size: 18pt)
// #let graycell= rect.with(stroke: none, fill: gray, radius: (rest: 10pt))
// #let cell= rect.with(stroke:none,height:55%)
// #let fullcell= rect.with(stroke:none,width:110%)
// // == 我们使用`Vampire`作为我们原子尺度反铁磁模拟软件
// == *在反铁磁体系中探究DMI对电流诱导自旋波激发过程的影响*
// #v(1em)
// - 写出系统的哈密顿量
// #grid(rows: 2,
// graycell[
// $ H_s = J_1 sum_(<i,j>_("xy")) bold(S)_i dot bold(S)_j + J_2 sum_(<i,j>_z) bold(S)_i dot bold(S)_j +overbrace(sum_(<i,j>_("xy")) D_(i,j) dot bold(S)_i times bold(S)_j,D_("ij")^k=D^k dot (bold(z) times bold( u_("ij") ))) - sum_i K (accent(n,hat)_i dot bold(S)_i)^2 $],
// cell[
// #grid(columns:2,
// fullcell[
// #figure(image("pic/layer_DMI.png",height:80%), caption: [`R <NAME>, et al., Nature Physics, 14(2018), 217-219.`
// \ 层间DMI示意图])
// ],
// fullcell[
// #v(3em)
// 由于我们的体系是重金属层和反铁磁层双层结构,由于界面处的对称性破缺,磁性原子对和非磁性原子之间会产生较大的DMI。
// ]
// )]
// )
// ]
#focus-slide[
#set align(center + horizon)
欢迎各位老师批评指正!
]
// #matrix-slide[
// left
// ][
// middle
// ][
// right
// ]
// #matrix-slide(columns: 1)[
// top
// ][
// bottom
// ]:SymbolsOutline<CR>
// #matrix-slide(columns: (1fr, 2fr, 1fr), ..(lorem(8),) * 9)
|
|
https://github.com/YouXam/kobe_numbers | https://raw.githubusercontent.com/YouXam/kobe_numbers/main/kobe_numbers.typ | typst | MIT License |
#let iwidth = 1.8em
#let H(path, left: 0em, right: 0em) = box(align(center)[#image(path)], width: iwidth, height: iwidth, stroke: black + 0.2pt, baseline: 0.6em, inset: (top: 0.1em, left: left, right: right))
#let map = (
"1": ($2/2$, false, true),
"2": ($2$, false, false),
"3": ($24/8$, false, true),
"4": ($4$, false, false),
"5": ($4+2/2$, true, true),
"6": ($24/4$, false, true),
"7": ($8-2/2$, true, true),
"8": ($8$, false, false),
"9": ($8+2/2$, true, true),
"0": ($2-2$, true, true),
"24": ($24$, false, false),
"12": ($24/2$, false, true)
)
#let expand(map, func, op) = {
let pairs = map.pairs()
for (ka, va) in pairs {
for (kb, vb) in pairs {
if ka != kb {
let (a, na, ea) = va
let (b, nb, eb) = vb
let pa = if na { "(pa)" } else { "pa" }
let pb = if nb { "(pb)" } else { "pb" }
let key = str(func(int(ka), int(kb)))
if map.at(key, default: none) == none {
map.insert(key, (eval(pa + op + pb, mode: "math", scope: (pa: a, pb: b)), true, true))
}
}
}
}
map
}
#{
map = expand(map, (a, b) => a * b, " times ")
}
#let find(x) = {
if map.at(str(x), default: none) != none {
return map.at(str(x))
}
let h = calc.floor(calc.sqrt(x))
if x - h * h == 0 {
let (a, na, ea) = find(h)
let pa = if na or ea { "(pa)" } else { "pa" }
(eval(pa + "^2", mode: "math", scope: (pa: a)), true, true)
} else {
let (a, na, ea) = find(h)
let (b, nb, eb) = find(x - h * h)
let pa = if na or ea { "(pa)" } else { "pa" }
(eval(pa + "^2 + pb", mode: "math", scope: (pa: a, pb: b)), true, true)
}
}
#let kobe_numbers(body) = {
show "2": H("kobe/2t.png", right: 0.5em)
show "4": H("kobe/4t.png", left: 0.5em)
show "24": H("kobe/24t.png")
show "8": H("kobe/8t.png")
show par: set block(spacing: 3em)
show regex("-{0,1}\d+"): it => {
if it.text.at(0) == "-" {
let (a, na, ea) = find(int(it.text.slice(1)))
if na {
box(eval("-(pa)", mode: "math", scope: (pa: a)))
} else {
box("-" + a)
}
} else {
box(find(int(it.text)).at(0))
}
}
body
} |
https://github.com/Isaac-Fate/math | https://raw.githubusercontent.com/Isaac-Fate/math/main/mathematical-analysis/mathematical-analysis.typ | typst | #import "@local/booxtyp:0.0.1": *
#show: book
#cover(
[Mathematical Analysis],
image("figures/coffee.jpg"),
authors: ("<NAME>",),
bar-color: color-schema.orange.primary,
)
#outline()
= The Real and Complex Number System
$RR$
|
|
https://github.com/chinabobo/resume-template | https://raw.githubusercontent.com/chinabobo/resume-template/main/main.typ | typst | MIT License | #show heading: set text(font: "Linux Biolinum")
#show link: underline
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
#set par(justify: true)
#let chiline() = {v(-3pt); line(length: 100%); v(-5pt)}
= <NAME>
<EMAIL> |
#link("https://herbertyan.netlify.app/")[herbertyan.netlify.app] |
#link("https://github.com/chinabobo")[github.com/chinabobo]
== Education
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(10)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(10)
== Work Experience
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
== Projects
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
|
https://github.com/DaAlbrecht/lecture-notes | https://raw.githubusercontent.com/DaAlbrecht/lecture-notes/main/discrete_mathematics/relation.typ | typst | MIT License | #import "../template.typ": *
#import "@preview/diagraph:0.2.5": *
= Relation
== Cartesian product
#definition[The Cartesian product of two sets $A$ and $B$ is the set of all ordered pairs $(a, b)$ where $a$ is an element of $A$ and $b$ is an element of $B$.
\
$ A * B = {(a,b) bar.v a in A and b in B}$]
#example[The Cartesian product of the sets $A = {1, 2}$ and $B = {3, 4}$ is:\
$A * B = {(1, 3), (1, 4), (2, 3), (2, 4)}$.]
#definition[A relation $R$ from a set $A$ to a set $B$ is a subset of the Cartesian product $A * B$.
\
$R subset.eq A * B$]
#example[Let $A = {1, 2}$ and $B = {3, 4}$. The relation $R = {(1, 3), (2, 4)}$ is a relation from $A$ to $B$.]
For $(a, b) in R$, we write $a R b$, and say that $a$ is in relation $R$ to $b$.
== Inverse relation
#definition[The inverse relation $R^{-1}$ of a relation $R$ is the relation that contains the ordered pairs of $R$ in reverse order.
\
$R^{-1} = {(b, a) | (a, b) in R}$]
#example[Let $R = {(1, 3), (2, 4)}$. The inverse relation $R^{-1}$ is:\
$R^{-1} = {(3, 1), (4, 2)}$.]
== Composition of relations
#definition[
Given the relation $R subset.eq A * B$ and $S subset.eq B * C$,
the composition of $R compose S$ is the relation from $A$ to $C$ defined by:
\
\
$R compose S = {(a, c) | exists b in B, (a, b) in R and (b, c) in S}$]
#pagebreak()
== Representation of relations
Relations can be represented in different ways, one way is by using a directed graph.
#example[$R = {(a,1), (b,1), (b,3), (c,2)} subset.eq A * B$ when $A = {a, b, c}$ and $B = {1, 2, 3}$.
\
#raw-render(
```
digraph {
rankdir=LR
a -> 1
b -> 1
b -> 3
c -> 2
}
```)
or $R^{-1} = {(1, a), (1, b), (3, b), (2, c)}$.
\
#raw-render(
```
digraph {
rankdir=LR
1 -> a
1 -> b
3 -> b
2 -> c
}
```)
]
#pagebreak()
== Relations $R subset.eq A * A$
Relations that are subsets of the Cartesian product of a set with itself are called relations on the set.
They can have the following properties:
#definition[Reflexive: $(a, a) in R forall a in A$.]
#example[The relation $R = {(1, 1), (2, 2)} subset.eq A * A$ is reflexive.
\
#raw-render(
```
digraph {
1 -> 1
2 -> 2
}
```)
]
#definition[Transitive: $forall a, b, c in A, (a, b) in R and (b, c) in R arrow.r.double (a, c) in R$.]
#example[The relation $R = {(1, 2), (2, 3), (1, 3)} subset.eq A * A$ is transitive.
\
#raw-render(
```
digraph {
rankdir=LR
1 -> 2
2 -> 3
1 -> 3
}
```)
]
#definition[Symmetric: $forall a, b in A, (a, b) in R arrow.r.double (b, a) in R$.]
#example[The relation $R = {(1, 2), (2, 1)} subset.eq A * A$ is symmetric.
\
#raw-render(
```
digraph {
rankdir=LR
1 -> 2
2 -> 1
}
```)
]
#definition[Antisymmetric: $forall a, b in A, (a, b) in R and (b, a) in R arrow.r.double a = b$.
\
or equivalently: $forall a, b in A, (a, b) in R and a != b arrow.r.double (b, a) in.not R$.]
#example[The relation $R = {(1, 2),(2, 3), (1,1)} subset.eq A * A$ is antisymmetric.
#raw-render(
```
digraph {
rankdir=LR
1 -> 2
2 -> 3
1 -> 1
}
```)
]
#definition[Asymmetric: $forall a, b in A, (a, b) in R arrow.r.double (b, a) in.not R$.]
#example[The relation $R = {(1, 2), (2, 3)} subset.eq A * A$ is asymmetric.
\
#raw-render(
```
digraph {
rankdir=LR
1 -> 2
2 -> 3
}
```)
]
#statement[
A relation $R$ on a set $A$ is called an equivalence relation if it is *reflexive*,
*symmetric*, and *transitive*.
\
For $(a, b) in R$, we say that $a$ is *equivalent* to $b$ and write $a equiv b$.
]
== Equivalence classes
#definition[
Given an equivalence relation $R$ on a set $A$, the equivalence class of an element $a in A$ is the set of all elements in $A$ that are equivalent to $a$.
\
$[a]_R = {b in A | a equiv b}$
]
Given the relation $R$ is an equivalence relation on the set $A$ then the following properties hold:
#statement[
1. The equivalence classes of $R$ form a partition of $A$.
\
2. A partition of a set $A$ is a collection of nonempty, mutually disjoint subsets of $A$ whose union is $A$.
]
== Order Relations
#definition[
A relation $R$ on a set $A$ is called a order(relation) if it is *reflexive*, *antisymmetric*
and *transitive*.
\
Often denoted by $a lt.eq b$.
]
For each order there also exists a strict order. A strict order is the result of removing the reflexive property from the order relation.
=== Strict order
#definition[
A relation $R$ on a set $A$ is called a strict order if it is *antisymmetric* and *transitive* and *not reflexive*.
]
#statement[
From each order relation $R$ there exists a strict order relation $S$ such that $a R b arrow.l.r.double.long a S b and a != b$.
From each strict order a order relation can be derived by adding the reflexive property.
]
#example[
$A lt.eq B$ is a order relation on the set $A$.
\
$A lt B$ is a strict order relation on the set $A$.
]
== Comparability
Two elements $a$ and $b$ in a set $A$ are said to be comparable with respect to a relation $R$ if either $a R b$ or $b R a$.
=== Total order
#definition[
A relation $R$ on a set $A$ is called a total order if it is a partial order and for all $a, b in A$ either $a R b$ or $b R a$.
]
#statement[
Total means that for any elements $a$ and $b$ in $A$, they are always related (they can always be compared) with respect to $R$
$arrow.l.r.double.long a R b or b R a$.
]
=== Partial order
#definition[
A relation $R$ on a set $A$ is called a partial order if it is *reflexive*,
*antisymmetric* and *transitive*.
]
#statement[
Partial means that for any elements $a$ and $b$ in $A$, they are not always related (they can not always be compared) with respect to $R$
$arrow.l.r.double.long a R b or b R a$.
]
== closures
Closure of a relation $R$ is the smallest relation that contains $R$ and has a certain property.
=== Reflexive closure
#definition[
The reflexive closure of a relation $R$ on a set $A$ is the smallest relation that contains $R$ and is reflexive.
\
A relation $R$ is reflexive if for all $a in A$, $(a, a) in R$.
]
#statement[
The reflexive closure of a relation $R$ is $R union {(a, a) | a in A}$.
\
Often denoted by $[R]^"refl"$.
]
#example[
Let $R = {(1, 2), (2, 3)} subset.eq A * A$.
\
The reflexive closure of $R$ is $R union {(1, 1), (2, 2), (3, 3)}$.
]
=== Transitive closure
#definition[
The transitive closure of a relation $R$ on a set $A$ is the smallest relation that contains $R$ and is transitive.
\
A relation $R$ is transitive if for all $a, b, c in A$, $(a, b) in R and (b, c) in R arrow.r.double (a, c) in R$.
]
#statement[
The transitive closure of a relation $R$ is the intersection of all transitive relations that contain $R$.
\
Often denoted by $[R]^"trans"$.
\
$[R]^"trans" = R union {(a, c) | exists b in A, (a, b) in R and (b, c) in R}$.
]
#example[
Let $R = {(1, 2), (2, 3)} subset.eq A * A$.
\
The transitive closure of $R$ is $R union {(1, 3)}$.
]
=== Symmetric closure
#definition[
The symmetric closure of a relation $R$ on a set $A$ is the smallest relation that contains $R$ and is symmetric.
\
A relation $R$ is symmetric if for all $a, b in A$, $(a, b) in R arrow.r.double (b, a) in R$.
]
#statement[
The symmetric closure of a relation $R$ is $R union {(b, a) | (a, b) in R}$.
\
Often denoted by $[R]^"sym"$.
]
#example[
Let $R = {(1, 2), (2, 3)} subset.eq A * A$.
\
The symmetric closure of $R$ is $R union {(2, 1), (3, 2)}$.
]
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/content/outlook.typ | typst | = Conclusion and Outlook
During the course of this work, we took a closer look at an already introduced @hda, @smhdt and provided a concrete realization.
Our experiments showed that after a certain point, using more metrics $S$ won't improve the @ber any further as they behave asymptotically for $S arrow infinity$.
Furthermore, we concluded that for higher choices of the symbol width $M$, @smhdt will not be able to improve on the @ber, as the initial error is too high.
An interesting addition to our analysis provided the improvement of Gray-coded labelling for the quantizer as this resulted in an improvement of $approx 30%$.
Going on, we introduced the idea of a new @hda which we called Boundary Adaptive Clustering with Helper data @bach.
Here we aimed to utilize the idea of moving our initial @puf measurement values away from the quantizer bound to reduce the @ber using weighted linear combinations of our input values.
Although this method posed promising results for a sign-based quantization yielding an improvement of $approx 96%$ in our testing, finding a good approach to generalize this concept turned out to be difficult.
The first issue was the lack of an analytical description of the probability distribution resulting from the linear combinations.
We accounted for that by using an algorithm that alternates between defining the quantizing bounds using an @ecdf and optimizing the weights for the linear combinations based on the found bounds.
The initial loose definition to find ideal linear combinations which maximize the distance to their nearest quantization bounds did not result in a stable probability distribution over various iterations.
Thus, we proposed a different approach to approximate the linear combination to the centers between the quantizing bounds.
This method resulted in a stable probability distribution, but did not provide any meaningful improvements to the @ber in comparison to not using any helper data at all.
Future investigations of the @bach idea might find a solution to the convergence of the bound distance maximization strategy.
Since the vector of bounds $bold(b)$ is updated every iteration of @bach, a limit to the deviation from the previous position of a bound might be set.
Furthermore, a recursive approach to reach higher order bit quantization inputs might also result in a converging distribution.
If we do not want to give up the approach using a vector of optimal points $bold(cal(o))$ as in the center point approximation, a way may be found to increase the distance between all optimal points $bold(cal(o))$ to achieve a better separation for the results of the linear combinations in every quantizer bin.
If a converging realization of @bach is found, using fractional weights instead of $plus.minus 1$ could provide more flexibility for the outcome of the linear combinations.
Ultimately, we can build on this in the future and provide a complete key storage system using @bach or @smhdt to improve the quantization process.
But in the end, the real quantizers were the friends we made along the way.
|
|
https://github.com/KaarelKurik/conditional-plasticity | https://raw.githubusercontent.com/KaarelKurik/conditional-plasticity/main/README.md | markdown | # Conditional plasticity
This repo includes both the `typst` and `latex` versions of my article on some
cute results in the theory of Banach space geometry. The `typst` version is
the original and likely has fewer typos, and it looks generally nicer.
The `latex` version can be found on the arxiv at https://arxiv.org/abs/2403.09245.
There is also a funny *ad hoc* shotgun parsing file `parsy.py` that was used
to aid conversion of `typst` to `latex`, since `pandoc` was insufficient
at the time of conversion. |
|
https://github.com/gvallinder/KTHThesis_Typst | https://raw.githubusercontent.com/gvallinder/KTHThesis_Typst/main/Template/kth_thesis.typ | typst | MIT License | #let sans_font = "Figtree"
#let serif_font = "Georgia"
#let math_font = "STIX Two Math"
#let titlepage(
title: "",
subtitle: "",
author: "",
degree: "",
body
) = {
set page(
paper: "sis-g5",
margin: 0mm
)
let kth_blue = rgb("000061")
align(center+top)[
#v(15%)
#image("../Figures/KTH_logo_RGB_bla.svg", width: 26%)
]
align(center+bottom)[
#set text(font: sans_font, fill: kth_blue)
#text(size: 12pt, degree)\
#v(1cm)
#text(size: 26pt, strong(title))\
#v(0.5cm)
#text(size: 16pt, subtitle)\
#v(1cm)
#text(size: 12pt, upper(author))\
#v(0.5cm)
#text(size: 10pt, "KTH Royal Institute of Technology")\
#v(15%)
]
pagebreak(to: "even")
body
}
#let kth_thesis(
title: "",
subtitle: "",
author: "",
degree: "",
add_dummy_titlepage: false,
body
) = {
set document(title: title, author: author)
if add_dummy_titlepage {
show: doc => titlepage(
title: title,
subtitle: subtitle,
author: author,
degree: degree,
doc
)
}
set text(font: serif_font, size: 11pt)
set page(
paper: "sis-g5",
margin: (
top: 30mm,
bottom: 30mm,
outside: 18mm,
inside: 36mm)
)
// Configure paragraph properties.
set par(
leading: 0.78em,
first-line-indent: 1em,
hanging-indent: 0pt,
justify: true,
linebreaks: "optimized")
show par: set block(spacing: 0.78em)
// Heading settings
show heading: set text(font: sans_font, weight: "bold", number-width: "tabular")
show heading.where(level: 1): it => text(21pt)[#it] + v(1em)
show heading.where(level: 2): it => text(13pt)[#it] + v(0.25em)
show heading.where(level: 3): it => text(11pt)[#it] + v(0.25em)
show heading.where(level: 4): it => text(size: 11pt, weight: "regular", style: "italic")[#it] + v(0.25em)
// Outline settings
show outline: set text(font: sans_font, number-width: "tabular")
show outline.entry.where(level: 1): it => [#v(1em) #text(weight: "bold",it)]
// List settings
set list(body-indent: 4mm)
// figure settings
show figure.caption: it => text(size: 10pt, font: sans_font, it)
// footnote settings
show footnote.entry: it => text(font: sans_font, it)
// math settings
show math.equation: set text(font: math_font)
set math.equation(numbering: "(1)")
body
}
#let header(
title: "",
body
) = {
set page(
header: locate(
loc => if calc.even(loc.page()){
set text(font: sans_font, size: 9pt)
align(left)[
*#loc.page()* #h(1em) #upper(title)
]
} else {
set text(font: sans_font, size: 9pt)
align(right)[
#upper(title) #h(1em) *#loc.page()*
]
}
)
)
body
}
#let chapter(
title: [],
body
) = {
pagebreak()
show: it=> header(title: title, it)
v(2cm)
heading(title)
body
} |
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/07-proposed-solution/04-extraction.typ | typst | #import "@preview/acrostiche:0.3.1": *
#import "/helpers.typ": *
== Extraction
Software development is typically done in sequential steps, either using the waterfall model, or using an iterative approach @royce_1970.
Analysis and design are two steps of early software development which often yield software development lifecycle artifacts in the form of use cases, process models, and diagrams.
After the completion of the development and the subsequent deployment, these documents are often not kept up to date, and sometimes even lost.
Hence, it is not always possible to use design documents for the information extraction phase.
A software development artifact that is generally available for legacy applications is the source code repository of the application.
For these reasons, we chose the source code repository as the starting point of the information extraction.
Our solution uses multiple coupling strategies to extract information from the source code repository.
The first strategy is the structural coupling strategy, which is based on the dependencies between software components.
When two software components are dependent on each other, they are structurally coupled.
#cite_full(<mazlami_etal_2017>) proposed a microservice extraction model that includes three possible extraction strategies: _logical coupling_ strategy, _semantic coupling_ strategy, and _contributor coupling_ strategy.
In this thesis, we concentrate on the logical coupling strategy, and the contributor coupling strategy as second and third strategies.
The next sections describe in detail how these strategies are used for extracting information from the source code repository.
=== Structural coupling
Structural coupling is a measure of the dependencies between software components.
The dependencies can take the form of control dependencies, or data dependencies.
Control dependencies are dependencies between software components that are related to the flow of control of the software system (e.g. interleaving method calls).
Data dependencies relate to the flow of data between software components (e.g. passing parameters).
MOSAIK extracts structural coupling information using static analysis of the source code.
As our solution is intended to collect information from monolith applications written in a dynamic programming language, the static analysis is limited to the information that is embedded in the source code.
Dynamic languages such as Python and Ruby typically include only incomplete type information that can be extracted using static analysis.
In particular, some techniques like meta-programming and dynamic class loading may affect the accuracy of the extracted information.
Our solution analyzes the source code of the monolith application using the `parser` library#footnote[#link("https://github.com/whitequark/parser")[https://github.com/whitequark/parser]].
The library is written in Ruby and can be used to parse Ruby source code files and extract the #acr("AST") of the source code.
Iterating over the #acr("AST") of the monolith application, MOSAIK extracts the references between classes.
Using this information, a call graph is constructed that represents the structural coupling of the monolith application. For each class in the monolith application $c_i in M_C$, a vertex is created in the call graph.
References between classes are represented as directed edges between the vertices.
A directed edge is created for each reference between two classes $c_i, c_j in M_C$.
This edge describes one of three types of references: (i) static method calls between two methods $m_i$ and $m_j$ of the classes $c_i, c_j$ _(method-to-method)_, (ii) references from method $m_i$ to an object of class $c_j$ _(method-to-entity)_, and (iii) associations between entities of class $c_i$ and $c_j$ _(entity-to-entity)_ @filippone_etal_2021.
Hence, the structural coupling $N_s$ for each pair of classes $c_i, c_j in M_C$ is defined as the sum of the number of references between the classes, as described in @aggregated_structural_coupling_formula.
$
N_s (c_i, c_j) =
sum_(m_i in c_i, m_j in c_j\ c_i, c_j in M_C)
italic("ref")_italic("mm") (m_i, m_j) +
italic("ref")_italic("mc") (m_i, c_j) +
italic("ref")_italic("cc") (c_i, c_j)
$ <aggregated_structural_coupling_formula>
The $italic("ref")_italic("mm")$, $italic("ref")_italic("mc")$, and $italic("ref")_italic("cc")$ functions return the number of references between the two methods $m_i$ and $m_j$, method $m_i$ and class $m_j$, and classes $c_i$ and $c_j$ respectively.
As #cite_full(<carvalho_etal_2020>) noted, the choice of granularity is an important decision in the extraction of microservices.
Existing approaches tend to use a more coarse-grained granularity (e.g. on the level of files or classes) rather than a fined-grained granularity (e.g. on the level of methods).
Using a coarse-grained granularity can lead to a smaller number of microservices that are responsible for a larger number of functionalities.
A fine-grained granularity can lead to a much larger number of microservices, which can decrease the maintainability of the system.
Hence, a trade-off between the two granularities must be made.
MOSAIK uses a coarse-grained granular approach, using the classes of the monolith application as the starting point for the extraction of microservices.
#figure(
table(
columns: (auto),
inset: 5pt,
stroke: (x: none),
align: (left),
[*@structural_coupling_algorithm*: Structural coupling extraction algorithm],
[
_calls_ $arrow.l$ _array_[][][] \
\
*for each* ( _class_ : _classes_ ) \
#h(1em) *for each* ( _method_ : _class_._methods_ ) \
#h(2em) *for each* ( _reference_ : _method_._references_ ) \
#h(3em) _receiver_ $arrow.l$ _reference_._receiver_ \
#h(3em) _type_ $arrow.l$ _reference_._type_ \
#h(3em) _calls_[_class_][_receiver_][_type_] $arrow.l$ 1 \
\
*return* _calls_;
]
),
kind: "algorithm",
supplement: "Algorithm",
caption: [Structural coupling extraction algorithm],
) <structural_coupling_algorithm>
@structural_coupling_algorithm describes the structural coupling extraction algorithm in pseudocode.
The algorithm first initializes an empty three-dimensional call matrix, which stores the number and type of references between classes in the monolith application.
The algorithm then iterates over all classes in the monolith application, and for each method in the class, it parses the method body.
All references from the method body are extracted, and the receiver and type of reference are stored in the call graph.
=== Logical coupling
The logical coupling strategy is based on the #acr("SRP") @martin_2003, which states that a software component should only have one reason to change.
Software design that follows the #acr("SRP") groups together software components that change together.
Hence, it is possible to identify appropriate microservice candidates by analyzing the history of modifications of the classes in the source code repository.
Classes that change together, should belong in the same microservice.
Let $M_H$ be the history of modifications of the source code files of the monolith application $M$.
Each change event $h_i$ is associated with a set of associated classes $c_i$ that were changed during the modification event at timestamp $t_i$, as described by @logical_history_formula @mazlami_etal_2017.
$ h_i = { c_i, t_i } $ <logical_history_formula>
If $c_1, c_2$ are two classes belonging to the same change event $h_i$, then the logical coupling is computed as follows in @logical_coupling_formula @mazlami_etal_2017.
$ Delta(c_1, c_2) = sum_(h_i in M_H) delta_h_i (c_1, c_2) $ <logical_coupling_formula>
Where $delta$ is the change function in @change_function_formula.
$ delta_h_i (c_1, c_2) = cases(1 "if" c_1\, c_2 "changed in" h_i, 0 "otherwise") $ <change_function_formula>
Then, the logical coupling is calculated for each change event $h_i in M_H$, and each pair of classes $c_1, c_2$ in the change event.
The logical coupling $N_c$ for each pair of classes $c_i, c_j in M_C$ is defined as the sum of the logical coupling for each change event $h_i in M_H$.
$ N_c (c_1, c_2) = Delta(c_1, c_2) $ <aggregated_logical_coupling_formula>
#figure(
table(
columns: (auto),
inset: 5pt,
stroke: (x: none),
align: (left),
[*@logical_coupling_algorithm*: Logical coupling extraction algorithm],
[
_cochanges_ $arrow.l$ _array_[][] \
\
*for each* ( _commit_ : _git.log_ ) \
#h(1em) _parent_ $arrow.l$ _commit_._parent_ \
#h(1em) _parent_diff_ $arrow.l$ _diff_ ( _commit_, _parent_ ) \
\
#h(1em) *for each* ( _file_one_ : _parent_diff_._files_ ) \
#h(2em) *for each* ( _file_two_ : _parent_diff_._files_ ) \
#h(3em) _cochanges_[_file_one_][_file_two_] $arrow.l$ 1 \
\
*return* _cochanges_;
]
),
kind: "algorithm",
supplement: "Algorithm",
caption: [Logical coupling extraction algorithm],
) <logical_coupling_algorithm>
Consider the extraction algorithm in pseudocode in @logical_coupling_algorithm.
First, a co-change matrix is initialized, which stores the number of times two files have changed together in a two-dimensional matrix.
The algorithm then iterates over all commits in the source code repository, and for each commit, retrieves the changes between the commit and its parent.
Then, it iterates over each pair of files in the changelist, and increments the co-change matrix for the pair of files.
=== Contributor coupling
Conway's law states that the structure of a software system is a reflection of the communication structure of the organization that built it @conway_1968.
The contributor coupling strategy is based on the notion that the communication structure can be recovered from analyzing the source code repository @mazlami_etal_2017.
Grouping together software components that are developed in teams that have a strong communication paradigm internally can lead to less communication overhead when developing and maintaining the software system.
Hence, identifying microservice candidates based on the communication structure of the organization can lead to more maintainable software systems.
Let $M_H$ be the history of modifications of the source code files of the monolith application $M$.
Each change event $h_i$ is associated with a set of associated classes $c_i$ that were changed during the modification event at timestamp $t_i$.
The change event $h_i$ is also associated with a set of developers $d_i in M_D$, as stated in @contributor_history_formula @mazlami_etal_2017.
$M_D$ is the set of developers that have contributed to the source code repository of the monolith application.
$ h_i = { c_i, t_i, d_i } $ <contributor_history_formula>
$H(c_i)$ is a function that returns the set of change events that have affected the class $c_i$, and $D(c_i)$ returns the set of developers that have worked on the class $c_i$.
$ H(c_i) = { h_i in M_H | c_i in h_i } $ <contributions_formula>
$ D(c_i) = { d_i in M_D | forall h_i in H(c_i) : d_i in h_i } $ <contributors_formula>
Then, @contributors_formula is calculated for each class $c_i in M_C$ in the monolith application.
Finally, the contributor coupling $N_d$ for each pair of classes $c_i, c_j in M_C$ is defined as the cardinality of the intersection of the sets of developers that have contributed to the classes $c_i, c_j$ @mazlami_etal_2017.
$ N_d (c_1, c_2) = |D(c_i) sect D(c_j)| $ <aggregated_contributor_coupling_formula>
#pagebreak()
Consider the extraction algorithm in pseudocode in @contributor_coupling_algorithm.
The algorithm first initializes the co-authorship matrix, which is a two-dimensional array that stores the (unique) authors of each file in the source code repository.
Then, it iterates over all commits in the source code repository, and for each commit, retrieves the changes between the commit and its parent.
Finally, iterating over each file in the changelist, the algorithm adds the author(s) of the commit to the entry corresponding to the file in the co-authorship matrix.
#figure(
table(
columns: (auto),
inset: 5pt,
stroke: (x: none),
align: (left),
[*@contributor_coupling_algorithm*: Contributor coupling extraction algorithm],
[
_coauthors_ $arrow.l$ _array_[][] \
\
*for each* ( _commit_ : _git_._log_ ) \
#h(1em) _parent_ $arrow.l$ _commit_._parent_ \
#h(1em) _parent_diff_ $arrow.l$ _diff_ ( _commit_, _parent_ ) \
\
#h(1em) *for each* ( _file_ : _parent_diff_._files_ ) \
#h(2em) _coauthors_[_file_] $arrow.l$ _commit_._authors_ \
\
*return* _coauthors_;
]
),
kind: "algorithm",
supplement: "Algorithm",
caption: [Contributor coupling extraction algorithm],
) <contributor_coupling_algorithm>
=== Dependency graph
As a final step in the information extraction phase, an edge-weighted undirected graph $G = (V, E)$ is constructed, where $V$ is the set of classes in the monolith application, and $E$ is the set of edges between classes that have an interdependency based on the discussed coupling strategies.
The weight for the edge $e_i in E$ between classes $c_j, c_k in V$ is calculated as the weighted sum of the call graph $N_s$ representing the structural coupling, the co-change matrix $N_c$ representing the logical coupling, and the co-authorship matrix $N_d$ representing the contributor coupling.
The weights $omega_s, omega_c, omega_d in [0, 1]$ are used to balance the contribution of the structural, logical, and contributor coupling respectively, as described in @weighted_edge_formula.
This makes the strategy adaptive and flexible @santos_paula_2021.
$ w(e_i) = w(c_j, c_k) = omega_s N_s (c_j, c_k) + omega_c N_c (c_j, c_k) + omega_d N_d (c_j, c_k) $ <weighted_edge_formula>
An illustration of the graph $G$ is presented in @dependency_graph.
#figure(
include("/figures/07-proposed-solution/dependency-graph.typ"),
caption: [Dependency graph]
) <dependency_graph>
|
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/examples/fault-tolerant-toffoli1.typ | typst | MIT License | #import "../src/quill.typ": *
#quantum-circuit(
fill-wires: false,
lstick($|0〉$), $H$, ctrl(3), 5, $X$, ctrl(2), rstick($|x〉$), [\ ],
lstick($|0〉$), $H$, 1, ctrl(3), 3, $X$, 1, ctrl(0), rstick($|y〉$), [\ ],
lstick($|0〉$), 3, targ(), 1, $Z$, 2, targ(), rstick($|z plus.circle x y〉$), [\ ],
lstick($|x〉$), 1, targ(), 5, meter(target: -3), [\ ],
lstick($|y〉$), 2, targ(), 3, meter(target: -3), [\ ],
lstick($|z〉$), 3, ctrl(-3), $H$, meter(target: -3)
) |
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/089.%20heroes.html.typ | typst | heroes.html
Some Heroes
April 2008There are some topics I save up because they'll be so much fun to
write about. This is one of them: a list of my heroes.I'm not claiming this is a list of the n most admirable people.
Who could make such a list, even if they wanted to?Einstein isn't on the list, for example, even though he probably
deserves to be on any shortlist of admirable people. I once asked
a physicist friend if Einstein was really as smart as his fame
implies, and she said that yes, he was. So why isn't he on the
list? Because I had to ask. This is a list of people who've
influenced me, not people who would have if I understood their work.My test was to think of someone and ask "is this person my
hero?" It often returned surprising answers. For example,
it returned false for Montaigne, who was arguably the inventor of
the essay. Why? When I thought
about what it meant to call someone a hero, it meant I'd decide what
to do by asking what they'd do in the same situation. That's a
stricter standard than admiration.After I made the list, I looked to see if there was a pattern, and
there was, a very clear one. Everyone on the list had two qualities:
they cared almost excessively about their work, and they were
absolutely honest. By honest I don't mean trustworthy so much as
that they never pander: they never say or do something because
that's what the audience wants. They are all fundamentally subversive
for this reason, though they conceal it to varying degrees.
<NAME>I grew up in Pittsburgh in the 1970s. Unless you were there it's
hard to imagine how that town felt about the Steelers. Locally,
all the news was bad. The steel industry was dying. But the
Steelers were the best team in football — and moreover, in a
way that seemed to reflect the personality of the city. They didn't
do anything fancy. They just got the job done.Other players were more famous: <NAME>, <NAME>, <NAME>. But they played offense, and you always get more attention
for that. It seemed to me as a twelve year old football expert
that the best of them all was
<NAME>. And what made him so
good was that he was utterly relentless. He didn't just care about
playing well; he cared almost too much. He seemed to regard it as
a personal insult when someone from the other team had possession
of the ball on his side of the line of scrimmage.The suburbs of Pittsburgh in the 1970s were a pretty dull place.
School was boring. All the adults around were bored with their
jobs working for big companies. Everything that came to us through
the mass media was (a) blandly uniform and (b) produced elsewhere.
<NAME> was the exception. He was like nothing else I'd seen.
<NAME> <NAME> is the best nonfiction writer I know of, on any
subject. Most people who write about art history don't really like
art; you can tell from a thousand little signs. But Clark did, and
not just intellectually, but the way one anticipates a delicious
dinner.What really makes him stand out, though, is the quality of his
ideas. His style is deceptively casual, but there is more in
his books than in a library
of art monographs. Reading
The Nude is like a ride in a
Ferrari. Just as you're getting settled, you're slammed back in
your seat by the acceleration. Before you can adjust, you're thrown
sideways as the car screeches into the first turn. His brain throws
off ideas almost too fast to grasp them. Finally at the end of the
chapter you come to a halt, with your eyes wide and a big smile on
your face.<NAME> was a star in his day, thanks to the documentary
series
Civilisation. And if you read only one book about
art history,
Civilisation is the one I'd recommend. It's
much better than the drab Sears Catalogs of art that undergraduates
are forced to buy for Art History 101.
<NAME>oA lot of people have a great teacher at some point in their childhood.
<NAME> was mine. When I look back it's like there's a line
drawn between third and fourth grade. After Mr. Mihalko, everything
was different.Why? First of all, he was intellectually curious. I had a few
other teachers who were smart, but I wouldn't describe them as
intellectually curious. In retrospect, he was out of place as an
elementary school teacher, and I think he knew it. That must have
been hard for him, but it was wonderful for us, his students. His
class was a constant adventure. I used to like going to school
every day.The other thing that made him different was that he liked us. Kids
are good at telling that. The other teachers were at best benevolently
indifferent. But Mr. Mihalko seemed like he actually wanted to
be our friend. On the last day of fourth grade, he got out one of
the heavy school record players and played <NAME>'s "You've
Got a Friend" to us. Just call out my name, and you know wherever
I am, I'll come running. He died at 59 of lung cancer. I've never
cried like I cried at his funeral.
LeonardoOne of the things I've learned about making things that I didn't
realize when I was a kid is that much of the best stuff isn't made
for audiences, but for oneself. You see paintings and drawings in
museums and imagine they were made for you to look at. Actually a
lot of the best ones were made as a way of exploring the world, not
as a way to please other people. The best of these explorations
are sometimes more pleasing than stuff made explicitly to please.Leonardo did a lot of things. One of his most admirable qualities
was that he did so many different things that were admirable. What
people know of him now is his paintings and his more flamboyant
inventions, like flying machines. That makes him seem like some
kind of dreamer who sketched artists' conceptions of rocket ships
on the side. In fact he made a large number of far more practical
technical discoveries. He was as good an engineer as a painter.His most impressive work, to me, is his
drawings. They're clearly
made more as a way of studying the world than producing something
beautiful. And yet they can hold their own with any work of art
ever made. No one else, before or since, was that good when no one
was looking.
<NAME> <NAME> has a very unusual quality: he's never wrong. It
might seem this would require you to be omniscient, but actually
it's surprisingly easy. Don't say anything unless you're fairly
sure of it. If you're not omniscient, you just don't end up saying
much.More precisely, the trick is to pay careful attention to how you
qualify what you say. By using this trick, Robert has, as far as
I know, managed to be mistaken only once, and that was when he was
an undergrad. When the Mac came out, he said that little desktop
computers would never be suitable for real hacking.It's wrong to call it a trick in his case, though. If it were a
conscious trick, he would have slipped in a moment of excitement.
With Robert this quality is wired-in. He has an almost superhuman
integrity. He's not just generally correct, but also correct about
how correct he is.You'd think it would be such a great thing never to be wrong that
everyone would do this. It doesn't seem like that much extra work
to pay as much attention to the error on an idea as to the idea
itself. And yet practically no one does. I know how hard it is,
because since meeting Robert I've tried to do in software what he
seems to do in hardware.
<NAME>People are finally starting to admit that Wodehouse was a great
writer. If you want to be thought a great novelist in your own
time, you have to sound intellectual. If what you write is popular,
or entertaining, or funny, you're ipso facto suspect. That makes
Wodehouse doubly impressive, because it meant that to write as he
wanted to, he had to commit to being despised in his own lifetime.<NAME> called him a great writer, but to most people at the
time that would have read as a chivalrous or deliberately perverse
gesture. At the time any random autobiographical novel by a recent
college grad could count on more respectful treatment from the
literary establishment.Wodehouse may have begun with simple atoms, but the way he composed
them into molecules was near faultless. His rhythm in particular.
It makes me self-conscious to write about it. I can think of only
two other writers who came near him for style: <NAME> and
<NAME>. Those three used the English language like they
owned it.But Wodehouse has something neither of them did. He's at ease.
<NAME> and <NAME> cared what other people thought of
them: he wanted to seem aristocratic; she was afraid she wasn't
smart enough. But Wodehouse didn't give a damn what anyone thought
of him. He wrote exactly what he wanted.
Alexander CalderCalder's on this list because he makes me happy. Can his work stand
up to Leonardo's? Probably not. There might not be anything from
the 20th Century that can. But what was good about Modernism,
Calder had, and had in a way that he made seem effortless.What was good about Modernism was its freshness. Art became stuffy
in the nineteenth century. The paintings that were popular at the
time were mostly the art equivalent of McMansions—big,
pretentious, and fake. Modernism meant starting over, making things
with the same earnest motives that children might. The artists who
benefited most from this were the ones who had preserved a child's
confidence, like Klee and Calder.Klee was impressive because he could work in so many different
styles. But between the two I like Calder better, because his work
seemed happier. Ultimately the point of art is to engage the viewer.
It's hard to predict what will; often something that seems interesting
at first will bore you after a month. Calder's
sculptures never
get boring. They just sit there quietly radiating optimism, like
a battery that never runs out. As far as I can tell from books and
photographs, the happiness of Calder's work is his own happiness
showing through.
<NAME>Everyone admires <NAME>. Add my name to the list. To me she
seems the best novelist of all time.I'm interested in how things work. When I read most novels, I pay
as much attention to the author's choices as to the story. But in
her novels I can't see the gears at work. Though I'd really like
to know how she does what she does, I can't figure it out, because
she's so good that her stories don't seem made up. I feel like I'm
reading a description of something that actually happened.I used to read a lot of novels when I was younger. I can't read
most anymore, because they don't have enough information in them.
Novels seem so impoverished compared to history and biography. But
reading Austen is like reading
nonfiction. She writes so well you don't even notice her.
<NAME> <NAME> invented Lisp, the field of (or at least the term)
artificial intelligence, and was an early member of both of the top
two computer science departments, MIT and Stanford. No one would
dispute that he's one of the greats, but he's an especial hero to
me because of
Lisp.It's hard for us now to understand what a conceptual leap that was
at the time. Paradoxically, one of the reasons his achievement is
hard to appreciate is that it was so successful. Practically every
programming language invented in the last 20 years includes ideas
from Lisp, and each year the median language gets more Lisplike.In 1958 these ideas were anything but obvious. In 1958 there seem
to have been two ways of thinking about programming. Some people
thought of it as math, and proved things about Turing Machines.
Others thought of it as a way to get things done, and designed
languages all too influenced by the technology of the day. McCarthy
alone bridged the gap. He designed a language that was math. But
designed is not really the word; discovered is more like it.
The SpitfireAs I was making this list I found myself thinking of people like
<NAME>
and
<NAME>
and
<NAME> and I realized
that though all of them had done many things in their lives, there
was one factor above all that connected them: the Spitfire.This is supposed to be a list of heroes. How can a machine be on
it? Because that machine was not just a machine. It was a lens
of heroes. Extraordinary devotion went into it, and extraordinary
courage came out.It's a cliche to call World War II a contest between good and evil,
but between fighter designs, it really was. The Spitfire's original
nemesis, the ME 109, was a brutally practical plane. It was a
killing machine. The Spitfire was optimism embodied. And not just
in its beautiful lines: it was at the edge of what could be
manufactured. But taking the high road worked. In the air, beauty
had the edge, just.
<NAME>People alive when Kennedy was killed usually remember exactly where
they were when they heard about it. I remember exactly where I was
when a friend asked if I'd heard <NAME> had cancer. It was
like the floor dropped out. A few seconds later she told me that
it was a rare operable type, and that he'd be ok. But those seconds
seemed long.I wasn't sure whether to include Jobs on this list. A lot of people
at Apple seem to be afraid of him, which is a bad sign. But he
compels admiration.There's no name for what <NAME> is, because there hasn't been
anyone quite like him before. He doesn't design Apple's products
himself. Historically the closest analogy to what he does are the
great Renaissance patrons of the arts. As the CEO of a company,
that makes him unique.Most CEOs delegate
taste to a subordinate.
The
design paradox
means they're choosing more or less at random. But <NAME> actually has taste himself — such good taste that he's shown
the world how much more important taste is than they realized.
<NAME> has a strange role in my pantheon of heroes: he's the one I
reproach myself with. He worked on big things, at least for part
of his life. It's so easy to get distracted working on small stuff.
The questions you're answering are pleasantly familiar. You get
immediate rewards — in fact, you get bigger rewards in your
time if you work on matters of passing importance. But I'm
uncomfortably aware that this is the route to well-deserved obscurity.To do really great things, you have to seek out questions people
didn't even realize were questions. There have probably been other
people who did this as well as Newton, for their time, but Newton
is my model of this kind of thought. I can just begin to understand
what it must have felt like for him.You only get one life. Why not do something huge? The phrase "paradigm
shift" is overused now, but Kuhn was onto something. And you know
more are out there, separated from us by what will later seem a
surprisingly thin wall of laziness and stupidity. If we work like
Newton.Thanks to <NAME>, <NAME>, and <NAME>Donough for reading drafts of this.Japanese Translation
|
|
https://github.com/jamesrswift/dining-table | https://raw.githubusercontent.com/jamesrswift/dining-table/main/src/note.typ | typst | The Unlicense | #let std-state = state
#let std-numbering = numbering
/// Stateful array that tracks table notes that are yet to be displayed
/// -> state
#let state = std-state("_dining-table:notes", ())
/// Stateful string that represents the numbering format to be used when rendering table notes. It is assumed that this does not change when there are as-of-yet undisplayed notes that are pending. Defaults of lowercase alphabetical numbering.
/// -> state
#let numbering = std-state("_dining-table:notes:numbering", "a")
/// Explcitly empties the stateful array tracking pending notes. Called prior to showing the table to ensure that previous notes that were forgotten about aren't accidentally absorbed into this table.
#let clear() = state.update(())
/// Helper function to update the numbering style of table notes.
/// -> content
#let set-numbering(new) = numbering.update(new)
/// Helper functions to render the numbering of a note (either in the table body, or underneath)
/// -> content
#let make-numbering() = context std-numbering(numbering.get(), state.get().len() + 1)
/// This function replicates the behviour of `#footnote`: It is called within the table body, and stores the content until the table notes are being rendered. It is not possible to make a hyperlink between the table body's number and the associated note.
/// - body (content): Content to be rended under the table.
#let make(body) = {
h(0em, weak: true) + sym.space.narrow + super(make-numbering())
state.update(it=>{it.push(body);it})
}
/// Helper function to display the numbering for a specific table note
/// - key (int): 0-indexed position of note inside stateful array
/// -> content
#let display-numbering(key) = super(context std-numbering(numbering.get(), key + 1))
/// Renders pending table notes in a grid-like manner (auto, 1fr), after which it empties the list of pending footnotes
/// -> content
#let display = context {
grid(
columns: (auto, 1fr),
inset: 0.15em,
..(for (key, value) in state.get().enumerate() {
(display-numbering(key), value)
})
)
} + clear()
/// Renders pending table notes in a list-like manner. Each note is boxed.
/// -> content
#let display-list = context {
state.get()
.enumerate()
.map( ((key, value)) => box[#display-numbering(key) #value])
.join(", ", last: ", and ")
}
#let display-style(notes) = {
v(-0.5em)
set text(0.888em)
set block(spacing: 0.5em)
set par(leading: 0.5em)
align(start, notes)
} |
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/intermediate/figure-time-travel.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.2.0"
#import "/typ/templates/page.typ": main-color, is-light-theme
#let std-scale = scale
#let figure-time-travel(
stroke-color: main-color,
light-theme: is-light-theme
) = {
import cetz.draw: *
let stroke-factor = if light-theme {
1
} else {
0.8
}
let line-width = 0.5pt * stroke-factor
let rect = rect.with(stroke: line-width + stroke-color)
let circle = circle.with(stroke: line-width + stroke-color)
let line = line.with(stroke: line-width + stroke-color)
let light-line = line.with(stroke: (0.3pt*stroke-factor) + stroke-color)
let exlight-line = line.with(stroke: (0.2pt*stroke-factor) + stroke-color)
let preview-img-fill = if light-theme {
green.lighten(80%)
} else {
green.darken(20%)
}
let preview-img-fill2 = if light-theme {
green.lighten(80%)
} else {
green.darken(20%)
}
let state-background-fill = rgb("#2983bb80")
let preview-background-fill = rgb("#baccd980")
let preview-content0 = {
translate((0.05, 1-0.2))
// title
light-line((0.15, 0), (0.55, 0))
translate((0, -0.08))
exlight-line((0.05, 0), (0.7, 0))
translate((0, -0.03))
exlight-line((0.00, 0), (0.7, 0))
translate((0, -0.03))
exlight-line((0.00, 0), (0.7, 0))
translate((0, -0.03))
exlight-line((0.00, 0), (0.4, 0))
}
let preview-content1 = {
translate((0, -0.06))
rect((0.05, 0), (0.65, -0.24), stroke: 0pt, fill: preview-img-fill, name: "picture")
content("picture", std-scale(20%)[$lambda x = integral.double x dif x$])
translate((0, -0.24))
}
let doc-state(prev-name, name, checkpoint: 0) = {
let arrow-line(pos) = {
line((rel: (-0.01, 0.025), to: pos), pos)
line((rel: (0.01, 0.025), to: pos), pos)
}
rect((0, 0), (0.2, 1), stroke: 0pt, fill: state-background-fill)
if checkpoint == 0 {
line(prev-name+"-S2", name+"-S1", stroke: line-width + red)
}
if checkpoint == 1 {
line(prev-name+"-S3", name+"-S2", stroke: line-width + red)
}
if checkpoint == 2 {
line(prev-name+"-S4", name+"-S3", stroke: line-width + red)
}
circle(name+"-S1", fill: blue, stroke: 0pt, radius: 0.01)
content((rel: (-0.04, 0), to: name+"-S1"), std-scale(40%, [S1]))
if checkpoint <= 0 {
return
}
circle(name+"-S2", fill: blue, stroke: 0pt, radius: 0.01)
content((rel: (-0.04, -0.03), to: name+"-S2"), std-scale(40%, [S2]))
line(name+"-S1", name+"-S2")
arrow-line(name+"-S2")
if checkpoint <= 1 {
return
}
circle(name+"-S3", fill: blue, stroke: 0pt, radius: 0.01)
content((rel: (-0.04, -0.02), to: name+"-S3"), std-scale(40%, [S3]))
line(name+"-S2", name+"-S3")
arrow-line(name+"-S3")
if checkpoint == 2 {
circle(name+"-R1", fill: blue, stroke: 0pt, radius: 0.01)
arc-through(name+"-R1", (rel:(0.02, -0.03), to: name+"-R1"), name+"-S3", stroke: line-width + blue)
line((rel: (50deg, 0.02), to: name+"-S3"), name+"-S3", stroke: line-width + blue)
line((rel: (10deg, 0.02), to: name+"-S3"), name+"-S3", stroke: line-width + blue)
}
if checkpoint <= 2 {
return
}
circle(name+"-S4", fill: blue, stroke: 0pt, radius: 0.01)
content((rel: (-0.04, -0.01), to: name+"-S4"), std-scale(40%, [S4]))
line(name+"-S3", name+"-S4")
if checkpoint == 3 {
circle(name+"-R2", fill: blue, stroke: 0pt, radius: 0.01)
}
arrow-line(name+"-S4")
if checkpoint == 3 {
arc-through(name+"-R2", (rel:(0.05, 0.33, 0), to: name+"-R2"), name+"-S2", stroke: line-width + blue)
line((rel: (-110deg, 0.02), to: name+"-S2"), name+"-S2", stroke: line-width + blue)
line((rel: (-20deg, 0.02), to: name+"-S2"), name+"-S2", stroke: line-width + blue)
}
}
let doc(name, checkpoint: 0) = {
group(name: name, {
// line((0, 0), (0.707, 0))
// line((0.707, 0), (0.707, 1))
// line((0.707, 1), (0, 1))
// line((0, 0), (0, 1))
rect((0, 0), (0.707, 1), stroke: 0pt, fill: preview-background-fill)
let margin = 0.05
translate((margin, 1-0.1))
scale(x: (0.707 - margin * 2))
let lm = (-margin) / (0.707 - margin * 2);
anchor("title", (0.5, 0))
content("title", std-scale(30%)[关于吃睡玩自动机的形式化研究])
// content("title", std-scale(30%)[#align(center, [A formal study on eat-sleep-\ play automating cats])])
translate((0, -0.07))
light-line((0.1, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
if checkpoint <= 0 {
light-line((0.05, 0), (0.45, 0))
anchor("P", (0.45, 0))
anchor("Q", (lm, 0))
return
}
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.75, 0))
translate((0, -0.03))
anchor("P", (0.59, -0.072))
anchor("Q", (lm, -0.072))
rect((0.1, 0), (0.9, -0.10), stroke: 0pt, fill: preview-img-fill, name: "picture")
content("picture", std-scale(30%)[$lambda x = integral.double x dif x$])
if checkpoint <= 1 {
return
}
translate((0, -0.03-0.10))
light-line((0.1, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.85, 0))
translate((0, -0.03))
light-line((0.1, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
if checkpoint == 2 {
anchor("R", (0.75, 0))
anchor("R2", (lm, 0))
}
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
anchor("P", (0.85, 0))
anchor("Q", (lm, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.35, 0))
if checkpoint <= 2 {
return
}
translate((0, -0.03))
light-line((0.1, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.35, 0))
translate((0, -0.03))
light-line((0.1, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
if checkpoint == 3 {
anchor("R", (0.75, 0))
anchor("R2", (lm, 0))
}
translate((0, -0.025))
light-line((0.05, 0), (0.95, 0))
anchor("P", (0.6, 0))
anchor("Q", (lm, 0))
translate((0, -0.025))
light-line((0.05, 0), (0.35, 0))
})
}
cetz.canvas({
// 导入cetz的draw方言
import cetz.draw: *
set-viewport((0, 0, 0), (4, 4, -4), bounds: (1, 1, 1))
group(name: "doc", {
let x = 0.25
let z = 0.22
translate((x, 0, -z))
translate((x, 0, -z))
translate((x, 0, -z))
doc("D1", checkpoint: 3)
circle("D1.P", fill: red, stroke: 0pt, radius: 0.01)
translate((-x, 0, z))
doc("D2", checkpoint: 2)
circle("D2.P", fill: red, stroke: 0pt, radius: 0.01)
translate((-x, 0, z))
doc("D3", checkpoint: 1)
circle("D3.P", fill: red, stroke: 0pt, radius: 0.01)
translate((-x, 0, z))
doc("D4", checkpoint: 0)
circle("D4.P", fill: red, stroke: 0pt, radius: 0.01)
circle("D2.R", fill: blue, stroke: 0pt, radius: 0.01)
circle("D1.R", fill: blue, stroke: 0pt, radius: 0.01)
let blue-light-line = line.with(stroke: (0.3pt*stroke-factor) + blue)
let red-light-line = line.with(stroke: (0.3pt*stroke-factor) + red)
red-light-line("D4.P", "D3.P")
red-light-line("D3.P", "D2.P")
red-light-line("D2.P", "D1.P")
blue-light-line("D2.R", "D2.P")
blue-light-line("D1.R", "D3.P")
let round-z-axis = ((x, y, z)) => (x, y, calc.round(z, digits: 10))
anchor("S1", (round-z-axis, (rel: (-x*0, 0, z*0), to: "D4.Q")))
anchor("S2", (round-z-axis, (rel: (-x*1, 0, z*1), to: "D3.Q")))
anchor("S3", (round-z-axis, (rel: (-x*2, 0, z*2), to: "D2.Q")))
anchor("S4", (round-z-axis, (rel: (-x*3, 0, z*3), to: "D1.Q")))
anchor("R1", (round-z-axis, (rel: (-x*2, 0, z*2), to: "D2.R2")))
anchor("R2", (round-z-axis, (rel: (-x*3, 0, z*3), to: "D1.R2")))
})
let anchor-s(prefix, p) = {
anchor(prefix + "-S1", (rel: p, to: "doc.S1"))
anchor(prefix + "-S2", (rel: p, to: "doc.S2"))
anchor(prefix + "-S3", (rel: p, to: "doc.S3"))
anchor(prefix + "-S4", (rel: p, to: "doc.S4"))
anchor(prefix + "-R1", (rel: p, to: "doc.R1"))
anchor(prefix + "-R2", (rel: p, to: "doc.R2"))
}
translate((-1, 0, 0))
group({
let x = 0.12
let z = 0.22
translate((x, 0, -z))
translate((x, 0, -z))
translate((x, 0, -z))
anchor-s("T1", (-1 + 0.2 / 2 + x * 3, 0, - z * 3))
doc-state("T0", "T1", checkpoint: 3)
translate((-x, 0, z))
anchor-s("T2", (-1 + 0.2 / 2 + x * 2, 0, - z * 2))
doc-state("T1", "T2", checkpoint: 2)
translate((-x, 0, z))
anchor-s("T3", (-1 + 0.2 / 2 + x * 1, 0, - z * 1))
doc-state("T2", "T3", checkpoint: 1)
translate((-x, 0, z))
anchor-s("T4", (-1 + 0.2 / 2 + x * 0, 0, - z * 0))
doc-state("T3", "T4", checkpoint: 0)
})
translate((-0.7, 0, 0))
line((0, 0), (0, 1), stroke: 0pt, fill: none)
})
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/modern-sysu-thesis/0.1.0/pages/bachelor-decl-page.typ | typst | Apache License 2.0 | #import "../utils/indent.typ": indent
#import "../utils/style.typ": 字号, 字体
// 本科生声明页
#let bachelor-decl-page(
anonymous: false,
twoside: false,
fonts: (:),
info: (:),
) = {
pagebreak(weak: true, to: if twoside { "odd" })
align(center, text(font: 字体.黑体, size: 字号.三号)[学术诚信声明])
set text(font: 字体.宋体, size: 字号.小四)
par(justify: true, first-line-indent: 2em)[
本人郑重声明:所呈交的毕业论文(设计),是本人在导师的指导下,独立进行研究工作所取得的成果。除文中已经注明引用的内容外,本论文(设计)不包含任何其他个人或集体已经发表或撰写过的作品成果。对本论文(设计)的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。本论文(设计)的知识产权归属于培养单位。本人完全意识到本声明的法律结果由本人承担。
]
v(2em)
align(right + top,
box(
grid(
columns: (auto, auto),
gutter: 2em,
"作者签名:", "",
"日" + h(2em) + "期:", h(2.5em) + text("年") + h(2em) + text("月") + h(2em) + text("日")
)
)
)
}
|
https://github.com/DannySeidel/typst-dhbw-template | https://raw.githubusercontent.com/DannySeidel/typst-dhbw-template/main/shared-lib.typ | typst | MIT License | #let is-in-dict(dict-type, state, element) = {
state.display(list => {
if element not in list {
panic(element + " is not a key in the " + dict-type + " dictionary.")
return false
}
})
return true
}
#let display-link(dict-type, state, element, text) = {
if is-in-dict(dict-type, state, element) {
link(label(dict-type + "-" + element), text)
}
}
#let display(dict-type, state, element, text, link: true) = {
if link {
display-link(dict-type, state, element, text)
} else {
text
}
}
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/demos/ribbon-ratio.typ | typst | #import "@local/typkit:0.1.0": *
#import "@local/mathematical:0.1.0": *
#let ribbon-ratio(size: Integer, ratios: RatioObjectArray) = {
let values = ratios.map((x) => x.value)
let d = values.sum()
let callback(rob) = {
return colored(fraction(rob.value, d), rob.fill)
}
let callback-2(rob) = {
let f = math.bold(callback(rob))
let answer = math.bold(str(int(size * rob.value / d)))
let v = math.equation(f + $times #size = #answer$)
centered(stack(30pt, f, v, spacing: 15pt))
}
// colored fractions based on ratio values
// let fractions = ratios.map(callback)
draw.canvas({
draw.brace((0, 1), (d, 1), size, side: "inside")
let step = 0
for ratio in ratios {
let start = step
let fill = resolve-fill(ratio.fill)
for i in range(ratio.value) {
draw.shapes.square((step, 0), fill: fill)
step += 1
}
draw.brace((start, 0), (step, 0), fill: fill, side: "outside", callback-2(ratio))
}
})
}
#ribbon-ratio(
ratios: (
(fill: "blue", value: 4),
(fill: "purple", value: 5),
),
size: 63,
)
|
|
https://github.com/freundTech/kit-slides-typst | https://raw.githubusercontent.com/freundTech/kit-slides-typst/main/CHANGELOG.md | markdown | Other | Changelog
=========
This file lists new additions and breaking changes. Consult it when updating your presentations to a newer version of the template.
## 0.3.2
* Added GitLab CI configuration
* Added Changelog
## 0.3.1
* Fixed outdated information in README
## 0.3.0
* The `group-logo` argument of `kit-theme` now takes `content` instead of a file path. If you previously passed a path to an image file just wrap it in `image()`.
* The `banner` argument of `title-slide` now takes `content` instead of a file path. If you previously passed a path to an image file just wrap it in `image()`.
* Added pixi configuration for easier compiling and linting
* Removed podman-compose configuration. Consider using pixi instead.
* Internal rework. Update typst version to 0.11.1
|
https://github.com/Gchism94/PrettyTypst | https://raw.githubusercontent.com/Gchism94/PrettyTypst/main/NEWS.md | markdown | Creative Commons Zero v1.0 Universal | # PrettyTypst 0.0.1 _2024-07-02_
- Create initial extension
- Add `pdf` format
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/typesetting.typ | typst | #import "@local/typkit:0.1.0": *
#let equals = marks.math.equals
#let wde(x) = {
let mc = mathup(x)
[*What does #mc equal?*]
}
#let find-x(x, target: "x") = {
let mc = mathup(x)
[*Find $#target$:* #h(7pt) #mc]
}
#let x-equals(x, answer) = {
let mc = mathup(x)
let opts = (fill: blue.lighten(80%), baseline: 25%, stroke: none)
let p = pill([*$x$ equals #answer.*], ..opts)
[#mc. #h(5pt) #p]
}
#let answer-x(x, target: "x") = {
let mc = mathup(x)
[The answer is #h(3pt) #boxy([*#target #equals #mc*])]
}
#let labeled(label, c) = {
boxy([*#label #equals #mathup(c)*])
}
// #table(inset: 10pt,
// find-x("a^1 * a^2 * a^3 = a^(x/2)"),
// x-equals($1 + 2 + 3 = display(x/2)$, 12),
// answer-x("a^(3x)", target: "b"),
// wde("a + b"),
// boxy("x^2 times 5"),
// )
// #boxy([#boxy(123) is cool])
#let bubbles(a, b) = {
let s = [
Choice #upper(a): #b
]
boxy(s, inset: 10pt)
}
|
|
https://github.com/swaits/typst-collection | https://raw.githubusercontent.com/swaits/typst-collection/main/pro-letter/0.1.0/lib.typ | typst | MIT License | #let pro-letter(
// sender information - all fields are optional, only use what you need
sender: (
name: none,
company: none,
street: none,
city: none,
state: none,
zip: none,
phone: none,
email: none,
),
// recipient information - all fields are optional, only use what you need
recipient: (
name: none,
company: none,
attention: none,
street: none,
city: none,
state: none,
zip: none,
phone: none,
email: none,
),
// date of letter (optional)
date: none,
// subject line of letter (optional)
subject: none,
// salutation line (optional)
salutation: "To whom it may concern,",
// closing line (required)
closing: "Sincerely,",
// signer line (required)
signer: none,
// attachments line at bottom of letter (optional)
attachments: none,
// set to true if you want a notary public acknowledgement page
notary-page: false,
// text settings
font: "Linux Libertine",
size: 11pt,
weight: "light",
strong-delta: 300,
lang: "en",
// page settings
paper: "us-letter",
margin: 1in,
// and finally the content
body) = {
// --------------------------------
// | Setup layout, style, options |
// --------------------------------
set page(
paper: paper,
margin: margin,
footer: align(right, context(counter(page).display("1 of 1", both: true))),
)
set par(
justify: true,
)
set text(
font: font,
size: size,
weight: weight,
fallback: false,
alternates: false,
lang: lang,
)
set strong(
delta: strong-delta,
)
// --------------------
// | Helper functions |
// --------------------
// Helper for our space between elements
let vspace = { v(0.5em) }
// Helper for baseline underlines
let blul(length) = box(line(length: length, stroke: 0.5pt))
// Helper to make sure address has all the fields we'll reference
let normlize-address(address) = {
(
name: address.at("name", default: none),
company: address.at("company", default: none),
attention: address.at("attention", default: none),
street: address.at("street", default: none),
city: address.at("city", default: none),
state: address.at("state", default: none),
zip: address.at("zip", default: none),
phone: address.at("phone", default: none),
email: address.at("email", default: none),
)
}
// A function to render an address block.
let show-address(address: (:)) = {
// Extract parameters with default none values to handle missing elements.
let a = normlize-address(address)
// Render the address, line by line, only including non-none elements.
if a.name != none { a.name + "\n" }
if a.company != none { a.company + "\n" }
if a.attention != none { "a.attention: " + a.attention + "\n" }
if a.street != none { a.street + "\n" }
if a.city != none and a.state != none and a.zip != none {
a.city + ", " + a.state + " " + a.zip + "\n"
} else if a.city != none and a.state != none {
a.city + ", " + a.state + "\n"
} else if a.city != none and a.zip != none {
a.city + " " + a.zip + "\n"
} else if a.city != none {
a.city + "\n"
} else if a.state != none {
a.state + "\n"
} else if a.zip != none {
a.zip + "\n"
}
if a.phone != none or a.email !=none { v(-0.4em)}
if a.phone != none { "phone: " + link("tel:"+a.phone, a.phone) + "\n" }
if a.email != none { "email: " + link("mailto:" + a.email, a.email) + "\n" }
vspace
}
// -----------------
// | Letter output |
// -----------------
// Top matter
show-address(address: sender)
if date != none { [#date #vspace] }
show-address(address: recipient)
if subject != none { [Subject: *#subject* #vspace] }
// Main body
if salutation != none { [#salutation #vspace] }
[#body #vspace]
[#closing #v(0.6in) #blul(3in) \ #signer]
// Bottom matter
if attachments != none { [#v(1fr) Attached: #attachments] }
// --------------------------
// | Notary acknowledgement |
// --------------------------
if notary-page {
par(
leading: 2.5em,
[
#set text(hyphenate: false)
#pagebreak(weak: true)
#align(center, underline(strong(text(size: 1.5em, [Acknowledgement])))) \
State of #blul(1.1in) ) \
#h(1.15in) § \
County of #blul(1.1in) ) \ \
On #box[this #blul(0.5in) day] #box[of #blul(0.9in)], in the #box[year 20#blul(0.3in)],
before me, #blul(1.45in) a notary public, personally appeared
#blul(2.45in), proved on the basis of satisfactory evidence to be the
person(s) whose name(s) #box[(is/are)] subscribed to this instrument, and
acknowledged #box[(he/she/they)] executed the same. \ \
Witness my hand and official seal. \ \ \ \
#blul(2.35in) \ #v(-0.5em) _(notary signature)_ \
#h(5in) _(seal)_
]
)
}
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/counter_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Count with string key.
#let mine = counter("mine!")
Final: #locate(loc => mine.final(loc).at(0)) \
#mine.step()
First: #mine.display() \
#mine.update(7)
#mine.display("1 of 1", both: true) \
#mine.step()
#mine.step()
Second: #mine.display("I")
#mine.update(n => n * 2)
#mine.step()
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/pages/graduate-decl.typ | typst | MIT License | #import "../utils/fonts.typ": 字号, 字体
#import "../utils/datetime-display.typ": datetime-display
#import "../utils/twoside.typ": *
#let graduate-decl(
outlined: false,
row-gutter: 11.5pt,
) = {
context {
twoside-pagebreak
set text(font: 字体.宋体)
let zju = underline[#text(font: 字体.楷体, weight: "bold")[浙江大学]]
block(width: 100%)[
#set par(justify: true)
#set text(size: 字号.小四)
#align(center)[
#set text(size: 字号.小二)
浙江大学研究生学位论文独创性声明<mzt:no-header-footer>
]
#v(2em)
本人声明所呈交的学位论文是本人在导师指导下进行的研究工作及取得的研究成果。除了文中特别加以标注和致谢的地方外,论文中不包含其他人已经发表或撰写过的研究成果,也不包含为获得#(zju)或其他教育机构的学位或证书而使用过的材料。与我一同工作的同志对本研究所做的任何贡献均已在论文中作了明确的说明并表示谢意。
#v(2em)
#align(center)[
#table(
columns: (0.5fr, 0.4fr, 0.5fr, auto),
align: (start, center),
stroke: none,
row-gutter: row-gutter,
[ 学位论文作者签名: ], [], [ 签字日期: ], [ 年#h(2em)月#h(2em)日],
)
]
#v(4em)
#align(center)[
#set text(size: 字号.小二)
学位论文版权使用授权书<mzt:no-header-footer>
]
#v(2em)
本学位论文作者完全了解#(zju)有权保留并向国家有关部门或机构送交本论文的复印件和磁盘,允许论文被查阅和借阅。本人授权#(zju)可以将学位论文的全部或部分内容编入有关数据库进行检索和传播,可以采用影印、缩印或扫描等复制手段保存、汇编学位论文。
(保密的学位论文在解密后适用本授权书)
#v(2em)
#align(center)[
#table(
columns: (0.5fr, auto, 0.5fr, auto),
align: (start, center),
stroke: none,
row-gutter: row-gutter,
[ 学位论文作者签名: ], [], [ 导师签名: ], [],
[], [], [], [],
[ 签字日期: ], [ 年#h(2em)月#h(2em)日], [ 签字日期: ], [年#h(2em)月#h(2em)日],
)
]
]
}
twoside-emptypage
} |
https://github.com/NOOBDY/formal-language | https://raw.githubusercontent.com/NOOBDY/formal-language/main/q8.typ | typst | The Unlicense | #let q8 = [
8. Let $M = (Q, Sigma, delta, q_0, F)$ be a `DFA`. A state $q in Q$ is _reachable_ iff there is some string $w in Sigma^*$ such that $hat(delta)(q_0, w) = q$. Consider the following method for computing the set $Q_r subset.eq Q$ of reachable states: define the sequence of sets $Q^i_r subset.eq Q$ where
$ Q^0_r &:= {q_0} \
Q^(i+1)_r &:= {q in Q | exists p in Q^i_r, exists a in Sigma, q = delta(p, a)} $
+ Prove by induction on $i$ that $Q^i_r$ is the set of all reachable states from $q_0$ using paths of length $i$.
Base case:
$ Q^0_r &:= {q_0} $
Inductive step:
$ Q^(i+1)_r &:= {q in Q | exists p in Q^i_r, exists a in Sigma, q = delta(p, a)} $
+ Give an example of a `DFA` such that $Q^(i+1)_r != Q^i_r "for all" i >= 0$.
+ Change the inductive definition of $Q^i_r$ as follows:
$ Q^(i+1)_r := Q^i_r union {q in Q | exists p in Q^i_r, exists a in Sigma, q = delta(p, a)} $
Prove that there exists an $i_0$ such that $Q^(i_0+1)_r = Q^(i_0)_r = Q_r$.
Define the `DFA` $M_r$ as follows: $M_r = (Q_r, Sigma, delta_r , q_0, F sect Q_r)$, where $delta_r : Q_r times Sigma -> Q_r$ is the restriction of $delta$ to $Q_r$ .
4. Explain why $M_r$ is indeed a `DFA`.
+ Prove that $L(M_r) = L(M)$. A `DFA` is called _reachable_ or _trim_ if $M = M_r$.
]
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/070.%20wisdom.html.typ | typst | wisdom.html
Is It Worth Being Wise?
February 2007A few days ago I finally figured out something I've wondered about
for 25 years: the relationship between wisdom and intelligence.
Anyone can see they're not the same by the number of people who are
smart, but not very wise. And yet intelligence and wisdom do seem
related. How?What is wisdom? I'd say it's knowing what to do in a lot of
situations. I'm not trying to make a deep point here about the
true nature of wisdom, just to figure out how we use the word. A
wise person is someone who usually knows the right thing to do.And yet isn't being smart also knowing what to do in certain
situations? For example, knowing what to do when the teacher tells
your elementary school class to add all the numbers from 1 to 100?
[1]Some say wisdom and intelligence apply to different types of
problems—wisdom to human problems and intelligence to abstract
ones. But that isn't true. Some wisdom has nothing to do with
people: for example, the wisdom of the engineer who knows certain
structures are less prone to failure than others. And certainly
smart people can find clever solutions to human problems as well
as abstract ones.
[2]Another popular explanation is that wisdom comes from experience
while intelligence is innate. But people are not simply wise in
proportion to how much experience they have. Other things must
contribute to wisdom besides experience, and some may be innate: a
reflective disposition, for example.Neither of the conventional explanations of the difference between
wisdom and intelligence stands up to scrutiny. So what is the
difference? If we look at how people use the words "wise" and
"smart," what they seem to mean is different shapes of performance.Curve"Wise" and "smart" are both ways of saying someone knows what to
do. The difference is that "wise" means one has a high average
outcome across all situations, and "smart" means one does spectacularly
well in a few. That is, if you had a graph in which the x axis
represented situations and the y axis the outcome, the graph of the
wise person would be high overall, and the graph of the smart person
would have high peaks.The distinction is similar to the rule that one should judge talent
at its best and character at its worst. Except you judge intelligence
at its best, and wisdom by its average. That's how the two are
related: they're the two different senses in which the same curve
can be high.So a wise person knows what to do in most situations, while a smart
person knows what to do in situations where few others could. We
need to add one more qualification: we should ignore cases where
someone knows what to do because they have inside information.
[3]
But aside from that, I don't think we can get much more specific
without starting to be mistaken.Nor do we need to. Simple as it is, this explanation predicts, or
at least accords with, both of the conventional stories about the
distinction between wisdom and intelligence. Human problems are
the most common type, so being good at solving those is key in
achieving a high average outcome. And it seems natural that a
high average outcome depends mostly on experience, but that dramatic
peaks can only be achieved by people with certain rare, innate
qualities; nearly anyone can learn to be a good swimmer, but to be
an Olympic swimmer you need a certain body type.This explanation also suggests why wisdom is such an elusive concept:
there's no such thing. "Wise" means something—that one is
on average good at making the right choice. But giving the name
"wisdom" to the supposed quality that enables one to do that doesn't
mean such a thing exists. To the extent "wisdom" means anything,
it refers to a grab-bag of qualities as various as self-discipline,
experience, and empathy.
[4]Likewise, though "intelligent" means something, we're asking for
trouble if we insist on looking for a single thing called "intelligence."
And whatever its components, they're not all innate. We use the
word "intelligent" as an indication of ability: a smart person can
grasp things few others could. It does seem likely there's some
inborn predisposition to intelligence (and wisdom too), but this
predisposition is not itself intelligence.One reason we tend to think of intelligence as inborn is that people
trying to measure it have concentrated on the aspects of it that
are most measurable. A quality that's inborn will obviously be
more convenient to work with than one that's influenced by experience,
and thus might vary in the course of a study. The problem comes
when we drag the word "intelligence" over onto what they're measuring.
If they're measuring something inborn, they can't be measuring
intelligence. Three year olds aren't smart. When we describe one
as smart, it's shorthand for "smarter than other three year olds."SplitPerhaps it's a technicality to point out that a predisposition to
intelligence is not the same as intelligence. But it's an important
technicality, because it reminds us that we can become smarter,
just as we can become wiser.The alarming thing is that we may have to choose between the two.If wisdom and intelligence are the average and peaks of the same
curve, then they converge as the number of points on the curve
decreases. If there's just one point, they're identical: the average
and maximum are the same. But as the number of points increases,
wisdom and intelligence diverge. And historically the number of
points on the curve seems to have been increasing: our ability is
tested in an ever wider range of situations.In the time of Confucius and Socrates, people seem to have regarded
wisdom, learning, and intelligence as more closely related than we
do. Distinguishing between "wise" and "smart" is a modern habit.
[5]
And the reason we do is that they've been diverging. As knowledge
gets more specialized, there are more points on the curve, and the
distinction between the spikes and the average becomes sharper,
like a digital image rendered with more pixels.One consequence is that some old recipes may have become obsolete.
At the very least we have to go back and figure out if they were
really recipes for wisdom or intelligence. But the really striking
change, as intelligence and wisdom drift apart, is that we may have
to decide which we prefer. We may not be able to optimize for both
simultaneously.Society seems to have voted for intelligence. We no longer admire
the sage—not the way people did two thousand years ago. Now
we admire the genius. Because in fact the distinction we began
with has a rather brutal converse: just as you can be smart without
being very wise, you can be wise without being very smart. That
doesn't sound especially admirable. That gets you <NAME>, who
knows what to do in a lot of situations, but has to rely on Q for
the ones involving math.Intelligence and wisdom are obviously not mutually exclusive. In
fact, a high average may help support high peaks. But there are
reasons to believe that at some point you have to choose between
them. One is the example of very smart people, who are so often
unwise that in popular culture this now seems to be regarded as the
rule rather than the exception. Perhaps the absent-minded professor
is wise in his way, or wiser than he seems, but he's not wise in
the way Confucius or Socrates wanted people to be.
[6]NewFor both Confucius and Socrates, wisdom, virtue, and happiness were
necessarily related. The wise man was someone who knew what the
right choice was and always made it; to be the right choice, it had
to be morally right; he was therefore always happy, knowing he'd
done the best he could. I can't think of many ancient philosophers
who would have disagreed with that, so far as it goes."The superior man is always happy; the small man sad," said Confucius.
[7]Whereas a few years ago I read an interview with a mathematician
who said that most nights he went to bed discontented, feeling he
hadn't made enough progress.
[8]
The Chinese and Greek words we
translate as "happy" didn't mean exactly what we do by it, but
there's enough overlap that this remark contradicts them.Is the mathematician a small man because he's discontented? No;
he's just doing a kind of work that wasn't very common in Confucius's
day.Human knowledge seems to grow fractally. Time after time, something
that seemed a small and uninteresting area—experimental error,
even—turns out, when examined up close, to have as much in
it as all knowledge up to that point. Several of the fractal buds
that have exploded since ancient times involve inventing and
discovering new things. Math, for example, used to be something a
handful of people did part-time. Now it's the career of thousands.
And in work that involves making new things, some old rules don't
apply.Recently I've spent some time advising people, and there I find the
ancient rule still works: try to understand the situation as well
as you can, give the best advice you can based on your experience,
and then don't worry about it, knowing you did all you could. But
I don't have anything like this serenity when I'm writing an essay.
Then I'm worried. What if I run out of ideas? And when I'm writing,
four nights out of five I go to bed discontented, feeling I didn't
get enough done.Advising people and writing are fundamentally different types of
work. When people come to you with a problem and you have to figure
out the right thing to do, you don't (usually) have to invent
anything. You just weigh the alternatives and try to judge which
is the prudent choice. But prudence can't tell me what sentence
to write next. The search space is too big.Someone like a judge or a military officer can in much of his work
be guided by duty, but duty is no guide in making things. Makers
depend on something more precarious: inspiration. And like most
people who lead a precarious existence, they tend to be worried,
not contented. In that respect they're more like the small man of
Confucius's day, always one bad harvest (or ruler) away from
starvation. Except instead of being at the mercy of weather and
officials, they're at the mercy of their own imagination.LimitsTo me it was a relief just to realize it might be ok to be discontented.
The idea that a successful person should be happy has thousands of
years of momentum behind it. If I was any good, why didn't I have
the easy confidence winners are supposed to have? But that, I now
believe, is like a runner asking "If I'm such a good athlete, why
do I feel so tired?" Good runners still get tired; they just get
tired at higher speeds.People whose work is to invent or discover things are in the same
position as the runner. There's no way for them to do the best
they can, because there's no limit to what they could do. The
closest you can come is to compare yourself to other people. But
the better you do, the less this matters. An undergrad who gets
something published feels like a star. But for someone at the top
of the field, what's the test of doing well? Runners can at least
compare themselves to others doing exactly the same thing; if you
win an Olympic gold medal, you can be fairly content, even if you
think you could have run a bit faster. But what is a novelist to
do?Whereas if you're doing the kind of work in which problems are
presented to you and you have to choose between several alternatives,
there's an upper bound on your performance: choosing the best every
time. In ancient societies, nearly all work seems to have been of
this type. The peasant had to decide whether a garment was worth
mending, and the king whether or not to invade his neighbor, but
neither was expected to invent anything. In principle they could
have; the king could have invented firearms, then invaded his
neighbor. But in practice innovations were so rare that they weren't
expected of you, any more than goalkeepers are expected to score
goals.
[9]
In practice, it seemed as if there was a correct decision
in every situation, and if you made it you'd done your job perfectly,
just as a goalkeeper who prevents the other team from scoring is
considered to have played a perfect game.In this world, wisdom seemed paramount.
[10]
Even now, most people
do work in which problems are put before them and they have to
choose the best alternative. But as knowledge has grown more
specialized, there are more and more types of work in which people
have to make up new things, and in which performance is therefore
unbounded. Intelligence has become increasingly important relative
to wisdom because there is more room for spikes.RecipesAnother sign we may have to choose between intelligence and wisdom
is how different their recipes are. Wisdom seems to come largely
from curing childish qualities, and intelligence largely from
cultivating them.Recipes for wisdom, particularly ancient ones, tend to have a
remedial character. To achieve wisdom one must cut away all the
debris that fills one's head on emergence from childhood, leaving
only the important stuff. Both self-control and experience have
this effect: to eliminate the random biases that come from your own
nature and from the circumstances of your upbringing respectively.
That's not all wisdom is, but it's a large part of it. Much of
what's in the sage's head is also in the head of every twelve year
old. The difference is that in the head of the twelve year old
it's mixed together with a lot of random junk.The path to intelligence seems to be through working on hard problems.
You develop intelligence as you might develop muscles, through
exercise. But there can't be too much compulsion here. No amount
of discipline can replace genuine curiosity. So cultivating
intelligence seems to be a matter of identifying some bias in one's
character—some tendency to be interested in certain types of
things—and nurturing it. Instead of obliterating your
idiosyncrasies in an effort to make yourself a neutral vessel for
the truth, you select one and try to grow it from a seedling into
a tree.The wise are all much alike in their wisdom, but very smart people
tend to be smart in distinctive ways.Most of our educational traditions aim at wisdom. So perhaps one
reason schools work badly is that they're trying to make intelligence
using recipes for wisdom. Most recipes for wisdom have an element
of subjection. At the very least, you're supposed to do what the
teacher says. The more extreme recipes aim to break down your
individuality the way basic training does. But that's not the route
to intelligence. Whereas wisdom comes through humility, it may
actually help, in cultivating intelligence, to have a mistakenly
high opinion of your abilities, because that encourages you to keep
working. Ideally till you realize how mistaken you were.(The reason it's hard to learn new skills late in life is not just
that one's brain is less malleable. Another probably even worse
obstacle is that one has higher standards.)I realize we're on dangerous ground here. I'm not proposing the
primary goal of education should be to increase students' "self-esteem."
That just breeds laziness. And in any case, it doesn't really fool
the kids, not the smart ones. They can tell at a young age that a
contest where everyone wins is a fraud.A teacher has to walk a narrow path: you want to encourage kids to
come up with things on their own, but you can't simply applaud
everything they produce. You have to be a good audience: appreciative,
but not too easily impressed. And that's a lot of work. You have
to have a good enough grasp of kids' capacities at different ages
to know when to be surprised.That's the opposite of traditional recipes for education. Traditionally
the student is the audience, not the teacher; the student's job is
not to invent, but to absorb some prescribed body of material. (The
use of the term "recitation" for sections in some colleges is a
fossil of this.) The problem with these old traditions is that
they're too much influenced by recipes for wisdom.DifferentI deliberately gave this essay a provocative title; of course it's
worth being wise. But I think it's important to understand the
relationship between intelligence and wisdom, and particularly what
seems to be the growing gap between them. That way we can avoid
applying rules and standards to intelligence that are really meant
for wisdom. These two senses of "knowing what to do" are more
different than most people realize. The path to wisdom is through
discipline, and the path to intelligence through carefully selected
self-indulgence. Wisdom is universal, and intelligence idiosyncratic.
And while wisdom yields calmness, intelligence much of the time
leads to discontentment.That's particularly worth remembering. A physicist friend recently
told me half his department was on Prozac. Perhaps if we acknowledge
that some amount of frustration is inevitable in certain kinds
of work, we can mitigate its effects. Perhaps we can box it up and
put it away some of the time, instead of letting it flow together
with everyday sadness to produce what seems an alarmingly large
pool. At the very least, we can avoid being discontented about
being discontented.If you feel exhausted, it's not necessarily because there's something
wrong with you. Maybe you're just running fast.Notes[1]
Gauss was supposedly asked this when he was 10. Instead of
laboriously adding together the numbers like the other students,
he saw that they consisted of 50 pairs that each summed to 101 (100
+ 1, 99 + 2, etc), and that he could just multiply 101 by 50 to get
the answer, 5050.[2]
A variant is that intelligence is the ability to solve problems,
and wisdom the judgement to know how to use those solutions. But
while this is certainly an important relationship between wisdom
and intelligence, it's not the distinction between them. Wisdom
is useful in solving problems too, and intelligence can help in
deciding what to do with the solutions.[3]
In judging both intelligence and wisdom we have to factor out
some knowledge. People who know the combination of a safe will be
better at opening it than people who don't, but no one would say
that was a test of intelligence or wisdom.But knowledge overlaps with wisdom and probably also intelligence.
A knowledge of human nature is certainly part of wisdom. So where
do we draw the line?Perhaps the solution is to discount knowledge that at some point
has a sharp drop in utility. For example, understanding French
will help you in a large number of situations, but its value drops
sharply as soon as no one else involved knows French. Whereas the
value of understanding vanity would decline more gradually.The knowledge whose utility drops sharply is the kind that has
little relation to other knowledge. This includes mere conventions,
like languages and safe combinations, and also what we'd call
"random" facts, like movie stars' birthdays, or how to distinguish
1956 from 1957 Studebakers.[4]
People seeking some single thing called "wisdom" have been
fooled by grammar. Wisdom is just knowing the right thing to do,
and there are a hundred and one different qualities that help in
that. Some, like selflessness, might come from meditating in an
empty room, and others, like a knowledge of human nature, might
come from going to drunken parties.Perhaps realizing this will help dispel the cloud of semi-sacred
mystery that surrounds wisdom in so many people's eyes. The mystery
comes mostly from looking for something that doesn't exist. And
the reason there have historically been so many different schools
of thought about how to achieve wisdom is that they've focused on
different components of it.When I use the word "wisdom" in this essay, I mean no more than
whatever collection of qualities helps people make the right choice
in a wide variety of situations.[5]
Even in English, our sense of the word "intelligence" is
surprisingly recent. Predecessors like "understanding" seem to
have had a broader meaning.[6]
There is of course some uncertainty about how closely the remarks
attributed to Confucius and Socrates resemble their actual opinions.
I'm using these names as we use the name "Homer," to mean the
hypothetical people who said the things attributed to them.[7]
Analects VII:36, Fung trans.Some translators use "calm" instead of "happy." One source of
difficulty here is that present-day English speakers have a different
idea of happiness from many older societies. Every language probably
has a word meaning "how one feels when things are going well," but
different cultures react differently when things go well. We react
like children, with smiles and laughter. But in a more reserved
society, or in one where life was tougher, the reaction might be a
quiet contentment.[8]
It may have been <NAME>, but I'm not sure. If anyone
remembers such an interview, I'd appreciate hearing from you.[9]
Confucius claimed proudly that he had never invented
anything—that he had simply passed on an accurate account of
ancient traditions. [Analects VII:1] It's hard for us now to
appreciate how important a duty it must have been in preliterate
societies to remember and pass on the group's accumulated knowledge.
Even in Confucius's time it still seems to have been the first duty
of the scholar.[10]
The bias toward wisdom in ancient philosophy may be exaggerated
by the fact that, in both Greece and China, many of the first
philosophers (including Confucius and Plato) saw themselves as
teachers of administrators, and so thought disproportionately about
such matters. The few people who did invent things, like storytellers,
must have seemed an outlying data point that could be ignored.Thanks to <NAME>, <NAME>, <NAME>,
and <NAME> for reading drafts of this.Polish TranslationFrench TranslationRussian TranslationRussian Translation
|
|
https://github.com/SE-legacy/physics_lectures_3_term | https://raw.githubusercontent.com/SE-legacy/physics_lectures_3_term/main/lesson_2/conf.typ | typst | // Function to get a string, containing the course and the speciality. Used in titlepage
#let get_course_speciality(group) = {
let specialities = (
[Фундаментальная информатика и информационные технологии],
[Информатика и вычислительная техника],
[Компьютерная безопасность],
[Математическое обеспечение и администрирование информационных систем],
[Программная инженерия],
[Педагогическое образование],
[Информатика и вычислительная техника],
[Математическое обеспечение и администрирование информационных систем],
[Системный анализ и управление]
)
let result = str(group).at(0) + " курс"
if str(group).at(1) == "7" {
result += " (магистратура)"
if str(group).at(2) == "1" {
result += ", «" + specialities.at(6) + "»"
} else if str(group).at(2) == "3" {
result += ", «" + specialities.at(7) + "»"
}
return result
}
let id = int(str(group).at(1)) - 1;
if id >= 0 and id <= 8 {
result += ", «" + specialities.at(id) + "»"
}
return result
}
#let codeblock(lang, code) = {
raw(
block: true,
lang: lang,
code
)
}
// Titlepage builder
#let make_titlepage(
info: ()
) = {
set align(center)
v(2em)
text(size: 2em,
weight: 700,
str(info.title))
v(1em)
text(size: 1em,
str(info.author) + "\n" + get_course_speciality(int(info.group)))
set align(center)
text(size: 1em,
str(info.city) + ", " + str(info.year))
}
// TOC builder
#let make_toc(
info: ()
) = {
outline(indent: 2%,
title: [Содержание])
pagebreak(weak: true)
}
// Main configuration script
#let conf(
meta: (),
toc: (),
content
) = {
show raw: set text(
font: "JetBrains Mono",
ligatures: false,
features: (calt: 0)
)
show raw.where(block: true): code => {
show raw.line: line => {
text(fill: gray)[#line.number]
h(1em)
line.body
}
code
}
show link: set text(
fill: gradient.linear(rgb("#6ec080"), rgb("#1b7ab4"), angle: 45deg)
)
set text(
font: "Cambria",
size: 14pt,
ligatures: false,
)
make_titlepage(info: meta)
make_toc(info: toc)
content
}
|
|
https://github.com/freundTech/kit-slides-typst | https://raw.githubusercontent.com/freundTech/kit-slides-typst/main/presentation.typ | typst | Other | #import "kit-slides.typ": *
#show: kit-theme.with(
title: [A KIT Presentation],
subtitle: [Created using Typst and kit-slides],
author: [<NAME>],
short-title: [A Kit Presentation using Typst],
// group-logo: image("Path to your group's logo"),
date: [July 2023],
language: "en",
institute: [Private],
show-page-count: false,
)
#title-slide(
//banner: image("assets/kit/banner.jpg")
)
#slide(title: [A slide title])[
Some text: #lorem(20)
A new paragraph with #text(fill: blue)[colored] text.
]
#slide(title: [A split slide])[
#side-by-side[
A list
- Item
- Another item
- A third item
][
The right side.
#lorem(40)
]
]
#slide(title: [Dynamic slides])[
A fancy dynamic slide.
#uncover("2-")[This appears later!]
]
#slide(title: [Colored Blocks])[
#set block(above: 0.8em) // Slightly reduce the block spacing, so we can fit 4 blocks on a page
#kit-info-block(title: [Info Block])[
- Green
]
#kit-example-block(title: [Example Block])[
- Blue
]
#kit-alert-block(title: [Alert Block])[
- Red
]
#kit-color-block(title: [Custom Colors], color: yellow)[
- Whatever you want
]
]
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/identify-tasks.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/template/entries.typ": create_entry
#import "/template/widgets.typ": *
#create_entry(
title: "Identify Challenges",
type: "identify",
start_date: datetime(year: 2023, month: 5, day: 12),
)[
#heading(([Tasks], level: 1)
After looking over the rules again we identified several tasks our robot needs
to be able to complete:
#grid(
columns: 2,
[
#heading(([Traversing the field], level: 2)
Our robot will need to be able to traverse the field. Not only will it have to
be able to cross normal tiles, but it will also have to be able to cross the
barrier in the middle of the field.
],
image("/assets/game-challenges/traversing.svg"),
image("/assets/game-challenges/scoring-triballs.svg"),
[
#heading(([Scoring Triballs], level: 2)
This task should be our highest priority as most of the game elements are
triballs, and we'll spend most of the game interacting with them. We are not
allowed to score more than one triball, so we agreed that the speed at which we
score triballs is very important.
],
[
#heading(([Picking up Triballs], level: 2)
Picking up triballs is also a very important task, but due to the fact that
triballs can be loaded directly into our robot at the match load zone this task
is not as important as it would normally be.
],
image("/assets/game-challenges/picking-up-triballs.svg"),
image("/assets/game-challenges/moving-triballs.svg"),
[
#heading(([Moving Triballs], level: 2)
Moving triballs is essential to our ability to score them. Like the scoring, we
decided that the highest priority when approaching this task how fast we can
move them due to our ability to only possess one at a time.
],
[
#heading(([Climbing], level: 2)
Our robot needs to be able to climb up the elevation bar. The way that this is
scored is relative to other robots, making this task very important. If we
manage to get our robot off the ground we aren't just scoring points for our
alliance, we're also removing points from the opposing alliance.
],
image("/assets/game-challenges/elevation.svg"),
)
]
|
https://github.com/aagumin/cv | https://raw.githubusercontent.com/aagumin/cv/typst/content/languages.typ | typst | #import "@preview/grotesk-cv:0.1.2": *
#import "@preview/fontawesome:0.2.1": *
#let meta = toml("../info.toml")
#let language = meta.personal.language
== #fa-icon("language") #h(5pt) #if language == "en" [Languages] else if language == "es" [Idiomas]
//#get-header-by-language("Languages", "Idiomas")
#v(5pt)
#if language == "en" {
language-entry(language: "English", proficiency: "Native")
language-entry(language: "Spanish", proficiency: "Fluent")
language-entry(language: "Machine Code", proficiency: "Fluent")
} else if language == "es" {
language-entry(language: "Inglés", proficiency: "Nativo")
language-entry(language: "Español", proficiency: "Fluido")
language-entry(language: "Código de Máquina", proficiency: "Fluido")
}
|
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Diagrams/ER.typ | typst | ```pintora
erDiagram
Faculty {
INTEGER Id
TEXT Title
}
Course {
INTEGER Id
TEXT Title
VARCHAR Shortcut(E1)
}
Module {
INTEGER Id
INTEGER Number(E1)
TEXT Title(E1)
TEXT Subtitle(E2)
VARCHAR Shortcut(E2)
TEXT Niveau(E3)
TEXT Type(E4)
INTEGER Credits(E7)
INTEGER HoursAtLocation(E8)
INTEGER HoursAtHome(E8)
INTEGER Semester(E9)
INTEGER CourseLength(E10)
TEXT Exam(E13)
TEXT Learnings(E14)
}
SubModule {
INTEGER Id
INTEGER Number(E15)
TEXT Language(E16)
TEXT Type(E18)
INTEGER PresenceHoursPerWeek(E18)
TEXT LearningRecommendations(E19)
INTEGER GroupSize(20)
TEXT Content(E21)
TEXT PresenceRequirements(E22)
TEXT LearningRequirements(E23)
TEXT Literature(E24)
}
User {
INTEGER Id
TEXT Title
VARCHAR Username
VARCHAR FirstName
VARCHAR LastName
VARCHAR Email
VARCHAR Password
}
Changelog {
INTEGER Id
DATETIME Timestamp
VARCHAR Table
}
ChangelogItem {
INTEGER Id
VARCHAR Column
VARCHAR PreviousValue
}
RequirementList {
INTEGER Id
TEXT Name
BOOLEAN Optional
}
RequirementListItem {
INTEGER Id
}
Faculty ||--o{ Course : "Courses"
Course ||--o{ Module : "Modules(E17)"
Module }o--o{ SubModule : "Submodules(E5)"
Module }o--|| User : "Responsible(E6)"
Course }o--|| User : "Responsible"
Changelog }o--|| User : "Author(F15)"
Changelog ||--o{ ChangelogItem : "Changes(F16)"
Module }o--|| RequirementList : "Requirement(E11/12)"
RequirementList }o--o{ RequirementListItem : "Requirements"
Module ||--o{ RequirementListItem : "Module"
``` |
|
https://github.com/howardlau1999/sysu-thesis-typst | https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/chapters/abstract-cn.typ | typst | MIT License | #let 中文关键词 = ("论文", "typst", "模板")
这是中文摘要。间起北家。 许士业小健明他该有金,升队民国团,理提已? 经局由情色于! 的经举国有发为题他什常直流望字防多学。 讲来破会全闻室; 个这提金自办太完作,明然内然我山是? 力过究可象定开不展法南顾取什说; 候社进。 动动里上谢再苦,务的里度成的文电儿说流像状好音! 得年跑电白线经合电终也玩青满情子,舞代公续斯会了作电李多。 回受轮了随自西同; 长样头些实林好分于,维龙布一市由本为会,入令比格带,依为健,竟少个共得家他们集:由德环? 很里习用人我方乐员在开亲书突! 建我这省们高意生开日一; 张他下心开图则所了热呢都难直着受可! 速己了很鱼不上痛便阳一且物月爸适台得科事下,乐着馆模校。
公明议要所布以流式雄道人他早在,的立样多的作整使政把升问,地灵失养中系说到出因由为身取到但大的著做区科过受小取她红看作效花。 不就品国家房星生率老自! 亚究先常,人的初指一全作保业好是只青国模一两力:以因后提开交馆明画因一装车多小基由,情安前在来孩地几空生是分看原? |
https://github.com/Caellian/UNIRI_voxels_doc | https://raw.githubusercontent.com/Caellian/UNIRI_voxels_doc/trunk/util.typ | typst | #let hr-month-name = (month) => {
if month == 1 {"siječnja"}
else if month == 2 {"veljače"}
else if month == 3 {"ožujka"}
else if month == 4 {"travnja"}
else if month == 5 {"svibnja"}
else if month == 6 {"lipnja"}
else if month == 7 {"srpnja"}
else if month == 8 {"kolovoza"}
else if month == 9 {"rujna"}
else if month == 10 {"listopada"}
else if month == 11 {"stodenog"}
else if month == 12 {"prosinca"}
else { panic("invalid month") }
}
#let hr-date-format = (date) => [#date.day(). #hr-month-name(date.month()) #date.year().]
#let locale-date-format = (locale, date) => {
if locale == "hr" {
return hr-date-format(date)
} else {
panic("unhandled locale-date-format locale: " + locale)
}
}
#let complexity(case: "worst", value) = {
if case == "same" {
$Theta(#value)$
} else if case == "worst" {
$O(#value)$
} else if case == "best" {
$Omega(#value)$
} else {
panic("unknown complexity case: " + case + "; valid values are: 'same', 'worst', 'best'")
}
}
|
|
https://github.com/xsro/xsro.github.io | https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/Control-for-Integrator-Systems/8sta.typ | typst | #import "lib/lib.typ":sig,sgn
= Super Twisting Control
The STA (Super Twisting Algorithm) can be written as
$
dot(x)_1&=-k_1 sig(x_1)^(1/2)+x_2+rho.alt_1(x,t)\
dot(x)_2&=-k_2 sgn(x_1)+rho.alt_2(x,t)
$<classical_sta>
where $x_i$ are the scalar state variables,
$k_i$ are gains to be designed,
and $rho.alt_i$ are the perturbation terms.
*Under some conditions on $k_i$, the algorithm is robust against a bounded perturbation*
$rho.alt_1(x,t)=0$, $abs(rho.alt_2(x,t)) <= L$.
Since the righthand side of @classical_sta is discontinuous,
the solutions will be understood in the sense of *Filippov*.
Finite time convergence and robustness for the STA has been proved by
+ *geometrical methods* @levant_principles_2007
+ *Homogeneity properties* of the algorithm @levant_homogeneity_2005 @orlov_finite_2004
- Weak Lyapunov function $V_w(x)=k_2 abs(x_1) + 1/2 x_2^2$ @orlov_finite_2004, $sqrt(V_w(x))$ @Utkin2017
- Strong Lyapunov function: $V$ in @polyakov_reaching_2009,@moreno_strict_2012,@seeber_stability_2017
"Weak" measns $dot(V)_w(x)=-k_1k_2 abs(x_1)^(1/2)$ is only negative semidefinite. (Finite time) convergence can only be asserted by using a generaization of LaSalle's invariance principle for discontinuous systems @orlov_finite_2004, but it is not possible to provide robustness results, or to estimate the convergence time from it.
@Utkin2017 analyse the weak Lyapunov function $sqrt(V_w(x))$ and the finite time and robust convergence for the STA is proved.
#pagebreak()
== Strick Lyapunov Functions for STA
#set math.mat(delim: "[")
#columns(2)[
#set cite(form:"full")
@polyakov_reaching_2009
$
V=cases(
k^2/4 ((y sgn(x_1))/gamma+k_0 e^(m(x_1,x_2))sqrt(s(x_1,x_2)))^2 quad & x_1 x_2!=0,
(2 k^2 x_2^2)/(alpha^2) & x_1=0,
abs(x_1)/2 & x_2=0
)
$
@moreno_strict_2012
$
V(x)=zeta^T P zeta,
zeta=mat(sig(x_1)^(1/2);x_2)
$
@seeber_stability_2017
$
V(x)=cases(
2 sqrt(x_2^2+ 3 alpha^2 k_1^2 x_1)-x_2
quad & x in M,
2 sqrt(x_2^2+ 3 alpha^2 k_1^2 x_1)+x_2 & -x in M,
3 abs(x_2) &"otherwise"
)
$
]
#pagebreak()
|
|
https://github.com/mattheww/tyroshup | https://raw.githubusercontent.com/mattheww/tyroshup/funcalls/funcalls/general.typ | typst | #import "fns.typ": dt, t, t2, rubric, syntax, editorial
= General
This document contains some of the text from a couple of pages of the Ferrocene Language Specification (commit `ab6469ca23` from 2023-10-05).
It covers call expressions and return expressions.
%SKIPPING% indicates a place where material has been cut out.
== Structure
Each chapter is divided into subchapters that have a common structure.
Each chapter and subchapter is then organized to include the following segments as is relevant to the topic:
#rubric[Syntax]
The syntax representation of a #t("construct").
#rubric[Legality Rules]
Compile-time rules and facts for each #t("construct").
A #t("construct") is legal if it obeys all of the Legality Rules.
#rubric[Dynamic Semantics]
Run-time effects of each #t("construct").
#rubric[Undefined Behavior]
Situations that result in unbounded errors.
#rubric[Implementation Requirements]
Additional requirements for conforming tools.
#rubric[Examples]
Examples illustrating the possible forms of a #t("construct").
This material is informative.
== Method of Description and Syntax Notation
The form of a Rust program is described by means of a context-free syntax together with context-dependent requirements expressed by narrative rules.
The meaning of a Rust program is described by means of narrative rules defining both the effects of each construct and the composition rules for constructs.
The context-free syntax of Rust is described using a simple variant of the Backus-Naur form.
In particular:
- A `monospaced` font is used to denote Rust syntax.
- Words in PascalCase font are used to denote a syntactic category, for example:
```
FloatExponent
```
- Words in *bold* font are used to indicate literal words and
#t2("keyword")[keywords], for example:
#syntax[```
$$crate$$
$$proc_macro_derive$$
$$Self$$
$$tt$$
```]
#editorial[We'd want some kind of custom processing for this, in particular
interpreting the \$\$ markup.]
%SKIPPING%
== Definitions
Terms are defined throughout this document, indicated by _italic_ type.
Terms explicitly defined in this document are not to be presumed to refer implicitly to similar terms defined elsewhere.
%SKIPPING%
The definitions of terms are available in #link(label("glossary"))[Glossary].
A _rule_ is a requirement imposed on the programmer, stated in normative language such as "shall", "shall not", "must", "must not", except for text under Implementation Requirements heading.
A _fact_ is a requirement imposed on a conforming tool, stated in informative language such as "is", "is not", "can", "cannot".
|
|
https://github.com/lublak/typst-echarm-package | https://raw.githubusercontent.com/lublak/typst-echarm-package/main/README.md | markdown | MIT License | # Echarm
A typst plugin to run echarts in typst with the use of CtxJS.
## Examples
<table>
<tr>
<td><a href="examples/mixed_charts.typ"><img src="examples/mixed_charts.png" width="100%"></a></td>
<td><a href="examples/radar.typ"><img src="examples/radar.png" width="100%"></a></td>
<td><a href="examples/pie.typ"><img src="examples/pie.png" width="100%"></a></td>
</tr>
<tr>
<td><a href="examples/mixed_charts.typ">Source Code</a></td>
<td><a href="examples/radar.typ">Source Code</a></td>
<td><a href="examples/pie.typ">Source Code</a></td>
</tr>
<tr>
<td><a href="examples/scatter.typ"><img src="examples/scatter.png" width="100%"></a></td>
<td><a href="examples/gauge.typ"><img src="examples/gauge.png" width="100%"></a></td>
<td><a href="examples/candlestick.typ"><img src="examples/candlestick.png" width="100%"></a></td>
</tr>
<tr>
<td><a href="examples/scatter.typ">Source Code</a></td>
<td><a href="examples/gauge.typ">Source Code</a></td>
<td><a href="examples/candlestick.typ">Source Code</a></td>
</tr>
</table>
For more examples see:
https://echarts.apache.org/examples/en/index.html
For the complete documentation for the configuration of echarts, see:
https://echarts.apache.org/en/option.html
## Usage
```typst
#import "@preview/echarm:0.1.0"
// options are echart options
#echarm.render(width: 100%, height: 100%, options: (:))
```
## Infos
The version is not the same as the echart version, so that I can update independently.
Animations are not supported here!
You can find more information about CtxJS here:
https://typst.app/universe/package/ctxjs/
## Versions
| Version | Echart-Version |
|---------|----------------|
| 0.1.0 | 5.5.1 | |
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/decorations/gategroup/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#quantum-circuit(
gategroup(1, 2, label: ((pos: top, content: "A"), (pos: left, content: "B")),), $K$, 1, 5pt, swap(0), [\ ],
2, swap(-1),
gategroup(2, 1, x: 2, y: 0, label: "swap", stroke: .5pt + blue, radius: 4pt, fill: blue)
) |
https://github.com/cohenasaf/Teoria-Informazione-Trasmissione | https://raw.githubusercontent.com/cohenasaf/Teoria-Informazione-Trasmissione/main/2023-10-06.typ | typst | #import "@preview/tablex:0.0.5": tablex
= Introduzione
== Storia
La teoria dell'informazione nasce nel 1948 grazie a *<NAME>* (1916-2001), un impiegato alla "Telecom" americana al quale sono stati commissionati due lavori: data una comunicazione su filo di rame, si voleva sfruttare tutta la capacità del canale, ma al tempo stesso coreggere gli errori di trasmissione dovuti al rumore presente.
Nel 1948 infatti viene pubblicato l'articolo "_A Mathematical Theory of Communication_" da parte di Bell Labs, dove Shannon pone le basi della teoria dell'informazione.
Ma non è l'unico personaggio che lavora in questo ambito: infatti, nel 1965, tre matematici russi pubblicano degli articoli che vanno a perfezionare il lavoro fatto anni prima da Shannon.
I tre matematici sono <NAME> (1947-), <NAME> (1926-2009) e *<NAME>* (1903-1987), ma si considerano solo gli articoli di quest'ultimo poiché ai tempi era molto più famoso dei primi due.
== Shannon vs Kolmogorov
La situazione generica che troveremo in quasi la totalità dei nostri studi si può ridurre alla comunicazione tra due entità tramite un *canale affetto da rumore*.
#v(12pt)
#figure(
image("assets/canale.svg", width: 50%)
)
#v(12pt)
Quello che distingue Shannon da Kolmogorov è l'approccio: il primo propone un *approccio ingegneristico*, ovvero tramite un modello formato da una distribuzione di probabilità si va a definire cosa fa _in media_ la sorgente, mentre il secondo propone un *approccio rigoroso e formale*, dove sparisce la nozione di media e si introduce la nozione di sorgente in modo _puntuale_.
In poche parole, dato un messaggio da comprimere:
- Shannon direbbe "lo comprimo _in media_ così, e lo comprimerei così anche se il messaggio fosse totalmente diverso";
- Kolmogorov direbbe "lo comprimo _esattamente_ così, ma lo comprimerei in modo totalmente diverso se il messaggio fosse diverso".
== Obiettivi di Shannon
Gli obiettivi che Shanno vuole perseguire sono due:
- *massimizzare* l'informazione trasmessa _ad ogni utilizzo del canale_;
- *minimizzare* il numero di errori di trasmissione dovuti alla presenza del rumore nel canale.
La parte "_ad ogni utilizzo del canale_" viene inserita per dire che, ogni volta che si accede al canale, deve essere utilizzato tutto, mentre senza questa parte una sorgente potrebbe mandare l'1% del messaggio ad ogni accesso al canale, mandandolo sì tutto ma senza sfruttare a pieno la banda.
Shanno risolverà questi due problemi con due importantissimi teoremi:
- *$I$° teorema di Shannon*, che riguarda la _source coding_, ovvero la ricerca di un codice per rappresentare i messaggi della sorgente che massimizzi l'informazione spedita sul canale, ovvero massimizzi la sua *compressione*;
- *$\I\I$° teorema di Shannon*, che riguarda la _channel coding_, ovvero la ricerca di un codice per rappresentare i messaggi della sorgente che minimizzi gli errori di trasmissione dovuti alla presenza del rumore nel canale.
L'approccio che viene usato è quello _divide-et-impera_, che in questo caso riesce a funzionare bene e riesce ad unire i risultati dei due teoremi di Shannon grazie al *teorema di codifica congiunta sorgente-canale* e ad alcune relazioni che legano i due problemi descritti.
In un caso generale del _divide-et-impera_ si ricade in una soluzione sub-ottimale.
== Primo teorema di Shannon
Il primo problema da risolvere è il seguente: come è distribuita l'informazione all'interno di un documento?
Vediamo due esempi dove un documento viene spedito su un canale e alcune informazioni vengono perse per colpa del rumore presente nel canale.
#v(12pt)
#figure(
image("assets/poca-informazione.svg", width: 75%)
)
#v(12pt)
In questo primo esempio notiamo che, nonostante l'informazione persa sia sostanziosa, possiamo in qualche modo "risalire" a quello perso per via delle informazioni che troviamo "nelle vicinanze".
#v(12pt)
#figure(
image("assets/tanta-informazione.svg", width: 75%)
)
#v(12pt)
In questo secondo esempio notiamo invece che, nonostante l'informazione persa sia molto meno rispetto a quella precedente, "risalire" al contenuto perso è molto più difficile.
Questi due esempi dimostrano come l'informazione contenuta in un documento *non* è uniforme, e quindi che una distorsione maggiore non implica una perdita maggiore di informazioni.
L'obiettivo del primo teorema di Shannon è eliminare le informazioni inutili e ridondanti, comprimendo il messaggio per poter utilizzare il canale per inviare altre informazioni.
Quello che facciamo è concentrare l'informazione, rendendola *equamente distribuita*, quindi impossibile da ridurre ancora e contenente solo informazioni importanti.
== Secondo teorema di Shannon
Il secondo teorema di Shannon è quello più rognoso, perchè si occupa della _channel coding_, ovvero di una codifica che permetta di minimizzare l'informazione persa durante la trasmissione.
Vogliamo questo perchè l'informazione che passa sul canale è compressa, quindi qualsiasi bit perso ci fa perdere molte informazioni, non essendoci ridondanza.
Quello che viene fatto quindi è aggiungere *ridondanza*, ovvero più copie delle informazioni da spedire così che, anche perdendo un bit di informazione, lo si possa recuperare usando una delle copie inviate.
La ridondanza che aggiungiamo però è *controllata*, ovvero in base al livello di distorsione del canale utilizzato si inviano un certo numero di copie.
In un *canale ideale* la ridondanza è pari a 0, mentre per canali con rumore viene usata una matrice stocastica, che rappresenta la distribuzione probabilistica degli errori.
#align(center)[
#table(
align: center + horizon,
columns: (7%, 7%, 7%, 7%, 7%, 7%),
inset: 10pt,
[], [a], [b], [c], [d], [e],
[a], [0.7], [0.0], [0.1], [0.1], [0.1],
[b], [...], [...], [...], [...], [...],
[c], [...], [...], [...], [...], [...],
[d], [...], [...], [...], [...], [...],
[e], [...], [...], [...], [...], [...]
)
]
Ogni riga $i$ rappresenta una distribuzione di probabilità che definisce la probabilità che, spedito il carattere $i$, si ottenga uno dei valori $j$ presenti nelle colonne.
Se il canale è ideale la matrice risultante è la matrice identità.
|
|
https://github.com/open-datakit/accs-finalreport-whitepaper | https://raw.githubusercontent.com/open-datakit/accs-finalreport-whitepaper/main/1-intro/content.typ | typst | = Introduction to the opendata.fit platform
#lorem(100)
== Motivation
== History
#include "team.typ"
|
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/moduleTablePrisma.typ | typst | ```prisma
model Module {
id Int @id @default(autoincrement())
name String
niveau String
abbreviation String
description String
...
degreePrograms DegreeProgramToModule[]
}
``` |
|
https://github.com/ojas-chaturvedi/typst-templates | https://raw.githubusercontent.com/ojas-chaturvedi/typst-templates/master/assignments/assignment.typ | typst | MIT License | #import "template.typ": *
#let title = "Assignment #1"
#let author = "<NAME>"
#let course_id = "CS101"
#let instructor = "<NAME>"
#let semester = "Fall 2024"
#let due_time = "August 24 at 11:59 PM"
#set enum(numbering: "a)")
#show: assignment.with(title, author, course_id, instructor, semester, due_time)
#prob(
[
What is the purpose of life?
],
[
1. I do not know.
2. Perchance.
]
) |
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/cyberdef/weeks/week4.typ | typst | #import "../../utils.typ": *
#section("Shell Exploit")
#subsection("Bind Shell")
#align(
center,
[#image("../../Screenshots/2023_10_10_09_13_33.png", width: 80%)],
)
#subsection("Reverse Shell")
#align(
center,
[#image("../../Screenshots/2023_10_10_09_14_19.png", width: 80%)],
)
#subsection("Reuse Web Shell")
#align(
center,
[#image("../../Screenshots/2023_10_10_09_14_38.png", width: 80%)],
)
#section("MetaSploit")
This is a framework to test exploits.
- payloads
- bash shell
- *Meterpreter*\
Meterpreter is an advanced, dynamically extensible payload that uses in-memory
DLL injection stagers and is extended over the network at runtime. It
communicates over the stager socket and provides a comprehensive client-side
Ruby API. It features command history, tab completion, channels, and more.
- 3 stage payload
- works on winshit and penguinOS
- can execute commands
- take screenshots
- load code
- can handle multiple connections
- all forms of shell exploits
#align(
center,
[#image("../../Screenshots/2023_10_10_09_19_26.png", width: 70%)],
)
|
|
https://github.com/Lindronics/skipper-reference | https://raw.githubusercontent.com/Lindronics/skipper-reference/main/skipper_reference.typ | typst | MIT License | #import "@preview/colorful-boxes:1.2.0": *
#set heading(numbering: "1.")
#set text(
size: 10pt,
)
#set page(
header: [
#h(1fr)
_Niklas' Skipper Companion_
],
numbering: "1"
)
#outline(
indent: 1em
)
#pagebreak()
= General
== Terms
#columns(
2,
[
/ abaft: Towards the stern
/ abeam: On the beam; at right angles to centre line
/ ahead: Forward; towards the bow
/ astern: Backwards; towards the stern
/ cable: Anchor chain/line
/ fender: Cushion for preventing damage to a boat; hung from the guard rails
/ foul: Entangled or entwined; e.g. _foul anchor_
/ guard rails: Cables or ropes
/ hawser: TODO
/ heaving to: Put the boat into a stable position, usually achieved by backing the foresail (@heave_to)
/ helm: Steering of the boat; helmsman
/ hull speed: speed at which the wavelength of the boat's bow wave equals its hull length
/ jack stays: TODO
/ lazy line: TODO
/ mooring: Attaching a boat to shore by rope
/ stanchions: Posts that hold the guard rails
/ tender: Dinghy for moving people and supplies to and from a ship
/ warp: A rope for warping or mooring a craft
]
)
== Common units
#figure(
table(
columns: (auto, auto, auto, auto),
[*Symbol*], [*Name*], [*SI conversion*], [*Definition*],
[_M, NM, nmi_], [nautical mile], [$1852m$], [one arc minute of latitude],
[], [cable length], [$185.2m$], [$1/10$ of a nautical mile],
[], [fathom], [$1.829m$], [$~1/100$ of a cable],
)
)
= Mooring
== Regional Differences
== Stern-to
Stern-to mooring is especially common in the Mediterranean. The boat is moored using two stern lines and one or two bow lines. In some countries, it is common for a "marinero" to assist mooring. In this case, it is not required for crew to step off.
The most common form of bow line is a "lazy line". These are lines which are attached to the pontoon on one end, and to a ring on the sea floor ahead of the bow on the other end. If no bow lines are available, an anchor needs to be used instead.
Since stern-to mooring usually implies that boats wil be moored right next to each other without being separated by a finger pontoon, fenders should be mounted at boat-height on both sides. There should be a strong emphasis on protecting the widest part of the boat. The quarter is usually less exposed than during side-to mooring. Additionally, a stern fender might be useful.
#figure(
image(
"res/mooring/stern-to-with-lazylines.svg",
height: 30%,
),
caption: [
Mooring stern-to with two lazy lines.
]
)
The ideal procedure for stern-to mooring involves several steps:
1. Motor backwards towards the quaywall. It is recommended to face astern to improve visibility. Once close enough to the pontoon, stop the boat with a short burst of forward power.
2. Attach two stern lines to cleats on the pontoon. This is done either by crew stepping off or by a marinero assisting the maneuver. The lines should be slightly longer than the desired final position of the boat (1m longer is a good starting value). As soon as the lines are attached, engage forward power to keep them under tension. This will prevent the bow from being pushed sideways.
3. Pick up the lazy lines which should be attached to the pontoon. This is usually done using the boat hook. There might only be one, but two is ideal. Walk the lazy line forward to the bow, making sure to keep the pontoon end slack, so it will not get pulled underneath the boat, fouling the propeller. Attach the lazy lines to the bow cleats, pulling the bow end as tight as possible.
4. Once lazy lines are attached, motor backwards to test whether they have good tension to hold the boat in the desired position. Take up the slack in the stern lines. The boat should now be tightly moored.
== Alongside
When mooring alongside to a finger pontoon or quay wall, put as many fenders as possible on the side that will face the pontoon. Make sure to use the adequate height for the pontoon. The quarter will be exposed, so make sure to protect it with a strong fender.
1. Prepare bow and stern lines using the respective cleats. Have the crew ready to step off near the shrouds. Make sure the lines are on the outside of the guardrails.
2. If approaching a single sideways pontoon or wall (e.g. the fuel pontoon), approach at roughly a $45 #sym.degree$ angle. Switch to neutral. When the bow is roughly a meter from the pontoon, steer hard over away from the pontoon. If you are uncomfortable with the size of the boat, have a crew member at the bow or shrouds announce the distance. The bow should turn away from the pontoon and the remaining momentum should be enough to slowly drift towards it.
3. Use a backwards burst to stop the boat. When next to pontoon and stopped, have crew step off and run bow and stern lines around the appropriate cleats.
4. Adjust both lines until in desired position. Affix bow and stern lines.
5. If at mooring for longer time and there is a risk of surging, add springs. There are two possible setups for this, depending on the cleat situation on the boat and pontoon/wall. The line running towards the bow and stopping the boat from surging forwards is defined as the bow spring.
#figure(
grid(
columns: (auto, auto),
image(
"res/mooring/alongside-a.svg",
height: 20%,
),
image(
"res/mooring/alongside-b.svg",
height: 20%,
)
),
caption: [
Mooring alongside with bow and stern lines as well as bow and stern springs. Springs can run either from amidships to pontoon cleats near the bow and stern, or from bow and stern cleats to a central cleat on the pontoon.
],
)
=== Using a Midship Line
This makes mooring alongside significantly easier and is recommended if the boat has a midship cleat.
1. Rig a warp to the midship cleat.
2. When next to the pontoon, have crew step off and attach the midship line first, cleating off immediately. This will keep the boat stopped and attached to the pontoon while finishing the maneouver.
3. Use the rudder and small amounts of power to pivot the boat around the midship line and align the bow in the desired position.
4. Finally, attach bow and stern lines as described above. If short-handed, prepare the bow and stern lines by festooning them over the guardrails. This way the crew that has stepped off can easily pick them up.
== Mooring buoy
1. Prepare two lines coming off the bow cleats.
2. Approach the buoy slowly. Keep it to the side the rope was prepared on. When the buoy is just off the bow, and the boat is stopped, lassoo it with the rope. Immediately cross the ends of the rope to avoid the buoy slipping away.
3. Pull up the buoy. Attach it using the second line and tie it off. If the buoy is itself attached to the sea bed using a line, it can be directly attached to the cleat too. (TODO verify)
4. Remove the first line.
== Anchoring
#pagebreak()
= Maneuvers
== Heaving to<heave_to>
#figure(
image(
"res/maneuvers/hove_to.svg",
width: 30%,
fit: "contain",
),
caption: [
A boat in a hove-to position. The jib is backed, pushing the bow to leeward. The rudder is set all the way to windward, pushing the bow up. If the boat falls off, the mainsail will power up and help push the bow back up.
]
)
== Man overboard recovery
=== Using Sail and Engine by Heaving To ("Crash-Tack")
@mob_sail_a shows how to recover a MOB using sails and engine.
#figure(
image(
"res/maneuvers/mob_sail_a.svg",
width: 50%,
fit: "contain",
),
caption: [
MOB recovery under sail with engine assistance.
]
)<mob_sail_a>
- *Step A* immediately after the MOB, change to a close-hauled course.
- *Step B* start the engine. After three boat lengths, heave to by tacking without changing the foresail over.
- *Step C* when hove to, the boat should be slowly drifting downwind towards the casualty. Use the engine to move forwards or backwards. Aim to keep the casualty near the shrouds.
#pagebreak()
= Navigation
== Pilotage
#figure(
grid(
columns: (20%, 20%),
image(
"res/fix/zone_diagram_ahead.svg",
width: 100%,
fit: "contain"
),
image(
"res/fix/zone_diagram_astern.svg",
width: 100%,
fit: "contain"
)
),
caption: [Diagrams indicating coloured sectors of a light house ahead (left) or astern (right).]
)
== Running fix
A running fix can be performed if only a single reference point is available. The geometry is shown in @running_fix.
- Step *A*: Take a true bearing #sym.alpha to the reference point. Take note of the log.
- Sail a steady course and take note of the true heading #sym.gamma. Wait until the bearing to the reference point has noticeably changed.
- Step *B*: Take another bearing #sym.beta to the reference point. Read off the log and calculate the distance traveled since the first reading $d$.
- Using the observed distance and heading, draw a vector starting from the reference point. If a reasonable guess can be made, you can apply leeway and tides to the vector. Draw the second bearing #sym.beta.
- Starting from the end of the vector, draw a line along the initial bearing #sym.alpha. The intersection of this line and the second bearing #sym.beta is the current position of the boat.
#figure(
image(
"res/fix/running_fix.svg",
width: 40%,
fit: "contain",
),
caption: [
Visualisation of a running fix. The red lines show the first and second bearing, and the course vector. The blue lines are parallel lines to the first bearing and course, which can be used to obtain an intersection with the second bearing line.
]
)<running_fix>
== Geographical Range of Lighthouses
#figure(
$s [M] = 2.075 * (sqrt(h_"eye" [m]) + sqrt(h_"light" [m]))$
)
= Radio
== Protocol
=== Hail
Hailing is done on channel 16.
#colorbox(
title: [Hail],
color: "black",
)[
/ Indefatigable: _Renown_, _Renown_, _Renown_, this is _Indefatigable_, _Indefatigable_, _Indefatigable_. Over.
/ Renown: _Indefatigable_, this is _Renown_. Over.
/ Indefatigable: _Renown_, this is _Indefatigable_. Channel 72 please. Channel seven two. Over.
/ Renown: _Indefatigable_, this is _Renown_. Understood. Channel 72. Over.
]
=== Distress (Mayday)
Should only be sent in case of grave an imminent danger to life or vessel. Use channel *16* on high power.
#colorbox(
title: [Distress call],
color: "black",
)[
Mayday Mayday Mayday \
This is _Indefatigable_ _Indefatigable_ _Indefatigable_ \
Call sign ABCD1 MMSI number 123456789 \
Mayday _Indefatigable_ \
Call sign ABCD1 MMSI number 123456789 \
My position is 12 degrees 34.56 minutes north, 012 degrees 34.56 minutes east. \
We are sinking. \
We require immediate assistance. \
There are 5 people on board. \
We are abandoning to the life raft. \
Over.
]
=== Urgency (Panpan)
Should be sent if the calling station has a very urgent message concerning the safety of a vessel or person. Must be addressed to someone (e.g. coast guard, or all stations).
#colorbox(
title: [Urgency call],
color: "black",
)[
Panpan Panpan Panpan \
All stations all stations all stations \
This is _Indefatigable_ _Indefatigable_ _Indefatigable_ \
Call sign ABCD1 MMSI number 123456789 \
My position is 12 degrees 34.56 minutes north, 012 degrees 34.56 minutes east. \
We have are adrift. \
We require a tow. \
There are 5 people on board. \
Over.
]
=== Safety (Securitay)
#colorbox(
title: [Safety call],
color: "black",
)[
Securitay Securitay Securitay \
All stations all stations all stations \
This is _Indefatigable_ _Indefatigable_ _Indefatigable_ \
Call sign ABCD1 MMSI number 123456789 \
My position is 12 degrees 34.56 minutes north, 012 degrees 34.56 minutes east. \
We have sighted a floating shipping container.
Over.
]
=== Specifying position
- Using coordinates: E.g. $12#sym.degree 34.56' N, 012#sym.degree 34.56' E$; read: _one two degrees three four decimal five six minutes north, zero one two degrees three four decimal fice six minutes east_
- Using a bearing: Read bearing from object, then distance. E.g. _one six one degrees from Punta Rasca, two decimal one miles_
== VHF (Very High Frequency)
VHF does not bend around obstacles. The horizon radius of a VHF antenna is approximately $r = 3 * sqrt(h)$, where $r$ is the horizon in nautical miles and $h$ is the height of the antenna in metres.
Two antennas are in range of each other if their horizons overlap. Thus, the total range is approximately $r_(a+b) = 3 * (sqrt(h_a) + sqrt(h_b))$.
High power is usually $25 W$ on a VHF built into the boat. Low power is usually $1 W$.
=== Channels
- Distress, safety and calling: *16*
- Inter-ship: *6*, *8*, *72*, *77*
- Port operations: *11*, *12*, *14*
= Tides
== Tidal heights
=== Secondary ports
Tide tables aren't always available for every port. For secondary ports, the times and heights of high water and low water can be obtained by applying a correction to those of the primary port.
The time of high/low water at the secondarty port $t_P$ is thus given as $t_P = t_S + Delta t$, where $t_S$ is the time at the standard port and $Delta t$ is the correction.
These corrections are usually supplied as two values that apply at $0000, 1200$ and $0600, 1800$.
#figure(
table(
columns: (auto, auto),
[*Times [hhmm]*], [*Height [m]*],
table(
columns: (auto, auto),
stroke: none,
[High water (HW)], [Low water (LW)],
table(
columns: (40pt, 40pt),
[0000], [0600],
[1200], [1800],
),
table(
columns: (40pt, 40pt),
[0000], [0600],
[1200], [1800],
),
),
table(
columns: auto,
rows: auto,
stroke: none,
table(
columns: (40pt, 40pt, 40pt, 40pt),
stroke: none,
[MHWS], [MHWN], [MLWN], [MLWS],
),
table(
columns: (40pt, 40pt, 40pt, 40pt),
[4.8], [3.9], [1.4], [0.5],
),
),
table(
columns: (auto, auto),
stroke: none,
align: left,
[Differences ($Delta t$)], [],
table(
columns: (40pt, 40pt),
align: center,
[-0052], [-0002],
),
table(
columns: (40pt, 40pt),
align: center,
[-0052], [-0002],
),
),
table(
columns: (auto),
stroke: none,
align: left,
[Differences ($Delta h$)],
table(
columns: (40pt, 40pt, 40pt, 40pt),
align: center,
[+1.8], [+0.6], [-0.3], [+0.1],
),
),
)
)
Values in between the explicitly stated times must be acquired through linear interpolation. Thus, the formula for caluclating the correction $Delta t$ for any given high water time in the standard port $t_S$ is as follows:
#figure(
$Delta t = Delta t_1 + frac((t_S - t_1), (t_2 - t_1)) (Delta t_2 - Delta t_1)$
)
where $Delta t_1$ is the correction at the start of the window (obtained from the table) and $Delta t_2$ is the correction at the end of the window (also obtained from the table).
Thus, the time of high/low water at the secondary port is obtained as follows:
#figure(
$t_P = t_S + Delta t_1 + frac((t_S - t_1), (t_2 - t_1)) (Delta t_2 - Delta t_1)$
)
The height of high water or low water at the secondary port $H_P$ can be determined in a similar fashion, by interpolating between the mean springs and neaps values.
#figure(
$h_P = h_S + Delta h_"springs" + frac((h_S - h_"springs"), (h_"neaps" - h_"springs")) (Delta h_"neaps" - Delta h_"springs")$
)
== Tidal streams
=== Course to steer
The diagram for working out CTS and SOG based on tidal set and drift, as well as a desired COG and an estimated boat STW, constitutes a triangle which is not guaranteed to have a right angle. Thus, we cannot use plain trigonometric identities to perform this calculation.
$
& theta_"COG" &&= "COG (course over groud), known" \
& theta_"CTS" &&= "CTS (course to steer), unknown" \
& theta_"tide" &&= "Tidal set, known" \
& v_"SOG" &&= "SOG (speed over groud) [kn], unknown" \
& v_"STW" &&= "STW (speed through the water) [kn], known" \
& v_"tide" &&= "Tidal drift [kn], known"
$
#figure(
image(
"res/tides/course_to_steer.svg",
width: 70%,
fit: "contain",
),
caption: [
Vector diagram used to determine course to steer ($"CTS"$).
]
)<cts>
@cts demonstrates that that $alpha = theta_"COG" - theta_"tide"$ and $gamma = theta_"CTS" - theta_"COG"$.
We can make use of the sine and cosine rules to calculate the course to steer.
Remember to set the calculator to degree mode, unless you fancy instructing your helm using a course measured in radians.
#figure(
$
sin(alpha)/a = sin(beta)/b = sin(gamma)/c & "(sine rule)" \
a^2 = b^2 + c^2 - 2 b c cos(alpha) & "(cosine rule)" \
alpha + beta + gamma = 180 degree & "(sum of angles)"
$,
)
By applying the sine rule, it follows that
#figure(
$
theta_"CTS" &= theta_"COG" + gamma \
&= theta_"COG" + arcsin(v_"tide" / v_"STW" sin(theta_"COG" - theta_"tide"))
$
)
Working out the expected SOG is more complicated.
By applying the sum of angles rule for triangles and the cosine rule we end up with the following.
#figure(
$
beta &= 180 degree - alpha - gamma \
&= 180 degree - (theta_"COG" - theta_"tide") - arcsin(v_"tide" / v_"STW" sin(theta_"COG" - theta_"tide")) \
"SOG" &= sqrt(v_"STW"^2 + v_"tide"^2 - 2 v_"STW" v_"drift" cos(beta)) \
&= sqrt(v_"STW"^2 + v_"tide"^2 - 2 v_"STW" v_"drift" cos(180 degree - alpha - gamma)) \
&= sqrt(v_"STW"^2 + v_"tide"^2 - 2 v_"STW" v_"drift" cos(180 degree - alpha - gamma))
$
)
=== Estimated position
For calculating the estimated position, we can add the vectors of the tidal drift and set, as well as the boat speed and course through the water, to obtain an estimated course and speed over the ground.
This is mathematically possible using simple trigonometry and linear alegbra. However, this one might actually be much more useful to draw out on the map.
We must first convert our vectors from polar to cartesian form. In the following example, we use the first dimension `x` to represent longitude and `y` to represent latitude, which is the definition of a cartesian plane. This can be a bit confusing, given that it is the norm to specify coordinates in the transposed Lat-Lon form.
Given a vector $accent(a, arrow) = d angle theta$, where $0 degree < theta <= 360 degree$, we can calculate the cartesian form as follows:
$ vec(x, y) = vec(d cos(theta), d sin(theta)) $
Converting back into polar form is painful. There is a $"arctan2"$ function available in many maths libraries that takes care of computing the below formula for the correct quadrant, but this is not present on most calculators.
$
theta &= arctan(y/x) + cases(
0 degree &"if" x >= 0 and y >= 0 \
360 degree &"if" x < 0 and y >= 0 \
180 degree &"if" y < 0
) \
d &= sqrt(x^2 + y^2)
$
= Morse code
- The length of a dot is one unit.
- A dash is three units.
- The space between parts of the same latter is one unit.
- The space between letters is three units.
- The space between words is seven units.
#figure(
table(
columns: (auto, auto, auto),
align: left,
stroke: none,
table(
columns: (auto, auto),
[*Symbol*], [*Sequence*],
[A], [·− ],
[B], [−··· ],
[C], [−·−· ],
[D], [−·· ],
[E], [· ],
[F], [··−· ],
[G], [−−· ],
[H], [···· ],
[I], [·· ],
[J], [·−−− ],
[K], [−·− ],
[L], [·−·· ],
[M], [−− ],
),
table(
columns: (auto, auto),
[*Symbol*], [*Sequence*],
[N], [−· ],
[O], [−−− ],
[P], [·−−· ],
[Q], [−−·− ],
[R], [·−· ],
[S], [··· ],
[T], [− ],
[U], [··− ],
[V], [···− ],
[W], [·−− ],
[X], [−··− ],
[Y], [−·−− ],
[Z], [−−·· ],
),
table(
columns: (auto, auto),
[*Symbol*], [*Sequence*],
[1], [·−−−−],
[2], [··−−−],
[3], [···−−],
[4], [····−],
[5], [·····],
[6], [−····],
[7], [−−···],
[8], [−−−··],
[9], [−−−−·],
[0], [−−−−−],
),
),
caption: [International Morse Code sequences]
)
= Flags
Flags are said to be _worn_ by the yacht and _flown_ by the owner.
The ideal flag size for a boat is dependent on its size. The ensign size should be roughly one inch for each foot of overall length. For other flags, it should be $1/2$ an inch for each foot of the highest mast above water.
== ICS International Maritime Flags
#figure(
table(
columns: (auto, auto, auto),
stroke: none,
table(
columns: (35pt, auto, auto),
rows: 35pt,
align: left+horizon,
image("res/flags/ICS_Alfa.svg"),[*A* - Alpha],[I have a diver down, keep clear],
image("res/flags/ICS_Bravo.svg"),[*B* - Bravo],[I am carrying dangerous goods],
image("res/flags/ICS_Charlie.svg"),[*C* - Charlie],[Affirmative],
image("res/flags/ICS_Delta.svg"),[*D* - Delta],[I am manouvering with difficulty, keep clear],
image("res/flags/ICS_Echo.svg"),[*E* - Echo],[I am altering course to starboard],
image("res/flags/ICS_Foxtrot.svg"),[*F* - Foxtrot],[I am disabled, communicate with me],
image("res/flags/ICS_Golf.svg"),[*G* - Golf],[I require a pilot],
image("res/flags/ICS_Hotel.svg"),[*H* - Hotel],[I have a pilot on board],
image("res/flags/ICS_India.svg"),[*I* - India],[I am altering course to port],
image("res/flags/ICS_Juliett.svg"),[*J* - Juliet],[I am on fire or leaking dangerous cargo],
image("res/flags/ICS_Kilo.svg"),[*K* - Kilo],[I wish to communicate],
image("res/flags/ICS_Lima.svg"),[*L* - Lima],[Stop your vessel instantly],
image("res/flags/ICS_Mike.svg"),[*M* - Mike],[I am stopped and not making way],
image("res/flags/ICS_November.svg"),[*N* - November],[Negative],
image("res/flags/ICS_Oscar.svg"),[*O* - Oscar],[Man overboard],
image("res/flags/ICS_Papa.svg"),[*P* - Papa],[I am about to sail, all report on board],
image("res/flags/ICS_Quebec.svg"),[*Q* - Quebec],[Vessel is healthy, request pratique],
image("res/flags/ICS_Romeo.svg"),[*R* - Romeo],[],
),
table(
columns: (55pt, auto, auto),
rows: 35pt,
align: left+horizon,
image("res/flags/ICS_Sierra.svg"),[*S* - Sierra],[I am operating astern propulsion],
image("res/flags/ICS_Tango.svg"),[*T* - Tango],[Keep clear of me],
image("res/flags/ICS_Uniform.svg"),[*U* - Uniform],[You are running into danger],
image("res/flags/ICS_Victor.svg"),[*V* - Victor],[I require assistance],
image("res/flags/ICS_Whiskey.svg"),[*W* - Whiskey],[I require medical assistance],
image("res/flags/ICS_X-ray.svg"),[*X* - X-ray],[Stop and watch for my signals],
image("res/flags/ICS_Yankee.svg"),[*Y* - Yankee],[I am dragging my anchor],
image("res/flags/ICS_Zulu.svg"),[*Z* - Zulu],[I require a tug],
image("res/flags/ICS_Pennant_Zero.svg"),[*0* - Zee-ro],[],
image("res/flags/ICS_Pennant_One.svg"),[*1* - Wun],[],
image("res/flags/ICS_Pennant_Two.svg"),[*2* - Too],[],
image("res/flags/ICS_Pennant_Three.svg"),[*3* - Tree],[],
image("res/flags/ICS_Pennant_Four.svg"),[*4* - Fow-er],[],
image("res/flags/ICS_Pennant_Five.svg"),[*5* - Fife],[],
image("res/flags/ICS_Pennant_Six.svg"),[*6* - Six],[],
image("res/flags/ICS_Pennant_Seven.svg"),[*7* - Sev-en],[],
image("res/flags/ICS_Pennant_Eight.svg"),[*8* - Ait],[],
image("res/flags/ICS_Pennant_Niner.svg"),[*9* - Nin-er],[],
),
),
caption: [ICS International maritime signal flags]
)
#pagebreak()
== Flag setup and etiquette
#columns(2)[
#figure(
image(
"res/flags/setup.svg",
width: 80%,
fit: "contain",
),
caption: [
Setup of flags excluding ensign
]
)
- *1* - Courtesy flag at highest position on starboard spreader
- *2* - Signal flags below courtesy flag (Q Flag)
- *3* - Custom flags, burgees and pennants on port spreader (below courtesy flag)
]
=== Ensign
Ensigns are mandatory for all vessels and signify the country of registration. The ensign should be flown at all times when outside of port (TODO). It is to be flown at the most privileged position on the boat, i.e. as close to the stern as possible.
When in port, the ensign is traditionally hoisted at 09:00 in winter and 08:00 in summer, and lowered at 21:00. However, this tradition is hardly followed anymore.
=== Courtesy flag
When in the waters of a different country to the one the boat is registered in, host country's flag must be hoisted. This is called the courtesy flag. It is to be hoisted on the starbord spreader and should be higher than the ensign and other flags.
= Weather
== Wind
=== The Beaufort Scale (UKMO)
#table(
columns: 8,
table.header([*Beaufort*], [*Mean wind speed [kn]*], [*Limits of wind speed [kn]*], [*Description*], [*Probable mean wave height [m]*], [*Probable maximum wave height [m]*], [*Sea state*], [*Sea description*]),
[*0*], [0], [$<1$], [Calm], [-], [-], [0], [Calm (glassy)],
[*1*], [2], [$1-3$], [Light air], [0.1], [0.1], [1], [Calm (rippled)],
[*2*], [5], [$4-6$], [Light breeze], [0.2], [0.3], [2], [Smooth (wavelets)],
[*3*], [9], [$7-10$], [Gentle breeze], [0.6], [1.0], [3], [Slight],
[*4*], [13], [$11-16$], [Moderate breeze], [1.0], [1.5], [$3-4$], [Slight-Moderate],
[*5*], [19], [$17-21$], [Fresh breeze], [2.0], [2.5], [4], [Moderate],
[*6*], [24], [$22-27$], [Strong breeze], [3.0], [4.0], [5], [Rough],
[*7*], [30], [$28-33$], [Near gale], [4.0], [5.5], [$5-6$], [Rough-Very rough],
[*8*], [37], [$34-40$], [Gale], [5.5], [7.5], [$6-7$], [Very rough-High],
[*9*], [44], [$41-47$], [Strong gale], [7.0], [10.0], [7], [High],
[*10*], [52], [$48-55$], [Storm], [9.0], [12.5], [8], [Very high],
[*11*], [60], [$56-63$], [Violent storm], [11.5], [16], [8], [Very high],
[*12*], [-], [$>64$], [Hurricane], [$>14$], [-], [9], [Phenomenal],
)
=== Reefing suggestions
#table(
columns: 4,
table.header([*Beaufort*], [*Conditions*], [*Main*], [*Fore*]),
[0], [Drifting or under engine], [Stowed or possibly full to steady yacht's motion.], [Furled],
[1], [Drifting or under engine, possibly motor-sailing], [Stowed or possibly full to steady yacht's motion.], [Furled if motor-sailing, else fully out],
[2], [Able to sail if fair tide], [Full], [Full],
[3], [Calm, gentle sailing], [Full], [Full],
[4], [Sails fully powered, good sailing], [Full, possibly one reef], [Full, possibly slightly furled],
[5], [Berthing more difficult, inexperienced crew might get nervous], [Reef one], [Possibly slightly furled],
[6], [Challenging conditions, consider seeking shelter], [Reef one or two], [$1/3$ furled away],
[7], [Unpleasant in unsheltered waters, limit for inexperienced skippers], [Reef two or three], [$2/3$ furled away],
[8], [Potentially dangerous outside sheltered waters if inexperienced. Upwind sailing difficult.], [Reef three or tri-sail], [mostly furled away or storm-jib],
[9], [Dangerous, seek shelter], [Reef three or tri-sail], [storm-jib],
[10], [Survival conditions, upwind sailing impossible], [tri-sail or none], [storm-jib],
)
== Swell
A wave can capsize the boat if it is higher than $1/3$ of the boat length, is a breaking wave, and reaches the boat abeam.
== Marine forecast glossary
#columns(
2,
[
=== Time
/ Imminent: $<6h$ from issue time
/ Soon: $6h-12h$ from issue time
/ Later: $>12h$ from issue time
=== Gale warnings
/ Gale: Winds of at least F8
/ Severe gale: Winds of at least F9
/ Storm: Winds of at least F10
/ Violent storm: Winds of at least F11
/ Hurricane force: Winds of at least F12
=== Visibility
/ Very poor: $<1000m$
/ Poor: $1000m-2M$
/ Moderate: $2M-5M$
/ Good: $>5M$
=== Sea state
/ Smooth: Wave height $<0.5m$
/ Slight: Wave height $0.5m-1.25m$
/ Moderate: Wave height $1.25m-2.5m$
/ Rough: Wave height $2.5m-4.0m$
/ Very rough: Wave height $4.0m-6.0m$
/ High: Wave height $6.0m-9.0m$
/ Very high: Wave height $9.0m-14.0m$
/ Phenomenal: Wave height $>14.0m$
=== Wind
/ Becoming cyclonic: Considerable direction change across the path of a depression
/ Veering: Turning clockwise
/ Backing: Turning anticlockwise
=== Movement of pressure systems
/ Slowly: $<15"kn"$
/ Steadily: $15"kn"-25"kn"$
/ Rather quickly: $25"kn"-35"kn"$
/ Rapidly: $35"kn"-45"kn"$
/ Very rapidly: $>45"kn"$
]
)
= Boat knowledge
== Rigs and sails
=== Sails
- Mainsail
- Headsail
=== Rigs
#table(
columns: (auto, auto, auto),
rows: 140pt,
align: horizon,
image("res/rigs/sloop.svg"), [*Sloop*], [Main mast ahead of 40-60 point. Usually one jib or genoa.],
image("res/rigs/cutter.svg"), [*Cutter*], [Main mast behind 40-60 point. Two headsails (yankee and staysail). Not to be confused with Solent rig.],
image("res/rigs/ketch.svg"), [*Ketch*], [Mizzen mast ahead of the rudder post. Mizzen mast and main mast connected using a stay.],
image("res/rigs/yawl.svg"), [*Yawl*], [Mizzen mast astern of the rudder post. Mizzen mast stands on its own and is often only used for steering.]
)
== The Engine
A well-maintained diesel engine will burn roughly $0.22 l / ("hp" h)$. E.g. a $100 "hp"$ engine will burn $22 l/h$.
Power is roughly proportional to the cube of the shaft speed. It follows that fuel consumption based on revs and engine power can be described as follows:
#figure(
$x [l/h] = 0.22 * (P_"max" ["hp"]) * (f_"current" / f_"max")^3$
)
A $100 "hp"$ engine at $80%$ RPM will develop rougly $50 "hp"$, consuming about $11 l/h$ of diesel.
The vessel's hull speed can be described as follows:
#figure(
$v_"hull" ["kn"] = 1.34 * sqrt(s_"LWL" ["ft"])$
)
Efficient crusing speed tends to be around $70% - 80%$ of the hull speed, but varies from vessel to vessel.
= Passage Planning
== Appraisal
- Vessel information (name, class, seaworthiness, draught, stability, range, callsign, MMSI)
- Crew (size, experience, preferences, condition)
- Charts, almanac, other relevant publications
== Planning
- Date/time
- Estimated duration, distance
- Weather and environmental conditions
- Sunrise and sunset
- Route and waypoints
- Dangers and restrictions along the route
- Tidal depths
- Method and frequency of position fixing
- Ports of refuge and contingency plans
== Execution
Prior to execution:
- Condition of navigation equipment
- ETAs at critical points
- Weather forecast
== Monitoring
- Fixes
- Weather changes
= Checklists
== Boat preparation
=== Ready for sea
#columns(2)[
- Below deck
- Passage planning
- Start boat log
- Instruments and VHF on
- Gear stowed, everything in shipshape
- Hatches closed
- Engine check (@engine_check)
- Lockers shut & locked
- Victualling
- Navigation lights at night
- Tools and spares
- Status of batteries
- Gas shut off
- Relevant charts and pilotage notes accessible
- Above deck
- Winch handles on deck
- Hand-bearing compasses on deck
- Instrument covers off and stowed below
- Disconnect shore power
- Remove sail cover
- Prepare main halyard
- Life jackets
- Fill water tanks
- Fill engine tank
- Ensign (and courtesy flag)
]
=== Engine check <engine_check>
- *W* ater tank should have sufficient water.
- *O* ngine oil should be within markers. Wipe down oil indicator before performing test.
- *B* elt. Should be just stiff enough to turn roughly 90 degrees.
- *B* ilges. Check for water or oil leaks.
- *L* ook around. Does anything look off?
- *E* xhaust. When starting the engine, check for water exhaust.
== Safety
=== Short safety brief: Three Fs
- Fire
- Gas
- Flooding
- Location of bilge pump
- Falling overboard
- Life vests
- Harnesses
#pagebreak()
=== Full safety brief
#columns(2)[
==== Below deck
- Gas
- Heavier than air
- Location and usage of stopcocks
- Location of gas bottles
- Routine for gas spillage
- Gas sensors and alarm
- Manual bilge pump location
- Fire prevention
- No smoking
- Never leave hob unattended
- Turn off gas at stopcock
- Fire extinguishers
- Locations
- Types
- Fire blanket
- Engine fire
- First aid box
- Everyday box
- Cat C box
- Heads and shower pump
- Operating procedure
- Provisioning/victualling
- Sea cocks
- Location
- Presence of bungs
- Engine
- WOBBLE (@engine_check)
- Galley
- Always wear strong bottoms when cooking at sea
- Galley strap
- Always clean spillages right away
- Only half-fill mugs in half water
- Pour boiling water into mugs over the sink
- Put kettle spout on fore-aft line
- Life jackets and life lines
- Location
- Assign one to each crew member and make sure they fit
- Check $"CO"_2$ canister and green tags
- Light, spray hood and whistle
- When to wear
- Clip on points and jackstays, never guard rails
- Clip in before exiting companionway and after entering
- Flares
- Location
- Types
- When and how to use
- Check expiry dates
- Emergency VHF aerial location
- VHF
- Basic operation (on/off, squelch, channels, push-to-talk)
- Mayday call procedure (check instruction poster)
- Location and battery charge of handheld radio
- Control panel switches
- Nav and cabin lights
- Water tank and battery indicators
- GPS
- VHF
- Fridge
- Bilge pump
- Battery isolators
- Shore power
- GPS, plotter and port navigation
- MOB button
==== Above deck
- Heaving line
- Lifebelt, drogues and danbuoy
- Liferaft
- Securing points, check painter
- When to launch
- How to launch
- Abandon ship routine
- Lifejackets
- Mayday
- Bring flares, handheld VHF, EPIRB, grab-bag, water
- Engine
- Batteries
- How to start and stop
- Slips, falls, other dangers
- One hand for yourself, one for the boat
- Step off, don not jump onto pontoon
- Danger of boom
- Do not fend off using body parts
- Winch and line safety
- Winch and jammer operation
- Never release a jammer without having at least one turn around the winch
- Keep fingers clear of winch
- Winch handle location
]
== Customs
=== Documents
- Vessel
- Ship registration
- VAT invoice
- Insurance certificate
- Radio licence
- Life-raft service certificate
- Skipper
- Skipper licence (e.g. ICC)
- VHF licence
- Everyone
- Passports
- Visas
- EHIC
- Form C1331
= Appendix
|
https://github.com/Airsequel/interpreted-languages-benchmark | https://raw.githubusercontent.com/Airsequel/interpreted-languages-benchmark/main/readme.md | markdown | # Interpreted Languages Benchmark
Benchmark for interpreted languages.

The values for Rust, V, and Haskell are not really representative
as they are compiled on the first run
and Haskell unfortunately does not even cache the compiled binary.
## Languages
- [Bash]
- [Bun]
- [Dart]
- [Dash]
- [Elixir]
- [Elvish]
- [F#]
- [Fish]
- [Guile]
- [Haskell]
- JavaScript via
- [Node.js]
- [Deno]
- [Bun]
- [Julia]
- [Ksh]
- [Lua]
- [Lua]
- [Nickel]
- [Nix Language]
- [Nushell]
- [OCaml]
- [Osh]
- [Perl]
- [PHP]
- TypeScript via
- [Deno]
- [Bun]
- [Python]
- [Python]
- [Racket]
- [Roc.roc]
- [Ruby]
- [Scala]
- [Swift]
- [Typst]
- [V]
[Bash]: https://www.gnu.org/software/bash/
[Bun]: https://bun.sh/
[Dart]: https://dart.dev/
[Dash]: https://wiki.archlinux.org/title/Dash
[Deno]: https://deno.com/
[Elixir]: https://elixir-lang.org/
[Elvish]: https://elv.sh/
[F#]: https://fsharp.org/
[Fish]: https://fishshell.com/
[Guile]: https://www.gnu.org/software/guile/
[Haskell]: https://www.haskell.org/
[Julia]: https://julialang.org/
[Ksh]: https://www.kornshell.com/
[Lua]: https://www.lua.org/
[Nickel]: https://nickel-lang.org/
[Nix Language]: https://nixos.org/manual/nix/stable/language/
[Node.js]: https://nodejs.org/
[Nushell]: https://www.nushell.sh/
[OCaml]: https://ocaml.org/
[Osh]: https://www.oilshell.org/
[Perl]: https://www.perl.org/
[PHP]: https://www.php.net/
[Python]: https://www.python.org/
[Racket]: https://racket-lang.org/
[Roc.roc]: https://roc-lang.org/
[Ruby]: https://www.ruby-lang.org/
[Scala]: https://www.scala-lang.org/
[Swift]: https://swift.org/
[Typst]: https://typst.app/docs/
[V]: https://vlang.io/
### Workarounds
- [Typst] \
Can only output a JSON string.
Use `… | jq -r` to remove the quotes.
## Result
Check out the workflow runs for the latest benchmark results.
### GitHub's MacOS 14 Runner
#### Bucket Calc
```txt
lua bucket-calc/main.lua ran
2.96 ± 3.97 times faster than nickel export bucket-calc/main.ncl
3.05 ± 3.98 times faster than bun run bucket-calc/main.js
3.09 ± 4.07 times faster than bun run bucket-calc/main.ts
4.71 ± 5.77 times faster than python3 bucket-calc/main.py
4.76 ± 5.83 times faster than deno run bucket-calc/main.ts
4.80 ± 5.91 times faster than deno run bucket-calc/main.js
8.56 ± 10.56 times faster than node bucket-calc/main.js
24.21 ± 29.52 times faster than
typst query --field=text --one bucket-calc/main.typ
```
#### Shebang Scripts
```txt
./luajit ran
1.06 ± 0.22 times faster than ./lua
1.61 ± 0.27 times faster than ./bash
1.62 ± 0.29 times faster than ./dash
2.12 ± 0.49 times faster than ./ksh
2.66 ± 0.55 times faster than ./osh
3.77 ± 0.63 times faster than ./elvish
3.91 ± 0.67 times faster than ./v.vsh
4.92 ± 0.82 times faster than ./fish
6.16 ± 1.02 times faster than ./bun
9.65 ± 1.72 times faster than ./guile
13.94 ± 2.29 times faster than ./python
14.20 ± 2.39 times faster than ./nushell
17.43 ± 2.86 times faster than ./php
23.01 ± 3.94 times faster than ./ocaml
35.43 ± 5.99 times faster than ./ruby
52.94 ± 9.08 times faster than ./racket
56.77 ± 9.59 times faster than ./perl
89.13 ± 14.62 times faster than ./dart
106.23 ± 18.77 times faster than ./swift
143.96 ± 24.03 times faster than ./julia
199.84 ± 33.40 times faster than ./roc.roc
224.83 ± 47.56 times faster than ./elixir
483.43 ± 87.95 times faster than ./haskell
507.16 ± 114.14 times faster than ./scala
528.19 ± 94.47 times faster than ./fsharp.fsx
```
## Related
- [jinyus/related_post_gen] - Data Processing benchmark
- [plb2] - A programming language benchmark
- [Programming-Language-Benchmarks][PLB]
- [script-bench-rs] - Rust embedded scripting languages benchmark
[jinyus/related_post_gen]: https://github.com/jinyus/related_post_gen
[PLB]: https://github.com/hanabi1224/Programming-Language-Benchmarks
[plb2]: https://github.com/attractivechaos/plb2
[script-bench-rs]: https://github.com/khvzak/script-bench-rs
|
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/linear/pset1.typ | typst | #import "template.typ": *
#show: template.with(
title: "Typst",
subtitle: "<NAME>",
pset: true,
)
- $sum_(i=0)^20$
Collaborators: <NAME>
= 1.1 (4)
#bimg("4.png")
= 1.1 (14)
#set enum(numbering: "a.")
+ The sum of twelve vectors is $boxed(0)$ because for each vector there is an opposite negative vector that cancels it out, for example the 2:00 vector is cancelled out by the 8:00 vector.
+ Similar to above, since nothing cancels 8:00 out but all other vectors cancel each other out, the result will be the 8:00 vector.
+ $boxed(theta = 30 degree)$
= 1.1 (24)
+ *Corners*: $2^4 = boxed(16)$
+ *Volume*: $2^4 = boxed(16)$
+ *3D-Faces*: $2 dot n = boxed(8)$
+ *Edges*: Each vertex has $4$ possible edges, and each edge is overcounted twice, so there are $(16 dot 4) / 2 = boxed(32)$ edges.
+ *Example Edge*: $(-1, -1, -1, -1)$ to $(-1, -1, -1, 1)$
= 1.2 (1)
- $bold(u) dot bold(v) = boxed(0)$
- $bold(u) dot bold(w) = boxed(1)$
- $bold(u) dot (bold(v) + bold(w)) = boxed(1)$
- $bold(w) dot bold(v) = boxed(10)$
= 1.2 (2)
- $||u|| = boxed(1)$
- $||v|| = boxed(5)$
- $||w|| = boxed(sqrt(5))$
Schwarz Inequalities
- $boxed(0 <= 5)$
- $boxed(10 <= 5 dot sqrt(5))$
= 1.2 (24)
Suppose our sides are of length $x, y, a, b$. Now say that we have one side of the parallelogram $bold(v) = (a, b)$ and the other side $bold(w) = (x, y)$. Then we have that $c = (v + w) = (a+x, b+y)$ and $d = (v - w) = (a-x, b-y)$.
The squared diagonal lengths are:
- $||bold(c)||^2 = a^2 + 2a x + x^2 + b^2 + 2b y + y^2$
- $||bold(d)||^2 = a^2 - 2a x + x^2 + b^2 - 2b y + y^2$
Thus we have that $||bold(v) + bold(w)||^2 + ||bold(v) + bold(w)||^2 = boxed(2a^2 + 2x^2 + 2b^2 + 2y^2)$
Now let us calculate the sum of the four squared side lengths:
$
2||bold(v)||^2 + 2||bold(w)||^2&=\
&= 2(a, b)^2 + 2(x, y)^2\
&= 2(a^2+b^2+x^2+y^2)\
&= boxed(2a^2 + 2x^2 + 2b^2 + 2y^2)
$
Thus the two results are equal and we have shown the squared diagonal lengths are equal to the sum of the four squared side lengths.
= 1.3 (8)
- $A$: All of $boxed(bb(R)^3)$
- $B$: Since they are multiples of each other, it describes a line $boxed(bb(R)^1)$.
- $C$: Because there is no set of three vectors that are linearly independent, it describes $boxed(bb(R)^2)$, since two of them are linearly independent.
= 1.3 (17)
#let bbx(x) = box(outset: (y: 200pt))[$#x$]
- *Rank 0* $A = bbx(vec(1, 1)), B = vec(-1, -1), A + B = vec(0, 0)$
- *Rank 1* $A = vec(1, 1), B = vec(1, 1), A + B = vec(2, 2)$
- *Rank 2* $A = mat(1, 1; 1, 1), B = mat(2, 4; 3, 6), A + B = mat(3, 5; 4, 7)$
Imagine that $A$ and $B$ are infinite lines. The matrices $A$ and $B$ simply contain possible vectors in that infinite line. Therefore, the columns of of $A+B$ must all be vectors that lie in the plane defined by these infinite lines. Thus, if all columns of $A+B$ lie in the same plane, it is impossible for the rank to be greater than 2.
= 1.3 (21)
$
y_1 &= boxed(c_1)\
y_1 + y_2 &= c_2\
y_1 + y_2 + y_3 &= c_3\
y_2 &= boxed(c_2 - c_1)\
y_3 &= boxed(c_3 - c_2)
$
$
boxed(A dot c = vec(c_1, c_2-c_1, c_3-c_2))
$
The columns of $S$ are independent because no pair are dependent. In addition, the inverse matrix exists, which means that the matrix is independent.
= 1.4 (3)
== First Case
$
boxed(mat(1, 0, 0; 0, 1, 0; 1, 0, 1))
$
== Second Case
$ boxed(mat(32)) $
== Third Case
$ boxed(mat(4, 8, 12; 5, 10, 15; 6, 12, 18)) $
= 1.4 (14)
== Rank One
$ boxed(mat(3, 6; 5, 10)) $
== Orthogonal
$ boxed(mat(6, 7; 7, -6)) $
== Rank 2
$ boxed(mat(2, 0; 3, 6)) $
== Identity
$ boxed(mat(3, 4; -2, -3)) $
= 1.4 (17)
== a
$
A = mat(1, 2, 3; 1, 2, 3;1, 2, 3)\
B = mat(1, 1, 1;1, 1, 1;-1,-1,-1)
$
In the above case, the matrix $A B$ is zeroed out, and so the rank is $boxed(0)$
#boxed("False")
== b
If $A$ and $B$ have rank 3, then it must be the case that there is no such $A x$ or $B x$ where $x$ is a non-zero vector and the result is of the multiplication is zero. That is, they are linearly independent. If $A B$ were not rank 3, then $A B x$ must have a non-zero solution that equals zero. However, we know that there is no $B x$ such that it is equal to zero, and same for $A x$, so it is impossible for the rank to be anything but 3.
#boxed("True")
== c
Let us find some $B$s such that they impose restrictions on $A$. Suppose $A = mat(a, b; c, d)$
$
B &= mat(1, 0; 0, 0)\
A B &= mat(a, 0; c, 0)\
B A &= mat(a, b; 0, 0)\
mat(a, 0; c, 0) &= mat(a, b; 0, 0)\
$
We learn that it must be the case that $a=a$ (trivial) and that $b, c=0$
$
B &= mat(0, 1; 0, 0)\
A B &= mat(0, a; 0, c)\
B A &= mat(c, d; 0, 0)\
mat(0, a; 0, c) &= mat(c, d; 0, 0)\
$
We learn that it must be the case that $c=0$ and that $a=d$
Thus we have arrived with these conditions that $A = mat(c, 0; 0, c)=c I$. It is impossible to impose more restrictions on $A$ since any other conditions without $0$ would have unresolvable equations. Thus, only these matrices of $A$ can commute with every $B$
#boxed("True")
|
|
https://github.com/tingerrr/anti-matter | https://raw.githubusercontent.com/tingerrr/anti-matter/main/docs/template.typ | typst | MIT License | // Modified version of https://github.com/Mc-Zen/tidy/blob/abedd7abbb7f072e67ef95867e3b89c0db987441/docs/template.typ
// 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(
package: (:),
subtitle: "",
abstract: [],
date: none,
body,
) = {
// Set the document's basic properties.
set document(author: package.authors, title: package.name)
set text(font: "Linux Libertine", lang: "en")
show heading.where(level: 1): it => block(smallcaps(it), below: 1em)
set heading(numbering: (..args) => if args.pos().len() == 1 { numbering("I", ..args) })
// show link: set text(fill: purple.darken(30%))
show link: set text(fill: rgb("#1e8f6f"))
v(4em)
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, package.name))
#block(text(1.0em, subtitle))
#v(4em, weak: true)
v#package.version #h(1.2cm) #date
#block(link(package.repository))
#v(1.5em, weak: true)
]
// Author information.
pad(
top: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, package.authors.len()),
gutter: 1em,
..package.authors.map(author => align(center, strong(author))),
),
)
v(3cm, weak: true)
// Abstract.
pad(
x: 3.8em,
top: 1em,
bottom: 1.1em,
align(center)[
#heading(
outlined: false,
numbering: none,
text(0.85em, smallcaps[Abstract]),
)
#abstract
],
)
set page(numbering: "1", number-align: center)
counter(page).update(1)
// Main body.
set par(justify: true)
v(10em)
body
}
|
https://github.com/mohe2015/not-tudabeamer-2023 | https://raw.githubusercontent.com/mohe2015/not-tudabeamer-2023/main/README.md | markdown | The Unlicense | # not-tudabeamer-2023
A [touying](https://github.com/touying-typ/touying) presentation template matching the TU Darmstadt Beamer Template 2023.
## Usage
Install Roboto font for your system or download them from https://github.com/googlefonts/roboto/releases/download/v2.138/roboto-unhinted.zip.
Run `typst init @preview/not-tudabeamer-2023:0.1.0`
Download https://download.hrz.tu-darmstadt.de/protected/ULB/tuda_logo.pdf.
Run `pdf2svg tuda_logo.pdf tuda_logo.svg` or convert to `.svg` using e.g. Inkscape.
### Examples
```typst
#import "@preview/not-tudabeamer-2023:0.1.0": *
#show: not-tudabeamer-2023-theme.with(
config-info(
title: [Title],
short-title: [Title],
subtitle: [Subtitle],
author: "Author",
short-author: "Author",
date: datetime.today(),
department: [Department],
institute: [Institute],
logo: text(fallback: true, size: 0.75in, emoji.cat.face)
//logo: image("tuda_logo.svg", height: 100%)
)
)
#title-slide()
#outline-slide()
= Section
== Subsection
- Some text
```
## Development
This template currently only follows the TU Darmstadt Beamer template in spirit but not pixel-perfect. As the PowerPoint template uses non-free fonts a goal of this project is to more closely match the LaTeX TU Darmstadt Beamer 2023 template. Pull requests to improve this are really welcome.
```
mkdir -p ~/.cache/typst/packages/preview/not-tudabeamer-2023
ln -s $PWD ~/.cache/typst/packages/preview/not-tudabeamer-2023/0.1.0
``` |
https://github.com/typst/templates | https://raw.githubusercontent.com/typst/templates/main/cereal-words/README.md | markdown | MIT No Attribution | # cereal-words
Oh no, the Typst guys jumbled the letters! Bring order into this mess by finding the hidden words.
This small game is playable in the Typst editor and best enjoyed with the web
app or `typst watch`. It was first released for the 24 Days to Christmas
campaign in winter of 2023.
## Usage
You can use this template in the Typst web app by clicking "Start from template"
on the dashboard and searching for `cereal-words`.
Alternatively, you can use the CLI to kick this project off using the command
```
typst init @preview/cereal-words
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `game` function, which accepts a single positional argument for the game input.
The template will initialize your package with a sample call to the `game`
function in a show rule. If you want to change an existing project to use this
template, you can add a show rule like this at the top of your file:
```typ
#import "@preview/cereal-words:0.1.0": game
#show: game
// Type the words here
```
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/5-implementation/interface.typ | typst | Wie zuvor im Kapitel der Konzeption festgestellt, kann das Interface der Anwendung in 3D- und 2D-Elemente unterteilt werden. Hierbei besitzen die einzelnen Elemente unterschiedliche Funktionen und Interaktionsmöglichkeiten.
Als erstes Interface-Element wird der Cursor der Anwendung betrachtet. Im Wireframe wurde festgelegt, dass der Cursor eine geeignete Position auf einer Ebene symbolisiert, auf der ein Möbelstück virtuell platziert werden kann. Zur Überprüfung der geeigneten Fläche wird die WebXR Hit Test API verwendet. Three.js bietet hierbei eine direkte Möglichkeit, auf diese WebXR API zuzugreifen. Grundsätzlich wird der Cursor als 3D-Objekt dargestellt und seine Position abhängig von der Hit Test API gesetzt.
Zur Implementierung wurde die Funktion "hitTest" erstellt. Ein Auszug dieser Funktion ist in @figure-hitTest dargestellt. Zuerst wird der Referenzraum und die Session des Renderers abgefragt. Anschließend wird geprüft, ob bereits ein HitTestSource angefordert wurde. Falls dies nicht der Fall ist, wird ein HitTestSource angefordert. Andernfalls wird das erste HitTestResult aus dem Frame abgefragt und die Position des Cursors entsprechend gesetzt. Hierbei kann die von der WebXR Hit Test API bereitgestellte Funktion "getPose" verwendet werden, um die Position des Cursors zu bestimmen.
#let code = ```js
export function hitTest(renderer, frame) {
const referenceSpace = renderer.xr.getReferenceSpace();
const session = renderer.xr.getSession();
if (this.hitTestSourceRequested === false) {
session.requestReferenceSpace("viewer").then((referenceSpace) => {
session.requestHitTestSource({ space: referenceSpace })
...
});
this.hitTestSourceRequested = true;
}
if (this.hitTestSource) {
const hitTestResults = frame.getHitTestResults(this.hitTestSource);
if (hitTestResults.length) {
const hit = hitTestResults[0];
switchDisplay(true, this);
this.cursor.matrix.fromArray(
hit.getPose(referenceSpace).transform.matrix,
);
} else {
switchDisplay(false, this);
}
}
}
```
#figure(
code,
caption: [Auszug aus der Funktion hitTest vom @appendix-hitTest],
) <figure-hitTest>
Auch das Menü, welches das Anheften von Möbelstücken ermöglicht, wird als 3D-Element dargestellt. Hierbei werden einzelne Platzierungsoptionen als 3D-Plus-Objekte visualisiert. Die Positionierung der einzelnen Optionen basiert auf den importierten Möbelstücken. Durch die Verwendung der jeweiligen Höhe und Breite der Möbelstücke können die Optionen um das Möbelstück herum angeordnet werden.
Im Wireframe werden jedoch auch 2D-Elemente verwendet, um die Benutzerinteraktion zu ermöglichen. Hierbei wird die Benutzeroberfläche in Form von Menüs und Buttons dargestellt. Um die Menüs zu erstellen und zu verwalten, wurde wie bereits im Abschnitt der Technologie beschrieben, die externe Bibliothek "three-mesh-ui" verwendet. Three Mesh UI ermöglicht das Erstellen von XR-Interfaces, welche direkt in Three.js verwendet werden können. Die Bibliothek bietet hierfür eine eigene Klasse namens ThreeMeshUI, welche das Erstellen von komplexen und verschachtelten Interfaces ermöglicht. Des Weiteren können direkt Schriftarten geladen und Text einzelnen Elementen hinzugefügt werden wie in @figure-ui dargestellt @three-mesh-ui.
#let code = ```js
const container = new ThreeMeshUI.Block({
fontFamily: FontJSON,
fontTexture: FontImage,
});
const text = new ThreeMeshUI.Text({
content: "Löschen",
});
container.add(text);
```
#figure(
code,
caption: [Auszug aus der Erstellung eines 2D-Buttons],
) <figure-ui>
Mithilfe dieser Bibliothek wurden alle 2D-Interfaces der Anwendung umgesetzt. Hervorzuheben ist hierbei das Menü "Auswahl". Da sich die Anzahl an Möbelstücken sowie deren Metadaten ändern können, wird das Menü automatisch beim Laden der Webkomponente generiert. In @figure-createMenu wird ein Auszug dieser Funktion dargestellt. Als Parameter wird eine Liste der bereitgestellten Möbelstücke übergeben. Diese werden mithilfe einer Schleife durchlaufen und als Auswahloptionen im Menü hinzugefügt. Dabei werden auch die Metadaten der Möbelstücke auf das Interface übertragen, um im späteren Schritt zwischen den einzelnen Optionen unterscheiden zu können.
#let code = ```js
export const create_menu = (options) => {
const container = new ThreeMeshUI.Block();
options.forEach((option, index) => {
const block = new ThreeMeshUI.Block();
const text = new ThreeMeshUI.Text({
content: option.userData.name,
});
block.add(text);
block.userData.index = index;
block.userData.isCreate = true;
container.add(block);
});
return container;
};
```
#figure(
code,
caption: [Auszug aus der Funktion "create_menu" vom @appendix-createMenu]
) <figure-createMenu>
Um die Sichtbarkeit und Ergonomie der 2D-Menüs zu verbessern, wurde in der Konzeption festgelegt, dass sich diese mit der Kamera-Rotation und -Position bewegen sollen. Um dies zu erreichen, kann der Three.js-Szenengraph wie in @figure-Graph verwendet werden. Hierbei können Objekte miteinander verschachtelt und somit in Bezug zueinander gesetzt werden. Durch das Hinzufügen des Auswahlmenüs zur Kamera folgt dieses automatisch deren Position und Rotation und bleibt somit automatisch im Sichtfeld der Kamera.
#let code = ```js
this.camera.add(this.menus.remove);
```
#figure(
code,
caption: [Beispielhafte Anwendung des Szenengraphen]
) <figure-Graph> |
|
https://github.com/SkytAsul/trombinoscope | https://raw.githubusercontent.com/SkytAsul/trombinoscope/main/pages/pageAssociations.typ | typst | MIT License | #let display(path, name) = block(breakable: false)[
== #name
#let cells = ()
#{
let data = csv("associations/" + path + ".csv")
let handled-roles = ()
for i in range(data.len()) {
let row = data.at(i)
let role = row.at(0)
if role not in handled-roles {
let role-count = 1
for j in range(i+1, data.len()) {
let next-role = data.at(j).at(0)
if next-role == role {
role-count += 1
} else if next-role == "" {
role-count += 1
data.at(j).at(0) = role
} else {
break
}
}
if (role-count > 1) {
handled-roles.push(role)
}
cells.push(table.cell(rowspan: role-count, align: horizon, role))
}
cells += row.slice(1)
}
}
#set text(size: 0.8em)
#table(
columns: (auto, auto, auto),
..cells
)
]
#align(center)[= Associations & Clubs]
#v(1em)
Dans cette partie vous retrouverez une liste (non exhaustive) des membres des bureaux des différents clubs et associations qui ont animé la vie associative de l'INSA sur cette année scolaire 2023/2024.
#show: it => columns(2, it)
#display("amicale", "Amicale")
#display("foyer", "Foy'")
#display("kfet", "Kfêt")
#display("sle", "Son & Lumières")
#display("rns", "Rock'n'Solex")
#display("uds", "Un Des Sens")
#display("fog", "Festival de l'Œil Glauque")
#display("gala", "GALA")
#display("fanfare", "Fanfare")
#display("insalan", "InsaLan")
#display("boom", "BOOM")
#display("bebop", "Bebop")
#display("weipa", "WEIPA XXIII")
#display("wei", "WEI")
#display("aei", "AEI")
#display("insatisfaites", "Insatisfait·es")
#display("photo", "Club photo")
#display("greensa", "Greensa")
#display("insindia", "Ins'India")
#display("ouest", "Ouest INSA")
#display("fgo", "Forum Grand Ouest (FGO)")
#display("as", "Association Sportive (AS)")
#display("eai", "<NAME> (EAI)")
|
https://github.com/nath-roset/suiviProjetHekzamGUI | https://raw.githubusercontent.com/nath-roset/suiviProjetHekzamGUI/master/typ%20sources/Bilan%20de%20mi-parcours.typ | typst | Apache License 2.0 | #import "template.typ": base
#import "@preview/cheq:0.1.0": checklist
#show: doc => base(
// left_header:[],
right_header : [Equipe scan-GUI-Printemps-2024],
title: [Projet Hekzam-GUI],
subtitle: [CC2 - Bilan de mi-Parcours],
version: [],
authors:(
(
name: "<NAME>",
affiliation:"Paul Sabatier University",
email:"",
),
(
name: "<NAME>",
affiliation:"Paul Sabatier University",
email:"",
),
(
name: "<NAME>",
affiliation:"Paul Sabatier University",
email:"",
),
(
name: "<NAME>",
affiliation:"Paul Sabatier University",
email:"",
)
),
doc
)
#outline(
title: none,
target: heading.where(level: 1)
)
= Retours personnels
== <NAME>
La première partie du projet consistait, pour ma part, à travailler sur la *réalisation des exigences fonctionnelles*, des cas de test et des plans de test en se basant sur le prototype moyenne fidélité, en duo avec Nathan.
La régularité des réunions de groupes et des rencontres avec notre responsable de projet nous a permis de rapidement identifier et éclaircir les différentes zones d’ombres du sujet.
Une fois le prototype validé, nous sommes passé à la seconde phase, la programmation. J’ai travaillé en collaboration avec Marco sur le tableau servant à lister et rechercher des copies. Nous nous sommes divisés les tâches: je devais personnellement m’occuper de la barre de recherche.
Une des difficultés fut le choix entre utiliser un `QTableWidget` ou un `QStandardItemModel`, un `QSortFilterProxyModel` et une `QTableView` (c’est un affichage tableau suivant l’architecture Model/View en trois composants). Nous avons décidé de partir sur la `QTableWidget`, malgré son manque de flexibilité, pour sa lisibilité et facilité de compréhension.
Pour la barre de recherche, je devais programmer 2 fonctionnalités : une recherche fonctionnant comme un ctrl+f, qui doit nous permettre de faire ressortir n’importe quel texte. La deuxième fonctionnalité était la recherche par tag. Je n’ai pas eu de difficulté particulière lors de la programmation.
Nous avons, en parallèle, mis en commun nos parties ce qui a généré différents problèmes d’affichage en fonction des systèmes d’exploitation. Une fois les problèmes réglés, il nous restera entre autre à définir un modèle de données pour les fichiers de l’utilisateur ainsi qu’à faire communiquer nos différents composants.
== <NAME>
Mon objectif lors de ce projet était de conceptualiser et d'implémenter la base de *l'interface de l'application*, sans fonctionnalités. Etant donné que sans cette étape, le projet n'aurait pas pu avancer, il était nécessaire de la finir au plus tôt que possible.\
Heureusement, j'ai pu atteindre la majorité de mes objectifs dans les temps en créant le *menu principal* et la structure de la *fenêtre d'évaluation*, cependant je me suis confronté à quelques problèmes lors de la programmation de la *fenêtre de création*, résultant d’un mauvais ajout de layout.
Ce problème fut réglé en temps et en heure du premier milestone, me permettant ainsi de continuer vers la prochaine étape dans laquelle je vais devoir rendre l’ouverture des fichiers de scans fonctionnelle, ceci en collaboration avec les autres membres de l’équipe.
== <NAME>
Lors de la phase de prototypage, la tâche que je devais réaliser était *l’élaboration de la fenêtre d’évaluation*. La difficulté principale de cette tâche était d’obtenir un rendu qui correspondait aux attentes de notre encadrant. Grâce à ses retours sur les premières versions de la fenêtre j’ai pu finaliser le prototype avec succès. \
Concernant la phase de développement, le défi principal était de proposer un code qui respecte les normes du langage *C++* étant donné que je n’étais pas familier avec celui-ci.\ Afin de pallier à cela j’ai dû suivre une formation sur le langage *C++* et la librairie *Qt* avant de pouvoir commencer à coder. \
Nous sommes désormais au milieu de la phase de développement durant laquelle mon rôle est d’implémenter le tableau d’évaluation ainsi que le tri et l’affichage des différentes métriques qu’il contient. La difficulté principale à laquelle j’ai dû faire face était de trouver les modèles de composants les plus adaptés afin d’optimiser l’ergonomie de l’interface utilisateur. Ma tâche actuelle est d’assurer la communication du tableau avec le reste des composants en collaboration avec les autres membres du groupe.
== <NAME>
Durant cette période, j'ai implémenté la classe `ExamPreview` dont l'utilité première sera à terme de *visualiser* et d'*intéragir* avec les pages des copies afin de montrer à l'utilisateur les éléments reconnus par le programmen d'apprécier la qualité de la reconnaissance automatique, et de modifier/calibrer l'interprétation du scan au besoin.\
La partie *visualisation* de l'interface devait permettre de montrer à la fois la page sélectionnée en entier ainsi que des champs en particulier. Cela a été implémenté avec un `QDialog` et un `QStackedWidget`.\
J'ai rencontré quelques difficultés du fait de mon manque d'expérience avec Qt en essayant d'utiliser des classes non adaptées au besoin. De ce fait il m'a fallu remanier plusieures parties du programme afin d'obtenir un résultat agréable à utiliser pour l'utilisateur.
= Échéancier mis à jour
#figure(
image(
"gantt final.png"
)
)
= Répartition des tâches en %
// #pagebreak()
#let a = table.cell( // 25%
fill: blue.lighten(75%),
)[25%]
#let b = table.cell( // 50%
fill: blue.lighten(50%),
)[50%]
#let c = table.cell( // 20%
fill: blue.lighten(85%),
)[20%]
#let d = table.cell( // 40%
fill: blue.lighten(60%),
)[40%]
#let e = table.cell( // 33%
fill: blue.lighten(70%),
)[33%]
#let f = table.cell( // 100%
fill: blue.lighten(20%),
)[100%]
#table(
columns: (auto, auto, auto, auto, auto ,auto),
align: center,
table.header(
[*ID tâche*],[*Nom de la tâche*], [Nathan], [Fabio], [Marco], [Emilien],
),
[WP 0.1], [Capture du besoin] ,a ,a ,a ,a,
[WP 1], [Pilotage projet] ,a ,a ,a ,a,
[WP 2], [Prototypage] ,a ,a ,a ,a,
[WP 3.1], [Conception Fenêtre Principale] ,[] ,f ,[] ,[],
[WP 3.1.1], [Implementation de la barre de menu] ,[] ,f ,[] ,[],
[WP 3.2], [Elaboration du tableau] ,[] ,[] ,f ,[],
[WP 3.2.2], [Filtrage du Tableau] ,[] ,[] ,[] ,f,
[WP 3.3], [Visualisation du scan] ,f ,[] ,[] ,[],
[WP 3.4], [Traitement des fichiers] ,e ,e ,e ,[],
[WP3.5], [Interaction tableau/visualisation] ,e ,[] ,e ,e,
[WP 3.6], [Interaction avec le scan] ,f ,[] ,[] ,[],
[WP 3.7], [Configuration de l'UI] ,c ,d ,c ,c,
[WP 3.8], [Test, déploiement, cross platform] ,a ,a ,a ,a,
[WP 3.9], [Prise en charge des options du CLI] ,[] ,f ,[] ,[],
)
#pagebreak()
= Description des tâches
#linebreak()
#show: checklist.with(unchecked: sym.ballot, checked: sym.ballot.x)
- [x] *Capture du Besoin*
- [x] *Pilotage de projet*
- *Prototypage*
- [x] Spécification des exigences
- [x] Création Prototype moyenne fidélité
- *Conception fenêtre principale*
- [x] Création du menu principal.
- [x] Création du menu de création.
- [x] Création du menu d'évaluation.
- *Implémentation de la barre menu.*
- [ ] Fonctionnalités fichier (ouvrir, sauvegarder, fermer).
- [ ] Fonctionnalités édition (undo, redo).
- [ ] Fonctionnalités d'aide (ouverture de la doc utilisateur).
- *Elaboration du tableau*
- [x] Création et remplissage du tableau
- [x] Implémentation d'une barre de progression sous forme de cellule
- [x] Gestion de l'affichage et du tri des colonnes
- *Filtrage du tableau*
- [x] Création du champ de recherche
- [x] Création de la fonction simple et multiples (fuzzy search...)
- [x] Création de la fonction de recherche par tags
- *Visualisation du scan*
- [x] Création des différentes scènes (grille et vue globale)
- [x] Affichage de la fenêtre de visualisation externe
- *Traitement des fichiers*
- [x] Ouverture via menu création.
- [x] Remplissage de la structure ScanInfo utilisée plus tard.
- [x] Lecture et interprétation des fichiers JSON
- *Interaction tableau/visualisation*
- [x] Définition d'une interface de communication entre les modules
- [x] Méthodes de correspondances entre cellules du tableau et fichiers
- *Interaction avec le scan*
- [x] Reglage des métriques de cadrage
- [x] Interactions aves les différents champs d'une page (modifier, déplacer, highlight)
- *Configuration de l'UI.*
- [ ] Options de configurations dans menu Affichage.
- [x] Sauvegarde de la configuration dans un fichier.
- *Test, déploiement, cross platform*
- [x] Tests non automatisés
- *Prise en charge des options du CLI *
- [x] Gestion des options (help, version...)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/down/0.1.0/README.md | markdown | Apache License 2.0 | # Down
Pass down arguments of `sum`, `integral`, etc. to the next line, which
can generate shorthand to present reusable segments. While writing long
step-by-step equations, only certain parts of a line change. `down`
leverages Typst's `context` (from version 0.11.0) to help relieve the
pressure of writing long and repetitive formulae.
Import the package:
``` typ
#import "@preview/down:0.1.0": *
```
## Usage
Create new contexts by using camel-case commands, such as
`Limit(x, +0)`. Retrieve the contextual with `cLimit`.
- `Limit(x, c)` and `cLimit`:
``` typ
$
Lim(x, +0) x ln(sin x)
= cLim ln(sin x) / x^(-1)
= cLim x / (sin x) cos x
= 0
$
```
- `Sum(index, lower, upper)` and `cSum`:
``` typ
$
Sum(n, 0, oo) 1 / sqrt(n + 1)
= Sum(#none, 0, #none) 1 / sqrt(n)
= cSum 1 / n^(1 / 2)
$
```
- `Integral(lower, upper, f, dif: [x])`, `cIntegral(f)` and
`cIntegrated(f)`:
``` typ
$
Integral(0, pi / 3, sqrt(1 + tan^2 x))
= cIntegral(1 / (cos x))
= cIntegrated(ln (cos x / 2 + sin x / 2) / (cos x / 2 - sin x / 2))
= ln (2 + sqrt(3))
$
```
Refer to `./sample.pdf` for more complex application.
|
https://github.com/uhChainsaws/gradie | https://raw.githubusercontent.com/uhChainsaws/gradie/main/caramell.typ | typst | // #let bg_colour = rgb("#fffcf2")
// #let text_colour = rgb("#252422")
// #let heading_colour = rgb("#403d39")
// #let accent_colour = rgb("#eb5e28")
#let bg_colour = rgb("#f2e8cf")
#let text_colour = rgb("#386641")
// #let heading_colour = rgb("#386641")
#let heading_colour = rgb("#6a994e")
#let accent_colour = rgb("#bc4749")
#let stylle(title: none, doc) = {
set text(
// font: ("Space Mono", "PT Mono"),
font: "PT Mono",
size: 12pt,
fill: text_colour,
hyphenate: false,
)
show math.equation: set text(fill: accent_colour)
show heading: it => [
#set align(right)
#set text(
16pt,
weight: "extrabold",
fill: heading_colour,
// tracking: 0.5em,
)
#block(upper(it.body))
]
set par(
justify: true,
leading: 1em,
)
set page(
paper: "a4",
fill: bg_colour,
)
align(right+horizon)[
#set text(
size: 42pt,
fill: accent_colour,
tracking: 0.2em,
hyphenate: true,
)
#title
]
align(left+bottom)[#emph[
#set text(size: 16pt)
by <NAME> \
#link("https://isu.ifmo.ru/pls/apex/f?p=2437:7:116994060325398")[ISU[368372]] \
#link("https://t.me/uhChainsaws")[\@uhChainsaws] \
]]
pagebreak()
set page(
margin: (x: 4cm, y: auto),
header: align(left + horizon)[
#set text(size: 8pt)
_#repeat([#title]+[;])_
],
)
doc
}
|
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/03-polynomials/10-rational-fractions.typ | typst | Other | #import "../../utils/core.typ": *
== Рациональные дроби
#def[
_Поле частных области целостности_ $R$ --- наименьшее поле, в которое вложена $R$.
Назовем его $Q(R)$.
]
Элементы поля частных представляются как дроби $(a)/(b)$, где $a, b in R$ и $b eq.not 0$. Это поле строится так:
Рассмотрим $M = R times (R without \{0\})$ и введём на $M$ отношение $sim$:
$(a, b) sim (a', b') <==> a b' = a'b$
#pr[
$sim$ --- отношение эквивалентности
]
#proof[
рефлексивность и симметричность очевидны
транзитивность:
$display(cases(
(a, b) sim (a', b')\\
(a', b') sim (a'', b'')
)) ==> a b' b'' = a' b b'' = a'' b b' ==> b'(a b'' - a'' b) = 0$
$b eq.not 0 ==> a b'' - a'' b = 0 ==> a b'' = a'' b ==> (a, b) sim (a'', b'')$
То есть $sim$ --- это отношение эквивалентности на $M$.
]
#def[
$Q(R) = M \/ sim = \{ [(a, b)] divides a in R, b in R without \{0\} \}$
]
#def[
Обозначим $(a)/(b)$ --- это $[(a, b)] in Q(R)$.
]
#pr[
Введём в $Q(R)$ операции сложения и умножения:
$
(a_1)/(b_1) + (a_2)/(b_2) = (a_1 b_2 + a_2 b_1)/(b_1 b_2)\
(a_1)/(b_1) dot (a_2)/(b_2) = (a_1 a_2)/(b_1 b_2)
$
]
#notice[
$(a, b) sim (a c, b c) quad forall c in R without \{0\}$
Такая замена не изменит результат.
]
#notice[
$(a, b) sim (a', b') <==> (a b', b b') = (a'b, b'b)$
]
#pr[
Операции на $Q(R)$ определены корректно, при этом $Q(R)$ с этими операциями --- поле.
]
#proof[
Коммутативность и ассоциативность сложения очевидны в случае одинакого знаменателя.
$(a_1)/(b) + (a_2)/(b) = (a_1 b + a_2 b)/(b^2) = (a_2 b + a_1 b)/(b^2) = (a_2)/(b) + (a_1)/(b)$
Но любые $2$ дроби можно привести к общему знаменателю:
$(a_1)/(b_1) = (a_1 b_2)/(b_1 b_2) quad (a_2)/(b_2) = (a_2 b_1)/(b_1 b_2)$
Нейтральный по сложению элемент --- это $(0)/(1)$
Противоположный по сложению элемент к $(a)/(b)$ --- это $(-a)/(b)$
Дистрибутивность: $((a_1)/(b) + (a_2)/(b)) (a')/(b') = (a_1 + a_2)/(b) (a')/(b') = ((a_1 + a_2) a')/(b b') = (a_1 a' + a_2 a')/(b b') = (a_1)/(b) (a')/(b') + (a_2)/(b) (a')/(b') = (a_1)/(b) (a')/(b') + (a_2)/(b) (a')/(b')$
Нейтральный по умножению элемент --- это $(1)/(1)$
$(a)/(b) eq.not (0)/(1) ==> a dot 1 eq.not b dot 0 <==> a eq.not 0$
Обратный по умножению элемент к $(a)/(b)$ --- это $(b)/(a)$
]
#notice[
$R limits(maps)^(epsilon) Q(R), space r maps (r)/(1)$
То есть, считаем $R subset Q(R)$
]
#def[
Пусть $K$ --- поле. Тогда поле $K(x) = Q(K[x])$ назовем _полем рациональных дробей_ (_дробно-рациональных функций_) над полем $K$.
]
#pr(name: [Несократимое представление])[
Пусть $R$ --- факториальное кольцо. Тогда любой $S in Q(R)$ представимых в виде $s = (p)/(q), space (p, q) = 1$. Такое представление единственно с точностью до умножения $p$ и $q$ на $epsilon in R^*$.
]
#proof[
Пусть $s = (a)/(b), space d = gcd(a, b) ==> a = d a', space b = d b' ==> s = (a')/(b'), space (a', b') = 1$
Если $(p)/(q) = (p')/(q'), space (p, q) = (p', q') = 1$, то $p q' = p' q ==> display(cases(
p divides p'q,
(p, q) = 1
)) ==> p divides p'$, аналогично $p' divides p$
То есть $p$ и $p'$ ассоциативны $==>$ $p' = epsilon p, space epsilon in R^*$
$p q' = epsilon p q ==> q' = epsilon q$
]
#lemma[
Пусть $s in K(x), space s = (p)/(q), quad p, q in K[x]$
Тогда $deg p - deg q$ --- инвариант $s$. (то есть не зависит от выбора представления в виде $p$ и $q$)
]
#proof[
Если $(p)/(q) = (p')/(q')$, то $p q' = p'q$, а значит $deg p + deg q' = deg p' + deg q ==> deg p - deg q = deg p' - deg q'$
Таким образом можно определить степень рациональной дроби $deg s = deg (p)/(q) = deg p - deg q$
]
#def[
$s in K(x)$ называется правильной дробью, если $deg s < 0$
В частности $0$ --- правильная дробь
]
#notice[
Очевидно сумма и произведение правильных дробей --- правильная дробь
]
#lemma[
Любая рациональная дробь однозначно представляется в виде суммы многочленов и правильной дроби.
]
#proof[
"Существование":
Пусть $s = (p)/(q)$, поделим на $p$ на $q$, получается:
$p = q dot t + r$, где $r = 0$ или $deg r < deg q ==> (p)/(q) = t + (r)/(q), space t in K[x],$ где $(r)/(q)$ --- правильная дробь
"Единственность":
$t + (r)/(q) = t_1 + (r_1)/(q_1), space t_1 in K[x],$ где $(r_1)/(q_1)$ --- правильная дробь
$t - t_1 = (r_1)/(q_1) - (r)/(q)$ --- правильная дробь
$t - t_1 = (t - t_1)/(1) = (r_1)/(q_1) - (r)/(q) ==> deg((r_1)/(q_1) - (r)/(q)) = deg(t - t_1) < 0 ==> t - t_1 = 0 = (r_1)/(q_1) - (r)/(q)$
]
#lemma[
Пусть $(f, g) = 1$. Тогда любую дробь со знаменателем $fg$ можно представить как сумму дробей со знаменателем $f$ и $g$.
]
#proof[
$1 = c f + d g$ для некоторых $c, d in K[x]$
$(a)/(f g) = (a(c d + d g))/(f g) = (a c f)/(f g) + (a d g)/(f g) = (a c)/(g) + (a d)/(f)$
]
#def[
Дробь $s$ называется _примарной_ (_$p$-примарной_), если $s = (a)/(p^n), space p$ --- неприводимый многочлен, $n in NN$
]
#pr[
Любую правильную дробь можно однозначно представить в виде суммы нескольких отличных от $0$ правильных $p$-примарных дробей, где $p$ --- различные унитарные неприводимые многочлены.
]
#proof[
"Существование":
Запишем значение $s$ в виде $p_1^(m_1) ... p_t^(m_t)$, где $p_i$ --- унитарные неприводимые многочлены
По лемме $s = (...)/(p_1^(m_1)) + (...)/(p_t^(m_t)) = (a_1)/(p_1^(m_1)) + ... + (a_t)/(p_t^(m_t))$
Перепишем это в виде суммы многочлена и правильных дробей, с тем же знаменателем, получим:
$s = f + (b_1)/(p_1^(m_1)) + ... + (b_t)/(p_t^(m_t)), space f in K[x], space (b_j)/(p_j^(m_j))$ --- правильная дробь
$==> f = s - (b_1)/(p_1^(m_1)) - ... - (b_t)/(p_t^(m_t))$, где $(f)/(1)$ --- правильная дробь
$==> deg f < 0 ==> f = 0$
"Единственность":
Пусть у $S$ есть $2$ различных таких разложения
Вычитаем из первого разложения второе, получим:
$(c_1)/(p_1^(n_1)) + ... + (c_l)/(p_l^(n_l)) = 0, space p_i$ --- унитарные неприводимые многочлены
$c_1, ..., c_l eq.not 0$
Можно считать все эти дроби несократимыми.
$==> (c_1)/(p_1^(n_1)) + ... + (c_(l-1))/(p_(l - 1)^(n_(l - 1))) = (-c_l)/(p_l^(n_l))$
Приведем к общему знаменателю левую часть и сократим дробь, тогда знаменатель полученной дроби будет делить $p_1^(n_1) ... p_(l-1)^(n_(l - 1))$ и не будет ассоциирован с $p_l^(n_l)$, так как не может быть делителем $p_l$, противоречие.
]
#def[
Простейшей дробью называется дробь вида $(a)/(p^n)$, где $p$ --- неприводимый многочлен, $n in NN$, $deg a < deg p$
]
#th[
Любая ненулувая правильная дробь единственным образом представляется в виде суммы нескольких простейших дробей с различными знаменателями.
]
#proof[
"Существование":
Достаточно разложить правильную примарную дробь $(a)/(p^n)$
$a = r_m p^m + ... + r_1 p + r_0$, $deg r_i < deg p, space r_m eq.not 0$
$m < n$, так как $deg a < deg p$
$(a)/(p^n) = (r_m)/(p^(n - m)) + (r_(m-1))/(p^(n - m + 1)) + ... + (r_1)/(p^(n - 1)) + (r_0)/(p^n)$ --- искомое представление, если удалить нулевые слагаемые
"Единственность":
Пусть для $s$ есть представления в виде суммы примарных. Обозначим $C_p$ за сумму $p$-примарных дробей в этом представлении.
$C_p$ --- $p$-примарная правильная дробь
$s = C_(p_1) + ... + C_(p_t) ==>$ все $C_p$ определены однозначно
Пусть у $C_p$ есть два разных разложения в сумму простейших дробей со степенями $p$ в знаменателях.
$(r_n)/(p^n) + ... + (r_1)/(p^1) = (s_n)/(p^n) + ... + (s_1)/(p^1)$, где $n$ --- максимальный показатель степени $p$ в знаменателях
Пусть $m$ --- максимальный индекс, такой что $r_m eq.not s_m$, некоторые $r_i$ и $s_i$ могут быть нулевыми
$(r_m - s_m)/(p^m) + ... + (r_1 - s_1)/(p^1) = 0$
$==> (r_m - s_m)/(p) = -(r_(m - 1) - s_(m - 1)) - p (r_(m - 2) - s_(m - 2)) - ... in K[X]$
Противоречие, слева дробь, а справа многочлен.
] |
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/04_laplace.typ | typst | #import "admonitions.typ": opomba
#import "@preview/fletcher:0.5.1": diagram, node, edge
#import "@preview/cetz:0.2.2" as cetz: canvas
= Minimalne ploskve
<minimalne-ploskve-laplaceova-enačba>
== Naloga
<naloga>
Žično zanko s pravokotnim tlorisom potopimo v milnico, tako da se nanjo napne
milna opna. Radi bi poiskali obliko milne opne, razpete na žični zanki. Malo brskanja po
fizikalnih knjigah in internetu hitro razkrije, da ploskve, ki tako nastanejo,
sodijo med
#link("http://en.wikipedia.org/wiki/Minimal_surface")[minimalne ploskve], ki so
burile domišljijo mnogim matematikom in nematematikom. Minimalne ploskve so
navdihovale tudi umetnike npr. znanega arhitekta
#link("https://en.wikipedia.org/wiki/Frei_Otto")[Otto Frei], ki je sodeloval pri
zasnovi Muenchenskega olimpijskega stadiona, kjer ima streha obliko minimalne
ploskve.
#figure(
image("img/1024px-Olympic_Stadium_Munich_Dachbegehung.JPG"),
caption: [Streha olimpijskega stadiona v Münchnu (vir #link(
"https://de.wikipedia.org/wiki/Olympiastadion_M%C3%BCnchen#/media/File:Olympic_Stadium_Munich_Dachbegehung.JPG")[wikipedia])],
)
Namen te vaje je primerjava eksplicitnih in iterativnih metod za reševanje linearnih sistemov enačb. Prav tako se bomo naučili, kako zgradimo matriko sistema in desne strani enačb za spremenljivke, ki niso podane z vektorjem ampak kot elementi matrike. V okviru te vaje opravi naslednje naloge.
- Izpelji matematični model za minimalne ploskve s pravokotnim tlorisom.
- Zapiši problem iskanja minimalne ploskve kot #link("https://en.wikipedia.org/wiki/Boundary_value_problem")[robni problem] za #link("https://en.wikipedia.org/wiki/Laplace%27s_equation")[Laplaceovo enačbo] na pravokotniku.
- Robni problem diskretiziraj in zapiši v obliki sistema linearnih enačb.
- Reši sistem linearnih enačb z LU razcepom. Uporabi knjižnico #link("https://docs.julialang.org/en/v1/stdlib/SparseArrays/")[SparseArrays] za varčno hranjenje matrike sistema.
- Preveri, kako se število neničelnih elementov poveča pri LU razcepu razpršene matrike.
- Uporabi iterativne metode (Jacobijeva, Gauss-Seidlova in SOR iteracija) in reši
sistem enačb direktno na elementih matrike višinskih vrednosti ploskve brez eksplicitne
uporabe matrike sistema.
- Nariši primer minimalne ploskve.
- Animiraj konvergenco iterativnih metod.
== Matematično ozadje
<matematično-ozadje>
Ploskev lahko predstavimo s funkcijo dveh spremenljivk $u (x, y)$, ki predstavlja višino ploskve nad točko $(x, y)$. Naša naloga je poiskati približek za funkcijo $u(x, y)$ na pravokotnem območju.
Funkcija $u(x, y)$, ki opisuje milno opno, zadošča matematična enačbi
$
Delta u(x,y) = (partial ^2 u)/(partial x^2) + (partial ^2 u)/(partial y^2) = rho(x, y),
$ <eq:Poisson>
znani pod imenom
#link("https://sl.wikipedia.org/wiki/Poissonova_ena%C4%8Dba")[Poissonova enačba].
Funkcija $rho(x, y)$ je sorazmerna tlačni razliki med zunanjo in notranjo
površino milne opne. Tlačna razlika je lahko posledica višjega tlaka v
notranjosti milnega mehurčka ali pa teže milnice.
Če tlačno razliko zanemarimo, dobimo
#link("https://en.wikipedia.org/wiki/Laplace%27s_equation")[Laplaceovo enačbo]:
$
Delta u(x, y) = 0.
$<eq:Laplace>
Vrednosti $u(x, y)$ na robu območja so določene z obliko zanke, medtem ko za vrednosti v notranjosti velja enačba @eq:Laplace. Problem za diferencialno enačbo, pri katerem so podane vrednosti na robu, imenujemo #link("https://en.wikipedia.org/wiki/Boundary_value_problem")[robni problem].
V nadaljevanju predpostavimo, da je območje pravokotnik $[a, b] times [c, d]$.
Poleg Laplaceove enačbe @eq:Laplace, veljajo za vrednosti funkcije $u(x, y)$
tudi #emph[robni pogoji]:
$
u(x, c) = f_s (x) \
u(x, d) = f_z (x) \
u(a, y) = f_l (y) \
u(b, y) = f_d (y)\
$
kjer so $f_s, f_z, f_l$ in $f_d$ dane funkcije. Rešitev robnega
problema je tako odvisna od območja, kot tudi od robnih pogojev.
== Diskretizacija in linearni sistem enačb
<diskretizacija-in-linearni-sistem-enačb>
Problema se bomo lotili numerično, zato bomo vrednosti
$u(x, y)$ poiskali le v končno mnogo točkah: problem bomo
#link("https://en.wikipedia.org/wiki/Discretization")[diskretizirali].
Za diskretizacijo je najpreprosteje uporabiti enakomerno razporejeno pravokotno mrežo točk na pravokotniku. Točke na mreži imenujemo #emph[vozlišča]. Zaradi enostavnosti se omejimo na mreže z enakim razmikom v obeh koordinatnih smereh. Interval $[a, b]$
razdelimo na $n + 1$ delov, interval $[c, d]$ pa na $m + 1$ delov in dobimo zaporedje koordinat
$
a = & x_0, & x_1, & dots & x_(n+1)=b\
c = & y_0, & y_1, & dots & y_(m+1)=d,
$
ki definirajo pravokotno mrežo točk $(x_i, y_j)$. Namesto funkcije $u
: [a, b] times [c, d] arrow.r bb(R)$
tako iščemo le vrednosti
$ u_(i j) = u(x_i, y_j), #h(1em) i=1, dots n, #h(1em) j=1, dots m $
//#figure([#image("sosedi.png")], caption: [
// sosednja vozlišča
//])
Elemente matrike $u_(i j)$ določimo tako, da je v limiti, ko gre razmik med vozliči proti
$0$, izpolnjena Laplaceova enačba @eq:Laplace.
Laplaceovo enačbo lahko diskretiziramo s
#link("https://en.wikipedia.org/wiki/Finite_difference")[končnimi diferencami]. Lahko pa
dobimo navdih pri arhitektu Frei Otto, ki je minimalne ploskve
#link("https://youtu.be/-IW7o25NmeA")[raziskoval z elastičnimi tkaninami]. Ploskev si
predstavljamo kot elastično tkanino, ki je fina kvadratna mreža iz elastičnih nitk. Vsako vozlišče v mreži je povezano s 4 sosednjimi vozlišči.
#figure(
caption:[Sosednje vrednosti vozlišča $(i,j)$.])[
#diagram(
node((1, 0), $u_(i j-1)$),
edge("d", "-"),
node((0, 1), $u_(i-1 j)$),
edge("-"),
node((1, 1), $u_(i j)$),
edge("-"),
node((2, 1), $u_(i+1 j)$),
node((1, 2), $u_(i j+1)$),
edge("u", "-")
)
]
Vozlišče bo v ravnovesju, ko bo vsota vseh sil nanj enaka 0.
#figure(
caption:[Sile elastik iz sosednjih vozlišč $(i-1, j)$ in $(i+1, j)$ na vozlišče $(i,j)$.])[
#canvas({
import cetz.draw: *
let x = 3
let y = -1.5
line((0, 0), (x, y))
line((0, 0), (x, 0), stroke: 0.2pt)
line((x, y), (x, 0), mark: (end: ">"), name:"f1")
line((x, y), (x, 2.5*y), mark: (end: ">"), name: "f2")
line((x, y), (2*x, 2.5*y))
line((x, 2.5*y), (2*x, 2.5*y), stroke: 0.2pt)
circle((x, y), radius: 0.05, fill: white)
circle((0, 0), radius: 0.05, fill: white)
circle((2*x, 2.5*y), radius: 0.05, fill: white)
content((x + 0.1, 0.5*y), [$bold(F)_1 prop u_(i-1 j) - u_(i j)$], anchor: "west")
content((x - 0.1, 1.5*y), [$bold(F)_2 prop u_(i+1 j) - u_(i j)$], anchor: "east")
content((-0.2, 0), [$u_(i-1 j)$], anchor: "east" )
content((x + 0.2, y), [$u_(i j)$], anchor: "west" )
content((2*x + 0.2, 2.5*y), [$u_(i+1 j)$], anchor: "west" )
})
]
Predpostavimo, da so vozlišča povezana z idealnimi vzmetmi in je sila sorazmerna z vektorjem med položaji vozlišč. Če zapišemo enačbo za komponente sile v smeri $z$, dobimo za točko $(x_i, y_j, u_(i j))$ enačbo
$
(u_(i-1 j) - u_(i j)) + (u_(i j-1) - u_(i j)) + (u_(i+1 j) - u_(i j)) + (u_(i j+1) - u_i(i, j)) &= 0\
u_(i-1 j) + u_(i j-1) - 4u_(i j) + u_(i+1 j) + u_(i j+1) &= 0.
$<eq:ravnovesje>
Za vsako vrednost $u_(i j)$ dobimo eno enačbo. Tako dobimo sistem linearnih $n dot m$ enačb za $n dot m$ neznank. Ker so vrednosti na robu določene z robnimi pogoji, moramo elemente $u_(0 j)$, $u_(n plus 1, j)$, $u_(i 0)$ in $u_(i m plus 1)$ prestaviti na desno stran in jih upoštevati kot konstante.
== Matrika sistema linearnih enačb
<matrika-sistema-linearnih-enačb>
Sisteme linearnih enačb običajno zapišemo v matrični obliki
$ A bold(x) = bold(b), $
kjer je $A$ kvadratna matrika, $bold(x)$ in $bold(b)$ pa vektorja. Spremenljivke
$u_(i j)$ moramo nekako razvrstiti v vektor $bold(x)=[x_1, x_2, dots]^T$.
Najpogosteje elemente $u_(i j)$ razvrstimo v vektor $bold(x)$ po stolpcih, tako da je
$
bold(x) = [u_(11), u_(21) med dots med u_(n 1), u_(12), u_(22) med dots med u_(1n) med dots med u_(m-1 n), u_(m n)]^T.
$
Za $n = m = 3$ dobimo $9 times 9$ matriko
$
A^(9, 9) = mat(-4, 1, 0, 1, 0, 0, 0, 0, 0; 1, -4, 1, 0, 1, 0, 0,
0, 0; 0, 1, -4, 0, 0, 1, 0, 0, 0; 1, 0, 0, -4, 1, 0, 1, 0, 0; 0, 1, 0, 1, -4,
1, 0, 1, 0; 0, 0, 1, 0, 1, -4, 0, 0, 1; 0, 0, 0, 1, 0, 0, -4, 1, 0; 0, 0, 0,
0, 1, 0, 1, -4, 1; 0, 0, 0, 0, 0, 1, 0, 1, -4),
$
ki je sestavljena iz $3 times 3$ blokov
$
L^(3, 3) = mat(-4,1,0; 1,-4,1; 0,1,-4),quad
I^(3, 3) = mat(1,0,0; 0,1,0; 0,0,1).
$
in desne strani
$
bold(b) = -\[&u_(0 1)+u_(1 0), u_(2 0) dots u_(n 0) + u_(n+1 1),\
&u_(0 2), 0 dots u_(n+1, 2), u_(0 3), 0 dots u_(n m+1), u_(n m+1) + u_(n+1 m)\]^T.
$
#let vecop = math.op("vec", limits: true)
#opomba(naslov: [Razvrstitev po stolpih in operator $vecop$])[
Eden od načinov, kako lahko elemente matrike razvrstimo v vektor, je po stolpcih. Stolpce
matrike enega za drugim postavimo v vektor. Indeks v vektorju $k$ lahko
izrazimo z indeksi $i,j$ v matriki s formulo
$ k = i+(n-1)j. $ Ta način preoblikovanja matrike v vektor označimo s posebnim operatorjem $vecop$:
$
vecop: RR^(n times m) -> RR^(n dot m)\
vecop(A)_(i + (n-1)j) = a_(i j)
$
]
== Izpeljava sistema s Kronekerjevim produktom
Množenje vektorja $bold(x) = vecop(U)$ z matriko $A$ lahko prestavimo kot
množenje matrike $U$ z matriko $L$ z leve in desne:
$
A vecop(U) = vecop(L U + U L),
$
kjer je $L$ Laplaceova matrika v eni dimenziji, ki ima $-2$ na diagonali in $1$ na spodnji pod-diagonali in zgornji nad-diagonali:
$
L = mat(
-2, 1, 0, dots, 0;
1, -2, 1, dots, dots.v;
dots.v, dots.down, dots.down, dots.down, 0;
0, dots, 1, -2, 1;
0, dots, 0, 1, -2;
).
$
Res! Moženje matrike $U$ z matriko $L$ z leve je ekvivalentno množenju stolpcev matrike $U$ z matriko $L$, medtem ko je množenje z matriko $L$ z desne ekvivalentno množenju vrstic matrike $U$ z matriko $L$. Prispevek množenja z leve vsebuje vsoto sil sosednjih vozlišč v smeri $y$, medtem ko množenje z desne vsebuje vsoto sil sosednjih vozlišč v smeri $x$. Element produkta $L U + U L$ na mestu $(i, j)$ je enak:
$
(L U + U L)_(i j) &= sum_(k=1)^m l_(i k) u_(k j) + sum_(k=1)^n u_(i k) l_(k j) \
&= u_(i j-1) -2u_(i j) + u_(i j+1) + u_(i - 1 j) -2u_(i j) + u_(i +1 j),
$
kar je enako desni strani enačbe @eq:ravnovesje.
Ker velja $vecop(A X B) = A times.circle B dot vecop(X)$, lahko matriko $A$ zapišemo s #link("https://sl.wikipedia.org/wiki/Kroneckerjev_produkt")[Kronekerjevim produktom] $times.circle$ matrik $L$ in $I$:
$
A dot vecop(U) &= vecop(L U + U L) = vecop(L U I + I U L) \
A^(N, N) &= L^(m, m) times.circle I^(n, n) + I^(m, m) times.circle L^(n, n).
$
#opomba(naslov:[Kroneckerjev produkt in operator $vecop$ v Juliji])[
Programski jezik Julia ima vgrajene funkcije `vec` in `kron` za preoblikovanje matrik v vektorje in računanje Kronekerjevega produkta. Z ukazom `reshape` pa lahko iz vektorja
znova zgradimo matriko.
]
== Primer
<primer>
```julia robni_problem = RobniProblemPravokotnik( LaplaceovOperator{2}, ((0,
pi), (0, pi)), [sin, y->0, sin, y->0] ) Z, x, y = resi(robni_problem) surface(x,
y, Z) savefig("milnica.png") ```
// #figure([#image("milnica.png")], caption: [
// minimalna ploskev
//])
== Napolnitev matrike ob eliminaciji
<napolnitev-matrike-ob-eliminaciji>
Matrika Laplaceovega operatorja ima veliko ničelnih elementov. Takim matrikam
pravimo
#link(
"https://sl.wikipedia.org/wiki/Redka_matrika",
)[razpršene ali redke matrike]. Razpršenost matirke lahko izkoristimo za
prihranek prostora in časa, kot smo že videli pri
#link("02_tridiagonalni_sistemi.md")[tridiagonalnih matrikah]. Vendar se pri
Gaussovi eliminaciji delež ničelnih elementov matrike pogosto zmanjša. Poglejmo
kako se odreže matrika za Laplaceov operator.
```julia using Plots L = matrika(100,100, LaplaceovOperator(2)) spy(sparse(L),
seriescolor = :blues) ```
//#figure([#image("laplaceova_matrika.png")], caption: [
// Redka struktura Laplaceove matrike
//])
Če izvedemo eliminacijo, se matrika deloma napolni z neničelnimi elementi:
```julia import LinearAlgebra.lu LU = lu(L) spy!(sparse(LU.L), seriescolor =
:blues) spy!(sparse(LU.U), seriescolor = :blues) ```
//#figure([#image("lu_laplaceove_matrike.png")], caption: [
// Napolnitev ob razcepu
//])
== Koda
<koda>
```@index Pages = ["03_minimalne_ploskve.md"] ```
```@autodocs Modules = [NumMat] Pages = ["Laplace2D.jl"]```
== Iteracijske metode <iteracijske-metode>
```@meta
CurrentModule = NumMat
DocTestSetup = quote
using NumMat
end
```
V #link("03_minimalne_ploskve.md")[nalogi o minimalnih ploskvah] smo reševali
linearen sistem enačb
```math
u_{i,j-1}+u_{i-1,j}-4u_{ij}+u_{i+1,j}+u_{i,j+1}=0
```
za elemente matrike $U = lr([u_(i j)])$, ki predstavlja višinske vrednosti na
minimalni ploskvi v vozliščih kvadratne mreže. Največ težav smo imeli z zapisom
matrike sistema in desnih strani. Poleg tega je matrika sistema $L$ razpršena
\(ima veliko ničel), ko izvedemo LU razcep ali Gaussovo eliminacijo, veliko teh
ničelnih elementov postane neničelni in matrika se napolni. Pri razpršenih
matrikah tako pogosto uporabimo
#link(
"https://en.wikipedia.org/wiki/Iterative_method#Linear_systems",
)[iterativne metode]
za reševanje sistemov enačb, pri katerih matrika ostane razpršena in tako lahko
prihranimo veliko na prostorski in časovni zahtevnosti.
!!! note "Ideja iteracijskih metod je preprosta"
```
Enačbe preuredimo tako, da ostane na eni strani le en element s koeficientom 1. Tako dobimo iteracijsko formulo za zaporedje približkov $u_{ij}^{(k)}$. Limita rekurzivnega zaporedja je ena od fiksnih točk rekurzivne enačbo, če zaporedje konvergira. Ker smo rekurzivno enačbo izpeljali iz originalnih enačb, je njena fiksna točka ravno rešitev originalnega sistema.
```
V primeru enačb za laplaceovo enačbo\(minimalne ploskve), tako dobimo rekurzivne
enačbe
```math
u_{ij}^{(k+1)} = \frac{1}{4}\left(u_{i,j-1}^{(k)}+u_{i-1,j}^{(k)}+u_{i+1,j}^{(k)}+u_{i,j+1}^{(k)}\right),
```
ki ustrezajo
#link("https://en.wikipedia.org/wiki/Jacobi_method")[jacobijevi iteraciji]
!!! tip "Pogoji konvergence"
```
Rekli boste, to je preveč enostavno, če enačbe le pruredimo in se potem rešitel kar sama pojavi, če le dovolj dolgo računamo. Gotovo se nekje skriva kak hakelc. Res je! Težave se pojavijo, če zaporedje približkov **ne konvergira dovolj hitro** ali pa sploh ne. Jakobijeva, Gauss-Seidlova in SOR iteracija **ne konvergirajo vedno**, zagotovo pa konvergirajo, če je matrika po vrsticah [diagonalno dominantna](https://sl.wikipedia.org/wiki/Diagonalno_dominantna_matrika).
```
Konvergenco jacobijeve iteracije lahko izboljšamo, če namesto vrednosti na
prejšnjem približku, uporabimo nove vrednosti, ki so bile že izračunani. Če
računamo element $u_(i j)$ po leksikografskem vrstnem redu, bodo elementi $u_(i l)^(lr((k plus 1)))$ za $l lt j$ in
$u_(l j)^(lr((k plus 1)))$ za $l lt i$ že na novo izračunani, ko računamo $u_(i j)^(lr((k plus 1)))$.
Če jih upobimo v iteracijski formuli, dobimo
#link(
"https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method",
)[gauss-seidlovo iteracijo]
$
u_(i,j)^((k+1)) = 1/4(u_(i,j-1)^((k+1))+ u_(i-1,j)^((k))+u_(i+1,j)^((k))+u_(i,j+1)^((k)))
$
Konvergenco še izboljšamo, če približek $u_(i j)^(lr((k plus 1)))$, ki ga dobimo
z gauss-seidlovo metodo, malce zmešamo s približkom na prejšnjem koraku $u_(i j)^(lr((k)))$
$
u_(i,j)^(("GS")) &= 1/4(u_(i,j-1)^((k+1))+ u_(i-1,j)^((k))+u_(i+1,j)^((k))+u_(i,j+1)^((k)))\
u_(i, j)^((k+1)) &= omega u_(i, j)^(("GS")) + (1 - omega) u_(i, j)^((k))
$
in dobimo
#link("https://en.wikipedia.org/wiki/Successive_over-relaxation")[metodo SOR].
Parameter $omega$ je lahko poljubno število
$paren.l 0, 2 bracket.r$ Pri $omega = 1$ dobimo Gauss-Seidlovo iteracijo.
=== Primer
<primer>
```julia
using Plots
U0 = zeros(20, 20)
x = LinRange(0, pi, 20)
U0[1,:] = sin.(x)
U0[end,:] = sin.(x)
surface(x, x, U0, title="Začetni približek za iteracijo")
savefig("zacetni_priblizek.png")
```
//#figure([#image("zacetni_priblizek.png")], caption: [
// začetni priblizek za iteracijo
//])
```julia
L = LaplaceovOperator(2)
U = copy(U0)
animation = Animation()
for i=1:200
U = korak_sor(L, U)
surface(x, x, U, title="Konvergenca Gauss-Seidlove iteracije")
frame(animation)
end
mp4(animation, "konvergenca.mp4", fps = 10)
```
`@raw html <video width="600" height="400" controls> <source src="../konvergenca.mp4" type="video/mp4"> <source src="konvergenca.mp4" type="video/mp4"> </video>`
#link("konvergenca.mp4")[Konvergenca Gauss-Seidlove iteracije]
=== Konvergenca
<konvergenca>
Grafično predstavi konvergenco v odvisnoti od izbire $omega$.
```julia
using Plots
n = 50
U = zeros(n,n)
U[:,1] = sin.(LinRange(0, pi, n))
U[:, end] = U[:, 1]
L = LaplaceovOperator(2)
omega = LinRange(0.1, 1.95, 40)
it = [iteracija(x->korak_sor(L, x, om), U; tol=1e-3)[2] for om in omega]
plot(omega, it, title = "Konvergenca SOR v odvisnosti od omega")
savefig("sor_konvergenca.svg")
```
//#figure([#image("sor_konvergenca.svg")], caption: [
// Konvergenca SOR v odvisnosti od omega
//])
=== Metoda konjugiranih gradientov
<metoda-konjugiranih-gradientov>
Ker je laplaceova matrika diagonalno dominantna z $minus 4$ na diagonali je
negativno definitna. Zato lahko uporabimo
#link(
"https://en.wikipedia.org/wiki/Conjugate_gradient_method",
)[metodo konjugiranih gradientov]. Algoritem konjugiranih gradientov potrebuje
le množenje z laplaceovo matriko, ne pa tudi samih elementov. Zato lahko
izkoristimo možnosti, ki jih ponuja programski jezik `julia`, da lahko za
#link(
"https://docs.julialang.org/en/v1.0/manual/methods/",
)[isto funkcijo napišemo različne metode za različne tipe argumentov].
Preprosto napišemo novo metodo za množenje #link("@ref")[`*`], ki sprejme
argumente tipa
#link("@ref%20LaplaceovOperator")[`LaplaceovOperator{2}`] in `Matrix`. Metoda
konjugiranih gradientov še hitreje konvergira kot SOR.
```@example
using NumMat
n = 50
U = zeros(n,n)
U[:,1] = sin.(LinRange(0, pi, n))
U[:, end] = U[:, 1]
L = LaplaceovOperator{2}()
b = desne_strani(L, U)
Z, it = conjgrad(L, b, zeros(n, n))
println("Število korakov: $it")
```
|
|
https://github.com/maxhves/maxhves-cv | https://raw.githubusercontent.com/maxhves/maxhves-cv/main/templates/resume.template.typ | typst | //region Constants
// Language
#let resume-language = "en"
// Font families
#let family-primary = "Roboto Serif"
#let family-seconday = "Playfair Display"
// Colors
#let stone-950 = rgb("#0c0a09")
#let stone-800 = rgb("#292524")
#let stone-700 = rgb("#44403c")
#let stone-600 = rgb("#57534e")
#let stone-500 = rgb("#78716c")
#let stone-300 = rgb("#d6d3d1")
// Text size
#let text-large = 18pt
#let text-big = 12pt
#let text-base = 10pt
#let text-small = 8pt
// Font weight
#let font-semibold = 600
#let font-medium = 500
#let font-normal = 400
//endregion
//region Text
#let authortext(body) = {
text(weight: font-medium, size: text-large, font: family-seconday, [#smallcaps(body)])
}
#let smalltext(body) = {
text(fill: stone-700, text-small, [#body])
}
#let sectionheading(body) = {
text(fill: stone-950, size: text-big, font: family-seconday, weight: font-semibold, [#body])
}
#let itemheading(body) = {
text(fill: stone-800, size: text-base, weight: font-medium, [#body])
}
#let itemsubheading(body) = {
text(fill: stone-500, size: text-small, [#body])
}
#let descriptiontext(body) = {
text(fill: stone-600, size: text-base, hyphenate: false, [#body])
}
//endregion
//region Resume
#let resume(
email: "",
phoneNumber: "",
author: "",
website: "",
github: "",
linkedin: "",
body
) = {
// Document metadata
set document(author: author, title: author)
// Document settings
set text(
font: family-primary,
size: text-base,
weight: font-normal,
fill: stone-950,
lang: resume-language
)
// Page setup
set page(
margin: (
top: 32pt,
bottom: 32pt,
left: 32pt,
right: 32pt
),
)
// Section heading
show heading: it => [
#pad(
top: 0pt,
bottom: -8pt,
sectionheading([#it.body])
)
#line(
start: (-8pt, 0pt),
end: (540pt, 0pt),
stroke: 1pt + stone-300
)
]
// Personal details
grid(
columns: (1fr, 2fr, 1fr),
align: center,
// Email and phone number
align(left)[
#stack(
spacing: 8pt,
smalltext(
[#link("mailto:" + email)[#email]]
),
smalltext(
[#link("tel:" + phoneNumber)[#phoneNumber]]
)
)
],
// Name and website
align(center)[
#stack(
spacing: 8pt,
authortext([#author]),
itemsubheading(
[#link("https://" + website)[#website]]
)
)
],
// Github and linkedin
align(right)[
#stack(
spacing: 8pt,
smalltext(
[Github: #strong(
delta: 100,
[#link("https://www.github.com/" + github)[#github]]
)]
),
smalltext(
[Linkedin: #strong(
delta: 100,
[#link("https://www.linkedin.com/in/" + linkedin)[#linkedin]]
)]
)
)
]
)
// Vertical separation space
v(16pt)
// Main content
set par(justify: true)
body
}
//endregion
//region Employment
#let employment(
title: "",
companyName: "",
startDate: "",
endDate: "",
location: "",
description: (),
) = {
pad(
top: 4pt,
bottom: 4pt,
stack(
spacing: 16pt,
grid(
columns: (1fr, 1fr, 1fr),
align: center,
align(left)[
#itemheading([#title])
],
align(center)[
#stack(
spacing: 8pt,
itemheading([#companyName]),
itemsubheading([#location])
)
],
align(right)[
#itemheading([#startDate\-#endDate])
]
),
pad(
left: 4pt,
par(
leading: 8pt,
descriptiontext([#description])
)
)
)
)
}
//endregion
//region Education
#let education(
location: "",
institution: "",
startDate: "",
endDate: "",
degree: "",
) = {
pad(
top: 4pt,
bottom: 4pt,
stack(
spacing: 16pt,
grid(
columns: (1fr, 1fr, 1fr),
align: center,
align(left)[
#itemheading([#location])
],
align(center)[
#itemheading([#institution])
],
align(right)[
#itemheading([#startDate\-#endDate])
]
),
pad(
left: 4pt,
par(
leading: 8pt,
descriptiontext([#degree])
)
)
)
)
}
//endregion
//region Projects
#let project(
name: "",
url: [],
description: []
) = {
pad(
top: 4pt,
bottom: 4pt,
stack(
spacing: 8pt,
itemheading([#name]),
itemsubheading([#emph(url)]),
pad(
top: 4pt,
left: 4pt,
par(
leading: 8pt,
descriptiontext([#description])
)
)
)
)
}
//endregion
//region Technical skills
#let technicalSkill(
domain: "",
skills: []
) = {
pad(
top: 4pt,
bottom: 4pt,
stack(
spacing: 16pt,
itemheading([#domain]),
pad(
left: 4pt,
par(
leading: 8pt,
descriptiontext([#skills])
)
)
)
)
}
//endregion
//region Helpers
/*
Allows hiding or showing full resume dynamically using global variable. This can
be helpful for creating a single document that can be rendered differently depending on
the desired output, for cases where you'd like to simultaneously render both a full copy
and a single-page instance of only the most important or vital information.
*/
#let hide(should-hide, content) = {
if not should-hide {
content
}
}
//endregion |
|
https://github.com/vonhyou/typst-resume-template | https://raw.githubusercontent.com/vonhyou/typst-resume-template/master/header.typ | typst | // Telephone numbers in Canada/ USA
#let phone_number_format(phone) = {
let number = phone.text
let area = number.slice(0, 3)
let prefix = number.slice(3, 6)
let line_number = number.slice(6)
text(
font: "TeX Gyre Cursor",
"(" + area + ")" + prefix + "-" + line_number
)
}
#let adjusted_line() = {
v(8pt, weak: true)
line(length: 100%)
v(8pt, weak: true)
}
#let social_links(social: ()) = {
for i, item in social {
let href = item.at(0)
let content = item.at(1)
link(href)[#text(font: "TeX Gyre Cursor", " " + content)]
}
}
#let header(
name: "<NAME>",
address: "6299 South St., Halifax, NS B3H 4R2",
phone: "9021234567",
email: "<EMAIL>",
social: ()
) = {
set align(right)
text(size: 17pt, weight: "bold", smallcaps(name))
adjusted_line()
set text(font: "Libre Baskerville")
text(size: 10pt,address)
linebreak()
social_links(social: social)
linebreak()
link("tel:" + phone)[#phone_number_format[#phone]]
text(" or ")
link("mailto:" + email)[#text(font: "TeX Gyre Cursor", email)]
}
|
|
https://github.com/hei-templates/hevs-typsttemplate-thesis | https://raw.githubusercontent.com/hei-templates/hevs-typsttemplate-thesis/main/README.md | markdown | MIT License | <h1 align="center">
<br>
<img src="./04-resources/logos/hei-en.svg" alt="HEI Logo Logo" width="300" height="200">
<img src="./04-resources/logos/synd-light.svg" alt="HEI Logo Logo" width="300" height="200">
<br>
HEI-Vs Engineering School - Typst Thesis Template
<br>
</h1>
[](https://github.com/tschinz/hevs-typsttemplate-thesis/blob/master/05-pdf/thesis.pdf) [](https://github.com/tschinz/hevs-typsttemplate-thesis/raw/master/05-pdf/thesis.pdf)
A Typst template for the HES-SO//Valais Wallis Bachelor thesis.
> **Warning**
> Disclaimer, this is an unofficial typst template not supported by the HEI-Vs. Use at your own risk, no support is provided for installation or use. You have been warned.
# Table of contents
<p align="center">
<a href="#features">Features</a> •
<a href="#getting-started">Getting started</a> •
<a href="#contributing">Contributing</a> •
<a href="#credits">Credits</a> •
<a href="#find-us-on">Find us on</a>
</p>
## Features
[(Back to top)](#table-of-contents)
* Title page with official layout
* Table of contents, Table of figures, Table of tables, Table of listings
* Abstract
* Nice title styles for chapter and appendices
* Chapter table of contents (minitoc)
* Bibliography
* Glossary
* Code highlighting
* Nice default typography settings
* Custom Boxes
## Getting started
[(Back to top)](#table-of-contents)
### Installation
This document is made for typst v0.11.0.
#### MacOS
```bash
# [homebrew](https://brew.sh)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/
install.sh)"
# [just](https://just.systems)
brew install just
# [typst](https://github.com/typst/typst)
brew install typst
```
#### Linux & MacOS (via Rust)
```bash
# [rust](https://www.rust-lang.org/tools/install)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# [just](https://just.systems)
cargo install just
# [typst](https://github.com/typst/typst)
cargo install typst
```
#### Windows
Open a Windows Powershell as Administrator

```powershell
# [chocolatey](https://chocolatey.org)
# ensure to use a administrative powershell
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
```
Open a new Windows Powershell as Administrator
```powershell
# [just](https://just.systems)
choco install just
# [typst](https://github.com/typst/typst)
choco install typst
# [vscode](https://code.visualstudio.com/)
choco install vscode vscli
# [git](https://git-scm.com/downloads)
choco install git.install
```
### How to use
1. Modify variables in `01-settings/metadata.typ`
2. Write your thesis there are plugins for VS-Code and Sublimetext available
3. Use the given justfile or typst directly to build the PDF
With the justfile
```bash
just
Available recipes:
clean # cleanup intermediate files
default # List all commands
info # Information about the environment
install # install required sw
open file_name=doc_name # open pdf
pdf file_name=doc_name # build, rename and copy a typ file to a pdf
pdf-all file_name=doc_name # build, rename and copy a typ file in all variants
watch file_name=doc_name # watch a typ file for continuous incremental build ```
```
With typst directly
```bash
typst c main.typ # compiles thesis to main.pdf
typst w main.typ # watches all documents and incrementally compiles to main.pdf
```
## Contributing
[(Back to top)](#table-of-contents)
1. Take a look at the [issues](https://github.com/tschinz/hevs-typsttemplate-thesis/issues) issues with the "Help wanted" tag
2. Choose something or open a new [issue](https://github.com/tschinz/hevs-typsttemplate-thesis/issues)
3. Fork the repo, fix the problem in a branch
4. Rebase your branch if needed
5. Submit a [pull request](https://github.com/tschinz/hevs-typsttemplate-thesis/pulls)
## Help
[(Back to top)](#table-of-contents)
[](https://github.com/tschinz/hevs-typsttemplate-thesis/blob/master/guide-to-typst.pdf) [](https://github.com/tschinz/hevs-typsttemplate-thesis/raw/master/guide-to-typst.pdf)
## Credits
[(Back to top)](#table-of-contents)
* All guys from Typst
* <NAME>
## Find us on
[(Back to top)](#table-of-contents)
* Webpage [hevs.ch](https://www.hevs.ch/synd)
* LinkedIn [HEI Valais-Wallis](https://www.linkedin.com/showcase/school-of-engineering-valais-wallis/)
* Youtube [HES-SO Valais-Wallis](https://www.youtube.com/user/HESSOVS/)
* Twitter [@hessovalais](https://twitter.com/hessovalais)
* Facebook [@hessovalais](https://www.facebook.com/hessovalais)
|
https://github.com/berceanu/activity-report | https://raw.githubusercontent.com/berceanu/activity-report/main/README.md | markdown | BSD 3-Clause "New" or "Revised" License | # activity-report
[Typst](https://github.com/typst/typst)-based template for activity reports.
## Usage
```
# produces usage.pdf
$ typst compile usage.typ
```
In case you have old printer drivers, rasterize the PDF file via
```
# produces usage.raster.pdf
$ bash rasterizepdf.sh usage.pdf
```
|
https://github.com/simon-epfl/notes-ba2-simon | https://raw.githubusercontent.com/simon-epfl/notes-ba2-simon/main/fds/fds-tricks-1.typ | typst | #set text(font: "DejaVu Sans")
#show heading.where(level: 1): contents => text(size: 20pt, contents)
#show heading: contents => pad(bottom: 10pt, contents)
#set quote(block: true)
#set heading(numbering: (ignore_first, ..n) => {
if (n.pos().len() != 0) {
numbering("1.1.", ..n)
}
})
#let stick-together(a, threshold: 3em) = {
block(a + v(threshold), breakable: false)
v(-1 * threshold)
}
= Tricks de FDS (part I)
== Calculer l'exposant IEEE-754 plus rapidement
Dans tous les cas, peu importe le nombre de bits :
- `0111111111` représente un exposant de 0.
- `1000000000` réprésente un exposant de 1.
Si on veut un exposant de -3, on part de `0111111111` et on enlève 3 #sym.arrow `0111111100`.
Si on veut un exposant de 3, on part de `1000000000` (1) et on ajoute *2* #sym.arrow `1000000010`.
== Calculer les nombres binaires plus rapidement
On s'approche très près de n'importe quel nombre avec la table de 16. On écrit ensuite le nombre en hexadécimal, puis on convertit en binaire.
*Table de 16*
#table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
table.header(
[*Multiple*], [*16 \* Multiple *],
),
"1", "16",
"2", "32",
"3", "48",
"4", "64",
"5", "80",
"6", "96",
"7", "112",
"8", "128",
"9", "144",
"10", "160",
)
== Convertir de Gray Code #sym.arrow.r.l.double Binary
Binary vers Gray Code : \
#sym.arrow on copie le MSB, puis on XOR chaque couple de bits qui suit.
Gray Code vers Binary : \
#sym.arrow on copie le MSB, puis à chaque 1 dans le gray code (ce qui signifie qu'il y avait un changement dans la chaîne originale) on switch entre 0 et 1.
== Comprendre la multiplication en 2's Complement
#image("assets/mult.png")
Pourquoi est-ce qu'on doit negate le dernier multiplicant ? On veut par exemple calculer -17x14.
- Si on fait -17x14 = 101111 x 001110, on fait 2x-17 + 4x-17, etc. jusqu'à avoir 14x-17. Pas besoin de negate !
- Par contre 14x-17 = 001110 x 101111, on fait 14x2 + 14x4 + 14x8 *- 14x32* (c'est pour ça qu'on doit negate le multiplicant).
== Pourquoi on invert, +1 pour changer de signe en 2's complement
Imaginons qu'on ait 17. On cherche donc -17. Inverser les bits de 17 revient à trouver les bits qui, sommés à ceux de 17, donne uniquement des 1. Or, uniquement des 1, en 2's complement, donne -1.
Donc en inversant 17, on a trouvé C tel que 17 + C = -1. Mais nous, on cherche N tel que N = -17 soit 17 + N = 0. Donc on ajoute +1 au complémentaire de C !
== Comment savoir combien de bits de fractions nécessaires après une opération ?
Pour une addition, ce sera toujours le max(f_x1, f_x2). Parce qu'il ne peut pas y avoir de débordement à droite, toujours à gauche.
Oour une multiplication, ce sera toujours f_x1 + f_x2. Pourquoi ? P. ex. en décimal quand on fait ax10^-3 x bx10^-5 ça donne toujours un résultat le plus faible en 10^-8.
dynamic range -> te dit si le système de nombre peut gérer des très grands nombres et de très petits nombres à la fois.
== Propriétés en floating point
#image("assets/accuracy_floating_point.png")
#image("assets/resolution_floating_point.png")
== Pourquoi est-ce qu'on fait un tie to even ?
Si on veut faire une division après l'arrondi (un shift), on perd le risque de faire une nouvelle erreur. Par exemple 3.5 #sym.arrow on peut soit faire 3 soit faire 4. Si on fait 3/2 = 1 et 4/2 = 2. 3.5/2 = 1.75, 2 est plus proche.
== Map de Karnaugh
pour faire une karnaugh map #sym.arrow mettre bien les nombres qui ont une unique différence entre eux à côté 10 11 01 00 (10 et 01 sont à côté parce qu'on considère un tableau comme une boule 3D).
#image("assets/karnaugh.png")
== Pourquoi on écrit la P.O.S en prenant les lignes à zéro et en complémentant ?
En fait on "fuit les zéros", c-a-d qu'on prend toutes les lignes qui donnent zéro, et pour chaque ligne, pour éviter de tomber dedans, on sait qu'il suffit qu'au moins une variable ait une valeur différente. Et on combine le tout avec un "et" pour contrôler qu'on a une variable différente nous permettant de nous "échapper" de tous les zéros.
== Comment faire une soustraction SIMPLE en binaire ?
- on choisit toujours le nombre le plus grand au-dessus (especially en IEEE-754), et si au lieu de faire a-b on fait b-a, on ajoute automatiquement un signe - au résultat.
- sinon, en 2's complement il vaut mieux obtenir la représentation négative de notre nombre et *sommer* les deux.
- sinon, si on obtient une retenue infinie, on ne tient compte *que du premier 1*.
== Comment passer d'une S.O.P à une P.O.S ?
pour passer d'une SOP à une POS, double négation, puis développement, puis application de la négation
#image("assets/pos.png")
== Comment comparer rapidement deux expressions
- si on a les minterms (les S.O.P), on peut les numéroter en fonction des termes positifs (par ex. ab(!c) représente 110, 6).
- si on a les maxterms (les P.O.S), on peut aussi les numéroter en fonction des termes négatifs (par ex. ab(!c) représente 001, 1).
Pour passer de maxterms M1, M4 à la liste des minterms, on prend les complément (m0, m2, m3, m5, etc.).
== Comprendre les delays et les fan-in/fan-out
#image("assets/fanout.png")
Pourquoi est-ce que l'inverter p2 prend 20ns à charger le gate AND à p7 et pas juste 10ns ? (comme il est branché à un seul input ?)
En fait c'est parce que les gate AND à 2 inputs ne sont pas construits de la même façon que les gates à 3 ou 4 inputs, et on affirme dans ce cours que le temps pour charger un input d'un gate est proportionnel au nombre d'inputs que ce gate doit gérer.
Ainsi charger un unique input (donc fan-out de 1) d'un gate à 3 inputs prend 3 fois plus de temps que charger un unique input d'un gate à 1 input.
== Trick cool pour obtenir une full P.O.S
Quand on part d'une P.O.S pas complète, on ajoute juste les termes manquants en (a)(!a) par exemple, puis on factorise, et on utilise que a + (x)(y) = (a+x)(a+y)
$ (a+b)(b+c)(overline(a) + overline(c)) \
equiv (a+b+overline(c)c)(overline(a)a + b + c)(overline(a) + overline(b)b + overline(c)) \
equiv (a+(b+overline(c))(b + c))((overline(a) + b)(a + b) + c)((overline(a) + overline(b))(overline(a) + b) + overline(c)) \
equiv (a+b+overline(c))(a + b + c)(overline(a) + b + c)(a + b + c)(overline(a) + overline(b) + overline(c))(overline(a) + b + overline(c)) \
equiv (a+b+overline(c))(overline(a) + b + c)(a + b + c)(overline(a) + overline(b) + overline(c))(overline(a) + b + overline(c))
$
*ça donne une technique très simple pour obtenir une full P.O.S.* : quand on a $ (a + b) equiv (a + b + overline(c))(a + b + c) $
== Arrondir rapidement en floating point
On écrit la mantisse avec un bit de plus. On ajoute +1. On prend le résultat tronqué.
== Addition/Soustraction en floating point
On aligne les exposants. On additionne les mantisses *en n'oubliant surtout pas de faire toujours apparaître le hidden bit!* On normalise.
== Convertir un circuit en NAND et NOR
pour les NAND : écrire la Sum of Products (elle n'a pas besoin d'être une full SOP!), puis appliquer 2 fois la De Morgan.
pour les NOR : écrire la Product of Sums (elle n'a pas besoin d'être une full POS!), puis appliquer 2 fois la De Morgan.
ne pas oublier qu'on peut créer un inverter en mettant en chaîne deux NAND ou deux NOR, donc on peut toujours obtenir un OR ou un AND avec des NAND ou des NOR.
== Checklist verilog
- ne pas oublier de déclarer en `reg` quand on fait du combinatoire
- le `case` n'a pas de `begin` ni de point-virgule mais un `endcase`
- ne pas oublier de faire un cas `default` dans les `case`
- ne pas oublier d'attribuer des valeurs par défaut aux variables modifiées en haut de tous les blocs `always`
- ne pas oublier la syntaxe `always @(variable1 or variable2)` (exécuté quand une des deux variables *change*) ou `always @(*)`
- ne pas oublier qu'on fait `[4:0]` pour déclarer un input à *5 variables* et pas `[0:5]` (mauvais sens + un bit de trop)
#pagebreak()
== Un peu de cours
- in 2's complement : complement and +1 to negate
- detect overflow : wrong sign (summing 2 nb of different signs never produces an overflow)
- PMOS : s'allume quand l'input est 0
- NMOS : s'allume quand l'input est 1
- (f est la fréquence, C la capacitance du condensateur, et V_DD la tension du circuit) $ P_D = f*C*V_D^2 $
- weighted number systems: $ x = sum W_i*X_i $
- radix number systems: $ W_i = W_(i-1) * R_i $
- canonical number system D means that each digit can take all the values between 0 and R (actually I don't know any other representation)
- precision (fixed-point) : the maximum number of non-zero bits (m + f)
- resolution : the smallest non-zero magnitude representable
- range : the difference between the most positive and the most negative number representable
- accuracy : the magnitude of the maximum difference between a real value and its representation
- dynamic range : ratio of the max absolute value representable an the minimum non-zero positive value representable
- quand on additionne deux nombres en floating point, on garde l'exposant le plus grand (et on modifie la mantisse du plus petit pour qu'il ait le même exposant), pour minimiser l'erreur *note: c'est le même fonctionnement pour le block floating point!*
#pagebreak()
=== À quoi servent les tristate buffers?
Quand on a un bus de données (c'est à dire une sorte de voie sur laquelle des modules peuvent se connecter), on veut que ceux-ci puissent lire et écrire dedans. Sauf qu'on doit décider qui peut écrire à un moment donné, ils ne peuvent pas tous écrire en même temps :
#image("assets/tristate.png")
Les tristate buffers permettent de résoudre ce problème. Ils ont 3 états : 0, 1, et Z (pour high impedance). Quand le tristate est à Z, il est déconnecté du bus (partie écriture), et les autres modules peuvent écrire dessus. Quand il est à 0 ou 1, il peut écrire sur le bus. (voir https://www.youtube.com/watch?v=_3cNcmli6xQ)
versus implémentation MUX (beaucoup moins propre) :
#image("assets/mux.png", width: 95%)
|
|
https://github.com/daniel-eder/typst-template-jku | https://raw.githubusercontent.com/daniel-eder/typst-template-jku/main/src/template/styles/header.typ | typst | // SPDX-FileCopyrightText: 2023 <NAME>
//
// SPDX-License-Identifier: Apache-2.0
#let buildMainHeader(mainHeadingContent) = {
[
#align(center, smallcaps(mainHeadingContent))
#line(length: 100%)
]
}
#let buildSecondaryHeader(mainHeadingContent, secondaryHeadingContent) = {
[
#smallcaps(mainHeadingContent) #h(1fr) #emph(secondaryHeadingContent)
#line(length: 100%)
]
}
// To know if the secondary heading appears after the main heading
#let isAfter(secondaryHeading, mainHeading) = {
let secHeadPos = secondaryHeading.location().position()
let mainHeadPos = mainHeading.location().position()
if (secHeadPos.at("page") > mainHeadPos.at("page")) {
return true
}
if (secHeadPos.at("page") == mainHeadPos.at("page")) {
return secHeadPos.at("y") > mainHeadPos.at("y")
}
return false
}
#let header() = {
locate(loc => {
// Find if there is a level 1 heading on the current page
let nextMainHeading = query(selector(heading).after(loc), loc).find(headIt => {
headIt.location().page() == loc.page() and headIt.level == 1
})
if (nextMainHeading != none) {
return buildMainHeader(nextMainHeading.body)
}
// Find the last previous level 1 heading -- at this point surely there's one :-)
let lastMainHeading = query(selector(heading).before(loc), loc).filter(headIt => {
headIt.level == 1
}).last()
// Find if the last level > 1 heading in previous pages
let previousSecondaryHeadingArray = query(selector(heading).before(loc), loc).filter(headIt => {
headIt.level > 1
})
let lastSecondaryHeading = if (previousSecondaryHeadingArray.len() != 0) {previousSecondaryHeadingArray.last()} else {none}
// Find if the last secondary heading exists and if it's after the last main heading
if (lastSecondaryHeading != none and isAfter(lastSecondaryHeading, lastMainHeading)) {
return buildSecondaryHeader(lastMainHeading.body, lastSecondaryHeading.body)
}
return buildMainHeader(lastMainHeading.body)
})
} |
|
https://github.com/jamesrswift/ionio-illustrate | https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/src/lib.typ | typst | MIT License | #import "@preview/cetz:0.1.2"
#import "util.typ": *
#import "defaults.typ": *
#import "extras.typ"
#let mass-spectrum-modes =(
"single", "dual-reflection", "dual-shift"
)
/// Returns an object representing mass spectrum content.
///
/// - data1 (array): The mass spectrum in the format of a 2D array, or an array of dictionarys.
/// By default, the mass-charges ratios are in the first column, and the relative
/// intensities are in the second column.
/// - data2 (array): similar format as `data1`, but to contain a second mass spectrum.
/// - args (dictionary): Override default behaviour of the mass spectrum by overriding methods,
/// or setting fields.
/// -> dictionary, none
#let mass-spectrum(
args: (:),
data1, data2: none,
) = {
let prototype = (
// --------------------------------------------
// Public member data
// --------------------------------------------
data1: data1,
data2: data2,
keys: (
mz: 0,
intensity: 1
),
size: (14,5),
range: (40, 400),
style: mass-spectrum-default-style,
labels: (
x: [Mass-Charge Ratio],
y: [Relative Intensity (%)]
),
linestyle: (this, idx)=>{},
plot-extras: (this)=>{},
plot-extras-bottom: (this)=>{},
// --------------------------------------------
// "Private" member data
// --------------------------------------------
_reflected: false
)
// Asserts
assert(type(prototype.keys.mz) in (int, str))
assert(type(prototype.keys.intensity) in (int, str))
// Overrides. This ensures the prototype is properly formed by the time we need it
prototype = merge-dictionary(prototype,args)
prototype.style = merge-dictionary(mass-spectrum-default-style,prototype.style)
// --------------------------------------------
// Methods : Utility
// --------------------------------------------
/// Get the intensity of a mass-peak for a given mass-charge ratio
//
// - mz (string, integer, float): Mass-charge ratio for which the intensity is being queried
// -> float
prototype.get-intensity-at-mz = (mz, input: auto) => {
let data = (if input == auto {prototype.data1} else {input})
// Search all mz matching query
let intensity_arr = data.filter(
it=>float(it.at(prototype.keys.mz, default:0))==mz
)
if ( intensity_arr.len() == 0 ) {return 0}
// Return "first" hit
return float(
intensity_arr.at(0).at(prototype.keys.intensity)
)
}
// --------------------------------------------
// Methods : Additional Content
// --------------------------------------------
prototype.callout-above = extras.callout-above
prototype.callout-aside = extras.callout-aside
prototype.callipers = extras.callipers
prototype.title = extras.title
prototype.cetz-raw = extras.cetz-raw
prototype.content = extras.content
// --------------------------------------------
// Methods : Property Setup, Internal
// --------------------------------------------
prototype.setup-plot = (ctx, x, y, ..arguments) => {
cetz.axes.scientific(
size: prototype.size,
// Axes
top: none, bottom: x,
right: none, left: y, // TODO: Optional secondary axis
..arguments
)
}
prototype.setup-axes = (reflection: false) => {
let axes = (:)
axes.x = cetz.axes.axis(
min: prototype.range.at(0),
max: prototype.range.at(1),
label: prototype.labels.x,
//ticks: (step: 10, minor-step: none)
)
axes.y = cetz.axes.axis(
min: if reflection {-110} else {0},
max: 110,
label: prototype.labels.y,
ticks: (step: if reflection {40} else {20}, minor-step: none)
)
return axes
}
// --------------------------------------------
// Methods : Rendering
// --------------------------------------------
prototype.display-extras = (body, axes: (:), sy: 1, dx: 0, plot-ctx: (:)) => {
// Assert we are drawing commands
let body = if body != none { body } else { () }
for cmd in body {
assert(
type(cmd) == dictionary and "type" in cmd,
message: "Expected plot sub-command in plot body, got " + repr(cmd)
)
}
// Prepare
for i in range(body.len()) {
if "plot-prepare" in body.at(i) {
body.at(i) = (body.at(i).plot-prepare)(body.at(i), plot-ctx)
}
}
// Transform coordinates
for i in range(body.len()) {
if "coordinates" in body.at(i).keys() {
body.at(i).coordinates = map( body.at(i).coordinates, (it) => {
(it.at(0) + dx, it.at(1) * sy)
})
}
if ( sy < 0 ){
if "anchors" in body.at(i).keys() {
body.at(i).anchors = body.at(i).anchors.map( (it) => {
if it == "bottom" {return "top"}
if it == "top-left" {return "bottom-left"}
})
}
}
}
// panic(body)
// Stroke + Mark data
for d in body {
//cetz.axes.axis-viewport(prototype.size, axes.x, axes.y, {
// cetz.draw.anchor("center", (0, 0))
if "style" in d {cetz.draw.set-style(..d.style)}
if "plot-fill" in d {(d.plot-fill)(d, plot-ctx)}
if "plot-stroke" in d {(d.plot-stroke)(d, plot-ctx)}
//})
}
}
// ms.display-single-peak handles the rendering of a single mass peak
prototype.display-single-peak = (idx, mz, intensity, arguments) => {
if (mz > prototype.range.at(0) and mz < prototype.range.at(1) ){
cetz.draw.line(
(mz, 0),
(rel: (0,intensity)),
..arguments, // Global style is overriden by individual style
..(prototype.linestyle)(prototype, idx),
)
}
}
prototype.display-single-data = (dataset, style, scale: 1, dx: 0) => {
if dataset.len() > 0 {
for (i, row) in dataset.enumerate() {
let x = float(row.at(prototype.keys.mz))
let y = float(row.at(prototype.keys.intensity))
(prototype.display-single-peak)(x, x + dx, y * scale, style)
}
}
}
// The ms.display-single method is responsible for rendering
// a single mass spectra plot
prototype.display-single = (ctx) => {
import cetz.draw: *
let (x,y) = (prototype.setup-axes)()
// Style
let style = merge-dictionary(
merge-dictionary(mass-spectrum-default-style, cetz.styles.resolve(ctx.style, (:), root: "mass-spectrum")),
prototype.style
)
cetz.axes.axis-viewport(prototype.size, x, y,{
// Prepare context argument
let plot-ctx = (prototype: prototype, reflected: false)
// Draw top mass spectrum
(prototype.display-extras)(
(prototype.plot-extras)(prototype),
axes: (x:x, y:y),
plot-ctx: plot-ctx
)
(prototype.display-single-data)(prototype.data1, style.peaks)
})
// Setup scientific axes
(prototype.setup-plot)(ctx, x, y, ..style.axes)
}
// The ms.display-dual-reflection method is responsible for rendering
// multiple mass spectra on the same plot by reflecting one of the plots
prototype.display-dual-reflection = (ctx) => {
// If there is only one dataset, fail safely quickly
if ( prototype.data2 == none){
return (prototype.display-single)(ctx)
}
import cetz.draw: *
let (x,y) = (prototype.setup-axes)(reflection: true)
// Style
let style = merge-dictionary(
merge-dictionary(mass-spectrum-default-style, cetz.styles.resolve(ctx.style, (:), root: "mass-spectrum")),
prototype.style
)
let style-data1 = merge-dictionary(style, prototype.style.data1).peaks
let style-data2 = merge-dictionary(style, prototype.style.data2).peaks
cetz.axes.axis-viewport(prototype.size, x, y,{
// Prepare context argument
let plot-ctx = (prototype: prototype, reflected: false)
// Draw top mass spectrum
(prototype.display-extras)(
(prototype.plot-extras)(prototype),
axes: (x:x, y:y),
plot-ctx: plot-ctx
)
(prototype.display-single-data)(prototype.data1, style-data1, scale: 1)
// Draw bottom mass spectrum
let plot-ctx = (prototype: prototype, reflected: true)
(prototype.display-extras)(
(prototype.plot-extras-bottom)(prototype),
axes: (x:x, y:y),
sy: -1,
plot-ctx: plot-ctx
)
(prototype.display-single-data)(prototype.data2, style-data2, scale: -1)
// Draw mid-line
cetz.draw.line((prototype.range.at(0), 0), (prototype.range.at(1), 0), ..style.axes)
})
// Setup scientific axes
(prototype.setup-plot)(ctx, x, y, ..style.axes)
}
// The ms.display-dual-shift method is responsible for rendering
// multiple mass spectra on the same plot by shifting one of the plots
prototype.display-dual-shift = (ctx) => {
// If there is only one dataset, fail safely quickly
if ( prototype.data2 == none){
return (prototype.display-single)(ctx)
}
import cetz.draw: *
let (x,y) = (prototype.setup-axes)()
// Style
let style = merge-dictionary(
merge-dictionary(mass-spectrum-default-style, cetz.styles.resolve(ctx.style, (:), root: "mass-spectrum")),
prototype.style
)
let style-data1 = merge-dictionary(style, prototype.style.data1).peaks
let style-data2 = merge-dictionary(style, prototype.style.data2).peaks
cetz.axes.axis-viewport(prototype.size, x, y,{
// Prepare context argument
let plot-ctx = (prototype: prototype, reflected: false)
let d = style.shift-amount
// Draw top mass spectrum
(prototype.display-extras)(
(prototype.plot-extras)(prototype),
axes: (x:x, y:y), dx:-d,
plot-ctx: plot-ctx
)
(prototype.display-single-data)(prototype.data1, style-data1, dx:-d)
// Draw bottom mass spectrum
let plot-ctx = (prototype: prototype, reflected: true)
(prototype.display-extras)(
(prototype.plot-extras-bottom)(prototype),
axes: (x:x, y:y), dx:+d,
plot-ctx: plot-ctx
)
(prototype.display-single-data)(prototype.data2, style-data2, dx:+d)
})
// Setup scientific axes
(prototype.setup-plot)(ctx, x, y, ..style.axes)
}
/// The ms.display method is responsible for rendering
prototype.display = (mode: "single") => {
assert(mode in mass-spectrum-modes, message: "Invalid mass-spectrum mode")
let render = (
if mode == "single" {prototype.display-single} else
if mode == "dual-reflection" {prototype.display-dual-reflection} else
if mode == "dual-shift" {prototype.display-dual-shift}
)
// Setup canvas
cetz.canvas(cetz.draw.group(render))
}
return prototype
}
#let MolecularIon(charge:none) = [M#super()[#charge+]] |
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/icml/README.md | markdown | MIT License | # International Conference on Machine Learning (ICML)
## Usage
You can use this template in the Typst web app by clicking _Start from
template_ on the dashboard and searching for `lucky-icml`.
Alternatively, you can use the CLI to kick this project off using the command
```shell
typst init @preview/lucky-icml
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `icml2024` function with the following named
arguments.
- `title`: The paper's title as content.
- `authors`: An array of author dictionaries. Each of the author dictionaries
must have a name key and can have the keys department, organization,
location, and email.
- `abstract`: The content of a brief summary of the paper or none. Appears at
the top under the title.
- `bibliography`: The result of a call to the bibliography function or none.
The function also accepts a single, positional argument for the body of the
paper.
- `accepted`: If this is set to `false` then anonymized ready for submission
document is produced; `accepted: true` produces camera-redy version. If
the argument is set to `none` then preprint version is produced (can be
uploaded to arXiv).
The template will initialize your package with a sample call to the `icml2024`
function in a show rule. If you want to change an existing project to use this
template, you can add a show rule at the top of your file.
## Issues
This template is developed at [daskol/typst-templates][1] repo. Please report
all issues there.
### Running Title
1. Runing title should be 10pt above the main text. With top margin 1in it
gives that a solid line should be located at 62pt. Actual, position is 57pt
in the original template.
2. Default value between header ruler and header text baseline is 4pt in
`fancyhdr`. But actual value is 3pt due to thickness of a ruler in 1pt.
### Page Numbering
1. Basis line of page number should be located 25pt below of main text. There
is a discrepancy in about ~1pt.
### Heading
1. Required space after level 3 headers is 0.1in or 7.2pt. Actual space size is
large (e.g. distance between Section 2.3.1 header and text after it about
12pt).
### Figures and Tables
1. At the moment Typst has limited support for multi-column documents. It
allows define multi-column blocks and documents but there is no ability to
typeset complex layout (e.g. page width figures or tables in two-column
documents).
### Citations and References
1. There is a small bug in CSL processor which fails to recognize bibliography
entries with `chapter` field. It is already report and will be fixed in the
future.
2. There is no suitable bibliography style so we use default APA while ICML
requires APA-like style but not exact APA. The difference is that ICML
APA-like style places entry year at the end of reference entry. In order to
fix the issue, we need to describe ICML bibliography style in CSL-format.
3. In the original template links are colored with dark blue. We can reproduce
appearance with some additional effort. First of all, `icml2024.csl` shoule
be updated as follows.
```
diff --git a/icml/icml2024.csl b/icml/icml2024.csl
index 3b9e9a2..3fe9f74 100644
--- a/icml/icml2024.csl
+++ b/icml/icml2024.csl
@@ -1648,7 +1648,8 @@
<key macro="date-bib" sort="ascending"/>
<key variable="status"/>
</sort>
- <layout prefix="(" suffix=")" delimiter="; ">
+ <!-- NOTE: Prefix and suffix parentheses are removed. -->
+ <layout delimiter="; ">
<group delimiter=", ">
<text macro="author-intext"/>
<text macro="date-intext"/>
```
Then instead of convenient citation shortcut `@cite-key1 @cite-key2`, one
should use special procedure `refer` with variadic arguments.
```typst
#refer(<cite-key1>, <cite-key2>)
```
[1]: example-paper.latex.pdf
[2]: example-paper.typst.pdf
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week4.typ | typst | #import "../../utils.typ": *
#subsection([State Pattern (for objects)])
#text(red)[often misunderstood]
#set text(size: 14pt)
Problem | Allow an object to alter its behavior when its internal state changes.
The object will appear to change its class.\
Context | Behavior should change depending on state without needing 10000 if
statements(aka not yandere dev)\
#set text(size: 11pt)
// images
#align(
center, [#image("../../Screenshots/2023_10_06_09_57_36.png", width: 80%)],
)
#align(
center, [Simple clock, 3 modes -> display time, change hours, and change minutes.\
On mode change you get to a different state.
#image("../../Screenshots/2023_10_13_10_23_32.png", width: 70%)],
)
#align(
center, [#image("../../Screenshots/2023_10_13_10_24_49.png", width: 90%)
- ClockDataContext: Handles data for the pattern -> all states need to access this
- ClockState: Parentobject that will redirect calls to each state
- concrete states: handle calls that will be used
- OcjectsClickStateMachine: needs both a reference of CLockDataContext(readonly
for this object) and the clockstate],
)
```rs
// self is necessary to ensure object safety
trait State {
fn operation(&self) {
println!("not implemented");
}
}
struct Context {
pub state: Box<dyn State>,
}
struct StateStart {}
impl State for StateStart {
fn operation(&self) {
println!("Game started");
}
}
struct StateEnd {}
impl State for StateEnd {
fn operation(&self) {
println!("Game ended");
}
}
fn main() {
let mut grengeng = Context {
// traits sizes are not known at compile time
// create a pointer to interface with V-table
state: Box::new(StateStart {}),
};
grengeng.state.operation();
grengeng.state = Box::new(StateEnd {});
grengeng.state.operation();
}
```
#columns(2, [
#text(green)[Benefits]
- abstracts functionality away
- no ifs needed to check for current state
#colbreak()
#text(red)[Liabilities]
- fixed structure -> lot of work when changed
- similar to visitor pattern
- pattern is often overkill
- virtual classes are often used -> performance
])
#subsection([State Pattern (Methods for States)])
#set text(size: 14pt)
Problem | Wile the object state pattern does solve the underlying problem, it
also creates indirection problems which means a complicated structure that is
hard to change later on. In order to avoid this, we can use function pointers
instead.\
#set text(size: 11pt)
// images
#align(
center, [#image("../../Screenshots/2024_01_02_02_54_35.png", width: 90%)
],
)
- all methods are created within the MethodsClockStateMachine
- tick is always the same
- increment, nextHour, nextMinute
- 3 different functions for 3 different modes
- nextModeDisplayingTime, nextModeSettingHours,NextModeSettingMinutes
- 3 different functions for 3 different modes
- The Mode object has 3 lambdas which will be created with the respective
functions for each mode to represent
- note that the functions inside Mode need to fit -> java -> runnable, rust ->
fn(i32) -> i32
```java
public class MethodsClockStateMachine implements ClockStateMachine {
// STATE DEFINITIONS (with transition to other states)
private final Mode displayingTime = new Mode( // increment, tick, changeMode
this::doNothing,
this::updateTime,
this::nextModeSettingHours);
private final Mode settingHours = new Mode(
this::nextHour,
this::doNothing,
this::nextModeSettingMinutes);
private final Mode settingMinutes = new Mode(
this::nextMinute,
this::doNothing,
this::nextModeDisplayingTime);
// initial state
private Mode behaviour = displayingTime;
// data for state management implementation
private int hour;
private int minute;
private int second;
@Override
public int getHour() { return hour; }
@Override
public int getMinute() { return minute; }
@Override
public int getSecond() { return second; }
/**
* State machine construction logic goes here...
*/
public MethodsClockStateMachine(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
/**
* Forward 'change mode' event to current state.
*/
@Override
public void changeMode() {
behaviour.getChangeMode().run();
}
/**
* Forward 'increment' event to current state.
*/
@Override
public void increment() {
behaviour.getIncrement().run();
}
/**
* Forward 'tick' event to current state.
*/
@Override
public void tick() {
behaviour.getTick().run();
}
// state management implementation
private void nextMode(Mode nextBehaviour) {
behaviour = nextBehaviour;
}
private void doNothing() { }
private void updateTime() {
if (++second == 60) {
second = 0;
if (++minute == 60) {
minute = 0;
hour = (hour + 1) % 24;
}
}
}
private void nextHour() { hour = (hour + 1) % 24; }
private void nextMinute() { minute = (minute + 1) % 60; }
private void nextModeDisplayingTime() { nextMode(displayingTime); }
private void nextModeSettingHours() { nextMode(settingHours); }
private void nextModeSettingMinutes() { nextMode(settingMinutes); }
}
public class Mode {
private final Runnable increment;
private final Runnable tick;
private final Runnable changeMode;
public Mode(@NotNull Runnable increment, @NotNull Runnable tick, @NotNull Runnable changeMode) {
this.increment = increment;
this.tick = tick;
this.changeMode = changeMode;
}
@NotNull
public Runnable getIncrement() {
return increment;
}
@NotNull
public Runnable getTick() {
return tick;
}
@NotNull
public Runnable getChangeMode() {
return changeMode;
}
}
```
#columns(
2, [
#text(green)[Benefits]
- slightly better performance due to removed typecasting -> virtual objects
- behavior is coupled to state machine and not into thousands of classes
- each distinct behavior is assigned its own method
- No object context needs to be passed around, methods can already access the
internal state of the state machine
#colbreak()
#text(red)[Liabilities]
- indirection still exists -> performance loss is still there
- list of methods might get too large to properly manage
],
)
#subsection([State Pattern (Collection For States)])
#set text(size: 14pt)
Problem | In order to solve the problem of both too many objects, but also too
many functions inside one object, we create multiple different state machines,
e.g. one for every state. Each state then uses a "Mode" class, here called
workpiece that will take the function of the state and apply it via lambda.\
Participants :
- CollectionClockStateMachine
- a state machine that is explicit for the state in question
- Workpiece
- class used to invoke functions
#set text(size: 11pt)
// images
#align(
center, [#image("../../Screenshots/2023_10_13_10_52_36.png", width: 90%)],
)
#align(
center, [#image("../../Screenshots/2023_10_13_10_53_07.png", width: 90%)],
)
```java
import java.util.ArrayList;
import java.util.List;
public class CollectionClockStateMachine implements ClockStateMachine {
// contains all states
private final List<Workpiece> workpieces = new ArrayList<>();
private final List<Workpiece> displayingTime = new ArrayList<>();
private final List<Workpiece> settingHours = new ArrayList<>();
private final List<Workpiece> settingMinutes = new ArrayList<>();
// the following fields/properties are only for demonstration purposes; not part of the pattern
private final Workpiece defaultPiece;
@Override
public int getHour() { return defaultPiece.getHour(); }
@Override
public int getMinute() { return defaultPiece.getMinute(); }
@Override
public int getSecond() { return defaultPiece.getSecond(); }
/**
* State machine construction logic goes here...
*/
public CollectionClockStateMachine(int hour, int minute, int second) {
// #defaultPiece isn't part of the pattern
defaultPiece = new Workpiece(hour, minute, second);
workpieces.add(defaultPiece); // in real world, there are *many* such objects with a state
displayingTime.addAll(workpieces);
}
@Override
public void tick() {
displayingTime.forEach(Workpiece::tick);
}
@Override
public void increment() {
settingHours.forEach(Workpiece::incrementHour);
settingMinutes.forEach(Workpiece::incrementMinute);
}
@Override
public void changeMode() {
// simply rotate the objects within the collections
ArrayList<Workpiece> displayingTimePieces = new ArrayList<>(displayingTime);
displayingTime.clear();
displayingTime.addAll(settingMinutes);
settingMinutes.clear();
settingMinutes.addAll(settingHours);
settingHours.clear();
settingHours.addAll(displayingTimePieces);
}
}
// workpiece
public class Workpiece {
private int hour;
private int minute;
private int second;
public int getHour() { return hour; }
public void setHour(int hour) { this.hour= hour; }
public int getMinute() { return minute; }
public void setMinute(int minute) { this.minute = minute; }
public int getSecond() { return second; }
public void setSecond(int second) { this.second = second; }
public Workpiece(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
public void incrementMinute() {
minute = (minute + 1) % 24;
}
public void incrementHour() {
hour = (hour + 1) % 24;
}
public void tick() {
if (++second == 60) {
second = 0;
if (++minute == 60) {
minute = 0;
hour = (hour + 1) % 24;
}
}
}
}
```
#columns(
2, [
#text(green)[Benefits]
- No need to create a class per state
- Optimized for multiple objects (state machines) in a particular state
- Object's collection implicitly determines its state
- No need to represent the state internally
- Can be combined with other State Machine (Objects / Methods) approaches
- good for multiple workpieces -> multiple set of functions
#colbreak()
#text(red)[Liabilities]
- can lead to a more complex state manager
- performance...
],
)
#section("Value Definition")
#subsection("System Analysis (OOA)")
#text(
teal,
)[An individual is something that can be named and reliably distinguished from
other individuals.]\
There are 3 kinds of individuals:
- events
- *an individual thing* that happens at a particular time
- example: user-action
- entities
- *an individual* that *persists* and *changes its properties and states*.
- entities may *invoke events*
- example: person
- values
- *exists outside of time and space* -> is not represented directly
- it is part of an entity
- example: weight
#align(
center, [#image("../../Screenshots/2023_10_13_11_11_10.png", width: 70%)],
)
#subsection("Software Design (OOD)")
- entity
- express system information, typicall of *persisten nature*.
- identity distinguishes an entity from another
- example: some custom class
- service
- represent *system activities*
- Services are *distinguished by their behavior* rather than their state or
content
- example:
- values
- *the content is the dominant behavior* -> value is more important than the rest
-> weight -> kg is just something to make it easier for us to interpret
- transient: 5kg is always 5kg, no other interpretation
- example: value weight
- task
- *like services, but with a representation of identity and state*
- example: threads
|
|
https://github.com/mismorgano/UG-FunctionalAnalyisis-24 | https://raw.githubusercontent.com/mismorgano/UG-FunctionalAnalyisis-24/main/tareas/Tarea-05/Tarea-05.typ | typst | #import "../../config.typ": config, exercise, ip, proof, cls, eps, int, conv
#show: doc => config([Tarea 5], doc)
#exercise[1.42][Sea $H$ un e.H. Muestra que existe un conjunto abstracto $Gamma$ tal que $H$ es isométrico a $l_2(Gamma)$.]
#proof[
Por el Teorema 1.35 existe base ortonormal ${e_gamma}_(gamma in Gamma)$.
]
#exercise[1.44][Supongamos que ${x^k}_(k=1)^infinity$ es uns sucesión ortonormal en $cal(l)_2$, donde $x^k = (x_i^k)$.
Muestra que $lim_(k -> infinity) (x_i^k) = 0 $ para todo $i in NN$. ]
#proof[
]
ni idea
#exercise[1.45][Un e.B $X$ se dice de _cotipo 2_ si existe constante $C>0$ tal que para todos los vectores $x_1, dots, x_n in X$
tenemos que
$ 1/2^n sum_(epsilon_i plus.minus 1) norm(sum_(i=1)^n e_i x_i) >= 1/C (sum_(i=1)^n norm(x_i)^2)^(1/2). $
Decimos que $X$ tiene _tipo 2_ si existe constante $C>0$ tal que para todos los vectores $x_1, dots, x_n in X$ tenemos que
$ 1/2^n sum_(epsilon_i plus.minus 1) norm(sum_(i=1)^n e_i x_i) <= C (sum_(i=1)^n norm(x_i)^2)^(1/2). $
El _tipo/cotipo q_ se define de manera similar.
Tomando por hecho que el dado izquierdo de la expresión puede ser remplazado por $(1/2^n sum_(epsilon_i plus.minus 1) norm(sum_(i=1)^n e_i x_i))^(1/2)$,
muestra que si $X$ es un e.B isomorfo a un e.H, entonces $X$ is de tipo 2 y cotipo 2.
]
#proof[]
#exercise[1.46][Muestra que $l_4$ no es isomorfico a un subespacio de $l_2$.]
#exercise[1.48][Muestra que un conjunto acotado $M$ en $c_0$ es totalmente acotado ssi para todo $epsilon>0$
existe $n_0$ tal que $abs(x_n) <= epsilon$ para todo $x in M$ y $n>= n_0$. Formula y prueba el resultado análogo
para los espacios $l_p$.]
#proof[
Sea $M subset c_0$ acotado. Supongamos primero que $M$ es totalmente acotado entonces dado $eps>0$ existe $N in NN$ y $a_1, dots, a_N in c_0$ tal que
$ M subset union.big_(n=1)^N B_(eps/2) (a_n). #footnote[Aqui denotamos por $B_eps (x)$ a la bola abierta de radio $eps$ centrada en $a_n$.] $
Lo anterior implica que dado $x in M$ existe $n in NN$ tal que
$x in B_(eps/2) (a_n)$, es decir $norm(x-a_n)_infinity < eps/2$.
Por lo cual tenemos que $abs(x_k - a_k^n) < eps/2$ para todo $k in NN$.
Por otro lado notemos que para $n=1, dots, N$ existen $M_n in NN$ tales que $abs(a_k^n) < eps/2$ para todo $k>= M_n$, pues $a_n in c_0$.
Tomando $M= max(M_n)$ obtenemos que para $k>= M$ se cumple
$ abs(x_k) <= abs(x_k - a_k^n) + abs(a_k^n) < eps/2 + eps/2 = eps, $
como queremos.
Supongamos ahora que para todo $epsilon>0$ existe $n_0$ tal que $abs(x_n) <= epsilon$ para todo $x in M$ y $n > n_0$.
Sea $eps > 0$, entonces existe $n_0$ que cumple lo anterior. Como $M$
es acotado existe $C>0$ tal que $norm(x) < C$ para todo $x in M$,
lo anterior implica que $abs(x_n) < C$ para todo $n=1, dots, n_0$.
Ademas es claro que $[-C, C] times dots times [-C, C] subset RR^(n_0)$ es acotado, por lo cual es totalmente acotado
]
#exercise[1.49][El cubo de Hilbert $C$ es definido como
$ C := { x = (x_i) in l_2 : abs(x_i) <= 2^(-i) "para todo" i in NN }. $
Muestra que el cubo de Hilbert es compacto en $l_2$. ]
#exercise[1.51][Sea $C$ un conjunto convexo es un e.n $X$, supongamos que $"Int"(C) != emptyset$.
Muestra que $cls("Int"(C)) = cls(C)$ y que $"Int"(cls(C)) = "Int"(C)$.]
#proof[
Notemos primero que $cls(int(C)) subset cls(C)$, pues $int(C) subset C$.
Por otro lado como $int(C) != emptyset$ existe $eps>0$ tal que $B_eps^circle.small (x_0) subset C$,
luego, dado $x in C$ podemos notar que $conv(B_eps^circle.small (x_0) union {x}) subset C$, pues $C$
es convexo
el cual tiene puntos en $int(C)$ arbitrariamente cerca de $x$ y por tanto $x in cls(int(C))$
Para probar que $int(cls(C)) = int(C)$, primero notemos que $int(C) subset int(cls(C))$ pues $C subset cls(C)$.
] |
|
https://github.com/PA055/5839B-Notebook | https://raw.githubusercontent.com/PA055/5839B-Notebook/main/Entries/drivetrain/drive-train-prototypes.typ | typst | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Drive Train Prototypes",
type: "build",
date: datetime(year: 2024, month: 3, day: 17),
author: "<NAME>",
witness: "<NAME>"
)
With inventory taken we can now begin to make some designs. To expirment with more complex Drives a Mechnum drive and a Swerve Drive module were completed. These should provide good practice for designing before the next season as well possibly giving us a head start if we choose to use these drives.
The first model made was that of a Mecanum Drive:
- 4 Mecanum wheels geared to 300 RPM with a 72:48 ratio driven by an 11w motor with the 600rpm cartrige.
- 24in HS axels with holes drilled in them as the main frame to ensure it was stronger then our previous drive trains.
- Center Omni Wheel for additional power
- PTO to allow for the cneter omni wheel to power other system while not in use
- Battery and Air Tanks kept low to ensure a proper center of gravity
- New Odometry Sensor fitted in the rear
#figure(
rect(fill: black.lighten(10%))[
#image("./Drive Proto Isometric.png", width: 80%)
],
caption: [ Isometric View of the Prototype Mecanum Drive
]
) <odomDiagram>
#figure(
rect(fill: black.lighten(10%))[
#image("./Mecanum Drive Proto Top.png", width: 80%)
],
caption: [ Top View of the Prototype Mecanum Drive
]
) <odomDiagram>
#figure(
rect(fill: black.lighten(10%))[
#image("./Mecanum Drive Proto Front.png", width: 80%)
],
caption: [ Front View of the Prototype Mecanum Drive
]
) <odomDiagram>
#figure(
rect(fill: black.lighten(10%))[
#image("./Mecanum Drive Proto Side.png", width: 80%)
],
caption: [ Side View of the Prototype Mecanum Drive
]
) <odomDiagram>
Before we could enter school to test this I created a Model for a Swerve Drive module:
- Keeps design compact with motors below the frame
- 72 tooth gear is screwed to the frame so they spin together
- Circular insert within the gear to allow the drive shaft to turn
- Chain runs to connect the Drive Shaft to the 11w motor
- 5.5w motor used to turn module
#figure(
rect(fill: black.lighten(10%))[
#image("./Swerve Drive Module Isometric.png", width: 50%)
],
caption: [ Isometric View of the Prototype Swerve Drive Module
]
) <odomDiagram>
#figure(
rect(fill: black.lighten(10%))[
#image("./Swerve Drive Module Side.png", width: 50%)
],
caption: [ Side View of the Prototype Swerve Drive Module
]
) <odomDiagram>
#figure(
rect(fill: black.lighten(10%))[
#image("./Swerve Drive Module Front.png", width: 50%)
],
caption: [ Front View of the Prototype Swerve Drive Module
]
) <odomDiagram>
#admonition(type: "note")[
It is unlikley any of these drives will be used as tank drives have proved superior for many games in a row. They simply serve as a way to practice building and design techniques and mechanisms before the next season. However, cataloging them is still important as the ideas learned from them could proove very important.
]
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/计算方法B/main.typ | typst | #import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../template.typ": *
#show: note.with(
title: "计算方法B",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withChapterNewPage: true
)
= 前言
- 授课教师:张磊
- 办公室:怀新园 78409
- email: <EMAIL>
- 助教 email: <EMAIL>
- 作业 30 + 期中 30 + 期末 40
一般来说,计算数学研究如何求出数学问题的近似解(数值解),以及算法的设计和分析(收敛性、稳定性、复杂性等等)。当代计算数学的主要研究方向包括数值逼近、数值微积分(数值分析)、数值代数、微分方程数值解等等。
== 主要任务
- 算法设计:构造特定问题的数值算法
- 算法分析:收敛性、稳定性、复杂性、计算精度等等
- 算法实现:编程实现、软件开发
== 敏度分析与误差分析
用计算机计算的数值总是不精确的。:
- 敏度分析是指原始数据的微小变化对计算结果的影响。往往能找到 $c(x)$ 使得:
$
norm(f(x + delta x) - f(x)) / norm(f(x)) <= c(x) norm(delta x)
$
其中的 $c(x)$ 就称为*条件数*,显然若 $f(x)$ 可微则可取 $c(x) = norm(x f'(x))/norm(f(x))$\
条件数较大的问题称为病态问题,这是问题本身的性质,与算法无关
- 误差分析是指计算结果与真实结果的差异。
== 直接法与迭代法
算法大致可分为两类:
- 直接法:算法在有限步终止,可以得到精确结果。其效率大致由运算量决定。
- 迭代法:算法一直进行,有限步只能得到近似结果。其效率由每步的运算量和收敛速度决定。
#definition[][
假设迭代法产生数列 $x_k -> x$ 其中 $x$ 是精确解
- 若存在 $0 < c < 1$ 满足:
$
norm(x_k - x) <= c norm(x_(k - 1) - x)
$
则称算法线性收敛
- 若存在 $0 < c < 1$ 满足:
$
norm(x_k - x) <= c norm(x_(k - 1) - x)^2
$
则称算法平方收敛
- 若存在 $0 < c < infinity$ 使得:
$
lim_(k -> infinity) norm(x_k - x) / norm(x_(k - 1) - x)^p = c
$
则称之为 $p$ 次渐进收敛
]
= 数值代数
== 基本知识
数值代数的基本问题:
+ 线性方程组
+ 线性最小二乘
+ 矩阵特征值
+ 奇异值分析
== 直接法解线性方程组
=== 三角形方程组和 LU 分解
若 $L$ 是下三角矩阵,且对角线上没有零,则称 $L y = b$ 是三角方程组。不难发现,这样的方程组可以在 $O(n^2)$ 时间解出。自然的,如果方程组 $A x = y$ 可以分解成:
$
A = L U\
L (U x) = y
$
其中 $L$ 是下三角矩阵,$U$ 是上三角矩阵,则可以先解 $U x$ 再解出 $x$,这样的分解称为 LU 分解。
一般的,我们可以使用高斯消元法来解线性方程组。如果枢纽元就选取每行(剩余)的一个元素,则确实可以找到如上形式的分解,运算量约为 $2/3 n^3$
#theorem[][
$L U$ 分解后得到的主对角元 $a_(i i)$ 均不为零的充要条件是 $A$ 的所有小于 $i$ 阶顺序主子式均不为零。
]
#proof[
简单应用归纳法即可
]
#theorem[][
假设所有顺序主子式均不为零,则 $L U$ 分解存在且唯一(在对应下三角矩阵的主元均为 1 的意义下)。当然这并非分解存在的必要条件。
]<LUcondition>
若已知矩阵有 LU 分解,也可以使用待定系数法来求得分解,运算量仍约为 $n^3$。
#let per(p, q) = $I_(#p #q)$
#let letc = "let"
然而通常而言,之前选取的每行第一个元素未必非零,而枢纽元过小会影响算法的稳定性,有时必须引入置换。
#algorithm[全主元高斯消元法][
记 $per(p, q)$ 为初等置换矩阵,左乘 $A$ 即是将第 $p$ 行与第 $q$ 行交换,右乘 $A$ 即是将第 $p$ 列与第 $q$ 列交换。
```hs
gaussAux :: Int -> [Matrix] -> [Matrix] -> [Matrix] -> Matrix -> ([Matrix], [Matrix], [Matrix], Matrix)
gaussAux r ls ps qs A =
```
其中 $r$ 为步数,$"ls"$ 为高斯变换矩阵,$"ps"$ 为行置换矩阵,$"qs"$ 为列置换矩阵,$A$ 为当前矩阵。
- 此时,我们假设 $A$ 形如:
$ A =
mat(A_(1 1, (n-r) times r), A_(1 2, (n-r) times (n-r));0_(r times r), A_(2 2, r times (n-r)))
$
- 目标是找到 $A_(2 2)$ 中(绝对值)最大元,并用其做下一次高斯消去,为此:
$
&letc (p, q) = argmax_((i, j) in RR^n times RR^n, i >= r + 1) |A_(i j)|\
&letc "pivot" = A_(p q)
$
- 假设 pivot $= 0$ 则算法结束,否则将 $(p, q)$ 调整至$(r + 1, r + 1)$,也即:
$
&letc "ps1" = per(p, r + 1) : "ps"\
&letc "qs1" = per(q, r + 1) : "qs"\
&letc A' = per(p, r + 1) A per(r + 1, q)
$
- 再做列变换:
$
&letc l_r = vec(0, dots.v, A'_(r+2, r+1), dots.v, A'_(n r+1)) \/ "pivot"\
&letc L_r = I - l_r e_(r+1)^T\
&letc "ls1" = L_r : "ls"\
$
- 最后:
$
&letc A'' = L_r A'\
$
即可保证 $A''$ 的左下 $r + 1$ 部分被消掉,因此最终返回:
```hs
gaussAux (r + 1) ls1 ps1 qs1 A''
```
递归结束后即得结果
]
#theorem[][
设 $A in RR^(n times n)$,则存在 $P, Q$ 和单位下三角阵 $L$,上三角阵 $U$ 使得 $P A Q = L U$,其中 $L$ 的所有元素的绝对值不超过 $1$
]
#proof[
从上面的算法不难看出大多数结论,事实上,令:
```hs
let (ls, ps, qs, U) = gaussAux 0 [] [] [] A
P' = foldr (*) I [l * p, p <- ps, l <- ls]
Q = foldr (*) I (reverse qs)
P = foldr (*) I ps
L = P * inv(P')
```
不难从算法过程看出:
$
P' A Q = U\
P A Q = L U
$
且其中 $"ls"$ 中的矩阵都是列变换产生的,其中元素绝对值均不大于 $1$,而 ps 中矩阵都是置换矩阵,以及:
$
L = P (L_n P_n ... L_1 P_1)^(-1) = (P_n ... P_1) P_1^(-1) L_1^(-1) ... P_n^(-1) L_n^(-1)
$
而 $L_i = I - l_i e_i^T, L_i^(-1) = I + l_i e_i^T$,且 $P_i^(-1)$ 也是对换矩阵,因此 $L$ 的元素绝对值不超过 $1$ 是容易证明的
]
#algorithm[列主元三角分解][
寻找全主元是很昂贵的,实践上往往只在 $r + 1$ 列选择最大元,其他算法是类似的,最终结果可以得到:
$
P A = L U
$
其中:
$
P = P_n ... P_1\
L = P (L_n P_n ... L_1 P_1)^(-1)\
$
]
== 平方根法
#theorem[Cholesky][
设 $A$ 是对称正定矩阵,则存在对角元均正的下三角矩阵 $L$ 使得 $A = L L^T$。$L$ 被称为 $A$ 的 Cholesky 因子。
]
#proof[
由于半正定矩阵的所有顺序主子式都正,因此可以运用 @LUcondition ,存在单位下三角阵 $L$ 和上三角阵 $U$ 使得:
$
A = L U = U^T L^T = A^T\
U Inv((L^T)) = Inv(L) U^T := D
$
上式左侧上三角,右侧下三角,因此 $D$ 是对角矩阵,并且对角元就是 $U$ 的对角元。
同时,有:
$
A = L U = L D L^T
$
因此 $D$ 与 $A$ 合同,导致其对角元都正。令 $D = T T^T$,则有:
$
A = L T T^T L^T = (L T) (L T)^T
$
注意到 $L$ 是单位下三角矩阵,不难验证 $L T$ 是对角元均正的下三角矩阵
]
#algorithm[][
求 Cholesky 因子当然可以通过 LU 分解,但事实上有更快的办法。只需从:
$
A = L L^T
$
便可得到等式:
$
a_(i j) = sum_(p = 1)^j l_(i p) l_(j p)
$
这些等式呈三角形,因此可以依次回代动态规划求解。具体而言:
```hs
choleskyij :: Matrix -> Map (Int, Int) Double -> Int -> Int -> Map (Int, Int) Double -- 计算 l_(i j),假设 i >= j
choleskyij A L i j = Map.insert L (i, j) lij
where lij = if i = j
then sqrt (A i i - sum [(L i p)^2 | p <- [1..j - 1]])
else (A i j - sum [(L i p) * (L j p) | p <- [1..j - 1]]) / (L j j)
cholesky :: Matrix -> Matrix
cholesky A = foldl (choleskyij A) Map.empty [(i, j) | i <- [1..n], j <- [1..i]]
```
若只考虑乘加运算,运算量约为:
$
sum_(i=1)^n sum_(j=1)^i 2j approx 1/3 n^3
$
// $
// sum_(k=1)^n sum_(j = k + 1)^n sum_(r = j)^n 2 = sum_(r = 2)^n sum_(j = 2)^r sum_(k=1)^(j-1) 2 = sum_(r = 2)^n sum_(j = 2)^r 2(j - 1) ~ sum_(r = 2)^n r^2 ~ 1/3 n^3
// $
之后,只需解:
$
L y = b\
L^T x = y
$
两个三角形方程组即可得到解。
此外,该分解是稳定的,既然由:
$
a_(i i) = sum_(p = 1)^(i - 1) l_(i p)^2
$
不难得到:
$
abs(l_(i j)) <= sqrt(a_(i i))
$
]
#algorithm[改进的平方根法][
平方根法需要进行开方运算。为了避免开方,可以求如下形式的分解:
$
A = L D L^T
$
其中 $L$ 是单位下三角矩阵,$D$ 是对角元均正的对角矩阵。(该分解称为 $L D L^T$ 分解)这样,方程变为:
$
a_(i j) = sum_(k = 1)^(j - 1) l_(i k) d_k l_(j k) + l_(i j) d_j
$
反解出:
$
d_j = a_(j j) - sum_(k = 1)^(j - 1) l_(j k)^2 d_k\
l_(i j) = (a_(i j) - sum_(k = 1)^(j - 1) l_(i k) l_(j k) d_k) / d_j
$
同样进行动态规划即可。它的运算量也约为 $1/3 n^3$
]
= 线性方程组的敏度分析
== 向量范数与矩阵范数
#definition[向量范数][
称满足:
- 正定性:$norm(x) >= 0, norm(x) = 0<=> x = 0$
- 齐次性:$norm(a x) = a norm(x)$
- 三角不等式:$norm(a + b) <= norm(a) + norm(b)$
的 $RR-$ 线性空间 $X$ 到 $RR$ 的函数为范数。常用范数包含:
- $p-$范数:$norm(x) = root(1/p, sum_i abs(x_i)^p)$
- $infinity-$ 范数:$norm(x) = max_i abs(x_i)$
- $0-$ "范数":$"card" {x_i | x_i != 0}$ (并不齐次)
]
#definition[相容性][
- 称矩阵范数相容,如果 $norm(A B) <= norm(A) norm(B)$
- 称矩阵范数与向量范数相容,如果 $norm(A x) <= norm(A) norm(x)$
一般的,我们假定我们使用的范数都是相容的。
]
#theorem[][
给定 $RR^n$ 上向量范数,则可以定义矩阵范数:
$
norm(A) = sup_(x != 0) (norm(A x))/norm(x)
$
它是 $RR^(m times n)$ 上的相容矩阵范数,也称为算子范数。它与向量范数相容。
]
#example[矩阵范数][
常用的矩阵范数包括:
- $1-$ 范数:$max_(j) sum_i a_(i j)$,也称列范数
- $infinity-$ 范数:$max_(i) sum_j a_(i j)$,它是向量无穷范数的诱导
- $2-$ 范数:$norm(A) = A^T A$ 最大特征值的平方根,也称为谱范数,它是向量 $2-$ 范数的诱导
]
#proposition[][
设 $A in RR^(m times n)$,则有:
- $norm(A)_2 = max_(norm(bx)_2 = 1, norm(by)_2 = 1) norm(by^T A bx)$
- $norm(A)_2 = norm(A^T)_2 = sqrt(norm(A A^T)_2)$
- 设 $U$ 是正交矩阵,则 $norm(U A)_2 = norm(A U) = norm(A)$
]
#definition[谱半径][
称矩阵的特征值的绝对值最大值为谱半径,记为 $rho(A)$
]
#theorem()[][
- 对于任意矩阵范数,有 $norm(A) >= rho(A)$
- 对于任意 $epsilon > 0$,存在矩阵范数使得 $norm(A) <= rho(A) + epsilon$
]
#proof[
- 设 $lambda$ 是特征值且 $abs(lambda) = rho(A)$,$alpha$ 是对应的特征向量。将有:
$
rho(A) norm(alpha e_1^T)= norm(rho(A) alpha e_1^T) = norm(A alpha e_1^T) <= norm(A) norm(alpha e_1^T)
$
两边消去即可。
]
#theorem[][
设 $A in CC^(n times m)$,则:
$
lim_(n -> +infinity) A^n = 0 <=> rho(A) < 1
$
更进一步,$lim_(n -> +infinity) A^n exists <=> rho(A) <= 1$
]
#proof[
使用 Jordan 分解即可。
]
#corollary[][
假设 $norm(I) = 1, norm(A) < 1$,则 $I - A$ 可逆,且有:
$
norm(Inv((I - A))) <= 1/(1 - norm(A))
$
]<norm-inv>
#proof[
#let suma = sumf()
#let summ = sumf(lower: $m$)
考虑形式幂级数:
$
suma A^n
$
断言它收敛,事实上使用柯西准则:
$
norm(summ A^n) <= summ norm(A^n) <= summ norm(A)^n -> 0
$
因此一定收敛。设其和为 $B$,则:
$
B (I - A) = (suma A^n)(I - A) = I
$
表明 $B$ 就是 $I-A$ 的逆,并且:
$
norm(B) = norm(suma A^n) <= suma norm(A^n) <= suma norm(A)^n = 1/(1 - norm(A))
$
证毕
]
== 线性方程组的敏度分析
本节中,我们希望计算解线性方程组的条件数。假设我们使用的范数满足 $norm(I) = 1$,对线性方程组问题:
$
A x = b
$
其中 $A$ 非奇异,假设微扰后变为:
$
(A + delta A)(x + delta x) = b + delta b\
A x + A delta x + delta A x + delta A delta x = b + delta b\
A delta x + delta A x + delta A delta x= delta b\
(A +delta A)delta x = delta b - delta A x\
delta x = Inv((A + delta A)) (delta b - delta A x) = Inv((I + Inv(A) delta A)) Inv(A) (delta b - delta A x)\
norm(delta x) <= norm(Inv((I + Inv(A) delta A))) norm(Inv(A)) (norm(delta b) + norm(delta A) norm(x))\
norm(delta x)/norm(x) <= norm(Inv((I + Inv(A) delta A))) norm(Inv(A)) (norm(delta b)/norm(x) + norm(delta A) )\
norm(delta x)/norm(x) <= norm(Inv((I + Inv(A) delta A))) norm(Inv(A)) (norm(delta b)/norm(x) + norm(delta A) ) <= (norm(A) norm(Inv(A)) ) / (1 - norm(Inv(A)) norm(delta A)) (norm(delta b)/(norm(A) norm(x)) + norm(delta A)/norm(A) )\
<= (norm(A) norm(Inv(A)) ) / (1 - norm(Inv(A)) norm(delta A)) (norm(delta b)/(norm(A x)) + norm(delta A)/norm(A) )
<= (norm(A) norm(Inv(A)) ) / (1 - norm(Inv(A)) norm(delta A)) (norm(delta b)/(norm(b)) + norm(delta A)/norm(A) )
$
其中运用了:
$
norm(Inv((I + Inv(A) delta A))) <= 1/(1 - norm(Inv(A) delta A)) <= 1/(1 - norm(Inv(A)) norm(delta A))
$
因此我们得到定理:
#theorem[][
假设 $A x =b$ 经微扰变为 $(A + delta A)(x + delta x) = b + delta b$,则有:
$
(delta x) / x <= (norm(A) norm(Inv(A)) ) / (1 - norm(Inv(A)) norm(delta A)) (norm(delta b)/norm(b) + norm(delta A)/norm(A) )
$
若令 $kappa(A) = norm(A) norm(Inv(A))$,则上式表明 $(delta x)/x$ 与 $kappa(A)$ 大约为线性,因此 $kappa(A)$ 称为线性方程组问题的条件数。
]
此外,我们有:
#theorem[][
在求逆问题中,有:
$
(norm((A + delta A)^(-1) - A^(-1))) / norm(A^(-1)) &<= norm(I - A (A + delta A)^(-1)) = norm(I - Inv((I + delta A Inv(A))))\
&= norm(((I + delta A Inv(A)) - I)Inv((I + delta A Inv(A))))\
&<= norm(delta A) norm(Inv(A)) norm(Inv((I + delta A Inv(A))))\
&<= (norm(delta A) norm(Inv(A)))/(1 - norm(delta A) norm(Inv(A)))\
&= (norm(A) norm(Inv(A)))/(1 - norm(delta A) norm(Inv(A))) norm(delta A)/norm(A)\
$
可见 $kappa(A)$ 也是求逆问题的条件数。
]
#theorem[][
若使用谱范数,则有:
$
min {norm(delta A) | A +delta A "奇异"} = 1/norm(Inv(A))
$
]
#proof[
由于谱范数是算子范数,取 $x$ 使得:
$
norm(Inv(A) x) = norm(Inv(A))
$
取:
$
y = (Inv(A) x)/norm(Inv(A) x)\
$
则:
$
A y = x/norm(x) = (x y^T y)/(norm(x)) = (x y^T)/norm(x) y
$
也即:
$
(A - (x y^T)/norm(x)) y = 0
$
同时:
$
norm((x y^T)/norm(x)) = 1/norm(x) sqrt(norm(x y^T y x^T)) = sqrt(norm(x x^T))/norm(x) = sqrt(norm(x^T x))/norm(x) = 1
$
表明 $A - (x y^T)/norm(x)$ 是奇异的,而 $(x y^T)/norm(x)$ 就是我们要找的微扰。
对于更小的微扰,@norm-inv 保证矩阵一定可逆。
]
= 线性最小二乘问题
=== 正规化法
#definition[最小二乘][
给定 $A in RR^(m times n), b in RR^m$,线性最小二乘问题是求解:
$
min norm(A x - b)^2
$
其中 $x in RR^n$ 为未知向量。
]
显然
- 若 $m = n$ 且 $A$ 非奇异时,$x = Inv(A) b$ 即可
- 若 $m < n$,称作嵌进方程组,解有无穷多组,我们往往希望解出:
$
min norm(x)^2 s.t. A x = b
$
也即范数最小的解。对于这种问题,我们往往通过拉格朗日乘子法解决。
- 若 $m > n$,称方程组超定 (overdetermined),我们希望解出:
$
min norm(A x - b)^2
$
也即最小化误差的平方和。这种问题的解法是线性最小二乘问题。当我们采用2-范数时,这是凸问题,存在唯一的最优解,求导可得解就是以下线性方程组的解:
$
A^T A x = A^T b
$
这被称为最小二乘问题的正则化方程,线性代数的知识保证了它总是有解的。假设 $A$ 列满秩,则 $A^T A$ 对称正定,使用平方根法即可,否则用一般的解线性方程组方法即可。
然而,注意到 $A^T A$ 的条件数是 $A$ 的条件数的平方,因此使用一般的线性方程组解法会导致误差放大,因此我们希望采用其他方法求解。之前高斯变换我们使用的是初等变换矩阵,而这里我们要处理 2- 范数,使用正交矩阵便可保证结果不变。
=== 初等正交变换
先介绍初等正交矩阵:
#definition[][
对于任意向量 $v$,令:
$
H = I - 2/ (v^T v) v v^T
$
这样的矩阵称为 Householder 矩阵,对应向量称为 Householder 向量 。它是对称的正交/对合矩阵,且 $v$ 是特征向量,对应特征值为 $-1$。事实上,它就是关于超平面 $v^T$ 的反射。
]
#lemma[][
设 $x != 0$,则存在单位向量 $v$,使得:
$
H_v x = alpha e_1
$
其中 $abs(alpha) = norm(x)$
]
#proof[
注意到:
$
H_v x = (I - 2 v v^T)x = x - 2 v v^T x = x - 2 (v^T x) v = alpha e_1
$
可得 $v$ 与 $x - alpha e_1$ 线性相关,进一步若取:
$
v = (x - alpha e_1)/norm(x - alpha e_1)
$
则恰好之前的等式成立。
]
实际计算时,我们希望 $alpha > 0$,因此上面选取减号,然而当 $x_1 > 0$ 时,这会造成数值不稳定的问题。不过,我们可以进行等价变形:
$
(x - alpha e_1)_1 = x_1 - norm(x)\
= x_1 - sqrt(sum_i x_i^2) = - (sum_(i = 2)^n x_i^2) / (x_1^2 + sqrt(sum_i x_i^2))\
$
同时,我们未必要算出单位化的向量 $v$,既然:
$
H = I - 2/ (v^T v) v v^T
$
令 $beta = 2/ (v^T v)$,算出 $beta$ 和 $v$ 即可。
我们给出 Householder 变换的算法:
```rust
fn Householder(x: Vec<R> n) -> (R, Vec<R> n)
{
let eta = max(x);
x = x / eta;
let sigma = sum(x[2..n] ^ 2);
let mut v = x;
v[1] = 1;
if (sigma == 0) return;
let alpha = sqrt(x[1] ^ 2 + sigma); // norm(x)
let v[1] =
if (x[1] <= 0) x[1] - alpha; // 直接运算
else -sigma / (x[1] + alpha); // 通过等价变形间接运算,保证数值稳定
beta = 2 / (sigma + v[1] ^ 2); // 2 / norm(v)^2
(beta, v)
}
```
如果只是想将向量的某一个分量变为零,可以利用 Givens 变换
#definition[][
设
$
G(i, k, theta) = I + s (e_i e_k^T - e_k e_i^T) + (c - 1) (e_i e_i^T + e_k e_k^T)\
where c = cos theta, s = sin theta
$
也就是 $i, k$ 行/列是旋转矩阵:
$
mat(cos theta, sin theta; -sin theta, cos theta)
$
其他位置是单位矩阵。易知:
$
G(i, k ,theta) x = &"match" i "with"\ | &i => c x_i + s x_k \ | &k => -s x_i + c x_k \ | &\_ => x_i
$
因此为使 $(G(i, k ,theta) x)_k = 0$,只需取:
$
c = x_i / sqrt(x_i^2 + x_k^2), s = x_k / sqrt(x_i^2 + x_k^2)
$
便有:
$
G(i, k ,theta) x = &"match" i "with"\ | &i => sqrt(x_i^2 + x_k^2) \ | &k => 0 \ | &\_ => x_i
$
]
为了数值稳定性,实际计算时,我们不用保证 $s, c$ 平方和为 1
=== QR 分解,正交变换法
#theorem[QR][
设 $A in RR^(m times n)$,则存在一个单位列正交阵 $Q$ 和对角元非负的上三角矩阵 $R$ 使得:
$
A = Q vec(R, 0)
$
且若 $m = n$,$A$ 非奇异,则上述分解唯一。
]
#proof[
对 $A$ 的列空间做 Gram-Schmidt 正交化即可。
]
回到最小二乘问题,设
$
A = (Q_1, Q_2) vec(R, 0) = Q_1 R\
Q^T b = vec(Q_1^T b, Q_2^T b)
$
原问题变为:
$
min norm(Q^T Q vec(R, 0) x - Q^T b)^2 = min norm(vec(R, 0) x - vec(Q_1^T b, Q_2^T b))^2\
= min norm(R x - Q_1^T b)^2 + norm(Q_2^T b)^2
$
而 $R$ 是满秩的方阵,直接求解:
$
R x = Q_1^T b\
x = Inv(R) Q_1^T b
$
即可。求解 QR 分解的方法可以采用之前的 Householder 变换,也可以采用 Givens 变换。往往在非零元素较多时使用 Givens 变换。
= 解线性方程组的迭代法
第一章已经介绍了解线性方程组的直接法,然而对于常见的大规模矩阵,它的元素往往比较稀疏,而 LU 分解会破坏许多零元素,不能保持稀疏性。本章介绍解线性方程组的迭代法,也就是构造一个向量序列使得它趋近于问题的解。对于迭代法,往往要解决以下几个问题:
- 如何构造迭代序列
- 是否收敛,在什么条件下收敛
- 若收敛,收敛速度如何
== 单步线性定长迭代法
#algorithm[Jacobi 迭代法][
Jacobi 迭代法是最简单的迭代法,它的思路是将 $A x = b$ 分解成对角线元素和非对角线元素两部分:
$
A = D - L - U\
D x = (L + U) x + b
$
其中 $D$ 是 $A$ 的对角线元素,$L, U$ 分别是 $A$ 的下三角和上三角元素(取负)。假设 $A$ 的对角线上没有零,就可以构造迭代公式:
$
x_(k + 1) = B x_k + g\
where
B = D^(-1) (L + U) \
g = D^(-1) b
$
]
#algorithm[Gauss - Seidel 迭代法][
注意到 Jacobi 迭代法中,每个 $x_i$ 分量更新都是独立的。而事实上,我们可以利用已经更新的 $x_i$ 取代前一次的 $x_i$,可以写成:
$
x_k = Inv(D) L x_k + Inv(D) U x_(k - 1) + Inv(D) b
$
也可以变形成:
$
(D - L) x_k = U x_(k - 1) + b\
x_k = Inv((D - L)) U x_(k - 1) + Inv((D - L)) b
$
下三角的非零部分就是已经更新的部分,而上三角的非零部分就是未更新的部分。这就是 Gauss - Seidel 迭代法。
]
所谓的单步线性定长迭代,就是迭代公式形如:
$
x_k = M x_(k - 1) + g
$
显然若序列收敛,则极限就是方程组:
$
(M - I) x + g = 0
$
的解。若该方程与 $A x = b$ 一致,则迭代法正确收敛。假设该方程的解为 $x$,则误差为:
$
y_k = x_k - x = M x_(k-1) + g - x = M y_(k-1)
$
因此显然方程收敛当且仅当 $M^k -> 0$,也即 $M$ 的谱半径小于 $1$。
=== 收敛条件
上面介绍的两种迭代法 Jacobi 和 Gauss - Seidel 有着不同的迭代矩阵,它们的收敛范围也互不包含。然而谱半径并不好计算,我们可以找到一些充分条件。
#theorem[][
若迭代矩阵满足 $norm(M) = q < 1$,则有:
$
norm(x_k - x) <= (q^k)/(1-q) norm(x_1 - x_0)
$
]
#proof[
$
norm(x_k - x) <= q^k norm(x_0 - x)\
norm(x_0 - x) <= norm(x_1 - x_0) + norm(x_1 - x) <= norm(x_1 - x_0) + q norm(x_0 - x)\
norm(x_1 - x_0) >= (1 - q) norm(x_0 - x) >= (1-q)/q^k norm(x_k - x)
$
]
这个定理可以用来得到所需要的迭代次数,但往往偏高。
#theorem[][
若迭代矩阵满足 $norm(M) = q < 1$,则有:
$
norm(x_k - x) <= q/(1 - q) norm(x_k - x_(k-1))
$
]
#proof[
就是上面定理的特例。
]
这个界往往更加准确,往往可以用来在迭代过程中及时估计误差。当然若 $q$ 很接近于 $1$,则误差还可能较大。注意上面两个定理中我们并不假定用何种范数,因此实践上往往使用便于计算的列范数 $norm(M)_1$ 和行范数 $norm(M)_infinity$。
当系数矩阵 $A$ 正定时,它的收敛性可能更易判定:
#theorem[][
设 $A x = b$ 中,$A$ 对称且对角元 $> 0$,则 Jacobi 迭代收敛当且仅当 $A, 2 D - A$ 都正定。
]
#proof[
注意到:
$
M = Inv(D) (L + U) = Inv(D) (D - A) = I - Inv(D) A
$
由条件,$D$ 可以开平方根,上式等于:
$
D^(-1/2) (I - D^(-1/2) A D^(-1/2)) D^(1/2)
$
显然 $I - D^(-1/2) A D^(-1/2)$ 对称,且与 $M$ 相似,有相同的特征值和谱半径,因此 $M$ 特征值均为实数。类似的,$I - M$ 与 $D^(-1/2) A D^(-1/2)$ 相似,$I + M$ 与 $(2 I - D^(-1/2) A D^(-1/2))$\
不难验证由 $M$ 特征值均为实数, $rho(M) < 1$ 当且仅当 $I - M, I + M$ 的特征值均为正实数,略作化简即是定理条件。
]
#theorem[][
设 $A x = b$ 中,$A$ 对称正定,则 Gauss - Seidel 迭代收敛。
]
=== 正定矩阵的判别
#definition[对角占优][
设矩阵 $A$ 满足:
$
abs(a_(i i)) >= sum_(j != i) abs(a_(i j)), forall i
$
且对至少一个 $i$ 严格不等号成立,则称之为弱严格对角占优。若对所有 $i$ 严格不等号成立,则称之为严格对角占优。
]
#definition[不可约][
如果存在 $n$ 阶正定矩阵 $P$ 使得:
$
P A P^T = mat(A_(1 1), 0;A_(2 1), A_(2 2))
$
则称 $A$ 可约或者可分,否则称之为不可约。假设 $A$ 可约,则方程:
$
A x = b
$
可以立刻化简为:
$
P A P^T P x = P b
$
进而可以将 $n$ 阶方程组降为两个低维的方程组。
]
#proposition[][
矩阵可约的充要条件是存在 ${1, 2, ..., n}$ 的一个划分 $W, T$ 使得:
$
a_(i j) = 0, forall i in W, j in T
$
]
若一个矩阵弱严格对角占优且不可约,则称之为*不可约对角占优*。
#theorem[][
若 $A$ 严格对角占优或不可约对角占优的,则 $A$ 非奇异。
]
#proof[
我们只证明前一种情形。如若不然,则存在非零向量 $x$ 使得:
$
A x = 0
$
不妨设 $norm(x)_infinity = 1 = abs(x_i)$,则有:
$
abs(a_(i i)) = abs(a_(i i) x_i) = abs(sum_(j != i) a_(i j) x_j) <= sum_(j != i) abs(a_(i j)) < abs(a_(i i))
$
矛盾!
]
#corollary[][
若 $A$ 是严格对角占优或不可约对角占优的对称矩阵,且 $A$ 对角线元素均为正数,则 $A$ 正定。
]
#theorem[][
若 $A$ 是严格对角占优或不可约对角占优,则 Jacobi 迭代法和 Gauss - Seidel 迭代法都收敛。
]
#proof[
我们只证 Jacobi 迭代,首先由条件对角元均非零,因此 $D$ 可逆。考虑:
$
M = Inv(D) (L + U)
$
假设它有特征值 $lambda >= 1$,不难验证 $lambda D - L - U$ 也是严格对角占优/不可约对角占优的,因此非奇异。但另一方面:
$
0 = abs(lambda I - Inv(D) (L + U)) = abs(Inv(D)) abs(lambda D - L - U)
$
而前面已经说明 $Inv(D), lambda D - L - U$ 都非奇异,矛盾!
]
=== 收敛速度
#definition[][
令:
$
R_k (M) := (-ln norm(M^k))/k
$
为迭代矩阵为 $M$ 时 $k$ 次迭代的平均收敛速度。特别的,记:
$
R_infinity (M) := lim_(k -> +infinity) R_k (M)
$
称为渐进收敛速度。
]
#proposition[][
假设 $M$ 对称,则不难验证:
$
norm(M^k) = rho(M)^k
$
进而 $R_k (M) = -ln rho(M)$\
但一般而言,$R_k (M)$ 是依赖于 $k$ 的
]
#proposition[][
对于任何矩阵 $M$ 都有:
$
R_infinity (M) = - ln rho(M)
$
]
#proof[
注意到谱半径小于任何范数,因此:
$
rho(M)^k = rho(M^k) <= norm(M^k) => rho(M) <= norm(M^k)^(1/k)
$
另一方面,不难验证对于任意 $epsilon > 0$ 有:
$
rho(1/(rho(M) + epsilon) M) < 1
$
进而对于充分大的 $k$:
$
norm((1/(rho(M) + epsilon) M)^k) <= 1\
norm(M^k) <= (rho(M) + epsilon)^k\
rho(M) <= norm(M^k)^(1/k) <= rho(M) + epsilon
$
由 $epsilon$ 的任意性,得证。
]
== 超松弛迭代法 SOR
考虑 Gauss - Seidel 迭代法:
$
x_(k + 1) = Inv(D) L x_(k + 1) + Inv(D) U x_k + Inv(D) b
$
令 $Delta x = x_(k + 1) - x_k$ 称为修正项。如果给修正项加一系数 $omega$ (称为松弛因子),也即:
$
x_(k + 1) = x_k + omega Delta x
$
迭代公式变为:
$
x_(k + 1) = (1 - omega) x_k + omega (Inv(D) L x_(k + 1) + Inv(D) U x_k + Inv(D) b)
$
若 $omega > 1$ 则称为超松弛迭代,否则 $omega < 1$ 时称为低松弛迭代。上面的迭代公式等价于:
$
x_(k + 1) = L_omega x_k + omega(D - omega L)^(-1) b\
where L_omega = Inv((D - omega L)) ((1 - omega) D + omega U)
$
#theorem[][
SOR 迭代法收敛的充要条件是 $rho(L_omega) < 1$
]
#theorem[][
SOR 迭代法收敛的必要条件是 $0 < omega < 2$
]
#proof[
不难发现若迭代法收敛,则:
$
abs(det(L_omega)) < 1\
abs(det((1 - omega) D + omega U)) < abs(det(D - omega L))\
abs(det((1 - omega) I + omega U Inv(D))) < abs(det(I - omega L Inv(D)))\
abs(1 - omega)^n < abs(1)^n\
$
化简立得结果
]
#theorem[][
若 $A$ 严格对角占优或不可约对角占优的,则当 $omega in (0, 1]$ 时迭代法收敛
]
#theorem[][
若 $A$ 是实对称正定的,则当 $omega in (0, 2)$ 时迭代法都收敛。
]
#proof[
设:
$
Inv((D - omega L))((1 - omega) D + omega L) x = lambda x\
(1 - omega) D x + omega U x = lambda (D - omega L) x\
(1 - omega) x^* D x + omega x^* U x = lambda x^* D x - lambda omega x^* L x\
$
令 $x^* D x = delta, x^* L x = beta$,将有:
$
(1 - omega) delta + omega overline(beta) = lambda delta - lambda omega beta\
(1 - omega) delta + omega overline(beta) = lambda (delta - omega beta)\
$
同时我们有:
$
x^* (D - L - U) x > 0\
x^T D x > x^T L x + overline(x^T L x)\
delta > beta + overline(beta)
$<cond1>
假设 $delta = omega beta$,意味着 $beta$ 是实数,将有:
$
omega beta > 2 beta
$
与 $omega < 2$ 矛盾。因此有:
$
lambda &= ((1 - omega) delta + omega overline(beta))/(delta - omega beta) \
norm(lambda)^2 &= norm((1 - omega) delta + omega overline(beta))^2/norm(delta - omega beta)^2\
&=(((1 - omega) delta + omega overline(beta))((1 - omega) delta + omega beta))/((delta - omega beta)(delta - omega overline(beta)))\
&=((1 - omega)^2 delta^2 + omega(1-omega)delta (beta + overline(beta)) + omega^2 norm(beta)^2)/(delta^2 - omega delta (beta + overline(beta)) + omega^2 norm(beta)^2)\
&=((1 - omega)^2 delta^2 + omega delta (beta + overline(beta)) - omega^2 delta (beta + overline(beta)) + omega^2 norm(beta)^2)/(delta^2 - omega delta (beta + overline(beta)) + omega^2 norm(beta)^2)\
$
往证上式 $<1$,也即:
$
(1 - omega)^2 delta^2 + omega delta (beta + overline(beta)) - omega^2 delta (beta + overline(beta)) + omega^2 norm(beta)^2 < delta^2 - omega delta (beta + overline(beta)) + omega^2 norm(beta)^2\
-2 omega delta^2 + omega^2 delta^2 + 2 omega delta (beta + overline(beta)) - omega^2 delta (beta + overline(beta)) < 0 \
delta^2 omega (omega - 2) + omega delta (beta + overline(beta))(2 - omega) < 0 \
delta omega (2 - omega) (-delta + (beta + overline(beta))) < 0 \
$
注意到正定矩阵对角元均正,因此 $delta > 0$,结合 @cond1 立得结论成立。
// &= norm(((1 - omega) delta + omega overline(beta))(delta - omega overline(beta)))/((delta - omega beta)(delta - omega overline(beta)))\
// &= norm((1 - omega)delta^2 - omega (1-omega) delta overline(beta) + omega delta overline(beta) - omega^2 overline(beta)^2)/((delta - omega beta)(delta - omega overline(beta)))\
// &= norm((1 - omega)delta^2 + omega^2 delta overline(beta) - omega^2 overline(beta)^2)/((delta - omega beta)(delta - omega overline(beta)))\
// 假设 $lambda > -1$,则 $omega + lambda omega > 0$,有:
// $
// (omega + lambda omega) x^T D x > 2 (omega + lambda omega) x^T L x = -2 (1 - omega - lambda) x^T D x\
// (2 - omega - 2 lambda + lambda omega) x^T D x > 0\
// (lambda - 1)(omega - 2) x^T D x > 0\
// (lambda - 1) x^T D x < 0
// $
// 上面的不等式已经表明 $x^T D x != 0$,而若 $x^T D x < 0$,将有 $x^T L x < 0, lambda > 1, 1 - omega - lambda < 0, omega(1 + lambda) > 0$
]
|
|
https://github.com/alberto-lazari/unipd-typst-doc | https://raw.githubusercontent.com/alberto-lazari/unipd-typst-doc/main/examples/essay.typ | typst | MIT License | #import "@local/unipd-doc:0.0.1": *
#show: unipd-doc(
title: [Title],
subtitle: [Subtitle],
author: [The author],
date: [DD-MM-YY],
)
= Heading
#lorem(50)
== Heading 2
#lorem(30)
#lorem(20)
=== A list
- A list of items
- Custom bullets
- For indented items
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/Queues.typ | typst | #import "../../../template.typ": *
= Queues
#definition[
A *queue* is a first in, first out abstract data type. Thus, queue and dequeue operations occur at _opposite_ ends of the structure
The main operations for queues include:
- *enqueue(data)* - adds data to the "back" of the queue
- *dequeue()* - removes the data from the front of the queue
- *peek* - returns the data at the front without removing it
]
== SLL Backed Queue
#note[
The SLL-backed queue requires a _tail pointer_ in order to get O(1) operations.
The "front" of the queue is the front of the list where data is dequeued from, while the "back" of the queue is the back of the list where data is enqueued
*enqueue(data)* -> *addToBack(data)*, and *dequeue()* -> *removeFromFront()*
]
== Array Backed Queue
#note[
Array backed queues require a size variable but also a front variable, because _the array behaves circularly_.
*arr[front]* is the front of the queue, and *arr[(front + size) % arr.length]* is the first empty index at the "back"
]
For *enqueue*
- Put the element at arr[(front+size) % arr.length] then size++
For *dequeue*
- Remove the element at arr[front], increment front and decrement size
- In this case, front = (front + 1) % arr.length when you increment so that _front never goes out of bounds_
== Dequeue
#note[
In Deques (double ended queues), we can add and remove from either side of the deque
The main operations include:
- *addFirst(data)*
- *addLast(data)*
- *removeFirst()*
- *removeLast()*
]
=== DLL Backed Queue
#note[
The DLL backed queue requires a tail.
*addFirst(data)* -> *addToFront(data)*: O(1)
*addLast(data)* -> *addToBack(data)*: O(1)
*removeFirst()* -> *removeFromFront()*: O(1)
*removeLast()* -> *removeFromBack()*: O(1)
]
=== Array Backed Deque
#note[
Uses a front variable and a size variably (_circular again_)
*Important Indices*
- arr[(front - 1) % capacity] = addFirst()
- arr[front] = removeFirst()
- arr[(front + size) % capacity] = addLast()
- arr[(front + size - 1) % capacity] = removeLast()
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.