Creating a default instance of a basic non-relational field.
427783
def get_field_kwargs(field_name, model_field):
    
    kwargs = {}

    # The following will only be used by ModelField classes.
    # Gets removed for everything else.
    kwargs['model_field'] = model_field

    if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):
        kwargs['label'] = capfirst(model_field.verbose_name)

    if hasattr(model_field, 'help_text'):
        kwargs['help_text'] = model_field.help_text

    if isinstance(model_field, me_fields.DecimalField):
        precision = model_field.precision
        max_value = getattr(model_field, 'max_value', None)
        if max_value is not None:
            max_length = len(str(max_value)) + precision
        else:
            max_length = 65536
        kwargs['decimal_places'] = precision
        kwargs['max_digits'] = max_length

    if isinstance(model_field, me_fields.GeoJsonBaseField):
        kwargs['geo_type'] = model_field._type

    if isinstance(model_field, me_fields.SequenceField) or model_field.primary_key or model_field.db_field == '_id':
        # If this field is read-only, then return early.
        # Further keyword arguments are not valid.
        kwargs['read_only'] = True
        return kwargs

    if model_field.default and not isinstance(model_field, me_fields.ComplexBaseField):
        kwargs['default'] = model_field.default

    if model_field.null:
        kwargs['allow_null'] = True

    if model_field.null and isinstance(model_field, me_fields.StringField):
        kwargs['allow_blank'] = True

    if 'default' not in kwargs:
        kwargs['required'] = model_field.required

        # handle special cases - compound fields: mongoengine.ListField/DictField
        if kwargs['required'] is True:
            if isinstance(model_field, me_fields.ListField) or isinstance(model_field, me_fields.DictField):
                kwargs['allow_empty'] = False

    if model_field.choices:
        # If this model field contains choices, then return early.
        # Further keyword arguments are not valid.
        kwargs['choices'] = model_field.choices
        return kwargs

    if isinstance(model_field, me_fields.StringField):
        if model_field.regex:
            kwargs['regex'] = model_field.regex

    max_length = getattr(model_field, 'max_length', None)
    if max_length is not None and isinstance(model_field, me_fields.StringField):
        kwargs['max_length'] = max_length

    min_length = getattr(model_field, 'min_length', None)
    if min_length is not None and isinstance(model_field, me_fields.StringField):
        kwargs['min_length'] = min_length

    max_value = getattr(model_field, 'max_value', None)
    if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['max_value'] = max_value

    min_value = getattr(model_field, 'min_value', None)
    if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['min_value'] = min_value

    return kwargs
370515
def field_for(name, predicate, options)
      Tripod::Fields::Standard.new(name, predicate, options)
    end
1092510
def default(self, value):
        """"""

        if value is None:
            if self:
                value = list(self.keys())[0]

        elif not isinstance(value, string_types):
            value = register(exprresolver=value, reg=self)

        elif value not in self:
            raise KeyError(
                '{0} not registered in {1}'.format(value, self)
            )

        self._default = value
1236164
def add_field(self, name, default=None, required=False, error=None):
        
        if name is None:
            return
        self.field_arguments.append(dict(
            name=name,
            default=default,
            required=required,
            error=error))
537322
def create_from(cls, another, **kwargs):
        
        reused_fields = {}
        for field, value in another.get_fields():
            if field in cls.FIELDS:
                reused_fields[field] = value
        reused_fields.update(kwargs)
        return cls(**reused_fields)
28423
def __parameter_default(self, field):
    
    if field.default:
      if isinstance(field, messages.EnumField):
        return field.default.name
      else:
        return field.default
57883
private Indexer getDefaultIndexer(Field field) {
    Type type = field.getGenericType();
    if (type instanceof Class && type.equals(String.class)) {
      return getIndexer(LowerCaseStringIndexer.class);
    } else if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Class<?> rawType = (Class<?>) parameterizedType.getRawType();
      if (List.class.isAssignableFrom(rawType) || Set.class.isAssignableFrom(rawType)) {
        Class<?>[] collectionType = IntrospectionUtils.resolveCollectionType(type);
        if (String.class.equals(collectionType[1])) {
          return getIndexer(LowerCaseStringListIndexer.class);
        }
      }
    }
    String message = String.format("No default indexer found for field %s in class %s",
        field.getName(), field.getDeclaringClass().getName());
    throw new NoSuitableIndexerException(message);
  }
1100525
def _construct_instance(cls, values):
        
        # we're going to take the values, which is from the DB as a dict
        # and translate that into our local fields
        # the db_map is a db_field -> model field map
        if cls._db_map:
            values = dict((cls._db_map.get(k, k), v) for k, v in values.items())

        if cls._is_polymorphic:
            disc_key = values.get(cls._discriminator_column_name)

            if disc_key is None:
                raise PolymorphicModelException('discriminator value was not found in values')

            poly_base = cls if cls._is_polymorphic_base else cls._polymorphic_base

            klass = poly_base._get_model_by_discriminator_value(disc_key)
            if klass is None:
                poly_base._discover_polymorphic_submodels()
                klass = poly_base._get_model_by_discriminator_value(disc_key)
                if klass is None:
                    raise PolymorphicModelException(
                        'unrecognized discriminator column {0} for class {1}'.format(disc_key, poly_base.__name__)
                    )

            if not issubclass(klass, cls):
                raise PolymorphicModelException(
                    '{0} is not a subclass of {1}'.format(klass.__name__, cls.__name__)
                )

            values = dict((k, v) for k, v in values.items() if k in klass._columns.keys())

        else:
            klass = cls

        instance = klass(**values)
        instance._set_persisted(force=True)
        return instance
1180180
def default(self, value):
        """"""
        if isinstance(value, ObjectId):
            return str(value)
        return super(ElasticJSONSerializer, self).default(value)
82236
def apply_defaults(self, instance):
        """"""
        for field, spec in self.doc_spec.iteritems():
            field_type = spec['type']
            if field not in instance:
                if 'default' in spec:
                    default = spec['default']
                    if callable(default):
                        instance[field] = default()
                    else:
                        instance[field] = copy.deepcopy(default)
            # Determine if a value already exists for the field
            if field in instance:
                value = instance[field]

                # recurse into nested docs
                if isinstance(field_type, Schema) and isinstance(value, dict):
                    field_type.apply_defaults(value)

                elif isinstance(field_type, Array) and isinstance(field_type.contained_type, Schema) and isinstance(value, list):
                    for item in value:
                        field_type.contained_type.apply_defaults(item)
174321
def make_field_objects(field_data, names):
        # type: (List[Dict[Text, Text]], Names) -> List[Field]
        """"""
        field_objects = []
        field_names = []  # type: List[Text]
        for field in field_data:
            if hasattr(field, 'get') and callable(field.get):
                atype = cast(Text, field.get('type'))
                name = cast(Text, field.get('name'))

                # null values can have a default value of None
                has_default = False
                default = None
                if 'default' in field:
                    has_default = True
                    default = field.get('default')

                order = field.get('order')
                doc = field.get('doc')
                other_props = get_other_props(field, FIELD_RESERVED_PROPS)
                new_field = Field(atype, name, has_default, default, order, names, doc,
                                 other_props)
                # make sure field name has not been used yet
                if new_field.name in field_names:
                    fail_msg = 'Field name %s already in use.' % new_field.name
                    raise SchemaParseException(fail_msg)
                field_names.append(new_field.name)
            else:
                raise SchemaParseException('Not a valid field: %s' % field)
            field_objects.append(new_field)
        return field_objects
741144
def Field(self, field, Value = None):
        '''
        
        '''
        if Value == None:
            try:
                return self.__Bitmap[field]
            except KeyError:
                return None
        elif Value == 1 or Value == 0:
            self.__Bitmap[field] = Value
        else:
            raise ValueError
1247590
def get_field(field):
    """"""
    if isinstance(field, djmodels.fields.Field):
        return field
    elif isinstance(field, basestring):
        field = field.split('.')
        if len(field) == 3:
            model = get_model(app=field[0], model=field[1])
        elif len(field) == 2:
            model = get_model(app=DEFAULT_APP, model=field[0])
        else:
            return None
            raise NotImplementedError("Unknown default model name. Don't know where to look for field %s" % '.'.join(field)) 
        field = model._meta.get_field(field[-1])
    return field
318210
def build_standard_field(self, field_name, model_field):
        
        kwargs = {}

        if model_field.null or model_field.blank:
            kwargs['required'] = False

            if model_field.null:
                kwargs['allow_null'] = True
            if model_field.blank and (issubclass(model_field.__class__, models.CharField) or
                                      (issubclass(model_field.__class__, models.TextField))):
                kwargs['allow_blank'] = True

        if isinstance(model_field, models.AutoField) or not model_field.editable:
            kwargs['read_only'] = True

        if model_field.has_default():
            kwargs['default'] = model_field.get_default()

        if issubclass(model_field.__class__, models.TextField):
            kwargs['style'] = {'base_template': 'textarea.html'}

        if model_field.verbose_name is not None:
            kwargs['label'] = model_field.verbose_name

        if model_field.help_text is not None:
            kwargs['help_text'] = model_field.help_text

        # TODO: TypedChoiceField?
        if model_field.flatchoices:  # This ModelField contains choices
            kwargs['choices'] = model_field.flatchoices
            if model_field.null:
                kwargs['empty'] = None
            return (ChoiceField, kwargs)

        # put this below the ChoiceField because min_value isn't a valid initializer
        if issubclass(model_field.__class__, models.PositiveIntegerField) or\
                issubclass(model_field.__class__, models.PositiveSmallIntegerField):
            kwargs['min_value'] = 0

        attribute_dict = {
            models.CharField: ['max_length'],
            models.CommaSeparatedIntegerField: ['max_length'],
            models.DecimalField: ['max_digits', 'decimal_places'],
            models.EmailField: ['max_length'],
            models.FileField: ['max_length'],
            models.ImageField: ['max_length'],
            models.SlugField: ['max_length'],
            models.URLField: ['max_length'],
        }

        # === django-rest-framework-hstore specific ====
        # if available, use __basefield__ attribute instead of __class__
        # this will cause DRF to pick the correct DRF-field
        key = getattr(model_field, '__basefield__', model_field.__class__)

        if key in attribute_dict:
            attributes = attribute_dict[key]
            for attribute in attributes:
                kwargs.update({attribute: getattr(model_field, attribute)})

        if model_field.__class__ == DictionaryField and model_field.schema:
            kwargs['schema'] = True

        try:
            return (self.serializer_field_mapping[key], kwargs)
        except KeyError:
            pass

        try:
            return (self.serializer_field_mapping[model_field.__class__.__name__], kwargs)
        except KeyError:
            # return ModelField(model_field=model_field, **kwargs)
            return super(HStoreSerializer, self).build_standard_field(field_name, model_field)
1367800
def GetDefault(self, fd=None, default=None):
    """"""
    if callable(self.default):
      return self.default(fd)

    if self.default is not None:
      # We can't return mutable objects here or the default might change for all
      # objects of this class.
      if isinstance(self.default, rdfvalue.RDFValue):
        default = self.default.Copy()
        default.attribute_instance = self
        return self(default)
      else:
        return self(self.default)

    if isinstance(default, rdfvalue.RDFValue):
      default = default.Copy()
      default.attribute_instance = self

    return default
351158
function createField(kind) {
  if (!fields.has(kind)) {
    let type;
    switch (kind) {
      case DynamicFieldKind.STRING_VAL.toString():
        type = StringType.create();
        break;

      case DynamicFieldKind.TEXT_VAL.toString():
        type = TextType.create();
        break;

      case DynamicFieldKind.INT_VAL.toString():
        type = IntType.create();
        break;

      case DynamicFieldKind.BOOL_VAL.toString():
        type = BooleanType.create();
        break;

      case DynamicFieldKind.FLOAT_VAL.toString():
        type = FloatType.create();
        break;

      case DynamicFieldKind.DATE_VAL.toString():
        type = DateType.create();
        break;

      default:
        throw new AssertionFailed(`DynamicField "${kind}" is not a valid type.`);
    }

    fields.set(
      kind, new Field({ name: kind, type, rule: FieldRule.A_SINGLE_VALUE, required: true }),
    );
  }

  return fields.get(kind);
}
1144722
def p_field(self, p):
        """"""
        has_annotations = len(p) > 5 and p[6] is not None
        has_docstring = len(p) > 5 and p[7] is not None
        has_anony_def = len(p) > 5 and p[8] is not None
        p[0] = AstField(
            self.path, p.lineno(1), p.lexpos(1), p[1], p[2])
        if p[3] is not None:
            if p[3] is NullToken:
                p[0].set_default(None)
            else:
                p[0].set_default(p[3])
        if has_annotations:
            p[0].set_annotations(p[6])
        if has_docstring:
            p[0].set_doc(p[7])
        if has_anony_def:
            p[8].name = p[2].name
            self.anony_defs.append(p[8])