Copy prepared new contexts from temp table to context table,
we do this in db specific way for perf reasons only.
@static
488409
protected static function merge_context_temp_table() {
        global $DB;

        /* MDL-11347:
         *  - mysql does not allow to use FROM in UPDATE statements
         *  - using two tables after UPDATE works in mysql, but might give unexpected
         *    results in pg 8 (depends on configuration)
         *  - using table alias in UPDATE does not work in pg < 8.2
         *
         * Different code for each database - mostly for performance reasons
         */

        $dbfamily = $DB->get_dbfamily();
        if ($dbfamily == 'mysql') {
            $updatesql = "UPDATE {context} ct, {context_temp} temp
                             SET ct.path     = temp.path,
                                 ct.depth    = temp.depth,
                                 ct.locked   = temp.locked
                           WHERE ct.id = temp.id";
        } else if ($dbfamily == 'oracle') {
            $updatesql = "UPDATE {context} ct
                             SET (ct.path, ct.depth, ct.locked) =
                                 (SELECT temp.path, temp.depth, temp.locked
                                    FROM {context_temp} temp
                                   WHERE temp.id=ct.id)
                           WHERE EXISTS (SELECT 'x'
                                           FROM {context_temp} temp
                                           WHERE temp.id = ct.id)";
        } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
            $updatesql = "UPDATE {context}
                             SET path     = temp.path,
                                 depth    = temp.depth,
                                 locked   = temp.locked
                            FROM {context_temp} temp
                           WHERE temp.id={context}.id";
        } else {
            // sqlite and others
            $updatesql = "UPDATE {context}
                             SET path     = (SELECT path FROM {context_temp} WHERE id = {context}.id),
                                 depth    = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
                                 locked   = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
                             WHERE id IN (SELECT id FROM {context_temp})";
        }

        $DB->execute($updatesql);
    }
214919
protected function _beforeInsert(DatabaseContext $context)
    {
        $mixer = $this->getMixer();
        $table = $mixer instanceof DatabaseRowInterface ?  $mixer->getTable() : $mixer;

        if($this->hasProperty('created_by') && empty($this->created_by)) {
            $this->created_by  = (int) $this->getObject('user')->getId();
        }

        if($this->hasProperty('created_on') && (empty($this->created_on) || $this->created_on == $table->getDefault('created_on'))) {
            $this->created_on  = gmdate('Y-m-d H:i:s');
        }
    }
1222524
def add_to_context(self, name, **attrs):
        
        context = self.get_context(name=name)
        attrs_ = context['context']
        attrs_.update(**attrs)
1148686
public function modifyDatabase()
    {
        foreach ($this->getDatabase()->getTables() as $table) {
            if (!$table->hasPrimaryKey()) {
                $b = clone $this;
                $table->addBehavior($b);
            }
        }
    }
747617
def new_context(environment, template_name, blocks, vars=None,
                shared=None, globals=None, locals=None):
    """"""
    if vars is None:
        vars = {}
    if shared:
        parent = vars
    else:
        parent = dict(globals or (), **vars)
    if locals:
        # if the parent is shared a copy should be created because
        # we don't want to modify the dict passed
        if shared:
            parent = dict(parent)
        for key, value in iteritems(locals):
            if value is not missing:
                parent[key] = value
    return environment.context_class(environment, parent, template_name,
                                     blocks)
601302
def copy(self, inheritance=False):
        # type: (bool) -> FactoryContext
        
        # Create a new factory context and duplicate its values
        new_context = FactoryContext()
        for field in self.__slots__:
            if not field.startswith("_"):
                setattr(
                    new_context, field, self._deepcopy(getattr(self, field))
                )

        if inheritance:
            # Store configuration as inherited one
            new_context.__inherited_configuration = self.__handlers.copy()
            new_context.__handlers = {}

        # Remove instances in any case
        new_context.__instances.clear()
        new_context.is_singleton_active = False
        return new_context
1108696
def copy_table_structure(self, source, destination, table):
        
        self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format(destination, wrap(table), source))
617390
def copy(defaults={}, context={})
      self.class.find(rpc_execute('copy', id, defaults, context), context: context)
    end
283327
function do_create_context(context) {
		var context = context || {};
		
		if(!context.replace) {
			context.replace = (function(chunk, context, bodies, params) {
					return chunk.tap(function(data) {
						return (params.from && params.to && (data === params.from) ) ? params.to : data;
					}).render(bodies.block, context).untap();
				});
		}
		
		if(!context.toFixed) {
			context.toFixed = (function(chunk, context, bodies, params) {
					return chunk.tap(function(data) {
						return parseFloat(data).toFixed(params.x || 0);
					}).render(bodies.block, context).untap();
				}); // end of context
		}
		
		return context;
	}
659942
public function saveContext($context)
    {

        $time = time();
        $now = date("{$this->dateFormat} {$this->timeFormat}", $time);
        $settingsValue = serialize($context->getSettings());
        $id = $context->getRecordId();
        $consumer_pk = $context->getConsumer()->getRecordId();
        if (empty($id)) {
            $sql = sprintf("INSERT INTO {$this->dbTableNamePrefix}" . DataConnector::CONTEXT_TABLE_NAME . ' (consumer_pk, lti_context_id, ' .
                           'type, settings, created, updated) ' .
                           'VALUES (%d, %s, %s, %s, %s, %s)',
               $consumer_pk, DataConnector::quoted($context->ltiContextId),
               DataConnector::quoted($context->type),
               DataConnector::quoted($settingsValue),
               DataConnector::quoted($now), DataConnector::quoted($now));
        } else {
            $sql = sprintf("UPDATE {$this->dbTableNamePrefix}" . DataConnector::CONTEXT_TABLE_NAME . ' SET ' .
                           'lti_context_id = %s, type = %s, settings = %s, '.
                           'updated = %s' .
                           'WHERE (consumer_pk = %d) AND (context_pk = %d)',
               DataConnector::quoted($context->ltiContextId),
               DataConnector::quoted($context->type),
               DataConnector::quoted($settingsValue),
               DataConnector::quoted($now), $consumer_pk, $id);
        }
        $ok = mysql_query($sql);
        if ($ok) {
            if (empty($id)) {
                $context->setRecordId(mysql_insert_id());
                $context->created = $time;
            }
            $context->updated = $time;
        }

        return $ok;

    }
740527
protected function prepareProcessContext()
    {
        if (null !== $this->context) {
            $this->context->setData($this->data);
            $this->context->setProcessor($this);
            return;
        }

        $class = $this->processContextClass;

        $this->context = new $class($this->data, $this->settings, $this);

    }
238148
public static XIncludeContext newContext(final XIncludeContext contextToCopy)
    {
        final XIncludeContext newContext = new XIncludeContext(contextToCopy.configuration);
        newContext.currentBaseURI = contextToCopy.currentBaseURI;
        newContext.basesURIDeque.addAll(contextToCopy.basesURIDeque);
        newContext.language = contextToCopy.language;
        newContext.xincludeDeque.addAll(contextToCopy.xincludeDeque);
        newContext.docType = DocType.copy(contextToCopy.docType);
        return newContext;
    }
767076
public ELContext setELContext(ELContext context) {
        ELContext prev = elContext;
        elContext = new StandardELContext(context);
        return prev;
    }
1162843
def copy_table(from_table, name):
    
    metadata = from_table.metadata

    if name in metadata.tables:
        return metadata.tables[name]

    schema = metadata.schema

    columns = [
        copy_column(column, schema)
        for column in from_table.columns
        if should_copy(column)
    ]

    return Table(
        name,
        metadata,
        schema=schema,
        comment=from_table.comment,
        *columns,
        **from_table.kwargs,
    )
866570
function _initStorage(options) {
    var self = this;
    var dbInfo = {
        db: null
    };

    if (options) {
        for (var i in options) {
            dbInfo[i] = options[i];
        }
    }

    // Get the current context of the database;
    var dbContext = dbContexts[dbInfo.name];

    // ...or create a new context.
    if (!dbContext) {
        dbContext = createDbContext();
        // Register the new context in the global container.
        dbContexts[dbInfo.name] = dbContext;
    }

    // Register itself as a running localForage in the current context.
    dbContext.forages.push(self);

    // Replace the default `ready()` function with the specialized one.
    if (!self._initReady) {
        self._initReady = self.ready;
        self.ready = _fullyReady;
    }

    // Create an array of initialization states of the related localForages.
    var initPromises = [];

    function ignoreErrors() {
        // Don't handle errors here,
        // just makes sure related localForages aren't pending.
        return Promise$1.resolve();
    }

    for (var j = 0; j < dbContext.forages.length; j++) {
        var forage = dbContext.forages[j];
        if (forage !== self) {
            // Don't wait for itself...
            initPromises.push(forage._initReady()["catch"](ignoreErrors));
        }
    }

    // Take a snapshot of the related localForages.
    var forages = dbContext.forages.slice(0);

    // Initialize the connection process only when
    // all the related localForages aren't pending.
    return Promise$1.all(initPromises).then(function () {
        dbInfo.db = dbContext.db;
        // Get the connection or open a new one without upgrade.
        return _getOriginalConnection(dbInfo);
    }).then(function (db) {
        dbInfo.db = db;
        if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
        }
        return db;
    }).then(function (db) {
        dbInfo.db = dbContext.db = db;
        self._dbInfo = dbInfo;
        // Share the final connection amongst related localForages.
        for (var k = 0; k < forages.length; k++) {
            var forage = forages[k];
            if (forage !== self) {
                // Self is already up-to-date.
                forage._dbInfo.db = dbInfo.db;
                forage._dbInfo.version = dbInfo.version;
            }
        }
    });
}
177198
function _cloneActiveContext() {
    var child = {};
    child['@base'] = this['@base'];
    child.mappings = _clone(this.mappings);
    child.clone = this.clone;
    child.inverse = null;
    child.getInverse = this.getInverse;
    if('@language' in this) {
      child['@language'] = this['@language'];
    }
    if('@vocab' in this) {
      child['@vocab'] = this['@vocab'];
    }
    return child;
  }
630080
def build_row_contexts
      rows = @data.size
      row_contexts = [:default] * rows
      offset = 0
      @contexts.each do |ctx|
        if ctx == :default
          break
        end
        size = ctx[:rows]
        row_contexts[offset...(size + offset)] = [ctx[:id]] * size
        offset += size
      end
      @contexts.reverse_each do |ctx|
        if ctx == :default
          break
        end
        size = ctx[:rows]
        row_contexts[(rows - size)...rows] = [ctx[:id]] * size
        rows -= size
      end
      row_contexts
    end