Skip to content

2020

Setting Up Auto-Formatting for Python in Visual Studio Code

I was writing Python code and encountered issues with formatting. These formatting problems can complicate code reviews and the use of automated tools to detect such issues. Fortunately, life becomes much easier when you integrate a formatter into your code editor to automatically fix those issues upon saving. Here's how to do it:

  1. First, install Google's yapf formatter:

pip install yapf

  1. Next, open your Visual Studio Code editor. Press “Command + Shift + P” if you're using a Mac, or “Ctrl + Shift + P” if you're on Linux. Type "Open settings (JSON)" in the search bar and add the following line:

"python.formatting.provider": "yapf"

  1. If you want your code to auto-format upon saving, rather than merely receiving tips within the editor, add this setting as well:

"editor.formatOnSave": true

  1. Optionally, if you wish to use your project's .style.yapf instead of the global styles, add the following line:

"python.formatting.yapfArgs": ["--style", ".style.yapf"]

Now you can test the auto-formatting feature. For example, if you don't have a new line at the end of your Python file and then you save it, the formatter will automatically correct this issue for you.

在Visual Studio Code中設定Python的自動格式化

我正在寫Python代碼,並遇到了格式化問題。這些格式問題可能會使代碼審查變得複雜,並對使用自動工具來檢測這些問題產生影響。幸運的是,當你將格式化工具集成到您的代碼編輯器中以在保存時自動修復這些問題時,生活會變得容易許多。這就是如何做的:

  1. 首先,安裝Google的yapf格式化工具:

pip install yapf

  1. 接著,打開你的Visual Studio Code編輯器。如果你使用的是Mac,按“Command + Shift + P”,如果你在Linux上,按“Ctrl + Shift + P”。在搜索欄中輸入"Open settings (JSON)"並添加以下行:

"python.formatting.provider": "yapf"

  1. 如果你希望你的代碼在保存時自動格式化,而不僅僅是在編輯器內部接收提示,也可以添加這個設置:

"editor.formatOnSave": true

  1. 如果你希望使用你的項目的.style.yapf而不是全局樣式,則添加以下行:

"python.formatting.yapfArgs": ["--style", ".style.yapf"]

現在你可以測試自動格式化功能。例如,如果你的Python文件末尾沒有新行,然後你保存它,格式化工具將自動為你修正這個問題。

How to Install Ubuntu Desktop on an AWS Instance Using Chrome Remote Desktop

In today's cloud-centric world, many resources have been moved to the cloud—photos, files, and servers among them. So why not your desktop environment? Imagine not needing to carry a heavy laptop. You could access your computing power from any thin client, such as a tablet with a keyboard, from anywhere. This is achievable using an AWS instance combined with Ubuntu Desktop and Chrome Remote Desktop. While there are other solutions like AWS Workspace or VNC connection, Chrome Remote Desktop offers the lowest latency and performance closest to a native desktop. Here's how to set it up:

  1. Log in to the AWS console and launch an instance using the Ubuntu Server AMI.

  1. Once the instance is launched, SSH into your Ubuntu server. Update the package manager and install wget:

sudo apt update sudo apt-get install --assume-yes wget

  1. Download the Chrome Remote Desktop package and install it:

wget https://dl.google.com/linux/direct/chrome-remote-desktop_current_amd64.deb sudo dpkg --install chrome-remote-desktop_current_amd64.deb sudo apt install --assume-yes --fix-broken

  1. Install the desktop GUI environment.

After testing various distributions, I found that Xfce performs best, especially over slow networks:

sudo DEBIAN_FRONTEND=noninteractive apt install --assume-yes xfce4 desktop-base

  1. Configure Chrome Remote Desktop to use Xfce by default:

sudo bash -c 'echo "exec /etc/X11/Xsession /usr/bin/xfce4-session" > /etc/chrome-remote-desktop-session'

  1. Install xscreensaver as an alternative to the default Xfce locker, which is not compatible with remote desktop:

sudo apt install --assume-yes xscreensaver

  1. Disable the display manager, as there is no display connected:

sudo systemctl disable lightdm.service

  1. Add your user account to the Linux group and then log out:

sudo usermod -a -G chrome-remote-desktop $USER logout

  1. On your local laptop browser, open Chrome Remote Desktop's Headless Mode. Follow the steps to set up another computer. You will probably copy a command similar to this into your AWS instance:

DISPLAY= /opt/google/chrome-remote-desktop/start-host --code="4/xxxxxxxxxxxxxxxxxxxxxxxx" --redirect-url="https://remotedesktop.google.com/_/oauthredirect" --name=

  1. Finally, you can remotely connect to your Ubuntu desktop.

    Extra tip: You can display a screensaver, although it's not necessary.

You can now access your desktop environment from anywhere, using any device. This setup is especially useful for software engineers who want access to a full set of development tools at all times.

如何使用Chrome遠程桌面在AWS實例上安裝Ubuntu桌面

在如今以雲端為中心的世界中,許多資源已被移至雲端,例如相片、檔案和伺服器等。那麼為何不將您的桌面環境也移到雲端呢?想像一下,不再需要帶著一台重型筆記本。您可以從任何薄型客戶端(例如帶有鍵盤的平板)在任何地方訪問您的計算能力。透過AWS實例,結合Ubuntu桌面和Chrome遠程桌面就可以實現這一點。雖然還有其他解決方法,如AWS工作區或VNC連接,但Chrome遠程桌面提供的延遲最低且性能最接近原生桌面。以下是如何設置的方法:

  1. 登錄AWS控制台,並使用Ubuntu Server AMI啟動一個實例。

  1. 實例啟動後,SSH登錄到您的Ubuntu服務器。更新包管理器並安裝wget:

sudo apt update sudo apt-get install --assume-yes wget

  1. 下載Chrome遠程桌面套裝軟體並安裝它:

wget https://dl.google.com/linux/direct/chrome-remote-desktop_current_amd64.deb sudo dpkg --install chrome-remote-desktop_current_amd64.deb sudo apt install --assume-yes --fix-broken

  1. 安裝桌面GUI環境。

在測試了各種不同的發行版本後,我發現Xfce在網路較慢的情況下表現最佳:

sudo DEBIAN_FRONTEND=noninteractive apt install --assume-yes xfce4 desktop-base

  1. 配置Chrome遠程桌面預設使用Xfce:

sudo bash -c 'echo "exec /etc/X11/Xsession /usr/bin/xfce4-session" > /etc/chrome-remote-desktop-session'

  1. 安裝xscreensaver作為預設的Xfce鎖屏程序的替代品,因為它不與遠程桌面兼容:

sudo apt install --assume-yes xscreensaver

  1. 禁用顯示管理器,因為沒有連接的顯示器:

sudo systemctl disable lightdm.service

  1. 將您的用戶賬戶添加到Linux群組,然後註銷:

sudo usermod -a -G chrome-remote-desktop $USER logout

  1. 在您的本地筆記本瀏覽器上,打開Chrome遠程桌面的無頭模式。按照步驟設置另一部電腦。您可能會在您的AWS實例中複製此類命令:

DISPLAY= /opt/google/chrome-remote-desktop/start-host --code="4/xxxxxxxxxxxxxxxxxxxxxxxx" --redirect-url="https://remotedesktop.google.com/_/oauthredirect" --name=

  1. 最後,您可以遠程連接到您的Ubuntu桌面了。

    額外的提示:您可以顯示屏幕保護程序,儘管這並不必要。

您現在可以使用任何設備,從任何地方訪問您的桌面環境。這種設置對於隨時需要訪問完整開發工具集的軟體工程師特別有用。

How to Install Ubuntu on an External Drive Using macOS

If you're using Mac hardware but also want to run Ubuntu, you can install Ubuntu on an external hard drive without risking the removal of your macOS installation. Here's how to do it without messing up your bootloader:

  1. Plug in your external SSD/HDD. Open Disk Utility and format it to MS-DOS (FAT).

  2. Open a Terminal window and run: diskutil list

This will help you find your external hard drive's IDENTIFIER, e.g., disk2 in this example.

  1. Download and install VirtualBox: VirtualBox Website

  2. Run the two commands below and start VirtualBox with admin rights:

sudo VBoxManage internalcommands createrawvmdk -filename bootcamp.vmdk -rawdisk /dev/disk2 sudo /Applications/VirtualBox.app/Contents/MacOS/VirtualBox

  1. Select "New" and then click on "Expert Mode." Choose "Use an existing virtual hard disk file."

  1. In the "System" tab, check the box for "Enable EFI (special OSes only)."

  2. In the "Storage" tab, mount the Ubuntu ISO file to the virtual machine. You can download the Ubuntu ISO file from here.

  3. Start the virtual machine and proceed with the Ubuntu installation.

  4. Once the installation is complete, you'll be ready to boot from the drive. For Mac, you'll also need to reduce the Security level and allow booting from external media. To do this, press and hold Command-R immediately after you see the Apple logo to start macOS recovery.

  5. Restart your Mac again and press the Option key. You can now choose your drive with the EFI label.

Enjoy using Ubuntu on Apple hardware! Note that you might have to sort out some driver issues, but hopefully, this guide makes the process easier for you.

如何使用macOS在外部驅動器上安裝Ubuntu

如果你在使用Mac硬體,但也想要運行Ubuntu,你可以在外部硬碟上安裝Ubuntu,而不會冒著刪除你的macOS安裝的風險。下面是如何在不搞砸你的引導裝載器的情況下進行操作:

  1. 將你的外部SSD/HDD插入。打開磁碟工具並將其格式化為MS-DOS(FAT)

  2. 打開終端窗口並運行: diskutil list

這將幫助你找到你的外部硬碟的標識符,例如,在這個示例中是disk2。

  1. 下載並安裝VirtualBox: VirtualBox網站

  2. 運行以下兩條命令並以管理員權限啟動VirtualBox:

sudo VBoxManage internalcommands createrawvmdk -filename bootcamp.vmdk -rawdisk /dev/disk2 sudo /Applications/VirtualBox.app/Contents/MacOS/VirtualBox

  1. 選擇“新建”然後點擊“專家模式”。選擇“使用現有的虛擬硬碟文件。”

  1. 在“系統”標籤中,勾選“啟用EFI(僅限特殊OS)”。

  2. 在“儲存”標籤中,將Ubuntu ISO文件掛載到虛擬機。 你可以從這裡下載Ubuntu ISO文件。

  3. 啟動虛擬機並進行Ubuntu安裝。

  4. 一旦安裝完成,你就可以從驅動器啟動了。 對於Mac,你也需要降低安全級別並允許從外部媒體啟動。要做到這一點,在你看到蘋果標誌後立即按住Command-R以啟動macOS恢復。

  5. 重新啟動你的Mac並按住選項鍵。你現在可以選擇你的驅動器擁有EFI標籤。

享受在Apple硬體上使用Ubuntu!請注意,你可能需要解決一些驅動問題,但希望這個指南能讓你的過程更容易。

How to Fix the "Access Denied" Error in an AWS Amplify Angular App

When you deploy your Angular app on AWS Amplify, the first landing page loads without any issues. However, if you have defined a path in your router and attempt to access it, you may encounter an "Access Denied" error:

To resolve this issue, navigate to the AWS Console and select "Rewrites and Redirects." Next, add a new rewrite and redirect rule. Click on "Open Text Editor" and insert the following rule:

[
  {
    "source": "</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>",
    "target": "/index.html",
    "status": "200",
    "condition": null
  }
]

After adding this rule, try accessing your URL again. It should work as expected now.

如何修復 AWS Amplify Angular App 中的“拒絕存取”錯誤

當您在 AWS Amplify 上部署您的 Angular 應用程式時,第一個登陸頁面可以正常載入。然而,如果您在您的路由器中定義了一條路徑並嘗試存取它,您可能會遇到一個“拒絕存取”的錯誤:

要解決這個問題,首先導航至 AWS 控制台,然後選擇“重寫和重定向”。接著,加入一條新的重寫和重定向規則。點擊“開啟文字編輯器”並插入以下的規則:

[
  {
    "source": "</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>",
    "target": "/index.html",
    "status": "200",
    "condition": null
  }
]

添加這條規則後,嘗試再次存取您的 URL。現在應該可以按預期工作了。

Writing Your Android App to Run in Background Mode as a Service

In some scenarios, you might face an issue where your app's functionality is lost after several minutes when users place it in background mode or lock their screens. This can lead to poor user experience, such as Bluetooth devices disconnecting from your app or data sync to the server getting interrupted. Users may then complain about the connectivity and stability of your app.

First, to address this issue, you need to understand the Android app Activity lifecycle. When a user switches to another app, like Facebook, instead of using yours, your app's activity is terminated and the onDestroy() method is triggered. While this behavior is beneficial for the Android system as it helps free up unused memory and manage battery life, it can be problematic for your app because its states and functionalities get lost.

The next step is to refactor your app to separate background functionalities, like Bluetooth connectivity, into a service. A service is an application component capable of performing long-running operations in the background, independent of the user interface. Here's a code example for a service:

import android.app.Service

class MyService : Service() {

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
      // Place your service logic here
    }

    override fun onDestroy() {
      // Clean up your service logic here
    }

}

To use this service, you also need to define it in your AndroidManifest.xml. Here is an example (replace the name with your service's package name):

<application>
    ...
    <service android:enabled="true" android:name="com.victorleungtw.myapp.services.MyService"></service>
</application>

Furthermore, to start this service in your activity (for example, in Activity.onCreate()), add the following line:

startService(Intent(this, MyService::class.java))

And where you wish to stop the service, include this line:

stopService(Intent(this, MyService::class.java))

After implementing these changes, your app will be better structured but won't yet be able to run indefinitely in the background. To achieve that, you also need to add two more methods within your service:

class MyService : Service() {
    // ... existing code

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val channelId =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    createNotificationChannel("my_service", "My Background Service")
                } else {
                    // If it's an earlier version, the channel ID is not used
                    ""
                }

        val notification: Notification = Notification.Builder(this, channelId)
                .setContentTitle("Title")
                .setContentText("Text")
                .build()
        startForeground(2001, notification)

        return START_STICKY
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String): String {
        val channel = NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE)
        channel.lightColor = Color.BLUE
        channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(channel)
        return channelId
    }
}

Here, a notification is created to inform the user that the app continues to run in the background. It might look something like this:

That's it. Now your users can multitask—like browsing Facebook—while your app continues to run in the background, maintaining Bluetooth connectivity, syncing user data, playing music, or performing other tasks depending on your app's features.

如何將您的Android應用程式寫入後台執行模式作為服務

在某些情況下,您可能會遇到一個問題,那就是當用戶將應用程式置於背景模式或鎖定屏幕後幾分鐘,您的應用程式的功能就會消失。這可能導致用戶體驗變差,例如藍牙設備從您的應用程式中斷開,或者數據同步到服務器中斷。用戶可能會抱怨您的應用程式的連接性和穩定性。

首先,為了解決這個問題,您需要了解Android應用程式活動生命周期。當用戶切換到另一個應用程式,例如Facebook,而不是使用您的,您的應用程式活動將被終止,並觸發 onDestroy() 方法。然而,這種行為對於Android系統是有利的,因為它可以幫助釋放未使用的記憶體和管理電池壽命,但對於您的應用程式來說,可能會有問題,因為其狀態和功能可能會丟失。

下一步是重構您的應用程式,將如藍牙連接等背景功能分離為服務。服務是一種應用程式組件,能夠在後台執行持久運作,獨立於使用者介面。下面是一個服務的代碼範例:

import android.app.Service

class MyService : Service() {

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
      // 在此擺放你的服務邏輯
    }

    override fun onDestroy() {
      // 在此清理你的服務邏輯
    }

}

要使用此服務,您還需要在您的 AndroidManifest.xml 中定義它。這是一個例子(將名稱替換為您的服務的套件名稱):

<application>
    ...
    <service android:enabled="true" android:name="com.victorleungtw.myapp.services.MyService"></service>
</application>

此外,要在您的活動中啟動此服務(例如在 Activity.onCreate() 中),請添加以下行:

startService(Intent(this, MyService::class.java))

並在您希望停止服務的地方,包括此行:

stopService(Intent(this, MyService::class.java))

實施這些更改後,您的應用程式將有更好的結構,但還不能在背景中無限期運行。為了實現這一點,您還需要在您的服務中添加兩個方法:

class MyService : Service() {
    // ... 現有的代碼

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val channelId =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    createNotificationChannel("my_service", "My Background Service")
                } else {
                    // 如果是較早的版本,則不使用頻道ID
                    ""
                }

        val notification: Notification = Notification.Builder(this, channelId)
                .setContentTitle("Title")
                .setContentText("Text")
                .build()
        startForeground(2001, notification)

        return START_STICKY
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String): String {
        val channel = NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE)
        channel.lightColor = Color.BLUE
        channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(channel)
        return channelId
    }
}

在這裡,創建了一個通知,通知用戶該應用程式繼續在背景中運行。它可能看起來像這樣:

就是這樣。現在您的用戶可以進行多任務操作,例如瀏覽Facebook,同時您的應用程式繼續在後台運行,保持藍牙連接,同步用戶數據,播放音樂或執行其他取決於您的應用程式功能的任務。