GithubHelp home page GithubHelp logo

nature-of-code / noc-book-2 Goto Github PK

View Code? Open in Web Editor NEW
563.0 15.0 43.0 290.03 MB

Nature of Code with p5.js and Notion workflow / build system.

Home Page: https://natureofcode.com

JavaScript 24.30% HTML 74.16% SCSS 0.83% CSS 0.70%
creative-coding nature-of-code p5js physics simulation

noc-book-2's Introduction

The Nature of Code 2nd Edition

This repo contains all the files for the Nature of Code 2nd edition. The book is now being authored in Notion and imported here as raw HTML files (which are then used to build the print PDF and gatsby website).

Data flow chart showing three parts: edit, store, and output.

Edit & Import

Notion Database Screenshot

Content are stored in a Notion Database with the following attributes:

  • Type (Page | Chapter): to be handled differently during builds, now only act in the website build.
  • Title: defines the title
  • Status (Draft | Published): only Published ones will be imported
  • File Name: defines the page sequence in a pdf build
  • Slug: defines the path in web page URL

Each entity also contains a page of its content, which will be transformed to html files based on the schema. The transformation script (nature-of-code/fetch-notion) is written in Node.js, utilized as a GitHub action.

Build

Following are the steps to build the book and website, however, you will have to skip the import-notion-docs as that can only be done with the Notion API key associated with the book. You can find the latest HTML version of the book in /content.

# Install Dependencies
npm install

# Build PDF (Magicbook) in `build` directory
npm run build:pdf

# Build Website in `public` directory
npm run build

Attributions

Icons used in this project:

πŸ–οΈ (Crayon) & 🦜 (Parrot) & πŸ”Ž (Magnifying glass) from OpenMoji – CC BY-SA 4.0

noc-book-2's People

Contributors

43-stuti avatar fturmel avatar jasongao97 avatar moodvector avatar shiffman avatar tuantinghuang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

noc-book-2's Issues

Fix step() method for Walker class in Introduction

In line 224 of the Introduction, void should be removed from the front of the method declaration.

Additionally, the if/else block starting on line 239 is missing this. for each of the changes to x and y.

The full method should read

    step() {
      let choice = floor(random(4));

      if (choice == 0) {
        this.x++;
      } else if (choice == 1) {
        this.x--;
      } else if (choice == 2) {
        this.y++;
      } else {
        this.y--;
      }
    }

Finally, as a reader, I personally find it confusing to have the explanation on lines 228-235 inserted in the middle of the two halves of this method declaration.

Accessibility

This will certainly need to become multiple, smaller issues, but filing one now just to remember the following:

  • Follow WCAG guidelines for website (book and homepage/download PDF system).
  • Make sure the digital PDF render is accessible.

Use let+const or just let?

In revising for p5.js, I have the option of using var, let, or const. var is out as I'd like the book to use ES6+, however, the question remains as to whether for readability and alignment with p5.js to skip const. I'll leave this open for now as it can be a global change later on. If I use const I'll want to include a brief explanation, probably in the intro.

Example that could use const:

  function step() {
    //{!2} Yields -1, 0, or 1
    let xstep = floor(random(3)) - 1;
    let ystep = floor(random(3)) - 1;
    x += xstep;
    y += ystep;
  }

random walker bias

The random walker example is biased towards the top left (or at least the original Processing example was.) This gets asked a lot so I should check the new p5 examples and address this as necessary. See: nature-of-code/noc-book#134

sin/cosine lookup table example

The old Processing wiki with more info no longer exists, I should build out the example and include it as part of the book itself.

p5.Vector.fromAngle()

I am switching some examples in chapter 6 to use p5.Vector.fromAngle(). I should check and see if this is mentioned in chapter 3 and if not, add in a mention!

flip book animation

I would really love to add a flipbook animation to the margins of the print book!

Project Structure

Hi Dan! I'm thinking about two ways of arranging the project. We can either separate the three parts(node script for fetching data from notion to create local HTML files / magicbook pdf build / gatsby website build) into three node.js packages/modules or create one big project with all the scripts and logic. Which one do you prefer?

Plan A: Separated three parts

β”œβ”€β”€ content/
β”‚Β Β  β”œβ”€β”€ html/
β”‚Β Β  β”œβ”€β”€ images/
β”‚Β Β  β”œβ”€β”€ package.json
β”‚Β Β  └── scripts/
β”œβ”€β”€ pdf/
β”‚Β Β  β”œβ”€β”€ magicbook.json
β”‚Β Β  └── package.json
└── website/
    β”œβ”€β”€ gatsby-browser.js
    β”œβ”€β”€ gatsby-config.js
    β”œβ”€β”€ gatsby-node.js
    β”œβ”€β”€ package.json
    └── src/

Plan B: Combined

β”œβ”€β”€ content/
β”œβ”€β”€ magicbook/
β”‚Β Β  β”œβ”€β”€ layouts
β”‚Β Β  └── stylessheets/
β”œβ”€β”€ scripts/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ pages/
β”‚   └── styles/
β”œβ”€β”€ gatsby-browser.js
β”œβ”€β”€ gatsby-config.js
β”œβ”€β”€ gatsby-node.js
β”œβ”€β”€ magicbook.json
└── package.json

quote consistencies

Just a note here that the book will require a pass over to check for consistencies of curly vs. plain quotes. The rules should be as follows:

  1. When quoting within narrative text or using a contraction, single / double curly quotes should be used, i.e:

I canβ€˜t imagine them saying ”I didnβ€˜t read the book!”

  1. When quotes are used in code examples, even code comments, they should be plain quotes.
// This line of code is "crazy"
let s = "Crazy, I say! Crazy!";

Unable to run the github action

I have imported all the contents in the noc-book-2 repository and successfully turn it back to HTML on my local side.

Screen Shot 2022-05-09 at 10 05 50 PM

However, I failed to run the script with GitHub action. Is it something with my permission/settings?

Screen Shot 2022-05-09 at 10 10 56 PM

Table of Contents Generation

I had some time on a flight today to start playing around with the table of contents. At some point I might make individual issues to track smaller items, but here's a list of some general stuff.

@runemadsen @alterebro

  1. How to I control what appears and does not appear in the TOC? Do I need to write custom code in includes/toc.html to parse the toc object? Or use CSS to hide elements? For example, I don't want want third level headers to appear. (Or do I?).

screen shot 2016-07-17 at 7 11 25 pm

1. I'm not seeing `
` or `
` showing up. I've searched for a bit but I can't find anywhere that determines which sections are selected for inclusion.

(FYI I'm using dev-shiffman.json as my test TOC generator.)

@alterebro if you want to start playing around with the CSS to do cleanup and match styles, go right ahead.

relationship between mass and radius

Noting that in my examples I just use a multiplier to tie radius to mass.

    this.radius = mass * 8;

Another, perhaps more accurate, way to approach this would be to consider surface area as corresponding to mass which would involve taking the square root (area = Ο€rΒ²).

    this.radius = sqrt(mass) * 8;

This would need to be addressed in the text and examples.

Debounce drag force (section 2.8)

There is a small issue in section 2.8 Air and Fluid Resistance: the computed instantaneous drag force can be so large that it causes objects to bounce. This can be disconcerting to readers who try out the code and experiment with different settings and wonder what they did wrong! So it would be helpful to describe the issue: the simulation goes in steps and the large computed drag force is instantaneous and doesn't last the entire step. There is an easy solution: the drag force will cause an object to stop, but never to change direction, so just add a line to limit the drag force to mover.velocity.mag() * mover.mass if the applyForce function divides by the mover's mass, or to mover.velocity.mag() * mover.mass if it doesn't.

Math Formula

Latex / Katex math formula rendering is broken in HTML and PDF builds.

(Not sure if this is true just an example issue).

surface area dated reference

An aerodynamic Lamborghini, for example, will experience less air resistance than a boxy Volvo. Nevertheless, for a basic simulation, I will consider the object to be spherical and ignore this element.

Dated reference or charming? Maybe something less sports-car-y would be nice here.

magicbook stylesheet error with node 17.3.0

When I run magicbook build I get the following error:

Required file: stylesheets cannot be found
Cannot register permalinks . stylesheets:insert not found
Cannot register katex:setup . stylesheets:move not found
Error: Cannot find module '/Users/shiffman/Repos/noc/noc-notion/node_modules/stylesheets'

It appears to be looking for the stylesheets in node_modules rather than in the root directory of the repo (where they are!)?

@jasongao97 @43-stuti do you also get this error or is this something perhaps related to my own local set-up?

GitHub Action for import to HTML

As discussed in our meeting, a next step is to redo the GitHub action to automate an import/pull request now that we are brining the book from notion to this repo as HTML files!

noc-book-2 repo

It looks like the build is pulling some images from the NOC Book 2 repo. When we first started this repo it was a speculative exploration of working with Notion. Now that are moving forward in that direction I think it maybe makes sense to bring everything here and archive the noc-book-2 repo. Or do we need two separate repos still?

The options are:

  1. Archive noc-book-2 and bring everything into noc-notion
  2. Archive noc-notion and integrate all of these build scripts into noc-book-2
  3. Keep both repos?

I think my preference is to go with (1) but I'll want to go through all of the issues there and resolve them or bring them over. What do you think @jasongao97?

build index (PDF only?)

Just filing an issue to track implementing an index which I believe is the only remaining item for the PDF build?

A whole bunch of issues with the intro chapter

I already posted this in the Discord but I feel like this is a better place to put this so I'm reposting it here


So in the section with the random walk, you say any given pixel has 8 neighbors. This is sort of correct, but it really depends on what you define as a neighbor. You could define a neighbor as an orthogonally adjacent square and that would be just as correct


This particular code snippet is wrong:

// 1 and 3 are stored in the array twice, making them more likely to be picked than 2.
let stuff = {1, 1, 2, 3, 3};
// Picking a random element from an array
let value = random(stuff);
print(value);

You have to use square brackets, also I would use console.log but if you want you can use print it doesn't really matter


In I.4 you just refer to a simulation of monkeys that doesn't even exist. Like...you never even introduced it


Then there's this paragraph:
Screenshot 2022-08-01 at 15 26 36
The y=x graph is actually wrong. The probability of any given value being picked is actually zero. What this graph actually is is what's called a "probability density function" (PDF). It doesn't show what the probability is of any one value being picked, it just shows the proportions of those probabilities. That's still not an entirely accurate description but you get what I mean


The beginning of chapter 1 still has the old division scheme for the book: the first 5 chapters are about physics, the next 3 about complexity, and the final 2 about intelligence. I'm not saying this is wrong, but especially with swapping chapters 5 and 6, I feel like you're moving to a different system: the first 6 chapters about physics, and the final 4 about...other things


Chris Sears posted a thing:

Puts on math teacher hat
From the introduction: "Technically speaking, the random number picked can never be 4.0, but rather the highest possibility is 3.999999999 (with as many 9s as there are decimal places)..." Since 3.9999..... = 4.0, you may want to sidestep this part. One possible edit could be: "Technically speaking, the random number picked can never be exactly 4, but numbers like 3.9, 3.99, or 3.999999999 are possible."
Is there a GitHub repository for the book? Sorry I missed the live stream where you talked about the book. I feel like a student who missed class.
Takes off teacher hat and puts on dunce cap

This is the famous 0.99999... = 1 theorem. In case you haven't seen it before, here is an algebraic proof:

Let's call 0.99999... X
X = 0.99999...

Multiply by 10
10X = 9.99999...

Subtract
9X = 9

Divide by 9
X = 1

And here's an intuitive proof:

True thing about the real numbers: take two numbers. Unless they're the same, there must be a number greater than one and less than the other (e.g. take the average)

Can you name a number which is in between 0.99999... and 1? You can't, it's impossible. From the above, it thus logically follows that 0.99999... and 1 are the same

Finally, not a mistake but an idea (not saying you should do this but I just feel like it makes sense): what if you call the intro chapter chapter 0? Everything in code starts at 0 anyway, so I feel like this would be a good idea

"average" the vector in group steering behaviors examples is a pointless step?

In some Nature of Code examples regarding group steering behaviors (Chapter 6) I noticed that, for averaging the velocity of all the vehicles/boids at play, you do some vector math in sequence:

  sum.div(count);
  sum.normalize();
  sum.mult(maxspeed);

but, since all the functions act on the vector as a scalar, the last function of the three will ultimately set the magnitude of the vector to a determined value, the result of the previous two will be useless.

Maybe we could map the magnitude of sum.div(count) to something btw a minimum value and "maxspeed", or just limit it to "maxspeed"?

forEach and for in

Chapter 4 covers for of loops and also mentions higher order functions like filter(). I may want to mention the existence of forEach() and for in as well which often cause confusion.

Exercise Solutions

The first edition of the book came with some exercise solutions (not all). Picking up on the conversation from #54, I'm filing an issue (for later) to develop a way to either include exercise solutions in the book text itself or separate repo.

toxiclibs in 3d

the book says the 3d examples are online so i either need to make them or take this out.

Translation FAQ

I get a lot of inquiries regarding translation, should write up a quick FAQ to point people towards.

Particle System "origin" and addParticle()

#75 is now merged but one thing I want to go back and look at is how the origin is stored and intialized with a particle system. Overall I find this passing in x,y and then creating a vector more clear than passing in a vector and calling copy(). In addition, some of the example there isn't a good reason to store an origin and it would make more sense to call addParticle(x,y).

Gas scenario in Chapter 5

Maybe a more environmentally friendly scenario would be nice? Or weave something in about sustainability and public transportation, etc.

Feedback: Complex systems often include a
feedback loop where the output of the system is fed back into the
system to influence its behavior in a positive or negative direction.
Let’s say you drive to work each day because the price of gas is low.
In fact, everyone drives to work. The price of gas goes up as demand
begins to exceed supply. You, and everyone else, decide to take the
train to work because driving is too expensive. And the price of gas
declines as the demand declines. The price of gas is both the input of
the system (determining whether you choose to drive or ride the train)
and the output (the demand that results from your choice). I should
note that economic models (like supply/demand, the stock market) are
one example of a human complex system. Others include fads and trends,
elections, crowds, and traffic flow.

attractor art examples

There are many artists that have worked with attractors over the years to create patterns. What are some examples I can include that represent a diversity of work and artists?

      <p>
        In the example above, there is a system (i.e. array) of
        <code>Mover</code> objects and one <code>Attractor</code> object. Build
        an example that has systems of both movers and attractors. What if you
        make the attractors invisible? Can you create a pattern/design from the
        trails of objects moving around attractors? See the <a
          href="http://processing.org/exhibition/works/metropop/">Metropop
          Denim project by Clayton Cubitt and Tom
          Carden</a> for an example.
      </p>

Missing Elements after HTML -> Notion Import

  1. Missing Images
  2. Code comes in as "plain text" would be nice to mark as JS
    Screen Shot 2022-02-21 at 3 56 00 PM
  3. The index terms don't come through I don't think (but this probably has to be redone anyway)
    <a data-primary="oscillation" data-secondary="on two axes" data-type="indexterm"></a>
  1. Custom formatting for exercises vs. examples?
    <div data-type="exercise" id="chapter03_exercise1">
    <div data-type="example">
  1. How do we incorporate interactive examples vs. static screenshots for examples.
    <figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/rJkWNeWOx">
      <img alt="ch03 ex07" src="chapter03/ch03_ex07.png" />
      <figcaption>&nbsp;</figcaption>
    </figure>

Chapter 5 -- Physics Libraries

@jasongao97 I think I probably once said to skip bringing chapter 5 to notion b/c I need to rewrite it, but maybe it's best to import as a starting point.

As of now, my plan is to replace box2d with matter.js, and keep toxiclibs (using toxiclibs.js?) But I may consider removing toxiclibs if it's not actively maintained.

Thoughts or comments appreciated!

(Also I plan to swap the order between 5 and 6.)

ellipse() with 3 arguments or circle()?

Almost all of the objects in the book are drawn with ellipse(). As I am going through I am removing the 4th argument since p5 supports 3 arguments (x, y, diameter) for ellipse(). I could also consider using the new-ish circle() method.

This issue is both a question as well as a reminder to do a global pass over the book for consistency with whatever decision is reached.

Embeded examples

I'm thinking about utilizing p5-web-editor's API (e.g. https://editor.p5js.org/editor/codingtrain/projects/JmEToUfk) to fetch and download example codes during website build time (or import time, depending on whether we want it to be tracked by git). So they can be served at the same place as the website with customizations. it could be in subfolders like content/examples/Nature_of_Code_1:_Vectors_1.

In this way, only a p5 editor link bookmark need to be added to the Notion callout block.

Screen Shot 2022-08-04 at 12 01 48 PM

Content source

Can we have two sources file for the PDF and the website build?
So they can be optimized for each build and don't need to worry about compatibility
It's also easier to have markdown frontmatter storing other database attributes for route generating, etc.

<!-- chapter_2_forces.html -->

<h1>Chapter 2. Forces</h1>

<blockquote data-type="epigraph">
  <p>β€œDon’t underestimate the Force.”</p>
  <p>β€” Darth Vader</p>
</blockquote>

<div data-type="example">
  <h5>Example 1.1: Bouncing ball with no vectors</h5>
  <figure>
    <img src="https://cdn.jsdelivr.net/gh/nature-of-code/noc-book-2/context/noc_html/imgs/chapter01/ch01_ex01.png" alt="If you are reading this book as a PDF or in print, then you will only see screenshots of the canvas. Motion, of course, is a key element of the discussion, so to the extent possible, the static screenshots will include trails to give a sense of the behavior. For more about how to draw trails, see the code examples linked from the website.">
    <figcaption>If you are reading this book as a PDF or in print, then you will only see screenshots of the canvas. Motion, of course, is a key element of the discussion, so to the extent possible, the static screenshots will include trails to give a sense of the behavior. For more about how to draw trails, see the code examples linked from the website.</figcaption>
  </figure>
</div>
<!-- chapter_2_forces.md -->

---
title: Chapter 2. Forces
slug: "02_forces"
---

> β€œDon’t underestimate the Force.”
> β€” Darth Vader

<example example-path="chp01_vectors/NOC_1_01_bouncingball_novectors/" p5-editor-url="https://editor.p5js.org/codingtrain/sketches/_HHLfcGx" />

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.