<?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 dp on Medium]]></title>
        <description><![CDATA[Stories by dp on Medium]]></description>
        <link>https://medium.com/@pasdan?source=rss-ce240c2edc95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h4_dQH2tptKqFE6I18kIlA.jpeg</url>
            <title>Stories by dp on Medium</title>
            <link>https://medium.com/@pasdan?source=rss-ce240c2edc95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pasdan/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[Private Routes in React]]></title>
            <link>https://medium.com/@pasdan/private-routes-in-react-7b6ea186849c?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6ea186849c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-router]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 14:42:02 GMT</pubDate>
            <atom:updated>2023-10-27T14:42:12.177Z</atom:updated>
            <content:encoded><![CDATA[<p>Quick and simple post on protecting private routes in a React application.</p><h3>Private Layout Component</h3><blockquote>Outlet — renders the child route’s element</blockquote><pre>import _ from &#39;lodash&#39;;<br><br>import React from &#39;react&#39;;<br>import { Navigate, Outlet, useLocation } from &#39;react-router-dom&#39;;<br><br>function navigateToLogin(): JSX.Element {<br>    const location = useLocation();<br>    return (<br>        &lt;Navigate<br>            replace={true}<br>            to=&#39;/login&#39;<br>            state={{ from: `${location.pathname}${location.search}` }}<br>        /&gt;<br>    );<br>}<br><br>export function PrivateLayout(): JSX.Element {<br>    const token = localStorage.getItem(&#39;token&#39;);<br>    if (_.isNil(token)) {<br>        return navigateToLogin();<br>    }<br><br>    return &lt;Outlet /&gt;<br>};</pre><h3>Routes</h3><p>Add PrivateLayout to a parent Route . If a token exists the routes under our PrivateLayout will render otherwise they will be redirected to the login page.</p><pre>import { BrowserRouter as Router, Routes, Route } from &#39;react-router-dom&#39;;<br>import { PrivateLayout } from &#39;./PrivateLayout&#39;;<br><br>&lt;Router&gt;<br>  &lt;Routes&gt;<br>    ...<br>    &lt;Route path=&quot;/private/&quot; element={ &lt;PrivateLayout /&gt; }&gt;<br>      &lt;Route index={ true } element={ ... } /&gt;<br>    &lt;/Route&gt;<br>  &lt;/Routes&gt;<br>&lt;/Router&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DV27k4GTxtM9tSo9" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6ea186849c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an NFL Game Simulator — Python]]></title>
            <link>https://medium.com/@pasdan/nfl-game-simulator-84e988e249c0?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e988e249c0</guid>
            <category><![CDATA[simulator]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[monte-carlo-simulation]]></category>
            <category><![CDATA[sports-analytics]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 10:58:54 GMT</pubDate>
            <atom:updated>2023-11-28T20:37:42.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an NFL Game Simulator — Python</h3><p>Simulate an NFL Game by estimating win probabilities based on Points For (PF) and Points Against (PA) from the Regular Season.</p><p>The <a href="https://www.pro-football-reference.com/years/2022/games.htm">2022–23 Week-by-Week Results</a> can be downloaded from Pro Football Reference.</p><h3>Data</h3><pre>import pandas as pd<br><br>df = pd.read_csv(&#39;&lt;path to downloaded data&gt;&#39;)<br>regular_season = pd.concat(<br>    [<br>        df[[&#39;Week&#39;, &#39;Winner/tie&#39;, &#39;Pts&#39;, &#39;Pts.1&#39;]].rename(columns={<br>            &#39;Week&#39;: &#39;week&#39;,<br>            &#39;Winner/tie&#39;: &#39;team&#39;,<br>            &#39;Pts&#39;: &#39;pf&#39;,<br>            &#39;Pts.1&#39;: &#39;pa&#39;,<br>        }),<br>        df[[&#39;Week&#39;, &#39;Loser/tie&#39;, &#39;Pts&#39;, &#39;Pts.1&#39;]].rename(columns={<br>            &#39;Week&#39;: &#39;week&#39;,<br>            &#39;Loser/tie&#39;: &#39;team&#39;,<br>            &#39;Pts.1&#39;: &#39;pf&#39;,<br>            &#39;Pts&#39;: &#39;pa&#39;,<br>        }),<br>    ]<br>).sort_values([&#39;week&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*ZaNNZJAG6o8b1Hg9OO9M1A.png" /></figure><h3>Team Ratings</h3><pre>class Ratings:<br>    def __init__(self, regular_season):<br>        self._ratings = regular_season.groupby(&#39;team&#39;).mean()[[&#39;pf&#39;, &#39;pa&#39;]]<br>        self._avg_points = regular_season[&#39;pf&#39;].mean()<br>        self._std_points = regular_season[&#39;pf&#39;].std()<br><br>    @property<br>    def df(self):<br>        return self._ratings<br>    <br>    @property<br>    def std_points(self):<br>        return self._std_points<br><br>    @property<br>    def avg_points(self):<br>        return self._avg_points<br>    <br>    def get_team_data(self, team):<br>        return self._ratings.loc[team][[&#39;pf&#39;, &#39;pa&#39;]]<br><br><br>ratings = Ratings(regular_season)<br><br>### 2022-2023 -- mu: 21.882, std: 9.308<br>ratings.df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*INEfCXy8SNm95zjbpLwYHQ.png" /></figure><h3>Match</h3><pre><strong>formula:</strong> ( <em>Team 1 PF (OFF)</em> x <em>Team 2 PA (DEF)</em> ) /<em> AVG GLOBAL PF</em><br><br>-- Intuition<br>-- a good OFFENSE vs a bad DEFENSE -- HIGH!<br>-- a good OFFENSE vs a good DEFENSE -- OFFENSE should be punished<br>-- a bad OFFENSE vs a good DEFENSE -- OFFENSE should be punished<br><br>-- <em>AVG GLOBAL PF</em> is meant to normalize the value</pre><pre>from abc import ABC, abstractmethod, abstractproperty<br><br>class AbstractMatch(ABC):<br>    @abstractmethod<br>    def generate_score(self, t1: str, t2: str):<br>        pass<br><br>class Match(AbstractMatch):<br>    def __init__(self, ratings: Ratings):<br>        self._ratings = ratings<br><br>    def compute_expected_points(self, t1, t2):<br>        def compute_expected_points(off, opposing_def):<br>            return (off * opposing_def) / self._ratings.avg_points<br>        <br>        t1_pf, t1_pa = self._ratings.get_team_data(t1)<br>        t2_pf, t2_pa = self._ratings.get_team_data(t2)<br><br>        team1_mu = compute_expected_points(t1_pf, t2_pa)<br>        team2_mu = compute_expected_points(t2_pf, t1_pa)<br><br>        return team1_mu, team2_mu<br>    <br>    def generate_score(self, t1, t2):<br>        team1_mu, team2_mu = self.compute_expected_points(t1, t2)<br>        return (<br>            round(norm.ppf(random.random(), team1_mu, self._ratings.std_points), 2),<br>            round(norm.ppf(random.random(), team2_mu, self._ratings.std_points), 2),<br>        )<br><br>match = Match(ratings)</pre><h3>Plot Cumulative Distribution Functions (CDF)</h3><pre>import matplotlib.pyplot as plt<br><br>def plot_game_cdfs(t1: str, t2: str):<br>    team1_mu, team2_mu = match.compute_expected_points(t1, t2)<br><br>    vals_1 = norm.cdf(x, team1_mu, ratings.score_std)<br>    vals_2 = norm.cdf(x, team2_mu, ratings.score_std)<br>  <br>    _, ax = plt.subplots(1, 2, figsize=(20, 10))<br>  <br>    x = np.linspace(-20, 60, 10000)<br>  <br>    ax[0].set_title(t1)<br>    ax[0].plot(x, vals_1, alpha=.8)<br>    ax[0].plot(team1_mu, .5, color=&#39;red&#39;, label=&#39;μ&#39;, marker=&#39;o&#39;)<br>    ax[0].vlines([team1_mu+.1], 0, .5, colors=&#39;red&#39;, alpha=.3, linestyles=&#39;dashed&#39;)<br>    ax[0].legend()<br>  <br>    ax[1].set_title(t2)<br>    ax[1].plot(x, vals_2, alpha=.8)<br>    ax[1].plot(team2_mu, .5, color=&#39;red&#39;, label=&#39;μ&#39;, marker=&#39;o&#39;)<br>    ax[1].vlines([team2_mu+.1], 0, .5, colors=&#39;red&#39;, alpha=.3, linestyles=&#39;dashed&#39;)<br>    ax[1].legend()<br>  <br>    plt.show()<br><br>plot_game_cdfs(&#39;Kansas City Chiefs&#39;, &#39;Indianapolis Colts&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0IsQHdHA1XmBhOURrunGQ.png" /><figcaption>Kansas City vs Indianapolis Colts — CDFs</figcaption></figure><h3>Simulate Games</h3><pre>import random<br>import numpy as np<br>from scipy.stats import norm<br><br>class Simulator:<br>    def __init__(self, match: AbstractMatch, simulations = 10000):<br>        self._match = match<br>        self._simulations = simulations<br><br>    def simulate(self, t1, t2):<br>        scores = [<br>            self._match.generate_score(t1, t2)<br>            for _ in range(self._simulations)<br>        ]<br><br>        t1_wins = sum(t1_score &gt; t2_score for t1_score, t2_score in scores)<br>        t1_win_percentage = t1_wins / self._simulations<br><br>        return {<br>           &#39;t1&#39;: t1_win_percentage,<br>           &#39;t2&#39;: 1 - t1_win_percentage<br>        }<br><br>simulator = Simulator(<br>    match=match,<br>    simulations=10000<br>)<br><br>schedule = [<br>    (&#39;Kansas City Chiefs&#39;, &#39;Cincinnati Bengals&#39;),<br>    (&#39;Kansas City Chiefs&#39;, &#39;Indianapolis Colts&#39;)<br>]<br><br>print(&#39;-&#39; * 100)<br>for team1, team2 in schedule:<br>    observations = simulator.simulate(team1, team2)<br><br>    t1 = round(observations[&#39;t1&#39;] * 100, 2)<br>    t2 = round(observations[&#39;t2&#39;] * 100, 2)<br><br>    print(f&#39;{team1}: {t1}&#39;)<br>    print(f&#39;{team2}: {t2}&#39;)<br>    print(&#39;-&#39; * 100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*lb8DWqgCuFenDEL3zPur1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3T5hOMhhTAkNNy0_" /><figcaption>Photo by <a href="https://unsplash.com/@hencetheboom?utm_source=medium&amp;utm_medium=referral">Adrian Curiel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e988e249c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Foundations of Document Databases with MongoDB]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-foundations-of-document-databases-with-mongodb-e7116a7d3719?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7116a7d3719</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[notes]]></category>
            <category><![CDATA[pluralsight]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 10:11:25 GMT</pubDate>
            <atom:updated>2023-07-25T09:53:01.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Foundations of Document Databases with MongoDB</h3><p>Notes from watching ‘Foundations of Document Databases with MongoDB’ from Pluralsight. High level overview of MongoDB and sets the stage for advanced learning.</p><p><a href="https://www.pluralsight.com/courses/foundations-document-databases-mongodb">Foundations of Document Databases with MongoDB</a></p><h3>Introduction to MongoDB</h3><p>What is NoSQL? — <strong><em>Not ONLY SQL<br> — Definitely have structured query language but other things will be involved.<br> — Relationships are stored differently</em></strong></p><h4>CAP Theorem</h4><ul><li><strong><em>Consistency</em></strong><em> </em>— all nodes see the same data.</li><li><strong><em>Availability</em> </strong>— operational all the time.</li><li><strong><em>Partition Tolerance</em></strong> — the cluster must continue to work despite any number of communication breakdowns between nodes in the system.</li></ul><p>— <em>MongoDB </em><strong><em>priority</em></strong><em> is between </em><strong><em>C</em></strong><em> and </em><strong><em>P</em></strong><em>. Does not mean </em><strong><em>A</em></strong><em> is missing.</em></p><h4>Types of NoSQL Databases</h4><ul><li><em>Relational Database </em>— Columns/Rows</li><li><em>Document Database</em> — JSON</li><li><em>Key-Value Database</em> — Redis/DynamoDB</li><li><em>Wide-Column Stores</em></li><li><em>Graph Databases</em> — Node/Edges, Neo4j</li></ul><h4>Advantages of Document Database</h4><ul><li><strong><em>Intuitive Data Model </em></strong>— documents map to the object in your code. No need to do expensive joins or divide up your data into multiple tables.</li><li><strong><em>Flexible Schema</em></strong> — different documents with different fields. Not set rules on how you build your schema. JSON</li><li><strong><em>Query Data Anyway</em></strong> — feature rich (aggregation, text search, etc), supports indexing</li><li><strong><em>Distributed Scalable Database </em></strong>— Horizontal scaling. Documents are independent units which makes it easier to distribute them across multiple servers. Supports <a href="https://www.mongodb.com/docs/manual/sharding/">sharding</a>.</li></ul><h4>Why use MongoDB?</h4><ul><li>Open Source and Free — <a href="http://www.mongodb.com/">www.mongodb.com</a>, free access</li><li>Document Database</li><li>High Performance — supports indexes, different data models</li><li>High Availability / Horizontal Scalability</li><li>Multiple Storage Engine —<a href="https://www.mongodb.com/docs/manual/core/storage-engines/">In-Memory / WiredTier</a></li></ul><h4>SQL vs Mongo Terms</h4><ul><li>SQL — MQL (MongoDB Query Language)</li><li>SQL (Database) — MongoDB (Database)</li><li>SQL (Table) — MongoDB (Collection)</li><li>SQL (Row) — MongoDB (JSON/BSON Document)</li><li>SQL (Column) — MongoDB (Field)</li><li>SQL (Table Joins) — MongoDB ($lookup), <a href="https://en.wikipedia.org/wiki/Denormalization">denormalize</a></li><li>SQL (Primary Key) — MongoDB (Primary Key)</li><li>SQL (Transactions) — MongoDB (Transactions)</li></ul><pre>{<br>  &quot;_id&quot;: &quot;1&quot;,<br>  &quot;firstname&quot;: &quot;Ned&quot;,<br>  &quot;lastname&quot;: &quot;Flanders&quot;,<br>  &quot;address&quot;: {<br>    &quot;state&quot;: &quot;Illinois&quot;,<br>    ...<br>  },<br>  &quot;hobbies&quot;: [&quot;traveling&quot;, ...],<br>  ...<br>}</pre><p><strong><em>BSON </em></strong>— Binary encoding, supports String, Boolean, Number (int/float/long/etc), Array, Date, Raw Binary . Only Machine Readable.</p><h3>CRUD Operations: Creating Objects</h3><p>What are CRUD operations? — <strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate and <strong>D</strong>elete operations.</p><p><strong><em>C</em></strong> — db.&lt;coll&gt;.insertOne(), db.&lt;coll&gt;.insertMany() <br><strong><em>R</em></strong> — db.&lt;coll&gt;.find() <br><strong><em>U</em></strong> — db.&lt;coll&gt;.updateOne(), db.&lt;coll&gt;.updateMany() <br><strong><em>D</em></strong> — db.&lt;coll&gt;.deleteOne(), db.&lt;coll&gt;.deleteMany(), db.&lt;coll&gt;.remove()</p><h3>Create</h3><p>All write operations are <strong>atomic</strong> on the level of a single document.</p><blockquote>atomic: operations that run completely independently of any other processes</blockquote><p>MongoDB will auto generate _id field if left off document on insert. Must be unique.</p><h3>Read</h3><p>— 3 things to find query</p><h4>Query Operators</h4><ul><li>Comparison</li><li>Logical</li><li>Evaluation</li><li>Geospatial</li><li>Array</li><li>Bitwise</li></ul><h4>Query Projection</h4><p>— specifies the fields to return in the documents, 1=yes / 0=no</p><h4><a href="https://www.mongodb.com/docs/manual/reference/read-concern/">Read Concern</a></h4><p>— control the consistency and isolation properties of the data read from replica sets and replica set shards</p><ul><li>Local — default for primary</li><li>Available</li><li><strong><em>Majority</em></strong></li><li>Linearizable</li><li>Snapshot</li></ul><h4>Query Examples</h4><pre>{ &quot;_id&quot;: { $eq: ObjectId(&#39;64bd2f45cf389c86c72f146f&#39;) } }</pre><pre>{ &quot;runtime&quot;: { $gt: 11 } }</pre><pre>{ $and: [{ &quot;awards.win&quot;: 3 }, { &quot;runtime&quot;: { $gt: 80 } }] }</pre><pre>db.user.find(<br>  { &quot;age&quot;: { $gt: 20 } },<br>  { &quot;name&quot;: 1, &quot;age&quot;: 1, &quot;_id&quot;: 0 },<br>).limit(10).skip(10)</pre><ul><li>items: { $in: [&#39;...&#39;] } , $nin: [&#39;...&#39;] , $in: [ /^A/ ]</li><li>$lt , $lte , $gt , $gte</li><li>{ address: null } — null &amp; field missing, { $type: &quot;null&quot; }</li><li>{ address : { $exists: false } }</li><li>{ $type: &quot;double&quot; } — <a href="https://www.mongodb.com/docs/manual/reference/bson-types/">BSON types</a></li><li>array — $all , $size</li><li>array — $elemMatch — {skills: { $elemMatch: { name: &#39;flying&#39; } } }</li><li>array projections — $slice , $ , $elemMatch</li><li>{ skills: { $slice: 1 } } , additional parameters — [skip, take]</li><li>{ &quot;skills.$&quot;: 5 } , limits to the first n-elements</li><li>$elemMatch , display only the first element that matches</li></ul><h4>Text Search</h4><pre>## index fields name and skills<br>db.crew.createIndex({ &quot;name&quot;: &quot;text&quot;, &quot;skills&quot;: &quot;text&quot; })<br><br>## technical or Anna<br>db.crew.find(<br>  {<br>    $text: {$search : &quot;technical Anna&quot;}<br>  },<br>  ## projection<br>  {<br>    score: { $meta: &quot;textScore&quot; } ## search score<br>  }<br>)<br><br>## sort by search score<br>db.crew.find(<br>  {<br>    $text: {$search : &quot;technical Anna&quot;}<br>  },<br>).sort({ score: { $meta: &quot;textScore&quot; } })</pre><h3>Update and Delete</h3><h4><a href="https://www.mongodb.com/docs/manual/reference/write-concern/">Write Concern</a></h4><p>— Level of acknowledgement requested from MongoDB for write operations. Making sure your data is consistent.</p><ul><li>{ w: &lt;value&gt;, j: &lt;boolean&gt;, wtimeout: &lt;number&gt; }</li><li>w:1 — Acknowledgement from primary</li><li>w:0 — No Acknowledgement</li><li>w:(n) — Primary + (n-1) secondary</li><li>w: &quot;majority”— Acknowledgement from majority of voting members. Default write concern.</li><li>wtimeout: &lt;value&gt; — limit to prevent write operations from blocking indefinitely. wtimeout: 0 == infinite</li></ul><h4>Update</h4><p>All update operations are <strong>atomic</strong> on the level of a single document.</p><p>_id cannot be replaced with a different value. Instead, just create a new document and delete the old one.</p><p>$set — creates a new field if it does not already exist.</p><p>$upsert: true — mixes update functionality with insert. If something matches your document, it updates. Otherwise a new document will be created.</p><pre>db.movies.updateOne(<br>  { &quot;title&quot;: { $eq: &quot;The Old Crocodile&quot; } },<br>  { <br>    $set: { &quot;title&quot;: &quot;The New Crocodile&quot;, &quot;year&quot;: 2020 }<br>  }<br>)<br><br>db.movies.updateMany(<br>  { &quot;year&quot;: { $eq: 2020 } },<br>  { <br>    $set: { &quot;year&quot;: 2021 }<br>  },<br>  { upsert: true, w: &quot;majority&quot;, wtimeout: 1000 }<br>)<br><br>## all the fields on previous go away and are replaced with new<br>db.movies.replaceOne(<br>  { &quot;runtime&quot;: { $eq: 1122 } },<br>  { ... }<br>)</pre><h4>Delete</h4><p>All delete operations are <strong>atomic</strong> on the level of a single document. (each document is independent)</p><p>Delete does not drop indexes</p><pre>## only 1<br>db.movies.deleteOne({ &quot;runtime&quot;: { $eq: 25 } })<br><br>## all<br>db.movies.deleteMany({ &quot;runtime&quot;: { $eq: 25 } })<br><br>## 2nd parameter specifies single vs all<br>db.movies.remove({ &quot;runtime&quot;: { $eq: 35 } }, true)<br><br>## drop collection / all indexes / etc.<br>db.movies.drop()</pre><h4>Index</h4><pre>## 1 - asc, -1 - desc<br>db.people.createIndex({ &quot;name&quot;: 1, &quot;age&quot;: -1 })</pre><h3>SQL vs MongoDB</h3><ul><li>dynamic schema (JSON based), quickly get started</li><li>no foreign keys</li><li>no triggers, for audits — just insert into another collection</li><li>CAP Theorem (SQL — ACID)</li><li>Horizontal Scaling — add new nodes vs new hardware (Vertical Scaling)</li></ul><h4>Important Questions?</h4><ol><li>Is your data structured or unstructured? Do you know your schema?</li><li>What is your scalability strategy for infrastructure?</li><li>How comfortable are your developers with Object Relational Mapping?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i64w0BZgeIkWgE6x" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7116a7d3719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Behavioral Design Patterns]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-behavioral-design-patterns-126e3f64f621?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/126e3f64f621</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[pluralsight]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 10:46:17 GMT</pubDate>
            <atom:updated>2023-08-02T13:25:06.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Behavioral Design Patterns</h3><p>Notes from watching ‘Design Patterns in Python 3’ from Pluralsight. Goes through a few Behavioral Patterns.</p><p><a href="https://www.pluralsight.com/courses/python-3-design-patterns">Design Patterns in Python 3</a></p><h3>Strategy</h3><ul><li>Used to encapsulate algorithms (<em>shipping calculations)</em> and separating them from the context (<em>shipping calculator</em>) where they operate.</li></ul><pre>from abc import ABC, abstractmethod<br><br>class AbstractStrategy(ABC):<br>    @abstractmethod<br>    def calculate(self, order):<br>        pass<br><br>class ShippingCost:<br>    def __init__(self, strategy: AbstractStrategy):<br>        self._strategy = strategy<br><br>    def shipping_cost(self, order):<br>        return self._strategy.calculate(order)<br><br>class PostalServiceStrategy(AbstractStrategy):<br>    def calculate(self, order):<br>        return 4.00<br><br>class FedExServiceStrategy(AbstractStrategy):<br>    def calculate(self, order):<br>        return 4.00<br><br>## main<br>order = Order()<br><br>cost1 = ShippingCost(PostalServiceStrategy()).shipping_cost(order)<br>cost2 = ShippingCost(FedExServiceStrategy()).shipping_cost(order)<br><br><br>## using functions<br>class ShippingCost:<br>    def __init__(self, strategy: Callable[[..], ...]):<br>        self._strategy = strategy<br><br>    def shipping_cost(self, order):<br>        return self._strategy(order)<br><br>cost1 = ShippingCost(lambda order: 4.00).shipping_cost(order)</pre><ul><li>We can now test each algorithm in isolation. Test the outer code using mocks/stubs for the algorithms.</li><li>We can use this pattern to help eliminate long if / else if / else statements that could have been present within the ShippingCost class.</li></ul><h3>Command</h3><ul><li>Used to control the operation of an object. Encapsulate a request as an object. Separate command logic from the client.</li></ul><pre>from abc import ABC, abstractmethod, abstractproperty<br><br>class AbstractCommand(ABC):<br>    @abstractmethod<br>    def execute(self):<br>        pass<br><br>class AbstractOrderCommand(ABC):<br>    @abstractproperty<br>    def name(self):<br>        pass<br><br>    @abstractproperty<br>    def description(self):<br>        pass<br><br>class UpdateOrder(AbstractCommand, AbstractOrderCommand):<br>    name = &#39;UpdateQuantity&#39;<br>    description = &#39;UpdateQuantity number&#39;<br><br>    def __init__(self, args):<br>        self.qty = args[1]<br><br>    def execute(self):<br>        ...<br><br>class ShipOrder(AbstractCommand, AbstractOrderCommand):<br>    name = description = &#39;ShipOrder&#39;<br><br>    def execute(self):<br>        ...<br><br>class NoCommand(AbstractCommand):<br>    def execute(self):<br>        ...<br><br>## main<br><br>commands = {<br>    &#39;UpdateOrder&#39;: UpdateOrder,<br>    &#39;ShipOrder&#39;: ShipOrder,<br>    ...<br>}<br><br>def parse_command(args):<br>    command = commands.setdefault(args[0], NoCommand)<br>    return command(args)<br><br>command = parse_command(sys.argv[1:])<br>command.execute()</pre><h3>State</h3><ul><li>Operates in a context. Instead of having methods track state in the Context, use a class for each state. Context delegates to the state objects and clients only interface with the Context. (<em>similar to strategy</em>) Encapsulates state-specific behavior (<em>ie. empty vs paid for state</em>). Makes it easy to add new states. Eliminates long conditional statements. Use when an objects behavior depends on state.</li></ul><pre>from abc import ABC, abstractmethod<br><br>class AbstractState(ABC):<br>    def __init__(self, context):<br>        self._context = context<br>    <br>    @abstractmethod<br>    def add_item(self):<br>        pass<br><br>    @abstractmethod<br>    def remove_item(self):<br>        pass<br>    ...<br><br>class CheckOut(AbstractState):<br>    ...<br><br>class Empty(AbstractState):<br>    def add_item(self):<br>        self._context.items += 1<br>        <br>        ## updates state<br>        self._context.state = self._context.not_empty<br>    ...<br><br>class ShoppingCart:<br>    def __init__(self):<br>        self.empty = Empty(self)<br>        self.not_empty = NotEmpty(self)<br>        ...<br>        self.state = self.empty ## current state<br><br>    def add_item(self):<br>        ## ShoppingCart doesn&#39;t care what the current state is<br>        self.state.add_item()<br><br>    def remove_item(self):<br>        self.state.remove_item()<br>    ...<br><br>## main<br><br>cart = ShoppingCart()<br>cart.add_item()<br>cart.remove_item()<br>...</pre><h3>Observer (Dependents)</h3><ul><li>One area needs to know about another area. Create One-Many relationships. Subject— Notify-&gt; Observer. Separate the concerns of the subject and observer. Can easily add new observers. MVC Pattern — Model=Subject, View=Observer.</li></ul><pre>from abc import ABC, abstractmethod<br><br>class AbstractObserver(ABC):<br>    @abstractmethod<br>    def update(self, value):<br>        pass<br><br>class AbstractSubject(ABC):<br>    _observers: Set[AbstractObserver] = set()<br><br>    def attach(self, observer):<br>        self._observers |= {observer}<br><br>    def detach(self, observer):<br>        self._observers -= {observer}<br><br>    def notify(self, value=None):<br>        for observer in self._observers:<br>            if value is None:<br>                observer.update()<br>            else:<br>                observer.update(value)<br><br>class KPIs(AbstractSubject):<br>    def set_kpis(self, open_tickets, closed_tickets, new_tickets):<br>        ...<br>        self.notify()<br><br>class CurrentKPIs(AbstractObserver):<br>    def __init__(self, subject):<br>        subject.attach(self)<br>        self._subject = subject<br><br>    def update(self):<br>        open_tickets = self._subject.open_tickets<br>        ...<br>        self.display()<br><br>    def display(self):<br>        ...<br><br>    ## context manager<br>    def __exit__(self):<br>        self._subject.detach(self)<br><br>## main<br>kpis = KPIs()<br>with CurrentKPIs(kpis), ...:<br>    kpis.set_kpis(...)<br></pre><h3>Visitor</h3><p>A way to add new abilities to an object structure which allows us to keep the new capabilities separate. A visitor visits an object and gets access to the object’s contents.</p><p><em>— see </em><a href="https://medium.com/@pasdan/pluralsight-notes-structural-design-patterns-3879ff696b7d"><em>Composite</em></a></p><pre>from abc import ABC, abstractmethod<br><br>class Visitor(ABC):<br>    @abstractmethod<br>    def visit_person(self, person):<br>        pass<br>    <br>    @abstractmethod<br>    def visit_tree(self, tree):<br>        pass<br><br>class PrettyPrint(Visitor):<br>    def visit_person(self, person):<br>        print(...)<br>    <br>    def visit_tree(self, tree):<br>        print(...)<br><br>class GetOldestPerson(Visitor):<br>    def __init__(self):<br>        self.oldest = NullPerson()<br><br>    def visit_person(self, person):<br>        if person.birthdate &lt; self.oldest.birthdate:<br>            self.oldest = person<br>    <br>    def visit_tree(self, tree):<br>        pass<br><br>class AbstractTree(ABC):<br>    @abstractmethod<br>    def accept(self, visitor):<br>        pass<br><br>class Person(AbstractTree):<br>    def accept(self, visitor):<br>        ## breaks encapsulation here...<br>        visitor.visit_person(self)<br><br>class Tree(..., AbstractTree):<br>    def accept(self, visitor):<br>        visitor.visit_tree(self)<br>        for node in self:<br>            node.accept(visitor)<br><br>## main<br>p = Person(...)<br>p.accept(PrettyPrint())<br><br>tree = Tree(...)<br>...<br><br>oldest_person = GetOldestPerson()<br>tree.accept(oldest_person)<br><br>print(oldest_person.oldest)</pre><h4>Consequences</h4><ul><li>Easy to add new applications. Makes it harder to change the data model. Breaks encapsulation since it is given the internal state of the object. Class decorators can replace Visitors.</li></ul><h3>Chain of Responsibility</h3><ul><li>An organized way of processing incoming requests. Decouple requests from request handlers. Each handle the request they are responsible for.</li></ul><pre>from abc import ABC, abstractmethod, abstractproperty<br><br>@dataclass<br>class Request:<br>    request_type: str<br>    request_details: str<br><br>class AbstractHandler(ABC):<br>    @abstractmethod<br>    def handle(self, request):<br>        pass<br><br>## Parent Handler<br>class PetHandler(AbstractHandler):<br>    def __init__(self):<br>        self._successors = successors<br><br>    def add_successor(self, successor):<br>        self._successors.add(successor)<br><br>    def handle(self, request):<br>        for successor in self._successors:<br>            if successor.handle(request):<br>                break<br><br>## Individual Handler<br>class CatHandler(PetHandler):<br>    def handle(self, request):<br>        if request.request_type == &#39;cats&#39;:<br>            ...<br>            return True<br><br>        return False<br><br>## main<br><br>chain = PetHandler()<br>chain.add_successor(CatHandler())<br>chain.add_successor(DogHandler())<br><br>REQUESTS = [<br>    Request(&#39;...&#39;, &#39;...&#39;),<br>    ...<br>]<br><br>for request in REQUESTS:<br>    chain.handle(request)</pre><h3>Mediator</h3><ul><li>Reduces interactions between objects.</li></ul><pre>from abc import ABC, abstractmethod<br><br>class AbstractPet(ABC):<br>    def __init__(self, name):<br>        self.name = name<br>        self.mediator = None<br><br>class Cat(AbstractPet):<br>    def wants_out(self):<br>        if self.mediator.is_fish_alive():<br>            print(&#39;...&#39;)<br>        else:<br>            print(&#39;...&#39;)<br><br>    def is_asleep(self):<br>        ...<br><br>class Dog(AbstractPet):<br>    def wants_walk(self):<br>        if self.mediator.is_cat_asleep():<br>            ...<br><br>class PetMediator:<br>    def __init__(self, cat, dog, fish):<br>        ...<br><br>    def is_fish_alive(self):<br>        return self.fish.is_alive()<br><br>    def is_cat_asleep(self):<br>        return self.cat.is_asleep()<br><br>    ...<br><br><br>## main<br>cat = Cat()<br>dog = Dog()<br><br>mediator = PetMediator(cat, dog, ...)<br><br>cat.mediator = mediator</pre><h4>Consequences</h4><ul><li>Reduces subclassing and increases reusability == simplifies maintenance. Will centralizes control and can become complex overtime.</li></ul><h3>Memento</h3><ul><li>Snapshot of object state at some point in time. Simplifies the originator as it doesn’t need to be concerned with saving state. Easy to restore state.</li></ul><pre>from pickle import dumps, loads<br><br>@dataclass<br>class GameState<br>    name: str<br>    level: int<br><br>class Memento:<br>    def set_state(self, state):<br>        self._caretaker = dumps(state)<br><br>    def get_state(self):<br>        return loads(self._caretaker)<br><br>class I_Heart_42:<br>    def __init__(self, name: str):<br>        self.game_state = GameState(name, 1)<br><br>    def create_memento(self):<br>        memento = Memento()<br>        memento.set_state(self.game_state)<br>        return memento<br><br>    def set_memento(self, memento):<br>        self.game_state = memento.get_state()<br><br>## main<br><br>game = I_Heart_42(&#39;bob&#39;)<br>memento = game.create_memento() ## snapshot<br><br>## do some stuff<br>...<br>game.game_state.level = 42<br>...<br><br>## restore<br>game.set_memento(memento)</pre><h3>Null</h3><ul><li>Provides a default object to clients. Avoids null references. No need to test for null. Return a functioning dummy object.</li></ul><pre>objects = {<br>    &#39;...&#39;: RealObject,<br>    ...<br>}<br><br>def create(name):<br>    return objects.setdefault(name, NullObject)()<br><br>obj = create(&#39;...&#39;)<br><br>## avoid checking for null ...<br>obj.do_something()</pre><h3>Template</h3><ul><li>Avoids the “Don’t Repeat Yourself Principle”. Defines the skeleton of an algorithm. They contain abstract / concrete methods and hooks (<em>empty methods</em>) which can be overridden in subclasses. Subclasses can redefine a step but step order is preserved in the abstract base class.</li></ul><pre>from abc import ABC, abstractmethod<br><br>class AbstractTransport(ABC):<br>    def __init__(self, destination):<br>        self._destination = destination<br><br>    def take_trip(self):<br>        self.start_engine()<br>        ...<br>        self.entertainment()<br>        ...<br><br>    @abstractmethod<br>    def start_engine(self):<br>        pass<br><br>    def entertainment(self):<br>        ...<br><br>class Bus(AbstractTransport):<br>    def start_engine(self):<br>        ...<br><br>class Airplane(AbstractTransport):<br>    def start_engine(self):<br>        ...<br><br>    def entertainment(self):<br>        print(&#39;watching movie&#39;)<br><br>## main<br><br>Bus(&#39;New York&#39;).take_trip()<br>Airplane(&#39;New York&#39;).take_trip()</pre><h4>Consequences</h4><ul><li>Parent class calls the subclass</li></ul><h3>Iterator</h3><ul><li>Collection of objects while hiding the implementation. Creates a consistent/standard approach to handling the problem while adding new abilities to a collection. Use when we want to iterate over a collection while providing a uniform interface.</li></ul><p><strong><em>Python</em></strong> — <em>Sequence:</em> __getitem__(), <em>Callable:</em> __iter__() and __next__()</p><pre>from collections import Iterator, Sequence<br><br>class Employees(Iterator):<br>    _employees = {}<br>    _headcount = 0<br>    _empid = 0<br>    <br>    def add(self, employee):<br>        self._headcount += 1<br>        self.employees[self._headcount] = employee<br><br>    def __iter__(self):<br>        self._empid = 0<br>        return self<br><br>    def __next__(self):<br>        if self._empid &lt; self._headcount:<br>            self._empid += 1<br>            return self._employees[self._empid]<br>        else:<br>            raise StopIteration()<br><br>class Departments(Sequence):<br>    _departments = []<br><br>    def add(self, department):<br>        self._departments.append(item)<br>    <br>    def __getitem__(self, item):<br>        return self._departments[item]<br><br>    def __len__(self):<br>        return len(self._departments)<br><br>## generators<br><br>class Employees(Iterator):<br>    _employees = {}<br>    _headcount = 0<br>    <br>    def add(self, employee):<br>        self._headcount += 1<br>        self.employees[self._headcount] = employee<br><br>    def __iter__(self):<br>        return (e for e in self._employees.values())<br><br>class Departments(Iterator):<br>    _departments = []<br><br>    def add(self, department):<br>        self._departments.append(item)<br>    <br>    def __iter__(self):<br>        return (department for department in self._departments)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ohGyDsLXSG_4m3Sj" /><figcaption>Photo by <a href="https://unsplash.com/ko/@hbunny_?utm_source=medium&amp;utm_medium=referral">Husna Miskandar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=126e3f64f621" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualize Word Embeddings with PCA Decomposition using Scikit-Learn Pipelines]]></title>
            <link>https://medium.com/@pasdan/visualize-word-embeddings-with-pca-decomposition-using-scikit-learn-pipelines-2ec28c29b029?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec28c29b029</guid>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-vizualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 10:54:24 GMT</pubDate>
            <atom:updated>2023-07-08T10:54:24.339Z</atom:updated>
            <content:encoded><![CDATA[<p>Quickly produce decomposed word embedding representations using Scikit-Learn.</p><p>This post utilizes the Scikit-Learn pipeline to wrap all components into a single model.</p><h4>Setup</h4><pre>from sklearn.pipeline import Pipeline<br>from sklearn.preprocessing import FunctionTransformer<br>from sklearn.decomposition import PCA<br><br>import numpy as np<br>import gensim.downloader as api<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>sns.set_theme()</pre><h4>Build Pipeline</h4><pre>class GloveWordVectorTransformer():<br>    def __init__(self, model_name):<br>        self._model = api.load(model_name)<br><br>    def __call__(self, terms):<br>        return np.array([<br>            self._model.get_vector(term).tolist()<br>            for term in terms<br>        ])<br><br>glove = GloveWordVectorTransformer(&#39;glove-twitter-100&#39;)<br><br>model = Pipeline(steps=[<br>    (&#39;wv&#39;, FunctionTransformer(glove)),<br>    (&#39;pca&#39;, PCA(n_components=2))<br>])</pre><h4>Visualize Words</h4><pre>terms = [<br>    &#39;good&#39;,<br>    &#39;fine&#39;,<br>    &#39;acceptable&#39;,<br>    &#39;adequate&#39;,<br>    &#39;virtuous&#39;,<br>    &#39;righteous&#39;,<br>    &#39;alright&#39;,<br>    &#39;great&#39;,<br>    &#39;awesome&#39;,<br>    &#39;exceptional&#39;,<br>    &#39;significant&#39;,<br>    &#39;best&#39;,<br>    &#39;ok&#39;,<br>    &#39;fine&#39;,<br>    &#39;bad&#39;,<br>    &#39;awful&#39;,<br>    &#39;worst&#39;,<br>    &#39;terrible&#39;,<br>    &#39;horrible&#39;,<br>]<br><br>x, y = model.fit_transform(terms).T<br><br>fig, ax = plt.subplots(figsize=(15, 6))<br>ax.scatter(x, y, c=&#39;b&#39;)<br><br>for i, term in enumerate(terms):<br>    ax.annotate(<br>        term,<br>        (x[i], y[i]),<br>        xytext=(4, 2),<br>        textcoords=&#39;offset points&#39;<br>    )<br><br>plt.title(&#39;word embeddings&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afDtB8rErpkJ7NrB1vt5ow.png" /><figcaption>Word Embeddings in 2D</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec28c29b029" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Structural Design Patterns]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-structural-design-patterns-3879ff696b7d?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/3879ff696b7d</guid>
            <category><![CDATA[pluralsight]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 10:12:22 GMT</pubDate>
            <atom:updated>2023-07-08T10:12:22.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Structural Design Patterns</h3><p>Notes from watching ‘Design Patterns in Python 3’ from Pluralsight. Goes through a few Structural Patterns.</p><p><a href="https://www.pluralsight.com/courses/python-3-design-patterns">Design Patterns in Python 3</a></p><h4>Adapter Pattern</h4><ul><li>Converts an interface of a class into another that the client expects. We end up programing against a single API.</li></ul><pre>from abc import ABC, abstractproperty<br><br>class ICustomer(ABC):<br>    @abstractproperty<br>    def name(self) -&gt; str:<br>        pass<br><br>    @abstractproperty<br>    def address(self) -&gt; str:<br>        pass<br><br>class Customer(ICustomer):<br>    @property<br>    def name(self) -&gt; str:<br>        ...<br><br>    @property<br>    def address(self) -&gt; str:<br>        ...<br><br>@dataclass<br>class Vendor:<br>    name: str<br>    number: str<br>    street: str</pre><h4><em>Object Adapters </em>— Composition</h4><pre>class AbstractCustomerAdapter(ABC, ICustomer):<br>    def __init__(self, adaptee):<br>        self._adaptee = adaptee<br><br>    @property<br>    def adaptee(self):<br>        return self.adaptee<br><br>class VendorAdapter(AbstractCustomerAdapter):<br>    @property<br>    def name(self) -&gt; str:<br>        return self.adaptee.name<br><br>    @property<br>    def address(self) -&gt; str:<br>        return &#39;{} {}&#39;.format(<br>            self.adaptee.number,<br>            self.adaptee.street<br>        )<br><br>items: List[ICustomer] = [<br>    Customers(name=&#39;...&#39;, address=&#39;...&#39;),<br>    VendorAdapter(<br>        Vendor(name=&#39;...&#39;, number=&#39;...&#39;, street=&#39;...&#39;)<br>    ),<br>]</pre><ul><li>favor composition over inheritance</li><li>adapter delegates to adaptee</li></ul><h4>Bridge</h4><p><a href="https://medium.com/@pasdan/pluralsight-notes-bridge-design-pattern-83089f898f84">Pluralsight Notes — Bridge Design Pattern</a></p><h4>Composite</h4><ul><li>Trees and hierarchies — a mini structure resembles the whole structure. Compose objects into tree structures.</li><li>Nodes — Leaf, Composite</li></ul><pre>from dataclasses import dataclass<br>from collections import Iterable<br><br>@dataclass<br>class Person:<br>    name: str<br><br>class Family(Iterable):<br>    _members = []<br><br>    def __init__(self, members):<br>        self._members = members<br><br>    def __iter__(self):<br>        return iter(self._members)<br><br>family = Family([<br>    Person(...),<br>    Person(...),<br>    ...<br>])<br><br>singles = Family([<br>    Person(...),<br>    ...<br>])</pre><pre>from abc import ABC, abstractmethod<br><br>class AbstractComposite(ABC):<br>    @abstractmethod<br>    def get_oldest(self):<br>        pass<br><br>## leafs<br><br>@dataclass<br>class Person(AbstractComposite):<br>    name: str<br>    birthdate: date<br><br>    @property<br>    def get_oldest(self):<br>        return self<br><br>class NullPerson(AbstractComposite):<br>    name: str = None<br>    birthdate: date = date.max<br><br>    @property<br>    def get_oldest(self):<br>        return self<br><br>## tree / composite structure<br><br>class Tree(Iterable, AbstractComposite):<br>    _members = []<br><br>    def __init__(self, members):<br>        self._members = members<br><br>    def __iter__(self):<br>        return iter(self._members)<br><br>    @property<br>    def get_oldest(self):<br>        ## depth first ...<br>        def f(t1, t2):<br>            t1_, t2_ = t1.get_oldest(), t2.get_oldest()<br>            return t1_ if t1_.birthdate &lt; t2_.birthdate else t2_<br><br>        return reduce(f, self, NullPerson())<br><br>## main<br><br>Tree([<br>    Tree([<br>        Person(...),<br>    ]),<br>    Person(...),<br>])</pre><h4>Decorator</h4><ul><li>adds abilities to an object dynamically at run time. Ends up with a flexible alternative to subclasses.</li></ul><pre>from abc import ABC, abstractproperty<br><br>class AbstractCar(ABC):<br>    @abstractproperty<br>    def description(self):<br>        pass<br><br>    @abstractproperty<br>    def cost(self):<br>        pass<br><br>class EconomyCar(AbstractCar):<br>    @property<br>    def description(self):<br>        return &#39;...&#39;<br><br>    @property<br>    def cost(self):<br>        return 1000<br><br>class AbstractDecorator(AbstractCar):<br>    def __init__(self, car):<br>        self._car = car<br>    <br>    @property<br>    def car(self):<br>        return self._car<br><br>class V6(AbstractDecorator):<br>    @property<br>    def description(self):<br>        return self._car.description + &#39;, V6&#39;<br><br>    @property<br>    def cost(self):<br>        return self._car.cost + 800.00<br><br>## main<br><br>car = EconomyCar()<br>car = V6(car)<br>car = Leather(car)<br>...</pre><ul><li>More flexible, keeps things simple. Downside is that lots of little classes exist (<em>leverage Creational Patterns — factory, builder?</em>).</li><li>Use when you want to add new functionality to existing objects (<em>wrap</em>).</li></ul><h4>Façade</h4><ul><li>Putting a nice face on an interface. Useful when combining multiple APIs or reducing complexity with a simpler/unified interface. Create a Higher-level interface.</li></ul><pre><br>from abc import ABC, abstractmethod<br><br>class AbstractGetEmployeeFacade(ABC):<br>    @abstractmethod<br>    def get_employees(self):<br>        pass<br><br>class GetEmployeeFacade(AbstractGetEmployeeFacade):<br>    def get_employee(self):<br>        connection = pyodbc.connect(...)<br>        ...<br><br>ActiveGetEmployeeFacades = {<br>    &#39;pyodbc&#39;: GetEmployeeFacade,<br>    ...<br>}<br><br>class GetEmployeeFacadeFactory:<br>    @staticmethod<br>    def create(name):<br>        facade = ActiveGetEmployeeFacades[name]<br>                 if name in ActiveGetEmployeeFacades<br>                 else NullGetEmployeeFacade<br>        return facade()<br><br>api = GetEmployeeFacadeFactory.create(&#39;pydoc&#39;)<br>api.get_employee()</pre><ul><li>shields clients from subsystem (multiple) details — simple API</li><li>reduces the number of objects we need to handle</li></ul><h4>Flyweight</h4><blockquote>lets you fit more objects into memory by sharing common parts of state between multiple objects instead of keeping all of the data in each object.</blockquote><ul><li>state data is centralized which reduces object instances.</li></ul><h4>Unshared State Example</h4><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Event:<br>    x: int  ## x coord<br>    y: int  ## y coord<br>    t: float<br>    e: float<br>    <br>    def velocity(self):<br>        return ...<br><br>## main<br>events = []<br>for _ in range(100000):<br>    events.append(<br>        Event(...)<br>    )</pre><h4>Shared State</h4><pre>from abc import ABC<br>import numpy as np<br><br>class AbstractFlyweight(ABC):<br>    @abstractmethod<br>    def get_velocity(self):<br>        pass<br><br>class SharedEvents(AbstractFlyweight):<br>    def __init__(self, xaxis, yaxis):<br>        self._events = np.zeros((xaxis, yaxis, 2), np.double)<br>    <br>    def set_event(self, x, y, e, t):<br>        self._events[x, y] = (t, e)<br><br>    def get_event(self, x, y):<br>        ## could return an Event type ...<br>        return self._events[x, y]<br><br>    def get_velocity(self, x, y):<br>        return ...<br><br>class FlyweightFactory:<br>    @staticmethod<br>    def create(xaxis, yaxis):<br>        return SharedEvents(x, y)<br><br>## main<br>events = FlyweightFactory.create(10, 10)<br>for _ in range(100000):<br>    events.set_event(...)</pre><ul><li>useful when similar objects put pressure on the CPU and memory of the system.</li><li>combine with factory pattern to supply reusable (<em>repeated</em>) objects</li></ul><h4>Proxy</h4><ul><li>A <em>proxy</em> acts on an object (<em>called subject</em>). Keeps a reference and exposes methods through an interface. In this way, the <em>proxy</em> controls access to the object (<em>subject</em>).</li></ul><pre>from abc import ABC, abstractmethod<br><br><br>class AbstractEmployeees(ABC):<br>    @abstractmethod<br>    def get_employees_info(self, empids):<br>        pass<br><br>EMPLOYEES = {<br>  &#39;&lt;id&gt;&#39;: Employee(...),<br>}<br><br>class Employees(AbstractEmployeees):<br>    def get_employees_info(self, empids):<br>        return (<br>            EMPLOYEES[id]<br>            for id in empids<br>            if id in EMPLOYEES<br>        )<br><br>class Proxy(AbstractEmployeees):<br>    def __init__(self, employees, reqid):<br>        ...<br><br>    def get_employees_info(self, empids):<br>        acc = AccessControls.get_access_control()<br>        can_see = reqid in acc and acc[reqid].can_see_pid()<br>        <br>        for e in self._employees.get_employees_info(empids):<br>            if e.id == reqid or can_see:<br>                ## using prototype pattern<br>                yield e.clone()<br>            else:<br>                clone = e.clone()<br>                clone.&lt;personal infor&gt; = &#39;****&#39; ## redact<br><br>                yield clone<br><br>## factory method, client doesn&#39;t know about the Proxy<br>def get_all_employees(reqid) -&gt; AbstractEmployeees:<br>    return Proxy(Employees(), reqid)<br><br>## main<br>for employee in get_all_employees(...):<br>    ...</pre><ul><li>introduces indirection but allows us to hide details from client</li><li>@functools.lru_cache — virtual proxy implementation</li><li>use when you need to add controls to an object</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BCYojNsjOVXWiqry" /><figcaption>Photo by <a href="https://unsplash.com/@alvaropinot?utm_source=medium&amp;utm_medium=referral">Alvaro Pinot</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3879ff696b7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Creational Design Patterns]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-creational-design-patterns-7fe3fc111aba?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fe3fc111aba</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pluralsight]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 15:04:36 GMT</pubDate>
            <atom:updated>2023-07-05T15:10:47.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Creational Design Patterns</h3><p>Notes from watching ‘Design Patterns in Python 3’ from Pluralsight. Goes through a few Creational Patterns.</p><p><a href="https://www.pluralsight.com/courses/python-3-design-patterns">Design Patterns in Python 3</a></p><h3>Factory Pattern</h3><ul><li>Defines an interface for creating an object. The subclasses decide on the object. In this way, it defers instantiation to the subclasses.</li></ul><h4>Simple Factory Pattern (1 factory)</h4><pre>from abc import ABC, abstractmethod, abstractpropery<br><br><br>class AbstractAuto(ABC):<br>    @abstractmethod<br>    def start(self):<br>        pass<br><br>    @abstractmethod<br>    def stop(self):<br>        pass<br><br>class Chevy(AbstractAuto):<br>    ...<br><br>class Jeep(AbstractAuto):<br>    ...<br><br>class NullAuto(AbstractAuto):<br>    ...<br><br>Autos = {<br>    &#39;Chevy&#39;: Chevy,<br>    &#39;Jeep&#39;: Jeep,<br>    ...<br>}<br><br>class SimpleAutoFactory:<br>    def create(self, name: str) -&gt; AbstractAuto:<br>        auto = Autos[name] if name in Autos else NullAuto<br>        return auto()</pre><h4>Problems Solved</h4><ul><li>Simple to create new Auto classes and drop them into the dictionary.</li><li>Eliminated the dependency on the implementation of the Auto classes. It just needs to know how to handle the AbstractAuto class.</li></ul><h4>Classic Factory Pattern (1 or more factories)</h4><pre>class AbstractAutoFactory(ABC):<br>    @abstractmethod<br>    def create(self) -&gt; AbstractAuto:<br>        pass<br><br>class JeepFactory(AbstractAutoFactory):<br>    def create(self) -&gt; Jeep:<br>        return Jeep()  <br><br>class ChevyFactory(AbstractAutoFactory):<br>    def create(self) -&gt; Chevy:<br>        return Chevy()</pre><h4>Problems Solved</h4><ul><li>Clients no longer depend on implementations</li><li>Encapsulates object instantiation</li><li>Honors the Dependency Inversion Principle</li></ul><h4>Abstract Factory (familes of objects)</h4><ul><li>abstract factory creates families of classes, enforces dependencies between the concrete classes. Defers object creation to subclasses.</li></ul><pre>from abc import abstractstaticmethod<br><br><br>class AbstractFactory(ABC):<br>    @abstractstaticmethod<br>    def create_economy() -&gt; AbstractAuto:<br>        pass<br><br>    @abstractstaticmethod<br>    def create_sport() -&gt; AbstractAuto:<br>        pass<br><br>    @abstractstaticmethod<br>    def create_luxury() -&gt; AbstractAuto:<br>        pass<br><br>class FordFactory(AbstractFactory):<br>    @staticmethod<br>    def create_economy() -&gt; AbstractAuto:<br>        return FordFiesta()<br>    ...<br><br>class GMFactory(AbstractFactory):<br>    @staticmethod<br>    def create_economy() -&gt; AbstractAuto:<br>        return ChevySpark()<br>    ...</pre><h4>Factory vs Abstract Factory?</h4><ul><li>factory is great when you do not know what concrete classes you need.</li><li>abstract factory is great when you have families of objects.</li></ul><h3>Builder</h3><ul><li>Separate construction of an object. Allows for a multistep construction process. The constructed object can vary. Only allow the client to see the abstraction.</li><li>Helps to solve the parameter proliferation problem in constructors</li></ul><pre>from abc import ABC, abstractmethod<br><br>class Computer(object):<br>    case: str<br>    cpu: str<br>    memory: str<br>    ...<br><br>    def display(self) -&gt; None:<br>        ...<br><br>class AbstractComputerBuilder(ABC):<br>    def get_computer(self) -&gt; Computer:<br>        return self._computer<br><br>    def new_computer(self) -&gt; Computer:<br>        self._computer = Computer()<br><br>    @abstractmethod<br>    def build_case(self) -&gt; None:<br>        pass<br><br>    @abstractmethod<br>    def build_mainboard(self) -&gt; None:<br>        pass<br><br>    @abstractmethod<br>    def install_hard_drive(self) -&gt; None:<br>        pass<br>    ...<br>    <br><br>class HomeComputer(AbstractComputerBuilder):<br>    def build_case(self):<br>        self._computer.case = &#39;...&#39;<br><br>    def build_mainboard(self):<br>        self._computer.cpu = &#39;...&#39;<br>        self._computer.memory = &#39;...&#39;<br><br>    def install_hard_drive(self):<br>        pass<br>    ...<br><br>class WorkComputer(AbstractComputerBuilder):<br>    ...<br><br>class ComputerBuilderDirector:<br>    def __init__(self, builder: AbstractComputerBuilder):<br>        self._builder = builder<br><br>    def build(self) -&gt; None:<br>        self.builder.new_computer()<br><br>        ## adds parts to the computer in order<br>        self.build_case()<br>        self.build_mainboard()<br>        self.install_hard_drive()<br><br>    def get(self) -&gt; Computer;<br>        return self.get_computer()<br><br>builder = ComputerBuilderDirector(HomeComputer())<br>builder.build()<br><br>home_computer = builder.get()</pre><h4>Problems solved</h4><ul><li>too many constructor parameters</li><li>not exposing parameters to client (encapsulated)</li><li>adds consistent build order</li><li>separates the assembly (<em>build order</em>) from the actual components (<em>class attributes</em>)</li><li>allows for different representations (<em>HomeComputer vs WorkComputer</em>)</li></ul><h3>Prototype</h3><ul><li>Uses a given instance as a prototype, clones and allows us to give different attributes. This helps to reduce the number of classes in the source code (<em>vs Factory / Builder methods</em>).</li></ul><pre>from abc import ABC<br>import copy<br><br><br>class AbstractComputer(ABC):<br>    @abstractmethod<br>    def display(self) -&gt; None:<br>        pass<br><br>class AbstractPrototype(ABC):<br>    @abstractmethod<br>    def clone(self):<br>        pass<br><br>class Laptop(AbstractComputer, AbstractPrototype):<br>    def display(self) -&gt; None:<br>        ...<br><br>    def clone(self):<br>        ## shallow: return copy.copy(self)<br><br>        ## may cause a recursive loop<br>        ## may copy too much!!<br>        return copy.deepcopy(self)<br><br>manager = {} ## or class PrototypeManager(dict) ...<br>manager[&#39;L1&#39;] = Laptop()<br>manager[&#39;L2&#39;] = Laptop()<br><br>clone_of_l1 = manager[&#39;L1&#39;].clone()</pre><h3>Singleton</h3><ul><li>only one instance of an object, control access to a single point of entry.</li><li>considered harmful, considered an anti-pattern… very specific usage</li></ul><pre>## classic<br>class Logger():<br>    def info(self, text):<br>        ...<br>    <br>    @staticmethod<br>    def instance():<br>        if &#39;_instance&#39; not in Logger.___dict__:<br>            Logger._instance = Logger()<br>        return Logger._instance<br>        <br>## with base class<br>class Singleton(type):<br>    _instances = {}<br><br>    def __new__(cls, *args, *kwargs):<br>        if cls not in cls._instances:<br>            cls._instances[cls] = super().__new__(cls)<br><br>        return cls._instances[cls]<br><br>class Logger(Singleton):<br>    def info():<br>        ...<br><br>## with metaclass - controls the building of a class<br>class Singleton(type):<br>    _instances = {}<br><br>    def __call__(cls, *args, *kwargs):<br>        if cls not in cls._instances:<br>            cls._instances[cls] = super().__new__(cls)<br><br>        return cls._instances[cls]<br><br>class Logger(metaclass=Singleton):<br>    def __init__(self, path):<br>        ...<br><br>    def info(self, text):<br>        ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfnEHXuHk1mYOalI" /><figcaption>Photo by <a href="https://unsplash.com/@ravipinisetti?utm_source=medium&amp;utm_medium=referral">Ravi Pinisetti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fe3fc111aba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Design Patterns]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-design-patterns-part-1-10d2fbecfb51?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/10d2fbecfb51</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 09:45:59 GMT</pubDate>
            <atom:updated>2023-07-22T10:46:54.744Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Design Patterns</h3><p>Notes from watching ‘Design Patterns in Python 3’ from Pluralsight. Provides a basic introduction into design patterns and why we should care.</p><p><a href="https://www.pluralsight.com/courses/python-3-design-patterns">Design Patterns in Python 3</a></p><h3>What are design Patterns?</h3><blockquote>a model solution to a common design problem. It describes the problem and a general solution to solving it.</blockquote><h4>Why do we need them?</h4><blockquote>ensure our work is consistent, reliable, and understandable.</blockquote><ul><li>avoid reinventing the wheel each time</li><li>easy for someone else to modify the code after us</li></ul><h3>5 Principles to follow — SOLID</h3><ul><li><strong><em>Single Responsibility </em></strong>— class should only have one responsibility.</li><li><strong><em>Open/Closed</em></strong> — open for extension (inheritance) but closed for modification.</li><li><strong><em>Liskov substitution</em></strong>— subclass should be able to stand in for their parents without breaking anything.</li><li><strong><em>Interface segregation </em></strong>— lots of smaller interfaces are better, avoid large interfaces.</li><li><strong><em>Dependency Inversion</em></strong> — program towards abstraction instead of concrete classes. This allows implementations to vary while the abstraction stays the same.</li></ul><h3>Interfaces in Python</h3><pre>from abc import ABC, abstractmethod<br><br><br>class BaseClass(ABC):<br>    @abstractmethod<br>    def run(self):<br>        pass<br><br>class HelloWorld(BaseClass):<br>    def run(self):<br>        print(&#39;Hello World!&#39;)</pre><ul><li>abc provides checks to ensure your classes are complete</li></ul><h3>Types of Patterns (Some)</h3><ul><li><strong><em>Creational</em></strong> — object creation</li></ul><p><a href="https://medium.com/@pasdan/pluralsight-notes-creational-design-patterns-7fe3fc111aba">Pluralsight Notes — Creational Design Patterns</a></p><ul><li><strong><em>Structural</em></strong> — composition</li></ul><p><a href="https://medium.com/@pasdan/pluralsight-notes-structural-design-patterns-3879ff696b7d">Pluralsight Notes — Structural Design Patterns</a></p><ul><li><strong><em>Behavioral </em></strong>— interaction between objects and responsibility</li></ul><p><a href="https://medium.com/@pasdan/pluralsight-notes-behavioral-design-patterns-126e3f64f621">Pluralsight Notes — Behavioral Design Patterns</a></p><h4>Related Terms</h4><p><strong><em>coupling</em></strong> — the degree of interdependence between software modules; a measure of how closely connected two routines or modules are; (<a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)">wiki</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yNlAlMGTgmRshfw5" /><figcaption>Photo by <a href="https://unsplash.com/@gpthree?utm_source=medium&amp;utm_medium=referral">George Pagan III</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10d2fbecfb51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Design Principles for Machine Learning Framework]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-design-principles-for-machine-learning-framework-73a9469c6365?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/73a9469c6365</guid>
            <category><![CDATA[pluralsight]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 18:19:44 GMT</pubDate>
            <atom:updated>2023-07-03T18:19:44.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Design Principles for Machine Learning Framework</h3><p>Notes from watching ‘Design Principles for Machine Learning Framework’ from Pluralsight. High level view of Machine Learning Pipelines and makes a case for MLOps.</p><blockquote>Design Patterns capture best practices and solutions to common problems…</blockquote><p><em>Agile — Software Process</em></p><p><em>DevOps — Software Development</em></p><p><em>MLOps — Machine Learning Development</em></p><p><a href="https://www.pluralsight.com/courses/design-principles-machine-learning-framework">Design Principles for Machine Learning Framework</a></p><h4>MLOps — Machine Learning Operations.</h4><blockquote>is a practice that aims to make developing and maintaining production machine learning seamless and efficient.</blockquote><h4>DevOps</h4><ul><li>software is usually just code</li><li>get instant feedback after change</li><li>code is fairly static / rule based methods</li></ul><p><strong><em>… vs ...</em></strong></p><h4>MLOps</h4><ul><li>ML is code + data</li><li>changes often require retraining model(s), time consuming</li><li>models are constantly learning, changing and accommodating</li></ul><h4>So why does MLOps matter?</h4><p>— Helps produce long-term value and reduce risk — Data Science, Machine Learning and AI projects. Combines operations and data expertise together. Deploying models requires discipline.</p><p>— Efficient deployments without putting the business at risk.</p><h3>Design Principles</h3><ol><li><strong><em>Collaborative</em></strong> — ML should be a collaborative. MLOps forces teams to make everything that goes into building a model visible. Everything is audited.</li><li><strong><em>Reproducible </em></strong>— This is a process not an experiment. Versioning data, parameters and metadata. Store all training related artifacts.</li><li><strong><em>Continuous</em></strong> — Integration (CI) and Deployment (CD). Retraining should be effortless.</li><li><strong><em>Scalable and Monitored </em></strong>— Easy to expand infrastructure. Monitor technical and predicted behavior at all times.</li></ol><p>Project Life Cycle — Data, Model, Evaluation, Production … continuous iterations</p><h3>Data Pipelines</h3><blockquote>sequence of steps that move data from source (point a) to destination (point b)</blockquote><p>— a machine learning pipeline is meant to automate the machine learning workflow.</p><h4>Benefits</h4><ul><li>automate the ML lifecycle steps</li><li>triggered by new data</li><li>eliminate manual workflows which can be error prone</li><li>focus on new models</li><li>prevent bugs</li><li>standardize the entire workflow (on-boarded, work across teams, reduces time spent on setup).</li><li>reduce maintenance of existing models</li></ul><h4>Steps to Design a Pipeline</h4><ol><li><strong><em>Data Pre-processing — </em></strong>clean, transform and store in a feature data store.</li><li><strong><em>Model Training / Tuning (Learning Phase)</em></strong> — choosing the best performing model</li><li><strong><em>Prediction</em></strong></li><li><strong><em>Model Deployment </em></strong>— model servers deploy without code, provide API endpoints</li><li><strong><em>Close the feedback Loop </em></strong>— measure performance of new model</li></ol><p><strong><em>** manage growth of ML applications without introducing magnitudes of complexity **</em></strong></p><h4>Elements of a Pipeline</h4><ul><li><strong><em>Transformer </em></strong>— transform dataset into another</li><li><strong><em>Estimator</em></strong> — algorithm that is fit on a dataset</li><li><strong><em>Evaluator</em></strong> — examine accuracy of model</li></ul><h4><strong><em>Steps and Elements</em>:</strong></h4><ul><li><strong><em>Data:</em></strong> Ingest, Preprocessing, Splitting Dataset into subsets — <em>Transformer</em></li><li><strong><em>Model:</em></strong> Train Model, Model Evaluate, Pick best model for Deployment, Deploy, Model Serving (API) — <em>Estimator</em></li><li><strong><em>Feedback:</em></strong> Monitor —<em> Evaluator</em></li></ul><p>— NoSQL DBs are ideal for rapidly transforming data!</p><p>— MLOps helps to productionize ML models, automate DevOps tasks and allow scientists to focus on model building.</p><h3>Evaluating Performance</h3><blockquote>creating feedback loop, track and report metrices.</blockquote><h4>Low Latency / High Throughput</h4><p><strong><em>Latency</em></strong> — time taken to process on unit of data at a time (seconds). Examle: time taken to process one image.</p><p><strong><em>Throughput </em></strong>— number of items processed in one second for batch_size &gt; 1.</p><h4>Fault Tolerant System</h4><p>— a system that can continue to operate when one or more of its components fails. Failure of a subsystem does not mean the failure of the entire application.</p><ul><li>fallback to previous model</li><li>rule based method</li></ul><p>** workflow tools for task scheduling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bBxeXoH6KXaPV9cu" /><figcaption>Photo by <a href="https://unsplash.com/@deepmind?utm_source=medium&amp;utm_medium=referral">Google DeepMind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73a9469c6365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluralsight Notes — Bridge Design Pattern]]></title>
            <link>https://medium.com/@pasdan/pluralsight-notes-bridge-design-pattern-83089f898f84?source=rss-ce240c2edc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/83089f898f84</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[pluralsight]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[dp]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 10:27:40 GMT</pubDate>
            <atom:updated>2023-07-02T11:11:02.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pluralsight Notes — Bridge Design Pattern</h3><p>Notes from watching ‘C# Design Patterns: Bridge’ from Pluralsight. Transformed examples into Python.</p><p><a href="https://www.pluralsight.com/courses/design-patterns-c-sharp-bridge">C# Design Patterns: Bridge</a></p><h3>Sample Application</h3><pre>from abc import ABC, abstractmethod<br>from dataclasses import dataclass<br>from datetime import datetime<br><br>@dataclass<br>class MovieLicense(ABC):<br>    movie: str<br>    purchase_time: datetime<br>    <br>    @abstractmethod<br>    def get_price(self) -&gt; float:<br>        pass<br><br>    @abstractmethod<br>    def get_expiration_date(self) -&gt; datetime:<br>        pass<br><br>class TwoDaysLicense(MovieLicense):<br>    pass<br><br>class LifeLongLicense(MovieLicense):<br>    pass<br><br>## ...<br><br>now = datetime.now()<br><br>lic1 = TwoDaysLicense(&#39;Secret Life of Pets&#39;, now)<br>lic2 = LifeLongLicense(&#39;Matrix&#39;, now)</pre><h3>New Requirement(s)</h3><ul><li>add military discount — 10%</li><li>add senior discount — 20%</li></ul><p><strong><em>naive approach:</em></strong> add two new subclasses to both TwoDaysLicense and LifeLongLicense (6 classes).</p><blockquote>This leads to exponential growth of complexity.</blockquote><blockquote>Domain knowledge duplication where the same discount is being applied in different spots (don’t repeat yourself)</blockquote><h3>How to Fix? — Attempt 1</h3><ul><li>split the hierarchy … bridge (acts as a link / composition) to new logic.</li></ul><pre>@dataclass<br>class Discount(ABC):<br>    @abstractmethod<br>    def get_discount(self) -&gt; int:<br>        ## return percentage -- 20 == .20 %<br>        pass<br><br>## using the Null Object Pattern<br>class NoDiscount(Discount):<br>    def get_discount(self) -&gt; int:<br>        return 0<br><br>class MilitaryDiscount(Discount):<br>    def get_discount(self) -&gt; int:<br>        return 10<br><br>class SeniorDiscount(Discount):<br>    def get_discount(self) -&gt; int:<br>        return 20<br><br>@dataclass<br>class MovieLicense(ABC):<br>    movie: str<br>    purchase_time: datetime<br><br>    ## Composition...<br>    discount: Discount<br>    <br>    def get_price(self) -&gt; float:<br>        return self.get_price_core() * (1 - (self.get_discount() / 100.0))<br><br>    @abstractmethod<br>    def get_price_core(self) -&gt; float:<br>        pass<br><br>    @abstractmethod<br>    def get_expiration_date(self) -&gt; datetime:<br>        pass<br><br>## ...<br><br>now = datetime.now()<br><br>lic1 = TwoDaysLicense(&#39;Secret Life of Pets&#39;, now, NoDiscount())<br>sen1 = TwoDaysLicense(&#39;Secret Life of Pets&#39;, now, SeniorDiscount())<br>milt1 = TwoDaysLicense(&#39;Secret Life of Pets&#39;, now, MilitaryDiscount())</pre><h4>What did we achieve?</h4><ul><li>no more duplication of discount rules</li><li>simplified the code</li></ul><h3>2. How to Fix? — Attempt 2</h3><pre>from enum import Enum<br><br>class DiscountType(Enum):<br>    Nothing = 0<br>    Military = 1<br>    Senior = 2<br><br>class LicenseType(Enum):<br>    TwoDays = 0<br>    LifeLong = 1<br><br>@dataclass<br>class MovieLicense():<br>    movie: str<br>    purchase_time: datetime<br>    license: LicenseType<br>    discount: DiscountType<br>    <br>    def get_price(self) -&gt; float:<br>        return self.get_price_core() * (1 - (self.get_discount() / 100.0))<br><br>    def get_discount(self) -&gt; int:<br>        if self.discount == DiscountType.Military:<br>            return 10<br>        if self.discount == DiscountType.Senior:<br>            return 20<br>        return 0<br><br>    def get_price_core(self) -&gt; float:<br>        if self.license == LicenseType.TwoDays:<br>            return 4<br>        if self.discount == LicenseType.LifeLong:<br>            return 8<br>        raise ...<br><br>    def get_expiration_date(self) -&gt; datetime:<br>        if self.license == LicenseType.TwoDays:<br>            return ...<br>        if self.discount == LicenseType.LifeLong:<br>            return ...<br>        raise ...<br><br>## ...<br><br>now = datetime.now()<br><br>lic1 = MovieLicense(<br>    &#39;Secret Life of Pets&#39;,<br>    now,<br>    LicenseType.TwoDay,<br>    DicountType.None<br>)</pre><ul><li>two hierarchies are now enumerations</li><li>all logic is in the single base class</li><li>To extend, just inject a new enumeration (ie. special offers?)</li></ul><h3>Summary</h3><blockquote>The Bridge Pattern replaces complexity multiplication with complexity addition (Composition). Its purpose is to split a class hierarchy through composition to reduce coupling — (author)</blockquote><ul><li>Complexity here is based on coupling.</li><li>Coupling meaning connections between elements.</li><li>In the naïve implementation, 2 licenses connected to 3 discounts resulting in 6 connections.</li></ul><p><strong><em>Main takeaway </em></strong>— Composition is more flexible, easier to change, easier to understand…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HUn8WvlRxWJXyUXe" /><figcaption>Photo by <a href="https://unsplash.com/@kylertrautner?utm_source=medium&amp;utm_medium=referral">kyler trautner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83089f898f84" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>