Beispiel #1
1
func getUpdates(token string, offset int, timeout int) (updates []Update, err error) {
	params := url.Values{}
	params.Set("offset", strconv.Itoa(offset))
	params.Set("timeout", strconv.Itoa(timeout))
	updatesJSON, err := sendCommand("getUpdates", token, params)
	if err != nil {
		return
	}

	var updatesRecieved struct {
		Ok          bool
		Result      []Update
		Description string
	}

	err = json.Unmarshal(updatesJSON, &updatesRecieved)
	if err != nil {
		return
	}

	if !updatesRecieved.Ok {
		err = FetchError{updatesRecieved.Description}
		return
	}

	updates = updatesRecieved.Result
	return
}
Beispiel #2
1
func (plan *Plan) Values(values *url.Values) error {
	if plan == nil {
		// TODO: Throw error
	}
	if plan.ID == "" {
		// TODO: Throw error
	}
	if plan.Name == "" {
		// TODO: Throw error
	}
	if plan.Amount <= 0 {
		// TODO: Throw error
	}
	if plan.Currency != "USD" {
		// TODO: Throw error
	}
	if plan.Interval != "month" && plan.Interval != "year" {
		// TODO: Throw error
	}
	if plan.TrialDays > 0 {
		values.Set("trial_period_days", strconv.Itoa(plan.TrialDays))
	}
	values.Set("id", plan.ID)
	values.Set("amount", strconv.Itoa(plan.Amount))
	values.Set("currency", plan.Currency)
	values.Set("interval", plan.Interval)
	values.Set("name", plan.Name)
	return nil
}
Beispiel #3
0
func TestManyFailures(t *testing.T) {
	fmt.Printf("Test: One ManyFailures mapreduce ...\n")
	mr := setup()
	i := 0
	done := false
	for !done {
		select {
		case done = <-mr.DoneChannel:
			check(t, mr.file)
			cleanup(mr)
			break
		default:
			// Start 2 workers each sec. The workers fail after 10 jobs
			w := port("worker" + strconv.Itoa(i))
			go RunWorker(mr.MasterAddress, w, MapFunc, ReduceFunc, 10)
			i++
			w = port("worker" + strconv.Itoa(i))
			go RunWorker(mr.MasterAddress, w, MapFunc, ReduceFunc, 10)
			i++
			time.Sleep(1 * time.Second)
		}
	}

	fmt.Printf("  ... Many Failures Passed\n")
}
Beispiel #4
0
func TestUnreliableOneKey(t *testing.T) {
	const nservers = 3
	cfg := make_config(t, "onekey", nservers, true, -1)
	defer cfg.cleanup()

	ck := cfg.makeClient(cfg.All())

	fmt.Printf("Test: Concurrent Append to same key, unreliable ...\n")

	ck.Put("k", "")

	const nclient = 5
	const upto = 10
	spawn_clients_and_wait(t, cfg, nclient, func(me int, myck *Clerk, t *testing.T) {
		n := 0
		for n < upto {
			myck.Append("k", "x "+strconv.Itoa(me)+" "+strconv.Itoa(n)+" y")
			n++
		}
	})

	var counts []int
	for i := 0; i < nclient; i++ {
		counts = append(counts, upto)
	}

	vx := ck.Get("k")
	checkConcurrentAppends(t, vx, counts)

	fmt.Printf("  ... Passed\n")
}
// Initialize entities to random variables in order to test ledger status consensus
func (t *SimpleChaincode) initRand(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval = rand.Intn(100)
	B = args[1]
	Bval = rand.Intn(100)
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}
Beispiel #6
0
func TestWatcherTimeout(t *testing.T) {
	server, etcdStorage := newEtcdTestStorage(t, testapi.Default.Codec(), etcdtest.PathPrefix())
	defer server.Terminate(t)
	cacher := newTestCacher(etcdStorage)
	defer cacher.Stop()

	// initialVersion is used to initate the watcher at the beginning of the world,
	// which is not defined precisely in etcd.
	initialVersion, err := cacher.LastSyncResourceVersion()
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	startVersion := strconv.Itoa(int(initialVersion))

	// Create a watcher that will not be reading any result.
	watcher, err := cacher.WatchList(context.TODO(), "pods/ns", startVersion, storage.Everything)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	defer watcher.Stop()

	// Create a second watcher that will be reading result.
	readingWatcher, err := cacher.WatchList(context.TODO(), "pods/ns", startVersion, storage.Everything)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	defer readingWatcher.Stop()

	for i := 1; i <= 22; i++ {
		pod := makeTestPod(strconv.Itoa(i))
		_ = updatePod(t, etcdStorage, pod, nil)
		verifyWatchEvent(t, readingWatcher, watch.Added, pod)
	}
}
Beispiel #7
0
// FmtDateShort returns the short date representation of 't' for 'it_IT'
func (it *it_IT) FmtDateShort(t time.Time) string {

	b := make([]byte, 0, 32)

	if t.Day() < 10 {
		b = append(b, '0')
	}

	b = strconv.AppendInt(b, int64(t.Day()), 10)
	b = append(b, []byte{0x2f}...)

	if t.Month() < 10 {
		b = append(b, '0')
	}

	b = strconv.AppendInt(b, int64(t.Month()), 10)

	b = append(b, []byte{0x2f}...)

	if t.Year() > 9 {
		b = append(b, strconv.Itoa(t.Year())[2:]...)
	} else {
		b = append(b, strconv.Itoa(t.Year())[1:]...)
	}

	return string(b)
}
Beispiel #8
0
func TestUpdate(t *testing.T) {
	a, _ := NewHyperLogLog(0.05)
	b, _ := NewHyperLogLog(0.05)
	c, _ := NewHyperLogLog(0.05)

	for i := 0; i < 2; i++ {
		add := strconv.Itoa(i)
		a.Add(add)
		c.Add(add)
	}
	for i := 2; i < 4; i++ {
		add := strconv.Itoa(i)
		b.Add(add)
		c.Add(add)
	}

	a.Update([]*HyperLogLog{b})

	if hllEqual(a, b) {
		t.Error("TestUpdate: a and b are equal")
	}
	if hllEqual(b, c) {
		t.Error("TestUpdate: b and c are equal")
	}
	if !hllEqual(a, c) {
		t.Error("TestUpdate: a and c are not equal")
	}

	d, _ := NewHyperLogLog(0.01)
	err := a.Update([]*HyperLogLog{d})
	if err == nil {
		t.Error("TestUpdate: different precisions didn't throw an error")
	}

}
func (p *ListDomainChildrenParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["id"]; found {
		u.Set("id", v.(string))
	}
	if v, found := p.p["isrecursive"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("isrecursive", vv)
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["listall"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("listall", vv)
	}
	if v, found := p.p["name"]; found {
		u.Set("name", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	return u
}
Beispiel #10
0
func FindUserId(name string) string {
	var users map[string][]User_t
	uri := "/api/1.0/workspaces/" + strconv.Itoa(config.Load().Workspace) + "/typeahead?type=user&query=" + name
	err := json.Unmarshal(Get(uri, nil), &users)
	utils.Check(err)
	return strconv.Itoa(users["data"][0].Id)
}
func (p *ReverseProxy) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *SessionState) error {

	for _, h := range hopHeaders {
		res.Header.Del(h)
	}
	defer res.Body.Close()

	// Close connections
	if config.CloseConnections {
		res.Header.Set("Connection", "close")
	}

	// Add resource headers
	if ses != nil {
		// We have found a session, lets report back
		res.Header.Add("X-RateLimit-Limit", strconv.Itoa(int(ses.QuotaMax)))
		res.Header.Add("X-RateLimit-Remaining", strconv.Itoa(int(ses.QuotaRemaining)))
		res.Header.Add("X-RateLimit-Reset", strconv.Itoa(int(ses.QuotaRenews)))
	}

	copyHeader(rw.Header(), res.Header)

	rw.WriteHeader(res.StatusCode)
	p.copyResponse(rw, res.Body)
	return nil
}
func getSTEvents(lastSeenID int) ([]Event, error) {
	Trace.Println("Requesting STEvents: " + strconv.Itoa(lastSeenID))
	r, err := http.NewRequest("GET", target+"/rest/events?since="+strconv.Itoa(lastSeenID), nil)
	res, err := performRequest(r)
	defer func() {
		if res != nil && res.Body != nil {
			res.Body.Close()
		}
	}()
	if err != nil {
		Warning.Println("Failed to perform request", err)
		return nil, err
	}
	if res.StatusCode != 200 {
		Warning.Printf("Status %d != 200 for GET", res.StatusCode)
		return nil, errors.New("Invalid HTTP status code")
	}
	bs, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	var events []Event
	err = json.Unmarshal(bs, &events)
	return events, err
}
Beispiel #13
0
//generate a random id to represent the unique id
func generateID(adId int) string {
	t := time.Now()
	year, month, day := t.Date()
	var id = Hex(4) + "-" + strconv.Itoa(year) +
		strconv.Itoa(int(month)) + strconv.Itoa(day) + "-" + strconv.Itoa(adId)
	return id
}
Beispiel #14
0
// buildLogLine creates a common log format
// in addittion to the common fields, we also append referrer, user agent and request ID
func buildLogLine(l *responseLogger, r *http.Request, start time.Time) string {
	username := parseUsername(r)

	host, _, err := net.SplitHostPort(r.RemoteAddr)

	if err != nil {
		host = r.RemoteAddr
	}

	uri := r.URL.RequestURI()

	referer := r.Referer()

	userAgent := r.UserAgent()

	fields := []string{
		host,
		"-",
		detect(username, "-"),
		fmt.Sprintf("[%s]", start.Format("02/Jan/2006:15:04:05 -0700")),
		r.Method,
		uri,
		r.Proto,
		detect(strconv.Itoa(l.Status()), "-"),
		strconv.Itoa(l.Size()),
		detect(referer, "-"),
		detect(userAgent, "-"),
		r.Header.Get("Request-Id"),
	}

	return strings.Join(fields, " ")
}
Beispiel #15
0
// buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size.
func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
	username := "******"
	if url.User != nil {
		if name := url.User.Username(); name != "" {
			username = name
		}
	}

	host, _, err := net.SplitHostPort(req.RemoteAddr)

	if err != nil {
		host = req.RemoteAddr
	}

	uri := url.RequestURI()

	buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
	buf = append(buf, host...)
	buf = append(buf, " - "...)
	buf = append(buf, username...)
	buf = append(buf, " ["...)
	buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
	buf = append(buf, `] "`...)
	buf = append(buf, req.Method...)
	buf = append(buf, " "...)
	buf = appendQuoted(buf, uri)
	buf = append(buf, " "...)
	buf = append(buf, req.Proto...)
	buf = append(buf, `" `...)
	buf = append(buf, strconv.Itoa(status)...)
	buf = append(buf, " "...)
	buf = append(buf, strconv.Itoa(size)...)
	return buf
}
Beispiel #16
0
func makePortsAndBindings(container *api.Container) (map[docker.Port]struct{}, map[docker.Port][]docker.PortBinding) {
	exposedPorts := map[docker.Port]struct{}{}
	portBindings := map[docker.Port][]docker.PortBinding{}
	for _, port := range container.Ports {
		exteriorPort := port.HostPort
		if exteriorPort == 0 {
			// No need to do port binding when HostPort is not specified
			continue
		}
		interiorPort := port.ContainerPort
		// Some of this port stuff is under-documented voodoo.
		// See http://stackoverflow.com/questions/20428302/binding-a-port-to-a-host-interface-using-the-rest-api
		var protocol string
		switch strings.ToUpper(string(port.Protocol)) {
		case "UDP":
			protocol = "/udp"
		case "TCP":
			protocol = "/tcp"
		default:
			glog.Warningf("Unknown protocol %q: defaulting to TCP", port.Protocol)
			protocol = "/tcp"
		}
		dockerPort := docker.Port(strconv.Itoa(interiorPort) + protocol)
		exposedPorts[dockerPort] = struct{}{}
		portBindings[dockerPort] = []docker.PortBinding{
			{
				HostPort: strconv.Itoa(exteriorPort),
				HostIP:   port.HostIP,
			},
		}
	}
	return exposedPorts, portBindings
}
Beispiel #17
0
func (stripe *Stripe) ListPlans(count, offset int) (resp []*Plan, err error) {
	values := make(url.Values)
	if count >= 0 {
		values.Set("count", strconv.Itoa(count))
	}
	if offset >= 0 {
		values.Set("offset", strconv.Itoa(offset))
	}
	params := values.Encode()
	if params != "" {
		params = "?" + params
	}
	r, err := stripe.request("GET", "plans"+params, "")
	if err != nil {
		return nil, err
	}
	var raw struct {
		Count int "count"
		Data  []*Plan
		Error *RawError "error"
	}
	err = json.Unmarshal(r, &raw)
	if err != nil {
		return nil, err
	}
	if raw.Error != nil {
		// TODO: throw an error
	}
	resp = raw.Data
	return
}
Beispiel #18
0
// Must based on ID now.
func (sc *Client) Delete(obj interface{}) (rowsAffected int, err error) {
	if err = sc.Init(nil); err != nil {
		return -1, fmt.Errorf("Delete> %v", err)
	}

	sqlStr := "DELETE FROM " + sc.Index + " WHERE id "
	switch v := obj.(type) {
	case int:
		if v <= 0 {
			return -1, fmt.Errorf("Delete> Invalid id val: %d", v)
		}
		sqlStr += "= " + strconv.Itoa(v)
	case []int:
		if len(v) == 0 {
			return -1, fmt.Errorf("Delete> Empty []int")
		}

		sqlStr += "IN ("
		for _, id := range v {
			if id <= 0 {
				return -1, fmt.Errorf("Delete> Invalid id val: %d", id)
			}
			sqlStr += strconv.Itoa(id) + ","
		}
		sqlStr = sqlStr[:len(sqlStr)-1] + ")" // Change the last "," to ")"
	default:
		return -1, fmt.Errorf("Delete> Invalid type, must be int or []int: %#v", obj)
	}

	rowsAffected, err = sc.ExecuteReturnRowsAffected(sqlStr)
	if err != nil {
		return 0, fmt.Errorf("Delete>  %v", err)
	}
	return
}
func (p *ListBaremetalDhcpParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["dhcpservertype"]; found {
		u.Set("dhcpservertype", v.(string))
	}
	if v, found := p.p["id"]; found {
		vv := strconv.FormatInt(v.(int64), 10)
		u.Set("id", vv)
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	return u
}
Beispiel #20
0
func TestUpdateQuantityAndValue(t *testing.T) {
	fmt.Println("[INFO] -- TestUpdateQuantityAndValue start --")
	purchProducts := getPurchaseProducts()

	id := purchProducts[0].ID
	quantity := 1000

	// updateQuantity
	url := "http://127.0.0.1:8080/api/inventory/purchaseProduct/" + strconv.Itoa(id) + "/updateQuantity/" + strconv.Itoa(quantity)
	response, err := makeRequest(router.PUT, url, make([]byte, 1), _headers)
	if err != nil {
		t.Error(err)
	}

	if response.StatusCode != http.StatusOK {
		t.Error("[ERROR] /purchase/:id/conclude should have received status 200, Got: ", response.StatusCode)
	}

	value := 127.27
	// updateValue
	url = "http://127.0.0.1:8080/api/inventory/purchaseProduct/" + strconv.Itoa(id) + "/updateValue/" + strconv.FormatFloat(value, 'f', 6, 64)
	response, err = makeRequest(router.PUT, url, make([]byte, 1), _headers)
	if err != nil {
		t.Error(err)
	}

	if response.StatusCode != http.StatusOK {
		t.Error("[ERROR] /purchase/:id/conclude should have received status 200, Got: ", response.StatusCode)
	}

	fmt.Println("[INFO] -- TestUpdateQuantityAndValue end --\n")
}
Beispiel #21
0
// GetAlbumTracksOpt behaves like GetAlbumTracks, with the exception that it
// allows you to specify extra parameters that limit the number of results returned.
// The maximum number of results to return is specified by limit.
// The offset argument can be used to specify the index of the first track to return.
// It can be used along with limit to reqeust the next set of results.
func (c *Client) GetAlbumTracksOpt(id ID, limit, offset int) (*SimpleTrackPage, error) {
	spotifyURL := fmt.Sprintf("%salbums/%s/tracks", baseAddress, id)
	v := url.Values{}
	if limit != -1 {
		v.Set("limit", strconv.Itoa(limit))
	}
	if offset != -1 {
		v.Set("offset", strconv.Itoa(offset))
	}
	optional := v.Encode()
	if optional != "" {
		spotifyURL = spotifyURL + "?" + optional
	}
	resp, err := c.http.Get(spotifyURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result SimpleTrackPage
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}
func (c *Client) ResizeContainerTTY(id string, height, width int) error {
	params := make(url.Values)
	params.Set("h", strconv.Itoa(height))
	params.Set("w", strconv.Itoa(width))
	_, _, err := c.do("POST", "/containers/"+id+"/resize?"+params.Encode(), nil)
	return err
}
Beispiel #23
0
// APIInfo is defined on Config interface.
func (c *configInternal) APIInfo() (*api.Info, bool) {
	if c.apiDetails == nil || c.apiDetails.addresses == nil {
		return nil, false
	}
	servingInfo, isStateServer := c.StateServingInfo()
	addrs := c.apiDetails.addresses
	if isStateServer {
		port := servingInfo.APIPort
		localAPIAddr := net.JoinHostPort("localhost", strconv.Itoa(port))
		if c.preferIPv6 {
			localAPIAddr = net.JoinHostPort("::1", strconv.Itoa(port))
		}
		addrInAddrs := false
		for _, addr := range addrs {
			if addr == localAPIAddr {
				addrInAddrs = true
				break
			}
		}
		if !addrInAddrs {
			addrs = append(addrs, localAPIAddr)
		}
	}
	return &api.Info{
		Addrs:      addrs,
		Password:   c.apiDetails.password,
		CACert:     c.caCert,
		Tag:        c.tag,
		Nonce:      c.nonce,
		EnvironTag: c.environment,
	}, true
}
func TestNestedIterativeConveysReported(t *testing.T) {
	myReporter, test := setupFakeReporter()

	Convey("A", test, func() {
		for x := 0; x < 3; x++ {
			Convey(strconv.Itoa(x), func() {
				for y := 0; y < 3; y++ {
					Convey("< "+strconv.Itoa(y), func() {
						So(x, ShouldBeLessThan, y)
					})
				}
			})
		}
	})

	expectEqual(t, ("Begin|" +
		"A|0|< 0|Failure|Exit|Exit|Exit|" +
		"A|0|< 1|Success|Exit|Exit|Exit|" +
		"A|0|< 2|Success|Exit|Exit|Exit|" +
		"A|1|< 0|Failure|Exit|Exit|Exit|" +
		"A|1|< 1|Failure|Exit|Exit|Exit|" +
		"A|1|< 2|Success|Exit|Exit|Exit|" +
		"A|2|< 0|Failure|Exit|Exit|Exit|" +
		"A|2|< 1|Failure|Exit|Exit|Exit|" +
		"A|2|< 2|Failure|Exit|Exit|Exit|" +
		"End"), myReporter.wholeStory())
}
Beispiel #25
0
func decodeStopRecord() {
	jsonStr := `{
	    "type": "flv",
	    "stream_event": "flv",
	    "ori_url": "rtmp://pushyf.hifun.mobi/live/10016593_4VZIi6Cnwxdev",
	    "domain":"send.a.com",
	    "app":"live",
	    "stream":"10016593_4VZIi6Cnwxdev",
	    "uri":"hls.a.com/live/hls_bew000/hls_bew000_20160707150625_20160707175817.m3u8",
	    "start_time": 1470306194,
	    "stop_time": 1470306497,
	    "duration": 275,
	    "size":8987799,
	    "cdn_url": "http://hls.a.com/live/hls_bew000/hls_bew000_20160707150625_20160707175817.m3u8"
	}`
	rec := YFRecCallback{}
	if err := json.Unmarshal([]byte(jsonStr), &rec); err != nil {
		fmt.Printf("json unmarshal err:%v\n", err)
	} else {
		param["liveid"] = rec.Stream
		param["url"] = rec.CdnUrl
		param["duration"] = strconv.Itoa(int(rec.Duration))
		param["size"] = strconv.Itoa(rec.Size)
		fmt.Printf("decodeStopRecord rec : %v \n%v \n", rec, param)
	}

}
func (p *ListCiscoAsa1000vResourcesParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["hostname"]; found {
		u.Set("hostname", v.(string))
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	if v, found := p.p["physicalnetworkid"]; found {
		u.Set("physicalnetworkid", v.(string))
	}
	if v, found := p.p["resourceid"]; found {
		u.Set("resourceid", v.(string))
	}
	return u
}
Beispiel #27
0
func makeLinkVariables(service api.Service, machine string) []api.EnvVar {
	prefix := makeEnvVariableName(service.ID)
	var port string
	if service.ContainerPort.Kind == util.IntstrString {
		port = service.ContainerPort.StrVal
	} else {
		port = strconv.Itoa(service.ContainerPort.IntVal)
	}
	portPrefix := prefix + "_PORT_" + makeEnvVariableName(port) + "_TCP"
	return []api.EnvVar{
		{
			Name:  prefix + "_PORT",
			Value: fmt.Sprintf("tcp://%s:%d", machine, service.Port),
		},
		{
			Name:  portPrefix,
			Value: fmt.Sprintf("tcp://%s:%d", machine, service.Port),
		},
		{
			Name:  portPrefix + "_PROTO",
			Value: "tcp",
		},
		{
			Name:  portPrefix + "_PORT",
			Value: strconv.Itoa(service.Port),
		},
		{
			Name:  portPrefix + "_ADDR",
			Value: machine,
		},
	}
}
func (t *StockMarketApp) HandleBuyStockRequest(args *Args, reply *Reply) error {
	stocks := strings.Split(args.StockData, ",")
	stockArray := make([]stock, len(stocks))
	for i := 0; i < len(stocks); i++ {
		stockDetails := strings.Split(stocks[i], ":")
		stockName := stockDetails[0]
		sharePercentage, err := strconv.ParseFloat(strings.Replace(stockDetails[1], "%", "", -1), 64)
		if err != nil {
			log.Fatal(err)
		}
		stockObj := stock{symbol: stockName, percentage: float32(sharePercentage)}
		stockArray[i] = stockObj
	}
	getYahooData(&stockArray)
	var leftOverBalance float32 = 0.0
	for i := 0; i < len(stockArray); i++ {
		stockBalanceShare := ((stockArray[i].percentage / 100.0) * args.Balance)
		stockArray[i].quantity = int(stockBalanceShare / stockArray[i].newNetAmount)
		if reply.Stocks != "" {
			reply.Stocks = reply.Stocks + "," + stockArray[i].symbol + ":" + strconv.Itoa(stockArray[i].quantity) + ":$" + fmt.Sprintf("%f", stockArray[i].newNetAmount)
		} else {
			reply.Stocks = stockArray[i].symbol + ":" + strconv.Itoa(stockArray[i].quantity) + ":$" + fmt.Sprintf("%f", stockArray[i].newNetAmount)
		}
		stockArray[i].leftOverBalance = stockBalanceShare - (float32(stockArray[i].quantity) * stockArray[i].newNetAmount)
		leftOverBalance = leftOverBalance + stockArray[i].leftOverBalance
	}
	reply.UnvestedAmount = leftOverBalance
	reply.TradeId = rand.Int()
	stockMarket = make(map[int][]stock)
	stockMarket[reply.TradeId] = stockArray
	return nil
}
Beispiel #29
0
func TestLoadLogEntry(t *testing.T) {
	logic := New(Server{Addr: ":1234", Role: Follower})

	for i := 0; i < 10; i++ {
		logic.entryToDisk(comm.Entry{Term: 1, LogIndex: i, Cmd: "+" + strconv.Itoa(i)})
	}

	for i := 2; i < 12; i++ {
		logic.entryToDisk(comm.Entry{Term: 2, LogIndex: i, Cmd: "+" + strconv.Itoa(i)})
	}

	logic.loadLogEntry("logentry.data")

	if logic.logEntries[0].Term != 1 {
		t.Fail()
	}

	if logic.logEntries[1].Term != 1 {
		t.Fail()
	}

	if logic.logEntries[2].Term != 2 {
		t.Fail()
	}
}
Beispiel #30
0
func TestDashboardErrLog(t *testing.T) {
	rt := createNewRoomTable()
	db := newDashboard()

	for i := 0; i < maxErrLogLen+1; i++ {
		db.onHttpErr(errors.New(strconv.Itoa(i)))
	}
	r := db.getReport(rt)

	if r.HttpErrs != maxErrLogLen+1 {
		t.Errorf("db.getReport().HttpErrs is %d, want %d", r.HttpErrs, maxErrLogLen+1)
	}
	if len(r.ErrLog) != maxErrLogLen {
		t.Errorf("len(db.getReport().ErrLog) is %d, want %d", len(r.ErrLog), maxErrLogLen)
	}

	// Verifies the start and the end of the error log.
	expected_err := "1"
	if r.ErrLog[0].Err != expected_err {
		t.Errorf("The first error in db.getReport().ErrLog is %s, want %s", r.ErrLog[0].Err, expected_err)
	}
	expected_err = strconv.Itoa(maxErrLogLen)
	if r.ErrLog[maxErrLogLen-1].Err != expected_err {
		t.Errorf("The last error in db.getReport().ErrLog is %s, want %s", r.ErrLog[maxErrLogLen-1].Err, expected_err)
	}
}