<?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 Antony Harfield on Medium]]></title>
        <description><![CDATA[Stories by Antony Harfield on Medium]]></description>
        <link>https://medium.com/@antonyharfield?source=rss-ed3185eec7ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pASTcewZFfQcxeseu0E_lQ.jpeg</url>
            <title>Stories by Antony Harfield on Medium</title>
            <link>https://medium.com/@antonyharfield?source=rss-ed3185eec7ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:04:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@antonyharfield/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[Converting the YAMNet audio detection model for TensorFlow Lite inference]]></title>
            <link>https://medium.com/@antonyharfield/converting-the-yamnet-audio-detection-model-for-tensorflow-lite-inference-43d049bd357c?source=rss-ed3185eec7ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d049bd357c</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[firebase-ml-kit]]></category>
            <category><![CDATA[bioacoustics]]></category>
            <dc:creator><![CDATA[Antony Harfield]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 14:31:08 GMT</pubDate>
            <atom:updated>2020-06-14T08:17:42.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting the YAMNet audio detection model to TensorFlow Lite</h3><p>For machine learning in the field of acoustics, most state-of-the-art models rely on recognising patterns in spectrograms using convolutional neural networks (CNNs). At <a href="https://rfcx.org/">Rainforest Connection</a>, we use CNNs to detect the sound of chainsaws, vehicles and other potentially illegal activities in the rainforest and other protected areas. While inferences are currently performed on servers in the cloud, we are excited at the prospect of inference at the edge on sensors in the field for faster event detection. To achieve this, we need efficient audio detection models capable of running on IoT or mobile devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxnmpcAI3B45qE-5qW52YA.png" /><figcaption>Ontology of sounds in AudioSet (taken from <a href="https://research.google.com/audioset/ontology/">https://research.google.com/audioset/ontology/</a>)</figcaption></figure><p>YAMNet is an acoustic detection model that classifies 521 different sounds, trained by <a href="https://github.com/dpwe">Dan Ellis</a> on the labelled audio from more than 2 million YouTube videos (<a href="https://research.google.com/audioset/">AudioSet</a>). The YAMNet model is included in the <a href="https://github.com/tensorflow/models/tree/master/research/audioset/yamnet">research section of the TensorFlow models repo</a>. It’s an awesome project.</p><p>I’m going to walkthrough converting the YAMNet model to a TensorFlow Lite model that can be run on mobile devices (e.g. deployed to Android or iOS as a <a href="https://firebase.google.com/docs/ml/use-custom-models">Firebase ML Custom Model</a>). 🚀</p><h3>1. Setup</h3><p>Download the <a href="https://github.com/tensorflow/models/tree/master/research/audioset/yamnet">TensorFlow models repository</a> from GitHub and make the yamnet folder your working directory. (I moved it out and deleted the rest of the repo as it’s not needed for the rest of this experiment.)</p><p>Get your favourite python environment setup with Tensorflow 2.2. You can use virtual environments or Anaconda if you prefer, but I find it easier to use Docker:</p><pre>docker run -it --rm -v ${PWD}:/app -w /app tensorflow/tensorflow:2.2.0</pre><p>Next, you need to download the model weights for YAMNet:</p><pre>curl -o yamnet.h5 https://storage.googleapis.com/audioset/yamnet.h5</pre><p>Then you can run YAMNet’s test script python yamnet_test.py. If you see Ran 4 tests… and OK then you have everything you need!</p><p>Next, let’s see the outputs when running the model on an audio file. The inference script will resample the file it if it does not match the 16kHz sample rate of the YAMNet model. Make sure you have soundfile and resampy installed. If you setup your environment with Docker then simply:</p><pre>apt-get install -y libsndfile1<br>pip install resampy soundfile</pre><p>Test the model on <a href="https://github.com/antonyharfield/tflite-models-audioset-yamnet/tree/master/examples">an audio file</a>:</p><pre>python inference.py examples/baby_5000ms.wav</pre><p>Expected output:</p><pre>examples/baby_5000ms.wav :<br>  Crying, sobbing: 0.555<br>  Baby cry, infant cry: 0.485<br>  Babbling    : 0.400<br>  Child speech, kid speaking: 0.100<br>  Inside, small room: 0.055</pre><p>We have a working YAMNet model on TensorFlow, the remainder of this article is dedicated to getting the same results on TensorFlow Lite. 👩🏻‍💻</p><h3>2. First try at TF Lite converter</h3><p>As described in the guide <a href="https://www.tensorflow.org/lite/guide/get_started">Get Started with TensorFlow Lite</a>, there are a few different ways to convert model to the TFLite format:</p><ul><li>SavedModel directories</li><li>Keras models</li><li>Concrete functions</li></ul><p>Looking at the yamnet.py file where the model is defined, we see that it is a Keras model. In my first try at converting, I simply passed the yamnet model into the TFLiteConverter.from_keras_model function as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5288ce4a34d6d192446114e680cefec/href">https://medium.com/media/b5288ce4a34d6d192446114e680cefec/href</a></iframe><p>When you run it python convert_fail1.py, it errors:</p><pre>ValueError: None is only supported in the 1st dimension. Tensor &#39;input_1&#39; has invalid shape &#39;[1, None]&#39;.</pre><p><strong>Lesson #1: TFLite doesn’t support dynamically-sized (None) dimensions.</strong> So we won’t be able to pass an arbitrary length audio file to a TFLite model as the shape of the input needs to be defined during compilation/conversion. (That’s not completely true as TFLite has <a href="https://github.com/tensorflow/tensorflow/commit/55912083e2f16087c2f29394acf8a6a4811a2ce0">added support for dynamically-sized inputs</a> in the <a href="https://www.tensorflow.org/api_docs/python/tf/lite/TFLiteConverter#attributes_1">new experimental converter</a>, but I was unable to get it working on a mobile device). Hence we need to pick the length of the audio clip. Looking at the params.py file, the default sample rate is 16,000 and the window length is 0.96 seconds. So originally I incorrectly guessed the input shape to be [1, 15360]. To explain why it’s incorrect, we can look at the YAMNet documentation and consider the spectrogram conversion…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*RFenmiHvGZ8d77fh8jXUNA.png" /><figcaption>Waveform (top) and it’s generated spectrogram (bottom)</figcaption></figure><blockquote>“A spectrogram is computed using magnitudes of the Short-Time Fourier Transform with a window size of 25 ms, a window hop of 10 ms, and a periodic Hann window.”</blockquote><p>I understood this as the raw audio waveform has a sliding window of 0.025s pieces, and we need sufficient windows to cover 0.96s. Hence the input length in seconds should be a multiple of 0.025, and it must be at least 0.96 seconds. It turns out the minimum is 0.975 seconds, or 15,600 samples. (I don’t know why the window length is not a multiple of the STFT frames, or why it wasn’t rounded up to 1 second — I suspect there is a mathematical explanation!)</p><p>To specify this, we copy the yamnet_frames_model function from yamnet.py and modify it so that the input shape is fixed at [1,15600].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/722a25acb91c266746536ba08d4739fa/href">https://medium.com/media/722a25acb91c266746536ba08d4739fa/href</a></iframe><p>Now when we run python convert_fail2.py we get:</p><pre>error: failed while converting: ‘main’: Ops that can be supported by the flex runtime (enabled via setting the -emit-select-tf-ops flag): RFFT,ComplexAbs.</pre><p><strong>Lesson #2: The RFFT and ComplexAbs operators are not supported in tflite. </strong>These are not actually used in the CNN, but are part of the spectrogram generation.</p><p>Next up I spent a lot of time trying to get things working with SELECT_TF_OPS by adding this line:</p><pre>converter.target_spec.supported_ops = [<br>    tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]</pre><p>The conversion completed successfully and I thought we were done — but I wasn’t able to get the converted TFLite file to load on Android or iOS. (Nor does it load in Python because TensorFlow doesn’t support inference with the SELECT_TF_OPS and hence local testing was impossible — suggest avoiding the select ops unless you know what you are doing.) Several hours of frustrated debugging followed!</p><h3>3. Generating spectrograms the TFLite way</h3><p>After several cups of tea, I discovered the solution is to avoid using the unsupported ops. For this I have to thank <a href="https://github.com/tensorflow/tensorflow/issues/27303">a long conversation on a GitHub issue</a> which showed the way forward: writing your own TFLite-compatible implementation of tf.signal.stft. Over at the <a href="https://magenta.tensorflow.org/">Magenta project</a> (Make Music and Art using Machine Learning), they have <a href="https://github.com/magenta/magenta/blob/41b891c137e8a51bd44322f0434ba8f3f7df0dba/magenta/models/onsets_frames_transcription/melspec_input.py">done exactly that</a>.</p><p>In the YAMNet source code, on line 35 of features.py (inside the function waveform_to_log_mel_spectrogram) you will find the call to tf.signal.stft that we need to replace.</p><pre>magnitude_spectrogram = tf.abs(tf.signal.stft(<br>        signals=waveform,<br>        frame_length=window_length_samples,<br>        frame_step=hop_length_samples,<br>        fft_length=fft_length))</pre><p>In a moment we will replace it with a modified version of the _stft_magnitude_tflite function from the Magenta project. Let’s copy only the functions we need into a new file features_tflite.py. Its quite long so please <a href="https://github.com/antonyharfield/tflite-models-audioset-yamnet/blob/master/features_tflite.py">download it here</a> and place the file in your working directory.</p><p>Then in our next attempt we use the waveform_log_mel_spectrogram function from our new file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3f68b57efcf9e64c6348221a5a58ba9/href">https://medium.com/media/b3f68b57efcf9e64c6348221a5a58ba9/href</a></iframe><pre>python convert.py</pre><p>Voilà! It converts successfully and the yamnet.tflite file is saved. 😍🎉🕺🏻</p><p><strong>Lesson #3: Make your own waveform-to-spectrogram function based on a STFT TFLite-compatible function. </strong>Thank you Magenta folks! (Funny aside: after I wrote this article I found out that the STFT functions were originally written by Dan Ellis himself!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*74f-dvNIUswB9Peg38UwXA.png" /><figcaption>TFLite converted YAMNet in Netron (with STFT layers for spectrogram generation visible on the left)</figcaption></figure><p>Inspect yamnet.tflite in <a href="https://github.com/lutzroeder/netron">Netron (awesome tool for visualising ML models)</a> and check the inputs and outputs look reasonable.</p><ul><li>Input: [1,15600] (raw audio samples of 0.975 seconds at 16kHz sample rate)</li><li>Output 0: [1,521] (predictions for the 521 classes)</li><li>Output 1: [96,64] (log mel spectrogram — you might not need this)</li></ul><h3>4. Testing</h3><p>Recall the inference.py script we used to test the model in part 1, and let’s now make a version that loads the model from the saved TFLite file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab4527975dcb9df3d80f5f675cfa2f3e/href">https://medium.com/media/ab4527975dcb9df3d80f5f675cfa2f3e/href</a></iframe><p>If you test it on the same audio file we used in part 1:</p><pre>python inference_tflite.py examples/baby_5000ms.wav</pre><p>Then you will get an error:</p><pre>Error when checking input: expected input_1 to have shape (15600,) but got array with shape (80000,)</pre><p>Remember that earlier we set a fixed shape for the input of the TFLite model. We will need an audio file that is exactly 0.975 seconds in duration. Try again with a correct length audio file:</p><pre>baby_975ms.wav :<br>  Crying, sobbing: 0.930<br>  Baby cry, infant cry: 0.862<br>  Whimper     : 0.157<br>  Babbling    : 0.112<br>  Inside, small room: 0.030</pre><p>Run the same baby_975ms.wav file on the original model inference.py and you should get exactly the same results — we can be confident that it is working correctly. Furthermore, we have a test wav file and the expected outputs that we can use to verify it is running correctly on a mobile device.</p><h3>What next?</h3><p>You now have a TFLite version of YAMNet that you can add to an Android or iOS application. I found the easiest way to run it was using Firebase ML Custom Models. The following tutorials are a good place to start.</p><ul><li><a href="https://heartbeat.fritz.ai/using-tensorflow-lite-and-ml-kit-to-build-custom-machine-learning-models-for-android-a7e272d3c61e">Using TensorFlow Lite and ML Kit to build custom machine learning models for Android</a></li><li><a href="https://medium.com/firebasethailand/firebase-ml-kit-custom-models-for-ios-developers-part-1-understanding-tensorflow-lite-123dfcfdce29">Firebase ML Kit Custom Models for iOS developers — Part 1: Understanding TensorFlow Lite</a></li><li><a href="https://medium.com/firebasethailand/firebase-ml-kit-custom-models-for-ios-developers-part-2-implementing-tic-tac-toe-44f1cd9f99c5">Firebase ML Kit Custom Models for iOS developers — Part 2: Implementing Tic Tac Toe</a></li></ul><p>The complete project is <a href="https://github.com/antonyharfield/tflite-models-audioset-yamnet">available on GitHub</a>. This has been a fun side-project for learning more about ML on mobile — welcome your comments and suggestions. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d049bd357c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Railway Oriented Programming in Kotlin]]></title>
            <link>https://proandroiddev.com/railway-oriented-programming-in-kotlin-f1bceed399e5?source=rss-ed3185eec7ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1bceed399e5</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Antony Harfield]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 05:01:01 GMT</pubDate>
            <atom:updated>2019-05-21T11:44:14.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a26jtvQ1vUqwKIKYhEw8cw.png" /></figure><p>I recently read Scott Wlaschin’s <a href="https://www.slideshare.net/ScottWlaschin/railway-oriented-programming">slide deck on Railway Oriented Programming</a> and it got me rather excited how it closely relates to the Result type that has been around for a while in various Kotlin and Swift libraries (and has recently been added to both their core libraries). Like many others I use it regularly — yet here are railway junctions giving some theoretical foundation to the use of the Result type and clearly explaining why it is a great solution to handling errors.</p><p>I was intrigued to know how we might implement this in Kotlin while preserving the beauty of Scott’s F# examples. And so began an extended conversation with Charles Allen via code snippets on his Facebook post (who I thank for introducing me to this in first place) that eventually led to this article. [Enough introduction,] I will jump straight into a Kotlin example and try to show how it might be given <em>the railway treatment</em>.</p><p>Let’s suppose that we are responsible for writing a module that reads in the content of an email (e.g. from disk) and performs the send operation.</p><p>I’m going to start by introducing a <strong>happy path</strong>:</p><pre>val input = read()<br>val email = parse(input)<br>send(email)</pre><p>where:</p><pre>fun read(): List&lt;String&gt; { // Get the raw data }</pre><pre>fun parse(inputs: List&lt;String&gt;): Email { // Convert it to an object }</pre><pre>fun send(email: Email) { // Perform the operation }</pre><pre>data class Email(to: String, subject: String, body: String)</pre><p>So what is an <strong>unhappy path?</strong> It is when you don’t get the perfect outcome. An example would be if the input ended unexpectedly and returned null (like you get with readLine).</p><pre>val input = read()<br>if (input != null) {<br>   val email = parse(input)<br>   send(email)<br>}<br>else {<br>   println(&quot;Error: Unexpected end of input&quot;)<br>}</pre><p>Unhappy paths can build up quite quickly. What if the parse function can throw an exception?</p><pre>val input = read()<br>if (input != null) {<br>   try {<br>      val email = parse(input)<br>      send(email)<br>   } catch (e: Exception) {<br>      println(&quot;Error: Unable to parse input&quot;)<br>   }<br>} else {<br>   println(&quot;Error: Unexpected end of input&quot;)<br>}</pre><p>Then you remember that you need to handle the validation. The email must have a valid “to” address and the subject and body must not be empty.</p><pre>val input = read()<br>if (input != null) {<br>   try {<br>      val email = parse(input)<br>      if (!email.to.contains(&quot;@&quot;)) {<br>         println(&quot;Error: Invalid email address&quot;)<br>      } else if (email.subject == &quot;&quot; || email.body == &quot;&quot;) {<br>         println(&quot;Error: Subject and body must not be blank&quot;)<br>      } else {<br>         send(email)<br>      }<br>   } catch (e: Exception) {<br>      println(&quot;Error: Unable to parse input&quot;)<br>   }<br>} else {<br>   println(&quot;Error: Unexpected end of input&quot;)<br>}</pre><p>I’m afraid to say that a lot of my code looks like this! A feature starts off simple, but as unhappy paths are added it becomes full of <em>if/elses</em> or <em>try/catches</em> (or the odd <em>switch</em> statement to maintain my reputation). The problem here is that the paths go deep — IntelliJ will remind you that <a href="https://blog.jetbrains.com/idea/2017/08/code-smells-deeply-nested-code/">deeply nested code is a code smell</a>. I feel safe with the “flat” code of the happy path, but not with the “depthy” code of this last example. Why is it that I don’t like the depthy code?</p><ol><li>The happy path is no longer obvious. The logic of the happy path is input-parse-validate-send, but it is lost in ifs and trys.</li><li>There are lots of unhappy paths and they are all in one function. The more branching, the more likely we are to get into unexpected states. I suddenly need unit tests to raise my confidence in this code.</li><li>It is difficult to see all the possible unhappy outcomes. (Can you spot them? They are: a) unexpected end of input, b) parse failure, c) invalid email address, d) missing subject or body)</li><li>The unhappy outcomes are not always located in the same place as the detection of the unhappy path. (The unexpected end of input outcome is at the bottom, but the check for it is at the top.)</li></ol><p>Railway Oriented Programming offers a functional approach to handling happy and unhappy paths (or successful states and error states). Let’s see how it can be implemented in Kotlin.</p><p>The main principle in Railway Oriented Programming is that every function can returns either success or failure (in the same way that a railway junction has two tracks out of it). In our example, bothparse and send are functions that have a happy outcome (success) or an unhappy outcome. The validation steps could be considered the same. Let’s write a separate function for the validation of the email address:</p><pre>fun validAddress(email: Email): Result = <br>    if (email.to.contains(&quot;@&quot;))<br>        Success(email)<br>    else<br>        Failure(&quot;Invalid email address&quot;)</pre><p>Both functions take an Email object as a parameter and return a Result object containing either Success or Failure. In the case of Success the object will also contain the Email object. In the case of Failure the object will also contain a String error message.</p><p>The Result is a <a href="https://proandroiddev.com/kotlin-sealed-classes-enums-with-swag-d3c4b799bcd4">sealed class</a> in Kotlin (read: enum on steroids) whose basic implementation might look something like this:</p><pre>sealed class Result<br>data class Success(val value: Email): Result()<br>data class Failure(val errorMessage: String): Result()</pre><p>But later we will want to use Result for any type of success, so let’s replace Email with a generic type.</p><pre>sealed class Result&lt;T&gt;<br>data class Success&lt;T&gt;(val value: T): Result&lt;T&gt;()<br>data class Failure&lt;T&gt;(val errorMessage: String): Result&lt;T&gt;()</pre><p>Then update our validAddress function to use the generic Result and introduce the second validation function for checking the email is not blank.</p><pre>fun validAddress(email: Email): Result&lt;Email&gt; = <br>    if (email.to.contains(&quot;@&quot;))<br>        Success(email)<br>    else<br>        Failure(&quot;Invalid email address&quot;)</pre><pre>fun notBlank(email: Email): Result&lt;Email&gt; = <br>    if (email.subject != &quot;&quot; &amp;&amp; email.body != &quot;&quot;)<br>        Success(email)<br>    else<br>        Failure(&quot;Subject and body must not be blank&quot;)</pre><p>These two functions might take up more lines of code than the validation code in our “depthy” example, but we have gained a piece of documentation in the function name and the logic of their unhappy outcomes is plain to see. We could use them individually:</p><pre>val result = validAddress(email)<br>when (result) {<br>   is Success -&gt; println(&quot;Ok&quot;)<br>   is Failure -&gt; println(&quot;Error: ${result.errorMessage}&quot;}<br>}</pre><p>Or the two functions could be composed:</p><pre>val result = validAddress(email).then(::notBlank)<br>when (result) {<br>   is Success -&gt; println(&quot;All validation checks passed&quot;)<br>   is Failure -&gt; println(&quot;Error: ${result.errorMessage}&quot;}<br>}</pre><p>Or the composition could be defined as a new function that performs all the validations:</p><pre>fun validate(email: Email) = validAddress(email).then(::notBlank)</pre><pre>val result = validate(email)<br>when (result) {<br>   is Success -&gt; println(&quot;All validation checks passed&quot;)<br>   is Failure -&gt; println(&quot;Error: ${result.errorMessage}&quot;}<br>}</pre><p>What is then? It is a function that we define on Result that applies the given function only on Success results (otherwise it returns the existing Failure value):</p><pre>infix fun &lt;T,U&gt; Result&lt;T&gt;.then(f: (T) -&gt; Result&lt;U&gt;) = <br>    when (this) {<br>        is Success -&gt; f(this.value)<br>        is Failure -&gt; Failure(this.errorMessage)<br>    }</pre><p>If then is defined as an <a href="https://medium.com/makingtuenti/infix-functions-in-kotlin-2db3d3142dd2">infix function</a> then it becomes more naturally readable (especially for the functional enthusiasts out there — <a href="https://www.dcs.warwick.ac.uk/~sgm/cs123/">Warwick Alumni of CS123</a>, you know who you are):</p><pre>fun validate(email: Email) = validAddress(email) then ::notBlank</pre><p>(The double colon prefix is a <a href="https://antonioleiva.com/function-references-kotlin/">function reference</a> which is needed in Kotlin to pass a top-level function around.)</p><p>Back to the railway analogy… Each function that returns a Result is the logic for a railway junction that evaluates to success or failure. They are composed to form sequences of junctions where the happy path is one where all the functions get executed (Success/green) and any failure causes the train to redirect to the unhappy path (Failure/red).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bzo0qxaFYMCfYGuz7O4qw.png" /></figure><p>Suppose our railway involves three main junctions defined above as parse, validate, and send. The validate function was given earlier as the composition of detecting invalid address and detecting blank subject/body. The other two functions are defined as follows:</p><pre>fun parse(inputs: List&lt;String&gt;): Result&lt;Email&gt; { ... }</pre><pre>fun send(email: Email): Result&lt;Unit&gt; { ... }</pre><p>Then our earlier example can be implemented as the following:</p><pre>val input = read()<br>parse(input) then ::validate then ::send</pre><p>I don’t think there is anyway to make the happy path of our module clearer than this! And we have encapsulated our unhappy outcomes in each individual function.</p><p>How do we deal with the unhappy paths? At the end of the railway, any failure is passed to an <em>error handler</em>. I introduced another infix function (named otherwise) specifically for handling any failures at end of the chain:</p><pre>infix fun &lt;T&gt; Result&lt;T&gt;.otherwise(f: (String) -&gt; Unit) =<br>   if (this is Failure) f(this.errorMessage) else Unit</pre><p>Thus, we can now handle any failure with:</p><pre>parse(input) then ::validate then ::send otherwise ::error</pre><pre>fun error(message: String) = println(&quot;Error: ${message}&quot;)</pre><p>Finally (and this is optional) we could pipe the input into the railway by just passing in the first Success object:</p><pre>Success(input) then ::parse then ::validate then ::send otherwise ::error</pre><p>I prefer not seeing that Success at the beginning, so let’s introduce a pipe function named to that does the work for us:</p><pre>infix fun &lt;T,U&gt; T.to(f: (T) -&gt; Result&lt;U&gt;) = Success(this).then(f)</pre><p>I hope you will agree that our final implementation of the email sending module looks pretty concise:</p><pre>input to ::parse then ::validate then ::send otherwise ::error</pre><p>The complete example code is available as a <a href="https://gist.github.com/antonyharfield/1928d02a1163cf115d701deca5b99f63">Github Gist</a>. 👩🏻‍💻</p><p>That’s how I implemented Railway Oriented Programming in Kotlin — there may be better ways in which case I would love to hear from you in the comments.</p><p>It was a useful exercise to implement Result myself, but <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html">Kotlin now has a </a><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html">Result type baked in</a>, ready for you to use (as of 1.3), and it’s a bit more powerful than mine! For a start, it wisely replaces the String error message with an exception Throwable. It has a map function instead of then and an onFailure function instead of otherwise. I used infix functions for natural readability but I suspect hardcore Kotlin-ers will prefer how it looks with Kotlin’s built-in Result type:</p><pre>parse(input).map(::validate).map(::send).onFailure(::error)</pre><p>The only reason that you might <strong>not</strong> want to use the built-in Result type is that the compiler doesn’t allow it to be the return type of a function by default (which is exactly how you want need to use it!) — however, <a href="http://rustyrazorblade.com/post/2018/2018-12-06-kotlin-result/">it can be enabled by adding a compiler flag</a>.</p><p>Enjoy building your own railways in Kotlin and keep preserving the beauty of happy paths! 🚂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1bceed399e5" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/railway-oriented-programming-in-kotlin-f1bceed399e5">Railway Oriented Programming in Kotlin</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dialogflow web hooks: how to develop locally and deploy to Cloud Functions]]></title>
            <link>https://medium.com/@antonyharfield/dialogflow-web-hooks-how-to-develop-locally-and-deploy-to-cloud-functions-48839919e998?source=rss-ed3185eec7ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/48839919e998</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[google-app-engine]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[dialogflow]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <dc:creator><![CDATA[Antony Harfield]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 11:06:55 GMT</pubDate>
            <atom:updated>2019-03-18T07:10:48.895Z</atom:updated>
            <content:encoded><![CDATA[<p>When our team started building the <a href="https://nilateams.com/">Nila</a> chatbot at <a href="https://hackth.line.me/">LINE HACK 2018</a>, we knew as much as Jon Snow about how to build a web hook. Some of us had some experience of Firebase and writing Cloud Functions, so we assumed it was going to be quite easy, especially when we found the Inline Editor — but we ended up building the first version completely on <a href="https://glitch.com/">Glitch</a>, a live environment for running Node.js apps. While Glitch is great for learning, we could have made our life easier by setting up a local development environment.</p><p>This article is explains how to build a web hook by developing locally and deploying to the cloud. It’s a set of tips and tricks that will make web hook development faster, practical and safer:</p><ul><li>Faster — run locally, only deploy when you need to</li><li>Practical — debug your application with live requests from your web hook</li><li>Safer — linting and autocomplete from your favourite editor</li></ul><h3>1. Start with a template and run it locally</h3><p>While the focus is Dialogflow web hooks in this article, I suspect these steps are the same for developing any web hook. If you are using Dialogflow then you might start with the <a href="https://dialogflow.com/docs/fulfillment/configure#create_a_webhook_with_the_inline_editor">Inline Editor</a> for fulfilment. The first thing to do is grab that code and modify it to run locally.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/616228f70bc87c734ddeb3722aef1516/href">https://medium.com/media/616228f70bc87c734ddeb3722aef1516/href</a></iframe><p>In simpleServer.js, I have taken the Dialogflow fulfillment code from the Inline Editor, removed the Firebase specific code and added express to serve the web hook. You will need a package.json with the dependencies for express, dialogflow-fulfillment and actions-on-google. Run the web hook by node simpleServer.js and then open <a href="http://localhost:8080/">http://localhost:8080/</a> to check it is working.</p><h3>2. Use ngrok to serve local http to public https</h3><p><a href="https://ngrok.com/">Ngrok</a> is a free service that gives you a public secure https URL to your local web server. You can install ngrok globally (download binary or npm install global), but my preference is to install as a dev dependency:</p><pre>npm install ngrok --save-dev</pre><p>And then modify your package.json:</p><pre>  ...<br>  &quot;scripts&quot;: {<br>    &quot;tunnel&quot;: &quot;ngrok http 8080&quot;<br>  },</pre><p>Now anytime you want to create an https URL to your local dev environment, you just use npm run tunnel. Ngrok will run and create a https URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGQ_Z30W02cndqWyG0JUtA.png" /><figcaption>Running ngrok to obtain a public https URL for your local server</figcaption></figure><p>Now you can copy the https URL under “Forwarding” (highlighted in red) to be your fulfillment web hook in Dialogflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*vaNKYCyT_YZrRAPNxztwjQ.png" /><figcaption>Configure Dialogflow’s Fulfillment to use an ngrok forwarding URL</figcaption></figure><p>At this point I would test that everything is working by sending a “hello” in Dialogflow’s test console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*hjb66FtBwBD4G3ywZAIgGQ.png" /></figure><p>The reason I prefer to install as a dev dependency is that when another developer joins the team, they don’t need install anything extra — they can just use npm run tunnel to create their https URL.</p><p>You can quit ngrok using Ctrl-C (and it will stop serving your public URL). Each time you restart ngrok you will receive a new URL, which means that you will need to update the URL in the Dialogflow console. One way around this is to upgrade to one of ngrok’s paid plans.</p><h3>3. Reloading (nodemon) and debugging (VS Code)</h3><p>At this point you have a public URL that tunnels all the traffic to our local machine which is running a basic Dialogflow template. We are going to want to edit the code and see the changes instantly in our web hook (e.g. through the Dialogflow simulator).</p><p><a href="https://nodemon.io/">Nodemon</a> is Node.js’s best friend, restarting the server whenever it detects changes. Like ngrok, I install it as a dev dependency:</p><pre>npm install nodemon --save-dev</pre><p>And modify your package.json scripts again:</p><pre>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;nodemon --inspect simpleServer.js&quot;,<br>    &quot;tunnel&quot;: &quot;ngrok http 8080&quot;<br>  },</pre><p>Then start your dev environment with npm run dev.</p><p>The --inspect argument enables the debugger. In <a href="https://code.visualstudio.com/">VS Code</a>, you can create a debug configuration that works with nodemon as follows:</p><ol><li>On the “Debug” menu, select “Open Configurations” to open the launch.json file.</li><li>Use the “Add Configuration…” button to add a new “Node.js: Attach” debug configuration. The resulting configuration should look like this:</li></ol><pre>&quot;configurations&quot;: [<br>  {<br>    &quot;type&quot;: &quot;node&quot;,<br>    &quot;request&quot;: &quot;attach&quot;,<br>    &quot;name&quot;: &quot;Attach&quot;,<br>    &quot;port&quot;: 9229<br>  }<br>]</pre><p>To test this out, press F5 to start debugging (you should see Debugger attached. on the Terminal). Then place a breakpoint in your welcome() agent. Go to the Dialogflow test console and say “hello” again. The debugger will stop the execution at your breakpoint.</p><h3>4. Code style (optional)</h3><p>While we are setting up VS Code, it might be a good time to setup a linter. I like to use the <a href="https://standardjs.com/">JavaScript Standard Style</a> because it is simple — I don’t like 100% of the rules but it is close enough and I do love the fact that it is a fixed style so there is no arguing/wasting time tweaking ESLint options. It’s also easy to install:</p><pre>npm install standard --save-dev</pre><p>Add a lint command to your package.json:</p><pre>&quot;scripts&quot;: {<br>    ...<br>    &quot;lint&quot;: &quot;standard&quot;<br>  },</pre><p>Then you can check your code with npm run lint or fix all the errors with npm run lint -- --fix.</p><p>However, you probably want the fix feature in your editor. VS Code has <a href="https://github.com/standard/vscode-standardjs">an extension for Standard</a>. After you install this, add {&quot;key&quot;: &quot;cmd+l&quot;, &quot;command&quot;: &quot;standard.executeAutofix&quot;} to your keybindings.json, changing cmd+l for whichever keyboard shortcut you would like to use. Now you can hit that shortcut to keep your code in the Standard style. :)</p><h3>5. (a) Deployment to Cloud Functions for Firebase</h3><p>After saying goodbye to Cloud Functions by removing them in step 1, it’s time for us to go back to deployment. Recall that our original Cloud Functions code looked like this:</p><pre>exports.dialogflowFirebaseFulfillment = <br>    functions.https.onRequest((request, response) =&gt; { ... })</pre><p>It turns out that an express app is also a function that takes a request/response, so it satisfies Cloud Functions requirements for (request, response) =&gt; { ... } .</p><p>Hence we can split our existing simpleServer.js into server.js and app.js. The app.js file contains our application which can either be run on Node.js or Cloud Functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*JnvBfKOExcw0QysR-7rNhA.png" /><figcaption>Running an express app through Cloud Functions</figcaption></figure><p>This architecture gives us the ability to run locally with ngrok and node when we are developing and to deploy to Cloud Functions for production.</p><p>The result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a03c0733a4c9cfb1977554d5b8dc01f/href">https://medium.com/media/2a03c0733a4c9cfb1977554d5b8dc01f/href</a></iframe><p>Don’t forget to install the dependencies for Firebase: npm install firebase-functions firebase-admin --save.</p><h4>Next, the deployment…</h4><p>If you are not familiar with deploying Cloud Functions then you can take a look at the <a href="https://firebase.google.com/docs/functions/get-started">Firebase documentation</a>.</p><p>Basic steps:</p><ol><li>Install Firebase CLI: npm install -g firebase-tools@latest</li><li>Create firebase.json containing:<br>{ &quot;functions&quot;: { &quot;source&quot;: &quot;.&quot;, &quot;predeploy&quot;: [&quot;npm run lint&quot;] } }</li><li>Run firebase use --add inside your project folder to select your Firebase project and assign an alias.</li><li>Edit your package.json to point the “main” script to “cloudFuncs.js”:<br>&quot;main&quot;: &quot;cloudFuncs.js&quot;,</li><li>If you want to use Node 8 (you probably do!) then also add this to package.json:<br>&quot;engines&quot;: { &quot;node&quot;: &quot;8&quot; },</li><li>Try to deploy: firebase deploy --only functions</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*44qbbRdnGKBsgv2HuW2MVA.png" /><figcaption>Deploy a web hook to Cloud Functions on Firebase</figcaption></figure><p>If the deploy completes successfully then you can open the test endpoint in your browser at: <a href="https://us-central1-[yourprojectid].cloudfunctions.net/app/">https://us-central1-</a><a href="https://us-central1-[yourprojectid].cloudfunctions.net/app/"><em>[yourprojectid]</em></a><a href="https://us-central1-[yourprojectid].cloudfunctions.net/app/">.cloudfunctions.net/app/</a> (note, the trailing slash / is required for express’s route matching).</p><p>And the web hook URL is <a href="https://us-central1-[yourprojectid].cloudfunctions.net/app/dialogflow.">https://us-central1-</a><a href="https://us-central1-[yourprojectid].cloudfunctions.net/app/dialogflow."><em>[yourprojectid]</em></a><a href="https://us-central1-[yourprojectid].cloudfunctions.net/app/dialogflow.">.cloudfunctions.net/app/dialogflow.</a></p><p>Finally, add a deploy script to your package.json, such that you can run npm run deploy-cf to deploy to Firebase at anytime:</p><pre>  &quot;scripts&quot;: {<br>    ...<br>    &quot;deploy-cf&quot;: &quot;firebase deploy --only functions&quot;<br>  },</pre><h4>Local Node.js vs Cloud Functions</h4><ul><li>Environment variables need to be set via the firebase command. Example:<br>firebase functions:config:set apiKey=&quot;THE API KEY&quot;</li><li>Automate getting and setting the environment variables with a script following <a href="https://medium.com/@AllanHasegawa/setting-config-for-firebase-cloud-functions-with-json-136f455e7c69">the advice of Allan </a><a href="https://medium.com/@AllanHasegawa?source=user_popover">Hasegawa</a>.</li><li>Global variables won’t behave as you expect:<br>“There is no guarantee that the state of a Cloud Function will be preserved for future invocations.” <a href="https://cloud.google.com/functions/docs/bestpractices/tips">https://cloud.google.com/functions/docs/bestpractices/tips</a></li></ul><h3>5. (b) Deployment to Google App Engine (bonus!)</h3><p>Google recently added more flexible scaling features to App Engine and support for Node 10. The difference between running your web hook on App Engine and Cloud Functions is quite subtle. From what I understand, Firebase is potentially running lots of Cloud Functions together on lots of instances and it manages which ones are deactivated when not being used. App Engine on the other hand runs your app on one or more dedicated instances that can be scaled automatically depending on demand.</p><p>When demand is zero, App Engine can scale to zero instances — this is the default which is good for managing costs when you are experimenting. <a href="https://cloud.google.com/appengine/quotas#Instances">App Engine has free quotas</a> (28 instance hours per day) which mean you might not incur any costs for a single instance (but don’t quote me on that!).</p><p>I found deployment to App Engine to be a lot easier than Cloud Functions.</p><ol><li>Install the gcloud command line tool — see <a href="https://cloud.google.com/sdk/gcloud/">documentation</a></li><li><a href="https://console.developers.google.com/apis/library/cloudbuild.googleapis.com">Enable the Cloud Build API</a> for your project on Google Cloud Platform’s API &amp; Services page.</li><li>Create a file named app.yaml in the root of your project, containing:<br>runtime: nodejs8<br>or alternatively for the latest Node.js has to offer:<br>runtime: nodejs10<br>(If you choose nodejs10 then you need to modify the node version in “engines” of package.json too.)</li><li>Deploy: gcloud app deploy --project <em>[yourprojectid]</em></li></ol><p>If the deploy was successful then open your browser at https://<em>[yourprojectid]</em>.appspot.com and your web hook will be available at https://<em>[yourprojectid]</em>.appspot.com/dialogflow.</p><p>Once again, tidy up with a deploy script to your package.json so that you can run npm run deploy-ae to deploy at anytime:</p><pre>&quot;scripts&quot;: {<br>    ...<br>    &quot;deploy-ae&quot;: &quot;gcloud app deploy --project <em>[yourprojectid]</em>&quot;<br>  },</pre><h3>Summary</h3><p>You should now be able to:</p><ul><li>Create a local development environment for your web hook project, with of linting and debugging capabilities— in your favourite browser</li><li>Serve your local environment as public https URL using ngrok</li><li>Deploy the application to Cloud Functions on Firebase AND to Google App Engine</li></ul><p>This project started out as a web hook for Dialogflow, but the techniques discussed would work for any web hook project.</p><p>You can find all the code on github: <a href="https://github.com/antonyharfield/webhook-template">webhook-template</a>. I use this as the starting point for any web hook project — hope you find it useful too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48839919e998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift-ly becoming a Vapor 3 web developer on Windows]]></title>
            <link>https://medium.com/@antonyharfield/swift-ly-becoming-a-vapor-3-web-developer-on-windows-68b149a8f038?source=rss-ed3185eec7ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/68b149a8f038</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Antony Harfield]]></dc:creator>
            <pubDate>Mon, 25 Jun 2018 11:37:04 GMT</pubDate>
            <atom:updated>2018-06-26T02:39:12.378Z</atom:updated>
            <content:encoded><![CDATA[<p>Last summer I started building <a href="http://grader.mobcomlab.com/">a web application in Swift</a>, using the excellent <a href="https://vapor.codes/">Vapor</a> framework. Since then I have been trying to persuade students to take up a Swift web project. Mostly they are reluctant because they “don’t have a Mac”. To which I reply, “run it on Docker”. And then I never see them again! So I thought I would try to setup Docker on Windows myself and go through the process of building and running a Vapor web app.</p><h4><em>Prerequisites</em></h4><ul><li>Docker for Windows requires Windows 10 (64-bit, Pro or Professional) because it uses Microsoft’s Hyper-V system. (If you have Windows 7 or 8 then you will have to use Docker Toolbox instead.)</li><li>Memory — I was able to get this working on 4GB of RAM(!), but you will get much better performance with 8GB or more.</li></ul><h4>Step 1: Setup Docker for Windows</h4><p>Download <a href="https://www.docker.com/docker-windows">Docker for Windows</a> and install it. After your installation, open a Command Prompt window and enter docker —-version to check that docker is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-j39pVM6XU4zUIjG_ZA6g.png" /></figure><p>Next, open your Docker settings and go to the Network page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dEJ8ydS4ZAyhdbJtTixFA.png" /></figure><p>Make a note of the IP address, most likely it will be 10.0.75.1. This will be the address of your website later!</p><p>If your PC is not the speediest of creatures then you can reduce the CPU cores or RAM usage on the Advanced tab of the Docker settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzrO1RfMY4LVDJ2zVohq8g.png" /></figure><h4>Step 2: Install an editor with Swift support (optional)</h4><p>I’m going “all in” on Microsoft products today, so I installed <a href="https://code.visualstudio.com/">Visual Studio Code</a> (an open source text editor — Visual Studio’s cool younger brother) because it supports a ton of languages. Another choice is <a href="https://atom.io/">Atom</a>. Both are good for editing the languages we need: Swift, Leaf, HTML, JS, CSS.</p><p>On the Welcome page, there is a section under “Customize” entitled “Tools and languages”. From here, search for “swift” and I picked the one with the most installs (Swift Language by Martin Kase).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3eHvN0M5_PGbcHwBIxLDw.png" /></figure><p>This will give us syntax highlighting for Swift files. Unfortunately there isn’t any way to get Swift code completion on Windows yet (as far as I am aware) so VS Code is not going to have the power of Xcode any time soon.</p><h4>Step 3: Build a Docker container for running Swift/Vapor</h4><p>You are going to create a separate folder for your Dockerfile that builds a Vapor image. Later, we will create another folder for each project.</p><p>a) Create a folder called vapor (I will assume you did this inside the Documents folder).</p><p>b) Create a file called Dockerfile inside the folder (no extension), and copy the following code into the file.</p><pre>FROM ubuntu:16.04</pre><pre># Install CURL<br>RUN apt-get update &amp;&amp; \<br>    apt-get -y install curl &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*;</pre><pre># Get Vapor repo including Swift<br>RUN curl -sL <a href="https://apt.vapor.sh/">https://apt.vapor.sh</a> | bash;</pre><pre># Installing Swift &amp; Vapor<br>RUN apt-get update &amp;&amp; \<br>    apt-get -y install swift vapor &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*;</pre><pre>WORKDIR /app</pre><p>The Dockerfile is the recipe for building a Docker image, which can then be used to run commands in a container. You can see that the image is based on Ubuntu 16.04 and installs Swift and Vapor.</p><p>c) Back on the Command Line, go to your Documents folder (cd Documents) and then use docker to build your image:</p><pre>docker build -t myvapor vapor</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73Gb8Z2GqScPR3Tk3XnFMQ.png" /><figcaption>Get a cup of tea… this is going to take a while!</figcaption></figure><p>d) Test that you can run vapor:</p><pre>docker run --rm myvapor vapor version</pre><p>All being well, you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oySjdcSz8pZ1I4XjdBYsqg.png" /></figure><h4>Step 4: Create a Vapor project</h4><p>I will assume you still have the Command Prompt open and you are currently in the Documents folder.</p><p>a) Run a new Docker container interactively, connecting your Documents folder to the /app folder and forwarding port 8080.</p><pre>docker run --rm -it -v C:\Users\Ant\Documents:/app -p 8080:8080 myvapor</pre><p>(The first time you run this, Docker for Windows should notify you to share the C:\ drive. You must agree to this.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJNQtIAVF-WLIs8tm-KYTg.png" /><figcaption>“Share it”</figcaption></figure><p>b) Now we are inside the container, use the Vapor toolbox to create a new project.</p><pre>vapor new HelloWorld</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5nNWBJuRWeH6VznzcQkIw.png" /></figure><p>c) Move into the HelloWorld folder and build the project.</p><pre>cd HelloWorld<br>vapor build</pre><p>If it builds successfully then you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgTczag1cZkjQ6TGqDQMgg.png" /></figure><p>d) Run the project. Note that we must specify the hostname else we will not be able to see if from outside the container.</p><pre>vapor run serve --hostname=0.0.0.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UFfMkFuEJj3IcDaAHBCzA.png" /></figure><p>e) Open your web browser at http://10.0.75.1:8080/hello. Note, you cannot access it on localhost because it is running inside the Hyper-V virtualisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*YD8uVX9eFoUBgW4NjVbfTQ.png" /></figure><p>That’s it, you are running Swift and Vapor on your Windows machine!</p><h4>Step 5: Improving the build/run workflow</h4><p>You already have completed all the steps required to build and run a Vapor web app, but all those commands are quite a lot to remember/type everytime you want to build and run. In just a moment, I’m going to create a batch file to simplify the commands. But first, I would like to show you that you can run the build command directly from the Command Prompt:</p><pre>docker run --rm -v C:\Users\Ant\Documents\HelloWorld:/app myvapor vapor build</pre><p>Note that we connect our project folder (HelloWorld) directly, then the container starts in that directory and runs the build command. Similarly, we can run the project:</p><pre>docker run --rm -v C:\Users\Ant\Documents\HelloWorld:/app -p 8080:8080 myvapor vapor run serve --hostname=0.0.0.0</pre><p>We can create a batch file on Windows to make typing these commands easier. Create a new file called vapor.bat in your HelloWorld folder, then copy in the following code.</p><pre>@echo off<br>docker run --rm --name vapor -v %cd%:/app -p 8080:8080 myvapor vapor %*</pre><p>Now if you are in your HelloWorld folder, you can build and run as follows (directly from Command Prompt):</p><pre>vapor build<br>vapor run serve --hostname=0.0.0.0</pre><p>Next, move vapor.bat to your vapor folder and <a href="https://www.computerhope.com/issues/ch000549.htm">add that folder to your Windows path</a>. You are good to run these commands from any of your project folders now.</p><p>Important note: when you do a vapor run serve, if you use Ctrl-c to stop the process then you will see the a “terminate process” message. Unfortunately this does not kill the child process (vapor), so you need to manually use docker stop vapor. Else when you run again you will get an error that port is already in use. (Maybe someone can suggest a better way to end the child process automatically so that I can use Ctrl-c similar to *nix?)</p><h4>Next steps</h4><p>If you need to update the version of Vapor, or the version of Swift, then you will need to rebuild the myvapor container as explained in Step 3(c).</p><pre>docker build --no-cache -t myvapor vapor</pre><p>When you are not developing then you can quit Docker for Windows from the tray to free up resources for other tasks, and start it up again as necessary. As long as you have Docker for Windows running, you can make use of your vapor batch file to run the Vapor toolbox. For example, you can create a new web project using a template by opening the Command Prompt and running:</p><pre>vapor new --template=<a href="https://github.com/antonyharfield/vapor-web-template">https://github.com/antonyharfield/vapor-web-template</a> WebTemplate</pre><p>With this magic complete, your friends will think you have got a native Vapor toolbox running on Windows! Go ahead and impress your Mac friends with your awesome Swift skills. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68b149a8f038" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>