modifies documents before being inserted or updated
168187
function prepareDocs(coll, docs, options) {
  const forceServerObjectId =
    typeof options.forceServerObjectId === 'boolean'
      ? options.forceServerObjectId
      : coll.s.db.options.forceServerObjectId;

  // no need to modify the docs if server sets the ObjectId
  if (forceServerObjectId === true) {
    return docs;
  }

  return docs.map(doc => {
    if (forceServerObjectId !== true && doc._id == null) {
      doc._id = coll.s.pkFactory.createPk();
    }

    return doc;
  });
}
1267246
function setModified(modified) {
        _modified = modified;
        if (_modified) {
            try {
                $(exports).triggerHandler('modified');
            } catch (err) {
                console.error(err);
            }
        }
    }
366982
function update() {
		$pkey=['_id'=>$this->document['_id']];
		if (isset($this->trigger['beforeupdate']) &&
			\Base::instance()->call($this->trigger['beforeupdate'],
				[$this,$pkey])===FALSE)
			return $this->document;
		$upsert=['upsert'=>TRUE];
		if ($this->legacy)
			$this->collection->update($pkey,$this->document,$upsert);
		else
			$this->collection->replaceone($pkey,$this->document,$upsert);
		if (isset($this->trigger['afterupdate']))
			\Base::instance()->call($this->trigger['afterupdate'],
				[$this,$pkey]);
		return $this->document;
	}
1038559
def _modify(self, **patch):
        """"""
        if 'state' in patch:
            if patch['state'] not in ['user-up', 'user-down', 'unchecked', 'fqdn-up']:
                msg = "The node resource does not support a modify with the " \
                      "value of the 'state' attribute as %s. The accepted " \
                      "values are 'user-up', 'user-down', 'unchecked', or 'fqdn-up'" \
                      % patch['state']
                raise NodeStateModifyUnsupported(msg)
        if 'session' in patch:
            if patch['session'] not in ['user-enabled', 'user-disabled']:
                msg = "The node resource does not support a modify with the " \
                      "value of the 'session' attribute as %s. " \
                      "The accepted values are 'user-enabled' or " \
                      "'user-disabled'" % patch['session']
                raise NodeStateModifyUnsupported(msg)
        super(Node, self)._modify(**patch)
1348284
function upsert(db, docId, diffFun) {
  return new Promise(function (fulfill, reject) {
    db.get(docId, function (err, doc) {
      if (err) {
        /* istanbul ignore next */
        if (err.status !== 404) {
          return reject(err);
        }
        doc = {};
      }

      // the user might change the _rev, so save it for posterity
      var docRev = doc._rev;
      var newDoc = diffFun(doc);

      if (!newDoc) {
        // if the diffFun returns falsy, we short-circuit as
        // an optimization
        return fulfill({updated: false, rev: docRev});
      }

      // users aren't allowed to modify these values,
      // so reset them here
      newDoc._id = docId;
      newDoc._rev = docRev;
      fulfill(tryAndPut(db, newDoc, diffFun));
    });
  });
}
200576
function modify(query, res) {
	// jshint ignore:line
	//	console.log(arguments);

	/* If source is a primitive value then return it */
	if (
		typeof res === 'undefined' ||
		typeof res === 'number' ||
		typeof res === 'string' ||
		typeof res === 'boolean'
	) {
		return res;
	}

	var modifier = query.modifier || alasql.options.modifier;
	var columns = query.columns;
	if (typeof columns === 'undefined' || columns.length == 0) {
		// Try to create columns
		if (res.length > 0) {
			var allcol = {};
			for (var i = Math.min(res.length, alasql.options.columnlookup || 10) - 1; 0 <= i; i--) {
				for (var key in res[i]) {
					allcol[key] = true;
				}
			}

			columns = Object.keys(allcol).map(function(columnid) {
				return {columnid: columnid};
			});
		} else {
			// Cannot recognize columns
			columns = [];
		}
	}

	//	console.log(columns);

	if (modifier === 'VALUE') {
		//		console.log(222,res);
		if (res.length > 0) {
			var key;
			if (columns && columns.length > 0) {
				key = columns[0].columnid;
			} else {
				key = Object.keys(res[0])[0];
			}
			res = res[0][key];
		} else {
			res = undefined;
		}
	} else if (modifier === 'ROW') {
		if (res.length > 0) {
			var key;
			var a = [];
			for (var key in res[0]) {
				a.push(res[0][key]);
			}
			res = a;
		} else {
			res = undefined;
		}
	} else if (modifier === 'COLUMN') {
		var ar = [];
		if (res.length > 0) {
			var key;
			if (columns && columns.length > 0) {
				key = columns[0].columnid;
			} else {
				key = Object.keys(res[0])[0];
			}

			for (var i = 0, ilen = res.length; i < ilen; i++) {
				ar.push(res[i][key]);
			}
		}
		res = ar;
	} else if (modifier === 'MATRIX') {
		// Returns square matrix of rows
		var ar = [];
		for (var i = 0; i < res.length; i++) {
			var a = [];
			var r = res[i];
			for (var j = 0; j < columns.length; j++) {
				a.push(r[columns[j].columnid]);
			}
			ar.push(a);
		}
		res = ar;
	} else if (modifier === 'INDEX') {
		var ar = {};
		var key, val;
		if (columns && columns.length > 0) {
			key = columns[0].columnid;
			val = columns[1].columnid;
		} else {
			var okeys = Object.keys(res[0]);
			key = okeys[0];
			val = okeys[1];
		}
		for (var i = 0, ilen = res.length; i < ilen; i++) {
			ar[res[i][key]] = res[i][val];
		}
		res = ar;
		//		res = arrayOfArrays(res);
	} else if (modifier === 'RECORDSET') {
		res = new alasql.Recordset({columns: columns, data: res});
		//		res = arrayOfArrays(res);
	} else if (modifier === 'TEXTSTRING') {
		var key;
		if (columns && columns.length > 0) {
			key = columns[0].columnid;
		} else {
			key = Object.keys(res[0])[0];
		}

		for (var i = 0, ilen = res.length; i < ilen; i++) {
			res[i] = res[i][key];
		}
		res = res.join('\n');
		//		res = arrayOfArrays(res);
	}
	return res;
}
444076
def modify_init(uid, data_dic):
        '''
        
        '''
        postinfo = MPost.get_by_uid(uid)
        entry = TabPost.update(
            time_update=tools.timestamp(),
            date=datetime.now(),
            kind=data_dic['kind'] if 'kind' in data_dic else postinfo.kind,
            keywords=data_dic['keywords'] if 'keywords' in data_dic else postinfo.keywords,
        ).where(TabPost.uid == uid)
        entry.execute()
        return uid
50223
def before_insert(mapper, conn, target):
        """"""
        from sqlalchemy import text

        if not target.id:
            sql = text('SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did')

            target.id, = conn.execute(sql, did=target.d_vid).fetchone()

            if not target.id:
                target.id = 1

        if target.contents and isinstance(target.contents, six.text_type):
            target.contents = target.contents.encode('utf-8')

        File.before_update(mapper, conn, target)
911135
def replace(self, resource, id_, document):
        """"""
        args = self._es_args(resource, refresh=True)
        document.pop('_id', None)
        document.pop('_type', None)
        self._update_parent_args(resource, args, document)
        return self.elastic(resource).index(body=document, id=id_, **args)
1359189
private function mergePartial(array &$document, array $updatedDocument, $prefix = null)
    {
        foreach ($updatedDocument as $key => $newValue) {
            // if original data is embedded document and value also - then merge
            if (is_array($newValue) && isset($document[$key]) && $this->isEmbeddedDocument($document[$key])) {
                $this->mergePartial($document[$key], $newValue, $prefix . $key . '.');
            } // in other cases just set new value
            else {
                $document[$key] = $newValue;
                $this->modifiedFields[] = $prefix . $key;
            }
        }
    }
1181484
def modification_changed(self, state=None, index=None, editor_id=None):
        
        if editor_id is not None:
            for index, _finfo in enumerate(self.data):
                if id(_finfo.editor) == editor_id:
                    break
        # This must be done before refreshing save/save all actions:
        # (otherwise Save/Save all actions will always be enabled)
        self.opened_files_list_changed.emit()
        # --
        if index is None:
            index = self.get_stack_index()
        if index == -1:
            return
        finfo = self.data[index]
        if state is None:
            state = finfo.editor.document().isModified() or finfo.newly_created
        self.set_stack_title(index, state)
        # Toggle save/save all actions state
        self.save_action.setEnabled(state)
        self.refresh_save_all_action.emit()
        # Refreshing eol mode
        eol_chars = finfo.editor.get_line_separator()
        self.refresh_eol_chars(eol_chars)
        self.stack_history.refresh()
1153451
def modifie_options(self, field_option, value):
        """"""
        options = dict(self["options"] or {}, **{field_option: value})
        self.modifications["options"] = options
1169121
function doUpdate (root, entry, cb) {
    entry = utils.updateEntry(root, entry, ['dateDetected'])

    // console.log('overwriting', root, 'with', entryJSON, 'resulting in', entry.toJSON())
    put(entry, cb)
  }
685820
def __find_and_modify(self, filter, projection, sort, upsert=None,
                          return_document=ReturnDocument.BEFORE, **kwargs):
        """"""
        common.validate_is_mapping("filter", filter)
        if not isinstance(return_document, bool):
            raise ValueError("return_document must be "
                             "ReturnDocument.BEFORE or ReturnDocument.AFTER")
        collation = validate_collation_or_none(kwargs.pop('collation', None))
        cmd = SON([("findAndModify", self.__name),
                   ("query", filter),
                   ("new", return_document)])
        cmd.update(kwargs)
        if projection is not None:
            cmd["fields"] = helpers._fields_list_to_dict(projection,
                                                         "projection")
        if sort is not None:
            cmd["sort"] = helpers._index_document(sort)
        if upsert is not None:
            common.validate_boolean("upsert", upsert)
            cmd["upsert"] = upsert
        with self._socket_for_writes() as sock_info:
            if sock_info.max_wire_version >= 4 and 'writeConcern' not in cmd:
                wc_doc = self.write_concern.document
                if wc_doc:
                    cmd['writeConcern'] = wc_doc
            out = self._command(sock_info, cmd,
                                read_preference=ReadPreference.PRIMARY,
                                allowable_errors=[_NO_OBJ_ERROR],
                                collation=collation)
            _check_write_command_response([(0, out)])
        return out.get("value")
690234
function _onDocumentSaved(event, doc) {
        if (!isActive() || !_server) {
            return;
        }

        var absolutePath            = doc.file.fullPath,
            liveDocument            = absolutePath && _server.get(absolutePath),
            liveEditingEnabled      = liveDocument && liveDocument.isLiveEditingEnabled  && liveDocument.isLiveEditingEnabled();

        // Skip reload if the saved document has live editing enabled
        if (liveEditingEnabled) {
            return;
        }

        // reload the page if the given document is a JS file related
        // to the current live document.
        if (_liveDocument.isRelated(absolutePath)) {
            if (doc.getLanguage().getId() === "javascript") {
                _setStatus(STATUS_RELOADING);
                _protocol.reload();
            }
        }
    }
340193
def apply_update(self, doc, update_spec):
        """"""

        # Helper to cast a key for a list or dict, or raise ValueError
        def _convert_or_raise(container, key):
            if isinstance(container, dict):
                return key
            elif isinstance(container, list):
                return int(key)
            else:
                raise ValueError

        # Helper to retrieve (and/or create)
        # a dot-separated path within a document.
        def _retrieve_path(container, path, create=False):
            looking_at = container
            for part in path:
                if isinstance(looking_at, dict):
                    if create and part not in looking_at:
                        looking_at[part] = {}
                    looking_at = looking_at[part]
                elif isinstance(looking_at, list):
                    index = int(part)
                    # Do we need to create additional space in the array?
                    if create and len(looking_at) <= index:
                        # Fill buckets with None up to the index we need.
                        looking_at.extend([None] * (index - len(looking_at)))
                        # Bucket we need gets the empty dictionary.
                        looking_at.append({})
                    looking_at = looking_at[index]
                else:
                    raise ValueError
            return looking_at

        def _set_field(doc, to_set, value):
            if "." in to_set:
                path = to_set.split(".")
                where = _retrieve_path(doc, path[:-1], create=True)
                index = _convert_or_raise(where, path[-1])
                wl = len(where)
                if isinstance(where, list) and index >= wl:
                    where.extend([None] * (index + 1 - wl))
                where[index] = value
            else:
                doc[to_set] = value

        def _unset_field(doc, to_unset):
            try:
                if "." in to_unset:
                    path = to_unset.split(".")
                    where = _retrieve_path(doc, path[:-1])
                    index_or_key = _convert_or_raise(where, path[-1])
                    if isinstance(where, list):
                        # Unset an array element sets it to null.
                        where[index_or_key] = None
                    else:
                        # Unset field removes it entirely.
                        del where[index_or_key]
                else:
                    del doc[to_unset]
            except (KeyError, IndexError, ValueError):
                source_version = get_mininum_mongodb_version()
                if source_version is None or source_version.at_least(2, 6):
                    raise
                # Ignore unset errors since MongoDB 2.4 records invalid
                # $unsets in the oplog.
                LOG.warning(
                    "Could not unset field %r from document %r. "
                    "This may be normal when replicating from "
                    "MongoDB 2.4 or the destination could be out of "
                    "sync." % (to_unset, doc)
                )

        # wholesale document replacement
        if "$set" not in update_spec and "$unset" not in update_spec:
            # update spec contains the new document in its entirety
            return update_spec
        else:
            try:
                # $set
                for to_set in update_spec.get("$set", []):
                    value = update_spec["$set"][to_set]
                    _set_field(doc, to_set, value)

                # $unset
                for to_unset in update_spec.get("$unset", []):
                    _unset_field(doc, to_unset)

            except (KeyError, ValueError, AttributeError, IndexError):
                exc_t, exc_v, exc_tb = sys.exc_info()
                msg = "Cannot apply update %r to %r" % (update_spec, doc)
                raise UpdateDoesNotApply(msg).with_traceback(exc_tb)
            return doc
357841
def insert(collection_name, docs, check_keys,
           safe, last_error_args, continue_on_error, opts, ctx=None):
    """"""
    if ctx:
        return _insert_compressed(
            collection_name, docs, check_keys, continue_on_error, opts, ctx)
    return _insert_uncompressed(collection_name, docs, check_keys, safe,
                                last_error_args, continue_on_error, opts)