<?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 Wandrys Nascimento on Medium]]></title>
        <description><![CDATA[Stories by Wandrys Nascimento on Medium]]></description>
        <link>https://medium.com/@wandrys.sousa?source=rss-4689528c2957------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CgGZA5bNkhX23HuiMwuhgg.jpeg</url>
            <title>Stories by Wandrys Nascimento on Medium</title>
            <link>https://medium.com/@wandrys.sousa?source=rss-4689528c2957------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:34:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wandrys.sousa/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[The Python programming language is being integrated into Excel]]></title>
            <link>https://medium.com/@wandrys.sousa/the-python-programming-language-is-being-integrated-into-excel-fb12c8607cde?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb12c8607cde</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 18:33:07 GMT</pubDate>
            <atom:updated>2023-10-09T18:38:19.424Z</atom:updated>
            <content:encoded><![CDATA[<p>The Python programming language is a versatile, open-source, object-oriented programming language that has grown in popularity in recent years. Excel is software developed by Microsoft for processing, analyzing and visualizing data in spreadsheets. So how do these two different tools come together and what are the benefits? In this article, we’ll try to answer the question of how the Python programming language is integrated with Excel.</p><p>Microsoft Excel can be a very powerful and versatile tool if you know how to use it. Of the Word — PowerPoint — Excel trio of applications, Excel is probably the most powerful. It’s easy to use for storing data, but you can do all sorts of things with it if you want to. Some people have even made games. But now these options have increased exponentially with the integration of Python.</p><p>Microsoft has introduced a Python Editor as an experimental add-on to Excel Labs that offers users the ability to write and edit Python formulas directly in Microsoft Excel and should be used with the new Python function support announced in August. Python Editor provides a dedicated code editor that shares similarities with Python notebook environments, designed to enhance the Python experience in Excel by accommodating more complex and longer Python code snippets. In other words, it offers an experience closer to what a typical IDE offers, but without leaving Excel.</p><p>The main benefits of the Python Editor include a simplified code execution view that displays Python cells in execution order along with their respective outputs, aiding debugging and code understanding. Python cells are executed on the main line, so this is extremely useful. In addition, the Python Editor offers greater flexibility, allowing you to create and edit longer sections of Python code. Taking advantage of the components included in Visual Studio Code, IntelliSense makes coding smoother by supporting important features such as automatic suggestions, formatting and highlighting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TdSiJk5PEViPkH4ILx95eQ.png" /></figure><p>A standout feature is the flexibility it offers to spaced coding workflows. You can write code, move on to other parts of Excel and add the code to the Excel sheet only when it’s ready. This gives you more control over when the code affects the Excel file.</p><p>To access the Python Editor, you can update the Excel Labs add-in if you already have it installed or install it from the Add-in Store using the Insert tab. However, access to Python in Excel is a prerequisite for using the Python Editor, so you’ll need this before you can start experimenting with the Python Editor.</p><h3>The Python programming language is being integrated into Excel: why, how and when? 🐍📊</h3><h3>Advantages of using the Python programming language and Excel together.</h3><p>There are many advantages to using Python and Excel together. Some of them are:</p><p>- Python allows you to easily perform many operations that you cannot or would have difficulty performing in Excel. For example, with Python you can extract data from the web, build machine learning models, perform text processing or carry out complex mathematical calculations.</p><p>- Python allows you to automate and speed up operations performed in Excel. For example, with Python you can read, edit, filter, merge or create new files in Excel files. This saves time and reduces the risk of errors.</p><p>- Python helps you make data visualized in Excel more impressive and interactive. For example, with Python you can embellish Excel charts, add animations or share them on the web. In this way, you make your data more understandable and interesting.</p><h3>Disadvantages of using the Python programming language and Excel together</h3><p>Using Python and Excel together also has some disadvantages. Some of them are:</p><ul><li>You may need some additional tools for combined use of Python and Excel. For example, to run Python code in Excel, you may need a library like [xlwings] or a plug-in like [PyXLL].</li><li>To use Python and Excel together, you may need to learn the Python programming language. Although Python is an easy language to learn, it may not be suitable for everyone. In addition, you may need to spend time writing and debugging Python code</li><li>Using Python and Excel together can cause security problems. For example, opening or sharing Excel files that contain Python code can infect your computer with malware. It is therefore important to open files from trusted sources and check your security settings.</li></ul><h3>The future of using Python and Excel together</h3><p>The future of using Python and Excel together looks bright. Because both Python and Excel are tools that are constantly being developed and updated. What’s more, there are many libraries, plugins and platforms that facilitate and support the joint use of these tools. For example, thanks to a platform like [Jupyter], you can interactively run and share Python code with Excel files. In this way, using Python and Excel together can become more widespread, efficient and enjoyable.</p><h3>Conclusion</h3><p>The answer to the question of whether the Python programming language is being integrated into Excel is yes. Although this integration has many advantages, it also has some disadvantages. However, these disadvantages are not insurmountable and the future of this integration is bright. So there are plenty of resources, tools and opportunities for anyone who wants to learn and experiment with using Python and Excel together.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb12c8607cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating the p-hacking problem with R]]></title>
            <link>https://medium.com/@wandrys.sousa/simulating-the-p-hacking-problem-with-r-1e6df07cf89b?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e6df07cf89b</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[p-hacking]]></category>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[p-value]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 00:12:12 GMT</pubDate>
            <atom:updated>2023-04-28T00:12:12.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*xa0BhUpZhWCPUHpkHAp50w.jpeg" /></figure><h3>1. Introduction</h3><p>I saw a tweet on twitter saying, “Don’t increase the sample size to later decrease the p-value”.</p><p>Indeed, the p-values are the same due to the final sample size and the data are exactly the same, but what about the p-hacking problem!?</p><p>Even if they say it is unfair, there is one thing I don’t understand. So let’s do a simulation.</p><h3>2. Data Settings</h3><p>Try a t-test of the means of the two groups as the null hypothesis.</p><p>Because of sampling groups with the same mean and variance, the p-values must be evenly distributed and in the same proportion as the alpha level to calculate a significant difference.</p><p>(If the α-level is 5%, even if the same group is in the same group, the proportion will show a significant difference once in 20 times).</p><p>As an experiment, look at the distribution of the p-values of the same group. Follow a mean of 50 and a standard deviation of 5. The sample size is 100. Repeat the test 10,000 times.</p><pre>rm(list = ls())<br>set.seed(12345)<br>record = NULL<br><br>for (i in 1:10000){<br>group1 = rnorm(100,50,5)<br>group2 = rnorm(100,50,5)<br><br>record = append(record,t.test(group1,group2)$p.value[1])  # record p value in record variable<br><br>}<br><br>hist(record)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*H6_Aio50PT_MQ4O2OpfYkw.png" /></figure><p>Almost theoretically, it was evenly distributed. At the 5% significance level, the rejection rate is almost 5%.</p><pre>sum(record &lt;= 0.05) / 10000<br><br>&gt;[1] 0.0528</pre><p>The significant difference rate was almost 5%, which is the same as the α-level.</p><h3>3. P-hacking simulation</h3><p>The p-hacking group has a design sample size of 100, but tests once when the sample size reaches 50. Here, the α-level is set to 5%. If there is no significant difference, the test is performed as planned. The only difference is whether or not to test once. Both have exactly the same data.</p><pre>set.seed(12345)<br><br>record1=NULL<br>record2=NULL<br><br>for( i in 1:10000){<br>group1 = rnorm(100,50,5)<br>group2 = rnorm(100,50,5)<br><br>#Normal group. Test with sample size 100 (as planned).<br>if(t.test(group1,group2)$p.value[1] &lt;= 0.05) {<br>record1 = append(record1,1) <br>}else{record1=append(record1,0)}<br><br><br># p-hacking group. Test once the sample size reaches 50.hack1=group1[1:50]<br>hack2=group2[1:50]<br><br># The p-hacking group is tested as planned if there is no significant difference<br>if(t.test(hack1,hack2)$p.value[1] &lt;= 0.05) {<br>record2 = append(record2,1) <br>}else{<br>  record2 = append(record2,0)<br>  hack1=group1[1:100]<br>  hack2=group2[1:100]<br> <br>    if(t.test(hack1,hack2)$p.value[1] &lt;=0.05) {<br>    record2 = append(record2,1)<br>    }else{record2 = append(record2,0)}<br>}<br>}</pre><p>Let’s compare the number of times a significant difference was found. Since there are 10,000 trials, the expected value for a significant difference is about 500.</p><pre>sum(record1)  #Normal test group<br>sum(record2)  #p-hacking group<br><br>&gt;[1] 528<br>&gt;[1] 857</pre><p>In the normal group, the number of times was almost as expected, but in the p-hacking group, the number was greater than the expected value, making it easier to see a significant difference. In the p-hacking group, the same data was tested only once, but we can see that the difference is more likely to be significant. How did this happen?</p><p>The p-hacking group has the same number of trials, but it seems that the reason is that the number of trials has increased.</p><pre>length(record1)  #normal group<br>length(record2)  #p-hacking group<br><br>&gt;[1] 10000<br>&gt;[1] 19486</pre><p>Now, to make it easier for the p-hacking group to make a significant difference, we will use the same data and run 20 tests in small batches and increase the number of tests.</p><pre>set.seed(12345)<br>record1=NULL<br>record2=NULL<br>end=0<br>for( i in 1:10000){<br>group1 = rnorm(100,50,5)<br>group2 = rnorm(100,50,5)<br><br>#Test the normal group with a sample size of 100 (as planned).<br>if(t.test(group1,group2)$p.value[1] &lt;= 0.05) {<br>record1 = append(record1,1) <br>}else{record1=append(record1,0)}<br><br># The p-hacking group is added by sample size 20 and the test is repeated.<br>hack1=group1[1:20]<br>hack2=group2[1:20]<br><br>if(t.test(hack1,hack2)$p.value[1] &lt;= 0.05) {<br>  record2 = append(record2,1) <br>  }else{<br>  record2 = append(record2,0)<br>  hack1=group1[1:40]<br>  hack2=group2[1:40]<br>  <br>  if(t.test(hack1,hack2)$p.value[1] &lt;=0.05) {<br>  record2 = append(record2,1)<br>    }else{record2 = append(record2,0)<br>     hack1=group1[1:60]<br>     hack2=group2[1:60]<br>     if(t.test(hack1,hack2)$p.value[1] &lt;=0.05) {<br>     record2 = append(record2,1)<br>     }else{record2 = append(record2,0)<br>        hack1=group1[1:80]<br>        hack2=group2[1:80]<br>        if(t.test(hack1,hack2)$p.value[1] &lt;=0.05) {<br>        record2 = append(record2,1)<br>        }else{record2 = append(record2,0)<br>        hack1=group1[1:100]<br>        hack2=group2[1:100]<br>        if(t.test(hack1,hack2)$p.value[1] &lt;=0.05) {<br>        record2 = append(record2,1)<br>        }else{record2 = append(record2,0)<br>        }<br>      } <br>     }<br>    }<br>  }<br><br>}</pre><p>Let’s compare the number of significant differences.</p><pre>sum(record1)  #Normal group<br>sum(record2)  #p-hacking group<br><br>&gt;[1] 528<br>&gt;[1] 1441</pre><p>The p-hacking group was able to use the same intended data to make the difference more likely to be significant.</p><p>As you increase the number of tests in this way, you are more likely to find a significant difference.</p><p>Next, if there is no significant difference in the t-test, try the non-parallel Wilcox test.</p><pre>set.seed(12345)<br><br>record1=NULL<br>record2=NULL<br><br>for( i in 1:10000){<br>group1 = rnorm(100,50,5)<br>group2 = rnorm(100,50,5)<br><br>#Normal group. Test with sample size 100 (as planned).<br>if(t.test(group1,group2)$p.value[1] &lt;= 0.05) {<br>record1 = append(record1,1) <br>}else{record1=append(record1,0)}<br><br><br># For the p-hacking group, perform a t-test or a Wilcox test and select only those cases in which either of the differences are significant <br>if(t.test(group1,group2)$p.value[1] &lt;= 0.05 | wilcox.test(group1,group2)$p.value[1] &lt;= 0.05) {<br>record2 = append(record2,1) <br>}else{record2 = append(record2,0)}<br>  <br>}</pre><p>Now let’s compare.</p><pre>sum(record1)  #Normal group<br>sum(record2)  #p-hacking group<br><br>&gt;[1] 528<br>&gt;[1] 624</pre><p>The p-hacking group was slightly more likely to have a significant difference.</p><p>Finally, the p-hacking group will combine the two methods.</p><pre>set.seed(12345)<br><br>record1=NULL<br>record2=NULL<br><br>for( i in 1:10000){<br>group1 = rnorm(100,50,5)<br>group2 = rnorm(100,50,5)<br><br>#Normal group. Test with sample size 100 (as planned).<br>if(t.test(group1,group2)$p.value[1] &lt;= 0.05) {<br>record1 = append(record1,1) <br>}else{record1=append(record1,0)}<br><br><br>#p-hacikib group. Test once the sample size reaches 50.<br>hack1=group1[1:50]<br>hack2=group2[1:50]<br><br># p-hacking group is tested two ways, and if there is no significant difference, the test is performed as planned<br>if(t.test(hack1,hack2)$p.value[1] &lt;= 0.05 | wilcox.test(group1,group2)$p.value[1] &lt;= 0.05) {<br>record2 = append(record2,1) <br>}else{<br>  record2 = append(record2,0)<br>  hack1=group1[1:100]<br>  hack2=group2[1:100]<br> <br>    if(t.test(hack1,hack2)$p.value[1] &lt;=0.05) {<br>    record2 = append(record2,1)<br>    }else{record2 = append(record2,0)}<br>}<br>}<br><br>sum(record1)  #Normal group<br>sum(record2)  #p-hacking group<br><br>[1] 528<br>[1] 939</pre><p>The p-hacking group was able to further improve the probability of a significant difference, compared to 857 when only the intermediate test was added.</p><p>With that said, if you set the number of tests only once and report that only one of the methods was used from the beginning, you can make it easier to produce a significant difference without anyone finding out. Furthermore, it is expected that the more multiple testing methods are combined, the more likely it is that a significant difference will be produced.</p><p>Thus, the for the reality of p-hacking the test should be repeated. Especially when there is no significant difference by trying a different test method, it is good to test p-hacking.</p><h3>4. Finally</h3><p>Surprisingly, I feel that there are many people who do not know about the problem of p-hacking.</p><p>Be careful when testing.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e6df07cf89b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding classes and object orientation from the creation of RPG characters]]></title>
            <link>https://medium.com/@wandrys.sousa/understanding-classes-and-object-orientation-from-the-creation-of-rpg-characters-aa6bbfb76547?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6bbfb76547</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[rpg]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 12:42:32 GMT</pubDate>
            <atom:updated>2023-04-23T12:43:49.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Initially</h3><p>Hello, I have 3 years of experience in Python. I majored in accounting, mathematics and statistics. Fortunately I was able to get involved with Python, Matlab, R, SAS and Julia, but a super important subject in the day to day life of a programmer, which I learned from a colleague who had more time in IT and already suffered a lot with this, is the understanding of classes and object orientation. Such knowledge that will make a project in Python, R etc. be a success or a real failure. So I am writing again to fill the gap a bit.<br>And this time I will cover classes and object orientation.<br>You may think: “It is too late for this level…”, but I graduated in mathematics and statistics without even knowing about object orientation.<br>But in practice I realized that there is an underlying object orientation, and I decided to summarize it in this article, judging it as a success for business.</p><h3>Purpose of this article</h3><p>1-Get familiar with classes and object orientation through RPG.<br>2- Try to understand from familiar, practical code. Concepts and vocabulary come later.<br>3- Experience RPG battles with created characters and enemies .</p><p>Our goal is to understand Python classes and object orientation through practical, easy-to-view code.<br>Becoming familiar with object-oriented concepts and vocabulary is not easy. I also referred to many articles and videos, but even when presented with examples of animals and cars, I had a hard time imagining what I wanted to do. So this time I will focus on RPGs and try to make you deepen your understanding of object orientation with more familiarity and purpose.</p><h3>Who this article is for</h3><p>1- People who deal with python, but are vague about classes and object orientation.<br>2- A person who has a minimal understanding of the RPG system.<br>3- A person who jumps in and moves forward even if there is something they are not happy with.<br>4- A person who can implement things slowly and step by step, without rushing to conclusions or key points.</p><p>I think that even if you only understand the concepts and conclusions of classes and object orientation, you will be able to understand. In particular, self and __ init __ are easier to understand if you understand the big picture and the flow. So don’t jump to conclusions, but let’s have a solid goal in this article and implement it step by step to deepen our understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*tH4mjTCw-5EyGmDBlz--BA.gif" /></figure><h3>Main story</h3><h3>Chapter 1: Assumptions and Settings.</h3><p>You are a role-playing game developer and are responsible for the roles and character creation. Guts is a warrior, Kanako is a magician, Jitan is a thief… RPGs have different stats and special abilities, depending on your position and character. This is why I think I can like the character I have created. Let’s learn through RPG character makeup.</p><h3>Chapter 2: Try to make a character. class creation</h3><p>Now let’s create a character. Try running this code first.</p><pre>class warrior():<br>  def __init__(self):<br>    print(&quot;I am a warrior!&quot;)<br><br>  def warrior_attack(self):<br>    print(&quot;This is swordsmanship!&quot;)<br><br>  def warrior_deffense(self):<br>    print(&quot;This is the warrior&#39;s defense!&quot;)<br><br>Kevin = warrior()<br># I am a warrior</pre><p>It’s okay if you don’t decipher the code at this stage.<br>What is init? If you start looking at it, it is the key to the result of the first bit of code.<br>What I want you to see is:<br>1- From the warrior class came the warrior character named Kevin.<br>2- At the time it was completed, it was printed out as (“I am a warrior!”), although I did not print it out.</p><p>As an image, the warrior is the title and Kevin is the actual character.<br>It is the RPG’s ironclad “Choose the position ⇒ Name and complete character creation” sign.</p><p>In technical terms, “select position ⇒ name and complete character creation” is called object creation or instantiation .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_CYhS34hmQ5IPfB_juYW6A.gif" /></figure><p>See Chapter 4 for details.</p><p>Let’s test it with this Kevin(object).</p><pre>Kevin.warrior_attack()<br>Kevin.warrior_deffense()</pre><pre># Result<br>This is swordsmanship!<br>This is the warrior&#39;s defense!</pre><p>I’ll go into detail later, but when he used Kevin warrior_attack(), he said, “This is a sword move!” Here, warrior_attack() is a talent<br>that can only be used by warriors created from the warrior class . This is called a special ability for each position (class).</p><p>Example: a warrior’s method is “sword technique”, a magician is “chant”, a thief is “surprise attack”, etc. I am slowly making a RPG character…! Did you get a picture of this?</p><p><em>“Is this really class or object oriented? What’s the point?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*dSJvQxPzYySSYpKm84KUIQ.gif" /></figure><p>I understand the feeling of thinking that.<br>In the past I also tried to focus on the shorter points and only the main ones, but it wasn’t something I could master, so please keep in touch with me a little more.</p><h3>Chapter 3: Delve deeper into the settings and content of character parameters. Mass production of class objects.</h3><p>Character creation has been completed, but there is no RPG without status differences and attack commands. Of course, warriors and mages have their own personalities, such as strength specialization and attack specialization, even among warriors. First, let’s define the basic stats and attack commands.</p><pre>class warrior():<br>  def __init__(self,hp,mp,power,speed):<br>    print(&quot;I am a warrior!&quot;)<br>    self.hp = hp<br>    self.mp = mp<br>    self.power = power<br>    self.speed = speed<br><br>  def attack(self,target):<br>    target.hp = target.hp - self.power  #Subtract your power value from the opponent&#39;s hp as #damage<br><br><br>  def warrior_attack(self,target):<br>    print(&quot;This is the power of a warrior!&quot;)<br>    target.hp = target.hp - self.power*1.5  # Subtract your power*1.5 from the opponent&#39;s hp as damage<br>    self.hp   -= 15                         # Self-inflicted damage<br>Kevin = warrior(200,50,20,20)</pre><p>What you want to see:<br>1- ｢hp,mp,power,speed｣is added to the arguments.<br>2- They are apparently defined in the next section, inside __init__.<br>3- Skills ( methods ) called attack and warrior_attack are defined, and the contents appear to be related to hp and power.</p><p>Details are given in Chapter 4.</p><p>If you attack with RPG, it is normal to have:<br>1- Target<br>2- The higher the attack power, the more damage you can inflict.</p><p>Since you are familiar with the background, you can see the following code without explaining it and it can be understood easily.</p><pre>def attack(self,target): #argument target Specify attack target<br>•   target.hp = target.hp - self.power  #subtract your power from the attacker&#39;s hp as damage<br>• def warrior_attack(self,target):            #argument target Specify attack target<br>•     print(&quot;This is the power of a warrior!&quot;)<br>    target.hp = target.hp - self.power*1.5  # subtract your power*1.5 from the opponent&#39;s hp as damage<br>    self.hp   -= 15  # self-inflicted damage from special moves</pre><p>And you can check the status as below.<br>I think it is better to memorize this by writing it down than by reasoning it out.object.hp (Kevin.hp)</p><pre>print(Kevin.hp)<br>print(Kevin.mp)<br>print(Kevin.power)</pre><p>Once you create a class, you can create a large number of warriors like this one.</p><p>One of the advantages of the class is that once created, the character (object)can be mass produced. Even with the same warrior, if there are individual differences, the depth of the RPG will increase.</p><pre>Kevin  = warrior(200,50,20,20)  # balanced<br>Stan   = warrior(120,60,10,40)  # power speed type<br>Guts   = warrior(600,280,5,120) # Mad warrior<br>Tanaka = warrior(80,20,5,30)    # Hazure</pre><h3>Chapter 4: Confirmation of the logic and vocabulary up to this point. self instantiation and __init__.</h3><p>I think you understood the flow somewhat, so I’ll finally talk about logic here.<br><strong>__init __</strong><br>Initialization that is done automatically when a character (object) is created.<br>The reason why the print(“I’m a warrior!”) process and the status setting are automatically set upon character creation is because these processes are within the scope of __ init __ .<br>The __ init __ range of the class is automatically executed when the character (object) is created.<br><strong>self</strong><br>self is the character, Kevin himself. After creating a character you should be able to see that the arguments match the character’s statistics by replacing the character’s name with all the classes that created the character. The argument is set to the character (object) status as in the init mentioned above .</p><p>Initialization that is done automatically when a character (object) is created.<br>The reason why the print(“I’m a warrior!”) process and the status setting are automatically set upon character creation is because these processes are within the scope of __ init __ .<br>The __ init __ range of the class is automatically executed when the character (object) is created.<br>- self<br>self is the character, Kevin himself. After creating a character you should be able to see that the arguments match the character’s statistics by replacing the character’s name with all the classes that created the character. The argument is set to the character (object) status as in the init mentioned above .</p><ul><li>Character creation from class = object creation/objectification = instantiation<br>They are basically the same, except for the way they are called objectification (instantiation) .<br>This time I created (instantiated) an object named Kevin from a class named warrior .<br>Although it overlaps, it means that I created a character named Kevin from the warrior class (post).<br>- Method<br>A talent for a character created from a class warrior.<br>Warriors use fencing, magicians use magic chants, and priests use miracles.<br>Characters created from the warrior class can use warrior-specific talents. These skills are called methods .</li></ul><p>At this stage I have created only one warrior, so it may be difficult to imagine, but you will understand when you create a large number of classes.</p><h3>Chapter 5: Define and create multiple roles.</h3><p>There is no RPG where the role is only that of a warrior. A magician, a priest, a thief. The real pleasure of an RPG is to examine the roles, so let’s create many roles like this. The stats also added m_pow for magic point.</p><pre>class Wizard():<br>  def __init__(self,hp,mp,power,m_pow,speed):<br>    print(&quot;I am a wizard&quot;)<br>    self.hp = hp<br>    self.mp = mp<br>    self.power = power<br>    self.m_pow = m_pow<br>    self.speed = speed<br><br>  def attack(self,target):<br>    target.hp = target.hp - self.power  # subtract your power value from the opponent&#39;s hp as damage<br><br><br>  def fire(self,target):<br>    print(&quot;Blah blah blah&quot;)<br>    target.hp = target.hp - self.m_pow * 2  # subtract your m_pow * 1.5 from the opponent&#39;s hp as damage<br>    self.mp   -= 6                          # mp consumption by magic attack.<br><br>  <br>class Thief():<br>  def __init__(self,hp,mp,power,m_pow,speed):<br>    print(&quot;Thief has arrived&quot;)<br>    self.hp = hp<br>    self.mp = mp<br>    self.power = power<br>    self.m_pow = m_pow<br>    self.speed = speed<br><br>  def attack(self,target):<br>    target.hp = target.hp - self.power  # subtract your power value from the opponent&#39;s hp as damage<br><br><br>  def fire(self,target):<br>    print(&quot;backstab&quot;)<br>    target.hp = target.hp - self.speed * 1.3  # subtract your power*1.5 from the opponent&#39;s hp as damage<br><br>Kanako = Wizard(60,5,30,70,10)<br>Jitan =  Thief(120,20,10,10,50)</pre><p>Define your favorite position like this and try to create more and more characters. Clerics and magic swordsmen who heal… should be fun.</p><h3>Chapter 6: Unify the common items of the positions (class inheritance)</h3><p>It’s better to have more titles, but if you define many classes… isn’t it hard to write each one? <br>`Each character has the same status and attack items`. What I mean is, don’t you think it would be more refreshing if you omitted the common parts and wrote only the differences (special abilities)?<br>This concept is heritage . It is faster to actually see and feel.</p><pre>#Common items for all characters <br>class Character(): <br>  def __init__(self,hp,mp,power,m_pow,speed):<br>     self.hp = hp<br>     self.mp = mp<br>     self.m_pow = m_pow<br>     self.speed = speed<br>  <br>  def attack(self,target):<br>    target.hp = target.hp - self.hp<br><br>  <br>class Warrior(Character): <br>  def warrior_attack(self,target):<br>    target.hp = target.hp - self.power *1.5<br>    self.hp -= 15<br><br>class Wizard(Character): <br>  def fire(self,target):<br>    print(&quot;Blah blah blah&quot;)<br>    target.hp = target.hp - self.m_pow * 2<br>    self.mp   -= 6<br><br>class Thief(Character):<br>  def fire(self,target):<br>    print(&quot;backstab&quot;)<br>    target.hp = target.hp - self.speed * 1.3</pre><p>Don’t you think it is very clean? Compared to code that does not inherit, it is less expensive, isn’t it?</p><h3>Summary</h3><p>This is the general flow. Here are the three things you learned through RPG this time.<br>1- Generating (instantiating) an object from a class and its merits<br>2- Role of __init__ and self<br>3- Heritage</p><p>Finally, I have updated what we have learned so far, more like an RPG, and have reproduced<br>specifically the part where the character does damage to the enemy .<br>If you understand the .self and f strings you learned this time, you should be able to figure it out. <br>Please try running it.</p><pre>class Character(): <br>    def __init__(self,hp,mp,power,m_pow,speed):<br>        self.hp = hp<br>        self.mp = mp<br>        self.power = power<br>        self.m_pow = m_pow<br>        self.speed = speed<br>  <br>    def attack(self,target):<br>        target.hp = target.hp - self.hp<br><br>class Warrior(Character): <br>    def warrior_attack(self,target):<br>        print(&quot;This is a sword technique&quot;)<br>        damage = self.power * 2<br>        target.hp = target.hp - damage<br>        self.hp -= 15<br>        print(f&quot;Damage of{damage}&quot;)<br>        print(f&quot;Enemy HP remaining: {target.hp}&quot;)<br><br>class Wizard(Character): <br>    def fire(self,target):<br>        print(&quot;blah blah blah&quot;)<br>        damage = self.m_pow * 1.3<br>        target.hp = target.hp - damage<br>        self.mp   -= 6<br>        print(f&quot;{damage} damage&quot;)<br>        print(f&quot;Enemy HP remaining:{target.hp}&quot;)<br><br>class Thief(Character):<br>    def Stelth_attack(self,target):<br>        print(&quot;blah blah blah&quot;)<br>        damage = self.speed * 1.3<br>        target.hp = target.hp - damage<br>        print(f&quot;{damage} damage&quot;)<br>        print(f&quot;Enemy HP remaining: {target.hp}&quot;)<br><br>class Enemy(Character):<br>    def Breath(self,target):<br>        damage = self.power + 50<br>        target.hp = target.hp - damage<br>        print(f&quot;{damage} damage&quot;)<br><br>Kevin = Warrior(60,5,30,70,10)<br>Kanako = Wizard(60,5,30,70,10)<br>Jitan =  Thief(120,20,10,10,50)<br>Dragon = Enemy(400,0,40,0,10)<br><br>#Kevin attacks enemy<br>Kevin.warrior_attack(Dragon)<br>print(&quot;------------------------&quot;)<br># Kanako attacks enemy<br>Kanako.fire(Dragon)<br>print(&quot;------------------------&quot;)<br># Zitan attacks enemy<br>Jitan.Stelth_attack(Dragon)</pre><p>Result:</p><pre>This is a sword technique<br>Damage of 60<br>Enemy HP remaining: 340<br>------------------------<br>blah blah blah<br>91.0 damage<br>Enemy HP remaining:249.0<br>------------------------<br>blah blah blah<br>65.0 damage<br>Enemy HP remaining: 184.0</pre><h3>Next time</h3><p>Now that we have created a character and exchanged simple attacks, next time we will use the for and while statements to actually fight! Also, I will continue to correct as soon as I notice missing explanations of typos and omissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*_IJ1qSVxUfIja72cOlZFIw.gif" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6bbfb76547" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Python x PDF] PyPDF2 is old! Use pypdf when working with PDF in Python]]></title>
            <link>https://medium.com/@wandrys.sousa/python-x-pdf-pypdf2-is-old-use-pypdf-when-working-with-pdf-in-python-7b32f4664bb4?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b32f4664bb4</guid>
            <category><![CDATA[pypdf2]]></category>
            <category><![CDATA[pypdf]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[extraction]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 23:28:24 GMT</pubDate>
            <atom:updated>2023-04-23T09:26:06.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Or0ARQyZLOUsuApd-IytoQ.gif" /></figure><h3>Introduction</h3><p>When I thought about dealing with PDF using Python, PyPDF2 there were just articles I was investigating various things, but when I looked at the official PyPDF2 website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*bZDYy5T5WNOuSkBRFUaRPw.jpeg" /></figure><p><a href="https://pypi.org/project/PyPDF2/">PyPDF2</a></p><p>is what it reads.</p><p>Since the pypdf official says he will continue the development of pypdf, I will summarize how to use it this time.</p><p><a href="https://pypi.org/project/pypdf/">pypdf</a></p><p>The release date ↓ is also very recent (April 16, 2023), so it seems that development is actively taking place.</p><p>In fact, if you look at the release history, you can see that it has been updated frequently since Christmas Eve last year.</p><p>So from now on, I recommend using pypdf instead of PyPDF2.</p><p>Let’s take a look at how to use pypdf!</p><h3>Ambient setting</h3><p>Install com pip instalar pypdf</p><pre>pip install pypdf</pre><h3><strong>Try using the pdf module</strong></h3><p><a href="https://pypdf.readthedocs.io/en/stable/">Welcome to pypdf - pypdf 3.8.0 documentation</a></p><p>Use the pdf METHODOLOGICAL AND STATISTICAL APPENDIX (<a href="https://www.imf.org/-/media/Files/Publications/fiscal-monitor/2023/April/English/msa.ashx">https://www.imf.org/-/media/Files/Publications/fiscal-monitor/2023/April/English/msa.ashx</a>) as a reference to summarize how to use each module.</p><p>I will use the PDF of the IMF’s Methodological and Statistical Annex</p><p>Save as msa.pdf</p><h3>1. Read text</h3><p>Try to read the text in the PDF.</p><p>When loading, use the module named pypdf.PdfReader</p><pre># Import libraries<br>from pypdf import PdfReader<br><br># Import PDF files<br>reader = PdfReader(&quot;msa.pdf&quot;)<br><br># Get number of pages<br>number_of_pages = len(reader.pages)<br><br># Get pages. In this case, get the first page.<br>page = reader.pages[0]<br><br># Extract text<br>text = page.extract_text()<br>print(text)</pre><p>Results:</p><pre>This appendix comprises four sections. “Data and <br>Conventions” describes the data and conventions <br>used to calculate economy group composites. “Fiscal <br>Policy Assumptions” summarizes the country-specific <br>assumptions underlying the estimates and projections <br>for 2023–28. “Definition and Coverage of Fiscal Data” <br>summarizes the classification of countries in the various <br>groups presented in the Fiscal Monitor and details the <br>coverage and accounting practices underlying each <br>country’s Fiscal Monitor data. Statistical tables on key <br>fiscal variables complete the appendix. Data in these <br>tables have been compiled on the basis of information <br>available through April 3, 2023.<br>Data and Conventions <br>Country-specific data and projections for key fiscal <br>variables are based on the April 2023 World Economic <br>Outlook database, unless indicated otherwise, and <br>compiled by IMF staff. Historical data and projections <br>are based on the information IMF country desk <br>officers gather in the context of their missions and <br>through their ongoing analysis of the evolving situation <br>in each country; data are updated continually as more <br>information becomes available. Structural breaks in <br>data may be adjusted to produce smooth series through <br>splicing and other techniques. IMF staff estimates serve <br>as proxies when complete information is unavailable. <br>As a result, Fiscal Monitor data may differ from official <br>data in other sources, including the IMF’s International <br>Financial Statistics and the Government Finance <br>Statistics Manual (GFSM 2014).<br>Sources for fiscal data and projections not covered <br>by the World Economic Outlook database are listed in <br>the respective tables and figures.<br>Country classification in the Fiscal Monitor divides <br>the world into three major groups: 41 advanced <br>economies, 95 emerging market and middle-income <br>economies, and 59 low-income developing countries. <br>Fiscal Monitor tables display 37 advanced economies, <br>39 emerging market and middle-income economies, <br>and 40 low-income developing countries. The <br>countries in the tables generally represent the largest <br>countries within each group based on the size of their GDP in current US dollars. Data for the full list of <br>economies can be found at https://www.imf.org/<br>external/datamapper/datasets/FM. The seven largest <br>advanced economies as measured by GDP (Canada, <br>France, Germany, Italy, Japan, the United Kingdom, <br>and the United States) constitute the subgroup of <br>major advanced economies, often referred to as the <br>Group of Seven (G7). The members of the euro area <br>are also distinguished as a subgroup. Composite data <br>shown in the tables for the euro area cover the current <br>members for all years, even though membership has <br>increased over time. Data for most European Union <br>(EU) member countries have been revised following <br>their adoption of the updated European System <br>of National and Regional Accounts (ESA 2010). <br>Low-income developing countries are countries that <br>have per capita income levels below a certain threshold <br>(set at $2,700, as of 2016, as measured by the World <br>Bank Atlas method), structural features consistent with <br>limited development and structural transformation, <br>and external financial relationships insufficiently open <br>for the countries to be considered emerging market <br>economies. Emerging market and middle-income <br>economies include those not classified as advanced <br>economies or low-income developing countries. <br>See Table A, Economy Groupings, for more details. <br>Most fiscal data for advanced economies refer to <br>the general government, whereas data for emerging <br>market and developing economies often refer to only <br>the central government or the budgetary central <br>government (for specific details, see Tables B–D). All <br>fiscal data refer to calendar years, except in the cases of <br>The Bahamas, Bangladesh, Barbados, Bhutan, Botswana, <br>Dominica, Egypt, Eswatini, Ethiopia, Fiji, Haiti, <br>Hong Kong Special Administrative Region, India, the <br>Islamic Republic of Iran, Jamaica, Lesotho, Malawi, <br>the Marshall Islands, Mauritius, Micronesia, Myanmar, <br>Namibia, Nauru, Nepal, Pakistan, Palau, Puerto Rico, <br>Rwanda, Samoa, Singapore, St. Lucia, Thailand, Tonga, <br>and T rinidad and Tobago, for which they refer to the <br>fiscal year. For economies whose fiscal years end before <br>June 30, data are recorded in the previous calendar <br>year. For economies whose fiscal years end on or after <br>June 30, data are recorded in the current calendar year.METHODOLOGICAL AND STATISTICAL APPENDIX<br>55 International Monetary Fund | April 2023</pre><p>Looking at the PDF, you can see that the text written on the first page can be obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*pDrx5ZRTFiutH6tt1FfXKw.jpeg" /></figure><h3>2. Combining PDFs</h3><p>When combining, use the module called pypdf.PdfMerger.</p><p>For this we will download the PDF FOREWORD (<a href="https://www.imf.org/-/media/Files/Publications/fiscal-monitor/2023/April/English/foreword.ashx">https://www.imf.org/-/media/Files/Publications/fiscal-monitor/2023/April/English/foreword.ashx</a>)</p><p>Save the second PDF as foreword.pdf and try to merge it with msa.pdf.</p><pre># Split PDF<br>from pypdf import PdfWriter<br><br>merger = PdfWriter()<br><br>for pdf in [&quot;msa.pdf&quot;, &quot;foreword.pdf&quot;]:<br>    merger.append(pdf)<br><br>merger.write(&quot;merged-pdf.pdf&quot;)<br>merger.close()</pre><p>Now you have joined the pdf but with the pdf foreword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*WAcOhoD5WtuNCkaaUbvpMA.gif" /></figure><h3>3. Split PDF</h3><p>Split a multi-page PDF.</p><p>It uses a combination of read and write functions.</p><pre># Import libraries<br>from pypdf import PdfReader, PdfWriter<br><br># Import PDF<br>reader = PdfReader(&quot;msa.pdf &quot;)<br>sourcepage = reader.pages[0]<br><br># Create object for writing<br>writer = PdfWriter()<br><br># Extract the 0th element (1st page PDF)<br>pdf = reader.pages[0]<br><br># Add to object for writing<br>writer.add_page(pdf)<br><br># Write to file<br>with open(&quot;msa_p1.pdf &quot;, &quot;wb&quot;) as fp:<br>    writer.write(fp)<br><br></pre><p>By doing this, I was able to split msa.pdf and save only the first page (msa_p1.pdf).</p><h3>4. Image loading</h3><p>I am trying to read an image in a PDF. To do this let’s first save the pdf The External Balance Assessment Methodology: 2018 Update ( <a href="https://www.imf.org/-/media/Files/Publications/WP/2019/WPIEA2019065.ashx)">https://www.imf.org/-/media/Files/Publications/WP/2019/WPIEA2019065.ashx)</a></p><p>If all goes well the pdf will be saved as WPIEA2019065.pdf</p><p>Now let’s get to the code!</p><pre># import modules <br>import os<br>from pypdf import PdfReader<br>from PIL import Image<br># Import PDF <br>#Please change the directory path <br>reader = PdfReader(r&quot;C:\xxxxxxx\PyPDF\WPIEA2019065.pdf&quot;)<br># Get pages. In this case, get the first page! [0Image113.png]. <br>page = reader.pages[0]<br>count = 0<br># Rotate the for statement by the number of images in the page <br>for image_file_object in page.images:<br>    # Create a new png file<br>    #Please change the directory path<br>    with open(os.path.join(r&quot; C:\xxxxxxx\PyPDF&quot;, str(count) + image_file_object.name + &quot;.png&quot;), &quot;wb&quot;) as fp:<br>        # Write out the image<br>        fp.write(image_file_object.data)<br>        count += 1<br>        # Open the saved image file and save it as PNG<br>        img = Image.open(fp.name)</pre><p>I was able to get an image like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMetv9eBR45A8pItBDfVTA.png" /></figure><p>Page 1 of WPIEA2019065.pdf:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*4v-KkkkODKyK56bhsHzL_Q.jpeg" /></figure><p>If you compare the two, you will see that the image on the first page can be acquired.</p><h3><strong>At last</strong></h3><p>Summary of how to use pypdf.</p><p>Please read the official page below for more details!</p><p><a href="https://pypi.org/project/pypdf/">https://pypi.org/project/pypdf/</a></p><p>Thanks for reading this far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*gV1Kr4VincpTjzeo0Httig.gif" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b32f4664bb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating DockerImage and version control when uploading to DockerHub]]></title>
            <link>https://medium.com/@wandrys.sousa/the-procedure-for-creating-dockerimage-and-the-procedure-for-version-control-when-uploading-to-7e1f632edacd?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1f632edacd</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[dockerhub]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 15:52:48 GMT</pubDate>
            <atom:updated>2023-04-22T16:43:31.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QQk-kwU6qwPlIkR_rzxrYQ.gif" /></figure><p>Hello.</p><p>In this article, I will write a memo on how to customize DockerImage and how to submit the customized DockerImage to DockerHub for version control.</p><p><strong>Django Image on DockerHub</strong></p><p>In the past, I deployed a Django container as a docker network test in my environment, and the command I got at that point is as follows:</p><pre>root@docker:~# docker run -itd --name django-con --net my-dk-br django:latest<br>Unable to find image &#39;django:latest&#39; locally<br>latest: Pulling from library/django<br>75a822cd7888: Pull complete<br>e4665cede9d1: Pull complete<br>202a45aa091c: Pull complete<br>7799136eb561: Pull complete<br>7a7f9ca3fd40: Pull complete<br>412f2d081014: Pull complete<br>Digest: sha256:5bfd3f442952463f5bc97188b7f43cfcd6c2f631a017ee2a6fca3cb8992501e8<br>Status: Downloaded newer image for django:latest<br>4fd58c1ecdd0354b55c9a71e0f1d2face81843555f127f005a0b4fe07af979dc</pre><p>When running this command, if there is a django image locally, it will be used, but if not, it will automatically go to DockerHub to get the image.</p><p>In my pattern this time, I didn’t have it locally, so I extracted the image from DockerHub, but the image I extracted at that point is probably as follows:</p><p><a href="https://hub.docker.com/_/django">https://hub.docker.com/_/django</a></p><p>Upon closer inspection, it appears that the last time it was updated was 6 years ago and it doesn’t appear to have been updated since.</p><p>Upon closer inspection, it appears that the last time it was updated was 6 years ago and it doesn’t appear to have been updated since.</p><p>Perhaps this is why the Django version is 1.● units. . . !</p><p>Here is the result of inserting the deployed container and printing the installed library version with the pip list.</p><p>Not only Django, but other things were a bit old, so I decided not to use this image and build my own from scratch.</p><pre>root@890ed06d9e04:/# pip list<br>DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.<br>Django (1.10.4)<br>mysqlclient (1.3.9)<br>pip (9.0.1)<br>psycopg2 (2.6.2)<br>setuptools (20.10.1)<br>You are using pip version 9.0.1, however version 23.1 is available.<br>You should consider upgrading via the &#39;pip install --upgrade pip&#39; command.</pre><p><strong>Create a Docker image</strong></p><p>Originally, it would be better to use a Dockerfile to code the image, but I don’t want to learn, so I’ll do it manually this time. As we go into the container we will gradually add the missing items, and when it takes shape to some extent, we will respond by turning the container into an image.</p><p>The DockerImage based on this time is ubuntu 22.04.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VxJdgmnFj_spMBdjbD17Q.png" /></figure><p><a href="https://hub.docker.com/_/ubuntu">https://hub.docker.com/_/ubuntu</a></p><p>First, extract this image locally.</p><pre>root@docker:~# docker pull ubuntu:22.04<br>22.04: Pulling from library/ubuntu<br>Digest: sha256:67211c14fa74f070d27cc59d69a7fa9aeff8e28ea118ef3babc295a0428a6d21<br>Status: Downloaded newer image for ubuntu:22.04<br>docker.io/library/ubuntu:22.04<br><br>root@docker:~# docker image ls<br>REPOSITORY               TAG       IMAGE ID       CREATED         SIZE<br>portainer/portainer-ce   latest    f031e549070f   3 days ago      273MB<br>redis                    latest    eca1379fe8b5   4 days ago      117MB<br>nextcloud                latest    964325ce9b95   7 days ago      1e+03MB<br>nginx                    latest    6efc10a0510f   9 days ago      142MB<br>postgres                 latest    ceccf204404e   9 days ago      379MB<br>httpd                    latest    4b7fc736cb48   9 days ago      145MB<br>mysql                    latest    412b8cc72e4a   2 weeks ago     531MB<br>alpine                   latest    9ed4aefc74f6   3 weeks ago     7.05MB<br>ubuntu                   22.04     08d22c0ceb15   6 weeks ago     77.8MB<br>ubuntu                   latest    08d22c0ceb15   6 weeks ago     77.8MB<br>centos                   centos7   eeb6ee3f44bd   19 months ago   204MB<br>django                   latest    eb40dcf64078   6 years ago     436MB</pre><p>Deploy a container based on the extracted image. Insert the deployed container and check the operating system version. The following is the result, but it looks like there is no problem with ubuntu 22.04.</p><pre>root@docker:~# docker run -itd --name my-django ubuntu:22.04<br>882373b6681d3a406cb8d94d1c555e162fac8219c8fc542f33418d652c12d973<br>root@docker:~# docker exec -it my-django /bin/bash<br>root@882373b6681d:/# cat /etc/os-release<br>PRETTY_NAME=&quot;Ubuntu 22.04.2 LTS&quot;<br>NAME=&quot;Ubuntu&quot;<br>VERSION_ID=&quot;22.04&quot;<br>VERSION=&quot;22.04.2 LTS (Jammy Jellyfish)&quot;<br>VERSION_CODENAME=jammy<br>ID=ubuntu<br>ID_LIKE=debian<br>HOME_URL=&quot;https://www.ubuntu.com/&quot;<br>SUPPORT_URL=&quot;https://help.ubuntu.com/&quot;<br>BUG_REPORT_URL=&quot;https://bugs.launchpad.net/ubuntu/&quot;<br>PRIVACY_POLICY_URL=&quot;https://www.ubuntu.com/legal/terms-and-policies/privacy-policy&quot;<br>UBUNTU_CODENAME=jammy<br>root@882373b6681d:/# python --version<br>bash: python: command not found</pre><p><strong>Install python, pip and Django.</strong></p><p>I used the following as a reference:</p><p>This document summarizes how to install the Python environment on Ubuntu 22.04.</p><p>*2023/03/20 I wrote this on Ubuntu 20.04, but checked it on Ubuntu 22.04.</p><p>Since the version of Python may differ depending on the project, install multiple versions to be able to switch between alternatives.</p><p>Also, after installing Python, create an environment using venv for applications, etc.</p><p>This article assumes Python 3.8 comes pre-installed, so you will install 3.6, 3.7, 3.9 and even 2.7 to run older applications.</p><p>I will summarize the procedure to enable the latest 3.9 among the installed ones and create an environment called “newest” with venv.</p><h3>Installation Instructions</h3><p>update apt packages</p><pre>sudo apt update<br>sudo apt upgrade -y</pre><p>(When using pip for package management) pip installation</p><p>Since pip is not installed in the following procedure, install it.</p><pre>sudo apt install -y python3-pip</pre><p>Check the version after installation.</p><pre>pip3 -V</pre><pre>pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)</pre><p>It is successful if the version is displayed without errors.</p><p>Add repositor</p><pre>sudo apt install -y software-properties-common<br>sudo add-apt-repository ppa:deadsnakes/ppa</pre><pre>For nightly builds, see ppa:deadsnakes/nightly https://launchpad.net/~deadsnakes/+archive/ubuntu/nightly<br> More info: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa<br>Press [ENTER] to continue or Ctrl-c to cancel adding it.</pre><p>If is displayed, press the Enter key.</p><p>apt upgrade</p><pre>sudo apt update</pre><p>Check the installable version of Python</p><pre>sudo apt list python3.*</pre><pre>python3.10-dbg/jammy-updates,jammy-security 3.10.6-1~22.04.2 amd64<br>python3.10-dev/jammy-updates,jammy-security,now 3.10.6-1~22.04.2 amd64 [installed,automatic]<br>python3.10-doc/jammy-updates,jammy-security 3.10.6-1~22.04.2 all<br>python3.10-examples/jammy-updates,jammy-security 3.10.6-1~22.04.2 all<br>python3.10-full/jammy-updates,jammy-security 3.10.6-1~22.04.2 amd64<br>python3.10-minimal/jammy-updates,jammy-security,now 3.10.6-1~22.04.2 amd64 [installed,automatic]<br>python3.10-nopie/jammy-updates,jammy-security 3.10.6-1~22.04.2 amd64<br>python3.10-venv/jammy-updates,jammy-security 3.10.6-1~22.04.2 amd64<br>python3.10/jammy-updates,jammy-security,now 3.10.6-1~22.04.2 amd64 [installed,automatic]</pre><p>Installable apt Python3.x packages are displayed, so decide which version to install.</p><p>Python installation of each version</p><pre>sudo apt install -y python3.9 python3.9-venv<br>sudo apt install -y python3.7 python3.7-venv<br>sudo apt install -y python3.6 python3.6-venv<br>sudo apt install -y python2.7 python2.7-venv</pre><blockquote>*To separate the virtual environment with venv, pythonX.X-venvele is also installed.</blockquote><blockquote>If you install mysqlclient with pip and compilation is required, an error may occur. If so, pythonX.X-devt install it as well.</blockquote><h3>Switching Versions with Alternatives</h3><p>definition</p><pre>sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 130<br>sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 120<br>sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.7 110<br>sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 10</pre><h3>Switching Method</h3><p>Selecting and Switching Priority</p><pre>sudo update-alternatives --config python</pre><p>There are 5 choices for the alternative python (providing /usr/bin/python).</p><pre>Selection    Path                Priority   Status<br>------------------------------------------------------------<br>* 0            /usr/bin/python3.9   130       auto mode<br>  1            /usr/bin/python2.7   10        manual mode<br>  2            /usr/bin/python3.6   100       manual mode<br>  3            /usr/bin/python3.7   110       manual mode<br>  4            /usr/bin/python3.8   120       manual mode<br>  5            /usr/bin/python3.9   130       manual mode<br><br>Press &lt;enter&gt; to keep the current choice[*], or type selection number:</pre><p>If Selection is displayed, type the number and Enter press the key to activate that version.</p><ul><li>The above is with Python 3.9 activated.</li></ul><pre>python -V</pre><pre>Python 3.9.6</pre><p>It is fine if it is the selected version.</p><p>How to set directly by command</p><p>If you enable 3.9:</p><pre>sudo update-alternatives --set python /usr/bin/python3.9</pre><pre>python -V</pre><pre>Python 3.9.6</pre><p><strong>venv (Python 3.x and later)</strong></p><blockquote>Here, we summarize the newest procedure for creating an environment for Python 3.9.</blockquote><p>Select the Python version:</p><pre>sudo update-alternatives --config python</pre><p>Specify the Python3.9 version with a number.</p><p>Create venv definition directory</p><pre>mkdir -p ~/venv/python3.9</pre><h3>Create environment</h3><p>Here we define a new environment name that will be used throughout the start directory and below.</p><pre>cd ~/venv/python3.9/</pre><p>Next, create a venv environment.</p><pre>python -m venv newest</pre><h4>Activate Created Environment</h4><pre>source ~/venv/python3.9/newest/bin/activate</pre><blockquote>If the environment name is displayed at the left end of the prompt (newest), it is referenced correctly.</blockquote><p>(When using pip for package management) pip update</p><pre>python -m pip install --upgrade pip</pre><p>(When using pip for package management) pip package installation</p><p>Install the packages you want to use.</p><pre>python -m pip install {Package Name }</pre><p>Whew! Now with that walkthrough given to setting up Python, let’s get back to Docker!!!</p><p>I’ll just describe what I did.</p><pre>root@882373b6681d:/# apt update<br>root@882373b6681d:/# apt upgrade<br>root@882373b6681d:/# apt install -y python3-pip<br>root@882373b6681d:/# pip --version<br>pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)<br>root@882373b6681d:/# apt install -y software-properties-common<br>root@882373b6681d:/# add-apt-repository ppa:deadsnakes/ppa<br>root@882373b6681d:/# apt update<br>root@882373b6681d:/# apt list python3.*<br>root@882373b6681d:/# apt install -y python3.12 python3.12-venv<br>root@882373b6681d:/# pip install Django</pre><p>Check the version of python and the version of various libraries.</p><p>I will install it whenever I find something missing.</p><pre>root@882373b6681d:/# python3 --version<br>Python 3.10.6</pre><pre>root@882373b6681d:/# pip list<br>Package             Version<br>------------------- -------------<br>asgiref             3.6.0<br>blinker             1.4<br>cryptography        3.4.8<br>dbus-python         1.2.18<br>distro              1.7.0<br>distro-info         1.1build1<br>Django              4.2<br>httplib2            0.20.2<br>importlib-metadata  4.6.4<br>jeepney             0.7.1<br>keyring             23.5.0<br>launchpadlib        1.10.16<br>lazr.restfulclient  0.14.4<br>lazr.uri            1.0.6<br>more-itertools      8.10.0<br>oauthlib            3.2.0<br>pip                 22.0.2<br>PyGObject           3.42.1<br>PyJWT               2.3.0<br>pyparsing           2.4.7<br>python-apt          2.4.0+ubuntu1<br>SecretStorage       3.3.1<br>setuptools          59.6.0<br>six                 1.16.0<br>sqlparse            0.4.4<br>unattended-upgrades 0.1<br>wadllib             1.3.6<br>wheel               0.37.1<br>zipp                1.0.0</pre><p>I will make an image in this state.</p><p>It seems that the docker commit command is used to create the image of a running container.</p><p>This time, I created a DockerImage called my-django-image.</p><p>Confirm with docker image ls that the image was created.</p><pre>root@docker:~# docker commit my-django my-django-image<br>sha256:55e95bb495d66998faf0e7f10ba54e7dc04a8dcb0e01d95fee5598c4e90c63ac</pre><pre>root@docker:~# docker image ls<br>REPOSITORY               TAG       IMAGE ID       CREATED         SIZE<br>my-django-image          latest    55e95bb495d6   2 minutes ago   646MB<br>portainer/portainer-ce   latest    f031e549070f   3 days ago      273MB<br>redis                    latest    eca1379fe8b5   4 days ago      117MB<br>nextcloud                latest    964325ce9b95   7 days ago      1e+03MB<br>nginx                    latest    6efc10a0510f   9 days ago      142MB<br>postgres                 latest    ceccf204404e   9 days ago      379MB<br>httpd                    latest    4b7fc736cb48   9 days ago      145MB<br>mysql                    latest    412b8cc72e4a   2 weeks ago     531MB<br>alpine                   latest    9ed4aefc74f6   3 weeks ago     7.05MB<br>ubuntu                   22.04     08d22c0ceb15   6 weeks ago     77.8MB<br>ubuntu                   latest    08d22c0ceb15   6 weeks ago     77.8MB<br>centos                   centos7   eeb6ee3f44bd   19 months ago   204MB<br>django                   latest    eb40dcf64078   6 years ago </pre><p><strong>Submit to DockerHub</strong></p><p>I would like to submit this to DockerHub.</p><p>First, access DockerHub with a web browser. Sign up if you don’t have an account.</p><p><a href="https://hub.docker.com/">https://hub.docker.com/</a></p><p>Set your username, email address, and password..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLu-Y56YiNv3h-zN0NYw8Q.png" /></figure><p>Select Personal for Plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcnCLqfVlGr3iaOfO4bRsg.png" /></figure><p>You will be asked to verify your email, so if you do…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*7xrtr2G3J2OcqCsuTaarcQ.jpeg" /></figure><p>I think the screen will look like this.</p><p>There is “Repositories” at the top of the screen, and you can create a site-side repository from here, but it is automatically generated when docker push, so you don’t need to create it here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwOztP29SyyfBO7MCzbITA.jpeg" /></figure><p>Log in to DockerHub on the server side.</p><p>Use the docker login command to log in.</p><pre>root@docker:~# docker login<br>Login with your Docker ID to push and pull images from Docker Hub. If you don&#39;t have a Docker ID, head over to https://hub.docker.com to create one.<br>Username: shotaohtsuka<br>Password:<br>WARNING! Your password will be stored unencrypted in /root/.docker/config.json.<br>Configure a credential helper to remove this warning. See<br>https://docs.docker.com/engine/reference/commandline/login/#credentials-store<br>Login Succeeded</pre><p>To upload the server image to DockerHub, it seems that the following steps should be followed.</p><p>1. tag the image using the docker tag command (tag: “latest” in “django:latest”)</p><p>2. Push it to DockerHub with the docker push command</p><p>Now tag the my-django image that was actually created and send it.</p><p>The list of strings after the tag is the IMAGE ID of my-django-image.</p><pre>root@docker:~# docker tag 55e95bb495d6 wandrys/my-django-image:latest<br>root@docker:~# docker image ls<br>REPOSITORY                     TAG       IMAGE ID       CREATED         SIZE<br>my-django-image                latest    55e95bb495d6   4 hours ago     646MB<br>wandrys/my-django-image   latest    55e95bb495d6   4 hours ago     646MB<br>portainer/portainer-ce         latest    f031e549070f   4 days ago      273MB<br>redis                          latest    eca1379fe8b5   4 days ago      117MB<br>nextcloud                      latest    964325ce9b95   7 days ago      1e+03MB<br>nginx                          latest    6efc10a0510f   9 days ago      142MB<br>postgres                       latest    ceccf204404e   9 days ago      379MB<br>httpd                          latest    4b7fc736cb48   10 days ago     145MB<br>mysql                          latest    412b8cc72e4a   2 weeks ago     531MB<br>alpine                         latest    9ed4aefc74f6   3 weeks ago     7.05MB<br>ubuntu                         22.04     08d22c0ceb15   6 weeks ago     77.8MB<br>ubuntu                         latest    08d22c0ceb15   6 weeks ago     77.8MB<br>centos                         centos7   eeb6ee3f44bd   19 months ago   204MB<br>django                         latest    eb40dcf64078   6 years ago     436MB</pre><pre>root@docker:~# docker push wandrys/my-django-image<br>Using default tag: latest<br>The push refers to repository [docker.io/wandrys/my-django-image]<br>bf846b78d73a: Pushed<br>b93c1bd012ab: Pushed<br>latest: digest: sha256:c64b17376f63a2c936e422dc29c6fda9c01e2202f8cb62c6c011349d941adb6c size: 742</pre><p>Let’s check if the image has been uploaded to the DockerHub side.</p><p>You can check it in Repositories.</p><p><strong>Let’s check if the image has been uploaded to the DockerHub side.</strong></p><p>You can check it in Repositories.</p><p>About DockerImage/DockerHub version control</p><p>I will omit it here, but I used my-django-image that I made to deploy a container and did several things.</p><p>So create an image again of the container after the job. I wanted to keep it as the latest (tag: latest) and manage this previous image as 1.0.</p><p>For such a pattern, the following seemed to work.</p><p>* There may be a more efficient way. . . .</p><p>1. Create an image file with tag set to 1.0 with the docker tag command.</p><p>2. Push 1.0 to DockerHub with docker push.</p><p>3. Image the current container with the docker commit command</p><p>4. Tagging the most recent images created with the docker tag command</p><p>5. Uploading the latest to DockerHub with docker push</p><p>Part one 1,2</p><pre>root@docker:~# docker image ls<br>REPOSITORY                     TAG       IMAGE ID       CREATED         SIZE<br>my-django-image                latest    55e95bb495d6   4 hours ago     646MB<br>wandrys/my-django-image   latest    55e95bb495d6   4 hours ago     646MB<br>portainer/portainer-ce         latest    f031e549070f   4 days ago      273MB<br>redis                          latest    eca1379fe8b5   4 days ago      117MB<br>nextcloud                      latest    964325ce9b95   7 days ago      1e+03MB<br>nginx                          latest    6efc10a0510f   9 days ago      142MB<br>postgres                       latest    ceccf204404e   9 days ago      379MB<br>httpd                          latest    4b7fc736cb48   10 days ago     145MB<br>mysql                          latest    412b8cc72e4a   2 weeks ago     531MB<br>alpine                         latest    9ed4aefc74f6   3 weeks ago     7.05MB<br>ubuntu                         22.04     08d22c0ceb15   6 weeks ago     77.8MB<br>ubuntu                         latest    08d22c0ceb15   6 weeks ago     77.8MB<br>centos                         centos7   eeb6ee3f44bd   19 months ago   204MB<br>django                         latest    eb40dcf64078   6 years ago     436MB<br>root@docker:~# docker tag 55e95bb495d6 wandrys/my-django-image:1.0<br>root@docker:~# docker image ls<br>REPOSITORY                     TAG       IMAGE ID       CREATED         SIZE<br>my-django-image                latest    55e95bb495d6   6 hours ago     646MB<br>wandrys/my-django-image   1.0       55e95bb495d6   6 hours ago     646MB<br>wandrys/my-django-image   latest    55e95bb495d6   6 hours ago     646MB<br>portainer/portainer-ce         latest    f031e549070f   4 days ago      273MB<br>redis                          latest    eca1379fe8b5   4 days ago      117MB<br>nextcloud                      latest    964325ce9b95   7 days ago      1e+03MB<br>nginx                          latest    6efc10a0510f   9 days ago      142MB<br>postgres                       latest    ceccf204404e   10 days ago     379MB<br>httpd                          latest    4b7fc736cb48   10 days ago     145MB<br>mysql                          latest    412b8cc72e4a   2 weeks ago     531MB<br>alpine                         latest    9ed4aefc74f6   3 weeks ago     7.05MB<br>ubuntu                         22.04     08d22c0ceb15   6 weeks ago     77.8MB<br>ubuntu                         latest    08d22c0ceb15   6 weeks ago     77.8MB<br>centos                         centos7   eeb6ee3f44bd   19 months ago   204MB<br>django                         latest    eb40dcf64078   6 years ago     436MB<br>root@docker:~# docker push wandrys/my-django-image:1.0<br>The push refers to repository [docker.io/wandrys/my-django-image]<br>bf846b78d73a: Layer already exists<br>b93c1bd012ab: Layer already exists<br>1.0: digest: sha256:c64b17376f63a2c936e422dc29c6fda9c01e2202f8cb62c6c011349d941adb6c size: 742</pre><p>then parts 3,4,5…</p><pre>root@docker:~# docker commit django-con my-django-image<br>sha256:55e0f735a3ae3c0426f1ed9cb64cf135974489ea3c8635b8294cb0fe88f63522<br>root@docker:~# docker image ls<br>REPOSITORY                     TAG       IMAGE ID       CREATED              SIZE<br>my-django-image                latest    55e0f735a3ae   About a minute ago   685MB<br>wandrys/my-django-image   1.0       55e95bb495d6   6 hours ago          646MB<br>wandrys/my-django-image   latest    55e95bb495d6   6 hours ago          646MB<br>portainer/portainer-ce         latest    f031e549070f   4 days ago           273MB<br>redis                          latest    eca1379fe8b5   4 days ago           117MB<br>nextcloud                      latest    964325ce9b95   7 days ago           1e+03MB<br>nginx                          latest    6efc10a0510f   9 days ago           142MB<br>postgres                       latest    ceccf204404e   10 days ago          379MB<br>httpd                          latest    4b7fc736cb48   10 days ago          145MB<br>mysql                          latest    412b8cc72e4a   2 weeks ago          531MB<br>alpine                         latest    9ed4aefc74f6   3 weeks ago          7.05MB<br>ubuntu                         22.04     08d22c0ceb15   6 weeks ago          77.8MB<br>ubuntu                         latest    08d22c0ceb15   6 weeks ago          77.8MB<br>centos                         centos7   eeb6ee3f44bd   19 months ago        204MB<br>django                         latest    eb40dcf64078   6 years ago          436MB<br>root@docker:~# docker tag 55e0f735a3ae wandrys/my-django-image:latest<br>root@docker:~# docker image ls<br>REPOSITORY                     TAG       IMAGE ID       CREATED         SIZE<br>my-django-image                latest    55e0f735a3ae   2 minutes ago   685MB<br>wandrys/my-django-image   latest    55e0f735a3ae   2 minutes ago   685MB<br>wandrys/my-django-image   1.0       55e95bb495d6   6 hours ago     646MB<br>portainer/portainer-ce         latest    f031e549070f   4 days ago      273MB<br>redis                          latest    eca1379fe8b5   4 days ago      117MB<br>nextcloud                      latest    964325ce9b95   7 days ago      1e+03MB<br>nginx                          latest    6efc10a0510f   9 days ago      142MB<br>postgres                       latest    ceccf204404e   10 days ago     379MB<br>httpd                          latest    4b7fc736cb48   10 days ago     145MB<br>mysql                          latest    412b8cc72e4a   2 weeks ago     531MB<br>alpine                         latest    9ed4aefc74f6   3 weeks ago     7.05MB<br>ubuntu                         22.04     08d22c0ceb15   6 weeks ago     77.8MB<br>ubuntu                         latest    08d22c0ceb15   6 weeks ago     77.8MB<br>centos                         centos7   eeb6ee3f44bd   19 months ago   204MB<br>django                         latest    eb40dcf64078   6 years ago     436MB<br>root@docker:~# docker push wandrys/my-django-image:latest<br>The push refers to repository [docker.io/wandrys/my-django-image]<br>4c6106b49d52: Pushed<br>bf846b78d73a: Layer already exists<br>b93c1bd012ab: Layer already exists<br>latest: digest: sha256:63dc995b9a27594c4b72c32c16168e5b4f8de614bcc633ff06b2d6bc5401b867 size: 954</pre><p>The check with DockerHub, 1.0 and newer has been completed.</p><p>It looks good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC2GijPH17fVgiCfCdSaww.jpeg" /></figure><p>In this article I have tried to present the issue in a more detailed way. In other articles I will try to bring up more issues about docker and the configuration environment.</p><p>I hope I have helped you!</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1f632edacd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Dockerfile with CUDA]]></title>
            <link>https://medium.com/@wandrys.sousa/create-dockerfile-with-cuda-b01873006a14?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/b01873006a14</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 11:32:27 GMT</pubDate>
            <atom:updated>2023-04-22T11:42:18.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*fnyqgVBvYvTCqEWGpxcb1g.gif" /></figure><h3>1. Overview</h3><p>How to generate a CUDA Dockerfile using the Dockerfile generation tool provided by nvidia.</p><p>Tool to generate a Dockerfile for nvidia/cuda:</p><p><a href="https://gitlab.com/nvidia/container-images/cuda">https://gitlab.com/nvidia/container-images/cuda</a></p><p>Useful when:</p><p>- When you want to create a deep learning environment using a GPU running on Docker.</p><p>- When you do not want to pollute the host terminal environment.</p><ul><li>When you want to use multiple CUDAs.</li></ul><h3>2. Environment</h3><ul><li>OS: Ubuntu20.04</li></ul><p><strong>In addition to the above, the settings required to run the Docker image using the generated Dockerfile</strong></p><p>- NVIDIA drivers must work correctly.</p><p>- nvidia-docker2 is installed.</p><p>nvidia-docker2: To install on ubuntu20.04, use the command below.</p><pre>distribution=$(. /etc/os-release;echo $ID$VERSION_ID) &amp;&amp; curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - &amp;&amp; curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list<br>sudo apt-get update<br>sudo apt-get install -y nvidia-docker2<br>sudo systemctl restart Docker</pre><h3>3. How to generate a Dockerfile</h3><p>clone the repositor:</p><pre>git clone https://gitlab.com/nvidia/container-images/cuda.git</pre><p>Delete built Dockerfile</p><p>In the cloned repository there is a Dockerfile directory called dist that has already been created, so delete it.</p><pre>rm -rf ./cuda/dist/*</pre><p>Create Virtual Environment</p><p>I don’t want to pollute the environment too much, so I create a virtual environment for the build. This time it is created using conda (miniconda).</p><pre>conda create -n build_cuda python=3.10.6<br>conda activate build_cuda</pre><p>Install poetry</p><p>poetry is a package manager called poetry that was used, so use that to install dependencies.</p><p>To do this, first install poetry.</p><pre>curl -sSL https://install.python-poetry.org | python3 –</pre><p>Change the working directory for the cloned repositor</p><pre>cd cuda</pre><p>Install dependencies using Poetry</p><p>In my environment, ~/.local/bin/poetry was installed, so run the following to install the dependencies.</p><pre>~/.local/bin/poetry install</pre><p>Generate Dockerfile</p><p>Try to generate the Dockerfile from CUDA11.2.2 with ubuntu20.04.</p><pre>python manager.py --manifest=&quot;manifests/cuda.yaml&quot; generate --cuda-version 11.2.2 --os-name ubuntu --os-version 20.04<br>python manager.py generate –help</pre><p>When running it, a directory will be generated in the Repository: directory/dist/CUDAversion/OSnamedirectory.basedeveruntimeDockerfile</p><p>About the generated Dockerfile type:</p><p><a href="https://hub.docker.com/r/nvidia/cuda">Docker</a></p><p>1. base: contains CUDA runtime (cudart)</p><p>2. runtime: contains CUDA math library and NCCL on top of base. There is also a runtime image that also includes cuDNN.</p><p>3. devel: Headers at the top of the runtime containing the development tools needed to build CUDA images. These images are especially useful for multi-stage builds.</p><h3>4. Create a custom Dockerfile</h3><ul><li>Add cuda to jupyter/minimal-notebook.</li></ul><p>correct manager.py</p><p>manager.py: Add filename patterns to the list around line 1041 (may vary depending on version).</p><p>For example, custom-dockerfile.j2, if you want to add a file named custom, add it as follows</p><pre>....<br>    def generate_containerscripts(self):<br>        for img in [&quot;base&quot;, &quot;devel&quot;, &quot;runtime&quot;, &quot;custom&quot;]:<br>            self.cuda[&quot;target&quot;] = img<br><br>            globber = f&quot;*&quot;<br>            ....</pre><h4><strong>Create file</strong></h4><p>Create a file in the Nameaddedintemplates/distribution-namelist-dockerfile.j2 directory.</p><p>In this case I have added a file called custom-dockerfile.j2.</p><pre>FROM jupyter/minimal-notebook:python-3.8.8<br>USER root<br>WORKDIR /tmp<br><br>ENV OS ubuntu2004<br>{% if &quot;x86_64&quot; in cuda %}<br>ENV NVARCH x86_64<br>{% if &quot;requires&quot; in cuda.x86_64 %}<br>ENV NVIDIA_REQUIRE_CUDA &quot;{{ cuda.x86_64.requires }}&quot;<br>{% endif %}<br><br>ENV NV_CUDA_CUDART_VERSION {{ cuda.x86_64.components.cudart.version }}<br>ENV NV_CUDA_COMPAT_PACKAGE cuda-compat-{{ cuda.version.major }}-{{ cuda.version.minor }}<br>{% endif %}<br>ENV LD_LIBRARY_PATH /usr/local/nvidia/lib:/usr/local/nvidia/lib64<br>ENV NVIDIA_VISIBLE_DEVICES all<br>ENV NVIDIA_DRIVER_CAPABILITIES compute,utility<br><br>ENV CUDA_VERSION {{ cuda.version.release_label }}<br><br>ENV NV_CUDA_LIB_VERSION &quot;{{ cuda.version.release_label + &quot;-1&quot; }}&quot;<br>{% if &quot;x86_64&quot; in cuda %}<br><br>ENV NV_CUDA_CUDART_DEV_VERSION {{ cuda.x86_64.components.cudart_dev.version }}<br>ENV NV_NVML_DEV_VERSION {{ cuda.x86_64.components.nvml_dev.version }}<br>ENV NV_LIBCUSPARSE_DEV_VERSION {{ cuda.x86_64.components.libcusparse_dev.version }}<br>    {% if &quot;libnpp_dev&quot; in cuda.x86_64.components %}<br>        {% set has_libnpp_dev_package = true %}<br>ENV NV_LIBNPP_DEV_VERSION {{ cuda.x86_64.components.libnpp_dev.version }}<br>ENV NV_LIBNPP_DEV_PACKAGE libnpp-dev-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_LIBNPP_DEV_VERSION}<br>    {% endif %}<br><br>ENV NV_LIBCUBLAS_DEV_VERSION {{ cuda.x86_64.components.libcublas_dev.version }}<br>ENV NV_LIBCUBLAS_DEV_PACKAGE_NAME libcublas-dev-{{ cuda.version.major }}-{{ cuda.version.minor }}<br>ENV NV_LIBCUBLAS_DEV_PACKAGE ${NV_LIBCUBLAS_DEV_PACKAGE_NAME}=${NV_LIBCUBLAS_DEV_VERSION}<br>    {% if &quot;nvprof&quot; in cuda.x86_64.components %}<br>        {% set has_nvprof_package = true %}<br><br>ENV NV_NVPROF_VERSION {{ cuda.x86_64.components.nvprof.version }}<br>ENV NV_NVPROF_DEV_PACKAGE cuda-nvprof-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_NVPROF_VERSION}<br>    {% endif %}<br>    {% if &quot;libnccl2&quot; in cuda.x86_64.components and cuda.x86_64.components.libnccl2 and &quot;libnccl2_dev&quot; in cuda.x86_64.components and cuda.x86_64.components.libnccl2_dev %}<br>        {% set has_libnccl_dev_package = true %}<br><br>ENV NV_LIBNCCL_DEV_PACKAGE_NAME libnccl-dev<br>ENV NV_LIBNCCL_DEV_PACKAGE_VERSION {{ cuda.x86_64.components.libnccl2_dev.version }}<br>ENV NCCL_VERSION {{ cuda.x86_64.components.libnccl2_dev.version }}<br>ENV NV_LIBNCCL_DEV_PACKAGE ${NV_LIBNCCL_DEV_PACKAGE_NAME}=${NV_LIBNCCL_DEV_PACKAGE_VERSION}+cuda{{ cuda.version.major }}.{{ cuda.version.minor }}<br>        {% if &quot;libnccl2&quot; in cuda.x86_64.components and &quot;source&quot; in cuda.x86_64.components.libnccl2 %}<br>ENV NV_LIBNCCL_PACKAGE_SHA256SUM {{ cuda.x86_64.components.libnccl2.sha256sum }}<br>ENV NV_LIBNCCL_PACKAGE_SOURCE {{ cuda.x86_64.components.libnccl2.source }}<br>ENV NV_LIBNCCL_PACKAGE_SOURCE_NAME {{ cuda.x86_64.components.libnccl2.basename }}<br><br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends wget<br><br>RUN wget -q ${NV_LIBNCCL_PACKAGE_SOURCE} \<br>    &amp;&amp; echo &quot;$NV_LIBNCCL_PACKAGE_SHA256SUM  ${NV_LIBNCCL_PACKAGE_SOURCE_NAME}&quot; | sha256sum -c --strict - \<br>    &amp;&amp; dpkg -i ${NV_LIBNCCL_PACKAGE_SOURCE_NAME} \<br>    &amp;&amp; rm -f ${NV_LIBNCCL_PACKAGE_SOURCE_NAME} \<br>    &amp;&amp; apt-get purge --autoremove -y wget \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>        {% endif %}<br>        {% if &quot;libnccl2_dev&quot; in cuda.x86_64.components and &quot;source&quot; in cuda.x86_64.components.libnccl2_dev %}<br>ENV NV_LIBNCCL_DEV_PACKAGE_SHA256SUM {{ cuda.x86_64.components.libnccl2_dev.sha256sum }}<br>ENV NV_LIBNCCL_DEV_PACKAGE_SOURCE {{ cuda.x86_64.components.libnccl2_dev.source }}<br>ENV NV_LIBNCCL_DEV_PACKAGE_SOURCE_NAME {{ cuda.x86_64.components.libnccl2_dev.basename }}<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends wget<br><br>RUN wget -q ${NV_LIBNCCL_DEV_PACKAGE_SOURCE} \<br>    &amp;&amp; echo &quot;$NV_LIBNCCL_DEV_PACKAGE_SHA256SUM  ${NV_LIBNCCL_DEV_PACKAGE_SOURCE_NAME}&quot; | sha256sum -c --strict - \<br>    &amp;&amp; dpkg -i ${NV_LIBNCCL_DEV_PACKAGE_SOURCE_NAME} \<br>    &amp;&amp; rm -f ${NV_LIBNCCL_DEV_PACKAGE_SOURCE_NAME} \<br>    &amp;&amp; apt-get purge --autoremove -y wget \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br>        {% endif %}<br>    {% endif %}<br>{% endif %}<br>ENV CUDNN_VERSION {{ cuda.x86_64.components.cudnn8.version }}<br><br>RUN sed -i &#39;s@archive.ubuntu.com@ftp.jaist.ac.jp/pub/Linux@g&#39; /etc/apt/sources.list &amp;&amp; \<br>    apt-get update &amp;&amp; apt-get install -y --no-install-recommends \<br>    wget software-properties-common tzdata dirmngr gpg-agent \<br>{% if cuda.os.version == &quot;22.04&quot; and not (cuda.image_tag_suffix | length) %}<br>    gnupg2 curl ca-certificates &amp;&amp; \<br>    curl -fsSLO {{ cuda.repo_url }}/${NVARCH}/cuda-keyring_1.0-1_all.deb &amp;&amp; \<br>    dpkg -i cuda-keyring_1.0-1_all.deb &amp;&amp; \<br>{% elif cuda.os.version != &quot;16.04&quot; or cuda.flavor == &quot;jetson&quot; %}<br>    {# Still used for internal 22.04 images until https://jirasw.nvidia.com/browse/CUDAINST-1240 #}<br>    gnupg2 curl ca-certificates &amp;&amp; \<br>    curl -fsSL {{ cuda.repo_url }}/${NVARCH}/3bf863cc.pub | apt-key add - &amp;&amp; \<br>    echo &quot;deb {{ cuda.repo_url }}/${NVARCH} /&quot; &gt; /etc/apt/sources.list.d/cuda.list &amp;&amp; \<br>{% else %}<br>    ca-certificates apt-transport-https gnupg-curl &amp;&amp; \<br>    NVIDIA_GPGKEY_SUM=a21c1a0b18a4196fa901b833e13c4fa64f094d7d9e8a6495318e7255f0ef23d1 &amp;&amp; \<br>    NVIDIA_GPGKEY_FPR=eb693b3035cd5710e231e123a4b469963bf863cc &amp;&amp; \<br>    apt-key adv --fetch-keys {{ cuda.repo_url }}/${NVARCH}/3bf863cc.pub &amp;&amp; \<br>    apt-key adv --export --no-emit-version -a $NVIDIA_GPGKEY_FPR | tail -n +5 &gt; cudasign.pub &amp;&amp; \<br>    echo &quot;$NVIDIA_GPGKEY_SUM  cudasign.pub&quot; | sha256sum -c --strict - &amp;&amp; rm cudasign.pub &amp;&amp; \<br>    echo &quot;deb {{ cuda.repo_url }}/${NVARCH} /&quot; &gt; /etc/apt/sources.list.d/cuda.list &amp;&amp; \<br>{% endif %}<br>    wget {{ cuda.repo_url }}/${NVARCH}/cuda-$OS.pin &amp;&amp; \<br>    mv cuda-$OS.pin /etc/apt/preferences.d/cuda-repository-pin-600 &amp;&amp; \<br>    apt-key adv --fetch-keys {{ cuda.repo_url }}/${NVARCH}/7fa2af80.pub &amp;&amp; \<br>    add-apt-repository &quot;deb {{ cuda.repo_url }}/${NVARCH}/ /&quot; &amp;&amp; \<br>    apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends \<br>    cuda-cudart-dev-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_CUDA_CUDART_DEV_VERSION} \<br>    ${NV_CUDA_COMPAT_PACKAGE} \<br>    cuda-command-line-tools-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_CUDA_LIB_VERSION} \<br>    cuda-minimal-build-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_CUDA_LIB_VERSION} \<br>    cuda-libraries-dev-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_CUDA_LIB_VERSION} \<br>    cuda-nvml-dev-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_NVML_DEV_VERSION} \<br>{% if has_nvprof_package %}<br>    ${NV_NVPROF_DEV_PACKAGE} \<br>{% endif %}<br>{% if has_libnpp_dev_package %}<br>    ${NV_LIBNPP_DEV_PACKAGE} \<br>{% endif %}<br>    libcusparse-dev-{{ cuda.version.major }}-{{ cuda.version.minor }}=${NV_LIBCUSPARSE_DEV_VERSION} \<br>    ${NV_LIBCUBLAS_DEV_PACKAGE} \<br>{% if has_libnccl_dev_package %}<br>    libnccl2=${NCCL_VERSION}+cuda{{ cuda.version.major }}.{{ cuda.version.minor }} \<br>    ${NV_LIBNCCL_DEV_PACKAGE} \<br>{% endif %}<br>{% if has_cuda_profiler_api_package %}<br>    ${NV_CUDA_PROFILER_API_PACKAGE} \<br>{% endif %}<br>    libcudnn8=${CUDNN_VERSION}+cuda{{ cuda.version.major }}.{{ cuda.version.minor }} &amp;&amp; \<br>    apt-mark hold libcudnn8 \<br>{% if ( cuda.version.major | int ) == 11 and ( cuda.version.minor | int ) &lt;= 2 %}<br>    &amp;&amp; ln -s cuda-{{ cuda.version.major }}.{{ cuda.version.minor }} /usr/local/cuda \<br>{% endif %}<br>    &amp;&amp; echo &quot;/usr/local/nvidia/lib&quot; &gt;&gt; /etc/ld.so.conf.d/nvidia.conf \<br>    &amp;&amp; echo &quot;/usr/local/nvidia/lib64&quot; &gt;&gt; /etc/ld.so.conf.d/nvidia.conf<br>#<br># cleanup<br>#<br>RUN npm cache clean --force &amp;&amp; \<br>    conda clean --all -f -y &amp;&amp; \<br>    apt-get clean &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br><br>WORKDIR /home/jovyan<br>EXPOSE 8888<br>USER $NB_UID<br>CMD jupyter notebook --no-browser --port 8888 --ip=*</pre><p>Run the following Dockerfile again to generate:</p><pre>python manager.py --manifest=&quot;manifests/cuda.yaml&quot; generate --cuda-version 11.2.2 --os-name ubuntu --os-version 20.04</pre><p>This time it was generated in ./dist/11.2.2/ubuntu2004/custom/Dockerfile.</p><p>The specifications are as follows:</p><p>- x86_64: Only for Other architectures . templates /distribution-name/****-dockerfile.j2 examine different files and modify accordingly.</p><p>- I have added some notes to avoid errors.</p><p>- Image-based devel.</p><ul><li>If you change to another operating system, modify the ubuntu2004 OS ENV part.</li></ul><h3>5. Explanation</h3><h4>gerenciador.py</h4><p>This manager.py method uses the method of just generating Dockerfile using the file.</p><p>When you run the script, python manager.py — manifest=”manifests/cuda.yaml” generate option it runs in the following order.</p><h4>manifests/cuda.yaml</h4><p>manifests/cuda.yaml contains version information for various libraries for generating Dockerfiles.</p><p>For example, cuda the version of 11.2.2 is cudnn described below, so if you look in reverse you will see that 8.1.1.33–1 is installed.</p><pre>...<br>.components_v11.2.2: &amp;cuda11_2_2_components<br>  ...<br>  cudnn8:<br>    version: 8.1.1.33-1<br>...<br>cuda_v11.2.2:<br>  ...<br>  ubuntu20.04:<br>    ...<br>    x86_64:<br>      &lt;&lt;: *cuda11_2_2_requires<br>      components:<br>        &lt;&lt;: *cuda11_2_2_components<br>    arm64:<br>      requires: &quot;cuda&gt;=11.2&quot;<br>      components:<br>        &lt;&lt;: *cuda11_2_2_components</pre><h3>6. Reference</h3><p><a href="https://github.com/jupyter/docker-stacks/blob/main/base-notebook/Dockerfile">docker-stacks/Dockerfile at main · jupyter/docker-stacks</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b01873006a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Blockchain with Python]]></title>
            <link>https://medium.com/@wandrys.sousa/learning-blockchain-with-python-7a65f142d4b9?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a65f142d4b9</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 17:46:17 GMT</pubDate>
            <atom:updated>2023-04-22T11:43:01.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMxkTAUPHoD61eU_E8bcqg.jpeg" /></figure><h3>1. First things first</h3><p>In this article, I will explain how to learn blockchain using Python. Blockchain is widely known in the field of cryptocurrencies, but its technology is used in various fields. I will also explain the blockchain mechanism in detail and how to implement it in Python for those with basic knowledge of Python.</p><p>For each section, an example Python implementation is provided. In “8.1. Full source code”, the complete source code is described, including the Python implementation for each section.</p><h3>1.1. What is Blockchain?</h3><p>Blockchain is a distributed database technology that allows data to be distributed and recorded in a format that cannot be falsified. The data is stored in a chain of blocks called blocks.</p><p>Blockchain is commonly associated with Bitcoin and other cryptocurrencies as a distributed accounting technology, but it has many other applications. For example, the financial industry uses blockchain to improve the transparency and reliability of transactions. Blockchain can also help to improve legal processes, such as digitally signing for legal contracts and documents.</p><p>The major advantage of blockchain is that it is highly tamper-resistant because it is a decentralized database, as opposed to a centralized one. This increases data transparency and trust, while reducing security risks.</p><h3>1.2. Blockchain mechanism</h3><p>Blockchain is a type of distributed database that enhances reliability and security by sharing information between multiple computers. It manages data by linking collections of information, which are called blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*9HnQpAIdD8TJAnu4OwxxXg.jpeg" /></figure><h3>2. Block Structure</h3><p>Blockchain technology stores data in the form of a chain of data blocks called blocks. Each block contains multiple transactions, and blockchains are used to keep records of these transactions. The first block in a blockchain is called the genesis block. In this article, we will take a closer look at the structure of the blocks.</p><h3>2.1. Overview of a Block</h3><p>A block is the fundamental data structure of a blockchain and typically consists of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*TkAk6sG35iNIMfvfkeutlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NoEtZWR3mwDpJ9nzM76ag.png" /></figure><h3>2.2 Overview of the Header</h3><p>The header contains the following elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*trBqPPwlj9cl4lPPds0u9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS83kydvCmrq3WJOmQRl3Q.png" /></figure><h3>2.3. Python Implementation</h3><p>In Python, the block header can be defined and variables can be initialized as follows:</p><pre>class Block:<br>    def __init__(self, index, timestamp, nonce, previous_block_hash, merkle_root, transactions):<br>        self.index = index  # index<br>        self.timestamp = timestamp  # time-stamping<br>        self.nonce = nonce  # nance<br>        self.previous_block_hash = previous_block_hash  # Previous block hash value<br>        self.merkle_root = merkle_root  # Mark Root</pre><h3>3. Transaction</h3><p>A transaction that occurs on the blockchain is called a transaction. Transactions involving virtual currency typically include information such as source address, destination address, amount of currency sent, transaction fee, and more, but the data contained in a transaction can vary depending on its purpose. For simplicity, we will not define each component of a transaction in this article.</p><h3>3.1 Overview of Transactions</h3><p>Transactions are initially added to a transaction pool. Miners then select transactions from the pool, include them in a new block, and then add the block to the blockchain, thereby verifying the transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*o6ircFnjlLu5x_jouRkQAA.jpeg" /></figure><p><strong>3.2 Python implementation</strong><br> When dealing with virtual currency, transactions are typically selected from the pool based on the highest transaction fee. However, for the sake of simplicity, we will use a Python queue class and implement it as first-in, first-out (FIFO). The transaction pool registration process is implemented as follows: a queue class named <strong>transaction_pool</strong> is defined, and the <strong>add_transaction</strong> function is used to add transactions to the queue.</p><pre>class Blockchain:<br>    def __init__(self):<br>        self.transaction_pool = Queue()  # transaction pool<br>    <br>    # Function to add a transaction<br>    def add_transaction(self, transaction):<br>        self.transaction_pool.put(transaction)</pre><p>In the mining function, <strong>transaction_pool</strong> we are fetching the transactions and setting them up as a list. After that, when adding a block as a blockchain, <strong>transaction_pool</strong> initializes it.</p><pre>    # Functions to be mined<br>    def mine_block(self):<br>        ## ...<br>        new_block_transactions = list(self.transaction_pool.queue)<br>        ## ...<br>        while True:<br>            ## ...<br>            # If hash value is less than requested difficulty, add block and exit<br>            if new_block_hash[:self.difficulty] == &#39;0&#39; * self.difficulty:<br>                self.transaction_pool = Queue()<br>                ## ...</pre><h3>4. Hashes and Merkle Roots</h3><p>Hashes and Merkle roots play a very important role in blockchain. This article provides an overview of Merkle hashes and roots, and explains how they are utilized in blockchains.</p><h3>4.1. Overview of Hashes</h3><p>A hash function generates a unique fixed-length value from data. Hash functions always produce the same hash value for the same data and different hash values for different data. Hash values are usually represented in numerical or hexadecimal format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-xFtGQPdCtEDbV7YB18bw.png" /></figure><p>Hash functions play a very important role in blockchain. Every transaction or block on the blockchain is assigned to a hash value. This ensures that all data on the blockchain is uniquely identified and has not been tampered with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*sZ4autG6_Hz7BmwvJbFhJA.jpeg" /></figure><p>Hash functions come in many varieties, such as SHA-256 and RIPEMD-160. These functions may produce the same output for different inputs, but they always produce the same output for the same inputs.</p><h3>4.2. Using Hashes in Blockchain</h3><p>Hashes also play an important role in blockchain. Each block contains the hash value of the previous block, which uniquely concatenates and identifies all blocks in the blockchain.</p><p>Additionally, all transactions on the blockchain are hashed. Changing the content of a transaction will generate a different hash value, making it difficult to tamper with the transaction.</p><h3>4.3. Merkle Root Overview</h3><p>A Merkle root is a data structure used in a blockchain to combine the hash values of multiple transactions into a single hash value. The Merkle root is a tree structure of hash values, and the root hash value is stored in the block header to ensure uniqueness of multiple transactions.</p><p>Merkle roots are used for blocks that contain multiple transactions. The hash value each transaction is placed in a leaf node and the hash value of the adjacent leaf nodes is calculated as the hash value of the parent node. This process is repeated until the entire hash value is set as the root.Merkle roots are used in blockchains to ensure that transactions are not tampered with. For instance, if a transaction in a block is tampered with, the hash value of that transaction will change, as will the hash value of its parent node. This also changes the hash value of the root, making tampering detectable.</p><h3>4.4. Use of Merkle Root in Blockchain</h3><p>In blockchain, Merkle roots are used to detect transaction tampering. If a transaction in a block changes, its hash value will change, and so will the hash value of its parent node. Thus,the root hash value will also change, making tampering detectable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*UhhorvPN3VKZglOjPznPJg.jpeg" /></figure><p>Blockchain uses the SHA-256 algorithm to calculate hash values. The SHA-256 algorithm is a cryptographic hash function that produces a fixed-length hash value from input data and is used to prevent data tampering.</p><h3>4.5. Python Implementation</h3><h3>4.5.1. Hashes</h3><p>The hash value of the block is calculated with SHA256 from the header. The implementation formats the headers in JSON and calculates the hash.</p><pre>    # Function to calculate hash with SHA256<br>    def calculate_hash(self):<br>        block_string = json.dumps({<br>            &#39;index&#39;: self.index,  # index<br>            &#39;timestamp&#39;: self.timestamp,  # time-stamping<br>            &#39;nonce&#39;: self.nonce,  # nonce<br>            &#39;previous_block_hash&#39;: self.previous_block_hash,  # Previous block hash value<br>            &#39;merkle_root&#39;: self.merkle_root,  # Mark Root<br>        }, sort_keys=True).encode()<br>        <br>        return hashlib.sha256(block_string).hexdigest()</pre><p>block_hash, the hash value of the previous block is obtained from the previous string during mining.</p><pre>    # Functions to be mined<br>    def mine_block(self):<br>        # Get the previous block<br>        previous_block = self.chain[-1]<br>        # ...<br>        new_block_previous_hash = previous_block[&#39;block_hash&#39;]</pre><h3>4.5.2. Merkle Root</h3><p>Merkle root is processed by the following algorithm.</p><p>1. Returns the hash value of an empty string if the number of transactions is 0</p><p>2. If the number of transactions is 1, return the hash value of that transaction</p><p>3. If the number of elements is odd, double the last element to make it even</p><p>4. Combine two elements to calculate a hash value and store it in a list</p><p>5. 3. to 4. are repeated recursively.</p><pre>  # Function to calculate the Markle root<br>    def calculate_merkle_root(self, transactions):<br>        # If the number of elements is 0, returns an empty string hash value<br>        if len(transactions) == 0:<br>            return hashlib.sha256(b&#39;&#39;).hexdigest()<br><br>        # If the number of elements is 1, return the hash value of the transaction        <br>        if len(transactions) == 1:<br>            return hashlib.sha256(transactions[0].encode()).hexdigest()<br><br>        # If the number of elements is odd, duplicate the last element to make it even.<br>        if len(transactions) % 2 == 1:<br>            transactions.append(transactions[-1])<br><br>        # Initialize list to store hash values<br>        hashes = []<br><br>        # Combine the two transactions, calculate the hash value, and store it in the list<br>        for i in range(0, len(transactions), 2):<br>            transaction_pair = transactions[i] + transactions[i+1]<br>            hash_value = hashlib.sha256(transaction_pair.encode()).hexdigest()<br>            hashes.append(hash_value)<br><br>        # Calculate Markle routes recursively<br>        return self.calculate_merkle_root(hashes)</pre><h3>5. Nonce and Difficulty</h3><p>In a decentralized network of blockchains, multiple nodes compete to add new blocks. To add a new block, you must find the correct answer before your competitors do. A value called nonce in the block header is used to find this answer.</p><h3>5.1. Overview of nonces</h3><p>A nonce is part of the block header and is used to maintain the security of the blockchain.</p><p>It could simply be a random value, but in that case, it would be very rare for the hash value of a block to meet certain criteria, making it difficult to mine the block. Therefore, the nonce needs to be coordinated so that miners can efficiently calculate block hashes.</p><h3>5.2. Using Nonces in Blockchain</h3><p>A block miner modifies the value of a nonce so that the hash value of a block meets certain conditions. This condition is called a blockchain difficulty.</p><h3>5.3 Overview of difficulty</h3><p>The difficulty controls the average speed at which new blocks are generated. If blocks are generated too quickly, the network may become overloaded and unable to process transactions. On the other hand, if blocks are generated too slowly, transaction processing may be delayed. Therefore, adjusting the speed at which blocks are generated keeps the network stable.</p><h3>5.4. Difficulty of using Blockchain</h3><p>To generate a new block in the blockchain, the “hash value” calculated from the block header must meet certain difficulty conditions. Specifically, the hash value must contain a certain number of leading zeroes, the number of which is determined based on rules shared in the network for adjusting the difficulty. The difficulty adjusts the speed at which blocks are generated by altering the amount of computation required to generate the hash value. In other words, if the difficulty is high, the amount of computation required to generate the hash value increases, slowing down the speed at which the block is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Ffjoz9HyMw4LVgCOGe39Dg.jpeg" /></figure><p>Changing the difficulty will change how long it takes to mine a new block, but generally the difficulty is set so that a block is generated every 10 minutes on average. This system is used in PoW (Proof of Work) blockchains, such as Bitcoin.</p><h3>5.5 Python Implementation</h3><p>First, set the nonce (the initial value is 0), calculate the hash and new_block_hash assign a. After that, new_block_hash take the number of bytes for the difficulty level (2 bytes in this case) from the beginning of, and check that 0 is continuous for the difficulty level (in this case, it corresponds to ‘00’). If the condition is met, add a block to the string and stop mining, otherwise add 1 to the nonce and repeat the process again.</p><pre>class Blockchain:<br>    def __init__(self):<br>        # ...<br>        self.difficulty = 2  # degree of difficulty<br>    # ...<br>    # Functions to be mined<br>    def mine_block(self):<br>        # ...<br>        new_block_nonce = 0<br>        # ...<br>        while True:<br>            # Create a new block<br>            new_block = Block(<br>                index = new_block_index,<br>                timestamp = new_block_timestamp,<br>                nonce = new_block_nonce,<br>                previous_block_hash = new_block_previous_hash,<br>                merkle_root = new_block_merkle_root,<br>                transactions = new_block_transactions<br>            )<br>            # ...<br>            new_block_hash = new_block.calculate_hash()<br>            <br>            # If hash value is less than requested difficulty, add block and exit<br>            if new_block_hash[:self.difficulty] == &#39;0&#39; * self.difficulty:<br>                # ...<br>            <br>            # Increase nonce and try again<br>            new_block_nonce += 1</pre><h3>6. Electronic Signature, Public Key, Private Key</h3><p>Cryptographic technologies, such as electronic signatures, public keys, and private keys, play a significamt role in blockchain technology. This article provides an overview of digital signatures, public and private keys and how they are used in blockchains.</p><h3>6.1. Overview of Electronic Signatures</h3><p>An electronic signature is a technology used to ensure the authenticity and integrity of documents. Specifically, by electronically signing a document, it is possible to confirm information such as whether the document has not been tampered with and who the signer is.</p><p>Digital signatures are based on public key cryptography. Public key cryptography is a system that uses different keys to encrypt and decrypt, and there are two keys: a private key and a public key.</p><h3>6.2. Use of Electronic Signatures in Blockchain</h3><p>Blockchain uses electronic signatures for transactions. Transactions, like transaction information, include sender and recipient addresses, amount of coins to be sent, etc. The sender signs the transaction with his private key and sends it to the network with this signature. Other nodes on the network can use the sender’s public key to verify that the sender’s signature is correct. If the signature is correct, the transaction is approved and added to the block. In this way, transactions on the blockchain are reliable and secure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*hWBXz2kNIf4gH3wwFzGYUQ.jpeg" /></figure><h3>6.3. Overview of Public and Private Keys</h3><p>The public and private keys are two cryptographically related keys that are essential for the security of asymmetric cryptography. Anyone can know the public key and only the owner knows the private key. Public key cryptography uses a public key to encrypt and a private key to decrypt. The sender uses the recipient’s public key to encrypt the message and the recipient uses his own private key to decrypt the message. This method has excellent security because it is safe even if the private key leaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*h5GnIyzIrd8fz59ANA7UvQ.jpeg" /></figure><h3>6.4. How public and private keys are used in blockchain</h3><p>In blockchain, public and private keys are used in transaction relationships. Transactions are signed with the private key of the sender. This proves that the transaction was actually generated by the sender. Blockchain also has a self-authentication function. This verifies who is the sender of the public key included in the transaction and the signature of the transaction. This method proves that the sender has legitimate rights and authorizes the transaction.</p><h3>7. Blockchain Security</h3><h3>7.1. The importance of Blockchain security</h3><p>Blockchain is generally considered a highly secure system compared to centralized systems due to the use of distributes accounting technology, where multiple nodes store and manage the same data.However, it is inevitable that attacks will occur against the important information held by blockchain. Cryptographic technology guarantees the security of blockchain, but attackers are constantly developing new methods to find vulnerabilities in blockchains. Much of the information held by blockchains, such as transaction histories and personal, is valuable to attackers. Therefore, appropriate security measures are required to ensure blockchain security. In this context, the 51% attack is a typical example that I will explain.</p><p><strong>7.2. 51% attack</strong></p><p>A 51% attack is an attack technique that allows attackers to attack a blockchain when they have a majority hash power on the network. In this attack technique, the attacker has the majority hash power, which allows him to cheat the adoption of the blocks generated by himself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ja8FU0cpxGc1cgRe5S_9hg.jpeg" /></figure><p>To prevent this attack, it is important to distribute hash power in the network. Also, since this attack is very expensive, it is difficult for an attacker to easily obtain majority hash power.</p><h3>8. Python Implementation</h3><h3>8.1. Full source code</h3><p>Here is the Python code that I have implemented:</p><p>Electronic signatures, etc. are important technical elements in transaction processing that have sender and recipient roles, but are outside the scope of this implementation for the following reasons:</p><p>- The goal is to understand the blockchain mechanism, and is not implemented in a transaction scenario</p><ul><li>The implementation of electronic signatures, public keys and private keys complicates the implementation and makes it difficult to see the actual state of the blockchain.</li></ul><pre>import hashlib<br>import json<br>import time<br><br># Block Classes<br>class Block:<br>    def __init__(self, index, timestamp, nonce, previous_block_hash, merkle_root, transactions):<br>        self.index = index  # index<br>        self.timestamp = timestamp  # time-stamping<br>        self.nonce = nonce  # nonce<br>        self.previous_block_hash = previous_block_hash  # Previous block hash value<br>        self.merkle_root = merkle_root  # Mark Root<br>        self.transactions = transactions  # transaction<br>        self.block_hash = self.calculate_hash()  # block hash value<br><br>    # Function to calculate hash with SHA256<br>    def calculate_hash(self):<br>        block_string = json.dumps({<br>            &#39;index&#39;: self.index,  # index<br>            &#39;timestamp&#39;: self.timestamp,  # time-stamping<br>            &#39;nonce&#39;: self.nonce,  # nonce<br>            &#39;previous_block_hash&#39;: self.previous_block_hash,  # Previous block hash value<br>            &#39;merkle_root&#39;: self.merkle_root,  # Mark Root<br>        }, sort_keys=True).encode()<br>        <br>        return hashlib.sha256(block_string).hexdigest()<br><br>    # Function to calculate the Markle root<br>    def calculate_merkle_root(self, transactions):<br>        # If the number of elements is 0, returns an empty string hash value<br>        if len(transactions) == 0:<br>            return hashlib.sha256(b&#39;&#39;).hexdigest()<br><br>        # If the number of elements is 1, return the hash value of the transaction<br>        if len(transactions) == 1:<br>            return hashlib.sha256(transactions[0].encode()).hexdigest()<br><br>        # If the number of elements is odd, duplicate the last element to make it even.<br>        if len(transactions) % 2 == 1:<br>            transactions.append(transactions[-1])<br><br>        # Initialize list to store hash values<br>        hashes = []<br><br>        # Combine the two transactions, calculate the hash value, and store it in the list<br>        for i in range(0, len(transactions), 2):<br>            transaction_pair = transactions[i] + transactions[i+1]<br>            hash_value = hashlib.sha256(transaction_pair.encode()).hexdigest()<br>            hashes.append(hash_value)<br><br>        # Calculate Markle routes recursively<br>        return self.calculate_merkle_root(hashes)<br><br># Blockchain Classes<br>class Blockchain:<br>    def __init__(self):<br>        self.chain = [self.create_genesis_block()]  # chain<br>        self.transaction_pool = Queue()  # transaction pool<br>        self.difficulty = 2  # degree of difficulty<br><br>    # Function to generate a genesis block<br>    def create_genesis_block(self):<br>        genesis_block = Block(<br>            index=0,<br>            timestamp=time.time(),<br>            nonce=0,<br>            previous_block_hash=&#39;&#39;,<br>            merkle_root=&#39;&#39;,<br>            transactions=[],<br>        )<br>        return genesis_block.__dict__<br><br>    # Function to add a transaction<br>    def add_transaction(self, transaction):<br>        self.transaction_pool.put(transaction)<br>    <br>    # Functions to be mined<br>    def mine_block(self):<br>        # Get the last block<br>        previous_block = self.chain[-1]<br>        <br>        # Set data for new block<br>        new_block_index = previous_block[&#39;index&#39;] + 1<br>        new_block_timestamp = time.time()<br>        new_block_nonce = 0<br>        new_block_previous_hash = previous_block[&#39;block_hash&#39;]<br>        new_block_merkle_root = &#39;&#39;<br>        new_block_transactions = list(self.transaction_pool.queue)<br>        <br>        while True:<br>            # Create a new block<br>            new_block = Block(<br>                index = new_block_index,<br>                timestamp = new_block_timestamp,<br>                nonce = new_block_nonce,<br>                previous_block_hash = new_block_previous_hash,<br>                merkle_root = new_block_merkle_root,<br>                transactions = new_block_transactions<br>            )<br>            new_block.merkle_root = new_block.calculate_merkle_root(new_block_transactions),<br>            new_block_hash = new_block.calculate_hash()<br>            <br>            # If hash value is less than requested difficulty, add block and exit<br>            if new_block_hash[:self.difficulty] == &#39;0&#39; * self.difficulty:<br>                self.chain.append(new_block.__dict__)<br>                self.transaction_pool = Queue()<br>                <br>                return new_block.__dict__<br>            <br>            # Increase nonce and try again<br>            new_block_nonce += 1</pre><h3>8.2. Execution Scenario</h3><ol><li>Add a transaction named “Alice” and check the state of the chain. In this state, we can see that only the genesis block exists in the chain.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-V-8HK-bSwfVpYeVoc4Yg.png" /></figure><p>2. During mining, block #1 containing the previously recorded transaction “Alice” was processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvrYz3fVNZ8cBwjWCkRrJQ.png" /></figure><p>3. Checking the chain, we can see that block #1 has been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myYE9fraImVJhvFBKLvhHw.png" /></figure><p>4. Now add two transactions, “Bob” and “Grace”, and check the state of the chain. As before, there is no change in the chain itself because it is before mining.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMpkq2_JVYBa5FPaJuN-5Q.png" /></figure><p>5. During mining, block #2 was processed containing two transactions, “Bob” and “Grace”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvt6Kxj5dxPFEGQT6RW0YA.png" /></figure><p>6. If you check the chain, you can see that block #2 has also been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RzjLzaHZVEMOqYM9yK2Vg.png" /></figure><p><strong>References</strong></p><p>-Book: Complete Understanding of Blockchain Principles of Next-Generation Scratch Technology, Daniel Drescher et al.</p><p>-Book: Illustrated, ready-to-use textbook, Consensus Base Co., Ltd.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a65f142d4b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assign a fixed IP address to a container in Docker-Compose]]></title>
            <link>https://medium.com/@wandrys.sousa/assign-a-fixed-ip-address-to-a-container-in-docker-compose-2cc6c1a6151e?source=rss-4689528c2957------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cc6c1a6151e</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[Wandrys Nascimento]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 17:06:44 GMT</pubDate>
            <atom:updated>2023-04-22T11:43:47.188Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Introduction</strong></li></ol><p><em>Let’s situate the current article considering the practical case that takes into account Ubuntu being launched in a virtual environment, and knowing that in this case it is done to know what are the route and firewall controls as a host and a router.</em></p><p><em>Initially it could be asked why the use of virtualbox in a virtual environment is not considered. In a virtualbox we have disadvantages for huge amounts of data and for sharing Ubuntu images with all users and installations, and the time consuming setup and startup can easily be highlighted.</em></p><p><em>So I was driven to build an experimental environment using Docker.</em></p><p><strong>2. Development environment</strong></p><p>The environments used for development are as follows, and we are sure that both work in the same way:</p><p><strong>Windows</strong></p><ul><li>Windows10 Home Edition</li><li>Versão Docker 20.10.14, construa um224086</li><li>Versão Docker Compose v2.4.1</li></ul><h4>macOS</h4><ul><li>macOS Monterey versão 12.3.1</li><li>Versão Docker 20.10.12, build e91ed57</li><li>Versão Docker Compose versão 1.29.2, build 5becea4c</li></ul><p><strong>3. Forms-basic data</strong></p><p>First, let’s make the forms with the base data for the present development easy to understand.</p><p>3.1 <strong>Services to create</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*K4T0mJamjAxqGjkUDWsbyA.png" /></figure><p>3.2 <strong>Network to create</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*hFV6wHgJJT0vC0BNC9C6oA.png" /></figure><p>Start hosts and routes on these networks to experiment with route control.</p><p>The following configuration diagrams are assumed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*CnhyhCLq9v-NVu4kDzaQqA.png" /></figure><p><strong>4. About the Dockerfile used for hosts and routers</strong></p><p><em>This time, we will create a docker image based on the official Ubuntu 20.04 Docker image for the host and router.</em></p><p><em>Specifically, the official Ubuntu20.04 Docker does not contain network-based commands (ping, route, etc.).</em></p><p><em>Therefore, you can create your own Dockerfiles and install these commands at build time.</em></p><p><em>The complete Dockerfile is as follows:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*6V1HDQnzlG0slOnuWoEOqw.png" /></figure><p><strong>5. Configure network and container in Docker-compose.yml</strong></p><p><em>In Docker-com.yml, we will set it to be built from a network like the one in the previous completed figure and a Dockerfile that has already been created.</em></p><p><em>The full text is as follows:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*WrnE6etjfUkRI9gC26uGvw.png" /></figure><p><strong>6. Create a network</strong></p><p><em>First, create a network.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*OzVodEQvO5e9N0uO_Ji0Eg.png" /></figure><p><em>Under networks, name the network you want to create. I will use route1_network this time.</em></p><p><em>What matters is the subnet part.</em></p><p><em>Specify the IP address you want to set here and its range.</em></p><p><em>Then you can assign this configured network to the service.</em></p><p><strong>7. Create services and assign networks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*gKodFCvEPL6IAAT7vnIYBQ.png" /></figure><p><em>First, I will specify the position of the context and dockerfile in the build.</em></p><p><em>This context setting determines the container’s root location and determines where it can be accessed, so it should be changed according to the service you are developing.</em></p><p><em>It is also a point to specify the command.</em></p><p><em>Docker containers will automatically crash when nothing is running, so leave the container running with this command.</em></p><p><em>now please look at the network part of the main subject.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*4M1xt67gIEkmrRvsTcsnzg.png" /></figure><p><em>Just by looking at it, you can see what it says, assign the network you just created, and write the IP address to be assigned to this container.</em></p><p><em>That’s it.</em></p><p><strong>8. Summary</strong></p><p><em>It’s very easy.</em></p><p><em>After that, it would be perfect if you could docker-compose up and create a routing table for your router or host.</em></p><p><em>In the future, I hope that dynamic route control can be done instead of manually setting the routing table.</em></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>If you’re looking for quality content that will surprise you, buy me a cup of coffee (<a href="https://www.buymeacoffee.com/Wandrys">https://www.buymeacoffee.com/Wandrys</a>) and follow me on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HE-Rqy_yQADYDKmPFWAEgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cc6c1a6151e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>