<repo_name>witcxc/funnycode<file_sep>/go/crawl/a.go
package main

import (
	"fmt"
	"strconv"
	"sync"
)

func main() {

	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func(si int) {
			defer wg.Done()
			t := strconv.Itoa(si)
			for i := 0; i < 90; i++ {
				t += strconv.Itoa(si)
			}

			fmt.Printf("%s\n", t)
		}(i)
	}
	wg.Wait()
}
<file_sep>/cppcode/trans_gitlog_time.cpp
#include    <stdio.h>
#include    <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <xlocale.h>
#include <string.h>
/*
 *
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:
 * =====================================================================================
 */
int main(int argc, char *argv[]) {
    struct tm tm_p;

    char buf [101];
    memset(buf,0,sizeof(buf));

    if ( fgets(buf, 40, stdin) != NULL ) {
        if (strcmp(argv[1], "git") == 0)
        {
            strptime(buf, "%a %b %e %T %Y", &tm_p);
            // puts(buf);
            // printf("%d %d %d %d %d %d\n",tm_p.tm_year,tm_p.tm_mon,tm_p.tm_mday,tm_p.tm_hour,tm_p.tm_min,tm_p.tm_sec);
            strftime (buf,40,"%Y-%m-%d %T",&tm_p);

            puts(buf);
        } else if(strcmp(argv[1], "fmt") == 0)
        {
            strptime(buf, "%Y-%m-%d %T", &tm_p);
            strftime (buf,40,"%Y%m%d%H%M",&tm_p);
            puts(buf);

        }

    }

    return EXIT_SUCCESS;
}
<file_sep>/dot/gen_mixer.sh
dot -Tpng mixer.dot -o mixer.png
dot -Tps mixer.dot -o mixer.ps
<file_sep>/compsys/code.c
/*
 * =====================================================================================
 *
 *       Filename:  code.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2017/06/11 22时56分45秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  <NAME> (happyleaf), <EMAIL>
 *   Organization:  
 *
 * =====================================================================================
 */

int accum = 0;
int sum(int x, int y)
{
    int t = x + y;
    accum += t;
    return t;
}
<file_sep>/cppcode/url_encode.cpp
/*
 * =====================================================================================
 *
 *       Filename:  url_encode.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2017/02/28 00时13分39秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  <NAME> (happyleaf), <EMAIL>
 *   Organization:  
 *
 * =====================================================================================
 */
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;

unsigned char ToHex(unsigned char x) 
{ 
	return  x > 9 ? x + 55 : x + 48; 
}

unsigned char FromHex(unsigned char x) 
{ 
	unsigned char y;
	if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;
	else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;
	else if (x >= '0' && x <= '9') y = x - '0';
	else assert(0);
	return y;
}

std::string UrlEncode(const std::string& str)
{
	std::string strTemp = "";
	size_t length = str.length();
	for (size_t i = 0; i < length; i++)
	{
		if (isalnum((unsigned char)str[i]) || 
				(str[i] == '-') ||
				(str[i] == '_') || 
				(str[i] == '.') || 
				(str[i] == '~'))
			strTemp += str[i];
		else if (str[i] == ' ')
			strTemp += "+";
		else
		{
			strTemp += '%';
			strTemp += ToHex((unsigned char)str[i] >> 4);
			strTemp += ToHex((unsigned char)str[i] % 16);
		}
	}
	return strTemp;
}

std::string UrlDecode(const std::string& str)
{
	std::string strTemp = "";
	size_t length = str.length();
	for (size_t i = 0; i < length; i++)
	{
		if (str[i] == '+') strTemp += ' ';
		else if (str[i] == '%')
		{
			assert(i + 2 < length);
			unsigned char high = FromHex((unsigned char)str[++i]);
			unsigned char low = FromHex((unsigned char)str[++i]);
			strTemp += high*16 + low;
		}
		else strTemp += str[i];
	}
	return strTemp;
}

#include	<stdio.h>
#include	<stdlib.h>

/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:  
 * =====================================================================================
 */
int main(int argc, char *argv[]) {
    string src = "my=apples&are=green+and+red";
    string ret = UrlEncode(src);
    cout<<"src:["<<src<<"]"<<endl<<"encode:["<<ret<<"]"<<endl;
    string dec = UrlDecode(ret);
    cout<<dec<<endl;
    cout<<"dec:["<<ret<<"]"<<endl<<"src:["<<dec<<"]"<<endl;

    
    return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
<file_sep>/go/go_equal.go
package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)

type ss struct {
	ID int
}
type s struct {
	ID   ss
	name string
}

type DiskSpec struct {
	VolumeName           string            `json:",omitempty"`
	AllowUseHostBootDisk bool              `json:",omitempty"`
	Size                 int64             //:61440000000 //单位：字节。磁盘空间大小
	Type                 string            `json:",omitempty"` //:"SSD", "SATA"
	Iops                 int               `json:",omitempty"` //单位：次/秒。应用单实例的磁盘iops配额， NC的iops能力要大于这个值才能被选中；如果后面有iops隔离，那么这个值就是磁盘iops的quota值
	Iobps                int64             `json:",omitempty"` //单位：字节。应用单实例的磁盘带宽配额， NC的io吞吐能力要大于这个值才能被选中；如果后面有磁盘io带宽隔离，那么这个值就是磁盘带宽的quota值
	Rm                   string            `json:",omitempty`  //ro：readonly， rw：read write 含义等同于docker -v /a=/b:rw中冒号后面的部分
	Exclusive            string            `json:",omitempty"` //none:不独占，instance：实例独占；app：同一个appname可以共用，不和其他app共用
	Mandate              bool              `json:",omitempty"` //是否必需,默认为 true, 若非必需调度时可能不会给予分配
	Driver               string            `json:",omitempty"` //磁盘driver 类型, 默认为local,
	IncludeVolumeInParam bool              `json:",omitempty"` // 是否把docker create api 中的-v 选项指定的非bind mount volume 也使用这个磁盘
	IncludeVolumeInImage bool              `json:",omitempty"` // 是否把镜像中的 volume 也使用这个磁盘
	Opt                  map[string]string `json:",omitempty"` //driver 的选项
	Label                map[string]string `json:",omitempty"` //磁盘的 label
}

//{ true 1073741824  0 0   true  false false map[] map[]}
func main() {
	var p, q s
	p.ID.ID = 10
	p.name = "hello"
	q.ID.ID = 11
	q.name = "hello"
	fmt.Printf("hello!aaa")
	if !reflect.DeepEqual(p, q) {
		fmt.Printf("equal %v", p)
	}
	if !reflect.DeepEqual(nil, q) {
		fmt.Printf("---- %v, %v", p, nil)
	}
	var a, b DiskSpec
	a.VolumeName = ""
	a.AllowUseHostBootDisk = true
	a.Size = 1073741824
	a.Iops = 0
	a.Iobps = 0
	a.Mandate = true
	a.IncludeVolumeInParam = false
	a.IncludeVolumeInImage = false
	jsonStr, err := json.Marshal(a)
	if err != nil {

		fmt.Printf("\nmarshar error!")
	}
	if err := json.Unmarshal(jsonStr, &b); err != nil {
		fmt.Printf("\nun marshar error!")
	}

	//	b.VolumeName = ""
	//	b.AllowUseHostBootDisk = true
	//	b.Size = 1073741824
	//	b.Iops = 0
	//	b.Iobps = 0
	//	b.Mandate = true
	//	b.IncludeVolumeInParam = false
	//	b.IncludeVolumeInImage = false

	if !reflect.DeepEqual(a, b) {
		fmt.Printf("\ndisk not equal [%v] != [%v]", a, b)
	} else {
		fmt.Printf("\nequal [%v] == [%v]", a, b)
	}
	var c, d map[string]string
	if !reflect.DeepEqual(c, d) {
		fmt.Printf("\n-----disk not equal [%v] != [%v]", c, d)
	}

}
<file_sep>/c/quick_sort.c
/*
 * =====================================================================================
 *
 *       Filename:  quick_sort.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2017/03/10 18时43分47秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  <NAME> (happyleaf), <EMAIL>
 *   Organization:  
 *
 * =====================================================================================
 */


#include	<stdio.h>
#include	<stdlib.h>


/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  quick_sort
 *  Description:  
 * =====================================================================================
 */
void quick_sort(int *arr, int size) {

    if (size <= 1) {
        return;
    }
    int mark = arr[0];
    int s_i = 0;
    
    for (int i = 1; i <= size - 1; ++i ) {

        if (arr[i] <= mark) {
            int tmp = arr[s_i + 1];
            arr[s_i + 1] = arr[i];
            arr[i] = tmp;
            s_i = s_i + 1;
        }
    }
    arr[0] = arr[s_i];
    arr[s_i] = mark;
    if(s_i > 1) {
        quick_sort(arr, s_i);
    }

    if ((size - s_i - 1) > 1) {
        quick_sort(arr + s_i + 1, size - s_i - 1);
    }
}		/* -----  end of function quick_sort  ----- */
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:  
 * =====================================================================================
 */
int main(int argc, char *argv[]) {
//    int arr[5] = {3, 4 , 2, 5, 1};
//    printf("%d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4]);
//    quick_sort(arr, sizeof(arr)/sizeof(arr[0]));
//    printf("%d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4]);
    int size = 0;
    int * arr = NULL;
    int i = 0;

    while(scanf("%d", &size) == 1){
        arr = (int *)malloc(sizeof(int) * size);

        for (i = 0; i < size; ++i)
        {
            scanf("%d", &(arr[i]));

        }
        for (i = 0; i < size; ++i) {
            printf("%d ", arr[i]);
        }
        printf("\n");
        quick_sort(arr, size);
        for (i = 0; i < size; ++i) {
            printf("%d ", arr[i]);
        }
        printf("\n");
    }

    return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
<file_sep>/cppcode/self2.c
#include <stdio.h>
char s[] ="#include <stdio.h>%cchar s [] =%c%s%c;main(){printf(s,10,34,s,34);}";main(){printf(s,10,34,s,34);}
<file_sep>/c/gen_sort_data.c
/*
 * =====================================================================================
 *
 *       Filename:  gen_sort_data.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2017/03/10 19时24分45秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  <NAME> (happyleaf), <EMAIL>
 *   Organization:  
 *
 * =====================================================================================
 */


#include	<stdio.h>
#include	<stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>

/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:  
 * =====================================================================================
 */

int main(int argc, char *argv[]) {

    FILE	*fp;										/* output-file pointer */
    char	*fp_file_name = "data.txt";		/* output-file name    */

    srand((int)time(0));
    fp	= fopen( fp_file_name, "w" );
    if ( fp == NULL ) {
        fprintf ( stderr, "couldn't open file '%s'; %s\n",
                fp_file_name, strerror(errno) );
        exit (EXIT_FAILURE);
    }
    int size  = rand()%1000000;

    fprintf(fp,"%d", size);
    for (int i = 0; i < size; ++i) {
        fprintf(fp," %d", rand());
    }
    if( fclose(fp) == EOF ) {			/* close output file   */
        fprintf ( stderr, "couldn't close file '%s'; %s\n",
                fp_file_name, strerror(errno) );
        exit (EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
<file_sep>/go/single_val.go
package main

import (
	"def"
	"fmt"
	"test"
)

func main() {
	fmt.Printf("\nhello[%d]", def.Con)
	def.Con += 2
	test.Change()
	fmt.Printf("\nhello[%d]", def.Con)

}
<file_sep>/clone/prep.sh
#!/bin/bash
yum install git
ssh-keygen -t rsa -b 4096 -C "<EMAIL>"

useradd -m  happyleaf
passwd happyleaf
visudo
# add
#username        ALL=(ALL)      ALL

git clone <EMAIL>:witcxc/funnycode.git

#yum install go
wget https://dl.google.com/go/go1.10.1.linux-amd64.tar.gz
tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz
export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin
export GOPATH=/home/happyleaf/go


go get github.com/shadowsocks/shadowsocks-go/cmd/shadowsocks-server
make all

nohup ./shadowsocks-server -c config.json > shadow_out.log 2>&1 &
sudo bash -c su
nice -n -20 nohup ./serv.bin -c config.json -d

#python
wget https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tgz
tar xzf Python-2.7.14.tgz
cd Python-2.7.14
./configure --prefix=/home/happyleaf/python --enable-optimizations --enable-unicode
make
make install

#virtual env
curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-X.X.tar.gz
tar xvfz virtualenv-X.X.tar.gz
cd virtualenv-X.X
[sudo] python setup.py install

#vim
sudo yum install ncurses-devel
sudo yum install -y ruby ruby-devel lua lua-devel luajit \
    luajit-devel ctags git python python-devel \
    python3 python3-devel tcl-devel \
    perl perl-devel perl-ExtUtils-ParseXS \
    perl-ExtUtils-XSpp perl-ExtUtils-CBuilder \
    perl-ExtUtils-Embed

git clone https://github.com/vim/vim.git
cd vim/
export PATH=/home/happyleaf/python/bin/:$PATH
make distclean
./configure --with-features=huge \
            --enable-multibyte \
            --enable-rubyinterp=yes \
            --enable-pythoninterp=yes \
            --with-python-config-dir=/home/happyleaf/python/lib/python2.7/config \
            --enable-perlinterp=yes \
            --enable-luainterp=yes \
            --enable-cscope \
            --prefix=/usr/local
#            --enable-python3interp=yes \
#            --with-python3-config-dir=/usr/lib/python3.5/config \

#vim Makefile
make
sudo make install

#{
#    "server":"0.0.0.0",
#    "server_port":8389,
#    "local_port":1080,
#    "local_address":"127.0.0.1",
#    "password":"<PASSWORD>",
#    "method": "aes-256-ctr",
#    "timeout":600
#}
<file_sep>/dot/gen.sh
dot -Tpng graph.dot -o graph.png
dot -Tpng simple.dot -o simple.png
dot -Tpng module.dot -o module.png
dot -Tpng simple_module.dot -o simple_module.png
dot -Tpng if_sigma.dot -o if_sigma.png
<file_sep>/go/httpserver.go
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
)

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {

	fmt.Printf("[%v]\n", req)
	buf := &bytes.Buffer{}
	nRead, err := io.Copy(buf, req.Body)
	if err != nil {
		fmt.Printf("\nerr[%v]\n", err)
	}
	fmt.Printf("\nbody[%v]\nlen[%v]\n", buf, nRead)
	io.WriteString(w, "hello, world!\n")
}

func main() {
	http.HandleFunc("/", HelloServer)
	err := http.ListenAndServe(":8089", nil)
	if err != nil {
		fmt.Printf("\nListenAndServe: %v\n", err)
	}
}
<file_sep>/go/compare.go
package main

import (
	"fmt"
)

type Person struct {
	age  int
	name string
}

func (Person p) change() int {
	p.age += 1
	fmt.Printf("\nin func %v", p)
	return 0

}
func change(t map[string]int) {
	t["hello"] = 13
	fmt.Printf("\nin func %v", t)

}
func main() {
	var p = Person{12, "hello"}
	p.change()
	fmt.Printf("\nout %v", p)
	a := make(map[string]int)
	a["hello"] = 12
	change(a)
	fmt.Printf("\nout func %v", a)
}
<file_sep>/go/crawl/page_parse.go
package main

import (
	"fmt"
	"golang.org/x/net/html"
	_ "log"
	"net/http"
	"os"
)

func forEachNode(n *html.Node, pre, post func(n *html.Node)) {
	if pre != nil {
		pre(n)
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		forEachNode(c, pre, post)
	}
	if post != nil {
		post(n)
	}
}
func main() {
	resp, err := http.Get(os.Args[1])
	if err != nil {
		return
	}
	if resp.StatusCode != http.StatusOK {
		resp.Body.Close()
		return
	}
	doc, err := html.Parse(resp.Body)
	resp.Body.Close()
	if err != nil {
		return
	}

	visitNode := func(n *html.Node) {
		if n.Type == html.ElementNode && n.Data == "title" {
			fmt.Printf("%+v", n.FirstChild.Data)
		}
	}
	forEachNode(doc, visitNode, nil)
}
