a few functions which should allow the document to be treated transactionally.
559083
function transaction( $action )
    {
        switch ( $action )
        {
        case 'start':
            // store all the data away into the checkpoint variable
            $data = get_object_vars( $this );
            $this->checkpoint = $data;
            unset( $data );
            break;
        case 'commit':
            if ( is_array( $this->checkpoint ) && isset( $this->checkpoint['checkpoint'] ) )
            {
                $tmp = $this->checkpoint['checkpoint'];
                $this->checkpoint = $tmp;
                unset( $tmp );
            }
            else
            {
                $this->checkpoint = '';
            }
            break;
        case 'rewind':
            // do not destroy the current checkpoint, but move us back to the state then, so that we can try again
            if ( is_array( $this->checkpoint ) )
            {
                // can only abort if were inside a checkpoint
                $tmp = $this->checkpoint;
                foreach ( $tmp as $k => $v )
                {
                    if ( $k != 'checkpoint' )
                    {
                        $this->$k = $v;
                    }
                }
                unset($tmp);
            }
            break;
        case 'abort':
            if ( is_array( $this->checkpoint ) )
            {
                // can only abort if were inside a checkpoint
                $tmp = $this->checkpoint;
                foreach ( $tmp as $k => $v )
                {
                    $this->$k = $v;
                }
                unset($tmp);
            }
            break;
        }

    }
12803
public void updateDocumentInfo(DocumentReference docref,
            String documentType, String ownerType, Long ownerId, Integer statusCode, String statusMessage) throws DataAccessException {
        TransactionWrapper transaction=null;
        try {
            transaction = startTransaction();
            engineImpl.updateDocumentInfo(docref, documentType, ownerType, ownerId, statusCode, statusMessage);
        } catch (DataAccessException e) {
            if (canRetryTransaction(e)) {
                transaction = (TransactionWrapper)initTransactionRetry(transaction);
                ((ProcessExecutor)getTransactionRetrier()).updateDocumentInfo(docref, documentType, ownerType, ownerId, statusCode, statusMessage);
            }
            else
                throw e;
        } finally {
            stopTransaction(transaction);
        }
    }
182285
def transaction_type(self, value):
        """"""
        if value is not None:
            if value not in self.ALLOWED_TRANSACTION_TYPES:
                raise AttributeError('%s transaction_type element must be one of %s not %s' % (
                    self.__class__.__name__, ','.join(self.ALLOWED_TRANSACTION_TYPES), value,))
        self._transaction_type = value
254898
def transaction_manager(fn):
    
    @wraps(fn)
    def transaction_manager_decorator(*args, **kwargs):
        with transaction.manager:
            return fn(*args, **kwargs)

    return transaction_manager_decorator
258156
function(options, callback) {
    // var self = this

    if (typeof options === 'function') {
      callback = options
      options = {}
    }

    if (options.transaction) {
      return callback(options.transaction)
    } else {
      return this.connection
        .transaction(function(transaction) {
          options.transaction = transaction
          return callback(transaction)
        })
        .then(function(result) {
          debug('commit')
          return result
        })
        .catch(function(e) {
          // TODO: do something with e.g. 'afterSave' rollback message!?!
          debug('rollback')
          throw e
        })
    }
  }
1245932
def do_transaction(self, function, *args, **kwargs):
        """"""
        for wait_in_seconds in self.backoff_generator():
            try:
                with self.config.db_transaction() as trans:
                    function(trans, *args, **kwargs)
                    trans.commit()
                    break
            except self.config.db_transaction.operational_exceptions:
                pass
            print(('failure in transaction - retry in %s seconds' %
                   wait_in_seconds))
            self.responsive_sleep(wait_in_seconds,
                                  "waiting for retry after failure in "
                                  "transaction")
724355
function (invoiceitem, cb) {

		Invoiceitem.findOrCreate(invoiceitem.id, invoiceitem)
	    .exec(function (err, foundInvoiceitem){
	      if (err) return cb(err);
	      if (foundInvoiceitem.lastStripeEvent > invoiceitem.lastStripeEvent) return cb(null, foundInvoiceitem);
	      if (foundInvoiceitem.lastStripeEvent == invoiceitem.lastStripeEvent) return Invoiceitem.afterStripeInvoiceitemUpdated(foundInvoiceitem, function(err, invoiceitem){ return cb(err, invoiceitem)});
	      Invoiceitem.update(foundInvoiceitem.id, invoiceitem)
	      .exec(function(err, updatedInvoiceitem){
	      	if (err) return cb(err);
	      	if (!updatedInvoiceitem) return cb(null,null);
	      	Invoiceitem.afterStripeInvoiceitemUpdated(updatedInvoiceitem[0], function(err, invoiceitem){
	      		cb(err, invoiceitem);
	      	});
	      });
	    });
	}
104945
function DocAction(docStr) {
    return function (target, propertyKey, descriptor) {
        let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
        m.docString = docStr;
    };
}
285567
function(transaction, cb){
		contract(arguments)
			.params('array', 'function')
			.end()
		;
		
		// Execute transaction
		async.series(transaction,function(err){
			cb(err instanceof Error? err : undefined);
		});
	}
936971
function handleExtractToVariable() {
        var editor = EditorManager.getActiveEditor();

        if (editor.getSelections().length > 1) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_MULTICURSORS);
            return;
        }

        initializeSession(editor);

        var selection = editor.getSelection(),
            doc       = editor.document,
            retObj    = RefactoringUtils.normalizeText(editor.getSelectedText(), editor.indexFromPos(selection.start),
                        editor.indexFromPos(selection.end), true),
            text      = retObj.text,
            start     = retObj.start,
            end       = retObj.end,
            ast,
            scopes,
            expns,
            inlineMenu;

        function callExtractToVariable(startPos, endPos, value) {
            RefactoringUtils.getScopeData(session, editor.posFromIndex(startPos))
                .done(function(expnscope) {
                    scopes = RefactoringUtils.getAllScopes(ast, expnscope, doc.getText());
                    extractToVariable(ast, startPos, endPos, value, scopes);
                }).fail(function() {
                    editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
                });
        }

        RefactoringUtils.getScopeData(session, editor.posFromIndex(start)).done(function(scope) {
            ast = RefactoringUtils.getAST(doc.getText());
            scopes = RefactoringUtils.getAllScopes(ast, scope, doc.getText());

            if (editor.hasSelection()) {
                extractToVariable(ast, start, end, text, scopes);
            } else {
                expns = getExpressions(ast, start, end);

                expns.forEach(function(expn, index) {
                    expn.value = doc.getText().substr(expn.start, expn.end - expn.start);
                });

                // Sort expressions by their length
                expns.sort(function(a, b) {
                    return a.value.length - b.value.length;
                });

                if (!expns || !expns.length) {
                    session.editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_NOT_VALID);
                    return;
                }

                // Filter expns based on length of first surrounding expression
                var firstExpnLength = RefactoringUtils.numLines(expns[0].value);
                expns = expns.filter(function(expn) {
                    return RefactoringUtils.numLines(expn.value) === firstExpnLength;
                });

                // Add name for the expression based on its value
                expns.forEach(function(expn, index) {
                    // If expn name is multi-line, display only first line
                    if (RefactoringUtils.numLines(expn.value) > 1) {
                        expn.name = expn.value.substr(0, expn.value.indexOf("\n")) + "...";
                    } else {
                        expn.name = expn.value;
                    }
                });

                // If only one surround expression, extract
                if (expns.length === 1) {
                    callExtractToVariable(expns[0].start, expns[0].end, expns[0].value);
                    return;
                }

                expns.forEach(function(expn, index) {
                    expn.id = index;
                });

                // UI for extract to variable
                inlineMenu = new InlineMenu(session.editor, Strings.EXTRACTTO_VARIABLE_SELECT_EXPRESSION);

                inlineMenu.onHover(function (expnId) {
                    // Remove the scroll Handlers If already Attached.
                    editor.off("scroll.inlinemenu");
                    // Add a scroll handler If Selection Range is not View.
                    // This is Added for a Bug, where Menu used not to open for the first Time
                    if(!editor.isLineVisible(editor.posFromIndex(expns[expnId].end).line)) {
                        editor.on("scroll.inlinemenu", function() {
                            // Remove the Handlers so that If scroll event is triggerd again by any other operation
                            // Menu should not be reopened.
                            // Menu Should be reopened only if Scroll event is triggered by onHover.
                            editor.off("scroll.inlinemenu");
                            inlineMenu.openRemovedMenu();
                        });
                    }
                    editor.setSelection(editor.posFromIndex(expns[expnId].start), editor.posFromIndex(expns[expnId].end));
                });

                inlineMenu.open(expns);

                inlineMenu.onSelect(function (expnId) {
                    callExtractToVariable(expns[expnId].start, expns[expnId].end, expns[expnId].value);
                    inlineMenu.close();
                });

                inlineMenu.onClose(function () {
                    inlineMenu.close();
                });
            }
        }).fail(function() {
            editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
        });
    }
734412
private function setSenderDocument()
    {
        $this->_paymentRequest->setSender()->setDocument()->withParameters(
            $this->_data['sender_document']['type'],
            $this->_data['sender_document']['number']
        );
    }
778660
function updateDocument(existingDoc, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback) {
    if (!f_ShouldUpdate) {
        f_ShouldUpdate = always;
    }

    if (!f_Merge) {
        f_Merge = useNewVersion;
    }

    // If we never grabbed the existing document from the DB, fetch it and try again.
    if (!existingDoc) {
        return db.get(id, function (err, r) {
            // If the fetch came back with nothing, attempt to do a fresh insert unless the user
            // doesn't want documents to be created.
            if (err && (err.error === "not_found")) {
                if (!shouldCreate)
                    // Don't create a document where one didn't exist, if the user so desires.
                    return callback(null, null);

                return db.insert(newDoc, id, function (err, r) {
                    // If someone beat us here, we should retry this whole operation.
                    if (err && err.error === "conflict")
                        return updateDocument(null, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);

                    // If anything else happened, we should bail.
                    if (err)
                        return callback("Could not fetch existing document: " + err.toString());

                    // The insert worked.  We're done.
                    return callback(null, extend({}, newDoc, {_rev: r.rev}));
                });
            }

            // If the fetch came back with any other error, bail.
            if (err)
                return callback("Could not fetch existing document: " + err.toString());

            // We got the document.  Let's try the update again.
            return updateDocument(r, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);
        });
    }

    if (!f_ShouldUpdate(existingDoc, newDoc)) {
        return callback(null, existingDoc);
    }

    // Before merging, record that we want to undelete a document that has been deleted.
    var mergedDoc = f_Merge(omit(existingDoc, "_deleted"), newDoc);
    if (!mergedDoc || typeof mergedDoc !== "object" || mergedDoc instanceof Error) {
        // Allow a user defined merge algorithm to say ``sorry...can't merge'' by returning a non-object or Error.
        // Bubble this error, so that the user can then test for it in their callback.
        return callback(mergedDoc);
    }

    // It's essential that we specify a revision or this will never terminate.
    // It's probably not a good idea to trust a user-specified merge function to do this.
    mergedDoc = extend({}, mergedDoc, { _rev: existingDoc._rev });

    // The document exists, and is out of date.  We need to overwrite it.
    db.insert(
        mergedDoc,
        id,
        function (err, result) {
            // If someone beat us here, we need to try the whole thing again.
            if (err && err.error === "conflict")
                return updateDocument(null, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);

            // If anything else happened, bail.
            if (err)
                return callback("Could not update the document to the proposed version: " + err.toString());

            // Update the new document's _rev
            mergedDoc._rev = result.rev;

            // The replacement worked.  We're done.  Finally!
            return callback(null, mergedDoc);
        }
    );
}
17856
def clean(self):
        '''
        
        '''

        if self.staffMember and self.staffMember.userAccount and \
        self.user and not self.staffMember.userAccount == self.user:
            raise ValidationError(_('Transaction party user does not match staff member user.'))

        if self.location and (self.user or self.staffMember):
            raise ValidationError(_('Transaction party may not be both a Location and a User or StaffMember.'))
1030215
function commitTransactional(params, callback) {
    if (transactionsManager.length)
      return transactionOperation.call(transactionsManager, 'transaction',
        params, callback);

    callback = callback || noop;

    var operations = params.operations;

    var promises = [];

    function checkId(operation, param) {
      if (param instanceof MediaObject && param.id === undefined) {
        var index = findIndex(operations, function (element) {
          return operation != element && element.params.object === param;
        });

        // MediaObject dependency is created in this transaction,
        // set a new reference ID
        if (index >= 0)
          return 'newref:' + index;

        // MediaObject dependency is created outside this transaction,
        // wait until it's ready
        promises.push(param);
      }

      return param
    }

    // Fix references to uninitialized MediaObjects
    operations.forEach(function (operation) {
      var params = operation.params;

      switch (operation.method) {
      case 'create':
        var constructorParams = params.constructorParams;
        for (var key in constructorParams)
          constructorParams[key] = checkId(operation, constructorParams[
            key]);
        break;

      default:
        params.object = checkId(operation, params.object);

        var operationParams = params.operationParams;
        for (var key in operationParams)
          operationParams[key] = checkId(operation, operationParams[key]);
      };
    });

    function callback2(error, result) {
      if (error) return callback(error);

      operations.forEach(operationResponse, result)

      callback(null, result);
    };

    Promise.all(promises).then(function () {
        operations.forEach(serializeOperation)

        encode('transaction', params, callback2);
      },
      callback);
  }
234644
function(cb) {
      //console.log('tx running for ' + scope);
      // me.not_ready_ = true;
      // transaction should be active now
      var tx = me.mu_tx_.getTx();
      me.r_no_++;
      req.setTx(tx, me.getLabel() + 'R' + me.r_no_);
    }
1188541
def valid_transaction_verbs
      {
        'set' => %w[Key Value],
        'cas' => %w[Key Value Index],
        'lock' => %w[Key Value Session],
        'unlock' => %w[Key Value Session],
        'get' => %w[Key],
        'get-tree' => %w[Key],
        'check-index' => %w[Key Index],
        'check-session' => %w[Key Session],
        'delete' => %w[Key],
        'delete-tree' => %w[Key],
        'delete-cas' => %w[Key Index]
      }
    end
37808
function(doc) {
      var that = this;
      doc = that._in_map(doc);

      return this._init.then(function() {
        return that.isAdmissible(doc);
      }).then(function(admissible) {
        if (!admissible) {
          throw new Error('Document not admissible');
        }

        doc = that.clean(doc);

        if (that._index) {
          delete doc[that._index];
        }

        return that.getNextIndex();
      }).then(function(max) {
        if (that._index && typeof max === 'number') {
          doc[that._index] = max;
        }

        return that._dbApi.create(doc).then(function(doc) {
          if (!doc) {
            throw new Error('Document not created');
          }

          return doc;
        });
      });
    }