Field Utility methods
 Return numeric version of value
509280
def as_int(value, default = 0)
      res = default

      if value
        if value.is_a?(Fixnum)
          res = value
        elsif value.respond_to?(:to_i)
          res = value.to_i
        end
      end

      res
    end
170541
def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
    
    if fill_value is not None:
        return fill_value
    if _na_ok_dtype(dtype):
        if fill_value_typ is None:
            return np.nan
        else:
            if fill_value_typ == '+inf':
                return np.inf
            else:
                return -np.inf
    else:
        if fill_value_typ is None:
            return tslibs.iNaT
        else:
            if fill_value_typ == '+inf':
                # need the max int here
                return _int64_max
            else:
                return tslibs.iNaT
135914
private void marshalVersionField() {
    PropertyMetadata versionMetadata = entityMetadata.getVersionMetadata();
    if (versionMetadata != null) {
      long version = (long) IntrospectionUtils.getFieldValue(versionMetadata, entity);
      ValueBuilder<?, ?, ?> valueBuilder = versionMetadata.getMapper().toDatastore(version + 1);
      valueBuilder.setExcludeFromIndexes(!versionMetadata.isIndexed());
      entityBuilder.set(versionMetadata.getMappedName(), valueBuilder.build());
    }
  }
822530
def _get_field_type(self, key, value):
        
        if isinstance(value, bool):
            return BooleanField(name=key)
        elif isinstance(value, int):
            return IntegerField(name=key)
        elif isinstance(value, float):
            return FloatField(name=key)
        elif isinstance(value, str):
            return StringField(name=key)
        elif isinstance(value, time):
            return TimeField(name=key)
        elif isinstance(value, datetime):
            return DateTimeField(name=key)
        elif isinstance(value, date):
            return DateField(name=key)
        elif isinstance(value, timedelta):
            return TimedeltaField(name=key)
        elif isinstance(value, Enum):
            return EnumField(name=key, enum_class=type(value))
        elif isinstance(value, (dict, BaseDynamicModel, Mapping)):
            return ModelField(name=key, model_class=self.__dynamic_model__ or self.__class__)
        elif isinstance(value, BaseModel):
            return ModelField(name=key, model_class=value.__class__)
        elif isinstance(value, (list, set, ListModel)):
            if not len(value):
                return None
            field_type = self._get_field_type(None, value[0])
            return ArrayField(name=key, field_type=field_type)
        elif value is None:
            return None
        else:
            raise TypeError("Invalid parameter: %s. Type not supported." % (key,))
1108700
function getValueLength(value, constructed) {
  var lenValue = 0;
  
  if (constructed) {
    for (var i = 0; i < value.length; i++) {
      lenValue = lenValue + value[i].byteLength;
    }
  } else {
    lenValue = value.length;
  }    
  
  return lenValue;
}
637292
def normalize_field(self, value):
        
        if self.default is not None:
            if value is None or value == '':
                value = self.default
        return value
1231051
function numericField (ops) {
  const calculateScore = (x, i, resultset) => {
    x.score = +x.match.filter(
      item => item.startsWith(ops.fieldName)
    )[0].split(':')[1];
    return x
  };
  return ops
    .resultSet
    .map(calculateScore)
  // sort by score descending
    .sort(ops.sort)
  // limit to n hits
    .slice(ops.offset, ops.limit)
}
337847
function(val) {

    if (val === undefined) {
      return "undefined";
    }
    if (val === null) {
      return "null";
    }

    let type = typeof val;

    if (type === "object") {
      type = getClass(val).toLowerCase();
    }

    if (type === "number") {
      return val.toString().indexOf(".") > 0 ?
        "float" :
        "integer";
    }

    return type;
  }
107709
private static String getJsonValueAsNumberString(JsonValue value) {
        return (value != null && value.getValueType() == ValueType.NUMBER) ? value.toString() : null;
    }
864890
private static int parseField(String field, Input s, Character delim, int minLen, int maxLen, boolean strict) {
    int startIndex = s.index;
    int result = parseInt(s);
    if (startIndex == s.index) throw new DateFormatException("missing value for field '" + field + "'", s.str, startIndex);
    if (strict) {
      int len = s.index - startIndex;
      if (len < minLen) throw new DateFormatException("field '" + field + "' must be at least " + minLen + " digits wide", s.str, startIndex);
      if (maxLen > 0 && len > maxLen) throw new DateFormatException("field '" + field + "' must be no more than " + minLen + " digits wide", s.str, startIndex);
    }
    if (delim != null) {
      if (s.index >= s.len) throw new DateFormatException("unexpected end of input", s.str, s.index);
      if (strict && s.getChar() != delim.charValue()) throw new DateFormatException("unexpected character, expected '" + delim + "'", s.str, s.index);
      s.index++;
    }
    return result;
  }
378747
function ValueStatGetter(model, params, options) {
  BaseStatGetter.call(this, model, params, options);

  var OPERATORS = new Operators(options);

  var schema = Interface.Schemas.schemas[model.name];
  function getAggregate() {
    return params.aggregate.toLowerCase();
  }

  function getAggregateField() {
    // NOTICE: As MySQL cannot support COUNT(table_name.*) syntax, fieldName
    //         cannot be '*'.
    var fieldName = params['aggregate_field'] || schema.primaryKeys[0]||
      schema.fields[0].field;
    return schema.name + '.' + fieldName;
  }

  function getIncludes() {
    var includes = [];
    _.values(model.associations).forEach(function (association) {
      if (['HasOne', 'BelongsTo'].indexOf(association.associationType) > -1) {
        includes.push({
          model: association.target.unscoped(),
          as: association.associationAccessor,
          attributes: []
        });
      }
    });

    return includes;
  }

  function getIntervalDateFilterForPrevious() {
    var intervalDateFilter;

    params.filters.forEach(function (filter) {
      var operatorValueParser =
        new OperatorDateIntervalParser(filter.value, params.timezone, options);
      if (operatorValueParser.hasPreviousInterval()) {
        intervalDateFilter = filter;
      }
    });
    return intervalDateFilter;
  }

  this.perform = function () {
    var countCurrent;
    var aggregateField = getAggregateField();
    var aggregate = getAggregate();
    var filters = this.getFilters();
    var filterDateIntervalForPrevious = getIntervalDateFilterForPrevious();

    return model
      .unscoped()
      .aggregate(aggregateField, aggregate, {
        include: getIncludes(),
        where: filters
      })
      .then(function (count) {
        countCurrent = count || 0;

        // NOTICE: Search for previous interval value only if the filterType is
        //         'AND', it would not be pertinent for a 'OR' filterType.
        if (filterDateIntervalForPrevious && params.filterType === 'and') {
          var operatorValueParser = new OperatorDateIntervalParser(
            filterDateIntervalForPrevious.value, params.timezone, options
          );
          var conditions = filters[OPERATORS.AND];
          conditions.forEach(function (condition) {
            if (condition[filterDateIntervalForPrevious.field]) {
              condition[filterDateIntervalForPrevious.field] =
                operatorValueParser.getIntervalDateFilterForPreviousInterval();
            }
          });
          return model
            .unscoped()
            .aggregate(aggregateField, aggregate, {
              include: getIncludes(),
              where: filters
            })
            .then(function (count) { return count || 0; });
        }
        return undefined;
      })
      .then(function (countPrevious) {
        return {
          value: {
            countCurrent: countCurrent,
            countPrevious: countPrevious
          }
        };
      });
  };
}
1185189
function formatValue(value) {
  if (isNumeric(value)) return t.numericLiteral(Number(value))
  if (isConvertiblePixelValue(value))
    return t.numericLiteral(Number(trimEnd(value, 'px')))
  return t.stringLiteral(value)
}
272182
function _convertToNumber(str) {
        if (typeof str !== "string") {
            return { isNumber: false, value: null };
        }

        var val = parseFloat(+str, 10),
            isNum = (typeof val === "number") && !isNaN(val) &&
                    (val !== Infinity) && (val !== -Infinity);

        return {
            isNumber: isNum,
            value:    val
        };
    }
1071528
function parseValueToStringOrNumber ( value ) {
	let resolvedValue, resolvedUnitValue;
	try {
		resolvedUnitValue = parseUnit(value);
		if ( unitTypes.indexOf(resolvedUnitValue.type) !== -1 ) {
			resolvedValue = new types.Number(resolvedUnitValue.value, resolvedUnitValue.unit);
		} else if ( resolvedUnitValue.type === 'percentage' ) {
			resolvedValue = new types.Number(resolvedUnitValue.value, '%');
		} else {
			resolvedValue = new types.String(resolvedUnitValue.value);
		}
	} catch ( e ) {
		resolvedValue = new types.String(value);
	}
	return resolvedValue;
}
612677
function getFormattedValues (formatString, rawValues) {
      var formattedValueString = formatString;
      var rawValuesLength = rawValues.length;

      for (var i = 0; i < rawValuesLength; i++) {
        formattedValueString = formattedValueString.replace(
          VALUE_PLACEHOLDER, +rawValues[i].toFixed(4));
      }

      return formattedValueString;
    }
74141
def convert(self, value, view):
        
        if isinstance(value, NUMERIC_TYPES):
            return value
        else:
            self.fail(
                u'must be numeric, not {0}'.format(type(value).__name__),
                view,
                True
            )
1136047
private int getFieldValueAsInt(final DatatypeConstants.Field field) {
        Number n = getField(field);
        if (n != null) {
            return n.intValue();
        }
        return 0;
    }