Combine maps and records.

Field defaults are kept when possible (i.e. when no coercion to a map
happens), with later definitions overriding previous ones.
346149
function combineObjects(types, opts) {
  var allTypes = []; // Field and value types.
  var fieldTypes = {}; // Record field types grouped by field name.
  var fieldDefaults = {};
  var isValidRecord = true;

  // Check whether the final type will be a map or a record.
  var i, l, type, fields;
  for (i = 0, l = types.length; i < l; i++) {
    type = types[i];
    if (type.getTypeName() === 'map') {
      isValidRecord = false;
      allTypes.push(type.getValuesType());
    } else {
      fields = type.getFields();
      var j, m, field, fieldDefault, fieldName, fieldType;
      for (j = 0, m = fields.length; j < m; j++) {
        field = fields[j];
        fieldName = field.getName();
        fieldType = field.getType();
        allTypes.push(fieldType);
        if (isValidRecord) {
          if (!fieldTypes[fieldName]) {
            fieldTypes[fieldName] = [];
          }
          fieldTypes[fieldName].push(fieldType);
          fieldDefault = field.getDefault();
          if (fieldDefault !== undefined) {
            // Later defaults will override any previous ones.
            fieldDefaults[fieldName] = fieldDefault;
          }
        }
      }
    }
  }

  if (isValidRecord) {
    // Check that no fields are missing and that we have the approriate
    // defaults for those which are.
    var fieldNames = Object.keys(fieldTypes);
    for (i = 0, l = fieldNames.length; i < l; i++) {
      fieldName = fieldNames[i];
      if (
        fieldTypes[fieldName].length < types.length &&
        fieldDefaults[fieldName] === undefined
      ) {
        // At least one of the records is missing a field with no default.
        if (opts && opts.strictDefaults) {
          isValidRecord = false;
        } else {
          fieldTypes[fieldName].unshift(createType('null', opts));
          fieldDefaults[fieldName] = null;
        }
      }
    }
  }

  var attrs;
  if (isValidRecord) {
    attrs = {
      type: 'record',
      fields: fieldNames.map(function (s) {
        var fieldType = combine(fieldTypes[s], opts);
        var fieldDefault = fieldDefaults[s];
        if (
          fieldDefault !== undefined &&
          ~fieldType.getTypeName().indexOf('union')
        ) {
          // Ensure that the default's corresponding type is first.
          var unionTypes = fieldType.getTypes();
          var i, l;
          for (i = 0, l = unionTypes.length; i < l; i++) {
            if (unionTypes[i].isValid(fieldDefault)) {
              break;
            }
          }
          if (i > 0) {
            var unionType = unionTypes[0];
            unionTypes[0] = unionTypes[i];
            unionTypes[i] = unionType;
            fieldType = createType(unionTypes, opts);
          }
        }
        return {
          name: s,
          type: fieldType,
          'default': fieldDefaults[s]
        };
      })
    };
  } else {
    attrs = {
      type: 'map',
      values: combine(allTypes, opts)
    };
  }
  return createType(attrs, opts);
}
663999
private void populateDefaultData(FieldItem[] defaultData)
   {
      for (FieldItem item : defaultData)
      {
         m_map.put(item.getType(), item);
      }
   }
492702
def _init_map(self, record_types=None, **kwargs):
        """"""

        osid_objects.OsidContainableForm._init_map(self)
        osid_objects.OsidSourceableForm._init_map(self)
        osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
        self._my_map['childIds'] = self._children_default
        self._my_map['assignedRepositoryIds'] = [str(kwargs['repository_id'])]
596801
public function extend_fieldmap($map)
    {
        if (is_array($map)) {
            self::$fieldmap = array_merge($map, self::$fieldmap);
        }
    }
1159277
function(records,config) {
    
    //the hell is this doing here
    this.id = new Date();

    if ( records instanceof Array ) {
        this.records = records;
    } else {
        var dataField = records.data;
        var data = records.datasource;
        this.records =  data[dataField];
    }
    this.config = config;
    if ( this.config ) {
        this.propertyConfigMap = {};
        this.config.cols.forEach( col => {
            this.propertyConfigMap[col.property] = col;
        });
    }

    //indexRecords.call(this);
}
983092
def append_fields(self, new_fields):
        '''
        
        '''
        for field in new_fields:
            self.push(field)
            if isinstance(field, Container):
                self.pop()
766537
public void setRecordMetadata(String key, Object value) {
    if (_recordMetadata == null) {
      _recordMetadata = new HashMap<>();
    }

    _recordMetadata.put(key, value);
  }
1168646
def add_fields(self, fields):
        
        for k, v in fields.items():
            if k not in self._fields:
                self._fields[k] = v
721872
def _init_map(self, record_types=None, **kwargs):
        """"""
        osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
        self._my_map['nextAssessmentPartId'] = str(kwargs['next_assessment_part_id'])
        self._my_map['cumulative'] = self._cumulative_default
        self._my_map['minimumScore'] = self._minimum_score_default
        self._my_map['maximumScore'] = self._maximum_score_default
        self._my_map['assessmentPartId'] = str(kwargs['assessment_part_id'])
        self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])]
        self._my_map['appliedAssessmentPartIds'] = []
134480
public void setupSFields()
    {
        Record record = this.getMainRecord();
        BaseField field = record.getField(DBConstants.MAIN_FIELD);
        if (field == record.getCounterField())
            field.setupDefaultView(this.getNextLocation(ScreenConstants.NEXT_LOGICAL, ScreenConstants.SET_ANCHOR), this, ScreenConstants.DEFAULT_DISPLAY);
        super.setupSFields();
    }
717768
public void fixRecord(Record record)
    {
        super.fixRecord(record);
        if (this.getProperty("field") != null)
        {
            BaseField field = this.getMainRecord().getField(this.getProperty("field").toString());
            if (field != null)
                this.fixCapitalization(field);
        }
    }
52617
static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {
        for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {
            Object existing = original.get(entry.getKey());
            if (existing != null) {
                ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);
            } else {
                original.put(entry.getKey(), entry.getValue());
            }
        }
    }
944712
def concat(*records)
      load_target
      flatten_records = records.flatten
      flatten_records.each { |val| raise_on_type_mismatch!(val) }
      target_ids = reflection.options[:target_ids]
      owner[target_ids] ||= []
      owner[target_ids].concat(flatten_records.map(&:id))

      flatten_records.each do |record|
        if index = @target.index(record)
          @target[index] = record
        else
          @target << record
        end
      end

      target
    end
1079485
private Map<UUID, FieldType> populateCustomFieldMap()
   {
      byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);
      int length = MPPUtility.getInt(data, 0);
      int index = length + 36;

      // 4 byte record count
      int recordCount = MPPUtility.getInt(data, index);
      index += 4;

      // 8 bytes per record
      index += (8 * recordCount);
      
      Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();
      while (index < data.length)
      {
         int blockLength = MPPUtility.getInt(data, index);         
         if (blockLength <= 0 || index + blockLength > data.length)
         {
            break;
         }
         
         int fieldID = MPPUtility.getInt(data, index + 4);
         FieldType field = FieldTypeHelper.getInstance(fieldID);
         UUID guid = MPPUtility.getGUID(data, index + 160);
         map.put(guid, field);
         index += blockLength;
      }
      return map;
   }
903167
public void maybeSetLegacyObjectMapOrRecordType() {
    if (type == Type.UNKNOWN) {
      type = Type.LEGACY_OBJECT_MAP_OR_RECORD;
    } else if (type == Type.MAP) {
      throw new IllegalStateException(
          "Expected a value of type `legacy_object_map`, got `map`. "
              + "These two map types are not interoperable. "
              + "Use `mapToLegacyObjectMap()` to convert this object to a legacy_object_map.");
    }
  }
419684
@SuppressWarnings("unchecked")
	private void mergeMap (Map<String, Object> dest, Object source) throws YamlReaderException {
		if (source instanceof Collection) {
			for (Object item : ((Collection<Object>)source))
				mergeMap(dest, item);
		} else if (source instanceof Map) {
			Map<String, Object> map = (Map<String, Object>)source;
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (!dest.containsKey(entry.getKey())) dest.put(entry.getKey(), entry.getValue());

			}
		} else
			throw new YamlReaderException("Expected a mapping or a sequence of mappings for a '<<' merge field but found: "
				+ source.getClass().getSimpleName());

	}
773517
public void saveOldProperties(Map<String,String> oldProperties, Record record)
    {
        this.saveOldProperty(oldProperties, record.getDatabaseName() + BaseDatabase.DBSHARED_PARAM_SUFFIX);
        this.saveOldProperty(oldProperties, record.getDatabaseName() + BaseDatabase.DBUSER_PARAM_SUFFIX);
        this.saveOldProperty(oldProperties, DBConstants.DB_USER_PREFIX);
        this.saveOldProperty(oldProperties, DBConstants.SYSTEM_NAME);
        this.saveOldProperty(oldProperties, DBParams.LANGUAGE);
    }