Migrate existing cozy to node4
188589
def migrate_2_node4():
    '''
        
    '''
    helpers.cmd_exec('npm install -g cozy-monitor cozy-controller',
                     show_output=True)
    helpers.cmd_exec('update-cozy-stack', show_output=True)
    helpers.cmd_exec('update-all', show_output=True)
    helpers.cmd_exec('rm /etc/supervisor/conf.d/cozy-indexer.conf',
                     show_output=True)
    helpers.cmd_exec('supervisorctl reload', show_output=True)
    helpers.wait_cozy_stack()
    ssl.normalize_cert_dir()
    helpers.cmd_exec('apt-get update', show_output=True)
    helpers.cmd_exec(
        'echo "cozy cozy/nodejs_apt_list text " | debconf-set-selections',
        show_output=True)
    helpers.cmd_exec('apt-get install -y cozy-apt-node-list', show_output=True)
    helpers.cmd_exec('apt-get update', show_output=True)
    helpers.cmd_exec('apt-get remove -y nodejs-legacy', show_output=True)
    helpers.cmd_exec('apt-get remove -y nodejs-dev', show_output=True)
    helpers.cmd_exec('apt-get remove -y npm', show_output=True)
    helpers.cmd_exec('apt-get install -y nodejs', show_output=True)
    helpers.cmd_exec('apt-get install -y cozy', show_output=True)
    helpers.cmd_exec('npm install -g cozy-monitor cozy-controller',
                     show_output=True)
    rebuild_app('data-system')
    rebuild_app('home')
    rebuild_app('proxy')
    helpers.cmd_exec('supervisorctl restart cozy-controller', show_output=True)
    helpers.wait_cozy_stack()
    rebuild_all_apps(restart=True)
    restart_stopped_apps()
    helpers.cmd_exec('apt-get install -y cozy', show_output=True)
200143
function updateSite () {
    start('Adding new version of the docs site...');
    const options = { cwd: './code.material.angularjs.org' };
    writeDocsJson();

    // build files for bower
    exec([
        'rm -rf dist',
        'gulp docs'
    ]);
    replaceFilePaths();

    // copy files over to site repo
    exec([
        `cp -Rf ../dist/docs ${newVersion}`,
        'rm -rf latest && cp -Rf ../dist/docs latest',
        'git add -A',
        `git commit -m "release: version ${newVersion}"`,
        'rm -rf ../dist'
    ], options);
    replaceBaseHref(newVersion);
    replaceBaseHref('latest');

    // update firebase.json file
    updateFirebaseJson();
    exec(['git commit --amend --no-edit -a'], options);
    done();

    // add steps to push script
    pushCmds.push(
        comment('push the site'),
        'cd ' + options.cwd,
        'git pull --rebase --strategy=ours',
        'git push',
        'cd ..'
    );

    function updateFirebaseJson () {
      fs.writeFileSync(options.cwd + '/firebase.json', getFirebaseJson());
      function getFirebaseJson () {
        const json = require(options.cwd + '/firebase.json');
        json.hosting.rewrites = json.hosting.rewrites || [];
        const rewrites = json.hosting.rewrites;

        switch (rewrites.length) {
          case 0:
            rewrites.push(getRewrite('HEAD'));
          case 1:
            rewrites.push(getRewrite('latest'));
          default:
            rewrites.push(getRewrite(newVersion));
        }
        return JSON.stringify(json, null, 2);
        function getRewrite (str) {
          return {
            source:      '/' + str + '/**/!(*.@(js|html|css|json|svg|png|jpg|jpeg))',
            destination: '/' + str + '/index.html'
          };
        }
      }
    }

    function writeDocsJson () {
      const config = require(options.cwd + '/docs.json');
      config.versions.unshift(newVersion);

      // only set to default if not a release candidate
      config.latest = newVersion;
      fs.writeFileSync(options.cwd + '/docs.json', JSON.stringify(config, null, 2));
    }
  }
1104639
function changeConfig(oldConfig, newConfig) {
  invariant(isObject(oldConfig), 'Old config is not valid');
  invariant(isObject(newConfig), 'Config is not valid');

  if (newConfig.host) {
    var host = newConfig.host;
    var prefix = '';

    if (host.indexOf('http://') < 0 && host.indexOf('https://') < 0) {
      prefix += 'http://';
    }

    oldConfig.host = prefix + newConfig.host;
  }

  if (newConfig.port) {
    oldConfig.port = newConfig.port;
  }
}
1091442
function migrateState (version) {
    // Make sure the object exists
    if (!config.mqtt) {
        config.mqtt = {};
    }

    // This is the previous default, but it's totally wrong
    if (!config.mqtt.preface) {
        config.mqtt.preface = '/smartthings';
    }

    // Default Suffixes
    if (!config.mqtt[SUFFIX_READ_STATE]) {
        config.mqtt[SUFFIX_READ_STATE] = '';
    }
    if (!config.mqtt[SUFFIX_COMMAND]) {
        config.mqtt[SUFFIX_COMMAND] = '';
    }
    if (!config.mqtt[SUFFIX_WRITE_STATE]) {
        config.mqtt[SUFFIX_WRITE_STATE] = '';
    }

    // Default retain
    if (config.mqtt[RETAIN] !== false) {
        config.mqtt[RETAIN] = true;
    }

    // Default port
    if (!config.port) {
        config.port = 8080;
    }

    // Default protocol
    if (!url.parse(config.mqtt.host).protocol) {
        config.mqtt.host = 'mqtt://' + config.mqtt.host;
    }

    // Stuff was previously in subscription.json, load that and migrate it
    var SUBSCRIPTION_FILE = path.join(CONFIG_DIR, 'subscription.json');
    if (semver.lt(version, '1.1.0') && fs.existsSync(SUBSCRIPTION_FILE)) {
        var oldState = jsonfile.readFileSync(SUBSCRIPTION_FILE);
        callback = oldState.callback;
        subscriptions = oldState.topics;
    }

    saveState();
}
1212154
function wrapCreateServer (original) {
    return function wrappedCreateServer (options, handler) {
      var server = original.apply(this, arguments)
      shimmer.wrap(server.constructor.prototype, 'emit', wrapEmit)
      wrappedCreateServer[symbols.unwrap]()
      return server
    }
  }
172337
function extendServerImport(url, cb) {
		if (/^http(s)?\:/.test(url)) {
			return require("request")(url, function(error, response, body) {
				if (error) {
					return cb(error);
				}
				return cb(null, evaluateModule(url, body, response.headers["content-type"]));
			});
		}
		if (/\.(js|json)$/.test(url)) {
			return cb(null, require(url));
		} else {
			return require("fs").readFile(require("path").join(__dirname, url), function(err, result) {
				if (err) {
					cb(err);
				} else {
					cb(null, result.toString());
				}
			});
		}
	}
725963
def replace(self, node, properties=None):
        
        self.disconnect_all()
        self.connect(node, properties)
1165943
public function up()
    {
      //remove anahita from nodes and edges table names
      if (!dbexists('SHOW TABLES LIKE "#__nodes"')) {
          dbexec('RENAME TABLE #__anahita_nodes TO #__nodes');
      }

      if (!dbexists('SHOW TABLES LIKE "#__edges"')) {
          dbexec('RENAME TABLE #__anahita_edges TO #__edges');
      }

        //migrate users usertype
       dbexec('UPDATE `#__users` SET `usertype`=\'registered\' WHERE `usertype` NOT LIKE \'%admin%\' ');
        dbexec('UPDATE `#__users` SET `usertype`=\'administrator\' WHERE `usertype`=\'Administrator\' ');
        dbexec('UPDATE `#__users` SET `usertype`=\'super-administrator\' WHERE `usertype`=\'Super Administrator\' ');
        dbexec('ALTER TABLE `#__users` DROP COLUMN `gid` ');
        dbexec('ALTER TABLE `#__users` DROP COLUMN `sendEmail` ');

       //migrate people usertype
       dbexec('UPDATE `#__nodes` SET `person_usertype`=\'registered\' WHERE `person_usertype` NOT LIKE \'%admin%\' ');
        dbexec('UPDATE `#__nodes` SET `person_usertype`=\'administrator\' WHERE `person_usertype`=\'Administrator\' ');
        dbexec('UPDATE `#__nodes` SET `person_usertype`=\'super-administrator\' WHERE `person_usertype`=\'Super Administrator\' ');

       //migrate session table
       dbexec('ALTER TABLE `#__session` DROP COLUMN `gid` ');

       //drop legacy tables
       dbexec('DROP TABLE #__core_acl_aro');
        dbexec('DROP TABLE #__core_acl_aro_groups');
        dbexec('DROP TABLE #__core_acl_aro_map');
        dbexec('DROP TABLE #__core_acl_aro_sections');
        dbexec('DROP TABLE #__core_acl_groups_aro_map');
        dbexec('DROP TABLE #__groups');

       //legacy component cleanup
       dbexec('DELETE FROM `#__components` WHERE `option` IN (\'com_users\', \'com_user\') ');
        dbexec('UPDATE `#__components` SET `admin_menu_link`=\'option=com_people\', `admin_menu_alt`=\'People\', `admin_menu_img`=\'js/ThemeOffice/component.png\' WHERE `option`=\'com_people\' ');

        dbexec('ALTER TABLE `#__nodes` MODIFY `enabled` tinyint(1) NOT NULL DEFAULT 0');
        dbexec('ALTER TABLE `#__nodes` MODIFY `is_default` tinyint(1) NOT NULL DEFAULT 0');
        dbexec('UPDATE `#__nodes` SET `story_subject_id` = `created_by` WHERE `story_subject_id` = `story_target_id` AND `name` = \'actor_follow\'');
        dbexec('UPDATE `#__nodes` SET `enabled`=1, `access` = \'admins\' WHERE `type` LIKE \'%com:people.domain.entity.person\' AND `enabled` = 0');
    }
651921
def replace_nodes(root, old, new):

    '''
     
    '''

    rep = Replacer(old, new)
    rep.visit(root)
    return
111763
def neo(graph: BELGraph, connection: str, password: str):
    """"""
    import py2neo
    neo_graph = py2neo.Graph(connection, password=password)
    to_neo4j(graph, neo_graph)
16495
def migrate_paths(opts):
    '''
    
    '''
    oldpki_dir = os.path.join(syspaths.CONFIG_DIR, 'pki')

    if not os.path.exists(oldpki_dir):
        # There's not even a pki directory, don't bother migrating
        return

    newpki_dir = opts['pki_dir']

    if opts['default_include'].startswith('master'):
        keepers = ['master.pem',
                   'master.pub',
                   'syndic_master.pub',
                   'minions',
                   'minions_pre',
                   'minions_rejected',
                   ]
        if not os.path.exists(newpki_dir):
            os.makedirs(newpki_dir)
        for item in keepers:
            oi_path = os.path.join(oldpki_dir, item)
            ni_path = os.path.join(newpki_dir, item)
            if os.path.exists(oi_path) and not os.path.exists(ni_path):
                shutil.move(oi_path, ni_path)

    if opts['default_include'].startswith('minion'):
        keepers = ['minion_master.pub',
                   'minion.pem',
                   'minion.pub',
                   ]
        if not os.path.exists(newpki_dir):
            os.makedirs(newpki_dir)
        for item in keepers:
            oi_path = os.path.join(oldpki_dir, item)
            ni_path = os.path.join(newpki_dir, item)
            if os.path.exists(oi_path) and not os.path.exists(ni_path):
                shutil.move(oi_path, ni_path)
399680
function makeMove(child, afterNode, toIndex) {
	  // NOTE: Null values reduce hidden classes.
	  return {
	    type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
	    content: null,
	    fromIndex: child._mountIndex,
	    fromNode: ReactReconciler.getHostNode(child),
	    toIndex: toIndex,
	    afterNode: afterNode
	  };
	}
341731
function createNodeServer(http, nodePort, webSocketPort, watchFiles, tsWarning, tsError, target) {
    return http.createServer(async (req, res) => {
        try {
            const fileExtension = req.url.slice(req.url.lastIndexOf('.') + 1);
            switch (fileExtension) {
                case '/': {
                    const indexFileContents = (await fs.readFile(`./index.html`)).toString();
                    const modifiedIndexFileContents = modifyHTML(indexFileContents, 'index.html', watchFiles, webSocketPort);
                    watchFile(`./index.html`, watchFiles);
                    res.end(modifiedIndexFileContents);
                    return;
                }
                case 'js': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'mjs': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'ts': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'tsx': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'jsx': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'wast': {
                    await handleWASTExtension(req, res, fileExtension);
                    return;
                }
                case 'wasm': {
                    await handleWASMExtension(req, res, fileExtension);
                    return;
                }
                default: {
                    await handleGenericFile(req, res, fileExtension);
                    return;
                }
            }
        }
        catch(error) {
            console.log(error);
        }
    });
}
309857
function processRebase(result, from, dirname, oldUrl, to) {
  var newPath = oldUrl
  if (dirname !== from) {
    newPath = path.relative(from, dirname + path.sep + newPath)
  }
  newPath = path.resolve(from, newPath)
  newPath = path.relative(to, newPath)
  if (path.sep === "\\") {
    newPath = newPath.replace(/\\/g, "\/")
  }
  // New-URLs needs to be relative formatted to allow differentiation between
  // local imports and imports from node_modules.
  if ((oldUrl.charAt(0) === "." || oldUrl.charAt(0) === "/") && newPath.charAt(0) !== "." && newPath.charAt(0) !== "/") {
    newPath = "./" + newPath
  }
  return newPath
}
1174201
function migrate(cb) {

      // get all already executed migrations.
      db.query('SELECT "version" FROM "schema_migrations"', function(err, resp) {
        var migrations_run = 0;
        var executed = [];

        // if there is an error assume we are at the default state, and run root migration
        if (err) {

          // attempt to run file located at app_root/migrations/schema/root.sql -- good for previous data force load (e.g. Rails)
          var schema = fs.readFileSync(migrations_dir + "schema/root.sql").toString();
          db.query(schema); // populate with root schema if not populated.
        } else {
          // if no error, dump all versions into an array called executed for quick searching.
          for (var rl = resp.rows.length; rl > 0; rl--) {
            executed.push(resp.rows[rl - 1].version);
          }
        }


        // function loop to execute through the remainin "torun" migrations
        var run_migrations = (function(torun) {

          // get the next migration
          var current = torun.pop();

          // if there is a migration
          if (current) {

            // test if already executed
            if (executed.indexOf(current.id) < 0) {
              // alert of execution
              console.log("Executing migration: " + current.id);

              // check if migration is SQL
              if (current.sql) {

                // suffix with schema migrations insertion so we dont run again if successful.
                var sql = OPEN_TRANSACTION+current.sql + "; INSERT INTO schema_migrations VALUES (" + current.id + "); "+CLOSE_TRANSACTION;

                // execute the full query
                db.query(sql, function(e, r) {
                  if (e) {
                    db.query("ROLLBACK;", function () {
                      // if error, dump why we couldn't migrate and process no more.
                      console.log("Could not migrate database. Error provided below.")
                      console.log(e);
                      db.end();
                    });
                  } else {

                    // otherwise add to counter and run the rest of the "torun" array
                    migrations_run++;
                    run_migrations(torun);
                  }
                });

                // if migration is JS code
              } else if (current.js) {

                // pass our db object and execute with callback to insert into schema migration AND recurse with rest of "torun" array
                current.js(db, function() {
                  db.query("INSERT INTO schema_migrations VALUES (" + current.id + ")", function(err, results) {
                    migrations_run++;
                    run_migrations(torun);
                  });
                });
              }
            } else {

              // if no idea what to do, just skip!
              run_migrations(torun);

            }

            // if no more migrations
          } else {
            // only output if we done work.
            if (migrations_run > 0) console.log("Migrations run: " + migrations_run);

            // if there is a callback, exec it
            if (cb) {
              cb();
            }
          }
        });




        // populate all existing migrations by reading the migrations directory
        fs.readdir(migrations_dir, function(err, list) {
          var migrations = [];


          for (var li = 0, ll = list.length; li < ll; li++) {

            // if the file has a .sql extension, load it as a file read for sql schema updating
            if (m = list[li].match(/(.*)\.sql/)) {
              migrations.push({
                id: m[1],
                sql: fs.readFileSync(migrations_dir + m[0]).toString()
              });

              // if the file has a .js extension, load via require system and set js attribute as .migrate function
            } else if (j = list[li].match(/(.*)\.js/)) {
              migrations.push({
                id: j[1],
                js: require(migrations_dir + "/" + list[li]).migrate
              });
            }
          }

          //recursively run through all migrations after they have been sorted by ID in ascending order
          run_migrations(migrations.sort((function(a, b) {
            return (parseInt(b.id) - parseInt(a.id));
          })));
        });
      });
    }
844953
def transform_import(self, node, results):
        
        import_mod = results.get("module")
        pref = import_mod.prefix

        names = []

        # create a Node list of the replacement modules
        for name in MAPPING[import_mod.value][:-1]:
            names.extend([Name(name[0], prefix=pref), Comma()])
        names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
        import_mod.replace(names)
1283331
function main() {
  var argv = require('yargs')
    .usage('Usage: $0 [options]')
    .example('$0 -s https://user:pass@host/db -b <bucket>', 'Backup db to bucket')
    .options({
      'source': { alias: 's', nargs: 1, demandOption: true, describe: 'Source database URL' },
      'bucket': { alias: 'b', nargs: 1, demandOption: true, describe: 'Destination bucket' },
      'prefix': { alias: 'p', nargs: 1, describe: 'Prefix for backup object key', default: 'couchbackup' },
      's3url': { nargs: 1, describe: 'S3 endpoint URL' },
      'awsprofile': { nargs: 1, describe: 'The profile section to use in the ~/.aws/credentials file', default: 'default' }
    })
    .help('h').alias('h', 'help')
    .epilog('Copyright (C) IBM 2017')
    .argv;

  const sourceUrl = argv.source;
  const backupName = new url.URL(sourceUrl).pathname.split('/').filter(function(x) { return x; }).join('-');
  const backupBucket = argv.bucket;
  const backupKeyPrefix = `${argv.prefix}-${backupName}`;
  const shallow = argv.shallow;

  const backupKey = `${backupKeyPrefix}-${new Date().toISOString()}`;

  const s3Endpoint = argv.s3url;
  const awsProfile = argv.awsprofile;

  // Creds are from ~/.aws/credentials, environment etc. (see S3 docs).
  const awsOpts = {
    signatureVersion: 'v4',
    credentials: new AWS.SharedIniFileCredentials({ profile: awsProfile })
  };
  if (typeof s3Endpoint !== 'undefined') {
    awsOpts.endpoint = new AWS.Endpoint(s3Endpoint);
  }
  const s3 = new AWS.S3(awsOpts);

  debug(`Creating a new backup of ${s(sourceUrl)} at ${backupBucket}/${backupKey}...`);
  bucketAccessible(s3, backupBucket)
    .then(() => {
      return backupToS3(sourceUrl, s3, backupBucket, backupKey, shallow);
    })
    .then(() => {
      debug('done.');
    })
    .catch((reason) => {
      debug(`Error: ${reason}`);
      process.exit(1);
    });
}