Computer Science Final Exam

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

The dark side

▪ Because BTC can be purchased with cash, and bitcoin addresses are not associated with individuals, it's an ideal currency for black market transactions ▪ On the dark web, accessible via the TOR browser, just about anything is available for BTC ▪ Note, however, that law enforcement knows this, too, and several large busts have been made, such as The Dread Pirate Robert's conviction for running Silk Road

Speculation

▪ BTC exchange rates against fiat currencies such as USD can fluctuate quite rapidly ▪ In 2010 you could grab 1,000 BTC for just a few hundred dollars (1 BTC = $421 at the moment) ▪ Conversely, last year 1 BTC = $1,100 ▪ The Winklevosses even created an index fund based on BTC (called, not kidding, the Winkdex)

Text boxes and other inputs

<input type='text' value = 'enter text' id='box1'> <input type="checkbox" id='cb1'>Choice 1 <br/> <input type="checkbox" id='cb2'>Choice 2 Radio buttons (only one selection allowed) <input name='fred' type="radio" id='rb1'>Choice 1 <br/> <input name='fred' type="radio" id='rb2'>Choice 2 the 'name' attribute groups these together

Variables

Consider this: x = 5 x = x + 2 ▪ What is the value of x? ▪ 7 ▪ Congrats, you know how a variable works! ▪ A variable is a symbol that holds some value ▪ We use the variable in our program, and the value that it represents is stored in memory ▪ For example, we might say x = 5; x = x + 7; ▪ This first stores the integer 5 in memory, then adds 7 and stores the result in the same location; x is the variable we use to manipulate the value

It isn't Java

You might have heard of the Java programming language ▪ You would expect that JavaScript would be, well, a 'script' version of Java ▪ In fact the two programming languages are unrelated ▪ JavaScript was based loosely on the C programming language

What does this code do?

let isItOdd = function(theNumber) { let remainder = theNumber % 2; return (remainder == 1); } let someNumber = 146; if (isItOdd(someNumber)) { console.log(someNumber + ' is odd'); } else { console.log(someNumber + ' is even'); } ▪ Bottom line...just about all of the code that you write will use functions, probably lots of them ▪ Next week we'll start looking at how to combine Javascript with HTML

A loop that prints a multiplication table

var mult = 6; for (count = 0; count < 10; count++) { console.log(mult + ' times ' + count + ' = ' + mult*count); }

What does this loop do?

while (true) { listen } It's an infinite loop...often used for servers that need to listen for incoming connections (such as a web server)

What can I buy?

▪ Anonymous cryptocurrency is fairly useless unless it can be used to actually buy things ▪ A growing number of 'real' companies accept BTC ▪ Dell, Microsoft, Overstock, CVS, and others...however... ▪ What these companies do is partner with a processing house such as Coinbase, which takes BTC in from the customer and forwards USD to the companies ▪ Still, it means that you can buy you can buy a Dell, dude, with BTC ▪ I believe you also can contribute to Bernie's campaign in BTC

Loops

▪ Another form of logic is looping; doing a series of steps repeatedly ▪ There are two forms: a while loop and a for loop ▪ They are similar but used for different situations

some notes...

• for (count = 0; count < 10; count = count +1) • 1: Normally we start the count at 0...this makes it easy to see how many times the loop will run when we use < as the test • 2: There's no constraint on what this test is. It is a comparison, so any comparison that will return true or false will work here. Usually it's designed so that it is obvious how many times we'll run the loop. • 3: There's a shortcut for adding 1 to a variable...instead of count = count + 1 we can say count++

otherwise...

▪ "if a is less than b, then give c the value 22, otherwise give c the value 9" ▪ The else keyword gives us this capability let a = 12; let b = 16; if (a < b) { console.log("a is less than b"); } else { console.log("a is greater than b");; } ▪ These are called conditional statements

Profit?

▪ 25BTC is currently worth around $137,000, and so it would seem to be an easy way to make money to just mine blocks...$137k every 3 or 4 days, right? ▪ The PoW is so difficult that groups of hundreds or thousands of miners pool together to try to solve the problem, and must split the bounty if successful ▪ And, oh by the way, it's a race with all the other miners

Callbacks

▪ A callback is a function that is executed when an event happens ▪ For example, you might want to change something on a page if a button is clicked ▪ We write callbacks to add interactivity on the page ▪ We'll spend a lot more time on callbacks in the next week or so

What is a BTC worth?

▪ A commodity currency is regulated by some central authority and its value often tied to some physical thing...gold or silver ▪ A fiat currency is valuable only because a government says it is ▪ In the US, dollars were a commodity currency...exchangeable for silver or gold...until 1971, at which time it became entirely a fiat currency ▪ Bitcoin is neither...its value is based solely on supply and demand

For loops

▪ A for loop executes a series of steps a certain number of times for (count = 1 to 12) do a step do another step increase the count by one ▪ Here the test evaluates a counter; when it reaches the last value, the loop stops repeating ▪ We use a for loop when we know ahead of time how many times we need to repeat the steps

String variables

▪ A string is a collection of characters, and it is stored in memory one character per memory location; each character is typically 1 or 2 bytes ▪ We can indicate a string in most languages with quotation marks myString = "This is an awesome string" ▪ Most languages have built-in functions to manipulate strings • Get the length • Search for substrings • Do substitutions etc

Strings

▪ A string is simply a group of characters ▪ Strings offer quite a few operations on them ▪ You've already used one of them... '+' let someNumber = 5; let aString = 'There are ' + someNumber + ' in total'; ▪ Here are two simple functions that convert a string to upper or lower case: let myText = "Winter is coming!"; myText = myText.toUpperCase(); myText = myText.toLowerCase();

substrings

▪ A substring is part of a longer string let myString = "This is a really long string"; • One substring would be "really long" • We use the substring() function to extract substrings • The function takes two parameters: • The starting position of the substring • The ending position of the substring ▪ For example let myString = "This is a really long string"; let really = myString.substring(10, 15); ▪ The unfortunately named substr() function does something similar, but the two parameters are the start position and the length of the desired substring let myString = "This is a really long string"; let really = myString.substr(10, 6); ▪ Aboutthosepositions... ▪ Javascriptstartscountingat0,not1 ▪ Thefirstcharacterinastringisatposition0

Input and output (I/O)

▪ A system that couldn't accept any input and didn't give any output would be pretty useless ▪ I think I just described congress... ▪ All programming languages have ways to read data in from the keyboard, a file, a mouse click, a sensor, etc, and to output information to a screen, a printer, a file, and so on • The exact method varies from language to language; for example • C++ uses cout >> to print • Javascript uses console.log("something") to print • Python uses print to print

Variables

▪ A variable is just a named value ▪ You've probably used them in math problems for years: Let a = the number of apples in a box ▪ JavaScript variables are exactly the same idea ▪ We use the let keyword to create a variable let a; ▪ Once you have a variable, you can put whatever you like into it ▪ It's 'variable', so you can change it to something else if you like a = 22; //now a is something else Note that we only need to use let once, when we create the variable ▪ Variables can hold any type of data let aVariable; let anotherVariable; aVariable = "This is a string"; anotherVariable = [14,12,16,2]; //an array

While loops

▪ A while loop executes a series of steps while some condition is true while (there are still lines in a file) read the next line print the line out ▪ The test (the part between the parens) returns either true or false ▪ The loop continues until the test returns false ▪ We use while loops when we don't know how many times we need to repeat the steps...it relies on an external condition

What's the obsession with 0?

▪ As you'll find out, most CS folks always start counting at 0 ▪ This makes sense when you think about how the computer stores numbers; in binary, an 'empty' location in memory is 00000000 ▪ The CS department motto is 'We're number zero!'

Bill and Paul

▪ Bill and his friend Paul Allen had read about the Altair 8800 in Popular Electronics and wanted one to play with ▪ Bill contacted MITS, the manufacturer, and lied, saying that he and his 'team' had been working on a BASIC language interpreter for the machine ▪ In fact, neither he nor Paul had ever seen the Altair in person ▪ The first meeting went well...Paul was hired by MITS, and Bill took a leave of absence from Hah-vad to go work on the new program

Anonymous transactions

▪ Bitcoin has a really weird dichotomy • Transactions - paying for things in BTC - are more or less anonymous • Records of transactions are completely transparent and publicly shared • Every single BTC can be accounted for, because every transaction is recorded in a public ledger that includes every single transaction ever made in BTC, right from the very first one in 2009 • Those transactions, though, are between numbered accounts, not between individuals

Cryptocurrency

▪ Bitcoin is one of several cryptocurrencies ▪ The 'crypto' part just means that Bitcoin et al are based on encryption techniques similar to what we looked at in our discussion of PGP ▪ The 'currency' part is more interesting, because we are used to dealing wth coins and paper money and bank accounts and currency created and maintained by governments...this is none of that

But how does it work?

▪ By now you understand that the computer hardware only works with ones and zeros and can only do a limited number of things ▪ When a program runs on a computer, it really is just a series of electrical signals passing through logic gates (NAND, AND, OR and so on) ▪ Humans think differently...when we want to add two numbers together, we don't see it as a bunch of logic gates, we see it as 12 + 30 ▪ We need some way to translate the way humans think into the way computers think ▪ The solution? Programming languages ▪ Programming languages take human-style language and transform it into the 1s and 0s that the computer understands ▪ The 1s and 0s we end with is called machine language ▪ The machine language is stored on some media, such as a disk drive or thumb drive, until it is ready to be used ▪ The program is then read from disk into the computer's memory and executed ▪ Note that disk ≠ memory! Disk and related media (thumb drive, DVD etc) are nonvolatile...the information is not erased when power is turned off (unlike memory) ▪ The computer's memory is volatile...it is erased when the power is turned off ▪ In order for a programming instruction to be executed by the CPU it must first be in memory

Setting the value of a box

▪ By using a text box's id we can change its value from Javascript ▪ In this case rather than retrieve the .value we are setting it <html> <head> <script> function showValue() { var theBox = document.getElementById('box1'); var theValue = theBox.value; var theSecondBox = document.getElementById('box2'); theSecondBox.value = theValue; } </script> </head> <body> <input type='text' value='enter text' id='box1'> <input type='text' value='new val appears here' id='box2'> <button onclick="showValue()">Show It</button> </body> </html> ▪ Setting values like this is pretty common ▪ You can do it for just about any HTML tag, such as a paragraph ▪ You also can set things like CSS style values (colors, fonts, position and so on )...we'll look at that in our next discussion

What's the goal?

▪ Computers can do absolutely nothing that they haven't been preprogrammed to do ▪ We say that computers are deterministic; given an input we can always predict the output ▪ Even what we consider 'smart' or 'learning' applications have been programmed to be that way ▪ For the most part, a computer program is created solve some problem ▪ (Sometimes the problem is just that we're bored!)

Logic

▪ Consider this: x = 5 is x > 42? ▪ No! (x < 42) ▪ Congrats, you know how to use logic in programs! ▪ Logic statements return either true or false; they are boolean operations • Usually we use an if statement to execute a logical operation • if (this statement is true) do a series of steps otherwise do a different series of steps • The test is often a comparison operator such as equal (==), less than (<), or greater than (>) ▪ Logical operators, similar to the gates we looked at earlier, are also provided • && means 'and', returns true if both sides of the operator are true a=5; b=6; (b > a) && (a > 0) //true • || (two pipes) means 'or', returns true if either side of the operator is true a=5; b=6; (b==2) || (b > 0) //true ▪ Negation is accomplished with the ! operator a=5; b=6; !(a == b) //true, since a == b is false, and ! negates that

The IRS...Is it Money?

▪ Cryptocurrencies are still new and we are figuring out many of the rules ▪ The IRS issued guidance in 2014 that such currencies be treated as property for purposes of taxes, which means that BTC is subject to capital gains tax ▪ This is complicated for miners but even more so for consumers...if you buy BTC this month and then spend it next month, IRS says you must report the gain if the exchange rate increased ▪ For example, buy $100 in BTC in October, in November it is worth $150, and when you buy a game with it you must report the $50 gain

Put it all together...

▪ Design a way to get the sum of all the integers between any two numbers ▪ We have a loop that does this, but it is hard-coded ▪ But! We know how to write functions that solve a general problem ▪ Combine the loop and the function... let series = sumOfSeries(2,6); function sumOfSeries (starting, ending) { let theCounter; let theSum = 0; for (theCounter = starting; theCounter < ending + 1; theCounter = theCounter + 1) { theSum = theSum + theCounter; } return theSum; }

Bottom line (programming languages)

▪ Each programming language was created to solve a specific genre of problems ▪ We use high-level, human-readable languages mainly for convenience ▪ Every computer language ends up being compiled or interpreted down to machine instructions that the CPU executes in its circuitry ▪ As we know, the computer can only operate on 1s and 0s! ▪ Even through there are literally thousands of programming languages, they all share common features such as logical operators, variables, and so on

Comments in code

▪ It's always a good idea to write comments in your programs, to explain what is going on and to make notes to yourself ▪ Comments in JavaScript start with two slashes:// //awesome.js by perryd 10 March 2015 // //This is the world's best piece of JavaScript coding, bar none. //We aren't quite sure yet what it does but it is bound to be awesome. // //Set up some variables first let a = 5; let b = 6;

The blockchain

▪ Each transaction - buying or selling - has an input and an output • The input is the unspent output of some other transaction - where the BTC came from • The output is where the BTC are going • A complete transaction also has an amount • The notion isn't that I 'own' a certain number of BTC and send it to someone else • It is instead that I received BTC from someone, and they received it from someone, and they received it...all the way back to the very first transaction ▪ It means that to calculate how much BTC I have, you'd have to calculate the amount based on all the prior transactions ▪ The 'sending to' and 'receiving from' parts are simply cryptographic addresses ▪ For example, you can send me BTC at 1BRpDX59fq1wMfUSm8J1n4hUGyVUs6UbQr ▪ The blockchain is the ledger that records all of these transaction ▪ Each transaction is cryptographically signed and submitted to the ledger ▪ The ledger - the blockchain - is widely distributed among thousands and thousands of computers ▪ Each computer verifies the transactions in the blockchain - this is called mining

Two tricks to using codeBlock

▪ Getting information out of JavaScript can sometimes be tricky ▪ There are two techniques you can use to help debug your code, and to provide output • console.log (whatever you like)...the command will print everything between the parens in the output console • alert (whatever you like)...will pop up a window with your message and an OK/Cancel button) • For example... (live demo of codeBlock)

A bit of history

▪ In 2008 Satoshi Nakamoto published a paper describing a new kind of digital currency ▪ In 2009 Nakamoto released open-source software implementing the idea ▪ Nakamoto is believed to hold approximately 1,000,000 bitcoin (BTC) currently worth just under $1 billion ▪ He was nominated for the Nobel Prize in economics ▪ If he wins, it will be difficult to contact him to let him know, because... ▪ ...no one knows who he really is ▪ It's widely accepted that Satoshi Nakamoto is a pseudonym, and many theories have been put forth about who he or she or they might be ▪ Clues include the language used in source code comments, which appears to be British english, a short list of mathematicians and theorists who might have been able to come up with the idea, and a lot of just wild guesses ▪ It might seem that it would be difficult to hide a billion dollars in net worth, but that's the whole point about Bitcoin!

When I was a kid...

▪ In days of yore, computers were programmed manually • Flipping switches, plugging in jumpers, rewiring... ▪ At that time, programs were written down on paper, and then we would input them one instruction at a time using the switches ▪ This was extremely tedious and error-prone ▪ At some point someone sat back and asked themselves, 'Why am I doing this when I have a computer in front of me?'

Getting the values

▪ In each type of input, we can fetch the value using GetElementById() and the value property ▪ Once you have a value from a box, your function can treat it just like any other variable Tip: The current version of Brackets doesn't offer 'value' in its dropdown selection...you'll usually have to the it in

Variable types

▪ In memory, different kinds of values take different amounts of space ▪ For example, an integer (a counting number like 5) might take 2 bytes, while a float (a number with a decimal like 123.456) might take 4 bytes ▪ This means that the program needs to know what type a variable is in order to set aside the correct amount of space ▪ Some languages, such as C++, are strongly typed, which means that the programmer must explicitly state the type of a variable; it's an error not to, or to specify the wrong type ▪ Example: int myInt = 5; //ok int anotherInt = 123.654; //results in a compile error ▪ Other languages, like Python, determine the type by context; if it looks like an int, it's an int. We call these languages weakly typed ▪ Example: someInt = 6 aNumber = 42.16 theSum = someInt + aNumber //result is a float ▪ Variables can hold any value, even another variable aNum = 5 anotherNum = aNum //both hold 5 ▪ You can use variables just like you would use the actual value (5 in this case)

[Arrays]

▪ In most computer languages, including Javascript, an array is an ordered collection ▪ Each item in the array has an index associated with it, which lets us set or get the item at that index ▪ You might think of it as an egg carton on which you've written integers from 0 to 11 (for a dozen), one number per slot ▪ You could then put the blue egg into slot 4 and go back later and get it ▪ To create an array, we use the [ ] symbols let someEggs = [ "blue", "white", "green"]; ▪ Here the blue egg is in location 0, the white egg is in location 1, the green egg (ew) is in location 2 ▪ You guessed it, arrays start at 0 just like strings ▪ To read something from the array, we need its index number let someEggs = [ "blue", "white", "green"]; let whiteEgg = someEggs[1]; ▪ Same idea if we want to replace a value let someEggs = [ "blue", "white", "green"]; someEggs[1] = "orange"; //replaces white ▪ Javascript arrays can have different kinds of values in each element let anArray = ["orange", 16, result, "blue"];

Fun with loops

▪ In our last discussion we looked at two kinds of loops • for loops, when we know how many times we want the loop to run • while loops, when we want the loop to run until something special happens • Let's take a closer look at the syntax of a loop

A host of golden languages

▪ In the 1960s and 1970s, as interest in computing exploded, hundreds of new languages were developed ▪ C, Ada (named for Ada Lovelace), PL/1, and so many others, were developed during this time ▪ General-purpose computers were still expensive, but IBM, DEC, Honeywell, and others were selling truckloads of them to government and businesses

'Other variables' = Properties

▪ In the object world we say that an object has properties, which is just a fancy name for 'a collection of variables' ▪ For example, we might want to create an egg carton object that stores the number of compartments it has var eggCarton = { slots: 12, variable name }; { and } characters enclose the object variable value material: "cardboard" console.log(eggCarton.slots, eggCarton.material); use . to access an object's variables

Ada Lovelace

▪ It might please you to know that the first computer program was written by a woman, Ada Lovelace ▪ Ada Lovelace, daughter of Lord Byron, the poet, was a dear friend of Charles Babbage and was fascinated by his Analytical Engine ▪ She was a polymath, interested in a wide variety of topics; her algorithm to compute Bernoulli numbers, written in 1842, is recognized as the first computer program

Buying BTC

▪ It's complicated... ▪ You either buy from an exchange or from an individual ▪ Some exchanges (such as coinbase) now offer credit-card purchases ▪ A large chunk of buying and selling is done through bank wire transfers, money orders, and, well, cash ▪ Trust becomes a big issue...fortunately the Internet is a good critic ▪ Sometimes exchanges fail ▪ MtGox is the poster child... ▪ In 2013 the exchange handled 70% of all BTC transactions ▪ In 2014 850,00 BTC 'disappeared' and the exchange filed for bankruptcy ▪ coindesk.com is a fairly reliable source of info for buying and selling BTC ▪ coinbase.com is also a great site

Functions redux

▪ It's often the case that we find our code doing the same thing multiple times ▪ For example, maybe I have to calculate the tax on an item, and it involves several steps ▪ Something like this... var price = 14.95; var salesTax = price * .06; var localTax = price * .02; var federalTax = price * .07; var totalTax = salesTax + localTax + federalTax; var totalPrice = price + totalTax; ▪ But what if I had many items that I needed to calculate the total Price for? ▪ One approach would be to repeat all 5 lines for every total Price I had to calculate ▪ This would get pretty ugly pretty quickly ▪ There's a cleaner way...using functions ▪ A function is simply a set of code that we want to re-use many times, but with different values ▪ Functions have a name ▪ They take zero or more input values ▪ And (optionally) return some result ▪ Weusefunctionsquiteabit,becausetheysimplifyourcode ▪ From the computers standpoint, it doesn't care if we repeat the same five lies of code over and over hundreds of times or just once inside a function ▪ From our standpoint, functions make it much easier to read and understand our programs ▪ Javascript comes with thousands of built-in functions that do all sorts of useful things

Doing something more than once

▪ It's often the case that we need to do a set of steps several times ▪ JavaScript provides us a waywiththeloop ▪ Loops come in two flavors: - You know how many times to do something - You don't know how many times to do something

What is it (JavaScript) for?

▪ JavaScript and webpages are intertwined ▪ HTML is great for pages where things don't change ▪ JavaScript was designed to let coders add interactivity to their pages ▪ All the 'fancy' things you see on webpages are in almost every case JavaScript programs running inside the page

Where does it run?

▪ JavaScript is a programming language...where does the actual program run? ▪ In the browser itself ▪ Browsers include a JavaScript 'engine' that reads and executes the JavaScript code in each web page ▪ You can turn the engine off in Settings or Preferences for each browser ▪ We looked at two types of programming languages earlier ▪ Compiled (C, C++, COBOL, Java) ▪ Interpreted (BASIC, PERL, Python) ▪ JavaScript is an interpreted language

A gotcha...

▪ JavaScript is an interpreted language ▪ In this kind of language, an interpreter reads each line of code, converts it to machine language (1s and 0s) and then executes it ▪ We've said that the JavaScript interpreter is built in to the browser ▪ The gotcha is that this means we have to send the human-readable source code to the browser for it to run ▪ This further means that anyone can read or even copy your JavaScript program on your web page

Printing things out

▪ JavaScript was designed to run in a browser, and so doesn't have a "normal" way to print things out fro a program ▪ (Usually the program is changing things on a webpage) ▪ We can print to the console, though, which is a text-based output system ▪ This is useful when running programs from the command line ▪ In a browser tire's still a console but it is somewhat hidden ▪ Here's an example: console.log("This will be printed out")

The basics

▪ JavaScript, as a programming language, has a certain syntax that must be used ▪ Syntax is just the rules for writing lines of code ▪ The first piece of syntax: Every line of code must end in a semicolon (;) (except when it doesn't...this is a bit of controversy in JavaScript) ▪ The language lets you work on numbers, strings of characters, images, and all the other things you might see on a web page ▪ It also gives you complete access to the pieces of the page itself

Built-in libraries

▪ Javascript comes with several important libraries pre-installed ▪ The libs define some of the often-used features in the language

Clicking a button

▪ Let's say we want to put a button on our HTML page and have a message pop up when someone clicks on the button ▪ We can tell the button to run a function when it is clicked ▪ The onClick event is just one of many that we can respond to on the page ▪ When the button is clicked, the function sayHello() will run ▪ We still need to write say Hello(), though... <button onClick="sayHello();">Clickez-moi!</button> Boston University Slideshow Title Goes Here ▪ In your HTML page, Javascript goes in the <head> of your page in between <script>...</script> tags <html> <head> <script> function sayHello() { alert('Hi there!'); } </script> </head> <body> <h2> A talkative button</h2> <button onclick="sayHello()">Clickez-moi</button> </body> </html> ▪ We could also tell sayHello what we wanted the alert to say by passing a message to the function <html> <head> <script> function sayHello(theMessage) { alert(theMessage); } </script> </head> <body> <h2> A talkative button</h2> <button onclick="sayHello('Clicked!')">Clickez-moi</button> </body> </html>

Two approaches

▪ Like so many things in computer science, there are two broad approaches to creating a program that the computer can run (called an executable) ▪ One way: Do everything ahead of time...translate the human-readable code into machine language, store it, and then execute it at some later time ▪ Languages that use this method are compiled languages ▪ Examples: C++, FORTRAN, COBOL, PL/1 ▪ The second way: Translate the human-readable code into machine language one line / statement at a time while the program is running ▪ Languages that use this method are interpreted languages ▪ Examples: Python, BASIC, Javascript ▪ I should mention a third way... ▪ Some languages, like Java (which is not Javascript but a separate language) compile code to an intermediate language called byte code ▪ Byte code is ow the compiled program is stored and distributed ▪ When you run the program, the byte code is interpreted by a run-time execution program (in Java it is called the Java Virtual Machine or JVM)

Strings and arrays

▪ Many times we encounter a string that is a comma-separated list of things ▪ In the spreadsheet world this would be called a CSV (comma separated value) string ▪ There's a handy Javascript function that takes a CSV string and converts it into an array, where each element is an item that was separated by commas let csvString = "blue, black, green, orange, purple"; let decoded = csvString.split(","); ▪ The result is an array decoded[0] = "blue"; decoded[1] = "black"; decoded[2] = "green"; decoded[3] = "orange"; decoded[4] = "purple"; ▪ Both arrays and strings have lots of built-in features let anArray = ["tree", "rock", "bunny"]; let theLength = anArray.length; anArray.push("snack"); //adds snack to array let someString = "Howdy doody"; theLength = someString.length; //should be 11 ▪ Browse through the docs at w3schools, or just type . after a variable in Brackets and explore

The id attribute

▪ Most HTML tags can have an attribute called "id" ▪ The id attribute allows us to work directly with an HTML tag and its contents from Javascript <p id='para1'>Some text</p> document.getElementById('para1').textValue = "something new";

Wallets

▪ Most bitcoin users don't have access to an ATM and instead use a digital wallet to keep track of their BTC ▪ Wallets are just a cryptographic address that BTC flow into and out of ▪ (And remember, the ledger is public and distributed, so anyone who knows your wallet address can see how much bitcoin is in it) ▪ A popular online wallet is at blockchain.info ▪ There are apps for Android and iOS (Breadwallet seems to be the most popular for iOS)

Libraries

▪ Nearly all computer languages include a set of libraries that add functionality to the base language ▪ For example, most languages don't offer a built-in random number generator, but will have a library that does ▪ This keeps the base language small, and you then can add just the functions that you need for your task ▪ Companies spring up around specialized libraries, and programmers often create and share useful libraries

Common features

▪ No matter the language, you'll find common programming features • Variables • Logic • Input / output • Math

There are no bitcoins

▪ No one produces a physical coin (well, not officially...see link below) ▪ They don't exist in physical form ▪ You can't store them on your computer ▪ There only exists a record of every transaction ever made in BTC, called the blockchain

Bottom Line

▪ Normally when we want to achieve some effect or computation, it's been done before and we can find a library to do it ▪ If the exact problem hasn't been solved, we can modify an existing one ▪ It's pretty rare now in commercial programming to invent something from scratch ▪ (Though when you do you can get rich!)

So was BASIC the first language?

▪ Not at all, there were many that came before it ▪ HOWEVER, early languages were designed for specific computers; remember, there might be only one or two copies of a particular machine ▪ The first widely used language was FORTRAN (FORmula TRANslation system), finished in 1957...it was available on several different computers ▪ COBOL (Common Business Oriented Language) was developed via the DoD from work done by Grace Hopper in 1959

'Behaviors' = functions

▪ Object have properties. They also have behaviors, which are the methods (functions) than an object contains ▪ We might, for example, want our egg carton to be able to print out how many slots it has var eggCarton = { slots: 12, material: "cardboard", printNumSlots: function( ) { console.log(this.slots); } }; What the heck is this? eggCarton.printNumSlots(); Use . to access function Add a function named printNumSlots

Math

▪ Programming languages provide basic math operations ▪ They look the same as your calculator: +, -, *, / ▪ Usually you will also find %, which is the modulo operator; it returns the remainder of a division: 5%2 would be 1 (5 / 2 is 2 with remainder 1) ▪ You might use modulo to see if a value is even or odd Math someNumber = 7 if (someNum % 2 == 0) number is even otherwise number is odd

Objects

▪ Programming with these high-level ideas is accomplished with something called an object ▪ In Javascript, an object is simply a variable that has some additional features - They can hold other variables - They also can hold functions ▪ We treat the object as one unit...it is essentially a collection of variables and functions ▪ Even though it is just a collection, we can use an object to model real-world things ▪ We like to think of objects having properties (also called attributes) and behaviors ▪ The objects can 'communicate' with one another and with the program ▪ This approach is called object-oriented programming (OOP)

JS variables

▪ So far we've seen some simple and some more complex JS variables - varaNumber=42; - varfirstName="Perry"; - vareggs=['white', 'blue', pink']; ▪ We can do some fairly interesting things with just this level of complexity

<script src= ...

▪ So far we've used the <script> tag to enclose our own functions ▪ Adding the src= attribute lets us specify a location for a Javascript library file ▪ For example <script src="http://balance3e.com/random.js"/> ▪ You'll find lots of these in nearly every web site you visit ▪ Normally, when you develop a web site you'll place all of the Javascripts that you need in a folder and use the <script src=> tag to include them in your page

Values that are numbers

▪ Text boxes contain just that...text ▪ If we want what is in a textbox to be treated as a number in Javascript, it needs to be converted ▪ The Number function will do that for us; there are several other ways, but this is the easiest to remember var z = Number(document.getElementById('box1').value);

The Math library

▪ That program returns a fraction number of days until we're done with the semester ▪ What if we wanted to round it to a whole number of days? ▪ The Math library can do this and quite a bit more ▪ Math is where you'll find trig functions (sine, cosine), random numbers, mins and maxes, absolute value, and so on ▪ Let's use the round( ) function in our program... //Calculate how long it is //until the end of the semester let today = new Date(Date.now()); let theEnd = new Date(2016,11,20); let numDaysLeft = theEnd - today; numDaysLeft = numDaysLeft / 24 / 60 / 60 / 1000; numDaysLeft = Math.round(numDaysLeft); console.log(numDaysLeft);

BTC creation

▪ The 25BTC bounty for mining a block comes from thin air, and so the total amount of all the BTC in existence increases gradually over time ▪ The bounty decreases by half after 210,000 blocks are mined ▪ The total number of BTC that can ever be created is set by the protocol at 21 million ▪ Around the start of 2015 we were at 12 million or so ▪ Current estimates show the the 21 millionth BTC will be mined in 2033

The HTML DOM (Document Object Model)

▪ The DOM is a way to represent the parts of a document ▪ It acts as a map to any given element ▪ Relationships among the elements are also shown ▪ We use the DOM to find things in anH TML document

for loop syntax

▪ The for loop needs three pieces of information: 1. The initial condition of a counter...where it starts 2. A test to determine if we've run the loop the right number of times 3. A way to increment the count of how many times we've been through the loop 123 • for (count = 0; count < 10; count = count +1)

Getting a value from a box

▪ The getElementById function is very commonly used in creating dynamic web pages...pages that the user can interact with ▪ There are actually several ways to address an individual HTML tag, but for the most part you'll use this one ▪ Once you are working with an HTML tag in this way you can change the content of the tag, change its color or font, reposition it, make it appear or disappear, and so on ▪ In this instance we are interested in seeing what someone has typed into an input box

The real world

▪ The real world, though, isn't usually so simplistic ▪ Most problems that we are trying to solve are much more complex and need an additional level of functionality ▪ We like to think in terms of things that we know...an egg carton, a store, a person, and so on

while loop syntax

▪ The while loop waits for something to happen, which is indicated by a boolean value of 'true' ▪ The initialization is done outside the loop ▪ Usually the 'something happens' comes from inside the loop itself • End of a file we're reading • Some variable goes to zero ▪ Sometimes the event really is external var words = "this is a sentence"; //initialize words var length = words.length; //initialize length while (length > 0) { console.log(words); words = words.substring(1, length); //remove a letter from end length = words.length; }

ATMs

▪ There are a few hundred BTC ATM machines in the US...supposedly there are three in Cambridge ▪ For small transactions you can buy and sell BTC without much effort ▪ For large transactions the companies behind the ATMs must comply with federal KYC (Know Your Customer) rules and ask for photo IDs, passport numbers and pictures

Which is better?

▪ There are advantages and disadvantages to each ▪ In compiled languages, error-checking is done ahead of time, and so we can weed out syntax errors before running the program; this takes time, though, especially for very large programs ▪ In interpreted languages we skip the compiling step, which can save time; the program might have bugs, though, that we don't find until run time ▪ Often the choice comes down to task...we often see compiled programs for large, application-level code, and interpreted programs for smaller tasks, such as scripts used for utilities ▪ The bigger issue is that each brand and model of CPU has slightly different instructions that can be executed (AMD vs ARM vs Intel i7 etc) ▪ If the program is compiled, it is creating machine language which must be targeted to the specific CPU it will be run on ▪ If the program is interpreted (or uses byte code ala Java) only the interpreter has to be able to run on the specific CPU (the interpreter is compiled) ▪ Choosing which approach you'll use for a program thus depends on how it will be distributed and run

Other popular libraries

▪ There are literally thousands of JS libraries available that do almost anything you can imagine, especially for web page design ▪ Some popular ones include Closure, JQuery, Angular, Mongo, and Node ▪ In CS, we spend a lot of time just learning acronyms and names of programming libraries!

Other HTML / DOM events

▪ There are many, many events that can be listened for, such as ▪ onBlur:The mouse pointer is moved across an element ▪ onMouseDown/onMouseUp: Clicks of the mouse ▪ onFocus: Clicking inside an input box ▪ onDblClick: Double clicking ▪ onLoad: When the page loads ▪ Each of these takes a function, for example <p id='para1' onDblClick='makeUpperCase()'>

The competition

▪ There are quite a few competing cryptocurrencies, often called alt coins (though BTC is by far the largest) ▪ Litecoin ▪ Dogecoin ▪ Peercoin ▪ Etherium ▪ There are also exchanges that will trade BTC, LTC, and so on for ingame currency for places like Second Life and WoW

replace()

▪ This one lets you get rid of winter... let myText = "Winter is coming!"; myText = myText.replace("Winter", "Spring");

The epoch

▪ Time in most programs and computers is stored as the number of milliseconds elapsed since January 1st, 1970 ▪ The UNIX operating system was 'born' in 1970, and so the system designers knew that nothing could have happened (in the UNIX world) before 1/1/70 ▪ The epoch evolved into an international standard for keeping time ▪ Unfortunately epoch time is stored in a 32-bit number, of which one bit is used a sign (plus or minus) ▪ Recall that 2^31 = 2,147,483,648 ▪ Time literally runs out on that date and will 'wrap' to December 13th, 1901 ▪ Fortunately we have time to fix the problem by moving to a 64-bit storage unit for time measurements ▪ Back to our problem...how do we convert milliseconds since 1970 to a number of days? ▪ Simple! Divide by 24/60/60/1000 (24 hours / 60 minutes per hour / 60 seconds per minute / 1000 milliseconds per second) ▪ Our new program looks like this... //Calculate how long it is //until the end of the semester let today = new Date(Date.now()); let theEnd = new Date(2017,12,20); let numDaysLeft = theEnd - today; numDaysLeft = numDaysLeft / 24 / 60 / 60 / 1000; console.log(numDaysLeft);

Is BTC related to Tor?

▪ Tor is The Onion Router, a system that helps anonymize web browsing ▪ It is accessed through the Tor Browser Bundle, which you can download at torproject.org ▪ BTC and Tor aren't related per se, however Tor is used to access the 'dark' web at .onion addresses, and many sites in that network accept BTC for items or services that might be illegal in your country

Mining

▪ Transactions made over a period of time are collected together into a block ▪ The block is widely distributed on the network ▪ Miners mathematically verify the validity of each block and create a hashed value of the block ▪ The block also includes the hashed value of the previous block, which is what connects the blocks together into a chain ▪ Each miner has access to the entire chain and so can verify where each BTC came from all the way back to the very first block ▪ Each time a block is verified, or mined, the miner receives compensation of 25 BTC ▪ *Note that the reward is halved every 210,000 blocks...we should be close to the next halving right now ▪ Calculating the hashes and verifying transactions normally wouldn't take all that much time ▪ In order to limit the growth of bitcoins, extra work is required of the miners, called the Proof of Work ▪ The PoW involves requiring a very specific format for the hash values, one that is extremely difficult to calculate - essentially the mining software has to make many guesses at the correct value ▪ The difficulty level is automatically adjusted periodically in order to keep the rate of mining at around 3 days per mined block across the entire network

Conditional statements

▪ Typically we want something to happen based on a comparison ▪ For example, "if a is less than b, then give c the value 22" ▪ The JavaScript reads just like the statement above let a = 12; let b = 16; let c; if (a < b) { console.log("a is less than b"); }

Operators

▪ We can do basic math functions such as addition, subtraction, and so on let a = 12; let b = 16; let c = 12 * 16; let d = 11 / b; let e = a - b; let f = a + b;

Functions( )

▪ We could write all of our programs so that they start at the top, and execute one line at a time until we get to the bottom ▪ In most cases, though, we'll find that we are doing something twice, or that we want to program something in a general way that can work on any values we provide ▪ A function lets us do just that... let aNumber = 42; let anotherNumber = 16; let theSum; theSum = addTwoNumbers(aNumber, anotherNumber); theSum = addTwoNumbers(3, aNumber); function addTwoNumbers (value1, value2) { return value1 + value2; } ▪ We use functions a lot ▪ They can be very simple or verycomplex ▪ Best practice: Go for simplicity ▪ It's better to use small functions that do one thing and chain them together if you need to do something complicated

Comparing things

▪ We often want to know whether one thing is less than, greater than, or equal to another thing - a<b //is a less than b? - a>b //is a greater than b? - a==b//is a equal to b?(notedouble==) - a===b//is a equal to b AND are they the same type? ▪ All of these expressions result in either true or false ▪ True and false are called boolean values

Bottom line (bitcoin)

▪ We still don't know yet if Bitcoin and other crypto currencies will flourish or wither ▪ It's still interesting to watch, and even speculate in ▪ To grow, though crypto currencies need to shed their black-market associations ▪ The idea of a public ledger, the blockchain, is growing in popularity for other types of transactions (think stocks and bonds and real estate for example)

Bottom line (getting things from HTML Boxes)

▪ We use functions, called listeners, to respond to actions taken by a user on the web page (clicking, dragging, and so on) ▪ The most common way to set or read the value of something on a web page is to use a combination of its id and its value properties ▪ Every element on the page is accessible from Javascript ▪ It isn't just HTML, but also CSS (styles) that we can get to from Javascript ▪ Because we are linking Javascript and HTML together, we are now able to essentially 'program' our web pages

Date examples

▪ We use the Date library to (you guessed it) manipulate dates ▪ The library includes an object called Date ▪ An object is simply a collection of variables and functions that provide an easy way to access them ▪ The Date library has quite a few functions to work with dates ▪ Let's say that you want to know how many days it is until the end of the semester... //Calculate how long it is //until the end of the semester let today = new Date(Date.now()); let theEnd = new Date(2017,12,20); let numDaysLeft = theEnd - today; console.log(numDaysLeft);

Javascript libraries

▪ We've seen simple Javascript functions so far ▪ It's often useful to place several functions together into a single file called a library ▪ The library file isn't anything special, it really is just a collection of functions ▪ The library may be added to a web page using the <script> tag

Mining hardware

▪ When BTC were introduced in 2009 it was relatively simple to calculate the correct hashes and mine blocks - well within the reach of the average PC ▪ Around 2011 the calculations became hard enough that miners turned to boxes full of graphics cards (which are very good at math) ▪ In 2013 or so the complexity surpassed ganged graphics cards and special-built mining computers which do nothing but calculate hashes were introduced ▪ The Monarch calculates around 700GH/s...700 billion hashes per second ▪ That seems like quite a lot! Surely a $350 monarch would pay for itself in just a few days! ▪ But...even at 700GH/s, here's what you could expect... ▪ You have to factor in the cost of electricity...these computers consume a lot of power ▪ At some point pretty low on the curve, the cost of power would exceed the expected return from mining ▪ For this reason, most mining is now done by large syndicates in big data centers...this one is in Washington state...

this

▪ When we work with objects, it's normal to have more than one of the same kind ... several egg cartons, for example ▪ It's quite likely then that two individual objects have the same variable name inside ▪ We use the keyword this. to specify that we are talking about the variable in this object, not some other object

The FOR loop

▪ When you know how many times to do something ▪ "Sum the numbers from 0 to 5,i .e. 0+1+2+3+4+5" ▪ The loop uses a counting variable to count how many times we've done the loop for (count=0; count < 6; count = count + 1) ▪ Thissays'startatzero,andaslongascountislessthan6,runthe loop then add one to the count' Boston University Slideshow Title Goes Here set up a variable to hold result this counts the number of times to do the loop let theSum = 0; for (counter = 0; counter < 6; counter = counter+1) { theSum = theSum + counter; } once we hit 6, exit the loop

BTC tracing

▪ While BTC is notionally anonymous, the transactions themselves are not...in fact, that's the whole point of BTC ▪ Each transaction is added to the BTC ledger, the blockchain ▪ The blockchain shows every single transaction in the history of BTC from the very first to the most recent ▪ The transactions are recorded against wallets, and so you can clearly see BTC moving from one wallet to another ▪ The challenge, then, is to keep your wallet anonymous ▪ To help hide transactions, services called mixers combine payments from many users, then break those payments up into smaller pieces ▪ Say I wanted to buy a rare mushroom but didn't want anyone to be able to trace the transaction ▪ I'd send payment to a mixer, which would combine my BTC with hundreds of other users', then pay the mushroom company themselves ▪ Even this just makes it harder...not impossible...to trace the original transaction

Initializing a variable

▪ While it isn't uncommon to create a variable with let and later assign a value to it, usually we do the two steps on one line ▪ Here's an example of initializing a variable...creating it and assigning a value: let studentAge = 22

Using codeBlock for lab

▪ code Block is a program that runs JavaScript right in the browser ▪ It's a little special in that it allows you to type in your own code and then run it ▪ We'll use codeBlock for our first lab...it's a great way to play with JavaScript


Ensembles d'études connexes

Blood Vessels of the Coronary system

View Set

ENG II Integrating Sources Notes

View Set

Origins and Insertions (Rhomboid Major)

View Set

Week 9: Supply Chain Management (chapter 9)

View Set

TTE-221 Chapter 2 Systems Architectures

View Set

chapter 18 consumer behavior quiz

View Set

How minerals are identified Chapt 3

View Set