generate a constants file from its template
507337
def generate_file(fname, ns_func, dest_dir="."):
    """"""
    with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f:
        tpl = f.read()
    out = tpl.format(**ns_func())
    dest = pjoin(dest_dir, fname)
    info("generating %s from template" % dest)
    with open(dest, 'w') as f:
        f.write(out)
1174513
function compileTemplate(file, replacements, templateFileLog) {
	file = File.find(path.resolve(file));
	let content = file.read();
	let tags = content.match(new RegExp(tplTagRegExpStr, 'g'));
	if (tags && tags.length) {
		content = getCompiledContent(
			file,
			content.split(new RegExp(tplTagRegExpStr)),
			tags,
			replacements,
			templateFileLog
		);
		file.write(content);
	}
}
705586
def _render_config(cls, dest, template_name, template_args):
        
        template_args = template_args.copy()

        # Substitute values here
        pyversion = template_args['pyversion']
        template_args['pyversion'] = cls.PYVERSIONS[pyversion]

        template = template_env.get_template(template_name)
        contents = template.render(**template_args)
        _write_file(dest, contents)
1025719
def create_template(properties)
      template_dir_path = Pathname.new(File.dirname(__FILE__)).join(NEW_TEMPLATE_FOLDER)
      rambaspec_template_file_path = template_dir_path.join(RAMBASPEC_TEMPLATE_NAME)
      code_file_path = template_dir_path.join(CODE_FOLDER)
      tests_file_path = template_dir_path.join(TESTS_FOLDER)

      file_source = IO.read(rambaspec_template_file_path)

      template = Liquid::Template.parse(file_source)
      output = template.render(properties)

      result_name = properties[TEMPLATE_NAME_KEY] + RAMBASPEC_EXTENSION
      result_dir_path = Pathname.new(properties[TEMPLATE_NAME_KEY])

      FileUtils.mkdir_p result_dir_path
      FileUtils.cp_r(code_file_path, result_dir_path)
      FileUtils.cp_r(tests_file_path, result_dir_path)

      File.open(result_dir_path.join(result_name), 'w+') {|f|
        f.write(output)
      }
    end
1355591
protected File generateTemplate(File template, Instance instance) throws IOException {

		String scriptName = instance.getName().replace( "\\s+", "_" );
		File generated = File.createTempFile( scriptName, ".script");
		InstanceTemplateHelper.injectInstanceImports(instance, template, generated);

		return generated;
	}
300651
def _in_conf_dir(filename):
    
    return os.path.join(
        os.path.dirname(__file__),
        "templates/conf",
        filename
    )
1262611
function generate(template, index) {

  var data,
      parser = parsers.getParser(template);

  if(typeof parser === 'function') {
    data = parser.call(this, template, index);
  } else {
    data = template;
  }
  return data;
}
87452
def generate_template(template_name, **context):
    """"""
    context.update(href=href, format_datetime=format_datetime)
    return template_loader.load(template_name).generate(**context)
87195
def compiled(template, delimiters=DEFAULT_DELIMITERS):
    
    re_tag = delimiters_to_re(delimiters)

    # variable to save states
    tokens = []
    index = 0
    sections = []
    tokens_stack = []

    # root token
    root = Root('root')
    root.filters = copy.copy(filters)

    m = re_tag.search(template, index)
    while m is not None:
        token = None
        last_literal = None
        strip_space = False

        if m.start() > index:
            last_literal = Literal('str', template[index:m.start()], root=root)
            tokens.append(last_literal)

        # parse token
        prefix, name, suffix = m.groups()

        if prefix == '=' and suffix == '=':
            # {{=| |=}} to change delimiters
            delimiters = re.split(r'\s+', name)
            if len(delimiters) != 2:
                raise SyntaxError('Invalid new delimiter definition: ' + m.group())
            re_tag = delimiters_to_re(delimiters)
            strip_space = True

        elif prefix == '{' and suffix == '}':
            # {{{ variable }}}
            token = Variable(name, name, root=root)

        elif prefix == '' and suffix == '':
            # {{ name }}
            token = Variable(name, name, root=root)
            token.escape = True

        elif suffix != '' and suffix != None:
            raise SyntaxError('Invalid token: ' + m.group())

        elif prefix == '&':
            # {{& escaped variable }}
            token = Variable(name, name, root=root)

        elif prefix == '!':
            # {{! comment }}
            token = Comment(name, root=root)
            if len(sections) <= 0:
                # considered as standalone only outside sections
                strip_space = True

        elif prefix == '>':
            # {{> partial}}
            token = Partial(name, name, root=root)
            strip_space = True

            pos = is_standalone(template, m.start(), m.end())
            if pos:
                token.indent = len(template[pos[0]:m.start()])

        elif prefix == '#' or prefix == '^':
            # {{# section }} or # {{^ inverted }}

            # strip filter
            sec_name = name.split('|')[0].strip()
            token = Section(sec_name, name, root=root) if prefix == '#' else Inverted(name, name, root=root)
            token.delimiter = delimiters
            tokens.append(token)

            # save the tokens onto stack
            token = None
            tokens_stack.append(tokens)
            tokens = []

            sections.append((sec_name, prefix, m.end()))
            strip_space = True

        elif prefix == '/':
            tag_name, sec_type, text_end = sections.pop()
            if tag_name != name:
                raise SyntaxError("unclosed tag: '" + tag_name + "' Got:" + m.group())

            children = tokens
            tokens = tokens_stack.pop()

            tokens[-1].text = template[text_end:m.start()]
            tokens[-1].children = children
            strip_space = True

        else:
            raise SyntaxError('Unknown tag: ' + m.group())

        if token is not None:
            tokens.append(token)

        index = m.end()
        if strip_space:
            pos = is_standalone(template, m.start(), m.end())
            if pos:
                index = pos[1]
                if last_literal: last_literal.value = last_literal.value.rstrip(spaces_not_newline)

        m = re_tag.search(template, index)

    tokens.append(Literal('str', template[index:]))
    root.children = tokens
    return root
1061229
function generate(file, template, context, minifyResult) {
  let string = template.render(context, {
    'styles.css': templates.styles,
    'embed.js': templates.embedJs
  });
  if (minifyResult) {
    string = minify(string, {
      caseSensitive: true,
      collapseWhitespace: true,
      html5: true,
      minifyCSS: true,
      minifyJS: true,
      removeComments: true,
      removeAttributeQuotes: true
    });
  };
  writeFile(path.join(context.config.destRoot, file), string);
}
311014
def __copy_static(self, template, output_path):
        """"""
        
        self.path_static = os.path.join(template, "static", "css")
        for file in os.listdir(self.path_static):
            print(file)
            shutil.copyfile(os.path.join(template, "static", "css", file), 
                            os.path.join(output_path, "output", self.name, "site", "static", "css", file))
            
        self.path_static = os.path.join(template, "static", "js")
        for file in os.listdir(self.path_static):
            print(file)
            shutil.copyfile(os.path.join(template, "static", "js", file), 
                            os.path.join(output_path, "output", self.name, "site", "static", "js", file))
428436
function generateCode(taskOptions) {
  try {
    // Perform initialization tasks
    const model = taskOptions.swagger;
    debug('Processing configuration');
    const config = defaults(taskOptions, configDefaults);
    debug('  Initializing template engine');
    const templateEngine = taskOptions.templateEngine(taskOptions);
    debug('  Mapping definitions from file');
    const definitionMap = taskOptions.definitionMapper(model);

    // Execute definition templates
    /* istanbul ignore else - Trivial case */
    if (config.perDefinition) {
      debug('  Executing per-definition templates:');
      for (const templateFile of Object.keys(config.perDefinition)) {
        debug('    Iterating template: %s', templateFile);
        const options = defaults(config.perDefinition[templateFile], {
          extension: '.js',
          operations: ['get', 'put', 'post', 'delete'],
        });
        const template = taskOptions.templateLoader(templateEngine)
          .loadTemplate(templateFile, taskOptions.textEncoding);
        for (const definitionKey of Object.keys(definitionMap)) {
          const definition = definitionMap[definitionKey];

          debug('      Processing definition %s', definitionKey);
          // Copy fields from options into definition for
          const context = {
            model,
            definition,
            definitionMap,
            options,
          };

          debug('      Rendering template');
          const output = template(context);
          const subPath = path.join(options.target,
            definition.definitionName.toLowerCase() +
            options.extension);
          taskOptions.output(subPath, output);
        }
      }
    } else {
      debug('    No per-definition templates specified in perDefinition');
    }

    // Execute path templates
    if (config.perPath) {
      debug('  Executing per-path templates:');
      for (const templateFile of Object.keys(config.perPath)) {
        debug('    Processing template: %s', templateFile);
        const options = defaults(config.perPath[templateFile], {
          extension: '.js',
          operations: ['get', 'put', 'post', 'delete'],
        });
        const template = taskOptions.templateLoader(templateEngine)
          .loadTemplate(templateFile, taskOptions.textEncoding);
        debug('    Iterating paths, grouping operations by %s', options.groupBy);

        const groups = {};

        for (const pathString of Object.keys(model.paths)) {
          debug('      Path: %s', pathString);
          const pathDef = model.paths[pathString];
          let groupKey = pathDef[options.groupBy];
          pathDef.pathString = pathString;

          // Iterate through the allowed operations
          for (const operationString of _.intersection(Object.keys(pathDef), options.operations)) {
            debug('        Operation: %s', operationString);
            const operationDef = model.paths[pathString][operationString];
            groupKey = operationDef[options.groupBy] || groupKey;
            operationDef.pathDef = pathDef;
            operationDef.operationString = operationString;

            // We need a grouping key at either operation or path level
            /* istanbul ignore if */
            if (groupKey === null || groupKey === undefined) {
              throw new Error(util.format(
                'Cannot map path operation. No groupBy match at path/operation level: %s/%s [%s]',
                pathString,
                operationString,
                options.groupBy));
            }
            debug('          Assigned to output group: %s', groupKey);

            // If the group does not exist, create it
            if (groups[groupKey] === undefined) {
              groups[groupKey] = [];
            }

            // Add to group
            groups[groupKey].push(operationDef);
          } // per operationString
        } // per pathString

        debug('    Rendering template for %s group(s)', Object.keys(groups).length);
        for (const groupKey of Object.keys(groups)) {
          debug('      Processing group: %s', groupKey);

          const context = {};
          context.fileName = groupKey.trim().toLowerCase();
          context.groupKey = groupKey;
          context.members = groups[groupKey];
          context.definitionMap = definitionMap;
          context.model = model;
          context.options = options;

          const output = template(context);
          const subPath = path.join(options.target,
            context.fileName + options.extension);
          taskOptions.output(subPath, output);
        }
      } // per templateFile
    } // if perPath
  } catch (err) {
    /* istanbul ignore next - We don't wan't to test process.exit */
    taskOptions.failureHandler(err);
  }
}
411214
def format_template_file(filename, content):
    """"""

    with open(filename, 'r') as f:
        template = f.read()
        if type(template) != str:
            template = template.decode('utf-8')

    return format_template(template, content)
36893
def templates_in(path):
    """"""
    ext = '.cpp'
    return (
        Template(f[0:-len(ext)], load_file(os.path.join(path, f)))
        for f in os.listdir(path) if f.endswith(ext)
    )
842852
function createFiles (files, argv, templates, cb) {
  if (!templates) {
    const parent = path.resolve(module.parent.filename)
    templates = path.join(parent, '../templates')
  }

  const dir = argv.directory
  parallel(files.map(mapFn), cb)

  function mapFn (file) {
    const tempDir = path.resolve(templates)
    const inFile = path.join(tempDir, file.replace(/^\./, '_.'))
    const outFile = path.resolve(path.join(dir, file))

    return function (done) {
      fs.createReadStream(inFile)
        .pipe(through(transform))
        .pipe(fs.createWriteStream(outFile))
        .on('error', done)
        .on('finish', function () {
          process.stdout.write('write: ' + outFile + '\n')
          done()
        })

      function transform (chunk, enc, cb) {
        const str = chunk.toString()
        const mt = mustache.render(str, argv)
        cb(null, mt)
      }
    }
  }
}
1224158
def compile(self, source, path=None):
        

        container = self._generate_code(source)

        def make_module_name(name, suffix=None):
            output = 'pybars._templates.%s' % name
            if suffix:
                output += '_%s' % suffix
            return output

        if not path:
            path = '_template'
            generate_name = True
        else:
            path = path.replace('\\', '/')
            path = path.replace('/', '_')
            mod_name = make_module_name(path)
            generate_name = mod_name in sys.modules

        if generate_name:
            mod_name = make_module_name(path, self.template_counter)
            while mod_name in sys.modules:
                self.template_counter += 1
                mod_name = make_module_name(path, self.template_counter)

        mod = ModuleType(mod_name)
        filename = '%s.py' % mod_name.replace('pybars.', '').replace('.', '/')
        exec(compile(container.full_code, filename, 'exec', dont_inherit=True), mod.__dict__)
        sys.modules[mod_name] = mod
        linecache.getlines(filename, mod.__dict__)

        return mod.__dict__[container.name]
375156
def constantize(str)
      str = str.to_s
      call_or_yield str do
        raise(NameError, "#{s.inspect} is not a valid constant name!") unless m = VALID_CONSTANT_NAME_REGEXP.match(str)
        Object.module_eval("::#{m[1]}", __FILE__, __LINE__)
      end
    end