小编hen*_*dry的帖子

如何grep博客中的URL?

我正在编写一个脚本来从我的博客帖子中获取URL并运行curl -I它们以便我可以检查它们是否仍然很好.但是我在编写grep模式时遇到了麻烦.

<p><a href="http://example.com/fujipol/2004/may/5/16:10:47/400x345">foobar</a></p>
Run Code Online (Sandbox Code Playgroud)

所以我想在这里http://example.com/fujipol/2004/may/5/16:10:47/400x345.

或者在降价时:

[Example markdown link](https://example.com)
Run Code Online (Sandbox Code Playgroud)

https://example.com

<http://example.com/?foo=bar>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我需要 http://example.com/?foo=bar

grep

2
推荐指数
1
解决办法
6898
查看次数

Awk打印匹配精确的列内容

echo -e "55 11\n25 11.0" | awk '$2 ~ /11/{print $1}'
Run Code Online (Sandbox Code Playgroud)

我只想匹配"11",而不是"11.0"的值25.任何提示?

awk

2
推荐指数
1
解决办法
5285
查看次数

在http.FileServer上记录404

我正在dirPath使用jpeg图像http.FileServer:

http.Handle("/o/", http.StripPrefix(
    path.Join("/o", dirPath), http.FileServer(http.Dir(dirPath))))
Run Code Online (Sandbox Code Playgroud)

我不明白的是如何在对不存在的文件发出请求时进行记录.我可以看到当我使用浏览器发出请求时找不到http.FileServer返回的404页面,但是在服务器控制台上没有找到.

http go http-status-code-404

2
推荐指数
1
解决办法
886
查看次数

如何将参数传递给 page.evaluate?

我希望我的结果是一个函数,它在浏览器上下文中运行,表现得像一个函数。所以我可以要求它获取不同的资源。然而这个p论点是行不通的。为什么,我该如何解决?

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({args: ['--no-sandbox'], headless: false})
  const page = await browser.newPage()
  await page.goto('https://hendry.iki.fi')

  const p = '/about'

  const result = await page.evaluate((p) => {
    return fetch(p)
    .then((response) => {
      if (response.ok) {
        return response.text()
      }
    })
  })

  console.log(result)

  await browser.close()
})()
Run Code Online (Sandbox Code Playgroud)

javascript async-await puppeteer

1
推荐指数
1
解决办法
2333
查看次数

在一个函数中定义的全局变量不会在另一个函数中定义

经过一些阅读,我认为我需要这个TestMain(m *testing.M)构造来设置我的数据库.但是,在运行测试时,db总是为零.我该如何解决?

var db *sql.DB

func TestMain(m *testing.M) {

        db, err := sql.Open("mysql", os.Getenv("DSN"))
        if err != nil {
                log.Fatal("error opening database")
        }

        defer db.Close()
        log.Printf("here testing with %v", db)
        code := m.Run()
        log.Printf("finished test")
        os.Exit(code)

}

func Test_getRole(t *testing.T) {
        if db == nil {
                t.Fatalf("db is nil")
        }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

2018/05/02 19:10:14 here testing with &{{bugzilla:SECRET@tcp(example.com:3306)/bugzilla?multiStatements=true 0x7aba40} 0 {0 0} [] map[] 0 0 0xc42001e180 0xc4200740c0 false map[] map[] 0 0 0 <nil> 0x4e9850} …
Run Code Online (Sandbox Code Playgroud)

mysql testing go

1
推荐指数
1
解决办法
59
查看次数

我如何倒带 io.ReadCloser

我总是因为阅读io.ReadCloser而忘记我以前读过它而陷入困境,当我再次阅读它时,我得到一个空的有效负载。我希望对我的愚蠢进行一些检查。尽管如此,我认为我可以使用 TeeReader,但它无法满足我的期望:

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        buf := &bytes.Buffer{}
        tee := io.TeeReader(r.Body, buf)
        body, err := ioutil.ReadAll(tee)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        log.Println("body", string(body))
        payload, err := httputil.DumpRequest(r, true)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        log.Println("dump request", string(payload))
        w.WriteHeader(http.StatusOK)
    })
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Run Code Online (Sandbox Code Playgroud)

我的“转储请求”日志行中缺少正文。

即当我跑步时 curl -i -X POST --data '{"username":"xyz","password":"xyz"}' http://localhost:8080

我想要完整的原始请求:

2019/01/14 11:09:50 dump request POST / HTTP/1.1
Host: localhost:8080
Accept: */* …
Run Code Online (Sandbox Code Playgroud)

http go

1
推荐指数
1
解决办法
4755
查看次数

Go 的会话中间件?

func indexHandler(w http.ResponseWriter, req *http.Request) {
    session, err := store.Get(req, sessionName)
    if err != nil {
        log.WithError(err).Error("bad session")
        http.SetCookie(w, &http.Cookie{Name: sessionName, MaxAge: -1, Path: "/"})
    }
    err = views.ExecuteTemplate(w, "index.html", session.Values)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}
Run Code Online (Sandbox Code Playgroud)

我所有的处理程序都使用Gorilla 会话。如何避免store.Get在我的每个处理程序中调用会话,即代码重复?

另一个问题是,是否有更好的方法来为模板提供会话值,而不是一种明确的方式,例如:

err = views.ExecuteTemplate(w, "index.html",
    struct {
        Session map[interface{}]interface{},
        ...other handler specific data for the template
    }{
        session.Values,
        ...
    })
Run Code Online (Sandbox Code Playgroud)

代码示例源自https://github.com/kaihendry/internal-google-login

session go gorilla

1
推荐指数
1
解决办法
1228
查看次数

gnuplot 中的水平条形图

当谷歌搜索“水平 gnuplot 条形图”时,我能找到的第一个结果http://www.phyast.pitt.edu/~zov1/gnuplot/html/histogram.html建议旋转(!)最终的条形图,这看起来相当巴洛克. 尽管如此,我尝试了这种方法,但标签被切断了。

第一次尝试使用 gnuplot 5.2 中的水平条形图

reset
$heights << EOD
dad                     181
mom                     170
son                     100
daughter        60
EOD

set yrange [0:*]      # start at zero, find max from the data
set boxwidth 0.5      # use a fixed width for boxes
unset key             # turn off all titles
set style fill solid  # solid color boxes

set colors podo

set xtic rotate by 90 scale 0
unset ytics
set y2tics rotate by 90

plot '$heights' using 0:2:($0+1):xtic(1) with boxes lc …
Run Code Online (Sandbox Code Playgroud)

gnuplot bar-chart

1
推荐指数
1
解决办法
868
查看次数

测试golang的Web应用程序查询参数的最佳做法

在两个必需参数的简单情况下,有四个可能的测试用例IIUC:

  1. 都是空的
  2. 第一组,但第二组
  3. 第二组但不是第一组
  4. 都设置

什么是最佳实践,请对这四个案例进行测试?

因为即使在Golang中测试第一个和最后一个案例也很冗长:

func TestGoodParameter(t *testing.T) {

        req, _ := http.NewRequest("GET", "/", nil)

        q := req.URL.Query()
        q.Add("first", "foo")
        q.Add("second", "bar")
        req.URL.RawQuery = q.Encode()

        rec := httptest.NewRecorder()
        root(rec, req)
        res := rec.Result()

        if res.StatusCode != http.StatusOK {
                t.Errorf("got %v, expected %v", res.StatusCode, http.StatusOK)
        }

}

func TestBadParameter(t *testing.T) {

        req, _ := http.NewRequest("GET", "/", nil)

        rec := httptest.NewRecorder()
        root(rec, req)
        res := rec.Result()

        if res.StatusCode != http.StatusBadRequest {
                t.Errorf("got %v, expected %v", res.StatusCode, http.StatusBadRequest)
        }

}
Run Code Online (Sandbox Code Playgroud)

还是我在这里缺少一些技巧?当说有五个参数(其中两个是可选参数)时,显然变得更加复杂!

testing go

0
推荐指数
1
解决办法
1291
查看次数

Pandas read_csv 在第一列失败

我有一些来自https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_daily_reports/ 的数据,如下所示:

Singapore,2020-04-17 23:30:32,1.2833,103.8333,5050,11,708,4331,Singapore
Singapore,2020-06-12 05:09:52,1.2833,103.8333,39387,25,27286,12076,Singapore,673.2425774010173,0.06347271942519106
Run Code Online (Sandbox Code Playgroud)

当我用熊猫读到它时,sg = pd.read_csv("singapore.csv", names=["Country_Region", "Last_Update", "Lat", "Long", "Confirmed", "Deaths","Recovered","Active"])它看起来很奇怪:

熊猫输出

看起来 CSV 没有正确读取......为什么?

奖励:如何“清理”已将列添加到数据结构中的数据,例如此处此处之间发生的情况。

https://github.com/kaihendry/covid19-sg/blob/master/pandas.ipynb

python csv pandas

0
推荐指数
1
解决办法
64
查看次数