Write main exception template file
349192
protected function writeMainExceptionTemplate()
	{
		$data = $this->mainExceptionData;

		$filePath = $this->outputPath . DIRECTORY_SEPARATOR . 'Exceptions' . DIRECTORY_SEPARATOR . 'ApiException.php';

		if (!is_null($this->outputInterface)) {
			$this->outputInterface->writeln('<info>Writing ' . $filePath . '</info>');
		}

		file_put_contents($filePath, $this->mainExceptionTemplate->render($data));
	}
1238746
public int writeTemplateEntry(String template, Object entry) {
        int returnCode = htod.writeTemplateEntry(template, entry);
        if (returnCode == HTODDynacache.DISK_EXCEPTION) {
            stopOnError(this.htod.diskCacheException);
        }
        return returnCode;
    }
1289234
public void processDynamicFile(Map<String, Object> context, TemplatePack templatePack, Template template) throws Exception {
        try {
            if (!(template.getName().indexOf(".vm.") >= 0 || template.getName().endsWith(".vm"))) {
                throw new IllegalStateException("not a velocity template!: " + template.getName());
            }

            String evaluatedTemplate = null;

            try {
                evaluatedTemplate = velocityGenerator.evaluate(context, templatePack, template);
            } catch (StopFileReachedException e) {
                return;
            }

            if (currentFullFilename.endsWith(".donotgenerate")) {
                return;
            }
            if (isBlank(currentFullFilename)) {
                log.error("In " + templatePack.getName() + ":" + template.getName() + "  target filename is missing");
                return;
            }
            if (!config.getCelerio().getConfiguration().hasFilename(templatePack.getName(), currentFullFilename)) {
                packDebug(templatePack, "SKIPPING:" + currentFullFilename);
                return;
            }

            if (currentEnableDynamicImport) {
                if (ImportsContext.getCurrentImportsHolder().hasImports()) {
                    evaluatedTemplate = evaluatedTemplate.replace(DYNA_IMPORTS_TAG, "\n" + ImportsContext.getCurrentImportsHolder().toJavaImportString());
                } else {
                    evaluatedTemplate = evaluatedTemplate.replace(DYNA_IMPORTS_TAG, "");
                }
            }

            if (currentFullFilename.endsWith(".java")) {
                evaluatedTemplate = eclipseCodeFormatter.format(evaluatedTemplate);
            } else if (currentFullFilename.endsWith(".xml") || currentFullFilename.endsWith(".xhtml")) {
                evaluatedTemplate = xmlCodeFormatter.format(evaluatedTemplate);
            }

            // generated content is in the string writer
            if (log.isDebugEnabled()) {
                packDebug(templatePack, "processing template " + template.getName() + " (" + currentFullFilename + ")");
            }
            try {
                contentWriter.processFile(outputResult, templatePack, template, evaluatedTemplate.getBytes("UTF-8"), currentFullFilename);
            } catch (Exception e) {
                log.error("In " + templatePack.getName() + ":" + template.getName() + " template, got exception " + e.getMessage(), e);
            }

        } finally {
            clearDynamicFileContext();
        }
    }
764893
void write(CallInfo callInfo, SQLException e) {
    Element rootNode = root(callInfo);
    Element exNode = createNode(rootNode, DATABASE_EXCEPTION_TAG);
    StringWriter sw = new StringWriter();
    sw.append('\n');
    e.printStackTrace(new PrintWriter(sw));
    exNode.appendChild(xmlDoc.createCDATASection(sw.toString()));
    flush(rootNode);
  }
754144
def template_engine(self, entry, startnode):
        

        # self.println("-----")
        # print("XXX", startnode)

        fmt = entry[0]
        arg = 1
        i = 0

        m = escape.search(fmt)
        while m:
            i = m.end()
            self.write(m.group('prefix'))

            typ = m.group('kind') or '{'
            node = startnode
            try:
                if m.group('child'):
                    node = node[int(m.group('child'))]
            except:
                print(node.__dict__)
                raise

            if   typ == '%':	self.write('%')
            elif typ == '+':	self.indentMore()
            elif typ == '-':	self.indentLess()
            elif typ == '|':	self.write(self.indent)
            elif typ == 'c':
                index = entry[arg]
                if isinstance(index, tuple):
                    assert node[index[0]] == index[1], (
                        "at %s[%d], %s vs %s" % (
                            node.kind, arg, node[index[0]].kind, index[1])
                        )
                    index = index[0]
                if isinstance(index, int):
                    self.preorder(node[index])
                arg += 1
            elif typ == 'p':
                p = self.prec
                length = len(entry)
                if length == 3:
                    (index, self.prec, name) = entry[arg]
                    assert node[index] == name, (
                        "at %s[%d], %s vs %s" % (
                            node.kind, arg, node[index[0]].kind, index[1])
                        )
                elif length == 2:
                    (index, self.prec) = entry[arg]
                else:
                    raise RuntimeError("Invalid %%p tuple length %d; length should be 1 or 2"
                                       % length)

                self.preorder(node[index])
                self.prec = p
                arg += 1
            elif typ == 'C':
                low, high, sep = entry[arg]
                remaining = len(node[low:high])
                for subnode in node[low:high]:
                    self.preorder(subnode)
                    remaining -= 1
                    if remaining > 0:
                        self.write(sep)
                arg += 1
            elif typ == 'D':
                low, high, sep = entry[arg]
                remaining = len(node[low:high])
                for subnode in node[low:high]:
                    remaining -= 1
                    if len(subnode) > 0:
                        self.preorder(subnode)
                        if remaining > 0:
                            self.write(sep)
                            pass
                        pass
                    pass
                arg += 1
            elif typ == 'x':
                # This code is only used in fragments
                assert isinstance(entry[arg], tuple)
                arg += 1
            elif typ == 'P':
                p = self.prec
                low, high, sep, self.prec = entry[arg]
                remaining = len(node[low:high])
                # remaining = len(node[low:high])
                for subnode in node[low:high]:
                    self.preorder(subnode)
                    remaining -= 1
                    if remaining > 0:
                        self.write(sep)
                self.prec = p
                arg += 1
            elif typ == '{':
                d = node.__dict__
                expr = m.group('expr')
                try:
                    self.write(eval(expr, d, d))
                except:
                    print(node)
                    raise
            m = escape.search(fmt, i)
        self.write(fmt[i:])
1183447
def render_and_write(template_dir, path, context):
    
    env = Environment(loader=FileSystemLoader(template_dir))
    template_file = os.path.basename(path)
    template = env.get_template(template_file)
    log('Rendering from template: %s' % template.name, level=DEBUG)
    rendered_content = template.render(context)
    if not rendered_content:
        log("Render returned None - skipping '%s'" % path,
            level=WARNING)
        return

    write(path, rendered_content.encode('utf-8').strip())
    log('Wrote template %s' % path, level=DEBUG)
510548
protected void rrdToolUpdate(String template, String data) throws Exception {
		List<String> commands = new ArrayList<>();
		commands.add(binaryPath + "/rrdtool");
		commands.add("update");
		commands.add(outputFile.getCanonicalPath());
		commands.add("-t");
		commands.add(template);
		commands.add("N:" + data);

		ProcessBuilder pb = new ProcessBuilder(commands);
		Process process = pb.start();
		checkErrorStream(process);
	}
1168430
public static void main(String[] args) throws Exception {
		int argCount = 0;
		boolean sortClasses = false;
		for (; argCount < args.length; argCount++) {
			String arg = args[argCount];
			if (arg.equals("-s")) {
				sortClasses = true;
			} else {
				break;
			}
		}
		// we should have one arg left
		if (argCount != args.length - 1) {
			throw new IllegalArgumentException("Usage: OrmLiteConfigUtil [-s] config-file-name");
		}
		writeConfigFile(args[argCount], sortClasses);
	}
806065
public void updateErrorTemplate(int statusCode, String template) throws SecurityException {
	checkWriteAccess();
	boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_DEBUGGING);
	if (!hasAccess) throw new SecurityException("no access to change error settings");

	Element error = _getRootElement("error");
	// if(template.trim().length()>0)
	error.setAttribute("template-" + statusCode, template);
    }
947211
def write_template(data, results_dir, parent):
    
    print("Generating html report...")
    partial = time.time()
    j_env = Environment(loader=FileSystemLoader(os.path.join(results_dir, parent, 'templates')))
    template = j_env.get_template('report.html')

    report_writer = ReportWriter(results_dir, parent)
    report_writer.write_report(template.render(data))
    print("HTML report generated in {} seconds\n".format(time.time() - partial))
1188591
def _write_template(upgrade_file, name, depends_on, repository, auto=False):
    """"""
    if auto:
        # Ensure all models are loaded
        from invenio_db import models
        list(models)
        template_args = produce_upgrade_operations()
        operations_str = template_args['upgrades']
        import_str = template_args['imports']
    else:
        operations_str = "    pass"
        import_str = ""

    with open(upgrade_file, 'w') as f:
        f.write(UPGRADE_TEMPLATE % {
            'depends_on': depends_on,
            'repository': repository,
            'year': date.today().year,
            'operations': operations_str,
            'imports': import_str,
            'cls': ''.join(w.capitalize() or '_' for w in name.split('_'))
        })
1009703
def print_exception(*args, file=None, **kwargs):
    
    for line in format_exception(*args, **kwargs):
        vtml.vtmlprint(line, file=file)
802947
private String generateContent(String templateFile) {
		try {
			GStringTemplateEngine gStringEngine = new GStringTemplateEngine();
			URL url = loadTemplate(templateFolder + "/" + templateFile);
			if (url == null) {
				logWarn("NO TEMPLATE FOUND FOR " + templateFile);
			} else {
				logDebug("Loaded template: " + url.getPath());
			}
			if (url == null) return null;
			
			Template template = gStringEngine.createTemplate(url);
			return template.make(modelMap).toString();
		} catch (Exception e) {
			ps.println("### ERROR: Failed generate templatefile: " + templateFile);
			e.printStackTrace(ps);
			return null;
		}
	}
382138
public void dumpTemplate(String templatePath) throws IOException
    {
        BufferedWriter bw = IOUtil.newBufferedWriter(templatePath);
        String template = getTemplate();
        bw.write(template);
        bw.close();
    }
452309
def __main(draft, directory, project_name, project_version, project_date, answer_yes):
    
    directory = os.path.abspath(directory)
    config = load_config(directory)
    to_err = draft

    click.echo("Loading template...", err=to_err)
    if config["template"] is None:
        template = pkg_resources.resource_string(
            __name__, "templates/template.rst"
        ).decode("utf8")
    else:
        with open(config["template"], "rb") as tmpl:
            template = tmpl.read().decode("utf8")

    click.echo("Finding news fragments...", err=to_err)

    definitions = config["types"]

    if config.get("directory"):
        base_directory = os.path.abspath(config["directory"])
        fragment_directory = None
    else:
        base_directory = os.path.abspath(
            os.path.join(directory, config["package_dir"], config["package"])
        )
        fragment_directory = "newsfragments"

    fragments, fragment_filenames = find_fragments(
        base_directory, config["sections"], fragment_directory, definitions
    )

    click.echo("Rendering news fragments...", err=to_err)
    fragments = split_fragments(fragments, definitions)
    rendered = render_fragments(
        # The 0th underline is used for the top line
        template,
        config["issue_format"],
        fragments,
        definitions,
        config["underlines"][1:],
        config["wrap"],
    )

    if project_version is None:
        project_version = get_version(
            os.path.join(directory, config["package_dir"]), config["package"]
        )

    if project_name is None:
        package = config.get("package")
        if package:
            project_name = get_project_name(
                os.path.abspath(os.path.join(directory, config["package_dir"])), package
            )
        else:
            # Can't determine a project_name, but maybe it is not needed.
            project_name = ""

    if project_date is None:
        project_date = _get_date()

    top_line = config["title_format"].format(
        name=project_name, version=project_version, project_date=project_date
    )
    top_line += u"\n" + (config["underlines"][0] * len(top_line)) + u"\n"

    if draft:
        click.echo(
            "Draft only -- nothing has been written.\n"
            "What is seen below is what would be written.\n",
            err=to_err,
        )
        click.echo("%s\n%s" % (top_line, rendered))
    else:
        click.echo("Writing to newsfile...", err=to_err)
        start_line = config["start_line"]
        append_to_newsfile(
            directory, config["filename"], start_line, top_line, rendered
        )

        click.echo("Staging newsfile...", err=to_err)
        stage_newsfile(directory, config["filename"])

        click.echo("Removing news fragments...", err=to_err)
        remove_files(fragment_filenames, answer_yes)

        click.echo("Done!", err=to_err)
1271649
private void initIndex() throws Exception {

        //0. Add the tasklog template
        if (doesResourceNotExist("/_template/tasklog_template")) {
            logger.info("Creating the index template 'tasklog_template'");
            InputStream stream = ElasticSearchDAOV5.class.getResourceAsStream("/template_tasklog.json");
            byte[] templateSource = IOUtils.toByteArray(stream);

            HttpEntity entity = new NByteArrayEntity(templateSource, ContentType.APPLICATION_JSON);
            try {
                elasticSearchAdminClient.performRequest(HttpMethod.PUT, "/_template/tasklog_template", Collections.emptyMap(), entity);
            } catch (IOException e) {
                logger.error("Failed to initialize tasklog_template", e);
            }
        }
    }
912206
def main(args=None):
    """"""
    if args is None:
        parser = create_parser()
        args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    input_module = input_mapping[args.input_reader]
    output_module = output_mapping[args.output_format]

    templates = []
    # Load templates from external folder if set.
    if args.template_folder:
        templates += read_templates(os.path.abspath(args.template_folder))

    # Load internal templates, if not disabled.
    if not args.exclude_built_in_templates:
        templates += read_templates()
    output = []
    for f in args.input_files:
        res = extract_data(f.name, templates=templates, input_module=input_module)
        if res:
            logger.info(res)
            output.append(res)
            if args.copy:
                filename = args.filename.format(
                    date=res['date'].strftime('%Y-%m-%d'),
                    invoice_number=res['invoice_number'],
                    desc=res['desc'],
                )
                shutil.copyfile(f.name, join(args.copy, filename))
            if args.move:
                filename = args.filename.format(
                    date=res['date'].strftime('%Y-%m-%d'),
                    invoice_number=res['invoice_number'],
                    desc=res['desc'],
                )
                shutil.move(f.name, join(args.move, filename))
        f.close()

    if output_module is not None:
        output_module.write_to_file(output, args.output_name)