清雨影的Blog
  • README
  • 机器学习
    • 一般话题
      • 再谈正则化项
      • 论文阅读:“快把卷积神经网络中的平移不变性带回来”
      • 半监督/无监督学习收集
      • 收藏夹
    • 推荐系统
      • Understanding LightGCN in a visualized way
      • Learning To Rank 之 RankNet
      • 随想: BPR Loss 与 Hinger Loss
      • 关于AA测试和AB测试的一些思考
      • 无采样的矩阵分解
      • 收藏夹
    • 强化学习
      • Re:从零开始的Multi-armed Bandit
  • 高级物理引擎实战指南笔记
    • 弹簧质点系统
    • 光滑粒子法
    • 专题:线性方程组求解
  • 有限单元法
    • 1. 引论
    • 2. 基于直接刚度法的杆系有限元方法
    • 3. 针对复杂几何形状变形体的力学描述(1)
  • Web开发相关技术
    • JWT简介
  • 技术杂文
    • React-Script转Vite时引用路径的问题
    • Let's encrypt -- 让我们一起愉快的使用HTTPS
    • 干掉吸血雷,重塑和谐P2P环境
    • 开源CAN总线信号可编程台架
    • Linux下利用mdadm设置软件 RAID
    • 互不联网时代的自给自足
    • 为什么我劝你不要使用云计算?
    • 科学的公司内网连接技术选型
    • 构建家用NAS过程中的碎碎念
    • 简易的Linux迁移指北
    • 记录一次rsync命令引起的异常
    • 为FFMPEG添加Intel QSV支持
    • 备忘录
    • 福冈外免切替(中国驾照换日本驾照)攻略
    • 记一个离谱的MySQL语句的性能问题
    • 拯救变砖的OpenWRT路由器
    • 使用FRP进行内网穿透
  • 政治不正确
    • 吃屎系列:资本家如何喂员工吃屎
      • 华为251事件记忆
    • 吃屎系列:资本家如何喂用户吃屎
      • 互不联网公司是如何强奸用户的(持续更新)
    • 吃屎系列:大学如何喂学生吃屎
    • 推荐系统如何让我们变得极端
    • 互联网政治圈观察日志
    • 中国网络防火长城简史
    • 《线性代数》(同济版)——教科书中的耻辱柱
    • 杂谈
      • 访谈:为什么毛泽东时代工人的积极性很高?
      • 90年代到21世纪初的商业环境
    • 为什么不应该用国产手机
    • “救救孩子”
  • 随园食单
    • ボロネーゼ
    • 甜酒酿的制作
    • 香草与香料
    • 皮塔饼
    • 韭菜鸡蛋饼
    • 牛肉蔬菜汤
由 GitBook 提供支持
在本页
  • 批量杀线程
  • MySQL
  • 创建用户并且授权读写Schema
  • MongoDB 权限配置
  • 管理员权限配置
  • 用户配置样例
  • 删除用户
  • MongoDB 慢查询相关
  • 查找当前大于10.0秒的、且最慢的一个查询的详情
  • 统计大于10秒的慢查数量
  • 查询Running总时间
  • 杀死超时任务
  • Python Tricks
  • Lazy Evaluation
  • Example of Async wait
  • FFMPEG
  • Convert MP4 File to MP3 File
  • Convert to H264 mp4 file
  • Merge subtitle (srt) file and video
  • 树莓派
  • RPI3 Ubuntu 摄像头
  • RPI3 Wifi
  • Encryption
  • SAML2 key/pem generator
  • K8S
  • 创建一个管理员账户的配置文件
  • Java/Scala/Kotlin
  • Maven Settings
  • Glances
  • 屏蔽多余的设备
  • Git
  • 自动使用SSH代替HTTP

这有帮助吗?

  1. 技术杂文

备忘录

批量杀线程

#!/bin/bash
ps -ef|grep $1|grep -v grep|awk '{print $2}'|xargs -r kill -9

MySQL

创建用户并且授权读写Schema

create user ${USERNAME} IDENTIFIED by '${PASSWORD}';
show grants for ${USERNAME};
grant all on ${SCHEMA}.* to ${USERNAME};
flush privileges;

MongoDB 权限配置

管理员权限配置

db.createUser({user:"root",pwd:"123456",roles: [{ role:"root", db:"admin"}]})

用户配置样例

db.createUser({ 
    user: "someuser",
    pwd: "somepassword",
    roles:[
        { role: "readWrite", db: "somedb" }
    ]
})

删除用户

db.dropUser("username")

MongoDB 慢查询相关

查找当前大于10.0秒的、且最慢的一个查询的详情

mongo --quiet --eval "let limit_time = 10.0;" slow_query.js

统计大于10秒的慢查数量

mongo --quiet --eval "db.currentOp().inprog.filter(x=>x['secs_running']>10).length"

一般统计大于5秒,15秒,30秒,60秒,300秒的慢查数量。

查询Running总时间

这个指标可以从侧面反应数据库的操作体验和压力。

mongo --quiet --eval "db.currentOp().inprog.map(x=>x.microsecs_running/1000000.0).reduce((a,b)=>a+b)"
// 检查大于 limit_time 秒的慢查询数据
// let limit_time = 10.0;
// 上一句在eval里面执行来达到动态设置的效果
db.currentOp().inprog.filter(
    x=>x["microsecs_running"]>(limit_time*1000000)
).sort(
    // 取最慢的一条进行展示
    (a,b)=>{
        const va = a["microsecs_running"];
        const vb = b["microsecs_running"];
        if(a==b){
            return 0;
        }else{
            if(a>b){
                return -1;
            }else{
                return 1;
            }
        }
    }
)

杀死超时任务

let over_time = 60.0;// Over 1 min
db.currentOp().inprog.forEach(
    opInfo=>{
        try{
            const opId = opInfo["opid"];
            const opDuration = opInfo["secs_running"];
            if(opDuration>over_time){
                db.killOp(opId);
                console.log(`Operation ${opId} killed, details: ${JSON.stringify(opInfo)}`)
            }
        }catch(err){
            console.error("Error while executing killing filter.")
            console.error(err)
        }
    }
)

Python Tricks

Lazy Evaluation

class lazy(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, cls):
        val = self.func(instance)
        setattr(instance, self.func.__name__, val)
        return val

def lazy_property(func):
    attr_name = "_lazy_" + func.__name__

    @property
    def _lazy_property(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, func(self))
        return getattr(self, attr_name)

    return _lazy_property

Comparing with the lazy, it more like cache the result, maybe can also simply replaced by lru_cache. We have to ensure the return value won't change while using it.

Example of Async wait

import asyncio
from asyncio import Future
from typing import Dict

futures: Dict[str, Future] = {}


@app.get("/test/lock/{task_id}")
async def test_lock(task_id: str):
    result = asyncio.get_event_loop().create_future()
    # Put the task in Queue
    futures[task_id] = result
    return {
        "result": await result
    }


@app.get("/test/release/{task_id}")
async def test_release(task_id: str):
    if task_id not in futures:
        raise Exception("Task not found")
    # Set result while the task finished
    futures[task_id].set_result(f"{task_id} is done")
    return {
        "task": task_id
    }

FFMPEG

Convert MP4 File to MP3 File

ffmpeg -i ${MP4_FILE} -vn \
       -acodec libmp3lame -ac 2 -ab 320k -ar 48000 \
        ${MP3_FILE}

Replace -ab {bitrate} to -ac 2 -qscale:a 4 to use VBR

Convert to H264 mp4 file

ffmpeg -vcodec h264 -acodec copy -movflags +faststart -pix_fmt yuv420p -crf 23 -i input.mp4 output.mp4

Merge subtitle (srt) file and video

ffmpeg -i ${INPUT_VIDEO} -f srt -i ${SUBTITLE_FILE} -c:v copy -c:a copy -c:s srt ${OUTPUT_VIDEO}
# -c:s can also be copy

树莓派

RPI3 Ubuntu 摄像头

  1. 只能使用32位的系统

  2. 在/boot/firmware/config.txt里增加start_x=1

  3. 执行 sudo snap install picamera-streaming-demo以后重启系统

  4. 打开 http://:8000/ 即可查看

参考资料:

RPI3 Wifi

  1. Edit /etc/netplan/xxxxxx.yaml:

# This file is generated from information provided by
# the datasource.  Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    version: 2
    ethernets:
        eth0:
            optional: true
            dhcp4: true
    # add wifi setup information here ...
    wifis:
        wlan0:
            optional: true
            access-points:
                "YOUR-SSID-NAME":
                    password: "YOUR-NETWORK-PASSWORD"
            dhcp4: true
sudo netplan --debug try 
# (continue even if there are errors)
sudo netplan --debug generate 
# (provides more details in case of issues with the previous command)
sudo netplan --debug apply 
# (if no issues during the previous commands)

Encryption

SAML2 key/pem generator

openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout encryption.key -out encryption.pem
openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout signing.key -out signing.pem

K8S

创建一个管理员账户的配置文件

首先创建一个Service Account

apiVersion: v1
kind: ServiceAccount
metadata:
  name: <Account Name>
  namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: <Account Name>
  namespace: default

获取账户详情 kubectl describe serviceaccount <Account Name>

随后获取secret的名字,格式一般是 <Account Name>-token-<随机字符串>

最后获取Token:

kubectl describe secret <Token Secret Name>
apiVersion: v1
kind: Config
users:
- name: <Account Name>
  user:
    token: "<TOKEN>"
clusters:
- name: <Cluster Name>
  cluster:
    api-version: v1
    server: <API ENDPOINT>
contexts:
- name: <Cluster Name>
  context:
    cluster: <Cluster Name>
    user: <Account Name>
current-context: <Cluster Name>

Java/Scala/Kotlin

Maven Settings

Mainly ~/.m2/settings.xml.

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">

  <servers>
    <server>
      <id>nexus-snapshots</id>
      <username>{username}</username>
      <password>{password}</password>
    </server>
    <server>
      <id>nexus-releases</id>
      <username>{username}</username>
      <password>{password}</password>
    </server>
  </servers>

  <mirrors>
    <mirror>
      <id>central</id>
      <name>central</name>
      <url>https://nexus.xxxx.com/repository/maven/</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
  </mirrors>

</settings>

Glances

屏蔽多余的设备

在使用snap的时候经常会有一些奇怪的设备,包括loop{x}或者是/snap/之类的,这个时候只要在配置文件里加上

[fs]
hide=/boot.*,/snap.*
[diskio]
hide=loop.*
[network]
hide=docker.*,lo,veth.*

就可以屏蔽这些设备。

官方文档:

  1. https://glances.readthedocs.io/en/latest/aoa/diskio.html

  2. https://glances.readthedocs.io/en/latest/aoa/fs.html

  3. 配置文件的位置 https://glances.readthedocs.io/en/latest/config.html

Git

自动使用SSH代替HTTP

来源:https://www.digitalocean.com/community/tutorials/how-to-use-a-private-go-module-in-your-own-project

在~/.gitconfig加入这一段:

[url "ssh://git@github.com/"]
insteadOf = https://github.com/

不仅可以用于导入私有的Go模块,还可以用于Brew安装的时候自动拉取Repo。

上一页为FFMPEG添加Intel QSV支持下一页福冈外免切替(中国驾照换日本驾照)攻略

最后更新于3个月前

这有帮助吗?

From the blog

Reference:

Python 延迟初始化(lazy property)
Enable Raspberry Pi Camera in Ubuntu 20.04 MATE on Raspberry Pi 4 8GB RAM
https://github.com/ogra1/picamera-streaming-demo
How to setup the Raspberry Pi 3 onboard WiFi for Ubuntu Server 18.04 with netplan?