I want to get my leetcode ranking, But I know about html and JavaScript just a little. After a lot of try, I get this output.
aQuaYi's ranking is Ranking: {[{ pc.ranking }]}
source is
package main
import (
"fmt"
"log"
"github.com/PuerkitoBio/goquery"
)
func showRanking(username string) {
URL := fmt.Sprintf("https://leetcode.com/%s", username)
doc, err := goquery.NewDocument(URL)
if err != nil {
log.Fatal(err)
}
ranking, _ := doc.Find("div.panel-body").Find("span.ranking").Attr("data-content")
fmt.Printf("%s's ranking is %v", username, ranking)
}
func main() {
showRanking("aQuaYi")
}
Please help me finish this code, Thank you very much.
func getRanking(username string) string {
URL := fmt.Sprintf("https://leetcode.com/%s/", username)
fmt.Println(URL)
data := getRaw(URL) // or your way to get raw html page down
str := string(data)
i := strings.Index(str, "ng-init")
j := i + strings.Index(str[i:], "ng-cloak")
str = str[i:j]
i = strings.Index(str, "(")
j = strings.Index(str, ")")
str = str[i:j]
strs := strings.Split(str, ",")
ans := strs[5]
i = strings.Index(ans, "'")
j = 2 + strings.Index(ans[2:], "'")
return ans[i+1 : j]
}
Related
I'm using below code for adding two rows in table
package main
import (
"database/sql"
"fmt"
"log"
"strconv"
_ "github.com/mattn/go-sqlite3"
)
func main() {
database, _ := sql.Open("sqlite3", "./nraboy.db")
statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT)")
statement.Exec()
statement, _ = database.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
statement.Exec("Nic", "Raboy")
statement, _ = database.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
statement.Exec("Tom", "Hardy")
_, err := statement.Exec("delete from people where id = 1")
if err != nil {
log.Fatal(err)
}
rows, _ := database.Query("SELECT id, firstname, lastname FROM people")
var id int
var firstname string
var lastname string
for rows.Next() {
rows.Scan(&id, &firstname, &lastname)
fmt.Println(strconv.Itoa(id) + ": " + firstname + " " + lastname)
}
}
but when I'm adding _, err := statement.Exec("delete from people where id = 1") for removing one of row I get following error:
2021/07/09 16:21:07 sql: expected 2 arguments, got 1
exit status 1
How to delete row in table ?
It looks like you forgot to call statement, _ = database.Prepare("delete from people where id = 1") for the delete command. When you are calling statement.Exec("delete from people where id = 1") the statement that was previously prepared is still in effect, and it expects two arguments (firstname, lastname).
I have written a go programme to query issues in github repository "golang:go".
The http.Get() responds with status "200 OK".
I then query for issues created in last 3 months and the http.Get() returns "422 Unprocessable Entity". Below is the programme
import(
"fmt"
"time"
"net/http"
"net/url"
)
func main() {
var ret error
var str string
q:=url.QueryEscape("repo:golang/go")
fmt.Println("q:", q)
urlStr := "https://api.github.com/search/issues" +"?q=" + q
fmt.Println("urlStr:", urlStr)
resp, ret:= http.Get(urlStr)
fmt.Println("ret :", ret, "resp.status :", resp.Status)
timeStr := "created:"
to := time.Now()
from := to.AddDate(0, -3, 0)
str = to.Format("2006-01-02")
timeStr = timeStr + str + ".."
fmt.Printf("time1 : %s\n", timeStr)
str = from.Format("2006-01-02")
timeStr = timeStr + str
fmt.Printf("time2 : %s\n", timeStr)
q=url.QueryEscape("repo:golang/go" + timeStr)
fmt.Println("q:", q)
urlStr = "https://api.github.com/search/issues" +"?q=" + q
fmt.Println("urlStr:", urlStr)
resp, ret = http.Get(urlStr)
fmt.Println("ret :", ret, "resp.status :", resp.Status)
}
I used this to form the query.
I am new to web programming and not able to understand where I went wrong in forming the second query.
two things that worked for me
1) reverse the "from" and "to" in your timeStr
2) don't use QueryEscape on the timeStr, just add it in like this
urlStr = "https://api.github.com/search/issues" + "?q=repo:golang/go+" + timeStr
Don't use an ampersand (I originally answered with this) use a plus sign or space. See https://help.github.com/articles/searching-issues-and-pull-requests/#search-by-when-an-issue-or-pull-request-was-created-or-last-updated for the syntax
update: on further consideration the QueryEscape is a good idea! It seems coincidentally to "just work"
I used like the following and it works for me if i don't escape the 2nd url:
package main
import(
"fmt"
"time"
"net/http"
"net/url"
)
func main() {
var ret error
var str string
q:=url.QueryEscape("repo:golang/go")
fmt.Println("q:", q)
urlStr := "https://api.github.com/search/issues" +"?q=" + q
fmt.Println("urlStr:", urlStr)
resp, ret:= http.Get(urlStr)
fmt.Println("ret :", ret, "resp.status :", resp.Status)
timeStr := "created:"
to := time.Now()
from := to.AddDate(0, -3, 0)
str = to.Format("2006-01-02")
timeStr = timeStr + str + ".."
fmt.Printf("time1 : %s\n", timeStr)
str = from.Format("2006-01-02")
timeStr = timeStr + str
fmt.Printf("time2 : %s\n", timeStr)
urlStr = "https://api.github.com/search/issues" +"?q=" + "repo:golang/go&created:2018-11-29..2018-08-29"
fmt.Println("urlStr:", urlStr)
resp, ret = http.Get(urlStr)
fmt.Println("ret :", ret, "resp.status :", resp.Status)
}
And the output is:
q: repo%3Agolang%2Fgo
urlStr: https://api.github.com/search/issues?q=repo%3Agolang%2Fgo
ret : <nil> resp.status : 200 OK
time1 : created:2018-11-29..
time2 : created:2018-11-29..2018-08-29
urlStr: https://api.github.com/search/issues?q=repo:golang/go&created:2018-11-29..2018-08-29
ret : <nil> resp.status : 200 OK
Many APIs including the one from github return the 422 status code when the client sends invalid input. In your code the bad input is generated by the line that concatenates the two qualifiers without a "separator".
So this "repo:golang/go" + timeStr will result in the q value containing a single "merged" qualifier that looks something like this:
"repo:golang/gocreated:2018-1...
To fix your code you just need to add a space between the two qualifiers and your query should work.
q=url.QueryEscape("repo:golang/go " + timeStr)
I'm trying to create two HTTP requests with the same request body. Unfortunately, the second request sends an empty body.
w := httptest.NewRecorder()
w2 := httptest.NewRecorder()
pd := &postData{
Data: 5,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(pd)
req, _ := http.NewRequest("PUT", "/v1/jobs/echo", b)
server.ServeHTTP(w, req)
req, _ = http.NewRequest("PUT", "/v1/jobs/echo", b)
server.ServeHTTP(w2, req)
Reading through the documentation and the source code for bytes.Buffer, it looks like there's no way to reset the buffer to 0 - there's a Reset method, but this also wipes the buffer's internal state.
Is there a way to "replay" any reader in Go? A bytes.Buffer or any other Reader.
OK. So I wouldn't consider this ideal and it would be better to just init a reader in the first place but if you put your data in a bytes.Reader instead of bytes.Buffer then you'll be able to seek back to the beginning after the first call to NewRequest has read to the end.
w := httptest.NewRecorder()
w2 := httptest.NewRecorder()
pd := &postData{
Data: 5,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(pd)
r := bytes.NewReader(b.Bytes())
req, _ := http.NewRequest("PUT", "/v1/jobs/echo", r)
server.ServeHTTP(w, req)
r.Seek(0, 0)
req, _ = http.NewRequest("PUT", "/v1/jobs/echo", r)
server.ServeHTTP(w2, req)
From a source I cannot influence I am given data in a map, which arrives as map[interface {}]interface {}.
I need to process the contained data, preferably as map[string]string (the data within is perfectly suitable for that).
I need to generate a list of the keys from the data as well, as those are not known beforehand.
Most similar questions I could find on the web say more or less, that this is impossible, but if my map is m, fmt.Println(m) shows the data is there, readable as map[k0:v0 K1:v1 k2:v2 ... ].
How can I do what fmt.Println is able to do?
A secure way to process unknown interfaces, just use fmt.Sprintf()
https://play.golang.org/p/gOiyD4KpQGz
package main
import (
"fmt"
)
func main() {
mapInterface := make(map[interface{}]interface{})
mapString := make(map[string]string)
mapInterface["k1"] = 1
mapInterface[3] = "hello"
mapInterface["world"] = 1.05
for key, value := range mapInterface {
strKey := fmt.Sprintf("%v", key)
strValue := fmt.Sprintf("%v", value)
mapString[strKey] = strValue
}
fmt.Printf("%#v", mapString)
}
Perhaps I misunderstand the question, but would this work?
m := make(map[interface{}]interface{})
m["foo"] = "bar"
m2 := make(map[string]string)
for key, value := range m {
switch key := key.(type) {
case string:
switch value := value.(type) {
case string:
m2[key] = value
}
}
}
// data is map[string]interface{}
form := make(map[string]string)
for k, v := range data {
form[k] = v.(string)
}
I'm trying to have a good access to multi-dimensional arrays with string indexes in Lua, here's basically what I'm trying to do:
rules =
{
{"S_RIGHT", "A_STOP", "S_RESULT"},
}
matrix = {}
for _,v in pairs(rules) do
if( matrix[ v[1] ] == nil ) then
matrix[ v[1] ] = {}
end
matrix[ v[1] ][ v[2] ] = v[3]
end
-- results in error ( attempt to index field 'S_NO' a nil value)
var = matrix["S_NO"]["S_RESULT"]
assert(var == nil, "Var should be nil")
A way to do it but quite verbose is:
var = matrix["S_NO"]
if var ~= nil then
var = var["S_RESULT"]
end
assert(var == nil, "Var should be nil")
Is there a way to make the first case to work ? ( less verbose )
Ok,
Found the answer.
If matrix is going to be read-only a correct approach would be:
local empty = {}
setmetatable(matrix, {__index=function() return empty end})
If I would like to allow writes and it's specifically two levels of tables, I could do:
setmetatable(matrix, {__index=function(t,k) local new={} rawset(t,k,new) return new end}
Hope this helps!