Initialize chain upon genesis or a migration
329364
def init_chain(self, genesis):
        """"""

        app_hash = ''
        height = 0

        known_chain = self.bigchaindb.get_latest_abci_chain()
        if known_chain is not None:
            chain_id = known_chain['chain_id']

            if known_chain['is_synced']:
                msg = f'Got invalid InitChain ABCI request ({genesis}) - ' + \
                      'the chain {chain_id} is already synced.'
                logger.error(msg)
                sys.exit(1)

            if chain_id != genesis.chain_id:
                validators = self.bigchaindb.get_validators()
                self.log_abci_migration_error(chain_id, validators)
                sys.exit(1)

            # set migration values for app hash and height
            block = self.bigchaindb.get_latest_block()
            app_hash = '' if block is None else block['app_hash']
            height = 0 if block is None else block['height'] + 1

        known_validators = self.bigchaindb.get_validators()
        validator_set = [vutils.decode_validator(v)
                         for v in genesis.validators]

        if known_validators and known_validators != validator_set:
            self.log_abci_migration_error(known_chain['chain_id'],
                                          known_validators)
            sys.exit(1)

        block = Block(app_hash=app_hash, height=height, transactions=[])
        self.bigchaindb.store_block(block._asdict())
        self.bigchaindb.store_validator_set(height + 1, validator_set)
        abci_chain_height = 0 if known_chain is None else known_chain['height']
        self.bigchaindb.store_abci_chain(abci_chain_height,
                                         genesis.chain_id, True)
        self.chain = {'height': abci_chain_height, 'is_synced': True,
                      'chain_id': genesis.chain_id}
        return ResponseInitChain()
584761
def _initialize(self, chain, length):
        """"""
        # If this db was loaded from the disk, it may not have its
        # tallied step methods' getfuncs yet.
        if self._getfunc is None:
            self._getfunc = self.db.model._funs_to_tally[self.name]
17835
def init(self, conn):
        
        base = self.read_scripts()[0]['fname']
        logging.info('Creating the initial schema from %s',  base)
        apply_sql_script(conn, os.path.join(self.upgrade_dir, base))
        self.install_versioning(conn)
894544
@Override
    public Response init(ChaincodeStub stub) {
        try {
            // Get the args from the transaction proposal
            List<String> args = stub.getParameters();
            if (args.size() != 2) {
                newErrorResponse("Incorrect arguments. Expecting a key and a value");
            }
            // Set up any variables or assets here by calling stub.putState()
            // We store the key and the value on the ledger
            stub.putStringState(args.get(0), args.get(1));
            return newSuccessResponse();
        } catch (Throwable e) {
            return newErrorResponse("Failed to create asset");
        }
    }
717903
function initialize(done) {
		debug('prepare');

		parser(options.index, options, function(err,  modules) {
			if(err) return done(err)

			debug('Parser return, now build the tree...');
			tree          = buildTree(options, modules, true);

			debug('Tree builded');

			// Extract from tree as a flatten list of packets to compile
			packets       = tree.getAllBundles(options);

			done(null);
		})

	}
36079
function initGlobal (args) {
    // do nothing if global data already defined
    if (global.__immutable_core_model__) {
        return
    }
    // create new global object
    var GLOBAL = global.__immutable_core_model__ = {
        // number of concurrent related queries to allow per query
        concurrency: 5,
        // default to use binary columns for ids
        defaultBinaryIds: true,
        // default character set
        defaultCharset: 'utf8',
        // default compression setting
        defaultCompression: true,
        // default elastic search client
        defaultElasticsearch: undefined,
        // default database engine
        defaultEngine: 'InnoDB',
        // default insert delayed option for myisam tables
        defaultInsertDelayed: false,
        // map of models indexed by name
        models: {},
    }
    // create validator as global object so that schemas will be shared
    // between all model classes
    GLOBAL.validator = new Ajv({
        allErrors: true,
        coerceTypes: 'array',
        removeAdditional: true,
        useDefaults: true,
        v5: true,
    })
}
742898
function init(config) {
    var deferred = Q.defer();

    connect(config.mongo.url, config.mongo.debug, config.mongo.mongos)
        .then(function () {

            IdxInfoModel = getModel({
                name: 'idx',
                fields: {
                    str: { type: String, index: { unique: true } },
                    name: String,
                    count: Number
                }
            });

            deferred.resolve(config);
        })
        .catch(function (err) {
            deferred.reject(err);
        });

    return deferred.promise;
}
346806
def run_on_changes(paths)
      if paths.any? { |path| path.match(%r{^db/migrate/(\d+).+\.rb}) } || reset?
        migrations = paths.map { |path| Migration.new(path) }
        migrate(migrations)
      elsif paths.any? { |path| path.match(%r{^db/seeds\.rb$}) }
        seed_only
      end
    end
916447
def check_chain_dir_exists(self, warn_migration=False):
        
        chain_path = os.path.join(self.DATA_DIR_PATH, 'Chains')

        if not os.path.exists(chain_path):
            try:
                os.makedirs(chain_path)
                logger.info("Created 'Chains' directory at %s " % chain_path)
            except Exception as e:
                logger.error("Could not create 'Chains' directory at %s %s" % (chain_path, e))

        warn_migration = False
        # Add a warning for migration purposes if we created a chain dir
        if warn_migration and ROOT_INSTALL_PATH != self.DATA_DIR_PATH:
            if os.path.exists(os.path.join(ROOT_INSTALL_PATH, 'Chains')):
                logger.warning("[MIGRATION] You are now using the blockchain data at %s, but it appears you have existing data at %s/Chains" % (
                    chain_path, ROOT_INSTALL_PATH))
                logger.warning(
                    "[MIGRATION] If you would like to use your existing data, please move any data at %s/Chains to %s " % (ROOT_INSTALL_PATH, chain_path))
                logger.warning("[MIGRATION] Or you can continue using your existing data by starting your script with the `--datadir=.` flag")
1027054
async def init():
    """"""
    global redis_conn  # pylint: disable=global-statement,invalid-name
    conn = await aioredis.create_connection(
        'redis://{}:{}'.format(
            SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'),
            SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('port', 56379)
        ),
        db=int(SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('db', 1))
    )
    redis_conn = aioredis.Redis(conn)
880786
def init_domain_ledger(self):
        
        if self.config.primaryStorage is None:
            genesis_txn_initiator = GenesisTxnInitiatorFromFile(
                self.genesis_dir, self.config.domainTransactionsFile)
            return Ledger(
                CompactMerkleTree(
                    hashStore=self.getHashStore('domain')),
                dataDir=self.dataLocation,
                fileName=self.config.domainTransactionsFile,
                ensureDurability=self.config.EnsureLedgerDurability,
                genesis_txn_initiator=genesis_txn_initiator)
        else:
            return initStorage(self.config.primaryStorage,
                               name=self.name + NODE_PRIMARY_STORAGE_SUFFIX,
                               dataDir=self.dataLocation,
                               config=self.config)
247697
function () {
                /*  determine parameters  */
                var params = $cs.params("migrate", arguments, {
                    comps:     { pos: "...", req: true    },
                    sync:      {             def: false   },
                    completed: {             def: $cs.nop }
                });

                /*  iterate over all components to migrate  */
                var n = 0;
                var parent = this;
                _cs.foreach(params.comps, function (comp) {
                    if (params.sync) {
                        /*  migrate synchronously  */
                        var state_old = comp.state();
                        comp.state({ state: "created", sync: true });
                        comp.detach();
                        comp.attach(parent);
                        comp.state(state_old);
                    }
                    else {
                        /*  migrate asynchronously  */
                        (function (comp, state_old) {
                            comp.state({ state: "created", sync: false, callback: function (/* state_new */) {
                                this.detach();
                                this.attach(parent);
                                this.state({ state: state_old, sync: false, callback: function (/* state_old */) {
                                    n--;
                                    if (n === 0)
                                        params.completed.call(null);
                                }});
                            }});
                        })(comp, comp.state());
                        n++;
                    }
                });
            }
689238
def create_migration(initial=False):
    """"""

    settings = DjangoSettings()
    if 'south' not in (name.lower() for name in settings.INSTALLED_APPS):
        print("Temporarily adding 'south' into INSTALLED_APPS.")
        settings.INSTALLED_APPS.append('south')

    kwargs = dict(initial=True) if initial else dict(auto=True)
    run_django_cmd('schemamigration', package['name'], **kwargs)
1124547
@Override
    public void chainInitialized(ChainData chainData) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "chainInitialized", chainData);

        chainState.set(ChainState.INITIALIZED.val);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "chainInitialized");
    }
769132
@Override
    public void init()
    {
        this.log.debug("Initializing the chaining uberspector.");
        // Create the chain
        // TODO Since we're in Plexus already, should we use components?
        String[] chainClassnames = this.runtime.getConfiguration().getStringArray(UBERSPECT_CHAIN_CLASSNAMES);
        for (String classname : chainClassnames) {
            initializeUberspector(classname);
        }
        // If the chain is empty, use a SecureUberspector
        if (this.inner == null) {
            this.log.error("No chained uberspectors defined! "
                + "This uberspector is just a placeholder that relies on a real uberspector "
                + "to actually allow method calls. Using SecureUberspect instead as a fallback.");
            initializeUberspector(SecureUberspector.class.getCanonicalName());
        }
        // Initialize all the uberspectors in the chain
        try {
            this.inner.init();
        } catch (Exception e) {
            this.log.warn(e.getMessage());
        }
    }
149190
async function init () {
  try {
    await sequelize.sync()
  } catch (err) {
    console.log(err)
    process.exit(-1)
  }
}
1190140
def _run_up(self, path, migration_file, batch, pretend=False):
        
        migration = self._resolve(path, migration_file)

        if pretend:
            return self._pretend_to_run(migration, "up")

        if migration.transactional:
            with migration.db.transaction():
                migration.up()
        else:
            migration.up()

        self._repository.log(migration_file, batch)

        self._note(
            decode("[<info>OK</>] <info>Migrated</info> ")
            + "<fg=cyan>%s</>" % migration_file
        )