Idiots should stay away from jQuery

Consider this one of my first real lessons of writing code. Idiots should stay away from jQuery.

I’m sure by this time in internet history this is well documented phenomenon.

I got a job, wrote a bunch of form validation in jQuery like an idiot. No functions, just purely procedural. Now I have to clean it up. It’s gross, disgusting, and disturbing.

I knew I was an idiot. (Still am, in many aspects.) But jQuery makes it’s insanely easy for idiots like me to write horrible code.

If you write code in Javascript, at least you begin to think “Huh, I should break this into functions”. This doesn’t exist in jQuery, because of callback structure. It encourages you to write twisty ugly code, that will be the bane of your existence later.

jQuery is NOT for idiots. If you are an idiot, please do not write jQuery. You will regret it later. Use ES6, or plain old JavaScript.

Also, learn to write code and some programming patterns.

Working through BUIDL Bootcamp: BankCoin

Problem with ECDSA Coin

The problem with our previous coin is that it could be doublespent. Alice could have sent that coin to anyone before sending it to us. There is no source of truth. We can use centralization to fix this.

Every time a coin is sent, we use a “bank” to make sure it is valid. Alice can’t send a coin to Bob, then send the same coin to Joe.

How We Build Our Bank

The Bank should be able to issue coins to anyone. We can create coins by using a person’s public key.

Our Bank should track the coins we created. This way, we can ensure ownership and transfers and make sure no one double-spends.

We’ll make sure our bank can check everyone’s balance, and that their balance is consistent with the ledger we’ve created.

Also, we’ll have a function that our users can use. This function tells the bank, “Hey, I let Bob have my coin now. Please update your ownership records.”

Building BankCoin

We go through and build the functionality that is described by the tests. This is pretty straightforward.

The deepcopy function allows us to not have side effects in our code. We will add the deepcopied coin to our database of coins, in Bank. For more reading about deepcopy.

If you worked through the extra exercise I talked about previously, this whole coding exercise might be simplistic for you.

In case it isn’t, let’s break it down.

We have 3 main classes: Bank, BankCoin, and Transfer.

Transfer

Transfer is exactly the same as what we constructed in ECDSACoin.

Bank

def __init__(self):
    # coins.id -> coin
    self.coins = {}

Bank is instantiated with a database.

def issue(self, public_key):
        # Create a message specifying who the coin is being issued to
        message = serialize(public_key)

        # Create the first transfer, signing with the banks private key
        transfer = Transfer(
            signature=None,
            public_key=public_key,
        )

        # Create and return the coin with just the issuing transfer
        coin = BankCoin(transfers=[transfer])
        self.coins[coin.id] = deepcopy(coin)
        return coin

We can issue from the bank, and we don’t need a private key, because we trust the bank. The public key is needed, because we have to send it to someone upon issuance.

We then copy the coin to our database of coins, so we can track all the coins.

def fetch_coins(self, public_key):
        coins = []
        for coin in self.coins.values():
            if coin.transfers[-1].public_key.to_string() == public_key.to_string():
                coins.append(coin)
        return coins

We build a fetch coins function. This allows us to check out all the coins that are associated with a given public key.

We’ll query the coins database, and loop through it. We’ll check out each individual coin last transfer, and see if it matches the public key we have. If it does, then that shows ownership and we can add it to our array of coins that belong to a certain person, which we’ll return later, when the function completes.

If this part is confusing to you, I would suggest revisiting object orientation and playing with the code to get a deeper understanding of what is going on here.

def observe_coin(self, coin):
        last_observation = self.coins[coin.id]
        last_observation_num_transfers = len(last_observation.transfers)

        assert last_observation.transfers == coin.transfers[:last_observation_num_transfers]
        coin.validate()

        self.coins[coin.id] = deepcopy(coin)
        return coin

The last function we build is called “observe coin”. This helps us make sure everything is valid and up to snuff.

We take a coin as a parameter, and find it in our database. We then compare the coin in our database to the coin we passed as a parameter. If they match their transfers list, we’ll call “coin.validate()”, then update the existing coin.

BankCoin

The last class we construct in this section is called BankCoin. We essentially have the same exact code here as we did in the ECDSA Coin, except we move the transfer mechanism inside, and delete a small amount of code. Not worthwhile to explain.

If you didn’t understand this part though, it would be a good idea to repeat the previous lesson and check it out. None of this stuff is super easy or trivial, so don’t feel bad if you don’t understand it initially.

By this time, I’ve reached the 38:00 minute mark, and there’s still a lot left to do, even though we just passed all our tests.

Building on BankCoin

Some of the problems with BankCoin includes that we can’t transfer more than 1 coin at a time, we cannot transfer multiple coins to a single person in a single transfer, we cannot transfer 1 coin and split it between multiple people.

This boils down to divisibility. We need to be able to divide up BankCoin. We can do this with UTXO’s.

UTXO

UTXO’s are shorthand for unspent transactions output. It’s probably smart to understand how UTXO’s work, so this link on stackoverflow you should read, also this one was pretty good too.

Basically – UTXO is unspent Bitcoin corresponding to a Bitcoin address. That’s not even technically accurate, but it’s easier to understand, I think.

PS – Here I stumbled across this resource and got incredibly distracted. It’s worth checking out if you’re interested in running a full node, testnode in the cloud.

At any rate — In order to solve the divisibility problem, we introduce the idea of UTXO’s. This causes us to completely throw away all the code we had beforehand, and rewrite it with TX’s in mind.

TX

class Tx:

    def __init__(self, id, tx_ins, tx_outs):
        self.id = id
        self.tx_ins = tx_ins
        self.tx_outs = tx_outs

    def sign_input(self, index, private_key):
        spend_message = self.tx_ins[index].spend_message()
        signature = private_key.sign(spend_message)
        self.tx_ins[index].signature = signature

The first bit of code we write is the TX class. We use this to manage all our tx_ins, and tx_outs.

We also have this function called “sign input”, where we grab a spend message, generate a signature from it, and assign it to a tx_in.

TXIN

class TxIn:

    def __init__(self, tx_id, index, signature):
        self.tx_id = tx_id
        self.index = index
        self.signature = signature

    def spend_message(self):
        return f"{self.tx_id}:{self.index}".encode()

Nothing novel here. We have our TxIn class, with a few attributes. TxIn’s don’t have an amount associated with them, only TxOut’s have amounts.

If we want to find the amount associated with it, we have to grab the txid, and then find the previous associated tx_out with it, then grab the amount from that tx_out. This might be wrong, but as far as I understand, it is correct.

Next, we have a spend_message() function. This is referenced by our original TX class. It just allows us to return a string with variables self.tx_id, and self.index passed into the string, and then encode them in utf-8 encoding. Learn more about this function here.

TXOUT

class TxOut:

    def __init__(self, tx_id, index, amount, public_key):
        self.tx_id = tx_id
        self.index = index
        self.amount = amount
        self.public_key = public_key

Very boring class. I mean, there’s nothing to expand on here.

Bank

class Bank:

    def __init__(self):
        self.txs = {}

    def issue(self, amount, public_key):

        id = uuid4()
        tx_ins = []

        tx_outs = [
            TxOut(tx_id = id, index=0, amount=amount, public_key=public_key)
        ]

        tx = Tx(id=id, tx_ins=tx_ins, tx_outs=tx_outs)
        self.txs[tx.id] = tx
        return tx

    def is_unspent(self, tx_in):
        for tx in self.txs.values():
            for _tx_in in tx.tx_ins:
                if tx_in.tx_id == _tx_in.tx_id and tx_in.index == _tx_in.index:
                    return False
        return True

    def validate_tx(self, tx):
        in_sum = 0
        out_sum = 0

        for tx_out in tx.tx_outs:
            out_sum += tx_out.amount

        for tx_in in tx.tx_ins:
            assert self.is_unspent(tx_in)

            tx_out = self.txs[tx_in.tx_id].tx_outs[tx_in.index]
            public_key = tx_out.public_key
            public_key.verify(tx_in.signature, tx_in.spend_message())
            in_sum += tx_out.amount

        assert in_sum == out_sum

    def handle_tx(self, tx):
        self.validate_tx(tx)
        self.txs[tx.id] = tx

    def fetch_utxo(self, public_key):
        # Find which (tx_id, index) pairs have been spent
        spent_pairs = [(tx_in.tx_id, tx_in.index)
                        for tx in self.txs.values()
                        for tx_in in tx.tx_ins]
        # Return tx_outs associated with public_key and not in ^^ list
        return [tx_out for tx in self.txs.values()
                   for i, tx_out in enumerate(tx.tx_outs)
                       if public_key.to_string() == tx_out.public_key.to_string()
                       and (tx.id, i) not in spent_pairs]

    def fetch_balance(self, public_key):
        utxo = self.fetch_utxo(public_key)
        return sum([tx_out.amount for tx_out in utxo])

Okay. This is a monster and there’s a ton of stuff going on here. Let’s work through this together, eh?

def __init__(self):
        self.txs = {}

This creates our database of TX’s. We throw all our TX’s here, when they’re created.

def issue(self, amount, public_key):

        id = uuid4()
        tx_ins = []

        tx_outs = [
            TxOut(tx_id = id, index=0, amount=amount, public_key=public_key)
        ]

        tx = Tx(id=id, tx_ins=tx_ins, tx_outs=tx_outs)
        self.txs[tx.id] = tx
        return tx

We’ve seen an issue function before, so we basically understand what is going on here. We’re issuing money to someone, we use a few variables of id, index, amount we’re gonna issue and the public key. Nothing really new here, we’ve done this before.

The bonus here, is that we add the TX to the database when we create it. That’s this part of the code:

tx = Tx(id=id, tx_ins=tx_ins, tx_outs=tx_outs)
self.txs[tx.id] = tx
return tx

The next part is us checking what is unspent.

def is_unspent(self, tx_in):
        for tx in self.txs.values():
            for _tx_in in tx.tx_ins:
                if tx_in.tx_id == _tx_in.tx_id and tx_in.index == _tx_in.index:
                    return False
        return True

This is pretty straightforward by itself. We grab our txs database, and iterate through the values, which are individual tx_out’s or tx_in’s.

We then loop through every single tx_in, and check to see if a tx_in in our database corresponds with the tx_in we passed. If there is a correspondence, then we’ve spent it before. If it doesn’t, then it hasn’t been spent.

def validate_tx(self, tx):
    in_sum = 0
    out_sum = 0

    for tx_out in tx.tx_outs:
        out_sum += tx_out.amount

    for tx_in in tx.tx_ins:
        assert self.is_unspent(tx_in)

        tx_out = self.txs[tx_in.tx_id].tx_outs[tx_in.index]
        public_key = tx_out.public_key
        public_key.verify(tx_in.signature, tx_in.spend_message())
        in_sum += tx_out.amount

    assert in_sum == out_sum

Next, we have a validate tx function. It makes sure the TX we pass in is valid, obviously.

We take the TX parameter, iterate through the outs and grab the amount and sum.

Next, we iterate through the tx_ins. tx_ins don’t have an amount, so we have to reference the previous tx_out associated with the tx_in. We then verify the signature, and then add the amount to our variable, “in_sum”.

def handle_tx(self, tx):
    self.validate_tx(tx)
    self.txs[tx.id] = tx

This function runs validate_tx on a tx, then adds or updates it in the db.

def fetch_utxo(self, public_key):
    # Find which (tx_id, index) pairs have been spent
    spent_pairs = [(tx_in.tx_id, tx_in.index)
                    for tx in self.txs.values()
                    for tx_in in tx.tx_ins]
    # Return tx_outs associated with public_key and not in ^^ list
    return [tx_out for tx in self.txs.values()
               for i, tx_out in enumerate(tx.tx_outs)
                   if public_key.to_string() == tx_out.public_key.to_string()
                   and (tx.id, i) not in spent_pairs]

We’re ignoring this function because it’s huge and ugly.

def fetch_balance(self, public_key):
    utxo = self.fetch_utxo(public_key)
    return sum([tx_out.amount for tx_out in utxo])

Fetches utxo, using public key, then grabs balance by iterating over the UTXO’s amount.

Last Refactor

This is the last refactor for the lesson, thank God.

def __init__(self):
    self.utxo = {}

We update the init function in Bank to this, and update throughout out code.

Then, Justin adds a new function, called outpoint. A formal definition can be found here so you can understand what it does. Basically – just references the outputs.

We can refactor other code using this idea of an outpoint, and it makes life a lot easier.

def fetch_utxo(self, public_key):
        return [utxo for utxo in self.utxo.values()
            if utxo.public_key.to_string() == public_key.to_string()]

This code grabs a UTXO for us, by iterating through the list of UTXO’s, and comparing the public key.

I’m done with this lesson right now, and there’s a lot I feel like I understand but a bit that I don’t get, so I’ll just come back to this later and update with the rest of the code.

Working through BUIDL Bootcamp: ECDSA Coin

Overview of Lesson

In my opinion, this lesson makes a lot of sense once you finish it. You’re kept a little bit in the dark while working through it, and even at the end, you can be a little confused about what is going on.

The fundamental thought of this lesson is this: We’re building a coin that can only be issued by using our “Bank Private Key”.

Next, we’ll build a validate function. This checks all the transfers in the list, to see if anyone wrongly executed the Transfer class.

This is an important function to run, because you can still use a coin that is wrongly transferred, and transfer it yourself. But, if you know the coin is stolen, you know it is not under valid ownership, therefore you should probably just leave it alone.

I would recommend playing around with the procedurally written code towards the end of the lesson, when we’re transferring the coin between Alice and Bob. Try and write a function that encapsulates the logic and still returns valid. I tried, and it kept throwing errors, but I had a better understanding of what I was doing and how the coin worked.

Notes: Overview of Digital Signatures

We generate a random number, called p. This is the private key.

We have a pair of huge numbers called G. We use special multiplications p * G. This returns our public key.

This special multiplication is called elliptic curve multiplication. It make sure that people cannot easily solve for our private key.

Signing a Message

If we wanted to sign a message, with our private key, we would:

  • generate R
  • Perform calculation to produce S

This calculation shows that we have possession of our private key, through a derivation.

However, this does not “show” the private key.

Overview of ECDSACoin

Key Structure:

We create the coin from the bank. Then we transfer to a particular person.

We write a function called issue():

def issue(public_key):
    message = serialize(public_key)

    signature = bank_private_key.sign(message)
    
    transfer = Transfer(
        signature=signature,
        public_key=public_key
    )
    
    coin = ECDSACoin([transfer])
    return coin

The important part here, is passing in the public key. This allows us to issue it to a particular person.

Validation:

We want to make sure that every coin is issued from the bank. If it is not issued from our bank, we need to throw an error.

We write a function called validate():

def validate(coin):
    transfer = coin.transfers[0]
    message = serialize(transfer.public_key)
    bank_public_key.verify(transfer.signature, message)

Working through BUIDL Bootcamp: PNG Coin

Fungibility means every coin is the same, or interchangeable.
Definition: In economics, fungibility is the property of a good or a commodity whose individual units are essentially interchangeable, and each of its parts is indistinguishable from another part.

We serialize the coins, because this is how we would transfer the data over the network.

Serialization is the process of converting data into a binary format.

In this lesson we learned:

  • Coins can be created.
  • Coins need to be validated.
  • Coins can be written to disk.
  • We understand how to make Coins, pass them as transfers to our class PNGCoin, validate those transfers, then write coins to disk.

Introduction to AJAX

History of AJAX

The pre-history to AJAX was a technology called “Livescript” developed by Netscape. This allowed users to interact with the browser using small scripts, a precursor to JavaScript.

Later a pseudo-asynchronous method was developed, using iFrames in order to change the content of a page, once it had been loaded and was termed “remote scripting”.

After the dotcom bubble, Microsoft added an API called IXMLHTTPRequest to Outlook Web Access which functions as an HTTP client for JavaScript. This allows the browser to download data, even after the page has been loaded.

Safari soon added support for this method in their 1.2 version of the browser, seemingly in response to the use of it within a social networking website called Orkut which allowed you to rate friends using a star system that was implemented in XMLHttpRequest.

The popularization of this method was caused by Jesse Garret, when he wrote a popular article entitled: Ajax: A New Approach to Web Applications, in which he coined the term AJAX.

The best early implementation of this technology came with the introduction of Gmail, which allowed asynchronous retrieval of email, which to that point had not existed within an email client.

Until recently, the main way to initiate asynchronous data retrieval was XMLHttpRequest, but with the recent introduction of ES6, we now have the Fetch API. Now we’re able to request data asynchronously using multiple methods.

Defining AJAX

Working with AJAX can be intimidating. When I first began to need to incorporate AJAX functionality within an application, I was a little nervous at first. It seemed as if there was a multitude of different definitions, and no one seemed to break them down easily enough. Let’s attempt to break down the various definitions surrounding AJAX.

AJAX

AJAX stands for Asynchronous Javascript And XML. It doesn’t describe a single technology, rather a range of technologies that are used to asynchronously communicate with the server. A more accurate acronym today would be AJAJ (but is rarely used), substituting JSON for XML.

However, AJAX is the dominant and more recognized acronym, so people tend to use AJAX instead.

JSON

JSON stands for Javascript Standard Notation which is an easy and modern approach to encoding data. It was created in 2002 by Douglas Crockford (ever heard of him?) as an alternative to XML

According to JSON.org, the main two ways JSON is structured is:
(a) by collection of name/value pairs
(b) an ordered list values.

Collection of name/values pairs is look a lot like:

{ "hello" : "world", "testing": "values" }

If you are unfamiliar with value pairs, you can copy this code, open the
browser console (CTRL + SHIFT + I on Chrome) and type var example = and paste in the code.

JSON is essentially written in the same structure as a JavaScript object, so you can type something like example.hello and it will return "world".

The second way JSON is structured is an ordered list of values. That essentially is just a JavaScript array, and is structured like this:

{ "testing" : [1,2,3,4,5,6]}

You can copy this too into the browser console, assign it a variable and work with it, almost exactly like a JavaScript array.

These two concepts can be combined, of course. You can write something similar to:

{ "hello": [1,2,3, "testing"], "blue": "is the best color" }

and it will be considered valid JSON.

To play around more with JSON, this is a great tool to learn what is valid and invalid.

XML

XML is an alternative standard to JSON. It stands for Extensible Markup Language and was created in 1996 as a standard for data encoding.

XML lost out to JSON for a few reasons, including; (1) XML didn’t have the data types JSON had, (2) JSON was easier on a computational level to encode and decode in comparison to XML, (3) JSON was practically built into the web (hyperbole), since JSON is a subset of JavaScript. This makes it much more practical to use JSON.

XML does have advantages such as: metadata, it is renderable by the browser, XML is actually a language which allows for advanced interaction and you can mix data types in XML.

Another big reason why XML lost out to JSON, was the movement from SOAP to REST. We won’t dive deeply into it here, but here is a great indepth article about the history of the movement from SOAP to REST.

XML is structured in a tag like, tree structure. It begins with a declarative statement around the structure, something similar to:

<?xml version="1.0" encoding="UTF-8"?>

Unlike HTML, it doesn’t have a set of tags that are required for the browser to interpret. Instead, you can make up your own set of tags to describe the data that is encoded within the XML similar to:

<clothing>
<hat>
<brand>Supreme</brand>
</hat>
</clothing>


If you’re interested in playing with XML, this online XML validator is a great tool to learning and messing around with XML.

XMLHttpRequest

XMLHttpRequest(XHR) is an API that allows asynchronous communications from the browser to the server.

Fetch

The Fetch API was integrated within ES6 and allows us another interface to communicate with the server asynchronously.

How AJAX Works

The following is an image that details how AJAX works from a graphical presentation. We’ll break this image down further into individual parts and describe them to you, so that you have a strong understanding of how AJAX functionality works from an implementation standpoint.

A description of how AJAX works

Step 1: Client Side – User interacts with the DOM

The first step in AJAX is the user interaction with the DOM. This can be a button click, an infinite scroll mechanism, lazy-loading images or any type of interaction with the browser that requests data from the server, without the page refreshing.

Typically, you will attach an event listener to a particular node in the DOM and send the asynchronous request when the event is triggered.

Step 2: Web Communication – An Asynchronous Web Request is Sent

After the user interacts with the DOM and an event listener is triggered, either an XMLHttpRequest or Fetch request is sent to the server.

You can send data along with the web request, including values to validate or user entered data (think a form submission with user input), to the server side.

Step 3: Server Side – Server Receives Asynchronous Request

Finally, the server side receives the request and data from the client side. You can begin processing the data, and formatting a response based off of the data sent along with the response.

Step 4: Server Side – Server sends back data

You can now begin to send back data from the request. Continuing our form example, if there was an error, it can be encoded in a JSON value pair:

{"error" : true }

or string/raw data:

"error" 

or XML

<?xml version='1.0' encoding='UTF-8'?>
   <error>
      <message>
         Broken
      </message>
   </error>
<?xml>

Step 5: Web Communication – Response from Server

The browser then receives the data from the server and processes it. Typically the response is processed by the Javascript, converted from JSON or XML and interpreted.

Step 6: Client Side – User Informed

Finally the client side is updated with a response. Sticking with our example, if there was an error response from the form, the page will update displaying with an error. If the submission was a success, we can update with a success message.

Brief Introduction to PushState in WordPress

Yesterday, I was developing a WordPress website and I needed to incorporate PushState in order to properly fulfill particular specifications.

I think it took me a lot longer than I needed, partially because I didn’t come across any easy documentation to understand how to work with PushState. So, consider this an introductory guide to using PushState.

What is PushState?

PushState is DOM function that allows us to change the history of a browser and changes the URL on call.

If you open the console right now and type:

history.pushState({}, "page 2", "bar.html"); 

You’ll see the URL change to https://samuelpedraza/programming/wordpress-pushstate/bar.html

Neat huh? Let’s break down the function:

If you type history in the browser, it’ll show you a snapshot of where you’ve been and a few attributes like the length, state, and so forth.

When you execute history.pushState({}, "", "/bar.html"), it will essentially push whatever elements you include, into this History object.

Our first parameter in history.pushState is {}, which is an empty object. You can pass a value pair into the object, similar to { a : "b"}, execute pushState in the browser, and then type history.state to note that the state is indeed {a : “b”}.

The second parameter is the title of the webpage. However, this isn’t supported by Mozilla and seems to be overall discouraged in using.

The third parameter is fairly obvious, being the URL that you want to set.

Using PushState

Now it the fun part, where we actually incorporate PushState within an application.

First, check out this repository and clone it to your local computer or copy the code to an instance on poopy.life. This is the theme that we will use in order to demonstrate PushState.

Next, go to whatever WordPress instance you are running and create posts with the categories “fruit”, “cars”, and “animals”. Assign three posts per category.

Let’s go file by file with an explanation of how it all fits together, and then we’ll demo it.

Style.css

Well, every theme needs a style.css file.

Single.php

For the individual posts.

Main.js

In this script, we grab all the radio buttons, and iterate through them, setting an eventlistener to execute our ugly function display_data on click.

Our display_data contains the bulk of the logic in our application. Let’s examine it now:

if(this.checked){
var get_data = this.value
history.pushState({page: get_data}, "", window.origin + "/" + get_data);
}

The first this we do is check to see if the radio button is checked, and if it is, then we grab the value of the radio button. Next, we execute the pushState function, changing the URL and passing the page data into the history object.

Note: We use window.origin in order to replace the entire URL. We don’t want to append over and over to the end of a URL.

var data = {
  action: "fetch_categories_post",
  category_slug: get_data
}

Next we prepare for the ajax post event by creating an object with an action field and a POST field of category_slug

// clear html
 jQuery("#element").html('');
 // initialize variable
 var information = "";

We then clear out the #element area, and initialize an empty string variable.

jQuery.post(window.location.origin + "/wp-admin/admin-ajax.php", data, function(response){
	// get response and parse
	response = JSON.parse(response);

	// prepare to display links
	for(var response_iterate = 0; response_iterate < response.length; response_iterate++){
		information += "<a href='/" + get_data + "/" + response[response_iterate].post_name + "'>" + response[response_iterate].post_title + "</a> <br>";
	}

	// display links
	jQuery("#element").append(information);
})

This is the last bulk of logic for our application. We post the data to the functions.php, get the response back, parse the response and then compile it into raw HTML, that we then append to webpage.

We then attach this function to the window “load” event, so we can display the proper links when the page is loaded.

Index.php & Categories.php

The index.php and categories.php webpage are very similarly structured.

 <?php wp_head(); ?>
 <form>
 	<div class="form-group">
 		<label>
 			Fruit
 			<input type="radio" name="display_cat" value="fruit" class="form-control" <?php $term = get_queried_object(); if($term->slug === "fruit"){ echo "checked"; } ?>>	
 		</label>
 	</div>
 	<div class="form-group">
 		<label>
 			Cars
 			<input type="radio" name="display_cat" value="cars" class="form-control" <?php $term = get_queried_object(); if($term->slug === "cars"){ echo "checked"; } ?>>
 		</label>
 	</div>
 	<div class="form-group">
 		<label>
 			Animals
 			<input type="radio" name="display_cat" value="animals" class="form-control" <?php $term = get_queried_object(); if($term->slug === "animals"){ echo "checked"; } ?>>
 		</label>
 	</div>
 </form>
 <div id="element">
 	
 </div>

 <?php wp_footer(); ?>

This code is from the categories.php page. If the URL is animals, for example, the radio box will be checked.

When the webpage is loaded, the proper posts associated with that category, are then displayed.

The index.php page is almost exactly similar, but without the if statement, that checks for the URL of the page.

Functions.php

The Functions.php is a very straightforward file. We register the main.js file, and then we have a function to process the AJAX request.

function load_js(){
     wp_enqueue_script('jquery', '', '', '', TRUE);
     wp_enqueue_script('mainJS', get_template_directory_uri() . '/main.js', '', '', TRUE);
 }
add_action('wp_enqueue_scripts', 'load_js');

Pretty straightforward code, registering the JavaScript and jQuery.

function fetch_categories(){
   $cat_slug = $_POST['category_slug'];

   $cat_posts = get_posts('category=' . get_cat_ID($cat_slug));

   echo json_encode($cat_posts);
   die();
}

This is fairly straightforward code. We get the POST request from the JS file, grab each post from the category, JSON encode it, and then send it back to the main.js file.

Conclusion

Overall, we’ve seen how to assemble a basic example of using PushState. We can grab and display different posts, without refreshing the entire page, while allowing the page to have indexable content.

Bitcoin & Protocol

Bitcoin is going to be a protocol.

Bitcoin is not currently a protocol.

Bitcoin is like the Internet. The Internet has 8 layers of infrastructure, that let you go on FaceBook. But it didn’t start with 8 layers.

Bitcoin has 1 ½ layers. The blockchain, and maybe Lightning Network.

We have to wait and see what Bitcoin layers on-top of itself. Then it will be very useable.

People don’t know what TCP/IP is or does. Perhaps people will barely know what Bitcoin is or does.

Programmer vs Engineer

Lately I’ve been diving deep into the fundamentals.

One thing I was quite interested in, was the underlying architecture of Git.

I didn’t understand was quite how Git stored information.

Then, I read about Hash Tables in Four Semesters of Computer Science in 5 hours. It was quite enlightening.

It made me realize the difference between Programmers and Engineers.

Engineers understand the system. Programmers use the system.

Maybe more directly, Engineers can build the system, use the system, critique the system, rewrite the system. Programmers can only use the system.

Frustrations and Programming

The most frustrated I get when I’m programming is when I focus on the outcome, and not the process.

You can learn how to program by focusing on the outcome. But I think the truly excellent programmers understand the process.

Example:

I learned Ruby on Rails lately. It abstracts away a lot of the process. I showed my friend, and he made fun of me, because he understands the magic of Rails, and I agree with him.

Rails is very outcome focused. Build an application, quickly. PHP is very processed based. Build an application, and understand deeply everything that goes on within it.