예제 #1
1
func TestUpdate(t *testing.T) {
	neuralNetwork := CreateSimpleNetwork(t)
	inputs := mat64.NewDense(1, 2, []float64{0.05, 0.10})
	neuralNetwork.Forward(inputs)
	values := mat64.NewDense(1, 2, []float64{0.01, 0.99})
	neuralNetwork.Backward(values)
	learningConfiguration := neural.LearningConfiguration{
		Epochs:    proto.Int32(1),
		Rate:      proto.Float64(0.5),
		Decay:     proto.Float64(0),
		BatchSize: proto.Int32(1),
	}
	neuralNetwork.Update(learningConfiguration)
	expected_weights_0 := mat64.NewDense(
		3, 2, []float64{0.149780716, 0.24975114, 0.19956143, 0.29950229, 0.35,
			0.35})
	if !mat64.EqualApprox(
		neuralNetwork.Layers[0].Weight, expected_weights_0, 0.0001) {
		t.Errorf("weights 0 unexpected:\n%v",
			mat64.Formatted(neuralNetwork.Layers[0].Weight))
	}
	expected_weights_1 := mat64.NewDense(
		3, 2, []float64{0.35891648, 0.51130127, 0.408666186, 0.561370121, 0.6,
			0.6})
	if !mat64.EqualApprox(
		neuralNetwork.Layers[1].Weight, expected_weights_1, 0.0001) {
		t.Errorf("weights 1 unexpected:\n%v",
			mat64.Formatted(neuralNetwork.Layers[1].Weight))
	}
}
예제 #2
0
파일: viewport.go 프로젝트: mysll/flynet
//容器创建
func (vt *PBViewportCodec) ViewportCreate(id int32, container Entityer) interface{} {
	msg := &s2c.CreateView{}
	msg.Entity = proto.String(container.ObjTypeName())
	msg.ViewId = proto.Int32(id)
	msg.Capacity = proto.Int32(container.GetCapacity())
	return msg
}
예제 #3
0
파일: main.go 프로젝트: xinghuwang/toolbox
func main() {
	// marshal
	msg := new(demo.DemoMsg)
	msg.ClientId = proto.Int32(8)
	msg.ClientName = proto.String("foo")
	msg.Desc = proto.String("just a demo")
	item := new(demo.MsgItem)
	item.Id = proto.Int32(55)
	item.Name = proto.String("funky")
	t := demo.ItemType(demo.ItemType_TypeY)

	item.Type = &t
	msg.Items = append(msg.Items, item)
	fmt.Println(msg.String())
	data, err := proto.Marshal(msg)
	fmt.Println(err, data)

	// unmarshal
	var pb demo.DemoMsg
	err = proto.Unmarshal(data, &pb)
	if err != nil {
		panic(err)
	}

	fmt.Println(pb.String())
}
예제 #4
0
파일: msg_pk.go 프로젝트: gitter-badger/ac
// TODO: error code is not handled properly
func PKDEL_Handler(acMessagePkReq *AcPublicKeyMessageRequest) (acMsgResponse *AcPublicKeyMessageResponse, err error) {
	var responseType AcPublicKeyMessageResponseAcPKRespMsgType
	responseType = AcPublicKeyMessageResponse_PKR_DEL

	// request: type && nick && server                   -> delete the specific public key
	reqNick := acMessagePkReq.GetNick()
	reqServ := acMessagePkReq.GetServer()
	acutl.DebugLog.Printf("(CALL) PKDEL <- '%s' ! <host> / %s\n", reqNick, reqServ)

	if len(reqNick) > 0 && len(reqServ) > 0 { // IS A SPECIFIC NICK REQUESTED ?!?!
		//_, ok := Pk[reqNick]
		//Pk, ok := ackp.ACmap.GetPKMap(reqServ)
		ok := ackp.ACmap.DelPKMapEntry(reqServ, reqNick)
		if ok == true {
			//delete(Pk, reqNick)
			acMsgResponse = &AcPublicKeyMessageResponse{
				Type:      &responseType,
				Bada:      proto.Bool(true),
				ErrorCode: proto.Int32(0), // no such nickname
			}
			acutl.DebugLog.Printf("(RET) PKDEL -> (0) ! deleted key\n")
			return acMsgResponse, nil
		}
	}

	// XXX TODO: not sure If I should remove all keys or just return error
	retErr := &acutl.AcError{Value: -1, Msg: "PKDEL_Handler().reqServ|reqNick: 0 bytes", Err: nil}
	acMsgResponse = &AcPublicKeyMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(false),
		ErrorCode: proto.Int32(-1), // no such nickname
	}
	acutl.DebugLog.Printf("(RET[!]) PKDEL -> (-1) ! missing argument\n")
	return acMsgResponse, retErr
}
예제 #5
0
파일: account.go 프로젝트: Slko/stove
func OnGetAchieves(s *Session, body []byte) *Packet {
	req := util.GetAchieves{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}
	res := util.Achieves{}
	dbfAchieves := []DbfAchieve{}
	db.Find(&dbfAchieves)
	for _, achieve := range dbfAchieves {
		achieveProgress := Achieve{}
		db.Where("achieve_id = ? and account_id = ?", achieve.ID, s.Account.ID).First(&achieveProgress)

		res.List = append(res.List, &util.Achieve{
			Id:              proto.Int32(achieve.ID),
			Progress:        proto.Int32(achieveProgress.Progress),
			AckProgress:     proto.Int32(achieveProgress.AckProgress),
			CompletionCount: proto.Int32(achieveProgress.CompletionCount),
			Active:          proto.Bool(achieveProgress.Active),
			DateGiven:       PegasusDate(achieveProgress.DateGiven),
			DateCompleted:   PegasusDate(achieveProgress.DateCompleted),
		})
	}
	return EncodePacket(util.Achieves_ID, &res)
}
예제 #6
0
//通用的服务端返回给客户端的数据协议
func CommonResultReturn(conn interface{}, result string, resultId int32, num int32) {
	returnMsg := &protocol.WMessage{
		MsgType:   proto.String(result),
		MsgTypeId: proto.Int32(resultId),
		StataCode: proto.Int32(num),
	}

	buffer, err := proto.Marshal(returnMsg)
	if err != nil {
		Logger.Warn("protobuf marshal failed: ", err)
		fmt.Println("failed: ", err)
		//	Log.SetLogger("file", `{"filename": "savelog.log"}`)
		return
	}
	length := len(buffer)
	newbuffer := append(IntToBytes(length), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err := conn.(net.Conn).Write(newbuffer)
		CheckErr(err)
	case websocket.Conn:
		_, err := conn.(*websocket.Conn).Write(newbuffer)
		CheckErr(err)
	}
	return
}
예제 #7
0
func (l *evtLogger) Log(ctx context.Context, evt *crit_event.ChromeInfraEvent) {
	// Get this as soon as possible, so proto encoding time etc
	// doesn't bump the logged event time.
	clck := clock.Get(ctx)
	now := clck.Now().Unix()

	evt.EventSource = l.src
	// TODO: Consider making this a func parameter.
	evt.TimestampKind = crit_event.ChromeInfraEvent_POINT.Enum()

	if trace, ok := ctx.Value(TraceID).(string); ok {
		evt.TraceId = proto.String(trace)
	}

	// TODO:
	//	evt.SpanId = // ?
	//	evt.ParentId = // ?

	bytes, err := proto.Marshal(evt)
	if err != nil {
		logging.Errorf(ctx, "Error marshaling ChromeInfraEvent: %v", err.Error())
		return
	}

	l.evtCh <- &crit_event.LogRequestLite_LogEventLite{
		EventTimeMs:     proto.Int64(now),
		EventCode:       proto.Int32(0),
		EventFlowId:     proto.Int32(0),
		SourceExtension: bytes,
	}
}
예제 #8
0
파일: account.go 프로젝트: beheh/stove
func OnGetDeck(s *Session, body []byte) ([]byte, error) {
	req := hsproto.PegasusUtil_GetDeck{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		return nil, err
	}

	id := req.GetDeck()
	var deck Deck
	db.First(&deck, id)

	// TODO: does this also need to allow brawl/arena decks? what about AI decks?
	if deck.DeckType != int(hsproto.PegasusShared_DeckType_PRECON_DECK) && deck.AccountID != s.Account.ID {
		return nil, fmt.Errorf("received OnGetDeck for non-precon deck not owned by account")
	}

	deckCards := []DeckCard{}
	db.Where("deck_id = ?", id).Find(&deckCards)

	res := hsproto.PegasusUtil_DeckContents{
		Deck: proto.Int64(id),
	}

	for i, card := range deckCards {
		cardData := &hsproto.PegasusShared_DeckCardData{
			Def:    MakeCardDef(card.CardID, card.Premium),
			Handle: proto.Int32(int32(i)),
			Qty:    proto.Int32(card.Num),
			Prev:   proto.Int32(int32(i) - 1),
		}
		res.Cards = append(res.Cards, cardData)
	}

	return EncodeUtilResponse(215, &res)
}
예제 #9
0
파일: account.go 프로젝트: beheh/stove
func OnGetAchieves(s *Session, body []byte) ([]byte, error) {
	req := hsproto.PegasusUtil_GetAchieves{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		return nil, err
	}
	res := hsproto.PegasusUtil_Achieves{}
	dbfAchieves := []DbfAchieve{}
	db.Find(&dbfAchieves)
	for _, achieve := range dbfAchieves {
		achieveProgress := Achieve{}
		db.Where("achieve_id = ? and account_id = ?", achieve.ID, s.Account.ID).First(&achieveProgress)

		res.List = append(res.List, &hsproto.PegasusUtil_Achieve{
			Id:              proto.Int32(achieve.ID),
			Progress:        proto.Int32(achieveProgress.Progress),
			AckProgress:     proto.Int32(achieveProgress.AckProgress),
			CompletionCount: proto.Int32(achieveProgress.CompletionCount),
			Active:          proto.Bool(achieveProgress.Active),
			DateGiven:       PegasusDate(achieveProgress.DateGiven),
			DateCompleted:   PegasusDate(achieveProgress.DateCompleted),
		})
	}
	return EncodeUtilResponse(252, &res)
}
예제 #10
0
파일: insert.go 프로젝트: datastream/btree
// Insert can insert record into a btree
func (t *Btree) insert(record TreeLog) error {
	tnode, err := t.getTreeNode(t.GetRoot())
	if err != nil {
		if err.Error() != "no data" {
			return err
		}
		nnode := t.newTreeNode()
		nnode.NodeType = proto.Int32(isLeaf)
		_, err = nnode.insertRecord(record, t)
		if err == nil {
			t.Nodes[nnode.GetId()], err = proto.Marshal(nnode)
		}
		t.Root = proto.Int64(nnode.GetId())
		return err
	}
	clonednode, err := tnode.insertRecord(record, t)
	if err == nil && len(clonednode.GetKeys()) > int(t.GetNodeMax()) {
		nnode := t.newTreeNode()
		nnode.NodeType = proto.Int32(isNode)
		key, left, right := clonednode.split(t)
		nnode.insertOnce(key, left, right, t)
		t.Nodes[nnode.GetId()], err = proto.Marshal(nnode)
		t.Root = proto.Int64(nnode.GetId())
	} else {
		t.Root = proto.Int64(clonednode.GetId())
	}
	return err
}
예제 #11
0
파일: account.go 프로젝트: Slko/stove
func OnGetDeck(s *Session, body []byte) *Packet {
	req := util.GetDeck{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}

	id := req.GetDeck()
	var deck Deck
	db.First(&deck, id)

	// TODO: does this also need to allow brawl/arena decks? what about AI decks?
	if deck.DeckType != int(shared.DeckType_PRECON_DECK) && deck.AccountID != s.Account.ID {
		log.Panicf("received OnGetDeck for non-precon deck not owned by account")
	}

	deckCards := []DeckCard{}
	db.Where("deck_id = ?", id).Find(&deckCards)

	res := util.DeckContents{
		Deck: proto.Int64(id),
	}

	for i, card := range deckCards {
		cardData := &shared.DeckCardData{
			Def:    MakeCardDef(card.CardID, card.Premium),
			Handle: proto.Int32(int32(i)),
			Qty:    proto.Int32(card.Num),
			Prev:   proto.Int32(int32(i) - 1),
		}
		res.Cards = append(res.Cards, cardData)
	}

	return EncodePacket(util.DeckContents_ID, &res)
}
예제 #12
0
func NewStartRequest(path string, dir string, args []string, allocated resource.ComputeResource, envs []string, host string, port int32) *cmd.ControlMessage {
	request := &cmd.ControlMessage{
		Type: cmd.ControlMessage_StartRequest.Enum(),
		StartRequest: &cmd.StartRequest{
			Path: proto.String(path),
			Args: args,
			Dir:  proto.String(dir),
			Resource: &cmd.ComputeResource{
				CpuCount: proto.Int32(int32(allocated.CPUCount)),
				CpuLevel: proto.Int32(int32(allocated.CPULevel)),
				Memory:   proto.Int32(int32(allocated.MemoryMB)),
			},
			Envs:     envs,
			Host:     proto.String(host),
			Port:     proto.Int32(port),
			HashCode: proto.Uint32(0),
		},
	}

	// generate a unique hash code for the request
	data, err := proto.Marshal(request)
	if err != nil {
		log.Fatalf("marshaling start request error: %v", err)
		return nil
	}
	request.StartRequest.HashCode = proto.Uint32(uint32(util.Hash(data)))

	return request
}
예제 #13
0
파일: filter.go 프로젝트: jfrabaute/gohbase
// NewColumnPaginationFilter is TODO
func NewColumnPaginationFilter(limit, offset int32, columnOffset []byte) *ColumnPaginationFilter {
	return &ColumnPaginationFilter{
		Limit:        proto.Int32(limit),
		Offset:       proto.Int32(offset),
		ColumnOffset: columnOffset,
	}
}
예제 #14
0
func processLogin(server *sev.Nexus, ipStr string,
	message *protocol.MobileSuiteModel) {
	loginDto := &protocol.LoginDTO{}
	proto.Unmarshal(message.Message, loginDto)

	userArr, err := server.DbConnector.QueryByUserName(
		*loginDto.UName, *loginDto.Pwd)
	if err != nil || userArr == nil || len(userArr) < 1 {
		sendBack(server, ipStr, nil,
			int32(protocol.MessageType_MSG_TYPE_LOGIN_RES))
		return
	}

	//loginResultDto := &protocol.LoginResultDTO{}
	//loginResultDto.UserId = loginDto.UserId
	//strName := strconv.FormatInt(*loginResultDto.UserId, 10)
	//loginResultDto.UName = &strName

	user := dao.User(userArr[0])

	// 登陆成功
	loginResultDto := &protocol.LoginResultDTO{}
	loginResultDto.UserId = proto.Int64(user.Id)
	loginResultDto.UName = &user.Name
	loginResultDto.Round = proto.Int32(int32(user.Round))
	loginResultDto.WinCount = proto.Int32(int32(user.WinCount))
	loginResultDto.Rank = proto.Int32(int32(user.Rank))

	byt, _ := proto.Marshal(loginResultDto)
	sendBack(server, ipStr, byt,
		int32(protocol.MessageType_MSG_TYPE_LOGIN_RES))
}
예제 #15
0
파일: draft.go 프로젝트: synap5e/stove
func MakeChest() (chest shared.RewardChest) {
	// TODO take arguments to determine the contents
	// There are up to 5 bags each which can hold a booster, card, dust or gold

	chest.Bag1 = &shared.RewardBag{
		RewardBooster: &shared.ProfileNoticeRewardBooster{
			BoosterType:  proto.Int32(1),
			BoosterCount: proto.Int32(1),
		},
	}
	chest.Bag2 = &shared.RewardBag{
		RewardCard: &shared.ProfileNoticeRewardCard{
			Card:     MakeCardDef(2078, 1),
			Quantity: proto.Int32(1),
		},
	}
	chest.Bag3 = &shared.RewardBag{
		RewardDust: &shared.ProfileNoticeRewardDust{
			Amount: proto.Int32(69),
		},
	}
	chest.Bag4 = &shared.RewardBag{
		RewardGold: &shared.ProfileNoticeRewardGold{
			Amount: proto.Int32(42),
		},
	}
	return chest
}
예제 #16
0
파일: msg_ctl.go 프로젝트: gitter-badger/ac
func CTLSAVE_Handler(acMessageCtlReq *AcControlMessageRequest) (acMsgResponse *AcControlMessageResponse, err error) {
	var responseType AcControlMessageResponseAcCTLRRespMsgType
	responseType = AcControlMessageResponse_CTLR_SAVECTX
	reqPassword := acMessageCtlReq.GetPassword()

	acutl.DebugLog.Printf("(CALL) SAVECTX '%s'\n", reqPassword)

	//func (psk PSKMap) Map2FileBlob(outfilestr string, salt []byte, keystr []byte) (bool, error) {
	// TODO: we hardcode the save file
	ok, err := ackp.ACmap.Map2File(ackp.AcSaveFile, []byte(reqPassword))
	if err != nil || ok != false {
		retErr := &acutl.AcError{Value: -1, Msg: "CTLSAVE_Handler().args(outfile, salt, keystr): 0 bytes", Err: nil}
		acMsgResponse = &AcControlMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
		}
		acutl.DebugLog.Printf("(RET[!]) SAVECTX -> (-1) Map2File failed\n")
		return acMsgResponse, retErr
	}
	acMsgResponse = &AcControlMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0),
	}
	acutl.DebugLog.Printf("(RET) SAVECTX -> (0) ! '%s' saved\n", reqPassword)
	return acMsgResponse, nil
}
예제 #17
0
// DoCustomMetadata checks that metadata is echoed back to the client.
func DoCustomMetadata(tc testpb.TestServiceClient) {
	// Testing with UnaryCall.
	pl := clientNewPayload(testpb.PayloadType_COMPRESSABLE, 1)
	req := &testpb.SimpleRequest{
		ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
		ResponseSize: proto.Int32(int32(1)),
		Payload:      pl,
	}
	ctx := metadata.NewContext(context.Background(), customMetadata)
	var header, trailer metadata.MD
	reply, err := tc.UnaryCall(
		ctx,
		req,
		grpc.Header(&header),
		grpc.Trailer(&trailer),
	)
	if err != nil {
		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
	}
	t := reply.GetPayload().GetType()
	s := len(reply.GetPayload().GetBody())
	if t != testpb.PayloadType_COMPRESSABLE || s != 1 {
		grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, 1)
	}
	validateMetadata(header, trailer)

	// Testing with FullDuplex.
	stream, err := tc.FullDuplexCall(ctx)
	if err != nil {
		grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
	}
	respParam := []*testpb.ResponseParameters{
		{
			Size: proto.Int32(1),
		},
	}
	streamReq := &testpb.StreamingOutputCallRequest{
		ResponseType:       testpb.PayloadType_COMPRESSABLE.Enum(),
		ResponseParameters: respParam,
		Payload:            pl,
	}
	if err := stream.Send(streamReq); err != nil {
		grpclog.Fatalf("%v.Send(%v) = %v", stream, streamReq, err)
	}
	streamHeader, err := stream.Header()
	if err != nil {
		grpclog.Fatalf("%v.Header() = %v", stream, err)
	}
	if _, err := stream.Recv(); err != nil {
		grpclog.Fatalf("%v.Recv() = %v", stream, err)
	}
	if err := stream.CloseSend(); err != nil {
		grpclog.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err)
	}
	if _, err := stream.Recv(); err != io.EOF {
		grpclog.Fatalf("%v failed to complete the custom metadata test: %v", stream, err)
	}
	streamTrailer := stream.Trailer()
	validateMetadata(streamHeader, streamTrailer)
}
예제 #18
0
파일: msg_ctl.go 프로젝트: gitter-badger/ac
func CTLLOAD_Handler(acMessageCtlReq *AcControlMessageRequest) (acMsgResponse *AcControlMessageResponse, err error) {
	var responseType AcControlMessageResponseAcCTLRRespMsgType
	responseType = AcControlMessageResponse_CTLR_LOADCTX
	reqPassword := acMessageCtlReq.GetPassword()

	acutl.DebugLog.Printf("(CALL) LOADCTX '%s'\n", []byte(reqPassword))

	ok, err := ackp.ACmap.File2Map(ackp.AcSaveFile, []byte(reqPassword))
	if err != nil || ok != false {
		retErr := &acutl.AcError{Value: -1, Msg: "CTLLOAD_Handler().args(outfile, salt, keystr): 0 bytes", Err: nil}
		acMsgResponse = &AcControlMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
		}
		acutl.DebugLog.Printf("(RET[!]) LOADCTX -> (-1)\n")
		return acMsgResponse, retErr
	}
	acMsgResponse = &AcControlMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0),
	}
	acutl.DebugLog.Printf("(RET) LOADCTX -> (0) ! '%s' opened\n", reqPassword)
	return acMsgResponse, nil
}
예제 #19
0
파일: msg_ctl.go 프로젝트: gitter-badger/ac
func CTLPING_Handler(acMessageCtlReq *AcControlMessageRequest) (acMsgResponse *AcControlMessageResponse, err error) {
	var responseType AcControlMessageResponseAcCTLRRespMsgType
	responseType = AcControlMessageResponse_CTLR_PONG
	timeStamp := acMessageCtlReq.GetTimestamp()

	acutl.DebugLog.Printf("(CALL) CTLPING timestamp: %d\n", timeStamp)

	if timeStamp <= 0 {
		retErr := &acutl.AcError{Value: -1, Msg: "CTLPING invalid timestamp", Err: nil}
		acMsgResponse = &AcControlMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
		}
		acutl.DebugLog.Printf("(RET[!]) CTLPING -> (-1) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}

	replyTime := time.Now().Unix()

	acMsgResponse = &AcControlMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0), // should be good enough for now... but better have a separate field with correct type..
		Timestamp: &replyTime,
	}
	acutl.DebugLog.Printf("(RET) CTLPING -> (0) ! PONG REPLIED. %d\n", replyTime)
	return acMsgResponse, nil
}
예제 #20
0
// StartHostedProgram is the client stub for LinuxHost.StartHostedProgram.
func (client LinuxHostAdminClient) StartHostedProgram(spec *HostedProgramSpec) (auth.SubPrin, int, error) {
	req := &LinuxHostAdminRPCRequest{
		Path:          proto.String(spec.Path),
		Dir:           proto.String(spec.Dir),
		ContainerArgs: spec.ContainerArgs,
		Args:          spec.Args,
		// TODO: pass uid and gid?
	}
	var fds []int
	if spec.Stdin != nil {
		req.Stdin = proto.Int32(int32(len(fds)))
		fds = append(fds, int(spec.Stdin.Fd()))
	}
	if spec.Stdin != nil {
		req.Stdout = proto.Int32(int32(len(fds)))
		fds = append(fds, int(spec.Stdout.Fd()))
	}
	if spec.Stdin != nil {
		req.Stderr = proto.Int32(int32(len(fds)))
		fds = append(fds, int(spec.Stderr.Fd()))
	}
	resp := new(LinuxHostAdminRPCResponse)
	client.oob.ShareFDs(fds...)
	err := client.Call("LinuxHost.StartHostedProgram", req, resp)
	if err != nil {
		return auth.SubPrin{}, 0, err
	}
	if len(resp.Child) != 1 {
		return auth.SubPrin{}, 0, newError("invalid response")
	}
	subprin, err := auth.UnmarshalSubPrin(resp.Child[0].Subprin)
	return subprin, int(*resp.Child[0].Pid), err
}
예제 #21
0
파일: msg_pk.go 프로젝트: gitter-badger/ac
func PKGEN_Handler(acMessagePkReq *AcPublicKeyMessageRequest) (acMsgResponse *AcPublicKeyMessageResponse, err error) {
	var responseType AcPublicKeyMessageResponseAcPKRespMsgType
	responseType = AcPublicKeyMessageResponse_PKR_GEN

	reqNick := acMessagePkReq.GetNick()
	reqHost := acMessagePkReq.GetHost()
	reqServ := acMessagePkReq.GetServer()

	acutl.DebugLog.Printf("(CALL) PKGEN <- %s ! %s / %s\n", reqNick, reqHost, reqServ)

	if len(reqServ) == 0 || len(reqNick) == 0 {
		retErr := &acutl.AcError{Value: -1, Msg: "PKGEN_Handler().Get{Nick|Server}(): 0 bytes", Err: nil}
		acMsgResponse = &AcPublicKeyMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
			Blob:      []byte(retErr.Error()),
		}
		acutl.DebugLog.Printf("(RET[!]) PKGEN -> (-1) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}

	myNewKeys, err := ackp.CreateKxKeys(reqNick, reqHost, reqServ)
	if err != nil {
		retErr := &acutl.AcError{Value: -2, Msg: "PKGEN_Handler().CreateMyKeys(): ", Err: err}
		acMsgResponse = &AcPublicKeyMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-2),
			Blob:      []byte(retErr.Error()),
		}
		acutl.DebugLog.Printf("(RET[!]) PKGEN -> (-2) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}
	// create the cached version instead of in CreateMyKeys()
	PK, err := accp.CreatePKMessageNACL(myNewKeys.GetPubkey()[:])
	if err != nil {
		retErr := &acutl.AcError{Value: -3, Msg: "PKGEN_Handler().CreateCachePubkey: ", Err: err}
		acMsgResponse = &AcPublicKeyMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-3),
			Blob:      []byte(retErr.Error()),
		}
		acutl.DebugLog.Printf("(RET[!]) PKGEN -> (-3) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}
	myNewKeys.Pubkey = string(PK)

	// create the Public Key storage if it's empty...
	ackp.ACmap.SetPKMapEntry(reqServ, reqNick, myNewKeys)
	acMsgResponse = &AcPublicKeyMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0),
	}
	acutl.DebugLog.Printf("(RET) PKGEN -> (0) ! Key Generated.\n")
	return acMsgResponse, nil
}
예제 #22
0
파일: viewport.go 프로젝트: mysll/flynet
//容器交换位置
func (vp *PBViewportCodec) ViewportNotifyExchange(srcid int32, src int32, destid int32, dest int32) interface{} {
	msg := &s2c.ViewExchange{}
	msg.ViewId1 = proto.Int32(srcid)
	msg.Index1 = proto.Int32(src)
	msg.ViewId2 = proto.Int32(destid)
	msg.Index2 = proto.Int32(dest)
	return msg
}
예제 #23
0
파일: viewport.go 프로젝트: mysll/flynet
//容器里增加对象
func (vp *PBViewportCodec) ViewportNotifyAdd(id int32, index int32, object Entityer) interface{} {
	msg := &s2c.ViewAdd{}
	msg.ViewId = proto.Int32(id)
	msg.Entity = proto.String(object.ObjTypeName())
	msg.Index = proto.Int32(index)
	msg.Props, _ = object.Serial()
	return msg
}
예제 #24
0
// PbMsgFactory: create msg by given params
func PbMsgFactory(Id int32, Topic string, Content string, Type int32) *msgproto.Msg {
	return &msgproto.Msg{
		Id:      proto.Int32(Id),
		Topic:   proto.String(Topic),
		Content: proto.String(Content),
		Type:    proto.Int32(Type),
	}
}
예제 #25
0
파일: draft.go 프로젝트: synap5e/stove
func OnDraftMakePick(s *Session, body []byte) *Packet {
	req := util.DraftMakePick{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}

	draft := Draft{}
	if db.Where("not ended and account_id = ?", s.Account.ID).First(&draft).RecordNotFound() {
		log.Panicf("received OnDraftMakePick for account with no active draft")
	}
	if req.GetSlot() != draft.CurrentSlot {
		log.Panicf("received OnDraftMakePick for the wrong slot")
	}
	if req.GetDeckId() != draft.DeckID {
		log.Panicf("received OnDraftMakePick for the wrong deck")
	}
	pick := DraftChoice{}
	db.Where("draft_id = ? and choice_index = ?", draft.ID, req.GetIndex()).First(&pick)
	db.Where("draft_id = ?", draft.ID).Delete(&DraftChoice{})

	if draft.CurrentSlot == 0 {
		deck := Deck{}
		db.Where("id = ?", draft.DeckID).First(&deck)
		deck.HeroID = pick.CardID
		deck.HeroPremium = 0
		deck.LastModified = time.Now().UTC()
		db.Save(&deck)
	} else {
		card := DeckCard{
			DeckID:  draft.DeckID,
			CardID:  pick.CardID,
			Premium: 0,
			Num:     1,
		}
		db.Save(&card)
	}

	if draft.CurrentSlot < 30 {
		draft.Choices = MakeCardChoices(draft.CurrentSlot)
	}
	draft.CurrentSlot += 1
	db.Save(&draft)

	choices := []*shared.CardDef{}
	for _, choice := range draft.Choices {
		choices = append(choices, &shared.CardDef{
			Asset:   proto.Int32(choice.CardID),
			Premium: proto.Int32(int32(0)),
		})
	}
	res := util.DraftChosen{
		Chosen:         MakeCardDef(pick.CardID, 0),
		NextChoiceList: choices,
	}

	return EncodePacket(util.DraftChosen_ID, &res)
}
예제 #26
0
func newTestMessage() *pb.MyMessage {
	msg := &pb.MyMessage{
		Count: proto.Int32(42),
		Name:  proto.String("Dave"),
		Quote: proto.String(`"I didn't want to go."`),
		Pet:   []string{"bunny", "kitty", "horsey"},
		Inner: &pb.InnerMessage{
			Host:      proto.String("footrest.syd"),
			Port:      proto.Int32(7001),
			Connected: proto.Bool(true),
		},
		Others: []*pb.OtherMessage{
			{
				Key:   proto.Int64(0xdeadbeef),
				Value: []byte{1, 65, 7, 12},
			},
			{
				Weight: proto.Float32(6.022),
				Inner: &pb.InnerMessage{
					Host: proto.String("lesha.mtv"),
					Port: proto.Int32(8002),
				},
			},
		},
		Bikeshed: pb.MyMessage_BLUE.Enum(),
		Somegroup: &pb.MyMessage_SomeGroup{
			GroupField: proto.Int32(8),
		},
		// One normally wouldn't do this.
		// This is an undeclared tag 13, as a varint (wire type 0) with value 4.
		XXX_unrecognized: []byte{13<<3 | 0, 4},
	}
	ext := &pb.Ext{
		Data: proto.String("Big gobs for big rats"),
	}
	if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil {
		panic(err)
	}
	greetings := []string{"adg", "easy", "cow"}
	if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil {
		panic(err)
	}

	// Add an unknown extension. We marshal a pb.Ext, and fake the ID.
	b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")})
	if err != nil {
		panic(err)
	}
	b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...)
	proto.SetRawExtension(msg, 201, b)

	// Extensions can be plain fields, too, so let's test that.
	b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19)
	proto.SetRawExtension(msg, 202, b)

	return msg
}
예제 #27
0
파일: kettle.go 프로젝트: synap5e/stove
func MakeTag(name, value int) *game.Tag {
	t := &game.Tag{}
	if name == 50 {
		value -= 1
	}
	t.Name = proto.Int32(int32(name))
	t.Value = proto.Int32(int32(value))
	return t
}
예제 #28
0
파일: draft.go 프로젝트: synap5e/stove
func ChoicesToCardDefs(choices []DraftChoice) (defs []*shared.CardDef) {
	for _, choice := range choices {
		defs = append(defs, &shared.CardDef{
			Asset:   proto.Int32(choice.CardID),
			Premium: proto.Int32(int32(0)),
		})
	}
	return defs
}
예제 #29
0
func (t *NotificationTemplate) GetActionChains() []*protobuf.ActionChain {

	//set actionChain
	actionChain1 := &protobuf.ActionChain{
		ActionId: proto.Int32(1),
		Type:     protobuf.ActionChain_Goto.Enum(),
		Next:     proto.Int32(10000),
	}

	//notification
	actionChain2 := &protobuf.ActionChain{
		ActionId:  proto.Int32(10000),
		Type:      protobuf.ActionChain_notification.Enum(),
		Title:     proto.String(t.Title),
		Text:      proto.String(t.Text),
		Logo:      proto.String(t.Logo),
		Ring:      proto.Bool(t.IsRing),
		Clearable: proto.Bool(t.IsClearable),
		Buzz:      proto.Bool(t.IsVibrate),
		Next:      proto.Int32(10010),
	}

	//goto
	actionChain3 := &protobuf.ActionChain{
		ActionId: proto.Int32(10010),
		Type:     protobuf.ActionChain_Goto.Enum(),
		Next:     proto.Int32(10030),
	}

	//appStartUp
	appStartUp := &protobuf.AppStartUp{
		Android: proto.String(""),
		Symbia:  proto.String(""),
		Ios:     proto.String(""),
	}

	//start app
	actionChain4 := &protobuf.ActionChain{
		ActionId:     proto.Int32(10030),
		Type:         protobuf.ActionChain_startapp.Enum(),
		Appid:        proto.String(""),
		Autostart:    proto.Bool(t.TransmissionType == 1),
		Appstartupid: appStartUp,
		FailedAction: proto.Int32(100),
		Next:         proto.Int32(100),
	}
	//end
	actionChain5 := &protobuf.ActionChain{
		ActionId: proto.Int32(100),
		Type:     protobuf.ActionChain_eoa.Enum(),
	}

	actionChains := []*protobuf.ActionChain{actionChain1, actionChain2, actionChain3, actionChain4, actionChain5}

	return actionChains
}
예제 #30
0
파일: account.go 프로젝트: Slko/stove
func (s *Session) GetBoosterInfo(kind int32) *shared.BoosterInfo {
	var count int32
	db.Model(Booster{}).
		Where("booster_type = ? and opened = ? and account_id = ?", kind, false, s.Account.ID).
		Count(&count)
	res := &shared.BoosterInfo{}
	res.Count = proto.Int32(count)
	res.Type = proto.Int32(kind)
	return res
}