Example #1
1
func TestLRUCache(t *testing.T) {
	strategy := NewLRUPeriodFlushStrategy(3, 100, 0)
	storage := NewInMemoryKeyValueStorage(10)
	flusher := &FakeFlusher{}

	cache := NewKeyValueCache(storage, strategy, flusher)
	fmt.Print("Start LRU cache test ...\t")

	for i := 0; i < 10; i++ {
		str := fmt.Sprint(i)
		cache.Show(str, str)
	}

	keys, _ := cache.Keys()
	if !same(convert2string([]int{7, 9, 8}), keys) {
		t.Errorf("should be [7 8 9], but %v", keys)
	}

	if v, _ := cache.Get("1"); v != nil {
		t.Errorf("%v should not be in cache", v)
	}

	cache.Get("7")
	cache.Show("1", "1")

	if v, _ := cache.Get("8"); v != nil {
		keys, _ := cache.Keys()
		t.Errorf("%v should not be in cache; cache content: %v", v, keys)
	}
	fmt.Print("OK\n")
}
// Find all document with an indexed value.
func ExampleTerm_GetAll_optArgs() {
	// Fetch the row from the database
	res, err := DB("examples").Table("heroes").GetAll("man_of_steel").OptArgs(GetAllOpts{
		Index: "code_name",
	}).Run(session)
	if err != nil {
		fmt.Print(err)
		return
	}
	defer res.Close()

	if res.IsNil() {
		fmt.Print("Row not found")
		return
	}

	var hero map[string]interface{}
	err = res.One(&hero)
	if err != nil {
		fmt.Printf("Error scanning database result: %s", err)
		return
	}
	fmt.Print(hero["name"])

	// Output: Superman
}
Example #3
1
func (char *Char) dump(s string) {
	fmt.Print(s, " ");
	for i := 0; i < len(char.field); i++ {
		fmt.Printf("%s:%q ", fieldName[i], char.field[i])
	}
	fmt.Print("\n");
}
Example #4
1
func fail(run string, stdout, stderr bytes.Buffer) {
	msg(fmt.Sprintf("Run %v stdout:", run))
	fmt.Print(stdout.String())

	msg(fmt.Sprintf("Run %v stderr:", run))
	fmt.Print(stderr.String())
}
Example #5
1
func (server *IpcServer)Connect() chan string {
	session := make(chan string, 0)

	go func(c chan string){
		for{
			request := <-c

			if request == "CLOSE" {
				break
			}

			var req Request
			err := json.Unmarshal([]byte(request), &req)
			if err != nil{
				fmt.Println("Invalid request format:", request)
			}

			resp := server.Handle(req.Method, req.Params)
			b, err := json.Marshal(resp)
			c <- string(b)

		}

		fmt.Print("Session closed.")
	}(session)

	fmt.Print("A new session has been created.")
	return session
}
Example #6
1
func printFields(datamap map[string]interface{}, fields string) {
	for k, v := range datamap {
		key := ""
		fieldsslice := strings.Split(fields, ",")
		if fields != "_all" {
			for _, rawfield := range fieldsslice {
				field := strings.TrimSpace(rawfield)
				if strings.EqualFold(field, strings.TrimSpace(k)) {
					key = strings.TrimSpace(k)
				}
			}
		} else {
			key = k
		}

		if key != "" {
			kp := strings.TrimSpace(key)
			fmt.Print(kp)
			fmt.Print(": ")

			if key == "id" {
				fmt.Print(int(v.(float64)))
			} else {
				fmt.Print(v)
			}

			fmt.Print("\n")
		}
	}
}
Example #7
0
func Branch(repo *libgit.Repository, args []string) {
	switch len(args) {
	case 0:
		branches, err := repo.GetBranches()
		if err != nil {
			fmt.Fprintln(os.Stderr, "Could not get list of branches.")
			return
		}
		head := getHeadBranch(repo)
		for _, b := range branches {
			if head == b {
				fmt.Print("* ")
			} else {
				fmt.Print("  ")
			}
			fmt.Println(b)
		}
	case 1:
		if head, err := getHeadId(repo); err == nil {
			if cerr := libgit.CreateBranch(repo.Path, args[0], head); cerr != nil {
				fmt.Fprintf(os.Stderr, "Could not create branch: %s\n", cerr.Error())
			}
		} else {
			fmt.Fprintf(os.Stderr, "Could not create branch: %s\n", err.Error())
		}
	default:
		fmt.Fprintln(os.Stderr, "Usage: go-git branch [branchname]")
	}

}
Example #8
0
func main() {
	files, _ := filepath.Glob(path + "*")
	namesSlice := []string{}
	for _, basename := range files {
		name := strings.TrimSuffix(basename, filepath.Ext(basename))
		namesSlice = append(namesSlice, strings.Replace(name, path, "", -1))
	}
	fmt.Print("var ourskins = \"")
	fmt.Print(strings.Join(namesSlice, ":"))
	fmt.Println("\";")
	fmt.Println("grabbing source from github")
	return
	/* a work in progress */
	cmd := exec.Command("git", "clone", "https://github.com/electronoob/agarmods.git")
	err := cmd.Start()
	if err != nil {
		fmt.Println("some dome error occured: ", err)
	}
	err = cmd.Wait()
	if err != nil {
		fmt.Println("Command finished with: ", err)
	} else {
		cmd := exec.Command("cp", "agarmods/mods.js", "mods.js")
		cmd.Start()
		cmd.Wait()
		cmd = exec.Command("rm", "-rf", "agarmods")
		cmd.Start()
		cmd.Wait()
	}

}
Example #9
0
func main() {
	app := cli.NewApp()
	app.Name = "qunosy"           // ヘルプを表示する際に使用される
	app.Usage = "print arguments" // ヘルプを表示する際に使用される
	app.Version = "0.1.0"         // ヘルプを表示する際に使用される
	absPath, _ := filepath.Abs("../qunosy")
	app.Action = func(c *cli.Context) { // コマンド実行時の処理
		if len(c.Args()) > 1 {
			if c.Args()[0] == "reload" {
				fmt.Println("Reloading qiita log ...")
				reload := exec.Command("sh", absPath+"/reload.sh", c.Args()[1])
				reloadOut, err := reload.Output()
				if err != nil {
					fmt.Println(err.Error())
					return
				}
				fmt.Print(string(reloadOut))
			} else {
				return
			}
		} else {
			qunosy := exec.Command("sh", absPath+"/qunosy.sh")
			qunosyOut, err := qunosy.Output()
			if err != nil {
				fmt.Println(err.Error())
				return
			}
			fmt.Print(string(qunosyOut))
		}
	}
	app.Run(os.Args)
}
Example #10
0
func main() {
	//  Socket to receive messages on
	receiver, _ := zmq.NewSocket(zmq.PULL)
	defer receiver.Close()
	receiver.Bind("tcp://*:5558")

	//  Socket for worker control
	controller, _ := zmq.NewSocket(zmq.PUB)
	defer controller.Close()
	controller.Bind("tcp://*:5559")

	//  Wait for start of batch
	receiver.Recv(0)

	//  Start our clock now
	start_time := time.Now()

	//  Process 100 confirmations
	for task_nbr := 0; task_nbr < 100; task_nbr++ {
		receiver.Recv(0)
		if task_nbr%10 == 0 {
			fmt.Print(":")
		} else {
			fmt.Print(".")
		}
	}
	fmt.Println("\nTotal elapsed time:", time.Since(start_time))

	//  Send kill signal to workers
	controller.Send("KILL", 0)

	//  Finished
	time.Sleep(time.Second) //  Give 0MQ time to deliver
}
Example #11
0
func printPath(path []int, start int, end int) {
	fmt.Print("[ ")
	for i := start; i <= end; i++ {
		fmt.Print(path[i], " ")
	}
	fmt.Print("]\n")
}
Example #12
0
func main() {

	b, err := ioutil.ReadFile("D:\\James\\Downloads\\kargerMinCut.txt")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	lines := strings.Split(string(b), "\n")

	arr := make([][]int, 0, len(lines))

	for _, v := range lines {
		textints := strings.Split(v, "\t")
		subarr := make([]int, 0, len(textints))
		for _, w := range textints {
			n, err := strconv.Atoi(w)
			if err != nil {
				fmt.Println("Error yo: ", err)
				continue
			}
			subarr = append(subarr, n)
		}
		arr = append(arr, subarr)
	}
	for _, v := range arr {
		for _, w := range v {
			fmt.Print(w, "\t")
		}
		fmt.Print("\r\n")
	}
}
Example #13
0
func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:8081")

	if err != nil {
		fmt.Println("connect to server error!")
		return
	}
	defer conn.Close()

	message, _ := bufio.NewReader(conn).ReadString('\n')
	fmt.Print(message)
	for {
		// read in input from stdin
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("Text to send: ")
		text, _ := reader.ReadString('\n')

		// send to socket
		_, _ = conn.Write([]byte(text))
		//fmt.Fprintf(conn, text + "\n")

		// listen for reply
		message, _ := bufio.NewReader(conn).ReadString('\n')
		if (message == "Good bye\n") {
			break
		} else {
			fmt.Print("Message from server: " + message)
		}
	}
	fmt.Println("conn is closed")
}
Example #14
0
func main() {
	var infile = flag.String("infile", "input13.txt", "Input file")
	flag.Parse()

	f, err := os.Open(*infile)
	if err != nil {
		log.Fatal(err)
	}
	rdr := bufio.NewReader(f)
	edges := make(map[string]map[string]int64)
	for {
		line, err := rdr.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		AddEdge(edges, line)
	}
	names := make([]string, len(edges))
	i := 0
	for name, _ := range edges {
		names[i] = name
		i++
		if edges["me"] == nil {
			edges["me"] = make(map[string]int64)
		}
		edges["me"][name] = 0
		edges[name]["me"] = 0
	}
	names = append(names, "me")
	fmt.Print("names: ", names, "\n")
	fmt.Print(FindHappiest(edges, names))
}
Example #15
0
File: main.go Project: Oooska/irc
//A barebones IRC 'client' in the loosest sense of the word.
//Takes input from console. If command starts with a '/', everything after is sent as a raw IRC command.
//Otherwise the first argument is considered the channel/username, and the rest of the line is the message to send
// as a privmsg.
func main() {
	flag.Parse()

	fmt.Print("Simple Text-Based IRC Test Client\n\n")

	fmt.Printf("Connecting to %s . . . \n", *address)

	//LogClientHandler will handle printing out to stdio unless we change the default logger
	client, err := irc.NewClient(*address, *ssl, irc.LogHandler)

	if err != nil {
		log.Fatalf("Error: %s", err.Error())
	}
	fmt.Print("Connected.\n\n")

	client.Send(irc.UserMessage(*username, "host", "domain", "realname"))
	client.Send(irc.NickMessage(*nick))
	client.Send(irc.JoinMessage("#go_test"))

	//Listen for input.
	go readInput(client)

	for { //Continuously read from the client until an error occurs
		_, err := client.Read()
		if err != nil {
			fmt.Printf("ERROR: %s\n", err.Error())
			fmt.Print("Exiting...")
			return
		}
	}
}
Example #16
0
func cmdExchange(cmd command) {
	switch cmd.Action {
	case "PRINT", "DISPLAY":
		com.ColorLog("[%s] DEBUG( %s ) --> %s\n", levelToCmdFormat(cmd.Level),
			getTitle(cmd), watchParametersToStr(cmd.Parameters))
	case "BREAK":
		if App.PrintStack {
			com.ColorLog("[%s] BREAK:\n# %s #", levelToCmdFormat(cmd.Level),
				cmd.Parameters["go.stack"])

			if !App.SkipSuspend && App.PrintSource {
				fmt.Print("press ENTER to view source...")
				fmt.Scanln()
			}
		} else {
			com.ColorLog("[%s] BREAK: 'print_stack' disenabled.\n",
				levelToCmdFormat(cmd.Level))
		}

		if App.PrintSource {
			line, _ := strconv.Atoi(cmd.Parameters["go.line"])
			fmt.Println()
			com.ColorLog("[%s] Source( %s ):\n%s", levelToCmdFormat(cmd.Level),
				cmd.Parameters["go.file"], getFileSource(cmd.Parameters["go.file"], line))
		}

		if !App.SkipSuspend {
			fmt.Print("press ENTER to continue...")
			fmt.Scanln()
		}
	}
}
Example #17
0
func (tokens LogTokens) Print() {
	defer color.ResetColor()

	var defColor color.Color = color.White
	var defBright bool = true

	for _, token := range tokens {
		if token.Type >= TOKEN_DEBUG {
			defColor, defBright, _ = token.Type.getFgColor()
		}
	}

	for _, token := range tokens {
		fg, bright, specific := token.Type.getFgColor()
		if !specific {
			fg = defColor
			bright = defBright
		}

		color.Foreground(fg, bright)
		fmt.Print(token.Text)
	}

	fmt.Print("\n")
}
Example #18
0
func (r Rspecish) Output(results <-chan []resource.TestResult, startTime time.Time) (exitCode int) {
	testCount := 0
	var failed []resource.TestResult
	for resultGroup := range results {
		for _, testResult := range resultGroup {
			if testResult.Successful {
				fmt.Printf(green("."))
			} else {
				fmt.Printf(red("F"))
				failed = append(failed, testResult)
			}
			testCount++
		}
	}

	fmt.Print("\n\n")
	if len(failed) > 0 {
		color.Red("Failures:")
		for _, testResult := range failed {
			fmt.Println(humanizeResult(testResult))
		}
		fmt.Print("\n")
	}

	fmt.Printf("Total Duration: %.3fs\n", time.Since(startTime).Seconds())
	if len(failed) > 0 {
		color.Red("Count: %d, Failed: %d\n", testCount, len(failed))
		return 1
	}
	color.Green("Count: %d, Failed: %d\n", testCount, len(failed))
	return 0
}
Example #19
0
// MustCheck runs a consistency check on the database and panics if any errors are found.
func (db *TestDB) MustCheck() {
	db.Update(func(tx *bolt.Tx) error {
		// Collect all the errors.
		var errors []error
		for err := range tx.Check() {
			errors = append(errors, err)
			if len(errors) > 10 {
				break
			}
		}

		// If errors occurred, copy the DB and print the errors.
		if len(errors) > 0 {
			var path = tempfile()
			tx.CopyFile(path, 0600)

			// Print errors.
			fmt.Print("\n\n")
			fmt.Printf("consistency check failed (%d errors)\n", len(errors))
			for _, err := range errors {
				fmt.Println(err)
			}
			fmt.Println("")
			fmt.Println("db saved to:")
			fmt.Println(path)
			fmt.Print("\n\n")
			os.Exit(-1)
		}

		return nil
	})
}
Example #20
0
func printDag(nd *mdag.Node, ds mdag.DAGService, indent int) {
	pbd, err := ft.FromBytes(nd.Data)
	if err != nil {
		panic(err)
	}

	for i := 0; i < indent; i++ {
		fmt.Print(" ")
	}
	fmt.Printf("{size = %d, type = %s, children = %d", pbd.GetFilesize(), pbd.GetType().String(), len(pbd.GetBlocksizes()))
	if len(nd.Links) > 0 {
		fmt.Println()
	}
	for _, lnk := range nd.Links {
		child, err := lnk.GetNode(context.Background(), ds)
		if err != nil {
			panic(err)
		}
		printDag(child, ds, indent+1)
	}
	if len(nd.Links) > 0 {
		for i := 0; i < indent; i++ {
			fmt.Print(" ")
		}
	}
	fmt.Println("}")
}
Example #21
0
func main() {
	if len(os.Args) > 1 {
		for _, arg := range os.Args[1:] {
			switch arg {
			case "-v", "--verbose":
				verbose = true
			case "-i", "--interactive":
				interactive = true
			case "-h", "--help":
				fmt.Print(`
Usage: myip [options]
where options include:
	--local, -l		return the local IP address(es)
	--verbose, -v		enable verbose output
	--interactive, -i	enable interactive mode
	--help, -h		print this help message
`)
				return
			case "-l", "--local":
				printLocalIP()
				return
			default:
				fmt.Print(`Invalid option: '` + arg + `'
`)
				return
			}
		}
	}

	printIP()
}
Example #22
0
func runTests() {
	fmt.Print(HIDE)
	db, ub := download(), upload()
	fmt.Print(SHOW)
	fmt.Printf("\n\nYour download speed is %.2f Mbps.\n", db)
	fmt.Printf("Your upload speed is %.2f Mbps.\n", ub)
}
Example #23
0
func Example_beforeAfter() {
	app := App("app", "App")
	bench := app.BoolOpt("b bench", false, "Measure execution time")

	var t0 time.Time

	app.Before = func() {
		if *bench {
			t0 = time.Now()
		}
	}

	app.After = func() {
		if *bench {
			d := time.Since(t0)
			fmt.Printf("Command execution took: %vs", d.Seconds())
		}
	}

	app.Command("cmd1", "first command", func(cmd *Cmd) {
		cmd.Action = func() {
			fmt.Print("Running command 1")
		}
	})

	app.Command("cmd2", "second command", func(cmd *Cmd) {
		cmd.Action = func() {
			fmt.Print("Running command 2")
		}
	})

	app.Run(os.Args)
}
Example #24
0
func emitZeframOption(t *astgen.OptionType) {
	fmt.Print("type AST")
	fmt.Printf("%v", t.Name)
	fmt.Print(" = ")
	fmt.Printf("%v", optionList(t))
	fmt.Print("\n")
}
// Find a document and merge another document with it.
func ExampleTerm_Get_merge() {
	// Fetch the row from the database
	res, err := DB("examples").Table("heroes").Get(4).Merge(map[string]interface{}{
		"powers": []string{"speed"},
	}).Run(session)
	if err != nil {
		fmt.Print(err)
		return
	}
	defer res.Close()

	if res.IsNil() {
		fmt.Print("Row not found")
		return
	}

	var hero map[string]interface{}
	err = res.One(&hero)
	if err != nil {
		fmt.Printf("Error scanning database result: %s", err)
		return
	}
	fmt.Printf("%s: %v", hero["name"], hero["powers"])

	// Output: The Flash: [speed]
}
Example #26
0
File: main.go Project: h8liu/golang
func main() {
	flag.Parse()

	var a [MAXDIM * MAXDIM]int32
	for i := 2; i < *dim; i += 8 {
		for j := 2; j < *dim-3; j += 8 {
			for y := 0; y < 3; y++ {
				a[i**dim+j+y] = 1
			}
		}
	}

	life.Run(*gen, *dim, *dim, a[:])

	for i := 0; i < *dim; i++ {
		for j := 0; j < *dim; j++ {
			if a[i**dim+j] == 0 {
				fmt.Print(" ")
			} else {
				fmt.Print("X")
			}
		}
		fmt.Print("\n")
	}
}
Example #27
0
func TestXML(t *testing.T) {
	feed := Channel{
		Title:         "test",
		Description:   "test",
		Link:          "http://cj-jackson.com/",
		LastBuildDate: time.Now(),
		PubDate:       time.Now(),
		Updated:       time.Now(),
		Ttl:           1800,
		Item: []Item{
			Item{
				Title:       "test",
				Description: "test",
				Link:        "http://cj-jackson.com/test/",
				PubDate:     time.Now(),
				Updated:     time.Now(),
				Name:        "Christopher John Jackson",
				Email:       "himself@cj-jackson.com",
			},
		},
	}

	fmt.Print(feed.RSS(), "\r\n\r\n")
	fmt.Print(feed.Atom(), "\r\n\r\n")
}
Example #28
0
// LimitsSet sets an app's limits.
func LimitsSet(appID string, limits []string, limitType string) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	limitsMap := parseLimits(limits)

	fmt.Print("Applying limits... ")

	quit := progress()
	configObj := api.Config{}

	if limitType == "cpu" {
		configObj.CPU = limitsMap
	} else {
		configObj.Memory = limitsMap
	}

	_, err = config.Set(c, appID, configObj)

	quit <- true
	<-quit

	if err != nil {
		return err
	}

	fmt.Print("done\n\n")

	return LimitsList(appID)
}
Example #29
0
func display(r io.Reader) error {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return err
	}

	width, height := widthAndHeight()

	fmt.Print("\033]1337;")
	fmt.Printf("File=inline=1")
	if width != "" || height != "" {
		if width != "" {
			fmt.Printf(";width=%s", width)
		}
		if height != "" {
			fmt.Printf(";height=%s", height)
		}
	}
	if *preserveAspectRatio {
		fmt.Print("preserveAspectRatio=1")
	}
	fmt.Print(":")
	fmt.Printf("%s", base64.StdEncoding.EncodeToString(data))
	fmt.Print("\a\n")

	return nil
}
Example #30
0
func (s *SudokuSolver) Eureka(O *Solution) {
	grid := make([][]int, s.Dim)
	for i := 0; i < s.Dim; i++ {
		grid[i] = make([]int, s.Dim)
	}
	for _, n := range *O {
		nodes := make([]*Node, 4)
		nodes = append(nodes, n)
		for m := n.Right; n != m; m = m.Right {
			nodes = append(nodes, m)
		}
		x, y, digit := s.coverToGrid(nodes)
		grid[x][y] = digit
	}
	sdim := int(math.Sqrt(float64(s.Dim)))
	delim := "+" + strings.Repeat(strings.Repeat("-", sdim*2+1)+"+", sdim)
	for i, line := range grid {
		if i%sdim == 0 {
			fmt.Println(delim)
		}
		for j, cell := range line {
			if j%sdim == 0 {
				if j > 0 {
					fmt.Print(" ")
				}
				fmt.Print("|")
			}
			fmt.Print(" ", cell)
		}
		fmt.Print(" |\n")
	}
	fmt.Println(delim)
}