Skip to content

Instantly share code, notes, and snippets.

@dolphinsue319
dolphinsue319 / TienHanQ3.swift
Created January 20, 2025 00:51
測速網域並儲存的物件
import Foundation
// 測速網域的物件
class DomainSpeedTester {
// 用來儲存測試結果的內部資料結構
private var results: [(domain: String, time: Double)] = []
// 請求圖片的 function,圖片不需儲存,最後回傳下載時間 (ms)
func downloadImg(domain: String) async throws -> Double {
let urlString = "https://\(domain)/test-img"
@dolphinsue319
dolphinsue319 / tienyu_chatQA.md
Created January 12, 2025 07:04
TienYu_處理斷線與漏掉訊息的聊天室

Q: 用戶 A 在聊天室中斷線並於 10 秒後重新連線,如何確保用戶 A 收到斷線期間(這 10 秒內)的所有訊息?

  • 前提:每則訊息都帶有一個可排序的唯一標識(例如 messageID 或「遞增的序號」),或使用「時間戳 (timestamp) + 伺服器的邏輯排序」來判斷訊息先後。
  • local 端儲存:在 local 端中,為每個房間記錄一個 lastReceivedMessageID(或 lastReceivedTimestamp),並在每次成功收到新的訊息後都更新。
  • 當用戶重新連線時,前端將 lastReceivedMessageID 傳給後端,後端依此回傳從這個 ID(或 Timestamp)之後的新訊息列表。
  • 當偵測到斷線(WebSocket 連線斷開事件),客戶端開始進行重連邏輯。
  • 在連線成功的初始握手或授權階段,客戶端告知伺服器「我在哪些聊天室,有哪些 lastReceivedMessageID」。。
  • 伺服器回傳遺漏訊息:
    • 從用戶提供的 lastReceivedMessageID 之後開始,批次或分頁 (pagination) 地將訊息傳回。
    • 為避免伺服器壓力,後端可設定一次最多回傳多少筆訊息,若訊息量過多則分多次回傳,讓客戶端透過多次請求或多次 WebSocket Event 接收。
  • 客戶端合併訊息:
@dolphinsue319
dolphinsue319 / LeetCode161.swift
Last active November 21, 2021 06:48
LeetCode 161. One Edit Distance
class Solution {
func isOneEditDistance(_ s: String, _ t: String) -> Bool {
if (s.count == t.count) {
return countOfReplaced(s, t) == 1
}
if (s.count == t.count - 1) {
return isRemoved(s, t)
}
if (t.count == s.count - 1) {
@dolphinsue319
dolphinsue319 / LogisticRegressionThroughSklearn.py
Created April 9, 2017 04:54
用 scikit-learn 實作 logistic regression
# coding: utf-8
# In[ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
@dolphinsue319
dolphinsue319 / SimplestKeras.py
Last active November 22, 2019 10:57
這是一個最簡短、最基本的 Keras 使用範例。
# 這段程式碼來自莫煩 Python: https://morvanzhou.github.io/tutorials/machine-learning/keras/2-1-regressor/
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy as np
# 建立 X, Y 兩組資料用來練習 keras 的使用
X = np.linspace(-1, 1, 200)
np.random.shuffle(X)
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))
# coding=utf-8
from peewee import *
import datetime
class DateHandler:
def __init__(self):
pass
THIS_YEAR = datetime.datetime.now().year
@dolphinsue319
dolphinsue319 / fetch_stocks_price.py
Created March 3, 2017 09:25
Fetch Taiwan OTC stocks price.
# coding=utf-8
import StringIO
import csv
import requests
from bs4 import BeautifulSoup
import time
import random
from Models import *
@dolphinsue319
dolphinsue319 / check_facebook_request.py
Last active February 1, 2017 08:13
Check Facebook's webhook request
@app.route('/', methods=['GET'])
def verify():
# when the endpoint is registered as a webhook, it must echo back
# the 'hub.challenge' value it receives in the query arguments
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
@dolphinsue319
dolphinsue319 / send_message_to_Facebook.py
Last active February 1, 2017 08:13
send message to Facebook
def send_message(recipient_id, message_text):
params = {
"access_token": os.environ["PAGE_ACCESS_TOKEN"]
}
headers = {
"Content-Type": "application/json"
}
data = json.dumps({
"recipient": {
"id": recipient_id
@dolphinsue319
dolphinsue319 / mock_message_location.json
Last active February 1, 2017 05:38
The json string from Facebook's post request.
{
"entry": [
{
"id": "entry_id",
"time": 1485670019761,
"messaging": [
{
"sender": {
"id": "USER_ID"
},