<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Zach Alexander]]></title><description><![CDATA[Zach Alexander]]></description><link>http://zpalexander.com/</link><generator>Ghost 0.11</generator><lastBuildDate>Sun, 23 Jan 2022 21:01:14 GMT</lastBuildDate><atom:link href="http://zpalexander.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[5 Easy Ways to Improve Web Accessibility]]></title><description><![CDATA[Accessibility often feels like an overwhelming topic for software developers. Learn five concrete things you can do to make your website more accessible today.]]></description><link>http://zpalexander.com/5-easy-ways-to-improve-web-accessibility/</link><guid isPermaLink="false">ea5c8a5e-38c6-4d45-9442-afce272f6db4</guid><category><![CDATA[a11y]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Mon, 04 May 2020 17:40:03 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2020/05/a11y.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2020/05/a11y.jpg" alt="5 Easy Ways to Improve Web Accessibility"><p>These days it's hard to conceive of life without the internet. We have come a long way since the early days of the internet as a hobbyist's retreat full of text bulletin boards and personal "web logs". People now rely on the internet to pay bills, shop for necessities and even earn an income. The world is at your fingertips... if you can use a mouse... and see the screen... and hear the audio.</p>

<p>For many many people this is not as simple as it sounds. <a href="https://www.cdc.gov/ncbddd/disabilityandhealth/infographic-disability-impacts-all.html">One in four adults in the United States has a disability</a>. This means that a huge number of Americans are limited in the way they can interact with a computer, and might use it differently than your average user.</p>

<p>The good news is that humans are clever and adaptible and we have created all kinds of fantastic <a href="https://www.youtube.com/watch?v=SIm2MuJUCTE">assistive technology</a> tools like screen readers, pointing implements and voice control that help make the digital world accessible to everyone. And they usually work great out of the box as long as the websites they visit follow a few simple best practices.</p>

<p><img src="http://zpalexander.com/content/images/2020/05/1-mckEDgq4dmr4_zh2GNqKmw.jpeg" alt="5 Easy Ways to Improve Web Accessibility"></p>

<p>You don't have to be a screen reader master or have a team of professional accessibility testers to improve the accessibility of your website. Here are five easy steps you can take to make your website accessible without needing to be an accessibility expert:</p>

<h2 id="1addalttexttoyourimages">1. Add alt text to your images</h2>

<p>What happens when a non-sighted user encounters an image on a website?</p>

<p>If the content is a news article, the image might be a picture illustrating the scene. If its a how to listicle, it might be a diagram illustrating a particularly complicated step. </p>

<p>Screen readers aren't smart enough to be able to describe a picture on their own, so they rely on the information that the webpage gives them about that image. For example, if our webpage is displaying an article about penguins and we want to show an image of the penguin we're talking about, but we only include the bare image tag on the page, such as</p>

<pre><code>&lt;img src="847227.jpg" /&gt;  
</code></pre>

<p>all the screen reader user will hear is:</p>

<blockquote>
  <p>"image. eight four seven two two seven dot jpg." </p>
</blockquote>

<p>This means the screen reader user is missing out on some of the information the page has to offer. </p>

<p>The good news is this issue is extremely easy to correct. Introducing <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img#Accessibility_concerns">the humble alt tag</a>!</p>

<pre><code>&lt;img src="847227.jpg" alt="A penguin standing on a beach" /&gt;  
</code></pre>

<p>With the simple addition of this tag, the screen reader will switch from reading out the meaningless image file name, to reading:</p>

<blockquote>
  <p>"image. A penguin standing on a beach."</p>
</blockquote>

<p>With this one line addition, screen reader users now have all the same information that visual readers do.</p>

<p>Adding alt tags to your images helps sighted users too! We've all had the experience of being in a place with such bad cell service that the images on the webpage we're trying to load time out. Alt text to the rescue! Most browsers will display alt text if they're unable to load the image, so users with bad cell signal can still get all the information the page has to offer, even if they're not able to download the images.</p>

<p>This kind of outcome - a design that's intended to help disabled users helps non-disabled users as well - is known as the <a href="https://medium.com/@mosaicofminds/the-curb-cut-effect-how-making-public-spaces-accessible-to-people-with-disabilities-helps-everyone-d69f24c58785">"curb cut effect"</a>.</p>

<p><img src="http://zpalexander.com/content/images/2020/05/curbcut.jpg" alt="5 Easy Ways to Improve Web Accessibility"></p>

<p>A curb cut is a depression in the sidewalk curb that leads down to the street. Curb cuts were designed to make public streets accessible to wheelchair users, but today everyone benefits. Curb cuts are useful to moms with strollers, delivery drivers, people with temporary injuries and anyone who has ever walked down the street with their eyes locked on their phone.</p>

<p>Many web accessibility fixes are curb cuts for regular users. We'll see many more examples in this article.</p>

<h2 id="2fixyourlowcontrastfonts">2. Fix your low contrast fonts</h2>

<p>In the early and mid 2010's, <a href="https://www.contrastrebellion.com">lots of websites underwent redesigns</a> to make them more aesthetically beautiful and "web 2.0":</p>

<p><img src="http://zpalexander.com/content/images/2020/05/page2-img2.jpg" alt="5 Easy Ways to Improve Web Accessibility" trendy"="" low="" contrast="" website="" design"=""></p>

<p>Light font weights and delicate low-contrast accent colors were all the rage. The instinct was understandable - the web was shifting from a smaller, technical minded audience to a more general audience who businesses who businesses knew they could draw in with more attractive experiences.</p>

<p>Aesthetics are important but they aren't the ultimate goal of design. The most beautiful website is useless if the user can't read and interpret its content. And often poor readability doesn't get noticed during the design process. We developers and designers don't read the text the same way a visitor might.</p>

<p>Humans have done a lot of scientific research on what makes text on a background readable vs. not readable, and the W3C has actually published a document called <a href="https://www.w3.org/TR/WCAG21/">Web Content Accessibility Guidelines (WCAG) 2.1</a> that covers successful contrast guidelines. They boil readable text down into a single mathematical formula: <strong>the contrast ratio</strong>.</p>

<p>The contrast ratio explains the difference between the lightest color brightness and the darkest color brightness in a given range. It’s the relative luminance of each color. This article is meant to be purely practical, so I'm not going to go into the details of the math here, but you can read <a href="https://css-tricks.com/understanding-web-accessibility-color-contrast-guidelines-and-ratios/">this great CSS Tricks article</a> for more information.</p>

<p>What we care about here is that the minimum acceptable ratio for readablility is 4.5:1 for most body text and 3:1 for larger text.</p>

<p>If your eyes just glazed over, don't worry. There are automated tools that can do this for you. The simplest way to look up the ratio between two colors is with the WebAIM contrast checker: <a href="https://webaim.org/resources/contrastchecker/">https://webaim.org/resources/contrastchecker/</a></p>

<p>For the working web developer, I suggest the WCAG Contrast Checker extension for <a href="https://chrome.google.com/webstore/detail/wcag-color-contrast-check/plnahcmalebffmaghcpcmpaciebdhgdf">Chrome</a> and <a href="https://addons.mozilla.org/en-US/firefox/addon/wcag-contrast-checker/">Firefox</a>. </p>

<p><img src="http://zpalexander.com/content/images/2020/05/wcag-contrast-checker.jpg" alt="5 Easy Ways to Improve Web Accessibility"></p>

<p>It will automatically analyze your entire webpage for contrast problems and suggest fixes.</p>

<p>Just like alt text, better contrast is a curb cut. More readable color schemes mean less strain on the eyes, and more readable websites for users who might be trying to read your website on their phone while they're outside in bright sunlight.</p>

<h2 id="3makeclickableelementskeyboardfriendly">3. Make clickable elements keyboard-friendly</h2>

<p>Are the only interactive elements on your website <code>&lt;a&gt;</code>, <code>&lt;button&gt;</code> and <code>&lt;video&gt;</code> tags? Great, you're done! You can go onto the next section, because HTML5 handles keyboard accessibility by default. </p>

<p>If you've ever put an <code>onClick</code> on a <code>&lt;div&gt;</code> tag, however, read on...</p>

<p>There are a lot of reasons why someone would choose to use a keyboard rather than a mouse to interact with your website. The most obvious case is that non-sighted users can't see where the cursor is, but many people have physical limitations that make mouse precision difficult or impossible. Many more people are perfectly capable of using a mouse, but can't or don't want to for a variety of reasons. Maybe their mouse is just broken and they're trying to use your ecommerce website to buy a new one!</p>

<p>The simplest way for a keyboard user to navigate through a website is with the tab key. Pressing tab will shift the browser focus to the next interactive element on the page. Once the focus is on the element the user is interested in, they can hit the enter or space key to interact. You've probably seen this before when you accidentally bumped tab and one of the links on the page reacted by looking like this: </p>

<p><img src="http://zpalexander.com/content/images/2020/05/focused-link.JPG" alt="5 Easy Ways to Improve Web Accessibility"></p>

<p>As I mentioned at the beginning of the section, this works by default for HTML5 elements that are meant to be interactive. The problem is that websites do a lot more nowadays than present text and links.</p>

<p>Go to your website right now and hit the tab key. Is the element you expect highlighted? Keep pressing tab until you cycle through the entire page. Did every element you know is clickable get highlighted? If not, that means that your keyboard-only users are unable to interact with all parts of your website.</p>

<p>The good news is that for most simple websites, the solution is elementary: <a href="https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML">USE. SEMANTIC. TAGS.</a></p>

<p>Replace </p>

<pre><code>&lt;div&gt;Play video&lt;/div&gt;  
</code></pre>

<p>with </p>

<pre><code>&lt;button&gt;Play video&lt;/button&gt;  
</code></pre>

<p>Things the user clicks to make something on the page are buttons, so call them buttons in your HTML.</p>

<p>Replace </p>

<pre><code>&lt;div onclick="window.location = 'https://new.url'"&gt;Click here to go&lt;/div&gt;  
</code></pre>

<p>with </p>

<pre><code>&lt;a href="https://new.url"&gt;Click here to go&lt;/a&gt;  
</code></pre>

<p>Things the user clicks to navigate from the current page to another page are links, so call them links in your HTML.</p>

<p><em>"BUT ZACH!"</em> you say, <em>"I'm maintaing a legacy widget that renders a grid of clickable images and if I change them to buttons the 10,000 lines of spaghetti CSS I inherited break the whole page due to a browser bug!"</em></p>

<p>Ok. I get it. I'm also a working web developer. You should always try to use semantic HTML tags wherever possible, but if you can't for whatever reason, at least put <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex">tabindex</a> on interactive elements so keyboard users can get to them.</p>

<h2 id="4addaccessibilityaudittoolstoyourbuild">4. Add accessibility audit tools to your build</h2>

<p>No one can be an expert in everything. While I always encourage web developers to understand accessibility basic, I also understand that there's an infinite amount of interesting things to learn about computers, and its unrealistic to expect everyone to be an expert in every topic.</p>

<p>But, as with everything else in computing, you don't have to be an expert to benefit from the learnings of other programmers and computer scientists. You can approach it in the most programmer way possible: automate it!</p>

<p><img src="http://zpalexander.com/content/images/2020/05/programmer-automation.jpg" alt="5 Easy Ways to Improve Web Accessibility" what="" are="" all="" these="" programmers="" doing="" here="" then?"="" and="" the="" other="" answers="" shipping="" good="" code!"=""></p>

<p>There are a huge variety of excellent accessibility testing tools out there, and its almost guaranteed you can find one to fit your workflow.</p>

<p>I suggest that every software project have two levels of automated accessibility testing: a static code analyzer and an end-to-end system tester.</p>

<h3 id="staticcodeanalysis">Static Code Analysis</h3>

<p>Are you working with a modern JavaScript framework and using ESLint? Great, you're one <code>npm install</code> away from automated a11y code auditing. There are ESLint accessibility audit plugins for <a href="https://www.npmjs.com/package/eslint-plugin-jsx-a11y">JSX</a> and <a href="https://github.com/maranran/eslint-plugin-vue-a11y">Vue</a>.</p>

<p>There's a ton of great accessibility linting tools out there, here's a few I found in a 5 minute search:</p>

<ul>
<li><a href="https://github.com/DuaneOBrien/arialinter">AriaLinter</a></li>
<li><a href="https://accesslint.com/">AccessLint</a></li>
<li><a href="https://github.com/YozhikM/stylelint-a11y">Stylelint A11y</a></li>
</ul>

<p>Look around and be creative. If you don't see one for your specific use case, consider writing a plugin for your linter and putting it out there!</p>

<h3 id="endtoendsystemtester">End to End System Tester</h3>

<p>Only so many issues can be caught by statically reading code, so its also important to have a tool that loads your website in a browser and audits the actual page for issues.</p>

<p>I strongly suggest <a href="https://www.deque.com/axe/">Axe</a>. Its a fantastic accessibility testing toolkit that is already built into a lot of existing integration test solutions.</p>

<p>There's a <a href="https://github.com/avanslaars/cypress-axe">Cypress integration</a>, a <a href="https://github.com/GoogleChrome/lighthouse">Lighthouse integration</a>, a <a href="https://www.npmjs.com/package/ghost-axe">Ghostjs integration</a> and even a <a href="https://www.npmjs.com/package/ghost-axe">Py Selenium integration</a>. Here's <a href="https://github.com/dequelabs/axe-core/blob/develop/doc/projects.md">the full list of integrations</a>, I can pretty much guarantee that at least one of these will work for your use case.</p>

<p>I use the Cypress integration and love it.</p>

<p><img src="http://zpalexander.com/content/images/2020/05/cmd_log.png" alt="5 Easy Ways to Improve Web Accessibility"></p>

<p>It gives you a clear printout of what went wrong, with a rule name ("heading-order in the screenshot) that's easily searchible, so you can look up what the fix is without being an accessibility expert.</p>

<h2 id="5learnthebasicsofassistivetechnologiesandempathizewithyourusers">5. Learn the basics of assistive technologies and empathize with your users</h2>

<blockquote>
  <p>“The more you watch users carefully and listen to them articulate their intentions, motivations, and thought processes, the more you realize that their individual reactions to Web pages are based on so many variables that attempts to describe users in terms of one-dimensional likes and dislikes are futile and counter-productive. Good design, on the other hand, takes this complexity into account.”</p>
  
  <p>― Steve Krug, Don't Make Me Think: A Common Sense Approach to Web Usability</p>
</blockquote>

<p>We're all in this industry because we love using the web so much we wanted to be a part of shaping the experience. Apply that enthusiasm on behalf of your users. Ask them questions and listen to what they say. Seek diverse perspectives. Try interacting with your sites the way they do.</p>

<p>I have spent the past year gaining fluency in Apple's VoiceOver and it has been an exciting and humbling experience. I'm now able to articulate accessibility pain points in design discussions because I myself have felt those pain points. I know what frustrates screen reader users the most beacuse I've felt those very frustrations.</p>

<p>The internet is also full of passionate assistive technology users <a href="https://www.youtube.com/watch?v=TiP7aantnvE">sharing</a> <a href="https://www.youtube.com/watch?v=Ko9rDmMTEus">their</a> <a href="https://www.youtube.com/watch?v=QjKG4Tx9ER8">experiences</a> <a href="https://www.youtube.com/watch?v=0EQOZRIA-nA">with</a> <a href="https://www.youtube.com/watch?v=SDcvqfwOxOE">technology</a>. Listen and reach out!</p>

<p>Here's one of the talks that got me excited about accessibility in the beginning. Hopefully it inspires you as well.</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/0EQOZRIA-nA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>]]></content:encoded></item><item><title><![CDATA[5 Steps to Clean Code]]></title><description><![CDATA[<p>As a beginner developer working on pet projects at home, it's easy to argue that once code goes through the compiler, it's all the same. Right? </p>

<p>The flaw in this argument is that it assumes that all software developers do is write new code. The reality is that <a href="https://blog.codinghorror.com/when-understanding-means-rewriting/">we actually</a></p>]]></description><link>http://zpalexander.com/the-best-quotes-from-clean-code/</link><guid isPermaLink="false">26aeb9bf-72f5-4155-8dc9-b96ff76f497b</guid><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Wed, 20 Dec 2017 19:47:30 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2017/11/spiral-galaxy-min.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2017/11/spiral-galaxy-min.jpg" alt="5 Steps to Clean Code"><p>As a beginner developer working on pet projects at home, it's easy to argue that once code goes through the compiler, it's all the same. Right? </p>

<p>The flaw in this argument is that it assumes that all software developers do is write new code. The reality is that <a href="https://blog.codinghorror.com/when-understanding-means-rewriting/">we actually spend much more time reading and modifying existing code than writing new code</a>.</p>

<p><img src="http://zpalexander.com/content/images/2017/10/6a0120a85dcdae970b0120a86d7477970b-pi.png" alt="5 Steps to Clean Code"></p>

<p>For this reason, code cleanliness and readability are paramount to project success. More important than your framework choice, test coverage percentage or project management solution, is the cleanliness and readability of your code. </p>

<p>The seminal MIT textbook <a href="https://en.wikipedia.org/wiki/Structure_and_Interpretation_of_Computer_Programs">Structure and Interpretation of Computer Programs</a> sums it up perfectly:  </p>

<blockquote>
  <p>Programs must be written for people to read, and only incidentally for machines to execute</p>
</blockquote>

<p>Clean code matters to project success because starting a project quickly is rarely the problem; it's finishing quickly that's hard. As the <a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of your app increases, it becomes more and more difficult to add new features and diagnose bugs. It also becomes harder for programmers who are not specialists to make meaningful contributions to your project. Bad code compounds these issues. If you can't read the code, how can you understand what it's doing?</p>

<p><a href="https://xkcd.com/1513/"><img src="https://imgs.xkcd.com/comics/code_quality.png" alt="5 Steps to Clean Code" title=""></a></p>

<p>For this reason, the most important book I have ever read as a programmer is <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a> by Robert C. Martin. Everyone who writes code should read this book. </p>

<p>I could write a second book just pointing out all the great parts of the first book. But for now, I'd like to reflect on my favorite five quotes from the first five chapters. I hope these quotes will inspire you to push yourself and your team towards better, more maintainable code.</p>

<hr>

<h3 id="chapter1cleancode">Chapter 1 - Clean Code</h3>

<blockquote>
  <p>"You know you are working on clean code when each routine you read turns out to be pretty much what you expected."</p>
  
  <p>&#8211; Ward Cunningham (inventor of Wiki)</p>
</blockquote>

<p>If I had to pick a favorite quote from the book, this would be it. Clean code does what you'd expect it to do. In many ways, every other sentence in the book is just an attempt to clarify this concept.</p>

<p>But how can you know what the reader expects your code to do? Grab a friend and <a href="https://en.wikipedia.org/wiki/Code_review">do a code review</a>.</p>

<p><img src="http://zpalexander.com/content/images/2017/09/wtf.png" alt="5 Steps to Clean Code"></p>

<p>Take note of what makes sense to them right away, and what makes them say "WTF". If you get a lot of "WTFs", your code is not clean. Let's look at some more quotes from the book to identify common causes of "WTF".</p>

<hr>

<h3 id="chapter2naming">Chapter 2 - Naming</h3>

<blockquote>
  <p>"Programmers must avoid leaving false clues that obscure the meaning of code... Do not refer to a grouping of accounts as an <code>accountList</code> unless it's actually a List. The word means something specific to programmers. If a container holding the accounts is not actually a List, it may lead to false conclusions. So accountGroup or bunchOfAccounts or just plain accounts would be better."</p>
</blockquote>

<p>Most programmers know to stay away from <a href="http://wiki.c2.com/?BadVariableNames">poor variable names</a> like one or two character names (e.g. <code>a1</code>) or undescriptive placeholders (e.g. <code>mystring</code>). But an overly descriptive name can be just as bad or worse. If you call a variable <code>thingHashMap</code> and a year later your team decides to model "things" as a tree map instead, all of a sudden the variable name isn't just useless, its actually <em>harmful</em>.</p>

<p>Choose names that describe what the content does, not what it is.</p>

<hr>

<h3 id="chapter3functions">Chapter 3 - Functions</h3>

<blockquote>
  <p>"Functions should do one thing. They should do it well. They should do it only."</p>
</blockquote>

<p>Take a look at this example Spring MVC controller method:</p>

<pre><code class="language-java">@RequestMapping(value = {"/"})
public ModelAndView execute() {  
  ModelAndView mav = new ModelAndView();
  URL url = new URL("http://example.com");
  HttpURLConnection con = (HttpURLConnection) 
  url.openConnection();
  con.setRequestMethod("GET");
  con.setRequestProperty("Content-Type", "application/json");
  BufferedReader in = new BufferedReader(
  new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer content = new StringBuffer();
  while ((inputLine = in.readLine()) != null) {
    content.append(inputLine);
  }
  con.disconnect()
  mav.add("content", content);
  return mav;
</code></pre>

<p>If you take 20 or so seconds, you can parse through this code block to understand the basic control flow:</p>

<ul>
<li>Instantiate a ModelAndView object</li>
<li>Get content from <code>example.com</code> and put it into the ModelAndView object</li>
<li>Return the ModelAndView object</li>
</ul>

<p>But when reading the code, there are all kinds of other details that distract from that main purpose, e.g.</p>

<ul>
<li>Modeling the URL as a Java object</li>
<li>Casting the connection to the right type</li>
<li>Setting request method and headers</li>
<li>Setting up a BufferedReader to parse the response</li>
</ul>

<p>etc etc.</p>

<p>A reader can understand the control flow once they figure out which lines are details and which lines are important, but that takes unnecessary effort, and someone who isn't well versed in Java might get bogged down trying to understand what's happening here.</p>

<p>Now consider this refactored version, which accomplishes the same thing:</p>

<pre><code class="language-java">@RequestMapping(value = {"/"})
public ModelAndView execute() {  
  ModelAndView mav = new ModelAndView();
  mav.add("content", getExampleContent());
  return mav;
}
</code></pre>

<p>Even though this refactored version looks radically different, it still accomplishes the same control flow:</p>

<ul>
<li>Instantiate a ModelAndView object</li>
<li>Get content from <code>example.com</code> and put it into the ModelAndView object</li>
<li>Return the ModelAndView object</li>
</ul>

<p>The difference is that it only explicitly describes the important parts. The name of the method <code>getExampleContent()</code> tells the reader what is happening without bogging them down with the details. If they need to know how it works under the hood, they can jump to that method definition. </p>

<p>A well written main method should read like a story. Just like each of the methods it executes, it should do one thing, do it well, and do it only: execute the right methods in the right order.</p>

<hr>

<h3 id="chapter4comments">Chapter 4 - Comments</h3>

<blockquote>
  <p>"When you find yourself in a position where you need to write a comment, think it through and see whether there isn't some way to turn the tables and express yourself in code."</p>
</blockquote>

<p>Comments seem like a great way to make code more readable, but they can be dangerous as well. Why is this? Uncle Bob explains it best:</p>

<blockquote>
  <p>Because they lie. Not always, and not intentionally, but too often. The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can't realistically maintain them."</p>
</blockquote>

<p><img src="http://zpalexander.com/content/images/2017/11/mislabeled.jpg" alt="5 Steps to Clean Code"></p>

<p>My rule of thumb is as follows: </p>

<p><em>A comment is helpful if it describes <strong>what</strong> the code is used for. A comment is harmful if it describes <strong>how</strong> the code works.</em></p>

<p><em>Do</em> write comments that describe what your class represents, what problems it solves, etc. <em>Do not</em> write comments explaining the control flow of your code. Comments that explain "how" your code works are an indication that your code isn't clean. </p>

<p>If you need to explain why you've defined a variable or what a for loop is doing, write a named function instead. Document your code with your code.</p>

<hr>

<h3 id="chapter5formatting">Chapter 5 - Formatting</h3>

<blockquote>
  <p>"Code formatting is <em>important</em>. It is too important to ignore and it is too important to treat religiously. Code formatting is about communication, and communication is the professional developer's first order of business."</p>
</blockquote>

<p>When different blocks of code in the same project look different, it causes the reader to wonder whether the differences are functional or stylistic. This is bad, because it increases cognitive overhead.</p>

<p><img src="https://i.redd.it/qsgym5mcmyxz.png" alt="5 Steps to Clean Code"></p>

<p>Imagine a legacy Javascript project with single quotes in one file and double quotes in another. When reading through that project for the first time, it’s natural to wonder whether the double quotes are there for a reason, or if one programmer just preferred them. </p>

<p>Your reader should never have to ask this question, because it unnecessarily increases the overhead required to understand the project. If you're constantly forced to manually separate style differences from functionality in your brain, you're wasting energy on making a distinction that should have been made by the author.</p>

<p>As an author, don't make your reader work any harder than they already have to. It doesn't really matter what your style rules are - just pick some and <strong>be consistent</strong>. The best way to do so is by codifying them into linter rules and enforcing them at build time.</p>

<hr>

<p>I hope these tips have inspired you to push yourself and your team towards better, more maintainable code. If you haven't yet read <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a> by Robert C. Martin, you should pick up the book as soon as possible. It made me a better programmer, and it can make you a better programmer too.</p>]]></content:encoded></item><item><title><![CDATA[Switching to ZSH]]></title><description><![CDATA[Bash comes pre-installed on most terminals, but its not the best shell out there. Follow step by step instructions to get started using ZSH on Mac OS X.]]></description><link>http://zpalexander.com/switching-to-zsh/</link><guid isPermaLink="false">907d215b-05e3-4b60-8b74-8fc8cba6cc91</guid><category><![CDATA[Productivity]]></category><category><![CDATA[Fun]]></category><category><![CDATA[Getting Started]]></category><category><![CDATA[Tools]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Sun, 16 Apr 2017 00:39:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2017/04/cool-terminal-2.png" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2017/04/cool-terminal-2.png" alt="Switching to ZSH"><p><a href="https://en.wikipedia.org/wiki/Jeff_Atwood">Jeff Atwood</a> once famously proclaimed <a href="https://blog.codinghorror.com/we-are-typists-first-programmers-second/">"we are typists first, programmers second"</a>. While I think software development is <a href="https://developers.slashdot.org/story/10/12/25/2034201/Does-Typing-Speed-Really-Matter-For-Programmers">a little more complicated than that</a>, this quote brings up an important point: efficiency in software development hinges on the tooling we choose.</p>

<p>For the longest time I used <a href="https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a> as my UNIX shell. It got the job done. I would occasionally feel frustrated by a repetitive command or a missing feature, but there was usually an <a href="http://www.tldp.org/LDP/abs/html/aliases.html">alias</a> or <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html">script</a> I could apply like a bandaid to minimize the pain enough to keep going. I even switched to <a href="https://iterm2.com/">iTerm</a> several years back to improve my terminal emulator GUI. I worked with Bash for long enough that I managed to amass a pretty fancy <a href="http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html">.bash_profile</a> config. If you're curious about my config, <a href="https://gist.github.com/zpalexander/213a0b53b4bc128c0410195a79a6ea51">you can check it out for yourself</a>.</p>

<p>But I'm not here to help you optimize Bash. I'm here to tell you there's a better way.</p>

<hr>

<h3 id="whyzshisbetterthanbash">Why ZSH is better than Bash</h3>

<p>After a few years working in the software industry, I kept noticing that the shells of senior programmers often looked much different than mine did.</p>

<p>Whereas my shell looked something like this:</p>

<p><img src="http://zpalexander.com/content/images/2017/04/terminal-mac.png" alt="Switching to ZSH"></p>

<p>Theirs tended to look more like this:</p>

<p><img src="https://cloud.githubusercontent.com/assets/2618447/6316862/70f58fb6-ba03-11e4-82c9-c083bf9a6574.png" alt="Switching to ZSH"></p>

<p>I had heard talk of alternative shells like <a href="http://www.zsh.org/">ZSH</a> before, but I always assumed that the difference was purely aesthetic. It wasn't until I started working for a company whose cloud machines all came pre-configured with ZSH that I realized what I was missing.</p>

<p>ZSH provides a huge number of improvements over other shells and I could write an entire post just comparing and contrasting the benefits and drawbacks. Instead, I'll provide you with <a href="//www.slideshare.net/jaguardesignstudio/why-zsh-is-cooler-than-your-shell-16194692">this excellent slide deck</a> about the benefits of ZSH over Bash:</p>

<iframe src="//www.slideshare.net/slideshow/embed_code/key/1XBPbsul67hF67" width="595" height="485" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe>

<hr>

<h3 id="gettingstartedonmacosx">Getting Started on Mac OS X</h3>

<p>First let's cover the basics of getting ZSH set up on your Mac. The good news is that you probably already have ZSH on your system. </p>

<h4 id="1installzsh">1. Install ZSH</h4>

<p><img src="https://ih0.redbubble.net/image.154489147.8220/flat,800x800,075,f.jpg" alt="Switching to ZSH"></p>

<p>Let's get started by running <code>which zsh</code> in whatever shell you're currently using. If you have the executable on your system, <code><a href="https://linux.die.net/man/1/which">which</a></code> should output <code>/bin/zsh</code> or something similar.</p>

<p>If <code>which</code> instead outputs <code>zsh not found</code>, you can install zsh easily with <a href="https://brew.sh/">Homebrew</a>. Just run <code>brew install zsh</code>.</p>

<p>I also strongly recommend using <a href="https://iterm2.com/">iTerm2</a> as your terminal emulator app on Mac OS X. You can download it <a href="https://iterm2.com/downloads/stable/latest">here</a>.</p>

<h4 id="2setzshasyourdefaultshell">2. Set ZSH as your default shell</h4>

<p>The actual process for changing your default shell from Bash to ZSH is extremely easy. Just run <code>chsh -s /bin/zsh</code>. </p>

<blockquote>
  <p><strong><em>Note</em></strong> that you'll need to supply the correct path your ZSH binary which you can get with the <code>which zsh</code> command we used earlier. <a href="https://linux.die.net/man/1/chsh">Click here</a> for more information on the <code>chsh</code> command.</p>
</blockquote>

<p>That's it! Close and reopen your terminal. You're now using ZSH!</p>

<h4 id="3installazshconfigurationmanager">3. Install a ZSH configuration manager</h4>

<p><img src="https://camo.githubusercontent.com/5c385f15f3eaedb72cfcfbbaf75355b700ac0757/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6f686d797a73682f6f682d6d792d7a73682d6c6f676f2e706e67" alt="Switching to ZSH"></p>

<p>In the old days, configuring ZSH manually took a lot of time and effort. Thankfully, ZSH has a large and devoted user community which has produced a few tools to help with writing and sharing ZSH configurations.</p>

<p>The two big players are <a href="http://ohmyz.sh/">Oh My ZSH</a> and <a href="https://github.com/sorin-ionescu/prezto">Prezto</a>. </p>

<blockquote>
  <p><strong><em>tl;dr</em></strong> Oh My ZSH has a larger community, but Prezto performs better with a large number of modules installed.</p>
</blockquote>

<p>I use <a href="http://ohmyz.sh/">Oh My ZSH</a> since it has a wider variety of themes and plugins. Its also the most "standard" of all options, which means a larger community and better support. If you hit a wall early with Oh My ZSH, feel free to try out alternatives.</p>

<p>Installing Oh My ZSH is pretty easy. You can find <a href="https://github.com/robbyrussell/oh-my-zsh#basic-installation">CURL and WGET instructions here</a>.</p>

<p>Run the command of your choice and that's it. One and done.</p>

<h4 id="4chooseatheme">4. Choose a theme</h4>

<p><img src="http://zpalexander.com/content/images/2017/04/zsh-theme-list-1.png" alt="Switching to ZSH"></p>

<p>Setting a custom theme with Oh My ZSH is simple. Oh My ZSH comes bundled with a bunch of themes by default. You can find a <a href="https://github.com/robbyrussell/oh-my-zsh/wiki/themes">list with screenshots on their wiki</a>. If you want to see the files on your local filesystem, they live in <code>~/.oh-my-zsh/themes</code>.</p>

<p>Once you've picked a theme, open the file <code>~/.zshrc</code> in the text editor of your choice. Towards the top of the file you should see a value <code>ZSH_THEME</code>. Change the value of the string to the name of the theme, save the file, and then run <code>source ~/.zshrc</code> to pick up the changes.</p>

<p>Check out the <a href="https://github.com/robbyrussell/oh-my-zsh#custom-plugins-and-themes">Oh My ZSH README</a> for info on how to install custom themes.</p>

<h4 id="5addplugins">5. Add plugins</h4>

<p>Oh My ZSH's best feature is its ability to manage custom ZSH plugins. Setting up a list of custom plugins works just like changing themes. Open <code>~/.zshrc</code> in a text editor and look for a line that looks something like <code>plugins=(git)</code>. Check out the comment two lines up for an example of how to add to this list.</p>

<p>Just like with themes, you can browse bundled plugins in <a href="https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins">a list on the Oh My ZSH wiki</a>, or you can browse the files locally at <code>~/.oh-my-zsh/plugins</code>. Custom plugins can also be installed. Check out the <a href="https://github.com/robbyrussell/oh-my-zsh#custom-plugins-and-themes">Oh My ZSH README</a> for more info.</p>

<p>I'm a relative newbie which makes me a bad resource, but here's a list of the plugins I'm currently using:</p>

<ul>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/colorize">colorize</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/colored-man-pages">colored-man-pages</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/command-not-found">command-not-found</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/cp">cp</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/extract">extract</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/git">git</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/npm">npm</a></li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/web-search">web-search</a></li>
</ul>

<h4 id="6customizeyourexperience">6. Customize your experience</h4>

<p>Now that you've got ZSH and Oh My ZSH set up, the possibilities for customization are nearly endless. You can add custom themes and plugins, write your own custom aliases or configure advanced auto-completion for the tools you use most commonly. A couple good places to get started are <a href="https://grml.org/zsh/zsh-lovers.html">zsh-lovers</a>, the <a href="https://linux.die.net/man/1/zsh">ZSH man page</a> and the <a href="http://ohmyz.sh/community/">Oh My ZSH community page</a>.</p>

<p>As a VIM lover, one addition I personally made was to add a command mode to my shell so that I could use VIM keybindings to navigate around the text of my commands. You can do this with <code>bindkey -v</code>.</p>

<p>Bonus shot of my terminal (PII grayed out):</p>

<p><img src="http://zpalexander.com/content/images/2017/04/my-terminal-screenshot-2.png" alt="Switching to ZSH"></p>]]></content:encoded></item><item><title><![CDATA[Migrating from Mocha to AVA]]></title><description><![CDATA[<p><a href="https://github.com/avajs/ava"><img src="http://zpalexander.com/content/images/2016/08/header-1.png" alt="AVA logo" title=""></a></p>

<p>Ever since I ditched jQuery soup and started writing proper JavaScript applications, I've <a href="http://sd.jtimothyking.com/2006/07/11/twelve-benefits-of-writing-unit-tests-first/">written unit tests</a> for my frontend code. And for as long as I've written JavaScript unit tests, I've used <a href="https://mochajs.org/">Mocha</a>. Mocha has been the de facto test runner in the JavaScript community for a while now. If</p>]]></description><link>http://zpalexander.com/migrating-from-mocha-to-ava/</link><guid isPermaLink="false">6ccc3a51-68be-44bd-97dc-1234bef10a9b</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Sat, 15 Oct 2016 21:45:42 GMT</pubDate><content:encoded><![CDATA[<p><a href="https://github.com/avajs/ava"><img src="http://zpalexander.com/content/images/2016/08/header-1.png" alt="AVA logo" title=""></a></p>

<p>Ever since I ditched jQuery soup and started writing proper JavaScript applications, I've <a href="http://sd.jtimothyking.com/2006/07/11/twelve-benefits-of-writing-unit-tests-first/">written unit tests</a> for my frontend code. And for as long as I've written JavaScript unit tests, I've used <a href="https://mochajs.org/">Mocha</a>. Mocha has been the de facto test runner in the JavaScript community for a while now. If it gets the job done and everyone uses it, then I should use it too. Right?</p>

<p><img src="http://zpalexander.com/content/images/2016/08/busy.jpg" alt="Technical debt cartoon"></p>

<p>This has been my philosophy for the past few years, and Mocha has been more or less fine. Recently, however, I've heard a lot of buzz about a new test runner called <a href="https://github.com/avajs/ava">AVA</a>. Wanting to see what all the fuss was about, I migrated one of my project's test suites from Mocha to AVA. Since then I haven't been able to go back.</p>

<hr>

<h3 id="whatswrongwithmochaanyway">What's wrong with Mocha anyway?</h3>

<p>It wasn't until after migrating to AVA that I realized how much Mocha was holding me back. Mocha seems like a good enough tool until you realize its shortcomings:</p>

<h5 id="globals">Globals</h5>

<p>Mocha implicitly depends on global variables like <code>describe</code> and <code>it</code>. Some assertion libraries even extend built-in prototypes! Implicit dependencies like this are confusing to new developers and make it a pain to properly lint your code without writing a bunch of exceptions.</p>

<p>AVA's dependencies are all explicit. Instead of writing:</p>

<pre><code class="language-javascript">describe('My Thing', () =&gt; {  
  it('should do a thing', () =&gt; {
    expect(true).toBeTrue();
  });
});
</code></pre>

<p>and praying that <code>describe</code> and <code>it</code> will be defined, instead you can explicitly declare your dependency to AVA at the top of your file and be sure it'll work:</p>

<pre><code class="language-javascript">import test from 'ava';

test('foo', t =&gt; {  
    t.true(true);
});
</code></pre>

<p>Aahhh. That's better.</p>

<h5 id="sharedstate">Shared State</h5>

<p>Most testing frameworks, Mocha included, provide <code>beforeEach</code> and <code>afterEach</code> hooks in addition to serial test running. The combination of serial tests and before/after hooks can sometimes encourage developers to share state between unit tests. This is a huge no no, because unit tests are <a href="http://programmers.stackexchange.com/a/64308">supposed to be</a> completely independent of one another. Shared state can cause tests to behave in unexpected ways.</p>

<p>AVA runs tests each test as a separate Node.js process. This means that you can change the global state of one test file without affecting another. AVA does allow you to run tests in serial if you have a good use case, but it can't be done by default. No more stateful gotchas.</p>

<h5 id="serialtestrunning">Serial Test Running</h5>

<p>Running things one after another is easy to understand for people who come from synchronous programming backgrounds. But JavaScript is async! There's no reason to force tests to wait for one another when JavaScript can run them concurrently. Mocha is slower than it needs to be.</p>

<p>AVA corrects this problem by running each test as a <a href="https://github.com/avajs/ava#what-is-the-difference-between-concurrency-and-parallelism">separate Node.js process</a>. This means faster tests that take advantage of multi-core CPUs. The AVA devs <a href="https://github.com/sindresorhus/pageres/commit/663be15acb3dd2eb0f71b1956ef28c2cd3fdeed0">provide a case study</a> where switching from Mocha brought the testing time of a project from 31 seconds to 11 seconds.</p>

<hr>

<h3 id="migrationfaq">Migration FAQ</h3>

<h5 id="howdoihandleasynccode">How do I handle async code?</h5>

<p>AVA is asynchronous by default. No more monkeying around with <code>done()</code>.</p>

<pre><code class="language-javascript">import test from 'ava';

test('async test', t =&gt; {  
  return Promise.resolve(1)
    .then(result =&gt; {
      t.is(result, 1);
    });
});
</code></pre>

<p>It just works.</p>

<h5 id="howdoisetupmocking">How do I setup mocking?</h5>

<p>AVA doesn't have any built in mocking features, but mocking is trival to set up with <a href="http://sinonjs.org/">Sinon.js</a>. You can do all the same Sinon mocking with AVA that you can do with Mocha.</p>

<pre><code class="language-javascript">import test from 'ava';  
import sinon from 'sinon';

const myFunction = sinon.spy();

test('my function ran', t =&gt; {  
  myFunction();
  t.true(myFunction.called);
});
</code></pre>

<h5 id="howdoireportcodecoverage">How do I report code coverage?</h5>

<p>AVA unfortunately <a href="https://github.com/avajs/ava#code-coverage">does not support vanilla istanbul</a> due to the way it uses subprocesses. Thankfully you can just use <a href="https://github.com/istanbuljs/nyc">NYC</a> instead, which is a CLI wrapper for Istanbul with support for subprocesses. NYC is extremely easy to set up: just run <code>npm i nyc --save-dev</code> in your project and preface your test command with the <code>nyc</code> command.</p>

<pre><code class="language-javascript">{
  "script": {
    "test": "nyc ava"
  }
}
</code></pre>

<p>That's it. You'll get code coverage printed every time you run <code>npm test</code>, and NYC will also save the printout in a directory in your project's root.</p>

<h5 id="howdoiconfigureavatowritetestsines2015">How do I configure AVA to write tests in ES2015?</h5>

<p>Its really easy. Just <a href="https://github.com/avajs/ava#es2015-support">follow the steps in the README</a> on how to hook up Babel and you're done.</p>

<hr>

<p>Hopefully this convinces you to at least give AVA a try! Now that I've migrated my JavaScript projects to AVA, I can't see why I would choose Mocha again.</p>]]></content:encoded></item><item><title><![CDATA[Your Referer Is Showing]]></title><description><![CDATA[Learn how referer headers work and how to disable them in order to ensure your privacy and security on the web.]]></description><link>http://zpalexander.com/your-referer-is-showing/</link><guid isPermaLink="false">269e1e6a-cfe3-4768-ba1f-e3c36f5697c8</guid><category><![CDATA[Security]]></category><category><![CDATA[Privacy]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Fri, 08 Jul 2016 19:54:31 GMT</pubDate><content:encoded><![CDATA[<p>Did you know that every time you click through to a new webpage, you're voluntarily telling that new webpage where you came from?</p>

<p>This isn't a trick by the NSA, its just the way the web works. As most people know, whenever you click a hyperlink, the browser sends a request to the resource on the other end of the link. What most people don't realize is that by default the request contains the referrer field, which indicates the page where the user clicked the link.</p>

<p><img src="http://zpalexander.com/content/images/2016/07/surveillance.jpg" alt="Surveillance camera"></p>

<p>Visible referer headers can lead to all kinds of privacy problems. The information contained in a referrer can be abused to track website visitors across the internet, especially when combined with cookies and other tracking techniques. Search engines in particular are especially bad when it comes to giving away information through referer headers since they often include the search terms used to find a web page:</p>

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Remember kids, when you embed other people’s stuff in your page, they see the referer header.</p>&mdash; Nick Craver (@Nick_Craver) <a href="https://twitter.com/Nick_Craver/status/593724330338611201">April 30, 2015</a></blockquote>  

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Oookay so <a href="http://t.co/Cp0u2ghdIf">http://t.co/Cp0u2ghdIf</a> sends your personal info to third-party sites via the Referer header... <a href="https://t.co/ixy1nZjB2v">https://t.co/ixy1nZjB2v</a></p>&mdash; Chris (@leftside) <a href="https://twitter.com/leftside/status/558072479798013952">January 22, 2015</a></blockquote>  

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>In addition to privacy concerns, leaky referer headers can also lead to all kinds of nasty security exploits:</p>

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">&quot;Referer Header Based Blind SQL Injection Explained With Example&quot;<br>Haider Mahmood.<a href="https://t.co/pICnVm0TZr">https://t.co/pICnVm0TZr</a></p>&mdash; KS7000 (@ks7000) <a href="https://twitter.com/ks7000/status/713154427088011264">March 25, 2016</a></blockquote>  

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">WP Slimstat = 4.1.5.2 - Referer Header Cross-Site Scripting (XSS) <a href="https://twitter.com/hashtag/wordpress?src=hash">#wordpress</a> <a href="https://twitter.com/hashtag/websecurity?src=hash">#websecurity</a> <a href="http://t.co/1B1I6aMiAB">http://t.co/1B1I6aMiAB</a></p>&mdash; eXploit.By (@exploitby) <a href="https://twitter.com/exploitby/status/625410275303231489">July 26, 2015</a></blockquote>  

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>As a side note, before you flip out about my misspelling of the word "referer", be aware that I'm not spelling it wrong by accident - <a href="https://en.wikipedia.org/wiki/HTTP_referer">this is how browser implementations spell it</a>:</p>

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">4 hours of debugging later: The HTTP spec INTENTIONALLY misspells the &quot;referer&quot; header with 3 R&#39;s instead of 4.  <a href="https://t.co/qT1M27yXOb">https://t.co/qT1M27yXOb</a></p>&mdash; Chris Johnson (@CJcodes) <a href="https://twitter.com/CJcodes/status/726553497739599872">April 30, 2016</a></blockquote>  

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>Now that we've got linguistics out of the way, let's talk about how to solve this problem.</p>

<hr>

<h3 id="disablingrefererheadersinfirefox">Disabling Referer Headers in Firefox</h3>

<p>Firefox provides the easiest method for disabling referer headers:</p>

<ol>
<li><p>Type <code>about:config</code> in the URL bar and hit enter. You may need to click through the "I'll be careful, I promise!" warning if you haven't visited this config page before.</p></li>
<li><p>In the search bar, type <code>network.http.sendRefererHeader</code></p></li>
<li><p>Double click on the preference's "Value" text box when it appears and set the value to either 0, 1 or 2.</p></li>
</ol>

<p><img src="http://zpalexander.com/content/images/2016/07/firefox-about-config.png" alt="Firefox about:config"></p>

<p>The value you enter determines how Firefox will handle your Referer Headers in the future:</p>

<ul>
<li><strong><em>Value 0</em></strong> - completely disables the Referer Header. This provides the most privacy, but may break some websites (more on this later)</li>
<li><strong><em>Value 1</em></strong> - Sends a Referer Header when clicking on a link, but not when loading images on a page. This will prevent </li>
<li><strong><em>Value 2</em></strong> - Default setting which sends all Referer Headers</li>
</ul>

<hr>

<h3 id="disablingrefererheadersinchrome">Disabling Referer Headers in Chrome</h3>

<p>Chrome unfortunately doesn't provide the same easy configuration as Firefox, but that's not to say that disabling referer headers on Chrome can't be done.</p>

<p>The easiest way to disable referer headers in Chrome is to head over to the Chrome Store and grab the <a href="https://chrome.google.com/webstore/detail/referer-control/hnkcfpcejkafcihlgbojoidoihckciin">Referer Control</a> browser extension.</p>

<p><img src="http://zpalexander.com/content/images/2016/07/referercontrol.png" alt="Referer Control screenshot"></p>

<p>If you don't want to bloat your browser with additional extensions, you can also launch the Chrome app with the <code>--no-referrers</code> flag. If you're on Windows, you can do this by editing the Browser's shortcut icon execution path, e.g. <code>"C:\Users\Username\AppData\Local\Google\Chrome\Application\chrome.exe" --no-referrers</code>.</p>

<hr>

<h3 id="otherbrowsers">Other Browsers</h3>

<p>I was unable to find information on how to block referer headers in Opera, Safari and Internet Explorer. As such, I feel that it is not sensible for a privacy-conscious user to perform personal browsing via any of these web browsers.</p>

<p>If anyone has information on how to disable referer headers on any browsers aside from Mozilla Firefox and Google Chrome I'd be very interested to know about it. Drop me a line on Twitter at <a href="https://twitter.com/zpalexander">@zpalexander</a>.</p>

<hr>

<h3 id="sideeffects">Side Effects</h3>

<p>Disabling sending of header referers can break some sites. Some web developers use header referers to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross Site Request Forgery</a>:</p>

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">If you want to disable the Referer header, do it in a way that still sends it within the domain. Otherwise you break many CSRF protections.</p>&mdash; Paul McMillan (@PaulM) <a href="https://twitter.com/PaulM/status/606573592076091392">June 4, 2015</a></blockquote>  

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>In my opinion, <a href="https://gispunt.wordpress.com/2012/01/10/why-using-referer-header-as-a-security-mechanism-is-a-bad-idea/">those developers are wrong</a> to rely on an easy to forge header in such a way that potentionally breaks accessibility. Nevertheless, its important to remember that disabling your browser's referer headers can cause problems such as these.</p>

<p>In conclusion, remember that referer headers are only passed on when you click through a link. Cutting and pasting a web address into a browser’s URL bar, or typing it out manually, will also prevent any referer headers being sent to the visited website. For more information, check out <a href="https://blog.fastmail.com/2016/06/20/everything-you-could-ever-want-to-know-and-more-about-controlling-the-referer-header/">this comprehensive article</a> on the subject.</p>]]></content:encoded></item><item><title><![CDATA[Unit Testing In Java Play]]></title><description><![CDATA[Learn how to write unit tests for the Java Play 2.x framework by leveraging Guice dependency injection.]]></description><link>http://zpalexander.com/unit-testing-in-java-play/</link><guid isPermaLink="false">e1857841-bf2d-44f4-bab5-d6ae19db5fb1</guid><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Wed, 06 Apr 2016 02:59:00 GMT</pubDate><content:encoded><![CDATA[<p>The <a href="https://www.playframework.com/">Java Play framework</a> is a Java development framework built on top of <a href="http://akka.io/">Akka</a> that makes it easy to write scalable web services in either Java or Scala. It is fully RESTful and comes with a number of great features such as hot reloading, type safety and in-browser errors. If you are a Java developer who hasn’t yet tried Play, you are missing out on one of the best web frameworks ever developed for the language.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/play_full_color.png" alt="Java Play Logo"></p>

<p>The advent of Play Version 2.4 brought with it some significant architectural changes. Most notably, version 2.4 introduced dependency injection via Guice as the new default architecture for managing dependencies between Play classes. Dependency injection is great in that it allows developers to write less tightly-coupled code. From <a href="https://en.wikipedia.org/wiki/Dependency_injection">Wikipedia</a>:</p>

<blockquote>
  <p>This means the client code does not need to know about the injecting code. The client does not need to know how to construct the services. The client does not need to know which actual services it is using. The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services. This separates the responsibilities of use and construction.</p>
</blockquote>

<p>Play depends on Google’s <a href="https://github.com/google/guice">Guice library</a> for resolving dependency injection. If you want one class of your Play code to depend on another, you simply annotate the classes constructor, pass the dependency you want to inject in as an argument, and Guice takes care of the rest. For example:</p>

<pre><code class="language-java">public class DataSaver {

    private ApiClient apiClient;

    @Inject
    public DataSaver(ApiClient apiClient) {
        this.apiClient = apiClient;
    }

    public int getAndSaveData() { 
        ArrayList&lt;String&gt; data = apiClient.getData();
        // Do data saving operation here 
        int itemsSaved = saveData(data); 
        return itemsSaved;
    } 
}
</code></pre>

<p>In this example, the <code>ApiClient</code> is passed as a parameter to the DataSaver class, which means that we can pass in anything to serve as the ApiClient instance. No more tightly coupled dependencies! Let’s see an example of how this makes unit testing easier. We’re using <a href="http://junit.org/junit4/">JUnit</a> for test assertions and <a href="http://mockito.org/">Mockito</a> for mocks / stubs:</p>

<pre><code class="language-java">public class DataSaverTest {  
    @Mock
    private ApiClient mockApiClient;

    private DataSaver dataSaver;

    /**
     * The setup block creates a mock instance of ApiClient
     * that we subsequently inject into DataSaver
     */
    @Before
    public void setup() {
        // Mock the ApiClient so that we're
        // not actually querying the API
        mockApiClient = mock(ApiClient.class);

        // Make up some fake data
        ArrayList&lt;String&gt; fakeData = new ArrayList&lt;&gt;();
        fakeData.add("point 1");
        fakeData.add("point 2");

        // Use Mockito to stub out method responses
        when(mockApiClient.getData()).thenReturn(fakeData);

        // Set up test module that injects mocks 
        // instead of actual classes
        dataSaver = new DataSaver(mockApiClient);
    }

    /**
     * Once the mock version of ApiClient has been injected,
     * we can call the .getAndSaveData() method without having
     * to worry about our unit test interacting with the actual API
     */
    @Test
    public void canSaveData() {
        int expectedResult = 2;
        int actualResult = dataSaver.getAndSaveData();
        assertEquals(actualResult, expectedResult);
    }
}
</code></pre>

<p>Using dependency injection makes mocking out the <code>ApiClient</code> instance so easy. No more fighting with integration tests just to make your dependencies work. Simply create the mock instance of the class as on line 15, mock whatever method results you need to and feed in the mock as on line 27. Writing tests has never been easier. Now get out there and test your code!</p>]]></content:encoded></item><item><title><![CDATA[Debugging "Unknown Provider" In Minified Angular.js]]></title><description><![CDATA[<p>For the past few months I’ve been working on an <a href="https://angularjs.org/">AngularJS</a> app that makes use of <a href="https://material.angularjs.org/latest/">Angular Material</a> as a Bootstrap-like front-end library. I recently had to solve one of the hardest bugs I’ve ever faced in Angular, and I’d like to share my debugging technique with</p>]]></description><link>http://zpalexander.com/debug-unknown-provider-minified-angularjs/</link><guid isPermaLink="false">c9791a19-e391-4f85-9930-c26599a4e931</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Angular]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Thu, 28 Jan 2016 04:09:00 GMT</pubDate><content:encoded><![CDATA[<p>For the past few months I’ve been working on an <a href="https://angularjs.org/">AngularJS</a> app that makes use of <a href="https://material.angularjs.org/latest/">Angular Material</a> as a Bootstrap-like front-end library. I recently had to solve one of the hardest bugs I’ve ever faced in Angular, and I’d like to share my debugging technique with anyone who might encounter the same problem down the road. While the bug was related to the use of Angular Material in my case, it could occur in vanilla Angular as well, so don’t stop reading just yet!</p>

<hr>

<h4 id="theproblem">The Problem</h4>

<p>Angular Material has an extremely useful directive called mdDialog. It allows developers to provide interactive modal dialog boxes to their users without all of the painful boilerplate usually associated with building your own from scratch.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/md-dialog-example-1024x639.png" alt="mdDialog screenshot"></p>

<p>Seems great, right? It honestly is, and my team and I have been using this directive throughout our app with no problems. That is, until QA discovered a bug in our staging environment that was keeping one of our dialog boxes from opening and throwing a cryptic error in the console:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/minified-angular-error-1024x132.png" alt="Console error screenshot"></p>

<p>Useless, right? While seasoned Angular developers will be able to catch what is happening here, most of them will also readily admit that this error is cryptic and unhelpful. Thankfully Angular has a feature that creates a custom docs page for you based on your error. You can see the URL for my custom error page on the first line. My page read:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/useless-error-1024x550.png" alt="Useless error"></p>

<p>I’m certain that anyone reading this who has put in their time with Angular is nodding their head right now. This is the dreaded <code>Error: $injector:unpr Unknown Provider error</code>.</p>

<p>For anyone who doesn’t know, this is a commonly seen Angular error that means Angular’s dependency injection can’t resolve one or more dependencies somewhere in your code. Explaining dependency injection is outside the scope of this post, but you can <a href="https://docs.angularjs.org/guide/di">read more about it here</a> if you don’t fully understand what I mean.</p>

<p>Dependency injection is great for writing explicit and testable code, but it runs into a hiccup during minification. The quirk is as follows. Suppose your app looks like this:</p>

<pre><code class="language-javascript">// Don't actually build apps like this, its just an example
// In real life follow this: https://github.com/johnpapa/angular-styleguide
angular.module('myModule', []); // Declare the module

angular.module('myModule')  
  .service('myService', function() {
    return {
      saySomething : function() { console.log('Something'); }
    }
  });

angular.module('myModule')  
  .controller('myController', function($scope, $http, myService) {
    //We included $scope, $http, and myService into the controller as dependencies
    myService.saySomething() //"Something"
  });
</code></pre>

<p>… then the minified version of <code>myController</code> will partially look like this:</p>

<pre><code class="language-javascript">var myController = function(a, b) {  
  //This will throw an error at runtime because 'a' is not a valid dependency
}
</code></pre>

<p>Angular developers know that the way to fix this is to tell Angular what your minified dependencies actually refer to like so:</p>

<pre><code class="language-javascript">myModule  
  .controller('myController', 
    ['$scope', '$http', 'myService',
    function($scope, $http, myService) {
    //We included $scope, $http, and myService into the controller as dependencies
    myService.saySomething() //"Something"
  }]);
</code></pre>

<p>So I had my problem laid out. Somewhere in this app a dependency injection was going wrong.</p>

<hr>

<h4 id="debugging">Debugging</h4>

<p>I spent almost an hour scouring the code related to my mdDialog box looking for a dependency that I had mis-declared or forgotten about, but I couldn’t find anything of the sort. Defeated, I started to look at the rest of the stacktrace that Angular had provided in the error, but I quickly realized that I’d need to use an un-minified version of the Angular library if I wanted to get anywhere. I swapped out the script tag and checked the stacktrace once more:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/unminified-angular-error.png" alt="Unminified error"></p>

<p>Equally useless. Feeling hopeless, I decided to step into the Angular source to see if I could find anything useful there. I clicked the first line number given by the stacktrace which brought me to the function that Angular uses to actually create the custom docs URL that gets printed in the console. Interesting… I decided to set a breakpoint on it to see what I could grok from the arguments:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/breakpoint-on-error-creator-1024x402.png" alt="Breakpoint on error creator"></p>

<p>Now I had something. Looking through the call stack on the right side of the developer tools, I noticed that <code>minErr()</code> makes a call to a function called <code>invoke()</code>. Invoking an error creator message must require some information about what error is occurring, so I stepped into it:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/after-clicking-invoke-1-1024x402.png" alt="After clicking invoke"></p>

<p>What’s that? I recognized that the arguments being passed in looked a lot like my code. I did a project wide Find for the snippet in Sublime Text and lo and behold: I had found bug.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/Screen-Shot-of-bug.png" alt="Bug snippet screenshot"></p>

<p>While what’s causing the DI problem might not be immediately clear, I knew right away. I had declared this code within a controller. As such, the $scope variables being referenced in the controller function that is passed into mdDialog on line 96 belong to the controller in which this is declared. Angular dependency injection does NOT allow developers to inject one controller into another, as per the docs:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/Screen-shot-of-error-msg.png" alt="Screenshot of error message"></p>

<p>Declaring a separate controller for the mdDialog solved the problem.</p>

<blockquote>
  <p>tl;dr if you get a weird unknown provider error only when you minify your code, set a breakpoint on the line that generates the error docs URL, step into its call to invoke(), and check its arguments to find what part of your code exactly is breaking.</p>
</blockquote>

<p>I hope this helps you avoid painful hours of fruitless debugging. Happy hacking!</p>]]></content:encoded></item><item><title><![CDATA[JavaScript Promises With Node.js]]></title><description><![CDATA[<p>JavaScript is a non-blocking programming language, which means that one chunk of JS code will not necessarily wait for the lines above it to execute before beginning itself. In many cases this is a pretty awesome feature of the language. Imagine if your website was only able to run one</p>]]></description><link>http://zpalexander.com/javascript-promises-with-node-js/</link><guid isPermaLink="false">74a65a28-7148-45ed-bad3-807abe32dbdb</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Mon, 21 Sep 2015 00:56:00 GMT</pubDate><content:encoded><![CDATA[<p>JavaScript is a non-blocking programming language, which means that one chunk of JS code will not necessarily wait for the lines above it to execute before beginning itself. In many cases this is a pretty awesome feature of the language. Imagine if your website was only able to run one window.onload call at a time. If your page needed to perform a number of calculations or data insertions in order to render correctly, things would take forever to load and users would see a bunch of unstyled content and blank boxes at the beginning of every page load. Yuck.</p>

<p>While non-blocking is a very desirable feature of JavaScript in the browser, the paradigm shifts when writing server code with Node.js. Servers often need to wait for a data response so that they can manipulate and serve that data correctly. This requirement most commonly arises during data read and write operations. In these cases, code executing out of order can cause serious problems with application logic.</p>

<p>The most commonly used solution to this problem in the JavaScript community has been callbacks. A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. Here’s an example of a callback that almost all  Node.js developers have seen:</p>

<pre><code class="language-javascript">mongodb.connect('mongodb://localhost:27017/mydb', function(err, db) {  
    if (err) {
        throw err;
    } else {
        console.log('Successfully connected to the database');
    }
    var contentCollection = db.collection('content');
    contentCollection.find({}).toArray(function(err, result) {
        if (err) {
            throw err;
        } else {
            res.status(200).json(result);
            db.close();
        }
    });        
});
</code></pre>

<p>In this example, we’re using the MongoDB native driver to connect to the database, grab all the data from a collection called “content” and return that data as JSON. Due to JavaScript’s non-blocking nature, however, we can’t make the <code>.find({})</code> call until we’re sure we have connected successfully to the database, so we pass a callback into <code>mongodb.connect();</code>. Similarly, we cannot reliably return the data via <code>res.json()</code> until we are sure the <code>.find({})</code> operation has completed successfully, so we pass a second callback into <code>.find({}).toArray()</code>.</p>

<hr>

<h4 id="whydocallbackssuck">Why Do Callbacks Suck?</h4>

<p>This doesn’t look so bad, but what happens if you need to pass a third, or fourth or fifth callback in order to manipulate the data further? A relatively simple algorithm can quickly turn into something Node.js developers term “callback hell”.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/gn3N5gB.png" alt="Callback hell"></p>

<p>Code like this can be very hard to understand at first glance, and looks extremely unwieldy in a text editor. Callbacks are essentially an inelegant hack for getting around JavaScript’s non-blocking nature. There has to be a better way…</p>

<hr>

<h4 id="enterjavascriptpromises">Enter JavaScript Promises</h4>

<p>Promises are a better way to write asynchronous JavaScript. A promise is essentially an object that, when returned from a function, represents an operation that hasn’t completed yet but is expected to in the future. Because that definition didn’t make sense to me the first time I read it either, here’s an example of the above MongoDB code written using promises instead of callbacks:</p>

<pre><code class="language-javascript">mongoClient.connectAsync('mongodb://localhost:27017/mydb')  
    .then(function(db) {
        return db.collection('content').findAsync({})
    })
    .then(function(cursor) {
        return cursor.toArrayAsync();
    })
    .then(function(content) {
        res.status(200).json(content);
    })
    .catch(function(err) {
        throw err;
    });
</code></pre>

<p>Pretty cool, right? This code is cleaner-looking and way easier to understand than its callback-infested cousin. “But”, you may be asking, “where did you get connectAsync() from? When I run that with Node I just get an error!”</p>

<hr>

<h4 id="usingthebluebirdpromiselibrarywithnodejs">Using the Bluebird Promise Library with Node.js</h4>

<p><a href="https://www.npmjs.com/package/bluebird">Bluebird</a> is a fully-featured promise library for JavaScript. The project’s NPM package means that integration with a Node.js app is fairly simple. Bluebird’s strongest feature is that it allows you to “promisify” other Node modules in order to use them asynchronously. After running <code>npm install --save bluebird</code> on your Node project, you can use the following code to “promisify” the MongoDB module and use it asynchronously:</p>

<pre><code class="language-javascript">/* Dependencies */
var Promise = require('bluebird');  
var mongoClient = Promise.promisifyAll(require('mongodb')).MongoClient;

mongoClient.connectAsync('mongodb://localhost:27017/mydb')  
    .then(function(db) {
        return db.collection('content').findAsync({})
    })
    .then(function(cursor) {
        return cursor.toArrayAsync();
    })
    .then(function(content) {
        res.status(200).json(content);
    })
    .catch(function(err) {
        throw err;
    });
</code></pre>

<p>Just use Bluebird’s <code>.promisifyAll()</code> method to create an async version of every method the module provides. It really is that easy.</p>

<hr>

<h4 id="returningpromisesfromotherfunctions">Returning Promises From Other Functions</h4>

<p>In the course of writing more sophisticated Node.js apps it sometimes becomes necessary to return a promise from your own function. Let’s extend our example above by hypothesizing that we want to be able to perform CRUD operations on the data that our DB call returns. In this particular instance, let’s implement a separate delete function that calls the code we wrote to get all content from the database, then looks through it for a specific value and deletes that value if it exists.</p>

<pre><code class="language-javascript">/* Dependencies */
var Promise = require('bluebird');  
var mongoClient = Promise.promisifyAll(require('mongodb')).MongoClient;

/* Functions */
var getAllContent = function() {  
    return mongoClient.connectAsync('mongodb://localhost:27017/mydb')
        .then(function(db) {
            return db.collection('content').findAsync({})
        })
        .then(function(cursor) {
           return cursor.toArrayAsync();
        })
        .then(function(content) {
            // This is how we return the data to the next .then() call
            return content;
        })
        .catch(function(err) {
           throw err;
        });
    });
};

var deleteItem = function(itemID) {  
    getAllContent()
        .then(function(content) {
            var itemExists = false;
            for (var i = 0; i &lt; content.length; i++) {
                if (content[i].itemID === itemID) {
                    itemExists = true;
                    break;
                }
            }
            if (itemExists) {
                // Delete the item from the DB here
            }
        })
        .catch(function(err) {
            throw err;
        });
};
</code></pre>

<p>And there you have it. Your getAllContent() function returns a promise, which you can use in your deleteItem() function.</p>

<hr>

<h4 id="creatingyourownpromises">Creating Your Own Promises</h4>

<p>You’ll almost never need to do this, but here’s how to wrap something in your own promise.</p>

<pre><code class="language-javascript">/* Dependencies */
var Promise = require('bluebird');  
var mongoClient = Promise.promisifyAll(require('mongodb')).MongoClient;  
var unpromisifiedLib = require('upl');

/* Functions */
var readFileAsync = function() {  
    return new Promise(function(resolve) {
        // Do some IO stuff which you'll almost defintely
        // be able to promisify without having to do this manually
        var contents = unpromisifiedLib.doSomething();
        resolve(contents);
    });
};

var consumeHomemadePromise = function(itemID) {  
    readFileAsync
        .then(function(contents) {
            console.log(contents);
        })
        .catch(function(err) {
            throw err;
        });
};
</code></pre>

<p>Keep in mind, you’ll be able to use the Bluebird library to promisify basically anything, so its usually unnecessary to do this.</p>

<p>Those are the basics of how to use Bluebird promises in Node.js. For more information, check out the <a href="https://github.com/petkaantonov/bluebird/blob/master/API.md">Bluebird API</a>.</p>]]></content:encoded></item><item><title><![CDATA[Responsive Sprites With SASS And Compass]]></title><description><![CDATA[<p>I came across an interesting problem over the weekend and I thought it might be a good idea to share my solution. I was working on a site using <a href="http://sass-lang.com/">SASS</a> plus <a href="http://compass-style.org/">Compass</a> and I had a number of images that I needed to set up as sprites in order to</p>]]></description><link>http://zpalexander.com/responsive-sprites-with-sass-and-compass/</link><guid isPermaLink="false">cdd96354-a643-4fcd-b606-44c4ffa80282</guid><category><![CDATA[SASS]]></category><category><![CDATA[CSS]]></category><category><![CDATA[Compass]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Mon, 13 Apr 2015 03:15:00 GMT</pubDate><content:encoded><![CDATA[<p>I came across an interesting problem over the weekend and I thought it might be a good idea to share my solution. I was working on a site using <a href="http://sass-lang.com/">SASS</a> plus <a href="http://compass-style.org/">Compass</a> and I had a number of images that I needed to set up as sprites in order to increase page load performance.</p>

<p>Setting up sprites with Compass is normally very easy. You simply add your sprite .png files to a directory within your project’s assets directory and point your <code>config.rb</code> file there with the following line: <code>images_dir = "assets"</code>.</p>

<p>For the purpose of this post, let’s say that your sprite assets have the following paths:</p>

<ul>
<li><code>assets/icons/new.png</code></li>
<li><code>assets/icons/edit.png</code></li>
<li><code>assets/icons/save.png</code></li>
<li><code>assets/icons/delete.png</code></li>
</ul>

<p>Once you’ve placed your icons and set your <code>config.rb</code> file correctly, you simply create a new SASS partial called <code>_sprites.scss</code> and add the following three lines:</p>

<pre><code class="language-scss">@import "compass/utilities/sprites";
@import "icons/*.png";
@include all-icons-sprites;
</code></pre>

<p>This will give you the following classes, which you can then apply to your site’s markup:</p>

<pre><code class="language-scss">.icons-sprite,
.icons-delete,
.icons-edit,
.icons-new,
.icons-save   { background: url('/images/icons-s34fe0604ab.png') no-repeat; }

.icons-delete { background-position: 0 0; }
.icons-edit   { background-position: 0 -32px; }
.icons-new    { background-position: 0 -64px; }
.icons-save   { background-position: 0 -96px; }
</code></pre>

<p>This is a great feature of Compass, but it falls short for responsive sites that need fluid-size sprites. On my project, I needed sprites that would resize to fill their fluid size containers. I did some digging, and ended up coming up with the following mix-in. Simply add this mixin to your <code>_sprites.scss</code> file and then use it within a selector for the container element. Here’s the mixin:</p>

<pre><code class="language-scss">@mixin responsive-sprite($map, $icon) {
  $icon-file: sprite-file($map, $icon);
  $icon-width: image-width($icon-file);
  $icon-height: image-height($icon-file);

  $sprite-file: sprite-path($map);
  $sprite-map: sprite-url($map);

  $sprite-width: image-width($sprite-file);
  $sprite-height: image-height($sprite-file);

  $space-top: floor(nth(sprite-position($map, $icon), 2));
  @if $space-top == 0 {
    $space-top: 0px
  }

  width: percentage($sprite-width / $icon-width);
  display: block;
  height: 0;
  padding-bottom: percentage($icon-height / $icon-width);
  background: $sprite-map;
  background-size: 100%;
  background-position:0 percentage(-1 * $space-top / ( $sprite-height - $icon-height ) );
}
</code></pre>

<p>Once you have this in place, you can use it as such:</p>

<pre><code class="language-scss">.my-sprite-wrapper-div {
  @include responsive-sprite($icons-sprites, save);
}
</code></pre>

<p>And voila, you now have responsive sprites which are auto-generated for you by Compass.</p>

<hr>

<p>Further reading:</p>

<ul>
<li><a href="http://compass-style.org/help/tutorials/spriting/">http://compass-style.org/help/tutorials/spriting/</a></li>
<li><a href="http://www.wunderkraut.com/blog/responsive-retina-sprites-with-compass/2014-04-16">http://www.wunderkraut.com/blog/responsive-retina-sprites-with-compass/2014-04-16</a></li>
<li><a href="http://www.hugeinc.com/ideas/perspective/using-compass-generated-sprite-sheets-in-responsive-sass">http://www.hugeinc.com/ideas/perspective/using-compass-generated-sprite-sheets-in-responsive-sass</a></li>
<li><a href="https://css-tricks.com/forums/topic/responsive-sprites-using-compasssass/">https://css-tricks.com/forums/topic/responsive-sprites-using-compasssass/</a></li>
</ul>]]></content:encoded></item><item><title><![CDATA[Beijing's Garage Cafe: An Ad-Hoc Startup Incubator]]></title><description><![CDATA[Beijing's Garage Cafe is where Chinese start-up founders go to meet, exchange ideas and build tomorrow's technology - all for the price of a cup of coffee.]]></description><link>http://zpalexander.com/beijings-garage-cafe-startups/</link><guid isPermaLink="false">8064bc61-4ed5-4342-988f-d1aa628ef777</guid><category><![CDATA[China]]></category><category><![CDATA[Startups]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Sat, 07 Feb 2015 15:23:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2016/05/IMG_5569.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2016/05/IMG_5569.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"><p>Peking University went on holiday last month in observance of Chinese New Year. As such, I knew I would be logging quite a few extra programming hours over the course of February. While I don’t mind working part-time from the comfort of my apartment’s bedroom, I actually kind of hate working from home full time. There are benefits of course: fewer interruptions, more comfortable and configurable workspace and no commute. Nevertheless, <a href="http://theoatmeal.com/comics/working_home">I start to go a little crazy</a> when I spend over 16 hours a day in the same 10′ x 10′ space.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/9.png" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>I started looking for coworking spaces in Beijing right away. Despite whatever misconceptions most Westerners might have about China’s backwardness, Beijing actually has a thriving tech sector who’s physical heart lies just south of Peking University campus in a neighborhood called Zhong Guan Cun (中关村). Quite a few tech giants call Zhong Guan Cun home, including <a href="https://en.wikipedia.org/wiki/Sina_Corp">SINA Corp</a>, Microsoft China, <a href="https://en.wikipedia.org/wiki/Tencent">Tencent</a>, <a href="https://en.wikipedia.org/wiki/Youku">Youku</a>, <a href="https://en.wikipedia.org/wiki/Tudou">Tudou</a> and <a href="https://en.wikipedia.org/wiki/Qunar">Qunar</a>.</p>

<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6114.256269487683!2d116.30975147553943!3d39.98324176767135!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x35f051505892a34f%3A0x6ea89d0cc8fe038c!2sZhongguancun%2C+Haidian%2C+Beijing%2C+China!5e0!3m2!1sen!2sus!4v1463408074786" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>

<p>What really makes Zhong Guan Cun interesting, however, is it’s thriving start-up scene. There are actually <a href="http://dealbook.nytimes.com/2011/12/15/seeding-chinas-start-up-scene-with-a-nod-to-silicon-valley/">hundreds of start-ups</a> that call Beijing home. The concentrated nature of both established and start-up tech companies has recently earned Zhong Guan Cun the title “China’s Silicon Valley”. The industry boom has lead to a massive influx of coworking spaces and incubators designed to produce the next <a href="https://en.wikipedia.org/wiki/Sina_Weibo">Weibo</a> or <a href="https://en.wikipedia.org/wiki/WeChat">WeChat</a>. Most of these spaces follow the traditional business model, requiring either invitation or a hefty monthly fee or both. Recently, however, a new class of coworking spaces has arrived in Zhong Guan Cun. These places may call themselves “cafes”, but they offer much more than just coffee.</p>

<hr>

<h4 id="meetbeijingsgaragecafe">Meet Beijing's Garage Cafe</h4>

<p>Garage Cafe (车库咖啡馆）can be difficult to find as a non-local. Its nestled in an alley called “Innoway” near the northwest corner of Zhong Guan Cun. According to one of the area’s natives, this alleyway used to be one of the largest book-seller streets in all of Beijing. Its only appropriate, therefore, that as the knowledge economy transitioned from paper to digital media, this information hub made the transition from literati bazaar to start-up haven.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/IMG_4173.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>The cafe itself sits on the second floor of an otherwise innocuous looking building. I walked around in circles and had to ask a few people on the street before I finally figured it out. Upon entering the building, it can almost feel like you’ve walked into a private apartment building rather than into one of the most important spots in the Chinese start-up scene:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/cheku-building.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>Nevertheless, once you head up the back stairs and through the door, you’re greeted by a massive space humming with energy and excitement.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/IMG_5569-1.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>The floor space of the cafe measures to 800 square meters, and has seating for about 150 people. The decor is sleek and industrial; minimalist black furniture, exposed fixtures and extension cords hanging down from the ceiling. Unlike most cafes, which seem to <a href="http://wifinetnews.com/archives/2005/05/coffeeshop_turns_off_wi-fi_on_weekends.html">despise laptop users</a>, Garage Cafe’s message is clear: grab a seat, plug in and get coding. Every table has a charging station with enough plugs for laptops, cell phones and even external monitors. The internet is also quite fast, which is a rarity at Chinese cafes. They even go so far as to provide monitors for people to plug into while they work.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/IMG_5572.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>Garage Cafe boasts a pretty solid library of programming books in both English and Chinese. No matter where you sit in the cafe, you can catch wisps of conversation about product optimization, unit testing, market share, etc. As a foreigner who speaks Chinese, I already had several job offers after just my first visit to the cafe. People go to Garage to network, brainstorm and build. There’s also a huge bulletin board of job listings that can be great to check out if you’re looking for a position in a Beijing start-up.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/IMAG0136.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>Keep in mind that Garage Cafe is much more “Chinese” than most cafes in Beijing. The staff most definitely does not speak English, and in the 20 or so times I have visited so far, I have only ever seen one other non-Han patron. Nevertheless, if you can speak Chinese and are looking for an awesome space to get some work done or network with like-minded programmers, Garage Cafe is a great option. The coffee isn’t half bad either, at least by Chinese standards.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/IMG_5567.jpg" alt="Beijing's Garage Cafe: An Ad-Hoc Startup Incubator"></p>

<p>In case you want to check it out for yourself, here is the address of Garage Cafe in English and Chinese:</p>

<p>Haidian District, <br>
Zhongguancun, Haidian Qiao, <br>
Dong Nan Haidian Tu Shu Cheng Bu Xing Jie</p>

<p>北京市海淀区中关村海淀桥东南海淀图书城步行街 (鑫鼎宾馆2层) – 车库咖啡</p>

<p>You can also find the cafe on Weibo <a href="http://weibo.com/chekucafe">here</a>.</p>]]></content:encoded></item><item><title><![CDATA[Binary Bomb Lab :: Phase 6]]></title><description><![CDATA[Learn how to work through Phase 6 of Bryant and O'Hallaron's Binary Bomb lab step by step. Get started on the path to defeating Dr. Evil!]]></description><link>http://zpalexander.com/binary-bomb-lab-phase-6/</link><guid isPermaLink="false">76ac9712-d0ae-40fa-9a17-631963a0f591</guid><category><![CDATA[IA32]]></category><category><![CDATA[Fun]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Sun, 11 Jan 2015 01:49:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2017/05/bob-omb-shirt.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2017/05/bob-omb-shirt.jpg" alt="Binary Bomb Lab :: Phase 6"><p>A note to the reader: For explanation on how to set up the lab environment see the <a href="http://zpalexander.com/binary-bomb-lab-set-up/">"Introduction"</a> section of the post.</p>

<p>If you're looking for a specific phase:</p>

<ul>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-1">Here is Phase 1</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-2">Here is Phase 2</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-3">Here is Phase 3</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-4">Here is Phase 4</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-5">Here is Phase 5</a></li>
</ul>

<hr>

<p>This phase is definitely the trickiest out of all of the other bomb lab phases. Prepare for data structures…</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-6-overview-min.png" alt="Binary Bomb Lab :: Phase 6"></p>

<p>This phase is a doosey. Let’s go through everything step by step to figure out what we need to do.</p>

<p>First things first, our friend <code>&lt;read_six_numbers&gt;</code> from Phase 2 is back again. So, our input should be six integers. That one is a gimmie.</p>

<p>Next, we’ve got some loops happening. Firstly, <code>&lt;phase_6+47&gt;</code> is making sure that each number in our password is less than six. Now we have two criteria for our password. It needs to be six integers separated by spaces, and each integer needs to be less than or equal to six.</p>

<p>The final constraint on our input occurs in the nested loops between <code>&lt;phase_6+57&gt;</code> and <code>&lt;phase_6+104&gt;</code>. We have a loop with iterators <code>%ebx</code> and <code>%edi</code>. Essentially what happens is that we compare each number with every other number, and we only jump <code>&lt;explode_bomb&gt;</code> on line <code>&lt;phase_6+89&gt;</code> if the comparisons are not equal. In other words, all six of our integers need to be distinct.</p>

<p>Let’s summarize what we know so far about our input for this phase:</p>

<ul>
<li>six integers separated by spaces</li>
<li>each integer should be less than or equal to 6</li>
<li>no integer should be the same as any other integer</li>
</ul>

<p>Now that we have a better idea of what our input should look like, let’s use the test string <code>1 2 3 4 5 6</code> and head on down towards the <code>&lt;explode_bomb&gt;</code> call at <code>&lt;phase_6+225&gt;</code> to see if we can find out more.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/final-comparison.png" alt="Binary Bomb Lab :: Phase 6"></p>

<p>Here is the conditional statement by itself. First, the contents of <code>%esi + 8</code> get moved into <code>%edx</code>. Subsequently, <code>%esi</code> itself gets moved into <code>%eax</code>. Then, <code>%eax</code> gets compared to <code>%edx</code>.  If the value of <code>%edx</code> (which is <code>%esi + 0x8</code>) is less than the value at <code>%eax</code> (which is <code>%esi</code>) then the bomb explodes.</p>

<p>So, what are these values we’re comparing anyway? Let’s take a look:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/linked-list-nodes.png" alt="Binary Bomb Lab :: Phase 6"></p>

<p>When we take a look at the contents of <code>%esi</code> and <code>%esi + 0x8</code>, we get a couple of structures called <code>&lt;node1&gt;</code> and <code>&lt;node2&gt;</code>. Each node has three elements. The second element here obviously corresponds to the node number itself: 1 for <code>&lt;node1&gt;</code>,  2 for <code>&lt;node2&gt;</code>, etc. The third element of the node looks like a pointer. As we check out the contents of <code>%esi + 0x8</code>, and then <code>((%esi + 0x8) + 0x8)</code>, and so on, we see that these pointers are decreasing <code>0x8</code> at a time. Given that the first column of values seem to be arbitrary, this is starting to look like a common data structure: a (singly) linked list. Column one is the value of the node, column two is the node’s position in the list, and column threee is the pointer to the next node in the list.</p>

<p>So now we know, when we compare <code>%edx</code> and <code>%eax</code> at <code>&lt;phase_6+221&gt;</code>, what we’re actually doing is comparing the value of the current linked list node to the value of the next node in the list. If the next node’s value isn’t lower than the present node’s value, the bomb explodes. In other words, we need to put the nodes in order from largest value to smallest value. How do we do this? With our input.</p>

<p>Here’s a table of the values for reference:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/Screen-Shot-2015-01-10-at-22-25-03.png" alt="Binary Bomb Lab :: Phase 6"></p>

<p>And here they are in order from largest to smallest:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/Screen-Shot-2015-01-10-at-22-28-53.png" alt="Binary Bomb Lab :: Phase 6"></p>

<p>So there you go. That’s the answer right there.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-6-complete.png" alt="Binary Bomb Lab :: Phase 6"></p>

<p>Phase 6 complete! We did it!</p>

<hr>

<h4 id="wrapup">Wrap Up</h4>

<p>I hope you had fun working through the six levels of the bomb lab with me. I certainly enjoyed it. There’s nothing like quite like some crunchy reverse engineering goodness to get your brain in gear again. For the record, I do know there is a secret phase. While I solved it correctly for my class, I am not going to go through the steps here. If you reallllly need a tutorial, you can find one pretty easily with the search engine of your choice.</p>

<p>Thanks for reading, and I hope you found this tutorial helpful.</p>]]></content:encoded></item><item><title><![CDATA[Binary Bomb Lab :: Phase 5]]></title><description><![CDATA[Learn how to work through Phase 5 of Bryant and O'Hallaron's Binary Bomb lab step by step. Get started on the path to defeating Dr. Evil!]]></description><link>http://zpalexander.com/binary-bomb-lab-phase-5/</link><guid isPermaLink="false">53e9a3ef-e430-4fd9-837e-32f4c3273a6c</guid><category><![CDATA[IA32]]></category><category><![CDATA[Fun]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Sat, 10 Jan 2015 01:40:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2017/05/bob-omb-shirt-1.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2017/05/bob-omb-shirt-1.jpg" alt="Binary Bomb Lab :: Phase 5"><p>A note to the reader: For explanation on how to set up the lab environment see the <a href="http://zpalexander.com/binary-bomb-lab-set-up/">"Introduction"</a> section of the post.</p>

<p>If you're looking for a specific phase:</p>

<ul>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-1">Here is Phase 1</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-2">Here is Phase 2</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-3">Here is Phase 3</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-4">Here is Phase 4</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-6">Here is Phase 6</a></li>
</ul>

<hr>

<p>Ok, let’s get right to it and dig into the <code>&lt;phase_5&gt;</code> code:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-5-overview.png" alt="Binary Bomb Lab :: Phase 5"></p>

<p>So, what have we got here? First things first, we can see from the call to <code>&lt;string_length&gt;</code> at <code>&lt;phase_5+23&gt;</code> and subsequent jump equal statement our string should be six characters long.</p>

<p>Next, as we scan through each operation, we see that a register is being incremented at <code>&lt;phase_5+57&gt;</code>, followed by a jump-less-than statement right afterwards that takes us back up to <code>&lt;phase_5+43&gt;</code>. Remember this structure from Phase 2? A loop is occurring. And, as you can see at <code>&lt;phase_5+58&gt;</code> structure, the loop iterates 6 times. Given that our string is 6 characters long, it makes sense to assume that the function is iterating over each character in the loop and presumably doing something to them.</p>

<p>Finally, we can see down at the bottom of the function that <code>&lt;strings_not_equal&gt;</code> is being called after the contents of <code>%eax</code> and the fixed address <code>0x804980b</code> have been pushed onto the stack. This looks just like phase 1. The code is comparing the string (presumably our input) stored in <code>%eax</code> to a fixed string stored at <code>0x804980b</code>.</p>

<p>So, what do we know about phase 5 so far?</p>

<ul>
<li>our input has to be a string of 6 characters</li>
<li>the function accepts this 6 character string and loops over each character in it</li>
<li>the result of the loop is compared to a fixed string, and if they’re equal, the bomb doesn’t explode</li>
</ul>

<p>As a next step, let’s input the test string “abcdef” and take a look at what the loop does to it. Then, we can take a look at the fixed value we’re supposed to match and go from there:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-5-compared-strings.png" alt="Binary Bomb Lab :: Phase 5"></p>

<p>Woah. “srveaw” is pretty far off from “abcdef”. On the bright side, at least now we know that our string should come out of the loop as “giants”. Given this info, it looks as though the loop is implementing a cypher. From here, we have two ways to solve this phase, a dumb way and a smart way. The dumb way is to simply input all characters from a-z into the cypher and create a mapping table. From this mapping table, we can figure out the un-cyphered version of “giants”. This works just fine, and I invite you to try it.</p>

<p>The smart way of solving this phase is by actually figuring out the cypher. Once we understand how it works, we can reverse engineer “giants” into its pre-cypher form without having to waste time doing trial and error.</p>

<p>I don’t want to go through either solution all the way here, since the first one is a no-brainer and the second one is a little complicated. In order to solve the cypher, take a look at <code>%esi</code> and you’ll find an array of characters stored there, where each character has an index. Essentially what is happening is, each character from our string is ANDed with 0xf, and the result is used to get the character with the corresponding index from the array. If you solve the phase this way, you’ll actually notice that there is more than one correct solution.</p>

<p>Either way, eventually you’ll find that the pre-cyphered version of “giants” is actually “opekmq”.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-5-complete.png" alt="Binary Bomb Lab :: Phase 5"></p>

<p>On to the last phase!</p>]]></content:encoded></item><item><title><![CDATA[Binary Bomb Lab :: Phase 4]]></title><description><![CDATA[Learn how to work through Phase 4 of Bryant and O'Hallaron's Binary Bomb lab step by step. Get started on the path to defeating Dr. Evil!]]></description><link>http://zpalexander.com/binary-bomb-lab-phase-4/</link><guid isPermaLink="false">763ac531-aaf4-4f13-97cb-c3588dc6e3b2</guid><category><![CDATA[IA32]]></category><category><![CDATA[Fun]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Fri, 09 Jan 2015 01:33:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2016/05/bob-omb-shirt.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2016/05/bob-omb-shirt.jpg" alt="Binary Bomb Lab :: Phase 4"><p>A note to the reader: For explanation on how to set up the lab environment see the <a href="http://zpalexander.com/binary-bomb-lab-set-up/">"Introduction"</a> section of the post.</p>

<p>If you're looking for a specific phase:</p>

<ul>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-1">Here is Phase 1</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-2">Here is Phase 2</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-3">Here is Phase 3</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-5">Here is Phase 5</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-6">Here is Phase 6</a></li>
</ul>

<hr>

<h4 id="phase4">Phase 4</h4>

<p>In my opinion, this is where things start to get tricky. In this phase, it is not enough to simply understand the assembly. Some pattern-recognition will be required. As usual, let's start by taking a look at the code for this phase's function to see if we can find a vector through which to understand what's happening. I'm going to do so by running gdb with a test string and using disas:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-4-function.png" alt="Binary Bomb Lab :: Phase 4"></p>

<p>On line <code>&lt;phase_4+16&gt;</code>, the <code>&lt;phase_4&gt;</code> function is pushing a fixed value stored at memory address <code>0x8049808</code> onto the stack right before a call to <code>scanf</code> is made. As we have learned from the past phases, fixed values are almost always important. Lo and behold, when we dump the contents of the memory address we get <code>“%d”</code>, which tells us that the answer to this phase should be a single integer</p>

<p>The second important feature of this code occurs on line <code>&lt;phase_4+53&gt;</code>. Our input value, which is stored in <code>%eax</code>, is getting input into this other function called <code>&lt;func4&gt;</code>. Right now <code>&lt;func4&gt;</code> is a black box, so we will need to dig into it using si to figure out what it is doing to our integer</p>

<p>The last thing we need to consider is that, after <code>&lt;func4&gt;</code> gets called and returns our potentially altered input back to <code>%eax</code>, <code>%eax</code> then gets compared to the hex value <code>37</code>, which in decimal is 55. This means that, whatever our input is to begin with, it needs to be turned into 55 by <code>&lt;func4&gt;</code>.</p>

<p>So, now that we know what is generally happening in <code>&lt;phase_4&gt;</code>, let’s dig into <code>&lt;func4&gt;</code> to figure out what we need to input in order to generate 55.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-4-func4.png" alt="Binary Bomb Lab :: Phase 4"></p>

<p>Ok, before we do anything else, let’s recognize that this function is calling itself, which makes it recursive. All recursive functions have a “base case”, which terminates the loop, and then a series of instructions to follow in order to continue the loop if the base case is not met.</p>

<p>Let’s first identify our base case. It should occur early in the function as a conditional check. In <code>&lt;func4&gt;</code>, our base case occurs at <code>&lt;func4+11&gt;</code>. The function compares its input to 1. If the input is less than or equal to 1, it jumps down to <code>&lt;func4+48&gt;</code>, where the return value is set to one. Finally, it returns this value.</p>

<p>Now that we understand that the base case occurs when input=1, let’s identify what happens when the base case is not met. The first thing to note is that the function calls itself twice, once at <code>&lt;func4+23&gt;</code> and once at <code>&lt;func4+37&gt;</code>. The first time it calls itself, it feeds the new function call its input-1. Similarly, the second time it calls itself, it feeds the new function call its input-2. Once the two recursivelly called functions return, it sums their return values at <code>&lt;func4+42&gt;</code> and returns the result.</p>

<p>Here’s what the corresponding C code would look like:</p>

<pre><code class="language-c">int test(int n) {  
  if (n&lt;2)
    return n;
  else
    return test(n-1) + test(n-2);
}
</code></pre>

<p>Now comes the part where we have to do some abstracted, big-picture thinking. We’ve got recursion, we’ve got a pattern, and we’ve got a function where <code>F(x) = F(x-1) + F(x-2)</code>. What famous pattern fits these three parameters? <a href="http://en.wikipedia.org/wiki/Fibonacci_number">The Fibbonaci sequence</a>!</p>

<p><img src="http://zpalexander.com/content/images/2016/05/fibonnaci-spiral.png" alt="Binary Bomb Lab :: Phase 4"></p>

<p>We should note that <code>&lt;func4&gt;</code> does not exactly return the Fibonacci number of the input. <code>&lt;func4&gt;</code> returns 1 if the input is 1 or less. For example, if our input is x=2, <code>&lt;func4&gt;</code> will return 1 for both x-1 = 1 and x-2 = 0.</p>

<p>So, now that we know all this stuff, how do we solve the stage? Remember that, in order to avoid the bomb blowing itself up, whatever gets spit out has to equal hex 37, which is 55 in decimal. Keeping in mind that func4(0) = func(1) = 1, func4(2) = 2, we will actually need to input the Fibonacci number for 55 with 1 subtracted from it. I find that taking a look at a table of the sequence makes this a little less confusing:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/fibbonaci-table.png" alt="Binary Bomb Lab :: Phase 4"></p>

<p>As we can see in the table above, the Fibonacci number for 55 is 10. So given our logic, 10-1= 9, so 9 should be the solution for the fourth phase.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-4-complete.png" alt="Binary Bomb Lab :: Phase 4"></p>

<p>Rock and roll.</p>]]></content:encoded></item><item><title><![CDATA[Binary Bomb Lab :: Phase 3]]></title><description><![CDATA[Learn how to work through Phase 3 of Bryant and O'Hallaron's Binary Bomb lab step by step. Get started on the path to defeating Dr. Evil!]]></description><link>http://zpalexander.com/binary-bomb-lab-phase-3/</link><guid isPermaLink="false">a855e71c-095f-4571-9cba-6d7332792b67</guid><category><![CDATA[IA32]]></category><category><![CDATA[Fun]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Wed, 07 Jan 2015 14:33:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2017/05/bob-omb-shirt-3.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2017/05/bob-omb-shirt-3.jpg" alt="Binary Bomb Lab :: Phase 3"><p>A note to the reader: For explanation on how to set up the lab environment see the <a href="http://zpalexander.com/binary-bomb-lab-set-up/">"Introduction"</a> section of the post.</p>

<p>If you're looking for a specific phase:</p>

<ul>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-1">Here is Phase 1</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-2">Here is Phase 2</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-4">Here is Phase 4</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-5">Here is Phase 5</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-6">Here is Phase 6</a></li>
</ul>

<hr>

<p>By now you know the drill. Off to our objdump file!</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-3-objdump.gif" alt="Binary Bomb Lab :: Phase 3"></p>

<p>Woah. There are a lot of conditionals here. Maybe you’re an IA32 warrior who can take one look at this code and immediately tell what is going on, but for the rest of us, an iterative approach might work better here.</p>

<p>The first interesting thing we see here is the call to <code>scanf</code> which occurs at memory address <code>8048bb7</code> in my objdump output file. There are two values that are pushed onto the stack right before <code>scanf</code> is called. After the call to <code>scanf</code> is made, the two pushed values are compared, and the bomb explodes if they’re not equal. Let’s use gdb to figure out what they are.</p>

<p>As usual, we will set a breakpoint at our phase, phase_3, and then run the bomb using answers.txt as an argument. After that, we can input a test string and when our breakpoint hits, we can use the gdb command <code>x/s [memory-address]</code> to print whatever string we find at that memory address:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-3-arg-params.png" alt="Binary Bomb Lab :: Phase 3"></p>

<p>From this we see that our test string is stored in register <code>%eax</code>, while the format being asked for follows the format <code>%d %c %d</code>. In case your C is rusty:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/scanf-inputs.png" alt="Binary Bomb Lab :: Phase 3"></p>

<p>From this, we know that our input will have to be an int, followed by a char, followed by an int again. This is a good first step. Let’s update our test input to <code>1 a 2</code> and run our bomb through gdb again.</p>

<p>When we do this, you’ll notice that after passing the format check, the next call to <code>&lt;explode_bomb&gt;</code> gets passed over as well. We could dig into <a href="https://code.google.com/p/binary-bomb/source/browse/phase3.txt?spec=svnb2dca04ee85e83c4693ac2cf58339bbfd34bd804&amp;r=b2dca04ee85e83c4693ac2cf58339bbfd34bd804">why 1 is correct as the first integer</a>, but let’s take the freebie and use our time to continue on.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-3-second-number.png" alt="Binary Bomb Lab :: Phase 3"></p>

<p>Once we arrive at the next test, we see that the value <code>$0xd6</code> is being compared to the value stored at <code>-0x4(%ebp)</code>.</p>

<p>As you should certainly know, <code>d6</code> in hexidecimal is equal to 214 in decimal. When we check the value stored in <code>-0x4(%ebp)</code>, it should be apparent that the program has jumped past our char input for now (its using a case statement for all of you A+ students), and is checking our second integer here. Since the jump statement to miss the next <code>&lt;explode_bomb&gt;</code> call requires equality, this means that our second integer must be 214.</p>

<p>Finally we come to our character. This one is just as simple as the last:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-3-character.png" alt="Binary Bomb Lab :: Phase 3"></p>

<p>From the move statement on line <code>&lt;+240&gt;</code> its clear that our char is stored at <code>-0x5(%ebp)</code> and the value to compare against is coming from <code>%bl</code>. When we print out the value to be compared against, we get a hexidecimal value of <code>62</code>, which in decimal is 98:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/Screen-Shot-2014-12-19-at-18-04-05.png" alt="Binary Bomb Lab :: Phase 3"></p>

<p>In other words, our character should be a lowercase ‘b’. Lo and behold, when we put our three answers together:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-3-correct-answer.png" alt="Binary Bomb Lab :: Phase 3"></p>

<p>Looks like the bomb squad is in town!</p>]]></content:encoded></item><item><title><![CDATA[Binary Bomb Lab :: Phase 2]]></title><description><![CDATA[Learn how to work through Phase 2 of Bryant and O'Hallaron's Binary Bomb lab step by step. Get started on the path to defeating Dr. Evil!]]></description><link>http://zpalexander.com/binary-bomb-lab-phase-2/</link><guid isPermaLink="false">731c07c8-c658-4614-8707-d0196bb6723f</guid><category><![CDATA[IA32]]></category><category><![CDATA[Fun]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Zach Alexander]]></dc:creator><pubDate>Tue, 06 Jan 2015 14:48:00 GMT</pubDate><media:content url="http://zpalexander.com/content/images/2017/05/bob-omb-shirt-2.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://zpalexander.com/content/images/2017/05/bob-omb-shirt-2.jpg" alt="Binary Bomb Lab :: Phase 2"><p>A note to the reader: For explanation on how to set up the lab environment see the <a href="http://zpalexander.com/binary-bomb-lab-set-up/">"Introduction"</a> section of the post.</p>

<p>If you're looking for a specific phase:</p>

<ul>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-1">Here is Phase 1</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-3">Here is Phase 3</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-4">Here is Phase 4</a> </li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-5">Here is Phase 5</a></li>
<li><a href="http://zpalexander.com/binary-bomb-lab-phase-6">Here is Phase 6</a></li>
</ul>

<hr>

<p>Ok, now things get a lot more interesting a lot more quickly. Let’s get started the same way we did last time, by looking at our objdump file for clues:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-2-objdump1.png" alt="Binary Bomb Lab :: Phase 2"></p>

<p>The first thing to notice here is that <code>&lt;phase_2&gt;</code> is calling a function by the name of <code>&lt;read_six_numbers&gt;</code>. If we really wanted to be pedantic, we could go take a look at this function, but for the sake of brevity in this already very long tutorial, I’m going to go ahead and tell you that it looks to make sure the stdin input has six integers in it, each separated by a space. So there’s our first big clue: our answer takes the format <code>a b c d e f</code> where a-f are integers.</p>

<p>Now that we know roughly what our input should look like, let’s fire up gdb and do a little reverse engineering to figure out which six integers we should be inputting.</p>

<p><strong><em>Sidenote</em></strong>: Typing in every passphrase every time we run the bomb gets really annoying really quickly. The bomb is written in such a way that it accepts a text file as an input. You can add your passphrases to this text file, separating each by a newline, and pass it to the bomb binary as an argument to avoid typing everything out every time you run the program. That’s what I’ll be doing from now on. See the <a href="http://csapp.cs.cmu.edu/public/bomblab.pdf">lab handout</a> for more information.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-2-fire-up-gdb.png" alt="Binary Bomb Lab :: Phase 2"></p>

<p>Now that we’re stopped at our breakpoint, let’s run disas to take a look at the assembly code and see if we can’t figure out exactly what’s going on. The output will look something like this:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-2-disas.png" alt="Binary Bomb Lab :: Phase 2"></p>

<p>Assuming you know assembly language basics (if you don’t, stop now and study up), a few things should jump out at you right away. Before anything else happens, a number is getting compared to 1, and the bomb is going off this number isn’t also 1. This means that the first integer in our secret phrase is undoubtedly 1.</p>

<p>The second thing to note is that the function is looping over its input. After <code>%eax</code> is compared to <code>(%esi, %ebx, 4)</code> at <code>&lt;+54&gt;</code>, <code>%ebx</code> gets incremented and, as long as its less than 5, the function jumps back to above the comparison so that it can do it again. This means that our input integers will probably be a pattern of some sort, where <code>&lt;+46&gt;</code> is where the math that increments the pattern happens. Let’s use until to jump down to the comparison and see if we can’t suss out what our second input number should be:</p>

<p><img src="http://zpalexander.com/content/images/2016/05/phase-2-registers.png" alt="Binary Bomb Lab :: Phase 2"></p>

<p>Once we’ve arrived at the comparison statement, we can use the <code>i r</code> command to see the contents of our registers. <code>%eax</code>, which is the register to which our value is being compared, is equal to 2. Therefore, the second integer in our passphrase should be 2.</p>

<p>The simplest way to solve this level completely is by continuing to step through the code, seeing what <code>%eax</code> is equal to after each iteration. Next you’ll find 6, then 24, then 120 followed by 720. If you’re really smart, however, you’ll notice that the assembly code is actually implementing the following algorithm:</p>

<pre><code class="language-`math">v[0] = 1  
v[i] = (i+i) * v[i-1]  
</code></pre>

<p>Either way, the second passphrase ends up being <code>1 2 6 24 120 720</code>.</p>

<p><img src="http://zpalexander.com/content/images/2016/05/Screen-Shot-2014-12-14-at-14-29-06.png" alt="Binary Bomb Lab :: Phase 2"></p>

<p>On to the next challenge!</p>]]></content:encoded></item></channel></rss>