// SerializeCells creates a MetricsCollection message from a slice of cells.
181194
func SerializeCells(cells []types.Cell, now time.Time) []*pb.MetricsCollection {
	collections := map[uint64]*pb.MetricsCollection{}
	dataSets := map[dataSetKey]*pb.MetricsDataSet{}

	for _, c := range cells {
		// Find the collection, add it if it doesn't exist.
		targetHash := c.Target.Hash()
		collection, ok := collections[targetHash]
		if !ok {
			collection = &pb.MetricsCollection{}
			collections[targetHash] = collection
			c.Target.PopulateProto(collection)
		}

		// Find the data set, add it if it doesn't exist.
		key := dataSetKey{targetHash, c.Name}
		dataSet, ok := dataSets[key]
		if !ok {
			dataSet = SerializeDataSet(c)
			dataSets[key] = dataSet
			collection.MetricsDataSet = append(collection.MetricsDataSet, dataSet)
		}

		// Add the data to the data set.
		dataSet.Data = append(dataSet.Data, SerializeValue(c, now))
	}

	// Turn the hash into a list and return it.
	ret := make([]*pb.MetricsCollection, 0, len(collections))
	for _, collection := range collections {
		ret = append(ret, collection)
	}
	return ret
}
1246498
func (p *Profiler) Serialize(f *freq.Frequency) []byte {
	// ensure the Builder is in a usable state.
	p.Builder.Reset()
	uoffs := make([]fb.UOffsetT, len(f.CPU))
	for i, cpu := range f.CPU {
		uoffs[i] = p.SerializeCPU(&cpu)
	}
	structs.FrequencyStartCPUVector(p.Builder, len(uoffs))
	for i := len(uoffs) - 1; i >= 0; i-- {
		p.Builder.PrependUOffsetT(uoffs[i])
	}
	cpusV := p.Builder.EndVector(len(uoffs))
	structs.FrequencyStart(p.Builder)
	structs.FrequencyAddTimestamp(p.Builder, f.Timestamp)
	structs.FrequencyAddSockets(p.Builder, f.Sockets)
	structs.FrequencyAddCPU(p.Builder, cpusV)
	p.Builder.Finish(structs.FrequencyEnd(p.Builder))
	b := p.Builder.Bytes[p.Builder.Head():]
	// copy them (otherwise gets lost in reset)
	tmp := make([]byte, len(b))
	copy(tmp, b)
	return tmp
}
52948
func (b *ImportLookupBody) Serialize(version uint8) ([]byte, error) {
	buf := make([]byte, 1)
	buf[0] = b.PrefixLength
	buf = append(buf, b.Addr.To4()...)
	return buf, nil
}
524699
func (m *multi) DeserializeCellBlocks(msg proto.Message, b []byte) (uint32, error) {
	mr := msg.(*pb.MultiResponse)

	var nread uint32
	for _, rar := range mr.GetRegionActionResult() {
		if e := rar.GetException(); e != nil {
			if l := len(rar.GetResultOrException()); l != 0 {
				return 0, fmt.Errorf(
					"got exception for region, but still have %d result(s) returned from it", l)
			}
			continue
		}

		for _, roe := range rar.GetResultOrException() {
			e := roe.GetException()
			r := roe.GetResult()
			i := roe.GetIndex()

			if i == 0 {
				return 0, errors.New("no index for result in multi response")
			} else if r == nil && e == nil {
				return 0, errors.New("no result or exception for action in multi response")
			} else if r != nil && e != nil {
				return 0, errors.New("got result and exception for action in multi response")
			} else if e != nil {
				continue
			}

			c := m.get(i)                     // TODO: maybe return error if it's out-of-bounds
			d := c.(canDeserializeCellBlocks) // let it panic, because then it's our bug

			response := c.NewResponse()
			switch rsp := response.(type) {
			case *pb.GetResponse:
				rsp.Result = r
			case *pb.MutateResponse:
				rsp.Result = r
			default:
				panic(fmt.Sprintf("unsupported response type for Multi: %T", response))
			}

			// TODO: don't bother deserializing if the call's context has already expired
			n, err := d.DeserializeCellBlocks(response, b[nread:])
			if err != nil {
				return 0, fmt.Errorf(
					"error deserializing cellblocks for %q call as part of MultiResponse: %v",
					c.Name(), err)
			}
			nread += n
		}
	}
	return nread, nil
}
671213
func (m *Table) FieldsAsMessages() []Message {
	msgs := make([]Message, len(m.Fields))
	for i, f := range m.Fields {
		msgs[i] = f
	}
	return msgs
}
900432
func removeCells(cells, toRemove, fullList []string) ([]string, bool) {
	// The assumption here is we already migrated something,
	// and we're reverting that part. So we're gonna remove
	// records only.
	leftoverCells := make([]string, 0, len(cells))
	if len(cells) == 0 {
		// we migrated all the cells already, take the full list
		// and remove all the ones we're not reverting
		for _, cell := range fullList {
			if !InCellList(cell, toRemove) {
				leftoverCells = append(leftoverCells, cell)
			}
		}
	} else {
		// we migrated a subset of the cells,
		// remove the ones we're reverting
		for _, cell := range cells {
			if !InCellList(cell, toRemove) {
				leftoverCells = append(leftoverCells, cell)
			}
		}
	}

	if len(leftoverCells) == 0 {
		// we don't have any cell left, we need to clear this record
		return nil, true
	}

	return leftoverCells, false
}
451308
func Serialize(v interface{}, simple bool) []byte {
	return NewWriter(simple).Serialize(v).Bytes()
}
637420
func (s SerializeFunc) Serialize(obj interface{}, options ...map[string]interface{}) ([]byte, error) {
	return s(obj, options...)
}
1195457
func (graphite *Graphite) sendMetrics(metrics []Metric) error {
	if graphite.IsNop() {
		for _, metric := range metrics {
			log.Printf("Graphite: %s\n", metric)
		}
		return nil
	}
	zeroed_metric := Metric{} // ignore unintialized metrics
	buf := bytes.NewBufferString("")
	for _, metric := range metrics {
		if metric == zeroed_metric {
			continue // ignore unintialized metrics
		}
		if metric.Timestamp == 0 {
			metric.Timestamp = time.Now().Unix()
		}
		metric_name := ""
		if graphite.Prefix != "" {
			metric_name = fmt.Sprintf("%s.%s", graphite.Prefix, metric.Name)
		} else {
			metric_name = metric.Name
		}
		if graphite.Protocol == "udp" {
			fmt.Fprintf(graphite.conn, "%s %s %d\n", metric_name, metric.Value, metric.Timestamp)
			continue
		}
		buf.WriteString(fmt.Sprintf("%s %s %d\n", metric_name, metric.Value, metric.Timestamp))
	}
	if graphite.Protocol == "tcp" {
		_, err := graphite.conn.Write(buf.Bytes())
		//fmt.Print("Sent msg:", buf.String(), "'")
		if err != nil {
			return err
		}
	}
	return nil
}
809471
func (p *Profiler) Serialize(proc *procs.Processors) ([]byte, error) {
	return json.Marshal(proc)
}
1121840
func (c *Collector) metricsMessages() (out []producers.MetricsMessage) {
	var msg producers.MetricsMessage
	t := time.Unix(c.timestamp, 0)

	for _, cm := range c.containerMetrics {
		datapoints, err := c.createContainerDatapoints(cm)
		if err == ErrNoStatistics {
			c.log.Warnf("Container ID %q did not supply any statistics; no metrics message will be sent", cm.ContainerID)
			continue
		}
		if err != nil {
			c.log.Errorf("Could not retrieve datapoints for container ID %q: %s", cm.ContainerID, err)
			continue
		}
		msg = producers.MetricsMessage{
			Name:       producers.ContainerMetricPrefix,
			Datapoints: datapoints,
			Timestamp:  t.UTC().Unix(),
		}

		fi := getFrameworkInfoByFrameworkID(cm.FrameworkID, c.agentState.Frameworks)
		if fi == nil {
			c.log.Warnf("Did not find FrameworkInfo for framework ID %s, skipping!", cm.FrameworkID)
			continue
		}

		ei := getExecutorInfoByExecutorID(cm.ExecutorID, fi.Executors)
		if ei == nil {
			c.log.Warnf("Did not find ExecutorInfo for executor ID %s, skipping!", cm.ExecutorID)
			continue
		}

		ti := getTaskInfoByContainerID(cm.ContainerID, ei.Tasks)
		if ti == nil {
			// This is not a warning because task ID is not guaranteed to be set, eg
			// a custom executor is a container with no associated task.
			c.log.Debugf("Did not find TaskInfo for container ID %s.", cm.ContainerID)
		}

		msg.Dimensions = producers.Dimensions{
			MesosID:            c.nodeInfo.MesosID,
			ClusterID:          c.nodeInfo.ClusterID,
			Hostname:           c.nodeInfo.Hostname,
			ContainerID:        cm.ContainerID,
			ExecutorID:         cm.ExecutorID,
			FrameworkID:        cm.FrameworkID,
			FrameworkName:      fi.Name,
			FrameworkRole:      fi.Role,
			FrameworkPrincipal: fi.Principal,
			Labels:             getLabelsByContainerID(cm.ContainerID, c.agentState.Frameworks, c.log),
		}

		if ti != nil {
			msg.Dimensions.TaskID = ti.ID
			msg.Dimensions.TaskName = ti.Name
		}
		out = append(out, msg)
	}
	return out
}
364125
func (prof *Profiler) Serialize(st *structs.DiskStats) ([]byte, error) {
	return json.Marshal(st)
}
701834
func Serialize(fields []Field, values []interface{}) []*pb.MetricsData_MetricField {
	ret := make([]*pb.MetricsData_MetricField, len(fields))

	for i, f := range fields {
		d := &pb.MetricsData_MetricField{
			Name: proto.String(f.Name),
		}

		switch f.Type {
		case StringType:
			d.Value = &pb.MetricsData_MetricField_StringValue{values[i].(string)}
		case BoolType:
			d.Value = &pb.MetricsData_MetricField_BoolValue{values[i].(bool)}
		case IntType:
			d.Value = &pb.MetricsData_MetricField_Int64Value{values[i].(int64)}
		}

		ret[i] = d
	}

	return ret
}
1106095
func Serialize(u *up.Uptime) []byte {
	mu.Lock()
	defer mu.Unlock()
	// ensure the Builder is in a usable state.
	builder.Reset()
	structs.UptimeStart(builder)
	structs.UptimeAddTimestamp(builder, u.Timestamp)
	structs.UptimeAddUptime(builder, u.Uptime)
	builder.Finish(structs.UptimeEnd(builder))
	p := builder.Bytes[builder.Head():]
	// copy them (otherwise gets lost in reset)
	tmp := make([]byte, len(p))
	copy(tmp, p)
	return tmp
}
484690
func (m *MetricBatch) Metrics() []Metric {
	result := make([]Metric, len(m.doc.Metrics))
	copy(result, m.doc.Metrics)
	return result
}
676376
func (prof *Profiler) Serialize(f *freq.Frequency) ([]byte, error) {
	return json.Marshal(f)
}
1027824
func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
	var err error
	cell, err = f.mergeCellsParser(xlsx, cell)
	if err != nil {
		return nil, 0, 0, err
	}
	col, row, err := CellNameToCoordinates(cell)
	if err != nil {
		return nil, 0, 0, err
	}

	prepareSheetXML(xlsx, col, row)

	return &xlsx.SheetData.Row[row-1].C[col-1], col, row, err
}