3 minute read

Tags: , , , , , , , ,

SQL


Postgres insert date

  • current_timestamp
    • 在時間內加時間
      • current_timestamp + interval ‘1 day’
    • ex:
         insert into table (create_time, estimated_time)
         value (current_timestamp, current_timestamp + interval '1 day')
    

sql 查看 time different

  SQL Server and Sybase PostgreSQL
Years DATEDIFF(yy, start, end) DATE_PART(‘year’, end) - DATE_PART(‘year’, start)
Months DATEDIFF(mm, start, end) years_diff * 12 + (DATE_PART(‘month’, end) - DATE_PART(‘month’, start))
Days DATEDIFF(dd, start, end) DATE_PART(‘day’, end - start)
Weeks DATEDIFF(wk, start, end) TRUNC(DATE_PART(‘day’, end - start)/7)
Hours DATEDIFF(hh, start, end) days_diff * 24 + DATE_PART(‘hour’, end - start )
Minutes DATEDIFF(mi, start, end) hours_diff * 60 + DATE_PART(‘minute’, end - start )
Seconds DATEDIFF(ss, start, end) minutes_diff * 60 + DATE_PART(‘minute’, end - start )

postgres get time with NOW()

select * from table t 
where t.start_time between ( NOW() - interval '50 day' ) and NOW ();

Sql 找重複 item

select t.item
from table t 
group by t.item
having count(*) > 1;

Go


Check string in []string

input := []string{"bird", "apple", "ocean", "fork", "anchor"}
sort.Strings(input)

fmt.Println(contains(input, "apple")) // true
fmt.Println(contains(input, "grow"))  // false

...

func contains(s []string, searchterm string) bool {
    i := sort.SearchStrings(s, searchterm)
    return i < len(s) && s[i] == searchterm
}

Time Caculation

// Common durations. There is no definition for units of Day or larger
// to avoid confusion across daylight savings time zone transitions.
//
// To count the number of units in a Duration, divide:
//	second := time.Second
//	fmt.Print(int64(second/time.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
//	seconds := 10
//	fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
//
const (
	Nanosecond  Duration = 1
	Microsecond          = 1000 * Nanosecond
	Millisecond          = 1000 * Microsecond
	Second               = 1000 * Millisecond
	Minute               = 60 * Second
	Hour                 = 60 * Minute
)
 endTime = startTime.Add(time.Duration( (value.StdTp + value.StdTs*value.Qty)*60)*time.Second)

Go 寶哥 考試

Go: Compiled Language

  • Go 迴圈

      for {...}
    	
      for true {...}
    
  • Go example

package main

import "fmt"

func main(){
result := sum(1, 2)
fmt.Println(result)
}

func sum(x, y int) (res int) {
  res = x, y
  return
}

--> 3
  • Go 每支原始檔案 .go

    • 含有 package 宣告
  • Go

      package main
    	
      import _ github.comlib/pq
    	
      import "fmt"
    
    • 執行該 package 的 init 方法
  • Go Modules 最主要的用途為何

    • package 相依去中心化
  • Go get

    • go get github.com/gorilla/mux@>v1.7.2

    • 找到的可能版本:v1.7.3

  • Go 檢查程式碼是否有錯誤 (例如是否含有 unreachable code 等問題)

    • go vet
  • Go 列出 fmt 使用方式

    • go help fmt
  • Go 會列出什麼結果

      package main
    	
      import "fmt"
    	
      func main() {
      ch := make(chan int)
      ch <- 10
      i :=  <- ch
      fmt.Prinln(i)
      }
    
    • fatal error: all goroutlines are asleep - deadlock!
  • Go 會列出什麼結果

      package main
    	
      import {
         "fmt"
         "time"
      }
    	
      func main(){
      ch := make(chan int)
      go func() {
      time.Sleep(1 * time.Second)
      ch <- 10
      }()
      i := <- ch
      fmt.Println(i)
      }
    
    • 10
  • Go 結果

     package main
       
     import (
       "fmt"
     )
       
     func main() {
     i, j := 99, 99
     setWithPointer(&i)
     setWithValue(j)
     fmt.Println(i, j)
     }
       
     func setWithPinter(i *int){
        *i = 100
     }
       
     func setWithValue(i int){
        i = 100
     }
    
    • i = 100, j = 99
  • Go 執行後的輸出順序

      package main
        
      import ( 
      "fmt" 
      )
        
      func main() {
      defer fmt.Print("defer 1, ")
      fmt.Print("hello, ")
      defer fmt.Print("defer 2, ")
      }
    
    • hello, defer 2, defer 1,

Go xorm showSql

// ShowSQL show SQL statement or not on logger if log level is great than INFO
func (engine *Engine) ShowSQL(show ...bool) {
	engine.logger.ShowSQL(show...)
	if len(show) == 0 {
		engine.showSQL = true
	} else {
		engine.showSQL = show[0]
	}
}

go 剪字元

  • queryStr[:len(queryStr)-3]

  • https://www.rosettacode.org/wiki/Substring/Top_and_tail#Go

Go xorm 自組合 query string

  • builder.Eq
    • type Eq map[string]interface{}
builder.Eq()
	
err = session.Select(selectSql).
		Limit(limit, startIndex).
		Where(builder.Eq(queryStr)).
		Find(&modal)

Golang switch

func main() {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

Go struct assign

Docker


Docker Ignore

  • .dockerignore
# dependencies
/node_modules
/.pnp
.pnp.js
.git
.ipynb_checkpoints/*
/notebooks/*
/unused/*
Dockerfile
.DS_Store
.gitignore
README.md
env.*
/devops/*

# To prevent storing dev/temporary container data
*.csv
/tmp/*

Docker toolbox

  • 看 docker toolbox run 起來的 ip 位置
    • docker-machine ip

Git


  • show git graph
    • git log –all –graph –decorate

Python


pandas read json file

import pandas as pd
from pandas.io.json import json_normalize
import json
import os
with open("./jobs.json", "rb") as json_data:
    data = json.load(json_data)
df = pd.DataFrame.from_dict(data, orient='index')

Javascript


Date add date

// Create new Date instance
var date = new Date()

// Add a day
date.setDate(date.getDate() + 1)

e2e cypress