Skip to content

Instantly share code, notes, and snippets.

View prnvbn's full-sized avatar

Pranav Bansal prnvbn

View GitHub Profile
@prnvbn
prnvbn / background.go
Created August 13, 2021 08:33
A task running periodically in the background in Golang.
ticker := time.NewTicker(70 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
// do the task here
case <-quit:
ticker.Stop()
return
@prnvbn
prnvbn / retry.go
Created August 13, 2021 09:30
A retry function in Golang
func retry(attempts int, sleep time.Duration, f func() error) (err error) {
for i := 0; i < attempts; i++ {
if i > 0 {
log.Println("retrying after error:", err)
time.Sleep(sleep)
sleep *= 2
}
err = f()
if err == nil {
return nil
@prnvbn
prnvbn / mux-utils.go
Created September 23, 2021 12:13
Utility functions for a mux REST API.
func respondWithErrorMsg(w http.ResponseWriter, code int, msg string) {
respondWithJSON(w, code, map[string]string{"error": msg})
}
func respondWithError(w http.ResponseWriter, code int, err error) {
respondWithJSON(w, code, map[string]string{"error": err.Error()})
}
// respondWithJSON converts the payload into JSON and responds with it
@prnvbn
prnvbn / remoteRun.go
Created October 14, 2021 19:18
run a command on a remote machine via SSH
unc remoteRun(user string, addr string, privateKey string, cmd string) (string, error) {
// privateKey could be read from a file, or retrieved from another storage
// source, such as the Secret Service / GNOME Keyring
key, err := ssh.ParsePrivateKey([]byte(privateKey))
if err != nil {
return "", err
}
// Authentication
config := &ssh.ClientConfig{
User: user,
@prnvbn
prnvbn / subsection.tex
Created October 23, 2021 15:57
Change formatting of sections and subsections in LaTeX
\usepackage{titlesec}
\titleformat{\section}[block]{\Large\bfseries\filcenter}{}{1em}{}
\titleformat{\subsection}[hang]{\filcenter\bfseries}{}{1em}{}
@prnvbn
prnvbn / clocks-tmz.py
Last active January 21, 2024 17:51
Generates a Go map that goes from country name to the list of timezones in that country
import json
import pytz
from pycountry import countries
def list_timezones_for_country(country_code):
try:
return pytz.country_timezones[country_code]
except KeyError:
return None
@prnvbn
prnvbn / vscode-vim.json
Last active September 14, 2024 15:40
My VS Code Vim keybinds
"vim.leader": " ",
"vim.foldfix": true,
"vim.smartRelativeLine": true,
"vim.useSystemClipboard": true,
"vim.normalModeKeyBindings": [
{
"before": [
"<leader>",
"w"
],