Upgrade all the NRML files contained in the given directory to the latest
    NRML version. Works by walking all subdirectories.
    WARNING: there is no downgrade!
345326
def upgrade_nrml(directory, dry_run, multipoint):
    
    for cwd, dirs, files in os.walk(directory):
        for f in files:
            path = os.path.join(cwd, f)
            if f.endswith('.xml'):
                ip = iterparse(path, events=('start',))
                next(ip)  # read node zero
                try:
                    fulltag = next(ip)[1].tag  # tag of the first node
                    xmlns, tag = fulltag.split('}')
                except Exception:  # not a NRML file
                    xmlns, tag = '', ''
                if xmlns[1:] == NRML05:  # already upgraded
                    if 'sourceModel' in tag and multipoint:
                        print('upgrading to multiPointSources', path)
                        node0 = nrml.read(path)[0]
                        sourceconverter.update_source_model(node0, path)
                        with open(path, 'wb') as f:
                            nrml.write([node0], f, gml=True)
                elif 'nrml/0.4' in xmlns and (
                        'vulnerability' in tag or 'fragility' in tag or
                        'sourceModel' in tag):
                    if not dry_run:
                        print('Upgrading', path)
                        try:
                            upgrade_file(path, multipoint)
                        except Exception as exc:
                            raise
                            print(exc)
                    else:
                        print('Not upgrading', path)
40654
def convert_environment(datadir, version, always_yes):
    
    # Since we don't call either load() or new() we have to call require_images ourselves.
    require_images()

    inp = None
    old_version = _get_current_format(datadir)
    migration_func = migrations[(old_version, version)]

    if version > CURRENT_FORMAT_VERSION:
        raise DatacatsError('Cannot migrate to a version higher than the '
                            'current one.')
    if version < 1:
        raise DatacatsError('Datadir versioning starts at 1.')

    if not always_yes:
        while inp != 'y' and inp != 'n':
            inp = raw_input(migration_func.__doc__.format(version))

        if inp == 'n':
            sys.exit(1)

    lockfile = LockFile(path_join(datadir, '.migration_lock'))
    lockfile.acquire()

    try:
        # FIXME: If we wanted to, we could find a set of conversions which
        # would bring us up to the one we want if there's no direct path.
        # This isn't necessary with just two formats, but it may be useful
        # at 3.
        # Call the appropriate conversion function
        migration_func(datadir)
    finally:
        lockfile.release()
1151020
def merge(directory=None, revisions='', message=None, branch_label=None,
          rev_id=None):
    """"""
    if alembic_version >= (0, 7, 0):
        config = current_app.extensions['migrate'].migrate.get_config(
            directory)
        command.merge(config, revisions, message=message,
                      branch_label=branch_label, rev_id=rev_id)
    else:
        raise RuntimeError('Alembic 0.7.0 or greater is required')
1273272
private function updateVersionInFile()
  {
    if ($this->myFilename)
    {
      $status = file_put_contents($this->myFilename, $this->myNewVersion['version']);
      if (!$status)
      {
        $this->logError("File %s is not writable", $this->myFilename);
      }
    }
  }
473404
def relink_all(cls, old_file, new_file):
        
        assert old_file.checksum == new_file.checksum
        assert old_file.id
        assert new_file.id

        with db.session.begin_nested():
            ObjectVersion.query.filter_by(file_id=str(old_file.id)).update({
                ObjectVersion.file_id: str(new_file.id)})
961557
private function replaceCurrentVersionbyNewVersion()
    {
        $this->fs->copy($this->newInstallerFile, $this->currentInstallerFile, true);

        return $this;
    }
1082507
@SuppressWarnings("deprecation")
    public boolean upgrade() throws Exception {
        // We need to start a client so we can send requests to elasticsearch
        try {
            esClient.start();
        } catch (Exception t) {
            logger.fatal("We can not start Elasticsearch Client. Exiting.", t);
            return false;
        }

        // The upgrade script is for now a bit dumb. It assumes that you had an old version of FSCrawler (< 2.3) and it will
        // simply move data from index/folder to index_folder
        String index = settings.getElasticsearch().getIndex();

        // Check that the old index actually exists
        if (esClient.isExistingIndex(index)) {
            // We check that the new indices don't exist yet or are empty
            String indexFolder = settings.getElasticsearch().getIndexFolder();
            boolean indexExists = esClient.isExistingIndex(indexFolder);
            long numberOfDocs = 0;
            if (indexExists) {
                ESSearchResponse responseFolder = esClient.search(new ESSearchRequest().withIndex(indexFolder));
                numberOfDocs = responseFolder.getTotalHits();
            }
            if (numberOfDocs > 0) {
                logger.warn("[{}] already exists and is not empty. No upgrade needed.", indexFolder);
            } else {
                logger.debug("[{}] can be upgraded.", index);

                // Create the new indices with the right mappings (well, we don't read existing user configuration)
                if (!indexExists) {
                    esClient.createIndices();
                    logger.info("[{}] has been created.", indexFolder);
                }

                // Run reindex task for folders
                logger.info("Starting reindex folders...");
                int folders = esClient.reindex(index, INDEX_TYPE_FOLDER, indexFolder);
                logger.info("Done reindexing [{}] folders...", folders);

                // Run delete by query task for folders
                logger.info("Starting removing folders from [{}]...", index);
                esClient.deleteByQuery(index, INDEX_TYPE_FOLDER);
                logger.info("Done removing folders from [{}]", index);

                logger.info("You can now upgrade your elasticsearch cluster to >=6.0.0!");
                return true;
            }
        } else {
            logger.info("[{}] does not exist. No upgrade needed.", index);
        }

        return false;
    }
941468
def set_version(version, rootdir = Dir.pwd, options = {})
      exit_status = 0
      type    = (options[:type])    ? options[:type]    : FalkorLib.config[:versioning][:type]
      source  = (options[:source])  ? options[:source]  : FalkorLib.config[:versioning][:source][ type ]
      versionfile = File.join( rootdir, source[:filename] ) unless source[:filename].nil?
      major, minor, patch = major(version), minor(version), patch(version)
      #tocommit = ""
      case type
      when 'file'
        info "writing version changes in #{source[:filename]}"
        File.open(versionfile, 'w') { |f| f.puts version } #if File.exist? ( versionfile )
      when 'gem'
        info "=> writing version changes in #{source[:filename]}"
        File.open(versionfile, 'r+') do |f|
          text = f.read
          text.gsub!(/^(\s*)MAJOR\s*,\s*MINOR,\s*PATCH\s*=\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(.*)$/,
                     '\1' + "MAJOR, MINOR, PATCH = #{major}, #{minor}, #{patch}" + '\5')
          f.rewind
          f.write(text)
        end
      when 'puppet_module'
        info "=> writing version changes in #{source[:filename]}"
        metadata = JSON.parse( IO.read( versionfile ) )
        metadata["version"] = version
        File.open(versionfile, "w") do |f|
          f.write JSON.pretty_generate( metadata )
        end
        #exit 1
      end
      if FalkorLib::Git.init?(rootdir)
        filelist = FalkorLib::Git.list_files( rootdir )
        Dir.chdir( rootdir ) do
          next if source[:filename].nil?
          unless filelist.include?( source[:filename] )
            warning "The version file #{source[:filename]} is not part of the Git repository"
            answer = ask("Adding the file to the repository? (Y|n)", 'Yes')
            next if answer =~ /n.*/i
            exit_status = FalkorLib::Git.add(versionfile, "Adding the version file '#{source[:filename]}', inialized to the '#{version}' version" )
            next
          end
          run %( git diff #{source[:filename]} )
          answer = ask(cyan("=> Commit the changes of the version file to the repository? (Y|n)"), 'Yes')
          next if answer =~ /n.*/i
          run %( git commit -s -m "bump to version '#{version}'" #{source[:filename]} )
          exit_status = $?.to_i
          # if (type == 'gem' && File.exists?(File.join(rootdir, 'Gemfile')) )
          #     run %{
          #        sleep 2
          #        bundle update falkorlib
          #        git commit -s -m "Update Gemfile.lock accordingly" Gemfile.lock
          #     } if command?( 'bundle' )
          # end
        end
      end
      exit_status
    end
150557
def copyFuncVersionedLib(dest, source, env):
    """"""

    if os.path.isdir(source):
        raise SCons.Errors.UserError("cannot install directory `%s' as a version library" % str(source) )
    else:
        # remove the link if it is already there
        try:
            os.remove(dest)
        except:
            pass
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
        installShlibLinks(dest, source, env)

    return 0
1136910
def _dirdiffandupdate(self, dir1, dir2):
        
        self._dowork(dir1, dir2, None, self._update)
352341
public static ns_upgrade upgrade(nitro_service client, ns_upgrade resource) throws Exception
	{
		return ((ns_upgrade[]) resource.perform_operation(client, "upgrade"))[0];
	}
464917
def upgrade(self):
        
        warn('Upgrading ' + self.filename)
        if self.backup_config(self.filename):
            return self.write_default_config(self.filename)
        return False
1223522
def _upgrade_genome_resources(galaxy_dir, base_url):
    
    import requests
    for dbkey, ref_file in genome.get_builds(galaxy_dir):
        # Check for a remote genome resources file
        remote_url = base_url % dbkey
        requests.packages.urllib3.disable_warnings()
        r = requests.get(remote_url, verify=False)
        if r.status_code == requests.codes.ok:
            local_file = os.path.join(os.path.dirname(ref_file), os.path.basename(remote_url))
            if os.path.exists(local_file):
                with open(local_file) as in_handle:
                    local_config = yaml.safe_load(in_handle)
                remote_config = yaml.safe_load(r.text)
                needs_update = remote_config["version"] > local_config.get("version", 0)
                if needs_update:
                    shutil.move(local_file, local_file + ".old%s" % local_config.get("version", 0))
            else:
                needs_update = True
            if needs_update:
                print("Updating %s genome resources configuration" % dbkey)
                with open(local_file, "w") as out_handle:
                    out_handle.write(r.text)
1105076
def update_system_path():
        """"""
        cwd = os.getcwd()
        lib_dir = os.path.join(os.getcwd(), 'lib_')
        lib_latest = os.path.join(os.getcwd(), 'lib_latest')

        # insert the lib_latest directory into the system Path if no other lib directory found. This
        # entry will be bumped to index 1 after adding the current working directory.
        if not [p for p in sys.path if lib_dir in p]:
            sys.path.insert(0, lib_latest)

        # insert the current working directory into the system Path for the App, ensuring that it is
        # always the first entry in the list.
        try:
            sys.path.remove(cwd)
        except ValueError:
            pass
        sys.path.insert(0, cwd)
918864
def replace_in_dirs(version):
    """"""
    print(color(
        "Upgrading directory-components dependency in all repos...",
        fg='blue', style='bold'))
    for dirname in Utils.dirs:
        replace = "directory-components=={}".format(version)
        replace_in_files(dirname, replace)
    done(version)
785854
@Override
  public boolean upgrade() {
    int schemaVersion = versionService.getSchemaVersion();
    if (schemaVersion < 31) {
      throw new UnsupportedOperationException(
          "Upgrading from schema version below 31 is not supported");
    }
    if (schemaVersion < versionService.getAppVersion()) {
      LOG.info(
          "Metadata version:{}, current version:{} upgrade needed",
          schemaVersion,
          versionService.getAppVersion());

      upgrades
          .stream()
          .filter(upgrade -> upgrade.getFromVersion() >= schemaVersion)
          .forEach(this::runUpgrade);

      versionService.setSchemaVersion(versionService.getAppVersion());

      LOG.info("Metadata upgrade done.");
      return true;
    } else {
      LOG.debug(
          "Metadata version:{}, current version:{} upgrade not needed",
          schemaVersion,
          versionService.getAppVersion());
      return false;
    }
  }
855088
def upgrade():
    """"""
    # table ObjectVersion: modify primary_key
    if op.get_context().dialect.name == 'mysql':
        Fk = 'fk_files_object_bucket_id_files_bucket'
        op.execute(
            'ALTER TABLE files_object '
            'DROP FOREIGN KEY {0}, DROP PRIMARY KEY, '
            'ADD PRIMARY KEY(version_id), '
            'ADD FOREIGN KEY(bucket_id) '
            'REFERENCES files_bucket(id)'.format(Fk))
    else:
        op.drop_constraint('pk_files_object', 'files_object', type_='primary')
        op.create_primary_key(
            'pk_files_object', 'files_object', ['version_id'])
    op.create_unique_constraint(
        'uq_files_object_bucket_id', 'files_object',
        ['bucket_id', 'version_id', 'key'])
    # table ObjectVersionTag: create
    op.create_table(
        'files_objecttags',
        sa.Column(
            'version_id',
            sqlalchemy_utils.types.uuid.UUIDType(),
            nullable=False),
        sa.Column(
            'key',
            sa.Text().with_variant(mysql.VARCHAR(255), 'mysql'),
            nullable=False
        ),
        sa.Column(
            'value',
            sa.Text().with_variant(mysql.VARCHAR(255), 'mysql'),
            nullable=False
        ),
        sa.PrimaryKeyConstraint('version_id', 'key'),
        sa.ForeignKeyConstraint(
            ['version_id'],
            [u'files_object.version_id'],
            ondelete='CASCADE'),
    )