Runs through a questionnaire to set up your project's deploy settings
329591
def init(provider=None):
    
    if os.path.exists(DEPLOY_YAML):
        _yellow("\nIt looks like you've already gone through the questionnaire.")
        cont = prompt("Do you want to go through it again and overwrite the current one?", default="No")

        if cont.strip().lower() == "no":
            return None
    _green("\nWelcome to the django-deployer!")
    _green("\nWe need to ask a few questions in order to set up your project to be deployed to a PaaS provider.")

    # TODO: identify the project dir based on where we find the settings.py or urls.py

    django_settings = prompt(
        "* What is your Django settings module?",
        default="settings",
        validate=_validate_django_settings
    )

    managepy = prompt(
        "* Where is your manage.py file?",
        default="./manage.py",
        validate=_validate_managepy
    )

    requirements = prompt(
        "* Where is your requirements.txt file?",
        default="requirements.txt",
        validate=_validate_requirements
    )
    # TODO: confirm that the file exists
    # parse the requirements file and warn the user about best practices:
    #   Django==1.4.1
    #   psycopg2 if they selected PostgreSQL
    #   MySQL-python if they selected MySQL
    #   South for database migrations
    #   dj-database-url

    pyversion = prompt("* What version of Python does your app need?", default="Python2.7")

    # TODO: get these values by reading the settings.py file
    static_url = prompt("* What is your STATIC_URL?", default="/static/")
    media_url = prompt("* What is your MEDIA_URL?", default="/media/")

    if not provider:
        provider = prompt("* Which provider would you like to deploy to (dotcloud, appengine, stackato, openshift)?",
                          validate=_validate_providers)

    # Where to place the provider specific questions
    site = {}
    additional_site = {}

    if provider == "appengine":
        applicationid = prompt("* What's your Google App Engine application ID (see https://appengine.google.com/)?", validate=r'.+')
        instancename = prompt("* What's the full instance ID of your Cloud SQL instance\n"
                              "(should be in format \"projectid:instanceid\" found at https://code.google.com/apis/console/)?", validate=r'.+:.+')
        databasename = prompt("* What's your database name?", validate=r'.+')
        sdk_location = prompt("* Where is your Google App Engine SDK location?",
                              default="/usr/local/google_appengine",
                              validate=r'.+'  # TODO: validate that this path exists
                              )

        additional_site.update({
            # quotes for the yaml issue
            'application_id': applicationid,
            'instancename': instancename,
            'databasename': databasename,
            'sdk_location': sdk_location,
        })

        # only option with Google App Engine is MySQL, so we'll just hardcode it
        site = {
            'database': 'MySQL'
        }

    elif provider == "openshift":
        application_name = prompt("* What is your openshift application name?")

        site = {
            'application_name': application_name
        }

    else:
        database = prompt("* What database does your app use?", default="PostgreSQL")
        site = {
            'database': database,
        }

    # TODO: add some validation that the admin password is valid
    # TODO: let the user choose the admin username instead of hardcoding it to 'admin'
    admin_password = prompt("* What do you want to set as the admin password?",
                            validate=_validate_admin_password
                            )

    import random
    SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
    SECRET_KEY = "'" + SECRET_KEY + "'"

    site.update({
        'pyversion': pyversion,
        'django_settings': django_settings,
        'managepy': managepy,
        'requirements': requirements,
        'static_url': static_url,
        'media_url': media_url,
        'provider': provider,
        'admin_password': admin_password,
        'secret_key': SECRET_KEY,
    })

    site.update(additional_site)

    _create_deploy_yaml(site)

    return site
731785
def load_settings(self, settings_file=None, session=None):
        

        # Ensure we're passed a valid settings file.
        if not settings_file:
            settings_file = self.get_json_or_yaml_settings()
        if not os.path.isfile(settings_file):
            raise ClickException("Please configure your zappa_settings file.")

        # Load up file
        self.load_settings_file(settings_file)

        # Make sure that the stages are valid names:
        for stage_name in self.zappa_settings.keys():
            try:
                self.check_stage_name(stage_name)
            except ValueError:
                raise ValueError("API stage names must match a-zA-Z0-9_ ; '{0!s}' does not.".format(stage_name))

        # Make sure that this stage is our settings
        if self.api_stage not in self.zappa_settings.keys():
            raise ClickException("Please define stage '{0!s}' in your Zappa settings.".format(self.api_stage))

        # We need a working title for this project. Use one if supplied, else cwd dirname.
        if 'project_name' in self.stage_config: # pragma: no cover
            # If the name is invalid, this will throw an exception with message up stack
            self.project_name = validate_name(self.stage_config['project_name'])
        else:
            self.project_name = self.get_project_name()

        # The name of the actual AWS Lambda function, ex, 'helloworld-dev'
        # Assume that we already have have validated the name beforehand.
        # Related:  https://github.com/Miserlou/Zappa/pull/664
        #           https://github.com/Miserlou/Zappa/issues/678
        #           And various others from Slack.
        self.lambda_name = slugify.slugify(self.project_name + '-' + self.api_stage)

        # Load stage-specific settings
        self.s3_bucket_name = self.stage_config.get('s3_bucket', "zappa-" + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(9)))
        self.vpc_config = self.stage_config.get('vpc_config', {})
        self.memory_size = self.stage_config.get('memory_size', 512)
        self.app_function = self.stage_config.get('app_function', None)
        self.exception_handler = self.stage_config.get('exception_handler', None)
        self.aws_region = self.stage_config.get('aws_region', None)
        self.debug = self.stage_config.get('debug', True)
        self.prebuild_script = self.stage_config.get('prebuild_script', None)
        self.profile_name = self.stage_config.get('profile_name', None)
        self.log_level = self.stage_config.get('log_level', "DEBUG")
        self.domain = self.stage_config.get('domain', None)
        self.base_path = self.stage_config.get('base_path', None)
        self.timeout_seconds = self.stage_config.get('timeout_seconds', 30)
        dead_letter_arn = self.stage_config.get('dead_letter_arn', '')
        self.dead_letter_config = {'TargetArn': dead_letter_arn} if dead_letter_arn else {}
        self.cognito = self.stage_config.get('cognito', None)
        self.num_retained_versions = self.stage_config.get('num_retained_versions',None)

        # Check for valid values of num_retained_versions
        if self.num_retained_versions is not None and type(self.num_retained_versions) is not int:
            raise ClickException("Please supply either an integer or null for num_retained_versions in the zappa_settings.json. Found %s" % type(self.num_retained_versions))
        elif type(self.num_retained_versions) is int and self.num_retained_versions<1:
            raise ClickException("The value for num_retained_versions in the zappa_settings.json should be greater than 0.")

        # Provide legacy support for `use_apigateway`, now `apigateway_enabled`.
        # https://github.com/Miserlou/Zappa/issues/490
        # https://github.com/Miserlou/Zappa/issues/493
        self.use_apigateway = self.stage_config.get('use_apigateway', True)
        if self.use_apigateway:
            self.use_apigateway = self.stage_config.get('apigateway_enabled', True)
        self.apigateway_description = self.stage_config.get('apigateway_description', None)

        self.lambda_handler = self.stage_config.get('lambda_handler', 'handler.lambda_handler')
        # DEPRECATED. https://github.com/Miserlou/Zappa/issues/456
        self.remote_env_bucket = self.stage_config.get('remote_env_bucket', None)
        self.remote_env_file = self.stage_config.get('remote_env_file', None)
        self.remote_env = self.stage_config.get('remote_env', None)
        self.settings_file = self.stage_config.get('settings_file', None)
        self.django_settings = self.stage_config.get('django_settings', None)
        self.manage_roles = self.stage_config.get('manage_roles', True)
        self.binary_support = self.stage_config.get('binary_support', True)
        self.api_key_required = self.stage_config.get('api_key_required', False)
        self.api_key = self.stage_config.get('api_key')
        self.endpoint_configuration = self.stage_config.get('endpoint_configuration', None)
        self.iam_authorization = self.stage_config.get('iam_authorization', False)
        self.cors = self.stage_config.get("cors", False)
        self.lambda_description = self.stage_config.get('lambda_description', "Zappa Deployment")
        self.environment_variables = self.stage_config.get('environment_variables', {})
        self.aws_environment_variables = self.stage_config.get('aws_environment_variables', {})
        self.check_environment(self.environment_variables)
        self.authorizer = self.stage_config.get('authorizer', {})
        self.runtime = self.stage_config.get('runtime', get_runtime_from_python_version())
        self.aws_kms_key_arn = self.stage_config.get('aws_kms_key_arn', '')
        self.context_header_mappings = self.stage_config.get('context_header_mappings', {})
        self.xray_tracing = self.stage_config.get('xray_tracing', False)
        self.desired_role_arn = self.stage_config.get('role_arn')

        # Load ALB-related settings
        self.use_alb = self.stage_config.get('alb_enabled', False)
        self.alb_vpc_config = self.stage_config.get('alb_vpc_config', {})

        # Additional tags
        self.tags = self.stage_config.get('tags', {})

        desired_role_name = self.lambda_name + "-ZappaLambdaExecutionRole"
        self.zappa = Zappa( boto_session=session,
                            profile_name=self.profile_name,
                            aws_region=self.aws_region,
                            load_credentials=self.load_credentials,
                            desired_role_name=desired_role_name,
                            desired_role_arn=self.desired_role_arn,
                            runtime=self.runtime,
                            tags=self.tags,
                            endpoint_urls=self.stage_config.get('aws_endpoint_urls',{}),
                            xray_tracing=self.xray_tracing
                        )

        for setting in CUSTOM_SETTINGS:
            if setting in self.stage_config:
                setting_val = self.stage_config[setting]
                # Read the policy file contents.
                if setting.endswith('policy'):
                    with open(setting_val, 'r') as f:
                        setting_val = f.read()
                setattr(self.zappa, setting, setting_val)

        if self.app_function:
            self.collision_warning(self.app_function)
            if self.app_function[-3:] == '.py':
                click.echo(click.style("Warning!", fg="red", bold=True) +
                           " Your app_function is pointing to a " + click.style("file and not a function", bold=True) +
                           "! It should probably be something like 'my_file.app', not 'my_file.py'!")

        return self.zappa
470273
protected function configure(): void
    {
        $this->setName('project:run')
            ->setAliases(['run'])
            ->setDescription(
                'Parses and transforms the given files to a specified location'
            )
            ->setHelp(
                <<<HELP
                phpDocumentor creates documentation from PHP source files. The simplest way
                to use it is:
                
                    <info>$ phpdoc run -d [directory to parse] -t [output directory]</info>
                
                This will parse every file ending with .php, .php3 and .phtml in <directory
                to parse> and then output a HTML site containing easily readable documentation
                in <output directory>.
                
                phpDocumentor will try to look for a phpdoc.dist.xml or phpdoc.xml file in your
                current working directory and use that to override the default settings if
                present. In the configuration file can you specify the same settings (and
                more) as the command line provides.
                
                <comment>Other commands</comment>
                In addition to this command phpDocumentor also supports additional commands:
                
                <comment>Available commands:</comment>
                <info>  help
                  list
                  parse
                  run
                  transform
                <comment>project</comment>
                  project:parse
                  project:run
                  project:transform
                <comment>template</comment>
                  template:generate
                  template:list
                  template:package</info>
                
                You can get a more detailed listing of the commands using the <info>list</info>
                command and get help by prepending the word <info>help</info> to the command
                name.
HELP
            )
            ->addOption(
                'target',
                't',
                InputOption::VALUE_OPTIONAL,
                'Path where to store the generated output'
            )
            ->addOption(
                'cache-folder',
                null,
                InputOption::VALUE_OPTIONAL,
                'Path where to store the cache files'
            )
            ->addOption(
                'filename',
                'f',
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Comma-separated list of files to parse. The wildcards ? and * are supported'
            )
            ->addOption(
                'directory',
                'd',
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Comma-separated list of directories to (recursively) parse'
            )
            ->addOption(
                'encoding',
                null,
                InputOption::VALUE_OPTIONAL,
                'encoding to be used to interpret source files with'
            )
            ->addOption(
                'extensions',
                null,
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Comma-separated list of extensions to parse, defaults to php, php3 and phtml'
            )
            ->addOption(
                'ignore',
                'i',
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Comma-separated list of file(s) and directories (relative to the source-code directory) that will be '
                . 'ignored. Wildcards * and ? are supported'
            )
            ->addOption(
                'ignore-tags',
                null,
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Comma-separated list of tags that will be ignored, defaults to none. package, subpackage and ignore '
                . 'may not be ignored.'
            )
            ->addOption(
                'hidden',
                null,
                InputOption::VALUE_NONE,
                'Use this option to tell phpDocumentor to parse files and directories that begin with a period (.), '
                . 'by default these are ignored'
            )
            ->addOption(
                'ignore-symlinks',
                null,
                InputOption::VALUE_NONE,
                'Ignore symlinks to other files or directories, default is on'
            )
            ->addOption(
                'markers',
                'm',
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Comma-separated list of markers/tags to filter'
            )
            ->addOption(
                'title',
                null,
                InputOption::VALUE_OPTIONAL,
                'Sets the title for this project; default is the phpDocumentor logo'
            )
            ->addOption(
                'force',
                null,
                InputOption::VALUE_NONE,
                'Forces a full build of the documentation, does not increment existing documentation'
            )
            ->addOption(
                'validate',
                null,
                InputOption::VALUE_NONE,
                'Validates every processed file using PHP Lint, costs a lot of performance'
            )
            ->addOption(
                'visibility',
                null,
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Specifies the parse visibility that should be displayed in the documentation (comma separated e.g. '
                . '"public,protected")'
            )
            ->addOption(
                'defaultpackagename',
                null,
                InputOption::VALUE_OPTIONAL,
                'Name to use for the default package.',
                'Default'
            )
            ->addOption(
                'sourcecode',
                null,
                InputOption::VALUE_NONE,
                'Whether to include syntax highlighted source code'
            )
            ->addOption(
                'template',
                null,
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Name of the template to use (optional)'
            )
            ->addOption(
                'parseprivate',
                null,
                InputOption::VALUE_NONE,
                'Whether to parse DocBlocks marked with @internal tag'
            );

        parent::configure();
    }
318534
def prepare_project(project, project_dir, binaries, ips, urls):
    

    # Get Various Lists / Project Waivers
    lists = get_lists.GetLists()

    # Get file name black list and project waivers
    file_audit_list, file_audit_project_list = lists.file_audit_list(project)

    # Get file content black list and project waivers
    flag_list, ignore_list = lists.file_content_list(project)

    # Get File Ignore Lists
    file_ignore = lists.file_ignore()

    ignore_directories = lists.ignore_directories(project)

    # Get URL Ignore Lists
    url_ignore = lists.url_ignore(project)

    # Get IP Ignore Lists
    ip_ignore = lists.ip_ignore(project)

    # Get Binary Ignore Lists
    hashlist = get_lists.GetLists()

    if binaries or ips or urls:
        try:
            apikey = os.environ["VT_KEY"]
        except KeyError:
            logger.error("Please set your virustotal.com API key as an environment variable")
            sys.exit(1)
        try:
            vt_rate_type = config.get('config', 'vt_rate_type')
        except six.moves.configparser.NoSectionError:
            logger.error("A config section is required for vt_rate_type with a public | private option")
            sys.exit(1)

        patten = re.compile(r'\bpublic\b|\bprivate\b')
        if not patten.match(vt_rate_type):
            logger.error("Unrecognized %s option for vt_rate_type", vt_rate_type)
            sys.exit(1)

    # Perform rudimentary scans
    scan_file(project, project_dir, binaries, ips, urls, file_audit_list,
              file_audit_project_list, flag_list, ignore_list, hashlist,
              file_ignore, ignore_directories, url_ignore, ip_ignore, apikey)
983603
def deploy
      connect do |http|
        response = http.post(uri('deploys'), '')
        check response
        log 'Deployed'
      end
    end
604437
def init(ctx, force):
    """"""
    if os.path.exists(PROJECT_CONFIG) and not force:
        click.secho(
            'An existing configuration file was found at "{}".\n'
            .format(PROJECT_CONFIG),
            fg='red', bold=True
        )
        click.secho(
            'Please remove it before in order to run the setup wizard or use\n'
            'the --force flag to overwrite it.'
        )
        ctx.exit(1)

    project_key = click.prompt('Project key on the issue tracker')
    base_branch = click.prompt('Integration branch', default='master')

    virtualenvs = ('.venv', '.env', 'venv', 'env')
    for p in virtualenvs:
        if os.path.exists(os.path.join(p, 'bin', 'activate')):
            venv = p
            break
    else:
        venv = ''
    venv_path = click.prompt('Path to virtual environment', default=venv)

    project_id = click.prompt('Project ID on Harvest', type=int)
    task_id = click.prompt('Task id on Harvest', type=int)

    config = configparser.ConfigParser()

    config.add_section('lancet')
    config.set('lancet', 'virtualenv', venv_path)

    config.add_section('tracker')
    config.set('tracker', 'default_project', project_key)

    config.add_section('harvest')
    config.set('harvest', 'project_id', str(project_id))
    config.set('harvest', 'task_id', str(task_id))

    config.add_section('repository')
    config.set('repository', 'base_branch', base_branch)

    with open(PROJECT_CONFIG, 'w') as fh:
        config.write(fh)

    click.secho('\nConfiguration correctly written to "{}".'
                .format(PROJECT_CONFIG), fg='green')
334860
def deploy_docs():
    
    run('rm -rf ./site/')
    build_docs()
    with util.cd('./site/'):
        run('git init')
        run('echo ".*pyc" > .gitignore')
        run('git config user.name "Travis CI"')
        run('git config user.email "%s"' % os.environ['EMAIL'])
        run('git add .')
        run('git commit -m "Deploy to GitHub Pages"')
        run(
            'git push --force --quiet "https://{GH_TOKEN}@{GH_REF}" '
            'master:gh-pages > /dev/null 2>&1'.format(
                GH_TOKEN=os.environ['GH_TOKEN'],
                GH_REF=os.environ['GH_REF'],
            )
        )
205343
public function setupCommand() {
		$serverPublicKeyString = Files::getFileContents('resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoServer.pub', FILE_TEXT);
		if ($serverPublicKeyString === FALSE) {
			$this->outputLine('Could not open resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoServer.pub, exiting.');
			$this->quit(1);
		}

		$serverPublicKeyFingerprint = $this->rsaWalletService->registerPublicKeyFromString($serverPublicKeyString);
		$this->outputLine('Registered sso demo server public key');

		$clientPrivateKeyString = Files::getFileContents('resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoClient.key', FILE_TEXT);
		if ($clientPrivateKeyString === FALSE) {
			$this->outputLine('Could not open resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoClient.key, exiting.');
			$this->quit(2);
		}

		$clientPublicKeyFingerprint = $this->rsaWalletService->registerKeyPairFromPrivateKeyString($clientPrivateKeyString);
		$this->outputLine('Registered demo client key pair');

		$globalSettings = $this->yamlSource->load(FLOW_PATH_CONFIGURATION . '/Settings');
		$globalSettings['Flowpack']['SingleSignOn']['Client']['client']['publicKeyFingerprint'] = $clientPublicKeyFingerprint;
		$globalSettings['Flowpack']['SingleSignOn']['Client']['server']['DemoServer']['publicKeyFingerprint'] = $serverPublicKeyFingerprint;
		$this->yamlSource->save(FLOW_PATH_CONFIGURATION . '/Settings', $globalSettings);
		$this->outputLine('Updated settings');
	}
712753
def deploy_sandbox_shared_setup(verbose=True, app=None, web_procs=1):
    """"""
    if verbose:
        out = None
    else:
        out = open(os.devnull, 'w')

    (id, tmp) = setup_experiment(debug=False, verbose=verbose, app=app)

    # Log in to Heroku if we aren't already.
    log("Making sure that you are logged in to Heroku.")
    ensure_heroku_logged_in()

    # Change to temporary directory.
    cwd = os.getcwd()
    os.chdir(tmp)

    # Commit Heroku-specific files to tmp folder's git repo.
    cmds = ["git init",
            "git add --all",
            'git commit -m "Experiment ' + id + '"']
    for cmd in cmds:
        subprocess.call(cmd, stdout=out, shell=True)
        time.sleep(0.5)

    # Load psiTurk configuration.
    config = PsiturkConfig()
    config.load_config()

    # Initialize the app on Heroku.
    log("Initializing app on Heroku...")
    subprocess.call(
        "heroku apps:create " + id +
        " --buildpack https://github.com/thenovices/heroku-buildpack-scipy",
        stdout=out,
        shell=True)

    database_size = config.get('Database Parameters', 'database_size')

    try:
        if config.getboolean('Easter eggs', 'whimsical'):
            whimsical = "true"
        else:
            whimsical = "false"
    except:
        whimsical = "false"

    # Set up postgres database and AWS/psiTurk environment variables.
    cmds = [
        "heroku addons:create heroku-postgresql:{}".format(database_size),

        "heroku pg:wait",

        "heroku addons:create rediscloud:250",

        "heroku addons:create papertrail",

        "heroku config:set HOST=" +
        id + ".herokuapp.com",

        "heroku config:set aws_access_key_id=" +
        config.get('AWS Access', 'aws_access_key_id'),

        "heroku config:set aws_secret_access_key=" +
        config.get('AWS Access', 'aws_secret_access_key'),

        "heroku config:set aws_region=" +
        config.get('AWS Access', 'aws_region'),

        "heroku config:set psiturk_access_key_id=" +
        config.get('psiTurk Access', 'psiturk_access_key_id'),

        "heroku config:set psiturk_secret_access_id=" +
        config.get('psiTurk Access', 'psiturk_secret_access_id'),

        "heroku config:set auto_recruit=" +
        config.get('Experiment Configuration', 'auto_recruit'),

        "heroku config:set wallace_email_username=" +
        config.get('Email Access', 'wallace_email_address'),

        "heroku config:set wallace_email_key=" +
        config.get('Email Access', 'wallace_email_password'),

        "heroku config:set heroku_email_address=" +
        config.get('Heroku Access', 'heroku_email_address'),

        "heroku config:set heroku_password=" +
        config.get('Heroku Access', 'heroku_password'),

        "heroku config:set whimsical=" + whimsical,
    ]
    for cmd in cmds:
        subprocess.call(cmd + " --app " + id, stdout=out, shell=True)

    # Set the notification URL in the cofig file to the notifications URL.
    config.set(
        "Server Parameters",
        "notification_url",
        "http://" + id + ".herokuapp.com/notifications")

    # Set the database URL in the config file to the newly generated one.
    log("Saving the URL of the postgres database...")
    db_url = subprocess.check_output(
        "heroku config:get DATABASE_URL --app " + id, shell=True)
    config.set("Database Parameters", "database_url", db_url.rstrip())
    subprocess.call("git add config.txt", stdout=out, shell=True),
    time.sleep(0.25)
    subprocess.call(
        'git commit -m "Save URLs for database and notifications"',
        stdout=out,
        shell=True)
    time.sleep(0.25)

    # Launch the Heroku app.
    log("Pushing code to Heroku...")
    subprocess.call("git push heroku HEAD:master", stdout=out,
                    stderr=out, shell=True)

    scale_up_dynos(id)

    time.sleep(8)

    # Launch the experiment.
    log("Launching the experiment on MTurk...")
    subprocess.call(
        'curl --data "" http://{}.herokuapp.com/launch'.format(id),
        shell=True)

    time.sleep(8)

    url = subprocess.check_output("heroku logs --app " + id + " | sort | " +
                                  "sed -n 's|.*URL:||p'", shell=True)

    log("URLs:")
    click.echo(url)

    # Return to the branch whence we came.
    os.chdir(cwd)

    log("Completed deployment of experiment " + id + ".")
984607
def SetupVars(self):
    """"""
    # Python paths chosen to match appveyor:
    # http://www.appveyor.com/docs/installed-software#python

    self.python_dir_64 = args.python64_dir
    self.python_dir_32 = args.python32_dir

    self.virtualenv_bin64 = os.path.join(self.python_dir_64,
                                         r"Scripts\virtualenv.exe")
    self.virtualenv_bin32 = os.path.join(self.python_dir_32,
                                         r"Scripts\virtualenv.exe")

    if args.virtualenv_64bit:
      self.virtualenv64 = args.virtualenv_64bit
    else:
      self.virtualenv64 = os.path.join(args.build_dir, "python_64")
    if args.virtualenv_32bit:
      self.virtualenv32 = args.virtualenv_32bit
    else:
      self.virtualenv32 = os.path.join(args.build_dir, "python_32")

    self.grr_client_build64 = os.path.join(self.virtualenv64,
                                           r"Scripts\grr_client_build.exe")
    self.grr_client_build32 = os.path.join(self.virtualenv32,
                                           r"Scripts\grr_client_build.exe")
    self.pip64 = os.path.join(self.virtualenv64, r"Scripts\pip.exe")
    self.pip32 = os.path.join(self.virtualenv32, r"Scripts\pip.exe")

    self.virtualenv_python64 = os.path.join(self.virtualenv64,
                                            r"Scripts\python.exe")
    self.virtualenv_python32 = os.path.join(self.virtualenv32,
                                            r"Scripts\python.exe")

    self.git = r"C:\Program Files\Git\bin\git.exe"

    self.install_path = r"C:\Windows\System32\GRR"
    self.service_name = "GRR Monitor"

    self.expect_service_running = args.expect_service_running
377100
function configureDocumentation(answers) {
  let docPackage = config.dependencies[answers.runner][answers.docs];
  let ghpagesPackage = config.dependencies[answers.runner]['gh-pages'];

  console.log(chalk.gray(`Installing ${docPackage}...`));
  installPackage(docPackage, false, answers.sudo, 'save-dev');

  console.log(chalk.gray(`Installing ${ghpagesPackage}...`));
  installPackage(ghpagesPackage, false, answers.sudo, 'save-dev');

  if (answers.docs === 'jsdoc') {
    let jsdocConfFile = `${config.path.templates}/${[answers.runner]}/${config.jsdoc.conf}`;

    execSync(`cp ${jsdocConfFile} ./`);
  }

  // Create empty `docs` folder
  execSync('mkdir docs');
}
200135
def run_deploy_website(restart_apache=False, restart_uwsgi=False,
                       restart_nginx=False):
    
    run_git_pull()
    run_pip_install()
    run_rsync_project()
    run_syncdb()
    run_collectstatic()
    if getattr(settings, 'MAKEMESSAGES_ON_DEPLOYMENT', False):
        run_makemessages()
    if getattr(settings, 'COMPILEMESSAGES_ON_DEPLOYMENT', False):
        run_compilemessages()
    if restart_apache:
        run_restart_apache()
    if restart_uwsgi:
        run_restart_uwsgi()
    if restart_nginx:
        run_restart_nginx()
    else:
        run_touch_wsgi()
636065
def run(self):
        

        self.sanity_check()

# TODO - check for devel
#        if not self.version:
#            raise Exception("no version")
# XXX check attr exist
        if not self.release_environment:
            raise Exception("no instance name")

        time_start = time.time()

        cwd = os.getcwd()

        who = getpass.getuser()
        self._make_outdirs()

        append_notices = ""
        if hasattr(self, 'opt_end'):
            append_notices = ". shortened push, only to %s stage" % self.opt_end
        if self.is_devel:
            append_notices += ". devel build"
        if hasattr(self, 'append_notices'):
            append_notices += self.append_notices

        line = "%s %s %s by %s%s" % (
            sys.argv[0], self.version, self.release_environment, who, append_notices)
        b = 'deploy begin %s' % line
        e = 'deploy done %s' % line

        if self.chatty:
            self.alact(b)

        ok = False
        stage_passed = None
        try:
            for stage in self.stages[self.stage_start:self.stage_end]:
                self.debug_msg("stage %s starting" % (stage,))
                getattr(self, stage)()
                self.chdir(cwd)
                stage_passed = stage
                self.debug_msg("stage %s complete" % (stage,))
            ok = True
        finally:
            if not ok:
                if self.chatty:
                    if not stage_passed:
                        self.alact(
                            'deploy failed %s. completed no stages' % line)
                    else:
                        self.alact('deploy failed %s. completed %s' %
                                   (line, stage_passed))
        self.status_msg('[OK]')
        if self.chatty:
            self.alact('%s in %0.3f sec' % (e, time.time() - time_start))

        return 0
361110
def run(**kwargs):
    
    from sampleproject.app import app

    app.update_settings(**kwargs)
    app.run()
455302
function(runs, suites, tests, coverages, logs) {
    debug('setting up Mocha command line reporter');

    runs.on('error', this.proxy('error'));

    runs.on('created', this.proxy('startRun'));
    runs.on('patched', this.proxy('updateRun'));

    suites.on('created', this.proxy('startSuite'));
    suites.on('patched', this.proxy('updateSuite'));

    tests.on('created', this.proxy('startTest'));
    tests.on('patched', this.proxy('updateTest'));

    logs.on('created', this.proxy('captureLog'));

    coverages.on('created', this.proxy('reportCoverage'));

    this.start();
  }
1089050
def set_up(self):
        """"""
        self.path.profile = self.path.gen.joinpath("profile")

        if not self.path.profile.exists():
            self.path.profile.mkdir()

        self.python = hitchpylibrarytoolkit.project_build(
            "strictyaml",
            self.path,
            self.given["python version"],
            {"ruamel.yaml": self.given["ruamel version"]},
        ).bin.python

        self.example_py_code = (
            ExamplePythonCode(self.python, self.path.gen)
            .with_code(self.given.get("code", ""))
            .with_setup_code(
                self.given.get("setup", "")
            )
            .with_terminal_size(160, 100)
            .with_strings(
                yaml_snippet_1=self.given.get("yaml_snippet_1"),
                yaml_snippet=self.given.get("yaml_snippet"),
                yaml_snippet_2=self.given.get("yaml_snippet_2"),
                modified_yaml_snippet=self.given.get("modified_yaml_snippet"),
            )
        )
602107
async function deploy() {
  // Initialize a new repository
  await makeDir('build');
  await spawn('git', ['init', '--quiet'], options);

  // Changing a remote's URL
  let isRemoteExists = false;
  try {
    await spawn(
      'git',
      ['config', '--get', `remote.${remote.name}.url`],
      options,
    );
    isRemoteExists = true;
  } catch (error) {
    /* skip */
  }
  await spawn(
    'git',
    ['remote', isRemoteExists ? 'set-url' : 'add', remote.name, remote.url],
    options,
  );

  // Fetch the remote repository if it exists
  let isRefExists = false;
  try {
    await spawn(
      'git',
      ['ls-remote', '--quiet', '--exit-code', remote.url, remote.branch],
      options,
    );
    isRefExists = true;
  } catch (error) {
    await spawn('git', ['update-ref', '-d', 'HEAD'], options);
  }
  if (isRefExists) {
    await spawn('git', ['fetch', remote.name], options);
    await spawn(
      'git',
      ['reset', `${remote.name}/${remote.branch}`, '--hard'],
      options,
    );
    await spawn('git', ['clean', '--force'], options);
  }

  // Build the project in RELEASE mode which
  // generates optimized and minimized bundles
  process.argv.push('--release');
  if (remote.static) process.argv.push('--static');
  await run(require('./build').default); // eslint-disable-line global-require
  if (process.argv.includes('--static')) {
    await cleanDir('build/*', {
      nosort: true,
      dot: true,
      ignore: ['build/.git', 'build/public'],
    });
    await moveDir('build/public', 'build');
  }

  // Push the contents of the build folder to the remote server via Git
  await spawn('git', ['add', '.', '--all'], options);
  try {
    await spawn('git', ['diff', '--cached', '--exit-code', '--quiet'], options);
  } catch (error) {
    await spawn(
      'git',
      ['commit', '--message', `Update ${new Date().toISOString()}`],
      options,
    );
  }
  await spawn(
    'git',
    ['push', remote.name, `master:${remote.branch}`, '--set-upstream'],
    options,
  );

  // Check if the site was successfully deployed
  const response = await fetch(remote.website);
  console.info(
    `${remote.website} => ${response.status} ${response.statusText}`,
  );
}