Create 2D bit array from 100 x 100 QR Code - go

Given a QR Code of dimensions 100 x 100, I need to make a 2D bit array (array[100][100] that will hold 1 or 0). To get a better idea of the array I am trying to make, look at the array given in this Stack Overflow question.
After hours of searching, I found a function on Google Code that would appear to get the job done. The problem is that the code is given in a .go file, which my computer cannot open.
The ideal solution would either offer a solution in another language, or suggest the way I should go about using the code I found on Google Code.
Thank you in advance for your help!

If you are looking for encoding an url (or other text) to a QR code array and show a textual presentation of the 2D array, you can rather easily make a command line tool to do this in Go.
Below is a fully working example of such a tool using the go package you mentioned.
In order to compile it and run it, go to http://golang.org where you can find instructions on how to install Go, install external libraries, and compile the tool:
package main
import (
"flag"
"fmt"
"os"
"code.google.com/p/go-qrcode"
)
var (
url = flag.String("url", "", "Url to encode")
level = flag.Int("level", 0, "Recovery level. 0 is lowest, 3 is highest")
)
func main() {
flag.Parse()
if *level < 0 || *level > 3 {
fmt.Println("Level must be between 0 and 3")
os.Exit(1)
}
qr, err := qrcode.New(*url, qrcode.RecoveryLevel(*level))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
printArray(qr.Bitmap())
}
func printArray(a [][]bool) {
fmt.Println("{")
for _, x := range a {
fmt.Print(" {")
out := ""
for _, y := range x {
if y {
out += "1"
} else {
out += "0"
}
fmt.Print(out)
out = ","
}
fmt.Println("}")
}
fmt.Println("}")
}
Usage:
Usage of qrarray.exe:
-level=0: Recovery level. 0 is lowest, 3 is highest
-url="": Url to encode

Related

how to realize mismatch of regexp in golang?

This is a multiple choice question example. I want to get the chinese text like "英国、法国", "加拿大、墨西哥", "葡萄牙、加拿大", "墨西哥、德国" in the content of following code in golang, but it does not work.
package main
import (
"fmt"
"regexp"
"testing"
)
func TestRegex(t *testing.T) {
text := `( B )38.目前,亚马逊美国站后台,除了有美国站点外,还有( )站点。
A.英国、法国B.加拿大、墨西哥
C.葡萄牙、加拿大D.墨西哥、德国
`
fmt.Printf("%q\n", regexp.MustCompile(`[A-E]\.(\S+)?`).FindAllStringSubmatch(text, -1))
fmt.Printf("%q\n", regexp.MustCompile(`[A-E]\.`).Split(text, -1))
}
text:
( B )38.目前,亚马逊美国站后台,除了有美国站点外,还有( )站点。
A.英国、法国B.加拿大、墨西哥
C.葡萄牙、加拿大D.墨西哥、德国
pattern: [A-E]\.(\S+)?
Actual result: [["A.英国、法国B.加拿大、墨西哥" "英国、法国B.加拿大、墨西哥"] ["C.葡萄牙、加拿大D.墨西哥、德国" "葡萄牙、加拿大D.墨西哥、德国"]].
Expect result: [["A.英国、法国" "英国、法国"] ["B.加拿大、墨西哥" "加拿大、墨西哥"] ["C.葡萄牙、加拿大" "葡萄牙、加拿大"] ["D.墨西哥、德国" "墨西哥、德国"]]
I think it might be a greedy mode problem. Because in my code, it reads option A and option B as one option directly.
Non-greedy matching won't solve this, you need positive lookahead, which re2 doesn't support.
As a workaround can just search on the labels and extract the text in between manually.
re := regexp.MustCompile(`[A-E]\.`)
res := re.FindAllStringIndex(text, -1)
results := make([][]string, len(res))
for i, m := range res {
if i < len(res)-1 {
results[i] = []string{text[m[0]:m[1]], text[m[1]:res[i+1][0]]}
} else {
results[i] = []string{text[m[0]:m[1]], text[m[1]:]}
}
}
fmt.Printf("%q\n", results)
Should print
[["A." "英国、法国"] ["B." "加拿大、墨西哥\n"] ["C." "葡萄牙、加拿大"] ["D." "墨西哥、德国\n"]]

How do I parse a currency value as *big.Int in Go?

I want to parse a string like "12.49" into a *big.Int in Go. The resulting *big.Int should represent the amount of cents in the given value, in this case 1249. Here are some more examples of inputs and their expected outputs:
"3": 300
"3.1": 310
".19": 19
I already tried working with *big.Float and its Int function, but realized, that *big.Float does not provide arbitrary precision.
Right now I'm using this algorithm, but it seems fragile (Go Playground link):
func eurToCents(in string) *big.Int {
missingZerosUntilCents := 2
i := strings.Index(in, ".")
if i > -1 {
missingZerosUntilCents -= len(in) - i - 1
if missingZerosUntilCents < 0 {
panic("too many decimal places")
}
}
in = strings.Replace(in, ".", "", 1)
in += strings.Repeat("0", missingZerosUntilCents)
out, ok := big.NewInt(0).SetString(in, 10)
if !ok {
panic(fmt.Sprintf("could not parse '%s' as an interger", in))
}
return out
}
Is there a standard library function or other common way to parse currencies in Go? An external library is not an option.
PS: I'm parsing Nano cryptocurrency values, which have 30 decimal places and a maximum value of 133,248,297.0. That's why I'm asking for *big.Int and not uint64.
Update: Seems like this solution is still buggy, because an inaccurate result is reported after multiplication: https://play.golang.org/p/RS-DC6SeRwz
After revisiting the solution with *big.Float, I realized, that it does work perfectly fine. I think I forgot to use SetPrec on rawPerNano previously. I'm going to provide an example for the Nano cryptocurrency, because it requires many decimal places.
This works as expected (Go Playground link):
func nanoToRaw(in string) *big.Int {
f, _ := big.NewFloat(0).SetPrec(128).SetString(in)
rawPerNano, _ := big.NewFloat(0).SetPrec(128).SetString("1000000000000000000000000000000")
f.Mul(f, rawPerNano)
i, _ := f.Int(big.NewInt(0))
return i
}
Thanks #hymns-for-disco for nudging me in the right direction!

Print multiple rows in parallel Golang

I am attempting to write a horse race simulator with multiple rows.
Each row will represent one horse location calculated by a goroutine.
For some reason the code, when run on the Go Playground, does not output the numbers randomly as happens on my machine.
package main
import (
"math/rand"
"os"
"strconv"
"time"
)
var counter = 0
func main() {
i := 1
horses := 9
for i <= horses {
go run(i)
i++
}
time.Sleep(5000 * time.Millisecond)
print("\ncounter: " + strconv.Itoa(counter))
print("\nEnd of main()")
}
func run(number int) {
var i = 1
var steps = 5
for i <= steps {
print("[" + strconv.Itoa(number) + "]")
rand.Seed(time.Now().UnixNano())
sleep := rand.Intn(10)
time.Sleep(time.Duration(sleep) * time.Millisecond)
i++
counter++
}
if i == steps {
println(strconv.Itoa(number) + " wins")
os.Exit(1)
}
}
Playground: https://play.golang.org/p/pycZ4EdH7SQ
My output unordered is:
[1][5][8][2][3][4][7][9][6][7][9][9][4][3]...
But my question is how would I go about to print the numbers like:
[1][1]
[2][2][2][2][2][2][2][2]
[3][3][3]
...
[N][N][N][N][N]
you may want to check out this stackoverflow answer which uses goterm to move the terminal cursor and allow you to overwrite part of it.
The idea is that once you get to the terminal bit you want to be "dynamic" (much like a videogame screen clear+redraw), you always reposition the cursor and "draw" your "horses" position.
Note that with this you will need to store their positions somewhere, to then "draw" their positions at each "frame".
With this exercise you are getting close to how video games work, and for this you may want to set up a goroutine with a given refresh rate to clear your terminal and render what you want.

Generating a random number in a custom range

I have go script that starts on "localhost:8080/1" with a previous and next links I need to add Random link with custom range that I can change like:
small numbers like 100 to 200 "localhost:8080/100 - 200" and
even to big number like: "16567684686592643791596485465456223131545455682945955"
So:
// Get next and previous page numbers
previous := new(big.Int).Sub(page, one)
next := new(big.Int).Add(page, one)
random :=????
You need to use the package crypto.rand Int() function, which does support big.Int (as opposed to the math.rand package)
See this article (and its playground example):
package main
import (
"fmt"
"math/big"
"crypto/rand"
)
func main() {
var prime1, _ = new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
// Generate random numbers in range [0..prime1]
// Ignore error values
// Don't use this code to generate secret keys that protect important stuff!
x, _ := rand.Int(rand.Reader, prime1)
y, _ := rand.Int(rand.Reader, prime1)
fmt.Printf("x: %v\n", x)
fmt.Printf("y: %v\n", y)
}

List of Strings - golang

I'm trying to make a list of Strings in golang. I'm looking up the package container/list but I don't know how to put in a string. I tried several times, but 0 result.
Should I use another thing instead of lists?
Thanks in advance.
edit: Don't know why are you rating this question with negatives votes...
Modifying the exact example you linked, and changing the ints to strings works for me:
package main
import (
"container/list"
"fmt"
)
func main() {
// Create a new list and put some numbers in it.
l := list.New()
e4 := l.PushBack("4")
e1 := l.PushFront("1")
l.InsertBefore("3", e4)
l.InsertAfter("2", e1)
// Iterate through list and print its contents.
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
}
If you take a look at the source code to the package you linked, it seems that the List type holds a list of Elements. Looking at Element you'll see that it has one exported field called Value which is an interface{} type, meaning it could be literally anything: string, int, float64, io.Reader, etc.
To answer your second question, you'll see that List has a method called Remove(e *Element). You can use it like this:
fmt.Println(l.Len()) // prints: 4
// Iterate through list and print its contents.
for e := l.Front(); e != nil; e = e.Next() {
if e.Value == "4" {
l.Remove(e) // remove "4"
} else {
fmt.Println(e.Value)
}
}
fmt.Println(l.Len()) // prints: 3
By and large, Golang documentation is usually pretty solid, so you should always check there first.
https://golang.org/pkg/container/list/#Element

Resources