// parseHeapSample parses a single row from a heap profile into a new Sample.
768865
func parseHeapSample(line string, rate int64, sampling string) (value []int64, blocksize int64, addrs []uint64, err error) {
	sampleData := heapSampleRE.FindStringSubmatch(line)
	if len(sampleData) != 6 {
		return value, blocksize, addrs, fmt.Errorf("unexpected number of sample values: got %d, want 6", len(sampleData))
	}

	// Use first two values by default; tcmalloc sampling generates the
	// same value for both, only the older heap-profile collect separate
	// stats for in-use and allocated objects.
	valueIndex := 1
	if LegacyHeapAllocated {
		valueIndex = 3
	}

	var v1, v2 int64
	if v1, err = strconv.ParseInt(sampleData[valueIndex], 10, 64); err != nil {
		return value, blocksize, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
	}
	if v2, err = strconv.ParseInt(sampleData[valueIndex+1], 10, 64); err != nil {
		return value, blocksize, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
	}

	if v1 == 0 {
		if v2 != 0 {
			return value, blocksize, addrs, fmt.Errorf("allocation count was 0 but allocation bytes was %d", v2)
		}
	} else {
		blocksize = v2 / v1
		if sampling == "v2" {
			v1, v2 = scaleHeapSample(v1, v2, rate)
		}
	}

	value = []int64{v1, v2}
	addrs = parseHexAddresses(sampleData[5])

	return value, blocksize, addrs, nil
}
52812
func StringSample(stringList ...string) string {
	str := ""
	if len(stringList) > 0 {
		str = stringList[Number(0, len(stringList))]
	}
	return str
}
806530
func (s *ExpDecaySample) Snapshot() Sample {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	vals := s.values.Values()
	values := make([]int64, len(vals))
	for i, v := range vals {
		values[i] = v.v
	}
	return &SampleSnapshot{
		count:  s.count,
		values: values,
	}
}
461187
func (wav *Reader) ReadSample() (n int32, err error) {
	s, err := wav.ReadRawSample()
	if err != nil {
		return 0, err
	}

	switch wav.bytesPerSample {
	case 1:
		n = int32(s[0])
	case 2:
		n = int32(s[0]) + int32(s[1])<<8
	case 3:
		n = int32(s[0]) + int32(s[1])<<8 + int32(s[2])<<16
	case 4:
		n = int32(s[0]) + int32(s[1])<<8 + int32(s[2])<<16 + int32(s[3])<<24
	default:
		n = 0
		err = fmt.Errorf("Unhandled bytesPerSample! b:%d", wav.bytesPerSample)
	}

	return
}
384368
func (samplerOptions) InitialSampler(sampler Sampler) SamplerOption {
	return func(o *samplerOptions) {
		o.sampler = sampler
	}
}
524149
func ParseDenseARFFToInstances(filepath string) (ret *DenseInstances, err error) {
	defer func() {
		if r := recover(); r != nil {
			if _, ok := r.(runtime.Error); ok {
				panic(r)
			}
			err = r.(error)
		}
	}()

	// Find the number of rows in the file
	rows, err := ParseARFFGetRows(filepath)
	if err != nil {
		return nil, err
	}

	// Get the Attributes we want
	attrs := ParseARFFGetAttributes(filepath)

	// Allocate return value
	ret = NewDenseInstances()

	// Add all the Attributes
	for _, a := range attrs {
		ret.AddAttribute(a)
	}

	// Set the last Attribute as the class
	ret.AddClassAttribute(attrs[len(attrs)-1])
	ret.Extend(rows)

	f, err := os.Open(filepath)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	// Read the data
	// Seek past the header
	err = ParseDenseARFFBuildInstancesFromReader(f, attrs, ret)
	if err != nil {
		ret = nil
	}
	return ret, err
}
369330
func NewHeapWithRecorder(keyFn KeyFunc, lessFn LessFunc, metricRecorder metrics.MetricRecorder) *Heap {
	return &Heap{
		data: &heapData{
			items:    map[string]*heapItem{},
			queue:    []string{},
			keyFunc:  keyFn,
			lessFunc: lessFn,
		},
		metricRecorder: metricRecorder,
	}
}
1133780
func sampleFormat(p *profile.Profile, sampleIndex string, mean bool) (value, meanDiv sampleValueFunc, v *profile.ValueType, err error) {
	if len(p.SampleType) == 0 {
		return nil, nil, nil, fmt.Errorf("profile has no samples")
	}
	index, err := p.SampleIndexByName(sampleIndex)
	if err != nil {
		return nil, nil, nil, err
	}
	value = valueExtractor(index)
	if mean {
		meanDiv = valueExtractor(0)
	}
	v = p.SampleType[index]
	return
}
831947
func (p *Profile) FilterSamplesByName(focus, ignore, hide, show *regexp.Regexp) (fm, im, hm, hnm bool) {
	focusOrIgnore := make(map[uint64]bool)
	hidden := make(map[uint64]bool)
	for _, l := range p.Location {
		if ignore != nil && l.matchesName(ignore) {
			im = true
			focusOrIgnore[l.ID] = false
		} else if focus == nil || l.matchesName(focus) {
			fm = true
			focusOrIgnore[l.ID] = true
		}

		if hide != nil && l.matchesName(hide) {
			hm = true
			l.Line = l.unmatchedLines(hide)
			if len(l.Line) == 0 {
				hidden[l.ID] = true
			}
		}
		if show != nil {
			l.Line = l.matchedLines(show)
			if len(l.Line) == 0 {
				hidden[l.ID] = true
			} else {
				hnm = true
			}
		}
	}

	s := make([]*Sample, 0, len(p.Sample))
	for _, sample := range p.Sample {
		if focusedAndNotIgnored(sample.Location, focusOrIgnore) {
			if len(hidden) > 0 {
				var locs []*Location
				for _, loc := range sample.Location {
					if !hidden[loc.ID] {
						locs = append(locs, loc)
					}
				}
				if len(locs) == 0 {
					// Remove sample with no locations (by not adding it to s).
					continue
				}
				sample.Location = locs
			}
			s = append(s, sample)
		}
	}
	p.Sample = s

	return
}
1334719
func ParseCSVToTemplatedInstancesFromReader(r io.ReadSeeker, hasHeaders bool, template *DenseInstances) (instances *DenseInstances, err error) {
	// Read the number of rows in the file
	rowCount, err := ParseCSVGetRowsFromReader(r)
	if err != nil {
		return nil, err
	}

	if hasHeaders {
		rowCount--
	}

	// Read the row headers
	attrs := ParseCSVGetAttributesFromReader(r, hasHeaders)
	templateAttrs := template.AllAttributes()
	ParseMatchAttributes(attrs, templateAttrs)

	// Allocate the Instances to return
	instances = CopyDenseInstances(template, templateAttrs)
	instances.Extend(rowCount)

	err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances)
	if err != nil {
		return nil, err
	}

	for _, a := range template.AllClassAttributes() {
		err = instances.AddClassAttribute(a)
		if err != nil {
			return nil, err
		}
	}

	return instances, nil
}
644639
func SortSampleItems(sc *stmtctx.StatementContext, items []*SampleItem) error {
	sorter := sampleItemSorter{items: items, sc: sc}
	sort.Stable(&sorter)
	return sorter.err
}
1057081
func (p *PerKeyThroughput) GetSampleRate(key string) int {
	p.lock.Lock()
	defer p.lock.Unlock()
	p.currentCounts[key]++
	if rate, found := p.savedSampleRates[key]; found {
		return rate
	}
	return 1
}
795802
func SampleEvery(stats Stats, t time.Duration) {
	c := time.Tick(t)
	for _ = range c {
		r := newRuntimeSample()
		r.drain(stats)
	}
}
254426
func NewSampler(sampleRate float64) (*Sampler, error) {
	if sampleRate <= 0.0 || sampleRate >= 1.0 {
		return nil, fmt.Errorf("invalid sample rate %f", sampleRate)
	}
	return &Sampler{numTried: atomic.NewInt32(0), sampleEvery: int32(1.0 / sampleRate)}, nil
}
652494
func parseJavaHeader(pType string, b []byte, p *Profile) ([]byte, error) {
	nextNewLine := bytes.IndexByte(b, byte('\n'))
	for nextNewLine != -1 {
		line := string(bytes.TrimSpace(b[0:nextNewLine]))
		if line != "" {
			h := attributeRx.FindStringSubmatch(line)
			if h == nil {
				// Not a valid attribute, exit.
				return b, nil
			}

			attribute, value := strings.TrimSpace(h[1]), strings.TrimSpace(h[2])
			var err error
			switch pType + "/" + attribute {
			case "heap/format", "cpu/format", "contention/format":
				if value != "java" {
					return nil, errUnrecognized
				}
			case "heap/resolution":
				p.SampleType = []*ValueType{
					{Type: "inuse_objects", Unit: "count"},
					{Type: "inuse_space", Unit: value},
				}
			case "contention/resolution":
				p.SampleType = []*ValueType{
					{Type: "contentions", Unit: "count"},
					{Type: "delay", Unit: value},
				}
			case "contention/sampling period":
				p.PeriodType = &ValueType{
					Type: "contentions", Unit: "count",
				}
				if p.Period, err = strconv.ParseInt(value, 0, 64); err != nil {
					return nil, fmt.Errorf("failed to parse attribute %s: %v", line, err)
				}
			case "contention/ms since reset":
				millis, err := strconv.ParseInt(value, 0, 64)
				if err != nil {
					return nil, fmt.Errorf("failed to parse attribute %s: %v", line, err)
				}
				p.DurationNanos = millis * 1000 * 1000
			default:
				return nil, errUnrecognized
			}
		}
		// Grab next line.
		b = b[nextNewLine+1:]
		nextNewLine = bytes.IndexByte(b, byte('\n'))
	}
	return b, nil
}
504049
func (a *Array) GenerateExample(r *RandomGenerator, seen []string) interface{} {
	count := r.Int()%3 + 1
	res := make([]interface{}, count)
	for i := 0; i < count; i++ {
		res[i] = a.ElemType.Type.GenerateExample(r, seen)
	}
	return a.MakeSlice(res)
}
880093
func NewSampleJSONBuilder() *SampleJSONBuilder {
	jb := &SampleJSONBuilder{
		_properties:        map[string]*SamplePropertyInfo{},
		_jsonPropertyMap:   map[string]*SamplePropertyInfo{},
		_structPropertyMap: map[string]*SamplePropertyInfo{},
		A: &SamplePropertyInfo{
			fieldName: "A",
			jsonName:  "foo!",
			Encoder: func(src *Sample, dest *SampleJSON) error {
				if src == nil {
					return nil
				}
				dest.A = src.A
				return nil
			},
			Decoder: func(src *SampleJSON, dest *Sample) error {
				if src == nil {
					return nil
				}
				dest.A = src.A
				return nil
			},
		},
		B: &SamplePropertyInfo{
			fieldName: "B",
			jsonName:  "b",
			Encoder: func(src *Sample, dest *SampleJSON) error {
				if src == nil {
					return nil
				}
				dest.B = src.B
				return nil
			},
			Decoder: func(src *SampleJSON, dest *Sample) error {
				if src == nil {
					return nil
				}
				dest.B = src.B
				return nil
			},
		},
	}
	jb._structPropertyMap["A"] = jb.A
	jb._jsonPropertyMap["foo!"] = jb.A
	jb._structPropertyMap["B"] = jb.B
	jb._jsonPropertyMap["b"] = jb.B
	return jb
}