<?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 Davor Hafnar on Medium]]></title>
        <description><![CDATA[Stories by Davor Hafnar on Medium]]></description>
        <link>https://medium.com/@dhafnar?source=rss-cbc518370dd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jbT7cUEkpkNtTHk8o2TQ_w.png</url>
            <title>Stories by Davor Hafnar on Medium</title>
            <link>https://medium.com/@dhafnar?source=rss-cbc518370dd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:20:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhafnar/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[Building a Serverless RAG System with BigQuery and Gemini]]></title>
            <link>https://medium.com/@dhafnar/building-a-serverless-rag-system-with-bigquery-and-gemini-12e66328f622?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/12e66328f622</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Sun, 19 May 2024 11:15:39 GMT</pubDate>
            <atom:updated>2024-12-01T20:32:19.367Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A guide to building a tool to ‘ask questions’ to your BigQuery data, with code, including a simple frontend.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXV4gXmIg6kjUSOIhPnVjA.png" /><figcaption>Sample usage of the system we are building. The user asks a question and gets back both the results of the vector search and a response from Gemini. We are using a BigQuery Public dataset with BBC articles from the mid-2000s for the demo.</figcaption></figure><blockquote>Update: I also made a video on the topic, available <a href="https://youtu.be/kGHPpsrFjGs?si=051xmCH9aYAiImY5">here</a>.</blockquote><h4>Introduction</h4><p>In this article, we’ll walk through the process of building an end-to-end Retrieval-Augmented Generation (RAG) system on top of BigQuery. This system allows internal users to ask questions and receive answers from your data in plain language. We will be using the Google Cloud stack, including BigQuery, Cloud Functions, and Gemini. Our solution will be serverless, ensuring a pay-as-you-go model that optimizes cost efficiency.</p><p>There are a lot of use cases for such a system, including <strong>knowledge bases</strong>, <strong>customer support tickets</strong>, <strong>onboarding</strong>, <strong>documentation</strong>, <strong>tenders</strong>, and more.</p><h4>Who is the intended audience</h4><p>Due to the nature of BigQuery, which is an analytical and not a production database, the solution is intended for limited audiences, such as company employees, or small groups of B2B clients. BigQuery excels in large-scale data analysis and complex queries, making it ideal for internal use where employees need insights from large datasets. It is not suited for high-frequency, low-latency transactions typical of production environments.</p><h4>I am not a data scientist, should I attempt this?</h4><p>The entire process uses two types of foundational models, meaning models that generalize so well that you don’t need to perform any additional training on them. The process of building a described solution requires only engineering knowledge. Intuition about vector search and embeddings is welcome, and there is a quick chapter explaining it in this article.</p><p>The models used are described below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*ci_Ki7RFrLtV3eKGcV1qXQ.png" /><figcaption>Both the embedding model, which takes text inputs and returns vector embeddings, and the generative model (Gemini) are already trained and consumed as basic REST APIs.</figcaption></figure><p>The AI solution we are building without any training is, I believe, a part of the important upcoming trend, nicely announced by A. Gutmans [1]:</p><blockquote>We are entering a post-training era in which application developers will drive the bulk of the innovation in applying generative AI to solve business problems.</blockquote><h4><strong>Solution Design</strong></h4><p>Our RAG system involves several key components:</p><p>1. <strong>Frontend</strong>: Where users write their questions, see the answer and search results.<br>2. <strong>Cloud Function</strong>: Serves as a REST API backend, and interacts with BigQuery and Gemini.<br>3. <strong>BigQuery</strong>: Holds the data, and enables and performs the vector search.<br>4. <strong>Gemini</strong>: Generates the answer to the user’s question based on the results of the vector search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*gsZIafrkSBHWi_v9Bg3Xlw.png" /><figcaption>Solution Design for our serverless RAG on Google Cloud</figcaption></figure><h3>Basic intuition for vector search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYMK489QyZ2_kW85r4Ep9Q.png" /><figcaption>Vectors are arrays of numbers that are assigned using an ML model in a way that reflects the relationship between words in real life. Source and more info: [2]</figcaption></figure><p>Vector embeddings are a way to represent words or phrases as arrays of numbers (vectors) in a continuous space. These vectors capture the semantic meaning of the words, so similar words are placed closer together in this space. For example, words like “king” and “man” would be near each other, while “king” and “apple” would be far apart. This mapping is done using a foundational model that generalizes to all types of data, learning relationships from large text datasets.</p><p>When a user searches for a term like “queen,” the search system converts “queen” into its corresponding vector. It then looks for vectors in the database that are closest to the “queen” vector, meaning they have similar meanings. For instance, the vector for “king” might be very close to “queen,” so “king” would appear as a top search result. This method allows the search system to return results based on meaning rather than just matching keywords, providing more relevant and accurate results.</p><h3>The BigQuery Part</h3><p><strong>Add an Embedding Model to BigQuery<br></strong>First, we need to add an embedding model to BigQuery. This model will convert text into vector embeddings, which are numerical representations of the text. To do this, you need to run the query below. Make sure that you have Vertex AI API enabled in your project and that the user running the query has permission to access it.</p><pre>CREATE OR REPLACE MODEL `my_project.my_dataset.textembedding`<br>REMOTE WITH CONNECTION `us.vertex_connection`<br>OPTIONS(ENDPOINT = &#39;textembedding-gecko@003&#39;);</pre><p>The result of the query is a ‘link’ between BigQuery and the API in Vertex AI which allows us to use the model directly in our queries. We are still charged just for the usage of the model, as all we have in BigQuery is a way to directly call the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*5qS7VUqjg_aCszuC" /><figcaption>The model we named ‘textembedding’ can now be referenced directly in BigQuery.</figcaption></figure><h4><strong>Add a Column with Vector Embeddings</strong></h4><p>Next, we add a column with vector embeddings to our table. This involves generating embeddings for the text data we have. We will select the table <em>bigquery-public-data.bbc_news.fulltext </em>from BigQuery public datasets for our example and create a new table <em>bbc_searchable</em> in our dataset. As the two columns we are using, content and titles can repeat in the dataset, we are also doing a <em>group by</em> for deduplication.</p><pre>CREATE OR REPLACE TABLE my_dataset.bbc_searchable AS<br>SELECT content, title, ml_generate_embedding_result<br>FROM<br>ML.GENERATE_EMBEDDING(<br>  MODEL `my_project.my_dataset.textembedding`,<br>  (SELECT body as content, title<br>  FROM `bigquery-public-data.bbc_news.fulltext`<br>  GROUP BY body, title),<br>  STRUCT(TRUE AS flatten_json_output, &#39;SEMANTIC_SIMILARITY&#39; as task_type)<br>);</pre><p>The result of the query is in the table below. Vector embeddings are in the column <em>ml_generate_embedding_result </em>and are in the form of an array of floats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*F5bK4b8yENQvuj_BnXnCTg.png" /><figcaption>We have taken two columns from the BBC dataset and added a vector embedding, over which we can perform a vector search.</figcaption></figure><h4>Perform Vector Search</h4><p>Finally, we perform a vector search to find the most relevant documents based on the user’s query. In this example, we are using the search term ‘<em>what did it say about Slovenia</em>’ to see if any articles referenced this country.</p><p>Note that to perform vector search, the user’s question needs to be embedded using the same model we used to embed the source data, as the searches use vectors, not strings. To achieve that, we can create a nested query that does the embedding on the fly. The <em>top_k </em>parameter specifies the number of results you want returned.</p><p>Note that this part will be performed from Python using a version of this query where parameters are dynamically inserted.</p><pre>SELECT base.title, base.content<br>FROM VECTOR_SEARCH(<br> TABLE `my_project.my_dataset.bbc_stories_emb`, &#39;ml_generate_embedding_result&#39;,<br> (<br> SELECT ml_generate_embedding_result as embedding_col<br> FROM ML.GENERATE_EMBEDDING<br> (<br> MODEL `my_project.my_dataset.textembedding`,<br> (SELECT &quot;what did it say about Slovenia&quot; as content),<br> STRUCT(TRUE as flatten_json_output)<br> )<br> ),<br> top_k =&gt; 5<br>);</pre><p>The results of the query are displayed below. Note that even though there was no mention of Slovenia in the articles, the vector search returned articles referencing Slovakia, Croatia, and Yugoslavia.</p><p>This emphasizes the two properties of our search. First, it will always return the specified number of matches, with the closest matches being on top. Second, the search uses complex relationships that derive from the fact that the embedding model was trained on vast amounts of data and has an understanding of real-world relationships.</p><p>This is how we can understand that it matched Slovenia with Croatia (its neighbour) or Yugoslavia (the country Slovenia split from in the 1990s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tuniQTCufBMERQ1P" /><figcaption>Slovenia was not mentioned in the articles, so the search returned the ones that were most closely related to the search term.</figcaption></figure><h3>The API and Gemini Part</h3><h4>Backend Design</h4><p>The REST API will handle the user’s question and the number of results to return. It will send the search results to Gemini, which will generate the final answer. We will write the API as a Python Cloud Function, using BigQuery and Gemini client libraries.</p><p>The design is outlined below, including the JSON input and output of the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO_nutrY7D4xdl7DRwJMog.png" /><figcaption>Design of our backend. The client sends the user’s question, which is forwarded as a prompt for the vector search on BigQuery. The question and results of vector search are then sent to Gemini. In the last step, Gemini’s answer and the results of the vector search are returned to the client. See the GitHub link for basic implementation.</figcaption></figure><h4>Generating the Answer with Gemini</h4><p>Using the Gemini model, we can generate a human-readable answer based on the search results. Here’s a sample prompt and model configuration:</p><pre>system_instruction = &quot;You are helping with summarization of articles. (...)&quot;<br>prompt = (f&quot;{user_query}. Answer based solely on &quot;<br>          f&quot;this data from BBC articles: {results_list}&quot;)<br>model = GenerativeModel(model_name=&#39;gemini-1.5-pro-preview-0514&#39;,<br> generation_config={<br> &quot;temperature&quot;: 0.0<br> },<br> system_instruction=system_instruction)<br>gemini_response = model.generate_content(prompt).text</pre><p>We need to write the instructions for the model and send both the query and the data returned from the BigQuery vector search to Gemini. The instructions shown are shortened, the whole instructions used are in the GitHub link at the end of the article.</p><p>Note that the instructions and choice of the model will have a critical impact on the usability of the generated text. You can use the ‘flash’ version of the Gemini model here, which enables greater speed. In contrast, the ‘pro’ version takes significantly longer and costs more, but offers better reasoning capabilities and can provide more accurate answers.</p><h4>Limitations</h4><p>For simplicity, our example does not address security. Ensure proper authentication for any production implementations. The article also doesn’t cover GCP permissions needed for each step. Depending on your approach, multiple permissions for users and API access will likely be required. Additionally, fine-tuning instructions and prompts will be necessary to achieve a satisfactory solution; here, I made basic adjustments sufficient for a proof of concept.</p><h4>Conclusion</h4><p>With the latest additions to BigQuery, you can build a pay-as-you-go, low-maintenance RAG system that leverages the power of Gemini to massively simplify accessing stored data. This system can enhance various business processes, from customer support (where it could directly provide a blueprint for an answer) to internal documentation, making information retrieval more efficient and user-friendly.</p><h4>References</h4><ol><li><a href="https://cloud.google.com/blog/products/ai-machine-learning/the-rise-of-geneng-how-ai-changes-the-developer-role">The rise of GenEng: How AI changes the developer role | Google Cloud Blog</a></li><li>Vector Databases simply explained! (Embeddings &amp; Indexes) <a href="https://www.youtube.com/watch?v=dN0lsF2cvm4&amp;t=139s">https://www.youtube.com/watch?v=dN0lsF2cvm4&amp;t=139s</a></li></ol><p>I originally developed the solution for the presentation at the <a href="https://gdg.community.dev/gdg-ljubljana/">Google Developers Group Ljubljana</a>. The <a href="https://github.com/dhafnar/rag-bq-gemini">entire code is available on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12e66328f622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to not call everything just ‘AI’: A business communication cheat sheet]]></title>
            <link>https://medium.com/@dhafnar/the-term-ai-is-not-specific-enough-anymore-here-is-how-to-break-it-down-ee4484303e14?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee4484303e14</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 15:59:58 GMT</pubDate>
            <atom:updated>2023-03-11T09:59:57.178Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Specific terms like computer vision, natural language processing, generative AI and predictive analytics make more sense than calling everything just &#39;AI’.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P15xtc747b7UU-ju05X3tQ.png" /><figcaption>It might be time to break apart the term AI in business communication. (Source: DALL-E)</figcaption></figure><p>In recent months it started to feel <strong>that the term AI is too broad and overused</strong> to <strong>explain what underlying technology we are talking about</strong>.</p><p>Here is what I mean: we are reading, at the same time, about how <strong>AI</strong> is <a href="https://abcnews.go.com/Health/wireStory/amid-chatgpt-outcry-teachers-inviting-ai-class-97179746">writing homework</a> essays; how it is <a href="https://www.businessinsider.com/layoffs-today-trends-ai-data-companies-jobs-algorithms-chatgpt-2023-2">deciding who to fire</a>; how it <a href="https://www.cancer.gov/news-events/cancer-currents-blog/2022/artificial-intelligence-cancer-imaging#:~:text=Finding%20cancer%20early&amp;text=Scientists%20have%20developed%20AI%20tools,this%20area%20is%20quickly%20evolving.">helps diagnose cancer</a>; and how it is <a href="https://www.vectornator.io/blog/will-ai-replace-artists/">behaving as an artist</a> by generating original images.</p><blockquote>No, it is not ChatGPT deciding who gets to keep their job. And it does not help diagnose cancer.</blockquote><p>The fact is that, while conforming with the basic definition of AI (“<a href="https://www.britannica.com/technology/artificial-intelligence">ability of a digital computer or computer-controlled robot to perform tasks commonly associated with intelligent beings</a>”), in the four instances above, the <strong>underlying technologies and use cases are fundamentally different</strong>. No, it is not ChatGPT deciding who gets to keep their job. And it does not help detect cancer.</p><p>So lets look at what technologies we could attribute the developments above instead of just ‘AI’:</p><blockquote>writing an essay -&gt; Natural language processing (not just ‘AI’)</blockquote><blockquote>deciding who to fire -&gt; Predictive analytics (not just ‘AI’)</blockquote><blockquote>helping diagnose cancer -&gt; Computer vision (not just ‘AI’)</blockquote><blockquote>creating art -&gt; Generative AI (not just ‘AI’)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkdcnTFsb19woMDrRBM0oA.png" /><figcaption>Calling everything AI increasingly feels like mixing apples and oranges. (Source: DALL-E)</figcaption></figure><p>Without going into the nitty gritty details of how a specific technology works, <strong>especially in business (non-academic) communication</strong>, we can use this <strong>cheat sheet</strong> to escape using AI for everything.</p><p>So when writing about AI in everyday and business communication feel free to use:</p><h3>Computer vision</h3><p><em>when talking about anything to do with AI image recognition;</em></p><h3><strong>Natural language processing (NLP)</strong></h3><p><em>when talking about anything to do about AI chatbots, translations or text in general;</em></p><h3><strong>Generative AI</strong></h3><p><em>when talking about AI generating original content, like images (for text, it’s better to use NLP);</em></p><h3><strong>Predictive analytics</strong></h3><p><em>when talking about predicting any kind of future events based on historical data.</em></p><p>There are <a href="https://www.cs.bham.ac.uk/~jxb/IAI/w2.pdf">multiple academic</a> and <a href="https://www.ibm.com/topics/artificial-intelligence">historical distinctions</a> of AI and its subsections, but they don’t appear to be useful for introducing AI into everyday and business communication.</p><p>The fact is that using the term AI is about as useful in describing a technology in 2023 as is ‘high definition’ in describing a video resolution. It is technically correct, but just not specific enough anymore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee4484303e14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key openEHR benefit explained in 5 minutes (with pictures)]]></title>
            <link>https://medium.com/@dhafnar/key-openehr-benefit-explained-in-5-minutes-with-pictures-3c36d5693eb7?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c36d5693eb7</guid>
            <category><![CDATA[e-health-industry]]></category>
            <category><![CDATA[openehr]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 09:02:59 GMT</pubDate>
            <atom:updated>2021-12-01T09:08:49.632Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Answers to questions like ‘what is openEHR?’ often get very technical. I wrote this article as a simple illustration that shows why openEHR makes sense, aimed at those who don’t need to understand this healthcare standard specification in detail.</em></p><h3>1. Saving and viewing the patient’s temperature</h3><p>Doctor takes a patient’s temperature and logs it into the system using <em>Program for doctors</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*zS0I9gCTkQ8N0B4YiNv8hg.png" /><figcaption>Image source: Pexels</figcaption></figure><p>Say that this <em>Program</em> saves the temperature into a table like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ZkC2z0zaPtLUkPtySBZrhg.png" /></figure><p>Information for multiple measurements can then be viewed within the same <em>Program</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*6Inm60sj9ENeuHBuAMdpXQ.png" /></figure><h3>2. After five years, it’s time for a new Program</h3><p>The hospital has decided to use a different <em>Program for doctors</em> — maybe it’s better, maybe it’s cheaper, or maybe the previous one just isn’t being maintained anymore.</p><p>This new <em>Program</em> saves the same information in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*xUvyjVsIRpLEdWtmDNDUTA.png" /></figure><p>If you want to <strong>import and</strong> <strong>use the data saved by the first Program</strong> to be used with the second Program you are in for a tedious game of ‘<strong>spot the difference’</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*YcC8muoOheGW2n6VvVBofA.png" /></figure><p>And … that is a lot of work to read a simple measurement in a different <em>Program for doctors*</em>.</p><p>Now imagine mapping (‘translating’) a real-life database with years worth of patient data from one format to another … without losing or misinterpreting any important information.</p><h3>3. How would using openEHR help</h3><p>If both <em>Programs for doctors</em> were <strong>based</strong> on openEHR standard specification that ‘<em>describes the management and storage, retrieval and exchange of health data</em>’ <strong>they would have saved the data in the same way.</strong></p><p>In our illustration, that means <strong>they would both use the same table design</strong>* to record the patient’s temperature. No mappings would be needed, and there would be <strong>no chance for anything to get lost or misinterpreted</strong>.</p><p>And that is, in five minutes, the core advantage of <em>Programs for doctors</em> being based on openEHR.</p><p>For more info, you might want to check out <a href="https://en.wikipedia.org/wiki/OpenEHR">openEHR on Wikipedia</a>.</p><blockquote>Alternatively, instead of switching Programs, imagine you would like two different Programs for doctors to use the exact same table (and show the exact same data). They can do that if they save the data in the same way.</blockquote><p><em>*Technical note: I am focusing on table design for simplification purposes. Interoperability is achieved using different methods in openEHR.</em></p><p>P. S.: I am using the term <em>Program for doctors</em> for simplification. A more proper term would, of course, be <em>Program for healthcare workers</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c36d5693eb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to instantly recover a table in Google BigQuery]]></title>
            <link>https://medium.com/@dhafnar/how-to-instantly-recover-a-table-in-google-bigquery-544a9b7e7a8d?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/544a9b7e7a8d</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[backup]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 06:08:05 GMT</pubDate>
            <atom:updated>2019-10-19T06:34:22.575Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you need to Ctrl-Z (undo) after something went wrong, here are a couple of ways to get your data back.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btLSGtIzraDwCmlsCopzOg.png" /></figure><h3>How much time do you have?</h3><p>Google gives you <strong>7 days of history for existing tables</strong> and <strong>2 days for deleted tables </strong>(<a href="https://cloud.google.com/solutions/bigquery-data-warehouse#backup_and_recovery">source</a>). Sow how to quickly restore the data?</p><p><strong>Important</strong><em>: Get familiar with the code by running it on dummy data before relying on it. The article is written to help and the author takes no responsibility for the cost incurred or lost data as a result of using the instructions from this article. Also, mind that this article is </em><strong><em>current as of October 2019</em></strong><em> (things will likely work differently in the future.)</em></p><h3>2. Restore using the console (no query cost)</h3><p>If the cost you incur by querying while restoring is an issue, you can use the Cloud Shell. Opening it is simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7PTHwMs5zo1QIy4b9kvXqg.png" /><figcaption>Select the right project, open the console, issue the command.</figcaption></figure><p>You will need to convert the time you want to go back to into a Unix timestamp — you can <a href="https://www.google.com/search?q=convert+current+date+to+milliseconds">find a converter here</a>. I am using 1577833205000 as a placeholder.</p><p>So, to restore data from a specific time in the past and save it to a new table:</p><pre>bq cp dataset.table@1577833205000 dataset.new_table</pre><p>This command works also on <strong>deleted tables</strong>, but only for 2 days since deletion. It also works for <strong>partitioned tables</strong>.</p><p>For overwriting an existing table (when the table wasn’t deleted) just enter the same table name twice:</p><pre>bq cp dataset.table@1577833205000 dataset.table</pre><p>You will be asked if you want to overwrite the table. Just enter “y” for yes.</p><p>Note that if you are undeleting a table, the second command won’t work: you need to specify a new name for the table, and then copy that table in the place of the old one.</p><h3>2. Restore data by using SQL (incurs query cost)</h3><h4><strong>2.1 Run a query on a table as it was one hour ago</strong></h4><p>You may want to simply query a table as it was one hour ago and decide what to do with the result later:</p><pre><strong>SELECT</strong><br>  *<br><strong>FROM</strong><br>  `project.dataset.table`<strong>FOR SYSTEM_TIME AS OF</strong><br>TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)</pre><p>All you need to do is add <strong>FOR SYSTEM_TIME AS OF </strong>to the end of the basic SELECT query, followed<strong> </strong>by the specific time you want to go to. The provided code offers an out-of-the-box way (no Unix timestamp needed) to jump back an hour from the time the query is run.</p><blockquote>You can find more about FOR SYSTEM_TIME AS OF<strong> </strong>in <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for-system-time-as-of">documentation</a>.</blockquote><h4>2.2 Create/replace a table with data from one hour ago</h4><p>Do you perhaps want to <strong>immediately restore the table</strong> to a state as it was an hour ago? Here is how to do that:</p><pre><strong>CREATE OR REPLACE TABLE</strong><br>  `project.dataset.table` <strong>AS</strong><br><strong>SELECT</strong><br>  *<br><strong>FROM</strong><br>  `project.dataset.table` <strong>FOR SYSTEM_TIME AS OF</strong>   TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)</pre><p>The result of this query will be saved in a table you specify in CREATE OR REPLACE; if you use the same name as in the FROM part, you will <strong>overwrite the table</strong> with the data as it was one hour ago.</p><h4>2.3 Create/replace a PARTITIONED table with past data</h4><p>You can do the same with a partitioned table. Below is an example where you have partitioned a table <strong>by day</strong> using a <strong>timestamp-type column</strong> in BigQuery and your table <strong>requires a partition filter</strong>:</p><pre><strong>CREATE OR REPLACE TABLE</strong><br>  `project.dataset.table`<br><strong>PARTITION BY</strong><br>  DATE(timestamp_value) <br>  OPTIONS (require_partition_filter=TRUE) <strong>AS</strong><br><strong>SELECT</strong><br>  *<br><strong>FROM</strong><br>  `project.dataset.table` <strong>FOR SYSTEM_TIME AS OF</strong> TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)<br><strong>WHERE</strong><br>  DATE(timestamp_value) &lt;= CURRENT_DATE()</pre><p>The WHERE condition as written just makes sure that you are allowed to query across all of the data (as every date is equal or smaller than today’s).</p><h4><strong>2.4 Go back DAYS or MINUTES, not hours</strong></h4><p>The examples that are shown above will retrieve the data from 1 hour ago. You can, of course, use any other number of hours, and if you need days or minutes, just replace the phrase HOUR with DAY or MINUTE.</p><h4><strong>2.5 Code in legacy SQL</strong></h4><p>If you are using legacy SQL, you can go back in time using the query below. You will need to convert the time you want to go to into Unix timestamp. You can find a page to help you do that quickly <a href="https://www.google.com/search?q=convert+current+date+to+milliseconds">by clicking here</a>, for example. You then enter the resulting number after the <strong>project:dataset.table@ </strong>as below ( I used 1577833205000 as a placeholder):</p><pre><strong>SELECT</strong><br>  *<br><strong>FROM</strong> </pre><pre>[project:dataset.table@1577833205000]</pre><p>Mind that legacy SQL query doesn’t support partitioned tables.</p><h3>3. Can I restore a deleted dataset?</h3><p>At the time of writing, unfortunately, no. To quote Google:</p><blockquote>After you delete a dataset, it cannot be recovered, restored, or undeleted. Deleting a dataset is permanent. (<a href="https://cloud.google.com/bigquery/docs/managing-datasets">source</a>)</blockquote><p>That’s it! I suggest you get familiar with how the functionality to go back in time works so you will know what to do if/when you actually need it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=544a9b7e7a8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If you stole the data, don’t win (too big)]]></title>
            <link>https://medium.com/@dhafnar/if-you-stole-the-data-dont-win-too-big-a4965f97dc1?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4965f97dc1</guid>
            <category><![CDATA[cambridge-analytica]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[the-great-hack]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Sun, 28 Jul 2019 13:33:09 GMT</pubDate>
            <atom:updated>2019-07-28T13:33:09.395Z</atom:updated>
            <content:encoded><![CDATA[<p>I just watched <a href="https://www.imdb.com/title/tt9358204">The Great Hack</a> and didn’t find the conclusions all that satisfying. Yes, users should own their own data; yes, political consultancies can be nightmarishly immoral; yes, Cambridge Analytica (CA) had and used data that it shouldn’t.</p><p>But a mixture of allegations doesn’t single out what is actually the problem (the Hack) and how it was resolved. It kinda gives the impression that CA, except having some data that it shouldn’t, didn’t do much that any other data-driven political consultancy would do (or is doing right now).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ht8dyDJJMax4atRyWsPGgA.jpeg" /></figure><p><strong>Immoral? Sure. Exceptional? Sadly, no.</strong></p><p>For example, the Trinidad and Tobago part exposed the CA’s use of social media to launch a targeted campaign to help CA’s clients win the elections. Is this an unusual behaviour for a campaign consultancy agency? No. Is the usage of social media for a political campaign anything special in 2019? No. Does it feel completely messed up and scary? Yup. But that’s how these political consultancy stories usually are (perhaps see <a href="https://www.imdb.com/title/tt6714534">Get Me Roger Stone</a>).</p><p>There are probably at least 20 similar immoral political campaigns going on in the World at the moment. And, yes, the smart marketers are using all the data they can get, as well as social media — as they would for selling washing powder, magical stain removers or organic kale smoothies.</p><p>I can’t help to think that if the campaigns they won weren’t so exceptional, against the ods (Brexit, Trump’s Election win) and if they wouldn’t piss off so many people, CA would still be thriving today.</p><p><strong>The future? The field levels — everybody is doing it.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mYkGAoZy2gH0M-p1_WhYQ.jpeg" /></figure><p>It is silly to think that numbers and voter targeting based on mathematical formulas are something new. It has been in politics for a long time — <a href="https://fivethirtyeight.com/features/a-history-of-data-in-american-politics-part-1-william-jennings-bryan-to-barack-obama/">according to FiveThirtyEight</a> in the US at least since the 1890s. What we are seeing now is a reflection of the leaps made in data science in recent years that are just entering the political reality.</p><p>I think it is fair to say that in the future every political campaign will be (and, to a degree, already is) using approaches so publicly discussed after the CA scandal. The only question is what data will they be using — the issue of ownership of personal data is surely to be a hot topic in years to come. No matter how much data they will have, ideally, nobody will have an unfair advantage and the field should even out. And any (good) data is usually better than no data.</p><p>The one major takeaway from CA and their “great hack”?</p><p><strong>If you stole the data, don’t win (too big), or they WILL get you.</strong></p><p><em>P. S. Because how the data was actually used is rarely explained simply enough, below I prepared a simple 3-point illustration of why having user data works so hackishly well.</em></p><h4>Example #1: All get the same message</h4><h3><strong>A TV commercial</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kDEyV427nB4ZMx3e" /></figure><p>The example of a basic form of advertising would be to buy some time on a national TV network. The same TV spot goes to all the viewers of that program at the same time.</p><p><strong>The good</strong>: You reach a big audience, you need a single commercial.</p><p><strong>The bad</strong>: You only have one angle and only a small fraction of the population will actually react to it. You are still paying a lot of money and spamming a lot of people.</p><h4><strong>Example #2: Some message differentiation</strong></h4><h3><strong>Ads in two magazines</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5QB7OvbwGBzBFde2" /></figure><p>Say you know that you have to convince a conservative audience in a specific state and market research has told you that female voters are concerned more about, say, immigration, and male more about, say, job security. You prepare two different ads and print them in two magazines (one targeting conservative men, other conservative women) so they will only address the population they have the best chance to leave a mark on.</p><p><strong>The good</strong>: You are sending the optimal message for the group you are targeting.</p><p><strong>The bad</strong>: You are still targeting broad groups. Some people are still spammed by the wrong message and you are not reaching everybody.</p><h4><strong>Example 3: </strong>Advanced message differentiation</h4><h3><strong>Multiple Facebook ads for multiple different groups</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yks7gsKOPKJqhJSB" /></figure><p>What is better than to know that you are targeting say a conservative man from a certain state with a message of job security? That you know that you target a conservative man from that state who loves dogs, is inclined to save a lot of his salary, is a baseball fan, introverted, prefers order, is reserved about new experiences and tends to worry a lot. You can have 100 different messages and a way to deliver them (via Facebook) to 100 separate groups of users created based on the above precise information.</p><p><strong>The good</strong>: You are delivering the most effective message to the best possible audience.</p><p><strong>The bad</strong>: You are as good as your data (and you need teams of people who know what they are doing).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4965f97dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In defence of passion projects]]></title>
            <link>https://medium.com/@dhafnar/in-defence-of-passion-projects-9af66ca5f077?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af66ca5f077</guid>
            <category><![CDATA[passion]]></category>
            <category><![CDATA[freeware]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Wed, 29 May 2019 20:55:16 GMT</pubDate>
            <atom:updated>2019-05-30T19:52:27.326Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Some of the best things in life are free. Maybe we should make more of them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*XzmUYPNUwpE0QnRURS9JGA.jpeg" /></figure><p>In the last months, two of my free Android apps have reached the end of life on the Google Play store. They worked well and lasted for long 6 years with basically no input or cost from my side.</p><p>Today I surprisingly received an email from a US user and an accompanying $10 donation from a page I at the time set up together with the app <strong>Lost Rescue</strong> (and forgot about the donation part since). The app was meant for quick location sending — with one click it got your GPS position and sent it via SMS as a Google Maps link, so anybody could open it.</p><h3>Strangers may rely on it, and you will have no idea</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*VsQpPmTBe67NyyLyRbYZOg.png" /></figure><p>“<em>I have really come to count on it and find it incredibly useful, even vital to my journeys</em>,” reads the email in which the user asked me for a copy of the app so he could install it on a friend’s phone. He added that even if he never needed it in an emergency, he always uses the app to send his location to loved ones “<em>just in case</em>”.</p><p>He told me about a case where he was biking about 240 kilometres from the nearest help and how he relied on it for his almost 9.000-kilometre journey. “<em>You can see why your app is so important to me</em>,” he added.</p><p>Again, this is a person I don’t know from another continent talking about a free app I barely had to spend any time on after publishing in the last 6 years.</p><p>I remember I received a couple of similar emails from users from abroad over the years. It felt really good when it got recommended a couple of times by mountain rescue services after they tested it thoroughly. (Note: I did, of course, test it thoroughly myself, ancient devices, going to the woods and all.)</p><h3><strong>Friends might need it, even if it weren’t yours</strong></h3><p>Another free app, <strong>Isci po SSKJ</strong> which I made at about the same time was still installed on 5.500 devices of Slovene speakers just some months ago.</p><p>I remember that a couple of years ago I asked a friend to show me his new phone and laughed when I saw he had the icon for the app pinned on the home screen. He looked at me funny when I pointed it out to him — he had no idea I was the author, he just happened to find the app useful.</p><p>The really silly thing is that the first version took me about a few hours to make and an email to the Fran Ramovš Institute of the Slovenian Language asking for their consent for my app to interface with their servers. All future versions were just facelifts so the app didn’t feel outdated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*P5RJXmukP6hirZjoOIWb2Q.png" /></figure><h3><strong>It feels good … and gives you something to show</strong></h3><p>Google started pushing against apps using permission to send SMS, which is at the core of the design for Lost Rescue and the app was removed from the store. Coincidentally, shortly after, I got an email from Fran Ramovš institute that they are changing the site it used and are planning something in the space themselves so they asked me if I can remove my app. I was glad to hear it, removed it, and got a kind offer from them for a free book for my volunteer work of making and maintaining the app through the years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9yd2qUlhl3M6Q9_k_xiHJg.jpeg" /></figure><p>I remember that originally I made those apps to practice, both programming and problem solving and to have an actual useful, end-to-end product to show as a reference. I didn’t imagine they would still be around six years later.</p><p>It is a nice feeling knowing that your decision to make something might help somebody at some point — or just make a user happy.</p><p>So if you happen to be a looking for a quick programming project to test yourself … aiming to make something genuinely useful for the everyday user might prove more rewarding than you would think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af66ca5f077" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ten goals to consider for a brighter tech-empowered future]]></title>
            <link>https://medium.com/@dhafnar/ten-goals-to-consider-for-a-brighter-tech-empowered-future-8a0877855ce7?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0877855ce7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[sustainable-development]]></category>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 13:36:04 GMT</pubDate>
            <atom:updated>2019-04-08T16:58:34.274Z</atom:updated>
            <content:encoded><![CDATA[<p>The view of the future is increasingly determined by rapid technological advancements. At the same time, episodes of dystopian series like Black Mirror that looked improbable at the time of initial release have become all but reality. The disturbing episode of the series where people were given social status based on an algorithm has, for example, started to prove as real with China introducing a similar system for their citizens.</p><p>“<em>In ten years, the cars will be self-driving,</em>” “<em>Shortly, jobs will be replaced by short term gigs,” “Artificial intelligence will misplace most of the currently existing jobs,”</em> are some of the things we tend to hear a lot in the recent years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SoFnz5yTEkH75BDm2cdzA.jpeg" /></figure><p>But are the changes that the “technology” is selecting for us the changes that we want, the ones that are needed and the ones that will make the life of the majority better? It seems that there is no consensus about the changes we want tech to bring, yet we continue to rush into this brave new world by simply accepting fate and hoping for the best.</p><p>In this reflection, I will propose and attempt to explain a couple of goals we should consider making sure we are getting the future we want and not the future pushed upon us by the world moving faster than we care to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdAFwi7Mb1JGpwAmrjH71A.jpeg" /></figure><h3>1. We need to be critical to ideas that disregard social security.</h3><p>Freelancing, driving for Uber, gig economy — the concepts sound fresh, but they risk essentially selling poor work regulation. Just because it happens through an app, it doesn’t mean it’s from the future. The basic problems those concepts introduce are from the past — social insecurity, inability to qualify for a bank loan, no real pension plan and problems that derive from the ones listed — stress because of insecurity, delayed adulthood etc. As this type of labour is just emerging and mostly affects young people, we might not have a real picture of what it means and what the effects will be in the longer run.</p><blockquote>Just because it happens through an app, it doesn’t mean it’s from the future.</blockquote><p>There surely are changes in relation to labour that technology enables and brings forward, but they by themselves are not enough. For a gig economy to work, the safety net much more efficient than today will have to be developed so that people participating in such an economy, in the long run, won’t be without security, loans for homes and pensions.</p><p>Labour isn’t the only way technology development might threaten the social security we got used to — services like Airbnb and booking.com have begun causing problems for real estate prices in the cities as apartments are getting easier to rent to global tourists. Again, just because it happens through an app, it shouldn’t mean that the rules don’t apply. If such services, in fact, lead to gains for the wealthy and hurt the poorer whose rents go up, technology can’t be an excuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HU-_y5K1LNRcXZSxBT5H9w.jpeg" /></figure><h3>2. We need to ask ourselves if a certain vision is taking us to a place we want to be.</h3><p>Mobile phones were first seen as a way to connect people, as were the first smartphones. It soon turned out that we are capable to sit with our friends in silence, staring at our phones, perhaps even chatting with people other than the ones we are sitting with. Is this really the place we wanted to get to? Are we happier spending an hour, two or more per day staring at the screens of mobile devices than we were before that was possible?</p><p>Similar is true for social networks like Facebook — they were intended to bring us together, but in the end, they turned out to perhaps isolate us even further. Is interacting with schoolmates over Snapchat, Instagram or WhatsApp really a better way to spend the youth than it was hanging out with buddies in real life?</p><blockquote>In the end, they turned out to perhaps isolate us even further.</blockquote><p>I am not saying that it would be better that above-mentioned inventions would not exist, but I would argue that we should carefully study the pros and cons of tech that is bound to bring huge social changes and have a say if we are better off with them or without them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiJYdBQ0FsJayvBK7KdNMQ.jpeg" /></figure><h3>3. We need to make sure legislators are able to respond to innovations in near real time.</h3><p>The two goals mentioned above both risk stifling innovation as IT companies can move much faster than legislators or public can follow. This needs to change, as more and more decisions made by parliaments and governmental institutions in the future will be linked to the informational technology.</p><p>The first visible examples of the legislators stepping into the world of IT are perhaps the two EU cases, the one with control of the browser cookies (which can be argued didn’t do much) and GDPR (General Data Protection Regulation, which just might pave the way how to regulate similar problems in the future).</p><p>The challenge is not new, as legislators were always required to respond to challenges of the times, but in recent decades it feels like the IT giants, not the governments (and behind them, the people) in which direction things should move.</p><blockquote>Lawmakers will simply have to be able to weight in as equal and prepare reasonable laws regarding IT.</blockquote><p>The issues have already arisen in the areas of privacy, internet neutrality, and taxation. One of the problems on the horizon is the fact that the internet is getting more and more centralized (as giants are getting an uncatchable lead with their datacenters worth hundreds of billions). Also, the area of machine learning (popularly AI), which is expected to gain huge importance in the future, is likely to be dominated by tech giants, as smaller firms simply cannot follow in this demanding field.</p><p>Some of the current and future challenges in the IT area will be too important for the legislators to let sort out for themselves. For the future that is driven in the interests of the people, lawmakers will simply have to be able to weight in as equal and prepare reasonable laws regarding IT so that technology continues to work in the interest of those they represent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gmaEZNhloDRaf1osy71VQ.jpeg" /></figure><h3>4. We shouldn’t assume people will (or should) change.</h3><p>In discussions about the future it also feels taken for granted that, for example, some industries would disappear, that all people should switch to life-long learning or that in the future almost everybody will have to move to the cities. Such foregone conclusions are naïve and have proven as very dangerous in the past.</p><p>Many such predictions were taken for granted with the rise of globalization in recent decades. As part of the middle class in well-off countries turned out to lose out, the anti-establishment sentiment started pushing forward populism.</p><blockquote>If people continue to get left out for the sake of the progress itself the backlash, similar to Brexit, is always on the horizon.</blockquote><p>If truck driving jobs are, for example, to disappear because of self-driving trucks a solution for the people losing out on their livelihoods as truck drives should be found. It is true that jobs don’t exist for the sake of those that want to do them — but it is at the same time true that the system that governs us and the economic system within it wasn’t born out of the natural order of things but of the agreement of the governed. And if people continue to get left out for the sake of the progress itself the backlash, similar to Brexit, is always on the horizon.</p><p>The goal of making a system that is fair, or at least considered as such for the majority isn’t only a moral, but also a pragmatical question which, when neglected because of the short-term goals, tends to bite back and cost a lot more than considerate decisions would in the first place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vABIBy1qO-WdgLB8LxU_6w.jpeg" /></figure><h3>5. We need to prioritise technology and protocols that inherently protect privacy.</h3><p>We all know that there are companies out there having a lot of data on us. We have even, in most part, accepted the fact that every move me make is recorded by somebody in some way. The fact is, we have no idea what is going on, how is data on us used and how it is protected from being stolen. Are there people looking at our personal pictures that we uploaded to the cloud to add some tags right now? Is an employee of some tech company reading our chats or emails just out of boredom?</p><p>With the internet boom, not enough attention was given to data protection. We all just kind of hope and expect that nobody would look into our personal data, that everybody at every company with access to our data knows what he is doing and has good intentions. We should demand more.</p><blockquote>The fact is, we have no idea what is going on, how is data on us used and how it is protected from being stolen.</blockquote><p>There needs to be a push for technology with end to end privacy and real oversight that those technologies are properly set up and maintained. No data should be exposed any more than is needed for the systems to function. Within companies, all data accesses should be strictly limited and monitored and all personnel that handles it trained how to properly protect it and be aware that is responsible for it. There should be protocols beyond companies that ensure all of this happens.</p><p>The data exposure and exploitation we are witnessing right now should go into history as an exception, not as the beginning of the end of privacy with potentially devastating consequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ND7KaK413kFB8D-kPUZpPQ.jpeg" /></figure><h3>6. We need to make sure the internet stays open.</h3><p>Some data suggests that Facebook and Google account for more than 50 percent of all web traffic. Cloud computing is becoming more and more popular and proprietary services offered by cloud giants threaten the disperse multitude of servers that used to compose the internet. The similar is true in the field of smartphones, where providers of content are reliant on only two global distributors of their applications on the two major operating systems. In the field of machine learning (AI), only a few big winners are expected to take most of the new segment.</p><blockquote>We shouldn’t forget that the internet became what it is today because people used it in millions of different and creative ways to solve real-world problems and inconveniences.</blockquote><p>Any new internet company is likely to be heavily reliant on an existing giant — for hosting, distribution, and marketing. That means that for every successful company, an existing giant gets even bigger, while it has nothing to lose if the new company fails.</p><p>The trend of takeovers is also problematic, as most of the promising newcomers get eaten up by the giants before they could compete with them. The current system seems to be working in favour of the big players keeping small ones on the margin.</p><p>We shouldn’t forget that the internet became what it is today because it was free, and people used it in millions of different and creative ways to solve real-world problems and inconveniences. As internet — and larger and larger chunks of our lives with it — is falling into the hands of a few big companies, we are at risk of losing freedom and creativity that created it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Za5l773CdP-rFqBz-okHg.jpeg" /></figure><h3>7. We need to enhance the role of education and learning.</h3><p>It has become a norm that a person should spend around 15 years of his or her life in school before getting a bachelor’s degree and get a job. Even if that seems long, it should be clear that is not nearly enough. The model where a person goes to college, graduates and works until he qualifies for a pension has become unsustainable. Constant changes — mostly because of technological advancements — make any knowledge that isn’t constantly updated insufficient in a matter of years.</p><blockquote>People who have the potential to be at the top of their field should be motivated to seek careers at least partially based on sharing their knowledge.</blockquote><p>This dynamic should be made clear and taken into consideration, and not only by an individual but also the system around him. Learning, when practically devised, is not only for the benefit of the individual but also of the society around him. Also, learning and work aren’t as separated as they used to be and should be better connected, supplementing each other. A decision about what a person will do for the rest of their lives can’t be taken before that person has even entered their twenties.</p><p>As lifelong learning is coming into focus, so should the role of educators. Quality of education should rise, and teachers should be better awarded and motivated to do everything they can to help develop a person. Educators on every level should be treated and compensated as are the college professors right now to make sure people who have the potential to be at the top of their field would seek careers at least partially in sharing knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqslUcGybZ9FdJT0cg4bhg.jpeg" /></figure><h3>8. We need to make sure people don’t fear old age.</h3><p>Pension systems, similarly as the systems that ensure employment stability are increasingly seen as an unsustainable remnant of some old way of doing things. They shouldn’t be. The problem of social security in old age is as old as humanity and should be addressed for a society to thrive.</p><blockquote>The problem of social security in old age is as old as humanity and should be addressed for a society to thrive.</blockquote><p>Expecting people to work forever and calling it progress isn’t going to work. Right now people the “work forever” principle will most likely apply to don’t concern themselves with retirement yet, but the idea will break down once they do. At the same time, the absence of trust in retirement systems threatens the support of the younger generation for maintaining any kind of for expensive welfare systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIXtTB4hlgI6IpbMOFNp9g.jpeg" /></figure><h3>9. We need to make sure the welfare state is forward facing.</h3><p>Since the fall of the Soviet Union, the traditional left has often put itself in the position to defend rights from the past and paradoxically often became a conservative force in society. Siding and being content with the old industries and fighting to make sure decades-old promises aren’t touched on the expense of younger people and progress is a bad bet that is making the welfare state unsustainable, unpopular and ineffective.</p><blockquote>The move to an increasingly tech-dependent society means changes in the workforce that are too big to be left for the market to resolve.</blockquote><p>The welfare state is no less needed now than it was ever in the past — the society should help its members from merely fighting for survival and in return, those members will perhaps be able to become a version of themselves that will be able to give back more than they would otherwise.</p><p>The move to an increasingly tech-dependent society means changes in the workforce that are too big to be left for the market to resolve. A welfare state should be able to step in and make sure people are striving to move forward, learn, if they want to, and not fear change. For that to happen, attitudes of the left should turn to the future and not to the past.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aaCom4CuBSwX01MK2bcMA.jpeg" /></figure><h3>10. We need to accept that China is a player that will rival the US in tech.</h3><p>Issues like the US had in recent years with the Chinese companies ZTE and Huawei aren’t likely to go away. They do not come from pettiness but are a symptom of the fact that the relationship between the two large powers has changed forever.</p><blockquote>The relationship between the two large powers has changed forever.</blockquote><p>For the last few decades, China was a cheap manufacturer for US companies, a fast-growing country with the willingness to do business and cause as little trouble as possible. That phase has ended and as has China started to develop its own huge base of consumers and modern military, so has it started to become a top world power when it comes to technological advancement.</p><p>The two countries appear to be destined to be the big rivals when it comes to technology — as just one of the things — in the years and decades to come. The problems they have now will stay in one way or the other and the return to the old way of doing things — US designing, China producing for cheap — cannot be expected.</p><blockquote><em>Note: The essay was originally written as part of a class assignment.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0877855ce7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically tag photos on your site (the way Google Photos does)]]></title>
            <link>https://medium.com/@dhafnar/adding-tags-to-pictures-for-e-commerce-using-serverless-aws-and-ml-94381785b1ca?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/94381785b1ca</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[e-commerce-solution]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Sun, 30 Sep 2018 16:19:45 GMT</pubDate>
            <atom:updated>2018-10-01T11:34:43.634Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a lot of talk about the potential of AI (artificial intelligence) and ML (machine learning), but the application appears to be for now limited to bigger firms who can afford departments to both design and develop the products incorporating rapidly evolving technologies.</p><p>Out of curiosity, I went looking for an example of a basic deep learning solution to an actual business problem that a developer without any ML background could implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTJCMhyOd3ldqvsWrvC47A.jpeg" /><figcaption>If you search for the term “lake” in Google Photos, the application will return all your photos for which an ML algorithm determined to include a lake.</figcaption></figure><h3>Adding tags using magic (or just ML)</h3><p>I stumbled upon the article How to Deploy Deep Learning Models with AWS Lambda and Tensorflow (<a href="https://aws.amazon.com/blogs/machine-learning/how-to-deploy-deep-learning-models-with-aws-lambda-and-tensorflow/">link</a>). The setup is simple enough <em>(make sure you select region=us-west-2 for everything to streamline the setup).</em></p><p>The solution allows you to upload a photo and leverage deep learning to get the description of the photo which you can potentially add as a tag in your database.</p><p>Once up and running, you can test the setup by simply uploading the photo in the S3 bucket and get served the labels the model was able to recognize from the photo in the CloudWatch Logs. So I tried a simple photo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ma4ZWpNt4GSgcG-EUBgKJg.jpeg" /><figcaption>Example of an everyday photo.</figcaption></figure><p>The result was close enough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*zI09VFt9098jcBAMTCK-fQ.png" /><figcaption>The motive is recognized as “espresso.”</figcaption></figure><p>I also tried a clearer example, one that an online store might use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*d08uF5mY1FvFUQza-px2Ng.jpeg" /><figcaption>Example of a clear and simple object (src: Wikipedia)</figcaption></figure><p>The result was compelling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*meqCPstQnHFnhjj5jIuosg.png" /><figcaption>Some useful tags were produced.</figcaption></figure><h3>Possible practical use: e-commerce</h3><p>S3 buckets are by now an industry standard and there are a lot of ways to automatically upload files into them. That means that this type of serverless implementation could be used to augment an existing website that deals with picture uploads in any form.</p><p>Imagine an e-commerce example. Every uploaded photo (even old archive) could get added tags based on what is in the picture. All the photos would have to be added to the S3 bucket and the output tag added to each picture in the database (of course output would have to be written in your database instead of into logs.)</p><p>The accuracy of the search results and user recommendation systems should benefit from the added tags, which should, used wisely, result in an increase of conversions. The solution tested is also quite cheap as you only pay for what you use.</p><h3>Conclusion</h3><p>Even if they at the moment more or less amount to hacking, simple solutions like the one described above can serve as a bridge between the business world and the still somewhat niche world of AI.</p><p>Explained simply enough and with a clear value proposition, at least some of the goodies of machine learning will in the future trickle down to smaller development companies who won’t be able to afford specialists in the area.</p><blockquote>Note: If you are interested in this type of solution, you might also want to check out <a href="https://cloud.google.com/vision/">https://cloud.google.com/vision/</a> and compare the possible costs. It is a more professional, commercial offering of the similar solution from Google I also stumbled upon.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94381785b1ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matching Brussels municipalities with Ljubljana using Foursquare and ML]]></title>
            <link>https://medium.com/@dhafnar/the-battle-of-the-neighborhoods-brussels-municipalities-vs-ljubljana-be%C5%BEigrad-9e5f561c4cad?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5f561c4cad</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Tue, 14 Aug 2018 18:39:19 GMT</pubDate>
            <atom:updated>2018-08-18T06:20:56.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L7GhJLyUKCY5o-xb6TVzw.jpeg" /><figcaption>Ljubljana — Bežigrad. Source: Wikipedia</figcaption></figure><p>Brussels is the capital of Belgium and an administrative seat of the European Union. People who want to work for one of the European institutions often have to move there. Moving to a capital of another country is a big step, so it would help to know you are moving to a similar neighborhood that you lived in your home country.</p><blockquote>The goal of this project is to determine which Brussels neighborhoods come the closest to Ljubljana using Foursquare data and K-means clustering.</blockquote><p>I will take Bežigrad, one of Ljubljana’s — capital of Slovenia — representative, mostly residential districts and compare it to the 19 municipalities of the Brussels-Capital Region. The goal is to find municipalities that are the most similar in terms of venues to the Ljubljana’s representative district.</p><p><em>Disclaimer: This post is a part of the IBM Applied Data Science specialization, not a scientific assessment.</em></p><h3>How does Bežigrad compare with municipalities</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQmZkxguoWSANrNd9to7dw.png" /></figure><p>Before deciding on the project, I have checked the data about Brussels and Ljubljana to see that comparison would make sense. The population data is given in the graph above. According to results, given the population, the district could might as well be one of the municipalities of Brussels.</p><h3>How will the comparison be made</h3><p>I will make the comparison based on the type of venues that are the most common in the district and municipalities. I will then perform a grouping using machine learning to determine which of the municipalities are most similar to Bežigrad district.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*yIQ-d16lVxhQYE84b9yB3w.png" /><figcaption>Data after attaching latitude and longitude from Google API.</figcaption></figure><p>I will be using data from Foursquare. The service enables us to search for specific venues at a certain location. Venues are places like coffee shops, restaurants, shops, parks etc. I will focus on types of venues, not names so that they are comparable across different locations.</p><p>For example, if the district is residential, you expect there to be a lot of small grocery stores, some coffee places etc. If the district is industrial, touristy or business oriented, the types of venues that are most frequent will be different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*1RP0GfLZEJzg5pNbhfxkrA.png" /><figcaption>Example of some Forsquare data for Bežigrad district.</figcaption></figure><p>I will not do the analysis by myself but compare the data with a machine learning method to determine the most similar municipalities.</p><h3>What can machine learning do</h3><p>To make the comparison and determine similarities between Brussels municipalities and Ljubljana’s Bežigrad district I will use a K-means clustering method. This is an unsupervised machine learning method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Nx6IyGfRAV1ly6uDGnVCxQ.gif" /><figcaption>K-means method. Source: Wikipedia</figcaption></figure><p>The goal of K-means clustering is to find groups in the data. K stands for the number of groups. Data points are clustered based on the similarity of the features. So the more similar the data features, the more likely they will be grouped.</p><p>A trivial example: if my data consists of an apple, a peach and a car and I would have a K-means algorithm separate them in two groups (K=2), an apple and a peach should be put in one group, and a car in the second.<br>I will run K-means algorithm to group the Brussels municipalities and Ljubljana’s district to determine how alike they are given the Foursquare venues data.What were the results</p><p>When I tried with splitting data into three groups, I was surprised to find that Bežigrad district was in the group with most of the Brussels&#39;s municipalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_sokyujhprs-LIAaKzR6Q.png" /><figcaption>Cluster labels 0, 1 or 2 tell us which group does a neighborhood belong to. Ljubljana-Bežigrad grouped with the majority of neigbourhoods.</figcaption></figure><p>The algorithm put them all in cluster 0, while only Woluwe-Saint-Lambert was put in cluster 1 and only Molenbeek-Saint-Jeanwas put in cluster 2.</p><p>To represent the groups visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*aLSb0a8DWduvoB1X4A5t9w.png" /><figcaption>Brussels municipalities. A color corresponds to a group municipality belongs to.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*_m5uwJqrORu8BhkQyWPGsg.png" /><figcaption>Ljubljana-Bežigrad belongs to the same group as most Brussels municipalities.</figcaption></figure><p>As I went further, increasing the number of groups to four or five, Ljubljana-Bežigrad still remained in the largest group. It stayed like that even when increasing to seven.</p><h3>So … conclusion?</h3><p>Regarding the question of which municipality of Brussels is similar enough to Ljubljana-Bežigrad, any municipality but Woluwe-Saint-Lambert and Molenbeek-Saint-Jean fits the bill.</p><p>Keep in mind we are only talking about Foursquare data. It still doesn’t tell us much about the view of the mountains or other very important qualities that would make a person feel most at home …</p><blockquote>The code walk trough for the project is available on <a href="https://github.com/dhafnar/ibm_coursera_capostone_project/blob/master/IBM%20Coursera%20Capstone%20-%20Final%20project.ipynb">Github</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5f561c4cad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Google is running away from Android]]></title>
            <link>https://medium.com/@dhafnar/why-google-is-running-away-from-android-885e5c7c3499?source=rss-cbc518370dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/885e5c7c3499</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[pixel]]></category>
            <dc:creator><![CDATA[Davor Hafnar]]></dc:creator>
            <pubDate>Sun, 11 Mar 2018 08:03:59 GMT</pubDate>
            <atom:updated>2018-04-01T05:52:34.113Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The battle of the mobile ecosystems has ended. The battle of the giants for the ultimate device is just starting.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*M6FTJ9XJDCie4PMRl0n4Vg.png" /></figure><p>For years after the introduction of the first iPhone, Google’s strategy was more or less the same. They competed with Apple in a way Microsoft started decades before; by focusing on a software platform alone. They left the expensive and risky hardware part that goes with their platform to any manufacturer willing to enter the market.</p><p>The strategy seems to have worked; at the beginning of 2018, Android and iOS are the only two mobile platforms mobile developers must consider. On top of that, Android has far surpassed iOS and is the world’s most used mobile platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gKemqsPzFqpOSXmbVDkkw.png" /><figcaption>Source: Statcounter</figcaption></figure><p>For comparison, the graph below shows how colourful the mobile ecosystem landscape was just five years ago, in 2013.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBI_0ovdtWi-idL9dzVAog.png" /><figcaption><em>Note: Series 40 is the operating system used on simple Nokia phones. Source: Statcounter</em></figcaption></figure><p>Android turned out to be one of the great Google successes; without the hustle of making physical devices that would have to compete with the iPhone (and likely fail), they got a dominant mobile operating system. Google’s Search app and Google Play Store now come preinstalled on hundreds of millions of mobile devices.</p><p>For a time now Google knows that the chance of another mobile ecosystem emerging is virtually zero. Any new contender would have to convince hundreds of major software firms to develop software for the new system. What good is a smartphone running an operating system without Facebook, Gmail, Instagram, Angry Birds, Clash of Clans or My Talking Tom?</p><p>Battle is over, and Google knows it.</p><h3><strong>Going after that iPhone money</strong></h3><p>The heavy lifting for the Android ecosystem is done by companies like Samsung, LG, HTC, Sony, Xiaomi, Huawei, Motorola, and Lenovo. They are the ones competing with Apple on one side and raising the quality of Android devices by competing with each other on the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqgNOvXr4Th9KOgWa1O0RA.png" /><figcaption>Google isn’t on the list. <em>Source: Statcounter</em></figcaption></figure><p>That doesn’t mean that Google never set foot on the device market. From 2010 to 2015 it was introducing the Nexus series. The focus for the devices was to introduce the newest and latest in Android to the market in the purest sense. Nexuses didn’t compete with the iPhone and carried a lower price. They were not intended to make serious profit for Google and were produced by major manufacturers in the industry. Along with a Nexus logo, the devices boosted a logo from their manufacturer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1RbjeMr5nElriQR9." /><figcaption><em>A Nexus device, carrying a Huawei logo.</em></figcaption></figure><p>Google’s strategy shifted with the introduction of Pixel phones. Google for the first time abandoned its sole role as the Android caretaker and moved in against the iPhone directly. At the same time, it moved against Samsung, LG, Huawei and other players in the Android ecosystem.</p><p>At the moment Google made clear it wants to become a smartphone brand, Samsung and others were already completely dependant on Android for the smartphones sales.</p><p>To clarify; no, Pixels in their second iteration don’t pose a real threat to any of the incumbents. It just may turn out that Pixels never will — distribution network, advertising, and user trust levels are far, far below the ones iPhone has. But Google’s goal to make devices that will (eventually) go head to head with iPhone — and the profits they make for Apple — is clear.</p><p><strong>Google Phones, not Android phones</strong></p><p>Nexus was a pure Android experience and any advantage it introduced would be shared to the whole Android ecosystem. Software-only advantages like AR stickers and software enhancements that make Pixels camera unique will stay only on Pixels. With Pixels, Google added another layer on top of Android.</p><p>Pixels use other specialised features like Pixel launcher and special types of wallpapers that you can’t get on other Android phones. If you buy a Pixel, your photos will be saved in better quality by Google Photos as will photos made with other Android phones. List of Pixel-only advantages over pure Android goes on and it is reasonable to expect that it will only get longer with any new version of the device. As AI is poised to play a bigger and bigger role for the smartphone industry, Google, a clear industry leader in the field, will surely be tempted to leverage it against the competition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeJKjN6vj_TADltZ_G1VXA.png" /><figcaption>Pixel 2 with a Google logo on the back.</figcaption></figure><p>That’s why an upcoming showdown between Google and Apple already produced one loser: Android itself.</p><p>Pixels can only stand out from the rest of the Android pack if they keep some exclusive software and design advantages for themselves. On the webpage where Pixels are sold, word Android is only mentioned in small print. Google isn’t selling Pixels as Android phones; it is selling them as Google phones.</p><p>It makes sense; battle of the mobile titans was always really between the worlds strongest brands; Apple vs. Google. It was never really Apple vs. Samsung or Apple vs. HTC. The low-end devices from those manufacturers branded Android in eyes of many consumers as an inferior, cheaper choice, which is something Pixels want to break with. Part of Google’s future plans for iPhone-like device profits is running away from Android’s perception and legacy.</p><p>And if — in a few years’ time — Google reaches its goal on the smartphone market, a typical consumer will have a choice between three types of phones.</p><p>Android phones, iPhones, and Google phones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=885e5c7c3499" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>