<?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 Shawn Shao on Medium]]></title>
        <description><![CDATA[Stories by Shawn Shao on Medium]]></description>
        <link>https://medium.com/@lucky23268?source=rss-ace8d9b2232------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2BrD0sarbqaZyejYPs_M0w.jpeg</url>
            <title>Stories by Shawn Shao on Medium</title>
            <link>https://medium.com/@lucky23268?source=rss-ace8d9b2232------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:40:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucky23268/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[Blog By MongoDB+flask service+Django (Development Procedure)]]></title>
            <link>https://medium.com/@lucky23268/blog-by-mongodb-flask-service-django-development-procedure-64e5e6b2ddef?source=rss-ace8d9b2232------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e5e6b2ddef</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Shawn Shao]]></dc:creator>
            <pubDate>Sun, 16 Dec 2018 14:23:28 GMT</pubDate>
            <atom:updated>2018-12-17T03:13:14.901Z</atom:updated>
            <content:encoded><![CDATA[<p>Timeline: 20180418~20180501</p><blockquote>Project SPEC and Framework</blockquote><blockquote><strong>Development Flow</strong></blockquote><ul><li>Connect to MongoDB and access it by the flask</li><li>Flask service provides restful api (get/post/put/patch/delete) for django to manipulate mongoDB</li><li>Django displays the blog website (including posts and comments) and access mongodb through the flask service (calling restful apis)</li></ul><blockquote><strong>MongoDB</strong></blockquote><blockquote><strong>Install MongoDB Community Edition with Homebrew</strong></blockquote><p><strong>db version v3.6.4</strong></p><ol><li>Create the data directory.</li><li>Set permissions for the data directory.</li><li>Run MongoDB ($ mongod)</li></ol><p>Ref: <a href="https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/#install-mongodb-community-edition-with-homebrew">https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/#install-mongodb-community-edition-with-homebrew</a></p><blockquote><strong>Test if the mongodb can work locally</strong></blockquote><p><strong>Utilize the python package: pymongo==3.6.1</strong></p><p>e.g.</p><p># mongo1.py</p><pre>from pymongo import MongoClient<br>import datetime</pre><pre>client = MongoClient(‘mongodb://localhost:27017/’)</pre><pre># data base name : ‘test-database-1’<br>mydb = client[‘test-database-1’]</pre><pre>myrecord = {<br>    “author”: “Duke”,<br>    “title” : “PyMongo 101”,<br>    “tags” : [“MongoDB”, “PyMongo”, “Tutorial”],<br>    “date” : datetime.datetime.utcnow()<br>}<br>record_id = mydb.mytable.insert(myrecord)<br>print(record_id)<br>print(mydb.collection_names())</pre><p>Ref: <a href="http://www.bogotobogo.com/python/MongoDB_PyMongo/python_MongoDB_pyMongo_tutorial_connecting_accessing.php">http://www.bogotobogo.com/python/MongoDB_PyMongo/python_MongoDB_pyMongo_tutorial_connecting_accessing.php</a></p><blockquote><strong>Debug tools: Robo 3T — 1.2 (macOS Version)</strong></blockquote><p><strong>Access mongodb through UI tools for convenient</strong></p><p>Ref: <a href="https://robomongo.org/">https://robomongo.org/</a></p><blockquote><strong><em>Flask Service</em></strong></blockquote><blockquote><strong>Expected specification</strong></blockquote><ul><li>Restful API</li><li>access mongodb</li><li>ORM (Bonus)</li><li>class-based views</li><li>PEP8 (Bonus) (undone)</li><li>Design Pattern (Bonus) (undone)</li></ul><blockquote><strong>The method I adopted</strong></blockquote><ul><li>Utilize package “<strong>mongoengine</strong>” to implement ODM (Object Document Mapper) with <strong>mongoDB</strong></li><li>Utilize the <strong>flask native method</strong> to implement <strong>Restful api (Class-based views)</strong></li></ul><p><a href="https://tw.wxwenku.com/d/100579854">https://tw.wxwenku.com/d/100579854</a></p><p><a href="https://github.com/flyhigher139/restapi_example">https://github.com/flyhigher139/restapi_example</a></p><p>p.s. <a href="https://stackoverflow.com/questions/12261866/what-is-the-difference-between-an-orm-and-an-odm">Difference between ODM/ORM</a></p><blockquote><strong>Candidate choice (but the db is sqlite not mongodb)</strong></blockquote><ul><li>Utilize package “<strong>sqlalchemy</strong>” to implement ORM (Object-Relational Mapper) with <strong>sqlite</strong></li><li>Utilize package “<strong>flask.ext.restful</strong>” to implement <strong>Restful api</strong></li></ul><p><a href="http://seanlin.logdown.com/posts/239771-use-flask-to-create-restful-api">http://seanlin.logdown.com/posts/239771-use-flask-to-create-restful-api</a></p><p><a href="https://github.com/seanlin0800/22kjobs">https://github.com/seanlin0800/22kjobs</a></p><blockquote><strong>Candidate choice (but the ODM is not implemented)</strong></blockquote><ul><li>No implement the ODM, just use the PyMongo to access the <strong>mongodb</strong> directly</li><li>Utilize package “<strong>flask_restful</strong>” to implement <strong>Restful api</strong></li></ul><p><a href="http://salmanwahed.github.io/2015/05/01/flask-restful-mongodb-api/">http://salmanwahed.github.io/2015/05/01/flask-restful-mongodb-api/</a></p><p><a href="https://github.com/chaitjo/flask-mongodb/blob/master/api.py">https://github.com/chaitjo/flask-mongodb/blob/master/api.py</a></p><blockquote><strong>Candidate choice (but Restful api is not implemented; db is sqlite)</strong></blockquote><ul><li>Utilize package “<strong>sqlalchemy</strong>” to implement ORM (Object-Relational Mapper) with <strong>sqlite</strong></li></ul><p><a href="https://blog.techbridge.cc/2017/08/12/python-web-flask101-tutorial-sqlalchemy-orm-database-models/">https://blog.techbridge.cc/2017/08/12/python-web-flask101-tutorial-sqlalchemy-orm-database-models/</a></p><blockquote><strong>Debug tools: Postman — 6.0.10 (macOS Version)</strong></blockquote><p><strong>Test if the api as expected (including request/response format)</strong></p><p>Note: When json format string is passed, the one (key | value) of headers must be set (<strong>Content-Type | application/json</strong>)</p><p>Ref: <a href="https://www.getpostman.com/apps">https://www.getpostman.com/apps</a></p><blockquote><strong>Debug tools: Robo 3T — 1.2 (macOS Version)</strong></blockquote><p><strong>Check if the api really store/load data into/from mongodb</strong></p><p>Ref: <a href="https://robomongo.org/">https://robomongo.org/</a></p><blockquote><strong><em>Django blog website</em></strong></blockquote><blockquote><strong>Expected specification</strong></blockquote><ul><li>Get the data from mongodb through flask service</li><li>class-based views</li><li>Higher the degree of completion is, better</li><li>PEP8 (Bonus) (undone)</li><li>Design Pattern (Bonus) (undone)</li></ul><blockquote><strong>Beginning — Build a similar blog</strong></blockquote><p>Ref: Follow the following tutorial ch1~ch8</p><p><a href="https://github.com/zmrenwu/django-blog-tutorial">https://github.com/zmrenwu/django-blog-tutorial</a></p><p>Usage:</p><ul><li>Good UI (Take use of its template)</li><li>Refer to its models (Post/comment)</li><li>List a list of posts/ list a detailed post</li></ul><p>Modification:</p><ul><li>Micro changes to UI and models</li><li>Get data from flask APIs not sqlite</li></ul><blockquote><strong>Add the function of Create/Update/Delete Post</strong></blockquote><p>Ref: Refer to the DjangoGirls Project I have ever been involved with.</p><p><a href="https://github.com/hsiang-ever/djangogirls">https://github.com/hsiang-ever/djangogirls</a></p><p>Usage:</p><ul><li>PostForm to create/edit post</li></ul><p>Modification:</p><ul><li>Micro changes to model from to meet the built models</li><li>Store data (create/update) to mongodb through flask</li></ul><p>Add:</p><ul><li>Delete data(post) to mongodb through flask</li></ul><blockquote><strong>Add the function of Create/Read comment in the post</strong></blockquote><p>Ref: Refer to the following tutorial in ch12, ch13</p><p><a href="https://github.com/zmrenwu/django-blog-tutorial">https://github.com/zmrenwu/django-blog-tutorial</a></p><p>Usage:</p><ul><li>Comment app (models, views, urls…)</li></ul><p>Modification:</p><ul><li>Access data source through flask</li></ul><blockquote><strong>Change the function-based views to class-based views</strong></blockquote><p>Ref: Refer to the following tutorial in ch18</p><p><a href="https://github.com/zmrenwu/django-blog-tutorial">https://github.com/zmrenwu/django-blog-tutorial</a></p><p>Usage:</p><ul><li>Class-based views for list posts/list a detailed posts</li></ul><p>Modification:</p><ul><li>Access data source through flask</li><li>Refer to the official docs to make other views to class-based</li></ul><p><strong>p.s. httphelp.py is the file for calling restful APIs provided by flask</strong></p><p>Ref: <a href="https://blog.csdn.net/qq_22795513/article/details/53170819">https://blog.csdn.net/qq_22795513/article/details/53170819</a></p><p>Note: The request and response between caller and callee should be noticed <strong>the type of passed data</strong></p><p>e.g.</p><pre># instance of Post class in models.py<br>ori_post = form.save(commit=False)<br># to_dict() is the method I defined to change instance to dict<br>str_json = json.dumps(ori_post.to_dict())<br># change json string to bytes<br>bytes = str_json.encode(‘utf-8’)<br># postPostDetail is API in flask for create Post<br>post = postPostDetail(bytes)</pre><p>p.s.</p><p><a href="https://stackoverflow.com/questions/19232011/convert-dictionary-to-bytes-and-back-again-python">json.dumps</a> is for change dict/array to json format string</p><p><a href="https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3">str_json.encode(‘utf-8’) is to convert string to bytes in Python 3</a></p><blockquote><strong><em>Deploy — </em>GCP (GAE)</strong></blockquote><h4><strong>Deployment order: mongodb -&gt; flask service -&gt; django</strong></h4><blockquote><strong>Deploy mongodb and flask service</strong></blockquote><p>Ref: <a href="https://cloud.google.com/python/getting-started/deploy-mongodb">Tutorial</a></p><blockquote><strong>Deploy django blog website</strong></blockquote><p>Ref: <a href="https://cloud.google.com/python/django/flexible-environment">Tutorial</a></p><h4>Deployment Info</h4><blockquote><strong>mongodb</strong></blockquote><p>Deployment tool : mLab</p><p>Management website: <a href="https://mlab.com/home">https://mlab.com/home</a></p><blockquote><strong>Flask service deployment</strong></blockquote><p>Deployment tool : Google App Engine Flexible Environment (GAE)</p><p>Deployed url (Stopped): <a href="https://shorten-url-1491815099304.appspot.com/">https://shorten-url-1491815099304.appspot.com/</a></p><p>Management website: <a href="https://console.cloud.google.com/appengine/versions?project=shorten-url-1491815099304&amp;serviceId=default&amp;versionssize=50">https://console.cloud.google.com/appengine/versions?project=shorten-url-1491815099304&amp;serviceId=default&amp;versionssize=50</a></p><p>Github Repo: <a href="https://github.com/hsiang-ever/flask_restful_api">https://github.com/hsiang-ever/flask_restful_api</a></p><blockquote><strong>Django blog website deployment</strong></blockquote><p>Deployment tool : Google App Engine Flexible Environment (GAE)</p><p>Deployed url: <a href="https://django-blog-202810.appspot.com/">https://django-blog-202810.appspot.com/</a></p><p>Management website: <a href="https://console.cloud.google.com/appengine/versions?project=django-blog-202810&amp;serviceId=default&amp;versionssize=50">https://console.cloud.google.com/appengine/versions?project=django-blog-202810&amp;serviceId=default&amp;versionssize=50</a></p><p>Github Repo: <a href="https://github.com/hsiang-ever/django_blog">https://github.com/hsiang-ever/django_blog</a></p><blockquote><strong>Review and Improvement</strong></blockquote><ul><li>f2e UI including html/css should be practiced more.</li><li>Observe the resources and project SPEC to decide which cloud server is more proper to utilize.</li></ul><p>Project Done by Shawn Shao on 05/02/2018, <a href="https://www.linkedin.com/in/chih-hsiang-shao/">LinkedIn</a>, <a href="https://github.com/hsiang-ever">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e5e6b2ddef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Button In One-Form]]></title>
            <link>https://medium.com/@lucky23268/multi-button-in-one-form-407e1192c095?source=rss-ace8d9b2232------2</link>
            <guid isPermaLink="false">https://medium.com/p/407e1192c095</guid>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[submit]]></category>
            <category><![CDATA[dataform]]></category>
            <dc:creator><![CDATA[Shawn Shao]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 09:20:30 GMT</pubDate>
            <atom:updated>2018-09-09T09:20:30.710Z</atom:updated>
            <content:encoded><![CDATA[<h4>Submit form and redirect to different page by different buttons</h4><blockquote><strong>Opinion One</strong></blockquote><blockquote>Use multi-buttons (input or button) with type “submit”. After the button is clicked, the delegated form will be triggered by the event “submit”. Then, recognize which button is clicked by attributes of button (might be name, user-defined, or others).</blockquote><h4>Difficulties</h4><ul><li>The order of the triggered event (“submit” and “click”)</li><li>If “submit” event is triggered first, then <strong>is it able to trace which selector(button)</strong> delegate the “submit” to the form or <strong>how to get the attribute of button in submit handler</strong>. If “click” event is triggered first, then get the attribute(id, name, or user-defined) of button in handler and make this variable global in order that the “submit” handler can retrieve the variable.</li></ul><h4>Final Decision</h4><blockquote>Not Adopted.</blockquote><ul><li>There is no resource found for the order of “submit” and “click”. Perhaps the order of “submit” and “click” can be known through try-and-error. Assume that the “submit” event is triggered first, there is no resource found for getting attributes of button in submit handler. Assume that the the “click” event is triggered first, which might be easier to deal with, listen to each button “click” event, but each of handler is just for getting the button/input attributes…kinda redundant, messy, or weird at first sight.</li><li>Most important of all, adopting this method, button must in the form scope, i.e., the button/input outside form cannot delegate the “submit” event to form.</li></ul><blockquote><strong>Opinion Two</strong></blockquote><blockquote>Make all button/input(selector) delegate the click event to their common parent. In handler, manually retrieve the form element, generate the formdata, and send it to server</blockquote><h4>Difficulties</h4><ul><li>How to manually get the form element including data inside instead of native form listening to submit event</li><li>What’s the data type of the form could be sent to the server</li></ul><h4>Final Decision</h4><ul><li>The button/input not in the form scope is feasible using this method</li><li>There is no need to write two kinds event handler “click” and “submit”</li></ul><h4>Implementation</h4><ul><li>Method 1: Get form, tune config, and submit it by native form submit method</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2FShawnShao%2Fembed%2Fpreview%2FGXyNdm%3Fheight%3D600%26slug-hash%3DGXyNdm%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2FShawnShao%2Fpen%2FGXyNdm%3Feditors%3D1010&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a65b8782fc1d3347caa884b07aad0d/href">https://medium.com/media/40a65b8782fc1d3347caa884b07aad0d/href</a></iframe><blockquote>NOT ADOPTED!</blockquote><p>It depends on the native submit event of form. After the form is sent to the server, the page is refreshed — the data is handled on the server side. That is, <strong>the submit() function doesn’t actually return anything, it just sends the form data to the server.</strong></p><ul><li>Method 2: Utilize the serialize method and send to server by ajax</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2FShawnShao%2Fembed%2Fpreview%2FMqrbZx%3Fheight%3D600%26slug-hash%3DMqrbZx%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2FShawnShao%2Fpen%2FMqrbZx%3Feditors%3D1010&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/652ee16cd0902830acd1b65cf6411785/href">https://medium.com/media/652ee16cd0902830acd1b65cf6411785/href</a></iframe><blockquote>NOT ADOPTED!</blockquote><p>The files attached in form (input type=”file”) cannot be sent together with serialized form data.</p><ul><li>Method 3: Utilize FormData class with ajax</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2FShawnShao%2Fembed%2Fpreview%2FzJpogx%3Fheight%3D600%26slug-hash%3DzJpogx%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2FShawnShao%2Fpen%2FzJpogx%3Feditors%3D1010&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/db2397ce8e56f0592b86cccdcc56b928/href">https://medium.com/media/db2397ce8e56f0592b86cccdcc56b928/href</a></iframe><blockquote>ADOPTED!!!</blockquote><p>The files attached in form can be sent to the server. In addition, it is easy to append other data into FormData instance. Note that contentType:false and processData:false should be added into ajax; otherwise, the files cannot be sent together.</p><p><strong>Reference</strong></p><ul><li><a href="https://stackoverflow.com/questions/374644/how-do-i-capture-response-of-form-submit">How do I capture response of form.submit</a></li><li><a href="https://stackoverflow.com/questions/41684385/how-to-add-file-value-with-jquery-serialize">How to add file value with jQuery serialize()</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=407e1192c095" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code (Agile Software Craftsmanship Handbook)]]></title>
            <link>https://medium.com/@lucky23268/clean-code-agile-software-craftsmanship-handbook-b384cf3cb48a?source=rss-ace8d9b2232------2</link>
            <guid isPermaLink="false">https://medium.com/p/b384cf3cb48a</guid>
            <category><![CDATA[principles]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Shawn Shao]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 14:38:19 GMT</pubDate>
            <atom:updated>2018-08-23T14:42:14.374Z</atom:updated>
            <content:encoded><![CDATA[<h4>Following is the principles I realize and want to follow mentioned in this book. Let’s clean code.</h4><h3>Meaningful Naming</h3><blockquote><strong>Intention-representative Name</strong></blockquote><p>Make it easier to recognize the real meaning when using “Auto-completion” or “context-sensitive” prompt.</p><pre>// elapsed time in days<br>int d; //BAD<br>int elaspedTimeInDays; //GOOD</pre><pre>// Never naming by sequence of numbers (a1, a2, ..., aN)<br>a2[i] = a1[i]; // BAD</pre><blockquote><strong>Avoid the misleading</strong></blockquote><p>Use the name we can recognize or guess it at first sight.</p><pre>// Type or container in variable name mislead its real type<br>String[] accountList; //BAD<br>String[] bunchOfAccounts; //GOOD</pre><pre>// It’s not easy to distinguish “l” from “1” and “O” from “0”<br>a=O1; // BAD<br>l=01; // BAD</pre><pre>// Long and similar name takes time to recognize<br>// (in &quot;Auto-completion&quot; likewise)<br>XYZControllerForEfficientHandlingOfStrings; // BAD<br>XYZControllerForEfficientStoreageOfStrings; // BAD</pre><blockquote><strong>Speakable Name</strong></blockquote><p>Speakable words make it easier to discuss with co-workers.</p><pre>genymdhms // BAD<br>generateTimestamp // GOOD</pre><blockquote><strong>Avoid Member Prefixes</strong></blockquote><pre>m_dsc // indicate a member variabel<br>IShapeFactory // indicate a interface</pre><blockquote><strong>The length of the naming should correspond to the size of the scope.</strong></blockquote><pre>// single letter is allowed in small scope<br>for(int i=0; i&lt;length; i++) {}</pre><blockquote><strong>Determine one consistent word for each abstract concept</strong></blockquote><pre>fetch<br>retrieve<br>get (My choice)</pre><h3>Function</h3><blockquote><strong>SHORT!!!</strong></blockquote><p>First and Last Principle</p><blockquote><strong>“ONLY” DO ONE THING!!! (One thing refer to one layer of abstract.)</strong></blockquote><p>Efficient and effective way to check if the function conform to the principle is to try to extract another function from it.</p><blockquote><strong>Signature (function name and parameters)</strong></blockquote><ul><li><em>Meaningful function name. (Naming can take the parameter into consideration, which combined into verb. or noun.)</em></li></ul><pre>write(name); // function is for write name</pre><ul><li><em>Less the number of the parameters. (Zero or one parameter is the best.)</em></li></ul><p>Too many parameters lead to one more pitfall. (Occurred by the positional parameters)</p><pre>// takes time to check the order<br>assertEquals(expected, actual);<br>// Solved method: Function Naming<br>assertExpectedEqualsActual(expected, actual);</pre><ul><li><em>Less passing parameter by value, more usage of instance variable. (Utilize the OOP)</em></li></ul><pre>writeField(outputStream, name); // BAD<br>// Make the outputStream as the instance variable<br>writeField(name); // GOOD</pre><ul><li><em>Don’t take the flag (boolean value) as parameter</em></li></ul><p>It is apparent that the function MUST do one more things.</p><pre>render(boolean isSuite) // BAD<br>// GOOD -&gt; Split above into two parts<br>renderForSuite()<br>renderForSingleTest()</pre><blockquote><strong>DRY (Don’t Repeat Yourself)</strong></blockquote><p>More repeat (redundant), more load on it once revise is needed.</p><blockquote><strong>Separate Command from Query (Each of them is one thing.)</strong></blockquote><pre>// BAD<br>if(set(&quot;username&quot;, &quot;unclebob&quot;)) ...<br>// GOOD<br>if(attributeExists(&quot;username&quot;)) {<br>    setAttribute(&quot;username&quot;, &quot;unclebob&quot;);<br>}</pre><blockquote><strong>Exception Handling replace the Error Code</strong></blockquote><p>Using “Error Code” would lead to much more nested if statement and force caller to handle the error immediately.</p><p>Note that try/catch should be extracted from the function. (Function do one thing; Exception Handling is one thing also.</p><h3>Comment</h3><blockquote><strong>Use the minimum amount of comment</strong></blockquote><p>Perfectly naming the function, parameter, and return value make a minimum comment.</p><blockquote><strong>Beneficial Comment</strong></blockquote><ul><li><em>Warnings of Consequence</em></li></ul><pre>//Don&#39;t run unless you have some time to kill</pre><ul><li><em>TODO</em></li></ul><pre>// TODO: These are not needed<br>// We expect this to go away when we do the checkout model</pre><blockquote><strong>Terrible Comment</strong></blockquote><ul><li><em>Lack of accuracy/precise, mislead, or lies</em></li></ul><p>Comment which have no clear explain or make programer misunderstand.</p><ul><li><em>Log-type, source and signature, or comment the code</em></li></ul><pre>// Log-type<br>* 11-Oct-2011 : Re-organized the xxxx<br>* 05-Nov-2011 : Added a getDescription() method, xxxx</pre><pre>// source and signature<br>/* Added by Rick */</pre><pre>// Comment the code<br>this.bytePos = writeBytes(pngIdBytes, 0);<br>//hdrPos = bytePos;<br>writeHeader();<br>//dataPos = bytePos;</pre><p>Comment the code would make us unable to figure out what its meaning. Important?? Will be use/modify in the future?? Useless?? Unrelated??</p><p>The purpose of the above is to record the history of modifying code, which can be achieved by the VCS such as git.</p><ul><li><em>Disturbing-type or rules-type</em></li></ul><p>Each variable is added a comment…</p><pre>// Disturbing-type<br>/**<br> * Default constructor<br> */<br>protected AnnualDateRule() {}</pre><h3>Arrangement</h3><blockquote><strong>Vertical Arrangement</strong></blockquote><ul><li><em>Vertical Space between concepts</em></li></ul><p>Each block represent a concept, space is necessary between different concepts. That is to say, vertically close blocks are closely related.</p><ul><li><em>Callee function should be right below the caller function</em></li><li><em>Local Variables should be declared at the top of the function</em></li></ul><pre>private static void readPreferences() {<br>    InputStream is = null;<br>    try {<br>        is = xxxx<br>        ...<br>}</pre><ul><li><em>Control Variable of the loop should be declared in the loop</em></li></ul><pre>for (Test each: tests)<br>    count += each.countTestCases();</pre><ul><li><em>Instance Variables should be declared at the top of the class</em></li></ul><blockquote><strong>Horizontal Arrangement</strong></blockquote><ul><li><em>Space besides the assignment operator make it more significant.</em></li><li><em>Space emphasizes the precedence of the operators.</em></li></ul><pre>return b*b - 4*a*c;</pre><h3>Object and Data Structure</h3><blockquote><strong>Comparison between Object and Data Structure on CONCEPT</strong></blockquote><ul><li><em>Object expose its behavior and hide its internal data.</em></li><li><em>Data Structure expose its data and none meaningful functions are provided.</em></li></ul><blockquote><strong>Comparison between Object and Data Structure on Code</strong></blockquote><ul><li><em>(OO) It’s easy to add the new type of class without modifying original method. On the contrary, it’s hard to add new method since all classes h must be modified.</em></li><li><em>(Procedural) It’s easy to add new functions without modifying original data structure. On the contrary, it’s hard to add new data structure since all functions have to must be modified.</em></li></ul><blockquote><strong>DTO (Data Transfer Objects)</strong></blockquote><p>Definition: Optimal form of data structure. Only public variables, none methods in the class.</p><p>Common Use: Conversion from “Raw Data in Database” to “Object in the app”</p><blockquote><strong>Active Records</strong></blockquote><p>Definition: A Special DTO. Often owns “save” and “find” methods for browsing.</p><p>Common Use: Convert from the tables in database or raw data.</p><p>Pitfall: Developers often count these kind of data structure as objects and add the business model methods into it.</p><p>Note: Active Records only can be regarded as the pure data structure. Additionally create a new class including business model methods and hiding internal data which might be the instances of active records.</p><h3>Error Handling</h3><blockquote><strong>Exception Handling instead of Error Code</strong></blockquote><ul><li><em>Try-Catch-Finally Statement occurs at the beginning</em></li><li><em>Narrow down the Exception Type</em></li><li><em>Provide Related Info the cause of exception</em></li></ul><blockquote><strong>Define Exception Class on the aspect of Caller</strong></blockquote><ul><li><em>Wrapper is good implementation tips to wrap the third party lib (APIs)</em></li></ul><blockquote><strong>DO NOT Return Null and Pass Null</strong></blockquote><ul><li><em>SPECIAL CASE PATTERN can be adopted to avoid it.</em></li></ul><h3>Boundary</h3><blockquote><strong>Learning Test</strong></blockquote><p>The test specifically and additionally written for the third party libs (APIs), which is for exploring and realizing them.</p><blockquote><strong>Clear borders between code</strong></blockquote><p>Use <strong>Wrapper</strong> to wrap the lib or <strong>Adapter</strong> to transform pre-defined interface to the third party interface.</p><h3>Unit Test</h3><blockquote><strong>Three Laws of TDD (Test-Driven Development)</strong></blockquote><ol><li><em>Never write the production code before the unit test</em></li><li><em>Only write the unit test just cannot pass</em></li><li><em>Only write the production code just pass the failed unit test</em></li></ol><blockquote><strong>Clean Test</strong></blockquote><ul><li><em>Double Standard in Production and test</em></li></ul><p>Production environment is different from testing environment and what they focus on also differs.</p><ul><li><em>One test, one concept (Less assert, the better)</em></li><li><em>F.I.R.S.T.</em></li></ul><p>Fast, Independent, Repeatable, Self-Validating, Timely</p><blockquote><strong>Importance of test</strong></blockquote><p>With test code, the flexibility, maintenance, and the reuse of the production could be enhanced.</p><h3>Class</h3><blockquote><strong>One Class, One Responsibility</strong></blockquote><p>Follow the SRP (Single Responsibility Principle)</p><blockquote><strong>Cohesiveness</strong></blockquote><p>Each method in class should manipulate at least one or more instance variables. More instance variables a method manipulates, the more cohesive to the class. The tip is that the way to <em>high cohesiveness</em> is the way to make the <em>class</em> shorter or smaller, i.e., <em>SRP</em>.</p><blockquote><strong>Isolation</strong></blockquote><p>Follow the DIP (Dependency Inversion Principle), which describes that the class depends on abstract concept not concrete details.</p><pre>public interface StockExchange {<br>    Money currentPrice(String symbol);<br>}</pre><pre>public Portfolio {<br>    private StockExchange exchange;<br>    public Portfolio(<strong>StockExchange</strong> exchange) {<br>        this.exchange = exchange;<br>    }<br>    // ...<br>}</pre><p>For example, TokyoStockExchange class implements the StockExchange interface. And confirm that Portfolio constructor takes the StockExchange as parameter. <strong>Portfolio class depends on StockExchange interface instead of the implementation details of the TokyoStockExchange class.</strong></p><p>Without the coupling (dependency), the effect of the isolation, isolation from revise and isolation from elements, in system is better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b384cf3cb48a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install Python Modules Offline]]></title>
            <link>https://medium.com/@lucky23268/install-python-modules-offline-e577eec90615?source=rss-ace8d9b2232------2</link>
            <guid isPermaLink="false">https://medium.com/p/e577eec90615</guid>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[wheels]]></category>
            <category><![CDATA[offline]]></category>
            <category><![CDATA[install]]></category>
            <dc:creator><![CDATA[Shawn Shao]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 03:11:58 GMT</pubDate>
            <atom:updated>2018-08-23T03:15:26.254Z</atom:updated>
            <content:encoded><![CDATA[<p>OS: Windows 10; Windows Server 2012 R2</p><blockquote>Preceding Operation</blockquote><blockquote>Option 1: pip cmd</blockquote><pre># -d: Download packages into &lt;dir&gt;<br># download the newest version of module into offline_package dir<br>&gt; pip download -d offline_package/ module_name</pre><p><strong>Related options for pip download cmd</strong></p><p>-r: Install from the given requirements file<br>--python-version: Only download wheels compatible with Python interpreter version &lt;version&gt;<br>-no-index: Ignore package index (only looking at --find-links URLs instead)<br>--find-links: If a url or path to an html file, then parse for links to archives</p><p><strong>Notes: Specify version of the module might lead to downloading the compressed file(.tar.gz) instead of wheel file</strong></p><blockquote>Option 2: Grab wheel file from website</blockquote><p><a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/#pip">Unofficial Windows Binaries for Python Extension Packages</a> by <a href="https://www.lfd.uci.edu/~gohlke/"><strong>Christoph Gohlke</strong></a></p><blockquote>Install module offline</blockquote><pre>&gt; python -m pip install module_name</pre><p>Ref:</p><p><a href="https://pip.pypa.io/en/stable/reference/pip_download/#usage">https://pip.pypa.io/en/stable/reference/pip_download/#usage</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e577eec90615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unable to Post Files with Chinese Name (Python)]]></title>
            <link>https://medium.com/@lucky23268/post-method-with-files-through-requests-module-python-48ba33256eea?source=rss-ace8d9b2232------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ba33256eea</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[post]]></category>
            <category><![CDATA[request]]></category>
            <category><![CDATA[issues]]></category>
            <dc:creator><![CDATA[Shawn Shao]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 14:51:52 GMT</pubDate>
            <atom:updated>2018-09-07T14:55:58.954Z</atom:updated>
            <content:encoded><![CDATA[<h4>Issue: Unable to post files with Chinese filename through requests module in Python</h4><h4>Reproduce</h4><p>Send files with Chinese name make uploading files failed</p><pre># filePath refer to the Chinese file, e.g. &quot;測試檔案.txt&quot;<br>with open(filePath, &#39;rb&#39;) as f:<br>    r = requests.post(url=&quot;&quot;, data=payload, files={&#39;file&#39;: f})</pre><h4>Root Cause</h4><p><strong><em>requests </em></strong>module call <strong><em>urllib3 </em></strong>module (fields.py) which can not successfully resolve the file with Chinese Name</p><p>My site-packages Path: venv\Lib\site-packages\urllib3\fields.py</p><h4>Solution</h4><blockquote>dict of files parameter: the value of the ‘file’ could be a 3-elements tuple, which are <strong>file name</strong>, <strong>file object</strong>, and <strong>file type</strong> respectively. If <strong>file name</strong> and <strong>file type</strong> are optional, and default value are used if not provided.</blockquote><blockquote>e.g. {&#39;file&#39;: (&#39;foo.png&#39;, open(&#39;foo.png&#39;,&#39;rb&#39;), &#39;image/png&#39;)}</blockquote><pre># pass the real file name (Chinese name) by payload<br>payload[&#39;file_name&#39;] = chtFileName<br># Use randomly set file name &#39;1&#39; instead of default value<br>with open(filePath, &#39;rb&#39;) as f:<br>    r = requests.post(url=&quot;&quot;, data=payload, files={&#39;file&#39;:(&#39;1&#39;, f)})</pre><p>On the server side, replace the randomly set file name, ‘1’, with the real file name in payload.</p><p>Reference</p><p>Root Cause Detail: <a href="https://github.com/requests/requests/issues/2117">https://github.com/requests/requests/issues/2117</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ba33256eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[夕陽餘暉下的平行時空]]></title>
            <link>https://medium.com/@lucky23268/%E5%A4%95%E9%99%BD%E9%A4%98%E6%9A%89%E4%B8%8B%E7%9A%84%E5%B9%B3%E8%A1%8C%E6%99%82%E7%A9%BA-c705fe47bd01?source=rss-ace8d9b2232------2</link>
            <guid isPermaLink="false">https://medium.com/p/c705fe47bd01</guid>
            <category><![CDATA[timeline]]></category>
            <category><![CDATA[sunset]]></category>
            <dc:creator><![CDATA[Shawn Shao]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 14:42:49 GMT</pubDate>
            <atom:updated>2018-08-04T15:41:29.238Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Everyone owns its timeline.</blockquote><p>一個在平常不過的一天，傍晚到來，一如往常總會有人在這個時候帶著小黃(小狗)到附近走走溜溜，而今天卻意外的特別，我和姊姊們不約而同的放下手邊的事情，往大甲溪堤岸走去，不知道有多久沒有和家人一起出來走走，即使只是離家不到1km的大甲溪堤岸。</p><p>在路程中，我們聊著彼此生活中的趣事，以輕笑的口吻訴說著歲月那把刀帶來的種種，以正經的語氣傾訴著買車買房結婚的那些現實面。</p><p>走到了一如既往讓小黃展現牠跳躍與奔馳的大片草原，看著那個青澀又青春的影子，我漸漸走向草原旁眺望著大甲溪畔與夕陽，此時我的背影是稚嫩？成長茁壯？又或是衰退的呢？連Probation都還沒過的我，到底在擔憂著什麼呢？</p><blockquote>靜靜的望著，再大的事情在這無邊無際的景色中都變得微不足道。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_Bhz7Tmzg4e6nG_qR9-Zw.jpeg" /><figcaption>享受著這夕陽餘暉</figcaption></figure><blockquote>Slow down and clean. (緩下腳步歸零自己)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c705fe47bd01" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>