<?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[Codebrace - Medium]]></title>
        <description><![CDATA[Coding blog to help people get going with Competetive programming, Big Data and other technologies, visit http://medium.com/codebrace - Medium]]></description>
        <link>https://medium.com/codebrace?source=rss----1d3a3d56651---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Codebrace - Medium</title>
            <link>https://medium.com/codebrace?source=rss----1d3a3d56651---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:08:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/codebrace" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unicode vs UTF-8 vs UTF-16: A Simple Guide]]></title>
            <link>https://medium.com/codebrace/unicode-vs-utf-8-vs-utf-16-a-simple-guide-583d3f9c2ed3?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/583d3f9c2ed3</guid>
            <category><![CDATA[utf-8]]></category>
            <category><![CDATA[unicode-font]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[text-encoding]]></category>
            <category><![CDATA[utf-16]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 11:38:58 GMT</pubDate>
            <atom:updated>2026-04-17T11:38:57.465Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>What UTF-8 and UTF-16 really mean, why “Unicode-8” is not the right term, and how text becomes bytes.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUHLWFmf0EY8OBBfSOU38Q.png" /></figure><p>One of the most common mistakes in programming is saying “Unicode” when we really mean UTF-8.</p><p>Another common mistake is hearing terms like “Unicode-8” and “Unicode-16.” They sound reasonable, but they are not the correct names. The correct terms are UTF-8 and UTF-16.</p><p>This naming detail matters because Unicode and UTF are not the same thing.</p><p>Unicode is the system that <strong>gives characters an identity</strong>. UTF-8 and UTF-16 are <strong>ways to store those characters as bytes</strong>.</p><p>That is the whole article in one sentence:</p><blockquote><strong>Unicode defines characters. UTF-8 and UTF-16 encode them.</strong></blockquote><p>If you keep that one line in mind, most of the confusion disappears.</p><h3>What Unicode Actually Is ?</h3><p>Unicode is a <strong><em>universal standard</em></strong> for characters.</p><p>It gives a unique number to each character,<strong> no matter which language or symbol</strong> set it belongs to.</p><p>English letters, accented characters, Hindi text, Chinese text, punctuation, currency symbols, and emoji can all live in the same system.</p><p>Those numbers are called <strong>code points</strong>.</p><p>A code point is just the official number assigned to a character inside Unicode.</p><p>For example:</p><ul><li>A is U+0041</li><li>é is U+00E9</li><li>ह is U+0939</li><li>😀 is U+1F600</li></ul><p>You can think of Unicode as a giant master list.</p><p>It tells us that a character exists and what number represents it, but it does not automatically tell us how that number should be stored in a file, sent over a network, or kept in memory.</p><p>That <em>next</em> <em>step</em> is the job of an <strong>encoding</strong>.</p><h3>What UTF-8 and UTF-16 Actually Do ?</h3><p>An encoding answers a practical question:</p><p><strong>How do we turn a Unicode code point into actual bytes?</strong></p><p>This is where UTF-8 and UTF-16 come in.</p><p>They are <strong>two different</strong> encoding formats for the <strong>same</strong> Unicode characters. They <strong>do not change the meaning</strong> of the character. They only change how the character is represented in bytes.</p><p>An easy analogy is this:</p><ul><li>Unicode is the <em>master list of products</em></li><li>UTF-8 and UTF-16 are<em> two different packaging formats</em></li></ul><p>The product is the same. The packaging is different.</p><p>That means A is still the same character in both encodings. The difference is only in how a computer stores it.</p><p>Here is the short comparison:</p><ul><li>Unicode: the character standard</li><li>UTF-8: an encoding that uses 1 to 4 bytes</li><li>UTF-16: an encoding that uses 2 or 4 bytes</li></ul><h3>UTF-8 in Simple Words</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkiTWICUb_3Fh0ddpgmaPQ.png" /></figure><h3>UTF-8 in Simple Words</h3><p>It is a <strong>variable-length encoding</strong>, which means different characters can use different numbers of bytes.</p><p>In UTF-8:</p><ul><li>common English characters often use 1 byte</li><li>many other characters use 2 or 3 bytes</li><li>emoji and some other characters use 4 bytes</li></ul><p>That makes UTF-8 very space-efficient for English-heavy text.</p><p>For example, the letter A only needs 1 byte in UTF-8. So if your text is mostly plain English, UTF-8 stays compact.</p><p>This is one reason it became the <strong>default encoding </strong>for websites, APIs, and many modern tools.</p><p>Some example byte sequences in UTF-8:</p><ul><li>A -&gt; 41</li><li>é -&gt; C3 A9</li><li>ह -&gt; E0 A4 B9</li><li>😀 -&gt; F0 9F 98 80</li></ul><p>You <strong>do not need to memorize</strong> those values. The important part is the pattern: UTF-8 can use more bytes when needed, but it stays small for basic ASCII text.</p><h3>UTF-16 in Simple Words</h3><p>UTF-16 is another way to encode the same Unicode characters.</p><p>It is also variable-length, but in a <strong>different</strong> way from UTF-8.</p><p>In UTF-16:</p><ul><li>many common characters use 2 bytes</li><li>some characters use 4 bytes</li></ul><p>So while UTF-8 works in units of 1 to 4 bytes, UTF-16 usually works in chunks of 2 bytes.</p><p>For simple Latin text, this means UTF-16 often uses more space than UTF-8. For example, A is 1 byte in UTF-8 but typically 2 bytes in UTF-16.</p><p>Some example values in UTF-16 are often shown as <strong>16-bit hex units</strong>:</p><ul><li>A -&gt; 0041</li><li>é -&gt; 00E9</li><li>ह -&gt; 0939</li><li>😀 -&gt; D83D DE00</li></ul><p>That last example needs a little extra explanation.</p><p>Some characters, especially many emoji and less common symbols, do not fit into one 16-bit unit in UTF-16. So UTF-16 uses <strong>two 16-bit units</strong> for them. This pair is called a <strong>surrogate pair</strong>.</p><p>You do not need to know the full math behind surrogate pairs to understand the main idea:</p><p>UTF-16 can store some characters in one 2-byte unit, but others need two units, which becomes 4 bytes total.</p><p>If you look at real files, the exact byte order can vary depending on endianness. For this article, the hex values above are just the simplest way to show the structure.</p><h3>Examples You Can See</h3><p>Let us compare the same characters across Unicode, UTF-8, and UTF-16.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNsdkVQK6ORrpGAAjJ-Jtg.png" /><figcaption>Unicode and UTF-8 vs UTF-16</figcaption></figure><p>This table shows the key idea very clearly:</p><p>The character itself does not change. Its Unicode identity stays the same. Only the byte representation changes depending on the encoding.</p><p>That is why it is important not to mix up Unicode and UTF-8.</p><h3>A Practical Way to Think About It</h3><p>When someone says, “This file is Unicode,” they usually mean one of two things:</p><ul><li>the file contains Unicode characters</li><li>the file is encoded in UTF-8</li></ul><p>Most of the time, they really mean the second one.</p><p>That is why developers often get confused during debugging. A system may fully support Unicode characters, but if one part writes text in UTF-16 and another part expects UTF-8, the bytes will not line up correctly.</p><p>So the practical mental checklist is:</p><ol><li>What character is this?</li><li>What is its Unicode code point?</li><li>Which encoding is being used to store it?</li></ol><p>If you separate those three questions, text handling gets much easier.</p><h3>The Mental Model to Remember</h3><p>Here is the simplest way to remember everything in this topic:</p><ul><li>Unicode is the identity of the character</li><li>UTF-8 and UTF-16 are byte representations of that character</li></ul><p>Or even shorter:</p><p><strong>Unicode is about meaning. UTF-8 and UTF-16 are about storage.</strong></p><p>That is why “Unicode-8” is not the right term. Unicode is not a storage format. UTF-8 and UTF-16 are.</p><p>If you remember that difference, you will understand why the same character can look identical on screen while having completely different byte sequences underneath.</p><p>And once that clicks, encodings stop feeling mysterious. They become what they really are: practical formats for packaging the same text in different ways.</p><p>#happycoding #codebrace</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=583d3f9c2ed3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/unicode-vs-utf-8-vs-utf-16-a-simple-guide-583d3f9c2ed3">Unicode vs UTF-8 vs UTF-16: A Simple Guide</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spark Runs a Query Internally: A Step-by-Step Guide]]></title>
            <link>https://medium.com/codebrace/how-spark-runs-a-query-internally-a-step-by-step-guide-c87e0a1937b5?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/c87e0a1937b5</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 14:25:49 GMT</pubDate>
            <atom:updated>2024-11-24T14:25:49.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*DpQ0LGpnY_vawGth.png" /><figcaption>Spark Query Execution</figcaption></figure><p><strong>Apache Spark</strong> is a powerful distributed computing framework widely used for big data processing.</p><p>Understanding how Spark executes queries can help optimize performance and debug issues efficiently. In this article, we’ll break down the entire lifecycle of a query in Spark, step by step.</p><h3>1. Query Submission</h3><p>The process begins with submitting a query to Spark through its SparkSession. This can be done using <strong>SQL</strong> queries or the <strong>DataFrame</strong> API.</p><h4>Example:</h4><pre># Submitting a SQL query<br>spark.sql(&quot;SELECT city, COUNT(*) FROM sales GROUP BY city;&quot;)</pre><p>At this point, the query is simply a string (if using SQL) or a logical representation in the case of the DataFrame API.</p><h3>2. Parsing</h3><p>Spark uses its <strong>Catalyst Optimizer</strong> to parse the query. This involves:</p><ul><li>Converting the SQL query into an <strong>Unresolved Logical Plan</strong>.</li><li>The plan defines the operations but <strong>does not resolve column names</strong> or table references.</li></ul><p><strong>Input</strong>: The SQL query string <br><em>“SELECT city, COUNT(*) FROM sales GROUP BY city;”</em></p><p><strong>Output</strong>: An <strong>Unresolved Logical Plan</strong>, which identifies the table (sales), column (city), and the aggregate function (COUNT) as follows</p><pre>&#39;Aggregate [city], [count(1) AS count]<br>+- &#39;UnresolvedRelation [sales]</pre><h3>3. Analysis</h3><p>In the analysis phase, Spark’s <strong>Analyzer</strong> resolves table names, column names, and functions using the Catalog. If any field, table, or function is missing or ambiguous, an error is raised.</p><ul><li>Spark resolves the sales table and the city column using its <strong>catalog</strong>.</li><li><strong>Output</strong>: A <strong>Resolved Logical Plan</strong> with fully qualified references to sales.city and the aggregate function as follows.</li></ul><pre>Aggregate [city], [count(1) AS count]<br>+- SubqueryAlias sales<br>   +- LogicalRDD [city#1]</pre><h3>4. Logical Optimization</h3><p>Spark applies optimization rules to the logical plan to make it more efficient. Common optimizations include:</p><ul><li><strong>Predicate Pushdown</strong>: Moving filters closer to the data source.</li><li><strong>Projection Pruning</strong>: Removing unused columns, <br><em>Only the </em><em>city column and the count are retained in the plan as they are the only ones being used.</em></li><li><strong>Constant Folding</strong>: Evaluating constant expressions.</li><li><strong>Output</strong>: An <strong>Optimized Logical Plan</strong> that minimizes unnecessary data movement and computation as follows.</li></ul><pre>Aggregate [city#1], [count(1) AS count]<br>+- LogicalRDD [city#1]</pre><h3>5. Physical Planning</h3><p>The <strong>Physical Planner</strong> converts the logical plan into one or more <strong>Physical Plans</strong>. Each physical plan represents a specific strategy for executing the query.</p><p><strong>Key steps (for query):</strong></p><ul><li>Spark evaluates different physical execution strategies.</li><li>One strategy might scan the sales table entirely and then group it by city.</li><li>The lowest-cost plan is selected, e.g.</li></ul><pre>HashAggregate(keys=[city#1], functions=[count(1)])<br>+- Exchange hashpartitioning(city#1, 200)<br>   +- HashAggregate(keys=[city#1], functions=[partial_count(1)])<br>      +- Scan ExistingRDD[city#1]</pre><h3>6. Code Generation</h3><p>Spark uses its <strong>Tungsten Execution Engine</strong> to generate optimized Java bytecode for the selected physical plan. This helps <strong>minimize</strong> <strong>CPU</strong> usage and <strong>memory</strong> <strong>overhead</strong>.</p><ul><li>Spark’s Tungsten Engine generates Java bytecode for <strong>selected</strong>(by cost model) the physical plan.</li><li>Optimizations like in-memory computation and pipelining are applied.</li></ul><h3>7. Query Execution</h3><p>The query execution is divided into <strong>jobs</strong>, <strong>stages</strong>, and <strong>tasks</strong>:</p><ol><li><strong>Job Creation</strong>: Spark creates a <strong>job</strong> for the query.</li><li><strong>Stage Division</strong>: Each job is split into <strong>stages</strong> based on <strong>shuffle boundaries</strong>.</li><li><strong>Task Execution</strong>: Each stage contains <strong>tasks</strong> that run in parallel on Spark executors.</li></ol><p>Executor Workflow:</p><ul><li><strong>Read Input Data</strong>: Data is read from sources like <strong>HDFS</strong>, <strong>S3</strong>, or <strong>databases</strong>.</li><li><strong>Apply Transformations</strong>: Filtering, mapping, and other transformations are applied.</li><li><strong>Shuffle Data</strong>: Data is repartitioned as needed for operations like join or groupBy.</li></ul><p><strong>Key steps (for query):</strong></p><ul><li>Spark divides the query into stages and tasks:</li><li><strong>Stage 1</strong>: Scan the sales table and extract the city column.</li><li><strong>Stage 2</strong>: Perform the groupBy operation and compute the COUNT for each city.</li><li>Shuffles occur if data needs to be repartitioned between stages.</li></ul><h3>8. Action Execution</h3><ul><li>If the query is triggered by an action like collect or write, Spark executes the stages:</li><li><strong>Executors</strong> read data, apply transformations, and compute the aggregate results.</li><li>The final results (e.g., city and count) are collected or written to storage.</li></ul><h3>Monitoring Query Execution</h3><h3>1. Spark UI</h3><ul><li>Available at http://&lt;driver-host&gt;:4040 (local) or through the Spark job tracker.</li><li>Shows details about jobs, stages, tasks, and execution timelines.</li></ul><h3>2. Explain Plan</h3><ul><li>Use explain() or the EXPLAIN SQL command to view the logical and physical plans.</li></ul><pre># For DataFrame<br>df.explain(extended=True)<br><br># For SQL Query<br>EXPLAIN EXTENDED SELECT * FROM my_table;</pre><p>The EXPLAIN output helps you understand how Spark optimizes and executes your query.</p><h3>Conclusion</h3><p>Understanding the query execution lifecycle in Spark is essential for optimizing performance and troubleshooting. By following the steps outlined above, you can gain insights into how Spark processes your queries and take advantage of its optimization techniques.</p><p><strong>Happy querying! #codebrace</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c87e0a1937b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/how-spark-runs-a-query-internally-a-step-by-step-guide-c87e0a1937b5">How Spark Runs a Query Internally: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Object Versioning in Google Cloud Storage: A Comprehensive Guide]]></title>
            <link>https://medium.com/codebrace/mastering-object-versioning-in-google-cloud-storage-a-comprehensive-guide-d74985549cd7?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/d74985549cd7</guid>
            <category><![CDATA[google-cloud-storage]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 13:47:04 GMT</pubDate>
            <atom:updated>2024-10-13T06:37:07.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rifO_fS78NivlRbn.jpg" /><figcaption>Using Object Versioning in Google Cloud Storage</figcaption></figure><h3>Usecase</h3><p>Suppose we have a lot of data in our Cloud Storage bucket and somehow by mistake someone runs</p><blockquote><strong><em>gsutil rm gs://my_bucket/*</em></strong></blockquote><p>or some <strong>script</strong> or <strong>application</strong> deletes some critical data due to some bug or missing <strong>argument</strong>.</p><p>we will lose all our data and won’t be able to recover it easily or may never recover it.</p><h3>How does GCS ObjectVersioning Help?</h3><p>By Design, every storage object (file) in <strong>Cloud Storage</strong> is assigned 2 sequence numbers</p><ul><li>generation number</li><li>meta-generation number</li></ul><p>we will talk about them in detail later,</p><p>In a Nutshell, a <strong>generation number</strong> will be assigned each time we replace an object or modify it. similarly, a <strong>meta-generation number </strong>will be assigned to an object each time we modify the meta-data.</p><p>By default, <strong>object versioning</strong> is disabled as it incurs more cost as we store multiple versions of the same object with different <strong>generation</strong> and <strong>meta-generation numbers, </strong>but if we need the ability to recover old data we can leverage<strong> object versioning.</strong></p><h3>Enabling Object versioning</h3><ul><li>We have just created a new bucket <strong>ashish_vtest </strong>having 2 files log.txt and Main.java</li><li>we can check if the Object versioning is enabled on a bucket/folder <br>status can be <strong>Suspended</strong> or <strong>Enabled</strong>.</li></ul><pre>gsutil versioning get gs://ashish_vtest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvTcAtx1Q9HafR8tQZtR8g.png" /><figcaption>checking object versioning status</figcaption></figure><p>Now Let’s <strong>enable</strong> the versioning</p><pre>gsutil versioning set on gs://ashish_vtest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82LklV5Y2KGQb0XW-SYt8g.png" /><figcaption>enabling object versioning</figcaption></figure><h3>Checking Object Versions</h3><ul><li>We can use <strong>gsutil ls -a gs://&lt;path&gt; </strong>to check all the file object versions. ( all the files including old versions and current ones )</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHBAY_6gcjvcOylnY-uJRg.png" /><figcaption>checking all object versions</figcaption></figure><ul><li>we can see there is the number after file names prefixed by <strong>#, </strong>which is called the <strong>generation number.</strong></li><li>we can access any non-current file( old versions ), using full name of the files ( name + generation number )</li></ul><h3>Deleting and recovering a file</h3><ul><li>Now, let’s do some real work first we will delete <strong>log.txt </strong>and then recover it using the <strong>generation number.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpLZJGzRfNVXhgN1jpGAjw.png" /><figcaption>Deleting a file</figcaption></figure><ul><li>as we can see there is only one <strong>current file</strong>, which we can check using <strong>gsutil ls gs://&lt;path&gt;</strong></li><li>but if we check all the Object versions we will still see 2 files</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GM7korsAG7phLUkv8tqxUw.png" /></figure><ul><li>Now, let’s recover the <strong>log.txt</strong> and put it inside the same location.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmbKjHtCixqEXpquAYJ17Q.png" /><figcaption>recovering deleted Object version</figcaption></figure><ul><li>As you can see, we are just copying files and putting them inside the same directory, note that for using the non-current file we will have to use the <strong>file name and generation number</strong> together.</li><li>we can see there are 2 current files but there will be 3 versions as a new version will be created when we copy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CvGEwy1IDctFCIgu39sFg.png" /></figure><h3>Generations and Meta-Generation Number</h3><ul><li>Even without <a href="https://cloud.google.com/storage/docs/object-versioning">Object Versioning</a> enabled, all Cloud Storage objects have generation numbers and meta-generation numbers. The generation number changes each time the object is replaced, and the meta-generation number changes each time the object’s <a href="https://cloud.google.com/storage/docs/metadata">metadata</a> is updated.</li><li>Buckets maintain a meta-generation number enabling users to uniquely identify a bucket metadata state.</li><li>we can check meta-generation numbers using <strong>-la </strong>flags in <strong>gsutil ls -la gs://&lt;path&gt;</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18ZKUE1pP-lFFZpfAyrfdg.png" /><figcaption>checking metageneration Numbers</figcaption></figure><ul><li><strong>meta-generation </strong>number starts from 1 and increases as we update the metadata state of an Object.</li><li>let’s update the meta-data for <strong>log.txt </strong>and check the <strong>meta-generation </strong>number.</li><li>We can edit metadata directly via UI or we can use CLI refer — <a href="https://cloud.google.com/storage/docs/viewing-editing-metadata#view">https://cloud.google.com/storage/docs/viewing-editing-metadata#view</a></li><li>from 3 dots on the right side of an object on GCP UI, we can edit metadata</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*RXLs18WuwSd_Afd1-rGFcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*OSNdakMe-mmijYSFhrGMjg.png" /><figcaption>Editing meta-data</figcaption></figure><ul><li>Now, if we check, we will see 2 meta-generation numbers for <strong>log.txt</strong><br>If we want to access a file with specific <strong>meta-data,</strong> we will have to use the <strong>generation number </strong>if that version is not the current one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlmR0m8bU0lvI0Oui-kCRg.png" /></figure><h3>Disabling Object versioning</h3><ul><li>we can disable object versioning using <strong>gsutil </strong>command</li></ul><pre>gsutil versioning set off gs://ashish_vtest</pre><ul><li>Even after disabling <strong>Object Versioning,</strong> all the versions that are there won’t be deleted, Although Cloud storage will not create any further Versions.</li><li>documentation — <a href="https://cloud.google.com/storage/docs/using-object-versioning">https://cloud.google.com/storage/docs/using-object-versioning</a></li></ul><p>If you like this article, please follow me and this publication for more interesting articles, a clap will be appreciated.</p><p>#codebrace #happy_coding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d74985549cd7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/mastering-object-versioning-in-google-cloud-storage-a-comprehensive-guide-d74985549cd7">Mastering Object Versioning in Google Cloud Storage: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signing commits with GPG in GitHub: A Complete Guide]]></title>
            <link>https://medium.com/codebrace/signing-commits-with-gpg-in-github-a-complete-guide-b5c930302961?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/b5c930302961</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[gpg]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 09:42:02 GMT</pubDate>
            <atom:updated>2024-10-17T09:42:02.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*WRDWw94BONDp1l2nA9mg_g.png" /></figure><p><strong>Introduction</strong></p><p>In today’s digital world, securing your online identity is more critical than ever. When it comes to GitHub, committing code securely ensures the integrity of your work and helps avoid unauthorized changes. One way to do this is by signing your commits using <strong>GPG</strong> (GNU Privacy Guard). This guide will walk you through the basics of GPG, how it works, and how to use it to sign your commits on GitHub.</p><p><strong>What is GPG?</strong></p><p>GPG (GNU Privacy Guard) is a tool for secure communication and data storage. It uses <strong>public-key cryptography</strong> to encrypt and sign data. With GPG, you have two keys:</p><p>1. <strong>Public Key</strong>: Shared with others to encrypt data sent to you or verify your digital signature.</p><p>2. <strong>Private Key</strong>: Kept secret and used to decrypt received data or sign data (like Git commits).</p><p>When you sign your commits with GPG, you add a layer of trust to your code by proving that the commits come from you and haven’t been altered.</p><p><strong>Why Should You Sign Git Commits?</strong></p><p>1. <strong>Security</strong>: Signed commits verify your identity, preventing others from impersonating you.</p><p>2. <strong>Trust</strong>: Signed commits help collaborators and the open-source community trust that the code truly came from you.</p><p>3. <strong>Professionalism</strong>: Signed commits can give you a more polished and secure professional presence on GitHub.</p><p><strong>Getting Started with GPG and GitHub</strong></p><p><strong>1. Install GPG</strong></p><p>First, install GPG on your machine:</p><ul><li><strong>macOS</strong>: Use Homebrew to install GPG.</li></ul><pre>brew install gnupg</pre><ul><li><strong>Linux</strong>: Install using your package manager.</li></ul><pre>sudo apt-get install gnupg</pre><ul><li><strong>Windows</strong>: Download GPG from <a href="https://gpg4win.org/">Gpg4win</a> and install it.</li></ul><p><strong>2. Generate a New GPG Key</strong></p><p>To generate a new GPG key, open your terminal and run:</p><pre>gpg --full-generate-key</pre><p>You will be prompted to choose the type of key. Select RSA and RSA (default) and choose a key size (4096 bits is recommended). Afterward, you’ll need to provide your name, email, and optionally, a passphrase.</p><p>Once generated, you can list your GPG keys with:</p><pre>gpg --list-secret-keys --keyid-format LONG</pre><p><strong>3. Add Your GPG Key to GitHub</strong></p><p>To sign commits, GitHub needs to recognize your public GPG key. First, copy your public key:</p><pre>gpg --armor --export YOUR_ID</pre><p>Replace YOUR_ID with the ID of your GPG key (visible in the output of the previous step). This will display your key in the terminal.</p><p>Copy the entire output, including the</p><p><em>— — -BEGIN PGP PUBLIC KEY BLOCK — — — </em><br>and<br><em> — — -END PGP PUBLIC KEY BLOCK — — — </em><br>sections.</p><p>Next, go to your GitHub account settings:</p><p>1. <strong>Settings</strong> &gt; <strong>SSH and GPG Keys</strong> &gt; <strong>New GPG Key</strong>.</p><p>2. Paste your copied public key.</p><p>3. Click <strong>Add GPG Key</strong>.</p><p><strong>4. Configure Git to Use Your GPG Key</strong></p><p>Once you’ve added your GPG key to GitHub, you need to configure Git to use it. Run the following commands:</p><pre>git config --global user.signingkey YOUR_ID<br>git config --global commit.gpgSign true</pre><p>Replace YOUR_ID with your GPG key ID.</p><p><strong>5. Signing Commits</strong></p><p>Now that GPG is configured, you can sign your commits automatically by adding -S when committing:</p><pre>git commit -S -m &quot;Your commit message&quot;</pre><p>Git will ask for your GPG passphrase (if you set one). If the commit is successfully signed, you’ll see a “Verified” badge next to the commit on GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aN76n9fdUIkgQTV9R1J5Fg.png" /></figure><p><strong>6. Verify Signed Commits</strong></p><p>On GitHub, any signed commit will show a <strong>Verified</strong> badge:</p><p>• A green badge means the commit is properly signed and verified.</p><ul><li>A red or gray badge might indicate an issue with the signature (e.g., the key isn’t recognized).</li></ul><p>Hoping this was helpful, Please clap and share you find this helpful, Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5c930302961" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/signing-commits-with-gpg-in-github-a-complete-guide-b5c930302961">Signing commits with GPG in GitHub: A Complete Guide</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking JSON Schema in Apache Spark: A Step-by-Step Guide to Inferring from JSON Columns]]></title>
            <link>https://medium.com/codebrace/unlocking-json-schema-in-apache-spark-a-step-by-step-guide-to-inferring-from-json-columns-864d803d1604?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/864d803d1604</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 05:25:53 GMT</pubDate>
            <atom:updated>2024-10-08T05:25:11.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/908/0*lILYmohK2lkeN4ks.png" /></figure><p><strong>Introduction</strong></p><p>In big data processing, dealing with <strong>JSON</strong> data in Spark often requires inferring the schema for further processing. However, inferring a schema from an entire dataset can be <strong>inefficient</strong>, especially when working with large datasets. A practical solution is to infer the schema from just the top N rows. This approach provides a good approximation of the schema while significantly improving performance.</p><p>In this article, we will walk through a step-by-step approach to efficiently infer <strong>JSON</strong> schema from the top N rows of a Spark DataFrame and use this schema to parse the <strong>JSON</strong> data.</p><h3>Step-by-Step Implementation</h3><p>Let’s dive into the implementation. We’ll use PySpark to demonstrate how to infer the schema from the top 100 rows of a DataFrame containing JSON strings.</p><p><strong>Creating a Sample DataFrame</strong></p><p>We’ll create a sample <strong>DataFrame</strong> with a JSON string column to demonstrate the schema inference process.</p><pre>from pyspark.sql import SparkSession<br># Initialize SparkSession<br>spark = SparkSession.builder.appName(&quot;JSONSchemaInference&quot;).getOrCreate()<br># Sample DataFrame with a JSON string column<br>data = [(&quot;1&quot;, &#39;{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}&#39;),<br>        (&quot;2&quot;, &#39;{&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}&#39;),<br>        (&quot;3&quot;, &#39;{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25,&quot;full_name&quot;: &quot;Charlie&quot;, &quot;city&quot;: &quot;New York&quot;}&#39;)]<br>in0 = spark.createDataFrame(data, [&quot;id&quot;, &quot;json_string&quot;])<br>in0.show(truncate=False)<br>OUTPUT:<br>+---+------------------------------------------------+<br>|id |json_string                                      |<br>+---+------------------------------------------------+<br>|1  |{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}                    |<br>|2  |{&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}                      |<br>|3  |{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25,&quot;full_name&quot;: &quot;Charlie&quot;, &quot;city&quot;: &quot;New York&quot;}|<br>+---+------------------------------------------------+</pre><h3>Inferring Schema from a Single Row</h3><p>Let’s infer the schema from just the first row:</p><pre>from pyspark.sql.functions import schema_of_json, lit, from_json, col<br># Get the JSON string from the first row<br>sample_json = in0.select(&quot;json_string&quot;).take(1)[0][0]<br># Infer the schema from the single JSON string<br>json_schema_single = schema_of_json(lit(sample_json))<br>print(&quot;Schema inferred from a single row:\n&quot;, json_schema_single)<br>OUTPUT:<br>Schema inferred from a single row:<br> STRUCT&lt;age: INT, name: STRING&gt;</pre><p>As you can see we have missed all the columns like <strong>full_name, city </strong>as they are not available in first row, as only first row defines the schema.</p><p><strong>Parsing the JSON Data with single row schema<br></strong>Finally, we can parse the JSON data using the inferred schema and add it as a new column to our DataFrame.</p><pre># Parse the JSON strings with the inferred schema<br>out0 = in0.withColumn(&quot;json_parsed_content&quot;, from_json(col(&quot;json_string&quot;), json_schema_single))<br>out0.show(truncate=False)<br>+----+------------------------------------------------------------------------------------------+---------------------+<br>| id | json_string                                                                              | json_parsed_content |<br>+----+------------------------------------------------------------------------------------------+---------------------+<br>|  1 | {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}                                                             | {25, Alice}         |<br>|  2 | {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}                                                               | {30, Bob}           |<br>|  3 | {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25, &quot;full_name&quot;: &quot;Charlie&quot;, &quot;city&quot;: &quot;New York&quot;}                 | {25, Alice}         |<br>+----+------------------------------------------------------------------------------------------+---------------------+</pre><ul><li>As we can see, we lost data of <strong>full_name </strong>and<strong> city </strong>even though it was there in just third row, infact any key which is not in first will be ignored.</li></ul><h3>Inferring Schema from a N Row</h3><p>We need to have a wholesome schema which can represent our data, we have 2 options</p><ol><li>Either we use all of our rows to infer schema, which will be very resource-intensive and time-consuming.</li><li>We can sample data (let’s say the top N rows) which are more likely to give us better results than the first one.</li></ol><p>By focusing on the top <strong>N</strong> rows, you can achieve a balance between accuracy and efficiency.</p><p><strong>3. Limiting the DataFrame to the Top N ( let say 100) Rows</strong></p><p>Instead of inferring the schema from the entire dataset, we limit our DataFrame to the top 100 rows. This is where the efficiency gain happens.</p><pre># Limit the DataFrame to the top 100 rows<br>limited_df = in0.limit(100)</pre><p><strong>4. Combining JSON Strings into a Single JSON Array String</strong></p><p>As <a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.schema_of_json.html"><strong>scheme_of_json()</strong></a> doesn’t take a column, it takes a string ( there is still a <a href="https://issues.apache.org/jira/browse/SPARK-24642">Spark Jira</a> which was closed)</p><p>To infer the schema, we need to combine these <strong>100</strong> JSON strings into a single JSON array string.</p><pre>from pyspark.sql.functions import concat_ws, collect_list<br><br># Collect the limited JSON strings from the column into a single JSON array string<br>combined_json_df = limited_df.select(concat_ws(&quot;,&quot;, collect_list(&quot;json_string&quot;)).alias(&quot;combined_json&quot;))<br>combined_json = combined_json_df.collect()[0][&quot;combined_json&quot;]<br>combined_json = &quot;[&quot; + combined_json + &quot;]&quot;</pre><p><strong>5. Generating the Schema</strong></p><p>With the combined JSON array string, we can now infer the schema which will give us a better schema.</p><pre>from pyspark.sql.functions import schema_of_json, lit<br><br># Generate the schema from the combined JSON array string<br>json_schema = schema_of_json(lit(combined_json))<br>print(json_schema)<br>OUTPUT -<br>Schema inferred from the top 100 rows:<br> STRUCT&lt;age: INT, city: STRING, full_name: STRING, name: STRING&gt;</pre><p>As we can see we got better representation and now we can use this schema to parse our JSON column</p><p><strong>Parsing the JSON Data</strong></p><p>Finally, we can parse the JSON data using the inferred schema and add it as a new column to our DataFrame.</p><pre># Parse the JSON strings with the inferred schema<br>out0 = in0.withColumn(&quot;json_parsed_content&quot;, from_json(col(&quot;json_string&quot;), json_schema_100))<br>out0.show(truncate=False)<br><br>OUTPUT: <br>+---+------------------------------------------------+----------------------------------------+<br>| id |                json_string                     |           json_parsed_content          |<br>+---+------------------------------------------------+----------------------------------------+<br>| 1  | {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}                   | {25, null, null, Alice}                |<br>| 2  | {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}                     | {30, null, null, Bob}                  |<br>| 3  | {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25,                   | {25, New York, Charlie, Alice}         |<br>|    | &quot;full_name&quot;: &quot;Charlie&quot;, &quot;city&quot;: &quot;New York&quot;}    |                                        |<br>+---+------------------------------------------------+----------------------------------------+</pre><ul><li>As we can see we got, the values of <strong>city</strong> and <strong>full_name</strong> as well.</li></ul><p><strong>Conclusion</strong></p><p>By limiting schema inference to the top N rows, we can significantly optimize performance when working with large datasets. This method strikes a balance between efficiency and accuracy, making it an effective approach for handling JSON data in Spark.</p><p>Whether working with massive datasets or just looking to speed up your data processing pipelines, this technique can be a valuable tool in your Spark arsenal.</p><p>If you found this guide helpful, don’t forget to share it with your colleagues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=864d803d1604" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/unlocking-json-schema-in-apache-spark-a-step-by-step-guide-to-inferring-from-json-columns-864d803d1604">Unlocking JSON Schema in Apache Spark: A Step-by-Step Guide to Inferring from JSON Columns</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitmasking and C++ bitset]]></title>
            <link>https://medium.com/codebrace/bitmask-and-c-std-bitset-683cd589f654?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/683cd589f654</guid>
            <category><![CDATA[bit]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[bitmask]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 15:16:03 GMT</pubDate>
            <atom:updated>2023-02-26T15:21:18.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*FPEuyK-WPgOMgiOs.png" /></figure><h3>What is Bitmasking?</h3><p>At the Smallest scale in computers, data is stored as <strong>bits</strong>. A <strong>bit</strong> stores either 0 or 1. A binary number is a number expressed in the base-2 system. Each digit can be either 0 or 1.</p><p>You can check the binary representation of a number in <strong>python</strong>:</p><pre>&gt;&gt;&gt; bin(21)<br>&#39;0b10101&#39;</pre><p>So, 21 is represented as ‘10101’ in Binary.</p><h4>Bitmask</h4><p>Now finally, what’s a mask? We can construct a <strong>binary number</strong> such that a particular digit is set to <strong>1</strong> and other digits are set to <strong>0</strong>. This creates a “mask” that when we AND it to another binary it &quot;turns off&quot; (set to 0) all digits except the 1 digit in the mask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*pN8154aa85kMbdKT.png" /></figure><h4>Common Bitmask Operations</h4><ol><li>(number | (1 &lt;&lt; i)) <br>this operation sets the ith bit in the number to 1.</li><li>(number &amp; ~(1 &lt;&lt; i)) <br>this operation sets the ith bit in the number to 0.</li><li>(number &amp; (1 &lt;&lt; i))<br>this operation checks if the ith bit in the number is set to 1 or not.<br>and so on.</li></ol><p>more bitmask operations -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b2007f10dece3da74ff7269ba311cf/href">https://medium.com/media/71b2007f10dece3da74ff7269ba311cf/href</a></iframe><h3>Bitset in C++</h3><p>In C++, A Bitset is a data structure that is used to represent a set of bits. It is similar to an array, but instead of storing integers or characters, it stores binary values. Bitsets are commonly used in computer graphics, network programming, and cryptography.</p><p>In C++, a Bitset is implemented using the std::bitset class. This class provides a set of operations for manipulating and querying the bits in the bitset. For example:</p><pre>#include &lt;bitset&gt;<br>#include &lt;iostream&gt;<br><br>using namespace std;<br><br>int main() {<br>    bitset&lt;8&gt; bits(&quot;10100101&quot;);<br><br>    cout &lt;&lt; bits &lt;&lt; endl; // prints &quot;10100101&quot;<br>    cout &lt;&lt; bits.count() &lt;&lt; endl; // prints &quot;4&quot;<br>    cout &lt;&lt; bits.any() &lt;&lt; endl; // prints &quot;true&quot;<br>    cout &lt;&lt; bits.none() &lt;&lt; endl; // prints &quot;false&quot;<br>    cout &lt;&lt; bits.test(3) &lt;&lt; endl; // prints &quot;true&quot;<br>    cout &lt;&lt; bits.set(2) &lt;&lt; endl; // prints &quot;10101101&quot;<br>    cout &lt;&lt; bits.reset(1) &lt;&lt; endl; // prints &quot;10101100&quot;<br>    cout &lt;&lt; bits.flip() &lt;&lt; endl; // prints &quot;01010011&quot;<br><br>    return 0;<br>}</pre><p>Here’s an example of how to use bitset for masking:</p><pre>// C++ program to demonstrate various functionality of bitset<br>#include &lt;bits/stdc++.h&gt;<br>using namespace std;<br><br>#define M 32<br><br>int main()<br>{<br> // default constructor initializes with all bits 0<br> bitset&lt;M&gt; bset1;<br><br> // bset2 is initialized with bits of 20<br> bitset&lt;M&gt; bset2(20);<br><br> // bset3 is initialized with bits of specified binary string<br> bitset&lt;M&gt; bset3(string(&quot;1100&quot;));<br><br> // cout prints exact bits representation of bitset<br> cout &lt;&lt; bset1 &lt;&lt; endl; // 00000000000000000000000000000000<br> cout &lt;&lt; bset2 &lt;&lt; endl; // 00000000000000000000000000010100<br> cout &lt;&lt; bset3 &lt;&lt; endl; // 00000000000000000000000000001100<br> cout &lt;&lt; endl;<br><br> // declaring set8 with capacity of 8 bits<br><br> bitset&lt;8&gt; set8; // 00000000<br><br> // setting first bit (or 6th index)<br> set8[1] = 1; // 00000010<br> set8[4] = set8[1]; // 00010010<br> cout &lt;&lt; set8 &lt;&lt; endl;<br><br> // count function returns number of set bits in bitset<br> int numberof1 = set8.count();<br><br> // size function returns total number of bits in bitset<br> // so there difference will give us number of unset(0)<br> // bits in bitset<br> int numberof0 = set8.size() - numberof1;<br><br> cout &lt;&lt; set8 &lt;&lt; &quot; has &quot; &lt;&lt; numberof1 &lt;&lt; &quot; ones and &quot;<br>  &lt;&lt; numberof0 &lt;&lt; &quot; zeros\n&quot;;<br><br> // test function return 1 if bit is set else returns 0<br> cout &lt;&lt; &quot;bool representation of &quot; &lt;&lt; set8 &lt;&lt; &quot; : &quot;;<br> for (int i = 0; i &lt; set8.size(); i++)<br>  cout &lt;&lt; set8.test(i) &lt;&lt; &quot; &quot;;<br><br> cout &lt;&lt; endl;<br><br> // any function returns true, if atleast 1 bit<br> // is set<br> if (!set8.any())<br>  cout &lt;&lt; &quot;set8 has no bit set.\n&quot;;<br><br> if (!bset1.any())<br>  cout &lt;&lt; &quot;bset1 has no bit set.\n&quot;;<br><br> // none function returns true, if none of the bit<br> // is set<br> if (!bset1.none())<br>  cout &lt;&lt; &quot;bset1 has some bit set\n&quot;;<br><br> // bset.set() sets all bits<br> cout &lt;&lt; set8.set() &lt;&lt; endl;<br><br> // bset.set(pos, b) makes bset[pos] = b<br> cout &lt;&lt; set8.set(4, 0) &lt;&lt; endl;<br><br> // bset.set(pos) makes bset[pos] = 1 i.e. default<br> // is 1<br> cout &lt;&lt; set8.set(4) &lt;&lt; endl;<br><br> // reset function makes all bits 0<br> cout &lt;&lt; set8.reset(2) &lt;&lt; endl;<br> cout &lt;&lt; set8.reset() &lt;&lt; endl;<br><br> // flip function flips all bits i.e. 1 &lt;-&gt; 0<br> // and 0 &lt;-&gt; 1<br> cout &lt;&lt; set8.flip(2) &lt;&lt; endl;<br> cout &lt;&lt; set8.flip() &lt;&lt; endl;<br><br> // Converting decimal number to binary by using bitset<br> int num = 100;<br> cout &lt;&lt; &quot;\nDecimal number: &quot; &lt;&lt; num<br>  &lt;&lt; &quot; Binary equivalent: &quot; &lt;&lt; bitset&lt;8&gt;(num);<br><br> return 0;<br>}<br><br>/* OUTPUT<br><br>00000000000000000000000000000000<br>00000000000000000000000000010100<br>00000000000000000000000000001100<br><br>00010010<br>00010010 has 2 ones and 6 zeros<br>bool representation of 00010010 : 0 1 0 0 1 0 0 0 <br>bset1 has no bit set.<br>11111111<br>11101111<br>11111111<br>11111011<br>00000000<br>00000100<br>11111011<br><br>Decimal number: 100 Binary equivalent: 01100100<br><br>*/<br></pre><h3>Conclusion</h3><p>One of the biggest benefits of using Bitmask and Bitset in C++ is their efficiency. <strong>Bitwise</strong> operations are much faster than <strong>arithmetic</strong> operations and can be used to manipulate multiple bits at once. This makes them ideal for working with large datasets in <strong>Competitive Programming </strong>competitions<strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=683cd589f654" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/bitmask-and-c-std-bitset-683cd589f654">Bitmasking and C++ bitset</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Validation — What, Why, and How?]]></title>
            <link>https://medium.com/codebrace/data-validation-what-why-and-how-546774172e6c?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/546774172e6c</guid>
            <category><![CDATA[great-expectations]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-validation]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Sat, 02 Apr 2022 18:08:01 GMT</pubDate>
            <atom:updated>2022-04-02T18:08:01.593Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Validation — What, Why, and How?</h3><h3>what?</h3><p><strong>Data validation</strong> is a method for checking the accuracy and quality of your data.</p><p>Data validation ensures that your data is <strong>complete</strong> (no blank or null values), <strong>unique</strong> (contains distinct values that are not duplicated), <strong>in range</strong> of values is what you expect, and much more depending on your field type and possible values.</p><h3>why?</h3><p>Often Used with ETLs ( Extract, Transform, and Load), <strong>Data Validation</strong> makes sure the data you are producing is accurate, safe for further use, and adheres to the guidelines set within your organization.</p><p>In <strong>ETL</strong> projects, data is extracted from the source, worked upon by applying some logic in the software, transformed, and then loaded into the target storage. In many cases, the transformation is done to change the source data into a more usable format for the business requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*eNxHFwBW2N0-U_k1r9OMBg.png" /><figcaption>Validations in ETL jobs</figcaption></figure><p>Further, if you are consuming data from systems that you don’t trust, you can implement your validation <strong>while</strong> <strong>extracting data</strong> to make sure the data you are using is accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*PhzQgEr8-BclUD0121AQJg.png" /><figcaption>Validations in ETL jobs reading data from External or unreliable sources</figcaption></figure><p>Here, data validation is required to confirm that the data which is loaded into the target system is complete, accurate and there are no data losses or discrepancies, as well as the data you are using is complete to catch any data issues as soon as possible.</p><h3>How?</h3><p>Data Validation could be used in many places and in many ways, but here we are going to explore a general <strong>ETL</strong> use case.</p><p>There could be many <strong>data quality parameters</strong> based on your data and requirements, here are a few important ones.</p><h4>#1 Data Accuracy —</h4><p>As the name suggests, we validate if the data is <strong>logically</strong> accurate.<br>There are <strong>two categories </strong>of values for this type of test. With this, the tester can catch the data quality issues even in the source system.</p><ul><li><strong>Literal Value analysis — </strong><br>Under this classification, we verify the accuracy of the non-numerical content. <strong>Examples — </strong>are Emails, Pin codes, Phone in a valid format.</li><li><strong>Domain Value Analysis — <br></strong>In this type of test, we pick domains of data and validate for errors. these values can be further divided into <strong>three</strong> groupings for this as follows:</li></ul><p><strong>1. Fixed Set of values </strong>— <br>Here we create a list of values that can occur for a field (column in the table). Then validate if the column values are a subset of our list.<br> <strong>Example:</strong> Verify if the Gender column contains either <strong>M, F, or Other.</strong></p><p><strong>2. Fixed Range — <br></strong>Here we set <strong>minimum</strong> and <strong>maximum</strong> ranges for valid data values for a column, based on logical or business reasoning. We then validate if the column values fall within this range.<br><strong>Example:</strong> <strong>0 to 120</strong> for Age.</p><p><strong>3. Foreign Referenced Values</strong> — <br>Here the system uses an external validation source.<br><strong>Example: </strong>Are Country codes valid, do they pick the right value from the reference source or database, or API.</p><h4>#2 Metadata Validation</h4><p>Here we primarily check if the <strong>meta-information</strong> associated with data is correct. A few of the metadata checks are given below<strong>:</strong></p><ul><li><strong>Data Type Check: </strong>Will the <strong>revenue</strong> column works correctly with Decimal (8, 16, or 20 bytes) or Double type?</li><li><strong>Data Length Check:</strong> <strong>Example:</strong> Will the data length for the <strong>address</strong> field be sufficient with <strong>500</strong> chars? this could be really important later on while migrating from one system to another and an exceedingly long format might lead to errors with some datatypes like <strong>varchar</strong> and so on.</li><li><strong>Partition check: </strong>You can check no. of partitions in Dataframe to make sure you are not creating excessive no. of small files, which might lead to performance issues later on.</li><li><strong>Metadata Check Across Environments: </strong>Under this check verify that Metadata matches between the QA test and the Production environment. Tests might pass in the QA environment but fail in other environments.</li></ul><h4>#3 Data Completeness</h4><p>These are sanity tests that uncover missing records or row counts between source and target table and can be run frequently once automated.</p><p>There are two types of tests:</p><p><strong>(i) Record count: </strong>Here, we can have two kinds of checks</p><ul><li>We can <strong>compare the total count</strong> of records for matching tables between source and target systems. This is a quick sanity check to verify the post running of the ETL or Migration job. We have a defect if the counts do not match.</li><li>We can also do a <strong>row range check</strong> to make sure the record count is in a specific range.<br>e.g. if your daily record count is around ~<strong>100K</strong>, you can be sure that the no. of records will always be in range (<strong>30K</strong>, <strong>300K), </strong>and flag a validation error if this is not the case. This could be valid no. of that particular day but certainly outlier enough to have your attention.</li></ul><p><strong>(ii) Column data profiling: </strong>This type of sanity test is valuable when record counts are huge. Here, we create logical sets of data that reduce the record count and then do a comparison between source and target.</p><ul><li>We can also pick all the major columns and check if <strong>KPIs</strong> (minimum, maximum, average, maximum, or minimum length, etc.) match between the target and source table. <strong>Example:</strong> Take average, minimum, and maximum values from the revenue column and compare these values between target and source tables for mismatches.</li><li>Another check can be done for <strong>Null</strong> values. Pick important columns and filter out a list of rows where the column contains Null values. Compare these rows between the target and source systems for the mismatch.</li></ul><p>and many more…</p><h3>Frameworks and Tools</h3><ul><li>there are quite a few libraries and tools to implement <strong>Data Validations, </strong>it actually comes down to your specific use cases and requirements, Lets have a look at a few —</li></ul><p><strong>#1. great_expectations —</strong></p><ul><li>Great Expectations is a shared, open standard for data quality. It helps data teams eliminate pipeline debt, through data testing, documentation, and profiling.</li><li>It is a full-fledge ecosystem with <strong>UI</strong> and integrations with different tools like <strong>Airflow.</strong></li><li>supports <strong>Apache Spark </strong>natively, so you can run your validations over Spark.</li></ul><p>more — <a href="https://greatexpectations.io/">https://greatexpectations.io/</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuM9DB2ca8T8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuM9DB2ca8T8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuM9DB2ca8T8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8d185eaa0c1bfbf46e1d1061c4ee35e/href">https://medium.com/media/a8d185eaa0c1bfbf46e1d1061c4ee35e/href</a></iframe><p><strong>#2. Pandera and fugue</strong></p><ul><li>These are little <strong>lightweight </strong>options if you do not want a full-fledged framework.</li><li><strong>Pandera</strong> — <em>A data validation library for scientists, engineers, and analysts seeking correctness.</em></li><li>Pandera doesn’t support Distributing computing natively, and is only available for Pandas Dataframes, if we have bigger data we can use <strong>Fugue </strong>to port Python or Pandas code to Spark or Dask.</li><li><strong>Fugue — </strong><em>It is a pure abstraction layer that adapts to different computing frameworks such as Spark and Dask.</em></li><li>there is a great article by <a href="https://medium.com/u/e8b70581a392">Kevin Kho</a>, about using <strong>Pandera </strong>and <strong>Fugue.</strong></li></ul><p><a href="https://towardsdatascience.com/using-pandera-on-spark-for-data-validation-through-fugue-72956f274793">Using Pandera on Spark for Data Validation through Fugue</a></p><h4>Comparison between different frameworks</h4><ul><li>There is a great demo from <strong>Data+ AI Summit 2021</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ff901OJrP5ls%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Df901OJrP5ls&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ff901OJrP5ls%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8e0d452382bee71a0842ac17a195ef2/href">https://medium.com/media/c8e0d452382bee71a0842ac17a195ef2/href</a></iframe><h3>Conclusion</h3><p>In this article, <br>we have briefly gone over <strong>What</strong> data validation is and <strong>Why </strong>we should use it to make sure the data is as per the standards, and <strong>How </strong>we can implement it.</p><p>want to give feedback, or have any questions, please leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=546774172e6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/data-validation-what-why-and-how-546774172e6c">Data Validation — What, Why, and How?</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Docker Networks and resolving conflict with Docker Subnet IP Range!]]></title>
            <link>https://medium.com/codebrace/understanding-docker-networks-and-resolving-conflict-with-docker-subnet-ip-range-bfaad092a7ea?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/bfaad092a7ea</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[teradata]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 07:53:45 GMT</pubDate>
            <atom:updated>2021-03-18T07:50:47.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NL-tvEYnHyhExPaZ3EhASQ.png" /><figcaption>Network types in Docker</figcaption></figure><ul><li>As we all know, By default Docker creates 3 networks automatically <br><strong>Bridge</strong>, <strong>Host,</strong> and <strong>None</strong> network.</li></ul><h3>Bridge Network</h3><ul><li>The private internal network created by default.</li><li>Every container is attached to this by default and gets an IP or range <strong>172.17.*.*</strong></li><li>Containers can also access each other using this IP if required.</li><li>For accessing internal IPs we need to map the port of the <strong>container to the docker host using the –p flag.</strong></li></ul><blockquote>By default, Docker uses 172.17.0.0/16 subnet range.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*9Ud3bF51HAry4w1USndcvw.png" /><figcaption>Docker Bridge Network</figcaption></figure><h3>Host Network</h3><ul><li>In this network, all the containers use the docker host’s IP and no mapping is required.</li><li>We can directly use the PORT as everything is available at HOST’s network.</li><li>But not we can’t have multiple containers running on the same PORT in docker as it would have been possible in the <strong>Bridge network</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*0dtD8ajsY0GrteySl-oOOQ.png" /><figcaption>Docker host Network</figcaption></figure><h3>None Network</h3><ul><li>Containers are not attached to any network and don’t have access to other containers or external networks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*g_YhbLQLEcC8mM-nAi6VBQ.png" /><figcaption>Docker None Network</figcaption></figure><blockquote>We can also create our own networks as per out needs, <a href="https://docs.docker.com/engine/reference/commandline/network_create/">more</a></blockquote><h3>Conflict with Docker Default Bridge IP Range</h3><ul><li>In my case, I have been using an external Database system that has an <strong>IP</strong> in the range of <strong>172.17.*.*</strong></li><li>so, when I am trying to connect with the system, It was not able to as <strong>docker bridge </strong>thinks that it is a <strong>container </strong>internal Ip and it was not going through the default gateway.</li><li>I was getting <strong>NoRouteToHostException, </strong>which can be caused due to some <strong>firewall or networking issue.</strong></li></ul><pre>java.net.NoRouteToHostException: No route to host  at java.net.PlainSocketImpl.socketConnect(Native Method)</pre><ul><li>And when I check my route of the container</li></ul><pre>$netstat -rn</pre><pre>Kernel IP routing table<br>Destination Gateway Genmask Flags MSS Window irtt Iface<br>0.0.0.0 172.31.16.1 0.0.0.0 UG 0 0 0 eth0<br>169.254.169.254 0.0.0.0 255.255.255.255 UH 0 0 0 eth0<br>172.18.0.0 0.0.0.0 255.255.0.0 U 0 0 0 br-e9768d205a82<br><strong>172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0</strong><br>172.31.16.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0</pre><ul><li><strong>docker0 </strong>is the <strong>default docker bridge</strong> and it is handling all destinations starting <strong>172.17.*.*</strong></li></ul><h3>Solution</h3><ul><li>for solving this issue I have to change the <strong>Default Bridge IP range</strong> to some other address, like <strong>172.26.*.*</strong></li><li>this could be done by editing <strong>/etc/docker/daemon.json </strong>docker host.</li><li>we will have to add a new field <strong>“bip”: “172.26.0.1/16” </strong>and restart the docker service.</li></ul><pre>sudo vi /etc/docker/daemon.json</pre><p>The JSON will look like this after you updated it:</p><pre>{<br>...<br>...</pre><pre>&quot;bip&quot;: &quot;172.26.0.1/16&quot;<br>}</pre><blockquote><strong>…</strong> is the content you already had before</blockquote><ul><li>Now, Restart Docker service</li></ul><pre>sudo systemctl restart docker</pre><ul><li>Check the routing table, we should be able to see the changed IP Range</li></ul><pre>netstat -rn</pre><p>You should see the following output (see the relevant line in bold):</p><pre>Kernel IP routing table<br>Destination Gateway Genmask Flags MSS Window irtt Iface<br>0.0.0.0 172.31.16.1 0.0.0.0 UG 0 0 0 eth0<br>169.254.169.254 0.0.0.0 255.255.255.255 UH 0 0 0 eth0<br>172.18.0.0 0.0.0.0 255.255.0.0 U 0 0 0 br-e9768d205a82<br><strong>172.26.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0</strong><br>172.31.16.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0</pre><ul><li>That&#39;s it, now we can connect to our required system having IP starting with <strong>172.17.*.* </strong>as there is no conflict and our IP goes through default gateway.</li></ul><p>thanks, #HappyCoding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfaad092a7ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/understanding-docker-networks-and-resolving-conflict-with-docker-subnet-ip-range-bfaad092a7ea">Understanding Docker Networks and resolving conflict with Docker Subnet IP Range!</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working on On-prem/External Airflow with Google Cloud Platform(GCP)]]></title>
            <link>https://medium.com/codebrace/working-on-on-prem-external-airflow-with-google-cloud-platform-gcp-5b2e77b0e3ba?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/5b2e77b0e3ba</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[astronomer]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 13:23:06 GMT</pubDate>
            <atom:updated>2021-03-11T13:18:30.324Z</atom:updated>
            <content:encoded><![CDATA[<p>If you want to work with <strong>Airflow</strong> and just starting up with your installation then <a href="https://cloud.google.com/composer"><strong>Google Cloud Composer</strong></a> is the best solution, As it creates all the required services and manages Kubernetes Cluster via <strong>GKE</strong> and everything connects like magic.</p><p>But if you already have an <strong>On-prem Airflow </strong>or <strong>Airflow</strong> working on some other <strong>Cloud Provider</strong> and want to connect with GCP, you will have to do a couple of things to get everything up and running.</p><h3>Local Setup via Docker</h3><p>You might want to test this setup locally in your local <strong>Airflow</strong> before deploying your DAG in your deployed instance.</p><p>There are 2 ways to install Airflow on your machines<br> 1. Running Airflow locally on your machine <br> 2. Running Airflow via Docker</p><p>If you have already decided not to work with Docker, <strong>good luck with that </strong>here are some docs you can <a href="https://airflow.apache.org/docs/apache-airflow/stable/start/local.html"><strong>refer</strong></a><strong> </strong>.<strong><br></strong>I love Docker and I will help you with this.</p><p>Step 1. Install Docker <a href="https://docs.docker.com/desktop/">more</a><br>Step 2. Use Docker compose to get the instance up and running in a couple of mins.</p><pre>mkdir docker-local &amp;&amp; cd docker-local</pre><pre># downloading docker-compose file<br>curl -LfO &#39;https://airflow.apache.org/docs/apache-airflow/2.0.1/docker-compose.yaml&#39;</pre><pre># initalizing the Airflow Environment<br>docker-compose up airflow-init</pre><pre># Start the services<br>docker-compose up</pre><p>Airflow should be available on Port:8080, by default <a href="http://localhost:8080/home">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFQll_D0grti_nr7xaVDww.png" /><figcaption>Local setup for Airflow</figcaption></figure><p>for more refer to the <a href="https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html"><strong>documentation</strong></a><strong>.</strong></p><h3>Connecting Airflow to Google Cloud Platform</h3><ul><li>Now, this is the exciting part, <br>first things first, you will have to choose a way to authenticate with the GCP from your Airflow to be able to execute all the tasks.</li></ul><h4>Step 1 — Creating Service Account Key</h4><ul><li>There are mainly 2 ways to do it using <strong>credentials </strong>or using a <strong>service account key. </strong>you can use either key file path or key as JSON, <a href="https://airflow.apache.org/docs/apache-airflow-providers-google/stable/connections/gcp.html"><strong>more</strong></a>.</li><li>We will be using the <strong>service key file JSON</strong> (but you can use the <strong>service key file path </strong>and store it, remember to add a volume in the docker so it could be found on the container).</li><li>Let&#39;s, create our Service Account key,<br> select your project from the dropdown and go to <strong>GCP console&gt; IAM &amp; Admin &gt; Service Accounts</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*fc9D9BVTO6vkT4uqiGZFCQ.png" /><figcaption>Service Accounts on GCP</figcaption></figure><ul><li>Now create a new <strong>service account</strong> or click on your <strong>existing one</strong> ( it must have required permissions to perform the operations), click on <strong>manage keys </strong>by clicking 3 dots on the right side.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0Gi4q_LThZgRfqgEpD0cA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*CxCBADiH858skSmBIhZhNw.png" /></figure><ul><li>create a new key and store</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYasrYs3utNygOtrRuY8wg.png" /></figure><ul><li>Choose type as JSON and create, the key file will be downloaded to your machine as JSON.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWNCq2z1wp3yslDgf4YtPA.png" /></figure><ul><li>that&#39;s it, now its time to create a connection in Airflow.</li></ul><h4>Step 2— Creating GCP Connection in Airflow</h4><ul><li>If we would have been using <strong>GCP Cloud composer</strong>, connections are already configured for us by default. <a href="https://cloud.google.com/composer/docs/how-to/managing/connections"><strong>more</strong></a></li><li>Here we will have to create those manually, so let&#39;s create one.</li><li>Go to <strong>Admin&gt;Connections&gt;Add </strong>in Airflow UI</li><li>Add your GCP Project Name and Copy JSON from Key file and paste inside <strong>KeyFile Json</strong> field ( remember when you will open this connection for edit next time you will see nothing but its still stored securely in Airflow).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmK2e3fCo411TG0FPc4aNg.png" /><figcaption>Creating Google Cloud Connection in Airflow</figcaption></figure><blockquote>Note — Here <strong>Conn Id </strong>is ‘google_cloud_default’, as this is <strong>default connection name</strong> for GCP, if we choose to have another, we will need to pass <strong>connection_id</strong> in operators.</blockquote><h4>Step 3— Running DAGS using Dataproc Cluster</h4><ul><li>Now, let&#39;s create a sample dag that connects to GCP and runs word count program.</li></ul><p>please find the DAG <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/composer/workflows/hadoop_tutorial.py"><strong>here</strong></a></p><ul><li>Upload file to <strong>dags/ </strong>folder on Airflow ( if you are using the local setup you can just put that to <strong>dags/ </strong>inside<strong> docker-local/</strong></li><li>Now, let&#39;s enable to dag and run it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYD86mwKZK7nMuQoNAiSvw.png" /></figure><ul><li>After some time, we should be able to see that it gets completed without any error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqUTeZaKPfwwsXlzmYruYQ.png" /></figure><ul><li>That&#39;s it, you have configured your Airflow to work with <strong>Google Cloud platform.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b2e77b0e3ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/working-on-on-prem-external-airflow-with-google-cloud-platform-gcp-5b2e77b0e3ba">Working on On-prem/External Airflow with Google Cloud Platform(GCP)</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with JSON ( JSONL)& multiline JSON in Apache Spark]]></title>
            <link>https://medium.com/codebrace/working-with-json-jsonl-multiline-json-in-apache-spark-42b524a4724?source=rss----1d3a3d56651---4</link>
            <guid isPermaLink="false">https://medium.com/p/42b524a4724</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-spark-tutorial]]></category>
            <category><![CDATA[json-lines]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Ashish Patel]]></dc:creator>
            <pubDate>Sun, 10 Jan 2021 09:38:56 GMT</pubDate>
            <atom:updated>2024-10-12T07:01:11.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working with JSON ( JSONL) &amp; multiline JSON in Apache Spark</h3><p>Few days back I was trying to work with <strong>Multiline JSONs (aka. JSON ) </strong>on <strong>Spark 2.1 </strong>and I faced a very peculiar issue while working on<strong> Single Line JSON</strong>(aka. JSONL or JSON Lines ) vs <strong>Multiline JSON</strong> files.</p><h3>JSON Lines vs JSON</h3><p>Consider an example, our JSON looks like below<br>here we can see we have 3 rows and all rows are enclosed inside an JSON array.</p><figure><img alt="JSON" src="https://cdn-images-1.medium.com/max/790/1*5FAo-J_BXpNTUyAeQjdckg.png" /></figure><p>Now if we compare same data to be represented as JSON Lines, it would look something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*sGrxA5yNycMF_C5kL6Yxzw.png" /></figure><p>So, the difference clearly includes <strong>absence </strong>of following in JSONL file</p><ul><li><strong>Square brackets</strong> representing array, so in JSONL files every lines is represented by a Record and delimited by New line.</li><li><strong>Commas, </strong>JSONL files do not require comma after every record.</li></ul><h3>Reading JSON &amp; JSONL files</h3><ul><li>By default Spark considers JSON files to be having <strong>JSON lines</strong> (JSONL format) and not Multiline JSON.</li><li>There is a difference when it comes to working with JSON files for<strong> Spark versions prior to 2.2</strong> and after <strong>Spark 2.2 release</strong>.</li></ul><h4><strong>Working with Single Line Records prior Apache Spark 2.2</strong></h4><ul><li>when working with JSON files ( both JSONL and JSON), if <strong>whole record is present in single line</strong>, then we can simply read it using</li></ul><blockquote><strong>spark.read.json(&lt;path&gt;)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mAA3MaLjtkac6d2eHeadQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__LJzCIQv71_QJxQctGTQw.png" /><figcaption>Json file having everything in single line ( minified JSON)</figcaption></figure><ul><li>when we read this data we will get results as expected in form of dataframe</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXLfV3o-BchLroR6XA1mag.png" /><figcaption>Reading JSON or JSONL files using Spark &lt; 2.2</figcaption></figure><h4>Working with Multi Line Records prior Apache Spark 2.2</h4><ul><li>if we have data in multiple lines as below,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*kk0p6NAECLDGard4DAXaQg.png" /><figcaption>Multiline Json Data</figcaption></figure><ul><li>if we try to simply read it we will get <strong>currupt_records</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boSe1Yc5fjUm4CYXRDB60A.png" /><figcaption>reading Multiline Json via read.json with Spark &lt; 2.2</figcaption></figure><h4>Solution</h4><ul><li>to be able to read multiline JSON records prior to Spark 2.2, we will have to use <strong>sc.wholeTextFiles() </strong>, which will give us <strong>RDD </strong>which we can convert to <strong>DataFrame</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b2fhViw5FdewrIdJsLFpQ.png" /></figure><h4>Working with Multi Line Records post Apache Spark 2.2</h4><ul><li>with Apache Spark 2.2+, it becomes very easy to work with Multiline JSON files, we just need to add option</li></ul><blockquote><em>multiline=’</em><strong><em>true</em></strong><em>’</em></blockquote><ul><li>suppose we have following data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*SSVDNhHMRVjfl6ZUKkOraA.png" /></figure><ul><li>now we can simply read it using spark.read.json() with option <strong>multiline=’true’</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*BtgRPpdjmS442hsmaDi2yQ.png" /><figcaption>reading multiline JSON files post Apache Spark 2.2</figcaption></figure><p>Thanks for reading, Please comment any queries or corrections.</p><p>#happy_coding #codebrace</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b524a4724" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codebrace/working-with-json-jsonl-multiline-json-in-apache-spark-42b524a4724">Working with JSON ( JSONL)&amp; multiline JSON in Apache Spark</a> was originally published in <a href="https://medium.com/codebrace">Codebrace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>