Finds all Django templates matching given glob in all TEMPLATE_LOADERS

    :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
                        to match

    .. important:: At the moment egg loader is not supported.
434168
def find_all_templates(pattern='*.html', ignore_private=True):
    
    templates = []
    template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)
    for loader_name in template_loaders:
        module, klass = loader_name.rsplit('.', 1)
        if loader_name in (
            'django.template.loaders.app_directories.Loader',
            'django.template.loaders.filesystem.Loader',
        ):
            loader_class = getattr(import_module(module), klass)
            if getattr(loader_class, '_accepts_engine_in_init', False):
                loader = loader_class(Engine.get_default())
            else:
                loader = loader_class()
            for dir in loader.get_template_sources(''):
                for root, dirnames, filenames in os.walk(dir):
                    for basename in filenames:
                        if ignore_private and basename.startswith("_"):
                            continue
                        filename = os.path.join(root, basename)
                        rel_filename = filename[len(dir)+1:]
                        if fnmatch.fnmatch(filename, pattern) or \
                           fnmatch.fnmatch(basename, pattern) or \
                           fnmatch.fnmatch(rel_filename, pattern):
                            templates.append(rel_filename)
        else:
            LOGGER.debug('%s is not supported' % loader_name)
    return sorted(set(templates))
67922
def extract(self, name, example):
        '''  '''

        # if pathlib not available do nothing
        if not pathlib:
            return None

        # ensure example is a string
        if isinstance(example, pathlib.Path):
            example = str(example)
        assert isinstance(example, six.string_types), 'example file must be a string'

        # get the template
        assert name in self.lookup_names(), '{0} must be a valid template name'.format(name)
        template = self.templates[name]

        # expand the environment variable
        template = os.path.expandvars(template)

        # handle special functions; perform a drop in replacement
        if re.match('%spectrodir', template):
            template = re.sub('%spectrodir', os.environ['BOSS_SPECTRO_REDUX'], template)
        elif re.search('%platedir', template):
            template = re.sub('%platedir', '(.*)/{plateid:0>6}', template)
        elif re.search('%definitiondir', template):
            template = re.sub('%definitiondir', '{designid:0>6}', template)
        if re.search('%plateid6', template):
            template = re.sub('%plateid6', '{plateid:0>6}', template)

        # check if template has any brackets
        haskwargs = re.search('[{}]', template)
        if not haskwargs:
            return None

        # escape the envvar $ and any dots
        subtemp = template.replace('$', '\\$').replace('.', '\\.')
        # define search pattern; replace all template keywords with regex "(.*)" group
        research = re.sub('{(.*?)}', '(.*)', subtemp)
        # look for matches in template and example
        pmatch = re.search(research, template)
        tmatch = re.search(research, example)

        path_dict = {}
        # if example match extract keys and values from the match groups
        if tmatch:
            values = tmatch.groups(0)
            keys = pmatch.groups(0)
            assert len(keys) == len(values), 'pattern and template matches must have same length'
            parts = zip(keys, values)
            # parse into dictionary
            for part in parts:
                value = part[1]
                if re.findall('{(.*?)}', part[0]):
                    # get the key name inside the brackets
                    keys = re.findall('{(.*?)}', part[0])
                    # remove the type : designation
                    keys = [k.split(':')[0] for k in keys]
                    # handle double bracket edge cases; remove this when better solution found
                    if len(keys) > 1:
                        if keys[0] == 'dr':
                            # for {dr}{version}
                            drval = re.match('^DR[1-9][0-9]', value).group(0)
                            otherval = value.split(drval)[-1]
                            pdict = {keys[0]: drval, keys[1]: otherval}
                        elif keys[0] in ['rc', 'br', 'filter', 'camrow']:
                            # for {camrow}{camcol}, {filter}{camcol}, {br}{id}, etc
                            pdict = {keys[0]: value[0], keys[1]: value[1:]}
                        else:
                            raise ValueError('This case has not yet been accounted for.')
                        path_dict.update(pdict)
                    else:
                        path_dict[keys[0]] = value
        return path_dict
772369
def find_referenced_templates(template, search_path):
    
    from jinja2 import Environment, meta
    env = Environment()
    ast = env.parse(template.read())
    referenced_templates = list(meta.find_referenced_templates(ast))

    def realpath(tpl):
        for path in search_path:
            t = os.path.realpath(os.path.join(path, tpl))
            if os.path.isfile(t):
                return t
        return None

    return [realpath(t) for t in referenced_templates if t is not None]
1126185
def glob(cls, files=None):
        '''
        
        '''
        files = files or []
        if isinstance(files, str):
            files = os.path.normpath(files)
            matches = lambda path: matches_patterns(path, [files])
            return [path for path in cls.get_static_files() if matches(path)]
        elif isinstance(files, (list, tuple)):
            all_files = cls.get_static_files()
            files = [os.path.normpath(f) for f in files]
            sorted_result = []
            for pattern in files:
                sorted_result.extend([f for f in all_files if matches_patterns(f, [pattern])])
            return sorted_result
47018
def super_glob(pattern):
    ''
    pieces = pattern.split('/')
    if '**' in pieces:
        prefix = '/'.join(pieces[:pieces.index('**')])
        postfix = '/'.join(pieces[pieces.index('**') + 1:])
        roots = [dirname
                 for dirname, dirnames, filenames in os.walk(prefix)]
        patterns = [root + '/' + postfix for root in roots]
    else:
        patterns = ['/'.join(pieces)]
    return chain.from_iterable(glob(pattern) for pattern in patterns)
68563
def collect_blobs(blob_service, container, pattern=None):
    
    if not blob_service:
        raise ValueError('missing parameter blob_service')

    if not container:
        raise ValueError('missing parameter container')

    if not _pattern_has_wildcards(pattern):
        return [pattern] if blob_service.exists(container, pattern) else []

    results = []
    for blob in blob_service.list_blobs(container):
        try:
            blob_name = blob.name.encode(
                'utf-8') if isinstance(blob.name, unicode) else blob.name
        except NameError:
            blob_name = blob.name

        if not pattern or _match_path(blob_name, pattern):
            results.append(blob_name)

    return results
1175150
def get_template(template_id,**kwargs):
    
    try:
        tmpl_i = db.DBSession.query(Template).filter(Template.id==template_id).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one()

        #Load the attributes.
        for tmpltype_i in tmpl_i.templatetypes:
            for typeattr_i in tmpltype_i.typeattrs:
                typeattr_i.attr

        return tmpl_i
    except NoResultFound:
        raise HydraError("Template %s not found"%template_id)
924963
def match_patterns(codedata) :
	

	ret = {}

	for index1, pattern in enumerate(shaman.PatternMatcher.PATTERNS) :
		print('Matching pattern %d "%s"' % (index1+1, pattern))

		matcher = shaman.PatternMatcher(pattern)
		tmp = {}

		for index2, (language, code) in enumerate(codedata) :
			if language not in shaman.SUPPORTING_LANGUAGES :
				continue

			if len(code) <= 20 or len(code) > 100000 :
				continue

			if language not in tmp :
				tmp[language] = []

			ratio = matcher.getratio(code)
			tmp[language].append(ratio)

			print('Matching patterns %d/%d    ' % (index2, len(codedata)), end='\r')


		ret[pattern] = {}
		for language, data in tmp.items() :
			ret[pattern][language] = sum(tmp[language]) / max(len(tmp[language]), 1)

	print('Matching patterns completed          ')
	return ret
114632
public static <T extends Tree> Matcher<T> packageMatches(Pattern pattern) {
    return (tree, state) -> pattern.matcher(getPackageFullName(state)).matches();
  }
1275143
def get_matches(pattern, language, max_count=8):
    
    if str(pattern) == pattern:
        pattern = compile_pattern(pattern)

    results = []

    if not dicts.exists(language):
        print("The language '%s' is not available locally." % language)
        return []

    with open(dicts.filepath(language), 'r') as f:
        for word in f:
            if max_count <= 0:
                break
            w = word.strip()
            if pattern.match(w) and w not in results:
                results.append(w)
                max_count -= 1

    return results
347707
def contains_glob(path_to_directory, pattern, wanted=None):
    """"""
    if not path_to_directory:
        return False
    needed = make_needed(pattern, path_to_directory, wanted)
    for name in _names_in_directory(path_to_directory):
        if needed(name):
            return True
    return False
546573
def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
        """"""
        return sorted(
            [
                Class(fn=fn)
                for fn in rglob(path, f"*{ext or ''}")
                if re.search(pattern, os.path.basename(fn), flags=flags) is not None
                and os.path.basename(fn)[0] != '~'  # omit temp files
            ],
            key=sortkey,
        )
691061
def _find_template(self, template, tree, blocks, with_filename,
                   source, comment):
        
        from uliweb import application
        from uliweb.core.template import _format_code

        def get_rel_filename(filename, path):
            f1 = os.path.splitdrive(filename)[1]
            f2 = os.path.splitdrive(path)[1]
            f = os.path.relpath(f1, f2).replace('\\', '/')
            if f.startswith('..'):
                return filename.replace('\\', '/')
            else:
                return f

        template_file = None

        if not tree:
            application.template_loader.comment = comment
            files = application.template_loader.find_templates(template)
            if files:
                template_file = files[0]

                for x in files:
                    print x

                if source:
                    print
                    print '---------------- source of %s ---------------' % template
                    t = application.template_loader.load(template_file)
                    if t and comment:
                        print _format_code(t.code).rstrip()
                        print
                    else:
                        print t.code
                        print

            else:
                print 'Not Found'
        else:
            application.template_loader.print_tree(template)

        if template_file and blocks:
            application.template_loader.print_blocks(template, with_filename)
342800
def expand_pattern(pattern: str) -> List[str]:
    ''''''
    ofiles = []
    sz = None
    res = glob_wildcards(pattern, [])
    sz = None
    wildcard = [{}]
    for key in res.keys():
        if key not in env.sos_dict:
            raise ValueError(f'Undefined variable {key} in pattern {pattern}')
        if not isinstance(env.sos_dict[key], str) and isinstance(
                env.sos_dict[key], collections.Sequence):
            if sz is None:
                sz = len(env.sos_dict[key])
                wildcard = [copy.deepcopy(wildcard[0]) for x in range(sz)]
            elif sz != len(env.sos_dict[key]):
                raise ValueError(
                    f'Variables in output pattern should have the same length (other={sz}, len({key})={len(env.sos_dict[key])})'
                )
            for idx, value in enumerate(env.sos_dict[key]):
                wildcard[idx][key] = value
        else:
            for v in wildcard:
                v[key] = env.sos_dict[key]
    #
    for card in wildcard:
        ofiles.append(
            apply_wildcards(
                pattern,
                card,
                fill_missing=False,
                fail_dynamic=False,
                dynamic_fill=None,
                keep_dynamic=False))
    return ofiles
955172
def detect_converters(pattern: str,
                      converter_dict: Dict[str, Callable],
                      default: Callable = str):
    
    converters = {}
    for matched in VARS_PT.finditer(pattern):
        matchdict = matched.groupdict()
        varname = matchdict['varname']
        converter = matchdict['converter']
        converters[varname] = converter_dict.get(converter, default)
    return converters
1014901
function template(pattern) {
    return app.src(pattern, { cwd: path.join(__dirname, 'templates') })
      .pipe(app.renderFile('*')).on('error', console.error)
      .pipe(app.conflicts(app.cwd))
      .pipe(app.dest(app.options.dest || app.cwd));
  }
1325644
function (pattern, options) {
    var self = this;
    function find() {
      var isMatch = lazy.mm.matcher(pattern, options);
      for (var key in self) {
        var val = self[key];
        if (typeof val === 'object' && isMatch(key)) {
          return val;
        }
      }
    }
    var res = this.fragmentCache(pattern, find);
    res.__proto__ = this;
    return res;
  }