mini-scanner to handle highlighting module names in import lines
350558
private function importLine()
    {
        $import = false;
        $from = false;
        while (!$this->eol()) {
            $c = $this->peek();
            $tok = null;
            $m = null;

            if ($c === '\\') {
                $m = $this->get(2);
            } elseif ($this->scan('/[,\\.;\\*]+/')) {
                $tok = 'OPERATOR';
            } elseif ($this->scan("/[ \t]+/")) {
            } elseif (($m = $this->scan('/import\\b|from\\b/'))) {
                if ($m === 'import') {
                    $import = true;
                } elseif ($m === 'from') {
                    $from = true;
                } else {
                    assert(0);
                }
                $tok = 'IDENT';
            } elseif ($this->scan('/[_a-zA-Z]\w*/')) {
                assert($from || $import);
                if ($import) {
                    // from module import *item*, or just import *item*
                    $tok = 'USER_FUNCTION';
                    $this->userDefs[$this->match()] = 'TYPE';
                } else {
                    // from *module* ...[import item], the module is not imported
                    $tok = 'IDENT';
                }
            } else {
                break;
            }
            $this->record(($m !== null) ? $m : $this->match(), $tok);
        }
    }
595438
function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
                // Todo: add support for ModuleResolutionHost too
                if (!host.directoryExists(nodeModulesPath)) {
                    return;
                }
                var typingNames = [];
                var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
                for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
                    var fileName = fileNames_2[_i];
                    var normalizedFileName = ts.normalizePath(fileName);
                    if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
                        continue;
                    }
                    var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
                    if (!result.config) {
                        continue;
                    }
                    var packageJson = result.config;
                    // npm 3's package.json contains a "_requiredBy" field
                    // we should include all the top level module names for npm 2, and only module names whose
                    // "_requiredBy" field starts with "#" or equals "/" for npm 3.
                    if (packageJson._requiredBy &&
                        ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
                        continue;
                    }
                    // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
                    // to download d.ts files from DefinitelyTyped
                    if (!packageJson.name) {
                        continue;
                    }
                    if (packageJson.typings) {
                        var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
                        inferredTypings[packageJson.name] = absolutePath;
                    }
                    else {
                        typingNames.push(packageJson.name);
                    }
                }
                mergeTypings(typingNames);
            }
193651
def get_imported_modules(self, module):
    """"""
    for name, member in inspect.getmembers(module):
      if inspect.ismodule(member):
        yield name, member
796509
private String checkinScriptCommand() {

        String exportModules = "";
        if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {
            StringBuffer exportModulesParam = new StringBuffer();
            for (String moduleName : m_modulesToExport) {
                exportModulesParam.append(" ").append(moduleName);
            }
            exportModulesParam.replace(0, 1, " \"");
            exportModulesParam.append("\" ");
            exportModules = " --modules " + exportModulesParam.toString();

        }
        String commitMessage = "";
        if (m_commitMessage != null) {
            commitMessage = " -msg \"" + m_commitMessage.replace("\"", "\\\"") + "\"";
        }
        String gitUserName = "";
        if (m_gitUserName != null) {
            if (m_gitUserName.trim().isEmpty()) {
                gitUserName = " --ignore-default-git-user-name";
            } else {
                gitUserName = " --git-user-name \"" + m_gitUserName + "\"";
            }
        }
        String gitUserEmail = "";
        if (m_gitUserEmail != null) {
            if (m_gitUserEmail.trim().isEmpty()) {
                gitUserEmail = " --ignore-default-git-user-email";
            } else {
                gitUserEmail = " --git-user-email \"" + m_gitUserEmail + "\"";
            }
        }
        String autoPullBefore = "";
        if (m_autoPullBefore != null) {
            autoPullBefore = m_autoPullBefore.booleanValue() ? " --pull-before " : " --no-pull-before";
        }
        String autoPullAfter = "";
        if (m_autoPullAfter != null) {
            autoPullAfter = m_autoPullAfter.booleanValue() ? " --pull-after " : " --no-pull-after";
        }
        String autoPush = "";
        if (m_autoPush != null) {
            autoPush = m_autoPush.booleanValue() ? " --push " : " --no-push";
        }
        String exportFolder = " --export-folder \"" + m_currentConfiguration.getModuleExportPath() + "\"";
        String exportMode = " --export-mode " + m_currentConfiguration.getExportMode();
        String excludeLibs = "";
        if (m_excludeLibs != null) {
            excludeLibs = m_excludeLibs.booleanValue() ? " --exclude-libs" : " --no-exclude-libs";
        }
        String commitMode = "";
        if (m_commitMode != null) {
            commitMode = m_commitMode.booleanValue() ? " --commit" : " --no-commit";
        }
        String ignoreUncleanMode = "";
        if (m_ignoreUnclean != null) {
            ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? " --ignore-unclean" : " --no-ignore-unclean";
        }
        String copyAndUnzip = "";
        if (m_copyAndUnzip != null) {
            copyAndUnzip = m_copyAndUnzip.booleanValue() ? " --copy-and-unzip" : " --no-copy-and-unzip";
        }

        String configFilePath = m_currentConfiguration.getFilePath();

        return "\""
            + DEFAULT_SCRIPT_FILE
            + "\""
            + exportModules
            + commitMessage
            + gitUserName
            + gitUserEmail
            + autoPullBefore
            + autoPullAfter
            + autoPush
            + exportFolder
            + exportMode
            + excludeLibs
            + commitMode
            + ignoreUncleanMode
            + copyAndUnzip
            + " \""
            + configFilePath
            + "\"";
    }
1318134
def import_name(stref: str):
    
    h = stref
    p = []
    m = None
    try:
        r = importlib.util.find_spec(stref)
    except (AttributeError, ImportError):
        r = None

    if r is not None:
        return importlib.import_module(stref)

    while '.' in h:
        h, t = h.rsplit('.', 1)
        p.append(t)
        if h in sys.modules:
            m = sys.modules[h]
            break

    if m is None:
        m = importlib.import_module(h)

    for i in reversed(p):
        if hasattr(m, i):
            m = getattr(m, i)
        else:
            h += '.' + i
            m = importlib.import_module(h)

    logger.debug('Imported "%s" as %r', stref, m)
    return m
277757
def parse_project_imports(dpath):
    
    import ubelt as ub
    import glob
    from os.path import join, exists
    package_modules = set()
    for fpath in glob.glob(join(dpath, '**/*.py'), recursive=True):
        try:
            sourcecode = ub.readfrom(fpath)
            _, modules = ut.parse_import_names(sourcecode, False, fpath=fpath)
            for mod in modules:
                package_modules.add(mod.split('.')[0])  # just bases
            if 'clab/live' in package_modules:
                raise ValueError()
                break
        except SyntaxError:
            print('encountered SyntaxError in fpath = {!r}'.format(fpath))
    import warnings
    import inspect
    stdlibs = [dirname(warnings.__file__), dirname(inspect.__file__)]
    def is_module_batteries_included(m):
        if m in sys.builtin_module_names:
            return True
        for p in stdlibs:
            if exists(join(p, m + '.py')):
                return True
            if exists(join(p, m)):
                return True
    used_modules = sorted([m for m in package_modules if not is_module_batteries_included(m)])
    print('used_modules non-buildin modules = {}'.format(ub.repr2(used_modules)))
191361
def visit_importfrom(self, node):
        ''''''
        module_filename = node.root().file
        if fnmatch.fnmatch(module_filename, '__init__.py*') and \
                not fnmatch.fnmatch(module_filename, 'test_*.py*'):
            return
        basename = node.modname
        self._check_blacklisted_module(node, basename)
406194
def get_module_names(p):
    '''
    '''
    mods = list()
    mods = [f.split('.')[0] for f in listdir(p)
            if isfile(join(p, f)) and not f.endswith('.pyc') and not f.startswith('__')]
    print len(mods)
    return mods
999995
def _module_name(self) -> str:
        """"""
        name = self.f.__module__
        if name == '__main__':
            return importer.main_module_name()
        return name
892600
def highlight(code, lexer='html', formatter='html', output_wrapper=None):
    """"""
    if not pygments:
        raise TypeError("pygments module required")
    if not isinstance(code, six.string_types):
        code = pprint.pformat(code)
    if isinstance(lexer, six.string_types):
        lexer = pygments.lexers.get_lexer_by_name(lexer)
    if isinstance(formatter, six.string_types):
        formatter = pygments.formatters.get_formatter_by_name(formatter)
        if formatter.name.lower() == 'html':
            formatter.full = True
            formatter.cssclass = "pygments-%s" % uuid.uuid4()
            if output_wrapper is None:
                output_wrapper = HTML
    return output_wrapper(pygments.highlight(code, lexer, formatter))
640129
def _import_all_modules():
    """"""
    import traceback
    import os
    global results
    globals_, locals_ = globals(), locals()

    def load_module(modulename, package_module):
        try:
            names = []
            module = __import__(package_module, globals_, locals_, [modulename])

            for name in module.__dict__:
                if not name.startswith('_'):
                    globals_[name] = module.__dict__[name]
                    names.append(name)
        except Exception:
            traceback.print_exc()
            raise

        return module, names

    def load_dir(abs_dirpath, rel_dirpath=''):
        results = []

        # dynamically import all the package modules
        for filename in os.listdir(abs_dirpath):
            rel_filepath = os.path.join(rel_dirpath, filename)
            abs_filepath = os.path.join(abs_dirpath, filename)

            if filename[0] != '_' and os.path.isfile(abs_filepath) and filename.split('.')[-1] in ('py', 'pyw'):
                modulename = '.'.join(os.path.normpath(os.path.splitext(rel_filepath)[0]).split(os.sep))
                package_module = '.'.join([__name__, modulename])

                module, names = load_module(modulename, package_module)
                results += names
            elif os.path.isdir(abs_filepath):
                results += load_dir(abs_filepath, rel_filepath)

        return results

    return load_dir(os.path.dirname(__file__))
530004
function isImported(source, classifiedName, importPath) {
    const allNodes = getSourceNodes(source);
    const matchingNodes = allNodes
        .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration)
        .filter((imp) => imp.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral)
        .filter((imp) => {
        return imp.moduleSpecifier.text === importPath;
    })
        .filter((imp) => {
        if (!imp.importClause) {
            return false;
        }
        const nodes = findNodes(imp.importClause, ts.SyntaxKind.ImportSpecifier).filter(n => n.getText() === classifiedName);
        return nodes.length > 0;
    });
    return matchingNodes.length > 0;
}
291483
private void parseImport() {
        tokenizer.consumeExpectedKeyword(KEYWORD_IMPORT);
        if (!tokenizer.current().isString()) {
            tokenizer.addError(tokenizer.current(),
                               "Unexpected token: '"
                               + tokenizer.current().getSource()
                               + "'. Expected a string constant naming an import file.");
        } else {
            result.addImport(tokenizer.consume().getContents());
        }
        tokenizer.consumeExpectedSymbol(";");
    }
793858
def visit_Import(self, node):
        """"""
        line = self._code_lines[node.lineno - 1]
        module_name = line.split("import")[0].strip()
        for name in node.names:
            imported_name = name.name
            if name.asname:
                imported_name = name.asname + "::" + imported_name
            self.imported_namespaces[imported_name] = module_name
718845
def _check_import(module_names):
    """"""
    diagnostics = {}
    for module_name in module_names:
        try:
            __import__(module_name)
            res = 'ok'
        except ImportError as err:
            res = str(err)
        diagnostics[module_name] = res
    return diagnostics
415652
def resolve_name(name):
    

    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]

    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''

    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)

    return ret
187670
def comment_import(r, unused_dot_list):
    """"""
    unused_dot_str = ".".join(unused_dot_list)
    for n in r("ImportNode"):
        if n.names()[0] == unused_dot_str:
            # The "!" is inserted so that this line doesn't show up when searching for
            # the comment pattern in code.
            n.replace("#{}# {}".format("!", str(n)))
            break