icps

notes

Go

PrintError
1
2
3
4
5
6
7
8
9
10
11
12
"runtime"

func printError(err error, str ...string) {
    if err != nil {
        pc, _, _, _ := runtime.Caller(1)
        fmt.Println(" -> ", runtime.FuncForPC(pc).Name())
        fmt.Println("   - ", err)
        for _, s := range str {
            fmt.Println("     - ", s)
        }
    }
}
sleep
1
2
3
4
5
time.Sleep(1 * time.Second)

func sleep(t int) {
    time.Sleep(time.Duration(t) * time.Millisecond)
}

cmd

toEXE
1
2
3
4
5
windoes/linux amd64/386
GOOS=windows GOARCH=amd64 go build -o hello.exe hello.go

GOOS=windows GOARCH=amd64 go build  -ldflags -H=windowsgui -o hello.exe hello.go
//hide windows
convert

https://mholt.github.io/curl-to-go/
https://mholt.github.io/json-to-go/ https://github.com/Terry-Mao/paint

argv

os.Args[1]

run command
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func runCmd(cmd string) {
    c := exec.Command(cmd)
    _, err := c.Output()
    printError(err)
}

func runCmd(cmd string) {
    c, err := exec.Command("bash", "-c", cmd).CombinedOutput()
    printError(err, string(c))
}

func runCmd(cmd string) {
    c, err := exec.Command("cmd", "/c", cmd).CombinedOutput()
    printError(err, string(c))
}

"bytes"
"golang.org/x/text/encoding/traditionalchinese"
"golang.org/x/text/transform"

func RunPS(cmd string) []string {
    big5utf8 := func(str string) string {
        reader := transform.NewReader(bytes.NewReader([]byte(str)), traditionalchinese.Big5.NewDecoder())
        out, _ := ioutil.ReadAll(reader)
        return string(out)
    }
    c, err := exec.Command("powershell", "/c", cmd).CombinedOutput()
    printError(err, string(c))
    content := big5utf8(string(c))
    return strings.Split(content, "\n")
}
ipconfig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func getLocalIp() []string {
    var result []string
    ifaces, _ := net.Interfaces()
    for _, i := range ifaces {
        addrs, _ := i.Addrs()
        for _, addr := range addrs {
            var gip net.IP
            switch v := addr.(type) {
            case *net.IPNet:
                gip = v.IP
            case *net.IPAddr:
                gip = v.IP
            }
            ip := gip.To4()
            if ip != nil && !ip.IsLoopback() {
                result = append(result, ip.String())
            }
        }
    }
    return result
}
checkUrl
1
2
3
4
5
6
7
8
9
10
func checkUrl(url string) bool {
    resp, err := http.Head(url)
    if err != nil {
        return false
    }
    if resp.StatusCode != http.StatusOK {
        return false
    }
    return true
}
screenShot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"github.com/kbinani/screenshot"
"github.com/oliamb/cutter"
"image"
"image/png"

func getScreenshot(px, py, width, height int, imageName string) {
    bounds := screenshot.GetDisplayBounds(0)

    img, err := screenshot.CaptureRect(bounds)
    if err != nil {
        fmt.Println(err)
    }
    file, _ := os.Create(imageName)
    defer file.Close()

    croppedImg, err := cutter.Crop(img, cutter.Config{
        Anchor: image.Point{px, py},
        Width:  width,
        Height: height,
    })

    png.Encode(file, croppedImg)
    sleep(delay)
}

list file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//"path/filepath"
func listFile(root string) []string {
    var files []string
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if regexMatch(path, `.*\.jpg`) {
            files = append(files, path)
        }
        return nil
    })
    printError(err)
    return files[1:]
}

"io/ioutil"

func listFile(filePath string) []string {
    var files []string
    fs, err := ioutil.ReadDir(filePath)
    printError(err)

    for _, f := range fs {
        files = append(files, f.Name())
    }
    return files
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"github.com/oliamb/cutter"
"github.com/sclevine/agouti"
"image"
"image/png"
func getScreenshot(page *agouti.Page, px, py, width, height int, imageName string) {
    page.Screenshot(imageName)

    f, err := os.Open(imageName)
    if err != nil {
        fmt.Println("Cannot open file", err)
    }
    img, _, err := image.Decode(f)
    if err != nil {
        fmt.Println("Cannot decode image:", err)
    }
    file, _ := os.Create(imageName)
    defer file.Close()

    croppedImg, err := cutter.Crop(img, cutter.Config{
        Anchor: image.Point{px, py},
        Width:  width,
        Height: height,
    })

    png.Encode(file, croppedImg)
    sleep(delay)
}
1
2
3
4
5
function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

console.log( getElementByXpath("//div[11]//span") );
curl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import (
    "io/ioutil"
)
resp, err := http.Get(url)
if err != nil {
    // handle err
}
defer resp.Body.Close()
body, e := ioutil.ReadAll(resp.Body)

if e != nil {
   // handle err
}
string(body)
input
1
2
3
4
5
6
7
8
9
10
11
12
func getInput ()  {
    var key string
   fmt.Scanln(&key)
 return key
}


reader := bufio.NewReader(os.Stdin)
fmt.Print("file: ")
ipt, _ := reader.ReadString('\n')
input := strings.TrimSuffix(ipt, "\n")
return input
continue
1
2
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
IO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"io/ioutil"

#save&read

func saveFile(path, content string) {
    err := ioutil.WriteFile(path, []byte(content), 0644)
    printError(err)
}

func readFile(path string) string{
    dat, err := ioutil.ReadFile(path)
    printError(err)
    return string(dat)
}



func saveLines(lines []string, path string) {
    file, err := os.Create(path)
    printError(err)
    defer file.Close()
    //file.WriteString("\xEF\xBB\xBF")
    for _, line := range lines {
        file.WriteString(line + "\n")
    }
}

import(
    "golang.org/x/text/encoding/traditionalchinese"
    "golang.org/x/text/transform"
)

"io/ioutil"
"strings"
"bytes"

func readFile(path string) []string {
    dat, err := ioutil.ReadFile(path)
    printError(err)
    var lines []string
    win16be := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM)
    utf16bom := unicode.BOMOverride(win16be.NewDecoder())
    unicodeReader := transform.NewReader(bytes.NewReader(dat), utf16bom)
    decoded, err := ioutil.ReadAll(unicodeReader)
    printError(err)

    for _, l := range strings.Split(string(dat), "\n") {
        //str, _, _ := transform.String(traditionalchinese.Big5.NewDecoder(), str2)
        //str2, _, _ := transform.String(traditionalchinese.Big5.NewEncoder(), str)
        lines = append(lines, l)
    }
    return lines
}

//win utf-16 le to utf-8
import "github.com/malexdev/utfutil"
d, _ := utfutil.ReadFile("txt", utfutil.UTF8)
c := string(d)


func appendFile(data []string, path string ) {
    f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
    printError(err)
    defer f.Close()

    for _, line := range data {
        f.WriteString(line + "\n")
    }
}

ref https://stackoverflow.com/questions/20875336/how-can-i-get-a-files-ctime-atime-mtime-and-change-them

mtime
1
2
3
4
5
6
7
8
9
10
11
func statTimes(name string) (atime, mtime, ctime time.Time, err error) {
    fi, err := os.Stat(name)
    if err != nil {
        fmt.Println(err)
    }
    mtime = fi.ModTime()
    stat := fi.Sys().(*syscall.Stat_t)
    atime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec))
    ctime = time.Unix(int64(stat.Ctim.Sec), int64(stat.Ctim.Nsec))
    return
}
stringCH
1
2
3
4
5
6
7
func checkWordsCH(words string) {
    for _, w := range words {
        if unicode.Is(unicode.Han, w) == true {

        }
    }
}
Json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
"encoding/json"
"io/ioutil"

type Employee struct {
    Name string
    Age  int
}

type List struct {
    ID []*Employee
}

func readJson(path string) []City {
    file, err := ioutil.ReadFile(path)
    printError(err)
    var reaJson []City
    err = json.Unmarshal([]byte(file), &reaJson)
    printError(err)
    return reaJson
}

func saveJson(data interface{}, path string) {
    file, err := json.MarshalIndent(data, "", " ")
    printError(err)
    _ = ioutil.WriteFile(path, file, 0644)
}
fname := "user.json"
saveJson(fname, p)
reaJson := readJson(fname)
ffmt.Puts(reaJson[0].Name)
1
2
3
4
5
6
7
8
9
10
11
12
13
var c map[string][]map[string]interface{}
var cs []string
json.Unmarshal([]byte(str), &c)

t := c["content_elements"]

for _, e := range t {
    c := e["content"]
    if c != nil {
        cs = append(cs, fmt.Sprintf("%s", c))
    }
}
return cs
Csv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"encoding/csv"
func readCsv(path string) [][]string {
    f, err := os.Open(path)
    printError(err)
    lines, err := csv.NewReader(f).ReadAll()
    return lines
}

func writeCsv(lines [][]string, path string) {
    file, err := os.Create(path)
    printError(err)
    defer file.Close()
    file.WriteString("\xEF\xBB\xBF")
    for _, line := range lines {
        file.WriteString(strings.Join(line, ", ") + "\n")
    }
}
pwd
1
2
3
4
5
6
7
import(
    "os"
    "path/filepath"
)

dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
dir, err := os.Getwd()
filepath
1
2
3
4
5
import "path/filepath"
dir, file := filepath.Split("/go/go.mod")

fmt.Println(dir)
fmt.Println(file)
fileExist
1
2
3
4
5
6
7
8
func fileExist(file string) bool {
  if _, err := os.Stat(file); err != nil {
    if os.IsNotExist(err) {
      return false
    }
  }
  return true
}
exec
1
2
cmd := exec.Command("sleep", "1")
err := cmd.Run()
 list Fo;e
1
2
3
4
5
6
7
8
9
10
11
 "path/filepath"

func listFile(root string) []string {
    var files []string
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        files = append(files, path)
        return nil
    })
    printError(err)
    return files[1:]
}
imageSize
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func getImageSize(file string) (string, string) {
    cmd = fmt.Sprintf(`identify %s`, file)
    c := runCmd(cmd)
    size := strings.Split(strings.Split(c, " ")[2], "x")
    return size[0], size[1]
}

func getImageSize(path string) (image.Image, int, int) {
    f, err := os.Open(path)
    defer f.Close()

    im, _, err := image.DecodeConfig(f)
    printError(err)

    ioReader, err := os.Open(path)
    printError(err)

    img, _, err := image.Decode(ioReader)
    printError(err)
    return img, im.Width, im.Height
}

debug

time
1
2
3
4
5
6
7
8
func debug() {
    fmt.Println("=> ", time.Now().Sub(start))
}

start := time.Now()
monthTab := []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
monthTab = []string{"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"}
mTab := []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
type class
1
2
3
4
5
6
7
import "reflect"
fmt.Println(reflect.TypeOf(doc))

import "github.com/go-ffmt/ffmt"
ffmt.P(m)  // type
ffmt.Puts
ffmt.Pjson

ignore not used
1
2
3
import (
    _ "fmt" //imported and not used
 )
skip declared
1
2
i := 1
_ = i
run time
1
2
start := time.Now()
time.Now().Sub(start)
screen
1
2
3
4
5
6
import "github.com/inancgumus/screen"

func cleanScreen() {
    screen.Clear()
    screen.MoveTopLeft()
}

time

time_format
1
2
3
4
5
time.Now().Unix()
func timeFormat() string {
    t := time.Now()
    return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", t.Year(), int(t.Month()), t.Day(), t.Hour(), t.Minute(), t.Second())
}
unix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// RFC822      = "02 Jan 06 15:04 MST"
// RFC822Z     = "02 Jan 06 15:04 -0700"
// RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
// RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
// RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700"
// RFC3339     = "2006-01-02T15:04:05Z07:00"
// RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"

func TimeTime(day int) time.Time {
    date := fmt.Sprintf("%v-%02v-%02vT00:00:00.000+08:00", NowYear, NowMonth, day)
    t, _ := time.Parse(time.RFC3339, date)
    return t
}

func getUnixTime(u time.Time) int {
    return int(u.Unix())
}

func getTimetime() time.Time{
    return  time.Unix(int64(respone.UTime), 0)
}
date cal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main

import (
    "fmt"
    "time"
)

var _ = fmt.Println

var (
    y1, m1, d1 = 2019, 9, 2
    y2, m2, d2 = 2020, 7, 20
)

func main() {
    days := getTwoDate(y1, m1, d1, y2, m2, d2)
    fmt.Println(days)

    y3, m3, d3 := getAfterDays(y1, m1, d1, days)
    fmt.Println(y3, m3, d3)
}

func unixTime(y, m, d int) int {
    date := fmt.Sprintf("%v-%.2v-%.2vT00:00:00.000Z", y, m, d)
    t, _ := time.Parse(time.RFC3339, date)
    return int(t.Unix())
}

func getTwoDate(y1, m1, d1, y2, m2, d2 int) int {
    s := unixTime(y2, m2, d2) - unixTime(y1, m1, d1)
    return s / 86400
}

func getAfterDays(y, m, d, days int) (int, int, int) {
    unix := int64(unixTime(y, m, d) + days*60*60*24 - 60*60*8)
    t := time.Unix(unix, 0)
    return t.Year(), int(t.Month()), t.Day()
}


func GetDays(year, month int) {
    days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    if (year%4 == 0 && year%100 != 0) || (year%400 == 0 && year%3200 != 0) {
        days[1] = 29
    }
    return days[month-1]
}

string

strip

strings.TrimSpace(str)

string <-> int float64
1
2
3
4
5
6
7
8
9
func to_i(s string) int {
    i, _ := strconv.Atoi(s)
    return i
}

func to_f(s string) float64 {
    fn, _ := strconv.ParseFloat(s, 64)
    return fn
}
fill_zero
1
2
3
4
5
6
func rjust(s string, n int, fill string) string {
    return strings.Repeat(fill, n-len(s)) + s
}
func ljust(s string, n int, fill string) string {
    return s + strings.Repeat(fill, n-len(s))
}
regexp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func regexMatch(str, keyword string) bool {
    match, _ := regexp.MatchString(keyword, str)
    return match
}

//scan
func regexScans(str, keyword string, is ...int) []string {
    var txts []string
    re := regexp.MustCompile(keyword)
    match := re.FindStringSubmatch(str)
    //.FindAllStringSubmatch
    fmt.Println(match)
    if len(match) > 0 {
        for _, i := range is {
            txts = append(txts, match[i])
        }
    }
    return txts
}

//replace
keyword := `"(.*)", "(.*)"`
re := regexp.MustCompile(keyword)
s := re.ReplaceAllString(e, ` $1 $2`)
chr <-> ord
1
2
3
4
5
6
func ord(s string) int {
    return int([]byte(s)[0])
}
func chr(i int) string {
    return fmt.Sprintf("%c", rune(i))
}
string reverse
1
2
3
4
5
6
7
func strReverse(str string) string {
    var comb string
    for i := len(str) - 1; i >= 0; i-- {
        comb += string(str[i])
    }
    return comb
}
index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func strIndex(str string, bstr string) int {
    arr := strings.Split(str, "")
    for i, e := range arr {
        if bstr == string(e) {
            return i
        }
    }
    return -1
}
func strIndexS(str string, bstr string) []int {
    arr := strings.Split(str, "")
    is := []int{}
    for i, e := range arr {
        if bstr == string(e) {
            is = append(is, i)
        }
    }
    return is
}
slice ch string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func sliceChString(ch string, start int, end int) string {
    var size int
    var chs = []rune(ch)
    if len(chs) > end && end > start {
        result := ""
        for _, e := range chs {
            str := string(e)
            if ord(str) > 127 {
                size += 2
            } else {
                size += 1
            }
            result += str
            if size > (end-start)*2 {
                break
            }
        }
        return result
    }
    return ch
}

#

1
2
3
4
5
6
7
8
9
10
11
12
13
func strEachSlice(str string, l int) []string {
    arr := strings.Split(str, "")
    var ar []string
    size := len(arr)
    for i := 0; i < size; i = i + l {
        j := i + l
        if j > size {
            j = size
        }
        ar = append(ar, strings.Join(arr[i:j], ""))
    }
    return ar
}

array

pop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
words = append(words[:idx], words[idx+1:]...)

func remove(words []string, idxs ...int) []string {
    include := func(idx int, idxs []int) bool {
        for _, i := range idxs {
            if i == idx {
                return true
            }
        }
        return false
    }
    var result []string
    for idx, word := range words {
        if !include(idx, idxs) {
            result = append(result, word)
        }
    }
    return result
}
eachSlice N part
1
2
3
4
5
6
7
8
9
10
11
12
13
func eachSlice(arr []string, l int) [][]string {
    var ar [][]string
    size := len(arr)
    for i := 0; i < size; i = i + l {
        j := i + l
        if j > size {
            j = size
        }
        fmt.Println(len(arr[i:j]))
        ar = append(ar, arr[i:j])
    }
    return ar
}
index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func arrIncludeIndex(arr []string, str string) int {
    for i, e := range arr {
        if str == e {
            return i
        }
    }
    return -1
}
func arrIndexS(arr []string, str string) []int {
    is := []int{}
    for i, e := range arr {
        if str == e {
            is = append(is, i)
        }
    }
    return is
}

func arrRemoveByIndex(arr []string, idx int) []string {
    arr[idx] = arr[len(arr)-1]
    return arr[:len(arr)-1]
}
bubbleSort
1
2
3
4
5
6
7
8
9
10
func bubbleSort(arr []int) {
    size := len(arr)
    for i := 0; i < size; i++ {
        for j := 1; j < size; j++ {
            if arr[j] > arr[j-1] {
                arr[j], arr[j-1] = arr[j-1], arr[j]
            }
        }
    }
}
duplicate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
type Count struct {
    id    string
    count int
}

func bubbleSort(arr []Count) {
    size := len(arr)
    for i := 0; i < size; i++ {
        for j := 1; j < size; j++ {
            if arr[j].count > arr[j-1].count {
                arr[j], arr[j-1] = arr[j-1], arr[j]
            }
        }
    }
}

func arrayDuplicate(arr []string) []Count {
    cs := make(map[string]int)
    for _, e := range arr {
        _, exist := cs[e]
        if exist {
            cs[e] += 1
        } else {
            cs[e] = 1
        }
    }
    count := []Count{}
    for cc := range cs {
        c := Count{cc, cs[cc]}
        count = append(count, c)
    }
    bubbleSort(count)
    return count
}
unique
1
2
3
func arrUnique ()  {

}
1
2
3
4
5
func arrReverse(arr []int) {
    for i := 0; i < len(arr)/2; i++ {
        arr[i], arr[len(arr)-i-1] = arr[len(arr)-i-1], arr[i]
    }
}
sub
1
2
3
4
5
6
7
8
9
func arrSub(arr1 []int, arr2 []int) []int {
    r := []int{}
    for _, e1 := range arr1 {
        if !arrInclude(arr2, e1) {
            r = append(r, e1)
        }
    }
    return r
}
include
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func arrInclude(arr []int, str int) bool {
    for _, e := range arr {
        if str == e {
            return true
        }
    }
    return false
}
func arr1InclueArr2(arr1 []int, arr2 []int) bool {
    for _, e := range arr1 {
        if !reflect.DeepEqual(e, arr2) {
            return false
        }

    }
    return true
}
Equal

reflect.DeepEqual(a, b)

compare
1
2
3
4
5
6
7
8
9
10
11
12
13
func arrCompare(a1, a2 []string) ([]string, []string, []string) {
    var d1, same []string
    for _, e1 := range a1 {
        idx := arrIncludeIndex(a2, e1)
        if idx != -1 {
            same = append(same, e1)
            a2 = arrRemoveByIndex(a2, idx)
        } else {
            d1 = append(d1, e1)
        }
    }
    return d1, a2, same
}

math

power
1
2
3
4
5
6
7
8
9
"math"
math.Pow(2, 5)

func pow(n, p int) int {
    if p == 1 {
        return n
    }
    return n * pow(n, p-1)
}
bit
1
2
3
4
n, err := strconv.ParseUint(val, 16, 32)
if err != nil {
    panic(err)
}
d
1
2
math.Ceil(0.2)
math.Floor(0.2)
even odd
1
2
3
4
5
6
func evenBool(i int) bool {
    return i%2 == 0
}
func oddBool(i int) bool {
    return i%2 != 0
}
toHex
1
2
3
func toHex(i int) string {
    return fmt.Sprintf("%x", i)
}
rand
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"math/rand"

func randNumStr(min, max float64) string {
    rand.Seed(time.Now().UnixNano())
    n := min + rand.Float64()*(max-min)
    return fmt.Sprintf("%.1f", n)
}

func randNumInt(min, max int) int {
    rand.Seed(time.Now().UnixNano())
    return min + rand.Intn(max-min+1)
}

func randChr(array []string) string {
    return array[rand.Intn(len(array))]
}

image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func rgbtoHex(i uint32) string {
    hex := fmt.Sprintf("%x", i)
    return hex[0:2]
}

func rgbaToPixel(r uint32, g uint32, b uint32, a uint32) string {
    return rgbtoHex(r) + rgbtoHex(g) + rgbtoHex(b)
}
img, _, err := image.Decode(file)

bounds := img.Bounds()
width, height := bounds.Max.X, bounds.Max.Y

pixel := rgbaToPixel(img.At(x, y).RGBA())


  f, err = os.Open(input)
        img, _, err = image.Decode(f)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
img = image.NewRGBA(image.Rect(0, 0, width, width))

gin

soup
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"github.com/anaskhan96/soup"
"fmt"
"io/ioutil"
"net/http"
"os"
"runtime"

doc := getDoc(url)

func getDoc(url string) soup.Root {
    req, err := http.NewRequest("GET", url, nil)
    printError(err)
    res, err := http.DefaultClient.Do(req)
    printError(err)
    body, err := ioutil.ReadAll(res.Body)
    printError(err)
    resp := string(body)
    //save(resp, "/tmp/log.html")
    return soup.HTMLParse(resp)
}

/*func getDoc(url string) soup.Root {
    tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
    client := &http.Client{
        Timeout:   15 * time.Second,
        Transport: tr,
    }
    req, err := http.NewRequest("GET", url, nil)
    req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
    printError(err)
    resp, err := client.Do(req)
    printError(err)

    body, err := ioutil.ReadAll(resp.Body)
    printError(err)
    return soup.HTMLParse(string(body))
}*/


"github.com/sclevine/agouti"

func openBrowser(screenX, screenY int) (*agouti.Page, *agouti.WebDriver) {
    driver := agouti.ChromeDriver(
        agouti.ChromeOptions("args", []string{
            "--headless",
            "--disable-gpu",
            "--disable-notifications",
            //"--no-sandbox",
            fmt.Sprintf("--window-size=%v,%v", screenX, screenY),
        }),
    )
    err := driver.Start()
    printError(err)
    page, err := driver.NewPage()
    printError(err)
    return page, driver
}

func main (){
    page, driver := openBrowser()
    defer driver.Stop()
    page.Navigate(url)
    resp, _ := page.HTML()
    doc := soup.HTMLParse(resp)

}

func runJs(page *agouti.Page) string{
    js := `window.scrollTo(0,window.scrollY+window.innerHeight*.9);`
    var text string
    page.RunScript(js, nil, &text)
    return text
}

func sendKeys(page *agouti.Page, key string) {
    var k string
    switch key {
    case "Home":
        k = "\uE011"
    case "pageDown":
        k = "\uE00F"
    }
    page.Find("html").SendKeys(k)

 // NULL        = "\uE000", CANCEL     = "\uE001", HELP     = "\uE002"
 // BACK_SPACE  = "\uE003", TAB        = "\uE004", CLEAR    = "\uE005"
 // RETURN      = "\uE006", ENTER      = "\uE007", SHIFT    = "\uE008"
 // CONTROL     = "\uE009", ALT        = "\uE00A", PAUSE    = "\uE00B"
 // ESCAPE      = "\uE00C", SPACE      = "\uE00D", PAGE_UP  = "\uE00E"
 // PAGE_DOWN   = "\uE00F", END        = "\uE010", HOME     = "\uE011"
 // LEFT        = "\uE012", ARROW_LEFT = "\uE012", ARROW_UP = "\uE013"
 // ARROW_RIGHT = "\uE014", ARROW_DOWN = "\uE015", INSERT   = "\uE016"
 // DELETE      = "\uE017", SEMICOLON  = "\uE018", EQUALS   = "\uE019"
 // NUMPAD0     = "\uE01A", NUMPAD1    = "\uE01B", NUMPAD2  = "\uE01C"
 // NUMPAD3     = "\uE01D", NUMPAD4    = "\uE01E", NUMPAD5  = "\uE01F"
 // NUMPAD6     = "\uE020", NUMPAD7    = "\uE021", NUMPAD8  = "\uE022"
 // NUMPAD9     = "\uE023", MULTIPLY   = "\uE024", ADD      = "\uE025"
 // SEPARATOR   = "\uE026", SUBTRACT   = "\uE027", DECIMAL  = "\uE028"
 // DIVIDE      = "\uE029", F1         = "\uE031", F2       = "\uE032"
 // F3          = "\uE033", F4         = "\uE034", F5       = "\uE035"
 // F6          = "\uE036", F7         = "\uE037", F8       = "\uE038"
 // F9          = "\uE039", F10        = "\uE03A", F11      = "\uE03B"
 // F12         = "\uE03C", META       = "\uE03D", COMMAND  = "\uE03D"


}
table
1
2
3
4
5
6
7
8
9
10
data := [][]string
info := doc.Find("table", "class", "auto-style4")
table := info.FindAll("tr")
for _, tr := range table {
    var tmp []string
    for _, td := range tr.FindAll("td", "class", "auto-style5") {
        tmp = append(tmp, td)
    }
    data = append(data, tmp)
}
br
1
2
3
4
5
6
data := [][]string
for _, t := range td.Children() {
    if t.NodeValue != "br" {
        data = append(data, t.NodeValue)
    }
}
nbsp
1
2
3
4
5
6
7
8
9
10
11
12
13
func removeNbsp(s string) string {
    return strings.Replace(s, "\u00A0", "", -1)
}

func removeNbsp(s string) string {
    var txt string
    for _, b := range []byte(s) {
        if b != 194 && b != 160 {
            txt += string(b)
        }
    }
    return txt
}
excel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func readXlsx(path string) [][]string {
    f, err := excelize.OpenFile(path)
    printError(err)
    var datas [][]string
    sheet1 := f.GetSheetMap()[1]
    rows := f.GetRows(sheet1)
    for _, row := range rows {
        var data []string
        for _, cell := range row {
            cell = strings.TrimSpace(cell)
            data = append(data, cell)
        }
        datas = append(datas, data)
    }
    return datas
}

func writeXlsx(path string, data [][]string) {
    f := excelize.NewFile()
    index := f.NewSheet("Sheet1")
    for i, row := range data {
        for j, cell := range row {
            c := fmt.Sprintf("%c%v", rune(j+65), i+1)
            f.SetCellValue("Sheet1", c, cell)
        }
    }
    f.SetActiveSheet(index)
    err := f.SaveAs(path)
    printError(err)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func moniterExit() {
    c := make(chan os.Signal)
    signal.Notify(c)

    go func() {
        for s := range c {
            switch s {
            case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM:
                fmt.Println(s)
                ExitFunc()
            default:
                fmt.Println(s)
            }
        }
    }()
}
image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"github.com/fogleman/gg"

img, err := gg.LoadImage(gfiImage)
printError(err)
s := img.Bounds().Size()
width, height := s.X, s.Y

dc := gg.NewContext(width, height)
dc.SetRGB(0, 0, 0)
dc.DrawImage(img, 0, 0)

addText(dc, timeFormat(), 45, 48, 40)
dc.SavePNG(imageFakeSend)


func addText(dc *gg.Context, str string, x, y, s float64) {
    dc.LoadFontFace("/data/font/msjh.ttc", s)
    dc.SetRGB(150, 150, 150)
    dc.DrawStringAnchored(str, x, y, 0, 0)
}

robotgo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"github.com/go-vgo/robotgo"

robotgo.MoveMouseSmooth(21, 297, 0.5, 1.0)
robotgo.MouseClick("left", true)
robotgo.KeyTap("o", "ctrl")
robotgo.KeyTap(`r`, `command`)

func findpic(pic string, tryTime int, try ...int) (int, int) {
    cs := robotgo.CaptureScreen()
    sx, sy := robotgo.FindPic(pic, cs, 0.1)
    if len(try) == 0 {
        try = append(try, 0)
    }
    last := try[len(try)-1]
    if (sx != -1 && sy != -1) || last > tryTime {
        return sx, sy
    }
    return findpic(pic, tryTime, last+1)
}

mp3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"

func mp3Play(path string, sec ...int) {
    f, err := os.Open(path)
    printError(err)
    streamer, format, err := mp3.Decode(f)
    printError(err)
    defer streamer.Close()
    speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
    speaker.Play(streamer)
    if len(sec) > 0 {
        sleep(sec[0])
    } else {
        sleep(1000)
    }
}

win UI

https://github.com/harry1453/go-common-file-dialog

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"github.com/harry1453/go-common-file-dialog/cfd"
"github.com/harry1453/go-common-file-dialog/cfdutil"

func pickFile(title string, ffs ...string) string {
    var fileFilters []cfd.FileFilter
    for _, f := range ffs {
        fileFilters = append(fileFilters, cfd.FileFilter{f, f})
    }
    all := "*.*"
    fileFilters = append(fileFilters, cfd.FileFilter{all, all})
    selectedFileName := ffs[0]
    defaultExtension := strings.Split(selectedFileName, ".")[0]

    result, err := cfdutil.ShowOpenFileDialog(cfd.DialogConfig{
        Title:       title,
        Role:        "OpenFileExample",
        FileFilters: fileFilters,

        SelectedFileFilterIndex: 0,
        FileName:                selectedFileName,
        DefaultExtension:        defaultExtension,
    })
    if err != nil && err.Error() == "cancelled by user" {
        fmt.Println("Dialog was cancelled by the user.")
        os.Exit(0)
    }
    return result
}

func pickFolder() string {
    pickFolderDialog, err := cfd.NewSelectFolderDialog(cfd.DialogConfig{
        Title: "PickFolder",
        Role:  "PickFolderExample",
        Folder: `Z:\`,
    })
    printError(err)
    err = pickFolderDialog.Show()
    printError(err)
    result, err := pickFolderDialog.GetResult()
  if err != nil && err.Error() == "cancelled by user" {
        fmt.Println("Dialog was cancelled by the user.")
        os.Exit(0)
    }
    return result
}

Msgbox

1
2
3
4
5
6
7
8
9
10
"syscall"


func MessageBox(title, caption string) {
    syscall.NewLazyDLL("user32.dll").NewProc("MessageBoxW").Call(
        uintptr(0),
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(caption))),
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(title))),
        uintptr(0))
}

barCode

1
2
3
4
5
6
7
8
9
10
11
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/oned"

func genCode128(id string) {
    enc := oned.NewCode128Writer()
    img, _ := enc.Encode(id, gozxing.BarcodeFormat_CODE_128, 250, 50, nil)
    path := genPath(id)
    file, _ := os.Create(path)
    defer file.Close()
    png.Encode(file, img)
}

ssh

1
2
3
4
5
6
7
8
9
10
11
12
"github.com/sfreiberg/simplessh"

client, err := simplessh.ConnectWithKeyFile("192.168.0.201:22", "icps", "/home/icps/.ssh/192.168.0.201")
defer client.Close()
printError(err)

output, err := client.Exec("uptime")
printError(err)
fmt.Println(string(output))

err = client.Upload("/tmdp/weatherTmp", "/tmp/123")
printError(err)

encoding big5

1
2
3
4
5
6
7
8
9
10
"golang.org/x/text/transform"
"bytes"
"golang.org/x/text/encoding/traditionalchinese"
"io/ioutil"

func big5utf8(str string) string {
    reader := transform.NewReader(bytes.NewReader([]byte(str)), traditionalchinese.Big5.NewDecoder())
    out, _ := ioutil.ReadAll(reader)
    return string(out)
}