0%

go defer

go defer 命名和匿名返回值函数中的返回结果不同

阅读全文 »

pprof

安装生成火焰图工具

go get github.com/uber/go-torch

下载graphviz

MacOS

brew install graphviz

Ubuntu

sudo apt-get install graphviz

Centos

yum install graphviz

阅读全文 »

js 时间戳格式化

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
// @param value 微秒
// @param fmt "yyyy-MM-dd hh:mm:ss" | yyyy/MM/dd hh:mm:ss
function formatTimestamp(value, fmt) {
let getDate = new Date(value)
let o = {
'M+': getDate.getMonth() + 1,
'd+': getDate.getDate(),
'h+': getDate.getHours(),
'm+': getDate.getMinutes(),
's+': getDate.getSeconds(),
'q+': Math.floor((getDate.getMonth() + 3) / 3),
'S': getDate.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt
}

r = formatTimestamp(1605780000 * 1000, "yyyy-MM-dd hh:mm:ss")
console.log(r)

CSS

em

em作为font-size的单位时,其代表父元素的字体大小,em作为其他属性单位时,代表自身字体大小——MDN

rem

em作为font-size的单位时,其代表父元素的字体大小,em作为其他属性单位时,代表自身字体大小——MDN

rem取值分为两种情况,设置在根元素时和非根元素时,举个例子

1
2
3
4
5
/* 作用于根元素,相对于原始大小(16px),所以html的font-size为32px*/
html {font-size: 2rem}

/* 作用于非根元素,相对于根元素字体大小,所以为64px */
p {font-size: 2rem}
阅读全文 »

Elasticsearch

新版本ES中一个 Index 只能有一种 doc_type

存储时document字段类型不能变化 除非删掉整个索引 重新创建document

python elasticsearch

python pip install

1
pip install elasticsearch
阅读全文 »

图数据库

什么是图数据库

图数据库源起欧拉和图理论,也可称为面向/基于图的数据库,对应的英文是Graph Database。图数据库的基本含义是以“图”这种数据结构存储和查询数据,而不是存储图片的数据库。它的数据模型主要是以节点和关系(边)来体现,也可处理键值对。它的优点是快速解决复杂的关系问题

图数据库名字的由来其实与其在底层的存储方式有关,Neo4j底层会以图的方式把用户定义的节点以及关系存储起来,通过这种方式,可是高效的实现从某个节点开始,通过节点与节点间关系,找出两个节点间的联系。

阅读全文 »

database

settings.py

1
2
3
4
5
6
7
8
9
10
11
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'django_mysql', # 数据库名
'USER': 'root', # 账号
'PASSWORD': 'root', # 密码
'HOST': '127.0.0.1', # HOST
'POST': 3306, # 端口

}
}

如果报错
ImproperlyConfigured: mysqlclient 1.3.13 or newer is required

pip install mysqlclient

django ImageField 存储图片

ref

matplotlib 图片存储 ImageField

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
from django.core.files.images import ImageFile
from io import BytesIO
import matplotlib.pyplot as plt

# plt 图表
plt.figure(figsize=(12, 6))
plt.title('Actual vs predicted')
plt.scatter(x, y)
plt.plot(x, y_pred, color='black')

# 转换图片
sio = BytesIO()
plt.savefig(sio, format='png')
plt.close() # 记得关闭,不然画出来的图是重复的
img = ImageFile(sio, name="{}_train.png".format(name))

# django model 存储
class model(models.Model):
img_field = models.ImageField(upload_to='img')

m = model(img_field=img)
m.save()

# settings.py
MEDIA_ROOT = 'media/'

# urls.py
from django.urls import path, include, re_path
from django.conf import settings

from django.views.static import serve

urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}),
]

根据项目依赖生成 requirements.txt

安装 pipreqs

pip install pipreqs

在当前目录生成

pipreqs . –encoding=utf8 –force

注意 –encoding=utf8 为使用utf8编码,不然可能会报UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xae in position 406: illegal multibyte sequence 的错误。

–force 强制执行,当 生成目录下的requirements.txt存在时覆盖。

位运算

1
2
3
4
5
6
7
8
9
10
11
package main

func main() {
println(isOdd(1))
println(isOdd(2))
}

// and运算通常用于二进制的取位操作,例如一个数 and 1的结果就是取二进制的最末位。这可以用来判断一个整数的奇偶,二进制的最末位为0表示该数为偶数,最末位为1表示该数为奇数。
func isOdd(i int) bool {
return i&1==1
}

golang json.Marshal() html特殊字符会转义 解决方法

go 语言提供了 JSON 的编解码包,JSON 字符串作为参数值传输时发现,json.Marshal 生成 JSON 特殊字符 <、>、&会被转义。

1
2
3
4
5
6
7
8
9
10
11
12
type Test struct {
Content string
}

func main() {
t := new(Test)
t.Content = "http://www.baidu.com?id=123&test=1"
jsonByte, _ := json.Marshal(t)
fmt.Println(string(jsonByte))
}
{"Content":"http://www.baidu.com?id=123\u0026test=1"}
Process finished with exit code 0

GoDoc 描述

String values encode as JSON strings coerced to valid UTF-8,
replacing invalid bytes with the Unicode replacement rune.
The angle brackets “<” and “>” are escaped to “\u003c” and “\u003e”
to keep some browsers from misinterpreting JSON output as HTML.
Ampersand “&” is also escaped to “\u0026” for the same reason.
This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.

json.Marshal 默认 escapeHtml 为 true,会转义 <、>、&

1
2
3
4
5
6
7
8
func Marshal(v interface{}) ([]byte, error) {
e := &encodeState{}
err := e.marshal(v, encOpts{escapeHTML: true})
if err != nil {
return nil, err
}
return e.Bytes(), nil
}

解决方法

直接替换

1
2
3
content = strings.Replace(content, "\\u003c", "<", -1)
content = strings.Replace(content, "\\u003e", ">", -1)
content = strings.Replace(content, "\\u0026", "&", -1)

SetEscapeHTML(false)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type Test struct {
Content string
}

func main() {
t := new(Test)
t.Content = "http://www.baidu.com?id=123&test=1"
bf := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(bf)
jsonEncoder.SetEscapeHTML(false)
jsonEncoder.Encode(t)
fmt.Println(bf.String())
}
{"Content":"http://www.baidu.com?id=123&test=1"}
Process finished with exit code 0

a generic solution for any struct

1
2
3
4
5
6
7
func JSONMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}

terraform init

1
terraform init -plugin-dir=/terraform/providers

plugin-dir 参数 本地获取已有provider

1
terraform init -no-color

不显示颜色

golang
exec.Command(commandName, params…)
stdout, err := cmd.Stdout
不加 -no-color
stdout 显示颜色信息代码

terraform apply