/* SQB
------------------------
(c) 2017-present Panates
SQB may be freely distributed under the MIT license.
For details and documentation:
https://panates.github.io/sqb/
190048
function lowerCaseObjectKeys(obj) {
  for (const key of Object.getOwnPropertyNames(obj)) {
    const name = key.toLowerCase();
    if (name !== key) {
      obj[name] = obj[key];
      delete obj[key];
    }
  }
  return obj;
}
619250
func MarkSquares(c color.Color, sqs ...chess.Square) func(*encoder) {
	return func(e *encoder) {
		for _, sq := range sqs {
			e.marks[sq] = c
		}
	}
}
199506
func (swaggerTag TagSwagger) Private() bool {
	text := reflect.StructTag(swaggerTag).Get("swagger")
	name := strings.Split(text, ",")[0]

	return name == "-"
}
646269
func (sp *SplitParams) areSplitColumnsPrimaryKey() bool {
	pkCols := getPrimaryKeyColumns(sp.splitTableSchema)
	if len(sp.splitColumns) != len(pkCols) {
		return false
	}
	// Compare the names of sp.splitColumns to the names of pkCols.
	for i := 0; i < len(sp.splitColumns); i++ {
		if !sp.splitColumns[i].Name.Equal(pkCols[i].Name) {
			return false
		}
	}
	return true
}
1222405
func (v *Validator) preLoadCommittedVersionOfRSet(block *internal.Block) error {

	// Collect both public and hashed keys in read sets of all transactions in a given block
	var pubKeys []*statedb.CompositeKey
	var hashedKeys []*privacyenabledstate.HashedCompositeKey

	// pubKeysMap and hashedKeysMap are used to avoid duplicate entries in the
	// pubKeys and hashedKeys. Though map alone can be used to collect keys in
	// read sets and pass as an argument in LoadCommittedVersionOfPubAndHashedKeys(),
	// array is used for better code readability. On the negative side, this approach
	// might use some extra memory.
	pubKeysMap := make(map[statedb.CompositeKey]interface{})
	hashedKeysMap := make(map[privacyenabledstate.HashedCompositeKey]interface{})

	for _, tx := range block.Txs {
		for _, nsRWSet := range tx.RWSet.NsRwSets {
			for _, kvRead := range nsRWSet.KvRwSet.Reads {
				compositeKey := statedb.CompositeKey{
					Namespace: nsRWSet.NameSpace,
					Key:       kvRead.Key,
				}
				if _, ok := pubKeysMap[compositeKey]; !ok {
					pubKeysMap[compositeKey] = nil
					pubKeys = append(pubKeys, &compositeKey)
				}

			}
			for _, colHashedRwSet := range nsRWSet.CollHashedRwSets {
				for _, kvHashedRead := range colHashedRwSet.HashedRwSet.HashedReads {
					hashedCompositeKey := privacyenabledstate.HashedCompositeKey{
						Namespace:      nsRWSet.NameSpace,
						CollectionName: colHashedRwSet.CollectionName,
						KeyHash:        string(kvHashedRead.KeyHash),
					}
					if _, ok := hashedKeysMap[hashedCompositeKey]; !ok {
						hashedKeysMap[hashedCompositeKey] = nil
						hashedKeys = append(hashedKeys, &hashedCompositeKey)
					}
				}
			}
		}
	}

	// Load committed version of all keys into a cache
	if len(pubKeys) > 0 || len(hashedKeys) > 0 {
		err := v.db.LoadCommittedVersionsOfPubAndHashedKeys(pubKeys, hashedKeys)
		if err != nil {
			return err
		}
	}

	return nil
}
1218105
func (t *TagReplace) AddSpans(ctx context.Context, spans []*trace.Span) error {
	for _, s := range spans {
		if s.Name != nil {
			for _, r := range t.rules {
				nms := r.SubexpNames()
				oldName := *s.Name
				if ms := r.FindStringSubmatch(oldName); ms != nil {
					ims := r.FindStringSubmatchIndex(oldName)

					var newName []string
					var index = 0
					if s.Tags == nil {
						s.Tags = map[string]string{}
					}

					for i := 1; i < len(ms); i++ {
						s.Tags[nms[i]] = ms[i]
						newName = append(newName, oldName[index:ims[i*2]], "{", nms[i], "}")
						index = ims[i*2+1]
					}
					if index < len(oldName) {
						newName = append(newName, oldName[index:])
					}
					s.Name = pointer.String(strings.Join(newName, ""))
					if t.exitEarly {
						break
					}
				}
			}
		}
	}
	return t.next.AddSpans(ctx, spans)
}
110893
func NewTablet(uid uint32, cell, host string) *topodatapb.Tablet {
	return &topodatapb.Tablet{
		Alias: &topodatapb.TabletAlias{
			Cell: cell,
			Uid:  uid,
		},
		Hostname: host,
		PortMap:  make(map[string]int32),
	}
}
968686
func allowedVersions(available *response.TerraformProviderVersions, required Constraints) []*response.TerraformProviderVersion {
	var allowed []*response.TerraformProviderVersion

	for _, v := range available.Versions {
		version, err := VersionStr(v.Version).Parse()
		if err != nil {
			log.Printf("[WARN] invalid version found for %q: %s", available.ID, err)
			continue
		}
		if required.Allows(version) {
			allowed = append(allowed, v)
		}
	}
	return allowed
}
566272
func (bs *BuildSummary) GitilesCommit() *buildbucketpb.GitilesCommit {
	for _, bset := range bs.BuildSet {
		if gc, ok := protoutil.ParseBuildSet(bset).(*buildbucketpb.GitilesCommit); ok {
			return gc
		}
	}
	return nil
}
1342295
func simpleMakeTable(poly uint32) *Table {
	t := new(Table)
	simplePopulateTable(poly, t)
	return t
}
977231
func GetGreasedVersions(supported []VersionNumber) []VersionNumber {
	b := make([]byte, 1)
	_, _ = rand.Read(b) // ignore the error here. Failure to read random data doesn't break anything
	randPos := int(b[0]) % (len(supported) + 1)
	greased := make([]VersionNumber, len(supported)+1)
	copy(greased, supported[:randPos])
	greased[randPos] = generateReservedVersion()
	copy(greased[randPos+1:], supported[randPos:])
	return greased
}
1272348
func CrossPlatformUbiquity(chain []*x509.Certificate) int {
	// There is no root store info, every chain is equal weighted as 0.
	if len(Platforms) == 0 {
		return 0
	}

	totalWeight := 0
	// A chain is viable with the platform if
	//	1. the root is in the platform's root store
	//	2. the chain satisfy the minimal constraints on hash function and key algorithm.
	root := chain[len(chain)-1]
	for _, platform := range Platforms {
		if platform.Trust(root) {
			switch {
			case platform.HashUbiquity <= ChainHashUbiquity(chain) && platform.KeyAlgoUbiquity <= ChainKeyAlgoUbiquity(chain):
				totalWeight += platform.Weight
			}
		}
	}
	return totalWeight
}
25449
func SqTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) {
	var err error

	// get the tables
	rows, err := models.SqTables(db, relkind)
	if err != nil {
		return nil, err
	}

	// get the SQL for the Autoincrement detection
	autoIncrements, err := models.SqAutoIncrements(db)
	if err != nil {
		// Set it to an empty set on error.
		autoIncrements = []*models.SqAutoIncrement{}
	}

	// Add information about manual FK.
	var tables []*models.Table
	for _, row := range rows {
		manualPk := true
		// Look for a match in the table name where it contains the autoincrement
		// keyword for the given table in the SQL.
		for _, autoInc := range autoIncrements {
			lSQL := strings.ToLower(autoInc.SQL)
			if autoInc.TableName == row.TableName && strings.Contains(lSQL, "autoincrement") {
				manualPk = false
			} else {
				cols, err := SqTableColumns(db, schema, row.TableName)
				if err != nil {
					return nil, err
				}
				for _, col := range cols {
					if col.IsPrimaryKey == true {
						dt := strings.ToUpper(col.DataType)
						if dt == "INTEGER" {
							manualPk = false
						}
						break
					}
				}
			}
		}
		tables = append(tables, &models.Table{
			TableName: row.TableName,
			Type:      row.Type,
			ManualPk:  manualPk,
		})
	}

	return tables, nil
}
100442
func (actor Actor) getAndSetSharedInformation(summary *ServiceInstanceSummary, spaceGUID string) (Warnings, error) {
	var (
		warnings Warnings
		err      error
	)

	// Part of determining if a service instance is shareable, we need to find
	// out if the service_instance_sharing feature flag is enabled
	featureFlags, featureFlagsWarnings, featureFlagsErr := actor.CloudControllerClient.GetConfigFeatureFlags()
	allWarnings := Warnings(featureFlagsWarnings)
	if featureFlagsErr != nil {
		return allWarnings, featureFlagsErr
	}

	for _, flag := range featureFlags {
		if flag.Name == string(constant.FeatureFlagServiceInstanceSharing) {
			summary.ServiceInstanceSharingFeatureFlag = flag.Enabled
		}
	}

	// Service instance is shared from if:
	// 1. the source space of the service instance is empty (API returns json null)
	// 2. the targeted space is not the same as the source space of the service instance AND
	//    we call the shared_from url and it returns a non-empty resource
	if summary.ServiceInstance.SpaceGUID == "" || summary.ServiceInstance.SpaceGUID != spaceGUID {
		summary.ServiceInstanceSharedFrom, warnings, err = actor.GetServiceInstanceSharedFromByServiceInstance(summary.ServiceInstance.GUID)
		allWarnings = append(allWarnings, warnings...)
		if err != nil {
			// if the API version does not support service instance sharing, ignore the 404
			if _, ok := err.(ccerror.ResourceNotFoundError); !ok {
				return allWarnings, err
			}
		}

		if summary.ServiceInstanceSharedFrom.SpaceGUID != "" {
			summary.ServiceInstanceShareType = ServiceInstanceIsSharedFrom
		} else {
			summary.ServiceInstanceShareType = ServiceInstanceIsNotShared
		}

		return allWarnings, nil
	}

	// Service instance is shared to if:
	// the targeted space is the same as the source space of the service instance AND
	// we call the shared_to url and get a non-empty list
	summary.ServiceInstanceSharedTos, warnings, err = actor.GetServiceInstanceSharedTosByServiceInstance(summary.ServiceInstance.GUID)
	allWarnings = append(allWarnings, warnings...)
	if err != nil {
		// if the API version does not support service instance sharing, ignore the 404
		if _, ok := err.(ccerror.ResourceNotFoundError); !ok {
			return allWarnings, err
		}
	}

	if len(summary.ServiceInstanceSharedTos) > 0 {
		summary.ServiceInstanceShareType = ServiceInstanceIsSharedTo
	} else {
		summary.ServiceInstanceShareType = ServiceInstanceIsNotShared
	}

	return allWarnings, nil
}
398596
func looksLikeDemangledCPlusPlus(demangled string) bool {
	if strings.Contains(demangled, ".<") { // Skip java names of the form "class.<init>"
		return false
	}
	return strings.ContainsAny(demangled, "<>[]") || strings.Contains(demangled, "::")
}
1273759
func main() {
	if len(os.Args) <= 1 {
		log.Fatal("Supply a version")
	}
	version := os.Args[1]
	if !strings.HasPrefix(version, "v") {
		version = "v" + version
	}
	oAPIDefs := wfv1.GetOpenAPIDefinitions(func(name string) spec.Ref {
		return spec.MustCreateRef("#/definitions/" + common.EscapeJsonPointer(swaggify(name)))
	})
	defs := spec.Definitions{}
	for defName, val := range oAPIDefs {
		defs[swaggify(defName)] = val.Schema
	}
	swagger := spec.Swagger{
		SwaggerProps: spec.SwaggerProps{
			Swagger:     "2.0",
			Definitions: defs,
			Paths:       &spec.Paths{Paths: map[string]spec.PathItem{}},
			Info: &spec.Info{
				InfoProps: spec.InfoProps{
					Title:   "Argo",
					Version: version,
				},
			},
		},
	}
	jsonBytes, err := json.MarshalIndent(swagger, "", "  ")
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(string(jsonBytes))
}
1218809
func (priv *PrivateKey) ToBytes() (b []byte) {
	d := priv.D.Bytes()

	/* Pad D to 32 bytes */
	padded_d := append(bytes.Repeat([]byte{0x00}, 32-len(d)), d...)

	return padded_d
}