<?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:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vijayabharathi Balasubramanian on Medium]]></title>
        <description><![CDATA[Stories by Vijayabharathi Balasubramanian on Medium]]></description>
        <link>https://medium.com/@vijayabharathib?source=rss-783f35ad67e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LTg7EPJ1yBvwhm7l7sCxHg.jpeg</url>
            <title>Stories by Vijayabharathi Balasubramanian on Medium</title>
            <link>https://medium.com/@vijayabharathib?source=rss-783f35ad67e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:36:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vijayabharathib/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why CSS Selectors are the most useful Selenium WebDriver locators?]]></title>
            <link>https://medium.com/hackernoon/why-css-selectors-are-the-most-useful-selenium-webdriver-locators-28082be1cd3b?source=rss-783f35ad67e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/28082be1cd3b</guid>
            <category><![CDATA[webdriver-locators]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css-selectors]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <dc:creator><![CDATA[Vijayabharathi Balasubramanian]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 18:11:03 GMT</pubDate>
            <atom:updated>2018-07-30T18:11:03.024Z</atom:updated>
            <content:encoded><![CDATA[<p>When Front end developers need to locate elements on a web page, they use CSS selectors! Why not for selenium webdriver automation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wR0Db7EtmodgSOTI.png" /><figcaption>image created via carbon.now.sh</figcaption></figure><p>A wide variety of locators are being used in Selenium Web Driver automation. <strong>CSS selectors</strong> come last when you ask the question, “What are all the locators do you use frequently and why?”</p><p><strong>XPath</strong> tops the list as one size fits all solution. There is also a tendency to use XPath even when a proper id is available.</p><p>Often, it is also lack of exposure to CSS selectors that drives them towards other options. People have mentioned that they are able to get the job done with other selectors. Fair enough, no harm was done.</p><h3>Why do you have to pay attention to CSS selectors?</h3><p>Answer this question. When you want to put a nail on the wall, will you use a brick, cobblestone or hammer?</p><p>Brick and cobblestone can do the job. But, <strong>Hammer</strong> is the tool for the job.</p><p>Just like that, there are ways to identify elements in an HTML document/DOM. But CSS selectors are the tool for the job. They have a <a href="https://www.w3.org/TR/selectors-3/">specification that browsers need to follow</a></p><p>If you are an automation engineer working on UI automation, invest time in learning CSS selectors (how about reading through the rest of the article?). You will reap benefits that are much more.</p><p>I can hear your question: “But, it is so easy to copy the XPath. How about CSS selectors?” Trust me, in many browsers, the option is right there next to Copy XPath. You’ll find Copy CSS Selector or Copy Selector.</p><p>Do you know why? Because the front-end developers use CSS selectors to apply visuals and behaviors of the web pages even before they come down to testing.</p><h3>Why CSS Selectors Were Invented?</h3><p>Have you ever wondered why all those classes and IDs are there? Did you ask anyone that I’d need some ID/classes included in these elements so that I can automate tests for this UI?</p><p>If not you, then who asked for those attributes?</p><p>The story goes back to the days when styles were added to HTML documents. This was before UI testing was automated. Each browser had its own way of styling documents. Document (HTML) authors were not in control as to how their documents were presented to readers. Authors needed a way to target tags and apply styles to arrive at the layout they wanted. <a href="https://www.w3.org/Style/CSS20/history.html">Håkon Wium Lie</a> proposed what would become the current cascading style language.</p><p>Selectors to target specific elements was specified formally by <a href="https://www.w3.org/Style/CSS/members">CSS Working Group</a>. The browser developers take that specification as the requirement and build the browsers to support CSS.</p><p>Attributes such as id and class were added as hooks to target specific elements. They are there to help front-end developers style and attach behaviors to elements. <strong>Automation engineers can piggyback</strong> on the same provisions, CSS selectors, to identify elements.</p><h3>How CSS selectors are used?</h3><p>To style an element, Front end developers need to locate the element first and then apply styling rules.</p><p>It looks like this:</p><pre>#logo{ color: white; background: black; }</pre><p>That CSS snippet says, apply color and background styles to any element with an ID of logo. Normally, ID will be unique in any HTML document carefully crafted. But there are chances for multiple developers working on the same page to use the same ID for different elements. Most of the time, without knowing it is already being used. Don’t worry, they’ll eventually catch up with that bug, but the point is the browser throws no warning. You should tell the developers when you find such scenarios.</p><p>The JavaScript developer who wants to take the logo for a spin writes code like this:</p><pre>let element=document.querySelector(&quot;#logo&quot;); <br>rotate(element);</pre><p>Don’t worry about the implementation of rotate, but just look at the first line. document.querySelector is a native API available to select elements in a browser. …and it takes CSS selector syntax.</p><p>In fact, you can use it within <strong>JavascriptExecutor</strong>.</p><p>Since Front End Developers are using CSS selectors to locate elements (either to style them / amend the elements / to attach behavior to elements), it makes sense for the UI test automation engineers also to use the same API to locate elements.</p><p>Convinced? Here is a preview of different selectors replaced by CSS selector.</p><pre>Other Selectors          =&gt; By.cssSelector <br>------------------------ =&gt; -------------- <br>By.className(&quot;register&quot;) =&gt; &quot;.register&quot; <br>By.tagName(&quot;table&quot;)      =&gt; &quot;table&quot; <br>By.id(&quot;unique_id&quot;)       =&gt; &quot;#unique_id&quot; <br>By.name(&quot;login&quot;)         =&gt; &quot;[name=login]&quot; <br>By.xpath(&quot;//body/nav&quot;)   =&gt; &quot;body &gt; nav&quot; <br>By.xpath(&quot;//body//nav&quot;)  =&gt; &quot;body nav&quot;</pre><h3>Four Selectors</h3><p>Let’s look at primitive selectors to start with. There are just about 4 you need to master and this is the easy part.</p><h4>Hash # for IDs</h4><p>Any element with a particular ID can be located using By.cssSelector by prefixing a hash # to the ID.</p><p>For example:</p><pre>By.cssSelector(&quot;#logout&quot;)</pre><p>#logout will help you locate an element that has ID with a value logout. It doesn’t matter what the tag name is. It could be a link or a button, but cssSelector finds it.</p><p>Usually, the ID is unique. It’s a fair assumption that there’s usually one. Assumptions can go wrong. Twenty developers working on a very busy UI might end up slipping the same ID on two different elements. So, if you wanted to pair it with a tag, you can do so. Put the tag name in front of the ID.</p><pre>By.cssSelector(&quot;a#logout&quot;)</pre><p>This selector is even more specific. It says, <em>find an anchor tag (a link) with an ID valued as </em><em>logout</em>.</p><h4>Dot . for Classes</h4><p>Now that we know how to deal with IDs, locating elements by class names will only be easier than ever.</p><p>You need to prefix a dot . to the class name to find an element with such a class.</p><p>Example overdue:</p><pre>By.cssSelector(&quot;.btn_red&quot;)</pre><p>That’s going to be a red button (if the developer adds relevant styles), but let’s not worry about that. This selector will identify an element with a class btn_red. If more than one element is found, the first one is returned.</p><p>And if you wanted to combine a tag name and a class name?</p><pre>By.cssSelector(&quot;a.btn_red&quot;)</pre><p>That makes sense, doesn’t it?</p><h4>Tag stays the same</h4><p>Now, this one is even easier. What if you want to locate a particular element using its tag name? <strong>No prefix, no suffix</strong>. Just the tag name will do.</p><p>That will give you the first table on the page.</p><h4>[attr] for Attributes</h4><p>The last selector among the four. This is entirely based on attributes within an element. HTML elements tend to have attributes such as id, name, class, type, src, href, alt and a lot more under data- prefix.</p><p>All these attributes can be used to identify elements if you know that their attributes are uniquely identifiable.</p><p>Here is an example:</p><pre>&lt;img src=&quot;logo.png&quot; class=&quot;top&quot;&gt;</pre><p>The locator could be any one of these:</p><pre>By.cssSelector(&quot;[src]&quot;) <br>By.cssSelector(&quot;[src=logo.png]&quot;) <br>By.cssSelector(&quot;img[src=logo.png]&quot;)<br>By.cssSelector(&quot;img.top[src=logo.png]&quot;</pre><ul><li>The first one identifies all elements with a src attribute</li><li>The second one locates by src attribute with a specific value</li><li>Third one uses tag name, attribute and its value</li><li>Fourth one uses tag name, class name, attribute &amp; specific value</li></ul><p>They all differ in their specificity. The last one is very specific, the first one is very generic.</p><p>It is also possible to specify conditions such as starts with, ends with or contains for attribute values.</p><p>Few examples:</p><p>The html first:</p><pre>&lt;input type=&quot;text&quot; class=&quot;form_text&quot;&gt;<br>&lt;input type=&quot;email&quot; class=&quot;form_email&quot;&gt; <br>&lt;input type=&quot;radio&quot; class=&quot;form_radio&quot;&gt;</pre><p>And a few locators using attributes:</p><p>By.cssSelector Description &quot;input[type*=form]&quot; input elements with type attribute containing the text form in the value &quot;input[type^=form]&quot; input elements with type attribute starting with form &quot;input[type$=radio]&quot; input elements with type attribute ending with radio</p><h3>Four Combinators</h3><p>We saw four different selectors that form the basis of CSS selectors family. We’ll now look at four combinators that give special powers to those CSS selectors.</p><h4>Plus + for Adjacent Sibling</h4><p>If you want to select an element that follows another element, you can use adjacent sibling combinator using a plus +.</p><p>Let’s set up some sample HTML:</p><pre>&lt;div id=&#39;profile&#39;&gt; <br>  &lt;img src=&#39;head.png&#39;&gt; <br>  &lt;h1&gt;Mr.Neo&lt;/h1&gt; <br>  &lt;p&gt;The one&lt;/p&gt;<br>&lt;/div&gt;</pre><p>If you wanted to select all h1 tags that are placed right after an img tag, you can use the following:</p><pre>By.cssSelector(&#39;img + h1&#39;)</pre><p>If you wanted to select all p tags that follow a h1 tag, this would help:</p><p>It is the rightmost element that is selected. For example, while using h1 + p, the p element is selected. h1 is there as a supporting actor.</p><p>Finally, what if you wanted to select img tag from the previous HTML snippet? Food for thought.</p><h4>Tilde ~ for General Sibling</h4><p>We saw what plus + does. What if you wanted to check if an element is a sibling of another element, not necessarily an immediate sibling?</p><p>That’s where the general sibling combinator comes to rescue. It uses tilde ~ sign to indicate a general sibling.</p><p>Let’s set up a HTML snippet showing your name and photos:</p><pre>&lt;div&gt; <br>  &lt;h1&gt; Your name!&lt;/h1&gt; <br>  &lt;img src=&#39;pic1.png&#39;&gt; <br>  &lt;img src=&#39;pic2.png&#39;&gt; <br>  &lt;img src=&#39;pic3.png&#39;&gt; <br>&lt;/div&gt;</pre><p>If you wanted to access all images that are a sibling of a h1 tag, you can use the general sibling combinator. If there is only one img, you’ll get just that.</p><pre>By.cssSelector(&#39;h1 ~ img&#39;)</pre><p>In this instance, it doesn’t matter if the img tags follow h1 immediately. What matters is, they all have the same parent and img tags are a sibling to h1.</p><p>What if you use img ~ img? You’ll get the last two. Go figure.</p><p>And by the way, your dear most xpath gives you a way to get elements by sibling via special function:</p><pre>By.xpath(&quot;//img/following-sibling::h1&quot;)</pre><h4>Angle Bracket &gt; For Children</h4><p>Siblings are fine. But children started crying now. Let’s pay attention to them. These are widely used combinators too. You can target an element which is a direct child of a parent element using RIGHT ANGULAR BRACKET &gt; sign.</p><p>We can reuse some of our earlier HTML snippets:</p><pre>&lt;div id=&#39;profile&#39;&gt;<br>  &lt;img src=&#39;head.png&#39;&gt;<br>  &lt;h1&gt;Mr.Neo&lt;/h1&gt;<br>  &lt;p&gt;The one&lt;/p&gt;</pre><pre>  &lt;div id=&#39;crew&#39;&gt;<br>    &lt;img src=&#39;crew1.png&#39;&gt;<br>    &lt;h2&gt;Mr. Morpheus&lt;/h2&gt;<br>    &lt;p&gt;The other one&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>All three elements can be located using the following options:</p><pre>By.cssSelector(&#39;#profile &gt; img&#39;)<br>By.cssSelector(&#39;#profile &gt; h1&#39;)<br>By.cssSelector(&#39;#profile &gt; p&#39;)</pre><p>These selectors do not locate img or p tags within the crew section. Because they are not direct children of #profile element. They are descendants, but not children.</p><h4>Space for Descendants</h4><p>We are now down to the fourth and last combinator, the descendant combinator which is designated by a white space .</p><p>Let’s use the same HTML:</p><pre>&lt;div id=&#39;profile&#39;&gt;<br>  &lt;img src=&#39;head.png&#39;&gt;<br>  &lt;h1&gt;Mr.Neo&lt;/h1&gt;<br>  &lt;p&gt;The one&lt;/p&gt;<br>  <br>  &lt;div id=&#39;crew&#39;&gt; <br>    &lt;img src=&#39;crew1.png&#39;&gt; <br>    &lt;h2&gt;Mr. Morpheus&lt;/h2&gt; <br>    &lt;p&gt;The other one&lt;/p&gt; <br>  &lt;/div&gt; <br>&lt;/div&gt;</pre><p>Here is what happens:</p><p>Locator Description #profile img targets two img tags #profile h1 targets the only h1 tag #profile h2 targets the only h2 in there #profile p targets two p tags</p><p>You see the difference. Descendant combinator selects all matching tags as long as they are descendants of the parent element given.</p><p>A small white space has so much meaning!</p><h3>Twenty Four Pseudo Classes</h3><p>There are about 24 pseudo-classes to help you. You can find them in <a href="https://www.w3.org/TR/selectors-3/#pseudo-classes">the specification</a>. But, we’ll look at four to pique your interest.</p><h4>:not</h4><p>This one is to negate all you’ve learned so far. What will do without negatives? Let’s say you want to target an element without a particular class/id/attribute. :not will come to your aid.</p><p>The HTML:</p><pre>&lt;input type=&quot;text&quot; class=&quot;required&quot; /&gt;<br>&lt;input type=&quot;text&quot; class=&quot;required&quot;/&gt;<br>&lt;input type=&quot;text&quot;&gt;<br>&lt;input type=&quot;radio&quot;&gt;<br>&lt;input type=&quot;email&quot;&gt;</pre><p>If you wanted to locate an input box that is not mandatory (which does not have a class required so to speak):</p><pre>By.cssSelector(&#39;input:not(.required)&#39;)</pre><p>If you wanted to select all inputs that are not email type, then &#39;input:not([type=email])&#39; will do.</p><p>And you can chain them too, like this: input:not([type=radio]).not(.required). That would give you all inputs that are not radio buttons and do not have a class required. In this case, that’s just one text type and another email type inputs.</p><h4>:nth-child</h4><p>This one helps you with targeting a particular element based on its position.</p><pre>&lt;div id=&#39;profile&#39;&gt; <br>  &lt;h1&gt;Name&lt;/h1&gt; &lt;img src=&#39;pic.png&#39; /&gt; <br>  &lt;img src=&#39;background.png&#39; /&gt; <br>  &lt;p&gt;Summary...&lt;/p&gt; <br>  &lt;p&gt;Details...&lt;/p&gt; <br>  &lt;p&gt;Conclusion...&lt;/p&gt; <br>&lt;/div&gt;</pre><p>Remember child selector from previous sections. We are going to use it. How do you say, “Get me the second child within the profile”. #profile &gt; *:nth-child(2) will do. * denotes any tag and nth-child looks for a particular child based on the number you’ve given.</p><p>You could have used the right tag name instead of *, as in #profile &gt; img:nth-child(2). You need to be careful when the tag name does not match. No element will be selected if you use a tag name that is not there. For example, #profile &gt; h1:nth-child(2) returns nothing, as the second child is not a h1 tag.</p><p>:nth-child takes input like a number, odd, even and 3n+2. You can read 3n+2 like, every 3rd element starting from the 2nd element. MDN defines it as An+B. This is used more in terms of styling elements. May not be so much for test automation. Let’s leave it right there.</p><p>There is another one to get an element counting from bottom: <strong>:nth-last-child</strong>. For example, #profile &gt; *:nth-last-child(1) will give you the last child, which is p tag that has the text “Conclusion…”. The spec has :last-child as a pseudo-class that will give you the similar outcome.</p><p>I’ll leave you to guess what <strong>:first-child</strong> would return.</p><h4>:nth-of-type</h4><p>While nth-child takes all children into account, nth-of-type takes only the tag type into account. Let’s use the same piece of code.</p><pre>&lt;div id=&#39;profile&#39;&gt;<br>  &lt;h1&gt;Name&lt;/h1&gt;<br>  &lt;img src=&#39;pic.png&#39; /&gt;<br>  &lt;img src=&#39;background.png&#39; /&gt;<br>  &lt;p&gt;Summary...&lt;/p&gt;<br>  &lt;p&gt;Details...&lt;/p&gt;<br>  &lt;p&gt;Conclusion...&lt;/p&gt;<br>&lt;/div&gt;</pre><p>We’ve seen that, #profile &gt; img:nth-child(1) would return nothing, as first child is h1, but #profile &gt; img:nth-of-type(1) returns the first image. The spec also has something called :first-of-type as a shorter version.</p><p>What do you do to count from the bottom (reverse order)? Yeah, <strong>:nth-last-of-type</strong> will come to your help. You also have <strong>:last-of-type</strong> to get the bottom-most child of the specified type.</p><h4>:disabled</h4><p>One last pseudo-class we’ll look at is :disabled. This is handy when you look for a particular element that is either disabled or enabled. In fact, <a href="https://www.w3.org/TR/selectors-3/#pseudo-classes">the specification</a> has classes like :enabled, :checked and other pseudo-classes for you to use.</p><h3>In Xpath’s defense</h3><blockquote><em>Knowing CSS selectors and then choosing XPath as a solution is different from NOT knowing CSS selectors and choosing XPath.</em></blockquote><p>Final words, do not get discouraged if you have been using XPath all the while. By now, you would have seen that they are very similar in nature. They have their own pros and cons. cssSelectors perform well as they are natives to the browser. XPath is more readable in certain instances. Whichever gets the job done is ok. One of these make your code readable? Go for that. Performs well over the other, choose that. Just don’t limit your options.</p><p>In my experience, test automation engineers started using XPath universally. So, this article was to add a counterweight to cssSelectors so that the scale is balanced against XPath. In fact, John Resig, creator of jQuery has written about such a <a href="https://johnresig.com/blog/xpath-css-selectors/">comparison showing how powerful xPath</a> can be (years ago).</p><p>References</p><ul><li><a href="https://flukeout.github.io/">Try this diner game for practice.</a></li><li><a href="https://www.w3.org/TR/selectors-3/">Official specification Level 3</a></li><li><a href="https://drafts.csswg.org/selectors-4/">Official draft Level 4</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors">The ever friendly MDN reference</a></li></ul><p>All right! <strong>Thanks for your time. </strong>Did you find this useful? Use your claps to let me know.</p><p><em>Originally published at </em><a href="https://www.pineboat.in/post/css-selectors-selenium-webdriver-find-element-xpath-replaced/"><em>www.pineboat.in</em></a><em>. You should </em><a href="http://eepurl.com/cYynNv"><em>subscribe here</em></a><em>, I’ll let you know when I write something new. Got you covered if you are </em><a href="https://www.pineboat.in/index.xml"><em>going back to RSS feeds</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28082be1cd3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/why-css-selectors-are-the-most-useful-selenium-webdriver-locators-28082be1cd3b">Why CSS Selectors are the most useful Selenium WebDriver locators?</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to energize your scary terminal with helpful little scripts]]></title>
            <link>https://medium.com/free-code-camp/how-to-energize-your-scary-terminal-with-helpful-little-scripts-c5ae92c12bfe?source=rss-783f35ad67e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ae92c12bfe</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Vijayabharathi Balasubramanian]]></dc:creator>
            <pubDate>Tue, 05 Dec 2017 11:58:10 GMT</pubDate>
            <atom:updated>2017-12-05T11:58:10.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ip_q_6I-kNpUjuPMOutuTA.jpeg" /><figcaption>Photo by Matt Artz on Unsplash</figcaption></figure><p>I’m going to talk about three valuable tools that will finally help conquer your fear of terminals: Git Aliases, Bash Aliases, and One click snippets.</p><p>A combination of aliases and bash scripts can make you very productive in your development workflow. Use it long enough and you’ll even forget the original commands beneath the aliases. Which isn’t actually a bad thing — until you get a shiny new laptop and have no idea where you placed your aliases in the old one :)</p><p>You may have used Git aliases. You might find bash aliases new. <strong>But, don’t miss</strong> the gif showing one-click icons at work towards the end. Those one-click desktop icons are my line of defense. They help me dive straight into coding/writing before the harmless “<strong>top visited</strong>” list on the browser’s new tab can send me off track.</p><p>By the way, I’m using Firefox’s nightly and it is easy to set up a clean slate as your new tab. All right, down to business.</p><h3>1: Git Aliases</h3><p>If terminal is the dungeon to people new to tech, Git tends to be the darkest passage, intimidating with long stretches of commands.</p><p><strong>But, Git is beautiful. </strong>Try this <a href="https://try.github.io/">game</a>.</p><p>Part of making git easier to use is setting up your own aliases. That is, once you understand the underlying commands. This is not to give you <strong>all</strong> the useful aliases. Instead, I’ll point you towards the possibilities so that you can <strong>build your own list of aliases.</strong></p><h4>Flying Solo</h4><p>Let’s say you are hacking on your own. You stage and commit all day, maybe your code or your writings for the blog. You’ll find a bunch of aliases very useful.</p><pre>git config --global alias.s status<br>git config --global alias.aa &#39;add --all&#39;<br>git config --global alias.cm &#39;commit -am&#39;<br>git config --global alias.up &#39;push&#39;</pre><p>Make sure you have a well defined .gitignore to avoid tracking unnecessary files such as node_modules. This will help you when you use git aa to stage all files.</p><p>All these aliases are stored in a config file under home directory. Take a look into ~/.gitconfig. You can even edit the config file directly — just make sure you don’t trip it off.</p><h4>Code Collaboration</h4><p>When you are collaborating with a team, a whole other list of commands may be useful. Remember, rebase rewrites history. It is <a href="https://coderwall.com/p/7aymfa/please-oh-please-use-git-pull-rebase">advised only for local branches</a>, to clean up your code on top of remote branch.</p><pre>git config --global alias.pr &#39;pull --rebase upstream master&#39;</pre><p>Here is one from <a href="https://csswizardry.com/2017/05/little-things-i-like-to-do-with-git/">Harry</a> about aliasing blame to praise and other nuggets that you may find useful.</p><h4>Advanced Aliases</h4><pre>git config --global alias.ls &#39;log --pretty=format:&quot;%C(yellow)%h %C(green)%s %Creset(%ad)&quot; --date=relative&#39;</pre><p>%C(yellow) marks the token following the color code in red. In our case above, %h stands for the commit hash, which will be painted yellow on our terminal. %Creset, without brackets, takes you back to default terminal font color. --date=relative tells you days/weeks ago instead of an actual date.</p><p>All those words may try hard to explain how it looks, but here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*0Jq_saMUzAe3XzA5iLkTcw.png" /><figcaption>color-coded git log</figcaption></figure><h4>References</h4><p>You can learn more about decorating in <a href="https://git-scm.com/docs/pretty-formats">git-scm.com</a>. There is a whole bunch of information that you can extract such as %h, %n and so on. By the way, <strong>that’s a whole free book on Git</strong>. Start from page 1.</p><p>I learned a lot of useful tricks from Nicola a while back from his 2014 Atlassian summit talk. I couldn’t find the video, but I found <a href="https://www.slideshare.net/GoAtlassian/becoming-a-git-master-nicola-paolucci">his slide</a>. Don’t miss that anonymous function within aliases.</p><p>Here is a list of his G<a href="http://bit.do/git-aliases">it aliases</a>. But, in his own words, do not just copy aliases. Build them as you go, adding only the aliases that are useful to you. Otherwise, it’ll just be like spending hours curating articles/books that we’ll never read.</p><h3>2: Bash Aliases</h3><p>Git is not the only command line interface (CLI) that asks for some typing on the terminal. Think about bundle exec rails db:migrate on a terminal or docker-compose exec npm run script that you run on a container. How about something shorter?</p><p>If you use commands that are longer, on a daily basis, consider setting up bash aliases.</p><p>The syntax is very simple.</p><pre>alias new_cmd=&#39;never-ending-command; and another command&#39;</pre><p><strong>You add this at the end of the </strong><strong>.bashrc file in your home folder.</strong> Normally ~/.bashrc is where it is located. The recent one I have set up is for docker commands. It should serve as an example.</p><pre>alias dc=&#39;docker-compose&#39;<br>alias de=&#39;docker-compose exec&#39; <br>alias up=&#39;cd ~/Projects/docker_project/; dc up&#39;</pre><p>I used to log out and log back in to make it work on terminals. However, this cool command from S<a href="https://stackoverflow.com/questions/2518127/how-do-i-reload-bashrc-without-logging-out-and-back-in">tackoverflow</a> rescued me. Run this on your terminal and start using new aliases right away: source ~/.bashrc</p><p>Are you thinking what I am thinking? Forget about Git aliases? What do we name bash alias for git pull --rebase upstream master? How about gprum?</p><p>Go wild! Be cautious <strong>not to reuse existing commands.</strong> For example, df shows free disk space in Linux, so I wouldn’t use that as an alias for anything else.</p><h3>3: One-Click Snippets</h3><p>My favorites. One click, on your custom designed desktop icon, with your own logo, and you’ll have these ready to roll:</p><ul><li>Opens your project folder in VS Code/atom</li><li>A terminal running dev server on one tab</li><li>Another tab running tests / hot reloading</li><li>Last tab that opens with Git status</li><li>The last tab stays open for you to git things done.</li><li>If your dev server doesn’t open browser, you can open it here</li></ul><p>There is something magical when you can just tap on an icon and the entire environment springs up for you. One tap and you get your text editor, web server and tests running already.</p><p>The bash file get-to-work.sh looks like this. By the way, this is on Linux.</p><pre>#!/bin/bash<br>export WD=&quot;~/development&quot;<br>code $WD gnome-terminal \<br> --tab --working-directory=$WD \<br> -e &#39;bash -c &quot;export BASH_POST_RC=\&quot;npm start\&quot;; exec bash&quot;&#39; \<br> --tab --working-directory=$WD \<br> -e &#39;bash -c &quot;export BASH_POST_RC=\&quot;npm run watch\&quot;; exec bash&quot;&#39; \<br> --tab --working-directory=$WD \<br> -e &#39;bash -c &quot;export BASH_POST_RC=\&quot;git status\&quot;; exec bash&quot;&#39;</pre><p>We have a working directory set up under variable WD. Then starts a very long line that folds for 7 lines on a terminal width of 80 characters. Don’t let it scare you. If you watch closely, we are opening gnome-terminal with three tabs and running three different commands on them.</p><p>Run this command to mark the bash script executable.</p><pre>chmod +x get-to-work.sh</pre><p>You can already check if the script is working. cd into the folder where you have the shell script and type this on your terminal.</p><pre>./get-to-work.sh</pre><p>Let’s add a nice desktop icon to our script. Exec and Icon are important. They need to be in a .desktop file. I’ve named mine as get-to-work.desktop.</p><p>By the way, this is for Linux. Most of the desktops use <a href="https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html">freedesktop</a> specification. Reading between the lines, I might have broken a few guidelines (such as not removing any fields even if they are not applicable).</p><pre>[Desktop Entry] <br>Name=Get To Work <br>Comment=Start coding in an instant. <br>GenericName=Development Environment <br>Exec=/home/username/snippets/get-to-work.sh <br>Icon=/usr/share/icons/logo.png <br>Type=Application <br>Terminal=true <br>StartupNotify=true <br>Categories=Utility;</pre><p>Remember to use the correct path instead of /home/username/.... Make sure you place the Icon in an accessible folder where you have permission to at least read the file.</p><p>Validate and install the .desktop file.</p><pre>desktop-file-validate get-to-work.desktop <br>desktop-file-install get-to-work.desktop</pre><p>In case you have permission issues, it is better to install it locally, like this:</p><pre>desktop-file-install get-to-work.desktop --dir=.local/share/applications</pre><p>That’s it. You’ll have your logo ready as an application within your launcher. You can set it up in the dock too.</p><h4>Watch One-click Icon in Action</h4><p>Here is a gif showing my recent one-click script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*HR8MRt3l6Xx2HZhj.gif" /></figure><p>A larger one, 2.6MB, can be found <a href="https://www.pineboat.in/img/005_one_click/one-click.gif">here</a> if you want to take a closer look.</p><p>Here is one more I use to start writing my blog.</p><ul><li>Opens up blog folder on VS code</li><li>Loads up localhost on firefox</li><li>Opens up hugo server on terminal</li></ul><p>Unlike the previous example, in this one, I use the elementary OS and default pantheon-terminal that comes with it. But this doesn’t open multiple tabs, and I haven’t figured out how to make pantheon-terminal do it (like we saw earlier with gnome-terminal ). That little &amp; at the end of firefox gives control back to the script. Otherwise, my terminal wouldn’t open until I close firefox.</p><pre>#!/bin/bash  <br>export WORK_DIR=&quot;~/pineboat&quot; <br>/opt/firefox/firefox localhost:1313 &amp; <br>code $WORK_DIR <br>pantheon-terminal -e &#39;bash -c &quot;cd $WORK_DIR;hugo server -wvFD&quot;&#39;</pre><p>Finally, I’ve setup a desktop file with the logo of my blog. Pretty sweet, isn’t it?</p><p>Hope that was useful and saves few keystrokes. Clap/Share/Tweet to let your network know, if you think they’ll enjoy this post. Any issues, log it under this <a href="https://github.com/pineboat/pineboat.github.io/issues/4">github issue</a>. Or in the conversations below.</p><p>Thanks for your time and attention!</p><p><em>Originally published at </em><a href="https://www.pineboat.in/post/energize-terminal-with-git-bash-aliases-one-click-icon/"><em>www.pineboat.in</em></a><em> — an uncharted island in the internet.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ae92c12bfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-energize-your-scary-terminal-with-helpful-little-scripts-c5ae92c12bfe">How to energize your scary terminal with helpful little scripts</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regular Expressions Demystified: RegEx isn’t as hard as it looks]]></title>
            <link>https://medium.com/free-code-camp/regular-expressions-demystified-regex-isnt-as-hard-as-it-looks-617b55cf787?source=rss-783f35ad67e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/617b55cf787</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vijayabharathi Balasubramanian]]></dc:creator>
            <pubDate>Thu, 23 Nov 2017 21:35:28 GMT</pubDate>
            <atom:updated>2017-11-26T03:27:32.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*kKGQn6RZmO--M8ix.jpg" /><figcaption>Understand Regular Expressions with this practical guide. image source — <a href="https://unsplash.com/photos/q99oeAG46BY">Unsplash</a></figcaption></figure><p>Are you one of those people who stays away from regular expressions because it looks like a foreign language? I was one. Not anymore.</p><p>Think of all those sounds, traffic signs and smells that you can recognize. Regular expressions are no different. It’s like a sign language to analyze strings.</p><p>We are going to get our head around regular expressions today. At least, <strong>regularly</strong> used expressions.</p><p>Much like any programming language, a regular expression is a succinct language in its own right.</p><p>We will know how to put regular expressions to good use by the end of this article. We will solve simple problems and learn loads in the process.</p><p>Are you willing to invest 30 minutes and come out enlightened in RegEx? Settle down then.</p><h4>Why regular expressions?</h4><p>We each have our own ‘why’, don’t we? One may be to test if the string is a valid hex color code. You may be writing a processor library such as <a href="https://github.com/search?l=&amp;q=regexp+repo%3Asass%2Fsass&amp;ref=advsearch&amp;type=Code&amp;utf8=%E2%9C%93">Sass</a> that leverages RegEx.</p><p>I’ll let the universe throw the <strong>why</strong> at you and help you cover the <strong>how</strong>.</p><h3>0. Get Your Playground Ready</h3><h4>References</h4><p>Most of the time, I find this page adequate to get going: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions from MDN</a>. In fact, that page is all you need. You can stop reading this post. Right now. Close this tab. 😉</p><p>Still with me? Thanks. You need a sandbox to play around in. Luckily, one is available on your browser. Just use the DevTools in your browser’s console.</p><h4>Familiarize yourself with the syntax</h4><p>To start with, we are going to use the /expression/.test(&#39;string&#39;) syntax.</p><p>An expression is any regular expression that we build. A string is the string under test. The test method returns true or false depending on the match.</p><p>Slashes mark the start and end of the expression. Treat them like the double quotes (“) and single quotes (‘) that you use to the mark start and end of a plain string.</p><p>The expression between / is a literal. <strong>They are treated as literal characters.</strong> Variable names wouldn’t be resolved down to their contents.</p><p>To make it dynamic, we’ll have to go via the constructor route, using new RegEx(variable_name) syntax. This will come to rescue towards the end of the post.</p><p><strong>Do it right now.</strong> Just type this into your browser console.</p><pre>/a/.test(&quot;a&quot;); //true<br>/a/.test(&quot;b&quot;); //false</pre><p>If that works, you are ready. Don’t worry about what it is. That’s what we are going to breakdown into pieces in the following lines.</p><p>Let’s dive in…</p><h3>1. Start Small With Letters</h3><p>Let’s start small. We need to find if a string has a particular character. Look for the character a in a string.</p><p>Here is the expression in all its glory:</p><pre>/a/.test(&quot;abc&quot;); //true <br>/a/.test(&quot;bcd&quot;); //false <br>/a/.test(&quot;cba&quot;); //true</pre><p>The expression does what we asked for, “Look for a in the string under test”. In our case, abc and bca do have the character a. But bcd does not have it.</p><h4>Breakdown</h4><p>Now, that’s a lot of slashes and backslashes. Let’s break them down.</p><p>We’ve seen that /expression/ is how we build regular expressions. So no question about slash there. In fact, we can even <strong>assign it to a variable</strong> and make it look better.</p><p><strong>The same code:</strong></p><pre>let e=/a/; <br>e.test(&quot;abc&quot;); //true <br>e.test(&quot;bcd&quot;); //false <br>e.test(&quot;cba&quot;); //true</pre><p>The expression between slashes is just a single character a in our case. We are looking only for that one character.</p><h4>Reach Multi-Characters</h4><p>Let’s scale the solution.</p><p>What if you want to find more than one character?</p><p>Put them in sequence. Treat them as a substring.</p><p>Here is an example:</p><pre>/ab/.test(&quot;abacus&quot;); //true <br>/bac/.test(&quot;abacus&quot;); //true  <br>/abc/.test(&quot;abacus&quot;); //false <br>/abas/.test(&quot;abacus&quot;); //false</pre><p>The string under test should contain the exact expression within slashes. We get a match if that condition is met.</p><p>bac is within abacusbut abas is not in abacus as it is. Even though we have those characters scrambled, we do not get an exact match.</p><h4>Review Ground Covered</h4><p>Symbol /.../ . Slash (/) marks the start and end of the regular expression. Ignore the dots, that’s where we place the pattern. The /a/ character between slashes is a pattern matched on string under test. The /abc/ characters between slashes are looked up as a sub-string during the pattern matching test on string under test.</p><h3>2. Patterns in Numbers</h3><p>Let’s spice it up a bit. Let’s say you want to find out if a string is full of numeric characters.</p><p>Here it is:</p><pre>let e=/0|1|2|3|4|5|6|7|8|9/;<br>e.test(&quot;42&quot;); //true <br>e.test(&quot;The answer is 42&quot;); //true</pre><p>First of all, the pattern looks pretty long. But the same long streak of characters <strong>can be expressed in just two characters</strong>. I reserved it towards end of this section for a dramatic closure.</p><p>The second case shouldn’t be true. We’ll deal with it a bit later.</p><p>For now, the pipe symbol (|) means <strong>or</strong>. Outside of regular expressions, we’ve used it as a bitwise <strong>or</strong> and conditional <strong>or</strong> with double pipes (||). That’s the same guy.</p><p>I could call that easy and call it a day. But you would scream for something better, right? We are developers. We spend the best part of our day thinking about better Bash and Git aliases to save few keystrokes.</p><p>Should I type in nine pipe symbols? Nah.</p><p>Here we go again:</p><pre>e=/[0123456789]/; <br>e.test(&quot;42&quot;); //true <br>e.test(&quot;The answer is 42&quot;); //still true</pre><p>This is better. 9 pipes were replaced with 2 square brackets. 7 characters were saved. That’s 77.7% less keystrokes.</p><p>By the way, anything within square brackets is considered as Either this or that. It is a character set. In our case, the string should contain either 0, or 1, or 2, or…bear with me, I promised myself to write 1000 words a day, or 3 or 4 or 5. All right, let’s stop. You get it.</p><p>What are you saying? It still looks quite lengthy? Not satisfied?</p><p>Okay, here we go once again:</p><pre>e=/[0-9]/; <br>e.test(42); //true <br>e.test(&quot;42&quot;); //true <br>e.test(&quot;The answer is 42&quot;); //true!</pre><p>How about that? Looks much cleaner, doesn’t it? Anything within square brackets [] means <strong>or</strong>. 0-9 marks a range, meaning zero to nine.</p><p>So the test looks for characters from zero to nine in the test string.</p><p>As you can see, the test takes numbers too.</p><h4>The prefix and suffix patterns</h4><p>Let’s now address that failing second case. The answer is 42 matches our test because our pattern looks for numeric characters somewhere <strong>within</strong> the string. <strong>Not start to end</strong>.</p><p>Let’s bring in ^ and $ to help us.</p><ul><li>^ means the <strong>start</strong> of the string. He is a double agent and he’ll trip us off. His second avatar is unmasked only in the last section.</li><li>$ means the <strong>end</strong> of the string.</li></ul><p>Let’s get the prefix pattern sorted out:</p><pre>/^a/.test(&quot;abc&quot;); //true <br>/^a/.test(&quot;bca&quot;); //false <br>/^http/.test(&quot;https://pineboat.in&quot;); //true /^http/.test(&quot;ftp://pineboat.in&quot;); //false</pre><p>Any pattern that follows ^ should be at the start of the string under test.</p><p>The second string starts with b while our pattern looks for a. The fourth one looks for http while the string starts with ftp. This is the reason they fail.</p><h4>The suffix patterns</h4><p>The suffix pattern follows. $ at the end of the pattern directs the test to look for end of string.</p><pre>/js$/.test(&quot;regex.js&quot;); //true <br>/js$/.test(&quot;regex.sj&quot;); //false</pre><p>That should sound in your head like, “Look for js and then the end of the string”. Better yet, “Look for a string that ends in js”.</p><h4>Pattern match End to End</h4><p>That paves the road to pattern match start to end, you might as well call it end to end.</p><pre>let e=/^[0-9]$/ <br>e.test(&quot;42&quot;); //false - NO! <br>e.test(&quot;The answer is 42&quot;); //false <br>e.test(&quot;7&quot;); //true</pre><p>Surprisingly, the first one failed when we added ^ and $.</p><p>/^[0-9]$/ reads like, “Go to the start of the string. Look for a<strong> single numeral</strong> from the character set. Check if the string ends right there.” That’s the reason the last entry returned true. It is just a single number, start to end.</p><p>That’s not what we wanted. We wanted to test if the string had one or more numerals.</p><p>We are very close. One last thing we need to learn is how to instruct the pattern to look for more than one character in the set.</p><h4>Tale of Three Musketeers</h4><p>A question mark (?), a plus (+) and an asterisk (*) met at a battle ground. Each is differently sighted.</p><p>The humble question mark (?)says, “I can see none or just one.”</p><p>Plus (+) says, “I need to see at least one or more.”</p><p>Asterisk (*) says, “I get you both. I can see none, one, or more.”</p><p><strong>One of them is cleverly hiding what he is capable of.</strong></p><p>The question mark gets on stage first:</p><pre>/a?/.test(&quot;&quot;); //true <br>/a?/.test(&quot;a&quot;); //true <br>/a?/.test(&quot;b&quot;); //true! <br>/a?/.test(&quot;aa&quot;); //true <br>/^a?$/.test(&quot;aa&quot;); //false</pre><ul><li>Matches empty string &quot;&quot; <br>as ? stands for 0 or 1</li><li>Matches a <br>one match</li><li>Matches b<br> matches 0 occurrence</li><li>Matches aa <br>one match and the second a is not part of the pattern</li><li>/^a?$/ does not match aa<br>It looks for zero or one a, start to end, nothing more, nothing less</li></ul><p>The plus (+) looks at question mark and remarks, “I’m impressed, but your focus is so binary!”. And takes the stage to show off:</p><pre>/a+/.test(&quot;a&quot;); //true <br>/a+/.test(&quot;aa&quot;); //true <br>/a+/.test(&quot;ba&quot;); //true! <br>/^a+$/.test(&quot;aa&quot;); //true  <br>/a+/.test(&quot;&quot;); //false <br>/a+/.test(&quot;b&quot;); //false <br>/^a+$/.test(&quot;ab&quot;); //false</pre><p>Remember what plus (+) said? It can match one or more occurrences of preceding pattern.</p><p>All those returning true have one or more a. We even managed to get a whole string comprised only of a in the last one that returned true with /^a+$/.</p><p>false should make sense now, but a word on the last one that returned false. /^a+$/ looks for a start to end, no other characters allowed. This is why ab failed the test.</p><p>Finally, star (*) of the show gets on stage. He boasts that, “I can duel alone or duel you both at once” and says, “I can match zero, one or more”.</p><pre>/a*/.test(&quot;a&quot;); //true <br>/a*/.test(&quot;aa&quot;); //true <br>/a*/.test(&quot;ba&quot;); //true <br>/a*/.test(&quot;&quot;); //true <br>/a*/.test(&quot;b&quot;); //true <br>/^a*$/.test(&quot;aa&quot;); //true <br>/^a*$/.test(&quot;&quot;); //true  <br>/^a*$/.test(&quot;ab&quot;); //false</pre><p>Except the last one, * was able to handle all else. /^a*$/ reads like, 0 or more a start to end. Which is why empty string &quot;&quot; passed the test and &quot;ab&quot; failed.</p><h4>Back to the Universal Answer</h4><p>Remember where were we before we met the three musketeers? Yes, “The answer is 42”.</p><p>Now if we need to look for only numerals, one or more, start to end, what do we do?</p><pre>//Let&#39;s throw in a plus <br>let e=/^[0-9]+$/ <br>e.test(&quot;4&quot;); //true <br>e.test(&quot;42&quot;); //true <br>e.test(&quot;The answer 42&quot;); //false - Hurray</pre><p>The plus sign (+) in [0-9]+ comes to our rescue. Plus means more than one occurrence of the character or pattern in front of it. In our case, more than one numerals.</p><p>It also fails the match for our last case The answer is 42 because, there are no numerals at the start of the string.</p><h4>Practice Patterns</h4><ul><li>Can you try to write a pattern for hexadecimal numbers (consisting of numerals 0–9 and letters a-f, with an optional # in front)?</li><li>How about a binary number? Can you test if a string is full of just 0 and 1?</li></ul><h4>That Dramatic End</h4><p>Oh, I almost forgot. [0-9] stands for any of the numeric character set and also has a shorthand version \d.</p><pre>let e=/^\d+$/; e.test(&quot;4&quot;); //true e.test(&quot;42&quot;); //true e.test(&quot;The answer 42&quot;); //false - Hurray</pre><p>Just two characters denoting numerals. And No, it doesn’t get any shorter than that.</p><p>There are a whole bunch of such special patterns to specify clusters such as numbers (\d), alpha numeric characters (\w), white spaces (\s).</p><h4>Review</h4><ul><li>[123]<br>The expression within square brackets are a character set<br>Any one of the characters match will pass the test. Just ONE character.</li><li>[0-9] <br>Looks for a single numeric digit between 0 to 9</li><li>[0-5] <br>Looks for a single numeric digit between 0 to 5</li><li>[a-z] <br>Looks for a single letter between a to z</li><li>[A-F] <br>Looks for a single letter between A to F</li><li>[123]+ <br>Plus (+) looks for one or more occurrence of the characters within the set This one matches a “23132” sub-string that consists of 1, 2 and 3 within a larger string “abc23132”.</li><li>| <br>Pipe symbol stands for <strong>or</strong></li><li>\d <br>A shorthand for numerals<br>Matches a single numeric digit.</li><li>\D <br>A shorthand for non-numeric characters<br>Anything other than numerals that’ll be matched by \d</li></ul><h3>3. Recurrence Match to Find Duplicates</h3><p>This is the actual problem I was trying to solve. I dove deep into regular expressions, which eventually led to this post.</p><p>You’ve been given a string. Find out if it has been infused with duplicate characters before sunset.</p><p>Here is the solution for duplicate characters appearing immediately after an occurrence:</p><pre>let e=/(\w)\1/; <br>e.test(&quot;abc&quot;); //false <br>e.test(&quot;abb&quot;); //true</pre><p>The expression does not match any part of the string abc as there are no duplicate characters in sequence. So it returns false.</p><p>But it matches bb part of the string abb and returns true.</p><p>Go ahead, type that on your DevTool console. Look at this!</p><p>Let’s break it down to understandable pieces.</p><h4>Backslash \ Unleashed</h4><p>I’ve been a little quiet about the backslash that was introduced in the last section. To those who have <strong>been there</strong> and <strong>done that</strong>, it may not have been a surprise. They might have <strong>escaped</strong> the confusion. But if you are new to programming world, you need to know more about backslash.</p><p>In the regular expression language, backslash is special. The backslash alters the meaning of the characters that follow them. Ring a bell?</p><p>What do you call \n when you encounter it in a string? Yes, a new line. We’ve got something similar here.</p><p>In fact, \n is what you use as a pattern if you want to look for a new line. That’s called escaping the usual meaning of n and giving it a whole new attire called new line.</p><ul><li>\d<br>A shorthand for numerals<br>Matches a single numeric digit</li><li>\D <br>A shorthand for non-numeric characters<br>Anything other than numerals that’ll be matched by \d</li><li>\s <br>Shorthand for single white space character such as space, new line or tab.</li><li>\S Antonym of \s<br>anything other than white space</li><li>\w <br>Shorthand for alpha-numeric character<br>Matches a-z, A-Z, 0–9 and underscore _.</li><li>\W <br>Antonym of \w</li></ul><h4>Recallable Matches</h4><p>We started this section with the solution for finding duplicate characters. /(\w)\1/ matched &quot;abb&quot;. That shows use of memory and recall within regular expressions.</p><p>Consider the use of brackets in this format (expression). The resulting string that matches the expression within a bracket is remembered for later use.</p><p>\1 remembers and uses the match from first expression that is within brackets. Likewise, \2 from second set of brackets. And so on.</p><p>Let’s translate our expression (\w)\1 to plain English:</p><p>Match any alpha-numeric character on a given string. Remember it as \1. Check if that character appears right next to the first occurrence.</p><h4>Extension 1 — Reverse Pairs</h4><p>Let’s say we want to find two characters appearing in reverse order right next to each other. That is like abba. ab is reversed as ba and is right next to each other.</p><p>Here is the expression:</p><pre>let e=/(\w)(\w)\2\1/; <br>e.test(&quot;aabb&quot;); //false <br>e.test(&quot;abba&quot;); //true <br>e.test(&quot;abab&quot;); //false</pre><p>The first (\w) matches a and remembers it as \1. The second (\w) matches b and remembers it as \2. Then the expression expects \2 to occur first followed by \1. Hence, abba is the only string that matches the expression.</p><h4>Extension 2 — No duplicates</h4><p>This time, we are going to look at sequence of characters with no duplicates. No character should be followed by the same character. Plain and simple.</p><p>Here, take a look at the solution:</p><pre>let e=/^(\w)(?!\1)$/; <br>e.test(&quot;a&quot;); //true <br>e.test(&quot;ab&quot;); //false <br>e.test(&quot;aa&quot;); //false</pre><p>Not the one we wanted, but close. The middle one shouldn’t be false. But we threw in a few more symbols that need explaining. That means confronting the most powerful musketeer once again.</p><h4>Return of the Question Mark</h4><p>Remember the three musketeers we met earlier. The humble <strong>question mark is actually the most powerful manipulator</strong> that can get other symbols to do his bidding. That is, if you take the backslash for granted.</p><p>A combination of brackets, question mark and exclamation mark (?!), is called a <strong>look ahead</strong>. A negative look ahead to be precise. a(?!b) matches a only if it is <strong>not</strong> followed by b.</p><p>Across JavaScript ecosystem, the exclamation mark means <strong>not</strong>. But its cousin CSS takes a u-turn and !important means it is actually very important and should not be overridden. I almost scrolled past <a href="https://twitter.com/vijayabharathib/status/910772769964548096">Chen’s tweet</a> thinking it is marked not important. I digress.</p><p>On the other hand, (?=) is a positive <strong>look ahead</strong>. a(?=b) matches a only if it is followed by b.</p><p>We had a solution. (\w)(?!\1) looks for a character without recurrence. <strong>But only for one character.</strong> We need to group it and look for 1 or more occurrences of characters with the use of plus (+). That’s all.</p><pre>let e=/^((\w)(?!\1))+$/; <br>e.test(&quot;madam&quot;); //false <br>e.test(&quot;maam&quot;); //false</pre><p>But it doesn’t seem to be working. If we group the pattern within plain brackets like ((\w)(?!\1)), the \1 does not represent(\w), it represents higher level bracket pair that groups the pattern. So it fails.</p><p>What we need is a <strong>forgetful</strong> grouping option. That’s where the question mark, ?, strikes back. It pairs with a colon, (?:) and wipes out any function of memory that the brackets can bring in.</p><p>One last time:</p><pre>let e=/^(?:(\w)(?!\1))+$/; <br>e.test(&quot;madam&quot;); //true <br>e.test(&quot;maam&quot;); //false</pre><p>This time, the first level of brackets are not remembered, thanks to ?:, hence, \1 remembers the match returned by \w.</p><p>It helps us use the plus + against the overall grouping to find similar pairs of characters start to end, which works like magic.</p><p>In English, “Look for a character. Look ahead to ensure it is not followed by the same character. Do this from start to end for all characters.”</p><h4>Review</h4><ul><li>\w represents all the alpha-numeric characters<br>If you capitalize ‘w’ and use \W&#39;, that would mean all characters <strong>other than</strong> alpha-numeric</li><li>( ) <br>The expression within a bracket is remembered for later use</li><li>\1 remembers and uses the match from first expression that is within brackets<br> \2 from second set of brackets. And so on.</li><li>a(?!b) <br>A combination of brackets, question mark and exclamation mark (?!), is called a <strong>look ahead<br></strong>This matches a only if it is <strong>not</strong> followed by b</li><li>a(?=b)<br>The other side of the coin<br>Match a only if it is followed by b. (?:a) <br><strong>Forgetful grouping<br></strong>Look for a but don’t remember it<br>You can’t use \1 pattern to reuse this match</li></ul><h3>4. Alternating Sequence</h3><p>The usecase is simple. Match a string that uses only two characters. Those two characters should alternate throughout the length of the string. Two sample tests for “abab” and “xyxyx” will do.</p><p>It wasn’t easy. I got it wrong on several attempts. This <a href="https://stackoverflow.com/questions/45504400/regex-match-pattern-of-alternating-characters">answer</a> directed me down the right street.</p><p>Here is the solution:</p><pre>let e=/^(\S)(?!\1)(\S)(\1\2)*$/; <br>e.test(&quot;abab&quot;); //true <br>e.test(&quot;$#$#&quot;); //true <br>e.test(&quot;#$%&quot;); //false <br>e.test(&quot;$ $ &quot;); //false <br>e.test(&quot;xyxyx&quot;); //false</pre><p>This is where you say, “I’ve had enough!” and throw in the towel.</p><p>But wait for the Aha moment! You are 3 feet away from the gold ore, not the right time to stop digging.</p><p>Let’s first make sense out of results before we arrive at ‘<strong>how?</strong>’ abab matches. $#$# matches, this is no different from abab.</p><p>#$% fails as there is a third character. $ $ fails though they are pairs, because space is excluded in our pattern.</p><p>All is well except, xyxyx fails, because our pattern doesn’t know how to handle that last x. We’ll get there.</p><p>Let’s take a look at the tools added to our belt. It’ll start to make sense soon.</p><h4>One piece at a time</h4><p>You already know most of the pieces. \S is the opposite of \s. \S looks for non white space characters.</p><p>Now comes the plain English version of /^(\S)(?!\1)(\S)(\1\2)*$/.</p><ul><li>Start from the start /^</li><li>Look for a non-white space character (\S)</li><li>Remember it as \1</li><li>Look ahead and see if the first character is not followed by the same character (?!\1). <br>Remember this is a <strong>negative look ahead</strong>.</li><li>If we are good so far, look for another character (\S)</li><li>Remember it as \2</li><li>Then look for <strong>0 or more pairs of first two matches</strong> (\1\2)*</li><li>Look for such pattern until end of the string $/</li></ul><p>Apply that to our test cases. &quot;abab&quot; and &quot;$#$#&quot; match.</p><h4>Tail End</h4><p>After looking at the solution you may think this does not demand a separate section. But the simplicity of it is elegant. Let’s fix that one failing case xyxyx. As we’ve seen, the last trailing x is the problem. We have a solution for xyxy. All we need is a pattern to say “Look for an optional occurrence of first character”.</p><p>As usual, let’s start with the solution.</p><pre>let e=/^(\S)(?!\1)(\S)(\1\2)*\1?$/; e.test(&quot;xyxyx&quot;); //true e.test(&quot;$#$#$&quot;); //true</pre><p>The question mark strikes again. There is no escaping him. It’s better we make him our ally than our enemy. A question mark ? after a character or pattern means 0 or 1 match for the preceding pattern. It is non-greedy in gobbling up characters.</p><p>In our case, \1? means, 0 or 1 match of the first character remembered through first set of brackets.</p><p>Easy. Relax.</p><h4>Review</h4><ul><li>\S <br>Represents all characters excluding white space such as a space and new lines<br>Note that it is capital S</li><li>a* <br>The asterisk or star, looks for 0 or more occurrences of the preceding character. In this case, it is 0 or more a<br>Remember plus (+) which looks for 1 or more? Yeah, these guys are cousins.</li><li>a(?!b) <br>This combination of brackets, question mark and exclamation mark (?!) is called a <strong>look ahead</strong>. <br>This matches a only if it is not followed by b. <br>For example, it matches a in aa, ax, a$ but does not match ab<br>Though it uses bracket, it does not remember the matching character after a.</li><li>\s <br>Small caps s matches a single white space character such as a space or new line.</li><li>a(?=b) <br>This matches a that is followed by b.</li><li>^ab*$ <br>You may think this translates to 0 or more occurrences of ab, but it matches a followed by 0 or more b<br>For example: This matches abbb, aand ab, but does not match abab</li><li>^(ab)*$ <br>This matches 0 or more pairs of ab<br> That means it will match empty string &quot;&quot;, aband abab, but not abb</li><li>a? <br>? matches 0 or 1 occurrence of preceding character or pattern<br> \1? matches 0 or 1 recurrence of first remembered match</li></ul><h3>5. Match an email address</h3><h4>Warning for Production</h4><p>Regular expressions alone may not help validate emails. Some would even argue that regular expressions should not be used as it can never match 100% of the emails.</p><p>Think about all the fancy domain names popping up. Also consider inclusion of symbols within email addresses, such as dot (.) and plus (+).</p><p>You need to validate email twice. Once on the client side to help users avoid misspelled addresses. Start with a semantic input tag type &lt;input type=&#39;email&#39;&gt;. Some of the browsers automatically validate it without any extra scripting on the front end.</p><p>Validate it once again on the server by actually sending a confirmation email.</p><p>Haven’t you seen one such lately? Just try to subscribe to this <a href="https://www.pineboat.in/">pineboat</a>. You’ll get an actual email asking you to confirm that it is yours. That confirmation is a solid proof that your email is valid.</p><p>That was smooth sailing, wasn’t it?</p><h4>RegEx for Email</h4><p>Now that we added the disclaimer, you’d actually want to see a pattern right? No, search for regular expression for an email address. One such result from <a href="http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html">perl module</a> goes for more than a page.</p><p>So, I am not even going to attempt it. Such long regular expressions are generated by computers through pattern builders. Not for mere mortals like us.</p><h3>6. Match a Strong Password</h3><p>If you are a coffee person, this is the right time to get a strong one. Because we are at last section of this post, but the longest one so far.</p><p>It introduces very few new operators and patterns. But it reuses many patterns. As usual, we reserve the shortest optimized one for last.</p><p>The ASCII range is the best part of this post. Because, I learned it while researching for this post.</p><p>Now, the problem. Remember that registration form that took several attempts before you could meet their strong password requirements? Weak, good, strong, and very strong? Yeah, we are going to build that validation.</p><p>The password should:</p><ul><li>have a minimum of 4 characters</li><li>contain lowercase</li><li>contain uppercase</li><li>contain a number</li><li>contain a symbol</li></ul><p>This is a tricky one. Once you start consuming letters, you can’t come back to check if they meet any other condition.<strong> </strong>There in lies our clue.<strong> We can’t look back, but we can look ahead!</strong></p><h4>Length of the string</h4><p>Let’s first test if the string password is 4 characters long. Pretty simple. Use .length on the password string. Done, right? No, who needs a simple solution? Let’s spice it up.</p><pre>//expression with just lookahead<br>//wouldn&#39;t consume any character<br>e1=/^(?=.{4,})$/; <br>e1.test(&quot;abc&quot;) //false<br>e1.test(&quot;abcd&quot;) //false  </pre><pre>//after lookahead, <br>//pattern to consume character is needed.<br>e2=/^(?=.{4,}).*$/; <br>e2.test(&quot;abc&quot;) //false <br>e2.test(&quot;abcd&quot;) //true</pre><ul><li>You may remember (?=) from our previous work on <a href="https://www.pineboat.in/post/regular-expressions-your-ally/#extension-2-no-duplicates">“no duplicates”</a> That’s a look ahead use<br>It does not consume any character</li><li>The dot (.) is an interesting character<br>It means, <strong>any character</strong>.</li><li>{4,} <br>Stands for at least 4 preceding characters with no maximum limit</li><li>\d{4} <br>Would look for exactly 4 numerals</li><li>\w{4,20} <br>Would look for 4 to 20 alpha-numeric characters</li></ul><p>Let’s translate /^(?=.{4,})$/. “Start from the beginning of the string. Look ahead for at least 4 characters. Don’t remember the match. Come back to the beginning and check if the string ends there.”</p><p>Doesn’t sound right. Does it? At least the last bit.</p><p>Which is why we brought in the variation /^(?=.{4,}).*$/. An extra dot and a star. It reads like this, “Start from the beginning. Look ahead for 4 characters. Don’t remember the match. Come back to the beginning. Consume all the characters using .* and see if you reach the end of the string.”</p><p>This makes sense now. Doesn’t it?</p><p>Which is why abc fails and abcd passes the pattern.</p><h4>At least One Number</h4><p>This is going to be easy.</p><pre>e=/^(?=.*\d+).*$/ <br>e.test(&quot;&quot;); //false <br>e.test(&quot;a&quot;); //false <br>e.test(&quot;8&quot;); //true <br>e.test(&quot;a8b&quot;); //true <br>e.test(&quot;ab890&quot;); //true</pre><p>Start from the beginning of the string /^. Look ahead for 0 or more characters ?=.*. Check if 1 or more numbers follow \d+. Once it matches, come back to the beginning (because we were in look ahead). Consume all the characters in the string until end of the string .*$/.</p><h4>At Least One Lowercase Letter</h4><p>This one follows the same patter as above.</p><pre>e=/^(?=.*[a-z]+).*$/; <br>e.test(&quot;&quot;); //false <br>e.test(&quot;A&quot;); //false <br>e.test(&quot;a&quot;); //true</pre><p>Translation? Sure. “Start from the… okay.” Instead of \d+, we have [a-z]+ which is a character set of letters from a to z.</p><h4>At least One Uppercase Letter</h4><p>Let’s not overkill. [A-Z] instead of [a-z] from the previous section will do.</p><h4>At least One Symbol</h4><p>This is going to be challenging. One way to match symbols is to place a list of symbols in a character set. /^(?=.*[-+=_)(\*&amp;\^%\$#@!~”’:;|\}]{[/?.&gt;,&lt;]+).*$/.test(“$”) That’s all the symbols in a character set. Properly escaped where necessary. It’ll take months for me to write it in plain English.</p><p>So to save all of us from eternal pain, here is a simple one:</p><pre>//considers space as symbol <br>let e1; <br>e1=/^(?=.*[^a-zA-Z0-9])[ -~]+$/ <br>e1.test(&quot;_&quot;); //true <br>e1.test(&quot; &quot;); //true  </pre><pre>//does not take space <br>let e2; <br>e2=/^(?=.*[^a-zA-Z0-9])[!-~]+$/ <br>e2.test(&quot; &quot;); //false <br>e2.test(&quot;_&quot;); //true  </pre><pre>//the underscore exception <br>let e3; <br>e3=/^(?=.*[\W])[!-~]+$/ <br>e3.test(&quot;_&quot;); //false</pre><p>Wait, what’s that ^ coming again from the middle of no where? If you have reached this far, this is where you realize that unassuming innocent ^ that marks start of a string is a double agent. Which means, the end is not too far. He has been exposed.</p><p>Within a character set, ^ negates the character set. That is, [^a-z] means, any character other than a to z.</p><p>[^a-zA-Z0-9] then stands for any character other than lower case alphabets, upper case alphabets, and numerals.</p><p>We could have used \W instead of the long character set. But \W stands for all alpha-numeric characters <strong>including underscore _.</strong> As you can see in the third set of examples above, that will not accept underscore as a valid symbol.</p><h4>CharSet Range</h4><p>The curious case of [!-~]. They stand next to each other in the keyboard, but their ASCII values are diagonally opposite.</p><p>Remember a-z? A-Z? 0–9? These are not constants. They are actually based on the ASCII range of their values.</p><p>The <a href="http://www.asciitable.com/">ASCII table</a> has 125 characters. zero (0) to 31 are not relevant to us. Space starts from 32 going all the way up to 126 which is tilda(~). The exclamation mark is 33.</p><p>So [!-~] covers all the symbols, letters and numbers we need. The seed for this idea came from <a href="https://stackoverflow.com/questions/8359566/regex-to-match-symbols">another solution</a> to the symbol problem.</p><h4>Assemble the Troops</h4><p>Bringing it all together, we get this nice looking piece of regular expression /^(?=.{5,})(?=.*[a-z]+)(?=.*\d+)(?=.*[A-Z]+)(?=.*[^\w])[ -~]+$/.</p><p>That’s starting to haunt and intimidate us. Though we’ve been studying them individually.</p><p>This is where the syntax for dynamically building expression object comes in handy. We are going to build each piece separately and assemble them later.</p><pre>//start with prefix <br>let p = &quot;^&quot;; </pre><pre>//look ahead  <br>// min 4 chars <br>p += &quot;(?=.{4,})&quot;; <br>// lower case <br>p += &quot;(?=.*[a-z]+)&quot;; <br>// upper case <br>p += &quot;(?=.*[A-Z]+)&quot;; <br>// numbers <br>p += &quot;(?=.*\\d+)&quot;; <br>// symbols <br>p += &quot;(?=.*[^ a-zA-Z0-9]+)&quot;; <br>//end of lookaheads  </pre><pre>//final consumption <br>p += &quot;[ -~]+&quot;;  <br>//suffix <br>p += &quot;$&quot;; </pre><pre>//Construct RegEx <br>let e = new RegEx(p); <br>// tests <br>e.test(&quot;aB0#&quot;); //true  <br>e.test(&quot;&quot;); //false <br>e.test(&quot;aB0&quot;); //false <br>e.test(&quot;ab0#&quot;); //false <br>e.test(&quot;AB0#&quot;); //false <br>e.test(&quot;aB00&quot;); //false <br>e.test(&quot;aB!!&quot;); //false  </pre><pre>// space is in our control <br>e.test(&quot;aB 0&quot;); //false <br>e.test(&quot;aB 0!&quot;); //true</pre><p>If your eyes are not tired yet, you’d have noticed two strange syntax in the above code.</p><ul><li>One, we didn’t use /^, instead we used just ^. We didn’t use $/ to end the expression either, instead just $.<br>The reason is that the RegEx constructor automatically adds starting and trailing slashes for us.</li><li>Two, to match numbers we used \\d instead of the usual \d. This is because the variable p is just a normal string within double quotes. To insert a backslash, you need to escape the backslash itself. <br>\\d resolves to \d within the RegEx constructor</li></ul><p>Apparently, there should be server side validations for passwords too. Think about SQL injection vulnerabilities if your framework or language doesn’t handle it already.</p><h3>7. Conclusion</h3><p>That brings us to the end of the story. But this is the beginning of a journey.</p><p>We just scratched the pattern matching portion of RegEx with test method. exec method builds on this foundation to return matched sub-strings based on pattern.</p><p>String object has methods such as match, search, replace, and split that widely uses regular expressions.</p><p>Hope this sets you off to explore those capabilities further with a solid understanding on composing patterns for RegEx.</p><h3>8. Call To Action</h3><p>No, after all this difficulty we’ve been through, I am not going to ask you to subscribe.</p><p>Just make good software.</p><p>If any code blocks presented here do not work, leave a comment on this <a href="https://github.com/pineboat/pineboat.github.io/issues/3">github issue</a> I created specially for this post.</p><p>Hope it was useful! Share it if others would benefit.</p><p>You’ve been wonderful. Appreciate your time. This content is far long by recent standards. Thanks for reading.</p><p>Originally published at <a href="https://www.pineboat.in/post/regular-expressions-your-ally/">www.pineboat.in</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617b55cf787" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/regular-expressions-demystified-regex-isnt-as-hard-as-it-looks-617b55cf787">Regular Expressions Demystified: RegEx isn’t as hard as it looks</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Shatter Impostor Syndrome and Boost Confidence]]></title>
            <link>https://codeburst.io/how-to-shatter-impostor-syndrome-and-boost-confidence-2f866519c30c?source=rss-783f35ad67e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f866519c30c</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vijayabharathi Balasubramanian]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 18:01:28 GMT</pubDate>
            <atom:updated>2017-11-14T18:01:28.798Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone faces their impostor self once in a while. Especially when you know how much you don’t know. One way to fight against the syndrome is to recognize what you do know. To realize you are becoming better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qlwcqaawBzrl9iwMaTwWQ.jpeg" /><figcaption>cc photo <a href="https://unsplash.com/@sergiunista">https://unsplash.com/@sergiunista</a></figcaption></figure><p>Have you ever tried refactoring your own code that was a year or two old? I had to. And the results were not just better code base. The refactoring also showed me what have I learned.</p><p>This is the story of refactoring I have done. I’m hoping it’ll inspire you to try the same.</p><p>Jump right on to the story.</p><p>The code was more than 2 years old. It was a weird project for many reasons. For starters, it was a static site hosted on SharePoint. Mainly because we didn’t have an option of a separate server or using public domain. We had to keep the information secure within the firewall. I thought SharePoint was not meant to serve static sites, but it worked. It was using an XML file as database. It had a single HTML with small section of CSS in the head. But the JavaScript is where most of the logic was.</p><p>It was operational for a while. I was helping another team with a copy of the installation. Before sharing it, I wanted to make sure all looks good so that the other team wouldn’t have trouble using it. I opened it up on Atom, my beloved text editor.</p><p>The view on the text editor was nothing short of <strong>shocking</strong>. I was like ‘really?’ How on earth this piece of code continues to run? I could see my past self looking at me with painful wrinkles of embarrassment on the face.</p><p>Then it dawned on me, I must have grown up. I have picked up tips and tricks on JavaScript. I learned and adopted best practices. I have gained more knowledge on the language. I have seen better design patters.</p><p>Here are some of them that I listed down while I was refactoring. You’ll also see <strong>What was the learning?</strong> and <strong>Do it yourself(DIY)</strong> sections within each refactoring option.</p><h3>1. Generous Use of Globals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*RpzD0-zZAzB3Nx6J.jpg" /><figcaption>Photo credit: <a href="https://stocksnap.io/author/46357">https://stocksnap.io/author/46357</a></figcaption></figure><p>Globals are the best way to hold data / manage state in JavaScript, when I didn’t know better ways. It’s quite natural for people to go for a global variables.</p><p>Look around your old code and find any global variables that you are using. I certainly could find many. Drop them all. May be leave a singleton.</p><p>What has changed? Someone must have shown me why globals are bad. By now I know many of the pitfalls of using global variables. It’s time for a list.</p><h3>What was the Learning?</h3><ul><li>When the code base is large, it is difficult understand use of globals within a function.</li><li>They open up rooms for defects that are hard to debug.</li><li>It is quite easy for you to break others’ code by using the same variable name</li><li>Worse, someone else could as easily overwrite your variable name</li><li>This one was new while I was, wait for it, researching(1) for this blog post. Global namespaces are hard to search. Hence, they lead to performance penalty when compared to locals.</li></ul><p>(1)You’d argue that there is no evidence of any sort of research in this post. So, let’s just say when I googled “globals are bad” and call it a day.</p><p>Usually, programming books show global variables first when the topic of ‘scope’ comes in. I would suggest all books on any programming language show global scope at the end, as a warning side note.</p><h3>DIY:</h3><ul><li>Read more on ‘why globals are bad’ on <a href="http://wiki.c2.com/?GlobalVariablesAreBad">this page</a>.</li><li>Try refactoring your code to eliminate globals.</li><li>Impure functions are one of the places where state from outer scope is mutated. Try limiting use of impure functions.</li></ul><h3>2. Duplicate code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*SjefWpb6L49QTakR.jpg" /><figcaption><a href="https://unsplash.com/search/photos/duplicate?photo=fPxOowbR6ls">Photo by Matthew Henry on Unsplash</a></figcaption></figure><p>You may see similar looking code all over the place. Just different variable names and flags, but common functionality. Think about extracting them to a function.</p><p><strong>Before:</strong></p><pre>//code to clear filters  <br>var priceFilter=document.getElementByID(&quot;priceFilter&quot;); priceFilter.value=&quot;None&quot;; <br>var brandFilter=document.getElementByID(&quot;brandFilter&quot;); brandFilter.value=&quot;None&quot;; <br>var sizeFilter=document.getElementByID(&quot;sizeFilter&quot;); sizeFilter.value=&quot;None&quot;; <br>//and a few more</pre><p><strong>After:</strong></p><pre>const clearFilter=(id)=&gt;{ <br> let filter=document.getElementByID(id);<br> filter.value=&quot;None&quot;; <br>} <br>clearFilter(&quot;authorFilter&quot;); <br>clearFilter(&quot;brandFilter&quot;); <br>clearFilter(&quot;sizeFilter&quot;); <br>//and so on</pre><h4>What was the learning ?</h4><ul><li>Don’t Repeat Yourself (DRY)</li><li>Duplicate code needs fix/change at multiple places.</li><li>When you make same changes to many places, it is quite easy to introduce a bug. [Have your key pad ever stuck and ctrl+v didn’t work. Have you ever missed one of the instances when you use multi-select/concurrent cursor?]</li><li>Takes up to much space than necessary and increases cognitive load</li></ul><h4>DIY</h4><ul><li>Identify and extract duplicate code into a reusable function</li><li>Delete all the duplicate code into function calls.</li><li>Feel the bliss of deleting code, hold that thought and savor the moment</li><li>Rewrite your tests to fit the new design (or write new tests)</li></ul><h3>3. Complex and Lengthy Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*P5umM_08zO_Os2dp.jpg" /><figcaption><a href="https://unsplash.com/search/photos/juggle?modal=%7B%22type%22%3A%22credit-badge%22%2C%22userId%22%3A%22jFDKfLlXxkE%22%7D">Photo from Unsplash</a></figcaption></figure><p>The previous section is relevant here. Duplicate code is one of the reasons some functions are large. But that may not be the only reason.</p><p>It’s natural for people coming linear programming languages such as C to write lengthier functions. That’s my opinion by the way.</p><p>The code I had written 2 years ago had functions as large as 50 lines of code. A set of instructions in sequence. Many loops, accessing data, updating DOM and triggering events. You name it, the function had it. The function was jack of all trades.</p><p>My brain needed a larger RAM to hold all those things the function was supposed to do.</p><h4>What was the Learning?</h4><blockquote><em>“There are only two hard problems in Computer Science: cache invalidation and naming things.” — Phil Karlton</em></blockquote><ul><li>It is difficult to fully understand purpose of a function if it is larger than your comfort level.</li><li>I’m on the side of small functions. Based on my experience, I see smaller functions make more readable code.</li><li>Some would argue jumping between smaller functions would hinder readability. That’s why a good name for function is necessary. Which is also why Phil was spot on.</li><li>When you have a large function, it is easy to name it. Think about some of the things it’s doing and rephrase it. For example, fetchDataAndProcessDataAndUpdateDOM. But when you break functions down to smaller ones, you need be good at naming them. For example, fetchData, sortData and updateUserTable</li></ul><h4>DIY:</h4><ul><li>Try to go through <a href="https://sites.google.com/site/unclebobconsultingllc/">Clean Code</a> by “Robert C. Martin”.</li><li>Pick a lengthy function, one with more than 50 lines of code.</li><li>Cut it short or split it into many smaller functions.</li><li>Try to maintain or increase the overall readability.</li><li>Remember, we can be jack of all trades. But our functions need to be master of one. That’s, just one job for a function to do well.</li><li>Much like deleting excess code, this is also an enjoyable experience. Savor the moment.</li></ul><h3>4. Hidden Nested Loops</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*O7CUf4pemL1UfEXd.jpg" /></figure><p>Photo from <a href="https://www.gratisography.com/">https://www.gratisography.com/</a></p><p>Like I said in the last section, long functions tend to have many responsibilities. Some of those responsibilities achieved through nested loops. I could see loops nested two level deep on my code. It was not very concerning at first sight. It is easy to spot deeply nested loops and uproot them. One such example here.</p><pre>for(let i=0;i&lt;array.length;i++){<br> for(let j=i;j&lt;array.length;j++){<br>  for(let k=j;k&lt;array.length;k++){<br>   doSomethingOverandOver(); <br>  } <br> } <br>}</pre><p>But there are times when the nesting is not explicit and in a single place. Take the one below for example,</p><pre>for(let i=0;i&lt;array.length;i++){<br> doSomething(array,i); <br>} </pre><pre>const doSomething=(array,i)=&gt;{<br> for(let j=i;j&lt;array.length;j++){<br>  over(array,j); <br> } <br>} <br>const over=(array,j)=&gt;{<br> for(let k=j;k&lt;array.length;k++){<br>  andOver();<br> } <br>}</pre><p>This is the same nested loop that is three level deep. The loops are nicely tucked away within separate functions — which doesn’t make it any better. Let’s say you have spread these functions away from each other. It may be difficult to realize you’ve run into nested loops that are several levels deep.</p><h4>What was the learning?</h4><ul><li>Nested loops are usually signs of <strong>brute force</strong> implementation.</li><li>A <a href="https://en.wikipedia.org/wiki/Bubble_sort">bubble sort</a> with no optimization will run for n2times.</li><li>Nested loops that are three levels deep may quickly escalate into several runs of same code.</li><li>When you deal with large scale data, nested loops are not the way to go. You’ll have hard time understanding when the loop will end.</li><li>Avoid looping through data that comes from a DB. Try to use the power of SQL and your database engine.</li></ul><h4>DIY</h4><ul><li>Try writing <a href="https://en.wikipedia.org/wiki/Bubble_sort">bubble sort</a> if you haven’t done so recently.</li><li>Two simple for loops will be sufficient to get the results. But it’s O(n2).</li><li>Run it against a fully sorted array. The best case scenario. It will run into O(n2).</li><li>Introduce a flag to break the loop if there was no swap, indicating array is already sorted, then it’s just O(n).</li><li>Now write a merge sort that uses recursion. Compare the difference in time for sorting 100k elements. Bubble sort took 2 mins, merge sort does it within 2 seconds.</li><li>If you must use nested loops, look for improvements to reduce iterations. That’s knowing when to stop. Then work towards stopping it early.</li><li>Consider if recursion or regular expression can be an option if you are working with strings.</li><li>There are few use cases for nested loops. Such as traversing a three dimensional array. Know when to use nested loops.</li></ul><h3>5. Synchronization Issues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*KHNyusbBsgq8JRhO.jpg" /><figcaption><a href="https://unsplash.com/search/photos/dancers?photo=upk3M2NEP_s">Photo by Joy Real on Unsplash</a></figcaption></figure><p>Let’s say you design and program a racing bot. What if, on the glorious day of racing, your bot starts to run before the race begins?</p><p>This is something I ran into when I was refactoring. May not be prevalent as other issues, but it does hit me occasionally. My JavaScript was working in full speed before DOM was loaded.</p><p>It took a long time to figure out. Certain changes had no effect on the application. Weird errors saying “element does not exist” while they are right in front of my eyes.</p><p>The problem was ‘DOMContentLoaded’ event. Rings any bell? Since I have been using frameworks and boilerplates for a while, I totally lost track of basics.</p><p>But the good news is, you eventually figure it out. If you start running JavaScript before DOM is ready, you are bound to run into such issues. We need to listen for ‘DOMContentLoaded’ event before we start doing anything with JavaScript. At least when your objective involves using elements from the DOM.</p><h4>What was the learning?</h4><p>Always respect this piece of code:</p><pre>document.addEventListener(&quot;DOMContentLoaded&quot;,function(e){<br>// This is where most of your code <br>// interacting with DOM should live <br>});</pre><h4>DIY:</h4><p>Nope, this is not something you may find in your project. There is no DIY here. Just hold this thought of “waiting for DOM” for a while. It’s worth it. It’ll come back to you when necessary.</p><h3>6. No tests whatsoever</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*r0BTPsu3MurZqruP.jpg" /><figcaption><a href="https://www.pexels.com/photo/biotechnology-bright-chemical-chemistry-207585/">Photo from pexels</a></figcaption></figure><p>The app I chose to refactor had no tests. I had to check if the app is still functional. It was quite manual. It was painful. It wasn’t so painful in the last project.</p><p>So, what’s changed? I was using TDD in the last project. I had some tests running in the background as part of my dev workflow.</p><p>Now that there are no tests, the refactoring was even more challenging.</p><h4>What was the learning?</h4><ul><li>You’ll enjoy refactoring if there are tests.</li><li>You’ll enjoy it more if it automatically runs when you make changes.</li><li>It’s rewarding if you have a code coverage tools like <a href="https://github.com/gotwarlost/istanbul">istanbul</a> and <a href="https://github.com/nickmerwin/node-coveralls">coveralls</a>. Steady increase in code coverage can be a motivating factor.</li><li>TDD is hard. It takes patience and practice to get into a habit of writing at least some tests.</li><li>You should almost always write tests first. That ‘almost’ is for you to retain the right to choose if you want to write tests first.</li></ul><p><strong>Confession</strong>: I rush to write the actual functionality first. Seeing the results on the browser is the normal impulsive behavior, at least for me. To write tests first is counter intuitive.</p><h4>DIY</h4><ul><li>As you refactor your project, ensure you also write tests.</li><li>If you already have tests, think about how you’d refactor your tests.</li><li>If you have none, all the more reason to write tests from scratch.</li><li>Find a way to run tests automatically when you change your code. For example, guard runs tests for rails and npm-watch for node.</li></ul><p>JavaScript DevTools are quite advanced. It is possible to get test results like the one below (source set up can be found on <a href="https://github.com/vijayabharathib/fcc-project-react-recipies">git repository</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*c7P-mx1I5h9yDwNgYNA5CQ.png" /><figcaption>Terminal showing test results breakdown by source files, with uncovered lines of code</figcaption></figure><h3>7. No sight of library/framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*xDlEoxgNE0Hcepus.jpg" /><figcaption><a href="https://unsplash.com/collections/1025135/construction?photo=8Gg2Ne_uTcM">Photo by 贝莉儿 NG on Unsplash</a></figcaption></figure><p>You might have hand crafted your application from scratch. That’s the best start you can give for any application. But you might also see your app as a composition of components. You might ask yourself “why did I hand craft everything in the first place?” There is so much imperative programming going on here.</p><p>Whether to handcraft everything or to use a library is a key decision. It has to be an informed one. Not based on ignorance. For example, the SPA I was refactoring appeared to have many components. I would naturally choose React now if I have to reboot the project.</p><p>But I didn’t. Not because I didn’t want to add 50kb+ for the library. Not because I didn’t like those libraries. Not because I didn’t understand the implications of the license. <strong>All these may be good reasons not to use a library. I didn’t use any, because I didn’t know how to use them 2 years ago.</strong></p><p>Not using existing tools / libraries is Ok as long as it is an informed decision. Getting to know tools of trade wouldn’t hurt. Especially in JavaScript ecosystem. It’s up to us to see that as <a href="https://medium.com/javascript-scene/why-im-thankful-for-js-fatigue-i-know-you-re-sick-of-those-words-but-this-is-different-296fae0c888f">treasure trove</a> instead of pandora’s box.</p><h4>What was the learning?</h4><ul><li>Have seen the power of declarative programming.</li><li>Experienced the productivity bliss of using tools like Rails and React.</li><li>The peace of mind comes along with state management libraries such as Redux.</li><li>You’ve got new pair of eyes that see your app as a collection of cohesive components</li></ul><h4>DIY</h4><ul><li>Try to bring in a tiny library to help you.</li><li>I haven’t used Preact but it fits the word Tiny and seems to have an API identical to React.</li><li>If you are feeling adventurous, try to write your own view management library. After all, those libraries are also JavaScript.</li></ul><p>May be in two years, I’ll write about why this post is not so good. I’ll list down what have I learned about ‘writing well’ and how to make this post better. I’d reassure myself that I am learning and growing.</p><p>I urge you to try this. Try refactoring your old project, may be a year or two old. <strong>Be conscious of changes you make</strong>. That’ll help you recognize what have you learned in the meantime. <strong>Write a post and remember to let me know!</strong></p><p>Thank you, hope it was worth reading.</p><p><em>Originally published at </em><a href="https://www.pineboat.in/post/shatter-impostor-syndrome-boost-confidence/"><em>www.pineboat.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f866519c30c" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/how-to-shatter-impostor-syndrome-and-boost-confidence-2f866519c30c">How to Shatter Impostor Syndrome and Boost Confidence</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Travis CI and GitHub for your web development workflow’s heavy lifting]]></title>
            <link>https://medium.com/free-code-camp/how-to-wire-travis-ci-to-do-the-heavy-lifting-in-your-workflow-72693c855696?source=rss-783f35ad67e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/72693c855696</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Vijayabharathi Balasubramanian]]></dc:creator>
            <pubDate>Wed, 27 Sep 2017 19:11:12 GMT</pubDate>
            <atom:updated>2017-09-28T11:24:13.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuG9pmpZOl03m_EM9eAQCw.jpeg" /><figcaption>It all becomes easier with continuous integration via Travis CI</figcaption></figure><p>It’s common to hack together apps on <a href="https://codepen.io/">CodePen</a> when you are starting out. But there will be a time when you will want to publish your own web apps to the whole world. They could be side projects or projects for a client. A good development workflow will make a world of difference at this point.</p><p>We are going to set up a development workflow using the following tools:</p><ul><li>create-react-app</li><li>npm scripts</li><li>Travis-CI</li></ul><p>We’ll wire Travis CI and GitHub together. At the end, we’ll to get a nice and shiny badge Like the one below.</p><p>But more than the look, the badge signifies a function. It’s a sign of Travis CI testing, building and publishing our commits to GitHub. Travis CI publishes only if the tests pass.</p><p>Get ready to place these badges on your repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*cI5UNTkT3JdED0K9BS95Jw.jpeg" /></figure><p>I have organized the whole workflow in stages. One sitting should do for each stage. That’s within about 50 minutes.</p><h3>Stage 1 : Run create-react-app locally</h3><h4>Get your git repository ready</h4><p>The first thing is to create a new repository on <a href="https://github.com/">GitHub</a>. If you don&#39;t already have an account, now is the time to register for one. Public repositories are free. When you create a new repository, GitHub lets you to create files for .gitignore, license and README.md.</p><p>If you are starting with Git for the first time, you can read this free <a href="https://git-scm.com/book/en/v2">book</a> online. There is also a <a href="https://help.github.com/">help</a> section on GitHub.</p><p>Here is how our new repository will look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*Vs79AoKEhQOk7k6n.png" /></figure><p>All right, let’s get that on our terminal. Do you see that bright green button on the above image showing <strong>Clone or download</strong>. That’ll give us the URL to the repository. On your terminal, run this command:</p><pre>git clone git@github.com:pineboat/react-continuous-deployment.git</pre><p>That command will download the contents of the repository into a new directory. It names the directory the same as the repository. In our case, the directory name will be <strong>react-continuous-deployment</strong>.</p><p>If you want to make sure a link to original repository is ready, use the command:</p><p>git remote -v</p><p>Now that we are set to push our changes to GitHub, let’s get React up and running.</p><h4>Up and running with create-react-app</h4><p>Starting a fresh react project from scratch might take longer than you’d expect. Especially when you are not using any predefined scaffolds. There are several solutions out there that we can use to get started. I chose official <a href="https://github.com/facebookincubator/create-react-app">Create React App</a> because I’ve tried it first and stuck with it. When you don’t have to micromanage your configurations, it gives you a clean start so you can hit the ground coding.</p><p>As the repository README.md file shows, you only have to install it once globally. Then you can use it to scaffold as many project as you like.</p><p>To install it type:</p><pre>npm install -g create-react-app</pre><p>Once that’s installed, you can run it from any directory to create a new app. Let’s give it our repository’s name:</p><pre>create-react-app react-continuous-deployment</pre><p>That will <strong>not</strong> create a new folder as we already have the folder created by Git. Instead it will start installing necessary node_modules and scaffold scripts within the existing folder.</p><p>If you want a fresh application, you can use:</p><p>create-react-app fancy-app-name</p><p>Then you’ll need to create a Git repository and connect it to GitHub. That is not too difficult. You can use this <a href="https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/">help</a> page from GitHub.</p><p>Has that installation finished yet? It shouldn’t take more than 5 minutes. It took me about 15 minutes. Don’t let that scare you. Unless you’re like me, and you are using a 150 mb/s 4G data card that gives you about 512kbps of download speed on its best day.</p><p>The nice thing is, the installation moved our old README.md file aside. The terminal shows this sweet message:</p><pre>You had a `README.md` file, we renamed it to `README.old.md`</pre><p>The terminal should also have shown you the enormous list of packages in a tree structure. This can look scary. But most of these are dependencies between packages. They are there to help you develop your app. The final product will only have necessary JavaScript files such as react.js and react-dom.js. We’ll go there in a while.</p><p>For now, let’s wake up our application. Once the installation is over, <br>create-react-app will give us a list of commands which will be handy.</p><p>Here is a catalog for reference:</p><ul><li>npm start<br>Starts the development server</li><li>npm run build<br>Bundles the app into static files for production</li><li>npm test <br>Starts the test runner</li><li>npm run eject <br>Removes the single dependency build from your project See <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-eject">here</a></li><li>npm run deploy <br>To deploy the build to gh-pages branch</li></ul><p>npm start and npm test built-in node commands are recognized by default. You need to run other scripts such as build, eject and deploy using an extra run flag: <br>npm run script_name</p><p>We’d add a few more in the process as we go. Now it’s time to load our site on a browser. Get inside the application directory and run:</p><pre>npm start</pre><p>Like magic, a new browser tab opens and you see a nice React wheel turning. The view must be challenging you to build the next best app the internet is about to witness.</p><p>So this is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*ZFgBeEisdZkQQW4W.gif" /></figure><p>That is a pretty neat GIF (Graphics Interchange Format) isn’t it? Except for my cursor coming in. I captured this GIF with a tool called <a href="https://github.com/phw/peek">Peek.</a> Check it out when you need it.</p><p>Well done! I hope that didn’t take more than 45 minutes. If you are running into issues, pay attention to the error messages and try to fix them.</p><p>When you are close to the point of frustration, head over to <a href="https://stackoverflow.com/">Stack Overflow</a> for help. Or leave your questions in the comments below.</p><p>Before we hack into any of the files, let’s get the code committed and pushed to GitHub repository. These commands will do:</p><pre>git status <br>git add --all git commit -m &quot;Initial Scaffold, this is your own message&quot;</pre><ul><li>git status <br>Shows a list of changes we’ve made</li><li>git add <br>Adds those changes to a temporary place called stage before we push it to the cloud</li></ul><p>If you run git status again, it will report that</p><pre>Your branch is ahead of &#39;origin/master&#39; by 1 commit.<br> (use &quot;git push&quot; to publish your local commits)<br> nothing to commit, working directory clean</pre><p>That’s right, we have made and committed changes locally. There are no uncommitted changes. But we are ahead of the cloud version of our repository. It’s time to publish them to a safe house, which is GitHub.</p><p>All you need to run is:<br>git push origin master</p><p>You’ll get a nice report showing a hash like fb74259..045ec7a, which is a reference for our commit. Of course, your hash will be different.</p><p>Check your GitHub repository. Are you surprised to see a long README.md?Remember that create-react-app has replaced our tiny README.md with its own. It’s huge and helpful, so we’ll keep it for now before we write our own.</p><h3>Stage 2: Porting site over to GitHub Pages</h3><h4>Build the static site</h4><p>Let’s take a look at the final build.</p><p>You only have to run:</p><p>npm run build</p><p>Make sure that you are within the application directory for all the commands. We’ll get this nice text showing us what has happened and what else can we do:</p><pre>$ npm run build <br>&gt; react-continuous-deployment@0.1.0 build /home/weebee/Projects/blog_projects/react-continuous-deployment<br>&gt; react-scripts build<br><br>Creating an optimized production build...<br>Compiled successfully.<br><br>File sizes after gzip:<br><br>  48.12 KB  build/static/js/main.9fdf0e48.js<br>  288 B     build/static/css/main.cacbacc7.css<br><br>The project was built assuming it is hosted at the server root.<br>To override this, specify the homepage in your package.json.<br>For example, add this to build it for GitHub Pages:<br><br>  &quot;homepage&quot; : &quot;http://myname.github.io/myapp&quot;,<br><br>The build folder is ready to be deployed.<br>You may serve it with a static server:<br><br>  npm install -g serve<br>  serve -s build</pre><p>The npm run build command does what we asked for. It builds our app, and optimizes and <a href="https://en.wikipedia.org/wiki/Minification_(programming)">minifies</a> our assets. And it places everything in a folder called <strong>build</strong>.</p><p>Towards the bottom, the suggestion is to install the serve npm package to start a local server. Most of the time, if you are on Linux, you’ll already have Python installed. It’s quite easy to start a local server if you have Python.</p><p>Step into the <strong>build</strong> directory and start a server, see following commands:</p><pre>cd build<br>python -m SimpleHTTPServer</pre><p>Python command by default starts the server on port 8000. So, http://localhost:8000 will serve the production version of the website. It uses assets from your local <strong>build</strong> directory that we just created.</p><p>If that looks good, we are going to send it over to GitHub pages.</p><h4>Primer on GitHub pages</h4><p>GitHub pages are hosting solution provided by GitHub for repositories. There are few places where you can host your site, all within a repository:</p><ul><li>You can use <strong>master</strong> branch (the default one) to host your website<br>If you have an index.html, it’ll show up. Otherwise, your README.md will show up.</li><li>You can also use <strong>docs</strong> folder in a master branch to host your site<br>The use case would be when you have a software or library developed on GitHub. You might want to host the documentation along in the same repository.</li><li>You can use the <strong>gh-pages </strong>branch to host your site</li></ul><p>There is an exception. Your repository name should not be &lt;your_user_name&gt;.github.io or &lt;orgname&gt;.github.io</p><p>These are special names and they limit you to using the <strong>master</strong> branch.</p><p>Once you host your website, you can load it in the following URLs. It depends on whether your repository is under your account or an organization account:</p><pre>https://&lt;your_user_name&gt;.github.io/&lt;your_repository_name&gt;/ </pre><pre>https://&lt;organization_name&gt;.github.io/&lt;your_repository_name&gt;/</pre><p>With that understanding, let’s equip our repository to go live.</p><h4>Publish to GitHub pages</h4><p>The new README.md given to us by the create-react-app has a separate section on GitHub pages. There are few things we need to do.</p><h4><strong>Check additions to </strong><strong>package.json file</strong></h4><pre>&quot;homepage&quot;: &quot;http://&lt;user_name&gt;.github.io/&lt;your_repository_name&quot;, &quot;scripts&quot;: {<br> &quot;predeploy&quot;: &quot;npm run build&quot;,<br> &quot;deploy&quot;: &quot;gh-pages -d build&quot;<br>}</pre><p><strong>Note</strong>: Usually, the last section or entry in a JSON doesn’t need a comma, all others should have one.</p><h4>Install gh-pages package</h4><p>This one is easy. Just run the following command while you are inside the project directory:</p><p>npm install --save gh-pages</p><p>The --save flag will add gh-pages as a dependency to package.json. This is to ensure anyone else who clones your project can also get it when they run npm install.</p><p>Here is a snapshot of git diff command showing all we have added since package.json was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*j_RARNCE-aljvNX3.png" /></figure><h4>Deploy to gh-pages branch</h4><p>Let’s run npm run deploy. It will automatically run predeploy, to generate the production build we’ve seen earlier. It will then deploy the build to our repository under a new branch named <strong>gh-pages</strong>.</p><p>Check if you get a Published status as the last statement. If so, you’ve successfully deployed the production build to GitHub. Here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*rgIQn_1bPY6JPvay.png" /></figure><h4>Select gh-pages branch to be published</h4><p>Let’s head over to the GitHub repository and publish our site. Open up the repository and go to settings tab at the top. It looks like this image below, wait a minute! GitHub has automatically published the <strong>gh-pages</strong> branch. There is nothing more to do. It also shows the URL in which we can access the site.</p><p>The sub-title above should actually say <strong>Do nothing</strong>. It’s all done and ready for us to consume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*m-QERXCUFDKKj-7E.png" /></figure><p><strong>Note</strong>: The URL shown for my repository may be misleading you. That’s because I have created this repository under an organization named PineBoat, which is my blog. GitHub places this under my custom domain which isn’t something I expected when I tried this. Yours will differ.</p><p>So far, so good. If you have you had prior experience in Git and Node packages, you should have had no trouble reaching this far. In fact, the default README.md was enough to help me this far. If you have had no experience, I hope you enjoyed the journey.</p><p>But we are aspiring for a continuous deployment workflow. We are starting to navigate some uncharted waters. One would argue nothing is uncharted in the Internet. I would agree, yet create my own map.</p><h3>Stage 3: Continuous Deployment</h3><p>This is where we bring in bots to do most of the deployment that we did in stage 2.</p><h4>Wire in Travis CI for automatic build</h4><p>Let’s get Travis CI to do the deploying for us. There is no harm in building and deploying your site on your own. As we have seen, all it takes is a few more minutes of our valuable time.</p><p>However, when you run into larger projects of scale it’s better to let trusted bots do some of the jobs. Travis CI is one such service.</p><p>We can take advantage of Travis CI to build and deploy whenever we commit our code to the repository.</p><h4>Sign Up to Travis CI</h4><p>It would be annoying if I start with “if you have a GitHub account” now. I’m sure you have one by now and we can use that to sign up to Travis CI.</p><h4>Connect to GitHub Repository</h4><p>Watch out for the permissions. If your repository does not get listed, click on the <strong>sync</strong> button and refresh the page. I had to grant permission to the “PineBoat” organization before I could see the repository.</p><p>Travis CI shows you the steps. Flick that switch against your repository to connect it.</p><p>Click on the repository name to open it up. It’ll show a build status as <strong>unknown</strong> and a larger note saying <strong>No builds for this repository</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*oKNcZTaP9AvJ_q4l.png" /></figure><p>Not for long. Let’s change it.</p><h4>Add .travis.yml to the repository</h4><p>Here is the .travis.yml that needs to be added. Have a look, and stay with me while I clear up some of the questions you might have.</p><pre>language: node_js</pre><pre>node_js:<br> - &quot;node&quot;</pre><pre>after_success:<br> - git config --global user.name &quot;vijayabharathi&quot;<br> - git config --global user.email &quot;<a href="https://pineboat.in/cdn-cgi/l/email-protection">[email protected]</a>&quot;<br> - git remote rm origin<br> - git remote add origin <a href="https://vijayabharathib:$%7BGH_TOKEN%7D@github.com/pineboat/react-continuous-deployment.git">https://vijayabharathib:${GH_TOKEN}@github.com/pineboat/react-continuous-deployment.git</a><br> - npm run deploy</pre><p>Be careful with the git remote add origin, it’s one long line. The YAML syntax is slightly different from JSON. <a href="http://docs.ansible.com/ansible/latest/YAMLSyntax.html">This page</a> might help. Now it’s time to break it down. You may have figured out most of those messages.</p><p><strong>Here it is in plain English:</strong></p><ul><li>This is a node project. Get the latest node version</li><li>Since Travis runs npm test by default, we are asking it to do things after the test is successful</li><li>Add your Git username and email</li><li>Then add git remote origin for the repository<br>Use your user name and the GH_TOKEN generated as credentials</li><li>Finally, run the npm run deploy command<br>If you recall, this will run npm run predeploy before running npm run deploy</li></ul><h4>Commit and watch Travis CI build</h4><p>Keep your Travis CI repository page open. On your terminal add changes, commit and push them to GitHub.</p><p>In case you need a reminder, here is the list of commands:</p><pre>git add --all <br>git commit -m &quot;add .travis.yml configuration for automatic build&quot; git push origin master</pre><p>If you switch to the Travis CI page, you’ll see the page coming alive once git push is over or within a few seconds. The build starts automatically and you’ll know if it is successful.</p><p>Here is my Travis CI page showing nice green status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*-VRvaW2OdhmkEhQe.png" /></figure><p>The log shown is no less than 2500 lines. I’m glad Travis-CI shows only what we need to see.</p><p>A clear indication of steps followed as shown below in the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*OUqyevFCYksP2KBC.png" /></figure><h3>Spot check, did we really succeed?</h3><p>This is where automated tests that run on production may come in handy.</p><p>But that’s for another day. The <a href="http://www.seleniumhq.org/projects/webdriver/">Selenium WebDriver</a> can wait until we finish this wiring. Let’s manually check if Travis CI really did publish to GitHub pages.</p><h4>Another trial, this time with changes to code</h4><p>Last time, we couldn’t see any difference in our application after deployment. That’s because we didn’t make any. So there was no way to tell if the build was successful. You can load gh-pages branch and look into the commits, but I digress.</p><p>Now, let’s make some small changes. It’s time to take the React wheel back in time.</p><p>We’ll only make two changes.</p><p>Within src/App.css file, there is a section for animation named @keyframes App-logo-spin. Change that 360deg to -360deg. This is to spin the wheel counter clockwise.</p><p>Load the src/logo.svg file and change the fill color from #61DAFB to #DA61FB. If your server is running via npm start, you can already see a purple wheel running counter clockwise. If not, add the changes to the stash, commit and push them to the repository. Watch if the build is successful in Travis-CI and then head over to your Github page.</p><p>Load your_user_name.github.io/repository_name. You should see the purple wheel instead of the blue one.</p><p>Alas, I don’t see that purple wheel. I still see the default blue one.</p><h4>Fix the missing GH_TOKEN</h4><p>Though Travis CI reported that all is well, it’s not. If you open up the <strong>gh-pages</strong> branch, you’ll see the original commit we made from local terminal. No other commits. That means, the after_success commands were not so successful.</p><p>If you expand the npm run deploy section in the Travis build log, you’ll see some <strong>authentication errors. </strong>That’s because we haven&#39;t given Travis CI permission to write to our repository.</p><p>You can create a new token from <a href="https://github.com/settings/tokens">Personal access tokens</a> page from GitHub.com. Remember to give access to public repository alone. Just one tickmark against public_repo will do. <strong>Don’t miss this.</strong> Once you generate a token, copy it. GitHub rightly warns that you will not be able to see it again.</p><p>Head over to Travis CI, click on <strong>More Options</strong> for your repository and choose <strong>settings</strong>. It’ll show several sections, but <strong>Environment Variables</strong> is the one to look for.</p><p>Name the token as GH_TOKEN and past the token under value field. Click add. <strong>Do not</strong> switch on the <strong>Display value in logs</strong> as it might be visible to people if you send the logs out. The token is equivalent to your password.</p><p>That’s it, now Travis-CI can write to our repository.</p><p>Go back to the <strong>Current</strong> tab of the repository and click on <strong>Restart build</strong>. Once the build is over, you can check the logs and check the <strong>gh-pages</strong> branch on GitHub. You should see a new commit.</p><p>Congrats! That’s our first automated deployment. How about the github.io website itself? No amount of refresh would bring the much needed purple wheel. Don’t loose hope yet.</p><h4>Ask service worker to take a break</h4><p>Still the wheel is bleeding blue. But <strong>gh-pages</strong> branch in the repository shows a second commit. Let’s compare the index.html on the repository and on the web page source. They are pointing at different CSS and JavaScript files. The hash suffix is our clue.</p><p>This seems to be the result of energetic JavaScript service worker. It has cached the page for offline use. But this conclusion needs more research. In the mean time, let’s just stop the service worker and clear the storage.</p><p>If you are on Chrome, <strong>Developer Tools</strong> can be accessed from menu or by pressing F12. The <strong>Application</strong> tab on Chrome DevTools has <strong>Clear Storage </strong>section. Check all entries and finally click on that <strong>Clear site data</strong>.</p><p>Refresh and boom! Here is our reverse wheel in bright purple. Now it’s time for celebration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*uJjmXE5EkbdSisEm.gif" /></figure><p><strong>Note</strong>: there must be a better way to do this storage clean up automatically. Would be a pain if we have to stop and clean service worker and storage each time to get the changes online. That’s a topic for more research.</p><h3>Stage 4: Badge of honor from Travis CI</h3><p>There is one final task in front of us. That is to get a shiny Travis CI build status badge over to our repository’s README.md file.</p><p>Open up Travis CI and click on the <strong>build:passing</strong> badge. It’ll show a dialog with options to port the image. Leave the branch as <strong>master</strong>. Select <strong>Markdown </strong>instead of <strong>Image URL</strong>. Copy the text you are given.</p><p>Paste it into the README.old.md, which was left to us by create-react-app previously. Write your own content.</p><p>You can delete the default README.md from the repository and rename the README.old.md to README.md.</p><p>Add the changes to Git staging, commit and push to the cloud. Now the repository should show the batch you always wanted. Here is the URL shown for our pet project.</p><pre><a href="https://travis-ci.org/pineboat/react-continuous-deployment.svg?branch=master">https://travis-ci.org/pineboat/react-continuous-deployment.svg?branch=master</a></pre><p>You can add that url to the README.md at the top. Here is the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*cI5UNTkT3JdED0K9BS95Jw.jpeg" /><figcaption>We are done here! Time to celebrate.</figcaption></figure><p>I’d like to leave you with a question. If you are working in a large teams using similar workflow, what are the challenges you face and how would you solve them? Write a comment and let me know.</p><p>Thank you so much for reading. I hope you found it useful.</p><p>This was originally published at <a href="https://www.pineboat.in/post/travis-to-deploy-react-to-github-pages/">pineboat.in</a>.</p><p>Clapping shows how much you appreciated this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72693c855696" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-wire-travis-ci-to-do-the-heavy-lifting-in-your-workflow-72693c855696">How to use Travis CI and GitHub for your web development workflow’s heavy lifting</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>