├── Ch05 ├── challenge │ ├── files │ │ ├── c.txt │ │ ├── a.txt │ │ ├── b.txt │ │ ├── e.txt │ │ └── d.txt │ └── sizes.py ├── solution │ ├── files │ │ ├── c.txt │ │ ├── a.txt │ │ ├── b.txt │ │ ├── e.txt │ │ └── d.txt │ ├── sizes.py │ └── sizes.go ├── 05_02 │ ├── chan.py │ └── chan.go ├── 05_01 │ ├── spin.py │ └── spin.go ├── 05_04 │ ├── urlcheck.py │ └── urlcheck.go └── 05_03 │ ├── wg.go │ └── wg.py ├── Ch06 ├── 06_02 │ ├── dev-requirements.txt │ ├── requirements.txt │ ├── httpd.py │ ├── test_httpd.py │ ├── httpd_test.go │ └── httpd.go ├── 06_03 │ └── nlp │ │ ├── doc.go │ │ ├── go.mod │ │ ├── example_test.go │ │ ├── stemmer │ │ ├── stemmer.go │ │ └── stemmer_test.go │ │ ├── cmd │ │ ├── stem │ │ │ └── main.go │ │ └── tokenize │ │ │ └── main.go │ │ ├── nlp.go │ │ ├── nlp_test.go │ │ ├── go.sum │ │ └── .vscode │ │ └── settings.json ├── solution │ └── shutdown │ │ ├── go.mod │ │ ├── log │ │ └── log.go │ │ ├── cmd │ │ └── shutdown │ │ │ └── main.go │ │ ├── shutdown.go │ │ ├── .vscode │ │ └── settings.json │ │ └── go.sum ├── 06_01 │ ├── rtb.go │ ├── rtb.py │ ├── test_rtb.py │ └── rtb_test.go ├── 06_04 │ ├── shutdown.go │ └── shutdown.py └── challenge │ └── shutdown.go ├── .gitignore ├── go.mod ├── Ch01 ├── 01_01 │ ├── hw.py │ └── hw.go ├── 01_02 │ ├── hw.py │ └── hw.go ├── 01_03 │ ├── hw.py │ └── hw.go ├── challenge │ └── now.py └── solution │ ├── now.py │ └── now.go ├── cheatsheet.pdf ├── Ch03 ├── 03_05 │ ├── head.png │ ├── head.py │ └── head.go ├── challenge │ ├── head.png │ └── magic.py ├── solution │ ├── head.png │ ├── magic.py │ └── magic.go ├── 03_02 │ ├── paths.py │ └── paths.go ├── 03_01 │ ├── collatz.py │ └── collatz.go ├── 03_03 │ ├── stats.py │ └── stats.go └── 03_04 │ ├── auth.go │ └── auth.py ├── .github ├── CODEOWNERS ├── PULL_REQUEST_TEMPLATE.md ├── workflows │ └── main.yml └── ISSUE_TEMPLATE.md ├── Ch04 ├── 04_05 │ ├── stats.py │ └── stats.go ├── 04_01 │ ├── sim.py │ ├── sim_pure.py │ └── sim.go ├── 04_02 │ ├── sim.py │ └── sim.go ├── 04_03 │ ├── sim.py │ └── sim.go ├── 04_04 │ ├── sim.py │ └── sim.go ├── solution │ ├── vm.py │ └── vm.go └── challenge │ └── vm.py ├── Ch02 ├── 02_02 │ ├── banner.py │ └── banner.go ├── 02_01 │ ├── fizzbuzz.py │ └── fizzbuzz.go ├── 02_03 │ ├── median.py │ └── median.go ├── 02_04 │ ├── most_common.py │ └── most_common.go ├── challenge │ └── char_freq.py └── solution │ ├── char_freq.py │ └── char_freq.go ├── CONTRIBUTING.md ├── NOTICE ├── .vscode └── settings.json ├── .devcontainer ├── devcontainer.json └── Dockerfile ├── README.md └── LICENSE /Ch05/challenge/files/c.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | -------------------------------------------------------------------------------- /Ch05/solution/files/c.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | -------------------------------------------------------------------------------- /Ch06/06_02/dev-requirements.txt: -------------------------------------------------------------------------------- 1 | # Development requirements 2 | 3 | pytest~=7.2 -------------------------------------------------------------------------------- /Ch06/06_02/requirements.txt: -------------------------------------------------------------------------------- 1 | # Production requirements 2 | 3 | Flask~=2.2 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | .tmp 4 | npm-debug.log 5 | *.pyc 6 | .pytest-cache 7 | -------------------------------------------------------------------------------- /Ch05/challenge/files/a.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | -------------------------------------------------------------------------------- /Ch05/solution/files/a.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/LinkedInLearning/go-for-python-developers-4362010 2 | 3 | go 1.19 4 | -------------------------------------------------------------------------------- /Ch01/01_01/hw.py: -------------------------------------------------------------------------------- 1 | # The obligatory "Hello World" 2 | 3 | message = 'Hello Pythoneers ♡' 4 | print(message) 5 | -------------------------------------------------------------------------------- /Ch01/01_02/hw.py: -------------------------------------------------------------------------------- 1 | # The obligatory "Hello World" 2 | 3 | message = 'Hello Pythoneers ♡' 4 | print(message) 5 | -------------------------------------------------------------------------------- /Ch01/01_03/hw.py: -------------------------------------------------------------------------------- 1 | # The obligatory "Hello World" 2 | 3 | message = 'Hello Pythoneers ♡' 4 | print(message) 5 | -------------------------------------------------------------------------------- /Ch01/challenge/now.py: -------------------------------------------------------------------------------- 1 | # Print current time 2 | from datetime import datetime 3 | 4 | print(datetime.now()) 5 | -------------------------------------------------------------------------------- /Ch01/solution/now.py: -------------------------------------------------------------------------------- 1 | # Print current time 2 | from datetime import datetime 3 | 4 | print(datetime.now()) 5 | -------------------------------------------------------------------------------- /cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/go-for-python-developers-4362010/HEAD/cheatsheet.pdf -------------------------------------------------------------------------------- /Ch03/03_05/head.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/go-for-python-developers-4362010/HEAD/Ch03/03_05/head.png -------------------------------------------------------------------------------- /Ch03/challenge/head.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/go-for-python-developers-4362010/HEAD/Ch03/challenge/head.png -------------------------------------------------------------------------------- /Ch03/solution/head.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/go-for-python-developers-4362010/HEAD/Ch03/solution/head.png -------------------------------------------------------------------------------- /Ch05/05_02/chan.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | 3 | queue = Queue() 4 | queue.put(99) 5 | val = queue.get() 6 | print(f'got {val}') 7 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) denotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /Ch05/solution/files/b.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | 11 12 | 12 13 | 13 14 | 14 15 | 15 16 | 16 17 | 17 18 | -------------------------------------------------------------------------------- /Ch05/challenge/files/b.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | 11 12 | 12 13 | 13 14 | 14 15 | 15 16 | 16 17 | 17 18 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package nlp provides some natural language processing functions. 3 | 4 | All function work on text as string. 5 | */ 6 | package nlp 7 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Ch01/solution/now.go: -------------------------------------------------------------------------------- 1 | // Print current time 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | fmt.Println(time.Now()) 11 | } 12 | -------------------------------------------------------------------------------- /Ch04/04_05/stats.py: -------------------------------------------------------------------------------- 1 | def add(a, b): 2 | return a + b 3 | 4 | 5 | if __name__ == '__main__': 6 | print(add(1, 2)) 7 | print(add(1.0, 2.0)) 8 | print(add('G', 'o')) 9 | -------------------------------------------------------------------------------- /Ch05/challenge/files/e.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | 11 12 | 12 13 | 13 14 | 14 15 | 15 16 | 16 17 | 17 18 | 18 19 | 19 20 | 20 21 | 21 22 | -------------------------------------------------------------------------------- /Ch05/solution/files/e.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | 11 12 | 12 13 | 13 14 | 14 15 | 15 16 | 16 17 | 17 18 | 18 19 | 19 20 | 20 21 | 21 22 | -------------------------------------------------------------------------------- /Ch01/01_01/hw.go: -------------------------------------------------------------------------------- 1 | // The obligatory "Hello World" 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | msg := "Hello Gophers ♡" 10 | fmt.Println(msg) 11 | } 12 | -------------------------------------------------------------------------------- /Ch01/01_02/hw.go: -------------------------------------------------------------------------------- 1 | // The obligatory "Hello World" 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | msg := "Hello Gophers ♡" 10 | fmt.Println(msg) 11 | } 12 | -------------------------------------------------------------------------------- /Ch01/01_03/hw.go: -------------------------------------------------------------------------------- 1 | // The obligatory "Hello World" 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | msg := "Hello Gophers ♡" 10 | fmt.Println(msg) 11 | } 12 | -------------------------------------------------------------------------------- /Ch05/05_02/chan.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | ch := make(chan int) 7 | ch <- 99 // send 8 | val := <-ch // receive 9 | fmt.Printf("got %d\n", val) 10 | } 11 | -------------------------------------------------------------------------------- /Ch05/challenge/files/d.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | 11 12 | 12 13 | 13 14 | 14 15 | 15 16 | 16 17 | 17 18 | 18 19 | 19 20 | 20 21 | 21 22 | 22 23 | 23 24 | 24 25 | 25 26 | 26 27 | 27 28 | 28 29 | -------------------------------------------------------------------------------- /Ch05/solution/files/d.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | 8 9 | 9 10 | 10 11 | 11 12 | 12 13 | 13 14 | 14 15 | 15 16 | 16 17 | 17 18 | 18 19 | 19 20 | 20 21 | 21 22 | 22 23 | 23 24 | 24 25 | 25 26 | 26 27 | 27 28 | 28 29 | -------------------------------------------------------------------------------- /Ch06/06_02/httpd.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/health') 7 | def health(): 8 | return 'OK\n' # FIXME 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run(port=8080) 13 | -------------------------------------------------------------------------------- /Ch06/solution/shutdown/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/353solutions/shutdown 2 | 3 | go 1.19 4 | 5 | require go.uber.org/zap v1.23.0 6 | 7 | require ( 8 | go.uber.org/atomic v1.7.0 // indirect 9 | go.uber.org/multierr v1.6.0 // indirect 10 | ) 11 | -------------------------------------------------------------------------------- /Ch06/06_02/test_httpd.py: -------------------------------------------------------------------------------- 1 | from http import HTTPStatus 2 | 3 | import httpd 4 | 5 | 6 | def test_health(): 7 | with httpd.app.test_client() as client: 8 | resp = client.get('/health') 9 | assert resp.status_code == HTTPStatus.OK 10 | -------------------------------------------------------------------------------- /Ch04/04_05/stats.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Add[T int | float64 | string](a, b T) T { 6 | return a + b 7 | } 8 | 9 | func main() { 10 | fmt.Println(Add(1, 2)) 11 | fmt.Println(Add(1.0, 2.0)) 12 | fmt.Println(Add("G", "o")) 13 | } 14 | -------------------------------------------------------------------------------- /Ch03/03_02/paths.py: -------------------------------------------------------------------------------- 1 | def split_ext(path): 2 | i = path.rfind('.') 3 | if i == -1: 4 | return path, '' 5 | return path[:i], path[i:] 6 | 7 | 8 | if __name__ == '__main__': 9 | root, ext = split_ext('app.py') 10 | print(f'{root=}, {ext=}') 11 | -------------------------------------------------------------------------------- /Ch05/05_01/spin.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | from time import sleep 3 | 4 | 5 | def worker(i): 6 | sleep(0.1) 7 | print(f'thread {i}') 8 | 9 | 10 | for i in range(5): 11 | Thread(target=worker, args=(i,), daemon=True).start() 12 | print('main') 13 | -------------------------------------------------------------------------------- /Ch03/03_01/collatz.py: -------------------------------------------------------------------------------- 1 | def collatz_step(n): 2 | """Compute one step in Collatz conjecture""" 3 | if n % 2 == 0: 4 | return n // 2 5 | return n * 3 + 1 6 | 7 | 8 | if __name__ == '__main__': 9 | print(collatz_step(4)) 10 | print(collatz_step(5)) 11 | -------------------------------------------------------------------------------- /Ch02/02_02/banner.py: -------------------------------------------------------------------------------- 1 | # Print a banner with length of 8 for the string 'Hi ☺' 2 | # Should output 3 | # Hi ☺ 4 | # -------- 5 | 6 | message = 'Hi ☺' 7 | width = 8 8 | padding = (width - len(message)) // 2 9 | print(' ' * padding, end='') 10 | print(message) 11 | print('-' * width) 12 | -------------------------------------------------------------------------------- /Ch02/02_01/fizzbuzz.py: -------------------------------------------------------------------------------- 1 | # What is the average of all the numbers between 1 to 100 that divide either 2 | # by 3 or 5? 3 | 4 | count, total = 0, 0 5 | for n in range(1, 101): 6 | if n % 3 == 0 or n % 5 == 0: 7 | count += 1 8 | total += n 9 | 10 | print(total/count) 11 | -------------------------------------------------------------------------------- /Ch02/02_03/median.py: -------------------------------------------------------------------------------- 1 | # Calculate the median of a list of numbers 2 | 3 | 4 | numbers = [2, 1, 3] 5 | 6 | numbers.sort() 7 | i = len(numbers) // 2 8 | if len(numbers) % 2 == 1: 9 | median = numbers[i] 10 | else: 11 | median = (numbers[i-1] + numbers[i]) / 2 12 | print(median) 13 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/353solutions/nlp 2 | 3 | go 1.19 4 | 5 | require github.com/stretchr/testify v1.8.4 6 | 7 | require ( 8 | github.com/davecgh/go-spew v1.1.1 // indirect 9 | github.com/pmezard/go-difflib v1.0.0 // indirect 10 | gopkg.in/yaml.v3 v3.0.1 // indirect 11 | ) 12 | -------------------------------------------------------------------------------- /Ch05/05_01/spin.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func worker(n int) { 9 | time.Sleep(100 * time.Millisecond) 10 | fmt.Printf("goroutine %d\n", n) 11 | } 12 | 13 | func main() { 14 | for i := 0; i < 5; i++ { 15 | go worker(i) 16 | } 17 | fmt.Println("main") 18 | } 19 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/example_test.go: -------------------------------------------------------------------------------- 1 | package nlp_test 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/353solutions/nlp" 7 | ) 8 | 9 | func ExampleTokenize() { 10 | s := "Hi, how are you feeling today?" 11 | tokens := nlp.Tokenize(s) 12 | fmt.Println(tokens) 13 | // Output: 14 | // [hi how are you feel today] 15 | } 16 | -------------------------------------------------------------------------------- /Ch03/03_01/collatz.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // CollatzStep computes one step in CollatzStep conjecture 6 | func CollatzStep(n int) int { 7 | if n%2 == 0 { 8 | return n / 2 9 | } 10 | return n*3 + 1 11 | } 12 | 13 | func main() { 14 | fmt.Println(CollatzStep(4)) 15 | fmt.Println(CollatzStep(5)) 16 | } 17 | -------------------------------------------------------------------------------- /Ch03/03_05/head.py: -------------------------------------------------------------------------------- 1 | def file_head(file_name, size): 2 | with open(file_name, 'rb') as fp: 3 | data = fp.read(size) 4 | 5 | if len(data) < size: 6 | raise ValueError(f'{file_name!r} too small') 7 | 8 | return data 9 | 10 | 11 | if __name__ == '__main__': 12 | data = file_head('Ch03/03_05/head.png', 8) 13 | print(data) 14 | -------------------------------------------------------------------------------- /Ch02/02_01/fizzbuzz.go: -------------------------------------------------------------------------------- 1 | // What is the average of all the numbers between 1 to 100 that divide either by 3 or 5? 2 | package main 3 | 4 | import "fmt" 5 | 6 | func main() { 7 | count, total := 0, 0 8 | for n := 1; n <= 100; n++ { 9 | if n%3 == 0 || n%5 == 0 { 10 | count++ 11 | total += n 12 | } 13 | } 14 | 15 | fmt.Println(total / count) 16 | } 17 | -------------------------------------------------------------------------------- /Ch05/05_04/urlcheck.py: -------------------------------------------------------------------------------- 1 | from urllib.request import URLError, urlopen 2 | 3 | 4 | def check_url(url): 5 | try: 6 | with urlopen(url, timeout=5): 7 | return True 8 | except (URLError, TimeoutError): 9 | return False 10 | 11 | 12 | if __name__ == '__main__': 13 | url = 'https://www.linkedin.com/learning/' 14 | print(check_url(url)) 15 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Copy To Branches 2 | on: 3 | workflow_dispatch: 4 | jobs: 5 | copy-to-branches: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | with: 10 | fetch-depth: 0 11 | - name: Copy To Branches Action 12 | uses: planetoftheweb/copy-to-branches@v1.2 13 | env: 14 | key: main 15 | -------------------------------------------------------------------------------- /Ch03/03_02/paths.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func SplitExt(path string) (string, string) { 9 | i := strings.LastIndex(path, ".") 10 | if i == -1 { 11 | return path, "" 12 | } 13 | 14 | return path[:i], path[i:] 15 | } 16 | 17 | func main() { 18 | root, ext := SplitExt("app.go") 19 | fmt.Printf("root=%#v, path=%#v\n", root, ext) 20 | } 21 | -------------------------------------------------------------------------------- /Ch03/03_03/stats.py: -------------------------------------------------------------------------------- 1 | class StatsError(Exception): 2 | pass 3 | 4 | 5 | def mean(values): 6 | if not values: 7 | raise StatsError('"mean" with no values') 8 | return sum(values) / len(values) 9 | 10 | 11 | if __name__ == '__main__': 12 | values = [2, 4, 8] 13 | try: 14 | print(mean(values)) 15 | except StatsError as err: 16 | print(f'error: {err}') 17 | -------------------------------------------------------------------------------- /Ch02/02_03/median.go: -------------------------------------------------------------------------------- 1 | // Calculate the median of a slice of numbers 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "sort" 7 | ) 8 | 9 | func main() { 10 | nums := []float64{2, 1, 3} 11 | 12 | sort.Float64s(nums) 13 | var median float64 14 | i := len(nums) / 2 15 | if len(nums)%2 == 1 { 16 | median = nums[i] 17 | } else { 18 | median = (nums[i-1] + nums[i]) / 2 19 | } 20 | fmt.Println(median) 21 | } 22 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/stemmer/stemmer.go: -------------------------------------------------------------------------------- 1 | package stemmer 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | var ( 8 | suffixes = []string{"ed", "ing", "s"} 9 | ) 10 | 11 | // Stem returns the stemmed version of word. 12 | func Stem(word string) string { 13 | for _, suffix := range suffixes { 14 | if strings.HasSuffix(word, suffix) { 15 | return word[:len(word)-len(suffix)] 16 | } 17 | } 18 | return word 19 | } 20 | -------------------------------------------------------------------------------- /Ch06/06_02/httpd_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httptest" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestHealth(t *testing.T) { 12 | w := httptest.NewRecorder() 13 | r := httptest.NewRequest(http.MethodGet, "/health", nil) 14 | 15 | healthHandler(w, r) 16 | 17 | res := w.Result() 18 | require.Equal(t, http.StatusOK, res.StatusCode) 19 | } 20 | -------------------------------------------------------------------------------- /Ch06/06_01/rtb.go: -------------------------------------------------------------------------------- 1 | package rtb 2 | 3 | import "fmt" 4 | 5 | func SecondBest(prices []int) (int, error) { 6 | if len(prices) == 0 { 7 | return 0, fmt.Errorf("SecondBest of empty prices") 8 | } 9 | 10 | first, second := prices[0], prices[0] 11 | for _, p := range prices[1:] { 12 | switch { 13 | case p > first: 14 | first, second = p, first 15 | case p > second: 16 | second = p 17 | } 18 | } 19 | 20 | return second, nil 21 | } 22 | -------------------------------------------------------------------------------- /Ch03/03_04/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Role string 6 | 7 | const ( 8 | Viewer Role = "viewer" 9 | Developer Role = "developer" 10 | Admin Role = "admin" 11 | ) 12 | 13 | type User struct { 14 | Login string 15 | Role Role 16 | } 17 | 18 | func Promote(u User, r Role) { 19 | u.Role = r 20 | } 21 | 22 | func main() { 23 | u := User{"elliot", Viewer} 24 | Promote(u, Admin) 25 | fmt.Printf("%#v\n", u) 26 | } 27 | -------------------------------------------------------------------------------- /Ch06/solution/shutdown/log/log.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "go.uber.org/zap" 5 | ) 6 | 7 | // New returns a new logger. 8 | // New might panic in some edge cases. 9 | func New(name string) *zap.SugaredLogger { 10 | cfg := zap.NewProductionConfig() 11 | cfg.InitialFields = map[string]any{ 12 | "name": name, 13 | } 14 | 15 | logger, err := cfg.Build() 16 | if err != nil { 17 | panic(err) 18 | } 19 | 20 | return logger.Sugar() 21 | } 22 | -------------------------------------------------------------------------------- /Ch06/06_01/rtb.py: -------------------------------------------------------------------------------- 1 | def second_best(prices): 2 | """Return second best price. 3 | 4 | >>> second_best([2, 1, 3]) 5 | 2 6 | """ 7 | if not prices: 8 | raise ValueError('second_best on empty prices') 9 | 10 | first = second = prices[0] 11 | for price in prices[1:]: 12 | if price > first: 13 | first, second = price, first 14 | elif price > second: 15 | second = price 16 | return second 17 | -------------------------------------------------------------------------------- /Ch06/06_02/httpd.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | 8 | "github.com/gorilla/mux" 9 | ) 10 | 11 | func healthHandler(w http.ResponseWriter, r *http.Request) { 12 | fmt.Fprintln(w, "OK") 13 | } 14 | 15 | func main() { 16 | r := mux.NewRouter() 17 | r.HandleFunc("/health", healthHandler).Methods("GET") 18 | 19 | if err := http.ListenAndServe(":8080", r); err != nil { 20 | log.Fatalf("error: %s", err) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Ch02/02_02/banner.go: -------------------------------------------------------------------------------- 1 | /* 2 | Print a banner with length of 8 for the string "Hi ☺" 3 | Should output 4 | 5 | Hi ☺ 6 | -------- 7 | */ 8 | package main 9 | 10 | import "fmt" 11 | 12 | func main() { 13 | message := "Hi ☺" 14 | width := 8 15 | padding := (width - len(message)) / 2 16 | for i := 0; i < padding; i++ { 17 | fmt.Print(" ") 18 | } 19 | fmt.Println(message) 20 | for i := 0; i < width; i++ { 21 | fmt.Print("-") 22 | } 23 | fmt.Println() 24 | } 25 | -------------------------------------------------------------------------------- /Ch03/03_04/auth.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from enum import Enum 3 | 4 | 5 | class Role(Enum): 6 | VIEWER = 'viewer' 7 | DEVELOPER = 'developer' 8 | ADMIN = 'admin' 9 | 10 | 11 | @dataclass 12 | class User: 13 | login: str 14 | role: Role 15 | 16 | 17 | def promote(user, role): 18 | user.role = role 19 | 20 | 21 | if __name__ == '__main__': 22 | user = User('elliot', Role.VIEWER) 23 | promote(user, Role.ADMIN) 24 | print(user) 25 | -------------------------------------------------------------------------------- /Ch06/06_01/test_rtb.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from rtb import second_best 3 | 4 | 5 | def test_rtb(): 6 | prices = [10, 20, 30] 7 | sb = second_best(prices) 8 | assert sb == 20 9 | 10 | 11 | rtb_cases = [ 12 | # prices, expected 13 | [[10, 20, 30], 20], 14 | [[1, 2, 3, 1, 2], 2], 15 | ] 16 | 17 | 18 | @pytest.mark.parametrize('prices, expected', rtb_cases) 19 | def test_rtb_table(prices, expected): 20 | sb = second_best(prices) 21 | assert sb == expected 22 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/cmd/stem/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/353solutions/nlp/stemmer" 9 | ) 10 | 11 | func main() { 12 | flag.Usage = func() { 13 | fmt.Fprintf(os.Stderr, "usage: stem WORD") 14 | flag.PrintDefaults() 15 | } 16 | flag.Parse() 17 | 18 | if flag.NArg() != 1 { 19 | fmt.Fprintf(os.Stderr, "error: wrong number of arguments") 20 | os.Exit(1) 21 | } 22 | 23 | fmt.Println(stemmer.Stem(flag.Arg(0))) 24 | } 25 | -------------------------------------------------------------------------------- /Ch02/02_04/most_common.py: -------------------------------------------------------------------------------- 1 | # What is the most common word in Rumi's poem? 2 | 3 | poem = ''' 4 | those who do not feel this love 5 | pulling them like a river 6 | those who do not drink dawn 7 | like a cup of spring water 8 | or take in sunset like supper 9 | those who do not want to change 10 | let them sleep 11 | ''' 12 | 13 | frequency = {} 14 | for word in poem.split(): 15 | frequency[word] = frequency.get(word, 0) + 1 16 | 17 | most_common = max(frequency, key=frequency.get) 18 | print(most_common) 19 | -------------------------------------------------------------------------------- /Ch04/04_01/sim.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class Location: 6 | lat: float 7 | lng: float 8 | 9 | def __post_init__(self): 10 | if self.lat < -90 or self.lat > 90: 11 | raise ValueError(f'invalid lat: {self.lat}') 12 | if self.lng < -180 or self.lng > 180: 13 | raise ValueError(f'invalid lng: {self.lng}') 14 | 15 | 16 | if __name__ == '__main__': 17 | loc = Location(lat=32.5253837, lng=34.9427434) 18 | print(loc) 19 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/cmd/tokenize/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/353solutions/nlp" 9 | ) 10 | 11 | func main() { 12 | flag.Usage = func() { 13 | fmt.Fprintf(os.Stderr, "usage: tokenize SENTENCE") 14 | flag.PrintDefaults() 15 | } 16 | flag.Parse() 17 | 18 | if flag.NArg() != 1 { 19 | fmt.Fprintf(os.Stderr, "error: wrong number of arguments") 20 | os.Exit(1) 21 | } 22 | 23 | for _, tok := range nlp.Tokenize(flag.Arg(0)) { 24 | fmt.Println(tok) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Ch06/solution/shutdown/cmd/shutdown/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/353solutions/shutdown" 9 | ) 10 | 11 | func main() { 12 | flag.Usage = func() { 13 | fmt.Fprintf(os.Stderr, "usage: shutdown PID_FILE\n") 14 | flag.PrintDefaults() 15 | } 16 | flag.Parse() 17 | 18 | if flag.NArg() != 1 { 19 | fmt.Fprintf(os.Stderr, "error: wrong number of arguments") 20 | os.Exit(1) 21 | } 22 | 23 | if err := shutdown.ShutdownServer(flag.Arg(0)); err != nil { 24 | os.Exit(1) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/nlp.go: -------------------------------------------------------------------------------- 1 | package nlp 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | 7 | "github.com/353solutions/nlp/stemmer" 8 | ) 9 | 10 | var ( 11 | wordRe = regexp.MustCompile("[a-z]+") 12 | ) 13 | 14 | // Tokenize splits text to list of tokens. 15 | func Tokenize(text string) []string { 16 | text = strings.ToLower(text) 17 | var tokens []string 18 | for _, tok := range wordRe.FindAllString(text, -1) { 19 | tok = stemmer.Stem(tok) 20 | if tok == "" { 21 | continue 22 | } 23 | tokens = append(tokens, tok) 24 | } 25 | return tokens 26 | } 27 | -------------------------------------------------------------------------------- /Ch04/04_01/sim_pure.py: -------------------------------------------------------------------------------- 1 | class Location: 2 | def __init__(self, lat, lng): 3 | if lat < -90 or lat > 90: 4 | raise ValueError(f'invalid lat: {lat}') 5 | if lng < -180 or lng > 180: 6 | raise ValueError(f'invalid lng: {lng}') 7 | 8 | self.lat = lat 9 | self.lng = lng 10 | 11 | def __repr__(self): 12 | cls = self.__class__.__name__ 13 | return f'{cls}({self.lat!r}, {self.lng!r})' 14 | 15 | 16 | if __name__ == '__main__': 17 | loc = Location(32.5253837, 34.9427434) 18 | print(loc) 19 | -------------------------------------------------------------------------------- /Ch05/05_03/wg.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | var wg sync.WaitGroup 11 | ch := make(chan string) 12 | 13 | for i := 0; i < 3; i++ { 14 | go func(id int) { 15 | for msg := range ch { 16 | time.Sleep(100 * time.Millisecond) 17 | fmt.Printf("%d finished %s\n", id, msg) 18 | wg.Done() 19 | } 20 | }(i) 21 | } 22 | 23 | for _, msg := range []string{"A", "B", "C", "D", "E", "F"} { 24 | wg.Add(1) 25 | ch <- msg 26 | } 27 | wg.Wait() 28 | fmt.Println("all jobs done") 29 | } 30 | -------------------------------------------------------------------------------- /Ch05/05_03/wg.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | from threading import Thread 3 | from time import sleep 4 | 5 | 6 | def worker(id, queue): 7 | while True: 8 | item = queue.get() 9 | sleep(0.1) 10 | print(f'{id} finished {item}') 11 | queue.task_done() 12 | 13 | 14 | if __name__ == '__main__': 15 | queue = Queue() 16 | for id in range(3): 17 | Thread(target=worker, args=(id, queue), daemon=True).start() 18 | 19 | for msg in ['A', 'B', 'C', 'D', 'E', 'F']: 20 | queue.put(msg) 21 | 22 | queue.join() 23 | print('all jobs done') 24 | -------------------------------------------------------------------------------- /Ch03/03_03/stats.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Sum(values []float64) float64 { 6 | total := 0.0 7 | for _, v := range values { 8 | total += v 9 | } 10 | return total 11 | } 12 | 13 | func Mean(values []float64) (float64, error) { 14 | if len(values) == 0 { 15 | return 0, fmt.Errorf("Mean of empty slice") 16 | } 17 | 18 | return Sum(values) / float64(len(values)), nil 19 | } 20 | 21 | func main() { 22 | values := []float64{2, 4, 8} 23 | m, err := Mean(values) 24 | if err != nil { 25 | fmt.Printf("error: %s\n", err) 26 | return 27 | } 28 | fmt.Println(m) 29 | } 30 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/stemmer/stemmer_test.go: -------------------------------------------------------------------------------- 1 | package stemmer 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | var testCases = []struct { 11 | word string 12 | stem string 13 | }{ 14 | {"work", "work"}, 15 | {"worked", "work"}, 16 | {"working", "work"}, 17 | {"works", "work"}, 18 | } 19 | 20 | func TestStem(t *testing.T) { 21 | require := require.New(t) 22 | for _, tc := range testCases { 23 | name := fmt.Sprintf("%s:%s", tc.word, tc.stem) 24 | t.Run(name, func(t *testing.T) { 25 | require.Equal(Stem(tc.word), tc.stem, "stem") 26 | }) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Ch04/04_02/sim.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class Location: 6 | lat: float 7 | lng: float 8 | 9 | def __post_init__(self): 10 | if self.lat < -90 or self.lat > 90: 11 | raise ValueError(f'invalid lat: {self.lat}') 12 | if self.lng < -180 or self.lng > 180: 13 | raise ValueError(f'invalid lng: {self.lng}') 14 | 15 | def move(self, lat, lng): 16 | self.lat = lat 17 | self.lng = lng 18 | 19 | 20 | if __name__ == '__main__': 21 | loc = Location(lat=32.5253837, lng=34.9427434) 22 | loc.move(32.0641339, 34.8742343) 23 | print(loc) 24 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2023 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | Please note, this project may automatically load third party code from external 8 | repositories (for example, NPM modules, Composer packages, or other dependencies). 9 | If so, such third party code may be subject to other license terms than as set 10 | forth above. In addition, such third party code may also depend on and load 11 | multiple tiers of dependencies. Please review the applicable licenses of the 12 | additional dependencies. 13 | -------------------------------------------------------------------------------- /Ch04/04_01/sim.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Location struct { 6 | Lat float64 7 | Lng float64 8 | } 9 | 10 | func NewLocation(lat, lng float64) (Location, error) { 11 | if lat < -90 || lat > 90 { 12 | return Location{}, fmt.Errorf("invalid lat: %#v", lat) 13 | } 14 | if lng < -180 || lng > 180 { 15 | return Location{}, fmt.Errorf("invalid lng: %#v", lng) 16 | } 17 | 18 | loc := Location{ 19 | Lat: lat, 20 | Lng: lng, 21 | } 22 | return loc, nil 23 | } 24 | 25 | func main() { 26 | loc, err := NewLocation(32.5253837, 34.9427434) 27 | if err != nil { 28 | fmt.Println("ERROR:", err) 29 | return 30 | } 31 | fmt.Println(loc) 32 | } 33 | -------------------------------------------------------------------------------- /Ch03/03_05/head.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func fileHead(fileName string, size int) ([]byte, error) { 9 | file, err := os.Open(fileName) 10 | if err != nil { 11 | return nil, err 12 | } 13 | defer file.Close() 14 | 15 | buf := make([]byte, size) 16 | n, err := file.Read(buf) 17 | 18 | if err != nil { 19 | return nil, err 20 | } 21 | if n != size { 22 | return nil, fmt.Errorf("%q too small", fileName) 23 | } 24 | 25 | return buf, nil 26 | } 27 | 28 | func main() { 29 | data, err := fileHead("head.png", 8) 30 | if err != nil { 31 | fmt.Println("ERROR:", err) 32 | } else { 33 | fmt.Println(data) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Ch02/02_04/most_common.go: -------------------------------------------------------------------------------- 1 | // What is the most common word in Rumi's poem? 2 | package main 3 | 4 | import ( 5 | "strings" 6 | ) 7 | 8 | var poem = ` 9 | those who do not feel this love 10 | pulling them like a river 11 | those who do not drink dawn 12 | like a cup of spring water 13 | or take in sunset like supper 14 | those who do not want to change 15 | let them sleep 16 | ` 17 | 18 | func main() { 19 | frequency := make(map[string]int) 20 | for _, word := range strings.Fields(poem) { 21 | frequency[word]++ 22 | } 23 | 24 | maxW, maxC := "", 0 25 | for w, c := range frequency { 26 | if c > maxC { 27 | maxW, maxC = w, c 28 | } 29 | } 30 | 31 | print(maxW) 32 | } 33 | -------------------------------------------------------------------------------- /Ch05/05_04/urlcheck.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "time" 7 | ) 8 | 9 | func CheckURL(url string) bool { 10 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 11 | defer cancel() 12 | 13 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) 14 | if err != nil { 15 | return false 16 | } 17 | 18 | resp, err := http.DefaultClient.Do(req) 19 | if err != nil { 20 | return false 21 | } 22 | 23 | if resp.StatusCode != http.StatusOK { 24 | return false 25 | } 26 | 27 | return true 28 | } 29 | 30 | func main() { 31 | url := "https://www.linkedin.com/learning/" 32 | print(CheckURL(url)) 33 | } 34 | -------------------------------------------------------------------------------- /Ch05/challenge/sizes.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from queue import Queue 3 | from threading import Thread 4 | 5 | 6 | def worker(file_name, queue): 7 | size = Path(file_name).stat().st_size 8 | queue.put((file_name, size)) 9 | 10 | 11 | files = [ 12 | 'Ch05/challenge/files/a.txt', 13 | 'Ch05/challenge/files/b.txt', 14 | 'Ch05/challenge/files/c.txt', 15 | 'Ch05/challenge/files/d.txt', 16 | 'Ch05/challenge/files/e.txt', 17 | ] 18 | 19 | queue = Queue() 20 | for file_name in files: 21 | Thread(target=worker, args=(file_name, queue), daemon=True).start() 22 | 23 | for _ in files: 24 | file_name, size = queue.get() 25 | print(f'{file_name} -> {size}') 26 | -------------------------------------------------------------------------------- /Ch05/solution/sizes.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from queue import Queue 3 | from threading import Thread 4 | 5 | 6 | def worker(file_name, queue): 7 | size = Path(file_name).stat().st_size 8 | queue.put((file_name, size)) 9 | 10 | 11 | files = [ 12 | 'Ch05/challenge/files/a.txt', 13 | 'Ch05/challenge/files/b.txt', 14 | 'Ch05/challenge/files/c.txt', 15 | 'Ch05/challenge/files/d.txt', 16 | 'Ch05/challenge/files/e.txt', 17 | ] 18 | 19 | queue = Queue() 20 | for file_name in files: 21 | Thread(target=worker, args=(file_name, queue), daemon=True).start() 22 | 23 | for _ in files: 24 | file_name, size = queue.get() 25 | print(f'{file_name} -> {size}') 26 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/nlp_test.go: -------------------------------------------------------------------------------- 1 | package nlp 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | ) 8 | 9 | func TestTokenize(t *testing.T) { 10 | testCases := []struct { 11 | text string 12 | expected []string 13 | }{ 14 | {"", nil}, 15 | {"hi", []string{"hi"}}, 16 | {"HI", []string{"hi"}}, 17 | {"Who's on first.", []string{"who", "on", "first"}}, 18 | } 19 | 20 | for _, tc := range testCases { 21 | name := tc.text 22 | if len(name) == 0 { 23 | name = "" 24 | } 25 | t.Run(name, func(t *testing.T) { 26 | require := require.New(t) 27 | out := Tokenize(tc.text) 28 | require.Equal(tc.expected, out) 29 | }) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Ch04/04_03/sim.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class Location: 6 | lat: float 7 | lng: float 8 | 9 | def __post_init__(self): 10 | if self.lat < -90 or self.lat > 90: 11 | raise ValueError(f'invalid lat: {self.lat}') 12 | if self.lng < -180 or self.lng > 180: 13 | raise ValueError(f'invalid lng: {self.lng}') 14 | 15 | def move(self, lat, lng): 16 | self.lat = lat 17 | self.lng = lng 18 | 19 | 20 | @dataclass 21 | class Car(Location): 22 | id: str 23 | 24 | 25 | if __name__ == '__main__': 26 | car = Car(id='pyth0n', lat=32.5253837, lng=34.9427434) 27 | car.move(32.0641339, 34.8742343) 28 | print(car) 29 | -------------------------------------------------------------------------------- /Ch05/solution/sizes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | type response struct { 9 | fileName string 10 | size int64 11 | } 12 | 13 | func worker(fileName string, ch chan<- response) { 14 | resp := response{fileName: fileName, size: -1} 15 | st, err := os.Stat(fileName) 16 | if err == nil { 17 | resp.size = st.Size() 18 | } 19 | ch <- resp 20 | } 21 | 22 | func main() { 23 | 24 | files := []string{ 25 | "files/a.txt", 26 | "files/b.txt", 27 | "files/c.txt", 28 | "files/d.txt", 29 | "files/e.txt", 30 | } 31 | ch := make(chan response) 32 | 33 | for _, f := range files { 34 | go worker(f, ch) 35 | } 36 | 37 | for range files { 38 | r := <-ch 39 | fmt.Printf("%s -> %d\n", r.fileName, r.size) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Ch02/challenge/char_freq.py: -------------------------------------------------------------------------------- 1 | # Print character and frequency in percent of Rumi's poem 2 | # Print in frequency descending order 3 | # Assume ASCII text, ignore white space 4 | from operator import itemgetter 5 | 6 | poem = ''' 7 | those who do not feel this love 8 | pulling them like a river 9 | those who do not drink dawn 10 | like a cup of spring water 11 | or take in sunset like supper 12 | those who do not want to change 13 | let them sleep 14 | ''' 15 | 16 | counts = {} 17 | count = 0 18 | for c in poem: 19 | if c.isspace(): 20 | continue 21 | counts[c] = counts.get(c, 0) + 1 22 | count += 1 23 | 24 | for c, frequency in sorted(counts.items(), key=itemgetter(1), reverse=True): 25 | frequency = frequency / count * 100 26 | print(f'{c}: {frequency:.2f}') 27 | -------------------------------------------------------------------------------- /Ch02/solution/char_freq.py: -------------------------------------------------------------------------------- 1 | # Print character and frequency in percent of Rumi's poem 2 | # Print in frequency descending order 3 | # Assume ASCII text, ignore white space 4 | from operator import itemgetter 5 | 6 | poem = ''' 7 | those who do not feel this love 8 | pulling them like a river 9 | those who do not drink dawn 10 | like a cup of spring water 11 | or take in sunset like supper 12 | those who do not want to change 13 | let them sleep 14 | ''' 15 | 16 | counts = {} 17 | count = 0 18 | for c in poem: 19 | if c.isspace(): 20 | continue 21 | counts[c] = counts.get(c, 0) + 1 22 | count += 1 23 | 24 | for c, frequency in sorted(counts.items(), key=itemgetter(1), reverse=True): 25 | frequency = frequency / count * 100 26 | print(f'{c}: {frequency:.2f}') 27 | -------------------------------------------------------------------------------- /Ch04/04_02/sim.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Location struct { 6 | Lat float64 7 | Lng float64 8 | } 9 | 10 | func NewLocation(lat, lng float64) (Location, error) { 11 | if lat < -90 || lat > 90 { 12 | return Location{}, fmt.Errorf("invalid lat: %#v", lat) 13 | } 14 | if lng < -180 || lng > 180 { 15 | return Location{}, fmt.Errorf("invalid lng: %#v", lng) 16 | } 17 | 18 | loc := Location{ 19 | Lat: lat, 20 | Lng: lng, 21 | } 22 | return loc, nil 23 | } 24 | 25 | func (l Location) Move(lat, lng float64) { 26 | l.Lat = lat 27 | l.Lng = lng 28 | } 29 | 30 | func main() { 31 | loc, err := NewLocation(32.5253837, 34.9427434) 32 | if err != nil { 33 | fmt.Println("ERROR:", err) 34 | return 35 | } 36 | loc.Move(32.0641339, 34.8742343) 37 | fmt.Printf("%#v\n", loc) 38 | } 39 | -------------------------------------------------------------------------------- /Ch03/solution/magic.py: -------------------------------------------------------------------------------- 1 | class MagicError(Exception): 2 | pass 3 | 4 | 5 | def file_type(file_name): 6 | with open(file_name, 'rb') as fp: 7 | data = fp.read(64) 8 | 9 | if data[:4] == b'\x00\x00\x01\x00': 10 | return 'ico' 11 | if data[:6] == b'\x47\x49\x46\x38\x37\x61': 12 | return 'gif' 13 | if data[:4] == b'\xFF\xD8\xFF\xF0': 14 | return 'jpg' 15 | if data[:8] == b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A': 16 | return 'png' 17 | 18 | raise MagicError(f'{file_name!r} - unknown file type') 19 | 20 | 21 | if __name__ == '__main__': 22 | file_name = 'Ch03/solution/head.png' 23 | try: 24 | typ = file_type(file_name) 25 | print(f'{file_name} -> {typ}') 26 | except (FileNotFoundError, MagicError) as err: 27 | print(f'error: {err}') 28 | -------------------------------------------------------------------------------- /Ch03/challenge/magic.py: -------------------------------------------------------------------------------- 1 | class MagicError(Exception): 2 | pass 3 | 4 | 5 | def file_type(file_name): 6 | with open(file_name, 'rb') as fp: 7 | data = fp.read(64) 8 | 9 | if data[:4] == b'\x00\x00\x01\x00': 10 | return 'ico' 11 | if data[:6] == b'\x47\x49\x46\x38\x37\x61': 12 | return 'gif' 13 | if data[:4] == b'\xFF\xD8\xFF\xF0': 14 | return 'jpg' 15 | if data[:8] == b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A': 16 | return 'png' 17 | 18 | raise MagicError(f'{file_name!r} - unknown file type') 19 | 20 | 21 | if __name__ == '__main__': 22 | file_name = 'Ch03/challenge/head.png' 23 | try: 24 | typ = file_type(file_name) 25 | print(f'{file_name} -> {typ}') 26 | except (FileNotFoundError, MagicError) as err: 27 | print(f'error: {err}') 28 | -------------------------------------------------------------------------------- /Ch06/06_04/shutdown.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | var ( 10 | logger = log.New(log.Writer(), "[shutdown ]", log.LstdFlags|log.Lshortfile) 11 | ) 12 | 13 | func shutdownServer(pidFile string) error { 14 | file, err := os.Open(pidFile) 15 | if err != nil { 16 | logger.Printf("ERROR: can't open %q", pidFile) 17 | return err 18 | } 19 | defer file.Close() 20 | 21 | var pid int 22 | if _, err := fmt.Fscanf(file, "%d", &pid); err != nil { 23 | logger.Printf("ERROR: %q: bad pid - %s", pidFile, err) 24 | return err 25 | 26 | } 27 | 28 | logger.Printf("INFO: shutting down %d", pid) 29 | // TODO: Actual shutdown 30 | 31 | if err := os.Remove(pidFile); err != nil { 32 | log.Printf("WARNING: can't delete %q - %s", pidFile, err) 33 | } 34 | 35 | return nil 36 | } 37 | 38 | func main() { 39 | shutdownServer("app.pid") 40 | } 41 | -------------------------------------------------------------------------------- /Ch06/06_04/shutdown.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from os import remove 3 | 4 | logging.basicConfig( 5 | format=( 6 | '%(asctime)s - %(name)s:%(levelname)s - %(filename)s:%(lineno)d' 7 | '- %(message)s' 8 | ), 9 | level=logging.INFO, 10 | ) 11 | logger = logging.getLogger('shutdown') 12 | 13 | 14 | def shutdown_server(pid_file): 15 | try: 16 | with open(pid_file) as fp: 17 | pid = int(fp.read()) 18 | except (OSError, ValueError) as err: 19 | logger.error('%r: cannot get pid - %s', pid_file, err) 20 | raise 21 | 22 | logger.info('shutting down %s', pid) 23 | # TODO: Actual shutdown 24 | 25 | try: 26 | remove(pid_file) 27 | except OSError as err: 28 | logger.warning('cannot delete %r - %s', pid_file, err) 29 | 30 | 31 | if __name__ == '__main__': 32 | shutdown_server('Ch06/06_04/app.pid') 33 | -------------------------------------------------------------------------------- /Ch06/challenge/shutdown.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | var ( 10 | logger = log.New(log.Writer(), "[shutdown ]", log.LstdFlags|log.Lshortfile) 11 | ) 12 | 13 | func shutdownServer(pidFile string) error { 14 | file, err := os.Open(pidFile) 15 | if err != nil { 16 | logger.Printf("ERROR: can't open %q", pidFile) 17 | return err 18 | } 19 | defer file.Close() 20 | 21 | var pid int 22 | if _, err := fmt.Fscanf(file, "%d", &pid); err != nil { 23 | logger.Printf("ERROR: %q: bad pid - %s", pidFile, err) 24 | return err 25 | 26 | } 27 | 28 | logger.Printf("INFO: shutting down %d", pid) 29 | // TODO: Actual shutdown 30 | 31 | if err := os.Remove(pidFile); err != nil { 32 | log.Printf("WARNING: can't delete %q - %s", pidFile, err) 33 | } 34 | 35 | return nil 36 | } 37 | 38 | func main() { 39 | shutdownServer("app.pid") 40 | } 41 | -------------------------------------------------------------------------------- /Ch06/solution/shutdown/shutdown.go: -------------------------------------------------------------------------------- 1 | package shutdown 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/353solutions/shutdown/log" 8 | ) 9 | 10 | var ( 11 | logger = log.New("shutdown") 12 | ) 13 | 14 | // ShutdownServer shuts down server from pid in pidFile. 15 | func ShutdownServer(pidFile string) error { 16 | file, err := os.Open(pidFile) 17 | if err != nil { 18 | logger.Errorw("can't open", "file", pidFile, "error", err) 19 | return err 20 | } 21 | defer file.Close() 22 | 23 | var pid int 24 | if _, err := fmt.Fscanf(file, "%d", &pid); err != nil { 25 | logger.Errorw("bad pid", "file", pidFile, "error", err) 26 | return err 27 | 28 | } 29 | 30 | logger.Infow("shutdown", "pid", pid) 31 | // TODO: Actual shutdown 32 | 33 | if err := os.Remove(pidFile); err != nil { 34 | logger.Warnw("can't delete", "file", pidFile, "error", err) 35 | } 36 | 37 | return nil 38 | } 39 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 6 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 7 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 9 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 10 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 11 | -------------------------------------------------------------------------------- /Ch04/04_04/sim.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class Location: 6 | lat: float 7 | lng: float 8 | 9 | def __post_init__(self): 10 | if self.lat < -90 or self.lat > 90: 11 | raise ValueError(f'invalid lat: {self.lat}') 12 | if self.lng < -180 or self.lng > 180: 13 | raise ValueError(f'invalid lng: {self.lng}') 14 | 15 | def move(self, lat, lng): 16 | self.lat = lat 17 | self.lng = lng 18 | 19 | 20 | @dataclass 21 | class Car(Location): 22 | id: str 23 | 24 | 25 | def move_all(items, lat, lng): 26 | for item in items: 27 | item.move(lat, lng) 28 | 29 | 30 | if __name__ == '__main__': 31 | items = [ 32 | Location(32.3477669, 34.9160405), 33 | Car(id='pyth0n', lat=32.5253837, lng=34.9427434), 34 | ] 35 | move_all(items, 32.0641339, 34.8742343) 36 | for item in items: 37 | print(item) 38 | -------------------------------------------------------------------------------- /Ch02/solution/char_freq.go: -------------------------------------------------------------------------------- 1 | /* 2 | Print character and frequency in percent of Rumi's poem 3 | Print in frequency descending order 4 | Assume ASCII text, ignore white space 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "sort" 11 | "unicode" 12 | ) 13 | 14 | var poem = ` 15 | those who do not feel this love 16 | pulling them like a river 17 | those who do not drink dawn 18 | like a cup of spring water 19 | or take in sunset like supper 20 | those who do not want to change 21 | let them sleep 22 | ` 23 | 24 | func main() { 25 | counts := make(map[rune]int) 26 | count := 0.0 27 | for _, c := range poem { 28 | if unicode.IsSpace(c) { 29 | continue 30 | } 31 | counts[c]++ 32 | count += 1 33 | } 34 | 35 | var chars []rune 36 | for c := range counts { 37 | chars = append(chars, c) 38 | } 39 | sort.Slice(chars, func(i, j int) bool { 40 | c1, c2 := chars[i], chars[j] 41 | return counts[c1] > counts[c2] 42 | }) 43 | 44 | for _, c := range chars { 45 | n := counts[c] 46 | f := float64(n) / count * 100 47 | fmt.Printf("%c: %.2f\n", c, f) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Ch03/solution/magic.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | func fileType(fileName string) (string, error) { 10 | file, err := os.Open(fileName) 11 | if err != nil { 12 | return "", err 13 | } 14 | defer file.Close() 15 | 16 | data := make([]byte, 64) 17 | if _, err := file.Read(data); err != nil { 18 | return "", err 19 | } 20 | 21 | if bytes.Equal(data[:4], []byte{0x00, 0x00, 0x01, 0x00}) { 22 | return "ico", nil 23 | } 24 | if bytes.Equal(data[:6], []byte{0x47, 0x49, 0x46, 0x38, 0x37, 0x61}) { 25 | return "gif", nil 26 | } 27 | if bytes.Equal(data[:4], []byte{0xFF, 0xD8, 0xFF, 0xF0}) { 28 | return "jpg", nil 29 | } 30 | if bytes.Equal(data[:8], []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) { 31 | return "png", nil 32 | } 33 | 34 | return "", fmt.Errorf("%q - unknown file type", fileName) 35 | } 36 | 37 | func main() { 38 | fileName := "head.png" 39 | typ, err := fileType(fileName) 40 | if err != nil { 41 | fmt.Println("ERROR:", err) 42 | return 43 | } 44 | fmt.Printf("%s -> %s\n", fileName, typ) 45 | } 46 | -------------------------------------------------------------------------------- /Ch04/04_03/sim.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Location struct { 6 | Lat float64 7 | Lng float64 8 | } 9 | 10 | func NewLocation(lat, lng float64) (Location, error) { 11 | if lat < -90 || lat > 90 { 12 | return Location{}, fmt.Errorf("invalid lat: %#v", lat) 13 | } 14 | if lng < -180 || lng > 180 { 15 | return Location{}, fmt.Errorf("invalid lng: %#v", lng) 16 | } 17 | 18 | loc := Location{lat, lng} 19 | return loc, nil 20 | } 21 | 22 | func (l *Location) Move(lat, lng float64) { 23 | l.Lat = lat 24 | l.Lng = lng 25 | } 26 | 27 | type Car struct { 28 | ID string 29 | Location 30 | } 31 | 32 | func NewCar(id string, lat, lng float64) (Car, error) { 33 | loc, err := NewLocation(lat, lng) 34 | if err != nil { 35 | return Car{}, err 36 | } 37 | 38 | car := Car{ 39 | ID: id, 40 | Location: loc, 41 | } 42 | return car, nil 43 | } 44 | 45 | func main() { 46 | car, err := NewCar("g0ph3r", 32.5253837, 34.9427434) 47 | if err != nil { 48 | fmt.Println("ERROR:", err) 49 | return 50 | } 51 | car.Move(32.0641339, 34.8742343) 52 | fmt.Printf("%#v\n", car) 53 | } 54 | -------------------------------------------------------------------------------- /Ch06/06_01/rtb_test.go: -------------------------------------------------------------------------------- 1 | package rtb 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestSecondBest(t *testing.T) { 9 | prices := []int{1, 0, 2, 3} 10 | p, err := SecondBest(prices) 11 | if err != nil { 12 | t.Fatal(err) 13 | } 14 | expected := 2 15 | if p != expected { 16 | t.Fatalf("expected %d, got %d", p, expected) 17 | } 18 | } 19 | 20 | var secondBestCases = []struct { 21 | prices []int 22 | expected int 23 | }{ 24 | {[]int{1}, 1}, 25 | {[]int{1, 2, 3, 4, 2}, 3}, 26 | } 27 | 28 | func TestSecondBestTable(t *testing.T) { 29 | for _, tc := range secondBestCases { 30 | name := fmt.Sprintf("%v", tc.prices) 31 | t.Run(name, func(t *testing.T) { 32 | p, err := SecondBest(tc.prices) 33 | if err != nil { 34 | t.Fatal(err) 35 | } 36 | if p != tc.expected { 37 | t.Fatalf("expected %d, got %d", p, tc.expected) 38 | 39 | } 40 | }) 41 | } 42 | } 43 | 44 | func ExampleSecondBest() { 45 | values := []int{2, 1, 3} 46 | p, err := SecondBest(values) 47 | if err != nil { 48 | fmt.Println("ERROR:", err) 49 | return 50 | } 51 | fmt.Println(p) 52 | // Output: 53 | // 2 54 | } 55 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /Ch04/solution/vm.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from datetime import datetime, timezone 3 | 4 | PER_HOUR = 5 # ¢ 5 | 6 | 7 | @dataclass 8 | class VM: 9 | start_time: datetime 10 | end_time: datetime = None 11 | 12 | def cost(self): 13 | end_time = self.end_time 14 | if end_time is None: 15 | end_time = datetime.now() 16 | 17 | duration = end_time - self.start_time 18 | hours = duration.total_seconds() / (60 * 60) 19 | return hours * PER_HOUR 20 | 21 | 22 | class Spot(VM): 23 | def cost(self): 24 | p = super().cost() 25 | return p * .8 # Spot is 20% cheaper 26 | 27 | 28 | def total_cost(vms): 29 | return sum(vm.cost() for vm in vms) 30 | 31 | 32 | if __name__ == '__main__': 33 | vms = [ 34 | VM( 35 | start_time=datetime(2022, 4, 12, 17, 30, tzinfo=timezone.utc), 36 | end_time=datetime(2022, 4, 12, 19, 54, tzinfo=timezone.utc), 37 | ), 38 | Spot( 39 | start_time=datetime(2022, 4, 13, 9, 46, tzinfo=timezone.utc), 40 | end_time=datetime(2022, 4, 15, 12, 7, tzinfo=timezone.utc), 41 | ), 42 | ] 43 | print(total_cost(vms)) 44 | -------------------------------------------------------------------------------- /Ch04/challenge/vm.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from datetime import datetime, timezone 3 | 4 | PER_HOUR = 5 # ¢ 5 | 6 | 7 | @dataclass 8 | class VM: 9 | start_time: datetime 10 | end_time: datetime = None 11 | 12 | def cost(self): 13 | end_time = self.end_time 14 | if end_time is None: 15 | end_time = datetime.utcnow() 16 | 17 | duration = end_time - self.start_time 18 | hours = duration.total_seconds() / (60 * 60) 19 | return hours * PER_HOUR 20 | 21 | 22 | class Spot(VM): 23 | def cost(self): 24 | p = super().cost() 25 | return p * .8 # Spot is 20% cheaper 26 | 27 | 28 | def total_cost(vms): 29 | return sum(vm.cost() for vm in vms) 30 | 31 | 32 | if __name__ == '__main__': 33 | vms = [ 34 | VM( 35 | start_time=datetime(2022, 4, 12, 17, 30, tzinfo=timezone.utc), 36 | end_time=datetime(2022, 4, 12, 19, 54, tzinfo=timezone.utc), 37 | ), 38 | Spot( 39 | start_time=datetime(2022, 4, 13, 9, 46, tzinfo=timezone.utc), 40 | end_time=datetime(2022, 4, 15, 12, 7, tzinfo=timezone.utc), 41 | ), 42 | ] 43 | print(total_cost(vms)) 44 | -------------------------------------------------------------------------------- /Ch04/solution/vm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | const PerHour = 5 // ¢ 9 | 10 | type VM struct { 11 | StartTime time.Time 12 | EndTime time.Time 13 | } 14 | 15 | func (v VM) Cost() float64 { 16 | end := v.EndTime 17 | if end.Equal(time.Time{}) { 18 | end = time.Now() 19 | } 20 | 21 | d := float64(end.Sub(v.StartTime)) / float64(time.Hour) 22 | return d * PerHour 23 | } 24 | 25 | type Spot struct { 26 | VM 27 | } 28 | 29 | func (s Spot) Cost() float64 { 30 | p := s.VM.Cost() 31 | return p * 0.8 32 | } 33 | 34 | type Coster interface { 35 | Cost() float64 36 | } 37 | 38 | func TotalCost(vms []Coster) float64 { 39 | total := 0.0 40 | for _, vm := range vms { 41 | total += vm.Cost() 42 | } 43 | return total 44 | } 45 | 46 | func main() { 47 | vms := []Coster{ 48 | &VM{ 49 | StartTime: time.Date(2022, time.April, 12, 17, 30, 0, 0, time.UTC), 50 | EndTime: time.Date(2022, time.April, 12, 19, 54, 0, 0, time.UTC), 51 | }, 52 | Spot{ 53 | VM: VM{ 54 | StartTime: time.Date(2022, time.April, 13, 9, 46, 0, 0, time.UTC), 55 | EndTime: time.Date(2022, time.April, 15, 12, 7, 0, 0, time.UTC), 56 | }, 57 | }, 58 | } 59 | fmt.Println(TotalCost(vms)) 60 | } 61 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.bracketPairColorization.enabled": true, 3 | "editor.cursorBlinking": "solid", 4 | "editor.fontFamily": "ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace", 5 | "editor.fontLigatures": false, 6 | "editor.fontSize": 22, 7 | "editor.formatOnPaste": true, 8 | "editor.formatOnSave": true, 9 | "editor.lineNumbers": "on", 10 | "editor.matchBrackets": "always", 11 | "editor.minimap.enabled": false, 12 | "editor.smoothScrolling": true, 13 | "editor.tabSize": 2, 14 | "editor.useTabStops": true, 15 | "emmet.triggerExpansionOnTab": true, 16 | "explorer.openEditors.visible": 0, 17 | "files.autoSave": "afterDelay", 18 | "screencastMode.onlyKeyboardShortcuts": true, 19 | "terminal.integrated.fontSize": 18, 20 | "workbench.activityBar.visible": true, 21 | "workbench.colorTheme": "Visual Studio Dark", 22 | "workbench.fontAliasing": "antialiased", 23 | "workbench.statusBar.visible": true, 24 | 25 | "python.testing.pytestArgs": [ 26 | "." 27 | ], 28 | "python.testing.unittestEnabled": false, 29 | "python.testing.pytestEnabled": true 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Ch06/06_03/nlp/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.bracketPairColorization.enabled": true, 3 | "editor.cursorBlinking": "solid", 4 | "editor.fontFamily": "ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace", 5 | "editor.fontLigatures": false, 6 | "editor.fontSize": 22, 7 | "editor.formatOnPaste": true, 8 | "editor.formatOnSave": true, 9 | "editor.lineNumbers": "on", 10 | "editor.matchBrackets": "always", 11 | "editor.minimap.enabled": false, 12 | "editor.smoothScrolling": true, 13 | "editor.tabSize": 2, 14 | "editor.useTabStops": true, 15 | "emmet.triggerExpansionOnTab": true, 16 | "explorer.openEditors.visible": 0, 17 | "files.autoSave": "afterDelay", 18 | "screencastMode.onlyKeyboardShortcuts": true, 19 | "terminal.integrated.fontSize": 18, 20 | "workbench.activityBar.visible": true, 21 | "workbench.colorTheme": "Visual Studio Dark", 22 | "workbench.fontAliasing": "antialiased", 23 | "workbench.statusBar.visible": true, 24 | 25 | "python.testing.pytestArgs": [ 26 | "." 27 | ], 28 | "python.testing.unittestEnabled": false, 29 | "python.testing.pytestEnabled": true 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Ch06/solution/shutdown/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.bracketPairColorization.enabled": true, 3 | "editor.cursorBlinking": "solid", 4 | "editor.fontFamily": "ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace", 5 | "editor.fontLigatures": false, 6 | "editor.fontSize": 22, 7 | "editor.formatOnPaste": true, 8 | "editor.formatOnSave": true, 9 | "editor.lineNumbers": "on", 10 | "editor.matchBrackets": "always", 11 | "editor.minimap.enabled": false, 12 | "editor.smoothScrolling": true, 13 | "editor.tabSize": 2, 14 | "editor.useTabStops": true, 15 | "emmet.triggerExpansionOnTab": true, 16 | "explorer.openEditors.visible": 0, 17 | "files.autoSave": "afterDelay", 18 | "screencastMode.onlyKeyboardShortcuts": true, 19 | "terminal.integrated.fontSize": 18, 20 | "workbench.activityBar.visible": true, 21 | "workbench.colorTheme": "Visual Studio Dark", 22 | "workbench.fontAliasing": "antialiased", 23 | "workbench.statusBar.visible": true, 24 | 25 | "python.testing.pytestArgs": [ 26 | "." 27 | ], 28 | "python.testing.unittestEnabled": false, 29 | "python.testing.pytestEnabled": true 30 | 31 | } 32 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Go", 3 | "build": { 4 | "dockerfile": "Dockerfile", 5 | "args": { 6 | // Update the VARIANT arg to pick a version of Go: 1, 1.18, 1.17 7 | // Append -bullseye or -buster to pin to an OS version. 8 | // Use -bullseye variants on local arm64/Apple Silicon. 9 | "VARIANT": "1.19-bullseye", 10 | // Options 11 | "NODE_VERSION": "lts/*" 12 | } 13 | }, 14 | "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ], 15 | 16 | // Set *default* container specific settings.json values on container create. 17 | "settings": { 18 | "go.toolsManagement.checkForUpdates": "local", 19 | "go.useLanguageServer": true, 20 | "go.gopath": "/go" 21 | }, 22 | 23 | // Add the IDs of extensions you want installed when the container is created. 24 | "extensions": [ 25 | "GitHub.github-vscode-theme", 26 | "golang.Go", 27 | "ms-python.python" 28 | ], 29 | 30 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 31 | // "forwardPorts": [], 32 | 33 | // Use 'postCreateCommand' to run commands after the container is created. 34 | // "postCreateCommand": "go version", 35 | 36 | // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 37 | "remoteUser": "vscode", 38 | "onCreateCommand" : "echo PS1='\"$ \"' >> ~/.bashrc", //Set Terminal Prompt to $ 39 | } 40 | -------------------------------------------------------------------------------- /Ch04/04_04/sim.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Location struct { 6 | Lat float64 7 | Lng float64 8 | } 9 | 10 | func NewLocation(lat, lng float64) (Location, error) { 11 | if lat < -90 || lat > 90 { 12 | return Location{}, fmt.Errorf("invalid lat: %#v", lat) 13 | } 14 | if lng < -180 || lng > 180 { 15 | return Location{}, fmt.Errorf("invalid lng: %#v", lng) 16 | } 17 | 18 | loc := Location{lat, lng} 19 | return loc, nil 20 | } 21 | 22 | func (l *Location) Move(lat, lng float64) { 23 | l.Lat = lat 24 | l.Lng = lng 25 | } 26 | 27 | type Car struct { 28 | ID string 29 | Location 30 | } 31 | 32 | func NewCar(id string, lat, lng float64) (Car, error) { 33 | loc, err := NewLocation(lat, lng) 34 | if err != nil { 35 | return Car{}, err 36 | } 37 | 38 | car := Car{ 39 | ID: id, 40 | Location: loc, 41 | } 42 | return car, nil 43 | } 44 | 45 | type Mover interface { 46 | Move(float64, float64) 47 | } 48 | 49 | func moveAll(items []Mover, lat, lng float64) { 50 | for _, item := range items { 51 | item.Move(lat, lng) 52 | } 53 | } 54 | 55 | func main() { 56 | 57 | items := []Mover{ 58 | &Location{32.3477669, 34.9160405}, 59 | &Car{ 60 | ID: "g0ph3r", 61 | Location: Location{ 62 | Lat: 32.5253837, 63 | Lng: 34.9427434, 64 | }, 65 | }, 66 | } 67 | moveAll(items, 32.0641339, 34.8742343) 68 | for _, item := range items { 69 | fmt.Printf("%#v\n", item) 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Ch06/solution/shutdown/go.sum: -------------------------------------------------------------------------------- 1 | github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 6 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 7 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 8 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 9 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 10 | github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= 11 | go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= 12 | go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= 13 | go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= 14 | go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= 15 | go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= 16 | go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY= 17 | go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY= 18 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 19 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.224.3/containers/go/.devcontainer/base.Dockerfile 2 | 3 | # [Choice] Go version (use -bullseye variants on local arm64/Apple Silicon): 1, 1.16, 1.17, 1-bullseye, 1.16-bullseye, 1.17-bullseye, 1-buster, 1.16-buster, 1.17-buster 4 | ARG VARIANT="1.19-bullseye" 5 | FROM mcr.microsoft.com/vscode/devcontainers/go:0-${VARIANT} 6 | 7 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 8 | ARG NODE_VERSION="none" 9 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 10 | 11 | # [Optional] Uncomment this section to install additional OS packages. 12 | RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 13 | && apt-get -y install --no-install-recommends file python3-pip 14 | RUN python3 -m pip install pytest~=7.2 Flask~=2.2 15 | RUN ln -s /usr/bin/python3 /usr/local/bin/python 16 | 17 | # [Optional] Uncomment the next lines to use go get to install anything else you need 18 | USER vscode 19 | # List of tools used by vscode go extension 20 | # TODO: Find a way to run "Go: Install/Update Tools" in vscode 21 | RUN go install github.com/cweill/gotests/gotests@v1.6.0 22 | RUN go install github.com/fatih/gomodifytags@v1.16.0 23 | RUN go install github.com/josharian/impl@v1.1.0 24 | RUN go install github.com/haya14busa/goplay/cmd/goplay@v1.0.0 25 | RUN go install github.com/go-delve/delve/cmd/dlv@latest 26 | RUN go install honnef.co/go/tools/cmd/staticcheck@latest 27 | RUN go install golang.org/x/tools/gopls@latest 28 | ENV PATH=/home/vscode/go/bin:${PATH} 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go for Python Developers 2 | This is the repository for the LinkedIn Learning course Go for Python Developers. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | ![Go for Python Developers][lil-thumbnail-url] 5 | 6 | Go is steadily becoming one of the most popular programming languages, and more and more organizations are now using Go to write services. Many Python developers now find themselves having to transition to Go, and in this course, Miki Tebeka helps Python developers make the switch to get started writing Go programs. Miki covers the basics, from built-in types to function definitions, and gets into concurrency and project engineering as well. He also provides challenges and solutions for each chapter, so you can practice your skills as you learn. If you’re a Python developer looking for some hands-on experience as you transition to Go, join Miki in this course. 7 | 8 | 9 | ## Installing 10 | 1. To use these exercise files, you must have the following installed: 11 | - Go 1.17 or higher 12 | - Python 3.10 or higher 13 | 2. Clone this repository into your local machine using the terminal (Mac), CMD (Windows), or a GUI tool like SourceTree. 14 | 15 | 16 | ### Instructor 17 | 18 | Miki Tebeka 19 | 20 | 21 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/miki-tebeka). 22 | 23 | [lil-course-url]: https://www.linkedin.com/learning/go-for-python-developers?dApp=59033956 24 | [lil-thumbnail-url]: https://media.licdn.com/dms/image/C4D0DAQGMZFAtTHBCyA/learning-public-crop_288_512/0/1679938358261?e=2147483647&v=beta&t=8oudFuDz_k2LOT-cnoF2zQOTtoj9nDnJ-bQ4CXw3Fg4 25 | 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | --------------------------------------------------------------------------------