Automatically try to discover Flask apps files,
    return them as relative module paths.
960583
def detect_flask_apps():
    

    matches = []
    for root, dirnames, filenames in os.walk(os.getcwd()):
        for filename in fnmatch.filter(filenames, '*.py'):
            full = os.path.join(root, filename)
            if 'site-packages' in full:
                continue

            full = os.path.join(root, filename)

            with io.open(full, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                for line in lines:
                    app = None

                    # Kind of janky..
                    if '= Flask(' in line:
                        app = line.split('= Flask(')[0].strip()
                    if '=Flask(' in line:
                        app = line.split('=Flask(')[0].strip()

                    if not app:
                        continue

                    package_path = full.replace(os.getcwd(), '')
                    package_module = package_path.replace(os.sep, '.').split('.', 1)[1].replace('.py', '')
                    app_module = package_module + '.' + app

                    matches.append(app_module)

    return matches
310587
def find_third_party_modules ():
    """"""
    parent = os.path.dirname(os.path.dirname(__file__))
    third_party = os.path.join(parent, "third_party")
    if os.path.isdir(third_party):
        sys.path.append(os.path.join(third_party, "dnspython"))
558313
def traverse_tree(cls, static_dir):
        """"""
        for root, dirs, files in os.walk(static_dir):
            for filename in files:
                if cls._pattern.match(filename):
                    APPS_INCLUDE_DIRS.append(static_dir)
                    return
612727
def auto_discover():
    
    urls = [
        url(r'^admin/', admin.site.urls),
    ]

    # TODO: we can create python package to have a lot of controllers
    # in separate files
    def get_controllers(module_name):
        """Return list of controllers in a module."""
        module = import_module('app.controllers.{}'.format(module_name))
        controllers = []
        for obj_name in dir(module):
            # we ignore import of Controller and hidden names
            if obj_name.startswith('_') or obj_name == 'Controller':
                continue
            obj = getattr(module, obj_name)
            # include only controllers
            if issubclass(obj, Controller):
                controllers.append(obj)
        return controllers

    def controller_to_path(controller):
        """
        Convert controller's name to a valid path.

        Make url in lower case by replace capital letters to small
        and adding underscore between words.
        """
        words = re.findall('[A-Z][a-z]*', controller.__name__)
        if words[-1] == 'Controller':
            del words[-1]
        # transform words to a url address
        url_path = '_'.join(words).lower()
        # main controller is a root handler
        # TODO: root address inside the file should always come last
        if url_path == 'main':
            url_path = ''
        return url_path

    # load all controllers (excluding main controllers)
    for file_name in listdir('controllers', get_files=True, hide_ignored=True):
        # remove .py extension from file name
        app_name = file_name.split('.', 1)[0]
        # we will include main controller at the end
        if app_name == 'main':
            continue
        # add url for each controller
        for controller in get_controllers(app_name):
            url_path = controller_to_path(controller)
            urls.append(url(
                r'^{}/{}$'.format(app_name, url_path),
                controller.as_view()
            ))

    # add urls for main controllers
    for controller in get_controllers('main'):
        url_path = controller_to_path(controller)
        # map urls to a root path
        urls.append(url(
            r'^{}$'.format(url_path),
            controller.as_view()
        ))

    return urls
198884
def _getModules(self):
        
        modules = {}
        modulesPath = os.path.join("application", "module")
        moduleList = os.listdir(modulesPath)

        for moduleName in moduleList:
            modulePath = os.path.join(modulesPath, moduleName, "module.py")
            if not os.path.isfile(modulePath):
                continue

            # importing module
            moduleSpec = importlib.util.spec_from_file_location(
                moduleName,
                modulePath
            )
            module = importlib.util.module_from_spec(moduleSpec)
            moduleSpec.loader.exec_module(module)

            # initializing module
            moduleInstance = module.Module(self)
            modules[moduleName] = moduleInstance

        return modules
1256297
private static List<File> findPythonScripts(List<File> pythonLibDirectories) {
        List<File> scripts = new ArrayList<>();
        for (File dir : pythonLibDirectories) {
            if (dir.exists()) {
                scripts.addAll(Arrays.asList(dir.listFiles(PYTHON_SCRIPT_FILE_FILTER)));
            }
        }
        return scripts;
    }
980541
def import_apps_submodule(submodule):
    
    found_apps = []
    for appconfig in apps.get_app_configs():
        app = appconfig.name
        if import_module_or_none('{0}.{1}'.format(app, submodule)) is not None:
            found_apps.append(app)

    return found_apps
415199
def autodiscover_modules():
    
    import imp
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        try:
            __import__(app)
            app_path = sys.modules[app].__path__
        except AttributeError:
            continue
        try:
            imp.find_module('permissions', app_path)
        except ImportError:
            continue
        __import__("%s.permissions" % app)
        app_path = sys.modules["%s.permissions" % app]
    LOADING = False
1368481
def flask_paths(self):
        
        paths = {}
        for url_path, handler in self.url_paths.items():
            url_path = convert_regex_to_flask_path(url_path)
            paths[url_path] = handler

        return paths
1257049
def discover_static_files(base_path, sub_path=''):
    
    js_files = discover_files(base_path, sub_path=sub_path,
                              ext='.js', trim_base_path=True)
    sources, mocks, specs = sort_js_files(js_files)
    html_files = discover_files(base_path, sub_path=sub_path,
                                ext='.html', trim_base_path=True)

    p = path.join(base_path, sub_path)
    _log(sources, 'JavaScript source', p)
    _log(mocks, 'JavaScript mock', p)
    _log(specs, 'JavaScript spec', p)
    _log(html_files, 'HTML template', p)

    return sources, mocks, specs, html_files
409229
def get_mod_paths(mod_name, out_dir):
    """"""
    paths = []
    try:
        mod = get_loader(mod_name)
        source = Path(mod.path)
        if source.name.endswith(".py"):
            source_rel = Path(*mod_name.split("."))
            if source.name == "__init__.py":
                source_rel = source_rel.joinpath("__init__.py")
            destination = Path(out_dir, source_rel.with_suffix(".pyi"))
            paths.append((source, destination))
    except Exception as e:
        _logger.debug(e)
        _logger.warning("cannot handle module, skipping: %s", mod_name)
    return paths
356351
def find_commands_module(app_name):
    
    parts = app_name.split('.')
    parts.append('commands')
    parts.reverse()
    part = parts.pop()
    path = None

    #Load the module if needed
    try:
        f, path, descr = imp.find_module(part, path)
    except ImportError as e:
        if os.path.basename(os.getcwd()) != part:
            raise e
        else:
            try:
                if f:
                    f.close()
            except UnboundLocalError:
                log.error("Could not import module {0} at path {1}.  Sys.path is {2}".format(part, path, sys.path))

    #Go down level by and level and try to load the module at each level
    while parts:
        part = parts.pop()
        f, path, descr = imp.find_module(part, [path] if path else None)
        if f:
            f.close()
    return path
718544
def search_app_root():
        
        while True:

            current = os.getcwd()

            if pathlib.Path("apps.py").is_file():
                return current
            elif pathlib.Path.cwd() == "/":
                raise FileNotFoundError
            else:
                os.chdir("../")
572019
def _gather_files(app, hidden, filepath_filter_regex=None):
    
    dirs = [(six.text_type(app.static_folder), app.static_url_path)]
    if hasattr(app, 'blueprints'):
        blueprints = app.blueprints.values()
        bp_details = lambda x: (x.static_folder, _bp_static_url(x))
        dirs.extend([bp_details(x) for x in blueprints if x.static_folder])

    valid_files = defaultdict(list)
    for static_folder, static_url_loc in dirs:
        if not os.path.isdir(static_folder):
            logger.warning("WARNING - [%s does not exist]" % static_folder)
        else:
            logger.debug("Checking static folder: %s" % static_folder)
        for root, _, files in os.walk(static_folder):
            relative_folder = re.sub(r'^/',
                                     '',
                                     root.replace(static_folder, ''))

            files = [os.path.join(root, x)
                     for x in files if (
                         (hidden or x[0] != '.') and
                         # Skip this file if the filter regex is
                         # defined, and this file's path is a
                         # negative match.
                         (filepath_filter_regex == None or re.search(
                             filepath_filter_regex,
                             os.path.join(relative_folder, x))))]
            if files:
                valid_files[(static_folder, static_url_loc)].extend(files)
    return valid_files
72319
function (options, iterationInfo, modules) {
        // filename filter
        if (options.fileNameFilter) {
            var match = iterationInfo.fileName.match(options.fileNameFilter);
            if (!match) {
                return;
            }
        }

        // Filter spec.js files
        var match = iterationInfo.fileName.match(/.spec.js/i);
        if (match) {
            return;
        }

        // relative path filter
        if (options.relativePathFilter) {
            var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
            if (!pathMatch)
                return;
        }

        //load module
        loadModule(modules, options, iterationInfo);
    }
1142326
def get_app_submodules(submodule_name):
    
    for name, module in get_app_modules():
        if module_has_submodule(module, submodule_name):
            yield name, import_module('%s.%s' % (name, submodule_name))
1174496
def _get_app_module_path(module_label):
    
    app_name = module_label.rsplit('.', 1)[0]
    for app in settings.INSTALLED_APPS:
        if app.endswith('.' + app_name) or app == app_name:
            return app
    return None