<?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 spff on Medium]]></title>
        <description><![CDATA[Stories by spff on Medium]]></description>
        <link>https://medium.com/@spff?source=rss-fc12e7c24e8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G7e4va8LuRJjIGHEMffF4Q.jpeg</url>
            <title>Stories by spff on Medium</title>
            <link>https://medium.com/@spff?source=rss-fc12e7c24e8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:00:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@spff/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[Programming for normal guy]]></title>
            <link>https://medium.com/@spff/programming-for-normal-guy-6fb6c0a17459?source=rss-fc12e7c24e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb6c0a17459</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[spff]]></dc:creator>
            <pubDate>Tue, 05 Nov 2019 17:47:51 GMT</pubDate>
            <atom:updated>2023-11-16T14:34:01.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>Programming for normal guy (Index)</h3><p>There are too many books teaching a certain programming language.</p><p>I think only linguists would read a dictionary page by page, normal people look up when they need. Those books are targeting audience who want to be a full-time programmer or a master of C/C++/Java/…, so each book has around a thousand pages, and the chapters arranged like below.</p><blockquote>Topic A<br> easy… p.1~30<br> hard… p.31~150<br>Topic B<br> easy… p.151~180<br> hard… p.180~300<br>…<br>Topic Z<br>…</blockquote><p>Those Topics might not have dependencies to each others, but most readers read sequentially and give up at p.250.</p><p>What’s more frustrating? Your first program is just printing a Hello World. Who is going to cheer for the dumb Hello World? Show me something interesting!</p><p>I believe in the near future, everybody will be able to do some little programming, but instead of “building a complex system”, it’ll rather be “scripting”, you may take advantage to accelerate your daily routine even you’re not a full-time programmer :D</p><p>The best way to learn programming is to perform Observing &amp; Modifying back and forth.</p><p>Let’s get started~</p><h4>Lesson 0</h4><p>Install Python 3</p><h4>Lesson 1</h4><ol><li>copy &amp; paste the code below, save it as main.py, or directly save the file <a href="https://gist.githubusercontent.com/spff/b8bbe09e53bcf01f3bb6dc8cf1f80c9a/raw/7015546d60d772ef745545f53006b04a89baf970/main.py">https://gist.githubusercontent.com/spff/b8bbe09e53bcf01f3bb6dc8cf1f80c9a/raw/7015546d60d772ef745545f53006b04a89baf970/main.py</a></li><li>open your terminal(terminal or cmd)</li><li>run it python main.py(or python3 main.py, depend on your environment)</li><li>observe it, try edit it as you want and run again. you’ll finally understand all the code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f81fc6d766da0846277f7f847089839/href">https://medium.com/media/8f81fc6d766da0846277f7f847089839/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb6c0a17459" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[給非資訊本科的計概二-如何快速上手]]></title>
            <link>https://medium.com/@spff/%E7%B5%A6%E9%9D%9E%E8%B3%87%E8%A8%8A%E6%9C%AC%E7%A7%91%E7%9A%84%E8%A8%88%E6%A6%82%E4%BA%8C-%E5%A6%82%E4%BD%95%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B-319a2be7465b?source=rss-fc12e7c24e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/319a2be7465b</guid>
            <dc:creator><![CDATA[spff]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 07:00:04 GMT</pubDate>
            <atom:updated>2018-11-20T06:29:56.614Z</atom:updated>
            <content:encoded><![CDATA[<p>恭喜你取得國外一流大學碩士，開學後Boss丟了個巨大無比的專案，充滿前輩們的心血。很不幸地你的教授剛帶著一位博士生來到這間學校開疆拓土，其他學長姐都不在旁邊，運氣不錯的是還有些許安裝文件和散落在程式碼間的註解，你照著打了一堆不曉得在幹嘛的指令以後可以跑成功了，卻對接下來的擴充和修改沒有頭緒。這篇文章正是要講如何快速上手既有的專案。</p><p>這篇文章假設你已經看過路上的計概書籍，寫過很基本的小程式，了解基本電腦元件(知道自己裝電腦要買啥以及用途)，所以我標題寫計概二</p><p>首先要說明幾點事實</p><ol><li>只有很少數的情況你會從頭打造一個Project，就算是，難免有改別人程式碼的需求。例如你用到的一個好用套件有bug，原作者因為種種原因無法繼續維護，或是你有特別的功能上的需求。</li><li>如同十個經濟學家會有十一個不同的經濟論點，同功能同語言的不同專案也會有不同的架構和書寫慣例，維護既有的程式碼不一定比從頭自幹來得容易。</li><li>大家都知道要寫註解和文件，恩。。。如果你遇到的話，你運氣不錯。</li><li>環境的架設從來就不是一件簡單的事。如果你在為如何修改程式碼而煩惱，回過頭看，你已經越過很大的坑了，加油~~~</li></ol><blockquote>上手一個專案好比入侵一個網站，經驗玩家在感知哪些地方可能有潛在漏洞以及或許可行的攻破手法就是比新手厲害，這仰賴<strong>經驗</strong>以及<strong>對背後的運作機制的了解</strong>，我認為本科的優勢也在此。接下來我會分享一些運作機制的概觀以及從我經驗歸納出的小技巧。</blockquote><ol><li>電腦就是一堆電路所組成的，其運算的核心部分和小時候學到的那種基本電路的差別在於有時鐘(振盪器，關鍵字：時序邏輯電路)。除此之外還有邏輯閘來輔助運算，邏輯閘的組合可以實現更多複雜運算，還可以存狀態(關鍵字：latch)。電腦在插電以後就會有設定好的電路開始運作，所有的電路串在一起達成使用者看到的螢幕會亮、有螢幕畫面、鍵盤滑鼠可操作。</li><li>CPU廠商會定義電路接腳的操作方法，例如某幾隻腳有通電的時候把另外幾隻腳的通電情況當作資料，做某種數學運算，在振盪器經過幾次振盪以後可以從其他腳的通電情況得到結果。數位電路每隻腳只有高電壓和低電壓，用來表示二進位，這些操作方法叫做指令，操作方法的集合叫做指令集。<br>實際上的CPU功能更複雜，廠商把上面提到的運算核心電路包起來，把核心的輸出入接到一塊可以存狀態的暫存器電路(由上面提到的latch組成)，這樣一來前一個指令的運算結果在沒被覆蓋的前提(因為暫存器的空間有限)就可以在之後的指令拿來使用，把核心包起來的外面這層電路具備一連串從外部記憶體讀取指令的機制、載入指令集、把暫存器的數值往外寫到記憶體(因為暫存器的空間有限)，或是把記憶體的數值載入到暫存器供之後的指令使用。(關鍵字：Machine code、Instruction pipelining)<br>然後其他硬碟的位置、螢幕畫面每個點要顯示的位置啥的對CPU來說都是記憶體的操作，區分的工作是主機板上的晶片會處理的。(關鍵字：MMU)</li><li>主機板廠商生產跟特定CPU規格相容可以連接周邊電路的板子，通電的時候會有一塊電路把該初始化的其他電路初始化，啟動CPU去讀某塊儲存電路的內容，裡面存的都是一堆指令和資料，指令的內容就是做事或是讀其他塊的指令，然後一連串地讀取和運算的執行完成整個開機的動作，讀取的動作直到開完機還會持續直到電源關閉，這中間很多閒置的時間就是你的作業系統會輪詢有沒有新的事件(除了輪詢還有更高級的機制，關鍵字：中斷)。所有的這一連串的指令內容都是人寫的，就只是很多時候人們寫比較好懂的語言再用工具轉換成機器的指令而非自己寫。</li><li>語言的種類繁多，不過有些共通點，像是很多時候做一件事的方法不只一種，但我不是很在乎到底怎麼做的而是只要能做到我要的一組事情即可。所以很多語言會支援把介面和實作拆開的語法，像是C家族的.h .hpp的header檔，Java的interface。 <strong>小技巧：看介面檔案可以讓你迅速看到這包程式的概觀</strong></li><li>因為打從開機以來就是一連串的指令的載入，程式一定會至少有一個進入點，有時候是main開頭的，或是第一行。不過當專案很大的時候，這個專案可能會是跑在一個框架底下，也就是會有其他人幫你開起一個程序，我們只是寫裡面一個功能，這在Java很常見，不過還是會有這個功能從哪邊開始的進入點。<strong>小技巧：找進入點</strong></li><li>如果只在乎某一包套件的使用有時候並不需要從最開始的進入點開始看，而是要看看外面有哪些地方使用到這包套件提供外部呼叫的端口(public function)，現代IDE按右鍵有很多選項可以輕鬆列出用到那些function的地方，function的介面宣告的地方，以及function實作的地方。<strong>小技巧：善用IDE尋找定義、介面、使用 的地方</strong></li><li>平時的圖形化介面(相對的詞語是指令介面)其實背後也是在呼叫一連串的指令，這裡的指令講的是作業系統”為使用者提供使用者介面”而非CPU指令集的指令(關鍵字：shell)</li><li>Shell中的指令大都是一個個的小程式，舉個例子 ls 會列出當前資料夾下的檔案，但你打 ls 的時候其實shell會在背後幫你呼叫叫做 ls 的程式，把他的輸出印在畫面上。如果你使用的是*nix系統，可以看看/bin底下的路徑就會知道哪些所謂的指令其實是小小的程式。</li><li>Git是個好用的東西，可以幫忙管理版本。不過在這邊不教如何使用，而是如同一個攻擊者在觀察網站的時候會看 robots.txt，原本只是用來告訴搜尋引擎說別爬這些路徑，觀察力敏銳的你一定會想到這裡搞不好有寶藏，畢竟窺探別人不想被看到的東西本身就是一件很有趣的事情啊~~~<br>回到Git，有個叫做 .gitignore的檔案描述哪些是修改完以後的提交中要直接無視的檔案，那些檔案很多都是中間產生的，現在的專案越來越複雜的情況下開發者會設定一層又一層的程式碼自動產生機制，如果你沒找到源頭而是修改中介檔，那下次clean build的時候你會哭。<strong>小技巧：用.gitignore區別原始檔案和自動生成的檔案</strong></li><li>Git的每筆提交都會包含提交者的註記、自動產生出來的這筆提交的唯一的代號、以及所有修改的檔案的變動。如果前人有良好的使用習慣，我們可以來一場時光旅行讓前輩來示範如何擴充這個專案<strong>小技巧：用git commit來觀察前人如何開發，路邊有很多圖形介面的git工具</strong></li><li>在程式的進入點之外還有很重要的是compile的進入點或規則，compile就是幫你把你寫的語言轉成機器的指令。有些語言不用一次轉到位(關鍵字：直譯)，不過多少還是有打包或是程式碼生成的階段，我們可以從這裡看出整個專案的結構，這種檔案像是make的 MakeFile, cmake的 CMakeLists.txt, gradle的 build.gradle, maven的 maven.xml, node的 index.js等等。<strong>小技巧：藉由描述&quot;打包/compile規則&quot;的檔案來了解專案結構</strong></li><li>網站的方面，一個基本的Http請求，Server吐回來的就是一坨資料，可以是任意格式，一般使用者上網的動作其實是如下動作：<br>使用者透過瀏覽器連線，Server吐了一個網頁的檔案，這個檔案包含三個區塊，HTML 和 CSS 描述<strong>在視窗畫畫的規則</strong>(因為視窗的比例和大小不固定，所以這裡用”規則”)<strong>，</strong>以及 JavaScript ，定義<strong>可以執行的邏輯</strong>，瀏覽器根據 HTML 和 CSS 區塊的定義來畫東西在視窗上，並根據 HTML 額外定義的一些欄位再去要其他資源檔案像是字體、圖片和更多的JavaScript區塊(可以引用外部的檔案)。然後視窗中的按鈕按下去有可能單純修改HTML ，瀏覽器會負責顯示最新的畫面以及畫動畫，也有可能會送新的HTTP 請求給Server，詳細要看這個網頁的定義。如果是送出請求，回來的資料就會根據JavaScript區塊的定義來更新 HTML 區塊，然後瀏覽器會看著 HTML 更新視窗畫面，達到互動的效果。</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=319a2be7465b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto Deploy AWS Lambda (Java8) with Gitlab CI]]></title>
            <link>https://medium.com/@spff/auto-deploy-aws-lambda-java8-with-gitlab-ci-34a408b0ebce?source=rss-fc12e7c24e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/34a408b0ebce</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[spff]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 12:01:55 GMT</pubDate>
            <atom:updated>2019-04-07T08:39:05.843Z</atom:updated>
            <content:encoded><![CDATA[<p>My supervisor asked me to build a simple backend service with AWS Lambda and the only request is it should be written in Java because we’re not familiar enough with JavaScript, and here I’m telling you how to build one.</p><p><strong>Requirement:<br></strong>1. GitLab Server (gitlab.com or your private one) &amp; Create a New Repo<br>2. GitLab Runner<br>3. AWS Account</p><h3><strong>GitLab Runner</strong></h3><p>Navigate to your repo’s Settings / CI/CD, you’ll find Auto DevOps. Great, that’s for those who already have their 3rd-party CI/CD. Let’s see the Runner below, we found Specific (auto/manual) / Shared / Group and let’s make a minimum viable GitLab Runner from scratch usingSetup a specific Runner manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmsJCkP8WouUBLn5QnH6wA.png" /></figure><h4>Installation</h4><p>Follow the link <a href="https://docs.gitlab.com/runner/install/">Install GitLab Runner</a>. My GitLab Runner is running on a Fedora server natively because I couldn’t make a successful installation via <a href="https://docs.gitlab.com/runner/install/docker.html">Install as a Docker service</a>.</p><p>Although I couldn’t make GitLab Runner as a docker service, I’m still able to use the <a href="https://docs.gitlab.com/runner/executors/docker.html">Docker executor</a> (you can navigate to this page via <a href="https://docs.gitlab.com/runner/install/#repositories">Install GitLab Runner#Repositories</a> -&gt; <a href="https://docs.gitlab.com/runner/install/linux-repository.html#prerequisites">Install using GitLab’s repository for Debian/Ubuntu/CentOS/RedHat # Prerequisites</a>).</p><p>The whole installation command would be sudo dnf install gitlab-runner docker.</p><h4>Registering Runners</h4><p>Follow the link <a href="https://docs.gitlab.com/runner/register/index.html#gnu-linux">Registering Runners</a> (ignore the Requirements. we’ve already done those).</p><ol><li>The step 6. shows why we were installing docker.</li><li>You can find the URL and token from theSetup a specific Runner manually inside the repo’s Settings / CI/CD.</li></ol><h4>Start</h4><p>Don’t forget to start it :D<br>You may also verify the status using gitlab-runner status.</p><h3>GitLab CI (Auto Deploy API Written in JavaScript)</h3><p>I learnt GitLab CI majorly from the article <a href="https://medium.com/@tarekbecker/a-production-grade-ci-cd-pipeline-for-serverless-applications-888668bcfe04">A production-grade CI/CD Pipeline for Serverless Applications</a> written by <a href="https://medium.com/u/74ffcb8f34b5">Tarek Becker</a>. Exploring the GitLab CI with his JavaScript version will be more time efficient because it takes time to compile the Java code.</p><p><strong>Some important things you should know.</strong></p><ol><li>You might encounter a lot of permission errors, you should give the account permissions shown below to get rid of the errors.<br><a href="https://console.aws.amazon.com/iam/home?region=us-east-1#policies/arn:aws:iam::aws:policy/AWSLambdaFullAccess">AWSLambdaFullAccess</a><br><a href="https://console.aws.amazon.com/iam/home?region=us-east-1#policies/arn:aws:iam::aws:policy/IAMFullAccess">IAMFullAccess</a><br><a href="https://console.aws.amazon.com/iam/home?region=us-east-1#policies/arn:aws:iam::aws:policy/AWSCodeDeployFullAccess">AWSCodeDeployFullAccess</a><br><a href="https://console.aws.amazon.com/iam/home?region=us-east-1#policies/arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator">AmazonAPIGatewayAdministrator</a><br><a href="https://console.aws.amazon.com/iam/home?region=us-east-1#policies/arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess">AWSCloudFormationReadOnlyAccess</a></li><li>Read the introduction (figure below) carefully, I’ve wasted hours debugging and finally found that my branch isn’t a protected branch but the variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY were protected (Umm… I was the murderer) so they weren’t set as the docker’s env variables and I was always getting Unable to locate credentials at the package stage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*x45QmpVwsmyQJUKtsGh-XA.png" /></figure><h3>Manually Deploy API Written in Java</h3><p>I learnt how to put build a Lambda written in Java from the article <a href="https://aws.amazon.com/blogs/opensource/java-apis-aws-lambda/">Running APIs Written in Java on AWS Lambda</a> from the <a href="https://aws.amazon.com/blogs/opensource/">AWS Open Source Blog</a>. This article uses aws-serverless-jersey-archetype which helps you easily generate a JerseySampleApi project.</p><p><strong>Some important things you should know.</strong></p><ol><li>The <a href="https://aws.amazon.com/blogs/opensource/java-apis-aws-lambda/">Running APIs Written in Java on AWS Lambda</a> assumed you’ve already configured the AWS CLI (AWS Access Key ID, AWS Secret Access Key, Default region name, and Default output format). If not, you might get errors when trying to execute the step Deploying to AWS in the article locally.<br>Refer to the links to see <a href="https://docs.aws.amazon.com/cli/latest/userguide/installing.html">How to Install AWS Command Line Interface</a> and <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html">How to the AWS CLI</a></li></ol><h3>Turn from Maven to Gradle</h3><p>I transferred the build tool from Maven to the Gradle so I can easily develop using Android Studio, the daily used IDE for my position as a mobile app developer.</p><h4>The Process</h4><ol><li>Created a new project and chose Add No Activity , removed the app module and Add a new Module / Java Library</li><li>Set the gradle version</li><li>Moved dependencies from <em>pom.xml</em> to <em>build.gradle</em></li><li>Got some errors and finally added the dependency slf4j-jdk14</li><li>Got more errors and finally made all dependencies perfect</li><li>Got Error loading class my.service.StreamLambdaHandler: javax/ws/rs/core/Application&quot;,&quot;errorType&quot;:&quot;java.lang.NoClassDefFoundError when testing via Amazon Api Gateway, I found the answer from <a href="https://stackoverflow.com/questions/32782980/aws-lambda-noclassdeffounderror/32783493#32783493">StackOverflow</a> and here’s what the <a href="https://docs.aws.amazon.com/lambda/latest/dg/java-create-jar-pkg-maven-no-ide.html">Official Doc</a> says</li></ol><blockquote>“In the plugins section, the Apache maven-shade-plugin is a plugin that Maven will download and use during your build process. This plugin is used for packaging jars to create a standalone .jar (a .zip file), your deployment “</blockquote><p>I finally found a Gradle version called <a href="https://github.com/johnrengelman/shadow">Shadow</a> ! Yeah~~~</p><p>You might not want to reproduce my process so here’s everything :D<br>You may ignore .gitlab-ci.yml which I’ll mention in the next section.</p><p><a href="https://github.com/spff/Auto-Deploy-AWS-Lambda-Java8-with-Gitlab-CI">spff/Auto-Deploy-AWS-Lambda-Java8-with-Gitlab-CI</a></p><h4>Project Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*OFXIBbmYtXsiaN9cGdQVOA.png" /><figcaption>The Project Structure</figcaption></figure><p>The <em>StreamLambdaHandler.java</em> and <em>StreamLambdaHandlerTest.java</em> were generated from the aws-serverless-jersey-archetype in the previous section.</p><h4>template.yml</h4><p>The only difference from <em>sam.yaml </em>(generated from the aws-serverless-jersey-archetype) is CodeUri: idgenerator/build/libs/shadow.jar, it’s the path where we generate our <em>fat-jar</em>, and I’ll mention the whole build process in the next section.</p><p><strong>Some important things you should know.</strong></p><ol><li>If you’re using IntelliJ based IDE, mind that executing Gradle will take the system’s JDK and it might not be the same as the one you set to the IDE, my approach is JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home ./gradlew build(I’m using MacOS)</li><li>Make sure you are using jdk-8 , the test might not pass if you use any higher version one. (At least I failed with openjdk-11)</li><li>I’m not sure whether it is the Android Studio’s bug, I need to do a Gradle Sync every time I open the project or the whole directory under my module is in the excluded path which makes me not able to browse files under the module.</li></ol><h3>Auto Deploy API Written in Java (Gradle)</h3><h4>The Build Process</h4><p>The last step was to write my <em>.gitlab-ci.yml</em>. It’s simple, with only three stages and each has only one job.</p><pre># define a default docker image for all jobs<br>image: node:10.12</pre><pre>variables:<br>    # replace this with YOUR custom bucket name<br>    S3_BUCKET: ******<br>    AWS_DEFAULT_REGION: ******</pre><pre>stages:<br>    - build_and_test   # build and test<br>    - package # upload source code to S3<br>    - deploy  # stage for deploying to production</pre><pre>buildAndTest:<br>    stage: build_and_test<br>    image: openjdk:8-alpine<br>    script:<br>        - ./gradlew clean test shadowJar<br>    # artifacts describe the result of the stage<br>    # that can be used in consecutive stages<br>    artifacts:<br>        untracked: true</pre><pre>packageApp:<br>    stage: package<br>    image: tarekbecker/awscli<br>    # use the artifcats of the &#39;buildAndTest&#39; job<br>    dependencies:<br>        - buildAndTest<br>    script:<br>        # package uploads the source code to S3 and creates a new<br>        # template file with a reference to the code in S3<br>        - aws cloudformation package --template template.yml --s3-bucket $S3_BUCKET --output-template template-export.yml<br>    artifacts:<br>        paths:<br>            # the modified template is the result of this stage<br>            - ./template-export.yml</pre><pre>deployProd:<br>    stage: deploy<br>    image: tarekbecker/awscli<br>    dependencies:<br>        - packageApp<br>    script:<br>        # use the template-export file to deploy the stack<br>        # the cloud formation stack name is prod for our stack<br>        - aws cloudformation deploy --template-file template-export.yml --stack-name demo-pipeline-java-prod-stack --capabilities CAPABILITY_IAM</pre><p>The magic which generate our <em>fat-jar</em> is the command shadowJar</p><p>Don’t forget to set AWS_ACCESS_KEY_ID and AWS_SECRET_KEY as your CI/CD Variables.</p><p>Hope you have fun with your own chain which is able to Auto Deploy AWS Lambda (Java8) with Gitlab CI !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34a408b0ebce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin - SAM conversion is not always NEWing, but ‘object’ is]]></title>
            <link>https://medium.com/@spff/kotlin-sam-is-not-always-newing-but-object-is-f8e4bb3d7e59?source=rss-fc12e7c24e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8e4bb3d7e59</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[spff]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 02:03:47 GMT</pubDate>
            <atom:updated>2018-10-25T01:12:13.203Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been debugging my <a href="https://github.com/spff/ObfuscatedPreferences">ObfuscatedPreferences</a> for the pass few days, about implementing the registerOnSharedPreferenceChangeListener() / unregisterOnSharedPreferenceChangeListener(). I need to make sure that the listeners I’ve stored will be collected by the garbage collector when there’s no longer any strong reference to the listener, as the same behavior written in the javadoc in SharedPrefenerces.java</p><pre><em>* &lt;p class=&quot;caution&quot;&gt;&lt;strong&gt;Caution:&lt;/strong&gt; The preference manager does<br>* not currently store a strong reference to the listener. You must store a<br>* strong reference to the listener, or it will be susceptible to garbage<br>* collection. We recommend you keep a reference to the listener in the<br>* instance data of an object that will exist as long as you need the<br>* listener.&lt;/p&gt;</em></pre><p>An efficient approach to know whether it works as expected is using the code below and see if OOM occurs.</p><pre>for( i in 0 <em>until  </em>1000000/*a big number*/){<br>    val listener = SharedPreferences.OnSharedPreferenceChangeListener <strong>{ </strong>_, _ <strong>-&gt; }<br>    </strong>obfuscatedPreferences.registerOnSharedPreferenceChangeListener(<br>listener)<br><strong>}</strong></pre><p>However, after double checking by logging the final size of the WeakHashMap which stores the listeners internally, it had always been <strong>1 </strong>! It’s very likely those listeners I’d NEWed (at least I thought I did) were sharing the same instance. I finally got the answer by looking at the Kotlin bytecode, the SAM which didn’t access outer scope nor stuff corresponding to this was optimized as a static object.</p><pre>for( i in 0 <em>until  </em>1000000/*a big number*/){</pre><pre>//GETSTATIC<br>    val listener = SharedPreferences.OnSharedPreferenceChangeListener <strong>{ </strong>_, _ <strong>-&gt; }</strong></pre><pre>//GETSTATIC<br>    val listener = SharedPreferences.OnSharedPreferenceChangeListener <strong>{ </strong>_, _ <strong>-&gt;<br>    </strong>Log.e(&quot;Foo&quot;, &quot;bar&quot;)<strong><br>}</strong></pre><pre>//NEW<br>    val listener = SharedPreferences.OnSharedPreferenceChangeListener <strong>{ </strong>_, _ <strong>-&gt;<br>    </strong>Log.e(&quot;Foo&quot;, this.toString())<strong><br>}</strong></pre><pre>//NEW<br>    val listener = SharedPreferences.OnSharedPreferenceChangeListener <strong>{ </strong>_, _ <strong>-&gt;<br>    </strong>Log.e(&quot;Foo&quot;, i.toString())<strong><br>}</strong></pre><pre><strong>    </strong>obfuscatedPreferences.registerOnSharedPreferenceChangeListener(<br>listener)<br><strong>}</strong></pre><p>Finally, if you really want to NEW an instance and make compiler NOT optimized as static, JUST GIVE SAM CONVERSION UP AND TURN TO object</p><pre>val listener = object : SharedPreferences.OnSharedPreferenceChangeListener {<br>    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {<br>        Log.e(&quot;Count&quot;, this.toString() + &quot;hi&quot;)<br>    }<br><br>}</pre><p>The code above guarantees that you’re always getting a new object!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e4bb3d7e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The order of constructing in Kotlin]]></title>
            <link>https://medium.com/@spff/the-order-of-constructing-in-kotlin-7c906479edad?source=rss-fc12e7c24e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c906479edad</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[spff]]></dc:creator>
            <pubDate>Fri, 02 Mar 2018 15:42:04 GMT</pubDate>
            <atom:updated>2018-03-02T15:43:09.671Z</atom:updated>
            <content:encoded><![CDATA[<pre>//Java<br>//<br>//public Z{<br>//<br>// int k;<br>// private int j;<br>// private String string;<br>//<br>// public Z(int i){<br>//     this(i, &quot;hi&quot;, 4);<br>// }<br>//<br>// public Z(int i, String string){<br>//     this(i, string, 5);<br>// }<br>//<br>// public Z(int i, String string, int j){<br>//     k = i + 1;<br>//     this.string = string;<br>//     this.j = j;<br>//     init();<br>// }<br>//<br>// private init(){<br>//<br>// }<br>//<br>//}<br>//<br><br>class Z (<strong><em>/**3rd load*/</em></strong>i: Int, private val string: String, private val j: Int = 5<strong><em>/**5th put field if declared as val/var*/</em></strong>)<strong><em>/**4th, if has parent class, call super*/</em></strong><em> </em>{<br><br>    <strong><em>/**6th*/</em></strong><em><br>    </em>var k = i + 1<strong><br><br><br>    </strong>constructor(<strong><em>/**1st load*/</em></strong>i:Int):this(<strong><em>/**2nd*/</em></strong>i, &quot;hi&quot;, 4){<br>        <strong><em>/**8th*/</em><br>    </strong>}<br><br>    init {<br>        <strong><em>/**7th*/</em><br>    </strong>}<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c906479edad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[swap，從不會到略懂 a = b.also{b = a}]]></title>
            <link>https://medium.com/@spff/swap-%E5%BE%9E%E4%B8%8D%E6%9C%83%E5%88%B0%E7%95%A5%E6%87%82-a-b-also-b-a-5bf6f7001cac?source=rss-fc12e7c24e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf6f7001cac</guid>
            <category><![CDATA[swap]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[spff]]></dc:creator>
            <pubDate>Wed, 28 Feb 2018 18:33:08 GMT</pubDate>
            <atom:updated>2019-03-20T02:07:29.041Z</atom:updated>
            <content:encoded><![CDATA[<p>如同C的a = i++其實是(t = i;i = i+1;t)，這裡的a = b.also{b = a}實際上也可以視作(t = b;b = a;t)，然後把回傳的值assign回a</p><h4>also的簽名如下 public inline fun &lt;T&gt; T.also(block: (T) -&gt; Unit): T</h4><p>This is a generic inline extension function which takes a function which returns Unit as input and return T</p><h4>名詞解釋</h4><p><a href="https://kotlinlang.org/docs/reference/lambdas.html#lambda-expressions-and-anonymous-functions">以下是官網的解釋</a></p><p>A lambda expression or an anonymous function is a “function literal”, i.e. a function that is not declared, but passed immediately as an expression.</p><p>Function可以被當成參數餵給其他function或是作為return，也就是所謂 <a href="https://en.wikipedia.org/wiki/First-class_function">first-class function</a>的概念。Function是一個interface，lambda expression是一種Function，長成用大括號包起來的樣子{something()}。<br>BTW在C++裡面lambda, function object, function reference講的是不同的事情~~~</p><h4>Extension function</h4><p>Extension function很有趣，在官網有非常簡單易懂的介紹。</p><p>如果你幫Int寫了一個extension functionfun Int.test1(float: Float)，<br>實際上在JVM層會變成fun test1(int: Int, float: Float) 。<br>詳見<a href="https://github.com/heimashi/kotlin_tips#tip4--%E6%89%A9%E5%B1%95%E5%87%BD%E6%95%B0%E5%92%8C%E5%B1%9E%E6%80%A7">heimashi/kotlin_tips的tip4</a>。</p><p>值得一提的是如果fun Int.test2()和 fun test2(int: Int) 同時存在會出錯，原因就是JVM層級的function簽名一樣。根據這點如果我們只寫了fun Int.test2()，已知背後會轉成fun test2(int: Int)，那是否可以直接呼叫test2(5)呢? <strong>答：在Kotlin不行，不過從其他Java來call Kotlin的時候可以。</strong></p><h4>Generic</h4><p>不解釋。</p><h4>Input(Argument)</h4><p>Kotlin的變數/常數宣告方式： var(mutable)/val(immutable): Type</p><ul><li>先來解釋一下Kotlin的參數傳遞。Kotlin是JVM語言，它傳non-primitive的reference其實是用類似pointer的那套而非C++那種reference，<a href="https://openhome.cc/Gossip/Java/ArrayCopy.html">這裡</a>有Java這套清楚的圖解。</li><li>Kotlin官方在2013年以後規定function的input是val，也就是這個(primitive type)的值或是 (non-primitive)所指到的”地方”(而非指到的地方的”內容”)不能改。假如寫fun test3(int: Int){int = 5} 就會出錯因為這裡的int是val。</li></ul><p>所以T.also的input是一個val，名字叫做block，其型態是一個Function，這個Function輸入參數是T，回傳是Unit。</p><p>Kotlin沒有void而是Unit。任何沒表明回傳的function<a href="https://kotlinlang.org/docs/reference/functions.html#unit-returning-functions">都視同回傳</a><a href="https://kotlinlang.org/docs/reference/functions.html#unit-returning-functions">Unit</a>，所以其實任何function都會有return。要注意的是用作lambda的時候必須寫-&gt; Unit，要不然會被視作一個Object而非Function然後就會跳error說無法invoke。</p><p>Unit是一個class，繼承自Any，而且屬於object class，也就是singleton，(如此一來不用每次都new出一個Unit浪費記憶體)，然後.toString()會回傳”Kotlin.Unit” ，詳見<a href="https://proandroiddev.com/nothing-else-matters-in-kotlin-994a9ef106fc">Nothing (else) matters in Kotlin</a> 。非常推薦這篇文章，從Unit開始說起，接著提到Nothing和null, Kotlin與Java中void的關係。精采絕倫！</p><h4>先來回頭看a = b.also{ b = a}</h4><p>它其實是a = b.also({b=a}) 。<br>當lambda是最後一個參數的時候可以拉出來變成a = b.also(){b = a}<br> 最後如果()裡頭沒東西則省略a = b.also{b = a}</p><p>這個{b = a}到底是什麼呢? 其實它是fun <em>anonymous</em>(it: T): Unit{ b = a}。 變成一個lambda的時候會長這樣 {it: T -&gt; b = a}。<br>通常input型態已經被外面規定好了，例如我們要餵給also，它已經規定block是一個Function接受一個T型態的input然後回傳Unit。(<strong>block: (T) -&gt; Unit</strong>)，所以可以省略成{it -&gt; b = a}。</p><p>這裡的變數名稱it是可以隨便取的。 由於我們沒用到這個it，所以會得到一個warning說可以改成{_-&gt; b=a}，這是為了當你有一堆不會用到的參數所有不會用到的都可以直接寫成_而不用去逐一取名。</p><p>然後我們又更懶了一點，由於只有一個參數所以如果不寫的話它會<a href="https://kotlinlang.org/docs/reference/lambdas.html#it-implicit-name-of-a-single-parameter">自動獲得it這個變數名稱</a>，{b = a}然後在這裡我們沒用到它。</p><h4>Inline</h4><p>每個語言的inline主要都是為了加速，其他用途以及進階玩法可以看官方介紹，簡單加速說明可以參考這邊：<a href="https://stackoverflow.com/questions/44471284/when-to-use-an-inline-function-in-kotlin">when to use an inline function in Kotlin?</a></p><h4><strong>also裡面到底做了什麼事</strong></h4><pre>public inline fun &lt;T&gt; T.also(block: (T) -&gt; Unit): T {<br>    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }<br>    block(this)<br>    return this<br>}</pre><p>抱歉，contract那邊還沒研究，不過大致是在設定接下來呼叫block(this)的一些行為規範(歡迎補充) 所以說also其實也就是把傳過來的Function設定好以後呼叫它然後再return this。</p><h4>所以說swap到底怎麼辦到的？</h4><p>展開成 b.also({it -&gt; b = a}) 較好理解，重點是生成Function的行為。</p><p>藉由把編好的JVM byte code給disassemble來觀察，我的發現是(歡迎糾正、補充)，其實是把b(primitive)或是b這個Pointer(non-primitive)複製一份給it(而且它是val，不能修改的) 進去以後b = a，然後執行完這個lambda以後also會回傳it，最後把它assign給a 也就完成swap的動作了 咦！突然發現如果是non-primitive type其實這個swap是shallow swap呢！可以把這坨丟到<a href="https://try.kotlinlang.org/#/Examples/Hello,%20world!/Simplest%20version/Simplest%20version.kt">這邊</a>跑來驗證是shallow swap。</p><pre>fun main(args: Array&lt;String&gt;) {<br>    var a = A()<br>    var b = A()<br>    val c = b<br>    b. variable = 5<br>    println(“${a.variable} ${b.variable} ${c.variable}”)<br>    a = b.myalso { b = a}<br>    println(“${a.variable} ${b.variable} ${c.variable}”)<br>}<br>class A( var variable = 2 )<br>fun A.myAlso(block: (A) -&gt; Unit): A {<br>    block(this)<br>    return this<br>}</pre><p>而更多的細節必須去挖掘closure(閉包)和lambda來更好地理解。</p><h4>看到這邊，只要學會swap，少少幾個字a = b.also{b = a} ，你就學會extension functions, inline, generic, higher-order functions, lambda, Unit了呢！</h4><p>BTW higer-order functions除了also，還有一堆，詳見這篇好文<a href="https://blog.cat73.org/2017/12/09/kotlin-standard/">Kotlin 的 with、apply、let 等函数的用处</a>。</p><p>舉個例子fun &lt;T, R&gt; T.run(block: T.() -&gt; R): R你要傳給他的block就會自動變成T的extension function，這個時候在block裡面就可以用this來獲取這個T的instance。這個block是一個function takes no input argument 然後回傳的任意型態會直接被run給return。</p><p>我開始覺得這真適合當作殘害脆弱小生命的面談的題目了(抖 <br><strong>請用also (簽名：public inline fun &lt;T&gt; T.also(block: (T) -&gt; Unit): T)寫個shallow swap並解釋</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf6f7001cac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>