Converts the given Electron app using Project Centennial
Container Virtualization.

@param program - Program object containing the user's instructions
@returns - Promise
324997
function convertWithContainer (program) {
  return new Promise((resolve, reject) => {
    if (!program.desktopConverter) {
      utils.log('Could not find the Project Centennial Desktop App Converter, which is required to')
      utils.log('run the conversion to appx using a Windows Container.\n')
      utils.log('Consult the documentation at https://aka.ms/electron-windows-store for a tutorial.\n')
      utils.log('You can find the Desktop App Converter at https://www.microsoft.com/en-us/download/details.aspx?id=51691\n')
      utils.log('Exiting now - restart when you downloaded and unpacked the Desktop App Converter!')

      process.exit(0)
    }

    let preAppx = path.join(program.outputDirectory, 'pre-appx')
    let installer = path.join(program.outputDirectory, 'ElectronInstaller.exe')
    let logfile = path.join(program.outputDirectory, 'logs', 'conversion.log')
    let converterArgs = [
      `-LogFile ${logfile}`,
      `-Installer '${installer}'`,
      `-Converter '${path.join(program.desktopConverter, 'DesktopAppConverter.ps1')}'`,
      `-ExpandedBaseImage ${program.expandedBaseImage}`,
      `-Destination '${preAppx}'`,
      `-PackageName "${program.packageName}"`,
      `-Version ${program.packageVersion}`,
      `-Publisher "${program.publisher}"`,
      `-AppExecutable '${program.packageExecutable}'`
    ]
    let args = `& {& '${path.resolve(__dirname, '..', 'ps1', 'convert.ps1')}' ${converterArgs.join(' ')}}`
    let child, tail

    utils.log(chalk.green.bold('Starting Conversion...'))
    utils.debug(`Conversion parameters used: ${JSON.stringify(converterArgs)}`)

    try {
      child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', args])
    } catch (error) {
      reject(error)
    }

    child.stdout.on('data', (data) => utils.debug(data.toString()))
    child.stderr.on('data', (data) => utils.debug(data.toString()))
    child.on('exit', () => {
      // The conversion process exited, let's look for a log file
      // However, give the PS process a 3s headstart, since we'll
      // crash if the logfile does not exist yet
      setTimeout(() => {
        tail = new Tail(logfile, {
          fromBeginning: true
        })

        tail.on('line', (data) => {
          utils.log(data)

          if (data.indexOf('Conversion complete') > -1) {
            utils.log('')
            tail.unwatch()
            resolve()
          } else if (data.indexOf('An error occurred') > -1) {
            tail.unwatch()
            reject(new Error('Detected error in conversion log'))
          }
        })

        tail.on('error', (err) => utils.log(err))
      }, 3000)
    })

    child.stdin.end()
  })
}
1138236
@Override
	public Response createApplication( Application app ) {

		this.logger.fine( "Request: create application " + app + "." );
		Response result;
		try {
			String tplName = app.getTemplate() == null ? null : app.getTemplate().getName();
			String tplQualifier = app.getTemplate() == null ? null : app.getTemplate().getVersion();
			String appName = app.getDisplayName() != null ? app.getDisplayName() : app.getName();
			ManagedApplication ma = this.manager.applicationMngr().createApplication( appName, app.getDescription(), tplName, tplQualifier );
			result = Response.ok().entity( ma.getApplication()).build();

		} catch( InvalidApplicationException e ) {
			result = handleError(
					Status.NOT_FOUND,
					new RestError( REST_MNGMT_INVALID_TPL, e, application( app )),
					lang( this.manager )).build();

		} catch( AlreadyExistingException e ) {
			result = handleError(
					Status.FORBIDDEN,
					new RestError( REST_MNGMT_CONFLICT, e, application( app )),
					lang( this.manager )).build();

		} catch( IOException e ) {
			result = handleError(
					Status.UNAUTHORIZED,
					new RestError( REST_SAVE_ERROR, e, application( app )),
					lang( this.manager )).build();
		}

		return result;
	}
216813
function (instruction, evaluator, context) {
        return Promise
            .resolve(evaluator.call(context, instruction))
            .then(function () {
            if (!('viewPorts' in instruction.config)) {
                instruction.config.viewPorts = {
                    'default': {
                        moduleId: instruction.config.moduleId
                    }
                };
            }
            return instruction;
        });
    }
564635
function(packageName, componentName) {
        return new Promise(function(resolve, reject) {
            exec(resolve, reject, APP_PLUGIN_NAME, "startApp", [packageName, componentName]);
        });
    }
1048870
function convert(program, callback) {

  // define no-op callback
  if (!callback) {
    callback = function (err, blueprint) { }
  }

  // Read in the file
  refparser.parse(program.input, function (err, schema) {
    if (err) isMain ? halt(err) : callback(err);
    // Read in aglio options
    var options = {
      themeTemplate: (program.themeTemplate === 'triple' || program.themeTemplate === 'index' || !program.themeTemplate) ?
        path.resolve(__dirname, 'templates/' + (program.themeTemplate || 'index') + '.jade') :
        themeTemplate,
      themeVariables: program.themeVariables,
      themeFullWidth: program.themeFullWidth,
      noThemeCondense: program.noThemeCondense,
      themeStyle: program.themeStyle,
      locals: {
        livePreview: program.server,
        host: ((schema.schemes && schema.schemes.length > 0 && schema.host) ? 
          (schema.schemes[0] || 'https') 
          : 'https') 
          + '://' + schema.host + (schema.basePath || '')
      }
    };

    swag2blue.run({ '_': [program.input] }, function (err, blueprint) {
      if (err) isMain ? halt(err) : callback(err);
      aglio.render(blueprint, options, function (err, html, warnings) {
        if (err) isMain ? halt(err) : callback(err);

        // If we had warnings and not outputting to console, print them out and continue.
        if (warnings && !program.output && isMain) {
          warn('Encountered ' + warnings.length + ' warnings: \n');
          warnings.forEach(function (warning) {
            warn("\n");
            warn(prettyjson.render(warning, { noColor: true }));
          });
          warn("\n");
        }

        if (!program.noMinify) {
          html = minify(html, {
            collapseBooleanAttributes: true,
            collapseWhitespace: true,
            minifyCSS: true,
            minifyJS: true,
            minifyURLs: true,
            removeAttributeQuotes: true,
            removeComments: true,
            removeEmptyAttributes: true,
            removeOptionalTags: true,
            removeRedundantAttributes: true,
            useShortDoctype: true
          });
        }

        // If output is specified, write to file.  Otherwise write to console.
        if (program.output) {
          fs.writeFile(program.output, html, function (err) {
            if (err) isMain ? halt(err) : callback(err);
            success("Success! Output written to: " + program.output);
            callback(null, html);
          });
        } else {
          if (isMain) console.log(html);
          callback(null, html);
        }
      });
    });
  });
}
1173815
function(apps) {

  var filepath = getGlobalConfig().appRegistry;

  var tempFilepath = filepath + '.tmp';

  // Write to temp file.
  return Promise.fromNode(function(cb) {
    fs.writeFile(tempFilepath, JSON.stringify(apps), cb);
    log.debug(format('Setting app registry with %j', apps));
  })
  // Rename temp file to normal file.
  .then(function() {
    return Promise.fromNode(function(cb) {
      fs.rename(tempFilepath, filepath, cb);
    });
  });

}
235429
public void setPostUninstallProgram( final String program) {
		if ( null == program) {
			format.getHeader().createEntry( POSTUNPROG, DEFAULTSCRIPTPROG);
		} else if ( 0 == program.length()){
			format.getHeader().createEntry( POSTUNPROG, DEFAULTSCRIPTPROG);
		} else {
			format.getHeader().createEntry( POSTUNPROG, program);
		}
	}
1126247
protected int executeProgram(PackagedProgram program, Client client, int parallelism) {
		JobExecutionResult execResult;
		try {
			client.setPrintStatusDuringExecution(true);
			execResult = client.run(program, parallelism, true);
		}
		catch (ProgramInvocationException e) {
			return handleError(e);
		}
		finally {
			program.deleteExtractedLibraries();
		}
		
		// we come here after the job has finished
		if (execResult != null) {
			System.out.println("Job Runtime: " + execResult.getNetRuntime());
			Map<String, Object> accumulatorsResult = execResult.getAllAccumulatorResults();
			if (accumulatorsResult.size() > 0) {
				System.out.println("Accumulator Results: ");
				System.out.println(AccumulatorHelper.getResultsFormated(accumulatorsResult));
			}
		}
		return 0;
	}
368873
public void setPreInstallProgram( final String program) {
		if ( null == program) {
			format.getHeader().createEntry( PREINPROG, DEFAULTSCRIPTPROG);
		} else if ( 0 == program.length()){
			format.getHeader().createEntry( PREINPROG, DEFAULTSCRIPTPROG);
		} else {
			format.getHeader().createEntry( PREINPROG, program);
		}
	}
1018147
function __runProgram() {
            try {
                eval(__program);
            } catch (err) {
                if (err.rethrow) throw(err);
                err = new Error(err.message+" in meta program of '"+__filename+"':\n"+__err2code(__program, err));
                err.rethrow = true;
                throw(err);
            }
        }
841220
private static <A> ProgramChromosome<A> create(
		final Tree<? extends Op<A>, ?> program,
		final Predicate<? super ProgramChromosome<A>> validator,
		final ISeq<? extends Op<A>> operations,
		final ISeq<? extends Op<A>> terminals
	) {
		final ISeq<ProgramGene<A>> genes = FlatTreeNode.of(program).stream()
			.map(n -> new ProgramGene<>(
				n.getValue(), n.childOffset(), operations, terminals))
			.collect(ISeq.toISeq());

		return new ProgramChromosome<>(genes, validator, operations, terminals);
	}
1146551
public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) {
    return executeWithinProcessApplication(callback, processApplicationReference, null);
  }
947953
def quilc_compile_payload(quil_program, isa, specs):
    """"""
    if not quil_program:
        raise ValueError("You have attempted to compile an empty program."
                         " Please provide an actual program.")
    if not isinstance(quil_program, Program):
        raise TypeError("quil_program must be a Program object.")
    if not isinstance(isa, ISA):
        raise TypeError("isa must be an ISA object.")
    if not isinstance(specs, Specs):
        raise TypeError("specs must be a Specs object.")

    payload = {"uncompiled-quil": quil_program.out(),
               "target-device": {
                   "isa": isa.to_dict(),
                   "specs": specs.to_dict()}}

    return payload
1094318
function buildMain(inpOptions, callback) {
  const options = Object.assign({}, inpOptions);

  // pre process app
  const tmpObj = tmp.dirSync({ mode: '0755', unsafeCleanup: true });
  const tmpPath = tmpObj.name;

  // todo check if this is still needed on later version of packager
  const packagerConsole = new PackagerConsole();

  const progress = new DishonestProgress(5);

  async.waterfall(
    [
      (cb) => {
        progress.tick('inferring');
        optionsFactory(options)
          .then((result) => {
            cb(null, result);
          })
          .catch((error) => {
            cb(error);
          });
      },
      (opts, cb) => {
        progress.tick('copying');
        buildApp(opts.dir, tmpPath, opts, (error) => {
          if (error) {
            cb(error);
            return;
          }
          // Change the reference file for the Electron app to be the temporary path
          const newOptions = Object.assign({}, opts, {
            dir: tmpPath,
          });
          cb(null, newOptions);
        });
      },
      (opts, cb) => {
        progress.tick('icons');
        iconBuild(opts, (error, optionsWithIcon) => {
          cb(null, optionsWithIcon);
        });
      },
      (opts, cb) => {
        progress.tick('packaging');
        // maybe skip passing icon parameter to electron packager
        let packageOptions = maybeNoIconOption(opts);
        // maybe skip passing other parameters to electron packager
        packageOptions = maybeNoAppCopyrightOption(packageOptions);
        packageOptions = maybeNoAppVersionOption(packageOptions);
        packageOptions = maybeNoBuildVersionOption(packageOptions);
        packageOptions = maybeNoVersionStringOption(packageOptions);
        packageOptions = maybeNoWin32metadataOption(packageOptions);

        packagerConsole.override();

        packager(packageOptions)
          .then((appPathArray) => {
            packagerConsole.restore(); // restore console.error
            cb(null, opts, appPathArray); // options still contain the icon to waterfall
          })
          .catch((error) => {
            packagerConsole.restore(); // restore console.error
            cb(error, opts); // options still contain the icon to waterfall
          });
      },
      (opts, appPathArray, cb) => {
        progress.tick('finalizing');
        // somehow appPathArray is a 1 element array
        const appPath = getAppPath(appPathArray);
        if (!appPath) {
          cb();
          return;
        }

        maybeCopyIcons(opts, appPath, (error) => {
          cb(error, appPath);
        });
      },
    ],
    (error, appPath) => {
      packagerConsole.playback();
      callback(error, appPath);
    },
  );
}
324749
function RedisProject(projectId, adapter) {
    var logger = adapter.logger.fork(projectId);
    this.projectId = projectId;

    this.closeProject = function (callback) {
        var deferred = Q.defer();
        deferred.resolve();
        return deferred.promise.nodeify(callback);
    };

    this.loadObject = function (hash, callback) {
        var deferred = Q.defer();
        if (typeof hash !== 'string') {
            deferred.reject(new Error('loadObject - given hash is not a string : ' + typeof hash));
        } else if (!REGEXP.HASH.test(hash)) {
            deferred.reject(new Error('loadObject - invalid hash :' + hash));
        } else {
            Q.ninvoke(adapter.client, 'hget', projectId, hash)
                .then(function (result) {
                    // Bulk string reply: the value associated with field,
                    // or nil when field is not present in the hash or key does not exist.
                    if (result) {
                        deferred.resolve(JSON.parse(result));
                    } else {
                        logger.error('object does not exist ' + hash);
                        deferred.reject(new Error('object does not exist ' + hash));
                    }
                })
                .catch(deferred.reject);
        }

        return deferred.promise.nodeify(callback);
    };

    this.insertObject = function (object, callback) {
        var deferred = Q.defer();
        if (object === null || typeof object !== 'object') {
            deferred.reject(new Error('object is not an object'));
        } else if (typeof object._id !== 'string' || !REGEXP.HASH.test(object._id)) {
            deferred.reject(new Error('object._id is not a valid hash.'));
        } else {
            Q.ninvoke(adapter.client, 'hsetnx', projectId, object._id, JSON.stringify(object))
                .then(function (result) {
                    // 1 if field is a new field in the hash and value was set.
                    // 0 if field already exists in the hash and no operation was performed.
                    if (result === 0) {
                        Q.ninvoke(adapter.client, 'hget', projectId, object._id)
                            .then(function (objectStr) {
                                var errMsg;
                                if (CANON.stringify(object) === CANON.stringify(JSON.parse(objectStr))) {
                                    logger.info('tried to insert existing hash - the two objects were equal',
                                        object._id);
                                    deferred.resolve();
                                } else {
                                    errMsg = 'tried to insert existing hash - the two objects were NOT equal ';
                                    logger.error(errMsg, {
                                        metadata: {
                                            newObject: CANON.stringify(object),
                                            oldObject: CANON.stringify(JSON.parse(objectStr))
                                        }
                                    });
                                    deferred.reject(new Error(errMsg + object._id));
                                }
                            })
                            .catch(deferred.reject);
                    } else {
                        if (object.type === CONSTANTS.COMMIT_TYPE) {
                            Q.ninvoke(adapter.client, 'hset', projectId + adapter.CONSTANTS.COMMITS,
                                object._id, object.time)
                                .then(function () {
                                    deferred.resolve();
                                })
                                .catch(deferred.reject);
                        } else {
                            deferred.resolve();
                        }
                    }
                });
        }

        return deferred.promise.nodeify(callback);
    };

    this.getBranches = function (callback) {
        return Q.ninvoke(adapter.client, 'hgetall', projectId + adapter.CONSTANTS.BRANCHES)
            .then(function (result) {
                return result || {};
            })
            .nodeify(callback);
    };

    this.getBranchHash = function (branch, callback) {
        return Q.ninvoke(adapter.client, 'hget', projectId + adapter.CONSTANTS.BRANCHES, branch)
            .then(function (branchHash) {
                return branchHash || '';
            }).nodeify(callback);
    };

    this.setBranchHash = function (branch, oldhash, newhash, callback) {
        var deferred = Q.defer(),
            branchesHashMap = projectId + adapter.CONSTANTS.BRANCHES;

        if (oldhash === newhash) {
            Q.ninvoke(adapter.client, 'hget', branchesHashMap, branch)
                .then(function (branchHash) {
                    branchHash = branchHash || '';
                    if (branchHash === oldhash) {
                        deferred.resolve();
                    } else {
                        deferred.reject(new Error('branch hash mismatch'));
                    }
                })
                .catch(deferred.reject);
        } else if (newhash === '') {
            Q.ninvoke(adapter.client, 'hget', branchesHashMap, branch)
                .then(function (branchHash) {
                    if (branchHash === oldhash) {
                        Q.ninvoke(adapter.client, 'hdel', branchesHashMap, branch)
                            .then(deferred.resolve);
                    } else if (branchHash === null) {
                        deferred.resolve();
                    } else {
                        deferred.reject(new Error('branch hash mismatch'));
                    }
                })
                .catch(deferred.reject);
        } else if (oldhash === '') {
            Q.ninvoke(adapter.client, 'hsetnx', branchesHashMap, branch, newhash)
                .then(function (result) {
                    // 1 if field is a new field in the hash and value was set.
                    // 0 if field already exists in the hash and no operation was performed.
                    if (result === 1) {
                        deferred.resolve();
                    } else {
                        deferred.reject(new Error('branch hash mismatch'));
                    }
                })
                .catch(deferred.reject);
        } else {
            Q.ninvoke(adapter.client, 'hget', branchesHashMap, branch)
                .then(function (branchHash) {
                    if (branchHash === oldhash) {
                        Q.ninvoke(adapter.client, 'hset', branchesHashMap, branch, newhash)
                            .then(function () {
                                deferred.resolve();
                            })
                            .catch(deferred.reject);
                    } else {
                        deferred.reject(new Error('branch hash mismatch'));
                    }
                })
                .catch(deferred.reject);
        }

        return deferred.promise.nodeify(callback);
    };

    this.getCommits = function (before, number, callback) {
        return Q.ninvoke(adapter.client, 'hgetall', projectId + adapter.CONSTANTS.COMMITS)
            .then(function (result) {
                var i,
                    hashArray,
                    timestamp,
                    hashKeys = Object.keys(result || {}),
                    commitsInfo = [];

                // FIXME: This is not a very optimized implementation
                for (i = 0; i < hashKeys.length; i += 1) {
                    timestamp = parseInt(result[hashKeys[i]], 10);
                    if (timestamp < before) {
                        commitsInfo.push({
                            hash: hashKeys[i],
                            time: timestamp
                        });
                    }
                }

                commitsInfo.sort(function (a, b) {
                    return b.time - a.time;
                });

                hashArray = commitsInfo.slice(0, number).map(function (commitInfo) {
                    return commitInfo.hash;
                });

                if (hashArray.length > 0) {
                    hashArray.unshift(projectId);
                    return Q.ninvoke(adapter.client, 'hmget', hashArray);
                } else {
                    return [];
                }
            })
            .then(function (commitObjects) {
                return commitObjects.map(function (commitObject) {
                    return JSON.parse(commitObject);
                });
            })
            .nodeify(callback);
    };

    this.createTag = function (name, commitHash, callback) {
        var deferred = Q.defer();

        Q.ninvoke(adapter.client, 'hsetnx', projectId + adapter.CONSTANTS.TAGS, name, commitHash)
            .then(function (result) {
                // 1 if field is a new field in the hash and value was set.
                // 0 if field already exists in the hash and no operation was performed.
                if (result === 1) {
                    deferred.resolve();
                } else {
                    deferred.reject(new Error('Tag already exists [' + name + ']'));
                }
            })
            .catch(deferred.reject);

        return deferred.promise.nodeify(callback);
    };

    this.deleteTag = function (name, callback) {
        return Q.ninvoke(adapter.client, 'hdel', projectId + adapter.CONSTANTS.TAGS, name)
            .nodeify(callback);
    };

    this.getTags = function (callback) {
        return Q.ninvoke(adapter.client, 'hgetall', projectId + adapter.CONSTANTS.TAGS)
            .then(function (result) {
                return result || {};
            })
            .nodeify(callback);
    };
}
607200
function postprocessProgram(program) {
      var body = program.body;

      if (body.length === 0) {
        return;
      }

      if (usesMorph(body[0])) {
        body.unshift(buildText(''));
      }

      if (usesMorph(body[body.length-1])) {
        body.push(buildText(''));
      }
    }
231775
async function runProgram() {
    const args = minimist(process.argv.slice(2));

    if (args.prefix) {
        intercept(function(txt) {
            return `[${pkg.name}]\n${txt}`;
        });
    }

    let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` })
                        .catch(error => pkg.version);
    if (semver.gt(latest, pkg.version)) {
        process.stderr.write(chalk.default.white(`\n     Update available `));
        process.stderr.write(chalk.default.grey(`${pkg.version}`));
        process.stderr.write(chalk.default.white(` -> `));
        process.stderr.write(chalk.default.greenBright(`${latest}\n`));
        process.stderr.write(chalk.default.white(`     Run `));
        process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
        process.stderr.write(chalk.default.white(`to update.\n`));
    }

    if (args.version || args.v) {
        process.stdout.write(pkg.version);
        return 0;
    }

    if (args.h || args.help) {
        help(process.stdout);
        return 0;
    }

    if (args.f || args.folder) {
        let inputDir = args.f.trim();
        let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./";
        if (outputDir.substr(0, 2) === "./") {
            outputDir = path.resolve(process.cwd(), outputDir.substr(2))
        }
        const len = await processFiles(inputDir, outputDir);
        process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`);
        return len;
    }
    else {
        const fileContents = await getInput(args);
        if (fileContents) {
            const activities = await chatdown(fileContents, args);
            const writeConfirmation = await writeOut(activities, args);

            if (typeof writeConfirmation === 'string') {
                process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`);
            }
            return 0;
        }
        else {
            help();
            return -1;
        }
    }
}