Take a config file as input and generate screenshots
434440
def generate_screenshots(self):
        
        headers = {'content-type': 'application/json', 'Accept': 'application/json'}
        resp = requests.post(self.api_url, data=json.dumps(self.config), \
                             headers=headers, auth=self.auth)
        resp = self._process_response(resp)
        return resp.json()
151711
def screenshot(self, filename, scale=1.0, quality=100):
        ''''''
        result = self.server.screenshot(filename, scale, quality)
        if result:
            return result

        device_file = self.server.jsonrpc.takeScreenshot("screenshot.png",
                                                         scale, quality)
        if not device_file:
            return None
        p = self.server.adb.cmd("pull", device_file, filename)
        p.wait()
        self.server.adb.cmd("shell", "rm", device_file).wait()
        return filename if p.returncode is 0 else None
858434
def generate_background
      background = MiniMagick::Image.open(fetch_config['background'])

      if background.height != screenshot.size[1]
        background.resize("#{screenshot.size[0]}x#{screenshot.size[1]}^") # `^` says it should fill area
        background.merge!(["-gravity", "center", "-crop", "#{screenshot.size[0]}x#{screenshot.size[1]}+0+0"]) # crop from center
      end
      background
    end
883435
def generate_readme(self):
        
        print("## Examples of settings runtime params")
        print("### Command-line parameters")
        print("```")
        self.generate_command()
        print("```")
        print("###  Environment variables")
        print("```")
        self.generate_env()
        print("```")
        print("###  ini file")
        print("```")
        self.generate_ini()
        print("```")
        print("###  docker run")
        print("```")
        self.generate_docker_run()
        print("```")
        print("###  docker compose")
        print("```")
        self.generate_docker_compose()
        print("```")
        print("###  kubernetes")
        print("```")
        self.generate_kubernetes()
        print("```")
        print("###  drone plugin")
        print("```")
        self.generate_drone_plugin()
        print("```")
644165
def create_config_file(filename):
    
    import textwrap
    from six.moves.urllib import parse

    if not os.path.exists(filename):
        old_default_config_file = os.path.join(os.path.dirname(filename),
                                               '.tksrc')
        if os.path.exists(old_default_config_file):
            upgrade = click.confirm("\n".join(textwrap.wrap(
                "It looks like you recently updated Taxi. Some "
                "configuration changes are required. You can either let "
                "me upgrade your configuration file or do it "
                "manually.")) + "\n\nProceed with automatic configuration "
                "file upgrade?", default=True
            )

            if upgrade:
                settings = Settings(old_default_config_file)
                settings.convert_to_4()
                with open(filename, 'w') as config_file:
                    settings.config.write(config_file)
                os.remove(old_default_config_file)
                return
            else:
                print("Ok then.")
                sys.exit(0)

        welcome_msg = "Welcome to Taxi!"
        click.secho(welcome_msg, fg='green', bold=True)
        click.secho('=' * len(welcome_msg) + '\n', fg='green', bold=True)

        click.echo(click.wrap_text(
            "It looks like this is the first time you run Taxi. You will need "
            "a configuration file ({}) in order to proceed. Please answer a "
            "few questions to create your configuration file.".format(
                filename
            )
        ) + '\n')

        config = pkg_resources.resource_string('taxi', 'etc/taxirc.sample').decode('utf-8')
        context = {}
        available_backends = plugins_registry.get_available_backends()

        context['backend'] = click.prompt(
            "Backend you want to use (choices are %s)" %
            ', '.join(available_backends),
            type=click.Choice(available_backends)
        )
        context['username'] = click.prompt("Username or token")
        context['password'] = parse.quote(
            click.prompt("Password (leave empty if you're using"
                         " a token)", hide_input=True, default=''),
            safe=''
        )
        # Password can be empty in case of token auth so the ':' separator
        # is not included in the template config, so we add it if the user
        # has set a password
        if context['password']:
            context['password'] = ':' + context['password']

        context['hostname'] = click.prompt(
            "Hostname of the backend (eg. timesheets.example.com)",
            type=Hostname()
        )

        editor = Editor().get_editor()
        context['editor'] = click.prompt(
            "Editor command to edit your timesheets", default=editor
        )

        templated_config = config.format(**context)

        directory = os.path.dirname(filename)
        if not os.path.exists(directory):
            os.makedirs(directory)

        with open(filename, 'w') as f:
            f.write(templated_config)
    else:
        settings = Settings(filename)
        conversions = settings.needed_conversions

        if conversions:
            for conversion in conversions:
                conversion()

            settings.write_config()
1030135
def main():
    """"""
    coloredlogs.install(level='debug')
    arguments = sys.argv[1:]
    if arguments:
        interpret_script(arguments[0])
    else:
        logger.notice(compact("""
            This script requires the 'urxvt' terminal emulator and the
            ImageMagick command line programs 'convert' and 'import' to be
            installed. Don't switch windows while the screenshots are being
            generated because it seems that 'import' can only take screenshots
            of foreground windows.
        """))
        generate_screenshots()
9065
def screenshot(fname):
    
    try:
        im = ImageGrab.grab()
        im.save(fname)
    except Exception as ex:
        print('image_tools.screenshot:cant create screenshot ' + str(ex))
930700
def GenerateFile(self, input_filename=None, output_filename=None):
    """"""
    if input_filename is None:
      input_filename = output_filename + ".in"
    if output_filename[-3:] == ".in":
      output_filename = output_filename[:-3]
    logging.debug("Generating file %s from %s", output_filename, input_filename)

    with io.open(input_filename, "r") as fd:
      data = fd.read()

    with io.open(output_filename, "w") as fd:
      fd.write(config.CONFIG.InterpolateValue(data, context=self.context))
1131720
function(configPath, configNames, config) {
	var configsUsed = [];

	config = config || projectConfig;

	// work with the raw configuration object
	if (config && config.root) {
		config = config.root();
	}

	config = convict(config);
	configPath = path.resolve(appPath, configPath);
	configNames = configNames || [];

	configNames.forEach(function(configName) {
		var file;

		// Ignore local config in production mode
		if (configName == 'local' && nodeEnv === 'production') { return; }

		file = path.join(configPath, 'config-'+configName);
		file += configName === 'default' ? '.js' : '.json';

		if (fs.existsSync(file)) {

			if (configName === 'default') {
				config = convict( require(file) );
				config.load(dynamicDefaults);
			}
			else {
				config.loadFile( file );
			}

			// logging
			configName === 'default' ? configsUsed.push('xtc defaults') : configsUsed.push(configName);
		}
	});

	// be informative
	!process.env.testRun
		&& configsUsed.push('env', 'args')
		&& console.log('configuration:', configsUsed.join(' < '));

	return config;
}
525241
def console_script():
    '''
        
    '''
    if len(sys.argv) == 1:
        print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]")
        return 0

    if "help" in sys.argv[1]:
        print("configcreate <server_url>:  Create initial config file for the OpenSubmit executor.")
        print("configtest:                 Check config file for correct installation of the OpenSubmit executor.")
        print("run:                        Fetch and run code to be tested from the OpenSubmit web server. Suitable for crontab.")
        print("test <dir>:                 Run test script from a local folder for testing purposes.")
        print("unlock:                     Break the script lock, because of crashed script.")
        print("help:                       Print this help")
        print(
            "-c config_file    Configuration file to be used (default: {0})".format(CONFIG_FILE_DEFAULT))
        return 0

    # Translate legacy commands
    if sys.argv[1] == "configure":
        sys.argv[1] = 'configtest'

    config_fname = get_config_fname(sys.argv)

    if "configcreate" in sys.argv[1]:
        print("Creating config file at " + config_fname)

        server_url = sys.argv[2]

        if create_config(config_fname, override_url=server_url):
            print("Config file created, fetching jobs from " + server_url)
            return 0
        else:
            return 1

    if "configtest" in sys.argv[1]:
        print("Testing config file at " + config_fname)

        if has_config(config_fname):
            config = read_config(config_fname)
            if not check_config(config):
                return 1
        else:
            print("ERROR: Seems like the config file %s does not exist. Call 'opensubmit-exec configcreate <server_url>' first." %
                  config_fname)
            return 1

        print("Sending host information update to server ...")
        send_hostinfo(config)
        return 0

    if "unlock" in sys.argv[1]:
        config = read_config(config_fname)
        break_lock(config)
        return 0

    if "run" in sys.argv[1]:
        config = read_config(config_fname)
        # Perform additional precautions for unattended mode in cron
        kill_longrunning(config)
        with ScriptLock(config):
            download_and_run(config)
        return 0

    if "test" in sys.argv[1]:
        config = read_config(config_fname)
        copy_and_run(config, sys.argv[2])
        return 0
563990
function () {
      this.cfg = {};

      // Copy from prompt settings
      Object.keys(this.settings).forEach(function (key) {
        this.cfg[key] = this.settings[key];
      }.bind(this));

      // Boolean config
      options.forEach(function (option) {
        var name = option.name;
        option.choices.forEach(function (choice) {
          var value = choice.value;
          switch (option.type) {
            case 'list':
              this.cfg[value] = value === this.cfg[name];
              break;
            case 'checkbox':
              this.cfg[value] = _.includes(this.cfg[name], value);
              break;
          }
        }.bind(this));
      }.bind(this));

      // Extra config
      this.cfg.slugName = _s.slugify(this.cfg.name);
      this.cfg.testing = this.cfg.mocha || this.cfg.jasmine;
      this.cfg.cssSourceMap = (this.cfg.css && this.cfg.autoprefixer) ||
                              this.cfg.sass ||
                              (this.cfg.less && (this.cfg.autoprefixer || this.cfg.cssmin));
      this.cfg.jsSourceMap = this.cfg.coffee;
    }
456142
def screenshot(self, scale=None, quality=None):
        
        output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
        screenshot_path = '%s%s%s.png' % (output_dir, os.sep, st)
        self.device.screenshot(screenshot_path, scale, quality)
        logger.info('\n<a href="%s">%s</a><br><img src="%s">' % (screenshot_path, st, screenshot_path), html=True)
463783
def fromConfigFile(filename = DEFAULT_CONFIG_FILE):
    
    parser = SafeConfigParser()
    section = 'fenixedu'
    parser.read(filename)

    client_id = parser.get(section, 'client_id')
    redirect_uri = parser.get(section, 'redirect_uri')
    client_secret = parser.get(section, 'client_secret')

    base_url = parser.get(section, 'base_url')
    api_endpoint = parser.get(section, 'api_endpoint')
    api_version = parser.get(section, 'api_version')

    return FenixEduConfiguration(client_id = client_id,
                                  redirect_uri = redirect_uri,
                                  client_secret = client_secret,
                                  base_url = base_url,
                                  api_endpoint = api_endpoint,
                                  api_version = api_version)
992323
function runCapturingProcess(options, config, outputFile, base64, onFinish) {
    const scriptFile = utils.filePath(SCRIPT_FILE),
          command = cliCommand(config).split(/[ ]+/),
          cmd = _.union(command, [scriptFile, base64, outputFile]),
          opts = {
              timeout: config.timeout
          };

    logger.debug(
        'Options for script: %s, base64: %s, command: %s',
        JSON.stringify(options), base64, JSON.stringify(cmd)
    );

    utils.execProcess(cmd, opts, (error) => {
        if (config.compress) {
            minimizeImage(outputFile, config.storage, () => onFinish(error));
        } else {
            onFinish(error);
        }
    });
}
871596
def cfgdump(path, config):
    """"""
    dump = yaml_dump(config)
    if not os.path.exists(path):
        os.makedirs(path)
    with open(os.path.join(path, 'config.yaml'), 'w') as outf:
        outf.write(dump)
    print(dump)
430858
def store_config(filepath, hash, options = {})
      content  = "# " + File.basename(filepath) + "\n"
      content += "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated\n"
      if options[:header]
        options[:header].split("\n").each { |line| content += "# #{line}" }
      end
      content += hash.to_yaml
      show_diff_and_write(content, filepath, options)
      # File.open( filepath, 'w') do |f|
      #     f.print "# ", File.basename(filepath), "\n"
      #     f.puts "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated"
      #     if options[:header]
      #         options[:header].split("\n").each do |line|
      #             f.puts "# #{line}"
      #         end
      #     end
      #     f.puts hash.to_yaml
      # end
    end
616295
def create_assets_env(generator):
    """"""

    theme_static_dir = generator.settings['THEME_STATIC_DIR']
    assets_destination = os.path.join(generator.output_path, theme_static_dir)
    generator.env.assets_environment = Environment(
        assets_destination, theme_static_dir)

    if 'ASSET_CONFIG' in generator.settings:
        for item in generator.settings['ASSET_CONFIG']:
            generator.env.assets_environment.config[item[0]] = item[1]

    if 'ASSET_BUNDLES' in generator.settings:
        for name, args, kwargs in generator.settings['ASSET_BUNDLES']:
            generator.env.assets_environment.register(name, *args, **kwargs)

    if 'ASSET_DEBUG' in generator.settings:
        generator.env.assets_environment.debug = generator.settings['ASSET_DEBUG']
    elif logging.getLevelName(logger.getEffectiveLevel()) == "DEBUG":
        generator.env.assets_environment.debug = True

    for path in (generator.settings['THEME_STATIC_PATHS'] +
                 generator.settings.get('ASSET_SOURCE_PATHS', [])):
        full_path = os.path.join(generator.theme, path)
        generator.env.assets_environment.append_path(full_path)