<?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 Kyle Stewart on Medium]]></title>
        <description><![CDATA[Stories by Kyle Stewart on Medium]]></description>
        <link>https://medium.com/@kyle.w.stewart?source=rss-b036923f9276------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*UMlc_LDYKSvWNUMHgMGspQ.jpeg</url>
            <title>Stories by Kyle Stewart on Medium</title>
            <link>https://medium.com/@kyle.w.stewart?source=rss-b036923f9276------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:21:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kyle.w.stewart/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[You Don’t Understand Cryptoassets]]></title>
            <link>https://medium.com/@kyle.w.stewart/you-dont-understand-cryptoassets-894364ad21e1?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/894364ad21e1</guid>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Fri, 06 Mar 2020 12:58:29 GMT</pubDate>
            <atom:updated>2020-03-06T12:58:29.509Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Awareness is Great</strong><br>A recent <a href="https://medium.com/blockchain-capital-blog/bitcoin-is-a-demographic-mega-trend-data-analysis-160d2f7731e5">Harris Poll</a> showed 89% of Americans are aware of Bitcoin, and 60% of 18–34 years old were ‘somewhat’ familiar with it. Way to go crypto influencers! All your tweets are making a difference.</p><p>Unfortunately, a <a href="https://www.statista.com/chart/18345/crypto-currency-adoption/">2018 Statista Consumer Survey </a>found only 5% of Americans have ever used a cryptocurrency.</p><p><em>You don’t understand cryptoassets.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjgyFCjwt941mKZYn2mPRQ.jpeg" /></figure><p><strong>An Analogy Might Help<br></strong>Don’t feel bad. Explaining cryptoassets is hard. Why not try a well-known analogy. Have you heard about the printing press?</p><p>The 14th-century was a rough time for Europe. Famine and disease drove the masses to the Catholic Church for comfort. As the Church gained power, it was corrupted and sold indulgences (God’s forgiveness). The printing press disrupted the Church by making it faster and easier to make books and enabling everyone to purchase a bible and BTOC (be their own Church). Bitcoin is the modern-day printing press and will eliminate monetary indulgences (bank bailouts and QE).</p><p>Unfortunately, cryptoassets are not at all like the printing press! They don’t make anything faster or easier.</p><p><em>You don’t understand cryptoassets or disruption.</em></p><p><strong>Cryptoassets Are Part of the Internet<br></strong>Forget the printing press. What about the web?</p><p>In 1989, Tim Bernes-Lee invented the World Wide Web and created a protocol that connected the world. Easy and cheap connectivity disrupted loads of stuff and replaced them with a handful of behemoths with more power than any Renaissance Pope. Oh well, an Orwellian future is a small price to pay for free two-day shipping.</p><p>Fortunately, cryptoassets are not at all like the web.</p><p><em>You don’t understand cryptoassets, disruption, or the internet.</em></p><p><strong>It’s about UX<br></strong>You know who does understand the internet? Reed Hastings.</p><p>Reed Hasting started a mail-order DVD service in 1997 called Netflix. Why mail-order? Because the user experience of watching internet streaming video sucked in 1997. Netflix didn’t start a streaming service until 2010. When that streaming service grew too fast for the internet, they built <a href="https://openconnect.netflix.com/en/">a solution</a> to make the internet better.</p><p>Cryptoassets are not like Netflix, but the point is user experience is important.</p><p><strong>Never Delegate Understanding<br></strong>The gap between cryptoasset awareness and use is not due to a lack of persuasion. User experience drives adoption, and cryptoasset UX is 1997 internet streaming video bad. Why so bad? Because cryptoassets are decentralized. That is not a typo. Decentralization is cryptoassets’ biggest advantage and most significant problem.</p><p>Decentralization requires users to figure out their custody, and cryptoasset custody is hard. Hard because it involves risk, and people are risk-averse, especially when they don’t understand the risks. No magic cryptography ferry is going to wave a magic wand and make these risks go away.</p><p>The only way to make custodial risks more tolerable (i.e., improve UX) is actually to explain cryptoassets and cryptoasset custodial risk to users. So, they can understand them and learn how to manage them. The alternative is to build a centralized clearinghouse that can socialize losses across members, but that would fundamentally centralize the asset class (kind of sounds like some crypto exchanges, huh?).</p><p>Persuasion is fun and drives clicks, but what the cryptoasset ecosystem really needs is more understanding. We founded Altmirai to help. Our only focus is on cryptoasset custody. Not as a custodian, but as a conflict-free resource to help users, service providers, and asset managers understand custody and mitigate custodial risks. Check us out at <a href="https://www.altmirai.com/">www.altmirai.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=894364ad21e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the Coincheck Hack is A Good Thing]]></title>
            <link>https://medium.com/@kyle.w.stewart/why-the-coincheck-hack-is-a-good-thing-dded8e295901?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/dded8e295901</guid>
            <category><![CDATA[cryptoasset]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Mon, 29 Jan 2018 21:27:21 GMT</pubDate>
            <atom:updated>2018-01-29T21:27:21.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*tGUNECy8_voTUmjseG1m1w.jpeg" /></figure><p>Japanese cryptoassets exchange, Coincheck, reported late last week that hackers stole 500 million NEM tokens worth around $500 million. Coincheck has since promised to reimburse users for their losses, Japanese regulators have pledged to investigate and suggested new government oversight is coming (<a href="https://en.wikipedia.org/wiki/Mt._Gox">Mt. Gox</a> was also based in Japan). Some will view this as a setback for cryptoassets; I believe it is a positive.</p><p>Any rational SWOT analysis of cryptoassets would have asymmetrical (public and private key) cryptography in all four quadrants. Asymmetrical cryptography is an essential component that allows cryptoassets to function without a trusted third party. It also a creates a significant hurdle to large-scale adoption as a lost or stolen private key results in the loss of assets 100% of the time (just ask this <a href="http://www.independent.co.uk/life-style/gadgets-and-tech/news/bitcoin-value-james-howells-newport-landfill-hard-drive-campbell-simpson-laszlo-hanyecz-a8091371.html">guy</a>). There is no resetting a password or showing up at your local branch with two forms of ID.</p><p>For many users, the solution has been to hold their cryptoassets in a wallet at an exchange. When a user opens an account with an exchange (whose password can be reset), they receive a wallet where they are required to transfer cryptoassets or currency before they trade. Users are not required to hold their cryptoassets at the exchange indefinitely, but many choose to as it is easier than managing private keys themselves. Users who do this sacrifice decentralization for convenience as the exchange now becomes a trusted third party.</p><p>This appears to be a reasonable trade-off as efficient trading does require some centralization (it is good to have all the buyers and sellers in the same place). However, the qualities that make for efficient trading maybe at odds with good security. It is good if buyers and sellers agreed to meet at the same place to trade, but it would be bad if they all stored their private keys on the same hard-drive. Someone who knows more about security protocols might argue for a monolithic exchange with the resources necessary to develop a hack-proof system, but then why even bother creating a decentralized asset.</p><p>It is good that Coincheck will reimburse users for lost NEM tokens. It might even be positive that the Japanese government may start regulating exchanges. However, it is a better reminder that cryptoassets and decentralization have drawbacks and centralized solutions are not perfect and ultimately come at the cost of decentralization.</p><p>Coincheck was a trusted third party who did not harm their users because they were intentionally evil and sold personal information or charged them high fees, they harmed them because they failed to manage their risk. Decentralization protects users against intentional harm by removing the trusted third party, but it does not eliminate the risks inherent to a system. Decentralization requires users to be responsible for their risks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dded8e295901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Cryptoassets is Facebook, ​not Fiat]]></title>
            <link>https://medium.com/@kyle.w.stewart/the-future-of-cryptoassets-is-facebook-not-fiat-af7bef60967e?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/af7bef60967e</guid>
            <category><![CDATA[cryptoasset]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Mon, 22 Jan 2018 23:40:23 GMT</pubDate>
            <atom:updated>2018-01-22T23:40:23.327Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Using Aggregation Theory to predict the future of CrytpoAssets</em></p><p>I am always amused when I hear claims that Bitcoin will one-day replace fiat money. Not because I dispute the potential of distributed ledgers and digital tokens, but because there is hard evidence the world likes fiat. Bitcoin, after all, is not the first censorship-resistant non-inflationary medium of exchange. Gold also has these proprieties and has literally been around for all of human existence.</p><p>Gold was the dominant medium of exchange until we, through our governments, chose to replace it with fiat money. We did so because we wanted individual countries to be able to implement independent monetary policy. Expecting the world en masse to abandon monetarism just because someone invented digital gold seems more like a libertarian fantasy or speculative wishful thinking than a rational analysis of facts.</p><p>Bitcoin (or another cryptoasset) will likely continue to facilitate censored transactions, play some role in cross-board transactions and satisfy some of the demand for gold. However, these do not justify the current price of Bitcoin (<a href="https://www.linkedin.com/pulse/what-right-price-bitcoin-kyle-w-stewart/">see: What is the Right Price for Bitcoin</a>). When I express this view, Bitcoin maximalists typical counter with the following strawman-like argument:</p><ol><li>The internet had more impact than anyone could have predicted.</li><li>Cryptoassets are like the internet.</li><li>Cryptoasset will have more impactful than anyone can predict.</li></ol><p>The main problems with this argument are:</p><ol><li>Not everything “internet” ended well (e.g., <a href="https://en.wikipedia.org/wiki/Pets.com">Pets.com</a>).</li><li>We now know the impact of the internet.</li><li>We can use this knowledge to make informed expectations for cryptoassets.</li></ol><h3>Aggregation Theory</h3><p>Ben Thompson, the creator of <a href="https://stratechery.com/">Stratechery</a>, writes about “the strategy and business side of technology and media, and the impact of technology on society.” He has developed <a href="https://stratechery.com/2015/aggregation-theory/">Aggregation Theory</a> to explain the impact of the internet.</p><blockquote><em>“The value chain for any given consumer market is divided into three parts: suppliers, distributors, and consumers/users. The best way to make outsize profits in any of these markets is to either gain a horizontal monopoly in one of the three parts or to integrate two of the parts such that you have a competitive advantage in delivering a vertical solution. In latter depended on controlling distribution.</em></blockquote><blockquote><em>The fundamental disruption of the Internet has been to turn this dynamic on its head. First, the Internet has made (of digital goods) free, neutralizing the advantage that pre-Internet distributors leveraged to integrate with suppliers. Secondly, the Internet has made transaction costs zero, making it viable for a distributor to integrate forward with end users/consumers at scale.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sL8poyszPm_4S4O3.png" /></figure><blockquote><em>This has fundamentally changed the plane of competition: no longer do distributors compete based exclusive supplier relationships, with consumers/users an afterthought. Instead, suppliers can be aggregated at scale leaving consumers/users as a first order priority. By extension, this means that the most important factor determining success is the user experience: the best distributors/aggregators/market-makers win by providing the best experience, which earns them the most consumers/users, which attracts the most suppliers, which enhances the user experience in a virtuous cycle.”</em></blockquote><p>This “virtuous cycle” is the main takeaway from Aggregation Theory for cryptoassets. As a network’s value grows exponentially (see: <a href="https://en.wikipedia.org/wiki/Metcalfe%27s_law">Metcalfe’s Law</a>), once a firm has aggregated enough users, it suffocates all competition as it becomes nearly impossible for a nascent network to compete by offering a comparable UX (ask Google about <a href="http://mashable.com/2015/08/02/google-plus-history/#2ZXiqxu4Xsq5">Google Plus</a>). Cryptoassets provides a potential solution to this obstacle.</p><p>A nascent decentralized network could present users with a financial incentive through a digital token to compensate them for accepting an inferior UX in the short-term. In this context, the goalpost for cryptoassets is to reach UX parity with centralized applications assuming a comparable user network. Arriving at this goalpost will require finding solutions to both technical and governance challenges.</p><h3>Technical Challenges</h3><p>To understand the technical challenges, read <a href="https://medium.com/@preethikasireddy/fundamental-challenges-with-public-blockchains-253c800e9428">Preethi Kasireddy: Fundamental challenges with public blockchains</a>. She does an excellent job explaining the relevant issues and potential solutions. I will highlight only one, scalability. A cryptoasset’s ability to store and distribute value comes from decentralization, but this decentralization also hinders scalability.</p><p>Decentralization requires data be replicated across the entire network and an expensive consensus mechanism for security. The larger a decentralized network, the worse it will perform. Attempting to build a decentralized Facebook clone today is roughly analogous to trying to stream Netflix on 56K dial-up. There are many potential solutions including sidechains and data tangles, but none are proved at scale, and all have limitations.</p><h3>Governance Challenges</h3><p>Centralized organizations are inherently better at decision making and more capable of responding to changing user demands. Facebook can alter an algorithm or move a button without needing to build consensus among users. Fred Ersam’s <a href="https://medium.com/@FEhrsam/blockchain-governance-programming-our-future-c3bfe30f2d74">Blockchain Governance: Programming Our Future</a> lays out much of the current thinking.</p><p>The difficulty of managing a decentralized organization, however, is not unique to cryptoassets. Attempts to find solutions go back as far as Plato and there is unlikely to be a magic bullet solution found anytime soon. Cryptoassets will most likely follow a Darwinian evolution with forks playing an important role (see: <a href="https://medium.com/@FEhrsam/accelerating-evolution-through-forking-6b0bba85a2ba">Fred Ersam: Accelerating Evolution Through Forking</a>).</p><h3>Conclusion</h3><p>Facebook provides users with a serviceable UX (or buys someone who creates a better one), aggregates 2 billion users, and requires them to consume advertising worth <a href="https://www.cnbc.com/2017/05/03/facebook-average-revenue-per-user-arpu-q1-2017.html">$16 a year</a> (with 50% operating margins) for the privilege of accessing their data. While operating margins vary by industry, 50% is excessive by any measure.</p><p>Facebook is not alone its ability to earn excess returns, nor is it unique to internet companies. User networks create a substantial barrier to entry across many industries that has thwarted even the deepest-pocketed competitors. Cryptoassets hold the potential for users and firms to gain access to a wealth of excess returns which will provide enough incentive to solve the many technical and governance challenges that remain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af7bef60967e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is the Right Price For Bitcoin]]></title>
            <link>https://medium.com/@kyle.w.stewart/what-is-the-right-price-for-bitcoin-3af6a83f4cb1?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af6a83f4cb1</guid>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Thu, 11 Jan 2018 19:19:12 GMT</pubDate>
            <atom:updated>2018-11-30T15:31:42.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is the Right Price for Bitcoin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cf7zHycZ4cR0Uez-bI5A5A.jpeg" /></figure><h4>IMPORTANT: This post is intended for informational purposes only. It is not investment advice or a recommendation of any kind.</h4><p>I recently came across an excellent <a href="https://medium.com/john-pfeffer/an-institutional-investors-take-on-cryptoassets-690421158904">paper</a> by John Pfeffer in which he makes a detailed argument for why he is more positive on Bitcoin as a monetary store of value than protocol or utility tokens. While I do not agree with John’s conclusions, he clarifies some complicated issues and I highly recommend it to anyone interested in cryptoassets. His paper challenged many of my own views and inspired me to formalize some of my views in this post.</p><p>Given Bitcoin’s limitations (speed, scalability and energy consumption) and the inability for the community to agree on solutions, I believe there are two likely outcomes for Bitcoin:</p><ol><li>Bitcoin’s public mindshare and large acceptance crowd out other cryptoassets despite its flaws and becomes the dominant store of value and cryptoassets designed for speed and scalability dominate payments,</li><li>A better-designed cryptoasset or cryptoassets replace Bitcoin, and it goes to zero</li></ol><p>I will start my analysis based on the first outcome with the most optimistic expectations possible to see if I can justify the current price of Bitcoin (~$14,000).</p><h3>Discount Rate</h3><p>While it may be rational to believe a bitcoin will be worth $1 million in 2050, it is not rational to purchase a bitcoin at $14,000 today based on this belief. Buying a bitcoin today at $14,000 and selling it at $1,000,000 in 2050 yields an annual return of only 13.5%. That is not sufficient to compensate for the risk given the S&amp;P 500 produced an averaged total annual return of 12.2% over the past 30 years. Cryptoassets are riskier than equities and should produce a significantly higher return.</p><p>Chris Burniske’s excellent<a href="https://medium.com/@cburniske/cryptoasset-valuations-ac83479ffca7"> Cryptoasset Valuations</a> suggest using a discount rate of 40% over a shorter investment horizon of 10 years. Using a discount rate of 40%, it is only rational to purchase a bitcoin today at $14,000 if one expects it to be worth at least $405,000 in ten years.</p><h3>Market Size</h3><p>The potential market for Bitcoin as a store of value is limited to public reserves and private financial wealth.</p><h3>Public Reserves</h3><p>According to the <a href="http://www.imf.org/external/pubs/ft/ar/2017/eng/assets/ar17-appI.pdf">IMF</a>, global international reserves were $12.7 tln in 2017. From 2009 to 2017, reserves grew at 5.4% annually and 10% were non-fiat currency, mostly gold. Using these as assumptions, total non-fiat global international reserves in ten years will be $2.2 tln.</p><p>I think it is reasonable not to expect central banks to dump their gold stock to purchase Bitcoin. So, an extremely optimistic expectation for Bitcoin in ten years is to capture all growth plus the non-gold portion, resulting in 50% of the non-fiat reserves or $1.1 tln.</p><h3>Private Wealth</h3><p>According to <a href="https://www.credit-suisse.com/corporate/en/research/research-institute/global-wealth-report.html?WT.i_short-url=%2Fgwr&amp;WT.i_target-url=%2Fcorporate%2Fen%2Fresearch%2Fresearch-institute%2Fglobal-wealth-report.html">Credit Suisse’s 2017 Global Wealth Report</a>, global wealth was $280 tln in 2017. From 2000 to 2017, global wealth grew at 5.5% annually and 62% were held as financial wealth. Using these as assumptions, total global financial wealth in ten years will be $297.4 tln.</p><p>According to <a href="http://www.academyfinance.ch/gri/companies/CPMGroup.pdf">CPM Group</a>, Gold accounted for ~2.5% of global assets in 1980 and less than 0.5% in the 2000’s before rising to just under ~0.8% post-GFC.</p><p>An extremely optimistic expectation would be for Bitcoin in ten years is to capture the same portion of global financial assets as gold did in 1980 or 2.5% or $7.4 tln. A higher percentage would likely require a cataclysmic financial crisis.</p><p>An extremely optimistic expectation for the total Bitcoin market in ten years is $8.5 tln.</p><h3>Velocity</h3><p>The velocity of Bitcoin is currently around 6.5 (see Chris Burniske’s post again) vs. 5.5 for M1 and 1.5 for M2. An extremely optimistic expectation for Bitcoin velocity in ten years is 1.5.</p><p><strong>Money Supply</strong></p><p>The number of bitcoins in circulations in ten years will likely be at least 20 million with some amount lost. A recent <a href="http://amp.timeinc.net/fortune/2017/11/25/lost-bitcoins">analysis</a> showed between 2.78 and 3.79 million bitcoins are lost. An optimistic expectation for the supply of Bitcoin in ten years to be 16.21 million (20.0–3.79).</p><h3>FV and Current Fair Value</h3><p>Given the above inputs and using the <a href="https://en.wikipedia.org/wiki/Equation_of_exchange">equation of exchange</a>, an optimistic expectation for the future value of a bitcoin in ten years is $350,000.</p><pre>P * Q = M * V<br></pre><pre>M = P * Q / V<br></pre><pre>M = $8.5 tln / 1.5<br></pre><pre>M = $5.67 tln<br></pre><pre>BTC / MS = $5.67 tln<br></pre><pre>BTC = $5.67 tln / 16.21 mln<br></pre><pre>BTC = $349,578.45</pre><p>Discounting $350,000 back to today at 40% results in current fair value of $12,100; suggesting Bitcoin at $14,000 is ~15% overvalued.</p><h3>Conclusion</h3><p>I believe the previous expectations are possible but not realistic. More realistic expectations are:</p><ul><li>1% of the global financial wealth. Gold is not difficult to purchase or hold. In developing countries, gold is probably the most accessible asset class. The creation of a better non-inflationary asset class will not create additional demand.</li><li>25% of global international reserves. There may be some forward-looking central bankers, but governments have the least incentives to buy bitcoin.</li><li>A velocity of 3.5. The average velocity of M1 and M2.</li><li>A discount rate of 50%. I believe it is more likely a new cryptoasset will solve Bitcoin’s problems and replace it. Cryptoasset evolution requires changing the protocol thru hard forks or a Darwinian evolution of soft forks. The recent <a href="https://cointelegraph.com/news/forks-in-the-road-2017-bitcoin-forks">history</a> of proposed Bitcoin hard forks is not encouraging and the incentives suggest inventors of better mousetraps are unlikely to give them away thru soft forks (see: <a href="https://medium.com/@FEhrsam/accelerating-evolution-through-forking-6b0bba85a2ba">Fred Ersham: Accelerating Evolution Through Forking</a>).</li></ul><p>Based on these assumptions, I believe the current fair price of Bitcoin is just under $1,100. I am sure many who read this will strongly disagree. I appreciate all feedback and please show your math.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af6a83f4cb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous User Inputs for React]]></title>
            <link>https://medium.com/@kyle.w.stewart/asynchronous-user-inputs-for-react-3ec8aae6a36a?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec8aae6a36a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Sun, 07 Jan 2018 14:21:03 GMT</pubDate>
            <atom:updated>2018-01-07T14:21:03.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Give your code a timeout.</p><p>A responsive client UX requires putting breaks on your code. Asynchronous design patterns are commonly used for APIs, but that often only solves half your problems. Consider an example where you want a user to verify their password before deleting their account. You could build a form like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3beXcB8YRGKw_cT69d5D1A.png" /></figure><p>The user must (1) enter their password, (2) hit submit, (3) wait for the password to be verified and then (4) delete the account.</p><p>This requires making the third step asynchronous. This is done by attaching an API call to the submit button (checkPassword) and making the API call asynchronous. This can be done with async / await and the component in react would look something like this (the code that displays the error message is not included):</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Container, Message, Form } from &#39;semantic-ui-react&#39;;<br>import axios from axios;</pre><pre>class <strong>DeleteAccount</strong> extends Component {<br> state = { password: &#39;&#39;, isValid: false, isFetch: false };</pre><pre> // API return true or false<br> checkPassword = <strong>async</strong> (password) =&gt; {<br>  this.setState({ isFetch: true });<br>  const isValid = <strong>await</strong> axios.post(<br>    `http://someurl/user/${this.props.id}`, <br>    { password },<br>   );<br>  this.setState({ isValid: isValid.data, isFetch: false });<br> }</pre><pre> handleDelete = () =&gt; {<br>   ...<br> }<br>  <br> render() {<br>  return (<br>   &lt;<strong>Container</strong>&gt;<br>    &lt;<strong>Message</strong> attached content=&quot;Delete Account&quot; /&gt;<br>     &lt;<strong>Form</strong> className=&quot;attached fluid segment&quot;&gt;<br>      &lt;<strong>Form</strong>.Group inline&gt;<br>       &lt;<strong>Form.Input</strong><br>        placeholder=&quot;Password&quot;<br>        type=&quot;Password&quot;<br>        value={this.state.password}<br>        onChange{(e, { val }) =&gt; this.setState({ password: val })}<br>        /&gt;<br>       &lt;<strong>Form.Button</strong><br>        content=&quot;Submit&quot;<br>        onClick={this.checkPassword(this.state.password}<br>        /&gt;<br>       &lt;<strong>Form.Button<br>        </strong>content=&quot;Delete Account&quot;<br>        loading={this.state.isFetch}<br>        disabled={!this.state.isValid}<br>        onClick={this.handleDelete}<br>        /&gt;<br>      &lt;/<strong>Form.Group</strong>&gt;<br>     &lt;/<strong>Form</strong>&gt;<br>   &lt;/<strong>Container</strong>&gt;<br>);<br>  }<br>}</pre><pre>export default DeleteAccount;</pre><p>This is fine, but asking a user to type their password and press a submit button is so 2010. We could clean this up by calling checkPassword as the user types. This is done by adding checkPassword to the Form.Input onChange callback.</p><pre>...</pre><pre>&lt;<strong>Form.Input</strong><br> placeholder=&quot;Password&quot;<br> type=&quot;Password&quot;<br> value={this.state.password}<br> onChange{(e, { val }) =&gt; {<br>  this.setState({ password: val };<br>  this.checkPassword(val);<br>}<br> /&gt;</pre><pre>....</pre><p>This would feel more 2018, but the result are suboptimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*EoJVDX1YhL-B0BhVMmZo2Q.gif" /></figure><p>We really want to call checkPassword once the user has stopped typing. Unfortunately, their is no stopped typing trigger. We can, however, assume a user has stopped if they started typing and then did typed for some specific amount of time. This can be done with just a few lines of code.</p><p>First we need to set an initial timer equal to null. Next we need to add a setTimer function that we will add to the Input call back.</p><pre>...</pre><pre>componentDidMount() {<br>    this.timer = null;<br>  }</pre><pre>...</pre><pre>setTimer = val =&gt; {<br>  clearTimeout(this.timer);<br>  this.timer = setTimeout(() =&gt; {<br>        this.checkPassword(val);<br>      }, 500);</pre><pre>...</pre><pre>&lt;<strong>Form.Input</strong><br> placeholder=&quot;Password&quot;<br> type=&quot;Password&quot;<br> value={this.state.password}<br> onChange{(e, { val }) =&gt; {<br>  this.setState({ password: val };<br> <strong> this.setTimer(val)</strong>;<br>}<br> /&gt;</pre><pre>...</pre><p>The setTimer function is called each time the user types. It calls <a href="https://developer.mozilla.org/en-US/docs/Talk:DOM/window.setTimeout">setTimeout</a>() which accepts two arguments. A callback (in our case, checkPassword) and a length of time in milliseconds.</p><p>So what exactly is going on here.</p><ul><li>Each time the user types it triggers onChange (in Form.Input) which calls setTimer.</li><li>#setTimer clears any previous Timeouts and sets a new Timeout for half a second.</li><li>The Timeout will only end and call checkPassword once a users has not typed again in a half a second.</li></ul><p>Which results in this behavior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*RsPJ-oo8iWtBIno9qN1-rw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec8aae6a36a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from Rails to Python]]></title>
            <link>https://medium.com/@kyle.w.stewart/moving-from-rails-to-python-f59d94581ba8?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/f59d94581ba8</guid>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Wed, 03 Jan 2018 14:41:02 GMT</pubDate>
            <atom:updated>2018-01-03T14:41:02.541Z</atom:updated>
            <content:encoded><![CDATA[<p>Part Three: Adding Models</p><p>In Part One and Two of this series of blogs I showed how to set up rails like Controllers for a Flask based Python web server and how to install MongoDB. In this blog I will go thru how to set Rails like Models. All the code can be found in this <a href="https://github.com/kylewstewart/rails-to-python-models">repo</a>.</p><ol><li>Connect the database to your app. Set up a config file to hold database configurations.</li></ol><pre>&gt; config<br>  - database_config.py</pre><pre>development = {<br>    &#39;host&#39;: &#39;localhost&#39;,<br>    &#39;port&#39;: 27017,<br>    &#39;db_name&#39;: &#39;Your Database Name&#39;,<br>}</pre><p>2. Create a models folder and an app_model.py file. This contains the database functionality all other models will inherit.</p><pre>&gt; models<br>  - app_model.py</pre><pre>from pymongo import MongoClient<br>from config import database</pre><pre>class AppModel():</pre><pre>  DB = MongoClient(database[&#39;host&#39;], database[&#39;port&#39;])    <br>                   [database[&#39;db_name&#39;]]</pre><pre>    @classmethod<br>    def all(cls):<br>        db = cls.DB<br>        collection = db[f&quot;{cls.COLLECTION}&quot;]<br>        return [doc for doc in collection.find()]</pre><pre>    @classmethod<br>    def find_one_by_id(cls, id):<br>        db = cls.DB<br>        collection = db[f&quot;{cls.COLLECTION}&quot;]<br>        doc = collection.find_one({&quot;id&quot;: id})<br>        if doc is None:<br>            return None<br>        else:<br>            return cls(**doc)</pre><pre>    @classmethod<br>    def update(cls, id, **data):<br>        db = cls.DB<br>        collection = db[f&quot;{cls.COLLECTION}&quot;]<br>        result = collection.update_one({&#39;id&#39;: id}, {&#39;$set&#39;: data})<br>        if result.acknowledged:<br>            return cls.find_one_by_id(id)<br>        else:<br>            return None</pre><pre>    @classmethod<br>    def delete(cls, id):<br>        db = cls.DB<br>        collection = db[f&quot;{cls.COLLECTION}&quot;]<br>        result = collection.delete_one({&#39;id&#39;: id})<br>        return result.acknowledged</pre><pre>    def save(self):<br>        db = self.DB<br>        collection = db[f&quot;{self.COLLECTION}&quot;]<br>        doc = {k: v for (k, v) in self.__dict__.items()}<br>        doc[&#39;id&#39;] = self.get_id_and_inc()<br>        result = collection.insert_one(doc)<br>        if result.acknowledged:<br>            self.id = doc[&#39;id&#39;]<br>            return doc<br>        else:<br>            return None</pre><pre>   def get_id_and_inc(self):<br># Collection name (COUNT) and increment value (1) are hardcoded<br>        db = self.DB<br>        counters = db.counters<br>        collection = self.COLLECTION<br>        counter = counters.find_one_and_update(<br>            {&quot;collection&quot;: f&quot;{collection}&quot;},<br>            {&#39;$inc&#39;: {&#39;id_count&#39;: 1}, &#39;$set&#39;: {&#39;done&#39;: True}}<br>        )<br>        return counter[&#39;id_count&#39;]</pre><pre>  def find_one(self):<br>        db = self.DB<br>        collection = db[f&quot;{self.COLLECTION}&quot;]<br>        if self.id is None:<br>            doc = {<br>              k: v for (k, v) in self.__dict__.items() if k != &quot;id&quot;<br>            }<br>            return collection.find_one(doc)<br>        else:<br>            return collection.find_one({&#39;id&#39;: self.id})<br></pre><p>3. Create model files. Here is the User Model file. Import the app_model file and pass its methods the model by placing the AppModel class in the argument.</p><pre>from models.app_model import AppModel</pre><pre>class User(AppModel):</pre><pre>COLLECTION = &#39;users&#39;</pre><pre>def __init__(self, id, username, password, **kwargs):<br>        self.id = id<br>        self.username = username<br>        self.password = password</pre><p>4. Hard code the database collection and set up the __init__ method which will act as my schema.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f59d94581ba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from Rails to Python]]></title>
            <link>https://medium.com/@kyle.w.stewart/moving-from-rails-to-python-f0cca785ffea?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0cca785ffea</guid>
            <category><![CDATA[python-flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Tue, 19 Dec 2017 23:37:03 GMT</pubDate>
            <atom:updated>2017-12-19T23:38:05.625Z</atom:updated>
            <content:encoded><![CDATA[<p>Part Two: Installing PyMongo</p><p>In the <a href="https://medium.com/@kyle.w.stewart/moving-from-rails-to-python-28060fb2e8ac">first blog</a> in this series, I showed how I used Flask to receive an HTTP request, route that request to Restful routes in a Controller and respond. The next step will be to add a Models which will interact with a database. I want to start that process with adding a database. I decided to work with MongoDB as my previous experience has been with SQL databases. Using MongoDB with Flask , however, was not as straight forward as I had hoped.</p><p>The first problem I had was with the Flask documentation. It recommends using MongoKit. MongoKit is a PyMongo, (the MongoDB official library) wrapper that makes it play nicer with Flask.</p><p><strong>Do Not</strong> use MongoKit. It is no longer maintained. Stay with just PyMongo, you do not need a wrapper.</p><p>The second problem I has was installing MongoDB on macOS High Sierra. The installation guide for MongoDB recommends the following steps to install with HomeBrew:</p><p>Update Homebrew’s package:</p><pre>$ brew update</pre><p>Install MongoDB</p><pre>$ brew install mongodb</pre><p>Create the data directory</p><pre>$ mkdir -p /data/db</pre><p><strong>DO NOT</strong> put it here if your are on High Sierra and probably Sierra. MongoDB will not start. It throw the following error:</p><pre>IllegalOperation: Attempted to create a lock file on a read-only directory: /data/db</pre><p>I am sure it is possible to set the permissions correctly for this file in High Sierra, but I spent hours looking for the answer. I instead put in my ~/Development folder and all the permission issues went away.</p><pre>mkdir ~/Development/data/db</pre><p>To start MongoDB now requires:</p><pre>mongod --dbpath ~/Development/data/db</pre><p>I added an alias to my ~/.bash_prolife to make life easier. Go to:</p><pre>$ nano ~/.bash_profile</pre><p>And add:</p><pre>alias ms=&quot;mongod --dbpath ~/Development/data/db&quot;</pre><p>Restart your terminal and no you can start MongoDB with:</p><pre>$ ms</pre><p>In the next blog, I will add Models and some Active Record type functionality with a Model superclass and a some classmethods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0cca785ffea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from Rails to Python]]></title>
            <link>https://medium.com/@kyle.w.stewart/moving-from-rails-to-python-28060fb2e8ac?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/28060fb2e8ac</guid>
            <category><![CDATA[python-flask]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Tue, 19 Dec 2017 17:56:11 GMT</pubDate>
            <atom:updated>2018-09-03T23:59:30.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Part One: Controllers</p><p>Rails is a mature opinionated MVC framework. It is a relatively painless option for setting up web APIs with relational databases. For many use cases, Rails and Ruby (the language Rails is built on) get the job done. Ruby, however, is not the programing language of choice for big data applications and many of the libraries required to make these application work do not exist in Ruby.</p><p>A more popular language for big data application is Python. I recently decided to upgrade my existing Python skills to Python 3 and learn a Python based web framework to expanded the type of projects I could develop.</p><p>I did some research and decided my first project should be with Flask, a micro framework that would allow me to learn as I built much of the functionality myself. This series of blogs will go thru the steps I took.</p><p>If you want to get up to speed on Python 3, I highly recommend<a href="https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g"> Corey Schafer’s YouTube Channel</a>.</p><h3>Flask</h3><p><a href="http://flask.pocoo.org/">Flask</a> is a micro framework that I am using strictly to receive and respond to HTTP requests. Flask’s documentation is good and suggest reading the<a href="http://flask.pocoo.org/docs/0.12/quickstart/"> quick start </a>tutorial before going any further.</p><h3>Routes</h3><p>The Repo for the code in this blog is <a href="https://github.com/kylewstewart/rails-to-python-routes">here</a>.</p><p>The project folder is rails-to-python-routes and the first for the stop for this application is the app.py file:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py<br></strong></pre><pre>from flask import Flask, request, jsonify<br>from http_method_override import HTTPMethodOverride<br>from dispatchers import controllers</pre><pre>app = Flask(__name__)<br>app.wsgi_app = HTTPMethodOverride(app.wsgi_app)</pre><pre>version = &quot;api/v1&quot;</pre><pre><a href="http://twitter.com/app">@app</a>.route(<br>    f&quot;/{version}/&lt;path&gt;&quot;,<br>    defaults={&#39;id&#39;: None},<br>    methods=[&#39;GET&#39;, &#39;POST&#39;]<br>)<br><a href="http://twitter.com/app">@app</a>.route(<br>    f&quot;/{version}/&lt;path&gt;/&lt;int:id&gt;&quot;,<br>    methods=[&#39;GET&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;]<br>)<br>def route(**params):<br>    try:<br>        controller = controllers[params[&#39;path&#39;]](<br>            params.get(&#39;id&#39;),<br>            request.get_json(silent=True)<br>        )<br>    except Exception as e:<br>        return (&quot;Bad Path&quot;, 404)</pre><pre>    method = getattr(controller, request.method.lower())<br>    return jsonify(method())</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>At the top of the file, I import Flask which I installed in my virtual environment like this:</p><pre>(venv) [<strong>10:51:30</strong>] (master) rails-to-python-routes</pre><pre>// $ pip install flak</pre><p>The next two imports are my own files which I will later.</p><p>The next two lines of code sets the flask <a href="http://flask.pocoo.org/docs/0.12/api/#application-object">application object</a> and middleware to allow for restful HTTP verbs:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...<br></strong></pre><pre>app = Flask(__name__)<br>app.wsgi_app = HTTPMethodOverride(app.wsgi_app)<br></pre><pre><strong>...</strong></pre><p>The <a href="http://flask.pocoo.org/docs/0.12/patterns/methodoverrides/#adding-http-method-overrides">HTTPMethodOverride</a> function comes straight from the Flask documentation and I keep it in separate file and imported it at the top of the <em>app.py</em> file.</p><pre><strong>&gt; rails-to-python-routes<br>  - http_method_override.py<br></strong></pre><pre>class HTTPMethodOverride(object):<br>    allowed_methods = frozenset([<br>        &#39;GET&#39;,<br>        &#39;HEAD&#39;,<br>        &#39;POST&#39;,<br>        &#39;DELETE&#39;,<br>        &#39;PUT&#39;,<br>        &#39;PATCH&#39;,<br>        &#39;OPTIONS&#39;<br>    ])<br>    bodyless_methods = frozenset([&#39;GET&#39;, &#39;HEAD&#39;, &#39;OPTIONS&#39;, &#39;DELETE&#39;])</pre><pre>def __init__(self, app):<br>        self.app = app</pre><pre>def __call__(self, environ, start_response):<br>        method = environ.get(&#39;HTTP_X_HTTP_METHOD_OVERRIDE&#39;,<br>                 &#39;&#39;).upper()<br>        if method in self.allowed_methods:<br>            method = method.encode(&#39;ascii&#39;, &#39;replace&#39;)<br>            environ[&#39;REQUEST_METHOD&#39;] = method<br>        if method in self.bodyless_methods:<br>            environ[&#39;CONTENT_LENGTH&#39;] = &#39;0&#39;<br>        return self.app(environ, start_response)</pre><p>The last two lines of code:</p><pre>&gt;<strong> rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...<br></strong></pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>Run the Flask app when<em> app.py</em> is run. Adding debug=True, reloads the Flask app every time you save a change in the project folder.</p><p>The next block of code defines which HTTP requests to accept:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...<br></strong></pre><pre>version = &quot;api/v1&quot;</pre><pre><a href="http://twitter.com/app">@app</a>.route(<br>    f&quot;/{version}/&lt;path&gt;&quot;,<br>    defaults={&#39;id&#39;: None},<br>    methods=[&#39;GET&#39;, &#39;POST&#39;]<br>)<br><a href="http://twitter.com/app">@app</a>.route(<br>    f&quot;/{version}/&lt;path&gt;/&lt;int:id&gt;&quot;,<br>    methods=[&#39;GET&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;]<br>)</pre><pre><strong>...</strong></pre><p>I abstracted this code from the start. I could have written separate block of code for each route. The users route, for example, would have looked like this:</p><pre>@app.route(&#39;/api/v1/users&#39;, defaults={&#39;id&#39;: None}, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>@app.route(&#39;/api/v1/users/&lt;int:id&gt;&#39;, methods=[&#39;GET&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;])</pre><p>The &lt;&gt; notation converts part of the URL to a variable which Flask passes to the function wrapped by the <em>@app.route</em> decorator. Flask refers to this argument as args, but I called it params. You can call it dog, but it must be start with ** in the function argument.</p><p>Here is the <em>route</em> function:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...</strong><br></pre><pre>def route(**params):<br>    try:<br>        controller = controllers[params[&#39;path&#39;]](<br>            params.get(&#39;id&#39;),<br>            request.get_json(silent=True)<br>        )<br>    except Exception as e:<br>        return (&quot;Bad Path&quot;, 404)</pre><pre>method = getattr(controller, request.method.lower())<br>    return jsonify(method())<br></pre><pre>.<strong>..</strong></pre><p>The function receives:</p><ul><li>A dict called <em>params</em> which includes the keys: <em>‘path’</em> and <em>‘id’.</em></li><li>It has access to the global Flask object called <a href="http://flask.pocoo.org/docs/0.12/api/#incoming-request-data"><em>request</em></a><em>. </em>I want to pull the json data from the HTTP request body, which I get by calling <em>request.get_json()</em>. I add the argument, silent=True, so it won’t throw and error if there is no data.</li></ul><p>For each HTTP request, I need to determine which controller and which method I need.</p><p>I get the controller with a dict where the keys equal to the <em>path</em> names and values equal to the controller class I want to instantiate (these are known as first class function in python). I put this dict in <em>dispatchers.py,</em> which looks like this:</p><pre><strong>&gt; rails-to-python-routes<br>  - dispatchers.py<br></strong></pre><pre>from controllers import UsersController</pre><pre>controllers = {<br>    &#39;users&#39;: UsersController<br>}</pre><p>I get the method with a controller super class whose method names are equal the HTTP verbs which call the route controller methods which will be named for the restful routes (I am not adding routes for New or Edit as I am only going to use this as an API).</p><pre><strong>&gt; rails-to-python-routes<br>  &gt; controllers<br>    - app_controller.py</strong></pre><pre><br>class AppController():<br>    def get(self):<br>        if self.id is None:<br>            return self.index()<br>        else:<br>            return self.show()</pre><pre>    def post(self):<br>        return self.create()</pre><pre>    def put(self):<br>        return self.update()</pre><pre>    def patch(self):<br>        return self.update()</pre><pre>    def delete(self):<br>        return self.destroy()</pre><p>I then need to import AppControl and pass it to the individual controllers.</p><pre><strong>&gt; rails-to-python-routes<br>  &gt; controllers<br>    - users_controller.py</strong></pre><pre>from controllers.app_controller import AppController</pre><pre>class UsersController(AppController):<br>    def __init__(self, id, data):<br>        self.id = id<br>        self.data = data</pre><pre>    def index(self):<br>        return &quot;User#Index&quot;</pre><pre>    def create(self):<br>        return &quot;User#Create&quot;</pre><pre>    def show(self):<br>        return &quot;User#Show&quot;</pre><pre>    def update(self):<br>        return &quot;User#Update&quot;</pre><pre>    def destroy(self):<br>        return &quot;User#Destroy&quot;</pre><h3>An Example</h3><p><strong>Step 1</strong>: The server receives an HTTP GET request at:</p><pre>http://127.0.0.1:5000/api/v1/users</pre><p><strong>Step 2</strong>: The request will be caught by:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...<br></strong></pre><pre><a href="http://twitter.com/app">@app</a>.route(<br>    f&quot;/{version}/&lt;path&gt;&quot;,<br>    defaults={&#39;id&#39;: None},<br>    methods=[&#39;GET&#39;, &#39;POST&#39;]<br>)</pre><pre><strong>...</strong></pre><p>Which calls <em>app.py#routes</em>:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...</strong><br></pre><pre>def route(**params):<br>    try:<br>        controller = controllers[params[&#39;path&#39;]](<br>            params.get(&#39;id&#39;),<br>            request.get_json(silent=True)<br>        )<br>    except Exception as e:<br>        return (&quot;Bad Path&quot;, 404)</pre><pre>method = getattr(controller, request.method.lower())<br>    return jsonify(method())</pre><pre><strong>...</strong></pre><p>Because, params[‘path’] = ‘users’</p><p><em>controller</em> = a new instance of the class <em>UserController </em>with</p><ul><li>params[‘id’] = None</li><li>requset.get_json(sillent=True) = None</li></ul><p><strong>Step 3</strong>: The last line of <em>app.py#route </em>determines which <em>UserController</em> method to<em> </em>call. The is done with the getattr() functions which allows me to pass class name and methods as arguemensts:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...</strong></pre><pre><br>method = getattr(controller, request.method.lower())<br>    return jsonify(method())</pre><pre><strong>...</strong></pre><p>So, calling method() calls the inherited method <em>get</em> on our instance of <em>UsersClass</em> and pass the arguments (id=none, data=none):</p><pre><strong>&gt; rails-to-python-routes<br>  &gt; controllers<br>    - app_controller.py</strong></pre><pre>...</pre><pre><br>def get(self):<br>        if self.id is None:<br>            return self.index()<br>        else:<br>            return self.show()</pre><pre><strong>...</strong></pre><p>Which, calls <em>self.index()</em> because id is None.</p><pre><strong>&gt; rails-to-python-routes<br>  &gt; controllers<br>    - users_controller.py</strong></pre><pre><strong>...</strong><br></pre><pre>def index(self):<br>        return &quot;User#Index&quot;</pre><pre><strong>...</strong></pre><p>Which return “User#Index” to:</p><pre><strong>&gt; rails-to-python-routes<br>  - app.py</strong></pre><pre><strong>...</strong></pre><pre>method = getattr(controller, request.method.lower())<br>    return jsonify(method())</pre><pre><strong>...</strong></pre><p>In my <a href="https://medium.com/@kyle.w.stewart/moving-from-rails-to-python-f0cca785ffea">next blog</a> in this series, I will start to add a database. I am going with MongoDB and will walk thru some issue I had with installing and getting MongoDB to run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28060fb2e8ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React-Router, Redux and User Auth]]></title>
            <link>https://medium.com/@kyle.w.stewart/react-router-redux-and-user-auth-856d09cc8fa?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/856d09cc8fa</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-router-4]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Mon, 04 Dec 2017 19:59:03 GMT</pubDate>
            <atom:updated>2017-12-04T19:59:03.505Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently started a new project and had to build user authentication for the nth time and decided to write this blog to my future self to explain how I did it. The code is in these repos: <a href="https://github.com/kylewstewart/react-router-redux-user-auth-client">client</a> and <a href="https://github.com/kylewstewart/react-router-redux-user-auth-api">server</a>. This blog will focus on the client only. The server is a quick and dirty Rails API. I used JWT for the auth token and (WARNING) I did not include a secret, so it is not secure.</p><p>The client tech stack is React, Redux, React-Router (v4) and Semantic-UI-React.</p><p>The Redux implementation is straightforward. If you are new to Redux, I recommend Stephen Grider’s <a href="https://www.udemy.com/react-redux/">course on Coursea</a>.</p><p>I used the “standard” React/Redux file structure with the exception of my container file which I separated between main and header. I have yet to find a goto React/Redux file structure. I like this <a href="https://medium.com/front-end-hacking/the-three-pigs-how-to-structure-react-redux-application-67f5e3c68392">blog</a> on some options.</p><p>I kept controlled form state at the component level, Dan Abramov <a href="https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367">approves</a>. I also choose to not integrate React-Router into my Redux store, which I also believe is WDWD (what Dan would do). This part was a bit tricky.</p><p>React-Router V4 provides you with a history.push() that allows you to programmatically change routes. Check my HeaderMenuLogInComponent:</p><pre>//HeaderMenuLogInComponent.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { Menu } from &#39;semantic-ui-react&#39;;<br>i<strong>mport { withRouter } from &#39;react-router-dom&#39;;</strong><br>import { setActiveItem } from &#39;../actions&#39;;</pre><pre>const propTypes = {<br>  isAuth: PropTypes.bool.isRequired,<br>  activeItem: PropTypes.string.isRequired,<br>  history: PropTypes.shape({<br>    push: PropTypes.func.isRequired,<br>  }).isRequired,<br>  setActiveItem: PropTypes.func.isRequired,<br>};</pre><pre>class HeaderMenuLogInComponent extends Component {<br>  handleClick = (e, { name, path }) =&gt; {<br>    <strong>this.props.history.push(path);</strong><br>    this.props.setActiveItem(name);<br>  }</pre><pre>render() {<br>    const { isAuth, activeItem } = this.props;</pre><pre>return (<br>      &lt;Menu secondary&gt;<br>        &lt;Menu.Item<br>          name=&quot;new user&quot;<br>          path=&quot;/newuser&quot;<br>          active={!isAuth &amp;&amp; activeItem === &#39;new user&#39;}<br>          onClick={this.handleClick}<br>        /&gt;<br>        &lt;Menu.Item<br>          name=&quot;log in&quot;<br>          path=&quot;/login&quot;<br>          active={!isAuth &amp;&amp; activeItem === &#39;log in&#39;}<br>          onClick={this.handleClick}<br>        /&gt;<br>      &lt;/Menu&gt;<br>    );<br>  }<br>}</pre><pre>HeaderMenuLogInComponent.propTypes = propTypes;</pre><pre>const mapStateToProps = ({ auth, activeItem }) =&gt; ({ isAuth: auth.isAuth, activeItem });</pre><pre><strong>export default withRouter(connect(mapStateToProps, {<br>  setActiveItem,<br>})(HeaderMenuLogInComponent));</strong></pre><p>To get access to history.push(), I had to first:</p><pre>import { withRouter } from &#39;react-redux-dom&#39;;</pre><p>Next I had to wrap my redux connect function with the withRouter function.</p><pre>export default withRouter(connect(mapStateToProps, {<br>  setActiveItem,<br>})(HeaderMenuLogInComponent));</pre><p>This gives me access to this.props.history.push(), which is what I use to change routes when the user clicks on a menu item. However, history.push() has a <a href="https://reacttraining.com/react-router/web/guides/redux-integration">small problem</a> with Redux apps. To fix this issue, wrap the component where you define your routes withRouter. For me this was in my MainRoutes. My structure is index.js — App.js — MainRoutes.js. Index is where I put React-Router &lt;Browser Router&gt; and my Redux &lt;Provider&gt;.</p><pre>//index.js</pre><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import { BrowserRouter } from &#39;react-router-dom&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import &#39;semantic-ui-css/semantic.min.css&#39;;<br>import registerServiceWorker from &#39;./registerServiceWorker&#39;;</pre><pre><strong>import App from &#39;./App&#39;;</strong><br>import store from &#39;./store&#39;;</pre><pre>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;BrowserRouter&gt;<br>      <strong>&lt;App /&gt;</strong><br>    &lt;/BrowserRouter&gt;<br>  &lt;/Provider&gt;,<br>  document.getElementById(&#39;root&#39;),<br>);</pre><pre>registerServiceWorker();</pre><p>App.js is where a separated my Header container and Main container and set up my semantic Grids.</p><pre><strong>//App.js</strong></pre><pre>import React from &#39;react&#39;;<br>import { Container, Grid } from &#39;semantic-ui-react&#39;;</pre><pre><strong>import Main from &#39;./MainRoutes&#39;;</strong><br>import Header from &#39;./header/HeaderContainer&#39;;</pre><pre>const App = () =&gt; (<br>  &lt;Container fluid={false} text&gt;<br>    &lt;Grid columns={1}&gt;<br>      &lt;Grid.Row /&gt;<br>      &lt;Grid.Row&gt;<br>        &lt;Grid.Column width={16}&gt;<br>          &lt;Header /&gt;<br>        &lt;/Grid.Column&gt;<br>      &lt;/Grid.Row&gt;<br>      &lt;Grid.Row&gt;<br>        &lt;Grid.Column width={16}&gt;<br>          <strong>&lt;Main /&gt;</strong><br>        &lt;/Grid.Column&gt;<br>      &lt;/Grid.Row&gt;<br>    &lt;/Grid&gt;<br>  &lt;/Container&gt;<br>);</pre><pre>export default App;</pre><p>MainRoutes is where I defined my routes which I wrapped with withRouter() to ensure history.push() would work nicely with Redux.</p><pre>//MainRoutes.js</pre><pre>import React from &#39;react&#39;;<br><strong>import {</strong> Switch, Route, <strong>withRouter</strong> <strong>}</strong> <strong>from &#39;react-router-dom&#39;;</strong></pre><pre>import Home from &#39;./main/HomeContainer&#39;;<br>import LogIn from &#39;./main/LogInContainer&#39;;<br>import NewUser from &#39;./main/NewUserContainer&#39;;<br>import About from &#39;./main/AboutContainer&#39;;<br>import PageOne from &#39;./main/PageOneContainer&#39;;<br>import PageTwo from &#39;./main/PageTwoContainer&#39;;<br>import withAuth from &#39;./HOCs/withAuth&#39;;</pre><pre>const MainRoutes = () =&gt; (<br>  &lt;Switch&gt;<br>    &lt;Route path=&quot;/login&quot; component={LogIn} /&gt;<br>    &lt;Route path=&quot;/newuser&quot; component={NewUser} /&gt;<br>    &lt;Route exact path=&quot;/&quot; component={Home} /&gt;<br>    &lt;Route path=&quot;/About&quot; component={About} /&gt;<br>    &lt;Route path=&quot;/pageone&quot; component={PageOne} /&gt;<br>    &lt;Route path=&quot;/pagetwo&quot; component={PageTwo} /&gt;<br>    &lt;Route component={Home} /&gt;<br>  &lt;/Switch&gt;<br>);</pre><pre><strong>export default withRouter(withAuth(MainRoutes));</strong></pre><p>P.S., react-router-redux will give you the ability to change routes with Redux actions. I think that might makes user auth more complicated than in it needs to be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856d09cc8fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Velocity: The Cryptoasset Risk You Haven’t Considered]]></title>
            <link>https://medium.com/@kyle.w.stewart/velocity-the-cryptoasset-risk-you-havent-considered-de84b80b967d?source=rss-b036923f9276------2</link>
            <guid isPermaLink="false">https://medium.com/p/de84b80b967d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ico]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[cryptoasset]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Kyle Stewart]]></dc:creator>
            <pubDate>Tue, 28 Nov 2017 02:43:24 GMT</pubDate>
            <atom:updated>2017-11-28T02:43:24.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*N37H4UnMNJfVQz61BkQLdg.png" /><figcaption>A Wheelbarrow of Venezuelan Bolivar</figcaption></figure><p>In a recent blog, “<a href="https://medium.com/@kyle.w.stewart/do-not-sleep-on-tokens-abe25a707113">Do Not Sleep on Tokens</a>,” I laid out the investment case for digital tokens as an asset class. I argued that despite the silliness of some ICOs and the many unresolved issues including technical, governance, regulation, and valuation. A few will survive and become the next Facebook or Amazon.</p><p>My argument is that speculation fueling the cryptoasset bubble is providing the resources necessary to solve these issues. The bubble will eventually burst. But, the projects that add value will continue to grow, and their token’s value will eventually recover. This <a href="https://en.wikipedia.org/wiki/Hype_cycle">hype cycle</a> is the same that most emerging technologies follow (see the below chart of Amazon quarterly revenue in blue vs. stock price in red from 1997 to 2007).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEn6EhlkCLdbZxwgyKrOaQ.jpeg" /></figure><p>The dynamics of token economies, however, create a risk that was not obvious to me when I wrote the blog nor one that I have seen discussed.</p><h3>The Value of a Token</h3><p>Chris Burniske was a buy-side analyst at ARK Investments when it became the first public fund to invest in Bitcoin. While at ARK, he began developing a model to value cryptoassets. He has written about it in “<a href="https://www.amazon.com/Cryptoassets-Innovative-Investors-Bitcoin-Beyond/dp/1260026671/ref=tmm_hrd_swatch_0?_encoding=UTF8&amp;qid=1511796847&amp;sr=8-1">Cryptoassets: The Innovative Investor’s Guide to Bitcoin and Beyond</a>” and blogged about it <a href="https://medium.com/@cburniske/cryptoasset-valuations-ac83479ffca7">here</a>. The model uses the <a href="https://en.wikipedia.org/wiki/Equation_of_exchange">equation of exchange</a> to determine a token’s current utility value (CUV) at some future point and then discounts it back to arrive at a discounted current utility value (DCUV) measure of fair value.</p><p>The equation of exchange states that the money supply of an economy (M) times the velocity of money (V) is equal to the price (P) times the quantity (Q) of the goods produced in that economy.</p><p><strong>M * V = P *Q</strong></p><p>For a digital token, P*Q is the size of the market or economy the token supports and M is the supply of tokens. V requires some work. Take an example of a made-up token, widget coin (WDX), with the following details:</p><p>- In 10 years, WDX has the potential to capture 10% of the $50 billion a year widget market (PQ = $5 billion).</p><p>- The Widget project issues 500 million WDX at $0.05 (M = 500 million).</p><p>- The Widget protocol requires users to buy and sell widget with WDX but does not require them to hold WDX.</p><p>But what is the velocity of WDX? Chris and coinbase estimate the transactional velocity of Bitcoin in 2016 was 14 and Chris assumes a velocity of 20 in his models. Assuming a velocity of 20 for WDX, the value of WDX in 10 years is:</p><p><strong>M * V = ($P * Q) / WDX</strong></p><p><strong>WDX = ($P * Q) / M * V</strong></p><p><strong>WDX = ($5,000,000,000) / (500,000,000 * 20)= $0.50</strong></p><p>Assuming a discount rate of 50% yields a DCUV of $0.0087, well below the ICO price of $0.05. But a market fueled by irrational expectations is not only likely to pay a premium for an ICO but will continue to pay a speculative premium until the bubble burst. Post correction, the price of WDX intuitively should have a price floor equal to the current utility value. As any value less than the current utility value would provide a utility arbitrage (see below a hypothetical graph of WDX with CUV in blue, DCUV in grey and the market price in red).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpKdhnFThv1ZPYxw9lZqTA.jpeg" /></figure><p>This intuition, however, is probably wrong as it assumes velocity is constant</p><h3>Hyperinflation</h3><p>Hyperinflation is a spiral of increasing currency supply, leading to declining currency value, creating less demand for the native currency and increasing velocity. Because a rapid increase in money supply usually triggers the spiral, most concern regarding token inflation focuses on token supply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*wFZ5C_MgHeBBrqtGHP-I7w.jpeg" /><figcaption>The 100 Quintillion Hungarian Pengo Bank Note</figcaption></figure><p>Hyperinflation, however, is not caused by money supply but by a demand shock (which is typically a response to a rapid increase in money supply). The Axis occupation of Greece in 1941, for example, led to a sharp rise in prices and a demand shock unrelated to the money supply that was large enough to start 4 ½ years of Greek Drachma hyperinflation.</p><p>The bursting of a speculative bubble could create demand shock large enough to trigger hyperinflation for most tokens. The impact of a hyperinflationary episode could impair some token’s velocity as participants change behavior. Velocity could go to zero if participants substitute the native token with a more stable medium of exchange (i.e., Bitcoin, Ethereum, USD). Or, approach terminal velocity if participants no longer deem the token a suitable store of value. Both are extreme cases that may be more or less likely due to the underlying protocol. In the widget coin example, a demand shock would likely increase velocity as it is a medium of exchange. A doubling of WDX velocity from 20 to 40 would halve the terminal current utility value of WDX to $0.25.</p><h3>Protocol Velocity Risk</h3><p>A protocol implements of its token is likely the biggest contributor to a token’s velocity risk. A token that is a medium of exchange is probably at greater risk of increased velocity, an optional token is probably at greater substitution risk, and a token that users must own probably have the lowest velocity risk but have slower adoption.</p><p>At this point, I have more questions than answer regarding velocity risk. Future protocol designs or governance models may create incentives that mitigate velocity risk. Financial instruments may be created to hedge velocity. Or, velocity could become just a subjective valuation measure like P/E.</p><p>Regardless of how cryptoassets evolve, velocity risk is not going away.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de84b80b967d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>