//  PrintMap prints a map - recursing through submaps
// concrete types, like map[float64]map[int]float64
//	  would have to be converted element by element
//   to map[interface{}]interface{}
// the json.indent function might be similar
// but I did not bring it to work
func PrintMapRecursive(m1 map[interface{}]interface{}, depth int) string {
	b1 := new(bytes.Buffer)
	fiveSpaces := "       " // html spaces
	cxIndent := fmt.Sprint(depth * 40)
	depthStyle := ""
	if depth == 0 {
		depthStyle = "margin-top:8px; border-top: 1px solid #aaa;"
	} else {
		darkening := 16 - 2*depth
		bgc := fmt.Sprintf("%x%x%x", darkening, darkening, darkening)
		depthStyle = "margin:0;padding:0;background-color:#" + bgc + ";"
	}
	for k1, m2 := range m1 {
		b1.WriteString("<div style='" + depthStyle + "margin-left:" + cxIndent + "px;'>\n")
		b1.WriteString(fmt.Sprint(k1))
		//b1.WriteString( "<br>\n" )
		switch typedvar := m2.(type) {
		default:
			type_unknown := fmt.Sprintf("<br>\n &nbsp; &nbsp;  --this type switch does not support type %#v", typedvar)
			//panic(type_unknown)
			b1.WriteString(fiveSpaces + fmt.Sprintf("%#v", typedvar) + type_unknown)
		case string:
			b1.WriteString(fiveSpaces + typedvar)
		case int, float64:
			b1.WriteString(fiveSpaces + fmt.Sprint(typedvar))
		case nil:
			b1.WriteString("nil interface")
		case map[interface{}]interface{}:
			b1.WriteString(PrintMapRecursive(typedvar, depth+1))
		}
		b1.WriteString("<br>\n")
		b1.WriteString("</div>\n")
	}
	return b1.String()
}
Exemple #2
1
func (entry *Entry) Panic(args ...interface{}) {
	if entry.Logger.Level >= Panic {
		msg := entry.log("panic", Panic, fmt.Sprint(args...))
		panic(msg)
	}
	panic(fmt.Sprint(args...))
}
// DescribeCdnDomainBaseDetail version 2014-11-11
//
// required parameters:
//  name: DomainName, type: string
//
// optional parameters:
//  name: OwnerId, type: int64
//  name: ResourceOwnerAccount, type: string
//  name: ResourceOwnerId, type: int64
//  name: _method, type: string, optional values: GET|POST
//  name: _region, type: string
//  name: _scheme, type: string, optional values: http|https
func (api API) DescribeCdnDomainBaseDetail(DomainName string, optional openapi.M) (*DescribeCdnDomainBaseDetailResponse, error) {
	args := NewParams()

	args.Query.Set("Action", "DescribeCdnDomainBaseDetail")
	args.Query.Set("DomainName", DomainName)
	if v, ok := optional["OwnerId"]; ok {
		if OwnerId, ok := v.(int64); ok {
			args.Query.Set("OwnerId", fmt.Sprint(OwnerId))
		} else {
			return nil, errors.New("OwnerId must be int64")
		}
	}
	if v, ok := optional["ResourceOwnerAccount"]; ok {
		if ResourceOwnerAccount, ok := v.(string); ok {
			args.Query.Set("ResourceOwnerAccount", ResourceOwnerAccount)
		} else {
			return nil, errors.New("ResourceOwnerAccount must be string")
		}
	}
	if v, ok := optional["ResourceOwnerId"]; ok {
		if ResourceOwnerId, ok := v.(int64); ok {
			args.Query.Set("ResourceOwnerId", fmt.Sprint(ResourceOwnerId))
		} else {
			return nil, errors.New("ResourceOwnerId must be int64")
		}
	}
	if v, ok := optional["_method"]; ok {
		if s, ok := v.(string); ok {
			if !openapi.IsIn(s, "GET|POST") {
				return nil, errors.New("_method must be GET|POST")
			}
			args.Method = s
		} else {
			return nil, errors.New("_method must be string")
		}
	}
	if v, ok := optional["_region"]; ok {
		if s, ok := v.(string); ok {
			args.Region = s
		} else {
			return nil, errors.New("_region must be string")
		}
	}
	if v, ok := optional["_scheme"]; ok {
		if s, ok := v.(string); ok {
			if !openapi.IsIn(s, "http|https") {
				return nil, errors.New("_scheme must be http|https")
			}
			args.Scheme = s
		} else {
			return nil, errors.New("_scheme must be string")
		}
	}

	result := new(DescribeCdnDomainBaseDetailResponse)
	if err := api.Service.Do(result, args); err != nil {
		return nil, err
	}
	return result, nil
}
Exemple #4
1
func parseGauges(info string) map[string]int64 {
	gauges_with_values := map[string]int64{
		"blocked_clients":           0,
		"connected_clients":         0,
		"instantaneous_ops_per_sec": 0,
		"latest_fork_usec":          0,
		"mem_fragmentation_ratio":   0,
		"migrate_cached_sockets":    0,
		"pubsub_channels":           0,
		"pubsub_patterns":           0,
		"uptime_in_seconds":         0,
		"used_memory":               0,
		"used_memory_lua":           0,
		"used_memory_peak":          0,
		"used_memory_rss":           0,
	}
	color.White("-------------------")
	color.White("GAUGES:")
	for gauge, _ := range gauges_with_values {
		r, _ := regexp.Compile(fmt.Sprint(gauge, ":([0-9]*)"))
		matches := r.FindStringSubmatch(info)
		if matches == nil {
			color.Yellow(fmt.Sprint("WARN: ", gauge, "is not displayed in redis info"))
		} else {
			value := matches[len(matches)-1]
			color.Cyan(fmt.Sprint(gauge, ": ", value))
			v, _ := strconv.ParseInt(value, 10, 64)
			gauges_with_values[gauge] = v
		}
	}
	return gauges_with_values
}
Exemple #5
1
func TestStatic(t *testing.T) {
	var (
		instances = []string{"foo", "bar", "baz"}
		endpoints = map[string]endpoint.Endpoint{
			"foo": func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
			"bar": func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
			"baz": func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
		}
		factory = func(instance string) (endpoint.Endpoint, error) {
			if e, ok := endpoints[instance]; ok {
				return e, nil
			}
			return nil, fmt.Errorf("%s: not found", instance)
		}
	)
	p := static.NewPublisher(instances, factory, log.NewNopLogger())
	have, err := p.Endpoints()
	if err != nil {
		t.Fatal(err)
	}
	want := []endpoint.Endpoint{endpoints["foo"], endpoints["bar"], endpoints["baz"]}
	if fmt.Sprint(want) != fmt.Sprint(have) {
		t.Fatalf("want %v, have %v", want, have)
	}
}
Exemple #6
1
func InsertWithUID(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	var col, doc string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "doc", &doc) {
		return
	}
	V3Sync.RLock()
	defer V3Sync.RUnlock()
	dbcol := V3DB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	var jsonDoc interface{}
	if err := json.Unmarshal([]byte(doc), &jsonDoc); err != nil {
		http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", doc), 400)
		return
	}
	id, uid, err := dbcol.InsertWithUID(jsonDoc)
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
		return
	}
	resp, err := json.Marshal(map[string]interface{}{"id": id, "uid": uid})
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
		return
	}
	w.WriteHeader(201)
	w.Write(resp)
}
Exemple #7
0
func viewInvite(w http.ResponseWriter, r *http.Request) {
	mail := r.PostFormValue("mail")
	conf, err := loadConf()
	if err != nil {
		log.Fatalln(err)
	}

	client := &http.Client{}
	data := url.Values{
		"email":      {mail},
		"token":      {conf.Token},
		"set_active": {"true"},
	}

	resp, err := client.Post(
		"https://"+conf.URL+"/api/users.admin.invite",
		"application/x-www-form-urlencoded",
		strings.NewReader(data.Encode()),
	)
	if err != nil {
		log.Fatalln(err)
	}
	body, _ := ioutil.ReadAll(resp.Body)

	var status map[string]interface{}
	json.Unmarshal(body, &status)
	fmt.Println(status["ok"])
	statusOk := fmt.Sprint(status["ok"])

	if statusOk == "true" {
		fmt.Fprintf(w, mail+"に招待状を送信しました.")
	} else {
		fmt.Fprintf(w, "失敗した。失敗した。失敗した。"+fmt.Sprint(status["error"]))
	}
}
Exemple #8
0
func (m *Map) String() string {
	s := "Map [" + fmt.Sprint(m.width) + " x " + fmt.Sprint(m.height) + "]\n{"
	for _, ap := range m.accessPoints {
		s += ap.String() + ", "
	}
	return s + "}"
}
Exemple #9
0
func TestUpdateToInvalid(t *testing.T) {
	ldb := db.OpenMemory()

	s := db.NewFileSet("test", ldb)

	localHave := fileList{
		protocol.FileInfo{Name: "a", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1000}}}, Blocks: genBlocks(1)},
		protocol.FileInfo{Name: "b", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1001}}}, Blocks: genBlocks(2)},
		protocol.FileInfo{Name: "c", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1002}}}, Blocks: genBlocks(5), Invalid: true},
		protocol.FileInfo{Name: "d", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1003}}}, Blocks: genBlocks(7)},
	}

	s.Replace(protocol.LocalDeviceID, localHave)

	have := fileList(haveList(s, protocol.LocalDeviceID))
	sort.Sort(have)

	if fmt.Sprint(have) != fmt.Sprint(localHave) {
		t.Errorf("Have incorrect before invalidation;\n A: %v !=\n E: %v", have, localHave)
	}

	localHave[1] = protocol.FileInfo{Name: "b", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1001}}}, Invalid: true}
	s.Update(protocol.LocalDeviceID, localHave[1:2])

	have = fileList(haveList(s, protocol.LocalDeviceID))
	sort.Sort(have)

	if fmt.Sprint(have) != fmt.Sprint(localHave) {
		t.Errorf("Have incorrect after invalidation;\n A: %v !=\n E: %v", have, localHave)
	}
}
Exemple #10
0
func main() {

	srv := &clonesrv_t{
		port:  5556,
		kvmap: make(map[string]*kvmsg.Kvmsg),
	}

	//  Set up our clone server sockets
	srv.snapshot, _ = zmq.NewSocket(zmq.ROUTER)
	srv.snapshot.Bind(fmt.Sprint("tcp://*:", srv.port))
	srv.publisher, _ = zmq.NewSocket(zmq.PUB)
	srv.publisher.Bind(fmt.Sprint("tcp://*:", srv.port+1))
	srv.collector, _ = zmq.NewSocket(zmq.PULL)
	srv.collector.Bind(fmt.Sprint("tcp://*:", srv.port+2))

	//  Register our handlers with reactor
	reactor := zmq.NewReactor()
	reactor.AddSocket(srv.snapshot, zmq.POLLIN,
		func(e zmq.State) error { return snapshots(srv) })
	reactor.AddSocket(srv.collector, zmq.POLLIN,
		func(e zmq.State) error { return collector(srv) })
	reactor.AddChannelTime(time.Tick(1000*time.Millisecond), 1,
		func(v interface{}) error { return flush_ttl(srv) })

	log.Println(reactor.Run(100 * time.Millisecond)) // precision: .1 seconds
}
Exemple #11
0
// zeroConst returns a new "zero" constant of the specified type,
// which must not be an array or struct type: the zero values of
// aggregates are well-defined but cannot be represented by Const.
//
func zeroConst(t types.Type) *Const {
	switch t := t.(type) {
	case *types.Basic:
		switch {
		case t.Info()&types.IsBoolean != 0:
			return NewConst(exact.MakeBool(false), t)
		case t.Info()&types.IsNumeric != 0:
			return NewConst(exact.MakeInt64(0), t)
		case t.Info()&types.IsString != 0:
			return NewConst(exact.MakeString(""), t)
		case t.Kind() == types.UnsafePointer:
			fallthrough
		case t.Kind() == types.UntypedNil:
			return nilConst(t)
		default:
			panic(fmt.Sprint("zeroConst for unexpected type:", t))
		}
	case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
		return nilConst(t)
	case *types.Named:
		return NewConst(zeroConst(t.Underlying()).Value, t)
	case *types.Array, *types.Struct, *types.Tuple:
		panic(fmt.Sprint("zeroConst applied to aggregate:", t))
	}
	panic(fmt.Sprint("zeroConst: unexpected ", t))
}
Exemple #12
0
// Test of aliasing.
func init() {
	type S struct {
		a, b string
	}

	s1 := []string{"foo", "bar"}
	s2 := s1 // creates an alias
	s2[0] = "wiz"
	if x := fmt.Sprint(s1, s2); x != "[wiz bar] [wiz bar]" {
		panic(x)
	}

	pa1 := &[2]string{"foo", "bar"}
	pa2 := pa1        // creates an alias
	(*pa2)[0] = "wiz" // * required to workaround typechecker bug
	if x := fmt.Sprint(*pa1, *pa2); x != "[wiz bar] [wiz bar]" {
		panic(x)
	}

	a1 := [2]string{"foo", "bar"}
	a2 := a1 // creates a copy
	a2[0] = "wiz"
	if x := fmt.Sprint(a1, a2); x != "[foo bar] [wiz bar]" {
		panic(x)
	}

	t1 := S{"foo", "bar"}
	t2 := t1 // copy
	t2.a = "wiz"
	if x := fmt.Sprint(t1, t2); x != "{foo bar} {wiz bar}" {
		panic(x)
	}
}
Exemple #13
0
func spinner(waitMsg string, position int, channelEnd *ChannelEnd, wg *sync.WaitGroup) {
	if channelEnd.closed {
		wg.Done()
		return
	}

	wg.Add(1)
	chars := []string{".", "-", ".", "-", "-", ".", "-", ".", "-", "-", ".", "-", ".", "-", "-", "."}
	if position > len(chars)-1 {
		position = 0
	}
	postfix := ""
	prefix := ""
	for counter, str := range chars {
		if counter < position {
			postfix = fmt.Sprint(postfix, str)
		} else {
			prefix = fmt.Sprint(prefix, str)
		}
	}

	clean()
	switch runtime.GOOS {
	case "windows":
		prefix = "..."
		postfix = ""
	}
	printWait(fmt.Sprintf("%s %s%s", waitMsg, prefix, postfix))
	time.Sleep(100 * time.Millisecond)

	spinner(waitMsg, position+1, channelEnd, wg)

	wg.Done()
}
Exemple #14
0
func (c *help) Run(context *Context, client *Client) error {
	const deprecatedMsg = "WARNING: %q is deprecated. Showing help for %q instead.\n\n"
	output := fmt.Sprintf("%s version %s.\n\n", c.manager.name, c.manager.version)
	if c.manager.wrong {
		output += fmt.Sprint("ERROR: wrong number of arguments.\n\n")
	}
	if len(context.Args) > 0 {
		if cmd, ok := c.manager.Commands[context.Args[0]]; ok {
			if deprecated, ok := cmd.(*DeprecatedCommand); ok {
				fmt.Fprintf(context.Stderr, deprecatedMsg, deprecated.oldName, cmd.Info().Name)
			}
			info := cmd.Info()
			output += fmt.Sprintf("Usage: %s %s\n", c.manager.name, info.Usage)
			output += fmt.Sprintf("\n%s\n", info.Desc)
			flags := c.parseFlags(cmd)
			if flags != "" {
				output += fmt.Sprintf("\n%s", flags)
			}
			if info.MinArgs > 0 {
				output += fmt.Sprintf("\nMinimum # of arguments: %d", info.MinArgs)
			}
			if info.MaxArgs > 0 {
				output += fmt.Sprintf("\nMaximum # of arguments: %d", info.MaxArgs)
			}
			output += fmt.Sprint("\n")
		} else if topic, ok := c.manager.topics[context.Args[0]]; ok {
			output += topic
		} else {
			return fmt.Errorf("command %q does not exist.", context.Args[0])
		}
	} else {
		output += fmt.Sprintf("Usage: %s %s\n\nAvailable commands:\n", c.manager.name, c.Info().Usage)
		var commands []string
		for name, cmd := range c.manager.Commands {
			if _, ok := cmd.(*DeprecatedCommand); !ok {
				commands = append(commands, name)
			}
		}
		sort.Strings(commands)
		for _, command := range commands {
			description := c.manager.Commands[command].Info().Desc
			description = strings.Split(description, "\n")[0]
			description = strings.Split(description, ".")[0]
			if len(description) > 2 {
				description = strings.ToUpper(description[:1]) + description[1:]
			}
			output += fmt.Sprintf("  %-20s %s\n", command, description)
		}
		output += fmt.Sprintf("\nUse %s help <commandname> to get more information about a command.\n", c.manager.name)
		if len(c.manager.topics) > 0 {
			output += fmt.Sprintln("\nAvailable topics:")
			for topic := range c.manager.topics {
				output += fmt.Sprintf("  %s\n", topic)
			}
			output += fmt.Sprintf("\nUse %s help <topicname> to get more information about a topic.\n", c.manager.name)
		}
	}
	io.WriteString(context.Stdout, output)
	return nil
}
Exemple #15
0
func UpdateByUID(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "text/json")
	var col, uid, doc string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "uid", &uid) {
		return
	}
	if !Require(w, r, "doc", &doc) {
		return
	}
	V3Sync.RLock()
	defer V3Sync.RUnlock()
	dbcol := V3DB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	var newDoc interface{}
	if err := json.Unmarshal([]byte(doc), &newDoc); err != nil {
		http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", newDoc), 400)
		return
	}
	newID, err := dbcol.UpdateByUID(uid, newDoc)
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
		return
	}
	w.Write([]byte(fmt.Sprint(newID)))
}
Exemple #16
0
func (this Pair) Up() (Pair, error) {
	if this.Left.patch {
		return this, nil
	}

	if err := this.Left.ApplyCidr(); err != nil {
		return this, errors.New(fmt.Sprint("Unable to Left.ApplyCidr, error:", err))
	}

	if err := this.Right.ApplyCidr(); err != nil {
		return this, errors.New(fmt.Sprint("Unable to Right.ApplyCidr, error:", err))
	}

	if err := this.Left.Up(); err != nil {
		return this, errors.New(fmt.Sprint("Unable to Left.Up(), error:", err))
	}

	if err := this.Right.Up(); err != nil {
		return this, errors.New(fmt.Sprint("Unable to Right.Up(), error:", err))
	}

	if err := this.Right.ApplyRoutes(); err != nil {
		return this, errors.New(fmt.Sprint("Unable to ApplyRoutes(), error:", err))
	}

	this.Left = this.Left.SetState("UP")
	this.Right = this.Right.SetState("UP")

	fmt.Println("[Link]", this.Left.NodeName, this.Left.Name, this.Left.Cidr, "<--->", this.Right.NodeName, this.Right.Name, this.Right.Cidr)

	return this, nil
}
Exemple #17
0
func ReassignUID(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	var col, id string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "id", &id) {
		return
	}
	V3Sync.RLock()
	defer V3Sync.RUnlock()
	dbcol := V3DB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	docID, err := strconv.Atoi(id)
	if err != nil {
		http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
		return
	}
	newID, newUID, err := dbcol.ReassignUID(uint64(docID))
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
	}
	resp, err := json.Marshal(map[string]interface{}{"id": newID, "uid": newUID})
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
		return
	}
	w.WriteHeader(201)
	w.Write(resp)
}
Exemple #18
0
func decodeValue(name string, data *asn1.RawValue, retVal *Variable) (err error) {
	switch Asn1BER(data.Tag) {

	// simple values
	case Integer, OctetString:
		params, val = "", new(interface{})
	// 32 bit application values
	case Counter32, TimeTicks, Gauge32:
		params, val = fmt.Sprint("tag:", data.Tag), new(int32)
	// 64 bit application values
	case Counter64:
		params, val = fmt.Sprint("tag:", data.Tag), new(int64)
	case NoSuchInstance:
		return fmt.Errorf("No such instance")
	case NoSuchObject:
		return fmt.Errorf("No such object")
	default:
		return fmt.Errorf("Unable to decode %x - not implemented", data[0])
	}
	_, err = asn1.UnmarshalWithParams(m.Data.FullBytes, &val, fmt.Sprint("tag:", data.Tag))
	if err != nil {
		return
	}
	*retVal.Name = name
	*retVal.Type = Asn1BER(data.Tag)
	*retVal.Value = val

	return
}
Exemple #19
0
func (self res) resolve(scope map[interface{}]interface{}) (output string) {
	output = self.value
	if self.needsResolution {
		curr := self.resolveValue(scope)

	OutputSwitch:
		switch t := curr; t.Kind() {
		case reflect.String:
			output = t.String()
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			output = fmt.Sprint(t.Int())
		case reflect.Float32, reflect.Float64:
			output = fmt.Sprint(t.Float())
		case reflect.Ptr:
			if !t.IsNil() {
				curr = t.Elem()
				goto OutputSwitch
			}
			output = ""
		case reflect.Interface:
			curr = t.Elem()
			goto OutputSwitch
		default:
			output = fmt.Sprint(curr)
		}
	}
	return
}
Exemple #20
0
// Results
func (u *Uchiwa) resultsHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "DELETE" {
		http.Error(w, "", http.StatusBadRequest)
		return
	}

	resources := strings.Split(r.URL.Path, "/")
	if len(resources) != 5 {
		http.Error(w, "", http.StatusBadRequest)
		return
	}

	check := resources[4]
	client := resources[3]
	dc := resources[2]

	token := auth.GetTokenFromContext(r)

	unauthorized := FilterGetRequest(dc, token)
	if unauthorized {
		http.Error(w, fmt.Sprint(""), http.StatusNotFound)
		return
	}

	err := u.DeleteCheckResult(check, client, dc)
	if err != nil {
		http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
		return
	}
}
Exemple #21
0
func parseCounters(info string) map[string]int64 {
	counters := map[string]int64{
		"evicted_keys":               0,
		"expired_keys":               0,
		"keyspace_hits":              0,
		"keyspace_misses":            0,
		"rejected_connections":       0,
		"sync_full":                  0,
		"sync_partial_err":           0,
		"sync_partial_ok":            0,
		"total_commands_processed":   0,
		"total_connections_received": 0,
	}
	color.White("-------------------")
	color.White("COUNTERS:")
	for counter, _ := range counters {
		r, _ := regexp.Compile(fmt.Sprint(counter, ":([0-9]*)"))
		matches := r.FindStringSubmatch(info)
		if matches == nil {
			color.Yellow(fmt.Sprint("ERROR: ", counter, "is not displayed in redis info"))
		} else {
			value := matches[len(matches)-1]
			color.Cyan(fmt.Sprint(counter, ": ", value))
			v, _ := strconv.ParseInt(value, 10, 64)
			counters[counter] = v
		}
	}
	return counters
}
func startClient(servers []string) (*benchClient, error) {
	path, err := getBenchClientPath()
	if err != nil {
		return nil, err
	}

	flags := []string{
		"--serviceName", benchServerName,
		"--requestSize", fmt.Sprint(*requestSize),
		"--timeout", fmt.Sprint(*timeout),
	}
	flags = append(flags, servers...)
	cmd := exec.Command(path, flags...)
	cmd.Stderr = os.Stderr
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return nil, err
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	bc := &benchClient{cmd: cmd, stdin: stdin, stdout: bufio.NewReader(stdout), errors: make(map[string]int)}
	return bc, bc.waitForStart()
}
func addTestManifest(repo, reference string, content []byte, m *testutil.RequestResponseMap) {
	*m = append(*m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "GET",
			Route:  "/v2/" + repo + "/manifests/" + reference,
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Body:       content,
			Headers: http.Header(map[string][]string{
				"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})
	*m = append(*m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "HEAD",
			Route:  "/v2/" + repo + "/manifests/" + reference,
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Headers: http.Header(map[string][]string{
				"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})

}
Exemple #24
0
func Get(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	categoryName := r.FormValue("category")
	if categoryName == "" {
		randomCat, err := getRandomCategory(c)
		if err != nil {
			http.Error(w, "Could not get random category"+err.Error(), http.StatusInternalServerError)
			return
		}
		categoryName = randomCat
	}
	q := datastore.NewQuery("Fortune").Filter("Category =", categoryName)
	count, err := q.Count(c)
	if err != nil {
		mess := fmt.Sprint("Could not count fortunes matching: %s. Error was: %s", categoryName, err.Error())
		http.Error(w, mess, http.StatusInternalServerError)
		return
	}
	if count == 0 {
		mess := fmt.Sprintf("No fortune matching %s", categoryName)
		http.Error(w, mess, http.StatusInternalServerError)
		return
	}
	fortunes := make([]Fortune, 0, count)
	_, err = q.GetAll(c, &fortunes)
	if err != nil {
		mess := fmt.Sprint("Could not get fortunes matching: %s. Error was: %s", categoryName, err.Error())
		http.Error(w, mess, http.StatusInternalServerError)
		return
	}
	randIndex := rand.Intn(count)
	fortune := fortunes[randIndex]
	fmt.Fprintf(w, "%s\n[%s]\n", fortune.Text, fortune.Category)
}
Exemple #25
0
func TestFromConfig(t *testing.T) {
	newString := func(s string) *string {
		return &s
	}
	tests := []struct {
		in string

		want    interface{}
		wanterr interface{}
	}{
		{in: "", wanterr: ErrNoAuth},
		{in: "slkdjflksdjf", wanterr: `Unknown auth type: "slkdjflksdjf"`},
		{in: "none", want: None{}},
		{in: "localhost", want: Localhost{}},
		{in: "userpass:alice:secret", want: &UserPass{Username: "******", Password: "******", OrLocalhost: false, VivifyPass: nil}},
		{in: "userpass:alice:secret:+localhost", want: &UserPass{Username: "******", Password: "******", OrLocalhost: true, VivifyPass: nil}},
		{in: "userpass:alice:secret:+localhost:vivify=foo", want: &UserPass{Username: "******", Password: "******", OrLocalhost: true, VivifyPass: newString("foo")}},
		{in: "devauth:port3179", want: &DevAuth{Password: "******", VivifyPass: newString("viviport3179")}},
		{in: "basic:alice:secret", want: &UserPass{Username: "******", Password: "******", OrLocalhost: false, VivifyPass: nil}},
		{in: "basic:alice:secret:+localhost", wanterr: `invalid basic auth syntax. got "alice:secret:+localhost", want "username:password"`},
		{in: "basic:alice:secret:+vivify=foo", wanterr: `invalid basic auth syntax. got "alice:secret:+vivify=foo", want "username:password"`},
	}
	for _, tt := range tests {
		am, err := FromConfig(tt.in)
		if err != nil || tt.wanterr != nil {
			if fmt.Sprint(err) != fmt.Sprint(tt.wanterr) {
				t.Errorf("FromConfig(%q) = error %v; want %v", tt.in, err, tt.wanterr)
			}
			continue
		}
		if !reflect.DeepEqual(am, tt.want) {
			t.Errorf("FromConfig(%q) = %#v; want %#v", tt.in, am, tt.want)
		}
	}
}
Exemple #26
0
// Display sends variable name,value pairs to the debugger. Values are formatted using %#v.
// The parameter 'nameValuePairs' must be even sized.
func (wp *WatchPoint) Display(nameValuePairs ...interface{}) *WatchPoint {
	if wp.disabled {
		return wp
	}

	_, file, line, ok := runtime.Caller(wp.offset)
	cmd := command{
		Action: "DISPLAY",
		Level:  levelToStr(wp.watchLevel),
	}
	if ok {
		cmd.addParam("go.file", file)
		cmd.addParam("go.line", fmt.Sprint(line))
	}

	l := len(nameValuePairs)
	if l%2 == 0 {
		for i := 0; i < l; i += 2 {
			k := nameValuePairs[i]
			v := nameValuePairs[i+1]
			cmd.addParam(fmt.Sprint(k), fmt.Sprintf("%#v", v))
		}
	} else {
		com.ColorLog("[WARN] BW: Missing variable for Display(...) in: %v:%v.\n", file, line)
		wp.disabled = true
		return wp
	}

	channelExchangeCommands(wp.watchLevel, cmd)
	return wp
}
Exemple #27
0
func (c Test) initData(userId int, fieldGroup FieldGroup, masterData *map[string]interface{}) {
	dateUtil := DateUtil{}
	if fieldGroup.FieldDataType == "STRING" {
		(*masterData)[fieldGroup.Id] = "user" + fmt.Sprint(userId) + "_data_" + fmt.Sprint(rand.Int())
	} else if fieldGroup.FieldDataType == "FLOAT" {
		(*masterData)[fieldGroup.Id] = fmt.Sprint(rand.Float64())[:10]
	} else if fieldGroup.FieldNumberType == "YEAR" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMdd() / (100 * 100)
	} else if fieldGroup.FieldNumberType == "YEARMONTH" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMdd() / 100
	} else if fieldGroup.FieldNumberType == "DATE" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMdd()
	} else if fieldGroup.FieldNumberType == "TIME" {
		(*masterData)[fieldGroup.Id] = 180605
	} else if fieldGroup.FieldNumberType == "DATETIME" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMddHHmmss()
	} else { // int
		if fieldGroup.Id == "billTypeId" {
			(*masterData)[fieldGroup.Id] = 1
		} else if fieldGroup.Id == "billTypeParameterId" {
			(*masterData)[fieldGroup.Id] = 1
		} else if fieldGroup.Id == "currencyTypeId" {
			(*masterData)[fieldGroup.Id] = 1
		} else {
			(*masterData)[fieldGroup.Id] = rand.Int()
		}
	}
}
Exemple #28
0
// Run the test cases above.
func TestComputeRoute(t *testing.T) {
	for routeLine, expected := range routeTestCases {
		method, path, action, found := parseRouteLine(routeLine)
		if !found {
			t.Error("Failed to parse route line:", routeLine)
			continue
		}
		actual := NewRoute(method, path, action)
		eq(t, "Method", actual.Method, expected.Method)
		eq(t, "Path", actual.Path, expected.Path)
		eq(t, "Action", actual.Action, expected.Action)
		eq(t, "pathPattern", fmt.Sprint(actual.pathPattern), fmt.Sprint(expected.pathPattern))
		eq(t, "staticDir", actual.staticDir, expected.staticDir)
		eq(t, "len(args)", len(actual.args), len(expected.args))
		for i, arg := range actual.args {
			if len(expected.args) <= i {
				break
			}
			eq(t, "arg.name", arg.name, expected.args[i].name)
			eq(t, "arg.constraint", arg.constraint.String(), expected.args[i].constraint.String())
		}
		eq(t, "actionPattern", fmt.Sprint(actual.actionPattern), fmt.Sprint(expected.actionPattern))
		if t.Failed() {
			t.Fatal("Failed on route:", routeLine)
		}
	}
}
Exemple #29
0
// ModifyCdnService version 2014-11-11
//
// required parameters:
//  name: InternetChargeType, type: string
//
// optional parameters:
//  name: OwnerId, type: int64
//  name: ResourceOwnerAccount, type: string
//  name: ResourceOwnerId, type: int64
//  name: _method, type: string, optional values: GET|POST
//  name: _region, type: string
//  name: _scheme, type: string, optional values: http|https
func (api API) ModifyCdnService(InternetChargeType string, optional openapi.M) (*openapi.Response, error) {
	args := NewParams()

	args.Query.Set("Action", "ModifyCdnService")
	args.Query.Set("InternetChargeType", InternetChargeType)
	if v, ok := optional["OwnerId"]; ok {
		if OwnerId, ok := v.(int64); ok {
			args.Query.Set("OwnerId", fmt.Sprint(OwnerId))
		} else {
			return nil, errors.New("OwnerId must be int64")
		}
	}
	if v, ok := optional["ResourceOwnerAccount"]; ok {
		if ResourceOwnerAccount, ok := v.(string); ok {
			args.Query.Set("ResourceOwnerAccount", ResourceOwnerAccount)
		} else {
			return nil, errors.New("ResourceOwnerAccount must be string")
		}
	}
	if v, ok := optional["ResourceOwnerId"]; ok {
		if ResourceOwnerId, ok := v.(int64); ok {
			args.Query.Set("ResourceOwnerId", fmt.Sprint(ResourceOwnerId))
		} else {
			return nil, errors.New("ResourceOwnerId must be int64")
		}
	}
	if v, ok := optional["_method"]; ok {
		if s, ok := v.(string); ok {
			if !openapi.IsIn(s, "GET|POST") {
				return nil, errors.New("_method must be GET|POST")
			}
			args.Method = s
		} else {
			return nil, errors.New("_method must be string")
		}
	}
	if v, ok := optional["_region"]; ok {
		if s, ok := v.(string); ok {
			args.Region = s
		} else {
			return nil, errors.New("_region must be string")
		}
	}
	if v, ok := optional["_scheme"]; ok {
		if s, ok := v.(string); ok {
			if !openapi.IsIn(s, "http|https") {
				return nil, errors.New("_scheme must be http|https")
			}
			args.Scheme = s
		} else {
			return nil, errors.New("_scheme must be string")
		}
	}

	result := new(openapi.Response)
	if err := api.Service.Do(result, args); err != nil {
		return nil, err
	}
	return result, nil
}
Exemple #30
0
func (p *Pattern) String() string {
	var output string

	// Output Version & Tempo
	output += fmt.Sprintln("Saved with HW Version:", p.Version)
	output += fmt.Sprintln("Tempo:", p.Tempo)

	// Loop over each track, printing id, name and beats for each one
	for _, track := range p.Tracks {
		output += fmt.Sprintf("(%d) %s\t", track.ID, track.Name)

		// Print the beats by first printing a line each 4 beats,
		// then printing 'x' for a beat, '-' for a non-beat
		for k, v := range track.Beats {
			if k%4 == 0 {
				output += fmt.Sprint("|")
			}
			if v == 1 {
				output += fmt.Sprint("x")
			} else {
				output += fmt.Sprint("-")
			}
		}

		// Add a closing '|'
		output += fmt.Sprintln("|")
	}
	return output
}