<?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 Benjamin Engen on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Engen on Medium]]></description>
        <link>https://medium.com/@bengen?source=rss-9197849f39e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sy8q_0z4ii7sHNW_0EuX0g.jpeg</url>
            <title>Stories by Benjamin Engen on Medium</title>
            <link>https://medium.com/@bengen?source=rss-9197849f39e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:21:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bengen/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[When All You Have is a Hammer]]></title>
            <link>https://bengen.medium.com/when-all-you-have-is-a-hammer-c7c29daedcbc?source=rss-9197849f39e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7c29daedcbc</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Benjamin Engen]]></dc:creator>
            <pubDate>Mon, 05 May 2025 18:55:54 GMT</pubDate>
            <atom:updated>2025-05-05T18:55:54.121Z</atom:updated>
            <content:encoded><![CDATA[<h4>Analytics Engineer’s Guide to Source Quality Issues</h4><figure><img alt="a data engineer working on their data pipeline" src="https://cdn-images-1.medium.com/max/1024/1*0oGPJYtbx0LVGDjQ-N-pfA.png" /><figcaption>Created with Google Gemini</figcaption></figure><p>If you’ve worked in data for any time at all, you’ve no doubt realized the great plight of the data professional: in the eyes of all beholders, we’re responsible for the quality of all data, everywhere, all the time. Quieting the data quality backlash from users leaves data professionals with a host of bad options, as we are left to walk the highwire between strictly withholding data that might otherwise be valid or exposing potentially invalid data.</p><p>Here, I’ll lay out some “hacks” I’ve had to implement during my time as an Analytics Engineer working in dbt. And when I say “hacks,” I mean this in the true sense of the word. None of the approaches below represent ideal solutions. But, all too often, data is the art of the possible. If you’re working as an Analytics Engineer, you’ve likely encountered scenarios where you lack the needed access to “upstream” systems to correct data errors, or perhaps you just can’t garner the attention of those systems owners to get them to produce accurate data. In situations like this, we’re left with three bad options:</p><ol><li><a href="https://docs.getdbt.com/best-practices/writing-custom-generic-tests?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">Write strict dbt tests</a> that will halt the processing of the <a href="https://www.getdbt.com/blog/dag-use-cases-and-best-practices?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">DAG (directed acyclic graph)</a> and potentially disrupt data availability.</li><li>Write weak dbt tests that will allow bad data to flow through the DAG but still alert Analytics Engineers so they can rush to fix the data before it impacts users.</li><li>Maintain a bloated and ever-growing series of data transformations to correct every potential error introduced into source data.</li></ol><p>As an Analytics Engineer and a maintainability maven, I’m adamantly opposed to the third option. This meant my time Analytics Engineer-ing has left me walking the previously mentioned highwire between the first two options. So let’s dive into some of the approaches I’ve taken to striking that balance when nothing more than dbt was available to do so. Hopefully, some of these methods can be adapted to your own needs.</p><ol><li><a href="#60d3">Create a new ‘staging_ref’ macro</a></li><li><a href="#ddb0">Anomaly detection with circuit breakers</a></li><li><a href="#a700">Dynamic ‘staging’ models</a></li></ol><h3>Create a new ‘staging_ref’ macro</h3><p>One of the trickier data quality challenges is that of validating field contents. It can be nearly impossible to parse “good” data from “bad” within fields that lack clear rules governing the type of data particular fields should contain.</p><p>For reasons that could fill a dedicated blog post, it’s <em>often</em> my preference to continue ingesting otherwise valid <em>records</em> with potentially invalid <em>field</em> content into the <a href="https://docs.getdbt.com/best-practices/how-we-structure/2-staging?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">‘staging’ models</a> of a dbt project. However, we don’t want to let this potentially “bad” data propagate through the DAG to the point where it can impact users. To avoid this, we filter out “bad” data in the first layer of the DAG <em>past</em> the ‘staging’ layer. This can be as simple as writing detailed where statements in the downstream models to exclude “bad” data.</p><p>For example, I’ve too frequently encountered scenarios where test data makes its way into production. In these scenarios, you might have a stream of events with distinct <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#:~:text=A%20Universally%20Unique%20Identifier%20(UUID,Acronym?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">UUIDs (universally unique identifiers)</a> serving as their primary key. …and then in the middle of these, a bunch of records where the ‘UUID’ = ‘test’. Obviously, we don’t want to include those records. We can filter them out in the first downstream model with a where statement to the effect of where len(uuid) != 36. Now, this <em>can</em> be a perfectly acceptable solution for one-off scenarios. But what happens when you have a source schema with 50 tables, all subject to similar data quality issues? Now, you’ll find yourself having to write and maintain that same filter logic across dozens of intermediate models. That’s not very <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#:~:text=%22Don&#39;t%20repeat%20yourself%22,redundancy%20in%20the%20first%20place.?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">DRY (don’t repeat yourself)</a>.</p><p>As an alternative, we can create our own special version of <a href="https://docs.getdbt.com/reference/dbt-jinja-functions/ref?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">dbt’s ref macro</a> that can help modularize and maintain the filters for known bad records.</p><p>There are two (that I can think of) broad approaches that can be used to facilitate the modularity of where conditions that may build cumulatively from the schema to the table level: distinct <a href="https://docs.getdbt.com/docs/build/jinja-macros?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">dbt macros and jinja</a> dictionaries. I’ll demonstrate a hybrid approach using both so you can pick and choose which elements might be best for your situation.</p><p>First, we create a top-level macro that wraps dbt’s native ref macro to check the table schema and direct it toward the macro containing the correct where criteria for that schema or schema-table combination in question.</p><pre>{%- macro staging_ref(target_ref) -%}<br><br>{%- target_lst = target_ref.split(&#39;.&#39;) -%}<br><br>{%- if target_lst[1] == &#39;example_schema_1&#39; -%}<br>  example_schema_1_ref(target_ref)<br>{%- elif target_lst[1] == &#39;example_schema_2&#39; -%}<br>  example_schema_2_ref(target_ref)<br>{%- endif -%}<br><br>{%- endmacro -%}</pre><p>The subsequent macro for a particular schema-table combination contains the where logic to be implemented when it’s applicable to all tables in a particular schema.</p><p>We also have additional where logic that applies to specific tables. In this example, we’ve stored this logic in a dictionary where it can be retrieved by table name. If the additional table-level logic is more complex, it may make sense to break down the criteria further by giving each table a dedicated macro or extending the logic within the model itself.</p><pre>{% macro example_schema_1_ref(target_ref) -%}<br><br>{%- set target_lst = target_ref.split(&#39;.&#39;) -%}<br><br>{%- set tables_dict = {<br>  &quot;example_table_1&quot;: &quot;and not contains(info_email, &#39;test.com&#39;)&quot;,<br>  &quot;example_table_2&quot;: &quot;and len(device_id) = 36&quot;<br>} -%}<br><br>{{ target_ref }}<br>  where len(uuid = 36)<br>    {{ tables_dict.get(target_lst[2]) }}<br><br>{%- endmacro -%}</pre><p>The change within the model itself is almost non-existent. We still use dbt’s ref macro, but now we’ve embedded it as an input into our new custom staging_ref() macro, which will append the additional where logic required to filter out known bad values.</p><pre>{{<br>  config(<br>    materialized=&#39;incremental&#39;,<br>    incremental_strategy=&#39;delete+insert&#39;,<br>    on_schema_change=&#39;append_new_columns&#39;,<br>    unique_key=&#39;uuid&#39;<br>  )<br>}}<br><br>select *<br>from {{ staging_ref(target_ref=ref(&#39;example_schema&#39;, &#39;example_table&#39;)) }}</pre><p>By creating a bifurcation in the DAG where “bad” data is allowed into one layer and not the next, you open the door for more than just data integrity. You can now write ‘warn’ level tests on your ‘staging’ models to maintain visibility into the existence of “bad” data without passing that data onward through your DAG where it might harm users and processes. Additionally, by comparing the presence of records in your ‘staging’ layer against your first ‘intermediate’ layer of models, you can create a/many quarantine tables to house the invalid records and make them available for further scrutiny.</p><h3>Circuit Breakers &amp; Anomaly Detection</h3><p>The most pernicious data errors are those where no bright line between “good” and “bad” data exists. For example, a table populating with web session data when a break on your site leads to a surge in ‘daily active sessions’ being recorded. How do we protect against this? Arbitrarily write a dbt test to fail the DAG if X or more active sessions occur in one day? But if you work for a growing business, hopefully, you are seeing a steady climb in ‘daily active sessions’ anyway. Now, you’re faced with constantly having to ratchet your test threshold up as your business grows. Not ideal.</p><p>I’m a big <a href="https://www.montecarlodata.com/?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">Monte Carlo</a> evangelist. If you aren’t using Monte Carlo to monitor and manage your data, I strongly recommend you give it a try. Monte Carlo has a “<a href="https://docs.getmontecarlo.com/docs/circuit-breakers?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">Circuit Breakers</a>” feature that allows you to add a step to your orchestrator’s pipeline to fail or pause a pipeline if certain monitors are tripped. In addition, Monte Carlo offers machine learning based monitors for anomaly detection. This feature combination is ideal protection for the scenario that opened this section. Given the choice, I recommend you pursue the Monte Carlo path. But this post is about surviving as a scrappy Analytics Engineer with little more than dbt. So, how can we emulate the Monte Carlo functionality using only dbt (and possibly our orchestrator)?</p><p>In applying an approach like this, there are a lot of considerations to be made as they pertain to your particular situation. But, broadly speaking, I think they can be boiled down to two questions: “Where?” and “How?”</p><p><em>Where</em> in your DAG do you plan to implement this level of quality check? Between source tables and ‘staging’? Between source system intermediate tables and their point of integration? Between business entities and the business intelligence tables?</p><p>As to the “<em>How</em>”, this is a question of severity. If anomalies are detected, how aggressively should they be handled? Should we stop building downstream tables and withhold <em>all</em> data from subsequent models until we can address the problem? You need to examine your circumstances and ask whether partial data could lead to errors of interpretation. If an Analyst opens a dashboard and it’s only populating new users for the day as they’re recorded in the CRM and not the website, is that going to be a problem? Or is it worse for that Analyst to see no users at all? Considerations like this are a major factor in determining your unique implementation.</p><p>For this example, I’m assuming we want valid data to continue to flow, so partial data is still available. I’m making that assumption simply because that’s the more challenging application and, as such, makes for a better example. We’ll also assume that we’re implementing this check between the source tables and your first layer of ‘staging’ models since this post is all about data errors we Analytics Engineers may not have control over.</p><p>The meat of the implementation for this method is simply writing a <a href="https://docs.getdbt.com/best-practices/writing-custom-generic-tests?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">custom dbt test</a> to check for the anomaly of interest. You can get pretty clever with this if you’re so inclined. For this example, I’m applying a simple test to see if the number of records in a day is one standard deviation above the seven-day trailing average for that table. The dbt test for that would look something like so:</p><pre>{% test volume_anamoly(model, column_name) %}<br><br>with aggregates as (<br>  select<br>    {{ column_name }} as date_field,<br>    count(*) as record_count<br>  from {{ model }}<br>  where {{ column_name }} &gt; (date_sub(current_date(), interval 7 day))<br>  group by date_field<br>),<br><br>summary_stats as (<br>  select<br>    max(date_field) over (partition by date_field) as date_field_new,<br>    max(record_count) over (partition by date_field) as record_count_new,<br>    avg(record_count) over () as period_average,<br>    stddev_samp(record_count) over () as period_stddev<br>  from aggregates<br>  qualify row_number() over (partition by date_field order by date_field) = 1<br>)<br><br>select<br>  date_field_new,<br>  record_count_new,<br>  period_average,<br>  period_stddev,<br>  (record_count_new - period_average) / period_stddev as daily_variance<br>from summary_stats<br>where abs((record_count_new - period_average) / period_stddev) &gt; 1<br>  and date_field_new &gt; (date_sub(current_date(), interval 1 day))<br>order by date_field_new<br><br>{% endtest %}</pre><p>As with all dbt tests, if this test returns no records, then the test passes. The final where statement in the test ensures that we’re only returning rows where the number of records is more than one standard deviation away from the mean <em>and</em> that occurred in the latest load period, in this case the last day. Note that this second part is a bit subtle. You could configure the test to fail if any period in the sample has a record count more than one standard deviation away from the mean. However, if that period is anything other than the latest, it’s likely that you’ve already ingested it into your first ‘staging’ model and by then it’s too late for an effective warning. Because of this, the best implementation is to use time periods that align with the frequency of your incremental updates for the accompanying ‘staging’ table.</p><p>Now that we’re armed with our anomaly detection dbt test, we can use this on our source tables to block the build of ‘staging’ models that might be impacted by “bad” data, thus protecting the rest of our DAG and users from receiving “bad” data.</p><p>To achieve both these aims, we can use our orchestration platform. (Yes, yes I said these are dbt-only solutions, but I assume you aren’t running dbt without an orchestrator). The below diagram shows how the implementation would look as a <a href="https://www.prefect.io/?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">Prefect</a> flow.</p><figure><a href="https://miro.com/app/board/uXjVIJqQEf8=/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-X4_09SkgFozcoELqq-Rsg.jpeg" /></a><figcaption>Image created by author using miro.com</figcaption></figure><p>Here, we have a single <a href="https://docs.prefect.io/v3/develop/write-flows?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">Prefect flow</a> that contains two separate tasks/jobs representing different invocations of <a href="https://docs.getdbt.com/reference/commands/build?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">dbt build</a>. The first invocation executes only the ‘staging’ models. I typically handle this by ensuring ‘staging’ models are <a href="https://docs.getdbt.com/reference/resource-configs/tags?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">tagged</a> as such and can then be executed independently using dbt build --select tag: staging. By using dbt build for the execution and configuring our anomaly test ‘severity’ to ‘fail’ we can ensure that anomalous data that emerges in the source tables isn’t passed on to our ‘staging’ models.</p><p>From here, we can configure the first Prefect “Staging” job to ‘allow failure’ so that the remainder of the Prefect flow continues. The next Prefect job in the flow can execute the rest of your dbt DAG according to whatever rules you currently have in place. For the sake of our simple example, this would be to run the rest of the DAG with the exception of the ‘staging’ models that were invoked in the first job. That can be done with dbt build --exclude tag: staging.</p><p>Combining the failure treatment of dbt tests and our orchestrator flow allows us to fail the ‘staging’ “gateway” model that would have allowed bad data to propagate through the DAG while still allowing downstream models to build with the data available from other sources.</p><h3>Dynamic ‘staging’ models</h3><p>The most frustrating data quality problem I’ve faced was source data tables changing with no warning. And yes, I can hear your moans about contracts through the screen. But, “it was what it was,” and we Analytics Engineers didn’t have the access, nor did other teams have the time to make fixes. Thus, we found ourselves in a situation where our dbt invocations were failing because a model would begin building only to try to select some now non-existent field from a source table.</p><p>I (almost) always follow <a href="https://docs.getdbt.com/best-practices/how-we-structure/1-guide-overview?utm_source=medium&amp;utm_content=when-all-you-have-is-a-hammer">dbt’s style guide</a> for laying out dbt projects. Relevant here is the fact that all of our source data tables had a complimentary ‘staging’ table/dbt model. These ‘staging’ models served as data’s first point of ingestion into our dbt project and performed light transformations to bring data into conformity with our data warehouse standards. These models performed actions like applying consistent field names and data transformations to the <em>format</em> of incoming data. For example, lowering or triming certain fields etc. Changes to the grain, schema, or actual contents of fields at this stage of the DAG is forbidden.</p><p>As this layer of our DAG attempted to select and rename fields from source tables, if a field vanished or its name changed in a source table unexpectedly, the dbt model and all its downstream dependencies would fail, leading to an outage.</p><p>We solved this problem using jinja and dbt’s ability to use queries as a step in model execution. ‘Staging’ models were altered to first query the database’s INFORMATION_SCHEMA to return the fields available in the source table. Then, we used jinja to loop through the available fields and rename them according to a dictionary of mapped field names we established. If a field vanished or was renamed, it was no longer a problem because that field would not be added to the model code that dbt built on the fly. The now-missing field remained present in the ‘staging’ models because we configured these to run incrementally.</p><p>In practice, the code for this approach would look something like so:</p><p>First, we create a macro that can be re-used for all of our staging models, or at least those subject to this vanishing field problem:</p><pre>{%- macro dynamic_fields(target_source) -%}<br>/* In actuality, we set this dictionary as its own macro that is called<br>  so all of our source to target field name mappings can be maintained<br>  in one spot. */<br>{%- set field_names_dict = {<br>  &quot;example_source_field_1&quot;: &quot;standardized_field_1&quot;,<br>  &quot;example_source_field_2&quot;: &quot;standardized_field_2&quot;<br>} -%}<br><br>{%- set target_lst = target_source.split(&#39;.&#39;) -%}<br><br>{%- set field_query_sql -%}<br>  select column_name<br>  from {{ target_lst[0] }}.information_schema.columns<br>  where table_name = {{ target_lst[2] }}<br>  order by column_name<br>{%- endset -%}<br>{%- set query_results = run_query(field_query_sql) -%}<br><br>{%- if execute -%}<br>  {%- set fields_lst = query_results.columns[0].values()|list -%}<br>{%- else -%}<br>  {%- set fields_lst = [] -%}<br>{%- endif -%}<br><br>{%- for field in fields_lst %}<br>  {%- if field in field_names_dict.keys() -%}<br>    {%- set output_field_str = fields_name_dict.get(field) -%}<br>  {%- else -%}<br>    {%- set output_field_str = &#39;new_&#39; ~ field -%}<br>  {%- endif -%}<br><br>  {{ field }} as {{ output_field_str }},<br><br>{% endfor -%}<br><br>{%- endmacro -%}</pre><p>Then, we simply call that macro in the select portion of our ‘staging’ model.</p><pre>{{  config(<br>      materialized=&#39;incremental&#39;,<br>      incremental_strategy=&#39;delete+insert&#39;,<br>      on_schema_change=&#39;append_new_columns&#39;,<br>      unique_key=&#39;primary_key_field&#39;<br>)}}<br><br>select<br> {{ dynamic_fields(target_source=source(&#39;dbt&#39;, &#39;target_source&#39;) }}<br><br>from {{ source(&#39;dbt&#39;, &#39;target_source&#39; )}}</pre><p>In some cases, we chose to make much more intensive use of this ‘dynamic_fields’ macro as well, adding things to the control dictionary like data types to consistently cast fields and adding stronger handling for unexpected fields that appear. But the above is the core of the methodology.</p><h3>Conclusion</h3><p>In closing, let me reiterate that none of these solutions are ideal. But sometimes, we Analytics Engineers are victims of circumstance and are forced to work with what we have. When you inevitably find yourself in that situation, I hope you can borrow from some of the methods outlined here to tide yourself over and quell the storm of data quality complaints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c29daedcbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Castles In The Sky]]></title>
            <link>https://medium.com/google-cloud/build-your-castles-in-the-sky-1c2d9e04f8c2?source=rss-9197849f39e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2d9e04f8c2</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Benjamin Engen]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 01:08:45 GMT</pubDate>
            <atom:updated>2023-01-10T01:08:45.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MOHhFwLd4S2WNpUo" /><figcaption>Photo by <a href="https://unsplash.com/@planety?utm_source=medium&amp;utm_medium=referral">Niklas Tinner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Google Cloud Platform (GCP)</h4><h4>Set up a powerful remote development environment on Google’s new Cloud Workstations</h4><p>Google recently released a new addition to Google Cloud Platform into public beta called <a href="https://cloud.google.com/workstations">Cloud Workstations</a>. Their answer to <a href="https://aws.amazon.com/cloud9/">Amazon’s Cloud9</a>. Cloud Workstations provide a lightweight, cheap, virtual machine specifically for development work. Below I’ll cover the detailed steps involved in setting up your first Cloud Workstation, connecting your local VSCode instance to it via SSH, and configuring your Workstation for Python development.</p><ol><li><a href="#cfff">Why Google Cloud Workstations?</a></li><li><a href="#dda6">Creating Your Google Cloud Project</a></li><li><a href="#98d4">Creating Your Google Cloud Workstation</a></li><li><a href="#81ea">Connecting to Your Google Cloud Workstation</a></li><li><a href="#8440">Configuring Your Google Cloud Workstation</a></li></ol><blockquote>If you found this guide useful and/or you’re interested in more detailed getting-started guides please <a href="https://medium.com/@bengen"><strong>follow me here on Medium</strong></a>.</blockquote><h3>Why Google Cloud Workstations?</h3><p>I use Google Cloud Workstations for my personal projects as it offers one big advantage over developing locally on my laptop — performance. Specifically when I need more:</p><ol><li>Bandwidth</li><li>Processing Power</li></ol><p>Like most of us working in data, my work is focused on wrangling messy data into something queryable and usable. In my case, this often involves sizable file transfers from source FTP servers. Speaking as a remote worker from before it was cool I can tell you, performing big file transfers to your laptop over the free Starbuckswifi is not ideal. Much better to let Google’s robust infrastructure transfer these files to one of its servers and work with it from there.</p><p>Bandwidth aside, there’s the more obvious performance component of sheer processing power. My slavish devotion to my 2013 laptop means my local development environment is easily outclassed by one of Google’s 8-CPU Cloud Workstations.</p><p>Lastly, I appreciate the seamless experience. Connecting my local instance of VS Code to my Google Workstation via SSH means I preserve the functionality and feel of the coding environment I’ve grown accustomed to while still being able to take advantage of the aforementioned bandwidth and power.</p><p>So, let’s get you set up to try it out for yourself.</p><h3>Creating Your Google Cloud Project</h3><figure><img alt="Google Cloud Platform project creation screen" src="https://cdn-images-1.medium.com/max/1024/1*p6SmQ9aMzKOdeAD4nvvG8g.png" /><figcaption>Screenshot 1 by Author</figcaption></figure><p>Assuming you’re starting from scratch, head over to: <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a></p><ol><li>Click the drop-down on the top-left and then choose “New Project” as shown in Screenshot 1.</li><li>Enter a “Project name” for your project. It’s considered good practice to append some numbers to the name you choose. For this example, I’m choosing “gcp-workstations-8379”</li><li>Choose an “Organization” and “Location” from the dropdowns. If you’re just starting out you should only have one option available for each.</li><li>Click the blue “Create” button.</li><li>It will take a minute for your project to create. Once it does you can select it from the same top-left drop-down shown in Screenshot 1 that you accessed to create the project.</li></ol><h3>Creating Your Google Cloud Workstation</h3><figure><img alt="Google Cloud Platform search bar" src="https://cdn-images-1.medium.com/max/1024/1*VonYwSuYBAFSh8GWgz5WLw.png" /><figcaption>Screenshot 2 by Author</figcaption></figure><ol><li>“Search” for “Workstations.” In the search bar at the top of the screen type “Workstations” and choose the “Cloud Workstations” option that populates in the drop-down.</li><li>Click the blue “Enable” button. You’ll need to enable the Cloud Workstations API on this project which is as easy as clicking the button to do so.</li><li>Choose “Clusters” from the menu on the left as shown in Screenshot 3. Creating the workstation requires three steps: creating a cluster, a configuration, and then the workstation.</li></ol><figure><img alt="Google Cloud Platform Workstations space" src="https://cdn-images-1.medium.com/max/1024/1*atYmUdIx4gSBFJCr2-EA2g.png" /><figcaption>Screenshot 3 by Author</figcaption></figure><p>4. Click the blue “Create Cluster” button.</p><p>5. Choose a “Name” for your cluster. I’ll call mine “demo-cluster-101”.</p><p>6. Choose a “Region” for your cluster’s location. It’s good practice to co-locate your cluster in the same region as other Google Cloud resources it might utilize or near users (in this case: you). I’ll choose “us-west1” for mine.</p><p>There’s a drop-down for advanced settings. This contains configuration options in the event that you’re adding this workstation to a new/existing VPC (Virtual Private Cloud) network. Since we’re assuming a start from scratch you can ignore this section.</p><p>7. Click the blue “Create” button. Cluster creation is the most time-consuming step and can take up to 20 minutes to complete. So… go make a coffee or something.</p><p>8. Choose “Configurations” from the same left-hand menu shown in Screenshot 3.</p><p>9. Click the blue “Create Configuration” button. The true intention of Cloud Workstations is to give organizations a consistent development environment for their developers. In this step, we’ll create a configuration that can be applied to many individual workstations.</p><p>10. Enter a “Name”, I’ll choose “gcp-demo-config-202”</p><p>11. Choose a “Cluster” from the drop-down. Your only option should be the cluster we just created in Step 7.</p><p>12. Choose “Disabled” under “Quick start workstations.” I choose this because it’s cheaper, but feel free to enable this option if you’re impatient.</p><p>13. Click “Continue.”</p><p>14. Chose a “Machine type.” I’ll choose the default “e2-standard-4&quot; which is a 4-CPU 16GB virtual machine.</p><p>15. Choose an “Auto-sleep” option. I’ll choose the default, “After 2 hours of inactivity” here as well.</p><p>16. Click “Continue.”</p><p>You’re now in the “Environment customization” section which is the most important step. Here you can choose the environment and IDE you’d like to build your workstation around. For this example, we’re going to use “Code editors on base images” and choose “Base Editor (Code OSS)” which is basically VS Code. If you are actually using this for an organization and intend to have several users I’d strongly advise choosing “Custom container image” instead. However, that is beyond the scope of this introduction.</p><p>17. Choose the “Code editors on base images” radio button.</p><p>18. Choose “Base Editor (Code OSS)” from the “Code editors” drop-down.</p><p>19. Choose a “Disk type” from the drop-down. I’ll choose “Standard.”</p><p>20. Choose an option for “Disk size” from the drop-down. I’ll choose the default “200 GB.”</p><p>21. Click the blue “Create” button.</p><p>22. Choose “Workstations” from the left-hand menu as shown in “Screenshot 3” above.</p><p>23. Click the blue “Create workstation” button.</p><p>24. Enter a “Name” for your workstation. I’ll choose “gcp-demo-workstation-303”</p><p>25. Choose a “Configuration” from the dropdown. Your only option should be the one we just created.</p><p>26. Click the blue “Create” button.</p><p>Your virtual workstation is now created.</p><h3>Connecting to Your Cloud Workstation</h3><figure><img alt="Google Cloud Workstations connection details" src="https://cdn-images-1.medium.com/max/1024/1*P6i19E716dTaRa5QndOHng.png" /><figcaption>Screenshot 4 by Author</figcaption></figure><p>Cloud Workstations make connection and use very simple. If you like you can simply launch a window in your web browser and begin right away. However, I prefer to use my local version of VS Code which requires establishing an SSH connection. We’ll cover both options here.</p><h4>Connecting via Browser</h4><ol><li>Click “Start” which should occupy the area in the blue box shown in Screenshot 4.</li><li>Click “Launch” once the “Start” button converts to this option. This will open your workstation-hosted instance of VS Code in a new browser tab and you’re good to go.</li></ol><h4>Connecting via SSH</h4><p>Connecting via SSH using the below will require having the Google Cloud CLI installed on your machine.</p><ol><li>Head to <a href="https://cloud.google.com/sdk/docs/install">https://cloud.google.com/sdk/docs/install</a>, download, and install the appropriate version of the Cloud CLI for your machine.</li><li>Launch the Google Cloud CLI. If you’re on windows you probably have this icon on your desktop now.</li><li>Enter the command gcloud auth login. This should open a web browser and prompt you to log in using the Google account you’re using to access Google Cloud Platform.</li><li>Once authenticated, return to the Cloud Workstation home screen as shown in “Screenshot 4” and click the drop-down arrow next to the “Launch Button” then choose “Connect using SSH…” This will bring up a window as shown in “Screenshot 4” that provides the Google Cloud CLI command necessary to establish the TCP tunnel to your Workstation.</li><li>Run the top command in the Google Cloud CLI. There is a newer version of this command available so I recommend replacing gcloud alpha workstations with gcloud beta workstations but the rest of the command which contains your individual workstation information should remain unchanged. You may receive a notification that alpha/beta commands are not available in your Google Cloud CLI install. If that happens, it should also prompt you to download that functionality. Once you successfully run the gcloud beta workstations…command it should return Listening on Port 2222.</li><li>Open your local version of VS Code.</li></ol><figure><img alt="VS Code ssh connection palette" src="https://cdn-images-1.medium.com/max/1024/1*Mx-DM2bjS6NL8KefbOs5xQ.png" /><figcaption>Screenshot 5 by Author</figcaption></figure><p>7. In VS Code hit Ctrl + Shift + P to open the command palette.</p><p>8. Type “Open SSH Configuration File” and choose that option when it populates in the drop-down. If you’re on windows the file should be something like C:\Users\user\.ssh\config</p><p>9. Enter the below into the file:</p><pre># GCP Workstation<br>Host gcp<br>HostName localhost<br>user user<br>port 2222<br>StrictHostKeyChecking no</pre><p>10. Save and close the config file.</p><p>11. Hit Ctrl + Shift + P to open the command palette.</p><p>12. Type “Connect to Host” and choose the option “Remote-SSH: Connect to Host…” from the dropdown.</p><p>13. Choose “gcp” from the next drop-down menu.</p><p>14. During setup it might prompt you to ask about the environment you’re connecting to. Choose “Linux”</p><blockquote>Troubleshooting:</blockquote><blockquote>If you have trouble connecting, or reconnecting, to your workstation it could be a problem with the “StrictHostKeyChecking” that we attempted to disable in the initial configuration. If this happens find the file known_hosts which on Windows should reside at c:\Users\user\.ssh\known_hosts open this file in notepad. Look for [localhost]:2222 and delete this text along with everything following it. Save and close the file and then try to connect in VS Code again.</blockquote><h3>Configuring Your Google Cloud Workstation</h3><p>As we’ve created our Cloud Workstation from the base image we now need to configure our environment. As I mentioned after Step 16 in the “Creating Your Google Cloud Workstation” section, if you’re going to have multiple Workstations it would likely be best to carry out these steps in a Dockerfile that you attach to your Configuration and then build subsequent Workstations from that configuration. As this example is for individual use we’ll just carry out these steps once our Workstation is live.</p><p>Below are the steps to configure your environment for Python.</p><ol><li>Assuming you’re connected via SSH from your local instance of VS Code as per the end of the previous section go to “Terminal” at the top and then choose “New Terminal.” A terminal should open at the bottom with a bash prompt including your workstation name. In my case the prompt is user@gcp-demo-workstation-303: Make sure yours is something similar.</li><li>In the terminal enter sudo apt update &amp;&amp; sudo apt upgrade -y</li><li>Once the upgrades are finished enter sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev curl libbz2-dev This step is particularly important for Python. If prompted “Do you wish to continue?” Type Y</li><li>Choose the Python version you wish to install from <a href="https://www.python.org/downloads/source/">https://www.python.org/downloads/source/</a> and note the path to the “Gzipped source tarball” you intend to use. I’m choosing 3.10.9, so in the terminal, I’ll enter wget <a href="https://www.python.org/ftp/python/3.10.9/Python-3.10.9.tgz.">https://www.python.org/ftp/python/3.10.9/Python-3.10.9.tgz</a> to download the file.</li><li>Extract the file by entering tar -xf Python-3.10.9.tgz in the terminal.</li><li>Enter the python directory by entering cd Python-3.10.9 in the terminal.</li><li>Set the configuration by entering ./configure --enable-optimizations in the terminal.</li><li>Enter nproc in the terminal to check the number of processors you have available. I have 4.</li><li>Enter make -j 4 in the terminal, replace “4” with the number of processors you have. This step will take a while.</li><li>Install Python by entering sudo make install in the terminal.</li><li>Check that you were successful by entering Python3.10 --version in the terminal. If it prints back the version you intended to install then all is well.</li></ol><p>Congratulations. Your Google Cloud Workstation is now ready for you to begin developing with Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2d9e04f8c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/build-your-castles-in-the-sky-1c2d9e04f8c2">Build Your Castles In The Sky</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Apache Superset on Google Cloud Run]]></title>
            <link>https://medium.com/data-science/deploying-apache-superset-on-google-cloud-run-4e8f9b85a78a?source=rss-9197849f39e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e8f9b85a78a</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[superset]]></category>
            <dc:creator><![CDATA[Benjamin Engen]]></dc:creator>
            <pubDate>Fri, 27 May 2022 17:32:37 GMT</pubDate>
            <atom:updated>2022-12-29T10:29:20.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHeGL77DQTm28__scHGT1w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@peacelily234?utm_source=medium&amp;utm_medium=referral">Izabel 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>DATA SCIENCE</h4><h4>Get Your Proof of Concept Up in Minutes</h4><p>Apache Superset is a powerful open-source tool for dashboarding. But, setup can be cumbersome. I’ll take you through it step by step.</p><h4>Introduction</h4><p>This guide depends on an accompanying GitHub repository which can be found <a href="https://github.com/bengen343/superset-on-gcp-cloud-run">here.</a></p><p>In broad strokes, we will use this repository to:</p><ul><li>Set up Superset in a local VS Code development container.</li><li>Rather than creating the Superset configuration database locally, we’ll point our development container to the SQL database within Google Cloud Platform that we’ll use to support the final deployment.</li><li>Use our local deployment to configure the GCP SQL database.</li><li>Once the Google Cloud database is configured we’ll stage a container image in Google Artifact Registry.</li><li>Create the Google Cloud Run service from the Artifact Registry Container.</li></ul><p>The repository contains:</p><ul><li>.devcontainer: folder containing the files that will create a VS Code development container.</li><li>setup-scripts: folder that contains a collection of shell scripts to set up and configure Google Cloud Platform (GCP) services. These scripts can be customized for your needs but they shouldn’t require any customization as they rely on environment variables from the VS Code development container which you’ll set in .env.template.</li><li>src: folder that contains the files to build the Google Cloud Run Service.</li><li>.env.template to allow you to set environment variables with the values for your deployment.</li></ul><blockquote>If you found this guide useful and/or you’re interested in more detailed getting-started guides please <a href="https://medium.com/@bengen"><strong>follow me here on Medium</strong></a>.</blockquote><h4><strong>Prerequisites</strong></h4><p>Performing the above steps will require:</p><ol><li><a href="https://www.docker.com/">Docker Desktop</a></li><li><a href="https://code.visualstudio.com/">Visual Studio Code</a></li></ol><ul><li>The <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers">Remote Containers</a> extension</li></ul><p>3. <a href="https://cloud.google.com/sdk/docs/install">Google Cloud CLI</a></p><p>It’s very important that all of the shell commands/scripts outlined below be executed from the terminal <em>inside</em> the VS Code development container.</p><p>Install each of the above prerequisites in the order presented. Visual Studio Code, the Remote Containers extension, and the Google Cloud CLI are all easy to install. <strong>Follow the Docker installation instructions explicitly!</strong> Docker itself has a number of prerequisite steps. If you don’t already have Docker installed be very mindful of the installation steps.</p><p><strong>If you encounter an error in the below steps it is likely because you didn’t execute the prerequisite installation steps correctly.</strong></p><h4><strong>Getting Started</strong></h4><p>1. Once you’ve completed the prerequisite installations, clone <a href="https://github.com/bengen343/superset-on-gcp-cloud-run">the repository</a> to your machine. Do not rename the repository root folder from superset-on-gcp-cloud-run.</p><p>2. Rename the file ./.env.template to ./.env and open this file in Notepad or another text editor. Keep it open until instructed to save and close it. We’ll be populating some needed values in the next section.</p><h4><strong>Configuring Google Cloud</strong></h4><h4><strong>Project Creation</strong></h4><p>If you don’t already have a Google Cloud project set up for this, you’ll need to create one. So, take a jaunt over to the Google Cloud Platform web interface — <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</p><p>Selecting or creating a project is easily done from the drop-down on the top-left next to the ‘Google Cloud Platform’ text. Once you’ve created your project make sure you’re working in it by ensuring the correct project name appears next to the drop-down you just selected.</p><figure><img alt="google cloud console" src="https://cdn-images-1.medium.com/max/1024/1*Hwbi8LbCBWl2vueYFJZLUQ.png" /><figcaption>Google Cloud Console — Project Selection &amp; Creation</figcaption></figure><p>Be sure to enable billing on the project that you’ve created.</p><ol><li>Type ‘<em>Billing</em>’ in the top search bar and choose that option.</li><li>You should be greeted by a notification saying that the project has no billing account. Choose <strong>Link a Billing Account</strong>.</li><li>Choose (or create) your billing account.</li></ol><p>Make sure the GOOGLE_CLOUD_PROJECT variable in ./.env is set to match whatever you’ve chosen for your project name. Note that this value needs to be used in the SUPERSET_CONNECTION_NAME and SUPERSET_CONECTION_SECRET variables as well, so replace that portion of those strings as well now.</p><h4><strong>Configure Google Consent Screen</strong></h4><p>Our deployment is designed to allow any user from your Google-based organization to access Superset. In other words, if their email contains ‘@yourorganization.com’ they’ll be able to sign in. To do this we’ll need to configure a few things in the Google Cloud Console before proceeding.</p><ol><li>From Google Console Home type ‘APIs &amp; Services’ and choose that section.</li><li>Choose ‘<strong>OAuth Consent Screen</strong>’ from the left-hand menu.</li><li>Select ‘Internal’ and click <strong>Create</strong>.</li><li>Set the below fields. All can be at your discretion but note that ‘<em>Authorized domains</em>’ will determine access so be sure that’s your organization’s correct, top-level domain.</li></ol><ul><li>App name</li><li>User support email</li><li>Authorized domains</li><li>Developer contact information</li></ul><p>5. Click <strong>Save and Continue</strong>.</p><p>6. Click the <strong>Add or Remove Scopes</strong> button.</p><p>7. Select the ‘<em>openid’</em> scope and click <strong>Update</strong>.</p><p>8. Click <strong>Save and Continue</strong>.</p><p>9. Click the <strong>Back To Dashboard</strong> button.</p><h4><strong>Create credentials</strong></h4><ol><li>Select <strong>Credentials</strong> from the left-hand menu of the ‘<em>APIs &amp; Services</em>’ screen.</li><li>Click <strong>+Create Credentials</strong> &gt; <strong>OAuth Client ID</strong>.</li><li>Set the <strong>Application type</strong> drop-down to ‘<em>Web application</em>’ and choose a ‘<em>Name</em>’ of your liking.</li><li>Click <strong>Create</strong>.</li><li>‘<em>Your Client ID</em>’ and ‘<em>Your Client Secret</em>’ will be displayed in a pop-up. Note these values and copy them into their respective variables in the ./.env file: GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. Be mindful of leading/trailing white space. It’d be wise to <strong>Download JSON</strong> as well. You shouldn’t need it, but just in case.</li></ol><h4><strong>Environment Variables</strong></h4><p>Ensure that all of the variables in the ./.env file accompanying this repository now have values assigned to them. Save and close the ./.env file.</p><h4><strong>Open the Local Development Container</strong></h4><ol><li>Ensure that Docker is running and open on your machine and then open VS Code.</li><li>Within VS Code select the <strong>Remote Explorer</strong> icon from the left navigation bar to open the ‘<em>Remote Containers</em>’ extension.</li><li>Choose the <strong>Open Folder in Container</strong> button and select the folder containing the entirety of <a href="https://github.com/bengen343/superset-on-gcp-cloud-run">the repository</a>: superset-on-gcp-cloud-run. This step can take 5–10 minutes while the dependencies download and the container is built. When the container is fully built the file tree should display in the left pane.</li><li>From the top VS Code menu choose <strong>Terminal</strong> &gt; <strong>New Terminal</strong> to open a terminal pane.</li><li>Enter the command printenv in the terminal and press return. This will print a list of all the environment variables in your container. Scan through this to make sure those variables defined in ./.env are displaying the correct values. If they aren’t double-check that file, save it, and rebuild the container. You won’t be able to proceed if there are inaccuracies.</li></ol><figure><img alt="vs code important points" src="https://cdn-images-1.medium.com/max/1024/1*SxLBoZTiM6_ulzrAnXE4WA.png" /><figcaption>VS Code — Container &amp; Terminal Controls</figcaption></figure><h4><strong>Configure Google Cloud Platform Infrastructure</strong></h4><ol><li>Log in to Google cloud via the terminal by entering the command gcloud auth login. Because the container isn’t connected to the outside world, it will generate a command that you’ll need to copy into your Google Cloud SDK running outside the container. So, open the Google Cloud SDK Shell on your machine and paste in the command from the VS Code Terminal. This should open a browser window seeking your authorization to continue. Grant it access using your Google account of the same domain that you’re deploying Superset on.</li><li>Copy and paste the results from the Google Cloud SDK back into the VS Code terminal. If successful you should get a message saying ‘<em>You are now logged in as…</em>’</li><li>Switch to the Google Cloud Project you set up earlier by entering the command gcloud config set project $GOOGLE_CLOUD_PROJECT this will take advantage of the environment variable defining the name of your Google Cloud Project that you should have set earlier. If successful the terminal should return ‘<em>Updated property [core/project].</em>’</li><li>Enable the various Google Cloud services we’ll need within the project by typing setup-scripts/enable_gcp_services.sh into the VS Code terminal.</li></ol><blockquote>Some users have reported getting a ‘Permission denied’ error when attempting to run these shell scripts. If that happens to you, simply give yourself permission to execute the script by typing chmod u+x setup-scripts/enable_gcp_services.sh for example. This will give you execute permission on the script you designate.</blockquote><h4><strong>Create the Superset Configuration SQL Database</strong></h4><ol><li>Create the Superset SQL database in Google Cloud by running the setup_sql.sh script from this repository by typing setup-scripts/setup_sql.sh into the VS Code Terminal.</li></ol><h4><strong>Set Secrets &amp; Service Accounts</strong></h4><p>Your Cloud Run service will pull secrets from GCP <a href="https://console.cloud.google.com/security/secret-manager">Secret Manager</a>. These secrets will all be created based on the values you set in the ./.env file.</p><ol><li>Run the create_gcp_secrets.sh script by entering setup-scripts/create_gcp_secrets.sh into the VS Code terminal.</li><li>We’ll also need to create a service account for Superset to use and grant it access to the secrets we just created as well as the various services we’ll rely on. Run setup-scripts/create_gcp_service_account.sh in the VS Code terminal to create a service account named ‘<em>superset</em>’ in your project that can do this.</li></ol><h4><strong>Build Superset Configuration SQL Database</strong></h4><ol><li>Connect the VS Code development container to the GCP database we created by running this command in the terminal: /cloud_sql_proxy -instances=$SUPERSET_CONNECTION_NAME=tcp:5432. If it’s successful you should see the number next to the ‘<em>PORTS</em>’ heading at the top of the terminal increase by one and a pop-up may display informing you that ‘<em>Your application is now running on port 5432</em>’.</li><li>This proxy connection will monopolize the terminal window you were just working in. Open a new terminal window by clicking <strong>+</strong> on the top-right of the terminal window you were just working in.</li><li>In the new terminal window you’ve just opened type superset db upgrade. This may take some time to execute but this command is critical as it populates your Google Cloud hosted SQL database with all of the tables needed for Superset to run.</li></ol><h4><strong>Build &amp; Deploy the Apache Superset Container</strong></h4><p>Next, we will push a Docker image to a Google Artifact Registry within the Google Cloud project. A Cloud Run service will then be created to deploy that image.</p><ol><li>Create a Google Artifact Registry container by typing the command setup-scripts/create_gcp_artifact.sh into the VS Code terminal.</li><li>Upload the contents of the repository’s src folder to the repository you just created as a Docker image by typing setup-scripts/create_gcp_image.sh into the VS Code terminal.</li><li>Turn the image you’ve uploaded into an active Google Cloud Run Service by typing the command setup-scripts/create_gcp_cloud_run.sh into the VS Code terminal</li></ol><h4><strong>Update Service Credential</strong></h4><p>After running the script above, you will receive a Google Cloud Run service URL.</p><ol><li>Return to <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li>Search for and select <strong>APIs &amp; Services</strong> in the top search bar.</li><li>Select <strong>Credentials</strong> from the left navigation bar.</li><li>Choose the <strong>pencil icon</strong> to edit your OAuth credential, and update the <em>Authorized redirect URIs</em> to &lt;CLOUD-RUN-URL&gt;/oauth-authorized/google, replacing &lt;CLOUD-RUN-URL&gt; with the value the VS Code terminal returned. <strong>Wait a few minutes before proceeding</strong>.</li><li>Navigate to the Cloud Run service URL displayed by the VS Terminal (<em>*without the extra text you added in Step 4.</em>). This will authenticate you as an admin of the Superset deployment.</li></ol><p>Once you’ve done that, you will need to run the steps below to ensure future users are not granted admin access.</p><h4><strong>Refresh Superset Roles</strong></h4><ol><li>Update AUTH_USER_REGISTRATION_ROLE in superset_config.py to ‘<em>Public</em>’. Save and close that file. All new accounts moving forward will default to Public and no longer Admin.</li><li>Update the container image by again typing setup-scripts/create_gcp_image.sh into the VS Code terminal.</li><li>Deploy your new container version by again typing setup-scripts/create_gcp_cloud_run.sh into the VS Code terminal.</li></ol><h4><strong>Initialize Superset</strong></h4><ol><li>Make sure you’re still connected via the Google cloud sql proxy and type superset init into the VS Code Terminal. This will take several minutes to complete.</li></ol><h4><strong>Congratulations</strong></h4><p>Everything should now be running successfully and you should be able to access your deployment by visiting the URL returned when running setup-scripts/create_gcp_cloud_run.sh.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e8f9b85a78a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploying-apache-superset-on-google-cloud-run-4e8f9b85a78a">Deploying Apache Superset on Google Cloud Run</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Your Conversion Rate in Just a Few Lines of Python]]></title>
            <link>https://medium.com/data-science/level-up-your-conversion-rate-in-just-a-few-lines-of-python-c9e2c4af3684?source=rss-9197849f39e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9e2c4af3684</guid>
            <category><![CDATA[conversion-optimization]]></category>
            <category><![CDATA[pyvis]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Benjamin Engen]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 14:32:38 GMT</pubDate>
            <atom:updated>2022-12-29T10:27:53.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KrEBn0xjn0VUE7Us" /><figcaption>Photo by <a href="https://unsplash.com/@sallybrad2016?utm_source=medium&amp;utm_medium=referral">Preethi Viswanathan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>And produce some beautiful visualizations while you’re at it</h4><h4>Introduction</h4><p>Is your web experience costing you sales? If you aren’t making an active effort at Conversion Rate Optimization (CRO) the answer is <em>yes</em>. Yet another in the panoply of acronyms that abound in business, CRO is one of the cheapest and easiest ways to boost sales. A poor web experience on a lead’s journey to becoming a customer can sometimes be remedied by something as small as adding or removing a single button, reducing text, or cutting a page out of the process altogether.</p><p>But, to understand where you’re losing sales you first need to understand how users move through the collection of pages that make up your website. You need to examine the flow that they follow on the path to becoming a sale.</p><p>Google Analytics is free and almost universally adopted for web analytics. But, its path analysis options can be frustratingly linear — and linear is rarely the path customers follow to a sale.</p><p>Luckily, we can use the data from Google Analytics coupled with a few lines of Python to create an intuitive, interactive network graph that will allow us to examine how users travel through your site on their way to a conversion.</p><p>To do so we’ll:</p><ol><li><a href="#ab3d">Setup the Google Analytics API &amp; Configure Access</a></li><li><a href="#10aa">Use Python to download Google Analytics data</a></li><li><a href="#7bca">Cleanup and format our data in Pandas</a></li><li><a href="#5a65">Create an interactive network graph with Pyvis</a></li></ol><p>If you’re not interested in the step-by-step you can <a href="https://github.com/bengen343/ua-network-graph">access the full code for this undertaking in this GitHub repo</a>.</p><blockquote>If you found this guide useful and/or you’re interested in more detailed getting-started guides please <a href="https://medium.com/@bengen"><strong>follow me here on Medium</strong></a>.</blockquote><h4>Configure Google Analytics API</h4><p>To begin you’ll need to allow yourself API access to Google Analytics. Google makes this process very easy but, if this is your first foray into the depths of <a href="https://cloud.google.com/">Google’s Cloud Platform</a>, it could be daunting.</p><p>Start by heading over to <a href="https://cloud.google.com/">https://cloud.google.com/</a> and select either ‘Console’ or ‘Get started for free’ if you’re starting entirely from scratch.</p><figure><img alt="google cloud platfrom login" src="https://cdn-images-1.medium.com/max/1024/1*8XcaBJ39PTSz4kuUVOJueA.png" /><figcaption>Image by author</figcaption></figure><p>From here you’ll likely need to create a new project. Select the drop-down arrow to the left of the top search bar and then choose ‘New Project’ from the top-right of the pop-up.</p><figure><img alt="google cloud platform new project creation" src="https://cdn-images-1.medium.com/max/1024/1*D5Qsd5WQzFeAtPV7-8IqsQ.png" /><figcaption>Image by author</figcaption></figure><p>Now that you have your project, you’ll need to enable the Google Analytics API on your account. Since this is Google, it’s easy to search for that functionality. Head up to the top search bar and enter ‘Google Analytics API.’ Several options will come up, select ‘Google Analytics Reporting API.’ Then click ‘Enable.’ You shouldn’t be able to miss it.</p><p>Once you’ve done that you should find yourself on the ‘Overview’ portion of the Google Analytics Reporting API. From here you’ll want to select ‘Credentials’ on the left menu, then choose ‘+Create Credentials’ at the top of the new screen, and ‘Service Account’ from the options that pop up.</p><figure><img alt="google analytics api credential creation" src="https://cdn-images-1.medium.com/max/1024/1*Z58UEtL1bDp7Ignp9BzmjA.png" /><figcaption>Image by author</figcaption></figure><p>This will take you to a three-step flow. Give your service account a memorable name, choose ‘Owner’ in Step 2 for project access, and then finish.</p><p>This should bring you to the ‘Service Accounts’ screen and you should see your new service account listed. Now you’ll need to download a key to your computer to use for access. Select the three dots under ‘Actions’ next to your service account and then choose ‘Manage keys.’</p><figure><img alt="google cloud platform manage keys" src="https://cdn-images-1.medium.com/max/1024/1*7ReoCq_wxIpY0xBfaD8l1A.png" /><figcaption>Image by author</figcaption></figure><p>On the next screen select the ‘Add Key’ dropdown menu and then choose JSON for your ‘Key type.’ This will at once create a JSON file and you’ll be prompted to download it to your computer. Download this file to the same folder that your code will reside in.</p><p>The last step before we dive into the code is to give this new service account access to the <a href="https://analytics.google.com/analytics/web/">Google Analytics</a> (GA/UA) account that you’ll be drawing the data from. As you can see in the above screenshot, the service account has its own email address. Copy this address.</p><p>Head over to your <a href="https://analytics.google.com/analytics/web/">Google Analytics</a> account. Choose the ‘Settings’ gear on the bottom-left of the screen and then ‘View Access Management’ for the view you’ll want to build your graph from. Add the service account email address that you copied from <a href="https://cloud.google.com/">Google Cloud Platform</a> as a viewer. While you’re here, note the ‘View ID’ of the view you’re adding your service account to. You can find this on the very top drop-down to the left of the search bar.</p><figure><img alt="google analytics add service account" src="https://cdn-images-1.medium.com/max/1024/1*3ttJYraKO6HY9fle3OXPrA.png" /><figcaption>Image by author</figcaption></figure><p>Now we can get on with the actual coding!</p><h4>Download Google Analytics Data with Python</h4><p>In addition to the ubiquitous pandas, you’ll also need:</p><ul><li>apiclient and oauth2client — to connect to the Goolge Analytics API.</li><li><a href="https://pyvis.readthedocs.io/en/latest/">pyvis</a> — to create our network graph visualization.</li></ul><p>All the necessary packages can easily be obtained via PIP.</p><p>In addition to importing your packages, you’ll need to define a few variables upfront. Most importantly, you’ll need to enter the name of the JSON file that you downloaded from Google Cloud Platform that contains your API access key. This file is named ‘KEY_FILE’ below. You’ll also need to create a variable called ‘VIEW_ID’ and give it the View ID of your Analytics property as noted earlier. Note, that while this is a number you should store it in Python as a string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4144051abb3738746b28b922bba143b5/href">https://medium.com/media/4144051abb3738746b28b922bba143b5/href</a></iframe><p>Now we’ll need to define several functions to help us access our Google Analytics data. We’ll create ‘initialize_analyticsreporting’ to build the API connection, ‘get_report’ to define the dimensions and metrics we want to download and retrieve them, and ‘response_to_df’ to grab the Analytics data, make sure it’s completely downloaded, and save it in a pandas dataframe so it’s more orderly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24200ccabfc214e48ba68d0787608f53/href">https://medium.com/media/24200ccabfc214e48ba68d0787608f53/href</a></iframe><p>Note that in the ‘get_report’ function, lines 23 and 24, we’re passing in the dimensions and metrics we want to retrieve as variables as these are likely to change often. The function needs the dimensions and metrics as dictionaries which we generate from lists that are passed to the function.</p><p><a href="https://ga-dev-tools.web.app/dimensions-metrics-explorer/">Google has a very easy-to-navigate site</a> with the names for all of the dimensions and metrics that can be downloaded. Using this webpage we can make a list for the dimensions, and another for the metrics we wish to download. We’ll also need to define the date ranges we wish to examine. The Google Analytics API is handy in that it supports descriptive, relative, time frames like ‘14daysAgo’ and ‘yesterday.’ With that done we can call our Analytics functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8df4421d04d253ce5f481346e2cc0f9/href">https://medium.com/media/d8df4421d04d253ce5f481346e2cc0f9/href</a></iframe><p>…and inspect our resulting data.</p><h4>Inspect, Clean &amp; Format Data in Pandas Dataframe</h4><figure><img alt="google analytics dataframe" src="https://cdn-images-1.medium.com/max/1024/1*K3-7bpmQqUEr7MUwlfhQTw.png" /></figure><p>Everything looks pretty good. …except… your page paths likely still have the query parameters attached to them. (Unless you planned ahead and have been filtering this out on your Analytics view). In order to get a true sense of the traffic between all your pages, we’ll need to remove those query parameters and aggregate the results by the true page paths. While we’re at it I’m also going to make sure to store the numbers as numbers and not strings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c03371cc748d12cbb89d98bb4acf08ff/href">https://medium.com/media/c03371cc748d12cbb89d98bb4acf08ff/href</a></iframe><h4>Create a Network Graph to Visualize Your Traffic</h4><p>With our data now cleaned and organized, we can assemble it as a network and visualize it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec66db03a879c4b32cbd74e938d9c93e/href">https://medium.com/media/ec66db03a879c4b32cbd74e938d9c93e/href</a></iframe><p>The core of the visualization functionality is adding your nodes and edges with the ‘.add_node’ and ‘.add_edge’ lines and then displaying the HTML graph with ‘.show’</p><p>You can see I’ve made a few modifications to the data and display. For example, at the beginning, I’ve narrowed the paths to display to the top 10% most traveled in order to keep the graph from becoming too cluttered. I also include a ‘for’ loop at the end that adds additional information to the tooltip for each node. And, most complexly, I’ve used a color dictionary to make my nodes different colors based on the portion of the broader site that each page is a member of.</p><p>My network graph uses the traffic between two nodes to define the weight of the line. The nodes themselves are sized according to each page’s exit rate. The larger the node circle, the smaller the exit rate.</p><p>Note line 36; ‘.show_buttons(filter_=True)’. The first time you run your graph you can include this code to load an interactive menu of formatting options. This menu makes it easy to tweak the graph until you’re happy with its appearance. Then you can click ‘generate options’ to generate the options you’ve chosen as a dictionary which can be used to recreate your formatting in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYMRSIsA60kp_GeBk5N2Ig.png" /></figure><p>As you can see, I’ve set the options I chose and I invoke those on Line 7 of the code snippet above where I call the graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbc0e4c08d3ad5669f01eb58ba7c0199/href">https://medium.com/media/fbc0e4c08d3ad5669f01eb58ba7c0199/href</a></iframe><p>Call the visualization again with your pre-defined formatting and viola, an interactive visualization of your web traffic. You can use this to easily see the most common paths users travel through your site, which pages are driving exits, and where people are most likely to enter your page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*uMZ0hAg2SmDGGk3NDpsBXA.gif" /></figure><p>You can find the <a href="https://github.com/bengen343/ua-network-graph">full code for this project saved as a notebook over on GitHub</a>.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9e2c4af3684" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/level-up-your-conversion-rate-in-just-a-few-lines-of-python-c9e2c4af3684">Level Up Your Conversion Rate in Just a Few Lines of Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Political Direct Mail Work?]]></title>
            <link>https://bengen.medium.com/does-political-direct-mail-work-e5494043ce96?source=rss-9197849f39e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5494043ce96</guid>
            <category><![CDATA[campaign-strategy]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <category><![CDATA[colorado-politics]]></category>
            <category><![CDATA[market-research]]></category>
            <category><![CDATA[political-analysis]]></category>
            <dc:creator><![CDATA[Benjamin Engen]]></dc:creator>
            <pubDate>Fri, 21 Aug 2020 18:48:28 GMT</pubDate>
            <atom:updated>2022-12-29T10:28:32.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ECZVy9hgBq6F2QIv.png" /></figure><h3>Summary</h3><p><a href="https://www.constellationpolitical.com/">We</a> conducted a groundbreaking study on the effectiveness of political direct mail that was ultimately published in <a href="https://us.sagepub.com/en-us/nam/political-research-quarterly/journal201839">Political Research Quarterly</a>. Even in the digital age, direct mail remains a staple of campaigning. So, let’s answer the question — does direct mail actually work?</p><ul><li>Direct mail, positive or negative, can increase name ID for the candidate mentioned.</li><li>Positive mailers do increase candidate favorability. While negative mailers do appear to harm a candidate’s favorability, it’s not a significant impact.</li><li>Direct mail does increase voters’ stated intention to vote, but not their actual voting behavior.</li><li>The impact of direct mail fades rapidly.</li><li>Direct mail reaches saturation quickly and loses all effectiveness by mid-October.</li></ul><blockquote>If you found this guide useful and/or you’re interested in more please <a href="https://medium.com/@bengen"><strong>follow me here on Medium</strong></a>.</blockquote><h3>Background</h3><p>When we launched this project, data-driven campaigning was really coming into its own. We were breaking through the barrier into the data-science age, and quantitative research in campaigns was all the rage. If you’re reading this, odds are you <em>may have</em> read the two books that captured this interest — <a href="https://www.amazon.com/Rick-Perry-His-Eggheads-Brainiest-ebook/dp/B005HE8ED4">Rick Perry and His Eggheads</a> and <a href="https://www.amazon.com/Get-Out-Vote-Increase-Turnout/dp/0815732686">Get Out the Vote!</a></p><p>At the time, I was working with the State Party and took a keen interest in this new, more precise approach to campaigning. It was the first year under a new legislative map, there were a number of competitive legislative races at play, and it was also the first year of the State Party’s Trailblazer program to support legislative candidates.</p><p>The Executive Director at the time, Chuck Poplstein, and I got to wondering:</p><blockquote><em>“Was all of this direct mail that the State Party was spending money on actually doing anything?”</em></blockquote><p>Most research on the impact of different campaign activities had only addressed turnout, not persuasion. Chuck and I set out to change this.</p><p>We had the resources and the know-how to design and execute a sizable direct mail program, and even to test it. But, to ensure that our results withstood scrutiny and to add credibility to the project, we partnered with two professors — David Doherty and E. Scott Adler. They helped ensure that the experiment would produce accurate results and that it would stand up to scrutiny.</p><p>Doherty and Adler went on to publish <a href="https://journals.sagepub.com/doi/abs/10.1177/1065912914535987">the study</a> in <a href="https://journals.sagepub.com/home/prq">Political Research Quarterly</a>. At the time it was only the second study of its kind ever done and it became the official word on the impact of partisan direct mail.</p><p>To answer our various questions about the impact of direct mail we selected three competitive Trailblazer campaigns:</p><ul><li>SD19 — Lang Sias</li><li>SD26 — Dave Kerber</li><li>SD35 — Larry Crowder</li></ul><p>We conducted two rounds of trials — one around August 21st and the other around October 16th. We randomly assigned members of the target universe of Unaffiliated voters for each race to four different groups, those who would:</p><ul><li>Receive a positive mailer about the Republican.</li><li>Receive a negative mailer about the Democrat.</li><li>Receive a contrast mailer with a positive message about the Republican on one side and a negative message about the Democrat on the other.</li><li>Receive no mail to act as our control group.</li></ul><p>Using this design we set out to determine:</p><ul><li>The impact on candidate name ID.</li><li>The impact on candidate favorability.</li><li>The impact on turnout.</li><li>How long the impact of a mailer persisted.</li><li>When saturation set in.</li></ul><p>The direct mail pieces were pretty standard political fodder. Here is an example of the pieces sent out in support of Kerber and Sias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waOc-khLGDYOG-LY.png" /><figcaption>Graphic 1</figcaption></figure><h3>Results</h3><p>In short, we found:</p><ul><li>Direct mail, positive or negative, can increase name ID for the candidate mentioned.</li><li>Positive mailers do increase candidate favorability. While negative mailers do appear to harm a candidate’s favorability, it’s not a significant impact.</li><li>Direct mail does increase voters’ stated intention to vote, but not their actual voting behavior.</li><li>The impact of direct mail fades rapidly.</li><li>Direct mail reaches saturation quickly and loses all effectiveness by mid-October.</li></ul><h4>Name ID</h4><p>The most encouraging result was that direct mail does, indeed, increase candidate Name ID by a significant amount. This is true whether the candidate is mentioned in either a positive or negative light. In fact, the increase in name ID is actually greater with a negative message. This suggests that voters retain negative information at a higher rate.</p><p>In our first, August 21st, test we found that <strong>a positive mailer increased name ID for the Republican candidate by 4.7 points. The negative mailer increased name ID for the Democrat candidate by 5.2 points.</strong></p><p>In our second, October 16th, test there was no discernable impact on candidate name ID in neither the positive, negative, or contrast instances — an outcome I’ll discuss further in the timing section below.</p><h4>Persuasion</h4><p>The results from our first trial in August showed that mailers had the intended effect on candidate favorability, albeit to a much smaller degree than is conventionally assumed.</p><p><strong>The positive mailer increased the favorability of the Republican candidate by about one-fifth of a standard deviation.</strong> This effect is small but still rises to the level of statistical significance.</p><p><strong>The negative mailer did seem to hurt the favorability of the Democrat but the results were not statistically significant.</strong></p><p>We also measured the relative standing between the two candidates’ favorability. In this case, both positive and negative mailers appeared to improve the standing of the Republican but neither result was statistically significant.</p><p>During the second test around October 16th we found no significant impact on candidate favorability. Also, by mid-October, the impact from our first round of mail during August had vanished entirely.</p><h4>Turnout</h4><p>The turnout findings were the most profound and even led to the subsequent development of a new method of polling — which is why <a href="https://www.constellationpolitical.com/">Constellation</a> polls are so accurate …but, I digress.</p><p>The mailers in both August and our second test in October increased voters’ stated intention to vote. In other words, voters who received any of our test mail <em>said</em> they were more likely to vote.</p><p>However!</p><p>…when comparing the results against actual ballots cast, we found <em>no actual impact</em> on turnout.</p><p>In short, receiving political mail made voters more likely to <em>say</em> they’d vote but they <em>didn’t actually</em> do it.</p><h4>Timing</h4><p>If you’re a candidate or any entity looking to do political mail this is the most important finding:</p><blockquote><strong><em>At the level of a competitive legislative race in a Presidential election year, direct mail loses all effectiveness by mid-October.</em></strong></blockquote><p>The intuition behind this result makes sense; as Election Day approaches, the total amount of campaign spending increases and voters begin to, one, ignore political advertising and, two, solidify their opinions about the candidates.</p><p>These effects mean that low-impact mediums of advertising lose effectiveness. At later stages of the election, we need higher impact mediums of advertising, like video, to cut through the noise.</p><p>This diminishing impact of direct mail started to get more attention after the 2018 election where legislative losses underscored Colorado Republicans’ overreliance on direct mail. I discussed this disparity in my summary of 2018 election spending. Additionally, many of you likely recall this graph on diminishing returns to advertising from the, more closely held, post-mortem of that election.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*v41I0RM26NK-ZPj3.png" /><figcaption>Graph 1</figcaption></figure><h3>Is Direct Mail for You?</h3><p>The takeaway from this study is not “don’t do direct mail.” Rather, it should be: “consider these factors when determining whether or not direct mail is right for you.”</p><h4>What’s your landscape?</h4><p>This test was done on competitive legislative races so in one instance there’s an easier answer:</p><blockquote><em>If your race is of competitive legislative or greater salience, your direct mail would need to be arriving in mailboxes by the beginning of September to have any impact. Moving forward it will only become less effective and by October it will be meaningless.</em></blockquote><p>For those of you in different types of races, take these results into consideration alongside the complete picture of your race.</p><p>Consider the amount of total advertising likely to be deployed in your race. Is it likely that other advertising will drown out your direct mail? Will there be high-impact advertising, like TV, for your race that could also drown out mail?</p><p>If you’re in a small or low-salience campaign, the great news from this study is that direct mail does have an impact and that a single piece can boost your name ID by five points …if it’s not crowded out by other advertising.</p><h4>What’s your budget?</h4><p>You also need to consider your budget relative to the size of your target universe of voters.</p><p>When comparing the expense of different forms of advertising a common metric is Cost-Per-iMpression (CPM). This is the amount you pay for every 1,000 “views” of your ad. The below table shows the rough CPM for different forms of advertising:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*lHMRHaTE4SNuPoLo.png" /><figcaption>Table 1</figcaption></figure><p>A lot of factors go into determining the CPM for a particular medium. Table 1 shows that high-impact or targeted mediums tend to be more expensive.</p><p>For example, the CPM for autodials is only around $30 — but everyone hates autodials. Contrast to cable at $75 — $250 CPM where you can deploy compelling creative to a captive audience.</p><p>Google Ads are very cheap on a per-impression basis because you can blanket the internet with them, but they’re now mostly untargeted. Compare the price of Google Ads at $6 CPM to Facebook ads at $12 — $25 CPM. Facebook is more expensive because those ads can (*could) be targeted to specific voters. In both cases, note how much cheaper digital is than other mediums of advertising. That’s because digital is a low-impact medium, it takes a lot more digital to move the needle than it does TV.</p><p>Let’s look at these costs in greater context. Table 2 shows how expensive it would be for a competitive Colorado State Senate campaign and a competitive State House campaign to reach every member of their target persuasion universe with one view of an advertisement via each medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*IKI2Xrv_FlmiJfdR.png" /><figcaption>Table 2</figcaption></figure><p>As you can see, direct mail is far-and-away the most expensive medium of advertising. And we all know that you can’t just reach voters with one ad, one time, and expect to win. This means that for mail alone a competitive State Senate race would need about $100,000 and a competitive State House race would need about $40,000.</p><p>In considering which ad mediums are right for you, first consider those you can afford to mount an effective campaign with.</p><h3>Conclusion</h3><p>The combined cost and oversaturation of other advertising mediums means direct mail is best suited for campaigns with smaller numbers of voters and/or those that will have minimal advertising from all sources — candidate, opponent, and outside groups.</p><p><a href="https://journals.sagepub.com/doi/abs/10.1177/1065912914535987">The Published Paper</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5494043ce96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>