<?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 Yogi Saputro on Medium]]></title>
        <description><![CDATA[Stories by Yogi Saputro on Medium]]></description>
        <link>https://medium.com/@yogisaputro?source=rss-fbe1c110f952------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uWcVXFE7VValS7E5i8Y9Dg.png</url>
            <title>Stories by Yogi Saputro on Medium</title>
            <link>https://medium.com/@yogisaputro?source=rss-fbe1c110f952------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:10:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yogisaputro/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[How Smart Are Free AIs? I Tested Them with Indonesian Twist]]></title>
            <link>https://yogisaputro.medium.com/how-smart-are-free-ais-i-tested-them-with-indonesian-twist-925e66d75cd6?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/925e66d75cd6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[indonesia]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 06:42:39 GMT</pubDate>
            <atom:updated>2025-02-02T06:42:39.083Z</atom:updated>
            <content:encoded><![CDATA[<p>AIs are firmly diffusing into the fabric of society. Big techs like Meta, Google, OpenAI offer them for free. News give AIs spotlight, with <a href="https://www.economist.com/business/2025/01/27/deepseek-sends-a-shockwave-through-markets">DeepSeek causing havoc in US stock market</a> as of this article is written. More importantly, people are trying it. Used to be millions, now billions are using AIs. Among those billions, Indonesians represent sizable chunk.</p><p>With that in mind, are those AIs smart enough to answer questions in context of Indonesian language and culture? Even with <a href="https://www.vellum.ai/blog/llm-benchmarks-overview-limits-and-model-comparison">many benchmarks</a> rigorously testing AIs, I can’t find any particular test for that purpose. So…fine, I’ll do it myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*iuZBRwFS-llBEAhffqUVHg.gif" /><figcaption>gotta admire Thanos for his hands-on approach</figcaption></figure><h4>Test Description</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_RPuAPTpYMFMtex4ZuhpFA.jpeg" /><figcaption>AI with local knowledge</figcaption></figure><p>A bit of foreword. This is not a scientific paper. I devised my own test, but I acknowledge it is lacking formal rigor. Just a weekend worth of exploring AIs. But if you find it interesting, <a href="https://www.linkedin.com/in/yogisaputro">contact me on LinkedIn</a> to collaborate. With that being said, let’s move to the scope.</p><ol><li>I only test free AIs. Many Indonesians consider AIs are free to use and don’t want to spend money on better ones.</li><li>The test was conducted between 26 to 29 January 2025.</li><li>I devised 4 questions that has different kinds of twist in Indonesian context.</li></ol><p>List of Free AIs I tested:</p><ul><li>ChatGPT 4o-mini</li><li>Gemini 2.0 Flash</li><li>Microsoft 365 Copilot (based on GPT-4)</li><li>Meta AI on WhatsApp (based on Llama 3.2)</li><li>Claude 3.5 Sonnet</li><li>plus our latest world-shaking contender: DeepSeek-V3</li></ul><p>List of questions (I’ll explain the twist later)</p><ol><li>Ada berapa huruf “a” dalam kata “Tasikmalaya”? [<em>How many letter “a” are present in word “Tasikmalaya”?</em>]</li><li>Jika tanggal 1 Februari adalah hari Senin Kliwon, tanggal berapa hari Senin Kliwon berikutnya? [<em>If 1st of February is Monday of Kliwon, when is the next Monday of Kliwon?</em>]</li><li>Apa bahasa Indonesia dari ekspresi “<em>order of magnitude</em>” yang menunjukkan kelipatan dalam skala puluhan/ratusan/ribuan? [<em>What is the Indonesian term for expression “order of magnitude” which shows powers of ten?</em>]</li><li>Tentukan kata yang tepat untuk mengisi titik-titik di kalimat berikut: “Pak Rafi masuk … ringan”. [<em>Fill the blanks in following sentence with correct word: “</em>Pak Rafi masuk … ringan.<em>”</em>]</li></ol><h4>Test Result</h4><p>I run through the questions to each AI model. Here I’ll present the result by questions. Each question has twist, and we can see how AIs are solving that by comparing the answers.</p><p><strong>Question 1: Ada berapa huruf “a” dalam kata “Tasikmalaya”?</strong></p><p>This is a classic known flaws of LLM-based AIs. They understand inputs as tokens through <a href="https://blog.seancoughlin.me/understanding-tokenization-in-large-language-models">process called tokenization</a>. Token is their basic reading unit, compared to letter or word or symbol like human. By default, interpreting word like the way we do is surprisingly challenging for these AIs. Updated AI version or model has additional layer to resolve this, like via frequency analysis or something.</p><p>Additionally, “Tasikmalaya” is name of <em>kabupaten</em> / municipality in Indonesia. You know, to keep the Indonesian context.</p><p>Now let’s see them in action.</p><ul><li>Correct answer: 4</li><li>ChatGPT 4o-mini: 4 ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*oolulvTDkQ9F9GMga-4WfA.png" /></figure><ul><li>Gemini 2.0 Flash: 4 ✅, although its reasoning uses zero index which could be confusing for general audience 🤷</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*V42RNaV5pMZPoRsE9-rpRQ.png" /></figure><ul><li>Microsoft 365 Copilot: it keeps gaslighting me the answer is 3 until I tell it to count occurrences of all letters🥲❌</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*wW-3OKM1fzqxABqe5_5Tsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*_chXB1z9E1Uz-Gavypzs4A.png" /></figure><ul><li>Meta AI on WhatsApp (Llama 3.2): 3 ❌, and I’m done being gaslighted.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*71rhw_N5nzccSBMi4wRsNA.jpeg" /></figure><ul><li>Claude 3.5 Sonnet: 4 ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*9Ku7GJpT86PstdYVJd0nCA.png" /></figure><ul><li>DeepSeek-V3: 4 ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*CH2VnLGBBBkd-uzXogqZIQ.png" /></figure><p>Conclusion: many newer AIs have added layers of logic to resolve this issue.</p><p><strong>Question 2: Jika tanggal 1 Februari adalah hari Senin Kliwon, tanggal berapa hari Senin Kliwon berikutnya?</strong></p><p>I struck myself in awe when invented this one. It’s devilishly simple yet deceiving. In Indonesian context, especially Javanese, there’s additional day-attribute called “pasaran” that traditionally used as the day when market/bazaar opens. There are 7 days and 5 pasaran-days, which combines to 35 days until the next Senin Kliwon. However, exact date of 35 days after 1 February depends on whether the year is leap-year. This requires additional level of analysis. Even humans may not be right at first attempt.</p><p>Correct answer: 8 March for non-leap year (check <a href="https://www.timeanddate.com/date/dateadded.html?d1=1&amp;m1=2&amp;y1=2021&amp;type=add&amp;ay=&amp;am=&amp;aw=&amp;ad=35&amp;rec=">here</a>) and 7 March for leap year (check <a href="https://www.timeanddate.com/date/dateadded.html?d1=1&amp;m1=2&amp;y1=2024&amp;type=add&amp;ay=&amp;am=&amp;aw=&amp;ad=35&amp;rec=">here</a>). On each part, unassisted correct answer yields two marks ✅✅, and assisted correct answer yields one mark ✅.</p><ul><li>ChatGPT 4o-mini: gets it right on first half ✅✅, then flops on second half ❌,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*hnDfUVfBpbTFBg9E7NqP_g.jpeg" /></figure><ul><li>Gemini 2.0 Flash: Flops without assistance on first half, then flops again WITH assistance ❌, then uses wrong reasoning and flop deeper on second half ❌.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cT_Qh6fbpB4FNc9NVsaaBA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ROmPFk9QT3_KvTVoY5OU3Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*Tr64StjFKNrS9ODOpHpYXw.jpeg" /></figure><ul><li>Microsoft 365 Copilot: gets it right on first half ✅✅, then flops on second half ❌</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2xvjbYVB29Uzdu_jBIU6ig.jpeg" /></figure><ul><li>Meta AI on WhatsApp (Llama 3.2): gets right with assistance on first half ✅, then gets it right with assistance again on second half ✅.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oocbGwpCb8N1R3NFfqkcLQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*iV6w0EfGdpSyysYDFFvaXA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7h3B0Mad-c-07bNPF4JvnQ.jpeg" /></figure><ul><li>Claude 3.5 Sonnet: gets correct with assistance on first half ✅, then gets correct with assistance again on second half ✅.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*MDeUS3w5q1vU8ZUQuS0v0w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*DpH2rJXYyBX-XHGD-Zgk-w.jpeg" /></figure><ul><li>DeepSeek-V3: gets right on first half ✅✅, has good reasoning but flops at the second half ❌</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*tCFuCWyrN2xzWPNp5uzpsQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3tYD_1h1gnUKYLUzMUv3mg.jpeg" /></figure><p>Conclusion: No AI has managed to answer the question right from the first try. Some performs better with assistance, some are helpless. In any case, always verify.</p><p><strong>Question 3: Apa bahasa Indonesia dari ekspresi “<em>order of magnitude</em>” yang menunjukkan kelipatan dalam skala puluhan/ratusan/ribuan?</strong></p><p>“Order of magnitude” seems like commonly used phrase in western world to describe number comparison in powers of ten. However, there’s no legitimate dictionary entry for such expression in Bahasa Indonesia. It means there’s no absolute answer for this question.</p><p>Then, how do one verify answers provided by AI? I judged their approach. Shallow AI shows rough translation and stop there. Better AI goes further by analyzing context and having real-life use case. The result goes as search engine input to make sure someone actually uses it, just like an expert approaching new concept. I also compared it to their understanding of “order of magnitude” in English as reference.</p><p>Correct answer: valid translation yields one mark ✅. Additional context yields another ✅. Understanding of concept yields one more mark ✅. Real use case on internet yields one mark ✅.</p><ul><li>ChatGPT 4o-mini: “orde besaran”, it translates and adds context. It also understands the concept (didn’t include it because too long). “Orde besaran” yields weak search engine result, though. ✅✅✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*oMc2cHYCquHuc9KdP1rw8A.jpeg" /></figure><ul><li>Gemini 2.0 Flash: tends to play safe and offers many possible outputs with context. Some are gibberish. ✅✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*9mVFzgur0jg9b0p2ISC6kQ.jpeg" /></figure><ul><li>Microsoft 365 Copilot: “orde besaran”, it translates but lacks deeper context. It understands the concept. ✅✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Ux616-vzV-qNvIqhl3FU1Q.jpeg" /></figure><ul><li>Meta AI on WhatsApp (Llama 3.2): “orde besaran”, it translates but lacks deeper context. It also lacks concise understanding. ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*963WSDlmWv7GDF6tjuQ34Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*bqoiAe7teqticRbfiXAWEQ.jpeg" /></figure><ul><li>Claude 3.5 Sonnet: “orde besaran”, translate without context, understand the concept. ✅✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*a7V5X__Rh51SwLqoV7lK1Q.jpeg" /></figure><ul><li>DeepSeek-V3: “orde magnitudo”, it translates and adds context. It also understands the concept. Search engine yields better result in “orde magnitudo” rather than “orde besaran” ✅✅✅✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hkj6RsdtBYeGbI4KVFE-vA.jpeg" /></figure><p>Conclusion: DeepSeek seems to have better approach in bringing new concept to existing language, complemented with better understanding in concise way, and better data fit.</p><p><strong>Question 4: Tentukan kata yang tepat untuk mengisi titik-titik di kalimat berikut: “Pak Rafi masuk … ringan”.</strong></p><p>This one is fun. The Indonesian context is so strong it’s lost in translation. The expected word is “angin”, so it forms “masuk angin” which is expression of “having common cold”. It checks whether the AI can capture nuance in Bahasa Indonesia and goes beyond formal structure. Other answer may be correct grammar-wise but lacks intuitive usage. Longer answer is not necessary because the provided word itself already represents the understanding of context.</p><ul><li>Correct answer: “angin” gets two points ✅✅. Technically correct answer gets one point ✅.</li><li>ChatGPT 4o-mini: “angin” ✅✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*HvTuIuYxoNyW3rAX_wul4A.jpeg" /></figure><ul><li>Gemini 2.0 Flash: Again, offers wide context. Basically, it provides list of technically correct answers. ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*KTmvSUOMLSTQo1-S2tcTWQ.png" /></figure><ul><li>Microsoft 365 Copilot: “dengan”, which is technically correct✅. I did some follow-up but didn’t get better result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*j4V6yfCE4CL8huZy3SFFnQ.jpeg" /></figure><ul><li>Meta AI on WhatsApp (Llama 3.2): “dengan”, which is technically correct✅.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nG5FVEeVmEQBViCTTc6KEw.jpeg" /></figure><ul><li>Claude 3.5 Sonnet: “angin” ✅✅.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*Aku_ndAk4RaDO80-SBN9qg.jpeg" /></figure><ul><li>DeepSeek-V3: “rumah sakit” e.g hospital is incorrect❌</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*plSnFNdkprYIwS1WbVttFw.jpeg" /></figure><p>Conclusion: ChatGPT and Claude seems to have fine-tuned its AI to capture nuances in Bahasa Indonesia, while others are stuck in general structure.</p><h4>Final remark</h4><p>ChatGPT has really good understanding of Indonesian context, followed by Claude and DeepSeek. They have the same root and probably has more parameters related to Indonesian context. Others like Gemini, Meta AI, and Copilot are behind on this case.</p><p>I made tier list from this test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XI3_ay-UZ-r3IVWRolPeYA.png" /><figcaption>Free AIs with Indonesian Context Tier List</figcaption></figure><p>That being said, ALWAYS validate your AIs. Never treat them as source of truth. After all, human is always the one hold accountable.</p><blockquote>Thank you for reading this far. I’m <strong>Yogi Saputro</strong>, tech lead at <a href="https://www.alto.id/"><strong>Alto Networks</strong></a>, with an <strong>engineering background and an MBA</strong>. I love exploring technology, software engineering, and their intersection with modern culture.</blockquote><blockquote>What do you think about AI’s understanding of local knowledge? Have you tried testing LLMs yourself? Let’s continue the conversation — connect with me on <a href="https://www.linkedin.com/in/yogisaputro/"><strong>LinkedIn</strong> </a>or reach out via <a href="/service/mailto:yogisaputro@outlook.com"><strong>email</strong></a>!</blockquote><blockquote>If you enjoyed this, check out my other stories on AI, tech, and more <a href="https://yogisaputro.medium.com/"><strong>here</strong></a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=925e66d75cd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Breaking Tables, Delivering Features: A Developer’s Guide to SQL Normalization”]]></title>
            <link>https://yogisaputro.medium.com/breaking-tables-delivering-features-a-developers-guide-to-sql-normalization-d9ff05a6e558?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ff05a6e558</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 08:59:36 GMT</pubDate>
            <atom:updated>2024-01-06T18:14:21.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*kLjTTl6DuoUIjKOJ.png" /></figure><p>Your new feature will break sophisticated, well-thought, beautiful, current SQL database structure? Worry not. This guide is here to help fellow developers to handle feature that involves changing database structure. With example, of course.</p><p>Please note that this guide is focused on normalizing SQL database. This is not related to programming language, nor this applies to NoSQL database.</p><p>Let’s dive in.</p><h3>Database Change is Inevitable</h3><p>First, a little background. As time passes, product usually grows following business needs. Complexity also grows. You will have more feature tickets awaiting. On one hand, this is good sign. People are using the product, which turns into revenue, which turns into your salary. Hopefully.</p><p>On the other hand, you will be pressed to work on new features, and more often than not, require changes on your codebase and database. It is not due to lack of planning. No one could cover all possible cases and put it into code. Therefore, the <strong>number zero tip is to embrace the change</strong> and deal with it.</p><p>I have encountered quite some breaking changes in my career. The early ones felt frustrating. I thought “They are messing with my desgin? Why didn’t they thought about it?”. Then sometimes I even doubt myself “Why didn’t I thought about it?”. That was bad. Then I realized it is just inherent reality of evolving product. After some more time, I finally developed simple guide to deal with it.</p><h3>Real World Example: NEW Split Bill Payment</h3><p>Suppose that your product is a restaurant management system that allows customer to see menu, make orders, and pay through app/website while dining-in. It reduces restaurant’s staff cost and improve efficiency.</p><p>Now the product have implemented order with payment. However, everyone agreed that one order is paid once. In other words, order and payment have 1:1 relation. Few weeks later, the company received feedback. Now people want to split bills. This means 1:1 relation between order and payment turns to 1:N relation.</p><p>What do you have to do now? Keep reading and follow these steps</p><h3>1. Identify Impacted Tables and Columns</h3><p>Once it is known that some table relations will be changed from 1:1 to 1:N, quickly determine which columns are impacted.</p><p>In example case above, let’s say that existing orders table is structured like this</p><pre>CREATE TABLE orders (<br>  id SERIAL PRIMARY KEY,<br>  order_date TIMESTAMP,<br>  bill_base_amount BIGINT,<br>  tax_amount BIGINT,<br>  other_fee_amount BIGINT,<br>  bill_total_amount BIGINT,<br>  payment_amount BIGINT,<br>  payment_type VARCHAR(255),<br>  payment_timestamp TIMESTAMP,<br>  payment_completed BOOLEAN,<br>  created_at TIMESTAMP,<br>  updated_at TIMESTAMP<br>);</pre><p>This is the table orders with sample data</p><pre>| id | order_date            | bill_base_amount | tax_amount | other_fee_amount | bill_total_amount | payment_amount | payment_type  | payment_timestamp      | payment_completed | created_at            | updated_at            |<br>|----|-----------------------|------------------|------------|------------------|-------------------|----------------|---------------|-------------------------|---------------------|------------------------|------------------------|<br>| 1  | 2023-11-14 12:00:00   | 5000             | 1000       | 200              | 6200              | 6200           | Credit Card   | 2023-11-14 12:05:00    | true                | 2023-11-14 12:00:00    | 2023-11-14 12:05:00    |</pre><p>In this case, following columns should be separated as new table.</p><pre>- `payment_amount`<br>- `payment_type` <br>- `payment_timestamp` <br>- `payment_completed`</pre><p>Why bill_total_amount and some others are not included in new table? Because the information is related to order as a whole. Furthermore, for bill_total_amount it is practical later as checker to make sure sum of all split bills are equal to bill on order.</p><p>Once impacted columns are identified, you need to make new table.</p><h3>2. Create New Table</h3><p>Now, a new table is needed to store payment data. Such table requires</p><ul><li>Identifier → id</li><li>Foreign key to orders --&gt; order_id</li><li>Impacted columns above</li><li>Timestamps → just good practice</li></ul><p>In SQL, this is one example</p><pre>CREATE TABLE payments (<br>  id SERIAL PRIMARY KEY,<br>  order_id INT REFERENCES orders(id),<br>  payment_amount INT,<br>  payment_type VARCHAR(255),<br>  payment_timestamp TIMESTAMP,<br>  payment_completed BOOLEAN,<br>  created_at TIMESTAMP,<br>  updated_at TIMESTAMP<br>);</pre><p>Now, you have the building blocks in the database. Time to start refactoring.</p><h3>3. Change Existing Codebase Logic</h3><p>At this point, you’d know orders and payments has1:N relation, meaning one order could have at least one payment. You just need to insert data to orders and payments. However, it&#39;s still unclear to insert the data. There are at least 2 options:</p><ol><li>Assuming there’s order_menu table (it&#39;s common sense for dev, right?), you can split by menu price. The splitting process is another part entirely, but from database perspective, all payment records can be generated and inserted together.</li><li>Split by amount. This approach relies on amount input. This allow each payment to be generated independently. However, the total amount must be thoroughly checked.</li></ol><p>Which one is better? It depends on what product team wants :)</p><p>This is an approach in Node.js</p><pre>const pgp = require(&#39;pg-promise&#39;)();<br>const db = pgp(&#39;your_connection_string&#39;);<br><br>// Sample data for an order<br>const orderData = {<br>  order_date: new Date(),<br>  bill_base_amount: 5000,<br>  tax_amount: 1000,<br>  other_fee_amount: 200,<br>  bill_total_amount: 6200,<br>  payment_amount: 6200,<br>  payment_type: &#39;Credit Card&#39;,<br>};<br><br>// Query for inserting into orders<br>const insertOrderQuery = `INSERT INTO orders -- etc`;<br>const insertPaymentQuery = `INSERT INTO payments -- etc`;<br>const mappingToPayments = (order_id) =&gt; {<br>    // do something mapping here<br>    // should be more complex, but you get the idea<br>    return paymentList<br>}<br><br>// Function to insert payments for a specific order_id<br>function insertPayments(order_id) {<br>  const insertPaymentPromises = mappingToPayments(order_id).map((paymentData) =&gt; {<br>    // Modify paymentData to include the order_id for the query<br>    const modifiedPaymentData = { ...paymentData, order_id };<br>    <br>    // Execute the query to insert into payments<br>    return db.none(insertPaymentQuery, modifiedPaymentData);<br>  });<br><br>  // Return a promise that resolves when all payments are inserted<br>  return Promise.all(insertPaymentPromises);<br>}<br><br>// Execute the first query to insert into orders<br>db.one(insertOrderQuery, orderData)<br>  .then((result) =&gt; {<br>    // Use the returned order_id in the function to insert payments<br>    const order_id = result.id;<br>    <br>    // Call the function to insert payments for the order_id<br>    return insertPayments(order_id);<br>  })<br>  .then(() =&gt; {<br>    console.log(&#39;Order and payments inserted successfully.&#39;);<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&#39;Error inserting order and payments:&#39;, error);<br>  })<br>  .finally(() =&gt; {<br>    pgp.end(); // Close the database connection when done<br>  });</pre><p>Also, don’t forget to refactor the query to fetch data. Plus, make sure to test your code.</p><h3>4. Migrate Existing Data</h3><p>Now that you’ve taken care of the development. It is time to migrate the data. As you’ve known, existing data is in orders. After deployment, they better be in payments as well.</p><p>Fortunately, there’s one-time query for this.</p><pre>INSERT INTO payments (order_id, payment_amount, payment_type, payment_timestamp, payment_completed, created_at, updated_at)<br>SELECT<br>  id AS order_id,<br>  bill_total_amount AS payment_amount, -- Assuming one payment for one order<br>  payment_type,<br>  payment_timestamp,<br>  true AS payment_completed,  -- Assuming all existing payments are completed<br>  created_at,<br>  updated_at<br>FROM orders<br>WHERE payment_type IS NOT NULL;  -- Add additional conditions if needed</pre><p>The query above copies existing data from orders to payments , with condition that payment_type exists. It assumes few things like all previous orders have exactly one payment and they all are completed. If there’s more complexities (e.g not all payments are completed), you need to handle them first before executing query above.</p><h3>6. Deploy &amp; Run</h3><p>This is time where you actually execute all steps above in production environment. Fingers crossed!</p><p>That’s it! I hope this guide helps you. Comments and feedbacks are always appreciated. Stay sane, developers :)</p><p>(Cover image generated by <a href="https://playgroundai.com/">playground.ai</a>)</p><p><em>Originally published at </em><a href="https://dev.to/yogski/breaking-tables-delivering-features-a-developers-guide-to-sql-normalization-56p3"><em>https://dev.to</em></a><em> on November 14, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ff05a6e558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Storytelling: Industri Apa yang Pemainnya Paling Cuan?]]></title>
            <link>https://yogisaputro.medium.com/data-storytelling-industri-apa-yang-pemainnya-paling-cuan-7899bcb2e8d0?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/7899bcb2e8d0</guid>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[indonesia]]></category>
            <category><![CDATA[industry]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 04:03:02 GMT</pubDate>
            <atom:updated>2022-11-02T04:03:02.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Pertanyaan seperti ini pernah hinggap di kepala saya, dulu waktu baru lulus kuliah. Saya rasa semua juga pernah mengalami. Rasa ketika butuh uang. Rasa ketika pilihan terbentang, dan diri ini perlu memutuskan bidang apa yang akan dijalani. Entah itu menjadi pekerja atau pengusaha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVHOOdTlofmZp82l0mQ5hw.png" /><figcaption>Industri paling cuan. Gambar dibuat oleh Kecerdasan Buatan DALL-E 2.</figcaption></figure><p>Lalu, layaknya laron yang mencari cahaya paling terang, kita mencari bidang yang uangnya bergelimang. Nah, yang manakah itu? Apakah sektor teknologi yang semakin lama semakin berkembang? Sektor komoditas yang memang kelebihan Indonesia? Sektor keuangan tempat segala rupa transaksi? Atau mungkin yang lain? Pertanyaan ini menarik buat saya, dan lewat tulisan ini saya ceritakan industri paling cuan di Indonesia. Tentunya dengan data.</p><h4>Pertama, Rumuskan Ulang Pertanyaan 📐</h4><p>Sebelum mencari data dan berkutat dengan berbagai grafik, saya perlu tahu apa yang sebenarnya saya cari. Betul, saya mau cari industri yang paling cuan bagi pemainnya. Tapi kalau saya teliti lagi, definisi ini masih terlalu umum.</p><p>Pertama, apa arti dari cuan? Cuan = untung. Berarti saya perlu cari keuntungan bersih per industri. Masuk akal? Ya. Masalahnya, mencari nilai data keuntungan bersih tergolong sulit. Saya bukan orang dalam Kemendag, Kemenperin, atau Kemenkeu. Di sisi lain, BPS punya data PDB (Produk Domestik Bruto) atau PDRB (Produk Domestik Regional Bruto) berdasarkan industri. Gampangnya, PDB sama dengan nilai tambah ekonomi. Oke, di sini cuan saya artikan sebagai nilai PDB. Namun cukupkah PDB saja?</p><ul><li>Sektor A nilai PDB Rp1 triliun dan di dalamnya ada 1.000.000 orang, tiap orang berkontribusi Rp1.000.000</li><li>Sektor B nilai PDB Rp100 miliar dan di dalamnya ada 50.000 orang, jadi tiap orang berkontribusi Rp2.000.000</li></ul><p>Dari contoh di atas, meski PDB sektor A &gt; PDB sektor B, ternyata pemain dalam sektor B menghasilkan nilai tembah 2x sektor A.</p><p>Dengan demikian, saya rumuskan ulang pertanyaannya menjadi</p><blockquote>Industri mana yang nilai tambah per kapitanya paling besar?</blockquote><p>Secara kasar, <a href="https://en.wikipedia.org/wiki/Gross_value_added">PDB suatu sektor</a> setara dengan omzet sektor, termasuk beban pengeluaran (gaji, biaya usaha), depresiasi, dan pajak, minus subsidi. Kemudian kalau bicara omzet dan pengeluaran tentunya setiap industri punya struktur biaya sendiri. Ini juga akan saya perhatikan ketika membahas industri nanti.</p><p>Selanjutnya untuk definisi pemain industri saya perjelas menjadi pengusaha dan pegawai. Secara umum, semakin tinggi nilai tambah per kapita, semuanya semakin cuan. Namun pemisahan pengusaha dan pegawai ini memberikan pertanyaan baru : Adilkah proporsi nilai tambah yang dinikmati pemilik usaha dan pegawai? Untuk menjawab itu, saya munculkan ukuran baru: <strong>rasio gaji rata-rata tahunan dan nilai tambah per kapita</strong>. Rasio tersebut akan kita bandingkan dari tahun ke tahun.</p><blockquote>Semakin kecil rasio gaji rata-rata terhadap nilai tambah per kapita, semakin besar ketidakadilan antara porsi pegawai dan pemilik usaha. Dalam kasus tersebut, porsi cuan pemilik usaha jauh lebih besar.</blockquote><p>Apakah definisi ini cukup? Untuk iterasi pertama, ya. Sambil berjalan, kita akan menemukan lebih banyak temuan menarik.</p><h4>Gali Data 🔍</h4><p>Untungnya, BPS sudah memberikan semua yang dibutuhkan. <a href="https://www.bps.go.id/subject/11/produk-domestik-bruto--lapangan-usaha-.htm">Data PDB berdasarkan sektor</a> dan <a href="https://www.bps.go.id/statictable/2009/04/16/970/penduduk-15-tahun-ke-atas-yang-bekerja-menurut-lapangan-pekerjaan-utama-1986---2022.html">data tenaga kerja berdasarkan sektor</a> sudah tersaji apik (di tingkat nasional saja, jangan berharap banyak untuk data tingkat provinsi dan daerah). Saya mengambil data tahun 2016–2021 untuk menunjukkan trennya, sehingga hasil dari analisis ini bukan dari satu titik pengamatan.</p><p>Versi data siap olah tersedia di <a href="https://github.com/yogski/data-storytelling">repo Github</a> saya. Boleh di-<em>star </em>apabila bermanfaat 😉</p><h4>Inilah Sumber Cuan Indonesia! 🚀</h4><p>Jadi, industri mana yang paling cuan di Indonesia? Lanjut! Saya <em>countdown</em> dari lima besar.</p><p><strong>5. Industri Pengolahan</strong></p><p>Industri pengolahan meliputi semua industri yang mengubah barang mentah ke barang jadi atau setengah jadi. Mulai dari makanan, minuman, tekstil, logam, mesin, obat, jepit rambut, dan seterusnya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*Hk7cgdUXx_8JtlSHhCsL8Q.png" /><figcaption>Sektor Industri Pengolahan 2016–2021</figcaption></figure><p>Data menunjukkan nilai tambah per kapita per tahun sekitar Rp143 juta. Sementara upah rata-rata pegawainya Rp32 juta per tahun. Artinya, pegawai di sektor ini dibayar 32 juta untuk menghasilkan 143 juta. Rasio upah dan nilai tambah per kapita cenderung stabil sejak tahun 2016 di kisaran 22%.</p><p>Apakah struktur kontribusi ini adil? <em>Surprisingly, yes</em>. Industri pengolahan banyak disorot dan diatur regulasi. Pemilik usaha sektor ini wajib memenuhi standar UMK atau UMP. Posisi pekerja di sektor ini lebih aman. Pekerja sektor lain seperti ritel dan akomodasi makan minum punya rata-rata gaji lebih rendah. Selain itu, ada banyak komponen biaya seperti transportasi, mesin produksi, bahan baku. Keuntungan bersih di sektor ini rata-rata kasarnya sebesar 10%. Total nilai tambah lebih banyak untuk pegawai daripada pemilik usaha. Meskipun begitu, jumlah karyawan 10.000x jumlah pemilik usaha, jadi dapatnya lebih sedikit 🤪.</p><p>Jadi, kalau anda seorang karyawan pabrik, anda cukup cuan. Anda punya pabrik, anda lebih cuan.</p><p><strong>4. Jasa Keuangan &amp; Asuransi</strong></p><p>Industri ini meliputi perbankan, <em>leasing</em>, <em>financing</em>, asuransi, investasi, pengelola dana baik konvensional maupun syariah.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*08RbG-PRw_17MhGbJplDgw.png" /></figure><p>Seperti tampak pada grafik di atas, nilai tambah dari 2016 hingga 2021 cenderung membaik. Pertumbuhan nilai tambahnya 6%. Kemudian nilai tambah per kapita sebesar Rp281 juta pada 2021. Di sisi lain, nilai upah rata-rata konstan di kisaran Rp50 juta per tahun. Rasio gaji dibanding nilai tambah per kapita terus menurun dari 24,2% di 2016 menjadi 17,5% di 2021.</p><p>Dalam sektor keuangan terdapat biaya operasional cukup besar. Dari infrastruktur ada kantor cabang, brankas penyimpanan, server yang harus menyala nonstop 24/7/365. Kemudian ada kegiatan marketing yang berbiaya besar. Belum lagi jika ada risiko fraud dan gagal bayar. Secara regulasi, sektor keuangan sangat ketat dengan pengawasan berbagai pihak seperti BI dan OJK. Kemudian, sepertinya faktor gaji ditekan sedemikian rupa. Dengan gaji di sektor ini di atas rata-rata, otomatis <em>supply </em>tenaga kerja tinggi dan pemilik usaha punya daya tawar lebih tinggi.</p><p>Artinya apa? Jadi pemilik usaha di bidang keuangan dan asuransi sangat cuan. Kalau jadi pegawai, pemasukan anda bakal stabil tapi tidak terlalu cuan. Mungkin sudah waktunya minta tambah pesangon ke atasan🧐.</p><p><strong>3. Pertambangan &amp; Penggalian</strong></p><p>Industri ini meliputi aktivitas penambangan batu bara, minyak bumi, logam, mineral, serta aktivitas penunjangnya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*KnwEegOIhI_hM-mKnaeW_Q.png" /></figure><p>Nilai tambah per kapita industri ini lumayan fantastis. Satu orang berkontribusi sekitar Rp600 juta per tahun. Gaji rata-ratanya pun lebih tinggi dari dua industri sebelumnya, sekitar Rp52 juta per tahun. Dari tahun 2016 hingga 2022, kondisinya cenderung stagnan. Rasionya pun konsisten di kisaran 9%. Dari sisi nilai rasionya, tampak ketimpangan besar antara porsi pegawai dan pemilik usaha di sektor ini.</p><p>Komponen besar biaya di industri ini adalah perizinan dan alat/mesin penambangan. Secara regulasi, sektor ini juga ketat dengan berbagai peraturan terkait lingkungan. Seperti sektor keuangan &amp; asuransi, sektor ini sepertinya menekan pertumbuhan gaji dengan memanfaatkan <em>supply</em> tenaga kerja yang tertarik gaji tinggi.</p><p>Secara statistik, pemilik usaha tambang itu <em>crazy rich</em>. Sementara pegawai di industri pertambangan itu mapan dan makmur. Kurang cuan apalagi?</p><p><strong>2. Informasi &amp; Komunikasi</strong></p><p>Sepertinya sektor ini awalnya menaungi segala yang berhubungan dengan informasi beserta teknologinya. Sekarang, sektor ini terasa cukup <em>random</em>. <em>Content creator </em>masuk, situs berita masuk, artis masuk, <em>provider</em> internet masuk, jasa pemrograman masuk, penerbit buku masuk, <em>data center </em>masuk. Dengan berkembangnya teknologi, sektor ini meroket dan diperkirakan masih memunculkan peluang-peluang baru.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*_DgHZPphVFUbl4wmj0DezA.png" /></figure><p>Nilai tambah per kapita selama 2016–2021 cukup fluktuatif dengan rata-rata pertumbuhan 1,4%. Per 2021, setiap orang berkontribusi nilai tambah sebesar Rp750 juta. Di sisi lain, gaji rata-rata relatif konstan di kisaran Rp50 juta per tahun. Rasionya sangat rendah, hanya di kisaran 6,5%-7,5%.</p><p>Apakah struktur perolehan nilai tambah adil di sektor ini? <strong>Sama sekali tidak</strong>. Berbeda dengan industri keuangan dan pertambangan yang regulasinya ketat, industri informasi dan komunikasi bisa diibaratkan <em>wild west</em>, setidaknya hingga 3–5 tahun ke depan. Belum ada tuntutan dan standar yang harus dipenuhi sehingga biaya di sektor ini bisa ditekan. Selain itu, <em>resource</em> utama sektor ini adalah perangkat teknologi dan kemampuan SDM. Seharusnya SDM mendapat kompensasi lebih. Pandangan pribadi saya, semestinya komponen gaji bisa melebihi sektor industri pengolahan. Dengan rasio 25% misalnya, gaji ideal di sektor ini adalah Rp188 juta per tahun.</p><p>Kalau anda pemilik usaha di sektor ini, anda kalau bukan <em>influencer</em> ya <em>silently rich</em>. Kalau anda pegawai dengan keahlian dan kontribusi mumpuni, mintalah gaji hingga Rp188 juta per tahun atau cari usaha sendiri.</p><p><strong>1.Real Estat</strong></p><p>Dan juara industri paling cuan di Indonesia adalah real estat alias properti! Ini meliputi jual-beli dan sewa tanah maupun bangunan. Nilai tambahnya per 2021 mencapai lebih dari Rp1 miliar per kapita. Hal ini tentunya didorong tren kenaikan harga properti. Pertumbuhan tahunan nilai tambah per kapita sejak 2016 sebesar 5%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*8aAL9mwW9exHXouh5Eelgg.png" /></figure><p>Di sisi lain, gaji di sektor ini berada di kisaran Rp40 juta hingga Rp48 juta per tahun dalam periode 2016–2021. Nilai tersebut cukup tinggi (meskipun bukan sektor dengan gaji tertinggi). Rasio gaji dan nilai tambah per kapita sebesar 5%. Tentunya rasio tersebut rendah, namun karakter sektor real estat berbeda dengan sektor lainnya.</p><p>Pertama, pendapatan pegawai bidang real estat didominasi sistem komisi. Nilai komisi beragam, umumnya di bawah 5% nilai properti. Jadi meskipun rasionya rendah, secara individu pegawai real estat memperoleh pendapatan yang lebih mendekati kontribusi nilai tambahnya.</p><p>Kedua, pekerjaan real estat kerap dihitung bisnis sampingan. Artinya, jumlah pemain riil di sektor real estat lebih banyak daripada jumlah pemain yang tercantum dalam statistik. PNS yang punya kos-kosan tidak dihitung tenaga kerja sektor real estate, namun menyumbang nilai tambah di sektor tersebut. Artinya, nilai tambah per kapita yang riil seharusnya lebih rendah daripada nilai pada grafik di atas. Nilai rasio pendapatan dan nilai tambah per kapita pun seharusnya lebih besar lagi. Seberapa banyak? <em>Well</em>, ini bisa jadi saran untuk penelitian lanjutan.</p><p>Ketiga, biaya <em>marketing </em>di sektor ini sangat besar. Pemain besar di sektor ini berani membuat acara televisi. Yang lainnya mengisi reklame di perempatan strategis, membuat <em>booth</em> di mal, dan merecoki warga-warga yang terlihat mapan.</p><p>Di sektor ini setiap pemain memperoleh sesuai kontribusinya. Yang membangun dari awal dapat margin besar. Yang menjadi broker dapat komisi. Jadi bisa dikatakan adil. Anda bisa pas-pasan ataupun tajir melintir di sektor ini, tergantung usahanya.</p><figure><img alt="Grafik lima besar industri paling cuan di Indonesia: real estat, informasi &amp; komunikasi, pertambangan, jasa keuangan, dan industri pengolahan." src="https://cdn-images-1.medium.com/max/963/1*OAEQEJMK2WD0shAeprXFpA.png" /><figcaption>Grafik lima besar industri paling cuan di Indonesia</figcaption></figure><h4>Intinya</h4><p>Berikut adalah jalan cuan di Indonesia</p><ul><li>Jika punya akses modal dan perizinan, silakan jadi pemilik usaha industri pengolahan, pertambangan, atau keuangan.</li><li>Jika kuat jiwa wirausaha, bikin usaha bidang real estat atau informasi dan komunikasi.</li><li>Jika pintar jualan dan punya koneksi luas, masuk jadi pemain real estat.</li><li>Jika punya skill, masuk industri informasi dan komunikasi dan perjuangkan gajimu.</li><li>Jika ingin hidup oke dan stabil, jadi pegawai bidang industri pengolahan, pertambangan, atau keuangan.</li></ul><h4>Potensi Analisis Lanjutan📚</h4><p>Di samping <em>insight </em>di atas, ada beberapa hal yang bisa digali lebih lanjut.</p><ul><li>Data yang digunakan adalah data BPS pusat, alias tingkat nasional. Data ini cenderung lebih relevan untuk wilayah Pulau Jawa sebab sebagian besar nilai tambah maupun tenaga kerja ada di sana. Di Sumatra, lebih baik jadi juragan sawit. Begitupun di wilayah lain, ada industri lain yang lebih cuan. Studi detail per provinsi bisa membuka <em>insight </em>tambahan. (NB: akses data ke BPS provinsi cukup menyiksa)</li><li>Ada industri dengan nilai tambah per kapita sangat besar, ada yang nilai tambahnya demikian kecil sampai saya menduga industri tersebut nombok alias perlu disubsidi. Analisis industri seperti ini bisa berguna untuk identifikasi masalah industri dan investasi potensial.</li></ul><p>Sebagai penutup, saya ingin menyampaikan satu hal. Meskipun statistik menunjukkan hutan itu hijau, akan tetap ada pohon berwarna merah. Meskipun ada industri paling cuan, jalan cuan anda bisa dari mana saja.</p><p>Yogyakarta, 2 November 2022<br>Yogi Saputro</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7899bcb2e8d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Enum Type in PostgreSQL]]></title>
            <link>https://yogisaputro.medium.com/dealing-with-enum-type-in-postgresql-23618f98f1e8?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/23618f98f1e8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Wed, 15 Dec 2021 06:14:51 GMT</pubDate>
            <atom:updated>2024-01-08T05:23:03.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*IgOD7B5vz6uLnaYy.png" /></figure><p>This is a brief guide for effectively understanding and working with enum type in Postgres: Why does it exist? What does it do? How to work with it?</p><h3>Why Does Enum Type Exist? 🌌</h3><p>There is boolean data type to define a binary column in PostgreSQL. Kind of yes/no switch. For example, is_active column is commonly used to describe whether a record is active.</p><p>But what if there are more than two options? Another data type is needed to handle the use case. That data type also has to be strict to prevent other values being written. Then enum comes to the rescue.</p><h3>What Does Enum Type Do Well? ✨</h3><p>Enum type is best solution to describe state data. It basically define states of a record in PostgreSQL. For example, an e-commerce platform needs to track package delivery status. The package is either in packaging process, waiting for pick-up, in delivery, in transit, or already delivered to customer. It can be formalized as five states: PACKAGING, WAITING_PICKUP, IN_DELIVERY, IN_TRANSIT, and DELIVERED. Enum can handle this, in a way that will be described below. Before that, know the characteristics of enum type to better understand it.</p><p>Enum type has following behaviours:</p><ul><li>It is treated as type in PostgreSQL</li><li>It applies to all tables in same schema</li><li>It has static values</li><li>Enum value is case-sensitive</li><li>Enum value size is 4 bytes</li><li>Each enum value is unique (duplicate is not allowed)</li><li>Adding enum value requires ALTER operation</li><li>Order of enum values matter when querying</li></ul><h3>When to Use Enum 🕰️</h3><p>Use enum if:</p><ul><li>Cheap constraint is preferrable</li><li>Enum values won’t change a lot in the future</li><li>Enum values aren’t too many. Personally, I’d say less than 10 as rule of thumb.</li><li>Enum values have different priority</li><li>Avoiding invalid value is necessary</li></ul><p>Otherwise, other solutions like reference table or even simple integer type will suffice.</p><h3>Enum Operations</h3><p>These are the basics of enum operations in PostgreSQL. Think of it as unconventional CRUD operations that I managed to compile. In order to illustrate better, I will draw an example from delivery status mentioned earlier.</p><h4>Create Enum Type</h4><p>Below is general query syntax to create delivery_statusenum type.</p><pre>CREATE TYPE delivery_status <br>AS ENUM (&#39;PACKAGING&#39;, &#39;WAITING_PICKUP&#39;, <br>&#39;IN_DELIVERY&#39;, &#39;IN_TRANSIT&#39;, &#39;DELIVERED&#39;);</pre><h4>Rename Enum Type</h4><p>One can rename enum type by using following query:</p><pre>ALTER TYPE delivery_status RENAME TO delivery_status_1;</pre><h4>Get Enum Values</h4><p>To get list of enum values, use following query</p><pre>SELECT UNNEST(enum_range(null::delivery_status)) <br>AS delivery_status;</pre><p>This is the result after creating delivery_status enum above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*AQt7EDiYFAhAEUDEY8dkGA.png" /><figcaption>Content of delivery_status type</figcaption></figure><h4>Add Enum Value</h4><p>As the product evolves, one realizes that package can be lost, broken, stolen, etc. In such case, new package state is needed. Let’s name it OTHERS to describe unexpected situations that may happen to a package.</p><p>As of version 9.1, PostgreSQL support adding enum value to do just that. Just execute query below.</p><pre>ALTER TYPE delivery_status ADD VALUE &#39;OTHERS&#39;;</pre><p>It is also possible to add value before or after specific value.</p><pre>ALTER TYPE delivery_status ADD VALUE &#39;OTHERS&#39; BEFORE &#39;DELIVERED&#39;;<br>ALTER TYPE delivery_status ADD VALUE &#39;OTHERS&#39; AFTER &#39;IN_TRANSIT&#39;;</pre><p>The result is the same, new value in enum type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*CosdOucNV6UoN6madJLLBQ.png" /><figcaption>Content of delivery_status type after IN_TRANSIT and OTHERS are introduced</figcaption></figure><p>Prior to version 9.1, things were more complicated. A popular workaround consists of three steps:</p><ol><li>Rename enum type to something else</li><li>Create new enum with correct type name and value</li><li>Delete old enum type.</li></ol><pre>ALTER TYPE delivery_status RENAME TO delivery_status_old;<br>CREATE TYPE delivery_status <br>AS ENUM (&#39;PACKAGING&#39;, &#39;WAITING_PICKUP&#39;, <br>&#39;IN_DELIVERY&#39;, &#39;IN_TRANSIT&#39;, &#39;DELIVERED&#39;, &#39;OTHERS&#39;);<br>DROP TYPE delivery_status_old;</pre><h4>Change or delete enum value</h4><p>As of version 10, PostgreSQL support renaming enum value.</p><pre>ALTER TYPE delivery_status RENAME VALUE &#39;PACKAGING&#39; TO &#39;PREPARING&#39;;</pre><p>Other than that, PostgreSQL doesn’t support changing or deleting specific enum value. The workaround is the same as above: rename old type, create new and correct type, and delete old type.</p><pre>-- change PACKAGING to PREAPRING<br>ALTER TYPE delivery_status RENAME TO delivery_status_old;<br>CREATE TYPE delivery_status <br>AS ENUM (&#39;PREPARING&#39;, &#39;WAITING_PICKUP&#39;, <br>&#39;IN_DELIVERY&#39;, &#39;IN_TRANSIT&#39;, &#39;DELIVERED&#39;, &#39;OTHERS&#39;);<br>DROP TYPE delivery_status_old;<br><br>-- delete IN_TRANSIT value<br>ALTER TYPE delivery_status RENAME TO delivery_status_old;<br>CREATE TYPE delivery_status <br>AS ENUM (&#39;PREPARING&#39;, &#39;WAITING_PICKUP&#39;, <br>&#39;IN_DELIVERY&#39;, &#39;DELIVERED&#39;, &#39;OTHERS&#39;);<br>DROP TYPE delivery_status_old;</pre><p>After changing enum value PACKAGING to PREPARING</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*MEmnRAVd5P6XwftrZG_X6g.png" /><figcaption>delivery_status type after changing PACKAGING to PREPARING</figcaption></figure><p>After removing IN_TRANSIT value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*Ssxa3lk6mGgSIklvGmviOA.png" /><figcaption>delivery_status type after removing IN_TRANSIT</figcaption></figure><h4>Delete enum type</h4><p>To delete enum type and all of it values, execute following query</p><pre>DROP TYPE delivery_status;</pre><h3>Conclusion 🔚</h3><p>Enum type is useful tool to ensure type safety in PostgreSQL. I personally use it to make sure system flow doesn’t mess up. I find this short article is useful to remind me important things about enum in PostgreSQL. I hope it helps you as well, dear readers.</p><p>If you find other tips to deal with enum types in PostgreSQL, please let me know in comments.</p><p>Stay sharp and curious.</p><p><em>This post is originally published at my </em><a href="https://dev.to/yogski/dealing-with-enum-type-in-postgresql-1j3g"><em>https://dev.to</em></a><em> account on December 15, 2021. Feel free to check other technical articles there as well.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23618f98f1e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arsitektur Microservice untuk Data Publik (Bagian 2) : Implementasi dengan Next.js]]></title>
            <link>https://yogisaputro.medium.com/arsitektur-microservice-untuk-data-publik-bagian-2-implementasi-dengan-next-js-7e437cab7724?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e437cab7724</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[public-sector]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 18:53:17 GMT</pubDate>
            <atom:updated>2021-10-17T08:34:25.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arsitektur Microservice untuk Data Publik (Bagian 2) : Implementasi dengan Next.js</h3><p><em>Artikel ini adalah bagian dari Serial Arsitektur Microservice untuk Data Publik, sebuah uraian untuk membuat data publik tersedia . </em><a href="https://yogisaputro.medium.com/arsitektur-microservice-untuk-data-publik-bagian-1-68a387d9fabe"><em>Lihat Bagian 1</em></a><em>.</em></p><h4>Microservice tanpa Database? Bisa.</h4><p>Di artikel sebelumnya, saya membahas desain layanan data publik yang lebih baik. Mulai dari paling sederhana hingga kompleks. Tapi seperti kata Linus Trovalds, “<em>Talk is cheap. Show me the code.</em>” Sekarang waktunya untuk singsingkan lengan baju dan meraih kibor.</p><p>Di kesempatan ini, saya akan membuat API untuk menampilkan data perusahaan/emiten yang terdaftar di Bursa Efek Indonesia alias IDX. Data tersebut akan disimpan sebagai <em>file </em>JSON, sehingga menghilangkan kebutuhan pemakaian <em>database</em>. Selanjutnya, saya membutuhkan <em>framework</em> FE yang dilengkapi manajemen <em>routing </em>dan <em>request-response</em>. Next.js adalah kandidat yang cocok, ditambah dengan opsi <em>integrated deploy </em>lewat Vercel. Gratis pula.</p><figure><img alt="Arsitektur microservice untuk data publik paling sederhana" src="https://cdn-images-1.medium.com/max/461/1*jZm6PqCgjPgYGS5cq5gU7w.png" /><figcaption>Gambar 1: Arsitektur Microservice</figcaption></figure><p>Mengacu pada Gambar 1, yang perlu dilakukan sebagai berikut</p><ol><li>Mencari data emiten publik. <a href="https://idx.co.id/">https://idx.co.id/</a> adalah tempat paling cocok untuk mencari.</li><li>Mengubah data menjadi JSON.</li><li>Membuat <em>repository </em>Next.js, lalu mulai koding.</li><li><em>Deploy microservice </em>ke Vercel.</li></ol><p>Karena saya baik hati dan lolos Tes Karakteristik Kepribadian CPNS, saya sudah sediakan <a href="https://github.com/yogski/indonesian_public_data/blob/master/json/indonesia_public_companies.json">data emiten format JSON</a>. Jika berkenan, silakan repo Github saya di-<em>star </em>ya😉. Kalau penasaran bagaimana cara menjalankan langkah 1 dan 2, silakan baca <a href="https://dev.to/yogski/data-wrangling-with-vscode-yes-really-2bbf">artikel saya tentang <em>data wrangling</em></a> di <em>dev.to </em>(bahasa Inggris ya).</p><p>Kalau ingin melihat hasil akhirnya, bisa cek ke <a href="https://emiten-api.vercel.app/api/emiten">https://emiten-api.vercel.app/api/emiten</a>. <em>Repository </em>bisa dicek di <a href="https://github.com/yogski/emiten-api">https://github.com/yogski/emiten-api</a>. Tutorial lengkapnya silakan baca sampai selesai ya.</p><h4>Implementasi dengan Next.js</h4><p>Sekarang saya beralih ke <em>repository</em>. Pastikan Node.js dan NPM sudah dipasang di komputer. Kalau belum, silakan merujuk pada <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">halaman berikut</a>. Selanjutnya, pilih <em>workspace </em>di komputer. Oh ya, di artikel ini saya pakai Windows 10. OS lain bisa menyesuaikan. Lalu masukkan perintah berikut.</p><pre>npx create-next-app emiten-api -e api-routes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*N6IsuESTF73UOxBytBVJfA.png" /><figcaption>Sabar menanti setup Next.js</figcaption></figure><p>Folder <em>repository </em>emiten-api akan muncul dengan <em>template </em>ala REST API. Isinya kurang lebih seperti ini.</p><pre>-- components<br> |-- Person.js  --&gt; untuk tampilan front-end (tidak diperlukan)<br>-- node_modules<br>-- pages<br> |-- api/people --&gt; endpoint API yang penting untuk microservice ini<br>   |-- [id].js<br>   |-- index.js<br> |-- person --&gt; route untuk front-end denga tampilan HTML (tidak diperlukan)<br>   |-- [id].js<br> |-- index.js --&gt; tidak diperlukan<br>.gitignore<br>data.js --&gt; template data, bisa diganti dengan data emiten<br>package-lock.json<br>package.json<br>README.md</pre><p>Ini mempercepat kita membuat <em>microservice</em>. Hanya perlu penyesuaian untuk megganti data dan logika <em>template </em>(Person) dengan emiten.</p><p>Tahap selanjutnya adalah bersih-bersih <em>template</em>. Di dalam <em>template </em>terdapat <em>folder/file </em>yang tidak diperlukan, seperti /components , /pages/person , /pages/index.js , dan data.js . Semuanya dihapus agar lebih ramping.</p><p>Selanjutnya, pasang <em>file </em>JSON daftar emiten terdaftar di IDX. Setelah itu, ganti nama folder untuk mengganti <em>route </em>di API. Misalnya folder person diganti dengan nama emiten .</p><p>Kemudian, diketahui bahwa pencarian emiten biasanya berdasarkan kode emiten yang terdiri dari 4 huruf kapital. Untuk mengakomodasi hal tersebut, <em>file </em>[id].js dalam folder /api/emiten (sudah diganti dari person ya) diubah menjadi [code].js . Hasil akhirnya, struktur project emiten-api bisa lebih ramping, seperti ini.</p><pre>-- node_modules<br>-- pages<br> |-- api/emiten --&gt; ganti nama folder<br>   |-- [code].js --&gt; ganti nama file<br>   |-- index.js<br>.gitignore<br>indonesia_public_companies.json --&gt; ganti sumber data<br>package-lock.json<br>package.json<br>README.md</pre><p>Sekarang beralih ke <em>logic </em>dari API. Ada 2 <em>endpoint </em>yang telah dibuat, /api/emiten dan /api/emiten/{:code} . Isinya jadi seperti berikut.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64b6aa44c9f6ed69b89b46be0d34a282/href">https://medium.com/media/64b6aa44c9f6ed69b89b46be0d34a282/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3314c7296cd9c6356df45be851e7e0a/href">https://medium.com/media/d3314c7296cd9c6356df45be851e7e0a/href</a></iframe><p>Apa lagi?</p><p>Sudah beres <em>development</em>, sekarang tinggal coba dijalankan dengan perintah berikut:</p><pre>npm run dev</pre><p>Lalu akses http://localhost:3000/api/emiten/BBRI , maka akan terlihat respon sebagai berikut.</p><pre>{<br>  &quot;kode_emiten&quot;:&quot;BBRI&quot;,<br>  &quot;nama_emiten&quot;:&quot;Bank Rakyat Indonesia (Persero&quot;,<br>  &quot;tanggal_listing&quot;:&quot;2003-11-10T00:00:00&quot;,<br>  &quot;jumlah_saham&quot;:122112351900,<br>  &quot;kategori&quot;:&quot;Utama&quot;<br>}</pre><h4>Tambah Endpoint Baru</h4><p>Perlu tambah <em>endpoint </em>baru? Tidak masalah. Kita tentukan dulu <em>routing</em>, kemudian tambahkan <em>file </em>atau <em>folder </em>baru. Misalnya saya akan membuat <em>endpoint </em>untuk tampilkan emiten berdasarkan kategori. Saya tentukan <em>routing</em> /api/emiten/category/{:category} . Berarti saya perlu membuat <em>folder </em>category dalam emiten , dan di dalamnya buat file [category].js .</p><p>Struktur <em>project </em>akan jadi seperti berikut.</p><pre>-- node_modules<br>-- pages<br> |-- api/emiten --&gt; ganti nama folder<br>   |-- [code].js --&gt; ganti nama file<br>   |-- index.js<br>   |-- categories<br>     |-- [category].js<br>.gitignore<br>indonesia_public_companies.json --&gt; ganti sumber data<br>package-lock.json<br>package.json<br>README.md</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b008ab4037780dc5bd7016deec9f24d/href">https://medium.com/media/8b008ab4037780dc5bd7016deec9f24d/href</a></iframe><h4><em>Deployment</em></h4><p>Mengikuti panduan resmi di <a href="https://nextjs.org/docs/deployment">halaman ini</a>, deployment Next.js ke Vercel sangat praktis. Intinya yang perlu dilakukan adalah</p><ol><li>Daftar Vercel</li><li>Hubungkan Vercel ke <em>repository</em> Github yang akan di-<em>deploy</em>.</li><li>Pastikan Vercel memiliki <em>permission </em>untuk akses <em>repository </em>yang akan di-<em>deploy</em>.</li><li>Begitu sudah berhasil, proses <em>deployment </em>gratis akan berjalan cepat.</li><li>Jika <em>deployment </em>berhasil, kita akan mendapat <em>address </em>dari <em>microservice</em>. Saya dapat <a href="https://emiten-api.vercel.app/api/emiten/BBCA">https://emiten-api.vercel.app/api/emiten/BBCA</a> dengan tampilan seperti ini.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*QLBvgLAXfd4FLu54O_jmsA.png" /></figure><h4>Beberapa Hal Kecil yang Penting</h4><ul><li>Jangan lupa buat dokumentasi API anda, <em>routing</em> bagaimana, parameter URL apa saja, dll.</li><li>Jangan berharap membuat <em>microservice </em>yang siap naik <em>production </em>dari artikel sini. Ini adalah <em>proof of concept</em>.</li><li>Jangan berharap kinerja <em>response time </em>di bawah 200ms. Orang <em>deploy </em>aja gratisan <strong>😅.</strong></li></ul><h4>Penutup</h4><p>Implementasi dengan Next.js ini memungkinkan data publik tersedia lewat standar REST API dan dijalankan oleh <em>microservice </em>ringan. Tentunya ada beberapa kekurangan seperti pembaruan data yang harus manual. Namun secara keseluruhan manfaatnya lebih besar dan kekurangannya bisa diantisipasi.</p><p>Besar harapan saya tulisan ini dibaca oleh pegiat teknologi dan pengambil kebijakan di sektor publik. Kalau jadi diimplementasikan ya lumayan, punya segudang API yang bisa dimanfaatkan publik.</p><p><em>Artikel ini adalah bagian dari Serial Arsitektur Microservice untuk Data Publik. Lihat artikel bagian 1di sini (</em><a href="https://yogisaputro.medium.com/arsitektur-microservice-untuk-data-publik-bagian-1-68a387d9fabe"><em>Bagian 1</em></a><em>). Lihat juga artikel lain tentang teknologi dan implementasinya untuk berbagai industri di </em><a href="https://medium.com/@yogisaputro"><em>Medium</em></a><em> dan </em><a href="https://dev.to/yogski"><em>dev.to</em></a><em> saya. [Yogi Saputro : Full Stack Developer | M.B.A | creating useful IT solutions]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e437cab7724" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arsitektur Microservice untuk Data Publik (Bagian 1)]]></title>
            <link>https://yogisaputro.medium.com/arsitektur-microservice-untuk-data-publik-bagian-1-68a387d9fabe?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a387d9fabe</guid>
            <category><![CDATA[process-improvement]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[public-service]]></category>
            <category><![CDATA[design-process]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Wed, 29 Sep 2021 01:55:20 GMT</pubDate>
            <atom:updated>2021-10-15T18:54:51.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Biar saya langsung bicara <em>to the point</em> : data publik di Indonesia itu payah karena 3 alasan.</p><ol><li>Dikeluarkan oleh instansi lewat <em>website </em>atau publikasinya sendiri. Per wilayah pula. Singkatnya, <em>scattered</em> alias <strong>tersebar</strong>.</li><li>Format penyajian data <strong>tidak seragam dan sebagian sulit diolah ulang</strong>. Yang paling top adalah instansi yang sajikan data berformat CSV/JSON. Selain itu, ekspor sebagai <em>spreadsheet </em>(Excel) juga cukup oke. Namun dari observasi pribadi, kebanyakan data tersedia dalam bentuk PDF dan tabel HTML. PDF juga ada jenisnya. PDF teks masih dapat diproses. Kalau ada PDF hasil <em>scan</em>, itulah mimpi buruk pengguna data.</li><li>Data <strong>tidak konsisten</strong> antar instansi maupun wilayah. Di wilayah A, ada tiga item ditampilkan dalam laporan. Di wilayah B, empat item. Di wilayah C, ada empat item juga tapi dua item berbeda dengan wilayah B. Saya langganan geleng-geleng kepala ketika ketemu kasus seperti ini.</li></ol><p>Contohnya, saya pernah coba kumpulkan data statistik BAZNAS per daerah. Ternyata setiap kabupaten/kota punya website BAZNAS sendiri dengan tingkat disiplin laporan bervariasi. Ada yang laporannya lengkap 5 tahun terakhir, ada yang <a href="https://kabsukabumi.baznas.go.id/category/laporan/statistik/">kosong (per 15 Sep 2021)</a>. Format laporannya pun beragam, ada yang PDF, ada pula yang <em>embedded </em>sebagai tabel HTML.</p><p>Saya coba gali jalan alternatif. BAZNAS menerbitkan statistik zakat per tahun (<a href="https://pid.baznas.go.id/wp-content/uploads/2020/02/Statistik-Zakat-Nasional-2018.pdf">ini contohnya</a>). Sayangnya BAZNAS menggunakan kategori <em>tier </em>mereka sendiri: pusat, provinsi (digabung), kota/kabupaten(digabung). Dari sudut pandang pengguna umum, statistik ini sekedar laporan berdasarkan titik setor. Tidak ada <em>value</em>, tidak ada <em>insight </em>tambahan. Memangnya kenapa kalau BAZNAS pusat sekian, BAZNAS provinsi sekian? Kenapa tidak per kabupaten/kota, atau setidaknya per provinsi? Mungkin bisa didapat temuan menarik, misalnya korelasi antara jumlah zakat dengan indeks pembangunan manusia.</p><p>Jalan terakhir adalah menghubungi instansi BAZNAS untuk meminta data. Lalu saya ukur besarnya usaha yang dibutuhkan, lamanya waktu tunggu, belum lagi jumlah instansi yang dikontak. Untuk hobi mencari data, bukan tuntutan kerja/penelitian, saya nilai opsi ini tidak <em>worth it</em>. Akhirnya saya menyerah.</p><h4>Sebuah Proposal Arsitektur Sistem</h4><p>Tapi kalau berani bilang data publik payah, mestinya kasih solusi sekalian dong? Demikian kata <em>haters</em>.</p><p>Tentu saja.</p><p>Saya ada solusi untuk membuat data publik menjadi lebih bermutu. Tapi sebelum melangkah lebih jauh ke arsitekturnya, saya definisikan dulu data publik dan karakteristiknya. Saya pakai definisi UU No 14 Tahun 2008:</p><blockquote>Informasi Publik adalah informasi yang dihasilkan, disimpan, dikelola, dikirim, dan/atau diterima oleh suatu badan publik yang berkaitan dengan penyelenggara dan penyelenggaraan negara dan/atau penyelenggara dan penyelenggaraan badan publik lainnya yang sesuai dengan Undang-Undang ini serta informasi lain yang berkaitan dengan kepentingan publik.</blockquote><p>Intinya, data yang dibuat oleh instansi sektor publik, berhak diketahui publik, dan tidak bahaya jika dipublikasikan. Supaya lebih paham lagi, kita contohkan. Apakah daftar pejabat DPR termasuk data publik? Ya, sebab berkaitan dengan penyelenggaraan negara. Kalau data NIK? Tidak. Meskipun adanya NIK untuk keperluan administrasi negara, data tersebut termasuk yang dikecualikan menurut UU No 14 Tahun 2008.</p><p>Kemudian saya jabarkan karakteristik data publik serta konsekuensinya terhadap desain arsitektur yang akan saya buat.</p><ol><li>Bisa diakses semua orang → tidak perlu <em>authorization </em>&amp; <em>authentication </em>untuk <em>read</em></li><li>Kebenaran dan keakuratan data adalah tanggung jawab instansi penerbit → perlu <em>authorization</em> &amp; <em>authentication </em>untuk <em>write</em></li><li>Data tidak sering mengalami perubahan → kita bisa optimalkan strategi untuk <em>storage</em>.</li><li>Data publik berasal dari banyak instansi sumber → perlu database untuk metadata data publik</li><li>Data yang dihasilkan instansi berformat beragam → perlu fungsi khusus untuk konversi ke format seragam</li><li>Data yang dihasilkan instansi bisa tidak seragam untuk satu jenis data → perlu ada validasi untuk setiap jenis data, paling bagus kalau ada definisi <em>field</em> data. Hal tersebut dapat diakomodasi oleh <em>database</em>.</li></ol><p>Oke, sekarang sudah dapat beberapa spek solusi berdasarkan karakteristik data publik. Apa sudah bisa merancang solusinya? Hoho, tentu saja belum. Kita perlu mengetahui <em>use case </em>umum. Untuk apa sebenarnya orang mencari data publik? Berdasarkan pengalaman pribadi, ada dua penggunaan data publik.</p><ol><li><em>Value lookup</em>, alias cek referensi nilai. Contohnya cek kode bank, kode pos, dan sebagainya. Kita cari datanya, ketemu, sudah beres. Kehidupan berlanjut, musim berganti.</li><li>Analisis lanjutan yang memerlukan data dasar. Misalnya, sebuah perusahaan bimbel mau membuka cabang di kota baru. Kota mana saja yang akan dipilih? Mereka memutuskan mencari berdasarkan PDB dan populasi penduduk usia sekolah (misal 7–16 tahun). Di sini data publik berperan sebagai bahan baku analisis ekspansi pasar, dengan pola pemakaian spesifik seperti memakai query SQL.</li></ol><p>Berdasarkan karakteristik data publik dan <em>use case </em>umum, saya jabarkan satu-satu keputusan arsitektur solusi saya. Sekalian saya membangun diagram arsitekturnya.</p><h4>Tahap 1 : Microservice tanpa DB</h4><p>Data yang diakses <em>user </em>jarang berubah dan terbuka. Kemudian dari sisi <em>use case</em>, tidak ada tuntutan <em>response time</em>. Ini membuat saya mempertimbangkan akses data. Saya bisa manfaatkan <em>database </em>maupun <em>file </em>untuk <em>storage</em>. Saya putuskan menggunakan <em>file</em> JSON karena lebih mudah dan murah. Menurut saya, pilihan ini menjadi kelebihan terbesar arsitektur:</p><blockquote>Layanan inti untuk data publik tidak butuh database</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*JfDt8iEopol4-uSXneq-cw.png" /><figcaption>Diagram 1: Arsitektur <em>microservice </em>untuk data publik, mode paling sederhana</figcaption></figure><p>Diagram 1 menunjukkan bagaimana kita bisa membuat <em>microservice </em>tanpa <em>database</em>.</p><ol><li>kita olah data mentah secara manual, atau kerennya <em>data wrangling</em>, sampai jadi format JSON.</li><li>Kita upload JSON ke repository. Nantinya repository ini berfungsi sebagai 3 hal : lokasi data, <em>source code</em>, dan dokumentasi API. <em>Repository </em>ini menggunakan CI/CD untuk memudahkan deploy ke server (lihat garis C).</li><li>Server dapat menggunakan static server yang ringan. Ingat, kita tidak pakai database, jadi <em>microservice </em>ini setara website statis.</li><li>User dapat mengakses <em>microservice </em>dan dapat melihat dokumentasi di <em>repository </em>(lihat D dan E).</li></ol><p>Di artikel berikutnya, akan saya contohkan implementasi arsitektur ini dengan Next.JS + Vercel. (<a href="https://yogisaputro.medium.com/arsitektur-microservice-untuk-data-publik-bagian-2-implementasi-dengan-next-js-7e437cab7724">Lihat artikel penuh di sini</a>)</p><h4><strong>Tahap 2 : <em>File Automation + </em>Metadata</strong></h4><p>Katakanlah kita sudah berhasil membuat <em>microservice </em>untuk data publik dengan cara seperti tahap 1. Untuk dua-tiga data publik beres lah. Kalau sudah menumpuk ratusan dokumen, tamat kita kalau pakai arsitektur sama. Kalau sudah begini, <em>upgrade </em>ke tahap 2. Hasilnya dapat dilihat di Diagram 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JAcO6pCmSLRkkx_HEM-JCw.png" /><figcaption>Diagram 2 : Arsitektur microservice data publik dengan tambahan automation dan metadata</figcaption></figure><p>Fokus peningkatan tahap ini adalah kapabilitas <em>automation </em>dan metadata. <em>Automation </em>artinya membuat proses <em>upload</em>, <em>wrangling</em>, konversi ke JSON, dan menyimpan ke <em>repository </em>jadi otomatis. Sementara metadata berarti <em>tracking </em>dokumen yang sudah diunggah dan diproses supaya mudah diakses.</p><ol><li>Praktiknya begini. Misalkan 100 dokumen diunggah untuk dibuat REST API nya. Akan ada <em>service/function</em> untuk mengunggah dan simpan <em>file </em>mentahan. Jika sistem ditaruh di <em>cloud </em>macam AWS, penggunaan <em>lambda function </em>akan lebih hemat biaya.</li><li>Setelah itu ada <em>service/function </em>untuk mengubahnya menjadi file JSON (lihat garis C). Dari situ, ada dua aktivitas yang dijalankan. Pertama, menyimpan file JSON ke <em>repository </em>seperti Github (garis F). Selanjutnya, menyimpan <em>metadata </em>file JSON ke <em>metadata service </em>(garis D). <em>Repository </em>menyimpan isi <em>file</em>, sementara metadata service menyimpan lokasi penyimpanan <em>file </em>dan menyediakan direktori untuk memudahkan pencarian API.</li><li><em>Microservice </em>data publik di-<em>deploy </em>dari <em>repository </em>(garis G).</li><li><em>User</em> mengecek daftar API yang tersedia lewat <em>API directory service </em>(lihat I1 dan I2). Setelah ketemu alamatnya, <em>user </em>bisa akses API yang tersedia (lihat garis H).</li></ol><h4>Tahap 3 : Tambahan <em>Auth</em></h4><p>Karena instansi penerbit bertanggung jawab atas data publik, kita perlu lindungi sisi <em>internal client</em>. Implementasinya sederhana saja, cukup tambahkan auth service lengkap bersama database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*0O3cEhXpK_MZei7kIkW2cQ.png" /><figcaption>Diagram 3 : Arsitektur microservice data publik dengan tambahan auth</figcaption></figure><h4>Tahap 4 : Automated File Distribution &amp; API Generator</h4><p>Kecuali bekerja di eselon kementrian atau punya pendanaan series A, anda belum butuh arsitektur ini. Tahap 4 ini mengandung kata-kata <em>scalable</em>, <em>complex</em>, <em>over-engineered</em>, dan <em>expensive</em>. Tapi tentunya menyenangkan untuk menganalisis sebarapa jauh proses bisnis jadi otomatis.</p><p>Kekurangan terbesar arsitektur ini hingga tahap 3 adalah adanya <em>edge API repository</em>. Itu menunjukkan beban kerja manual dari sisi <em>developer</em>. Kalau ada 100 dokumen yang akan dibuat API nya, developer perlu 100 kali membuat API. Meskipun hanya request GET dengan filter semua kolom, itu tetap beban yang memperlambat usaha <em>scaling-up</em>. Saatnya untuk membuatnya jadi otomatis. Hasilnya bisa dilihat di Diagram 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*G51GHc7unIL0ay9Uch-t6Q.png" /><figcaption>Diagram 4 : Arsitektur microservice versi lengkap, scalable, dan over-engineered. Lakukan ini kalau anda punya banyak duit.</figcaption></figure><p>Proses otomatis nantinya terdiri dari dua langkah.</p><ol><li>Distribusi file JSON ke CDN. Jika sebelumnya file JSON diberikan ke repository, kali ini file JSON diteruskan ke <em>service/function </em>lain (garis H) yang akan mengunggahnya ke CDN (lihat garis L). Setelah itu, data <em>file address </em>di CDN akan disimpan lewat <em>metadata service (garis J)</em>. Distribusi yang sukses akan memicu <em>trigger </em>untuk memanggil <em>service/function</em> kedua (lihat garis I).</li><li>Generator API. <em>Service/function </em>ini secara otomatis akan membaca file JSON, mendeteksi <em>field </em>JSON, lalu membuat API baru. Setelah itu, API baru segera di-<em>deploy </em>(lihat garis M). Address API akan disimpan di <em>metadata service</em> (lihat garis K).</li></ol><h4>Penutup: Siapkah Beralih?</h4><p>Sekarang, sudah ada rancangan untuk menyediakan data publik. Masalahnya tinggal kesiapan dan keinginan untuk beralih. Solusi ini tidak menjadikan kita secanggih <a href="https://e-estonia.com/">sektor publik Estonia </a>yang sudah 99% online, tapi saya percaya data yang transparan dan accessible akan membuka jalan kemajuan.</p><p><em>Artikel ini adalah bagian dari Serial Arsitektur Microservice untuk Data Publik. Lihat artikel bagian 2 di sini (</em><a href="https://yogisaputro.medium.com/arsitektur-microservice-untuk-data-publik-bagian-2-implementasi-dengan-next-js-7e437cab7724"><em>Bagian 2</em></a><em>). Lihat juga artikel lain tentang teknologi dan implementasinya untuk berbagai industri di </em><a href="https://medium.com/@yogisaputro"><em>Medium</em></a><em> dan </em><a href="https://dev.to/yogski"><em>dev.to</em></a><em> saya. [Yogi Saputro : Full Stack Developer | M.B.A | creating useful IT solutions]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a387d9fabe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Javascript Array Cheat Sheet]]></title>
            <link>https://yogisaputro.medium.com/practical-javascript-array-cheat-sheet-5eca962ead1d?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eca962ead1d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-arrays]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 05:39:50 GMT</pubDate>
            <atom:updated>2022-06-29T05:45:54.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hphxw7ZtY0SVHzXU" /><figcaption>Photo by <a href="https://unsplash.com/@hooverpaul55?utm_source=medium&amp;utm_medium=referral">Paul Teysen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Javascript is undoubtedly widespread by now. Web is full of them. It is getting more accessible as well. Plenty of resources are available for anyone willing to learn. Tutorials, courses, forums, books, boot camps, all tried to make us able to make a working application from scratch.</p><p>But in my experience as mentor at <a href="https://medium.com/u/5e57a9ef6d1e">Binar Academy</a>, those jungle of knowledge is overwhelming for some. So I figured out that there should be condensed version of learning material. Furthermore, it should be both conceptual and practical. Javascript array is fine example. We use them a lot. So in this article, I assembled a list of common tasks of Javascript array manipulation. Hopefully, this can be helpful for Javascript developers.</p><p>Please do mind that this article will not mention built-in Javascript array functions. You can find them <a href="https://www.w3schools.com/js/js_arrays.asp">here </a>or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">here</a>. I’m talking about common use cases like finding maximum value of an array, deleting duplicates, etc. Practical things useful in many projects.</p><p>As convention, I’m going to use regular function declaration with array(s) and some parameter. The output might be single value, an array, or arrays. Now, please enjoy my assortment of practical use cases using Javascript array.</p><h4>Maximum/minimum value of Javascript array</h4><p>Given an array of numbers, find the maximum or minimum value of an array.</p><pre>// get minimum value of an array<br>function minValueArray(arr) {<br>  return Math.min.apply(null, arr);<br>}</pre><pre>// get maximum value of an array<br>function minValueArray(arr) {<br>  return Math.max.apply(null, arr);<br>}</pre><h4>Access Last Element of Array</h4><p>Given an array, get its last element. Actually, I’m quite surprised there’s no built-in function like array.end() in PHP or array[-1] in Python. So it made its way into my list. There are two “safe ” (a.k.a non-mutating) approaches: count from its length or using .slice.</p><pre>// get last element of an array<br>function lastElement(arr) {<br>  return arr[arr.length - 1]<br>}</pre><pre>// OR</pre><pre>function lastElement(arr) {<br>  return arr.slice(-1)[0] <br>}</pre><p>Either choice is sufficient to get last element of any array. The first is considered faster, but the second can be attached nicely to other manipulation functions. For example, I have an URL “<em>https://random.url/with/some/id_123</em>”. If I need to get URL params (‘id_123’) without additional library, I can convert it to array with .split method, then pick the last element.</p><pre>function getParams(urlString) {<br>  return urlString.split(&#39;/&#39;).slice(-1)[0];<br>}</pre><h4>Sum of numbers in Javascript array</h4><p>Giv en an array of numbers, find the sum of its numeric elements. This includes two versions: naive version where we consider the input will always be array of numbers, and more realistic approach with validation and error handling (because users love to ruin our perfect array).</p><pre>// get sum of numbers in array<br>function sumNumbers(arr) {<br>  var result = 0;<br>  for (var i=0; i&lt;arr.length; i++) {<br>    // we assume each element is always a number<br>    result += arr[i];<br>  }<br>  return result;<br>}</pre><pre>// get sum of numbers in array - realistic approach<br>function sumNumbersRealistic(arr) {<br>  // only add if the element exist and translatable into number<br>  var numbers = arr.filter(Number);<br>  var result = 0;<br>  for (var i=0; i&lt;numbers.length; i++) {<br>    result += parseInt(numbers[i]);<br>  }<br>  return result;<br>}</pre><pre>//====================================================</pre><pre>var sample = [1,2,null,&#39;-1&#39;,&#39;0&#39;,3,]<br>console.log(sumNumbers(sample)); // 3-103<br>console.log(sumNumbersRealistic(sample)); // 5</pre><h4>Longest element in Javascript array of strings</h4><p>Given an array of strings, find the longest element (i.e most character count). There is possible case where there are more than one longest elements. We will separate algorithm for each case below.</p><pre>// 1. get the FIRST longest element in array of strings<br>function longestElement(arr) {<br>  return arr.sort((a, b) =&gt; { return b.length - a.length; })[0];<br>}</pre><pre>// 2. get ALL longest elements in array of strings<br>function longestElements(arr) {<br>  return arr<br>    .reduce((a,b) =&gt; a &gt; b.length ? a : b.length, 0)<br>    .filter(element =&gt; element.length == maxLength);<br>}</pre><p>In theory, the first approach has O(n log(n))time complexity from sort method. The second approach is better with O(n)time complexity.</p><h4>Select Random Element in Javascript Array</h4><p>Given an array, return a random element in that array.</p><pre>// get random index of an array<br>function getRandomIndex(array) {<br>  return Math.floor(Math.random()*array.length))<br>}</pre><pre>// get random element of an array<br>function getRandomElement(array) {<br>  return array[Math.floor(Math.random()*array.length))]<br>}</pre><h4>Finding elements that match search term in array of strings</h4><p>Given an array and search term, return new array containing elements that match the search term.</p><pre>// get the index of FIRST match<br>function findString(term, arr) {<br>  for (var i=0; i&lt;arr.length; i++)  {<br>    if (arr[i].match(term)) return i;<br>  }<br>  return -1;<br>}</pre><pre>// get the elements of ALL matches, return -1 if not found<br>function findAllString(term, arr) {<br>  let result =[];<br>  for (var i=0; i&lt;arr.length; i++)  {<br>    if (arr[i].match(term)) {<br>      result.push(arr[i]);<br>    };<br>  }<br>  if (result.length &gt; 0) {<br>    return result;<br>  } else {<br>    return -1;<br>  }<br>}</pre><h4>Javascript array parameter validation</h4><p>Given a function with parameter, checks if it’s an array. Return true (or continue) if it is an array, otherwise stop.</p><pre>function stepsWithArrayValidation(arr) {<br>  if (!Array.isArray(arr)) return -1;<br>  return true; // or continue your code<br>}</pre><h4>Remove duplicates or get distinct elements in Javascript array</h4><p>Given an array, return new array with duplicated elements removed, leaving it as array of distinct values. Personally, I like the elegance of this approach.</p><pre>// return array of distinct elements, no more duplicates<br>function removeDuplicates(arr) {<br>  return [...new Set(arr)]<br>}</pre><h4>Add elements without mutating the array (useful for React state)</h4><p>Given an array, return the same array with additional element(s). The key is using method that does not mutate original array. .push() method mutates array, so we will need other approaches. This method is desirable if you have array state in React, where immutability is primary concern.</p><pre>// add an element to array without mutating<br>function addWithoutMutate(arr, element) {<br>  return arr.concat(element)<br>}<br>// or <br>function addWithoutMutate(arr, element) {<br>  return [...arr,element]<br>}</pre><pre>// add an array of elements to array without mutating<br>function addWithoutMutate(arr, elements) {<br>  return [...arr, ...elements]<br>}</pre><h4>Remove null or undefined elements in Javascript array</h4><p>Given an array, remove empty elements. Now, we might need to be more specific about what “empty” means. It could be 0, “”, [], {}, null, or undefined. In this case, want to remove null or undefined elements. Then, it returns filtered array.</p><p>This can be useful when we need clean array to work with. In most cases, we don’t want to deal with null or undefined value throughout business logic. It will break things somewhere.</p><pre>// remove null or undefined array elements<br>function removeNullElements(arr) {<br>  return arr.filter((e) =&gt; {return e != null});<br>}</pre><pre>//======================================================</pre><pre>var sample = [1,,,null,&quot;&quot;,2,0,,{},-1,undefined,-2,[],false,];<br>console.log(removeNullElements(sample));<br>// [ 1, &#39;&#39;, 2, 0, {}, -1, -2, [], false ]</pre><h4>Declare empty array with specific length</h4><p>Given a desired length, return an empty array with that length. For example, if we call makeArray(5), we wil have [undefined, undefined, undefined, undefined, undefined]. It can be useful when we need to specify container of values with fixed length. This way, we can assign value to specific index immediately.</p><pre>// make empty array with specific length<br>function makeArray(length) {<br>  return Array.apply(null, Array(length));<br>}</pre><pre>// OR with ES6<br>function makeArray(length) {<br>  return Array.from({ length: length });<br>}</pre><pre>//======================================================</pre><pre>var sample = makeArray(3); // [undefined, undefined, undefined]<br>console.log(sample.length) // 3<br>sample[1] = &#39;yes&#39; // [undefined, &#39;yes&#39;, undefined]</pre><h4>Add Array Element on Specified Index</h4><p>Javascript has push() to add array element to the end.unshift() is available to add new element to the beginning of array. What if you need to add new element at specific index of an array? Well, splice() got your back!</p><pre>// Add array element on specific index<br>function addArrayElement(arr, idx, element) {<br>  return arr.splice(idx, 0, element);<br>}</pre><pre>// =========example===========<br>let example = [1,2,3,4,5]<br>addArrayElement(example,3,3)<br>console.log(example)<br>// [1,2,3,3,4,5]</pre><h4>Remove Array Element on Specified Index</h4><p>The next useful pair is removing array alement on specified index. Just like before, splice() can save the day.</p><pre>// Remove array element on specific index<br>function removeArrayElement(arr, idx) {<br>  return arr.splice(idx, 1);<br>}</pre><pre>// ========example========<br>let example = [1,2,3,4,5];<br>removeArrayElement(example, 2);<br>console.log(example);<br>// [1,2,4,5]</pre><p>There’s more to come. I’ll keep up with more use cases later. If you have feedback or ideas, please don’t hesitate to tell me.</p><p><em>I am </em><a href="https://yogski.github.io/"><em>Yogi Saputro</em></a><em>, a full stack developer at </em><a href="https://pinjammodal.id/"><em>Pinjammodal.id</em></a><em> and full stack development mentor at </em><a href="https://binaracademy.com/"><em>Binar Academy</em></a><em>. I’m also passionate in building data architecture and provide value to businesses. Check out </em><a href="https://medium.com/@yogski"><em>my other stories</em></a><em> to find out more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eca962ead1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Use Cases of Javascript Array]]></title>
            <link>https://yogisaputro.medium.com/practical-use-cases-of-javascript-array-f1affcc61419?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1affcc61419</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-arrays]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 00:14:00 GMT</pubDate>
            <atom:updated>2020-08-09T01:13:44.141Z</atom:updated>
            <content:encoded><![CDATA[<h3>Practical Javascript Array Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JXDVhaOUQmj6Bre2" /><figcaption>Array of Soldiers (Photo by <a href="https://unsplash.com/@mcoswalt?utm_source=medium&amp;utm_medium=referral">Maria Oswalt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>)</figcaption></figure><p>Javascript is undoubtedly widespread by now. Web is full of them. It is getting more accessible as well. Plenty of resources are available for anyone willing to learn. Tutorials, courses, forums, books, boot camps, all tried to make us able to make a working application from scratch.</p><p>But in my experience as mentor at <a href="https://medium.com/u/5e57a9ef6d1e">Binar Academy</a>, those jungle of knowledge is overwhelming for some. So I figured out that there should be condensed version of learning material. Furthermore, it should be both conceptual and practical. Javascript array is fine example. We use them a lot. So in this article, I assembled a list of common tasks of Javascript array manipulation. Hopefully, this can be helpful for Javascript developers.</p><p>Please do mind that this article will not mention built-in Javascript array functions. You can find that <a href="https://www.w3schools.com/js/js_arrays.asp">here </a>or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">here</a>. I’m talking about finding maximum value of an array, deleting duplicates, etc. Practical things useful in many projects.</p><p>As convention, I’m going to use regular function declaration with array(s) and some parameter. The output might be single value, an array, or arrays. Now, please enjoy my assortment of practical use cases using Javascript array.</p><h4>Maximum/minimum value of Javascript array</h4><p>Given an array of numbers, find the maximum or minimum value of an array.</p><pre>// get minimum value of an array<br>function minValueArray(arr) {<br>  return Math.min.apply(null, arr);<br>}<br><br>// get maximum value of an array<br>function minValueArray(arr) {<br>  return Math.max.apply(null, arr);<br>}</pre><h4>Longest element in Javascript array of strings</h4><p>Given an array of strings, find the longest element (i.e most character count). There is possible case where there are more than one longest elements. We will separate algorithm for each case below.</p><pre>// get the FIRST longest element in array of strings<br>function longestElement(arr) {<br>  return arr.sort((a, b) =&gt; { return b.length - a.length; })[0];<br>}<br><br>// get ALL longest elements in array of strings<br>function longestElements(arr) {<br>  let maxLength = arr.reduce((a,b) =&gt; a &gt; b.length ? a : b.length, 0);<br>  return arr.filter(element =&gt; element.length == maxLength);<br>}</pre><h4>Select Random Element in Javascript Array</h4><p>Given an array, return a random element in that array.</p><pre>// get random index of an array<br>function getRandomIndex(array) {<br>  return Math.floor(Math.random()*array.length))<br>}<br><br>// get random element of an array<br>function getRandomElement(array) {<br>  return array[Math.floor(Math.random()*array.length))]<br>}</pre><h4>Finding elements that match search term in array of strings</h4><p>Given an array and search term, return new array containing elements that match the search term.</p><pre>// get the index of FIRST match<br>function findString(term, arr) {<br>  for (var i=0; i&lt;arr.length; i++)  {<br>    if (arr[i].match(term)) return i;<br>  }<br>  return -1;<br>}<br><br>// get the elements of ALL matches, return -1 if not found<br>function findAllString(term, arr) {<br>  let result =[];<br>  for (var i=0; i&lt;arr.length; i++)  {<br>    if (arr[i].match(term)) {<br>      result.push(arr[i]);<br>    };<br>  }<br>  if (result.length &gt; 0) {<br>    return result;<br>  } else {<br>    return -1;<br>  }<br>}</pre><h4>Javascript array parameter validation</h4><p>Given a function with parameter, checks if it’s an array. Return true (or continue) if it is an array, otherwise stop.</p><pre>function stepsWithArrayValidation(arr) {<br>  if (!Array.isArray(arr)) return -1;<br>  return true; // or continue your code<br>}</pre><h4>Remove duplicates or get distinct elements in Javascript array</h4><p>Given an array, return new array with duplicated elements removed, leaving it as array of distinct values. Personally, I like the elegance of this approach.</p><pre>// return array of distinct elements, no more duplicates<br>function removeDuplicates(arr) {<br>  return [...new Set(arr)]<br>}</pre><p>There’s more to come. I’ll keep up with more use cases later. If you have feedback or ideas, please don’t hesitate to tell me.</p><p><em>I am </em><a href="https://yogski.github.io/"><em>Yogi Saputro</em></a><em>, a full stack developer and mentor at Binar Academy, a tech company focused on developing high quality engineering talents. I’m also passionate in data science and business. Check out my other stories to find out more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1affcc61419" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons Learned  from Mentoring Online Bootcamp, Part 1 : Challenges & Missions]]></title>
            <link>https://yogisaputro.medium.com/lessons-learned-from-mentoring-online-bootcamp-part-1-challenges-missions-9942b58eee01?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/9942b58eee01</guid>
            <category><![CDATA[online-courses]]></category>
            <category><![CDATA[education-technology]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Fri, 22 May 2020 00:21:03 GMT</pubDate>
            <atom:updated>2020-05-22T00:21:03.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lessons Learned from Mentoring Online Bootcamp, Part 1 : Challenges &amp; Missions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yE0OO5N99ObrykMHBLjPQQ.png" /></figure><p>For almost a year, I’ve been contracted as full stack development mentor in <a href="https://www.instagram.com/academybinar">Binar Academy</a>. In short, my job is mentoring students / fresh graduates in a bootcamp. It is a pleasant experience, overall. I met eager and dedicated students, guided them through full stack development curriculum, laughed and swept tears, and most importantly, learned from them. As a mentor, I helped students to gain knowledge, experience, and confidence. It was done in various methods: teaching in class, sharing outside class, providing written materials, and setting up project. In my opinion, Binar Academy crafted more than just programming bootcamp. It created environment for anyone to grow as better programmer, as well as better person.</p><p>Most of the time, the bootcamp was done in face-to-face setting. Learning and feedback process happened in classroom, or at least in same space. However, Covid-19 pandemic forced us to shift. Classroom is no longer. Face-to-face communication becomes limited. Education sector is crippled everywhere. Yet, students must continue to learn. It is their rights. Schools and institutions moved to online meeting or classroom solution. So did Binar Academy. The usual bootcamp became full online bootcamp.</p><p>In this post, I’m going to share my experience navigating my bootcamp classes. I faced several challenges in mentoring due to shifts in learning environment. Then, with help of Binar Academy and fellow mentors, I crafted methods to increase engagement and effectiveness of online teaching. Some works, some need improvements. Finally, I extracted insights from those experience, which I hope can be useful for my dear readers.</p><h3>Challenges</h3><p>I can sum up challenges in online bootcamp as “keeping students and instructor engaged and motivated throughout bootcamp sessions.” Well, I think it is quite universal. However, there are some constraints I have to address. Identifying them is crucial process to determine which teaching method will be effective.</p><ol><li><strong>Students are used to one-way teaching</strong>. “When you attend school (or bootcamp in my case), you come to classroom, listen to the teacher, ask questions, then go home.” This has been the norm for decades. Teacher is perceived to hold absolute knowledge and truth. Straying off of the intended learning path (due to boredom or pure curiosity), and student will be labelled as rebellious or disobedient. So, why take risks? That is what students think. Ironically, this norm severely blocks learning process rather than encourage it. Students earn knowledge, but they won’t actually learn and develop themselves.</li><li><strong>Infrastructures are somewhat limited from both sides</strong>. Since schools and offices are closed due to pandemic, students and teachers must provide their own infrastructure e.g stable internet connection, dedicated room without distractions, and decent PC/laptop. Some people can’t afford them. Some are not easily available in Indonesia, like stable internet connection. Moreover, online meeting apps consume data horrendously. A 3-hour session in Zoom, with occasional recording, screen sharing, and active video/audio consumes 2.0–2.5 GB of data. Mobile data plan is not an option anymore. I switched to FO-based ISP immediately.</li><li><strong>Law of Class Interactions</strong>. In my experience as student from elementary school to master degree in Indonesia, I’ve found relation between class size and student engagement. This pattern is also consistent when I was the one lecturing. In general, student engagement level is inversely proportional to class size. The bigger the class, the less likely students will pay attention.</li><li><strong>Inherent limits of online communications</strong>. Basic communication theory states there exist two primary forms of communication: verbal and non-verbal. Verbal communication relates to written/oral message. Non-verbal communication relates to the way message is presented. Thanks to technological advancement, we can deliver audio and video in real time, enabling us to perform direct communication. Non-verbal communication can be relayed through intonation, tempo, or facial expression. However, there’s more to non-verbal communication. Ambience, aura, presence, or even smell contribute to overall class experience. However, they cannot be transmitted easily using current technology. That’s why it’s called inherent limits.</li><li><strong>Administrative requirements</strong>. Education entities need to keep track of students. What’s the attendance rate? How many students actually pay attention? Is there anyone showing significant progress in test grades? Who are struggling to keep up? To track all of it, some mechanisms are defined: attendance, assignment submission, grading, etc. In offline class setting, tracking is simple. Teacher/instructor can actually see who skip classes, who’s struggling, and who’s just plain lazy. Assignment submission and grading are also straightforward. In online settings, things get complicated. Tracking attendance can be cumbersome when using virtual meeting apps (Zoom, Meet, Skype) or messenger group (WhatsApp, Telegram,etc). Grading can be long process, even with platform like Google Classroom. Personally, I find dealing with these kinds of tasks exhausting.</li></ol><h3>Missions</h3><p>To craft wholesome online learning experience, the academic team from Binar Academy created a set of tools and rules. They combined various platforms to enable simplified online bootcamp flow. I also incorporated my own style and methods in class. The details will be omitted, but here are important features needed:</p><ol><li>Class structuring</li><li>Attendance tracking</li><li>Online class rules</li><li>Online class engagement</li><li>Material delivery</li><li>Supplementary platforms and materials</li><li>Keeping morale</li><li>Off-class engagement</li><li>Assignment tracking</li></ol><p>First thing first, we need to make the class small enough. In Binar Academy, each mentor ideally teaches up to ten students. In my case, I occasionally teach 12 students in a session. Obeying the law of class interaction, this structuring allows me to handle students better. It also makes students easier to ask, reducing barrier of one-way teaching norm.</p><p>Moreover, the class could be designed as fixed class for bootcamp setting. In Binar Academy, each student picks up his/her own schedule. There are slots available from morning class until evening class. In practice, once a student picks up a schedule, about 90% chance he/she will stick around it. Consequently, the students in my classes are 90% same every day. This results in better engagement and progress in bootcamp setting.</p><p>Next, handling the attendance administration. Let me describe simple case of an online class. As a mentor, I can create a meeting session via Zoom or Google Meet. Then, I send the invitation email to all students in that particular session. Or, I can even send the link to a messenger group so students can click on it directly. Then, before the class begins, I jolt down names of participant in my screen. Well, that’s the boring way, right?</p><p>One good thing about online platform is <strong>unlimited potential for automation. </strong>What if I can automate attendance process? Turns out that I actually could. The simple way is to put login page before the invitation. That way, students must login (via email or social media) before getting the actual meeting invitation link. We can track the login records and treat them as attendance record. Simple. How can it be done? Well, we are web development mentors. It wasn’t that hard :).</p><p>Still, the process can be improved. Instead of Zoom/Meet session manually created by mentor, we can create an automatic session using API, then put it behind login page, and renew the session every day. That will be very convenient.</p><p>There’s still more to tell. I will share my way to keep class entertained while delivering web development courses. I also will show my platform stack to demonstrate coding, write class notes, extra material, and assignment handling. Stay tuned for Part 2!</p><blockquote>This article is the first part of Lessons Learned from Mentoring Online Bootcamp. You can find the other part when the series is done.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9942b58eee01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Story of Ready-to-drink Tea in Indonesia]]></title>
            <link>https://yogisaputro.medium.com/data-visualization-tea-2beff8ec9903?source=rss-fbe1c110f952------2</link>
            <guid isPermaLink="false">https://medium.com/p/2beff8ec9903</guid>
            <category><![CDATA[industry]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[indonesia]]></category>
            <dc:creator><![CDATA[Yogi Saputro]]></dc:creator>
            <pubDate>Sat, 09 Nov 2019 10:41:24 GMT</pubDate>
            <atom:updated>2019-11-09T11:00:18.444Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Data Visualization from Registered Ready-to-drink Dataset in Indonesia</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rBXE4HwtX7b2Ja5R" /><figcaption>Photo by <a href="https://unsplash.com/@cchabot?utm_source=medium&amp;utm_medium=referral">Crystal de Passillé-Chabot</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are plenty of tea drink products in Indonesia. They are as common as bottled water or coffee these days. Tea drinks can be found on small stores, supermarkets, malls, restaurants, street vendors, and practically everywhere.</p><p>Despite its popularity, data analysis about this product is quite rare. Probably due to lack of ready-to-use data. I’ve found reliable source from Indonesian Food And Drug Administration (Bahasa: BPOM-Badan Pengawas Obat dan Makanan).</p><p>Link: <a href="http://cekbpom.pom.go.id/index.php/home/produk/r2isesetrjp2lvbjcb4617o7i0/13/row/5100/page/0/order/4/DESC/search/1/minuman%20teh">http://cekbpom.pom.go.id/index.php/home/produk/r2isesetrjp2lvbjcb4617o7i0/13/row/5100/page/0/order/4/DESC/search/1/minuman%20teh</a></p><p>The data is extracted from html table, converted to CSV, and then cleansed to make it usable for analysis.</p><p>You can find complete code and dataset on <a href="https://github.com/yogski/bpom-visualization">my Github repository.</a></p><pre>#import libraries<br>import pandas as pd<br>import seaborn as sns<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import itertools<br>import warnings<br>warnings.filterwarnings(“ignore”)<br>import io<br>import base64<br>from matplotlib import rc,animation<br>from mpl_toolkits.mplot3d import Axes3D<br>import os<br>import re</pre><p>This dataset is in Bahasa Indonesia. For short translation, these are what each column represents:</p><ul><li><strong>nomor_registrasi </strong>: ID of registered product in BPOM database. In this dataset, this ID uniqueness has been validated.</li><li><strong>nama_product</strong> : product name, basically explaining what product this is. For this dataset, this provides detailed information about the tea drink.</li><li><strong>merk</strong> : brand of the product.</li><li><strong>jenis_kemasan</strong> : type of package.</li><li><strong>ukuran_kemasan</strong> : size(s) of package for every registered product. Please do note that one product may have more than one package size. They are encapsulated in round brackets (a.k.a ‘()’) and separated by semicolon (a.k.a ‘;’).</li><li><strong>produsen</strong> : name of manufacturing company</li><li><strong>kota_produsen</strong> : city where manufacturing company HQ (and probably its plant) is located</li><li><strong>provinsi_produsen</strong> : province where manufacturing company HQ (and probably its plant) is located</li></ul><pre>dataset = pd.read_csv(“dataset_bpom_tea.csv”)<br>dataset.head(10)</pre><h4><strong>Distribution of Tea Drink Packages</strong></h4><pre>dataset_kemasan = dataset[“jenis_kemasan”].value_counts().reset_index()<br>dataset_kemasan = dataset_kemasan[dataset_kemasan[“jenis_kemasan”]&gt;=2]</pre><pre>plt.figure(figsize=(10,8))<br>ax = sns.barplot(y=dataset_kemasan[“index”][:15],x = dataset_kemasan[“jenis_kemasan”][:15],palette=”husl”, linewidth=1,edgecolor=”k”*15)<br>sns.set_style(“white”)<br>sns.despine()</pre><pre>plt.xlabel(“Number of product”)<br>plt.ylabel(“Package Type”)<br>plt.grid(True)<br>plt.title(“Distribution of Tea Drink Packages”,color=’b’)<br>for i,j in enumerate(dataset_kemasan[“jenis_kemasan”][:15].astype(str)):<br>  ax.text(.7,i,j,fontsize = 9,color=”black”)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*ASh79an6i_vQz3ovqX2JCA.png" /></figure><p>Most of tea drinks are packaged in plastic bottle (“Botol Plastik”) or plastic cup (“Gelas Plastik”). Some other packages available are aluminum can, laminated carton, glass bottle, tetrapak, Aluminum foil pouch, and PET plastic bottle. Some products are packaged in plastic (“Plastik”), which is unclear whether it is bottle or cup. It is probably caused by non-standard data entry process.</p><p>From this graph, one can conclude that tea drinks largely contributes to plastic production. According to <a href="https://www.wartaekonomi.co.id/read193618/berebut-manisnya-industri-minuman-teh-dalam-kemasan.html">this source </a>, the industry produces roughly 2 billion liters of tea drink annually. Assuming average tea serving size is 350ml, the industry sends <strong>5.7 billion cups/bottles</strong> to the environment annually.</p><h4><strong>Distribution of Tea Servings</strong></h4><p>Tea serving data can be obtained from “ukuran_kemasan” column. Please note that the column contains many values. So, we will need an array to capture all of those values, and then put them into DataFrame.</p><pre>#get all serving sizes using regex search over iterated rows<br>a=[]<br>for index,item in dataset[“ukuran_kemasan”].iteritems():<br>  for s in re.findall(r’[0–9]+’, item):<br>    a.append(int(s))</pre><pre>#create new Pandas series and group them by 4 serving size groups<br>index = [‘Small’, ‘Medium’, ‘Large’]<br>dataset_servings = pd.DataFrame({‘value’: a})<br>bins = pd.IntervalIndex.from_tuples([(0, 200), (200,400), (400, 600), (600, 2000)])<br>dataset_servings = pd.cut(dataset_servings[‘value’], bins).value_counts()</pre><pre>ax = dataset_servings.plot.bar(color=”maroon”, alpha=0.7)<br>sns.set_style(“white”)<br>sns.despine()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*oihhXv2p8mrcyKA1tqeE_Q.png" /></figure><p>Manufacturers choose to make their serving size not too big. Majority of tea drinks are served in either small bottles (200ml — 400ml) or in cups (up to 200ml). Regular bottle (400ml — 600ml) products exist, although it is not really popular among manufacturers. Some large quantities serving products also exist in market, but it is significantly less than other products.</p><p>This finding can be explained from both manufacturer and user perspective. From user perspective, it indicates that Indonesian people preferred compact-sized tea drinks. Probably it is due to easier mobility, and the serving size is just enough to satisfy the thirst. From manufacturer perspective, it is always profitable to sell small servings because it costs less, but sells for more margin. For example, if 500ml tea sells for Rp5.000,00 then 250ml tea always sells for more than Rp2.500,00. Small bottle servings might be an equilibrium zone for tea drinks.</p><h4><strong>Distribution of Flavours</strong></h4><p>Tea drink has many combination of flavours. It could be either jasmine tea, black tea, white tea, oolong tea, etc. It can be added with honey or milk as well. Some even have fruity flavours like apple, orange, or blackcurrant. Some tea has flavour combination like honey jasmine tea or fruit black tea. To deal with that requirement technically, new columns are created. These columns will display binary characteristic of tea flavours.</p><pre>dataset_flavour = dataset</pre><pre>dataset_flavour[“is_jasmine”] = [1 if (‘Melati’ in x or ‘Jasmine’ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_black”] = [1 if (‘Hitam’ in x or ‘Black ‘ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_green”] = [1 if (‘Hijau’ in x or ‘Green ‘ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_white”] = [1 if (‘Putih’ in x or ‘White ‘ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_honey”] = [1 if (‘Madu’ in x or ‘Honey ‘ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_milk”] = [1 if (‘Susu’ in x or ‘Milk ‘ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_flavoured”] = [1 if (‘Rasa’ in x) else 0 for x in dataset_flavour[‘nama_produk’]]<br>dataset_flavour[“is_oolong”] = [1 if (‘Oolong’ in x) else 0 for x in dataset_flavour[‘nama_produk’]]</pre><p>Now that necessary columns are ready, we can proceed to visualization step. We will use pie chart to show percentage of tea flavour.</p><pre># Jasmine pie chart<br>labels = [‘Jasmine Tea’, ‘Non-Jasmine Tea’]<br>sizes = [dataset_flavour[dataset_flavour[“is_jasmine”]==1].count()[“is_jasmine”],dataset_flavour[dataset_flavour[“is_jasmine”]==0].count()[“is_jasmine”]]</pre><pre>fig, ax = plt.subplots()<br>ax.pie(sizes, labels=labels, autopct=’%1.1f%%’, colors =[‘yellow’, ‘azure’])<br>ax.axis(‘equal’) # Equal aspect ratio ensures the pie chart is circular<br>ax.set_title(‘Jasmine Tea Product’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*Ws-OkX_fsWXIXb3KqvqM3A.png" /></figure><p>Jasmine tea is popular tea type in Indonesia. The ingredients are primarily tea leaves and jasmine flowers. It is characterized by its pleasant odor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*p2Gd_CN9zx4PTkGtYfjrNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*9HvGSJb9QoxR24bv5O_8mA.png" /></figure><p>Green tea is also quite popular. While most of tea drinks in this case is sweet, green tea gives acceptable bitter taste for the population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*BITAj5nukcuASNGPXpJKBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*xh287Z1_gf1ECC6VYoy5IA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*XoxLYsGcvm8VXH3JtWaxBg.png" /></figure><p>This graph shows interesting insight. <strong>More than half</strong> of tea drinks in Indonesia are flavoured. Different sensation might be expected from tea drink, whether it is fruity , honey, or milk flavour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*VGQwcb_hqSiBNUpkwu_x-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*J7zatZH807qUMCXGBbhrlw.png" /></figure><h4><strong>Import vs Local Brands</strong></h4><p>The difference from local and import brands can be identified by its registration number. For this case, only two permits matter.</p><p>First, <strong>MD registered product</strong> indicates that the local producer has its own brand.</p><p>Then, <strong>ML registered product</strong> indicates that the producer import goods and then sell it in Indonesia. In short, a product with this label means this is importing brand.</p><p>“nomor_registrasi” column contains information whether a product is registered as domestic product (MD) or imported product (ML). Upon checking the value, those two are only options exist in dataset. So, we can create binary column “is_local” by matching substring in each row of “nomor_registrasi”. If it matches with “MD”, then “is_local” value equals 1. Otherwise, the value is 0.</p><pre>dataset_brand = dataset<br>dataset_brand[“is_local”] = [1 if (‘MD’ in x ) else 0 for x in dataset_brand[‘nomor_registrasi’]]</pre><p>Then, we can make new pie chart from “is_local” column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*9k1A1cXzI7AhidBivsATVw.png" /></figure><p>Almost ten percent of registered tea drinks in Indonesia are imported. It <em>doesn’t</em> mean imported tea drinks own 10% market share in Indonesia. It means that while foreign brand can exist in Indonesia, local brands still hold their presence to customers.</p><h4><strong>Manufacturer Location</strong></h4><p>Manufacturer locations might reveal some interesting pattern. In essence, it is better to produce goods near customers. additionally, manufacturers choose strategic place where infrastructure is mature and distribution cost is low. My hypothesis is most of manufacturers are located around Jakarta area, and then transported.</p><p>To test it, we need to code some more.</p><pre># Select manufacturer and its location<br>dataset_loc = dataset[[“kota_produsen”,”produsen”]].drop_duplicates().reset_index()<br>loc_count = dataset_loc[“kota_produsen”].value_counts().reset_index()<br>print(“Tea drink manufacturers are distributed in %d cities.” % dataset_loc[“kota_produsen”].unique().size)</pre><pre># Create graph<br>plt.figure(figsize=(10,8))<br>ax = sns.barplot(y=loc_count[“index”][:15],x = loc_count[“kota_produsen”][:15],palette=”husl”, linewidth=1,edgecolor=”k”*15)</pre><pre>sns.set_style(“white”)<br>sns.despine()<br>plt.xlabel(“Number of companies”)<br>plt.ylabel(“City”)<br>plt.grid(True)<br>plt.title(“Distribution of Producer Location (City)”,color=’b’,fontsize = 18)</pre><pre>for i,j in enumerate(loc_count[“kota_produsen”][:15].astype(str)):<br>  ax.text(.7,i,j,fontsize = 9,color=”black”)</pre><pre>plt.show()</pre><p>Tea drink manufacturers are distributed in 49 cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*fIqmxmlXPAPA8hxz6jllIg.png" /></figure><p>Tea drink manufacturers are distributed in 15 provinces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*RUNgOHUmVOUuJvnq1M9edA.png" /></figure><p>According to graphs above, tea drink manufacturers spread in <strong>49 cities</strong> and <strong>15 provinces</strong>. Majority of them are located in Java Island. There are some reasons behind this fact:</p><ul><li>more than 70% of Indonesian population are located in Java</li><li>Infrastructures in Java are more developed, thus making it cheaper to distribute the products</li></ul><h4><strong>List of Companies</strong></h4><pre>dataset_corp = dataset[“produsen”].unique()<br>print(“Number of companies:”,dataset_corp.size)<br>dataset_corp</pre><p>From piece of code above, we found 134 companies are registered as tea drink manufacturer or importer in Indonesia.</p><h4><strong>Company Product Lines</strong></h4><pre>dataset_cline = dataset[[“produsen”,”merk”]].drop_duplicates()<br>cline_count = dataset_cline[“produsen”].value_counts().reset_index()</pre><pre>#create graph<br>plt.figure(figsize=(10,8))<br>ax = sns.barplot(y=cline_count[“index”][:15],x = cline_count[“produsen”][:15],palette=”husl”, linewidth=1,edgecolor=”k”*15)<br>plt.xlabel(“Number of product line”)<br>plt.ylabel(“Company”)<br>plt.grid(True)<br>plt.title(“Companies with Most Product Lines”,color=’maroon’,fontsize = 18)</pre><pre>for i,j in enumerate(cline_count[“produsen”][:15].astype(str)):<br>  ax.text(0.55,i,j,fontsize = 10,color=”black”)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*UzkbCQ-tyXvhGoaG1ySz0A.png" /></figure><p>PT Sinar Sosro has the most product lines compared to other tea drink manufacturers. It is not surprising since its core competence is in tea industry, and Sosro has been in industry for almost 50 years.</p><p>We know that Sosro is an outlier. But given PT Sehat Sukses Sejahtera with 3 product lines makes it into the graph, one might wonder: how many products does each manufacturer have? We can find out using code below.</p><pre>cline_dist = cline_count[“produsen”]<br>plt.figure(figsize=(13,7))</pre><pre>ax = sns.distplot(cline_dist, kde=False, color=”maroon”)<br>sns.set_style(“white”)<br>sns.despine()</pre><pre># Add title and axis names<br>plt.title(‘Distribution of Companies Based on Product Lines’)<br>plt.xlabel(‘Number of product lines’)<br>plt.ylabel(‘Number of companies’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*SAIRbRYjN_W7Cvb2JH4Dig.png" /></figure><p>Many tea drink manufacturers hold only one brand. This might indicate that most of tea drink manufacturers have yet to penetrate the market. Maybe they are relatively new to this market. On the other hand, old players have resource and experience to expand their product line in order to gain greater market share.</p><h4><strong>Companies Producing Less Plastics</strong></h4><p>Once again, we’ll talk about plastics. Personally, I feel like plastics will be dangerous problem for Indonesia in next decades. While other countries have taken action to limit plastic usage, Indonesian keeps using and wasting more plastics. Here, I’ll emphasize companies that use less plastic as appreciation for not adding more waste to mother earth.</p><p>Companies are producing less plastics when the have no product line with plastic packages. Plastic cups, plastic bottles, and PET packages are considered plastic packages.</p><p>Basically, we want to make a left join operation. Here’s the approach.</p><p>1. Divide “jenis_kemasan” values to two arrays: non-plastics and plastics.</p><p>2. Create dataframe with companies producing tea drink in plastic packages.</p><p>3. Create dataframe with companies producing tea drink in non-plastic packages.</p><p>4. Remove dataframe step 2 from dataframe step 3.</p><pre>non_plastics = [“Kaleng”, “Karton Laminat”, “Botol Kaca”, “Tetrapak”, “Pouch Aluminium Foil”]<br>plastics = [“Gelas Plastik”, “Botol Plastik”, “Plastik”, “Gelas Plastik PET”, “Botol Plastik PET”]<br>dataset_plastics = dataset[dataset[‘jenis_kemasan’].isin(plastics)]<br>dataset_non_plastics = dataset[dataset[‘jenis_kemasan’].isin(non_plastics)]<br>corp_plastics = dataset_plastics[“produsen”].drop_duplicates().values<br>corp_clean = dataset_non_plastics[~dataset_non_plastics.isin(corp_plastics)]<br>corp_clean = corp_clean[“produsen”].drop_duplicates().reset_index()</pre><p>Then we can make pie chart with relevant data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*rkpx3M07s9rjC896JNJJkQ.png" /></figure><p>We found 28 companies that doesn’t use any plastic package in their product lines. It equals to 17.3% of all tea drink manufacturers. But it <em>doesn’t </em>mean that 17.3% of tea drinks on the market are not made of plastics. It requires production data (which is more difficult to obtain). Still, I appreciate these companies for choosing not to make plastic-packaged product.</p><p>From this finding, we know that there is no sign of plastic pollution awareness among the companies. Plastic packages are used because they are cheap, durable, and easy to manufacture. Negative environmental effects are not considered. There is no enforcement or regulation in Indonesia, yet.</p><p>Maybe additional regulation could help. Government can give incentives to company that uses no plastic package in their product line. Another idea, companies producing certain amount of plastics can be subject to penalty.</p><h4><strong>Closing</strong></h4><p>Due to limited time, I can only tell little bit of stories about ready-to-drink tea in Indonesia. Still, we have some interesting key takeaways:</p><ol><li>Tea drink industry creates crazy vast amount of plastics: <strong>5.7 billion cups or bottles </strong>annually.</li><li>There are 134 companies playing in Indonesian ready-to-drink tea market and almost 90% are locals.</li><li>Most popular tea serving size is between 200ml to 400ml.</li><li>Many people like their tea flavoured, whether it is honey, fruit, milk, or anything.</li><li>Most manufacturers are located in Java, especially Jakarta area.</li><li>Most manufacturers have only one type of product to sell. Product diversification rate is quite low. Sosro is peerless with 16 products in its portfolio.</li><li>82.7% of manufacturers still use plastic packaging.</li></ol><p>If you have questions, comments, or critics, please let me know. I think I still have some stories in backlog just from this dataset.</p><ul><li>packages in different servings</li><li>servings according to manufacturers</li><li>flavours in different regions</li><li>Distribution of fruity flavours</li></ul><p>You can find the Jupyter Notebook file and dataset on <a href="https://github.com/yogski/bpom-visualization">my Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2beff8ec9903" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>