JS 生成随机字符串

Generate random characters

Math.random().toString(36).replace(/[^a-z]+/g, '').slice(0, 5);

Math.random(),生成随机数,例如:0.09751664076957856
.toString(36),转换成36进制后的字符串。输出类似:“0.3idqid3cvvy”
.replace(/[^a-z]+/g, '') ,仅保留小写自负。输出类似:“idqidcvvy”
.slice(0, 5), 截取前5个字符。输出类似:"idqid"

Python 遍历指定目录下的文件

列出指定目录下的全部文件,或可以通过扩展名指定文件类型,也可以通过指定排除规则,忽略部分文件。

def list_files(
    dir: str, ext: list = None, recursive: bool = True, excludes: list = None
):
    """
    Args:
        - dir, directory path.
        - ext, file extension list, lowercase letters. Default is None, which means all files.
        - recursive, Default is True, will list files in subfolders.
        - excludes, exclude folder or file name list, regexp pattern string. Default is None, which means all folders

    Tips:
        - How to get relative path of a file: os.path.relpath(file_path, dir_path)
        - How to get only name of a file: os.path.basename(file_path)

    Version:
        v0.2.0
        https://gist.github.com/nodewee/eae12e2b74beb82162b8b488648f1fdd
    """

    for f in os.scandir(dir):
        if excludes:
            is_ignore = False
            for pat in excludes:
                if re.search(pat, f.name):
                    is_ignore = True
                    break
            if is_ignore:
                continue

        if recursive:
            if f.is_dir():
                for item in list_files(f.path, ext, recursive, excludes):
                    yield item

        if f.is_file():
            if ext is None:
                yield f.path
            else:
                if os.path.splitext(f.name)[1].lower() in ext:
                    yield f.path

Code on GitHub Gist

Python 复制文本到剪贴板

目前(Python 3.8)为止,Python 并没有原生支持访问系统剪贴板。

搜寻出有几种方法,梳理如下:

简单有效。但是并不适合复杂环境。

import os
# on macOS
def write_to_clipboard(text):
    command = f"echo '{text}' | pbcopy"
    os.system(command)

def read_from_clipboard():
    command = "pbpaste"
    return os.popen(command).read()

更多 Shell 命令参考:Shell use clipboard to copy and paste

Qt Pyside2 访问剪贴板

Qt/Pyside2 读取系统剪贴板内容

import sys
from PySide2.QtWidgets import QApplication

app = QApplication(sys.argv)
clipboard = app.clipboard()

print(clipboard.mimeData().formats())
print(clipboard.mimeData().data(clipboard.mimeData().formats()[0]))

app.closeAllWindows()
app=None

mimeData() 就和 drag 时对 mimeData() 的操作一样了。

引用自 doc.qt.io:

QClipboard supports the same data types that QDrag does, and uses similar mechanisms. For advanced clipboard usage read Drag and Drop .

JS 自动滚动页面到底部

function getScrollTop() {
    var scrollTop = 0,
        bodyScrollTop = 0,
        documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop =
        bodyScrollTop - documentScrollTop > 0
            ? bodyScrollTop
            : documentScrollTop;
    return scrollTop;
}

function getScrollHeight() {
    var scrollHeight = 0,
        bodyScrollHeight = 0,
        documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight =
        bodyScrollHeight - documentScrollHeight > 0
            ? bodyScrollHeight
            : documentScrollHeight;
    return scrollHeight;
}

function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//
function autoScroll() {
    if (getScrollTop() + getWindowHeight() < getScrollHeight()) {
        window.scrollTo({
            top: window.scrollY + 5,
            behavior: "smooth",
        });
        var timerId = setTimeout(autoScroll, 50);
        // stop when click
        document.addEventListener("click", (event) => {
            window.clearInterval(timerId);
        });
    }
}
autoScroll();

通过浏览器标签(Bookmarklet方式)调用,拖拽下面的链接到浏览器标签栏: