Archiving a bunch of old stuff

This commit is contained in:
Dan Buch
2015-06-22 13:15:42 -05:00
parent a6ec1d560e
commit bd1abd8734
395 changed files with 1 additions and 76 deletions

4
oldstuff/gotime/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
/bin/
/.env
/.installation/go/
/src/github.com/

View File

@@ -0,0 +1,5 @@
go/src/all.bash:
hg clone -u release https://code.google.com/p/go
go/bin/go: go/src/all.bash
cd go/src && ./all.bash

34
oldstuff/gotime/Makefile Normal file
View File

@@ -0,0 +1,34 @@
TARGETS = \
github.com/meatballhat/box-o-sand/gotime/amqpfun \
github.com/meatballhat/box-o-sand/gotime/amqpfun-runner \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/buffered-channels \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/channels \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/exercise-fibonacci-closure \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/exercise-http-handlers \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/exercise-maps \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/exercise-rot13-reader \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/exercise-slices \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/exercise-sqrt \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/generic-maps \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/goroutines \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/hello-web \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/maps \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/ranges \
github.com/meatballhat/box-o-sand/gotime/gotour-artifacts/selects \
github.com/meatballhat/box-o-sand/gotime/junkdrawer/greppish \
github.com/meatballhat/box-o-sand/gotime/junkdrawer/reflectish \
github.com/meatballhat/box-o-sand/gotime/junkdrawer/randimg
test: build
go test -x -v $(TARGETS)
build: deps
go install -x $(TARGETS)
deps:
go get -n -x $(TARGETS)
clean:
go clean -x -i $(TARGETS)
.PHONY: test build clean fmt

View File

@@ -0,0 +1,24 @@
package main
import (
"fmt"
"os"
)
import (
"github.com/meatballhat/box-o-sand/gotime/amqpfun"
)
const USAGE = "Usage: amqpfun-runner (publish|consume)"
func main() {
if len(os.Args) < 2 {
fmt.Println(USAGE)
os.Exit(1)
}
if os.Args[1] == "publish" {
amqpfun.Publish()
} else if os.Args[1] == "consume" {
amqpfun.Consume()
}
}

View File

@@ -0,0 +1,185 @@
package amqpfun
import (
"log"
"os"
"os/signal"
"runtime"
"time"
)
import (
"github.com/streadway/amqp"
)
func Publish() {
// Connects opens an AMQP connection from the credentials in the URL.
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatalf("connection.open: %s", err)
}
// This waits for a server acknowledgment which means the sockets will have
// flushed all outbound publishings prior to returning. It's important to
// block on Close to not lose any publishings.
defer conn.Close()
c, err := conn.Channel()
if err != nil {
log.Fatalf("channel.open: %s", err)
}
// We declare our topology on both the publisher and consumer to ensure they
// are the same. This is part of AMQP being a programmable messaging model.
//
// See the Channel.Consume example for the complimentary declare.
err = c.ExchangeDeclare("logs", "topic", true, false, false, false, nil)
if err != nil {
log.Fatal("exchange.declare: %s", err)
}
// Prepare this message to be persistent. Your publishing requirements may
// be different.
msg := amqp.Publishing{
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
ContentType: "text/plain",
Body: []byte("Go Go AMQP!"),
}
// This is not a mandatory delivery, so it will be dropped if there are no
// queues bound to the logs exchange.
err = c.Publish("logs", "info", false, false, msg)
if err != nil {
// Since publish is asynchronous this can happen if the network connection
// is reset or if the server has run out of resources.
log.Fatal("basic.publish: %s", err)
}
}
func Consume() {
// Connects opens an AMQP connection from the credentials in the URL.
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatalf("connection.open: %s", err)
}
defer conn.Close()
c, err := conn.Channel()
if err != nil {
log.Fatalf("channel.open: %s", err)
}
// We declare our topology on both the publisher and consumer to ensure they
// are the same. This is part of AMQP being a programmable messaging model.
//
// See the Channel.Publish example for the complimentary declare.
err = c.ExchangeDeclare("logs", "topic", true, false, false, false, nil)
if err != nil {
log.Fatal("exchange.declare: %s", err)
}
// Establish our queue topologies that we are responsible for
type bind struct {
queue string
key string
}
bindings := []bind{
bind{"page", "alert"},
bind{"email", "info"},
bind{"firehose", "#"},
}
for _, b := range bindings {
_, err = c.QueueDeclare(b.queue, true, false, false, false, nil)
if err != nil {
log.Fatal("queue.declare: %s", err)
}
err = c.QueueBind(b.queue, b.key, "logs", false, nil)
if err != nil {
log.Fatal("queue.bind: %s", err)
}
}
// Set our quality of service. Since we're sharing 3 consumers on the same
// channel, we want at least 3 messages in flight.
err = c.Qos(3, 0, false)
if err != nil {
log.Fatal("basic.qos: %s", err)
}
// Establish our consumers that have different responsibilities. Our first
// two queues do not ack the messages on the server, so require to be acked
// on the client.
pages, err := c.Consume("page", "pager", false, false, false, false, nil)
if err != nil {
log.Fatal("basic.consume: %s", err)
}
go func() {
for page := range pages {
// ... this consumer is responsible for sending pages per log
log.Printf("Processing page: %+v\n", page)
page.Ack(false)
}
}()
// Notice how the concern for which messages arrive here are in the AMQP
// topology and not in the queue. We let the server pick a consumer tag this
// time.
emails, err := c.Consume("email", "", false, false, false, false, nil)
if err != nil {
log.Fatal("basic.consume: %s", err)
}
go func() {
for email := range emails {
// ... this consumer is responsible for sending emails per log
log.Printf("Processing email: %+v\n", email)
email.Ack(false)
}
}()
// This consumer requests that every message is acknowledged as soon as it's
// delivered.
firehose, err := c.Consume("firehose", "", true, false, false, false, nil)
if err != nil {
log.Fatal("basic.consume: %s", err)
}
// To show how to process the items in parallel, we'll use a work pool.
for i := 0; i < runtime.NumCPU(); i++ {
go func(work <-chan amqp.Delivery) {
for drop := range work {
// ... this consumer pulls from the firehose and doesn't need to acknowledge
log.Printf("Processing firehose drop: %+v\n", drop)
}
}(firehose)
}
// // Wait until you're ready to finish, could be a signal handler here.
// time.Sleep(10 * time.Second)
q := make(chan os.Signal)
signal.Notify(q, os.Interrupt)
log.Println("Waiting...")
<-q
log.Println("Shutting down...")
// Cancelling a consumer by name will finish the range and gracefully end the
// goroutine
err = c.Cancel("pager", false)
if err != nil {
log.Fatal("basic.cancel: %s", err)
}
// deferred closing the Connection will also finish the consumer's ranges of
// their delivery chans. If you need every delivery to be processed, make
// sure to wait for all consumers goroutines to finish before exiting your
// process.
}

View File

@@ -0,0 +1,29 @@
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int, 2)
q := make(chan bool)
go func(c chan int) {
for i := range c {
fmt.Println("\t", i, "<- popped")
time.Sleep(300 * time.Millisecond)
}
}(c)
go func(c chan int) {
i := 0
for {
c <- i
fmt.Println("pushed ->", i)
i += 1
}
}(c)
<-q
}

View File

@@ -0,0 +1,31 @@
package main
import (
"fmt"
"math"
"time"
)
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
to_sleep := time.Duration(100*math.Abs(float64(sum))) * time.Millisecond
fmt.Printf("Sleeping %s...\n", to_sleep)
time.Sleep(to_sleep)
c <- sum
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x := <-c
fmt.Printf("x = %d\n", x)
y := <-c
fmt.Printf("y = %d\n", y)
fmt.Println(x, y, x+y)
}

View File

@@ -0,0 +1,23 @@
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev := 0
cur := 1
return func() int {
old_cur := cur
cur = prev + cur
prev = old_cur
return cur
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}

View File

@@ -0,0 +1,32 @@
package main
import (
"fmt"
"net/http"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (s String) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprintf(w, "%s\n", s)
}
func (s Struct) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprintf(w, "%s%s %s", s.Greeting, s.Punct, s.Who)
}
func main() {
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
http.ListenAndServe("localhost:4000", nil)
}

View File

@@ -0,0 +1,19 @@
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
counts := make(map[string]int)
words := strings.Fields(s)
for _, word := range words {
counts[word]++
}
return counts
}
func main() {
wc.Test(WordCount)
}

View File

@@ -0,0 +1,97 @@
package main
import (
"fmt"
"io"
"os"
"strings"
)
var lookupTable = map[byte]byte{
'A': 'N',
'B': 'O',
'C': 'P',
'D': 'Q',
'E': 'R',
'F': 'S',
'G': 'T',
'H': 'U',
'I': 'V',
'J': 'W',
'K': 'X',
'L': 'Y',
'M': 'Z',
'N': 'A',
'O': 'B',
'P': 'C',
'Q': 'D',
'R': 'E',
'S': 'F',
'T': 'G',
'U': 'H',
'V': 'I',
'W': 'J',
'X': 'K',
'Y': 'L',
'Z': 'M',
'a': 'n',
'b': 'o',
'c': 'p',
'd': 'q',
'e': 'r',
'f': 's',
'g': 't',
'h': 'u',
'i': 'v',
'j': 'w',
'k': 'x',
'l': 'y',
'm': 'z',
'n': 'a',
'o': 'b',
'p': 'c',
'q': 'd',
'r': 'e',
's': 'f',
't': 'g',
'u': 'h',
'v': 'i',
'w': 'j',
'x': 'k',
'y': 'l',
'z': 'm',
}
type rot13Reader struct {
reader io.Reader
}
func (rot *rot13Reader) Read(p []byte) (i int, err error) {
if len(p) == 0 {
return 0, nil
}
buf := make([]byte, len(p))
i, err = rot.reader.Read(buf)
var (
b, c byte
found bool
)
for i := range buf {
b = buf[i]
c, found = lookupTable[b]
if found {
p[i] = c
} else {
p[i] = b
}
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
fmt.Println("")
}

View File

@@ -0,0 +1,20 @@
package main
import (
"code.google.com/p/go-tour/pic"
)
func Pic(dx, dy int) [][]uint8 {
cols := make([][]uint8, dy)
for i := range cols {
cols[i] = make([]uint8, dx)
for j := range cols[i] {
cols[i][j] = uint8(j ^ i)
}
}
return cols
}
func main() {
pic.Show(Pic)
}

View File

@@ -0,0 +1,25 @@
package main
import (
"fmt"
"math"
)
// using Newton's method
func Sqrt(x float64) float64 {
z := x - (x * 0.1)
for i := 0; i < 1000; i++ {
newZ := z - (((z * z) - x) / 2 * z)
diff := math.Abs(newZ) - math.Abs(z)
if math.Abs(diff) < 0.01 {
return newZ
}
z = newZ
}
return z
}
func main() {
fmt.Printf("stdlib -> %f\n", math.Sqrt(2))
fmt.Printf("newton -> %f\n", Sqrt(2))
}

View File

@@ -0,0 +1,37 @@
package main
import (
"fmt"
"time"
)
type Shoe struct {
Hamsters uint8
Tacos []string
}
type Cheese struct {
Holes float64
Flavors map[string]string
ShelfLife time.Time
}
func main() {
v := make(map[string]interface{})
v["loafer"] = &Shoe{
Hamsters: uint8(49),
Tacos: []string{"spicy", "crunchy"},
}
flavors := make(map[string]string)
flavors["fruit01"] = "grape"
flavors["fruit02"] = "apple"
v["cheddar"] = &Cheese{
Holes: float64(9.2),
Flavors: flavors,
ShelfLife: time.Date(1999, time.Month(8), 12, 7, 15, 22, 0, time.UTC),
}
fmt.Printf("v = %+v\n", v)
fmt.Printf("v[\"loafer\"] = %+v\n", v["loafer"])
fmt.Printf("v[\"cheddar\"] = %+v\n", v["cheddar"])
}

View File

@@ -0,0 +1,18 @@
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}

View File

@@ -0,0 +1,19 @@
package main
import (
"fmt"
"net/http"
)
type Hello struct{}
func (h Hello) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "Hello!\n")
}
func main() {
var h Hello
http.ListenAndServe("localhost:4000", h)
}

View File

@@ -0,0 +1,18 @@
// From go-tour #28
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex
func main() {
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, 74.39967,
}
fmt.Println(m["Bell Labs"])
}

View File

@@ -0,0 +1,13 @@
package main
import "fmt"
func main() {
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i)
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}

View File

@@ -0,0 +1,39 @@
package main
import (
"fmt"
"os"
"strconv"
)
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x + y
case <- quit:
return
}
}
}
func main() {
count := 10
if len(os.Args) > 1 {
var err error
if count, err = strconv.Atoi(os.Args[1]); err != nil {
fmt.Fprintln(os.Stderr, os.Args[1], "is not an int!")
os.Exit(1)
}
}
c := make(chan int)
quit := make(chan int)
go func(count int) {
for i := 0; i < count; i++ {
fmt.Println(<-c)
}
quit <- 0
}(count)
fibonacci(c, quit)
}

View File

@@ -0,0 +1,51 @@
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"regexp"
)
const USAGE = `Usage: greppish <regex> [filename]
Prints lines matching <regex> in [filename] or standard input.`
func main() {
if len(os.Args) < 2 {
fmt.Println(USAGE)
os.Exit(1)
}
regMatch, err := regexp.Compile(os.Args[1])
if err != nil {
log.Fatal("Problem compiling regex: ", err)
}
inbuf := bufio.NewReader(os.Stdin)
if len(os.Args) > 2 {
infile, err := os.Open(os.Args[2])
if err != nil {
log.Fatal("Problem opening input file: ", err)
}
inbuf = bufio.NewReader(infile)
}
var line string
for {
line, err = inbuf.ReadString('\n')
if err != nil {
if err == io.EOF {
os.Exit(0)
}
log.Fatal("Problem reading input: ", err)
}
if regMatch.MatchString(line) {
fmt.Printf(line)
}
}
}

View File

@@ -0,0 +1,52 @@
package main
import (
"fmt"
"flag"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
var (
outfile = flag.String("o", "randimg.png", "Output PNG file name")
)
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
out, err := os.Create(*outfile)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
imgRect := image.Rect(0, 0, 200, 200)
img := image.NewGray(imgRect)
draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
for y := 0; y < 200; y += 10 {
for x := 0; x < 200; x += 10 {
fill := &image.Uniform{color.Black}
if rand.Intn(10) % 2 == 0 {
fill = &image.Uniform{color.White}
}
draw.Draw(img, image.Rect(x, y, x+10, y+10), fill, image.ZP, draw.Src)
}
}
err = png.Encode(out, img)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(2)
}
fmt.Printf("Wrote random image to \"%s\"\n", *outfile)
os.Exit(0)
}

View File

@@ -0,0 +1,41 @@
package main
import (
"fmt"
"reflect"
)
type Fooer interface {
Foo(int) int
}
type Bar struct {
SomeField int
}
func (this *Bar) Foo(x int) int {
return x
}
type Baz struct {
SomeField int
}
func (this Baz) Foo(x int) int {
return x
}
func main() {
var bar, baz Fooer
bar = &Bar{
SomeField: 5,
}
baz = Baz{
SomeField: 5,
}
fmt.Println(reflect.ValueOf(baz).FieldByName("SomeField"))
fmt.Println(reflect.Indirect(reflect.ValueOf(bar)).FieldByName("SomeField"))
}