// MakeRuleSet converts slice of rules to the set of rules
198482
func MakeRuleSet(rules []Rule) RuleSet {
	set := make(RuleSet)
	for _, rule := range rules {
		for _, resource := range rule.Resources {
			rules, ok := set[resource]
			if !ok {
				set[resource] = []Rule{rule}
			} else {
				rules = append(rules, rule)
				set[resource] = rules
			}
		}
	}
	for resource := range set {
		rules := set[resource]
		// sort rules by most specific rule, the rule that has actions
		// is more specific than the one that has no actions
		sort.Slice(rules, func(i, j int) bool {
			return rules[i].IsMoreSpecificThan(rules[j])
		})
		set[resource] = rules
	}
	return set
}
979378
func MakeReadOnly(path string, filter func(string) bool) error {
	return recursiveChmod(path, filter, func(mode os.FileMode) os.FileMode {
		return mode & (^os.FileMode(0222))
	})
}
323277
func (b *RWSetBuilder) AddToWriteSet(ns string, key string, value []byte) {
	nsPubRwBuilder := b.getOrCreateNsPubRwBuilder(ns)
	nsPubRwBuilder.writeMap[key] = newKVWrite(key, value)
}
884316
func (r *router) makeRegion() *Region {
	m := &methods{}
	i := &interceptor{[]appliable{}}

	region := &Region{i, m.init()}
	r.regions.PushBack(region)

	return region
}
1026705
func MakeTable(headers []string) Table {
	t := MakeHeadlessTable(len(headers))
	for i := range t.columns {
		t.columns[i].title = headers[i]
		t.columns[i].width = len(headers[i])
	}
	return t
}
1166609
func NewSet(name string, loader TemplateLoader) *TemplateSet {
	return &TemplateSet{
		name:          name,
		loader:        loader,
		Globals:       make(Context),
		bannedTags:    make(map[string]bool),
		bannedFilters: make(map[string]bool),
		templateCache: make(map[string]*Template),
	}
}
1185005
func finalizeSet(set DefinitionSet) error {
	for _, def := range set {
		if finalize, ok := def.(Finalize); ok {
			finalize.Finalize()
		}
	}
	return nil
}
550451
func (l layouts) groupsSet() map[string]struct{} {
	m := make(map[string]struct{})
	for _, layout := range l {
		for grp := range layout.QuantitiesByGroup {
			m[grp] = struct{}{}
		}
	}
	return m
}
285292
func MakeList(len int) UnionSassValue {
	return C.sass_make_list(C.size_t(len), C.SASS_COMMA, false)
}
285767
func (dr *DescribeRequest) flatRules() []*DescribeRule {
	if dr.flatRuleCache == nil {
		dr.flatRuleCache = make([]*DescribeRule, 0)
		for _, rule := range dr.Rules {
			rule.appendToFlatCache(dr)
		}
	}
	return dr.flatRuleCache
}
1106149
func makeReverseBlockIterator(ns walletdb.ReadWriteBucket) blockIterator {
	seek := make([]byte, 4)
	byteOrder.PutUint32(seek, ^uint32(0))
	c := ns.NestedReadWriteBucket(bucketBlocks).ReadWriteCursor()
	return blockIterator{c: c, seek: seek}
}
389256
func makeRequest(ctx context.Context, r *httpRequest, method string, p payload) (*httpResponse, error) {
	r.addHeader("User-Agent", MailgunGoUserAgent)
	rsp, err := r.makeRequest(ctx, method, p)
	if (err == nil) && notGood(rsp.Code, expected) {
		return rsp, newError(r.URL, expected, rsp)
	}
	return rsp, err
}
143504
func (a *API) ShapeListErrors() []*Shape {
	list := []*Shape{}
	for _, n := range a.ShapeNames() {
		// Ignore error shapes in list
		if s := a.Shapes[n]; s.Exception {
			list = append(list, s)
		}
	}
	return list
}
1279482
func (b *Blob) StaticSetMergeSets() []blob.Ref {
	if b.Type() != "static-set" {
		return nil
	}

	s := make([]blob.Ref, 0, len(b.ss.MergeSets))
	for _, ref := range b.ss.MergeSets {
		if ref.Valid() {
			s = append(s, ref)
		}
	}
	return s
}
799790
func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyleSheet) *xlsxWorksheet {
	worksheet := newXlsxWorksheet()
	xSheet := xlsxSheetData{}
	maxRow := 0
	maxCell := 0

	if s.Selected {
		worksheet.SheetViews.SheetView[0].TabSelected = true
	}
	if s.SheetFormat.DefaultRowHeight != 0 {
		worksheet.SheetFormatPr.DefaultRowHeight = s.SheetFormat.DefaultRowHeight
	}
	worksheet.SheetFormatPr.DefaultColWidth = s.SheetFormat.DefaultColWidth

	colsXfIdList := make([]int, len(s.Cols))
	worksheet.Cols = &xlsxCols{Col: []xlsxCol{}}
	for c, col := range s.Cols {
		XfId := 0
		if col.Min == 0 {
			col.Min = 1
		}
		if col.Max == 0 {
			col.Max = 1
		}
		style := col.GetStyle()
		//col's style always not nil
		if style != nil {
			xNumFmt := styles.newNumFmt(col.numFmt)
			XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
		}
		colsXfIdList[c] = XfId

		var customWidth int
		if col.Width == 0 {
			col.Width = ColWidth
		} else {
			customWidth = 1
		}
		worksheet.Cols.Col = append(worksheet.Cols.Col,
			xlsxCol{Min: col.Min,
				Max:         col.Max,
				Hidden:      col.Hidden,
				Width:       col.Width,
				CustomWidth: customWidth,
				Collapsed:   col.Collapsed,
				Style:       XfId,
			})
	}

	for r, row := range s.Rows {
		if r > maxRow {
			maxRow = r
		}
		xRow := xlsxRow{}
		xRow.R = r + 1
		if row.isCustom {
			xRow.CustomHeight = true
			xRow.Ht = fmt.Sprintf("%g", row.Height)
		}
		for c, cell := range row.Cells {
			XfId := colsXfIdList[c]

			// generate NumFmtId and add new NumFmt
			xNumFmt := styles.newNumFmt(cell.NumFmt)

			style := cell.style
			if style != nil {
				XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
			} else if len(cell.NumFmt) > 0 && s.Cols[c].numFmt != cell.NumFmt {
				XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles)
			}

			if c > maxCell {
				maxCell = c
			}
			xC := xlsxC{}
			xC.R = fmt.Sprintf("%s%d", numericToLetters(c), r+1)
			switch cell.cellType {
			case CellTypeString:
				if len(cell.Value) > 0 {
					xC.V = strconv.Itoa(refTable.AddString(cell.Value))
				}
				xC.T = "s"
				xC.S = XfId
			case CellTypeBool:
				xC.V = cell.Value
				xC.T = "b"
				xC.S = XfId
			case CellTypeNumeric:
				xC.V = cell.Value
				xC.S = XfId
			case CellTypeDate:
				xC.V = cell.Value
				xC.S = XfId
			case CellTypeFormula:
				xC.V = cell.Value
				xC.F = &xlsxF{Content: cell.formula}
				xC.S = XfId
			case CellTypeError:
				xC.V = cell.Value
				xC.F = &xlsxF{Content: cell.formula}
				xC.T = "e"
				xC.S = XfId
			case CellTypeGeneral:
				xC.V = cell.Value
				xC.S = XfId
			}
			xRow.C = append(xRow.C, xC)

			if cell.HMerge > 0 || cell.VMerge > 0 {
				// r == rownum, c == colnum
				mc := xlsxMergeCell{}
				start := fmt.Sprintf("%s%d", numericToLetters(c), r+1)
				endcol := c + cell.HMerge
				endrow := r + cell.VMerge + 1
				end := fmt.Sprintf("%s%d", numericToLetters(endcol), endrow)
				mc.Ref = start + ":" + end
				if worksheet.MergeCells == nil {
					worksheet.MergeCells = &xlsxMergeCells{}
				}
				worksheet.MergeCells.Cells = append(worksheet.MergeCells.Cells, mc)
			}
		}
		xSheet.Row = append(xSheet.Row, xRow)
	}

	if worksheet.MergeCells != nil {
		worksheet.MergeCells.Count = len(worksheet.MergeCells.Cells)
	}

	worksheet.SheetData = xSheet
	dimension := xlsxDimension{}
	dimension.Ref = fmt.Sprintf("A1:%s%d",
		numericToLetters(maxCell), maxRow+1)
	if dimension.Ref == "A1:A1" {
		dimension.Ref = "A1"
	}
	worksheet.Dimension = dimension
	return worksheet
}
500591
func (runner *runner) CreateSet(set *IPSet, ignoreExistErr bool) error {
	// sets some IPSet fields if not present to their default values.
	set.setIPSetDefaults()

	// Validate ipset before creating
	valid := set.Validate()
	if !valid {
		return fmt.Errorf("error creating ipset since it's invalid")
	}
	return runner.createSet(set, ignoreExistErr)
}
139630
func (ac *APIController) RuleCreate(rule *contivModel.Rule) error {
	log.Infof("Received RuleCreate: %+v", rule)
	var epg *contivModel.EndpointGroup
	epg = nil

	// verify parameter values
	if rule.Direction == "in" {
		if rule.ToNetwork != "" || rule.ToEndpointGroup != "" {
			return errors.New("can not specify 'to' parameters in incoming rule")
		}
		if rule.FromNetwork != "" && rule.FromIpAddress != "" {
			return errors.New("can not specify both from network and from ip address")
		}

		if rule.FromNetwork != "" && rule.FromEndpointGroup != "" {
			return errors.New("can not specify both from network and from EndpointGroup")
		}
	} else if rule.Direction == "out" {
		if rule.FromNetwork != "" || rule.FromEndpointGroup != "" || rule.FromIpAddress != "" {
			return errors.New("can not specify 'from' parameters in outgoing rule")
		}
		if rule.ToNetwork != "" && rule.ToIpAddress != "" {
			return errors.New("can not specify both to-network and to-ip address")
		}
		if rule.ToNetwork != "" && rule.ToEndpointGroup != "" {
			return errors.New("can not specify both to-network and to-EndpointGroup")
		}
	} else {
		return errors.New("invalid direction for the rule")
	}

	// Make sure endpoint groups and networks referred exists.
	if rule.FromEndpointGroup != "" {
		epgKey := rule.TenantName + ":" + rule.FromEndpointGroup
		// find the endpoint group
		epg = contivModel.FindEndpointGroup(epgKey)
		if epg == nil {
			log.Errorf("Error finding endpoint group %s", epgKey)
			return errors.New("endpoint group not found")
		}
	} else if rule.ToEndpointGroup != "" {
		epgKey := rule.TenantName + ":" + rule.ToEndpointGroup

		// find the endpoint group
		epg = contivModel.FindEndpointGroup(epgKey)
		if epg == nil {
			log.Errorf("Error finding endpoint group %s", epgKey)
			return errors.New("endpoint group not found")
		}
	} else if rule.FromNetwork != "" {
		netKey := rule.TenantName + ":" + rule.FromNetwork

		net := contivModel.FindNetwork(netKey)
		if net == nil {
			log.Errorf("Network %s not found", netKey)
			return errors.New("from Network not found")
		}
	} else if rule.ToNetwork != "" {
		netKey := rule.TenantName + ":" + rule.ToNetwork

		net := contivModel.FindNetwork(netKey)
		if net == nil {
			log.Errorf("Network %s not found", netKey)
			return errors.New("to Network not found")
		}
	}

	policyKey := GetpolicyKey(rule.TenantName, rule.PolicyName)

	// find the policy
	policy := contivModel.FindPolicy(policyKey)
	if policy == nil {
		log.Errorf("Error finding policy %s", policyKey)
		return core.Errorf("Policy not found")
	}

	if rule.Direction == "in" && rule.ToIpAddress != "" {
		// rules from k8s network policy
		// verify 'toIpAddress' is part of epg and subnet
		if len(policy.LinkSets.EndpointGroups) != 1 {
			errMsg := fmt.Errorf("failed to configure %s, %d endpoint groups linked to policy %s ",
				rule.ToIpAddress,
				len(policy.LinkSets.EndpointGroups),
				rule.PolicyName)
			log.Error(errMsg)
			return errMsg
		}
		epgKey := ""
		for key := range policy.LinkSets.EndpointGroups {
			epgKey = strings.Replace(key, rule.TenantName+":", "", 1) + ":" + rule.TenantName
		}

		stateDriver, err := utils.GetStateDriver()
		if err != nil {
			log.Errorf("failed to configure %s, %s", rule.ToIpAddress, err)
			return fmt.Errorf("failed to configure %s, unable to connect to key-value store",
				rule.ToIpAddress)
		}
		readEp := &mastercfg.CfgEndpointState{}
		readEp.StateDriver = stateDriver
		epCfgs, err := readEp.ReadAll()
		if err != nil {
			log.Errorf("failed to configure %s, %s", rule.ToIpAddress, err)
			return fmt.Errorf("failed to configure %s, unable to read endpoint state", rule.ToIpAddress)
		}

		// TODO: cache ip <--> epg for performance
		if func(epgName string) bool {
			for _, epCfg := range epCfgs {
				if ep, ok := epCfg.(*mastercfg.CfgEndpointState); ok {
					if ep.IPAddress == rule.ToIpAddress && ep.EndpointGroupKey == epgName {
						return true
					}
				}
			}
			return false
		}(epgKey) != true {
			errMsg := fmt.Errorf("failed to configure %s, ip address is not in epg %s",
				rule.ToIpAddress,
				epgKey)
			log.Error(errMsg)
			return errMsg
		}
	}

	// Trigger policyDB Update
	err := master.PolicyAddRule(policy, rule)
	if err != nil {
		log.Errorf("Error adding rule %s to policy %s. Err: %v", rule.Key, policy.Key, err)
		return err
	}

	// link the rule to policy
	modeldb.AddLinkSet(&rule.LinkSets.Policies, policy)
	modeldb.AddLinkSet(&policy.LinkSets.Rules, rule)
	err = policy.Write()
	if err != nil {
		return err
	}

	// link the rule to epg and vice versa
	if epg != nil {
		modeldb.AddLinkSet(&epg.LinkSets.MatchRules, rule)
		modeldb.AddLink(&rule.Links.MatchEndpointGroup, epg)
		err = epg.Write()
		if err != nil {
			return err
		}
	}

	// Update any affected app profiles
	pMap := getAffectedProfs(policy, epg)
	syncAppProfile(pMap)

	return nil
}