Competitive Programming

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Add one to n using bit ops

-~n

Properties of the Object built-in-type?

1. Object.length Has a value of 1. 2. Object.prototype Allows the addition of properties to all objects of type Object.

DOCUMENT_TYPE_NODE

<!DOCTYPE html>

Add a "//" to multiple lines at once

<C-v> + I + // + esc

@angular/router

Component router.

What letter is typically used to depict a cost function?

Function J

What is "this" keyword for?

In JavaScript, the thing called this, is the object that "owns" the current code.

What is the page object in a browser?

In a browser the page object is the browser window. The function above automatically becomes a window function.

inflection points

In differential calculus, an inflection point, point of inflection, flex, or inflection (inflexion) is a point on a curve at which the curve changes from being concave (concave downward) to convex (concave upward), or vice versa. A point where the curvature vanishes but does not change sign is sometimes called a point of undulation or undulation point.

transpose matrix

In linear algebra, the transpose of a matrix A is another matrix AT (also written A′, Atr, tA or At) created by any one of the following equivalent actions: reflect A over its main diagonal (which runs from top-left to bottom-right) to obtain AT write the rows of A as the columns of AT write the columns of A as the rows of AT Formally, the i th row, j th column element of AT is the j th row, i th column element of A: {\displaystyle [\mathbf {A} ^{\mathrm {T} }]_{ij}=[\mathbf {A} ]_{ji}} [\mathbf {A} ^{\mathrm {T} }]_{ij}=[\mathbf {A} ]_{ji} If A is an m × n matrix then AT is an n × m matrix.

AJS: What scope does JS have as specifically as possible?

Lexical scoping with function scope.

Array.prototype.concat - does it mutate the given array?

Nah, creates a new one. See specs: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.4

Haskell: do strings exist in Haskell?

Nah, lists of chars do though [Char] single chars can be written with single quotes while list of chars can be written with double quotes

Object.getPrototypeOf()

The Object.getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.

Router vs Request Handlers?

The Router routes the URL the requests are coming in for and routes these requests to the Request Handlers.

What does the R mean in matrices?

The set of all rows x columns matrices

String.prototype.toString()

The toString() method returns a string representing the specified object. str.toString()

What was the significant advance of ML?

Type inference - compiler would infer types based on code.

What is the advantage of using call and apply methods?

With call() or apply() you can set the value of this inside the function and invoke the function as a new method of an existing object.

Say there are four DB Queries, one takes 200ms, the second takes 400ms, the third takes 600 ms, the fourth takes 800ms - how does node shine in this case?

With node, you can execute all your queries at once, reducing the response time to the duration it takes to execute the slowest query. -- 800MS - whereas in other non asynchronous platforms it would take 200+400+600+800 unless specifically made to run in parallel

X && Y equivalent?

X ∧ Y (called wedge)

X || Y equivalent?

X ∨ Y (called Vee)

Is the current directory dot necessary when importing modules in Node?

Yes.

var foo = function bar() { // statements go here }; What are the three ways to recursively call this named function expression?

bar() arguments.callee() foo()

Import a module foo in the subdirectory bar

const foo = require('./bar/foo');

toString()

returns a string value of the regular expression

What are the three ways a function can refer to itself? (Recursion)

the function's name arguments.callee an in-scope variable that refers to the function

therefore

ES6: var a = 5; var b = 10; console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + "."); // "Fifteen is 15 and // not 20." rewrite using ES6 template literals

var a = 5; var b = 10; console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`); // "Fifteen is 15 and // not 20."

trim()

white space is removed from both sides of string original string is not altered

when does a stream stop writing

whitespace encounter

Haskell: whitespace is not significant in Haskell T or F?

whitespace is significant in Haskell

ES6: let name = 'Bob'; String.raw`Hi\n${name}!`; returns?

"Hi\nBob!"

jQuery( selector [, context ] ) is equivalent to

$(); not to be confused with Chrome's default

Gradient Descent for linear regression?

(Review again)

Why is Function.prototype.apply() useful?

(There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. )

AJS: IIFE syntax ways

(function(){ /* code */ })(); - ben alman and many others (function(){ /* code */ }()); - crockford

How to check if a number is a power of two?

(n & (n - 1)) == 0 this works because every power of 2 has just one 1 in binary

Get absolute value of n using bit ops?

(n ^ (n >> 31)) - (n >> 31);

Scalar official definition?

(of a quantity) having only magnitude, not direction.

Define the properties of two matrices and those particular of square matrices

*All Matrices* Not commutative, Distributive over matrix addition Scalar multiplication is compatible with matrix multiplication, Transpose Complex Conjugate Conjugate Transpose Traces *Square Matrices* Identity Element - If A is a square matrix, then AI = IA = A where I is the identity matrix of the same order. Inverse Matrix - ?? Determinants - if A and B are square matrices of the same order, the determinant of their product AB equals the product of their determinants:

When is Matrix Multiplication commutative?

... one matrix is the Identity matrix. ... one matrix is the Zero matrix. ... both matrices are rotation matrices. (basically case #2) ... both matrices are Diagonal matrices.

Create a Student class that inherits from a Person Class

// Define the Person constructor var Person = function(firstName) { this.firstName = firstName; }; // Add a couple of methods to Person.prototype Person.prototype.walk = function(){ console.log("I am walking!"); }; Person.prototype.sayHello = function(){ console.log("Hello, I'm " + this.firstName); }; // Define the Student constructor function Student(firstName, subject) { // Call the parent constructor, making sure (using Function#call) // that "this" is set correctly during the call Person.call(this, firstName); // Initialize our Student-specific properties this.subject = subject; } // Create a Student.prototype object that inherits from Person.prototype. // Note: A common error here is to use "new Person()" to create the // Student.prototype. That's incorrect for several reasons, not least // that we don't have anything to give Person for the "firstName" // argument. The correct place to call Person is above, where we call // it from Student. Student.prototype = Object.create(Person.prototype); // See note below // Set the "constructor" property to refer to Student Student.prototype.constructor = Student; // Replace the "sayHello" method Student.prototype.sayHello = function(){ console.log("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + "."); }; // Add a "sayGoodBye" method Student.prototype.sayGoodBye = function(){ console.log("Goodbye!"); }; // Example usage: var student1 = new Student("Janet", "Applied Physics"); student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics." student1.walk(); // "I am walking!" student1.sayGoodBye(); // "Goodbye!" // Check that instanceof works correctly console.log(student1 instanceof Person); // true console.log(student1 instanceof Student); // true

What do we create with a constructor invocation? step 1

// This is a function constructor: function myFunction(arg1, arg2) { this.firstName = arg1; this.lastName = arg2; } A constructor invocation creates a new object. The new object inherits the properties and methods from its constructor. // This creates a new object var x = new myFunction("John","Doe"); x.firstName; // Will return "John"

Write a file my-module.js that exports a default function cube! Then import it in another file. Use Default Exports

// module "my-module.js" export default function cube(x) { return x * x * x; } import cube from 'my-module'; console.log(cube(3)); // 27

Write a file my-module.js that exports a function Cubed and a const foo. Then import the two into another file. Use Named Exports

// module "my-module.js" export function cube(x) { return x * x * x; } const foo = Math.PI + Math.SQRT2; export { foo }; -------- import { cube, foo } from 'my-module'; console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888

Synchronous vs Asynchronous code?

//example 1 var result = database.query("SELECT * FROM hugetable"); console.log("query finished"); console.log("Next line"); //example 2 database.query("SELECT * FROM hugetable", function(result) { console.log("query finished"); }); console.log("Next line"); query finished Next line Next line query finished

Create a global namespace called MYAPP, then create a sub namespace called event

//global namespace var MYAPP = MYAPP || {}; // sub namespace MYAPP.event = {};

AJS: What are the four ways that the <this> keyword can be called?

1. New Keyword 2. Explicit/Hard Binding 3. Implicit Binding Rule: turns into the object that invoked the function -- o2 = {bar: "bar2", foo: foo}; 4 (least precedence). normal function call : default binding rule - if you are in strict mode, this is undefined if not, then this is the global object. 1. Default Binding - (catch all) - plain, un-decorated function reference - goes to global or undefined depending on strict mode settings 2. Implicit Binding - calling a function off an object obj1.foo() where foo can be defined anywhere - goes to the object that is calling it 3a. Explicit Binding - explicitly defining the this reference using call or apply ``` function foo(){ console.log(this.a); } var obj = { a: 2 }; foo.call(obj); ``` how does "boxing" work? 3b. Hard Binding - solves the possibility of explicit or any binding losing its intended binding - you can implement using Function.prototype.bind, a helper function, function wrapping or any other mechanism ``` function foo(){ console.log(this.a); } var obj = { a : 2; }; var bar = function(){ foo.call( obj); }; bar(); // 2 setTimeout(bar, 100); //2 bar.call(window); // 2 ``` 4. New Keyword - As a new object created via constructor call hijacking via "new"

Three use cases for apply()

1. Using apply to chain constructors You can use apply to chain constructors for an object, similar to Java. In the following example we will create a global Function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. 2. Using apply and built-in functions Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min to find out the maximum/minimum value in an array. (// min/max number in an array var numbers = [5, 6, 2, 3, 7]; // using Math.min/Math.max apply var max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...) // or Math.max(5, 6, ...) var min = Math.min.apply(null, numbers); // vs. simple loop based algorithm max = -Infinity, min = +Infinity; for (var i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } }) 3. Using apply in "monkey-patching" Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given some object.foo function, you can modify the function in a somewhat hacky way, like so: (var originalfoo = someobject.foo; someobject.foo = function() { // Do stuff before calling function console.log(arguments); // Call the function as it would have been called normally: originalfoo.apply(this, arguments); // Run stuff after, here. })

In 8-bit Two's Complement what is -1 in binary, what about -127?

1111 1111

Haskell: how to convert infix operator to prefix?

2 + 2 ---> (+) 2 2

Simplify 2(3x), and justify your steps.

2(3x) original (given) statement (2×3)x by the Associative Property 6x simplification (2×3 = 6)

The sum of powers of two is...

2^(n+1) - 1

Commutative Property

3 * 2 = 2 * 3, 5 + 3 = 3 + 5 The word "commutative" comes from "commute" or "move around", so the Commutative Property is the one that refers to moving stuff around. For addition, the rule is "a + b = b + a"; in numbers, this means 2 + 3 = 3 + 2. For multiplication, the rule is "ab = ba"; in numbers, this means 2×3 = 3×2. Any time they refer to the Commutative Property, they want you to move stuff around; any time a computation depends on moving stuff around, they want you to say that the computation uses the Commutative Property.

3x4 matrix * 4x1 vector result is...

3x1 matrix

function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); result = fn_inside(5); Value of result?

8

Haskell: how to get type of expression in GHCI?

:type expr

String comparison - strcmp equivalent?

<, > var a = 'a'; var b = 'b'; if (a < b) { // true console.log(a + ' is less than ' + b); } else if (a > b) { console.log(a + ' is greater than ' + b); } else { console.log(a + ' and ' + b + ' are equal.'); }

ELEMENT_NODE example?

<body>, <a>, <p>, <script>, <style>, <html>, <h1>

Haskell: Generalizations of <head> and <tail>?

<take> and <drop>

@angular/common

@angular/common - The commonly needed services, pipes and directives provided by the Angular team.

@angular/compiler

@angular/compiler - Angular's Template Compiler. It understand templates and can convert them to code that makes the app run and render. Developers typically don't interact with the compiler directly. They use it indirectly via platform-browser-dynamic or the offline template compiler.

@angular/core

@angular/core - Critical runtime parts of the framework needed by every application. Includes all metadata decorators, Component, Directive, dependency injection, and the component lifecycle hooks.

@angular/platform-browser

@angular/platform-browser - Everything DOM and browser related, especially the pieces that help render into DOM. This package also includes the bootstrapStatic method for bootstrapping applications for production builds that pre-compile templates offline.

@angular/platform-browser-dynamic

@angular/platform-browser-dynamic - Providers and a bootstrap method for applications that compile templates on the client. don't use offline compilation. We use this package for boostrapping during development and for boostrapping plunker samples

What is a Node?

A Node is an interface from which a number of DOM types inherit and allow these various types to be treated or tested similarly.

What is the structure of node objects in the DOM typically compared to?

A Tree

Inheritance definition

A class can inherit characteristics and capabilities from another class.

Namespace definition

A container which lets developers bundle all functionality under a unique, application-specific name.

What are contour plots?

A contour plot is a graphical technique for representing a #D surface by plotting constant z slices, called contours onto a 2Dimensional format. That is, given a value for z, lines are drawn for connecting the x,y, coordinates twhere that z value occurs. The circles in a contour plot are called level sets - the function J is equal here.The center of the contour plot is the minimum of the cost function typically in ML.

Cost function vs Gradient Descent?

A cost function is something you want to minimize. For example, your cost function might be the sum of squared errors over your training set. Gradient descent is a method for finding the minimum of a function of multiple variables. So you can use gradient descent to minimize your cost function. If your cost is a function of K variables, then the gradient is the length-K vector that defines the direction in which the cost is increasing most rapidly. So in gradient descent, you follow the negative of the gradient to the point where the cost is a minimum. If someone is talking about gradient descent in a machine learning context, the cost function is probably implied (it is the function to which you are applying the gradient descent algorithm).

system.js

A dynamic module loader compatible with the ES2015 module specification. There are other viable choices including the well-regarded webpack. SystemJS happens to be the one we use in the documentation samples. It works.

Constructor definition

A method called at the moment an object is instantiated. It usually has the same name as the class containing it.

What is a Privileged Method?

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

What is the Christmas Tree problem?

A problem of asynchronous code due to severe nesting of callbacks.

Array.prototype.slice vs Array.prototype.slice is a good demonstration of what?

A pure function vs a non-pure function. arr.slice([begin[, end]]) --> begin is zero-indexed, end is zero-indexed but is not included in the slice. slice does NOT alter the given array. It returns a shallow copy of elements from the original array. array.splice(start, deleteCount[, item1[, item2[, ...]]]) --> start is the beginning index to start changing the array, deleteCount is the number of elements to delete, items are anything to be added var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; // removes 0 elements from index 2, and inserts 'drum' var removed = myFish.splice(2, 0, 'drum'); // myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] // removed is [], no elements removed // myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] // removes 1 element from index 3 removed = myFish.splice(3, 1); // myFish is ['angel', 'clown', 'drum', 'surgeon'] // removed is ['mandarin'] // myFish is ['angel', 'clown', 'drum', 'surgeon'] // removes 1 element from index 2, and inserts 'trumpet' removed = myFish.splice(2, 1, 'trumpet'); // myFish is ['angel', 'clown', 'trumpet', 'surgeon'] // removed is ['drum'] // myFish is ['angel', 'clown', 'trumpet', 'surgeon'] // removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue' removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); // myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'] // removed is ['angel', 'clown'] // myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'] // removes 2 elements from index 2 removed = myFish.splice(myFish.length -3, 2); // myFish is ['parrot', 'anemone', 'surgeon'] // removed is ['blue', 'trumpet']

What is a vector in linear algebra?

A vector is a list of numbers (can be in a row or column) - think Array. n x 1 matrix (https://en.wikipedia.org/wiki/Row_and_column_vectors)

var foo = function() { ... }

ANONYMOUS FUNCTION EXPRESSION

Divisible by 3?

Add up all digits and see if divisble by 3. If so, the number is divisible by 3.

What is ceteris paribus?

All other things equal, all else unchanged, etc (think partial derivative)

Who founded Lambda Calculus?

Alonzo Church (1930)

ES6: Difference between function declarations and class declarations for OOP JS?

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError: var p = new Polygon(); // ReferenceError class Polygon {}

Object definition in OOP

An instance of a class.

What does it mean for an algorithm to converge?

An iterative algorithm is said to converge when as the iterations proceed the output gets closer and closer to a specific value. In some circumstances, an algorithm will diverge; its output will undergo larger and larger oscillations, never approaching a useful result. The "converge to a global optimum" phrase in your first sentence is a reference to algorithms which may converge, but not to the "optimal" value (e.g. a hill-climbing algorithm which, depending on initial conditions, may converge to a local maximum, never reaching the global maximum).

What is an octet? Why do we use the term?

An octet is a unit of digital information in computing and telecommunications that consists of eight bits. The term is often used when the term byte might be ambiguous, since historically there was no standard definition for the size of the byte.

@angular/http

Angular's http client

What is the root of an Angular 2 App?

AppComponent is the root of the application

What function should you use when intentionally iterating with a predicate that produces side effects?

Array.prototype.foreach(predicate) -- as recommended by Kyle Simpson

Why is it unnecessary to change alpha over time to ensure that the gradient descent converges to a local minimum?

As we approach a local minimum, the gradient descent will take smaller steps because of the change of the derivative or the steepness of the cost function J. Don't need to worry about divergence.

Properties of matrix multiplication?

Associative Trace Determinant: For square matrices only, the determinant of a product is the product of determinants:

What does AMD stand for?

Asynchronous module definition (AMD) is a JavaScript specification that defines an API for defining code modules and their dependencies, and loading them asynchronously if desired. Implementations of AMD provide the following benefits: Website performance improvements.

What does AMD stand for?

Asynchronous module definition designed with browser in mind

What is Node's execution model?

Asynchronous, single-threaded, event-driven execution model.

AJS: Why is the <let> keyword stylistically good for <for> loops?

Because <let> indicates in the code that the variable being created is meant to only exist within that loop. For example, counters like (var i = 0; i < whatever; i++) indicates that, but does not functionally restrict access to i within that loop or block.

Where do we put the object when using apply() or call() methods?

Both methods takes an owner object as the first argument.

What is Bower?

Bower is pretty much dead. Don't need two package managers esp. when NPM is so good and continuously getting grouped with JS overall and not just Node. But, Bower WAS a front-end package manager -- remember when I used it, it sucked. such overtooling. From MPJME: (https://www.quora.com/Why-use-Bower-when-there-is-npm) In almost all cases, it's more appropriate to use Browserify and npm over Bower. It is simply a better packaging solution for front-end apps than Bower is. At Spotify, we use npm to package entire web modules (html, css, js) and it works very well. Bower brands itself as the package manager for the web. It would be awesome if this was true - a package manager that made my life better as a front-end developer would be awesome. The problem is that Bower offers no specialized tooling for the purpose. It offers NO tooling that I know of that npm doesn't, and especially none that is specifically useful for front-end developers. There is simply no benefit for a front-end developer to use Bower over npm. With browserify or webpack, it becomes super-easy to concatenate all your modules into big minified files, which is awesome for performance, especially for mobile devices. Not so with Bower, which will require significantly more labor to get the same effect. npm also offers you the ability to use multiple versions of modules simultaneously. If you have not done much application development, this might initially strike you as a bad thing, but once you've gone through a few bouts of Dependency hell you will realize that having the ability to have multiple versions of one module is a pretty darn great feature. Note that npm includes a very handy dedupe tool that automatically makes sure that you only use two versions of a module if you actually have to - if two modules both can use the same version of one module, they will. But if they can't, you have a very handy out.

What are the three sources of Node modules?

Built in modules, your own project files, third party modules

AJS: What are the different ways to create a new scope?

Catch blocks, curly braces with <let> in ES6, functions.

How to change a linear regression to better fit a data using the same features?

Change the order of the polynomial model by taking the order of the polynomial model and just applying it to the features you do have.

Divisible by 4?

Check last two digits, if divisible by 4 then it is divisible by 4. Also note that all divisble by 4 numbers end in 0,4,8,2,6

Classifier?

Classifier: A classifier is a special case of a hypothesis (nowadays, often learned by a machine learning algorithm). A classifier is a hypothesis or discrete-valued function that is used to assign (categorical) class labels to particular data points. In the email classification example, this classifier could be a hypothesis for labeling emails as spam or non-spam. However, a hypothesis must not necessarily be synonymous to a classifier. In a different application, our hypothesis could be a function for mapping study time and educational backgrounds of students to their future SAT scores.

AJS: What is the definition of Closure (Kyle Simpson's)?

Closure is when a function remembers its lexical scope even when the function is executed outside of that lexical scope.

Browserify allows you to use CommonJS or AMD or RequireJS?

CommonJS in the browser! Remember RequireJS implements the AMD api.

Does Node implement CommonJS or AMD?

CommonJS. RequireJS IMPLEMENTS the AMD api

Object.assign

Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object. Object.create(proto[, propertiesObject])

What is cross-validation?

Cross-validation, sometimes called rotation estimation,[1][2][3] is a model validation technique for assessing how the results of a statistical analysis will generalize to an independent data set. It is mainly used in settings where the goal is prediction, and one wants to estimate how accurately a predictive model will perform in practice. In a prediction problem, a model is usually given a dataset of known data on which training is run (training dataset), and a dataset of unknown data (or first seen data) against which the model is tested (testing dataset).[4] The goal of cross validation is to define a dataset to "test" the model in the training phase (i.e., the validation dataset), in order to limit problems like overfitting, give an insight on how the model will generalize to an independent dataset (i.e., an unknown dataset, for instance from a real problem), etc.

SOLI*D*

DIP - Dependency Inversion Principle (In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:[1] A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend on details. Details should depend on abstractions.)

function multiply(a, b = 1) { return a*b; } multiply(5); // 5 What ES6 feature does this demonstrate?

Default parameters

Class definition

Defines the object's characteristics. A class is a template definition of an object's properties and methods.

JQUERY: event.type

Describes the nature of the event. -- mouseclick,

Nobody complains when you mop the floor.

Do work that is undesired. Don't ask. It's an asset.

Why use one line functions?

Don't be scared of 1-line functions! A lot of programmers seem to have a mental block about 1-line functions, you shouldn't. If it makes the code clearer and cleaner, extract the line into a function. Performance probably won't be affected. Any decent compiler made in the last decade (and perhaps further) will automatically inline a simple 1-line function. Also, 1-line of C can easily correspond to many lines of machine code. You shouldn't assume that even in the theoretical case where you incur the full overhead of a function call that this overhead is significant compared to your "one little line". Let alone significant to the overall performance of your application. Abstraction Leads to Better Design. (Even for single lines of code) Functions are the primary building blocks of abstract, componentized code, they should not be neglected. If encapsulating a single line of code behind a function call makes the code more readable, do it. Even in the case where the function is called once. If you find it important to comment one particular line of code, that's a good code smell that it might be helpful to move the code into a well-named function. Sure, that code may be 1-line today, but how many different ways of performing the same function are there? Encapsulating code inside a function can make it easier to see all the design options available to you. Maybe your 1-line of code expands into a call to a webservice, maybe it becomes a database query, maybe it becomes configurable (using the strategy pattern, for example), maybe you want to switch to caching the value computed by your 1-line. All of these options are easier to implement and more readily thought of when you've extracted your 1-line of code into its own function. Maybe Your 1-Line Should Be More Lines. If you have a big block of code it can be tempting to cram a lot of functionality onto a single line, just to save on screen real estate. When you migrate this code to a function, you reduce these pressures, which might make you more inclined to expand your complex 1-liner into more straightforward code taking up several lines (which would likely improve its readability and maintainability).

What does don't block the event loop mean?

Dont put slow blocking code onto the stack. the event loop wont put other functions onto the stack until it is clear!

Files and modules in Node are in one to one correspondence. What does this mean?

Each js file is its own module. //foo.js const circle = require('./circle.js'); console.log( `The area of a circle of radius 4 is ${circle.area(4)}`); //circle.js const PI = Math.PI; exports.area = (r) => PI * r * r; exports.circumference = (r) => 2 * PI * r;

How do they differ from each other?

Each method differs in how this is initialized.

"Batch" Gradient Descent (BGD or GD)

Each step of gradient descent uses all the training examples. batch GD - This is different from (SGD - stochastic gradient descent or MB-GD - mini batch gradient descent) In GD optimization, we compute the cost gradient based on the complete training set; hence, we sometimes also call it batch GD. In case of very large datasets, using GD can be quite costly since we are only taking a single step for one pass over the training set -- thus, the larger the training set, the slower our algorithm updates the weights and the longer it may take until it converges to the global cost minimum (note that the SSE cost function is convex).

How to set an attribute on an element in Pure JS DOM?

Element.setAttribute() -- element.setAttribute(name, value); *name* is the name of the attribute as a string. *value* is the desired new value of the attribute.

What are the three configurable or not so configurable Object properties?

Enumerable: I can access to all of them using a for..in loop. Also, enumerable property keys of an object are returned using Object.keys method. Writable: I can modify their values, I can update a property just assigning a new value to it: ob.a = 1000; Configurable: I can modify the behavior of the property, so I can make them non-enumerable, non-writable or even non-cofigurable if I feel like doing so. Configurable properties are the only ones that can be removed using the delete operator.

What is an error-first callback?

Error-first callbacks are used to pass errors and data. The first argument is always an error object that the programmer has to check if something went wrong. Additional arguments are used to pass data. (fs.readFile(filePath, function(err, data) { if (err) { //handle the error } // use the data object });)

What is feature scaling?

Feature scaling is a method used to standardize the range of independent variables or features of data. In data processing, it is also known as data normalization and is generally performed during the data preprocessing step. The range of values of raw data varies widely, in some machine learning algorithms, objective functions will not work properly without normalization[citation needed]. For example, the majority of classifiers calculate the distance between two points by the Euclidean distance[citation needed]. If one of the features has a broad range of values, the distance will be governed by this particular feature[citation needed]. Therefore, the range of all features should be normalized so that each feature contributes approximately proportionately to the final distance[citation needed]. Another reason why feature scaling is applied is that gradient descent converges much faster with feature scaling than without it[citation needed]. Some methods are rescaling, standardization, scaling to unit length.

Synonym for Input variable?

Features

What are the three package categories in the dependencies section of package.json?

Features - Feature packages provide our application with framework and utility capabilities. Polyfills - Polyfills plug gaps in the browser's JavaScript implementation. Other - Other libraries that support the application such as bootstrap for HTML widgets and styling.

pandas.DataFrame.fillna

Fill NA/NaN values using the specified method - returns the filled DataFrame

Shift + CMD + A

Find Action

Why do we square instead of using the absolute value when calculating variance and standard deviation?

First I'll answer the mathematical question asked in the question details, which I'm going to restate because I think it is stated wrong: The short answer is "Because of Jensen's inequality." See http://en.wikipedia.org/wiki/Jen... and the rest of the article for context. It says in particular that for a concave function What about the more general question, "Why variance?" I don't believe there is any compelling conceptual reason to use variance as a measure of spread. If forced to choose, my guess is that most people would say more robust measures like interquartile range or MAD better capture the concept of "spread" in most cases. But variance (and more generally "sum of squares") has some attractive properties, many of which flow from the Pythagorean theorem one way or another. Here some of them, without much math: We can decompose sums of squares into meaningful components like "between group variance" and "within-group variance." To generalize the above point, when a random variable Y Y is partly explained by another random variable X X there is a useful decomposition of the variance of Y Y into the part explained by X X and the unexplained part. (See http://en.wikipedia.org/wiki/Law...). If we think more broadly about mean squared error, this too can be decomposed into the sum of variance and squared bias. It is easy to interpret this total error as the sum of "systematic error" and "noise." Often we want to minimize our error. When the error is a sum of squares, we are minimizing something quadratic. This is easily accomplished by solving linear equations. So yes, variance and mean squared error are conveniences rather than conceptual necessities. But they are convenient conveniences.

JQUERY: event.which

For key or mouse events, this property indicates the specific key or button that was pressed.

AMD vs CommonJS advantages and disadvantages summary and where does ES6 modules play into this?

From Reddit: AMD is dead (was killed by Node-compatible bundlers). CommonJS is dead (was killed by Node). Node uses something that looks like CommonJS and is commonly called CommonJS but isn't actually CommonJS (there's a spec for CommonJS imports and Node knowingly violates good chunks of it). ES6 imports aren't currently natively supported in any JS engine I know of. They can however be translated to Node-style "CommonJS" and there are bundlers that support them directly. As for what CommonJS is: CommonJS was an effort to define common standards for the various competing server-side JavaScript environments that existed at the time (including well-known but now mostly obsolete stuff like Rhino as well as a few lesser known alternatives to Node that have died out). Node mostly won, so the new common standard is "whatever Node does". One of the reasons AMD failed was that it is a lot more complex than the alternative. AMD is intended to be asynchronous at runtime. This means it not only defines dependencies, it also conflates the issue of lazy loading dependency bundles. As it turned out, lazy loading dependency bundles at runtime is a difficult, rare and heterogeneous enough problem that a module system can't easily solve it. But having this kind of complexity in it meant that it was effectively overengineered for the more common simple problems. That said, if you write code today, just use either Node-style imports directly or a tool like Babel that translates ES6 imports to Node-style ones.

pandas.Series.describe

Generate various summary statistics, excluding NaN values. For numeric dtypes, it will include: count, mean, std, min, max, and lower, 50, and upper percentiles. For object dtypes (e.g. timestamps or strings), the index will include the count, unique, most common, and frequency of the most common. Timestamps also include the first and last items. For mixed dtypes, the index will be the union of the corresponding output types. Non-applicable entries will be filled with NaN. Note that mixed-dtype outputs can only be returned from mixed-dtype inputs and appropriate use of the include/exclude arguments. If multiple values have the highest count, then the count and most common pair will be arbitrarily chosen from among those with the highest count.

Derive SSE

Given a linear regression model, the difference at each predicted point with the correct point is given by diff = y_i - (mx + b)

When code is executed, an execution context is created. What is created within this execution context ALWAYS?

Global object, <this>

CMD + O

Go to class

What is the downside of using an alpha (learning rate) that is too small?

Gradient descent can be way too slow.

What is the downside of using an alpha (learning rate) that is too big?

Gradient descent can overshoot the minimum and it may fail to converge or even diverge.

What is a nibble in Computer Programming?

Half an octet, 4-bit aggregation 0xF

What are polymorphic types in Haskell?

Haskell also incorporates polymorphic types---types that are universally quantified in some way over all types. Polymorphic type expressions essentially describe families of types. For example, (forall a)[a] is the family of types consisting of, for every type a, the type of lists of a. Lists of integers (e.g. [1,2,3]), lists of characters (['a','b','c']), even lists of lists of integers, etc., are all members of this family. (Note, however, that [2,'b'] is not a valid example, since there is no single type that contains both 2 and 'b'.)

Is Haskell lazy or strict?

Haskell is often described as a lazy language. However, the language specification simply states that Haskell is non-strict, which is not quite the same thing as lazy.

Why is writing code for Node different?

Highly dependent on using callbacks to take full advantage of asynchronous (non-blocking) pattern and event loops.

What is "hypothesis" in machine learning?

Hypothesis: A hypothesis is a certain function that we believe (or hope) is similar to the true function, the target function that we want to model. In context of email spam classification, it would be the rule we came up with that allows us to separate spam from non-spam emails.

AJS: How to avoid pollution of namespace while hiding some variables?

IIFE

SOL*I*D

ISP - Interface Segregation Principle (The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.)

when can we say that the function is invoked with a constructor?

If a function invocation is preceded with the new keyword, it is a constructor invocation.

Gradient Descent algorithm

Image result for gradient descent Gradient descent is a first-order optimization algorithm. To find a local minimum of a function using gradient descent, one takes steps proportional to the negative of the gradient (or of the approximate gradient) of the function at the current point. used with simultaneous updates of the parameters of success Susceptible to falling into local optimum depending on initialization.

the In "non-strict" mode if the value of the first argument is null or undefined, What is value of the first argument replaced with?

In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.

What is the defult global object in HTML?

In HTML the default global object is the HTML page itself, so the function above "belongs" to the HTML page.

In JS OOP, what's a namespace?

In JavaScript a namespace is just another object containing methods, properties, and objects. (The idea behind creating a namespace in JavaScript is simple: create one global object, and all variables, methods, and functions become properties of that object. Use of namespaces also reduces the chance of name conflicts in an application, since each application's objects are properties of an application-defined global object.)

in strict javascript mode which argument becomes the value of this?

In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object. "so it creates an object from anying. "

What datatype is a function in js?

In JavaScript, functions are objects.

What is the gobal object in a webrowser?

In a web browser the global object is the browser window.

Document.createElement

In an HTML document, the Document.createElement() method creates the specified HTML element or an HTMLUnknownElement if the given element name isn't a known one.

Pure Function conditions

In computer programming, a function may be considered a pure function if both of the following statements about the function hold: The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices (usually—see below). Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices (usually—see below).

What is a side effect?

In computer science, a function or expression is said to have a side effect if it modifies some state or has an observable interaction with calling functions or the outside world. For example, a particular function might modify a global variable or static variable, modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions. In the presence of side effects, a program's behaviour may depend on history; that is, the order of evaluation matters. Understanding and debugging a function with side effects requires knowledge about the context and its possible histories

What is a stream?

In computer science, a stream is a sequence of data elements made available over time. A stream can be thought of as items on a conveyor belt being processed one at a time rather than in large batches Streams are processed differently from batch data - normal functions cannot operate on streams as a whole, as they have potentially unlimited data, and formally, streams are codata (potentially unlimited), not data (which is finite). Functions that operate on a stream, producing another stream, are known as filters, and can be connected in pipelines, analogously to function composition. Filters may operate on one item of a stream at a time, or may base an item of output on multiple items of input, such as a moving average. - *processed one at a time rather than in batches*

What is a computer thread??

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.[1] The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its executable code and the values of its variables at any given time. Systems with a single processor generally implement multithreading by time slicing: the central processing unit (CPU) switches between different software threads. This context switching generally happens very often and rapidly enough that users perceive the threads or tasks as running in parallel. On a multiprocessor or multi-core system, multiple threads can execute in parallel, with every processor or core executing a separate thread simultaneously; on a processor or core with hardware threads, separate software threads can also be executed concurrently by separate hardware threads.

K-Fold?

In k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k − 1 subsamples are used as training data. The cross-validation process is then repeated k times (the folds), with each of the k subsamples used exactly once as the validation data. The k results from the folds can then be averaged to produce a single estimation. The advantage of this method over repeated random sub-sampling (see below) is that all observations are used for both training and validation, and each observation is used for validation exactly once. 10-fold cross-validation is commonly used,[7] but in general k remains an unfixed parameter. When k=n (the number of observations), the k-fold cross-validation is exactly the leave-one-out cross-validation. In stratified k-fold cross-validation, the folds are selected so that the mean response value is approximately equal in all the folds. In the case of a dichotomous classification, this means that each fold contains roughly the same proportions of the two types of class labels. Ultimately this helps fix the problem that we want to maximize both the training and test sets in cross-validation.

Haskell 98?

In late 1997, the series culminated in Haskell 98, intended to specify a stable, minimal, portable version of the language and an accompanying standard library for teaching, and as a base for future extensions. The committee expressly welcomed creating extensions and variants of Haskell 98 via adding and incorporating experimental features.

What is an identity matrix?

In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere. Multiplying by the identity matrix I doesn't change anything, just like multiplying a number by 1 doesn't change anything. This property is why I and 1 are each called the "multiplicative identity". But while there is only one "multiplicative identity" for regular numbers (namely the number 1), there are lots of different identity matrices.

Partial derivative?

In mathematics, a partial derivative of a function of several variables is its derivative with respect to one of those variables, with the others held constant (as opposed to the total derivative, in which all variables are allowed to vary). Partial derivatives are used in vector calculus and differential geometry.

Convex functions?

In mathematics, a real-valued function defined on an interval is called convex (or convex downward or concave upward) if the line segment between any two points on the graph of the function lies above or on the graph, in a Euclidean space (or more generally a vector space) of at least two dimensions. Equivalently, a function is convex if its epigraph (the set of points on or above the graph of the function) is a convex set. Well-known examples of convex functions include the quadratic function {\displaystyle x^{2}} x^{2} and the exponential function {\displaystyle e^{x}} e^{x} for any real number x. Convex functions play an important role in many areas of mathematics. They are especially important in the study of optimization problems where they are distinguished by a number of convenient properties. For instance, a (strictly) convex function on an open set has no more than one minimum.

What is differential calculus?

In mathematics, differential calculus is a subfield of calculus concerned with the study of the rates at which quantities change. It is one of the two traditional divisions of calculus, the other being integral calculus. The primary objects of study in differential calculus are the derivative of a function, related notions such as the differential, and their applications. The derivative of a function at a chosen input value describes the rate of change of the function near that input value. The process of finding a derivative is called differentiation. Geometrically, the derivative at a point is the slope of the tangent line to the graph of the function at that point, provided that the derivative exists and is defined at that point. For a real-valued function of a single real variable, the derivative of a function at a point generally determines the best linear approximation to the function at that point.

What are first order methods in numerical analysis?

In numerical analysis, methods that have at most linear local error are called first order methods. They are frequently based on finite differences, a local linear approximation.

What is lazy evaluation?

In programming language theory, lazy evaluation, or call-by-need[1] is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).[2][3] The sharing can reduce the running time of certain functions by an exponential factor over other non-strict evaluation strategies, such as call-by-name.[citation needed] The benefits of lazy evaluation include: The ability to define control flow (structures) as abstractions instead of primitives. The ability to define potentially infinite data structures. This allows for more straightforward implementation of some algorithms. Performance increases by avoiding needless calculations, and error conditions in evaluating compound expressions.

Encapsulation definition

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination[1][2] thereof: A language mechanism for restricting direct access to some of the object's components.[3][4] A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.[5][6] Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of object-oriented programming, while other programming languages which provide lexical closures view encapsulation as a feature of the language orthogonal to object orientation. The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition. The features of encapsulation are supported using classes in most object-oriented programming languages, although other alternatives also exist.

What is normalization?

In statistics and applications of statistics, normalization can have a range of meanings.[1] In the simplest cases, normalization of ratings means adjusting values measured on different scales to a notionally common scale, often prior to averaging. In more complicated cases, normalization may refer to more sophisticated adjustments where the intention is to bring the entire probability distributions of adjusted values into alignment. In the case of normalization of scores in educational assessment, there may be an intention to align distributions to a normal distribution. A different approach to normalization of probability distributions is quantile normalization, where the quantiles of the different measures are brought into alignment.

What is overfitting?

In statistics and machine learning, one of the most common tasks is to fit a "model" to a set of training data, so as to be able to make reliable predictions on general untrained data. In overfitting, a statistical model describes random error or noise instead of the underlying relationship. Overfitting occurs when a model is excessively complex, such as having too many parameters relative to the number of observations. A model that has been overfit has poor predictive performance, as it overreacts to minor fluctuations in the training data. how to avoid overfitting? cross-validation, regularization, early stopping, pruning, Bayesian priors on parameters or model comparison and more!

What is a simple linear regression?

In statistics, simple linear regression is the least squares estimator of a linear regression model with a single explanatory variable. In other words, simple linear regression fits a straight line through the set of n points in such a way that makes the sum of squared residuals of the model (that is, vertical distances between the points of the data set and the fitted line) as small as possible. minimize squared error

What's different about ES6 and Anonymous Function Expressions?

In the case of the anonymous function expression, the function is anonymous — literally, it has no name. However, in ES6, they do!!! Well, most of the time. (As of ES6, though, a lot of "anonymous" function expressions create functions with names, and this was predated by various modern JavaScript engines being quite smart about inferring names from context. In ES6, your anonymous function expression results in a function with the name boo. This is strewn throughout the spec rather than being defined in one place with a bunch of rules.)

Inflection points

Inflection points are where the function changes concavity. Since concave up corresponds to a positive second derivative and concave down corresponds to a negative second derivative, then when the function changes from concave up to concave down (or vise versa) the second derivative must equal zero at that point. So the second derivative must equal zero to be an inflection point. But don't get excited yet. You have to make sure that the concavity actually changes at that point.

How to implement inheritance in Javascript?

Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.

Invoking a Function as a Method

Invoking a Function as a Method

Invoking a Function with a Function Method

Invoking a Function with a Function Method

Invoking a Function with an object Constructor

Invoking a Function with an object Constructor

What if we invoke a function as a global function?

Invoking a function as a global function, causes the value of this to be the global object.

What will be the value of "this" inside the code block of the function if we Invoke the function as the method of an object?

Invoking a function as an object method, causes the value of this to be the object itself.

Differential calculus intuition

It answers the question how fast things are changing (instantaneous) at a certain point in time rather than across a long period of time. This is where we attempt to find the slope at a point by using a tangent line. Because we cannot find the slope at a particular point to be precise, we do this by approaching a difference of zero when finding rise over run.

why did they name this subject calculus?

It's from the Latin meaning reckon or account (like calculate), which came from using pebbles (calx) to count with.

For a sufficiently small alpha...

J(Theta) should decrease EVERY iteration

ES6: Why the hell are there classes in ES6?

JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

What do objects have in js?

JavaScript functions have properties and methods.

How does JS define classes?

JavaScript uses functions as constructors for classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person with an empty constructor. var Person = function () {};

SO*L*ID

LSP - Liskov Substitution Principle Derived classes must be substitutable by their base classes.

Learning algorithm?

Learning algorithm: Again, our goal is to find or approximate the target function, and the learning algorithm is a set of instructions that tries to model the target function using our training dataset. A learning algorithm comes with a hypothesis space, the set of possible hypotheses it can come up with in order to model the unknown target function by formulating the final hypothesis

Higher derivatives?

Let f be a differentiable function, and let f ′(x) be its derivative. The derivative of f ′(x) (if it has one) is written f ′′(x) and is called the second derivative of f. Similarly, the derivative of a second derivative, if it exists, is written f ′′′(x) and is called the third derivative of f. Continuing this process, one can define, if it exists, the nth derivative as the derivative of the (n-1)th derivative. These repeated derivatives are called higher-order derivatives. The nth derivative is also called the derivative of order n.

AJS: What is lexical scope? (Kyle Simpson)

Lexical scope is scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are authored, by you, at write time, and thus is mostly set in stone by the time the lexer processes the code.

AJS: What type of scoping rule(s) does JS have? What are the exceptions?

Lexical, exceptions being <eval> and <with>

What are the three core components of NodeJS?

Libuv, V8 Engine, C++/JS Custom Code

First FP programming language?

Lisp -- this is important because Lisp is often used as a good comparison and frequently referenced.

Haskell: What do back quotes do for operators?

Makes the operator infix

Why add methods using prototype as opposed to using this?

Methods that inherit via the prototype chain can be changed universally for all instances, for example: function Class () {} Class.prototype.calc = function (a, b) { return a + b; } // Create 2 instances: var ins1 = new Class(), ins2 = new Class(); // Test the calc method: console.log(ins1.calc(1,1), ins2.calc(1,1)); // -> 2, 2 // Change the prototype method Class.prototype.calc = function () { var args = Array.prototype.slice.apply(arguments), res = 0, c; while (c = args.shift()) res += c; return res; } // Test the calc method: console.log(ins1.calc(1,1,1), ins2.calc(1,1,1)); // -> 3, 3 ) Notice how changing the method applied to both instances? This is because ins1 and ins2 share the same calc() function. In order to do this with public methods created during construction, you'd have to assign the new method to each instance that has been created, which is an awkward task. This is because ins1 and ins2 would have their own, individually created calc() functions. Another side effect of creating methods inside the constructor is poorer performance. Each method has to be created every time the constructor function runs. Methods on the prototype chain are created once and then "inherited" by each instance. On the flip side of the coin, public methods have access to "private" variables, which isn't possible with inherited methods. var YourClass = function(){ var privateField = "somevalue"; this.publicField = "somevalue"; this.instanceMethod1 = function(){ //you may access both private and public field from here: //in order to access public field, you must use "this": alert(privateField + "; " + this.publicField); }; } YourClass.prototype.instanceMethod2 = function(){ //you may access only public field 2 from this method, but not private fields: alert(this.publicField); //error: drawaback of prototype methods: alert(privateField); }; When you define methods via prototype, they are shared among all YourClass instances. As a result the total size of such instances is less than if you define methods in constructor; There are tests that show how method definition via prototype decrease the total size of html page and as a result a speed of its loading. another advantage of methods, defined via prototype - is when you use inherited classes, you may override such methods and in the overriden method of the derived class you may invoke the method of base class with the same name, but with methods defined in constructor, you cannot do this.

Model definition?

Model: In machine learning field, the terms hypothesis and model are often used interchangeably. In other sciences, they can have different meanings, i.e., the hypothesis would be the "educated guess" by the scientist, and the model would be the manifestation of this guess that can be used to test the hypothesis.

Alt+Click

Multiple Cursor or Multiline edit

Matrix scalar multiplication rules?

Multiply the scalar against each number in the matrix.

var foo = function bar() { ... } --> what type of function?

NAMED FUNCTION EXPRESSION

What are the two types of Exports?

Named exports: export { myFunction }; // exports a function declared earlier export const foo = Math.sqrt(2); // exports a constant Default exports *(only one per script):* export default function() {} // or 'export default class {}' // there is no semi-colon here

Ctrl+B (⌘B) or Ctrl+Click (⌘-Click)

Navigate to declaration: Ctrl+B (⌘B) or Ctrl+Click (⌘-Click) You can instantly jump to the function or method definition or a variable, class, component, or CSS style declaration: just Ctrl-click on it, or place the caret on it and press Ctrl+B. This shortcut can also help you jump to the referenced file or imported module:

Does Javascript have function overloading?

No, you cannot double-define functions in the same scope.

Can you assign to a const after declaring the const?

No. A const promises that we won't change the value of the variable for the rest of its life and this is considered a reassignment or rewrite.

Node.appendChild()

Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

Standardization vs normalization

Normalization rescales the values from to a range of [0,1]. This might useful in some cases where all parameters need to have the same positive scale, but outliers from data set are lost. Xchanged = (X - Xmin)/(Xmax-Xmin) Standardization rescales data to have a mean of 0 and standard deviation of 1 (unit variance). Xchanged = (x-mean)/sd For most applications standardization is recommended. In the business world, "normalization" typically means that the range of values are "normalized to be from 0.0 to 1.0". "Standardization" typically means that the range of values are "standardized" to measure how many standard deviations the value is from its mean. However, not everyone would agree with that. It's best to explain your definitions before you use them. In any case, your transformation needs to provide something useful.

is "this" a variable? can its value be changed?

Note that this is not a variable. It is a keyword. You cannot change the value of this.

S*O*LID

OCP - Open Closed Principle (Open for extension, closed for modification)

Bitwise Swap Intuition x = x xor y y = x xor y x = x xor y

On line 1 we combine x and y (using XOR) to get this "hybrid" and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again. So, this is exactly what we do on line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into y, so now they have swapped. On the last line, x still has the hybrid value. We XOR it yet again with y (now with x's original value) to remove all traces of x out of the hybrid. This leaves us with y, and the swap is complete! *The mathematics are fairly simple and work because XOR has a useful property, when you XOR A and B, you get a value C. If you XOR C and A you'll get B back, if you XOR C and B you'll get A back.*

What is the essential structure of an ng2 Component?

One or more import statements to reference the things we need. A @Component decorator that tells Angular what template to use and how to create the component. A component class that controls the appearance and behavior of a view through its template.

Router

Our server will need to answer differently to requests, depending on which URL the request was asking for, thus we need some kind of router in order to map requests to request handlers

Object.prototype.__proto__

Points to the object which was used as prototype when the object was instantiated.

Polymorphism defintiion

Poly means "many" and morphism means "forms". Different classes might define the same method or property.

Prototype-based programming

Prototype-based programming is an OOP model that doesn't use classes, but rather it first accomplishes the behavior of any class and then reuses it (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)

pandas.DataFrame.loc

Purely label-location based indexer for selection by label. .loc[] is primarily label based, but may also be used with a boolean array. Allowed inputs are: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. A slice object with labels, e.g. 'a':'f' (note that contrary to usual python slices, both the start and the stop are included!). A boolean array. A callable function with one argument (the calling Series, DataFrame or Panel) and that returns valid output for indexing (one of the above) .loc will raise a KeyError when the items are not found.

When were React and ReactDOM split?

React and ReactDOM were only recently split into two different libraries. Prior to v0.14, all ReactDOM functionality was part of React. This may be a source of confusion, since any slightly dated documentation won't mention the React / ReactDOM distinction. As the name implies, ReactDOM is the glue between React and the DOM. Often, you will only use it for one single thing: mounting with ReactDOM.render(). Another useful feature of ReactDOM is ReactDOM.findDOMNode() which you can use to gain direct access to a DOM element. (Something you should use sparingly in React apps, but it can be necessary.) If your app is "isomorphic", you would also use ReactDOM.renderToString() in your back-end code. For everything else, there's React. You use React to define and create your elements, for lifecycle hooks, etc. i.e. the guts of a React application. The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilised in web and mobile apps. ReactDOM functionality is utilised only in web apps. [UPDATE: Upon further research, it's clear my ignorance of React Native is showing. Having the React package common to both web and mobile appears to be more of an aspiration than a reality right now. React Native is at present an entirely different package.] See the blog post announcing the v0.14 release: https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html

Regression vs Classification?

Regression: the output variable takes continuous values. - Price of house given a size. Classification: the output variable takes class labels, or discrete value output - Breast cancer, malignant or benign? Almost like quantitative vs categorical

The callback pattern for async code is more... The event pattern for async code is more...

Request/Reply -- no results until all results -- Publish/Subscribe -- act on results as they come in -- so the .on is kind of like a subscription when an event occurs.

Object.prototype.hasOwnProperty()

Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.

Object.prototype.isPrototypeOf()

Returns a boolean indication whether the specified object is in the prototype chain of the object this method is called upon.

Separation of concerns - Single Responsibility Principle

SOC: Divide your app into distinct features with as little overlap in functionality as possible. SRP: The single responsibility principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Robert C. Martin expresses the principle as follows:[1] A class should only have one reason to change.

*S*OLID

SRP - Single Responsibility Principle (https://www.youtube.com/watch?v=Ib-gxqF6Wuk)

The sum of an arithmetic sequence?

S_n = (n(a_1 + a_n))/2

Sum of geometric series?

S_n = a_1(1-r^n)/(1-r)

Sum of an arithmetic sequence?

S_n = terms(a_1 + a_n) / 2

Double Shift

Search everywhere

@angular/upgrade

Set of utilities for upgrading Angular 1 application2

What is the difference between a deep copy and a shallow copy?

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Why is the following true? 2(x + y) = 2x + 2y

Since they distributed through the parentheses, this is true by the Distributive Property.

Object.prototype.constructor

Specifies the function that creates an object's prototype.

What are all of String.prototype properties?

String.prototype.constructor - specifies the function that creates an object's prototype. String.prototype.length, N (Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of length. These properties are read-only.), constructor

Supervised learning

Supervised learning is a type of machine learning algorithm that uses a known dataset (called the training dataset) to make predictions. The training dataset includes input data and response values. From it, the supervised learning algorithm seeks to build a model that can make predictions of the response values for a new dataset. A test dataset is often used to validate the model. Using larger training datasets often yield models with higher predictive power that can generalize well for new datasets. Called Supervised learning BECAUSE the data is labeled with the "correct" responses.

Target Function definition?

Target function: In predictive modeling, we are typically interested in modeling a particular process; we want to learn or approximate a particular function that, for example, let's us distinguish spam from non-spam email. The target function f(x) = y is the true function f that we want to model. The target function is the (unknown) function which the learning problem attempts to approximate.

Synonym for output variable?

Targets

ES6: Template Literals

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), the template string is called "tagged template literal". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting.

The Node - King Analogy

That's right, everything runs in parallel, except your code. To understand that, imagine your code is the king, and node is his army of servants. The day starts by one servant waking up the king and asking him if he needs anything. The king gives the servant a list of tasks and goes back to sleep a little longer. The servant now distributes those tasks among his colleagues and they get to work. Once a servant finishes a task, he lines up outside the kings quarter to report. The king lets one servant in at a time, and listens to things he reports. Sometimes the king will give the servant more tasks on the way out. Life is good, for the king's servants carry out all of his tasks in parallel, but only report with one result at a time, so the king can focus. *

Distributive Property

The Distributive Property is easy to remember, if you recall that "multiplication distributes over addition". Formally, they write this property as "a(b + c) = ab + ac". In numbers, this means, that 2(3 + 4) = 2×3 + 2×4. Any time they refer in a problem to using the Distributive Property, they want you to take something through the parentheses (or factor something out); any time a computation depends on multiplying through a parentheses (or factoring something out), they want you to say that the computation used the Distributive Property.

Node EventEmitter class

The EventEmitter class is used as a construct to help us build the publish/subscribe pattern of the event model of writing async code. the subscriber: emitter.on(event, listener); the publisher: emitter.emit(event, [args]);

EventTarget.addEventListener()

The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest). target.addEventListener(type, listener[, options]); target.addEventListener(type, listener[, useCapture]); type A string representing the event type to listen for. listener The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or simply a JavaScript function.

HTTP Server

The HTTP Server "serves" content located in the server, this includes HTML, images, flash and any file related. The server is not restricted to server static content, it also serves dynamic content generated on fly from a database or similar. We want to serve web pages, therefore we need an HTTP server

Node.appendChild()

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node). Returns the appended child. var addCourseToDom = function addCourseToDom(course){ var li = document.createElement("li"); var text = document.createTextNode(course.title); li.appendChild(text); var placeToAdd = document.getElementById("courses"); placeToAdd.appendChild(li); return "added " + li; }

Node.insertBefore()

The Node.insertBefore() method inserts the specified node before the reference node as a child of the current node.

The NodeJS Docs have stability indexes. What does this mean?

The Node.js API is still somewhat changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upon, that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned. Stability 0 - 3. Only use features from Stability 2-3 if you really want to have consistent and compatible code

Object.create

The Object.create() method creates a new object with the specified prototype object and properties. Object.create(proto[, propertiesObject]) // Example where we create an object with a couple of sample properties. // (Note that the second parameter maps keys to *property descriptors*.) o = Object.create(Object.prototype, { // foo is a regular 'value property' foo: { writable: true, configurable: true, value: 'hello' }, // bar is a getter-and-setter (accessor) property bar: { configurable: false, get: function() { return 10; }, set: function(value) { console.log('Setting `o.bar` to', value); } /* with ES5 Accessors our code can look like this get function() { return 10; }, set function(value) { console.log('setting `o.bar` to', value); } */ } });

Object.defineProperty() Needs MUCH MORE ELABORATION

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

Object.freeze()

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

String.prototype[@@iterator]()

The [@@iterator]() method returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value. string[Symbol.iterator]

String.prototype.anchor()

The anchor() method creates an <a> HTML anchor element that is used as a hypertext target.

String.prototype.charAt()

The charAt() method returns the specified character from a string.

String.prototype.charCodeAt()

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index (the UTF-16 code unit matches the Unicode code point for code points representable in a single UTF-16 code unit, but might also be the first code unit of a surrogate pair for code points not representable in a single UTF-16 code unit, e.g. Unicode code points > 0x10000). If you want the entire code point value, use codePointAt().

Cocktail party effect/problem

The cocktail party effect is the phenomenon of being able to focus one's auditory attention on a particular stimulus while filtering out a range of other stimuli, much the same way that a partygoer can focus on a single conversation in a noisy room. Example of source separation.

Is the code in a function executed when the function is defined?

The code in a function is not executed when the function is defined. It is executed when the function is invoked.

String.prototype.codePointAt()

The codePointAt() method returns a non-negative integer that is the Unicode code point value.

String.prototype.concat()

The concat() method combines the text of two or more strings and returns a new string.

Abstraction definition

The conjunction of an object's complex inheritance, methods, and properties must adequately reflect a reality model.

What is the equivalent of a constructor in JS?

The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript the function serves as the constructor of the object, therefore there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation. The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.

ES6: What there's a constructor keyword now?

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

What does the derivative of a function tell us?

The derivative of a function of a real variable measures the sensitivity to change of a quantity (a function value or dependent variable) which is determined by another quantity (the independent variable). Derivatives are a fundamental tool of calculus. For example, the derivative of the position of a moving object with respect to time is the object's velocity: this measures how quickly the position of the object changes when time is advanced. The derivative of a function of a single variable at a chosen input value, when it exists, is the slope of the tangent line to the graph of the function at that point. The tangent line is the best linear approximation of the function near that input value. For this reason, the derivative is often described as the "instantaneous rate of change", the ratio of the instantaneous change in the dependent variable to that of the independent variable.

What happens if you initialize a parameter at a local minimum and attempt to use gradient descent on it?

The derivative turns out to be zero because the tangent is a flat line meaning that regardless of alpha it is multiplied by zero, indicating no change.

String.prototype.endsWith()

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate. str.endsWith(searchString[, position])

what is "main" in NPM package.json?

The entry point of the module. It is what is executed when someone requires the module.

AJS: Eval function? What's it do? Why is it good or bad?

The eval() function evaluates JavaScript code represented as a string. It's a way to cheat Lexical Scope "The eval(..) function in JavaScript takes a string as an argument, and treats the contents of the string as if it had actually been authored code at that point in the program. " Excerpt From: Riley Gelwicks. "You Dont Know JS by Kyle Simpson." iBooks. "function foo(str, a) { eval( str ); // cheating! console.log( a, b ); } var b = 2; foo( "var b = 3;", 1 ); // 1, 3" Excerpt From: Riley Gelwicks. "You Dont Know JS by Kyle Simpson." iBooks.

ES6: export

The export statement is used to export functions, objects or primitives from a given file (or module). export { name1, name2, ..., nameN }; export { variable1 as name1, variable2 as name2, ..., nameN }; export let name1, name2, ..., nameN; // also var export let name1 = ..., name2 = ..., ..., nameN; // also var, const export default expression; export default function (...) { ... } // also class, function* export default function name1(...) { ... } // also class, function* export { name1 as default, ... }; export * from ...; export { name1, name2, ..., nameN } from ...; export { import1 as name1, import2 as name2, ..., nameN } from ...;

Where does fullName function belong to?

The function belongs to the object.

Variables that are created within code and not within a function is always attached to...

The global object

String.prototype.includes()

The includes() method determines whether one string may be found within another string, returning true or false as appropriate. str.includes(searchString[, position])

String.prototype.indexOf()

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found. str.indexOf(searchValue[, fromIndex])

what does jQuery() return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example). More importantly, you can also apply jQuery functions against all the selected elements. The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().

String.prototype.lastIndexOf()

The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found. str.lastIndexOf(searchValue[, fromIndex])

String.prototype.link()

The link() method creates a string representing the code for an <a> HTML element to be used as a hypertext link to another URL. str.link(url)

String.prototype.localeCompare()

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation dependent. referenceStr.localeCompare(compareString[, locales[, options]])

String.prototype.match()

The match() method retrieves the matches when matching a string against a regular expression. str.match(regexp)

What is [[Prototype]]?

The mechanism by which objects can point to their successors. Basically a reference to another object. Written in the spec, not public

What is private about a nested function?

The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

What is a nodeType in regards to DOM nodes?

The nodeType property can be used to distinguish different kind of nodes, such that elements, text and comments, from each other. -- basically a number system for the types of nodes there are.

String.prototype.normalize()

The normalize() method returns the Unicode Normalization Form of a given string (if the value isn't a string, it will be converted to one first). str.normalize([form])

Matrix multiplication?

The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix. And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix. remember matrix multiplication does not have the commutative property. Use the Dot Product to get each value for matrix multiplication.

What is the difference between Object.create() and new?

The object used in Object.create actually forms the prototype of the new object, whereas in the new Function() form, the declared properties/functions do not form the prototype. With constructor functions, the newly created object inherits from the constructor's prototype when using new. var o = new SomeConstruct(); --> inheriting from SomeConstructor.prototype.

What is the only difference between apply() and call() methods?

The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array.

Dependencies vs devdependencies in package.json?

The packages listed under dependencies are essential to running the application. The devDependencies are only necessary to develop the application. They can be excluded from production installations as in this example: $npm install my-application --production

Partial derivative notation?

The partial derivative of z with respect to x. Remember that the partial derivative is a derivative of one variable wiht others held in constant.

Does a declared function like the previous one belong to any object?

The previous function does not belong to any object. But in JavaScript there is always a default global object.

String.prototype.repeat()

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. str.repeat(count)

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. str.replace(regexp|substr, newSubStr|function)

String.prototype.search()

The search() method executes a search for a match between a regular expression and this String object. str.search(regexp)

String.prototype.slice()

The slice() method extracts a section of a string and returns a new string. str.slice(beginSlice[, endSlice])

String.prototype.split()

The split() method splits a String object into an array of strings by separating the string into substrings. str.split([separator[, limit]])

ES6: Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected. it is practical for fixing cases where you have to use .apply in "hacky" sort of ways particularly when you are manipulating or using the <arguments> object and want to use arguments as an array.

String.prototype.startsWith()

The startsWith() method determines whether a string begins with the characters of another string, returning true or false as appropriate. str.startsWith(searchString[, position])

String.fromCharCode()

The static String.fromCharCode() method returns a string created by using the specified sequence of Unicode values.

String.fromCodePoint()

The static String.fromCodePoint() method returns a string created by using the specified sequence of code points.

String.raw()

The static String.raw() method is a tag function of template literals, similar to the r prefix in Python or the @ prefix in C# for string literals (yet there is a difference: see explanations in this issue). It's used to get the raw string form of template strings (that is, the original, uninterpreted text). String.raw(callSite, ...substitutions) String.raw`templateString`

String.prototype.substr()

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters. str.substr(start[, length])

String.prototype.substring()

The substring() method returns a subset of a string between one index and another, or through the end of the string. str.substring(indexStart[, indexEnd])

What is SSE?

The sum of squared error

What is "this" this time?

The thing called this, is the object that "owns" the JavaScript code. In this case the value of this is myObject.

What is the value of "this" in a function constructor?

The this keyword in the constructor does not have a value. The value of this will be the new object created when the function is invoked.

String.prototype.toLocaleLowerCase()

The toLocaleLowerCase() method returns the calling string value converted to lower case, according to any locale-specific case mappings. str.toLocaleLowerCase()

String.prototype.toLocaleUpperCase()

The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings. str.toLocaleUpperCase()

String.prototype.toLowerCase()

The toLowerCase() method returns the calling string value converted to lowercase. str.toLowerCase()

String.prototype.toUpperCase()

The toUpperCase() method returns the calling string value converted to uppercase. str.toUpperCase()

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). str.trim()

Tsconfig.json?

The tsconfig.json file specifies the root files and the compiler options required to compile the project.

What does the URL module do?

The url module provides methods which allow us to extract the different parts of a URL (like e.g. the requested path and query string), and querystring can in turn be used to parse the query string for request parameters:

String.prototype.valueOf()

The valueOf() method returns the primitive value of a String object. str.valueOf() The valueOf() method of String returns the primitive value of a String object as a string data type. This value is equivalent to String.prototype.toString(). This method is usually called internally by JavaScript and not explicitly in code.

AJS: <with> keyword

The with statement extends the scope chain for a statement.

AJS: With function?

The with statement extends the scope chain for a statement. One way to create dynamic scope "with is typically explained as a short-hand for making multiple property references against an object without repeating the object reference itself each time." Excerpt From: Riley Gelwicks. "You Dont Know JS by Kyle Simpson." iBooks.

Associative Property

The word "associative" comes from "associate" or "group";the Associative Property is the rule that refers to grouping. For addition, the rule is "a + (b + c) = (a + b) + c"; in numbers, this means 2 + (3 + 4) = (2 + 3) + 4. For multiplication, the rule is "a(bc) = (ab)c"; in numbers, this means 2(3×4) = (2×3)4. Any time they refer to the Associative Property, they want you to regroup things; any time a computation depends on things being regrouped, they want you to say that the computation uses the Associative Property.

Polynomial functions

These functions consist of one or more terms of variables with whole number exponents. (Whole numbers are positive integers and zero.) All such functions in one variable (usually x) can be written in this type of format: constant, linear, quadratic, cubic, quartic, quintic

3D Surface Plot - how can it be used to plot the cost function?

Theta 0 and Theta 1 in a univariate linear regression can be plotted on the x and y axes. the Z axis will indicate the actual cost

What does this return? function myFunction() { return this; } myFunction();

This example returns the window object as the value of this: // Will return the window object [object Window]

is it a good practice to invoke a function like this? window.myFunction(10, 2);

This is a common way to invoke a JavaScript function, but not a good practice in computer programming. Global variables, methods, or functions can easily create name conflicts and bugs in the global object.

Request Handlers

To fulfill the requests that arrived at the server and have been routed using the router, we need actual request handlers

AJS: What is the official transpiler for TC39?

Traceur maintained by Google. But it only features ES.next features and not future feature sets like Babel does.

Training sample definition?

Training sample: A training sample is a data point x in an available training set that we use for tackling a predictive modeling task. For example, if we are interested in classifying emails, one email in our dataset would be one training sample. Sometimes, people also use the synonymous terms training instance or training example.

True or false? In a nested function, the inner function has access to the outer function's variables and arguments

True

AJS: What feature had block scope back in ES3?

Try and Catch Blocks. Specifically, just the catch blocks. Unfortunately, JSLint and JSHint and many other linters don't pick up on this and may throw errors.

Matrix Addition & Subtraction rules?

Two matrices may be added or subtracted only if they have the same dimension; that is, they must have the same number of rows and columns. Addition or subtraction is accomplished by adding or subtracting corresponding elements. For example, consider matrix A and matrix B.

ES6: Why is the scope of the arrow function particularly useful?

Typically, Javascript functions create new scopes with a new this binding. Arrow functions support "lexical" this meaning that a new "this" is not binded, instead it uses the "This" of the function that encloses it. Problem: function Person() { // The Person() constructor defines `this` as an instance of itself. this.age = 0; setInterval(function growUp() { // In non-strict mode, the growUp() function defines `this` // as the global object, which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } var p = new Person(); Old fix: function Person() { var self = this; // Some choose `that` instead of `self`. // Choose one and be consistent. self.age = 0; setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); }

AJS: What's the difference between undeclared and undefined?

Undefined IS a value -- empty placeholder -- indicates that there was a declared variable. Undeclared means it hasnt been registered in the scope when the compiler runs through in phase 1.

Unsupervised learning

Unsupervised learning is the machine learning task of inferring a function to describe hidden structure from unlabeled data. Since the examples given to the learner are unlabeled, there is no error or reward signal to evaluate a potential solution. This distinguishes unsupervised learning from supervised learning and reinforcement learning. Unsupervised learning is closely related to the problem of density estimation in statistics.[1] However unsupervised learning also encompasses many other techniques that seek to summarize and explain key features of the data.

What to do when J(Theta) is moving up and down in waves ?

Use a smaller Alpha!!

RequireJS

Used mainly in the browser. Packages everything into file and helps you manage how JS is loading.

AJS: IIFE mainstream use?

Used to hide things in anonymous functions within a function expression. The compiler will treat it as a function expression. Recommended to name IIFE for stack tracing purposes. Because the point of the parens or coercing operators is to disambiguate between function expressions and function declarations, they can be omitted when the parser already expects an expression (but please see the

What might happen if we use the window object as a variable?

Using the window object as a variable can easily crash your program.

Primitive parameters are passed to to functions by...

Value. the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. (If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:)

Alt+Enter or ⌥-Enter

WebStorm has a great number of intentions to help you quickly apply fixes, generate code, or change some project settings. Place the caret on highlighted or underlined code, and press Alt+Enter to see the list of available intention actions. For example:

Webpack?

Webpack is a powerful module bundler. A bundle is a JavaScript file that incorporate assets that belong together and should be served to the client in a response to a single file request. A bundle can include JavaScript, CSS styles, HTML, and almost any other kind of file. Webpack roams over your application source code, looking for import statements, building a dependency graph, and emitting one (or more) bundles. With plugin "loaders" Webpack can preprocess and minify different non-JavaScript files such as TypeScript, SASS, and LESS files. We determine what Webpack does and how it does it with a JavaScript configuration file, webpack.config.js.

What does this refer to if a function is called without an owner object?

When a function is called without an owner object, the value of this becomes the global object.

Haskell: What character denotes function application?

Whitespace

Does resetting the prototype constructor in a subclass matter?

Yes and no. In ES5 and earlier, JavaScript itself didn't use constructor for anything. It defined that the default object on a function's prototype property would have it and that it would refer back to the function, and that was it. Nothing else in the specification referred to it at all. That changed in ES2015 (ES6), which started using it in relation to inheritance hierarchies. For instance, Promise#then uses the constructor property of the promise you call it on (via SpeciesConstructor) when building the new promise to return. It's also involved in subtyping arrays. Note that in the places the ES2015 spec uses it, it's set automatically for you (you can't subclass Promise or arrays except via class, and class handles it for you). Outside of the language itself, sometimes people would use it when trying to build generic "clone" functions or just generally when they wanted to refer to what they believed would be the object's constructor function. My experience is that using it is rare, but sometimes people do use it. It's there by default, you only need to put it back when you replace the object on a function's prototype property: Student.prototype = Object.create(Person.prototype); If you don't do this: Student.prototype.constructor = Student; ...then Student.prototype.constructor inherits from Person.prototype which (presumably) has constructor = Person. So it's misleading. It's okay if nothing in your code (or library code you use) uses it. I've always ensured it was correctly wired up. Of course, with ES2015 (aka ES6)'s class keyword, most of the time we would have used it, we don't have to anymore, because it's handled for us when we do class Student extends Person { }

What does module.exports do?

You assign variables that are to be exposed to other files as a module to it. one.js: var doIt = function(i, callback){///} var count = 2; module.exports.doIt = doIt; module.exports.foo = 'bar'; two.js: var one = require('./one'); one.doit(23, function (err, result){ // } console.log(one.foo); *Notice the multiple assignments to module.exports* *Notice how you import the FILE as a module due to the 1 to 1 correspondenceness of Node though you can import just single properties *

Haskell: Select 2nd element of a list

[1,2,3,4,5] !! 2 note that this is not a constant time operation because lists are not arrays in Haskell

What is the dunder proto?

__proto__

What is left associativity?

a Q b Q c If Q is left associative, then it evaluates as (a Q b) Q c And if it is right associative, then it evaluates as a Q (b Q c)

How to swap two values a,b using bits?

a ^= b; b ^= a; a ^= b; OR (easier to memorize) x = x xor y y = x xor y x = x xor y

Derivatives?

a derivative is the rate of change of a function with respect to changes in its variable

function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); Value of fn_inside?

a function that adds 3 to whatever you give it.

Clustering

a method of unsupervised learning - a good way of discovering unknown relationships in datasets. Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). It is a main task of exploratory data mining, and a common technique for statistical data analysis, used in many fields, including machine learning, pattern recognition, image analysis, information retrieval, bioinformatics, data compression, and computer graphics. Cluster analysis itself is not one specific algorithm, but the general task to be solved. It can be achieved by various algorithms that differ significantly in their notion of what constitutes a cluster and how to efficiently find them. Popular notions of clusters include groups with small distances among the cluster members, dense areas of the data space, intervals or particular statistical distributions. Clustering can therefore be formulated as a multi-objective optimization problem. The appropriate clustering algorithm and parameter settings (including values such as the distance function to use, a density threshold or the number of expected clusters) depend on the individual data set and intended use of the results. Cluster analysis as such is not an automatic task, but an iterative process of knowledge discovery or interactive multi-objective optimization that involves trial and failure. It is often necessary to modify data preprocessing and model parameters until the result achieves the desired properties.

Nth term of geometric series?

a_n = a_1 * r^(n-1)

Find nth term of an arithmetic sequence?

a_n = a_1 + (n-1)d

Nth term of arithmetic sequence?

a_n = a_1 + (n-1)d

unshift()

adds given value to the front of an array array will get bigger

Haskell: :t length returns length :: [a] -> Int => wtf is the [a]?

alpha type, meaning its polymorphic

x^i_j notation in ML means?

an index into a training set for the ITH training example and JTH feature (input variable)

List all the properties of the arguments keyword

arguments.callee, arguments.length, arguments[@@iterator]. (arguments.caller is deprecated due to security vulnerabilities)

multivariate linear regression

ask: why is the notation shorter and what does that convenience notation indicate?

What do both of the methods have to have?

both methods must have the owner object as first parameter.

What are the 2 predefined function methods by which we can invoke a function?

call() and apply() are predefined JavaScript function methods.

character literals in C++

completely distinct from string literals - and always enclosed in single quotes whereas strings are always enclosed in double quotes.

console.log("string text line 1\n"+ "string text line 2"); rewrite this using ES6 template literals

console.log(`string text line 1 string text line 2`);

Import a constructor from a module named Bar

const Bar = require('bar'); notice the casing

Import a single property bar of a module named foo into a file

const bar = require('foo').bar;

Import a module foo in the current directory

const foo = require('./foo');

Import a node module named foo into a file

const foo = require('foo');

contains as a member, "ni"

why use features that are on a similar scale?

contour plots with differently scaled features will be extremely thin or extremely fat resulting in a very slow gradient descent (convergence is slower) get them to a -1 <= x <= 1 scale. poorly scaled is too large -100 to 100 or -0.00001 or 0.00001

How to make sure gradient descent is working properly?

create an automatic convergence test - declare convergence based on amount of decrease of J(Theta) plot on graph, y axis being J and axis being number of iterations.

doctype

declaration of standards compliance

AMD define function?

define(moduleId, dependencies, definitionFunc); define(dependencies, definitionFunc); -- preferred anonymous modules typically defaults module to filename // MyApp/MyModule: define( ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'], function (modA, modB, modC) { var myModule = { doStuff: function() { ... } } return myModule; } );

Erase until and including character

df charactef

body

document data displayed to users by client browser

head

document metadata used by browsers and search engines

Erase until and excluding character

dt character

In Javascript/jQuery what does (e) mean?

e is the short var reference for event object which will be passed to event handlers. The event object essentially has lot of interesting methods and properties that can be used in the event handlers. jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.

ATTRIBUTE_NODE example?

e.g. class="funEdges"

DOCUMENT_FRAGMENT_NODE

e.g. document.createDocumentFragment() The DocumentFragment interface represents a minimal document object that has no parent. It is used as a light-weight version of Document to store well-formed or potentially non-well-formed fragments of XML. DocumentFragments allow developers to place child elements onto an arbitrary node-like parent, allowing for node-like interactions without a true root node. Doing so allows developers to produce structure without doing so within the visible DOM -- an increase of speed is the true advantage. Let me show you how DocumentFragments are used!

CommonJS fixes what problem

encapsulation of modules and ability to connect with other modules.

AJS: Two keywords that cheat lexical scope?

eval, with

Self contained modules

everything with my module is in my module no global variables if a module manages more than one thing it should be broken up

What are Node's built in modules?

exports._builtinLibs = ['assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'string_decoder', 'tls', 'tty', 'url', 'util', 'vm', 'zlib'];

Quadratic function form?

f(x) = ax2 + bx + c

∀ meaning?

for all..

why use Array.prototype.forEach when iterating with side effects?

forEach has an "undefined" return value always. MAP, being a functional programming method is much better suited when creating a pure function. For non-pure iterative functions forEach makes sense. The predicate here should produce a side effect. immutability is promoted with FP and can be exhibited when using map. That is map doesnt mutate the given array, only creates a new array as a copy of the given and then modifies it. example: function logValue(v) {console.log(v);} forEach(arr,logValue);

Import the linear regression class from Scikit

from sklearn.linear_model import LinearRegression

Explain Function.prototype.apply()

fun.apply(thisArg, [argsArray]) thisArg The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. argsArray An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information.

AJS: Why use .call(this) for IIFE's?

function Foo() { (function () { console.log(this); // > Foo }).call(this); (function () { console.log(this); // > undefined in strict mode, or Window in non strict mode })(); } var bar = new Foo; Also here (Non-iife): function identify() { return this.name.toUpperCase(); } function speak() { var greeting = "Hello, I'm " + identify.call(this); console.log(greeting); } var me = { name: "Kyle" } identify.call(me)

Haskell: What operator has highest priority?

function application

map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]); --> function expression or declaration?

function expression

Find the odd int - Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times.

function findOdd(A) { var searched = []; for (let i = 0; i < A.length; i++){ var index = searched.findIndex((val) => A[i] ===val[0]); if (index === -1){ var pair = []; pair.push(A[i]); //element pair.push(1); //count searched.push(pair); } else { searched[index][1]++; } }; console.log(searched); for (let i = 0; i < searched.length; i++){ if (searched[i][1] % 2 === 1) return searched[i][0]; } return 0; }

Write function map(f,a) {};

function map(f,a){ var result =[], i; for (i = 0; i != a.length; i++){ result[i] = f(a[i]); } return result; }

an example of apply()

function myFunction(a, b) { return a * b; } myArray = [10,2]; myFunction.apply(myObject, myArray); // Will also return 20

example of call()

function myFunction(a, b) { return a * b; } myFunction.call(myObject, 10, 2); // Will return 20

Haskell: double colon <::> means

has the type <type>

Kyle Simpson's public API classic Module way?

have a variable called publicAPI that is returned as an object. it holds a reference this way and is clear on what is happening. this way you can modify at runtime. whereas if you had an anonymous return value you cannot do so.

select()

highlights text in the textarea object

Privileged vs Private vs Public

http://javascript.crockford.com/private.html Public function Constructor(...) { this.membername = value; } Constructor.prototype.membername = value; Private function Constructor(...) { var that = this; var membername = value; function membername(...) {...} } Note: The function statement function membername(...) {...} is shorthand for var membername = function membername(...) {...}; Privileged function Constructor(...) { this.membername = function (...) {...}; }

How do event handlers work?

http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649 it uses a queue - event loop other systems often use the polling mechanism and/or observer pattern

How to check if the nth bit is set?

if (x & (1 << n)) { //set } else { //not-set }

How many ways can js functions be evoked?

in 4 different ways.

Get Max Int (Bit Ops)

int maxInt = ~(1 << 31); int maxInt = (1 << 31) - 1; int maxInt = (1 << -1) - 1;

Get Min Int (Bit Ops)

int minInt = 1 << 31; int minInt = 1 << -1;

How to detect if two integers have opposite signs?

int x, y; // input values to compare signs bool f = ((x ^ y) < 0); // true iff x and y have opposite signs

is in, element of..

What is the value of "this" when used in a function?

it is the object that "owns" the function.

What does J(Theta) increasing tell you about ur gradient descent?

it's not working lol. use a bigger alpha. on the other end if you use too big of an alpha you'll end up with a bowl shaped curve and you might be moving farther away from convergence.

jQuery

javascript library

What is a lambda expression?

lambda expression in computer programming, also called anonymous function, a function (or a subroutine) defined, and possibly called, without being bound to an identifier Lambda Expressions are nameless functions given as constant values. They can appear anywhere that any other constant may, but are typically written as a parameter to some other function. The canonical example is that you'll pass a comparison function to a generic "sort" routine, and instead of going to the trouble of defining a whole function (and incurring the lexical discontinuity and namespace pollution) to describe this comparison, you can just pass a lambda expression describing the comparison. HOWEVER, this misses one of the most important features of Lambda Expressions, which is that they execute in the context of their appearance. Therefore, they can use the values of the variables that are defined in that context. This differentiates function-pointers from true lambda expressions. In languages supporting mutable variables, proper lambda expressions offer the power change the values of those variables. Lambda expressions are rooted in lambda calculus.

ES6: This is used to work around the <this> bindings in JS What ES6 feature fixes this? and how can it be rewritten? let sum = function(){ return Array.prototype.reduce.call(arguments,(prev,curr) => {prev+curr}); } sum(2,3,4,5);

let sum = function(...args){ return args.reduce((prev,curr) => prev + curr); }

What is libuv?

libuv is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it's also used by Luvit, Julia, pyuv, and others.

Haskell: convention meaning: xs, ns, nss

list of type s, list of type n, list of lists of type s

lowercase letter convention in reference to matrices?

lowercase indicates vectors, uppercase indicates matrices

Export a module that sums up the area of a square

module.exports = (width) => { return { area: () => width * width }; }

Classic Module Pattern characteristics

must be an IIFE or an outer function that gets executed. second characteristic, one or more functions that get returned from the function call that have a closure over the inner private scope.

is myFunction() and window.myFunction() different?

myFunction() and window.myFunction() is the same function:

What is the owner of the fullName function?

myObject is the owner of the function.

What is a zero matrix?

n mathematics, particularly linear algebra, a zero matrix or null matrix is a matrix with all its entries being zero. Acts as the additive identity.

Haskell: What does null do

null checks if a list is empty. If it is, it returns True, otherwise it returns False. Use this function instead of xs == [] (if you have a list called xs)

How to clear a bit

number &= ~(1 << x);

How to toggle a bit?

number ^= 1 << x;

How to set any bit?

number |= 1 << x;

SSE formula?

observation - mean for each observation squared.

React.createClass accepts?

one argument, an object of which the only property required is the render function

function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); result = fn_inside(5); result1 = outside(3)(5); Explain how result1 returns its value.

outside(3) returns a function that adds 3 to whatever it is given because of the closure. That is, the inside function has access to the arguments and variables of the outside function. Thus, when outside(3) returns it calls the 'add 3 to whatever' function with the value (5) thus returning 8. (Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible. This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.)

∂ meaning?

partial, often used for partial differentials

What is the equivalent to the global object, Window, in Node?

process

What are the mutative array functions in Javascript?

push, pop, shift, unshift, sort, reverse, splice and delete (kind of).

push()

pushes an item onto the end of an array

What does theta typically represent in stat/ML?

quite often θ stands for the set of parameters of a distribution.

Definition of stochastic?

randomly determined; having a random probability distribution or pattern that may be analyzed statistically but may not be predicted precisely.

replace()

receives 2 arguments, first the string to be replaced, then the replacement text

hypothesis model

remember that the HYPOTHESIS MODEL or SET is what is depicted with h(theta)

shift()

removes the first position of an array and returns it

pop()

removes the last position of an array and returns it

Using RequireJS show how to import a module in AMD

require(['calculator/add'], function (add){ console.log(add(1,6)); });

What are the ways to do character access in JS?

return 'cat'.charAt(1); // returns "a" return 'cat'[1]; // returns "a"

getDay()

returns day of the week

getTime()

returns milliseconds since 1970

getDate()

returns the calendar day number

Document.querySelector(String selector)

returns the first element node within the document in document order that matches the specified selectors.

valueOf()

returns the primitive value of the String object

html

root element

How are matrices denoted? Columns then rows or rows then columns?

rows x columns

search()

searches a string for text and returns an index position if found

match()

similar to search, but sends back array of matched text instead of index position

A square matrix that is not invertible is called ..

singular or degenerate

split()

splits a string and returns an array of substrings

ES6: The spread operator is also called...

spread, rest, gather

subset of or equal to

Haskell: Sum up list, length of list, product, reverse, append two lists

sum [1,2,3,4,5], product, [1,2,3,4,5] ++ [6,7,8], reverse

superset of or equal to

Haskell: Remove first element from a list

tail [1,2,3,4,5];

Haskell: Select first N elements of a list

take 3 [1,2,3,4,5]

test()

tests a string for a matching pattern, used with regular expression

TEXT_NODE example?

text characters in an html document including carriage returns and white space

What does Document.createElement() return?

the element that is created.

Why would you want to use setTimeout(function cb() { console.log('there'); }, 0); ???

the event loop only pushes tasks onto the stack when the stack is empty. thus, this code waits for the stack to be code. essentially, this defers the execution of the callback until the stack is cleared.

what is the difference between the function constructor and the object constructor?

they look the same.

AJS: (function ($) { $(document).ready(function () { // my code }); })(jQuery);

this technique is used to rename different globals appropriately, i.e. conflict of prototype and JQuery using $

How to access component properties?

this.props

What is the purpose of the DOM?

to provide a programatic interface for scripting (removing, adding, replacing, eventing, modifiying) this live document using JavaScript.

What does this hypothesis represent? h_theta(x) = theta_0 + theta_1 x

univariate linear regression model

How to iterate across an object with side effects?

use the for... in loop while checking .hasOwnProperty because for...in will check parents as well.

Create a property firstName within a class Person

var Person = function (firstName) { this.firstName = firstName; }; //instantiation: var person1 = new Person('Alice');

Create a method sayHello on a class Person using the prototype design pattern

var Person = function (firstName) { this.firstName = firstName; }; Person.prototype.sayHello = function() { console.log("Hello, I'm " + this.firstName); };

class Student { fullName: string; constructor(public firstName, public middleInitial, public lastName) { this.fullName = firstName + " " + middleInitial + " " + lastName; } } interface Person { firstName: string; lastName: string; } function greeter(person : Person) { return "Hello, " + person.firstName + " " + person.lastName; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user); Typescript -> ES5 compiles to....?

var Student = (function () { function Student(firstName, middleInitial, lastName) { this.firstName = firstName; this.middleInitial = middleInitial; this.lastName = lastName; this.fullName = firstName + " " + middleInitial + " " + lastName; } return Student; }()); function greeter(person) { return "Hello, " + person.firstName + " " + person.lastName; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);

Document.createElement()

var element = document.createElement(tagName); *element* is the created Element object. *tagName* is a string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method.

Document.getElementsByClassName()

var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names); *elements* is a live HTMLCollection of found elements. *names* is a string representing the list of class names to match; class names are separated by whitespace getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.

Your code (king) gives node (servants) the two tasks to read and write a file, and then goes to sleep. Once node has completed a task, the callback for it is fired. But there can only be one callback firing at the same time. Until that callback has finished executing, all other callbacks have to wait in line. In addition to that, there is no guarantee on the order in which the callbacks will fire.

var fs = require('fs') , sys = require('sys'); fs.readFile('treasure-chamber-report.txt', function(report) { sys.puts("oh, look at all my money: "+report); }); fs.writeFile('letter-to-princess.txt', '...', function() { sys.puts("can't wait to hear back from her!"); });

syntax of testing if the value of this belong to the global object

var myObject = { firstName:"John", lastName: "Doe", fullName: function () { return this; } } myObject.fullName(); // Will return [object Object] (the owner object)

Use Math.max with apply to find the maximum value of [1,2,3,4,5]; and do it without it apply as well.

var numbers = [1,2,3,4,5]; var max = Math.max.apply(null, numbers); var max2 = Math.max(1,2,3,4,5);

How do we create an instance or object of a class named Person?

var person1 = new Person();

Rewrite the following async code that utilizes callbacks to using events getThem(param, function(err, items) { //check for err //operate on array of items }

var results = getThem(param); results.on('item', function(i){ //do something with this one item }); results.on('done', function(){ //no more items }); results.on('error', function(err){ //react to error }); Request/Reply -- no results until all results -- either error or results Publish/Subscribe -- act on results as they come in -- partial results before error -- the .on is kind of like a subscription when an event occurs.

local variables

varaibles defined inside a pair of curly braces and exist only while executing the part of the program within those braces.

Move forward one word

w

What do we make from a function with call and apply?

we make a method for an existing object. we envoke the function which becomes a method of an existing object because among the arguments we define the object to which the funcion will belong

DOCUMENT_NODE example?

window.document

How to fill first byte with 1's to a variable x?

x |= (0xFF)

Check for even or odd number using bits

x&1 ? "odd" : "even"

Method vs function invocation

x.a() vs a(x) (""the method-invocation syntax is an elegant way to express the fact that function is operating on an object");

Does the order of operations matter in Matrices?

yes

Haskell: Are functions first class citizens?

yes

var account = require('./myModule2.js')(2000);what is this code doing in relation to CommonJS

you can assume that the module being imported or required is a constructor/class, and by invoking the constructor we're creating a class instance

Find the partial derivative of 3x-2y^4 with respect to x and with respect to y.

you treat everything else as a constant f_x = 3 f_y = -8y^3

Subtract one to n using bit ops

~-n

How do you change the sign of an integer?

~x + 1


Kaugnay na mga set ng pag-aaral

Interpret Linux File System Permissions

View Set

AIR 1002 Department of the Air Force

View Set

Types of Life Policies Ch2 Texas Life Insurance Exam

View Set

Government Chapter 14 Foreign Policy

View Set

Chapter 21: Bonus Chapter A: Working within the Legal Environment

View Set

Best 100 closing lines from books (from https://www.stylist.co.uk/books/the-best-100-closing-lines-from-books/123681, on 2/18/2019)

View Set