// PopulateFromModeledType creates fields for the model
// based on the goa UserTypeDefinition it models, which is
// set using BuildsFrom().
// This happens before fields are processed, so it's
// ok to just assign without testing.
195805
func (f *RelationalModelDefinition) PopulateFromModeledType() {
	if f.BuiltFrom == nil {
		return
	}
	for _, utd := range f.BuiltFrom {
		obj := utd.ToObject()
		obj.IterateAttributes(func(name string, att *design.AttributeDefinition) error {
			rf, ok := f.RelationalFields[codegen.Goify(name, true)]
			if ok {
				// We already have a mapping for this field.  What to do?
				if rf.Datatype != "" {
					return nil
				}
				// we may have seen the field but don't know its type
				// TODO(BJK) refactor this into separate func later
				switch att.Type.Kind() {
				case design.BooleanKind:
					rf.Datatype = Boolean
				case design.IntegerKind:
					rf.Datatype = Integer
				case design.NumberKind:
					rf.Datatype = BigDecimal
				case design.StringKind:
					rf.Datatype = String
				case design.DateTimeKind:
					rf.Datatype = Timestamp
				case design.MediaTypeKind:
					// Embedded MediaType
					// Skip for now?
					return nil

				default:
					dslengine.ReportError("Unsupported type: %#v %s", att.Type.Kind(), att.Type.Name())
				}
				if !utd.IsRequired(name) {
					rf.Nullable = true
				}
			}

			rf = &RelationalFieldDefinition{}
			rf.Parent = f
			rf.FieldName = codegen.Goify(name, true)

			if strings.HasSuffix(rf.FieldName, "Id") {
				rf.FieldName = strings.TrimSuffix(rf.FieldName, "Id")
				rf.FieldName = rf.FieldName + "ID"
			}
			switch att.Type.Kind() {
			case design.BooleanKind:
				rf.Datatype = Boolean
			case design.IntegerKind:
				rf.Datatype = Integer
			case design.NumberKind:
				rf.Datatype = BigDecimal
			case design.StringKind:
				rf.Datatype = String
			case design.DateTimeKind:
				rf.Datatype = Timestamp
			case design.MediaTypeKind:
				// Embedded MediaType
				// Skip for now?
				return nil

			default:
				dslengine.ReportError("Unsupported type: %#v %s", att.Type.Kind(), att.Type.Name())
			}
			if !utd.IsRequired(name) {
				rf.Nullable = true
			}
			// might need this later?
			rf.a = att
			f.RelationalFields[rf.FieldName] = rf

			addAttributeToModel(name, att, f)

			return nil
		})
	}
	return
}
887047
func (n *mutDir) populate() error {
	n.mu.Lock()
	defer n.mu.Unlock()
	ctx := context.TODO()

	// Only re-populate if we haven't done so recently.
	now := time.Now()
	if n.lastPop.Add(populateInterval).After(now) {
		return nil
	}
	n.lastPop = now

	res, err := n.fs.client.Describe(ctx, &search.DescribeRequest{
		BlobRef: n.permanode,
		Depth:   3,
	})
	if err != nil {
		Logger.Println("mutDir.paths:", err)
		return nil
	}
	db := res.Meta[n.permanode.String()]
	if db == nil {
		return errors.New("dir blobref not described")
	}

	// Find all child permanodes and stick them in n.children
	if n.children == nil {
		n.children = make(map[string]mutFileOrDir)
	}
	currentChildren := map[string]bool{}
	for k, v := range db.Permanode.Attr {
		const p = "camliPath:"
		if !strings.HasPrefix(k, p) || len(v) < 1 {
			continue
		}
		name := k[len(p):]
		childRef := v[0]
		child := res.Meta[childRef]
		if child == nil {
			Logger.Printf("child not described: %v", childRef)
			continue
		}
		if child.Permanode == nil {
			Logger.Printf("invalid child, not a permanode: %v", childRef)
			continue
		}
		if target := child.Permanode.Attr.Get("camliSymlinkTarget"); target != "" {
			// This is a symlink.
			n.maybeAddChild(name, child.Permanode, &mutFile{
				fs:        n.fs,
				permanode: blob.ParseOrZero(childRef),
				parent:    n,
				name:      name,
				symLink:   true,
				target:    target,
			})
		} else if isDir(child.Permanode) {
			// This is a directory.
			n.maybeAddChild(name, child.Permanode, &mutDir{
				fs:        n.fs,
				permanode: blob.ParseOrZero(childRef),
				parent:    n,
				name:      name,
			})
		} else if contentRef := child.Permanode.Attr.Get("camliContent"); contentRef != "" {
			// This is a file.
			content := res.Meta[contentRef]
			if content == nil {
				Logger.Printf("child content not described: %v", childRef)
				continue
			}
			if content.CamliType != "file" {
				Logger.Printf("child not a file: %v", childRef)
				continue
			}
			if content.File == nil {
				Logger.Printf("camlitype \"file\" child %v has no described File member", childRef)
				continue
			}
			n.maybeAddChild(name, child.Permanode, &mutFile{
				fs:        n.fs,
				permanode: blob.ParseOrZero(childRef),
				parent:    n,
				name:      name,
				content:   blob.ParseOrZero(contentRef),
				size:      content.File.Size,
			})
		} else {
			// unhandled type...
			continue
		}
		currentChildren[name] = true
	}
	// Remove unreferenced children
	for name, oldchild := range n.children {
		if _, ok := currentChildren[name]; !ok {
			if oldchild.eligibleToDelete() {
				delete(n.children, name)
			}
		}
	}
	return nil
}
167223
func (s *CreateMLModelInput) SetMLModelType(v string) *CreateMLModelInput {
	s.MLModelType = &v
	return s
}
1339461
func appendModels(pkgpath, controllerName string, realTypes []string) {
	for _, realType := range realTypes {
		if realType != "" && !isBasicType(strings.TrimLeft(realType, "[]")) &&
			!strings.HasPrefix(realType, astTypeMap) && !strings.HasPrefix(realType, "&") {
			if _, ok := modelsList[pkgpath+controllerName][realType]; ok {
				continue
			}
			_, mod, newRealTypes := getModel(realType)
			modelsList[pkgpath+controllerName][realType] = mod
			appendModels(pkgpath, controllerName, newRealTypes)
		}
	}
}
123433
func populateSubReferences(domain string, protoType *ProtoType) {
	for _, prop := range protoType.Properties {
		// a new SubType
		if isSubType(prop) {
			prefix := "Sub" + strings.Title(prop.Name)
			ref := &GlobalReference{}
			ref.LocalRefName = prop.Name
			ref.ExternalGoName = domain + prefix
			globalRefs[domain+prefix] = ref
			continue
		}

	}
}
809411
func (c *Client) ListModels(user string) ([]base.UserModel, error) {
	var models params.UserModelList
	if !names.IsValidUser(user) {
		return nil, errors.Errorf("invalid user name %q", user)
	}
	entity := params.Entity{names.NewUserTag(user).String()}
	err := c.facade.FacadeCall("ListModels", entity, &models)
	if err != nil {
		return nil, errors.Trace(err)
	}
	result := make([]base.UserModel, len(models.UserModels))
	for i, usermodel := range models.UserModels {
		owner, err := names.ParseUserTag(usermodel.OwnerTag)
		if err != nil {
			return nil, errors.Annotatef(err, "OwnerTag %q at position %d", usermodel.OwnerTag, i)
		}
		modelType := model.ModelType(usermodel.Type)
		if modelType == "" {
			modelType = model.IAAS
		}
		result[i] = base.UserModel{
			Name:           usermodel.Name,
			UUID:           usermodel.UUID,
			Type:           modelType,
			Owner:          owner.Id(),
			LastConnection: usermodel.LastConnection,
		}
	}
	return result, nil
}
321357
func NewPopulator(config *common.RuntimeConfig) *Populator {
	p := &Populator{RuntimeConfig: config}
	sharedInformer := config.InformerFactory.Core().V1().PersistentVolumes()
	sharedInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			pv, ok := obj.(*v1.PersistentVolume)
			if !ok {
				glog.Errorf("Added object is not a v1.PersistentVolume type")
				return
			}
			p.handlePVUpdate(pv)
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			newPV, ok := newObj.(*v1.PersistentVolume)
			if !ok {
				glog.Errorf("Updated object is not a v1.PersistentVolume type")
				return
			}
			p.handlePVUpdate(newPV)
		},
		DeleteFunc: func(obj interface{}) {
			pv, ok := obj.(*v1.PersistentVolume)
			if !ok {
				glog.Errorf("Added object is not a v1.PersistentVolume type")
				return
			}
			p.handlePVDelete(pv)
		},
	})
	return p
}
1077104
func (b modelBuilder) addModelFrom(sample interface{}) {
	if modelOrNil := b.addModel(reflect.TypeOf(sample), ""); modelOrNil != nil {
		// allow customizations
		if buildable, ok := sample.(ModelBuildable); ok {
			modelOrNil = buildable.PostBuildModel(modelOrNil)
			b.Models.Put(modelOrNil.Id, *modelOrNil)
		}
	}
}
404499
func InitModels() {
	index := mgo.Index{
		Key:      []string{"username"},
		Unique:   true,
		DropDups: true,
	}
	db.EnsureIndex(mongoCollectionName, index)

	index = mgo.Index{
		Key:      []string{"username", "token"},
		Unique:   true,
		DropDups: true,
	}
	db.EnsureIndex(mongoCollectionNameResetToken, index)

	automaticExpiration := mgo.Index{
		Key:         []string{"createdat"},
		ExpireAfter: time.Minute * 10,
		Background:  true,
	}
	db.EnsureIndex(mongoCollectionNameResetToken, automaticExpiration)
}
186396
func FillDefaultFrom(defaultsList ...interface{}) interface{} {
	if len(defaultsList) == 0 {
		return nil
	}

	rootType := reflect.TypeOf(defaultsList[0])
	if rootType.Kind() != reflect.Ptr {
		panic(fmt.Sprintf("FillDefaultsFrom only takes pointer types, not %s", rootType))
	}
	typeToMake := rootType.Elem()

	existing := reflect.New(typeToMake).Interface()
	existingVal := reflect.ValueOf(existing).Elem()
	existingType := reflect.TypeOf(existing)
	for _, defaults := range defaultsList {
		if defaults == nil {
			continue
		}
		defaultType := reflect.TypeOf(defaults)
		if defaultType != existingType {
			panic(fmt.Sprintf("Uncompatible types %s vs %s", existingType, defaultType))
		}
		defaultsVal := reflect.ValueOf(defaults)
		if defaultsVal.IsNil() {
			continue
		}
		defaultsVal = defaultsVal.Elem()
		singleItemCopy(existingVal, defaultsVal)
	}
	return existing
}
1335585
func NewRelationalModelDefinition() *RelationalModelDefinition {
	baseAttr := &design.AttributeDefinition{}
	utd := &design.UserTypeDefinition{
		AttributeDefinition: baseAttr,
	}
	utd.Type = design.Object{}
	m := &RelationalModelDefinition{
		RelationalFields: make(map[string]*RelationalFieldDefinition),
		BuiltFrom:        make(map[string]*design.UserTypeDefinition),
		RenderTo:         make(map[string]*design.MediaTypeDefinition),
		BelongsTo:        make(map[string]*RelationalModelDefinition),
		HasMany:          make(map[string]*RelationalModelDefinition),
		HasOne:           make(map[string]*RelationalModelDefinition),
		ManyToMany:       make(map[string]*ManyToManyDefinition),
		UserTypeDefinition: &design.UserTypeDefinition{
			AttributeDefinition: baseAttr,
		},
	}
	return m
}
98368
func (ms *modelSpec) checkModelType(model Model) error {
	if reflect.TypeOf(model) != ms.typ {
		return fmt.Errorf("model was the wrong type. Expected %s but got %T", ms.typ.String(), model)
	}
	return nil
}
1177868
func (self *RecordSet) PopulateFromRecords(into interface{}, schema *Collection) error {
	vInto := reflect.ValueOf(into)

	// get value pointed to if we were given a pointer
	if vInto.Kind() == reflect.Ptr {
		vInto = vInto.Elem()
	} else {
		return fmt.Errorf("Output argument must be a pointer")
	}

	// we're going to fill arrays or slices
	switch vInto.Type().Kind() {
	case reflect.Array, reflect.Slice:
		indirectResult := true

		// get the type of the underlying slice element
		sliceType := vInto.Type().Elem()

		// get the type pointed to
		if sliceType.Kind() == reflect.Ptr {
			sliceType = sliceType.Elem()
			indirectResult = false
		}

		// for each resulting record...
		for _, record := range self.Records {
			// make a new zero-valued instance of the slice type
			elem := reflect.New(sliceType)

			// if we have a registered collection, use its
			if schema != nil && schema.HasRecordType() {
				elem = reflect.ValueOf(schema.NewInstance())
			}

			// populate that type with data from this record
			if err := record.Populate(elem.Interface(), schema); err == nil {
				// if the slice elements are pointers, we can append the pointer we just created as-is
				// otherwise, we need to indirect the value and append a copy

				if indirectResult {
					vInto.Set(reflect.Append(vInto, reflect.Indirect(elem)))
				} else {
					vInto.Set(reflect.Append(vInto, elem))
				}
			} else {
				return err
			}
		}

		return nil
	case reflect.Struct:
		if rs, ok := into.(*RecordSet); ok {
			*rs = *self
			return nil
		}
	}

	return fmt.Errorf("RecordSet can only populate records into slice or array, got %T", into)
}
222486
func (b *BaggedModel) AddModel(m base.Classifier) {
	b.Models = append(b.Models, m)
}
1020471
func (b *OpenAPI3Builder) buildTypeFromParameters(
	name string,
	parameters []*openapiv3.ParameterOrReference,
	requestBody *openapiv3.RequestBodyOrReference) (typeName string, err error) {
	t := &Type{}
	t.Name = name + "Parameters"
	t.Description = t.Name + " holds parameters to " + name
	t.Kind = TypeKind_STRUCT
	t.Fields = make([]*Field, 0)
	for _, parametersItem := range parameters {
		var f Field
		f.Type = fmt.Sprintf("%+v", parametersItem)
		parameter := parametersItem.GetParameter()
		if parameter != nil {
			switch parameter.In {
			case "body":
				f.Position = Position_BODY
			case "header":
				f.Position = Position_HEADER
			case "formdata":
				f.Position = Position_FORMDATA
			case "query":
				f.Position = Position_QUERY
			case "path":
				f.Position = Position_PATH
			}
			f.Name = parameter.Name
			if parameter.GetSchema() != nil && parameter.GetSchema() != nil {
				f.Kind, f.Type, f.Format = b.typeForSchemaOrReference(parameter.GetSchema())
			}
			f.Serialize = true
			t.addField(&f)
		}
	}
	if requestBody != nil {
		content := requestBody.GetRequestBody().GetContent()
		if content != nil {
			for _, pair2 := range content.GetAdditionalProperties() {
				if pair2.Name != "application/json" {
					log.Printf("unimplemented: %q requestBody(%s)", name, pair2.Name)
					continue
				}
				var f Field
				f.Position = Position_BODY
				f.Kind, f.Type, f.Format = b.typeForSchemaOrReference(pair2.GetValue().GetSchema())
				f.Name = strings.ToLower(f.Type) // use the schema name as the parameter name, since none is directly specified
				f.Serialize = true
				t.addField(&f)
			}
		}
	}
	if len(t.Fields) > 0 {
		b.model.addType(t)
		return t.Name, err
	}
	return "", err
}
782761
func (lp PDPKALoginPackage) PopulateArgs(h *HTTPArgs) {
	h.Add("pdpka4", S{string(lp.pdpka4)})
	h.Add("pdpka5", S{string(lp.pdpka5)})
}
1372713
func populateNewBindVariable(
	bindVariableName string,
	bindVariableValue *querypb.BindVariable,
	resultBindVariables map[string]*querypb.BindVariable) {
	_, alreadyInMap := resultBindVariables[bindVariableName]
	if alreadyInMap {
		panic(fmt.Sprintf(
			"bindVariable %v already exists in map: %v. bindVariableValue given: %v",
			bindVariableName,
			resultBindVariables,
			bindVariableValue))
	}
	resultBindVariables[bindVariableName] = bindVariableValue
}