<?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 shihab uddin on Medium]]></title>
        <description><![CDATA[Stories by shihab uddin on Medium]]></description>
        <link>https://medium.com/@shihab-buet-cse07?source=rss-3e80046fb6f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zg7Lkkf1N4hYXJJi</url>
            <title>Stories by shihab uddin on Medium</title>
            <link>https://medium.com/@shihab-buet-cse07?source=rss-3e80046fb6f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:47:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shihab-buet-cse07/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[A Journey From Data Engineer to Staff Data Engineer at Pathao]]></title>
            <link>https://shihab-buet-cse07.medium.com/a-journey-from-data-engineer-to-staff-data-engineer-at-pathao-4b848648362e?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b848648362e</guid>
            <category><![CDATA[pathao]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Wed, 31 May 2023 12:27:39 GMT</pubDate>
            <atom:updated>2023-06-01T03:14:43.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*-P4sQH38dvRqUE0dq5wEiQ.png" /></figure><p>Back in 2017, when Pathao was growing really fast, they felt the necessity of organised data. A bunch of data guys were onboarded and formed the data engineering team at Pathao. I had the opportunity to be part of the team and started the wonderful journey. The blog is outlined to show how we have built data oriented decision making culture, data infrastructure and brief introduction of some exciting data driven systems that are making impact of day to day users life.</p><h3>Data Warehouse</h3><p>From Account to Data Science team, Marketing to Ops team everyone needs data. Transactional database was the only source to meet the need. For analytics purposes, our first priority was to build a centralized data storage system so that all the dependent team can avail data from a single source and keep the application database untouched as much as possible. To serve the purpose, we built our own configuration based ETL tool powered by Apache Spark that will pull data from one source like Mysql/Postgres to another source like GCS/Bigquery. Using the framework, we had the opportunity to implement a customized batch ETL pipeline that runs on the Dataproc cluster. Still we’re using the framework to pull data from hundreds of tables and push it to GCS and Bigquery on different time intervals. We are using Bigquery as Data warehouse(DW) as it’s google managed, serverless and can hold petabytes of data. The DW has made it easier to build its own data model based on the business requirement. We are using DBT to build a data pipeline for internal reporting and machine learning (ML) on top of DW. Currently we’ve moved from the Dataproc cluster to a containerised system to minimize GCP cost.</p><p>After building a central data storage system, the question first come how the users/clients of the data product will get access to it and visualise the datà. We chose Redash as base visualizing tool, made some changes for our use case and integrated our own ACL system. After integrating the ACL system, we can now grant access to individuals in granularity of BQ table(s)</p><h3>Event Service Bus (ESB)</h3><p>From app login to logout, users generate different types of events. For example, when users login to his/her account, we consider the interaction as an event (applogin). Similarly order creation, order completion are also events that are generated based on the user interaction. The events can be generated externally based on user interaction with the app or internally from different micro services. We needed to build a system where the events would be passed through the service bus and the end consumer/ processor(s) of the events would make decisions or implement logic based on it. That means a managed, auto scaled messaging system in which different micro services can push event data to the system and subscribers of the event can consume it. We chose Google pub/sub as the core messaging system.</p><p>The system (ESB) is not as simple as it looks. There is a high throughput micro service as an abstraction layer in front of pub/sub. The service consumes millions of events per minute from different services and dispatches the events to pub/sub topics. To pull the data easily from pub/sub, we have implemented libraries for different languages like Golang, Python, JavaScript and PHP. The Consumer system just needs to integrate the library to pull data to its system.</p><p>To persist the event data in our data lake as well as Bigquery, we implemented a managed, auto scaled, unified streaming process using Apache beam in Java. The streaming process runs on top of Google Dataflow that helps to auto scale/down the process horizontally. The window size of the streaming process varies from one event type to another event type. Currently different services are pushing about 300 types of events through ESB.</p><h3>Advanced Allocation System</h3><p>Advanced allocation system or A2 is the first intelligent data driven allocation engine that was written about five years ago and still it is woking fine. Before A2, the allocation system was scattered and the system would search best candidate against an order in a native way. So we wanted to move from native allocation system to data driven managed system powered by machine learning models.</p><p>The core objective of A2 is to find the best candidate for an order that will decrease cancellation rate, increase completion rate and prevent fraud activity. We had to keep in mind that user satisfaction is met, under performed drivers get enough opportunity to improve. We built a model that will optimize the metrics and provide better experience to the customer. We deployed different models at a time and wanted to see which perform better though our own AB Testing framework. The new system showed significance improvement comparing to the old system. Batch and realtime data pipeline generate user features that is fed to model. Interestingly, we’ve replaced direct database call by rest API using GraphQL to fetch user features data.</p><h3>Migration from Google Map to In house Map:</h3><p>Map is one of the most key component for any ride sharing company. For a fare estimation request from point A to point B, two important parameters need to be calculated:</p><ol><li>Estimated distance</li><li>Estimated time of Arrival (ETA)</li></ol><p>The two parameters play an important role to calculate fare for an order. Some internal micro services also need to know the two values for better user experience. Initially Pathao was heavily depended on Google map service specifically on routing api to determine the distance and ETA. As Google map became costly, we had no other option rather than moving to another map service. Then we decided to build our own map service.</p><p>Multiple teams were involved in the project. Firstly we had to explore which one might be the best candidate to start with. We chose open street map(OSM) as base map service. Then we did some analysis task to find how much business will be impacted if we replace Google map with the open street map. We had to keep in mind the following three important challenges:</p><ol><li>How route will be fixed on regular interval</li><li>Point of interest(POI) ingestion</li><li>Traffic</li></ol><p>We took the risk to replace Google map service with our own map service. We made some changes to the open street map(OSM) for Bangladesh, Nepal geo regions and hosted in our own platform. Parallelly we built system to fix route and ingest POI data. We are collecting the data from different sources and integrating with our map.</p><p>When user writes an address or location name on search bar, backend system needs to know its corresponding geolocation to proceed further execution. Geocoding means converting a text to geolocation and vice versa for reverse geocoding. From the beginning, Pathao is using its own geocoding and reverse geocoding api. POI ingestion is playing an important role to enrich backend dataset and searching more relevant. Currently we’ve deployed new version of the API that is providing more relevant result with less amount of interaction.</p><p>ETA from point A to point B is a million dollar question. It impacts on fare calculation as well as user experience. Finding ETA of a road segment in near realtime seems most challenging project under Map epic. Good thing is that, we’ve built a system that generate traffic data from driver’s movement on the road and feeding the traffic data in near realtime. We’ve rolled out the system only Dhaka car plus users, but we’ve plan for 100% roll out.</p><p>Those are not the only projects or systems that we deal with. There are many more exciting projects that are making impact on thousand of users around you.</p><h3>Conclusion</h3><p>It has been 5+ years since I’ve been a part of Data engineering team at Pathao. My journey has not ended yet and wish to make it longer. It has been great opportunity to work with the talented team.</p><p>If you are keen to deal with terabytes of data, thousand of requests per second and eventually making an impact on thousand of users in Bangladesh as well as Nepal, Data engineering Team should be in the top priority. I’ve a plan to write about Pathao work culture, techstack and why Pathao should be #1 choice for your career growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b848648362e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Multithreaded TCP server from scratch]]></title>
            <link>https://shihab-buet-cse07.medium.com/a-multithreaded-tcp-server-from-scratch-334c045928f7?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/334c045928f7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 06:05:17 GMT</pubDate>
            <atom:updated>2023-04-28T06:05:17.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*zby1KC745z7HJz0z7b-B6Q.png" /></figure><p>When we dial a number to talk with someone, a connection is established between the two users through mobile network. When we login to Facebook from any client like web browser or app, a connection is establish with the facebook web server. There are several popular standard communication protocol to make connection between client and server:</p><ol><li>TCP =&gt; Connection oriented, reliable communication protocol</li><li>UDP =&gt; Message oriented communication protocol</li><li>FTP =&gt; File transfer protocol between client and server</li><li>SMTP =&gt; Electronic mail transfer protocol</li></ol><p>In this story, we will see how to create a simple multithreaded tcp server using golang. The concept is same, anyone can choose his/her preferred language to implement.</p><h3>A simple TCP server</h3><p>Golang has provided called net which has provided network interface to build tcp server.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net&quot;<br>)<br><br>func process(cnn net.Conn)  {<br> defer cnn.Close()<br> buf := make([]byte, 1023)<br> _, err := cnn.Read(buf)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> cnn.Write([]byte(&quot;HTTP/1.1 200 OK \r\n\r\nHello world\r\n&quot;))<br>}<br><br><br>func main() {<br> log.Printf(&quot;Hello World&quot;)<br> listener, err := net.Listen(&quot;tcp&quot;, &quot;:2001&quot;)<br> if err != nil {<br>  log.Fatalln(err)<br> }<br><br> for {<br>  cnn, err := listener.Accept()<br>  if err != nil {<br>   log.Fatalln(err)<br>  }<br><br>  process(cnn)<br> }<br><br>}</pre><p>This is a simple tcp server that is running on port 2001. When a connection is established with a client the server send back hello world message to the client and then wait for another connection. From the codebase, it’s clear that the tcp server is single threaded, that means it can not handle multiple connections at a time. let’s make it multithread.</p><h3>Multithreaded TCP server</h3><p>The above single threaded tcp server can be made multithreaded by simple making the process method call multithreaded. That means, when a thread execute the process method, another thread wait for new connection to establish.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net&quot;<br>)<br><br>func process(cnn net.Conn)  {<br> defer cnn.Close()<br> buf := make([]byte, 1023)<br> _, err := cnn.Read(buf)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> cnn.Write([]byte(&quot;HTTP/1.1 200 OK \r\n\r\nHello world\r\n&quot;))<br>}<br><br><br>func main() {<br> log.Printf(&quot;Hello World&quot;)<br> listener, err := net.Listen(&quot;tcp&quot;, &quot;:2001&quot;)<br> if err != nil {<br>  log.Fatalln(err)<br> }<br><br> for {<br>  cnn, err := listener.Accept()<br>  if err != nil {<br>   log.Fatalln(err)<br>  }<br><br>  go process(cnn)<br> }<br><br>}</pre><p>Now the tcp server can accept multiple connection simultaneously.</p><p>This is the basic demonstration to build a multithreaded TCP server from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=334c045928f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking interface in Golang Unit testing]]></title>
            <link>https://shihab-buet-cse07.medium.com/mocking-interface-in-golang-unit-testing-1fc2088955ac?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc2088955ac</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 08:19:07 GMT</pubDate>
            <atom:updated>2022-07-13T08:19:07.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eXLqRpXnwKY4WtxKmxKDg.png" /><figcaption>credit: morioh, google</figcaption></figure><p>Frontend or Backend, whatever developers you are, It’s important to write <br>unit test of your code to make sure that each part is working as expected. <br>You might need to deal with mocking some method calls so that external dependencies are resolved with custom/own data. Coding layout or method implementation to be decorated in such way that, the unit of task can be tested easily. The blog will illustrate how interface can be mocked or substituted with own implementation and the benefit of using interface to access other layer.</p><h4>A Simple Layout</h4><p>Often we need to fetch data from database table and return to the client. Before sending the fetched result, it might be needed to do some modifications or implement logics based on business requirements. The responsibilities are distributed among layers. IO operations to database are implements in data access object (DAO) layer. On the other hand business logic are implemented in service layer. Service Layer communicates with DAO layer through interface. This is the common layout of coding to access data from database and serve the business/client requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*t_QseqhQPSH7_hT-4arukA.png" /><figcaption>service layer &lt;&gt; dao layer</figcaption></figure><p>In nutshell,</p><ol><li>DAO layer is responsible to run IO operation on database</li><li>DAO layer is accessed through Interface.</li><li>Service layer communicate with DAO layer through Interface.</li><li>Business logic are implemented on Service layer.</li></ol><p>Here is some benefits of the layout/design:</p><ol><li>Easily switchable from one database system to other one. No need to touch in service layer.</li><li>Interface implementation can be substituted with own data easily. Mocking of Interface is simple and straightforward.</li></ol><h4>Let’s see an example:</h4><p>In this example, a simple dao layer has been implemented where user information is extracted from database. let’s see the snippet of code to implement it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af2804a8ce404f4a2f0a9cc967191e5a/href">https://medium.com/media/af2804a8ce404f4a2f0a9cc967191e5a/href</a></iframe><p>Here is the dao where IO operation takes place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5000e1be2e897a1c09bf84585d1bb1c3/href">https://medium.com/media/5000e1be2e897a1c09bf84585d1bb1c3/href</a></iframe><p>Here is the service layer where business logics are implemented.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38ad9f04ba0853b87ae266303ea0c56b/href">https://medium.com/media/38ad9f04ba0853b87ae266303ea0c56b/href</a></iframe><p>Now we will see the unit testing ofGetUser method. Before doing the unit testing the dao needs to be mocked or substituted with custom data. Here is the code of mocking and unit testing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89ab97b409db1d39fa4fee13c74e79e2/href">https://medium.com/media/89ab97b409db1d39fa4fee13c74e79e2/href</a></iframe><p>Dao layer’s responsibility can be distributed through multiple interfaces. That means, based on different service new interface will be added in the dao layer and IO operation will be implemented on the interface.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc2088955ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regex 101]]></title>
            <link>https://shihab-buet-cse07.medium.com/regex-101-8660bdf367b1?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8660bdf367b1</guid>
            <category><![CDATA[regular-expressions]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Sun, 09 May 2021 08:46:21 GMT</pubDate>
            <atom:updated>2021-05-09T08:46:21.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*pBcU7-GtBdBDwzqxLTxidg.jpeg" /></figure><p>Regular expression is needed to learn for everyone. Sometimes it looks clumsy or difficult to understand. The story will show some examples of regular expression and it’ll remove the fear of regex. Also it might be a better gateway to enter in the world of regular expression.</p><h3>Some definitions:</h3><p>There are some special characters/symbols that have different meaning to regular expression. First we’ll learn the definition that:</p><ol><li>.(dot) =&gt; Any character except new line</li><li>\w =&gt; Word character. (a-z, A-Z, 0–9, _)</li><li>\W =&gt; Not word character.</li><li>\d =&gt; Digit. (0–9)</li><li>\D =&gt; Not digit.</li><li>\s =&gt; Whitespace. (space, newline, tab)</li><li>\S =&gt; Not whitespace.</li><li>\b =&gt; Word boundary.</li><li>\B =&gt; Not Word boundary</li><li>^ =&gt; Beginning of string</li><li>$ =&gt; End of string</li><li>[] =&gt; Match characters inside bracket. For example: [a-zA-z0–9] defines all capital, smaller letters and digit from 0 to 9.</li><li>[^] =&gt; Match character except character set inside bracket. For example[^a-z] defines all character except smaller letters.</li><li>| =&gt; Or. For example: \d|[A-Z] defines either digits or capital letters.</li><li>() =&gt; Group</li><li>* =&gt; 0 or more.</li><li>+ =&gt; 1 or more</li><li>? =&gt; 0 or one</li><li>{N} =&gt; exact number , where N is a digit.</li><li>{M,N} =&gt; range of number, where M,N define minimum and maximum respectively.</li></ol><h3>Find comment:</h3><p>Write a regular expression to find the “Comments” from the bunch of lines. Comment starts with #(hash) character.</p><p><em># This is a comment<br>#This is also a comment<br>This is not a comment #But it a comment<br>This is not a comment.</em></p><p>Here is the regular expression of the first example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*uTabJKzrF25At7_uEfQoIA.png" /><figcaption>pic: Regex breakdown to find comment</figcaption></figure><h3>Find first name:</h3><p>In the second example, we’ll find first name from the set of lines. First name can be defined as only first character is capital letter at the beginning of line and there will be only english letter in the name. From the following list of names:</p><p><em>Siam hossain<br>siam Hossain<br>siam hossain<br>SiAm hossain</em></p><p><strong>Only the first line has valid first name (Siam)</strong>. Here is regex to find first name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*SzUAEWW2nur_j4dHWLFtXw.png" /><figcaption>Pic: Regex breakdown of first name</figcaption></figure><h3>Find date:</h3><p>Now we’ll find valid date using regular expression. Valid date must be in <strong>yyyy/mm/dd</strong> or <strong>yyyy-mm-dd</strong> format. Here is couple of valid dates:</p><p><em>2020/01/01<br>2020–01–01</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*D91fgrhyJ42YAGOTvTQBcQ.png" /><figcaption>pic: Valid date regex breakdown</figcaption></figure><ul><li>N.B: For simplicity, we didn’t check valid month or day.</li></ul><h3>Find mobile number:</h3><p>In this example we’ll find valid mobile number. Here is some valid mobile numbers:</p><p><em>01914288017<br>+8801914288017<br>01914–288017<br>+8801914–288017</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*3m0_ojhSiFZriDOhzd6JzA.png" /><figcaption>Pic: Regex breakdown to find phone number</figcaption></figure><h3>Find valid email :</h3><p>let’s move on the last and final example. We need to write an regular expression to find valid email address. Here is some valid email address:</p><p><em>shihabuddin@pathao.com<br>shihab.buet.cse07@gmail.com<br>abc-124-xyz@unversity.edu<br>abc-124-xyz@my-company.org</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*IXd_21t0DHA0JdqY9adQ5w.png" /><figcaption>pic: Regex breakdown for email address</figcaption></figure><p>There is no alternative of practicing more and more. Hopefully the blog will help to solve basic requirements regarding regular expression.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8660bdf367b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DBMS table indexing]]></title>
            <link>https://shihab-buet-cse07.medium.com/dbms-table-indexing-eab035c0f6c0?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab035c0f6c0</guid>
            <category><![CDATA[dbms]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 15:51:20 GMT</pubDate>
            <atom:updated>2021-04-18T05:34:12.960Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose there is a Student table in a database, and you need to fetch information frequently from the table using id as filtering column. The query contains id inside where clause, the data fetching will be faster due to the indexing column. In this blog I’ll discuss the following topic:</p><ol><li>Structure of Disk</li><li>Storing a table data inside Disk</li><li>Querying on non indexing table</li><li>Introducing indexing on the table</li><li>Multi level indexing</li><li>B+ tree (not details, just some idea)</li></ol><p>In nutshell I’ll describe how indexing on a column contributes to make a query faster. Before going to the topic, we need to understand the disk and how data is stored and fetched from an IO operation.</p><h3><strong>Structure of Disk:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*528T4gV2QyzFTLLMrLTpPg.png" /><figcaption><strong>Disk</strong></figcaption></figure><p>The above picture shows the basic structure a disk. A disk consists of tracks, each track is divided into sectors, joining of sector and track create block and each block consists of bits. The disk has 2 tracks, 16 sectors and 32 blocks. To access a block, we need to know both track and sector number. Block are identified by number or address. For readability, I’ve numbered the blocks from 1 to 32. Data is stored in block. When we run any query on DBMS, the DBMS access blocks to serve the result. Accessing less block means making the query faster.</p><h3>Storing table data in Disk:</h3><p>When we insert data into a table, the DBMS pick blocks and store the data on the blocks. I’ll use the following table as example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*r8FXI3BYG_fxlIbz0vVIUg.png" /><figcaption>student table</figcaption></figure><p>For simplicity, let assume that the size of each row and block are equal. Without any indexing, If the table has thousand of rows, it’ll occupy same number of blocks. The following table will occupy 8 blocks (let say 1–8) in the disk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*l6b2sdfyjfIzaVWHIcFt7g.png" /><figcaption>non indexing student table in disk</figcaption></figure><h3>Querying on the non indexing table:</h3><p>Let say, we need to find the student information for id 8, Here is the query:</p><p><em>select * from student where id = 8</em></p><p>As there is no extra intelligence or meta information are stored, the DBMS needs to search from first block to the last block until the result is found. For the above query, DBMS needs to access 8 blocks.</p><h3>Introduce Indexing on the table:</h3><p>As mentioned earlier, making query faster means accessing less amount of blocks to fetch result. Indexing on a table means storing some extra informations so that the DBMS doesn’t need to search all blocks sequentially. Let’s see how it looks after introducing indexing on the table’s id column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*kizvjBK5TgBK9ekHGThG4w.png" /><figcaption>First level indexing</figcaption></figure><p>Due to indexing on the id column, reference or the address of the row and its associated id are stored in some new blocks. As only indexing column value and reference of the record are needed to store, a block can store multiple pairs. Let’s assume that a block can store 3 pairs, so we need more 3 blocks from 11 to 13 to store indexing column information.</p><p>What will happen now if we run the same query. The DBMS will now search from 11th block and after reaching at 13th block, it’ll get know that it needs to go to 8th block to fetch the require row. Now the DBMS needs to scan only 4 block(11th, 12th, 13th, 8th). Thus the performance will be improved due to adding indexing. But remember, the indexing column must be inside the <em>where</em> clause to get the performance improvement.</p><h3>Multi level of indexing :</h3><p>The table may have millions of rows. The DBMS might need thousands of blocks to refers the millions of rows. Thus it’ll require more time to fetch result , if only first level indexing is used. Querying on the millions of rows can be made faster by introducing multi level indexing. Multi level indexing means indexing on indexing. Let see how it looks like if we introduce multi level (2nd level) indexing on the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*X1IIIymMN40s-twWHWDDWw.png" /><figcaption>Multi level indexing</figcaption></figure><p>What will happen now when when we run same query now. The DBMS search in block 10 and get to know that it needs to go into block 13. From block 13, the DBMS will know that the row value for id=8 is stored on block no 8. Thus it’ll fetch the information. Here DBMS needs to scan 3 blocks. The indexing on indexing or multi level indexing looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*XjYGgU37nFFdrGiLfnSypA.png" /><figcaption>Multilevel indexing in tree format</figcaption></figure><h3>B+ tree:</h3><p>When number of rows increase, the DBMS increases the level of indexing. On the other hand, the level of indexing decreases based on the deletion of rows. DBMS takes care of those addition and deduction. B+ tree algorithm is used to maintain the indexing. That means when a row is inserted or deleted, the B+ tree is changed. In this blog, I’ll not cover how B+ tree is constructed based on a table data changes. But I recommend to learn about the algorithm. It will give a clear picture about the DBMS table indexing system.</p><h3>Conclusion:</h3><p>Hopefully the blog will help to understand how indexing plays an important role to improve query performance. Thanks to Mr Abdul Bari for decent and clear explanation. I would recommend to watch the <a href="https://www.youtube.com/watch?v=aZjYr87r1b8&amp;t=2131s">video</a> , it’ll also provide clear picture about B+ tree algorithm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab035c0f6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Spark Application in Intellij]]></title>
            <link>https://shihab-buet-cse07.medium.com/first-spark-application-in-intellij-87b0468bcbe0?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/87b0468bcbe0</guid>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 09:15:26 GMT</pubDate>
            <atom:updated>2021-04-03T09:15:26.591Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s important to understand the IDEA you are using. It’ll save your time and make development faster. In this blog, we’ll learn how to open a new Spark application using Intellij Idea. Before starting, i assume that you’ve already installed Intellij Idea with JDK version 7+ and also integrated MAVEN build tool with the Idea.</p><p>The blog will illustrate the following topics step by step:</p><ol><li>How to install Scala plugin</li><li>Create a simple Maven project</li><li>How to integrate Scala SDK</li><li>A simple Spark Application</li></ol><h3>Scala plugin:</h3><p>It’s possible to write Spark application using Java, Scala, and Python languages but i prefer to write in Scala. So first we need to install Scala plugin with the Idea. Plugin is a component, after integrating it with the Idea it will provide more functionalities. Scala plugin provides coding assistance, testing support etc. let’s see how to install the Scala plugin. If you already know how to install plugin, you can skip the section. But you must need to install the plugin if it’s not installed before.</p><p>When you first launch you Idea, you’ll see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHVj2Dyt4Rjy-89wV2e3iQ.png" /></figure><p>At the bottom of the left, go to <strong>Configure-&gt;Plugins</strong> and you’ll see the available plugins in the marketplace. Now Search for the desired Scala plugin and install it. The installed plugin will be activated after restarting the Idea.</p><h3><strong>Create Maven Project:</strong></h3><p>Creating Maven project in Intellij is easy and simple. You just go to the <strong>`New Project -&gt; maven` </strong>direction, you’ll see the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4e1CbKbPPrGFYfayqYbjQ.png" /></figure><p>You can create maven projects in two ways, creating from archetype and without archetype. If you create from archetype, you’ll get a template but you need to find out the right archetype for your use case. You may need to install new archetype but that is a different story, we’ll not discuss about that. We’ll create maven project without archetype. So go to the next page, fill up the box and click on <strong>finish</strong> button. Here is sample one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDhQ7qrsTz_dWfaCJFy7hQ.png" /></figure><p>When the project creation is finish, you’ll see the following project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsZJatMDHQg7UC8r5bqYyQ.png" /></figure><h3>Integrate Scala SDK:</h3><p>If you remember, we installed Scala plugin that assist to code in Scala but does not provide the libraries or components of Scala. So we need to install and integrate Scala SDK. Just left click on the project and go to the the Add new framework support page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSq2VCXtcSN88zdcDJ_g4Q.png" /></figure><p>Then it’ll show the available SDK/framework installed before and also the SDK/framework you can install globally. Select <strong>Scala</strong> option and install Scala <strong>2.12.X</strong> version, because till now Spark support for maximum Scala 2.12.x version . Once the SDK is installed, you can use any of your project you want. Now you’ll see the SDK inside <strong>External libraries </strong>folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Oik697tfi1pDzUIadMiKZg.png" /></figure><p>We also created folder <strong>scala </strong>inside <strong>main</strong> folder and marked the <strong>scala </strong>folder as root. All the scala code will be inside the <strong>scala</strong> directory.</p><h3><strong>Some examples using Spark</strong></h3><p>Till now, we’ve created a simple maven project and integrated Scala SDK with the project. Scala plugin will assist to code in Scala.</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>        &lt;artifactId&gt;spark-core_2.12&lt;/artifactId&gt;<br>        &lt;version&gt;3.1.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>        &lt;artifactId&gt;spark-sql_2.12&lt;/artifactId&gt;<br>        &lt;version&gt;3.1.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>To access apache spark, we need to add the about maven dependencies in <strong>pom.xml. </strong>it’ll facilitate basic functionalities using the Apache Spark. <strong><em>Make Sure that you’ve 2.12.X Scala SDK integrated.</em></strong></p><p>Create package sample package <strong><em>com.su.so.spark and </em></strong><em>create</em><strong><em> main </em></strong>method inside an object type Scala class. As a sample example we will read a simple CSV file and show the content. Here is the code:</p><pre>package com.su.so.spark<br><br>import org.apache.spark.sql.SparkSession<br><br>object HelloSpark {<br>  def main(args: Array[String]): Unit = {<br>    val spark: SparkSession = SparkSession<br>      .<em>builder</em>()<br>      .appName(&quot;reading logs&quot;)<br>      .master(&quot;local&quot;)<br>      .getOrCreate()<br><br>    val dataFrame = spark.read.csv(&quot;csv_file_path&quot;)<br>    dataFrame.show()<br>  }<br>}</pre><p>The objective of the story is not to dig deep into Spark rather than just to show how beginner can start to learn Spark using Scala in Intellij.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87b0468bcbe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between YYYY and yyyy in date format]]></title>
            <link>https://shihab-buet-cse07.medium.com/difference-between-yyyy-and-yyyy-in-date-format-be5a827603c?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5a827603c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dateformatter]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 16:40:10 GMT</pubDate>
            <atom:updated>2020-01-01T16:40:10.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you were in Christmas vacation and come back in the new year with fresh energy. But when you were checking out everything, you found that some pipelines or processes output date has come to one year ahead for the last few days of the last year although it’s working fine in the current year. Isn’t it making confusion ? Yes , that happened to me this year. I wrote a streaming process using apache beam in java that usually dump output in date and hour partitioned path in gcs like <strong><em>gs:///&lt;gcs_path&gt;/d=&lt;date&gt;/hour=&lt;hour&gt;/ </em></strong>format<em>.</em> It had been running fine throughout the year except for the last three days of the last year. For the last three days the process dumped output in 2020–12–29,2020–12–30,2020–12–31 date partition respectively. Later I found out that i made mistake in the date format and figured out that there is a subtle difference between the meaning of “<strong>YYYY</strong>” and “<strong>yyyy</strong>” in the date format.</p><p>Let see an example which convert timestamp to date:</p><pre><strong>public static void </strong>main(String[] args) {<br>    <strong>long </strong>[]timestamps = {1577586396000L,1577672796000L, 1577759196000L};<br>    <strong>for </strong>(<strong>long </strong>t : timestamps) {<br>        String f1 = <strong>&quot;YYYY-MM-dd&quot;</strong>;<br>        String d1 = <em>getDate</em>(t,f1);<br>        String f2 = <strong>&quot;yyyy-MM-dd&quot;</strong>;<br>        String d2 = <em>getDate</em>(t,f2);<br>        System.<strong><em>out</em></strong>.println(String.<em>format</em>(<strong>&quot;Timestamp:%s,Format1:%s,Date1:%s,Format2:%s,Date2:%s&quot;</strong>,t,f1,d1,f2,d2));<br>    }<br>}<br><br><strong>private static </strong>String getDate(<strong>long </strong>timestamp, String format) {<br>    SimpleDateFormat sdf = <strong>new </strong>SimpleDateFormat(format);<br>    <strong>return </strong>sdf.format(<strong>new </strong>Date(timestamp));<br>}</pre><p>I’ve taken three timestamps from last three days of year 2019 respectively and the above programme gives the following output:</p><pre>Timestamp:1577586396000,Format1:YYYY-MM-dd,Date1:2020–12–29,Format2:yyyy-MM-dd,Date2:2019–12–29<br>Timestamp:1577672796000,Format1:YYYY-MM-dd,Date1:2020–12–30,Format2:yyyy-MM-dd,Date2:2019–12–30<br>Timestamp:1577759196000,Format1:YYYY-MM-dd,Date1:2020–12–31,Format2:yyyy-MM-dd,Date2:2019–12–31</pre><p>Let’s come to the explanation of why the output looks like that. The “yyyy” represents the calendar year of the date while the “YYYY” represents the year of the week. For example, Calendar year of date 2019–12–29 is 2019 on the other hand the date is Sunday, the first day and first week of the year 2020. For the date, year of the week will be 2020. Hence yyyy and YYYY are representing different years for the same date or timestamp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5a827603c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python unit test using unittest]]></title>
            <link>https://shihab-buet-cse07.medium.com/python-unit-test-using-unittest-30cfcba3d24f?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/30cfcba3d24f</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Fri, 02 Aug 2019 06:22:58 GMT</pubDate>
            <atom:updated>2019-08-02T09:08:08.094Z</atom:updated>
            <content:encoded><![CDATA[<p>When you wrote your first “Hello world” program, you checked if the program showed right output. When you add a new feature, you run the application and check whether the new feature is working or not. Those are the manual process to test your application working. We’ve no argument on that application must be well tested. You don’t want to be embarrassed after deploying your application in production. You don’t want to break up other code block for doing some changes or adding new features in your application.</p><p>It’s important to write test cases to make sure that the application is mature enough to give the right output. Writing unit test makes sure that every block of codes is providing expected output and thus it’s certifying that overall implementation is on track. To test your Python application, there are several modules or libraries that help to write unit test easily with great features.</p><p>In this story I will discuss on a popular python built in unit testing module named “unittest”, provided that “unittest” is not the only one python library to write unit test.The story can be divided into two pieces :</p><ol><li>Introduction to unittest library</li><li>Some examples of using unittest</li></ol><h4><strong>Unit test VS Integration test:</strong></h4><p>Suppose you’ve bought a car and you want to check the Headlight of the car. You’ve turned on the switched and expecting that the light will be turned on. If light is on, that means the Headlight of the car is working. But if it doesn’t , it is very difficult to find out why the light is not working. There are several parts for example bulb, switch, battery or might be any other parts that are responsible for making light turned off or on. Now you have to test each part to find out which parts are responsible for wrong output. Testing the Headlight is similar to integration test and checking each part is similar to unit test.</p><p>In nutshell, Unit test can be defined as a type of testing in which each individual units of code (methods) are tested. On the other hand the integration testing check if the different blocks of code are working together.</p><h4><strong>What and Why unittest:</strong></h4><p>Unittest is a framework written to construct and execute testing of the python application. It has been built into Python standard library since version 2.1. We can write unit tests without using any library or framework but it has some drawbacks.Suppose we’ve a module named “<strong>math.py” </strong>which contains couple of methods</p><pre>def sum(a,b):<br>   return a+b<br>def subtract(a,b):<br>   return a - b</pre><p>We will write test cases for “math.py” module to test <strong>sum</strong> and <strong>subtract</strong></p><pre>from math import sum,subtract<br>def test_sum():<br>   assert sum(1,2) == 1<br>   assert sum(1.1, 2.1) == 4.3<br>def test_subtract():<br>   assert subtract(1,1) == 0<br>   assert subtract(2,1) == 1<br>if __name__ == &#39;__main__&#39;:<br>   test_sum()<br>   test_subtract()</pre><p>If we run the test cases, it’ll throw Assertion exception as 3 is not equal to 1 (first assertion in test_sum).There are some pitfalls:</p><ol><li>Program exit if any assertion fails</li><li>Not all assertion is checked.</li><li>Not all method is executed</li></ol><p>Unittest module offers useful features to solve all the issues and there are other strong capability that make possible to write unit test easily.</p><h4><strong>First test using unittest:</strong></h4><p>After adding two more methods in math.py module, it looks like:</p><pre>def sum(a,b):<br>   return a + b</pre><pre>def subtract(a,b):<br>   return a - b</pre><pre>def mul(a,b):<br>   return a*b</pre><pre>def divide(a,b):<br>   return a/b</pre><p>We’ve to write code to test the functionality of each method. Some notes to keep in mind before using unittest:</p><ol><li>Test code must be within a class.</li><li>The class must extends/inherits “ <strong>TestCase</strong>” class of unittest module</li><li>Inside the class, put your test code in methods</li><li>Inside method, use “<strong>assertion</strong>” method from TestCase class.</li><li>Call “<strong>main</strong>” method of unittest module to start the testing</li></ol><p>So the code to test each and every functionality of math.py module looks like:</p><pre>import unittest<br>import math</pre><pre>class TestMath(unittest.TestCase):<br>   def test_sum(self):<br>       self.assertEqual(math.sum(1,2),3)<br>       self.assertEqual(math.sum(1.1, 2.3), 3.4)</pre><pre>   def test_subtract(self):<br>       self.assertEqual(math.subtract(10, 2), 8)<br>       self.assertEqual(math.subtract(-3, 2), -5)</pre><pre>   def test_mul(self):<br>       self.assertEqual(math.mul(2,3),6)<br>       self.assertEqual(math.mul(-1,-2),2)</pre><pre>   def test_divide(self):<br>       self.assertEqual(math.divide(10, 2), 5)<br>       self.assertEqual(math.divide(3, 2), 1.5)</pre><pre>if __name__ == &#39;__main__&#39;:<br>   unittest.main()</pre><h4><strong>Test exception:</strong></h4><p>If we look at “division” method carefully, we’ll see that we’ve not thrown any exception if the denominator equals zero in divide method. So the test case should be written in such a way that the mistake is caught while running the test code. We’ll modify the division method and its corresponding test code so that an exception is raised and tested. Now the divide method looks like :</p><pre>def divide(a,b):<br>    if b == 0:<br>         raise ValueError(&quot;Denominator can not be zero&quot;)<br>    return a/b</pre><p>And the divide method test code looks like:</p><pre>def test_divide(self):<br>   self.assertEqual(math.divide(10, 2), 5)<br>   self.assertEqual(math.divide(3, 2), 1.5)<br>   self.assertRaises(ValueError,math.divide,12,0)<br>  # Or it can be written using context manager<br>   with self.assertRaises(ValueError):<br>       math.divide(12,0)</pre><p>TestCase class has <strong>assertRaise</strong> method that take expected exception, method to call and its arguments to test whether the exception is raised or not.</p><h4><strong>Avoid repeated scenario:</strong></h4><p>While writing test cases there are some scenarios you may come across.</p><ol><li>Doing some tasks at the beginning of testing (i.e : initializing client or connection)</li><li>Doing some tasks at the end of testing (i.e: closing connection)</li><li>Doing some tasks at the beginning of each test case (i.e : initializing some objects)</li><li>Doing some tasks at the end of each test case (reset some objects)</li></ol><p>Unittest module has provided some methods to solve the use cases. You’ve to just override the methods and implement what you need to do. Here is the name of the methods to do that:</p><ol><li><strong>setUpClass</strong>: The class method is called only once at the beginning of the whole test life cycle.</li><li><strong>tearDownClass</strong>: The class method is called only once at the end of the whole test life cycle.</li><li><strong>setUp</strong>: The method is called once at the beginning of each test case.</li><li><strong>tearDown</strong>: The method is called once at the end of each test case.</li></ol><p>Let’s look at an example. We have a <strong>student.py</strong> module which has <strong>Student</strong> class. Here is the code:</p><pre>class Student(object):<br>   def __init__(self, std_id, dept, subject, marks):<br>       self.std_id = std_id<br>       self.dept = dept<br>       self.subject = subject<br>       self.marks = marks<br>       self.grade = self._get_grade(marks)<br>       self.review = self._get_review(self.grade)</pre><pre>   def _get_grade(self, marks):<br>       if marks &gt;= 80:<br>           return &quot;A+&quot;<br>       elif marks &gt;=70 and marks &lt; 80:<br>           return &quot;A&quot;<br>       elif marks &gt;= 60 and marks &lt; 69:<br>           return &quot;A-&quot;<br>       elif marks &gt;= 50 and marks &lt; 60:<br>           return &quot;B&quot;<br>       elif marks &gt;= 40 and marks &lt; 50:<br>           return &quot;C&quot;<br>       elif marks &gt;= 33 and marks &lt; 40:<br>           return &quot;D&quot;<br>       else :<br>           return &quot;F&quot;</pre><pre>   def _get_review(self, grade):<br>       if grade == &quot;A+&quot; or grade == &quot;A&quot;:<br>           return &quot;VERY GOOD&quot;<br>       elif grade == &quot;A-&quot; or grade == &quot;B&quot;:<br>           return &quot;GOOD&quot;<br>       elif grade == &quot;C&quot; or grade == &quot;D&quot;:<br>           return &quot;BAD&quot;<br>       else:<br>           return &quot;VERY BAD&quot;</pre><p>We have to write test cases to check if grade and review is correctly initialized inside student object.</p><pre>import unittest<br>from student import Student</pre><pre>class TestStudent(unittest.TestCase):</pre><pre>   @classmethod<br>   def setUpClass(cls):<br>       print(&quot;Only once at beginning in whole test life cycle&quot;)</pre><pre>   def setUp(self):<br>       print(&quot;setUp at beginning of test case&quot;)<br>       self.student1 = Student(1,&quot;Rahul&quot;, &quot;Math&quot;, 80)<br>       self.student2 = Student(2,&quot;Hasib&quot;, &quot;Physics&quot;, 65)</pre><pre>   def test_grade(self):<br>       print(&quot;testing grade&quot;)<br>       self.assertEqual(self.student1.grade,&quot;A+&quot;)<br>       self.assertEqual(self.student2.grade, &quot;A-&quot;)</pre><pre>   def test_review(self):<br>       print(&quot;testing review&quot;)<br>       self.assertEqual(self.student1.review, &quot;VERY GOOD&quot;)<br>       self.assertEqual(self.student2.review, &quot;GOOD&quot;)</pre><pre>   def tearDown(self):<br>       print(&quot;tearDown at ending of test case&quot;)</pre><pre>   @classmethod<br>   def tearDownClass(cls):<br>       print(&quot;Only once at end in whole test life cycle&quot;)</pre><pre>if __name__ == &#39;__main__&#39;:<br>   unittest.main()</pre><h4><strong>Avoid outside effect by mocking:</strong></h4><p>The methods we write in our projects should be less affected by the outside call. It makes easy to write unit test properly. Sometimes we need to fetch data from different databases or request to a url. Those calls might affect our test cases. So the best way to avoid the effect is to mock the outside calls.</p><p>Let’s assume that we need to add new feature that will fetch previous review of a student by requesting to a url. Here is the addition of code in <strong>student.py </strong>module:</p><pre>import requests<br>def get_previous_review(self, year):<br>   response = requests.get(f&#39;http://school.com/{self.dept}/{year}/{self.std_id}/review&#39;)<br>   if response.ok:<br>       return response.text<br>   else :<br>       return &quot;Not available&quot;</pre><p>Now we have to write test cases for the new feature. Here <strong>requests.get </strong>is doing an outside call. So we will mock the calling. So the test code to check the feature looks like:</p><pre><strong>from </strong>unittest.mock <strong>import </strong>patch<br>def test_previous_review(self):<br>   print(&quot;testing previous review&quot;)<br>   year = datetime.date.today().year - 1<br>   url1 = f&#39;http://school.com/{self.student1.dept}/{year}/{self.student1.std_id}/review&#39;<br>   url2 = f&#39;http://school.com/{self.student2.dept}/{year}/{self.student2.std_id}/review&#39;</pre><pre>with patch(&#39;student.requests.get&#39;) as mock:<br>       mock.return_value.ok = True<br>       mock.return_value.text = &quot;GOOD&quot;<br>       review = self.student1.get_previous_review(year)<br>       mock.assert_called_with(url1)<br>       self.assertEqual(review, &quot;GOOD&quot;)<br>       mock.return_value.ok = False<br>       review = self.student2.get_previous_review(year)<br>       mock.assert_called_with(url2)<br>       self.assertEqual(review, &quot;Not available&quot;)</pre><p><strong>patch </strong>method inside <strong>unittest.mock </strong>module provides mocking feature of unit test. In the above example we’ve mocked requests.get of student.py module and inside test method we’ve set some return values before calling the target method(“<strong>get_previous_review</strong>”). We’ve checked if the mocked method has got correct arguments and eventually the calling method or target method has returned correct value.</p><p>In this story i’ve provided some basics features of unittest module and hopefully it’ll help to write unit test cases using unittest. Special thanks to <a href="https://www.youtube.com/watch?v=6tNS--WetLI">Corey Schafer</a> and <a href="https://realpython.com/python-testing/">realpython.com</a> for simple and details explanation on unittest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30cfcba3d24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Google Cloud Storage effectively]]></title>
            <link>https://shihab-buet-cse07.medium.com/how-to-use-google-cloud-storage-effectively-cc232b787057?source=rss-3e80046fb6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc232b787057</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-storage]]></category>
            <dc:creator><![CDATA[shihab uddin]]></dc:creator>
            <pubDate>Sat, 19 Jan 2019 06:28:06 GMT</pubDate>
            <atom:updated>2019-01-20T13:00:56.520Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Google Cloud Storage</strong> or GCS is an infrastructure as service provided by google cloud platform (GCP) to enable storing and accessing unstructured data in files. The storage and operational cost of GCS is very low and sometimes we don’t consider so much about it. If GCS is used in right way, you can save money and get better performance. I’ve compiled some important informations that should be known before using GCS.</p><h4>Creating GCS bucket:</h4><p>Bucket is the root container to store objects and object is the piece of data that has been uploaded in bucket (i.e <strong>/user/name/file.txt</strong>). GCS asks some mandatory inputs before creating a bucket. For example, it asks:</p><ol><li>Bucket name</li><li>Storage class</li><li>Location</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqnzMKDsAOidGKTXB-_aPw.png" /><figcaption>Creating bucket</figcaption></figure><p>In this article I’ve also explained the guidelines to provide the information before creating a bucket.</p><h3><strong>Naming convention of bucket:</strong></h3><p>As all GCS buckets reside in a single google cloud storage namespace, the bucket name must be unique globally. The bucket as well as object name should not contain personal identifiable information (PII) for safety reason.<br>For more information go through <a href="https://cloud.google.com/storage/docs/best-practices#naming">bucket naming</a>.</p><h3><strong>Choose appropriate storage class:</strong></h3><p>GCS offers 4 types of storage class. Based on use case and accessibility it’s important to choose appropriate storage class to get better performance with optimal cost. Here is the comparison between storage classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZsNbhWf-cuXiAKDeBMCuQ.png" /><figcaption>Storage classes comparision</figcaption></figure><p><em>*The cost is shown for US multi-region</em><br> For data backup and storing historical data, Nearline or Coldline is the best option as the data will be accessed hardly. On the other hand for real time streaming or accessing data frequently, Multi-regional or Regional class is the best option. If it’s confusing to choose a class, Regional is the safe option.</p><h3><strong>Choose appropriate location:</strong></h3><p>Choosing appropriate bucket location depends on the location of consumer and data source. To get optimize latency, better network bandwidth consumer, data source, bucket should be in same location. As Multi-regional storage class offers data geo-redundancy feature, data is copied in multiple geographical regions. So consumer, data source, bucket should be in same multi-regional location (us/asia/eu/eur4/nam4) if storage class is selected as Multi-regional.</p><h3><strong>Set versioning on bucket :</strong></h3><p>Versioning to bucket must be enabled to ensure data recovery if any object is removed accidently. GCS has provided simple way to manage versioning of object using <strong>gsutil</strong> command. Here is some examples:</p><pre>#see whether versioning enabled or not<em><br></em>gsutil versioning get gs://&lt;BUCKET_NAME&gt;<em><br></em>#enable versioning<em><br></em>gsutil versioning set on gs://&lt;BUCKET_NAME&gt;<br>#check versioned object<br>gsutil ls -a gs://&lt;BUCKET_NAME&gt;/&lt;PATH&gt;<br>#recover an object from archived object<br>gsutil cp gs://&lt;GS_PATH&gt;/&lt;SOURCE_OBJECT_NAME‌&gt;#&lt;GENERATION_NUMBER&gt;          gs://‌&lt;GS_PATH&gt;/&lt;DESTINATION_OBJECT_NAME&gt;</pre><p>Put your value on &lt;&gt; when you run the command. Extra cost will be added if versioning is enabled on the bucket.</p><h3><strong>Avoid sequential filenames:</strong></h3><p>GCS maintains a lexicographical ordered index of object keys for each bucket. The index is updated when<strong> </strong>an object is written to or deleted from the bucket. If files with sequential names such as timestamp-based file names are uploaded in the bucket, same backend server will likely to handle the file upload requests and it’ll affect the throughput.</p><h3><strong>Ramp up traffic gradually:</strong></h3><p>Initially buckets have an IO capacity around 1000 write requests per second and 5000 read requests per second. GCS has the ability to redistribute the load across more servers when it detects that the load is approaching to the IO limit. But it takes an order of minutes to detect and redistribute the load. So if the request rate on the bucket increase faster than GCS can perform its redistribution, your application that is generating the request rate will face higher latency and more error rate for the time being.</p><p>Also if you want to remove irrelevant data automatically after each fixed interval of time, you’ve to set retention policy in the bucket. Access policy to bucket should be maintained carefully so that no data is lost accidentally. In this short article For more details , go through <a href="https://cloud.google.com/storage/docs/best-practices">best practices</a> of using GCS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc232b787057" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>