Scratch
Amazing physics going on…
看到StackOverflow上有个人说他用Emacs用了32年才知道有这么个好用的功能: follow-mode
可以在org文件头部来指定加载的css。
^M
可以这样输入:按住Ctrl然后再依次按v和m
查看本机IP详情
curl 4.ifcfg.me/all
Vimeo也支持自适应码率了: Adaptive streaming and 4K: coming soon for your videos
If you examine a butterfly according to the laws of aerodynamics, it shouldn't be able to fly. But the butterfly doesn't know that, so it flies.
加入Mathjax支持。
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script>
进入到Docker容器中。
docker exec -it CONTAINER_NAME /bin/bash
Orgmode标记条目DONE时加上时间戳和笔记。
Emacs可以通过按键 C-q <TAB>
来插入一个tab.
按文件大小列出文件:
du -ah | sort -rh | head -10
记录下Vim启动时间:
vim --startuptime vim.log
\(\LaTeX\)中可以用ctex包来输入中文:
\usepackage[UTF8]{ctex}
\(\LaTeX\)中使用TTF字体,需要使用 xelatex
编译:
\usepackage{fontspec} \setmainfont{EBGaramond.ttf}
一个\(\LaTeX\)的示例Makefile:
# .tex --> .dvi --> .ps --> .pdf filename = foobar pdf : ps ps2pdf $(filename).ps ps : dvi dvips $(filename).dvi dvi : latex $(filename).tex bibtex $(filename) latex $(filename).tex latex $(filename).tex clean: rm -f $(filename).{ps,log,aux,out,dvi,bbl,blg}
\(\LaTeX\)中比较优雅地使用省略号
x_1 + x_2 + \cdots + x_n ~ (x_1, x_2, \ldots , x_n)
\(\LaTeX\)中区分左右符号
\left| -x \right| = \left| +y \right|
\(\LaTeX\)中用 \,
(代表1/6 quad) 来控制字符间距
\sum_{p\rm\;\prime}f(p) = \int_{t>1}f(t)\,d\pi(t)
\(\LaTeX\)中用 \!
(代表-1/6 quad) 来控制字符间距
\int\!\!\!\int_D dx\,dy
Git的代理设置:
git config --global http.proxy socks5://127.0.0.1:1080 git config --global https.proxy socks5://127.0.0.1:1080
Beamer主题设置:
\usetheme{metropolis}
Beamer首页的信息设置:
\title{A minimal example} \subtitle{subtitle here} \date{\today} \author{Matt Wong} \institute{Center for Modern Beamer Themes}
Beamer的一个普通页面:
\begin{frame} \frametitle{Title Name} Hello everyone, ... \end{frame}
Beamer的标题页面:
\begin{frame} \titlepage{} \end{frame}
Beamer的大纲页面:
\begin{frame} \frametitle{Outline} \tableofcontents{} \end{frame}
Beamer中带描述的列表:
\begin{description}[Some description] \item[First item] Description of first item \item[Second item] Description of second item \item[Third item] Description of third item \end{description}
Beamer中的字型设置:
\emph{Sample Text} \textbf{Sample Text} \textit{Sample Text} \textsl{Sample Text} \alert{Sample Text} \textrm{Sample Text} \textsf{Sample Text} \color{green}{Sample Text}
Beamer中的图片,需要导入 graphics
这个包:
\centering \includegraphics[width=\textwidth]{figures/example-image}
Beamer中分栏:
\begin{columns} \column{.5\columnwidth} Column Number 1 \column{.5\columnwidth} Column Number 2 \end{columns}
\(\LaTeX\)中插入表格:
\begin{tabular}{c||c|c|c|} & \textbf{header 1} & \textbf{header 2} & \textbf{header 4} \\ \hline \hline \textbf{header 4} & cell 1 & cell 2 & cell 3 \\ \hline \textbf{header 5} & cell 4 & cell 5 & cell 6 \\ \end{tabular}
Beamer中的脚注:
\begin{frame} The lemma 1 is from here\footnotemark and the lemma 2 is from here\footnotemark. \footnotetext[1]{Some link} \footnotetext[2]{Other link} \end{frame}
Beamer中的文本框,需要导入 fancybox
这个包:
\begin{frame} \frametitle{Text Boxes} \begin{itemize} \item \shadowbox{Sample text} \item \fbox{Sample text} \item \doublebox{Sample text} \item \ovalbox{Sample text} \item \Ovalbox{Sample text} \end{itemize} \end{frame}
Beamer中的区块环境:
Content Type | Corresponding Environment |
---|---|
Generic | block |
Theorems | theorem |
Lemmas | lemma |
Proofs | proof |
Corollaries | corollary |
Examples | example |
Highlighted Title | alertblock |
Emacs中的多行缩进:用 C-u 4 C-x <TAB>
缩进四个空格; C-u -4 C-x <TAB>
取消缩进四个空格。
orgmode中引用bib文件,第一个参数是不加后缀的bib文件(references),第二个是样式。
用orgmode来写Beamer,可以在任意标题上用 C-c C-b
进行选择展示环境。
Emacs中用orgmode来管理配置文件。
(org-babel-load-file (expand-file-name name dotfiles-dir))
orgmode中可以用 C-c /
来根据任务情况进行过滤。
orgmode中用 S-M-<RET>
可以在当前位置新建TODO项目。
orgmode可以这样自定义TODO的样式。
# -*- org-todo-keyword-faces: (("WANT" . "blue") ("DISPOSE". "orange") ("NEED" . "red") ("HAVE" . "green")); -*-
利用pandoc进行格式转换:
pandoc -f org -t docx foo.org -o foo.docx
Emacs可以用 C-c C-x C-l
来预览公式,用 C-c C-c
来取消预览。
Emacs中使用magit的流程是:
magit-status
: 进入状态预览;s
: 添加未被追踪的文件;c
: 提交更改;P
: 推送到远程仓库。
Emacs Lisp中的引用:
;; 产生列表 (1 2 3), 并且不会对列表元素进行求值 (quote (1 2 3)) ;; 单引号是 (quote (...)) 形式的简写 '(1 2 3 ) ;; 可以直接用 list 来构造 (list 1 (+ 1 1 ) 3) ;; 反引号生成 `(1 ,(+ 1 1) 3)
Emacs Lisp表达式的执行:
- 将光标移到表达式最后一个封闭的括号的后面,然后执行
C-j
; - 将光标移到表达式内部,然后执行
M-C-x
; - 将光标放到表达式最后一个封闭的括号的后面,然后执行
C-x C-e
.
Dired的快捷键:
Key | Description |
---|---|
d |
mark a file for deletion |
x |
delete marked files |
C |
copy a file |
R |
rename/move a file |
+ |
create a directory |
w |
copy filename |
M-0 w |
copy file absolute path |
W |
open file |
Emacs的包仓库设置:
(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/") ("melpa" . "http://melpa.org/packages/") ("org" . "http://orgmode.org/elpa/")))
我发现这个系统足够简单,但也足够完善,连tag系统都是现成的。
85%的Facebook视频是被静了音观看的。
Dracula这个主题也挺好看的嘛。
Windows下创建类似软链接的文件:
mklink /d dest_dir src_dir
\usepackage{siunitx}
可以用来写单位。
字符串搜索及替换
- Call
dired
. - Mark the files you want. You can mark by regex by
% m
- Type
Q
to calldired-do-query-replace-regexp
- Type your find regex and replace string.
- For each occurrence, type
y
to replace,n
to skip andC-g
to abort. - Type
!
to replace all occurrences without asking,N
to skip all the rest one. - Type
Y
to replace all the occurrences.
利用 compile
指令可以进行指定的make操作。
使用 wgrep
包,在 grep
状态下按 C-c C-p
可以对搜索结果进行编辑。
用以下几种方式可以实现在某些模式下屏蔽Evil:
(evil-set-initial-state 'dired-mode 'emacs) ;; or (add-to-list 'evil-emacs-state-modes 'dired-mode)
Chocolatey is awesome!
eshell是个好东西,不过前提是要把补全给关掉,不然太烦了。
终端查看天气
curl -4 wttr.in/Shanghai
cygwin中建立crontab任务,需要管理员权限。
利用
crontab
命令来管理任务:crontab -e #edit crontab -l #list crontab -r #remove
建立一个周期性任务,下面的例子是每六小时执行一次
date
命令:* */6 * * * date
安装cron服务:
cygrunsrv -I cron -p /usr/sbin/cron -a -n
启动cron服务:
cygrunsrv -S cron
查看服务状态:
cygrunsrv -Q cron
Mac盗版软件下载:
- http://www.macappstore.net/
- http://xclient.info/
- http://www.macpeers.com/
- http://www.macbed.com/
- http://www.macupdate.com/
- https://www.appaddict.org/
- http://soft.macx.cn/
- http://www.macfans.org/
- http://www.pshezi.com/
- http://www.waitsun.com/
- http://www.isofts.org/
- http://www.waerfa.com/
可以用TeXLive提供的宏包 ps2eps
把PS格式的图转换成EPS格式:
ps2eps foobar.ps
OpenCV的常量名称会因为版本的不同而不同,可以通过 help(cv2)
来查看。
键盘们
- HHKB
- Leopold FC660M
- Filco Minila Air 67
- RK RK61
在图论里面 node 和 vertex 两个词是没有任何区别的。
DejaVu是一种支持Unicode字符的字体。
手动编译emacs lisp包。
(byte-recompile-directory "~/.emacs.d/elpa/ranger-20160531.39" 0 t)
用Visio作图后的格式转换。
pdftops foobar.pdf # convert pdf to ps ps2eps foobar.ps # convert ps to eps
Gnome下面的dock插件:
Foobar 2000的主题:
- Mnlt2 Plus 2.0: http://inhiblon.deviantart.com/art/Foobar-Mnlt2-Plus-2-0-297076953
- MonoLite Plus 0.4.3: http://junior-spirit.deviantart.com/art/MonoLite-Plus-0-4-3-151086022
Windows下的音乐播放器:
- AIMP: http://www.aimp.ru/
- Clementine: https://www.clementine-player.org/
- Audacious: http://audacious-media-player.org/
Windows下编译zlib和libzip:
- 下载CMake并加入到PATH中。
- 加入类似
C:\Windows\Microsoft.NET\Framework64\v4.0.30319
这样的目录加入到PATH中,以便使msbuild
可以使用。 - 下载zlib和libzip源码,以下将其各自目录分别唤作
%ZLIB_DIR%
及%LIBZIP_DIR%
编译zlib:
cd /d %ZLIB_DIR% && md build & cd build cmake .. -G"Visual Studio 14 2015 Win64" -DCMAKE_INSTALL_PREFIX="%ZLIB_DIR%" msbuild /P:Configuration=Release INSTALL.vcxproj
编译libzip:
cd /d %LIBZIP_DIR% && md build & cd build cmake .. -G"Visual Studio 14 2015 Win64" -DCMAKE_PREFIX_PATH="%ZLIB_DIR%" msbuild /P:Configuration=Release ALL_BUILD.vcxproj
用systemd来控制shadowsocks,其中的 example
就是`/etc/shadowsocks/example.json`.
systemctl start shadowsocks@example
聚合的即时聊天应用: Franz
根据 PKGBUILD
手动安装软件包:
# download the Snapshot file and extract it wget http://aru.archlinux.org/xxx/snapshot; tar -xvf xxx # get into that foler and create a src folder cd foo-pkg/; mkdir src # download file according to source filed in PKGBUILD wget http://somewhere.com/foo.tar.gz # put source file to the src folder mv foo.tar.gz src/ # create a link to the source file ln src/foo.tar.gz foo.tar.gz # calculate md5 value; then write result to md5sums filed in PKGBUILD md5sum foo.tar.gz # make package makepkg -g; makepkg # install package pacman -U foo.pkg.tar.xz
设置CMOS硬件时钟。
# set to localtime (default) hwclock --systohc --localtime # set to utc hwclock --systohc --utc
图形之间的距离
\setlength{\floatsep}{10pt plus 3pt minus 2pt}
\floatsep |
出现在页面的顶部或底部的浮动对象之间的垂直距离。 缺省为 12pt plus 2pt minus 2pt。 |
\textflowsep |
出现在页面的顶部或底部的浮动对象与文本之间的垂直距离。 缺省为 20pt plus 2pt minus 4pt。 |
\intextsep |
出现在页面中间的浮动对象(如使用了 h 选项 的浮动对象)与上下方文本之间的垂直距离。 缺省为 12pt plus 2pt minus 2pt。 |
Emacs中查看当前光标下的字符字体: C-u C-x =
在启用 helm
的情况下用 bbdb-create
新建条目时候,最后要用 C-<Return>
代替 <Return>
以表示完成,不然就会死循环。
利用org进行时间记录,可以在 org-agenda
界面下按 R
来显示统计报告。
Key | Description |
---|---|
C-c C-x C-i | Clock in |
C-c C-x C-o | Clock out |
C-c C-x C-r | Generate report |
org-agenda界面下可以按 C-x C-w
导出到多种格式,只要在保存的时候指定文件后缀就行了,比如说html, ps, pdf。
一个比较优雅的org导出HTML的样式文件:
evdev
以及 synaptics
已经不再更新(maintenance mode),建议使用 libinput
.
有的会议不接受pdf文件中包含书签和链接,可以这样设置 hyperref
的参数。
\hypersetup{bookmarks=false,draft}
Windows下重启资源管理器。
taskkill /f /im explorer.exe & start explorer.exe
Rime的首字母模糊音设置,放到 luna_pinyin.custom.yaml
文件中:
"speller/algebra/@before 0": xform/^([b-df-hj-np-tv-z])$/$1_/
Sci-Hub可用网址:
Two methods for making figures for .tex
files.
Use
.eps
image format and compile with:latex main.tex bibtex main latex main.tex latex main.tex dvips main.dvi ps2pdf main.ps
Advantages are that bounding boxes can be well determined (using pdf -> ps -> eps or the likes); Disadvantages are that some images in eps format may get aliasing on shape edges. Besides, I usually put a
Makefile
for convenience.Use
.pdf
image format and compile with:pdflatex main.tex bibtex main pdflatex main.tex pdflatex main.tex
Actually, it leads to a successful compilation if we use
pdflatex
oneps
images because it will converteps
topdf
implicitly. However, the outputs have wrong bounding boxes. Thus, it is a better choice that we generate thepdf
image files by hand usingpdfcrop
which is used aspdfcrop inputimg.pdf outputimg.pdf
. For the compilation of main file, I use aMakefile
or justlatexmk
for simplicity.
Windows下利用 ffmpeg
捕获获取摄像头数据。
- 查看可用摄像头设备:
ffmpeg -f dshow -list_devices true -i dummy
- 查看某摄像头的参数:
ffmpeg -f dshow -list_options true -i video="PC Camera"
- 使用指定设备进行录像:
ffmpeg -f dshow -i video="PC Camera" out.mp4
- 参考链接: https://trac.ffmpeg.org/wiki/Capture/Webcam
在Windows下的GUI版本,Emacs中设置等宽的中英文字体:
(when (display-graphic-p) ;; Setting English Font (set-face-attribute 'default nil :font "Consolas 11") ;; Chinese Font (dolist (charset '(kana han symbol cjk-misc bopomofo)) (set-fontset-font (frame-parameter nil 'font) charset (font-spec :family "Microsoft Yahei" :size 16))))
在org中可以用 C-c C-x \
来预览数学符号。
Python简单的HTTP服务器。
# python 2 python -m SimpleHTTPServer 1070 # python 3 python -m http.server 1070
在org中使用 org-info.js
其中的 path
属性用于指定加载的js文件,默认是 http://orgmode.org/worg/code/org-info-js/org-info.js。
关于 org-info
的css跟js都托管到某个地方:
http://tilde.works/~isaac/assets/org-info.css http://tilde.works/~isaac/assets/org-info.js
org在导出html的时候默认有个样式,有两种方式可以去除。
- 全局的设置:
(setq org-html-head-include-default-style nil)
- 在org文件中设置:
#+OPTIONS: html-style:nil
让cygwin的软链接与Windows兼容。
其中 native
跟 nativestrict
都需要管理员权限(不同的是前者在失败的时候会回滚到原来的链接),还有一个需要注意的是 nativestrict
会导致lockfile的功能出错,一般是用 native
做 .emacs.d
的链接。参考链接
export CYGWIN="winsymlinks:lnk" export CYGWIN="winsymlinks:native" export CYGWIN="winsymlinks:nativestrict"
基于 helm-bibtex
来根据 .bbl
文件导出里面包含的引用条目,最后生成一个新的 .bib
文件。首先是从bbl文件中搜索出所有引用条目的key:
grep '\\bibitem{' manuscript.bbl | sed 's/^.*\\bibitem{\([^}]*\)}.*$/\1/'
导出来的key应该是以回车分隔的,把回车替换成 " "
然后头尾稍作修改就行了。
最后把导出的key放到下面代码的对应位置就行了
(progn (switch-to-buffer (generate-new-buffer "new.bib")) (--map (insert (bibtex-completion-make-bibtex it)) (-distinct '("Key1" "Key2"))))
Emacs下的字符串替换可以用 M-%
来做,依次输入被替换的和替换为的然后:
key | description |
---|---|
y | replace current match and continue |
n | skip current match and continue |
q | skip current match and quit |
. | replace current match and quit |
! | replace all the following matches |
Emacs中 solarized-theme
包的mode-line问题,默认的它的mode-line看上去字体会下沉,我还以为是字体设置的问题,搜了一下,原来是它默认的行为是给mode-line整行都加了下划线,而下划线是直接加在字符下方,就会使得字体看起来下沉了一下。有关这个问题repo上也有 相关讨论, 至于为什么要加这个下划线,作者给出的理由是本身solarized-theme设置的mode-line配色很浅,所以为了让它跟header-line有明显的额区隔所以加了一条线也就是下划线,弄清楚了原因,那么解决的方法有如下两种:
(setq x-underline-at-descent-line t)
: 更改下划线的行为,让它出现在整个字块的下面。(setq solarized-high-contrast-mode-line t)
: 采用solarized-theme提供的高对比度的mode-line配色。
隐藏 mode-line
中的 minor-mode
列表,mode-line中的 minor-mode
列表由 minor-mode-alist
定义,问题是这个列表是随当前加载的函数动态变化的,所以不能直接把它设置成nil,下面是一种变通的方法,每次载入函数后马上把它设置为nil。
(defun clear-minor-mode-alist (&rest _) (setq minor-mode-alist nil)) (add-hook 'after-load-functions 'clear-minor-mode-alist)
Emacs中 C-\
竟然可以切换输入法。
Windows下已经编译好的Python库 http://www.lfd.uci.edu/~gohlke/pythonlibs/
R语言里数据框的筛选和排序
a <- c(1,2,3,4) b <- c(5,6,7,8) c <- c(0,0,0,0) data.frame(a,b,c)[order(a,b),c(a,b)]
ffmpeg截取视频
ffmpeg -i yellowstone.mp4 -ss 00:00:07.5 -to 00:04:05 -c copy yellowstone_cut.mp4
Linux下查看占用磁盘空间
du -ah --max-depth=1 <PATH>
Deep Learning Tutorials
- http://www.cs.toronto.edu/~rsalakhu/kdd.html
- https://www.iro.umontreal.ca/~bengioy/talks/DL-Tutorial-NIPS2015.pdf
- http://www.iis.sinica.edu.tw/Workshop/dl2015/LEE.pptx
- http://www.vision.jhu.edu/tutorials/ICCV15-Tutorial-Math-Deep-Learning-Intro-Rene-Joan.pdf
- https://github.com/lisa-lab/DeepLearningTutorials
- http://deeplearning.net/tutorial/
- http://www.slideshare.net/tw_dsconf/ss-62245351
- http://www.deeplearningbook.org
在org文件头部执行lisp代码
# -*- org-todo-keyword-faces: (("WANT" . "yellow") ("DISPOSE" . "gray") ("NEED" . "red") ("HAVE" . "green")); -*-
Emacs中的复制粘贴
C-y
: to "paste" (called yank in Emacs)M-w
: to "copy" (called kill-ring-save in Emacs)C-w
: to "cut" (called kill-region in Emacs)
Windows的Chrome打开主页的快捷键是 Alt+Home
。
Google高级搜索: https://www.google.com/advanced_search
可以用下面的方法隐藏邮箱:
data:text/plain;chartset=UTF-8;base64,aW1qaWF4aUBnbWFpbC5jb20K
Emacs配置中尽量不要用 require
,要利用autoloads特性:
(load "evil-surround-autoloads")
Dropbox官方提供了一个单文件版本的Python脚本。
# Download the script for dropbox wget "https://www.dropbox.com/download?dl=packages/dropbox.py" # Give it permission of execution chmod u+x dropbox.py # Getting started dropbox.py help
解决 zsh compinit: insecure directories
的错误两种方法:
# Solution 1: autoload -Uz compinit compinit -u # Solution 2: compaudit #> There are insecure directories: #> /usr/share/zsh/site-functions #> /usr/share/zsh/5.0.6/functions #> /usr/share/zsh #> /usr/share/zsh/5.0.6 cd /usr/share/zsh chgrp -R Users . chmod -R g-w . compaudit
zsh主题:
Highly是个不错的摘录工具,我的json导出地址是 https://www.highly.co/user/caasi/export.json。
Twitter都要被收购了,瞬间感觉Path好顽强。https://path.com/profile/3Ik6Rtv
.gnupg
的权限:
chmod 700 ~/.gnupg chmod 600 ~/.gnupg/*
利用ffmpeg切割视频,例如要截取视频的1分钟到2分钟之间的视频片段,注意 -ss
选项需要在 -i
选项之前:
ffmpeg -ss 60 -i input.mp4 -t 120 -acodec copy -vcodec copy output.mp4
利用GPG加密文件。
# encrypt tar zcvf - foldername | gpg -c > foldername.tar.gz.gpg # decrypt gpg -d foldername.tar.gz.gpg | tar zxvf
利用 http://ix.io 的代码片段存储
账户是基于 .netrc
的,格式如下:
machine ix.io login [USERNAME] password [PWD]
下面是基本的一些用法,注意所有实名上传的代码片段可以在 http://ix.io/user/username 看到,另外上传的代码支持代码高亮,只要在它的URL后面加入 /python
之类的就行了。
# anonymous upload echo "some text" | ix cat filename.py | ix # nonymous upload cat filenmae.py | ix -n # delte some snippet ix -d ID # the
香水:
- CK one
- Issey Miyake
- Marc Jocobs Daisy
- Gucci the Flora Garden
- Chole Perfume
- Versace Bright Crystal
- Hermes Un Jardin Sur Le Nil
- Burberry Brit sheer
Windows批处理的小技巧,可以直接把文件拖放到bat文件上作为输入参数,其中 %~dp1
表示路径, %~nx1
表示文件名。
@echo off call foo.py %~dp1 %~nx1 pause
一段用来裁剪pdf图片的批处理代码,只要把要裁剪的pdf文件拖放到这个bat文件上就行了,生成的图片是适应了bounding box,直接插入论文就可以了。
@echo off pdfcrop %~nx1 tmp.pdf del %~nx1 ren tmp.pdf %~nx1 echo Done! pause
TeXLive包管理。
# set mirror tlmgr option repository http://mirrors.ustc.edu.cn/CTAN/systems/texlive/tlnet # update all packages tlmgr update --self --all
\(\LaTeX\)中并列插图。用 subcaption
包实现\(\LaTeX\)的多个插图并排。至于 subfig
包的话虽然已经被废弃了,但是他们还是会出现在一些期刊或者会议的模板里因为这些模板可能不兼容 subcaption
:
\usepackage{graphicx} \usepackage{subcaption} \begin{figure} \centering % one figure \begin{subfigure}[b]{.49\textwidth} \includegraphics[width=\textwidth]{example-image-a} \caption{Letter A.} \label{fig:a} \end{subfigure} % another figure \begin{subfigure}[b]{.49\textwidth} \includegraphics[width=\textwidth]{example-image-b} \caption{Letter B.} \label{fig:b} \end{subfigure} % global caption \caption{Two figures above.}\label{fig:anb} \end{figure}
SwitchyOmega的切换规则。
[SwitchyOmega Conditions] ; A line starting with semi-colon is a comment line, ignored by the parser. ; This is a HostWildcardCondition matching *.example.com. *.example.com ; This is a UrlWildcardCondition. UrlWildcard: https://*.google.com/* ; You can also write UW for short, representing the same UrlWildcardCondition. UW: https://*.google.com/* ; This is a UrlRegexCondition. Most types of conditions can be represented with :ConditionType pattern UrlRegex: ^https://www\.example\.(net|org)/ ; Conditions can be prefixed with ! to make it exclusive. Any requests matching an exclusive condition will ; use the "default profile" instead of "match profile". !*.internal.example.org ; Conditions are matched against the request in top-down order. ; The process stops as soon as the first matching condition is applied. ; If no other condition matches, the "default profile" will be used.
注意texlive安装路径中不要有空格,不然会有很多奇怪的问题。
用pandoc将包含中文的org文件转换为pdf文件。
pandoc --latex-engine=xelatex -V mainfont=SimSun input.org -o output.pdf
使用国内的PYPI源:
pip install matplot -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
在脚本中快速调用Emacs函数,下面的例子是将org文件转换为html。
# 单个文件 emacs input.org --batch --load init.el --eval '(org-html-export-to-html)' # Or emacs --batch --load init.el --visit foo.org -f org-html-export-to-html # 整个项目 emacs --batch --eval "(require 'org)" --eval "(org-publish-all)"
Emacs下的Ivy配置:
;; ivy (require-package 'ivy) (setq ivy-use-virtual-buffers t) (setq ivy-initial-inputs-alist nil) (global-set-key (kbd "C-x b") 'ivy-switch-buffer) ;; swiper (require-package 'swiper) (global-set-key (kbd "C-s") 'swiper) ;; counsel (require-package 'counsel) (global-set-key (kbd "M-x") 'counsel-M-x) (global-set-key (kbd "M-y") 'counsel-yank-pop) (global-set-key (kbd "C-x C-f") 'counsel-find-file) (global-set-key (kbd "C-h f") 'counsel-describe-function) (global-set-key (kbd "C-h v") 'counsel-describe-variable)
添加网页背景音乐:
<script> window.onload = function() { var snd = new Audio("hb.ogg"); snd.loop = true; snd.autoplay = true; } </script>
Windows下小巧的抓包工具RawCap
- 主页: http://www.netresec.com/?page=RawCap
- 特性: 可以抓取本地回路的包(如果用Wireshark的话会比较麻烦);非常小巧只有23KB;没有外部依赖;无需安装;可以抓取WiFi的包
- 运行的时候需要有管理员权限。
# 查看帮助信息 RawCap.exe --help # 抓取本地回路的包 RawCap.exe 127.0.0.1 localhost_cap1.pcap # 抓取某个网卡的包 RawCap.exe 3 ether1.pcap
ffmpeg流播
## 1. UDP # server side ffmpeg -i INPUT -f mpegts udp://127.0.0.1:1234 # client side ffplay udp://127.0.0.1:1234 ## 2. TCP (start client first) # client side ffplay tcp://127.0.0.1:1234?listen # server side ffmpeg -i INPUT -f mpegts tcp://127.0.0.1:1234 ## 3. RTSP on TCP (start clietn frist) # client side ffplay -rtsp_flags listen rtsp://127.0.0.1:1234/live.sdp?tcp # server side ffmpeg -i INPUT -f rtsp -rtsp_transport tcp rtsp://127.0.0.1:1234/live.sdp
tshark
是wireshark的命令行版本。
手册页: https://www.wireshark.org/docs/man-pages/tshark.html
# show network interfaces tshark -D # capture No.4 interface for 60 seconds and write to file test.pcap tshark -i 4 -a duration:60 -w test.pcap # filter rule tshark -r input.pcap -Y "ip.src==192.168.10.212" -w output.pcap
使用mutt来过滤邮件: http://www.mutt.org/doc/manual/#patterns-modifier
Pattern modifier | Description |
---|---|
~A | all messages |
~b EXPR | messages which contain EXPR in the message body |
=b STRING | messages which contain STRING in the message body. If IMAP is enabled, searches for STRING on the server, rather than downloading each message and searching it locally. |
~B EXPR | messages which contain EXPR in the whole message |
=B STRING | messages which contain STRING in the whole message. If IMAP is enabled, searches for STRING on the server, rather than downloading each message and searching it locally. |
~c EXPR | messages carbon-copied to EXPR |
%c GROUP | messages carbon-copied to any member of GROUP |
~C EXPR | messages either to: or cc: EXPR |
%C GROUP | messages either to: or cc: to any member of GROUP |
~d [/MIN/]-[/MAX/] | messages with “date-sent” in a Date range |
~D | deleted messages |
~e EXPR | messages which contains EXPR in the “Sender” field |
%e GROUP | messages which contain a member of GROUP in the “Sender” field |
~E | expired messages |
~F | flagged messages |
~f EXPR | messages originating from EXPR |
%f GROUP | messages originating from any member of GROUP |
~g | cryptographically signed messages |
~G | cryptographically encrypted messages |
~h EXPR | messages which contain EXPR in the message header |
#ERROR | messages which contain STRING in the message header. If IMAP is enabled, searches for STRING on the server, rather than downloading each message and searching it locally; STRING must be of the form “header: substring” (see below). |
~H EXPR | messages with a spam attribute matching EXPR |
~i EXPR | messages which match EXPR in the “Message-ID” field |
~k | messages which contain PGP key material |
~L EXPR | messages either originated or received by EXPR |
%L GROUP | message either originated or received by any member of GROUP |
~l | messages addressed to a known mailing list |
~m [/MIN/]-[/MAX/] | messages in the range MIN to MAX *) |
~n [/MIN/]-[/MAX/] | messages with a score in the range MIN to MAX *) |
~N | new messages |
~O | old messages |
~p | messages addressed to you (consults alternates) |
~P | messages from you (consults alternates) |
~Q | messages which have been replied to |
~r [/MIN/]-[/MAX/] | messages with “date-received” in a Date range |
~R | read messages |
~s EXPR | messages having EXPR in the “Subject” field. |
~S | superseded messages |
~t EXPR | messages addressed to EXPR |
~T | tagged messages |
~u | messages addressed to a subscribed mailing list |
~U | unread messages |
~v | messages part of a collapsed thread. |
~V | cryptographically verified messages |
~x EXPR | messages which contain EXPR in the “References” or “In-Reply-To” field |
~X [/MIN/]-[/MAX/] | messages with MIN to MAX attachments *) |
~y EXPR | messages which contain EXPR in the “X-Label” field |
~z [/MIN/]-[/MAX/] | messages with a size in the range MIN to MAX ) *) |
~= | duplicated messages |
~$ | unreferenced messages (requires threaded view) |
~(PATTERN) | messages in threads containing messages matching PATTERN, e.g. all threads containing messages from you: ~(~P) |
Bash下输入多行文本:
用 cat << EOF
就行了,最后要结束的时候输入 EOF 就行了。所以可以这样来写邮件正文
mutt -s "Subject here." whowhowho@gmail.com < cat <<EOF
Vim在可视模式的几个技巧:
V
: 进入针对行的可视操作。o
: 切换高亮选取的活动端。
ffmpeg参数:
-r |
rate (20fps) |
-s |
size (480x320) |
-b |
bitrate (500kbps) |
下载Youtube视频,注意Youtube提供多种格式的视频,除了普通的流播视频格式,它全线支持MPEG-DASH,而且高码率的流只有DASH协议,它的音视频是分离的,所以下载下来后需要手动合并,可以用ffmpeg来合并: ffmpeg -i video.mp4 -i audio.m4a -c copy output.mp4
- Savedeo: 网站可以输出所有格式,提供复制链接。
- Youtube-dl: 功能强大,基于Python的单文件。
- You-Get: 同样也是基于Python的,可以下载很多网站的视频。
- 硕鼠Youtube专用下载器: Windows下的图形界面,操作简单。
利用 tcpdump
抓包
# run for 15 seconds tcpdump -i eth0 -G 15 -W 1 -w output.pcap
利用 darkstat
来进行流量统计:
darkstat -i eth0 -b 127.0.0.1 -p 1234
直接在终端上传文件到Box网盘:
curl -u me@email.com:mypassword -T local_file_path https://dav.box.com/dav/remote_file_name curl -u me@email.com:mypassword https://dav.box.com/dav/remote_file_name --output download_file_path
百度云盘上传下载脚本: 主页: https://github.com/houtianze/bypy
# authorize first bypy # upload bypy upload somefile.txt # download bypy downfile somefile.txt
rsync的使用
rsync -r user@192.168.10.212:/home/user/somefolder/ localfolder
Windows下磁盘检查和清理工具
- CCleaner: https://www.piriform.com/ccleaner
- Dism++: https://www.chuyu.me/
- SpaceSniffer: http://www.uderzo.it/main_products/space_sniffer/
- TreeSize: https://www.jam-software.com/treesize_free/
Bento4处理视频
# 1. Fragment videos mp4fragment input.mp4 output.mp4 # 2. Multiplex tracks to one video mp4mux --track input1.mp4#track=video --track input2.mp4#track=video input2.mp4#track=audio mux.mp4 # 3. Generate mpd mp4dash -o output/
用MP4Box来进行Dash打包
mp4box -dash 5000 -frag 1000 \ -rap -frag-rap \ -segment-name $RepresentationID$/apple_$Number$$Init=init$ \ -out apple/stream.mpd \ apple_1000.mp4#video:id=apple_1000bps \ apple_2000.mp4#video:id=apple_2000bps \ apple_2000.mp4#audio:id=apple_audio
快速提交到Github:
#!/bin/sh git add . if [ $# -eq 1 ]; then git commit -am "$1" else git commit -am "update" fi git push
泛用型打包工具:
Emacs中处理文本中的回车符 (carriage return):
; display ^M (setq inhibit-eol-conversion t)
M-%
: esc % on Mac X11 EmacsC-q C-m RET
: specifies ^M to replaceC-q C-j RET
: specifies a line return as the replacement!
: runs the replace on the entire file
Atom换用国内源:
添加文件 C:\Users\USERNAME\.atom\.apmrc
:
registry=https://registry.npm.taobao.org/ strict-ssl=false
Emacs下配置hunspell:
- hunspell的词典需要另外下载
- 词典文件放到路径
/usr/share/hunspell
,这是其中一个词典搜索路径,详细的可以通过hunspell -D
查看。 - 如果是在Emacs中,需要设置本地的环境变量
(setenv "DICTIONARY" "en_US")
以便hunspell调用指定的词典。
zsh_stats
可以显示常用命令的统计信息。
zsh配置文件加载顺序,所有这些文件的位置是由环境变量 $ZDOTDIR
控制的,默认是 $HOME
:
.zshenv
: all invocations.zprofile
: when login.zshrc
: when interactive.zlogin
: when login.zlogout
: when logout
dos2unix
and unix2dos
:
Dos2unix软件包包括工具"dos2unix"和"unix2dos",用于纯文本文件在DOS或Mac格式与Unix格式之间相互转换。
DOS/Windows的文本文件中,断行符是由两个字符共同表示的:回车符(CR)和换行符(LF)。Unix的文本文件中,换行符则由单(LF)表示。而Mac的文本文件则由单个回车符(CR,用于Mac OS X之前的系统)或单个换行符(LF,用于当下的新Mac OS)表示。
除了断行符,Dos2unix还可以转换文件编码。一些DOS码页可以被转换为Unix Latin-1,Windows Unicode(UTF-16)文件也可以被转换为Unix Unicode(UTF-8)文件。
建立locate数据库:
# specify the search path and database file to be generated updatedb --locatepaths='/home/isaac/Documents /home/isaac/.mail/' --output=/home/isaac/Downloads/locatedb # use locate with the generated databsed file locate -d /home/isaac/locatedb
Living in China’s Expanding Deserts - The New York Times
Text-based web browsers:
- links: http://links.twibright.com/
- lynx: http://lynx.browser.org/
- w3m: http://w3m.sourceforge.net/
- elinks: http://elinks.or.cz/
Wireshark报错的解决方案:
- 报错: The NPF driver isn't running.
- 解决:
net start npf
matplotlib支持的颜色
import matplotlib print(matplotlib.colors.cnames)
利用matplotlib保存pdf格式时控制bounding box:
# 控制四周的边界 plt.tight_layout(rect = [0, 0, 0.4, 1]) # 设置tight参数 plt.savefig("test.pdf", bbox_inches='tight', pad_inches=0)
一行Perl代码实现dos2unix的功能:
perl -pi -e 's/\r\n/\n/g' in.txt
使用bitpocket与服务器双向同步:
# Repo: https://github.com/sickill/bitpocket # server side mkdir ~/master # client side mkdir ~/slave; cd ~/slave bitpocket init jiaxi@server.com ~/master # start sync bitpocket sync
网页顶端的彩条,图片文件在: http://imgur.com/a/DyAPD
#banner { background-image: url('border.png'); background-repeat: repeat-x; background-size: 40px 3px; width:100%; height:30px; }
Python中计算滑动平均的两种方法:
import pandas as pd # Method 1. use on DataFrame data = {'score': [1, 1, 1, 2, 2, 2, 3, 3, 3]} df = pd.DataFrame(data) pd.rolling_mean(df, window=2, min_periods=1) # Method 2. use on Series ds = pd.Series([1, 1, 1, 2, 2, 2, 3, 3, 3]) ds.rolling(window=2, min_periods=1).mean()
org做表格的一个例子
|---------+---------------+------------------| | airmass | zenith_seeing | delivered_seeing | |---------+---------------+------------------| | 1.3 | 1.1 | 1.2875340 | | 1.1 | 1.2 | 1.4045825 | | 1.3 | 1.9 | 2.2239223 | |---------+---------------+------------------|
org里面调用calc来进行泰勒展开
#+BEGIN_SRC calc taylor(sin(x),x,6) #+END_SRC
org可以直接在行内运行代码插入结果
The scaling for 1.3 airmasses is src_{format(1.3**(3.0/5.0),digits=3)} The scaling for 1.3 airmasses is src_{round(1.3**(3.0/5.0),4)} The scaling for 1.3 airmasses is src_{return "%4.1f" % (1.3**(3.0/5.0))}
直接在org里面通过R操作表格
| airmass | zenith_seeing | delivered_seeing | |---------+---------------+------------------| | 1.3 | 0.95 | 1.1119612 | | 1.3 | 1.0 | 1.1704854 | | 1.3 | 1.1 | 1.2875340 | | 1.3 | 1.2 | 1.4045825 | #+BEGIN_SRC R :exports both :results output graphics :var delsee=delsee :file delsee-r.png :width 400 :height 300 library(ggplot2) p <- ggplot(delsee, aes(zenith_seeing, delivered_seeing)) p <- p + geom_point() p #+END_SRC
通过R来生成表格插入到org
#+BEGIN_SRC R :colnames yes d <- data.frame(foo=c('a','b','n'), bar=c(1.0/3.0,22,32)) d #+END_SRC
从org导出到中文pdf
ebib配置
;; ebib (require-package 'ebib) (add-to-list 'evil-emacs-state-modes 'ebib-index-mode) (add-to-list 'evil-emacs-state-modes 'ebib-entry-mode) (setq ebib-index-display-fields '(title)) (setq ebib-file-search-dirs (list (concat org-directory "pdf"))) (setq ebib-notes-directory (concat org-directory "org")) (setq ebib-bib-search-dirs (list (concat org-directory "org/bib"))) (setq ebib-preload-bib-files '("main.bib")) (setq ebib-notes-use-single-file (concat org-directory "org/research-notes.org")) (setq ebib-notes-template "* %C\n:PROPERTIES:\n%K\n:END:\n>|<\n") (with-eval-after-load "ebib" (add-to-list 'ebib-notes-template-specifiers '(?C . ebib-create-org-custom-title))) (defun ebib-create-org-custom-title (key db) "Return a custom title with year infomation only." (let ((title (or (ebib-db-get-field-value "title" key db 'noerror 'unbraced 'xref) "(No Title)")) (year (or (ebib-db-get-field-value "year" key db 'noerror 'unbraced 'xref) "????"))) (remove ?\n (format "%s (%s)" title year))))
Emacs方便的字数统计: M-=
isync本地子目录的问题
- 在配置mbsync的本地路径中如果是包含子目录的话,那么在每个子目录前面会默认有一个
.
,据说这是legacy的方式。 - 目前发布的1.2.1版本的isync不支持自定义子目录样式: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=758172
- 在isync的git最新版代码库(1.3.0)中可以通过
SubFolders
选项配置,写入SubFolders Verbatim
即为理想的子目录格式。
solarized-theme
默认的亮色modeline是有个下划线的,作者说是为了提高区分度(所以这个下划线在高对比度下是没有的),但是关键在于下划线这个东西系统默认是在字体的中下方,也就是会挡住下沉的部分,所以会影响视觉效果,当然可以通过选项来调整下划线的行为,但是这样做是具有全局破坏性的,所以下面这行代码就是让这个下划线不管是在高对比度还是低对比度的modeline中都不要使用。
(s-mode-line-underline (if solarized-high-contrast-mode-line nil nil))
使用 powerline
隐藏minor mode列表
- minor mode列表会占用大面积的mode-line空间,但其实从来都不必关心它。
- powerline支持主题,默认主题中把那行设计minor mode的代码删除就可以了。
git中加入上游仓库
# add remote repo git remote add upstream git@github.com:milkypostman/powerline.git # fetch upstream git fetch upstream # merge code git merge upstream/master
如果Visio导出为pdf的bounding box总是不对,在导出时候的选项中把“辅助功能文档结构标记”取消勾选就行了。
美国洛杉矶一年十刀套餐(768m内存20g硬盘2t流量): https://hostus.us/
RSS全文输出
- http://fulltextrssfeed.com: 不限抓取上限,成功率极其不稳定。
- http://morss.it/: 不限抓取上限,成功率非常不稳定。
- http://hzmn.info/full-content-rss/: 抓取上限10条,无广告,成功率较高。
- https://feedenlarger.com/: 抓取上限10条,无广告,成功率较高,网站不稳定。
- https://freefullrss.com/: 抓取上限5条,无广告,成功率较高。
- https://feedex.net/: 不限抓取上限,但速度很慢很慢。
exiftool读取图片的EXIF信息: http://www.sno.phy.queensu.ca/~phil/exiftool/
org导出html时候的代码高亮
- 代码高亮是由 htmlize 包提供的功能
- 高亮模式由
org-html-htmlize-output-type
控制: inline-css, css, font - 默认的配色是从UI(即emacs主题)中继承的,所以如果是batch模式的话就是没有颜色的了
- 可以通过以下的方式来让它调用外部的css来进行代码高亮,这样就跟UI无关了
(setq org-html-htmlize-output-type 'css) (setq org-html-head-extra \"<link rel='stylesheet' href='http://jiaxi.sdf.org/css/highlight.css'>\")
ggplot2中调整图表的长宽比例
plot + coord_fixed(ratio=10)
: 这种方法的缺点在于这里的比例是跟数据挂钩的。plot + theme(aspect.ratio=9/16)
: 这种方法好处在于跟数据无关。
用一个org文件来管理所有博客文章
- 参考: http://anbasile.github.io/2016/11/15/howiwrite/
- 把文章放入一级标题中,然后把subtree导出为markdown文章。
* How I write this blog :PROPERTIES: :EXPORT_FILE_NAME: 2016-11-15-howiwrite :END: #+BEGIN_EXPORT html --- layout: post title: How I write this blog --- #+END_EXPORT I write all my posts in emacs org-mode. I keep eve...
Ascii art
Small Slant
___ _ _____ __ / (_)__ ___ __ (_) / ___/_ __ / // / / _ `/\ \ // / / (_ / // / \___/_/\_,_//_\_\/_/ \___/\_,_/
Sub-Zero
__ __ ______ __ __ __ ______ __ __ /\ \ /\ \ /\ __ \ /\_\_\_\ /\ \ /\ ___\ /\ \/\ \ _\_\ \\ \ \\ \ __ \\/_/\_\/_\ \ \ \ \ \__ \\ \ \_\ \ /\_____\\ \_\\ \_\ \_\ /\_\/\_\\ \_\ \ \_____\\ \_____\ \/_____/ \/_/ \/_/\/_/ \/_/\/_/ \/_/ \/_____/ \/_____/
Larry 3D
_____ ____ /\___ \ __ __ /\ _`\ \/__/\ \ /\_\ __ __ _ /\_\ \ \ \L\_\ __ __ _\ \ \\/\ \ /'__`\ /\ \/'\\/\ \ \ \ \L_L /\ \/\ \ /\ \_\ \\ \ \ /\ \L\.\_\/> </ \ \ \ \ \ \/, \\ \ \_\ \ \ \____/ \ \_\\ \__/.\_\/\_/\_\ \ \_\ \ \____/ \ \____/ \/___/ \/_/ \/__/\/_/\//\/_/ \/_/ \/___/ \/___/
自适应码率串流建议的segment length为2至10秒。
The segment size can vary depending on the particular implementation, but they are typically between two (2) and ten (10) seconds.
org的每一个章节都可以单独设置属性,VISIBILITY属性包括: folded, children, content, all
:PROPERTIES: :VISIBILITY: folded :END:
info-js的可选项
- path: Absolute or relative URL to the script
- view: info, overview, content, showall
- toc:
t
,nil
… - ltoc:
t
,nil
,above
- mouse:
underline
,#dddddd
- buttons: If 't', display the little Up|HOME|HELP|Toggle view links next to each headline in plain view mode.
org导出html的几个css样式
Use socks proxy in curl
curl -O https://pdfs.semanticscholar.org/2a26/efb0096d535bd4c27b1ec05fe8aaa7cb166c.pdf --socks5 127.0.0.1:1080
Windows笔记本
- Microsoft Surface Book: https://www.microsoftstore.com.cn/surface/surface-book/p/mic1625
- Lenovo Thinkpad X1 Carbon: http://thinkpad.lenovo.com.cn/product/34727.html
- Dell XPS 13: http://china.dell.com/cn/p/xps-laptops
HP Spectre: http://www.hpstore.cn/spectre-13-v117tu-1.html
orgmode中指定字体
orgmode中 C-c C-o
打开链接。
brew删除一个程序连同它的依赖。
brew rm FORMULA brew rm $(join <(brew leaves) <(brew deps FORMULA))
basictex
里面按照缺少的文件搜索包
tlmgr search --global --file algorithm.sty
Mac软件签名
sudo codesign --force --deep --sign - /Applications/Folx.app/
Homebrew下载的文件缓存目录: ~/Library/Caches/Homebrew
vim与系统剪贴板交互
:.!pbcopy "Copy current line clipboard :4,8!pbcopy "Copy line 4 to 8 :!echo "%:p" | pbcopy "Copy current filename to clipboard :r !pbpaste "Paste clipboard content to current line
Mac下的Emacs无法响应mouse-2事件,可以用以下的方法来让flyspell中的右键起作用:
(eval-after-load "flyspell" '(progn (define-key flyspell-mouse-map [down-mouse-3] #'flyspell-correct-word) (define-key flyspell-mouse-map [mouse-3] #'undefined)))
MacOS重启、睡眠的快捷键
Ctrl+Shift+Power
: 关闭屏幕Cmd+Opt+Power
: 睡眠 (sleep)Cmd+Ctrl+Power
: 重启 (restart)Cmd+Ctrl+Opt+Power
: 关机 (shutdown)
递归删除当前目录下的 .DS_Store
文件:
find . -name '*.DS_Store' -type f -delete
Android保持屏幕常亮的两种方法
写到Activity里面
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }
写到布局的xml里面
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:keepScreenOn="true"> ... </RelativeLayout>
Android的文件读写
private void createDataFile() { filename = "foobar" + "_" + System.currentTimeMillis() + ".csv"; realfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), filename); try { FileWriter writer = new FileWriter(realfile, false); writer.write("type,time,value1,value2,value3,value4\n"); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
通过网络调试Andorid应用
./adb tcpip 5555 ./adb connect 192.168.199.180
Debian打包,在源码目录下操作:
dpkg-buildpackage -us -c
Ubuntu安装管理deb包
# install package dpkg -i xxx.deb # remove package dpkg -r xxx # list installed packages dpkg -l
Emacs下根据当前时间来动态切换明暗主题
;; theme-changer (use-package theme-changer :if window-system :config (change-theme 'solarized-light 'solarized-dark))
Emacs中设置fringe的背景色
(set-face-attribute 'fringe nil :background "#030303")
MacOS重建LaunchPad图标
defaults write com.apple.dock ResetLaunchPad -bool true;killall Dock
orgmode导出模板
#+TITLE: Foo Bar
Linux修改Capslock键
# capslock as ctrl setxkbmap -option ctrl:nocaps # swap capslock and ctrl setxkbmap -option ctrl:swapcaps
Android中使用ndk-build来引入C/C++支持
文件结构
~/Desktop/MyApplication ├── MyApplication.iml ├── app │ ├── app.iml │ ├── build │ ├── build.gradle │ ├── libs │ ├── proguard-rules.pro │ └── src │ ├── androidTest │ │ └── java │ │ └── com │ └── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ ├── jni │ │ ├── Android.mk │ │ ├── Application.mk │ │ └── MyLibrary.cpp │ ├── libs │ └── res ├── build ├── build.gradle ├── gradle ├── gradle.properties ├── gradlew ├── gradlew.bat ├── local.properties └── settings.gradle
build.gradle
android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.google.android.myapplication" minSdkVersion 19 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" ndk { moduleName "MyLibrary" cFlags "-std=c++11 -fexceptions" stl "gnustl_shared" } } sourceSets.main { jni.srcDirs = ['src/main/jni'] // This prevents the auto generation of Android.mk jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project. } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } externalNativeBuild { ndkBuild { path 'src/main/jni/Android.mk' } } }
MainActivity.java
static { System.loadLibrary("MyLibrary"); } public native String helloFromJNI();
Android.mk
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := MyLibrary LOCAL_SRC_FILES =: MyLibrary.cpp include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_MODULES := MyLibrary APP_ABI := all
MyLibrary.cpp
文件中的方法可以先在java类中用native定义,然后由IDE提示来生成,
Android使用cmake来加入C/C++支持
目录结构
. ├── README.md ├── app │ ├── CMakeLists.txt │ ├── app.iml │ ├── build │ ├── build.gradle │ ├── libs │ └── src │ └── main │ ├── AndroidManifest.xml │ ├── ant.properties │ ├── assets │ ├── build.xml │ ├── java │ ├── jni │ │ ├── include │ │ └── native-jni.c │ └── project.properties ├── build ├── build.gradle ├── gradle ├── gradle.properties ├── gradlew ├── gradlew.bat ├── local.properties └── settings.gradle
build.gradle
defaultConfig { minSdkVersion 19 targetSdkVersion 25 externalNativeBuild { // For ndk-build, instead use the ndkBuild block cmake { // Passes optional arguments to CMake. arguments "-DANDROID_TOOLCHAIN=clang" } } } externalNativeBuild { cmake { path 'CMakeLists.txt' } }
CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1) add_library(native-jni SHARED src/main/jni/native-jni.c ) include_directories(src/main/jni/include/) target_link_libraries(native-jni android log)
Native.jni.c
#include <jni.h> #include <string.h> JNIEXPORT jstring JNICALL Java_org_gearvrf_gvr360video_Minimal360VideoActivity_stringFromJNI(JNIEnv *env, jobject instance) { return (*env)->NewStringUTF(env, "hello from jni"); }
MainActivity.java
static { System.loadLibrary("native-jni"); } public native String stringFromJNI();
MacOS下用C语言调用ffmpeg库(libav等)
注意源代码包含libav相关的头文件需要用 extern "C"
, 而且文件名需要用比如说 foo.cc 而不是 foo.c.
#include <stdlib.h> #include <stdio.h> #include <string.h> extern "C" { #include "libavcodec/avcodec.h" #include "libavutil/mathematics.h" } int main(int argc, char **argv) { AVCodec *codec; codec = avcodec_find_encoder(AV_CODEC_ID_MP2); printf("hello"); return 0; }
编译时候需要这么做:
g++ foo.cc $(pkg-config --libs --cflags libavformat)
MacOS下配置 irony-mode
- 到LLVM网站上下载Clang Source Code,需要用到它的头文件。
- 对于
libclang.dylib
, 我们使用的是Xcode的,路径应该在/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/
在emacs下执行
irony-install-server
, 注意把Clang的include路径加上,当然还有那个libclang.dylib
。cmake -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON -DLIBCLANG_LIBRARY=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libclang.dylib -DLIBCLANG_INCLUDE_DIR=/Users/jiaxi/Downloads/cfe-3.9.1.src/include/ -DCMAKE_INSTALL_PREFIX=/Users/jiaxi/.emacs.d/irony/ /Users/jiaxi/.emacs.d/elpa/irony-20170223.515/server && cmake --build . --use-stderr --config Release --target install
Org-mode中预览数学符号快捷键: C-c C-x C-l
购买美区礼品卡
使orgmode导出的html文件打印到pdf更美观: https://github.com/BafS/Gutenberg
利用ImageMagick指定LZW算法压缩eps文件
This works great on rasterized images; for vector graphics, this will rasterize everything, which may not be what we’re looking for.
convert input.eps -compress lzw eps2:output.eps
Change Maps language in MacOS
# change to Chinese defaults write com.apple.maps AppleLanguages '(zh-CN)' # change to English defaults write com.apple.maps AppleLanguages '(en-US)'
显示系统所有的环境变量
printenv
vim变量的设置
:set - shows vars different from defaults :set all - shows all values :set foo? - shows the value of foo :set foo+=opt - add opt to the value w/o changing others :set foo-=opt - remove opt from value :set foo& - reset foo to default value :setlocal foo - only the current buffer
org导出的html不包含默认的样式:
(setq org-html-head-include-default-style nil)
\(\LaTeX\)项目的Makefile:
TEX=pdflatex -shell-escape -interaction=nonstopmode -file-line-error BIB=bibtex NAME=main # Test if latexmk is available and not buggy (like on my Windows machine...) HAS_LATEXMK=FALSE ifneq (,$(shell which latexmk)) ifeq (0,$(shell latexmk --help > /dev/null 2>&1; echo $$?)) HAS_LATEXMK=TRUE endif endif .PHONY: all clean rebuild .SILENT: all : $(NAME).pdf ifeq ($(HAS_LATEXMK),TRUE) # latexmk available $(NAME).pdf: $(NAME).tex $(NAME).bib @latexmk -pdf -quiet $(NAME).tex rebuild: @latexmk -pdf -quiet -gg $(NAME).tex clean: @latexmk -C $(NAME).tex @rm -f $(NAME).bbl $(NAME).vtc $(NAME).synctex.gz comment.cut @rm -rf auto latex.out else # latexmk unavailable $(NAME).pdf : $(NAME).tex $(NAME).bbl $(NAME).blg $(TEX) $(NAME).tex $(TEX) $(NAME).tex $(NAME).bbl $(NAME).blg : $(NAME).bib $(NAME).aux $(BIB) $(NAME) $(NAME).aux: $(NAME).tex $(TEX) $(NAME).tex clean: @rm -f $(NAME).aux $(NAME).bbl $(NAME).blg $(NAME).log $(NAME).out \ $(NAME).vtc $(NAME).fdb_latexmk $(NAME).fls $(NAME).synctex.gz latex.out comment.cut @rm -rf auto latex.out endif
Adaptation 和 Adaption 的区别
Adaption and adaptation are different forms of the same word, and they share all their meanings, which include (1) the act of changing to suit new conditions, and (2) a work of art recast in a new form or medium. But the longer word, adaptation, is preferred by most publications and is much more common. Adaption is not completely absent, but it usually gives way to the longer form in edited writing.
Both forms are old. The OED lists examples of adaption from as long ago as the early 17th century. Adaptation is just a little older, having come to English from French in the middle 16th century. Adaption has never been the preferred form, though, and in fact has grown less common relative to adaptation over the centuries.
It’s possible that some English speakers now view adaptation and adaption as separate words each with their own uses, but any such emerging differentiation is not yet borne out in general usage. For now, at least, adaption always bears replacement with the more common form.
插图配色
Set1: "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF" Set2: "#66C2A5" "#FC8D62" "#8DA0CB" "#E78AC3" "#A6D854" "#FFD92F" "#E5C494" "#B3B3B3" Set3: "#8DD3C7" "#FFFFB3" "#BEBADA" "#FB8072" "#80B1D3" "#FDB462" "#B3DE69" "#FCCDE5"
Ubuntu下编译Vim 8.0 with python3
./configure \ --enable-python3interp=yes \ --with-python3-config-dir=/usr/lib/python3.4/config-3.4m-x86_64-linux-gnu \ --prefix=/usr/local/vim make make install
Ubuntu下编译opencv with opencv_contrib
git clone git@github.com:opencv/opencv.git git clone git@github.com:opencv/opencv_contrib.git cd opencv mkdir build; cd build cmake \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr/local/opencv-3.2 \ -DPYTHON3_EXECUTABLE=/usr/bin/python3 \ -DPYTHON3_INCLUDE_DIR=/usr/include/python3.4m \ -DPYTHON3_INCLUDE_DIR2=/usr/include/x86_64-linux-gnu/python3.4m \ -DPYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.4m.so \ -DPYTHON3_NUMPY_INCLUDE_DIRS=/usr/local/lib/python3.4/dist-packages/numpy/core/include/ \ -DPYTHON2_EXECUTABLE=/usr/bin/python2 \ -DPYTHON2_INCLUDE_DIR=/usr/include/python2.7 \ -DPYTHON2_INCLUDE_DIR2=/usr/include/x86_64-linux-gnu/python2.7 \ -DPYTHON2_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7.so \ -DPYTHON2_NUMPY_INCLUDE_DIRS=/usr/local/lib/python2.7/dist-packages/numpy/core/include/ \ .. make sudo make install
Ubuntu下编译ffmpeg
./configure \ --prefix=/usr/local/ffmpeg-3.2.4 \ --pkg-config-flags="--static" \ --enable-shared \ --enable-gpl \ --enable-libass \ --enable-libfdk-aac \ --enable-libfreetype \ --enable-libmp3lame \ --enable-libopus \ --enable-libtheora \ --enable-libvorbis \ --enable-libvpx \ --enable-libxvid \ --enable-libx264 \ --enable-libx265 \ --enable-sdl \ --enable-nonfree make sudo make install
eps文件bounding box自动适应图像
ps2epsi <input.eps> <output.eps>
Vim 8自带的插件管理目录结构
.vim ├── pack │ └── plugins │ ├── opt │ └── start │ ├── auto-pairs │ ├── nerdcommenter │ ├── vim-airline │ ├── vim-rsi │ └── vim-surround └── vimrc
方便的代码片段分享,放到bash里的别名
# pastebins alias ix="curl -F 'f:1=<-' http://ix.io" alias ptpb="curl -F 'c=<-' https://ptpb.pw" alias sprunge="curl -F 'sprunge=<-' http://sprunge.us"
Vim识别的gnuplot文件后缀是 .gpi
orgmode导出pdf时去掉作者跟日期
R语言在orgmode中的绘图设置
- orgmode的绘图机制应该是自动在开头设置一个device,所以代码里面需要判断是否存在device
mar
参数是设置绘图的左下右上的边界距离,tcl
是控制刻度长度(可以是负值),mgp
是控制标签、刻度值、刻度的位置,这里距离的单位都是 mex.- 最后输出注释掉是因为如果是orgmode导出的话就不是一个图形device,所以没法copy。
# Solution 1: #+BEGIN_SRC R :exports both :results graphics :file img1.png :width 700 :height 450 :res 90 par(mar=c(2,2,0,0), tcl=0.5, mgp=c(1,0,0)) plot(rnorm(100), xlab="label_x", ylab="label_y") ## dev.copy2eps(file="new.eps") #+END_SRC # Solution 2: #+BEGIN_SRC R :exports both :results output graphics both :file img2.png :width 400 :height 300 library(ggplot2) df <- data.frame(x1=c(1,2,3,4), x2=c(3,4,5,6)) p <- ggplot(df, aes(x=x1, y=x2)) + geom_line() ggsave("foo.eps", p, width=7, height=4) p #+END_SRC
Auctex通过 C-c C-o C-b
来折叠环境。
Apple Mail会把只有一页的文档附件内嵌(inline)到邮件正文中,可以这样来关闭这个功能:
# disable inline attachment viewing defaults write com.apple.mail DisableInlineAttachmentViewing -bool yes # enable inline attachment viewing defaults write com.apple.mail DisableInlineAttachmentViewing -bool no
Matplotlib画图的一些配置
import matplotlib.pyplot as plt plt.style.use('classic') plt.rc('font', **{'family': 'sans-serif', 'serif': ['Times', 'Times New Roman'], 'sans-serif': ['Helvetica', 'Arial'], 'size': 14.0}) plt.rc('figure', figsize=[6.4, 4.0])
为什么样本方差(sample variance)的分母是\(n-1\)而不是\(n\):
- 因为按照方差(variance)的定义,它需要一个总体均值,而这个值靠样本是无从得知的,样本均值是已知的,所以自由度减少了一。
- 因为需要保证方差的估计是无偏估计(unbiased estimator),即\(\mathbb{E}(S^2)=\sigma^2\)。 我们把方差记作\(\sigma^2\),继续来看样本方差\(S^2=\frac{1}{n-1}\sum_{i=1}^n(X_i - \bar{X})^2\),对它求期望: \[ \mathbb{E}(S^2)=\mathbb{E}[\frac{1}{n-1}\sum_{i=1}^n(X_i-\bar{X})^2]=\sigma^2 \] 刚好是方差的无偏估计,所以这个分母\(n-1\)也是合理的。
n 阶矩阵 A 相似于对角矩阵的充分必要条件是 A 有 n 个线性无关的特征向量。
读Facebook发表于2017-04-20的一篇博客, 介绍了立方投影的以下三点好处:
- 没有几何变形(geometry distortion);
- 像素是均匀分布的;
- 投影更加简单,每一个面只会投影到跟它对应的表面上。
学习了以下几个知识点:
- K-means,它的核心思想其实就是EM算法。它的缺点是对离群点敏感,对以下情况效果不好:各个类的规模相差很大、密度分布不均,形状不规则。
- 马氏距离、协方差矩阵,它的思想是考虑数据点的分布。
- PCA、相似矩阵、相似对角化、特征向量和特征值(相当于用某空间下的一组基来表示其上的点)
- 雅可比矩阵,海森矩阵,海森矩阵的正定半正定定义了函数的凹凸性。
- EM算法的推导,主要解决的问题是估计来自不同分布的数据的参数,同时也可以以此做聚类,核心是将含未知分布的极大似然估计,运用Jensen不等式求下界,然后调整参数,反复迭代。详细见 课件。
- 由EM导出混合高斯模型。
R语言设置包仓库
# get repository url getOption("repos") # set repository options(repos="https://mirrors.tuna.tsinghua.edu.cn/CRAN")
Rscript接收参数
args <- commandArgs(TRUE) if (length(args) < 4) { print("./thisfile.r <tp_file> <vid_name> <seg_len> <sample_len>") quit(save="no", status=1) } tp_file <- args[1] vid_name <- args[2]
Vim里面强制保存
:w !sudo tee %”
MoneyWiz导出的 moneywiz.csv
文件转换成ledger支持的格式
- csv文件预处理:
./moneywiz.awk moneywiz.csv > moneywiz-tmp.csv
,这里需要注意的是moneywiz里面的转账会在相关(转入&转出)账户中各自创建一笔记录,如果直接解析到ledger的格式会导致重复计算,所以只能这里需要考虑删除重复的转账记录。
#!/usr/bin/env gawk -f BEGIN { # ignore commas in quotes # FS = "," FPAT = "[^,]*|\"[^\"]*\"" print("\"account\",\"date\",\"amount\",\"currency\",\"category\",\"payee\",\"description\",\"memo\",\"balance\",\"type\"") } NR > 2 { name = $1 current_balance = $2 account = $3 transfers = $4 description = $5 payee = $6 gsub(" > ", ":", $7) category = $7 date = $8 memo = $9 amount = $10 currency = $11 check = $12 tags = $13 balance = $14 if (account == "\"\"" || account == "") { next } if (match(amount, "-")) { type = "\"Expenses\"" } else { type = "\"Income\"" } if (transfers != "\"\"" && transfers != "") { type = "\"Transfers\"" payee = transfers # skip duplicating transactions of transfers am = amount gsub("-", "", am) gsub("+", "", am) if (seen[account"-"transfers"-"date"-"am]++ || seen[transfers"-"account"-"date"-"am]++) { next } } printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", account, date, amount, currency, category, payee, description, memo, balance, type) }
- 根据规则文件将处理过后的csv文件转换成ledger格式1,执行
hledger -f moneywiz-tmp.csv print > moneywiz.ledger
# hledger CSV conversion rules for MoneyWiz's register export format skip 1 fields account, date, amount, currency-del, category, payee, description, memo, balance, type date-format %m/%d/%Y amount %amount CNY description %description account1 Assets:%account if Expenses account2 Expenses:%category comment %payee if Income account2 Income:%category comment %payee if Transfers account2 Assets:%payee status *
ledger demo
2016/09/10 * Opening Balance (Assets:CCB:D2126) 859.00 CNY (Assets:HXB:D2645) 8406.41 CNY (Assets:ICBC:D3687) 63450.58 CNY 2016/10/14 * Salary Assets:CCB:D2126 200.00 CNY Income:Salary:Wuxi 2016/10/18 * Alipay Expenses:Alipay 259.00 CNY Assets:CCB:D2126 2016/10/21 * General Expenses:General 90.00 CNY Assets:CCB:D2126 2016/10/21 * Salary Assets:CCB:D2126 3400.00 CNY Income:Salary:Tsinghua 2016/10/21 * Transfer Assets:HXB:D2645 3000.00 CNY Assets:CCB:D2126 2016/10/21 * Salary Assets:ICBC:D3687 1700.00 CNY Income:Salary:NWPU 2016/10/21 * Interest Assets:ICBC:D3687 45.00 CNY = 65195.58 CNY Income:Interest 2016/10/28 * Transfer for Expense Expenses:General 200.00 CNY Assets:CCB:D2126 2016/10/30 * Tmall Expenses:Tmall:Phone 209.00 CNY Expenses:General 91.00 CNY Assets:CCB:D2126 2016/11/05 * Personal Care Expenses:Tmall:Personal Care 93.00 CNY Expenses:General 107.00 CNY Assets:CCB:D2126 2016/11/07 * Food Expenses Expenses:General 200.00 CNY Assets:CCB:D2126 2016/11/09 * Food Expenses Expenses:General 10.00 CNY Assets:CCB:D2126 2016/11/15 * Wuxi Salary Assets:CCB:D2126 200.00 CNY Income:Salary:Wuxi 2016/11/15 * Alipay transfer Expenses:General 200.00 CNY ; left: 120*27-200=3040 Assets:CCB:D2126 2016/11/20 * Regular expenses Expenses:General 200.00 CNY Assets:CCB:D2126 2016/11/25 * Salary Expenses:General Expenses:Network:Inoreader 14.99 USD @@ 108.82 CNY ; Annual Assets:CCB:D2126 2300.00 CNY Income:Salary:Tsinghua -3000.00 CNY 2016/12/01 * Train Ticket to Xi'an Expenses:Transportation 200.00 CNY Assets:CCB:D2126 2016/12/04 * Train to Hangzhou Expenses:Transportation 400.00 CNY Assets:CCB:D2126 2016/12/05 * Buy clothes on Lativ Expenses:Clothes 300.00 CNY Assets:CCB:D2126 2016/12/06 * Books Expenses:Books 100.00 CNY Assets:CCB:D2126 2016/12/09 * Travel Expenses:Travel 800.00 CNY Assets:CCB:D2126 2016/12/12 * Salary Assets:ICBC:D3687 3600.00 CNY Income:Salary:NWPU
awk中的trim操作
function ltrim(s) { sub(/^[ \t\r\n]+/, "", s); return s } function rtrim(s) { sub(/[ \t\r\n]+$/, "", s); return s } function trim(s) { return rtrim(ltrim(s)); } BEGIN { # whatever } { # whatever } END { # whatever }
orgmode写beamer
#+TITLE: MASH: A Rate Adaptation Algorithm for Multiview Video Streaming over HTTP #+AUTHOR: Jiaxi Gu #+EMAIL: imjiaxi@gmail.com #+DATE: Jul 6, 2017 * Introduction ** What is HTTP Adaptative Bitrate Streaming :B_frame: :PROPERTIES: :BEAMER_env: frame :END: HTTP Adaptative Bitrate Streaming... ** Workflow :B_frame: :PROPERTIES: :BEAMER_env: frame :END: 1. hello cite:foo2017bar 2. hello world. * References :B_frame: :PROPERTIES: :BEAMER_OPT: allowframebreaks :BEAMER_env: frame :END: \printbibliography
Jain's fairness index \[ \mathcal{J}(x_1, x_2, \cdots, x_n) = \frac{(\sum_{i=1}^n{x_i})^2}{n \sum_{i=1}^n{x_i}^2} \in \left[\frac{1}{n}, 1\right] \]
- There are \(n\) users and \(x_i\) represents the share of \(i\) -th user.
- Fairness: worst -> \(1/n\); best -> 1
利用 xetex
指定字体
\documentclass{article} \usepackage{xeCJK} \setCJKmainfont{STSong} % 中文衬线字体 \setCJKsansfont{STHei} % 中文无衬线字体 \setCJKmonofont{Kai} % 中文等宽字体 \setmainfont{Times} % 英文衬线字体 \setsansfont{Helvetica} % 英文无衬线字体 \setmonofont{Menlo} % 英文等宽字体 \begin{document} \begin{verse} Stray birds of summer come to my window to sing and fly away. \\ And yellow leaves of autumn, which have no songs, \\ flutter and fall there with a sign.\\ \hfill \emph{Rabindranath Tagore} \end{verse} \begin{verse} 夏天的飞鸟,飞到我的窗前唱歌,又飞去了。\\ 秋天的黄叶,它们没有什么可唱,只叹息一声,飞落在那里。\\ \hfill \emph{罗宾德拉纳特·泰戈尔} \end{verse} \end{document}
gpg有个问题是这样的:
echo "hello" | gpg -c -a - # gpg: problem with the agent: Inappropriate ioctl for device # gpg: error creating passphrase: Operation cancelled # gpg: symmetric encryption of '[stdin]' failed: Operation cancelled
添加个环境变量就好了。
export GPG_TTY=$(tty)
M-x list-faces-display
可以显示可用的样式。
My crafted mode-line for Emacs
(setq-default mode-line-format (list '(:eval (propertize (evil-generate-mode-line-tag evil-state) 'face '(:inherit font-lock-function-name-face))) "%e" 'mode-line-mule-info 'mode-line-modified 'mode-line-remote " " '(:eval (propertize " %b " 'face (if (buffer-modified-p) '(:background "#d33682" :foreground "#fdf6e3" :weight bold) '(:background "#268bd2" :foreground "#fdf6e3" :weight light)) 'help-echo (buffer-file-name))) '(:propertize " %p/%I " face (:background "gray30" :foreground "#fdf6e3") help-echo (count-words--buffer-message)) '(:eval (propertize (concat " " (eyebrowse-mode-line-indicator) " "))) '(:eval (propertize (format-time-string "%p·%H:%M ") 'help-echo (format-time-string "%F %a") 'face '(:inherit font-lock-doc-face :slant normal))) 'battery-mode-line-string '(:propertize (which-func-mode (" " which-func-format))) '(:eval (when (> (window-width) 70) (propertize " {%m}" 'face '(:weight normal)))) '(:eval (when (> (window-width) 70) (propertize vc-mode 'face '(:inherit font-lock-keyword-face :weight bold)))) "-%-"))
Emacs中 battery.el
在macOS 10.12中的bug
因为 pmset -g ps
的输出格式改变了。
;; change the line (looking-at "\\([0-9]\\{1,3\\}\\)%") ;; to (re-search-forward "\\([0-9]\\{1,3\\}\\)%")
libmobi是一个用来修改mobi文件meta信息的工具。
# show meta data mobimeta some.mobi # modify meta data mobimeta -s title="sometile" -s author="someone" some.mobi
查看压缩包内容并解压出单个文件夹
## list content tar -tvf foo.tgz # foo/ # foo/foo.txt # bar/ ## extract a specific folder tar -xvf foo.tgz foo
Matplotlib的自定义主题设置,相关属性可以参考: Customizing matplotlib
plt.style.use('seaborn-paper') plt.rc('font', **{'family': 'sans-serif', 'size': 12}) plt.rc('xtick', **{'direction': 'in', 'labelsize': 10, 'major.size': 3.5}) plt.rc('ytick', **{'direction': 'in', 'labelsize': 10, 'major.size': 3.5}) plt.rc('axes', **{'labelsize': 10}) plt.rc('grid', **{'linestyle': 'dashed'}) plt.rc('figure', **{'figsize': (3.5, 2.2), 'autolayout': True}) plt.rc('savefig', **{'bbox': 'tight'})
有三种方式设置绘图属性
# Method 1: plt.rcParams['xtick.direction'] = 'in' plt.rcParams['xtick.labelsize] = 10 plt.rcParams['xtick.major.size] = 3.5 # Method 2 plt.rc('xtick', direction='in', labelsize=10) plt.rc('xtick.major', size=3.5) # Method 3 (preferred method): plt.rc('xtick', **{'direction': 'in', 'labelsize': 10, 'major.size: 3.5})
ggplot2主题设置
theme_iz <- function(base_size = 12, base_family = 'Helvetica') { theme_classic(base_size = base_size, base_family = base_family) %+replace% theme( panel.background = element_rect(fill = FALSE), panel.border = element_rect(fill = FALSE, size = 0.5), panel.grid.major = element_line(colour = 'grey87', linetype = 'dotted', size = 0.25), panel.grid.minor = element_line(colour = 'grey87', linetype = 'dotted', size = 0.125) ) }
Matplotlib面向对象的方式更推荐
import matplotlib.pyplot as plt fig1, ax1 = plt.subplots(2, 1) ax1[0].plot([1, 2, 3, 4]) ax1[1].plot([4, 3, 2, 1]) fig1.savefig("p1.pdf") fig2, ax2 = plt.subplots() ax2.plot([1, 1, 1, 1]) fig2.savefig("p2.pdf")
使 subcaption
包与 IEEEtran
兼容 2
\makeatletter \let\MYcaption\@makecaption \makeatother \usepackage[font=footnotesize]{subcaption} \makeatletter \let\@makecaption\MYcaption \makeatother
CTEX宏包对文档的汉化选项 预设有 chinese 和 plain 两种方案。
% 对“图”、“表”、“目录”、“参考文献”等均有汉化 [默认] \usepackage[scheme=chinese]{ctex} % 不调整默认字号和行距,不汉化标题名字,仅做中文支持。 \usepackage[scheme=plain]{ctex}
在 IEEEtran
的环境下兼容 algorithm2e
宏包 3
IEEEtran的指南上说不要使用 algorithm
的float结构,因为模板只允许 figure
和 table
两种float结构。但是 algorithm2e
包写出来的算法确实比它推荐的包要好看,所以其实我们可以把它放到figure结构中,用H选项来禁止float,这样的话需要一个小hack让它可以在双栏的文档类型下工作。
\documentclass[journal, a4paper]{IEEEtran} \usepackage[ruled,norelsize]{algorithm2e} \makeatletter \newcommand{\removelatexerror}{\let\@latex@error\@gobble} \makeatother \begin{document} \begin{figure}[!t] \removelatexerror \begin{algorithm}[H] \caption{multiobjective DE} initialize population $P = \left \{ X_{1}, ... , X_{N} \right \} $\; \For( \emph{Evolutionary loop}){$g := 1$ to $G_{max}$} { Do things \; Trim the population to size $N$ using nondominated sorting and diversity estimation \; } \end{algorithm} \end{figure} \end{document}
利用GPU加速的视频转码 相关链接: https://developer.nvidia.com/ffmpeg
ffmpeg -hwaccel cuvid -c:v h264_cuvid -i apple.mp4 -vcodec h264_nvenc apple_nv.mp4
Ubuntu系统的回收站(Trash)地址: ~/.local/share/Trash/
Sketch.app的缓存
sudo rm -rf /.DocumentRevisions-V100/
Gamma function
\begin{equation*} \Gamma(c) = \int_{0}^{\infty} \! e^{-u}u^{c-1} \, \mathrm{d}u \end{equation*}Two of its key properties are:
\begin{equation*} \Gamma(c) = (c-1) \Gamma(c-1) \\ \Gamma(c)\Gamma(1-c) = \frac{\pi}{sin(\pi c)} \end{equation*}
beta分布是二项分布的共轭先验分布 4
\begin{equation*} k|n,\theta \sim Binomial(\theta, n) \\ \theta|\beta_1, \beta_2 \sim Beta(\beta_1, \beta_2) \\ \theta|k,n,\theta_1,\theta_2 \sim Beta(\beta_1 + k, \beta_2 + n - k) \end{equation*}
\(\LaTeX\)排版的一些细节问题 5
% dash ✅ This style -- spaced en dashes, and is common in Europe. ✅ This style---unspaced em dashes, and is common in America. % dots ❌ Sort $a_1 ... a_n$. ✅ Sort $a_1, \dots, a_n$. % extraspace ❌ Zebras occur in the Serengeti ~\cite{zebras}. ✅ Zebras occur in the Serengeti~\cite{zebras}. % footnote ❌ We see~\footnote{Or hear.} the problems here\footnote{Or there}. ✅ We saw\footnote{Or heard.} the problems there.\footnote{Not here.} % mathunit ❌ Our dist holds $40TB$ of data. ✅ Our disk holds $40~\text{TB}$ of data. % mid (| is for absolute vlues, not for comprehensions) ✅ $S = \{x \mid |x| < 5\}$ % negatives ❌ The number is -1. ✅ The number is $-1$. % range ❌ Lines 1-3 present our results. ❌ Lines $1-3$ present our results. ❌ Lines 1 -- 3 present our results. ✅ Lines 1--3 present our results. % refnoun (References are not nouns. They aren't even parts of speech.) ❌ In [15] modern disk drives are shown to be effective. ❌ [1] applies cache-aware algorithms to binary search trees. ✅ Modern disk drives are effective [15]. ✅ Cormen et al. [1] apply cache-aware algorithms to binary search trees. % thousands ❌ That cost $\$2,000,000$. ✅ That costs \$2,000,000. ✅ That cost $\$2{,}000{,}000$.
Vim寄存器的使用
- Press
"ayy
to copy current line to register a. - Press
"ap
to paste the content in register a.
Netflix使用的是固定为4秒的DASH视频片段长度 6
RefTex的使用
- 快捷键:在latex-mode下是
C-c [
, 在org-mode下是C-c C-x [
- 它会根据当前文件中定义的bib文件来进行智能地搜索。
- 如果想要它列出bib文件中所有的项目,可以输入
\.
以匹配所有的规则。
如果需要从bib文件中提取被引用的条目,可以在Emacs下使用 reftex-create-bibtex-file
.
Functor, Applicative and Monad
fmap :: Functor f => (a -> b) -> f a -> f b pure :: Applicative f => a -> f a (<*>) :: Applicative f => f (a -> b) -> f a -> f b return :: Monad m => a -> m a (>>=) :: Monad m => m a -> (a -> m b) -> m b
创建用gpg加密的org文件,创建文件名为 foo.org.gpg
的文件,添加本地变量:
# -*- epa-file-encrypt-to: "imjiaxi@gmail.com" -*-
strip
discards symbols from the object file. They are generally only needed for debugging.
du -h hello # 1.1M hello strip hello du -h hello # 998K hello
控制Haskell编译后的可执行文件大小
- 加入
-dynamic
编译参数,如果是用stack的话,可以是:stack ghc foo.hs -- -dynamic
- 使用
strip
来去除二进制文件中用于调试的符号等。
ffmpeg one-line cheatsheet 7
ffmpeg -i input.mp4 -vf scale=3840x2160,setdar=16:9 -r 30 -c:v hevc_nvenc -b:v 30M -pix_fmt yuv420p -c:a aac -b:a 192K output.mp4
使用某函数输出结果来进行compare并排序进行
immport Data.Ord (comparing) lsort = sortBy (comparing length) -- lsort ["abc", "a", "aa"]
exa is a modern replacement for ls
.
显示IP地址
ifconfig | grep inet | grep -v inet6 | cut -d" " -f2 | tail -n1
enca: Charset analyzer and converter.
文本文件字符编码的检测与转换,The option -i
is equivalent to --mime
. In macOS, it should be -I
instead.
# detect file encoding file -bi input.txt # convert from gb18030 to utf-8 iconv -f gb18030 -t utf-8 input.txt # list all supported encodings iconv -l
\(\LaTeX\) 控制页边距
\usepackage[top=.7in, bottom=.7in, left=1.25in, right=1.25in]{geometry}
objective
: 目标,强调个人或需求而决定的目标,书面用词。
刪除誤上屏的錯詞
先把選字光標(用上、下鍵)移到要刪除的用戶詞組上,再按下 Shift+Delete 或 Control+Delete(蘋果鍵盤用 Shift+Fn+Delete)。 只能夠從用戶詞典中刪除詞組。用於碼表中原有的詞組時,只會取消其調頻效果。
拉格朗日中值定理: If a function \(f\) is continuous on the closed interval \([a,b]\), and differentiable on the open interval \((a,b)\), then there exists a point \(c\) in \((a,b)\) such that: \[ f^{\prime}(c) = \frac{f(b) - f(a)}{b-a} \]
Singular Value Decomposition Tutorial
- 很不错的一篇教程,简短又易懂。
- https://www.dropbox.com/s/rfrw54blp8dz6sb/linalgWithSVD.pdf?dl=0
什么叫做线性空间
用ADB来传输文件,注意路径的写法,除了push同样还有pull操作。
adb push somefile /storage/emulated/0/somefile # [100%] /storage/emulated/0/somefile # adb: error: failed to copy 'somefile' to '/storage/emulated/0/somefile': Read-only file system adb push somefile /sdcard/somefile # [100%] /sdcard/somefile
时间戳解析
date -r 1508573115005 # Wed Oct 12 07:30:05 CST 49774
Python3里的 execfile()
exec(open("./filename.py").read())
ripgrep
的常用命令
# search content in files rg -i "some" # search files rg --iglob '*filename*' --files # list rg supported types rg --typ-list # search for specific file types rg -t tex 'something'
Vim配置fzf进行模糊搜索
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
设置默认音轨
# inspect file information mp4box -info "movie.mp4" # change default audio stream mp4box "movie.mp4" -enable 3 mp4box "movie.mp4" -disable 2
禁用iOS设备连接iTunes后同步时自动备份
defaults write com.apple.iTunes AutomaticDeviceBackupsDisabled -bool true
Cabinet是Android下的一个简洁又轻量的文件管理器
orgmode中星号的转义还没什么好办法,可以用特殊字符代替
For completeness, you can "escape" an asterisk in Org using entities, in this case ∗, or *:
"The person wanted to say ∗BSD. Now this is bold*"
Unfortunately, for obvious reasons, this will not work in verbatim snippets, i.e,
...
and...
, which is why at some point, Org will need to allow escaping ~ and = there.
rsync指定端口
rsync -a -e 'ssh -p 2345' user@server.com:foo/bar/ local/foo/
rsync通过IPV6连接
rsync -a user@[2001:db8:1234:5678:feed:face:dead:beef]:foo/bar/ local/foo/
查找文件中的重复行
sort file.txt | uniq -d
输出目录下所有媒体文件的播放总时长
find . -maxdepth 1 -iname '*.ts' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bc
用Imagemagick来压缩图片
- 本文作者尝试了不同的参数,最后得出了一个比较合理的一个压缩脚本: https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
- 用imagemagick压缩出来的图片的size还是很大,可以考虑用这个:https://pngquant.org
smartresize() { mogrify -path $3 -filter Triangle -define filter:support=2 -thumbnail $2 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB $1 }
把图片编码到org文件中
- 来源: http://mbork.pl/2017-12-04_Embedding_files_in_Org-mode
- 这种方法可以确保图片文件所在位置和数据的重现
- 在用
org-insert-file
插入图片后,这部分的代码一旦执行,就会在相应的位置生成图像文件。
(defun org-insert-file (filename) "Insert Elisp code block recreating file named FILENAME." (interactive "f") (let ((base64-string (with-temp-buffer (insert-file-contents-literally filename) (base64-encode-region (point-min) (point-max)) (buffer-string)))) (insert (format "#+BEGIN_SRC emacs-lisp :exports none :results output silent\n (with-temp-file %S\n (insert (base64-decode-string\n %S)))\n#+END_SRC" filename base64-string))))
\(\LaTeX\) 中控制图片下面离文本的间隔
\setlength{\textfloatsep}{2pt}
获取当前时间并格式化
date +%Y%m%d%H%M%S
用 curl
与WebDav服务器通信
# Box.com curl -u me@email.com:mypassword -T local_file_path https://dav.box.com/dav/remote_file_name curl -u me@email.com:mypassword https://dav.box.com/dav/remote_file_name --output download_file_path # jianguoyun.com curl -u "xxx@gmail.com:mypassword" -T filename.pdf "https://dav.jianguoyun.com/dav/SomeDir/filename.pdf"
mutt最小化配置
set imap_user = "name@aol.com" set imap_pass = "your-password" set smtp_url = "smtp://name\@aol.com@smtp.aol.com:587/" set smtp_pass = "your-password" set folder = "imaps://imap.aol.com:993" set spoolfile = "+INBOX"
mutt发送html内容的邮件
mutt -e 'set content_type="text/html"' recipient@gmail.com -s "Foo Subject" < foo.html
Git删除历史提交中的敏感信息文件
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch sensitive.txt' --prune-empty --tag-name-filter cat -- --all # or git filter-branch --treefilter 'rm -f sensitive.txt' HEAD
输出文件名中包含某串字符的文件(递归并大小写不敏感)
function rf () { if hash rg 2> /dev/null; then rg -l --files --iglob "*$1*" else find . -iname "*$1*" fi }
Emacs Calc在orgmode中的使用
#+BEGIN_SRC calc :exports both (300 + 120) * 2 %% Double prices #+END_SRC
Emacs lisp解析csv文件
(defun parse-csv-string-rows (data separator quote-char line-sep) "Parse a separated and quoted string DATA into a list of list of strings. Uses SEPARATOR as the column seperator, QUOTE-CHAR as the string quoting character, and LINE-SEP as the line separator." (let ((items '()) (lines '()) (offset 0) (rawlines (if line-sep (split-string data line-sep) (list data))) (line "") (current-word "") (state :read-word)) (catch 'return (progn (setq line (pop rawlines)) (cl-loop (when (or (not line) (= offset (length line))) ;; all done (cl-ecase state (:in-string (if rawlines; have more lines (progn (setq offset 0) (setq current-word (concat current-word line-sep)) (setq line (pop rawlines))) (error "Unterminated string"))) (:read-word ;; new line! (push (nreverse (cons current-word items)) lines) (if rawlines (progn (setq current-word "") (setq items '()) (setq offset 0) (setq line (pop rawlines))) (throw 'return (nreverse lines)))))) ;; handle empty line (if (= 0 (length line)) (cl-ecase state (:in-string (setq offset 0) (setq current-word (concat current-word line-sep)) (setq line (pop rawlines))) (:read-word ;; new line! (push (nreverse (cons current-word items)) lines) (setq offset 0) (setq line (pop rawlines)))) (let ((current (aref line offset))) (cond ((char-equal separator current) (cl-ecase state (:in-string (setq current-word (concat current-word (char-to-string current)))) (:read-word (push current-word items) (setq current-word "")))) ((char-equal quote-char current) (cl-ecase state (:in-string (let ((offset+1 (1+ offset))) (cond ((and (/= offset+1 (length line)) (char-equal quote-char (aref line offset+1))) (setq current-word (concat current-word (char-to-string quote-char))) (cl-incf offset)) (t (setq state :read-word))))) (:read-word (setq state :in-string)))) (t (setq current-word (concat current-word (char-to-string current)))))) (cl-incf offset)))))))
Do not put 'and' before 'etc' (et cetera). Et cetera is a Latin phrase. Et means “and.” Cetera means “the rest.”
✅ The children should bring paper, pencils, scissors, etc. ❌ The children should bring paper, pencils, scissors and etc.
\(\LaTeX\)简历模板
- https://github.com/cies/resume/
- https://github.com/treyhunner/resume/
- https://github.com/dnl-blkv/mcdowell-cv
\(\LaTeX\)文本靠右对齐
\begin{flushright} Jack\\ 12/23/2018 \end{flushright}
用pandoc将markdown或org转换为pdf
# 设定pdf文件的边界空白 pandoc input.md -o output.pdf -V geometry:margin=1in # 处理中文字符,注意后面指定的两种字体 pandoc input.org -o output.pdf --pdf-engine=xelatex -V CJKmainfont=STSong -V mathfont=Times
\(\LaTeX\)强制插入未引用的角注
\let\thefootnote\relax\footnotetext{\textit{\today}}
\(\LaTeX\)在 \begin{document}
前加入以下代码可以用于去掉页码
\pagestyle{empty}
用 troff
进行排版的一个例子
groff -mom -T ps input.mom > output.ps
.TITLE "The Cask of Amontillado" .AUTHOR "Edgar Allen Poe" .PRINTSTYLE TYPESET .START .PP .DROPCAP T 3 he terms text processing and macro set may be unfamiliar to you. Text processing is a method of creating documents that separates the content of what you’re writing from its presentation, much like html. Working in a text editor, you intersperse documents with instructions describing how you’d like the text to look. When a document prepared this way is intended for processing with groff, the instructions are called macros. .HEAD "MOM Format" .SUBHEAD "Font Styles" .PP Here are some font styles: .FT B bold, .FT I italic, .FAM H helvetica. .SUBHEAD "Lists" .LIST BULLET .ITEM Item one .ITEM Item two .ITEM Item three .LIST OFF .SUBHEAD "Footnotes" .PP No sea takimata\c .FOOTNOTE Takimata sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et do\%lo\%re magna ali\%quyam erat, sed diam voluptua. .FOOTNOTE OFF
删除stack安装的包
To remove a package that stack installed, you need to manually do so. This entails using ghc-pkg unregister and then finding the location of the package on your system and removing it via another tool or simply
rm
.
# just for test stack install <pkg-name> # query for the <pkg-id> ghc-pkg field <pkg-name> id # unregister the package ghc-pkg unregister <pkg-id> # This could be something like ~/.stack/xxx cd /path/to/stack/packages rm <pkg-name>
orgmode中的表格可以使用 org-table-export
导出到csv文件,可以添加章节属性来指定导出文件路径。
:PROPERTIES: :TABLE_EXPORT_FILE: /tmp/books.csv :TABLE_EXPORT_FORMAT: orgtbl-to-csv :END:
根据国际标准组织的规定,矩阵(matrix)用粗斜体(bold italic)书写,而张量(tensor)用斜体(slanted)无衬线字体书写. 8
ISO/IEC regulations for technical writing prescribe using bold italic for matrices (and slanted sans serif for tensors).
Discuz的RSS地址是域名后面加 /forum.php?mod=rss
一个常见的语法问题,下面两种说法都是可以的:
There is work [for you] to do. There is work to be done [by you].
FFT计算频域
# series: signal in time domain; fsmp: sampling frequency def do_fft(series, fsmp): N = len(series) fs = np.fft.rfftfreq(N, 1.0 / fsmp) amp = np.fft.rfft(series, N) db = 20 * np.log10(np.abs(amp) / np.abs(amp).max()) return fs, db
dim这个package用来隐藏mode-line中的minor mode名称简单有效
CSS里面强制长的链接自动换行,而代码块里面的内容除外
body { word-wrap: break-word; } pre { word-wrap: normal; }
\(\pi\)的值可以由\(4 * arctan(1)\)计算得到。
buku
删除某个标签可以用 buku --replace oldtagname
, 一般用在删除导入书签后自动生成的日期标签。
--replace old new Replace old tag with new tag if both are passed; delete old tag if new tag is not specified.
万象节锁(Gimbal Lock)的问题只会出现在动态坐标系(也就是坐标系随旋转物体而转动),描述如下:三轴旋转如果由欧拉角的表示的话,其次序是固定的,分别记作1,2,3三次,一旦第2次旋转为+/-90°,那么Gimbal Lock就会发生,这种情况下,第3次的旋转效果可以由第1次旋转所在维度达成,换句话说,第3次旋转并没有发生在新的维度上,所以说“失去了一个自由度”,也可以理解为这样的旋转实际只有两个轴起了作用而不是3个。
Emacs文件本地变量(File-local variables)可以用头或尾两种方式设置(为了避免作用于本文件,每一行开头的字符故意重复输入了)。
--*- mode: mode-name-here; my-variable: value -*-
OR
LLocal Variables: mmode: mode-name-heree mmy-variable: value EEnd:
RFC3339规定的日期和时间格式如下(东八区2018年3月13日下午3点37分53秒,字母T用于分隔日期和时间):
2018-03-13T15:37:53+08:00
\(\Theta(n)\)表示算法复杂度的确界(tight bound); 常用的\(O(n)\)表示上界(upper bound),\(o(n)\)也表示上界但它同时包含非确界的含义;\(\Omega(n)\)表示下界(lower bound),\(\omega(n)\)也表示下界但它同时包含非确界的含义。
比如说一个\(\Theta(n^3)\)的算法,我们可以说它是\(o(n^4)\)以及\(\omega(n^2)\),表明该算法的复杂度不可能超过四次方同时不可能低于二次方。当然我们也可以说该算法是\(O(n^3)\)和\(\Omega(n^3)\)。
Emacs中单独为某些face设置字体
(when (member "PragmataPro" (font-family-list)) (add-hook 'org-mode-hook (lambda () (mapc (lambda (face) (set-face-attribute face nil :font "PragmataPro-14")) (list 'org-table 'org-link 'org-date 'org-code 'org-verbatim 'org-formula)))) (add-hook 'markdown-mode-hook (lambda () (mapc (lambda (face) (set-face-attribute face nil :font "PragmataPro-14")) (list 'markdown-table-face)))))
Emacs中为某个major mode设置字体
(when (member "PragmataPro" (font-family-list)) (add-hook 'org-mode-hook (lambda () (setq buffer-face-mode-face '(:family "PragmataPro")) (buffer-face-mode))))
编程字体推荐
- Menlo: MacOS自带
- Consolas: Windows自带
- PragmataPro™: 宽度刚好是中文字符一半; 包含一些Unicode字符
- Input: 可自定义程度较高,包括字宽和行高,还有一些字符的样式
- Monoid: 可自定义
- Iosevka: 宽度刚好是中文字符的一半; 包含多种字重
- Hack: 带有Powerline的一些字符
- FiraCode: 带有Ligature
- Source Code Pro: Adobe出品的一个字体族
MacOS自带的Grapher.app可以用来书写简单的公式,这样在做keynote的时候就可以不用MathType了。
Orgmode的脚注有三种方式:
[fn:name]
: 最直接的脚注形式,需要再指定脚注内容。[fn::some content]
: 匿名的脚注,内容直接接在后面。[fn:name:some content]
: 命名脚注,可以多次引用。
Haskell里的符号不是胡乱选的鬼画符,是有联系的,看 $
和 <$>
:
($) :: (a -> b) -> a -> b (<$>) :: Functor f => (a -> b) -> f a -> f b (<*>) :: Applicative f => f (a -> b) -> f a -> f b
Haskell中的Functor需满足两大法则
-- Law 1 fmap id == id -- Law 2 fmap (f . g) == fmap f . fmap g
monoid | semigroup | magma | |
---|---|---|---|
binary operation | yes | yes | yes |
associativity | yes | yes | no |
identity | yes | no | no |
A monad is just a monoid in the category of endofunctors.
有关 Monad是自函子范畴上的一个幺半群 这句话的一个解释
幺半群Monad并不是针对*的类型而言的,而是针对类别为* -> *的自函子而言的,他的操作对象是Maybe、[]这样的自函子,这些自函子在值的层面的表现是千差万别的。这里的二元操作就是join,单位元就是return。
-- 单位律 join . return == id -- 结合律 join . (join . join) == (join . join) . join
奇异值分解(Singular Value Decomposition): 对于任意矩阵 \(\mathbf{A} \in \mathbb{R}^{m \times n}\), 都可以分解为: \(\mathbf{A} = \mathbf{U} \mathbf{\Sigma} \mathbf{V}^{\top}\), 其中 \(\mathbf{U} \in \mathbb{R}^{m \times m}\) 和 \(\mathbf{V} \in \mathbb{R}^{n \times n}\) 都是正交矩阵(注意正交矩阵的定义: 列向量标准正交), 此外 \(\mathbf{\Sigma} \in \mathbb{R}^{m \times n}\) 是一个对角矩阵(注意对角矩阵的定义: 行列号不等的元素均为零),对角元素被称为 \(\mathbf{A}\) 的奇异值(singular values), 记作 \(\sigma_i\), 且其中只有前 \(r = rank(\mathbf{A})\) 个奇异值非零,通常按照从大到小排列: \(\sigma_1 \geq \sigma_2 \geq \cdots \geq \sigma_r > \sigma_{r+1} = \cdots = \sigma_{\min}(m,n) = 0\). 在这个基础上,我们来看下面两个式子:
\begin{equation*} \begin{aligned} \mathbf{A} \mathbf{A}^{\top} = \mathbf{U} \Sigma \mathbf{V}^{\top} (\mathbf{U} \mathbf{\Sigma} \mathbf{V}^{\top})^{\top} = \mathbf{U} \mathbf{\Sigma} \mathbf{V}^{\top} \mathbf{V} \mathbf{\Sigma}^{\top} \mathbf{U}^{\top} = \mathbf{U} \mathbf{\Sigma} \mathbf{\Sigma}^{\top} \mathbf{U}^{\top}\\ \mathbf{A}^{\top} \mathbf{A} = (\mathbf{U} \Sigma \mathbf{V}^{\top})^{\top} \mathbf{U} \mathbf{\Sigma} \mathbf{V}^{\top} = \mathbf{V} \mathbf{\Sigma}^{\top} \mathbf{U}^{\top} \mathbf{U} \mathbf{\Sigma} \mathbf{V}^{\top} = \mathbf{V} \mathbf{\Sigma}^{\top} \mathbf{\Sigma} \mathbf{V}^{\top} \end{aligned} \end{equation*}由此可见, \(\mathbf{U}\) (左奇异矩阵)的列向量是矩阵 \(\mathbf{A}\mathbf{A}^{\top}\) 的特征向量,而 \mathbf{V}$ (右奇异矩阵)的列向量是矩阵 \(\mathbf{A}^{\top}\mathbf{A}\) 的特征向量,而 \(\mathbf{A}\) 的奇异值(即 \(\mathbf{\Sigma}\) 的对角元素)即为 \(\mathbf{A}\mathbf{A}^{\top}\) 或 \(\mathbf{A}^{\top}\mathbf{A}\) 的特征值的平方根。
™
表示未注册的商标, ®
表示注册商标。
The trademark symbol (™) is a symbol to indicate that the preceding mark is a trademark. It is usually used for unregistered trademarks, as opposed to the registered trademark symbol (®) which is reserved for registered trademarks.
有关PCA (Principle Component Analysis)推导的一个步骤的理解。
问题如下: \[ {arg\,max}_w (w^\top v w) \qquad \text{s.t.} \quad w^\top w = 1 \] 书上说这里的 \(w\)是\(v\)的最大特征值对应的特征向量。 (方便起见,这里简化了一些符号,比如用\(v\)代替了书中的\(X^\top X\))
证明如下: \[ \sigma = w^\top v w \\ \] 利用拉格朗日乘子法 (Lagrange multiplier) \[ \mathcal{L}(w,\lambda) \equiv \sigma + \lambda(w^\top w - 1) \\ \frac{\partial L}{\partial \lambda} = w^\top w - 1 \\ \frac{\partial L}{\partial w} = 2vw - 2 \lambda w \] 令两个偏导等于1求极值即 \[ w^\top w = 1 \\ vw = \lambda w \] 代到原式中 \[ \sigma = w^\top v w = w^\top \lambda w = \lambda \] 即为使\(\lambda\)最大,也就是说,欲求的\(w\)即为\(v\)的最大特征值对应的特征根。
参考:
有关sigmoid函数\(\sigma(x)\)及softplus函数\(\zeta(x)\)的一些性质:
\[ \sigma(x) = \frac{1}{1 + \exp(-x)} \\ \frac{d}{dx}\sigma(x) = \sigma(x) (1 - \sigma(x)) \\ 1 - \sigma(x) = \sigma(-x) \\ \log \sigma(x) = -\zeta(-x) \\ \frac{d}{dx}\zeta(x) = \sigma(x) \\ \forall x \in (0,1), \sigma^{-1}(x) = \log(\frac{x}{1-x}) \\ \forall x > 0, \zeta^{-1}(x) = \log(\exp(x) - 1) \\ \zeta(x) = \int^x_{-\infty}\sigma(y)\,dy \\ \zeta(x) - \zeta(-x) = x \]
豆瓣读书的记录可以通过官方的API导出为json,比如下面的地址就是导出“读过的书”,注意每次请求的数量最大是100,超过会被重置:
https://api.douban.com/v2/book/user/gujiaxi/collections?status=read&start=0&count=100 https://api.douban.com/v2/book/user/gujiaxi/collections?status=read&start=100&count=100
Haskell中Applicative的几个函数
import Control.Applicative (<$>) :: Functor f => (a -> b) -> f a -> f b liftA :: Applicative f => (a -> b) -> f a -> f b liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
用\(\LaTeX\)生成独立的公式
\documentclass{standalone} \begin{document} $\displaystyle e = mc^2 $ \end{document}
似然函数:
\begin{equation*} L(\theta; x^n_1) = \prod_{i=1}^n f_X(x_i; \theta) \end{equation*}目标是求满足最大似然的\(\hat{\theta}\):
\begin{equation*} \begin{aligned} \hat{\theta} & = arg\,max_\theta L(\theta; X^n_1) \\ & = arg\,min_\theta -\log L(\theta; X^n_1) \\ & = arg\,min_\theta \sum_{i=1}^n\{-\log f(X_i; \theta)\} \end{aligned} \end{equation*}可以证明\(\frac{1}{n}\sum_{i=1}^n\{-\log f(X_i; \theta)\}\)收敛至\(f(x; \theta_0)\)与\(f(x; \theta)\)的交叉熵,即最小化的情况在\(\theta = \theta_0\)时取得,其中\(\theta_0\)为真实分布的参数:
\begin{equation*} \begin{aligned} \frac{1}{n}\sum_{i=1}^n\{-\log f(X_i; \theta)\} & = \frac{1}{n}\sum_{i=1}^n\{-\log f(X_i; \theta) + \log f(X_i; \theta_0) - \log f(X_i; \theta_0) \} \\ & = \frac{1}{n} \sum_{i=1}^n \{ \log \frac{f(X_i; \theta_0)}{f(X_i; \theta)} - \log f(X_i; \theta_0) \} \\ & = \frac{1}{n}\sum_{i=1}^n \log \frac{f(X_i; \theta_0)}{f(X_i; \theta)} - \frac{1}{n}\sum_{i=1}^n \log f(X_i; \theta_0) \\ & \to D_{KL}[f(x; \theta_0) \| f(x; \theta)] + H[f(x; \theta_0)] \end{aligned} \end{equation*}
Emacs中Flyspell可以通过在文末添加词列表来指定词典外的词拼写
% LocalWords: accelerometer phonation
Emacs中更新全部包的一个函数
(defun package-upgrade-all () "Upgrade all packages automatically without showing *Packages* buffer." (interactive) (package-refresh-contents) (let (upgrades) (cl-flet ((get-version (name where) (let ((pkg (cadr (assq name where)))) (when pkg (package-desc-version pkg))))) (dolist (package (mapcar #'car package-alist)) (let ((in-archive (get-version package package-archive-contents))) (when (and in-archive (version-list-< (get-version package package-alist) in-archive)) (push (cadr (assq package package-archive-contents)) upgrades))))) (if upgrades (when (yes-or-no-p (message "Upgrade %d package%s (%s)? " (length upgrades) (if (= (length upgrades) 1) "" "s") (mapconcat #'package-desc-full-name upgrades ", "))) (save-window-excursion (dolist (package-desc upgrades) (let ((old-package (cadr (assq (package-desc-name package-desc) package-alist)))) (package-install package-desc) (package-delete old-package))))) (message "All packages are up to date"))))
aspell
输出可用的词典
aspell dump dicts
Out-of-Sample Extensions for LLE, Isomap, MDS, Eigenmaps, and Spectral Clustering: 这篇文章的作者是机器学习大牛Bengio,主要关注MDS,基于样本间距离的流形(manifold)降维方法,主要用于数据可视化。因为它是用已知的整个样本空间来做降维,所以对于out-of-sample的情况即新样本没有办法进行直接判断。这篇文章的方法是提出用已知数据得到的核矩阵来应用到新数据即out-of-sample的数据上来,以衡量新数据之间的距离,证明了可以这样做的合理性。并没有说直接可以对新数据降维,虽然说也可以这么做,但其实还是需要一些额外的运算的。
多元时间序列的分类,主要分为两大类:一类是基于样本间相似性的;第二类是基于时间序列的特征的。目前来看第二类方法效果比第一类要好,主流的是两种方法,都是2018年发表的,它们相互之间也进行了性能的比较。
- Multivariate Time Series Classification with WEASEL+MUSE 9 : 根据patrickzib/SFA: Scalable Time Series Data Analytics的评价,WEASEL本身是时间序列分类方法了,MUSE使得它可以应用于多元时间序列。文中提到跟MLSTM-FCN比较,两者在很多数据集上 都 表现出很好的效果,但是作者指出,WEASEL+MUSE在样本数和特征数较少(几十)的情况表现更好,而MLSTM-FCN在样本数和特征数较多(几百上千)的情况。
- Multivariate LSTM-FCNs for Time Series Classification 10: 基于LSTM。
特征选择方法主要有两种: \(\chi^2\) 检验、互信息
Emacs的speedbar默认是会随着当前buffer改变其显示的目录的,但是可以通过 sr-speedbar
提供的 sr-speedbar-refresh-turn-off
来关掉自适应切换目录。
用Python虚拟环境的时候可以用 --system-site-packages
来继承系统的python包。
python3 -m venv proj --system-site-packages
Python输出当前操作系统平台
import platform print(platform.system()) # "Linux" or "Darwin" or "Windows"
用Hammerspoon结合Buku来添加书签。
------------------------ --/ Function Trigger /-- ------------------------ function bookmark() hs.applescript([[ set tags to display dialog "Add some tags?" default answer the clipboard --> {button returned:"Continue", text returned:"Jen"} set res to do shell script "/usr/local/bin/buku -a " & the clipboard & " --tag " & (text returned of tags) ]]) end hs.hotkey.bind(hyper, "b", function() bookmark() end)
快速查看某个命令行工具的使用方法
curl cheat.sh/tar
从Kindle的读书笔记文件 My Clippings.txt
文件中随机输出一句摘抄。
BEGIN { clipping = ""; i=0; flag=1; srand(); } { if ($0 !~ /==========/) { if ($0 !~ /^-\s+/) { if ($0 !~ /^\s*$/ ) { if (clipping == "") { clipping = "--- " $0; } else { clipping = $0 "\n\n" clipping; } } } } else { clippings[i++] = clipping; clipping = ""; } } END { print clippings[int(rand()*i)]; }
关掉Mac下更改文件后缀名的警告。
# Disable the warning when changing a file extension defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
Matplotlib报错 no display name and no $DISPLAY environment variable
- 解决方案一,设置环境变量
export MPLBACKEND="agg"
- 解决方案二,在python代码里切换图形后端
import matplotlib.pyplot as plt. plt.switch_backend('agg')
笔记: A Comprehensive Guide to Machine Learning
- 如果向量空间 \(V\) 由一组线性独立的向量生成,那么这组向量就成为该空间的基(basis);每一组线性独立的向量都可以成为该空间的基,所以基不是唯一的。
- 如果向量空间由有限个基生成,那么基的数量就成为该空间的维数(dimension)。
- 向量空间必须满足以下六个条件:
- 存在零元素,使得 \(\mathbf{x} + \mathbf{0} = \mathbf{x}, \forall \mathbf{x} \in V\)
- 对于任意元素 \(\mathbf{x} \in V\), 存在逆元 \(-\mathbf{x}\) 使得 \(\mathbf{x} + (-\mathbf{x}) = \mathbf{0}\).
- 存在标量单位乘数 (\(1 \in \mathbb{R}\)), 即满足 \(1 \mathbf{x} = \mathbf{x}, \forall \mathbf{x} \in V\).
- 满足交换律: \(\mathbf{x} + \mathbf{y} = \mathbf{y} + \mathbf{x}, \forall \mathbf{x}, \mathbf{y} \in V\)
- 满足结合律: \((\mathbf{x} + \mathbf{y}) + \mathbf{z} = \mathbf{x} + (\mathbf{y} + \mathbf{z}), \forall \mathbf{x}, \mathbf{y}, \mathbf{z} \in V\) and \(\alpha (\beta \mathbf{x}) = (\alpha \beta) \mathbf{x}, \forall \alpha, \beta \in \mathbb{R}\)
- 满足分配率: \(\alpha (\mathbf{x} + \mathbf{y}) = \alpha \mathbf{x} + \alpha \mathbf{y}, \forall \mathbf{x}, \mathbf{y} \in V\) and \((\alpha + \beta) \mathbf{x} = \alpha \mathbf{x} + \beta \mathbf{x}, \forall \alpha, \beta \in \mathbb{R}\).
- 两个向量子空间的和表示为: \(U+W = \{\mathbf{u} + \mathbf{w} | \mathbf{u} \in U, \mathbf{w} \in W\}\), 生成空间的维度满足: \(\dim(U + W) = \dim U + \dim W - \dim(U \cap W)\).
- 如果两个向量子空间满足 \(U \cap W = \{\mathbf{0}\}\) (其中 \(\mathbf{0}\) 指零向量),那么它们的和被叫做直和(direct sum),写作 \(U \oplus W\), 并且有 \(\dim(U \oplus W) = \dim U + \dim W\).
- 线性映射(Linear maps)需要满足下列两个条件:
- \(T(\mathbf{x} + \mathbf{y}) = T\mathbf{x} + t\mathbf{y}, \forall \mathbf{x}, \mathbf{y} \in V\)
- \(T(\alpha \mathbf{x}) = \alpha T \mathbf{x}, \forall \mathbf{x} \in V, \alpha \in \mathbb{R}\)
- 向量空间中的线性映射叫做向量空间的同态(homomorphism),可逆的同态叫做同构 (isomorphism),如果存在从向量空间 \(V\) 到向量空间 \(W\) 的同构(写作 \(V \cong W\) ),那么 \(V\) 和 \(W\) 就称为同构的(isomorphic).
- 具有相同维度的有限维向量空间总是同构的。
- 巴拿赫空间(Banach space)是一个完备的赋范向量空间(normed vector space),希尔伯特空间(Hilbert space)是一个完备的内积空间(inner produce space)。
- 柯西不等式(Cauchy-Schwarz inequality): \(\left|\langle \mathbf{x}, \mathbf{y} \rangle\right| \leq \|\mathbf{x}\| \|\mathbf{y}\|\)
- 一个矩阵的迹(trace)等于它的特征值的和; 一个矩阵的行列式(determinant)等于它的特征值的积。
- 瑞利熵(Rayleigh quotients): \(R_\mathbf{A}(\mathbf{x}) = \frac{\mathbf{x}^{\top} \mathbf{A} \mathbf{x}}{\mathbf{x}^{\top}}\mathbf{x}\)
- 如果 \(\mathbf{x}\) 是 \(\mathbf{A}\) 的特征向量,对应的特征值为 \(\lambda\), 那么: \(R_\mathbf{A}(\mathbf{x}) = \lambda\)
- \(\lambda_{\min}(\mathbf{A}) \leq R_\mathbf{A}(\mathbf{x}) \leq \lambda_{\max}(\mathbf{A})\)
- 如果一个矩阵 \(\mathbf{Q}\) 的列向量全都两两 标准正交(orthonormal), 则称该矩阵是正交的(orthogonal),有下列等式存在: \(\mathbf{Q}^{\top}\mathbf{Q} = \mathbf{Q}\mathbf{Q}^{\top} = \mathbf{I}\).
- 对于一个对称矩阵 \(\mathbf{A} \in \mathbb{R}^{n \times n}\), 表达式 \(\mathbf{x}^{\top}\mathbf{A}\mathbf{x}\) 称为矩阵的二次型(quadratic form).
- 半正定(positive semi-definite)只有在对称矩阵上才有定义,具体定义为: 给定一个对称矩阵 \(\mathbf{A} \in \mathbb{R}^{n \times n}\), 如果对于所有的 \(\mathbf{x} \in \mathbb{R}^n\), 满足 \(\mathbf{x}^{\top}\mathbf{A}\mathbf{x} \geq 0\), 那么就称矩阵 \(\mathbf{A}\) 为半正定矩阵,记作 \(\mathbf{A} \succeq 0\).
- 函数的水平集/等高线(level set / isocontour)定义为: 具有相同函数输出值的输入值的集合。
- 对于一个正定矩阵 \(\mathbf{A} \in \mathbb{R}^{n \times n}\) (隐含了对称矩阵的含义)的二次型函数: \(f(\mathbf{x}) = \mathbf{x}^{\top} \mathbf{A} \mathbf{x}\), 该函数的等高线是一个椭球,轴的方向即为 \(\mathbf{A}\) 的特征向量,轴的半径即为对应特征值的 \(-\frac{1}{2}\) 次方(inverse square root).
在 .bashrc
中设置简洁的提示符
export PS1="\n\[\e[33m\]\u@\h\[\e[m\]:\w\n\[\e[1m\e[32m\]\\$\[\e[m\] "
数的定义 (\(\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R} \subset \mathbb{C}\)):
notation | description |
---|---|
\(\mathbb{N} = \{0, 1, 2, \cdots\}\) | the natural numbers |
\(\mathbb{Z} = \{m - n \mid m, n \in \mathbb{N}\}\) | the integers |
\(\mathbb{Q} = \{m / n \mid m, n \in \mathbb{Z}, n \neq 0\}\) | the rational numbers |
\(\mathbb{R}\) | the real numbers |
\(\mathbb{C}\) | the complex numbers |
The definitions of Group, Ring, Field and Ideal 11
- Group: A group is a set \(G\) equipped with a binary operation "\(\cdot\)" satisfying the following axioms (group axioms):
- Closure/Totality: \(a \cdot b \in G\) for all \(a, b \in G\).
- Associativity: \((a \cdot b) \cdot c = a \cdot (b \cdot c)\) for all \(a, b, c \in G\).
- Identity: There is an element \(1 \in G\) such that \(a \cdot 1 = 1 \cdot a = a\) for all \(a \in G\).
- Invertibility: Given \(a \in G\), there is \(a^{-1} \in G\) such that \(a \cdot a^{-1} = a^{-1} \cdot a = 1\).
- Ring: A ring is a set \(R\) equipped with two binary operations that is "\(+\)" (addition) and "\(\cdot\)" (multiplication) satisfying the following axioms (ring axioms):
- \(R\) is a commutative group under addition.
- \(R\) is a monoid under multiplication.
- Multiplication is distributive with respect to addition.
- Field: A field is a set \(F\) equipped with two binary operations that is addition and multiplication satisfying the following properties:
- Associativity of addition and multiplication.
- Commutativity of addition and multiplication.
- Additive and multiplicative identity.
- Additive and multiplicative invertibility.
- Multiplication is distributive with respect to addition.
- Ideal: Let \(R\) be a commutative ring, A subset \(I\) of \(R\) is an ideal if:
- If \(a, b \in I\), then \(a + b \in I\).
- If \(a \in I\) and \(b \in R\), then \(a \cdot b \in I\).
信息论中熵(entropy)的概念:
- 定义一个事件 \(\text{X} = x\) 的自信息(self-information)为: \(I(x) = -\ln P(x)\) 12, 对数底数如果是 \(e\), 那么自信息的单位就是奈特(nats); 如果对数底数是2那么单位就是比特(bits)或者香农(shannons).
- 服从某个分布的随机变量的香农熵(Shannon entropy)被定义为: \(H(x) = \mathbb{E}_{X \sim P}[I(x)] = -\mathbb{E}_{X \sim P}[\ln P(x)]\).
- KL散度(Kullback-Leibler (KL) divergence)可以用于衡量两个分布的差异: \(D_{KL}(P\|Q) = \mathbb{E}_{X \sim P}[\ln \frac{P(x)}{Q{x}}]\).
- KL散度具有非负性和非对称性,KL散度为0当且仅当两个分布是相同的分布(离散情况)或“几乎出处相同”(连续情况).
- 交叉熵(cross-entropy)定义为: \(H(P, Q) = -\mathbb{E}_{X \sim P}\ln Q(x)\), 它与KL散度的关系如下: \(H(P, Q) = H(P) + D_{KL}(P\|Q)\).
- 交叉熵可以理解为用 \(Q\) 的编码去发送 \(P\) 的消息所需要的信息量,而KL散度就是所需要的额外信息量。
两个随机变量的互信息(mutual information)定义为:
\begin{aligned} I(X, Y) &= KL(P(x, y) \| P(x)P(y)) \\ &= -\sum_{y \in Y} \sum_{x \in X} P(x, y) \ln \frac{P(x)P(y)}{P(x, y)} \end{aligned}互信息非负且对称,且有: \(I(X, Y) = H(X) - H(X|Y) = H(Y) - H(Y|X) = H(X) + H(Y) - H(X, Y)\). 互信息用来表示两个随机变量的相关性,互信息为0当且仅当它们是独立随机变量。
给定正整数 \(n \in \mathbb{Z}^{+}\), 矩阵 \(\mathbf{A} \in \mathbb{R}^{n \times n}\) 与定义在其上的乘法和加法构成一个环。
orgmode支持的语言: https://orgmode.org/worg/org-contrib/babel/languages.html
latex中的 split
和 aligned
环境都可以用来对齐公式,但是一般 split
是针对一个公式跨行的情况的。还有就是记得它们最好都配合 equation
环境一起用。
\begin{equation} \begin{split} \mathbf{U}\mathbf{U^{\top}} & = \mathbf{U}^{\top}\mathbf{U}\\ & = \mathbf{I} \end{split} \end{equation} \begin{equation*} \begin{aligned} E & = mc^2\\ a^2 + b^2 & = c^2 \end{aligned} \end{equation*}
谱定律(Spectral Theorem): 对称矩阵 \(\mathbf{A} \in \mathbb{R}^{n \times n}\) 存在由其特征向量组成的标准正交基。因此可以分解为下式,其中 \(\mathbf{Q}\) 的列向量即为原矩阵的标准正交基, 对角阵 \(\mathbf{\Lambda} = diag(\lambda_1, \lambda_2, \cdots, \lambda_n)\) 中的对角元素即为对应的特征值。 \[ \mathbf{A} = \mathbf{Q} \mathbf{\Lambda} \mathbf{Q}^{\top} \]
导出Safari的Reading List的一段Python脚本。
#!/usr/bin/env python import os import plistlib # load bookmarks plist into dict relpath = 'Library/Safari/Bookmarks.plist' fullpath = os.path.join(os.environ['HOME'], relpath) plist = plistlib.readPlist(fullpath) # get the reading list node for child in plist['Children']: if child.get('Title', None) == 'com.apple.ReadingList': bookmarks = child['Children'] # extract urls from each urls = (bookmark['URLString'] for bookmark in bookmarks) print('\n'.join(urls))
如果需要从外部(目录)执行Makefile,可以考虑 -C
参数来指定Makefile所在目录,这样可以避免目录引起的问题。
markdown-mode处理表格可以用 C-c C-d
对齐。
orgmode中条目的属性可以用 C-c C-x p
和 C-c C-c d
来增删。
A matrix \(\mathbf{A} \in \mathbb{R}^{m \times n}\) can be seen as a linear map from vector space \(V \in \mathbb{R}^n\) to \(W \in \mathbb{R}^m\).
The nullspace of \(A\) is defined as: \[ null(A) = \{\mathbf{v} \in V \mid A \mathbf{v} = \mathbf{0}\} \]
The range of \(A\) is defined as: \[ range(A) = \{\mathbf{w} \in W \mid \exists \mathbf{v} \in V \text{such that} A \mathbf{v} = \mathbf{w} \} \]
The nullspace and range are always the subspaces of the domain and codomain respectively. And they have the following relationships:
- \(null(\mathbf{A}) = range(\mathbf{A}^\top)^\perp\)
- \(null(\mathbf{A}) \oplus range(\mathbf{A}^\top) = \mathbb{R}^n\)
- If \(\mathbf{A} = \mathbf{U} \mathbf{\Sigma} \mathbf{V}^\top\) is the SVD of \(\mathbf{A}\), then:
Subspace | Columns |
---|---|
\(range(\mathbf{A})\) | The first \(r\) columns of \(\mathbf{U}\) |
\(range(\mathbf{A}^\top)\) | The first \(r\) columns of \(\mathbf{V}\) |
\(null(\mathbf{A}^\top)\) | The last \(m-r\) columns of \(\mathbf{U}\) |
\(null(\mathbf{A})\) | The last \(n-r\) columns of \(\mathbf{V}\) |
在 \(\LaTeX\) 中输入 arg min
:
\begin{equation*} w^{\ast} = \operatorname*{arg\,min}_{w}f(w) \end{equation*}
orgmode中代码块使用c++14标准: https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-C.html#org3d51d9d
#+BEGIN_SRC cpp :flags "-std=c++14" :includes '("<iostream>" "<vector>") :namespaces '("std") vector<int> v = {1, 2, 3}; for (auto x : v) cout << x; #+END_SRC
CentOS 7添加 firewalld
的防火墙规则。
# start firewalld service sudo systemctl start firewalld # enable firewalld service (start with system) sudo systemctl enable firewalld # allow port 80 sudo firewall-cmd --permanent --add-port=80/tcp # reload firewalld sudo firewall-cmd --reload
Archlinux基础系统安装
# 查看磁盘分区 fdisk -l # 交互式地对磁盘进行分区 fdisk /dev/sda # 格式化分区并启用SWAP分区 mkfs.ext4 /dev/sda1 mkswap /dev/sda2 swapon /dev/sda2 # 挂载分区 mount /dev/sda1 /mnt # 安装基础包 pacstrap /mnt base # 进入根目录操作 arch-chroot /mnt # 配置启动项 pacman -S grub grub-mkconfig -o /boot/grub/grub.cfg grub-install /dev/sda # 配置DHCP pacman -S dhcpcd systemctl start dhcpcd systemctl enable dhcpcd # 配置桌面 pacman -S xorg pacman -S i3-wm pacman -S rxvt-unicode echo "exec i3" > ~/.xinitrc
\(\LaTeX\)中加入咖啡印。
\documentclass{article} \usepackage{coffee4} \begin{document} \cofeCm{.2}{.4}{0}{.35\linewidth}{-.6\linewidth} I love coffee. \end{document}
\(\LaTeX\)自定义页码:
\documentclass{article} \usepackage{lastpage} \usepackage{fancyhdr} \renewcommand{\headrulewidth}{0pt} \cfoot{Page \thepage\ / \pageref{LastPage}} \pagestyle{fancy} \begin{document} The last page is \pageref{LastPage} \newpage ... \newpage ... \end{document}
单纯形(simplex)是在\(n\)维欧式空间中的\(n+1\)个仿射无关的点的集合的凸包。
有关线性模型局限的一个例子:考虑异或函数(两个输入值,当且仅当其中有一个为1的时候输出1,其他时候输出0),当\(x_1=1\)时,模型的输出必须随着\(x_2\)的增大而减小。线性模型必须对\(x_2\)使用固定的系数\(w_2\)。因此,线性模型不能使用\(x_1\)的值来改变\(x_2\)的系数,从而不能解决这个问题。
Dynamic Programming: dividing a large problem into simpler subproblems, solving these and storing their solutions, and combining the stored solutions to solve larger subproblems or the original problem.
What's the difference between probability and likelihood?
Denote the observed outcomes by \(O\) and the set of parameters that describe the stochastic process as \(\theta\). Given specific values for \(\theta\), \(P(O\mid \theta)\) is the probability that we would observe the outcomes. However, we often do not know \(\theta\). Thus, a 'natural' estimation process is to choose that value of \(\theta\) that would maximize the probability that we would actually observe \(O\). \(L(\theta \mid O)\) is called the likelihood function.
Capslock改键,短按为Esc,组合按键为Ctrl。
- Mac:
- 安装Karabiner-Elements
添加如下配置
"complex_modifications": { "parameters": { "basic.simultaneous_threshold_milliseconds": 50, "basic.to_delayed_action_delay_milliseconds": 500, "basic.to_if_alone_timeout_milliseconds": 1000, "basic.to_if_held_down_threshold_milliseconds": 500 }, "rules": [ { "manipulators": [ { "description": "Change caps_lock to control/esc.", "from": { "key_code": "caps_lock", "modifiers": { "optional": [ "any" ] } }, "to": [ { "key_code": "left_control", "modifiers": { "optional": [ "any" ] } } ], "to_if_alone": [ { "key_code": "escape", "modifiers": { "optional": [ "any" ] } } ], "type": "basic" } ] } ] }
- Linux:
- 安装xcape。
命令如下:
# make CapsLock behave like Ctrl: setxkbmap -option ctrl:nocaps # make short-pressed Ctrl behave like Escape: xcape -e 'Control_L=Escape'
- Windows:
- 运行由AutoHotKey编译产生的可执行文件(压缩包中包含源码): https://d.pr/4lZCGj
在Emacs里用mutt发送邮件
- 选中buffer中任意部分内容作为待发送的邮件正文。
- 按下组合键
M-|
,此时可以输入正常的shell命令并执行,注意刚才选中的region会被作为该命令的标准输入。 - 输入mutt命令:
mutt -s "Subject here" -a ~/attachment.txt someone@gmail.com
.
利用isync把一个邮箱中的邮件转移到另一个邮箱
# Transfer settings CopyArrivalDate yes Create Slave Sync Pull SyncState ~/.mbsync/imap-transfer # The IMAP server you wish to copy mails from. IMAPAccount imap-from-account SSLType IMAPS Host imap.yahoo.com User username@yahoo.com Pass xxxxx # The IMAP server you wish to copy mails to. IMAPAccount imap-to-account SSLType IMAPS Host imap.gmail.com User username@gmail.com Pass xxxxx # Link IMAP server to remote used below IMAPStore imap-from Account imap-from-account IMAPStore imap-to Account imap-to-account # Transfer mailboxes one by one Channel transfer-inbox Master :imap-from:"INBOX" Slave :imap-to:"INBOX" Channel transfer-sent Master :imap-from:"Sent" Slave :imap-to:"Sent"
mutt批处理邮件
T
: 开始标记邮件。~f marketing
: 标记From字段中包含marketing的所有邮件。;
: 要求对已标记邮件做批处理。d
: 删除所有已标记邮件。
Hadamard product is an entrywise product operation with two matrices of the same dimensions.
Python在交互式控制台执行文件指令:
exec(open("somefile.py").read())
flymake对C/C++的语法检查是依靠Makefile的,所以Makefile中需要有以下语法检查项目:
check-syntax: CC -Wall -Wextra -pedantic -std=c++14 -fsyntax-only $(CHK_SOURCES)
如果没有激活函数的作用,就不存在隐藏层了(因为多个线性单元可以组合成一个),那么模型的表达能力就会大打折扣,常用的激活函数有: Sigmoid, Tanh(比sigmoid更常用因为它是以原点对称的), ReLU(比较常用尤其是图像领域)。
把\(z_i\)看作是第\(i\)个神经单元的logit(logit是odds的对数,值越大表示事件可能性越高),那么有\(z_i = \log(p_i / (1-p_i))\),这里\(p_i\)表示概率,那么可以得到\(p_i = 1 / (1 + \exp(-z_i))\),即为sigmoid函数。
利用 pdfcrop
批量裁切pdf格式图片的白边。
for i in *.pdf; do pdfcrop $i $i.out; rm -f $i; mv $i.out $i; done
深度学习过拟合问题的解决办法:
- Get more training data
- Reduce the capacity of the network
- Add weight regularization
- Add dropout
- Data augmentation
- Batch normalization
unsupervised learning的应用:
- 聚类
- 降维
- 可视化
- 异常点检测
- 相关规则学习
The differences between MLE (Maximum Likelyhood Estimation) and MAP (Maximum A Posteriori):
- The goal of MLE is to find the hypothesis model that maximizes the probability of the data.
- The goal of MAP is to find the hypothesis model, for which the data maximizes the probability of the model.
概率分布的数学记号,\(p(y) = \mathcal{N}(y\mid\mu, \sigma)\)表示服从正态分布\(\mathcal{N}(\mu, \sigma^2)\)的变量\(y\)的概率。
tail
, sort
, colum
的用法示例。
# generate some content echo "id,income,expense\n1,4,6\n2,3,7" > foo.txt tail +2 foo.txt | sort -t ',' -k 2 | column -s ',' -t
VBR更适合视频的存储而CBR更适合视频的传输
- Twitch建议直播视频流使用CBR: https://blog.twitch.tv/better-broadcasting-with-cbr-d45fd4ed199
- Youtube的上传视频建议: https://support.google.com/youtube/answer/1722171?hl=en
- Youtube直播视频建议: https://support.google.com/youtube/answer/2853702?hl=en
GnuPlot绘图的示例,文件名 input.gpi
, 执行命令: gnuplot input.gpi
set terminal postscript eps enhanced color font "Helvetica,24" set output 'out.eps' set style fill solid 0.40 noborder set format y "%.1f" set key inside center top vertical Left reverse enhanced autotitles nobox set encoding utf8 set samples 500, 500 set xtics norangelimit set xtics ("-π" -3.14159, "-π/2" -1.57080, 0.00000, "π/2" 1.57080, "π" 3.14159) set title "Polynomial approximation of sin(x)" set xrange [ -3.20000 : 3.20000 ] noreverse nowriteback approx_1(x) = x - x**3/6 approx_2(x) = x - x**3/6 + x**5/120 approx_3(x) = x - x**3/6 + x**5/120 - x**7/5040 GPFUN_approx_1 = "approx_1(x) = x - x**3/6" GPFUN_approx_2 = "approx_2(x) = x - x**3/6 + x**5/120" GPFUN_approx_3 = "approx_3(x) = x - x**3/6 + x**5/120 - x**7/5040" label1 = "x - {x^3}/3!" label2 = "x - {x^3}/3! + {x^5}/5!" label3 = "x - {x^3}/3! + {x^5}/5! - {x^7}/7!" plot '+' using 1:(sin($1)):(approx_1($1)) with filledcurve title label1 lt 3, '+' using 1:(sin($1)):(approx_2($1)) with filledcurve title label2 lt 2, '+' using 1:(sin($1)):(approx_3($1)) with filledcurve title label3 lt 1, sin(x) with lines lw 1 lc rgb "black" # fix bounding box system("eps2eps out.eps desiredname.eps; rm out.eps")
C/C++:变量指针可以递增,而数组不能递增,因为数组是一个常量指针。
C++中引用和指针的区别
- 不存在空引用。引用必须连接到一块合法的内存。
- 一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
- 引用必须在创建时被初始化。指针可以在任何时间被初始化。
C/C++中定义指针变量时候的星号靠近类型或者变量是个人的喜好问题,但是我更偏向靠近变量名,看下面的例子
int *a, *b;
C++中引用的用法主要是作为函数形式参数和作为返回值返回。
- 作为函数形式参数
- 类似指针传递的作用,在被调用函数中对参数的操作会直接反馈到调用者函数。
- 作为函数返回值
- 返回过来的值可以作为赋值的左值。
C++类访问修饰符
public
: 公有成员在程序中类的外部是可访问的。private
: 私有成员变量或函数在类的外部是不可访问的。只有类和友元函数可以访问私有成员。protected
: 保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的。
C++中继承的访问控制几乎不使用protected或private继承,通常使用public继承。当使用不同类型的继承时,遵循以下几个规则:
- 公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
- 保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
- 私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
C++中一个派生类继承了所有的基类方法,但下列情况除外:
- 基类的构造函数、析构函数和拷贝构造函数。
- 基类的重载运算符。
- 基类的友元函数。
C++11遍历列表
int a[] = {1, 2, 3}; for (auto i : a) { std::cout << i << std::endl; }
交换两个文件的一个shell函数
function swap() { local TMPFILE=tmp.$$ mv "$1" $TMPFILE && mv "$2" "$1" && mv $TMPFILE $2 }
同时包含C和C++文件项目的Makefile示例
CC = cc CXX = c++ CFLAGS = -std=c99 -Wall -lm CXXFLAGS = -std=c++14 -Wall C_SRCS = $(wildcard *.c) C_OUTS = $(patsubst %.c, %, $(C_SRCS)) CXX_SRCS = $(wildcard *.cpp) CXX_OUTS = $(patsubst %.cpp, %, $(CXX_SRCS)) .PHONY: clean all: $(C_OUTS) $(CXX_OUTS) %.out: %.c $(CC) $(CFLAGS) $< -o $@ %.out: %.cpp $(CXX) $(CXXFLAGS) $< -o $@ clean: $(RM) $(C_OUTS) $(CXX_OUTS) check-syntax: check-syntax-c check-syntax-cpp check-syntax-c: $(CC) $(CFLAGS) -pedantic -fsyntax-only $(filter %.c,$(CHK_SOURCES)) check-syntax-cpp: $(CXX) $(CXXFLAGS) -pedantic -fsyntax-only $(filter %.cpp,$(CHK_SOURCES))
C++中优先队列(priority queue)的两种写法
auto comp = [](const int& x, const int& y) {return x > y;}; priority_queue<int, vector<int>, decltype(comp)> pq(comp);
struct CustomCompare { bool operator() (const int& x, const int& y) { return x > y; } } priority_queue<int, vector<int>, CustomCompare> pq;
Manifesto for Minimalist Software Engineers: http://minifesto.org
- Fight for Pareto's law, look for the 20% of effort that will give you the 80% of results.
- Prioritize, minimalism isn't about not doing things but about focusing first in the important.
- Perfect is enemy of good, first do it, then do it right, then do it better.
- Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast.
- Add value. Think constantly how you can help your team and position yourself in that field/skill.
- Basics, first. Follow always a top-down thinking starting by the best-practises of CS.
- Think different. Simple is harder than complex, which means you'll need to use your creativity.
- Synthesis is the key of communication. We have to write code for humans not machines.
- Keep it plain. Try to keep your designs with few layers of indirection.
- Clean kipple and redundancy. Minimalism is all about removing distractions.
C++中常用的容器
#include <iostream> #include <vector> #include <list> #include <stack> #include <queue> #include <set> #include <map> using namespace std; int main() { // vector std::vector<int> x_vector = {1, 2, 3}; x_vector.pop_back(); x_vector.emplace_back(4); cout << "vector member (random access): " << x_vector[1] << endl; cout << "vector first member: " << x_vector.front() << endl; cout << "vector last member: " << x_vector.back() << endl; // list std::list<int> x_list = {1, 2, 3}; x_list.pop_front(); x_list.emplace_front(0); x_list.pop_back(); x_list.emplace_back(4); cout << "list first member: " << x_list.front() << endl; cout << "list last member: " << x_list.back() << endl; // stack std::stack<int> x_stack({1, 2, 3}); x_stack.pop(); x_stack.emplace(4); cout << "stack member: " << x_stack.top() << endl; // queue std::queue<int> x_queue({1, 2, 3}); x_queue.pop(); x_queue.emplace(4); cout << "queue front member: " << x_queue.front() << endl; cout << "queue back member: " << x_queue.back() << endl; // set std::set<int> x_set = {1, 2, 3}; x_set.emplace(4); if (x_set.count(4)) cout << "set count test" << endl; // map std::map<int, int> x_map({{1, 11}, {2, 22}, {3, 33}}); x_map.emplace(4, 44); if (x_map.count(4)) cout << "map count test" << endl; return 0; }
二分查找(Binary Search)
bool binarySearch(const vector<int>& vec, int target) { int n = (int) vec.size(); int left = 0, right = n - 1; int mid; while (left <= right) { mid = (left + right) / 2; if (vec[mid] == target) { return true; } else if (vec[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return false; }
Leetcode 796: Rotate String: 题目意思是给一个字符串A,看它是不是可以通过平移几个字符的位置来得到字符串B。解题的思路是把A复制成重复的两份,看B是不是这个新字符串的子串,比较巧妙,复杂度比依次平移再判断要小。
class Solution { public: bool rotateString(string A, string B) { return A.size() == B.size() && (A + A).find(B) != string::npos; } };
C++中元素的元素查找和计数
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec = {1, 2, 3}; vector<int>::iterator it = find(vec.begin(), vec.end(), 3); if (it != vec.end()) cout << "found"; else cout << "not found"; cout << count(vec.begin(), vec.end(), 3); return 0; }
C++中实现类似列表推导式功能
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec = {1, 2, 3}; for_each(vec.begin(), vec.end(), [](int& n) {n++;}); for (auto v : vec) cout << v; return 0; }
注意C++里面的 std::vector<bool>
不是一个容器,它的迭代器不返回 bool&
而是一个代理实例(proxy instance).
#include <iostream> #include <vector> using namespace std; int main() { vector<bool> a(3, false); for_each(a.begin(), a.end(), [](vector<bool>::reference x) {x = true;}); for (auto i : a) cout << i; return 0; }
C++中表示数的最大值及极限
#include <iostream> #include <cfloat> using namespace std; int main() { cout << hex << INT_MAX << endl; cout << hex << UINT_MAX << endl; cout << hex << CHAR_MAX << endl; cout << hex << UCHAR_MAX << endl; cout << hex << numeric_limits<double>::max() << endl; cout << hex << numeric_limits<double>::infinity() << endl; // defined in header <cfloat> cout << hex << DBL_MAX << endl; return 0; }
C++向量从后往前搜索元素
#include <iostream> #include <vector> using namespace std; int main() { vector<int> x = {1, 2, 1}; cout << distance(find(x.rbegin(), x.rend(), 1), x.rend()) - 1; if (find(x.rbegin(), x.rend(), 3) == x.rend()) cout << "Not Found"; return 0; }
ranger可以用 dc
来显示文件夹大小,调用的是 get_cumulative_size
.
C++中集合的交与并
#include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; int main() { set<int> a = {1, 2, 3}; set<int> b = {2, 3, 4}; vector<int> c; // set intersection set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c)); for (auto i : c) cout << i; c.clear(); cout << endl; // set union set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c)); for (auto i : c) cout << i; return 0; }
如何写好一份简历: This is what a GOOD resume should look like
- HR基本上只有15-30秒的时间看你的简历。
- 尽量保持在一页,除非有十年以上的工作经历。
- 不用写应聘职位,因为这个信息在投简历的时候就已经告知给对方了,不用再浪费篇幅。
- 分条目列出来的项目尽量短一点。
- 围绕你所做到的、创造的、优化的来写而不是你负责的什么之类的。
- 做一些必要的量化,比如说你完成了什么任务,那么这个任务做到什么程度呢。
- 如果GPA在三分以上的话可以考虑写上。
- 项目可以是未上线的甚至未完成的,但是必须是足够令人印象深刻的。
- 专业技术可以只写最擅长的几个(也就是你觉得面试时候问不倒你的那些),如果感觉有点虚的话就还是乖乖括号里写上“熟练”、“熟悉”之类的词吧。
- 尽量写必要的信息,别人不关心不要写。
- 方差: \(var(X) = E((X - E(X))^2) = E(X^2) + E(X)^2\);
- 协方差: \(cov(X, Y) = E((X-E(X)) (Y-E(Y)))\);
- 相关系数: \(\rho_{X,Y} = corr(X,Y) = \frac{cov(X,Y)}{\rho_X\rho_Y}\)
用互信息做特征选择
- 为什么不通过计算特征变量与标签变量的相关性来做特征选择,因为相关性分析只能用于数值型变量,而且其只适用于线性相关,无法描述一些非线性关系。
- 记某特征变量为\(X\),标签变量为\(Y\),其互信息定义如下,互信息非负,当且仅当两个变量独立时取等号:
\[ \mathbb{I}(X;Y)\triangleq \mathbb{KL}(p(X,Y)\|p(X)p(Y)) = \sum_x\sum_y p(x, y)\log\frac{p(x, y)}{p(x)p(y)} \]
- 在特征选择的语境下,互信息可以理解为在观测到该特征的分布时标签变量熵的减少。
- [bookmarklet] Add to Google bookmarks
javascript:(function(){var%20a=window,b=document,c=encodeURIComponent,d=a.open("https://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=%22+c(b.location)+%22&title=%22+c(b.title),%22bkmk_popup%22,%22left=%22+((a.screenX||a.screenLeft)+10)+%22,top=%22+((a.screenY||a.screenTop)+10)+%22,height=510px,width=550px,resizable=1,alwaysRaised=1%22);a.setTimeout(function(){d.focus()},300)})();
- [bookmarklet] Share on Twitter
javascript:(function(){var%20a=window,b=document,c=encodeURIComponent,d=a.open("https://twitter.com/share?url=%22+c(a.location.href)+%22&text=%22+c(b.title),%22bkmk_popup%22,%22left=%22+((a.screenX||a.screenLeft)+10)+%22,top=%22+((a.screenY||a.screenTop)+10)+%22,height=510px,width=550px,resizable=1,alwaysRaised=1%22);a.setTimeout(function(){d.focus()},300)})();
通过IMAP列出邮件服务器上的目录
curl --url "imaps://imap.gmail.com/" --user "xxxx@gmail.com"
用ffmpeg拼接视频
ffmpeg -f concat -i <(for i in *.mp4; do echo "file '$i'"; done) -c copy output.mp4
Apache服务器的配置及启动(以Tiny-Tiny-RSS为例)
- 实际的网站目录放到
/var/www/html/ttrss
中 创建配置文件
/etc/httpd/conf.d/ttrss.conf
监听81端口Listen 81 NameVirtualHost *:81 <Directory /var/www/html/ttrss/cache> Require all denied </Directory> <Directory /var/www/html/ttrss> <Files "config.php"> Require all denied </Files> </Directory> <VirtualHost *:81> ServerName Test1 DocumentRoot "/var/www/html/ttrss" DirectoryIndex index.php </VirtualHost>
开启并激活httpd守护进程
sudo systemctl start httpd sudo systemctl enable httpd
[TTRSS] 安装并配置postgresql数据库
yum install postgresql10 sudo systemctl start postgresql-10 sudo systemctl enable postgresql-10
[TTRSS] 配置RSS源自动更新的守护进程,配置文件为
/etc/systemd/system/ttrss-updater.service
[Unit] Description=ttrss_backend After=network.target mysql.service [Service] User=apache ExecStart=/var/www/html/ttrss/update_daemon2.php [Install] WantedBy=multi-user.target
配置Shadowsocks服务器
创建配置文件
/etc/shadowsocks/shadowsocks.json
{ "server": ["[::0]", "0.0.0.0"], "server_port": 2018, "local_address": "127.0.0.1", "local_port": 1080, "password": "somepasswordhere", "timeout": 600, "method": "rc4-md5" }
创建文件
/etc/systemd/system/shadowsocks.service
以配置守护进程[Unit] Description=Shadowsocks Server [Service] User=root Group=root Type=simple ExecStart=/usr/local/bin/ss-server -c /etc/shadowsocks/shadowsocks.json [Install] WantedBy=multi-user.target
启动并激活守护进程
sudo systemctl start shadowsocks sudo systemctl enable shadowsocks
禁止root用户通过密码从ssh登录(其他用户无此限制),配置文件在 /etc/ssh/sshd_config
PasswordAuthentication yes Match User root PasswordAuthentication no Match all
清理Debian/Ubuntu系统
# clear out the local repository of retrieved package files apt-get clean apt-get autoclean # remove packages that were automatically installed to satify dependencies apt-get autoremove # deporphan is not built-in, it works like autoremove but much aggressively deborphan | xargs apt-get -y purge
基于iptables配置防火墙
设置iptables规则,最后可以用
iptables -L
查看。# clean up iptables -F iptables -X iptables -Z # permit legal connections iptables -A INPUT -i lo -j ACCEPT iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # permit port for ssh iptables -A INPUT -p tcp --dport 22 -j ACCEPT # permit port for http/https iptables -A INPUT -p tcp -m multiport --dport 80,443 -j ACCEPT # set fallback rules iptables -P OUTPUT ACCEPT iptables -P INPUT DROP iptables -P FORWARD DROP
- 如果是远程服务器的话,在进行下一步操作之前,测试并确保仍可以通过ssh连接,否则会有丢失服务器管理权限的风险。
让当前的iptables规则在主机重启后仍然生效,这一步可以根据不同发行版来做修改,CentOS的话可以直接交给systemd的一个iptables守护进程来实现
iptables-save > /etc/sysconfig/iptables systemctl enable iptables systemctl start iptables
深度学习(deep learning)其实就是有多个隐藏层的神经网络(neural networks),那么为什么需要多个隐藏层呢,可以从两个方面来理解:
- 拿人脸识别来说,深度神经网络可以看作是一个从无意义的像素数据开始逐层理解高层语意的过程,前面的隐藏层可能是在进行边缘检测之类的底层操作,而后面的隐藏藏可能就是再做类似识别男女、是否双眼皮之类的高层语意信息了。
- 用电路理论(circuit theory)来类比,我们假设输入的特征有很多,那么在只有一个隐藏层的情况下来“猜测”对应输出的概率需要大量的计算量,而多个隐藏层就可以分担掉快速增长的计算量。
Emacs中基于S表达式的快捷操作
C-M-f
: 向前移动一个S表达式C-M-b
: 向后移动一个S表达式C-M-d
: 移动到光标后的一个S表达式中(down)C-M-u
: 移动到当前所在S表达式到开头(up)C-M-k
: 删除光标后到一个S表达式
Logistic Regression中用sigmoid映射的原因
- 给定二分类问题,输入\(\boldsymbol{x}\),输出\(y \in \{1, 0\}\).
- 给定样本输入\(\boldsymbol{x}\),我们希望能得到它属于某类的概率p,但是如果直接采用一个线性函数来映射:\(\boldsymbol{w}^{\top}\boldsymbol{x}\),得到的值定义在整个实数范围内,与概率的定义(在0到1之间)不符。
- 我们先放一放上面的映射问题,考虑分对数(logit),它是几率(odds)的对数:即\(logit = \log \frac{p}{1 - p}\),可以发现logit也刚好是定义在实数范围内的单调函数。
- 我们把logit和\(\boldsymbol{w}^{\top}\boldsymbol{x}\)对应起来,那么就可以得到概率p的映射\(p = \frac{1}{1 + e^{-\boldsymbol{w}^{\top}\boldsymbol{x}}}\),这个就是sigmoid函数了。
利用生成式模型进行分类的一个基础公式: \[ p(y = c \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{p(y=c\mid \boldsymbol{\theta}) p(\boldsymbol{x}\mid y=c,\boldsymbol{\theta})}{\Sigma_{c^\prime}p(y=c^\prime \mid \boldsymbol{\theta}) p(\boldsymbol{x} \mid y=c^\prime, \boldsymbol{\theta})} \]
期望(expectation)和方差(variance)都是定义在函数上的,而不是变量。
机器学习中对分类问题的处理可以分成两步来理解,第一步叫做推断(inference),在这一步中我们使用训练数据来学习后验概率的模型;第二步叫做决策(decision),在这一步中我们根据后验概率来决定类别。
安装Jekyll到用户目录
gem install --user-install --no-doc jekyll
注意最后还需要把gem的可执行文件目录加入到系统环境变量中.
echo "export PATH=\"\$(ruby -e 'print Gem.user_dir')/bin:\$PATH\"" >> ~/.zshrc
Transmission可以用这个配置来屏蔽IPv4流量: https://nwps.ws/pub/misc/ipv4-blocklist.txt
如果先验跟后验有相同的形式,那么这个先验就是对应似然的共轭先验(conjugate prior),先验分布的参数被称为超参数(hyper-parameters),在二项分布的情况下,其共轭先验就是Beta分布;而多项式分布的共轭先验是Dirichlet分布。
Paparazzi!是macOS平台上一个小巧的网页截图工具: https://derailer.org/paparazzi/
zsh有五个配置文件,默认是在用户家目录里的,但是我习惯一股脑都放到 .zshrc
里。
$ZDOTDIR/.zshenv $ZDOTDIR/.zprofile $ZDOTDIR/.zshrc $ZDOTDIR/.zlogin $ZDOTDIR/.zlogout
电子书下载网站
- https://mlook.mobi/
- https://bookset.me/
- https://shuwu.mobi/
- http://booksk.com/
- https://jiumodiary.com/
英文邮件的落款注意事项
- 英国人常用Yours sincerely而美国人常用Sincerely yours.
- 英国人会觉得省略yours不礼貌。
- 只要第一个单词的首字母大写。
- 后面加逗号,然后换行写自己的名字。
禁止搜索引擎收录网页中的图片
<meta name="robots" content="noimageindex">
欧拉公式: \[ e^{i\theta} = \cos\theta + i\sin\theta \]
\(\LaTeX\)加水印:
\usepackage{draftwatermark}
用pngquant来对png图片进行无损压缩
pngquant foo.png --skip-if-larger --force --output foo.png
zip压缩命令,压缩等级可以用 -0, -1, -2, ..., -9
来表示,默认是 -6
, 数字越大表示压缩率越大。
zip foo.zip -r -9 foobar
一个方便统计当前目录下文件(包括隐藏文件)磁盘占用的别名
alias duu="du -hs .[^.]* * | sort -rh"
vim可以用 gqip
达到跟emacs下的 fill-paragraph
一样的调整换行的作用,可配置选项 textwidth
对应emacs下的 fill-column
。
vim中可以用 :vim foo **/*.py
来进行递归地 vimgrep
操作。
grep后进行字符串替换
grep -rl "foo" * | xargs sed -i "" "s/foo/bar/g"
图片压缩
搜索电子书的一个技巧,直接Google: icaredbd.com 书名 azw3
vim中删除匹配模式的行,下面的例子是删除所有以 foo
开始的行
:g/^foo/d
中文世界通常所说的“英国”指的实际上是“United Kindom”(联合王国),全称“United Kingdom of Great Britain and Northern Ireland”(大不列颠及北爱尔兰联合王国),其中包含四个构成国:首都为London(伦敦)的England(英格兰);首都为Edinburgh(爱丁堡)的Scotland(苏格兰);首都为Cardiff(加的夫)的Wales(威尔士);首都为Belfast(贝尔法斯特)的Northern Ireland(北爱尔兰)。而“Great Britan”(大不列颠)由除北爱尔兰之外的其他三个构成国组成。
Git打标签
# 创建一个tag git tag v0.1 # 更新tag至远程仓库 git push --tags # 删除本地及远程仓库中的tag git tag -d v0.1 git push origin :refs/tags/v0.1
根据一级标题将org-mode文件导出到单独的多个文件
(defun org-export-headlines-to-pdf () "Export all subtrees that are *not* tagged with :noexport: to separate files. Subtrees that do not have the :EXPORT_FILE_NAME: property set are exported to a filename derived from the headline text." (interactive) (save-buffer) (let ((modifiedp (buffer-modified-p))) (save-excursion (goto-char (point-min)) (goto-char (re-search-forward "^*")) (set-mark (line-beginning-position)) (goto-char (point-max)) (org-map-entries (lambda () (let ((export-file (org-entry-get (point) "EXPORT_FILE_NAME"))) (unless export-file (org-set-property "EXPORT_FILE_NAME" (replace-regexp-in-string " " "_" (nth 4 (org-heading-components))))) (deactivate-mark) (org-pdf-export-to-pdf nil t) (unless export-file (org-delete-property "EXPORT_FILE_NAME")) (set-buffer-modified-p modifiedp))) "-noexport" 'region-start-level))))
Org-mode中插入图片可以这样指定大小
#+attr_html: :width 200 #+attr_latex: :width 200 [[~/Desktop/foo.png]]
Org-mode导出pdf想要为hyperref添加 hidelinks
参数的话可以有以下几种方案
- 修改
org-latex-default-packages-alist
, 该列表变量包含了默认加载的包,其中包含了未指定参数的hyperref,我们可以通过(add-to-list 'org-latex-default-packages-alist "\\PassOptionsToPackage{hidelinks}{hyperref}")
来给hyperref追加hidelinks
选项。 - 在org文件头部加
#+latex_header: \hypersetup{hidelinks}
来实现。 - 修改
org-latex-hyperref-template
: 该列表本身包含了\hypersetup{...}
的设置,在其中加入hidelinks
即可。
Bayesian and non-Bayesian
The rules of probability ensure that if two people make the same assumptions and receive the same data then they will draw identical conclusions. This more general use of probability to quantify beliefs is known as the Bayesian viewpoint. It is also known as the subjective interpretation of probability, since the probabilities depend on assumptions. Advocates of a Bayesian approach to data modelling and pattern recognition do not view this subjectivity as a defect, since in their view,
You cannot do inference without making assumptions.
The big difference between Bayesian and non-Bayesian is that: Bayesian use probabilities to describe both random variables and inferences while non-Bayesian use probabilities to describe only random variables.
Never say "the likelihood of the data". Always say "the likelihood of the parameters". The likelihood function is not a probability distribution.13
If \(\theta\) denotes the unknown parameters, \(D\) denotes the data, and \(\mathcal{H}\) denotes the overall hypothesis space, the general equation:
\[ P(\theta | D, \mathcal{H}) = \frac{P(D | \theta, \mathcal{H}) P(\theta | \mathcal{H})}{P(D | \mathcal{H})} \]
is written:
\[ \text{posterio} = \frac{\text{likelihood} \times \text{prior}}{\text{evidence}} \]
Probability and Likelihood
- For a fixed \(\theta\), \(P(D | \theta, \mathcal{H})\) defines a probability over \(D\).
- For a fixed \(D\), \(P(D | \theta, \mathcal{H})\) defines the likelihood of \(\theta\).
\(\LaTeX\)中如果要强制使用英文的分段样式(即段落垂直间隔而首行不缩进),尤其是在CTEX环境下,可以通过导入 parskip
包来实现。
Org-mode导出文档时不显示作者、日期等:
#+OPTIONS: author:nil date:nil
从Kindle的笔记文件 My Clippings.txt
中随机输出一条
BEGIN { clipping = ""; i=0; srand(); } { if ($0 !~ /==========/) { if ($0 !~ /- /) { clipping = $0 "\r\n" clipping; } else { clipping = "-- " clipping; } } else { clippings[i++] = clipping; clipping = ""; } } END { print clippings[int(rand()*i)]; }
lighttpd中启用CGI模块
server.modules += "mod_cgi" cgi.assign = (".cgi" => "")
lighttpd中禁止访问某后缀的文件
url.access-deny = ( ".txt", ".pdf" )
lighttpd中禁止访问某目录
$HTTP["url"] =~ "^/res/" { url.access-deny = ("") }
将CGI输出结果放到一个div中
<body onload="zSay()"> <div id="quote"></div> <script type="text/javascript"> function zSay() { var div = document.getElementById("quote"); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) { div.innerHTML = this.responseText; } else { div.innerHTML = "<h1>Error " + this.status + "</h1><p>The content could not be loaded.</p>"; } } }; xhttp.open("GET", "cgi-bin/zsay.cgi", true); xhttp.send(); } </script> </body>
Google搜索中文网页: https://google.com?lr=lang_zh-CN
奇异值分解和特征值分解都是给一个矩阵(线性变换)找一组特殊的基:
- 奇异值分解则找到一组基,这组基下线性变换的旋转、缩放、投影三种功能独立地展示出来了。
- 特征值分解找到了特征向量这组基,在这组基下该线性变换只有缩放效果。
SCI收录号(Accession Number)查询: https://webofknowledge.com/
Python基于虚拟环境的依赖管理:
python3 -m venv .venv source .venv/bin/activate pip install <pkgname1> <pkgname2> pip freeze > requirements.txt echo ".venv/" >> .gitignore
Dashes in \(\LaTeX\)
- hyphen:
-
- en dash:
--
- em dash:
---
Emacs设置本地变量操作minor modes,不要直接用变量(VARIABLE)设置,这样会有安全问题14,推荐用 eval:
,比如下面的设置会在该文件中禁用 flyspell-mode
:
eval: (flyspell-mode -1)
廉价VPS
- LowEndSpirit OpenVZ MiniVPS (3.50 EUR/Year): https://clients.inceptionhosting.com/cart.php?gid=13
- AlphaRacks OpenCV (8 USD/Year): https://www.alpharacks.com
Emacs中calc模式下可以用 M-0 DEL
来清空栈。
在决策树中,每次数据集分叉的准则是最大化Gini Gain,指的是分叉前后的Gini Impurity减少的量。
Vim的补全框架对比
- vim-mucomplete: 由vim script驱动,只是一个前端(但默认就支持路径补全),需要另外安装补全后端如
vim-jedi
,clang-compelte
. - completor.vim: 由python驱动,扩展性强,配置简单。
Vim补全框架vim-mucomplete配置
let g:mucomplete#no_mappings=1 let g:mucomplete#enable_auto_at_startup=1
默认的Org-mode导出pdf时需要两个包: wrapfig
, capt-of
.
texlive显示已安装的包:
tlmgr list --only-installed
简单但不失优雅的网页样式
body { max-width: 38rem; padding: 2rem; margin: auto; }
BibTex引用网页文章的条目
@online{duggan2013photo, title = {Photo and Video Sharing Grow Online}, author = {Duggan, Maeve}, url = { }, urldate = {2018-01-21}, year = 2013 }
Linux隐藏输出
Hide
stdout
:./foo.sh >/dev/null
Hide
stdout
andstderr
:./foo.sh >/dev/null 2>&1
在网页动态内容加载完成后用MathJax进公式的渲染:
首先,头部加载MathJax脚本时加入
delayStartupUntil=configured
参数。<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured"></script>
为动态加载内容完成后触发MathJax配置。
var xhttp = new XMLHttpRequest(); ... xhttp.addEventListener('load', function(e){MathJax.Hub.Configured();});
目标函数和所有的约束函数都为线性函数,则该问题为线性规划问题(Linear Programming)。相反,如果目标函数或任何一个约束函数为非线性函数,则该问题为非线性规划问题(Nonlinear Programming) 。
凸优化问题是一种特殊的约束优化问题,需满足目标函数为凸函数,并且等式约束函数为线性函数,不等式约束函数为凹函数。
拷贝SSH公钥到服务器
ssh-copy-id ~/.ssh/id_ed25519.pub user@host
Linux中创建用户
# create a user and create its home directory useradd -m someone # add a user to the `sudo' group adduser someone sudo
一般来说,混淆矩阵的横行代表真实标签,纵列代表预测标签
mat <- matrix(c(1, 0, 0, 1, 1, 0, 1, 0, 1), nrow=3) # mat: # [,1] [,2] [,3] # [1,] 1 1 1 # [2,] 0 1 0 # [3,] 0 0 1 accuracy <- sum(diag(mat)) / sum(mat) # [1] 0.6 precision <- diag(mat) / rowSums(mat) # [1] 0.3 1.0 1.0 recall <- diag(mat) / colSums(mat) # [1] 1.0 0.5 0.5
Homebrew显示软件包的依赖情况
brew deps --tree --installed
Matplotlib使用自定义字体,分下列三种情况讨论:
提供额外字体目录给matplotlib,让其对目录中的字体进行解析,注意这种方式只会解析
ttf
格式的字体文件,而ttc
格式的字体文件会被忽略。另外,字体文件的文件名可能和其定义的字体名称不同,matplotlib视角下的字体名称可以在列表[f.name for f in matplotlib.font_manager.fontManager.ttflist]
中查看。import matplotlib.pyplot as plt import matplotlib.font_manager as fm # 添加字体搜索路径 font_dirs = ["/Library/Fonts", "./fonts"] font_files = fm.findSystemFonts(fontpaths=font_dirs) font_list = fm.createFontList(font_files) fm.fontManager.ttflist.extend(font_list) # 指定全局的绘图字体 plt.rcParams['font.family'] = ['STKaiti', 'sans-serif'] # 绘图测试 plt.plot(range(5)) plt.title("测试Matplotlib绘图字体") plt.show()
直接指定字体文件位置来设置字体
import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.font_manager as fm # 指定自定义字体 font_list = fm.createFontList(["./fonts/Kaiti.ttf"]) fm.fontManager.ttflist.extend(font_list) # 指定全局绘图字体 plt.rcParams['font.family'] = ['STKaiti', 'sans-serif'] # 绘图测试 plt.plot(range(5)) plt.title("测试Matplotlib绘图字体") plt.show()
仅在某些位置使用自定义字体
import matplotlib.pyplot as plt import matplotlib.font_manager as fm # 定义字体 cfont = fm.FontProperties(fname="./fonts/Kaiti.ttf") # 绘图测试 plt.plot(range(5)) plt.title("测试Matplotlib绘图字体", fontproperties=cfont) plt.show()
matplotlib修改默认样式
import matplotlib.pyplot as plt plt.rcParams['font.size'] = 8 plt.rcParams['font.family'] = 'sans-serif' plt.rcParams['font.serif'] = ['DejaVu Serif'] plt.rcParams['font.sans-serif'] = ['DejaVu Sans'] plt.rcParams['font.monospace'] = ['DejaVu Sans Mono'] plt.rcParams['grid.linestyle'] = 'dashed' plt.rcParams['grid.linewidth'] = 0.5 plt.rcParams['grid.alpha'] = 0.5 plt.rcParams['legend.fontsize'] = 8 plt.rcParams['axes.labelsize'] = 8 plt.rcParams['axes.titlesize'] = 8 plt.rcParams['xtick.labelsize'] = 8 plt.rcParams['ytick.labelsize'] = 8 plt.rcParams['savefig.dpi'] = 150 plt.rcParams['figure.figsize'] = [3.39, 2.10]
CTEX中强制取消中英文之间的空格。
\(\LaTeX\) 中 \autoref{}
引用时的格式:
\def\equationautorefname~#1\null{Equation~(#1)\null}
利用dos2unix命令递归地修改文件编码
find . -type f -exec dos2unix --keepdate {} +
Emacs编辑远程文件,其中的 method
可以是ssh或者ftp等。
/method:host:filename /method:user@host:filename /method:user@host#port:filename
Vim的各种补全插件比较
lifepillar/vim-mucomplete: 纯vimscript实现的一个精简补全前端框架。
Plug 'lifepillar/vim-mucomplete' let g:mucomplete#no_mappings = 1 let g:mucomplete#enable_auto_at_startup = 1
autozimu/LanguageClient-neovim: Rust实现的LSP客户端,没有什么特别的依赖,只要vim版本够高就行,补全的话只提供后端实现,所以如果需要高级的补全定制就需要与mucomplete之类的前端配合。
Plug 'autozimu/LanguageClient-neovim', {'branch': 'next', 'do': './install.sh'} let g:LanguageClient_serverCommands = {'python': ['pyls']}
w0rp/ale: 纯vimscript实现的异步语法检查插件,但同时也可以作为LSP客户端,还有自带的自动补全功能,因此总觉得功能过于庞杂。
Plug 'w0rp/ale' let g:ale_set_highlights = 0 let g:ale_completion_enabled = 1 let g:ale_linters = {'python': ['pyls', 'flake8']}
natebosch/vim-lsc: 纯vimscript实现的LSP客户端,缺点是它提供的语法检查是改变字体颜色来实现的,而不是在sign column中显示。
Plug 'natebosch/vim-lsc' let g:lsc_autocomplete_length = 1 let g:lsc_server_commands = {'python': 'pyls'}
maralla/completor.vim: 依赖Python的补全框架,各个语言的补全后端由独立的插件提供。
Plug 'maralla/completor.vim' let g:completor_complete_options='menuone,noselect' let g:completor_python_binary='python3'
主流的邮件存储格式主要有mbox和maildir,前者的历史较后者来得悠久。两者主要区别在于mbox把邮箱中的所有邮件存储在一个文件中,而maildir则将邮件分成单独的文件存储。就现代的邮箱使用习惯来说,不管是在邮箱可靠性还是大邮件的更新速率等多个方面,maildir的性能都是要优于mbox的,因此一般也更推荐maildir格式。
至于应用对这两者的支持,isync默认以maildir存储,而mutt默认是mbox格式,可以通过在配置文件中 set mbox_type=Maildir
进行修改。
macOS平台下的邮件应用仅支持导入mbox格式的邮件,不过可以通过下面的脚本将mbox转换为maildir格式再进行导入,运行 python maildir2mbox.py maildir_folder mails.mbox
即可。
import mailbox import sys import email def md2mb(md, mb): """ Convert mailbox format from maildir to mbox. Inspired by: https://github.com/bluebird75/maildir2mbox """ if sys.version_info < (3, 0): mdir = mailbox.Maildir(md, email.message_from_file) else: mdir = mailbox.Maildir(md, email.message_from_binary_file) mbox = mailbox.mbox(mb) for msg in mdir: mbox.add(msg) mbox.close() mdir.close() if __name__ == '__main__': md2mb(sys.argv[-2], sys.argv[-1])
openssl通过文件来进行对称的加密/解密。
# encryption openssl rc4 -in foo.txt -out foo.enc -pass file:pass.key # decryption openssl rc4 -in foo.enc -pass file:pass.key -d
IMAP邮箱名称会出现utf-7跟utf-8相关的编码问题,用imapclient可以解析utf-7.
from imapclient import imap_utf7 decoded = imap_utf7.decode(b'&UXZO1mWHTvZZOQ-') print(decoded)
mutt中可以通过设置 sort
参数的值暂时改变邮件排序方式,比如通过 set sort=reverse-size
来按照邮件大小从大到小排列。
mutt中的邮件过滤和标记后批量处理功能:
- 邮件过滤显示是通过按键
l
(limit)实现的,根据提示输入不同的标识符可以实现不同的过滤需求~s party
: 过滤出邮件标题(subject)中包含attention
的邮件。~b party
: 过滤出邮件正文(body)中包含party
的邮件。~B party
: 从邮件全部信息中搜素关键词party
并过滤。~f foo@gmail.com
: 按照发件人(From:)过滤。~t
: 按照收件人(To:)过滤。~=
: 按照Message-ID过滤出重复邮件(需要开启threads显示)。all / . / ^ / ~A
: 这几个标识符都可以用来清除当前过滤器以便显示所有消息。
- 邮件批量处理是通过标记并对带标记邮件执行相关操作来实现的:
- 邮件标记可以通过按键
t
来对邮件逐个进行手动标记,或者通过按键T
后接修饰符(与邮件过滤中所用的修饰符相同)来批量标记。 - 在标记完成后,要使接下来的邮件指令作用到标记邮件而不是当前光标所在位置邮件,需要在指令前加前缀
;
, 如;d
表示删除已标记邮件,;s
表示将已标记邮件保存到指定位置,;c
表示将已标记邮件拷贝到指定位置。
- 邮件标记可以通过按键
mutt配色
# --- vombatidae text colors --- color normal color253 color234 color message color253 color234 # --- slightly less yellow text colors --- color indicator color230 color238 color status color101 color16 color tree color208 color234 color signature color102 color234 color attachment color117 color234 color error color30 color234 color tilde color130 color235 color search color100 color234 color markers color138 color234 color quoted color107 color234 color quoted1 color66 color234 color quoted2 color32 color234 color quoted3 color30 color234 color quoted4 color99 color234 color quoted5 color36 color234 color quoted6 color114 color234 color quoted7 color109 color234 color quoted8 color41 color234 color quoted9 color138 color234 color body cyan color234 "((ftp|http|https)://)[^ >)\"\t]+" color body cyan color234 "[-a-z_0-9.+]+@[-a-z_0-9.]+" color index color202 color234 ~F color index color39 color234 ~N color index color39 color234 ~O color index color229 color22 ~T color index color240 color234 ~D # --- header --- color hdrdefault color30 color233 color header color132 color233 '^date:' color header color153 color233 '^(to|cc|bcc):' color header color120 color233 '^from:' color header color178 color233 '^subject:' color header color31 color233 '^user-agent:' color header color29 color233 '^reply-to:'
macOS Sierra新加入的字体 SF Mono
默认不是全局不可见,它的文件位置在: /Applications/Utilities/Terminal.app/Contents/Resources/Fonts/
下面这些项目结构比较简单,而且代码风格也非常规范,值得作为程序设计、项目开发的例子来学习。
- C
- noice - small file browser: https://git.2f30.org/noice/
- C
- smu - simple markdown markup: https://github.com/Gottox/smu
新鲜服务器的基本配置:
- 更新系统,安装: vim, tmux, openssh, zsh。
- 配置ssh公钥登陆。
- 上传配置文件: vim, tmux, zsh,并测试可用性
- 利用iptables配置防火墙
口碑不错的卖旅行包的店铺:
- Minall: https://www.minaal.com
- Tom Bihn: https://www.tombihn.com
如果某个服务器上的scp或rsync都不能用,可以用如下的方法来传输文件到服务器上:
cat ./foo.txt | ssh username@ipaddress "cat > ~/somepath/foo.txt"
lighttpd配置SSL,配置文件在 /etc/lighttpd/lighttpd.conf
$SERVER["socket"] == ":443" { ssl.engine = "enable" ssl.pemfile = "/etc/lighttpd/certs/server.pem" }
lighttpd按照域名指定网站目录,配置文件在 /etc/lighttpd/lighttpd.conf
$HTTP["host"] =~ "(^|www\.)domain\.com$" { server.document-root = "/var/www/root/" } $HTTP["host"] == "foo.domain.com" { server.document-root = "/var/www/foo_path/" server.modules += ("mod_cgi") cgi.assign = (".cgi" => "") url.access-deny = (".txt") } $HTTP["host"] == "bar.domain.com" { server.document-root = "/var/www/bar_path/" server.modules += ("mod_cgi") cgi.assign = (".cgi" => "") }
R语言中ggplot2使用系统字体
library(Cairo) p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("楷体") + xlab("横坐标") + ylab("纵坐标") + theme_bw() + theme(text=element_text(family="STKaiti")) ggsave(filename="test.pdf", plot=p, device=cairo_pdf)
Emacs下获取当前行号
(format-mode-line "%l")
用CSS来使网页自适应系统的明暗配色 15
@media (prefers-color-scheme: dark) { body { background-color: #444; color: #e4e4e4; } a { color: #e39777; } img { filter: grayscale(30%); } }
TeXLive常用的一些包:
- 中文支持:ctex, fandol.
- 工具类:biblatex, latexdiff, latexmk, pdfcrop.
- Org-mode导出PDF时要调用的:wrapfig, capt-of.
- 扩展类:algorithm2e, enumitem, siunitx, diagbox.
- 字体类:helvetic, courier.
- 其他:ifsym, bbm, bbm-macros, pict2e, nomencl, zhnumber, relsize, ifoddpage, xstring, logreq, multirow, titlesec.
Hugo主题:
- dashdashzako/hugo-journal
- jrutheiser/hugo-lithium-theme
- natarajmb/charaka-hugo-theme
- zhe/hugo-theme-slim
- niklasbuschmann/contrast-hugo
Jekyll主题:
Unix系统下配置邮件自动转发:
将新邮件转发至指定邮箱而不保留副本
echo "xxx@gmail.com" > ~/.forward
将新邮件转发至指定邮箱并保留副本
echo "\\`whoami`, xxx@gmail.com" > ~/.forward
Makefile的清理模块可以这么写:
clean: @rm -rf *.{ps,log,aux,out,dvi,bbl,blg}
Debian开启BBR拥塞控制算法16:
- 需要4.9.0以上内核。
在
/etc/sysctl.conf
末尾添加以下内容:net.core.default_qdisc=fq net.ipv4.tcp_congestion_control=bbr
- 运行
sysctl -p
让配置生效。 - 运行
lsmod | grep bbr
检查BBR是否正确开启。
MKVToolNix是一个跨平台的处理MKV视频文件的工具集。
kodi播放视频时现实解码器等信息:
kodi-send --action=PlayerProcessInfo kodi-send --action=PlayerDebug
用calibre转换mobi为epub,可以指定 --output-profile tablet
来关闭对图片的resize,主要是针对一些漫画
ebook-convert input.mobi output.epub --output-profile tablet
命令行测试IPV6
curl -XGET https://v6.ident.me
查看端口绑定情况: netstat -ltpn
随机生成UUID
uuidgen
macOS下以读写模式挂载NTFS格式U盘
sudo umount /Volumes/UNTITLED sudo mount -t ntfs -o rw,auto,nobrowse /dev/disk3s1 ~/ntfs_volume
红米AC2100获取root权限:
- 从路由器管理界面登录并获取
<STOK>
:http://192.168.31.1/cgi-bin/luci/;stok=<STOK>/web/home#router
分别访问以下两个地址(其中
<STOK>
替换为上一步获取到的字符串),执行成功后会看到{"code": 0}
.http://192.168.31.1/cgi-bin/luci/;stok=<STOK>/api/misystem/set_config_iotdev?bssid=Xiaomi&user_id=longdike&ssid=-h%3B%20nvram%20set%20ssh_en%3D1%3B%20nvram%20commit%3B%20sed%20-i%20's%2Fchannel%3D.*%2Fchannel%3D%5C%22debug%5C%22%2Fg'%20%2Fetc%2Finit.d%2Fdropbear%3B%20%2Fetc%2Finit.d%2Fdropbear%20start%3B http://192.168.31.1/cgi-bin/luci/;stok=<STOK>/api/misystem/set_config_iotdev?bssid=Xiaomi&user_id=longdike&ssid=-h%3B%20echo%20-e%20'admin%5Cnadmin'%20%7C%20passwd%20root%3B
通过ssh登录路由器(密码为 =admin=)。
ssh root@192.168.31.1
将名为 gfwipset
这个ipset的流量转发到1080端口
ipset -N gfwipset iphash iptables -t nat -A PREROUTING -p tcp -m set --match-set gfwipset dst -j REDIRECT --to-port 1080 iptables -t nat -A OUTPUT -p tcp -m set --match-set gfwipset dst -j REDIRECT --to-port 1080
v2ray配置
{ "inbounds": [{ "port": 1234, "protocol": "vmess", "settings": { "clients": [ { "id": "AE49D4FA-6A0D-4751-9625-9E907F4D8BC8", "level": 1, "alterId": 64 } ] } },{ "port": 1235, "protocol": "shadowsocks", "settings": { "method": "aes-256-gcm", "password": "password", "network": "tcp,udp" } } ], "outbounds": [{ "protocol": "freedom", "settings": {} },{ "protocol": "blackhole", "settings": {}, "tag": "blocked" }], "routing": { "rules": [ { "type": "field", "ip": ["geoip:private"], "outboundTag": "blocked" } ] } }
通过每一行定义一个域名的 gfwlist.txt
文件更新 dnsmasq.conf
的脚本。
#!/bin/sh gfwlist= dnsmasqconf="/etc/dnsmasq.d/gfwlist" function show_help() { printf "This script is basically a set of commands. SYNOPSIS: ./servctl.sh [OPTION ...] OPTIONS: -h, --help: Show this help. -r: Restart services. -f FILE, --gfwlist FILE: Update ss rules using the give file.\n" } function update_gfwlist() { echo "" > $dnsmasqconf sort -u "$1" | while read line; do if [[ "$line" != "" ]]; then printf "server=/%s/127.0.0.1#1090\n" "$line" >> $dnsmasqconf printf "ipset=/%s/ss_rules_dst_forward\n\n" "$line" >> $dnsmasqconf fi done /etc/init.d/dnsmasq restart } function restart_services() { /etc/init.d/dnsmasq restart /etc/init.d/shadowsocks-libev restart /etc/init.d/firewall restart } while getopts "h?rf:" opt; do case "$opt" in h|\?) show_help exit 0 ;; r) restart_services echo "[INFO] Services restarted." ;; f) gfwlist=$OPTARG if [[ -f "$gfwlist" ]]; then update_gfwlist "$gfwlist" echo "[INFO] \"$dnsmasqconf\" has been updated with \"$gfwlist\"" else echo "[ERROR] File not found: $gfwlist" exit 1 fi ;; esac done
OpenWRT上的Shadowsocks配置,配置文件: /etc/config/shadowsocks-libev
:
config ss_redir 'ss_rd' option disabled '0' option server 'sss0' option local_address '0.0.0.0' option local_port '1100' option mode 'tcp_and_udp' option timeout '60' option fast_open '1' option reuse_port '1' option verbose '0' config ss_rules 'ss_rules' option disabled '0' option redir_tcp 'ss_rd' option redir_udp 'ss_rd' config ss_tunnel option disabled '0' option server 'sss0' option local_address '0.0.0.0' option local_port '1090' option tunnel_address '8.8.8.8:53' option mode 'tcp_and_udp' config server 'sss0' option disabled '0' option server 'xxx.xxx.xxx.xxx' option server_port 'xxxx' option method 'aes-256-gcm' option password 'xxxxxxxx'
nftables可以用来替代iptables,好处是配置方便,且不用分别为IPv4跟IPv6维护两套规则。
- 使用
nft flush ruleset
来清空规则。 - 使用
nft -f nftables.conf
来载入规则。 - 默认规则文件位置为
/etc/nftables.conf
下面是一个简单的提供类似防火墙功能的规则:
#!/usr/sbin/nft -f flush ruleset define tcp_services = { 22, 80, 443, 1234, 2345 } define udp_services = { 1234, 2345 } table inet filter { chain input { type filter hook input priority 0; policy drop; iif lo accept; ct state established, related accept; ct state invalid drop; # accept ping ip protocol icmp icmp type echo-request ct state new accept; # accept incomming connections on these ports tcp dport $tcp_services accept; udp dport $udp_services accept; # to not break ipv6 ip6 nexthdr icmpv6 icmpv6 type { nd-neighbor-solicit, nd-router-advert, nd-neighbor-advert } accept } chain forward { type filter hook forward priority 0; # route your own packets policy drop; } chain output { type filter hook output priority 0; policy accept; } }
orgmode中彻底禁止某个代码片段的执行:
#begin_src shell :eval never-export echo "foo" #end_src
某些epub电子书用kindlegen转换为mobi格式后会出现乱码,来自kobo的电子书基本都会有这个问题,原因在于epub文档中的html文件没有指定编码,而kindlegen默认都会用utf-8编码,所以会出现乱码:
解压已去DRM的epub电子书
unzip ebook_raw.epub -d ebook_unzipped/
在xhtml文件起始位置指定编码信息(注意以下示例用的是macOS下的sed,GNU sed的命令可能有所差异)
for tfile in ebook_unzipped/OEBPS/Text/*.xhtml; do (echo '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html>' && cat $tfile) > $TMPDIR/ebook_tmp && \mv $TMPDIR/ebook_tmp $tfile; done
重新封装为epub文件
cd ebook_unzipped/ && zip -rX ../ebook_new.epub mimetype META-INF/ OEBPS/ -x \*.DS_Store && cd -
用kindlegen将epub转换为mobi格式
kindlegen -dont_append_source ebook_new.epub
Kindle Paperwhite内置字体名:
@font-face { /* 中文简体宋 */ font-family: "zwjts"; src: local("Song S"); } @font-face { /* 中文楷体 */ font-family: "zwkt"; src: local("MKai PRC"); } @font-face { /* 中文简体黑 */ font-family: "zwjth"; src: local("MYing Hei S"); } @font-face { /* 中文繁体黑 */ font-family: "zwfth"; src: local("MYing Hei T"); } @font-face { /* 中文繁体宋 */ font-family: "zwfts"; src: local("Song T"); }
通常可以如下设置字体:
body { font-family: "Song T", Song,"宋体"; } h1,h2,h3,h4,h5,h6 { font-family: "MYing Hei T", Hei, "黑体"; }
isync遇到证书问题可以用手动下载证书来解决
wget https://gist.githubusercontent.com/petRUShka/af96ae25ce8280729b9ea049b929f31d/raw/a79471ce8aee3f6d04049039adf870a53a524f7f/get_certs.sh sh get_certs.sh imap.xxx.com 993 ~/.cert/
如果需要在服务器上转发邮件到指定邮箱,并在原邮箱中保留一份,可以写入文件 ~/.forward
:
localusername, forwardto@gmail.com
实用lookbusy来制造系统占用,并置于后台运行程序
nohup /usr/local/bin/lookbusy -c 20 -m 64MB >/dev/null 2>&1 & # show jobs jobs # > [1]+ Running ... # kill jobs kill %1 # put a job foreground fg 1
GarlicOS默认无法显示中文,可以通过替换 CFW/Skin/font.ttf
来实现中文显示,推荐字体:寒蝉高黑体。
GarlicOS/OnionOS (链接)的ROM文件仅支持一级目录,超过一级目录就不解析了,而且zip压缩也算一级目录,所以汉化版的ROM文件放到一个文件夹下就不会被解析,要么放弃zip压缩,要么把zip都放到一级目录下,因为想尽量节省存储空间,所以我选择了后一个办法,尽管汉化、原版什么都放到了同一级目录,但是为了让ROM目录尽量有条理,最后我选择了在文件命名上做一些变更,在中文汉化版ROM前加上 ·[CN]
这个前缀,起始的 ·
字符的ASCII值比各种常见字符包括英文字母都要大,所以可以保证排序上处于最后。
# get into the directory full of Chinese ROMs cd cn_roms # add a specific prefix to all the ROMs for xx in *.zip; do mv "$xx" "·[CN]$xx"; done # list all Chinese translated ROMs ls "·[CN]"*.zip
用ghostscript压缩pdf
gs -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile="output.pdf" input.pdf
雷鸟电视刷机及开启adb的方法
- 历史版本固件下载:
https://www.znds.com/tv-1229547-1-1.html 提取码o2j6
; 因为我的电视是雷鸟鹏50S365C,所以下载的固件是V8-A982T01-LF1V051.zip (注意更新版本的固件可能会导致adb无法安装第三方软件) - 把对应版本的固件zip包(不用解压)直接放到U盘(FAT32格式,插入电视上的USB2.0口,即白色的口)
- 依次进入电视的
设置->关于本机->系统升级->本地升级
, 之后电视会自动搜寻并校验固件安装包,等待几分钟安装完成即可。 - 开启adb: 依次进入电视的
设置->关于本机->本机信息
, 在本机信息界面依次按遥控器上、下、左、右
即可。 关闭系统自动更新。
# 关闭自动更新 adb shell pm uninstall -k --user 0 com.snm.upgrade adb shell pm uninstall -k --user 0 com.tcl.versionUpdateApp # 注意 com.tcl.versionUpdateApp 禁用后,在设置里使用网络升级和本地升级了,只能用U盘强刷bin固件包(强刷固件包)来更新系统 # 如果需要恢复启用系统本身的网络升级(不推荐)和本地升级(推荐,即上述用zip包放入U盘的方式)功能,可以如此设置 adb shell cmd package install-existing com.snm.upgrade adb shell cmd package install-existing com.tcl.versionUpdateApp
利用bilingual_book_maker制作双语epub
~/.venv/bbook/bin/bbook_maker --book_name eng.epub --model google -p 127.0.0.1:7890
利用Cloudflare Workers部署V2ray代理,可以参考教程 https://blog.dongstop.link/edgetunnel
联通光猫获取超级用户权限
- 取得光猫MAC地址:
arp 102.168.1.1
- 启用telnet,输入网址(最后的key后接获取得到的MAC地址,注意大小写):
http://192.168.1.1/telnet?enable=1&key=<956E784E8880>
登录telnet获取超级用户密码
telnet 192.168.1.1 # 用户名: admin 密码: Fh@<MAC地址后6位,全大写> load_cli factory show admin_pwd # 字段admin_pwd=后面的就是超级密码
- 登录光猫: 浏览器打开
http://192.168.1.1/cu.html
, 用户名: CUAdmin 密码即为上一步获取得到的密码
联通光猫关闭IPv6入站防火墙,这里采用的是光猫拨号+路由一体的方式
- telnet登录光猫
查看哪个chain影响到了IPv6流量入站,一般来说是以FIREWALL为关键词就能找到。
ip6tables -L --line-number
【选择1】往找到的这个chain头部添加一条规则放开部分流量,这里假设找到的chain是FORWARD_FIREWALL。
ip6tables -I FORWARD_FIREWALL -p tcp -m multiport --dport 80,443 -j ACCEPT
【选择2】根据打印出来的编号删除那条防火墙规则就可以了,这里假设是编号4。
ip6tables -D FORWARD_FIREWALL 4
为LibreELEC添加防火墙规则,固化的规则放置在 /config/.config/iptables/
目录下,里面还有个README文件可以看一下。注意防火墙规则每次修改完毕后别急着固化到文件里,在写入到文件前一旦发现异常都可以通过重启设备来让恢复,所以务必确认无误(主要是ssh能否顺利登录)后再固化到文件中。
IPv4规则,确认无误后这样来固化到文件:
iptables-save > /storage/.config/iptables/rules.v4
iptables -F; iptables -X; iptables -Z iptables -P OUTPUT ACCEPT iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT iptables -A INPUT -i lo -j ACCEPT iptables -A INPUT -s 192.168.0.0/16 -j ACCEPT # 允许局域网内连接 iptables -A INPUT -p tcp --dport 233 -j ACCEPT # 允许233端口入站 iptables -P INPUT DROP iptables -P FORWARD DROP
IPv6规则,确认无误后这样来固化到文件:
ip6tables-save > /storage/.config/iptables/rules.v6
ip6tables -F; ip6tables -X; ip6tables -Z ip6tables -P OUTPUT ACCEPT ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT ip6tables -A INPUT -p ipv6-icmp -j ACCEPT # 这是关键的,不然IPv6无法连接 ip6tables -A INPUT -i lo -j ACCEPT ip6tables -A INPUT -p tcp --dport 80 -j ACCEPT # 允许80端口入站 ip6tables -A INPUT -p tcp --dport 443 -j ACCEPT # 允许443端口入站 ip6tables -P INPUT DROP ip6tables -P FORWARD DROP
用aria2做种。
- 在数据目录下创建一个存放种子文件的文件夹
torrents/
写一个脚本
reseed.sh
DIRNAME=$(dirname $0) ls "${DIRNAME}"/*.torrent | aria2c \ --listen-port=10012 \ --enable-dht=false \ --enable-dht6=false \ --enable-peer-exchange=false \ --peer-id-prefix=-TR2920- \ --user-agent=Transmission/2.92 \ --peer-agent=Transmission/2.92 \ --bt-seed-unverified=true \ --bt-detach-seed-only=true \ --bt-max-open-files=10 \ --bt-max-peers=10 \ --max-overall-upload-limit=10M \ --seed-ratio=100 \ -d "${DIRNAME}"/../ \ -i -
后台执行: =
# 启动 nohup sh reseed.sh &> /dev/null & # 停止 pkill -f reseed.sh
Aria2的配置:
# Basic settings log-level=error summary-interval=0 quiet=true dir=/path/to/downloads/ # Pre-allocation (change it for legacy FS or on SSD) file-allocation=falloc # Basic download settings continue=true max-concurrent-downloads=20 max-connection-per-server=10 disable-ipv6=false async-dns=false # Session manager input-file=/path/to/aria2.session save-session=/path/to/aria2.session save-session-interval=60 force-save=true # RPC enable-rpc=true rpc-listen-port=6800 rpc-allow-origin-all=true rpc-listen-all=true rpc-secret=xxxpswd # BT/PT listen-port=10086 dht-listen-port=10086 enable-dht=true enable-dht6=true dht-file-path=/path/to/dht.dat dht-file-path6=/path/to/dht6.dat bt-seed-unverified=true bt-detach-seed-only=true bt-save-metadata=true bt-load-saved-metadata=true user-agent=Transmission/2.77 peer-agent=Transmission/2.77 peer-id-prefix=-TR2770- bt-tracker=http://1337.abcvg.info:80/announce,http://aboutbeautifulgallopinghorsesinthegreenpasture.online:80/announce,http://bt.okmp3.ru:2710/announce,http://bvarf.tracker.sh:2086/announce,http://ipv6.rer.lol:6969/announce,http://nyaa.tracker.wf:7777/announce,http://open.acgnxtracker.com:80/announce,http://share.camoe.cn:8080/announce,http://t.acg.rip:6699/announce,http://t.nyaatracker.com:80/announce,http://tinfoil.space:6969/announce,http://tk.greedland.net:80/announce,http://torrentsmd.com:8080/announce,http://tracker.electro-torrent.pl:80/announce,http://tracker.files.fm:6969/announce,http://tracker.gbitt.info:80/announce,http://tracker.ipv6tracker.org:80/announce,http://tracker.ipv6tracker.ru:80/announce,http://tracker.renfei.net:8080/announce,http://tracker.tfile.co:80/announce,http://www.all4nothin.net:80/announce.php,http://www.wareztorrent.com:80/announce,https://t1.hloli.org:443/announce,https://tr.burnabyhighstar.com:443/announce,https://tracker.gbitt.info:443/announce,https://tracker.kuroy.me:443/announce,https://tracker.loligirl.cn:443/announce,https://tracker.renfei.net:443/announce,https://tracker.tamersunion.org:443/announce,https://tracker.yemekyedim.com:443/announce,https://tracker1.520.jp:443/announce,https://trackers.mlsub.net:443/announce,https://www.peckservers.com:9443/announce,udp://aarsen.me:6969/announce,udp://amigacity.xyz:6969/announce,udp://bt1.archive.org:6969/announce,udp://ec2-18-191-163-220.us-east-2.compute.amazonaws.com:6969/announce,udp://epider.me:6969/announce,udp://evan.im:6969/announce,udp://exodus.desync.com:6969/announce,udp://ipv6.fuuuuuck.com:6969/announce,udp://martin-gebhardt.eu:25/announce,udp://moonburrow.club:6969/announce,udp://ns1.monolithindustries.com:6969/announce,udp://odd-hd.fr:6969/announce,udp://oh.fuuuuuck.com:6969/announce,udp://open.demonii.com:1337/announce,udp://open.demonoid.ch:6969/announce,udp://open.dstud.io:6969/announce,udp://open.stealth.si:80/announce,udp://open.tracker.ink:6969/announce,udp://opentor.org:2710/announce,udp://opentracker.io:6969/announce,udp://p4p.arenabg.com:1337/announce,udp://retracker.lanta.me:2710/announce,udp://retracker01-msk-virt.corbina.net:80/announce,udp://thetracker.org:80/announce,udp://tracker-udp.gbitt.info:80/announce,udp://tracker.0x7c0.com:6969/announce,udp://tracker.bittor.pw:1337/announce,udp://tracker.dler.com:6969/announce,udp://tracker.doko.moe:6969/announce,udp://tracker.fnix.net:6969/announce,udp://tracker.jamesthebard.net:6969/announce,udp://tracker.moeking.me:6969/announce,udp://tracker.opentrackr.org:1337/announce,udp://tracker.picotorrent.one:6969/announce,udp://tracker.qu.ax:6969/announce,udp://tracker.skyts.net:6969/announce,udp://tracker.srv00.com:6969/announce,udp://tracker.t-rb.org:6969/announce,udp://tracker.tiny-vps.com:6969/announce,udp://tracker.torrent.eu.org:451/announce,udp://tracker.tryhackx.org:6969/announce,udp://tracker2.dler.com:80/announce,udp://tracker2.dler.org:80/announce,udp://ttk2.nbaonlineservice.com:6969/announce,udp://wepzone.net:6969/announce,udp://www.torrent.eu.org:451/announce,wss://tracker.openwebtorrent.com:443/announce
用mktorrent制作种子用于发布。
mktorrent -v -p -l 20 -a <ANNOUNCE_URL> DIR_NAME/
Footnotes:
A channel variation-aware algorithm for enhanced video streaming quality
italic和slanted都表示斜体,但其实它们是不太一样的,italic可以看作是一种新的字型了(直观上更“花哨”),而slanted只是把原来的字型倾斜过来而已。
Schäfer, Patrick, and Ulf Leser. "Multivariate Time Series Classification with WEASEL+ MUSE." arXiv preprint arXiv:1711.11343 (2017).
Karim, Fazle, et al. "Multivariate LSTM-FCNs for Time Series Classification." arXiv preprint arXiv:1801.04503 (2018).
Groups, Rings, Fields and Ideals: http://d.pr/TcOUfF
一般我们用 \(P(x)\) 表示离散变量上的概率分布而用 \(p(x)\) 表示连续变量上的概率分布
If you want to mention the data that a likelihood function is associated with, you may say "the likelihood of the parameters given the data".