text:
# Is a closed embedding of CW-complexes a cofibration?

It is a standard fact that the inclusion of a sub-CW-complex into a CW-complex is a cofibration, it follows from the fact that the inclusions $$S^k\to D^{k+1}$$ are, and that they are preserved by pushouts.

My question is about a general closed embedding of a CW-complex into another one, say $$f:Y\to X$$; but it's not necessarily cellular, and even if it were, it doesn't necessarily witness $$Y$$ as a sub-CW-complex of $$X$$.

Is it still necessarily a cofibration ?

If it helps/changes the answer, we may assume that $$Y$$ or both $$X,Y$$ are finite dimensional, or even finite (though if the answer is "yes" for one of these cases with more hypotheses and "no" with fewer hypothese, I would still be interested in counterexamples for fewer hypotheses)

• Surely the Alexander horned sphere is not an NDR, but a proof escapes me. – user98602 Feb 13 at 22:31
• @MikeMiller I had the same idea and tried to prove it - but I discovered that is an NDR. – Paul Frost Feb 14 at 10:16

This is only a partial answer:

If $$X$$ is a locally finite CW-complex and $$A \subset X$$ is a closed subspace which is also a CW-complex (but not necessarily a subcomplex), then $$i : A \hookrightarrow X$$ is a cofibration.

This is based on three well-known facts.

(1) Locally finite CW-complexes are metrizable.

See e.g. Proposition 1.5.17 of [1].

(2) Metrizable CW-complexes are ANRs.

This is due to the fact that CW-complexes are absolute neighborhood extensors for metrizable spaces.

(3) If $$X$$ is an ANR and $$A$$ a closed subset of $$X$$, then the following are equivalent:

a) the inclusion $$i : A \to X$$ a cofibration.

b) $$A$$ is an ANR.

See for example Proposition A.6.7 of [1].

[1] Fritsch, Rudolf, and Renzo Piccinini. Cellular structures in topology. Vol. 19. Cambridge University press, 1990.

https://epub.ub.uni-muenchen.de/4493/1/4493.pdf

• This is already great, thank you ! I'll wait and see of someone can bring more information (e.g. the general case, or replacing "locally finite" with "finite dimensional" ) – Max Feb 14 at 10:51
• Wow, (3) is much more flexible than I would have ever guessed. – user98602 Feb 19 at 19:39

If you don‘t insist on finiteness of the CW-complex, then you may take for $$X$$ an infinite CW-complex and $$Y$$ its one-point-compactification. For example, if $$X=R^n$$, then $$Y=S^n$$ is a CW-complex. But the inclusion $$X\to Y$$ is not a cofibration because its image is not closed. (Or because there exist homotopies which are not proper and thus do not extend.)

• Thank you; but I actually meant a closed embedding, I'm sorry about that; I'll edit my question accordingly – Max Feb 13 at 22:29

format: plain


text:
# Writing your own NES emulator Part 3 - the 6502 CPU

Emulating the NES 6502 CPU

It’s been a while since the last update - I was mostly focusing on database technologies. Beginning of the year 2021 is a bit slow (that’s when many big companies start their annual / semi-annual review process), so I had a bit of time to write up this post about 6502 CPU emulation. All the code referenced in this post is in my simple NES emulator github repo NesChan. It’s fun to go back and look at my old code and the 6502 CPU wiki.

## The 6502 CPU

NES uses 8-bit 6502 CPU with 16-bit address bus, meaning it can access memory range 0x0000~0xffff - not much, but more than enough for games back in the 80s with charming dots and sprites. It is used in a surprising large range of famous vintage computers/consoles like Apple I, Apple II, Atari, Commodore 64, and of course NES. The variant used by NES is a stock 6502 without decimal mode support. It is running at 1.79HMZ (PAL version runs at 1.66MHZ). It has 3 general purpose register A/X/Y, and 3 special register P (status) /SP (stack pointer) /PC (program counter, or instruction pointer), all of them being 8-bit except PC which is 16-bit. NES dev wiki has a great section on 6502 CPU that has a lot more details and we’ll be covering the most important aspects in the remainder of the article.

To emulate the CPU, the main loop would look something like this:

1. We start at a memory location by set current program counter (also known as instruction pointer in other architectures) PC to that location
2. Check if we reached the special end condition (end of program, BRK instruction, infinite loop, etc…), if met, terminate the execution process
3. Decode CPU instruction at current PC
4. Set instruction pointer to next instruction
5. Fetch data as per memory access mode
6. Execute instruction with data fetched
7. Move to the next instruction by going back to 2

The most interesting aspect are instruction decoding, memory access modes, and instruction execution. Let’s look at this one by one.

## Decoding the instructions

Assembly instructions are usually encoded with 3 character memonics and they typically perform very low level hardware related operations supported by the CPU, to keep CPU simple and reduce cost. That’s why assembly instructions are considered low level. High-level language statements are usually compiled down to one or more CPU instructions, with the help of compiler. This is a perfect example of layering.

Let’s just take a look at a few examples of what 6502 CPU can do:

• DEC, DEX, DEY for decrementing memory, X register, Y register, respectively
• JMP for jumping to a particular address to keep executing code
• LDA, LDX, LDY for loading A/X/Y register into target location, depending on the memory address mode
• ADC, SBC for addition / subtraction using the A register (accumulator) and specified memory location, so basically A += M and A-= M, taking carry flag into account as well

If you are interested to know more, you can go to this page for a list of common 6502 CPU instructions and what they do.

Before executing the instruction, you need to first look up the bytes in memory and understand which instruction it represents, what is the arguments, etc. This is called decoding. Fortunately, 6502 CPU instructions are always single byte, only the arguments differ by memory access mode. This makes the decoding much easier - we just need a big table of all instructions and then call the right helper function for that instruction based on the byte!

We’ll look at memory access mode later. For now you’ll just need to know they indicates where the actual data is coming from, while the instruction itself is the operation. Instruction typically supports different memory access modes so that it can operate on different data from different locations using different methods, whether it is register, memory, etc.

In order to build the table, it’s useful to visualize it by looking at the following table from nesdev unofficial opcodes wiki:

But in order to see the patterns a bit better, let’s re-arrange it:

You can see the ALU (green ones, that does math operations) and the RMW (blue ones, = Read Modify Write) instructions follow a very clear pattern, while the red (mostly control instructions) and gray (unofficial / undocumented instructions) are sort of all over the place.

To keep things simple (and make modification easier, as I was still learning the instructions, and I don’t want to do it over when I misunderstood something), in the current implementation I went with a switch case approach with macros. This could be easily updated to use a real table with helper function pointers. You might think the jump table approach might be faster, but actually the reality can be a bit more complicated: compiler should easily create a jump table, and jumping into inlined version of the helper functions directly, end up being much faster than a jump table solution. Such optimization are actually more difficult with function pointers (but not impossible). Either way, since I’m not optimizing for a benchmark but to run NES games, I didn’t care too much about performance.

For example, for ALU instructions we use this macro in nes_cpu.cpp:

#define IS_ALU_OP_CODE_(op, offset, mode) \
case nes_op_code::op##_base + offset : \
break;

This defines a case statement for a variant of instruction op. For example, for ADC, offset 0x9 is ADC with immediate memory access mode. We’ll be calling to the op helper function for executing the code with the corresponding memory access mode. NES_TRACE4 is for logging and we can ignore that for now.

And for each particular ALU instruction, we define 8 variants of all memory access patterns based on the table earlier:

#define IS_ALU_OP_CODE(op) \
IS_ALU_OP_CODE_(op, 0x9, imm) \
IS_ALU_OP_CODE_(op, 0x5, zp) \
IS_ALU_OP_CODE_(op, 0x15, zp_ind_x) \
IS_ALU_OP_CODE_(op, 0xd, abs) \
IS_ALU_OP_CODE_(op, 0x1d, abs_x) \
IS_ALU_OP_CODE_(op, 0x19, abs_y) \
IS_ALU_OP_CODE_(op, 0x1, ind_x) \
IS_ALU_OP_CODE_(op, 0x11, ind_y)

For example, ADC + 0x9 is immediate mode, ADC + 0x5 is zero page mode, etc.

Then we can support a series of ALU instructions easily with these macros:

        IS_ALU_OP_CODE(ADC)
IS_ALU_OP_CODE(AND)
IS_ALU_OP_CODE(CMP)
IS_ALU_OP_CODE(EOR)
IS_ALU_OP_CODE(ORA)
IS_ALU_OP_CODE(SBC)

Take a simple instruction as an example, the code looks like follows:

// Logical AND
{
A() &= val;

// flags
calc_alu_flag(A());

// cycle count
}

• decode_operand is responsible for decoding the following bytes based on the address mode, and return the access pattern in operand_t
• Next we proceed to read the operand using op into val. The reason the decoding and reading are separate step is because some instruction do read, write, or both, so it is useful to separate them into different helpers.
• Once we read the val, as per AND instruction, we AND the accmulator A register with val and then write it back. Note we have helpers that return registers (which really are just variables) as reference so the code reads quite naturally:
    uint8_t &A() { return _context.A; }
uint8_t &X() { return _context.X; }
uint8_t &Y() { return _context.Y; }
uint16_t &PC() { return _context.PC; }
uint8_t &P() { return _context.P; }
uint8_t &S() { return _context.S; }

• Based on the result of A, we need to update the ALU zero/negative flags accordingly. Those flags are typically checked at beginning of instruction and updated at the end of instruction, usually for math operations (carry flag) or controls (jump if zero). For a full list flags you can refer to this list.
• Finally, we simulate the passing of CPU cycles (or rather, time). This is important for accuracy of emulation as many games rely this for timing, especially to synchronize with GPU cycles! Now that’s what we call real programmers .

## Memory access mode

This is one of the more complicated aspect of 6502 CPU. Many instructions have different modes when it comes to where the operands are coming from. This is the full list of all suppported modes:

AbbrNameNotes
ImpImplicitInstructions like RTS or CLC have no address operand, the destination of results are implied.
AAccumulatorMany instructions can operate on the accumulator, e.g. LSR A. Some assemblers will treat no operand as an implicit A where applicable.
#vImmediateUses the 8-bit operand itself as the value for the operation, rather than fetching a value from a memory address.
dZero pageFetches the value from an 8-bit address on the zero page.
aAbsoluteFetches the value from a 16-bit address anywhere in memory.
labelRelativeBranch instructions (e.g. BEQ, BCS) have a relative addressing mode that specifies an 8-bit signed offset relative to the current PC.
(a)IndirectThe JMP instruction has a special indirect addressing mode that can jump to the address stored in a 16-bit pointer anywhere in memory.

There are also more complicated memory access modes using the above:

AbbrNameFormulaCycles
d,xZero page indexedval = PEEK((arg + X) % 256)4
d,yZero page indexedval = PEEK((arg + Y) % 256)4
a,xAbsolute indexedval = PEEK(arg + X)4+
a,yAbsolute indexedval = PEEK(arg + Y)4+
(d,x)Indexed indirectval = PEEK(PEEK((arg + X) % 256) + PEEK((arg + X + 1) % 256) * 256)6
(d),yIndirect indexedval = PEEK(PEEK(arg) + PEEK((arg + 1) % 256) * 256 + Y)5+

In the code I have a enum for all the supported modes:

// Addressing modes of 6502
{
nes_addr_mode_ind_jmp,    //          val = peek16(arg_16), with JMP bug
nes_addr_mode_rel,        //          val = arg_8, as offset
nes_addr_mode_abs,        //          val = PEEK(arg_16), LSB then MSB
nes_addr_mode_zp_ind_x,   // d, x     val = PEEK((arg_8 + X) % $FF ), 4 cycles nes_addr_mode_zp_ind_y, // d, y val = PEEK((arg_8 + Y) %$FF), 4 cycles
nes_addr_mode_abs_x,      // a, x     val = PEEK(arg_16 + Y), 4+ cycles
nes_addr_mode_abs_y,      // a, y     val = PEEK(arg_16 + Y), 4+ cycles
nes_addr_mode_ind_x,      // (d, x)   val = PEEK(PEEK((arg + X) % $FF) + PEEK((arg + X + 1) %$FF) * $FF), 6 cycles nes_addr_mode_ind_y, // (d), y val = PEEK(PEEK(arg) + PEEK((arg + 1) %$FF)* $FF + Y), 5+ cycles };  Recall that in instruction implementation we call decode_operand and read_operand (there is also write_operand) to decode and then read the target (whether it is register, an address, etc). So all the magic for decoding memory address modes are in there. For example, following code in decode_operand_addr (used in decode_operand internally supports indirect y mode:  else if (addr_mode == nes_addr_mode::nes_addr_mode_ind_y) { // Indirect Indexed // implies a table of table address in zero page uint8_t arg_addr = decode_byte(); uint16_t addr = peek(arg_addr) + (uint16_t(peek((arg_addr + 1) & 0xff)) << 8); uint16_t new_addr = addr + _context.Y; return new_addr; }  ## Show me the RAM Accesing “RAM” in a emulator in theory should be easy, right? Just reserve a “big chunk” of whopping 64K RAM and access that. Unfortunately it is a little bit more complicated than that: • The system only has built-in 2KB RAM - RAM is expensive those days • Some memory are mapped to I/O (such as PPU) registers so accessing those registers become simple memory operations, rather than, say, dedicated instructions • When NES cartridges are inserted, its onboard data (RAM, ROM) are mapped onto the 64K memory space as well So the actual memory layout looks like this: Address rangeSizeDevice$0000-$07FF$08002KB internal RAM
$0800-$0FFF$0800Mirrors of$0000-$07FF$1000-$17FF$0800Mirrors of $0000-$07FF
$1800-$1FFF$0800Mirrors of$0000-$07FF$2000-$2007$0008NES PPU registers
$2008-$3FFF$1FF8Mirrors of$2000-2007 (repeats every 8 bytes)
$4000-$4017$0018NES APU and I/O registers$4018-$401F$0008APU and I/O functionality that is normally disabled. See CPU Test Mode.
$4020-$FFFF$BFE0Cartridge space: PRG ROM, PRG RAM, and mapper registers (See Note) For more details you can refer to this page in NES wiki. Dealing with cartridges and mappers are another big topic and a whole lot of complexity which we’ll cover a bit later. For now we’ll treat it as a black box. All these means that whenever you write to a byte you need to do a bit of indirection (just like most of magic in computer science): nes_memory.cpp void nes_memory::set_byte(uint16_t addr, uint8_t val) { redirect_addr(addr); if (is_io_reg(addr)) { write_io_reg(addr, val); return; } if (_mapper && (_mapper_info.flags & nes_mapper_flags_has_registers)) { if (addr >= _mapper_info.reg_start && addr <= _mapper_info.reg_end) { _mapper->write_reg(addr, val); return; } } _ram[addr] = val; }  ## Testing I use doctest which is a simple and convenient testing framework that is good enough for my needs. At the beginning I write manual tests - basically execute a bunch of instructions until BRK (stop the system) and verify the state of the CPU and RAM: cpu_test.cpp TEST_CASE("CPU tests") { nes_system system; SUBCASE("simple") { INIT_TRACE("neschan.instrtest.simple.log"); cout << "Running [CPU][simple]..." << endl; system.power_on(); system.run_program( { 0xa9, 0x10, // LDA #$10     -> A = #$10 0x85, 0x20, // STA$20      -> $20 = #$10
0xa9, 0x01,     // LDA #$1 -> A = #$1
0x65, 0x20,     // ADC $20 -> A = #$11
0x85, 0x21,     // STA $21 ->$21=#$11 0xe6, 0x21, // INC$21      -> $21=#$12
0xa4, 0x21,     // LDY $21 -> Y=#$12
0xc8,           // INY          -> Y=#\$13
0x00,           // BRK
},
0x1000);

auto cpu = system.cpu();

CHECK(cpu->peek(0x20) == 0x10);
CHECK(cpu->peek(0x21) == 0x12);
CHECK(cpu->A() == 0x11);
CHECK(cpu->Y() == 0x13);
}

But this quickly get tedious. Fortunately, there are a lot of existing test roms. I’m been using this one - it is fairly comprehensive. This does mean I need to implement a rudimentary ROM loading first (which we won’t cover here), but once that’s ready I can just load the ROM and follow the convention of the test ROM - in this case it means checking peek(0x6000) == 0.

#define INSTR_V5_TEST_CASE(test) \
SUBCASE("instr_test-v5 " test) { \
INIT_TRACE("neschan.instrtest.instr_test-v5." test ".log"); \
cout << "Running [CPU][instr_test-v5-" << test << "]" << endl; \
system.power_on(); \
auto cpu = system.cpu(); \
cpu->stop_at_infinite_loop(); \
system.run_rom("./roms/instr_test-v5/rom_singles/" test ".nes", nes_rom_exec_mode_reset); \
CHECK(cpu->peek(0x6000) == 0); \
}

With that I can run a bunch of ROMs as regression tests, much better:

    INSTR_V5_TEST_CASE("01-basics")
INSTR_V5_TEST_CASE("02-implied")
// INSTR_V5_TEST_CASE("03-immediate")
INSTR_V5_TEST_CASE("04-zero_page")
INSTR_V5_TEST_CASE("05-zp_xy")
INSTR_V5_TEST_CASE("06-absolute")
// INSTR_V5_TEST_CASE("07-abs_xy")
INSTR_V5_TEST_CASE("08-ind_x")
INSTR_V5_TEST_CASE("09-ind_y")
INSTR_V5_TEST_CASE("10-branches")
INSTR_V5_TEST_CASE("11-stack")
INSTR_V5_TEST_CASE("12-jmp_jsr")
INSTR_V5_TEST_CASE("13-rts")
INSTR_V5_TEST_CASE("14-rti")
// INSTR_V5_TEST_CASE("15-brk")
// INSTR_V5_TEST_CASE("16-special")
}

Some of the commenting are most likely signs there are still bugs in CPU emulation.

## Conclusion

It took me a few days to implement all CPU and get majority of the CPU tests to pass. Things are a bit more subtle than I expected, but that’s probably the case for emulating real world CPU which always has its own quirks or even bugs, and the documentation has bugs too (which are hard to find unless you test with a real CPU or a emulator). There are quite a bit of subtle behavior I didn’t cover (such as page crossing, etc) that I need to get exactly right. Getting CPU emulation correct is absolutely critical for getting games working, not surprisingly. One thing that did surprise me is that the last bug that prevented Super Mario Bros from working is bugs in my CPU emulation, including a documentation bug. If I remember correctly I had to debug it with another emulator side by side to find out the exact problem. On retrospective I probably should’ve get all the CPU tests working properly, and the fact that I had disabled a few (especially the earlier ones from 1-14) is definitely red flag. Unfortunately I was too excited to push ahead and “mostly working” is deemed “good enough”, which turned out to be a big mistake. That’s why we work on side projects - have fun, and learn something doing it.

## If you are hungry for more NES…

Head to NESDev Wiki - I’ve learned pretty much everything about NES there. There is also a great book on NES called I am error, which is surprisingly deeply technical for a book about history of NES.


text:
Browse Questions
Home  >>  AIMS

# How many circles can be drawn passing through three non-collinear points?

$\begin{array}{1 1}(A)\;1&(B)\;2\\(C)\;0&(D)\;\text{Infinite}\end{array}$

1
Hence (A) is the correct answer.


text:
# Samples and Surveys

In this video, we are going to look at samples and surveys.

First, let’s identify a population. A population is a total group of something that we are going to analyze. For example, if we wanted to see where the high school seniors want to go on a school trip, then the population is high school seniors. Instead of asking every single high school senior, we only want to look at part of the group. This part of the group is called a sample. It would be much easier and more efficient to only interview a percent of the high school seniors. We can safely assume that the opinions of this percentage can represent the high school seniors as a whole if we pick the sample wisely.

Now we will talk about a bias. Different groups of people can have different opinions. If you want a good representation of a group, you want to make sure that you cover the entire group, and not just certain sectors of the group.

For example, going back to the high school trip, if you ask the football team where to go on the trip, it would make sense that they would want to see a football game. If you ask the students in the theater where they want to go, it would make sense for them to want to see a play. You don’t want to focus the sample on just one group of people. It should represent the entire population. In order to do this, you would want to do random sampling. For example, you might want to ask every fifth student who enters school. You do not want to just ask the students at the gym, or at the library, or in a theater. Not every student may go to the gym, or be in the library, or be in a theater, but every student must enter school, so this method would best represent the population as a whole.

## Video-Lesson Transcript

Let’s go over samples and surveys.

First, what is a sample?

Before we identify the sample, we have to identify the population.

A population is a total group of people or whatever it is that we are looking at what we want to analyze.

For example, we have high school seniors and we want to know where do they want to go for their school trip.

The population here is the high school seniors.

But if we want to have an idea of where do they want to go, we don’t want to interview all of them.

What we want to do is to interview a part of them or a part of the population.

This part of the population is the sample.

It will be a lot easier and efficient if we can do $10\%$ of everybody.

If we pick the group nicely, we can assume that that $10\%$ will share the same opinion with the entire population of high school senior students.

It’s very important to pick the sample wisely.

Another example.

Let’s say you are writing for a fitness blog and you’re thinking what article be best to write next.

In order to do that, you should know what the readers like.

The entire population that you’re concerned with is the readers of the blog.

But the readers vary greatly day-to-day from a hundred to ten thousand.

You don’t want to interview every single person because it might be annoying to them and it might also be too much data for you.

So, you just have to take a part of the population of readers to be your sample.

But again, you want to make sure to choose your sample wisely in order to get a good representation of all the readers.

Now, let’s go to something we call bias.

Different groups of people tend to have different opinions just like individuals have different opinions.

If you want to make a good representation of the population, you want to make sure that you cover the entire population not just sectors of the group.

For example, the high school trip.

It will make sense that if you ask the football team where they want to go, they might say a football game.

If you ask students in the theater where they want to go, they may say a play.

And other groups have different opinions.

So, you don’t want to focus your sample on just one type of group of people.

The sample should represent the entire population.

We don’t want to interview all the students. But we want to represent everyone in the population.

How do we do that?

We’ll do a random sampling.

Maybe every fifth student who enters school.

You don’t want to ask students at the gym. You don’t want to ask students at the library. Don’t ask students in theater.

But every student who enters school. Here, you will have a varied random sampling of students.

Not every student goes to the gym, or in the library, or in the theater.

If you choose something that every student takes part in such as entering school or entering the cafeteria, that will be a random sampling.

Now, let’s do the same thing for your blog.

Do you want to know what will be your next fitness article?

The population is everyone who visits the blog.

If you have a yoga section, readers are interested in yoga only.

If you have a weightlifting section, readers are biased towards that topic.

Readers on eating well section will be interested in this types of articles.

But since you want to get the opinion of all people who read your blog, it will be the best to have a survey on the main page.

This way no bias is built in.

Anybody could be on the main page. Not only readers who are interested in yoga, weightlifting, and eating well.

This survey can show up for only a couple of hours. Maybe it can show up to every other visitor. Or maybe it can be on at five minutes at a time at random parts of the day.

In this way, you cover everyone who goes to the blog without actually interviewing every single person.


text:
## Theorem

Let $\left({G, +_G, \circ}\right)_R$ and $\left({H, +_H, \circ}\right)_R$ be $R$-modules.

Let $\phi: G \to H$ and $\psi: G \to H$ be linear transformations.

Let $\phi +_H \psi$ be the operation on $H^G$ induced by $+_H$ as defined in Induced Structure.

Then $\phi +_H \psi: G \to H$ is a linear transformation.

## Poof

From the definition of a module, the group $\left({H, +_H}\right)$ is abelian.

Therefore we can apply Homomorphism on Induced Structure to show that $\phi +_H \psi: G \to H$ is a homomorphism.

Then:

 $\displaystyle \left({\phi +_H \psi}\right) \left({\lambda \circ x}\right)$ $=$ $\displaystyle \phi \left({\lambda \circ x}\right) +_H \psi \left({\lambda \circ x}\right)$ $\displaystyle$ $=$ $\displaystyle \lambda \circ \phi \left({x}\right) +_H \lambda \circ \psi \left({x}\right)$ $\displaystyle$ $=$ $\displaystyle \lambda \circ \left({\phi \left({x}\right) +_H \psi \left({x}\right)}\right)$ $\displaystyle$ $=$ $\displaystyle \lambda \circ \left({\phi +_H \psi}\right) \left({x}\right)$

$\blacksquare$


text:
# How is Plutus Compiled to Plutus Core?

High level:

GHC: Haskell -> GHC Core
Plutus Tx compiler: GHC Core -> Plutus IR
Plutus IR compiler: Plutus IR -> Typed Plutus Core -- Can we target this instead??
Type eraser: Typed Plutus Core -> Untyped Plutus Core

## In-depth

GHC Core is part of GHC compilation pipeline. To intercept it, we need a GHC plug-in. This gets run during the GHC compilation process, and is able to access and modify the program that GHC is compiling.

We want to then retrieve it and place it back into the main Haskell program.

This is because the transactions we submit need to include these (plutus core) scripts.

Hence we can represent this as:

compile :: forall a . a   -- expression we compile
-> CompiledCode a -- plutus core output

### A catch: Compile is a function?! but it causes side-effects!

Compile is not actually a function but a label.

The GHC plugin we implement trawls through the program to find applications of compile, and inlines the compiled code.

### Another catch: How do we deal with runtime depedencies?

Suppose we have a function, which has runtime values as input. Since these runtime values need to be passed on-chain, we need to compile them as well.

How can we apply these?

Well because of functional approach we can compile runtime values, then pass them in.

Compile time we wrap these in Typeable which describes how we map haskell types to plutus core types. We also have Lift which describes how to turn a Haskell value into a Plutus Core value.


text:
An object at rest has three forces acting on it. The first force is289. N acting along the positive x-axis. The second force is 447. Nacting at an angle of 55. degrees relative to the positive x-axis.What is the x component of the third force?

What is the y component of the third force?

What is the MAGNITUDE of the third force?

What is the angle (in degrees) of the third force?The angle should be measured from the positive x-axis in thecounter-clockwise direction. That is, it is some number between 0and 360. (Do not include units.) I

Im getting magnitude of 656N, X-component 545N, and angle34 !!


text:
# Solution: A bedroom has a volume of 115m3. What is its volume in:  b....

###### Question

A bedroom has a volume of 115m3. What is its volume in:

b. dm3

###### Video Transcript

Hey guys, on this question we're told that a room has a volume of 115 meters cubed and we have to convert those meters cubed into decimeters cubed. So we're going to start out with 115 meters cubed we want to get rid of meters so meters goes on the bottom decimeters goes on top, deci is a metric prefix and remember 1 is associated with a metric prefix so 1 deci is 10^-1 but meters and meters cubed will not cancel out completely so we have to cube this entire thing, what effect does that have? So we're going to have 115 meters cubed, now here this is really -1x3 so it's going to be 10^-3, so 10^-3 meters cubed on the bottom and then 1 decimeters cubed on the top so this cancels out with this so what we get at the end is 1.15x10^-1 decimeters cubed and I actually no it wouldn't be -1 it would be to the 5 actually. So that will be our answer 1.15x10^5 decimeters cubed.


text:
Level probe

A level probe is a special pressure transmitter for level measurement of liquids in open vessels and tanks. Level probes are submerged directly into the liquid and remain permanently floating above the tank bottom.  The measurement is carried out according to the hydrostatic principle. The gravity pressure of the liquid column causes an expansion of the pressure-sensitive sensor element, which converts the measured pressure into an electrical standard signal. The connecting cable of level probes has several tasks to fulfil. In addition to the power supply and signal forwarding, the level sensor is held in place by the cable. The cable also includes a thin air tube that directs the ambient air pressure to the level probe. Level probes are therefore usually designed as relative pressure sensors, which use the current ambient pressure as the zero point of their measuring range.

Without this so-called relative pressure compensation, level probes would not only measure the hydrostatic pressure but also the air pressure on the liquid column. At sea level, this is about 1013 mbar - which would correspond to the pressure exerted by a water column ten meters high.  In addition, a variable air pressure would affect the measurement result. Typical air pressure fluctuations of about +/- 20 mbar, corresponding to +/- 20 cmWs (water column).

For deep well designs, the Sealed Gauge measuring principle is also used. From a depth of approx. 20 m, the relative pressure can only be compensated to a limited extent by the thin hose. The level sensor is then designed as an absolute pressure transmitter whose zero point is adjusted to the desired mean air pressure depending on the location of use. This means that the level sensor no longer has any connection to the atmosphere. Possible fluctuations in air pressure may have an impact on the measurement result, but they play a rather minor role in deep well wells.

Measuring principle

Hydrostatic pressure, also gravity pressure or gravity pressure, occurs within a stationary fluid. It is caused by gravity and depends on the density and height of the liquid column. The mass of the fluid does not matter - see also hydrostatic paradox - i. e. not the total weight of the liquid in the container, but the filling level is decisive.

${\displaystyle p(h)=\rho gh+p_{0}}$

${\displaystyle \rho }$ = Density [for water: ${\displaystyle \rho }$ ≈ 1.000 kg/m³]
${\displaystyle g}$ = Gravitational constant [: ${\displaystyle g}$ ≈ 9,81 m/s²]
${\displaystyle h}$ = Height of the liquid column
${\displaystyle p_{0}}$ = Ambient air pressure
${\displaystyle p(h)}$ = hydrostatic pressure

The measuring minimum level starts from a complete covering of the measuring element near the head end of the level sensor. Filling levels below the level probe are not detected. Depending on the application and mounting height, it is therefore necessary to adjust the level in the evaluation unit to the respective mounting height with an offset setting.

Design types

Depending on the requirements of the site, level probes offer different features:

Protective cap
Size and number of openings / holes
Housing material
Stainless steel, Ttitanium, PTFE
Cable material
PE, FEP, PURE EPR, PA
Measuring principle
Relative or sealed gauge
Sensor technology
Piezoresistive silicon sensor, ceramic thick-film sensor, ceramic capacitive


text:
The exact value of $\lim_{n \to \infty} \frac{a_n}{\sqrt[4]{n^3}}$ [duplicate]

Let $a_1=1$ and $a_{n+1}=a_n+\frac{\sqrt{n}}{a_n}$. If it exists, find $$\lim_{n \to \infty} \frac{a_n}{\sqrt[4]{n^3}}$$

Obviously, $a_n \to \infty$ and $a_n$ is strictly increasing. I tried to get rid of that $n$ in the limit and get only $a_n$ terms in the numerator so that I could substitute $a_n$ to $x \to \infty$ and maybe use L'Hospital to finish. But $a_{n+1}, a_n$ and $\sqrt{n}$ are so tightly connected that I didn't manage to do that.

Another approach was Cesaro-Stolz, writing the limit as $$\lim_{n \to \infty}\left(\sqrt[4]{\frac{\sqrt[3]{a_n^4}}{n}}\right)^3=\left(\lim_{n \to \infty}\left(\sqrt[3]{a_{n+1}^4}-\sqrt[3]{a_n^4}\right) \right)^\frac{3}{4}$$ but I encountered the same issue. I'm even wondering if there is a nice closed form for the limit.

Edit: As pointed below, if the limit exists, then its value is $\frac{2}{\sqrt{3}}$. How can we prove that it exists?

marked as duplicate by Martin R, Community♦Jan 12 '18 at 13:58

Assume the limit $$l=\lim_{n \to \infty} \frac{a_n}{n^{3/4}}$$ exists and is nonzero, then it is very easy to see that $l=2/{\sqrt{3}}$. To see why, consider $$\lim_{n\to\infty} \frac{{{a_{n + 1}} - {a_n}}}{{{{(n + 1)}^{3/4}} - {n^{3/4}}}} =\lim_{n\to\infty} \frac{{\sqrt n }}{{{{(n + 1)}^{3/4}} - {n^{3/4}}}}\frac{1}{{{a_n}}} = \frac{4}{3}\lim_{n\to\infty}\frac{{{n^{3/4}}}}{{{a_n}}} = \frac{4}{3l}$$
Hence by Stolz's theorem, $l=4/(3l)$.
• If it exists, it must be nonzero, because $a_n \geq \sqrt[4]{n^3}.$ I tried to use this inequality in order to prove that $\frac{a_n}{\sqrt[4]{n^3}}$ is eventually decreasing, but it is not strong enough – Shroud Jan 10 '18 at 14:03


text:
# What is an Unun: RF Antenna Unun

## RF antenna Ununs are unbalanced to unbalanced RF transformers typically used with antennas like end fed wires where impedance transformation is required to match the coaxial feeder.

RF Antenna Baluns & Ununs Includes:
Antenna Balun basics     Current balun     Unun basics

Although the name "Unun" sounds a little unusual, it refers to a component that has many similarities to the more familiar balun.

A balun provides a balanced to unbalanced transformation for feeder systems. By the same logic, an unun provides an unbalanced to unbalanced transformation.

The main purpose of an antenna unun is to provide an impedance transformation, and it is often used with end fed wire antennas, and in particular with end fed half wavelength wires. They can also be used with vertical antennas which are also unbalanced.

## Antenna unun applications

An antenna unun is effectively a form of RF transformer that is used to interface two different impedance levels both of which have an unbalanced line.

Coaxial cable is an unbalanced form of feeder, i.e. it has a screen and a centre and the screen is normally earthed. A balanced feeder, by contrast has two lines, neither of which is earthed - the two lines carry equal and opposite signals, so the fields cancel out and no power is radiated.

Also antennas can be balanced or unbalanced. The dipole is an ideal example of a balanced form of antenna because neither of the two sections at the feed point is earthed.

Conversely there are many antennas like end fed wires or vertical antennas where the antenna uses an earth as part of the antenna, and this requires an unbalanced form of feeder like coaxial cable.

If an impedance transformation is required at the feed point of the antenna, then this can be accomplished using an unun.

Often quarter wave vertical antennas have a feed impedance of around 20Ω. This is too low if it is to be fed directly using 50&Omega coaxial feeder cable. To overcome this issue, an autotransformer is often included in the base assembly. This is effectively an unun which matches the 20Ω of the vertical antenna with the 50Ω of the coaxial feeder.

The ununs used for matching quarter wave or similar vertical antennas are normally contained within the base of commercial manufactured vertical antennas ad therefore they are not often seen as separate items.

However there is an increasing level of use of end fed wire antennas. In past years, these were often brought directly into the radio room and interfaced via an antenna tuning unit.

To obtain the best performance and also keep the levels of RF energy away from occupied areas, the best way is to install the end fed wire in the open and away from inhabited areas and then to feed the antenna using coaxial cable. As the feed impedance of an end fed wire, and in particular the increasingly popular end fed half wave antenna, a means of matching the feeder to the antenna is required at its feed point. This matching can be obtained using an unun.

## Difference between balun and unun

As baluns an ununs are both used in antenna systems and they both provide functions associated with matching the antenna to the feeder, there is often a lot of confusion between the two. Many people ask what the difference is between a balun and an unun.

IN essence a balun enables a transition between an unbalanced and a balanced system, whereas an unun works with unbalanced systems at both the input and output.

Naturally there are circuit differences as well. The unun has an earth side connection for both the input and output, whereas the balun only has an earth side connection for the unbalanced side.

It is worth noting that in the case of the balun, the outer of the coaxial cable which is at earth potential is connected to the centre point, leaving the ends of the autotransformer balanced and not earthed to RF.

## Unun basics

The theory behind the unun is basically the same as any transformer. That said, with high frequencies being used than for power line transformation or audio, etc, factors such as the loss in any formers, interwinding capacitance, etc need to be considered more closely.

As with any transformer the impedance transformation is equal to the square of the turns ratio.

$\frac{{Z}_{\mathrm{in}}}{{Z}_{\mathrm{out}}}=\frac{{N}_{\mathrm{in}}^{2}}{{N}_{\mathrm{out}}^{2}}$

This means that for an unun with the output circuit having twice as many turns as the input, the impedance will be transformed by a factor of four.

## Practical ununs

Ununs are often wound as an autotransformer. The windings are also often wound together so that there are two, three, four windings together.

This means that where there are two windings together, the impedance transformation ratio will be 22, i.e. 1:4 giving a match to 200Ω with 50&Omega coax.

Some ununs will have three windings, so the the impedance ratio is 23, or 1:9 giving a match to 450Ω when used with 50Ω coax feeder.

The 9:1 ununs are often seen for use with end fed half wave antennas. These end fed antennas may have an impedance that is higher than the 450Ω that would give a match to &50&Omega coax.

Accordingly some ununs have a higher turns ratio giving a higher impedance. Accordingly some ununs are seen with turns ratios of 49 or even 64:1. Notice that the impedance ratios are always a square of turns ratio on the former: 4, 9, 16, 25, 36, 49 . . . and so forth.

Whatever the unun used, it is always advisable to use an antenna tuning unit at the transmitter. There is likely to be a relatively high level of SWR on the line, and although this will cause a small signal loss, the main issue will be to protect the transmitter from seeing a high level of SWR.

If the transmitter does see a high level of SWR, then the voltage and current peaks could cause damage to the transmitter power amplifier. If the power amplifier has protection circuitry, then it could result in the transmitter reducing its power output.

With end fed wires now being an ideal option for multiband HF antennas, along with the need for matching vertical quarter wave and similar antennas, the unun is being widely used for these and many other applications.

More Antenna & Propagation Topics:
EM waves     Radio propagation     Ionospheric propagation     Ground wave     Meteor scatter     Tropospheric propagation     Antenna basics     Cubical quad     Dipole     Discone     Ferrite rod     Log periodic antenna     Parabolic reflector antenna     Phased array antennas     Vertical antennas     Yagi     Antenna grounding     TV antennas     Coax cable     Waveguide     VSWR     Antenna baluns     MIMO


text:
# Relation between triangle and its circumscribed circle, on the surface of a sphere. Generalizations to higher dimensions.

Consider the unit sphere in $R^3$ and an equilateral triangle of side length 1, with all vertices on the surface of the sphere. Now project (from the center of the sphere outward) the triangle and its circumscribed circle onto the surface of the sphere to get a spherical triangle and its circumscribed spherical circle (the area covered by which would be dome-shaped).

I am trying to find the relation between the area of the spherical triangle and the area of the circumscribed spherical circle, not only in $R^3$, but in general. That is, in $R^{n+1}$ with $S^n$ and an $n$-simplex of unit side length with all vertices on the surface of $S^n$ projected onto the surface of $S^n$ along with its circumscribed $(n-1)$-sphere.

This is because I think it will be easier to compute the area of the spherical disk (equivalently, area covered by the spherical circle) rather than the area of the spherical triangle, which is my ultimate goal. Ideally, this could be generalized even more to a sphere of radius $r$ and a simplex of side length $r$, but right now I'm just trying to get a foothold of this problem.

Any help in this direction is appreciated!

-


text:
• 13
• 18
• 19
• 27
• 10

# Does typedefs/defines must be inside namespaces?

This topic is 3951 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello I want to do my own namespace but i have no idea if typedefs/defines and etc must be inside namesapce? What is the correct from beneath:
#include <iostream>
namespace myns{
typedef int myint;

class etc{
...
};
};

or
#include <iostream>

typedef int myint;

namespace myns{
class etc{
...
};
};

And one more question if i declare namespace in h/hpp file do i need to declare the same namespace in c/cpp file that is realization of h/hpp? Thanks a lot

##### Share on other sites
A define is just a preprocessing macro and has no bearing on the runtime structure of your program, at least not from the compiler's perspective (because the compiler never gets to see it). You may place it almost anywhere that you could otherwise place a preprocessing directive.

A typedef can go either outside a namespace (which makes it global and causes it to apply everywhere), or inside (which causes it to be scoped to that namespace). Typedefs are safer than defines because the compiler can check the type at compile time, whereas a define is simply a literal substitution ("replace all instances of this word with this one").

hope that helps,


text:
how long is this cable? arc length question

• Nov 12th 2009, 04:45 PM
superdude
how long is this cable? arc length question
question:A telephone cable susbended between two poles 20 meters appart hangs in a curve with equation: $y=10(e^{\frac{x}{20}}+e^{\frac{-x}{20}})$ where -10<=x<=10

how long is the cable?

work:using the formula $L=2\int_0^{10} \sqrt{1+(\frac{dy}{dx})^2}dx$

this gives me an impossible (beyond my level) integral to solve
• Nov 12th 2009, 05:06 PM
chisigma
The problem can be easily solved remembering some properties of the hyperbolic functions. In fact is...

$y= 20 \cdot \cosh \frac{x}{20}$ (1)

... so that is...

$\frac{dy}{dx}= \sinh \frac{x}{20}$ (2)

$(\frac{dy}{dx})^{2} = \sinh^{2} \frac{x}{20} = \cosh^{2} \frac{x}{20} -1$ (3)

Kind regards

$\chi$ $\sigma$
• Nov 12th 2009, 05:38 PM
superdude
could someone elaborate on a differnt approach? I haven't learned about hyperbolic functions(Worried)


text:
# Tag Info

6

In refraction and reflection the incoming electromagnetic wave causes the electron density of the refracting material to oscillate. This happens because at any point in space the wave produces an oscillating electric field (and magnetic field, though that isn't relevant here) so any material that has a non-zero polarisability will respond by developing an ...

4

As $T = t_1 - t_0 \to 0$, we have$$\lim_{t_1 - t_0 \to 0} \langle x_1, t_1\,|\,x_0, t_0\rangle = \lim_{T \to 0}\left({{m\omega}\over{2\pi i\sin\omega T}}\right)^{1/2}\text{exp}\left[{{im\omega}\over{2\sin\omega T}}\left(\left(x_1^2 + x_0^2\right)\cos \omega T - 2x_0x_1\right)\right]$$=\lim_{\epsilon = iT/m \to 0} ... 3 Beginning with \begin{align} -\frac{\partial H}{\partial x} & = -kx = \dot{p}\\ \frac{\partial H}{\partial p} & = \frac{p}{m} = \dot{x} \end{align} One takes the time derivative of both sides of the second equation \frac{d}{dt}(\frac{p}{m}) = \frac{d}{dt}\dot{x} giving \frac{\dot{p}}{m} = \ddot{x} Substituting from Hamilton's first ... 3 A string is a one-dimensional object, and not a zero-dimensional like a point. This means that the object traced out by it following its trajectory is a two-dimensional surface, the worldsheet, while particles - points - trace out one-dimensional objects, the worldlines. Much of the difference between string theory and theories with particles as the ... 2 The propagator does satisfy the Schrodinger equation for most values of x and t... The easiest way to show this is to let \hbar=m=\omega=1. Also, we can work with \sqrt{2\pi}e^{i\pi/4}K\to K instead of K to clean up the mess a little further. Further, let x_f\to x and x_0 \to 0. Then let: K=fe^{ig} with f=\frac{1}{\sqrt{\sin(t)}} and ... 2 In your comment you asked a second (closely related) question about a cart accelerating horizontally. Both these problems can be solved by transforming the frame of reference to a new frame in which the net acceleration is vertically down. The transformation you want to use is a rotation of the axes; the new "apparent gravity" is the vector sum of the two ... 2 OP asks in the title (v1) for help understanding what the Hamiltonian signifies for the action compared with the Euler-Lagrange equations for the Lagrangian. It seems relevant in this context to point out that there is an action principle for both the Lagrangian and Hamiltonian formalism. On one hand, the stationary action principle for the Lagrangian ... 2 I know I'm late to the party, but let me show that Lagrangian and Hamiltonian mechanics are compatible by direct substitution of the Lagrangian into Hamilton's equations. The Hamiltonian is, in terms of the Lagrangian,H(p,q)=p\dot q(p,q)-L(q,\dot q(p,q))$$Now we take the first Hamilton equation and plug in$$\dot q=\frac{\partial H}{\partial p}=\dot ...

2

The energy of a photon doesn't change when moving from one medium to another as pointed out by Andrew in a comment. Considering that $E = h\nu$, $\nu$ being the frequency of the photon and $h$ Planck's constant, we see that the frequency has to stay the same when going from one medium to another. Since the frequency is the same, then the wavelength of the ...

1

The net force acting on the mass M will be $$F=-2kx\sin\phi$$ Here,x is extension of spring,which can be found out by $$d=(x+d)\cos\phi$$ $$2d\sin^2\frac{\phi}2=x\cos\phi$$ $$2d\cdot (\frac {\phi}2)^2=x$$...Considering very small oscillations. Also, $$F=M\frac{d^2((x+d)\sin\phi)}{dt^2}=M\cdot d\cdot\frac{d^2(\tan\phi)}{dt^2}$$ If,we consider the ...

1

Since this is a 1D problem the frequency of small oscillations is simply given by the relation $$\omega^2 = \frac1m U''(x_0),$$ where $U(x)$ is the potential energy of the system and $x_0$ the equilibrium position. This is explicitly given by $$U(x) = mgx + k\left(\sqrt{x^2+d^2}-d\right)^2,$$ and from here one finds $$\omega^2 = \frac{2k}m\left(1-\frac dl + ... 1 The damping introduces a dissipative element to the system, that is, energy is leaving the spring-mass system with time. As such, the energy is not conserved. The maximum energy for the system occurs at its initial configuration; the spring is stretched to some extent A (initial amplitude). The initial energy for the spring is thus purely of a potential ... 1 I randomly had this typed up in personal notes. Was probably an exercise somewhere. Consider a harmonic oscillator, which is described by the Hamiltonian$$H=\frac{p^2}{2m}+\frac{1}{2}m\omega^2q^2$$Doing the Legendre transform, we obtain the action as$$\mathcal{S}=\tfrac{1}{2}m\int_0^t(\dot{q}^2-\omega^2q^2)dt'$$Now we use the Euler-Lagrange equation to ... 1 Because if the coupling is not there it still will behave like$$ m \frac{{\rm d}^2x}{{\rm d}t^2} + m \omega_0^2 x = 0 The coupling just acts as an additional effect of $k (2 x)$ magnitude.

1

So this is a bit tricky actually and perhaps the original question makes this more clear. The problem I'm having when thinking about this is what exactly does the function generator do. Does it take the original force of the string and add some force $F(t)$ on top of it, or does it essentially fix the force on one side of the spring? So if the spring is ...

1

Think of the function generator producing prescribed displacements $X(t)$. What is the extension of the first spring? It is $x$, so its restoring force is $-k_1 x$. Now what is the extension of the second spring? It is $X(t)-x$, with its restoring force $-k_2 (X(t)-x)$. What is missing from the diagram is the direction of positive forces and displacements. ...

Only top voted, non community-wiki answers of a minimum length are eligible


text:
# RPi Minecraft Cannon

## Goal:

Using Minecraft’s API and the Python programming language, spawn a cannon that’s orientation and launch trajectory can be adjusted in real time.

## What You Will Learn:

• Introduction to Github

## What is GitHub?

GitHub is an online repository that offers version control.  It is most often used for computer code and interacted with using a command line tool called git.

## Getting Started:

Open a terminal either using the icon or the keyboard shortcut CTRL+ALT+t.

When opening the terminal like this we are placed in the home directory.  In RPi: Minecraft + Python Introduction we created a directory named code in the home directory.  We will now navigate into that directory using cd (change directory). Enter the following into the terminal.

`cd code`

You may have noticed that the prompt that was previously

`pi@raspberrypi:~ \$`

Has now become

`pi@raspberrypi:~/code \$`

It is informing you of the directory you are currently in, also known as the current working directory.  Remember that ~ (tilde) refers to the home directory.

Now that we are in our code directory, lets use git to download the cannon code from this GitHub repository

`git clone https://github.com/martinohanlon/minecraft-cannon.git`

Now the code has been cloned from the specified github repository into the current working directory.  Lets inspect ours with the ls (lists all files and directories)

`ls`

You should notice that a new directory “minecraft-cannon” has been created.  Lets navigate into the directory using cd and then inspect the contents using ls

`cd minecraft-code`

`ls`

There are several files and directories here, feel free to explore them using cd.

Note that,

`cd ..`

will move your current working directory “up” one or backwards into the directory containing the current directory.

At this point we need to launch Minecraft and get into a game.

Once Minecraft is open, click Start Game then join a preexisting world or Create New.

Back in the terminal we want Python to execute the “minecraft-cannon.py”.  If you left the directory we downloaded with git you can get back there with the following

`cd ~/code/minecraft-cannon`

Then,

`python minecraft-cannon.py`

this instructs the Raspberry Pi to use Python to run the “minecraft-cannon.py” file.

Your prompt in the terminal should have changed to

`Stuffaboutcode.com Cannon >>`

You can now use the following list of special commands to create, aim and fire a cannon in the running Minecraft game.

• start
• rotate [0-360]
• tilt [0-90]
• fire
• exit

Start  spawns a cannon, exit an active cannon.  Using start multiple times in a row will construct multiple cannons however only the most recently made cannon can be controlled with the other commands.  You do not need to include the square brackets when typing the commands.

## Whats Next?

• RPi: Minecraft Clock
• RPi: Minecraft Snake

# RPi Minecraft + Python Introduction

## Goal:

Interact with Minecraft using the Python programming language and Minecraft’s application programming interface(API).

## What You Will Learn:

• Basic Python Programming
• Use of the Minecraft API

## What is an API?

To put it simply an API is a well defined method of interacting with some kind of software.  Think of it like the rules to a game, the rules dictate how the game is played and how you are able to interact with the game state.

## What is Python?

Python is an interpreted programming language that is designed to be easy to learn and easy to use.  Python has many available libraries for the Raspberry Pi and is a very useful tool on the platform. Keep in mind that python uses white space (spaces, tabs, etc) to format and organize it’s instructions, take close care when typing to avoid these sometimes unobvious mistakes.

## Getting Started:

Open a terminal either clicking the icon on the top bar or using the keyboard shortcut CTRL+ALT+t.

We are going to make a folder to store help organize the code we will be writing.  Enter the following into a terminal

`mkdir ~/code`

The mkdir command creates a new directory at the specified location, in this case “~/code”.

The “code” directory is created at the “~/” location ~ or tilde is a shortcut for the home directory.  We can verify the success of the command by entering

`ls`

In the terminal (this command lists all files and directories), or using a file explorer.

Next, open Thonny Python IDE by navigating to the Raspberry Pi icon in the upper left side of the desktop, click on Programming  and look at the bottom of the list for Thonny Python IDE.

Click on File and select New.

Click on File and Save As “minecraft_python.py” in the code folder we created earlier(/home/pi/code).

Now we are ready to start programming in Python.

Into your empty Python file type

```import mcpi.minecraft as minecraft
import mcpi.block as block
from time import sleep```

The “import” keyword load a specific code module.  The “as” keyword allows you to rename a code module to something else.  The “from” keyword allows you to load a submodule as it’s own module.

Currently this python program does nothing exciting however lets learn how to execute the program. You can either use they keyboard shortcut F5 or click on the green play icon.

After program execution the shell at the bottom of the window should have some lines of text appear, however nothing should else should happen.

Now type the following into your program

```mc = minecraft.Minecraft.create()

mc.postToChat("Hello, world!")
sleep(5)```

The first line creates an object that is connected to running an instance of Minecraft.  Setting it equal to mc lets us access the Minecraft game using mc within the code. The second line uses the mc object and a method “postToChat” to send text to the games chat.  The third line delays the program for the specified number of seconds, in this case 5 seconds.

Before running the code this time, we need to open Minecraft and enter a new world.  Click on the Raspberry Pi icon in the upper left, click on Games and then Minecraft Pi.

Once Minecraft is open, click Start Game then join a preexisting world or Create New.

Using the tab key to free your mouse from the Minecraft window, run the code and switch back to the Minecraft window.  “Hello, world!” should appear in the chat.

Going back to the code, type in the following

```playerPos = mc.player.getPos()
mc.player.setPos(playerPos.x, playerPos.y + 50, playerPos.z)
mc.postToChat("Don’t look down!")
sleep(5)```

The position of the players head is stored in the playerPos object.  The players new position is then set relative to the previous position (In Minecraft you stand on the XZ plane with the Y axis being vertical).

Running this code will in addition to the previous action of sending text to the chat but then teleport the player 50 blocks vertically of their current position.

It is ideal to type in code whenever possible as it helps with learning however this next section is rather large and copy-paste will make quick work.

```playerTilePos = mc.player.getTilePos()
blockBelowPlayerType = mc.getBlock(playerTilePos.x, playerTilePos.y - 1, playerTilePos.z)
mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z + 1, blockBelowPlayerType)
mc.setBlock(playerTilePos.x - 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z - 1, blockBelowPlayerType)
mc.postToChat("Trapped you")
sleep(5)

mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, block.AIR)
mc.postToChat("Be free!")
sleep(5)```

Notice that a different method is called to identify the position of the tile the player is standing in.  The setBlock method allows a single block specified with an (X,Y,Z) coordinate and a block

After running the code try to look back and see if you can identify what each line is doing.

```mc.setBlocks(playerTilePos.x - 25, playerTilePos.y - 1, playerTilePos.z - 25, playerTilePos.x + 25, playerTilePos.y - 1, playerTilePos.z + 25, block.DIAMOND_BLOCK)
mc.postToChat("Now that's a big diamond floor!")```

Notice that the setBlocks method unlike the setBlock method can take a range of X, Y, and Z coordinates.

Running the code this time in addition to the previous actions will change the blocks in a 50 x 50 x 1 shape 1 block beneath the players feet.

## Whats Next?

• Modify the code, move the player in different directions.
• Try changing DIAMOND_BLOCK to another block type, a list of the block types can be found in the API documentation, about halfway down the page
• Inspect the API documentation to see how else you can interact with Minecraft using Python

Article and code adapted from source

# RPi Node-Red: Neopixel LED Ring

## Goal:

Use string injection nodes and a specific LED ring node to control a LED ring

## What You Will Learn:

• Basic Node-Red Programming

## Parts List:

12 pixel LED ring

3x male to female jumper wires

## Getting Started:

### Setting up the Hardware

Use jumper cables to attach the LED ring as in the image.
Attach the red wire to +5v, the black to ground, and the white data line to GPIO pin 18.

### Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880  using the web browser.
Drag in the ‘rpi neopixels’ node; and double click on it to start editing its properties.

Set the LEDs field to the number of LED on the ring: 12. Set the Mode to ‘bar – Number of pixels’.  The other fields are all optional, but it might be nice to lower the Brightness, here I lowered it to 15 to lower eye damage. The LED ring can be painfully bright if you are indoors.

Next we drag in the ‘injection’ node, the LED ring node reads strings of text-based commands, and turns them into output on the ring.
We configure our injector like this; setting up Payload to be a string, and contents to be  ‘Blue’. Set the checkbox for Inject once after and set the timer to 1 seconds. Repeat can be set to ‘none’.

Connect the two nodes up like this, check your wiring from the start of the tutorial; and then you’re ready to hit Deploy.
If everything is setup correctly the LED ring should display blue within a few seconds.

The command ‘Purple’ sets the background color to purple on the LED ring.
When the LED ring is initialized all the LEDs are changed to the background color, this can also be set in the node preferences as one of the fields we ignored earlier.
If you read the ‘Node Help’ page for the LED ring node you can see further commands.

For example if we change the payload in the injection node to ‘5,Red’ and Deploy then the first 5 LED will be turned Red; the rest of the LED will remain at the background color we can set in the properties field.

Another possible command is a range of pixels, for example the command ‘3,7,Red’ will set pixels 3-7 Red.
The Color names the LED ring will accept can be found here on Wikipedia : https://en.wikipedia.org/wiki/Web_colors

CONTINUING
the next step is to connect this knowledge with other tutorials, see other tutorials to maybe connect the LED ring to a physical button, or use it in concert with other outputs like speakers.
More advanced logic can be used to turn the LED ring into a clock, or dial.

# 3D Printing: QIDI 3D Printer + Software Setup

## Goal:

Setup your QIDI 3D printer from un-boxing to first print – you can use other 3d printers but will have to find their own instructions

## What You Will Learn:

• How to assemble your printer
• How to level the bed of your printer
• How to slice 3D STL models into files the printer can print

## Printer Bed Leveling

Since the Qidi printer is based on an open source design there are quite a few different printer control software packages you can use. The one we have settled on that seems to work best with the most useful features is the Flashforge Flashprint printer software. When using this software you need to select “flashforge

Steps:

• Choose Creator Pro as your printer:
• Slice your 3D model by clicking on Print and selecting the appropriate settings
• PLA is the recommended material – make sure you have PLA loaded into the printer also
• Save your .x3g file to the 3D printer SD card you should have plugged into your laptop
• Thats it! your file should be ready to print on the QIDI 3D printer!

# RPi Node-Red: Camera

## Goal:

Install the Raspberry Pi camera and take a picture using Node-Red

## Parts List:

• Pi Camera
• Pi Camera Ribbon Cable

## Getting Started:

### Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Into the flow area drag an “inject” node and a “camerapi takephoto” node.

Deploy the flow, then point the camera at something and press the inject button.  The camera will take a picture and then store it in /home/pi/Pictures by default.  Open the file explorer.

Click on the Pictures folder.

## Whats Next?

• Try and trigger the camera node with a Raspberry Pi input node connected to a button or PIR sensor.

# (Archive) RPi Node-Red: PIR(motion) Sensor

## Goal:

Learn how to wire a passive infrared sensor and read it’s state in Node-Red.

## What You Will Learn:

• Basic Circuit Prototyping
• Basic Node-Red Programming

## Parts List:

• One PIR
• Some Jumper Wires
• One 100 Ohm Resistor

## What is a PIR?

A passive infrared sensor or PIR is able to detect movement by measuring the change of infrared radiation.  This PIR comes in a 3 pin package, if you remove the diffusion cap you can see that the pins are labeled “VCC”, “OUT”, and “GND”.  VCC means “voltage at the common collector” and normally refers to a power rail within a circuit, this sensor requires 5 volts. OUT is the pin we will read information from.  GND is the ground connection.

## Getting Started:

### Setting up the Hardware

I encourage gently taking off the diffusion cap on the PIR to view the pins labels.  GND goes to ground, VCC goes to 5V, and OUT is connected to a 100 ohm resistor and then to GPIO20.

### Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag a Raspberry Pi input node and a Debug node into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO20.  Name the node “PIR”.

The debug node can be left with it’s default settings, wire the button node to the debug node and deploy the flow.

If everything has been put together correctly, the state under the PIR node should change from a 0 to a 1 if movement has been detected and then back to 0 after a period of time, inspect the debug tab to view a log of these state transitions.  You may have noticed the two components under the PIR with a plus pattern on them. These are adjustable potentiometers, they control the sensitivity of the PIR and the duration of the activated state.

# RPi Node-Red: Push Button + LED or Buzzer

## Goal:

Combine the use of Raspberry Pi input and output nodes in Node-Red to control an LED or buzzer with a push button.

## What You Will Learn:

• Basic Circuit Prototyping
• Basic Node-Red Programming

## Parts List:

• At Least 1 LED
• At Least 1 Resistor
• Piezoelectric Buzzer
• Some Jumper Wires

Optional

• Needle Nose Pliers

## Getting Started:

### Setting up the Hardware

This wiring diagram is simply the combination of the individual LED, buzzer, and push button circuits.  Make sure that the LED has a resistor on it. Wire a pin on the buzzer to GPIO16, wire the positive leg of the LED to GPIO12, and wire one of the pins on the button to GPIO25.  You can wire all the grounds to a rail and then to the GPIO GND or the connections can be made individually.

If it is difficult to put the components into the breadboard without the legs bending try and use needle nose pliers to help push the pins in.

### Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag one Raspberry Pi input node and two Raspberry Pi output nodes into the flow area.

Double click the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO25.  Set Resistor? to pulldown.  I set the Name to “button”.

Double click one of the Raspberry Pi output nodes to open its configuration menu.  This will be the LED so set the Pin to GPIO12.  Leave Type set to Digital output, Initialise the pin state to low.  Name the node “LED”

Double click the other Raspberry Pi output node to open it’s configuration menu.  Set Pin to GPIO16.  Set Type to PWM output.  Set Frequency to 100.  Name the node “buzzer”.

Wire each output node to the single input node and deploy the flow.

If everything works properly activating the button should turn on the LED and activate the buzzer.  To stop either output node from activating just remove its connection to the button node and redeploy the flow.

## Whats Next?

• What other combinations can you make with the items in your kit?

# (Archive) RPi Node-Red: Push Button

## Goal:

Learn how to wire a push button and read it’s current state in Node-Red

## What You Will Learn:

• Basic Circuit Prototyping
• Basic Node-Red Programming

Optional

## Parts List:

• 1 Push Button
• Some Male-Female Jumper Wires

Optional

• Multi Meter
• Needle Nose Pliers

## What is a Push Button?

A push button is a momentarily activated button.  When the button mechanism is fully depressed an internal electrical connection is made and this newly made connection can be read as the activation of the button.

A breadboard is a prototyping platform that allows the easy creation of circuits without having to solder.  Each row of the breadboard is connected internally (not across the middle break). This mean that putting something into position 1a and 1b connects them electrically together while something plugged into position 1a and 2a are electrically isolated.

The power rails on the left and right hand side of the breadboard are connected in a column and can be an easy way to access ground of power if you choose to route it there.  The color red and by extension the red column is often used for power while blue is often associated with ground and thus used for a ground connection.

## Getting Started:

### Setting up the Hardware

Take care when wiring the button to the GPIO, you want to connect the correct pins.  In it’s 4 pin package only some pins are isolated in the inactivated state.  A pair of pins that come out of the same side of the button are isolated as well as diagonal partners.  A multi meter on the diode setting can also be used to test if there is a connection between pins in an activate/inactivated state. Once you have identified the correct pair of pins attach one to 5V and the other to GPIO25.

Additionally it can be difficult to get the short legs of the push button to correctly make contact with the breadboard, I find that using needle nose pliers to straighten the legs of the push button and then inserting them 2 at a time to be a successful method.

### Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag a Raspberry Pi input node and a Debug node into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO25.  Set Resistor? to pulldown.  You can Name the node anything, I chose “button”.

The debug node can be left with it’s default settings, wire the button node to the debug node and deploy the flow.

If everything has been put together correctly you should see the number under the button node in the Node-Red flow change from a 0 to a 1 when the button is activated and from 1 to 0 when the button is deactivated.  You should also be able to see a record of the button activation in the debug tab of Node-Red.

# (Archive) RPi Node-Red: LED

## Goal:

Turn a light emitting diode(LED) on and off using a button in Node-Red.

## What You Will Learn:

• Basic circuit prototyping
• Basic Node-Red programming

## What You Need to Know:

• Node-Red Basics

Optional

## Parts List:

• At Least 1 LED
• At Least 1 resistor
• At least 2 male-female jumper wires

A breadboard is a prototyping platform that allows the easy creation of circuits without having to solder.  Each row of the breadboard is connected internally (not across the middle break). This mean that putting something into position 1a and 1b connects them electrically together while something plugged into position 1a and 2a are electrically isolated.

The power rails on the left and right hand side of the breadboard are connected in a column and can be an easy way to access ground of power if you choose to route it there.  The color red and by extension the red column is often used for power while blue is often associated with ground and thus used for a ground connection.

## What is a Resistor?

A resistor is an electrical component that has a specific value of resistance measured in ohms.  Resistors are used to restrict the amount of current in a circuit or facilitate a drop in voltage.  Its value of resistance can be read in ohms using the colored bands on the body of the resistor.

## What is an LED?

An LED is a light emitting diode.  Diode’s are a class of electronic components that are designed to only allow current to pass through them in one direction.  This means that LEDs are polar meaning they have an anode (positive) and a cathode (negative). Current must flow into the anode and the cathode must be attached to ground.

There are several methods of identifying the anode and cathode:

• Look at the lengths of the pins, If the LEDs’ pin have not been modified the longer pin is the anode and the shorter pin is the cathode
• Look at the sides of the LED a portion of the case will be flat the pin on that flat side is the cathode
• Look inside of the bulb, each pin is connected to a flat piece of metal internally.  The pin that is attached to the larger piece is the cathode

An LED must have a current limiting resistor between it and ground or between it and power.  An unprotected LED will pull more and more current until it burns itself out. The value of the resistor will have an effect on the LEDs’ luminosity.  The higher the value of resistance the resistor has the less current will get to the LED and thus the dimmer the bulb will shine. The amount of current can be calculated in milliamps with Ohm’s Law, using the value in ohm’s for resistance

$text{current} = frac{text{voltage}}{text{resistance}}$

## Getting Started:

### Setting up the Hardware

If you are following the wiring diagram make sure to attach the cathode (straight leg in the diagram) of the LED to a resistor and then to GND (ground).  Attach the anode (leg with the kink) to GPIO #12.

### Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880  using the web browser. Drag two inject nodes and a Raspberry Pi output node into the flow area

Double click on the Raspberry pi output node to open its configuration menu.  Set the Pin to the same pin you physically connected the LED to. If you are following the wiring diagram this is GPIO12.  Leave the Type as Digital Output.  We can also Name the node, since I used a green LED I named it “Green led”, this follows a good programming practice of accurately and succinctly naming variables.

Double click one of the inject nodes.  Use the drop down menu to change the Payload data type number, type a “1” in the text box.  Name the inject node “on”.

Double click the unmodified inject node.  Use the drop down menu to change the Payload data type to number, except type a “0” in the text box.  Name this node “off”.

1 and 0 correspond for to values of a binary digit(bit) true and false, high and low, on and off respectively.  These are called boolean values and are a fundamental data type in Computer Science.

Connect the inject nodes to the output node and then deploy the flow.

The green square under the Green LED node tells us what state the LED is in, 1 being on and 0 being off.  Injecting a different value will change the state from off to on or from on to off.

# 3D Printing: Design – Tinkercad

In this lesson, students will create a TinkerCAD account, as well as learn the basics of creating a 3D object.

## Overview

3D Printing & Computer Aided Design (CAD) will allow students to discover the potential and limitations of 3D Printing through a build intensive design project. Students will learn how to use CAD software such as AutoDesk, SolidWorks, etc. An excellent opportunity for anyone interested in prototyping, creating artworks, or product customizations.

TinkerCAD is a simple, online 3D design and 3D printing app for everyone. TinkerCAD is used by designers, hobbyists, teachers, and kids to make prototypes, artworks, and Minecraft models!

# RPi Minecraft + Networking

In this activity students will learn about networking on the Raspberry Pi using a popular pre installed game called Minecraft.

I use this opportunity to speak about the human networking that happens when a team of individuals work together. Minecraft is known as a sandbox game where blocks can be created or destroyed.   Many students have played Minecraft in a way that players attack each other known as player vs player, or PVP. Establish that this is not the kind of environment that is being created.  Students will work together to build something cool.

Establishing a level of experience with Minecraft is a good way to start.  I like to group advanced users with each other and beginning users together.  Each group needs to brainstorm, plan and build something in a specified amount of time.  I usually give students between 15 and 30 minutes and encourage them to stretch to collaborate.   Groups can range in size from 2 – 5 players.  One student will “host” the world on their device and will need to identify their I.P address to share with partner players.

Immediately upon opening up Minecraft students given an option to join game or create a new world.  If they create a world, it exists on their pi, if they join a world they need to know who’s world they are joining.  This becomes a process of students calling out and identifying who’s pi is at which IP address.  The IP address can be found by hovering over the Wifi signal in the upper right corner of the screen.

Students who have never used Minecraft will need assistance learning to move within the world, to place a block and to change their inventory.  These students should focus on building something very simple.  Advanced students might build a castle or a huge underground maze.  At the end of the build time, join into the world on your Pi and let one of the students from each group share what they created.

If students wish to save the world they are working on, they will need to navigate to the .minecraft folder from and drill down to the folder of the world they were playing in.  The following video goes over how to do this.

# RPi Scratch Reaction Time

Programing is about giving a computer a set of instructions. Instructions can be given in a text based format or in a visual format. Scratch is a visual programing language that allows a user to easily create interactive stories, games, and animations by dragging specific bits of code to an area and running the program. To get an idea of what Scratch can do, share this overview video.

Scratch can be run in a browser on a regular computer but it is a bit resource intensive to run on a Pi. Two versions come installed on the Raspberry Pi, the classic version labeled Scratch, and an updated version Scratch 2.0.  Scratch 2.0 tends to be a bit less responsive, however it has some very cool features that are explored in a later lesson.

Have students open Scratch (not scratch 2) from the program menu and follow along with the tutorial below.

When students have been able to do some basic functions in a Scratch environment introduce them to this project creating a reaction time game.

# Getting Started

There are a myriad of ways to edit text files and code built into the Raspbian distribution; several even inside the terminal. But here we will cover some of the easier to use graphical programs.

It’s important you know your way around the terminal before continuing, please see the terminal tutorial -> here

# Editing config files with leafpad

Leafpad is a lightweight notepad-like text editor that is bundled with Raspbian; we will use it here to edit simple config files in the file system.
For example the led ring tutorial directs us to edit the /boot/config.txt and comment out some lines.
To do this navigate to the /boot/ directory in the terminal; and then run ‘sudo leafpad config.txt’, this is similar to other commands you have seen taking a path as an argument, the important difference is the ‘sudo’ prefix which tells the terminal to run this command as a ‘super user’. This allows us to overwrite important system files and access gpio pins ect. You’ll have to use it often but you should still be careful.

We get an editor window like notepad on windows, we can insert a ‘#’ before dptparam to comment it out, and then save with control s
after exiting the editor you will regain control of your terminal.

# Editing and running python scripts with Thonny

Next we can use a slightly complicated editor, Thonny is specifically for python ‘.py’ files and has some features that make debugging scripts easier.
Thonny can be found in the menu in the top left corner, or again opened from the terminal with ‘sudo thonny’.
Most scripts accessing the GPIO require sudo powers to work correctly, so its best to get used to running it as sudo.
You open a file to edit by navigating to it in the thonny gui; like notepad on windows.

We can enter python scripts line by line into the main window, and at any moment run our script with F5 or the gui button (green arrow).
Here is what it looks like to run a simple program inside thonny.
note the output in the lower window, this is the result of pressing F5 or the run button

# RPi Sense HAT+Minecraft

The Sense HAT was developed by the folks at Raspberry Pi as an add on board that contains a number of sensors and a LED display. In this lesson we can demonstrate how to use the Sense HAT in conjunction with Minecraft to visualize real world data and control the LED Screen.

I use this lesson primarily to get students excited about the connection between a sensor and the way that we can visualize data through Minecraft.  This worksheet from the folks at the Raspberry Pi foundation is an excellent resource. In the latter portions of the lesson it goes into methods of collecting data from the Sense HAT and displaying it within the Minecraft world.

https://www.raspberrypi.org/learning/exploring-space-with-minecraft/

Follow along with the Sense HAT installation and the first several worksheets of this project.

# 4. Github Intro

Github is known as a repository for cool programs that can be used in all sorts of ways on your Pi. In this lesson we will learn how to install programs from Github using the terminal.

First lets install a program that can do screen captures. Something that is handy when students have created something amazing in their Minecraft world.

Lets follow the instructions for taking screenshots provided by Martin O’Hanlon.

Here is a video going through the process.

Students will be really excited when they learn to download programs that can run within their Minecraft world. Lets go back to Martin’s API tutorial and have students select one of the first three items, clock, cannon, or snake video game.

In each of these examples, there is a section of code that should be copied into the terminal. When enter is pressed on the keyboard, a bunch of code will appear and a new program file will be placed in the home directory on the Pi

Have students navigate to the file folder and open the file with the .py extension by right clicking on the file and selecting open with python 2 from the drop down menu.  If the program is run while Minecraft is open it will place an exciting new feature in the Minecraft world. This will hopefully trigger a desire to try downloading other python programs to modify their Minecraft worlds.

# Navigating with the terminal

Like on windows or any other computer, files in Linux are arranged in a hierarchical directory structure; meaning starting at root there is a sort of tree of folders containing files and other folders.
The terminal has a concept of ‘working directory’ ; using the metaphor of navigating an office building this is simply what room the terminal is in. If you use a command to list files it will look around the current directory and return you a list of files currently visible.

After opening a terminal with the icon in the upper left you will be confronted with something like this (but most likely with a different color-scheme and font)

upon opening terminal

We can now use the ‘pwd’ print working directory command to see what directory or room we are in; the result is returned to us in simple text:

Now we know what directory we are in, but we still don’t have any idea what accompanies us; for that we can use ‘ls’ list command; which returns us a list of files and directories in our working directory.

I have added a file here to demonstrate that files are coloured differently to directories.
Now we can try entering one of the directories listed, for this we can use the cd change directory command. This command takes a ‘path’ as an argument. Paths are just strings of text describing the location of a directory or file; pwd returns the ‘path’ of our current working directory. Another path could be ‘/home/pi/Documents/’. Paths can also be relative to our current location, so if our current working directory is ‘/home/pi’ then ‘Documents’ would be a valid path.

Most of the time you will use relative paths, they are shorter and easier to work with too.
To navigate to a directory relative to our own we first use ls to see what our options are.

Then we use the cd command with a path to enter one, we’ll use the python_games directory because we know ahead of time its not empty: cd python_games

Another valid and equivalent command would again be cd /home/pi/python_games

Once we enter the directory we can use the ls command to orient ourselves.

We can see dozens of files and no directories, here we can practice running and terminating a python script.

# Running and Exiting python scripts

Just like the cd command there is a python command pre-installed that takes a python script as an argument, python scripts are files with a .py extension.
To run a game choose any file with a .py extension and use it as an argument to run python.

To exit the program at any time use the Control-C keybind, this sends a kill signal to the python process we just started; this will also be used regularly when you want to exit python scripts you are testing.

Next we will navigate back home using terminal commands and create our own directories and files.
Apart from relative and absolute paths that we already covered there are some more special cases, for example the ‘..’ path refers to the directory one level above our current working one. This makes it easy to navigate upwards out of whatever area we entered.
To navigate back to the home directory use ‘cd ..’, and then use ‘pwd’ to check if you made it back.

Finally we will create our own directory and some files to populate it. Just like the cd command there exists a mkdir command which again takes a path. This command simply spawns a folder with our chosen path, for example..

At first we have no indication that our command did anything, but a simple ls will reveal all.

We don’t want to spam files all over our home directory, so before we start making them lets enter our directory with cd.
The command for creating files in the terminal is called touch, it takes a path and creates an empty file whereever we tell it too, or if the file already exists it just ‘touches’ it; updating its last modified date ect.

Now that we are safely in our own directory we can try it out:

There does exist a rm command to remove files, but it can be dangerous if you accidentally delete some script or important document you were just working on!
as you can guess it takes a path as its argument; here we can see it at work.

Last of all we can clean up after our empty directory, navigate back to the home using cd, and then use the sister to rm, rmdir to remove our directory.

# Conclusions

In this tutorial we reminded ourselves what directories and files are, how to find our current working directory in the terminal, how to list files and folders, how to enter and leave directories, how to run and exit python scripts, and how to create and delete files / folders.


text:
# Scientific Notation and Metric Conversion Worksheet

In metric conversions worksheet, students solve 6 problems with multiple parts to each including converting from ordinary notation to scientific notation, from scientific notation to ordinary notation and converting metric units.

Concepts

Resource Details


text:
#jsDisabledContent { display:none; } My Account | Register | Help

Article Id: WHEBN0000424582
Reproduction Date:

 Title: Minor triad Author: World Heritage Encyclopedia Language: English Subject: Collection: Publisher: World Heritage Encyclopedia Publication Date:

Component intervals from root
perfect fifth
minor third
root
Tuning
10:12:15[1]

In When a chord has these three notes alone, it is called a minor triad. Some minor triads with additional notes, such as the minor seventh chord, may also be called minor chords.

A minor triad can also be described as a minor third interval with a major third interval on top or as a root note, a note 3 semitones higher than the root, and a note 7 semitones higher than the root. Hence it can be represented by the integer notation {0, 3, 7}.

A )) differs from a minor chord in having a major third above the root instead of a minor third. It can also be described as a major third with a minor third on top, in contrast to a minor chord, which has a minor third with a major third on top. They both contain fifths, because a major third (4 semitones) plus a minor third (3 semitones) equals a fifth (7 semitones).

A )

An example of a minor chord is the C minor chord, which consists of the notes C (root), E (minor third) and G (perfect fifth):

).

The minor chord, along with the major chord, is one of the basic building blocks of tonal music and the common practice period. In Western music, a minor chord, in comparison, "sounds darker than a major chord"[3] but is still considered highly consonant, stable, or as not requiring resolution.

## Acoustic consonance of the minor chord

A unique particularity of the minor chord is that this is the only chord of three notes in which the three notes have one harmonic - hearable and with a not too high row - in common (more or less exactly, depending on the tuning system used) : This harmonic, common to the three notes, is situated 2 octaves above the high note of the chord : This is the harmonic of row 6 of the fundamental of the chord, the one of row 5 of middle note, the one of row 4 of the high note:

In the example do, mi$\flat$, sol : a sol, 2 octaves above.

Demonstration :

• Minor third = 6/5 = 12/10
• Major third = 5/4 = 15/12
• So the ratios of Minor chord : 10:12:15
• And the explication of the unique harmonic in common, between the three notes, is verified by : 10*6 = 12*5 = 15*4

## Just intonation

In ). More tunings of the minor chord are also available in various equal temperaments other than 12-TET.

Rather than directly from the harmonic series, Sorge derived the minor chord from joining two major triads; for example the A minor triad being the confluence of the F and C major triads.[13] A-C-E= f-A-C-E-g. Given justly tuned major triads this produces a justly tuned minor triad: 10:12:15 on 8/5.

## Minor chord table

Chord Root Minor Third Perfect Fifth
Cm C E G
Cm C E G
Dm D F (E) A
Dm D F A
Dm D F A
Em E G B
Em E G B
Em E G B
Fm F A C
Fm F A C
Gm G B (A) D
Gm G B D
Gm G B D
Am A C (B) E
Am A C E
Am A C E (F)
Bm B D F
Bm B D F


text:
# What is the physical nature of electromagnetic waves?

I've been trying to work out what the physical nature of electromagnetic waves is, since I reasoned that given electromagnetic waves have wavelengths that are given in distance units, rather than units of energy or some other more abstract/non-physical unit, then electromagnetic waves must have a physical description.

I queried my roommate (who is studying computer hardware engineering in university) and though he could provide some appropriate equations relating properties of electromagnetic waves, it seemed as though their physical description was left as a blackbox by his professors.

For elucidation on what I'm asking:

a) What do a peak or a trough represent in physical space?

b) Does an electromagnetic wave traversing physical space over time fill an area, or rather in the case of non-polarized light a volume? If not, why do we use units of distance to measure amplitude and wavelength?

c) If it takes up a volume, does this volume shrink during a trough and expand during a peak?

d) If it takes up a volume, is the energy of the photon(s) becoming maximally diffuse and then minimally diffuse cyclically?

Just trying to fathom it for myself, my end result is a drawing of a single wave with a grid drawn overtop where I assume that each box is a planck area and we assign a 1 for boxes which are inside the area of the wave and a 0 for boxes outside. Using this technique I concluded for each moment in time I could assign a percentage value for the density (or alternatively the diffusivity; I do not know the word you would use to refer to the degree to which a system is diffuse, on a side note, if you do, please let me know!) of the photon(s) energy (perhaps in the form of physical oscillation over the distance) based on the ratio of 1s to 0s in that column. In this drawing I'm assuming polarized light and only looking at one of either the electric force or magnetic force, though I assume I could simple double my density percentage for each column to include both. This interpretation seems ill-conceived though; how does the probability wave of the photon(s) look in comparison to the wave I've drawn?

Very confused and seeking answers which might help shine some light on the matter. I ultimately fear that the issue with my attempts to discern a physical picture of an electromagnetic wave lie in the fact that the answer is truly unintuitive and unsatisfying. By the way, I'm a layman with an interest in physics, not a student of it, so please try to be as idiot-friendly as possible with your answers.

Thanks!

Fields

First you need to understand what a field is. There is a very good answer by dmckee on what a field really is which you can (and should read), but I'll try my own version. Mathematically, a field is something that has a value at every point of space and time. A typical example is temperature. The air in your room has a different temperature at every point and this temperature may change with time, so to each point in space and time we associate a number $T$. We might write $T(x, y, z, t)$, indicating that the temperature is a function of $x, y, z$ (space) and $t$ (time).

Temperature is a scalar field because at each point it is a scalar (i.e., a number). But we can have different kinds of fields. For example, the air in your room might be moving around, and so at each point it will have some velocity $\mathbf{v}(x,y,z,t)$. This velocity is a vector field, because at each point it has a magnitude and a direction (if you don't know what a vector is, picture it as a small arrow; the direction tells you which way the air is moving at that particular point, and the length of the arrow tells you how fast it is moving).

Waves

Air can carry waves, which we call sound. Sound is nothing more than a bunch of air molecules oscillating together in such a way that they carry energy from one place to another, in the same way that we see waves in water. With our fancy fields we can describe a wave by saying that at any given point the velocity is oscillating back and forth, and the phase of this oscillation changes as we move from place to place.

Temperature and velocity are fields that, in a sense, don't physically exist by themselves: they describe some property of a fluid, but it is the fluid that has physical reality, not its properties. But there are fields that are not a property of anything else, and the electromagnetic field is the most important among them.

Electromagnetic field

The electromagnetic field is described by two vector fields $\mathbf{E}$ and $\mathbf{B}$, called the electric and magnetic field respectively. For the purposes of light we can forget about $\mathbf{B}$ and just talk about the electric field. Just like the velocity of a fluid, this field can be represented by an arrow at every point in spacetime. Its physical intepretation is that if you place a charge somewhere, there is a force felt by the charge that points in the direction of $\mathbf{E}$ and is proportional to its magnitude. (Also there are magnetic effects but we're ignoring those). This is simply a more sophisticated view of the idea that like charges repel and opposite charges attract; instead of thinking of a force between the charges, we say that one charge creates an electric field near it, which is in turn felt by the other charge.

An electromagnetic wave is simply an oscillation of the electric and magnetic fields. At each point, the field's magnitude is increasing and decreasing with time. Wikpiedia has some nice gifs showing this process in time and space. The wavelength is a physical distance: it's the distance between two maxima or two minima of the field. The amplitude is not a distance, however: it measures how strong the field is, and so it is measured in units of field (Newton per Coulomb or Volt per meter for the electric field in SI units).

You can see in the usual pictures that an EM wave is a transverse wave; that is, the direction of the fields is perpendicular to the direction of propagation of the light. This is in contrast to a sound wave, which is longitudinal: that is, the molecules oscillate back and forth, and the move in the same line that the wave travels.

b,c,d) A wave doesn't really take up space. There might be fields over a region of space, but the arrows you see in the animations don't have a physical length. They represent the magnitude of the fields, but they don't occupy physical space. Remember that there are two arrows (because of $\mathbf{E}$ and $\mathbf{B}$) at every point in space. As I've said before and has been said in the comments, wavelengths are lengths because they are the distance between two maxima, but amplitudes are not lengths.
• @machinemessiah: 1. Yes, the magnitude is the strength of the field. A particle with charge $q$ placed in a field of magnitude $E$ will feel a force of magnitude $F=qE$. 2. At each point the magnitude goes from negative to positive and back. Remember that if at a point at some given instant the field is zero, there is a point a quarter of a wavelength over (again, see the animations) that has maximum field. The energy is traveling in the direction of the wave. (...) – Javier Dec 7 '15 at 4:05


text:
## Essential University Physics: Volume 1 (4th Edition) Clone

10.4 $m/s$
The average speed is defined as the change in position over the change in time: $\bar{v} = \frac{\Delta x}{\Delta t} = \frac{100m}{9.58s} =$ 10.4 $m/s$


text:
SEARCH HOME
 Math Central Quandaries & Queries
 Question from ryan, a student: 3         4 --   -    --      =     1      (1) x         y 7       2             11 --   -  --        =   --       (2) x       y              12

Ryan,

When you have simultaneous equations in two variables, the general strategy is to is to get rid of one of the variables, leaving you with one equation in one variable. The easiest way to proceed might be to multiply your second equation by -2, then add the two equations.

If you do not like working with fractions, then it is easy to get rid of them here: just set u = 1/x and v = 1/y. Next, solve for u and v the usual way you were taught to solve simultaneous equations. After you have found u and v, then x will be 1/u and y will be 1/v.

Chris

Hi Ryan.

To get this solution started, why not multiply the second equation by 2, then subtract it from the first equation? That way you can eliminate the y terms and find x.

Write back if you need more help.
Stephen La Rocque

Math Central is supported by the University of Regina and The Pacific Institute for the Mathematical Sciences.