Code or Die Welcome to my kitchen

Yak shaving tips, Infosec, Astronomy, Gardening

This is my blog. Proud guardian of three cats and two dogs, I currently reside in San Antonio, Texas.

I'm interested in gardening, astronomy, infosec among other pursuits. About this site.

Past and current projects.. You can also browse the blog archive if you like.

Message of the Day: Under construction

Don't Act Surprised

I had an experience recently in my coder education that I had previously only read about in blog posts and twitter stories. It is when you state your ignorance of a certain topic to someone, (be they a peer, mentor or manager,) and their first reaction is complete and utter surprise. “You don’t know about (some topic in software development)? WOW! OMG”

There are few things more off-putting than this “acting surprised” phenomenon for the budding learner. It makes the entirely wrong assumption that knowledge that an experienced coder has internalized must be second nature to someone else, even if they are still learning the subject. This can be especially harmful for anyone who has just mustered the courage to ask the question in the first place on a topic that may be new or concepts that are still foreign.

At the coding bootcamp I attended we were encouraged to “expose your ignorance”. This is a great way to let go of any fears of appearing to know less than the sum total of all human knowledge, something that I have noticed some professionals in the wild seem to hold as an attainable goal. Putting the stuff one does not know very well out in the open provides a direct way of tackling these gaps and being able to learn and grow.

The concept here is that you may know some things that others don’t and vice versa. It is therefore completely natural to not know everything, (as strange as this sounds.) This reminds me of my beginning of the year post: It’s OK To Be Wrong

In a professional setting, if I am say, a coder with fifteen years of experience, and I ask a seemingly “obvious” question, then perhaps the person receiving that question could be permitted to act surprised over an apparent gap in knowledge. However, even in this instance the experience will most likely leave a bad taste in my mouth and I would think twice about asking that individual for help again in the future.

From the point of view of the mentor, just as one would not “call out” a child for not knowing what a mortgage is, how to file taxes, drive a car, or do any number of ‘adulting’ activities, one should also not act surprised (or worse) when a junior dev, intern or apprentice has expressed their ignorance over a topic that seems to the mentor to be trivially obvious.

Serious thought should be given to type of culture that one wishes to foster: a culture of openness and freedom to ask questions or one of closeted ignorance and constant fear of being judged for perceived shortcomings.

So the next time someone asks a question, please don’t act surprised.

Did You Miss Me?

Hello there, bloggy blog,

It’s been a while, so I thought I’d pop in and drop a quick post.

As I mentioned in a recent /now post, I’ve been super busy with my dev apprenticeship which is now entering the last phase. It’s been an amazing experience and I will be glad to share more about it in the coming weeks.

Although it may look like I have been neglecting you, my beloved reliable and nimble static Jekyll blog, astute readers (all three of you) will have noticed a few subtle improvements behind the scenes in the past few weeks:

Drafts

To my chagrin, I found that I posted a (naive) interpretation of ES6 JavaScript Promises before it was complete. This was not very Genuine Hacker™ of me, so that day I learned the hard way about creating a _drafts/ folder for my cobbled but not-quite-ready-for-peer-review blog posts. Adding that folder to my .gitignore file prevents pushing up any more half-baked ideas to the main repository.

Excerpts

Additionally, I wished to shorten the amount of scrolling that one had to do on the main index page just to get the bottom pagination links. This meant condensing posts into blurbs or snippets, and wouldn’t you just know it? Jekyll already has such a functionality in the Liquid template system, and it is called excerpts. Yet another great example to always RTFDocs, folks.

CNAME

I migrated from my GitHub-generated .io URL to this shiny new .com one. Namecheap had it on sale for 88¢ for the first-year, so I went for it. I kinda like it.

Google Analytics

Shoved this code snippet into my _includes/ folder.

Redcarpet to kramdown

Finally I updated Jekyll to 3.0 and saw that GitHub was leaving some ominous warning messages on the command line about the coming use of kramdown, one of a many types of Markdown parsers that have sprung up over the years. The message indicated kramdown would soon be used as a default for GitHub hosted webpages like this one.

Note: Starting May 1st, 2016, GitHub Pages will only support kramdown.

At the time I was on Redcarpet, which I had settled upon after a short survey revealed it provided what I needed: fenced code block syntax highlighting (via Pygments), strikethrough, superscript, and footnotes. Even tables were supported! The autolink extension was very nice also (wherein URLs in the Markdown document were automagically converted to anchor tags in markup.)

After the requisite panicking stage, I soon found out one of the main reasons why kramdown was chosen: it is blazingly fast. GitHub even provided a handy dandy page to help people update. Soon I was able to semi-smoothly make the transition.

Here are all the steps I took in excruciating detail. First, modify the _config.yml file to use kramdown for Markdown instead of Redcarpet, and Rouge instead of Pygments (which is also being deprecated,) for syntax highlighting. kramdown is “GitHub Flavored Markdown” so naturally the three-backtick (`) code blocks work just fine. More on this code syntax-highlighting later.

I still had footnotes, and strikeouts, but support for super or sub -scripts will have to wait. The workaround method of HTML in Markdown exists via <sup> and <sub> tags, but that still won’t work within code blocks. For me, this is not a tremendous issue, but I could see it being a problem for science equation publishers. Nevertheless LaTeX fully works in kramdown, in case I want to break out some Laws of Thermodynamics or Drake Equation posts.

All the previously autolinked URLs that were in my posts went back to being just plain strings, so I had to go back and fix them. C’est la vie.

Going back to the code syntax highlighting issue, one last thing that I wanted to implement was line numbers in my code blocks, since it would be much easier to reference specific points within the posts. I was able to accomplish syntax highlighting with Rouge which was replacing Pygments by applying the knowledge of this blog post: Syntax Highlighting in Jekyll With Rouge Thank you, Sacha!

However that post ends with the statement that line numbers are not yet supported, and that for code block line numbers “you’ll have to wait for a little while.” Luckily for us, a little while has passed, and I found a post a few months later on a different blog describing a very nice workaround for implementing line numbers in your Rouge code blocks on Jekyll. All credit is due to Minh Nguyen for this solution: JEKYLL LINE NUMBERS Thank you, Minh!

Good to be back

Yes, indeed. After stressing out about learning new and difficult/different stuff on work projects, it feels really good to just be able to poke around and have fun with a pet project like this blog. I hope this information helps the next person that may happen upon it. Cheers!

Addendum

I forgot to mention a final enhancement which was to modify the internal/external link behavior globally. kramdown helpfully provides anchor tags with the target="_blank" to open the link in another tab/window. In kramdown you can do this, on a per link basis:

[Link Text](Link URL){:target="_blank"}

However, being a good lazy programmer, I wanted to not worry about adding this to every past and future link, so I found a quick n’ dirty fix using jQuery.

Edit (December 2016): I have updated this using pure Vanilla Js so as not to require the entirety of the jQuery library for this simple function.

After including jQuery, add this JavaScript snippet to application.js:

jQuery(function ($) {
  //Change target attribute of external links
  var domain_root = document.location.protocol + '//' + document.location.host;
  var all_links = $('a').each(function (index, element) {
    if (element.href.substr(0, domain_root.length) !== domain_root) {
      element.target = '_blank';
    }
  });
});

Now every external link will open its own tab while internal links (say to /projects) will proceed in the same window as normal.

I like the way this blog is coming along as my own Incremental build model. Onwards and upwards!

What's The Deal With Closure?

Although closure is easy to understand in relatively simple terms, it was not until recently in my coding education that I discovered a few subtleties about the subject that clarified my understanding of it immensely.

Since I always love to demystify computer science and coding, let’s pull aside the curtain to take a look at what really is happening with this phenomenon.

History

A quick aside to cover some background on closure:

Closure first saw use in 1964 by Peter J. Landin who coined it as a lambda expression whose open bindings have been closed by (or bound in) the lexical environment, resulting in a closed expression, or closure.1 This concept was then used by Sussman and Steele in Scheme, a lexically scoped variant of LISP,2 and the rest is history.

In plain English, the definition of closure consists of two important concepts:

  1. A closure consists of a function or reference to a function.
  2. A closure also consists of the referencing environment, also known as the function’s lexical scope.

Although the definition of closure varies slightly between programming languages, this is the accepted general definition for languages that employ first-class functions, in other words languages that treat functions as first-class citizens.

A language that supports passing functions as arguments to other functions, returning them from other functions, and assigning them to variables or storing them in data structures is said to employ first-class functions.3 Some examples of programming languages that fit this description are Haskell, Ruby, Python and JavaScript.

What does this all mean, really?

All Ruby code blocks are really closures. What?? I know, it sounded strange to me too. Let’s get into examples.

Consider the following Ruby code snippet:

str = "Hello"
5.times do
	str2 = "world!"
	puts "#{str} #{str2}"
end

Output:

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

Nothing too groundbreaking here since we are just exploring Ruby code blocks and how they act as closures.

We see that the code within the block between the do and end was somehow aware of the value of the local variable outside the scope of the block, str. The opposite is not true; if we try to show str2 outside the block, it is an undefined local variable.

Why does this happen? It is because Ruby, (at least the most common version of Ruby known interchangeably as Matz’s Ruby Interpreter, Ruby MRI or CRuby), uses a copy of the current stack frame for each iteration of the block. This copy contains the environmental pointers that indicate what the variables were at the time of the creation of the block - kind of a snapshot, if you will.

Let’s see what happens if we change str inside the block.

str = "Hello"
5.times do
  str2 = "world!"
  puts "#{str} #{str2}"
  str = "Just kidding, goodbye"
end

Output:

Hello world!
Just kidding, goodbye world!
Just kidding, goodbye world!
Just kidding, goodbye world!
Just kidding, goodbye world!

We see that the block acknowledges the original environmental pointer of local variable str in the first iteration, but on subsequent iterations the pointer has changed, and it continues to honor this new definition until the end. The so-called snapshot of the current stack frame was changed after the first iteration because we changed the value of str inside the block.

Stack and heap memory

It sounds a bit complicated, but we can better visualize this if we learn about the concept of heap and stack memory, both of which are stored in the computer’s RAM (Random Access Memory). Programming languages will use RAM to assign variables to values. A variable is nothing more than a pointer to a specific address in memory that contains the corresponding value.

Stack memory is used for running your program, and from what I understand, each stack frame is like a single step in any given line of code. In the case of Ruby MRI, it is the underlying C code that determines the current stack frame. Stack memory is fast, but liable to overflow i.e. if the program goes into an infinite loop or otherwise runs out of memory due to a runaway process. Stack memory is nice in that as soon as a particular function or process is done, the variables deallocate or disappear, freeing up the space automatically.

Heap memory on the other hand is used to allocate a more permanent block of data apart from the current stack frame. This helps enable multithreading in applications, or applications that need to access the same memory address at the same time: each thread has its own stack but also a shared heap. Excessive fragmentation is a common danger for heap memory which makes it hard to allocate a large enough block to new processes. Luckily in garbage collection (GC) enabled languages such as Ruby, heap memory will persist only until the data’s environmental pointers disappear (in other words when a block ends), or (if GC is not available) until the programmer expressly deletes the data.

It is these details, as well as many other great reasons, that make C and C++ an asset to learn since many high level modern programming languages tend to abstract away these vital computer science concepts.

Bringing it home

As we saw in the above code examples, Ruby blocks refer to a specific environment (the lexical scope) as well as the functions and variables contained therein. This fulfills the requirements of closure as defined above.

Since both Procs and Lambdas are types of blocks in Ruby, these also act as closures. Closures, as it turns out, are everywhere and underpin some of the most important concepts in programming.

In JavaScript, we use callback functions to pass a function as an argument to another function to be returned or called later. Callback functions are really, you guessed it, closures. They contain a function and the lexical scope of said function at the time of its creation, including any object’s chain of inheritance.

Something to watch out for in JavaScript is this fact that excessive use of callback functions or closures will negatively impact processing speed and memory consumption.4 For this reason it is advisable to use an object’s prototype for methods so that they are not reassigned every time an object gets created via closure.

I love learning new (to me) underlying concepts and this fascinating concept of closure has many facets. If you spot any glaring errors or wish to give some feedback, please feel free to reach out to me on Twitter or shoot me an email.