Skip to content

Instantly share code, notes, and snippets.

View linw1995's full-sized avatar
🎯
Focusing

林玮 (Jade Lin) linw1995

🎯
Focusing
View GitHub Profile
@linw1995
linw1995 / SilceManipulationWithInvoking.go
Last active August 12, 2021 07:06
Golang Troublesome problem
// https://play.golang.org/p/bxTn8L2gf3d
package main
import (
"fmt"
)
func Remove(arr []int, idx int) (rv []int) {
rv = arr[:idx]
rv = append(rv, arr[idx+1:]...)
@linw1995
linw1995 / main.py
Created April 14, 2021 06:57
How to add custom convertors for JSON serializer in Python
import dataclasses
import json
from datetime import datetime
def convertor(v):
if isinstance(v, datetime):
return v.timestamp()
elif dataclasses.is_dataclass(v):
return dataclasses.asdict(v)
@linw1995
linw1995 / README.md
Last active June 6, 2021 06:51
Please don't use ContextVar.reset in async_generator.

Please don't use ContextVar.reset in async_generator.

Important rule: Different coroutines own different contexts.

  • The example1.py runs one coroutine with async_generator, the async_generator.__anext__ method runs in same context and thus it works find.
  • The example2.py produces two coroutines with the same async_generator, the async_generator.__anext__ method runs in different contexts and thus it raises an ValueError exception.

Tips for async_generator with ContextVar

@linw1995
linw1995 / cmd_with_retry.py
Last active May 9, 2021 13:09
Simple script for executing command with retry
import os
import subprocess
import sys
def run_cmd_with_retry(
cmd,
retry_count_limit=3,
retry_delay_seconds=60,
stdout=sys.stdout.fileno(),
@linw1995
linw1995 / demo.py
Created April 13, 2021 07:16
Get datetime objects in month range in Python.
import calendar
import dataclasses
from datetime import datetime, timezone
@dataclasses.dataclass
class DatetimeRange:
begin: datetime
end: datetime
@classmethod
@linw1995
linw1995 / main.py
Created April 9, 2021 05:51
Click with async command
# Standard Library
import asyncio
import functools
# Third Party Library
import click
def async_command(coro_func):
@functools.wraps(coro_func)
@linw1995
linw1995 / main.py
Created April 6, 2021 10:39
aiohttp integrates with mitmproxy
import ssl
import asyncio
from aiohttp import ClientSession
async def main():
async with ClientSession() as session:
sslcontext = ssl.create_default_context(cafile='~/.mitmproxy/mitmproxy-ca.pem')
r = await session.get('https://example.com', proxy='http://localhost:8080', ssl=sslcontext)
@linw1995
linw1995 / main.py
Last active April 6, 2021 10:05
Convert pyppeteer cookies to SimpleCookie
import logging
from http.cookies import CookieError, Morsel, SimpleCookie
from pyppeteer.page import Page
logger = logging.getLogger(__name__)
PYPPETEER_2_MORSEL = {"httpOnly": "httponly", "sameSite": "samesite"}
@linw1995
linw1995 / main.py
Last active April 6, 2021 09:23
Get browser timezone in pyppeteer.
from datetime import timedelta, timezone
from pyppeteer.page import Page
async def get_browser_timezone(page: Page) -> timezone:
js_timezone_offset = await page.evaluate(
"""
function () {
return new Date().getTimezoneOffset();
@linw1995
linw1995 / README.org
Last active April 2, 2021 06:49
Get PDM to work with lsp-python-ms in Emacs

Get PDM to work with lsp-python-ms in Emacs

A code snippet to show how to use PDM to work with lsp-python-ms in Emacs.

;; TODO: Cache result
(defun linw1995/pdm-get-python-executable (&optional dir)
  (let ((pdm-get-python-cmd "pdm info --python"))
    (string-trim
     (shell-command-to-string