Context:
        - all_metadata

    Templates:
        - billy/web/public/downloads.html
355050
def downloads(request):
    '''
    
    '''
    all_metadata = sorted(db.metadata.find(), key=lambda x: x['name'])
    return render(request, 'billy/web/public/downloads.html',
                  {'all_metadata': all_metadata})
265408
def construct_context(self, request):
        
        opts = self.model._meta
        app_label = opts.app_label
        object_name = opts.object_name.lower()
        form = self.construct_form(request)

        media = self.media(form)
        context = {
            'user': request.user,
            'title': '%s %s' % (self.label, opts.verbose_name_plural.lower()),
            'tool': self,
            'opts': opts,
            'app_label': app_label,
            'media': media,
            'form': form,
            'changelist_url': reverse('admin:%s_%s_changelist' % (
                app_label, object_name
            ))
        }

        # Pass along fieldset if sepcififed.
        if hasattr(form, 'fieldsets'):
            admin_form = helpers.AdminForm(form, form.fieldsets, {})
            context['adminform'] = admin_form

        return context
1006232
def get_context_template():
    
    import random
    return {
        'SITE_ID': 1,
        'SECRET_KEY': ''.join(
            [random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]),
        'DATA_DIR': os.path.join(os.environ['PRODUCT_DIR'], '__data__'),
    }
404050
def handle_template(self, template, subdir):
        
        if template is None:
            return six.text_type(os.path.join(yacms.__path__[0], subdir))
        return super(Command, self).handle_template(template, subdir)
492828
def index(self):
        
        root_dir = os.path.dirname(__file__)
        template_dir = os.path.join(root_dir, "templates", "gnotty")
        with open(os.path.join(template_dir, "base.html"), "r") as f:
            base = f.read()
        with open(os.path.join(template_dir, "chat.html"), "r") as f:
            base = base.replace("{% block content %}", f.read())
        replace = {
            "{% block content %}": "",
            "{% block extrahead %}": "",
            "{% endblock %}": "",
            "{% load gnotty_tags %}": "",
            "{% extends \"gnotty/base.html\" %}": "",
            "{% url gnotty_chat %}": "/",
            "{% gnotty_nav %}": "",
            "{% templatetag openvariable %}": "{{",
            "{% templatetag closevariable %}": "}}",
        }
        for k, v in replace.items():
            base = base.replace(k, v)
        for k, v in settings.items():
            base = base.replace("{{ %s }}" % k, unicode(v or ""))
        return base
1179200
def context(self):
    ""
    if self._context is None:
      with io.open(path.join(path.abspath(path.dirname(__file__)), "compiler.js")) as compiler_file:
        compiler_source = compiler_file.read()
      self._context = self.backend.compile(compiler_source)
    return self._context
264201
function (f, data, context) {
    try {
        return _.template(data)(context);
    } catch(e) {
        log('error', 'could not parse template file', f);
        throw(e);
    }
}
1060439
def update_context(app, pagename, templatename, context, doctree):
    
    if doctree is None:
        return
    visitor = _FindTabsDirectiveVisitor(doctree)
    doctree.walk(visitor)
    if not visitor.found_tabs_directive:
        paths = [posixpath.join('_static', 'sphinx_tabs/' + f) for f in FILES]
        if 'css_files' in context:
            context['css_files'] = context['css_files'][:]
            for path in paths:
                if path.endswith('.css'):
                    context['css_files'].remove(path)
        if 'script_files' in context:
            context['script_files'] = context['script_files'][:]
            for path in paths:
                if path.endswith('.js'):
                    context['script_files'].remove(path)
844497
function Template (filename, context) {
    // Save the context for reuse in sub-templates
    this.context = context || {}
    this.context.include = this.render.bind(this)
    this.context.forEach = forEach

    // Save the filename for the initial render
    this.filename = filename

    // Create a cache so we only read files once
    this.cache = {}
}
365371
function Template( name, dir){
  this.name = name;
  if( name){
    this.view = this.load( 
      util.format(
        '%s/%s/%s.%s', 
        dir, name, name, 'html'
      )
    );
  }
  return this;
}
944448
function init(app, context, swagger) {
        logger.log('debug', '%s|adding|routes|context=%s', meta.module, context, meta);
        if (swagger) {
            describeModels(swagger);
            swagger.addPost({
                'spec': {
                    "path" : context + format + '/lex/phrase', 
                    "notes" : "To use only the lexer to tokenize a phrase. The output of the lexer can be pass directly to the tokenizer.",
                    "method": "POST",
                    "summary" : "Split a phrase into tokens.",
                    "nickname" : "lexer",
                    "responseClass" : "Tokens",
                    "params" : [
                        swagger.params.post("phrase", "A phrase to be tokenized", '{"phrase":"Hello world"}'),
                    ],
                    "errorResponses" : [
                        swagger.errors.notFound('phrase'),
                        swagger.errors.invalid('phrase')
                    ]
                },
                'action': function(req, res) {
                    if (!req.body)
                        throw swagger.error(400, 'Missing body of the request');
                    if (!req.body.phrase)
                        throw swagger.error(400, 'Missing the "phrase" in the body of the request');
                    pos.rest.lexPhrase(req, res);
                }
            }).addPost({
                'spec': {
                    "path" : context + format + '/tag/words',
                    "notes" : "To use the tagger on a list of tokens.",
                    "method": "POST",
                    "summary" : "Tag each tokenized word.",
                    "nickname" : "word-tagger",
                    "responseClass" : "Tags",
                    "params" : [
                        swagger.params.post("words", "A list of tokenized words to be tagged", '{"words":["hello","world"]}'),
                    ],
                    "errorResponses" : [
                        swagger.errors.notFound('words'),
                        swagger.errors.invalid('words')
                    ]
                },
                'action': function(req, res) {
                    if (!req.body)
                        throw swagger.error(400, 'Missing body of the request');
                    if (!req.body.words)
                        throw swagger.error(400, 'Missing the "words" array in the body of the request');
                    pos.rest.tagWords(req, res);
                }
            }).addPost({
                'spec': {
                    "path" : context + format + '/tag/phrase',
                    "notes" : "Use the lexer on the phrase and, tag the resulting tokens.",
                    "method": "POST",
                    "summary" : "Tokenize a phrase and then tag each token.",
                    "nickname" : "tagger",
                    "responseClass" : "Tags",
                    "params" : [
                        swagger.params.post("phrase", "A phrase to be tokenized and tagged", '{"phrase":"Hello world"}'),
                    ],
                    "errorResponses" : [
                        swagger.errors.notFound('phrase'),
                        swagger.errors.invalid('phrase')
                    ]
                },
                'action': function(req, res) {
                    if (!req.body)
                        throw swagger.error(400, 'Missing body of the request');
                    if (!req.body.phrase)
                        throw swagger.error(400, 'Missing the "phrase" in the body of the request');
                    pos.rest.tagPhrase(req, res);
                }
            });
        } else {
            router.add(app, context + '/pos.json/lex/phrase', 'POST', pos.rest.lexPhrase);
            router.add(app, context + '/pos.json/tag/words',  'POST', pos.rest.tagWords);
            router.add(app, context + '/pos.json/tag/phrase', 'POST', pos.rest.tagPhrase);
        }
    }
423888
def comp(request, slug, directory_slug=None):
    
    context = {}
    path = settings.COMPS_DIR
    comp_dir = os.path.split(path)[1]
    template = "{0}/{1}".format(comp_dir, slug)
    if directory_slug:
        template = "{0}/{1}/{2}".format(comp_dir, directory_slug, slug)
    working_dir = os.path.join(path, slug)
    if os.path.isdir(working_dir):
        return redirect('comp-listing', directory_slug=slug)

    try:
        t = get_template(template)
    except TemplateDoesNotExist:
        return redirect('comp-listing')

    c = RequestContext(request, context)
    return HttpResponse(t.render(c))
487261
def direct_to_template(
        request, template, extra_context=None, mimetype=None, **kwargs):
    
    if extra_context is None:
        extra_context = {}
    dictionary = {'params': kwargs}
    for key, value in extra_context.items():
        if callable(value):
            dictionary[key] = value()
        else:
            dictionary[key] = value
    t = loader.get_template(template)
    return HttpResponse(
        t.render(context=dictionary, request=request),
        content_type=mimetype)
20718
def fix_examples_data
      each_item do |ex|
        ex["name"] = ex["url"] unless ex["name"]

        unless ex["url"] =~ /^https?:\/\//
          ex["url"] = @opts.examples_base_url + ex["url"]
        end
        unless ex["icon"] =~ /^https?:\/\//
          ex["icon"] = @opts.examples_base_url + ex["icon"]
        end

        unless ex["title"]
          ex["title"] = ex["text"]
          ex.delete("text")
        end
        unless ex["description"]
          ex["description"] = ex["desc"]
          ex.delete("desc")
        end
      end
    end
337900
function compile( $compiled_template_filename = '' )
		{
			if (empty($this->template))
			{
				return;
			}
			/* Quick hack to allow subtemplates */
			if(eregi("<!-- INCLUDE", $this->template))
			{
				while ($this->count_subtemplates() > 0)
				{
					preg_match_all('/<!-- INCLUDE ([a-zA-Z0-9_.]+) -->/', $this->template, $tvar);
					foreach($tvar[1] as $subfile)
					{
						if(file_exists($this->template_dir . "/$subfile"))
						{
							$subst = implode('',file($this->template_dir . "/$subfile"));
						}
						else
						{
							$subst = 'SmartTemplate Parser Error: Subtemplate not found: \''.$subfile.'\'';
						}
						$this->template = str_replace("<!-- INCLUDE $subfile -->", $subst, $this->template);
					}
				}
			}
			//	END, ELSE Blocks
			$page  =  preg_replace("/<!-- ENDIF.+?-->/",  "<?php\n}\n?>",  $this->template);
			$page  =  preg_replace("/<!-- END[ a-zA-Z0-9_.]* -->/",  "<?php\n}\n\$_obj=\$_stack[--\$_stack_cnt];}\n?>",  $page);
			$page  =  str_replace("<!-- ELSE -->",  "<?php\n} else {\n?>",  $page);

			//	'BEGIN - END' Blocks
			if (preg_match_all('/<!-- BEGIN ([a-zA-Z0-9_.]+) -->/', $page, $var))
			{
				foreach ($var[1] as $tag)
				{
					list($parent, $block)  =  $this->var_name($tag);
					$code  =  "<?php\n"
							. "if (!empty(\$$parent"."['$block'])){\n"
							. "if (!is_array(\$$parent"."['$block']))\n"
							. "\$$parent"."['$block']=array(array('$block'=>\$$parent"."['$block']));\n"
							. "\$_tmp_arr_keys=array_keys(\$$parent"."['$block']);\n"
							. "if (\$_tmp_arr_keys[0]!='0')\n"
							. "\$$parent"."['$block']=array(0=>\$$parent"."['$block']);\n"
							. "\$_stack[\$_stack_cnt++]=\$_obj;\n"
							. "foreach (\$$parent"."['$block'] as \$rowcnt=>\$$block) {\n"
							. "\$$block"."['ROWCNT']=\$rowcnt;\n"
							. "\$$block"."['ALTROW']=\$rowcnt%2;\n"
							. "\$$block"."['ROWBIT']=\$rowcnt%2;\n"
							. "\$_obj=&\$$block;\n?>";
					$page  =  str_replace("<!-- BEGIN $tag -->",  $code,  $page);
				}
			}

			//	'IF nnn=mmm' Blocks
			if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+)[ ]*([!=<>]+)[ ]*(["]?[^"]*["]?) -->/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					list($parent, $block)  =  $this->var_name($tag);
					$cmp   =  $var[3][$cnt];
					$val   =  $var[4][$cnt];
					$else  =  ($var[1][$cnt] == 'ELSE') ? '} else' : '';
					if ($cmp == '=')
					{
						$cmp  =  '==';
					}
					
					if (preg_match('/"([^"]*)"/',$val,$matches))
					{
						$code  =  "<?php\n$else"."if (\$$parent"."['$block'] $cmp \"".$matches[1]."\"){\n?>";
					}
					elseif (preg_match('/([^"]*)/',$val,$matches))
					{
						list($parent_right, $block_right)  =  $this->var_name($matches[1]);
						$code  =  "<?php\n$else"."if (\$$parent"."['$block'] $cmp \$$parent_right"."['$block_right']){\n?>";
					}
					
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	'IF nnn' Blocks
			if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+) -->/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					$else  =  ($var[1][$cnt] == 'ELSE') ? '} else' : '';
					list($parent, $block)  =  $this->var_name($tag);
					$code  =  "<?php\n$else"."if (!empty(\$$parent"."['$block'])){\n?>";
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	Replace Scalars
			if (preg_match_all('/{([a-zA-Z0-9_. >]+)}/', $page, $var))
			{
				foreach ($var[1] as $fulltag)
				{
					//	Determin Command (echo / $obj[n]=)
					list($cmd, $tag)  =  $this->cmd_name($fulltag);

					list($block, $skalar)  =  $this->var_name($tag);
					$code  =  "<?php\n$cmd \$$block"."['$skalar'];\n?>\n";
					$page  =  str_replace('{'.$fulltag.'}',  $code,  $page);
				}
			}


			//	ROSI Special: Replace Translations
			if (preg_match_all('/<"([a-zA-Z0-9_.]+)">/', $page, $var))
			{
				foreach ($var[1] as $tag)
				{
					list($block, $skalar)  =  $this->var_name($tag);
					$code  =  "<?php\necho gettext('$skalar');\n?>\n";
					$page  =  str_replace('<"'.$tag.'">',  $code,  $page);
				}
			}


			//	Include Extensions
			$header = '';
			if (preg_match_all('/{([a-zA-Z0-9_]+):([^}]*)}/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					//	Determin Command (echo / $obj[n]=)
					list($cmd, $tag)  =  $this->cmd_name($tag);

					$extension  =  $var[1][$cnt];
					if (!isset($this->extension_tagged[$extension]))
					{
						$header  .=  "include_once \"smarttemplate_extensions/smarttemplate_extension_$extension.php\";\n";
						$this->extension_tagged[$extension]  =  true;
					}
					if (!strlen($tag))
					{
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension();\n?>\n";
					}
					elseif (substr($tag, 0, 1) == '"')
					{
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension($tag);\n?>\n";
					}
					elseif (strpos($tag, ','))
					{
						list($tag, $addparam)  =  explode(',', $tag, 2);
						list($block, $skalar)  =  $this->var_name($tag);
						if (preg_match('/^([a-zA-Z_]+)/', $addparam, $match))
						{
							$nexttag   =  $match[1];
							list($nextblock, $nextskalar)  =  $this->var_name($nexttag);
							$addparam  =  substr($addparam, strlen($nexttag));
							$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],\$$nextblock"."['$nextskalar']"."$addparam);\n?>\n";
						}
						else
						{
							$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],$addparam);\n?>\n";
						}
					}
					else
					{
						list($block, $skalar)  =  $this->var_name($tag);
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar']);\n?>\n";
					}
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	Add Include Header
			if (isset($header) && !empty($header))
			{
				$page  =  "<?php\n$header\n?>$page";
			}

			//	Store Code to Temp Dir
			if (strlen($compiled_template_filename))
			{
		        if ($hd  =  fopen($compiled_template_filename,  "w"))
		        {
			        fwrite($hd,  $page);
			        fclose($hd);
			        return true;
			    }
			    else
			    {
			    	$this->error  =  "Could not write compiled file.";
			        return false;
			    }
			}
			else
			{
				return $page;
			}
		}
570926
def render_markdown(post):
        
        from engineer.conf import settings

        # A hack to guarantee the YAML output is in a sensible order.
        # The order, assuming all metadata should be written, should be:
        # title
        # status
        # timestamp
        # link
        # via
        # via-link
        # slug
        # tags
        # updated
        # template
        # content-template
        # url
        d = [
            ('status', post.status.name),
            ('link', post.link),
            ('via', post.via),
            ('via-link', post.via_link),
            ('tags', post.tags),
            ('updated', post.updated_local.strftime(settings.TIME_FORMAT) if post.updated is not None else None),
            ('template', post.template if post.template != 'theme/post_detail.html' else None),
            ('content-template',
             post.content_template if post.content_template != 'theme/_content_default.html' else None),
        ]

        # The complete set of metadata that should be written is the union of the FINALIZE_METADATA.config setting and
        # the set of metadata that was in the file originally.
        finalization_config = FinalizationPlugin.get_settings()['config']
        metadata_to_finalize = set([m for m, s in finalization_config.iteritems() if post.status in s])
        metadata_to_finalize.update(post.metadata_original)

        if 'title' in metadata_to_finalize:
            # insert at the top of the list
            d.insert(0, ('title', post.title))
        if 'slug' in metadata_to_finalize:
            # insert right before tags
            d.insert(d.index(('tags', post.tags)), ('slug', post.slug))
        if 'timestamp' in metadata_to_finalize:
            # insert right after status
            d.insert(d.index(('status', post.status.name)), ('timestamp',
                                                             post.timestamp_local.strftime(settings.TIME_FORMAT)))
        if 'url' in metadata_to_finalize:
            # insert at end of list
            d.append(('url', post.url))

        metadata = ''
        for k, v in d:
            if v is not None and len(v) > 0:
                metadata += yaml.safe_dump(dict([(k, v)]), default_flow_style=False)

        # handle custom metadata
        if len(post.custom_properties):
            metadata += '\n'
            metadata += yaml.safe_dump(dict(post.custom_properties), default_flow_style=False)
        return settings.JINJA_ENV.get_template(post.markdown_template_path).render(metadata=metadata,
                                                                                   content=post.content_finalized,
                                                                                   post=post)
283342
def render(self, template, filename, context={}, filters={}):
        
        filename = os.path.normpath(filename)
        path, file = os.path.split(filename)
        try:
            os.makedirs(path)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise

        path, file = os.path.split(template)
        loader = jinja2.FileSystemLoader(path)
        env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)
        env.filters.update(filters)
        template = env.get_template(file)
        text = template.render(context)
        with open(filename, 'wt') as f:
            f.write(text)