Given a template and a regex match within said template, return a
    dictionary of information about the match to be used to help parse the
    template.
513471
def get_match_info(template, match, state):
    
    info = match.groupdict()

    # Put special delimiter cases in terms of normal ones
    if info['change']:
        info.update({
            'tag_type' : '=',
            'tag_key' : info['delims'],
        })
    elif info['raw']:
        info.update({
            'tag_type' : '&',
            'tag_key' : info['raw_key'],
        })

    # Rename the important match variables for convenience
    tag_start = match.start()
    tag_end = match.end()
    tag_type = info['tag_type']
    tag_key = info['tag_key']
    lead_wsp = info['lead_wsp']
    end_wsp = info['end_wsp']

    begins_line = (tag_start == 0) or (template[tag_start-1] in state.eol_chars)
    ends_line = (tag_end == len(template) or
                 template[tag_end] in state.eol_chars)
    interpolating = (tag_type in ('', '&'))
    standalone = (not interpolating) and begins_line and ends_line

    if end_wsp:
        tag_end -= len(end_wsp)
    if standalone:
        template_length = len(template)
        # Standalone tags strip exactly one occurence of '\r', '\n', or '\r\n'
        # from the end of the line.
        if tag_end < len(template) and template[tag_end] == '\r':
            tag_end += 1
        if tag_end < len(template) and template[tag_end] == '\n':
            tag_end += 1
    elif lead_wsp:
        tag_start += len(lead_wsp)
        lead_wsp = ''

    info.update({
        'tag_start' : tag_start,
        'tag_end' : tag_end,
        'tag_type' : tag_type,
        'tag_key' : tag_key,
        'lead_wsp' : lead_wsp,
        'end_wsp' : end_wsp,
        'begins_line' : begins_line,
        'ends_line' : ends_line,
        'interpolating' : interpolating,
        'standalone' : standalone,
    })
    return info
393266
def get_template(filename_or_string, is_string=False):
    '''
    
    '''

    # Cache against string sha or just the filename
    cache_key = sha1_hash(filename_or_string) if is_string else filename_or_string

    if cache_key in TEMPLATES:
        return TEMPLATES[cache_key]

    if is_string:
        # Set the input string as our template
        template_string = filename_or_string

    else:
        # Load template data into memory
        with open(filename_or_string, 'r') as file_io:
            template_string = file_io.read()

    TEMPLATES[cache_key] = Template(template_string, keep_trailing_newline=True)
    return TEMPLATES[cache_key]
328474
def extract_options_dict(template, options):
    """"""
    for option, val in template.items():
        if options and option in options:
            yield option, options[option]
        else:
            yield option, Default(template[option]['default'](os.environ))
1069551
def format(self, template=None):
        
        pattern = r"(?:<([^<]*?)\$(\w+)([^>]*?)>)"
        s = sub(pattern, self._format_repl, template or self.template)
        s = self._str_fix_whitespace(s)
        return s
751656
function templateFunc(str, data) {

  const func = function(obj) {
    return str.replace(/<%=([^%]*)%>/g, match => {
      //match t("...")
      let s = match.match(/t\s*\(([^)]+)\)/g);
      //replace with translation
      if (s.length) {
        s = obj.t(s[0].match(/"([^"]+)"/g)[0].split('"').join(""));
      }
      //use object[name]
      else {
        s = match.match(/([a-z\-A-Z]+([a-z\-A-Z0-9]?[a-zA-Z0-9]?)?)/g)[0];
        s = obj[s] || s;
      }
      return s;
    });
  };
  // Figure out if we're getting a template, or if we need to
  // load the template - and be sure to cache the result.
  const fn = !/<[a-z][\s\S]*>/i.test(str) ? templates[str] = templates[str] || templateFunc(globals.templates[str]) : func;

  // Provide some basic currying to the user
  return data ? fn(data) : fn;
}
1027684
def expand(template_str, dictionary, **kwargs):
    
    t = Template(template_str, **kwargs)
    return t.expand(dictionary)
674649
def _get_string_match(self, key):
        

        expression = r'(?:\s*)'.join([
            '^',
            'define',
            r'\(',
            '\'{}\''.format(key),
            ',',
            r'\'(.*)\'',
            r'\)',
            ';'
        ])

        pattern = re.compile(expression, re.MULTILINE)
        return pattern.search(self._content)
1280943
def get_templates():
    
    injected = {}
    for name, data in templates.items():
        injected[name] = dict([(k, v % env) for k, v in data.items()])
    return injected
369261
def parse_route(cls, template):
        
        regex = ''
        last_pos = 0

        for match in cls.ROUTES_RE.finditer(template):
            regex += re.escape(template[last_pos:match.start()])
            var_name = match.group(1)
            expr = match.group(2) or '[^/]+'
            expr = '(?P<%s>%s)' % (var_name, expr)
            regex += expr
            last_pos = match.end()

        regex += re.escape(template[last_pos:])
        regex = '^%s$' % regex

        return re.compile(regex)
1095327
def matches_input(self, optimized_str):
        """"""

        if all([keyword in optimized_str for keyword in self['keywords']]):
            logger.debug('Matched template %s', self['template_name'])
            return True
218125
def from_template(cls, template):
        
        regex = r'#{\s*%s\s*}' % cls.ALLOWED_KEY
        keys = re.findall(regex, template)
        if len(keys) == 0:
            raise cls.Bad("Bad keys template: %s. Should be: \"%s\"" % (
                template, "a = #{key1}, b = #{key2.key3} ..."))
        return keys
1189932
def visit_regex(self, node, regex):
        """"""
        tilde, literal, flags, _ = regex
        flags = flags.text.upper()
        pattern = literal.literal  # Pull the string back out of the Literal
                                   # object.
        return Regex(pattern, ignore_case='I' in flags,
                              locale='L' in flags,
                              multiline='M' in flags,
                              dot_all='S' in flags,
                              unicode='U' in flags,
                              verbose='X' in flags,
                              ascii='A' in flags)
387454
def parse_template(input_filename, output_filename=''):
    
    data = load_input()
    with open(input_filename, 'rb') as file:
        template = file.read().decode("utf-8")
    
    # Check if 'input' in data
    if not 'input' in data:
        raise ValueError("Could not find 'input' in data")
    
    # Parse template
    for field in data['input']:
        subs = ["filename", "value"] if isinstance(data['input'][field], dict) and "filename" in data['input'][field] and "value" in data['input'][field] else [""]
        for sub in subs:
            displayed_field = field + (":" if sub else "") + sub
            regex = re.compile("@([^@]*)@" + displayed_field + '@([^@]*)@')
            for prefix, postfix in set(regex.findall(template)):
                if sub == "value":
                    text = open(data['input'][field][sub], 'rb').read().decode('utf-8')
                elif sub:
                    text = data['input'][field][sub]
                else:
                    text = data['input'][field]
                rep = "\n".join([prefix + v + postfix for v in text.splitlines()])
                template = template.replace("@{0}@{1}@{2}@".format(prefix, displayed_field, postfix), rep)
    
    if output_filename == '':
        output_filename=input_filename
    
    # Ensure directory of resulting file exists
    try:
        os.makedirs(os.path.dirname(output_filename))
    except OSError as e:
        pass

    # Write file
    with open(output_filename, 'wb') as file:
        file.write(template.encode("utf-8"))
1175053
def template(self, data=None, settings=None):
        
        if settings is None:
            settings = {}
        ts = _.templateSettings
        _.defaults(ts, self.templateSettings)
        _.extend(settings, ts)

        # settings = {
        #     "interpolate": self.templateSettings.get('interpolate'),
        #     "evaluate": self.templateSettings.get('evaluate'),
        #     "escape": self.templateSettings.get('escape')
        # }

        _.extend(settings, {
            "escaper": r"\\|'|\r|\n|\t|\u2028|\u2029",
            "unescaper": r"\\(\\|'|r|n|t|u2028|u2029)"
        })

        src = self.obj
        #src = re.sub('"', r'\"', src)
        #src = re.sub(r'\\', r"\\", src)
        ns = self.Namespace()
        ns.indent_level = 1

        def unescape(code):
            def unescapes(matchobj):
                a = re.sub("^[\'\"]|[\'\"]$", "", ("%r" % matchobj.group(1)))
                # Python doesn't accept \n as a key
                if a == '\n':
                    a = "bn"
                if a == '\r':
                    a = "br"
                if a == '\t':
                    a = "bt"
                if a == '\u2028':
                    a = 'bu2028'
                if a == '\u2029':
                    a = 'bu2029'
                return self.escapes[a]
            return re.sub(settings.get('unescaper'), unescapes, code)

        def escapes(matchobj):
            a = matchobj.group(0)
            # Python doesn't accept \n as a key
            if a == '\n':
                a = "bn"
            if a == '\r':
                a = "br"
            if a == '\t':
                a = "bt"
            if a == '\u2028':
                a = 'bu2028'
            if a == '\u2029':
                a = 'bu2029'
            return '\\' + self.escapes[a]

        def indent(n=None):
            if n is not None:
                ns.indent_level += n
            return "  " * ns.indent_level

        def interpolate(matchobj):
            if getattr(str, 'decode', False):
                key = (matchobj.group(1).decode('string-escape')).strip()
            else:
                key = (bytes(matchobj.group(1), "utf-8").decode()).strip()
            return "' + str(" + unescape(key) + " or '') + '"

        def evaluate(matchobj):
            if getattr(str, 'decode', False):
                code = (matchobj.group(1).decode('string-escape')).strip()
            else:
                code = (bytes(matchobj.group(1), "utf-8").decode()).strip()
            if code.startswith("end"):
                return "')\n" + indent(-1) + "ns.__p += ('"
            elif code.endswith(':'):
                return "')\n" + indent() + unescape(code) + \
                       "\n" + indent(+1) + "ns.__p += ('"
            else:
                return "')\n" + indent() + unescape(code) + \
                       "\n" + indent() + "ns.__p += ('"

        def escape(matchobj):
            if getattr(str, 'decode', False):
                key = (matchobj.group(1).decode('string-escape')).strip()
            else:
                key = (bytes(matchobj.group(1), "utf-8").decode()).strip()
            return "' + _.escape(str(" + unescape(key) + " or '')) + '"

        source = indent() + 'class closure(object):\n    pass' + \
                            ' # for full closure support\n'
        source += indent() + 'ns = closure()\n'
        source += indent() + "ns.__p = ''\n"
        #src = re.sub("^[\'\"]|[\'\"]$", "", ("%r" % src))
        src = re.sub(settings.get("escaper"), escapes, src)
        source += indent() + "ns.__p += ('" + \
            re.sub(settings.get('escape'), escape, src) + "')\n"
        source = re.sub(settings.get('interpolate'), interpolate, source)
        source = re.sub(settings.get('evaluate'), evaluate, source)

        if getattr(str, 'decode', False):
            source += indent() + 'return ns.__p.decode("string_escape")\n'
        else:
            source += indent() + 'return bytes(ns.__p, "utf-8").decode()\n'

        f = self.create_function(settings.get("variable")
                                 or "obj=None", source)

        if data is not None:
            return f(data)
        return f
211572
def _fetch_templates(src):
    '''
    
    '''
    templates = []
    log.debug('Listing contents of %s', src)
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            template_path = os.path.join(s, TEMPLATE_FILE_NAME)
            if os.path.isfile(template_path):
                templates.append(_get_template(template_path, item))
            else:
                log.debug("Directory does not contain %s %s", template_path,
                          TEMPLATE_FILE_NAME)
    return templates
451544
function template(string, data) {
  var proxyRegEx = /\{\{([^\}]+)?\}\}/g;
  return string.replace(proxyRegEx, function(_, key) {
    var keyParts = key.split('.');
    var value = data;
    for (var i = 0; i < keyParts.length; i++) {
      value = value[keyParts[i]];
    }
    return value || '';
  });
}
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