<?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 Andrew Nease on Medium]]></title>
        <description><![CDATA[Stories by Andrew Nease on Medium]]></description>
        <link>https://medium.com/@andrew.nease.code?source=rss-325df8d9c91f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EoVeid-qZnYlLaxcPnbzwg.jpeg</url>
            <title>Stories by Andrew Nease on Medium</title>
            <link>https://medium.com/@andrew.nease.code?source=rss-325df8d9c91f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:32:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrew.nease.code/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[using a recursive function in javascript to simulate exponential behavior while exploring value…]]></title>
            <link>https://medium.com/@andrew.nease.code/using-a-recursive-function-in-javascript-to-simulate-exponential-behavior-while-exploring-value-7c8a450eec19?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c8a450eec19</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[unique-combinations]]></category>
            <category><![CDATA[exponent]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Mon, 05 Mar 2018 01:06:57 GMT</pubDate>
            <atom:updated>2018-04-30T15:07:55.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>using a recursive function in javascript to simulate exponential behavior while exploring value combinations in PINs, binary code, and the number of phones you would need to guarantee an HQ quiz win.</h3><p>The answer is 531,441.</p><p>That’s how many phones it would take to guarantee a win at HQ Quiz.</p><p>In 2018,<strong><em> HQ Quiz</em></strong> is a popular multiple-choice quiz game. Players are asked trivia questions and given three options for an answer. If correct, the player advances to the next question. If incorrect, the player is eliminated. The game ends after 12 questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*d1Uo_my4EzqVOadmAygS6Q.png" /></figure><p>In order to guarantee a win, you would need 531,441 players. Each player would have a unique series of answers:</p><pre>Player 1: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]<br>Player 2: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]<br>Player 3: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3]<br>Player 4: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1]<br>Player 5: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2]<br>Player 6: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3]<br>Player 7: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1]<br>…<br>Player 531437: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2]<br>Player 531438: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3]<br>Player 531439: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1]<br>Player 531440: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2]<br>Player 531441: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]</pre><p>During each round, a 1/3 of the remaining players would need to answer each of the options. During the first question:</p><ul><li>177,147 players would select option 1.</li><li>177,147 players would select option 2.</li><li>177,147 players would select option 3. <em>CORRECT!</em></li></ul><p>354,294 players would be eliminated, leaving 177,147 to answer question number 2. During the second question:</p><ul><li>59,049 players would select option 1.</li><li>59,049 players would select option 2.</li><li>59,049 players would select option 3. <em>CORRECT!</em></li></ul><p>118,098 players would be eliminated, leaving 59,049 to answer question number 3, and so on, until only one player remains: the only player in our set who correctly answered all 12 questions:</p><pre>Player ? : [1, 3, 2, 1, 1, 3, 3, 2, 1, 2, 1, 3]</pre><p>—</p><p>But this isn’t the direction a problem like this one is usually solved. It’s easy to have arrived at a solution and think backwards from it. To figure it out from the bottom, I had to start building something and see what I could learn.</p><p>What if the quiz had just one question? We would need 3 players:</p><pre>Players = [<br>  [1], // player 1’s choices<br>  [2], // player 2’s choices<br>  [3]  // player 3’s choices<br>]</pre><p>What if the quiz had 2 questions?</p><pre>Players = [<br>  [1,1], // player 1’s choices<br>  [1,2],<br>  [1,3],</pre><pre>  [2,1],<br>  [2,2],<br>  [2,3],</pre><pre>  [3,1],<br>  [3,2],<br>  [3,3]  // player 9’s choices <br>]</pre><p>We would need 9 players. And what if the quiz had 3 questions? We would need… 27 players.</p><pre>Players = [<br>  [1,1,1], // player 1’s choices<br>  [1,1,2],<br>  [1,1,3],</pre><pre>  [1,2,1],<br>  [1,2,2],<br>  [1,2,3],</pre><pre>  [1,3,1],<br>  [1,3,2],<br>  [1,3,3],</pre><pre>  [2,1,1],<br>  [2,1,2],<br>  [2,1,3],</pre><pre>  ...</pre><pre>  [3,3,1],<br>  [3,3,2],<br>  [3,3,3]   // player 27’s choices<br>]</pre><p>This was enough data to start a chart.</p><pre>questions | unique players</pre><pre>1           3<br>2           9<br>3           27</pre><p>So what is the relationship here?<br>3 = 3.<br>3 x 3 = 9.<br>3 x 3 x 3 = 27.<br>It looks like an exponential relationship.</p><pre>questions | unique players | ?</pre><pre>1           3                3^1<br>2           9                3^2<br>3           27               3^3</pre><p>In other words, the number of unique players needed is equal to the number of options (3) raised to the power of the number of questions (12).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXA65wSxm0lau9eugInKZg.jpeg" /></figure><p>In order to build this out as a javascript simulation, I started with a basic game with 2 questions:</p><pre>let phones = [<br>  [1,1],<br>  [1,2],<br>  [1,3],<br>  [2,1],<br>  [2,2],<br>  [2,3],<br>  [3,1],<br>  [3,2],<br>  [3,3]  <br>];</pre><pre>let phonesInPlay = phones;</pre><pre>let answers = [1,1];</pre><pre>// eliminate losers<br>answers.forEach((answer, index) =&gt; {</pre><pre>  // for each answer, remove the phones that don&#39;t match<br>  phonesInPlay = phonesInPlay.filter((phoneChoices) =&gt; {<br>  return phoneChoices[index] === answer;<br>  });</pre><pre>});</pre><pre>// Who won?<br>console.log(phonesInPlay); // [[1,1]]</pre><p>To begin removing the hard coding, we can randomize the answers array (<em>thanks </em><strong><em>Stack Overflow</em></strong>) and add some configuration variables:</p><pre>// configuration variables<br>let numOfOptions = 3;<br>let numOfQuestions = 2;</pre><pre>// generate a random array of answers<br>let answers = Array.from({length: numOfQuestions}, () =&gt; Math.floor(Math.random() * numOfOptions + 1));</pre><pre>console.log(answers); // [3,2]</pre><p>But how are we going to generate the choices of the phones?</p><pre>????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????</pre><p>I needed a function to return a phones array:</p><pre>function createPhonesArray(numOfOptions, numOfQuestions) {</pre><pre>  // how is this going to work?<br>  return [<br>    [1,1],<br>    [1,2],<br>    [1,3],<br>    [2,1],<br>    [2,2],<br>    [2,3],<br>    [3,1],<br>    [3,2],<br>    [3,3]  <br>  ]<br>}</pre><p>I briefly explored some <em>for</em> loops, but that didn’t work. Going back to my manual calculations, I noticed that when I added a question, I was transforming the phones array by going through each element and “adding one of each option to the end of itself and deleting itself”. In other words:</p><pre>[1,1] is replaced by [1,1,1], [1,1,2], [1,1,3]<br>[1,2] is replaced by [1,2,1], [1,2,2], [1,2,3]<br>...<br>[1,1,1] is replaced by [1,1,1,1], [1,1,1,2], [1,1,1,3]<br>[1,1,2] is replaced by [1,1,2,1], [1,1,2,2], [1,1,2,3]</pre><pre>etc.</pre><p>So maybe I could have a function do that for me?</p><pre>function addEachOptionToItselfAndDeleteItself(arr, numOfOptions) {</pre><pre>  let whatToReturn = [];</pre><pre>  // for each element in the received array...<br>  arr.forEach((el) =&gt; {</pre><pre>    // add a copy of itself with each option attached<br>    for (let i = 1; i &lt;= numOfOptions; i++) {<br>      whatToReturn.push([...el, i]);<br>    }<br>  });</pre><pre>  return whatToReturn;<br>};</pre><pre>console.log(addEachOptionToItselfAndDeleteItself([[1], [2], [3]], 3));</pre><pre>// [[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]]</pre><p>This is looking good. It’s starting to feel like how I was figuring out the problem manually. Sure enough, if I chained the functions together, it was returning the right answers:</p><pre>let question1Phones = [[1], [2], [3]];</pre><pre>let question2Phones = addEachOptionToItselfAndDeleteItself(question1Phones, 3);</pre><pre>console.log(question2Phones.length); // 9</pre><pre>let question3Phones = addEachOptionToItselfAndDeleteItself(question2Phones, 3);</pre><pre>console.log(question3Phones.length); // 27</pre><pre>let question4Phones = addEachOptionToItselfAndDeleteItself(question3Phones, 3);</pre><pre>console.log(question4Phones.length); // 81</pre><p>And if we bypass the variable assignments, the above can be written:</p><pre>let getNewArr = addEachOptionToItselfAndDeleteItself;</pre><pre>let question4Phones = getNewArr(getNewArr(getNewArr(question1Phones , 3), 3), 3);</pre><pre>console.log(question4Phones.length); // 81</pre><p>Now it’s starting to look a lot like <strong>recursion</strong>: the notorious function that calls a new instance of itself. A function within a function within a function within a function.</p><p>The number of nested function calls will be related to the number of questions. So we can start passing the number of questions into our function as well.</p><p>In addition, from having been exposed to the recursion pattern, I remember that I want to start thinking of an exit scenario (<em>the base case</em>), as well as the initial call:</p><pre>function getNewArr(arr, numOfOptions, numOfQuestions) {</pre><pre>if (numOfQuestions === 0) {<br>  return arr;<br>}</pre><pre>let whatToReturn = [];</pre><pre>  arr.forEach((el) =&gt; {<br>    for (let i=1; i&lt;=numOfOptions; i++) {<br>      whatToReturn.push([...el, i]);<br>    }<br>  });</pre><pre>return whatToReturn;<br>};</pre><pre>getNewArr([[]], 3, 1); // [[1], [2], [3]]<br>getNewArr([[]], 3, 0); // [[]]</pre><p>And finally, we take the full leap into recursion. Instead of returning whatToReturn, we return a call to the same function, passing whatToReturn along as a new parameter:</p><pre>return getNewArr(whatToReturn, numOfOptions, numOfQuestions - 1);</pre><p><em>numOfQuestions</em> will act as a reverse counter, decrementing with each call until it equals 0, at which point no more calls are made and each of the functions we created can be resolved. Here it is a little cleaner:</p><pre>function getNewArr(arr, numOfOptions, numOfQuestions) {<br>if (numOfQuestions === 0) {<br>  return arr;<br>}<br>let whatToReturn = [];<br>  arr.forEach((el) =&gt; {<br>    for (let i=1; i&lt;=numOfOptions; i++) {<br>      whatToReturn.push([...el, i]);<br>    }<br>  });</pre><pre>return getNewArr(whatToReturn, numOfOptions, numOfQuestions - 1);<br>};</pre><pre>console.log(getNewArr([[]], 3, 12).length); // 531441</pre><p>If you haven’t walked through a recursive call stack before, here’s what it looks like.</p><pre>function getNewArr(arr, numOfOptions, numOfQuestions)</pre><pre>Instance 1:<br>getNewArr([[]], 3, 3);</pre><pre>Does numOfQuestions === 0 ?  No.<br>this whatToReturn will equal [[1], [2], [3]]<br>and get passed to the second call in the return statement:</pre><pre>Instance 2:<br>getNewArr([[1], [2], [3]], 3, 3-1)</pre><pre>Does numOfQuestions === 0 ? No.<br>this whatToReturn will equal [[1,1], [1,2], [1,3] ... [3,3]]<br>and get passed to the third call in the return statement:</pre><pre>Instance 3:<br>getNewArr([[1,1], [1,2], [1,3] ... [3,3]], 3, 2-1)</pre><pre>Does numOfQuestions === 0 ? No.<br>this whatToReturn will equal [[1,1,1], [1,1,2], ... [3,3,3]]<br>and get passed to the fourth call in the return statement:</pre><pre>Instance 4:<br>getNewArr([[1,1,1], [1,1,2], ... [3,3,3]], 3 1-1)</pre><pre>Does numOfQuestions === 0 ? Yes.<br>Instance 4 is resolved.  Return the array to resolve Instance 3.<br>Instance 3 is resolved.  Return the array to resolve Instance 2.<br>Instance 2 is resolved.  Return the array to resolve Instance 1.<br>Instance 1 is resolved.  You&#39;ve got your answer.</pre><p>Here’s the entire simulation, which can be copy and pasted to a javascript emulator, such as <a href="http://repl.it/languages/javascript">repl</a>:</p><pre>// recursive function to return one of each choice to end of each array item<br>function getNewArr(arr, options, questions) {<br>  if (questions === 0) {<br>    return arr;<br>  }</pre><pre>let newValues = [];</pre><pre>arr.forEach((el) =&gt; {<br>    for (let i=1; i &lt;= options; i++) {<br>      newValues.push([...el, i]);<br>    }<br>  });</pre><pre>return getNewArr(newValues, options, questions - 1);<br>}</pre><pre>// configuration variables<br>let numOfChoices = 3;<br>let numOfQuestions = 12;</pre><pre>let phones = getNewArr([[]], numOfChoices, numOfQuestions);<br>let phonesStillInPlay = phones;</pre><pre>// generate a random array of answers<br>let answers = Array.from({length: numOfQuestions}, () =&gt; Math.floor(Math.random() * numOfChoices + 1));</pre><pre>// eliminate losers<br>answers.forEach((answer, index) =&gt; {<br>  phonesStillInPlay = phonesStillInPlay.filter((phoneChoices) =&gt; {<br>  return phoneChoices[index] === answer;<br>  });<br>});</pre><pre>console.log(&#39;Answers:&#39;);<br>console.log(answers);<br>console.log(`Congratulations:`);<br>console.log(phonesStillInPlay[0]);<br>console.log(&#39;losers: &#39;, phones.length - phonesStillInPlay.length);</pre><pre>// Answers:<br>// [ 1, 1, 2, 2, 1, 3, 1, 1, 3, 3, 3, 1 ]<br>// Congratulations:<br>// [ 1, 1, 2, 2, 1, 3, 1, 1, 3, 3, 3, 1 ]<br>// losers: 531440</pre><p>And what about Sunday nights when HQ Quiz has 15 questions?</p><pre>3¹⁵ = 14,348,907 phones</pre><p>What if the game had 4 choices?</p><pre>4¹² = 16,777,216 phones</pre><p>What about the fact that the first two questions in HQ Quiz are usually so easy that they are difficult to get wrong?</p><pre>3¹⁰ = 59,049 phones</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iw51iQ6nZoaWQJbUTeRbKA.jpeg" /><figcaption>number of options ^ number of inputs = number of combinations</figcaption></figure><p>The equation can be used to find any number of unique combinations given a fixed set of options and a number of inputs.</p><p>A standard PIN number? 10 options. 4 inputs.</p><pre>10⁴ = 10,000 pin numbers</pre><p>A 6 digit pin? 10 options. 6 inputs.</p><pre>10⁶ = 1,000,000 pin numbers</pre><p>A typical combination lock? 40 options. 3 inputs.</p><pre>40³ = 64,000 combinations</pre><p>Lexical phonology aside, the number of possible 4-letter English words? 26 options. 4 inputs.</p><pre>26⁴ = 456,976 words</pre><p>An 8-letter password? 26 options. 8 inputs.</p><pre>26⁸ = 208,827,064,576 passwords, including &quot;password&quot;</pre><p>Hexadecimal color codes? 16 options. 6 inputs.</p><pre>16⁶ = 16,777,216 colors</pre><p>And speaking of code, what about binary code? A byte has 8 units of zero or one. 2 options. 8 inputs.</p><pre>2⁸ = 256 values</pre><p>16-bit numbers? 2 options. 16 inputs.</p><pre>2¹⁶ = 65,536 values</pre><p>In summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QG1F4Nojud06TIDdE94Rw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhPmMkc1S79meEkCnF3coQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c8a450eec19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[use a package.json script and a configuration array to select/choose which mocha tests to run]]></title>
            <link>https://medium.com/@andrew.nease.code/use-package-json-and-a-configuration-array-to-select-which-mocha-tests-to-run-80766c478c47?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/80766c478c47</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[npm-scripts]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Tue, 30 Jan 2018 23:10:37 GMT</pubDate>
            <atom:updated>2018-04-30T15:09:54.821Z</atom:updated>
            <content:encoded><![CDATA[<p>So you want a faster-paced solution for selecting which tests to include and exclude when running mocha? This should save you plenty of clicks, clacks, and keystrokes when wanting to filter a large number of cluttering unit tests.</p><p>Outside of your chai and mochas, spies, stubs, and mocks, here’s what you’ll need:</p><pre>npm install --save-dev npm-run-all<br>npm install --save-dev filehound</pre><pre>touch test/bin/rename-selected-spec-files.js<br>touch test/tests-to-run.js</pre><ul><li><strong>npm-run-all </strong>is a simple package to run multiple npm scripts.</li><li><strong>filehound</strong> is a helpful package to recursively search a directory structure for [paths/to/filenames.and.extensions].</li></ul><p><em>rename-selected-spec-files.js</em> will be our script file.</p><p><em>tests-to-run.js</em> will be our configuration array.</p><p>First, get <em>rename-selected-spec-files.js</em> to run by including these values in the your package.json file:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npm-run-all select-tests test-run&quot;,<br>  &quot;select-tests&quot;: &quot;node test/bin/rename-selected-spec-files.js&quot;,<br>  &quot;test-run&quot;: &quot;mocha --require babel-core/register \&quot;app/**/*.spec.js\&quot; || true&quot;,<br>},</pre><p>Replace the “test-run” value above with your custom mocha command. (This example is written for a mocha test that needs a mock DOM for React testing and a mock store for Redux testing.) The only important specification to consider is that all the mocha tests should be named <em>name-of-test.spec.js</em>, unless you want to change it.</p><p>Now, npm run select-tests will run the forthcoming script file. npm run test-runwill run the mocha tests. npm run test will run both scripts: first the former, and later the latter.</p><p>Throw a console.log(‘console.logged’) in the <em>rename-selected-spec-files.js</em> to test out the execution.</p><p>The <em>tests-to-run.js</em> should look like this:</p><pre>module.exports = [</pre><pre>  &#39;app/test1&#39;,<br>  &#39;app/test2&#39;,<br>  // &#39;app/components/specs/test3&#39;</pre><pre>  ];</pre><p>This file will hold the paths to your spec files as strings in an array. Notice the absence of file extensions, as well as the path that is commented out. In this scenario, only the first two spec files will be included when mocha is executed.</p><p><em>rename-selected-spec-files.js </em>will rename your spec file’s extensions according to their inclusion in the imported <em>tests-to-run.js</em> configuration file. In other words, after executing <em>rename-selected-spec-files.js, </em>your files will be renamed:</p><pre>app/test1.spec.js<br>app/test2.spec.js<br>app/components/specs/test3.spec.disabled.js</pre><p>And doing so will include or exclude spec files when running mocha.</p><p>And finally, the <em>rename-selected-spec-files.js</em> file:</p><pre>var fs = require(&#39;fs&#39;);<br>var FileHound = require(&#39;filehound&#39;);<br>var testsToRun = require(&#39;../tests-to-run.js&#39;);</pre><pre>const trim = (fn) =&gt; fn.substring(0, fn.indexOf(&#39;.&#39;));</pre><pre>const jsFiles = FileHound.create()<br>  .paths([&#39;./test&#39;, &#39;./app&#39;])<br>  .ext(&#39;js&#39;)<br>  .find();</pre><pre>jsFiles.then((pathsArr) =&gt; {<br>  let specFiles = pathsArr.filter((filePath) =&gt; filePath.includes(&quot;.spec.js&quot;) || filePath.includes(&quot;.spec.disabled.js&quot;));</pre><pre>  let pathsToEnable = specFiles.filter((fileName) =&gt; testsToRun.includes(trim(fileName)) &amp;&amp; fileName.includes(&quot;disabled&quot;));</pre><pre>  let pathsToDisable = specFiles.filter((fileName) =&gt; !testsToRun.includes(trim(fileName)) &amp;&amp; !fileName.includes(&quot;disabled&quot;));</pre><pre>  pathsToEnable.forEach((oldName) =&gt; {<br>    let newName = `${trim(oldName)}.spec.js`;</pre><pre>    fs.rename(oldName, newName, (err) =&gt; {<br>      if (err) {console.log(err); return;}<br>    });<br>  });</pre><pre>  pathsToDisable.forEach((oldName) =&gt; {<br>    let newName = `${trim(oldName)}.spec.disabled.js`;</pre><pre>    fs.rename(oldName, newName, (err) =&gt; {<br>      if (err) {console.log(err); return;}<br>    });<br>  });</pre><pre>});</pre><p>Below is a slightly more detailed version to copy, paste, and explore:</p><pre>/*<br> This script finds all .spec.js files and renames them .spec.disabled.js according to their presence in tests-to-run.js<br> */</pre><pre>var fs = require(&#39;fs&#39;);<br>var FileHound = require(&#39;filehound&#39;);<br>var testsToRun = require(&#39;../tests-to-run.js&#39;);</pre><pre>// a function to remove the extensions from a path and filename<br>const trim = (fileNameWithExt) =&gt; fileNameWithExt.substring(0, fileNameWithExt.indexOf(&#39;.&#39;));</pre><pre>// find all .js files<br>const jsFilePathsPromise = FileHound.create()<br>  .paths([&#39;./test&#39;, &#39;./app&#39;])<br>  .ext(&#39;js&#39;)<br>  .find();</pre><pre>// use the resulting array of paths<br>jsFilePathsPromise.then((jsFilePathsArr) =&gt; {<br>  let specFileNames = jsFilePathsArr.filter((filePath) =&gt; filePath.includes(&quot;.spec.js&quot;) || filePath.includes(&quot;.spec.disabled.js&quot;));</pre><pre>console.log(&#39;*********&#39;);<br>console.log(&quot;testToInclude&quot;, testsToRun.length);<br>console.log(testsToRun);<br>console.log(&quot;spec file names&quot;, specFileNames.length);<br>console.log(specFileNames);</pre><pre>let pathsToEnable = specFileNames.filter((fileName) =&gt; testsToRun.includes(trim(fileName)) &amp;&amp; fileName.includes(&quot;disabled&quot;));<br>console.log(&quot;files to enable&quot;, pathsToEnable.length);<br>console.log(pathsToEnable);</pre><pre>let pathsToDisable = specFileNames.filter((fileName) =&gt; !testsToRun.includes(trim(fileName)) &amp;&amp; !fileName.includes(&quot;disabled&quot;));<br>console.log(&quot;files to disable&quot;, pathsToDisable.length);<br>console.log(pathsToDisable);</pre><pre>  pathsToEnable.forEach((oldFileName) =&gt; {<br>    let newFileName = `${trim(oldFileName)}.spec.js`;</pre><pre>    fs.rename(oldFileName, newFileName, (err) =&gt; {<br>      if (err) {console.log(err); return;}<br>      console.log(`Renamed ${newFileName}`)<br>    });<br>  });</pre><pre>  pathsToDisable.forEach((oldFileName) =&gt; {<br>    let newFileName = `${trim(oldFileName)}.spec.disabled.js`;<br>    fs.rename(oldFileName, newFileName, (err) =&gt; {<br>      if (err) {console.log(err); return;}<br>      console.log(`Renamed ${newFileName}`)<br>    });<br>  });</pre><pre>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80766c478c47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[set up a self-booting node.js server on a raspberry pi 3 using pm2, nginx, dataplicity …]]></title>
            <link>https://medium.com/@andrew.nease.code/set-up-a-self-booting-node-js-eb56ebd05549?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb56ebd05549</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Thu, 20 Jul 2017 20:20:25 GMT</pubDate>
            <atom:updated>2018-04-30T15:09:13.805Z</atom:updated>
            <content:encoded><![CDATA[<h3>set up a self-booting node.js server on a raspberry pi 3 using pm2, nginx, dataplicity, and your mac</h3><p>Here in the summer of 2017:</p><p>Among many ways to accomplish this set up, here’s one of them.</p><p>Prerequisite skills:</p><ul><li>basic BASH shell (cd / mkdir / touch / sudo nano / exit)</li><li>running a local server with node.js, such as <a href="https://github.com/andigan/minimal_node_app">this one</a></li></ul><p>Required materials:</p><ul><li>a <a href="https://www.raspberrypi.org/products/raspberry-pi-3-model-b/">Raspberry Pi 3 Model B</a></li><li>an <a href="https://www.google.com/search?q=sd+card&amp;oq=SD+card&amp;aqs=chrome.0.0j69i59j0l4.2582j0j4&amp;sourceid=chrome&amp;ie=UTF-8#q=8gb+micro+sd+card">8GB micro SD card</a></li><li>an <a href="https://www.google.com/search?q=sd+card+reader&amp;oq=sd+card+reader&amp;aqs=chrome.0.0l6.4302j0j4&amp;sourceid=chrome&amp;ie=UTF-8">SD card reader</a>, or an <a href="https://www.raspberrypi.org/documentation/installation/noobs.md">SD card with NOOBS pre-installed</a></li><li>USB Mouse and keyboard (for about ten minutes)</li><li>HDMI cable and screen (perhaps your tv)</li></ul><h3>Get SSH terminal access to your Raspberry Pi</h3><ol><li>Follow <a href="http://Download and image Raspbian directly">this guide</a> to get Raspian onto your Pi. I would recommend “Download and image Raspian directly”. Briefly:</li></ol><ul><li>Use the <a href="https://www.sdcard.org/downloads/formatter_4/index.html">SD Formatter 4.0</a> to format the SD drive (overwrite format).</li><li>Download the <a href="https://www.raspberrypi.org/downloads/">Raspian image</a></li><li>Copy the image to the SD card using <a href="http://www.etcher.io/">etcher.io</a>.</li><li>Put the micro SD chip into the Pi. Plug a mouse, keyboard, HDMI cable, and power into the Pi.</li></ul><p>2. When the Pi’s GUI appears on your television screen or monitor, connect to your wireless network. Open the terminal by clicking the terminal icon at the top of the screen. Type hostname -I and remember your Pi’s local IP address. Type sudo raspi-config and use the menu system to enable SSH access.</p><p>3. On your mac, type ssh pi@xxx.xxx.x.xxx replacing the x’s with your Pi’s local IP address. The password will be raspberry and you’ll be prompted to change the password.</p><p>Assuming you are able to connect to your Pi via SSH on your mac, you’ll no longer need the mouse or keyboard. You may need to install nano at this stage: sudo apt-get install nano .</p><h3>Install Node.js and your server on the Pi</h3><ol><li>Connect to your Pi via SSH and type sudo apt update , and then sudo apt full-upgrade .</li><li>Install Node Version Manager by copying the curl line from <a href="https://github.com/creationix/nvm">https://github.com/creationix/nvm</a> into the Pi terminal.</li><li>Install Node.js by typing nvm install 8.0.0 .</li><li>You can copy files to your pi using terminal commands, or use <a href="https://cyberduck.io/?l=en">CyberDuck</a> for drag and drop. To use CyberDuck, download it, and:</li></ol><pre>Open Cyberduck and click on File — Open Connection.<br>Choose SFTP from the dropdown box, then fill out the fields as follows:<br>Server: your Pi&#39;s local IP<br>Port: 22<br>Username: the username of your Pi, typically Pi<br>Password: the password of your Pi<br>Uncheck the box for Anonymous Login.<br>Hit Connect</pre><p>5. Copy your node project file onto your Pi. I played around with a few locations and ultimately put my app folder in an app directory at the root level.</p><p>6. Navigate to your app directory and start up your server. If you’re mac is connected to the same wireless network, you should now be able to access your server in your browser at http://xxx.xxx.x.xx:8080 using your Pi’s local IP address and the port specified in your node app.</p><h3>Make your server load when the Pi reboots</h3><p>I struggled with services and the <em>rc.local</em> file for quite awhile before finding a quick solution using an npm module called pm2:</p><ol><li>When connected to your Pi via SSH, type npm install -g pm2 to do a global install of the pm2 module.</li><li>To run a server using pm2, go to your app directory and type pm2 start filename.js . If you need to see if it’s running, type pm2 ls . If you need to stop it, type pm2 delete 0 or whichever thread number you want to delete.</li><li>To discover and implement the appropriate boot strategy for pm2, type pm2 startup . In this case, pm2 will create a the file <em>/etc/systemd/system/pm2-pi.service</em> which will include the following line: ExecStart=/home/pi/.nvm/versions/node/v8.0.0/lib/node_modules/pm2/bin/pm2 resurrect . In other words, when the Pi boots, it will execute pm2 resurrect, which will load whatever pm2 threads you have saved.</li><li>In order to save the state of pm2 that you want to resurrect, run your server using pm2 start filename.js and then type pm2 save .</li></ol><p>For more details and commands for pm2, visit <a href="http://pm2.keymetrics.io/docs/usage/startup/">http://pm2.keymetrics.io/docs/usage/startup/</a></p><h3>Connect your server to the outside world</h3><p>Again, there are many methods, some involving port-forwarding, to allow the world to connect to your raspberry pi. Since I don’t currently care about appearances, I used a service called Dataplicity.</p><ol><li>Set up a currently free account at <a href="https://www.dataplicity.com/">Dataplicity</a>. Follow the directions to link your Pi to the site by copying a line of code to your Pi.</li><li>Click <em>Activate Wormhole</em> to receive an https link to your Pi’s port 80.</li><li>To set up port 80 on your Pi, install nginx by typing sudo apt-get install nginx .</li><li>Edit the config file by typing sudo nano /etc/nginx/sites-available/default .</li><li>Delete everything in the file and, using your Pi’s local IP address and node’s port, replace it with:</li></ol><pre>server {<br>    listen 80;</pre><pre>server_name whatever;</pre><pre>location / {<br>        proxy_pass <a href="http://192.168.1.112:8000/">http://xxx.xxx.x.xxx:8080</a>;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>    }<br>}</pre><p>6. To confirm that nginx is working, type sudo netstat -an | grep LISTEN |grep :80 .</p><p>7. If you mess up and need to restart nginx, type sudo service nginx restart .</p><p>Now, assuming pm2, nginx, and your Dataplicity account were all set up properly, you should be able to connect to the node.js server on your Pi via the url provided by Dataplicity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb56ebd05549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[javascript objects, linguistic relativity, and general semantics]]></title>
            <link>https://medium.com/@andrew.nease.code/javascript-objects-linguistic-relativity-and-general-semantics-50561038f3e7?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/50561038f3e7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[linguistic-relativity]]></category>
            <category><![CDATA[general-semantic]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[objects]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Wed, 03 May 2017 18:32:37 GMT</pubDate>
            <atom:updated>2018-04-30T15:11:12.038Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>There is a knife moving here… an intellectual scalpel so swift and so sharp you sometimes don’t see it moving. You get the illusion that all those parts are just there and are being named as they exist. But they can be named quite differently and organized quite differently depending on how the knife moves.</em></blockquote><blockquote><em>It is important to see this knife for what it is and not to be fooled into thinking that motorcycles or anything else are the way they are just because the knife happened to cut it up that way. It is important to concentrate on the knife itself.</em></blockquote><blockquote><strong><em>Robert Pirsig</em></strong><em> — Zen and the Art of Motorcycle Maintenance</em></blockquote><blockquote><em>Whatever you might say the object “is”, well it is not.</em></blockquote><blockquote><strong><em>Alfred Korzybski</em></strong></blockquote><h3>General Semantics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*9_tmFBtFXuwRo7s7.jpg" /></figure><p>In 1933, Alfred Korzybski published <strong><em>Science and Sanity</em></strong>, a hefty book that established an elaborate foundation for a field of thinking called <em>general semantics</em>. <strong>General semantics</strong> concerns itself with language and abstraction, along with a noble goal of providing sanity to the world at large.</p><p>Perhaps Alfred’s most succinct and influential advice was <strong>“The map is not the territory.”</strong> This was how he started a conversation about how the words we use are not the things to which those words refer. Our words are abstracted from our experience of objects, and our objects are abstracted from a deeper reality.</p><p>Alfred created a visual tool, which he called a <em>Structural Differential</em>, to help him communicate his ideas. In these pictures, the circles represent individualized objects abstracted from innumerable reality events above; the strings represent characteristics that are attended to; and the rectangles represent words, inferences, and words about words further along the chain of abstraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z_Hcq-95h8VyTJKM.png" /></figure><blockquote><em>If we take something, anything… and enquire what it represents… we find that the ‘scientific object’ represents an ‘event’, a mad dance of ‘electrons’, which is different every instant, which never repeats itself, which is known to consist of extremely complex dynamic processes of a very fine structure, acted upon by, and reacting upon, the rest of the universe, inextricably connected with everything else and depending on everything else. If we enquire how many characteristics we should ascribe to such an event, the only possible answer is that we should ascribe an infinite number of characteristics, as it represents a process which never stops in one form or another; neither, to the best of our knowledge, does it repeat itself.<br>…<br>The free hanging strings indicate the most important characteristics left out, neglected, or forgotten in the abstracting.<br>…<br>The label stands for the name which we assigned to the object…. We can also consider the level of the first label as a descriptive level or statement. The label, the importance of which lies in its meaning to us, represents a still higher abstraction from the event, and usually, labels, also, a semantic reaction… The number of characteristics we ascribe by definition to the label is still smaller than the number of characteristics the object has. To the label ‘pencil’, we would ascribe, perhaps, its length, thickness, shape, color, hardness, etc. But we would mostly disregard the accidental characteristics, such as a scratch on its surface, or the kind of glue by which two wooden parts of the objective ‘pencil’ are held together…. We see that the object is not the event but an abstraction from it, and that the label is not the object nor the event, but a still further abstraction.</em></blockquote><blockquote><strong><em>Alfred Korzybski</em></strong><em> — pp. 386–411</em></blockquote><p>In javascript and other languages, we define objects or hashes:</p><pre>myPet = {name: ‘Caterina’, color: ‘ashen’}</pre><p>and classes or prototypes:</p><pre>class Pet {<br>  constructor(name, color) {<br>    this.name = name;<br>    this.color = color;<br>  }<br>}</pre><pre>class Cat extends Pet {<br>  constructor(name, color) {<br>    super(name, color)<br>    this.type = ‘cat’;<br>  }</pre><pre>  meow() {<br>    console.log(`${this.color} ${this.type} ${this.name} meows`);<br>  }<br>}</pre><pre>var myPet = new Cat(‘Caterina’, ‘ashen’);</pre><pre>myPet.meow(); // ashen cat Caterina meows</pre><p>The properties we choose are like the strings of abstraction in Alfred’s structural differential. Which characteristics do we deem essential to an Object? More importantly, which strings are <em>left out, neglected, or forgotten</em>?</p><p>In addition to making decisions about properties, we also make decisions about data types and validations. For example, when we scroll through Terms of Service documents (which might take <a href="https://www.theatlantic.com/technology/archive/2012/03/reading-the-privacy-policies-you-encounter-in-a-year-would-take-76-work-days/253851/">25 days</a> to read fully), we’re greeted by an incontestable Boolean decision: Agree = true || false.</p><p>According to the 2010 United States Census, a Person has a fairly distinct race property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*95ZLotU-cqPNb2HG.png" /></figure><p>And a majority of websites still define us as male or female, so much so that it’s big news when Facebook offered 50+ custom genders to choose from in 2014:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JRfEbVUbgrmYraZH.png" /></figure><p>Clicking 0 or 1 to agree to a 10-minute legal document is problematic. As is grouping all Germans, Irish, English, Polish, French, and others into a top-of-the-list white majority. And defining some gender identities as Custom will covertly continue to reinforce the <em>otherness</em> of individuals who don’t identify with the expected standard validations of Male || Female.</p><p>These digital maps don’t match the analog territory.</p><blockquote><em>Simplification is usually taken to mean a mathematical reduction to common denominators. But another form of simplification is more idiosyncratic: the reduction to the already known, the repression of irregularities…</em></blockquote><blockquote><em>This is the difference between simplifying cognition and a more habitual, comfortable cognition… Comfortable cognition, then, does not mean easy cognition so much as it means “situated” cognition.</em></blockquote><blockquote><strong><em>Schleifer &amp; Davis and Mergler</em></strong><em> — Culture and Cognition: The Boundaries of Literary and Scientific Inquiry</em></blockquote><h3>Linguistic Relativity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*OwKI8rPrkE05ML5M.jpg" /></figure><p>In 1939, Benjamin Lee Whorf wrote a reflective essay, <strong><em>The relation of habitual thought and behavior to language</em></strong>. A student of Edward Sapir, Benjamin later became known for the <em>Whorf Sapir Hypothesis</em>, a theory of “linguistic relativity” which basically argues that “Language affects thought and behavior.” Although this sounds simple enough, the hypothesis itself ruffled an endless number of feathers.</p><blockquote><em>Language is not simply a reporting device for experience but a defining framework for it.</em></blockquote><blockquote><strong><em>Benjamin Lee Whorf</em></strong></blockquote><p>Whorf wrote about his experience as a fire insurance inspector. He observed that workers handled fullgasoline drums with care, but were careless and smoked cigarettes around drums that were called empty. The used gasoline drums were not empty or null; they contained dangerous flammable vapors. “<em>Physically the situation is hazardous, but the linguistic analysis according to regular analogy must employ the word ‘empty,’ which inevitably suggests lack of hazard.”</em>“</p><p>Does language affect behavior?</p><p>The Boolean like button, a virtual empathy counter, was introduced to the world on October 30, 2007 by FriendFeed, and implemented by Facebook on February 9, 2009. The psychological impact of chasing and accumulating likes is <a href="https://www.psychologytoday.com/blog/rewired-the-psychology-technology/201207/the-power">speculative</a> at this time, as are sociological concerns of slactivism. But the like button is now a part of the language that affects thought and behavior of billions of people.</p><p>As programmers, what choices are we making to affect the language of our culture? In substantial ways, our decisions could ripple through the core identities of our civilization.</p><blockquote><em>We cut nature up, organize it into concepts, and ascribe significances as we do, largely because we are parties to an agreement to organize it in this way — an agreement that holds through our speech community and is codified in the patterns of our language.</em></blockquote><blockquote><strong><em>Benjamin Lee Whorf</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ksal-tL8R9cAmMe-.png" /></figure><h3>Platonism and Process Philosophy</h3><p>In 380 B.C., Plato wrote about Aristotelian Forms in his <em>Dialogues</em>. An object in reality is a cave shadow of a more universal, transcendental Form. A Form, like a class, has immutable categories of attributes and properties, and things we experience are instances of those Forms.</p><p>Around 500 B.C., Heraclitus was reportedly arguing instead that “We both step and do not step in the same rivers. We are and are not.” In 2000, Nicholas Rescher summarized the Heraclitean worldview: <em>“…reality is not a constellation of things at all, but one of processes. The fundamental ‘stuff’ of the world is not material substance, but volatile flux, namely ‘fire’, and all things are versions thereof.”</em></p><p>In 1929, Alfred Whitehead extended the spirit of Heraclitus by writing <em>Process and Reality</em>, which laid out a modern framework for Process Philosophy. According to process philosophers, Objects only exist as “temporally overlapping occasions of experience” and are secondary to unique processes of change.</p><blockquote><em>We diverge from Descartes by holding that what he has described as primary attributes of physical bodies, are really the forms of internal relationships between actual occasions. Such a change of thought is the shift from materialism to Organic Realism, as a basic idea of physical science.<br>…<br>Connectedness is of the essence of all things of all types. It is of the essence of types, that they be connected. Abstraction from connectedness involves the omission of an essential factor in the fact considered. No fact is merely itself. The penetration of literature and art at their height arises from our dumb sense that we have passed beyond mythology; namely, beyond the myth of isolation.</em></blockquote><blockquote><strong><em>Alfred Whitehead</em></strong></blockquote><p>This distinction between the centrality of <em>Being</em> or <em>Becoming</em>, between Platonic Forms or Hegelian Changing, may sound similar to a common argument that takes place amongst dogmatic programmers: the superiority of either <strong><em>object-oriented programming</em></strong> or <strong><em>functional programming</em></strong>. The cornerstones of object-oriented programming (OOP) are objects; the cornerstones of functional programming (FP) are functions.</p><p>The core concepts of FP are continuously up for debate, but it seems that functions, as instruments of change, become more central to the conversation. Functions are passed around as parameters (callbacks), and ‘immutable’ data is passed, and often executed asynchronously, through a chain of functions until a new value is ready to be stored.</p><p>Does using OOP or FP affect our thoughts, behaviors, and final products? The quotable computer scientist, Edsger Dijkstra, seems to suggest so.</p><blockquote><em>A most important, but also most elusive, aspect of any tool is its influence on the habits of those who train themselves in its use. If the tool is a programming language this influence is, whether we like it or not, an influence on our thinking habits.</em></blockquote><blockquote><strong><em>Edsger Dijkstra</em></strong></blockquote><h3>Extensional Devices and Semantic Awareness</h3><p>There’s not much difference between learning how to code differently and learning how to think differently. In my opinion, the languages we learn will affect our thoughts.</p><p>Alfred Korzybski offered a handful of tools to combat Aristotelian patterns of thought, which he considered destructive to the civilization. He called these tools <em>Extensional Devices</em>, and perhaps we can recognize the value of some of these devices in our code.</p><p><strong>Indexing</strong><br>Indexing looks like this: “I Love<em>1</em> my wife. I Love<em>2</em> watching tv.” By indexing our abstractions, we become more aware of the differences between our generalizations.</p><pre>aPetInstance.id; // 1<br>bPetInstance.id; // 2</pre><p><strong>Chain-Indexing<br></strong>Roughly speaking, nouns can most closely be associated with objectifications and inaccurate abstractions of dynamic experiences. Chain-Indexing looks like this: “John1 was at the park last night. John2 went to a movie in the morning.” The purpose of indexing is to highlight that John1 and John2 are two different abstractions and have different associated qualities of being.</p><pre>this.state.history = [state1, state2, state3, state4]</pre><p><strong>Et cetera<br></strong>By using <em>etc.</em> frequently in our language, we acknowledge that there is always more to an abstraction: attribute strings we are missing, unique differences we are excluding, etc.</p><pre>function doTheseThings(callback_arguments) {<br>  callback_arguments.forEach(callback) {<br>    callback()<br>  };<br>};</pre><p><strong>Quotes<br></strong>Alfred was known to use quotation marks to indicate enormous abstractions. “The United States of America”, “The Majority”, “Liberals”, “Animals”, etc… Because quotation marks encapsulate String data-types in javascript, we often use capitalization instead:</p><pre>class Racist {<br>  hatePeople() {<br>  }<br>}</pre><p>Using extensional devices consistently would be a little ridiculous and certainly alienate you at parties. We must continue to speak the amazing and flawed language we and others know. However, Alfred’s ultimate goal was to raise semantic awareness and implicit mindfulness about the abstractions in the language that we use.</p><h3>Conclusion</h3><p>In javascript, there is a reported confusion concerning the comparison of two “identical” objects:</p><pre>({ key: “Happiness” } == { key: “Happiness” }); // false</pre><p>Is this a confusion? Technically, these two objects are being compared not by their values, but by their references to individual locations in memory.</p><p><em>Whatever you might say the object “is”, well it is not.</em></p><p><em>We are and are not.</em></p><p>I believe Plato might call it a bug, but Heraclitus would call it a feature.</p><p><em>Originally published February 4, 2017</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50561038f3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[set up a node.js environment on digital ocean to make a website and learn to code]]></title>
            <link>https://medium.com/@andrew.nease.code/setting-up-a-node-sandbox-on-digital-ocean-4420423198?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4420423198</guid>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[digitalocean]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Wed, 03 May 2017 18:23:08 GMT</pubDate>
            <atom:updated>2018-04-30T15:14:22.801Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started to learn to code, two things were incredibly helpful to me: setting up a sandbox to play in, and having a working project I could carry around in my pocket.</p><p>I took notes about the steps I took to accomplish these goals, and this blog post will be a compilation of those notes, with a few comments. Not included are the false starts, broken tutorials, unnecessary downloads, dead ends, and misunderstandings. Because I barely knew what I was doing, consider this less of a “how-to-do” and more of a “how-I-did.”</p><p>The topics covered here will include setting up:</p><ul><li>a local coding environment</li><li>a Digital Ocean account</li><li>a node server on the Digital Ocean ‘droplet’</li><li>a ‘Hello World’ Node.js app</li><li>a way to get your code onto the internet quickly</li></ul><p>Special Note: this blog post is being written in January, 2017. If something doesn’t work, use a popular search engine to track down a new strategy.</p><p>Another Special Note: this “how-I-did” was completed using a modern mac. And Digital Ocean will cost $5 a month. The first time I went through this process, it took hours and hours. After the third or fourth time, I can set up this environment in less than an hour.</p><h3>Coding Environment</h3><ol><li><strong>Download and install a coding editor.</strong> <a href="https://atom.io/">Atom Editor</a></li><li><strong>Download and install Node.js.</strong> There are many ways to get <em>Node</em> working on your system, including downloading and installing the package directly from <a href="https://nodejs.org/en/">Node.js</a>.</li><li><strong>Confirm that Node.js has been installed.</strong> Hit Command-Spacebar and type “terminal” to open your terminal. Type node -v. If the terminal responds with v.7.2.0 or any other set of numbers, congratulations. <em>Node</em> is on your system. Otherwise, troubleshoot via <a href="https://www.google.com/">Google.com</a> before moving on.</li><li><strong>Confirm that npm has been installed.</strong> <em>npm</em> stands for “Node Package Manager” and the associated website is <a href="https://www.npmjs.com/">here</a>. When you download the <em>Node</em> package in step 2, <em>npm</em> should be installed along with it. In your terminal, type npm -v. If the terminal responds with ‘3.10.9’ or any set of numbers, congratulations. <em>npm</em> is on your system. Otherwise, troubleshoot. (The <a href="http://blog.npmjs.org/post/85484771375/how-to-install-npm">npm blog</a> recommends running sudo npm install npm -g). After confirming your <em>npm</em> installation, to practice installing something globally, type npm install -g mocha. To see a list of what is currently <strong><em>globally</em></strong>installed with <em>npm</em>, type npm -g ls or npm -g ls --depth=0. To remove what you installed, type npm uninstall -g mocha.</li><li><strong>Install XCode.</strong> While not directly required to run <em>Node</em>, some features of <em>Node</em> may depend on it eventually. Get <em>XCode</em> free from the <a href="https://itunes.apple.com/us/app/xcode/id497799835?mt=12">Mac App Store</a>. In your terminal, type xcode-select --install to install the command line tools. To confirm that <em>XCode</em> has been installed, type sudo gcc --version.</li><li><strong>Install nvm.</strong> <em>nvm</em> stands for “Node Version Manager” and the associated website is <a href="https://github.com/creationix/nvm">here</a>. While <em>nvm</em> is also not required to run <em>Node</em>, it will be helpful in the future in order to install new versions of <em>Node</em> and quickly change which version is currently running. Check the <em>nvm</em> website for up-to-date best practices for installation. Today, it recommends: in your terminal, type curl -o- https: //raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash. To confirm that <em>nvm</em> has been installed, type nvm --version. To see which version of <em>Node</em> you’re using, type nvm current. To see which versions of <em>Node</em> can be installed, type nvm ls-remote. To install another version of <em>Node</em>, type nvm install 7.4.0. To switch <em>Node</em> versions, type nvm use 7.0.0. (Take note: any node modules installed globally with <em>npm</em> will be bound to the current <em>Node</em> version and be unavailable to other versions installed on your system.)</li></ol><h3>Set up a node server on Digital Ocean.</h3><ol><li><strong>Create a Digital Ocean account.</strong> Go to <a href="https://www.digitalocean.com/">Digital Ocean</a> and create an account. It’s free to create an account. It costs money to use a droplet.</li><li><strong>Create a droplet.</strong> Log in to Digital Ocean and create a droplet. Choose a newer <em>Ubuntu</em> distribution (like Ubuntu 16.04.1), the cheapest size, and a location. Give the droplet a name.</li><li><strong>Remember your IP address and password.</strong> When you create a droplet, it will be assigned an <em>IP address</em>. Write this down. You’ll be using it a lot for a while. Also, you will almost immediately get an email containing a long temporary password.</li><li><strong>Log in to your server</strong>. In your terminal, type ssh root@xxx.xxx.xx.xxx, replacing the x’s with your IP address. (If your terminal responds with “The authenticity of host ‘xxx.xxx.xx.xxx’ can’t be established,” don’t worry. This is your computer telling you that it does not recognize the IP address in its known_hosts file, located in the ~/.ssh directory. Type yes.) Now type the temporary password from your email (Twice!) and create a new password. Now you’ll be connected to your server via your terminal. To confirm that you are connected, type cd .. and then ls. You should see a directory listing. To disconnect back to your local machine, type exit.</li><li><strong>Use an SSH key.</strong> So that you don’t have to type in a password every time you type ssh root@xxx.xxx.xx.xxx to log in, you can create an SSH, or <em>Secure Shell</em>, relationship between your home computer and the server. Digital Ocean provides a <a href="https://www.digitalocean.com/community/tutorials/how-to-use-ssh-keys-with-digitalocean-droplets">walkthrough</a> for this and here are some details. Firstly, create an SSH key, but only create a new key if you’ve never created one before. You can check by looking for an <strong>id_rsa</strong> file by typing cd ~/.ssh and ls. To create a new key, type ssh-keygen -t rsa which will create two <em>key</em> files in your ~/.ssh directory: <strong>id_rsa</strong> is your private key; <strong>id_ras.pub</strong> is your public key. Secondly, now that the <strong>id_rsa</strong> file exists, type cat ~/.ssh/id_rsa.pub | ssh root@xxx.xxx.xx.xxx &quot;mkdir -p ~/.ssh &amp;&amp; cat &gt;&gt; ~/.ssh/authorized_keys&quot;. This command is basically saying, “Take the local public key, log on to the server, make an .ssh directory, and add the local public key to the server’s <em>authorized_keys</em> file.” (Special conditions arise if you ‘rebuild’ the server but keep the same IP address. Also, check Digital Ocean’s walkthrough for additional security details.)</li><li><strong>Add an alias to your .bash_profile.</strong> It will be incredibly helpful not to type your IP address every time you want to log in to your server. In your local terminal, type cd and then atom ~\.bash_profile. Assuming you’ve installed Atom, your <em>.bash_profile</em> file will appear in your Atom editor. Add the line alias whatever=&quot;ssh -t root@xxx.xxx.x.xxx&quot;. Or, if you want to log in to a default path on the server and run your server bash file, type alias whatever=&quot;ssh -t root@xxx.xxx.xx.xxx &#39;cd /var/www ; /bin/bash&#39;&quot;. Now typing whatever in your terminal should connect you efficiently. To re-load your .bash_profile file without restarting your terminal, type source ~/.bash_profile</li></ol><h3>Install Node.js on the server</h3><ol><li><strong>Update your server.</strong> Log on to your server, most easily by using the alias, such as whatever created above. When you’re connected, type sudo apt-get update which will fetch a current list of upgrades. Then type sudo apt-get upgrade to upgrade the current applications on your server. <em>apt-get</em> is a program Ubuntu can use to grab packages from the web. Type apt-get install curl to confirm that <em>curl</em> is installed and ready to use.</li><li><strong>Install nvm on server with apt-get.</strong> Similar to installing <em>nvm</em> above, in your terminal when connected to the server, type curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash or a similar command taken from the <a href="https://github.com/creationix/nvm">nvm website</a>. Type exit to disconnect, and then log on again. To confirm that <em>nvm</em> has been installed on your server, type nvm --version.</li><li><strong>Install Node.js on the server.</strong> Using <em>nvm</em> on the server, you can type nvm install 7.0.0 or whichever version you want to use. To confirm <em>Node</em> is installed, type node -v.</li><li><strong>Make the Node.js installation permanent.</strong> On the server, type n=$(which node);n=${n%/bin/node}; chmod -R 755 $n/bin/*; sudo cp -r $n/{bin,lib,share} /usr/local. According to a Digital Ocean <a href="https://www.digitalocean.com/community/tutorials/how-to-install-node-js-with-nvm-node-version-manager-on-a-vps">tutorial</a>, this command is “copying whatever version of node you have active via nvm into the /usr/local/ directory (where user installed global files should live on a linux VPS) and setting the permissions so that all users can access them.” If you switch <em>Node</em> versions on the server, you’ll need to run this line again. (Update: usenvm alias default 7.2.0 to set the default Node version on the server.)</li><li><strong>Make a directory on the server.</strong> Create a directory on your server where your <em>Node.js</em> project will be stored. For instance, type mkdir /var/www.</li><li><strong>Install pm2 on server.</strong> <em>pm2</em> is a node module available through <em>npm</em> that allows a node app to run permanently and in the background. On your server, type npm install -g pm2. To confirm that <em>pm2</em> has been installed, type pm2 ls. To start or stop an existing Node app, you would type something like pm2 start app.js or pm2 stop app.js. But first we need to make and upload an app. For more information on <em>pm2</em>, check out their <a href="http://pm2.keymetrics.io/">website</a></li></ol><h3>Create a ‘Hello World’ Node.js app</h3><ol><li><strong>Download a sample app.</strong> Choose a directory on your machine to create a <em>Node.js</em> app. I put a very <a href="https://github.com/andigan/hello_world_node_app">basic example</a> of a Node app on github for you to clone or copy.</li><li><strong>Install nodemon.</strong> nodemon is an npm module that both runs your Node app and re-runs the app when the javascript files are re-saved. (Changes to HTML files are less reliable.) To install, on your local machine, type npm install nodemon. Then, to run the app, type nodemon app.js. Check out the associated website <a href="https://nodemon.io/">here</a></li><li><strong>Change the port.</strong> If you’ve been following along, running the app above should not work in your local browser. This is because the port is set to <strong>80</strong>. In the app directory, type atom . to open the project, find the <em>config.js</em> file, and change the port to <strong>8000</strong> or another port. This will allow the nodemon app.js to run the app on your local machine, and you can visit the site at http://localhost:8000. When you copy the project up to the server, the port needs to be set to <strong>80</strong> in order for it to work on the internet. (Eventually, you’ll want to sync all files except the <em>config</em> file so that the port will remain appropriate to your environment.)</li></ol><h3>Loose ends</h3><ol><li><strong>Create another alias.</strong> To make this really fast, let’s add one last alias to the <em>~/.bash_profile</em> file, as above. Add this line to your .bash_profile, and make sure to replace all the relevant directories and IP addresses: alias ff=&quot;rsync -av --progress --delete ~/dev/hello_world_node_app root@xxx.xxx.x.xxx:/var/www &amp;&amp; ssh root@xxx.xxx.x.xxx &#39;cd /var/www/hello_world_node_app ; pm2 stop app.js ; pm2 start app.js&#39;&quot;. This command will sync all the local files from the hello_world_node_app directory up to the server’s www directory, stop <em>pm2</em>, and then start it again with the new copy.</li><li><strong>Install node modules on server.</strong> The above alias will copy all the files to the server, but we still need to install our node modules on the server. Connect to the server, navigate to the app’s directory: cd /var/www/hello_world_node_app, and type npm install.</li><li><strong>Troubleshooting.</strong> The alias above didn’t work for me at first. I had to log onto my server, type nvm use system, then npm install -g pm2. This will make sure that the <em>pm2</em> module is loaded into the version of <em>npm</em> that is used by the server when it isn’t loading the server’s bash.</li></ol><h3>Outcome</h3><p>By creating the environment in this way, I have been able to make minor changes in my node sandbox projects, type ff, push those changes up the server, connect to the IP address, and see almost immediately the effects of those changes in my browsers.</p><p>I’m certain there are better ways to organize and accomplish these goals, and I look forward to learning them.</p><p><em>Originally published January 25, 2017</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4420423198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[javascript, linting, and ESLint]]></title>
            <link>https://medium.com/@andrew.nease.code/javascript-linting-and-eslint-13e340b26b8a?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e340b26b8a</guid>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[linting]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Wed, 03 May 2017 18:20:32 GMT</pubDate>
            <atom:updated>2018-04-30T15:15:12.616Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Don’t call the world dirty because you forgot to clean your glasses.</em></blockquote><blockquote><strong><em>Aaron Hill</em></strong></blockquote><h3>Linting</h3><p>At Flatiron School, a resounding mantra while developing code, an echoed sentiment of Kent Black, is “<em>Make it work. Make it right. Make it fast.</em>“ Within this context, <strong>linting</strong> could be considered an element of making it right.</p><p>In 1979, a program called <strong>Lint</strong> was widely used to check the source code of C programs for potential errors. <strong>Lint</strong> would warn you if you had divisions by zero, out-of-range values, or other system-crashing, fatal flaws in your code.</p><p><strong>Lint</strong> was a lifesaver, and quite literally a lifesaver as well, which is why a conversation about <strong>linting</strong> should inevitably fall back upon the size of NASA’s code standards and the importance of consistency and reliability within your code. NASA rightfully takes <a href="https://en.wikipedia.org/wiki/Coding_conventions">coding standards</a> more seriously than the rest of us.</p><p>(For further learning on how a rocket scientist conceptualizes these validation concerns, consult <a href="https://www.usenix.org/conference/hotdep12/workshop-program/presentation/holzmann">a presentation by Gerald Holzmann</a>, senior research scientist at NASA’s Jet Propulsion Laboratory.)</p><p>In 2017, the definition of <strong>linting</strong> has become more generalized. <strong>Linting</strong> is the process of checking your code for not only system-crashing errors, but also stylistic inconsistencies as well.</p><blockquote><em>Consistency is contrary to nature, contrary to life. The only completely consistent people are dead.</em></blockquote><blockquote><strong><em>Aldous Huxley</em></strong></blockquote><p>It’s hard to find a positive quotation about consistency, but it does have its perks.</p><p>The field of cognitive neuroscience has long explored the relationship between pattern recognition and efficiency. The general idea is that the more often you see a thing’s pattern, the faster you can recognize what it is, as well as its components.</p><p>Development teams will often adopt a common set of stylistic standards for this reason. If two people share the same style, it will be much easier for them to read, understand, and modify each other’s code.</p><blockquote><em>Never offend people with style when you can offend them with substance.</em></blockquote><blockquote><strong><em>Sam Brown</em></strong><em> — Washington Post</em></blockquote><h3>ESLint</h3><p>Choosing a <strong>linting tool</strong> for your own projects is a matter of personal preference. Each tool will have weaknesses and strengths. For this post, I’ll be writing about <strong>ESLint</strong>, an open-source javascript linter created in 2013.</p><p><strong>ESLint</strong> has some core philosophies it abides by, such as:</p><ul><li>All rules can be turned off or on (nothing can be deemed “too important to turn off”)</li><li>Rules are “agenda free” — ESLint does not promote any particular coding style</li><li>ESLint values documentation and clear communication</li></ul><p>Like many linting tools, <strong>ESLint</strong> can be plugged directly into your preferred editor by installing a package. For example, in Atom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WVyTJ9RI1xCp-HYn.png" /></figure><p>Next, put an <em>.eslintrc</em> file in the root directory of your project. Where do you get the content for the file? Look around the internet for a template to use, write one from scratch, or ask a friend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cD6ySX8yG-xBNXyD.png" /></figure><p>I was fairly intimidated the first time I saw an <em>.eslintrc</em> file, but it turns out to be rather simple once you’ve seen it a few times. Pattern recognition and efficiency, indeed.</p><blockquote><em>The nice thing about standards is that there are so many of them to choose from.</em></blockquote><blockquote><strong><em>Andrew S. Tanenbaum</em></strong></blockquote><p>The purpose of the <em>.eslintrc</em> file is to define the rules by which you want to code by. For example: &quot;quotes&quot;: [2, &quot;single&quot;, &quot;avoid-escape&quot;] will set some rules related to quotation marks. Because <strong>ESLint</strong>respects documentation and clear communication, each rule is carefully explained at <a href="http://eslint.org/docs/rules/">eslint.org/docs/rules/</a>. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RisYivdvVw_HMOYK.png" /></figure><p>Beyond stylistic preferences, <strong>ESLint</strong> can also be used to identify problems in your code before it is executed. Errors I’ve commonly found in my code include:</p><ul><li>Missing semi-colons</li><li>Unused variables</li><li>Unexpected tokens</li></ul><p>By installing the package in Atom, I’m able to see the errors in my code immediately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1gmqWDn-GEuZc4su.png" /></figure><blockquote><em>Be regular and orderly in your life like a bourgeois, so that you may be violent and original in your work.<br></em><strong><em>Gustave Flaubert</em></strong></blockquote><p>Whatever your coding style is, a <strong>linter</strong> can improve your aesthetic awareness and help you to teach yourself to adhere to a consistent set of rules — whichever ones you elect to follow.</p><p>Before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-YdOlBnRT-6s9Wvs.png" /></figure><p>After:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*THuhxbYhk2C3JI5H.png" /></figure><p><em>Originally published January 9, 2017</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e340b26b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ruby and self-awareness]]></title>
            <link>https://medium.com/@andrew.nease.code/ruby-and-self-awareness-51c4735e09ce?source=rss-325df8d9c91f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51c4735e09ce</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[self]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Nease]]></dc:creator>
            <pubDate>Wed, 03 May 2017 18:11:10 GMT</pubDate>
            <atom:updated>2018-04-30T15:16:14.893Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Knowing others is wisdom. Knowing the self is enlightenment. Mastering others requires force. Mastering the self requires strength.</blockquote><blockquote><strong>Lao Tzu</strong> — Tao Te Ching</blockquote><blockquote>Your burden is of false self-identifications—abandon them all.</blockquote><blockquote><strong>Nisargadatta Maharaj</strong></blockquote><h3>What is self?</h3><p>While the history of self is outside the scope of this post, self has been around for a long short while. Across coding languages, self has been this and self has been Me. This is Me and Me is self.</p><p>So what is self again?</p><p>Perhaps not the most carefully named keyword, self has been described as:</p><ul><li>the object receiving the method</li><li>the thing that called it</li><li>the object itself</li></ul><p>This confuses Me.</p><p>A good way to approach a simple complex problem is to start from the start. What follows are a series of Ruby poems. Consider it Ruby haiku, without the syllable.count.</p><h3>Self and main</h3><blockquote><em>This above all: to thine own </em><em>self be </em><em>true.</em></blockquote><blockquote><strong><em>William Shakespeare</em></strong><em> — Hamlet</em></blockquote><p>Within the main file, printing self will consistently return the word <strong>main</strong>.</p><pre>puts self</pre><pre>#=&gt; main</pre><p><strong>main</strong> is a unique label. Consider the <strong>main</strong> self in our code to be the entire root program. Its body is the lines of code in our file, including all the code imported with require and require_relative. According to itself, it’s the alpha and omega.</p><p><strong>main</strong> is also called the ‘top-level object’ for a reason:</p><pre>puts self<br>puts “is an”<br>puts self.class</pre><pre>#=&gt; main<br>#=&gt; is an<br>#=&gt; Object</pre><p>All the code written into the <strong>main</strong> file is being written into a hidden <strong>main</strong> object.</p><p>Every self is an object, and when you puts an object, the object’s label will printed to the console.</p><p>As an object, <strong>main</strong> has a unique id, which changes each time the code is compiled:</p><pre>puts self.object_id<br>puts object_id</pre><pre>#=&gt; 23409245239845<br>#=&gt; 23409245239845</pre><p>When we write a basic method into the body of an object, that method belongs to the object, and the method can then be called in a few ways. Here are examples using the <strong>main</strong> object:</p><pre>public</pre><pre>def i_have_my_methods<br>  puts self<br>end</pre><pre># Here we call the method with an implicit self<br>i_have_my_methods</pre><pre># Here we call the method with an explicit self<br>self.i_have_my_methods</pre><pre># Here we call the method with the the Object class’s send method<br>self.send(:i_have_my_methods)</pre><pre>#=&gt; main<br>#=&gt; main<br>#=&gt; main</pre><p>The use of public here is necessary for the second method call, but the purpose of this snippet is to note that, within an object or an object’s methods, self becomes the object calling it.</p><p>(It is necessary in this code block to use the <em>public</em> method as a flag. Without calling the <em>public</em> method, the <em>i_have_my_methods</em> method would be a private method by default. You can call an object’s private methods with an implicit self, but not with an explicit self. Certainly not to be confusing, public is a private method within the <strong>Object</strong> class.)</p><p>Also worth noting is that methods can be written into objects explicitly as well:</p><pre>def self.i_have_my_self<br>  puts self<br>end</pre><pre>i_have_my_self</pre><pre>#=&gt; main</pre><p>It would be an easy mistake at this point to think of self as static. In the two blocks of code above, each of the calls to self is returning <strong>main</strong>, either as the object or as a label for the object. However, consistency isn’t constancy, and we’ll see more clearly below that self is dynamically being defined each time it is encountered.</p><blockquote><em>A </em><em>self is not something static, tied up in a pretty parcel and handed to the child, finished and complete. A </em><em>self is always becoming.</em></blockquote><blockquote><strong><em>Madeleine L’Engle</em></strong><em> — A Circle of Quiet</em></blockquote><p>Sometimes self just doesn’t feel like itself today. A good possibility is that her or his context has changed.</p><p>When is self not being its <strong>main</strong> self? When self is in another object.</p><pre># print the main id<br>puts self.object_id #=&gt; main id: 70263203353360</pre><pre># create a new object<br>self_within_a_self = Object.new()</pre><pre># print the id of the new object<br>puts self_within_a_self.object_id #=&gt; 70263211775100</pre><pre># create a method within the new object<br>def self_within_a_self.say_you_say_me<br>  puts self<br>  puts self.object_id<br>end</pre><pre># call the new object’s method<br>self_within_a_self.say_you_say_me</pre><pre>#=&gt; #&lt;Object:0x007fcedb8ea8f8&gt;<br>#=&gt; 70263211775100</pre><p>By calling the <em>say_you_say_me</em> method, we can see that the value of self within a nested object will be the new object itself. The object_ids of the inner self and the new object will be the same.</p><p>(The <strong>self_within_a_self</strong> object id is similar to the <strong>main</strong> object id because the id’s have a relationship to the address where the Object is being stored in memory.)</p><h3>Self and classes</h3><blockquote><em>We can change environments and replace most body parts, but our brain is pretty fundamental to who we are. And who we are includes a sense of </em><em>self. That said, understanding where the sense of </em><em>self comes from ultimately needs to involve the consideration of bodies and environments that shape the </em><em>self.</em></blockquote><blockquote><strong><em>Bruce Hood</em></strong><em> — The Self Illusion: How the Social Brain Creates Identity</em></blockquote><p>Because an instance of a class is an object, we can expect the same behavior from a self within an instance:</p><pre>class OtherSelf</pre><pre>  def initialize<br>    puts “Who am I?”<br>    puts self<br>    puts self.object_id<br>  end<br>end</pre><pre>dissociative_self = OtherSelf.new()</pre><pre>puts “Who is he?”<br>puts dissociative_self.object_id<br>puts “— — -”</pre><pre>another_self = OtherSelf.new</pre><pre>puts “Who is she?”<br>puts another_self.object_id</pre><pre>#=&gt; Who am I?<br>#=&gt; #&lt;OtherSelf:0x007fe3bc12b428&gt;<br>#=&gt; 70308044823060<br>#=&gt; Who is he?<br>#=&gt; 70308044823060<br>#=&gt; — — -<br>#=&gt; Who am I?<br>#=&gt; #&lt;OtherSelf:0x007fe3bc12ad48&gt;<br>#=&gt; 70308044822180<br>#=&gt; Who is she?<br>#=&gt; 70308044822180</pre><p>Above, two different objects were created with two unique object_ids. In lines 5, 24, and 33, we see that self will dynamically become “the object in which it is called”.</p><p>This is where it can get a little confusing. Try not to lose your self.</p><p>In the code below, we’ll define a class <strong>OtherSelf</strong> and give it <strong><em>instance methods</em></strong> and a <strong><em>class method</em></strong>.</p><p>Note the #1 block will happen only once, when <strong>OtherSelf</strong> is defined. The code in <strong>OtherSelf</strong> that is outside of a method would execute even if an instance of <strong>OtherSelf</strong> wasn’t created.</p><p>Also note that only one instance is being created here with dissociative_self = OtherSelf.new(). The object_ids in instance methods would otherwise be unique amongst multiple instances.</p><pre>class OtherSelf<br>  puts “1. CLASS OBJECT: What is my self?”<br>  puts self #=&gt; OtherSelf<br>  puts self.object_id #=&gt; 70335135276500<br>  puts self.class #=&gt; Class<br>  puts “** My self is the OtherSelf object and my class is Class.”</pre><pre>### instance methods</pre><pre>  def initialize<br>    puts “2. INSTANCE OBJECT: Who is my self?”<br>    puts self #=&gt; #&lt;OtherSelf:0x007ff05981b3b0&gt;<br>    puts self.object_id #=&gt; 70335135275480<br>    puts “** My self is a newly created instance object.”<br>  end</pre><pre>  def and_what_is_my_self?<br>    puts “3. INSTANCE OBJECT: And what is my self?”<br>    puts self.class #=&gt; OtherSelf<br>    puts “** My self’s class is the OtherSelf object.”<br>  end</pre><pre>  def and_who_is_what_my_self_is?<br>    puts “4. INSTANCE OBJECT: And who is what my self is?”<br>    puts self.class.object_id #=&gt; 70335135276500<br>    puts “** My self’s class is the unique OtherSelf object.”<br>  end</pre><pre>### class method</pre><pre>  def self.who_is_my_self_then?<br>    puts “5. CLASS OBJECT: Who is my self then?”<br>   puts self#=&gt; OtherSelf<br>    puts self.object_id #=&gt; 70335135276500<br>    puts “** In this class method, my self is the unique OtherSelf object.”<br>  end<br>end</pre><pre>dissociative_self = OtherSelf.new()</pre><pre>puts “6. MAIN OBJECT: Who is that?”<br>puts OtherSelf #=&gt; #&lt;OtherSelf:0x007ff05981b3b0&gt;</pre><pre>puts OtherSelf.class #=&gt; OtherSelf<br>puts dissociative_self.object_id #=&gt; 70335135275480</pre><pre>puts “** That is an instance object.”<br>puts “7. MAIN OBJECT: What is who that is?”<br>puts OtherSelf #=&gt; OtherSelf<br>puts OtherSelf.class #=&gt; Class<br>puts OtherSelf.object_id #=&gt; 70335135276500<br>puts “** OtherSelf is the class object.”</pre><p>Why does the self within a <strong><em>class method</em></strong> become the <strong>OtherSelf</strong> object and not the instance object?</p><p>The answer is buried within the topic of metaprogramming and you can read about it here:<a href="http://yugui.jp/articles/846">Three Implicit Contexts in Ruby</a></p><p>But for now, we’ll say that defining the class method with an explicit self changes the scope of the method and therefore self resolves to <strong>OtherSelf</strong>. In other word: magic.</p><h3>Self and modules</h3><blockquote><em>There is something that is me; there is an area of my experience that I call myself. And there is another area of my experience which I call not myself. But you will immediately see that neither one could be realized without the other. You would not know what you meant by </em><em>self unless you experience something other than </em><em>self. You would not know what you meant by other unless you understood </em><em>self. They go together. They arise at the same time. You do not have first </em><em>self and then other, or first other and then </em><em>self; they come together.</em></blockquote><blockquote><strong><em>Alan Watts</em></strong><em> — The Philosophies of Asia</em></blockquote><p>Within methods inherited from a module, self continues to become the object that calls the method.</p><pre>module Dao</pre><pre>  class Atman<br>    def who_am_I?<br>      puts self<br>    end</pre><pre>    def what_am_I?<br>      puts self.class<br>    end<br>  end<br>end</pre><pre>class MySelf &lt; Dao::Atman<br>end</pre><pre>i = MySelf.new</pre><pre>i.who_am_I? #=&gt; #&lt;MySelf:0x007fe37b0bd1a8&gt;<br>i.what_am_I? #=&gt; MySelf</pre><p>i is an instance of MySelf, so self becomes the instance object.</p><p>But is there a way to go deeper? Is a self only a self, or is it something else?</p><p>We can use the <em>ancestors</em> method to find out about our selfs. According to Ruby’s documentation, the <em>ancestors</em> method is attached to all <strong>Modules</strong>, and because all <strong>Classes</strong> are <strong>Modules</strong>, we can call <em>ancestors</em> on any <strong>Class</strong>.</p><pre>puts self.class.ancestors.inspect</pre><pre>#=&gt; [Object, Kernel, BasicObject]</pre><p>The <em>ancestors</em> method will return an array of parent <strong>Modules</strong>. In the code above, self is inheriting each of its ancestor’s methods. For example, puts is a method in the <strong>Kernel</strong>, so puts can be called in any <strong>class</strong>, including <strong>object</strong>. puts is a private method, so it can’t be called explicitly. However, since putsbelongs to the <strong>Kernel</strong>, when our self is our <strong>main</strong> self, self.class.ancestors[1].puts &quot;The Kernel privately says hello.&quot; will result in a friendly little greeting from the <strong>Kernel</strong> module.</p><p>We can use the <em>ancestors</em> method to explore our self a little deeper. Also, note that self.class.superclass will return the first parent from the <em>ancestors</em> method.</p><pre>module Dao</pre><pre>  class Atman<br>    @@deep_down = self</pre><pre>    def who_am_I?<br>      puts self<br>    end</pre><pre>    def what_am_I?<br>      puts self.class<br>    end</pre><pre>    def who_am_I_really?<br>      puts @@deep_down<br>      puts self.class.superclass<br>    end</pre><pre>    def who_am_I_really_really?<br>      puts self.class.ancestors.inspect<br>    end<br>  end<br>end</pre><pre>class MySelf &lt; Dao::Atman<br>end</pre><pre>i = MySelf.new</pre><pre>i.who_am_I?<br>#=&gt; #&lt;MySelf:0x007fbe59837d58&gt;</pre><pre>i.what_am_I?<br>#=&gt; MySelf</pre><pre>i.who_am_I_really?<br>#=&gt; Dao::Atman</pre><pre>#=&gt; Dao::Atman<br>i.who_am_I_really_really?<br>#=&gt; [MySelf, Dao::Atman, Object, Kernel, BasicObject]</pre><h3>Self and procs</h3><blockquote><em>In fanciful exaggeration we may say that the vicarious experience belongs to a parallel </em><em>self, one that runs its course alongside the </em><strong><em>main</em></strong><em> </em><em>self.</em></blockquote><blockquote><strong><em>Jon Elster</em></strong><em>The Multiple Self</em></blockquote><p>selfs within Proc objects, or procedures, also have some interesting behavior. In the code below, we’ll be printing two selfs: the first as a method call within the procedure, and the second as the self passed into the procedure as an argument.</p><pre>public</pre><pre># Define a procedure which receives `self` as an argument<br># Print the `self` value in the procedure<br># Print the `self` value received as an argument</pre><pre>i_have_my_procedures = proc { |self_as_argument|<br>  puts self<br>  puts self_as_argument<br>}</pre><pre># PROCEDURE CALL from main object<br># with main `self` as an argument</pre><pre>i_have_my_procedures.call(self)<br>#=&gt; main<br>#=&gt; main</pre><pre># print the Proc location</pre><pre>puts i_have_my_procedures<br>#=&gt; #&lt;Proc:0x007fc87908d4e8@filename.rb:6&gt;</pre><pre># define a class object which initializes with a Proc object</pre><pre>class OtherSelf</pre><pre>### instance methods<br>  def initialize(procedure_to_call)</pre><pre>    # PROCEDURE CALL from new instance object<br>    # with instance `self` as an argument:</pre><pre>    procedure_to_call.call(self)<br>    #=&gt; main<br>    #=&gt; #&lt;OtherSelf:0x007fc87908cd40&gt;</pre><pre>    # print the Proc location</pre><pre>    puts procedure_to_call<br>    #=&gt; #&lt;Proc:0x007fc87908d4e8@filename.rb:6&gt;</pre><pre>    # (Proc blocks can be stored as instance variables)<br>    @stored_proc = procedure_to_call<br>  end</pre><pre>  # (and retrieved)</pre><pre>  def get_repressed_self<br>    @stored_proc.call(self)</pre><pre>    #=&gt; main<br>    #=&gt; #&lt;OtherSelf:0x007fc87908cd40&gt;<br>  end</pre><pre>### class method<br>  def self.we_all_have_procedures(proc_to_call)<br>    # PROCEDURE CALL from class method<br>    # with class self as an argument:</pre><pre>    proc_to_call.call(self)<br>    #=&gt; main<br>    #=&gt; OtherSelf<br>  end<br>end</pre><pre>myself = OtherSelf.new(i_have_my_procedures)<br>OtherSelf.we_all_have_procedures(i_have_my_procedures)</pre><p>Notice in lines 18 and 34, the Proc object location is always pointing to the main object. Thus, when selfis called within a proc, self becomes the object in which it was first defined, such as <strong>main</strong>.</p><p>But if we pass our current self as an argument, our Proc will be able to use the object in which the Proc is called.</p><h3>What is Self?</h3><blockquote><em>Know thy</em><em>self.</em></blockquote><blockquote><strong><em>Unknown</em></strong><em> — The Delphic Maxims</em></blockquote><blockquote><em>The problem with introspection is that it has no end.</em></blockquote><blockquote><strong><em>Philip K. Dick</em></strong><em> — The Transmigration of Timothy Archer</em></blockquote><p>But what is self really? The neverending question.</p><p>self is a keyword, and to learn more about how Ruby compiles keywords, prepare for a long study. In fact, here’s <a href="http://hokstad.com/compiler">a blog by Vidar Hokstad</a>, who wrote a Ruby compiler from scratch. And here’s a book called <a href="https://www.amazon.com/Ruby-Under-Microscope-Illustrated-Internals/dp/1593275277">Ruby Under a Microscope: An Illustrated Guide to Ruby Internals</a> by Pat Shaughnessy. Godspeed.</p><p>In summary, like most topics in the world, you can always go deeper. Also, a great way to learn about a complicated simple concept such as your self is through experimentation, trial and error, poetry, and play.</p><p>Write it out. Run it. Repeat.</p><p>Suggested rabbit hole: <a href="https://www.google.com/#q=%22self+within+a+self%22">Google search: self within a self</a></p><p><em>Originally published December 6, 2016</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51c4735e09ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>