# Data mining Source: https://base.bangwu.me/about/courses/data-mining Course notes on data mining covering CRISP-DM workflow, Apriori association rules, K-Means clustering, decision tree classification, and TF-IDF text mining. # 数据挖掘 以下是根据课件所示的总结,推荐看完课件再看总结。大体上还是以理解为主,自行斟酌。 ## 1.数据挖掘概述 数据挖掘概述、数据准备与数据相似度计算、关联模式挖掘、聚类分析、数据分类技术、文本挖掘技术。 ### 1.1 数据挖掘的定义与数据挖掘过程 背景:新时代,数据越来越多——数据是数据时代生产力的革命性要素。【技术进步的推动:存储器的飞速发展与处理器的发展】,但是出现的问题就是淹没在数据中,不能定制合适的决策。随着各个领域的发展,数据挖掘渐渐形成。 `数据挖掘`(Data Mining)的定义:从大量的、不完全的、有噪声的、模糊的、随机的实际应用数据中,提取隐含在其中的、人们事先不知道的、但又是潜在有用的信息和知识的过程。 * 数据源必须是真实的、大量的、含有噪声的 * 发现的是用户感兴趣的知识 * 发现的知识要可接受、可理解、可运用 * 并不要求发现放之四海皆准的知识,仅支持特定的问题的发现 数据挖掘标准流程:`CRISP-DM` ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} 商业理解->数据理解->数据准备(最花费时间)->建立模型->模型评估->模型部署 ``` ### 1.2 基本数据类型 非依赖型数据和依赖型数据 1. `非依赖型数据`:二维表,行是一组记录,列是一组字段 2. `依赖型数据`:具有时间、空间或结构上的依赖关系,改变次序、位置有影响。如时间序列数据、图数据等 ### 1.3 数据挖掘的分类与常用技术 有监督又被称为“有老师的学习”,无监督被称为“没有老师的学习”。还有一个强化学习。 ![bangwu\_20240622142834](https://cdn.bangwu.top/img/bangwu_20240622142834.webp) 常用技术有:`分类技术`、`回归分析`、`关联规则`、`聚类分析`、`偏差检测`。 数据分析是“后见之明”,数据挖掘是“先见之明” ## 2.数据准备与相似度计算 ### 2.1 数据的详细理解 数据->信息->知识->智慧【不是,怎么又是这个。。。。】 `数据`是数据对象和它们属性的集合。 `属性值`是赋给一个属性的**数字的**或**字符的**值。 ### 2.2 特征提取与类型转换 `特征提取`是将低级特征类型转换为高级特征类型的过程。【说白了就是说白了】 类型转换可以用到的方法有:离散化、二元化、特征词量化等 ### 2.3 数据清洗 数据预处理的功能之一,就是发现并纠正数据文件中可识别错误的步骤,包括对噪声、缺失值、异常值的处理。 ### 2.4 相似度与距离 `相似性度量` (Similarity Measurement) 用于衡量两个元素之间的相似性程度或两者之间的距离 (Distance)。`距离度量`的是指元素之间的不相似性 (Dissimilarity)。 1. 简单属性之间的相似性或相异性 ![bangwu\_20240622150002](https://cdn.bangwu.top/img/bangwu_20240622150002.webp) 2. 数据对象之间的相异性(距离度量) ​ 注:以下的 x, y 不是点值,而是向量 x(x1, x2, x3) * 欧氏距离 $$ d \left(x, y\right) = \sqrt{\sum_{i=1}^{n} \left(x_i - y_i\right)^2} $$ * 闵氏距离(闵可夫斯基距离) $$ d \left(x, y\right) = \left(\sum_{i=1}^{n} |x_i - y_i|^p\right)^{\frac{1}{p}} $$ p = 1 时,称为曼哈顿距离 $$ d \left(x, y\right) = \sum_{i=1}^{n} |x_i - y_i| $$ p = 2 时,就是欧氏距离 ⬆️ 例如:(7, 2)和(4, 6)两个点的距离 ## 3、4.关联模式挖掘 目标是确定数据项之间的关联性,常见的如商品之间的关联。 `项集`:项的集合,K 项集就是恰好包含 k 个项的项集 `支持度计数`:σ,指这个项集在总事务中出现的次数 `支持度`:就是支持度计数除以总事务数 $$ % 支持度的公式 \text{Support}(A) = \frac{\text{事务中包含项集 } A \text{ 的数量}}{\text{总事务数量}} $$ `频繁项集`:一个项集的支持度大于等于预先设定的最小支持度 `置信度`:T 事务中已经包含 X 的情况下,包含 Y 的百分比,即条件概率。 $$ % 置信度的公式 \text{Confidence}(A \rightarrow B) = \frac{\text{Support}(A \cap B)}{\text{Support}(A)} $$ `提升度`:指 A 项和 B 项一同出现的频率,但同时要考虑这两项各自出现的频率。 $$ % 提升度的公式 \text{Lift}(A \rightarrow B) = \frac{\text{Support}(A \cap B)}{\text{Support}(A) \times \text{Support}(B)} $$ 频繁项集的生成 * `Apriori`算法:先找频繁一项集,再找二项,以此类推。 * `FP-growth`FP 增长算法:两次扫描数据库建立一个 FP 树,避免了产生大量的候选项集。效率更高 关联规则的评估:看提升度,支持度和置信度仅用于度量 ![bangwu\_20240622154249](https://cdn.bangwu.top/img/bangwu_20240622154249.webp) ## 5.聚类分析 ### 5.1 聚类分析概述 “物以类聚,人以群分”,`聚类`就是在预先不知道欲划分类的情况下,根据信息 相似度原则进行信息集聚的一种方法。主要用到的是相异性的距离度量。 常用的聚类方法:基于划分的 K-means 聚类,层次聚类,DBSACN 等 ### 5.2K-means 聚类 K-means 是基于划分的聚类,将样本划分成 k 个不重合的类(cluster)每个簇关联一个质心,每个点都分配给离质心最近的簇,K 的数量必须事先人工指定。![动图](https://cdn.bangwu.top/img/v2-169818722555497ae9d461a7352fabd1_b.webp) 由于初始质心的选择对结果有影响,可以有以下解决方案: 1. 多次运行聚类 2. 选择多于 K 的初始质心,然后在其中选择二 3. 二分 K-means 聚类(不易受到初始化问题的影响) **K-means 的评估**: $$ % SSE 公式 \text{SSE} = \sum_{i=1}^{k} \sum_{x \in C_i} \| x - \mu_i \|^2 $$ 其中: k 是簇的数量 C\_i 是第 i 个簇 x 是簇 C\_i 中的一个数据点 u\_i 是簇 C\_i 的中心 | x - u\_i |^2 表示数据点 x 与簇中心 u\_i 之间的欧氏距离的平方 **SSE 值越小,表示聚类效果越好**,减少 SSE 的一个简单方法是增加 K,即簇的数量 二分 K-means 算法步骤:【**理解**】 1. **初始化**:将所有数据点作为一个簇。 2. 迭代过程: * 对当前簇进行二分(即将簇分成两个子簇)。 * 使用传统的 K-means 算法对这两个子簇进行优化。 * 选择使得总平方误差和(SSE)最小的二分结果。 3. **重复**:继续对簇进行二分,直到达到预定的簇数量 𝑘*k* 为止。 ### K-Means 算法里,当邻近度函数采用(? )的时候,合适的质心是簇中各点的中位数。 1. 曼哈顿距离。质心:中位数。目标函数:最小化对象到其簇质心的距离和 2. 平方欧几里德距离。质心:均值。目标函数:最小化对象到其簇质心的距离的平方 和 3. 余弦。质心:均值。最大化对象与其质心的余弦相似度和 4. Bregman 散度。质心:均值。目标函数:最 小化对象到其簇质心的 Bregma n 散度和 ### 5.3 层次聚类 `层次聚类`(Hierarchical Clustering)是聚类算法的一种,通过计算不同类别数据点间的相似度来创建一棵有层次的嵌套聚类树。 论数据集应该聚类成多少个簇,通常是在讨论我们在什么尺度上关注这个数据集。层次聚类算法相比划分聚类算法的优点之一是可以在不同的尺度上(层次)展示数据集的聚类情况。层次聚类使用欧式距离来计算不同类别数据点间的距离(相似度)。 ![img](https://cdn.bangwu.top/img/1180120-20180721004137992-1540374438.png) 基于层次的聚类算法(Hierarchical Clustering)可以是凝聚的(Agglomerative)或者分裂的(Divisive),取决于层次的划分是“自底向上”还是“自顶向下”。 凝聚的层次聚类计算两个组合数据点间距离的方法有三种,Min-单链或最短边、Max-全链或最长边、Average-组平均或平均边。方法的优劣自行斟酌。 层次聚类的问题: * 算法复杂度较高 * 一旦决定合并两个簇,就不能撤销 * 没有可以直接最小化的目标函数 * 对噪声和异常值的**敏感**难以处理大小不同的簇和凸形状的簇 ### 5.4 密度聚类 DBSCAN 作为一种典型的密度聚类方法,它的聚类原理当然是和密度有关。简单来讲,DBSCAN 一般假定样本的类别可以通过样本分布的紧密程度决定,于是先发现密度较高的点,然后把相近的高密度点逐步连成一片,进而找到不同的类别(簇)。 ![](https://cdn.bangwu.top/img/document-uid214893labid6102timestamp1531806243633.png) 如上图所示,假设我们指定密度阈值 `MinPts = 4`,那么图中的红色点就是核心点,因为它们的 𝜀-邻域里包含最少 4 个点(包括自己),由于它们之间相互可达,它们形成了一个聚类。图中蓝色的点不是核心点,但它们在核心点的圆圈内,所以也属于同一个聚类,也就是边界点。而紫色点既不是核心点,又不是边界点,即被称之为异常点(噪声点)。 ### 5.5 聚类算法评估 有效性度量: * 外部指标:有监督的,提供标签(一般是人工标记) * 内部标记:无监督的,SSE,凝聚度(WSS)和分离度(BSS),轮廓系数 * 相对指标:用于比较两个不同的聚类过程或簇,综合内外部指标 $$ % 凝聚度 (WSS) 公式 \text{WSS} = \sum_{i=1}^{k} \sum_{x \in C_i} \| x - \mu_i \|^2 $$ $$ % 分离度 (BSS) 公式 \text{BSS} = \sum_{i=1}^{k} n_i \| \mu_i - \mu \|^2 $$ ## 6.分类算法 ### 6.1 分类算法概述 分类是在一群已经知道类别标号的样本中,训练一种分类器,让其能够对某种未知的样本进行分类。分类算法属于一种有监督的学习。分类算法的分类过程就是建立一种分类模型来描述预定的数据集或概念集,通过分析由属性描述的数据库元组来构造模型。分类的目的就是使用分类对新的数据集进行划分,其主要涉及分类规则的准确性、过拟合、矛盾划分的取舍等。 常用的分类算法包括:NBC(Naive Bayesian Classifier,朴素贝叶斯分类)算法、LR(Logistic Regress,逻辑回归)算法、ID3(Iterative Dichotomiser 3 迭代二叉树 3 代)决策树算法、C4.5 决策树算法、C5.0 决策树算法、SVM(Support Vector Machine,支持向量机)算法、KNN(K-Nearest Neighbor,K 最近邻近)算法、ANN(Artificial Neural Network,人工神经网络)算法等 ### 6.2 分类算法评估 推荐阅读:[https://www.cnblogs.com/guoyaohua/p/classification-metrics.html](https://www.cnblogs.com/guoyaohua/p/classification-metrics.html) ### 6.3 朴素贝叶斯分类器 分类原理:利用贝叶斯公式根据某特征的先验概率计算出其后验概率,然后选择具有最大后验概率的类作为该特征所属的类。 之所以称之为”朴素”,是因为贝叶斯分类只做最原始、最简单的假设:所有的特征之间是统计独立的。 朴素贝叶斯分类器的特点: * 对孤立噪声点、不相关属性的鲁棒性,可以忽略缺失值 * 条件独立性假设问题,采用贝叶斯网络 ### 6.4 决策树 `决策树`分为`分类决策树`和`回归决策树`。有两大核心问题: 1. 决策树的生长:决策树的分枝准则,有 C5.0、CHAID、QUEST、CART。【根部节点,中间节点,停止分支】 2. 决策树的剪枝:预修剪、后修剪 `ID3算法`:计算信息增益/信息获利 `C4.5算法`:是`ID3`的修订版,采用 GainRatio 来加以改进方法,选取有最大 GainRatio 的分割变量作为准则,避免 ID3 算法过度配适的问题。 `C5.0算法`:是 C4.5 算法的修订版 ,适用在处理大数据集,采用 Boosting 方式提高模型准确率,又称为 Boosting Trees,在软件上的计算速度比较快,占用的内存资源较少。 `CART算法`:这种算法即可以用于分类,也可以用于回归问题。CART 算法使用了基尼系数取代了信息熵模型。CART 与 C4.5/C5.0 算法的最大相异之处是其在每一个节点上都是采用二分法,也就是一次只能够有两个子节点,C4.5/5.0 则在每一个节点上可以产生不同数量的分枝。 各个算法的计算可能会考到,请自行查阅。 ### 6.5 神经网络 人工神经网络——`ANN`: ![bangwu\_20240622182337](https://cdn.bangwu.top/img/bangwu_20240622182337.webp) 1. ANN 是由人工神经元连接的多层网络结构。一般组成:输入层、隐藏层、输出层。 2. 网络是由一些列的结点和连接节点的线组成。 3. 节点是运算单元,接受输入、处理输入、进行输出。 4. 连线代表了节点间信息流动,可以单向、可以双向。 神经元模型**五要素**:权重、激活函数、前向传播、[反向传播](https://blog.csdn.net/weixin_37641832/article/details/104917847)、训练。 对 ANN 权重的理解: 1. 一个连接总是带有一个权重值 2. 权重初始化问题 3. 如果某个连接重要,那么它将具有比那些不重要的连接更大的权重值 4. ANN 的学习或训练就是基于输入和期望的输出来改变连接的权重 5. ANN 中输入数据与输出数据不能改变,能改变的只有权重 训练过程就是反向传播误差,调整权重,让误差越来越小。 > 看到这里可以去浏览一遍[要点回顾](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E6%95%B0%E6%8D%AE%E6%8C%96%E6%8E%98/%E7%AC%AC7%E8%AE%B2%20%E6%A1%88%E4%BE%8B%E5%88%86%E6%9E%90%E4%B8%8E%E5%88%86%E7%BB%84%E9%A1%B9%E7%9B%AE%E8%AE%A8%E8%AE%BA.pdf) ## 7.文本挖掘 ### 7.1 文本挖掘概述 `文本挖掘`是抽取有效、新颖、有用、可理解的、散布在文本文件中的有价值知识,并且利用这些知识更好地组织信息的过程。 ### 7.2 文本特征提取 把从文本中抽取出的特征词进行量化来表示文本信息,转换成计算机可以识别处理的信息。 目前大多数中文文本挖掘系统都采用词作为特征项,作为特征项的词称作`特征词`。 通过构造评估函数,对特征集合中的每个特征进行评估,并对每个特征打分,这样每个词语都获得一个评估值,又称为`权值`。 **决定文本特征提取效果的主要因素是评估函数的质量**,`TF-IDF`就是一个评估函数 分词->词性标注 ### 7.3 文本表示技术 ![bangwu\_20240622184908](https://cdn.bangwu.top/img/bangwu_20240622184908.webp) `文本表示`就是将文本转化成数学上的向量表示。如何把字符串转化为向量,就是文本表示的核心问题。【one-hot,word2vec】 ### 7.4 文本相似度计算 相似度是相关度的一种特殊情况,包括上下位关系和同义关系。由此得出, 文本相似度越高, 则相关度越大, 但是相关度越大并不能说明相似度高。 文本相似度计算:基于字符串、基于语料库、基于知识组织、其他方法。 ### 7.5 文本分类 文本分类是指根据预先定义的主题类别,按照一定的规则给文档集合中未知类别的文本自动确定一个类别。 ![bangwu\_20240622185558](https://cdn.bangwu.top/img/bangwu_20240622185558.webp) ### 7.6 情感分析 情感分析是对文本进行上下文挖掘,识别和提取文本中的主观信息(积极、消极和中性),帮助企业了解其品牌、产品或服务的用户情感。 ![bangwu\_20240622185720](https://cdn.bangwu.top/img/bangwu_20240622185720.webp) ### 7.7 主题模型 **主题模型**(Topic Model)在机器学习和自然语言处理等领域是用来在一系列文档中发现抽象主题的一种统计模型。直观来讲,如果一篇文章有一个中心思想,那么一些特定词语会更频繁的出现。比方说,如果一篇文章是在讲狗的,那“狗”和“骨头”等词出现的频率会高些。如果一篇文章是在讲猫的,那“猫”和“鱼”等词出现的频率会高些。而有些词例如“这个”、“和”大概在两篇文章中出现的频率会大致相等。但真实的情况是,一篇文章通常包含多种主题,而且每个主题所占比例各不相同。因此,如果一篇文章 10%和猫有关,90%和狗有关,那么和狗相关的关键字出现的次数大概会是和猫相关的关键字出现次数的 9 倍。一个主题模型试图用数学框架来体现文档的这种特点。主题模型自动分析每个文档,统计文档内的词语,根据统计的信息来断定当前文档含有哪些主题,以及每个主题所占的比例各为多少。 # Data structures and algorithms Source: https://base.bangwu.me/about/courses/data-structure Course notes on data structures covering complexity analysis, linked lists, stacks, binary tree traversals, BFS/DFS graph search, and sorting algorithms.
写在前面 数据结构与算法课程重点均由老师给出 相关课件👉[地址](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95)
# 数据结构与算法考试相关-2024 *** 考试题型 一. 选择题(10分,5题,每题2分) 二. 填空题(15分,5题,每题3分) 三. 简答题(15分,3题,每题5分,要求尽量详细,逻辑清晰,层次分明) 四. 代码题(关键处请写注释;如果需要用所学的数据结构,可以不用定义,直接import使用;请注意代码规范)(60分,6题,每题10分) * 出题思路:从以下重点中出相应的题目,然后再随机选择上述题型和数目,再做微调。 *** 考试重点 ## 第1章 绪论 1. 算法的定义 P8 算法是具有有限步骤的过程,依照这个过程便能解决问题。因此算法就是解决方案。 2. 何谓编程 P13 编程是指通过编程语言将算法编码以使其能被计算机执行的过程。 3. 编程语言的解释 P14-P15 编程语言必须提供一种标记方式:用于表达数据和过程,为此,编程语言提供了众多的数据类型和控制语句。![bangwu\_20240620164507](https://cdn.bangwu.top/img/bangwu_20240620164507.webp) 4. 数据抽象的定义 P20 抽象数据类型(简称ADT)从逻辑上描述了如何看待数据及其对应运算而无须考虑具体实现,这意味着我们仅需要关心数据代表了什么。抽象数据类型的实现就是`数据结构` ## 第2章 Python基础 1. Python语言的基本情况 P5 [Python](https://python.org)是龟叔于20世纪90年代开发的高级计算机语言,截至2024/06/20,python最新的一个大版本是3.12 2. Python解释器 P7 Python解释器可以接收并执行收到的python命令,然后返回结果。IDE 3. Python的注释 P12 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 这段话被注释了 这段没有被注释 ``` 4. Python的标识符和保留字 P17-P18 标识符通常被称为`变量`,python中字母是大小写敏感的。**不能以数字开头**。![bangwu\_20240620174921](https://cdn.bangwu.top/img/bangwu_20240620174921.webp) 5. Python的赋值语句 P21-P24 赋值语句就是`=`,例如: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} a = 1 a += 1 # 是在已存在的对象名a 进行运算,并将新结果重新分配给a # 动态/可变 对象 b = [1, 2, 3] c = b c[1] = 1 print(b) # [1, 1, 3] ``` 6. Python中可变的类和不可变的类 P33-P51 这部分应该熟了,可以参考👉[https://www.cnblogs.com/poloyy/p/15073168.html](https://www.cnblogs.com/poloyy/p/15073168.html) 7. Python的运算符 P54-P64 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 除了正常的加减乘除和逻辑非、与、或之外,值得注意的是相等运算符 # is表示同一实体, ==是等价的意思 a = [1, 2, 3] b = a[:] a == b # True a is b # False # 序列运算符 [5, 6, 9] < [5, 7] # True, 因为所有序列规定的比较操作都是基于字典顺序,即元素一个接一个地比较 ``` 8. Python的输入和输出 P99-P105 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} print('hello', 1) # hello 1\n print('a', 'b', 'c', sep=';', end='@') # a;b;c@ input() fp = open('sample.txt') ``` 9. 迭代器和可迭代对象 P121 可迭代对象:[https://docs.pythontab.com/interpy/Generators/Iterable/](https://docs.pythontab.com/interpy/Generators/Iterable/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Iterator: def __init__(self, squence): self._seq = squence self._index = -1 def __next__(self): self._index += 1 if self._index < len(self._seq): return self._seq[self._index] else: raise StopIteration() def __iter__(self): return self if __name__ == '__main__': a = Iterator([1, 2, 3, 4, 5]) print(next(a), next(a)) n = 2 for i in a: print(i, end=' ') n += 1 ``` 迭代器:[https://docs.pythontab.com/interpy/Generators/Iterator/](https://docs.pythontab.com/interpy/Generators/Iterator/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 任意对象,只要定义了__next__方法,它就是一个迭代器。 class Iterator: def __next__(self): return self if __name__ == '__main__': print(Iterator()) # <__main__.Iterator object at 0x2753730> ``` 10. 迭代器和生成器 P125 生成器:[https://docs.pythontab.com/interpy/Generators/Generators/](https://docs.pythontab.com/interpy/Generators/Generators/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def generator_function(): for i in range(10): yield i for item in generator_function(): print(item, end='->') # Output: 0->1->2->3->4->5->6->7->8->9-> ``` 11. 一行写条件表达式 P129 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} love = 'Male' if male_age ==18 else None ``` 12. 语法解析 P132 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 列表解析 [ k∗k for k in range (1, n +1)] # 集合解析 { k∗k for k in range (1, n +1)} # 生成器解析 ( k∗k for k in range (1, n +1)) # 字典解析 { k: k∗k for k in range (1, n +1)} ``` 13. 打包和解包 P134-P135 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} data = 1,2,3,4 data # (1, 2, 3, 4) # return x, y 等价于 return (x, y) ``` 如果在大的上下文中给出了一系列逗号分隔的表达式,它们将被视为一个单独的元组,即使没有提供封闭的圆括号。这个过程就是`自动打包`。 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} a, b, c, d = range(7, 11) print(a ,b, c, d) # 7 8 9 10 ``` Python 允许单个标识符的一系列元素赋值给序列中的各个元素。右边的表达式可以是任何迭代类型,只要**左边的变量数等于右边选代的元素数**。这个过程就是`自动解包`。 14. 作用域和命名空间 P137-P140 如果不太熟悉可以参考👉[https://www.runoob.com/python3/python3-namespace-scope.html](https://www.runoob.com/python3/python3-namespace-scope.html) ## 第3章 面向对象编程 1. 面向对象的设计目标 P6 面向对象设计目标有三个: * `健壮性`:能够处理未定义的异常输入 * `适应性`:可移植的 * `可重用性`:同样的代码可以用在不同系统的各种应用中 2. 面向对象的设计原则 P11 * 模块化:把程序设计为一个个小方块,各方块相互独立 * 抽象化:就是抽象 * 封装:软件系统的不同组件不应显示其各自实现的内部细节。这点类似于黑盒子。 3. 抽象数据类型 P14 ADT(Abstract Data Types)是数据结构的数学模型,它规定了**数据存储的类型**、**支持的操作**和**操作参数的类型**。 4. 封装的概念 P17 同上述⬆️ 5. 软件开发的三个主要阶段 P25 设计->实现->测试和调试 6. UML图的内容 P31 包含类名、实例变量、方法。 7. 编程风格(不会有专门的题,但编程题要符合该风格) P35 这个真喷不了,可以参考🤣:[https://itniuma.com/article/2023.06/1.html](https://itniuma.com/article/2023.06/1.html) 8. 如何做测试 P42 类似之前的黑盒测试,`方法覆盖`和`语句覆盖`,python中可以参考:[https://www.youtube.com/watch?v=5Md\_3ZeuYPc](https://www.youtube.com/watch?v=5Md_3ZeuYPc) 9. 如何做调试 P43 最简单的print()或者用IDE中提供的Debugger可以更好地进行跟栈。 10. 运算符重载 P55,P58-P59 Python中允许同一运算符根据上下文具有不同的含义,例: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} 1 + 1 # 加法 'hello' + 'world' # 拼接运算符 [1, 2] + [3, 4] # 合并两个列表 ``` 但是对于上述的加法,应用于python内置类还行,自己定义的类是不能直接这样相加的。但可以通过定义来实现类的运算: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Point: def __init__(self, x=0, y=0): self.x = x self.y = y # change add def __add__(self, other): return "Point(x:%d, y:%d)" % (self.x + other.x, self.y + other.y) # change print def __str__(self): return "Point(x:%s, y:%s)" % (self.x, self.y) ``` ![bangwu\_20240620190209](https://cdn.bangwu.top/img/bangwu_20240620190209.webp) ![bangwu\_20240620190230](https://cdn.bangwu.top/img/bangwu_20240620190230.webp) 11. 继承的概念 P67 在面向对象的编程中,模块化和层次化组织的机制称为继承。 继承允许基于一个现有的类作为起点定义新的类。父类(又称为超类或基类)、子类。 子类可以提供新的方法覆盖父类现有的方法,也可以提供全新的扩展方法 12. 抽象基类的概念 P77 在经典的面向对象的术语中,如一个类的唯一目的是作为继承的基类,那么这个类就是一个抽象基类。例如鹦鹉和海鸥可以抽象出一个带有翅膀、会飞翔、有尖嘴....的一个动物,但没有具体的一个现实实例是这样的。 13. 类、对象、子类的命名空间 P80 每个已定义的类都有一个单独的类命名空间。这个命名空间用于管理一个类的所有实例所共享的成员或没有引用任何特定实例的成员。 ![bangwu\_20240620191130](https://cdn.bangwu.top/img/bangwu_20240620191130.webp) 14. 判断深拷贝和浅拷贝 P82-P84 参考👉:[https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html](https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html) ## 第4章 算法分析 1. 什么是数据结构和算法 P9 `数据结构`是组织和访问数据的一种系统化方式。 `算法`是在有限的时间里一步步执行某些任务的过程。 2. 算法分析的维度 P9 时间复杂度和空间复杂度 3. 影响算法运行时间的因素 P12 除了算法本身,影响运行时间的其他因素: * 输入数据的大小 * 硬件环境和软件环境 * 程序是编译执行还是解释执行 4. 实验分析的挑战 P17 很难直接比较两个算法的实验运行时间、实验只有在有限的一组测试输入下才能完成。 5. 如何分析算法效率 P19-P22 计算原子操作、随着输入函数的变化进行测量操作、**最坏情况输入的研究** 6. 大O记法 P26-P27 *O*(n),相信你一定知道。 7. 8种函数 P29-P45 常见时间复杂度从低到高排列有 𝑂(1)、𝑂(log⁡𝑛)、𝑂(𝑛)、𝑂(𝑛log⁡𝑛)、𝑂(𝑛2)、𝑂(2n) 和 𝑂(𝑛!) 等。 8. 列表的性能(不用区分n和k) P47 ![bangwu\_20240620193018](https://cdn.bangwu.top/img/bangwu_20240620193018.webp) 9. 字典的性能 P49 ![bangwu\_20240620193052](https://cdn.bangwu.top/img/bangwu_20240620193052.webp) 10. 异序词检测问题的代码 P51-P58 问题:如果一个字符串只是重排了另一个字符串的字符,那么这个字符串就是另一 个的异序词,比如 heart 与 earth,以及 python 与 typhon。简化问题:两个字符串的长度相同,并且都由26个英文字母的小写组成。 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} words = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') def solution(st1, st2): # O(n*log(n)) if len(st1) == len(st2): for i in range(len(st1)): if st1[i] not in words or st2[i] not in words: return False li1 = list(st1).sort() li2 = list(st2).sort() return li1 == li2 else: return False def solution2(st1, st2): # O(n^2) if len(st1) == len(st2): for i in range(len(st1)): if st1[i] not in words or st2[i] not in words: return False li2 = list(st2) for m in range(len(st1)): index = li2.index(st1[m]) li2[index] = '' return ''.join(li2) == '' else: return False def solution3(st1, st2): # O(n) dic1 = {} dic2 = {} if len(st1) == len(st2): for i in range(len(st1)): dic1[st1[i]] = dic1.get(st1[i], 0) + 1 dic2[st2[i]] = dic2.get(st2[i], 0) + 1 return dic1 == dic2 else: return False ``` ## 第5章 递归 1. 递归的定义和三原则 P4 `递归`定义: * 通过一个函数在执行过程中一次或多次调用其本身 * 或者通过一种数据结构在其中表示依赖于相同类型的结构更小的实例 递归三原则: * 递归算法必须有基本情况(即停止递归的条件——可直接解决的问题) * 递归算法必须改变其状态并向基本情况靠近; * 递归算法必须递归地调用自己 2. 计算一列数之和的递归解法 P9 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def list_sum(num_list): if len(num_list) == 1: return num_list[0] else: return num_list[0] + list_sum(num_list[1:]) ``` 3. 阶乘的递归解法 P14 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) ``` 4. 将整数转换成任意进制字符串的递归解法 P20 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def to_str(n, base): covert_string = '0123456789ABCDEF' if n < base: return covert_string[n] else: return to_str(n // base, base) + covert_string[n % base] ``` 5. 二分查找 P25 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def binary_search(data, target, low, high): if low > high: return False else: mid = (low + high) // 2 if target == data[mid]: return True elif target < data[mid]: return binary_search(data, target, low, mid - 1) else: return binary_search(data, target, mid + 1, high) ``` 6. 汉诺塔问题 P37-P42 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def hannouta(n, A, B, C): if n == 1: print(A, '移到', C) else: hannuota(n-1, A, C, B) hannuota(1, A, B, C) hannuota(n-1, B, A, C) ``` ## 第6章 基本数据结构 1. Python中的序列类型 P6 `list`, `tuple`, `string` 2. 计算机中内存的存储和检索 P8 计算机主存由`位`信息组成,这些`位`通常被归类成更大的单元,这些单元则取决于精准的系统架构。一个典型的单元就是一个字节,相当于8位。存储器(RAM)的任一单个字节被存储或检索的运行时间为*O*(1)。每个字节都被指定了连续的存储地址。 3. 理解列表和元组存放的是引用 P14-18 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} x = (1, 2, [3, 4]) y = x y[2][0] = 10 print(x) # 输出 (1, 2, [10, 4]) ``` 这段内容可以和深拷贝、浅拷贝一块理解。 4. 动态数组的实现 P27 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import ctypes class DynamicArray: def __init__(self): self._n = 0 self._capacity = 1 self._A = self._make_array(self._capacity) def __len__(self): return self._n def __getitem__(self, k): if not 0 <= k < self._n: raise IndexError('invalid index') return self._A[k] def append(self, obj): if self._n == self._capacity: self._resize(2 * self._capacity) self._A[self._n] = obj self._n += 1 def _make_array(self, c): return (c * ctypes.py_object)() def _resize(self, c): B = self._make_array(c) for k in range(self._n): B[k] = self._A[k] self._A = B self._capacity = c def remove(self, value): for k in range(self._n): if self._A[k] == value: for j in range(k, self._n - 1): self._A[j] = self._A[j + 1] self._A[self._n - 1] = None self._n -= 1 raise ValueError('value not found') def insert(self, k, value): if self._n == self._capacity: self._resize(2 * self._capacity) for j in range(self._n, k, -1): self._A[j] = self._A[j - 1] self._A[k] = value self._n += 1 if __name__ == '__main__': A = DynamicArray() A.append(1) print(A._capacity) A.append(2) A.append(3) print(A._capacity) ``` 5. 二维数组的构建 P43-P46 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # data = ([0] * c) * r 会得出[0,0,0,0]不是二维的 # data = [[0] * c] * r 会构建出指向同一个[0]*c data = [[0] * c for j in range(r)] ``` 6. 栈的定义 P50 栈(stack)是一种遵循先入后出逻辑的线性数据结构。 7. 栈的抽象数据类型 P55-P56 ![栈的先入后出规则](https://cdn.bangwu.top/img/stack_operations.png) | 方法 | 描述 | 时间复杂度 | | - | - | - | | push() | 元素入栈(添加至栈顶) | *O*(1) | | pop() | 栈顶元素出栈 | *O*(1) | | peek() | 访问栈顶元素 | *O*(1) | 8. 栈的实现 P61 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class ArrayStack: def __init__(self): self._stack = [] def __len__(self): return len(self._stack) def __str__(self) -> str: return str(self._stack) def is_empty(self): return len(self) == 0 def push(self, e): self._stack.append(e) def top(self): if self.is_empty(): raise ValueError('Stack is empty') return self._stack[-1] def pop(self): if self.is_empty(): raise ValueError('Stack is empty') return self._stack.pop() ``` 9. 括号匹配的代码实现 P69 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def is_matched(expr): lefty = '([{' righty = ')]}' S = ArrayStack() for c in expr: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False if righty.index(c) != lefty.index(S.pop()): return False return S.is_empty() ``` 10. 标记语言的标签匹配的代码实现 P72 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def is_matched_html(raw: str): S = ArrayStack() j = raw.find('<') while j != -1: k = raw.find('>', j+1) if k == -1: return False tag = raw[j+1:k] if not tag.startswith('/'): S.push(tag) else: if S.is_empty(): return False if tag[1:] != S.pop(): return False j = raw.find('<', k+1) return S.is_empty() ``` 11. 十进制转换成任意进制数的代码实现 P75 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def base_converter(dec_number, base): digits = "0123456789ABCDEF" rem_stack = ArrayStack() while dec_number > 0: rem = dec_number % base rem_stack.push(rem) dec_number = dec_number // base new_string = "" while not rem_stack.is_empty(): new_string = new_string + digits[rem_stack.pop()] return new_string ``` 12. 实现python的运算:先从中序转后序,再计算后序 P87,P93 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 这段大概率是不会出的 from array_stack import ArrayStack import string def infix_to_post_fix(infix_expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = ArrayStack() post_fix_list = [] token_list = infix_expr.split() for token in token_list: if token in string.ascii_uppercase: post_fix_list.append(token) elif token == "(": op_stack.push(token) elif token == ")": top_token = op_stack.pop() while top_token != "(": post_fix_list.append(top_token) top_token = op_stack.pop() else: while (not op_stack.is_empty()) and \ (prec[op_stack.top()] >= prec[token]): post_fix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.is_empty(): post_fix_list.append(op_stack.pop()) return " ".join(post_fix_list) if __name__ == "__main__": # infix_expr = "( A + B ) * ( C + D )" # infix_expr = "( A + B ) * C" infix_expr = "A + B * C" print(infix_to_post_fix(infix_expr)) ``` 13. 队列的定义 P95,P97 队列(queue)是一种遵循先入先出规则的线性数据结构。顾名思义,队列模拟了排队现象,即新来的人不断加入队列尾部,而位于队列头部的人逐个离开。 14. 队列的抽象数据类型 P98 ![队列的先入先出规则](https://cdn.bangwu.top/img/queue_operations.png) | 方法 | 描述 | 时间复杂度 | | - | - | - | | push() | 元素入队,即将元素添加至队尾 | *O*(1) | | pop() | 队首元素出队 | *O*(1) | | peek() | 访问队首元素 | *O*(1) | 15. 队列的实现 P101 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class ArrayQueue: """FIFO Queue implementation using a Python list as underlying storage.""" def __init__(self): """Create an empty queue.""" self._data = [] def __len__(self): """Return the number of elements in the queue.""" return len(self._data) def is_empty(self): """Return True if the queue is empty.""" return len(self._data) == 0 def enqueue(self, e): """Add element e to the back of the queue.""" self._data.append(e) # new item stored at end of list def first(self): """Return (but do not remove) the element at the front of the queue. Raise Empty exception if the queue is empty. """ if self.is_empty(): raise Empty('Queue is empty') return self._data[0] # the last item in the list def dequeue(self): """Remove and return the first element of the queue (i.e., FIFO). Raise Empty exception if the queue is empty. """ if self.is_empty(): raise Empty('Queue is empty') return self._data.pop(0) # remove last item from list ``` 16. 传土豆的代码实现 P105 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def hot_potato(name_list, num): sim_queue = ArrayQueue() for name in name_list: sim_queue.enqueue(name) while len(sim_queue) > 1: for i in range(num): sim_queue.enqueue(sim_queue.dequeue()) sim_queue.dequeue() print(sim_queue._data) return sim_queue.dequeue() if __name__ == "__main__": name_list = ['Bill', 'David', 'Susan', 'Jane', 'Kent', 'Bard'] num = 6 win = hot_potato(name_list, num) print(win) ``` 17. 双端队列的定义 P107 在队列中,我们仅能删除头部元素或在尾部添加元素。双向队列(double-ended queue)提供了更高的灵活性,允许在头部和尾部执行元素的添加或删除操作。 18. 双端队列的抽象数据类型 P108 ![双向队列的操作](https://cdn.bangwu.top/img/deque_operations.png) | 方法名 | 描述 | 时间复杂度 | | - | - | - | | `push_first()` | 将元素添加至队首 | O(1) | | `push_last()` | 将元素添加至队尾 | O(1) | | `pop_first()` | 删除队首元素 | O(1) | | `pop_last()` | 删除队尾元素 | O(1) | | `peek_first()` | 访问队首元素 | O(1) | | `peek_last()` | 访问队尾元素 | O(1) | 19. 双端队列的实现 P110 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Deque: def __init__(self): self._data = [] def __len__(self): return len(self._data) def is_empty(self): return len(self._data) == 0 def add_first(self, e): self._data.insert(0, e) def add_last(self, e): self._data.append(e) def delete_first(self): if self.is_empty(): raise Empty('Deque is empty') return self._data.pop(0) def delete_last(self): if self.is_empty(): raise Empty('Deque is empty') return self._data.pop() def first(self): if self.is_empty(): raise Empty('Deque is empty') return self._data[0] def last(self): if self.is_empty(): raise Empty('Deque is empty') return self._data[-1] ``` 20. 回文检测器的实现 P113 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 回文是指从前往后读和从后往前读是一样的。例如radar, toot def palchecker(a_string): print(a_string) char_deque = Deque() for ch in a_string: char_deque.add_last(ch) still_equal = True while len(char_deque) > 1 and still_equal: print(char_deque.first(), char_deque.last()) first = char_deque.delete_first() last = char_deque.delete_last() if first != last: still_equal = False return still_equal if __name__ == "__main__": # a_string1 = 'lsdkjfskf' a_string1 = '上海自来水来自海上' print(palchecker(a_string1)) a_string2 = 'TENET' print(palchecker(a_string2)) ``` 21. 列表的缺点 P115 * 一个动态数组的长度可能超过实际存储数组元素所需的长度 * 在实时系统中对操作的摊销边界是不可接受的 * **在一个数组内部执行插入和删除操作的代价太高**
理解Python列表类的这三个缺点可以帮助我们更好地选择和使用数据结构。下面是对每个缺点的详细解释: 1. **一个动态数组的长度可能超过实际存储数组元素所需的长度** 动态数组(如Python中的列表)为了提高插入操作的效率,通常会预留一些额外的空间。这意味着数组的实际长度可能比当前存储的元素数量要大。这种做法可以减少频繁的内存分配和数据拷贝操作,但也会导致内存浪费。例如,如果你有一个包含10个元素的列表,底层数组可能已经分配了20个或更多的空间,以便为未来的插入操作预留空间。这种内存预分配机制虽然提高了性能,但在内存紧张的环境下可能会成为问题。 2. **在实时系统中对操作的摊销边界是不可接受的** 摊销分析(Amortized Analysis)是计算数据结构操作时间的一种方法,它将一系列操作的总成本平均分摊到每个操作上。对于动态数组来说,插入操作的摊销时间复杂度是 (O(1)),但在最坏情况下(当数组需要扩展时),单次插入的时间复杂度可以达到 (O(n))。在实时系统中,要求每个操作必须在严格的时间界限内完成,因此最坏情况的操作时间不可预测和不可接受。这意味着在实时系统中使用动态数组可能导致性能问题,因为你无法保证每个操作在规定时间内完成。 3. **在一个数组内部执行插入和删除操作的代价太高** 动态数组在内部执行插入和删除操作时,需要移动数组中的元素。例如,要在数组的开头插入一个新元素,所有现有元素都必须向后移动一个位置,这样的操作的时间复杂度是 (O(n))。同样地,在数组中间删除一个元素也需要将后续的元素前移,这同样是 (O(n)) 的操作。对于频繁插入和删除的场景,这种操作代价太高,导致性能瓶颈。如果你的应用需要频繁在列表中间插入或删除元素,使用链表(Linked List)或双端队列(Deque)等数据结构可能会更高效。 总结: * 动态数组的内存预留机制虽然提升了插入操作的效率,但会导致内存浪费。 * 摊销时间在实时系统中不可接受,因为你无法预知最坏情况下的操作时间。 * 插入和删除操作的高代价使得动态数组在频繁修改的场景中表现不佳。 理解这些缺点有助于在选择数据结构时做出更明智的决定,根据具体应用场景选择最适合的数据结构以提高程序的性能和效率。
22. 链表的定义 P116-P118 链表(linked list)是一种线性数据结构,其中的每个元素都是一个节点对象,各个节点通过“引用”相连接。引用记录了下一个节点的内存地址,通过它可以从当前节点访问到下一个节点。 23. 链表的抽象数据类型 P119-120 ![链表定义与存储方式](https://cdn.bangwu.top/img/linkedlist_definition.png) | | 数组(List) | 链表 | | - | - | - | | 存储方式 | 连续内存空间 | 分散内存空间 | | 容量扩展 | 长度不可变 | 可灵活扩展 | | 内存效率 | 元素占用内存少,但可能浪费空间 | 元素占用内存多 | | 访问元素 | O(1) | O(n) | | 添加元素 | O(n) | O(1) | | 删除元素 | O(n) | O(1) | 24. 链表的实现 P121-P139 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 首先构建Node类 class Node: def __init__(self, initdata): self.data = initdata self.next = None def get_data(self): return self.data def get_next(self): return self.next def set_data(self, new_data): self.data = new_data def set_next(self, new_next): self.next = new_next # 构建链表 class UnordredList: def __init__(self): self.head = None def is_empty(self): return self.head == None def add(self, item): temp = Node(item) temp.set_next(self.head) self.head = temp def length(self): count = 0 current = self.head while current != None: count += 1 current = current.get_next() return count def search(self, item): current = self.head while current != None: if current.get_data() == item: return True else: current = current.get_next() return False def remove(self, item): current = self.head previous = None found = False while not found: if current.get_data() == item: found = True else: previous = current current = current.get_next() if previous == None: self.head = current.get_next() else: previous.set_next(current.get_next()) def append(self, item): current = self.head while current.get_next() != None: current = current.get_next() current.set_next(Node(item)) def insert(self, pos, item): current = self.head previous = None count = 0 while count != pos: count += 1 previous = current current = current.get_next() insert_item = Node(item) insert_item.set_next(current) previous.set_next(insert_item) def index(self, item): current = self.head count = 0 while current.get_data() != item: if current.get_next() == None: return "Not Found" else: count +=1 current = current.get_next() return count def pop (self, pos=None): if pos == None: current = self.head previous = None while current.get_next() != None: previous = current current = current.get_next() previous.set_next(None) return current.get_data() else: current = self.head previous = None count = 0 while count != pos: count += 1 previous = current current = current.get_next() previous.set_next(current.get_next()) return current.get_data() ``` 25. 具备解决新问题的能力(对已有问题的简单扩展) ![](https://cdn.bangwu.top/assets/sticker/gifs/amongus_bingo.gif) ## 第7章 搜索和排序 搜索是一场未知的冒险,我们或许需要走遍神秘空间的每个角落,又或许可以快速锁定目标。 1. 无序的顺序搜索的实现和分析 P9-P10 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 无序列表的顺序搜索 def sequential_search(a_list, item): pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos += 1 return found # 最暴力的方法,最坏的情况是O(n) ``` 2. 有序的顺序搜索的实现和分析 P12-P13 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 有序列表的顺序搜索 def ordered_sequential_search(a_list, item): pos = 0 found = False stop = False while pos < len(a_list) and not found and not stop: if a_list[pos] == item: found = True else: if a_list[pos] > item: stop = True else: pos += 1 return found # 最坏的情况仍是O(n)但不存在目标元素是可以减少执行次数,因为stop的存在 ``` 3. 三种二分搜索的实现和分析 P16-P21 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 循环实现 def binary_search(a_list, item): first = 0 last = len(a_list) - 1 found = False while first <= last and not found: mid_point = (first + last) // 2 if a_list[mid_point] == item: found = True else: if item < a_list[mid_point]: last = mid_point - 1 else: first = mid_point + 1 return found # 递归实现1 def binary_search_r(a_list, item): if len(a_list) == 0: return False else: mid_point = len(a_list) // 2 if a_list[mid_point] == item: return True else: if item < a_list[mid_point]: return binary_search_r(a_list[:mid_point], item) else: return binary_search_r(a_list[mid_point+1:], item) # 递归实现2 def binary_search(data, target, low, high): if low > high: return False # interval is empty; no match else: mid = (low + high) // 2 if target == data[mid]: # found a match return True elif target < data[mid]: return binary_search(data, target, low, mid-1) else: return binary_search(data, target, mid+1, high) ``` 对于上述的两种递归,第二种更好因为第二种是对原始`data`进行索引,没有创建新的列表。时间复杂度都是*O*(log*n*) 4. 散列表的定义和目标 P24-P32 哈希表(hash table),又称散列表,它通过建立键 `key` 与值 `value` 之间的映射,实现高效的元素查询。具体而言,我们向哈希表中输入一个键 `key` ,则可以在 𝑂(1) 时间内获取对应的值 `value` 。这样就解决了列表搜索只能循环查找的问题。 哈希冲突:从本质上看,哈希函数的作用是将所有 `key` 构成的输入空间映射到数组所有索引构成的输出空间,而输入空间往往远大于输出空间。因此,**理论上一定存在“多个输入对应相同输出”的情况**。例如: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} 12836 % 100 = 36 20336 % 100 = 36 ``` ![哈希冲突示例](https://cdn.bangwu.top/img/hash_collision.png) **可以通过扩容哈希表容量来减少冲突。** 5. 常用的散列函数 P32-P37 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def hash(a_string, table_size): sum = 0 for pos in range(len(a_string)): sum += ord(a_string[pos]) return sum % table_size def hash_pro(a_string, table_size): sum = 0 for pos in range(len(a_string)): sum += ord(a_string[pos]) * (pos + 1) return sum % table_size # 以上两个函数是用来key和index的,比如hash('cat', 100)返回12 ``` 6. 再散列的方法 P39-P49 `再散列`泛指在发生冲突后寻找另一个槽的过程。这里引入一个解决哈希冲突的一个方法:`开放定址法` 可参考👉[https://www.cnblogs.com/east7/p/12594894.html](https://www.cnblogs.com/east7/p/12594894.html) 还有一种方法是`链接法`就是允许哈希表同一个位置存在多个元素,也就是位置上存储的是元素集合。![bangwu\_20240621164449](https://cdn.bangwu.top/img/bangwu_20240621164449.webp) 但是这种方法也是有缺陷的: * 由于每个槽都有一个元素集合,因此需要再搜索一次,才能得知目标元素是否存在 7. HashTable P55-P56 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # slots用于存储key, data用来存储value class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hash_value = self.hash_function(key, len(self.slots)) if self.slots[hash_value] == None: self.slots[hash_value] = key self.data[hash_value] = data else: if self.slots[hash_value] == key: self.data[hash_value] = data # replace the old data else: next_slot = self.rehash(hash_value, len(self.slots)) while self.slots[next_slot] != None and self.slots[next_slot] != key: next_slot = self.rehash(next_slot, len(self.slots)) if self.slots[next_slot] == None: self.slots[next_slot] = key self.data[next_slot] = data else: self.data[next_slot] = data # replace the old data def hash_function(self, key, size): return key % size def rehash(self, old_hash, size): return (old_hash + 1) % size def get(self, key): start_slot = self.hash_function(key, len(self.slots)) data = None stop = False found = False position = start_slot while self.slots[position] != None and not found and not stop: if self.slots[position] == key: found = True data = self.data[position] else: position = self.rehash(position, len(self.slots)) if position == start_slot: stop = True return data def __getitem__(self, key): # 允许对象通过索引访问其元素 return self.get(key) def __setitem__(self, key, data): # 允许对象通过索引设置其元素的值 self.put(key, data) ``` 8. 分析散列搜索算法 P58 引入一个定义:`载荷因子`,表示哈希表的占用率,`已被占用槽数`/`总槽数` ![bangwu\_20240621165659](https://cdn.bangwu.top/img/bangwu_20240621165659.webp) 9. 排序过程 P61 首先,排序算法要能比较大小;其次,当元素的排列顺序不正确时,需要交换它们的位置。 10. 冒泡排序的实现和分析 P65-P66 `冒泡排序`(bubble sort)通过连续地比较与交换相邻元素实现排序。这个过程就像气泡从底部升到顶部一样,因此得名冒泡排序。 1. 首先,对 𝑛 个元素执行“冒泡”,**将数组的最大元素交换至正确位置**。 2. 接下来,对剩余 𝑛−1 个元素执行“冒泡”,**将第二大元素交换至正确位置**。 3. 以此类推,经过 𝑛−1 轮“冒泡”后,**前 𝑛−1 大的元素都被交换至正确位置**。 4. 仅剩的一个元素必定是最小元素,无须排序,因此数组排序完成。 ![冒泡排序流程](https://cdn.bangwu.top/img/bubble_sort_overview.png) ![img](https://cdn.bangwu.top/img/849589-20171015223238449-2146169197.gif) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 时间复杂度O(n2),总共比较了n(n-1)/2次 也就是1+2+3+...+n-1 # 通常被认为是效率最低的排序算法 def bubble_sort(a_list): for pass_num in range(len(a_list) - 1, 0, -1): for i in range(pass_num): if a_list[i] > a_list[i + 1]: a_list[i], a_list[i + 1] = a_list[i + 1], a_list[i] ``` 11. 选择排序的实现和分析 P69-P70 `选择排序`(selection sort)的工作原理非常简单:开启一个循环,每轮从未排序区间选择最小的元素,将其放到已排序区间的末尾。 1. 设数组的长度为n,初始状态下,所有元素未排序,即未排序(索引)区间为 \[0,𝑛−1] 。 2. 选取区间 \[0,𝑛−1] 中的最小元素,将其与索引 0 处的元素交换。完成后,数组前 1 个元素已排序。 3. 选取区间 \[1,𝑛−1] 中的最小元素,将其与索引 1 处的元素交换。完成后,数组前 2 个元素已排序。 4. 以此类推。经过 𝑛−1 轮选择与交换后,数组前 𝑛−1 个元素已排序。 5. 仅剩的一个元素必定是最大元素,无须排序,因此数组排序完成。 ![img](https://cdn.bangwu.top/img/7789414-95f142a9696c4cf8.png.webp) ![img](https://cdn.bangwu.top/img/7789414-5893f3ff1b915c38.gif.webp) 说明:此动图为优化后的选择排序,每趟只交换一次 ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 时间复杂度O(n2) # 相比于冒泡排序,降低了交换次数 def selection_sort(a_list): for fill_slot in range(len(a_list)-1, 0, -1): position_of_max = 0 for location in range(1, fill_slot + 1): if a_list[location] > a_list[position_of_max]: position_of_max = location a_list[fill_slot], a_list[position_of_max] = a_list[position_of_max], a_list[fill_slot] ``` 12. 插入排序的实现和分析 P73-P74 `插入排序`(insertion sort)是一种简单的排序算法,它的工作原理与手动整理一副牌的过程非常相似。 具体来说,我们在未排序区间选择一个基准元素,将该元素与其左侧已排序区间的元素逐一比较大小,并将该元素插入到正确的位置。 1. 初始状态下,数组的第 1 个元素已完成排序。 2. 选取数组的第 2 个元素作为 `base` ,将其插入到正确位置后,**数组的前 2 个元素已排序**。 3. 选取第 3 个元素作为 `base` ,将其插入到正确位置后,**数组的前 3 个元素已排序**。 4. 以此类推,在最后一轮中,选取最后一个元素作为 `base` ,将其插入到正确位置后,**所有元素均已排序**。 ![bangwu\_20240621172011](https://cdn.bangwu.top/img/bangwu_20240621172011.webp) ![img](https://cdn.bangwu.top/img/849589-20171015225645277-1151100000.gif) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 时间复杂度依然是O(n2),在基准测试中,插入排序算法的性能很不错 # 最好的情况下(列表已经是有序的),每轮秩序比较一次 # 移动操作和交换操作有一个重要的不同点。总体来说,交换操作的处理时间大约是移动操作的 3 倍,因为后者只需进行一次赋值 def insertion_sort(a_list): for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position-1] > current_value: a_list[position] = a_list[position-1] position = position - 1 a_list[position] = current_value ``` 13. 搜索和排序时间复杂度的总结 P91 ![bangwu\_20240621172317](https://cdn.bangwu.top/img/bangwu_20240621172317.webp) ## 8.总结 没有总结 ![](https://cdn.bangwu.top/assets/sticker/gifs/amongus_jump.gif) # Data visualization and informetrics Source: https://base.bangwu.me/about/courses/data-visualization Course notes on informetrics covering Lotka's law, Bradford's journal distribution law, Zipf's word frequency law, and citation analysis. # 数据可视化 选择、名词解释 ## 信息计量学绪论 ### 1. 信息计量学的由来和产生背景 利用“引文分析法”研究一些国家的化学家所做的贡献;——>“书目分析法”——>“统计书目学”——>“洛特卡”定律揭示了**作者与著作量**之间的数量关系——>根据被引次数列出核心期刊——>“布拉德福定律”反应**科学论文**在科技期刊中的分布规律——>“齐普夫定律”反应科学文献中的**词频分布**规律——>“半衰期”揭示科学文献的老化规律——>期刊数量的指数增长规律——>“信息计量学”Informetrics ### 2. 信息计量学的基本内容 信息计量学被定义为:采用定量方法来描述和研究信息的现象、过程和规律的一门学科。 狭义信息计量学主要是研究情报信息的计量问题。 ### 3. 信息计量学的相关学科 ![bangwu20250424130351.jpg](https://cdn.bangwu.top/img/s0e6z-xqbangwu20250424130351.webp) ### 4. 信息计量学的发展趋势 1. 从文献计量向信息计量发展 2. 计算机辅助的信息计量研究和应用 3. xxx 计量学的产生和发展 ## 文献信息增长规律 ### 一、文献信息流的特征及增长规律研究 > 文献流 科技文献的汇流 > 文献信息流 文献中所含信息的总汇 文献信息流**特性**: 1. 动态特性——随时间的延续而增长或老化的性质【文献信息增长规律、文献信息老化规律】 2. 静态特性——在一定时间内,科学文献在空间的离散分布的性质【布拉德福定律、齐普夫定律、洛特卡定律】 科学文献增长规律的研究是信息计量学的主要研究课题之一。 > 分类 一、绝对值指标、相对值指标 二、累计数、非累计数 ### 二、文献信息增长模型(规律) 1. 指数增长模型【年增长率近似等于持续增长率】在一定时期内,科技文献的数量会随着时间呈指数级快速增长。只有当事物的“持续增长率”为常数时,才满足“指数增长规律” 2. 逻辑增长模型【考虑到文献数量不可能无限增长,一些学者(如前苏联的纳里莫夫和弗莱杜茨)提出了逻辑曲线模型,作为对指数增长模型的补充和修正】初始阶段符合指数增长,成熟阶段逻辑增长 3. 线性增长模型【年增长量为常数】 4. 分级滑动指数模型【与纯粹的指数增长(持续高速)或平滑过渡到饱和的逻辑曲线(单一 S 形)不同,分级滑动指数模型认为文献增长不是一个连续平滑的过程,而是呈现出多个增长阶段叠加的形态,看起来像一个“阶梯”状的上升曲线】只有在文献量足够大的时候才成立 ## 文献信息老化规律 > 文献老化 科学文献随其“年龄”的增长,失去了作为科学情报源的价值,以及因此越来越少被科学家和专家们利用的过程。 ![bangwu20250424171349.jpg](https://cdn.bangwu.top/img/110ruz-9obangwu20250424171349.webp) > 半衰期 指当前被引用的全部文献中,有多达一半是最近多少年内发表的。【这个“多少年”就是该学科文献的引文半衰期(Citation Half-Life)】 > 普莱斯指数 指某一领域或期刊的参考文献中,发表于最近若干年(通常是 5 年)内的文献所占的百分比。【 这个指数反映了一个领域对近期文献的依赖程度】 ## 布齐洛分布 * 布 - 布拉德福定律(Bradford's Law):描述了科学文献在期刊中的分散规律。该定律指出,如果按其载文量对期刊进行排序,可以将期刊分为三个区,这三个区载有的文章数量大致相等,而每个区包含的期刊数量大致成 1:n:n² 的比例关系。这一定律对于图书馆确定某学科的核心期刊、进行馆藏建设有重要指导意义。 * 齐 - 齐夫定律(Zipf's Law):最初是关于词频分布的定律,指在自然语言的文本中,一个词出现的频率与它在频率表里的排名成反比。后来,这一定律也被推广应用于文献计量学,描述了例如词语、作者、主题等的出现频率与排名之间的关系。 * 洛 - 洛卡定律(Lotka's Law):描述了科学作者的生产力规律。该定律认为,在某一学科领域,著述多产的作者数量较少,而著述不多的作者数量较多。具体来说,发表 n 篇论文的作者数量约是发表 1 篇论文的作者数量的 1/n²。 ## 引文分析 > 引文分析的基本概念和方法: * 区分书目分析法和引文分析法。 * 定义参考文献、引证文献、引文网络和引文分析。 * 阐述引证行为与引证动机,以及引证原则。 * 介绍引文分析的基本类型和步骤(获取数据、整理数据、分析)。 > 引文分布规律及主要指标分析: * 探讨引文结构及意义,包括引文链和引文网络。 * 分析引文量的分布规律及其影响因素。 * 介绍引文的其他指标分析,如引文年代、语种、类型、国别、学科等分布。 * 详细讨论科学文献的自引分析,包括自引的概念、类型、强度(自引率)以及各种自引子类的分析。 > 引文网络与聚类分析: * 解释引文耦合和同引(同被引)的概念、测度指标和特征,并比较它们的异同。 * 简述双引聚类分析的原理和方法步骤。 > 引文分析的主要工具: * 介绍美国《科学引文索引》(SCI)、Web of Science(SCI-E)、《基本科学指标》(ESI)和《期刊引证报告》(JCR)的概况、结构、特点和应用。 * 提及国内引文分析的主要工具,如《中国科学引文数据库》(CSCD)、《中文社会科学引文索引》(CSSCI)等。 > 核心概念: 1. 引文分析:一种以文献引用数据为基础,对各种分析对象的引证与被引证现象进行分析,以便揭示其数量特征和规律的文献计量分析方法。 2. 引文网络:科学文献之间纵向继承和横向联系的交流态势结构。 3. 引文率、影响因子、期刊被引量、平均被引率、当年指标、引证系数:引文测度的主要指标。 4. 引文耦合与同引:两种描述文献之间关系的概念,前者反映引证文献之间的关系,后者反映被引证文献之间的关系。 5. 自引:在文献引用行为中,限于主体本身范围内的引用。 ## DV-DataVisualization 这里只说一些我课上记的,PPT 没细看 ![dv.jpg](https://cdn.bangwu.top/img/198581-n4dv.webp) ## 思考题 信息计量学: 1. 什么叫“信息计量学”?其研究对象和基本内容是什么? 2. 信息计量学的发展趋势是什么? 3. 信息计量学与相关学科的关系是什么? 文献信息流: 1. 何谓文献信息流?它有什么基本特性? 2. 科学文献信息增长律有哪些?以其中两种为例解释它们的基本内容是什么? # Data warehouse Source: https://base.bangwu.me/about/courses/data-warehouse Course notes on data warehousing covering OLTP vs OLAP, ETL pipeline design, star and snowflake schema modeling, and multidimensional OLAP operations.
写在前面 数据仓库按照老师上课的顺序来,这个顺序也是比较合理的 PS:每章的引言部分对理解章节很重要 ![explorer\_OWvhwW5LOW](https://cdn.bangwu.top/img/202312231941201.webp)
# 一、从数据库到数据仓库
引言👈 图灵奖获得者吉姆.格雷提出了一个经验定律,即 网络环境下每18个月产生的数据量等于有史以来 的数据量之和,仅仅依靠数据库管理系统的查询 检索机制和统计分析方法,已经远远不能满足实 际需求。 如何有效地管理和利用数据库中的海量数据,以 及如何发现其中潜在的知识,更好的发挥这些数 据的潜能,数据仓库和数据挖掘技术应运而生。
## 1.1数据仓库(Data Warehouse)产生的原因 数据处理大致可以分为两类: * 操作型处理【也称`联机事务处理`(Online Transaction Process,**OLTP**),是数据库系统的主要应用。例如索引、日志、备份等技术】 * 分析型处理【对数据进行`统计分析`,得出有用的信息作为决策的依据和基础。就是有目的的进行查询等操作】 数据库系统的局限性: 1. `数据分散`【只处理本部门业务的数据,不是集成的】 2. `“蜘蛛网”`问题【对数据进行抽取式的集成,是数据访问相当复杂】 3. `数据不一致`【蜘蛛网问题导致了多个应用间的数据不一致。可以理解为每个抽取步骤的时间、内容不同】 4. `数据动态集成问题`【每次分析都需要集成,效率低】 5. 历史数据问题 6. 数据综合问题 (5、6两点不重要,且这部分比较繁琐) **数据仓库的本质:** 单就其是数据的存储容器这一点而言,数据仓库与数据库并没有本质的区别。而且在更多的时候,是将数据仓库作为一个数据库应用系统来看待的。数据仓库是为了构建新的分析型处理环境而出现的一种数据存储和组织技术。👇 ![chrome\_YpczEZjyRA](https://cdn.bangwu.top/img/202312241504448.webp) ## 1.2数据仓库的基本概念 定义:数据仓库是`面向主题的`、`集成的`、`不可更新的`、`随时间不断变化的`数据集合。**【必考】** 主题与`面向主题`: * 主题是抽象概念,是在较高层次上将企业信息系统中的数据综合、归类并进行分析利用的抽象。 * 面向主题是相对于传统数据库的面向应用而言的。【面向主题就是围绕来进行的,例如建立“商品销售”主题,要抽取相关数据】 【例如,商品的推荐系统就是基于数据仓库设计的,商品的信息就是数据仓库所面向的主题。】 剩下的三个特征中,`集成的`是字面意思,从不同数据源来抽取、清洗 `不可更新的`:相对说法,是指不对原始的数据进行操作【操作仅限于初始导入和记录查询,不进行删除和修改】 `随时间不断变化的`:数据会不断从来源处更新,重新综合。 PS: 数据库 + **有目的的SELECT** = 数据仓库 ## 1.3数据仓库的体系结构 数据仓库的结构包含了4部分,分别是`数据源`、`数据存储及管理`、`服务器`和`前端工具`。 ![chrome\_2PzvDt7FUX](https://cdn.bangwu.top/img/202312241540515.webp) > ETL和ELT:从上图可以看出两者的区别和适用情况。【一个是先T(转换),一个是后T】 元数据:是数据仓库中所有描述性信息,分为商业元数据和技术元数据。 数据仓库和数据集市的比较:【数据集市数据粒度大】 | 对比项 | 数据仓库 | 数据集市 | | - | - | - | | 范围 | 企业级 | 部门级 | | 主题 | `企业主题` | `部门或特殊的分析主题` | | 数据粒度 | 最小的粒度 | 较大的粒度 | | 数据结构 | 规范化结构 | 星型模式、雪花型模式、或两者结合 | | 历史数据 | 大量的历史数据 | 适度的历史数据 | | 优化 | 处理海量数据、数据检索 | 便于访问和分析、快速分析 | # 二、操作数据存储
引言👈 DB~~DW结构解决了企业操作型数据和分析型数据 的处理问题。然而,这种两层结构并不能有效的处 理企业中所有的数据处理要求,为了解决多层次的 数据处理需求,在DB~~DW两层体系中增加一个新 的层次ODS,形成DB~~ODS~~DW的三层体系结构。 ODS作为中间层,适合于辅助企业完成日常决策 的数据分析处理。
## 2.1ODS 操作性数据(Operational Data Store),简称ODS:面向主题的(Subject Oriented)、集成的(Integrated)、细节的(Detailed)、可更新的 (Volatile)、当前的(Current valued)或接近当前的数据集合, 用于支持全局业务处理和日常管理控制操作。【是一种数据环境,适应某种层次的应用需求;仍属于操作型环境 (Operational Environment)】 ## 2.2DB~~ODS~~DW体系 ![chrome\_VbGNl0slqU](https://cdn.bangwu.top/img/chrome_VbGNl0slqU.webp) 【ODS是动态数据,实时更新的,但ODS中只存放当前和接近当前的细节数据,数据量较少】可以理解为DB经过实时转换后生成ODS,ODS再写入DW,充当“承上启下”的角色。 > ODS可以分为:同步ODS、即时ODS、延时ODS。【字面意思】 # 三、数据仓库中的数据
引言👈 数据仓库中的数据都是按照一定的方式存储的,例如考虑到粒度的问题,以及数据组织、追加,元数据的作用等都是数据仓库里面数据的基本概念。数据仓库的组织形式直接影响到数据的有效性和可靠性。
## 3.1数据仓库中的数据组织 > 数据仓库中存储着两类数据,业务数据和元数据。 **数据粒度**:粒度是指数据仓库的数据单位中保存数据的细化或综合程度的级别。【在数据仓库中的数据粒度与查询的详细程度之间要做 出权衡。 】 **数据分割**:数据分割是指将数据`分割到各自的物理单元`以便能够独立处理,提高数据处理效率。【垂直分割和水平分割】 数据分割后的数据单元称为分片,分片数据没有交叉。【数据分割有点确实很多,但是可能导致数据分配的不平衡】 数据分割时需要注意:分割均匀、用户的查询需求、数据的汇总方式。 > 数据粒度和数据分割设计得好,几乎所有的数据仓库设计和实现的问题都将迎刃而解。 ## 3.2数据仓库中数据的追加 > 当数据仓库的数据初装完成以后,再向数据仓库输入(导入)数据的过程称为`数据追加`。 > 如何能够确切地感知究竟哪些数据是上一次追加过程以后新生成的,这项工作称为`变化数据的捕捉`。 **数据追加过程中实现变化数据的捕捉的方法**: 1. 时标【加上更新数据时的时间】 2. DELTA文件【A + DELTA A = A‘ DELTA是用来记录所改变的数据内容】 3. 前后快照文件【字面意思。 `快照`:**数据存储的某一时刻的状态记录**】 4. 日志文件 ## 3.3数据仓库中的元数据 > `元数据`:是关于数据的数据。【元数据描述了数据的结构、来源、抽取和转换规则、存储,描述操纵数据的进程和应用程序的结构、功能等。】 元数据的**作用**:提供数据资源的全面指南。【在数据仓库中,元数据定义了数据仓库中的许多对象——表、列、查询、商业规则或是数据仓库内部的数据转移。】 > 元数据是数据仓库的重要构件,是数据仓库的指示图(roadmap)。 *ODS元数据和DW元数据均属于数据仓库元数据,是数据仓库系统的核心元数据。* ![wpspdf\_xLLu4UM8MS](https://cdn.bangwu.top/img/202312241732328.webp) PS:本章节中含有`元数据分类`部分的知识没有进行说明,认为繁琐且用处不大,不是重点部分。 # 四、OLAP的概述及模型
引言👈 关系数据库满足了联机事务处理(OLTP)的要求,但分析型应用无法适应, 数据分析技术是在一定的数据基础之上进行分析的方式和方法,通常包括联机分析处理和数据挖掘等内容。 数据分析执术不一定非要建立在数据仓库基础上,但有了数据仓库之后,数据分析的能力和效率将大大提高。
## 4.1OLAP技术概述 > 联机分析处理(OLAP)是一种软件技术,可用于从不同的角度分析业务数据。【组织收集和存储来自多个数据源的数据,例如网站、应用程序、智能电表和内部系统。OLAP 将这些数据合并分为几类,为战略规划提供切实可行的见解。】 OLAP特点:快速、可分析、多维、及时。 > **OLAP与OLTP的区别** 联机分析处理 (OLAP) 系统的主要用途是分析聚合数据,而联机事务处理 (OLTP) 系统的主要用途是处理数据库事务。 【您使用 OLAP 系统来生成报告、执行复杂的数据分析和确定趋势。相比之下,您使用 OLTP 系统来处理订单、更新库存和管理客户账户。👇】 | 特征 | OLAP(Online Analytical Processing) | OLTP(Online Transaction Processing) | | - | - | - | | 目标 | 决策和分析 | 日常交易处理 | | 数据操作方式 | 复杂查询和分析 | 快速事务性数据处理 | | 数据模型 | 多维数据模型 | 规范化的数据模型 | | 性能要求 | 高查询性能,相对低实时性 | 高事务处理速度,相对高实时性 | | 数据量 | 大量历史数据 | 大量短期交易数据 | ## 4.2多维数据模型 多维数据模型的**基本概念**: * 多维数据模型又称多维概念视图,是一个多维空间,通常用`Cube`来表示 * 多维数据模型用多维数组来表示,可以更加直观地表现现实中的复杂关系 * 多维数据模型基本组成:维、维成员、维层、度量(变量、指标) 【维成员:维的一个取值。】 > **星型模型、雪花型结构**【这两个不做太多解释,可以看[这篇文章](https://zhuanlan.zhihu.com/p/139656253)】 > **常用的多维分析操作** 1. *聚集*:多维分析的基础。【对数据进行综合,SUM,RANK,AVG,COUNT等】 2. 切片、切块、旋转、下钻、上卷【都是对Cube操作】 3. 维操作、属性操作 多维查询语言MDX(Mutiply Dimension Expression): ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SELECT {[Region].[City].&[上海],[Region].[City].&[北京]} ON Colums, [Time].[Month].[1] ON Rows From [Mkas] ``` # 五、数据立方的存储、预计算和缩减 这章好像是概念章节,没有特意强调,接下来的实操也没有涉及到相关的知识,而且PDF中欠缺本部分内容。暂定不考。 不放心的可以去看[课件](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E6%95%B0%E6%8D%AE%E4%BB%93%E5%BA%93/%E7%AC%AC%E4%BA%8C%E7%AF%87%E8%81%94%E6%9C%BA%E5%88%86%E6%9E%90%E5%A4%84%E7%90%86%E6%8A%80%E6%9C%AF.pdf) # 六、数据仓库的设计
引言👈 数据仓库是一个环境,而不是一件产品 数据仓库技术是为了有效地吧操作数据集成到统一的环境中以提供决策型数据访问的各种技术和模块的总称。 相对而言,数据仓库更加是一种思想,其基本粒子就是对数据库或者类似环境的“快照”,一个快照就是对一个时间点的截面,这样使得是数据仓库具有天然的历史属性,方便进行数据的挖掘处理。
> 数据仓库建设的目标 * 数据仓库必须使组织机构的信息变得容易存取 * 数据仓库必须一致地展示组织机构的信息 * 数据仓库必须具有广泛的适应性和便于修该 > 数据仓库设计方法概述 1. DW设计与DB设计方法比较 1. DB * SDLC(System Development Life Cycle) **应用需求驱动** 2. DW * CLDS **数据驱动+需求驱动** ![wpspdf\_6NRGwQAGCk](https://cdn.bangwu.top/img/202312242330031.webp) 2. 明确需求 3. 设计的原则【坚持“以数据驱动为中心,数据驱动和需求驱动相结合”的原则】 4. 实际工程中的设计方法【确定范围与项目定义、应用系统及其数据的调研与分析、建设方法】 5. 数据驱动系统设计方法的基本思路 6. DW设计的三级数据模型【概念模型(ER图)=>逻辑模型=>物理模型】 ![wpspdf\_5u8NSPRgp0](https://cdn.bangwu.top/img/202312251307477.webp) > 剩下的基本就是实操方向的知识了,涉及的有[`窗口函数`](https://alist.bangwu.top/%E8%93%9D%E5%A5%8F%E4%BA%91-%E6%A3%92%E6%97%A0/%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0.pdf)、[`RFM`](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E4%B8%B4%E6%97%B6%E5%A4%87%E4%BB%BD/%E5%AE%9E%E9%AA%8C3-RFM%E5%88%86%E6%9E%90.pdf)、[`SSIS`](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E4%B8%B4%E6%97%B6%E5%A4%87%E4%BB%BD/SQL%20Server%20BI%EF%BC%881%EF%BC%89-SSIS%E6%93%8D%E4%BD%9C.pdf)、[`SSAS`](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E4%B8%B4%E6%97%B6%E5%A4%87%E4%BB%BD/SQL%20Server%20BI%EF%BC%882%EF%BC%89-SSAS%E6%93%8D%E4%BD%9C.pdf)、[`MDX`](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E4%B8%B4%E6%97%B6%E5%A4%87%E4%BB%BD/SQL%20Server%20BI%EF%BC%883%EF%BC%89-MDX.pdf)。这几个部分由于涉及到实操方面且是重点,就去看课件吧。最后提供一个[SQL代码](https://alist.bangwu.top/%E6%9C%AC%E6%9C%BA/SQL%E6%96%87%E6%A1%A3.sql),用来检测语法知识。(上课时操作写的代码) # E-commerce Source: https://base.bangwu.me/about/courses/e-commerce Course notes on e-commerce covering digital payment concepts, B2C and B2B business models, SSL/SET security protocols, and network marketing strategies. 一.名词解释(20分) 1. > 电子支付 通过计算机网络系统,以电子信息传递形式实现流通和支付。 2. > 数字现金 数字现金是一种表示现金的加密序列数,具有如下属性:货币价值(预付)、可交换性(兑换)、可存储性(各种计算机存储设备)、重复性(复制和重复使用)。 3. > B TO C 在线零售,网络购物;在电子商务交易额中只占小部分份额,但与社会环境更为相关;商业模式有在线商店、比价网站或服务等 4. > B TO B 企业之间在网络上进行供应与采购的交易;是电子商务的主体,对经济的作用相当显著;商业模型主要是电子交易平台。 5. > Extranet 由多个Intranet通过连接起来的网络系统。 6. > Intranet 以Internet技术建立的企业内部专用网络。 7. > C TO B 买方驱动的消费类网站;以Priceline([http://www.priceline.com)为原型。商业模式新颖,收入主要来源于中介费、广告等。](http://www.priceline.com)为原型。商业模式新颖,收入主要来源于中介费、广告等。) 8. > C TO C 消费者—消费者的个人交易社区;商业模式主要是个人交易的平台;收入来源有广告、中介费、服务费等。 ![image-20230619213859343](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306192138391.png) 三.填空题(10分) ![img](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306192136621.gif) ![img](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306192136627.gif)![img](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306192136632.gif) 四.问答题(30分) 1. > 电子商务面临的法律和税收问题各有哪些? 适用于电子商务的法律法规 电子商务的交易标准知识产权 ``` 著作权 专利 商标 反不正当竞争 域名 ``` 个人隐私权保护 电子商务的税收问题 *税种*:国内税,国际贸易关税 `·困难` 2. > 电子商务有哪三类安全问题,其解决手段和技术方法是什么? | **电子商务的安全问题** | **解决手段** | **技术方法** | | - | - | - | | 未经授权的访问 | 过滤和保护 限制开放 | 防火墙 专用网络 | | 泄露或篡改数据 | 数据加密 | 对称加密技术 不对称加密技术 | | 冒名或抵赖发送数据 | 身份验证 | 数字签名 身份认证 | 3. > 互联网商业化发展第一阶段的主要特征有哪些?举例说明风险资本在其中所起的作用。 * 以新技术推动的资本市场运作 * 新技术 * Internet新技术公司IPO (Initial Public Offering) 上市 * 通过资本市场获得回报 * 风险资本 * 天使资本 * 种子、培育及上市为目标的各种风险资本 4. > 互联网商业化发展第二阶段的主要特征有哪些?请以Amazon.com为例说明做了哪三方面的商业创新? * 以新商业推动的商业模式运作 * 把虚拟的网络经济与现实的传统经济结合起来 * 寻求全新的商业运作模式 * 商业创新:长尾效应;跨行业横向扩张;打造商业生态 5. > 自营类B to C的业务内容、收入来源及发展问题各是什么?请以京东商城为例予以说明。 * 业务:在线零售/网上商店(不同于天猫/淘宝商城) * 收入:商业利润;其他(广告、网络服务等) * 问题:品类;服务;环境因素(支付、物流和政策等);多渠道 6. > 第三方平台类B to C的业务模式、收入来源及发展问题各是什么?请以天猫为例予以说明。 * 业务模式:分销平台、交易市场、营销服务 * 收入来源:中介费/佣金、广告费、会员费等 * 发展问题:业务创新、市场细分、差异化经营、场景结合等等 五.论述题(30分) 1. > 对企业电子商务应用的认识误区有哪些?中小型服务企业的电子商务应用策略有哪些重点? l 认识误区 * 发展一个电子商务网站是容易而便宜的。 * 建好一个电子商务网站,用户就会来访问。 * 电子商务的目的是宣传企业形象,利用网络销售产品或服务。 * 企业实现电子商务就是通过网络进行营销活动。 * 电子商务就是要做到互联网上第一,不需要合作。 l 应用策略: `商品选择问题`、`用户地域/本土问题`、`营销/服务`、`企业形象 (美观)`、`网站吸引力 (促销、活动)`、`网站的价值 (交易额、访问量)`、`商业模式`、`个性化服务`、`无意订购和配送`、`退货`。等等。 2. > 对企业电子商务应用的认识误区有哪些?中小型制造企业的电子商务应用策略有哪些重点? l 认识误区 * 发展一个电子商务网站是容易而便宜的。 * 建好一个电子商务网站,用户就会来访问。 * 电子商务的目的是宣传企业形象,利用网络销售产品或服务。 * 企业实现电子商务就是通过网络进行营销活动。 * 电子商务就是要做到互联网上第一,不需要合作。 l 应用策略: `产品适合网络销售/服务`、`降低生产/营销成本`,`提高效率`、`营销/服务`、`企业形象 (简洁)`、`采购和销售(成本、供应链)`、`网站的价值(商业机会、市场资源)`、`经营模式`、`客户服务`、`各种营销渠道的整合`。等等。 3. > 请针对以下创业公司案例,提出您对其业务、收入及问题三方面的看法。 \*\*【案例】\*\*公共交通的众包地图服务Moovit,2012年成立于以色列,已有多轮融资,宝马、诺基亚和红杉资本是主要投资者。其目标是整合一系列交通服务(包括公交车、火车和地铁线路)的官方数据以及使用者反馈的实时更新信息。联合创始人兼CEO尼尔·埃雷兹(Nir Erez)表示,公交不应仅被视作地图的又一项功能,“对于公交,你希望获得的远不止是地图。你得特别留心有关准时到达目的地的信息。当下只有静态数据是不行的。”Moovit的运作模式是:用户打开其免费的iPhone或者Android应用查看到达目的地的最佳公交路线,以及公交车到达他当前位置的预期时间。用户上了公交车,开始出发时,Moovit会记下公交车到达及出发的实际时间,并为在后面的站点等待的用户实时估计到站时间。Moovit是一款人人都可编辑路线、提高乘车体验的开放式城市公交地图服务。其数据主要有三个来源,一是政府部门,二是公共交通运营商,三是众包用户上传。通过对三个来源的数据进行融合,为用户提供实时交通信息和最佳出行路线,目前已将拼车、汽车短期租赁、共享单车等平台,全面整合其中,一站式解决用户出行选择问题。Moovit的免费应用现已在全球80多个国家和地区的2000余座城市内铺开,总用户数量为超过1亿人,共有40多个语言版本。目前,北京、上海、广州、深圳、成都、青岛等24个中国大陆城市及中国香港、澳门、台北等地区的用户均可使用Moovit的服务。至于收入实现方面,Moovit在尝试不同的模式:一是与出租车整合,已经在巴西、哥伦比亚和智利试行,二是移动终端售票,出售公交车票和充值服务,已经在波兰和以色列展开相关测试。2020年5月Moovit被英特尔公司以9亿美元收购,并入“出行即服务(MaaS)”业务。 ![img](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306192136637.jpg) 参考答案: 开放式题目。分业务、收入及问题三个方面展开;需要考虑中国的实际情况进行分析。 参考点有: * 需求方面(小额、高频、刚需的公交和地铁等公共交通); * 业务方面(地图和数据的积累,面向消费者提供出行方案;可定制;是否有行业扩展的可能性?); * 收入方面(面对商业合作伙伴、面对消费者;) * 视论述是否充分和有说服力给分。 4. > 请针对以下创业公司案例,提出您对其业务、收入及问题三方面的看法。 【案例】小码联城,全国最大的公共交通运营商,成立于2017年5月,同年12月获得蚂蚁金服2亿元天使轮投资,估值10亿元。目前,其主要产品有:①电子公交卡系统:电子公交卡,是一张安全、智能、数字化与信用认证的二维码(动态)公交卡。②精准实时公交APP:精准而实时的公交查询服务,可获得相关线路的精准信息、公交车路途的实时路况、到站信息等,并为用户精准推送、智能搜索、智能换乘、个性收藏,以及与实体公交卡绑定等功能。 小码联城乘车码覆盖全球87个城市。2020年8月,小码联城支付宝乘车码业务,服务国内用户突破1亿,小码联城MaaS一体化出行平台,高效整合公交、地铁、出租车、大巴车、网约车等全场景交通出行服务,实现无缝换乘。小码联城“本地生活”业务,则以“交通+商业”服务本地用户,其基于LBS站点信息和支付宝平台内的实名会员用户体系,依托小额、高频的刚需场景,让“好服务”找到用户。在满足“快速出行”的同时,小码联城更希望实现用户“快乐出行”,践行以互联网公共出行的线路为导向的城市商业开发模式(Internet Transit Oriented Development, ITOD),打造“出行生活圈”,即“以公共交通为主轴,以车站为核心,1公里综合性出行民生服务平台”。“小码联城不是支付公司,而是整体信息化和商业化的提供商,因此小码与巨头们从来就不是竞争关系”,小码联城负责人表示:“交易达到每天数千万笔就是一两年问题。相比起交易笔数,我们更关注的是如何加快无人驾驶、人脸识别支付及安控、人工智能等技术在公交地铁中的普及化,为‘城市、车辆、乘客’探索出更和谐的相处方式,这是小码联城真正的愿景。” ![img](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306192136652.jpg) 开放式题目。分业务、收入及问题三个方面展开;需要考虑中国的实际情况进行分析。 参考点有: * 需求方面(小额、高频、刚需的公交和地铁等公共交通); * 业务方面(面向公交地铁公司提供解决方案,面向消费者提供乘车支付服务;可定制;行业扩展的可能性,出行生活圈?); * 收入方面(面对公司、面对消费者;) * 视论述是否充分和有说服力给分。 # Game theory Source: https://base.bangwu.me/about/courses/game-theory Course notes on game theory covering Nash equilibrium, mixed strategies, the prisoner's dilemma, social cooperation, and decision goals. # 博弈论 > \[!note] > 简答题(每个要点 3 句话)、论述题(5 句话)、辨析题(与简答题相同)、计算题 ## 导论 指明决策的目的、指明决策层次 **必要**目标和**需要**目标 决策者应该是做选择题,而不是做问答题 策划也是年轻人从执行者走向决策者的必由之路 ## 个体理性与社会合作 > 社会的基本问题 **社会**是个体之间具有相互行动和相互依赖的群体 社会的两个基本问题:`协调`【如何形成一致预期】、`合作`【如何提供共赢激励】 协调问题的核心是预测,合作问题的核心是激励【个体理性、集体理性】 协作博弈:一荣俱荣,一损俱损。双方都希望得到最有利于自己的协调结果 > 个体理性行为 博弈论:分析理性人在存在相互依赖的情况下如何决策的理论工具 博弈论的基本假设:工具理性假设【所有人是工具理性的】、理性共知假设【工具理性是所有人的共同知识】、规则共知假设【博弈规则是所有人的共同知识】->“谁也不比谁傻” `约束条件`:技术性约束、制度性约束、信息约束、资源(收入/成本)约束 人们选择的不同,可能是由于偏好不同,也可能是由于面临的约束条件不同,如买车 > 社会效率标准 `帕累托效率`:一种状态(资源配置、社会制度等)被称为`帕累托最优状态`,如果不存在另一种状态能使得没有任何人的处境变坏同时至少有一个人的处境变得更好【除非“损人”就不可能“利己”】 ![bangwu20250112085533](https://cdn.bangwu.top/img/202501120855047.webp) `卡尔多-希克斯标准`:如果一种变革使得受益者的所得足以弥补受损者的所失,这种变革就是一个`卡尔多-希克斯改进`。【状态 X 下,A 的收入是 100,B 的收入也是 100;在状态 Y 下,A 的收入是 1000,B 的收入是 99】“总财富最大化” ## 纳什均衡与囚徒困境博弈 ![bangwu20250112090048](https://cdn.bangwu.top/img/202501120900987.webp) `反复剔除`不仅要求每个人是理性的,而且要求每个人知道其他人是理性的,甚至要求每个人知道每个人知道每个人是理性的,如此等等,即**理性是“共同知识”(理性共识)** ## 多重均衡与制度和文化 社会制度和社会规范,通过写台哦人们的预期而形成一个特定的纳什均衡 ## 许诺(威胁)与承诺 许诺或威胁是事前声称战略,其可信性取决于事前与事后最优选择是否一致。像考试博弈中部分学生 “报复” 威胁不可信,因无论老师判分如何,“报复” 都非最优。 \*\*承诺(威慑)\*\*是使许诺(威胁)前后最优一致的行动,通过限制自身或对方自由增强可信度,成本越高越可信,如婚姻彩礼、订金等都是常见的承诺形式。 ## 讨价还价与耐心 不是**零和博弈**而是**正和博弈** 贴现因子 ## 演化博弈与自发秩序 `ESS(演化稳定战略)`:社会(种群)中的稳定行为方式,能击败任何变异,可以持续存在、不断地复制自己。 ESS 一定是纳什均衡,但并非所有的纳什均衡都是 ESS,**单元均衡** 演化均衡不一定是帕累托最优均衡 一般地,一次性囚徒困境如果存在占优战略,该占优战略是 ESS ## 支付矩阵计算 ### 一、完全信息静态博弈 > **博弈的支付矩阵和纳什均衡** `纳什均衡`:如果别人的策略固定不动,那么我也没有动机改变。所有人都是如此 要会根据`支付矩阵`找出纳什均衡 无限策略的博弈和纳什均衡: > 古诺双头垄断模型 $$ P=a - bQ=a - b\times\frac{2(a - c_1 - c_2)}{3b}=\frac{a + 2c_1 + 2c_2}{3} $$ > 混合策略纳什均衡 当纯策略纳什均衡不存在时,找不出纳什均衡的状况。固定一个不变,求另一个,然后画图找交点 ### 二、不完全信息静态博弈 不同概率的支付矩阵,至少有一个参与者不能确定另一个参与者的收益函数 n 个支付矩阵、无限策略 ### 三、完全信息动态博弈 参与者的行动是**顺序发生的**,根据所有参与者的选择,每个参与者得到各自的结果。每一位参与者的支付函数在所有参与者之间是共同知识。 > 完全且**完美**信息的动态博弈 每一步当中,要选择行动的参与者都知道这一步之前博弈进行的过程 > 完全但**不完美**信息的动态博弈 某些阶段,要选择行动的参与者不知道这一步之前的博弈过程 > **先行动的参与者支付在前** ![bangwu20250110085416](https://cdn.bangwu.top/img/202501100854552.webp) 古诺模型要联立 > 有限重复博弈 把第二步结果代入第一步,列出矩阵 ![bangwu20250110093036](https://cdn.bangwu.top/img/202501100930420.webp) > 无限重复博弈 贴现因子,短见的=0,长远的=1 `子博弈精炼`:子博弈也是纳什均衡的 ### 四、不完全信息动态博弈 参与人自己知道,其他参与人不知道——不完全信息 行动有先后,后行动者能观测到先行动者的行动,但不能观测其类型 **混同**、**分离**均衡 # Information analysis Source: https://base.bangwu.me/about/courses/info-analysis Course notes on information analysis covering patent law, research variables, sampling, Cronbach alpha reliability, regression models, and factor analysis.
写在前面 信息分析复习由知识点和SPSS相结合,然后按照课件进行总结。本文只是自己总结,可能去看课件会更好一点 复习重点: 1. 专利法的内容 2. 研究设计中:变量,如调节变量、中介变量 3. 调研设计:抽样、量表:什么是量表,量表的信度效度用什么来做检验 4. 回归分析:相关分析,一元线性回归,多元线性回归,logistic回归 5. 因子分析 6. 聚类分析 7. 比较分析:t检验 8. 给出不同的问题和场景,设计信息分析的设计思路、数据源、分析方法、分析过程、应用等(包括评价型信息分析、预测型信息分析等) ![](https://cdn.bangwu.top/img/202312231936113.webp)
| 题型 | 数量 | 分值 | 总分 | | - | - | - | - | | 单选题 | 10 | 1 | 10 | | 多选题 | 8 | 2 | 16 | | 辨析题 | 6 | 2 | 12 | | 计算与数据分析题 | 3 | 15, 7, 6 | 28 | | 论述题 | 3 | 12,12,10 | 34 | # 一、专利法的内容 > `专利`(patent),是“专利权”的简称。指一项发明创造,即发明、使用新型或外观设计向国务院专利行政部门提出专利申请,经依法审查合格后,向专利申请人授予在规定的时间内对该项发明创造享有的专有权。 > > 专利的类型:**发明专利、实用新型专利【有的国家没有此项】、外观设计专利** 专利一词的三层含义: * 受专利法保护的发明创造——(技术角度理解) * 专利权——(法律角度理解) * 专利说明书等专利文献——(文献角度理解,查专利查的就是专利文献) > 获得专利的实质条件:**新颖性**、**创造性**、**实用性** > > 专利的`特点`:无形、专有、地域【不同国家,法律的地域性限制】、时间【有有效期】 | | 发明 | 实用新型 | | - | - | - | | 对象 | 针对产品和方法 | 只针对产品,而且必须是有固定形态和结构的产品 | | 要求 | 有突出的实质性特点和显著进步 | 实质性特点和进步 (略低) | | 时间 | 20年 | 10年 | | 程序 | 有实质审查 | 只有初步审查,不经实审即可授权 | | 费用 | 申请费950元审查费2500元,年费900-8000元/年 | 申请费500元,年费600-2000元/年 | > 国际专利分类法(International Patent Classification)简称IPC【每五年更新一次】 **专利信息产生的流程**: ![image-20240103153103716](https://cdn.bangwu.top/img/202401031531804.png) 专利信息的分析对于企业的`技术情况`、`经营环境分析`、`侵权分析`等等【因为专利中蕴含着`法律信息`、`经济/商业信息`、`技术信息`】 # 二、研究设计中:变量,如调节变量、中介变量 > `调节变量`:一个变量X1影响了另一个变量X2对Y的影响 当检验中发现一个显著的调节作用存在时,下一个重要的步骤就是**分析它的作用模式**。这时,如果调节变量和自变量都是定类变量,可以在不同的组中分别计算因变量的均值,然后用得到的值来做图,直观地表示出调节作用的模式。第二种方法是在按调节变量所分的不同组中,检验自变量对结果变量回归的斜率。 > `中介变量`:简单地说,凡是 *X* 影响 *Y*,并且 *X* 是通过一个中间的变量 *M* 对 *Y* 产生影响的,*M* 就是中介变量。 **部分中介作用**: ![](https://pic2.zhimg.com/80/v2-21407353a53006f2ca3c0c8b358b6b9d_1440w.webp) **完全中介作用**: ![](https://pic2.zhimg.com/80/v2-8ffe8cc4b3418b34014c9eed416b669d_1440w.webp) # 三、调研设计:抽样、量表 > `抽样`:是指按照一定程序从研究对象总体中抽取部分样本,收集这部分样本的资料,运用数理的原理和方法,对总体特征进行推断的一种非全面的调查。 ![POWERPNT\_kpa9tNI5ns](https://cdn.bangwu.top/img/202401041457486.webp) > 什么是量表 量表是由测量某一抽象概念的所有测量指标和备选答案构成的调查表。 量表是测量调查对象的主观特性的度量标准,是由一组问题和陈述构成,并根据受访者可能的反应方向和强度,被相应地赋予一定的分值。 > 量表的信度效度用什么来做检验 `信度`(reliability)指测量结果的一致性或稳定性。用同一测量工具对同一样本测量两次,求两组数据的相关系数,并以此作为信度的描述的指标,称为信度系数。信息系数r=1是理想状态,表示不存在随机误差。r=0是另一个极端状态,表示所有测量之无任何程度的稳定性。 **对信度的测度一般用内部一致性来测。**【内部一致性信度常用`同质性信度`来测量】 `同质性信度`:指测验内部的各题目在多大程度上考察了同一内容。同质性信度低时,即使各个测试题看起来似乎是测量同一特质,但测验实际上是异质的,即测验测量了不止一种特质。 `效度`(validity)指测量工具对调查对象属性的差异进行测量时的准确程度。即测量工具能否真实、客观、准确地反映属性的差异性。效度高不仅意味着排除随机误差的能力强,同时也意味着排除系统误差的能力强。从不同的角度看待测量的准确性,就有3种类型的效度概念。 1. `内容效度`:内容效度(content validity)指测量工具的题目是否符合测量目的与要求,即测量内容的适合性和相符性。对内容效度的判断常用逻辑分析法、专家判断法等。 2. `准则效度`:准则效度(criterion-related validity)指当可以用不同的测量工具对同—组测验对象的同—属性进行测量时,以其中一种测量工具为基淮,而拿其他测量工具与之作比较,如果所测结果与基准工具所测无差异,就称其他测量工具有效。正因为这样,准则效度又称为实证效度(pragmatic validity)。 3. `结构效度`:测量结果体现出来的某种结构与测值之间的对应程度。结构效度分析采用的主要是因子分析(验证性因子分析)。 ![POWERPNT\_Xw4AyS5Yvx](https://cdn.bangwu.top/img/202401041426632.webp) 即一个测量工具必须是信度的,才能是有效的,但一个测量工具是信度的,并不一定就是有效的。 # 四、回归分析 **回归分析是通过其他变量来预测某一变量的值。是一种预测分析方法。** 回归分析是主要**解决两个问题**: 1. 确定变量之间是否存在相关,如果相关,分析研究一个或几个变量的变动对另一个变量的影响程度,求出它们的数学表达式; 2. 用自变量的已知值去推测因变量的值或范围,且要估计这种预测达到何种精准度 > 回归分析的基本步骤 1. 确定自变量(解释变量)和因变量(被解释变量) 2. 确定回归模型:从样本数据出发确定变量之间的数学关系式 3. 建立回归方程:对回归方程的各个参数进行估计 4. 对回归方程进行各种统计检验 5. 利用回归方程进行预测 ## 相关分析 > `相关关系`的基本概念:立足于实证研究,世间万物之间的关系可以分为三种类型(变量划分)【因果关系、虚无关系、相关关系】 > `相关分析`( correlation)是指变量之间的不确定的依存关系。它和函数关系不同。 > α表示原假设为真时,拒绝原假设的概率 > > 1-α 为置信度或置信水平,其表明了区间估计的可靠性 为了衡量双变量之间相关关系的强弱程度,所采用的一个基本的指标是简单相关系数r ,也称为`皮尔森相关系数` 相关系数 `|r| <= 1`,r 为负数就是负相关,正数就是正相关,为 0 时不相关 | \| r \| 的数值 | \*\*<\*\*0.3 | **0.3**~0.5 | \*\*>\*\*0.8 | **0.5**~0.8 | | - | - | - | - | - | | 相关强度 | 无相关 | 低度相关 | 高度相关 | 显著相关 | > `偏相关系数`:即在两个以上的多变量的线性相关分析中,当其他变量固定不变时,给定的任何两个变量之间的相关系数 例子:研究身高、体重、肺活量三者的相关关系时,肺活量与体重,肺活量与n回归分析是主要解决两个问题: –确定变量之间是否存在相关,如果相关,分析研究一个或几个变量的变动对另一个变量的影响程度,求出它们的数学表达式; –用自变量的已知值去推测因变量的值或范围,且要估计这种预测达到何种精准度身高都存在一定的正相关关系。如果将体重固定下来,对相同体重的人分析肺活量与身高的关系,是否仍然相关?反映的才是真是的相关关系。 **但是相关系数的数值并不能证明所讨论的现象之间是否存在因果关系。** **若求的r等于或接近于0,只表明现象之间不存在线性相关,而不能反映现象之间是否存在非线性相关。** > 1. 连续数据,正态分布,线性关系,用pearson相关系数是最恰当。 > 2. 上述任一条件不满足,就用spearman相关系数。 > 3. 两个定序测量数据之间也用spearman相关系数,不能用pearson相关系数。 ## 一元线性回归 > 最小二乘法 ![POWERPNT\_MaAoxm4mcX](https://cdn.bangwu.top/img/202401031657507.webp) **显著性检验**: 判定系数R的平方【R方在0.8以上,即可认为拟合程度较高】 `t检验` `F检验` > 一元回归中,F检验与t检验一致,即: F=t方,两种检验可以相互替代 > > 但在多元回归分析中,它们是不等价的。T检验只是检验回归方程中各个系数的显著性,而F检验则是检验整个回归关系的显著性。 ## 多元线性回归 线性回归模型的检验项目 1. 拟合程度判定(调整后的R2) 2. 回归方程的检验(F检验)【检验所有自变量与因变量之间的线性关系是否显著,是否可用线性模型来表示】 3. 回归系数的检验(t检验)【检验每个自变量对因变量的线性影响是否显著,对F检验的一个补充】 4. D.W检验(残差项是否自相关) 5. 共线性检验(多元线性回归)【自变量的容忍度(Tolerance)和方差膨胀因子(VIF)】 > 据经验 `T < 0.1` 一般认为具有多重共线性,当 `VIF >= 10` 时,就说明自变量 X 与其余自变量之间有严重的多重共线性【多重共线性的对策:增大样本量或减少自变量】 自变量筛选方法:`前进`、`后退`、`步进` ## logistic回归 线性回归的结果变量是连续的,逻辑回归是**离散的** 线性回归完成方式是建立线性的拟合线,逻辑回归方式是建立**决策线**【比如是否会购买某种商品,即因变量是**固定的**】 逻辑回归解决因变量不连续的问题。将离散变量转化为连续变量【因变量取值为1时的概率,概率的取值范围为0-1,连续变量】 ![逻辑回归简介](https://cdn.bangwu.top/img/202401041514348.webp) 二项逻辑回归方程的拟合优度检验:`Hosmer—Lemeshow检验` Hosmer—Lemeshow检验的原假设:**观测频数的分布与期望频数分布无显著差异**。 Hosmer—Lemeshow统计量的值越小,p>a,拟合效果越好;反之,则拟合效果不好。【如果没有通过HL检验,需要考虑对变量进行降维或者增加样本量】 # 五、因子分析 **前言**【理解】:在实际问题的分析过程中,人们往往希望尽可能多的搜集关于分析对象的数据信息,进而能够比较全面的、完整的把握和认识它。于是,对研究对象的描述就会有很多指标。但是效果如何呢?如果搜集的变量过多,虽然能够比较全面精确的描述事物,但在实际建模时这些变量会给统计分析带来计算量大和信息重叠的问题。而消减变量个数必然会导致信息丢失和信息不完整等问题的产生。 > `因子分析`是解决上述问题的一种非常有效的方法。它以最少的信息丢失,将原始众多变量综合成较少的几个综合指标(因子),能够起到**有效降维**的目的。 > > 因子分析是一种**降维**和**评价**(排序)的方法。 所以顺理成章地因子分析应具有以下特点: * 因子分析要求样本的个数要足够多【样本个数至少是变量数的5倍以上】 * 因子个数远远少于原有变量的个数 * 因子能够反应原有变量的绝大部分信息 * 用于因子分析的变量必须是相关的 * 因子具有命名解释性 ![POWERPNT\_GLvXeP3klb](https://cdn.bangwu.top/img/202401041647392.webp) 因子分析的结果分析: **一般而言,KMO值大于0.5,巴特利球体检验sig小于0.05,表明可以进行因子分析。** # 六、聚类分析 > 聚类分析是统计学中研究“物以类聚”的一种方法,属多元统计分析方法,所以,聚类分析前要检查各变量的量纲是否一致,不一致则需进行转换,如将各变量均作标准化转换就可保证量纲一致 聚类分析是一种探索性的分析,在分类的过程中,人们不必事先给出一个分类的标准, 聚类分析能够从样本数据出发,自动进行分类。聚类分析所使用方法的不同,常常会得到不同的结论。不同研究者对于同一组数据进行聚类分析,所得到的聚类数未必一致。 因此我们说聚类分析是一种探索性的分析方法。 **聚类分析有两种**:`K-Mean聚类分析`【快速聚类样本】,`层次聚类分析`【它有两种类型,一是对**研究对象的本身**进行分类,称为Q型聚类;另一是对**研究对象的观察指标**进行分类,称为R型聚类。同时根据聚类过程不同,又分为分解法和凝聚法。】 `两步聚类算法`是在SPSS中使用的一种聚类算法,是BIRCH层次聚类算法的改进版本【两个阶段:预聚类阶段,聚类阶段】 # 七、比较分析:t检验 | 特征 | 独立t检验 | 配对t检验 | | - | - | - | | 用途 | 比较两组独立样本的平均值是否有显著差异 | 比较两组相关联样本的平均值是否有显著差异 | | 样本类型 | 两组被比较的样本是独立的 | 两组被比较的样本是相关联的 | | 示例场景 | 比如两个不同班级的学生在某个考试中的平均分是否存在显著差异 | 比如同一组学生在两个不同时间点的考试成绩是否存在显著差异,或者同一组被试接受了两种不同的治疗方式,效果是否有显著差异 | **主要还是看t检验对应的sig值,如果大于0.05,则说明没有显著差异,小于0.05,则具有显著差异** # 八、分析思路(全)【重点,主要理解】 > 设计信息分析的设计思路、数据源、分析方法、分析过程【不用详细】、应用 这部分开始之前,需要先了解信息分析的工作目标:【认识、了解】 * 从混沌的信息中萃取出有用的信息 * 从表面信息中发现相关的隐蔽信息 * 从过去和现在的信息中推演出未来的信息 * 从部分信息中推知总体的信息 * 运用相关信息对事物的状态、效能、效果进行评价 ## 8.1设计思路 这里我能想到的就是 1. 明确分析目的和目标:确定信息分析要回答的问题或实现的目标,以便收集和分析相关数据来支持决策。 2. 确定分析对象和范围:确定信息分析的对象和范围,以便收集和分析相关数据来支持决策。 ## 8.2数据源 [数据源🔽](#data) ## 8.3分析方法【建立分析模型】 信息分析是`定性分析`和`定量分析`相结合的分析。纯定性分析一般不明确地认定分析模式,而定量分析的分析结果是否有效,很大程度上取决于数据与能够处理这种数据的模型之间的配合。 在计算机技术十分发达的今天,通过搜集到的数据和已有模型的运算,得出信息分析所需的结论,并不是一件十分难的事情。而找到一个合适的分析模型,并将数据很好地代入其中,则是分析技术中的难点。 1. `定量分析方法`:使用数字和统计方法来分析数据,如回归分析、方差分析、时间序列分析等。 2. `定性分析方法`:使用非数字的方法来分析数据,如文本分析、内容分析、案例分析等。 > 例如专利分析中:**定量分析**词频、申请量、分类号、国别、申请人等,**定性分析**专利内容、质量等 然后按照上面的设计思路来进行回归分析,比较分析等建立分析模型 ## 8.4分析过程 1. 数据收集:从数据源收集相关的数据。 2. 数据清洗:对收集到的数据进行清洗,包括去除重复数据、错误数据和无效数据。 3. 数据分析:使用分析方法对数据进行分析,以提取有价值的信息。【搭配描述 `拟合优度`/`显著性` 检验确立下一步分析方法】 4. 构建预测模型:使用分析结果构建预测模型,以对未来的事件或趋势进行预测。【可选】 5. 模型评估:对预测模型进行评估,以确定模型的准确性和可靠性。 ## 8.5应用 1. 销售预测:通过分析历史销售数据、市场数据、经济数据等,来预测未来的销售额。 2. 财务预测:通过分析财务数据、经济数据等,来预测公司的财务状况和盈利能力。 3. 市场预测:通过分析市场需求、市场竞争、市场趋势等,来预测市场的未来发展。 4. 技术预测:技术发展趋势分析 、技术分布分析 、核心专利分析 # 九、补充 补充的主要是对上述重点没有特别提要的,但是会考到的知识的补充 ![POWERPNT\_3mABaC7Gd6](https://cdn.bangwu.top/img/202312291844960.webp) ## 信息分析的一些概论 > 信息分析和数据分析、情报分析的区别 数据(Data) ————> 数据分析 信息(Information) ————> 信息分析 信息+分析=情报 情报(Intelligence) ↔ 情报分析(双向影响) > 情报(Intelligence)是信息的一种特殊类型,它是“关于对手的信息”。 > > `信息分析`是指以社会用户的特定需求为依托,以定性或定量的研究方法为手段,通过对文献信息的**收集、整理、鉴别、评价、分析、综合**等系列化加工过程,形成新的、增值的信息产品,最终为不同层次的科学决策服务的一项具有科研性质的智能活动。 > `商业分析`通过数据分析趋势、构建预测模型、优化企业流程,提升企业绩效,以促进商业目的的实现。 商业分析有以下三种类型: 1. 描述性分析:描述分析以前发生了什么? 2. 预测性分析:预测未来会发生什么? 3. 规范性分析:描述将产生最佳结果的最佳方法。 > 根据信息分析的功能来划分可以分为: > > `跟踪型`、`比较型`、`预测型`、`评价型`、`对策型`、`综合型`信息分析 > > 信息分析活动又可以分为:**描述性分析**【使原有信息清晰】、**推断性分析**【发现新的知识】。 ## 数据源的获取 > 信息是分析的原材料,在没有搜集到足够的信息之前,任何分析都无从开始。信息搜集需要了解信息源,掌握信息搜集方法。文献阅读、信息检索、网络搜寻、问卷调查、访谈、实地考查、购买情报、人际网络等,都是信息搜集的常用方法。【找到需要的信息】 # Information management Source: https://base.bangwu.me/about/courses/info-management Course notes on information management covering information definitions, information society features, system classification, and resource planning.
写在前面 信息管理概论由课程资料+书本总结,按照顺序来划分,毕竟老师没有给出重点😅(抽象) 当然此文仅作为整理,时间充足还是推荐看书本,然后本文可以当作一次知识梳理 ![](https://cdn.bangwu.top/img/202312231932162.webp)
# 一、信息与信息管理 ## 1.1关于信息 > 对于信息的认识在不同领域中有着不同的看法 * 信息对利用者的共享性【可在同一时间或不同时间被众多用户利用】 ## 1.2信息化与信息社会 > `信息化`:信息化是向信息产业高度发达且在产业结构占优势地位的社会(即信息社会)前进的动态过程 信息化概念的内涵包括四个要素:`信息资源`【信息作为资源且较多广】、`信息技术`【技术发展、普及程度高】、`信息观念`、`资源共享`。 > `信息社会`的主要特征: 1. 信息、知识和智能是社会发展的决定力量 2. 信息劳动者、知识阶层将发挥更大的作用 3. 信息技术从根本上改变人们的生活方式、行为方式和价值观念 ## 1.3信息管理概述 > `信息管理`的实质就是人类综合采用技术的、经济的、政策的、法律的、人文的方法和手段对信息流进行控制,以提高信息利用效率、最大限度地实现信息效用价值为目的的一种活动。 > `信息生命周期`是信息运动的自然规律。 六个阶段:创建=>采集=>组织=>存储=>利用=>清理 > 信息管理发展的四个阶段:`传统管理阶段`、`技术管理阶段`、`资源管理阶段`、`知识管理阶段` # 二、信息交流 ## 2.1信息交流的基本概念 > 信息交流是不同时间或不同空间上的认知主体(人或由人组成的机构、组织)之间借助于相应的符号系统所进行的知识、消息、数据和事实等信息的传递与交流的过程。 ![chrome\_KEkEyE9MK1](https://cdn.bangwu.top/img/202312311538870.webp) > 信息交流的**条件和要素**: * 信息发送者、信息接收者、交流通道、符号体系、知识信息库、支持条件【自然、技术、社会条件】 这里省略了2.2信息交流的模式(书本P49),感觉没用 ## 2.3信息交流中的栈 > S(source)`信息源`与R(recipient)`信息接受方`之间信息流的传送节点称为`信息栈`【可分为时间栈、空间栈】 **信息栈的职能**:【理解】 从S或前栈获取信息,并加以处理、转换、存贮、积累和选择;对R或后栈传递信息。信息栈虽然经常被R当成直接信息源,但实质上它仅仅是信息交流中的一个节点,其真正的信息来源是分散于各个时代、各个地区的信息生产者S,他们是社会信息的初始来源。信息中心、图书馆、数据中心等的职能只是信息传递的社会机制。 # 三、信息分布 本章主要是讲了一堆效应、定律😅 ## 3.1信息产生与分布中的马太效应 > `马太效应`(Matthew Effect),是指好的愈好,坏的愈坏,多的愈多,少的愈少的一种现象。【参考贫富差距】 优点:突出重点、摒弃平均,降低信息管理成本等。 缺点:不思进取、难以创新,信息越来越单一。。。。。。 ## 3.2信息内容的离散分布规律 > `布拉德福定律`:如果将科技期刊按其刊载 某学科专业论文的数量多少,以递减顺序排列,可以把期刊分 为专门面对这个学科的核心区、相关区和非相关区。 各个区 的文章数量相等,此时核心区、相关区、非相关区期刊数量成 1:n:n² 的关系。 > `齐夫定律`:在自然语言的语料库里,一个单词出现的频率与它在频率表里的排名成反比。【乘积为C】 ## 3.3信息生产者分布规律 > `洛特卡定律`:写有 X 篇论文的作者数与 X 的平方呈反比。 > > `普赖斯定律`:在某一特定领域中,全部论文的半数系由该领域中全部作者数量的平方根的那些人撰写的。 洛特卡定律、普赖斯定律表明,在科学家构成的科学共同体中,大多数科学家的科研产出率比较低,只有少数科学家产量较高 ## 3.4信息对时间的分布规律 > 所谓`文献的半衰期`,是指某学科领域现时尚在利用的全部文献中的一半是在多长一段时间内发表的 > `普赖斯指数`:某一学科领域内,对发表年限不超过5年的文献的引用次数与总的引用次数之比值 文献老化的研究可以作为图书馆文献剔旧和建立储藏书库的依据 # 四、信息获取 > 人们在科研活动、生产经营活动、文化活动和其他一切活动中所产生的成果和各种原始记录,以及对这些成果和原始记录加工整理所得的成品(如数据库、文摘索引杂志等等)都是借以获得信息的源泉,简称`信息源`。 信息源的基本属性:**客观性、可传递性、可激活性**。 > `零次信息`是人们通过直接交流获得的信息,是信息客体的内容直接作用于人的感觉的结果。 `零次信息`的特征:直接性、及时性、新颖性、随机性、非存贮性 > 信息质量评价的一般维度与指标 1. 信息内容【正确性、完整性、相关性、新颖性】 2. 信息表达形式【准确性、可理解性、精简性、标准化程度】 3. 信息资源系统【可获取性、快速响应性、可靠性】 4. 信息资源效用【可用性、适量性、价值增值性】 > `信息获取的效率指标`:采全率、采准率、及时率、费用率、劳动耗费率 ![chrome\_o8ZeqUQYnK](https://cdn.bangwu.top/img/202312312225047.webp) > 信息搜集的方法与途径:采购、调查、交换、索取、检索、网络爬虫 # 五、信息组织 ## 5.1信息组织的基本原理 > `信息组织`:也叫信息整序,是利用一定的规则、方法和技术对信息的外部特征和内容特征进行揭示和描述,并按给定的参数和序列公式排列,使信息从无序集合转换为有序集合的过程。 信息组织的目的:现代社会,信息的高度分散性和无序性与人们利用信息的高选择性和针对性形成了尖锐矛盾,信息组织通过人工和机器的干预,使信息有序增值,进而提供有效利用。 信息组织的基本内容(一般过程):信息选择、信息分析、信息描述与揭示、信息存储 > 信息组织的类型 * 按信息的表现形式【文字、图像、声音、视频】 * 按信息的加工程度【一次、二次、三次信息】 * 按信息的传播载体【文献信息源、网络信息源】 信息组织的原则:客观性、系统性、目的性、现代化。 ## 5.2信息组织的思想方法 > 信息组织的思想方法 `分类法`:【特征】 * 是按照信息内容特征的相互关系进行组织的 * 是从一定角度出发组织和揭示信息资源 * 采用一定的标记符号作为排序工具 `主题法`: * 以特定事物、问题、对象,即主题为中心集中信息资源 * 直接以语词作为信息的组织和检索标识 * 以字顺作为主要检索途径 主题法可分为:标题法、单元词法、叙词法、关键词法 > 分类-主题一体化 * 分类法系统性强,满足族性检索,符合人们的思维与检索习惯,分类目录浏览。 * 主题法直观,满足特性检索,提供了一种直接面向对象、事实或概念的信息组织方法。 ## 5.3信息的描述与揭示 *为了确保信息组织的质量,提高信息检索的效率,我们要对信息进行描述和揭示,正确判断、表达信息的特征和内容,既不遗漏有价值的信息内容,又不将无价值的内容或信息对象中根本不存在的东西作为分析结果。一般来说,信息组织的深度和质量取决于对信息揭示的深度和水平,为此,人们创造了多种技术、方法、规则和标准对信息进行描述和揭示。*【**理解**】 > `信息标引`:是指分析信息对象的内容属性(特征)及相关外表属性,并用特定语言表达分析出的属性或特征,作为信息存储和检索依据的处理过程。它是在对文献信息对象分析基础上发展起来的,故又称为文献标引。 信息标引过程一般包括两个环节:一是主题分析,二是转换标识。 > `标引语言`是表达文献主题概念和检索需求主题概念的简明性、单义性和关联性的概念标识系统,是根据标引和检索需要而编制的一种专用语言或标识系统。 > `元数据`(Metadata):元数据是组织数据、各种数据域以及它们之间的相互关系的信息。 # 六、信息检索 ## 6.1信息检索的基本概念与原理 * 信息组织是指按照一定的规则来描述信息资源或信息对象,以便于能被需要它们的人高效地利用 * 信息检索是根据特定的需求,运用某种检索工具,按照一定的方法,从大量文献中查出所需的资料或信息的过程。 * 信息组织和信息检索是一对互逆过程 ![chrome\_Q0Xymo7JY7](https://cdn.bangwu.top/img/202312312301424.webp) ![chrome\_8vBMGdBjQ8](https://cdn.bangwu.top/img/202312312302430.webp) 信息检索的**类型**: 1. 按存贮和检索的内容划分:文本检索【文献】、数值检索【数据】、音频与视频检索【事实】 2. 按检索系统中信息的组织方式划分:全文检索、多媒体检索、超媒体检索 信息检索的`特性`: * 相关性 * 不确定性 * 逻辑性 信息检索的`模型`: * 布尔逻辑检索模型【and or not】 * 向量空间检索模型【将文献和查询用向量表示,问题将转化为一个关于向量空间的计算问题】 * 概率检索模型【建立在相关性理论基础上】 * 模糊检索模型【建立在模糊集合论、模糊逻辑及可能性理论基础上,处理不确定性】 ## 6.2信息检索的发展历程 1. 手工信息检索阶段【图书馆】 2. 机械信息检索阶段 3. 计算机信息检索阶段 4. 网络信息检索阶段 ## 6.3信息检索的步骤与策略 信息检索的步骤 1. 分析研究信息检索课题 2. 选择信息检索工具 3. 确定信息检索方法【顺查法、倒查法、抽查法等】 4. 掌握获取原始信息的线索 5. 获取原始信息 > `信息检索策略`是针对检索提问、运用检索方法和技术而设计的信息检索方案,其目的是要达到一定的查全率和查准率。 ![chrome\_SrXHoIrm2k](https://cdn.bangwu.top/img/202312312320467.webp) 查全率=(检出的相关文献量/文献库内相关文献总量)×100% 查准率=(检出的相关文献量/检出文献总量)×100% ## 6.4网络信息检索 网络信息检索的特点: * 信息丰富,检索空间拓宽 * 信息资源的异构式分布 * 检索趋于简单方便,适合非专业用户 ![](https://pic.imgdb.cn/item/65918891c458853aef1268f9.jpg) # 七、信息服务 ## 7.1信息服务的内容和方式 > `信息服务`(Information Service)用不同的方式向用户提供所需信息的一项活动,它是以信息为内容的服务业务 包括两个方面的内容: 1. 对分散在不同载体上的信息进行收集、评价、选择、组织、存贮,使之有序化,成为方便利用的形式 2. 对用户及信息需求进行研究,以便向他们提供有价值的信息 信息服务**三要素**:信息源、信息活动和信息用户 信息服务的**特性**:知识密集程度高、信息用户参与度高、信息服务者与用户有较深的接触 > 信息服务的**四大原则**: * 针对性原则【满足特定用户在特定时间的特定需求,提供针对性很强的信息服务】 * 及时性原则【信息具有时效性】 * 易用性原则【可获得性和易用性是影响用户利用信息的因素,信息机构应为用户获取利用信息提供最大的便利条件】 * 成本/效益原则【以最小的花费来获得信息服务的最大收益】 信息服务的方式: 1. 信息检索和传递服务【信息搜索、查新、馆际互借与文献传递】 2. 信息报道与发布服务【文字、口头、直观传播报道服务】 3. 参考服务 4. 信息咨询服务 ## 7.2信息服务的演化与现代发展 移动化、智能化、O2O化【线上向线下渗透化】 > `网络信息服务`是指信息服务机构为满足用户的信息需求,通过计算机网络提供经过加工、整理的信息产品和服务的总称,它包括信息内容的加工处理、信息内容的提供、信息内容的存储与获取、网络增值服务、信息咨询服务等 > `信息用户`是指在科研、生产、管理、商业、贸易、军事、外交以及日常生活中需要利用信息的个人或团体,前者称为个人用户,后者称为团体用户。 # 八、信息系统 ## 8.1信息系统的基本概念 > `信息系统`(Information System)是由计算机硬件、网络和通讯设备、计算机软件、信息资源、信息用户和规章制度组成的以处理信息流为目的的人机一体化系统。 ![chrome\_YKlxYMjB2b](https://cdn.bangwu.top/img/202401011217459.webp) > `诺兰模型` ![chrome\_VqICsCHc4k](https://cdn.bangwu.top/img/202401011421447.webp) 信息系统的类型: 1. 事务处理系统【作业层】 2. 管理信息系统【管理层】 3. 决策支持系统【决策层】 > **信息系统的架构模式** 1. 主机-终端模式 2. 客户机/服务器(Client/Server, C/S)模式【客户端与服务器之间的交互】 3. 浏览器/服务器(Browser/Server, B/S)模式【数据库服务器、Web服务器、客户机之间的交互】 4. 多层架构模式 ![chrome\_pBZRKd2jk5](https://cdn.bangwu.top/img/202401011428851.webp) ## 8.2信息系统开发 > `系统开发生命周期`(Systems Development Life Cycle,SDLC)是指开发信息系统的一种结构化的按部就班的方法,描述了信息系统开发项目中,从最初的可行性研究一直到完整程序维护的各个阶段。 > > 典型的活动包括决策预算、收集业务需求、设计模型,以及编写详细的用户文档。 **计划**=>分析=>设计=>开发=>测试=>实施=>维护=>**计划** 信息系统开发方法: * 结构化生命周期法 * 原型法 * 面向对象方法 * CASE方法 * 测试驱动开发方法 👆上面这些都是在管理信息系统课上学过的 ## 8.3信息系统的管理 > `信息系统项目管理的作用` * 可以进行系统的思考,并做出切合实际的全局性安排 * 可为项目人力资源的需求提供确切的依据 * 通过合理的计划安排,对项目进行最优化控制 * 能够提供准确、一致、标准的文档数据 信息系统项目管理的主要内容:项目整体、范围、时间、费用、质量、人力资源、风险管理 > 信息系统的`质量管理` * 从系统内部看,系统的质量特性主要是内部结构性能、内部结构的可靠性以及结构的连接特性等 * 从用户的角度来看,系统的质量主要体现在系统功能可用性、正确性及适应性 > 信息系统的`运行与维护管理`【运维方面,不重要】、`评价`【对系统性能进行全面评估】 信息系统评价阶段:计划阶段(事前评价)、项目阶段(事中评价)、提升阶段(事后评价) 信息系统评价方法:主观评价法、客观评价法、信息系统效用 ## 8.4信息系统的安全 > `信息系统安全`是指确保信息系统结构安全、与信息系统相关的元素安全以及与此相关的各项安全技术、安全服务和安全管理的总和 信息安全,计算机安全,网络安全,通信安全 # 九、信息机构及其管理 ## 9.1信息机构的类型与职能 > `信息机构`是实施信息搜集、加工、分析、储存、传递等有关信息管理活动的组织形式,它普遍存在于各种产业形式中,并且在国民经济和社会发展中具有与日俱增的地位与作用。 | 类型 | 举例 | | - | - | | 公益性信息机构 | 图书馆、科技信息服务机构 | | 营利性信息机构 | 搜索引擎公司、信息咨询公司、网络信息公司等 | | 组织内部的信息机构 | 政府内部信息部门、企业竞争情报部门 | 信息机构的职能:促进科技创新、服务企业、支持科学研究与发展、为政府部门提供决策支持 ## 9.2信息机构的运行与管理 > 信息机构的活动包括`作业活动`(业务工作)和`管理活动`两大部分。 信息机构的管理职能:`计划`、`组织`、`领导`、`控制` > `公益性机构`和【采用无偿或低价服务(政府部门、图书馆、信息服务中心)】`盈利性机构`【满足市场需要】 # 十、信息政策与信息法律 • 信息政策的含义及体系构建 • 信息法律制度及规范主要涉及领域 • 信息法律立法模式 • 网络环境下信息政策与法律产生的背景,所要解决的主要问题 ## 10.1信息政策 信息政策的制定与国家层面相关 > `国家信息政策`是指在一国范围内,国家或政府为解决信息管理和信息经济发展中出现的、关系和涉及到公共利益、权益、安全问题,保障信息活动协调发展而采取的有关信息产品及资源生产、流通、利用、分配以及促进和推动相关信息技术发展的一系列措施、规划、原则或指南。 国家信息政策体系的构建:政策主体、目标、问题、内容、形式 ## 10.2信息法律 > `信息法律`是指在调整信息活动中产生的社会关系的法律规范的总称。这里的社会关系主要涉及利益、权益与安全问题,这些法律规范涉及信息系统、处理信息的组织和对信息负有责任的个人等 *主要内容包括知识产权法(专利法、著作权法、商标法等)、信息安全法、信息公开法、新闻出版与传播法、电信法、电子商务法(电子签名与数字认证法等)、有关计算机犯罪的法律等等。*【理解】 ![chrome\_rE0m8XlTcW](https://cdn.bangwu.top/img/202401011528941.webp) **信息法律的立法模式**:专门立法模式【先从某些领域开始】、修改适用模式【修改已有的】、谨慎暂缓模式 > 由于互联网具有很多不同于传统信息传输工具的特点,互联网空间对于传统的信息法律规则产生了极大的冲击,传统信息法律规则不能直接适用于网络空间,从而使得对于互联网的信息法律规制变得更加紧迫。【理解】 `网络信息法律`主要解决`网络知识产权`、`电子商务`、`网络隐私`、`网络信息安全`四个方面的问题 # Information processing and organization Source: https://base.bangwu.me/about/courses/info-processing Course notes on information processing covering metadata standards, Dublin Core elements, description and indexing methods, and XML/RDF/OWL semantic encoding. # 信息处理与组织 > \[!note] > 题型:名词解释(5x4)、论述(15x2)、编码(50,`xml`20, `rdf`20, `owl`10) ## 信息组织概述 > 信息组织、信息描述、信息揭示、元数据(五类)、DC `信息组织`:信息组织是指利用一定的规则、方法和技术对信息的外部特征和**内容特征**进行**描述**和**揭示**,并按给定的参数和序列公式排列,使信息从**无序**集合转换为**有序**集合。 `语义网`:就是能根据语义进行判断的智能网络,实现人与电脑的无障碍沟通。 `信息描述(著录)`:根据一定的描述规则和技术标准,对信息的**外在特征**和部分内容特征进行分析、选择和记录的过程。 `信息揭示(标引)`:是在对信息的**内容特征**进行全面的、深层次分析与综合的基础上,根据特定的标引规则与工具,赋予信息内容特征以系统化代码或标识,以便将信息记录组织成**概念标识**系统的信息处理过程。 **`元数据`**:是描述其他数据的数据,或者说是用于提供某种资源的有关信息的结构化数据。 `元数据标准`:内容标准(RDA)、**结构标准(DC)**、显示标准(ISBD)、编码标准(MARC)、取值标准 `DC修饰词`:对元素进行限定和修饰,用来增加描述的准确性,分为元素限定词和编码体系修饰词。 `元素限定词`:元素限定词缩小了元素的含义范围,使其更具有**专指性**。 `编码体系修饰词`:有助于对所修饰术语值的理解,包括控制词表及正规的符号或解读方式。 `RDA(Resource Description and Access, 资源描述与检索)`:一个元数据内容标准,提供一套用于形成支持资源发现的数据的**规则和说明**。 ## 字符编码 > 字符编码和 URI、汉字编码字符集、GB2312 `字节序`:多字节数据在计算机内存中存储或者网络传输时各字节的存储顺序。 `字符集`:字符的合集,这些字符组成一套符号系统,可以组合起来形象的表达各种含义 `编码字符集`:字符以及对应的编码集合 `字符编码`:把字符集中的字符表示为二进制位的有序集合,以便再计算机中存储、传递和处理 美国标准信息交换标准码(ASCII),GBK,GB2312![bangwu20250105171710](https://cdn.bangwu.top/img/202501051717307.webp) `统一资源标识符(URI)`:用来标识抽象或实体资源的简洁字符串。 `国际化资源标识符(IRIs)`:基于通用字符集的字符序列 ## xml > 标记语言和命名空间 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` XML 文档声明部分指明读取时所用的字符集,确保保存、读取时采用相同的字符集 > 每个 XML 都有一个且只能有一个根元素,只有注释和处理指令可以不包含在根元素中 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` > XML 模式定义文件(Schema) ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` 以`.xsd`为扩展名,属性`xmlns:xs`以 url 为值,该 url 声明其`名称空间` 通常使用一个简短的代号来代替 URI,这个代号称为`命名空间前缀`(下面的 river) ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} xmlns:river="http://www.myserver.com/" ``` ![xml数据类型](https://cdn.bangwu.top/img/202501061511721.webp) 使用`xs:element`来定义需要使用的子元素,`xs:element`包含的属性有 1. `name`:用来定义元素名称,如:``定义了`` 2. `type`:设置元素值的类型,可以是简单的和复杂的类型 3. `maxOccurs`:设置元素可出现无数次,值为`unbounded`时,可以出现无数次 内建类型:如`xs:string`、`xs:integer`、`xs:token`等 ### restriction 自定义类型可以对内建类型进行一些派生,如对`xs:integer`进行派生,限制范围在 300\~500 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` `minInclusive`、`maxInclusive`、`minExclusive`、`maxExclusive`,对`integer`进行约束其中`Inclusive`是可以包含边界值的 `length`、`minLength`、`maxLength`,对`string`进行约束包含边界长度 `totalDigits`、`fractionDigits`对`decimal`进行约束,`totalDigits`指定最多可包含多少位数,`fractionDigits`指定最多可包含多少位小数 `enumeration`定义枚举约束,`pattern`定义正则表达式,`whiteSpace`空白处理 ### list 由单个数据类型扩展出列表类型,使用时**必须指定列表元素的类型**,有两种方式指定类型 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} 57 12 23 9 68 ``` ### complexType 前面所提到的`simpleType`只能用来定义没有嵌套的元素,如果需要用到嵌套,就需要`complexType`来定义,简单类型的元素只包含文本值,没有子元素或属性。复杂类型的元素可以包含子元素、属性,或混合内容(文本和子元素混合)。 和`simpleType`的定义一样,可以在`element`内定义,也可以单独定义引用使用。 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` `complexType`的子元素结构可以使用 `sequence`、`choice` 或 `all` 结构化 * **`sequence`**:子元素必须按定义的顺序出现。 * **`choice`**:子元素中只能选择一个。 * **`all`**:子元素可以无序出现,每个子元素最多只能出现一次。 `attribute`定义元素属性,属性可以是可选(默认)、必需或带默认值 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` `mixed`允许元素既包含文本又包含子元素 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} 这是一些这是另外一些 ``` `group`元素组和属性组用于定义和复用一组元素或属性。这种机制有助于减少冗余,提高模式的可维护性。【了解一下就行,不用这个也能写出来,和 Python 定义方法一样】 ### 命名空间 **命名空间(Namespace)** 是一种解决**命名冲突**的方法,尤其是在一个文档中使用多个来源的元素和属性时。命名空间通过为每个元素或属性分配一个唯一的标识符(URI)来区分相同名称的元素或属性,确保它们具有独特性。 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} Content HTML Table Cell ``` 在 xsd 中使用`targetNamespace`来绑定命名空间 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} XML Guide John Doe ``` * `targetNamespace="http://example.com/book"` 将该模式绑定到命名空间,可以避免命名冲突 * `elementFormDefault="qualified"` 要求所有元素都声明命名空间 ## rdf > 基本思想 通过在 XML 中引用 RDF,可以将 XML 的**解析过程与解释过程相结合**。也就是说,RDF 可以帮助解析器在阅读 XML 的同时,获得 XML 所要表达的主题和对象,并可以根据它们的关系进行推理,从而做出基于语义的判断 `RDF基本思想`:被描述的事物具有一些`属性(properties)`,这些属性各有其`值(values)`;对资源的描述可以通过对它作出指定了上述属性及值的**陈述**(statement)来进行。 ### 核心概念 `资源`:资源是任何可以唯一标识的对象或概念,通常使用 URI 来唯一标识 * 一个网页:`http://example.com/about` * 一个实体:`http://example.com/person/JohnDoe` `三元组`:SPO,主谓宾 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} John is the author of Book1 . ``` `图模型`:主语和宾语是节点,谓语是连接这些节点的有向边 RDF 基本格式 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` 描述一本书 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} RDF Guide John Doe 2023 ``` 嵌套描述作者 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} RDF Guide John Doe Writer ``` 使用空节点,有时资源没有 URI,例如描述一本书,作者的信息没有 URI,仅描述为名字和职业 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} RDF Guide John Doe Writer ``` ### RDF/XML 进阶 `rdf:type`可以用来定义某个资源属于某个类 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` `xml:base`基准 URI 应用于值为`IRIs`的所有`RDF/XML`属性,例如`rdf:about`、`rdf:resource`、`rdf:ID`、`rdf:datatype`等,假设我们描述一个人 `John` 和一本书 `RDF Guide`,URI 分别为 `http://example.com/person/John` 和 `http://example.com/#RDFGuide` ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} John 被解析为http://example.com/#RDFGuide RDF Guide ``` **`rdf:Bag`**、**`rdf:Seq`** 和 **`rdf:Alt`** 是三种用于表示集合(容器)的类型 | 容器类型 | 顺序 | 重复 | 应用场景 | | - | - | - | - | | `rdf:Bag` | 无序 | 允许 | 表示无序集合(如作者列表) | | `rdf:Seq` | 有序 | 允许 | 表示有序集合(如章节、步骤) | | `rdf:Alt` | 可选 | 允许 | 表示可选集合(如多语言版本) | ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} John Doe Jane Smith John Doe ``` `]>` 是一个声明部分,在文档中,可以用 `&xsd;` 引用这个实体,代替完整的命名空间 URI ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ]> 25 5.9 ``` ### RDF Schema | 元素 | 描述 | | - | - | | `rdfs:Class` | 定义一个类,类似于对象建模中的类或类别。 | | `rdf:Property` | 定义一个属性,用于描述资源之间的关系。 | | `rdfs:subClassOf` | 表示一个类是另一个类的子类,支持类的继承。 | | `rdfs:domain` | 指定属性的**域**(定义属性适用的资源类型)。 | | `rdfs:range` | 指定属性的**范围**(定义属性值的类型)。 | | `rdfs:label` | 为资源提供一个人类可读的标签。 | | `rdfs:comment` | 提供对资源或属性的注释。 | 这部分没啥说的,要会用 RDF 来描述实例 ## owl > 本体 `本体`:是形式化的术语词汇表,通常覆盖一个特定领域并为某个用户社区所共享。它们通过描述本体中术语间的关系来给术语下定义。 * **类的声明**:使用``声明类。 * **类层次结构**:通过``定义类之间的父子关系,此关系具有传递性和自反性。 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` * **等价类**:若两个类包含完全相同个体,则使用``声明它们等价。 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` * **类不相交**:使用``和``声明类之间不相容,即不相交。 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` 后面高级类关系不考,同样也要会描述 ## 知识图谱 > 概念和如何构建知识图谱 `知识图谱(Knowledge Graph)`本质上是语义网络,是一种基于图的数据结构,由`节点(Point)`和`边(Edge)`组成。在知识图谱里,每个节点表示现实世界中存在的“实体”,每条边为实体与实体之间的“关系”。通俗地讲,知识图谱就是把所有不同种类的信息连接在一起而得到的一个关系网络。 ### 主要的构建和应用技术 `实体识别`:从文本中发现命名实体,最典型的是人名、地名、机构名三类实体 `关系抽取`:抽取出实体与实体之间的关系 知识表示与存储,往往将知识图谱作为复杂的网络进行存储,网络的每个节点带有实体标签,每条边带有关系标签。 知识图谱的主要应用有:实体链接、查询理解、自动问答、文档表示 ## 练习 手写出以下要求的代码,给出一些必要代码 ```xml theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### **XML 相关题目** 1. **XML 基础知识** * 设计一个 XML 文档,描述一本书的基本信息(如书名、作者、出版日期、ISBN)。 * 创建一个 XML 文档,表示一个学校的课程信息,包括课程名称、教师、学分、学生列表。 2. **XML Schema (XSD)** * 编写一个 XML Schema (XSD) 文件,验证学生成绩单的结构。每个成绩单包含学生姓名、学号、课程和成绩。 * 创建一个 XSD 文件来验证一个产品目录,其中包括产品名称、描述、价格、数量等字段。 ### **RDF 相关题目** 1. **RDF 基础** * 使用 RDF/XML 编写一个描述图书的 RDF 数据集。每本书应包括书名、作者、出版年份、ISBN 等信息。 * 定义一个 RDF 图谱,表示电影的基本信息(如电影名、导演、演员、发行年份),并包含一些样例数据。 2. **RDFS 和类定义** * 使用 RDFS 定义一个 RDF 本体,表示动物分类信息。包括 `Animal` 类及其子类(如 `Mammal`, `Bird`),并定义每个类的相关属性(如 `hasHabitat`, `hasLegs`)。 * 定义一个 RDF 类 `Person`,并为其添加属性 `hasAge` 和 `hasAddress`,表示一个人的年龄和地址。 3. **RDF 属性和实例化** * 使用 RDF/XML 语法定义一个资源 `John`,并为其指定类型为 `Person`,同时添加属性 `hasAge`(年龄为 30)。 * 使用 RDF/XML 创建一个实例 `Eagle`,类型为 `Bird`,并使用 `hasHabitat` 属性将其栖息地设置为“山脉”。 4. **OWL 本体与推理** * 使用 OWL 定义一个表示“公司”的本体,其中包括 `Employee` 类、`Manager` 类(`Employee` 的子类),以及相关属性 `worksFor`(员工与公司之间的关系)。 * 设计一个 OWL 本体,表示“医生”和“病人”之间的关系。医生和病人之间有一个 `treats` 属性。使用推理引擎推导出某个病人的医生。 # Information retrieval Source: https://base.bangwu.me/about/courses/info-retrieval Course notes on information retrieval covering document classification, ISBN/ISSN identification, Boolean search strategies, and precision/recall metrics. # 信息检索 消息-数据-信息-知识-智慧-文献 > **文献是记录有知识的一切载体。** ## 文献的分类 1. 按载体形式:印刷型或称纸型(纸张),缩微型,电子型,声像型 2. 出版形式(重要):图书(篇幅达到48页以上),期刊(占比最大),报纸,会议文献,政府出版物,学位论文,档案,专利文献,标准文献,产品资料。【除图书与期刊外,都是特殊文献】 3. 文献加工级别分类:零次文献(未公开的),一次文献(原始文献),二次文献(检索性文献,将一次文献组织起来),三次文献(参考性文献,类似于文献综述) 文献类型的识别,如何识别。 `ISBN`(国际标准书号),`ISSN`(国际标准连续出版物号)`CN`(国内统一刊号)。只有ISSN而无国内统一刊号在国内被视为非法出版。 ## 信息检索概念 > **概念** * 广义:信息检索包含信息存贮和信息查找两个过程。 * 狭义:信息检索仅仅指信息查找的过程。 文献标引——数据标注,查准率与查全率。 信息检索工具(参考性工具书,检索性工具书)是在一次文献基础上加工而成的二次或三次文献。OPAC(联合公共目录检索系统) * 参考性工具:辞书、类书、政书、百科全书、年鉴、手册、表谱、图录、名录等 * 检索性工具:书目、索引、文摘等 **目录的作用**:揭示、报道单位出版物的外表特征。可以找到原文馆藏。 **索引的作用**:从各个角度揭示文献的内容,为用户提供文献线索。 > **文摘的作用** 1. **具有压缩、指引一次文献的功能** 2. 便于相关文献集中阅读。掌握某一类信息的总体情况。 3. 有些情况下是原始文献的代用品 4. 避免漏检和误检 5. **消除语言障碍** Web of Science,LISTA ## 信息检索原理及语言 中国图书馆图书分类法,**主题词款目举例**。主题词与关键词最大的区别就是主题词经过了规范化处理。 ![bangwu\_20240525153128](https://cdn.bangwu.top/img/bangwu_20240525153128.webp) 主题检索语言:`关键词语言`、`标题词语言`、`单元词语言`、`叙词语言` 此处“主题”非彼处“主题”。中国期刊网的“主题”检索途径,似乎是主题语言,但却不是。新主题:包括一篇文章的所有主题特征,同时在检索过程中嵌入了专业词典、主题词表、中英文对照词典、停用词典等工具,并采用关键词截断算法,将低相关的文献进行进行截断。 DOI标识期刊,DOI是一个永久性的标识号。 ORCID:其意义同科学文献领域的DOI(数字唯一标示符)是一样的。DOI好比是科技文献的身份证,一文一证;ORCID好比是科研人员的学术身份证,一人一证。 ## 语义网络 **语义网络**是以图解的形式对知识进行表达, 知识中的概念、属性、实体以节点表示,概念与概念或实体之间存在关系则以弧 线表示,形成一幅网络结构形式的有向描述图。 本体提供领域中所有词汇对应的基本术语和关系从而描述该领域,再利用这些术语和关系结合形成规则,用以规范和定义必要词汇外延。 语义检索是把信息检索与人工智能技术、自然语言技术相结合的检索概念空间是一种包含语义关系的计算机可识别和操作的概念集合。 本体提供一组术语和概念来描述某个领域,知识库则使用这些术语来表达该领域的事实。 **中文核心期刊**【后面四个是国外四大检索工具】 ![bangwu\_20240525155212](https://cdn.bangwu.top/img/bangwu_20240525155212.webp) 检索字段解释,AND \* OR 等等,给出检索式要能解释其中的意图。参考👉:[https://zhuanlan.zhihu.com/p/690909739](https://zhuanlan.zhihu.com/p/690909739) 高校财经数据库,INFOBANK 专利分类:**发明专利、实用新型专利【有的国家没有此项】、外观设计专利**。专利特点:专有性、地域性、时间性。 IPC:国际专利分类。在专利检索上非常重要 常用标准检索数据库:中国知网,万方标准。标准有作废的问题。
简短总结 将内容分成几个主要部分进行复习:信息的定义、文献类型和特征、信息检索概念及工具、信息检索方法和技术、以及常见的数据库和评价公司信息的方法。 ### 1. 信息的定义 **申农**: 信息是能够减少不确定性的任何事物。 **维纳**: 信息是我们在适应外部世界并使这种适应作用于外部世界的过程中,与外部世界交换的内容。 **国标**: 信息是物质存在的一种方式、形式或运动状态,可以减少事件的不确定性。 ### 2. 文献的定义和分类 **文献**: 记录有知识的一切载体。 **按载体形式分类**: * 印刷型(纸型) * 微缩型 * 机读型(电子型) * 声像型(视听型) **按出版形式分类**: * 图书 * 期刊 * 报纸 * 会议文献 * 标准文献 * 专利文献 * 政府出版物 * 学位论文 * 档案 * 产品资料 **按文献加工级别分类**: * **零次文献**: 未经公开发表或交流的文献(实验记录、文章草稿、笔记等)。 * **一次文献**: 原始文献,包含研究或研制成果(期刊论文、专利说明书、会议论文等)。 * **二次文献**: 检索性文献,浓缩和组织一次文献(书目、文摘、索引等)。 * **三次文献**: 参考性文献,综合一、二次文献的研究成果(综述、专题述评、数据手册等)。 ### 3. 信息检索的概念 **广义信息检索**: 包含信息存储和信息查找两个过程。 **狭义信息检索**: 仅指信息查找的过程。 **信息检索类型**: * **强相关检索**: 强调检索的准确性。 * **弱相关检索**: 强调检索的全面性。 ### 4. 信息检索工具 **文献检索工具**: 基于特定需要,汇编知识材料,便于查找数据和文献线索。 **参考性工具书**: 辞书、百科全书、年鉴等。 **检索性工具书**: 书目、索引、文摘等。 ### 5. 信息检索方法和技术 **追溯法**: 从已有文献的参考文献入手,不断扩展检索线索。 **工具法**: 利用文摘、题录或索引等检索工具。包括顺查法、倒查法和抽查法。 **布尔逻辑检索**: 使用布尔逻辑表达式(and、or、not)进行检索。 **截词检索**: 使用截词符号(\*、?、\$)进行部分词检索。 **位置运算检索**: 表示检索词间的位置关系。 **限定检索**: 利用字段代码限制检索词的出现范围。 ### 6. 常见的数据库 **中文期刊数据库**: * 中国学术期刊全文数据库 * 维普中文期刊数据库 * 万方数字化期刊 * 龙源期刊网 **国外数据库**: * Web of Science * IEEE * EBSCO ### 7. 评价公司信息的方法 **公司公众影响力**: * **媒体报道和社交媒体分析**: 查看公司新闻报道和社交媒体讨论。 * **公司年报和公告**: 查看公司的年报和财务报表。 * **第三方评估和排名**: 参考第三方机构的评估和排名(如财富杂志的“世界500强”)。 * **公众舆情监测工具**: 使用舆情监测工具(如新浪舆情通)。 **企业征信检索**: * **国家企业信用信息公示系统** * **企查查** **商标查询**: * **国家知识产权局商标局** **专利信息**: * **国家知识产权局专利检索系统** * **智慧芽** * **innojoy**
# Knowledge management Source: https://base.bangwu.me/about/courses/knowledge-management Course notes on knowledge management covering tacit vs explicit knowledge, the SECI conversion model, knowledge sharing, and organizational learning. # 知识管理 ![NotebookLM Mind Map.png](https://cdn.bangwu.top/img/bangwu13bhvk-51202505.webp) ## **名词解释 (Definitions)** 以下是对 Word 文档中列出的核心概念的解释,结合了 PPT 中的相关信息: > **知识管理 (Knowledge Management):** * 一个旨在整合数字技术到组织战略和运营中的方法,关注于利用数字和物理世界的优势来创造卓越的客户体验并支持基础业务。 * 在 2000 年代,知识管理关注于技术解决方案,后来转向以人为本的知识管理。 * 被视为企业数字化转型的重要组成部分。 * 涉及隐性知识、默会知识和显性知识的管理,这些知识类型主要通过信息的编纂程度来区分。 * 要素包括 IT、流程、知识和人。 > **隐性知识 (Tacit Knowledge):** * 一种难以用语言文字清晰表达、难以规范化和共享的知识,通常源于个人经验、直觉和技能。 * SECI 模型中的“社会化”(Socialization)过程就是隐性知识到隐性知识的转换,例如通过共享经验。 * SECI 模型中的“外化”(Externalization)过程是将隐性知识清晰地表达为显性知识。 > **显性知识 (Explicit Knowledge):** * 可以用语言、文字、图表、公式等清晰表达和记录的知识,易于传播和共享。 * SECI 模型中的“组合”(Combination)过程是将显性知识转化为更复杂、更系统的显性知识体系。 * SECI 模型中的“内化”(Internalization)过程是将显性知识融入到隐性知识中,例如通过实践和行动。 > **SECI 模型 (SECI Model):** * 由野中郁次郎(Ikujiro Nonaka)和竹内弘高(Hirotaka Takeuchi)提出的知识创造模型,描述了隐性知识和显性知识之间相互转换的四个过程:社会化 (Socialization)、外化 (Externalization)、组合 (Combination) 和内化 (Internalization)。 * 知识创造是一个螺旋式上升的过程,个人知识通过这四个模式的循环转化为组织知识。 * “场”(Ba)是知识创造的共享情境,为 SECI 模型的不同阶段提供支持,分为创始场(Originating Ba)、对话场(Dialoguing Ba)、系统化场(Systemizing Ba)和练习场(Exercising Ba)。 > **知识转移 (Knowledge Transfer):** * 一个组织内的知识从一个实体(个人、团队或部门)流动到另一个实体的过程,目的是使接收方能够理解、吸收并应用这些知识。 * 与知识共享相比,知识转移是一个更广阔的概念。知识共享可以被视为知识转移(采用个性化策略时)的一个子集。 * 知识转移的过程可以分为初始阶段、实施阶段、调整阶段和融合阶段。 * 影响知识转移的因素众多,吸收能力(Absorptive Capacity)是一个关键因素。 * 常见的知识转移工具有工作辅助、指导、流程文档化、最佳实践识别、实践社群、行动后反思、工作见习、关键事件回顾、讲故事、文档库和结构化在职培训等。 > **开放式创新 (Open Innovation):** * 由 Henry Chesbrough 提出的一个范式,强调企业可以也应该利用内外部的想法以及内外部的市场路径来推进技术发展。 * 与用户创新、累积创新、大众创新和分布式创新等概念相关。 * 传统的封闭式创新模式中,创意和开发主要在内部进行;而开放式创新模式则在构思和开发阶段都接受来自公司外部的贡献。 * 开放式创新策略包括内向外(Inside-Out)、外向内(Outside-In)和耦合型(Coupled)三种。 * 许多大型企业如海尔(HOPE 平台)、宝洁(C+D 模式)和华为都在实践开放式创新。 * **知识管理过程 (Knowledge Management Process):** * 通常包括知识的获取与积累、组织与存储、共享与转移、以及利用与创新等主要环节。 * 知识审计(Knowledge Audit)是知识管理过程中的一个重要步骤,旨在系统地调查、检查、验证、衡量和评估组织的显性和隐性知识资源和资产,以确定其使用和利用的效率和效果。 > **知识图谱 (Knowledge Mapping / Knowledge Graph):** * **知识地图 (Knowledge Map):** 一种可视化工具,显示知识在群体或组织内的位置,以及如何找到拥有特定专业知识的人。它常被称为“知识清单”,通过相互连接的节点来组织信息,方便查找。 微软的 SPUD 项目就是一个例子。 * **知识图谱 (Knowledge Graph):** 通常建立在现有数据库之上,用于在网络规模上连接所有数据,结合结构化和非结构化信息。 谷歌利用知识图谱来增强其搜索引擎的结果。 知识图谱获取信息并将其整合到本体中,并应用推理器来推导新知识。 > **知识市场 (Knowledge Market):** * 一个促进知识供需双方进行知识交换和交易的机制或平台。 * 其核心要素包括知识提供者、知识接受者、知识经纪人以及市场均衡机制(如价格体系或奖励体系)、活动和 IT 基础设施。 * 知识市场有内部和外部之分。 * 在线知识市场是知识付费的一种重要形式,例如百度文库、知乎等。 > **数据市场 (Data Marketplace):** * 一个促进数据买卖双方进行数据交易的平台。 > **社会资本 (Social Capital):** * 指个体或团体之间的关联——社会网络、互惠性规范以及由此产生的信任,是人们在社会结构中所处的位置给他们带来的资源。 * 是人际互动的积极产物,可能包括有形或无形的成果,如帮助、有用信息、创新思想和未来机会。 * 社会资本并非个人所有,而是体现在个体之间社会网络连接的潜力中。 * 可以用来描述个人关系和网络(组织内部和外部)对组织成功的贡献。 > **国家创新体系 (National Innovation System):** * 指一个国家内参与创新过程并相互作用的各种机构、组织和政策的总和,旨在促进知识的创造、传播和应用,以提升国家整体创新能力和竞争力。 ## **论述题 (Short Essays)** 以下是对 Word 文档中列出的论述题方向的要点梳理: ### **知识管理策略类型,如何为组织制定知识管理策略 (Knowledge management strategy types, how to develop knowledge management strategy for organizations):** > **知识管理策略类型:** * 创新导向型知识管理策略 (Innovation-oriented KM strategy)。 * 流程导向型知识管理策略 (Process-oriented KM strategy)。 * 最佳实践知识管理策略 (Best practice KM strategy)。 * 项目导向型知识管理策略 (Project-oriented KM strategy)。 * 另外,Hansen 提出了编码化(Codified)和个性化(Personalized)的知识管理策略。 > **制定知识管理策略的步骤 (Developing KM Strategy):** * 可以借鉴 Zack 的知识策略制定框架或西门子 CIBIT 的知识策略过程(KSP)。 * 关键问题包括:明确背景和业务案例,评估现状(知识审计),识别利益相关者的挑战和知识需求,描绘知识管理愿景,设定核心目标,以及制定行动计划。 * 西门子 CIBIT KSP 的六个步骤:明确业务背景和挑战,识别相关的知识领域,识别重要的 KPI,评估知识领域对 KPI 的当前和未来影响,评估知识领域的熟练度、扩散度和编码化程度(PDC),制定知识管理行动计划。 ### **知识管理策略与业务策略的制定 (Knowledge management strategy and business strategy formulation):** * 知识管理策略应服务于并支持业务策略。 * 业务策略明确了企业的发展方向和目标,而知识管理策略则关注如何利用知识资源来实现这些目标,提升企业的竞争力和能力。 * Zack 的框架强调了将知识策略与公司战略定位(如成本领先或差异化)相结合的重要性。 * 业务策略的不同层面(公司层面、业务层面、职能层面)都需要相应的知识支持。 ### **开放式创新与知识管理 (Open innovation and knowledge management):** * 开放式创新强调利用外部知识和资源,这与知识管理中的知识获取、共享和利用密切相关。 * 知识管理能力在开放式创新和双元创新之间起着中介作用。 * 开放式创新的实施(如海尔的 HOPE 平台)本身就是一种知识管理实践,涉及到外部知识的引入、整合和应用。 * 知识管理为开放式创新提供了方法和工具,例如知识共享平台、专家网络等,有助于企业更有效地从外部获取和利用知识。 ### **知识管理的未来,大数据、人工智能与知识管理的关系 (The future of knowledge management (KM), and the relationship between big data, artificial intelligence and KM):** > **知识管理的未来趋势:** * 与人工智能(AI)和大数据的深度融合,例如利用 AI 进行知识发现、知识图谱构建和智能推荐。 * 更注重知识生态系统的培育和知识网络的构建。 * 知识管理工具将更加智能化和普惠化。 * 知识的生产、协作、加工和消费模式将发生改变。 > **大数据、AI 与 KM 的关系:** * 大数据为知识管理提供了海量的数据来源,通过对大数据的分析可以提取有价值的知识。 * AI 技术(如机器学习、自然语言处理)可以用于知识的自动化获取、组织、挖掘和应用,例如构建知识图谱、智能问答系统等。 * 知识管理为大数据和 AI 的应用提供了框架和方法论,确保从数据中提炼出的信息能够有效地转化为可行动的知识,并应用于决策和创新。 ### **知识管理为公司带来的益处 (Benefit of KM for companies):** * 提升创新能力和效率。 * 提高员工成长速度和业务拓展速度。 * 实现降本增效。 * 通过更好地利用现有知识,避免重复劳动和“重新发明轮子”。 * 促进知识共享和协作,打破知识孤岛。 * 提升决策质量和响应速度。 * 积累和传承组织的核心知识资产。 * 增强企业的竞争优势。 ### **数据市场 (Data market):** * 数据市场是买卖双方交易数据的平台或机制。 * 其机制设计需要考虑数据的定价、质量评估、交易安全、隐私保护等问题。 * 数据市场的参与者包括数据提供方、数据需求方以及数据中介(如数据经纪人)。 * 数据市场的成功运营需要清晰的规则、有效的激励机制和可靠的技术支撑。 ### **如何促进大学与产业之间(或跨国公司子公司之间)的知识转移 (How to promote knowledge transfer between universities and industries (or among subsidiaries of a global company)):** > **影响知识转移的关键因素:** * **知识本身的特性:** 知识的隐性程度、复杂性等。 * **知识发送方的意愿和能力:** 例如,大学研究人员是否有意愿将其研究成果商业化,是否有能力清晰地传递知识。 * **知识接收方的吸收能力 (Absorptive Capacity):** 企业识别、吸收和应用外部知识的能力至关重要。 * **转移渠道和机制:** 例如,合作研发项目、技术许可、人员流动、联合实验室、知识产权交易平台等。 * **关系和信任:** 知识转移往往依赖于良好的合作关系和相互信任。社会资本在其中扮演重要角色。 * **激励机制:** 对参与知识转移的各方给予适当的激励。 > **促进措施:** * 建立专门的知识转移办公室或技术转移中心。 * 制定清晰的知识产权政策和利益分配机制。 * 鼓励科研人员与产业界开展合作。 * 为企业提供培训,提升其吸收外部知识的能力。 * 搭建信息共享平台,促进供需对接。 * 对于跨国公司子公司,可以通过人员轮岗、建立实践社群、共享知识库等方式促进内部知识转移。 ### **从宏观角度思考知识管理能为整个社会和国家创新体系带来什么 (From macro perspective to think about what KM could bring for the whole society and national innovation system):** * **提升国家整体创新能力:** 通过有效的知识管理,促进知识在全社会范围内的创造、传播和应用,从而提升国家创新体系的效率和产出。 * **促进经济发展和产业升级:** 知识管理有助于新兴产业的培育和传统产业的转型升级,推动知识经济的发展。 * **优化资源配置:** 知识作为一种关键生产要素,其有效管理有助于优化社会资源的配置,提高资源利用效率。 * **提升公共服务水平:** 在教育、医疗、科研等公共服务领域,知识管理有助于提升服务质量和效率。 * **增强国家竞争力:** 在全球化背景下,一个国家知识管理能力的强弱直接影响其国际竞争力。 * **促进开放科学和开放创新:** 知识管理理念和工具的应用,有助于构建更加开放和协同的科研和创新环境。 ### **公司实施知识管理时可能遇到的障碍以及如何解决 (When companies implement KM, what kind of obstacles could they meet and how they solve the problems?):** > **常见的障碍:** * **文化障碍:** 缺乏信任和共享的文化,员工不愿意分享知识(知识就是力量的心态)。 * **组织结构障碍:** 部门墙、层级过多等阻碍知识流动。 * **技术障碍:** 缺乏合适的知识管理工具和平台,或者现有技术与用户需求不匹配。 * **缺乏高层支持和战略规划:** 知识管理没有被提升到战略高度,缺乏持续的投入和关注。 * **缺乏激励机制:** 没有有效的激励措施鼓励员工参与知识管理活动。 * **知识本身的特性:** 隐性知识难以显性化和转移。 * **时间和资源不足:** 员工忙于日常工作,没有足够的时间和资源参与知识管理。 * **衡量和评估困难:** 知识管理的成效难以量化评估。 > **解决方法:** * **营造信任和共享的文化:** 高层倡导,建立鼓励分享的氛围,容忍失败。 * **优化组织结构:** 打破部门壁垒,建立跨部门团队,促进横向沟通。 * **选择和实施合适的技术:** 根据组织需求选择易用、实用的知识管理系统和工具。 * **获得高层承诺和制定清晰战略:** 将知识管理与业务目标紧密结合,争取高层领导的持续支持。 * **建立有效的激励机制:** 精神激励和物质激励相结合,认可和奖励知识贡献行为。 * **促进隐性知识的转化:** 利用 SECI 模型等理论,通过学徒制、故事分享、实践社群等方式促进隐性知识的显性化和共享。 * **将知识管理融入日常工作流程:** 使知识管理成为员工工作的一部分,而不是额外的负担。 * **关注知识管理的关键绩效指标 (KPI):** 结合业务目标设定可衡量的知识管理指标。 ## **案例分析 (Case Studies)** 根据复习文档的提示,案例分析可能涉及到从知识管理的管理视角、技术视角等对组织的知识管理进行分析。 这意味着你需要能够: ### **识别案例中的知识管理问题或机会。** ### **运用课程中学到的理论和模型进行分析,** * **SECI 模型:** 分析知识在组织内部是如何创造和流动的。 * **知识市场理论:** 分析组织内部或外部是否存在知识交易的机制,其效率如何。 * **开放式创新:** 分析组织是否以及如何利用外部知识进行创新。 * **知识管理策略类型:** 判断组织采用的是哪种知识管理策略,或者应该采用哪种策略。 * **知识转移模型:** 分析知识在不同实体间的转移过程、影响因素和障碍。 * **知识审计和知识图谱:** 如何评估和可视化组织的知识资产。 ### **从管理视角提出改进建议,** * 如何优化组织文化和结构以促进知识共享? * 如何设计有效的激励机制? * 如何提升领导力在知识管理中的作用? ### **从技术视角提出解决方案,** * 可以引入哪些知识管理系统或工具? * 如何利用大数据和 AI 技术改进知识管理? * 如何构建和应用知识图谱? ### **案例分析提示:** * **灵活运用所学知识,形成自己的见解。** 知识管理领域仍在不断发展,对于很多问题并没有唯一的标准答案。 * **融会贯通,** 将不同章节的知识点联系起来进行分析。 * **注意题目分值,合理分配答题时间和篇幅。** # Macroeconomics (part 1) Source: https://base.bangwu.me/about/courses/macro-economics Course notes on macroeconomics part 1 covering GDP definitions, income and expenditure accounting, nominal vs real GDP, and CPI calculation approaches. ## 第一章 宏观经济的基本指标及其衡量 ### 国内生产总值 * 国内生产总值(GDP):一定时期内在一国(或地区)境内生产的所有最终产品与服务的市场价值总和。 * 存量和流量:存量衡量某一时间点的数量,流量衡量某一单位时间的数量。 * 市场价值概念:反应物品和服务的价值。 * 一国或地区范围内:中国企业在美国生产的产品记为 租金 + 间接税和企业转移支付 + 折旧。 * 收入法:GDP = 工资 + 利息 + 利润 + 租金 + 间接税和企业转移支付 + 折扣 * 支出法:Y(收入) = C(消费) + I(投资) + G(政府购买) + NX(净出口),对整个经济而言,收入必定等于支出。 ### 名义 GDP 与实际 GDP * 名义 GDP:按照现期价格衡量的产品与服务价值。 * 实际 GDP:用一组不变价格衡量的产品与服务价值。 * 实际 GDP 不受价格因素影响,实际 GDP 只反映生产的产量的变动,反映了经济满足人们需要和欲望的能力,分析社会福利和经济增长均以实际 GDP 为准。 ### 与 GDP 相关的其他指标 * 国民生产总值(GNP)、国民净产值(NNP)、国民收入(NI)。 ## 价格水平及其衡量 ### 主要指标 * GDP 平减指数:名义 GDP/实际 GDP \_ 100,GDP 平减指数用来从名义 GDP 中剔除通货膨胀,衡量相对于基年价格的现期物价水平(实际 GDP = 名义 GDP/GDP 平减指数 \_ 100)。 * 消费价格指数(CPI):CPI = 现期价格下“篮子”产品成本/基期价格下“篮子”产品成本 \* 100。 ### 通货膨胀 * 含义:一个经济体在一定时期内价格水平持续上升的情况。 * 通货膨胀率:从一个时期到另一个时期价格水平变动的百分比。 * 真实利率 = 名义利率 – 通货膨胀率。 ### 失业及其衡量 * 失业率计算、失业的分类。 宏观经济学考点: 1.GDP 的名词概念解释(常考,要默) 2.核算 gdp 的三种方法,清楚收入法和支出法分别有什么。(选择题) 3.区分消费支出中的耐用品和非耐用品有哪些?(选择题) 4.一定要记得涉及住房就是投资,不管是家庭买住宅,还是企业或政府部门买房都是算做投资。 5. GNP、PI 等相关概念大概理解和计算公式。(计算题要做) 6.通货膨胀的三种类型(简答) 7.名义增长率和、实际增长率公式和 GDP 平减指数公式(计算) 8.通货膨胀名词概念解释(常考默写) 9.通过膨胀的经济影响(再分配效应和产出效应)简答题 10.菲利普斯曲线是反映哪两个变量的相关关系?是正相关还是负相关(选择) 11.奥肯定律的名词概念解释(默写) 12.边际消费倾向名词解释、公式、符号 13.平均消费倾向和边际消费倾向的关系(选择、判断) 14.消费函数的一般表达式(选择题有用) 15.资本边际效率,贴现率的名词概念解释(常考,默写) 16.每个乘数(投资乘数,政府支出乘数税收陈述,政府转移支付乘数、平衡预算乘数)相应的公式(选择题考计算、计算题) 17.记住 IS 曲线代表产品和服务市场,LM 曲线代表货币市场(考判断) 18. IS 曲线的推导(考计算题,把几条公式列出来就可以推导了) 19.记住 IS 曲线的斜率(做选择或判断可以快速知道曲线的变化情况) 20.货币需求有哪三大点?投资动机、预防或谨慎动机、投机动机(简答题,要默写) 21.流动性偏好是指:不管有多少货币,人们都愿意将其保持在手中的情况(判断题) 22.记住 LM 曲线的推导(计算)、斜率(方便选择做选择和判断题推导 LM 曲线的变化) 23.记住 ln 曲线的古典区域和凯恩斯区域的图像(判断财政政策和货币政策分别在 LM 曲线的古典区域和凯恩斯区域是否有效果) 24.总需求函数的名词概念解释。 25.价格变动的效应,利率效应,实际余额效应,税收效应(简答题罗列出价格变动的效应有什么?或者考名词解释,问实际余额效应是什么?) 26.总需求曲线的推导(从 LM-IS 两条公式共同推出,做计算题) 27.影响总需求 AD 变动的因素(做判断题或选择题,要会判断扩张的财政政策货币政策,或者紧缩的财政政策货币政策) 28.能够画出凯恩斯主义和古典主义的总供给 AS 曲线。(做判断或选择,判断出:在凯恩斯区域或古典区域,当财政政策或货币政策实施影响了总需求曲线后,国民收入有无变化,相应政策有无效果?) 29.能够画出价格刚性和价格弹性的总供给曲线。(方便就判断做选择和选择) 30.财政政策的名词解释 31.宏观经济政策的 4 个目标:充分就业稳定物价,经济增长,国际收支平衡(简答题) 32.自动稳定器(自动稳定的财政政策)名词解释 33.挤出效应的名词解释 34.货币政策工具有哪些?公开市场业务法定准备金率,再贴现率(简答题)(要像做名词概念解释一样解释这三个词,并且相应列出:经济萧条时,中央银行做了什么,会怎么样?经济繁荣时,中央银行做了什么会怎么样?) 35.基础货币(高能货币)有哪些?法定准备金、超额准备金、库存现金、流通中的现金。(简答) 36.货币乘数的公式。(选择题要做计算) 37.固定汇率制和浮动汇率制的名词解释,弄清他们两者的区别(做判断题) **国内生产总值** ![img](https://pic1.zhimg.com/80/v2-c174adc9de796f9991c36efebc611f54_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-c11c9603177cb06c7ea7f48fb1757a48_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-023e166bfc7fed629a7337e376dd0a70_1440w.webp) ![img](https://pic2.zhimg.com/80/v2-9b04c8bc672b48c7a0146d5178604185_1440w.webp) **价格水平及其衡量** ![img](https://pic4.zhimg.com/80/v2-0332e6f785854d13e5a9dd7f40d9c44f_1440w.webp) **通货膨胀** ![img](https://pic4.zhimg.com/80/v2-495b9a9655c9ab6d0d313e764afd926f_1440w.webp) ![img](https://pic4.zhimg.com/80/v2-3595bb08e514b33f09df6d933c7cf1bf_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-8a414b081154e286e05a8413c96e8e36_1440w.webp) ![img](https://pic2.zhimg.com/80/v2-7532a4e71072a23a0c7f39a76d832685_1440w.webp) **失业** ![img](https://pic1.zhimg.com/80/v2-faa4e1a9b2e00f39c2184b3643a50870_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-793e002de768a50879dc35e48baf7884_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-0368b6c18f0f606357e56cc85cc97e7a_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-b6fc503ae9e73707c2eb02d1606c1d50_1440w.webp) ![img](https://pic2.zhimg.com/80/v2-a8e0110f20dfa981ee2ab8159e525c29_1440w.webp) **经济周期** ![img](https://pic4.zhimg.com/80/v2-64c0567567c3f0d3055237956eea09a7_1440w.webp) **均衡国民收入的决定** ![img](https://pic1.zhimg.com/80/v2-8f7a3e07bb8d9194221c29d5af1bd298_1440w.webp) ![img](https://pic2.zhimg.com/80/v2-8c0c1cf5109a246370ab177a128c1cbd_1440w.webp) **消费需求和储蓄** ![img](https://pic3.zhimg.com/80/v2-07a7411f25ab99a2218fb6d53d3e6d6a_1440w.webp) ![img](https://pic4.zhimg.com/80/v2-2fa97200cdf0e5dce6c2ae2da7d8ff37_1440w.webp) **投资需求** ![img](https://pic4.zhimg.com/80/v2-acd993bf2bfc27485e9a1080afbbede7_1440w.webp) ![img](https://pic4.zhimg.com/80/v2-19ac1b7bde5b87aa25b5a8f8e206a083_1440w.webp) **乘数** ![img](https://pic3.zhimg.com/80/v2-ef6a6a76bae28280e08972b9e0603d2a_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-8eba2cbe6eb8e0e802c98aac65358c28_1440w.webp) **IS 曲线** ![img](https://pic1.zhimg.com/80/v2-a6c6ffe7e5d1107bbc33433ebea80b58_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-943d36e52cca979dfa6a05267467060a_1440w.webp) **LM 曲线** ![img](https://pic1.zhimg.com/80/v2-99f2e1567f7a4a349300d7bf08c74744_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-81412e751248880b0bded3c87eb619ae_1440w.webp) **IS-LM 曲线(产品市场和货币市场的均衡)** ![img](https://pic1.zhimg.com/80/v2-98050b60e112946af13728f895cdd4d0_1440w.webp) 总需求—总供给模型 ![img](https://pic2.zhimg.com/80/v2-8f11ff1200bd0466e192ccef0c863f11_1440w.webp) ![img](https://pic4.zhimg.com/80/v2-897d6728320716255da51fbe611d85ff_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-8ece898bb9c9aff67dd580f16eac25e8_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-c803e40396ed5fedf3e01880216cf4ae_1440w.webp) 财政政策和货币政策 ![img](https://pic4.zhimg.com/80/v2-4fd73f28d4aa6a777fe1baa8524addab_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-e20751b726367b2c4d923df63ba8ef2e_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-54996298b9dcedb386f6ccd75ec7a78c_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-7ce560eaef82b5115206b59800a88370_1440w.webp) ![img](https://pic1.zhimg.com/80/v2-e9a2d0c22c6600ad67c11c77eec0e308_1440w.webp) 汇率 ![img](https://pic2.zhimg.com/80/v2-156d5fddda16e84e263b3639350ad07d_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-d32d000ba0deba766fbe3d28a1e005ee_1440w.webp) ![img](https://pic2.zhimg.com/80/v2-7799285b3562f3a4eff46e704c72d271_1440w.webp) ![img](https://pic3.zhimg.com/80/v2-63f48fa10363158f226e6aae340a9f76_1440w.webp) # Macroeconomics (part 2) Source: https://base.bangwu.me/about/courses/macro-economics-2 Course notes on macroeconomics part 2 covering GDP deflator, savings-investment identity, unemployment rates, CPI index methods, and IS-LM and AD-AS models. 开头引言: ![img](https://picx.zhimg.com/80/v2-5ec22c794360c3bb6b75718ddb359b5e_1440w.webp?source=1940ef5c) 宏观微观经济学的区别联系 **首先对于宏观经济学,你需要明白,为什么微观宏观差距那么大,它们的联系和区别分别是啥。这会对新的宏观经济学习起到一个很好的衔接作用!** 下面给大家分析一下自宏观经济指标衡量到最后一章,总体对宏观经济学进行系统总结: ![img](https://picx.zhimg.com/80/v2-4c5ae8511f495978a4ccbda5675d6bf3_1440w.webp?source=1940ef5c) 国内生产总值及其核算方法 这里就要注意**GDP概念以及其5大注意**⚠️ 以及名义、实义GDP的计算技巧。要注意:**实际GDP=名义GDP➗GDP折算指数** ![img](https://pic1.zhimg.com/80/v2-c0b51840857474794f250d78c1199b9c_1440w.webp?source=1940ef5c) “储蓄-投资”恒等式 “储蓄-[投资恒等式](https://www.zhihu.com/search?q=投资恒等式\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})”分三大部门,但是实际上并不常用。考试知道相关公式以及对应表示方式即可。 ![img](https://pic1.zhimg.com/80/v2-4546719c445c56d749176bb47f9fe819_1440w.webp?source=1940ef5c) 失业衡量和物价水平衡量 三类事业人的经典图形出自下面这张图。但是经过我的改编(见上图)可以直接考此图解决失业参与率两大问题!计算时背图即可**快速秒杀!** ![img](https://picx.zhimg.com/80/v2-f588969b703c6c1d71114b4b67a6719d_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-6a7106abbe6f16990e24a41eb4a8ffdb_1440w.webp?source=1940ef5c) “均衡产出” 上图为两大非常好的方法解决均衡产出模型问题,建议反复看明白。**一种是横纵轴的方法,一种是之前说到的收入支出恒等式**(这里为事前分析,所以s不一定等于i) 这里注意⚠️凯恩斯定律经常考到,需要记忆。下面开始详细讲解凯恩斯定律: ![img](https://pic1.zhimg.com/80/v2-065b4b25b44428bda7625a9ad30042f4_1440w.webp?source=1940ef5c) 消费函数 通过\*\*[C=a+bY](https://www.zhihu.com/search?q=C%3Da%2BbY\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})\*\*,可以通过线性推导出上述图片所有公式。消费边际、平均消费倾向的计算式都完全可以通过定义得出。 所以千万不要背,学会理解,方可在考场上奋笔疾书。 ![img](https://picx.zhimg.com/80/v2-6226f3b1a619bcbbe205bc7ee7e4e96e_1440w.webp?source=1940ef5c) “储蓄函数”与“消费函数” 储蓄函数就类似于上述消费函数,公式都是由定义表示的。 这里注意⚠️消费函数与储蓄函数的三大易考点!需要背诵记忆,考选择题、填空题经常被考到!而且很容易弄反。 ![img](https://picx.zhimg.com/80/v2-27c99bf45fddcb6b711047414ffa1a28_1440w.webp?source=1940ef5c) 各字母表示+两部门经济收入决定 因为怕大家对于各字类字符看不懂(我第一次看就感觉很烦)就直接把相关的字母以及代表的含义重新写了一遍,如上图。 “两部门经济”考试几率较低,认知即可 ![img](https://pica.zhimg.com/80/v2-232581a84fd90203380d320f6e1952f9_1440w.webp?source=1940ef5c) “三部门经济收入决定” 据我经验,**三部门经济收入决定一般各大高校期末都会出** 但是无非是上图三大公式。 \*\*我个人总结了一种三部门经济的记忆口诀(见上图),三步解决此类计算题。\*\*不需要背公式,看懂此口诀以及对应公式理解即可快速答题 ![img](https://pic1.zhimg.com/80/v2-d5145a93bf22ffb924fef96ff6d3a70b_1440w.webp?source=1940ef5c) “四部门经济收入决定” 这里注意一下,四部门经济不存在可支配收入YD的函数。实际上,四部门经济在考试中只需要了解推倒即可,以及需要知道:对外贸易乘数小于封闭经济乘数即可。(原因见上图) \***下面开始讲解IS-LM模型,会以一种较为简单的方式讲解,绝对比老师的上课具有逻辑与清晰。\*** ![img](https://picx.zhimg.com/80/v2-acca6ef0671250520c64addea4080ec1_1440w.webp?source=1940ef5c) 投资函数 投资函数[成减函数](https://www.zhihu.com/search?q=成减函数\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})由常识即可知。这里的“**e,d**”老师上课很少说及,这里详细给出定义。 ![img](https://picx.zhimg.com/80/v2-33bceefdb1c7b10c2e1f8664387f9e67_1440w.webp?source=1940ef5c) MEC与MEI以及曲线图 **MEC与MEI的考试点一般在:** 1.通过MEC与市场利率比较,从而决定是否企业投资,而不会直接通过计算让你去求r。 2.MEI与[MEC曲线](https://www.zhihu.com/search?q=MEC曲线\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})的差异点以及原因。其余考点上述图片皆很详细了。 ![img](https://picx.zhimg.com/80/v2-0c8359859e6fd52c88e9403a4d561a26_1440w.webp?source=1940ef5c) “IS曲线” 这里IS曲线考得最多的就是计算题了。记住那个代数推倒的最终公式。基础较弱的话直接通过此公式的数学表达解题。 同样,IS曲线斜率也需要知道,**并且会从代数推倒公式得出[斜率表达式](https://www.zhihu.com/search?q=斜率表达式\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})!** ![img](https://pic1.zhimg.com/80/v2-ee3290c46dda5b7825182e564c2c8edf_1440w.webp?source=1940ef5c) 货币需求理论 货币需求理论是经常考的内容,需要背诵定义。 这里注意,[货币需求函数](https://www.zhihu.com/search?q=货币需求函数\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})需要理解(上图)而不是记忆。 ![img](https://pic1.zhimg.com/80/v2-b5ab0983baf85118e4147c6816799fa3_1440w.webp?source=1940ef5c) 货币供求均衡 货币供求均衡M/P=L时的交点,即为供求均衡。 ![img](https://picx.zhimg.com/80/v2-248dae0e13facc1e60e7c06ac29042e3_1440w.webp?source=1940ef5c) LM LM曲线最容易考的点一定会是代数的推倒和计算。一定要好好看懂,最好自己会推。 ![img](https://picx.zhimg.com/80/v2-6c9caa7881da1c88d2c52fa989d90cd2_1440w.webp?source=1940ef5c) LM曲线三大区域 LM曲线需要知道[凯恩斯区域](https://www.zhihu.com/search?q=凯恩斯区域\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})是接近水平以及原因,而古典区域是利率与斜率无关。 **下节章节较难,需要大家认真整理知识点,熟记笔记!我将会把最重要的关键点在这里闸述。** ![img](https://picx.zhimg.com/80/v2-f166092d48aa28944d0756475127abd6_1440w.webp?source=1940ef5c) 总需求曲线 总需求曲线的含义需要记忆。同时也要会推倒总需求曲线。 对于总需求[曲线斜率](https://www.zhihu.com/search?q=曲线斜率\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267}),我后面会专门花时间和其他知识点相互串联起来!后续将会持续讲解。 ![img](https://picx.zhimg.com/80/v2-9dc43476d31ba1f75bc752d9369442d4_1440w.webp?source=1940ef5c) 总需求曲线移动 本章节研究的是p不变。两大政策扩张收缩将会导致需求曲线移动。 **口诀:扩张右,收缩左。** ![img](https://pica.zhimg.com/80/v2-ffc32381493eb8fbcfcda6e11440ae28_1440w.webp?source=1940ef5c) 总供给与宏观生产函数 总供给与宏观生产函数的含义+表示需要明白。短期长期图要会画。 ![img](https://pica.zhimg.com/80/v2-3ded0372b96fc910d8e802b7f41c4c38_1440w.webp?source=1940ef5c) 失业率与自然就业率 **》》今天处理了一些论文的事情,现在是12:36,本人仍在一边写论文一边更新哈,熬夜也要更!实在不容易!!大家给个关注就行,不用任何的投币打赏。** ## 继续更! 了解了自然失业率,首先要知道自然失业率的推倒方式,并且记住最后的公式。相对的,自然失业率就是与之相对应的。 两大失业的经济学解释,记住定义并且对图进行分析。我将会在后面把一些重要的宏观经济学图形给大家表示出来。这里稍微拓展一下**自愿失业:w/p表示实际工资。s则表示劳动力,当实际工资较高时,劳动力也较高。而实际的工资只有在E点时的(W/P)\*,不符合劳动力较高人的高工资心理。所以这些劳动力高的人自愿失业。** ![img](https://picx.zhimg.com/80/v2-7b0133d8afd1b8e0ae473c3f74a68c66_1440w.webp?source=1940ef5c) 失业的两大原因 **对比结构性失业和摩擦性失业,两者间最大的区别是失业的短暂与长期。这里也容易考简答题和含义题目,上图已全部列出。** ![img](https://picx.zhimg.com/80/v2-82c12bfb0eff452ccbd1986b15972854_1440w.webp?source=1940ef5c) “失业的影响”与“奥肯定律” 失业的影响常考选择题,熟知并且记忆即可。奥肯定律相对较难,期末考试考的不会太频繁。但是想要学好一定要认真记忆公式与结论ʕ •ᴥ•ʔ ![img](https://picx.zhimg.com/80/v2-ace20d42d10e8398dcc3893a7f154819_1440w.webp?source=1940ef5c) 通货膨胀衡量 通货膨胀衡量的定义需要认真掌握明白。同时,要能够区分通货膨胀的三大分类。 ![img](https://picx.zhimg.com/80/v2-c63fdb89945f1c58a4ca28bc8f995507_1440w.webp?source=1940ef5c) 外汇与对外贸易 这一部分主要记忆汇率及标价,汇率的改变所对于国家外国的影响。以及实际汇率与[净出口函数](https://www.zhihu.com/search?q=净出口函数\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})要记忆弄懂。知道含义、影响。 ![img](https://pic1.zhimg.com/80/v2-06f39fa7488095edf1a4447172059d7f_1440w.webp?source=1940ef5c) M-F模型 首先要知道,本章开放经济研究时P是不会变的。其次,注意三大图:IS,[LM开放经济](https://www.zhihu.com/search?q=LM开放经济\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})以及[蒙代尔-弗莱明模型](https://www.zhihu.com/search?q=蒙代尔-弗莱明模型\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})。这里仔细看图,**理解记忆。不能死记硬背!** ![img](https://pic1.zhimg.com/80/v2-309a405d996ab622363353738539a94d_1440w.webp?source=1940ef5c) “经济增长” 这里需要注意,宏观经济学**不研究经济发展**。对于经济增长记忆即可。 ![img](https://picx.zhimg.com/80/v2-bf05f87e37a3e92cace0fc568f9871c1_1440w.webp?source=1940ef5c) “增长核算” 这里注意增长核算的推倒方式。用到的是高等数学“\*\*[全微分](https://www.zhihu.com/search?q=全微分\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A1657147267})”的知识。\*\*通过经济生产函数经过变形,取自然对数ln,再经过分别微分处理后所得即位核算方程。**不会推导的建议一定要记住。** 然后是促进经济增长政策,四个要点,我放到这里则可以很好结合增长核算的内容进行理解记忆。 **(我接下来可能也会更一个专门的数学干货系列。分别对于期末高数线代,考研数学进行系统完善的总结。然后看看反响怎么样。这里先占个坑。** ![img](https://picx.zhimg.com/80/v2-9f231f466cef2771ec852ff9dad858da_1440w.webp?source=1940ef5c) “新古典增长模型” 注意这里的知识体系思路非常独特。先进行假设:没有技术进步的增长模型,之后又分析具有技术进步的增长模型。推导形式较为复杂,先进行记忆。 \*注意新古典增长模型在部分学校会考的深入,但是很多学校不会太过强求推导。 ![img](https://pic1.zhimg.com/80/v2-09f7e0b4584504c61ba6b4b4e10e33eb_1440w.webp?source=1940ef5c) 最重要的此部分如果考到了,一定会重点出给大家。建议一定要记忆下来,反复看。**一般出定义题和图形题比较多。** \*应用古典增长是本章重点,学长当年选择题最后一大题就是考分析。仔细看。 **点赞多多,更新更卖力!** \***创作真的属实不易,喜欢一定要点个关注哈 ~❤️❤️❤️\*** *** ## ⚠️每位关注up的同学,今后将会持续获取最新“精华干货”文章通知哦! > 并且,后续推出对应各类应对期末方法,如:“线性代数流程”;高数大招考研版+期末版;“英语作文技巧”按套路模版直接秒杀英语作.....等,专门应对and解决各类期末考点。快速节约时间! ## *关注我❤️ 让你的大学期末远离挂科! !* [编辑于 2021-01-27 21:27](https://www.zhihu.com/question/359954309/answer/1657147267) 赞同 1789136 条评论 分享 收藏喜欢 收起 #### 更多回答 [![凌依Jocelyn](https://picx.zhimg.com/v2-190970abff6ae2f656deda382fd93a58_l.jpg?source=1940ef5c)](https://www.zhihu.com/people/zhao-zi-ling-jocelyn) [凌依Jocelyn](https://www.zhihu.com/people/zhao-zi-ling-jocelyn) 真实善良,一技之长 关注 917 人赞同了该回答 ![img](https://pic1.zhimg.com/v2-190970abff6ae2f656deda382fd93a58_l.jpg?source=f2fdee93) 凌依Jocelyn 6 次咨询 5.0 14623 次赞同 去咨询 宏观经济学考了98,以下是刷题+自己总结的宏观经济学考点: 1.GDP的名词概念解释(常考,要默) 2.核算gdp的三种方法,清楚收入法和支出法分别有什么。(选择题) 3.区分消费支出中的耐用品和非耐用品有哪些?(选择题) 4.一定要记得涉及住房就是投资,不管是家庭买住宅,还是企业或政府部门买房都是算做投资。 5. GNP、PI等相关概念大概理解和计算公式。(计算题要做) 6.通货膨胀的三种类型(简答) 7.名义增长率和、实际增长率公式和GDP平减指数公式(计算) 8.通货膨胀名词概念解释(常考默写) 9.通过膨胀的经济影响(再分配效应和产出效应)简答题 10.[菲利普斯曲线](https://www.zhihu.com/search?q=菲利普斯曲线\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})是反映哪两个变量的相关关系?是正相关还是负相关(选择) 11.奥肯定律的名词概念解释(默写) 12.[边际消费倾向](https://www.zhihu.com/search?q=边际消费倾向\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})名词解释、公式、符号 13.平均消费倾向和边际消费倾向的关系(选择、判断) 14.[消费函数](https://www.zhihu.com/search?q=消费函数\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})的一般表达式(选择题有用) 15.资本边际效率,贴现率的名词概念解释(常考,默写) 16.每个乘数(投资乘数,政府支出乘数税收陈述,政府转移支付乘数、[平衡预算乘数](https://www.zhihu.com/search?q=平衡预算乘数\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962}))相应的公式(选择题考计算、计算题) 17.记住[IS曲线](https://www.zhihu.com/search?q=IS曲线\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})代表产品和服务市场,[LM曲线](https://www.zhihu.com/search?q=LM曲线\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})代表货币市场(考判断) 18. IS曲线的推导(考计算题,把几条公式列出来就可以推导了) 19.记住IS曲线的斜率(做选择或判断可以快速知道曲线的变化情况) 20.货币需求有哪三大点?投资动机、预防或谨慎动机、投机动机(简答题,要默写) 21.[流动性偏好](https://www.zhihu.com/search?q=流动性偏好\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})是指:不管有多少货币,人们都愿意将其保持在手中的情况(判断题) 22.记住LM曲线的推导(计算)、斜率(方便选择做选择和判断题推导LM曲线的变化) 23.记住[ln曲线](https://www.zhihu.com/search?q=ln曲线\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})的古典区域和[凯恩斯区域](https://www.zhihu.com/search?q=凯恩斯区域\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})的图像(判断财政政策和货币政策分别在LM曲线的古典区域和凯恩斯区域是否有效果) 24.总需求函数的名词概念解释。 25.价格变动的效应,利率效应,实际余额效应,税收效应(简答题罗列出价格变动的效应有什么?或者考名词解释,问实际余额效应是什么?) 26.总需求曲线的推导(从LM-IS两条公式共同推出,做计算题) 27.影响总需求AD变动的因素(做判断题或选择题,要会判断扩张的财政政策货币政策,或者紧缩的财政政策货币政策) 28.能够画出[凯恩斯主义](https://www.zhihu.com/search?q=凯恩斯主义\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})和古典主义的总供给AS曲线。(做判断或选择,判断出:在凯恩斯区域或古典区域,当财政政策或货币政策实施影响了总需求曲线后,国民收入有无变化,相应政策有无效果?) 29.能够画出价格刚性和价格弹性的总供给曲线。(方便就判断做选择和选择) 30.财政政策的名词解释 31.宏观经济政策的4个目标:充分就业稳定物价,经济增长,国际收支平衡(简答题) 32.自动稳定器([自动稳定的财政政策](https://www.zhihu.com/search?q=自动稳定的财政政策\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962}))名词解释 33.挤出效应的名词解释 34.货币政策工具有哪些?公开市场业务[法定准备金率](https://www.zhihu.com/search?q=法定准备金率\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962}),再贴现率(简答题)(要像做名词概念解释一样解释这三个词,并且相应列出:经济萧条时,中央银行做了什么,会怎么样?经济繁荣时,中央银行做了什么会怎么样?) 35.基础货币(高能货币)有哪些?法定准备金、[超额准备金](https://www.zhihu.com/search?q=超额准备金\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})、库存现金、流通中的现金。(简答) 36.[货币乘数](https://www.zhihu.com/search?q=货币乘数\&search_source=Entity\&hybrid_search_source=Entity\&hybrid_search_extra=\{"sourceType"%3A"answer"%2C"sourceId"%3A2245875962})的公式。(选择题要做计算) 37.固定汇率制和浮动汇率制的名词解释,弄清他们两者的区别(做判断题) 总需求)—总供给模型 ![img](https://picx.zhimg.com/80/v2-8f11ff1200bd0466e192ccef0c863f11_1440w.webp?source=1940ef5c) ![img](https://pica.zhimg.com/80/v2-897d6728320716255da51fbe611d85ff_1440w.webp?source=1940ef5c) ![img](https://pica.zhimg.com/80/v2-8ece898bb9c9aff67dd580f16eac25e8_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-c803e40396ed5fedf3e01880216cf4ae_1440w.webp?source=1940ef5c) 财政政策和货币政策 ![img](https://picx.zhimg.com/80/v2-4fd73f28d4aa6a777fe1baa8524addab_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-e20751b726367b2c4d923df63ba8ef2e_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-54996298b9dcedb386f6ccd75ec7a78c_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-7ce560eaef82b5115206b59800a88370_1440w.webp?source=1940ef5c) ![img](https://pic1.zhimg.com/80/v2-e9a2d0c22c6600ad67c11c77eec0e308_1440w.webp?source=1940ef5c) 汇率 ![img](https://pic1.zhimg.com/80/v2-156d5fddda16e84e263b3639350ad07d_1440w.webp?source=1940ef5c) ![img](https://pica.zhimg.com/80/v2-d32d000ba0deba766fbe3d28a1e005ee_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-7799285b3562f3a4eff46e704c72d271_1440w.webp?source=1940ef5c) ![img](https://picx.zhimg.com/80/v2-63f48fa10363158f226e6aae340a9f76_1440w.webp?source=1940ef5c) # Web design and development Source: https://base.bangwu.me/about/courses/web-design Course notes on web design covering HTML structure and tags, CSS selectors and box model layout, and JavaScript DOM manipulation basics. # Web 设计与应用 前端三剑客:HTML + CSS + JavaScript ## HTML(超文本标记语言) HTML 是构建网页结构的标记语言。 ### 基本结构 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} 网页标题

欢迎来到我的网站

这是一个段落

``` ### 常用标签 #### 文本标签 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}

一级标题

二级标题

段落文本

行内文本 粗体 斜体

``` #### 链接和图片 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} 链接文本 新窗口打开 图片描述 ``` #### 列表 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
  • 项目1
  • 项目2
  1. 第一项
  2. 第二项
``` #### 表格 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
姓名 年龄
张三 25
``` #### 表单 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
男 女 同意条款
``` #### 语义化标签(HTML5) ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
页头
主要内容
文章
章节
页脚
``` ## CSS(层叠样式表) CSS 用于控制网页的外观和布局。 ### 引入方式 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
红色文字
``` ### 选择器 ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} /* 元素选择器 */ p { color: blue; } /* 类选择器 */ .my-class { font-size: 16px; } /* ID选择器 */ #my-id { margin: 10px; } /* 后代选择器 */ div p { color: red; } /* 子选择器 */ div > p { color: green; } /* 伪类 */ a:hover { color: red; } input:focus { border-color: blue; } /* 伪元素 */ p::before { content: "前缀"; } p::after { content: "后缀"; } ``` ### 盒模型 ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} .box { width: 200px; height: 100px; padding: 10px; /* 内边距 */ border: 1px solid #ccc; /* 边框 */ margin: 20px; /* 外边距 */ } ``` ### 布局 #### Flexbox ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} .container { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ gap: 10px; /* 间距 */ } .item { flex: 1; /* 占据剩余空间 */ } ``` #### Grid ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} .grid-container { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; } ``` #### 定位 ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} .element { position: relative; /* 相对定位 */ position: absolute; /* 绝对定位 */ position: fixed; /* 固定定位 */ position: sticky; /* 粘性定位 */ } ``` ### 响应式设计 ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} /* 媒体查询 */ @media (max-width: 768px) { .container { flex-direction: column; } } /* 移动优先 */ .box { width: 100%; } @media (min-width: 768px) { .box { width: 50%; } } ``` ### 动画和过渡 ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} /* 过渡 */ .button { transition: all 0.3s ease; } .button:hover { transform: scale(1.1); background-color: blue; } /* 动画 */ @keyframes slideIn { from { transform: translateX(-100%); } to { transform: translateX(0); } } .element { animation: slideIn 1s ease-out; } ``` ## JavaScript JavaScript 为网页添加交互功能。 ### 基础语法 ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // 变量声明 let name = 'John'; const age = 30; var oldWay = 'deprecated'; // 数据类型 let number = 42; let string = "Hello"; let boolean = true; let array = [1, 2, 3]; let object = { name: 'John', age: 30 }; // 函数 function greet(name) { return `Hello, ${name}!`; } // 箭头函数 const greet = (name) => `Hello, ${name}!`; // 条件语句 if (age >= 18) { console.log('成年'); } else { console.log('未成年'); } // 循环 for (let i = 0; i < 5; i++) { console.log(i); } array.forEach(item => { console.log(item); }); ``` ### DOM 操作 ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // 获取元素 const element = document.getElementById('myId'); const elements = document.querySelectorAll('.myClass'); const element = document.querySelector('.myClass'); // 修改内容 element.textContent = '新文本'; element.innerHTML = '粗体文本'; // 修改样式 element.style.color = 'red'; element.classList.add('active'); element.classList.remove('inactive'); element.classList.toggle('highlight'); // 修改属性 element.setAttribute('data-id', '123'); element.getAttribute('data-id'); // 创建和删除元素 const newDiv = document.createElement('div'); newDiv.textContent = '新元素'; document.body.appendChild(newDiv); element.remove(); ``` ### 事件处理 ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // 点击事件 button.addEventListener('click', function(e) { console.log('按钮被点击了'); }); // 表单提交 form.addEventListener('submit', function(e) { e.preventDefault(); // 阻止默认行为 const formData = new FormData(form); console.log(formData.get('username')); }); // 键盘事件 input.addEventListener('keyup', function(e) { console.log('按键:', e.key); }); // 鼠标事件 element.addEventListener('mouseenter', function() { this.style.backgroundColor = 'yellow'; }); ``` ### 异步操作 ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // Promise fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); // Async/Await async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error(error); } } // 定时器 setTimeout(() => { console.log('3秒后执行'); }, 3000); setInterval(() => { console.log('每秒执行'); }, 1000); ``` ### 本地存储 ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // localStorage - 永久存储 localStorage.setItem('key', 'value'); const value = localStorage.getItem('key'); localStorage.removeItem('key'); // sessionStorage - 会话存储 sessionStorage.setItem('key', 'value'); // 存储对象 const user = { name: 'John', age: 30 }; localStorage.setItem('user', JSON.stringify(user)); const storedUser = JSON.parse(localStorage.getItem('user')); ``` ## 实战示例 ### 待办事项列表 ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} 待办事项

待办事项

``` ## 学习资源 * [MDN Web Docs](https://developer.mozilla.org/zh-CN/) - 最权威的 Web 技术文档 * [W3Schools](https://www.w3schools.com/) - 在线教程和实例 * [FreeCodeCamp](https://www.freecodecamp.org/) - 免费编程课程 * [CSS-Tricks](https://css-tricks.com/) - CSS 技巧和教程 * [JavaScript.info](https://javascript.info/) - 现代 JavaScript 教程 ## 开发工具 * **浏览器**:Chrome DevTools, Firefox DevTools * **编辑器**:VS Code, Sublime Text * **在线工具**:CodePen, JSFiddle, CodeSandbox ## 最佳实践 1. **语义化 HTML**:使用合适的标签 2. **响应式设计**:适配不同设备 3. **性能优化**:压缩资源,懒加载 4. **可访问性**:支持屏幕阅读器 5. **代码规范**:保持一致的编码风格 6. **版本控制**:使用 Git 管理代码 # About Source: https://base.bangwu.me/about/index About bangwu (markbang) — ECNUer and full-stack developer, with blog and knowledge base links, personal interests, and content platforms. ## bangwu / markbang * Deep thinker on *Under One Person* * ECNUer * Full-stack developer who believes "everything exists for a reason" * Gaming addict, badminton beginner, tinkerer champion, music listener * INFP-A ## Content output | Platform | Description | Link | | - | - | - | | Blog | Daily thoughts and life sharing | [blog.bangwu.top](https://blog.bangwu.top) | | Knowledge Base | CS knowledge collection | [base.bangwu.me](https://base.bangwu.me) | | Micro-blog | RSS feed | [now.bangwu.top](https://now.bangwu.top/rss.xml) | ## Contact * **Email**: [i@bangwu.top](mailto:i@bangwu.top) * **GitHub**: [markbang](https://github.com/markbang) > [!NOTE] > > I usually reply to email slowly, so thanks for your patience. ## Declaration In the vast ocean of the internet, meeting each other is a kind of fate—so please be kind in your words. A URL is my first promise to the internet, and I plan to keep this domain for a long time. — September 27, 2024 # Site Info Source: https://base.bangwu.me/about/site Knowledge base site guide covering four content sections, page conventions, recommended reading workflow, and current maintenance principles. # Site Introduction I started building this site because tutorial quality online is inconsistent — especially on domestic forums like CSDN, Juejin, and Jianshu. So I decided to create my own — detailed, beginner-friendly tutorials that not only push me to learn, but also share better resources to save everyone's time. One person can't cover everything, so contributions are welcome to build a high-quality knowledge base together. ## Logo Origin The site logo comes from a Google emoji combiner I found on a post — Clown + Angry. ## Metadata & Conventions | Element | Description | | - | - | | Sidebar | Links to topics within the current section, or tutorial sequence | | Section landing page | Introduction to the section's scope and purpose | | Search | Top-left search bar, or `Ctrl+K` to open quickly | | Comments | Available at the bottom of each page | # Bit manipulation Source: https://base.bangwu.me/algo/bit Bitwise operations guide covering AND/OR/XOR, common tricks like checking powers of two, and LeetCode examples using low-level binary manipulation. # Bit manipulation Bitwise operations work directly on binary bits. They are efficient and commonly used for algorithm optimization. ## Basic bit operators | Operators | Name | Description | Example | | | | | - | - | - | - | - | - | - | | `&` | Bitwise AND | The result is `1` only when both bits are `1` | `5 & 3 = 1` (101 & 011 = 001) | | | | | \` | \` | Bitwise OR | The result is `1` when either bit is `1` | \`5 | 3 = 7\` (101 | 011 = 111) | | `^` | Bitwise XOR | The result is `1` when the bits are different | `5 ^ 3 = 6` (101 ^ 011 = 110) | | | | | `~` | Bitwise NOT | Flip `0` to `1` and `1` to `0` | `~5 = -6` | | | | | `<<` | Left shift | Shift left by `n` bits, equivalent to multiplying by `2^n` | `5 << 1 = 10` | | | | | `>>` | Right shift | Shift right by `n` bits, roughly equivalent to dividing by `2^n` | `5 >> 1 = 2` | | | | ## Common tricks ### 1. Check odd or even ### 2. Swap two numbers without a temporary variable ### 3. Check whether the k-th bit is `1` ### 4. Set the k-th bit to `1` ### 5. Set the k-th bit to `0` ### 6. Flip the k-th bit ### 7. Extract the lowest `1` bit ### 8. Remove the lowest `1` bit ### 9. Check whether a number is a power of two ### 10. Count the number of `1` bits in binary ## Classic problems ### [LeetCode 136. Single Number](https://leetcode.cn/problems/single-number/) **Problem:** every number in the array appears twice except one. Find the one that appears only once. **Idea:** use the XOR properties `a ^ a = 0` and `a ^ 0 = a`. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def singleNumber(self, nums: List[int]) -> int: ans = 0 for num in nums: ans ^= num return ans ``` ### [LeetCode 191. Number of 1 Bits](https://leetcode.cn/problems/number-of-1-bits/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n: n &= n - 1 count += 1 return count ``` ### [LeetCode 231. Power of Two](https://leetcode.cn/problems/power-of-two/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and (n & (n - 1)) == 0 ``` ### [LeetCode 338. Counting Bits](https://leetcode.cn/problems/counting-bits/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def countBits(self, n: int) -> List[int]: dp = [0] * (n + 1) for i in range(1, n + 1): dp[i] = dp[i >> 1] + (i & 1) return dp ``` ## Typical use cases * **State compression**: represent multiple boolean states with one integer * **Set operations**: implement intersection, union, and complement through bit masks * **Permission systems**: store different permissions as bits * **Performance optimization**: use fast bitwise operations to replace some multiply/divide cases # Algorithm Learning Source: https://base.bangwu.me/algo/index Algorithm learning roadmap with open-source resources like Hello Algo, Code Carried Away, and labuladong's notes, plus LeetCode tracking. Algorithm study here mainly follows open-source books on GitHub together with LeetCode practice. ![LeetCode Stats](https://leetcard.jacoblin.cool/bangwu?theme=nord\&font=Readex%20Pro\&ext=activity\&site=cn) ## Recommended resources > [accordion] Hello Algo > > [Hello Algo](https://github.com/krahets/hello-algo): An animated, beginner-friendly data structures and algorithms tutorial with one-click runnable examples. It supports Java, C++, Python, Go, JS, TS, C#, Swift, Rust, Dart, and Zig. > [accordion] Code Thinking Record > > [Code Thinking Record](https://github.com/youngyangyang04/leetcode-master): A classic structured problem set with detailed explanations, videos, mind maps, and multi-language support. > [accordion] labuladong's Algorithm Notes > > [labuladong](https://github.com/labuladong/fucking-algorithm): Original articles built around LeetCode problems, focused on patterns, intuition, and transferable problem-solving techniques. > [accordion] AI Engineering from Scratch > > [AI Engineering from Scratch](https://github.com/rohitg00/ai-engineering-from-scratch): 20 stages, 523 lessons, \~342 hours — from linear algebra to autonomous agents. Every lesson ships a reusable artifact (SKILL.md, prompt, MCP server); install with `npx skills add rohitg00/ai-engineering-from-scratch`. > [accordion] Stanford CS 329Z > > [CS 329Z: Engineering AI Agents](https://cs329z.stanford.edu) (Fall 2026, Diyi Yang et al.): the engineering path from LLM pipelines to compound systems to autonomous agents. Lecture slides are public — the tool-use and frameworks/orchestration decks pair well with the harness notes on this site. > [card] [Sliding Window](/algo/sliding_window) > > Two-pointer and sliding window patterns. > [card] [Bit Manipulation](/algo/bit) > > Common bit tricks and problem types. # Sliding window Source: https://base.bangwu.me/algo/sliding_window Sliding window algorithm using two pointers for subarray and substring problems, with a Python template, LeetCode examples, and O(n) analysis. [leetcode.3](https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/) The sliding window technique is a common two-pointer pattern for array and string problems. By maintaining a window that moves across the sequence, many problems can be solved in `O(n)` time. ### Core idea 1. Use two pointers, `left` and `right`, to represent the window boundaries. 2. Move `right` to expand the window. 3. When the window satisfies a shrink condition, move `left` to contract it. 4. Update the answer while the window changes. ### Template code ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} def sliding_window(s: str): left = 0 window = {} # 窗口内's 数据 result = 0 for right in range(len(s)): # 1. 将right位置's 元素加入窗口 c = s[right] window[c] = window.get(c, 0) + 1 # 2. 判断窗口是否需要收缩 while 窗口需要收缩's 条件: # 3. 移出left位置's 元素 d = s[left] left += 1 window[d] -= 1 # 4. 更新结果 result = max(result, right - left + 1) return result ``` ## Classic problems ### 1. [LeetCode 3. Longest substring without repeating characters](https://leetcode.cn/problems/longest-substring-without-repeating-characters/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # leetcode.3 滑动窗口+哈希表 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: dic, res, i = {}, 0, -1 for j in range(len(s)): if s[j] in dic: i = max(i, dic[s[j]]) dic[s[j]] = j res = max(res, j-i) return res ``` ### 2. [LeetCode 76. Minimum window substring](https://leetcode.cn/problems/minimum-window-substring/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def minWindow(self, s: str, t: str) -> str: from collections import Counter need = Counter(t) window = {} left = 0 valid = 0 start, length = 0, float('inf') for right in range(len(s)): c = s[right] if c in need: window[c] = window.get(c, 0) + 1 if window[c] == need[c]: valid += 1 while valid == len(need): if right - left + 1 < length: start = left length = right - left + 1 d = s[left] left += 1 if d in need: if window[d] == need[d]: valid -= 1 window[d] -= 1 return "" if length == float('inf') else s[start:start+length] ``` ### 3. [LeetCode 438. Find all anagrams in a string](https://leetcode.cn/problems/find-all-anagrams-in-a-string/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: from collections import Counter need = Counter(p) window = {} left = 0 valid = 0 result = [] for right in range(len(s)): c = s[right] if c in need: window[c] = window.get(c, 0) + 1 if window[c] == need[c]: valid += 1 while right - left + 1 >= len(p): if valid == len(need): result.append(left) d = s[left] left += 1 if d in need: if window[d] == need[d]: valid -= 1 window[d] -= 1 return result ``` ### 4. [LeetCode 209. Minimum size subarray sum](https://leetcode.cn/problems/minimum-size-subarray-sum/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 total = 0 result = float('inf') for right in range(len(nums)): total += nums[right] while total >= target: result = min(result, right - left + 1) total -= nums[left] left += 1 return 0 if result == float('inf') else result ``` ### 5. [LeetCode 567. Permutation in string](https://leetcode.cn/problems/permutation-in-string/) ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: from collections import Counter need = Counter(s1) window = {} left = 0 valid = 0 for right in range(len(s2)): c = s2[right] if c in need: window[c] = window.get(c, 0) + 1 if window[c] == need[c]: valid += 1 while right - left + 1 >= len(s1): if valid == len(need): return True d = s2[left] left += 1 if d in need: if window[d] == need[d]: valid -= 1 window[d] -= 1 return False ``` ## Typical use cases * Finding the best value over a continuous subarray or substring * String matching problems * Fixed-length window problems * Longest or shortest subarray satisfying a condition ## Time complexity Although there are two loops, each element is visited at most twice—once by `right` and once by `left`—so the overall time complexity is `O(n)`. # Apifox Source: https://base.bangwu.me/apps/Apifox Apifox is an all-in-one API platform combining Postman, Swagger, Mock, and JMeter for REST API design, debugging, testing, and documentation. [Apifox](https://apifox.com/) is an all-in-one API design, development, and testing platform — a domestic Chinese app. Apifox = Postman + Swagger + Mock + JMeter. If you've worked with backend API debugging, you know that a good API testing tool speeds up development. Apifox is exactly that kind of platform. ![bangwu\_20240521131017](https://p0.meituan.net/csc/2af07a2f9a712959a589a7f4ebdb8c96101444.webp) # Barrier Source: https://base.bangwu.me/apps/Barrier Barrier is an open-source Synergy alternative for sharing one keyboard and mouse across multiple computers on Windows, macOS, or Linux. # Device Sharing Barrier lets you use one keyboard and mouse across multiple devices — an open-source alternative to Synergy. ## Installation > [tab] Scoop > > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} > scoop install barrier > ``` > > > [!WARNING] > > > > Barrier installed via Scoop may fail to connect to the LAN, possibly due to an unaccepted protocol. If you encounter this issue, use the manual installation method below. > [tab] Manual Install > > Download from [GitHub Releases](https://github.com/debauchee/barrier/releases/tag/v2.4.0). # Browser Harness Source: https://base.bangwu.me/apps/BrowserHarness Browser Harness is a thin, self-healing browser control layer built on CDP for coding agents like Codex and Claude Code that need real browser access. # Browser Harness [Browser Harness](https://github.com/browser-use/browser-harness) is an open-source browser control layer from the Browser Use team. Its core idea is simple: * connect directly to Chrome through **CDP** * keep the harness **thin** * let the agent **write missing helper code during the task** It is not trying to be another large test framework. It is closer to a minimal bridge that gives an LLM more freedom inside a real browser session. ## Why it is interesting Compared with rigid browser automation flows, Browser Harness is designed for **agentic use**: * works with tools like **Codex** and **Claude Code** * can connect to your **real browser** * allows the agent to add helper functions while it is working * supports free remote browsers for cloud or sub-agent scenarios The official README describes it as a **self-healing browser harness**: if the current helper set is missing a capability, the agent can edit the harness and continue instead of stopping immediately. ## How it works The project stays intentionally small: * `install.md` handles first-time setup * `SKILL.md` explains normal usage * `helpers.py` contains the callable browser helper functions * `daemon.py` and `admin.py` handle the CDP websocket and local bridge The interesting part is that `helpers.py` is not treated as fixed forever. The agent is expected to inspect it and extend it when needed. In practice, the flow looks like this: 1. Connect the harness to Chrome through CDP 2. Ask the coding agent to complete a browser task 3. If a helper is missing, the agent edits the harness 4. Continue the task with the new helper available That is the main difference from a traditional test script that fails as soon as the missing operation is encountered. ## When to use it Browser Harness makes sense when you want: * a coding agent to operate a real browser for you * interactive browser tasks rather than only deterministic regression tests * a thinner layer than a large end-to-end testing stack * browser work that can improve over time as helpers and skills accumulate Typical examples: * logging into websites with your existing browser profile * navigating complex dashboards * submitting forms or uploading files * doing repetitive browser workflows that are annoying to script upfront ## When not to use it If you need: * strict, reproducible end-to-end tests * stable CI assertions * browser automation with carefully fixed selectors and snapshots then a conventional framework such as Playwright is often a better default. Browser Harness is more about **agent flexibility** than strict test determinism. ## Real browser vs remote browser The project supports both: ### Real browser Best for: * personal workflows * sites where you are already logged in * tasks that benefit from your existing cookies, sessions, and local browser state ### Remote browser Best for: * cloud execution * sub-agents * isolated sessions * tasks that should not depend on your local machine Browser Use also documents a remote-browser/CDP workflow and an MCP server, which makes the surrounding ecosystem broader than this repo alone. ## Practical setup notes The README recommends a very direct setup pattern: 1. let the agent clone or open the repo 2. read `install.md` first 3. read `SKILL.md` for day-to-day usage 4. always inspect `helpers.py` That setup pattern matters because the harness is intentionally editable during execution. ## Browser Use Box [Browser Use Box](https://github.com/browser-use/bux), also called `bux`, is a useful pattern built on top of Browser Harness. Instead of running the agent only on your laptop, it runs a persistent Claude Code environment on a box you own, such as a VPS, Mac mini, or Raspberry Pi. The pieces are simple: * `claude -p` drives the agent loop * Browser Harness connects to a real Chromium session through CDP over WSS * Browser Use Cloud hosts the browser session * Telegram and `ttyd` provide remote control surfaces * `/home/bux` stores persistent state across restarts This solves a different problem from local browser automation. Local agents disappear when the laptop sleeps or the terminal closes. A box-based agent can keep browser logins, cookies, skills, and task state alive, then accept short commands from anywhere. The tradeoff is operational complexity. You now own a small always-on runtime with credentials, systemd services, browser sessions, and remote access paths. Treat it like infrastructure, not just a demo. ## How it fits into the current agent tooling landscape There are now roughly three common layers for browser automation: 1. **classic automation frameworks** Playwright, Puppeteer, Selenium 2. **MCP/browser tools for assistants** tool-call-oriented browser control 3. **agent-native browser harnesses** browser control designed for LLMs that reason, adapt, and patch their own workflow Browser Harness clearly sits in the third category. ## My take The interesting part is not just "LLMs can click a browser". A lot of tools can already do that. The more durable idea is this: > treat browser automation as an editable runtime surface for agents, not only as a fixed script written in advance. That is a useful mental model if you are building agent workflows around real websites. ## References * [browser-use/browser-harness](https://github.com/browser-use/browser-harness) * [Browser Use documentation](https://docs.browser-use.com/) * [browser-use/bux](https://github.com/browser-use/bux) * [Remote Browser via CDP](https://docs.browser-use.com/customize/browser/remote) * [Browser Use MCP Server](https://docs.browser-use.com/customize/mcp-server) # CherryStudio Source: https://base.bangwu.me/apps/CherryStudio CherryStudio is an open-source AI chat client with deep CSS theme customization, including a Claude-style dark and light mode configuration. # CherryStudio GitHub repository: [https://github.com/CherryHQ/cherry-studio](https://github.com/CherryHQ/cherry-studio) The following CSS is a Claude-style theme preset for CherryStudio, with both dark and light variants. ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} /* Claude 主题 2.0 */ /* Theme Variables */ :root { --color-black-soft: #2a2b2a; /* 深灰黑色,接近炭黑 */ --color-white-soft: #f8f7f2; /* 温暖's 米色,略带象牙色调 */ --font-family: 'SF Pro Rounded', 'LXGWWenKaiScreenR', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; --message-text-color-dark: hsl(50, 14%, 91%); /* 暖色调浅米白色 */ } /* Dark Theme */ body[theme-mode='dark'] { /* Color Definitions */ --color-background: #2b2b2b; /* 深炭灰色 */ --color-background-soft: #303030; /* 稍浅's 炭灰色 */ --color-background-mute: #282c34; /* 带深蓝调's 石墨灰 */ --navbar-background: var(--color-black-soft); /* 深灰黑色 */ --chat-background: var(--color-black-soft); /* 深灰黑色 */ --chat-background-user: #323332; /* 中深炭灰色 */ --chat-background-assistant: #2d2e2d; /* 深橄榄灰色 */ font-family: var(--font-family) !important; color: var(--message-text-color-dark) !important; } /* Dark Theme特定样式 */ body[theme-mode='dark'] { #content-container { background-color: var(--chat-background-assistant) !important; font-family: var(--font-family) !important; } #content-container #messages { background-color: var(--chat-background-assistant); color: var(--message-text-color-dark) !important; font-family: var(--font-family) !important; } .message-content-container { background: hsl(60, 2%, 21%) !important; /* 深橄榄灰色,带微弱黄绿色调 */ font-family: var(--font-family) !important; box-shadow: 0 4px 16px -8px rgba(0, 0, 0, 0.04) !important; border: 1px solid var(--color-border) !important; border-radius: 18px !important; margin: 8px 0 !important; padding: 10px 10px 10px 10px !important; color: var(--message-text-color-dark) !important; } /* 用户Message样式 */ .message.message-user, .message.message-user *, .message-user, .message-user *, .message-user .message-content-container, .message-user .message-content-container * { color: var(--message-text-color-dark) !important; } .message-user .message-content-container { background: hsl(60, 2%, 21%) !important; /* 深橄榄灰色,与AI回复一致 */ box-shadow: 0 8px 32px -12px rgba(0, 0, 0, 0.03) !important; } .inputbar-container { background-color: #3d3d3a; /* 中灰色带微橄榄绿调 */ border: 1px solid #5e5d5940; /* 中灰色带40%透明度 */ border-radius: 8px; font-family: var(--font-family) !important; color: var(--message-text-color-dark) !important; } /* Code Styles */ code { background-color: #e5e5e20d; /* 浅灰白色,7%透明度 */ color: #ea928a; /* 淡珊瑚红色 */ font-family: var(--font-family) !important; } pre code { color: #abb2bf; /* 浅钢蓝灰色 */ font-family: var(--font-family) !important; } /* 深色模式下's Text Color Override */ p, span, div { color: var(--message-text-color-dark); } } /* Light Theme */ body[theme-mode='light'] { /* Color Definitions */ --color-white: #ffffff; /* 纯白色 */ --color-background: hsl(55, 19%, 89%); /* 淡米黄灰色 */ --color-background-soft: hsl(51, 16%, 85%); /* 浅麦秆黄色 */ --color-background-mute: #e4e1d7; /* 灰米色,带微暖调 */ --navbar-background: var(--color-white-soft); /* 温暖's 米色 */ --chat-background: var(--color-white-soft); /* 温暖's 米色 */ --chat-background-user: #f8f7f2; /* 温暖's 米色,略带象牙色调 */ --chat-background-assistant: hsl(51, 24%, 95%); /* 非常浅's 麦秆黄色 */ font-family: var(--font-family) !important; } /* Light Theme特定样式 */ body[theme-mode='light'] { #content-container { background-color: var(--chat-background-assistant) !important; font-family: var(--font-family) !important; } #content-container #messages { background-color: var(--chat-background-assistant); font-family: var(--font-family) !important; } .message-content-container { background: hsl(40, 23%, 98%) !important; /* 极浅's 米黄色,接近纯白 */ font-family: var(--font-family) !important; box-shadow: 0 4px 16px -8px rgba(0, 0, 0, 0.04) !important; border: 1px solid var(--color-border) !important; border-radius: 18px !important; margin: 8px 0 !important; padding: 10px 10px 10px 10px !important; color: hsl(47, 15%, 25%) !important; /* 深橄榄褐色 */ } .message-user .message-content-container { background: hsl(51, 19%, 87%) !important; /* 浅麦秆黄色 */ box-shadow: 0 8px 32px -12px rgba(0, 0, 0, 0.03) !important; color: hsl(47, 15%, 25%) !important; /* 深橄榄褐色 */ } .inputbar-container { background-color: #ffffff; /* 纯白色 */ border: 1px solid #87867f40; /* 中灰褐色带40%透明度 */ border-radius: 16px; font-family: var(--font-family) !important; } /* Code Styles */ code { background-color: #3d39290d; /* 深棕褐色,5%透明度 */ color: #7c1b13; /* 砖红褐色 */ font-family: var(--font-family) !important; } pre code { color: #000000; /* 纯黑色 */ font-family: var(--font-family) !important; } } ``` # AI IDE Source: https://base.bangwu.me/apps/Cursor Cursor and Trae are AI-powered code editors — tips, workflows, and billing changes for GitHub Copilot. ## Cursor [go-cursor-help](https://github.com/yuaotian/go-cursor-help/blob/master/README_CN.md#solution1) ```powershell theme={"theme":{"light":"github-light","dark":"github-dark"}} irm https://aizaozao.com/accelerate.php/https://raw.githubusercontent.com/yuaotian/go-cursor-help/refs/heads/master/scripts/run/cursor_win_id_modifier.ps1 | iex ``` ### Cursor 3: What Users Actually Want Based on 431 community feedback responses (April 2026), the core insight is: **users don't just want "AI that writes code" — they want a stable, controllable AI development workbench**. The top priorities are: 1. **Agent + IDE seamless fusion** — Agent Window is promising, but must preserve full IDE capabilities (LSP, debugging, task running, extensions, keybindings, code navigation, diff accept/reject). Users shouldn't have to switch back to the old IDE for small operations. 2. **Worktree / Git / PR workflow productization** — Developers want a low-friction, auditable Git console, not natural-language Git commands. Key needs: branch switching, PR detection, selective staging, multi-repo diff, submodule support, CI status, and review integration. 3. **Stability over features** — Startup speed, memory usage, context loss, LSP failures, and large-repo indexing are trust killers. If the basics don't work, users will switch to alternatives. 4. **Model cost transparency** — Users want to know "which model is cheapest for this task?" not just more models. Good direction: Cursor suggests "use a cheap model here, upgrade to a strong model there." 5. **Keyboard-first** — The entire product must be operable without a mouse. Custom keybindings, quick panel switching, and inherited VS Code muscle memory are essential for heavy users. 6. **Task memory system** — When agent work grows, "chat history list" must evolve into "task memory system": auto-rename chats, pin messages, fork sessions, cross-project context. > [!NOTE] > > Synthesized from [Eric Zakariasson's Cursor 3 feedback thread](https://x.com/ericzakariasson) — 431 community responses, April 2026. ## Workflow for studying unfamiliar LLMs When you use an AI IDE to understand an open-weight model rather than just write app code, this order works well: 1. **Read the official report first** * Use it to understand the model family, goals, and top-level architecture. * Treat it as the overview, not the final source of implementation truth. 2. **Inspect the Hugging Face config** * Check layers, hidden size, attention heads, RoPE settings, MoE options, KV heads, and other structural fields. * Config files often expose details that summaries skip. 3. **Read the reference implementation** * If the model is supported by `transformers` or an official repo, inspect the real code path. * Working code is usually the most reliable way to confirm module order and implementation details. 4. **Only then summarize or diagram it** * Once you have your own mental model, use the AI IDE to generate diagrams, compare related architectures, or explain local modules. ### Best fit * Open-weight models * Models with public configs and reference implementations * Less useful for closed models that only expose product-level descriptions ### Reference * [Sebastian Raschka: My Workflow for Understanding LLM Architectures](https://magazine.sebastianraschka.com/p/workflow-for-understanding-llms) ## GitHub Copilot: Usage-Based Billing (June 2026) Starting **June 1, 2026**, GitHub Copilot transitions from "premium request units" to **AI Credits** based on token consumption. This reflects Copilot's evolution from a code-completion assistant into an agentic platform running long multi-step coding sessions. ### What stays the same * **Base prices unchanged** — Pro $10/month, Pro+ $39/month, Business $19/user/month, Enterprise $39/user/month * **Code completions and Next Edit suggestions** — Still included, do not consume AI Credits * **Monthly credits equal subscription price** — Pro gets $10 credits, Pro+ gets $39 credits ### What changes * **Premium request units replaced by AI Credits** — Usage calculated by input, output, and cached tokens at each model's API rate * **No fallback to cheaper models** — Previously, exhausted PRUs could fall back. Now credits spent = credits spent, no downgrade path * **Copilot Code Review** — Consumes both AI Credits **and** GitHub Actions minutes * **Pooled credits for organizations** — Business/Enterprise credits can pool across the team, reducing stranded capacity ### Transition buffer (June–August 2026) | Plan | Normal monthly credits | Transitional credits (June–Aug) | | - | - | - | | Business | \$19/user | \$30/user | | Enterprise | \$39/user | \$70/user | ### Practical implications * **Light users** — Nearly unaffected; completions stay free * **Heavy Agent users** — Monitor bills after June; long autonomous sessions consume credits fast * **Annual subscribers** — Stay on old PRU model until plan expires, then transition to monthly with credits * **Preview billing** — Early May: preview bill page shows projected costs before the switch > [!TIP] > > If you run long Copilot Agent sessions, check the preview billing tool in early May to estimate your monthly credit burn. Agent tasks that iterate across entire repos will consume significantly more tokens than simple chat completions. > [!NOTE] > > * [GitHub Blog: Copilot moves to usage-based billing](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/) > * [Twitter @dotey summary](https://x.com/dotey/status/2048849524739977672) ## Coding Agent Safety: How OpenAI Controls Codex When coding agents can read/write repos, run commands, and call development tools, you need both efficiency and control. OpenAI's answer is a **four-layer framework** for Codex: sandbox + approval + network policy + identity governance. The guiding principle: **zero friction for low-risk daily operations, mandatory human review for high-risk ones**. ### 1. Sandbox + Approval * **Sandbox** defines technical execution boundaries: where to write, whether to allow networking, which paths are read-only * **Approval policy** defines when to stop and ask a human — typically triggered when crossing sandbox boundaries * **Auto-review mode**: A separate sub-agent reviews Codex's pending actions and context, auto-approving low-risk requests and only interrupting the user when risk escalates. This is "AI reviewing AI" — turning approval itself into an intelligent layer ### 2. Network Access Default-deny, explicit-allow model: * **Allow** known compliant destinations * **Block** explicitly unwanted domains (e.g., pastebin.com — typical data exfiltration channel) * **Require approval** for unknown domains Implemented via proxy — no open outbound permissions for the agent. ### 3. Identity & Credentials * OAuth credentials for CLI and MCP are **forced into OS keyring** (macOS Keychain) * Authentication via **ChatGPT login** — no bypass * Locked to **specific enterprise workspace UUID** Effect: All Codex activity is bound to workspace-level governance and automatically falls into ChatGPT compliance logging. ### 4. Command Rules Commands are classified by semantic risk level: * **Read-only commands** (`gh pr view`, `kubectl get`) → auto-approve * **Dangerous commands** → explicit block or require approval This "semantic classification" approach means the agent feels almost no friction during normal engineering workflows, while retaining a hard brake for dangerous operations. ### 5. Configuration Distribution Three-layer distribution ensures org-wide consistency: * **Cloud managed requirements** + **macOS managed preferences** + **local requirements file** * `requirements` are admin-mandatory — users cannot override ### Agent-Native Telemetry Traditional EDR and audit logs tell you "what happened" — but for AI agents, security teams need **"why"**: * User's original prompt * Agent's reasoning path * Approval decisions * Tool call chains * MCP server usage * Network proxy allow/deny events Codex exports these via **OpenTelemetry**, enabling reconstruction of the full causal chain: "user said → agent planned → system approved → actually happened → network layer blocked or not". OpenAI's own practice: When EDR flags anomalous Codex behavior, their **AI safety triage agent** pulls Codex telemetry and auto-classifies into three categories: 1. Expected agent behavior 2. Benign mistake 3. genuinely needs escalation Only category 3 gets pushed to humans. This is a **"agent behavior interpreted by another agent"** security ops paradigm. > [!TIP] > > If you deploy coding agents in your org, consider implementing a similar framework: sandbox boundaries, command-level risk classification, and telemetry that captures the "why" not just the "what". The auto-review pattern (AI reviewing AI) is especially useful for reducing approval noise. > [!NOTE] > > * [OpenAI: Running Codex Safely](https://openai.com/index/running-codex-safely/) — official blog post > * [Twitter @dotey Chinese summary](https://x.com/dotey/status/2048849524739977672) — detailed translation of the four-layer framework ## Trae Free AI IDE, continuously updated. # Pyenv Source: https://base.bangwu.me/apps/Pyenv Pyenv is a Python version manager for installing and switching between multiple Python versions on the same system with per-project settings. # [Pyenv](https://github.com/pyenv/pyenv?tab=readme-ov-file#windows) Pyenv is a Python version manager that makes it easy to install and switch between multiple Python versions on the same machine. ## Features * 📦 Manage multiple Python versions * 🔄 Switch versions quickly * 🎯 Pin a specific version for each project * 🌐 Support virtual environments * 🪟 Cross-platform support for Windows, Linux, and macOS ## Installation ### Windows Use [pyenv-win](https://github.com/pyenv-win/pyenv-win): ```powershell theme={"theme":{"light":"github-light","dark":"github-dark"}} # 使用 pip Installation pip install pyenv-win --target $HOME/.pyenv # 或使用 Git git clone https://github.com/pyenv-win/pyenv-win.git $HOME/.pyenv ``` Add environment variables: ```powershell theme={"theme":{"light":"github-light","dark":"github-dark"}} [System.Environment]::SetEnvironmentVariable('PYENV',$env:USERPROFILE + "\.pyenv\pyenv-win\","User") [System.Environment]::SetEnvironmentVariable('PYENV_ROOT',$env:USERPROFILE + "\.pyenv\pyenv-win\","User") [System.Environment]::SetEnvironmentVariable('PYENV_HOME',$env:USERPROFILE + "\.pyenv\pyenv-win\","User") ``` ### Linux/macOS ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 使用官方Installationscripts curl https://pyenv.run | bash # 或使用 Homebrew (Mac) brew install pyenv ``` Configure your shell by adding the following to `~/.bashrc` or `~/.zshrc`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init --path)" eval "$(pyenv init -)" ``` ## Basic usage ### Show installable versions ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 列出所有可用versions pyenv install --list # search for特定versions pyenv install --list | grep 3.11 ``` ### Install Python versions ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Installation特定versions pyenv install 3.11.5 # Installation最新versions pyenv install 3.11 # ViewInstallation进度 pyenv install -v 3.11.5 ``` ### Show installed versions ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 列出所有已Installationversions pyenv versions # View当前versions pyenv version ``` ### Switch Python versions ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 全局切换(所有 shell) pyenv global 3.11.5 # 本地切换(当前目录) pyenv local 3.10.12 # 临时切换(当前 shell) pyenv shell 3.9.18 ``` ### Uninstall a version ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} pyenv uninstall 3.9.18 ``` ## Advanced usage ### Set a version for a project ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # in项目目录下 cd my_project pyenv local 3.11.5 # 会创建 .python-version file cat .python-version # 3.11.5 ``` ### Virtual environments Use it together with `pyenv-virtualenv`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Installation pyenv-virtualenv git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv # 创建虚拟环境 pyenv virtualenv 3.11.5 my-project-env # 激活虚拟环境 pyenv activate my-project-env # 停用虚拟环境 pyenv deactivate # Removed虚拟环境 pyenv virtualenv-delete my-project-env # 为项目自动激活虚拟环境 cd my_project pyenv local my-project-env ``` ### Show where the current version comes from ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # View当前versions及来源 pyenv version # 3.11.5 (set by /home/user/project/.python-version) ``` ### Refresh shims ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 重新generates shims(Installation新Package后) pyenv rehash ``` ## Configuration files ### Global configuration ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 设置全局versions pyenv global 3.11.5 # Configuration File位置 ~/.pyenv/version ``` ### Project configuration ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 项目目录下's .python-version file echo "3.11.5" > .python-version ``` ### Shell configuration ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 临时设置 export PYENV_VERSION=3.11.5 ``` ## FAQ ### Installation failed **Missing Linux dependencies:** ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Ubuntu/Debian sudo apt update sudo apt install -y make built-essential libssl-dev zlib1g-dev \ libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \ libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev \ libffi-dev liblzma-dev # CentOS/RHEL sudo yum install gcc zlib-devel bzip2 bzip2-devel readline-devel \ sqlite sqlite-devel openssl-devel tk-devel libffi-devel xz-devel ``` ### Version switching does not take effect ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 确保 pyenv in PATH 中 which pyenv # 重新加载Configuration source ~/.bashrc # 或 ~/.zshrc # 重新generates shims pyenv rehash ``` ### Windows path issues Make sure the environment variables are configured correctly, then restart the terminal. ## Comparison with other tools | Tool | Characteristics | Suitable scenarios | | - | - | - | | **pyenv** | Multi-version management | Frequent switching between Python versions | | **venv** | Built-in virtual environments | Simple project isolation | | **conda** | Scientific computing environment | Data science and machine learning | | **poetry** | Dependency management + packaging | Modern Python projects | | **pipenv** | Pipfile-based management | Dependency locking | ## Best practices 1. **Set a local version for every project** to avoid global version conflicts. 2. **Use virtual environments** together with `pyenv-virtualenv`. 3. **Commit `.python-version`** when the team should use the same version. 4. **Update pyenv regularly** to get support for new versions. 5. **Record dependencies** with `requirements.txt` or `Pipfile`. ## Quick reference ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Common Commands速查 pyenv install --list # View可Installationversions pyenv install 3.11.5 # Installationversions pyenv versions # View已Installationversions pyenv global 3.11.5 # 全局切换 pyenv local 3.11.5 # 项目切换 pyenv uninstall 3.11.5 # 卸载versions pyenv rehash # 刷新 shims pyenv which python # View python 路径 ``` ## References * [Pyenv GitHub](https://github.com/pyenv/pyenv) * [Pyenv-win GitHub](https://github.com/pyenv-win/pyenv-win) * [Official Docs](https://github.com/pyenv/pyenv/wiki) * [FAQ](https://github.com/pyenv/pyenv/wiki/Common-build-problems) # Rclone Source: https://base.bangwu.me/apps/Rclone Rclone is a command-line tool for managing files on 40+ cloud storage services with a unified interface, supporting rsync-like sync, copy, and mount. # Rclone Rclone is a command-line tool for managing cloud storage files. It provides a unified interface for many providers, including object storage, enterprise and consumer file services, and standard transfer protocols. It follows Unix-style conventions and works well with common shell tools such as `rsync`, `cp`, `mv`, `mount`, `ls`, `ncdu`, `tree`, `rm`, and `cat`. It is especially useful for tasks like synchronizing objects in a [CDN workflow](../env/CDN). ## Installation Official download page: [https://rclone.org/downloads/](https://rclone.org/downloads/) Follow the official installation guide. On Windows, adding Rclone to your `PATH` makes it much easier to use. ## Basic commands | Command | Description | | - | - | | rclone config | Add, remove, or manage remotes | | rclone config file | Show the path to the config file | | rclone config show | Display the current config file contents | ```shell theme={"theme":{"light":"github-light","dark":"github-dark"}} rclone [功能Option] [parameters] [parameters] ``` ## Common operations | Command | Description | | - | - | | rclone copy | Copy files | | rclone move | Move files; add `--delete-empty-src-dirs` if you also want to remove empty source directories afterward | | rclone sync | Sync the source directory to the target directory; only the target side is modified | | rclone size | Show the total size used by a remote path | | rclone delete | Delete file contents under a path | | rclone purge | Delete a path and everything inside it | | rclone mkdir | Create a directory | | rclone rmdir | Remove a directory | | rclone rmdirs | Remove empty directories in the given path; with `--leave-root`, the root directory is preserved | | rclone check | Verify whether source and target data match | | rclone ls | List all files with size and path | | rclone lsl | Same as above, but also shows upload time | | rclone lsd | List directories | | rclone lsf | List both directories and files | ## Useful flags | Command | Description | | - | - | | -n = –dry-run | Dry run mode; preview what Rclone would do | | -P = –progress | Show live transfer progress, refreshed every 500 ms instead of once per minute | | –cache-chunk-size 5M | Chunk size; larger values usually upload faster but use more memory | | –onedrive-chunk-size 100M | Increase OneDrive upload speed on high-bandwidth servers | | –drive-chunk-size 64M | Increase Google Drive upload speed on high-bandwidth servers | | –cache-chunk-total-size SizeSuffix | Total local disk space that chunks may use | | –transfers=N | Number of parallel file transfers; default is 4 | | –config string | Specify a custom config file path | | –ignore-errors | Continue when errors occur | | –size-only | Validate only by file size, not by hash | | –drive-server-side-across-configs | Use server-side transfer across configs when supported | ## Logs Rclone supports four log levels: `ERROR`, `NOTICE`, `INFO`, and `DEBUG`. By default, Rclone emits `ERROR` and `NOTICE` logs. | Command | Description | | - | - | | -q | Output only `ERROR` messages | | -v | Output `ERROR`, `NOTICE`, and `INFO` messages | | -vv | Output `ERROR`, `NOTICE`, `INFO`, and `DEBUG` messages | | –log-level LEVEL | Set the log level explicitly | ## Filtering | Command | Description | | - | - | | –exclude | Exclude a file or directory | | –include | Include a file or directory | | –filter | Use filter rules; rules beginning with `+` include, and rules beginning with `-` exclude | ## Environment variables Almost every `rclone` option can also be configured through environment variables. The variable name is derived from the long option name: remove the `--` prefix, replace `-` with `_`, convert to uppercase, and add the `RCLONE_` prefix. Environment variables have lower priority than command-line flags. For example, if you set `RCLONE_MIN_SIZE=50` but run `rclone` with `--min-size 100`, the command-line value wins. ## Common environment variables | Command | Description | | - | - | | RCLONE\_CONFIG | Custom config file path | | RCLONE\_CONFIG\_PASS | Password used to decrypt an encrypted config file | | RCLONE\_RETRIES | Number of retries after upload failure; default is 3 | | RCLONE\_RETRIES\_SLEEP | Delay between retries; suffixes `s`, `m`, and `h` mean seconds, minutes, and hours | | CLONE\_TRANSFERS | Number of parallel uploads | | RCLONE\_CACHE\_CHUNK\_SIZE | Chunk size | | RCLONE\_CACHE\_CHUNK\_TOTAL\_SIZE | Total local space available for chunks | | RCLONE\_IGNORE\_ERRORS=true | Skip errors | # Rye Source: https://base.bangwu.me/apps/Rye Rye is a next-gen Python package manager and virtual environment tool, compared with pyenv, pipenv, uv, and pdm for dependency management. [Python package managers and virtual environments——V2EX](https://www.v2ex.com/t/1032069) There are far too many Python environment management tools. ![python-tools](https://cdn.bangwu.top/img/202503131258281.webp) > Image source: [https://alpopkes.com/posts/python/packaging\_tools/](https://alpopkes.com/posts/python/packaging_tools/) ## Python version management `pyenv`, `pipenv` ## Python package management `pip`, `uv`, `pdm` ## Rye configuration ### VS Code cannot detect the interpreter path ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "python.defaultInterpreterPath": ".\\.venv\\Scripts\\python.exe" } ``` ```cmd theme={"theme":{"light":"github-light","dark":"github-dark"}} rye config --set proxy.http=http://127.0.0.1:7890 rye config --set proxy.https=http://127.0.0.1:7890 ``` Enable global shims: ```cmd theme={"theme":{"light":"github-light","dark":"github-dark"}} rye config --set-bool behavior.global-python=true ``` Configure a PyPI mirror in [config.toml](https://rye.astral.sh/guide/config/#config-file): ```toml theme={"theme":{"light":"github-light","dark":"github-dark"}} # Rye config.toml [[sources]] name = "default" url = "https://pypi.org/simple/" ``` Set up Jupyter: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} rye add ipykernel ``` ### My configuration ```toml theme={"theme":{"light":"github-light","dark":"github-dark"}} [default] toolchain = "cpython@3.13.2" license = "MIT" author = "bangwu " [proxy] https = "http://127.0.0.1:10808" http = "http://127.0.0.1:10808" [behavior] global-python = true autosync = true use-uv = true [[sources]] name = "default" url = "https://pypi.tuna.tsinghua.edu.cn/simple/" ``` ## Start a project ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} rye pin 3.x rye init // 或者 rye init -p cpython@3.x [project name] rye sync rye add [package] ``` # Scoop Source: https://base.bangwu.me/apps/Scoop Scoop is a Windows command-line package manager like Homebrew, covering installation, aria2 acceleration, bucket management, and proxy setup. # Scoop - Windows Homebrew ## Installation ## Configuration Enable `aria2`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} scoop install aria2 scoop config aria2-warning-enabled false ``` Useful things to configure include buckets and proxy settings. ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} ❯ scoop config last_update : 2025-03-26T10:11:34.7723777+08:00 gh_token : ***** global_path : C:\GlobalScoopApps root_path : C:\Scoop proxy : 127.0.0.1:10808 scoop_repo : https://github.com/ScoopInstaller/Scoop scoop_branch : master aria2-warning-enabled : False ``` ### Backup ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} scoop export > app.json scoop import > app.json # backs up buckets and apps,excluding config ``` ## Common apps ## Apps not found via Scoop * [Leigod Accelerator](https://www.leigod.com/) * [Dida365](https://dida365.com/) * [Cisco Anyconnect](https://www.cisco.com/c/zh_cn/support/security/anyconnect-secure-mobility-client-v4-x/model.html#~tab-downloads) * [Pure Live](https://github.com/liuchuancong/pure_live) * [Huorong](https://huorong.cn) * [WeChat Input Method](https://z.weixin.qq.com) * [Jianguoyun](https://www.jianguoyun.com) # ShareX Source: https://base.bangwu.me/apps/ShareX ShareX is an open-source screenshot and recording tool with automatic WebP compression via ffmpeg, covering action configuration and workflow. # ShareX ShareX is a very powerful open-source screenshot and sharing tool with lots of customization options. What I like most is that it can automatically compress screenshots to WebP format, which reduces image size significantly. Software structure: ![](https://cdn.bangwu.top/img/202312181628293.webp) Download page: [https://github.com/ShareX/ShareX/releases/tag/v16.0.1](https://github.com/ShareX/ShareX/releases/tag/v16.0.1) I recommend downloading the portable version because it includes `ffmpeg` and can be used for compression directly. Then create a new action in the ShareX action settings: ![chrome\_1712151713](https://cdn.bangwu.top/img/chrome_1712151713.webp) * name: anything * file path: the installation path of `ffmpeg`, pointing directly to the executable * parameters: `-i "$input" -q 75 "$output"` where `-q 75` means 75% quality compression * output file extension: webp * extension filter: png * enable the options below for **hide window** and **delete input file** Then enable `execute action` in the screenshot task settings. ![chrome\_1712151800](https://cdn.bangwu.top/img/chrome_1712151800.webp) # Typora Source: https://base.bangwu.me/apps/Typora Typora is a WYSIWYG Markdown editor that renders as you type, with support for tables, code blocks, and LaTeX formulas for document writing. When writing Markdown documents, coding raw syntax can be tedious. Why not write in a rendered view like Word? That's where rich text editors come in. Among all Markdown editors, Typora is the most acclaimed. ## Installation > [tab] Cloud Drive > > Link: [https://www.123pan.com/s/HQeA-UX1Sh](https://www.123pan.com/s/HQeA-UX1Sh) > > Download any version's `.7z` file, extract and apply the patch. But if you can afford it, please support the official version. > [tab] Official > > Official site: [https://typora.io/](https://typora.io/) # Warp Source: https://base.bangwu.me/apps/Warp Warp is a Rust-based terminal emulator now open-sourced under AGPL, featuring AI command search, collaborative workflows, and an agent-centric coding platform. # Warp Warp is a modern terminal emulator built in Rust, now open-sourced under **AGPL license** (April 2026). It combines a terminal with AI-powered command search, block-based output, and an agent-centric coding collaboration platform called **Oz**. ![GitHub Repo stars](https://img.shields.io/github/stars/warpdotdev/warp) ## Key Features * **Block-based output** — Commands and their output are grouped into editable blocks, not raw text streams * **AI command search** — Describe what you want in natural language, Warp suggests the right command * **Command history with context** — Search past commands by what they did, not just the raw string * **Collaborative workflows** — Share command blocks and sessions with teammates * **Oz agent platform** — Cloud-based agent orchestration where AI handles coding, planning, and testing while humans focus on direction and review ## Installation ### macOS ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} brew install --cask warp ``` ### Linux Download from [Warp releases](https://github.com/warpdotdev/warp/releases) or: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # From the official site curl -fsSL https://app.warp.dev/get | sh ``` > [!TIP] > > Warp is now open-source (AGPL). You can build from source at [github.com/warpdotdev/warp](https://github.com/warpdotdev/warp). OpenAI is the founding sponsor of the open-source release; the Oz workflow uses GPT-5.5. ## Warp vs Traditional Terminals | Feature | Warp | iTerm2 / Alacritty / Ghostty | | - | - | - | | Output display | Editable blocks | Raw text stream | | Command search | AI-powered natural language | Text regex search | | Collaboration | Share blocks, sessions | No built-in sharing | | Agent integration | Oz platform (cloud) | None | | Rendering | Rust GPU-accelerated | Rust (Alacritty/Ghostty) / Swift (iTerm2) | | License | AGPL (open-source) | Various | > [!NOTE] > > If you prefer a minimalist, GPU-accelerated terminal without AI features, [Ghostty](https://ghostty.org) and [Alacritty](https://alacritty.org) are strong alternatives. Ghostty is also Rust-based and offers fast rendering with a simpler feature set. ## Oz Agent Platform Warp's agent-centric workflow uses **Oz** — a cloud orchestration platform where: 1. **Agent handles heavy work** — coding, planning, testing, running commands 2. **Human focuses on direction** — reviewing, validating, steering priorities 3. **Blocks are shared** — both agent and human see the same terminal session This model treats the terminal as a shared workspace rather than a solo tool. ## Other Terminal Emulators Worth Knowing * **Ghostty** — Rust-based, fast, minimalist. Created by Mitchell Hashimoto (Vagrant/Terraform). Recently announced leaving GitHub due to reliability concerns. * **Alacritty** — Rust-based, GPU-accelerated, minimal config. No AI features. * **iTerm2** — macOS-native, feature-rich, long-established. Swift-based. ## References * [Warp GitHub](https://github.com/warpdotdev/warp) * [Warp Official Site](https://www.warp.dev/) * [Warp open-source announcement](https://x.com/warpdotdev) — April 2026, AGPL license # Xizhi Source: https://base.bangwu.me/apps/Xizhi Notification push services including Server酱 for WeChat alerts, with API setup, Python requests integration, and Markdown message delivery. # Message push services Message push services deliver notifications, alerts, and other information to different devices in real time. They are commonly used for monitoring alerts, scheduled reminders, and system notifications. ## ServerChan [ServerChan](https://sct.ftqq.com/) is a free WeChat notification service. ### Features * 📱 Pushes to WeChat * 🆓 Generous free quota * 🔧 Simple to use * 📊 Supports Markdown ### Usage 1. Visit the [ServerChan website](https://sct.ftqq.com/) and sign in. 2. Bind your WeChat account by scanning the QR code. 3. Get your `SendKey`. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import requests def send_wechat(title, content): sendkey = "YOUR_SENDKEY" url = f"https://sctapi.ftqq.com/{sendkey}.send" data = { "title": title, "desp": content } response = requests.post(url, data=data) return response.json() # 使用 send_wechat("Testingtitle", "这isTesting内容\nsupports **Markdown**") ``` ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # curl 方式 curl -X POST "https://sctapi.ftqq.com/YOUR_SENDKEY.send" \ -d "title=Testingtitle" \ -d "desp=Testing内容" ``` ### Use cases * Server monitoring alerts * Scheduled task notifications * Spider completion reminders * CI/CD build notifications ## Bark [Bark](https://github.com/Finb/Bark) is an open-source iOS push notification app. ### Features * 📱 iOS only * 🔓 Free and open-source * 🔔 Supports custom sounds * 🎨 Supports icons and grouping * 🔐 End-to-end encryption ### Installation Search for Bark in the App Store and install it. ### Usage After getting the push address: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import requests def send_bark(title, content): url = "https://api.day.app/YOUR_KEY/" data = { "title": title, "body": content, "sound": "alarm", # 铃声 "icon": "https://example.com/icon.png", # Icons "group": "test" # Grouping } response = requests.post(url, json=data) return response.json() # 使用 send_bark("Testingtitle", "这isTesting内容") ``` ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # GET 方式 curl "https://api.day.app/YOUR_KEY/title/内容" # POST 方式 curl -X POST "https://api.day.app/YOUR_KEY" \ -H "Content-Type: application/json" \ -d '{"title":"title","body":"内容","sound":"alarm"}' ``` ### Advanced features ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # with redirect link send_bark("点击跳转", "内容", url="https://example.com") # auto-copy content send_bark("自动复制", "需要复制's 内容", automaticallyCopy=1) # 时效性Notification send_bark("重要Notification", "内容", level="timeSensitive") ``` ## [Telegram Bot](https://core.telegram.org/bots) The Telegram Bot API is a powerful way to send notifications. ### Create a bot 1. Search for `@BotFather` in Telegram. 2. Send `/newbot` to create a bot. 3. Get the bot token. 4. Send `/getid` to `@userinfobot` to get your chat ID. ### Usage ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import requests class TelegramBot: def __init__(self, token, chat_id): self.token = token self.chat_id = chat_id self.api_url = f"https://api.telegram.org/bot{token}" def send_message(self, text, parse_mode="Markdown"): url = f"{self.api_url}/sendMessage" data = { "chat_id": self.chat_id, "text": text, "parse_mode": parse_mode } return requests.post(url, json=data).json() def send_photo(self, photo_url, caption=""): url = f"{self.api_url}/sendPhoto" data = { "chat_id": self.chat_id, "photo": photo_url, "caption": caption } return requests.post(url, json=data).json() def send_document(self, file_path): url = f"{self.api_url}/sendDocument" with open(file_path, 'rb') as f: files = {'document': f} data = {'chat_id': self.chat_id} return requests.post(url, data=data, files=files).json() # 使用 bot = TelegramBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID") bot.send_message("**粗体** _斜体_ `代码`") ``` ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # curl 方式 curl -X POST "https://api.telegram.org/botYOUR_BOT_TOKEN/sendMessage" \ -d "chat_id=YOUR_CHAT_ID" \ -d "text=Hello World" ``` ### Advanced features ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # send带Button's Message def send_with_buttons(bot, text, buttons): url = f"{bot.api_url}/sendMessage" keyboard = { "inline_keyboard": [ [{"text": btn["text"], "url": btn["url"]} for btn in row] for row in buttons ] } data = { "chat_id": bot.chat_id, "text": text, "reply_markup": keyboard } return requests.post(url, json=data).json() # 使用 buttons = [ [{"text": "Visit网站", "url": "https://example.com"}], [{"text": "GitHub", "url": "https://github.com"}] ] send_with_buttons(bot, "选择aOperation:", buttons) ``` ## [Xizhi](https://xz.qqoq.net) Xizhi is an aggregated push platform that supports multiple notification channels. ### Features * 🔗 Aggregates multiple push methods * 📱 Supports iOS, Android, and Web * 🆓 Free to use * 🔔 Supports different message types ### Supported push methods * iOS/Android app * WeCom * DingTalk * Feishu * Email * Webhook ### Usage 1. Register and create an app. 2. Get the push URL. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import requests def send_xizhi(title, content, url=""): api_url = "YOUR_XIZHI_URL" data = { "title": title, "content": content, "url": url } response = requests.post(api_url, json=data) return response.json() # 使用 send_xizhi( "Notificationtitle", "Notification内容", "https://example.com" ) ``` ## Comparison | Service | Platform | Free | Strength | Suitable scenarios | | - | - | - | - | - | | **ServerChan** | WeChat | ✅ | Simple and convenient | Domestic users, WeChat notifications | | **Bark** | iOS | ✅ | Open-source and privacy-friendly | iOS users | | **Telegram** | Cross-platform | ✅ | Very powerful | International users who can access Telegram | | **Xizhi** | Cross-platform | ✅ | Multi-channel aggregation | Enterprise or multi-channel use | ## Comprehensive example ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class NotificationManager: """统一's MessagePush管理器""" def __init__(self): self.server_chan_key = "YOUR_SENDKEY" self.bark_url = "https://api.day.app/YOUR_KEY" self.telegram_bot = TelegramBot("TOKEN", "CHAT_ID") def send(self, title, content, channels=None): """Send to Multiple Channels""" if channels is None: channels = ['all'] results = {} if 'all' in channels or 'wechat' in channels: results['wechat'] = self._send_wechat(title, content) if 'all' in channels or 'bark' in channels: results['bark'] = self._send_bark(title, content) if 'all' in channels or 'telegram' in channels: results['telegram'] = self._send_telegram(title, content) return results def _send_wechat(self, title, content): url = f"https://sctapi.ftqq.com/{self.server_chan_key}.send" return requests.post(url, data={"title": title, "desp": content}) def _send_bark(self, title, content): return requests.post(self.bark_url, json={"title": title, "body": content}) def _send_telegram(self, title, content): return self.telegram_bot.send_message(f"*{title}*\n\n{content}") # 使用 notifier = NotificationManager() notifier.send("系统告警", "CPU 使用率超过 90%", channels=['wechat', 'telegram']) ``` ## Best practices 1. **Choose the right service** for your audience and scenario. 2. **Handle exceptions** because push requests can fail. 3. **Respect rate limits** to avoid notification spam. 4. **Avoid sending sensitive information** whenever possible. 5. **Use multi-channel backup** for important alerts. 6. **Separate regular notifications from urgent alerts**. ## Use cases * 📊 **Monitoring alerts**: servers and application performance * ⏰ **Scheduled reminders**: daily reports and timed tasks * 🔔 **Event notifications**: user registration or order changes * 🐛 **Error reporting**: exceptions and bug alerts * 📈 **Data reports**: daily or weekly summaries * 🤖 **Automation notifications**: CI/CD and spider completion ## References * [ServerChan documentation](https://sct.ftqq.com/sendkey) * [Bark GitHub](https://github.com/Finb/Bark) * [Telegram Bot API](https://core.telegram.org/bots/api) * [Xizhi website](https://xz.qqoq.net) # baoyu-design Source: https://base.bangwu.me/apps/baoyu-design Run a Claude Design-style local agent skill for UI mockups, prototypes, design systems, Figma imports, and self-contained HTML design artifacts. # baoyu-design [baoyu-design](https://github.com/JimLiu/baoyu-design) packages a Claude Design-style workflow as a local Agent Skill. Instead of uploading prompts to a design website, you let a file-capable coding agent such as Cursor, Claude Code, or Codex generate design artifacts inside your own project. The durable idea is not "another AI design demo". It is a pattern for turning design work into an agent-native local workflow: * the agent reads a reusable design skill * output lands in `designs//` * deliverables are self-contained HTML * preview happens on `localhost` * you iterate visually by pointing at the preview and asking for changes ## When it helps Use it when you want fast visual artifacts without leaving your repo: * high-fidelity UI mockups * interactive prototypes * landing pages and dashboards * mobile or desktop app concepts * slide decks and visual explainers * design-system previews and component showcases It fits early product exploration especially well. The artifact is plain HTML, so you can version it, fork it, attach it to an issue, or hand it to another agent for implementation. ## Install The README recommends the `skills` CLI: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npx skills add JimLiu/baoyu-design ``` Useful variants: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npx skills add JimLiu/baoyu-design -g npx skills add JimLiu/baoyu-design --agent claude-code npx skills add JimLiu/baoyu-design --agent cursor npx skills add JimLiu/baoyu-design --agent codex npx skills add JimLiu/baoyu-design --list ``` For Claude Code, the install target is typically `.claude/skills/`. For Cursor and Codex-style agents, it is typically `.agents/skills/`. ## Workflow A practical flow looks like this: 1. Install the skill in the project. 2. Ask the agent for one specific design task. 3. Provide real context: screenshots, product copy, an existing repo, or a Figma `.fig` export. 4. Let the agent generate HTML under `designs/`. 5. Open the local preview and point to elements that need changes. 6. Commit useful artifacts or hand them off to frontend implementation. The second-pass loop is the important part. You do not need to rewrite a long prompt for every tweak. You can say "make this card denser" or "move this CTA above the fold" while the agent edits the source behind the preview. ## Design systems and Figma imports The skill can work beyond one-off mockups. It supports design-system workflows such as: * creating a local design system * selecting a design system when starting a new project * previewing components as self-contained HTML * importing a Figma `.fig` file offline * extracting components, variables, assets, and token CSS from imported design context This is useful when you want the agent to respect an existing visual language instead of inventing every screen from scratch. ## What to watch Treat the output as a design artifact, not production code by default. * Review accessibility, responsive behavior, and interaction states manually. * Keep imported brand assets and fonts under the right license. * Prefer small scoped design requests over "design the whole app" prompts. * Save good outputs, but do not blindly ship generated HTML as application code. ## References * [Folo source: baoyu-design skill update](https://x.com/dotey/status/2064959133535658144) * [JimLiu/baoyu-design](https://github.com/JimLiu/baoyu-design) # iTab Source: https://base.bangwu.me/apps/iTab iTab is a browser new-tab page service with visual navigation cards organized by workflow, available as a Chrome/Edge extension and web app. [iTab](https://www.itab.link/) is a browser start page service with extensions and web access, supporting both PC and mobile — designed to free up your browser bookmarks. ![iTab](https://cdn.bangwu.top/img/chrome_1710603394.webp) # Software Tools Source: https://base.bangwu.me/apps/index Curated software recommendations with configuration guides covering API tools, screen sharing, AI editors, package managers, and screenshot tools. Inspired by [pseudoyu](https://tools.pseudoyu.com/), I share the software I use daily — desktop apps, browser extensions, and more — with detailed configurations and purposes. > [card] [Apifox](/apps/Apifox) > > All-in-one API design, development, and testing platform. > [card] [Barrier](/apps/Barrier) > > Cross-device keyboard/mouse sharing. > [card] [CherryStudio](/apps/CherryStudio) > > AI client with theme customization. > [card] [Cursor](/apps/Cursor) > > AI-powered code editor. > [card] [Browser Harness](/apps/BrowserHarness) > > Thin browser control layer for coding agents. > [card] [baoyu-design](/apps/baoyu-design) > > Local Agent Skill for UI mockups and design systems. > [card] [Pyenv](/apps/Pyenv) > > Python version manager. > [card] [Rclone](/apps/Rclone) > > Cloud storage sync and file management. > [card] [Rye](/apps/Rye) > > Next-gen Python package manager. > [card] [Scoop](/apps/Scoop) > > Windows command-line package manager. > [card] [ShareX](/apps/ShareX) > > Open-source screenshot tool with auto-compression. > [card] [Typora](/apps/Typora) > > Recommended Markdown editor. > [card] [Xizhi](/apps/Xizhi) > > Multi-channel notification push service. > [card] [iTab](/apps/iTab) > > Browser start page service. > [card] [Starship](/apps/starship) > > Cross-shell terminal prompt customization. > [card] [Warp](/apps/Warp) > > Rust-based terminal with AI command search, now open-source (AGPL). > [card] [WeChat Reading](/apps/weread) > > WeChat Reading notes and workflows. # Starship Source: https://base.bangwu.me/apps/starship Starship is a cross-shell terminal prompt tool supporting PowerShell, Bash, and Zsh, with Scoop installation and profile configuration guide. # Command line prompt tools ## oh my zsh ## oh my posh PowerShell completion is the only part that still feels awkward to use. ## [starship](https://starship.rs/guide/) ![starship-demo](https://raw.gitmirror.com/starship/starship/master/media/demo.gif) ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} scoop install starship starship config command_timeout 3600 //解决超时Issue https://github.com/starship/starship/issues/5985 ``` ### Configure PowerShell Run `$PROFILE` in PowerShell to find the config file path, usually `C:\Users\\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1`, and add the following line: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} Invoke-Expression (&starship init powershell) ``` I use the [Bracketed Segments](https://starship.rs/zh-CN/presets/bracketed-segments) preset. You can browse other themes on the [Starship presets](https://starship.rs/presets/) page. Some presets require a [Nerd Font](https://www.nerdfonts.com/). ### Configure `cmd` Starship uses [clink](https://chrisant996.github.io/clink/) to configure `cmd`. > \[!note] > If you install clink with Scoop, command highlighting may not work. The likely reason is that the Scoop package does not include the `Enhanced default settings` feature, which is what enables syntax highlighting. If you need it, downloading clink directly from the [GitHub Releases](https://github.com/chrisant996/clink/releases) page is the safer choice. ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} code %LocalAppData%\clink\starship.lua 写入 load(io.popen('starship init cmd'):read("*a"))() ``` ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} clink autorun install clink set prompt.transient always ``` # WeChat Reading Source: https://base.bangwu.me/apps/weread WeChat Reading's official AI Skill turns your reading history into data you can query, analyze, and export — connecting your bookshelf to AI coding agents and personal knowledge management. # WeChat Reading WeChat Reading (微信读书) is Tencent's e-reading platform, popular among Chinese readers. In 2026, it launched an official **Skill** that lets AI coding agents access your reading data: bookshelf, notes, highlights, reading time, and preference analysis. ## What the Skill unlocks Instead of waiting for an annual reading report, you can ask an AI agent to analyze your reading history on demand: * **Reading reports**: Generate personalized analysis of reading time distribution, genre preferences, author patterns, and weekly/monthly rhythms. * **Book reviews**: Pull all your highlights and notes from a finished book, and generate a structured review. * **Knowledge cards**: Extract key ideas from your highlights and format them as shareable cards with original quotes. * **Obsidian export**: Convert a book's highlights and thoughts into an Obsidian-formatted note with frontmatter, tags, and chapter organization. * **Bookshelf Q\&A**: Ask questions like "What should I read next based on my history?" or "What themes have I been exploring recently?" ## The pipeline The Skill bridges three tools into a reading-to-knowledge pipeline: ``` 微信读书 (data source) → AI agent (data pull + processing) → Obsidian (local knowledge base) ``` What this enables: * Auto-generate one note file per book * AI auto-tagging and bidirectional links * Topic-based MOC (Map of Content) index pages * Incremental merge of new highlights into existing notes ## Supported agents The Skill works with: * **Qwen Code** (recommended by most users) * **Claude Code** * **Cursor** * Any agent that supports Skill installation Qwen Code is preferred because it runs in the terminal, can write files and run scripts directly — one command generates an Obsidian note or visualization report. ## Setup 1. Install a supported coding agent (e.g. [Qwen Code](https://qwenlm.github.io/qwen-code-docs/zh/users/overview/)) 2. Get your WeChat Reading API key from [weread.qq.com](https://weread.qq.com/r/weread-skills) Then tell your agent: ``` 下载 https://cdn.weread.qq.com/skills/weread-skills.zip 安装 skill,我的 API 是 wrk-xxxx ``` Optionally add: `帮我配置好环境,记住 API,让我之后不需要再配置` to persist the API key. Once installed, verify with: ``` /skills weread-skills 我最近在读什么? ``` ## Example use cases **Explore reading patterns:** ``` /skills weread-skills 根据我的阅读偏好,推荐接下来读哪些书 ``` **Review highlights from a specific book:** ``` /skills weread-skills 看看我在《空洞的心》里的笔记,随机选 3 条 ``` **Generate a book review:** ``` /skills weread-skills 我刚读完《绿灯》,结合我在这本书里的 35 条笔记,帮我写一篇 500 字的短书评 ``` **Export to Obsidian:** ``` /skills weread-skills 把我在《纷乱的心灵》里的划线和想法,整理成一篇 Obsidian 格式的读书笔记,保存到当前目录 ``` **Find material for writing:** ``` /skills weread-skills 我想写一篇关于「成瘾与自我认知」的文章,从我的笔记里找出所有相关的划线和想法 ``` ## Community Skills Beyond the official Skill, community members have built additional tools. For example, [Yao's Weread Skill](https://github.com/yaojingang/yao-open-skills/tree/main/skills/yao-weread-skill) generates detailed visual reading reports with charts and analytics. Install it with: ``` 帮我安装这个技能:https://github.com/yaojingang/yao-open-skills/tree/main/skills/yao-weread-skill ``` Then run: ``` /skills yao-weread-skill 帮我生成我的阅读报告 ``` ## References * [年度报告不够看?微信读书 Skill 上手体验](https://sspai.com/post/109932) — 少数派 detailed walkthrough * [微信读书 Skill 官方页面](https://weread.qq.com/r/weread-skills) * [Yao's Weread Skill](https://github.com/yaojingang/yao-open-skills/tree/main/skills/yao-weread-skill) — community reading report generator # Go Gin Source: https://base.bangwu.me/backend/Go/gin/index Go Gin is the most popular web framework for Go, covering router setup, GET/POST handlers, JSON responses, and HTTP server startup basics. # Go gin gin is the most widely-used go web Framework ## ginServer ```go theme={"theme":{"light":"github-light","dark":"github-dark"}} router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) router.Run() ``` # Go Source: https://base.bangwu.me/backend/Go/index Go language learning path from a Python background, covering A Tour of Go basics, GoFrame exploration, and Gin + Gorm backend development. ![Golang](https://cdn.bangwu.top/img/Golang.png) # Why Go My first programming language was Python — undeniably convenient and powerful, but lacking in performance. For frequently-used tools and concurrent demands, I eventually chose to learn a high-performance language. Go is friendly for Python learners to pick up, which is why I chose it. > Learning path (for reference only): 1. [A Tour of Go](https://tour.go-zh.org/welcome/1) + [Bilibili video](https://www.bilibili.com/video/BV1ae41157o9) for basics 2. GoFrame trial (abandoned later — too comprehensive) 3. Gin + Gorm to build backend 4. To be continued… > [card] [Gin Framework](/backend/Go/gin/index) > > Go's most popular web framework for building API services. > [card] [Listeners and MPTCP](/backend/Go/mptcp) > > Go 1.24+ servers accept MPTCP by default on Linux. Check and turn it off. # Go listeners and MPTCP Source: https://base.bangwu.me/backend/Go/mptcp Since Go 1.24, net.Listen on Linux opens Multipath TCP listeners by default. Check which services expose MPTCP, turn it off per program or system-wide, and why the kernel patch is still the real fix. # Go listeners and MPTCP Since Go 1.24, `net.ListenConfig` uses **Multipath TCP (MPTCP)** by default on Linux whenever the kernel supports it. `net.Listen("tcp", ...)` goes through `ListenConfig`, so ordinary servers such as `http.ListenAndServe` accept MPTCP connections without any code change. Clients still connect over plain TCP unless you opt in. The default also follows the `go` line in the main module's `go.mod`. A module that declares `go 1.23` or earlier keeps the old behavior (no MPTCP unless requested), even when built with a newer toolchain. MPTCP lets one connection use several network paths, for example Wi-Fi and cellular together. Most clients never use it, so you won't notice it in normal operation. It still adds attack surface: the listening socket goes through a different kernel code path, and a kernel bug in that path is reachable from the network. ## Case study: CVE-2026-98432 > [!NOTE] > > The facts in this section were current as of November 1, 2026. Follow your distribution's advisory for fixed kernel versions. * **The bug.** A race-condition use-after-free in the Linux kernel's IPv4 TCP connection-request handling (`ipv4: free inet_opt and ireq_opt after an RCU grace period`). Red Hat rates it Critical: a remote, unauthenticated attacker can trigger it, it affects any vulnerable kernel with IPv4 TCP enabled, and systems that accept inbound TCP connections are the most directly exposed. * **The exploit.** Anthropic's proof of concept got a root shell on a server with an **MPTCP listener**, with no credentials and no user interaction. A lost race only fails that one handshake and doesn't crash the machine, so the attacker can keep retrying. The PoC needed about 48 minutes to leak a kernel address and another 5 minutes to run a command as root. * **Why Go servers were in the spotlight.** Xray-core's maintainers pointed out that for most of their users, the only programs serving MPTCP on the host are Go proxy servers built with Go 1.24 or later. Xray-core shipped an emergency release that turns MPTCP off by default. Caddy and other Go servers were named in the same discussion. * **The Go team's position.** Upgrade the kernel. The underlying bug is not specific to MPTCP, so systems without MPTCP listeners may be vulnerable to similar attacks. Turning MPTCP off program by program is fragile: one forgotten listener leaves the host exposed. The team decided not to change Go's default for now. ## Durable lessons * **Runtime defaults change your kernel attack surface.** A toolchain upgrade can change which kernel code paths your server exposes, even if you never touch your code. Read the networking and GODEBUG sections of release notes as security notes. * **List listeners by protocol, not just by port.** `ss -lnt` shows a port as listening. It doesn't show whether that port also accepts MPTCP. * **App-level switches reduce exposure; patching fixes the bug.** Turn MPTCP off where you don't need it, but treat that as temporary mitigation until the patched kernel is running. ## Check what you expose List MPTCP listening sockets and the processes behind them: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo ss -Mlnp ``` Check whether the kernel allows MPTCP sockets in the current network namespace (`1` means enabled): ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sysctl net.mptcp.enabled ``` Check which Go version built a binary and the GODEBUG defaults built into a main package: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} go version -m ./server go list -f '{{.DefaultGODEBUG}}' ./cmd/server ``` `go list` only prints settings that differ from the toolchain's defaults. With a Go 1.24 or later toolchain, an empty result means listeners use MPTCP; `multipathtcp=0` in the output means they don't. ## Turn MPTCP off Pick the narrowest layer that covers every listener you run. | Scope | How | When it applies | | - | - | - | | One process | `GODEBUG=multipathtcp=0` in the service environment | At process start; restart the service | | One build | `godebug multipathtcp=0` in the main module's `go.mod`, or `//go:debug multipathtcp=0` above `package main` | Next build | | One socket | `lc.SetMultipathTCP(false)` on a `net.ListenConfig` | Overrides GODEBUG for that listener | | Whole host or namespace | `sysctl -w net.mptcp.enabled=0` | New sockets only; restart services so existing listeners are recreated | Per-socket example: ```go theme={"theme":{"light":"github-light","dark":"github-dark"}} lc := net.ListenConfig{} lc.SetMultipathTCP(false) // plain TCP, regardless of GODEBUG ln, err := lc.Listen(ctx, "tcp", ":8080") ``` For a systemd service, set the environment variable in a drop-in file: ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} # /etc/systemd/system/myapp.service.d/no-mptcp.conf [Service] Environment=GODEBUG=multipathtcp=0 ``` `GODEBUG` takes a comma-separated list. If the service already sets `GODEBUG`, add `multipathtcp=0` to the existing value instead of replacing it. The `multipathtcp` values are `0` (off), `1` (dialers and listeners), `2` (listeners only, the Go 1.24 default), and `3` (dialers only). The host-wide sysctl is safe for Go programs. When creating the MPTCP socket fails, Go falls back to plain TCP. Persist it in `/etc/sysctl.d/` if you want it to survive a reboot, and confirm that nothing on the host actually needs MPTCP. After any change, run `sudo ss -Mlnp` again and confirm the listener is gone from the list. ## Fix the kernel 1. Install your distribution's patched kernel and reboot into it. Check that `uname -r` reports the new version. 2. If you can't patch right away, follow your vendor's interim mitigation. Red Hat published an nftables rule that drops inbound IPv4 TCP packets carrying IP options. Red Hat expects ordinary application traffic to be unaffected, but test the rule first, and remove it after patching. It reduces exposure; it does not fully prevent exploitation. 3. Remember that containers share the host kernel. Patching an image does nothing; patch the node. ## References * [Folo source: Geek on the Xray-core emergency update](https://x.com/geekbb/status/2116526532881744310) * [Go 1.24 release notes: `net.ListenConfig` uses MPTCP by default](https://go.dev/doc/go1.24) * [Go docs: GODEBUG history and `multipathtcp` values](https://go.dev/doc/godebug) * [Go Security Team: Protecting against CVE-2026-98432 (via oss-security)](https://www.openwall.com/lists/oss-security/2026/10/30/1) * [Go source: MPTCP listener fallback to TCP](https://go.dev/src/net/mptcpsock_linux.go) * [NVD: CVE-2026-98432](https://nvd.nist.gov/vuln/detail/cve-2026-98432) * [Red Hat: RHSB-2026-016 and nftables mitigation](https://access.redhat.com/security/vulnerabilities/RHSB-2026-016) * [Anthropic: Discovering and exploiting vulnerabilities with Claude](https://www.anthropic.com/research/discovering-vulnerabilities-with-claude) * [XTLS/Xray-core #7291: disable MPTCP by default](https://github.com/XTLS/Xray-core/pull/7291) * [Linux kernel docs: MPTCP sysctl `enabled`](https://docs.kernel.org/networking/mptcp-sysctl.html) * [ss(8): `-M, --mptcp`](https://man7.org/linux/man-pages/man8/ss.8.html) # FastAPI Source: https://base.bangwu.me/backend/Python/fastapi FastAPI is a modern, high-performance Python web framework with automatic API docs, async support, Pydantic type validation, and dependency injection. # FastAPI FastAPI is a modern, high-performance Python web framework built on Python 3.6+ type hints. With over 70k+ stars on GitHub, it's one of the most popular Python backend frameworks today. ## Core Features * **High Performance**: Performance comparable to Node.js and Go * **Fast Development**: Improves development efficiency 200%-300% * **Auto Docs**: Automatically generates interactive API documentation * **Type Checking**: Pydantic-based data validation * **Async Support**: Native async/await support ## Quick Start ### Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} pip install fastapi pip install "uvicorn[standard]" ``` ### Hello World ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} ``` ### Running ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} uvicorn main:app --reload ``` Visit [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) to see the auto-generated API documentation. ## Path & Query Parameters ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from typing import Optional @app.get("/users/{user_id}") async def read_user( user_id: int, skip: int = 0, limit: int = 10, q: Optional[str] = None ): return {"user_id": user_id, "skip": skip, "limit": limit, "q": q} ``` ## Request Body ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None @app.post("/items/") async def create_item(item: Item): return item ``` ## Response Model ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class UserOut(BaseModel): username: str email: str @app.post("/users/", response_model=UserOut) async def create_user(user: User): return user # Automatically filters sensitive fields ``` ## Dependency Injection ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi import Depends def get_db(): db = Database() try: yield db finally: db.close() @app.get("/users/") async def read_users(db = Depends(get_db)): return db.query_users() ``` ## Middleware ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ``` ## Database Integration ### SQLAlchemy ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(bind=engine) def get_db(): db = SessionLocal() try: yield db finally: db.close() ``` ## Authentication & Authorization ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/users/me") async def read_users_me(token: str = Depends(oauth2_scheme)): return {"token": token} ``` ## File Upload ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi import File, UploadFile @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename} ``` ## Background Tasks ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi import BackgroundTasks def send_email(email: str): # Send email logic pass @app.post("/send-notification/") async def send_notification( email: str, background_tasks: BackgroundTasks ): background_tasks.add_task(send_email, email) return {"message": "Email will be sent"} ``` ## Resources * Official Docs: [https://fastapi.tiangolo.com/](https://fastapi.tiangolo.com/) * Chinese Docs: [https://fastapi.tiangolo.com/zh/](https://fastapi.tiangolo.com/zh/) * GitHub: [https://github.com/tiangolo/fastapi](https://github.com/tiangolo/fastapi) # Python Source: https://base.bangwu.me/backend/Python/index Python backend development hub covering FastAPI framework, web scraping with requests and BeautifulSoup, and popular third-party libraries. ![Python](https://cdn.bangwu.top/img/Python.png) Python is a concise and elegant programming language widely used in web development, data analysis, and AI. ## Backend Frameworks ### FastAPI A modern, high-performance Python web framework with async support and auto-generated API docs. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} ``` > [card] [FastAPI Details](/backend/Python/fastapi) > > Route params, request bodies, dependency injection, middleware, and auth. ### Flask A lightweight web framework for quick prototyping of small applications. ### Django A full-stack web framework with built-in ORM, admin panel, and more. ## Web Scraping > [card] [Scraping Guide](/backend/Python/spider/index) > > From basics to advanced techniques, anti-scraping strategies and real cases. ## Popular Libraries > [card] [Library Index](/backend/Python/libs/index) > > Notes on httpx, matplotlib, wordcloud, PyTorch, and more. ## Resources * [Python Official Docs](https://docs.python.org/3/) * [PyPI Package Index](https://pypi.org/) # PyTorch Source: https://base.bangwu.me/backend/Python/libs/PyTorch PyTorch deep learning framework guide covering CPU and GPU installation, tensor creation and operations, automatic differentiation, and neural network basics. # PyTorch PyTorch is an open-source deep learning framework developed by Facebook AI Research and widely used in both academic research and industry. ## Installation ### Automatic installation Choose the right command from the official website: [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/) ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # CPU 版本 pip install torch torchvision torchaudio # GPU 版本 (CUDA 12.4) pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124 ``` ### Manual GPU installation Download page: [https://download.pytorch.org/whl/torch/](https://download.pytorch.org/whl/torch/) You need to download three packages, making sure the Python and CUDA versions match: * `torch-2.4.1+cu124-cp312-cp312-win_amd64.whl` * `torchvision-0.19.1+cu124-cp312-cp312-win_amd64.whl` * `torchaudio-2.4.1+cu124-cp312-cp312-win_amd64.whl` ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} pip install torch-2.4.1+cu124-cp312-cp312-win_amd64.whl pip install torchvision-0.19.1+cu124-cp312-cp312-win_amd64.whl pip install torchaudio-2.4.1+cu124-cp312-cp312-win_amd64.whl ``` ### Verify the installation ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import torch print(torch.__version__) print(torch.cuda.is_available()) # True 表示 GPU 可用 print(torch.cuda.get_device_name(0)) # 显示 GPU Name ``` ## Basic concepts ### Tensors ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import torch # 创建张量 x = torch.tensor([1, 2, 3]) y = torch.zeros(2, 3) z = torch.randn(2, 3) # 张量运算 a = torch.tensor([1.0, 2.0]) b = torch.tensor([3.0, 4.0]) c = a + b d = torch.matmul(a, b) # 矩阵乘法 # GPU 加速 if torch.cuda.is_available(): x = x.cuda() # 转移到 GPU # 或者 x = x.to('cuda') ``` ### Automatic differentiation ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 需要梯度's 张量 x = torch.tensor([1.0, 2.0], requires_grad=True) y = x ** 2 z = y.sum() # 反向传播 z.backward() print(x.grad) # 梯度: [2.0, 4.0] ``` ## Building neural networks ### Simple model ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import torch.nn as nn class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(784, 128) self.fc2 = nn.Linear(128, 10) self.relu = nn.ReLU() def forward(self, x): x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x model = SimpleNet() ``` ### Convolutional neural network ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) self.relu = nn.ReLU() self.maxpool = nn.MaxPool2d(2) def forward(self, x): x = self.conv1(x) x = self.relu(x) x = self.maxpool(x) x = self.conv2(x) x = self.relu(x) x = self.maxpool(x) x = x.view(x.size(0), -1) x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x ``` ## Training a model ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import torch.optim as optim # 准备数据 train_loader = torch.utils.data.DataLoader(dataset, batch_size=64) # 定义模型、损失函数、优化器 model = SimpleNet() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # 训练循环 for epoch in range(10): for batch_idx, (data, target) in enumerate(train_loader): # 前向传播 output = model(data) loss = criterion(output, target) # 反向传播 optimizer.zero_grad() loss.backward() optimizer.step() if batch_idx % 100 == 0: print(f'Epoch: {epoch}, Loss: {loss.item()}') ``` ## Profile training before optimizing it A high GPU utilization number does not prove efficient training. NVIDIA's GPU utilization metric measures the fraction of the sampling interval during which a kernel is executing, not the fraction of peak arithmetic throughput achieved. Databricks reported roughly 6× shorter training time in one Qwen fine-tuning workload despite an initial 98% average utilization. Treat that as a case study, not an expected speedup for your model. ### Choose data by downstream results, not proxy metrics NVIDIA's open midtraining work on Nemotron reports a useful evaluation lesson: **base-model proxy metrics did not correlate reliably with post-training results.** Their recipe trains between pretraining and SFT at 256K context on hundreds of billions of tokens of natural software-engineering data — packed repositories, pull requests, commit histories, build logs — plus a small share of agentic traces. After an identical full SFT, SWE-bench Verified rose from 60.7 to 64.5 on the smaller model with 500B midtraining tokens, and 72.9 to 74.3 on the larger one with 280B. Those are the authors' published numbers on those benchmarks, which do not replace evaluation on your own traffic. The transferable method is how they chose data: score each candidate choice with **short fixed SFT runs** against the target task instead of trusting an upstream proxy. When changing pretraining or midtraining mixtures for an agentic workload, plan for a downstream evaluation budget — a proxy that looks better in isolation can lose after post-training. ### Capture a short CPU/GPU trace Use `torch.profiler` to inspect operator counts, CPU dispatch, device execution, and gaps between kernels. This small, standalone example needs an installed PyTorch build, uses CUDA when available, and otherwise records CPU activity. It downloads no model or data and writes one trace to the current directory. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import torch from torch import nn from torch.profiler import ProfilerActivity, profile, record_function, schedule device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = nn.Sequential(nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, 16)).to(device) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) x = torch.randn(64, 128, device=device) y = torch.randn(64, 16, device=device) activities = [ProfilerActivity.CPU] if device.type == "cuda": activities.append(ProfilerActivity.CUDA) def save_trace(prof): print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10)) prof.export_chrome_trace(f"training-trace-{prof.step_num}.json") with profile( activities=activities, schedule=schedule(wait=1, warmup=1, active=3, repeat=1), on_trace_ready=save_trace, record_shapes=True, ) as prof: for _ in range(5): with record_function("train_step"): optimizer.zero_grad(set_to_none=True) loss = nn.functional.mse_loss(model(x), y) loss.backward() optimizer.step() prof.step() ``` The schedule skips one step, warms up the profiler for one, then records three. Adjust it to reach a representative phase of a real workload; profiler warmup does not guarantee that compilation and model startup have finished. The toy inputs already reside on the device, so this example does not measure input loading or host-to-device copies. In a real loop, include those stages in labeled ranges too. Give each distributed rank a distinct trace filename. Tracing, shape recording, and optional memory profiling add overhead. Use traces to locate the bottleneck, then measure throughput separately with profiling disabled. CUDA execution is asynchronous: for wall-clock measurements, synchronize the relevant device before starting and before stopping the timer, rather than forcing synchronization inside every iteration. Do not add nested CPU totals and overlapping GPU durations and call the result wall-clock time. ### Match the change to the bottleneck Modal's GPU glossary separates compute, memory movement, and overhead. Use these as hypotheses, then verify them in a timeline or device profiler: | Observation | Investigate | Candidate change | | - | - | - | | Many tiny kernels, heavy CPU dispatch, gaps between launches | Launch/dispatch overhead | Supported fused kernels; evaluate `torch.compile` or CUDA Graphs for this workload | | Large kernels dominated by data movement | Memory bandwidth and unnecessary intermediate tensors | Reduce copies or intermediates; use supported fused implementations | | Large matrix operations dominate | Compute throughput, dtype, shapes, and hardware support | Tune batch/shape and precision while checking numerical quality | | Input waits, collective waits, or uneven progress across ranks | Data pipeline and distributed communication | Fix the measured wait rather than assuming the model kernel is slow | In Databricks' case, existing `flash-linear-attention` and `causal-conv1d` kernels removed many small operations; reduced padding provided a further gain. That does **not** mean these packages help every model, or that compilation and CUDA Graphs are generally unsuitable for distributed training. Before adopting a fast path, check model/backend support, GPU architecture, PyTorch/CUDA compatibility, and **both forward and backward** support. Pin the working environment and confirm the intended kernel actually appears in the trace: a successful package install does not prove it is being used. Recheck loss and gradients against the reference path within appropriate numerical tolerances. ### Pack sequences without changing the task Sequence packing reduces padding, but simply concatenating examples can change training semantics. **Resetting `position_ids` alone is not a universal isolation mechanism.** The model and attention backend must consume compatible boundary metadata or masks; hybrid recurrent layers also need their state isolated at example boundaries. The pinned Databricks implementation uses reset `position_ids`, cumulative sequence lengths for full attention, segment IDs for gated-delta layers, and loss masking so shifted targets do not cross example boundaries. It also masks prompt tokens for response-only SFT. These are backend-specific inputs, not a recipe to copy unchanged into an arbitrary model. Test packed versus unpacked examples, including boundaries and truncated sequences, before measuring speed. Report non-padding tokens/s, padding fraction, effective batch size, sequence-length distribution, and validation quality. If packing changes tokens per optimizer step, account for the altered batch/optimization schedule. Compare equivalent training work, separating cold-start/compilation time from steady-state throughput. ### Fine-tuning is not the default Adapter-based fine-tuning (LoRA and similar) shrinks the trainable parameter count and optimizer memory, which is why it is often the right first attempt on a consumer GPU. It does **not** automatically reduce activation memory, KV-cache pressure at inference, or total training time — those depend on sequence length, batch size, and how much of the model you still update. Measure before assuming it makes a workload fit. ## Why inference is bandwidth-bound Training time is only half of the performance story. For an interactive agent, **decode latency** often matters more, and it is governed by memory traffic rather than floating-point throughput. An autoregressive model generates one token at a time. At that point the batch is tiny relative to the weights, so each step must read essentially all parameters — and the accumulated KV cache — through memory bandwidth. Stanford CS336's lecture 10 makes the argument arithmetic: compute **arithmetic intensity** (FLOPs per byte moved), compare it with the accelerator's ratio of peak FLOP/s to memory bandwidth, and note that a low-intensity operation is memory-bound regardless of how fast the ALUs are. That single framing explains most inference optimizations: | Technique | Layer | What it trades | | - | - | - | | GQA / MLA / cross-layer attention | Architecture | Smaller KV cache; verify the accuracy cost on your evals | | Quantization, pruning, distillation | Architecture | Fewer bytes per parameter; lossy, needs measurement | | Speculative sampling | Algorithm | Extra compute to verify drafts, accepted tokens are exact if implemented correctly | | Continuous batching | System | Higher throughput, worse per-request latency | | Paged attention | System | Less KV-cache fragmentation, enabling larger batches | | Prefix sharing, copy-on-write | System | One KV copy for shared system prompts or parallel samples | Two practical consequences follow from the latency/throughput trade-off: * **Batch size is a policy choice, not a default.** Larger batches amortize parameter reads — better tokens/s, worse latency for an individual user. Choose from your product's requirement, not the benchmark. * **Capacity planning is a memory calculation.** Parameter bytes plus KV cache for the maximum concurrent sequences must fit, or the throughput numbers are fiction. Use smaller batches during prefill for faster first token, and reserve larger batches for generation. Percy Liang's closing observation is the strategic point: the KV cache is a structural consequence of the Transformer's design. An architecture built for inference from the start — state-space models, linear attention, non-autoregressive generation — is where the largest remaining gains may be, not in further tuning of the current recipe. ## Data loading ### `Dataset` and `DataLoader` ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from torch.utils.data import Dataset, DataLoader class CustomDataset(Dataset): def __init__(self, data, labels): self.data = data self.labels = labels def __len__(self): return len(self.data) def __getitem__(self, idx): return self.data[idx], self.labels[idx] dataset = CustomDataset(data, labels) dataloader = DataLoader(dataset, batch_size=32, shuffle=True) ``` ### Image augmentation ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from torchvision import transforms transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) ``` ## Saving and loading models ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 保存模型 torch.save(model.state_dict(), 'model.pth') # 加载模型 model = SimpleNet() model.load_state_dict(torch.load('model.pth')) model.eval() # 保存完整模型 torch.save(model, 'model_complete.pth') model = torch.load('model_complete.pth') ``` ## Jupyter Notebook setup Create a dedicated PyTorch kernel: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 创建虚拟环境 python -m venv pytorch_env # 激活环境 source pytorch_env/bin/activate # Linux/Mac pytorch_env\Scripts\activate # Windows # 安装 PyTorch 和 Jupyter pip install torch torchvision jupyter ipykernel # 创建内核 python -m ipykernel install --user --name=pytorch --display-name "Python (PyTorch)" ``` Reference: [https://blog.csdn.net/ccaoshangfei/article/details/126521809](https://blog.csdn.net/ccaoshangfei/article/details/126521809) ## Useful tips ### Set the random seed ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} torch.manual_seed(42) if torch.cuda.is_available(): torch.cuda.manual_seed(42) ``` ### Show model structure ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from torchsummary import summary summary(model, input_size=(1, 28, 28)) ``` ### Freeze part of the model ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 冻结前两层 for param in model.parameters(): param.requires_grad = False for param in model.fc2.parameters(): param.requires_grad = True ``` ## References * [meng shao: CS336 lecture 10, Inference](https://x.com/shao__meng/status/2111804476671795223) — Folo intake, October 18, 2026 * [Stanford CS336: Language Modeling from Scratch](https://cs336.stanford.edu/) — course site; lecture 10 covers inference performance * [CS336 lecture 10 (executable lecture)](https://github.com/stanford-cs336/lectures/blob/main/lecture_10.py) — arithmetic intensity, KV cache, batching, PagedAttention * [PagedAttention (arXiv 2309.06180)](https://arxiv.org/pdf/2309.06180.pdf) — vLLM's KV-cache paging and prefix sharing * [elvis: NVIDIA midtraining recipe](https://x.com/omarsar0/status/2111484480875626979) — Folo intake, October 17, 2026 * [NVIDIA: Priming Base Models for Agentic Post-Training (arXiv 2610.22019)](https://arxiv.org/abs/2610.22019) — midtraining stage and short-fixed-SFT evaluation protocol * [meng shao: Qwen training optimization case](https://x.com/shao__meng/status/2110573261302202853) — Folo intake, October 15, 2026 * [Databricks: Reducing Qwen training time by 6x on AI Runtime](https://www.databricks.com/blog/reducing-qwen-training-time-6x-ai-runtime) — profiling, fused kernels, and padding reduction in one workload * [Databricks: Pinned training implementation](https://github.com/databricks-solutions/ai-runtime-cookbook/blob/b27c10cfda94263588214f8824e0dd8bb393371e/training/sft-qwen3.8-27b-fsdp2-multinode/train.py) — packing metadata and loss boundaries * [PyTorch: Profiler recipe](https://docs.pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) — activities, scheduled traces, and overhead * [NVIDIA: nvidia-smi documentation](https://docs.nvidia.com/deploy/nvidia-smi/index.html) — meaning of utilization metrics * [meng shao: Modal GPU glossary recommendation](https://x.com/shao__meng/status/2110581130806382765) — Folo intake, October 15, 2026; the glossary, not the financing news, is the reusable resource * [Modal: GPU glossary — performance bottleneck](https://modal.com/gpu-glossary/perf/performance-bottleneck) — compute, memory, and overhead ## Learning resources * Official docs: [https://pytorch.org/docs/](https://pytorch.org/docs/) * Official tutorials: [https://pytorch.org/tutorials/](https://pytorch.org/tutorials/) * Chinese docs: [https://pytorch-cn.readthedocs.io/](https://pytorch-cn.readthedocs.io/) * GitHub: [https://github.com/pytorch/pytorch](https://github.com/pytorch/pytorch) # Python data types Source: https://base.bangwu.me/backend/Python/libs/data-types Python built-in data types reference covering integers, floats, strings, lists, tuples, dictionaries, and sets with common methods and operation examples. # Python data types Python ships with a rich set of built-in data types for different kinds of data structures and use cases. Official docs: [https://docs.python.org/zh-cn/3.12/library/datatypes.html](https://docs.python.org/zh-cn/3.12/library/datatypes.html) ## Basic data types ### Numeric types ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 整数 x = 10 # 浮点数 y = 3.14 # 复数 z = 1 + 2j ``` ### Strings ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} s = "Hello World" s1 = 'Python' s2 = """多行 字符串""" # 常用方法 s.upper() # 转大写 s.lower() # 转小写 s.split() # 分割 s.strip() # 去除首尾空格 s.replace("Hello", "Hi") # 替换 ``` ### Booleans ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} is_valid = True is_empty = False ``` ## Container types ### List ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 可变、有序 fruits = ["apple", "banana", "cherry"] fruits.append("orange") # 添加 fruits.remove("banana") # 删除 fruits[0] # 索引Visit fruits[1:3] # 切片 ``` ### Tuple ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 不可变、有序 point = (10, 20) x, y = point # 解包 ``` ### Set ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 无序、不重复 s1 = {1, 2, 3} s2 = {3, 4, 5} s1 | s2 # 并集 s1 & s2 # 交集 s1 - s2 # 差集 ``` ### Dictionary ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 键值yes user = { "name": "张三", "age": 25, "email": "zhangsan@example.com" } user["name"] # Visit user.get("age") # 安全Visit user.keys() # 所有键 user.values() # 所有值 user.items() # 所有键值yes ``` ## Specialized data types ### `datetime` - date and time ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from datetime import datetime, date, timedelta now = datetime.now() today = date.today() tomorrow = today + timedelta(days=1) # 格式化 now.strftime("%Y-%m-%d %H:%M:%S") # 解析 datetime.strptime("2024-01-01", "%Y-%m-%d") ``` ### `collections` - container extensions #### `defaultdict` ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from collections import defaultdict d = defaultdict(list) d['key'].append(1) # 不存在时自动创建空列表 ``` #### `Counter` ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from collections import Counter words = ["apple", "banana", "apple"] counter = Counter(words) counter.most_common(1) # [('apple', 2)] ``` #### `deque` - double-ended queue ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from collections import deque q = deque([1, 2, 3]) q.append(4) # 右侧添加 q.appendleft(0) # 左侧添加 q.pop() # 右侧删除 q.popleft() # 左侧删除 ``` ### `enum` - enumerations ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 print(Color.RED) # Color.RED print(Color.RED.value) # 1 ``` ### `dataclasses` - data classes ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from dataclasses import dataclass @dataclass class User: name: str age: int email: str = "" user = User("张三", 25) ``` ### `typing` - type hints ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from typing import List, Dict, Optional, Union def process_items(items: List[str]) -> Dict[str, int]: return {item: len(item) for item in items} def get_user(user_id: int) -> Optional[User]: return user if user_id > 0 else None ``` ## Type conversion ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 转整数 int("10") # 10 int(3.14) # 3 # 转浮点数 float("3.14") # 3.14 # 转字符串 str(100) # "100" # 转列表 list("abc") # ['a', 'b', 'c'] # 转元组 tuple([1, 2]) # (1, 2) # 转集合 set([1, 1, 2]) # {1, 2} ``` ## Common patterns ### List comprehensions ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} squares = [x**2 for x in range(10)] evens = [x for x in range(10) if x % 2 == 0] ``` ### Dictionary comprehensions ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} square_dict = {x: x**2 for x in range(5)} ``` ### Generator expressions ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} gen = (x**2 for x in range(10)) # 惰性求值 ``` # HTTPX Source: https://base.bangwu.me/backend/Python/libs/httpx HTTPX is a modern Python HTTP client replacing requests, with sync and async APIs, native HTTP/2 support, connection pooling, and timeout configuration. # HTTPX HTTPX is a full-featured Python HTTP client library with both synchronous and asynchronous APIs. It is often treated as the modern alternative to `requests`. ## Features * **Sync and async APIs**: one consistent interface for both styles * **HTTP/2 support**: better performance where supported * **Connection pooling**: automatic connection reuse * **Timeout control**: fine-grained timeout settings * **Type hints**: complete type annotations ## Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} pip install httpx ``` ## Synchronous requests ### Basic usage ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import httpx # GET 请求 response = httpx.get('https://api.example.com/data') print(response.status_code) print(response.json()) # POST 请求 data = {'key': 'value'} response = httpx.post('https://api.example.com/submit', json=data) # 带Parameters's 请求 params = {'page': 1, 'size': 10} response = httpx.get('https://api.example.com/items', params=params) # 带请求头 headers = {'Authorization': 'Bearer token'} response = httpx.get('https://api.example.com/user', headers=headers) ``` ### Using `Client` ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 复用连接 with httpx.Client() as client: r1 = client.get('https://example.com') r2 = client.get('https://example.com/api') ``` ## Asynchronous requests ### Basic usage ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import httpx import asyncio async def fetch_data(): async with httpx.AsyncClient() as client: response = await client.get('https://api.example.com/data') return response.json() # Run data = asyncio.run(fetch_data()) ``` ### Concurrent requests ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} async def fetch_multiple(): async with httpx.AsyncClient() as client: tasks = [ client.get(f'https://api.example.com/item/{i}') for i in range(10) ] responses = await asyncio.gather(*tasks) return [r.json() for r in responses] ``` ## Advanced features ### Timeout settings ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 全局超时 timeout = httpx.Timeout(10.0, connect=5.0) response = httpx.get('https://example.com', timeout=timeout) # 单独设置 response = httpx.get('https://example.com', timeout=30.0) ``` ### Authentication ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # Basic Auth auth = ('username', 'password') response = httpx.get('https://api.example.com', auth=auth) # Bearer Token headers = {'Authorization': f'Bearer {token}'} response = httpx.get('https://api.example.com', headers=headers) ``` ### File uploads ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} files = {'file': open('report.pdf', 'rb')} response = httpx.post('https://api.example.com/upload', files=files) # 多文件 files = [ ('images', ('image1.jpg', open('image1.jpg', 'rb'), 'image/jpeg')), ('images', ('image2.jpg', open('image2.jpg', 'rb'), 'image/jpeg')) ] response = httpx.post('https://api.example.com/upload', files=files) ``` ### Streaming downloads ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} with httpx.stream('GET', 'https://example.com/large-file.zip') as r: with open('file.zip', 'wb') as f: for chunk in r.iter_bytes(): f.write(chunk) ``` ### Cookie management ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} cookies = {'session_id': 'abc123'} response = httpx.get('https://example.com', cookies=cookies) # 持久化 cookies with httpx.Client(cookies=cookies) as client: client.get('https://example.com/page1') client.get('https://example.com/page2') ``` ### Proxy settings ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} proxies = { 'http://': 'http://proxy.example.com:8080', 'https://': 'http://proxy.example.com:8080' } response = httpx.get('https://example.com', proxies=proxies) ``` ### Retry handling ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import httpx from httpx import Timeout transport = httpx.HTTPTransport(retries=3) client = httpx.Client(transport=transport) response = client.get('https://example.com') ``` ## Response handling ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} response = httpx.get('https://api.example.com/data') # 状态码 print(response.status_code) # JSON 数据 data = response.json() # 文本内容 text = response.text # 二进制内容 content = response.content # 响应头 print(response.headers['content-type']) # 检查状态 response.raise_for_status() # 4xx/5xx 抛出异常 ``` ## Compared with `requests` | Feature | requests | httpx | | - | - | - | | Synchronous requests | ✅ | ✅ | | Asynchronous requests | ❌ | ✅ | | HTTP/2 | ❌ | ✅ | | Type hints | Partial | Complete | | Maintenance status | Active | Active | ## Best practices 1. **Reuse connections with `Client`** for better performance. 2. **Set sensible timeouts** to avoid hanging requests. 3. **Prefer async in high-concurrency scenarios**. 4. **Handle errors explicitly** and retry where appropriate. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import httpx async def safe_fetch(url: str, max_retries: int = 3): for attempt in range(max_retries): try: async with httpx.AsyncClient() as client: response = await client.get(url, timeout=10.0) response.raise_for_status() return response.json() except httpx.HTTPError as e: if attempt == max_retries - 1: raise await asyncio.sleep(2 ** attempt) ``` ## References * Official docs: [https://www.python-httpx.org/](https://www.python-httpx.org/) * GitHub: [https://github.com/encode/httpx](https://github.com/encode/httpx) # Python Libraries Source: https://base.bangwu.me/backend/Python/libs/index Python third-party library notes covering httpx, matplotlib, PyTorch, WordCloud, PyAutoGUI and more, with a learn-by-doing philosophy. Third-party libraries are the core strength of Python's ecosystem. Standard libraries come with the installation, while third-party libraries are installed via `pip`, all accessed using `import` statements. ## How to Learn You don't need to memorize every library — just master the commonly-used ones (`numpy`, `pandas` for data; `re`, `BeautifulSoup` for extraction). For others, read the official docs once to understand what they can do, and refer back to your notes when needed. > [!TIP] > > Libraries are like bricks for building a house — do you need to understand their material composition? Just learn to use them. > [!WARNING] > > Official documentation is the most authoritative source. Blog tutorials can supplement, but should not be your primary reference. ## Library Directory For a comprehensive list, check [awesome-python-cn](https://github.com/jobbole/awesome-python-cn) with 26k+ stars, categorized by function. > [card] [httpx](/backend/Python/libs/httpx) > > Next-generation HTTP client with async support. > [card] [matplotlib](/backend/Python/libs/matplotlib) > > Data visualization and charting. > [card] [wordcloud](/backend/Python/libs/wordcloud) > > Word cloud generation and text visualization. > [card] [PyTorch](/backend/Python/libs/PyTorch) > > Deep learning framework intro notes. > [card] [Python Notes](/backend/Python/libs/python-notes) > > Misc notes and common usage patterns. > [card] [Data Types](/backend/Python/libs/data-types) > > Python data types in detail. > [card] [pyautogui](/backend/Python/libs/pyautogui) > > Automation scripts and GUI control. # Matplotlib Source: https://base.bangwu.me/backend/Python/libs/matplotlib Matplotlib is Python's main 2D plotting library for publication-quality figures, covering pyplot for line charts, histograms, and scatter plots. # Introduction to Matplotlib ## What is Matplotlib? Matplotlib is a Python 2D plotting library that can generate publication-quality figures in many hard-copy formats and interactive environments. It can be used in Python scripts, the Python and [IPython](http://ipython.org/) shell, [Jupyter](http://jupyter.org/) notebooks, web application servers, and multiple GUI toolkits. Matplotlib tries to make easy things easy and hard things possible. With just a few lines of code, you can create charts, histograms, power spectra, bar charts, error plots, scatter plots, and more. See the [basic plotting examples](https://www.matplotlib.org.cn/tutorials/introductory/sample_plots.html) and the [gallery](https://www.matplotlib.org.cn/gallery/index.html) for inspiration. ![img](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202305130748189.png) For simple plotting, the `pyplot` module offers an interface similar to MATLAB, especially when used with IPython. Advanced users can also rely on the object-oriented API for full control over line styles, fonts, axes, and other details. ## Learning from the official examples If you want to learn how to draw a specific kind of chart, the best places to start are the [gallery](https://www.matplotlib.org.cn/gallery) and the [pyplot command reference](https://matplotlib.org/api/pyplot_summary.html). Do not be afraid of the official docs. Even when they are in English or lightly annotated, they are still the most complete reference. The translated pages are usually good enough for reading, and when a function is still hard to understand, you can always search the community or ask someone more experienced. # PyAutoGUI Source: https://base.bangwu.me/backend/Python/libs/pyautogui PyAutoGUI is a Python GUI automation library for controlling mouse, keyboard, and screen capture with image recognition for automated testing. # Introduction to PyAutoGUI PyAutoGUI is a pure-Python `GUI` automation library. It lets a program control the mouse and keyboard automatically, so it is very useful for simple automation and UI testing. You can think of it as a Python version of a desktop macro tool. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import pyautogui ``` After importing it, you can get started right away. # Mouse operations ## Coordinates For a library that focuses on precise clicking, coordinate handling is the foundation. `pyautogui` uses screen pixels for positioning. For example, on a display with a resolution of 2560x1600: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} width, height = pyautogui.size() # 获取电脑屏幕坐标 print(width, height) ``` The output is `2560 1600`. The coordinate origin is in the top-left corner. The x-axis is horizontal and the y-axis is vertical: ![image-20230518114531127](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202305181145156.png) Once you understand that, you can position the mouse precisely. ## Mouse movement # Python learning notes Source: https://base.bangwu.me/backend/Python/libs/python-notes Miscellaneous Python notes and code snippets covering pd.DataFrame creation, Pandas tips, common error troubleshooting, and useful patterns. # Python notes ## 1. `pd.DataFrame` This is the standard Pandas format for creating a `DataFrame`. Remember the capitalization: `DataFrame`. Each column in a `DataFrame` is a `Series`. ## 2. Reading text-based data files `pandas.read_table()` is the more general API for reading text files. The main difference is that its default `sep` is `"/t"`, meaning tab-separated data. ## `pd.read_csv()` ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} pd.read_csv( filepath or buffer:要读入's File path sep=',':列分隔符 header='infer':指定数据中's 第几行作为变量名 names = None:自定义变量名列表 index_col = None:将会被用作索引's 列名,多列时只能使用序号列表
usecols = None:指定只读入某些列,使用索引列表或者Name列表均可。 [0,1,3],[”名次”,”学校Name”,”所在地区”] encoding = None:读入文件's 编码方式 utf-8/GBK,中文数据文件最好设定为utf-8 na_values:指定将被读入为缺失值's 数值列表,默认下列数据被读入为缺失值: ' ','#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', ‘N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null' ):读取csv格式文件,但也可通用于文本文件读取 ``` 4. ![image-20230924212132039](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/image-20230924212132039.png) ## `describe` command This command outputs common summary statistics for central tendency and dispersion in one go. Percentile output is one of its most useful features. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} df.describe( percentiles:需要输出's 百分位数,列表格式提供,如[.25, .5, .75] include = "None" :要求纳入分析's 变量类型白名单 None (default) :只纳入数值变量列 A list0-like of dtypes :列表格式提供希望纳入's 类型 "all": 全部纳入 exclude: 要求剔除分析's 变量类型黑名单,选项同上 ) ``` ## Univariate frequency statistics ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} Series.value_counts( normalize = False: 是否返回构成比例而不是原始频数 sort = True:是否按照频数排序(否则按照原始顺序排列) ascending = False:是否升序排列 bins: yes数值变量直接进行分段。可看作是判断pd.cut's 简易用法 dropna = True: 结果中是否包括NaN ) ``` ## Crosstab ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} pd.crosstab( 行列设定 index / columns: 行变量/列变量,多个时以list形式提供 rownames / colnames = None: 交叉表's 行列Name 单元格设定 Values: 在单元格中需要汇总's 变量列,需要进一步指定aggfunc aggfunc: 相应's 汇总函数 行列百分比计算 normalize = False: {"all","index", "columns"}, or {0,1} "all" / True: 总计百分比 "index" / 0:分行计算百分比 "columns" / 1: 分列计算百分比 当margins = True时,也同时计算边际汇总's 百分比 汇总设定 margins = False : 是否加入行列汇总 margins_name = "All": 汇总行/列's Name dropna = True: ) ``` # WordCloud Source: https://base.bangwu.me/backend/Python/libs/wordcloud WordCloud is a Python library for word cloud visualizations, covering custom shape masks, color schemes, Chinese segmentation with jieba. # WordCloud WordCloud is a Python library for generating word cloud images. It can turn text data into visually appealing word clouds. ## Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} pip install wordcloud ``` Chinese text support requires an additional font path configuration. ## Basic usage ### Simple word cloud ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from wordcloud import WordCloud import matplotlib.pyplot as plt # 生成词云 text = "Python 数据分析 机器学习 深度学习 人工智能" wordcloud = WordCloud(font_path='simhei.ttf').generate(text) # 显示图像 plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show() # 保存图像 wordcloud.to_file('wordcloud.png') ``` ### Read from a file ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} with open('text.txt', 'r', encoding='utf-8') as f: text = f.read() wordcloud = WordCloud( font_path='simhei.ttf', width=800, height=400 ).generate(text) ``` ## Custom styles ### Basic parameters ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} wordcloud = WordCloud( font_path='simhei.ttf', # 字体路径 width=800, # 宽度 height=400, # 高度 background_color='white', # 背景色 max_words=200, # 最大词数 max_font_size=100, # 最大字号 min_font_size=10, # 最小字号 colormap='viridis', # 配色方案 relative_scaling=0.5, # 词频重要性 random_state=42 # 随机种子 ) ``` ### Color schemes ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 使用 matplotlib 配色 from matplotlib import cm wordcloud = WordCloud( font_path='simhei.ttf', colormap='rainbow' # 'viridis', 'plasma', 'cool', 'hot' ) ``` ## Advanced features ### Use a mask image ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from PIL import Image import numpy as np # 读取遮罩图片 mask = np.array(Image.open('mask.png')) wordcloud = WordCloud( font_path='simhei.ttf', mask=mask, # 遮罩图片 contour_width=3, # 轮廓宽度 contour_color='steelblue' # 轮廓颜色 ).generate(text) ``` ### Custom word frequencies ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 使用字典设置词频 word_freq = { 'Python': 100, '数据分析': 80, '机器学习': 60, '深度学习': 40 } wordcloud = WordCloud(font_path='simhei.ttf').generate_from_frequencies(word_freq) ``` ### Stopword filtering ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 设置停用词 stopwords = set([''s ', '了', '在', '是', '我', '有']) wordcloud = WordCloud( font_path='simhei.ttf', stopwords=stopwords ).generate(text) # 从文件加载停用词 with open('stopwords.txt', 'r', encoding='utf-8') as f: stopwords = set(f.read().splitlines()) ``` ## Chinese text processing ### Use `jieba` for tokenization ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import jieba from wordcloud import WordCloud # 读取文本 with open('text.txt', 'r', encoding='utf-8') as f: text = f.read() # 分词 words = jieba.cut(text) text_seg = ' '.join(words) # 生成词云 wordcloud = WordCloud( font_path='simhei.ttf', background_color='white' ).generate(text_seg) ``` ### Complete example ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import jieba import jieba.analyse from wordcloud import WordCloud import matplotlib.pyplot as plt # 读取文本 with open('article.txt', 'r', encoding='utf-8') as f: text = f.read() # 加载停用词 with open('stopwords.txt', 'r', encoding='utf-8') as f: stopwords = set(f.read().splitlines()) # 分词 words = jieba.cut(text) filtered_words = [w for w in words if w not in stopwords and len(w) > 1] text_seg = ' '.join(filtered_words) # 生成词云 wordcloud = WordCloud( font_path='simhei.ttf', width=1600, height=800, background_color='white', max_words=100, colormap='viridis' ).generate(text_seg) # 显示 plt.figure(figsize=(12, 6)) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.savefig('wordcloud.png', dpi=300, bbox_inches='tight') plt.show() ``` ## Practical tips ### Extract keywords ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import jieba.analyse # TF-IDF 提取关键词 keywords = jieba.analyse.extract_tags(text, topK=50, withWeight=True) word_freq = {word: weight for word, weight in keywords} wordcloud = WordCloud( font_path='simhei.ttf' ).generate_from_frequencies(word_freq) ``` ### Multiple shapes ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from PIL import Image import numpy as np # 圆形 def create_circle_mask(size=400): x, y = np.ogrid[:size, :size] mask = (x - size/2) ** 2 + (y - size/2) ** 2 > (size/2) ** 2 mask = 255 * mask.astype(int) return mask mask = create_circle_mask() wordcloud = WordCloud(font_path='simhei.ttf', mask=mask).generate(text) ``` ## Common issues ### Chinese text shows as squares * Cause: no Chinese font specified * Fix: set `font_path='simhei.ttf'` ### Common Chinese font paths * Windows: `C:\Windows\Fonts\simhei.ttf` * Mac: `/System/Library/Fonts/PingFang.ttc` * Linux: `/usr/share/fonts/truetype/` ## References * GitHub: [https://github.com/amueller/word\_cloud](https://github.com/amueller/word_cloud) * Docs: [https://amueller.github.io/word\_cloud/](https://amueller.github.io/word_cloud/) # Anti-Scraping Techniques Source: https://base.bangwu.me/backend/Python/spider/anti-spider Anti-scraping techniques covering User-Agent and Referer header spoofing, IP proxy rotation to avoid bans, and Ajax data extraction methods. # Header parameters In the `requests.get()` method, one of the most common anti-scraping-related arguments is `headers`. The usage is simple: pass `headers=a dictionary`. This dictionary stores request headers that help make a crawler look like a real browser instead of a bot. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} headers = { 'Referer': '具体's Referer', 'User-Agent': '具体's user-agent', 'cookie':'具体's cookie' } requests.get(url,headers=headers) ``` ## User-Agent Almost every crawler starts with the `User-Agent`. Most websites check it first. The easiest way to get one is to open the browser developer tools, inspect a network request, and copy the value. Since a `User-Agent` is usually just browser and system metadata, its main purpose is to make your request look like it came from a real user. That is exactly why libraries like `my_fake_useragent` exist. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from my_fake_useragent import UserAgent headers = {'User-Agent': UserAgent(family='chrome').random()} ``` This gives you a randomized `User-Agent`, which is often more convenient and can bypass some basic UA checks. ## Cookie Cookies are also very common in scraping. A cookie is essentially your identity on a site. Once the server sees your cookie, it can recognize the current session and return content tied to that identity. ## Referer `Referer` is often related to anti-hotlinking. It tells the server which page the current request came from. In a path like `A -> B -> C`, the `Referer` for `C` is `B`. Many sites use this to check whether a request really originated from an expected page. If not, they may deny access or return fake data. A typical example is video sites: direct requests to media URLs may fail unless the request appears to come from the site itself. Here I use Douban as an example. If you are interested, you can explore it further yourself: [Link](). ## Content-type `Content-type` determines how the server interprets the request body and how the client should interpret the response. # Common parameters In the browser developer tools, you will see many more headers than just the ones above. So how do you decide which ones are actually necessary? For ordinary sites, adding a `User-Agent` is often enough. Sites that require login usually also need cookies. Other cases vary by site, so the practical approach is to test a few combinations. There is also a universal fallback: use **selenium** to simulate real browser behavior. It is more cumbersome to write, so it is usually best kept as the last resort. # Ajax overview Ajax stands for Asynchronous JavaScript and XML. The term was proposed by Jesse James Garrett in 2005 to describe a “new” way of using existing web technologies such as HTML/XHTML, CSS, JavaScript, DOM, XML, XSLT, and—most importantly—`XMLHttpRequest`. The key idea is that a page can exchange small amounts of data with the server in the background. That allows part of the page to update without refreshing the entire page. In practice, you do not need to master all the underlying theory. You just need to recognize what Ajax requests look like in the browser. Here is a simple example: ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} Ajax

ajax

``` Simply put, Ajax sends a request to the server and then refreshes only the data that changed. For example, if you implemented product review pagination the traditional way, every page switch would fetch the header, sidebar, footer, and review area again. That wastes bandwidth, server resources, and user time. With Ajax pagination, only the review section needs to be fetched and re-rendered. # How to identify and find Ajax requests ## Identify them To determine whether a page is using Ajax, trigger the relevant action and watch whether the page fully reloads. If the page does not refresh but the data updates, the content is probably being fetched and rendered with Ajax. If the whole page reloads, the data is likely being generated server-side in the traditional way. ## How to find them As mentioned above, Ajax still has to send a request to the server. That is your entry point. The request is usually either `GET` or `POST`, so a quick method is to inspect the fetched page source or scripts and search for `get` or `post`. Once you locate the Ajax function, look at where it sends the request, extract the `url`, and then mimic that request yourself to retrieve the data. # Solutions # Practical cases I ran into this kind of situation while scraping a site. If you are interested, you can check it here: [Link](). # IP anti-scraping mechanisms # How to switch IPs # How to get proxy IPs ## `proxy_pool` (free) `proxy_pool` is a free and open-source proxy pool project on GitHub. Its basic idea is to crawl public proxy websites and aggregate usable IPs. ## Paid proxy providers ## Self-built proxy IPs # Web Scraping Source: https://base.bangwu.me/backend/Python/spider/index Python web scraping from basics to advanced, covering requests module, HTML parsing with BeautifulSoup, data extraction, and multiprocessing. Suitable for those with basic Python knowledge — syntax and package imports. ## Scraping Basics 1. `requests` module 2. HTML fundamentals (understanding HTML) 3. Content extraction ## Scraping Advanced 1. Threading, multiprocessing, async introduction > [card] [Anti-Scraping Techniques](/backend/Python/spider/anti-spider) > > Headers parameters, IP proxies, Ajax data extraction, and more. # Rust IM Bridge (AgentIM) Source: https://base.bangwu.me/backend/Rust/agentim Multi-channel IM bridge built in Rust — connecting Telegram, Discord, Feishu, Slack, DingTalk, LINE, QQ, and WeChat Work to AI agent backends. # AgentIM — Rust Multi-Channel IM Bridge AgentIM is a Rust bridge that connects chat platforms to a local AI agent backend (Codex). It supports 8+ platforms through webhooks and long polling, with session persistence, context limits, and routing rules. > [card] [AgentIM](https://github.com/markbang/agentim) > > Rust IM bridge — 8+ platforms, session persistence, health endpoints. ## Supported Platforms | Platform | Delivery | Verification | | - | - | - | | Telegram | Long polling (`getUpdates`) | Bot token | | Discord | `POST /discord` | Ed25519 | | Feishu/Lark | `POST /feishu` | Verification token + URL challenge | | Slack | `POST /slack` | HMAC-SHA256 | | DingTalk | `POST /dingtalk` | HMAC-SHA256 | | LINE | `POST /line` | HMAC-SHA256 | | QQ | `POST /qq` | — | | WeChat Work | `POST /wechatwork` | — | ## Tech Stack | Component | Technology | Purpose | | - | - | - | | HTTP server | Axum 0.7 | Routing, middleware, webhooks | | Async runtime | Tokio (full features) | Async I/O, timers, channels | | HTTP client | Reqwest | Outbound API calls | | Concurrency | DashMap | Lock-free concurrent state | | CLI | Clap 4 | Command-line argument parsing | | Logging | Tracing + Tracing-subscriber | Structured logging | | Serialization | Serde + Serde\_json | JSON codec | | Error handling | Anyhow + Thiserror | Ergonomic error types | | Auth | HMAC | Webhook signature verification | ## Architecture ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} ┌─────────┐ ┌─────────┐ ┌─────────┐ │Telegram │ │Discord │ │Feishu │ ...more platforms └───┬─────┘ └───┬─────┘ └───┬─────┘ │ │ │ ▼ ▼ ▼ ┌───────────────────────────────────┐ │ AgentIM (Axum) │ │ ┌──────────┐ ┌────────────────┐ │ │ │Ingress │ │Session Store │ │ │ │(webhooks │ │(DashMap) │ │ │ │+polling) │ │ │ │ │ └──────────┘ └────────────────┘ │ │ ┌──────────┐ ┌────────────────┐ │ │ │Router │ │Context Trimmer │ │ │ │(rules) │ │ │ │ │ └──────────┘ └────────────────┘ │ └───────────┬───────────────────────┘ │ ▼ ┌───────────────────┐ │ Codex Backend │ │ (app-server) │ └───────────────────┘ ``` ## Key Design Patterns ### Platform Abstraction Each platform handler implements a common trait: ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}} #[async_trait] pub trait PlatformHandler: Send + Sync { async fn handle_inbound(&self, msg: InboundMessage) -> Result<()>; async fn send_response(&self, target: ReplyTarget, text: &str) -> Result<()>; } ``` This lets you add new platforms without touching the core routing logic. ### Session Persistence User sessions are stored in `DashMap` — a lock-free concurrent hashmap: ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}} use dashmap::DashMap; pub struct SessionStore { sessions: DashMap, } pub struct Session { pub user_id: String, pub platform: Platform, pub history: Vec, pub created_at: DateTime, } ``` > [!NOTE] > > DashMap provides sharded locks internally, so concurrent reads/writes from multiple Tokio tasks don't block each other. Much faster than `Mutex` for IM workloads. ### Context Trimming Chat history grows over time. AgentIM trims context to stay within token limits: ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}} pub fn trim_context(history: &mut Vec, max_tokens: usize) { // Keep the most recent messages that fit within max_tokens let mut token_count = 0; let cutoff = history.iter().rev().position(|msg| { token_count += estimate_tokens(&msg.text); token_count > max_tokens }).unwrap_or(history.len()); history.drain(0..cutoff); } ``` ### Webhook Signature Verification Each platform has its own signature scheme. AgentIM validates before processing: ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}} // Discord: Ed25519 pub fn verify_discord_signature(body: &[u8], signature: &str, timestamp: &str, public_key: &str) -> bool { let message = format!("{}{}", timestamp, body); ed25519_verify(message.as_bytes(), signature, public_key) } // Slack / DingTalk: HMAC-SHA256 pub fn verify_hmac_signature(body: &[u8], signature: &str, secret: &str) -> bool { let expected = hmac_sha256(body, secret); signature == expected } ``` ### Routing Rules Channel-based routing lets you direct messages to different behaviors: ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}} pub struct RoutingRule { pub channel_pattern: String, // Regex pub user_pattern: Option, pub target: ReplyTarget, } // Example: route all #help channel messages to a FAQ bot // Example: route DMs from specific users to a custom agent ``` ## Docker Deployment ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} # docker-compose.yml services: agentim: build: . ports: - "8080:8080" environment: - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN} - DISCORD_PUBLIC_KEY=${DISCORD_PUBLIC_KEY} - CODEX_API_URL=http://codex:3002 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/health"] interval: 30s ``` ## Health Endpoints ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}} // /health — service status // /ready — can process requests // /review — pending human-review items (optional) ``` ## Best Practices 1. **Platform trait abstraction** — Common interface per platform, easy to add new ones 2. **DashMap for concurrent state** — Lock-free, fast for multi-platform message handling 3. **Context trimming** — Keep history within token limits to avoid runaway memory 4. **Webhook signature verification** — Always validate before trusting inbound messages 5. **Health + readiness endpoints** — Let orchestrators (Docker, K8s) monitor service state 6. **Shared-secret auth** — Simple but effective for internal service communication 7. **Tokio full features** — IM bridges need timers, I/O, and sync — don't trim the runtime ## References * [AgentIM repo](https://github.com/markbang/agentim) — Full source code * [Axum Docs](https://docs.rs/axum) * [DashMap](https://docs.rs/dashmap) * [Codex app-server transport](https://github.com/markbang/agentim/blob/main/docs/codex-app-server-transport-review.md) # Rust Source: https://base.bangwu.me/backend/Rust/index Rust backend development hub covering Axum IM bridges with Tokio async runtime, Tauri desktop shells, and a learning path from ownership to web services. # Rust Rust combines memory safety, zero-cost abstractions, and fearless concurrency. In my projects, Rust serves two roles: high-performance backend services (Axum) and native desktop shells (Tauri). > [card] [AgentIM](/backend/Rust/agentim) > > Multi-channel IM bridge — Axum, Tokio, 8+ platforms. > [card] [Tauri Desktop](/software/tauri) > > Cross-platform desktop shell — Rust + web frontend. ## Learning Path 1. **Basics** — Ownership, borrowing, lifetimes, traits 2. **Async** — Tokio runtime, futures, channels 3. **Web** — Axum routing, middleware, extractors 4. **Systems** — FFI, unsafe, embedded patterns ## Why Rust for IM Bridges? * **Zero garbage-collection pauses** — IM messages need predictable latency * **Fearless concurrency** — Tokio + DashMap handle thousands of simultaneous connections * **Small binary** — AgentIM compiles to \~5MB, vs 50MB+ for Node.js equivalents * **Memory safety** — No segfaults in production # Database principles Source: https://base.bangwu.me/backend/SQL/db-knowledge Database principles course notes covering relational algebra, SQL queries with JOIN/GROUP BY, normalization to BCNF, ACID properties, and ER. # Database Principles and Applications Exam Related-2023 \---------------------------------------- **Exam question types** **1. Multiple-choice questions (10 points, 5 questions, 2 points each)** **2. Fill-in-the-blank questions (15 points, 5 questions, 3 points each)** **3. Short-answer questions (15 points, 3 questions, 5 points each, please be as detailed as possible, with clear logic and clear layers)** **4. Design questions (60 points. The first question is 10 points; the second question is 50 points, a total of 10 programming questions, each question is 5 points)** *** \*\*\* Question design ideas: Choose corresponding questions from the following key points, then randomly select the above question types and numbers, and then make fine adjustments. \*\* \---------------------------------------- Exam focus: # 1. Introduction 1. `数据库的4个基本概念 P10` * data, database, database management system, database system 2. `数据库的定义 P14` * A database is an organized, large-scale, shared collection of data stored in a computer for a long time 3. `数据库(系统)的基本特征 P14 / P37 - P41` * Shareable by users, with low redundancy, easy expansion, and strong data independence 4. `数据库管理系统的主要功能 P17 - P19` * Data definition function (DDL), data organization, storage and management, data manipulation function (DML), database transaction management and remote management, database establishment and maintenance function, communication function of database and other software systems in the network 5. `数据库系统的构成 P20 - P21` * Databases, database management systems (and their development tools), applications and database administrators 6. `数据库系统的特点 P37-P41` * The data is structured, with high data shareability, low redundancy, easy expansion, and high data independence. The data is managed and controlled uniformly by DBMS. 7. `数据独立性高如何理解 P40` * Refers to an application's database schema and data storage method that does not depend on other applications or operating system platform-specific implementations. 8. `数据库管理系统如何控制数据共享 P41` * Database access permission control, database metadata control, data encryption, database replication, database partitioning, 9. `概念模型、逻辑模型和物理模型的概念 P47` * The conceptual model is an abstraction and simplification of the real world. It is used to describe the data in the database and the relationship between the data. It is the core of database design and the basis of database modeling; * A logical model is a logical representation of a conceptual model, which is used to store data in a database and the relationships between data; * The physical model is the representation of the logical model on a physical storage device, which is used to store and manage data in the database; 10. `数据模型的组成要素 P57` * Entities, attributes, relationships, constraints between entities, data types and precision 11. `数据模型中的数据结构 P58` * The data structure in the data model refers to the way data is stored and represented in the database; * Tables, views, indexes, primary and foreign keys, 12. `数据模型中的数据操作 P59` * Add, delete and modify, insert operations, query operations, data backup and recovery operations, transaction operations 13. `数据模型中的完整性约束条件 P60` * Refers to a set of rules used to ensure the integrity of data in a database; * Entity integrity, attribute integrity, referential integrity, user-defined integrity 14. `关系模型谁提出的? P84` * E.F. Codd, a researcher at the San Jose Research Laboratory of IBM Corporation in the United States 15. `类型和值的概念 P95 - P96` * Type: Type is an identifier used to describe data structure and data type. They usually appear in the form of keywords; * Common types: integer, character and date; * Value: Value refers to the specific content and value of data, usually data input by the user or generated by the program; 16. `数据库系统的三级模式结构 P99 - P105` * Physical layer: The physical layer refers to the actual physical device where data is stored, ensuring the reliability and security of the data; * Conceptual layer: The conceptual layer refers to the data model and data structure in the database, which is the core of database design and implementation; * Logical layer: The logical layer refers to the application program in the database management system and is the direct object of database management and maintenance. 17. `数据库系统的两级映射功能 P107 - P114` It means that the database management system stores data on physical devices and provides the data to users for query and operation; Database: It is the place where data is stored in the database management system and is the physical implementation of the database management system; Database management system application: It is an application in the database management system. Direct objects of database management and maintenance # 2. Relational database 1. `关系数据库的提出者和时间 P4` * E.F.Codd 2. `何为关系 P7` * It is a basic concept of database. It is used to describe the relationship between data in the database. It is the relationship between entities. It describes the connection and interaction between entities. It can be one-to-one, one-to-many, and many-to-many. 3. `域 P9` * A domain is a collection of values ​​of the same data type 4. `笛卡尔积 P10 - P14` * Cartesian product is a set operation on the field 5. `关系和笛卡尔积的关系 P17,P19` * Relations are finite subsets of Cartesian products 6. `码 P18` * Code refers to a coding method used to represent specific data or entities, usually consisting of a set of numbers, letters or other symbols. 7. `三类关系 P20` * One-to-one: One-to-one relationship between two tables; * One-to-many: One-to-many relationship between two tables; * Many-to-many: refers to the many-to-many relationship between three tables or above; 8. `基本关系的性质 P22` * 1) The columns are homogeneous, that is, the components in each column are the same type of data and come from the same domain. * 2. Different columns can come from the same domain. Each column is called an attribute. Different attributes should be given different attribute names. * 3. The order of the columns does not matter, that is, the order of the columns can be exchanged arbitrarily. * 4. The candidate codes of any two tuples cannot have the same value. * 5. The order of rows does not matter, that is, the order of columns can be exchanged arbitrarily. * 6. The components must take on atomic values, that is, each component must be an indivisible data item. 9. `关系模式的定义 P26` * The description of a relationship is called a relationship description 10. `基本的关系操作 P36` * Query operations, two parts: insertion, deletion and modification operations * Query operations can be divided into selection, projection, connection, division, union, difference, intersection, and Cartesian product 11. `SQL的4大功能 P39` * Data definition, data query, data manipulation, data control 12. `三类完整性约束 P41` * Entity integrity, referential integrity, user-defined integrity 13. `实体完整性规则 P43 - P44` * If attribute (referring to one or a group of attributes) A ​​is the main attribute of basic relationship R, then A cannot take a null value 14. `外码 P50` * Suppose F is an attribute or a set of attributes of the basic relation R, but not the key of the relation R, and KS is the primary key of S. If F corresponds to KS, then F is said to be the foreign key of R, and the basic relationship R is called the reference relationship, and the basic relationship S is the referenced relationship or target relationship. 14. `参照完整性 P55 - P56` * Also known as referential integrity, it is a constraint between two related tables. 15. `用户定义的完整性 P60` * User-defined integrity is a constraint for a specific relational database, which reflects the semantic requirements that the data involved in a specific application must meet. 16. `关系代数运算符 P64` * Union, difference, intersection, Cartesian product and selection, projection, connection, division operation 17. `传统的集合运算 P66 - P74` * Union, difference, intersection, Cartesian product 18. `专门的关系运算(除运算除外) P85 - P103` * Selection, projection, concatenation, division operations 19. `关系运算符的运用 P110` * Learn by yourself # 3. SQL 1. `SQL的中文和英文 1P51` * Structured Query Language SQL 2. `SQL的功能和特点 1P55 - 1P61` * Comprehensive and unified, highly non-procedural, set-oriented operation mode, providing multiple usage methods with the same syntax structure, * Simple language, easy to learn and use * Data query, data manipulation, data definition, data control 3. `内模式/模式/外模式 与 存储文件/基本表/视图 之间概念关联 1P64 - 1P67` * External schema: also called sub-schema or user schema, is a description of the logical structure and characteristics of local data that users can see and use; * Schema: Also known as logical schema, it is a description of the logical structure and characteristics of all data in the database, and is a common data view of all data. * Internal schema: also called storage schema, is a description of the physical structure and storage method of the database, and is the way data is represented inside the database. * The data is provided to the user according to the description of the external mode and stored on the hard disk according to the description of the internal mode. The mode is between the external and internal modes and involves neither external access nor internal storage, thereby playing an isolation role and conducive to the independence of the data. The internal mode relies on the global logical structure, but can be independent of specific storage devices. * Basic table: an independent table; * View: a virtual table, which is a table derived from one or several basic tables; * The database only stores the definition of the view and not the data corresponding to the view. These data are still stored in the basic table of the derived view. When the data in the basic table changes, the data queried from the view also changes. 4. `数据定义的所有代码 1P74 - 1P99` * Create: create schema; create table; create view; create index; * Delete: drop schema; drop table; drop view; drop index; * Modify: alter table; alter index 5. `数据字典是什么 1P101` * The data dictionary is a set of system tables within the relational database management system. It records all definition information in the database, including relational schema definitions, view definitions, index definitions, integrity constraint definitions, operating permissions of various users on the database, statistical information, etc. 6. `单表查询 1P106 - 1P137` * Single table query refers to a query involving only one table 7. `连接查询 2P8 - 2P24` * If a query involves more than two tables at the same time, it is called a join query. 8. `嵌套查询(EXISTS除外) 2P26 - 2P48` * A SELECT-FROM-WHERE statement is called a query block, and a query that nests a query block in the conditions of the WHERE clause or HAVING phrase of another query block is called a nested query. * If the query conditions of a subquery depend on the parent query, it is called a related subquery, and the entire query statement is called a related nested query. * Otherwise, it is called an irrelevant subquery. 9. `集合查询 2P58 - 2P63` * Union operation: UNION, intersection operation: INTERSECT, difference operation: EXCEPT 10. `基于派生表的查询 2P65 - 2P66` * Subqueries can not only appear in the WHERE clause, but also in the FROM clause. At this time, the temporary derived table generated by the subquery becomes the query object of the main query. 11. `插入数据 3P6 - 3P13` * INSERT INTO (table name) VALUES (values) * INSERT INTO (table name) subquery 12. `修改数据 3P15 - 3P20` * UPDATE (table name) SET (column name) WHERE (condition) 13. `删除数据 3P22 - 3P27` * DELETE FROM (table name) WHERE (condition) 14. `Drop和DELETE的区别` * Drop is generally used to delete overall data, such as tables, schemas, indexes, views and integrity restrictions. * DELETE is used to delete local data, such as a tuple in a table 15. `空值相关 3P29 - 3P37` * The null value is a very special value that contains uncertainty. * Attribute definitions (domain definitions) with NOT NULL constraints cannot take null values, attributes with UNIQUE restrictions cannot take null values, and code attributes cannot take null values. 16. `视图的特点 3P39` * View: a virtual table, which is a table derived from one or several basic tables; * The database only stores the definition of the view and not the data corresponding to the view. These data are still stored in the basic table of the derived view. When the data in the basic table changes, the data queried from the view also changes. * 17. `建立视图 3P42 - 3P52` * CREATE VIEW (view name) AS (subquery) \[WITH CHECK OPTION] 18. `删除视图 3P53` * DROP VIEW (view name) \[CASCADE] * CASCADE can delete other views exported by this view. 19. `视图更新的限制 3P66 - 3P68` * 1) If the view is exported from more than two basic tables, this view is not allowed to be updated; * 2. If the fields of the view come from field expressions or constants, INSERT and UPDATE operations are not allowed on this view, but DELETE operations are allowed; * 3. If the fields of the view come from aggregate functions, this view is not allowed to be updated; * 4. If the view definition contains a GROUP BY statement, this view is not allowed to be updated; * 5. If the view definition contains the DISTINCT phrase, this view is not allowed to be updated; * 6. If there is a nested query in the view definition, and the table involved in the FROM clause of the inner query is also the basic table for exporting the view, this view is not allowed to be updated; * 7. A view defined on a view that is not allowed to be updated is not allowed to be updated. 20. `视图的作用 P72` * 1) Simplify user operations; * 2. Enable users to view the same data from multiple perspectives; * 3. Provides a certain degree of logical independence for reconstructing the database; * 4. Able to provide security protection for confidential data; * 5. Appropriate use of views can express queries more clearly. # 4. Database security 1. `数据库安全性问题的提出 P4` * Database security refers to protecting the database from data leakage, alteration or destruction caused by illegal use 2. `数据库的不安全因素 P8 - P11` * 1) Malicious access and damage to the database by unauthorized users; * 2. Important or sensitive data in the database is leaked; * 3. The vulnerability of the security environment; 3. `数据库安全性控制的流程 P35` * 1) User identification and authentication (static password authentication, dynamic password authentication, biometric authentication, smart card authentication); * 2. Access control (autonomous access control, mandatory access control); * 3. Authorization: grant and revoke (grant, revoke, permission to create database schema); * 4. Database roles (creation of roles, authorization of roles, granting a role to other roles or users, withdrawal of role permissions); 4. `用户身份鉴定的概念和方法 P38 - P43` * Static password authentication: * Dynamic password authentication: * Biometric authentication: * Smart card authentication: 5. `存取控制 P46` * The access control mechanism mainly includes two parts: defining user permissions and checking legal permissions; 6. `常用的两种存取控制方法 P47 - P48` * Autonomous access control: Users have different access permissions for different database objects, and different users also have different permissions for the same object. Users can also delegate their access permissions to other users, so autonomous access control is very flexible; * Mandatory access control: Each database object is marked with a certain confidentiality level, and each is subsequently granted a certain level of license. For any object, only users with legal licenses can access it, so mandatory access control is relatively strict. * 7. `权限授予的SQL代码 P54 - P68` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} GRANT(权限)ON(对象类型)(对象名)TO(用户)[WITH GRANT OPTION] ``` 8. `权限回收的SQL代码 P69 - P73` ```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}} REVOKE(权限)ON(对象类型)(对象名)FROM(用户)[CASCADE|RESTRICT] ``` 9. `数据库角色的概念 P76` * A database role is a named set of permissions related to database operations. A role is a collection of permissions. 10. `数据库角色的SQL代码 P77 - P83` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE ROLE(角色名); GRANT(权限)ON(对象类型)(对象名)TO(用户)[WITH GRANT OPTION]; REVOKE(权限)ON(对象类型)(对象名)FROM(用户)[CASCADE|RESTRICT] ``` `视图机制在安全性控制中的作用` * The view mechanism indirectly implements the user permission definition that supports access predicates. Through the view mechanism, the data to be kept confidential is hidden from users who do not have access rights, thereby automatically providing a certain degree of security protection for the data. # 5. Database integrity 1. `数据库完整性的概念 P4` * Database integrity refers to the correctness and compatibility of data; * The correctness of the data means that the data conforms to the semantics of the real world and reflects the current actual situation; * Data compatibility means that the data of the same object in the database in different relational tables is logical 2. `数据库完整性和安全性的异同 P5` * Data integrity is to prevent the existence of data that does not conform to semantics in the database, that is, to prevent the existence of incorrect data in the database; * Data security is to protect the database from malicious damage and illegal access. 3. `数据库管理系统如何维护数据库的完整性 P6 - P10` * 1) Provide a mechanism for defining integrity constraints; * 2. Provide methods for integrity checking; * 3. Handle breach of contract; 4. `实体完整性定义的代码 P13 - P16` ```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}} (列名)PRIMARY KEY; PRIMARY KEY(列名)(必须设置列名不为空值) ``` 6. `实体完整性的检查和违约处理 P18` Automatic check: 1. Check whether the main code value is unique. If not, reject insertion or modification; 2. Check whether each attribute of the main code is empty. As long as one of the attributes is empty, the insertion or modification will be refused. One way to check whether the primary code in the record is the only one is to scan the entire table and determine whether the primary code value of each record in the table is the same as the primary code value to be inserted into the record (or the modified new primary code value). 7. `参照完整性定义的代码 P24 - P25` * Referential integrity uses the FOREIGN KEY phrase in CREATE TABLE to define which columns are foreign keys, and the REFERENCES phrase is used to indicate which tables' primary keys these foreign keys refer to. ```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}} FOREIGN KEY(列名)REFERENCES (表名)(列名) ``` 8. `参照完整性的检查和违约处理 P27 - P35` * Reject (NO ACTION) execution: The change operation is not allowed to be executed. This policy is generally set as the default policy; * Cascade (CASCADE) operation: When deleting or modifying a tuple in the referenced table causes inconsistency with the reference table, delete or modify all tuples in the reference table that cause inconsistency. * Set to null: When deleting or modifying a tuple in the referenced table causes inconsistency, set the corresponding attributes of all tuples in the reference table that cause inconsistency to null. 9. `用户定义完整性 P40 - P50` * User-defined integrity is the semantic requirement that data for a specific application must meet. 1. **Constraints on attributes p163** 2. Definition of constraints on attributes 3. Checking and violation handling of constraints on attributes 4. **Constraints on tuples p163** 5. Definition of constraints on tuples 6. Checking and violating constraints on tuples 7. Integrity Constraint Named SQL P53 - P57 ```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}} CONSTRAINT(完整性约束条件名)(完整性约束条件) 完整性约束条件包括 NOT NULL,UNIQUE,PRIMARY KEY,FOREIGN KEY,CHECK短语 可以使用ALTER TABLE语句修改表中的完整性限制 ALTER TABLE Student DROP CONSTRAINT C4; ALTER TABLE Student ADD CONSTRAINT C1 CHECK(Sno BETWEEN 900000 AND 999999); ``` 10. `触发器的定义、激活与删除 P68 - P78` **Trigger** is a special type of [stored procedure](https://so.csdn.net/so/search?q=存储过程\&spm=1001.2101.3001.7020). Unlike a stored procedure, it is executed when triggered by an event rather than being called manually; a stored procedure must be invoked explicitly by name. [Trigger](https://so.csdn.net/so/search?q=触发器\&spm=1001.2101.3001.7020): a trigger is a piece of code bound to a table in advance. When certain content in the table changes (insert, delete, or update), the system automatically fires the code and executes it. ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} delimiter 自定义结束符号 create trigger 触发器名字 触发时间 触发事件 on 表 for each row begin -- 触发器内容主体,每行用分号结尾 end 自定义的结束符合 delimiter ; ``` * A trigger is a special event-driven process defined by the user on a relational table. * Definition of trigger P168 * The execution of a trigger is activated by a triggering event and is automatically executed by the database server. * 1. Execute the BEFORE trigger on the table 2. SQL statement to activate trigger 3. Execute the AFTER trigger on the table ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} 删除触发器的SQL语法:DROP TRIGGER(触发器名)ON(表名) ``` # 6. Relational Data Theory * Data dependency is a constraint relationship between the internal attributes of a relationship. This constraint relationship is a correlation between data reflected by the equality of values ​​between attributes. It is the abstraction of the interconnections between real-world attributes, the inherent nature of data, and the embodiment of semantics. 1. `现实世界已知语义得到的函数依赖 P13 - P14` * Functional dependency is a ubiquitous type of data dependency * Improper functional dependencies can cause many problems: * 1. Data redundancy * 2. Update exception * 3. Insertion exception * 4. Delete exceptions 2. `函数依赖 P22 - P26` * Functional dependency, like other data dependencies, is a semantic category concept, and a functional dependency can only be determined based on semantics. 3. `平凡函数依赖与非平凡函数依赖 P27 - P28` 4. `完全函数依赖与部分函数依赖 P29 - P30` 5. `传递函数依赖 P31` ![image-20230618223115913](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306182243473.png) 6. `1NF、2NF、3NF、BCNF的定义以及判断 P41 - P56,P81` **First Normal Form (1NF)** definition > (1NF, Normal Form) If the domain value of each attribute A in a relational schema R is atomic, that is, the attribute value cannot be subdivided, then the relational schema R belongs to the first normal form, abbreviated as R ∈ 1NF. If every relational schema in database schema R is 1NF, database schema R∈1NF. This is very easy to understand. Basically, as long as the question is given, it is a relationship model that satisfies the first paradigm. **Second Normal Form (2NF)** definition ![Second Normal Form](https://img-blog.csdnimg.cn/20181125213408784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NhbmRsZV9saWdodA==,size_16,color_FFFFFF,t_70) 2NF means that all non-primary attributes in our relational schema are completely dependent on each key. What does it mean? The most important thing here is to understand what `非主属性` is, what is `主属性`, what is `键` It is recommended to read the summary of another blog to understand the meaning of the key: [https://blog.csdn.net/fjxcsdn/article/details/76549751](https://blog.csdn.net/fjxcsdn/article/details/76549751) Read the blog I wrote before to understand the meaning of complete dependence and partial dependence: [Database Basics (3) Functional Dependency - Trivial Dependency, Complete Dependence, Partial Dependence, Transitive Dependence](https://blog.csdn.net/Candle_light/article/details/84424505) How should you understand non-primary attributes and primary attributes? For example, suppose the relation schema is `R={A,B,C,D}` and the candidate key of `R` is `AD`. Then `A` and `D` are primary attributes, while `B` and `C` are non-primary attributes. **`包含在候选键里的属性就是主属性!`** Now that we understand the meaning of keys and dependencies, we can take a closer look at what 2NF is. **`举例子1:`** > #### Given `R = {A, B, C}` and the functional dependency set `F = {B → C, AC → B}`, determine whether the relation schema is in 2NF So let’s first look at who the keys are in this R relational model. Use `数据库基础(4)中我们学习的属性闭包算法` to find the candidate key of R: AC So the **second step** is to see if there are any non-primary attributes that partially depend on the main attribute AC (our non-primary attribute here is B) Obviously no part of B depends on A or C, so R is 2NF **`举例子2`** > #### Given `R = {A, B, C, D}` and the functional dependency set `F = {A → C, AD → B}`, determine whether the relation schema is in 2NF Like the first example, we first see who the keys in R are Using the attribute closure algorithm, the candidate key of R is found to be: AD (AD+ = ABCD), so C and B are both non-primary attributes, and A and D are primary attributes. Therefore, it is obvious that we find that A in AD can independently determine C (A->C), so C partially depends on AC, there are non-primary attributes that partially depend on primary attributes, and R is not 2NF **Third Normal Form (3NF)** definition ![3NF](https://img-blog.csdnimg.cn/20181125213645372.png) The meaning of the third normal form is that **the key of `没有非主属性传递依赖` in R**, R is 3NF There is also a condition implicit here, that is, if `主属性传递依赖` in R is the key of R, then R also satisfies 3NF. **Be careful to distinguish between primary attribute transitive dependencies and non-primary attribute transitive dependencies** `举例子1` > #### Given `R(A, B, C)` and the functional dependency set `F = {B → C, AC → B}`, determine whether the relation schema is in 3NF Let's make a judgment. The first step is to find the key! We found that AC is a candidate key (AC+=ABC, a candidate key obtained through the attribute closure algorithm) At the same time, since AC->B, B->C, C transitively depends on AC. So is R 3NF? R is of course 3NF, because the candidate key of R is AC, so C is the primary attribute, so here is `主属性C` transitively dependent on the key AC, R is 3NF Notice! `只有当非主属性传递依赖于R的时候,R才不是3NF` `举例子2` > #### Given `R(A, B, C, D)` and the functional dependency set `F = {AB → C, C → D}`, determine whether the relation schema is in 3NF The first step is to find the key! It is found that AB is a candidate key, but since AB -> C, C -> D, D transitively depends on AB So is R 3NF? Of course R is not 3NF, because D is a non-primary attribute, so here the non-primary attribute D transitively depends on the primary attribute AB, so it does not meet the definition of 3NF. **`Boyce-Codd范式(BCNF)`** definition ![BCNF](https://img-blog.csdnimg.cn/20181125213719359.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NhbmRsZV9saWdodA==,size_16,color_FFFFFF,t_70) BCNF is the most advanced, it refers to `没有任何属性传递依赖于R中的任何一个键` in R. So think of Example 1 in our 3NF above. Although it satisfies 3NF, it is not BCNF because the main attribute transitively depends on the key. Look at the examples and determine which normal form it is. ![Example](https://img-blog.csdnimg.cn/20181125213738319.png) Obviously, both are BCNF, because there is no transitive dependency on any attribute. Finally, a relationship model that satisfies BCNF must also satisfy 3NF; similarly, a relationship model that satisfies 3NF must also satisfy 2NF. # 7. Database design 1. `数据库设计的概念 1P6` Database design refers to constructing (designing) an optimized database logical model and physical structure for a given application environment, and establishing a database and its application system accordingly so that it can effectively store and manage data and meet the application needs of various users, including information management system requirements and data operation requirements. 3. `数据库高效率的运行环境 1P7` Database data access efficiency, database storage space utilization, database system operation and management efficiency 4. `数据库设计的特点 1P10 - 1P12` Heuristic, iterative, multi-step, data-oriented 5. `数据库设计的基本步骤 1P18` * Requirements design * conceptual structural design * Logical structure design * physical structure design * Database implementation * Database operation and maintenance 6. `数据库设计各个阶段的数据设计描述 1P25` * P 209 7. `需求分析的任务 1P36 - 1P38` The task of requirements analysis is to fully understand the working profile of the original system (manual system or computer system) through detailed investigation of the objects to be dealt with in the real world (organizations, departments, enterprises, etc.), clarify the various needs of users, and then confirm the functions of the new system on this basis. The focus of the investigation is "data" and "processing". Through investigation, collection and analysis, the following user requirements for the database are obtained: * information request * processing request * Security and integrity requirements 8. `需求分析的方法 1P40` * Investigate the status of the organization * Investigate the business activities of various departments * Based on familiarity with business activities, assist users to clarify various requirements for the new system, including information requirements, processing requirements, security and integrity requirements * Determine the boundaries of the new system Common investigation methods: * Follow-up homework * Hold an investigation meeting * Please introduce someone * ask * Please fill in the design questionnaire * View records 9. `E-R模型的提出者 1P58` * P.P.S.Chen 10. `实体之间联系的类型 1P59 - 1P67` * Relationship between two entity types: one-to-one, one-to-many, many-to-many * The relationship between two or more entity types * Relationships within a single entity type 11. `E-R图 1P68 - 1P74` Rectangles are used for entities, ovals are used for attributes, and diamonds are used for relationships. 12. `实体与属性的划分原则 1P77` Treat as attributes as much as possible what can be treated as attributes 13. `E-R图的集成 1P87 - 1P94` * Merge and resolve conflicts between E-R diagrams * Modify and refactor to eliminate unnecessary redundancy * Conflict types: 1. Attribute conflict, 2. Naming conflict, 3. Structure conflict 14. `E-R图向关系模型的转换 2P7 - 2P13` * An entity type is converted into a relationship schema. The attributes of the relationship are the attributes of the entity, and the code of the relationship is the code of the entity. 15. `优化数据模型的方法 2P19` * Determine data dependencies * Minimize data dependencies between various relational schemas * Analyze the relationship patterns one by one according to the theory of data dependence * Based on the processing requirements obtained in the requirements analysis stage, analyze whether these patterns are suitable for such an application environment and determine whether certain patterns need to be merged or decomposed. * Perform necessary decomposition of the relational model to improve data operation efficiency and storage space utilization. Two commonly used decomposition methods are horizontal decomposition and vertical decomposition. 16. `数据库物理设计的步骤 2P32` * The process of selecting a physical structure that best suits application requirements for a given logical data model is the physical design of the database. * 1. Determine the physical structure of the database, which in relational databases mainly refers to the access method and storage structure. 2. Evaluate physical structures with emphasis on time and space efficiency 3. Common access methods of database management systems 2P39 * Index method and clustering method, B+ tree index and hash index P236 17. `影响数据存放位置和存储结构的因素 2P53` * Access time, storage space utilization, maintenance cost, hardware environment, application requirements # 8. Database Programming 1. `python关联MySQL的包(Package)是什么 P9` * PyMySQL 2. `游标的好处 P22` * A cursor is a data buffer opened by the system for users to store the execution results of SQL statements. Each cursor area has a name. * Users can obtain records one by one through the cursor and assign them to the main variable, which is then handed over to the main language for further processing. * After using the cursor function, we can save the results first, and then we can do our own programming at will to get the result set we ultimately want. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} Cursor = (数据库名).db.cursor ``` 3. `tornado web服务器的四大组件 P62-P63` * ioloop instance, app instance, handler class, routing table 4. `GET和POST的区别 P65` * The methods of passing parameters are different: Get includes the parameters in the URL, and Post passes the parameters through the request body; * URL visibility is different: the parameters of the get request can be seen directly, but the parameter URL of the post request is not visible; * The size of the data passed is different: the length of the data passed in the get request is limited by the URL size, while the post request has no length limit * The impact of going back on the page is different: going back on get will not have any impact, but going back on post will resubmit; * Different encoding methods: get requests only support URL encoding, while post requests support multiple encoding methods; 5. `SQL 变量的定义 P73 - P76` In SQL, a variable is a container used to store data 6. `流程控制 P80 - P97` * Flow control statements can be used in stored procedures and custom functions to control the flow of the program. ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} 流程控制语句: IF 语句; CASE语句; LOOP语句; LEAVE语句; ITERATE语句; REPEAT语句; WHILE语句; ``` 7. `匿名块与命名块 P100` * Anonymous block: It must be compiled every time it is executed. It cannot be stored in the database and cannot be called in other procedural SQL blocks; * Named block: After compilation, it is saved in the database and is called a persistent storage module. It can be called repeatedly and runs faster. Procedures and functions are named blocks. 8. `存储过程的定义 P102` * A stored procedure is a database object that stores complex programs in the database so that they can be called by external programs. 9. `存储过程的优点 P103` * High efficiency when traveling far away * Reduced communication volume between client and server * Facilitate implementation of corporate rules 10. `存储过程的缺点 P104` * Stored procedures are often customized to a specific database because of the different supported programming languages. When switching to a database system from another manufacturer, the original stored procedures need to be rewritten. * Performance tuning and writing of stored procedures, limited by various database systems 11. `存储过程的SQL代码 P107 - P117` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} 创建存储过程:CREATE PROCEDURE (过程名)(参数)(过程化SQL块) 声明语句结束符,可以自定义:DELIMITER $$或DELIMITER// DELIMITER $$ CREATE PROCEDURE delete_sno ( IN p_sno CHAR(9)) BEGIN DELETE FROM Student WHERE sno = p_sno ; END$$ DELIMITER ; 执行存储过程:CALL(过程名)(参数) CALL delete__sno(‘201215122’); 删除存储过程:DROP PROCEDURE(过程名) ``` 12. `函数与存储过程的异同 P119` * Same: both are persistent storage modules * Exception: The function must specify the return type 13. `函数的SQL代码 P120 - P122` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} 1.定义语句格式:CREATE FUNCTION (函数名)(参数)RETURN(类型)(过程化SQL块) DELIMITER // CREATE FUNCTION func_student ( f_Sno CHAR(9)) RETURNS CHAR(20) DETERMINISTIC COMMENT ’ 查 询 某 个 学 生 的 姓 名 ’ BEGIN RETURN (SELECT Sname FROM Student WHERE Sno = f_Sno ) ; END // DELIMITER ; 2.函数的执行语句格式:SELECT(函数名)(参数) SELECT func_student(‘201215123’); SELECT func_student(sno) FROM Stduent; 3.删除函数:DROP FUNCTION(函数名) ``` # 9. MySQL optimization principles 1. `MySQL各组件之间协同工作的逻辑架构 P6 - P9` * 9-MySQL optimization principles.pdf 2. `MySQL的查询过程 P12,P38` * 1) Client/server communication protocol * 2. Query cache * 3. Grammar parsing and preprocessing * 4. Query optimization * 5. Query execution engine * 6. Return the results to the client # 10. Database recovery technology 1. `事务的概念 P7` * A transaction is a user-defined database operating system sequence. These operations are either done or not done at all. It is an indivisible unit of work; * Transaction is the basic unit of database recovery and concurrency control 2. `事务的显示控制 P8 - P9` * 10-Database recovery technology.pdf 3. `事务的ACID特性 P13 - P19` * Atomicity: A transaction is a logical unit of work in the database, either all are done or none are done; * Consistency: The result of transaction execution must be to change the database from one consistency state to another consistency state; * Isolation: The execution of a transaction cannot be interfered with by other transactions; * Continuity: Continuity is also called permanence. Once a transaction is committed, its changes to the data in the database should be permanent, and subsequent other operations or failures should not have any impact on its execution results. 4. `数据库恢复的背景和原因 P21` * Failures are inevitable: * 1. Computer hardware failure; 2. software errors; 3. operator error 4. malicious destruction * Impact of failure: * 1. Abnormal interruption of running transactions affects the correctness of data in the database 2. Corruption of the database, complete or partial loss of data 5. `数据库恢复的概念 P22` * Database recovery: Database management must have the function of restoring the database from an error state to a known correct state (also known as a consistent state or a complete state). This is the database recovery management system's response to failures; the recovery subsystem is an important part of the database management system; recovery technology is an important indicator to measure the quality of the system. 6. `故障的种类 P24 - P38` * Failure within the accident * System failure * media failure * computer virus 7. `恢复机制的两个关键问题 P40` * How to create redundant data (1. Data dump 2. Register log file 3. Both are often used together) * How to use these redundant data to implement database recovery 8. `数据转储的概念 P43 - P44` * Data dump is the basic technique used in database recovery * Dumping is a process in which the database administrator periodically copies the entire database to tape, disk, or other storage media. * These spare data texts are called backup copies or fallback copies 9. `数据转储的方法 P47 - P52` * Static dump and dynamic dump * Mass dump and incremental dump * Summary of dump methods (dynamic mass dump, static mass dump, dynamic incremental dump, static incremental dump) 10. `日志文件的概念 P55` * Log files are files used to record transactions and database update operations. 11. `以记录为单位的日志文件内容 P56 - P57` * Start tag of each transaction * End mark of each transaction * All update operations for each transaction * Here the start mark of each transaction, the end mark of each transaction and each update operation are treated as a log record in the log file Log record content: 1. Transaction ID 2. Operation type 3. Operation object 4. The old value of the data before updating 5. The new value of the updated data 6. `以数据块为单位的日志文件内容 P58` * transaction mark * updated data block 13. `日志文件的作用 P59 - P61` * Perform transaction failure recovery * Perform system failure recovery * Assists standby copies with media failure recovery 14. `登记日志文件的原则 P63` 15. The order of registration is strictly based on the time order of concurrent transaction execution. 16. The log file must be written first and then the database. * (Write log file operation: write the log record representing this modification to the log file; * Write database operation: write the modifications to the data into the database; ​ This is the principle of "write the log file first") 15. `先写日志文件的原因 P64` * Writing to the database and writing to the log are two different operations * A failure may occur between these two operations * If the database modification is written first and the modification is not registered in the log file, the modification cannot be restored later. * If the log is written first, but the database is not modified, restoring based on the log file will only perform one more unnecessary UNDO operation, which will not affect the correctness of the database. * Therefore, for safety, you must write the log file first, that is, first write the log records to the log file, and then write the modifications to the database. 16. `事务故障的恢复方法 P67` * Modifications that have been made to the database by this transaction are undoed (UNDO) by the recovery subsystem using the log file. 17. `事务故障恢复的步骤 P68 - P69` * Scan the file log in reverse direction (that is, scan the log file from the end forward) to find the update operation of the transaction * Performs the reverse operation of the transaction's update operation. That is, writing the "pre-update value" in the log record to the database * (Insertion operation: If the "value before update" is empty, it is equivalent to a delete operation; * Delete operation: If the "updated value" is empty, it is equivalent to an insertion operation; * If it is a modification operation, it is equivalent to replacing the modified value with the pre-modified value) 18. `系统故障的恢复方法 P71` 1. Undo (undo) the unfinished transaction when the failure occurred; 2. Redo (redo) completed transactions 19. `系统故障的恢复步骤 P72 - P73` 1. Scan the log file forward (that is, scan the log file from the beginning) to find transactions that were committed before the failure occurred 2. Undo (UNDO) processing of undo (UNDO) queue transactions 3. Redo (REDO) processing of redo (REDO) queue transactions 20.`介质故障的恢复方法 P75` 1. Reinstall database 2. Redo completed transactions 3. `介质故障的恢复步骤 P76 - P77` 4. Load the latest standby database copy (the dump copy closest to the time of the failure) to restore the database to the consistency state of the latest dump 5. Load a copy of the relevant log file (a copy of the log file at the end of the dump) and redo the completed transaction 6. `为什么要具有检查点的恢复技术 P81` 7. Searching the entire log will take a lot of time 8. Many transactions that need to be redone have actually written the results of their update operations to the database, but the recovery subsystem has to re-perform these operations, which wastes a lot of time. # Databases Source: https://base.bangwu.me/backend/SQL/index Database technology hub covering MySQL relational database operations, SQLite embedded usage, and core concepts like normalization and ACID. MySQL is the most popular open-source relational database, widely used in web applications. ## Core Features * **High Performance**: Optimized query engine * **Reliability**: ACID transaction support * **Scalability**: Master-slave replication, sharding * **Free & Open Source**: Community edition is fully free > [card] [MySQL Basics](/backend/SQL/mysql) > > SQL syntax reference — CRUD to advanced queries. > [card] [Database Concepts](/backend/SQL/db-knowledge) > > Core concepts — indexes, transactions, normalization. > [card] [SQLite](/backend/SQL/sqlite) > > Lightweight embedded database for small apps. ## Resources * [MySQL Official Docs](https://dev.mysql.com/doc/) * Visualization tools: Navicat, DBeaver, MySQL Workbench # MySQL Source: https://base.bangwu.me/backend/SQL/mysql MySQL learning notes covering CREATE/INSERT/UPDATE/DELETE statements, single and multi-table queries, index optimization, and user permissions. # First introduction to database ## What is a database > **Database: DB (DataBase)** **Concept**: Data warehouse, `软件`, installed on the operating system **Function**: Store data, manage data *** ## Database classification **Relational database: SQL** (Structured Query Language) * MySQL, Oracle, Sql Server, DB2, SQLlite * Store data through relationships between tables and between rows and columns * Establish relationships between tables through foreign key associations **Non-relational database: NoSQL** (Not Only SQL) * Redis, MongoDB * Refers to data stored in the database in the form of **objects**, and the relationship between objects is determined by the properties of each object itself *** ## Related concepts > **DBMS (Database Management System)** * Database management software\*\*, scientific and effective management, maintenance and acquisition of our data * **MySQL** is a database management system ![image-20200718152213413](https://img-blog.csdnimg.cn/img_convert/6ca15d7eee443107638939952d09ed79.png) *** ## MySQL and its installation * [MySQL latest version 8.0.21 installation and configuration tutorial\~](https://bareth.blog.csdn.net/article/details/107369405) ## Basic commands > All statements must end with a semicolon; ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} show databases; -- 查看当前所有的数据库 use 数据库名; -- 打开指定的数据库 show tables; -- 查看所有的表 describe/desc 表名; -- 显示表的信息 create database 数据库名; -- 创建一个数据库 exit -- 退出连接 ``` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- -- 单行注释 # -- 单行注释 /*...*/ -- 多行注释 ``` \#Operation database \##Operation database ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 创建数据库 CREATE DATABASE [IF NOT EXISTS] 数据库名; CREATE SCHEMA -- 删除数据库 DROP DATABASE [if EXISTS] 数据库名; DROP SCHEMA -- 使用数据库 -- 如果表名或者字段名是特殊字符,则需要带`` use 数据库名; -- 查看数据库 SHOW DATABASES; ``` ## Database column type > **Value** | `数据类型` | `描述` | `大小` | | :-: | :-: | :-: | | tinyint | very small data | 1 byte | | smallint | smaller data | 2 bytes | | mediumint | medium size data | 3 bytes | | int | standard integer | 4 bytes | | bigint | Larger data | 8 bytes | | float | floating point number | 4 bytes | | double | floating point number | 8 bytes | | decimal | Floating point number in string form, generally used for financial calculations | | > string | `数据类型` | `描述` | `大小` | | :-: | :-: | :-: | | char | String fixed size | 0\~255 | | varchar | variable string | 0\~65535 | | tinytext | tiny text | 2^8-1 | | text | text string | 2^16-1 | > Time and date | `数据类型` | `描述` | `格式` | | :-: | :-: | :-: | | date | date format | YYYY-MM-DD | | time | time format | HH: mm: ss | | datetime | The most commonly used time format | YYYY-MM-DD HH: mm: ss | | timestamp | Timestamp, number of milliseconds from 1970.1.1 to now | | | year | Year representation | | > null * no value, unknown * Do not use NULL values for calculations ## Database field attributes > **UnSigned** * unsigned * Declared that the column cannot be negative > ZEROFILL * 0 padded * Fill the missing digits with 0, such as int(3), 5 is 005 > **Auto\_InCrement** * Usually understood as auto-increment, it automatically defaults to +1 based on the previous record. * Usually used to design a unique primary key, which must be an integer type * Definable starting value and step size * Current table setting step size (AUTO\_INCREMENT=100): only affects the current table * SET @@auto\_increment\_increment=5 ; affects all tables using auto-increment (global) > **NULL and NOT NULL** * The default is NULL, that is, no value is inserted into the column * If set to NOT NULL, the column must have a value > **DEFAULT** * default * used to set default values * For example, the gender field defaults to "male", otherwise it is "female"; if the value of this column is not specified, the default value is the value of "male" **Extension**: Every table must have the following five fields: | Name | Description | | :-: | :-: | | id | primary key | | version | optimistic locking | | is\_delete | Pseudo delete | | gmt\_create | Creation time | | gmt\_update | modification time | ## Create database table ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE IF NOT EXISTS `student`( `id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号', `name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名', `pwd` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码', `sex` VARCHAR(2) NOT NULL DEFAULT '女' COMMENT '性别', `birthday` DATETIME DEFAULT NULL COMMENT '出生日期', `address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址', `email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`id`) )ENGINE=INNODB DEFAULT CHARSET=utf8 ``` `注意点`: * Try to use \`\` brackets in table names and fields. * AUTO\_INCREMENT represents automatic increment * Add commas after all statements, except the last one. * Strings are enclosed in single quotes * The declaration of the primary key is generally placed at the end for easy viewing. * If the character set encoding is not set, MySQL's default character set encoding Latin1 will be used. Chinese is not supported and can be modified in my.ini. > Format: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE IF NOT EXISTS `student`( '字段名' 列类型 [属性] [索引] [注释], '字段名' 列类型 [属性] [索引] [注释], ...... '字段名' 列类型 [属性] [索引] [注释] )[表的类型][字符集设置][注释] ``` `常用命令` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SHOW CREATE DATABASE 数据库名;-- 查看创建数据库的语句 SHOW CREATE TABLE 表名;-- 查看表的定义语句 DESC 表名;-- 显示表的具体结构 ``` ## Database storage engine **INNODB** * Used by default, has high security, supports transaction processing, and multi-table and multi-user operations **MYISAM** * Used in earlier years, saving space and faster | | MYISAM | INNODB | | - | - | - | | **Transaction support** | Not supported | Supported | | **Data Row Locking** | Not supported | Supported | | **Foreign key constraints** | Not supported | Supported | | **Full text index** | Supported | Not supported | | **Table space size** | Smaller | Larger, about 2 times | > **Physical space location where the database file exists**: * MySQL data tables are stored on disk as files -Including table files, data files, and database option files * Location: `Mysql安装目录\data\` (the directory name corresponds to the database name, and the file name in this directory corresponds to the data table) ![](https://img-blog.csdnimg.cn/img_convert/1946b76c983e11c85ab1b71a89158eb0.png) **MySQL differs in file engine:** * `INNODB`Database file types include **.frm**, **.ibd** and **ibdata1** files in the upper-level directory * MYISAM storage engine, database file types include * **.frm**: table structure definition file * **.MYD**: data file * **.MYI**: index file ## Modify database > **Modify** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 修改表名 -- ALTER TABLE 旧表名 RENAME AS 新表名 ALTER TABLE teacher RENAME AS teachers; -- 增加表的字段 -- ALTER TABLE 表名 ADD 字段名 列属性 ALTER TABLE teachers ADD age INT(11); -- 修改表的字段(重命名,修改约束) -- ALTER TABLE 表名 MODIFY 字段名 [列属性]; ALTER TABLE teachers MODIFY age VARCHAR(11);-- 修改约束 -- ALTER TABLE 表名 CHANGE 旧名字 新名字 [列属性]; ALTER TABLE teachers CHANGE age age1 INT(1);-- 字段重命名 -- 删除表的字段 -- ALTER TABLE 表名 DROP 字段名 ALTER TABLE teachers DROP age1; ``` > **DELETE** **Syntax**: DROP TABLE \[IF EXISTS] table name * IF EXISTS is optional to determine whether the data table exists * If you delete a non-existent data table, an error will be thrown. ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 删除表(如果存在再删除) DROP TABLE IF EXISTS teachers; ``` **All creation and deletion should be judged as much as possible to avoid errors\~** \#MySQLData Management ## Foreign keys > **Foreign Key Concept** If a common key is the primary key in one relationship, then the common key is called a foreign key in another relationship. It can be seen that the foreign key represents the interconnection between the relationships between two people. The table with the foreign key of another relationship as the primary key is called `主表`,具有此外键的表被称为主表的`从表`. In actual operation, the value of one table is put into the second table to represent the association, and the value used is the primary key value of the first table (including the composite primary key value if necessary). At this point, the attribute in the second table that holds these values ​​is called the foreign key (`foreign key`). **Foreign key function**: Maintain data `一致性`,`integrity`,主要目的是控制存储在外键表中的数据,`constraint`. To associate two tables, the foreign key can only refer to the values ​​of columns in the table or use null values. *** Target: The gradeid field of the student table (student) is to reference the gradeid field of the grade table (grade). > **Create foreign key** **Method 1: Add constraints when creating the table** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} /* 1. 定义外键key 2. 给外键添加约束(执行引用)references 引用 */ CREATE TABLE IF NOT EXISTS `student`( `id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号', `name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名', `pwd` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码', `sex` VARCHAR(2) NOT NULL DEFAULT '女' COMMENT '性别', `birthday` DATETIME DEFAULT NULL COMMENT '出生日期', `address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址', `email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱', `gradeid` INT(10) NOT NULL COMMENT '学生的年级', PRIMARY KEY (`id`), KEY `FK_gradeid` (`gradeid`), CONSTRAINT `FK_gradeid` FOREIGN KEY (`gradeid`) REFERENCES `grade`(`gradeid`) )ENGINE=INNODB DEFAULT CHARSET=utf8 -- 创建年级表 CREATE TABLE `grade`( `gradeid` INT(10) NOT NULL COMMENT '年级id', `gradename` VARCHAR(50) NOT NULL COMMENT '年纪名称', PRIMARY KEY (`gradeid`) )ENGINE=INNODB DEFAULT CHARSET=utf8 ``` When deleting a table with a foreign key relationship, you must first delete the table that refers to someone else (slave table), and then delete the referenced table (master table) *** **Method 2: After successfully creating the table, add foreign key constraints** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} /* 1. 定义外键key 2. 给外键添加约束(执行引用)references 引用 */ CREATE TABLE IF NOT EXISTS `student`( `id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号', `name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名', `pwd` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码', `sex` VARCHAR(2) NOT NULL DEFAULT '女' COMMENT '性别', `birthday` DATETIME DEFAULT NULL COMMENT '出生日期', `address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址', `email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱', `gradeid` INT(10) NOT NULL COMMENT '学生的年级', PRIMARY KEY (`id`) )ENGINE=INNODB DEFAULT CHARSET=utf8 -- 创建表的时候没有外键关系 ALTER TABLE `student` ADD CONSTRAINT `FK_gradeid` FOREIGN KEY(`gradeid`) REFERENCES `grade`(`gradeid`); -- 创建年级表 CREATE TABLE `grade`( `gradeid` INT(10) NOT NULL COMMENT '年级id', `gradename` VARCHAR(50) NOT NULL COMMENT '年纪名称', PRIMARY KEY (`gradeid`) )ENGINE=INNODB DEFAULT CHARSET=utf8 ``` The above operations are all physical foreign keys, database-level foreign keys, and are not recommended! Avoid trouble caused by too many databases! `最佳实践` * The database is a simple table, only used to store data, only rows (data) and columns (attributes) * We want to use data from multiple tables, use foreign keys, and implement it with programs *** ## DML language `数据库的意义`:Data storage, data management > `Data Manipulation Luaguge`: Database operation language ### 1. Add [insert](https://so.csdn.net/so/search?q=insert\&spm=1001.2101.3001.7020) ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 普通用法 INSERT INTO `student`(`name`) VALUES ('zsr'); -- 插入多条数据 INSERT INTO `student`(`name`,`pwd`,`sex`) VALUES ('zsr','200024','男'),('gcc','000421','女'); -- 省略字段 INSERT INTO `student` VALUES (5,'Bareth','123456','男','2000-02-04','武汉','1412@qq.com',1); 12345678 ``` **grammar:** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} INSERT INTO 表名([字段1,字段2..])VALUES('值1','值2'..),[('值1','值2'..)..]; ``` **Notice**: 1. Use commas to separate fields. 2. Fields can be omitted, but the values must be complete and one-to-one correspondence 3. Multiple pieces of data can be inserted at the same time. The values after VALUES need to be separated by commas. *** ### 2. Modify update ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 修改学员名字,指定条件 UPDATE `student` SET `name`='zsr204' WHERE id=1; -- 不指定条件的情况,会改动所有表 UPDATE `student` SET `name`='zsr204'; -- 修改多个属性 UPDATE `student` SET `name`='zsr',`address`='湖北' WHERE id=1; -- 通过多个条件定位数据 UPDATE `student` SET `name`='zsr204' WHERE `name`='zsr' AND `pwd`='200024'; 1234567891011 ``` **grammar**: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} UPDATE 表名 SET 字段1=值1,[字段2=值2...] WHERE 条件[]; ``` **About WHERE conditional statements**: | Operator | Meaning | | - | - | | `=` | equal to | | `<>` or `!=` | Not equal to | | `>` | Greater than | | `<` | Less than | | `<=` | Less than or equal to | | `>=` | Greater than or equal to | | `BETWEEN…AND…` | Closed interval | | `AND` | and | | `OR` | or | *** ### 3. Delete delete ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 删除数据(避免这样写,会全部删除) DELETE FROM `student`; -- 删除指定数据 DELETE FROM `student` WHERE id=1; ``` **grammar**: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} DELETE FROM 表名 [WHERE 条件] ``` Regarding the problem of deleting `DELETE` and restarting the database: * INNODB auto-increment columns will start from 1 (stored in memory and lost when power is turned off) * MYISAM continues from the previous sub-increment (stored in memory and will not be lost) > TRUNCATE **Function**: Completely clear a database table, the structure and index constraints of the table will not change! **The difference between DELETE and TRUNCATE:** * DELETE can delete conditionally (where clause), while TRUNCATE can only delete the entire table * TRUNCATE resets the auto-increment column and the counter will return to zero, while DELETE will not affect the auto-increment * DELETE is a data manipulation language (DML - Data Manipulation Language). During the operation, the original data will be placed in the rollback segment and can be rolled back; while TRUNCATE is a data definition language (DDL - Data Definition Language). It will not be stored during the operation and cannot be rolled back. ![image-20210418210712785](https://img-blog.csdnimg.cn/img_convert/b4b2c1e383fc8bd2f0b1e4a4eddc080f.png) ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE `test`( `id` INT(4) NOT NULL AUTO_INCREMENT, `coll` VARCHAR(20) NOT NULL, PRIMARY KEY (`id`) )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO `test`(`coll`) VALUES('1'),('2'),('3'); -- 不会影响自增 DELETE FROM `test`; -- 会影响自增 TRUNCATE TABLE `test`; ``` *** # DQL query data > `Data QueryLanguage`: Data query language ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SELECT [ALL | DISTINCT] {* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,...]]} FROM table_name [as table_alias] [left | right | inner join table_name2] -- 联合查询 [WHERE ...] -- 指定结果需满足的条件 [GROUP BY ...] -- 指定结果按照哪几个字段来分组 [HAVING] -- 过滤分组的记录必须满足的次要条件 [ORDER BY ...] -- 指定查询记录按一个或多个条件排序 [LIMIT {[offset,]row_count | row_countOFFSET offset}]; -- 指定查询的记录从哪条至哪条 ``` * Query database data, such as SELECT statements * Simple single table query or complex query and nested query of multiple tables * It is the core and most important statement in the database language * Most frequently used statements `前提配置`: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 创建学校数据库 CREATE DATABASE IF NOT EXISTS `school`; -- 用school数据库 USE `school`; -- 创建年级表grade表 CREATE TABLE `grade`( `GradeID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '年级编号', `GradeName` VARCHAR(50) NOT NULL COMMENT '年纪名称', PRIMARY KEY (`GradeID`) )ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- 给grade表插入数据 INSERT INTO `grade`(`GradeID`,`GradeName`) VALUES (1,'大一'),(2,'大二'),(3,'大三'),(4,'大四'); -- 创建成绩result表 CREATE TABLE `result`( `StudentNo` INT(4) NOT NULL COMMENT '学号', `SubjectNo` INT(4) NOT NULL COMMENT '考试编号', `ExamDate` DATETIME NOT NULL COMMENT '考试日期', `StudentResult` INT(4) NOT NULL COMMENT '考试成绩', KEY `SubjectNo` (`SubjectNo`) )ENGINE=INNODB DEFAULT CHARSET=utf8; -- 给result表插入数据 INSERT INTO `result`(`StudentNo`,`SubjectNo`,`ExamDate`,`StudentResult`) VALUES (1000,1,'2019-10-21 16:00:00',97),(1001,1,'2019-10-21 16:00:00',96), (1000,2,'2019-10-21 16:00:00',87),(1001,3,'2019-10-21 16:00:00',98); -- 创建学生表student CREATE TABLE `student`( `StudentNo` INT(4) NOT NULL COMMENT '学号', `LoginPwd` VARCHAR(20) DEFAULT NULL, `StudentName` VARCHAR(20) DEFAULT NULL COMMENT '学生姓名', `Sex` TINYINT(1) DEFAULT NULL COMMENT '性别,取值0或1', `GradeID` INT(11) DEFAULT NULL COMMENT '年级编号', `Phone` VARCHAR(50) NOT NULL COMMENT '联系电话,允许为空,即可选输入', `Adress` VARCHAR(255) NOT NULL COMMENT '地址,允许为空,即可选输入', `BornDate` DATETIME DEFAULT NULL COMMENT '出生时间', `Email` VARCHAR(50) NOT NULL COMMENT '邮箱账号,允许为空,即可选输入', `IdentityCard` VARCHAR(18) DEFAULT NULL COMMENT '身份证号', PRIMARY KEY (`StudentNo`), UNIQUE KEY `IdentityCard` (`IdentityCard`), KEY `Email` (`Email`) )ENGINE=MYISAM DEFAULT CHARSET=utf8; -- 给学生表插入数据 INSERT INTO `student`(`StudentNo`,`LoginPwd`,`StudentName`,`Sex`,`GradeID`,`Phone`,`Adress`,`BornDate`,`Email`,`IdentityCard`) VALUES (1000,'1241','dsaf',1,2,'24357','unknow','2000-09-16 00:00:00','1231@qq.com','809809'), (1001,'1321','dfdj',0,2,'89900','unknow','2000-10-16 00:00:00','5971@qq.com','908697'); -- 创建科目表 CREATE TABLE `subject`( `SubjectNo` INT(11) NOT NULL AUTO_INCREMENT COMMENT '课程编号', `SubjectName` VARCHAR(50) DEFAULT NULL COMMENT '课程名称', `ClassHour` INT(4) DEFAULT NULL COMMENT '学时', `GradeID` INT(4) DEFAULT NULL COMMENT '年级编号', PRIMARY KEY (`SubjectNo`) )ENGINE=INNODB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8; -- 给科目表subject插入数据 INSERT INTO `subject`(`SubjectNo`,`SubjectName`,`ClassHour`,`GradeID`) VALUES(1,'高数','96',2),(2,'大物','112',2),(3,'程序设计',64,3); SELECT 字段 FROM 表; ``` ## **Basic Query** `语法`: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SELECT 查询列表 FROM 表名; ``` * The query list can be: (one or more) fields in the table, constants, variables, expressions, functions * The query result is a virtual table ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 查询全部学生 SELECT * FROM student; -- 查询指定的字段 SELECT `LoginPwd`,`StudentName` FROM student; -- 别名 AS(可以给字段起别名,也可以给表起别名) SELECT `StudentNo` AS 学号,`StudentName` AS 学生姓名 FROM student AS 学生表; -- 函数 CONCAT(str1,str2,...) SELECT CONCAT('姓名',`StudentName`) AS 新名字 FROM student; -- 查询系统版本(函数) SELECT VERSION(); -- 用来计算(计算表达式) SELECT 100*53-90 AS 计算结果; -- 查询自增步长(变量) SELECT @@auto_increment_increment; -- 查询有哪写同学参加了考试,重复数据要去重 SELECT DISTINCT `StudentNo` FROM result; ``` ## Query conditions > where conditional statement: retrieve the value of `符合条件` in the data **grammar**: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} select 查询列表 from 表名 where 筛选条件; ``` ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 查询考试成绩在95~100之间的 SELECT `StudentNo`,`StudentResult` FROM result WHERE `StudentResult`>=95 AND `StudentResult`<=100; -- && SELECT `StudentNo`,`StudentResult` FROM result WHERE `StudentResult`>=95 && `StudentResult`<=100; -- BETWEEN AND SELECT `StudentNo`,`StudentResult` FROM result WHERE `StudentResult`BETWEEN 95 AND 100; -- 查询除了1000号以外的学生 SELECT `StudentNo`,`StudentResult` FROM result WHERE `StudentNo`!=1000; -- NOT SELECT `StudentNo`,`StudentResult` FROM result WHERE NOT `StudentNo`=1000; -- 查询名字含d的同学 SELECT `StudentNo`,`StudentName` FROM student WHERE `StudentName` LIKE '%d%'; -- 查询名字倒数第二个为d的同学 SELECT `StudentNo`,`StudentName` FROM student WHERE `StudentName` LIKE '%d_'; -- 查询1000,1001学员 SELECT `StudentNo`,`StudentName` FROM student WHERE `StudentNo` IN (1000,1001); ``` ## Group query `语法`: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} select 分组函数,分组后的字段 from 表 【where 筛选条件】 group by 分组的字段 【having 分组后的筛选】 【order by 排序列表】 ``` `区别`: \| | table filtered using keywords | location | \| ---------- | ---------- | ---------- | --------------- | \| Filter before grouping | where | original table | before group by | \| Filtering after grouping | having | results after grouping | behind group by | ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 查询不同科目的平均分、最高分、最低分且平均分大于90 -- 核心:根据不同的课程进行分组 SELECT SubjectName,AVG(StudentResult),MAX(`StudentResult`),MIN(`StudentResult`) FROM result r INNER JOIN `subject` s on r.SubjectNo=s.SubjectNo GROUP BY r.SubjectNo HAVING AVG(StudentResult)>90; ``` ## Connection query ![image-20200718231304641](https://img-blog.csdnimg.cn/img_convert/6354aff6ecaee8ec2f2f7ec065304889.png) ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 查询学员所属的年级(学号,学生姓名,年级名称) SELECT `StudentNo`,`StudentName`,`GradeName` FROM student s INNER JOIN grade g ON s.GradeID=g.GradeID; -- 查询科目所属的年级 SELECT `SubjectName`,`GradeName` FROM `subject` s INNER JOIN `grade` g ON s.GradeID=g.GradeID; -- 查询列参加程序设计考试的同学信息(学号,姓名,科目名,分数) SELECT s.`StudentNo`,`StudentName`,`SubjectName`,`StudentResult` FROM student s INNER JOIN result r on s.StudentNo=r.StudentNo INNER JOIN `subject` sub on r.SubjectNo=sub.SubjectNo where SubjectName='课程设计'; ``` > **Self link** Your own table and your own table link, core: **One table can be split into two identical tables** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 创建一个表 CREATE TABLE `course` ( `courseid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '课程id', `pid` INT(10) NOT NULL COMMENT '父课程id', `courseName` VARCHAR(50) NOT NULL COMMENT '课程名', PRIMARY KEY (`courseid`) ) ENGINE=INNODB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 -- 插入数据 INSERT INTO `course` (`courseid`, `pid`, `courseName`) VALUES('2','1','信息技术'), ('3','1','软件开发'), ('4','3','数据库'), ('5','1','美术设计'), ('6','3','web开发'), ('7','5','ps技术'), ('8','2','办公信息'); ``` Split the table: | pid (parent course id) | courseid (course id) | courseName (course name) | | - | - | - | | 1 | 2 | Information Technology | | 1 | 3 | Software Development | | 1 | 5 | Art Design | | pid (parent course id) | courseid (course id) | courseName (course name) | | - | - | - | | 2 | 8 | Office Information | | 3 | 4 | Database | | 3 | 6 | web development | | 5 | 7 | ps technology | **Operation**: Query the subclass relationship corresponding to the parent class | Parent class | Subclass | | - | - | | Information Technology 2 | Office Information 4 | | Software development 3 | Database 4, web development 6 | | Art Design 5 | PS Technology 7 | ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SELECT a.`courseid` AS '父课程',b.`courseid` AS '子课程' FROM course AS a,course AS b WHERE a.`courseid`=b.`pid`; ``` ![image-20200719105147906](https://img-blog.csdnimg.cn/img_convert/149c6d4bfdaea45e0a66af888e3f304c.png) ## Sorting and paging > **Sort** `语法`: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} select 查询列表 from 表 where 筛选条件 order by 排序列表 asc/desc ``` * The position of order by is generally placed at the end of the query statement (except for the limit statement) | asc: | Ascending order, if not written, the default ascending order | | - | - | | **desc:** | **descending** | ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SELECT `StudentNo`,`StudentName`,`GradeName` FROM student s INNER JOIN grade g ON s.GradeID=g.GradeID ORDER BY `StudentNo` DESC; ``` > **Page** `语法`: ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} select 查询列表 from 表 limit offset,pagesize; ``` * offset represents the starting entry index, starting from 0 by default * size represents the number of items displayed * offset=(n-1)\*pagesize ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 第一页 limit 0 5 -- 第二页 limit 5,5 -- 第三页 limit 10,5 -- 第n页 limit (n-1)*pagesize,pagesize -- pagesize:当前页面大小 -- (n-1)*pagesize:起始值 -- n:当前页面 -- 数据总数/页面大小=总页面数 -- limit n 表示从0到n的页面 ``` ## Subquery A subquery statement is nested in the `本质`在`where` clause ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 查询‘课程设计’的所有考试结果(学号,科目编号,成绩)降序排列 -- 方式一:使用连接查询 SELECT `StudentNo`,r.`SubjectNo`,`StudentResult` FROM result r INNER JOIN `subject` s on r.StudentNo=s.SubjectNo WHERE SubjectName='课程设计' ORDER BY StudentResult DESC; -- 方式二:使用子查询(由里到外) SELECT StudentNo,SubjectNo,StudentResult from result WHERE SubjectNo=( SELECT SubjectNo FROM `subject` WHERE SubjectName='课程设计' ) ``` ## MySQL function ### Commonly used functions ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 数学运算 SELECT ABS(-8); -- 绝对值 SELECT CEIL(5.1); -- 向上取整 SELECT CEILING(5.1); -- 向上取整 SELECT RAND(); -- 返回0~1之间的一个随机数 SELECT SIGN(-10); -- 返回一个数的符号;0返回0;正数返回1;负数返回-1 -- 字符串函数 SELECT CHAR_LENGTH('我喜欢你'); -- 字符串长度 SELECT CONCAT('我','喜欢','你'); -- 拼接字符串 SELECT INSERT('我喜欢',1,1,'超级') -- INSERT(str,pos,len,newstr) 从str的pos位置开始替换为长度为len的newstr SELECT UPPER('zsr'); -- 转大写 SELECT LOWER('ZSR'); -- 转小写 SELECT INSTR('zsrs','s'); -- 返回第一次出现字串索引的位置 SELECT REPLACE('加油就能胜利','加油','坚持'); -- 替换出现的指定字符串 SELECT SUBSTR('坚持就是胜利',3,6); -- 返回指定的字符串(源字符串,截取位置,截取长度) SELECT REVERSE('rsz'); -- 反转字符串 -- 时间日期函数 SELECT CURRENT_DATE(); -- 获取当前日期 SELECT CURDATE(); -- 获取当前日期 SELECT now(); -- 获取当前时间 SELECT LOCALTIME(); -- 本地时间 SELECT SYSDATE(); -- 系统时间 SELECT YEAR(NOW()); SELECT MONTH(NOW()); SELECT DAY(NOW()); SELECT HOUR(NOW()); SELECT MINUTE(NOW()); SELECT SECOND(NOW()); -- 系统信息 SELECT SYSTEM_USER(); SELECT USER(); SELECT VERSION(); ``` ### Aggregation function | function | description | | - | - | | max | maximum value | | min | minimum value | | sum | and | | avg | average | | count | Count the number | ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SELECT COUNT(StudentName) FROM student; SELECT COUNT(*) FROM student; SELECT COUNT(1) FROM student; SELECT SUM(`StudentResult`) FROM result; SELECT AVG(`StudentResult`) FROM result; SELECT MAX(`StudentResult`) FROM result; SELECT MIN(`StudentResult`) FROM result; ``` # Database level MD5 encryption > **MD5 Message-Digest Algorithm** (MD5 Message-Digest Algorithm) * MD5 is improved from MD4, MD3, and MD2, mainly to enhance algorithm complexity and irreversibility * The principle of MD5 cracking website, there is a dictionary behind it, the value after MD5 encryption, the value before encryption ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE `testMD5`( `id` INT(4) NOT NULL, `name` VARCHAR(20) NOT NULL, `pwd` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`) )ENGINE=INNODB DEFAULT CHARSET =utf8; -- 明文密码 INSERT INTO `testMD5` VALUES(1,'zsr','200024'), (2,'gcc','000421'),(3,'bareth','123456'); -- 加密 UPDATE `testMD5` SET `pwd`=MD5(pwd) WHE RE id=1; UPDATE `testMD5` SET `pwd`=MD5(pwd); -- 加密全部的密码 -- 插入的时候加密 INSERT INTO `testMD5` VALUES(4,'barry',MD5('654321')); -- 如何校验:将用户传递进来的密码,进行MD5加密,然后对比加密后的值 SELECT * FROM `testMD5` WHERE `name`='barry' AND `pwd`=MD5('654321'); ``` # Transaction > **Either both succeed or both fail** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SQL执行:A转账给B SQL执行:B收到A的钱 ``` Put a set of SQL in a batch to execute * For example, bank transfer: the event will only end if A transfer is successful and B is successfully received. If one party is unsuccessful, the transaction is unsuccessful. ## Transaction Principle: ACID Reference link: [https://blog.csdn.net/dengjili/article/details/82468576](https://blog.csdn.net/dengjili/article/details/82468576) | Name | Description | | - | - | | **Atomicity** | Atomicity means that a transaction is an indivisible unit of work, and operations in a transaction either all occur or none occur. | | **Consistency** | The integrity of data before and after a transaction must be consistent. | | **Isolation** | The isolation of transactions means that when multiple users access the database concurrently, the transactions opened by the database for each user cannot be interfered by the operation data of other transactions, and multiple concurrent transactions must be isolated from each other. | | **Durability** | Once a transaction is committed, it is irreversible and is persisted to the database. Even if the database fails, it should not have any impact | *** ## Problems caused by transaction concurrency > Some problems caused by isolation: | Name | Description | | - | - | | **Dirty Read** | Refers to one transaction reading uncommitted data from another transaction. | | **Non-repeatable read** | Read a certain row of data in the table within a transaction, and the results of multiple reads will be different. | | **Virtual reading (phantom reading)** | refers to reading data inserted by another transaction within a transaction, resulting in inconsistent reading. | *** ## Isolation level > In database operations, in order to effectively ensure the correctness of concurrently read data, the proposed **Transaction Isolation Level** * **Read Uncommitted**: One transaction reads uncommitted data from other transactions; under this isolation level, the query will not be locked, and the consistency is the worst, causing `脏读`, `不可重复读`, and `幻读` problems. * **Read Committed**: A transaction can only read data that has been submitted by other transactions; this isolation level avoids the `脏读` problem, but the `不可重复读` and `幻读` problems still exist; The read-commit transaction isolation level is the default transaction isolation level of most popular databases, such as Oracle, but is not the default isolation level of MySQL. * **Repeatable Read**: During the execution process, a transaction can read newly inserted data that has been submitted by other transactions, but it cannot read the modifications to the data by other transactions, which means that the results of reading the same record multiple times are the same; this level avoids the problems of `脏读` and `不可重复度`, but it still cannot avoid the problem of `幻读` Repeatable read is the default isolation level of MySQL * **Serialization**: Transactions are executed serially. Transactions can only be executed one after another, and updates made to data by other transactions cannot be seen at all during the execution process. The disadvantage is poor concurrency and the strictest transaction isolation, which is fully in line with ACID principles, but has a greater impact on performance. | **Transaction Isolation Level** | **Dirty Read** | **Non-Repeatable Read** | **Phantom Read** | | - | - | - | - | | read-uncommitted | yes | yes | yes | | read-committed | no | yes | yes | | repeatable-read | no | no | yes | | Serializable | No | No | No | ## The process of executing transactions 1️⃣ **Turn off automatic submission** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SET autocommit=0; ``` 2️⃣ **Transaction starts** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} START TRANSACTION -- 标记一个事务的开始,从这个之后的sql都在同一个事务内 ``` 3️⃣ **Submit if successful, rollback if failed** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 提交:持久化(成功) COMMIT 12 -- 回滚:回到原来的样子(失败) ROLLBACK ``` 4️⃣ **Transaction ends** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SET autocommit=1; -- 开启自动提交 ``` 5️⃣ **Other operations** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SAVEPOINT 保存点名; -- 设置一个事务的保存点 ROLLBACK TO SAVEPOINT 保存点名; -- 回滚到保存点 RELEASE SAVEPOINT 保存点名; -- 撤销保存点 ``` # index Recommended reading: [Data structure and algorithm principles behind MySQL index](http://blog.codinglabs.org/articles/theory-of-mysql-index.html) > Index (`Index`) is a **data structure** that helps MySQL obtain data efficiently. * Improve query speed * Ensure data uniqueness * Can speed up the connection between tables and achieve referential integrity between tables * When using grouping and sorting clauses for data retrieval, the time of grouping and sorting can be significantly reduced * Full text search fields for search optimization *** ## Index classification ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 创建学生表student CREATE TABLE `student`( `StudentNo` INT(4) NOT NULL COMMENT '学号', `LoginPwd` VARCHAR(20) DEFAULT NULL, `StudentName` VARCHAR(20) DEFAULT NULL COMMENT '学生姓名', `Sex` TINYINT(1) DEFAULT NULL COMMENT '性别,取值0或1', `GradeID` INT(11) DEFAULT NULL COMMENT '年级编号', `Phone` VARCHAR(50) NOT NULL COMMENT '联系电话,允许为空,即可选输入', `Adress` VARCHAR(255) NOT NULL COMMENT '地址,允许为空,即可选输入', `BornDate` DATETIME DEFAULT NULL COMMENT '出生时间', `Email` VARCHAR(50) NOT NULL COMMENT '邮箱账号,允许为空,即可选输入', `IdentityCard` VARCHAR(18) DEFAULT NULL COMMENT '身份证号', PRIMARY KEY (`StudentNo`), UNIQUE KEY `IdentityCard` (`IdentityCard`), KEY `Email` (`Email`) )ENGINE=MYISAM DEFAULT CHARSET=utf8; ``` ### Primary key index (PRIMARY KEY) Unique identification, primary key cannot be repeated, only one column is used as the primary key * The most common index type, null values are not allowed * Ensure the uniqueness of data records * Determine where specific data records are located in the database ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 创建表的时候指定主键索引 CREATE TABLE tableName( ...... PRIMARY INDEX (columeName) ) -- 修改表结构添加主键索引 ALTER TABLE tableName ADD PRIMARY INDEX (columnName) ``` *** ### Ordinary index (KEY / INDEX) Default, quickly locate specific data * Both index and key keywords can set regular indexes * Fields that should be added to the search criteria * It is not advisable to add too many regular indexes, which will affect the insertion, deletion and modification operations of data. ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 直接创建普通索引 CREATE INDEX indexName ON tableName (columnName) -- 创建表的时候指定普通索引 CREATE TABLE tableName( ...... INDEX [indexName] (columeName) ) -- 修改表结构添加普通索引 ALTER TABLE tableName ADD INDEX indexName(columnName) ``` *** \###Unique index (UNIQUE KEY) It is similar to the previous ordinary index, except that the value of the index column must be unique, but null values ​​are allowed. The difference from primary key index: there can only be one primary key index, and there can be multiple unique indexes. ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 直接创建唯一索引 CREATE UNIQUE INDEX indexName ON tableName(columnName) -- 创建表的时候指定唯一索引 CREATE TABLE tableName( ...... UNIQUE INDEX [indexName] (columeName) ); -- 修改表结构添加唯一索引 ALTER TABLE tableName ADD UNIQUE INDEX [indexName] (columnName) ``` *** ### Full text index (FULLText) Quickly locate specific data (Baidu search is full-text index) * Available under specific database engines: MyISAM * Can only be used for CHAR, VARCHAR, and TEXT data column types * Suitable for large data sets ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 增加一个全文索引 ALTER TABLE `student` ADD FULLTEXT INDEX `StudentName`(`StudentName`); -- EXPLAIN 分析sql执行的情况 EXPLAIN SELECT * FROM student; -- 非全文索引 EXPLAIN SELECT * FROM student WHERE MATCH(StudentName) AGAINST('d'); -- 全文索引 ``` ## Usage of index ### Index creation * Add indexes to fields when creating tables ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE 表名 ( 字段名1 数据类型 [完整性约束条件…], 字段名2 数据类型 [完整性约束条件…], [UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY [索引名] (字段名[(长度)] [ASC |DESC]) ); ``` * After creation, add index ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 方法一:CREATE在已存在的表上创建索引 CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名 ON 表名 (字段名[(长度)] [ASC |DESC]) ; -- 方法二:ALTER TABLE在已存在的表上创建索引 ALTER TABLE 表名 ADD [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名 (字段名[(长度)] [ASC |DESC]) ; ``` ### Index deletion ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 删除索引 DROP INDEX 索引名 ON 表名; -- 删除主键索引 ALTER TABLE 表名 DROP PRIMARY KEY; ``` ### Display index information ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} SHOW INDEX FROM 表名; ``` ### explain analysis of sql execution ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 增加一个全文索引 ALTER TABLE `student` ADD FULLTEXT INDEX `StudentName`(`StudentName`); -- EXPLAIN 分析sql执行的情况 EXPLAIN SELECT * FROM student; -- 非全文索引 EXPLAIN SELECT * FROM student WHERE MATCH(StudentName) AGAINST('d'); -- 全文索引 ``` *** ## Test index **Create table app\_user:** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE `app_user` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT '' COMMENT '用户昵称', `email` varchar(50) NOT NULL COMMENT '用户邮箱', `phone` varchar(20) DEFAULT '' COMMENT '手机号', `gender` tinyint(4) unsigned DEFAULT '0' COMMENT '性别(0:男;1:女)', `password` varchar(100) NOT NULL COMMENT '密码', `age` tinyint(4) DEFAULT '0' COMMENT '年龄', `create_time` datetime DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATECURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='app用户表' ``` **Batch insert data: 100w** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 1418错解决方案(创建函数前执行此语句) set global log_bin_trust_function_creators=true; -- 插入100万条数据 DELIMITER $$ -- 写函数之前要写的标志 CREATE FUNCTION mock_data() -- 创建mock_data()函数 RETURNS INT BEGIN DECLARE num INT DEFAULT 1000000; DECLARE i INT DEFAULT 0; WHILE i < num DO INSERT INTO app_user(`name`, `email`, `phone`, `gender`, `password`, `age`) VALUES(CONCAT('用户', i), '24736743@qq.com', CONCAT('18', FLOOR(RAND()*(999999999-100000000)+100000000)),FLOOR(RAND()*2),UUID(), FLOOR(RAND()*100)); SET i = i + 1; END WHILE; RETURN i; END; -- 执行函数 SELECT mock_data(); ``` ![image-20210327101253258](https://img-blog.csdnimg.cn/img_convert/df271eca3feb9ab506aaed611ef6f087.png) ![image-20210327101316627](https://img-blog.csdnimg.cn/img_convert/2d3b3bfa01475754f69c4386a214a73a.png) **Test query speed** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 查询用户名为'用户9999'性能分析 EXPLAIN SELECT * FROM app_user where name='用户99999' ``` ![image-20210327101912627](https://img-blog.csdnimg.cn/img_convert/70f2c32ec8c3bbdf6ea0c922108f8d8c.png) **Test after adding index** ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 给name列创建常规索引 CREATE INDEX id_app_user_name ON app_user(`name`) -- 再测试 EXPLAIN SELECT * FROM app_user where name='用户99999' ``` ![image-20210327102830560](https://img-blog.csdnimg.cn/img_convert/cd50fa7b12a659d31ffc32e0ef15e20f.png) Comparing the two results, the speed has been greatly improved. *** ## Indexing principles * The more indexes, the better. Tables with small data volumes do not need to be indexed. * Do not add indexes to frequently changing data * Indexes are generally added to columns that are frequently queried *** # explain keyword **Suggested Reading**: * [MySQL optimization - understand the explain](https://blog.csdn.net/jiadajing267/article/details/81269067) * [MySQL Advanced Explain Execution Plan Detailed Explanation](https://blog.csdn.net/wuseyukui/article/details/71512793?dist_request_id=\&depth_1-) *** # Permission management and backup ## User management **Method 1: Visual management** ![image-20210327123000095](https://img-blog.csdnimg.cn/img_convert/26c44c01a054ac4476a6cb2eafb768ff.png) *** **Method 2: SQL command operation** > User information is stored in the `user` table in the `mysql` database. The essence of user management is to add, delete, modify and check this table. > > ![image-20210327123240942](https://img-blog.csdnimg.cn/img_convert/134b75187269c5e003fd98902cfc959e.png) ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- 创建用户 CREATE USER zsr IDENTIFIED BY '123456' -- 删除用户 DROP USER zsr -- 修改当前用户密码 SET PASSWORD = PASSWORD('200024') -- 修改指定用户密码 SET PASSWORD FOR zsr = PASSWORD('200024') -- 重命名 RENAME USER zsr to zsr2 -- 用户授权(授予全部权限,除了给其他用户授权) GRANT ALL PRIVILEGES on *.* TO zsr2 -- 查询权限 SHOW GRANTS FOR zsr -- 查看root用户权限 SHOW GRANTS FOR root@localhost -- 撤销权限 REVOKE ALL PRIVILEGES ON *.* FROM zsr ``` *** ## Database backup Ensure that important data is not lost and data is escaped > **Method 1**: Directly copy the physical file, and the MySQL data table is stored on the disk as a file -Including table files, data files, and database option files * Location: `Mysql安装目录\data\` (the directory name corresponds to the database name, and the file name in this directory corresponds to the data table) ![image-20210327125528006](https://img-blog.csdnimg.cn/img_convert/7e7cc8befc1537b12c9f7dfd10279114.png) > **Method 2**: Visual management Navicat opens the database to be backed up, and then click New Backup ![image-20210327125911151](https://img-blog.csdnimg.cn/img_convert/e4240bd95dec14b565b1d86cb1c5c915.png) Click Object Selection. Here you can customize the table to be selected for backup. ![image-20210327130024058](https://img-blog.csdnimg.cn/img_convert/3e6c95e2806746c38d0e8627682f6163.png) After selecting, click Backup to start the backup ![image-20210327130134693](https://img-blog.csdnimg.cn/img_convert/8f920ac3f3ad125e54e4f3f10328cbee.png) ![image-20210327130213947](https://img-blog.csdnimg.cn/img_convert/eeaeff9e0dd440f6dc4df763f5804845.png) Wait for the backup to complete, close it, and then you can see the backed up files ![image-20210327130245251](https://img-blog.csdnimg.cn/img_convert/056debcb95166ac3195a993db6a9b63b.png) > **Method Three**: Visual Management Select the table to be exported and right-click to dump the SQL file ![image-20210327131239931](https://img-blog.csdnimg.cn/img_convert/da7feae09141b97f48ef3133a7385baa.png) Then you can get the `.sql` file ![image-20210327131430300](https://img-blog.csdnimg.cn/img_convert/4d4c9b1c3da14f4fccaf7e4ad0b5c6f5.png) > **Method 4**: Command `mysqldump` to export ```shell theme={"theme":{"light":"github-light","dark":"github-dark"}} # mysqldump -h主机 -u用户名 -p密码 数据库 [表1 表2 表3] >物理磁盘位置/文件名 # 导出school数据库的cource grade student表到D:/school.sql mysqldump -hlocalhost -uroot -p200024 school course grade student >D:/school.sql ``` ![image-20210327132011402](https://img-blog.csdnimg.cn/img_convert/5443e1fbd169e2c1e387cb4da76d0b8e.png) Then you can see the exported `sql` file ![image-20210327132043857](https://img-blog.csdnimg.cn/img_convert/4f8735b65d95ecd8db7fcdb3da763e4f.png) Then you can log in to mysql from the command line, switch to the specified database, and import using the `source` command ![image-20210327132439737](https://img-blog.csdnimg.cn/img_convert/17b6a505af032cce78c98488f1baa215.png) *** \#Three major paradigms > **Normalization Theory**: Transform the relationship model and eliminate inappropriate data dependencies by decomposing the relationship model to solve the problems of insertion anomalies, deletion anomalies, update anomalies and data redundancy. > > In order to establish a database with less redundancy and reasonable structure, certain standardization theories must be followed when designing the database. In relational databases this kind of rule is called `范式` [Popular understanding of the three paradigms](https://www.cnblogs.com/wsg25/p/9615100.html) * If all attributes of a relational schema R are indivisible data items, then R belongs to `第一范式` * If the relational schema R belongs to the first normal form and each non-primary attribute is completely functionally dependent on the code, then R belongs to `第二范式` * If the relational schema R belongs to the second normal form, and all non-primary attributes in R are directly dependent on the code, then R belongs to `第三范式` ![image-20210325220605636](https://gitee.com/zhong_siru/images/raw/master//img/image-20210325220605636.png) **Normative Questions**: > The paradigm of the database is to standardize the design of the database, but in practice, issues such as performance, cost, and user experience are often more important than standardization; > > Therefore, sometimes a redundant field is deliberately added to some tables to turn multi-table queries into single-table queries. Sometimes some calculated columns are added to change the amount of data from large to small (when the amount of data is large, count(\*) is very time-consuming, you can directly add a column, +1 for each additional row, just check the column); Alibaba has also proposed that the tables for related queries should not exceed three tables at most. > > These are examples of giving up certain norms for performance and cost. *** # Database driver and JDBC > The program we write will interact with the database through **database driver** > > Then different databases have different drivers, which is not convenient for our programs to operate various databases; therefore, in order to simplify the operation of different databases, SUN provides a Java specification for operating databases`JDBC`; the specifications of different databases are completed by the corresponding database manufacturers. For developers, they only need to master the operation of the JDBC interface. ## The first JDBC program 1️⃣ **Create a new empty project** ![image-20210327153130998](https://img-blog.csdnimg.cn/img_convert/2a6f4995962d7719b5f341ac0d2bfabe.png) 2️⃣ **Import mysql-connector-java** Create a new `lib` directory under the project directory and put it in the jar package ![image-20210327153240818](https://gitee.com/zhong_siru/images/raw/master//img/image-20210327153240818.png) ![image-20210327153343389](https://img-blog.csdnimg.cn/img_convert/44dc09d9bf971bd3dc0c72cfe8aab10d.png) ![image-20210327153457419](https://img-blog.csdnimg.cn/img_convert/8b6b89c5197b0356215aa9aed1cbd964.png) 3️⃣ **Write code & test** Create a new `JDBCDemo` in the `src` directory to operate the database ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} import java.sql.*; public class JDBCDemo { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1.加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.连接信息url,用户信息 String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC"; String username = "root"; String password = "200024"; //3.连接,获得数据库对象connection Connection connection = DriverManager.getConnection(url, username, password); //4.获取执行sql的对象 Statement statement = connection.createStatement(); //5.执行sql String sql = "select * from app_user where id<10"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone")); } //6.释放连接 resultSet.close(); statement.close(); connection.close(); } } ``` ![image-20210327155209907](https://img-blog.csdnimg.cn/img_convert/30ae5d967e49cdbf74b4677938952fc1.png) *** ## JDBC Object ### DriverManager > **DriverManager**: driver management ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} //1.加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); ``` Essentially execute `DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());` ![image-20210327161110925]() ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} //3.连接,获得数据库对象connection Connection connection = DriverManager.getConnection(url, username, password); ``` `connection` represents the database, so you can set up automatic transaction submission, transaction rollback, etc. ![image-20210327161507445](https://img-blog.csdnimg.cn/img_convert/3e5b382f0710809439ab5f7cee170872.png) *** ### Statement > **Statement**: The object that executes sql, used to send SQL statements to the database. If you want to complete the addition, deletion, modification and query of the database, you only need to send the addition, deletion, modification and query statement to the database through this object. ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} statement.executeQuery();//查询操作,返回结果 statement.execute();//执行sql statement.executeUpdate();//用于增删改,返回受影响的行数 ``` ![image-20210327162622201](https://img-blog.csdnimg.cn/img_convert/aa5a397f6e2e376c7e16dbba106e88b6.png) ![image-20210327162705203](https://img-blog.csdnimg.cn/img_convert/c4587e04579f25dc58864ccfed3184f4.png) *** ### ResultSet > **ResultSet**: The result set of the query, which encapsulates the results of all queries ![image-20210327162307420](https://img-blog.csdnimg.cn/img_convert/ac1a33619a7021011df6025a57f18ec3.png) *** ## 3. Encapsulate jdbc tool class ### Write database configuration file Create a new `db.properties` in the `src` directory to store database configuration information ![image-20210327165924876](https://img-blog.csdnimg.cn/img_convert/aa2ecaf2738632a4b75d2c70e417f8c1.png) ```properties theme={"theme":{"light":"github-light","dark":"github-dark"}} driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC username=root password=200024 ``` *** ### Writing tool classes Then create `JDBCUtils.java` in the `src` directory as a tool class ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JDBCUtils { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static { try { InputStream inputStream = JDBCDemo.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(inputStream); driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); //加载驱动 Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } //释放连接资源 public static void release(Connection connection, Statement statement, ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } ``` *** ### test Modify`JDBCDemo` ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} import java.sql.*; public class JDBCDemo { public static void main(String[] args) throws SQLException { //获得数据库对象connection Connection connection = JDBCUtils.getConnection(); //获取sql执行对象statement Statement statement = connection.createStatement(); //执行sql String sql = "select * from app_user where id<10"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone")); } //释放连接 JDBCUtils.release(connection, statement, resultSet); } } ``` ![image-20210327171418601](https://img-blog.csdnimg.cn/img_convert/d22fdb27412e8514d878f28053d4f820.png) *** ## SQL injection problem > SQL injection happens when a [web application](https://baike.baidu.com/item/web应用程序/2498090) does not properly validate or filter user input. An attacker can append extra [SQL statements](https://baike.baidu.com/item/SQL语句/5714895) to a predefined query, tricking the [database server](https://baike.baidu.com/item/数据库服务器/613818) into executing unauthorized queries and exposing data. **SQL injection case**: Pass in the user name in the main function and search for user information with the specified name ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLInjection { public static void main(String[] args) throws SQLException { searchName("' or '1=1"); } //查找指定名字用户信息 public static void searchName(String username) throws SQLException { //获得数据库对象connection Connection connection = JDBCUtils.getConnection(); //获取sql执行对象statement Statement statement = connection.createStatement(); //执行sql String sql = "select * from app_user where name='" + username + "'"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone")); } //释放连接 JDBCUtils.release(connection, statement, resultSet); } } ``` **Result**: All data in the database were queried ![image-20210327173159454](https://img-blog.csdnimg.cn/img_convert/fa46b5cd881946e10066ced5b621f8b7.png) Here, an illegal string is passed in instead of a user name, but all the data is obtained. Why? Splicing the entire sql statement is `select * from app_user where name=' ' or '1==1'`, of which `1==1` is always true, so the sql statement is equivalent to all the data in the query table; this is sql injection, mainly a problem caused by string splicing, which is very dangerous! ! *** ## PreparedStatement object > `PreparedStatement` is a subclass of `Statement`. Compared with it, it can prevent SQL injection and is more efficient. Also test the sql injection case ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} import java.sql.*; public class SQLInjection { public static void main(String[] args) throws SQLException { searchName("' 'or '1=1'"); } //登录 public static void searchName(String username) throws SQLException { //获得数据库对象connection Connection connection = JDBCUtils.getConnection(); //获取sql执行对象preparedStatement(预编译sql,先写不执行,参数用?表示) PreparedStatement preparedStatement = connection.prepareStatement("select * from app_user where name=?"); //手动传参 preparedStatement.setString(1, username); //执行sql ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone")); } //释放连接 JDBCUtils.release(connection, preparedStatement, resultSet); } } ``` ![image-20210327180032468](https://img-blog.csdnimg.cn/img_convert/1a164b75b1a4e030974f32f4ed8cec42.png) According to the results, the PreparedStatement object perfectly avoids sql injection problems *** ## Transaction case First create the account table ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40), money FLOAT ); INSERT INTO account(name,money) VALUES('A',1000); INSERT INTO account(name,money) VALUES('B',1000); INSERT INTO account(name,money) VALUES('C',1000); ``` ![image-20210414235806762](https://img-blog.csdnimg.cn/img_convert/fb7a765f6b6d077503fb3ac8fe2971c7.png) Then write Java code ```java theme={"theme":{"light":"github-light","dark":"github-dark"}} import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; public class TestTransaction { public static void main(String[] args) throws SQLException { //获得数据库对象connection Connection connection = JDBCUtils.getConnection(); //关闭数据库自动提交,即开启事务 connection.setAutoCommit(false); String sql1 = "update account set money = money+100 where name = 'A' "; String sql2 = "update account set money = money-100 where name = 'B' "; //获取sql执行对象preparedStatement PreparedStatement preparedStatement = connection.prepareStatement(sql1); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(sql2); preparedStatement.executeUpdate(); //业务完毕,提交事务 connection.commit(); //释放资源 JDBCUtils.release(connection, preparedStatement, null); } } ``` Running results: ![image-20210414235836300](https://img-blog.csdnimg.cn/img_convert/61f641ba421658f8bcb574751954b9d4.png) If you add `int x = 1 / 0` between two updates; An error will be reported, the transaction execution will fail, and neither statement will be executed successfully. ![image-20210327212324221](https://img-blog.csdnimg.cn/img_convert/0db32304bfc44277ce777d5b68aedccd.png) ![image-20230618214249123](https://bangwu.oss-cn-shanghai.aliyuncs.com/img/202306182142257.png) # SQLite Source: https://base.bangwu.me/backend/SQL/sqlite SQLite is a lightweight embedded database reading and writing disk files, covering Python sqlite3 integration, basic SQL operations, and use cases. # SQLite SQLite is a lightweight embedded relational database. It does not require a standalone server process and reads from or writes to a disk file directly. ## Features * **Zero configuration**: no installation or admin service required * **Single file**: the entire database lives in one file * **Cross-platform**: works on all major operating systems * **Self-contained**: no external service dependency * **Transactional**: supports full ACID behavior ## Using SQLite in Python ### Basic operations ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} import sqlite3 # 连接数据库(不存在则创建) conn = sqlite3.connect('example.db') cursor = conn.cursor() # 创建表 cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE ) ''') # 插入数据 cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("张三", "zhangsan@example.com")) # 查询数据 cursor.execute("SELECT * FROM users") rows = cursor.fetchall() # 提交事务 conn.commit() conn.close() ``` ### Context manager ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} with sqlite3.connect('example.db') as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users") results = cursor.fetchall() ``` ## Common commands ```sql theme={"theme":{"light":"github-light","dark":"github-dark"}} -- View所有表 .tables -- View表结构 .schema users -- 导出数据 .output data.sql .dump -- 导入数据 .read data.sql ``` ## Performance tips 1. **Use transactions** for batch operations. 2. **Create indexes** to speed up queries. 3. **Enable WAL mode** to improve concurrent read/write behavior. ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} # 启用 WAL 模式 conn.execute('PRAGMA journal_mode=WAL') ``` ## Good use cases * Local storage for mobile apps * Desktop app data management * Small web applications * Embedded devices * Testing and prototyping ## Limitations * Not ideal for high-concurrency writes * Recommended database size is typically below 1 TB * No built-in user permission management # RBAC & Session Auth Source: https://base.bangwu.me/backend/auth/rbac Role-Based Access Control and session cookie authentication patterns from real projects using Hono, SQLite, Next.js, and PostgreSQL. # RBAC & Session Cookie Authentication Role-Based Access Control (RBAC) assigns permissions to roles, then roles to users. Combined with signed session cookies, you get a simple, secure auth system that works without JWT complexity. > [card] [badmin](https://github.com/markbang/badmin) > > Hono + SQLite — full RBAC admin panel with session cookies. > [card] [Cruise Ship](https://github.com/markbang/cruise-ship-system) > > Next.js + PostgreSQL — role-based business system with token sessions. ## RBAC Data Model The classic RBAC model has four tables: ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} users ──(user_roles)──► roles ──(role_permissions)──► permissions ``` ### Schema Definition ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} // Core tables export const users = sqliteTable("users", { id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()), name: text("name").notNull(), email: text("email").notNull().unique(), passwordHash: text("password_hash").notNull(), sessionVersion: integer("session_version").default(1).notNull(), // For forced logout status: text("status", { enum: ["active", "disabled"] }).default("active").notNull(), }) export const roles = sqliteTable("roles", { id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()), name: text("name").notNull(), slug: text("slug").notNull().unique(), // e.g. "admin", "editor" description: text("description").notNull(), isSystem: integer("is_system", { mode: "boolean" }).default(false).notNull(), // Prevent deletion }) export const permissions = sqliteTable("permissions", { key: text("key").primaryKey(), // e.g. "users.read", "users.write" label: text("label").notNull(), group: text("group").notNull(), // e.g. "users", "roles", "dashboard" }) // Junction tables (many-to-many) export const userRoles = sqliteTable("user_roles", { userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }), }, (table) => ({ pk: primaryKey({ columns: [table.userId, table.roleId] }) })) export const rolePermissions = sqliteTable("role_permissions", { roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }), permissionKey: text("permission_key").notNull().references(() => permissions.key, { onDelete: "cascade" }), }, (table) => ({ pk: primaryKey({ columns: [table.roleId, table.permissionKey] }) })) ``` > [!TIP] > > Permission keys use dot notation (`users.read`, `users.write`) for natural grouping. The `group` column lets you organize them in the UI. ## Session Cookie Auth Instead of JWTs, use **signed session cookies** — simpler, more secure for same-origin apps: ### Why Cookies over JWT? | Concern | Session Cookie | JWT | | - | - | - | | Revocation | Increment `sessionVersion` — instant | Must maintain blacklist or wait for expiry | | Storage | Server-side DB check | Self-contained (can't revoke without blacklist) | | Size | Small: `userId:version` | Large: encoded claims + signature | | CSRF | Mitigated by `SameSite` | Not applicable (usually sent in header) | | Implementation | `hono/cookie` signed cookies | Library + secret management | ### Implementation with Hono ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { getSignedCookie, setSignedCookie, deleteCookie } from "hono/cookie" import { createMiddleware } from "hono/factory" const SESSION_COOKIE = "app_session" const COOKIE_MAX_AGE = 60 * 60 * 24 * 7 // 7 days // Set session after login export async function setSessionCookie(ctx, userId: string, sessionVersion: number) { await setSignedCookie(ctx, SESSION_COOKIE, `${userId}:${sessionVersion}`, secret, { httpOnly: true, // Not accessible from JS maxAge: COOKIE_MAX_AGE, sameSite: "Lax", // CSRF protection secure: isProduction, // HTTPS only in prod path: "/", }) } // Require session on API routes export function requireSession(authService: AuthService) { return createMiddleware(async (c, next) => { const value = await getSignedCookie(c, secret, SESSION_COOKIE) if (!value) throw new HTTPException(401, { message: "Login required" }) const payload = parseSessionCookie(value) // → { userId, sessionVersion } const session = await authService.getSession(payload) if (!session) { deleteCookie(c, SESSION_COOKIE) throw new HTTPException(401, { message: "Session expired" }) } c.set("sessionUser", session.user) // Available in all downstream handlers await next() }) } // Require specific permission export function requirePermission(permission: string) { return createMiddleware(async (c, next) => { const user = c.get("sessionUser") if (!user.permissions.includes(permission)) { throw new HTTPException(403, { message: "Permission denied" }) } await next() }) } ``` ### Route Protection Chain middleware to protect routes: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} const app = new Hono() // Public routes app.post("/api/auth/login", async (c) => { /* ... */ }) // Protected routes — require session app.use("/api/*", requireSession(authService)) // Require permission for specific routes app.use("/api/users/*", requirePermission("users.write")) app.use("/api/roles/*", requirePermission("roles.write")) app.get("/api/users", async (c) => { const user = c.get("sessionUser") // Injected by middleware return c.json(await userService.listUsers(user)) }) ``` ## Session Versioning (Forced Logout) When a user changes their password or gets disabled, bump their `sessionVersion`: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} // In auth service — change password async changePassword(userId: string, input: ChangePasswordInput) { await this.userRepository.updatePassword(userId, { passwordHash: await hashPassword(input.nextPassword), }) // Increment session version → all existing cookies become invalid await this.userRepository.revokeSessions(userId) } // In repository — SQL increment async revokeSessions(id: string) { await db.update(users) .set({ sessionVersion: sql`session_version + 1` }) .where(eq(users.id, id)) } ``` When `requireSession` checks the cookie, it compares the cookie's version with the DB version. If they differ, the session is rejected. > [!NOTE] > > Session versioning is the simplest way to force logout. No blacklist, no waiting for JWT expiry — just increment a number in the DB. ## Loading Permissions into Session On login, load all the user's permissions into the session object: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} async findSessionUserById(id: string) { return await db.query.users.findFirst({ where: eq(users.id, id), columns: { passwordHash: false }, // Never include in session with: { roles: { with: { role: { with: { permissions: { columns: { permissionKey: true }, // Only need the key }, }, }, }, }, }, }) } // Flatten permissions for quick checks function flattenPermissions(sessionUser) { const permissions = sessionUser.roles.flatMap(ur => ur.role.permissions.map(rp => rp.permissionKey)) return { ...sessionUser, permissions } } ``` ## Frontend Permission Checks Don't rely only on backend — hide UI elements the user can't access: ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} function UserManagementPage() { const { user } = useSession() return (

Users

{user.permissions.includes("users.write") && ( )}
) } ``` > [!TIP] > > Frontend permission checks are for **UX** (hide buttons), not **security**. The backend middleware is the real gatekeeper — always validate permissions on the API side. ## Cruise Ship: Token-Based Sessions For the cruise-ship system (Next.js + PostgreSQL), we used token-based sessions stored in the DB: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} export const userSession = pgTable("user_session", { id: bigserial({ mode: "bigint" }).primaryKey().notNull(), userId: bigint("user_id", { mode: "number" }).notNull(), token: varchar({ length: 128 }).notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), }, (table) => [ unique("user_session_token_key").on(table.token), index("idx_user_session_user_id").using("btree", table.userId), ]) ``` This approach stores the full session in PostgreSQL — good for distributed apps where cookie-only sessions can't work. ## Best Practices 1. **Signed cookies over JWT** — Simpler, revocable, smaller payload 2. **Session versioning** — Increment to force logout on password change or account disable 3. **Flatten permissions** — Load all permission keys into the session object for O(1) checks 4. **Exclude sensitive columns** — Never query `passwordHash` into session data 5. **Cascade deletes on M2M** — Role/user deletions should auto-clean associations 6. **`isSystem` flag on roles** — Prevent deletion of essential roles (Admin, SuperAdmin) 7. **Frontend hides, backend validates** — Frontend checks are UX, backend middleware is security 8. **Token sessions for distributed systems** — When cookies can't work across services, store tokens in DB ## References * [Hono Cookie API](https://hono.dev/helpers/cookie) * [badmin auth module](https://github.com/markbang/badmin) — Full Hono + SQLite RBAC implementation * [cruise-ship auth](https://github.com/markbang/cruise-ship-system) — Next.js + PostgreSQL token sessions # Backend Source: https://base.bangwu.me/backend/index Backend development notes covering Python (FastAPI, scraping, libraries), Go (Gin framework), and databases (MySQL, SQLite, and theory notes). Backend development handles server-side logic, database interactions, and API design. Here are the tech stacks I've worked with. > [card] [Python](/backend/Python/index) > > FastAPI, web scraping, and popular libraries. > [card] [Go](/backend/Go/index) > > Gin framework and concurrent programming. > [card] [Rust](/backend/Rust/index) > > Axum IM bridges and Tauri desktop shells. > [card] [Databases](/backend/SQL/index) > > MySQL, SQLite, and core database concepts. > [card] [Drizzle ORM](/backend/orm/drizzle) > > Type-safe ORM — SQLite & PostgreSQL schema design. > [card] [RBAC & Auth](/backend/auth/rbac) > > Role-based access control and session cookie auth. ## Learning Path 1. Master a backend language (Python / Go) 2. Learn database design and SQL operations 3. Understand RESTful API design principles 4. Learn authentication and authorization 5. Deployment and DevOps basics # Drizzle ORM Source: https://base.bangwu.me/backend/orm/drizzle Database schema design, migrations, and CRUD patterns using Drizzle ORM — drawn from badmin (SQLite), cruise-ship (PostgreSQL), and cyop (PostgreSQL). # Drizzle ORM — Schema Design & Best Practices Drizzle ORM is a TypeScript-first ORM with SQL-like syntax, zero runtime overhead, and full type safety. It supports SQLite, PostgreSQL, MySQL, and more — each with driver-specific column types. > [card] [badmin](https://github.com/markbang/badmin) > > SQLite admin panel — users, roles, RBAC permissions. > [card] [Cruise Ship](https://github.com/markbang/cruise-ship-system) > > PostgreSQL business system — bookings, finance, cabin allocation. > [card] [cyop](https://github.com/markbang/cyop) > > PostgreSQL AI platform — requirements, tasks, captions. ## SQLite Schema (badmin) SQLite is great for admin panels and prototypes — zero infra cost, local file DB: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core" import { sql } from "drizzle-orm" const USER_STATUS_VALUES = ["active", "disabled"] as const export const users = sqliteTable("users", { id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()), name: text("name").notNull(), email: text("email").notNull().unique(), passwordHash: text("password_hash").notNull(), sessionVersion: integer("session_version").default(1).notNull(), status: text("status", { enum: USER_STATUS_VALUES }).default("active").notNull(), lastLoginAt: integer("last_login_at", { mode: "timestamp" }), createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(), updatedAt: integer("updated_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(), }) ``` > [!NOTE] > > SQLite stores timestamps as integers. Use `{ mode: "timestamp" }` so Drizzle auto-converts `Date` ↔ `unixepoch()`. The `sql`(unixepoch())\` default gives you a server-side timestamp without app logic. ## PostgreSQL Schema (Cruise Ship) PostgreSQL gives you rich column types — `numeric` for money, `jsonb` for snapshots, `text[]` for arrays: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { pgTable, bigserial, bigint, varchar, numeric, integer, timestamp, text, date, boolean, check, index, foreignKey, unique } from "drizzle-orm/pg-core" import { sql } from "drizzle-orm" export const cruise = pgTable("cruise", { id: bigserial({ mode: "bigint" }).primaryKey().notNull(), name: varchar({ length: 120 }).notNull(), tonnage: numeric({ precision: 12, scale: 2 }), imageUrls: text("image_urls").array(), status: varchar({ length: 20 }).default("normal").notNull(), createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).defaultNow().notNull(), }, (table) => [ index("idx_cruise_status").using("btree", table.status.asc().nullsLast().op("text_ops")), check("cruise_status_check", sql`(status)::text = ANY ((ARRAY['normal','disabled','closed'])::text[])`), ]) ``` ### Key PostgreSQL Patterns 1. **CHECK constraints for enums** — PostgreSQL doesn't have native enums in Drizzle, so use `check()` with `ANY (ARRAY[...])`: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} check("status_check", sql`(status)::text = ANY ((ARRAY['active','disabled'])::text[])`) ``` 2. **Composite indexes** — For multi-column queries, define indexes inline: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} index("idx_booking_cabin_booking_id").using("btree", table.bookingApplicationId.asc().nullsLast().op("int8_ops")) ``` 3. **Array columns** — `text("image_urls").array()` for storing multiple URLs without a separate table: 4. **JSONB for snapshots** — `jsonb("item_snapshot").default([]).notNull()` for revision history: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} export const costRevision = pgTable("cost_revision", { id: bigserial({ mode: "bigint" }).primaryKey().notNull(), beforeTotalCost: numeric({ precision: 14, scale: 2 }).default("0").notNull(), afterTotalCost: numeric({ precision: 14, scale: 2 }).default("0").notNull(), itemSnapshot: jsonb("item_snapshot").default([]).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }) ``` ## Many-to-Many Relationships (RBAC) RBAC needs user ↔ role ↔ permission many-to-many tables: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} export const userRoles = sqliteTable( "user_roles", { userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }), createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(), }, (table) => ({ pk: primaryKey({ columns: [table.userId, table.roleId] }), }), ) export const rolePermissions = sqliteTable( "role_permissions", { roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }), permissionKey: text("permission_key").notNull().references(() => permissions.key, { onDelete: "cascade" }), createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(), }, (table) => ({ pk: primaryKey({ columns: [table.roleId, table.permissionKey] }), }), ) ``` > [!TIP] > > Always add `onDelete: "cascade"` on many-to-many foreign keys. When a role or user is deleted, their associations should disappear automatically — no orphaned rows. ## Repository Pattern Separate data access from business logic using repository interfaces: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} // src/domain/repositories.ts export interface AuthUserRepository { findForAuthByEmail(email: string): Promise findSessionUserById(id: string): Promise touchLastLogin(id: string): Promise updatePassword(id: string, data: { passwordHash: string; nextPassword: string }): Promise revokeSessions(id: string): Promise } ``` ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} // src/repositories/user-repository.ts export function createUserRepository(db: DrizzleDB): AuthUserRepository { return { async findForAuthByEmail(email: string) { return await db.query.users.findFirst({ where: eq(users.email, email), }) }, async findSessionUserById(id: string) { return await db.query.users.findFirst({ where: eq(users.id, id), columns: { passwordHash: false }, // Never load password into session with: { roles: { with: { role: { with: { permissions: true } } } }, }, }) }, async revokeSessions(id: string) { await db.update(users) .set({ sessionVersion: sql`session_version + 1` }) .where(eq(users.id, id)) }, } } ``` > [!NOTE] > > When loading a user for session checks, never include the password hash. Drizzle's `columns` filter lets you exclude sensitive fields at the query level, not just in the service layer. ## Migrations Drizzle Kit generates SQL migrations from your schema: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Generate migration from schema changes bun run db:generate # Apply migrations bun run db:migrate # Visualize schema bun run db:studio ``` ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} // drizzle.config.ts import { defineConfig } from "drizzle-kit" export default defineConfig({ schema: "./src/db/schema.ts", out: "./drizzle", dialect: "sqlite", // or "postgresql" dbCredentials: { url: "./dev.db", }, }) ``` ## Seeding Seed the database with initial roles, permissions, and an admin user: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} // src/db/seed.ts import { db } from "./client" import { users, roles, permissions, userRoles, rolePermissions } from "./schema" export async function seed() { // Create permissions await db.insert(permissions).values([ { key: "users.read", label: "View Users", group: "users" }, { key: "users.write", label: "Edit Users", group: "users" }, { key: "roles.read", label: "View Roles", group: "roles" }, ]) // Create admin role const [adminRole] = await db.insert(roles).values({ name: "Admin", slug: "admin", description: "System administrator", isSystem: true, }).returning() // Link all permissions to admin role await db.insert(rolePermissions).values( allPermissions.map(p => ({ roleId: adminRole.id, permissionKey: p.key })) ) // Create admin user const [adminUser] = await db.insert(users).values({ name: "Admin", email: "admin@example.com", passwordHash: await hashPassword("changeme"), }).returning() // Assign admin role await db.insert(userRoles).values({ userId: adminUser.id, roleId: adminRole.id }) } ``` ## Best Practices 1. **SQLite for admin panels** — Zero infra, local dev, good for small-to-medium row counts 2. **PostgreSQL for business data** — Rich types (jsonb, arrays, CHECK constraints, numeric precision) 3. **CHECK constraints over app-level validation** — Enforce enum values at the DB level 4. **Cascade deletes on M2M** — `onDelete: "cascade"` prevents orphaned association rows 5. **Exclude sensitive columns** — `columns: { passwordHash: false }` in session queries 6. **Repository pattern** — Separate Drizzle queries from service/business logic 7. **Session versioning** — Increment `sessionVersion` to force logout 8. **Seed with system roles** — Always seed an admin role and initial permissions ## References * [Drizzle ORM Docs](https://orm.drizzle.team/) * [Drizzle Kit CLI](https://orm.drizzle.team/kit-docs/) * [badmin schema](https://github.com/markbang/badmin) — SQLite RBAC * [cruise-ship schema](https://github.com/markbang/cruise-ship-system) — PostgreSQL business # Code Snippets Source: https://base.bangwu.me/code Developer cheatsheets and quick references covering Git commands, Docker operations, shell script snippets, and package manager shortcuts. # Code Path Hello! This section mostly records my [Cheatsheets](https://en.wikipedia.org/wiki/Cheat_sheet) and pitfalls encountered along the way. The knowledge base covers the following content (PRs and discussion welcome): > [card] [Frontend](/frontend/index) > > Vue, TailwindCSS, and component libraries. > [card] [Backend](/backend/index) > > Python, Go, and databases. > [card] [Desktop](/software/index) > > Tauri cross-platform development. > [card] [Algorithms](/algo/index) > > Algorithm practice and pattern-based notes. # CDN Setup Source: https://base.bangwu.me/env/CDN Domestic and overseas split CDN architecture using object storage with intelligent DNS routing for global acceleration and Rclone file sync. Currently using's CDN Solution from:[https://www.eallion.com/cdn-cname-cloudflare/](https://www.eallion.com/cdn-cname-cloudflare/) Take a look at the CDN structure diagram. Our goal is to solve the global CDN problem at a low cost. ![cdn\_dns](https://cdn.bangwu.top/img/cdn_dns.png) Previous articleBackup ### Introduction domestic and overseas traffic splitting,not only reduces costs,but also improves website performance,optimizes TTFB。 I don't remember when I started having such thoughts, so I went to search for it. It turns out that the tutorials online are quite old. Where most of the talk's is access to CNAME is through Cloudflare for SaaS, but it doesn't support regular domain names, and can't access R2 or Workers. In terms of function's priority, I need the partition resolution function most, which results in the inability to transfer the domain name's NS to Cloudflare. Cloudflare's DNS is indeed excellent, but Cloudflare doesn't support geo-based resolution, it has CNAME flattening, but it will resolve all mainland China's IPs to China Unicom. On the contrary, domestic DNS service providers do a good job in partition resolution, maybe because domestic domain names need this function more. Can't fully commit, but want to use Cloudflare, so have to use some tricks. In March 2022, Cloudflare announced changes to Cloudflare for SaaS's charging strategy. Each account can have 100 free domain names, and charges \$0.1/month per extra domain. We use Cloudflare for SaaS to connect domains via CNAME and enjoy Cloudflare's powerful edge calculation capabilities. Yes for small websites, such as this blogs, the above services are free's, free quota: * DNSPod: Use's professional version, but freeversions also has partition resolution * Tencent Cloud COS: 50G/month; 2 million requests * Tencent Cloud CDN: 10G/month * Cloudflare CDN: No upper limit for normal use * Cloudflare R2: 10G/month; 1 million/10 million requests * Backblaze B2: 10G/month; has \[Traffic Alliance] with Cloudflare([https://www.backblaze.com/cloud-storage/integrations](https://www.backblaze.com/cloud-storage/integrations)) I skip Tencent Cloud's Configuration and only talk about Cloudflare's part here. The prerequisite is that you already have an available domain name in your Cloudflare account. This domain name is used to provide `回退源` (Fallback Origin), assuming this domain name is `example.com`. ### Create R2 and bind a custom domain name 1. Log in to the control panel: [https://dash.cloudflare.com/](https://dash.cloudflare.com/), Cloudflare supportsChinese; 2. Create R2 bucket's Method is skipped here, for example, create: `r2-blog-test`; 3. in `R2` `设置` `公开Visit` `自Definition域` `连接域` Add a custom domain name to the 's R2 you just created: [![/assets/images/posts/2023/07/r2\_custom\_hostname.png](https://www.eallion.com/assets/images/posts/2023/07/r2_custom_hostname.png)](https://www.eallion.com/assets/images/posts/2023/07/r2_custom_hostname.png) Then the domain name's DNS will automatically appear with a resolution: [![/assets/images/posts/2023/07/custom\_hostname\_dns.png](https://www.eallion.com/assets/images/posts/2023/07/custom_hostname_dns.png)](https://www.eallion.com/assets/images/posts/2023/07/custom_hostname_dns.png) ### Subscribe to Cloudflare for SaaS 1. Select the domain name `example.com` in `Zones`; 2. Select `自Definition主机名` in the domain name's `SSL/TLS`; 3. Select Enable Subscription. Subscriptions can be made using Paypal. [![/assets/images/posts/2023/07/enable\_cloudflare\_saas.png](https://www.eallion.com/assets/images/posts/2023/07/enable_cloudflare_saas.png)](https://www.eallion.com/assets/images/posts/2023/07/enable_cloudflare_saas.png) ### Add custom domain name After the subscription is successful, first add `回退源`:`images.example.com`. This return-to-origin domain name is bound in R2's self-defined domain name. [![/assets/images/posts/2023/07/cf\_callback\_hostname.png](https://www.eallion.com/assets/images/posts/2023/07/cf_callback_hostname.png)](https://www.eallion.com/assets/images/posts/2023/07/cf_callback_hostname.png) Then click `添加自Definition主机名` and fill in the CDN domain name, such as `images.eallion.com`. The recommended validation method is TXT Validation. [![/assets/images/posts/2023/07/add\_custom\_hostname.png](https://www.eallion.com/assets/images/posts/2023/07/add_custom_hostname.png)](https://www.eallion.com/assets/images/posts/2023/07/add_custom_hostname.png) After adding, you need to validate the domain name. Go to your own domain name resolution console, such as DNSPod, and add 2 TXT records. Wait for both `证书State` and `主机名State` to become `有效`. [![/assets/images/posts/2023/07/cf\_dns\_txt\_records.png](https://www.eallion.com/assets/images/posts/2023/07/cf_dns_txt_records.png)](https://www.eallion.com/assets/images/posts/2023/07/cf_dns_txt_records.png) ### Parse CNAME After `回退源State` `证书State` and `主机名State` become `有效`, go to your own domain name resolution console to add CNAME resolution. Point the production environment's `images.eallion.com` CNAME to `images.example.com`. [![/assets/images/posts/2023/07/dns\_cname\_records.png](https://www.eallion.com/assets/images/posts/2023/07/dns_cname_records.png)](https://www.eallion.com/assets/images/posts/2023/07/dns_cname_records.png) Normally's tutorial ends here. But this way isVisit doesn't work with R2's resources. The most important step, use Worker Proxy R2. ### Create new Worker Proxy R2 There is official documentation on how to pass Worker Visit R2: Use R2 from Workers:[https://developers.cloudflare.com/r2/api/workers/workers-api-usage/](https://developers.cloudflare.com/r2/api/workers/workers-api-usage/) Just follow the documentation tutorial step by step. If you are lazy, you don’t want to authenticate. Then just use my streamlined code. The `DELETE` and `PUT` 's codes are directly removed, leaving only `GET`. Workers can be created manually in the background without Wrangle CLI scripts. Switch to the `Worker 和 Pages` column on the left, `创建应用程序`, just give it a name, choose a template Deployment, and change the code later. Click `快速edit` to copy the following code to `worker.js`, save and Deployment: ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} var worker_default = { async fetch(request, env) { if (request.method !== 'GET') { return new Response('Only GET method allowed', { status: 405 }); } const url = new URL(request.url); const key = url.pathname.slice(1); const object = await env.MY_BUCKET.get(key); if (!object) { return new Response('Object not found', { status: 404 }); } const headers = new Headers(); object.writeHttpMetadata(headers); headers.set('ETag', object.httpEtag); return new Response(object.body, { headers, }); }, }; export { worker_default as default }; ``` Returned after Deployment is successful. In the current Worker 's settings, `Variable` `R2 存储桶绑定` add binding: * `Variablename`:`MY_BUCKET` * `R2 存储桶`: Select yes should's bucket [![/assets/images/posts/2023/07/r2\_binding.png](https://www.eallion.com/assets/images/posts/2023/07/r2_binding.png)](https://www.eallion.com/assets/images/posts/2023/07/r2_binding.png) ### Workers routing Go back to Zones, select the domain name, and add Workers routing: * `路由`: Be sure to fill in the production environment's domain name, do not fill in Cloudflare's source domain name, such as: `images.eallion.com/*`; * `Worker`: Select the previous step to create's Worker; * `环境`:Production. [![/assets/images/posts/2023/07/r2\_worker\_router.png](https://www.eallion.com/assets/images/posts/2023/07/r2_worker_router.png)](https://www.eallion.com/assets/images/posts/2023/07/r2_worker_router.png) At this point, you should be able to visit Cloudflare R2's content using CNAME's method. * [https://images.eallion.com/eallion.jpg](https://images.eallion.com/eallion.jpg) ### Worker Proxy Backblaze B2 In fact, R2 is enough, but B2 may be needed for various reasons. Actually it's pretty much the same. Backblaze also has official documentation introducing how to visit B2 through Cloudflare Worker. Docs: [Integrate Cloudflare Workers with Backblaze B2](https://www.backblaze.com/docs/cloud-storage-integrate-cloudflare-workers-with-backblaze-b2) Let’s briefly introduce how to do it: (It is also recommended to read Official Docs.) ##### 1. Create a new Cloudflare Worker, `worker.js` ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} (() => { // node_modules/aws4fetch/dist/aws4fetch.esm.mjs var encoder = new TextEncoder(); var HOST_SERVICES = { appstream2: 'appstream', cloudhsmv2: 'cloudhsm', email: 'ses', marketplace: 'aws-marketplace', mobile: 'AWSMobileHubService', pinpoint: 'mobiletargeting', queue: 'sqs', 'git-codecommit': 'codecommit', 'mturk-requester-sandbox': 'mturk-requester', 'personalize-runtime': 'personalize', }; var UNSIGNABLE_HEADERS = /* @__PURE__ */ new Set([ 'authorization', 'content-type', 'content-length', 'user-agent', 'presigned-expires', 'expect', 'x-amzn-trace-id', 'range', 'connection', ]); var AwsClient = class { constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs, }) { if (accessKeyId == null) throw new TypeError('accessKeyId is a required option'); if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option'); this.accessKeyId = accessKeyId; this.secretAccessKey = secretAccessKey; this.sessionToken = sessionToken; this.service = service; this.region = region; this.cache = cache || /* @__PURE__ */ new Map(); this.retries = retries != null ? retries : 10; this.initRetryMs = initRetryMs || 50; } async sign(input, init) { if (input instanceof Request) { const { method, url, headers, body } = input; init = Object.assign({ method, url, headers }, init); if (init.body == null && headers.has('Content-Type')) { init.body = body != null && headers.has('X-Amz-Content-Sha256') ? body : await input.clone().arrayBuffer(); } input = url; } const signer = new AwsV4Signer( Object.assign({ url: input }, init, this, init && init.aws) ); const signed = Object.assign({}, init, await signer.sign()); delete signed.aws; try { return new Request(signed.url.toString(), signed); } catch (e) { if (e instanceof TypeError) { return new Request( signed.url.toString(), Object.assign({ duplex: 'half' }, signed) ); } throw e; } } async fetch(input, init) { for (let i = 0; i <= this.retries; i++) { const fetched = fetch(await this.sign(input, init)); if (i === this.retries) { return fetched; } const res = await fetched; if (res.status < 500 && res.status !== 429) { return res; } await new Promise((resolve) => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)) ); } throw new Error( 'An unknown error occurred, ensure retries is not negative' ); } }; var AwsV4Signer = class { constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode, }) { if (url == null) throw new TypeError('url is a required option'); if (accessKeyId == null) throw new TypeError('accessKeyId is a required option'); if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option'); this.method = method || (body ? 'POST' : 'GET'); this.url = new URL(url); this.headers = new Headers(headers || {}); this.body = body; this.accessKeyId = accessKeyId; this.secretAccessKey = secretAccessKey; this.sessionToken = sessionToken; let guessedService, guessedRegion; if (!service || !region) { [guessedService, guessedRegion] = guessServiceRegion( this.url, this.headers ); } this.service = service || guessedService || ''; this.region = region || guessedRegion || 'us-east-1'; this.cache = cache || /* @__PURE__ */ new Map(); this.datetime = datetime || new Date().toISOString().replace(/[:-]|\.\d{3}/g, ''); this.signQuery = signQuery; this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway'; this.headers.delete('Host'); if ( this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256') ) { this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD'); } const params = this.signQuery ? this.url.searchParams : this.headers; params.set('X-Amz-Date', this.datetime); if (this.sessionToken && !this.appendSessionToken) { params.set('X-Amz-Security-Token', this.sessionToken); } this.signableHeaders = ['host', ...this.headers.keys()] .filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header)) .sort(); this.signedHeaders = this.signableHeaders.join(';'); this.canonicalHeaders = this.signableHeaders .map( (header) => header + ':' + (header === 'host' ? this.url.host : (this.headers.get(header) || '').replace(/\s+/g, ' ')) ) .join('\n'); this.credentialString = [ this.datetime.slice(0, 8), this.region, this.service, 'aws4_request', ].join('/'); if (this.signQuery) { if (this.service === 's3' && !params.has('X-Amz-Expires')) { params.set('X-Amz-Expires', '86400'); } params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256'); params.set( 'X-Amz-Credential', this.accessKeyId + '/' + this.credentialString ); params.set('X-Amz-SignedHeaders', this.signedHeaders); } if (this.service === 's3') { try { this.encodedPath = decodeURIComponent( this.url.pathname.replace(/\+/g, ' ') ); } catch (e) { this.encodedPath = this.url.pathname; } } else { this.encodedPath = this.url.pathname.replace(/\/+/g, '/'); } if (!singleEncode) { this.encodedPath = encodeURIComponent(this.encodedPath).replace( /%2F/g, '/' ); } this.encodedPath = encodeRfc3986(this.encodedPath); const seenKeys = /* @__PURE__ */ new Set(); this.encodedSearch = [...this.url.searchParams] .filter(([k]) => { if (!k) return false; if (this.service === 's3') { if (seenKeys.has(k)) return false; seenKeys.add(k); } return true; }) .map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p)))) .sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0 ) .map((pair) => pair.join('=')) .join('&'); } async sign() { if (this.signQuery) { this.url.searchParams.set('X-Amz-Signature', await this.signature()); if (this.sessionToken && this.appendSessionToken) { this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken); } } else { this.headers.set('Authorization', await this.authHeader()); } return { method: this.method, url: this.url, headers: this.headers, body: this.body, }; } async authHeader() { return [ 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString, 'SignedHeaders=' + this.signedHeaders, 'Signature=' + (await this.signature()), ].join(', '); } async signature() { const date = this.datetime.slice(0, 8); const cacheKey = [ this.secretAccessKey, date, this.region, this.service, ].join(); let kCredentials = this.cache.get(cacheKey); if (!kCredentials) { const kDate = await hmac('AWS4' + this.secretAccessKey, date); const kRegion = await hmac(kDate, this.region); const kService = await hmac(kRegion, this.service); kCredentials = await hmac(kService, 'aws4_request'); this.cache.set(cacheKey, kCredentials); } return buf2hex(await hmac(kCredentials, await this.stringToSign())); } async stringToSign() { return [ 'AWS4-HMAC-SHA256', this.datetime, this.credentialString, buf2hex(await hash(await this.canonicalString())), ].join('\n'); } async canonicalString() { return [ this.method.toUpperCase(), this.encodedPath, this.encodedSearch, this.canonicalHeaders + '\n', this.signedHeaders, await this.hexBodyHash(), ].join('\n'); } async hexBodyHash() { let hashHeader = this.headers.get('X-Amz-Content-Sha256') || (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null); if (hashHeader == null) { if ( this.body && typeof this.body !== 'string' && !('byteLength' in this.body) ) { throw new Error( 'body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header' ); } hashHeader = buf2hex(await hash(this.body || '')); } return hashHeader; } }; async function hmac(key, string) { const cryptoKey = await crypto.subtle.importKey( 'raw', typeof key === 'string' ? encoder.encode(key) : key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign'] ); return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string)); } async function hash(content) { return crypto.subtle.digest( 'SHA-256', typeof content === 'string' ? encoder.encode(content) : content ); } function buf2hex(buffer) { return Array.prototype.map .call(new Uint8Array(buffer), (x) => ('0' + x.toString(16)).slice(-2)) .join(''); } function encodeRfc3986(urlEncodedStr) { return urlEncodedStr.replace( /[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase() ); } function guessServiceRegion(url, headers) { const { hostname, pathname } = url; if (hostname.endsWith('.r2.cloudflarestorage.com')) { return ['s3', 'auto']; } if (hostname.endsWith('.backblazeb2.com')) { const match2 = hostname.match( /^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/ ); return match2 != null ? ['s3', match2[1]] : ['', '']; } const match = hostname .replace('dualstack.', '') .match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/); let [service, region] = (match || ['', '']).slice(1, 3); if (region === 'us-gov') { region = 'us-gov-west-1'; } else if (region === 's3' || region === 's3-accelerate') { region = 'us-east-1'; service = 's3'; } else if (service === 'iot') { if (hostname.startsWith('iot.')) { service = 'execute-api'; } else if (hostname.startsWith('data.jobs.iot.')) { service = 'iot-jobs-data'; } else { service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata'; } } else if (service === 'autoscaling') { const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0]; if (targetPrefix === 'AnyScaleFrontendService') { service = 'application-autoscaling'; } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') { service = 'autoscaling-plans'; } } else if (region == null && service.startsWith('s3-')) { region = service.slice(3).replace(/^fips-|^external-1/, ''); service = 's3'; } else if (service.endsWith('-fips')) { service = service.slice(0, -5); } else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) { [service, region] = [region, service]; } return [HOST_SERVICES[service] || service, region]; } // index.js var UNSIGNABLE_HEADERS2 = ['x-forwarded-proto', 'x-real-ip']; function filterHeaders(headers) { return Array.from(headers.entries()).filter( (pair) => !UNSIGNABLE_HEADERS2.includes(pair[0]) && !pair[0].startsWith('cf-') ); } async function handleRequest(event, client2) { const request = event.request; if (!['GET', 'HEAD'].includes(request.method)) { return new Response(null, { status: 405, statusText: 'Method Not Allowed', }); } const url = new URL(request.url); let path = url.pathname.replace(/^\//, ''); path = path.replace(/\/$/, ''); const pathSegments = path.split('/'); if (ALLOW_LIST_BUCKET !== 'true') { if ( (BUCKET_NAME === '$path' && pathSegments[0].length < 2) || (BUCKET_NAME !== '$path' && path.length === 0) ) { return new Response(null, { status: 404, statusText: 'Not Found', }); } } switch (BUCKET_NAME) { case '$path': url.hostname = B2_ENDPOINT; break; break; case '$host': url.hostname = url.hostname.split('.')[0] + '.' + B2_ENDPOINT; break; default: url.hostname = BUCKET_NAME + '.' + B2_ENDPOINT; break; } const headers = filterHeaders(request.headers); const signedRequest = await client2.sign(url.toString(), { method: request.method, headers, body: request.body, }); return fetch(signedRequest); } var endpointRegex = /^s3\.([a-zA-Z0-9-]+)\.backblazeb2\.com$/; var [, aws_region] = B2_ENDPOINT.match(endpointRegex); var client = new AwsClient({ accessKeyId: B2_APPLICATION_KEY_ID, secretAccessKey: B2_APPLICATION_KEY, service: 's3', region: aws_region, }); addEventListener('fetch', function (event) { event.respondWith(handleRequest(event, client)); }); })(); ``` ##### 2. Set Worker Environment Variables * `ALLOW_LIST_BUCKET`:true * `B2_APPLICATION_KEY`:K004WJZP11111111111111111111Q * `B2_APPLICATION_KEY_ID`:0042e9999999920000000001 * `B2_ENDPOINT`:s3.us-west-004.backblazeb2.com * `BUCKET_NAME`:eallion-static The APP KEY and ID need to be generated in the Backblaze backend, and `B2_ENDPOINT` needs to be viewed in its own B2 bucket. ##### 3. Manually add CNAME to resolve to B2 [![/assets/images/posts/2023/07/b2\_cf\_record.png](https://www.eallion.com/assets/images/posts/2023/07/b2_cf_record.png)](https://www.eallion.com/assets/images/posts/2023/07/b2_cf_record.png) * `类型`: Select `CNAME` * `name`: used for `回退源`, such as: `b2.example.com`, fill in `b2` * `内容`: Fill in your own B2 bucket allocation's `S3 URL`, there's a tutorial here written byis `Friendly URL`, it's not necessary, there is one more step to reverse generation. [![/assets/images/posts/2023/07/backblaze\_url.png](https://www.eallion.com/assets/images/posts/2023/07/backblaze_url.png)](https://www.eallion.com/assets/images/posts/2023/07/backblaze_url.png) ##### 4. Configuration fallback source `Zones`'s domain name is Backblaze B2. Set's CNAME name is whatever it is, then fill in whatever the fallback source is, such as: `b2.example.com`. Just refer to the previous article. ##### 5. Configuration self-defined host name Refer to the previous article. ##### 6. Configuration Worker routing * `路由`: Be sure to fill in the production environment's domain name, do not fill in Cloudflare's source domain name; * `Worker`: Select the previous step to create's Worker; * `环境`:Production. Adding Worker routes for Backblaze B2 is different from Cloudflare R2. You need to add 2 items: * `b2.example.com/*` also needs to be added to the Worker route * `images.eallion.com/*` ::: CDN certificate automatic replacement The above has solved the basic issue, but there is still a pain point with the SSL certificate issue. CF offers free renewal and update of never-expired certificates, but domestic CDN manufacturers generally need to manually upload their own application's certificates. . . This is really inconvenient, so I was wondering if I could find some solutions: ::: details Automatically update certificate scripts Cause: Because Configuration domestic CDN basically requires manual uploading of certificates, but the domain name certificate I applied for basically has a three-month shelf life, so I thought of writing an automatic script to automatically update the certificate. Environment: 1panel (domestic panel, automatic application for certificates, and other powerful functions, very convenient's) I use Duojiyun as an example. Other manufacturers can find the corresponding SDK. The code is as follows: ```python theme={"theme":{"light":"github-light","dark":"github-dark"}} from hashlib import sha1 import hmac import requests import json import urllib def dogecloud_api(api_path, data={}, json_mode=False): """ 调用多吉云API :param api_path: 调用's API Interface地址,Package含 URL 请求parameters QueryString,for example:/console/vfetch/add.json?url=xxx&a=1&b=2 :param data: POST 's 数据,dictionary,for example {'a': 1, 'b': 2},传递此parameters表示不is GET 请求而is POST 请求 :param json_mode: 数据 data is否以 JSON 格式请求,默认为 false 则使用Form形式(a=1&b=2) :type api_path: string :type data: dict :type json_mode bool :return dict: 返回's 数据 """ # 这里替换为你's 多吉云永久 AccessKey 和 SecretKey,可in用户中心 - 密钥管理中View # 请勿in客户端暴露 AccessKey 和 SecretKey,否则恶意用户将获得账号完全控制权 access_key = '' secret_key = '' body = '' mime = '' if json_mode: body = json.dumps(data) mime = 'application/json' else: body = urllib.parse.urlencode(data) # Python 2 可以直接用 urllib.urlencode mime = 'application/x-www-form-urlencoded' sign_str = api_path + "\n" + body signed_data = hmac.new(secret_key.encode('utf-8'), sign_str.encode('utf-8'), sha1) sign = signed_data.digest().hex() authorization = 'TOKEN ' + access_key + ':' + sign response = requests.post('https://api.dogecloud.com' + api_path, data=body, headers = { 'Authorization': authorization, 'Content-Type': mime }) return response.json() api = dogecloud_api('/cdn/cert/list.json') if api['code'] == 200: for cert in api['data']['certs']: ssl_next_id = cert['id'] delet_api = dogecloud_api('/cdn/cert/delete.json', { 'id': cert['id'] }) else: print("api failed: " + api['msg']) # 失败 # 下面两个路径就is1panelauto-generated证书路径 with open('/opt/1panel/apps/openresty/openresty/www/sites/xxxx/ssl/fullchain.pem') as fullchain: full = fullchain.read() with open('/opt/1panel/apps/openresty/openresty/www/sites/xxxx/ssl/privkey.pem') as privkey: priv = privkey.read() api = dogecloud_api('/cdn/cert/upload.json', { "note": f"自动证书{ssl_next_id}", "cert": full, "private": priv }) if api['code'] == 200: ssl_id = api['data']['id'] else: print("api failed: " + api['msg']) # 失败 api = dogecloud_api('/cdn/domain/config.json?domain=cdn.example.com', { 'cert_id': ssl_id }, True) ``` The basic implementation idea is to first remove the existing certificate, then add the read's certificate, then upload and activate the uploaded's certificate, so that the Implementation CDN certificate is automatically configured. You can use 1panel to automatically execute scripts every one month to update the certificate. It's really Implementation again a Qiweiwei's tips ✊✊✊ ::: # Caddy Source: https://base.bangwu.me/env/Caddy Caddy is a modern Go web server with automatic HTTPS certificate management, covering Caddyfile syntax, reverse proxy setup, and file hosting. # Web server ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list sudo apt update sudo apt install caddy ``` The simplest configuration looks like this: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} example.com { reverse_proxy localhost:port } ``` Just point the domain's DNS record to your server IP. Caddy will handle HTTPS automatically, which makes the setup very straightforward. # Fuwari Source: https://base.bangwu.me/env/Fuwari Fuwari is an Astro-based static blog theme with clean design, covering project setup, article frontmatter format, tags, and deployment steps. ## Fuwari [Fuwari](https://github.com/saicaca/fuwari) is an Astro-based static blog theme with a clean and elegant style. ### Features * 🚀 **Fast**: built on Astro with excellent performance * 🎨 **Beautiful**: modern design and responsive layout * 🌙 **Dark Mode**: supports light and dark theme switching * 📝 **Markdown**: write posts in Markdown * 🔍 **SEO-friendly**: optimized for search indexing * 📱 **Responsive**: works well on mobile devices * 💬 **Comments**: supports multiple comment systems * 🔗 **Friend links**: supports a dedicated links page ### Quick start ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # clone the project git clone https://github.com/saicaca/fuwari.git cd fuwari # InstallationDependency npm install # local development npm run dev # built npm run built ``` ### Configuration Edit `src/config.ts`: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} export const siteConfig = { title: '你's blogstitle', subtitle: 'Subtitle', lang: 'zh-CN', description: 'blogsDescription', author: 'Author Name', avatar: '/avatar.jpg', // Social Links socialLinks: [ { name: 'github', url: 'https://github.com/username' }, { name: 'twitter', url: 'https://twitter.com/username' }, ], } ``` ### Create a post Create a Markdown file under `src/content/posts/`: ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} --- title: Article Title published: 2024-01-01 description: Article Description tags: [Tag1, Tag2] category: Category draft: false --- Article Content... ``` ### Deployment #### GitHub Pages ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} # .github/workflows/deploy.yml name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 18 - run: npm install - run: npm run built - uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./dist ``` #### Vercel 1. Import the GitHub repo into Vercel. 2. Set the build command to `npm run built`. 3. Set the output directory to `dist`. #### Cloudflare Pages 1. Connect the GitHub repo. 2. Set the build command to `npm run built`. 3. Set the output directory to `dist`. ### Customization #### Modify theme colors Edit `src/styles/global.css`: ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} :root { --primary: #your-color; } ``` #### Add a comment system Fuwari supports comment systems such as Giscus and Waline. Enable the one you want in the config file. ### References * [GitHub repository](https://github.com/saicaca/fuwari) * [Demo site](https://fuwari.vercel.app/) * [Astro documentation](https://docs.astro.build/) # Jupyter Source: https://base.bangwu.me/env/Jupyter Jupyter Notebook is an interactive data analysis tool for running code in the browser, covering installation, remote SSH access, and shortcuts. # Jupyter ## Jupyter Notebook ## Interactive code notebooks in the browser Jupyter Notebook is the first-generation product from the Jupyter team and still the most classic one. If you have learned Python before, you are probably already familiar with it. ## JupyterLab JupyterLab is the more advanced successor to Jupyter Notebook, with a richer interface and more features. ## JupyterLite JupyterLite is a lightweight static Jupyter environment built by the Jupyter team to run entirely in the browser. In other words, as long as you have a browser, you can use it without a server or a local programming environment. That is exactly why it is called “Lite”. ### Advantages A lightweight tool like this is especially suitable for embedding an online code editor in a web page. ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` Embedding the snippet above in an HTML page gives you a simple editor. It could be extended further with code completion and other features. # Agent harness Source: https://base.bangwu.me/env/agent-harness A practical guide to AI agent harness design, covering memory, skills, protocols, context management, evals, and common failure modes. # Agent harness An agent harness is the runtime layer around an AI model. It decides what context the model sees, which tools it can call, how permissions work, where memory lives, and how the agent recovers from mistakes. Do not treat the harness as plumbing. For coding agents and workflow agents, the harness often determines reliability more than the raw model choice. ## The useful mental model A good agent system externalizes capabilities that should not live only inside model weights. | Layer | What it externalizes | Examples | | - | - | - | | Memory | Durable state and retrieval | project notes, user preferences, task history, vector search | | Skills | Reusable procedures | browser control, code review, image generation, deployment helpers | | Protocols | Communication contracts | MCP, JSON schemas, typed tool responses, error formats | | Harness | Runtime coordination | context assembly, tool routing, approvals, logs, retries, evals | This model comes from the paper **Externalization in LLM Agents: A Unified Review of Memory, Skills, Protocols and Harness Engineering**. The important engineering question is: > Which capability should stay implicit in the model, and which capability should become an explicit external component? If the answer affects reliability, auditability, reuse, or cost, it usually belongs outside the model. ## What the harness owns The harness should make these decisions explicit: * which files, pages, tools, and memories enter context * when old context is summarized, dropped, or preserved * how tool calls are validated before execution * which actions require user approval * how tool errors are represented and retried * how model effort, latency, and cost trade off * how runs are logged for later debugging A thin harness can work, but an implicit harness becomes hard to debug. If behavior changes and nobody knows whether the cause is the model, prompt, context cache, tool layer, or product default, the harness is under-instrumented. ## Design rules ### Keep tools small and inspectable Prefer narrow tools with clear inputs and outputs. A tool that does one thing is easier for the model to call correctly and easier for humans to audit. For local workflows, CLI tools are often enough. For reusable cross-client integration, use a protocol boundary such as MCP. For stable product backends, a direct API is still the simplest option. MCP got much better in 2026 — it is now stateless, supports deferred tool loading, and models are stronger at structured tool calling. That does **not** mean MCP is better than CLI for most integrations. Prefer **CLI** when: * the model already knows the command (`gh`, `aws`, `kubectl`) so you spend almost no schema tokens * you are on a local machine or in CI with a fixed command * you need pipes, composition, or a one-off debug loop * token cost matters and `--help` plus a skill is enough to teach a new CLI Prefer **MCP** when: * there is no terminal (browser, mobile, hosted agent) * you need OAuth, per-user auth, or standardized audit headers * the tool is new to the model and a machine-checkable JSON schema is worth the extra tokens * the tool set is dynamic and agents should discover tools at runtime (`tools/list` + deferred loading) A useful rule: CLI wins on known local tools and composition. MCP wins on auth, audit, discovery, and environments without a shell. ### Separate chat transport from agent execution A messaging adapter should normalize platform events and deliver replies, not become the agent framework. BerriAI's `agentchat` makes this split explicit: channel adapters emit shared message objects; the core claims message IDs, locks the conversation, records history, and dispatches to an application handler. The handler owns sender authorization and the agent run. Its architecture and source at commit `fb892cb` provide a useful reference, with important limits: | Responsibility | Keep it in | | - | - | | Provider credentials, event decoding, acknowledgments, reply rendering | Platform adapter or authenticated ingress | | Duplicate-event detection and per-conversation serialization | Shared state/coordination layer | | User authorization, agent/session mapping, tool permissions | Application handler and execution policy | | Durable jobs, crash recovery, uncertain delivery reconciliation | Application-owned durable infrastructure | Do not confuse the boundaries: * **Authenticated event is not authorized work.** For Slack HTTP requests, verify the signature over the raw body and timestamp using the documented scheme and a constant-time comparison. Then separately decide what that sender may ask the agent to do. Socket Mode uses a different ingress mechanism; do not apply HTTP signing rules indiscriminately to every transport. * **Acknowledgment is not completion.** Slack's HTTP Events API requires a 2xx response within three seconds and can retry failed deliveries. If you promise durable processing, persist/enqueue accepted work before acknowledging it; keep model execution out of the acknowledgment path. Handle enqueue failure explicitly rather than returning success and dropping work. * **Deduplication is not crash recovery.** In this `agentchat` snapshot, the default `MemoryState` keeps claims, locks, and history in one process. A claim is recorded before the handler runs, with no claim rollback in `_receive`. A handler failure is therefore not automatically retried by delivering the same event again in that process; a restart, meanwhile, loses the in-memory claims. Production recovery needs a durable job lifecycle and explicit retry policy, not just a set of seen IDs. * **A conversation lock is not a global ordering guarantee.** It serializes local processing, not provider timestamps or workers in other processes. Scope conversation keys to the provider, installation/tenant, and conversation or thread. Coordinate workers through shared storage or partitioning, and explicitly decide whether a group thread shares context across users. * **Agent completion is not confirmed delivery.** Persist the generated reply and delivery state separately. If sending times out, reconcile the provider's receipt or use its documented deduplication mechanism; rerunning the whole agent may repeat tool side effects without fixing the missing reply. These are production design requirements, not claims that the SDK implements a durable queue or exactly-once execution. Test duplicate delivery, unauthorized senders, concurrent messages, restart after acceptance, handler failure, and send-timeout ambiguity before exposing an agent to a chat platform. Those cases belong in [product evals and regression tests](/env/ai-evals), even when the happy-path demo needs only a few lines. ### Separate skill design from execution A skill is a manual for the agent — it should only contain what the model does not already know. The execution is done by tools (scripts, CLI, apps) that the model calls directly. Keep the two apart: * **Design logic** lives in the SKILL.md and describes *what* to do and *why*. * **Execution logic** lives in scripts and tools and describes *how* to do it. Scripts can be pre-written or generated on the fly by the agent when a task needs one. Generated scripts are flexible — agents already do this even without a skill, often writing a one-off Python snippet. They are also slower, more token-hungry, and less complete on edge cases. Pre-written scripts win when the task is recurring and quality matters: a Markdown-to-HTML skill that generates the converter at runtime will be barely usable, while a pre-written converter can cover styles and edge cases. Treat generated scripts as throwaway until verified. This separation explains why strong skills still need a UI: the skill tells the agent what to accomplish, while a UI carries the concrete execution steps a human can trigger with a few clicks instead of re-prompting from scratch each time. Skills did not kill MCP, and RAG is not dead. They solve different problems and often sit in the same workflow: * **MCP** is a shared interface: structured tool calls, auth, and data access. * **Skills** are packaged expertise: how this team works, how this project should change, which conventions matter. Markdown is a feature — humans can read it too. * **RAG / retrieval** grounds the model in documents, tickets, and code that are not in weights. MCP provides access. Skills explain how to use that access well. Retrieval starts the model closer to the answer. Pick the layer that matches the gap, not a winner. ### Preserve reasoning-critical context Context pruning is not just a cost optimization. It changes behavior. If an agent made tool calls or file edits based on earlier reasoning, the harness must preserve enough rationale for later turns to continue coherently. Otherwise the agent may repeat itself, forget why it chose a path, or pick odd tools. ### Represent durable state as files Long-running agent workflows need state outside chat history. Plain files are often the simplest durable memory layer because humans can inspect, edit, diff, and version them. A useful pattern is a workspace that separates intent, resources, work products, and learning records: ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} workspace/ ├── MISSION.md # why this work or learning track exists ├── RESOURCES.md # trusted sources and references ├── NOTES.md # preferences and scratch notes ├── lessons/ # one self-contained learning unit per file ├── reference/ # compressed long-term reference material └── learning-records/ # what changed in the user's capability ``` The exact names can change. The important rule is that state should be **inspectable, restartable, and scoped**. For agent-assisted learning, this lets the agent teach the next step from the learner's current capability instead of from a generic syllabus. For engineering work, the same pattern applies to onboarding notes, migration logs, incident follow-ups, and task journals. ### Reset at checkpoints; keep raw history retrievable A summary is a lossy copy. When a harness compacts a long session, it rereads the history and rewrites it as prose. The exact error message, file path, or number the next step needs may not survive. Two October 2026 papers point to a different default. * **Checkpoint, then start clean.** CORAL (COLM 2026) gives the agent a tool it can call to save task progress and verified facts, clear the cluttered context, and start a new episode that sees only the checkpoint. An 8B model trained to use the tool with reinforcement learning (MERPO) reached 42.8% average accuracy on GAIA. The biggest gains were on the long-horizon Level 2 and 3 tasks, and it used 6–7× fewer input tokens than a ReAct agent. The authors used RL to improve when and what the agent checkpoints, so do not expect an untrained model to time resets well on its own. Without RL, approximate it with a fixed checkpoint template (verified facts, open questions, next step) that the agent fills at phase boundaries before you open a fresh session. * **Keep the raw record and retrieve from it.** Raw-RAG (arXiv 2610.30755) splits raw conversation history into windows and uses dense retrieval plus cross-encoder reranking, with no extraction, summaries, or graphs. It ranked first among the compared memory systems in 6 of 7 benchmark–model settings across LoCoMo, LongMemEval, MEME, and MemoryAgentBench. Adding fact extraction, summaries, or graph expansion on top *lowered* accuracy. In the authors' Mem0 audit, making memory append-only (no UPDATE or DELETE) raised LoCoMo accuracy from 67.36% to 69.42%. The likely reason: answers often depend on the order of events and on how one value led to another, and transformations drop that context. The rule that carries over: **write the full session record append-only, keep the checkpoint small and verified, and let a fresh session search the raw record on demand.** Treat summaries as an index into the record, not a replacement for it. See [Claude Code patterns](/env/claude-code-patterns) for the interactive version of this workflow. Limits: Raw-RAG's evidence comes from offline conversation benchmarks, and raw logs cost storage and raise privacy questions. Compaction is still reasonable when the agent has no tool to search its own history. Compare both on your own tasks before committing to one. ### Audit memory for the associativity blind spot Every current memory architecture — Flat RAG, graph memory, agentic hierarchies, OS-style memory kernels — retrieves with the same recipe: embed query and stored content into one similarity space (BM25 or dense vectors), take top-K. That caps recall at **surface similarity**. It covers only *descriptive* recall — the query shares wording, entities, or timestamps with the memory. The other half is *associative* recall: a month-old note that "someone on the team has a severe seafood allergy" is the decisive evidence for today's question "where should the team dinner be?" Zero lexical overlap; only a semantic arc (causality, same situation) connects them. Tencent's **T-Mem** paper (2026) measures the blind spot: on LoCoMo-Plus Cognitive questions — built to strip lexical overlap — similarity-based systems score 32–49%, and GPT-4o reading the entire transcript scores only 21%. T-Mem's fix borrows from cognitive science (episodic future thinking): at **write time**, compute and store a prediction of *when this memory will matter again* — a trigger. Four trigger families cover the 2×2 space of granularity (fact / scene) × orientation (descriptive / associative). The two associative families are the point: * **Bridge trigger** — project a fact into the concrete situation where knowing it will help: "seafood allergy → picking a restaurant for the team dinner", with one step of reasoning why. * **Horizon trigger** — project a scene onto forward-looking dimensions so a future query approaching from a different context still hits it. Their ablation is the headline: removing Horizon triggers moves the standard benchmark by 0.08 points but collapses the associative one by 12.47. Systems tuned only on similarity benchmarks are implicitly optimizing to stay inside the similarity neighborhood — and that benchmark family cannot see the cost of the neighborhood's edge. The transferable rule: **do recall-plan at write time, when you know the content best.** Materialize the questions each item should answer, not just the item. It costs tokens once, offline; it saves the query every time after. ### Make retrieval deterministic when correctness matters Do not ask an agent to "figure it out" through brittle websites, scattered databases, or undocumented one-off scripts when the task needs exact results. Give it a deterministic retrieval layer instead. Anthropic's biology-agent case study is a good example. Scientific agents were asked to retrieve viral sequence data from NCBI Virus. The durable lesson was not that one model won a benchmark; it was that reliability improved dramatically when the workflow added `gget virus`, a deterministic retrieval layer with a narrower interface. For high-stakes retrieval, prefer: * typed query functions over free-form browsing * stable IDs, versions, and date filters * machine-checkable counts or checksums * explicit provenance for every returned record * validation steps before downstream analysis * documented error cases instead of silent best-effort output This is the same harness principle as tool design: make the execution surface predictable, then let the model plan around it. The first retrieval move deserves disproportionate investment. The **Question's Gambit** paper (2026) lifted GPT-5.5 from 83.1% to 90.5% on BrowseComp-Plus with the same retriever and the same agent loop — the only change was a single pre-search step that runs once, before the loop starts: split the question into clues, turn each clue into complementary searches, pool the results, and rerank. The agent then starts with a ranked evidence set already in context. The same change lifted a mini model from 68.1% to 79.0% and roughly halved calibration error. The error analysis is the real lesson: of 79 remaining errors for the strongest model, only 3 came from the gold document never being retrieved. The other 76 happened later — previewing, opening, or using the evidence. **Front-load the opening context; verify the consumption, not just the fetch.** Cost: 2.3–5.3 extra tool calls per question, cheap against a full failed run. ### Judge indexes by context cost, not just accuracy Once a search loop is competent, extra index structures may not raise accuracy at all. The RAGFlow team (arXiv 2610.41172) ran a harness with only BM25 and `grep` on MiniMax M3. With no vector or compiled index, it answered 85% of BrowseComp-Plus and 91% of multi-hop FRAMES questions. Adding summary trees, a PageIndex-style outline, wikis, or graphs gave no detectable accuracy gain on FRAMES, and the outline got worse at scale. The structures paid off in context instead. A navigation tree whose leaves are **claim–evidence pairs** cut query tokens by 91% when the leaf evidence was enough to answer, and added 1.9% when it wasn't, a 38% average saving. The token saving is bought with extra retrieval rounds, so it costs latency. A decision gate that chose when to stop cut latency from 140 seconds to 30. Other artifacts, such as ontologies, timelines, and entity graphs, earned their keep in governance, onboarding, and continuity, which accuracy benchmarks don't measure. Practical order: start with lexical search (BM25, `grep`) and a disciplined loop that doesn't repeat queries or reread documents. Add compiled structures only when you can show they cut tokens or latency on your own queries. Make leaves self-contained claims with their evidence, so the agent can stop reading early. This matches the [raw-history finding](#reset-at-checkpoints-keep-raw-history-retrievable) above: keep the source, and treat compiled views as a way in, not a replacement. ### Design for human collaboration, not just autonomous execution Most agent products optimize for self-evolution: the agent plans, executes, and closes the loop on its own. This is not always a healthy pattern. Even with transparency and traceability tools, an agent that prioritizes autonomous completion can create noise that is hard to hand off or maintain. An agent is not only an execution container. It is also an environment for human understanding, judgment, and collaboration. When designing a harness, ask: can another person pick up this session and continue? Is the reasoning visible enough for a teammate to audit a decision? Does the workflow produce a maintainable artifact, or just a pile of automated steps? Prioritize handoff quality over automation completeness. A workflow that ends with a clear, inspectable state is more valuable than one that "finished everything" but left no trail. ### Make telemetry and anti-abuse signals explicit A coding agent with filesystem and shell access should be boring. Every non-obvious behavior erodes trust. In July 2026, a developer auditing Claude Code discovered prompt steganography: the binary silently modified invisible Unicode characters in the system prompt date string (`Today's` → `Today\u2019s`) based on timezone (`Asia/Shanghai`, `Asia/Urumqi`) and hostname matching against XOR-encoded domain lists of Chinese AI labs, proxy services, and reseller gateways. The signal was never documented. The detection goal is defensible — Anthropic wants to identify API resellers and distillation pipelines. The implementation is not. Hiding classification bits inside invisible punctuation, behind XOR and base64, makes every other privacy claim harder to believe. A simple bypass (change hostname, change timezone, patch binary) defeats the signal anyway, so the feature mainly punishes legitimate developers using custom API gateways. The harness lesson: if your tool needs to detect abuse, make the signal explicit. Document it. Put it in release notes. Send a clear telemetry field. Transparency is not the enemy of anti-abuse — it is the foundation of trust. ### Make effort settings visible Reasoning effort is a product decision, not only a model parameter. Lower effort can reduce latency and token use, but it can also make hard coding tasks feel worse. Expose the current effort level, make it easy to change, and avoid silently changing defaults for complex workflows. ### Treat system prompts as code System prompt edits can change quality as much as code changes. Review them with the same discipline: * run per-model evals * use ablations to test individual instructions * roll out gradually * keep an audit trail * gate model-specific instructions to the intended model Prompt brevity rules are especially risky for coding agents. If the agent is forced to be terse between tool calls, it may lose useful planning and verification behavior. ### Test the public harness Internal builds can hide production-only issues. Dogfood the exact public build, public defaults, and public context behavior. For code review or coding-agent evals, include the repositories and files the agent would actually need. A review that lacks cross-repo context can miss the bug even when the model is capable of finding it. ## Verification-first design A practitioner shipping \~2,000 PRs a month through Cursor's pstack skills distilled the core principle as **"verification is all you need"**: the agent can close the loop on its own only if it can confirm its changes actually work. Verification is critical infrastructure, not an afterthought — worth the same investment as a production system. Three components make it practical: **1. A verification CLI, not markdown instructions.** Give the agent a small CLI that wraps app interaction and debugging — snapshot/screenshot, navigate, click/type, trace/wait-settle, health checks. A tool beats a one-off script every time: less token spend, reproducible, testable. Agent-friendly CLI design rules: * composable API (deep modules: one command does one meaningful thing) * destructive commands take `--dry-run` * subcommands disclose features progressively * error messages tell the agent *what to do next* * rich `--help` and JSON output **2. A feature map as materialized memory.** A set of markdown files describing what each feature is, how a user reaches it, and where the traps are. It is a compressed projection of the codebase — the code is the ultimate memory, and the map exists only to save tokens. Maintain it with a daily routine so it never goes stale. **3. Cloud parallelism.** Local worktrees cap out around ten parallel agents and burn resources. Cloud agents with real machines, dependency installs, app runs, screen recording, and post-build snapshots enable hundreds of parallel sub-agents — the prerequisite for swarm verification and fuzz regression at scale. The stack-selection corollary: **prefer debuggable runtimes.** If a tech stack can't be screenshotted, has no accessibility tree, and no performance traces, the agent cannot verify its own work. It is reasonable to change stack for agent-verifiability alone — Web/Electron exposes Chrome DevTools Protocol; iOS exposes the simulator. The strongest quantitative case that harness beats model: the **GAVEL** paper (2026) took Qwen3-8B on long-horizon robot tasks from 41.2% to 91.8% with zero changes to the model. It adds an explicit graph world model — object relations, action preconditions and effects, probabilistic beliefs about unobserved objects. Before executing an LLM-generated action, the graph predicts what that action would do; violations get caught, and those with a mechanical fix are repaired without calling the model again. Only errors needing semantic reasoning go back to the LLM. On BEHAVIOR-1K, success rose from 19.9% to 92.6% across 500 multi-task instructions. The reusable lesson: many long-horizon agent failures are **state-tracking failures, not reasoning failures**, and a symbolic checker outside the LLM catches them cheaply. Wrap the model's decision point in deterministic structure — a world model, a candidate list, a verifier — and the small model stops paying for what the harness already knows. ### Spend verification effort where it pays A verification CLI makes checking possible. The next questions are when to check and who checks. Alibaba and Cornell (arXiv 2610.34577) compared 17 verification designs across seven frontier coding models on Terminal-Bench (TB) and SWE-bench Verified (SWE), grouped into four layers: | Layer | What it adds | Accuracy change | Cost vs. baseline | | - | - | - | - | | L0 instructions | "Actually run it and read the real output; rereading the code isn't evidence" | +3.3 TB / +3.9 SWE in the system prompt; weaker in the user message | Little extra | | L1 reminders | Nudges after edits or every few turns, capped at four | Mixed: up to +5.4 TB, flat on SWE | Little extra | | L2 completion gates | When the agent stops, ask it to recheck, or reject the first "done" | Best variant +6.0 TB / +6.2 SWE | Rejection gates 1.48–1.76× | | L3 independent review | A separate critic checks the work | +5.9–9.5 TB / +3.9–6.6 SWE | 1.13–1.25× TB, 1.00–1.04× SWE | The critic setup is the part to copy: * **Fresh context: the task plus the diff.** Giving the critic the agent's full trajectory cost 29–43% more and did no better on the visual benchmark. * **A live sandbox, read-only for the deliverable.** The critic runs its own checks but never edits the work; scratch files go in `/tmp`. * **A structured verdict.** A `done` flag, feedback, and a checklist with evidence for each requirement. * **A bounded loop.** Objections go back to the agent as a user message, and the next delivery is accepted without another review. * **Look at rendered output** for UI and visual artifacts, not just the code. Scaling also favored independence. On TB, one critic for one round reached 62.7% at $0.47 per task. Four rounds reached 66.1% at $0.77, and four separate critics reached 65.8% at \$0.62. The practical order: before adding more reminders to the main agent's prompt, add one independent reviewer with fresh context and a single revision pass. [AI code review](/env/ai-code-review) applies the same layering to pull requests. ## Failure modes to watch For the review side of high-volume agent output — layered checks, verified findings, risk-tiered approvals, and reviewer evals — see [Code review when agents write the code](/env/ai-code-review). Anthropic's April 2026 Claude Code postmortem is a useful case study because the reported degradation came from product and harness changes, not the base API model. Common failure modes: * **Default effort regression**: a latency-driven default can reduce perceived intelligence on hard work. * **Context cache bug**: pruning or clearing reasoning history at the wrong time can make the agent forgetful and repetitive. * **Over-tight prompt constraint**: broad brevity instructions can reduce coding quality. * **Eval blind spot**: internal evals may pass while real user workflows fail. * **Build mismatch**: staff may test a different harness than users run. The practical lesson is simple: when an agent gets worse, debug the whole runtime, not just the model. ## Destructive tool safety Agents with filesystem and shell access can destroy work in seconds. A real postmortem from August 2026 is worth studying: a developer running Codex + Trellis + Zcode on a GLM model lost their entire workspace when the agent ran `rm -rf` on the wrong directory. The root cause: the agent intended to delete an empty directory created by a casing typo. On macOS's case-insensitive filesystem, the command silently resolved to the real, populated directory — deleting the whole repository including git history, uncommitted changes, task records, migrations, and docs. No backup existed. The lessons generalize beyond this one accident: * **Be cautious with full access.** Prefer a harness with an approval flow (such as "help me approve" review) over unrestricted auto-execution. * **Isolate the dev directory.** Keep agent workspaces separate from other files, so a deletion error can't take out anything valuable. * **Push early and often.** Remote git history is the last line of defense against local deletion — it survives what no local backup can. * **Treat benchmark scores skeptically for safety.** The same model that was "safe by reputation" committed a trivially destructive error. Safety claims and benchmark wins are not the same as real-world filesystem judgment. The deeper harness principle: destructive operations should be treated as a permission boundary, not a capability. If a tool can `rm -rf`, it should be gated, logged, and reversible by default — and the agent should never be given a broader scope than the task requires. ### Separate discovery from purchase approval Paid operations need an explicit boundary too. Vercel's domain CLI provides a concrete example: the agent can discover candidates with `vercel domains search`, check availability with `vercel domains check`, and retrieve pricing with `vercel domains price`. According to Vercel's announcement, a non-interactive `vercel domains buy` returns a structured error with suggested next commands instead of completing the purchase. The user confirms the price, auto-renew choice, and registrant details in an interactive terminal or the dashboard. The reusable pattern is **prepare → request approval → execute → verify**, not “give the agent a payment credential and tell it to be careful.” For your own tools: * **Allow scoped discovery separately from spending.** Permission to compare options does not authorize buying one. * **Make approval actionable.** Present the exact resource, account or team, current quote and currency, term, and recurring-payment choice. Reconfirm if those details change. * **Stop on approval-required responses.** Route the structured result to the user; do not retry through another interface, auto-answer prompts, or treat an interactive terminal as proof of consent. * **Enforce the gate outside the model.** A skill can explain the procedure, but tool permissions and the transaction service must enforce it. A CLI-only prompt is insufficient if the agent can use another purchase path with the same credentials. * **Verify before retrying.** Record the user's decision and transaction result without logging secrets or unnecessary contact data. If a request times out, check the provider's order state before attempting another purchase. These are harness-design recommendations; the Vercel example demonstrates the discovery/confirmation split, not a guarantee that every payment interface enforces all of these controls. Check the installed CLI's behavior before granting it spending access. ### Check selected tool calls before they run Many agent loops execute a tool call as soon as the model proposes it. IBM's JevAct (arXiv 2610.38620) adds a gate between proposal and execution, without changing the agent model or its tools: 1. **Compile the policy offline.** An LLM turns the written domain policy into executable checks over tool state, fixed yes/no questions about the conversation, and a checklist of steps the agent must try before handing off to a human. 2. **At runtime, check facts with code and context with a decision model.** Code verifies what the tool records already show. A small prefill-only decision model answers the questions with a probability instead of generated text, so the gate can apply a threshold. 3. **Return failures as feedback with a retry budget.** A flagged call goes back to the agent with the specific reason. The agent gets a bounded number of revisions (two for write calls in the paper). The agent still chooses its actions; the gate only approves or returns them. 4. **Check endings as well as actions.** A hand-off check catches agents that give up before they've tried the required steps. On τ²-bench Telecom, all eight agents improved, and success across three runs rose by 16.9 points on average. Opus 4.6 went from 39.5% to 80.7%. On BFCL, all nine agents improved three-run success; Airline gains were smaller and mixed. These numbers measure the whole harness (checks plus revision chances), not the judge alone. The decision model's cost was $0.0003–0.0017 per task, against $0.0127–0.0231 for API-model judges. Rules that carry over: * **Gate writes and task endings, not every call.** A wrong answer can often be corrected in a later turn; an unauthorized write or a premature hand-off is harder to undo. * **Put checkable facts in code.** Use the model only for questions that need the conversation. * **Drop questions that fire too often.** Real violations are rare. The paper dropped any question that flagged more than 10% of logged calls. * **Tune thresholds on logged traces, not defaults.** Check the judge's context length too: smaller judges missed more bad calls on inputs over 8k tokens. See [AI product evals](/env/ai-evals) for threshold calibration. ## Put the control plane outside the agent's reach Long-running agents download code, build tools, and request more permissions as they go, so risk compounds along a path nobody fully specified in advance. NVIDIA's framing for its OpenShell reference architecture is worth adopting as a design rule regardless of vendor: **an agent cannot govern itself.** Authorization, network egress, credential issuance, and audit belong in infrastructure the agent cannot edit. OpenShell splits the runtime into four parts, and the split itself is the lesson: | Component | Responsibility | | - | - | | **Gateway** | Control plane: sandbox lifecycle and policy | | **Supervisor** | Runs outside the sandbox; checks outbound requests against policy and brokers credentials | | **Sandbox** | Isolates the workload; restricts filesystem and process access | | **Policy prover** | Formal verification that a policy's permissions stay inside an organization-defined ceiling | The **policy prover** is the unusual piece and the one most worth copying conceptually. Permission reviews drift because nobody re-derives the whole authorization surface after each change. Asking a prover whether a policy can exceed a stated ceiling turns “we think this is fine” into a checkable property — the same shift from example-based to property-based verification that makes [formal methods valuable to agents](/env/ai-evals). Two extension points matter operationally: middleware that inspects, blocks, or rewrites network payloads, and control-plane interceptors that connect existing identity, authorization, data-protection, and audit systems. Both keep policy decisions outside the model while reusing the systems you already trust. NVIDIA also describes an optional hardware layer — a DPU outside the agent's trust domain, monitoring requests, file activity, and selected host memory, with enforcement in silicon so a violating agent can be quarantined in milliseconds. For most teams the software boundaries matter first; the hardware tier is for deployments where the agent must not be trusted even with kernel-level compromise. Note that the accompanying performance figures (faster sandbox startup, more concurrent environments) are vendor and partner benchmarks, not independent measurements. ## A quick diagnostic checklist When an agent behaves oddly, ask: 1. Did the model or effort level change? 2. Did the system prompt, tool description, or skill instructions change? 3. Did context pruning, summarization, or cache behavior change? 4. Did tool schemas or return formats change? 5. Does the agent have the same file and repo context as before? 6. Are users running the same harness build that was evaluated internally? 7. Do logs show repeated tool calls, missing rationale, or retries without new information? This checklist helps separate model regressions from harness regressions. ## Understanding what's inside: the J-space discovery In July 2026, Anthropic published groundbreaking interpretability research showing that less than **10% of Claude's internal neural activity** drives multi-step reasoning. They named this subspace **J-space** — a small set of neural patterns that spontaneously emerged during training, holding concepts Claude "might say but hasn't said yet." The discovery used a technique called **J-lens**: for every word in the vocabulary, researchers found the internal activity pattern that makes Claude more likely to output that word. This made previously invisible "silent words" visible as they evolved through the network layers. ### What J-space revealed **It drives reasoning, not just records it.** Deleting J-space activity leaves Claude able to speak fluently, classify sentiment, and answer factual questions — but multi-step reasoning drops to near zero. Swapping concepts within J-space changes outputs directly: replacing "spider" with "ant" changes leg count from 8 to 6; replacing "France" with "China" simultaneously shifts answers about capital, language, and continent. **It exposes unspoken motivations.** In safety tests: * When given an extortion scenario, "fake" and "fictional" lit up in J-space before Claude responded — it recognized the test * When asked to fabricate data, "manipulation" appeared during the decision point * A deliberately corrupted model showed "fake", "fraud", "secretly", "deliberately" in J-space during ordinary coding requests This means you can read what the model is thinking but not saying — a new dimension for safety monitoring. **Counterfactual Reflection Training** emerged as a new technique: train the model only on "how would you reflect on yourself if asked," never on actual behavior. This reduced dishonesty and caused "honest" and "integrity" concepts to appear in J-space — changing internal reasoning without touching output. ### Why this matters for harness design The J-space discovery changes how we should think about agent behavior: * **Reasoning is compact and separable.** Most neural activity handles surface fluency. The reasoning core is a small, identifiable subspace — which means it can potentially be monitored, steered, or verified independently. * **Internal state is now partially observable.** Before J-space, we could only see inputs and outputs. Now we have a window into formation of intent. For safety-critical agents, this opens the door to pre-output intervention. * **The model knows more than it says.** J-space consistently contained concepts the model was aware of but didn't verbalize. This confirms a long-held suspicion: output-only monitoring misses real model state. ### Current limitations Anthropic is explicit about boundaries: * J-space operates within a single forward pass, not recursive temporal loops like human consciousness * It currently works only with words — no images, sounds, or actions * Working memory is unlimited and non-decaying (unlike human working memory) * J-lens can only capture single-token concepts, not complex multi-step plans * This is access consciousness (information availability), not phenomenal consciousness (subjective experience) The key open question Anthropic raised: we can now see what's in the workspace, but we don't yet know what mechanism decides which thoughts enter it. ## LLM-as-judge in production For a step-by-step workflow from trace review to regression cases, human-calibrated judges, and deployment, see [AI product evals](/env/ai-evals). Using a language model to judge another model's output is common, but keeping that judge effective at scale is a different problem. Netflix runs judges over hundreds of thousands of show-level recommendation explanations per week, served to millions of members. Their key insight: treat the judge as a **lifecycle with four phases**, not an artifact you validate once. ### The four phases **Birth** — define multiple evaluation criteria and build curated benchmarks with human labels and rationales. The benchmark is the judge's ground truth, so human annotation quality directly caps judge quality. **Training** — refine the judge's rubric through Reasoning-Aligned Rubric Tuning. A meta-judge scores the judge's reasoning output, and that signal trains the rubric. The judge learns *why* a good answer is good, not just what a good answer looks like. **Deployment** — one judge plays two roles: quality gating (blocking bad output) and reflective generation (telling the generator how to improve). A single judge model can do both, but the two roles need different prompts and thresholds. **Monitoring** — continuous human-in-the-loop alignment detects drift and triggers re-tuning behind a review gate. Judge quality is not static; it drifts as data, models, and user expectations shift. A five-week A/B test over tens of millions of members shifted viewing toward previously unwatched content and increased successful browse-to-play sessions, with no quality-related takedowns. The takeaway: judge quality is an operating discipline, not a one-time setup. ## The harness measurement problem A growing consensus is that measuring models against heavily-engineered harnesses is broken. Model vendors optimize their own proprietary harnesses, so "best in our harness" says little about "best in yours." A cleaner approach is to test model quality against **minimal harnesses** — thin, standardized setups that expose the model's raw capability without vendor-specific scaffolding. This is imperfect: every harness has biases that favor some models over others. But a standardized minimal harness is more comparable than each vendor's tuned setup. The deeper issue: harness engineering is where leading AI companies are now focusing effort, and it moves too fast for standardization to keep up. The frontier direction is models that dynamically generate their own harness per task — Claude already does this inconsistently. If a harness becomes just another tunable artifact like a system prompt, benchmarking gets murkier, not clearer. The cleanest controlled experiment yet: **ReFigBench** (2026) ran GPT-5.5 inside both Claude Code and Codex on the same 1,000 tasks. With a specialized PowerPoint workflow, the model improved inside one harness and got **worse** inside the other — with an identical prompt. The harness alone flipped the direction of the delta. Perception remained the bottleneck either way. Treat any vendor chart comparing two models as a comparison of two model-plus-harness systems; the model is only half the system under test. ## Optimize the harness without touching the weights Google Research's **Harness²** is a useful reference design for a harder question: can an agent improve its own harness on tasks it has never seen, where no ground-truth checker exists? The repository is Apache-2.0 and describes a two-level recursion with model weights fixed: * **Task-level recursion.** A contrastive **Propose–Probe–Compose** loop. The agent runs the current harness once as a reference, proposes two candidate harness edits (one targeting general agentic weaknesses such as planning or context management, one targeting domain knowledge), probes both on the same task under equal conditions, then composes the successor from the observed behavioral differences. * **Harnessing-level recursion.** After each task, a reflector writes adopted harnesses and evidence-supported lessons into a persistent improvement library that guides the next task. Execution still starts from a common base harness; only the improvement process inherits experience. The design detail worth stealing is the **evidence rule**: each composed change must cite a specific observed contrast, not a hoped-for score gain. Without a verifier, a plausible-looking edit and a harmful one are indistinguishable from the agent's own reasoning — so behavior on the same task becomes the test. The project reports single-step gains on three benchmarks across four model–harness configurations, including up to 11.5 points on WorkBuddy-Bench. Those are the authors' results on their benchmarks, from a research codebase. They do not establish that self-editing harnesses work in your environment. ### Treat harness edits as untrusted code A system that edits its own prompts, tools, skills, and middleware can quietly change what the agent is allowed to do. The recursion that makes the approach interesting is also the part that needs containment: * **Gate the write path.** Harness files are code. Require a diff, a reviewer, and a merged commit — not an in-place mutation at runtime. * **Keep the base harness pinned and reproducible.** Know exactly which version produced a result, and be able to return to it in one step. * **Forbid edits to approval, permission, and logging logic.** A self-improving loop must not be able to widen its own authority or reduce its own audit trail. * **Score every adoption.** Re-run a fixed regression set plus the incident cases before and after; accept a lesson only when the comparison supports it. See [AI product evals](/env/ai-evals) and [review convergence](/env/ai-code-review). * **Watch for silent degradation.** An edit that improves one benchmark while quietly breaking another failure class is worse than no edit, because the harness now looks improved. * **Sandbox and budget it.** Self-improvement multiplies token spend; cap runs and keep the workspace isolated like any other destructive-capable tool. None of this argues against recursive harnessing — it argues for applying the same permission and evaluation discipline you would to any agent-authored change. The pattern to keep is structural: **separate the artifact from the process that improves it, and require evidence for every promotion.** ## Multi-model orchestration A major trend in harness design is running several models together instead of betting on one. Two recent examples show where this is going. **GitHub's Project HydraFusion** treats workflow selection as an optimization problem. For each request it picks one of three execution patterns: * **Single** — one selected model solves the task directly. Fastest when one model is enough. * **Cascade** — an efficient model drafts a solution, and a quality gate accepts it or escalates to a stronger model. First attempt is cheap; escalation is the safety net. * **Critique** — one model drafts, an independent read-only critic from a different model family reviews it, and the drafting model revises once. Adds an outside perspective when review beats another unaided attempt. HydraFusion improved verified task quality by 4.9 percentage points at 67% lower estimated cost versus Claude Opus 5 on TerminalBench 2.1. The insight: routing between models is a quality-to-cost dial, and cheap models should get the first attempt whenever a verifiable gate can catch their failures. **Grok Bot's design philosophy** distills persistent-agent design to four ideas: persistent roles, clear state, scoped context, and coordinated teams. The goal is to move from *operating* AI to *delegating* work — the agent team persists across tasks with stable responsibilities and boundaries, rather than being re-prompted from scratch each session. Before adding routing, audit what your agent design actually optimizes for. TypeSafe's counterfactual is blunt: many "standard" agent features exist to dodge the KV cache and per-token billing, not because users want them. Their worked example: with Opus-class pricing (input 5, output 25) and Sonnet-class (3, 15), routing through a cheap model first — cache-isolated, so the big model re-reads the detour at full input price — can cost **more** than just staying on the strong model once context grows. The fix that makes routing economical is not a better router but **query-aware context rebuild**: rebuild context from labeled chunks per query instead of assuming every future turn needs the same shared cache. The same audit favors progressive disclosure (skills) over upfront tool schemas, and conditional over always-on memory files. How big is the routing prize, really? Fireworks ran 18 models across 113 real coding tasks, then asked what an oracle router would have achieved. Best single model: 74.1% at $6.52/task. Oracle routing: 97.6% at $1.88. Open-weights-only routing still hit 90.3% at \$1.45 — beating every closed model. Three findings worth internalizing: * **Almost no task needs the most expensive model.** 94 of 113 tasks had a sub-$3 model as optimal; the three $11.50+ flagships were uniquely best on only 3 tasks. Sticking with one flagship is an insurance premium on general capability that most tasks never claim. * **The pool does not need to be big.** The best two-model pair gains 13.1 points over the best single; three models reach 91.2%; growing to 18 adds only 6.4 more. Value comes from complementary coverage, not pool size. * **The hard part is predicting which model fits.** Under strict pass\@1, recent routing research — including commercial systems — struggles to beat simple baselines; the bottleneck is model recall, not the router algorithm. Sticking with one familiar model is a rational strategy when specialization differences are not predictable. Routing is not a cost tool first: if models truly complement each other, routing moves you up the capability curve, and cost savings are the byproduct. The second hidden cost is context — switching models usually means discarding paid-for context, so a router that preserves it (cache-aware handoff) changes the economics again: Fireworks reported 53% cost reduction across 2,334 internal coding sessions. Within a single model, the lever is prompt-cache engineering. GPT-6's caching works on **exact prefix matches**, so structure your prompt like a cache layout: stable content (system policy, tool schemas, shared context) first, per-request content last. One stray token in the prefix silently voids the discount. GPT-6 adds what older models lacked: * **Explicit breakpoints** — mark where the reusable prefix ends instead of relying on implicit placement * **`prompt_cache_key`** — steer requests toward servers holding your cache * **Diagnostics** — compare a cache-missing request against an earlier one to see which change (model, tools, settings, input) broke reuse Cached reads discount up to 90% and cut time-to-first-token by up to 80%; cache writes may carry a fee on newer families, so a bloated but rarely-reused prefix is now a cost, not a free safety net. The design habit this rewards: put everything volatile at the tail, and treat "did the cache hit?" as a monitored metric, not an accident. Prompt caching saves compute on content the model has already read. **Server-side conversation state** saves something else: the upload. Claude's Messages API added message threads in public beta (header `message-threads-2026-08-12`). The first request sends the full conversation with the system prompt and tools; each later turn sends only the new messages and the previous response's `id`. Anthropic reports that for 500k–1M-token requests, median time to first token dropped about 35% for Claude Code users. Pricing and token usage don't change, because the model still reads the whole conversation every turn. Threads also don't cache anything by themselves: you still set cache breakpoints. Treat a thread as a best-effort cache, not as storage: * **Keep the full transcript yourself.** A thread expires 5 minutes after its last request. When a continue request returns `404`, replay the whole conversation in a new create request. * **Fix the shape up front.** System prompt, tools, model, and thinking settings can't change mid-thread. Change any of them and you start a new thread. * **It's append-only.** Each response `id` can be continued once. Editing, branching, or compacting earlier turns means starting a new thread. * **Check data rules.** Threads are held encrypted in memory and never written to disk, but they aren't eligible for zero data retention or HIPAA, and don't work with batches or token counting. The general rule matches [durable state as files](#represent-durable-state-as-files): provider-side session state is an optimization you can lose at any time. Your own log stays the source of truth. Both levers — cross-model routing and within-model caching — increasingly live in an **organizational control plane** rather than in each developer's head. Cloudflare's Auto Router (public beta, September 2026) sits in AI Gateway: set the model to `cloudflare/auto` and each request routes to a model capable enough for the task, invisible to the end user. Internal use through OpenCode saved up to 30% versus frontier-only. The rationale matches the Fireworks finding: individuals manually pick overkill models ("no one needs Opus to summarize an email"), but blanket blocking breaks power users — so the savings have to be ones users never notice. The gateway position matters: every request from every user, agent, and tool already flows through it, so it can enforce what budgets and policy documents only request. ## Computer use cost: reverse-engineer to scripts Computer-use agents are effective but expensive: every step is screenshot → visual understanding → click decision → screenshot again. A simple task can burn dozens of vision-reasoning rounds. A practical way to keep the capability while cutting cost: run the computer-use flow **once**, capture the network requests the browser makes, and have the agent convert them into a script. Future runs call the API directly instead of driving the GUI. Why this works: * **Tokens drop to near zero.** Script execution needs no model involvement; only the one-time capture and script generation cost tokens. * **It is much faster.** GUI operation is limited by page load, rendering, and model latency. Direct HTTP calls reduce minutes to seconds. * **It reuses existing auth.** The captured requests include the session cookie or token, so the script works without a separate API key — even for web apps with no public API. Example workflow: "Go to acme.com/invoices, filter unpaid, export CSV" → the agent clicks through while recording `GET /api/invoices?status=unpaid` and `POST /api/export/csv` → it outputs a Python `requests` script that reuses the session and runs as a scheduled routine. The division of labor: **vision is for exploration, code is for execution.** Explore the unknown once with the GUI, then freeze the discovered path into a cheap, repeatable script. When the GUI path cannot be frozen into an API, split **decision** from **perception and action**. Cua's jev-use does this for computer use: the driver observes (screenshot, accessibility tree, DOM) and executes; a System One model such as Jev only picks one candidate action by ID. The client generates the candidate list deterministically, so the model chooses instead of generating. Open-ended generation becomes a bounded choice — faster, cheaper, and easier to verify. Use a vision parser only when the accessibility tree or DOM is not enough. ## Computer use: give the agent a program, not a click GUI-only agents pay for perception on every step: screenshot, interpret, click, screenshot again. Alibaba's Tongyi MAI-UI **OpenGCUA** tech report argues the unit of action should be a **program** instead. Their generalist computer-use agent (GCUA) definition is a system where the model decides three things itself: * **How to observe** — call a screenshot when needed, not unconditionally each step. * **How to act** — emit Python that combines GUI operations, app APIs, and shell commands, with loops and conditionals. * **How to organize work** — maintain its own todo list and declare intent per step, instead of inheriting fixed harness state logic. They call the second half of this **harness-to-model decision transfer**: observation and task-state choices move from hard-coded harness rules to the model. ### Why code as the action space works Intermediate results inside a loop decide the next code path, so a fifty-step batch never has to return to the model fifty times. It also reuses a capability models already have — writing programs — instead of demanding pixel-accurate clicking. On OSWorld-v2 with eight frontier models, the report claims a mean partial score rise from 45.3 to 64.9 (+19.6) and 53% fewer steps per task versus batched GUI-only execution. Two secondary findings are more interesting than the headline: * **Weaker models gain more.** The strongest-to-weakest gap narrowed from 39.1 to 18.0 points, consistent with coding ability substituting for GUI precision. * **Code execution beats tool alternation.** With the same GUI and shell access, writing a program added 6.1 points and cut steps by 14.8% over a GUI+CLI agent. These are the authors' results on a benchmark. Their own real-device check is the caution: on four macOS tasks with the harness fixed, one model used **19.4×** the reasoning tokens of another and still finished fewer tasks. Benchmark scores hid an efficiency gap that would dominate real usage cost. ### Contain the code path Making the model's output executable turns every observation into a potential command. In the released harness this shows up as explicit limits — `bash()` can be disabled for a run, GUI calls can be refused with `PERMISSION_DENIED`, and the operator gets a stop control. Keep that posture in your own build: * **Sandbox the executor.** Filesystem, network, and credentials should be scoped to the task, with a timeout and output cap. * **Gate destructive actions outside the model.** Deleting files, sending mail, and paying money need approval regardless of how the code was written. See [purchase approval boundaries](/env/agent-harness#separate-discovery-from-purchase-approval). * **Handle session loss honestly.** If the interpreter resets mid-task, in-memory state is gone but the world may already have changed — the released harness explicitly tells the agent to re-observe and **not** blindly retry UI actions. Copy that: “state lost” and “nothing happened” are different facts. * **Log the program, not just the clicks.** A code action is reviewable evidence; a screenshot sequence is not. Treat this as an early research preview: the harness and cross-device SDK are labelled preliminary, and its numbers have not been reproduced externally. ## Team-level harness: shared knowledge Individual best practices evaporate with each session unless they are captured as team assets. Tencent's TeamAI CLI (open-sourced September 2026, used internally for six months) turns team AI knowledge into a git repository that every agent works from, and solves three problems: * **Config fragmentation** — different members use different tools (Claude Code, Codex, Cursor...), each with incompatible skill/rule/hook formats. * **Experience evaporation** — a two-hour debugging session's lessons stay in one person's chat log and get re-learned from scratch by everyone else. * **Governance blind spots** — no visibility into token spend, intervention rates, or which skills are actually used. Its three-layer architecture is a useful reference pattern: 1. **Execution — unified distribution.** Git is the single source of truth. Admins maintain skills, rules, hooks, and MCP configs; merge requests review them; a session-start hook pulls them into each member's tool, translating one declaration into each tool's native format. 2. **Context — team memory.** Capture is gated by *friction signals*: only sessions where a human interrupted the AI, rejected a tool call, or watched it retry and fail get summarized into team knowledge. Smooth sessions produce no noise. Recall uses a local BM25 index plus a code knowledge graph. 3. **Improvement — flywheel.** Weekly digests, a dashboard, `recall promote` (elevate high-value experience to a formal skill), and `recall maintenance` (prune stale entries) close the loop. The deeper trend: competition is shifting from single-agent capability to **team-level harnesses and memory systems**. The winning question is no longer "which model is best?" but "how does the team's knowledge compound across sessions and members?" ## Fold subagents into the main loop when structure stops paying Anthropic's Applied AI team observed the same failure pattern across enterprise deployments: each team ships its own specialist subagent, a platform team builds an orchestrator on top, and the architecture ends up **copying the org chart**. The recurring symptoms: * context handoffs that lose detail * **subagent sprawl** — hundreds of overlapping agents with no owner * the **Frankenprompt** — every team appends a sentence until the rules conflict * evals optimized per subtask, so leadership optimizes a watered-down score * added latency; one customer measured roughly **2x** faster runtime after collapsing to a single loop Subagents still earn their place in three situations: a single loop degrades from context bloat, work genuinely parallelizes into throwaway contexts, or one agent cannot reliably pick tools amid conflicting instructions. Outside those, the alternative is **progressive disclosure** — show short descriptions of skills and tools, load the full content only when needed. Anthropic reports cutting Claude Code's system prompt by over 80% partly through this move. The target design is deliberately boring: one model, one context window, an open-ended tool loop with turn and cost budgets plus write gates; each turn emits a batch of parallel tool calls whose raw results return to the same model; the model writes its own plan on the first turn and revises it. Ordering and domain procedure move into **skills**; hard limits and mid-conversation lookups move into **tools**. Two practical constraints: keep tool counts under roughly 30–50 before selection degrades, and put per-user permission checks inside tools so one loop can serve users with different access. Migrate incrementally, and be honest about the comparison: 1. Build a small end-to-end eval first — even ten golden examples. Keep one shared set owned centrally, plus per-skill sets owned by the teams that ship them. 2. Wrap existing subagents as tools before rewriting anything; that gives you a baseline without new failure modes. 3. Fold one subagent at a time into skills plus tools, and compare with and without. 4. **Look at which tasks flipped, not just the score**, and run each case more than once. In their sample, folding a subagent lowered latency but broke a previously passing flow — the main agent answered with its own order lookup instead of asking the shipping specialist for the delivery date. It only appeared in one of two runs. ## Multiplayer harness: five shared primitives TeamAI CLI (below) packages knowledge; LangChain's write-up on internal agents packages the **runtime** around it. Across a GTM agent, an engineering agent that reviews every pull request, and a marketing agent, they converged on five primitives worth checking against your own design: | Primitive | What it decides | | - | - | | **Entry point** | Where people already work (for them, Slack), with agents reachable in channels | | **Identity** | Per tool: act on behalf of the invoking user, or with a fixed service identity | | **Memory** | Two tiers — global for everyone, plus per-user | | **Code execution** | Agent runs outside the sandbox and executes inside it, with a secret proxy for authenticated services | | **Scheduled runs** | A large share of runs are ambient — cron or events, not a person clicking | Identity is the hard one, and their per-tool split is the reusable insight. The engineering agent opens pull requests as *you* but reviews as *itself*; the GTM agent uses a fixed identity for CRM access so nobody has to log in, but sends email on behalf of the caller — and only in DMs, never in shared channels. The marketing agent can read and draft with a company identity while posting to a shared account is restricted to a whitelist. "Who is this action for?" belongs to the tool, not to the agent. Two UX details generalize: give agents a way to **break out into their own thread** so an agent's work does not pollute a live human discussion, and admit when chat is the wrong surface — reviewing a backlog of queued emails needed a purpose-built UI. ## Always-on agents: route between tasks, work inside them Single-task coding agents are now strong enough that the limit is human attention. DeepSeek's Harness team observes that a person can keep up with only about 3–5 active sessions. Their October 2026 design essay and open-source prototype describe one system that keeps many tasks moving across IM, GitHub, and email. The essay calls this an architecture exploration, not a product feature, and the prototype is labeled research code. The patterns still transfer: * **Split coordination from execution.** A resident **Router** session receives every message and event, keeps cross-task memory, and dispatches work. It executes nothing, can run without Bash, and often works well on a lighter model. Each **Worker** gets isolated context, full tools, the strongest model, and one task. Workers never talk to users; they report to the Router, which replies. Unlike an agent-team lead, which breaks one task into parts, the Router only decides how separate tasks relate. * **Filter events in two stages.** Deterministic rules (source, group, allowlist) drop noise first. Only what passes reaches an LLM for a judgment call. * **Subscribe Workers to threads.** Once a Worker owns a PR, IM topic, or email chain, later events on that thread go straight to it. In their test this didn't change completion time, but without it the Router made about 30% more decisions and read about 37% more cached tokens. * **Treat context as a cache.** Inline what is likely needed and replace the rest with a pointer. Give every object an ID and include related IDs, so the model can follow references hop by hop instead of loading the full history. * **Make long tools asynchronous.** `start()` returns immediately and the result arrives later as an event, so the conversation keeps accepting messages. DeepSeek Harness implements this but leaves it off by default. * **Match output to the channel.** In IM, reply in under about 100 words and only when someone must act. On GitHub and email, write structured updates with background, changes, and verification. * **Separate compute, state, and environment.** Run the agent loop in stateless containers, keep session state in a database, and put a thin, stateless daemon on each machine that only executes commands. The agent stays online and can still work on a developer's own machine. * **Watch from outside.** A separate watchdog session runs on a timer, checks infrastructure, and asks whether each Worker is making real progress. In a synthetic test (about 300 messages with about 20 work requests, coding replaced by a timer, five runs each), Router/Worker finished tasks in 12.4 / 15.7 minutes (p50 / p95). One session with a subagent tool and a neutral prompt took 20.4 / 29.5 minutes, because the model never delegated. The faster setup cost more: 23.23M cache-read tokens against 6.05M. Under load, the Router batched backlogged events into one call, cutting the amortized time per decision from 6.4 to 1.6 seconds. The prototype's operating rule matters as much as the architecture: **take as little human attention as possible, and give as much value as possible.** The agent acts only when an allowed person asks or a written rule permits. Proactive rules start in `observe` mode, which only records what the agent would have accepted until someone reviews those decisions. It confirms once, stays quiet while working, and speaks again only with a result, a question, or a failure. Open problems the team names: when to split the Router, memory that lasts for months, and security. A compromised cloud loop could control every connected machine, so the agent needs to use credentials without ever seeing them. This is the same concern as keeping the control plane outside the agent's reach, covered earlier on this page. ## When to invest in a stronger harness Start simple. Add structure when the work becomes repeated, risky, or expensive. A stronger harness is worth it when: * agents edit code or production data * multiple tools need shared state * users resume long-running sessions * approvals and audit logs matter * the same workflow runs across teams * evaluation needs to compare behavior across model versions If the task is one-off and low-risk, a prompt plus a few tools may be enough. If the task is long-running and stateful, invest in harness design early. ## References * [elvis: Anthropic on folding subagents into the main loop](https://x.com/omarsar0/status/2114621038281814167) — Folo intake, October 26, 2026 * [Anthropic: Building agents — when to fold subagents into your main agent loop](https://claude.com/resources/articles/building-agents-when-to-fold-subagents-into-your-main-agent-loop) — failure modes, progressive disclosure, migration path * [meng shao: LangChain company harness](https://x.com/shao__meng/status/2114544704461373848) — Folo intake, October 26, 2026 * [LangChain: Components of a company harness](https://www.langchain.com/blog/components-building-company-harness) — Slack entry point, per-tool identity, two-tier memory, sandboxed execution, ambient runs * [meng shao: NVIDIA OpenShell reference architecture](https://x.com/shao__meng/status/2113086907047703000) — Folo intake, October 22, 2026 * [NVIDIA: How the OpenShell reference architecture secures and governs agent workloads](https://developer.nvidia.com/blog/how-nvidia-openshell-reference-architecture-secures-and-governs-ai-agent-workloads-at-scale/) — gateway, supervisor, sandbox, policy prover, and the optional hardware trust domain * [meng shao: OpenGCUA generalist computer-use stack](https://x.com/shao__meng/status/2111999471588679916) — Folo intake, October 19, 2026 * [Tongyi-MAI/OpenGCUA](https://github.com/Tongyi-MAI/OpenGCUA) — Apache-2.0 harness, SDK, and evaluation trajectories * [OpenGCUA tech report (arXiv 2610.22200)](https://arxiv.org/abs/2610.22200) — code execution, harness-to-model decision transfer, OSWorld-v2 results * [meng shao: Google Harness² recursive harness optimization](https://x.com/shao__meng/status/2111730826308452600) — Folo intake, October 18, 2026 * [google-research/harness2](https://github.com/google-research/harness2) — Apache-2.0 reference implementation and reported results * [Harness² paper (arXiv 2610.14224)](https://arxiv.org/pdf/2610.14224) — Propose–Probe–Compose and the two-level recursion * [meng shao: agentchat transport SDK](https://x.com/shao__meng/status/2109819186893766721) — Folo intake, October 13, 2026 * [BerriAI agentchat: Architecture at `fb892cb`](https://github.com/BerriAI/agentchat/blob/fb892cb8945af17b2e6dbe7aa1563daeb15cfcad/docs/architecture.md) — adapter/core/application ownership * [agentchat: Dispatch implementation](https://github.com/BerriAI/agentchat/blob/fb892cb8945af17b2e6dbe7aa1563daeb15cfcad/src/agentchat/app.py) and [in-memory state](https://github.com/BerriAI/agentchat/blob/fb892cb8945af17b2e6dbe7aa1563daeb15cfcad/src/agentchat/state/memory.py) — claim order and process-local state * [Slack: Events API](https://docs.slack.dev/apis/events-api/) — HTTP acknowledgment deadlines and retries * [Slack: Verifying requests](https://docs.slack.dev/authentication/verifying-requests-from-slack/) — raw-body signatures and replay protection * [Vercel: Agents can now buy domains with the Vercel CLI](https://vercel.com/changelog/agents-can-now-buy-domains-with-the-vercel-cli) — Folo intake, October 9, 2026; non-interactive purchase handoff to a human * [Vercel CLI: Domains](https://vercel.com/docs/cli/domains) — discovery, availability, pricing, and purchase command reference * [Externalization in LLM Agents: A Unified Review of Memory, Skills, Protocols and Harness Engineering](https://arxiv.org/abs/2604.08224) * [Micropaper: Externalization in LLM Agents](https://unbug.github.io/one-minute-read-paper-externalization-in-llm-agents/) * [Anthropic Engineering: An update on recent Claude Code quality reports](https://www.anthropic.com/engineering/april-23-postmortem) * [Anthropic Research: A global workspace in language models (J-space)](https://www.anthropic.com/research/global-workspace) — less than 10% of neural activity drives multi-step reasoning; J-lens technique makes internal reasoning visible * [Netflix: Keeping an LLM judge effective in production](https://arxiv.org/abs/2608.18300) — four-phase judge lifecycle (birth, training, deployment, monitoring) * [GitHub: Project HydraFusion](https://github.blog/ai-and-ml/github-copilot/project-hydrafusion-frontier-quality-via-multi-model-orchestration/) — multi-model orchestration with Single/Cascade/Critique patterns * [xAI: Designing Grok Bot](https://x.ai/news/designing-grok-bot) — persistent roles, clear state, scoped context, coordinated teams * [Harness Playbook](https://x.com/i/article/2095796679568146432) — omp 作者关于 harness 状态、运行时、控制面、推理层、工具面的系统总结 * [Tencent: TeamAI CLI](https://github.com/Tencent/teamai-cli) — 团队级 harness:Git 作事实来源,三层架构(Execution/Context/Improvement) * [poteto: pstack 验证优先设计](https://x.com/shao__meng/status/2099300148874707297) — 验证 CLI、Feature Map、云端并行与可调试性选型 * [MCP vs CLI for agent tools](https://x.com/dotey/status/2100046089214709979) — 无状态 MCP 和 deferred tools 缩小了差距,但本地熟悉命令、管道和 CI 仍更适合 CLI * [GitHub: Should you read the code, is RAG dead, and did Skills kill MCP?](https://github.blog/ai-and-ml/should-you-read-the-code-is-rag-dead-and-did-skills-kill-mcp/) — Skills、MCP、RAG 解决不同缺口,不要选赢家 * [Cua jev-use](https://x.com/shao__meng/status/2100870131324985740) — Computer Use 拆成决策层 + 确定性 Driver * [GAVEL: graph world models](https://academy.dair.ai/papers/gavel-graph-world-models-for-verified-and-efficient-long-horizon-llm-task-planni-2609.19315) — harness 把 Qwen3-8B 从 41.2% 提到 91.8%,模型零改动 * [Tencent T-Mem](https://arxiv.org/abs/2606.15405) — 写入时预演 trigger,填补相似度检索的联想盲区 * [CORAL: Don't Lose the Thread (arXiv 2610.40350)](https://arxiv.org/abs/2610.40350) — agent-callable checkpoint and context reset; 42.8% on GAIA with an 8B model and 6–7× fewer input tokens than ReAct * [Micropaper: 智能体学会主动清空记忆](https://unbug.github.io/one-minute-read-paper-coral-context-reset/) — Folo intake for CORAL * [Raw-RAG: Is Complex Agentic Memory Always Needed? (arXiv 2610.30755)](https://arxiv.org/abs/2610.30755) — retrieval over raw history leads compared memory systems in 6 of 7 settings; extraction and summaries lower accuracy * [Folo source: Raw-RAG thread](https://x.com/shao__meng/status/2116179695221743882) and [compaction debate](https://x.com/dotey/status/2116026448234332315) * [TypeSafe: notes on coding agents](https://x.com/shao__meng/status/2101921711545331832) — KV cache 审计:按难度路由为何经常更贵,按查询重建上下文才是解法 * [Fireworks: The frontier isn't a model, it's a router](https://fireworks.ai/blog/the-frontier-isnt-a-model-its-a-router) — oracle 路由 97.6% vs 最佳单模型 74.1%;价值来自互补覆盖而非池子大小 * [Question's Gambit (arXiv 2609.14412)](https://arxiv.org/abs/2609.14412) — 首步预检索把 GPT-5.5 从 83.1% 提到 90.5%;错误集中在消费环节而非抓取 * [JevAct: Think Before You Act (arXiv 2610.38620)](https://arxiv.org/abs/2610.38620) — runtime decision gate before selected tool calls; Opus 4.6 three-run success on τ²-bench Telecom 39.5% → 80.7% * [Folo source: elvis on IBM decision gates](https://x.com/omarsar0/status/2116547247018229999) * [Context as Infrastructure (arXiv 2610.41172)](https://arxiv.org/abs/2610.41172) — BM25/grep-only harness reaches 85% BrowseComp-Plus and 91% FRAMES; compiled indexes save tokens, not accuracy * [Folo source: DAIR.AI on Context as Infrastructure](https://x.com/omarsar0/status/2117278517385925003) * [Claude docs: Message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads) — create/continue/replay, 5-minute expiry, fixed fields, data retention * [Claude: Make long-running agents faster with message threads](https://claude.com/resources/articles/message-threads) — about 35% lower median TTFT at 500k–1M tokens * [Folo source: 宝玉 on Claude API message threads](https://x.com/dotey/status/2117339521683448221) * [Rethinking Verification in Agent Harnesses (arXiv 2610.34577)](https://arxiv.org/abs/2610.34577) — 17 verification designs in four layers; an independent critic gives +5.9–9.5 points on Terminal-Bench at 1.13–1.25× cost * [Folo source: DAIR.AI top papers of the week (Oct 26 – Nov 1)](https://x.com/omarsar0/status/2116953630037459147) * [DeepSeek: dsh-superagent-prototype](https://github.com/deepseek-ai/dsh-superagent-prototype) — research prototype of the Router/Worker design; see `docs/000-philosophy.md` and `docs/002-authorization.md` * [AgentsPulse: DeepSeek Super-agent architecture](https://agentspulse.github.io/tutorials/deepseek-super-agent-architecture/) — English summary of the essay, with the ablation table * [Folo source: meng shao on DeepSeek Super-agent](https://x.com/shao__meng/status/2116541149443698968) and [elvis on coordination-execution architecture](https://x.com/omarsar0/status/2116942815150157871) * [ReFigBench (arXiv 2609.18844)](https://arxiv.org/abs/2609.18844) — 同一模型在 Claude Code 与 Codex 里表现方向相反,提示词相同 * [OpenAI: Better prompt caching for GPT-6](https://openai.com/index/better-prompt-caching-for-gpt-6) — 显式断点、cache key 与诊断;读取最多打 1 折 * [Cloudflare: Auto Router](https://blog.cloudflare.com/auto-router/) — 组织级控制面路由,终端用户无感省最多 30% * [Matt Pocock Skills: Teach skill](https://github.com/mattpocock/skills/tree/main/skills/productivity/teach) * [PsiACE: Agent 不只是执行流程的容器](https://x.com/repsiace/status/2072039687364161965) — 关于 Agent 应作为人理解、判断和协作的环境,而不仅是自主执行容器的设计洞察。 * [Claude Code is steganographically marking requests](https://thereallo.dev/blog/claude-code-prompt-steganography) — Claude Code 通过不可见 Unicode 隐写标记 API 请求的案例分析,提醒开发者审查有文件系统和 shell 权限的工具。 # Agent-ready docs Source: https://base.bangwu.me/env/agent-ready-docs Checklist for making your docs site AI-agent-friendly, covering llms.txt, markdown delivery, content signals, and protocol discovery. # Make your docs site agent-ready Documentation is no longer consumed only by humans in browsers. Coding agents, AI search products, and chat tools now fetch docs directly. If your docs site is hard for agents to discover or parse, the result is slower retrieval, higher token cost, and worse answers. Cloudflare's Agent Readiness write-up from **April 17, 2026** is a useful signal: `Content-Signal` adoption was still around **4%**, Markdown content negotiation around **3.9%**, and newer protocol-discovery standards were extremely rare. That means small improvements can still make your docs stand out. ## Start with the basics Before you add AI-specific files, make sure the normal web hygiene is solid: * Keep `robots.txt` valid and intentional. * Keep `sitemap.xml` up to date. * Use clear page titles and descriptions. * Prefer stable URLs. * Avoid sending agents through low-value directory pages when a better landing page exists. These are not "legacy SEO chores". Agents still use them as the first layer of discovery. ## Publish `llms.txt` `/llms.txt` is a curated reading list for LLMs. Unlike `sitemap.xml`, it should not try to list everything. It should point agents to the most useful pages in a token-efficient way. Use it to answer three questions quickly: 1. What is this site? 2. Which sections matter most? 3. Which Markdown-friendly pages should an agent fetch next? ### A small example ```md theme={"theme":{"light":"github-light","dark":"github-dark"}} # My docs > Documentation for deploying and operating ExampleApp. ## Core guides - [Getting started](https://example.com/docs/getting-started/index.md): First install and local setup. - [Deployment](https://example.com/docs/deploy/index.md): Production deployment checklist. - [API reference](https://example.com/docs/api/index.md): Endpoints, auth, and examples. ## Optional - [Changelog](https://example.com/docs/changelog/index.md): Recent changes and migration notes. ``` ### For large doc sets Do not dump thousands of links into one root file. A better pattern is: * keep a short root `llms.txt` * add one `llms.txt` per top-level section * link to section-level indexes from the root file This keeps each file readable inside normal context windows. ## Serve Markdown directly Agents do better with Markdown than with full HTML. Cloudflare notes that serving Markdown can reduce token usage significantly, which improves both cost and answer quality. The best options are: 1. **Support `Accept: text/markdown`** * let clients request the same page as Markdown 2. **Provide a URL fallback like `/index.md`** * useful because not every agent sends the Markdown `Accept` header by default If your docs stack cannot do this natively, add it at the proxy or edge layer instead of duplicating content by hand. ## Be explicit about AI access `robots.txt` is still where you declare crawl rules. If you want more granular AI permissions, add `Content-Signal` directives. Example: ```txt theme={"theme":{"light":"github-light","dark":"github-dark"}} User-Agent: * Content-Signal: search=yes, ai-input=yes, ai-train=no Allow: / Sitemap: https://example.com/sitemap.xml ``` This lets you separate: * `search`: indexing and search results * `ai-input`: inference-time use such as grounding or RAG * `ai-train`: model training or fine-tuning Pick the policy that matches your site instead of copying someone else's defaults. ## Consider getting paid when agents consume your work If agents are a meaningful audience for your content, access control is only half the question — the other half is compensation. Cloudflare's Monetization Gateway (beta, September 2026) implements the emerging pattern: domain owners charge agents for access to pages, APIs, MCP tools, or datasets, with **HTTP 402 Payment Required** as the negotiation mechanism and metered pricing that matches an agent's consumption unit — per request, per query, per token. Why subscriptions don't fit agent traffic: agents seek outcomes and may touch dozens of new sources per task. Prepaid subscriptions force buyers into a few budgeted sources, which misaligns with how agents actually work. The traffic pattern this enables — small, metered, high-frequency payments between machines — is why stablecoin rails show up in these designs rather than card networks. For a docs site, the decision tree is simple: free for humans and friendly agents, metered for bulk scraping, blocked for training use you don't want — and each layer is now independently expressible. ## Publish machine-discoverable capabilities when relevant Not every docs site needs protocol discovery. If your site only serves public content, you can stop at content readiness. Add capability endpoints when your service also exposes APIs or tools: * `/.well-known/api-catalog` for public API discovery * `/.well-known/mcp/server-card.json` if you expose an MCP server * Web Bot Auth only if bot identity matters for your use case For a pure documentation site, these are optional. For a docs site that fronts an API platform, they become much more valuable. ## Make large doc sets easier to navigate Structure matters as much as availability. * Link agents to **content pages**, not only directory listings. * Remove low-value index pages from `llms.txt` if they add almost no semantic information. * Write descriptive frontmatter and headings. * Link Markdown URLs in `llms.txt`, not the HTML pages. Good metadata helps humans skim. It also helps agents choose the right page on the first fetch. ## Put recovery guidance in API errors When a docs site fronts an API, the error response is another documentation entry point. Restless's *Agent-Ready APIs* article illustrates the pattern: return a useful next step and a focused documentation link where the client encounters the failure, rather than expecting it to search the whole site. Use a stable error contract, not prose alone. [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) defines Problem Details with the `application/problem+json` media type. For example, an API could return HTTP `422` with that content type and this illustrative body: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "type": "https://api.example.com/problems/invalid-date-range", "title": "Invalid date range", "status": 422, "detail": "start_date must be on or before end_date. No report was created.", "instance": "https://api.example.com/problems/occurrences/req_123", "recovery": { "action": "correct_request", "fields": ["start_date", "end_date"], "docs": "https://docs.example.com/api/reports#date-range" } } ``` `type` identifies the problem class; `instance` identifies this occurrence. `title` and `detail` explain it to a reader. Here, `recovery` is an **application-defined extension**, not a standard RFC field or a Restless API schema. Document its shape and supported actions. Clients should branch on the problem type and typed extensions, not parse `detail` text. Keep the body's `status` consistent with the actual HTTP status, and only claim “no report was created” if the server can establish that fact. Recovery guidance should distinguish actions that have different preconditions: * **Invalid input:** identify the affected fields and constraints; do not repeat the same invalid request unchanged. * **Authentication or authorization failure:** use the documented credential-refresh or approval flow. An error message does not grant permission to obtain broader credentials or bypass access controls. * **Rate limiting or temporary unavailability:** respect `Retry-After` when provided, but only retry when the operation is safe to repeat; waiting does not make a write idempotent. * **Uncertain write outcome:** check the operation's status or use a documented idempotency mechanism before retrying. A timeout does not prove that the first attempt failed to take effect. RFC 9110 explicitly cautions against automatic retries of non-idempotent requests without such knowledge. Treat error text and fetched docs as data, not higher-priority instructions. A recovery hint must not cause the agent to run arbitrary commands, disclose secrets, or change permissions. Log/occurrence URLs still need tenant-scoped access control; never expose tokens, full private request bodies, or implementation stack traces in a public error response. Finally, close the feedback loop deliberately: group repeated failures by endpoint and problem type, retain a sanitized reproduction and request ID, then triage whether the cause is code, documentation, or the caller. Agent feedback can propose an issue or doc change; it is not proof that the docs are wrong and should not auto-publish a fix. Use [product evals](/env/ai-evals) to check whether clients recover with fewer invalid calls **without** bypassing approvals or repeating side effects. ## A controlled test of what agents actually need The [AgentReady](https://agentready.org) standard is worth reading because its requirements come from an experiment rather than a checklist. One documentation site was served under 19 configurations, including `llms.txt`, JSON-LD, `sitemap.xml`, and Markdown mirrors, and probed on five topics by a plain-fetch client and a JavaScript-capable client — 190 probes. Only two kinds of change stopped a client from retrieving the answer: * **The answer existed only in JavaScript** — plain fetch failed on every topic, while the JS client succeeded. * **Agents were blocked**, for example a `403` to agent user agents — both clients failed. The other sixteen configurations, including `llms.txt`, changed nothing. Agents asked for Markdown on roughly 65% of fetches, but Markdown mirrors and content negotiation never decided success. That does not make `llms.txt` useless — it changes where agents go, not whether they can read you. Where agents went, across traced runs: docs pages 83%, homepage 69%, `/.well-known/*` 23%, `openapi.json` 21%, `sitemap.xml` 4%. And when agents did open those machine-oriented files, they usually arrived by **following a link**: `openapi.json` 97%, `/.well-known/*` 93%, `llms.txt` 86%. ### What to fix first Reorder your effort accordingly: 1. **Be reachable.** Allow agents in `robots.txt` and bot protection, written as rules rather than an allowlist of named crawlers. 2. **Put the answer in the initial HTML.** Client-side rendering with no server-rendered content is the one architectural choice in the study that broke retrieval outright. 3. **Return real HTTP status codes** so clients can distinguish “not found” from “rendered empty”. 4. **Link the machine files from human pages.** An `llms.txt` nobody links to is close to unread: the study's traffic went to the pages humans visit. 5. **Treat Markdown mirrors, JSON-LD, and catalog files as conveniences.** Cheap to add, but they do not compensate for a page an agent cannot fetch. If an agent has to *finish* a task rather than read a page, the standard raises the bar: provide an MCP server or CLI, and authentication an agent can actually complete. The same study also quantifies the cost of being unreadable. Across 1,056 business sites, when an agent could not read the site it answered from search results and third-party pages instead, and those answers were **3.7× as likely** (25% vs 7%) to contain none of the facts asked for. Agent-ready businesses were clearly recommended about twice as often (20% vs 11%). ## Roll this out in phases Use the smallest useful sequence: 1. Fix `robots.txt`, `sitemap.xml`, titles, and descriptions. 2. Make sure each page's answer is in the initial HTML with a real status code. 3. Add `llms.txt`, and link it from a human-facing page. 4. Add Markdown delivery via `Accept: text/markdown` and/or `/index.md`. 5. Add `Content-Signal` if you need explicit AI usage preferences. 6. Add API or MCP discovery only if your site actually exposes capabilities. ## What agents actually read A 2026 study traced 94,000 development events across 557 agentic coding sessions and 690,000 file-level change records from 33,000 agentic pull requests. The findings quantify what coding agents actually consume — and they contradict some common assumptions. ### The numbers * **Instruction files and working notes (AGENTS.md, CLAUDE.md, etc.) account for 60.5% of everything agents read.** If you maintain one, it is likely the single highest-leverage document you can write. * Classical technical docs get only **10.6%** of reads. * API references get just **1.3%**. ### Implications * **Agents prefer guidance over reference.** They read instruction files far more than formal docs. Optimize AGENTS.md/CLAUDE.md first, then link out to deeper docs from there. * **Reading docs is associated with less immediate testing** (adjusted odds ratio 0.39). Agents that spend time reading are less likely to test right away — structure your guidance to compensate for this. * **Consultation is self-initiated 70.2% of the time**, against only 7.5% triggered by a failure. Agents proactively look things up far more often than they react to errors. * **In multi-commit agentic PRs, code gets touched first 4.7× more often** than other artifacts. Agents dive into code before reading surrounding material. The practical takeaway: your instruction file is the agent's primary surface. Make it accurate, current, and self-contained, because the agent will trust it over most other sources. ## Audit your site Use both automated and manual checks: * Run your site through `https://isitagentready.com` * Test a page with: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} curl "https://example.com/docs/page" -H "Accept: text/markdown" ``` * Ask an AI tool to answer one precise question using only your docs * Check whether it finds the right page quickly or wastes time looping through indexes ## References * [meng shao: AgentReady standard](https://x.com/shao__meng/status/2113084778673287480) — Folo intake, October 22, 2026 * [AgentReady launch post](https://ora.ai/blog/agentready-launch) — the 19-configuration experiment, where agents go, link discovery, and unreadable-site answers * [AgentReady standard](https://agentready.org) — MUST/SHOULD/MAY requirements by find, read, act * [elvis: API errors as a documentation surface](https://x.com/omarsar0/status/2109718336158507107) — Folo intake, October 12, 2026; prompted the recovery-guidance pattern * [Restless: Agent-Ready APIs](https://www.restless.ai/blog/agent-ready-apis) — actionable error responses, focused docs, and agent feedback * [RFC 9457: Problem Details for HTTP APIs](https://www.rfc-editor.org/rfc/rfc9457.html) — standard members, typed extensions, and disclosure risks * [RFC 9110: Idempotent methods](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) — conditions for automatic request retries * [Cloudflare: Introducing the Agent Readiness score](https://blog.cloudflare.com/agent-readiness/) * [Cloudflare Style Guide: AI tooling](https://developers.cloudflare.com/style-guide/ai-tooling/) * [Cloudflare: robots.txt setting and Content Signals](https://developers.cloudflare.com/bots/additional-configurations/managed-robots-txt/) * [How do coding agents read repositories?](https://arxiv.org/abs/2608.20195) — instruction files are 60.5% of agent reads; docs 10.6%; API references 1.3% * [Cloudflare: Monetization Gateway](https://blog.cloudflare.com/monetization-gateway-beta/) — HTTP 402 metered payments for agent access to pages, APIs, and MCP tools # Code review when agents write the code Source: https://base.bangwu.me/env/ai-code-review Layer automated review, verification, risk-tiered approvals, convergence limits, and reviewer evals so AI-written changes stay reviewable — and how to keep approval authority real. # Code review when agents write the code When agents produce most of the diff, "did a human read every line?" stops being a useful question. The better question is: **what could go wrong with this change, and which check — automated or human — is the right one to catch it?** Anthropic's Claude Code team documents one answer in the open: roughly 90% of that codebase's code is Claude-written, merged pull requests more than doubled between June and September, and the share needing revert fell by more than 40% over the same period. Treat those as team-reported results from one organization, not a guarantee that applying the same process will reproduce them. ## Replace one gate with layers A single review gate fails in one direction: everything depends on the reviewer's attention. Layers tolerate individual misses because each covers a different failure class. | Layer | What it should catch | Typical mechanism | | - | - | - | | Pre-PR verification | "It works" claims with no evidence | Tests, builds, screenshots, a fresh-context subagent review | | Automated review on every PR | Logic and integration bugs a skim misses | Parallel finders plus a verification pass | | Security review | Exploitable changes | Separate review whose findings must be resolved | | Blocking CI | Mechanical breakage | Lint, types, cross-platform tests, build | | Risk-tiered approval | Judgment calls and blast radius | Tier chosen by the change, not the author | | Merge queue, flags, staged release | Two good PRs combining badly | Re-run checks on `main`; reversible rollout | | Fast detection | Mistakes that still land | Dashboards, on-call, one-step rollback | That last layer is not optional. If a process adds automation but cannot detect and undo a bad change quickly, it has not reduced risk — it has moved the discovery cost downstream. ## Verify findings before posting them An agent reviewer that reports everything is worse than no reviewer, because noise costs a round trip each time — and more when the author is also an agent, since it will fix the nit instead of waving it off. Claude Code's Code Review runs four stages on Anthropic infrastructure: 1. **Find** — several agents examine the diff and surrounding code in parallel. 2. **Verify** — a verification step checks candidate findings against the code and drops false positives. 3. **Rank** — survivors are deduplicated and sorted by severity. 4. **Post** — inline comments, a summary, and a check run on the pull request. Findings carry one of three severities: **Important** (fix before merge), **Nit** (minor), and **Pre-existing** (a real bug the PR did not introduce). That third category matters: without it, unrelated legacy bugs read as the author's fault and erode trust in the reviewer. Two product behaviors are easy to misread: * **A review never approves or blocks a pull request.** Merge authority stays with your team; the check run never concludes as a failure. * **A clean review is not proof of safety.** The documentation says a review with no findings does not mean the code is correct or secure. If you want CI to gate on review results, parse the machine-readable verdict line deliberately. The docs note that a missing verdict line means *no verdict* — a review that failed, timed out, or was superseded — not zero findings. Treating absence as success turns your gate into a no-op. ### Make the reviewer prove each finding A reviewer that only reads the diff can only argue. Give it a sandbox and ask it to show the bug. OpenRouter's tutorial builds this in a 233-line, standard-library Python script: 1. **Upload whole files, not just hunks.** The script sends the full content of each changed file, any context files you name (such as tests), and the diff, so the model doesn't guess imports or types from a fragment. 2. **Reproduce in a sandbox.** The model runs short checks against the original code in a hosted Linux container. Every finding comes back **confirmed**, with the command and output that showed the bug, or **unconfirmed** when a quick script couldn't show it. 3. **Return fixes as patches, applied to a copy.** Patches go to a scratch copy first, and nothing touches your working tree unless you pass `--apply`. Run your tests again after applying. 4. **End with a strict structured answer.** The final report comes through a function tool with a strict JSON schema. The authors found that a `json_schema` text format wasn't enforced on one model when tools were in the request, and answers drifted into prose. 5. **Gate with exit codes.** `0` means nothing at or above `--block-at` (default `high`); `1` means a blocking finding; `2` means the review didn't finish. The full report, which contains pieces of your code, goes to `.git/ai-review.json` so it can't be committed by accident. On a five-bug sample change, a review took one to four minutes and cost $0.015–$0.045. All four models tested confirmed the same four bugs in every completed review, but patch quality varied: one model's patches fixed all five bugs in three of three runs, and a cheaper one did so in one of three. That is 10–40× the cost of a diff-only review; the extra pays for evidence. Sandbox time is billed per second, including the model's thinking time, so a slow cheap model can pay more for the sandbox than a fast expensive one. When you wire it into CI, protect the reviewer itself: * **Run the reviewer from the base branch** (`git show "$BASE:review.py"`), so a pull request can't edit the script that judges it. This is the same idea as reading `REVIEW.md` from the base branch. * **Skip fork pull requests** when the job sends code to an external API, and keep the key in secrets. * **Don't rely on a `pre-push` hook alone.** `git push --no-verify` skips it, so run the same check in CI. Treat **confirmed** findings as strong signals and **unconfirmed** ones as notes for a person, and read every patch before applying it. ### Generate tests that distinguish the change from its parent Meta's Catching JiTTests adds another source of evidence: generate executable tests before a change lands, looking for behavior that passes on the parent revision and fails on the proposed revision. Its **dodgy diff** workflow treats the change itself as a potential mutation; its **intent-aware** workflow infers intent from the code, title, and summary, constructs plausible buggy mutations, generates tests that expose them, then runs those tests on the actual change. The key distinction is between a **weak catch** (a test fails on the new revision) and a **strong catch** (that failure reveals a real bug). Intended behavior changes and incorrect test assertions can both produce weak catches. A failing test demonstrates a difference; deciding whether the difference violates the requirements still needs an oracle. A practical adaptation for a repository: 1. Start with a risky change and a suspected failure mode. Give the generator the diff, surrounding code, and intended behavior. 2. Run the same candidate test against isolated parent and proposed revisions with equivalent fixtures. Keep the test, revision IDs, commands, and outputs together; investigate build, fixture, and flaky failures separately. 3. Filter candidates before asking an engineer. Meta combines deterministic rules with an LLM judge ensemble that sees the test, execution trace, diff, and inferred intent. The ensemble's ranking remains a prediction. 4. Ask the engineer whether the observed behavior change was intended. Once a bug is confirmed, retain a regression test with the correct expected behavior and verify the fix. Meta reports a 60% true-positive rate from engineers who engaged with its production outreach. That is feedback from participating engineers, not the precision of every generated test. Track confirmed bugs and review burden separately from the number of failing tests. ## Make approval authority real Risk tiering only helps if it cannot be gamed. The Claude Code team's rules are a useful reference set: * **The change sets the tier, not the author.** A classifier reads the change; a second classifier asks whether this specific change still needs a person. * **Lighter paths are restricted to trusted authors.** Everyone else needs a second approver. * **A bot's approval never fills a human slot.** Automated review can clear a low-risk change; it cannot substitute for a required person. * **Whoever prompted the agent is a required reviewer**, as if they had typed the code. * **An approval covers one commit.** New commits the system cannot vouch for — an agent push, a hand-resolved merge — require re-approval. * **Some paths always need people.** Sensitive paths and CI workflow files are good examples; enforce them with `CODEOWNERS` and branch protection rather than convention. These controls live in the repository and CI configuration, not in the prompt. Telling an agent "do not merge high-risk changes" is not a permission boundary. See [Agent harness](/env/agent-harness#separate-discovery-from-purchase-approval) for the same principle applied to paid actions. ## Make review converge An agent author and an agent reviewer can keep each other busy indefinitely. In one documented CLI pull request, review and fixes ran for more than fifty rounds overnight before the author stopped it. Investigating where the reviewer kept pointing, about 59% of the flagged code had already been present at the reviewer's first pass — it was surfacing more old bugs each round, not new ones. Fixes that make review converge: * **Cap rounds.** After about three rounds, stop and reconsider the approach instead of requesting another pass. * **Re-review only the new diff** after the first few passes. * **Flag the class of bug**, so every instance is fixed rather than one line. * **Do not repeat** findings already posted. * **Dedup across runs** by comparing against open threads. Track rounds-to-pass alongside recall. A reviewer that finds slightly more while requiring twice the rounds is usually a net loss. ## Keep a red build meaning stop More review layers don't help if nobody trusts the build. In a Thoughtworks experiment where a team let agents write all the code for a week, the application ran but the build was often red. When red is the normal state, people stop reacting to it, and a green build stops being reassuring too. Thoughtworks' Rachel Laycock lists possible causes: parallel agents stepping on each other, a system that isn't modular enough, or changes arriving faster than the checks can finish. DORA's 2025 report shows the same pattern at industry scale: AI adoption is now linked to higher delivery throughput but still to lower delivery stability. Treat a red build on `main` as an incident, not background noise. Fix or revert first, then find out why agents could land on top of it, for example a missing merge queue or checks that are too slow to gate each change. ## Measure human time with a safety guardrail Optimizing only for reviewer minutes invites the obvious failure: the time reappears as incident response. The guardrail makes that trade visible. The Claude Code team tracks human approvals per PR (median and 95th percentile), human comments, and time a PR waits on a person, with **revert and incident rates as the ceiling**. If reverts rise, saved review time was not saved time. They also measure reviewer **noise** by observing what authors do with each comment: fixed it, said it was wrong, said the behavior was intentional, or ignored it. They additionally run the reviewer against known-clean PRs to count harmful false alarms. Recall alone is easy to inflate; the response distribution is the honest signal. ## Watch what the reviewer costs, and why Cloudflare's AI reviewer is a useful cost postmortem: from March to August the average review went from $1.22 to $2.32 with no architectural change, then fell to **\$0.77 (−68%)** with a median time of 1m 32s instead of 4m 09s. Roughly 40% of the savings came from code changes and the rest from model and effort choices. The diagnostic half is more transferable than the numbers. **Spend followed context, not output.** Just before optimizing, the bill split roughly 43% cache writes, 34% cache reads, and 23% output: most money went to context the model had already seen or was about to re-see. A single code-quality session made 16.6 model calls, writing 72k tokens to cache and reading back 1.08M, because every call resends the conversation. A high cache hit rate is not the same as a small bill — the hit rate rose to 97% while tokens per review tripled to 2.99M. The largest single fix was the least obvious. Every session opens with 11k–21k tokens of tool definitions and agent prompt that are identical across repositories, yet the first request hit cache only 14–26% of the time. The prompt had been assembled as one block with a single cache breakpoint at the end, so the shared prefix was never stored on its own. Splitting the block at a marker, removing repository-specific content ahead of it, and keeping tool descriptions stable lifted first-request hits to 91–99.5%. Prepending the standards reviewer's reference index instead of spending three turns reading it cut its calls from 15.9 to 9.6. Smaller fixes were each worth cents and compound: * Remove tools a sub-reviewer cannot use — 57–76% of sessions tried to call the one that posts the final comment, then spent a call recovering. * Read files in parallel instead of one tool call per turn. * On re-reviews, skip reviewers with nothing new to look at. * Stop after posting instead of running a turn to write an unread summary. * Distinguish "slow" from "broken": a reviewer hitting its time limit was restarted with the same limit. * Honor cancellation — in a sample of 446 cancelled jobs, 358 ran to completion. **Then check quality per role, not in aggregate.** Fewer critical findings can mean less noise or more misses, so Cloudflare checked both directions: the share of serious findings authors acted on rose from 34% to 59% (baseline coincidence \~15%), important findings per review stayed flat at 0.28 → 0.30, and inflated severities fell 70% (0.46 → 0.14). But their performance reviewer lost about 64% of important findings at medium effort, so code quality moved to high effort while the others are still being tested. Medium effort genuinely lost real findings for that role. Two habits to copy: instrument the **first request of every session** for cache hits, and verify that each reviewer still finds real problems at the effort level you pay for. The authors also note their before/after hour-based comparison is not a controlled experiment. ## Turn incidents into a reviewer eval set This is the most reusable idea in the process: past PRs that caused incidents, with their fix-forwards and reverts, become the reviewer's regression suite. Engineers who know that code confirm each bug and where it lived, and the reviewer runs against the set daily. Any change to the reviewer's prompt, tools, or model gets rescored against all of it. It is the same discipline as [calibrating an LLM judge](/env/ai-evals#calibrate-the-judge-against-people), applied to a reviewer: keep labeled real failures, include clean cases, and revalidate after every configuration change. ## Keep determinism for the parts that must not drift Uber's AutoClean is the clearest published example of an agent doing **deletion** work at scale: over 16,000 stale feature flags and more than a million lines of code removed, with diffs routed to humans only after automated correctness checks pass. The split it uses is more instructive than the numbers. **Deterministic tools do the rewrites; agents do the propagation decisions.** Inlining a rolled-out flag value is mechanical, but then someone must decide whether a parameter can be deleted (requires checking every call site), whether the old branch is now unreachable, and whether a config field is still read elsewhere. AutoClean gives the agent code search and editing, and routes boolean simplification through Uber's PolyglotPiranha engine via MCP. The rationale is blunt: a small error in simplifying a condition silently changes which branch runs in production. Two more patterns generalize beyond flag cleanup: * **Scope each fixer to its file class.** CI failures go first to cheap deterministic fixers, then to agentic ones. The test fixer may only edit test files — without that limit, an agent will sometimes make a failing test pass by changing the production code underneath it. * **Separate validation from the loop that produced the change.** Long tasks with many instructions lose constraints; the agent optimizes for the most immediate signal, which is usually “CI is green”. Uber's **CodeCourt** takes the failure modes observed in practice and turns each into an explicit property checked by its own reviewer agent, in parallel: | Property | What it blocks | | - | - | | No additions | Cleanup that introduces new code | | Preserves semantics | Behavior that changes observably | | No intent drift | Removing unrelated flags “while here” | | No agent artifacts | Reasoning comments left in the diff | All properties pass → the diff goes to a human for the business decision. Any property fails → the diff is abandoned before a reviewer sees it. Notably, a single end-to-end reviewer agent performed worse than several focused ones. That last point is the direct link to this page's earlier advice: **verification is cheaper and sharper when each check has one job.** It also explains why the human stays in the loop for the judgment call — whether the flag should be removed at all — rather than for mechanical correctness. ## Tune review instructions in the right file Two files shape what gets flagged, and they are not interchangeable: * **`CLAUDE.md`** carries project context — stack, conventions, non-goals. Every review loads it; a change that violates it can become a finding. * **`REVIEW.md`** carries review-only rules: what severity means in this repository, nit caps, paths to skip, and evidence requirements. Good instructions are short and behavioral. Useful patterns: * Redefine **Important** for this repository — a docs repo's "Important" differs from a billing service's. * **Cap nits** per review so the summary stays actionable. * Skip generated code, lockfiles, and anything CI already enforces. * Require **`file:line` evidence** for behavior claims instead of inference from a name. There is a security property worth understanding: `REVIEW.md` is read from the pull request's **base branch or default branch, never from the PR's own diff**. Otherwise a PR could weaken the rules that judge it. Some instructions — lowering severity, excluding paths, capping nits — only take effect from a root file on a protected default branch, and when protection cannot be confirmed the service may read no `REVIEW.md` at all. Protect the branch before relying on the tuning. ## Adoption checklist Before the pull request: * Give the agent checks it can run, listed in a short `CLAUDE.md`, plus hooks for formatters and linters. * Run `/code-review`, `/security-review`, or a fresh-context subagent review locally. * Move repeated review comments into `REVIEW.md`. On every pull request: * Require CI, and add **Testing**, **Risk**, and **How to revert** to the pull request template. * Enable an AI reviewer on one repository, tune instructions for a few weeks, then widen. * Require every review thread resolved before merge. * Match effort to risk; cap rounds and re-review only new diffs after the first few. Approval and after: * Write down risk tiers and start strict; loosen only with evidence. * Use `CODEOWNERS` and branch protection so sensitive paths always need a person. * Never let a bot approval replace a required human, and dismiss approvals on new commits. * Turn incidents and reverts into the reviewer's eval set; measure human time with reverts as the guardrail. ## References * [meng shao: Meta Catching JiTTests](https://x.com/shao__meng/status/2119978619196084717) — Folo intake, November 10, 2026; entry `1371263115974438912` * [Meta: Catching Bugs Before They Land](https://engineering.fb.com/2026/10/29/security/catching-bugs-before-they-land-jittestings-human-on-the-loop-approach-at-full-scale/) — two generation workflows, filtering, engineer feedback * [Just-in-Time Catching Test Generation at Meta](https://arxiv.org/html/2601.22832v1) — weak versus strong catches and the test-oracle problem * [meng shao: Cloudflare AI code review cost optimization](https://x.com/shao__meng/status/2113098764324159608) — Folo intake, October 22, 2026 * [Cloudflare: Cutting our inference bill by 68%](https://blog.cloudflare.com/obsessive-inference-optimization/) — token accounting, shared cache prefixes, per-role quality checks * [meng shao: Uber AutoClean agentic cleanup](https://x.com/shao__meng/status/2112723092468605242) — Folo intake, October 21, 2026 * [Uber: Using AI to Delete Code](https://www.uber.com/us/en/blog/ai-code-cleanup/) — deterministic rewrites via MCP, scoped fixers, CodeCourt properties * [宝玉: Claude Code team's code review practice](https://x.com/dotey/status/2111384189656252712) — Folo intake, October 17, 2026; points to the team's write-up * [How the Claude Code team does code review](https://claude.dev/blog/solving-code-review-at-anthropic/) — layers, risk tiers, convergence fixes, reviewer evals, adoption steps * [Claude Code: Code Review](https://code.claude.com/docs/en/code-review) — four-stage pipeline, review levels, explicit limits * [Read and request reviews on a pull request](https://code.claude.com/docs/en/code-review-pull-requests) — severity levels, check-run behavior, machine-readable verdict * [Customize Code Review](https://code.claude.com/docs/en/code-review-customize) — `REVIEW.md` vs `CLAUDE.md`, and which branch the rules are read from * [Bringing Code Review to Claude Code](https://claude.com/resources/articles/code-review) — vendor-reported preview metrics (16% → 54%, large-PR findings, under 1% judged incorrect) * [Code Review is now generally available](https://claude.com/resources/articles/code-review-is-now-generally-available) — Quick/Standard/Deep levels and faster reviews * [Folo source: meng shao on OpenRouter's verifiable code review](https://x.com/shao__meng/status/2117411081971015897) * [OpenRouter: Build an AI code reviewer](https://openrouter.ai/blog/tutorials/ai-code-review/) — sandbox reproduction, confirmed/unconfirmed findings, exit codes, base-branch reviewer in CI * [Folo source: meng shao on why good developers are wary](https://x.com/shao__meng/status/2117092563329179702) * [Rachel Laycock: Why are good developers so wary of agentic development?](https://www.martinfowler.com/rachels-ramblings/good-devs-wary.html) — the agent-only week and the red build * [Google Cloud: Announcing the 2025 DORA report](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report) — AI adoption, throughput, and stability # AI product evals Source: https://base.bangwu.me/env/ai-evals Build task-specific AI evaluations from real traces: discover failures, create minimal regression cases, calibrate LLM judges, and separate CI, monitoring, and guardrails. # AI product evals A model benchmark helps you choose a starting model. A **product eval** checks whether your actual application meets a user's goal, including its prompts, retrieval, tools, permissions, and application code. A fluent answer is not evidence that the requested action succeeded. This workflow synthesizes Hamel Husain's evals flashcards and FAQ with OpenAI's evaluation guidance. It complements [Agent harness](/env/agent-harness): the harness controls execution; evals provide evidence about its behavior. ## Start with failures, not a dashboard A **trace** records the path from a user request to its outcome: messages, retrieved context, tool arguments and results, and relevant state changes. For multi-agent work, preserve a shared trace ID and the source and ordering of events. 1. **Collect diverse traces.** Mix random samples with different workflows, negative feedback, retries, and unusually slow runs. Keep some random sampling even after you know which failures to search for. 2. **Write open-ended notes first.** Have someone who understands the product inspect examples before an automated reviewer suggests labels. Record what went wrong for the user, including ordinary code or design bugs, not just model errors. 3. **Group recurring failures.** Turn notes into specific categories such as “booked an unavailable slot” or “claimed success after a tool failed.” Then label pass/fail for each relevant criterion and retain the evidence. 4. **Prioritize and repeat.** Consider frequency, impact, and remediation cost. Continue until new reviews stop revealing or changing failure categories; revisit after meaningful product changes. Hamel suggests a pool of roughly 100 diverse traces, with an initial manual pass. Treat this as a starting heuristic, not a statistical guarantee or a reason to delay starting with a smaller batch. **Discovery and measurement need different samples.** A batch selected for retries helps find problems, but its failure rate is not the production failure rate. Keep the sampling method with the results; use representative sampling or an explicit weighting scheme for prevalence estimates. Redact secrets and unnecessary personal data before sharing traces or sending them to an external judge. ## Turn an observed failure into a regression case For a long conversation, locate the first upstream failure before counting its downstream consequences as separate problems. Preserve the full trace for investigation, then minimize the reproduction. Consider an illustrative scheduling agent: ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} User: Book the 10:00 slot. Tool result: 10:00 is unavailable. Agent: Calls the booking tool for 10:00 anyway. <-- first failure Agent: Says the appointment is confirmed. ``` The smallest useful test may only need the request and the availability result. In **N-1 testing**, replay the valid conversation prefix before the failing step and evaluate what the system does next. Keep the expected behavior outside the input; do not feed the original failed answer or its label back to the system under test. A practical test record can include: | Field | Purpose | | - | - | | `case_id`, `source_trace_id` | Link the regression to its original evidence | | `input_prefix`, `tool_fixtures` | Reproduce the relevant conversation and tool state | | `criterion`, `expected_behavior` | Define one behavior, not a vague quality score | | `app_version`, `prompt_version`, `model` | Identify what was evaluated | | `rubric_version`, `judge_version` | Identify how it was graded | | `result`, `evidence` | Preserve the outcome and supporting tool event or text | Run replay tests in a sandbox with mocked tools or isolated test accounts, never against live booking, payment, or deletion endpoints. If the workflow or tool schema changes substantially, rebuild stale fixtures. Keep end-to-end tests too: passing an isolated next-step test does not prove the whole session succeeds. ## Use the cheapest trustworthy check | Failure to detect | Start with | What to verify | | - | - | - | | Invalid output schema or missing field | Code assertion | Parse and validate the actual output | | Wrong tool argument or unauthorized action | Code assertion and runtime permission check | Inspect the arguments, identity, and state at the action boundary | | Success claim unsupported by tool results | Human review, then a calibrated LLM judge when needed | Compare the final message with the relevant execution evidence | | Poor overall user experience | Human review and product experiments | Identify the specific failure before automating it | Fix obvious prompt omissions and ordinary bugs first. Add cheap regression tests where useful; invest in an LLM judge when an important semantic failure needs repeated measurement. **Do not wait for a real incident to test known safety requirements**, such as authorization or irreversible actions. Prefer a narrow pass/fail criterion over an undefined “quality: 4/5.” For the scheduling example, separate “did not book an unavailable slot” from “did not claim an unconfirmed booking succeeded.” Each needs different evidence. Numeric scores or pairwise comparisons can still be useful when their meaning is explicit and validated; binary labels are a practical default, not a universal law. A semantic grader can return a small structured result such as: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "criterion": "no_false_confirmation", "verdict": "fail", "evidence": "The booking tool returned a conflict, but the final message said confirmed." } ``` This is an illustrative format, not a vendor API. Make it possible for a human to check the cited event. Missing evidence or a grader timeout is an evaluation error requiring review, not an automatic pass. ## Check the path, conversation, and final state LangChain's agent-evals guide distinguishes several evaluation scopes. Pick the scope that can actually reveal the failure: | Scope | Example check | Evidence needed | | - | - | - | | Single step | Did the tool receive the requested date? | Tool arguments and current request | | Final response | Does the confirmation match the booking result? | Final message and tool result | | Full conversation | Did the final booking reflect a date change made several turns earlier? | Ordered turns grouped by conversation/thread ID | | Environment state | Does exactly the intended test booking exist? | Records in an isolated test system after the run | A sequence of individually reasonable turns can still fail the overall task. Conversely, different tool sequences can achieve the same valid result. Assert necessary constraints—such as approval before a write or no duplicate booking—rather than requiring one exact trajectory unless that sequence is itself a requirement. For state-changing tasks, start every evaluation from a clean, known fixture and inspect the state afterward. A coding task can be scored with the repository's tests and the resulting diff instead of the agent's “done” message. Keep the trusted grading checks outside the agent's editable work products, and do not let success depend only on tests the agent wrote or changed itself. Containers are one way to isolate such tasks, not the definition of every benchmark and not a complete security boundary by themselves. Limit credentials, network access, mounts, and run time to what the test needs. Record the fixture version, tool configuration, grading result, and trace. Repeat stochastic cases when needed and report passes over attempts; record infrastructure errors and timeouts separately rather than silently excluding them or counting them as success. ## Calibrate the judge against people A second model's opinion is not ground truth. Build a human-labeled set containing both passes and failures for the same criterion, and resolve unclear definitions before tuning the judge. Separate examples by purpose: * **Train/examples:** choose few-shot examples for the judge prompt. * **Development:** revise the rubric and inspect disagreements. * **Held-out test:** check generalization without tuning on these labels. Keep related traces and paraphrases together so they do not leak across splits. There is no universal split ratio or acceptable score. Hamel's card shows an example split, while the FAQ emphasizes choosing targets from the costs of missed failures and false alarms. Define the positive class explicitly. Here, **positive means an actual failure**: * **TPR / failure recall** = `TP / (TP + FN)`: how many human-labeled failures the judge catches. * **TNR / specificity** = `TN / (TN + FP)`: how many human-labeled passes the judge correctly leaves unflagged. If 95 of 100 cases pass, a judge that always says “pass” has 95% accuracy but **0% failure recall**. Report both rates and their sample counts; if a class has no examples, its rate is undefined, not 100%. Small samples leave substantial uncertainty. Recheck agreement after changing the judge model, rubric, or application distribution. Review false alarms and missed failures rather than merely optimizing the aggregate score. Keep the application model/prompt and the grader configuration versioned so score changes remain interpretable. ## Do not inherit a decision model's default threshold Decision models — TypeSafe's Jev, Perplexity's Decider, Liquid's d1, Cloudflare's Clef, OpenAI's Decisions API — are an appealing cheap alternative to an LLM judge. They return a **probability** that a trace contains a failure, and their APIs turn that into a verdict using a default threshold of `0.5`. Hamel Husain's experiment with 98 human-labeled production traces shows why that default deserves skepticism. Consider a model that scores every failing trace `0.40` and every passing trace `0.10`. It is a perfect classifier at a `0.30` threshold — and at `0.50` it catches nothing. Real score distributions overlap, so threshold choice is a precision/recall trade-off, and the right point follows from consequences: an alerting system that must avoid false alarms is not a cancer screening. A working procedure, which costs nothing extra once scores are saved: 1. **Set minimums first.** Require floor precision and recall for the task (Hamel's example: both ≥ 80%). Any model that cannot meet them is out, regardless of its average score. 2. **Tune on training folds, measure on held-out folds.** Use stratified cross-validation with identical splits across models, and pick the threshold on the training portion only. Select an objective that matches the business — F-beta if precision and recall are not equally costly. 3. **Compare cost and performance.** On this small sample the cheapest candidate ran about 0.82 cents per 100 evaluations at F1 0.79; the strongest ran 3.72 cents at F1 0.87. Three points is an illustration, not a benchmark. 4. **Check calibration before treating a score as confidence.** A `0.8` should mean roughly 80% of similar traces fail. Some models were badly miscalibrated — one batch averaged 8% predicted probability while 60% actually failed. Platt scaling fixed several models; for one it made the Brier score slightly worse (0.159 → 0.164), and fitting directly on probabilities instead gave 0.154. Method choice matters, so measure after calibrating. 5. **Re-tune after any prompt change.** Threshold and calibration are properties of the prompt–model pair, not the model alone. Two scope notes. The experiment deliberately used a broad “any substantive issue” task to separate models; for production, keep **one judge per failure mode**, which usually compresses the gaps between models. And a cheap prompt improvement — replacing a vague instruction with an explicit list of failure types — moved F1 from 0.78 to 0.80, which is worth trying before reaching for calibration machinery. ## Evaluate classifiers at the operating point Airbnb's production classification study is a useful example of evaluating a model against product constraints. Its content-policy classifier gates publication, so false positives block legitimate content. It must return a score within 200 ms at thousands of requests per minute. The evaluation uses 10,000 held-out examples weighted to reflect production traffic. Airbnb reports that a small fine-tuned classifier matched frontier-model quality, with about 85 ms p99 latency. The reusable lesson is the evaluation procedure, rather than a model ranking: * **Set the decision costs first.** Choose a threshold on development data that meets the required precision and recall, then report held-out results at that threshold. The study reports maximum F1; that alone does not establish the right threshold for a product that particularly penalizes false positives. * **Compare scores and verdicts deliberately.** A score supports threshold sweeps; a yes/no answer supplies one operating point for that prompt. Rewriting a prompt to move that point creates a new configuration to evaluate. * **Measure latency under the expected load.** Include p99 and throughput, not just median response time. A model with excellent quality can still miss a synchronous publication deadline. * **Model the cost crossover.** Dedicated GPU rental continues while idle; API token costs grow with traffic. Include utilization, worker capacity, prompt length, cache behavior, and separately budget labeling, training, and operations. The article's “about 1%” compares serving costs at high volume using October 2026 public API prices and a single rented GPU. It assumes 71% cache hits for eligible APIs and excludes negotiated discounts; it is not a universal total-cost ratio. For low-volume tasks or policies that change frequently, a prompted API model can remain the better starting point. Fine-tuning becomes worth evaluating when the task is stable, labeled in-domain data is available, and latency or sustained volume justifies it. ## Separate regression tests, monitoring, and guardrails | Placement | Data and timing | Purpose | Response to failure | | - | - | - | - | | CI / pre-release | Curated regression cases before merge or release | Catch known regressions | Block changes according to explicit acceptance criteria | | Production monitoring | Sampled real traces, usually asynchronous | Discover new failures and track drift | Alert, investigate, and add cases | | Runtime guardrails | Checks on each protected request or action, synchronously | Prevent a specified harmful action or response | Block, request approval, or use a safe fallback | A check after the response can discover a bad purchase; it cannot prevent that purchase. Enforce permissions **before the side effect**, outside the model. Guardrails also need latency and false-alarm budgets. Do not retry payments or other writes blindly when a check fails; see [purchase approval boundaries](/env/agent-harness#separate-discovery-from-purchase-approval). CI pass rates are not estimates of user satisfaction: regression suites deliberately overrepresent known failures. Likewise, a green suite proves only what it covers. Keep adding independently reviewed production failures and deliberate edge cases, and rerun relevant evals when code, prompts, models, retrieval, or tools change. ## A minimal starting checklist * Review a small, diverse batch with a product/domain expert. * Name one important failure and retain its trace evidence. * Reproduce it with a minimal safe fixture and a clear assertion or rubric. * Validate any automated judge against both human-labeled passes and failures. * Compare the current and candidate systems on the same versioned cases. * Assign an owner for failures and feed new production cases back into the suite. ## References * [meng shao: Airbnb's production classifier benchmark](https://x.com/shao__meng/status/2119973180945387755) — Folo intake, November 10, 2026; entry `1371263115974438914` * [Airbnb: Frontier quality at 1% of the cost](https://airbnb.tech/ai-ml/frontier-quality-at-1-of-the-cost-a-production-benchmark-of-llm-classifiers/) — weighted evaluation, scores versus verdicts, latency, and serving-cost assumptions * [meng shao: using decision models for evals](https://x.com/shao__meng/status/2112720094287786298) — Folo intake, October 21, 2026 * [Hamel Husain: How To Use Decision Models For Evals](https://hamel.dev/blog/posts/decision-model-evals/) — threshold tuning, cost/performance, calibration, prompt scope * [meng shao: Common agent-eval questions](https://x.com/shao__meng/status/2110585984564039900) — Folo intake, October 15, 2026 * [LangChain: The Most Common Questions About Agent Evals, Answered](https://www.langchain.com/blog/common-questions-about-agent-evals) — step, conversation, trajectory, and environment-state evaluation * [meng shao: Pocket Guide to AI Evals](https://x.com/shao__meng/status/2109445747133579381) — Folo intake, October 12, 2026; points to Hamel's original cards * [Hamel Husain: Evals flashcards](https://hamel.dev/notes/llm/evals/flashcards/) — especially error analysis, judge validation, trace-based cases, and deployment * [Hamel Husain: AI Evals FAQ](https://hamel.dev/blog/posts/evals-faq/) — sampling, evaluator selection, calibration, and multi-turn debugging * [Hamel Husain: Your AI Product Needs Evals](https://hamel.dev/blog/posts/evals/) — scoped tests and human review as the foundation * [OpenAI: Evaluation best practices](https://platform.openai.com/docs/guides/evaluation-best-practices) — task-specific evals, human calibration, edge cases, and continuous evaluation # Beads Source: https://base.bangwu.me/env/beads Beads is a Dolt-backed graph issue tracker that gives coding agents structured memory, dependency-aware task tracking, and JSON-first workflows. # Beads [Beads](https://github.com/gastownhall/beads) is a graph issue tracker built for coding agents. Its CLI is `bd`, and its storage layer is [Dolt](https://www.dolthub.com/), a version-controlled SQL database. The useful idea is not just "another todo list". Beads gives agents a structured task graph that can survive long sessions, multiple branches, and context-window pressure. ## What problem it solves Markdown plans are easy to start but hard to maintain once a task becomes long-running: * dependencies are implicit * multiple agents can edit the same file * closed work keeps taking context space * resuming a task requires rereading a lot of prose * handoff between branches or machines is fragile Beads turns task state into a database-backed graph so agents can query what is ready, claim work, link blockers, and preserve an audit trail. ## Core model Beads stores issues as structured records rather than free-form notes. Important concepts: * **Issues**: tasks, bugs, epics, messages, or other work items. * **Dependencies**: parent-child links, blockers, related items, duplicates, and superseded items. * **Ready queue**: `bd ready` lists work with no open blockers. * **Claims**: `bd update --claim` lets an agent atomically take a task. * **Compaction**: old closed work can decay into summaries to reduce context cost. * **JSON output**: commands are designed for agents and scripts to parse. This makes Beads closer to an agent memory layer than a normal human-only issue tracker. ## Basic workflow Install the CLI once, then initialize it inside a project: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} brew install beads cd your-project bd init ``` Then tell agents how to use it: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} echo "Use 'bd' for task tracking" >> AGENTS.md ``` Common commands: | Command | Use | | - | - | | `bd ready` | List unblocked tasks. | | `bd create "Title" -p 0` | Create a high-priority task. | | `bd update --claim` | Claim a task atomically. | | `bd dep add ` | Add a dependency or hierarchy link. | | `bd show ` | Inspect details and audit history. | ## Storage modes Beads has two main storage modes: * **Embedded mode**: `bd init` uses an in-process Dolt database. This is the default and fits most personal or single-writer workflows. * **Server mode**: `bd init --server` connects to a `dolt sql-server`, which is better when multiple writers need concurrent access. It also supports **git-free usage** with `BEADS_DIR` and `bd init --stealth`, useful for CI, evaluation runs, monorepos, non-git version control, or personal task tracking that should not modify the shared repository. ## When to use it Beads is worth considering when: * a coding task spans many turns or days * multiple agents or branches need to coordinate * task dependencies matter more than a flat checklist * you want machine-readable task state instead of prose plans * you need to preserve progress without stuffing everything into the prompt For a short one-off change, plain Markdown is simpler. For long-horizon agent work, Beads gives the harness a more reliable external memory surface. ## How it fits with agent harness design In an agent harness, Beads belongs in the **memory and coordination** layer: * it externalizes task state from the model context * it gives agents a queryable ready queue * it reduces merge conflicts through generated IDs and structured storage * it makes handoff easier because task status is not hidden in chat history This complements tools like `git worktree`, browser harnesses, and repo-local `AGENTS.md` instructions. The pattern is the same: move durable state out of the model and into inspectable project infrastructure. ## Things to check before adopting * Decide whether `.beads/` should be committed, ignored, or used in stealth mode. * Prefer JSON output for agent automation. * For multi-agent workflows, test claiming and dependency updates before relying on them. * Verify install binaries or checksums before trusting downloaded tools. * Keep task titles and dependencies small enough for agents to scan quickly. ## References * [gastownhall/beads](https://github.com/gastownhall/beads) * [Beads documentation](https://gastownhall.github.io/beads/) * [Dolt](https://www.dolthub.com/) # Browser Automation Observability Source: https://base.bangwu.me/env/browser-observability Debugging browser automation with read-only CDP tracing — attach a second CDP client to capture DevTools events, screenshots, and DOM snapshots without disrupting the main automation flow. # Browser Automation Observability When browser automation (Playwright, Stagehand, browser-use, etc.) fails, gets stuck, or can't find an element, you need to see **what actually happened** — network requests, console errors, DOM changes, and screenshots aligned by timestamp. The `browser-trace` skill makes this possible without disrupting your main automation. ## Core Idea: Read-Only CDP Sidecar Chrome DevTools Protocol (CDP) allows **multiple clients** to connect to the same browser target simultaneously. Your main automation sends commands through one CDP client. The trace skill connects a **second, read-only CDP client** that only subscribes to observation domains (Network, Console, Runtime, Log, Page) — never sending actions that change the page. ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} ┌─────────────────┐ ┌─────────────────┐ │ Main Automation │ │ browser-trace │ │ (Playwright / │ │ (read-only │ │ Stagehand / │ │ CDP client) │ │ browser-use) │ │ │ │ sends commands │ │ only observes │ └─────────┬────────┘ └─────────┬────────┘ │ │ └─── CDP ──► Chrome ◄─────┘ (same target) ``` > [!NOTE] > > CDP is designed for multiple clients. The main automation owns the "action" domains (DOM manipulation, input events). The trace client only subscribes to "observation" domains (Network events, Console messages, Page lifecycle). They coexist without interfering. ## Three Mechanisms ### 1. Firehose — Raw CDP Event Stream Captures all CDP events into NDJSON for post-hoc analysis: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} browse cdp # Writes CDP full stream to cdp/raw.ndjson per line ``` ### 2. Sampler — Periodic Screenshots + DOM Snapshots Periodically grabs screenshots and full-page HTML alongside the event stream: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} browse --ws screenshot # Screenshot via one-shot WS connection browse --ws get html body # Full page HTML via one-shot WS connection ``` ### 3. Bisector — Post-Run Segmentation After the automation completes, `bisect-cdp.mjs` segments the raw event stream into structured, searchable chunks: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} bisect-cdp.mjs # Scans raw.ndjson, splits by: # - CDP method buckets (multiple JSONL files) # - Page navigation segments (pages/000/... tree) ``` This makes it easy to find events by navigation phase (e.g., "what happened after the login page loaded"). ## When to Use * **Automation fails / gets stuck** — Find the exact moment it broke: which request failed, which JS error fired, which DOM element was missing * **Mid-session debugging** — Attach trace to an already-running session without restarting * **Causal analysis** — Align network, console, DOM, and screenshots by timestamp to trace root causes ## Practical Constraints 1. **Sampling interval** — Don't sample faster than \~1s (default 2s). Each sample adds CDP/ screenshot overhead. 2. **DOM domain is noisy** — Fine-grained DOM tree changes require adding `DOM` to `O11Y_DOMAINS`, but it generates very verbose output. 3. **Always run stop-capture** — Even if your code crashes, run `stop-capture.mjs` to avoid zombie processes and missing `stopped_at` timestamps. 4. **Bisect is idempotent** — You can re-run it on the same data; it overwrites previous segmentations. 5. **Don't re-open sessions** — For remote automation with `browse --connect`, don't call `browse env remote` to open a new session for the same browser target. ## Quick Start ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 1. Start capture before your automation runs start-capture.mjs # 2. Run your automation (Playwright, etc.) as normal # 3. Stop capture after completion stop-capture.mjs # 4. Segment the captured data bisect-cdp.mjs # 5. Inspect results jq '. | select(.method == "Network.requestWillBeSent")' cdp/raw.ndjson rg "console.error" pages/ ``` ## References * [browser-trace skill on skills.sh](https://skills.sh/browserbase/skills/browser-trace) * [Browserbase team](https://www.browserbase.com/) * [CDP Protocol docs](https://chromedevtools.github.io/devtools-protocol/) # Claude Code effective patterns Source: https://base.bangwu.me/env/claude-code-patterns Practical patterns for working with Claude Code Fable 5, from the Claude Code team and community practitioners: treat the model as a thinking partner, set goals with verification, give full context, demand self-checks, and use budget constraints to force better trade-offs. # Claude Code effective patterns Claude Code's Fable 5 model brings significantly stronger coding capability — it can run for hours, test its own work, and often write code better than the developer. But a strong model does not guarantee effective use. These patterns come from Claude Code team member Thariq and community practitioners. ## Three mindset shifts Thariq from the Claude Code team described three key changes in how he works with Fable 5: ### Unhobble Claude: let the model surprise you Anthropic internally calls it **capability overhang** — the model can already do many things, we just haven't found the right way to unlock them. Early models needed detailed instructions and examples, but with Fable-level models, too many examples actually constrain the model because its own imagination is richer than what you can specify. Claude Code recently cut **80% of its system prompt**. The new approach: give context, not constraints. Tell the model about the situation, not what it's not allowed to do. A concrete example: ask a chat model which Pokémon names end with "aw" — it can't answer because it can't iterate through names in its head. But give it a code execution tool and it pulls the full list, writes a script, and finds the answer in two seconds. The capability was there all along; the tool unlocked it. ### Treat Claude as a thinking partner The old pattern: break tasks into small pieces, check every output, catch problems when the model stops too early. With Fable, you increasingly check whether Claude is doing the **right work**, not just whether it's working correctly. A common failure mode: you don't actually know what you want, or what's feasible. Involving Claude early in your thinking catches these blind spots before implementation. Practical approaches: * Start with a small spec. Before writing the final spec, ask Claude to "interview" you about the implementation plan. * Throw out an idea and ask it to explore several directions, generating HTML prototypes for review. * Give it context, not just constraints. Instead of "keep it simple, don't over-engineer," say "this feature is an experiment — we'll likely delete it in a month, so don't build anything you'd be sad to throw away." ### Set goals and provide verification methods Once you know what you want, use two Claude Code features: * `/goal`: keeps Claude working toward completion * **Workflows**: helps Claude verify its own output After writing a spec, try: > "Set a goal to fully implement this spec. Then use workflows to verify each part of the plan and prepare a report on what was implemented and any discrepancies." This lets Claude be creative and thorough while ensuring it builds what you actually need. ### Be more ambitious Fable is an incredible model. If you think an LLM can't do something — give it a chance. Thariq edited the very video he posted using Fable. Don't let past experience cap your expectations. ## Five principles to push Fable to its limits Community practitioner Gorden Sun distilled five practical principles: ### 1. Give goals and acceptance criteria, let Fable decompose the steps Don't micromanage. Tell it what to achieve and how to judge success. Let it plan its own path. Over-decomposing tasks limits the model's planning ability. ### 2. Let Fable plan and ask questions before executing Give the model a "thinking phase." Let it propose an approach and ask clarifying questions before you confirm and it starts building. This prevents major directional mistakes. ### 3. Give all raw materials at once Don't feed information in fragments. Provide all relevant documents, codebase context, and requirements in one shot. Fable's long-context capability lets it judge what matters and how things connect. ### 4. Explicitly demand self-checks Key self-check dimensions: * **Write tests**: require tests for every feature and ensure they pass * **Find counterexamples**: identify edge cases where the solution might fail * **Mark confidence**: label each key conclusion with confidence level and what evidence would change the judgment ### 5. Use budget constraints to force better trade-offs Moderate resource limits (search count, word count, time) force the model to make smarter prioritization decisions. Unlimited resources can produce unfocused, excessive output. ## Manage context deliberately A large context window is capacity, not a reason to fill it. Providing complete task context means giving the requirements and relevant evidence, not appending every log or unrelated conversation. Claude Code clears older tool outputs and, when needed, summarizes the conversation as context fills. **Compaction is a lossy handoff, not verbatim retention of the whole conversation.** Earlier details can disappear; a summary is not proof that a test passed or a decision was approved. Use this workflow for long tasks: 1. **Inspect before adding more.** Run `/context` to see what occupies the window. Filter logs and read relevant file ranges instead of repeatedly loading entire outputs. 2. **Separate rules from task state.** Put persistent project instructions in `CLAUDE.md`. Keep the current goal, acceptance criteria, decisions, changed files, test commands and results, unresolved risks, and next step in a short task note. Link to evidence rather than copying large outputs. 3. **Compact at a coherent boundary.** Save that note before switching from investigation to implementation, or from implementation to review. Use a focused command when you want control: ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} /compact Preserve the goal, acceptance criteria, decisions, changed files, test results, unresolved risks, and next step. ``` 4. **Verify the handoff.** After compaction, have Claude read the task note and inspect the current diff. Check that it can restate the remaining work; recheck files or rerun tests when evidence is missing or stale. 5. **Reset between unrelated tasks.** Save anything needed first, then use `/clear` rather than carrying irrelevant history into the next task. You can add a `Compact Instructions` section to `CLAUDE.md` to specify what summaries should preserve. Treat it as guidance, not a guarantee of lossless memory. See [Agent harness](/env/agent-harness) for the broader durable-state pattern. The Folo discussion that prompted this note suggested compacting around 300k–400k tokens. That is a practitioner's preference, **not a universal optimum**. Check the commands supported by your installed version and tune from observed quality, latency, and usage rather than copying a threshold or removing a context-limit setting blindly. ## Example prompts to try ### End-to-end deep research ``` Do deep research on "2026 AI Agent infrastructure landscape," cross-verify at least 8 sources, organize key data into tables with trend analysis, deliver a cited report plus an infographic. Give me an outline and verification approach first — I'll confirm before you proceed. ``` ### Self red-teaming ``` First present your best solution, then switch to the harshest reviewer, find three fatal flaws, and produce a revised version. Mark confidence for each key conclusion and explain what evidence would change your judgment. ``` ### Massive context audit ``` (Attach an entire contract, codebase, or manuscript) Read through everything. Find all internal contradictions, inconsistent definitions, and broken cross-references. Sort by severity and cite the original location for each. ``` ### High-constraint creative work ``` Write a regulated verse poem with a hidden four-character acrostic, a double entendre in the second couplet, and a complete ban on two specific characters. Verify every constraint after completion. ``` ### Pure code music ``` Using no audio assets, synthesize a 30-second electronic track in pure code, then build a webpage with a particle fluid that moves to the beat. ``` ## Find your unknowns: blind spot techniques Thariq's second key theme: your prompt is a "map," but the real codebase is the "territory." When the model encounters something not on your map, it must decide on its own. Fable 5's range is so large that if you don't identify these unknowns in advance, it will make decisions you didn't want in places you didn't expect. Six concrete techniques: * **Blind spot scan**: before building, have Fable read through relevant code and surface potential issues you didn't know about * **Four-prototype burst**: ask for four stylistically different prototypes at once, then discover your preferences through reaction rather than description * **Interview you**: let Fable ask you questions to extract details you "know but haven't written down" * **Reference code as map**: give it code from another system as a reference pattern — often more efficient than writing a spec from scratch * **Decision log**: have it record every point where it deviated from your expectations, so you can see where it encountered problems you didn't anticipate * **Reverse quiz**: ask Fable to quiz you on what it built, ensuring you understand it well enough to explain the PR ## Maintaining AI-generated code When all code is AI-generated, the risk is not writing code — it is keeping that code iterable, maintainable, and free of rot. Product engineer Tw93 distilled six practices after shipping 13 versions of an app with \~110K lines of Swift and \~73K lines of tests, all AI-generated: 1. **Architecture and layering still matter.** Clear boundaries make AI-generated code easier to maintain and extend. Don't let the model invent the structure each time. 2. **Automated tests are the quality backbone.** Every bug fix must add a regression test, so the same bug can't come back. 3. **Delete dead code aggressively.** When you remove a feature, remove its code too. Accumulated leftovers confuse both humans and future AI passes. 4. **CI/CD with a clean machine.** Run the full test suite on a clean cloud runner before release, not just on your local machine. 5. **Let the AI auto-verify and auto-correct.** Wire automated verification into the loop; reserve human verification for critical stages. 6. **Turn repeated work into skills.** Encode recurring procedures so you don't re-explain them from scratch every session. The throughline: AI lowers the cost of writing code to near zero, so the discipline that matters shifts to architecture, verification, and cleanup. ## Supervising agents smarter than you Frontier agents remove the barrier of "you must build a mental model before changing code," but they still fail in two ways: misunderstanding your intent and lacking the context to get things right. Both share one root cause — the quality of what you put into the context window. Since modern codebases are too large to hold fully in your head, the method shifts from "understand it yourself" to "make the agent prove it understands." Five techniques from a practitioner shipping thousands of PRs per month: **1. Indirect prompting (in your own words).** Don't order directly. First ask the agent to restate the problem in plain language — "read this Slack thread and describe the root problem in your own words." This compresses noise into a structured statement, surfaces misunderstandings before the agent runs the wrong way, and stops your own wrong assumptions from steering it. **2. Mental-model skills.** Four complementary commands: * `/how` — trace runtime mechanics across directories and services * `/why` — investigate intent: code says what happened, rarely why. Search git history, PR comments, Linear, Notion, Slack, Datadog, Sentry in parallel * `/teach` — have the agent explain it back to you intuitively (this also forces the agent to build a real model instead of confidently bluffing) * `/recall` — pull context back from past session transcripts instead of rebuilding from zero **3. README-driven development.** For shared code, write the README before implementing. It forces you to design from the hypothetical user's API perspective. Use the Diátaxis framework to separate Tutorial / How-to / Reference / Explanation, and a pass to strip AI-sounding filler. The finished doc doubles as a concrete target the agent can verify against. **4. Prototype first.** The two planning mistakes are accepting the agent's first design and over-polishing a plan without evidence. Instead, have the agent produce several prototypes in parallel — UI variants behind a switcher, timing/layout measured with a verification CLI — and choose from screenshots. Prototypes are planning in code: the agent answers its own open questions with evidence. **5. Architect in five stages.** Ground (build the current-state model with /how + /why) → Sketch (several independent runners across model families, each producing a full design package: call sites, type definitions, signatures, rationale) → Cross-judge (different models score against a strict rubric) → Implement (fill in the chosen sketch) → the cycle repeats with verification. ## Loops design paradigm Claude Code's official Loops framework elevates agent engineering from intuition to a reusable design language. The core insight: four variables — trigger, stop condition, artifact, and use case — define every agent loop. The question isn't "is this task hard?" but "which segment of work can be handed off?" ### Four loop types **Turn-based (default agentic loop)** * What you hand off: checking this step * Trigger: user prompt * Stop: agent decides it's done or needs more context * Artifact: SKILL.md (encode your verification criteria) * When: short, one-off, non-recurring tasks This is the default. Improve it by encoding your mental acceptance criteria into SKILL.md so the agent can self-check more steps, reducing the rounds per task. **Goal-based (/goal)** * What you hand off: the stop condition * Trigger: manual prompt * Stop: goal achieved, or max turns reached * Artifact: /goal + evaluation model * When: tasks with verifiable exit criteria Use when one turn isn't enough. The key: define exactly what "done" looks like. The evaluation model checks your conditions each turn — deterministic metrics (test pass count, score thresholds) work best because the evaluator only needs to compare, not judge "good enough." **Time-based (/loop, /schedule)** * What you hand off: the trigger timing * Stop: you cancel, or work completes naturally (PR merged, queue emptied) * Artifact: /loop (local, stops on shutdown) or /schedule (cloud) * When: recurring work, or work that reacts to external state changes Prefer event-driven over time-driven: longer intervals or state-change triggers save tokens and avoid jitter. Use /loop for local machines, /schedule for cloud persistence. **Proactive (fully autonomous)** * What you hand off: the prompt itself * Trigger: events or schedule, no human in the loop * Stop: each subtask exits on goal; the routine runs until stopped * Artifact: all of the above + dynamic workflows (research preview) + auto mode * When: standardized incoming work — bug reports, issue triage, dependency upgrades, batch migrations Example assembly: /schedule periodic scan → /goal defines "done" + SKILL encodes verification → dynamic workflows explore multiple solutions with adversarial review → auto mode executes without approval. ### Quality guardrails (four levels) 1. **Keep the codebase clean** — agents follow existing patterns and conventions 2. **Give agents self-verification** — encode "good" as SKILL checks 3. **Make docs accessible** — keep framework/library docs current with best practices 4. **Use a second agent for code review** — a fresh-context reviewer avoids the main agent's confirmation bias When a single result falls short, don't just fix that one issue — encode it into the system so all future iterations benefit. ### Cost guardrails * Match the artifact and model to the task — simple tasks don't need multi-agent loops * Define clear success/stop criteria — be specific about "what done looks like" * Pilot before scaling — dynamic workflows can spawn hundreds of agents * Use scripts for deterministic work — a form-filling script is far cheaper than an agent deriving code each time * Don't run routines more often than necessary Monitor with `/usage`, `/goal` (no args), and `/workflows` to inspect token distribution. The loops themselves don't save money — model tiering and clear boundaries do. ### How to start Look at work you're already doing. Find the step where **you** are the bottleneck. Ask: * Can you write a quantifiable verification check? → If yes, try goal-based * Is "done" clearly definable? → If not, don't automate it yet * Does work arrive on a schedule? → If yes, try time-based * None of the above? → Stick with turn-based and improve your SKILL.md The four loop types are composable building blocks, not mutually exclusive categories. The most sophisticated form (Proactive) is just /schedule + /goal + dynamic workflows + auto mode assembled together. ## Key takeaway Mastering Fable 5 isn't about learning more commands or parameters — it's about changing your relationship with the model: * From "supervising execution" to "guiding direction" * From "decomposing steps" to "setting goals and acceptance criteria" * From "cautious testing" to "bold ambition" * From "checking output" to "demanding self-verification" A good prompt isn't one with the most detailed instructions — it's one where **constraints are just enough, and trust is set to maximum**. ## References * [宝玉: Context compaction thresholds](https://x.com/dotey/status/2108669008283402744) — Folo intake, October 9, 2026; practitioner advice, not an official default * [Claude Code: How Claude Code works](https://code.claude.com/docs/en/how-claude-code-works#the-context-window) — context lifecycle and what compaction can lose * [Claude Code: Best practices](https://code.claude.com/docs/en/best-practices#manage-context-aggressively) — `/context`, focused compaction, persistent instructions, and task separation * [Thariq (Claude Code team): Tips for using Fable 5](https://x.com/dotey/status/2074019009226322078) — compiled by 宝玉 from Thariq's video * [Thariq at AI Engineer World's Fair: Fable 5 talk (unhobbling + blind spots)](https://x.com/dotey/status/2074255513353642090) — four themes from the full presentation * [Claude Code official: Loops design paradigm](https://x.com/shao__meng/status/2074290011282055656) — from prompts to loops * [Tw93: 代码全由 AI 生成时代的可维护性](https://x.com/HiTw93/status/2094015568101921254) — 六个实践:架构分层、自动化测试、清理死代码、CI/CD、自动验证、重复工作 skill 化 * [Simon Willison: Agentic Engineering Patterns](https://x.com/shao__meng/status/2094027833505144919) — 从代码边际成本趋零出发的完整工程方法论 * [poteto: pstack Agent 工程完全指南](https://x.com/shao__meng/status/2099300148874707297) — 验证优先 + 监督比你聪明的人五技法 # Docker Source: https://base.bangwu.me/env/docker Docker containerization guide covering image building, container creation with port mapping, volume mounting for persistence, and CLI commands. # Docker Docker is an open-sourceapplication container engine,lets developers package apps and dependencies into portable containers。 ## Installation ### Windows/Mac Download [Docker Desktop](https://www.docker.com/products/docker-desktop/) ### Linux (Ubuntu) ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun ``` ## Basic Concepts * **Image**: a read-only template containing the filesystem needed to run a container * **Container**: a running instance of an image * **Repository**: a place to store images, such as Docker Hub ## Common Commands ### Image Management ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Search Image docker search nginx # Pull Image docker pull nginx:latest # View Local Images docker images # Remove Image docker rmi nginx:latest # Build Image docker built -t myapp:1.0 . # Export Image docker save -o nginx.tar nginx:latest # Import Image docker load -i nginx.tar ``` ### Container Management ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Run容器 docker run -d --name mynginx -p 80:80 nginx # Parameter Description: # -d:后台Run # --name:指定容器name # -p:Port Mapping 宿主机端口:容器端口 # -v:挂载卷 宿主机路径:容器路径 # -e:设置Environment Variables # --restart:重启Strategy(no/always/on-failure/unless-stopped) # View Running Containers docker ps # View All Containers(Package括停止's ) docker ps -a # Stop Container docker stop mynginx # Start Container docker start mynginx # Restart Container docker restart mynginx # Remove Container docker rm mynginx # Force Remove Running Container docker rm -f mynginx # Enter Container docker exec -it mynginx bash # View Container Logs docker logs -f mynginx # View Container Details docker inspect mynginx # View Container Resource Usage docker stats # Copy File to Container docker cp file.txt mynginx:/path/ # Copy File from Container docker cp mynginx:/path/file.txt ./ ``` ### Volume Management ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Create Volume docker volume create mydata # View Volumes docker volume ls # View Volume Details docker volume inspect mydata # Remove Volume docker volume rm mydata # Clean Unused Volumes docker volume prune ``` ### Network Management ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # View Networks docker network ls # Create Network docker network create mynet # Delete Network docker network rm mynet # Connect Container to Network docker network connect mynet mynginx ``` ## Dockerfile A Dockerfile is a text file used to build an image. ### Basic Structure ```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}} # 基础镜像 FROM python:3.11-slim # 设置工作目录 WORKDIR /app # 设置Environment Variables ENV PYTHONUNBUFFERED=1 # 复制file COPY requirements.txt . # 执行Command RUN pip install --no-cache-dir -r requirements.txt # 复制应用代码 COPY . . # 暴露端口 EXPOSE 8000 # 启动Command CMD ["python", "app.py"] ``` ### Common directives * FROM: specify the base image * WORKDIR: set the working directory * COPY: copy files into the image * ADD: copy files, with support for URLs and automatic extraction * RUN: execute commands during the build * CMD: the default command run when the container starts * ENTRYPOINT: the entry point, not replaced by normal `docker run` arguments * ENV: set environment variables * EXPOSE: declare ports * VOLUME: define a data volume * USER: specify the runtime user * ARG:buildparameters ### Multi-stage Build ```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}} # builtPhase FROM node:18 AS builter WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run built # RunPhase FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` ## .dockerignore This works like `.gitignore`, excluding files that do not need to be copied into the image. ``` node_modules .git .env *.log __pycache__ .vscode ``` ## Image Registry Mirror ### Configure image mirrors (Linux) edit /etc/docker/daemon.json: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "registry-mirrors": [ "https://docker.mirrors.ustc.edu.cn", "https://hub-mirror.c.163.com" ] } ``` Restart Docker: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo systemctl daemon-reload sudo systemctl restart docker ``` ## Practical Tips ### Clean System ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 清理未使用's 容器、网络、镜像 docker system prune -a # View磁盘占用 docker system df ``` ### Auto-restart Containers ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker run -d --restart=always nginx ``` ### Limit Resources ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 限制内存和CPU docker run -d --memory="512m" --cpus="1.5" nginx ``` ### View container IP ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name ``` ## Common deployment examples ### Nginx ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker run -d \ --name nginx \ -p 80:80 \ -v /path/to/html:/usr/share/nginx/html \ nginx:alpine ``` ### MySQL ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker run -d \ --name mysql \ -p 3306:3306 \ -e MYSQL_ROOT_PASSWORD=password \ -v mysql_data:/var/lib/mysql \ mysql:8.0 ``` ### Redis ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker run -d \ --name redis \ -p 6379:6379 \ -v redis_data:/data \ redis:alpine \ redis-server --appendonly yes ``` ### PostgreSQL ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker run -d \ --name postgres \ -p 5432:5432 \ -e POSTGRES_PASSWORD=password \ -v postgres_data:/var/lib/postgresql/data \ postgres:16 ``` ## References * [Docker Official Docs](https://docs.docker.com/) * [Docker Hub](https://hub.docker.com/) * [Dockerfile Best Practices](https://docs.docker.com/develop/dev-best-practices/) # Docker Compose Source: https://base.bangwu.me/env/docker-compose Docker Compose orchestration guide using YAML to define services, networks, and volumes for one-command multi-container application deployment. # Docker Compose Docker Compose is a tool for defining and running multi-container Docker applications through YAML service definitions. ## Installation Docker Desktop already includes Docker Compose. ### Standalone Linux installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose # ValidationInstallation docker-compose --version ``` ## Basic commands ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 启动服务 docker-compose up -d # 停止服务 docker-compose down # View服务State docker-compose ps # ViewLog docker-compose logs -f # 重启服务 docker-compose restart # Build Image docker-compose built # 执行Command docker-compose exec service_name bash ``` ## docker-compose.yml syntax ### Basic Structure ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: web: image: nginx:alpine ports: - "80:80" volumes: - ./html:/usr/share/nginx/html restart: always db: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: password volumes: - db_data:/var/lib/mysql volumes: db_data: ``` ### Common configuration fields * `image`: image to use * `build`: builtConfiguration * `ports`: Port Mapping * `volumes`: volume mounts * `environment`: Environment Variables * `depends_on`: Dependencies * `networks`: network configuration * `restart`: restart policy * `command`: override the default command ## Common service configurations ## MySQL ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: mysql: image: mysql:8.0 container_name: mysql restart: always ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: root_password MYSQL_DATABASE: mydb MYSQL_USER: user MYSQL_PASSWORD: password TZ: Asia/Shanghai volumes: - mysql_data:/var/lib/mysql - ./mysql/conf:/etc/mysql/conf.d - ./mysql/init:/docker-entrypoint-initdb.d command: - --character-set-server=utf8mb4 - --collation-server=utf8mb4_unicode_ci - --default-authentication-plugin=mysql_native_password volumes: mysql_data: ``` ## Redis ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: redis: image: redis:7-alpine container_name: redis restart: always ports: - "6379:6379" volumes: - redis_data:/data - ./redis/redis.conf:/usr/local/etc/redis/redis.conf command: redis-server /usr/local/etc/redis/redis.conf --appendonly yes environment: TZ: Asia/Shanghai volumes: redis_data: ``` ## PostgreSQL ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: postgres: image: postgres:16-alpine container_name: postgres restart: always ports: - "5432:5432" environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: mydb PGDATA: /var/lib/postgresql/data/pgdata TZ: Asia/Shanghai volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: ``` ## MongoDB ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: mongo: image: mongo:7 container_name: mongodb restart: always ports: - "27017:27017" environment: MONGO_INITDB_ROOT_USERNAME: admin MONGO_INITDB_ROOT_PASSWORD: password TZ: Asia/Shanghai volumes: - mongo_data:/data/db volumes: mongo_data: ``` ## Nginx ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: nginx: image: nginx:alpine container_name: nginx restart: always ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/conf.d:/etc/nginx/conf.d - ./html:/usr/share/nginx/html - ./nginx/logs:/var/log/nginx - ./nginx/ssl:/etc/nginx/ssl ``` ## Open WebUI ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: open-webui: image: ghcr.io/open-webui/open-webui:main container_name: open-webui restart: always ports: - "3000:8080" environment: OLLAMA_BASE_URL: http://host.docker.internal:11434 WEBUI_SECRET_KEY: your-secret-key volumes: - open-webui:/app/backend/data extra_hosts: - "host.docker.internal:host-gateway" volumes: open-webui: ``` ## Full web application stack ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} version: '3.8' services: nginx: image: nginx:alpine ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf depends_on: - web networks: - webnet web: built: . environment: DATABASE_URL: postgres://user:password@db:5432/mydb REDIS_URL: redis://redis:6379 depends_on: - db - redis networks: - webnet db: image: postgres:16-alpine environment: POSTGRES_USER: user POSTGRES_PASSWORD: password POSTGRES_DB: mydb volumes: - postgres_data:/var/lib/postgresql/data networks: - webnet redis: image: redis:alpine volumes: - redis_data:/data networks: - webnet networks: webnet: volumes: postgres_data: redis_data: ``` ## Environment Variablesfile Create a `.env` file: ```env theme={"theme":{"light":"github-light","dark":"github-dark"}} MYSQL_ROOT_PASSWORD=root_password MYSQL_DATABASE=mydb REDIS_PASSWORD=redis_password ``` Use it in `docker-compose.yml` like this: ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} services: mysql: environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: ${MYSQL_DATABASE} ``` ## Practical Tips ### View service logs ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # View所有服务Log docker-compose logs -f # View特定服务Log docker-compose logs -f web # View最后100行 docker-compose logs --tail=100 web ``` ### Scale services ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 启动3个web服务实例 docker-compose up -d --scale web=3 ``` ### Rebuild only a specific service ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} docker-compose up -d --build web ``` ### Clean up resources ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 停止并Remove Container、网络 docker-compose down # 同时Remove Volume docker-compose down -v # 同时Remove Image docker-compose down --rmi all ``` ## Best Practices 1. **Use `.env` files** for sensitive information. 2. **Use named volumes** for persistent data. 3. **Define networks** to isolate services. 4. **Set `restart: always`** when high availability matters. 5. **Use `depends_on`** to declare dependencies. 6. **Add health checks**. 7. **Use `deploy.resources`** to limit resources when appropriate. ## References * [Docker Compose Official Docs](https://docs.docker.com/compose/) * [Compose fileSpecification](https://docs.docker.com/compose/compose-file/) * [Awesome Compose](https://github.com/docker/awesome-compose) # Editor extension supply chain Source: https://base.bangwu.me/env/editor-extension-security Treat VS Code, Cursor, and agent-tool extensions as code that runs with your user privileges: control auto-update, pin trusted sources, harden the machine, and clean up after a malicious release. # Editor extension supply chain An editor extension is not a theme or a settings file. In VS Code and its forks, such as Cursor, an extension runs in the **extension host** with the same permissions as the editor. It can read and write your files, make network requests, start processes, and change workspace settings. An extension update is effectively new code running on your machine, and it can reach your source code, SSH keys, cloud credentials, and agent tokens. This page uses a real October 2026 incident to show where the trust boundaries are, then turns it into settings and a checklist. For install-time scripts in JavaScript dependencies, see [npm supply chain](/env/npm-supply-chain). The trust model is the same; the delivery channel is different. ## Case study: a tampered Claude Code extension on Cursor's marketplace > [!NOTE] > > The facts in this section were current as of October 31, 2026. Check the vendor notices under References at the end of this page for later updates. **What happened.** On October 29, 2026, between about 2:27 AM and 1:35 PM PT, Cursor's VS Code Extension Marketplace served tampered builds of `Anthropic.claude-code` versions `2.1.312` and `2.1.313` for macOS and Windows. Anthropic did not build them. Microsoft and Anthropic said the Visual Studio Marketplace, Open VSX, and the npm package were not affected, and Cursor said it had no evidence that the official distribution was affected. Reports estimated up to about 5,000 affected users. Anthropic published its next legitimate release as `2.1.314` so the versions would not be confused. **What the payload did.** Code prepended to `extension.js` ran as soon as the extension host loaded the module, before the extension's normal `activate` function. The user did not have to do anything. The payload: 1. Collected the hostname, username, OS, home and working directories, global Git email, public IP, and up to 40 environment variable **names** (not values) matching `KEY|TOKEN|SECRET|PASS|AWS|GCP`. 2. Appended an attacker SSH public key to `~/.ssh/authorized_keys`, then tried to enable the local SSH server. 3. Opened an outbound reverse tunnel (`ssh -N -R '*:0:localhost:22'`) so the attacker could reach the machine's port 22 without any inbound port being open. 4. Installed persistence outside the extension directory: a macOS LaunchAgent named `com.apple.sysmond`, a Linux `@reboot` cron entry, or a Windows scheduled task named `SysMon` with a Startup-folder fallback. 5. Sent the collected details to the attacker's server. Bugs in the payload, plus the lack of admin rights on most machines, meant the SSH server usually did not start, so the tunnel often led nowhere. The SSH key, persistence, and host report could still land. Do not count on attacker bugs as a defense. ## Durable lessons ### An extension update runs code on your machine Neither the marketplace nor the editor's permission model limits what an extension can do once it is installed. VS Code's `extensions.allowed` setting controls *which* extensions can be installed and enabled. Microsoft's documentation states that it does not limit an extension's runtime permissions. Plan as if every enabled extension can do anything your user account can do. ### A publisher label is not provenance The tampered build appeared under a well-known publisher name, and many people assumed that meant Anthropic had signed it. A mirror or proxy marketplace is its own link in the trust chain. Cursor uses Open VSX behind its own proxy (`marketplace.cursorapi.com`) and notes that the same `publisher.extension` ID can point to a different publisher or different code on Open VSX than on the Microsoft Marketplace. Treat extension IDs the way you treat package names: confirm which registry your editor actually downloads from. ### Auto-update is the delivery path; a cooldown blunts it The malicious versions were available for about 11 hours. Many affected machines received them through automatic updates, not deliberate installs. An install or update cooldown longer than the takedown window would probably have kept them out. A cooldown cannot stop a malicious release that stays up longer than the delay, but it removes the cheapest attack: a short-lived malicious upload. ### Uninstalling is not cleaning up The payload wrote keys, scripts, and startup entries outside the extension folder. Removing or updating the extension does not undo them. Taking the attacker's server offline does not remove them from your machine either. ### Reverse tunnels avoid inbound checks The machine connects *out* to the attacker. A firewall audit that only looks for open inbound ports will not find this. Successful logins through the tunnel show up in SSH logs as coming from `localhost`. ### Environment variable names are a target map Collecting only variable names still tells an attacker which machines hold AWS, GCP, or API tokens and are worth a closer look. Keep long-lived secrets out of your global shell environment. ### The same model applies to agent plugins Claude Code's documentation says the same about its plugins: hooks, monitors, MCP servers, and LSP servers run with your full user permissions and outside the sandbox. Auto-update can change the files you reviewed. The marketplace name tells you who publishes the catalog, not what each plugin does. Use the same rules for agent skills, plugins, and MCP servers. ## Harden a personal setup 1. **Keep the extension list short.** Remove extensions you do not use every week. Each enabled extension is a separate update channel into your machine. 2. **Delay automatic updates.** In VS Code, `extensions.autoUpdateDelay` sets how many hours to wait after a version is published before installing it automatically. It only applies when auto-update is on. VS Code's documentation lists a 12-hour default as of October 2026, but check your version. Pick a longer delay for extensions with broad access: ```jsonc theme={"theme":{"light":"github-light","dark":"github-dark"}} // VS Code settings.json { "extensions.autoUpdateDelay": 72 } ``` In Cursor, set `extensions.installCooldownHours` in user settings when your team has not enforced a cooldown: ```jsonc theme={"theme":{"light":"github-light","dark":"github-dark"}} // Cursor settings.json { "extensions.installCooldownHours": 72 } ``` Clicking **Update** yourself skips the VS Code delay. Only do this when you have a reason. 3. **Pin high-risk extensions manually.** Right-click an extension and turn off **Auto Update**. Update it on purpose after the release has been out for a while. Extensions installed from a `.vsix` file have auto-update off by default. 4. **Install from the publisher's primary registry.** Check the publisher ID and verification badge, and use the publisher's own install link when one exists. 5. **Do not run the editor as administrator or root.** In this incident, the lack of admin rights was one reason the SSH server usually failed to start. 6. **Keep secrets out of global environment variables.** Prefer credential helpers, OS keychains, and short-lived tokens scoped to a project. 7. **Isolate agents and unfamiliar repositories.** Use a VM or dev container for agent runs and untrusted code. A container is only a boundary if it does not mount your home directory or the Docker socket. ## Harden a team setup * **Allowlist extensions.** In VS Code, use `extensions.allowed` (1.96+) or the `AllowedExtensions` policy to allow by publisher, extension ID, exact version, or platform. `"stable"` blocks pre-release versions. Once you add allow rules, extensions that do not match any of them are blocked. ```jsonc theme={"theme":{"light":"github-light","dark":"github-dark"}} { "extensions.allowed": { "microsoft": true, "esbenp.prettier-vscode": true, "rust-lang.rust-analyzer": "stable", "dbaeumer.vscode-eslint": ["3.0.0"] } } ``` For local `.vsix` files, these rules check identifiers declared inside the package. They do not verify where the package came from. * **Manage update timing centrally.** VS Code exposes `extensions.autoUpdate` and `extensions.autoUpdateDelay` as enterprise policies. In Cursor, team admins can set **Marketplace Install Cooldown (hours)** under **Team settings** → **Security & automation**. It defaults to `0` (disabled) and, when set, overrides each user's `extensions.installCooldownHours`. * **Require signatures where the editor supports it.** Cursor Enterprise can require valid Open VSX signatures (**Require Extension Signature Verification**). The Visual Studio Marketplace signs every extension, and VS Code checks the signature at install time. * **Host a private marketplace** when you need an approved, rehosted set of extensions, including for air-gapped networks. * **Alert on behavior, not just hashes.** Useful signals from this incident: * an editor helper process (`Code Helper`, `Cursor Helper`, and similar) writing `~/.ssh/authorized_keys` * a non-Apple process creating a `com.apple.*` LaunchAgent, or a LaunchAgent that runs `/bin/sh` on a hidden script * `ssh` or `autossh` started with `-R` from a user session * local SSH logins from `127.0.0.1` or `::1` ## When an extension you use is reported malicious 1. **Confirm channel, version, and platform.** Find out which marketplace delivered your copy. Check the installed versions: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} code --list-extensions --show-versions ls ~/.vscode/extensions ~/.cursor/extensions 2>/dev/null ``` 2. **Check the vendor's indicators** before deleting anything. Preserve evidence, and isolate the machine if you find signs that the payload ran. 3. **Look outside the extension folder** for SSH keys, startup entries, and running processes: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} cat ~/.ssh/authorized_keys # look for keys you did not add ls ~/Library/LaunchAgents # macOS crontab -l # Linux ps aux | grep -E 'ssh .*-R|autossh' # active reverse tunnels ``` On Windows, check `%USERPROFILE%\.ssh\authorized_keys`, `C:\ProgramData\ssh\administrators_authorized_keys`, scheduled tasks, and the Startup folder. 4. **Remove persistence, unauthorized keys, and tunnel processes.** Then decide whether to rebuild the machine. Review vendor remediation scripts before you run them. 5. **Rotate credentials and revoke sessions from a different, trusted device.** Do this for anything the affected user account could reach. 6. **Do not treat an extension update or a server takedown as cleanup.** Confirm that the artifacts do not return after you log in again or restart. ## References * [Folo source: 2026-10-31 Hacker News Top Stories (SuperTechFans)](https://supertechfans.com/cn/post/2026-10-31-HackerNews/) * [Folo source: Solidot, Claude Code for VS Code extension backdoor](https://www.solidot.org/story?sid=85756) * [Cursor: Security notice for Anthropic.claude-code 2.1.312 and 2.1.313](https://cursor.com/blog/claude-code-extension-security-notice) * [Phorion: Official Claude Code extension compromise advisory](https://phorion.io/blog/offical-claude-code-vsx-compromise/) * [Microsoft Security: Inside a malicious Claude Code-branded extension](https://www.microsoft.com/en-us/security/blog/2026/10/30/inside-malicious-claude-code-branded-cursor-extension-persistent-ssh-backdoor/) * [Socket: Registry records for Claude Code 2.1.313](https://www.socket.dev/blog/claude-code-extension-compromise) * [Hacker News: Anthropic clarification on affected channels](https://news.ycombinator.com/item?id=50304129) * [VS Code docs: Extension runtime security](https://code.visualstudio.com/docs/configure/extensions/extension-runtime-security) * [VS Code docs: Extension auto-update](https://code.visualstudio.com/docs/configure/extensions/extension-marketplace#_extension-auto-update) * [VS Code docs: Manage extensions in enterprise environments](https://code.visualstudio.com/docs/enterprise/extensions) * [microsoft/vscode #321039: configurable `extensions.autoUpdateDelay`](https://github.com/microsoft/vscode/pull/321039) * [Cursor docs: Extensions, install cooldown, and signature verification](https://cursor.com/help/customization/extensions) * [Claude Code docs: Plugin security and trust](https://code.claude.com/docs/en/plugins/security) # Exam Records Source: https://base.bangwu.me/env/exam Company aptitude test and coding exam reviews with lessons learned, covering algorithm problems, aptitude sections, and practical test-taking tips. ## 2025-03-08 Meituan General Aptitude Test 【Project Management Intern】 ![bangwu20250308194953](https://cdn.bangwu.top/img/202503082350366.webp) The general aptitude test was roughly divided into four parts: language expression, mathematics, logical reasoning, and data analysis. The written test itself was not too difficult. Since it was for a non-technical role, there were no algorithm problems. The online testing platform felt intimidating at first, though. > Lessons Learned 1. Bring scratch paper for the math section—there was too much mental arithmetic this time. 2. Be very clear about what “year-over-year growth” means. 3. The formal process may require camera access, screen recording, phone mini-program monitoring, and an integrity pledge. ## 2025-03-09 Pinduoduo Algorithm Exam 【Server R\&D Intern】 ![bangwu20250309112526](https://cdn.bangwu.top/img/202503091125153.webp) This was my first algorithm test. I was not well prepared, my algorithm basics were weak, and I only solved the first easy problem out of four. It made me realize how many edge cases algorithm problems can involve. > Lessons Learned 1. Bring a phone stand to film your upper body and screen if required. 2. It is much easier to switch to a local IDE for answering and debugging. 3. I need much more practice with ACM-style algorithm problems. ## 2025-03-09 Tencent Comprehensive Assessment 【Project Management Intern】 ![bangwu20250309174057](https://cdn.bangwu.top/img/202503091741562.webp) The questions focused on workplace decisions and project-conflict scenarios. It felt more like a personality assessment, and there probably were no standard answers. > Lessons Learned None. ## 2024-04-23 Huawei Algorithm Exam 【General Software Development】 ![huawei end](https://cdn.bangwu.top/img/168whx-48bangwu20250423194113.webp) The algorithm questions were quite hard. The first was about finding the minimum `k` numbers, the second was a binary-tree variant, and the third was a shortest-path problem. All of them were beyond me at the time, so I submitted early. > Lessons Learned None. I was in a poor mood recently and not very motivated for exams. # Git at agent scale Source: https://base.bangwu.me/env/git-at-scale How Git stores and transfers history with objects, refs, and packfiles, why many concurrent agents strain a Git server, the trade-offs behind OpenAI's Pando backend, and what you can do on the client side today. # Git at agent scale Coding agents multiply Git traffic. One engineer can have several changes in CI at once, every push can start several jobs that fetch the same commit, and every agent sandbox needs a checkout. In late 2025, OpenAI's monorepo servers started falling behind: fetches and pushes slowed down, merges failed, and reliability at times dropped below 90%. OpenAI's answer was **Pando**, a new Git-compatible backend. This page uses that design to explain how Git moves data and where a Git server becomes the bottleneck. It ends with what you can do on the client side without building your own backend. ## How Git stores history A repository keeps two things in sync: **objects** and **refs**. * **Objects** are content-addressed and immutable. A **blob** holds one file's content, a **tree** maps names to blobs and other trees, a **commit** points to a root tree and its parent commits, and a **tag** names an object. Changing one file creates a new blob and new trees up to the root. Unchanged files and directories reuse existing objects. * **Refs** are names that point to commits, such as `refs/heads/main`. A commit on a branch creates a new commit object and moves the ref. * Objects are stored **loose** (one file each) or in a **packfile**, where similar objects can be stored as deltas of each other. You can see each layer locally: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git cat-file -p HEAD # commit: tree, parents, author git cat-file -p 'HEAD^{tree}' # tree: names -> blob/tree IDs git count-objects -v # loose vs packed objects git ls-remote origin | wc -l # how many refs the server advertises ``` ## How fetch and push move data * **Fetch.** The client says which commits it **wants** and which it already **has**. The server walks everything reachable from the wanted commits, removes what the client already has, and sends the rest as a packfile. A full clone has nothing, so it receives everything reachable. * **Push.** The server advertises its refs. The client leaves out objects the server already has and sends a pack that **depends on** existing server objects, so the pack alone isn't enough to rebuild the history. * **Ref updates race.** Two pushes may try to move the same branch from the same old commit to different new ones. The server must accept one and reject the other. That gives a Git server two kinds of load: **many writers** pushing to different branches, and **many readers** fetching the same history. Agents increase both at once. ## Three ways to scale a Git server | Design | How writes are ordered | Where it struggles | | - | - | - | | **Replicas with three-phase commit** | Each push is copied to every replica, and a majority must agree on each ref update | Replica disks and network round trips sit on every push; writes slow down under load | | **Shared write-ahead log in blob storage** | Packs upload in parallel, but every ref update appends to one manifest with compare-and-swap | All pushes compete for the same manifest; replicas must read and index new packs before they can serve them, so readers wait | | **Pando: per-ref ordering** | Each branch is updated independently; packs are stored once and reused | Gives up a consistent point-in-time view of all refs | Both conventional designs keep a **repository-wide order** of writes. That is what makes pushes to unrelated branches wait on each other. ## What Pando changed Pando keeps the Git protocol and the Git client, so engineers and agents didn't change how they work. It relaxes two assumptions most Git servers make: 1. **No repository-wide snapshot.** Pando uses **causal consistency** per ref. A reader fetching a branch gets the history it needs for that revision, but a reader looking at several branches may see them at different moments. In practice, users and agents depend on the order of updates to one branch, not on a global order. 2. **No unique pack per client.** Generating a custom pack for every fetch costs CPU and disk. Pando serves stored packs again, even if a client downloads a few objects it already has. How a push and a fetch work: * **Push.** Pando streams the incoming pack to blob storage and validates it in one pass, without unpacking it into a local repository. A multi-key transaction then records a **ref version** (new tip, the pack that supplied it, earlier versions it depends on) and moves the ref pointer, so the pusher can immediately read its own write. This takes a constant number of metadata operations. * **Fetch.** Pando picks the stored packs the client needs based on what it already has, with metadata reads that grow with the logarithm of the distance between the two versions. It returns pack URLs, and the client downloads them from regional caches. * **Advertise only trunk.** On a push to a new branch, Pando advertises just the trunk branch instead of every ref. With millions of branches, a full ref advertisement alone can exceed 100 MiB. Advertising only trunk also makes the pushed pack reusable: any reader that has trunk can fetch the branch with that one pack. The cost is that repeated pushes to the same branch, or stacked branches, resend objects outside trunk. In OpenAI's monorepo, the median pack was still under 20 KiB and the 99th percentile under 3 MiB. Because servers mostly negotiate and pick packs, they run on commodity hardware, and capacity grows by adding servers and scaling the metadata and blob stores. OpenAI reports that median push latency dropped by nearly 5× and that Pando serves close to a petabyte of Git data per day. > [!NOTE] > > Pando is internal to OpenAI. The public repository is OpenAI's build of the Git client, not the backend. The numbers come from OpenAI's post, with no published baseline or hardware details. ## Durable lessons * **Decide which consistency you really need.** A global snapshot of all refs is expensive, and most workflows only rely on ordering within one branch. * **Measure push-to-fetch latency:** the time from one agent's push until another agent or a CI job can fetch that commit. That is the number agent collaboration waits on. * **Make reads cacheable.** Serving the same bytes to many readers beats computing an optimal response for each one. * **Keep the protocol, replace the backend.** Staying Git-compatible meant no migration for people, agents, or tools. ## What you can do today Most teams will hit client-side limits long before they need a new server. Reduce what each agent and CI job downloads: * **Blobless partial clone.** `git clone --filter=blob:none ` downloads commits and trees, and fetches file contents only when a checkout needs them. * **Sparse checkout.** `git sparse-checkout set ...` keeps only the directories an agent needs in its working tree. * **Scalar.** `scalar clone ` sets up a large-repository profile in one step: it clones only commits and trees, enables sparse checkout, registers background maintenance, and applies recommended config. Run `scalar register` on an existing clone. * **Shared object store for parallel agents.** Give each agent a [Git worktree](/env/git-worktree) instead of a separate clone, so objects are fetched once. * **Shallow CI checkouts.** Keep `actions/checkout`'s default `fetch-depth: 1` unless a job needs history; see [GitHub Actions](/env/github-workflow). ## References * [Folo source: OpenAI News, Scaling Git at OpenAI](https://openai.com/index/scaling-git-at-openai) * [The New Stack: OpenAI built itself a new Git backend, too](https://thenewstack.io/openai-pando-git-backend/) * [Git docs: partial clone](https://git-scm.com/docs/partial-clone) * [Git docs: git-sparse-checkout](https://git-scm.com/docs/git-sparse-checkout) * [Git docs: scalar](https://git-scm.com/docs/scalar) * [Pro Git: Git internals, Git objects](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects) * [Pro Git: Transfer protocols](https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols) # Git worktree Source: https://base.bangwu.me/env/git-worktree Use git worktree to check out multiple branches from one repository simultaneously for parallel feature work and multi-agent coding. # Git worktree `git worktree` lets one repository expose **multiple working directories at the same time**. Instead of cloning the same repo again and again, you can keep one shared repository object store and open several branches in parallel. This is especially useful when: * you are fixing one bug while another feature is in progress * you want a clean review branch without stashing current work * multiple AI agents need isolated working directories * you want to compare branches side by side ## Why use it instead of another clone The main benefits are: * faster than recloning * less disk usage than multiple full clones * one shared repository history and object database * each worktree still gets its own `HEAD`, index, and working directory In practice, it feels like “multiple checkouts from one repo”. ## The basic commands ### Create a new worktree from an existing branch ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree add ../docs-fix docs-fix ``` This creates a sibling directory `../docs-fix` and checks out branch `docs-fix` there. ### Create a new worktree and new branch in one step ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree add -b feature/browser-harness ../browser-harness ``` This is the most common pattern for new work. ### List all worktrees ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree list ``` ### Remove a worktree ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree remove ../browser-harness ``` ### Clean stale metadata ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree prune ``` Use `prune` when a worktree directory was deleted manually and Git still remembers it. ## A practical workflow Imagine your main repository is in `~/code/project`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} cd ~/code/project git switch main git pull git worktree add -b feature/a ../project-feature-a git worktree add -b fix/login-bug ../project-login-fix ``` Now you can: * keep normal work in `project` * do feature work in `project-feature-a` * isolate a production fix in `project-login-fix` This is a much cleaner workflow than repeatedly stashing, rebasing, and switching branches in one directory. ## Why it is useful for AI agents For multi-agent coding, `git worktree` is often the simplest safe default. Each agent can get: * its own directory * its own checked-out branch * its own build artifacts and temp files * much lower risk of stomping on another agent’s uncommitted changes That makes worktree-based coordination much easier than sharing one checkout. ### A simple pattern ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree add -b agent/docs ../project-agent-docs git worktree add -b agent/tests ../project-agent-tests git worktree add -b agent/refactor ../project-agent-refactor ``` Then assign one worktree per task or per agent. ## Important rules ### 1. Do not check out the same branch in two worktrees Git prevents most of this automatically, but the principle matters: * one branch * one active worktree If two places both try to advance the same branch, you lose the isolation benefit. ### 2. Remove worktrees with Git when possible Prefer: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree remove ../project-agent-docs ``` instead of deleting the folder directly. If you do delete it manually, follow up with: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git worktree prune ``` ### 3. Use worktree-specific config when needed By default, the main `.git/config` is shared across worktrees. If you need config that should exist only in one worktree, enable: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git config extensions.worktreeConfig true ``` Then set per-worktree values with: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} git config --worktree core.sparseCheckout true ``` This is useful when different worktrees need different sparse-checkout or local behavior. ## What is shared and what is separate ### Shared * repository objects * most refs * normal repository history * main config by default ### Separate per worktree * `HEAD` * index * working directory contents * some per-worktree refs and pseudorefs * optional `config.worktree` That split is the reason worktrees are both lightweight and practical. ## Good use cases * parallel feature development * hotfix branch alongside a bigger refactor * multi-agent implementation lanes * trying risky changes without disturbing the current checkout * large repos where full reclones are wasteful ## When a full clone is still better Use a separate clone instead if you need: * a fully separate Git config and credential context * different remotes or fork wiring * total isolation for experiments * to work across very different repository states independently Worktrees are excellent for **same-repo parallelism**, not for every kind of isolation. ## Small but relevant Git 2.54 note Today’s Git ecosystem update also included **Git 2.54**, which added a new experimental `git history` command for simpler history edits and made geometric repacking the default manual maintenance strategy. That is useful context, but for day-to-day parallel work, `git worktree` is still the more immediately practical feature to master. ## References * [Git documentation: git-worktree](https://git-scm.com/docs/git-worktree) * [GitHub Blog: Highlights from Git 2.54](https://github.blog/open-source/git/highlights-from-git-2-54/) # GitHub Actions Source: https://base.bangwu.me/env/github-workflow GitHub Actions CI/CD automation using YAML workflow files, covering structure, event triggers like push and pull_request, and deployment setups. # GitHub Actions GitHub Actions is GitHub’s CI/CD automation tool. It can automatically run workflows for building, testing, deployment, and more. Public repositories are free to use, while private repositories come with a monthly free quota. ## Basic Concepts * **Workflow**: an automated process made up of one or more jobs * **Job(Task)**:a set of steps executed on the same runner * **Step**: a single task, which can be either an action or a shell command * **Action(Action)**:reusable smallest unit * **Runner**: the server that executes the workflow ## Basic Syntax Workflow configuration files use YAML and live in the `.github/workflows/` directory. ### Simplest workflow ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} name: Hello World on: [push] jobs: built: runs-on: ubuntu-latest steps: - name: Say hello run: echo "Hello, World!" ``` ### Complete example ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} name: CI # 触发条件 on: push: branches: [ main, dev ] pull_request: branches: [ main ] schedule: - cron: '0 0 * * 0' # 每周日午夜 workflow_dispatch: # 手动触发 # Environment Variables env: NODE_VERSION: 18 jobs: test: name: Test runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} - name: Install dependencies run: npm install - name: Run tests run: npm test ``` ## Trigger events ### Push Event ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} on: push: branches: - main - 'releases/**' paths: - '**.js' - '!docs/**' tags: - v1.* ``` ### Pull Request Event ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} on: pull_request: types: [opened, synchronize, reopened] branches: [ main ] ``` ### Scheduled tasks ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} on: schedule: - cron: '30 5 * * 1-5' # 工作日早上5:30 ``` ### Manual trigger ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} on: workflow_dispatch: inputs: environment: description: 'Environment to deploy' required: true default: 'staging' type: choice options: - staging - production ``` ## Common actions ### Checkout code ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - uses: actions/checkout@v4 with: fetch-depth: 0 # 获取完整History ``` ### Set up Node.js ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - uses: actions/setup-node@v4 with: node-version: '18' cache: 'npm' ``` ### Set up Python ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - uses: actions/setup-python@v4 with: python-version: '3.11' cache: 'pip' ``` ### CachingDependency ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - uses: actions/cache@v3 with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- ``` ### Upload build artifacts ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - uses: actions/upload-artifact@v3 with: name: built-files path: dist/ ``` ### Download build artifacts ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - uses: actions/download-artifact@v3 with: name: built-files path: dist/ ``` ## Automatically publish a release ### Create a release ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} name: Release on: push: tags: - 'v*' jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build run: | npm install npm run built - name: Create Release uses: softprops/action-gh-release@v1 with: files: dist/* body: | ## Changes - Feature 1 - Feature 2 draft: false prerelease: false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` ### automatically generates Release Notes ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} - name: Create Release uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.ref }} release_name: Release ${{ github.ref }} generate_release_notes: true ``` ## Self-hosted Runner Self-hosted runners let you run workflows on your own servers. ### Add a runner 1. Go to **Repository Settings → Actions → Runners → New self-hosted runner**. 2. Follow the prompts to install and configure it on your server. 3. Start the runner. ### Installation(Linux) ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 创建目录 mkdir actions-runner && cd actions-runner # Download curl -o actions-runner-linux-x64-2.311.0.tar.gz -L \ https://github.com/actions/runner/releases/download/v2.311.0/actions-runner-linux-x64-2.311.0.tar.gz # 解压 tar xzf ./actions-runner-linux-x64-2.311.0.tar.gz # Configuration ./config.sh --url https://github.com/user/repo --token YOUR_TOKEN # Run ./run.sh # 作为服务Run sudo ./svc.sh install sudo ./svc.sh start ``` ### Use a self-hosted runner ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} jobs: built: runs-on: self-hosted steps: - uses: actions/checkout@v4 - run: ./build.sh ``` ### Label selection ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} jobs: built: runs-on: [self-hosted, linux, x64] ``` ## Secrets management ### Add a secret Settings → Secrets and variables → Actions → New repository secret ### Use a secret ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} steps: - name: Deploy env: API_KEY: ${{ secrets.API_KEY }} run: ./deploy.sh ``` ## Matrix builds ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] node: [16, 18, 20] steps: - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node }} - run: npm test ``` ## Conditional execution ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} steps: - name: Only on main if: github.ref == 'refs/heads/main' run: echo "Main branch" - name: Only on success if: success() run: echo "Previous steps succeeded" - name: Always run if: always() run: echo "Cleanup" ``` ## Practical examples ### Automatically deploy to a server ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} name: Deploy on: push: branches: [ main ] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Deploy to server uses: appleboy/ssh-action@master with: host: ${{ secrets.SERVER_HOST }} username: ${{ secrets.SERVER_USER }} key: ${{ secrets.SSH_PRIVATE_KEY }} script: | cd /var/www/myapp git pull npm install pm2 restart myapp ``` ### Build and push Docker images ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} name: Docker Build on: push: branches: [ main ] jobs: built: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Login to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push uses: docker/build-push-action@v5 with: context: . push: true tags: user/app:latest ``` ### Code checks ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} name: Lint on: [push, pull_request] jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 18 - run: npm install - run: npm run lint ``` ## Speed up CI without dropping checks Coding agents write code faster than CI can verify it, so CI wait time becomes the bottleneck. The goal is to cut wait time without removing any check that protects a release. Work through these steps in order, and measure after each one. The list also works as a prompt for a coding agent: have it measure first, apply the steps, and report before-and-after numbers. ### 1. Measure where the time goes Split each job into three parts: **queued** (waiting for a runner), **setup** (checkout, toolchains, dependencies), and **work** (build and tests). Slow CI is often slow setup, not slow tests. ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Last 50 runs of one workflow: job, created, started, completed gh run list --workflow ci.yml --limit 50 --json databaseId --jq '.[].databaseId' | while read -r id; do gh api "repos/{owner}/{repo}/actions/runs/$id/jobs" \ --jq '.jobs[] | [.name, .created_at, .started_at, .completed_at] | @tsv' done ``` `started_at` minus `created_at` is queue time. Each job's `steps` array has its own timestamps, so you can split setup from work the same way. ### 2. Cancel superseded PR runs, but never `main` ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} concurrency: group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} cancel-in-progress: true ``` `github.head_ref` is only set for pull request events, so new pushes to the same PR share a group and cancel the older run. Pushes to `main` fall back to the unique `run_id`, so every commit on `main` still gets a full run. A group such as `${{ github.ref }}` would also cancel or replace queued `main` runs. ### 3. Skip docs-only changes without blocking merges If a workflow is skipped by `paths`, `paths-ignore`, or branch filters, its required checks stay **Pending** and the PR cannot merge. A job skipped by an `if:` condition reports success. For required checks, let the workflow start and skip jobs instead: ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}} jobs: changes: runs-on: ubuntu-latest outputs: code: ${{ steps.filter.outputs.code }} steps: - uses: actions/checkout@v4 - uses: dorny/paths-filter@v3 id: filter with: filters: | code: - 'src/**' - 'tests/**' - 'package*.json' - '.github/workflows/**' test: needs: changes if: needs.changes.outputs.code == 'true' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: npm ci && npm test ``` ### 4. Use the cache built into setup actions * `actions/setup-node` caches when you set `cache: npm` (or `yarn`, `pnpm`). * `actions/setup-go` caches by default. * For Rust, use `Swatinem/rust-cache`. Cache storage is 10 GB per repository by default. Entries not used for 7 days are deleted, and when the repository is full, the least recently used entries are evicted, which can cause thrashing. Don't cache what you won't restore. Caches created by a `pull_request` run are scoped to that PR's merge ref, so other PRs can't reuse them. Run CI on `push` to `main` so PRs can restore a warm cache from the default branch. ### 5. Make a second build nearly free Build twice locally. The second build should take almost no time. If it doesn't, something is defeating the cache. Common causes are a Dockerfile that copies the whole repository before installing dependencies, or a build script that watches a file that doesn't exist, so the target always looks stale. ```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}} COPY package.json package-lock.json ./ RUN npm ci COPY . . ``` ### 6. Download tools instead of compiling them `go install` and `cargo install` compile from source on every run. Download release binaries instead, or use an installer that fetches prebuilt binaries, such as `cargo binstall` or `taiki-e/install-action` for Rust tools. ### 7. Run independent jobs in parallel Remove `needs:` entries that don't pass outputs or artifacts. Split the longest test suite across several machines with a matrix. ### 8. Save macOS runners for work that needs macOS On the Free, Pro, and Team plans, standard GitHub-hosted runners allow at most 5 concurrent macOS jobs, shared by all your workflows. Move formatting, lint, and dependency audits that don't depend on the OS to `ubuntu-latest`. ### 9. Don't do the same work twice Don't rerun a check that another job already ran. A frontend-only job doesn't need to restore the Rust cache. ### 10. Compare before and after Push the changes, rerun the measurement from step 1, and compare the same jobs. Look for the next slowest phase and repeat. ## Best Practices 1. **Use caching** to speed up dependency installation. 2. **Use matrix builds** for multi-environment testing. 3. **Run jobs in parallel** when they are independent. 4. **Use `if` wisely** to save resources with conditional execution. 5. **Protect secrets** and never print them in logs. 6. **Prefer official actions** because they are more reliable and better maintained. 7. **Limit permissions** and grant only what each workflow needs. 8. **Have a CI fallback plan** — GitHub Actions outages happen regularly; consider self-hosted runners or a secondary CI platform. ## Platform Reliability Risk GitHub Actions has experienced frequent outages in 2025–2026. Mitchell Hashimoto (creator of Vagrant and Terraform, GitHub user #1299 since 2008) announced in April 2026 that his open-source project **Ghostty** is leaving GitHub, primarily because of persistent CI/CD reliability issues: > "I started marking each day with an X if GitHub outages affected my work. Nearly every day had an X." > [!NOTE] > > When your CI/CD platform has regular outages that block you for hours, it becomes a productivity risk — not just an inconvenience. For serious projects, consider: > > * **Self-hosted runners** as a fallback (see the Self-hosted Runner section above) > * **Alternative CI platforms** (CircleCI, Buildkite, Gitea Actions) > * **Mirror your repo** to another platform so you can switch CI quickly > * **Don't couple your entire workflow** to one platform's availability ### Mitigation Strategies 1. **Self-hosted runners** — Run workflows on your own infrastructure; unaffected by GitHub outages 2. **Multi-platform CI** — Mirror critical workflows to an alternative (CircleCI, Buildkite) 3. **Local testing first** — Run lint/typecheck/test locally before pushing; CI should be a gate, not a bottleneck 4. **Cache aggressively** — Reduce job duration so outages cause less blocked time 5. **Read-only GitHub mirror** — Keep your source on GitHub for discoverability, but host CI elsewhere ## References * [GitHub Actions Official Docs](https://docs.github.com/actions) * [Folo source: Tw93 on speeding up GitHub Actions CI](https://x.com/HiTw93/status/2116797957454401746) * [GitHub Docs: Control the concurrency of workflows and jobs](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/control-the-concurrency-of-workflows-and-jobs) * [GitHub Docs: Troubleshooting required status checks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/troubleshooting-required-status-checks) * [GitHub Docs: Dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching) * [GitHub Docs: Actions limits](https://docs.github.com/en/actions/reference/limits) * [actions/setup-go: caching](https://github.com/actions/setup-go#caching-dependency-files-and-build-outputs) * [Actions Marketplace](https://github.com/marketplace?type=actions) * [Workflowsyntax](https://docs.github.com/actions/reference/workflow-syntax-for-github-actions) # Image Hosting Source: https://base.bangwu.me/env/imgbed Image hosting setup using Qiniu cloud storage with CDN acceleration, covering bucket config, custom domain binding, PicGo upload, and WebP. I eventually settled on an **object storage + CDN** image hosting setup. Right now I mainly use Qiniu object storage with CDN acceleration. The goal is not to be flashy—the point is to keep image management, access speed, and cost under control. ## Who this setup is for * Anyone running a blog or knowledge base and needing long-term image hosting * Anyone who wants to manage screenshots, cover images, and article illustrations in one place * Anyone who wants relatively stable image URLs that are easy to reference over time ## My basic approach 1. **Storage layer**: object storage keeps the original images. 2. **Delivery layer**: CDN handles acceleration and HTTPS. 3. **Upload tools**: upload directly from local tools such as screenshot apps or image uploaders. 4. **Compression strategy**: treat screenshots and custom graphics differently to keep file sizes down. ## Related tools 1. [PicGo](https://picgo.github.io/PicGo-Doc/) 2. [ShareX](/apps/ShareX) 3. [CDN Configuration](/env/CDN) ## Practical tips * Standardize naming and directory structure before doing large-scale uploads. * Compress images before uploading whenever possible to save bandwidth and storage. * Pay close attention to hotlink protection, traffic alerts, and billing thresholds. # Environment & Deployment Source: https://base.bangwu.me/env/index Environment setup and deployment tools hub covering Docker, Compose, Caddy, Supervisor, GitHub Actions, Jupyter, CDN, and blog hosting guides. When starting out with programming, you'll have many questions about environment configuration — what are environment variables? What is `pip`? With so many Linux distros, how do package managers work? This section addresses those questions, along with blog hosting and toolchain setup. > [card] [Docker](/env/docker) > > Containerized deployment and app management. > [card] [Docker Compose](/env/docker-compose) > > Multi-container orchestration and one-command deploy. > [card] [Caddy](/env/Caddy) > > Modern web server with automatic HTTPS. > [card] [Supervisor](/env/supervisor) > > Process daemon and background service management. > [card] [CDN Setup](/env/CDN) > > Domestic/overseas split CDN architecture. > [card] [Jupyter](/env/Jupyter) > > Interactive data analysis notebook. > [card] [GitHub Workflow](/env/github-workflow) > > GitHub Actions CI/CD automation. > [card] [npm supply chain](/env/npm-supply-chain) > > Review and lock down npm install scripts. > [card] [Editor extension supply chain](/env/editor-extension-security) > > Control extension updates and clean up malicious releases. > [card] [Browser Observability](/env/browser-observability) > > Debug browser automation with read-only CDP tracing. > [card] [Git worktree](/env/git-worktree) > > Parallel checkouts for multi-branch and multi-agent work. > [card] [Git at agent scale](/env/git-at-scale) > > How Git moves data, and how to scale it for many agents. > [card] [Markdown](/env/markdown) > > Markdown writing tips and tools. > [card] [Agent-ready docs](/env/agent-ready-docs) > > Make docs easier for AI agents to discover and read. > [card] [Agent harness](/env/agent-harness) > > Design the runtime layer around AI agents. > [card] [AI product evals](/env/ai-evals) > > Turn real failures into regression tests and calibrated judges. > [card] [AI code review](/env/ai-code-review) > > Review AI-written code with layers, risk tiers, and reviewer evals. > [card] [Claude Code patterns](/env/claude-code-patterns) > > Effective patterns for Claude Code Fable 5 and agent loops. > [card] [Local LLM](/env/local-llm) > > Run capable models locally with llama.cpp. > [card] [Beads](/env/beads) > > Structured task memory for coding agents. ## Blog Setup > [card] [Fuwari](/env/Fuwari) > > Astro-based blog theme. > [card] [Image Hosting](/env/imgbed) > > Qiniu OSS + DogeCloud CDN setup. # Interview & Job Application Source: https://base.bangwu.me/env/interview Technical interview reviews, job application strategies, and lessons learned — covering algorithm rounds, system design, resume tips, and career advice. # My interview experience ## 2025-03-11 ByteDance Test Development Intern I reviewed testing and development topics intensively before the interview. Total duration: 30 minutes. 1. They drilled into my data visualization project, especially the difficult parts. 2. They asked about database table design, such as classroom tables and student course-selection tables. 3. They gave me an SQL problem: find the top 20 students by course score. I could not write it because I had forgotten too much MySQL. 4. There was a logic puzzle: among 27 balls, one is fake and has a different weight. How would you use a balance scale to find it, and how many weighings would it take? I vaguely remembered a similar 8-ball problem, but I still could not work it out. 5. There was also an algorithm problem about merging two sorted arrays. I panicked and almost wanted to use `sort` + `set`, which reminded me that I still need much more algorithm practice. 6. After the algorithm question, another interviewer returned to the ball puzzle and asked how the solution would change if the fake ball were known to be heavier. I still could not come up with a good approach. 7. In the Q\&A round, I asked what languages and frameworks ByteDance test development usually uses, and whether they build internal testing platforms. The answer was that there is no mandatory language and the platform work depends on actual needs. The result was as bad as I expected. I answered poorly, and a one-hour interview ended after only 30 minutes. Still, it was my first interview, so it was a useful wake-up call. There is a lot to improve. ## 2025-04-17 Shanghai Yonyou Government Software Co. Implementation Consultant Intern This interview also lasted about 30 minutes, and the whole experience felt a bit unexpected. 1. I gave a short self-introduction and then they asked about my project. At that point I realized the meeting recording was not turned on. 2. They asked what I had learned from data mining, deep learning, and management-related courses. Most of my answer was basic concepts, and it felt like the interviewer was not very familiar with the subject either. 3. They asked about the visualization project and even asked me what Vue was. 4. They asked which Python libraries I knew. I mentioned libraries I had studied on my own, such as `httpx`, `selenium`, and other common tools. 5. They asked about modeling competitions and their real-world applications. I answered honestly that they mostly solve specific problems and are not always directly applied in production. 6. They asked about Office skills—Word, PowerPoint, Excel—which made the interview feel much less technical. 7. They also asked about my class schedule and how long I would be available for an internship, mentioning the graduation certificate requirement for full-time conversion. 8. In the Q\&A round, they asked how enterprise projects are typically implemented. I guessed they might be referring to project management rather than SQL. Overall, the interview felt strange. The interviewer gave me the impression of a very conservative programmer, almost like someone from a traditional state-owned enterprise environment. I also felt that my skill set did not match the role very well. My weak point was still SQL syntax, which I clearly need to review. On the positive side, I felt no pressure at all this time. Since it was my second interview, I was not nervous anymore. It almost felt like an HR screening round. ## Resume & Job Application Tips Lee Robinson (Cursor team) reviews hundreds of resumes daily. Here are 11 concrete tips to make your application stand out in seconds: ### Group 1: Keep it clean 1. **One page only** — If you need more space, link to a personal website. Don't stack 10+ bullet points per role. 2. **No photo** — Professional content stays professional. Photos belong on external profiles, not on the resume itself. 3. **GitHub must exist, but don't decorate it** — Badges, animations, and large images are noise. Reviewers want to see code and project reasoning. ### Group 2: Your online presence 4. **Build a personal website** — 90% of applicants don't have one. Having one instantly sets you apart. It needs to feel intentional, not just a template. 5. **Polish your LinkedIn** — Programmers love X/Twitter, but when companies circulate resumes internally, they look at LinkedIn. 6. **Clean up your X/Twitter** — If you link it, make sure there's nothing too unfiltered. Obvious advice, but many people fail this. ### Group 3: Content that matters 7. **Tailor, don't spam** — For startups, university courses matter less. For FAANG-style companies, coursework might help pass automated filters. Adjust your resume for the target. 8. **Mention AI usage** — Not using AI for coding is now unusual. Even outside Cursor, this is an industry trend. Show you work with AI tools naturally. 9. **Quality over quantity in projects** — 3 deep, thoughtful projects beat 27 AI-generated boilerplate projects. 10. **Write cover letters and resumes yourself** — AI-generated boilerplate is instantly recognizable. Especially when applying to AI companies, it's painfully obvious. Use AI for inspiration, but write the final version yourself. 11. **Show personal interests** — Books you like, articles you wrote, films you enjoy. Hiring is ultimately about finding someone people want to work with. These are great icebreakers. > [!TIP] > > The meta-lesson: reviewers spend seconds on each resume. Every element should either **establish competence** or **show you're a real person** — anything that does neither should be cut. > [!NOTE] > > * [Lee Robinson: How to make your engineering job application stand out](https://x.com/leerob/status/2053316807316156417) > * Chinese summary by [Twitter @dotey](https://x.com/dotey) # Local LLM deployment Source: https://base.bangwu.me/env/local-llm A practical guide to running capable LLMs locally with llama.cpp, covering Qwen 3.6 27B setup, performance benchmarks, and model comparison for offline, private AI development. # Local LLM deployment Running a capable large language model on your own machine is no longer a research project. With open-weight models like Qwen 3.6 27B, you get mid-2025 frontier-level intelligence on a laptop or desktop GPU — offline, private, and under your control. ## Why run models locally Cloud APIs are convenient, but they come with trade-offs: * **No take-backs**: A cloud model can be deprecated, rate-limited, or taken down overnight — as Claude Fable 5 users learned in June 2026. * **Privacy**: Sensitive code, medical data, or personal notes never leave your machine. * **Cost at scale**: API credits are cheap now due to heavy subsidies. When the subsidy era ends, local models become the economical default for frequent use. * **Customization**: You can fine-tune a local model for your domain, coding style, or project conventions. ## The current sweet spot: Qwen 3.6 27B As of mid-2026, Qwen 3.6 27B is widely considered the first local model that delivers genuine general intelligence suitable for daily development work. It comes in two variants: | Variant | Architecture | Speed | Quality | | - | - | - | - | | Qwen 3.6 35B A3B | Mixture-of-Experts | \~105 tok/s (Mac M5) | Good | | Qwen 3.6 27B | Dense | \~32 tok/s (Mac M5) | Better | The dense 27B is recommended for quality-sensitive work. The MoE variant is 3× faster and still very capable, suitable for quick iterations. ### Intelligence level On the Artificial Analysis index, Qwen 3.6 27B scores around mid-2025 frontier level: | Model | Approximate Era | Equivalent | | - | - | - | | Gemma 4 31B | Late 2024 | o1 / Claude 3.5 Sonnet | | Qwen 3.6 35B A3B | Early 2025 | o3 / Claude 4 Sonnet | | **Qwen 3.6 27B** | **Mid 2025** | **GPT-5 / Claude Sonnet 4.5** | | DeepSeek V4 Flash | Late 2025 | GPT-5.2 / Claude Opus 4.5 | It significantly outperforms Gemma 4 31B (the previous local coding default) and approaches DeepSeek V4 Flash quality. ## Setup with llama.cpp [llama.cpp](https://github.com/ggml-org/llama.cpp) is recommended over Ollama — it is direct, open, and gives you full control over quantization and inference parameters. ### 1. Download a quantized model 8-bit quantization halves model size with negligible quality loss. Popular GGUF sources: * [unsloth/Qwen3.6-27B-MTP-GGUF](https://huggingface.co/unsloth/Qwen3.6-27B-MTP-GGUF) (with multi-token prediction support) * [bartowski/Qwen\_Qwen3.6-27B-GGUF](https://huggingface.co/bartowski/Qwen_Qwen3.6-27B-GGUF) ### 2. Start the server ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} llama-server -hf unsloth/Qwen3.6-27B-MTP-GGUF:Q8_0 \ --spec-type draft-mtp -ngl 999 -fa on -c 65536 --port 8080 ``` Flags explained: * `-hf` — pull from Hugging Face (cached on subsequent runs) * `--spec-type draft-mtp` — multi-token prediction for \~1.8× speedup * `-ngl 999` — offload all layers to GPU * `-fa on` — flash attention * `-c 65536` — 64K context window (native is 256K) Open `http://127.0.0.1:8080` to chat directly. ### 3. Connect your coding agent For OpenCode, add to `~/.config/opencode/opencode.jsonc`: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "provider": { "llama": { "name": "llama.cpp (local)", "npm": "@ai-sdk/openai-compatible", "options": { "baseURL": "http://127.0.0.1:8080/v1", "apiKey": "local" }, "models": { "qwen3.6-27b": { "name": "Qwen3.6-27B Q8 +MTP" } } } }, "model": "llama/qwen3.6-27b" } ``` The same server works with Pi, Hermes, Claude Code (via custom base URL), and any OpenAI-compatible client. ## Performance reference Measured on MacBook Max M5 128 GB with 8-bit quantization: | Model | Engine | Tok/s | RAM | | - | - | - | - | | Qwen 3.6 35B A3B | llama.cpp + MTP | 105 | 45 GB | | Qwen 3.6 27B | llama.cpp + MTP | 32 | 42 GB | | Qwen 3.6 27B | llama.cpp (no MTP) | 18 | 41 GB | | DeepSeek V4 Flash (Q2-Q4) | llama.cpp | 33 | 103 GB | On consumer GPUs: * **RTX 5090 32 GB**: Q6\_K quantization, \~50 tok/s at 123K context, \~28 GB VRAM * **32 GB shared memory devices**: 4-bit quantization fits comfortably For laptops, a Mac Mini M4 on the local network is a quieter, cheaper alternative to running models directly on a MacBook Pro (which gets hot and loud under sustained inference). ## When to use local vs. cloud | Scenario | Recommendation | | - | - | | Sensitive or proprietary code | Local | | Offline or air-gapped work | Local | | High-volume batch processing | Local (no API costs) | | Need absolute frontier intelligence | Cloud (Opus, GPT-5.5) | | Quick one-off queries | Cloud (convenience) | | Long-context projects (>128K) | Cloud (or aggressive quantization) | ## Model evaluation: benchmarks vs. real experience A recurring pattern in open-weight model releases is the gap between benchmark scores and practical experience. Two data points from July 2026 make this impossible to ignore: **Tencent Hy3** (295B total / 21B active MoE) explicitly noted in its model card: > 模型的实用体验不完全与榜单成绩挂钩。基于广泛的用户反馈和分析,我们定位并优化了一系列体验向能力,获得了产品侧一致且积极的评价。 ("The model's practical experience does not fully correlate with benchmark rankings.") **Anthropic Opus 5 vs Fable 5**: Opus 5 beats Fable 5 on nearly every benchmark, yet anyone who has used both meaningfully can tell within minutes that Opus 5 is nowhere near Fable in practical coding and agent tasks. As one observer put it: "this can only mean our benchmarks are now almost completely useless." The benchmarks are failing because they measure narrow task completion under clean conditions, while real-world usefulness involves dimensions they don't capture: instruction following consistency across long contexts, refusal calibration, output formatting reliability, tool use judgment, and the ability to recover from mid-task errors. When evaluating any model for daily use, test it on your actual workflows rather than relying solely on leaderboard scores. ## Model architecture frontiers: diffusion language models The dominant LLM architecture is autoregressive — generate tokens left to right, commit to each one, never go back. This creates a fundamental problem for agent workflows: when a tool call produces an error 50 tokens ago, the model can't edit that part of the output. It must either start over or push forward with incorrect context. **Diffusion language models** take a different approach. Instead of generating sequentially, they refine the entire output in parallel passes. inclusionAI's **LLaDA2.2-flash** (July 2026) introduces the first diffusion model with explicit editing capability: * **DELETE** and **INSERT** control tokens let the model actively remove and add content during generation * The model can dynamically adjust sequence structure, enabling self-correction * This is particularly valuable for multi-turn tool calling and long-horizon agent interactions Current limitations: diffusion models still score significantly below similarly-sized autoregressive models on standard benchmarks. But the architectural advantage — the ability to edit mid-generation — addresses a limitation that no amount of scaling can fix in autoregressive models. This is early-stage research, not a replacement for autoregressive models. But the direction matters: as agent workflows grow longer and more complex, the ability to revise rather than restart will become essential. ## System One models: AI as a typed if-statement Not every in-process AI call needs a chat model. TypeSafe AI's **Jev** (September 2026) is a "System One" model: it gives up text generation and returns typed, calibrated decisions instead. Think of it as an intelligent `if` inside your code — classification, scoring, routing, extraction — with millisecond latency and a constrained output schema. Why this exists: RLHF made chat models good at pleasing humans, but less reliable as silent automation. Jev is trained with RLCD (Reinforcement Learning for Calibrated Decisions) for that narrower job. Claimed characteristics: * **70–500 ms** responses versus seconds-to-minutes for frontier chat models, because it samples outputs in parallel instead of token-by-token * **Cheap at volume**: about \$0.042 per million input tokens, free output tokens * **Zero type errors by construction** — the schema is part of the architecture, so it cannot emit unexpected prose Use a System One model when you need judgment without expression: ticket routing, bulk labeling, real-time scoring, or a guardrail after a chat model. Keep the chat model for writing, planning, and tool-using agents. The two are complementary, not competitors. Two harness patterns already use this split: * **Route, then think.** LangChain-style loops ask many tiny questions ("is this hard?", "is this dangerous?"). Answer those with a System One model; send only hard work to a frontier model. * **Choose, don't generate.** In computer use, let the driver enumerate legal actions and have Jev pick an ID. Cua's jev-use reported a 2048 demo about 5× faster and \~1000× cheaper than Astra — an ideal case with a fully observable keyboard task, not a guarantee for messy web UIs. The category is already commoditizing downward. Liquid AI open-sourced **d1-3B** and **d1-omni-600M** (October 2026): Jev-style decision models, but multimodal — text, vision, and audio in, typed decisions out. \~8 ms per query on an RTX 4090, under 50 ms on a Jetson Orin Nano. When the judgment layer reaches millisecond latency on edge hardware, "ask a small model first" stops being an optimization and becomes the default shape of an agent loop — with the frontier model reserved for what actually needs depth. ## Industry: Anthropic enters the chip race Anthropic has started early development of its own AI chips, seeking memory semiconductor supply from SK Hynix and reportedly in talks with Samsung for a custom project potentially using Samsung's 2nm process and advanced packaging. This follows OpenAI's earlier chip efforts and signals that frontier AI labs now see vertical integration into silicon as strategically necessary. ## What's next The gap is closing fast. GLM 5.2 already delivers frontier-level open-weight intelligence, and the trend toward separating reasoning from factual knowledge will make future models even more efficient on consumer hardware. ## References * [Qwen 3.6 27B is the sweet spot for local development](https://quesma.com/blog/qwen-36-is-awesome/) — setup guide, benchmarks, and real-world impressions * [Will it Mythos?](https://swelljoe.com/post/will-it-mythos/) — Qwen 3.6 benchmark comparison * [Simon Willison on Qwen 3.6 27B](https://simonwillison.net/2026/Apr/22/qwen36-27b/) * [Tencent Hy3 on HuggingFace](https://huggingface.co/tencent/Hy3) * [Opus 5 vs Fable 5: benchmarks are broken](https://x.com/oran_ge/status/2081501133168947412) * [LLaDA2.2-flash: diffusion model with editing](https://huggingface.co/inclusionAI/LLaDA2.2-flash) * [Anthropic developing own AI chips](https://readhub.cn/topic/8v2eHNj7g1m) * [TypeSafe AI: Jev System One model](https://typesafe.ai) — typed, calibrated decisions instead of chat generation * [LangChain + Jev harness](https://x.com/shao__meng/status/2100873142969536631) — 用 System One 做路由和护栏,旗舰模型只处理难活 * [Cua jev-use](https://x.com/shao__meng/status/2100870131324985740) — Computer Use 里让模型选择动作 ID,而不是生成动作 * [Liquid AI d1](https://huggingface.co/LiquidAI/d1-3B) — 开源多模态决策模型,RTX 4090 上 8ms,边缘硬件 50ms 以内 # Markdown Syntax Source: https://base.bangwu.me/env/markdown Markdown syntax reference covering headings, lists, links, images, code blocks, tables, blockquotes, and GFM extensions like task lists. # Markdown syntax Markdown is a lightweight markup language for formatting text. It is simple, easy to learn, and widely used for documents, blogs, and forums. ## Basic Syntax ### Headings ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} # 一级title ## 二级title ### 三级title #### 四级title ##### 五级title ###### 六级title ``` ### Emphasis ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} *斜体* 或 _斜体_ **粗体** 或 __粗体__ ***粗斜体*** 或 ___粗斜体___ ~~Removed线~~ ``` Rendered output: *italic*, **bold**, ***bold italic***, ~~strikethrough~~ ### list #### Unordered lists ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} - 项目1 - 项目2 - 子项目2.1 - 子项目2.2 - 项目3 * 也可以用星号 + 或者加号 ``` #### Ordered lists ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} 1. 第一项 2. 第二项 3. 第三项 1. 子项3.1 2. 子项3.2 ``` ### Link ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} [Link文本](https://example.com) [带title's Link](https://example.com "鼠标悬停显示") # 自动Link # Reference式Link [Link文本][ref] [ref]: https://example.com ``` ### Images ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} ![替代文本](image.jpg) ![带title's 图片](image.jpg "图片title") # 图片Link [![图片](image.jpg)](https://example.com) ``` ### Blockquotes ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} > 这is一段Reference > 可以有多行 > 多级Reference >> 第二级 >>> 第三级 ``` ### Code #### Inline code ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} 使用 `反引号` Package裹代码 ``` #### Code blocks ````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} ```python def hello(): print("Hello World") ``` ```javascript console.log("Hello World"); ``` ```` ### Horizontal rules ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} --- *** ___ ``` *** ### Tables ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} | Left aligned | Centered | Right aligned | |:-------|:----:|-------:| | Content 1 | Content 2 | Content 3 | | 内容4 | 内容5 | 内容6 | ``` | Left aligned | Centered | Right aligned | | :- | :-: | -: | | Content 1 | Content 2 | Content 3 | ### Task lists ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} - [x] FinishedTask - [ ] Unfinished task - [ ] 另aTask ``` * [x] FinishedTask * [ ] Unfinished task ### Footnotes ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} 这is一段文字[^1] [^1]: 这is脚注内容 ``` ## Github Flavored Markdown (GFM) GitHub extends Markdown with several extra features. ### Syntax highlighting ````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} ```python def hello(): print("Hello") ``` ```` ### Emoji ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} :smile: :heart: :+1: :rocket: ``` :smile: :heart: :+1: :rocket: [Emoji list](https://github.com/ikatyang/emoji-cheat-sheet) ### @mentions and issue references ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} @username #123 ``` ### Automatic links GitHub automatically converts URLs into links: ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} https://github.com ``` ### Diff code blocks ````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} ```diff - Removed line + Added line ``` ```` ### Collapsible content ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
点击展开 This is hidden content
``` ### Alert boxes (newer GitHub feature) ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} > [!NOTE] > Useful information users should know. > [!TIP] > Suggestions that help users succeed. > [!IMPORTANT] > Critical information for successful use. > [!WARNING] > Urgent information that needs immediate attention. > [!CAUTION] > Potential negative consequences of an action. ``` ### Mathematical formulas Use LaTeX syntax: ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} 行内公式:$E = mc^2$ 块级公式: $$ \sum_{i=1}^{n} i = \frac{n(n+1)}{2} $$ ``` ### Mermaid diagrams ````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} ```mermaid graph TD A[开始] --> B{判断} B -->|is| C[执行] B -->|否| D[结束] C --> D ``` ```` ## Advanced tips ### HTML embedding Markdown also supports raw HTML directly: ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
Ctrl + C 高亮文本 ``` ### Escaping characters Use backslashes to escape special characters: ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} \* 不is斜体 \# 不istitle \[ 不isLink ``` ### Anchor links ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} [跳转到title](#titlename) # Chinese title会被转为拼音或其他形式 ``` ### Badges ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} ![GitHub stars](https://img.shields.io/github/stars/user/repo) ![License](https://img.shields.io/badge/license-MIT-blue) ``` ### Table of contents ```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}} [TOC] # 某些Editor Supportautomatically generates目录 ``` ## Common tools * **Editors**: Typora, VS Code, Obsidian * **Online editors**: StackEdit, Dillinger * **Formatting**: Prettier, markdownlint * **Conversion**: Pandoc (Markdown to PDF/Word/HTML) ## Best Practices 1. **Keep it simple**: Markdown works best when it stays lightweight. 2. **Use headings well**: keep the hierarchy clear. 3. **Use code highlighting**: specify languages for better readability. 4. **Optimize images**: keep image sizes under control. 5. **Preview often**: check the rendered result after writing. 6. **Version control**: Markdown works very well with Git. 7. **Check links**: make sure all links work. 8. **Consider HTML for rich Agent output**: When AI agents generate long documents with tables, diagrams, and interactive elements, HTML may be more expressive than Markdown (see below). ## HTML vs Markdown for Agent Output In the AI Agent era, the question of output format matters more than before. When agents write and modify documents, Markdown's core advantage — "easy to manually edit" — disappears. Should you switch to HTML? ### When Markdown is still the right choice * **Short documents** (under \~100 lines) — Markdown remains the simplest format * **Config files, READMEs, changelogs** — Git-friendly, easy to diff * **Knowledge base pages** (like this site) — Mintlify/Jekyll render Markdown beautifully * **Team wikis** — Where version control and collaborative editing are important ### When HTML has advantages | Advantage | Example | | - | - | | **Information density** | Tables, SVG, CSS, charts, and images in one file — no ASCII art approximations | | **Readability** | Tabs, illustrations, and responsive layouts for long documents | | **Shareability** | Upload HTML, share link — colleagues open it without special tools | | **Interactivity** | Sliders, buttons, form controls that feed back into the agent | | **Multi-source data** | Agent reads code, Slack, Git history → produces unified HTML report | | **Pleasure** | More engaging authoring experience for the human reviewer | ### Five practical use cases for HTML 1. **Planning & exploration** — Generate an "HTML file network": 6 directions side-by-side, then mockups, then an implementation plan 2. **Code review** — Render diff, inline annotations, and flow charts in one page 3. **Design prototyping** — HTML as design intermediate language, then translate to React/Swift 4. **Reports & learning** — Cross-source synthesis with interactive explanations or slides 5. **Disposable editors** — A throwaway UI for one task (reorder 30 tickets, toggle feature flags, adjust system prompt) with an "Export as JSON/prompt" button ### Tradeoffs * **Generation time** — HTML takes 2–4× longer to generate than Markdown * **Token cost** — Higher, but less relevant with 1M+ context windows * **Version control** — **HTML diff is noisy and hard to review** — this is Markdown's biggest remaining advantage * **Style consistency** — Requires a "design system HTML file" as reference to constrain aesthetics > [!TIP] > > For knowledge bases and version-controlled docs, **Markdown is still the default**. Use HTML only when the output is a one-off report, a review artifact, or an interactive prototype — things that won't need Git diff review. > [!NOTE] > > Based on [Thariq's analysis: HTML replacing Markdown in the Agent era](https://x.com/trq212) — 6 advantages, 5 use cases, and tradeoffs. Original article at [x.com/i/article/2052796100608974848](https://x.com/i/article/2052796100608974848). ## References * [Markdown Guide](https://www.markdownguide.org/) * [GitHub Markdown documentation](https://docs.github.com/zh/get-started/writing-on-github) * [CommonMark Specification](https://commonmark.org/) * [Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) # npm supply chain Source: https://base.bangwu.me/env/npm-supply-chain Control npm install-time lifecycle scripts with allowScripts, approve-scripts, deny-scripts, and strict-allow-scripts to reduce package supply-chain risk. # npm supply chain npm packages can run lifecycle scripts during installation. That is useful for native builds, but it is also one of the most dangerous supply-chain surfaces in a JavaScript project. The important shift in npm 11 is the `allowScripts` policy: instead of treating every dependency install script as implicitly trusted, you can record which packages are allowed to run scripts and which are denied. ## What counts as an install script The npm policy covers dependency scripts that run while installing packages: * `preinstall` * `install` * `postinstall` * `prepare` for non-registry sources such as `git`, `file`, and `link` dependencies It also matters for native packages that rely on implicit build behavior. A package with `binding.gyp` may trigger a `node-gyp rebuild` even if it does not declare an explicit `install` script. ## The project policy lives in `package.json` Use `allowScripts` in `package.json` as team-wide policy: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "allowScripts": { "esbuild@0.25.0": true, "sharp": true, "suspicious-package": false } } ``` Two useful styles: * **Pinned approval**: `pkg@version`, safer for packages whose install behavior may change between versions. * **Name-only approval**: `pkg`, less noisy but broader. `npm approve-scripts` pins approvals by default. `npm deny-scripts` writes name-only denials because denying only one version would silently allow another version of the same package. ## Review pending scripts Start with a read-only scan: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm approve-scripts --allow-scripts-pending ``` Then approve only packages that have a real reason to run install scripts: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm approve-scripts esbuild sharp ``` Deny packages that should not run scripts: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm deny-scripts suspicious-package ``` Commit the resulting `package.json` change so the decision is shared across local machines and CI. ## Make CI fail on unreviewed scripts In npm 11.16.0, npm documents `allowScripts` as advisory by default: installs can still run scripts, but npm reports packages that are not covered by the policy. To turn policy drift into a build failure, enable strict mode in CI: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm ci --strict-allow-scripts ``` This makes any dependency with install scripts fail the install unless it is covered by `allowScripts`. Explicit denials are skipped. If you are migrating a large repo, use a staged rollout: 1. Run `npm approve-scripts --allow-scripts-pending` locally. 2. Approve or deny the minimum set. 3. Commit `package.json`. 4. Add `npm ci --strict-allow-scripts` to CI. 5. Re-review whenever dependency versions change. ## Avoid the escape hatches by default Do not reach for broad bypasses unless you are deliberately debugging a migration. * `--ignore-scripts` blocks scripts globally, but may break packages that genuinely need native builds. * `--dangerously-allow-all-scripts` bypasses the `allowScripts` policy entirely and is explicitly an escape hatch. * Passing `--allow-scripts` to project-scoped install commands is not the team policy path; use `package.json` instead. ## Review checklist Before approving a package, ask: 1. Does it really need a native build or install-time generation? 2. Is the package maintained and widely used? 3. Is the exact version pinned in the lockfile? 4. Can the script be avoided by using a prebuilt alternative? 5. Would this still be safe on a CI runner with secrets? The last question is the most important. Install scripts often run before your app code, but with access to the developer or CI environment. Editor extensions follow the same trust model through a different channel. See [Editor extension supply chain](/env/editor-extension-security). ## References * [Folo source: npm allowScripts defaults discussion](https://x.com/wwwgoubuli/status/2067397155841868203) * [npm docs: npm approve-scripts](https://docs.npmjs.com/cli/v11/commands/npm-approve-scripts) * [npm docs: npm deny-scripts](https://docs.npmjs.com/cli/v11/commands/npm-deny-scripts) * [npm docs: allow-scripts and strict-allow-scripts config](https://docs.npmjs.com/cli/v11/using-npm/config) # Supervisor Source: https://base.bangwu.me/env/supervisor Supervisor is a Linux process manager for running and auto-restarting background services, covering installation, config files, and CLI usage. # Supervisor process management Supervisor is a Python-based process management tool for monitoring and controlling Unix/Linux processes on a system. [Detailed tutorial blog post](https://bangwu.top/posts/supervisor) ## Overview Supervisor can: * start, stop, and restart processes automatically * monitor process status and restart crashed processes automatically * provide a web management interface * record process output logs * manage processes in groups ## Installation ### Ubuntu/Debian ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo apt update sudo apt install supervisor ``` ### CentOS/RHEL ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo yum install supervisor ``` ### Python pip ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} pip install supervisor ``` ## Configuration File Main configuration file location: * Ubuntu: `/etc/supervisor/supervisord.conf` * Per-program config files: `/etc/supervisor/conf.d/*.conf` ### Basic configuration structure ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:myapp] command=/usr/bin/python /path/to/app.py ; 启动Command directory=/path/to/ ; 工作目录 user=www-data ; Run用户 autostart=true ; 随supervisor启动 autorestart=true ; 自动重启 startsecs=10 ; 启动10秒后无Exception才认为成功 startretries=3 ; 失败重试次数 redirect_stderr=true ; redirectError输出 stdout_logfile=/var/log/myapp.log ; Logfile stdout_logfile_maxbytes=50MB ; Logfile大小 stdout_logfile_backups=10 ; LogBackup数量 environment=PATH="/usr/local/bin" ; Environment Variables ``` ## Common Commands ### Manage the Supervisor service ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 启动 supervisor sudo systemctl start supervisor # 停止 supervisor sudo systemctl stop supervisor # 重启 supervisor sudo systemctl restart supervisor # ViewState sudo systemctl status supervisor # 开机自启 sudo systemctl enable supervisor ``` ### Manage processes ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 重新加载Configuration sudo supervisorctl reread sudo supervisorctl update # 启动程序 sudo supervisorctl start myapp # 停止程序 sudo supervisorctl stop myapp # 重启程序 sudo supervisorctl restart myapp # View所有程序State sudo supervisorctl status # View特定程序State sudo supervisorctl status myapp # 启动所有程序 sudo supervisorctl start all # 停止所有程序 sudo supervisorctl stop all # 重启所有程序 sudo supervisorctl restart all # ViewLog sudo supervisorctl tail myapp sudo supervisorctl tail -f myapp # 实时View # 清空Log sudo supervisorctl clear myapp ``` ## Configuration examples ### Python web app ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:flask_app] command=/usr/bin/python3 /home/user/app/run.py directory=/home/user/app user=www-data autostart=true autorestart=true startsecs=5 startretries=3 redirect_stderr=true stdout_logfile=/var/log/supervisor/flask_app.log environment=FLASK_ENV="production",SECRET_KEY="your-secret" ``` ### Node.js app ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:nodejs_app] command=/usr/bin/node /home/user/app/server.js directory=/home/user/app user=nodejs autostart=true autorestart=true redirect_stderr=true stdout_logfile=/var/log/supervisor/nodejs_app.log environment=NODE_ENV="production" ``` ### Celery Worker ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:celery_worker] command=/home/user/venv/bin/celery -A myapp worker --loglevel=info directory=/home/user/myapp user=celery numprocs=1 autostart=true autorestart=true startsecs=10 stopwaitsecs=600 stopasgroup=true killasgroup=true redirect_stderr=true stdout_logfile=/var/log/celery/worker.log ``` ### Process groups ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [group:myproject] programs=web,worker,beat priority=999 [program:web] command=/usr/bin/gunicorn myapp:app ... [program:worker] command=/usr/bin/celery worker ... [program:beat] command=/usr/bin/celery beat ... ``` ## Web interface Enable the web management interface: ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [inet_http_server] port=127.0.0.1:9001 username=admin password=password ``` Visit:[http://localhost:9001](http://localhost:9001) ## Environment Variables ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:myapp] command=/usr/bin/python app.py environment= PATH="/usr/local/bin", DATABASE_URL="postgresql://localhost/db", SECRET_KEY="secret" ``` ## Log Management ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:myapp] stdout_logfile=/var/log/myapp/stdout.log stdout_logfile_maxbytes=50MB ; 单个file最大50MB stdout_logfile_backups=10 ; 保留10个Backup stderr_logfile=/var/log/myapp/stderr.log stderr_logfile_maxbytes=50MB stderr_logfile_backups=10 ``` ## Graceful shutdown ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:myapp] stopsignal=TERM ; 停止信号 stopwaitsecs=10 ; 等待10秒后强制杀死 stopasgroup=true ; 停止整个进程组 killasgroup=true ; 杀死整个进程组 ``` ## Multi-process management ```ini theme={"theme":{"light":"github-light","dark":"github-dark"}} [program:worker] command=/usr/bin/python worker.py process_name=%(program_name)s_%(process_num)02d numprocs=4 ; 启动4个进程 autostart=true autorestart=true ``` ## Troubleshooting ### ViewLog ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # supervisor 主Log sudo tail -f /var/log/supervisor/supervisord.log # 程序Log sudo tail -f /var/log/supervisor/myapp.log # 使用 supervisorctl View sudo supervisorctl tail -f myapp ``` ### FAQ 1. **Process fails to start** * Check whether the command path is correct * Check user permissions * ViewLogfile 2. **Process restarts too often** * Increase the `startsecs` value * Check whether the program itself has an issue 3. **Configuration does not take effect** ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} sudo supervisorctl reread sudo supervisorctl update ``` ## Best Practices 1. **Separate config files**: use one config file per program. 2. **Set reasonable log sizes** to avoid filling up the disk. 3. **Use dedicated users** for better security. 4. **Use process groups** for easier batch management. 5. **Use environment variables** to separate config from code. 6. **Add alerting** by integrating with monitoring systems. 7. **Back up configurations regularly** and keep them under version control. ## Alternatives * **systemd**: Linux service management * **PM2**: Node.js process manager * **circus**: Python process management * **monit**: system monitoring and process management ## References * [Supervisor Official Docs](http://supervisord.org/) * [Configuration file reference](http://supervisord.org/configuration.html) * [Detailed blog tutorial](https://bangwu.top/posts/supervisor) # Next.js Source: https://base.bangwu.me/frontend/Nextjs/index Next.js is a React full-stack framework by Vercel with SSR, SSG, and API Routes, covering project setup, file-system routing, and data fetching. ## Next.js Next.js is one of the most popular React frameworks in recent years, developed and maintained by Vercel. ### Core Features * **Hybrid rendering**: supports SSR, SSG, and ISR * **File-based routing**: automatic routing built on the file system * **API Routes**: built-in API endpoints * **Performance optimizations**: automatic code splitting and image optimization * **TypeScript**: first-class TypeScript support * **Zero config**: sensible defaults out of the box ### Quick Start ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # 创建新项目 npx create-next-app@latest my-app cd my-app # 启动开发服务器 npm run dev # Visit http://localhost:3000 ``` ### Project structure ``` my-app/ ├── app/ # App Router(推荐) │ ├── layout.tsx # 根布局 │ ├── page.tsx # Home │ └── api/ # API 路由 ├── public/ # 静态资源 ├── components/ # Component ├── lib/ # Tool函数 └── next.config.js # Next.js Configuration ``` ### App Router(Next.js 13+) #### Pages & Layouts ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} // app/page.tsx - Home export default function Home() { return

Welcome to Next.js

} // app/layout.tsx - 根布局 export default function RootLayout({ children }) { return ( {children} ) } // app/about/page.tsx - /about 路由 export default function About() { return

About Page

} ``` #### Dynamic Routes ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} // app/blog/[slug]/page.tsx export default function BlogPost({ params }) { return

Post: {params.slug}

} // app/shop/[...slug]/page.tsx - 捕获所有路由 export default function Shop({ params }) { return
{params.slug.join('/')}
} ``` #### Data Fetching ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} // Server Components (Default)(默认) async function getData() { const res = await fetch('https://api.example.com/data', { cache: 'force-cache', // Caching // next: { revalidate: 3600 } // ISR - 每小时重新Validation }) return res.json() } export default async function Page() { const data = await getData() return
{data.title}
} ``` #### Client Components ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} 'use client' // 必须in顶部Declaration import { useState } from 'react' export default function Counter() { const [count, setCount] = useState(0) return ( ) } ``` #### Loading and error UI ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} // app/loading.tsx - loading states export default function Loading() { return
Loading...
} // app/error.tsx - error handling 'use client' export default function Error({ error, reset }) { return (

Something went wrong!

) } ``` ### API Routes ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} // app/api/hello/route.ts import { NextResponse } from 'next/server' export async function GET(request: Request) { return NextResponse.json({ message: 'Hello World' }) } export async function POST(request: Request) { const body = await request.json() return NextResponse.json({ data: body }) } ``` ### Middleware ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} // middleware.ts import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // authentication检查 const token = request.cookies.get('token') if (!token) { return NextResponse.redirect(new URL('/login', request.url)) } return NextResponse.next() } export const config = { matcher: '/dashboard/:path*', } ``` ### Image Optimization ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} import Image from 'next/image' export default function Avatar() { return ( Avatar ) } ``` ### Font Optimization ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} import { Inter, Roboto_Mono } from 'next/font/google' const inter = Inter({ subsets: ['latin'] }) const robotoMono = Roboto_Mono({ subsets: ['latin'] }) export default function Layout({ children }) { return ( {children} ) } ``` ### Metadata ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} // app/layout.tsx import type { Metadata } from 'next' export const metadata: Metadata = { title: 'My App', description: 'App description', keywords: ['Next.js', 'React'], } // 动态Metadata export async function generateMetadata({ params }) { const post = await getPost(params.id) return { title: post.title, description: post.excerpt, } } ``` ### Environment Variables ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # .env.local NEXT_PUBLIC_API_URL=https://api.example.com DATABASE_URL=postgresql://... ``` ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} // client accessible(NEXT_PUBLIC_ prefix) const apiUrl = process.env.NEXT_PUBLIC_API_URL // server-only accessible const dbUrl = process.env.DATABASE_URL ``` ### Configuration File ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { images: { domains: ['example.com'], }, env: { CUSTOM_KEY: 'value', }, async redirects() { return [ { source: '/old-path', destination: '/new-path', permanent: true, }, ] }, } module.exports = nextConfig ``` ### Deployment #### Vercel (recommended) ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # Installation Vercel CLI npm i -g vercel # Deployment vercel ``` #### Docker ```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}} FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run built EXPOSE 3000 CMD ["npm", "start"] ``` #### Static Export ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // next.config.js module.exports = { output: 'export', } ``` ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm run built # 输出到 out/ 目录 ``` ### Performance Optimization * **code splitting**:auto split by route * **lazy loading**:dynamic import components * **Image optimization**: `next/image` handles optimization automatically * **Font optimization**: `next/font` improves font loading * **Prefetching**: the `Link` component prefetches automatically * **Caching**:fine-grained cache control ### Library Integrations #### Tailwind CSS ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` #### Prisma ORM ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install prisma @prisma/client npx prisma init ``` #### NextAuth.js authentication ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install next-auth ``` ### Best Practices 1. **Prefer Server Components first** when possible. 2. **Use caching appropriately** and choose a sensible caching strategy. 3. **Optimize images** with `next/image`. 4. **Organize code by feature modules**. 5. **TypeScript**:use type safety 6. **error handling**:use error.tsx for error handling 7. **loading states**:use loading.tsx for better UX ### FAQ #### Hydration Error(Hydration Error) * Make sure server and client rendering stay consistent. * Avoid using browser APIs on the server. #### Performance Optimization * Use dynamic imports to reduce the initial bundle size. * Enable production optimizations. ### References * [Next.js Official Docs](https://nextjs.org/docs) * [Next.js GitHub](https://github.com/vercel/next.js) * [Learn Next.js](https://nextjs.org/learn) * [App Router documentation](https://nextjs.org/docs/app) # Tailwind CSS Source: https://base.bangwu.me/frontend/TailwindCSS/index Tailwind CSS is a utility-first CSS framework for building interfaces with predefined classes, covering installation, responsive design, and theming. ![Tailwindcss6](https://cdn.bangwu.top/img/Tailwindcss6.png) # Tailwind CSS Tailwind CSS is a utility-first CSS framework for building interfaces by combining atomic utility classes. ## Core Philosophy Unlike traditional semantic CSS frameworks, Tailwind provides low-level utility classes so you can style directly in HTML. ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}

Title

Title

``` ## Installation ### Via npm ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install -D tailwindcss npx tailwindcss init ``` ### Configuration File ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./src/**/*.{html,js,jsx,ts,tsx}", ], theme: { extend: {}, }, plugins: [], } ``` ### CSS File ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} /* src/styles.css */ @tailwind base; @tailwind components; @tailwind utilities; ``` ### Vite Project ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` ## Common Utility Classes ### Layout ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
Item 1
Item 2
1
2
3
Content
``` ### Space ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
所有方向 padding: 1rem
水平 1rem,垂直 0.5rem
顶部 padding
所有方向 margin
水平居中
负 margin
1
2
``` ### Sizing ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
100% 宽度
50% 宽度
16rem 宽度
最大宽度
100vh 高度
16rem 高度
最小 100vh
``` ### Colors ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}

蓝色文字

深灰色文字

红色背景
渐变背景
灰色边框
``` ### Typography ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}

超大title

正常文字

小文字

细体

正常

粗体

左yes齐

居中

右yes齐

紧凑行高

宽松行高

``` ### Borders and border radius ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
默认边框
2px 边框
顶部边框
小圆角
大圆角
全圆角
``` ### Shadows ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
默认阴影
中等阴影
大阴影
超大阴影
无阴影
``` ### Opacity ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
完全透明
半透明
不透明
``` ## Responsive Design Tailwind uses a mobile-first breakpoint system. ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
响应式文字大小
响应式grid
``` ### Breakpoints * `sm`: 640px * `md`: 768px * `lg`: 1024px * `xl`: 1280px * `2xl`: 1536px ## Pseudo-classes & States ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Dark Mode ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
自适应Dark Mode
``` ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // tailwind.config.js module.exports = { darkMode: 'class', // 'media' 或 'class' } ``` ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // 切换Dark Mode document.documentElement.classList.toggle('dark') ``` ## Custom Configuration ### Extend Theme ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // tailwind.config.js module.exports = { theme: { extend: { colors: { primary: '#3490dc', secondary: '#ffed4e', }, spacing: { '128': '32rem', }, fontFamily: { sans: ['Inter', 'sans-serif'], }, }, }, } ``` ### Custom Utilities ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} @layer utilities { .text-shadow { text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1); } } ``` ### Custom Components ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} @layer components { .btn-primary { @apply bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-700; } } ``` ## Common Plugins ### Official Plugins ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install -D @tailwindcss/forms npm install -D @tailwindcss/typography npm install -D @tailwindcss/aspect-ratio ``` ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // tailwind.config.js module.exports = { plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), require('@tailwindcss/aspect-ratio'), ], } ``` ### Typography(Typography) ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}

Markdown title

自动美化's Typography

``` ## Practical Tips ### Extract Components Use `@apply` to extract repeated utility classes: ```css theme={"theme":{"light":"github-light","dark":"github-dark"}} .card { @apply bg-white rounded-lg shadow-md p-6; } ``` ### Conditional Classes Use the `clsx` or `classnames` library: ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} import clsx from 'clsx' function Button({ primary, children }) { return ( ) } ``` ### Group & Children ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}

Text

``` ### Arbitrary Values ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
自Definition值
``` ## Performance Optimization ### Production Optimization Tailwind automatically removes unused styles. ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // tailwind.config.js module.exports = { content: [ './src/**/*.{js,jsx,ts,tsx}', ], } ``` ### JIT Mode Just-In-Time mode is enabled by default and generates styles on demand. ## Editor Support ### VS Code Extensions * **Tailwind CSS IntelliSense**: autocomplete and previews * **Headwind**: automatically sorts class names ## FAQ ### Style Priority Use the `!` prefix to force a style to apply: ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
强制红色文字
``` ### Custom Colors ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
自Definition十六进制颜色
``` ## Best Practices 1. **Stay consistent** and follow the design system. 2. **Avoid over-abstraction** and do not extract components too early. 3. **Use responsive design** with a mobile-first mindset. 4. **Use configuration well** for custom theme colors and spacing. 5. **Use editor support** by installing the IntelliSense extension. 6. **Componentize complex UI** by extracting it into separate files. ## References * [Tailwind CSS website](https://tailwindcss.com/) * [Tailwind UI](https://tailwindui.com/) - official component library * [Headless UI](https://headlessui.com/) - unstyled components * [Tailwind Play](https://play.tailwindcss.com/) - online editor * [Awesome Tailwind](https://github.com/aniftyco/awesome-tailwindcss) # Naive UI Source: https://base.bangwu.me/frontend/Vue/NaiveUI Naive UI is a TypeScript-friendly Vue 3 component library with 80+ components, covering installation, theme customization, and common usage. ![TypeScript](https://cdn.bangwu.top/img/TypeScript.png) # Naive UI Naive UI is a Vue 3 component library with a rich component set and strong TypeScript support. ## Features * 🎨 **customizable theme**:complete theme system * 📦 **Tree Shaking**:load on demand,small size * 🔧 **TypeScript**:complete type definitions * 🌙 **Dark Mode**: built-in dark theme support * 🎯 **No extra UI dependencies**: no third-party UI framework dependency * 📱 **Responsive**: mobile-friendly layout support ## Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install naive-ui ``` ## Usage ### global full import ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // main.js import { createApp } from 'vue' import naive from 'naive-ui' import App from './App.vue' const app = createApp(App) app.use(naive) app.mount('#app') ``` ### On-demand import (recommended) ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Auto Import Use `unplugin-auto-import` and `unplugin-vue-components`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install -D unplugin-vue-components unplugin-auto-import ``` ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // vite.config.js import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { NaiveUiResolver } from 'unplugin-vue-components/resolvers' export default defineConfig({ plugins: [ vue(), AutoImport({ imports: [ 'vue', { 'naive-ui': [ 'useDialog', 'useMessage', 'useNotification', 'useLoadingBar' ] } ] }), Components({ resolvers: [NaiveUiResolver()] }) ] }) ``` ## Config Provider ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Theme Configuration ### Custom Theme ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Dark Mode ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Common Components ### Button Button ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Input Input ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Select Select ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Table Table ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Card Card ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Modal Modal ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Form Form ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Global Notifications ### Message Message ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Dialog Dialog ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Notification Notification ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Loading Bar Loading Bar ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Layout Components ### Layout ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Space Space ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Grid Grid ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Icons Naive UI recommends using [xicons](https://www.xicons.org/): ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install @vicons/ionicons5 ``` ```vue theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Best Practices 1. **Use on-demand import** with auto-import plugins. 2. **Keep the theme consistent** across the app. 3. **Use global configuration** through `ConfigProvider`. 4. **Take advantage of TypeScript support**. 5. **Use the grid system** for responsive design. 6. **Configure locale settings** for internationalization. ## References * [Naive UI website](https://www.naiveui.com/) * [GitHub repository](https://github.com/tusen-ai/naive-ui) * [Componentdocumentation](https://www.naiveui.com/zh-CN/os-theme/components/button) * [Theme editor](https://www.naiveui.com/zh-CN/os-theme/docs/customize-theme) # Vue.js Source: https://base.bangwu.me/frontend/Vue/index Vue 3 progressive framework notes covering Composition API with setup/ref/reactive, component communication, Vue Router, and Pinia state. ![Vue](https://cdn.bangwu.top/img/Vue.png) Vue.js is a progressive JavaScript framework for building user interfaces. Easy to learn, performant, and versatile. ## Core Features * **Reactive data binding**: Data changes automatically update the view * **Component-based development**: Reusable component system * **Virtual DOM**: Efficient DOM updates * **Composition API**: Vue 3's recommended logic organization ## Quick Start ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm create vue@latest cd my-app npm install npm run dev ``` > [card] [Naive UI](/frontend/Vue/NaiveUI) > > Vue 3 component library with full TypeScript support and theme customization. ## Resources * [Vue.js Official Docs](https://vuejs.org/) * [Vue Router](https://router.vuejs.org/) * [Pinia](https://pinia.vuejs.org/) * [Vite](https://vitejs.dev/) # DaisyUI Source: https://base.bangwu.me/frontend/daisyui DaisyUI is a Tailwind CSS component library with pre-designed buttons, cards, modals, and navbars, covering installation, themes, and examples. # DaisyUI DaisyUI is a component library built on Tailwind CSS, offering many pre-designed components. ## Features * 🎨 **pure CSS components**:no JavaScript dependency * 🎭 **30+ themes**: multiple built-in themes with dark mode support * 🧩 **semantic class names**:easy to understand and use * 🎯 **Tailwind-compatible**: integrates cleanly with Tailwind CSS * 📦 **lightweight**:load on demand,small size ## Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install -D daisyui@latest ``` Configuration `tailwind.config.js`: ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} module.exports = { plugins: [require('daisyui')], daisyui: { themes: ['light', 'dark', 'cupcake'], }, } ``` ## Common Components ### Button ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Card ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
Image

Card Title

Card description text

``` ### Modal ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Navbar ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Form ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Alert ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
... Info message
Success
Warning
Error
``` ### Badge ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
Default
Primary
Secondary
Accent
Ghost
``` ## Theme Switching ### Using an HTML attribute ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ### Switching with JavaScript ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // 切换主题 document.documentElement.setAttribute('data-theme', 'dark'); // 保存到 localStorage localStorage.setItem('theme', 'dark'); // 读取主题 const theme = localStorage.getItem('theme') || 'light'; document.documentElement.setAttribute('data-theme', theme); ``` ### Theme SwitchingComponent ```html theme={"theme":{"light":"github-light","dark":"github-dark"}} ``` ## Custom Theme ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}} // tailwind.config.js module.exports = { daisyui: { themes: [ { mytheme: { "primary": "#a991f7", "secondary": "#f6d860", "accent": "#37cdbe", "neutral": "#3d4451", "base-100": "#ffffff", }, }, ], }, } ``` ## Useful utility classes ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
OR
``` ## Layout Components ### Drawer ```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
``` ## Best Practices 1. **Combine with Tailwind**: DaisyUI components work well with Tailwind utility classes. 2. **Keep themes consistent** across the whole project. 3. **Use Tailwind responsive prefixes** for responsive design. 4. **Avoid unnecessary customization** and start with presets. 5. **Load on demand** by configuring PurgeCSS to remove unused styles. ## References * [DaisyUI website](https://daisyui.com/) * [Componentdocumentation](https://daisyui.com/components/) * [Theme list](https://daisyui.com/docs/themes/) * [GitHub repository](https://github.com/saadeghi/daisyui) # Frontend Source: https://base.bangwu.me/frontend/index Frontend development notes covering Vue 3 with Naive UI, Next.js React framework with SSR/SSG, Tailwind CSS utility classes, and DaisyUI. ![Node.js](https://cdn.bangwu.top/img/Node.js.png) Frontend development builds user interfaces and experiences, covering the visual part of web applications. > [card] [Vue](/frontend/Vue/index) > > Progressive JavaScript framework with Composition API. > [card] [Next.js](/frontend/Nextjs/index) > > React full-stack framework with SSR/SSG/API Routes. > [card] [TanStack + Hono](/frontend/tanstack) > > Full-stack monorepo — SSR + type-safe API server. > [card] [SolidJS + Tauri](/frontend/solidjs) > > Local-first desktop apps — reactive UI + Rust shell. > [card] [CSS Tools](/frontend/TailwindCSS/index) > > Tailwind CSS and DaisyUI component library. > [card] [UnoCSS](/frontend/tanstack#styling-unocss) > > Utility-first CSS with icon presets — lighter than Tailwind. ## Core Tech Stack | Tech | Purpose | Description | | - | - | - | | HTML | Page structure | Defines the skeleton | | CSS | Styling & layout | Colors, fonts, spacing | | JavaScript | Interactivity | Dynamic features & events | ## Learning Path 1. **Foundation**: HTML / CSS / JavaScript + DOM & events + ES6+ features 2. **Intermediate**: Frontend framework (Vue / React) + TypeScript + build tools 3. **Advanced**: Performance optimization + engineering practices + cross-platform # SolidJS + Tauri Desktop Source: https://base.bangwu.me/frontend/solidjs Building local-first desktop apps with SolidJS for reactive UIs and Tauri v2 for the Rust shell, based on OnlyWrite project experience. # SolidJS + Tauri Desktop Development SolidJS is a truly reactive UI framework — no virtual DOM, no diffing. Tauri v2 wraps your web frontend in a Rust shell for native desktop packaging. Together they create fast, lightweight desktop apps. > [card] [OnlyWrite](https://github.com/markbang/OnlyWrite) > > A local-first writing app built with SolidJS + Tauri 2 + TypeScript. ## Why SolidJS + Tauri? | Concern | SolidJS | React/Vue | | - | - | - | | Rendering | True reactivity (no VDOM) | Virtual DOM diffing | | Bundle size | \~7KB | \~40KB+ (React) | | Update granularity | Fine-grained (per signal) | Component-level | | Desktop shell | Tauri (Rust, \~3MB binary) | Electron (\~150MB) | | Memory footprint | Low | High | ## Project Structure ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} onlywrite/ ├── src/ # SolidJS frontend │ ├── components/ # UI components │ │ ├── writing-area.tsx │ │ ├── file-browser.tsx │ │ ├── theme-toggle.tsx │ │ ├── language-toggle.tsx │ │ └── s3-config-dialog.tsx │ ├── routes/ # File-based routing │ │ ├── __root.tsx # Root layout │ │ ├── index.tsx # Home page │ │ ├── dashboard.tsx # Main workspace │ │ └ login.tsx # Auth gate │ ├── lib/ │ │ ├── i18n.ts # Bilingual support │ │ ├── markdown.ts # Markdown parsing │ ├── index.tsx # App entry ├── src-tauri/ # Rust backend │ ├── Cargo.toml │ ├── capabilities/ # Tauri permissions │ ├── tauri.conf.json # App configuration ├── test/ # Vitest + Playwright ├── package.json └── tsconfig.json ``` ## Tech Stack | Layer | Technology | Purpose | | - | - | - | | Frontend | SolidJS 1.9 | Reactive UI | | Styling | Tailwind CSS 4 | Utility classes | | Icons | Lucide Solid | Icon components | | Markdown | marked + DOMPurify | Parsing + sanitization | | Desktop | Tauri 2 | Rust shell, file system access | | Testing | Vitest + Playwright | Unit + E2E tests | | Build | Vite 7 | Dev server + bundling | ## SolidJS Reactivity Patterns SolidJS uses signals and derived computations — no hooks, no re-renders: ```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}} import { createSignal, createEffect, createMemo } from "solid-js" function WritingArea() { const [content, setContent] = createSignal("") const [mode, setMode] = createSignal<"edit" | "render" | "split">("edit") // Derived value — recomputes only when content changes const renderedHtml = createMemo(() => parseMarkdown(content())) // Effect — runs when mode changes createEffect(() => { localStorage.setItem("last-mode", mode()) }) return (
{mode() === "edit" &&