// optimize converts the container to the type which will take up the least
// amount of space.
770451
func (c *Container) optimize() {
	if c.n == 0 {
		statsHit("optimize/empty")
		return
	}
	runs := c.countRuns()

	var newType byte
	if runs <= runMaxSize && runs <= c.n/2 {
		newType = containerRun
	} else if c.n < ArrayMaxSize {
		newType = containerArray
	} else {
		newType = containerBitmap
	}

	// Then convert accordingly.
	if c.isArray() {
		if newType == containerBitmap {
			statsHit("optimize/arrayToBitmap")
			c.arrayToBitmap()
		} else if newType == containerRun {
			statsHit("optimize/arrayToRun")
			c.arrayToRun(runs)
		} else {
			statsHit("optimize/arrayUnchanged")
		}
	} else if c.isBitmap() {
		if newType == containerArray {
			statsHit("optimize/bitmapToArray")
			c.bitmapToArray()
		} else if newType == containerRun {
			statsHit("optimize/bitmapToRun")
			c.bitmapToRun(runs)
		} else {
			statsHit("optimize/bitmapUnchanged")
		}
	} else if c.isRun() {
		if newType == containerBitmap {
			statsHit("optimize/runToBitmap")
			c.runToBitmap()
		} else if newType == containerArray {
			statsHit("optimize/runToArray")
			c.runToArray()
		} else {
			statsHit("optimize/runUnchanged")
		}
	}
}
198213
func (rc *RediffContext) OptimizePatch(patchReader savior.SeekSource, patchWriter io.Writer) error {
	var err error

	if rc.SourcePool == nil {
		return errors.WithStack(fmt.Errorf("SourcePool cannot be nil"))
	}

	if rc.TargetPool == nil {
		return errors.WithStack(fmt.Errorf("TargetPool cannot be nil"))
	}

	if rc.DiffMappings == nil {
		return errors.WithStack(fmt.Errorf("AnalyzePatch must be called before OptimizePatch"))
	}

	rctx := wire.NewReadContext(patchReader)
	wctx := wire.NewWriteContext(patchWriter)

	err = wctx.WriteMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	err = rctx.ExpectMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	ph := &PatchHeader{}
	err = rctx.ReadMessage(ph)
	if err != nil {
		return errors.WithStack(err)
	}

	compression := rc.Compression
	if compression == nil {
		compression = defaultRediffCompressionSettings()
	}

	wph := &PatchHeader{
		Compression: compression,
	}
	err = wctx.WriteMessage(wph)
	if err != nil {
		return errors.WithStack(err)
	}

	rctx, err = DecompressWire(rctx, ph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	wctx, err = CompressWire(wctx, wph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	targetContainer := &tlc.Container{}
	err = rctx.ReadMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wctx.WriteMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	sourceContainer := &tlc.Container{}
	err = rctx.ReadMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wctx.WriteMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	sh := &SyncHeader{}
	bh := &BsdiffHeader{}
	rop := &SyncOp{}

	bdc := &bsdiff.DiffContext{
		SuffixSortConcurrency: rc.SuffixSortConcurrency,
		Partitions:            rc.Partitions,
		Stats:                 rc.BsdiffStats,
		MeasureMem:            rc.MeasureMem,
	}

	if rc.Timeline != nil {
		rc.Timeline.Groups = append(rc.Timeline.Groups, TimelineGroup{
			ID:      0,
			Content: "Worker",
		})
	}

	initialStart := time.Now()
	bconsumer := &state.Consumer{}

	var biggestSourceFile int64
	var totalRediffSize int64

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		if _, ok := rc.DiffMappings[int64(sourceFileIndex)]; ok {
			if sourceFile.Size > biggestSourceFile {
				biggestSourceFile = sourceFile.Size
			}

			totalRediffSize += sourceFile.Size
		}
	}

	var doneSize int64

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		sh.Reset()
		err = rctx.ReadMessage(sh)
		if err != nil {
			return errors.WithStack(err)
		}

		if sh.FileIndex != int64(sourceFileIndex) {
			return errors.WithStack(fmt.Errorf("Malformed patch, expected index %d, got %d", sourceFileIndex, sh.FileIndex))
		}

		diffMapping := rc.DiffMappings[int64(sourceFileIndex)]

		if diffMapping == nil {
			// if no mapping, just copy ops straight up
			err = wctx.WriteMessage(sh)
			if err != nil {
				return errors.WithStack(err)
			}

			for {
				rop.Reset()
				err = rctx.ReadMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}

				if rop.Type == SyncOp_HEY_YOU_DID_IT {
					break
				}

				err = wctx.WriteMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}
			}
		} else {
			// signal bsdiff start to patcher
			sh.Reset()
			sh.FileIndex = int64(sourceFileIndex)
			sh.Type = SyncHeader_BSDIFF
			err = wctx.WriteMessage(sh)
			if err != nil {
				return errors.WithStack(err)
			}

			bh.Reset()
			bh.TargetIndex = diffMapping.TargetIndex
			err = wctx.WriteMessage(bh)
			if err != nil {
				return errors.WithStack(err)
			}

			// throw away old ops
			for {
				err = rctx.ReadMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}

				if rop.Type == SyncOp_HEY_YOU_DID_IT {
					break
				}
			}

			// then bsdiff
			sourceFileReader, err := rc.SourcePool.GetReadSeeker(int64(sourceFileIndex))
			if err != nil {
				return errors.WithStack(err)
			}

			targetFileReader, err := rc.TargetPool.GetReadSeeker(diffMapping.TargetIndex)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf(">%s", sourceFile.Path))

			_, err = sourceFileReader.Seek(0, io.SeekStart)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf("<%s", sourceFile.Path))

			_, err = targetFileReader.Seek(0, io.SeekStart)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf("*%s", sourceFile.Path))

			startTime := time.Now()

			err = bdc.Do(targetFileReader, sourceFileReader, wctx.WriteMessage, bconsumer)

			endTime := time.Now()

			if rc.Timeline != nil {
				heat := int(float64(sourceFile.Size) / float64(biggestSourceFile) * 240.0)
				rc.Timeline.Items = append(rc.Timeline.Items, TimelineItem{
					Content: filepath.Base(sourceFile.Path),
					Style:   fmt.Sprintf("background-color: hsl(%d, 100%%, 50%%)", heat),
					Title:   fmt.Sprintf("%s %s", progress.FormatBytes(sourceFile.Size), sourceFile.Path),
					Start:   startTime.Sub(initialStart).Seconds(),
					End:     endTime.Sub(initialStart).Seconds(),
					Group:   0,
				})
			}

			doneSize += sourceFile.Size
		}

		// and don't forget to indicate success
		rop.Reset()
		rop.Type = SyncOp_HEY_YOU_DID_IT

		err = wctx.WriteMessage(rop)
		if err != nil {
			return errors.WithStack(err)
		}

		rc.Consumer.Progress(float64(doneSize) / float64(totalRediffSize))
	}

	err = wctx.Close()
	if err != nil {
		return errors.WithStack(err)
	}

	return nil
}
835343
func Resize(buf []byte, o Options) ([]byte, error) {
	// Required in order to prevent premature garbage collection. See:
	// https://github.com/h2non/bimg/pull/162
	defer runtime.KeepAlive(buf)
	return resizer(buf, o)
}
1022090
func (s *mustRunAs) Generate(pod *api.Pod, container *api.Container) (*int64, error) {
	return &s.opts.Ranges[0].Min, nil
}
137469
func (iter *iterator) optimize() (Iterator, error) {
	if len(iter.cursors) != 1 {
		return iter, nil
	}

	cur := iter.cursors[0]

	if cur.ssIndex == -1 && cur.sc == nil {
		// Optimization to return lowerLevelIter directly.
		return iter.lowerLevelIter, nil
	}

	seg, ok := iter.ss.a[cur.ssIndex].(*segment)
	if !ok || seg == nil {
		return iter, nil
	}

	return &iteratorSingle{
		s:       seg,
		sc:      cur.sc,
		op:      cur.op,
		k:       cur.k,
		v:       cur.v,
		closer:  iter.closer,
		options: iter.ss.options,

		iteratorOptions: iter.iteratorOptions,
	}, nil
}
1104290
func (daemon *Daemon) ContainerResize(name string, height, width int) error {
	container, err := daemon.GetContainer(name)
	if err != nil {
		return err
	}

	if !container.IsRunning() {
		return errNotRunning(container.ID)
	}

	if err = daemon.containerd.ResizeTerminal(context.Background(), container.ID, libcontainerdtypes.InitProcessName, width, height); err == nil {
		attributes := map[string]string{
			"height": fmt.Sprintf("%d", height),
			"width":  fmt.Sprintf("%d", width),
		}
		daemon.LogContainerEventWithAttributes(container, "resize", attributes)
	}
	return err
}
1117976
func (s *DisjunctionHeapSearcher) Optimize(kind string, octx index.OptimizableContext) (
	index.OptimizableContext, error) {
	if len(s.searchers) == 1 {
		o, ok := s.searchers[0].(index.Optimizable)
		if ok {
			return o.Optimize(kind, octx)
		}
	}

	return octx, nil
}
722390
func (j *AuroraJob) Container(container Container) Job {
	j.jobConfig.TaskConfig.Container = container.Build()

	return j
}
1269192
func (c *Conn) OptimizeIndices(args map[string]interface{}, indices ...string) (ExtendedStatus, error) {
	var retval ExtendedStatus
	var optimizeUrl string = "/_optimize"
	if len(indices) > 0 {
		optimizeUrl = fmt.Sprintf("/%s%s", strings.Join(indices, ","), optimizeUrl)
	}

	body, err := c.DoCommand("POST", optimizeUrl, args, nil)
	if err != nil {
		return retval, err
	}
	if err == nil {
		// marshall into json
		jsonErr := json.Unmarshal(body, &retval)
		if jsonErr != nil {
			return retval, jsonErr
		}
	}
	return retval, err
}
1074896
func (rc *runContainer16) toEfficientContainer() container {

	// runContainer16SerializedSizeInBytes(numRuns)
	sizeAsRunContainer := rc.getSizeInBytes()
	sizeAsBitmapContainer := bitmapContainerSizeInBytes()
	card := int(rc.cardinality())
	sizeAsArrayContainer := arrayContainerSizeInBytes(card)
	if sizeAsRunContainer <= minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) {
		return rc
	}
	if card <= arrayDefaultMaxSize {
		return rc.toArrayContainer()
	}
	bc := newBitmapContainerFromRun(rc)
	return bc
}
72440
func (s *PutTemplateService) OpType(opType string) *PutTemplateService {
	s.opType = opType
	return s
}
430294
func (image *Image) Resize(param *ResizeParam) *Image {
	return image.setActionParam(ResizeOperation, param)
}
1127654
func (p *Init) Resize(ws console.WinSize) error {
	p.mu.Lock()
	defer p.mu.Unlock()

	if p.console == nil {
		return nil
	}
	return p.console.Resize(ws)
}
1007205
func (l *LevelDb) Opts() *opt.Options {
	return &opt.Options{
		OpenFilesCacheCapacity: l.G().Env.GetLevelDBNumFiles(),
		Filter:                 filter.NewBloomFilter(10),
		CompactionTableSize:    10 * opt.MiB,
	}
}
760908
func (ls *LState) OptInt(n int, d int) int {
	v := ls.Get(n)
	if v == LNil {
		return d
	}
	if intv, ok := v.(LNumber); ok {
		return int(intv)
	}
	ls.TypeError(n, LTNumber)
	return 0
}
104672
func (r *grammarOptimizer) optimize(expr0 Expression) Visitor {
	switch expr := expr0.(type) {
	case *ActionExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	case *AndExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	case *ChoiceExpr:
		expr.Alternatives = r.optimizeRules(expr.Alternatives)

		// Optimize choice nested in choice
		for i := 0; i < len(expr.Alternatives); i++ {
			if choice, ok := expr.Alternatives[i].(*ChoiceExpr); ok {
				r.optimized = true
				if i+1 < len(expr.Alternatives) {
					expr.Alternatives = append(expr.Alternatives[:i], append(choice.Alternatives, expr.Alternatives[i+1:]...)...)
				} else {
					expr.Alternatives = append(expr.Alternatives[:i], choice.Alternatives...)
				}
			}

			// Combine sequence of single char LitMatcher to CharClassMatcher
			if i > 0 {
				l0, lok0 := expr.Alternatives[i-1].(*LitMatcher)
				l1, lok1 := expr.Alternatives[i].(*LitMatcher)
				c0, cok0 := expr.Alternatives[i-1].(*CharClassMatcher)
				c1, cok1 := expr.Alternatives[i].(*CharClassMatcher)

				combined := false

				switch {
				// Combine two LitMatcher to CharClassMatcher
				// "a" / "b" => [ab]
				case lok0 && lok1 && len([]rune(l0.Val)) == 1 && len([]rune(l1.Val)) == 1 && l0.IgnoreCase == l1.IgnoreCase:
					combined = true
					cm := CharClassMatcher{
						Chars:      append([]rune(l0.Val), []rune(l1.Val)...),
						IgnoreCase: l0.IgnoreCase,
						posValue:   l0.posValue,
					}
					expr.Alternatives[i-1] = &cm

				// Combine LitMatcher with CharClassMatcher
				// "a" / [bc] => [abc]
				case lok0 && cok1 && len([]rune(l0.Val)) == 1 && l0.IgnoreCase == c1.IgnoreCase && !c1.Inverted:
					combined = true
					c1.Chars = append(c1.Chars, []rune(l0.Val)...)
					expr.Alternatives[i-1] = c1

				// Combine CharClassMatcher with LitMatcher
				// [ab] / "c" => [abc]
				case cok0 && lok1 && len([]rune(l1.Val)) == 1 && c0.IgnoreCase == l1.IgnoreCase && !c0.Inverted:
					combined = true
					c0.Chars = append(c0.Chars, []rune(l1.Val)...)

				// Combine CharClassMatcher with CharClassMatcher
				// [ab] / [cd] => [abcd]
				case cok0 && cok1 && c0.IgnoreCase == c1.IgnoreCase && c0.Inverted == c1.Inverted:
					combined = true
					c0.Chars = append(c0.Chars, c1.Chars...)
					c0.Ranges = append(c0.Ranges, c1.Ranges...)
					c0.UnicodeClasses = append(c0.UnicodeClasses, c1.UnicodeClasses...)
				}

				// If one of the optimizations was applied, remove the second element from Alternatives
				if combined {
					r.optimized = true
					if i+1 < len(expr.Alternatives) {
						expr.Alternatives = append(expr.Alternatives[:i], expr.Alternatives[i+1:]...)
					} else {
						expr.Alternatives = expr.Alternatives[:i]
					}
				}
			}
		}

	case *Grammar:
		// Reset optimized at the start of each Walk.
		r.optimized = false
		for i := 0; i < len(expr.Rules); i++ {
			rule := expr.Rules[i]
			// Remove Rule, if it is no longer used by any other Rule and it is not the first Rule.
			_, used := r.ruleUsedByRules[rule.Name.Val]
			_, protected := r.protectedRules[rule.Name.Val]
			if !used && !protected {
				expr.Rules = append(expr.Rules[:i], expr.Rules[i+1:]...)
				r.optimized = true
				continue
			}
		}
	case *LabeledExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	case *NotExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	case *OneOrMoreExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	case *Rule:
		r.rule = expr.Name.Val
	case *SeqExpr:
		expr.Exprs = r.optimizeRules(expr.Exprs)

		for i := 0; i < len(expr.Exprs); i++ {
			// Optimize nested sequences
			if seq, ok := expr.Exprs[i].(*SeqExpr); ok {
				r.optimized = true
				if i+1 < len(expr.Exprs) {
					expr.Exprs = append(expr.Exprs[:i], append(seq.Exprs, expr.Exprs[i+1:]...)...)
				} else {
					expr.Exprs = append(expr.Exprs[:i], seq.Exprs...)
				}
			}

			// Combine sequence of LitMatcher
			if i > 0 {
				l0, ok0 := expr.Exprs[i-1].(*LitMatcher)
				l1, ok1 := expr.Exprs[i].(*LitMatcher)
				if ok0 && ok1 && l0.IgnoreCase == l1.IgnoreCase {
					r.optimized = true
					l0.Val += l1.Val
					expr.Exprs[i-1] = l0
					if i+1 < len(expr.Exprs) {
						expr.Exprs = append(expr.Exprs[:i], expr.Exprs[i+1:]...)
					} else {
						expr.Exprs = expr.Exprs[:i]
					}
				}
			}
		}

	case *ZeroOrMoreExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	case *ZeroOrOneExpr:
		expr.Expr = r.optimizeRule(expr.Expr)
	}
	return r
}
326705
func Optimize(s Shape, qs graph.QuadStore) (Shape, bool) {
	if s == nil {
		return nil, false
	}
	qs = graph.Unwrap(qs)
	var opt bool
	if qs != nil {
		// resolve all lookups earlier
		s, opt = s.Optimize(resolveValues{qs: qs})
	}
	if s == nil {
		return Null{}, true
	}
	// generic optimizations
	var opt1 bool
	s, opt1 = s.Optimize(nil)
	if s == nil {
		return Null{}, true
	}
	opt = opt || opt1
	// apply quadstore-specific optimizations
	if so, ok := qs.(Optimizer); ok && s != nil {
		var opt2 bool
		s, opt2 = s.Optimize(so)
		opt = opt || opt2
	}
	if s == nil {
		return Null{}, true
	}
	return s, opt
}