- Jan 2021
-
www.py4e.com www.py4e.com
-
Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.
def count(string, letter): char_count = 0 for char in string: if char == letter: char_count = char_count + 1 print(char_count) if __name__ == "__main__": count("Bananaaaa", "a")
-
Exercise 2: Given that fruit is a string, what does fruit[:] mean?
The same as the original string. It's a bit of a redundant statement.
-
Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
fruit = "Banana" index = len(fruit) while index > 0: print(fruit[index-1]) index = index - 1
-
index < len(fruit)
loop condition
-
-
www.py4e.com www.py4e.com
-
hat happens when you run this program?
It runs like before.
-
error message you get.
NameError: name 'repeat_lyrics' is not defined
-
-
www.py4e.com www.py4e.com
-
1 + 2 * 5
Value: 11 Type: Int
-
height/3
Value:4.0 Type:Float
-
width/2.0
Value: 8.5 Type: Float
-
width//2
Value: 8 Type: Int
-
-
www.py4e.com www.py4e.com
-
Exercise 9: How do you fix a “Syntax Error”?
Check for typos
-
Output Device
A human equivalent of an output device - all the built-in orifices that generate sound!
-
Secondary Memory
notes written in a Notebook, or a blog is an example of secondary memory
-
Input Device
Input devices are like the Ears, Eyes, Nose and Mouth in Humans.
-
Main Memory
Is like the memories in our heads. Just like information stored in the memory is unretrievable when a machine is switched off, our memories are erased when we die.
-
Central processing unit
Is like the brain, which processes the information and gives us cognition
-
We need to pick a name for that value to be remembered and we can use that symbolic name to retrieve the value later
Why do we need variables?
-
stored instructions a program and the act of writing these instructions down and getting the instructions to be correct programming.
What is a program? What is programming?
Tags
Annotators
URL
-
- Nov 2020
-
github.com github.com
-
json('https://unpkg.com/world-atlas@1.1.4/world/110m.json')
Curran: "The first thing we need for the map is the data that goes into it. The outlines of the countries. There's a great project called World Atlas and it's released as a package on npm so if you just do a Google search for "world atlas NPM" you'll find it. This is a project by Mike Bostock which converts the natural earth vector data to topoJson format which is an efficient format for representing data about geography. It's like a compressed version of geoJson but in any case this URL here is what you can copy to load in the low resolution shapes for the countries of the world.
"It's a bunch of JSON data that has countries inside of it. From this data we can render polygons on the screen for each country which is our goal."
-
svg = select('svg');
The const declaration creates a read-only reference to a value. We're calling the D3 module select on the SVG element which was declared in the index.html file, and assigning it to a named constant called svg.
-
json
Fetches the JSON file at the specified input URL https://github.com/d3/d3-fetch
This function is called at line 13.
-
type: 'Sphere
Makes only the earth part of the background blue.
-
geoPath
This package converts the data path into an SVG path. A string that we can use on SVG paths.
Preamble: "Let's look at a reference example of a map to see how everything else sort of fits together. My favorite way of finding examples is blockbuilder.org/ search. You could type a map into here and then just look at the ones with thumbnails and I know Mike Bostock has like the simplest most canonical example so I can search by mbostock as the username this looks like a good starting point. US states topoJson this is pretty close to what we want but we want to do the same thing for countries. One thing we need is geoPath from d3."
-
geoNaturalEarth1
The map projection style can be picked here. e.g. Geomercator, etc.
Curran: "In the d3 geo package which is part of the default d3 bundle there is an embarrassment of riches in terms of different map projections that are available to you."
-
topojson
TopoJSON is an extension of GeoJSON that encodes topology.
Curran explains: "Because the data is formatted as TopoJSON and there are d3 utilities to render GeoJSON data structures, we need to convert TopoJSON to GeoJSON in memory using a library that’s called topojson. Also written by Mike Bostock. This is an npm package, that can be loaded from unpkg. Use the minified version."
-
select
This d3 module selects the first DOM element that matches the specified selector string. If no elements match the selector, returns an empty selection. If multiple elements match the selector, only the first matching element (in document order) will be selected. https://devdocs.io/d3~5/d3-selection#select
-
const projection = geoNaturalEarth1(); const pathGenerator = geoPath().projection(projection);
Setting up instances of the projection and geoPath here. The projection is passed into pathGenerator on line 7.
-
feature
Topojson.feature is the function that we need to convert our topojson into geojson. In our code we can say import {feature} from topoJson and then we can invoke feature, passing in as the first argument the data and the second argument is going to be the countries.
-
-
github.com github.com
-
onChange
1)
Let’s recap what happens when you edit an input:
React calls the function specified as onChange on the DOM input element.
In our case, this is the handleChange method in the TemperatureInput component.
-
ReactDOM
8)
React DOM updates the DOM with the boiling verdict and to match the desired input values. The input we just edited receives its current value, and the other input is updated to the temperature after conversion.
-
TemperatureInput
7)
React calls the render methods of the individual TemperatureInput components with their new props specified by the Calculator. It learns what their UI should look like.
-
onTemperatureChange
3)
When it previously rendered, the Calculator had specified that onTemperatureChange of the Celsius TemperatureInput is the Calculator’s handleCelsiusChange method, and onTemperatureChange of the Fahrenheit TemperatureInput is the Calculator’s handleFahrenheitChange method. So either of these two Calculator methods gets called depending on which input we edited.
-
render
6)
React calls the Calculator component’s render method to learn what the UI should look like. The values of both inputs are recomputed based on the current temperature and the active scale. The temperature conversion is performed here.
-
handleCelsiusChange(temperature) { this.setState({scale: 'c', temperature}); } handleFahrenheitChange(temperature) { this.setState({scale: 'f', temperature}); }
4)
Inside these methods, the Calculator component asks React to re-render itself by calling this.setState() with the new input value and the current scale of the input we just edited.
-
Calculator
Calculator: A component that renders an < input > that lets you enter the temperature, and keeps its value in this.state.temperature. Additionally, it renders the BoilingVerdict for the current input value.
-
BoilingVerdict
8)
React calls the render method of the BoilingVerdict component, passing the temperature in Celsius as its props.
It accepts the celsius temperature as a prop, and prints whether it is enough to boil the water:
-
handleChange
2)
The handleChange method calls this.props.onTemperatureChange() with the new desired value. Its props, including onTemperatureChange, were provided by its parent component, the Calculator.
-
-
legacy.reactjs.org legacy.reactjs.org
-
preventDefault()
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
-
event
https://developer.mozilla.org/en-US/docs/Web/API/Event
The Event interface represents an event which takes place in the DOM.
An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent().
The target property of the Event interface is a reference to the object onto which the event was dispatched
Value comes from the HTMLInputElement interface https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement 605
-
- Oct 2020
-
github.com github.com
-
res
HTTP response argument to the middleware function, called "res" by convention.
Request - User's incoming data. Response - Your outgoing data.
-
req
HTTP request argument to the middleware function, called "req" by convention.
Request - User's incoming data. Response - Your outgoing data.
-
process
Node has a handful of built-in identifiers. One of those globals is console, which we use to log out values to the terminal (console.log()). There's another global with the name of global. This object is a namespace which is available throughout the entire Node process. Process is another such global. It gives you access to the running node process.
-
- Sep 2020
-
www.moneycontrol.com www.moneycontrol.com
-
CodeNinja
-
Unqork
-
Zapier
-
Airtable
-
Bubble
-
Appsmith
-
Adalo
-
Webflow
-
Glideapps
-
Notion
-
Retool
-
Smolcoach
-
Nocoloco
-
-
-
toUTCString
The toUTCString() method converts a date to a string, using the UTC time zone.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
-
Date.parse
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
-
-
github.com github.com
-
.select("-age")
Then call the select method on this → inside give a string wit '-age' → this excludes the age field from the result objects
query.select()
Specifies which document fields to include or exclude (also known as the query "projection"). A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default. https://mongoosejs.com/docs/api/query.html#query_Query-select
-
.limit(2)
Then call the limit() method on this → inside give 2 → this limits to returning 2 documents
https://mongoosejs.com/docs/api/query.html#query_Query-limit
-
.sort({ name: "asc" })
Call the sort() method on this → inside give an object with a key of 'name' and a value for 'asc' → This sorts them by name in ascending order.
query.sort
Sets the sort order. If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.
-
.exec((err, filteredData) => {
Finally call the exec() method, inside this give a callback function that takes in an error and an array of the filtered results
query.exec()
Executes the query. Inside a Callback function is specified, taking in error and any returned data.
-
if (err) { console.log(err); } else { done(null, filteredData);
Inside this, log any errors if they exist, otherwise give the filtered results array to the done() function as the second argument for marking
-
Person.find({ favoriteFoods: { $all: [foodToSearch] } })
In the queryChain function, call the find() method on the Person model → as the sole argument, give an object with a key of favoriteFoods and a value of an object with a key of $all and a value of an array with just the foodToSearch variable inside
-
if (err) { console.log(err); } done(null, response);
log any errors if they exist, otherwise call the done() function, giving null as the first argument and the JSON status as the second argument
-
err, response
As the second argument, give a callback function that takes in an error and a JSON status
-
name: nameToRemove
As the first argument, give an object with a key of name and value of the nameToRemove variable (Mary)
-
Person
In the removeManyPeople function, call the remove() method on the Person model
-
remove
model.remove()
Removes all documents that match conditions from the collection. To remove just the first document that matches conditions, set the single option to true.
https://mongoosejs.com/docs/api/model.html#model_Model.remove
-
if (err) { console.log(err); } else { done(null, delrec)
log the error if it exists, otherwise call the done() function with null as the first argument and the deleted record as the second
-
err, delrec
As the second argument give a callback function that takes in an error and the deleted record
-
personId
As the first argument, provide the personId that the main function takes in
-
Person
call the findByIdAndRemove() method on the Person Model
-
findByIdAndRemove
model.findByIdAndRemove()
Issue a mongodb findAndModify remove command by a document's _id field. findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). Finds a matching document, removes it, passing the found document (if any) to the callback. https://mongoosejs.com/docs/api/model.html#model_Model.findByIdAndRemove
-
findOneAndUpdate
model.findOneAndUpdate()
Issues a mongodb findAndModify update command. Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes if callback is passed else a Query object is returned.
https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndUpdate
-
if (err) return console.log(err); done(null, updatedDoc);
If the error exists, log it, Otherwise run the done function with null as the first argument and the updated record as the second argument
-
err, updatedDoc
As the fourth argument, give a callback function that takes in an error and the updated record
-
new: true
As the third argument, give an object with the option new set to true
-
age: ageToSet
As the second argument, give an object with the age set to the ageToSet variable → This is the desired properties of the updated record
-
name: personName
As the first argument, give an object for our search query, with name set to the personName that the main function takes in
-
findAndUpdate
Mongoose has some methods findOneAndUpdate() and findByIdAndUpdate() that allow us to update records in one step. We pass in a query object to find our desired record, a second object with our desired properties, a third object with an option to return the new record, and finally a callback function.
In the findAndUpdate function, call the findOneAndUpdate() method on the Person Model
-
if (err) return console.log(err); done(null, updatedPerson);
Log the error if it exists, otherwise, call the done() function, giving null as the first argument, and the updatedResult as the second
-
person.save
Call the save() method on this result, and give a callback function that takes in an error and an updated result
-
Person.findById(personId, (err, person)
Call the findById on the Person Model, giving the personId as the first argument and a callback function as the second, taking in an error and a result
-
findEditThenSave
To Update records, it's a 3 step process: Find and Retrieve the record, Edit and make changes, and Save the changes to the database. We can combine the concepts we learned in the previous challenges to do this.
-
if (error) { console.log(error); } else { done(null, result);
If there is an error, log it, otherwise, call the done() method, giving the arguments null (no error) and result
-
error, result
As the second argument, give a callback function taking in an error and a result
-
_id: personId
As the first argument, give the personId that the outer function takes in
-
Person.findById
model.findById()
Finds a single document by its _id field. findById(id) is almost* equivalent to findOne({ _id: id }). If you want to query by a document's _id, use findById() instead of findOne().
-
if (error) { console.log(error); } else { done(null, result); }
If there is an error, log it, otherwise, call the done() method, giving the arguments null (no error) and result
-
error, result
/As the second argument, give a callback function taking in an error and a result.
-
favoriteFoods: food
- As the first argument, give an object with a key of 'favoriteFoods' and 'food' as the value
-
Person.findOne
Inside the findOneByFood function, call the findOne() method on the Person model
-
findOne
model.findOne()
Behaves like .find(), but it returns only one document (not an array), even if there are multiple items. It is especially useful when searching by properties that you have declared as unique.
-
document
Instances of Models are documents
-
Model.find
model.find()
Accepts a query document (a JSON object) as the first argument, then a callback. It returns an array of matches from the collection for that model.
-
Person.find
Inside the findPeopleByName function, call the find() method on the Person model
-
error, arrayOfResults
As the second argument, give a callback function taking in an error and an array of results
-
name: personName
As the first argument, give an object with a key of 'name' and a value of 'personName'
-
done
Otherwise, run the done() function with null and createdPeople to allow it to be tested
-
err
If there is an error, console log it
-
done(null, arrayOfResults
- Otherwise, run the done() function with null and arrayOfResults to allow it to be tested
-
if (error) { console.log(error);
If there is an error, console log it
-
err, createdPeople
As the second argument, give a function that takes in an error, and the returned data after the document has been written to the database → in this case an array of 'createdPeople'
-
Person.create(arrayOfPeople
In createManyPeople, call the create() method on the Person model, giving the arrayOfPeople array as the first argument
-
arrayOfPeople
define 'arrayOfPeople' as an array of object with property keys and values for our people schema
-
sriramSharma.save
Call the save() method on this instance, giving it a function, which itself takes in an error and data
document.save()
Saves this document by inserting a new document into the database if document.isNew is true, or sends an updateOne operation only with the modifications to the database, it does not replace the whole document in the latter case.
-
data
'Data' refers to the data that was created on the database, in this case, the person from the database is returned as a javascript object for easy access.
-
done(null, data)
Otherwise, call the done() function, giving in 'null' as the first argument (since there is no error), and the data as the second argument, so that it can be tested.
-
if (err) return console.error(err)
Inside this function, log the error if there is an error
-
var sriramSharma = new Person
Inside the createAndSavePerson() method, create a new Person using the model constructor and give some properties
-
CRUD
Create, Retrieve, Update, Delete. These are operations enabled through a database.
-
var Person = mongoose.model("Person", personSchema
Create a Model from this schema with mongoose.model() and call it 'Person'
We can now use Person() as a constructor to create Person Records (documents)
-
personSchema = new Schema
Inside the constructor, give an Object with key value pairs:
- For Name, give an object declaring a type of string, and required as true
- For Age, give a type of Number
- For Favourite Foods, give an array of Strings
-
var Schema = mongoose.Schema
Create a Schema and assign it to a variable
-
mongoose.model
mongoose.model()
When you call mongoose.model() on a schema, Mongoose compiles a model for you. The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. https://mongoosejs.com/docs/models.html#compiling
-
Models
Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.
-
Schema
You can think of a Mongoose schema as the configuration object for a Mongoose model. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. You construct one, giving an object with key value pairs with properties and types the collection should have.
-
-
www.freecodecamp.org www.freecodecamp.org
-
Schema
Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
-
Express
Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:
- Write handlers for requests with different HTTP verbs at different URL paths (routes).
- Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
- Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
- Add additional request processing "middleware" at any point within the request handling pipeline.
While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction
-
Node.js
"As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications."
"Node.js is similar in design to, and influenced by, systems like Ruby's Event Machine and Python's Twisted. Node.js takes the event model a bit further. It presents an event loop as a runtime construct instead of as a library.
In other systems, there is always a blocking call to start the event-loop. Typically, behavior is defined through callbacks at the beginning of a script, and at the end a server is started through a blocking call like EventMachine::run(). In Node.js, there is no such start-the-event-loop call. Node.js simply enters the event loop after executing the input script. Node.js exits the event loop when there are no more callbacks to perform. This behavior is like browser JavaScript — the event loop is hidden from the user."
-
-
github.com github.com
-
var express = require('express'); var app = express();
Creating an express app object.
-
post
Create a new resource using the information sent with the request,
-
bodyParser.json
Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).
https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions
-
urlencoded
Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).
https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions
-
extended: false
extended=false is a configuration option that tells the parser to use the classic encoding. When using it, values can be only strings or arrays
-
bodyParser
Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
https://expressjs.com/en/resources/middleware/body-parser.html
-
req, res, next
What is Middleware? It is those methods/functions/operations that are called BETWEEN processing the Request and sending the Response in your application method.
FCC: Middleware functions are functions that take 3 arguments: the request object, the response object, and the next function in the application’s request-response cycle. These functions execute some code that can have side effects on the app, and usually add information to the request or response objects. They can also end the cycle by sending a response when some condition is met. If they don’t send the response when they are done, they start the execution of the next function in the stack. This triggers calling the 3rd argument, next().
-
firstName
template literals
-
first: firstName, last: lastName
Destructuring lets you specify the elements you want to extract from an array or object on the left side of an assignment
https://www.freecodecamp.org/news/destructuring-in-javascript-es6-ee963292623a/
-
req.query
Docs: "This property is an object containing a property for each query string parameter in the route"
https://expressjs.com/en/5x/api.html#req.query
FCC: "Another common way to get input from the client is by encoding the data after the route path, using a query string. The query string is delimited by a question mark (?), and includes field=value couples. Each couple is separated by an ampersand (&). Express can parse the data from the query string, and populate the object req.query"
-
req.params
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
https://expressjs.com/en/guide/routing.html#route-parameters
-
function
this is the "final handler" which responds with a JSON object. taking the structure {time: req.time}
-
function
this is the middleware function
-
process.env.MESSAGE_STYLE
FCC: The environment variables are accessible from the app as process.env.VAR_NAME. The process.env object is a global Node object, and variables are passed as strings. By convention, the variable names are all uppercase, with words separated by an underscore
https://www.freecodecamp.org/learn/apis-and-microservices/basic-node-and-express/use-the--env-file
-
res.json
converts a valid JavaScript object into a string, then sets the appropriate headers to tell your browser that you are serving JSON, and sends the data back
-
express.static
express.static(root, [options])
FCC: "An HTML server usually has one or more directories that are accessible by the user. You can place there the static assets needed by your application (stylesheets, scripts, images). In Express, you can put in place this functionality using the middleware express.static(path), where the path parameter is the absolute path of the folder containing the assets."
-
res.sendFile
You can respond to requests with a file using the res.sendFile(path) method
-
function
app.METHOD(path, callback [, callback ...])
Callback functions; can be: A middleware function. A series of middleware functions (separated by commas). An array of middleware functions. A combination of all of the above.
-
res.send('Hello Express');
res.send([body]) Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array. For example:
res.send(Buffer.from('whoop')) res.send({ some: 'json' }) res.send('
some html
') res.status(404).send('Sorry, we cannot find that!') res.status(500).send({ error: 'something blew up' })This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.
When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined as shown below:
res.set('Content-Type', 'text/html') res.send(Buffer.from('
some html
')) When the parameter is a String, the method sets the Content-Type to “text/html”:res.send('
some html
') When the parameter is an Array or Object, Express responds with the JSON representation: -
'/'
Path (route) for which the middleware function applies.
-
get
The HTTP method for which the middleware function applies.
"Routes HTTP GET requests to the specified path with the specified callback functions."
https://expressjs.com/en/5x/api.html#app.get
What is GET? via MDN:
HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.
The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
-
middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
The following figure shows the elements of a middleware function call:
-
app.listen(process.env.PORT || 3000 )
It tells your server to listen on a given port, putting it in running state. You can see it at the bottom of the file.
It is inside comments because, for testing reasons, we need the app to be running in the background. All the code that you may want to add goes between these two fundamental parts.
-
console.log("Hello World")
Node is just a JavaScript environment. Like client side JavaScript, you can use the console to display useful debug information.
-
- Aug 2020
-
www.freecodecamp.org www.freecodecamp.org
-
runtime
"Runtime describes software/instructions that are executed while your program is running, especially those instructions that you did not write explicitly, but are necessary for the proper execution of your code.
Low-level languages like C have very small (if any) runtime. More complex languages like Objective-C, which allows for dynamic message passing, have a much more extensive runtime.
You are correct that runtime code is library code, but library code is a more general term, describing the code produced by any library. Runtime code is specifically the code required to implement the features of the language itself."
via: https://stackoverflow.com/questions/3900549/what-is-runtime
-
-
github.com github.com
-
svg.append('path')
selection.append(type)
Appends a new element of this type (tagname) as the last child of each selected element (in this case, svg), or before the next following sibling in the update selection if this is an enter selection. https://devdocs.io/d3~5/d3-selection#selection_append
-
enter
The enter selection is typically used to create “missing” elements corresponding to new data. https://devdocs.io/d3~5/d3-selection#selection_enter
-
attr
selection.attr(name[, value])
"If a value is specified, sets the attribute with the specified name to the specified value on the selected elements and returns this selection.
If the value is a constant, all elements are given the same attribute value; otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]"
-
import
What: A statement. Why:: To import modules. To access what an export has made available in another file/module. You can import a variable, object literal, class, or function.
https://www.freecodecamp.org/news/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773/
-
- Jul 2020
-
github.com github.com
-
pathGenerator
same as "d => pathGenerator(d)"
-
svg.selectAll('path').data(countries.features)
making one SVG path here for each of the countries.
-
feature(data, data.objects.countries);
"Topojson.feature is the function that we need to convert our topojson into geojson. In our code we can say import {feature} from topoJson and then we can invoke feature passing in as the first argument the data and the second argument is going to be the countries."
-
then(data
Passing a url to json returns a promise. So to get access to this data we can say .then, and then pass a function that accepts as input the data.
-
-
github.com github.com
-
useState
Returns a stateful value, and a function to update it.
During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).
The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
-
.selectAll("circle") .data(data)
"Hey D3, select all of the existing circle elements in my SVG, and synchronise them with the data I am giving you here. "
-
data
The data defined in the useState hook is also added to the dependency array of the useEffect hook. Every time data changes, the useEffect code block is triggered again.
-
useState
We've stored a data array in the useState hook so that we can store the array and change it.
-
circle
Does the same thing as:
enter-> enter.append("circle")
-
join
"D3’s data join lets you specify exactly what happens to the DOM as data changes. This makes it fast—you can minimize DOM operations—and expressive—you can animate enter, update and exit separately. Yet power comes at a cost: the data join’s generality makes it hard to learn and easy to forget."
-
useRef
To make this svg available to d3, we're going to use a hook called useRef. We are importing it here.
"useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
A common use case is to access a child imperatively:" https://reactjs.org/docs/hooks-reference.html#useref
-
select
With select, we're now making all the d3 methods available on this SVG element.
-
svgRef.current
svgRef.current is where the DOM element lives.
-
useEffect
"The function passed to useEffect will run after the render is committed to the screen"
We're making the SVG DOM element available to D3 by using the useEffect hook, so that it accesses the SVG after it is rendered.
-
useEffect
useEffect(didUpdate); Accepts a function that contains imperative, possibly effectful code.
Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI.
Instead, use useEffect. The function passed to useEffect will run after the render is committed to the screen. Think of effects as an escape hatch from React’s purely functional world into the imperative world.
By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.
-
data
An array with some arbitrary numbers in it.
-
-
egghead.io egghead.io
-
interpreted
A language that executes instructions directly and freely, without previously compiling a program into machine-language instructions.
-
supports object-oriented, imperative, and functional programming styles
Programming paradigms/styles.
-
dynamic
A dynamic language (Lisp, Perl, Python, Ruby) is designed to optimize programmer efficiency, so you can implement functionality with less code. A static language (C, C++, etc) is designed to optimize hardware efficiency, so that the code you write executes as quickly as possible. https://stackoverflow.com/questions/20563433/difference-between-static-and-dynamic-programming-languages#:~:text=A%20dynamic%20language%20(Lisp%2C%20Perl,executes%20as%20quickly%20as%20possible.
-
multi-paradigm
Programming paradigms are a way to classify programming languages based on their features - these include imperative, declarative,
https://upload.wikimedia.org/wikipedia/commons/f/f7/Programming_paradigms.svg
https://en.wikipedia.org/wiki/Comparison_of_multi-paradigm_programming_languages
-
prototype-based,
"A style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as prototypal, prototype-oriented, classless, or instance-based programming."
-
Apache CouchDB
An open-source document-oriented NoSQL database. https://couchdb.apache.org/
-
node.js
"An open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser." https://en.wikipedia.org/wiki/Node.js
-
scripting language
"A script or scripting language is a computer language with a series of commands within a file that is capable of being executed without being compiled. Good examples of server-side scripting languages include Perl, PHP, and Python. The best example of a client side scripting language is JavaScript."
-
first-class functions
"A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. " - developer.mozilla.org
-
object-oriented
a computer programming model that organizes software design around data, or objects, rather than functions and logic
-