Scratch

Amazing physics going on…

[2016-06-02 Thu 11:48]


看到StackOverflow上有个人说他用Emacs用了32年才知道有这么个好用的功能: follow-mode

[2016-05-30 Mon 14:07]


可以在org文件头部来指定加载的css。

#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="style1.css" />
#+HTML_HEAD_EXTRA: <link rel="alternate stylesheet" type="text/css" href="style2.css" />

[2016-05-30 Mon 14:24]


^M 可以这样输入:按住Ctrl然后再依次按v和m

[2016-05-30 Mon 15:50]


查看本机IP详情

curl 4.ifcfg.me/all

[2016-05-30 Mon 19:01]


Vimeo也支持自适应码率了: Adaptive streaming and 4K: coming soon for your videos

[2016-05-30 Mon 19:13]


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.

[2016-05-30 Mon 19:27]


加入Mathjax支持。

<script type="text/javascript"
  src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>

[2016-05-30 Mon 21:07]


进入到Docker容器中。

docker exec -it CONTAINER_NAME /bin/bash

[2016-05-30 Mon 21:09]


Orgmode标记条目DONE时加上时间戳和笔记。

#+STARTUP: logdone lognotedone

[2016-05-30 Mon 21:10]


Emacs可以通过按键 C-q <TAB> 来插入一个tab.

[2016-05-30 Mon 21:11]


按文件大小列出文件:

du -ah | sort -rh | head -10

[2016-05-30 Mon 21:12]


记录下Vim启动时间:

vim --startuptime vim.log

[2016-05-30 Mon 21:13]


\(\LaTeX\)中可以用ctex包来输入中文:

\usepackage[UTF8]{ctex}

[2016-05-30 Mon 21:14]


\(\LaTeX\)中使用TTF字体,需要使用 xelatex 编译:

\usepackage{fontspec}
\setmainfont{EBGaramond.ttf}

[2016-05-30 Mon 21:18]


一个\(\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}

[2016-05-30 Mon 21:20]


\(\LaTeX\)中比较优雅地使用省略号

x_1 + x_2 + \cdots + x_n ~ (x_1, x_2, \ldots , x_n)

[2016-05-30 Mon 21:21]


\(\LaTeX\)中区分左右符号

\left| -x \right| = \left| +y \right|

[2016-05-30 Mon 21:22]


\(\LaTeX\)中用 \, (代表1/6 quad) 来控制字符间距

\sum_{p\rm\;\prime}f(p) = \int_{t>1}f(t)\,d\pi(t)

[2016-05-30 Mon 21:23]


\(\LaTeX\)中用 \! (代表-1/6 quad) 来控制字符间距

\int\!\!\!\int_D dx\,dy

[2016-05-30 Mon 21:31]


Git的代理设置:

git config --global http.proxy socks5://127.0.0.1:1080
git config --global https.proxy socks5://127.0.0.1:1080

[2016-05-30 Mon 21:37]


Beamer主题设置:

\usetheme{metropolis}

[2016-05-30 Mon 21:39]


Beamer首页的信息设置:

\title{A minimal example}
\subtitle{subtitle here}
\date{\today}
\author{Matt Wong}
\institute{Center for Modern Beamer Themes}

[2016-05-30 Mon 21:40]


Beamer的一个普通页面:

\begin{frame}
  \frametitle{Title Name}
  Hello everyone, ...
\end{frame}

[2016-05-30 Mon 21:41]


Beamer的标题页面:

\begin{frame}
  \titlepage{}
\end{frame}

[2016-05-30 Mon 21:41]


Beamer的大纲页面:

\begin{frame}
  \frametitle{Outline}
  \tableofcontents{}
\end{frame}

[2016-05-30 Mon 21:42]


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}

[2016-05-30 Mon 21:43]


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}

[2016-05-30 Mon 21:43]


Beamer中的图片,需要导入 graphics 这个包:

\centering
\includegraphics[width=\textwidth]{figures/example-image}

[2016-05-30 Mon 21:43]


Beamer中分栏:

\begin{columns}
  \column{.5\columnwidth} Column Number 1
  \column{.5\columnwidth} Column Number 2
\end{columns}

[2016-05-30 Mon 21:44]


\(\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}

[2016-05-30 Mon 21:45]


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}

[2016-05-30 Mon 21:46]


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}

[2016-05-30 Mon 21:47]


Beamer中的区块环境:

Content Type Corresponding Environment
Generic block
Theorems theorem
Lemmas lemma
Proofs proof
Corollaries corollary
Examples example
Highlighted Title alertblock

[2016-05-30 Mon 21:48]


Emacs中的多行缩进:用 C-u 4 C-x <TAB> 缩进四个空格; C-u -4 C-x <TAB> 取消缩进四个空格。

[2016-05-30 Mon 21:49]


orgmode中引用bib文件,第一个参数是不加后缀的bib文件(references),第二个是样式。

#+BIBLIOGRAPHY: references plain

[2016-05-30 Mon 21:50]


用orgmode来写Beamer,可以在任意标题上用 C-c C-b 进行选择展示环境。

[2016-05-30 Mon 21:53]


Emacs中用orgmode来管理配置文件。

(org-babel-load-file (expand-file-name name dotfiles-dir))

[2016-05-30 Mon 21:54]


orgmode中可以用 C-c / 来根据任务情况进行过滤。

[2016-05-30 Mon 21:56]


orgmode中用 S-M-<RET> 可以在当前位置新建TODO项目。

[2016-05-30 Mon 21:56]


orgmode可以这样自定义TODO的样式。

# -*- org-todo-keyword-faces: (("WANT" . "blue") ("DISPOSE". "orange") ("NEED" . "red") ("HAVE" . "green")); -*-
#+TODO: WANT(w!) DISPOSE(d!) NEED(n!) HAVE(h!)

[2016-05-30 Mon 21:57]


利用pandoc进行格式转换:

pandoc -f org -t docx foo.org -o foo.docx

[2016-05-30 Mon 21:58]


Emacs可以用 C-c C-x C-l 来预览公式,用 C-c C-c 来取消预览。

[2016-05-30 Mon 21:58]


Emacs中使用magit的流程是:

  1. magit-status: 进入状态预览;
  2. s: 添加未被追踪的文件;
  3. c: 提交更改;
  4. P: 推送到远程仓库。

[2016-05-30 Mon 22:00]


Emacs Lisp中的引用:

;; 产生列表 (1 2 3), 并且不会对列表元素进行求值
(quote (1 2 3))
;; 单引号是 (quote (...)) 形式的简写
'(1 2 3 )
;; 可以直接用 list 来构造
(list 1 (+ 1 1 ) 3)
;; 反引号生成
`(1 ,(+ 1 1) 3)

[2016-05-30 Mon 22:05]


Emacs Lisp表达式的执行:

[2016-05-30 Mon 22:06]


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

[2016-05-30 Mon 22:07]


Emacs的包仓库设置:

(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
                         ("melpa" . "http://melpa.org/packages/")
                         ("org" . "http://orgmode.org/elpa/")))

[2016-05-30 Mon 22:16]


我发现这个系统足够简单,但也足够完善,连tag系统都是现成的。

[2016-05-30 Mon 22:42]


85%的Facebook视频是被静了音观看的。

[2016-05-31 Tue 21:44]


Dracula这个主题也挺好看的嘛。

[2016-06-01 Wed 11:01]


Windows下创建类似软链接的文件:

mklink /d dest_dir src_dir

[2016-06-01 Wed 14:21]


\usepackage{siunitx} 可以用来写单位。

[2016-06-01 Wed 16:02]


字符串搜索及替换

  1. Call dired.
  2. Mark the files you want. You can mark by regex by % m
  3. Type Q to call dired-do-query-replace-regexp
  4. Type your find regex and replace string.
  5. For each occurrence, type y to replace, n to skip and C-g to abort.
  6. Type ! to replace all occurrences without asking, N to skip all the rest one.
  7. Type Y to replace all the occurrences.

[2016-06-01 Wed 21:50]


利用 compile 指令可以进行指定的make操作。

[2016-06-01 Wed 22:33]


使用 wgrep 包,在 grep 状态下按 C-c C-p 可以对搜索结果进行编辑。

[2016-06-01 Wed 22:33]


用以下几种方式可以实现在某些模式下屏蔽Evil:

(evil-set-initial-state 'dired-mode 'emacs)
;; or
(add-to-list 'evil-emacs-state-modes 'dired-mode)

[2016-06-02 Thu 16:28]


Chocolatey is awesome!

[2016-06-02 Thu 21:41]


eshell是个好东西,不过前提是要把补全给关掉,不然太烦了。

[2016-06-03 Fri 11:31]


终端查看天气

curl -4 wttr.in/Shanghai

[2016-06-06 Mon 20:21]


cygwin中建立crontab任务,需要管理员权限。

  1. 利用 crontab 命令来管理任务:

    crontab -e #edit
    crontab -l #list
    crontab -r #remove
    
  2. 建立一个周期性任务,下面的例子是每六小时执行一次 date 命令:

    * */6 * * * date
    
  3. 安装cron服务:

    cygrunsrv -I cron -p /usr/sbin/cron -a -n
    
  4. 启动cron服务:

    cygrunsrv -S cron
    
  5. 查看服务状态:

    cygrunsrv -Q cron
    

[2016-06-14 Tue 14:15]


Mac盗版软件下载:

  1. http://www.macappstore.net/
  2. http://xclient.info/
  3. http://www.macpeers.com/
  4. http://www.macbed.com/
  5. http://www.macupdate.com/
  6. https://www.appaddict.org/
  7. http://soft.macx.cn/
  8. http://www.macfans.org/
  9. http://www.pshezi.com/
  10. http://www.waitsun.com/
  11. http://www.isofts.org/
  12. http://www.waerfa.com/

[2016-06-15 Wed 23:09]


可以用TeXLive提供的宏包 ps2eps 把PS格式的图转换成EPS格式:

ps2eps foobar.ps

[2016-06-17 Fri 23:33]


OpenCV的常量名称会因为版本的不同而不同,可以通过 help(cv2) 来查看。

[2016-06-20 Mon 17:08]


键盘们

[2016-06-21 Tue 19:27]


在图论里面 nodevertex 两个词是没有任何区别的。

[2016-06-21 Tue 20:41]


DejaVu是一种支持Unicode字符的字体。

[2016-06-22 Wed 12:16]


手动编译emacs lisp包。

(byte-recompile-directory "~/.emacs.d/elpa/ranger-20160531.39" 0 t)

[2016-06-22 Wed 16:44]


用Visio作图后的格式转换。

pdftops foobar.pdf # convert pdf to ps
ps2eps foobar.ps   # convert ps to eps

[2016-07-02 Sat 12:44]


Gnome下面的dock插件:

[2016-07-04 Mon 11:46]


Foobar 2000的主题:

[2016-07-14 Thu 14:00]


Windows下的音乐播放器:

[2016-07-14 Thu 15:09]


Windows下编译zlib和libzip:

  1. 下载CMake并加入到PATH中。
  2. 加入类似 C:\Windows\Microsoft.NET\Framework64\v4.0.30319 这样的目录加入到PATH中,以便使 msbuild 可以使用。
  3. 下载zlib和libzip源码,以下将其各自目录分别唤作 %ZLIB_DIR%%LIBZIP_DIR%
  4. 编译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
    
  5. 编译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
    

[2016-07-15 Fri 16:14]


用systemd来控制shadowsocks,其中的 example 就是`/etc/shadowsocks/example.json`.

systemctl start shadowsocks@example

[2016-07-15 Fri 21:28]


聚合的即时聊天应用: Franz

[2016-07-16 Sat 16:27]


根据 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

[2016-07-16 Sat 20:32]


设置CMOS硬件时钟。

# set to localtime (default)
hwclock --systohc --localtime
# set to utc
hwclock --systohc --utc

[2016-07-17 Sun 11:45]


图形之间的距离

\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。

[2016-07-19 Tue 16:34]


Emacs中查看当前光标下的字符字体: C-u C-x =

[2016-07-24 Sun 21:59]


在启用 helm 的情况下用 bbdb-create 新建条目时候,最后要用 C-<Return> 代替 <Return> 以表示完成,不然就会死循环。

[2016-07-26 Tue 11:01]


利用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

[2016-07-26 Tue 11:03]


org-agenda界面下可以按 C-x C-w 导出到多种格式,只要在保存的时候指定文件后缀就行了,比如说html, ps, pdf。

[2016-07-26 Tue 11:32]


一个比较优雅的org导出HTML的样式文件:

#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://orgminimal.tizi.moe/bundle.min.css"/>
#+HTML_HEAD: <script src="http://orgminimal.tizi.moe/bundle.min.js" type="text/javascript" ></script>

[2016-07-26 Tue 15:06]


evdev 以及 synaptics 已经不再更新(maintenance mode),建议使用 libinput.

[2016-07-27 Wed 08:44]


有的会议不接受pdf文件中包含书签和链接,可以这样设置 hyperref 的参数。

\hypersetup{bookmarks=false,draft}

[2016-07-27 Wed 11:02]


Windows下重启资源管理器。

taskkill /f /im explorer.exe & start explorer.exe

[2016-07-28 Thu 11:37]


Rime的首字母模糊音设置,放到 luna_pinyin.custom.yaml 文件中:

"speller/algebra/@before 0": xform/^([b-df-hj-np-tv-z])$/$1_/

[2016-07-29 Fri 10:07]


Sci-Hub可用网址:

[2016-07-29 Fri 17:14]


Two methods for making figures for .tex files.

  1. 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.

  2. 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 on eps images because it will convert eps to pdf implicitly. However, the outputs have wrong bounding boxes. Thus, it is a better choice that we generate the pdf image files by hand using pdfcrop which is used as pdfcrop inputimg.pdf outputimg.pdf. For the compilation of main file, I use a Makefile or just latexmk for simplicity.

[2016-08-04 Thu 15:25]


Windows下利用 ffmpeg 捕获获取摄像头数据。

[2016-08-17 Wed 17:12]


在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))))

[2016-08-23 Tue 19:45]


在org中可以用 C-c C-x \ 来预览数学符号。

[2016-08-24 Wed 16:00]


Python简单的HTTP服务器。

# python 2
python -m SimpleHTTPServer 1070
# python 3
python -m http.server 1070

[2016-08-26 Fri 09:54]


在org中使用 org-info.js 其中的 path 属性用于指定加载的js文件,默认是 http://orgmode.org/worg/code/org-info-js/org-info.js

#+INFOJS_OPT: view:info path:./js/org-info.js

[2016-08-26 Fri 19:00]


关于 org-info 的css跟js都托管到某个地方:

http://tilde.works/~isaac/assets/org-info.css
http://tilde.works/~isaac/assets/org-info.js

[2016-08-27 Sat 11:32]


org在导出html的时候默认有个样式,有两种方式可以去除。

  1. 全局的设置: (setq org-html-head-include-default-style nil)
  2. 在org文件中设置: #+OPTIONS: html-style:nil

[2016-08-27 Sat 12:05]


让cygwin的软链接与Windows兼容。 其中 nativenativestrict 都需要管理员权限(不同的是前者在失败的时候会回滚到原来的链接),还有一个需要注意的是 nativestrict 会导致lockfile的功能出错,一般是用 native.emacs.d 的链接。参考链接

export CYGWIN="winsymlinks:lnk"
export CYGWIN="winsymlinks:native"
export CYGWIN="winsymlinks:nativestrict"

[2016-08-28 Sun 12:27]


基于 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"))))

[2016-08-29 Mon 15:40]


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

[2016-09-01 Thu 09:10]


Emacs中 solarized-theme 包的mode-line问题,默认的它的mode-line看上去字体会下沉,我还以为是字体设置的问题,搜了一下,原来是它默认的行为是给mode-line整行都加了下划线,而下划线是直接加在字符下方,就会使得字体看起来下沉了一下。有关这个问题repo上也有 相关讨论, 至于为什么要加这个下划线,作者给出的理由是本身solarized-theme设置的mode-line配色很浅,所以为了让它跟header-line有明显的额区隔所以加了一条线也就是下划线,弄清楚了原因,那么解决的方法有如下两种:

  1. (setq x-underline-at-descent-line t): 更改下划线的行为,让它出现在整个字块的下面。
  2. (setq solarized-high-contrast-mode-line t): 采用solarized-theme提供的高对比度的mode-line配色。

[2016-09-01 Thu 17:48]


隐藏 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)

[2016-09-01 Thu 21:53]


Emacs中 C-\ 竟然可以切换输入法。

[2016-09-03 Sat 21:57]


Windows下已经编译好的Python库 http://www.lfd.uci.edu/~gohlke/pythonlibs/

[2016-09-05 Mon 11:50]


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)]

[2016-09-05 Mon 11:50]


ffmpeg截取视频

ffmpeg -i yellowstone.mp4 -ss 00:00:07.5 -to 00:04:05  -c copy yellowstone_cut.mp4

[2016-09-05 Mon 11:51]


Linux下查看占用磁盘空间

du -ah --max-depth=1 <PATH>

[2016-09-05 Mon 11:51]


Deep Learning Tutorials

[2016-09-05 Mon 11:53]


在org文件头部执行lisp代码

# -*- org-todo-keyword-faces: (("WANT" . "yellow") ("DISPOSE" . "gray") ("NEED" . "red") ("HAVE" . "green")); -*-

[2016-09-05 Mon 12:00]


Emacs中的复制粘贴

[2016-09-05 Mon 12:01]


Windows的Chrome打开主页的快捷键是 Alt+Home

[2016-09-06 Tue 16:23]


Google高级搜索: https://www.google.com/advanced_search

[2016-09-06 Tue 16:25]


可以用下面的方法隐藏邮箱:

data:text/plain;chartset=UTF-8;base64,aW1qaWF4aUBnbWFpbC5jb20K

[2016-09-07 Wed 00:02]


Emacs配置中尽量不要用 require ,要利用autoloads特性:

(load "evil-surround-autoloads")

[2016-09-08 Thu 15:23]


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

[2016-09-08 Thu 15:32]


解决 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

[2016-09-09 Fri 00:40]


zsh主题:

[2016-09-10 Sat 17:46]


Highly是个不错的摘录工具,我的json导出地址是 https://www.highly.co/user/caasi/export.json

[2016-09-12 Mon 13:49]


Twitter都要被收购了,瞬间感觉Path好顽强。https://path.com/profile/3Ik6Rtv

[2016-09-13 Tue 22:11]


.gnupg 的权限:

chmod 700 ~/.gnupg
chmod 600 ~/.gnupg/*

[2016-09-14 Wed 10:37]


利用ffmpeg切割视频,例如要截取视频的1分钟到2分钟之间的视频片段,注意 -ss 选项需要在 -i 选项之前:

ffmpeg -ss 60 -i input.mp4 -t 120 -acodec copy -vcodec copy output.mp4

[2016-09-15 Thu 00:47]


利用GPG加密文件。

# encrypt
tar zcvf - foldername | gpg -c > foldername.tar.gz.gpg
# decrypt
gpg -d foldername.tar.gz.gpg | tar zxvf

[2016-09-15 Thu 10:23]


利用 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

[2016-09-16 Fri 20:37]


香水:

[2016-09-17 Sat 20:32]


Windows批处理的小技巧,可以直接把文件拖放到bat文件上作为输入参数,其中 %~dp1 表示路径, %~nx1 表示文件名。

@echo off
call foo.py %~dp1 %~nx1
pause

[2016-09-18 Sun 16:12]


一段用来裁剪pdf图片的批处理代码,只要把要裁剪的pdf文件拖放到这个bat文件上就行了,生成的图片是适应了bounding box,直接插入论文就可以了。

@echo off
pdfcrop %~nx1 tmp.pdf
del %~nx1
ren tmp.pdf %~nx1
echo Done!
pause

[2016-09-18 Sun 16:19]


TeXLive包管理。

# set mirror
tlmgr option repository http://mirrors.ustc.edu.cn/CTAN/systems/texlive/tlnet
# update all packages
tlmgr update --self --all

[2016-09-19 Mon 00:14]


\(\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}

[2016-09-19 Mon 00:01]


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.

[2016-09-19 Mon 15:44]


注意texlive安装路径中不要有空格,不然会有很多奇怪的问题。

[2016-09-19 Mon 16:21]


用pandoc将包含中文的org文件转换为pdf文件。

pandoc --latex-engine=xelatex -V mainfont=SimSun input.org -o output.pdf

[2016-09-20 Tue 15:23]


使用国内的PYPI源:

pip install matplot -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

[2016-09-20 Tue 15:50]


在脚本中快速调用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)"

[2016-09-20 Tue 20:26]


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)

[2016-09-21 Wed 10:50]


添加网页背景音乐:

<script>
window.onload = function() {
  var snd = new Audio("hb.ogg");
  snd.loop = true;
  snd.autoplay = true;
}
</script>

[2016-09-21 Wed 14:15]


Windows下小巧的抓包工具RawCap

# 查看帮助信息
RawCap.exe --help
# 抓取本地回路的包
RawCap.exe 127.0.0.1 localhost_cap1.pcap
# 抓取某个网卡的包
RawCap.exe 3 ether1.pcap

[2016-09-22 Thu 11:56]


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

[2016-09-22 Thu 22:33]


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

[2016-09-22 Thu 23:57]


使用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)

[2016-09-25 Sun 12:30]


Bash下输入多行文本: 用 cat << EOF 就行了,最后要结束的时候输入 EOF 就行了。所以可以这样来写邮件正文

mutt -s "Subject here." whowhowho@gmail.com < cat <<EOF

[2016-09-26 Mon 13:19]


Vim在可视模式的几个技巧:

[2016-09-28 Wed 10:29]


ffmpeg参数:

-r rate (20fps)
-s size (480x320)
-b bitrate (500kbps)

[2016-09-28 Wed 18:49]


下载Youtube视频,注意Youtube提供多种格式的视频,除了普通的流播视频格式,它全线支持MPEG-DASH,而且高码率的流只有DASH协议,它的音视频是分离的,所以下载下来后需要手动合并,可以用ffmpeg来合并: ffmpeg -i video.mp4 -i audio.m4a -c copy output.mp4

  1. Savedeo: 网站可以输出所有格式,提供复制链接。
  2. Youtube-dl: 功能强大,基于Python的单文件。
  3. You-Get: 同样也是基于Python的,可以下载很多网站的视频。
  4. 硕鼠Youtube专用下载器: Windows下的图形界面,操作简单。

[2016-09-28 Wed 23:28]


利用 tcpdump 抓包

# run for 15 seconds
tcpdump -i eth0 -G 15 -W 1 -w output.pcap

[2016-09-29 Thu 11:06]


利用 darkstat 来进行流量统计:

darkstat -i eth0 -b 127.0.0.1 -p 1234

[2016-09-29 Thu 11:07]


直接在终端上传文件到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

[2016-09-29 Thu 11:52]


百度云盘上传下载脚本: 主页: https://github.com/houtianze/bypy

# authorize first
bypy
# upload
bypy upload somefile.txt
# download
bypy downfile somefile.txt

[2016-09-29 Thu 12:11]


rsync的使用

rsync -r user@192.168.10.212:/home/user/somefolder/ localfolder

[2016-09-30 Fri 10:31]


Windows下磁盘检查和清理工具

[2016-10-08 Sat 12:07]


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/

[2016-10-09 Sun 22:59]


用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

[2016-10-10 Mon 11:28]


快速提交到Github:

#!/bin/sh
git add .
if [ $# -eq 1 ]; then
    git commit -am "$1"
else
    git commit -am "update"
fi
git push

[2016-10-10 Mon 12:10]


泛用型打包工具:

[2016-10-10 Mon 16:39]


Emacs中处理文本中的回车符 (carriage return):

; display ^M
(setq inhibit-eol-conversion t)
  1. M-%: esc % on Mac X11 Emacs
  2. C-q C-m RET: specifies ^M to replace
  3. C-q C-j RET: specifies a line return as the replacement
  4. !: runs the replace on the entire file

[2016-10-11 Tue 14:36]


Atom换用国内源: 添加文件 C:\Users\USERNAME\.atom\.apmrc:

registry=https://registry.npm.taobao.org/
strict-ssl=false

[2016-10-13 Thu 14:20]


Emacs下配置hunspell:

[2016-10-17 Mon 14:34]


zsh_stats 可以显示常用命令的统计信息。

[2016-10-17 Mon 23:10]


zsh配置文件加载顺序,所有这些文件的位置是由环境变量 $ZDOTDIR 控制的,默认是 $HOME:

  1. .zshenv: all invocations
  2. .zprofile: when login
  3. .zshrc: when interactive
  4. .zlogin: when login
  5. .zlogout: when logout

[2016-10-17 Mon 23:28]


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)文件。

[2016-10-20 Thu 11:58]


建立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

[2016-10-24 Mon 11:55]


Living in China’s Expanding Deserts - The New York Times

[2016-10-24 Mon 23:53]


Text-based web browsers:

[2016-10-25 Tue 15:26]


Wireshark报错的解决方案:

[2016-10-27 Thu 21:30]


matplotlib支持的颜色

import matplotlib
print(matplotlib.colors.cnames)

[2016-11-01 Tue 13:12]


利用matplotlib保存pdf格式时控制bounding box:

# 控制四周的边界
plt.tight_layout(rect = [0, 0, 0.4, 1])
# 设置tight参数
plt.savefig("test.pdf", bbox_inches='tight', pad_inches=0)

[2016-11-01 Tue 14:26]


一行Perl代码实现dos2unix的功能:

perl -pi -e 's/\r\n/\n/g' in.txt

[2016-11-03 Thu 13:31]


使用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

[2016-11-06 Sun 22:34]


网页顶端的彩条,图片文件在: http://imgur.com/a/DyAPD

#banner {
  background-image: url('border.png');
  background-repeat: repeat-x;
  background-size: 40px 3px;
  width:100%;
  height:30px;
}

[2016-11-14 Mon 16:54]


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()

[2016-11-15 Tue 11:39]


org做表格的一个例子

|---------+---------------+------------------|
| airmass | zenith_seeing | delivered_seeing |
|---------+---------------+------------------|
|     1.3 |           1.1 |        1.2875340 |
|     1.1 |           1.2 |        1.4045825 |
|     1.3 |           1.9 |        2.2239223 |
|---------+---------------+------------------|
#+TBLFM: $3=$2*($1**0.6)

[2016-11-15 Tue 14:46]


org里面调用calc来进行泰勒展开

#+BEGIN_SRC calc
taylor(sin(x),x,6)
#+END_SRC

[2016-11-15 Tue 14:47]


org可以直接在行内运行代码插入结果

The scaling for 1.3 airmasses is src_R{format(1.3**(3.0/5.0),digits=3)}
The scaling for 1.3 airmasses is src_calc{round(1.3**(3.0/5.0),4)}
The scaling for 1.3 airmasses is src_python{return "%4.1f" % (1.3**(3.0/5.0))}

[2016-11-15 Tue 14:52]


直接在org里面通过R操作表格

#+tblname: delsee
| 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 |
#+TBLFM: $3=$2*($1**0.6)
#+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

[2016-11-15 Tue 14:59]


通过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

[2016-11-15 Tue 15:02]


从org导出到中文pdf

#+LaTeX_HEADER: \usepackage{ctex}
#+LaTeX_HEADER: \ctexset{today=old}

[2016-11-17 Thu 14:17]


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))))

[2016-11-17 Thu 16:01]


Emacs方便的字数统计: M-=

[2016-11-19 Sat 14:48]


isync本地子目录的问题

[2016-11-21 Mon 11:44]


solarized-theme 默认的亮色modeline是有个下划线的,作者说是为了提高区分度(所以这个下划线在高对比度下是没有的),但是关键在于下划线这个东西系统默认是在字体的中下方,也就是会挡住下沉的部分,所以会影响视觉效果,当然可以通过选项来调整下划线的行为,但是这样做是具有全局破坏性的,所以下面这行代码就是让这个下划线不管是在高对比度还是低对比度的modeline中都不要使用。

(s-mode-line-underline (if solarized-high-contrast-mode-line nil nil))

[2016-11-21 Mon 15:43]


使用 powerline 隐藏minor mode列表

[2016-11-21 Mon 15:49]


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

[2016-11-22 Tue 14:42]


如果Visio导出为pdf的bounding box总是不对,在导出时候的选项中把“辅助功能文档结构标记”取消勾选就行了。

[2016-11-24 Thu 15:31]


美国洛杉矶一年十刀套餐(768m内存20g硬盘2t流量): https://hostus.us/

[2016-11-28 Mon 13:44]


RSS全文输出

[2016-11-28 Mon 15:43]


exiftool读取图片的EXIF信息: http://www.sno.phy.queensu.ca/~phil/exiftool/

[2016-11-28 Mon 19:31]


org导出html时候的代码高亮

  1. 代码高亮是由 htmlize 包提供的功能
  2. 高亮模式由 org-html-htmlize-output-type 控制: inline-css, css, font
  3. 默认的配色是从UI(即emacs主题)中继承的,所以如果是batch模式的话就是没有颜色的了
  4. 可以通过以下的方式来让它调用外部的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'>\")

[2016-11-29 Tue 13:42]


ggplot2中调整图表的长宽比例

  1. plot + coord_fixed(ratio=10): 这种方法的缺点在于这里的比例是跟数据挂钩的。
  2. plot + theme(aspect.ratio=9/16): 这种方法好处在于跟数据无关。

[2016-11-29 Tue 16:56]


用一个org文件来管理所有博客文章

* 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...

[2016-12-08 Thu 11:18]


Ascii art

[2016-12-08 Thu 11:51]


自适应码率串流建议的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.

[2016-12-08 Thu 14:38]


org的每一个章节都可以单独设置属性,VISIBILITY属性包括: folded, children, content, all

:PROPERTIES:
:VISIBILITY: folded
:END:

[2016-12-13 Tue 22:43]


info-js的可选项

#+INFOJS_OPT: view:showall toc:nil ltoc:nil mouse:underline buttons:0 path:http://thomasf.github.io/solarized-css/org-info.min.js

[2016-12-15 Thu 14:51]


org导出html的几个css样式

  1. Solarized CSS

    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://thomasf.github.io/solarized-css/solarized-light.min.css" />
    
  2. orgcss

    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://gongzhitaao.org/orgcss/org.css" />
    
  3. Tufte CSS

    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="https://edwardtufte.github.io/tufte-css/tufte.css" />
    
  4. org-notes-style

    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://taopeng.me/org-notes-style/css/notes.css" />
    
  5. Rethink

    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="https://jessekelly881-rethink.surge.sh/rethink.css" />
    

[2016-12-16 Fri 14:34]


Use socks proxy in curl

curl -O https://pdfs.semanticscholar.org/2a26/efb0096d535bd4c27b1ec05fe8aaa7cb166c.pdf --socks5 127.0.0.1:1080

[2017-01-05 Thu 11:28]


Windows笔记本

[2017-01-09 Mon 14:46]


orgmode中指定字体

#+HTML_HEAD_EXTRA: <style>body{font-family:"Georgia","KaiTi";}</style>

[2017-01-11 Wed 13:19]


orgmode中 C-c C-o 打开链接。

[2017-01-11 Wed 16:14]


brew删除一个程序连同它的依赖。

brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))

[2017-01-19 Thu 13:17]


basictex 里面按照缺少的文件搜索包

tlmgr search --global --file algorithm.sty

[2017-01-19 Thu 14:02]


Mac软件签名

sudo codesign --force --deep --sign - /Applications/Folx.app/

[2017-01-21 Sat 21:15]


Homebrew下载的文件缓存目录: ~/Library/Caches/Homebrew

[2017-02-13 Mon 00:06]


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

[2017-02-13 Mon 14:56]


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)))

[2017-02-14 Tue 01:56]


MacOS重启、睡眠的快捷键

[2017-02-14 Tue 16:48]


递归删除当前目录下的 .DS_Store 文件:

find . -name '*.DS_Store' -type f -delete

[2017-02-15 Wed 18:36]


Android保持屏幕常亮的两种方法

  1. 写到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);
      }
    }
    
  2. 写到布局的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>
    

[2017-02-15 Wed 18:39]


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();
    }
}

[2017-02-15 Wed 18:44]


通过网络调试Andorid应用

./adb tcpip 5555
./adb connect 192.168.199.180

[2017-02-15 Wed 21:02]


Debian打包,在源码目录下操作:

dpkg-buildpackage -us -c

[2017-02-20 Mon 12:35]


Ubuntu安装管理deb包

# install package
dpkg -i xxx.deb
# remove package
dpkg -r xxx
# list installed packages
dpkg -l

[2017-02-20 Mon 12:37]


Emacs下根据当前时间来动态切换明暗主题

;; theme-changer
(use-package theme-changer
  :if window-system
  :config
  (change-theme 'solarized-light 'solarized-dark))

[2017-02-21 Tue 14:14]


Emacs中设置fringe的背景色

(set-face-attribute 'fringe nil :background "#030303")

[2017-02-21 Tue 14:37]


MacOS重建LaunchPad图标

defaults write com.apple.dock ResetLaunchPad -bool true;killall Dock

[2017-02-24 Fri 22:40]


orgmode导出模板

#+TITLE: Foo Bar
#+STARTUP: hidestars indent content align inlineimages
#+OPTIONS: toc:nil num:nil ^:{} html-style:nil html-scripts:nil
#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://jiaxi.sdf.org/css/org.css" />

[2017-02-25 Sat 16:17]


Linux修改Capslock键

# capslock as ctrl
setxkbmap -option ctrl:nocaps
# swap capslock and ctrl
setxkbmap -option ctrl:swapcaps

[2017-02-25 Sat 19:58]


Android中使用ndk-build来引入C/C++支持

[2017-02-26 Sun 00:17]


Android使用cmake来加入C/C++支持

[2017-02-26 Sun 13:15]


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)

[2017-03-02 Thu 14:49]


MacOS下配置 irony-mode

  1. 到LLVM网站上下载Clang Source Code,需要用到它的头文件。
  2. 对于 libclang.dylib, 我们使用的是Xcode的,路径应该在 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/
  3. 在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
    

[2017-03-03 Fri 13:09]


Org-mode中预览数学符号快捷键: C-c C-x C-l

[2017-03-03 Fri 23:49]


购买美区礼品卡

[2017-03-07 Tue 16:10]


使orgmode导出的html文件打印到pdf更美观: https://github.com/BafS/Gutenberg

#+HTML_HEAD_EXTRA: <link rel="stylesheet" href="https://unpkg.com/gutenberg-css" media="print">

[2017-03-10 Fri 14:57]


利用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

[2017-03-17 Fri 03:23]


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)'

[2017-03-21 Tue 15:35]


显示系统所有的环境变量

printenv

[2017-03-24 Fri 15:01]


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

[2017-03-26 Sun 11:34]


org导出的html不包含默认的样式:

(setq org-html-head-include-default-style nil)

[2017-03-27 Mon 17:12]


\(\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

[2017-03-30 Thu 10:33]


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.

[2017-04-01 Sat 10:52]


插图配色

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"

[2017-04-05 Wed 13:11]


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

[2017-04-08 Sat 21:09]


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

[2017-04-08 Sat 21:34]


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

[2017-04-09 Sun 13:58]


eps文件bounding box自动适应图像

ps2epsi <input.eps> <output.eps>

[2017-04-15 Sat 00:22]


Vim 8自带的插件管理目录结构

.vim
├── pack
│   └── plugins
│       ├── opt
│       └── start
│           ├── auto-pairs
│           ├── nerdcommenter
│           ├── vim-airline
│           ├── vim-rsi
│           └── vim-surround
└── vimrc

[2017-04-20 Thu 15:34]


方便的代码片段分享,放到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"

[2017-04-22 Sat 16:07]


Vim识别的gnuplot文件后缀是 .gpi

[2017-05-02 Tue 11:33]


orgmode导出pdf时去掉作者跟日期

#+OPTIONS: author:nil date:nil

[2017-05-02 Tue 20:37]


R语言在orgmode中的绘图设置

# 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

[2017-05-03 Wed 10:46]


Auctex通过 C-c C-o C-b 来折叠环境。

[2017-05-05 Fri 15:12]


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

[2017-05-17 Wed 10:28]


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])

[2017-05-17 Wed 23:31]


为什么样本方差(sample variance)的分母是\(n-1\)而不是\(n\):

[2017-05-18 Thu 13:54]


n 阶矩阵 A 相似于对角矩阵的充分必要条件是 A 有 n 个线性无关的特征向量。

[2017-05-18 Thu 16:03]


读Facebook发表于2017-04-20的一篇博客, 介绍了立方投影的以下三点好处:

  1. 没有几何变形(geometry distortion);
  2. 像素是均匀分布的;
  3. 投影更加简单,每一个面只会投影到跟它对应的表面上。

[2017-05-19 Fri 12:54]


学习了以下几个知识点:

  1. K-means,它的核心思想其实就是EM算法。它的缺点是对离群点敏感,对以下情况效果不好:各个类的规模相差很大、密度分布不均,形状不规则。
  2. 马氏距离、协方差矩阵,它的思想是考虑数据点的分布。
  3. PCA、相似矩阵、相似对角化、特征向量和特征值(相当于用某空间下的一组基来表示其上的点)
  4. 雅可比矩阵,海森矩阵,海森矩阵的正定半正定定义了函数的凹凸性。
  5. EM算法的推导,主要解决的问题是估计来自不同分布的数据的参数,同时也可以以此做聚类,核心是将含未知分布的极大似然估计,运用Jensen不等式求下界,然后调整参数,反复迭代。详细见 课件
  6. 由EM导出混合高斯模型。

[2017-05-19 Fri 12:54]


R语言设置包仓库

# get repository url
getOption("repos")
# set repository
options(repos="https://mirrors.tuna.tsinghua.edu.cn/CRAN")

[2017-05-21 Sun 17:19]


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]

[2017-05-25 Thu 18:11]


Vim里面强制保存

:w !sudo tee %”

[2017-06-17 Sat 16:56]


MoneyWiz导出的 moneywiz.csv 文件转换成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)
}
# 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 *

[2017-06-19 Mon 17:40]


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

[2017-06-20 Tue 15:24]


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
}

[2017-06-21 Wed 18:04]


orgmode写beamer

#+STARTUP:              hidestars indent showall beamer
#+TITLE:                MASH: A Rate Adaptation Algorithm for Multiview Video Streaming over HTTP
#+AUTHOR:               Jiaxi Gu
#+EMAIL:                imjiaxi@gmail.com
#+DATE:                 Jul 6, 2017
#+OPTIONS:              H:2 toc:nil
#+DESCRIPTION:          A paper from INFOCOM'17
#+KEYWORDS:             multimedia network dash
#+LaTeX_CLASS:          beamer
#+BEAMER_THEME:         default
#+BEAMER_COLOR_THEME:   beaver
#+LATEX_HEADER:         \usepackage{fancybox}
#+LATEX_HEADER:         \usepackage{graphics}
#+LATEX_HEADER:         \usepackage[UTF8]{ctex}
#+LATEX_HEADER:         \usepackage[backend=bibtex]{biblatex}
#+LATEX_HEADER:         \bibliography{references}

* 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

[2017-06-23 Fri 14:39]


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] \]

[2017-06-23 Fri 15:34]


利用 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}

[2017-06-26 Mon 13:52]


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)

[2017-07-02 Sun 14:47]


M-x list-faces-display 可以显示可用的样式。

[2017-07-04 Tue 11:41]


My crafted mode-line for Emacs JxaqaJb.png

(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))))
                    "-%-"))

[2017-07-04 Tue 15:52]


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\\}\\)%")

[2017-07-05 Wed 10:26]


libmobi是一个用来修改mobi文件meta信息的工具。

# show meta data
mobimeta some.mobi
# modify meta data
mobimeta -s title="sometile" -s author="someone" some.mobi

[2017-07-08 Sat 00:00]


查看压缩包内容并解压出单个文件夹

## list content
tar -tvf foo.tgz
# foo/
# foo/foo.txt
# bar/
## extract a specific folder
tar -xvf foo.tgz foo

[2017-07-08 Sat 21:02]


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})

[2017-07-10 Mon 15:05]


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)
        )
}

[2017-07-11 Tue 11:58]


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")

[2017-07-11 Tue 14:19]


使 subcaption 包与 IEEEtran 兼容 2

\makeatletter
\let\MYcaption\@makecaption
\makeatother

\usepackage[font=footnotesize]{subcaption}

\makeatletter
\let\@makecaption\MYcaption
\makeatother

[2017-07-11 Tue 21:59]


CTEX宏包对文档的汉化选项 预设有 chinese 和 plain 两种方案。

% 对“图”、“表”、“目录”、“参考文献”等均有汉化 [默认]
\usepackage[scheme=chinese]{ctex}
% 不调整默认字号和行距,不汉化标题名字,仅做中文支持。
\usepackage[scheme=plain]{ctex}

[2017-07-12 Wed 10:20]


IEEEtran 的环境下兼容 algorithm2e 宏包 3 IEEEtran的指南上说不要使用 algorithm 的float结构,因为模板只允许 figuretable 两种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}

[2017-07-12 Wed 11:48]


利用GPU加速的视频转码 相关链接: https://developer.nvidia.com/ffmpeg

ffmpeg -hwaccel cuvid -c:v h264_cuvid -i apple.mp4 -vcodec h264_nvenc apple_nv.mp4

[2017-07-21 Fri 17:34]


Ubuntu系统的回收站(Trash)地址: ~/.local/share/Trash/

[2017-07-23 Sun 11:25]


Sketch.app的缓存

sudo rm -rf /.DocumentRevisions-V100/

[2017-07-27 Thu 11:10]


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*}

[2017-08-04 Fri 16:21]


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*}

[2017-08-04 Fri 16:33]


\(\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$.

[2017-08-06 Sun 13:33]


Vim寄存器的使用

[2017-08-06 Sun 13:58]


Netflix使用的是固定为4秒的DASH视频片段长度 6

[2017-08-06 Sun 14:08]


RefTex的使用

[2017-08-08 Tue 17:46]


如果需要从bib文件中提取被引用的条目,可以在Emacs下使用 reftex-create-bibtex-file.

[2017-08-09 Wed 16:08]


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

[2017-08-21 Mon 16:03]


创建用gpg加密的org文件,创建文件名为 foo.org.gpg 的文件,添加本地变量:

# -*- epa-file-encrypt-to: "imjiaxi@gmail.com" -*-

[2017-08-22 Tue 17:52]


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

[2017-08-25 Fri 11:31]


控制Haskell编译后的可执行文件大小

  1. 加入 -dynamic 编译参数,如果是用stack的话,可以是: stack ghc foo.hs -- -dynamic
  2. 使用 strip 来去除二进制文件中用于调试的符号等。

[2017-08-26 Sat 14:57]


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

[2017-08-27 Sun 17:02]


使用某函数输出结果来进行compare并排序进行

immport Data.Ord (comparing)
lsort = sortBy (comparing length)
-- lsort ["abc", "a", "aa"]

[2017-08-28 Mon 11:22]


exa is a modern replacement for ls.

[2017-08-30 Wed 17:15]


显示IP地址

ifconfig | grep inet | grep -v inet6 | cut -d" " -f2 | tail -n1

[2017-09-07 Thu 10:55]


enca: Charset analyzer and converter.

[2017-09-27 Wed 11:34]


文本文件字符编码的检测与转换,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

[2017-09-27 Wed 11:41]


\(\LaTeX\) 控制页边距

\usepackage[top=.7in, bottom=.7in, left=1.25in, right=1.25in]{geometry}

[2017-09-27 Wed 20:25]


objective: 目标,强调个人或需求而决定的目标,书面用词。

[2017-10-17 Tue 22:06]


刪除誤上屏的錯詞

先把選字光標(用上、下鍵)移到要刪除的用戶詞組上,再按下 Shift+Delete 或 Control+Delete(蘋果鍵盤用 Shift+Fn+Delete)。 只能夠從用戶詞典中刪除詞組。用於碼表中原有的詞組時,只會取消其調頻效果。

[2017-10-18 Wed 15:17]


拉格朗日中值定理: 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} \]

[2017-10-19 Thu 14:02]


Singular Value Decomposition Tutorial

[2017-10-19 Thu 20:25]


什么叫做线性空间 xykTyDP.png

[2017-10-19 Thu 20:30]


用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

[2017-10-21 Sat 16:17]


时间戳解析

date -r 1508573115005
# Wed Oct 12 07:30:05 CST 49774

[2017-10-21 Sat 16:22]


Python3里的 execfile()

exec(open("./filename.py").read())

[2017-10-26 Thu 16:19]


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'

[2017-10-27 Fri 11:27]


Vim配置fzf进行模糊搜索

Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }

[2017-10-31 Tue 20:12]


设置默认音轨

# inspect file information
mp4box -info "movie.mp4"
# change default audio stream
mp4box "movie.mp4" -enable 3
mp4box "movie.mp4" -disable 2

[2017-11-01 Wed 10:03]


禁用iOS设备连接iTunes后同步时自动备份

defaults write com.apple.iTunes AutomaticDeviceBackupsDisabled -bool true

[2017-11-19 Sun 17:13]


Cabinet是Android下的一个简洁又轻量的文件管理器

[2017-11-20 Mon 14:29]


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.

[2017-11-29 Wed 11:55]


rsync指定端口

rsync -a -e 'ssh -p 2345' user@server.com:foo/bar/ local/foo/

[2017-11-29 Wed 21:54]


rsync通过IPV6连接

rsync -a user@[2001:db8:1234:5678:feed:face:dead:beef]:foo/bar/ local/foo/

[2017-11-29 Wed 21:55]


查找文件中的重复行

sort file.txt | uniq -d

[2017-11-29 Wed 22:40]


输出目录下所有媒体文件的播放总时长

find . -maxdepth 1 -iname '*.ts' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bc

[2017-12-03 Sun 11:57]


用Imagemagick来压缩图片

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
}

[2017-12-04 Mon 11:08]


把图片编码到org文件中

(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))))

[2017-12-05 Tue 10:42]


\(\LaTeX\) 中控制图片下面离文本的间隔

\setlength{\textfloatsep}{2pt}

[2017-12-09 Sat 16:47]


获取当前时间并格式化

date +%Y%m%d%H%M%S

[2017-12-11 Mon 14:22]


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"

[2017-12-13 Wed 16:48]


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"

[2017-12-15 Fri 11:13]


mutt发送html内容的邮件

mutt -e 'set content_type="text/html"' recipient@gmail.com -s "Foo Subject" < foo.html

[2017-12-15 Fri 11:34]


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

[2018-01-04 Thu 20:05]


输出文件名中包含某串字符的文件(递归并大小写不敏感)

function rf ()
{
    if hash rg 2> /dev/null; then
        rg -l --files --iglob "*$1*"
    else
        find . -iname "*$1*"
    fi
}

[2018-01-04 Thu 21:13]


Emacs Calc在orgmode中的使用

#+BEGIN_SRC calc :exports both
(300 + 120) * 2 %% Double prices
#+END_SRC

[2018-01-11 Thu 10:45]


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)))))))

[2018-01-11 Thu 14:01]


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.

[2018-01-11 Thu 21:19]


\(\LaTeX\)简历模板

[2018-01-16 Tue 12:09]


\(\LaTeX\)文本靠右对齐

\begin{flushright}
Jack\\
12/23/2018
\end{flushright}

[2018-01-23 Tue 14:38]


用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

[2018-01-24 Wed 14:28]


\(\LaTeX\)强制插入未引用的角注

\let\thefootnote\relax\footnotetext{\textit{\today}}

[2018-01-26 Fri 13:41]


\(\LaTeX\)在 \begin{document} 前加入以下代码可以用于去掉页码

\pagestyle{empty}

[2018-01-26 Fri 13:43]


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

[2018-01-28 Sun 11:03]


删除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>

[2018-02-04 Sun 21:27]


orgmode中的表格可以使用 org-table-export 导出到csv文件,可以添加章节属性来指定导出文件路径。

:PROPERTIES:
:TABLE_EXPORT_FILE: /tmp/books.csv
:TABLE_EXPORT_FORMAT: orgtbl-to-csv
:END:

[2018-02-09 Fri 11:05]


根据国际标准组织的规定,矩阵(matrix)用粗斜体(bold italic)书写,而张量(tensor)用斜体(slanted)无衬线字体书写. 8

ISO/IEC regulations for technical writing prescribe using bold italic for matrices (and slanted sans serif for tensors).

[2018-02-15 Thu 11:51]


Discuz的RSS地址是域名后面加 /forum.php?mod=rss

[2018-02-23 Fri 11:16]


一个常见的语法问题,下面两种说法都是可以的:

There is work [for you] to do.
There is work to be done [by you].

[2018-02-23 Fri 14:18]


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

[2018-02-23 Fri 16:16]


dim这个package用来隐藏mode-line中的minor mode名称简单有效

[2018-02-25 Sun 13:50]


CSS里面强制长的链接自动换行,而代码块里面的内容除外

body {
  word-wrap: break-word;
}
pre {
  word-wrap: normal;
}

[2018-03-10 Sat 20:38]


\(\pi\)的值可以由\(4 * arctan(1)\)计算得到。

[2018-03-11 Sun 11:20]


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.

[2018-03-12 Mon 09:43]


万象节锁(Gimbal Lock)的问题只会出现在动态坐标系(也就是坐标系随旋转物体而转动),描述如下:三轴旋转如果由欧拉角的表示的话,其次序是固定的,分别记作1,2,3三次,一旦第2次旋转为+/-90°,那么Gimbal Lock就会发生,这种情况下,第3次的旋转效果可以由第1次旋转所在维度达成,换句话说,第3次旋转并没有发生在新的维度上,所以说“失去了一个自由度”,也可以理解为这样的旋转实际只有两个轴起了作用而不是3个。

[2018-03-12 Mon 10:19]


Emacs文件本地变量(File-local variables)可以用头或尾两种方式设置(为了避免作用于本文件,每一行开头的字符故意重复输入了)。

--*- mode: mode-name-here; my-variable: value -*-

OR

LLocal Variables:
mmode: mode-name-heree
mmy-variable: value
EEnd:

[2018-03-13 Tue 10:25]


RFC3339规定的日期和时间格式如下(东八区2018年3月13日下午3点37分53秒,字母T用于分隔日期和时间):

2018-03-13T15:37:53+08:00

[2018-03-13 Tue 20:13]


\(\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)\)。

[2018-03-14 Wed 10:50]


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)))))

[2018-03-14 Wed 13:07]


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))))

[2018-03-15 Thu 10:46]


编程字体推荐

[2018-03-16 Fri 10:01]


MacOS自带的Grapher.app可以用来书写简单的公式,这样在做keynote的时候就可以不用MathType了。

[2018-03-16 Fri 11:07]


Orgmode的脚注有三种方式:

[2018-03-19 Mon 12:02]


Haskell里的符号不是胡乱选的鬼画符,是有联系的,看 $<$>:

($) :: (a -> b) -> a -> b
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<*>) :: Applicative f => f (a -> b) -> f a -> f b

[2018-03-20 Tue 11:37]


Haskell中的Functor需满足两大法则

-- Law 1
fmap id == id
-- Law 2
fmap (f . g) == fmap f . fmap g

[2018-03-20 Tue 15:12]


  monoid semigroup magma
binary operation yes yes yes
associativity yes yes no
identity yes no no

[2018-03-20 Tue 15:15]


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

[2018-03-20 Tue 16:37]


奇异值分解(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}\) 的特征值的平方根。

[2018-03-22 Thu 23:18]


表示未注册的商标, ® 表示注册商标。

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.

[2018-03-22 Thu 23:36]


有关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\)的最大特征值对应的特征根。

参考:

[2018-03-23 Fri 22:00]


有关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 \]

[2018-03-27 Tue 22:02]


豆瓣读书的记录可以通过官方的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

[2018-03-28 Wed 11:12]


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

[2018-03-28 Wed 16:15]


用\(\LaTeX\)生成独立的公式

\documentclass{standalone}
\begin{document}
$\displaystyle
e = mc^2
$
\end{document}

[2018-04-08 Sun 14:06]


从熵的角度来理解最大似然

似然函数:

\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*}

[2018-04-12 Thu 20:27]


Emacs中Flyspell可以通过在文末添加词列表来指定词典外的词拼写

% LocalWords: accelerometer phonation

[2018-05-11 Fri 11:36]


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"))))

[2018-05-14 Mon 11:02]


aspell 输出可用的词典

aspell dump dicts

[2018-05-15 Tue 16:39]


Out-of-Sample Extensions for LLE, Isomap, MDS, Eigenmaps, and Spectral Clustering: 这篇文章的作者是机器学习大牛Bengio,主要关注MDS,基于样本间距离的流形(manifold)降维方法,主要用于数据可视化。因为它是用已知的整个样本空间来做降维,所以对于out-of-sample的情况即新样本没有办法进行直接判断。这篇文章的方法是提出用已知数据得到的核矩阵来应用到新数据即out-of-sample的数据上来,以衡量新数据之间的距离,证明了可以这样做的合理性。并没有说直接可以对新数据降维,虽然说也可以这么做,但其实还是需要一些额外的运算的。

[2018-05-31 Thu 11:01]


多元时间序列的分类,主要分为两大类:一类是基于样本间相似性的;第二类是基于时间序列的特征的。目前来看第二类方法效果比第一类要好,主流的是两种方法,都是2018年发表的,它们相互之间也进行了性能的比较。

[2018-05-31 Thu 11:02]


特征选择方法主要有两种: \(\chi^2\) 检验、互信息

[2018-05-31 Thu 16:17]


Emacs的speedbar默认是会随着当前buffer改变其显示的目录的,但是可以通过 sr-speedbar 提供的 sr-speedbar-refresh-turn-off 来关掉自适应切换目录。

[2018-05-31 Thu 18:23]


用Python虚拟环境的时候可以用 --system-site-packages 来继承系统的python包。

python3 -m venv proj --system-site-packages

[2018-05-31 Thu 20:33]


Python输出当前操作系统平台

import platform
print(platform.system())
# "Linux" or "Darwin" or "Windows"

[2018-06-01 Fri 13:49]


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)

[2018-06-14 Thu 16:29]


快速查看某个命令行工具的使用方法

curl cheat.sh/tar

[2018-06-15 Fri 10:34]


从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)];
}

[2018-06-15 Fri 21:51]


关掉Mac下更改文件后缀名的警告。

# Disable the warning when changing a file extension
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false

[2018-06-18 Mon 09:38]


Matplotlib报错 no display name and no $DISPLAY environment variable

export MPLBACKEND="agg"
import matplotlib.pyplot as plt.
plt.switch_backend('agg')

[2018-06-20 Wed 11:44]


笔记: A Comprehensive Guide to Machine Learning

[2018-06-20 Wed 19:59]


.bashrc 中设置简洁的提示符

export PS1="\n\[\e[33m\]\u@\h\[\e[m\]:\w\n\[\e[1m\e[32m\]\\$\[\e[m\] "

[2018-06-22 Fri 22:56]


数的定义 (\(\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

[2018-06-26 Tue 10:39]


The definitions of Group, Ring, Field and Ideal 11

[2018-06-26 Tue 10:51]


信息论中熵(entropy)的概念:

[2018-06-26 Tue 19:40]


两个随机变量的互信息(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当且仅当它们是独立随机变量。

[2018-06-26 Tue 21:34]


给定正整数 \(n \in \mathbb{Z}^{+}\), 矩阵 \(\mathbf{A} \in \mathbb{R}^{n \times n}\) 与定义在其上的乘法和加法构成一个环。

[2018-06-27 Wed 16:06]


orgmode支持的语言: https://orgmode.org/worg/org-contrib/babel/languages.html

[2018-06-28 Thu 10:59]


latex中的 splitaligned 环境都可以用来对齐公式,但是一般 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*}

[2018-06-28 Thu 11:48]


谱定律(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} \]

[2018-06-28 Thu 15:23]


导出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))

[2018-06-28 Thu 23:02]


如果需要从外部(目录)执行Makefile,可以考虑 -C 参数来指定Makefile所在目录,这样可以避免目录引起的问题。

[2018-06-29 Fri 11:25]


markdown-mode处理表格可以用 C-c C-d 对齐。

[2018-06-29 Fri 21:43]


orgmode中条目的属性可以用 C-c C-x pC-c C-c d 来增删。

[2018-06-29 Fri 21:44]


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:

  1. \(null(\mathbf{A}) = range(\mathbf{A}^\top)^\perp\)
  2. \(null(\mathbf{A}) \oplus range(\mathbf{A}^\top) = \mathbb{R}^n\)
  3. 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}\)

[2018-06-30 Sat 11:22]


在 \(\LaTeX\) 中输入 arg min:

\begin{equation*}
w^{\ast} = \operatorname*{arg\,min}_{w}f(w)
\end{equation*}

[2018-07-01 Sun 17:08]


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

[2018-07-04 Wed 10:29]


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

[2018-07-12 Thu 13:43]


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

[2018-07-13 Fri 14:29]


\(\LaTeX\)中加入咖啡印。

\documentclass{article}
\usepackage{coffee4}

\begin{document}
\cofeCm{.2}{.4}{0}{.35\linewidth}{-.6\linewidth}

I love coffee.

\end{document}

[2018-07-13 Fri 16:53]


\(\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}

[2018-07-15 Sun 16:46]


单纯形(simplex)是在\(n\)维欧式空间中的\(n+1\)个仿射无关的点的集合的凸包。

[2018-07-16 Mon 14:45]


有关线性模型局限的一个例子:考虑异或函数(两个输入值,当且仅当其中有一个为1的时候输出1,其他时候输出0),当\(x_1=1\)时,模型的输出必须随着\(x_2\)的增大而减小。线性模型必须对\(x_2\)使用固定的系数\(w_2\)。因此,线性模型不能使用\(x_1\)的值来改变\(x_2\)的系数,从而不能解决这个问题。

[2018-07-16 Mon 15:55]


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.

[2018-07-17 Tue 11:09]


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.

[2018-07-17 Tue 19:06]


Capslock改键,短按为Esc,组合按键为Ctrl。

[2018-07-17 Tue 23:11]


在Emacs里用mutt发送邮件

  1. 选中buffer中任意部分内容作为待发送的邮件正文。
  2. 按下组合键 M-| ,此时可以输入正常的shell命令并执行,注意刚才选中的region会被作为该命令的标准输入。
  3. 输入mutt命令: mutt -s "Subject here" -a ~/attachment.txt someone@gmail.com.

[2018-07-19 Thu 20:03]


利用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"

[2018-07-20 Fri 10:28]


mutt批处理邮件

  1. T: 开始标记邮件。
  2. ~f marketing: 标记From字段中包含marketing的所有邮件。
  3. ;: 要求对已标记邮件做批处理。
  4. d: 删除所有已标记邮件。

[2018-07-20 Fri 16:37]


Hadamard product is an entrywise product operation with two matrices of the same dimensions.

[2018-07-23 Mon 23:07]


Python在交互式控制台执行文件指令:

exec(open("somefile.py").read())

[2018-08-07 Tue 19:19]


flymake对C/C++的语法检查是依靠Makefile的,所以Makefile中需要有以下语法检查项目:

check-syntax:
        CC -Wall -Wextra -pedantic -std=c++14 -fsyntax-only $(CHK_SOURCES)

[2018-08-09 Thu 11:22]


如果没有激活函数的作用,就不存在隐藏层了(因为多个线性单元可以组合成一个),那么模型的表达能力就会大打折扣,常用的激活函数有: Sigmoid, Tanh(比sigmoid更常用因为它是以原点对称的), ReLU(比较常用尤其是图像领域)。

[2018-08-09 Thu 16:49]


把\(z_i\)看作是第\(i\)个神经单元的logit(logit是odds的对数,值越大表示事件可能性越高),那么有\(z_i = \log(p_i / (1-p_i))\),这里\(p_i\)表示概率,那么可以得到\(p_i = 1 / (1 + \exp(-z_i))\),即为sigmoid函数。

[2018-08-09 Thu 20:19]


利用 pdfcrop 批量裁切pdf格式图片的白边。

for i in *.pdf; do pdfcrop $i $i.out; rm -f $i; mv $i.out $i; done

[2018-08-13 Mon 11:44]


深度学习过拟合问题的解决办法:

  1. Get more training data
  2. Reduce the capacity of the network
  3. Add weight regularization
  4. Add dropout
  5. Data augmentation
  6. Batch normalization

[2018-08-14 Tue 15:21]


unsupervised learning的应用:

  1. 聚类
  2. 降维
  3. 可视化
  4. 异常点检测
  5. 相关规则学习

[2018-08-14 Tue 21:59]


The differences between MLE (Maximum Likelyhood Estimation) and MAP (Maximum A Posteriori):

  1. The goal of MLE is to find the hypothesis model that maximizes the probability of the data.
  2. The goal of MAP is to find the hypothesis model, for which the data maximizes the probability of the model.

[2018-08-15 Wed 10:08]


概率分布的数学记号,\(p(y) = \mathcal{N}(y\mid\mu, \sigma)\)表示服从正态分布\(\mathcal{N}(\mu, \sigma^2)\)的变量\(y\)的概率。

[2018-08-16 Thu 11:11]


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

[2018-08-25 Sat 13:47]


VBR更适合视频的存储而CBR更适合视频的传输

[2018-08-26 Sun 21:40]


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")

[2018-08-27 Mon 11:20]


C/C++:变量指针可以递增,而数组不能递增,因为数组是一个常量指针。

[2018-08-29 Wed 10:29]


C++中引用和指针的区别

  1. 不存在空引用。引用必须连接到一块合法的内存。
  2. 一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
  3. 引用必须在创建时被初始化。指针可以在任何时间被初始化。

[2018-08-29 Wed 10:39]


C/C++中定义指针变量时候的星号靠近类型或者变量是个人的喜好问题,但是我更偏向靠近变量名,看下面的例子

int *a, *b;

[2018-08-29 Wed 10:40]


C++中引用的用法主要是作为函数形式参数和作为返回值返回。

作为函数形式参数
类似指针传递的作用,在被调用函数中对参数的操作会直接反馈到调用者函数。
作为函数返回值
返回过来的值可以作为赋值的左值。

[2018-08-29 Wed 10:48]


C++类访问修饰符

  1. public: 公有成员在程序中类的外部是可访问的。
  2. private: 私有成员变量或函数在类的外部是不可访问的。只有类和友元函数可以访问私有成员。
  3. protected: 保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的。

[2018-08-29 Wed 11:20]


C++中继承的访问控制几乎不使用protected或private继承,通常使用public继承。当使用不同类型的继承时,遵循以下几个规则:

[2018-08-29 Wed 13:48]


C++中一个派生类继承了所有的基类方法,但下列情况除外:

[2018-08-29 Wed 13:50]


C++11遍历列表

int a[] = {1, 2, 3};
for (auto i : a) {
    std::cout << i << std::endl;
}

[2018-08-29 Wed 19:49]


交换两个文件的一个shell函数

function swap() {
    local TMPFILE=tmp.$$
    mv "$1" $TMPFILE && mv "$2" "$1" && mv $TMPFILE $2
}

[2018-09-14 Fri 11:41]


同时包含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))

[2018-09-14 Fri 11:42]


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;

[2018-09-16 Sun 22:07]


Manifesto for Minimalist Software Engineers: http://minifesto.org

[2018-09-26 Wed 21:16]


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;
}

[2018-09-29 Sat 18:55]


二分查找(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;
}

[2018-09-29 Sat 19:08]


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;
    }
};

[2018-09-29 Sat 19:40]


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;
}

[2018-09-29 Sat 21:19]


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;
}

[2018-09-29 Sat 21:38]


注意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;
}

[2018-09-29 Sat 22:12]


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;
}

[2018-09-29 Sat 23:42]


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;
}

[2018-10-08 Mon 22:42]


ranger可以用 dc 来显示文件夹大小,调用的是 get_cumulative_size.

[2018-10-08 Mon 23:10]


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;
}

[2018-10-09 Tue 13:34]


如何写好一份简历: This is what a GOOD resume should look like

[2018-10-09 Tue 18:36]


[2018-10-12 Fri 10:04]


用互信息做特征选择

\[ \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)} \]

[2018-10-12 Fri 16:41]


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)})();
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)})();

[2018-10-24 Wed 10:37]


通过IMAP列出邮件服务器上的目录

curl --url "imaps://imap.gmail.com/" --user "xxxx@gmail.com"

[2018-10-28 Sun 19:01]


用ffmpeg拼接视频

ffmpeg -f concat -i <(for i in *.mp4; do echo "file '$i'"; done) -c copy output.mp4

[2018-11-08 Thu 19:13]


Apache服务器的配置及启动(以Tiny-Tiny-RSS为例)

  1. 实际的网站目录放到 /var/www/html/ttrss
  2. 创建配置文件 /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>
    
  3. 开启并激活httpd守护进程

    sudo systemctl start httpd
    sudo systemctl enable httpd
    
  4. [TTRSS] 安装并配置postgresql数据库

    yum install postgresql10
    sudo systemctl start postgresql-10
    sudo systemctl enable postgresql-10
    
  5. [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
    

[2018-11-10 Sat 18:24]


配置Shadowsocks服务器

  1. 创建配置文件 /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"
    }
    
  2. 创建文件 /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
    
  3. 启动并激活守护进程

    sudo systemctl start shadowsocks
    sudo systemctl enable shadowsocks
    

[2018-11-10 Sat 18:30]


禁止root用户通过密码从ssh登录(其他用户无此限制),配置文件在 /etc/ssh/sshd_config

PasswordAuthentication yes
Match User root
PasswordAuthentication no
Match all

[2018-11-18 Sun 10:17]


清理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

[2018-11-18 Sun 10:28]


基于iptables配置防火墙

  1. 设置iptables规则,最后可以用 iptables -L 查看。

    # clean up
    iptables --flush
    iptables --delete-chain
    iptables --table mangle --flush
    iptables --table mangle --delete-chain
    # permit port for ssh
    iptables --append INPUT --protocol tcp --dport 22 -j ACCEPT
    # permit port for http
    iptables --append INPUT --protocol tcp --dport 80 -j ACCEPT
    # permit port for https
    iptables --append INPUT --protocol tcp --dport 443 -j ACCEPT
    # allow legal connections
    iptables --append INPUT --match conntrack --ctstate ESTABLISHED,RELATED --jump ACCEPT
    # set fallback rules
    iptables --policy INPUT DROP
    iptables --policy OUTPUT ACCEPT
    iptables --policy FORWARD DROP
    
  2. 如果是远程服务器的话,在进行下一步操作之前,测试并确保仍可以通过ssh连接,否则会有丢失服务器管理权限的风险。
  3. 让当前的iptables规则在主机重启后仍然生效,这一步可以根据不同发行版来做修改,CentOS的话可以直接交给systemd的一个iptables守护进程来实现

    iptables-save > /etc/sysconfig/iptables
    systemctl enable iptables
    systemctl start iptables
    

[2018-11-18 Sun 11:41]


深度学习(deep learning)其实就是有多个隐藏层的神经网络(neural networks),那么为什么需要多个隐藏层呢,可以从两个方面来理解:

  1. 拿人脸识别来说,深度神经网络可以看作是一个从无意义的像素数据开始逐层理解高层语意的过程,前面的隐藏层可能是在进行边缘检测之类的底层操作,而后面的隐藏藏可能就是再做类似识别男女、是否双眼皮之类的高层语意信息了。
  2. 用电路理论(circuit theory)来类比,我们假设输入的特征有很多,那么在只有一个隐藏层的情况下来“猜测”对应输出的概率需要大量的计算量,而多个隐藏层就可以分担掉快速增长的计算量。

[2018-11-21 Wed 19:34]


Emacs中基于S表达式的快捷操作

[2018-12-12 Wed 09:50]


Logistic Regression中用sigmoid映射的原因

  1. 给定二分类问题,输入\(\boldsymbol{x}\),输出\(y \in \{1, 0\}\).
  2. 给定样本输入\(\boldsymbol{x}\),我们希望能得到它属于某类的概率p,但是如果直接采用一个线性函数来映射:\(\boldsymbol{w}^{\top}\boldsymbol{x}\),得到的值定义在整个实数范围内,与概率的定义(在0到1之间)不符。
  3. 我们先放一放上面的映射问题,考虑分对数(logit),它是几率(odds)的对数:即\(logit = \log \frac{p}{1 - p}\),可以发现logit也刚好是定义在实数范围内的单调函数。
  4. 我们把logit和\(\boldsymbol{w}^{\top}\boldsymbol{x}\)对应起来,那么就可以得到概率p的映射\(p = \frac{1}{1 + e^{-\boldsymbol{w}^{\top}\boldsymbol{x}}}\),这个就是sigmoid函数了。

[2018-12-13 Thu 19:11]


利用生成式模型进行分类的一个基础公式: \[ 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})} \]

[2018-12-20 Thu 15:32]


期望(expectation)和方差(variance)都是定义在函数上的,而不是变量。

[2018-12-22 Sat 16:58]


机器学习中对分类问题的处理可以分成两步来理解,第一步叫做推断(inference),在这一步中我们使用训练数据来学习后验概率的模型;第二步叫做决策(decision),在这一步中我们根据后验概率来决定类别。

[2018-12-22 Sat 21:27]


安装Jekyll到用户目录

gem install --user-install --no-doc jekyll

注意最后还需要把gem的可执行文件目录加入到系统环境变量中.

echo "export PATH=\"\$(ruby -e 'print Gem.user_dir')/bin:\$PATH\"" >> ~/.zshrc

[2018-12-23 Sun 21:56]


Transmission可以用这个配置来屏蔽IPv4流量: https://nwps.ws/pub/misc/ipv4-blocklist.txt

[2018-12-24 Mon 09:39]


如果先验跟后验有相同的形式,那么这个先验就是对应似然的共轭先验(conjugate prior),先验分布的参数被称为超参数(hyper-parameters),在二项分布的情况下,其共轭先验就是Beta分布;而多项式分布的共轭先验是Dirichlet分布。

[2018-12-24 Mon 15:50]


Paparazzi!是macOS平台上一个小巧的网页截图工具: https://derailer.org/paparazzi/

[2018-12-29 Sat 18:22]


zsh有五个配置文件,默认是在用户家目录里的,但是我习惯一股脑都放到 .zshrc 里。

$ZDOTDIR/.zshenv
$ZDOTDIR/.zprofile
$ZDOTDIR/.zshrc
$ZDOTDIR/.zlogin
$ZDOTDIR/.zlogout

[2019-01-05 Sat 17:05]


电子书下载网站

[2019-01-08 Tue 10:40]


英文邮件的落款注意事项

[2019-01-15 Tue 11:29]


禁止搜索引擎收录网页中的图片

<meta name="robots" content="noimageindex">

[2019-02-28 Thu 20:02]


欧拉公式: \[ e^{i\theta} = \cos\theta + i\sin\theta \]

[2019-03-01 Fri 11:21]


\(\LaTeX\)加水印:

\usepackage{draftwatermark}

[2019-03-13 Wed 21:35]


pngquant来对png图片进行无损压缩

pngquant foo.png --skip-if-larger --force --output foo.png

[2019-03-15 Fri 15:53]


zip压缩命令,压缩等级可以用 -0, -1, -2, ..., -9 来表示,默认是 -6, 数字越大表示压缩率越大。

zip foo.zip -r -9 foobar

[2019-03-15 Fri 16:54]


一个方便统计当前目录下文件(包括隐藏文件)磁盘占用的别名

alias duu="du -hs .[^.]* * | sort -rh"

[2019-03-21 Thu 10:54]


vim可以用 gqip 达到跟emacs下的 fill-paragraph 一样的调整换行的作用,可配置选项 textwidth 对应emacs下的 fill-column

[2019-03-25 Mon 14:24]


vim中可以用 :vim foo **/*.py 来进行递归地 vimgrep 操作。

[2019-03-25 Mon 14:26]


grep后进行字符串替换

grep -rl "foo" * | xargs sed -i "" "s/foo/bar/g"

[2019-03-27 Wed 11:12]


图片压缩

[2019-03-27 Wed 15:35]


搜索电子书的一个技巧,直接Google: icaredbd.com 书名 azw3

[2019-03-28 Thu 12:35]


vim中删除匹配模式的行,下面的例子是删除所有以 foo 开始的行

:g/^foo/d

[2019-03-29 Fri 15:15]


中文世界通常所说的“英国”指的实际上是“United Kindom”(联合王国),全称“United Kingdom of Great Britain and Northern Ireland”(大不列颠及北爱尔兰联合王国),其中包含四个构成国:首都为London(伦敦)的England(英格兰);首都为Edinburgh(爱丁堡)的Scotland(苏格兰);首都为Cardiff(加的夫)的Wales(威尔士);首都为Belfast(贝尔法斯特)的Northern Ireland(北爱尔兰)。而“Great Britan”(大不列颠)由除北爱尔兰之外的其他三个构成国组成。

ZrTx1p8.gif

[2019-03-30 Sat 13:51]


Git打标签

# 创建一个tag
git tag v0.1
# 更新tag至远程仓库
git push --tags
# 删除本地及远程仓库中的tag
git tag -d v0.1
git push origin :refs/tags/v0.1

[2019-04-01 Mon 18:06]


根据一级标题将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))))

[2019-04-02 Tue 14:29]


Org-mode中插入图片可以这样指定大小

#+attr_html: :width 200
#+attr_latex: :width 200
[[~/Desktop/foo.png]]

[2019-04-03 Wed 09:51]


Org-mode导出pdf想要为hyperref添加 hidelinks 参数的话可以有以下几种方案

  1. 修改 org-latex-default-packages-alist, 该列表变量包含了默认加载的包,其中包含了未指定参数的hyperref,我们可以通过 (add-to-list 'org-latex-default-packages-alist "\\PassOptionsToPackage{hidelinks}{hyperref}") 来给hyperref追加 hidelinks 选项。
  2. 在org文件头部加 #+latex_header: \hypersetup{hidelinks} 来实现。
  3. 修改 org-latex-hyperref-template: 该列表本身包含了 \hypersetup{...} 的设置,在其中加入 hidelinks 即可。

[2019-04-03 Wed 11:11]


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.

[2019-04-04 Thu 15:51]


Never say "the likelihood of the data". Always say "the likelihood of the parameters". The likelihood function is not a probability distribution.13

[2019-04-04 Thu 16:17]


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}} \]

[2019-04-04 Thu 16:25]


Probability and Likelihood

[2019-04-04 Thu 16:41]


\(\LaTeX\)中如果要强制使用英文的分段样式(即段落垂直间隔而首行不缩进),尤其是在CTEX环境下,可以通过导入 parskip 包来实现。

[2019-04-06 Sat 10:39]


Org-mode导出文档时不显示作者、日期等:

#+OPTIONS: author:nil date:nil

[2019-04-06 Sat 11:30]


从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)];
}

[2019-04-07 Sun 22:06]


lighttpd中启用CGI模块

server.modules += "mod_cgi"
cgi.assign = (".cgi" => "")

[2019-04-08 Mon 16:30]


[2019-04-08 Mon 16:33]


将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>

[2019-04-08 Mon 19:29]


Google搜索中文网页: https://google.com?lr=lang_zh-CN

[2019-04-11 Thu 16:49]


奇异值分解和特征值分解都是给一个矩阵(线性变换)找一组特殊的基:

[2019-04-11 Thu 17:51]


SCI收录号(Accession Number)查询: https://webofknowledge.com/

[2019-04-13 Sat 10:32]


Python基于虚拟环境的依赖管理:

python3 -m venv .venv
source .venv/bin/activate
pip install <pkgname1> <pkgname2>
pip freeze > requirements.txt
echo ".venv/" >> .gitignore

[2019-04-14 Sun 10:18]


Dashes in \(\LaTeX\)

[2019-04-16 Tue 09:58]


Emacs设置本地变量操作minor modes,不要直接用变量(VARIABLE)设置,这样会有安全问题14,推荐用 eval: ,比如下面的设置会在该文件中禁用 flyspell-mode:

eval: (flyspell-mode -1)

[2019-04-19 Fri 11:35]


廉价VPS

[2019-04-21 Sun 09:07]


Emacs中calc模式下可以用 M-0 DEL 来清空栈。

[2019-04-21 Sun 10:36]


在决策树中,每次数据集分叉的准则是最大化Gini Gain,指的是分叉前后的Gini Impurity减少的量。

[2019-04-28 Sun 12:18]


Vim的补全框架对比

[2019-05-09 Thu 15:29]


Vim补全框架vim-mucomplete配置

let g:mucomplete#no_mappings=1
let g:mucomplete#enable_auto_at_startup=1

[2019-05-09 Thu 15:39]


默认的Org-mode导出pdf时需要两个包: wrapfig, capt-of.

[2019-05-09 Thu 19:55]


texlive显示已安装的包:

tlmgr list --only-installed

[2019-05-09 Thu 19:55]


简单但不失优雅的网页样式

body {
  max-width: 38rem;
  padding: 2rem;
  margin: auto;
}

[2019-05-20 Mon 11:33]


BibTex引用网页文章的条目

@online{duggan2013photo,
  title =        {Photo and Video Sharing Grow Online},
  author =       {Duggan, Maeve},
  url =          {https://www.pewinternet.org/2013/10/28/photo-and-video-sharing-grow-online/},
  urldate =      {2018-01-21},
  year =         2013
}

[2019-05-21 Tue 17:05]


Linux隐藏输出

[2019-05-22 Wed 09:57]


在网页动态内容加载完成后用MathJax进公式的渲染:

  1. 首先,头部加载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>
    
  2. 为动态加载内容完成后触发MathJax配置。

    var xhttp = new XMLHttpRequest();
    ...
    xhttp.addEventListener('load', function(e){MathJax.Hub.Configured();});
    

[2019-05-25 Sat 09:56]


目标函数和所有的约束函数都为线性函数,则该问题为线性规划问题(Linear Programming)。相反,如果目标函数或任何一个约束函数为非线性函数,则该问题为非线性规划问题(Nonlinear Programming) 。

[2019-05-30 Thu 11:26]


凸优化问题是一种特殊的约束优化问题,需满足目标函数为凸函数,并且等式约束函数为线性函数,不等式约束函数为凹函数。

[2019-05-30 Thu 11:26]


拷贝SSH公钥到服务器

ssh-copy-id ~/.ssh/id_ed25519.pub user@host

[2019-06-01 Sat 16:08]


Linux中创建用户

# create a user and create its home directory
useradd -m someone
# add a user to the `sudo' group
adduser someone sudo

[2019-06-04 Tue 16:27]


一般来说,混淆矩阵的横行代表真实标签,纵列代表预测标签

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

[2019-06-05 Wed 15:57]


Homebrew显示软件包的依赖情况

brew deps --tree --installed

[2019-06-05 Wed 18:31]


Matplotlib使用自定义字体,分下列三种情况讨论:

  1. 提供额外字体目录给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()
    
  2. 直接指定字体文件位置来设置字体

    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()
    
  3. 仅在某些位置使用自定义字体

    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()
    

[2019-06-06 Thu 08:59]


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]

[2019-06-07 Fri 10:27]


CTEX中强制取消中英文之间的空格。

[2019-06-10 Mon 19:31]


\(\LaTeX\) 中 \autoref{} 引用时的格式:

\def\equationautorefname~#1\null{Equation~(#1)\null}

[2019-06-10 Mon 19:50]


利用dos2unix命令递归地修改文件编码

find . -type f -exec dos2unix --keepdate {} +

[2019-06-12 Wed 17:04]


Emacs编辑远程文件,其中的 method 可以是ssh或者ftp等。

/method:host:filename
/method:user@host:filename
/method:user@host#port:filename

[2019-06-13 Thu 14:21]


Vim的各种补全插件比较

[2019-06-14 Fri 10:22]


主流的邮件存储格式主要有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])

[2019-06-20 Thu 18:23]


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

[2019-06-26 Wed 20:39]


IMAP邮箱名称会出现utf-7跟utf-8相关的编码问题,用imapclient可以解析utf-7.

from imapclient import imap_utf7
decoded = imap_utf7.decode(b'&UXZO1mWHTvZZOQ-')
print(decoded)

[2019-06-27 Thu 09:42]


mutt中可以通过设置 sort 参数的值暂时改变邮件排序方式,比如通过 set sort=reverse-size 来按照邮件大小从大到小排列。

[2019-06-27 Thu 17:23]


mutt中的邮件过滤和标记后批量处理功能:

[2019-06-28 Fri 08:53]


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:'

[2019-06-28 Fri 17:59]


macOS Sierra新加入的字体 SF Mono 默认不是全局不可见,它的文件位置在: /Applications/Utilities/Terminal.app/Contents/Resources/Fonts/

[2019-06-30 Sun 12:27]


下面这些项目结构比较简单,而且代码风格也非常规范,值得作为程序设计、项目开发的例子来学习。

C
noice - small file browser: https://git.2f30.org/noice/
C
smu - simple markdown markup: https://github.com/Gottox/smu

[2019-07-03 Wed 22:52]


新鲜服务器的基本配置:

  1. 更新系统,安装: vim, tmux, openssh, zsh。
  2. 配置ssh公钥登陆。
  3. 上传配置文件: vim, tmux, zsh,并测试可用性
  4. 利用iptables配置防火墙

[2019-07-06 Sat 09:01]


口碑不错的卖旅行包的店铺:

[2019-07-08 Mon 09:26]


如果某个服务器上的scp或rsync都不能用,可以用如下的方法来传输文件到服务器上:

cat ./foo.txt | ssh username@ipaddress "cat > ~/somepath/foo.txt"

[2019-07-17 Wed 10:35]


lighttpd配置SSL,配置文件在 /etc/lighttpd/lighttpd.conf

$SERVER["socket"] == ":443" {
  ssl.engine  = "enable"
  ssl.pemfile = "/etc/lighttpd/certs/server.pem"
}

[2019-07-19 Fri 10:48]


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" => "")
}

[2019-07-19 Fri 10:49]


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)

[2019-08-13 Tue 20:57]


Emacs下获取当前行号

(format-mode-line "%l")

[2019-08-29 Thu 15:13]


用CSS来使网页自适应系统的明暗配色 15

@media (prefers-color-scheme: dark) {
  body {
    background-color: #444;
    color: #e4e4e4;
  }
  a {
    color: #e39777;
  }
  img {
    filter: grayscale(30%);
  }
}

[2019-10-14 Mon 17:02]


TeXLive常用的一些包:

[2019-10-15 Tue 23:00]


Hugo主题:

[2019-10-20 Sun 15:43]


Jekyll主题:

[2019-10-30 Wed 20:55]


Unix系统下配置邮件自动转发:

[2019-11-19 Tue 10:48]


Makefile的清理模块可以这么写:

clean:
        @rm -rf *.{ps,log,aux,out,dvi,bbl,blg}

[2020-01-05 Sun 11:48]


Debian开启BBR拥塞控制算法16

  1. 需要4.9.0以上内核。
  2. /etc/sysctl.conf 末尾添加以下内容:

    net.core.default_qdisc=fq
    net.ipv4.tcp_congestion_control=bbr
    
  3. 运行 sysctl -p 让配置生效。
  4. 运行 lsmod | grep bbr 检查BBR是否正确开启。

[2020-01-08 Wed 12:47]


MKVToolNix是一个跨平台的处理MKV视频文件的工具集。

[2020-01-11 Sat 00:52]


kodi播放视频时现实解码器等信息:

kodi-send --action=PlayerProcessInfo
kodi-send --action=PlayerDebug

[2020-04-20 Mon 23:05]


用calibre转换mobi为epub,可以指定 --output-profile tablet 来关闭对图片的resize,主要是针对一些漫画

ebook-convert input.mobi output.epub --output-profile tablet

[2020-07-18 Sat 20:39]


命令行测试IPV6

curl -XGET https://v6.ident.me

[2020-08-21 Fri 07:30]


查看端口绑定情况: netstat -ltpn

[2020-08-23 Sun 22:36]


随机生成UUID

uuidgen

[2021-02-13 Sat 15:40]


macOS下以读写模式挂载NTFS格式U盘

sudo umount /Volumes/UNTITLED
sudo mount -t ntfs -o rw,auto,nobrowse /dev/disk3s1 ~/ntfs_volume

[2021-02-14 Sun 15:40]


红米AC2100获取root权限:

  1. 从路由器管理界面登录并获取 <STOK>: http://192.168.31.1/cgi-bin/luci/;stok=<STOK>/web/home#router
  2. 分别访问以下两个地址(其中 <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
    
  3. 通过ssh登录路由器(密码为 =admin=)。

    ssh root@192.168.31.1
    

[2021-03-15 Mon 22:25]


将名为 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

[2021-03-17 Wed 20:10]


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"
      }
    ]
  }
}

[2021-03-19 Fri 20:22]


通过每一行定义一个域名的 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

[2021-03-19 Fri 21:32]


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'

[2021-03-19 Fri 21:37]


nftables可以用来替代iptables,好处是配置方便,且不用分别为IPv4跟IPv6维护两套规则。

  1. 使用 nft flush ruleset 来清空规则。
  2. 使用 nft -f nftables.conf 来载入规则。
  3. 默认规则文件位置为 /etc/nftables.conf
  4. 下面是一个简单的提供类似防火墙功能的规则:

    #!/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;
        }
    }
    

[2021-03-20 Sat 14:35]


orgmode中彻底禁止某个代码片段的执行:

#begin_src shell :eval never-export
echo "foo"
#end_src

[2021-03-20 Sat 14:43]


某些epub电子书用kindlegen转换为mobi格式后会出现乱码,来自kobo的电子书基本都会有这个问题,原因在于epub文档中的html文件没有指定编码,而kindlegen默认都会用utf-8编码,所以会出现乱码:

  1. 解压已去DRM的epub电子书

    unzip ebook_raw.epub -d ebook_unzipped/
    
  2. 在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
    
  3. 重新封装为epub文件

    cd ebook_unzipped/ && zip -rX ../ebook_new.epub mimetype META-INF/ OEBPS/ -x \*.DS_Store && cd -
    
  4. 用kindlegen将epub转换为mobi格式

    kindlegen -dont_append_source ebook_new.epub
    

[2021-07-11 Sun 07:57]


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, "黑体";
}

[2021-07-11 Sun 10:16]


isync遇到证书问题可以用手动下载证书来解决

wget https://gist.githubusercontent.com/petRUShka/af96ae25ce8280729b9ea049b929f31d/raw/a79471ce8aee3f6d04049039adf870a53a524f7f/get_certs.sh
sh get_certs.sh imap.xxx.com 993 ~/.cert/

[2022-02-13 Sun 14:47]


如果需要在服务器上转发邮件到指定邮箱,并在原邮箱中保留一份,可以写入文件 ~/.forward:

localusername,
forwardto@gmail.com

[2022-10-16 Sun 22:15]


实用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

[2023-03-01 Wed 20:52]


GarlicOS默认无法显示中文,可以通过替换 CFW/Skin/font.ttf 来实现中文显示,推荐字体:寒蝉高黑体。

[2023-04-29 Sat 14:45]


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

[2023-04-29 Sat 23:04]


用ghostscript压缩pdf

gs -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile="output.pdf" input.pdf

[2023-05-09 Tue 22:07]


雷鸟电视刷机及开启adb的方法

  1. 历史版本固件下载: https://www.znds.com/tv-1229547-1-1.html 提取码o2j6; 因为我的电视是雷鸟鹏50S365C,所以下载的固件是V8-A982T01-LF1V051.zip (注意更新版本的固件可能会导致adb无法安装第三方软件)
  2. 把对应版本的固件zip包(不用解压)直接放到U盘(FAT32格式,插入电视上的USB2.0口,即白色的口)
  3. 依次进入电视的 设置->关于本机->系统升级->本地升级, 之后电视会自动搜寻并校验固件安装包,等待几分钟安装完成即可。
  4. 开启adb: 依次进入电视的 设置->关于本机->本机信息, 在本机信息界面依次按遥控器 上、下、左、右 即可。
  5. 关闭系统自动更新。

    # 关闭自动更新
    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
    

[2023-07-09 Sun 16:04]


利用bilingual_book_maker制作双语epub

~/.venv/bbook/bin/bbook_maker --book_name eng.epub --model google -p 127.0.0.1:7890

[2023-08-17 Thu 22:00]


利用Cloudflare Workers部署V2ray代理,可以参考教程 https://blog.dongstop.link/edgetunnel

[2024-01-08 Mon 12:14]


Footnotes:

6

A channel variation-aware algorithm for enhanced video streaming quality

8

italic和slanted都表示斜体,但其实它们是不太一样的,italic可以看作是一种新的字型了(直观上更“花哨”),而slanted只是把原来的字型倾斜过来而已。

9

Schäfer, Patrick, and Ulf Leser. "Multivariate Time Series Classification with WEASEL+ MUSE." arXiv preprint arXiv:1711.11343 (2017).

10

Karim, Fazle, et al. "Multivariate LSTM-FCNs for Time Series Classification." arXiv preprint arXiv:1801.04503 (2018).

11

Groups, Rings, Fields and Ideals: http://d.pr/TcOUfF

12

一般我们用 \(P(x)\) 表示离散变量上的概率分布而用 \(p(x)\) 表示连续变量上的概率分布

13

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".

Edited by Isaac Gu on 2024-01-08 Mon 12:15